feat: Sabre resolve and guided upsample shader optimizations

This commit is contained in:
zhoubinjia committed 2026-11-03 16:02:45 +08:00
1 parent 78297ea307
commit 36e5622cfd
7 files changed
+367 -1060

No files matched your search

@@ -674,64 +674,4 @@ internal object GlesMgcRawSabreShaders {
oColor = vec4(vec3(1.0) / max(weights, vec3(1.0e-7)), targetAlpha);
}
""".trimIndent()
private val outputTransformBody = """
precision highp float;
precision highp sampler2D;
precision highp int;
precision highp usampler2D;
uniform highp usampler2D uResolvedR;
uniform highp usampler2D uResolvedG;
uniform highp usampler2D uResolvedB;
uniform sampler2D uLensShading;
uniform ivec2 uOutputSize;
uniform int uUseLensShading;
uniform vec3 uFinalBlackLevel;
uniform float uDemosaicWhiteLevel;
uniform float uOutputExposureScale;
vec3 transformOutput(ivec2 p) {
uvec3 encoded = uvec3(
texelFetch(uResolvedR, p, 0).r,
texelFetch(uResolvedG, p, 0).r,
texelFetch(uResolvedB, p, 0).r
);
// ResolveSabre emits camera RGB in its RAW14 domain and deliberately retains the
// per-channel final black level. Convert that native result to the black-free,
// normalized camera domain expected by Photon's linear-RGB pipeline.
vec3 resolved = max(vec3(encoded) - uFinalBlackLevel, vec3(0.0)) /
max(vec3(uDemosaicWhiteLevel) - uFinalBlackLevel, vec3(1.0));
if (uUseLensShading != 0) {
vec2 uv = (vec2(p) + vec2(0.5)) / vec2(uOutputSize);
vec4 shading = texture(uLensShading, uv);
resolved *= vec3(shading.r, 0.5 * (shading.g + shading.b), shading.a);
}
return max(
resolved * uOutputExposureScale,
vec3(0.0)
);
}
""".trimIndent()
val outputTransformUint16 = """
#version 300 es
${outputTransformBody.prependIndent(" ")}
layout(location = 0) out highp uvec4 oResolved;
void main() {
ivec2 p = ivec2(gl_FragCoord.xy);
vec3 resolved = clamp(transformOutput(p), 0.0, 1.0);
oResolved = uvec4(uvec3(round(resolved * 65535.0)), 65535u);
}
""".trimIndent()
val outputTransformFloat = """
#version 300 es
${outputTransformBody.prependIndent(" ")}
layout(location = 0) out vec4 oResolved;
void main() {
ivec2 p = ivec2(gl_FragCoord.xy);
oResolved = vec4(transformOutput(p), 1.0);
}
""".trimIndent()
}
@@ -524,7 +524,6 @@ internal class GlesMgcRawSpatialStacker(
/** §2.2 merge variance accumulator of the merge in flight; released with the merge. */
private var mergeNoise: PhotonMergeNoise? = null
private var sabreOutputTransformProgram = 0
private var currentMergeCovariance = 0
private var mergeRgbProgram = 0
private var normalizeBayerProgram = 0
@@ -2174,8 +2173,6 @@ internal class GlesMgcRawSpatialStacker(
// The reference merges without a frame weight texture (useFrameWeight = false).
add(1f, referenceCalibration.cameraRgbReadNoise, referenceCalibration.cameraRgbShotNoise, 0)
}
val sabreResolveFinalBlackLevel =
sabreResolveBlackLevel(referenceCalibration.blackLevels)
PLog.i(
SABRE_TAG,
"MGC Sabre NoiseModel meanSignal=${kernelTuning.referenceSignal} " +
@@ -2361,18 +2358,25 @@ internal class GlesMgcRawSpatialStacker(
PLog.i(
SABRE_TAG,
"MGC Sabre Resolve domain=mgc14 rawScale=$sabreResolveRawScale " +
"black=${sabreResolveFinalBlackLevel.contentToString()} " +
"gains=${sabreResolveFinalGains.contentToString()} " +
"demosaicWhite=$demosaicWhiteLevel " +
"greenImbalanceRetention=" +
"${sabreResolveParameters.greenImbalanceRetention} " +
"demosaicSharpness=${sabreResolveParameters.demosaicSharpness}",
)
val lensShadingTexture = createLensShadingTexture()
val fullOutput = MgcSpatialRgbRect(0, 0, width, height)
val fullOutputTile = MgcSpatialRgbTile(index = 0, outputCore = fullOutput)
val chromaPostprocessor = checkNotNull(rgbChromaPostprocessor) {
"MGC Sabre VGN color noise/IIR postprocessor is not initialized"
}
chromaPostprocessor.initStorage(listOf(fullOutputTile))
val resolvedRgb = chromaPostprocessor.normalizationTargetTexture()
val resolveStartNs = System.nanoTime()
val resolvedPlanes = renderSabreResolve(
renderSabreResolve(
accumulatedColor = accumulatedColor,
finalBlackLevel = sabreResolveFinalBlackLevel,
demosaicWhiteLevel = demosaicWhiteLevel,
lensShadingTexture = lensShadingTexture,
output = resolvedRgb,
greenImbalanceRetention = sabreResolveParameters.greenImbalanceRetention,
demosaicBlendScale = -demosaicBlendRange * frames.size,
demosaicBlendBias = SABRE_DEMOSAIC_BLEND_END / demosaicBlendRange,
@@ -2383,22 +2387,8 @@ internal class GlesMgcRawSpatialStacker(
SABRE_TAG,
"MGC Sabre Resolve GPU submit=${elapsedMs(resolveStartNs)}ms",
)
releaseSabreMergePhaseTextures(resolvedPlanes)
val lensShadingTexture = createLensShadingTexture()
val fullOutput = MgcSpatialRgbRect(0, 0, width, height)
val fullOutputTile = MgcSpatialRgbTile(index = 0, outputCore = fullOutput)
val chromaPostprocessor = checkNotNull(rgbChromaPostprocessor) {
"MGC Sabre VGN color noise/IIR postprocessor is not initialized"
}
chromaPostprocessor.initStorage(listOf(fullOutputTile))
renderSabreOutputTransform(
resolvedRgbPlanes = resolvedPlanes,
lensShadingTexture = lensShadingTexture,
finalBlackLevel = sabreResolveFinalBlackLevel,
demosaicWhiteLevel = demosaicWhiteLevel.toFloat(),
output = chromaPostprocessor.normalizationTargetTexture(),
)
chromaPostprocessor.markTileWritten(fullOutputTile)
releaseSabreMergePhaseTextures(resolvedRgb)
if (!exportGpuLinearRgbSource) {
val outputBytes = width.toLong() * height * 3L * Short.SIZE_BYTES
cpuOutput = LargeDirectBuffer.allocate(outputBytes, "MGC Sabre VGN RGB16 output")
@@ -2812,21 +2802,19 @@ internal class GlesMgcRawSpatialStacker(
/**
* ResolveSabre on the GPU (see [GlesMgcSabreResolveShaders]): demosaics the dehomogenized
* accumulation, blends it with the accumulated colour by coverage and returns the R/G/B
* RAW14 planes as R16UI textures. The int16 intermediates are padded so every pass reads the
* virtual-CFA neighbourhood the original AOT reads.
* accumulation, blends it with the accumulated colour by coverage and writes the normalized,
* lens-shaded camera RGB into the RGBA16UI [output]. The int16 intermediates are padded so
* every pass reads the virtual-CFA neighbourhood the original AOT reads.
*/
private fun renderSabreResolve(
accumulatedColor: Int,
finalBlackLevel: FloatArray,
demosaicWhiteLevel: Int,
lensShadingTexture: Int,
output: Int,
greenImbalanceRetention: Float,
demosaicBlendScale: Float,
demosaicBlendBias: Float,
demosaicQuantizationScale: Float,
): IntArray {
require(finalBlackLevel.size == 3)
require(demosaicWhiteLevel in 1..Short.MAX_VALUE.toInt())
) {
require(demosaicQuantizationScale.isFinite() && demosaicQuantizationScale > 0f)
require(sabreResolveFinalGains.all { it.isFinite() && it > 0f })
// Offset of the red site; the AOT resolves in a virtual RGGB frame anchored there.
@@ -2843,9 +2831,6 @@ internal class GlesMgcRawSpatialStacker(
val converted = createTexture(planeWidth, planeHeight, GLES30.GL_R16I, GLES30.GL_NEAREST)
val balanced = createTexture(planeWidth, planeHeight, GLES30.GL_R16I, GLES30.GL_NEAREST)
val green = createTexture(planeWidth, planeHeight, GLES30.GL_R16I, GLES30.GL_NEAREST)
val resolvedPlanes = IntArray(3) {
createTexture(width, height, GLES30.GL_R16UI, GLES30.GL_NEAREST)
}
GLES30.glUseProgram(sabreResolveConvertProgram)
bindTexture(sabreResolveConvertProgram, "uAccumulated", 0, accumulatedColor)
@@ -2872,62 +2857,21 @@ internal class GlesMgcRawSpatialStacker(
draw(sabreResolveGreenProgram, planeWidth, planeHeight, intArrayOf(green))
val program = sabreResolveOutputProgram
val white = demosaicWhiteLevel.toFloat()
val black = finalBlackLevel
val gains = sabreResolveFinalGains
GLES30.glUseProgram(program)
bindTexture(program, "uAccumulated", 0, accumulatedColor)
bindTexture(program, "uBalanced", 1, balanced)
bindTexture(program, "uGreen", 2, green)
bindTexture(program, "uLensShading", 3, lensShadingTexture)
uniform2i(program, "uImageSize", width, height)
uniform2i(program, "uPlaneSize", planeWidth, planeHeight)
uniform2i(program, "uRedSite", redX, redY)
uniform1f(program, "uBlendBias", demosaicBlendBias)
uniform1f(program, "uBlendScale", demosaicBlendScale)
// The AOT multiplies by the binary32 reciprocal rather than dividing per pixel.
uniform1f(program, "uInverseQuantizationScale", 1f / demosaicQuantizationScale)
uniform3f(program, "uFinalGains", gains[0], gains[1], gains[2])
uniform3f(program, "uFinalBlackLevel", black[0], black[1], black[2])
uniform3f(
program,
"uOutputRange",
white - black[0],
white - black[1],
white - black[2],
)
GLES30.glUniform1ui(uniformLocation(program, "uFloatFence"), 0)
draw(program, width, height, resolvedPlanes)
checkGlError("MGC Sabre Resolve")
return resolvedPlanes
}
private fun renderSabreOutputTransform(
resolvedRgbPlanes: IntArray,
lensShadingTexture: Int,
finalBlackLevel: FloatArray,
demosaicWhiteLevel: Float,
output: Int,
) {
require(resolvedRgbPlanes.size == 3)
require(finalBlackLevel.size == 3)
val program = sabreOutputTransformProgram
GLES30.glUseProgram(program)
bindTexture(program, "uResolvedR", 0, resolvedRgbPlanes[0])
bindTexture(program, "uResolvedG", 1, resolvedRgbPlanes[1])
bindTexture(program, "uResolvedB", 2, resolvedRgbPlanes[2])
bindTexture(program, "uLensShading", 3, lensShadingTexture)
uniform2i(program, "uOutputSize", width, height)
uniform1i(program, "uUseLensShading", if (hasLensShading()) 1 else 0)
uniform3f(
program,
"uFinalBlackLevel",
finalBlackLevel[0],
finalBlackLevel[1],
finalBlackLevel[2],
)
uniform1f(program, "uDemosaicWhiteLevel", demosaicWhiteLevel)
uniform1f(program, "uOutputExposureScale", 1f)
draw(program, width, height, intArrayOf(output))
checkGlError("MGC Sabre Resolve")
}
private fun initSabrePrograms() {
@@ -3010,10 +2954,6 @@ internal class GlesMgcRawSpatialStacker(
GlesMgcSabreResolveShaders.resolveOutput,
"mgc_sabre_resolve_output",
)
sabreOutputTransformProgram = linkProgram(
GlesMgcRawSabreShaders.outputTransformUint16,
"mgc_sabre_output_transform_rgba16ui",
)
if (exportGpuLinearRgbSource && gpuLinearRgbStorage == GpuLinearRgbStorage.RGBA16F
) {
copyRgb16ToFloatProgram = linkComputeProgram(
@@ -3430,14 +3370,6 @@ internal class GlesMgcRawSpatialStacker(
}
}
private fun sabreResolveBlackLevel(referenceBlackLevel: FloatArray): FloatArray =
floatArrayOf(
referenceBlackLevel[0] * sabreResolveRawScale,
0.5f * (referenceBlackLevel[1] + referenceBlackLevel[2]) *
sabreResolveRawScale,
referenceBlackLevel[3] * sabreResolveRawScale,
)
private fun createBayerKernelTuning(
frame: RawStackFrame,
image: SafeImage,
@@ -8422,15 +8354,13 @@ internal class GlesMgcRawSpatialStacker(
}
/**
* ResolveSabre's accumulated-color readback has already completed every merge-stage draw.
* Retire that arena before allocating the three full-resolution RGBA16UI VGN IIR surfaces;
* only the freshly uploaded planar Resolve result crosses this phase boundary.
* ResolveSabre has consumed every merge-stage texture. Retire that arena before the VGN
* IIR surfaces are allocated; only the Resolve result in the chroma stage's assembled RGB
* crosses this phase boundary.
*/
private fun releaseSabreMergePhaseTextures(retainedTextures: IntArray) {
val retained = retainedTextures.toHashSet()
check(retained.isNotEmpty() && retained.all(textures::contains)) {
"Sabre Resolve phase must retain its uploaded RGB planes"
}
private fun releaseSabreMergePhaseTextures(resolvedRgb: Int) {
check(resolvedRgb in textures) { "Sabre Resolve phase must retain its resolved RGB" }
val retained = setOf(resolvedRgb)
detachRenderTargets()
val beforeBytes = estimatedOwnedTextureBytes()
val toDelete = textures.filterNot(retained::contains).toIntArray()
@@ -1,9 +1,9 @@
package com.hinnka.mycamera.processor
/**
* Bit-exact GLES translation of MGC 9.6.080 V24 `gcam::ResolveSabreHalide`
* (libgcastartup.so entry 0x34A55D4, worker 0x349B1B8). The independent reference and the
* oracle that checks it against the original AOT live in tools/mgc_sabre_resolve.
* GLES implementation of MGC 9.6.080 V24 `gcam::ResolveSabreHalide`
* (libgcastartup.so entry 0x34A55D4, worker 0x349B1B8). The algorithm notes live in
* tools/mgc_sabre_resolve.
*
* The AOT works in a virtual RGGB frame V(u, v) = input(clamp(u + bx), clamp(v + by)), where
* (bx, by) is the red site of the sensor CFA; output(x, y) is the result at V(x, y). Its Funcs are
@@ -12,12 +12,14 @@ package com.hinnka.mycamera.processor
* 1. `converted_to_int`: remosaic the dehomogenized RGBA16F colour into an int16 CFA.
* 2. `g_gb`: Gr/Gb balance at G sites; R/B sites keep their converted value.
* 3. `g_b$1`: adaptive green at R/B sites; G sites keep their balanced value.
* 4. `demosaic` + `output`: chroma interpolation, coverage blend and RAW14 output mapping.
* 4. `demosaic` + `output`: chroma interpolation, coverage blend, final gains and lens shading,
* written as the normalized RGBA16UI camera RGB the chroma stage consumes.
*
* Passes 1-3 write int16 planes padded by [PLANE_PADDING] on each side, covering the virtual
* coordinates their consumers touch (radius 4 for pass 1 down to radius 1 for pass 3). Every
* integer operation reproduces the NEON lane semantics of the AOT: 16-bit wraparound,
* SHADD/SRHADD rounding, SABD magnitudes, SQADD/SQSUB saturation and SSHL by a signed byte.
* coordinates their consumers touch (radius 4 for pass 1 down to radius 1 for pass 3). The
* integer demosaic is the algorithm itself, so its operations keep the NEON lane semantics of
* the AOT: 16-bit wraparound, SHADD/SRHADD rounding, SABD magnitudes, SQADD/SQSUB saturation and
* SSHL by a signed byte. The float stages around it run in native binary32.
*/
internal object GlesMgcSabreResolveShaders {
const val PLANE_PADDING = 4
@@ -106,17 +108,7 @@ internal object GlesMgcSabreResolveShaders {
}
""".trimIndent()
private val halfToFloat = """
// The AOT widens F16 with an exponent rebias only: bits = sign | magnitude << 13, plus
// 0x38000000. Zero becomes 2^-15 and subnormals keep the normal-number formula.
float aotHalfToFloat(float value) {
uint h = packHalf2x16(vec2(value, 0.0)) & 0xffffu;
uint bits = ((h & 0x8000u) << 16) | ((h & 0x7fffu) << 13);
return uintBitsToFloat(bits + 0x38000000u);
}
""".trimIndent()
/** Pass 1, `converted_to_int`: int16(clamp(roundEven(h2f * S), -32768, 32767)). */
/** Pass 1, `converted_to_int`: int16(clamp(roundEven(c * S), -32768, 32767)). */
val convertToInt = """
${header.prependIndent(" ").trimStart()}
uniform highp sampler2D uAccumulated;
@@ -125,15 +117,13 @@ internal object GlesMgcSabreResolveShaders {
uniform float uQuantizationScale;
layout(location = 0) out highp ivec4 oConverted;
${halfToFloat.prependIndent(" ").trimStart()}
void main() {
ivec2 virtualSite = ivec2(gl_FragCoord.xy) - ivec2($PLANE_PADDING);
ivec2 source = clamp(virtualSite + uRedSite, ivec2(0), uImageSize - ivec2(1));
vec4 color = texelFetch(uAccumulated, source, 0);
int cfaColor = (virtualSite.x & 1) + (virtualSite.y & 1);
float sampleValue = cfaColor == 0 ? color.r : (cfaColor == 1 ? color.g : color.b);
float scaled = aotHalfToFloat(sampleValue) * uQuantizationScale;
float scaled = sampleValue * uQuantizationScale;
oConverted = ivec4(int(clamp(roundEven(scaled), -32768.0, 32767.0)), 0, 0, 0);
}
""".trimIndent()
@@ -255,9 +245,9 @@ internal object GlesMgcSabreResolveShaders {
""".trimIndent()
/**
* Pass 4, `demosaic` + `output`. Float arithmetic follows the AOT's FMUL/FADD order without
* fused multiply-add: every product that feeds an addition passes through [uFloatFence],
* a uniform zero the compiler cannot prove to be zero, so it is rounded to binary32 first.
* Pass 4, `demosaic` + `output`. The coverage weight blends the accumulated colour toward the
* demosaic; the result times the final gains and the lens shading is the black-free camera RGB,
* stored as RGBA16UI on [0, 65535].
*/
val resolveOutput = """
${header.prependIndent(" ").trimStart()}
@@ -271,19 +261,12 @@ internal object GlesMgcSabreResolveShaders {
uniform float uBlendScale;
uniform float uInverseQuantizationScale;
uniform vec3 uFinalGains;
uniform vec3 uFinalBlackLevel;
uniform vec3 uOutputRange;
uniform uint uFloatFence;
layout(location = 0) out highp uvec4 oRed;
layout(location = 1) out highp uvec4 oGreen;
layout(location = 2) out highp uvec4 oBlue;
// RGGB gains of the lens shading map; a 1x1 map of ones when the capture has none.
uniform highp sampler2D uLensShading;
layout(location = 0) out highp uvec4 oResolved;
${integerOps.prependIndent(" ").trimStart()}
${halfToFloat.prependIndent(" ").trimStart()}
float rounded(float value) { return uintBitsToFloat(floatBitsToUint(value) ^ uFloatFence); }
// Converted value; only read at R/B sites, where pass 2 kept it.
int converted(int u, int v) { return planeAt(uBalanced, uPlaneSize, u, v); }
int green(int u, int v) { return planeAt(uGreen, uPlaneSize, u, v); }
@@ -328,14 +311,6 @@ internal object GlesMgcSabreResolveShaders {
return ig2(cost2, cost1, x2, x1);
}
uint resolveChannel(float accumulated, int demosaiced, float weight, int channel) {
float demosaicedValue = float(demosaiced) * uInverseQuantizationScale;
float mixed = rounded((1.0 - weight) * accumulated) + rounded(weight * demosaicedValue);
float scaled = rounded((mixed * uFinalGains[channel]) * uOutputRange[channel]);
float value = roundEven(uFinalBlackLevel[channel] + scaled);
return uint(clamp(value, 0.0, 65535.0));
}
void main() {
ivec2 site = ivec2(gl_FragCoord.xy);
int u = site.x;
@@ -344,14 +319,16 @@ internal object GlesMgcSabreResolveShaders {
int demosaicedRed = cfaColor == 0 ? converted(u, v) : chroma(u, v, false);
int demosaicedGreen = green(u, v);
int demosaicedBlue = cfaColor == 2 ? converted(u, v) : chroma(u, v, true);
vec3 demosaiced = vec3(demosaicedRed, demosaicedGreen, demosaicedBlue) *
uInverseQuantizationScale;
ivec2 source = clamp(site + uRedSite, ivec2(0), uImageSize - ivec2(1));
vec4 color = texelFetch(uAccumulated, source, 0);
float weight = uBlendBias + rounded(aotHalfToFloat(color.a) * uBlendScale);
weight = max(min(weight, 1.0), 0.0);
oRed = uvec4(resolveChannel(aotHalfToFloat(color.r), demosaicedRed, weight, 0));
oGreen = uvec4(resolveChannel(aotHalfToFloat(color.g), demosaicedGreen, weight, 1));
oBlue = uvec4(resolveChannel(aotHalfToFloat(color.b), demosaicedBlue, weight, 2));
float weight = clamp(uBlendBias + color.a * uBlendScale, 0.0, 1.0);
vec4 shading = texture(uLensShading, (vec2(site) + 0.5) / vec2(uImageSize));
vec3 gains = uFinalGains * vec3(shading.r, 0.5 * (shading.g + shading.b), shading.a);
vec3 resolved = clamp(mix(color.rgb, demosaiced, weight) * gains, 0.0, 1.0);
oResolved = uvec4(uvec3(round(resolved * 65535.0)), 65535u);
}
""".trimIndent()
}
@@ -1,199 +1,33 @@
package com.hinnka.mycamera.raw
/**
* Bit-exact GLES translation of the MGC 9.7.047 V25 guided upsampling chain
* GLES implementation of the MGC 9.7.047 V25 guided upsampling chain
* (`BoxDownsampleS16` 0x4D3686C and `GuidedUpsampleS16To16Bit` 0x4BA6500 in libgcastartup.so)
* together with the former CPU adapters around it. The independent reference, the algorithm notes
* and the oracle that checks these shaders against the original AOT live in
* tools/mgc_guided_upsample.
* together with the former CPU adapters around it. The algorithm notes live in
* tools/mgc_guided_upsample. Everything runs in binary32; luma is on the encoded [0, 1] scale. The
* mathematics of the original is kept, not its fixed-point and evaluation-order rounding.
*
* Prepare (full-resolution float RGBA source):
* 1. `guide`: padded Q14 linear Y in the sqrt domain (R16I, padded size).
* 2. `lowGuide`: box-downsampled Q14 Y in the sqrt domain (R16I, padded size / scale).
* 3. `lowColor`: box-downsampled linear RGB / 16383 / white balance (RGBA16F, low size).
* 1. `guide`: linear Y in the sqrt-domain guide units sqrt(16383 Y) * 128 (R16I, padded size).
* 2. `low`: box means of the white-balanced, clamped linear RGB at padded size / scale; their
* guide value (R16I) and the colour with the white balance removed again (RGBA16F).
*
* Render (low-resolution encoded RGBA16F):
* 1. `lowYuv`: U12 Y, U, V (RGBA16I, low size).
* 2. `cellFit`: two-level weighted affine fit per grid cell (2 x RGBA32UI, cell grid).
* 3. `horizontal`: cell models interpolated to output columns (2 x RGBA32UI).
* 4. `guidedY`: vertical interpolation and the two-level blend (R16I, output grown by
* 1. `cellFit`: two-level weighted ridge fit Y = a G + b per grid cell (2 x RGBA32UI holding
* binary32 bits, cell grid).
* 2. `horizontal`: cell models interpolated to output columns (2 x RGBA32UI).
* 3. `guidedY`: vertical interpolation and the two-level blend (R32F, output grown by
* [GUIDED_PADDING] per side; the guided luma outside the image is its natural extension).
* 5. `level1`, `level2`, `output`: the V24 SharpenTo16Bit passes on the guided luma, plus the
* integer chroma upsampling and the Q12 YUV -> RGB of the original.
*
* GLSL ES 3.00 guarantees correct rounding only for finite +, - and * in highp. Everything that can
* become infinite or NaN (from the det on) travels as binary32 bit patterns and goes through
* the `*Bits` helpers, which resolve special operands explicitly and hand only finite operands to the
* hardware. Divisions are integer long divisions with round-to-nearest-even; the sqrt is a LUT.
* 4. `level1`, `level2`, `output`: the [GlesMgcSharpenShaders] pyramid and kernel on the guided
* luma; the chroma is the bilinear upsampling of the low-resolution colour.
*/
internal object GlesMgcGuidedUpsampleShaders {
const val GUIDED_PADDING = 7
const val LEVEL1_PADDING = 6
const val LEVEL2_PADDING = 4
private val header = """
#version 300 es
precision highp float;
precision highp int;
precision highp sampler2D;
precision highp isampler2D;
precision highp usampler2D;
""".trimIndent()
private val header = GlesMgcSharpenShaders.header
private val integerOps = """
private val padding = """
const int GUIDED_PADDING = $GUIDED_PADDING;
const int LEVEL1_PADDING = $LEVEL1_PADDING;
const int LEVEL2_PADDING = $LEVEL2_PADDING;
int s16(int v) { return (v << 16) >> 16; }
// SHADD / SRHADD .8h; inputs are int16 so the halved sums never wrap.
int hadd(int a, int b) { return (a + b) >> 1; }
int rhadd(int a, int b) { return (a + b + 1) >> 1; }
""".trimIndent()
// GLSL ES has no `precise`. XOR with a zero uniform forces each product to be rounded to binary32
// before it is added, as the original's separate FMUL/FADD do.
private val floatOps = """
uniform uint uFloatFence;
float fenced(float value) { return uintBitsToFloat(floatBitsToUint(value) ^ uFloatFence); }
float unitToU12(float value) { return fenced(clamp(value, 0.0, 1.0) * 4095.0); }
// One row of the FinishRaw U12 matrix, rounded half to even and clamped to +-4095.
int u12Row(float r, float g, float b, float m0, float m1, float m2) {
float partial = fenced(fenced(r * m0) + fenced(g * m1));
return clamp(int(roundEven(partial + fenced(b * m2))), -4095, 4095);
}
""".trimIndent()
// binary32 arithmetic on bit patterns with AArch64 semantics (default NaN, no flush to zero).
// Results are only ever consumed as "NaN or not", so one canonical NaN suffices. Subnormal
// operands and results do not occur on this pipeline; the branches that would need them return
// trapBits(), whose subnormal product the oracle's checked float rejects.
private val bitOps = """
const uint SIGN_BIT = 0x80000000u;
const uint MAGNITUDE = 0x7fffffffu;
const uint INFINITY_BITS = 0x7f800000u;
const uint NAN_BITS = 0x7fc00000u;
const uint MANTISSA = 0x007fffffu;
bool isNanBits(uint a) { return (a & MAGNITUDE) > INFINITY_BITS; }
bool isInfBits(uint a) { return (a & MAGNITUDE) == INFINITY_BITS; }
bool isZeroBits(uint a) { return (a & MAGNITUDE) == 0u; }
int exponentBits(uint a) { return int((a >> 23) & 0xffu); }
uint trapBits() { return floatBitsToUint(fenced(uintBitsToFloat(0x00800000u) * 0.5)); }
uint mulBits(uint a, uint b) {
uint signBit = (a ^ b) & SIGN_BIT;
if (isNanBits(a) || isNanBits(b)) return NAN_BITS;
bool zero = isZeroBits(a) || isZeroBits(b);
if (isInfBits(a) || isInfBits(b)) return zero ? NAN_BITS : (signBit | INFINITY_BITS);
if (zero) return signBit;
if (exponentBits(a) == 0 || exponentBits(b) == 0) return trapBits();
int e = exponentBits(a) + exponentBits(b) - 254;
if (e >= 128) return signBit | INFINITY_BITS;
if (e >= -126 && e <= 125) {
return floatBitsToUint(fenced(uintBitsToFloat(a) * uintBitsToFloat(b)));
}
// |a * b| may reach 2^128 or fall below 2^-126: multiply the significands in [1, 2)
// and rebuild the exponent.
float ma = uintBitsToFloat((a & MANTISSA) | 0x3f800000u);
float mb = uintBitsToFloat((b & MANTISSA) | 0x3f800000u);
uint p = floatBitsToUint(fenced(ma * mb));
int biased = exponentBits(p) + e;
if (biased >= 255) return signBit | INFINITY_BITS;
if (biased <= 0) return trapBits();
return signBit | (uint(biased) << 23) | (p & MANTISSA);
}
uint addBits(uint a, uint b) {
if (isNanBits(a) || isNanBits(b)) return NAN_BITS;
if (isInfBits(a)) return isInfBits(b) && ((a ^ b) & SIGN_BIT) != 0u ? NAN_BITS : a;
if (isInfBits(b)) return b;
int ea = exponentBits(a);
int eb = exponentBits(b);
if (max(ea, eb) <= 253) {
return floatBitsToUint(fenced(uintBitsToFloat(a) + uintBitsToFloat(b)));
}
// One operand is at least 2^127. A far smaller one is below half an ulp.
if (isZeroBits(b) || eb < 224) return a;
if (isZeroBits(a) || ea < 224) return b;
float halved = fenced(uintBitsToFloat(a - 0x00800000u) + uintBitsToFloat(b - 0x00800000u));
uint s = floatBitsToUint(halved);
if (isZeroBits(s)) return s;
if (exponentBits(s) >= 254) return (s & SIGN_BIT) | INFINITY_BITS;
return s + 0x00800000u;
}
uint subBits(uint a, uint b) { return addBits(a, b ^ SIGN_BIT); }
// Correctly rounded (RNE) division by long division of the 24-bit significands.
uint divBits(uint a, uint b) {
uint signBit = (a ^ b) & SIGN_BIT;
if (isNanBits(a) || isNanBits(b)) return NAN_BITS;
if (isInfBits(a)) return isInfBits(b) ? NAN_BITS : (signBit | INFINITY_BITS);
if (isInfBits(b)) return signBit;
if (isZeroBits(b)) return isZeroBits(a) ? NAN_BITS : (signBit | INFINITY_BITS);
if (isZeroBits(a)) return signBit;
if (exponentBits(a) == 0 || exponentBits(b) == 0) return trapBits();
uint ma = (a & MANTISSA) | 0x00800000u;
uint mb = (b & MANTISSA) | 0x00800000u;
int e = exponentBits(a) - exponentBits(b) + 127;
if (ma < mb) {
ma <<= 1;
e -= 1;
}
uint q = 0u;
uint r = ma;
for (int i = 0; i < 25; ++i) {
q <<= 1;
if (r >= mb) {
r -= mb;
q |= 1u;
}
r <<= 1;
}
uint roundBit = q & 1u;
q >>= 1;
if (roundBit == 1u && (r != 0u || (q & 1u) == 1u)) q += 1u;
if (q == 0x01000000u) {
q >>= 1;
e += 1;
}
if (e >= 255) return signBit | INFINITY_BITS;
if (e <= 0) return trapBits();
return signBit | (uint(e) << 23) | (q & MANTISSA);
}
// SCVTF: int32 -> binary32, round to nearest even.
float intToFloat(int v) {
if (v >= -16777216 && v <= 16777216) return float(v);
uint signBit = v < 0 ? SIGN_BIT : 0u;
uint m = v < 0 ? uint(-(v + 1)) + 1u : uint(v);
int msb = findMSB(m);
int shift = msb - 23;
uint q = m >> uint(shift);
uint rest = m & ((1u << uint(shift)) - 1u);
uint halfway = 1u << uint(shift - 1);
if (rest > halfway || (rest == halfway && (q & 1u) == 1u)) q += 1u;
if (q == 0x01000000u) {
q >>= 1;
msb += 1;
}
return uintBitsToFloat(signBit | (uint(msb + 127) << 23) | (q & MANTISSA));
}
// FRINTN, then FMIN/FMAX against the int16 range and FCVTZS (NaN -> 0).
int roundSaturateS16(uint v) {
if (isNanBits(v)) return 0;
if (isInfBits(v)) return (v & SIGN_BIT) != 0u ? -32768 : 32767;
float f = uintBitsToFloat(v);
if (f >= 32768.0) return 32767;
if (f <= -32769.0) return -32768;
return clamp(int(roundEven(f)), -32768, 32767);
}
""".trimIndent()
// Q17 cell coordinate of a full-resolution pixel, u = (x + 0.5) / (2 * scale) - 0.5, and the
@@ -212,226 +46,128 @@ internal object GlesMgcGuidedUpsampleShaders {
return ivec2(p >> 16, p & 0xffff);
}
// 1.52590219e-05 (0x37800080), the original's 1 / 65535.
float fractionScale() { return uintBitsToFloat(0x37800080u); }
float tapFraction(int q16) { return float(q16) * (1.0 / 65536.0); }
""".trimIndent()
// -- prepare ----------------------------------------------------------------------------------
// GuidedFloatRgbaToLinearYuv: WB, clamp to [0, 1], ties-away Q14 quantisation, Q13 matrix with
// saturating rounding narrows. The source is replicated beyond its own size into the padding.
// White balance, clamp to [0, 1] and the Q13 BT.709 luma, whose weights sum to exactly one.
// The source is replicated beyond its own size into the padding.
private val linearOps = """
uniform highp sampler2D uSource;
uniform ivec2 uSourceMax;
uniform float uWhiteBalance[3];
uniform highp isampler2D uSqrtLut;
uniform vec3 uWhiteBalance;
int q14(float channel, float gain) {
uint balanced = mulBits(floatBitsToUint(channel), floatBitsToUint(gain));
float bounded;
if (isNanBits(balanced)) {
bounded = 0.0;
} else if (isInfBits(balanced)) {
bounded = (balanced & SIGN_BIT) != 0u ? 0.0 : 1.0;
} else {
bounded = clamp(uintBitsToFloat(balanced), 0.0, 1.0);
}
float scaled = fenced(bounded * 16383.0);
float whole = floor(scaled);
return int(whole) + (fenced(scaled - whole) >= 0.5 ? 1 : 0);
const vec3 LINEAR_LUMA = vec3(1742.0, 5859.0, 591.0) / 8192.0;
vec3 balanced(ivec2 p) {
return clamp(texelFetch(uSource, min(p, uSourceMax), 0).rgb * uWhiteBalance, 0.0, 1.0);
}
int narrow13(int v) { return clamp((v + 4096) >> 13, -32768, 32767); }
ivec3 linearYuv(ivec2 p) {
vec4 color = texelFetch(uSource, min(p, uSourceMax), 0);
int r = q14(color.r, uWhiteBalance[0]);
int g = q14(color.g, uWhiteBalance[1]);
int b = q14(color.b, uWhiteBalance[2]);
return ivec3(narrow13(1742 * r + 5859 * g + 591 * b),
narrow13(-1331 * r - 4477 * g + 5808 * b),
s16(r + narrow13(-7441 * g - 751 * b)));
}
// SqrtGuide: LUT of int16(sqrt(max(g, 0)) * 128) for g in [0, 32767], 256 x 128.
int sqrtGuide(int g) {
if (g <= 0) return 0;
return texelFetch(uSqrtLut, ivec2(g & 255, g >> 8), 0).r;
}
""".trimIndent()
private val boxOps = """
uniform int uLog2Scale;
// BoxDownsample: per column a rounded vertical mean, then a rounded horizontal mean (int32).
ivec3 boxYuv(ivec2 low) {
int scale = 1 << uLog2Scale;
int rounding = scale >> 1;
ivec3 sum = ivec3(0);
for (int i = 0; i < scale; ++i) {
ivec3 column = ivec3(0);
for (int j = 0; j < scale; ++j) column += linearYuv(low * scale + ivec2(i, j));
sum += (column + rounding) >> uLog2Scale;
}
return (sum + rounding) >> uLog2Scale;
}
// SqrtGuide of the Q14 luma: sqrt(16383 Y) * 128, at most 16384.
int guideValue(float luma) { return int(roundEven(sqrt(luma * 16383.0) * 128.0)); }
""".trimIndent()
private val guide = """
layout(location = 0) out int oGuide;
void main() {
oGuide = sqrtGuide(linearYuv(ivec2(gl_FragCoord.xy)).x);
oGuide = guideValue(dot(balanced(ivec2(gl_FragCoord.xy)), LINEAR_LUMA));
}
""".trimIndent()
private val lowGuide = """
// BoxDownsample of the linear YUV followed by YUV -> RGB is, by linearity, the box mean of the
// balanced RGB; the low colour is that mean with the white balance removed.
private val low = """
uniform int uLog2Scale;
layout(location = 0) out int oGuide;
layout(location = 1) out vec4 oColor;
void main() {
oGuide = sqrtGuide(boxYuv(ivec2(gl_FragCoord.xy)).x);
}
""".trimIndent()
// GuidedLinearYuvToRgb followed by rgb / 16383 / wb (two RNE divisions) and RNE to binary16,
// emitted as a float the RGBA16F attachment stores exactly.
private val lowColor = """
layout(location = 0) out vec4 oColor;
int saturate16(int v) { return clamp(v, -32768, 32767); }
float roundToHalf(uint v) {
uint signBit = v & SIGN_BIT;
float signValue = signBit != 0u ? -1.0 : 1.0;
if (isInfBits(v)) return uintBitsToFloat(v);
if (isZeroBits(v)) return uintBitsToFloat(signBit);
int e = exponentBits(v) - 127;
if (e >= 16) return uintBitsToFloat(signBit | INFINITY_BITS);
uint m = (v & MANTISSA) | 0x00800000u;
int shift = e >= -14 ? 13 : -1 - e;
if (shift >= 25) return uintBitsToFloat(signBit);
uint q = m >> uint(shift);
uint rest = m & ((1u << uint(shift)) - 1u);
uint halfway = 1u << uint(shift - 1);
if (rest > halfway || (rest == halfway && (q & 1u) == 1u)) q += 1u;
int unit = e >= -14 ? e - 10 : -24;
if (unit == 5 && q == 2048u) return uintBitsToFloat(signBit | INFINITY_BITS);
float power = uintBitsToFloat(uint(unit + 127) << 23);
return fenced(fenced(float(q) * power) * signValue);
}
float unitColor(int v, int channel) {
uint scaled = divBits(floatBitsToUint(float(v)), floatBitsToUint(16383.0));
return roundToHalf(divBits(scaled, floatBitsToUint(uWhiteBalance[channel])));
}
void main() {
ivec3 yuv = boxYuv(ivec2(gl_FragCoord.xy));
int y = yuv.x;
int u = yuv.y;
int v = yuv.z;
int r = saturate16(y + ((v * 25802 + 16384) >> 15));
int g = saturate16(y + ((v * -15340 + u * -8658 + 32768) >> 16));
int b = saturate16(y + ((u * 21442 + 8192) >> 14));
oColor = vec4(unitColor(r, 0), unitColor(g, 1), unitColor(b, 2), 1.0);
int scale = 1 << uLog2Scale;
ivec2 origin = ivec2(gl_FragCoord.xy) * scale;
vec3 sum = vec3(0.0);
for (int j = 0; j < scale; ++j) {
for (int i = 0; i < scale; ++i) sum += balanced(origin + ivec2(i, j));
}
vec3 mean = sum / float(scale * scale);
oGuide = guideValue(dot(mean, LINEAR_LUMA));
oColor = vec4(mean / uWhiteBalance, 1.0);
}
""".trimIndent()
// -- render -----------------------------------------------------------------------------------
private val lowYuv = """
uniform highp sampler2D uSource;
layout(location = 0) out ivec4 oYuv;
void main() {
vec4 color = texelFetch(uSource, ivec2(gl_FragCoord.xy), 0);
float r = unitToU12(color.r);
float g = unitToU12(color.g);
float b = unitToU12(color.b);
oYuv = ivec4(u12Row(r, g, b, 0.2125999927520752, 0.7152000069618225, 0.07219959795475006),
u12Row(r, g, b, -0.16245023906230927, -0.5464943051338196, 0.7089447379112244),
u12Row(r, g, b, 0.9999967217445374, -0.9083024859428406, -0.09169333428144455), 0);
}
""".trimIndent()
// Cell (kx, ky) fits out = a * g + b on the 4x4 low-resolution window starting at
// Cell (kx, ky) fits Y = a G + b on the 4x4 low-resolution window starting at
// (2 kx - 1, 2 ky - 1) (clamped), for two levels softly split between min - 1 and max + 1 of the
// sqrt-domain guide, with tent spatial weights. Sums run serially in the original order.
// sqrt-domain guide, with tent spatial weights. Each level minimises
// sum w (a G + b - Y)^2 + EPSILON (a^2 + b^2). The moments are taken about lo (C = G - lo), so the
// normal equations do not cancel catastrophically; with b = b' - a lo the penalty becomes
// EPSILON (a^2 + (b' - a lo)^2), which keeps the solution of the uncentred problem.
private val cellFit = """
uniform highp isampler2D uLowGuide;
uniform highp isampler2D uLowYuv;
uniform highp sampler2D uLowSource;
uniform ivec2 uLowMax;
uniform ivec2 uCellOrigin;
layout(location = 0) out uvec4 oCell0;
layout(location = 1) out uvec4 oCell1;
float tent(int i) { return i == 0 || i == 3 ? 0.625 : 0.875; }
const float EPSILON = 1.0e-4;
uvec2 solve(float s0, float sg, float sgg, float sy, float sgy) {
float epsilon = uintBitsToFloat(0x38d1b717u);
float s0e = s0 + epsilon;
float sgge = sgg + epsilon;
float negativeSg = 0.0 - sg;
float det = fenced(s0e * sgge) - fenced(sg * sg);
uint reciprocal = divBits(floatBitsToUint(1.0), floatBitsToUint(det));
float bNumerator = fenced(sgge * sy) + fenced(negativeSg * sgy);
float aNumerator = fenced(negativeSg * sy) + fenced(s0e * sgy);
return uvec2(mulBits(reciprocal, floatBitsToUint(aNumerator)),
mulBits(reciprocal, floatBitsToUint(bNumerator)));
}
float tent(int i) { return i == 0 || i == 3 ? 0.625 : 0.875; }
void main() {
ivec2 cell = ivec2(gl_FragCoord.xy) + uCellOrigin;
ivec2 origin = 2 * cell - ivec2(1);
int g[16];
int y[16];
int lowest = 32767;
int highest = -32768;
float g[16];
float y[16];
float lowest = 32767.0;
float highest = -32768.0;
for (int r = 0; r < 4; ++r) {
for (int k = 0; k < 4; ++k) {
ivec2 p = clamp(origin + ivec2(k, r), ivec2(0), uLowMax);
g[r * 4 + k] = texelFetch(uLowGuide, p, 0).r;
y[r * 4 + k] = texelFetch(uLowYuv, p, 0).r;
g[r * 4 + k] = float(texelFetch(uLowGuide, p, 0).r);
vec3 rgb = clamp(texelFetch(uLowSource, p, 0).rgb, 0.0, 1.0);
y[r * 4 + k] = dot(rgb, ENCODED_LUMA);
lowest = min(lowest, g[r * 4 + k]);
highest = max(highest, g[r * 4 + k]);
}
}
float lo = float(lowest) + -1.0;
float hi = float(highest) + 1.0;
float reciprocal = uintBitsToFloat(divBits(floatBitsToUint(1.0), floatBitsToUint(hi - lo)));
uvec2 model[2];
float lo = lowest - 1.0;
float hi = highest + 1.0;
float range = hi - lo;
vec2 model[2];
for (int level = 0; level < 2; ++level) {
float w[16];
for (int r = 0; r < 4; ++r) {
for (int k = 0; k < 4; ++k) {
float t = fenced((hi - float(g[r * 4 + k])) * reciprocal);
float spatial = fenced(tent(r) * tent(k));
w[r * 4 + k] = fenced(spatial * (level == 0 ? t : 1.0 - t));
}
}
float s0 = 0.0;
float sg = 0.0;
float sgg = 0.0;
for (int i = 0; i < 16; ++i) {
s0 = s0 + w[i];
sg = sg + fenced(w[i] * float(g[i]));
sgg = sgg + fenced(w[i] * intToFloat(g[i] * g[i]));
}
float sc = 0.0;
float scc = 0.0;
float sy = 0.0;
float sgy = 0.0;
float scy = 0.0;
for (int i = 0; i < 16; ++i) {
sy = sy + fenced(w[i] * float(y[i]));
sgy = sgy + fenced(w[i] * intToFloat(g[i] * y[i]));
float c = g[i] - lo;
// Level 0 favours the dark end of the window, level 1 the bright end.
float t = level == 0 ? (hi - g[i]) / range : c / range;
float w = tent(i >> 2) * tent(i & 3) * t;
s0 += w;
sc += w * c;
scc += w * c * c;
sy += w * y[i];
scy += w * c * y[i];
}
model[level] = solve(s0, sg, sgg, sy, sgy);
float m00 = s0 + EPSILON;
float m01 = sc - EPSILON * lo;
float m11 = scc + EPSILON * (1.0 + lo * lo);
float det = m00 * m11 - m01 * m01;
float a = (m00 * scy - m01 * sy) / det;
float centred = (m11 * sy - m01 * scy) / det;
model[level] = vec2(a, centred - a * lo);
}
oCell0 = uvec4(floatBitsToUint(lo), floatBitsToUint(hi), model[0].x, model[0].y);
oCell1 = uvec4(model[1].x, model[1].y, 0u, 0u);
oCell0 = floatBitsToUint(vec4(lo, hi, model[0]));
oCell1 = floatBitsToUint(vec4(model[1], 0.0, 0.0));
}
""".trimIndent()
// Row j holds cell row uCellOrigin.y + j interpolated to columns x = i - GUIDED_PADDING:
// c0 * (1 - f C) + (c1 * f) * C.
// Row j holds cell row uCellOrigin.y + j interpolated to columns x = i - GUIDED_PADDING.
private val horizontal = """
uniform highp usampler2D uCell0;
uniform highp usampler2D uCell1;
@@ -439,33 +175,24 @@ internal object GlesMgcGuidedUpsampleShaders {
layout(location = 0) out uvec4 oRow0;
layout(location = 1) out uvec4 oRow1;
uint lerpBits(uint c0, uint c1, uint w0, uint f, uint scale) {
return addBits(mulBits(c0, w0), mulBits(mulBits(c1, f), scale));
}
void main() {
ivec2 p = ivec2(gl_FragCoord.xy);
ivec2 tap = cellTap(p.x - GUIDED_PADDING);
ivec2 left = ivec2(tap.x - uCellOrigin.x, p.y);
ivec2 right = left + ivec2(1, 0);
float f = float(tap.y);
float w0 = 1.0 - fenced(f * fractionScale());
uint w0Bits = floatBitsToUint(w0);
uint fBits = floatBitsToUint(f);
uint scale = floatBitsToUint(fractionScale());
uvec4 a0 = texelFetch(uCell0, left, 0);
uvec4 b0 = texelFetch(uCell0, right, 0);
uvec4 a1 = texelFetch(uCell1, left, 0);
uvec4 b1 = texelFetch(uCell1, right, 0);
oRow0 = uvec4(lerpBits(a0.r, b0.r, w0Bits, fBits, scale), lerpBits(a0.g, b0.g, w0Bits, fBits, scale),
lerpBits(a0.b, b0.b, w0Bits, fBits, scale), lerpBits(a0.a, b0.a, w0Bits, fBits, scale));
oRow1 = uvec4(lerpBits(a1.r, b1.r, w0Bits, fBits, scale), lerpBits(a1.g, b1.g, w0Bits, fBits, scale),
0u, 0u);
float f = tapFraction(tap.y);
vec4 row0 = mix(uintBitsToFloat(texelFetch(uCell0, left, 0)),
uintBitsToFloat(texelFetch(uCell0, right, 0)), f);
vec2 row1 = mix(uintBitsToFloat(texelFetch(uCell1, left, 0)).xy,
uintBitsToFloat(texelFetch(uCell1, right, 0)).xy, f);
oRow0 = floatBitsToUint(row0);
oRow1 = floatBitsToUint(vec4(row1, 0.0, 0.0));
}
""".trimIndent()
// Vertical interpolation H0 * (1 - w1) + H1 * w1, then
// Y = sat16(rne((1 - t) (b0 + a0 G) + t (b1 + a1 G))), t = clamp((G - lo) / (hi - lo), 0, 1).
// Vertical interpolation, then
// Y = (1 - t) (b0 + a0 G) + t (b1 + a1 G), t = clamp((G - lo) / (hi - lo), 0, 1).
// hi - lo >= 2 in every cell, so the interpolated range never vanishes.
// Pixel (i, j) is image position (i, j) - GUIDED_PADDING.
private val guidedY = """
uniform highp usampler2D uRow0;
@@ -473,11 +200,7 @@ internal object GlesMgcGuidedUpsampleShaders {
uniform highp isampler2D uGuide;
uniform ivec2 uGuideMax;
uniform int uCellOriginY;
layout(location = 0) out int oLuma;
uint vertical(uint top, uint bottom, uint w0, uint w1) {
return addBits(mulBits(top, w0), mulBits(bottom, w1));
}
layout(location = 0) out float oLuma;
void main() {
ivec2 p = ivec2(gl_FragCoord.xy);
@@ -485,199 +208,69 @@ internal object GlesMgcGuidedUpsampleShaders {
ivec2 tap = cellTap(image.y);
ivec2 top = ivec2(p.x, tap.x - uCellOriginY);
ivec2 bottom = top + ivec2(0, 1);
float w1 = fenced(float(tap.y) * fractionScale());
uint w1Bits = floatBitsToUint(w1);
uint w0Bits = floatBitsToUint(1.0 - w1);
uvec4 t0 = texelFetch(uRow0, top, 0);
uvec4 d0 = texelFetch(uRow0, bottom, 0);
uvec4 t1 = texelFetch(uRow1, top, 0);
uvec4 d1 = texelFetch(uRow1, bottom, 0);
uint lo = vertical(t0.r, d0.r, w0Bits, w1Bits);
uint hi = vertical(t0.g, d0.g, w0Bits, w1Bits);
uint a0 = vertical(t0.b, d0.b, w0Bits, w1Bits);
uint b0 = vertical(t0.a, d0.a, w0Bits, w1Bits);
uint a1 = vertical(t1.r, d1.r, w0Bits, w1Bits);
uint b1 = vertical(t1.g, d1.g, w0Bits, w1Bits);
float f = tapFraction(tap.y);
// (lo, hi, a0, b0) and (a1, b1)
vec4 row0 = mix(uintBitsToFloat(texelFetch(uRow0, top, 0)),
uintBitsToFloat(texelFetch(uRow0, bottom, 0)), f);
vec2 row1 = mix(uintBitsToFloat(texelFetch(uRow1, top, 0)).xy,
uintBitsToFloat(texelFetch(uRow1, bottom, 0)).xy, f);
float guide = float(texelFetch(uGuide, clamp(image, ivec2(0), uGuideMax), 0).r);
uint guideBits = floatBitsToUint(guide);
float low = uintBitsToFloat(lo);
float t = uintBitsToFloat(divBits(floatBitsToUint(guide - low),
floatBitsToUint(uintBitsToFloat(hi) - low)));
t = max(min(t, 1.0), 0.0);
uint lowModel = addBits(b0, mulBits(a0, guideBits));
uint highModel = addBits(b1, mulBits(a1, guideBits));
uint blended = addBits(mulBits(floatBitsToUint(1.0 - t), lowModel),
mulBits(floatBitsToUint(t), highModel));
oLuma = roundSaturateS16(blended);
float t = clamp((guide - row0.x) / (row0.y - row0.x), 0.0, 1.0);
oLuma = mix(row0.w + row0.z * guide, row1.y + row1.x * guide, t);
}
""".trimIndent()
private val level1 = """
uniform highp isampler2D uLuma;
layout(location = 0) out int oLevel;
private val guidedLuma = """
uniform highp sampler2D uLuma;
int luma(ivec2 p) { return texelFetch(uLuma, p + ivec2(GUIDED_PADDING), 0).r; }
int column(ivec2 p) {
return rhadd(hadd(luma(p - ivec2(0, 1)), luma(p + ivec2(0, 1))), luma(p));
}
void main() {
ivec2 p = ivec2(gl_FragCoord.xy) - ivec2(LEVEL1_PADDING);
oLevel = hadd(rhadd(column(p - ivec2(1, 0)), column(p + ivec2(1, 0))), column(p));
}
float luma(ivec2 p) { return texelFetch(uLuma, p + ivec2(GUIDED_PADDING), 0).r; }
""".trimIndent()
private val level2 = """
uniform highp isampler2D uLevel1;
layout(location = 0) out int oLevel;
private val guidedLumaSource = """
$guidedLuma
int level1(ivec2 p) { return texelFetch(uLevel1, p + ivec2(LEVEL1_PADDING), 0).r; }
int column(ivec2 p) {
return rhadd(hadd(level1(p - ivec2(0, 2)), level1(p + ivec2(0, 2))), level1(p));
}
void main() {
ivec2 p = ivec2(gl_FragCoord.xy) - ivec2(LEVEL2_PADDING);
oLevel = hadd(rhadd(column(p - ivec2(2, 0)), column(p + ivec2(2, 0))), column(p));
}
float source(ivec2 p) { return luma(p); }
""".trimIndent()
// The original adds the sharpened Y to the bilinearly upsampled U and V of the clamped low
// colour; by linearity that is the upsampled colour with its luma replaced.
private val output = """
uniform highp isampler2D uLuma;
uniform highp isampler2D uLevel1;
uniform highp isampler2D uLevel2;
uniform highp isampler2D uLowYuv;
uniform highp sampler2D uLowSource;
uniform ivec2 uLowMax;
// Per band: knots 1..3 (U12), then four segment slopes (Q8) and intercepts (U12).
uniform int uKnots[9];
uniform int uSlopes[12];
uniform int uIntercepts[12];
// (width >> 1, ((height + 1) & ~1) >> 1) and 1 / (cx^2 + cy^2).
uniform ivec2 uCenter;
uniform float uInverseMaxRadius2;
uniform float uCorner[3];
uniform float uLowerScale;
uniform float uUpperScale;
layout(location = 0) out vec4 oColor;
int luma(ivec2 p) { return texelFetch(uLuma, p + ivec2(GUIDED_PADDING), 0).r; }
int level1(ivec2 p) { return texelFetch(uLevel1, p + ivec2(LEVEL1_PADDING), 0).r; }
int level2(ivec2 p) { return texelFetch(uLevel2, p + ivec2(LEVEL2_PADDING), 0).r; }
int column(ivec2 p) {
return rhadd(hadd(level2(p - ivec2(0, 4)), level2(p + ivec2(0, 4))), level2(p));
vec3 lowColor(int x, int y) {
return clamp(texelFetch(uLowSource, clamp(ivec2(x, y), ivec2(0), uLowMax), 0).rgb, 0.0, 1.0);
}
// Segment by |d| (int16 abs: -32768 stays negative), slope on the signed d, mirrored intercept.
int curve(int band, int d) {
int magnitude = s16(abs(d));
int knot = band * 3;
int segment = magnitude >= uKnots[knot + 2] ? 3
: magnitude >= uKnots[knot + 1] ? 2
: magnitude >= uKnots[knot] ? 1 : 0;
int index = band * 4 + segment;
int scaled = clamp((uSlopes[index] * d) >> 8, -32768, 32767);
int intercept = d < 0 ? s16(-uIntercepts[index]) : uIntercepts[index];
return s16(scaled + intercept);
}
// FCVTZS to int32 (truncate, saturate) narrowed to int16.
int truncateS16(float value) {
if (value >= 2147483648.0) return -1;
if (value <= -2147483648.0) return 0;
return s16(int(value));
}
int bandTerm(int band, int d, float radius2) {
float gain = fenced(radius2 * uCorner[band]) + 1.0;
return truncateS16(fenced(gain * float(curve(band, d))));
}
int overshootBound(int value, float scale) {
return s16(int(clamp(float(value) * scale, -32768.0, 32767.0)));
}
// Truncating Q16 lerp with a wrapping int16 difference.
int lerp16(int a, int b, int f) { return s16(a + ((s16(b - a) * f) >> 16)); }
ivec2 lowChroma(int x, int y) {
ivec4 yuv = texelFetch(uLowYuv, clamp(ivec2(x, y), ivec2(0), uLowMax), 0);
return ivec2(yuv.g, yuv.b);
}
ivec2 chroma(ivec2 p) {
vec3 upsampled(ivec2 p) {
ivec2 tx = lowTap(p.x);
ivec2 ty = lowTap(p.y);
ivec2 c00 = lowChroma(tx.x, ty.x);
ivec2 c10 = lowChroma(tx.x + 1, ty.x);
ivec2 c01 = lowChroma(tx.x, ty.x + 1);
ivec2 c11 = lowChroma(tx.x + 1, ty.x + 1);
int u = lerp16(lerp16(c00.x, c10.x, tx.y), lerp16(c01.x, c11.x, tx.y), ty.y);
int v = lerp16(lerp16(c00.y, c10.y, tx.y), lerp16(c01.y, c11.y, tx.y), ty.y);
return ivec2(u, v);
}
// Exact binary16 value of RNE(v / 4095), the former float division followed by an RNE half
// conversion, so the attachment write does not depend on the driver's float -> half rounding.
float u12ToUnit(int v) {
if (v == 0) return 0.0;
int shift = 12 - findMSB(v);
if ((v << shift) >= 8190) shift -= 1;
int numerator = v << (shift + 10);
int quotient = numerator / 4095;
if (2 * (numerator - quotient * 4095) > 4095) quotient += 1;
return float(quotient) * uintBitsToFloat(uint(117 - shift) << 23);
float fx = tapFraction(tx.y);
vec3 top = mix(lowColor(tx.x, ty.x), lowColor(tx.x + 1, ty.x), fx);
vec3 bottom = mix(lowColor(tx.x, ty.x + 1), lowColor(tx.x + 1, ty.x + 1), fx);
return mix(top, bottom, tapFraction(ty.y));
}
void main() {
ivec2 p = ivec2(gl_FragCoord.xy);
int y0 = luma(p);
int y1 = level1(p);
int y2 = level2(p);
int y3 = hadd(rhadd(column(p - ivec2(4, 0)), column(p + ivec2(4, 0))), column(p));
float dx = float(p.x - uCenter.x);
float dy = float(p.y - uCenter.y);
float radius2 = fenced(fenced(dy * dy) + fenced(dx * dx)) * uInverseMaxRadius2;
int sharp = s16(y3 + bandTerm(0, s16(y0 - y1), radius2)
+ bandTerm(1, s16(y1 - y2), radius2) + bandTerm(2, s16(y2 - y3), radius2));
int lowest = y0;
int highest = y0;
for (int j = -2; j <= 2; ++j) {
for (int i = -2; i <= 2; ++i) {
int neighbour = luma(p + ivec2(i, j));
lowest = min(lowest, neighbour);
highest = max(highest, neighbour);
}
}
sharp = max(overshootBound(lowest, uLowerScale),
min(overshootBound(highest, uUpperScale), sharp));
sharp = clamp(sharp, 0, 4095);
ivec2 uv = chroma(p);
int u = uv.x;
int v = uv.y;
int red = clamp(sharp + ((3225 * v + 2048) >> 12), 0, 4095);
int green = clamp(sharp + ((-959 * v + -541 * u + 2048) >> 12), 0, 4095);
int blue = clamp(sharp + ((5360 * u + 2048) >> 12), 0, 4095);
oColor = vec4(u12ToUnit(red), u12ToUnit(green), u12ToUnit(blue), 1.0);
vec3 rgb = upsampled(p);
oColor = vec4(clamp(rgb + (sharpenedLuma(p) - dot(rgb, ENCODED_LUMA)), 0.0, 1.0), 1.0);
}
""".trimIndent()
val guideShader = join(header, integerOps, floatOps, bitOps, linearOps, guide)
val lowGuideShader = join(header, integerOps, floatOps, bitOps, linearOps, boxOps, lowGuide)
val lowColorShader = join(header, integerOps, floatOps, bitOps, linearOps, boxOps, lowColor)
val lowYuvShader = join(header, floatOps, lowYuv)
val cellFitShader = join(header, floatOps, bitOps, cellFit)
val horizontalShader = join(header, integerOps, floatOps, bitOps, gridOps, horizontal)
val guidedYShader = join(header, integerOps, floatOps, bitOps, gridOps, guidedY)
val level1Shader = join(header, integerOps, level1)
val level2Shader = join(header, integerOps, level2)
val outputShader = join(header, integerOps, floatOps, gridOps, output)
val guideShader = join(header, linearOps, guide)
val lowShader = join(header, linearOps, low)
val cellFitShader = join(header, GlesMgcSharpenShaders.encodedLuma, cellFit)
val horizontalShader = join(header, padding, gridOps, horizontal)
val guidedYShader = join(header, padding, gridOps, guidedY)
val level1Shader = GlesMgcSharpenShaders.levelShader(join(padding, guidedLumaSource), 1,
GlesMgcSharpenShaders.LEVEL1_PADDING)
val level2Shader = GlesMgcSharpenShaders.levelShader(GlesMgcSharpenShaders.level1Source, 2,
GlesMgcSharpenShaders.LEVEL2_PADDING)
val outputShader = join(header, padding, gridOps, GlesMgcSharpenShaders.encodedLuma, guidedLuma,
GlesMgcSharpenShaders.kernel, output)
private fun join(vararg parts: String) = parts.joinToString("\n\n")
private fun join(vararg parts: String) = GlesMgcSharpenShaders.join(*parts)
}
@@ -25,7 +25,7 @@ internal class GlesMgcSharpen {
fun render(source: Int, target: Int, width: Int, height: Int, curves: FloatArray, attenuation: Float) {
require(width > 0 && height > 0 && source != 0 && target != 0)
require(attenuation.isFinite() && attenuation >= 0f)
val uniforms = KernelUniforms(curves, width, height, attenuation)
val uniforms = KernelUniforms(curves, attenuation)
ensurePrograms()
ensurePlanes(width, height)
GLES30.glBindFramebuffer(GLES30.GL_FRAMEBUFFER, outputFramebuffer)
@@ -39,7 +39,6 @@ internal class GlesMgcSharpen {
begin(lumaProgram, lumaFramebuffer, width, height)
bindTexture(lumaProgram, "uSource", 0, source)
GLES30.glUniform1ui(GLES30.glGetUniformLocation(lumaProgram, "uFloatFence"), 0)
quad.draw(lumaProgram)
begin(level1Program, level1Framebuffer, width + 2 * level1Padding, height + 2 * level1Padding)
@@ -57,18 +56,8 @@ internal class GlesMgcSharpen {
bindTexture(program, "uLuma", 1, lumaTexture)
bindTexture(program, "uLevel1", 2, level1Texture)
bindTexture(program, "uLevel2", 3, level2Texture)
fun location(name: String) = GLES30.glGetUniformLocation(program, name)
GLES30.glUniform2i(location("uImageMax"), width - 1, height - 1)
GLES30.glUniform1ui(location("uFloatFence"), 0)
GLES30.glUniform1iv(location("uKnots"), uniforms.knots.size, uniforms.knots, 0)
GLES30.glUniform1iv(location("uSlopes"), uniforms.slopes.size, uniforms.slopes, 0)
GLES30.glUniform1iv(location("uIntercepts"), uniforms.intercepts.size, uniforms.intercepts, 0)
GLES30.glUniform1i(location("uRadialValid"), if (uniforms.radialValid) 1 else 0)
GLES30.glUniform2i(location("uCenter"), width shr 1, height shr 1)
GLES30.glUniform1f(location("uInverseMaxRadius2"), uniforms.inverseMaxRadius2)
GLES30.glUniform1fv(location("uCorner"), 3, RELATIVE_CORNER_ACUTANCE_CORRECTION, 0)
GLES30.glUniform1f(location("uLowerScale"), uniforms.lowerScale)
GLES30.glUniform1f(location("uUpperScale"), uniforms.upperScale)
GLES30.glUniform2i(GLES30.glGetUniformLocation(program, "uImageMax"), width - 1, height - 1)
uniforms.bind(program)
quad.draw(program)
GLES30.glFramebufferTexture2D(GLES30.GL_FRAMEBUFFER, GLES30.GL_COLOR_ATTACHMENT0,
@@ -117,10 +106,10 @@ internal class GlesMgcSharpen {
try {
val level1Padding = 2 * GlesMgcSharpenShaders.LEVEL1_PADDING
val level2Padding = 2 * GlesMgcSharpenShaders.LEVEL2_PADDING
lumaTexture = MgcGlesSurfaces.texture(GLES30.GL_R16I, width, height, "MGC sharpen luma")
level1Texture = MgcGlesSurfaces.texture(GLES30.GL_R16I, width + level1Padding,
lumaTexture = MgcGlesSurfaces.texture(GLES30.GL_R32F, width, height, "MGC sharpen luma")
level1Texture = MgcGlesSurfaces.texture(GLES30.GL_R32F, width + level1Padding,
height + level1Padding, "MGC sharpen level1")
level2Texture = MgcGlesSurfaces.texture(GLES30.GL_R16I, width + level2Padding,
level2Texture = MgcGlesSurfaces.texture(GLES30.GL_R32F, width + level2Padding,
height + level2Padding, "MGC sharpen level2")
lumaFramebuffer = MgcGlesSurfaces.framebuffer("MGC sharpen luma", lumaTexture)
level1Framebuffer = MgcGlesSurfaces.framebuffer("MGC sharpen level1", level1Texture)
@@ -155,55 +144,42 @@ internal class GlesMgcSharpen {
}
/**
* The AOT entry's curve preparation, in the same unfused binary32 order (JVM Float arithmetic
* is never contracted): knots and y values become int16 U12 codes, then each of the four
* segments gets a Q8 slope and an intercept. Curves use [MgcSharpenCurveBuilder]'s
* [point, frequency, coordinate] layout. The corner term is normalised over
* [cornerWidth] x [cornerHeight]: the image for SharpenTo16Bit, the two-row padded output for
* GuidedUpsample.
* The band curves and overshoot scales of the kernel. Curves use [MgcSharpenCurveBuilder]'s
* [point, frequency, coordinate] layout on the encoded [0, 1] scale: per band five strictly
* increasing knots and their responses. Each of the four segments becomes its start knot,
* the response there and its slope.
*/
class KernelUniforms(curves: FloatArray, cornerWidth: Int, cornerHeight: Int, attenuation: Float) {
val knots = IntArray(9)
val slopes = IntArray(12)
val intercepts = IntArray(12)
val radialValid: Boolean
val inverseMaxRadius2: Float
val lowerScale = 1f - attenuation
val upperScale = attenuation + 1f
class KernelUniforms(curves: FloatArray, attenuation: Float) {
private val knots = FloatArray(12)
private val values = FloatArray(12)
private val slopes = FloatArray(12)
private val lowerScale = 1f - attenuation
private val upperScale = 1f + attenuation
init {
require(curves.size == 30)
for (band in 0..2) {
val knot = IntArray(5) { toS16(curves[5 * band + it] * 4095f) }
val y = IntArray(5) { toS16(curves[15 + 5 * band + it] * 4095f) }
for (i in 1..3) knots[band * 3 + i - 1] = knot[i]
for (k in 0..3) {
val dx = (knot[k + 1] - knot[k]).toShort().toInt().coerceAtLeast(1)
val dy = (y[k + 1] - y[k]).toShort().toInt()
val slope = dy.toFloat() / dx.toFloat()
val slopeX0 = slope * knot[k].toFloat()
val slopeQ8 = slope * 256f
val intercept = y[k].toFloat() - slopeX0
slopes[band * 4 + k] = toS16(slopeQ8)
intercepts[band * 4 + k] = toS16(intercept)
val x0 = curves[5 * band + k]
val x1 = curves[5 * band + k + 1]
val y0 = curves[15 + 5 * band + k]
val y1 = curves[15 + 5 * band + k + 1]
require(x1 > x0) { "Sharpen knots must increase: band=$band segment=$k" }
knots[band * 4 + k] = x0
values[band * 4 + k] = y0
slopes[band * 4 + k] = (y1 - y0) / (x1 - x0)
}
}
val halfWidth = cornerWidth shr 1
val halfHeight = cornerHeight shr 1
val maxRadius2 = (halfWidth * halfWidth).toFloat() + (halfHeight * halfHeight).toFloat()
radialValid = maxRadius2 > 0f
inverseMaxRadius2 = if (radialValid) 1f / maxRadius2 else 0f
}
// Round half to even, clamp to int16 (NaN -> 0), truncate.
private fun toS16(value: Float): Int {
if (value.isNaN()) return 0
return Math.rint(value.toDouble()).toFloat().coerceIn(-32768f, 32767f).toInt().toShort().toInt()
/** Sets the [GlesMgcSharpenShaders.kernel] uniforms of the current [program]. */
fun bind(program: Int) {
fun location(name: String) = GLES30.glGetUniformLocation(program, name)
GLES30.glUniform1fv(location("uKnots"), knots.size, knots, 0)
GLES30.glUniform1fv(location("uValues"), values.size, values, 0)
GLES30.glUniform1fv(location("uSlopes"), slopes.size, slopes, 0)
GLES30.glUniform1f(location("uLowerScale"), lowerScale)
GLES30.glUniform1f(location("uUpperScale"), upperScale)
}
}
private companion object {
// FinishRaw's relative corner acutance correction; the original call site passes zeros.
val RELATIVE_CORNER_ACUTANCE_CORRECTION = floatArrayOf(0f, 0f, 0f)
}
}
@@ -1,216 +1,163 @@
package com.hinnka.mycamera.raw
/**
* Bit-exact GLES translation of MGC 9.6.080 V24 `gcam::SharpenTo16BitHalide` (libgcastartup.so
* entry 0x4B77000) together with the former CPU adapters around it: RGBA16F encoded RGB -> U12
* YUV before the kernel and U12 RGB -> RGBA16F after it. The independent reference, the algorithm
* notes and the oracle that checks these shaders against the original AOT live in tools/mgc_sharpen.
* GLES implementation of MGC 9.6.080 V24 `gcam::SharpenTo16Bit` (libgcastartup.so entry
* 0x4B77000) together with the former CPU adapters around it. The algorithm notes live in
* tools/mgc_sharpen. Everything runs in binary32 on the encoded [0, 1] scale; the original's U12
* quantisation, NEON halving adds and int16 wraparound are not reproduced.
*
* The kernel sharpens Y only, on an undecimated binomial pyramid with dilations 1, 2 and 4:
* The kernel sharpens luma only, on an undecimated binomial pyramid with dilations 1, 2 and 4:
*
* 1. `luma`: encoded RGB -> U12 Y (R16I, image size).
* 1. `luma`: encoded RGB -> Y (R32F, image size).
* 2. `level1`: L1 = blur(clamped Y, 1), stored over the image grown by [LEVEL1_PADDING] per side.
* 3. `level2`: L2 = blur(L1, 2), stored over the image grown by [LEVEL2_PADDING] per side.
* 4. `output`: L3 = blur(L2, 4), band curves, corner gain, 5x5 overshoot clamp and Q12 YUV -> RGB.
* 4. `output`: L3 = blur(L2, 4), band curves, 5x5 overshoot clamp, and the luma change added to
* every channel, which is the original's Y -> RGB with the chroma of the source.
*
* Only Y is clamped at the image border (repeat edge); L1 and L2 outside the image are their
* natural extension, which is why they keep a halo instead of being clamped.
*
* [GlesMgcGuidedUpsampleShaders] runs the same pyramid and [kernel] on its guided luma.
*/
internal object GlesMgcSharpenShaders {
const val LEVEL1_PADDING = 6
const val LEVEL2_PADDING = 4
private val header = """
val header = """
#version 300 es
precision highp float;
precision highp int;
precision highp sampler2D;
precision highp isampler2D;
precision highp usampler2D;
""".trimIndent()
private val integerOps = """
const int LEVEL1_PADDING = $LEVEL1_PADDING;
const int LEVEL2_PADDING = $LEVEL2_PADDING;
int s16(int v) { return (v << 16) >> 16; }
// SHADD / SRHADD .8h; inputs are int16 so the halved sums never wrap.
int hadd(int a, int b) { return (a + b) >> 1; }
int rhadd(int a, int b) { return (a + b + 1) >> 1; }
/** BT.709 luma of the encoded RGB, the Y row of FinishRaw's YUV matrix. */
val encodedLuma = """
const vec3 ENCODED_LUMA = vec3(0.2126, 0.7152, 0.0722);
""".trimIndent()
// GLSL ES has no `precise`. XOR with a zero uniform forces each product to be rounded to binary32
// before it is added, as the original's separate FMUL/FADD do.
private val floatOps = """
uniform uint uFloatFence;
/**
* Pyramid level: binomial [1, 2, 1] / 4 per axis at [dilation], drawn over the image grown by
* [padding] per side. [source] declares `float source(ivec2 p)` in image coordinates.
*/
fun levelShader(source: String, dilation: Int, padding: Int) = join(header, source, """
layout(location = 0) out float oLevel;
float fenced(float value) { return uintBitsToFloat(floatBitsToUint(value) ^ uFloatFence); }
float unitToU12(float value) { return fenced(clamp(value, 0.0, 1.0) * 4095.0); }
// One row of the FinishRaw U12 matrix, rounded half to even and clamped to +-4095.
int u12Row(float r, float g, float b, float m0, float m1, float m2) {
float partial = fenced(fenced(r * m0) + fenced(g * m1));
return clamp(int(roundEven(partial + fenced(b * m2))), -4095, 4095);
float column(ivec2 p) {
return 0.25 * (source(p - ivec2(0, $dilation)) + source(p + ivec2(0, $dilation))) + 0.5 * source(p);
}
void main() {
ivec2 p = ivec2(gl_FragCoord.xy) - ivec2($padding);
oLevel = 0.25 * (column(p - ivec2($dilation, 0)) + column(p + ivec2($dilation, 0))) + 0.5 * column(p);
}
""".trimIndent())
/** Lookup of a level 1 plane drawn by [levelShader] with [LEVEL1_PADDING]. */
val level1Source = """
uniform highp sampler2D uLevel1;
float source(ivec2 p) { return texelFetch(uLevel1, p + ivec2($LEVEL1_PADDING), 0).r; }
""".trimIndent()
/**
* `float sharpenedLuma(ivec2 p)`: band curves on y0 - L1, L1 - L2 and L2 - L3 added to L3, then
* limited to the 5x5 neighbourhood of y0 widened by the overshoot scales and to [0, 1]. The
* includer declares `float luma(ivec2 p)`.
*/
val kernel = """
uniform highp sampler2D uLevel1;
uniform highp sampler2D uLevel2;
// Per band, segments 0..3: start knot, response at the knot and slope.
uniform float uKnots[12];
uniform float uValues[12];
uniform float uSlopes[12];
uniform float uLowerScale;
uniform float uUpperScale;
float level1(ivec2 p) { return texelFetch(uLevel1, p + ivec2($LEVEL1_PADDING), 0).r; }
float level2(ivec2 p) { return texelFetch(uLevel2, p + ivec2($LEVEL2_PADDING), 0).r; }
float level2Column(ivec2 p) {
return 0.25 * (level2(p - ivec2(0, 4)) + level2(p + ivec2(0, 4))) + 0.5 * level2(p);
}
float level3(ivec2 p) {
return 0.25 * (level2Column(p - ivec2(4, 0)) + level2Column(p + ivec2(4, 0)))
+ 0.5 * level2Column(p);
}
// Odd, piecewise linear response through the curve points; the last segment extrapolates.
float bandResponse(int band, float d) {
float magnitude = abs(d);
int first = band * 4;
int segment = magnitude >= uKnots[first + 3] ? 3
: magnitude >= uKnots[first + 2] ? 2
: magnitude >= uKnots[first + 1] ? 1 : 0;
int index = first + segment;
return sign(d) * (uValues[index] + uSlopes[index] * (magnitude - uKnots[index]));
}
float sharpenedLuma(ivec2 p) {
float y0 = luma(p);
float y1 = level1(p);
float y2 = level2(p);
float y3 = level3(p);
float sharp = y3 + bandResponse(0, y0 - y1) + bandResponse(1, y1 - y2)
+ bandResponse(2, y2 - y3);
float lowest = y0;
float highest = y0;
for (int j = -2; j <= 2; ++j) {
for (int i = -2; i <= 2; ++i) {
float neighbour = luma(p + ivec2(i, j));
lowest = min(lowest, neighbour);
highest = max(highest, neighbour);
}
}
sharp = max(lowest * uLowerScale, min(highest * uUpperScale, sharp));
return clamp(sharp, 0.0, 1.0);
}
""".trimIndent()
private val clampedLuma = """
uniform highp sampler2D uLuma;
uniform ivec2 uImageMax;
float luma(ivec2 p) { return texelFetch(uLuma, clamp(p, ivec2(0), uImageMax), 0).r; }
""".trimIndent()
private val clampedLumaSource = """
$clampedLuma
float source(ivec2 p) { return luma(p); }
""".trimIndent()
private val luma = """
uniform highp sampler2D uSource;
layout(location = 0) out int oLuma;
layout(location = 0) out float oLuma;
void main() {
vec4 color = texelFetch(uSource, ivec2(gl_FragCoord.xy), 0);
oLuma = u12Row(unitToU12(color.r), unitToU12(color.g), unitToU12(color.b),
0.2125999927520752, 0.7152000069618225, 0.07219959795475006);
}
""".trimIndent()
private val level1 = """
uniform highp isampler2D uLuma;
uniform ivec2 uImageMax;
layout(location = 0) out int oLevel;
int luma(ivec2 p) { return texelFetch(uLuma, clamp(p, ivec2(0), uImageMax), 0).r; }
int column(ivec2 p) {
return rhadd(hadd(luma(p - ivec2(0, 1)), luma(p + ivec2(0, 1))), luma(p));
}
void main() {
ivec2 p = ivec2(gl_FragCoord.xy) - ivec2(LEVEL1_PADDING);
oLevel = hadd(rhadd(column(p - ivec2(1, 0)), column(p + ivec2(1, 0))), column(p));
}
""".trimIndent()
private val level2 = """
uniform highp isampler2D uLevel1;
layout(location = 0) out int oLevel;
int level1(ivec2 p) { return texelFetch(uLevel1, p + ivec2(LEVEL1_PADDING), 0).r; }
int column(ivec2 p) {
return rhadd(hadd(level1(p - ivec2(0, 2)), level1(p + ivec2(0, 2))), level1(p));
}
void main() {
ivec2 p = ivec2(gl_FragCoord.xy) - ivec2(LEVEL2_PADDING);
oLevel = hadd(rhadd(column(p - ivec2(2, 0)), column(p + ivec2(2, 0))), column(p));
vec3 rgb = clamp(texelFetch(uSource, ivec2(gl_FragCoord.xy), 0).rgb, 0.0, 1.0);
oLuma = dot(rgb, ENCODED_LUMA);
}
""".trimIndent()
private val output = """
uniform highp sampler2D uSource;
uniform highp isampler2D uLuma;
uniform highp isampler2D uLevel1;
uniform highp isampler2D uLevel2;
uniform ivec2 uImageMax;
// Per band: knots 1..3 (U12), then four segment slopes (Q8) and intercepts (U12).
uniform int uKnots[9];
uniform int uSlopes[12];
uniform int uIntercepts[12];
// 0 for a 1x1 image, whose radial term is NaN in the original and zeroes every band.
uniform int uRadialValid;
uniform ivec2 uCenter;
uniform float uInverseMaxRadius2;
uniform float uCorner[3];
uniform float uLowerScale;
uniform float uUpperScale;
layout(location = 0) out vec4 oColor;
int luma(ivec2 p) { return texelFetch(uLuma, clamp(p, ivec2(0), uImageMax), 0).r; }
int level1(ivec2 p) { return texelFetch(uLevel1, p + ivec2(LEVEL1_PADDING), 0).r; }
int level2(ivec2 p) { return texelFetch(uLevel2, p + ivec2(LEVEL2_PADDING), 0).r; }
int column(ivec2 p) {
return rhadd(hadd(level2(p - ivec2(0, 4)), level2(p + ivec2(0, 4))), level2(p));
}
// Segment by |d| (int16 abs: -32768 stays negative), slope on the signed d, mirrored intercept.
int curve(int band, int d) {
int magnitude = s16(abs(d));
int knot = band * 3;
int segment = magnitude >= uKnots[knot + 2] ? 3
: magnitude >= uKnots[knot + 1] ? 2
: magnitude >= uKnots[knot] ? 1 : 0;
int index = band * 4 + segment;
int scaled = clamp((uSlopes[index] * d) >> 8, -32768, 32767);
int intercept = d < 0 ? s16(-uIntercepts[index]) : uIntercepts[index];
return s16(scaled + intercept);
}
// FCVTZS to int32 (truncate, saturate) narrowed to int16.
int truncateS16(float value) {
if (value >= 2147483648.0) return -1;
if (value <= -2147483648.0) return 0;
return s16(int(value));
}
int bandTerm(int band, int d, float radius2) {
int shaped = curve(band, d);
if (uRadialValid == 0) return 0;
float gain = fenced(radius2 * uCorner[band]) + 1.0;
return truncateS16(fenced(gain * float(shaped)));
}
int overshootBound(int value, float scale) {
return s16(int(clamp(float(value) * scale, -32768.0, 32767.0)));
}
// Exact binary16 value of RNE(v / 4095), the former float division followed by an RNE half
// conversion, so the attachment write does not depend on the driver's float -> half rounding.
float u12ToUnit(int v) {
if (v == 0) return 0.0;
int shift = 12 - findMSB(v);
if ((v << shift) >= 8190) shift -= 1;
int numerator = v << (shift + 10);
int quotient = numerator / 4095;
if (2 * (numerator - quotient * 4095) > 4095) quotient += 1;
return float(quotient) * uintBitsToFloat(uint(117 - shift) << 23);
}
void main() {
ivec2 p = ivec2(gl_FragCoord.xy);
int y0 = texelFetch(uLuma, p, 0).r;
int y1 = level1(p);
int y2 = level2(p);
int y3 = hadd(rhadd(column(p - ivec2(4, 0)), column(p + ivec2(4, 0))), column(p));
float dx = float(p.x - uCenter.x);
float dy = float(p.y - uCenter.y);
float radius2 = fenced(fenced(dy * dy) + fenced(dx * dx)) * uInverseMaxRadius2;
int sharp = s16(y3 + bandTerm(0, s16(y0 - y1), radius2)
+ bandTerm(1, s16(y1 - y2), radius2) + bandTerm(2, s16(y2 - y3), radius2));
int lowest = y0;
int highest = y0;
for (int j = -2; j <= 2; ++j) {
for (int i = -2; i <= 2; ++i) {
int neighbour = luma(p + ivec2(i, j));
lowest = min(lowest, neighbour);
highest = max(highest, neighbour);
}
}
sharp = max(overshootBound(lowest, uLowerScale),
min(overshootBound(highest, uUpperScale), sharp));
sharp = clamp(sharp, 0, 4095);
vec4 color = texelFetch(uSource, p, 0);
float r = unitToU12(color.r);
float g = unitToU12(color.g);
float b = unitToU12(color.b);
int u = u12Row(r, g, b, -0.16245023906230927, -0.5464943051338196, 0.7089447379112244);
int v = u12Row(r, g, b, 0.9999967217445374, -0.9083024859428406, -0.09169333428144455);
int red = clamp(sharp + ((3225 * v + 2048) >> 12), 0, 4095);
int green = clamp(sharp + ((-959 * v + -541 * u + 2048) >> 12), 0, 4095);
int blue = clamp(sharp + ((5360 * u + 2048) >> 12), 0, 4095);
oColor = vec4(u12ToUnit(red), u12ToUnit(green), u12ToUnit(blue), 1.0);
vec3 rgb = clamp(texelFetch(uSource, p, 0).rgb, 0.0, 1.0);
oColor = vec4(clamp(rgb + (sharpenedLuma(p) - luma(p)), 0.0, 1.0), 1.0);
}
""".trimIndent()
val lumaShader = join(header, floatOps, luma)
val level1Shader = join(header, integerOps, level1)
val level2Shader = join(header, integerOps, level2)
val outputShader = join(header, integerOps, floatOps, output)
val lumaShader = join(header, encodedLuma, luma)
val level1Shader = levelShader(clampedLumaSource, 1, LEVEL1_PADDING)
val level2Shader = levelShader(level1Source, 2, LEVEL2_PADDING)
val outputShader = join(header, clampedLuma, kernel, output)
private fun join(vararg parts: String) = parts.joinToString("\n\n")
fun join(vararg parts: String) = parts.joinToString("\n\n")
}
@@ -1,9 +1,6 @@
package com.hinnka.mycamera.raw
import android.opengl.GLES30
import java.nio.ByteBuffer
import java.nio.ByteOrder
import kotlin.math.sqrt
/**
* MGC V25 guided finish on the GPU ([GlesMgcGuidedUpsampleShaders]).
@@ -32,7 +29,6 @@ internal class MgcGuidedUpsample {
val globalHeight get() = lowHeight shl log2Scale
private val quad = RawFullscreenQuad()
private val programs = HashMap<String, Int>()
private var sqrtLutTexture = 0
fun prepare(texture: Int, width: Int, height: Int, gains: FloatArray,
resolution: MgcFinishResolution) {
@@ -45,7 +41,7 @@ internal class MgcGuidedUpsample {
paddedHeight = (height + 15) and -16
lowWidth = paddedWidth shr log2Scale
lowHeight = paddedHeight shr log2Scale
val framebuffers = IntArray(3)
val framebuffers = IntArray(2)
try {
guideTexture = MgcGlesSurfaces.texture(GLES30.GL_R16I, paddedWidth, paddedHeight, "MGC guide")
lowGuideTexture = MgcGlesSurfaces.texture(GLES30.GL_R16I, lowWidth, lowHeight, "MGC low guide")
@@ -54,21 +50,17 @@ internal class MgcGuidedUpsample {
profileTexture = MgcGlesSurfaces.texture(GLES30.GL_RGBA16F, lowWidth, lowHeight,
"MGC low profile", GLES30.GL_LINEAR)
profileFramebuffer = MgcGlesSurfaces.framebuffer("MGC low profile", profileTexture)
val lut = sqrtLut()
val sourceSetup: (Int) -> Unit = { program ->
bindTexture(program, "uSource", 0, texture)
bindTexture(program, "uSqrtLut", 1, lut)
GLES30.glUniform2i(location(program, "uSourceMax"), width - 1, height - 1)
GLES30.glUniform1fv(location(program, "uWhiteBalance"), 3, whiteBalance, 0)
GLES30.glUniform1ui(location(program, "uFloatFence"), 0)
GLES30.glUniform3fv(location(program, "uWhiteBalance"), 1, whiteBalance, 0)
GLES30.glUniform1i(location(program, "uLog2Scale"), log2Scale)
}
framebuffers[0] = MgcGlesSurfaces.framebuffer("MGC guide", guideTexture)
draw("guide", framebuffers[0], paddedWidth, paddedHeight, sourceSetup)
framebuffers[1] = MgcGlesSurfaces.framebuffer("MGC low guide", lowGuideTexture)
draw("lowGuide", framebuffers[1], lowWidth, lowHeight, sourceSetup)
framebuffers[2] = MgcGlesSurfaces.framebuffer("MGC low colour", cameraTexture)
draw("lowColor", framebuffers[2], lowWidth, lowHeight, sourceSetup)
framebuffers[1] = MgcGlesSurfaces.framebuffer("MGC low guide and colour", lowGuideTexture,
cameraTexture)
draw("low", framebuffers[1], lowWidth, lowHeight, sourceSetup)
finishPasses("prepare")
} catch (error: Throwable) {
releaseBuffers()
@@ -102,8 +94,8 @@ internal class MgcGuidedUpsample {
check(isPrepared && width == fullWidth && height == fullHeight)
require(attenuation.isFinite() && attenuation >= 0f && source != 0 && target != 0)
val padding = GlesMgcGuidedUpsampleShaders.GUIDED_PADDING
val level1Padding = 2 * GlesMgcGuidedUpsampleShaders.LEVEL1_PADDING
val level2Padding = 2 * GlesMgcGuidedUpsampleShaders.LEVEL2_PADDING
val level1Padding = 2 * GlesMgcSharpenShaders.LEVEL1_PADDING
val level2Padding = 2 * GlesMgcSharpenShaders.LEVEL2_PADDING
val scale = 1 shl log2Scale
val cellStep = 32768 / scale
fun cellOf(x: Int) = ((2 * x + 1) * cellStep - 65536) shr 17
@@ -113,83 +105,64 @@ internal class MgcGuidedUpsample {
val cellRows = cellOf(height - 1 + padding) + 1 - cellY0 + 1
val guidedWidth = width + 2 * padding
val guidedHeight = height + 2 * padding
val paddedOutputHeight = (height + 1) and -2
val kernel = GlesMgcSharpen.KernelUniforms(curves, width, paddedOutputHeight, attenuation)
val textures = IntArray(8)
val framebuffers = IntArray(7)
val kernel = GlesMgcSharpen.KernelUniforms(curves, attenuation)
val textures = IntArray(7)
val framebuffers = IntArray(6)
try {
val lowYuv = MgcGlesSurfaces.texture(GLES30.GL_RGBA16I, lowWidth, lowHeight, "MGC low YUV")
.also { textures[0] = it }
val cell0 = MgcGlesSurfaces.texture(GLES30.GL_RGBA32UI, cellColumns, cellRows, "MGC cells 0")
.also { textures[1] = it }
.also { textures[0] = it }
val cell1 = MgcGlesSurfaces.texture(GLES30.GL_RGBA32UI, cellColumns, cellRows, "MGC cells 1")
.also { textures[2] = it }
.also { textures[1] = it }
val row0 = MgcGlesSurfaces.texture(GLES30.GL_RGBA32UI, guidedWidth, cellRows, "MGC rows 0")
.also { textures[3] = it }
.also { textures[2] = it }
val row1 = MgcGlesSurfaces.texture(GLES30.GL_RGBA32UI, guidedWidth, cellRows, "MGC rows 1")
.also { textures[3] = it }
val guided = MgcGlesSurfaces.texture(GLES30.GL_R32F, guidedWidth, guidedHeight, "MGC guided luma")
.also { textures[4] = it }
val guided = MgcGlesSurfaces.texture(GLES30.GL_R16I, guidedWidth, guidedHeight, "MGC guided luma")
.also { textures[5] = it }
val level1 = MgcGlesSurfaces.texture(GLES30.GL_R16I, width + level1Padding,
height + level1Padding, "MGC guided level1").also { textures[6] = it }
val level2 = MgcGlesSurfaces.texture(GLES30.GL_R16I, width + level2Padding,
height + level2Padding, "MGC guided level2").also { textures[7] = it }
framebuffers[0] = MgcGlesSurfaces.framebuffer("MGC low YUV", lowYuv)
draw("lowYuv", framebuffers[0], lowWidth, lowHeight) { program ->
bindTexture(program, "uSource", 0, source)
GLES30.glUniform1ui(location(program, "uFloatFence"), 0)
}
framebuffers[1] = MgcGlesSurfaces.framebuffer("MGC cells", cell0, cell1)
draw("cellFit", framebuffers[1], cellColumns, cellRows) { program ->
val level1 = MgcGlesSurfaces.texture(GLES30.GL_R32F, width + level1Padding,
height + level1Padding, "MGC guided level1").also { textures[5] = it }
val level2 = MgcGlesSurfaces.texture(GLES30.GL_R32F, width + level2Padding,
height + level2Padding, "MGC guided level2").also { textures[6] = it }
framebuffers[0] = MgcGlesSurfaces.framebuffer("MGC cells", cell0, cell1)
draw("cellFit", framebuffers[0], cellColumns, cellRows) { program ->
bindTexture(program, "uLowGuide", 0, lowGuideTexture)
bindTexture(program, "uLowYuv", 1, lowYuv)
bindTexture(program, "uLowSource", 1, source)
GLES30.glUniform2i(location(program, "uLowMax"), lowWidth - 1, lowHeight - 1)
GLES30.glUniform2i(location(program, "uCellOrigin"), cellX0, cellY0)
GLES30.glUniform1ui(location(program, "uFloatFence"), 0)
}
framebuffers[2] = MgcGlesSurfaces.framebuffer("MGC rows", row0, row1)
draw("horizontal", framebuffers[2], guidedWidth, cellRows) { program ->
framebuffers[1] = MgcGlesSurfaces.framebuffer("MGC rows", row0, row1)
draw("horizontal", framebuffers[1], guidedWidth, cellRows) { program ->
bindTexture(program, "uCell0", 0, cell0)
bindTexture(program, "uCell1", 1, cell1)
GLES30.glUniform2i(location(program, "uCellOrigin"), cellX0, cellY0)
GLES30.glUniform1i(location(program, "uCellStep"), cellStep)
GLES30.glUniform1ui(location(program, "uFloatFence"), 0)
}
framebuffers[3] = MgcGlesSurfaces.framebuffer("MGC guided luma", guided)
draw("guidedY", framebuffers[3], guidedWidth, guidedHeight) { program ->
framebuffers[2] = MgcGlesSurfaces.framebuffer("MGC guided luma", guided)
draw("guidedY", framebuffers[2], guidedWidth, guidedHeight) { program ->
bindTexture(program, "uRow0", 0, row0)
bindTexture(program, "uRow1", 1, row1)
bindTexture(program, "uGuide", 2, guideTexture)
GLES30.glUniform2i(location(program, "uGuideMax"), paddedWidth - 1, paddedHeight - 1)
GLES30.glUniform1i(location(program, "uCellOriginY"), cellY0)
GLES30.glUniform1i(location(program, "uCellStep"), cellStep)
GLES30.glUniform1ui(location(program, "uFloatFence"), 0)
}
framebuffers[4] = MgcGlesSurfaces.framebuffer("MGC guided level1", level1)
draw("level1", framebuffers[4], width + level1Padding, height + level1Padding) { program ->
framebuffers[3] = MgcGlesSurfaces.framebuffer("MGC guided level1", level1)
draw("level1", framebuffers[3], width + level1Padding, height + level1Padding) { program ->
bindTexture(program, "uLuma", 0, guided)
}
framebuffers[5] = MgcGlesSurfaces.framebuffer("MGC guided level2", level2)
draw("level2", framebuffers[5], width + level2Padding, height + level2Padding) { program ->
framebuffers[4] = MgcGlesSurfaces.framebuffer("MGC guided level2", level2)
draw("level2", framebuffers[4], width + level2Padding, height + level2Padding) { program ->
bindTexture(program, "uLevel1", 0, level1)
}
framebuffers[6] = MgcGlesSurfaces.framebuffer("MGC guided output", target)
draw("output", framebuffers[6], width, height) { program ->
framebuffers[5] = MgcGlesSurfaces.framebuffer("MGC guided output", target)
draw("output", framebuffers[5], width, height) { program ->
bindTexture(program, "uLuma", 0, guided)
bindTexture(program, "uLevel1", 1, level1)
bindTexture(program, "uLevel2", 2, level2)
bindTexture(program, "uLowYuv", 3, lowYuv)
bindTexture(program, "uLowSource", 3, source)
GLES30.glUniform2i(location(program, "uLowMax"), lowWidth - 1, lowHeight - 1)
GLES30.glUniform1i(location(program, "uCellStep"), cellStep)
GLES30.glUniform1iv(location(program, "uKnots"), kernel.knots.size, kernel.knots, 0)
GLES30.glUniform1iv(location(program, "uSlopes"), kernel.slopes.size, kernel.slopes, 0)
GLES30.glUniform1iv(location(program, "uIntercepts"), kernel.intercepts.size, kernel.intercepts, 0)
GLES30.glUniform2i(location(program, "uCenter"), width shr 1, paddedOutputHeight shr 1)
GLES30.glUniform1f(location(program, "uInverseMaxRadius2"), kernel.inverseMaxRadius2)
GLES30.glUniform1fv(location(program, "uCorner"), 3, RELATIVE_CORNER_ACUTANCE_CORRECTION, 0)
GLES30.glUniform1f(location(program, "uLowerScale"), kernel.lowerScale)
GLES30.glUniform1f(location(program, "uUpperScale"), kernel.upperScale)
GLES30.glUniform1ui(location(program, "uFloatFence"), 0)
kernel.bind(program)
}
finishPasses("render")
} finally {
@@ -223,9 +196,7 @@ internal class MgcGuidedUpsample {
val source = with(GlesMgcGuidedUpsampleShaders) {
when (pass) {
"guide" -> guideShader
"lowGuide" -> lowGuideShader
"lowColor" -> lowColorShader
"lowYuv" -> lowYuvShader
"low" -> lowShader
"cellFit" -> cellFitShader
"horizontal" -> horizontalShader
"guidedY" -> guidedYShader
@@ -246,31 +217,8 @@ internal class MgcGuidedUpsample {
GLES30.glUniform1i(location(program, name), unit)
}
/** SqrtGuide(g) for g in [0, 32767] at texel (g and 255, g shr 8). */
private fun sqrtLut(): Int {
if (sqrtLutTexture != 0) return sqrtLutTexture
val values = ByteBuffer.allocateDirect(32768 * 2).order(ByteOrder.nativeOrder())
// JVM float sqrt is correctly rounded; for g >= 1 the AOT's `s < 1 ? rne(s)` never applies
// and g = 0 gives 0, so this equals fcvtzs(sqrt(g) * 128) of the original.
for (g in 0 until 32768) values.putShort((sqrt(g.toFloat()) * 128f).toInt().toShort())
values.position(0)
val texture = MgcGlesSurfaces.texture(GLES30.GL_R16I, 256, 128, "MGC sqrt guide LUT")
GLES30.glBindTexture(GLES30.GL_TEXTURE_2D, texture)
GLES30.glPixelStorei(GLES30.GL_UNPACK_ALIGNMENT, 2)
GLES30.glTexSubImage2D(GLES30.GL_TEXTURE_2D, 0, 0, 0, 256, 128,
GLES30.GL_RED_INTEGER, GLES30.GL_SHORT, values)
GLES30.glPixelStorei(GLES30.GL_UNPACK_ALIGNMENT, 4)
GLES30.glBindTexture(GLES30.GL_TEXTURE_2D, 0)
val error = GLES30.glGetError()
if (error != GLES30.GL_NO_ERROR) {
MgcGlesSurfaces.deleteTextures(texture)
error("MGC sqrt guide LUT upload failed: 0x${Integer.toHexString(error)}")
}
sqrtLutTexture = texture
return texture
}
/** Drops the prepared guides and low-resolution textures; programs and the LUT are kept. */
/** Drops the prepared guides and low-resolution textures; programs are kept. */
fun releaseBuffers() {
MgcGlesSurfaces.deleteFramebuffers(profileFramebuffer)
MgcGlesSurfaces.deleteTextures(cameraTexture, profileTexture, guideTexture, lowGuideTexture)
@@ -284,13 +232,9 @@ internal class MgcGuidedUpsample {
releaseBuffers()
programs.values.forEach { GLES30.glDeleteProgram(it) }
programs.clear()
MgcGlesSurfaces.deleteTextures(sqrtLutTexture)
sqrtLutTexture = 0
}
private companion object {
// FinishRaw's relative corner acutance correction; the original call site passes zeros.
val RELATIVE_CORNER_ACUTANCE_CORRECTION = floatArrayOf(0f, 0f, 0f)
val BOX_COLOR = """
#version 300 es
precision highp float;
@@ -312,8 +256,8 @@ internal class MgcGuidedUpsample {
}
/**
* The guide's linear YUV boundary applies channel gains normalized to the green mean; the
* low colour pass removes them again after YUV -> RGB.
* The guide applies channel gains normalized to the green mean before clamping; the low colour
* pass removes them again from the box means.
*/
private fun normalizedRgbWhiteBalance(gains: FloatArray): FloatArray {
fun safeGain(index: Int, fallback: Float): Float {