feat: remove old rgb chroma post processor

This commit is contained in:
zhoubinjia committed 2026-11-03 18:30:59 +08:00
1 parent 60aa79a8b8
commit 8ef38ff7bd
10 files changed
+376 -1684

No files matched your search

@@ -8,7 +8,7 @@ internal enum class GpuStackCompletionStage(val logKey: String) {
LONG_ALIGNMENT("longAlignment"),
HIGHLIGHT_ALIGNMENT("highlightAlignment"),
TILED_RECONSTRUCTION("tiledReconstruction"),
CHROMA_POSTPROCESS("chromaPostprocess"),
OUTPUT_HANDOFF("outputHandoff"),
FINAL_EXPORT("finalExport"),
}
@@ -434,7 +434,7 @@ internal class GlesMgcRawSpatialStacker(
private var spatialRgbAccumulateProgram = 0
private var spatialRgbResolveProgram = 0
private var copyRgb16ToFloatProgram = 0
private var rgbChromaPostprocessor: GlesMgcSpatialRgbChromaPostprocessor? = null
private var rgbOutputAssembler: GlesMgcSpatialRgbOutputAssembler? = null
private var supportsComputePrograms = false
private var supportsComputeReadback = false
private var maxShaderStorageBlockBytes = 0L
@@ -2256,11 +2256,11 @@ internal class GlesMgcRawSpatialStacker(
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"
val outputAssembler = checkNotNull(rgbOutputAssembler) {
"MGC Sabre VGN output assembler is not initialized"
}
chromaPostprocessor.initStorage(listOf(fullOutputTile))
val resolvedRgb = chromaPostprocessor.normalizationTargetTexture()
outputAssembler.initStorage(listOf(fullOutputTile))
val resolvedRgb = outputAssembler.normalizationTargetTexture()
val resolveStartNs = System.nanoTime()
renderSabreResolve(
accumulatedColor = accumulatedColor,
@@ -2276,7 +2276,7 @@ internal class GlesMgcRawSpatialStacker(
SABRE_TAG,
"MGC Sabre Resolve GPU submit=${elapsedMs(resolveStartNs)}ms",
)
chromaPostprocessor.markTileWritten(fullOutputTile)
outputAssembler.markTileWritten(fullOutputTile)
releaseSabreMergePhaseTextures(resolvedRgb)
if (!exportGpuLinearRgbSource) {
val outputBytes = width.toLong() * height * 3L * Short.SIZE_BYTES
@@ -2286,31 +2286,30 @@ internal class GlesMgcRawSpatialStacker(
)
}
GlesGpuScheduler.memoryBarrier()
val onChromaFinalSubmitted: (() -> Unit)? = when {
val onOutputSubmitted: (() -> Unit)? = when {
exportGpuLinearRgbSource -> {
{ completionRecorder.mark(GpuStackCompletionStage.CHROMA_POSTPROCESS) }
{ completionRecorder.mark(GpuStackCompletionStage.OUTPUT_HANDOFF) }
}
else -> null
}
val chromaResult = chromaPostprocessor.process(
outputAssembler.process(
obtainOutputBuffer = { checkNotNull(cpuOutput) },
deferFullSizeReadback = exportGpuLinearRgbSource,
onFinalSubmitted = onChromaFinalSubmitted,
)
postprocessedUi = chromaResult.exportedTextureId
onFinalSubmitted = onOutputSubmitted,
).also { postprocessedUi = it.exportedTextureId }
if (exportGpuLinearRgbSource) {
check(postprocessedUi != 0) {
"MGC Sabre VGN color noise/IIR did not export its filtered texture"
"MGC Sabre VGN output did not export its resolved texture"
}
exportedTexture = if (gpuLinearRgbStorage == GpuLinearRgbStorage.RGBA16UI) {
postprocessedUi.also { postprocessedUi = 0 }
} else {
// The chroma component leaves its final image pass behind a deferred export
// checkpoint. Complete that ownership handoff before submitting a dependent
// conversion and deleting the RGBA16UI source. This mirrors Spatial RGB and
// avoids exposing partially retired VGN work groups on affected Mali queues.
// Resolve leaves its final pass behind a deferred export checkpoint. Complete
// that ownership handoff before submitting a dependent conversion and deleting
// the RGBA16UI source. This mirrors Spatial RGB and avoids exposing partially
// retired work groups on affected Mali queues.
GlesGpuCompletion.awaitSubmittedWork(
label = "MGC Sabre VGN IIR-to-float handoff",
label = "MGC Sabre VGN RGB16-to-float handoff",
checkGlError = ::checkGlError,
)
createTexture(
@@ -2335,15 +2334,13 @@ internal class GlesMgcRawSpatialStacker(
textureSpecs.remove(exportedTexture)
}
}
checkGlError("MGC Sabre Resolve/VGN color noise")
checkGlError("MGC Sabre Resolve/VGN output")
PLog.i(
SABRE_TAG,
"MGC Sabre complete frames=${frames.size} native=${width}x$height " +
"output=${outputWidth}x$outputHeight " +
"referenceSnr=${kernelTuning.referenceSnr} " +
"result=${if (exportedTexture != 0) gpuLinearRgbStorage.name + "_GPU" else "RGB16_CPU"} " +
"colorNoiseIir=${chromaResult.chromaSubmissionMs}ms " +
"chromaFinal=${chromaResult.finalSubmissionMs}ms " +
"total=${elapsedMs(processStartNs)}ms",
)
val result = RawStackResult(
@@ -2765,7 +2762,7 @@ internal class GlesMgcRawSpatialStacker(
private fun initSabrePrograms() {
check(supportsComputePrograms) {
"MGC Sabre VGN color noise/IIR requires the GLES 3.1 compute baseline"
"MGC Sabre VGN requires the GLES 3.1 compute baseline"
}
sabreExtractBayerProgram = linkProgram(
GlesMgcRawSabreShaders.extractBayer,
@@ -2847,17 +2844,17 @@ internal class GlesMgcRawSpatialStacker(
) {
copyRgb16ToFloatProgram = linkComputeProgram(
GlesMgcRawSpatialShaders.copyRgb16ToFloat,
"mgc_sabre_chroma_to_rgba16f",
"mgc_sabre_rgb16_to_rgba16f",
)
}
// ResolveSabre and VGN stay on the native grid. A requested larger output is a separate
// display transform after FinishRaw/GuidedUpsample in RawDemosaicProcessor.
rgbChromaPostprocessor = createRgbChromaPostprocessor(
// ResolveSabre stays on the native grid. A requested larger output is a separate display
// transform after FinishRaw/GuidedUpsample in RawDemosaicProcessor.
rgbOutputAssembler = createRgbOutputAssembler(
imageWidth = width,
imageHeight = height,
exportFullSizeTexture = exportGpuLinearRgbSource ||
outputWidth != width || outputHeight != height,
).also { it.initPrograms() }
)
}
private fun initMergeUpsampleAlignment(): Int {
@@ -3017,7 +3014,7 @@ internal class GlesMgcRawSpatialStacker(
}
if (outputMode == MgcSpatialOutputMode.RGB) {
check(supportsComputePrograms) {
"MGC Spatial RGB color noise/IIR requires the GLES 3.1 compute baseline"
"MGC Spatial RGB requires the GLES 3.1 compute baseline"
}
spatialRgbConvertProgram = linkProgram(
GlesMgcGreenDemosaicShaders.convertRaw16,
@@ -3035,7 +3032,7 @@ internal class GlesMgcRawSpatialStacker(
GlesMgcSpatialRgbMergeShaders.accumulateFrame,
"mgc_spatial_v25_rgb_accumulate",
)
// Color noise/IIR owns a fixed RGBA16UI boundary, matching the VGN/Radiance
// The output assembler owns a fixed RGBA16UI boundary, matching the VGN/Radiance
// contract. The merged F16 output enters that boundary exactly once.
spatialRgbResolveProgram = linkProgram(
GlesMgcSpatialRgbMergeShaders.resolve,
@@ -3046,12 +3043,10 @@ internal class GlesMgcRawSpatialStacker(
) {
copyRgb16ToFloatProgram = linkComputeProgram(
GlesMgcRawSpatialShaders.copyRgb16ToFloat,
"mgc_spatial_rgb_chroma_to_rgba16f",
"mgc_spatial_rgb16_to_rgba16f",
)
}
rgbChromaPostprocessor = createRgbChromaPostprocessor().also {
it.initPrograms()
}
rgbOutputAssembler = createRgbOutputAssembler()
}
normalizeBayerProgram = linkProgram(
GlesMgcRawSpatialShaders.normalizeBayer,
@@ -3059,21 +3054,16 @@ internal class GlesMgcRawSpatialStacker(
)
}
private fun createRgbChromaPostprocessor(
private fun createRgbOutputAssembler(
imageWidth: Int = outputWidth,
imageHeight: Int = outputHeight,
exportFullSizeTexture: Boolean = exportGpuLinearRgbSource,
): GlesMgcSpatialRgbChromaPostprocessor {
return GlesMgcSpatialRgbChromaPostprocessor(
): GlesMgcSpatialRgbOutputAssembler {
return GlesMgcSpatialRgbOutputAssembler(
imageWidth = imageWidth,
imageHeight = imageHeight,
calculationWbGains = calculationWhiteBalance,
outputScale = 1f,
exportFullSizeTexture = exportFullSizeTexture,
backend = object : GlesMgcSpatialRgbChromaPostprocessor.Backend {
override fun linkComputeProgram(source: String, name: String): Int =
this@GlesMgcRawSpatialStacker.linkComputeProgram(source, name)
backend = object : GlesMgcSpatialRgbOutputAssembler.Backend {
override fun createRgba16UiTexture(
width: Int,
height: Int,
@@ -3094,9 +3084,6 @@ internal class GlesMgcRawSpatialStacker(
this@GlesMgcRawSpatialStacker.transferOwnedTexture(texture, label)
}
override fun uniformLocation(program: Int, name: String): Int =
this@GlesMgcRawSpatialStacker.uniformLocation(program, name)
override fun checkGlError(label: String) {
this@GlesMgcRawSpatialStacker.checkGlError(label)
}
@@ -5613,9 +5600,6 @@ internal class GlesMgcRawSpatialStacker(
GLES30.glBindFramebuffer(GLES30.GL_FRAMEBUFFER, 0)
}
private fun rgbIirWorkingSetBytes(): Long =
MgcSpatialRgbMemoryPolicy.iirWorkingSetBytes(outputWidth, outputHeight)
/**
* MGC 9.7.047 V25's Spatial RGB merge (MergeRgbRaw16F16TileSize16Halide) on the GPU, see
* [GlesMgcSpatialRgbMergeShaders]. Each burst frame's DemosaicGreenRaw16 guide feeds the same
@@ -5676,10 +5660,10 @@ internal class GlesMgcRawSpatialStacker(
"Unable to allocate MGC V25 Spatial RGB16 output",
)
}
val chromaPostprocessor = checkNotNull(rgbChromaPostprocessor) {
"MGC Spatial RGB chroma postprocessor is not initialized"
val outputAssembler = checkNotNull(rgbOutputAssembler) {
"MGC Spatial RGB output assembler is not initialized"
}
chromaPostprocessor.initStorage(listOf(fullOutputTile))
outputAssembler.initStorage(listOf(fullOutputTile))
val lensShadingTexture = createLensShadingTexture()
val mergeStartNs = System.nanoTime()
mergeSpatialRgbFrames(
@@ -5689,7 +5673,7 @@ internal class GlesMgcRawSpatialStacker(
capture = capture,
referenceBlack = referenceBlack,
lensShadingTexture = lensShadingTexture,
target = chromaPostprocessor.normalizationTargetTexture(),
target = outputAssembler.normalizationTargetTexture(),
outputExposureScale = outputExposureScale,
cameraWhite = mergeCameraWhite,
ultrashortWeight = ultrashortWeight,
@@ -5699,32 +5683,31 @@ internal class GlesMgcRawSpatialStacker(
"merge=${mergeCameraWhite.contentToString()} normalization=$outputExposureScale " +
"referenceFallbackWhiteScale=$outputExposureScale " +
"hasShort=${ultrashortWeight != 0} stage=before-rgb16")
chromaPostprocessor.markTileWritten(fullOutputTile)
outputAssembler.markTileWritten(fullOutputTile)
releaseRgbFusionPhaseTextures(
retainedTexture = chromaPostprocessor.normalizationTargetTexture(),
retainedTexture = outputAssembler.normalizationTargetTexture(),
label = "V25 merge",
)
GlesGpuScheduler.memoryBarrier()
val chromaResult = chromaPostprocessor.process(
outputAssembler.process(
obtainOutputBuffer = { checkNotNull(cpuOutput) },
deferFullSizeReadback = exportGpuLinearRgbSource,
onFinalSubmitted = if (exportGpuLinearRgbSource) {
{ completionRecorder.mark(GpuStackCompletionStage.CHROMA_POSTPROCESS) }
{ completionRecorder.mark(GpuStackCompletionStage.OUTPUT_HANDOFF) }
} else {
null
},
)
postprocessedUi = chromaResult.exportedTextureId
).also { postprocessedUi = it.exportedTextureId }
if (exportGpuLinearRgbSource) {
check(postprocessedUi != 0) {
"MGC Spatial RGB chroma did not export its filtered texture"
"MGC Spatial RGB output did not export its merged texture"
}
gpuOutput = if (gpuLinearRgbStorage == GpuLinearRgbStorage.RGBA16UI) {
postprocessedUi.also { postprocessedUi = 0 }
} else {
GlesGpuCompletion.awaitSubmittedWork(
label = "MGC Spatial V25 merge IIR-to-float handoff",
label = "MGC Spatial V25 merge RGB16-to-float handoff",
checkGlError = ::checkGlError,
)
createTexture(
@@ -5755,9 +5738,7 @@ internal class GlesMgcRawSpatialStacker(
"MGC Spatial V25 RGB merge frames=${frames.size} " +
"native=${width}x$height " +
"output=${outputWidth}x$outputHeight rawScale=$sabreResolveRawScale " +
"mergeSharpness=$mergeSharpness merge=${mergeMs}ms " +
"colorNoiseIir=${chromaResult.chromaSubmissionMs}ms " +
"chromaFinal=${chromaResult.finalSubmissionMs}ms",
"mergeSharpness=$mergeSharpness merge=${mergeMs}ms",
)
return RgbMergeOutput(
cpuBuffer = cpuOutput,
@@ -6034,7 +6015,7 @@ internal class GlesMgcRawSpatialStacker(
GLES31.GL_WRITE_ONLY,
GLES30.GL_RGBA16F,
)
checkGlError("MGC Spatial RGB chroma RGBA16F handoff")
checkGlError("MGC Spatial RGB RGBA16F handoff")
}
private fun readRgbTile(
@@ -6483,9 +6464,9 @@ internal class GlesMgcRawSpatialStacker(
}
/**
* 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.
* ResolveSabre has consumed every merge-stage texture. Retire that arena before the output
* handoff; only the Resolve result in the output assembler's RGB texture crosses this phase
* boundary.
*/
private fun releaseSabreMergePhaseTextures(resolvedRgb: Int) {
check(resolvedRgb in textures) { "Sabre Resolve phase must retain its resolved RGB" }
@@ -6544,16 +6525,16 @@ internal class GlesMgcRawSpatialStacker(
}
/**
* Closes RGB fusion before the recursive chroma stage allocates its two additional full-size
* surfaces. The assembled RGBA16UI input becomes IIR scratch after seeding; every other fusion
* texture is dead at this boundary and must not inflate the IIR allocation peak.
* Closes RGB fusion before the output handoff. Only the assembled RGBA16UI output survives;
* every other fusion texture is dead at this boundary and must not overlap the export or
* full-size readback.
*/
private fun releaseRgbFusionPhaseTextures(
retainedTexture: Int,
label: String,
) {
check(retainedTexture != 0 && textures.contains(retainedTexture)) {
"MGC Spatial RGB $label IIR input is not owned by the stacker"
"MGC Spatial RGB $label output is not owned by the stacker"
}
val beforeBytes = estimatedOwnedTextureBytes()
val waitMs = GlesGpuCompletion.awaitSubmittedWork(
@@ -6575,7 +6556,7 @@ internal class GlesMgcRawSpatialStacker(
TAG,
"MGC Spatial RGB $label fusion arena released textures=${releasedTextures.size} " +
"releasedBytes=$releasedBytes retainedBytes=${estimatedOwnedTextureBytes()} " +
"iirWorkingSetBytes=${rgbIirWorkingSetBytes()} beforeBytes=$beforeBytes " +
"beforeBytes=$beforeBytes " +
"gpuWait=${waitMs}ms",
)
}
@@ -7119,8 +7100,8 @@ internal class GlesMgcRawSpatialStacker(
noiseLutCache.clear()
globalAlignment?.release()
globalAlignment = null
rgbChromaPostprocessor?.release()
rgbChromaPostprocessor = null
rgbOutputAssembler?.release()
rgbOutputAssembler = null
if (programs.isNotEmpty()) {
for (program in programs) GLES30.glDeleteProgram(program)
}
@@ -0,0 +1,287 @@
package com.hinnka.mycamera.processor
import android.opengl.GLES30
import android.opengl.GLES31
import com.hinnka.mycamera.utils.DirectBufferPixelPacker
import com.hinnka.mycamera.utils.LargeDirectBuffer
import java.nio.ByteBuffer
/**
* Full-size RGBA16UI output boundary for MGC Spatial RGB and Sabre VGN.
*
* Fusion/Resolve tiles are assembled into one full-size 2D texture owned by this stage. The merged
* un-white-balanced camera RGB is handed off unchanged: either exported as a GPU texture or read
* back into the packed RGB16 CPU buffer. No post-fusion color noise or IIR filtering runs here.
*/
internal class GlesMgcSpatialRgbOutputAssembler(
private val imageWidth: Int,
private val imageHeight: Int,
private val backend: Backend,
private val exportFullSizeTexture: Boolean = false,
) {
interface Backend {
fun createRgba16UiTexture(width: Int, height: Int, label: String): Int
fun deleteTexture(texture: Int, label: String)
fun transferTextureOwnership(texture: Int, label: String)
fun checkGlError(label: String)
fun yieldToUiRenderer()
}
data class ReadbackTiming(
val elapsedMs: Long,
val gpuQueueWaitMs: Long,
val pixelTransferMs: Long,
val cpuPackMs: Long,
val allocMs: Long,
)
data class ProcessResult(
val readbackTiming: ReadbackTiming,
val exportedTextureId: Int,
val cpuBufferPopulated: Boolean,
)
private var tiles: List<MgcSpatialRgbTile> = emptyList()
private var readbackTileWidth = 0
private var readbackTileHeight = 0
private var assembledRgb = 0
private var writtenTileCount = 0
private var readbackFbo = 0
init {
require(imageWidth > 0 && imageHeight > 0)
}
private fun validateAndSetTiles(newTiles: List<MgcSpatialRgbTile>) {
require(newTiles.isNotEmpty())
check(assembledRgb == 0) { "MGC Spatial RGB output storage is already active" }
val tiles = newTiles.toList()
val rows = tiles.groupBy { it.outputCore.top }.toSortedMap().values.toList()
var expectedTop = 0
var expectedIndex = 0
rows.forEachIndexed { rowIndex, row ->
val orderedRow = row.sortedBy { it.outputCore.left }
require(orderedRow.first().outputCore.top == expectedTop) {
"MGC Spatial RGB tile row $rowIndex starts at ${orderedRow.first().outputCore.top}, " +
"expected $expectedTop"
}
val rowBottom = orderedRow.first().outputCore.bottom
var expectedLeft = 0
orderedRow.forEach { tile ->
require(tile.index == expectedIndex++) {
"MGC Spatial RGB tiles must be row-major"
}
require(tile.outputCore.left == expectedLeft && tile.outputCore.top == expectedTop) {
"MGC Spatial RGB tile ${tile.index} leaves a gap or overlaps another tile"
}
require(tile.outputCore.bottom == rowBottom) {
"MGC Spatial RGB tile row $rowIndex has inconsistent heights"
}
expectedLeft = tile.outputCore.right
}
require(expectedLeft == imageWidth) {
"MGC Spatial RGB tile row $rowIndex covers width $expectedLeft, expected $imageWidth"
}
expectedTop = rowBottom
}
require(expectedTop == imageHeight) {
"MGC Spatial RGB tiles cover height $expectedTop, expected $imageHeight"
}
readbackTileWidth = tiles.maxOf { it.outputCore.width }
readbackTileHeight = tiles.maxOf { it.outputCore.height }
this.tiles = tiles
}
fun initStorage(tiles: List<MgcSpatialRgbTile>) {
validateAndSetTiles(tiles)
val maxTextureSize = IntArray(1)
GLES30.glGetIntegerv(GLES30.GL_MAX_TEXTURE_SIZE, maxTextureSize, 0)
require(imageWidth <= maxTextureSize[0] && imageHeight <= maxTextureSize[0]) {
"MGC Spatial RGB output requires ${imageWidth}x$imageHeight 2D textures; " +
"GLES supports up to ${maxTextureSize[0]}"
}
assembledRgb = backend.createRgba16UiTexture(imageWidth, imageHeight, "assembled camera RGB")
backend.checkGlError("MGC Spatial RGB output storage ${imageWidth}x$imageHeight")
writtenTileCount = 0
}
/**
* Full-size integer render target owned by this stage.
*
* The normalize/Resolve fragment pass renders each tile directly into its global viewport on
* this texture, which is then exported or read back without another image copy.
*/
fun normalizationTargetTexture(): Int {
check(assembledRgb != 0) { "MGC Spatial RGB output storage is not initialized" }
return assembledRgb
}
fun markTileWritten(tile: MgcSpatialRgbTile) {
check(writtenTileCount < tiles.size) { "All MGC Spatial RGB tiles are already assembled" }
check(tiles[writtenTileCount].index == tile.index) {
"MGC Spatial RGB tile ${tile.index} was written out of row-major order; " +
"expected ${tiles[writtenTileCount].index}"
}
writtenTileCount += 1
}
fun process(
obtainOutputBuffer: () -> ByteBuffer,
deferFullSizeReadback: Boolean,
onFinalSubmitted: (() -> Unit)? = null,
): ProcessResult {
check(assembledRgb != 0) { "MGC Spatial RGB output has no assembled fusion output" }
check(writtenTileCount == tiles.size) {
"MGC Spatial RGB output is incomplete: $writtenTileCount/${tiles.size} tiles"
}
onFinalSubmitted?.invoke()
val cpuBufferPopulated = !exportFullSizeTexture || !deferFullSizeReadback
val timing = if (cpuBufferPopulated) {
readbackFullSize(assembledRgb, obtainOutputBuffer())
} else {
check(onFinalSubmitted != null) {
"Deferred MGC Spatial RGB export requires a completion checkpoint"
}
ReadbackTiming(
elapsedMs = 0L,
gpuQueueWaitMs = 0L,
pixelTransferMs = 0L,
cpuPackMs = 0L,
allocMs = 0L,
)
}
val exportedTextureId = if (exportFullSizeTexture) assembledRgb else 0
if (exportedTextureId != 0) {
backend.transferTextureOwnership(exportedTextureId, "camera RGB export")
} else {
backend.deleteTexture(assembledRgb, "assembled camera RGB")
}
assembledRgb = 0
writtenTileCount = 0
tiles = emptyList()
readbackTileWidth = 0
readbackTileHeight = 0
return ProcessResult(
readbackTiming = timing,
exportedTextureId = exportedTextureId,
cpuBufferPopulated = cpuBufferPopulated,
)
}
fun release() {
if (assembledRgb != 0) {
backend.deleteTexture(assembledRgb, "assembled camera RGB")
assembledRgb = 0
}
writtenTileCount = 0
tiles = emptyList()
readbackTileWidth = 0
readbackTileHeight = 0
if (readbackFbo != 0) {
GLES30.glDeleteFramebuffers(1, intArrayOf(readbackFbo), 0)
readbackFbo = 0
}
}
private fun readbackFullSize(texture: Int, outputBuffer: ByteBuffer): ReadbackTiming {
val gpuQueueWaitMs = GlesGpuCompletion.awaitSubmittedWork(
label = "MGC Spatial RGB full-size output",
checkGlError = backend::checkGlError,
)
ensureReadbackFramebuffer()
val allocationStart = System.currentTimeMillis()
val scratchBytes = readbackTileWidth.toLong() * readbackTileHeight.toLong() * 8L
val scratch = LargeDirectBuffer.allocate(
scratchBytes,
"MGC Spatial RGB full-size readback",
)
?: throw IllegalStateException("Unable to allocate full-size MGC Spatial RGB readback scratch")
val allocationMs = System.currentTimeMillis() - allocationStart
outputBuffer.clear()
var glReadMs = 0L
var copyMs = 0L
GLES31.glMemoryBarrier(
GLES31.GL_SHADER_IMAGE_ACCESS_BARRIER_BIT or GLES31.GL_FRAMEBUFFER_BARRIER_BIT,
)
GLES30.glBindFramebuffer(GLES30.GL_FRAMEBUFFER, readbackFbo)
try {
GLES30.glFramebufferTexture2D(
GLES30.GL_FRAMEBUFFER,
GLES30.GL_COLOR_ATTACHMENT0,
GLES30.GL_TEXTURE_2D,
texture,
0,
)
GLES30.glReadBuffer(GLES30.GL_COLOR_ATTACHMENT0)
val status = GLES30.glCheckFramebufferStatus(GLES30.GL_FRAMEBUFFER)
check(status == GLES30.GL_FRAMEBUFFER_COMPLETE) {
"Full-size MGC Spatial RGB framebuffer incomplete: 0x${status.toString(16)}"
}
GLES30.glPixelStorei(GLES30.GL_PACK_ALIGNMENT, 8)
tiles.forEach { tile ->
scratch.clear()
val readStart = System.currentTimeMillis()
GLES30.glReadPixels(
tile.outputCore.left,
tile.outputCore.top,
tile.outputCore.width,
tile.outputCore.height,
GLES30.GL_RGBA_INTEGER,
GLES30.GL_UNSIGNED_SHORT,
scratch,
)
glReadMs += System.currentTimeMillis() - readStart
backend.checkGlError("Full-size MGC Spatial RGB read tile ${tile.index}")
val copyStart = System.currentTimeMillis()
check(
DirectBufferPixelPacker.unpackRgba16TileToRgb16(
source = scratch,
sourceWidth = tile.outputCore.width,
sourceHeight = tile.outputCore.height,
destination = outputBuffer,
destinationWidth = imageWidth,
destinationHeight = imageHeight,
destinationLeft = tile.outputCore.left,
destinationTop = tile.outputCore.top,
),
) { "Unable to pack full-size MGC Spatial RGB tile ${tile.index}" }
copyMs += System.currentTimeMillis() - copyStart
backend.yieldToUiRenderer()
}
} finally {
GLES30.glFramebufferTexture2D(
GLES30.GL_FRAMEBUFFER,
GLES30.GL_COLOR_ATTACHMENT0,
GLES30.GL_TEXTURE_2D,
0,
0,
)
GLES30.glBindFramebuffer(GLES30.GL_FRAMEBUFFER, 0)
LargeDirectBuffer.free(scratch)
}
outputBuffer.rewind()
return ReadbackTiming(
elapsedMs = gpuQueueWaitMs + allocationMs + glReadMs + copyMs,
gpuQueueWaitMs = gpuQueueWaitMs,
pixelTransferMs = glReadMs,
cpuPackMs = copyMs,
allocMs = allocationMs,
)
}
private fun ensureReadbackFramebuffer() {
if (readbackFbo != 0) return
val ids = IntArray(1)
GLES30.glGenFramebuffers(1, ids, 0)
readbackFbo = ids[0]
check(readbackFbo != 0) { "Failed to allocate MGC Spatial RGB output readback framebuffer" }
backend.checkGlError("MGC Spatial RGB output readback framebuffer")
}
}
@@ -8,9 +8,6 @@ package com.hinnka.mycamera.processor
* threshold, the smallest estimated candidate remains runnable.
*/
internal object MgcSpatialRgbMemoryPolicy {
private const val RGBA16_BYTES_PER_PIXEL = 8L
private const val IIR_SURFACE_COUNT = 3L
fun selectAdvisoryPlanIndex(
projectedBytes: List<Long>,
advisoryBytes: Long,
@@ -25,9 +22,4 @@ internal object MgcSpatialRgbMemoryPolicy {
projectedBytes.indices.minBy { projectedBytes[it] }
}
}
fun iirWorkingSetBytes(width: Int, height: Int): Long {
require(width > 0 && height > 0)
return width.toLong() * height * RGBA16_BYTES_PER_PIXEL * IIR_SURFACE_COUNT
}
}
@@ -35,7 +35,9 @@ internal object PhotonDenoiseShaders {
layout(local_size_x = $LOCAL, local_size_y = $LOCAL) in;
ivec2 groupId() { return ivec2(gl_WorkGroupID.xy); }
// Work-group offset of a partial dispatch (row bands of the synthesis); 0 for a whole level.
uniform ivec2 uGroupOffset;
ivec2 groupId() { return ivec2(gl_WorkGroupID.xy) + uGroupOffset; }
ivec2 globalId() { return groupId() * $LOCAL + ivec2(gl_LocalInvocationID.xy); }
const float LUMA_TAPS[7] = float[7](
@@ -167,9 +167,8 @@ internal class PhotonMultiScaleDenoiser {
bindSynthesize(synthesizeProgram, inputTexture, lscTexture, mergeTexture, gaussians,
denoisedCoarse, sizes, level, lumaEnabled, chromaEnabled, bilateralEnabled, params)
bindImage(0, result, GLES30.GL_RGBA16F)
dispatch(synthesizeProgram, size)
dispatchBands(synthesizeProgram, size)
}
GlesGpuScheduler.yieldToUiRenderer()
sink?.onPass(if (level == 0) "output" else "denoised$level", result, size[0], size[1], false)
if (timing.ablation) {
synthesizeAblation(timing, inputTexture, lscTexture, mergeTexture, gaussians, denoisedCoarse,
@@ -235,9 +234,8 @@ internal class PhotonMultiScaleDenoiser {
bindSynthesize(synthesizeProgram, inputTexture, lscTexture, mergeTexture, gaussians,
denoisedCoarse, sizes, level, variant.luma, variant.chroma, variant.bilateral, params)
bindImage(0, scratch, GLES30.GL_RGBA16F)
dispatch(synthesizeProgram, size)
dispatchBands(synthesizeProgram, size)
}
GlesGpuScheduler.yieldToUiRenderer()
}
}
} finally {
@@ -454,6 +452,31 @@ internal class PhotonMultiScaleDenoiser {
)
}
/**
* The fused synthesis in row bands of [SYNTHESIS_BAND_GROUPS] work-group rows, each flushed with
* a yield so the UI renderer gets GPU slots inside a level (L0 alone is ~300ms in one dispatch).
* Tiles read only the inputs and write disjoint pixels, so bands need no barrier between them
* and the result is the same as one whole-level dispatch.
*/
private fun dispatchBands(program: Int, size: IntArray) {
val groupsX = GlesComputeWorkGroup.imageGroupCount(size[0])
val groupsY = GlesComputeWorkGroup.imageGroupCount(size[1])
val offset = location(program, "uGroupOffset")
var row = 0
while (row < groupsY) {
val rows = minOf(SYNTHESIS_BAND_GROUPS, groupsY - row)
GLES31.glUniform2i(offset, 0, row)
GLES31.glDispatchCompute(groupsX, rows, 1)
GlesGpuScheduler.yieldToUiRenderer()
row += rows
}
GLES31.glUniform2i(offset, 0, 0)
GLES31.glMemoryBarrier(
GLES31.GL_SHADER_IMAGE_ACCESS_BARRIER_BIT or GLES31.GL_TEXTURE_FETCH_BARRIER_BIT or
GLES31.GL_FRAMEBUFFER_BARRIER_BIT,
)
}
private fun bindImage(unit: Int, texture: Int, format: Int) {
GLES31.glBindImageTexture(unit, texture, 0, false, 0, GLES31.GL_WRITE_ONLY, format)
}
@@ -476,6 +499,7 @@ internal class PhotonMultiScaleDenoiser {
private companion object {
const val ABLATION_REPEATS = 3
const val SYNTHESIS_BAND_GROUPS = 64
const val UNIT_INPUT = 0
const val UNIT_LSC = 1
const val UNIT_FINE = 2
@@ -1,154 +0,0 @@
package com.hinnka.mycamera.processor
import java.io.File
import org.junit.Assert.assertArrayEquals
import org.junit.Assert.assertEquals
import org.junit.Assert.assertFalse
import org.junit.Assert.assertTrue
import org.junit.Assume.assumeTrue
import org.junit.Test
class GlesMgcSpatialRgbChromaPostprocessorTest {
@Test
fun postprocessorKeepsWbPairedUsesRgbDirectionAndDoesNotReapplyLensShading() {
val seed = GlesMgcSpatialRgbChromaShaders.seed
val finish = GlesMgcSpatialRgbChromaShaders.finalCameraRgb
assertTrue(seed.contains("cameraRgb * uCalculationGains"))
assertTrue(finish.contains("/\n max(uCalculationGains"))
assertTrue(seed.contains("directionMaskAt(p)"))
assertTrue(seed.contains("float rgbGradient"))
assertTrue(seed.contains("gradients[i] = rgbGradient"))
assertFalse(seed.contains("directionMomentAt"))
assertFalse(seed.contains("doubledDirectionAxes"))
assertTrue(seed.contains("count << 8"))
assertTrue(seed.contains("const float finiteScale = 65504.0 / 65535.0"))
assertTrue(!seed.contains("vec3(imageLoad(uCameraRgb"))
assertTrue(!seed.contains("LensShading"))
assertTrue(!finish.contains("LensShading"))
}
@Test
fun recursiveFiltersUseAnalyticConstantBoundaryState() {
val rgb = GlesMgcSpatialRgbChromaShaders.iirRgb
val error = GlesMgcSpatialRgbChromaShaders.iirError
assertTrue(rgb.contains("float steadyOutput"))
assertTrue(rgb.contains("1.0 + b[1] + b[2]"))
assertTrue(rgb.contains("steadyState(boundaryY, steadyY)"))
assertTrue(error.contains("Delayer steadyState(float value)"))
assertTrue(error.contains("1.0 + uB10[1] + uB10[2]"))
assertTrue(!rgb.contains("uBoundaryWarmup"))
assertTrue(!error.contains("uBoundaryWarmup"))
}
@Test
fun everyFilterUsesDirectCoordinatesOverFullSize2dStorage() {
val globalShaders = listOf(
GlesMgcSpatialRgbChromaShaders.seed,
GlesMgcSpatialRgbChromaShaders.colorNoise1,
GlesMgcSpatialRgbChromaShaders.colorNoise2,
GlesMgcSpatialRgbChromaShaders.colorNoise3Smooth,
GlesMgcSpatialRgbChromaShaders.restoreOriginal,
GlesMgcSpatialRgbChromaShaders.iirRgb,
GlesMgcSpatialRgbChromaShaders.calculateColorNoiseError,
GlesMgcSpatialRgbChromaShaders.iirError,
GlesMgcSpatialRgbChromaShaders.colorNoiseFilter,
GlesMgcSpatialRgbChromaShaders.finalCameraRgb,
)
globalShaders.forEach { shader ->
assertTrue(shader.contains("uimage2D"))
assertTrue(!shader.contains("uimage2DArray"))
assertTrue(!shader.contains("uTileLefts"))
assertTrue(!shader.contains("uTileTops"))
assertTrue(!shader.contains("tiledPosition"))
}
assertTrue(GlesMgcSpatialRgbChromaShaders.iirRgb.contains("innerSize = uAxis == 0 ? uImageSize.x"))
assertTrue(GlesMgcSpatialRgbChromaShaders.iirRgb.contains("for (int i = 0; i < innerSize; ++i)"))
assertTrue(GlesMgcSpatialRgbChromaShaders.iirRgb.contains("ivec2 storage = p;"))
assertTrue(GlesMgcSpatialRgbChromaShaders.iirRgb.contains("imageStore(uOutput, storage"))
assertTrue(GlesMgcSpatialRgbChromaShaders.iirError.contains("for (int i = 0; i < innerSize; ++i)"))
}
@Test
fun finalHandoffUsesOneGlobal2dSurface() {
val finish = GlesMgcSpatialRgbChromaShaders.finalCameraRgb
assertTrue(finish.contains("uimage2D uInput"))
assertTrue(finish.contains("uimage2D uOutput"))
assertTrue(finish.contains("imageStore(uOutput, p, outputPixel)"))
assertTrue(!finish.contains("uimage2DArray"))
}
@Test
fun nativeScaleRetainsReferenceVgnCoefficientsAndSrScaleLowersDigitalCutoff() {
val native = MgcSpatialRgbChromaIirCoefficients.forOutputScale(1f)
val sr = MgcSpatialRgbChromaIirCoefficients.forOutputScale(1.5f)
assertArrayEquals(
floatArrayOf(0.0674552768f, 0.134910554f, 0.0674552768f, 0f),
native.pass1.a10,
0f,
)
assertArrayEquals(
floatArrayOf(1f, -1.14298046f, 0.412801594f, 0f),
native.pass1.b10,
0f,
)
assertTrue(sr.pass1.a10[0] < native.pass1.a10[0])
assertEquals(2f * sr.pass1.a10[0], sr.pass1.a10[1], 1e-6f)
}
@Test
fun generatedPostprocessorShadersPassAvailableNdkValidator() {
val sdkRoot = System.getenv("ANDROID_SDK_ROOT") ?: System.getenv("ANDROID_HOME")
val validator = sdkRoot?.let(::File)
?.resolve("ndk")
?.listFiles()
?.sortedByDescending { it.name }
?.asSequence()
?.mapNotNull { ndk ->
ndk.resolve("shader-tools")
.walkTopDown()
.firstOrNull { it.name == "glslc" && it.canExecute() }
}
?.firstOrNull()
assumeTrue("Android NDK glslc is unavailable", validator != null)
val sources = listOf(
GlesMgcSpatialRgbChromaShaders.seed,
GlesMgcSpatialRgbChromaShaders.colorNoise1,
GlesMgcSpatialRgbChromaShaders.colorNoise2,
GlesMgcSpatialRgbChromaShaders.colorNoise3Smooth,
GlesMgcSpatialRgbChromaShaders.restoreOriginal,
GlesMgcSpatialRgbChromaShaders.iirRgb,
GlesMgcSpatialRgbChromaShaders.calculateColorNoiseError,
GlesMgcSpatialRgbChromaShaders.iirError,
GlesMgcSpatialRgbChromaShaders.colorNoiseFilter,
GlesMgcSpatialRgbChromaShaders.finalCameraRgb,
)
sources.forEachIndexed { index, source ->
val sourceFile = File.createTempFile("mgc-spatial-rgb-chroma-$index-", ".compute")
val outputFile = File.createTempFile("mgc-spatial-rgb-chroma-$index-", ".spv")
try {
sourceFile.writeText(source)
val process = ProcessBuilder(
checkNotNull(validator).absolutePath,
"--target-env=opengl",
"-fauto-map-locations",
"-fauto-bind-uniforms",
"-fshader-stage=compute",
sourceFile.absolutePath,
"-o",
outputFile.absolutePath,
).redirectErrorStream(true).start()
val output = process.inputStream.bufferedReader().use { it.readText() }
assertEquals("shader $index: $output", 0, process.waitFor())
} finally {
sourceFile.delete()
outputFile.delete()
}
}
}
}
@@ -12,7 +12,7 @@ class GpuStackQueueTimingTest {
GpuStackStageWait(GpuStackCompletionStage.LONG_ALIGNMENT, 7L),
GpuStackStageWait(GpuStackCompletionStage.HIGHLIGHT_ALIGNMENT, 11L),
GpuStackStageWait(GpuStackCompletionStage.TILED_RECONSTRUCTION, 29L),
GpuStackStageWait(GpuStackCompletionStage.CHROMA_POSTPROCESS, 2_137L),
GpuStackStageWait(GpuStackCompletionStage.OUTPUT_HANDOFF, 2_137L),
GpuStackStageWait(GpuStackCompletionStage.FINAL_EXPORT, 35L),
),
)
@@ -20,7 +20,7 @@ class GpuStackQueueTimingTest {
assertEquals(2_219L, timing.totalWaitMs)
assertEquals(
"normalAlignment=0ms longAlignment=7ms highlightAlignment=11ms " +
"tiledReconstruction=29ms chromaPostprocess=2137ms finalExport=35ms",
"tiledReconstruction=29ms outputHandoff=2137ms finalExport=35ms",
timing.logFields(),
)
}
@@ -1,7 +1,6 @@
package com.hinnka.mycamera.processor
import org.junit.Assert.assertEquals
import org.junit.Assert.assertTrue
import org.junit.Test
class MgcSpatialRgbMemoryPolicyTest {
@@ -32,12 +31,4 @@ class MgcSpatialRgbMemoryPolicyTest {
),
)
}
@Test
fun twoTimesSpatialOutputKeepsOnlyThreeFullSizeIirSurfaces() {
val workingSet = MgcSpatialRgbMemoryPolicy.iirWorkingSetBytes(8192, 6144)
assertEquals(1_207_959_552L, workingSet)
assertTrue(workingSet > 640L * 1024L * 1024L)
}
}