fix: raw / rawmax performance

This commit is contained in:
zhoubinjia committed 2026-08-04 13:53:04 +08:00
1 parent 1b9b8a3712
commit aef459efba
5 files changed
+852 -196

No files matched your search

@@ -5,8 +5,10 @@ import android.opengl.EGLConfig
import android.opengl.EGLContext
import android.opengl.EGLDisplay
import android.opengl.GLES30
import android.opengl.GLES31
import android.os.Process
import com.hinnka.mycamera.utils.PLog
import java.util.ArrayDeque
object GlesGpuScheduler {
private const val EGL_CONTEXT_MINOR_VERSION_KHR = 0x30FB
@@ -17,6 +19,210 @@ object GlesGpuScheduler {
private const val GPU_CHECKPOINT_SLEEP_MS = 1L
private const val GPU_UI_BREATHING_ROOM_MS = 2L
/**
* Keeps independent GPU passes in flight without queuing a consumer behind its producer.
*
* Mali drivers can fail to retire a producer fence when a dependent consumer has already
* been submitted after it. Resource declarations let the scheduler retire every conflicting
* producer before the consumer is encoded, while unrelated passes still share the window.
*/
class PassWindow(
private val tag: String,
private val maxInFlight: Int = 2,
) {
private data class PendingPass(
val label: String,
val sync: Long,
val reads: LongArray,
val writes: LongArray,
)
private data class ActivePass(
val label: String,
val reads: LongArray,
val writes: LongArray,
)
private val pending = ArrayDeque<PendingPass>(maxInFlight)
private var activePass: ActivePass? = null
init {
require(maxInFlight > 0) { "GPU pass window capacity must be positive" }
}
fun beginPass(
label: String,
reads: LongArray = longArrayOf(),
writes: LongArray = longArrayOf(),
) {
check(activePass == null) {
"GPU pass ${activePass?.label ?: "unknown"} was not ended before $label"
}
var newestConflictIndex = -1
pending.forEachIndexed { index, pass ->
if (hasHazard(pass, reads, writes)) {
newestConflictIndex = index
}
}
if (newestConflictIndex >= 0) {
waitThrough(newestConflictIndex, label, "resource hazard")
}
if (pending.size >= maxInFlight) {
waitThrough(0, label, "window full")
}
activePass = ActivePass(label, reads.copyOf(), writes.copyOf())
}
fun endPass() {
val pass = checkNotNull(activePass) { "GPU pass ended without beginPass" }
activePass = null
val sync = GLES30.glFenceSync(GLES30.GL_SYNC_GPU_COMMANDS_COMPLETE, 0)
if (sync == 0L) {
PLog.w(tag, "Failed to allocate GPU pass fence label=${pass.label}; completing queue")
GLES30.glFinish()
deletePendingFences()
return
}
pending.addLast(PendingPass(pass.label, sync, pass.reads, pass.writes))
}
/**
* Retires pending users before a texture or buffer is overwritten, recycled, or deleted.
*/
fun awaitResources(label: String, resources: LongArray) {
check(activePass == null) {
"Cannot retire resources while ${activePass?.label ?: "a pass"} is active"
}
var newestUserIndex = -1
pending.forEachIndexed { index, pass ->
if (intersects(resources, pass.reads) || intersects(resources, pass.writes)) {
newestUserIndex = index
}
}
if (newestUserIndex >= 0) {
waitThrough(newestUserIndex, label, "resource retirement")
}
}
/**
* Use after a later component/tile checkpoint has completed every command in this window.
*/
fun clearAfterCheckpoint() {
check(activePass == null) {
"Cannot clear GPU pass window while ${activePass?.label ?: "a pass"} is active"
}
deletePendingFences()
}
/**
* Completes outstanding passes before their resources or GL context are destroyed.
*/
fun drain(label: String) {
if (activePass != null) {
PLog.w(
tag,
"GPU pass window draining with an unterminated pass " +
"active=${activePass?.label} boundary=$label",
)
GLES30.glFinish()
activePass = null
deletePendingFences()
return
}
while (pending.isNotEmpty()) {
waitThrough(0, label, "drain")
}
}
private fun waitThrough(index: Int, nextLabel: String, reason: String) {
val target = pending.elementAt(index)
try {
var flags = GLES30.GL_SYNC_FLUSH_COMMANDS_BIT
var result: Int
do {
result = GLES30.glClientWaitSync(
target.sync,
flags,
GPU_CHECKPOINT_WAIT_NS,
)
flags = 0
} while (result == GLES30.GL_TIMEOUT_EXPIRED)
if (result == GLES30.GL_WAIT_FAILED) {
PLog.w(
tag,
"GPU pass window wait failed target=${target.label} next=$nextLabel " +
"reason=$reason",
)
GLES30.glFinish()
}
} catch (e: RuntimeException) {
PLog.w(
tag,
"GPU pass window wait threw target=${target.label} next=$nextLabel " +
"reason=$reason",
e,
)
GLES30.glFinish()
} finally {
repeat(index + 1) {
GLES30.glDeleteSync(pending.removeFirst().sync)
}
}
}
private fun hasHazard(
pendingPass: PendingPass,
reads: LongArray,
writes: LongArray,
): Boolean {
return intersects(reads, pendingPass.writes) ||
intersects(writes, pendingPass.reads) ||
intersects(writes, pendingPass.writes)
}
private fun intersects(first: LongArray, second: LongArray): Boolean {
for (left in first) {
if (left == NO_RESOURCE) continue
for (right in second) {
if (left == right) return true
}
}
return false
}
private fun deletePendingFences() {
while (pending.isNotEmpty()) {
GLES30.glDeleteSync(pending.removeFirst().sync)
}
}
}
private const val NO_RESOURCE = 0L
private const val BUFFER_RESOURCE_NAMESPACE = 1L shl 32
fun textureResource(texture: Int): Long {
return if (texture == 0) NO_RESOURCE else texture.toLong() and 0xffff_ffffL
}
fun bufferResource(buffer: Int): Long {
return if (buffer == 0) {
NO_RESOURCE
} else {
BUFFER_RESOURCE_NAMESPACE or (buffer.toLong() and 0xffff_ffffL)
}
}
/**
* VGN/Radiance is a long mixed image/sampler/framebuffer dependency chain. Keep one
* conservative visibility contract on every driver; scheduling and resource lifetime are
* optimized independently.
*/
fun memoryBarrier() {
GLES31.glMemoryBarrier(GLES31.GL_ALL_BARRIER_BITS)
}
fun createBackgroundContext(display: EGLDisplay, config: EGLConfig, tag: String): EGLContext {
if (supportsLowPriorityContext(display)) {
val lowPriorityContext = EGL14.eglCreateContext(
@@ -39,8 +39,6 @@ internal class GlesRadianceVgnChromaPostprocessor(
fun checkGlError(label: String)
fun waitForGpuCheckpoint(label: String)
fun yieldToUiRenderer()
}
@@ -71,6 +69,8 @@ internal class GlesRadianceVgnChromaPostprocessor(
}
private val safeOutputScale = outputScale.takeIf { it.isFinite() && it > 0f } ?: 1f
private val coefficients = RadianceVgnChromaIirCoefficients.forOutputScale(safeOutputScale)
private val passWindow =
GlesGpuScheduler.PassWindow("GlesRadianceVgnChroma", 2)
private val readbackTileWidth: Int
private val readbackTileHeight: Int
@@ -91,6 +91,8 @@ internal class GlesRadianceVgnChromaPostprocessor(
private var writtenTileCount = 0
private var readbackFbo = 0
private val ownedTextures = ArrayList<Int>(3)
private val pendingImageReads = ArrayList<Long>(3)
private val pendingImageWrites = ArrayList<Long>(3)
init {
require(imageWidth > 0 && imageHeight > 0)
@@ -222,6 +224,7 @@ internal class GlesRadianceVgnChromaPostprocessor(
val chromaSubmissionStartNs = System.nanoTime()
originalYccd = createFullSizeTexture("original YCCD")
smoothYccd = createFullSizeTexture("smooth YCCD")
clearImageBindings()
dispatchSeed()
dispatchLocal(colorNoise1Program, originalYccd, assembledRgb, "color noise 1")
@@ -316,6 +319,7 @@ internal class GlesRadianceVgnChromaPostprocessor(
}
fun release() {
passWindow.drain("Radiance VGN chroma release")
if (ownedTextures.isNotEmpty()) {
GLES30.glDeleteTextures(ownedTextures.size, ownedTextures.toIntArray(), 0)
ownedTextures.clear()
@@ -407,9 +411,10 @@ internal class GlesRadianceVgnChromaPostprocessor(
bindImage(0, originalYccd, GLES31.GL_READ_ONLY)
bindImage(1, destination, GLES31.GL_WRITE_ONLY)
// The result leaves this component and can be consumed as both an FBO attachment and a
// sampler by the persistent RAW renderer. dispatchImage establishes the full barrier and
// completion boundary before ownership is transferred.
// sampler by the persistent RAW renderer, so this ownership boundary remains a
// CPU-visible checkpoint.
dispatchImage(finalProgram, "final camera RGB")
passWindow.drain("final camera RGB handoff")
}
private fun runIirRgb(
@@ -492,21 +497,25 @@ internal class GlesRadianceVgnChromaPostprocessor(
program: Int,
label: String,
) {
beginTrackedPass(label)
GLES31.glDispatchCompute(groupCount(imageWidth), groupCount(imageHeight), 1)
GLES31.glMemoryBarrier(GLES31.GL_ALL_BARRIER_BITS)
GlesGpuScheduler.memoryBarrier()
backend.checkGlError("Radiance VGN chroma $label")
backend.waitForGpuCheckpoint(label)
clearImageBindings()
passWindow.endPass()
}
private fun dispatchIir(axis: Int, label: String) {
beginTrackedPass(label)
if (axis == 0) {
GLES31.glDispatchCompute(1, imageHeight, 1)
} else {
GLES31.glDispatchCompute(imageWidth, 1, 1)
}
GLES31.glMemoryBarrier(GLES31.GL_ALL_BARRIER_BITS)
GlesGpuScheduler.memoryBarrier()
backend.checkGlError("Radiance VGN chroma $label")
backend.waitForGpuCheckpoint(label)
clearImageBindings()
passWindow.endPass()
}
private fun setImageUniforms(program: Int) {
@@ -514,6 +523,13 @@ internal class GlesRadianceVgnChromaPostprocessor(
}
private fun bindImage(unit: Int, texture: Int, access: Int) {
val resource = GlesGpuScheduler.textureResource(texture)
if (access != GLES31.GL_WRITE_ONLY) {
pendingImageReads += resource
}
if (access != GLES31.GL_READ_ONLY) {
pendingImageWrites += resource
}
GLES31.glBindImageTexture(
unit,
texture,
@@ -525,6 +541,30 @@ internal class GlesRadianceVgnChromaPostprocessor(
)
}
private fun beginTrackedPass(label: String) {
passWindow.beginPass(
label,
reads = pendingImageReads.toLongArray(),
writes = pendingImageWrites.toLongArray(),
)
pendingImageReads.clear()
pendingImageWrites.clear()
}
private fun clearImageBindings() {
for (unit in 0..2) {
GLES31.glBindImageTexture(
unit,
0,
0,
false,
0,
GLES31.GL_READ_ONLY,
GLES30.GL_RGBA16UI,
)
}
}
private fun createFullSizeTexture(label: String): Int {
val ids = IntArray(1)
GLES30.glGenTextures(1, ids, 0)
@@ -203,6 +203,10 @@ internal class GlesRawRadianceStacker(
val access: Int,
val format: Int,
)
private data class RadianceFrameSlot(
val index: Int,
val rawRegionTexture: Int,
)
private data class RegistrationAcceptance(
val accepted: Boolean,
val transform: RawStackPerspectiveTransform,
@@ -450,6 +454,10 @@ internal class GlesRawRadianceStacker(
private var radianceLongParticipationTexture = 0
private var radianceRgbTileTexture = 0
private var radianceSemanticSeedTexture = 0
private val radianceFrameSlots = ArrayList<RadianceFrameSlot>()
private var nextRadianceFrameSlotIndex = 0
private val radiancePassWindow =
GlesGpuScheduler.PassWindow(TAG, RADIANCE_PASS_WINDOW_SIZE)
private var radianceVgnPackedFloatTexture = 0
private var radianceVgnPackedBayerTexture = 0
private var radianceVgnPackedSmoothTexture = 0
@@ -458,7 +466,8 @@ internal class GlesRawRadianceStacker(
private var radianceVgnEdgeTexture = 0
private var radianceVgnFull0Texture = 0
private var radianceVgnFull1Texture = 0
private var radianceVgnUbo = 0
private val radianceVgnUbos = IntArray(RADIANCE_PASS_WINDOW_SIZE)
private var nextRadianceVgnUboIndex = 0
private var radianceVgnCapacityGeometry: RadianceVgnGeometry? = null
private var radianceVgnChromaPostprocessor: GlesRadianceVgnChromaPostprocessor? = null
private var rcdRawRegionTexture = 0
@@ -1246,12 +1255,6 @@ internal class GlesRawRadianceStacker(
this@GlesRawRadianceStacker.checkGlError(label)
}
override fun waitForGpuCheckpoint(label: String) {
this@GlesRawRadianceStacker.waitForRadianceGpuCheckpoint(
"chroma $label",
)
}
override fun yieldToUiRenderer() {
GlesGpuScheduler.yieldToUiRenderer()
}
@@ -1532,10 +1535,10 @@ internal class GlesRawRadianceStacker(
checkGlError("uploadRawTexture $label")
}
private fun ensureRawRegionTexture(capacityWidth: Int, capacityHeight: Int) {
private fun ensureRawRegionCapacity(capacityWidth: Int, capacityHeight: Int) {
val requestedWidth = capacityWidth.coerceIn(1, width)
val requestedHeight = capacityHeight.coerceIn(1, height)
if (rcdRawRegionTexture != 0) {
if (rcdRegionCapacityWidth > 0 && rcdRegionCapacityHeight > 0) {
require(
requestedWidth <= rcdRegionCapacityWidth &&
requestedHeight <= rcdRegionCapacityHeight,
@@ -1547,6 +1550,11 @@ internal class GlesRawRadianceStacker(
}
rcdRegionCapacityWidth = requestedWidth
rcdRegionCapacityHeight = requestedHeight
}
private fun ensureRawRegionTexture(capacityWidth: Int, capacityHeight: Int) {
ensureRawRegionCapacity(capacityWidth, capacityHeight)
if (rcdRawRegionTexture != 0) return
rcdRawRegionTexture = createTexture2D(
rcdRegionCapacityWidth,
rcdRegionCapacityHeight,
@@ -1579,7 +1587,11 @@ internal class GlesRawRadianceStacker(
}
}
private fun ensureRadianceTileResources(capacityWidth: Int, capacityHeight: Int) {
private fun ensureRadianceTileResources(
capacityWidth: Int,
capacityHeight: Int,
requiredFrameSlotCount: Int,
) {
if (!radianceUsesVgnSemanticBackend) {
ensureRcdRegionResources(capacityWidth, capacityHeight)
if (radianceRgbTileTexture == 0) {
@@ -1592,8 +1604,17 @@ internal class GlesRawRadianceStacker(
}
return
}
ensureRawRegionTexture(capacityWidth, capacityHeight)
if (radianceRgbTileTexture != 0) return
require(requiredFrameSlotCount > 0) {
"Radiance VGN reconstruction requires at least one frame input slot"
}
ensureRawRegionCapacity(capacityWidth, capacityHeight)
if (radianceFrameSlots.isNotEmpty()) {
check(radianceFrameSlots.size == requiredFrameSlotCount) {
"Radiance frame input slot count changed from " +
"${radianceFrameSlots.size} to $requiredFrameSlotCount"
}
return
}
radianceRgbTileTexture = createTexture2D(
rcdRegionCapacityWidth,
rcdRegionCapacityHeight,
@@ -1660,23 +1681,40 @@ internal class GlesRawRadianceStacker(
GLES30.GL_RGBA16UI,
GLES30.GL_NEAREST,
)
val ids = IntArray(1)
GLES31.glGenBuffers(1, ids, 0)
check(ids[0] != 0) { "Failed to allocate Radiance VGN UBO" }
radianceVgnUbo = ids[0]
buffers += radianceVgnUbo
GLES31.glGenBuffers(radianceVgnUbos.size, radianceVgnUbos, 0)
check(radianceVgnUbos.all { it != 0 }) {
"Failed to allocate Radiance VGN UBO ring"
}
radianceVgnUbos.forEach { buffers += it }
repeat(requiredFrameSlotCount) { slotIndex ->
radianceFrameSlots += RadianceFrameSlot(
index = slotIndex,
rawRegionTexture = createTexture2D(
rcdRegionCapacityWidth,
rcdRegionCapacityHeight,
GLES30.GL_R16UI,
GLES30.GL_NEAREST,
),
)
}
RawStackRuntimeDebug.i(TAG) {
"Radiance reconstruction=VGN-reference/semantic-nonreference " +
"Radiance reconstruction=VGN-reference/semantic-nonreference " +
"region=${rcdRegionCapacityWidth}x$rcdRegionCapacityHeight " +
"vgnWork=${geometry.workWidth}x${geometry.workHeight} " +
"frameInputRing=${radianceFrameSlots.size} " +
"perFrameColorDenoise=false postFusionChromaIir=" +
radianceVgnChromaPostprocessEnabled
}
}
private fun uploadRcdRawRegion(image: SafeImage, region: RadianceTileRect, label: String) {
private fun uploadRcdRawRegion(
image: SafeImage,
region: RadianceTileRect,
targetTexture: Int,
label: String,
) {
require(
rcdRawRegionTexture != 0 &&
targetTexture != 0 &&
region.width <= rcdRegionCapacityWidth &&
region.height <= rcdRegionCapacityHeight,
)
@@ -1686,7 +1724,7 @@ internal class GlesRawRadianceStacker(
val uploadBuffer = plane.buffer.duplicate().order(ByteOrder.nativeOrder()).apply {
position(region.top * plane.rowStride + region.left * plane.pixelStride)
}
GLES30.glBindTexture(GLES30.GL_TEXTURE_2D, rcdRawRegionTexture)
GLES30.glBindTexture(GLES30.GL_TEXTURE_2D, targetTexture)
GLES30.glPixelStorei(GLES30.GL_UNPACK_ALIGNMENT, 1)
GLES30.glPixelStorei(GLES30.GL_UNPACK_ROW_LENGTH, plane.rowStride / 2)
GLES30.glTexSubImage2D(
@@ -5242,6 +5280,19 @@ internal class GlesRawRadianceStacker(
}
private fun clearSuperResolutionAccumulator() {
beginRadianceGpuPass(
"clear accumulator",
writes = radianceTextureResources(
radianceNrAccumulatorTexture,
radianceDetailAccumulatorTexture,
if (visualizeRadianceFusionRejections) radianceFusionRejectionTexture else 0,
if (visualizeRadianceLongParticipation) {
radianceLongParticipationTexture
} else {
0
},
),
)
GLES31.glUseProgram(clearSuperResolutionAccumulatorProgram)
bindImage(
0,
@@ -5281,18 +5332,18 @@ internal class GlesRawRadianceStacker(
groupCount(superResolutionAccumulatorHeight),
1,
)
GLES31.glMemoryBarrier(
GLES31.GL_SHADER_IMAGE_ACCESS_BARRIER_BIT or
GLES31.GL_TEXTURE_FETCH_BARRIER_BIT or
GLES31.GL_FRAMEBUFFER_BARRIER_BIT,
)
GlesGpuScheduler.memoryBarrier()
checkGlError("clearSuperResolutionAccumulator")
clearRadianceAccumulatorImageBindings()
submitRadianceGpuCommands()
}
private fun accumulateRadianceFusionFrame(
isReference: Boolean,
sourceRegion: RadianceTileRect,
accumulatorRegion: RadianceTileRect,
rawRegionTexture: Int,
rgbTileTexture: Int,
frameFlowTexture: Int,
frameRobustnessTexture: Int,
frameTileMaskTexture: Int,
@@ -5308,10 +5359,55 @@ internal class GlesRawRadianceStacker(
fusionStatsCoreRegion: RadianceTileRect,
recordFusionRejections: Boolean,
) {
val passLabel = if (isReference) {
"reference fusion"
} else if (isLongFrame) {
"long fusion"
} else {
"normal fusion"
}
val accumulatorResources = radianceTextureResources(
radianceNrAccumulatorTexture,
radianceDetailAccumulatorTexture,
)
beginRadianceGpuPass(
passLabel,
reads = accumulatorResources + radianceTextureResources(
rgbTileTexture,
frameFlowTexture,
frameRobustnessTexture,
frameTileMaskTexture,
kernelTexture,
lensShadingTexture,
radianceReferenceBaseTexture,
rawRegionTexture,
if (visualizeRadianceFusionRejections) {
radianceFusionRejectionTexture
} else {
0
},
),
writes = accumulatorResources + radianceTextureResources(
if (visualizeRadianceFusionRejections) {
radianceFusionRejectionScratchTexture
} else {
0
},
if (visualizeRadianceLongParticipation) {
radianceLongParticipationTexture
} else {
0
},
) + if (logRadianceFusionParticipation) {
longArrayOf(GlesGpuScheduler.bufferResource(fusionStatsBuffer))
} else {
longArrayOf()
},
)
bindRadianceAccumulatorFramebuffer()
GLES30.glViewport(0, 0, accumulatorRegion.width, accumulatorRegion.height)
GLES30.glUseProgram(accumulateSuperResolutionProgram)
bindTexture(accumulateSuperResolutionProgram, "uRcdRgbTile", 0, radianceRgbTileTexture)
bindTexture(accumulateSuperResolutionProgram, "uRcdRgbTile", 0, rgbTileTexture)
bindTexture(accumulateSuperResolutionProgram, "uFlowGrid", 1, frameFlowTexture)
bindTexture(accumulateSuperResolutionProgram, "uRobustness", 2, frameRobustnessTexture)
bindTexture(accumulateSuperResolutionProgram, "uTileMask", 3, frameTileMaskTexture)
@@ -5327,7 +5423,7 @@ internal class GlesRawRadianceStacker(
accumulateSuperResolutionProgram,
"uRawRegion",
8,
rcdRawRegionTexture,
rawRegionTexture,
)
if (visualizeRadianceFusionRejections) {
bindTexture(
@@ -5543,22 +5639,7 @@ internal class GlesRawRadianceStacker(
GLES30.glDrawArrays(GLES30.GL_TRIANGLES, 0, 3)
GLES30.glDisable(GLES30.GL_BLEND)
GLES30.glBindFramebuffer(GLES30.GL_FRAMEBUFFER, 0)
GLES31.glMemoryBarrier(
GLES31.GL_FRAMEBUFFER_BARRIER_BIT or
GLES31.GL_TEXTURE_FETCH_BARRIER_BIT or
(if (visualizeRadianceFusionRejections ||
visualizeRadianceLongParticipation
) {
GLES31.GL_SHADER_IMAGE_ACCESS_BARRIER_BIT
} else {
0
}) or
(if (logRadianceFusionParticipation) {
GLES31.GL_SHADER_STORAGE_BARRIER_BIT
} else {
0
}),
)
GlesGpuScheduler.memoryBarrier()
checkGlError(
if (visualizeRadianceFusionRejections) {
"accumulateRadianceFusionFrame RGBA16F MRT with rejection ping-pong"
@@ -5566,6 +5647,8 @@ internal class GlesRawRadianceStacker(
"accumulateRadianceFusionFrame"
},
)
clearRadianceFrameSamplerBindings()
submitRadianceGpuCommands()
if (visualizeRadianceFusionRejections) {
val previousRejections = radianceFusionRejectionTexture
radianceFusionRejectionTexture = radianceFusionRejectionScratchTexture
@@ -5580,6 +5663,11 @@ internal class GlesRawRadianceStacker(
}
private fun captureRadianceReferenceBase(regionWidth: Int, regionHeight: Int) {
beginRadianceGpuPass(
"capture reference base",
reads = radianceTextureResources(radianceNrAccumulatorTexture),
writes = radianceTextureResources(radianceReferenceBaseTexture),
)
GLES31.glUseProgram(radianceReferenceBaseProgram)
bindTexture(
radianceReferenceBaseProgram,
@@ -5599,11 +5687,20 @@ internal class GlesRawRadianceStacker(
regionHeight,
)
GLES31.glDispatchCompute(groupCount(regionWidth), groupCount(regionHeight), 1)
GLES31.glMemoryBarrier(
GLES31.GL_SHADER_IMAGE_ACCESS_BARRIER_BIT or
GLES31.GL_TEXTURE_FETCH_BARRIER_BIT,
)
GlesGpuScheduler.memoryBarrier()
checkGlError("captureRadianceReferenceBase")
GLES31.glBindImageTexture(
0,
0,
0,
false,
0,
GLES31.GL_READ_ONLY,
GLES30.GL_RGBA16F,
)
GLES31.glActiveTexture(GLES31.GL_TEXTURE0)
GLES31.glBindTexture(GLES31.GL_TEXTURE_2D, 0)
submitRadianceGpuCommands()
}
private fun resetSuperResolutionDecisionStats() {
@@ -5910,7 +6007,23 @@ internal class GlesRawRadianceStacker(
requiredRcdHeight = max(requiredRcdHeight, highlightRegion.height)
}
}
ensureRadianceTileResources(requiredRcdWidth, requiredRcdHeight)
val participatingFrameCount = if (radianceUsesVgnSemanticBackend) {
1 +
acceptedFrames.size +
longAlignments.size +
if (highlightAlignment != null) 1 else 0
} else {
0
}
val requiredFrameSlotCount = minOf(
RADIANCE_PASS_WINDOW_SIZE,
participatingFrameCount,
)
ensureRadianceTileResources(
capacityWidth = requiredRcdWidth,
capacityHeight = requiredRcdHeight,
requiredFrameSlotCount = requiredFrameSlotCount,
)
val chromaPostprocessor = radianceVgnChromaPostprocessor
val readbackAllocStart = System.currentTimeMillis()
val readbackScratch = if (chromaPostprocessor == null) {
@@ -5985,15 +6098,22 @@ internal class GlesRawRadianceStacker(
}
clearSuperResolutionAccumulator()
val referenceRegion = radianceSourceRegion(tile, RadianceFlowBounds.Zero)
val referenceSlot = acquireRadianceFrameSlot(
"tile ${tile.index + 1}/${radianceTiles.size} reference",
)
reconstructRadianceReferenceTile(
image = referenceImage,
sourceRegion = referenceRegion,
frameSlot = referenceSlot,
label = "Radiance reference tile ${tile.index}",
)
accumulateRadianceFusionFrame(
isReference = true,
sourceRegion = referenceRegion,
accumulatorRegion = tile.outputWorking,
rawRegionTexture =
referenceSlot?.rawRegionTexture ?: rcdRawRegionTexture,
rgbTileTexture = radianceRgbTileTexture,
frameFlowTexture = flowTexture,
frameRobustnessTexture = robustnessTexture,
frameTileMaskTexture = tileMaskTexture,
@@ -6010,21 +6130,30 @@ internal class GlesRawRadianceStacker(
recordFusionRejections = false,
)
captureRadianceReferenceBase(tile.outputWorking.width, tile.outputWorking.height)
waitForRadianceGpuCheckpoint(
awaitRadianceFallbackInputReuse(
referenceSlot,
"tile ${tile.index + 1}/${radianceTiles.size} reference fused",
)
acceptedFrames.forEachIndexed { statsFrameIndex, frame ->
val sourceRegion = radianceSourceRegion(tile, frame.flowBounds())
val frameSlot = acquireRadianceFrameSlot(
"tile ${tile.index + 1}/${radianceTiles.size} " +
"normal frame ${frame.frameIndex}",
)
reconstructRadianceNonReferenceTile(
image = frame.image,
sourceRegion = sourceRegion,
frameSlot = frameSlot,
label = "Radiance frame ${frame.frameIndex} tile ${tile.index}",
)
accumulateRadianceFusionFrame(
isReference = false,
sourceRegion = sourceRegion,
accumulatorRegion = tile.outputWorking,
rawRegionTexture =
frameSlot?.rawRegionTexture ?: rcdRawRegionTexture,
rgbTileTexture = radianceRgbTileTexture,
frameFlowTexture = frame.flowTexture,
frameRobustnessTexture = frame.robustnessTexture,
frameTileMaskTexture = frame.tileMaskTexture,
@@ -6041,7 +6170,8 @@ internal class GlesRawRadianceStacker(
recordFusionRejections = rejectionNormalFrame != null &&
statsFrameIndex == rejectionFrameOrdinal,
)
waitForRadianceGpuCheckpoint(
awaitRadianceFallbackInputReuse(
frameSlot,
"tile ${tile.index + 1}/${radianceTiles.size} " +
"normal frame ${frame.frameIndex} fused",
)
@@ -6049,15 +6179,23 @@ internal class GlesRawRadianceStacker(
longAlignments.forEachIndexed { longIndex, alignment ->
val sourceRegion = radianceSourceRegion(tile, alignment.flowBounds())
val frameSlot = acquireRadianceFrameSlot(
"tile ${tile.index + 1}/${radianceTiles.size} " +
"long frame ${alignment.plan.sourceFrameIndex}",
)
reconstructRadianceNonReferenceTile(
image = alignment.plan.longFrame.image,
sourceRegion = sourceRegion,
frameSlot = frameSlot,
label = "Radiance long ${alignment.plan.sourceFrameIndex} tile ${tile.index}",
)
accumulateRadianceFusionFrame(
isReference = false,
sourceRegion = sourceRegion,
accumulatorRegion = tile.outputWorking,
rawRegionTexture =
frameSlot?.rawRegionTexture ?: rcdRawRegionTexture,
rgbTileTexture = radianceRgbTileTexture,
frameFlowTexture = alignment.flowTexture,
frameRobustnessTexture = alignment.robustnessTexture,
frameTileMaskTexture = alignment.tileMaskTexture,
@@ -6074,21 +6212,33 @@ internal class GlesRawRadianceStacker(
recordFusionRejections = rejectionLongFrame != null &&
longIndex == rejectionLongIndex,
)
waitForRadianceGpuCheckpoint(
awaitRadianceFallbackInputReuse(
frameSlot,
"tile ${tile.index + 1}/${radianceTiles.size} " +
"long frame ${alignment.plan.sourceFrameIndex} fused",
)
}
var highlightSlot: RadianceFrameSlot? = null
val highlightSourceRegion = highlightAlignment?.let { highlight ->
radianceSourceRegion(tile, highlight.flowBounds()).also { sourceRegion ->
highlightSlot = acquireRadianceFrameSlot(
"tile ${tile.index + 1}/${radianceTiles.size} highlight",
)
reconstructRadianceReferenceTile(
image = highlight.frame.shortFrame.image,
sourceRegion = sourceRegion,
frameSlot = highlightSlot,
label = "Radiance highlight tile ${tile.index}",
)
}
}
if (radianceUsesVgnSemanticBackend) {
check(nextRadianceFrameSlotIndex == participatingFrameCount) {
"Radiance tile consumed $nextRadianceFrameSlotIndex of " +
"$participatingFrameCount frame inputs"
}
}
normalizeRadianceTile(
tile,
@@ -6096,6 +6246,9 @@ internal class GlesRawRadianceStacker(
acceptedFusionFrameCount = if (hasRejectionFrame) 1 else 0,
highlightAlignment = highlightAlignment,
highlightSourceRegion = highlightSourceRegion,
highlightRgbTexture = highlightSourceRegion?.let {
radianceRgbTileTexture
},
)
if (chromaPostprocessor != null) {
chromaPostprocessor.markTileWritten(tile)
@@ -6108,13 +6261,12 @@ internal class GlesRawRadianceStacker(
totalGpuQueueWaitMs += timing.gpuQueueWaitMs
totalPixelTransferMs += timing.pixelTransferMs
totalCpuPackMs += timing.cpuPackMs
radiancePassWindow.clearAfterCheckpoint()
}
waitForRadianceGpuCheckpoint(
"tile ${tile.index + 1}/${radianceTiles.size} normalized",
)
resetRadianceFrameInputSlots()
}
if (chromaPostprocessor != null) {
GLES31.glMemoryBarrier(GLES31.GL_SHADER_IMAGE_ACCESS_BARRIER_BIT)
radiancePassWindow.drain("tiled reconstruction handoff")
}
gpuTimelineRecorder?.mark(GpuStackCompletionStage.TILED_RECONSTRUCTION)
if (logRadianceFusionParticipation) {
@@ -6226,11 +6378,17 @@ internal class GlesRawRadianceStacker(
private fun reconstructRadianceReferenceTile(
image: SafeImage,
sourceRegion: RadianceTileRect,
frameSlot: RadianceFrameSlot?,
label: String,
) {
uploadRcdRawRegion(image, sourceRegion, label)
val rawRegionTexture = frameSlot?.rawRegionTexture ?: rcdRawRegionTexture
uploadRcdRawRegion(image, sourceRegion, rawRegionTexture, label)
if (radianceUsesVgnSemanticBackend) {
runRadianceReferenceVgn(sourceRegion, label)
runRadianceReferenceVgn(
sourceRegion = sourceRegion,
frameSlot = checkNotNull(frameSlot),
label = label,
)
} else {
runRcdRegion(sourceRegion, label)
storeRcdRgbRegion(
@@ -6245,11 +6403,17 @@ internal class GlesRawRadianceStacker(
private fun reconstructRadianceNonReferenceTile(
image: SafeImage,
sourceRegion: RadianceTileRect,
frameSlot: RadianceFrameSlot?,
label: String,
) {
uploadRcdRawRegion(image, sourceRegion, label)
val rawRegionTexture = frameSlot?.rawRegionTexture ?: rcdRawRegionTexture
uploadRcdRawRegion(image, sourceRegion, rawRegionTexture, label)
if (radianceUsesVgnSemanticBackend) {
runRadianceSemanticProxy(sourceRegion, label)
runRadianceSemanticProxy(
sourceRegion = sourceRegion,
frameSlot = checkNotNull(frameSlot),
label = label,
)
} else {
runRcdRegion(sourceRegion, label)
storeRcdRgbRegion(
@@ -6300,7 +6464,7 @@ internal class GlesRawRadianceStacker(
}
private fun dispatchRadianceVgnPass(
program: Int,
programIndex: Int,
groupCountX: Int,
groupCountY: Int,
label: String,
@@ -6308,6 +6472,26 @@ internal class GlesRawRadianceStacker(
ubo: ByteBuffer? = null,
vararg images: RadianceVgnImageBinding,
) {
val imageReads = images
.filter { it.access != GLES31.GL_WRITE_ONLY }
.map { GlesGpuScheduler.textureResource(it.texture) }
val imageWrites = images
.filter { it.access != GLES31.GL_READ_ONLY }
.map { GlesGpuScheduler.textureResource(it.texture) }
val uboId = if (uboBinding != null && ubo != null) {
val id = radianceVgnUbos[nextRadianceVgnUboIndex % radianceVgnUbos.size]
nextRadianceVgnUboIndex += 1
id
} else {
0
}
val uboResource = GlesGpuScheduler.bufferResource(uboId)
beginRadianceGpuPass(
label,
reads = (imageReads + uboResource).filter { it != 0L }.toLongArray(),
writes = (imageWrites + uboResource).filter { it != 0L }.toLongArray(),
)
val program = radianceVgnPrograms[programIndex]
check(program != 0) { "Radiance VGN program unavailable: $label" }
GLES31.glUseProgram(program)
images.forEach { image ->
@@ -6322,39 +6506,149 @@ internal class GlesRawRadianceStacker(
)
}
if (uboBinding != null && ubo != null) {
check(radianceVgnUbo != 0) { "Radiance VGN UBO is unavailable" }
GLES31.glBindBuffer(GLES31.GL_UNIFORM_BUFFER, radianceVgnUbo)
check(uboId != 0) { "Radiance VGN pass UBO is unavailable: $label" }
GLES31.glBindBuffer(GLES31.GL_UNIFORM_BUFFER, uboId)
GLES31.glBufferData(
GLES31.GL_UNIFORM_BUFFER,
ubo.remaining(),
ubo,
GLES31.GL_DYNAMIC_DRAW,
)
GLES31.glBindBufferBase(GLES31.GL_UNIFORM_BUFFER, uboBinding, radianceVgnUbo)
GLES31.glBindBufferBase(GLES31.GL_UNIFORM_BUFFER, uboBinding, uboId)
GLES31.glBindBuffer(GLES31.GL_UNIFORM_BUFFER, 0)
}
GLES31.glDispatchCompute(groupCountX.coerceAtLeast(1), groupCountY.coerceAtLeast(1), 1)
// Radiance repeatedly reuses the same VGN images and UBO for every frame in every tile.
// A memory barrier only establishes visibility; the checkpoint also bounds the
// background compute queue before those resources are updated by the next pass.
GLES31.glMemoryBarrier(GLES31.GL_ALL_BARRIER_BITS)
GlesGpuScheduler.memoryBarrier()
checkGlError("Radiance VGN $label")
waitForRadianceGpuCheckpoint("VGN $label")
clearRadianceVgnBindings()
submitRadianceGpuCommands()
}
private fun clearRadianceVgnBindings() {
for (unit in 0..5) {
GLES31.glBindImageTexture(
unit,
0,
0,
false,
0,
GLES31.GL_READ_ONLY,
GLES30.GL_RGBA16F,
)
}
for (binding in intArrayOf(2, 4, 5)) {
GLES31.glBindBufferBase(GLES31.GL_UNIFORM_BUFFER, binding, 0)
}
for (unit in 0..1) {
GLES31.glActiveTexture(GLES31.GL_TEXTURE0 + unit)
GLES31.glBindTexture(GLES31.GL_TEXTURE_2D, 0)
}
GLES31.glActiveTexture(GLES31.GL_TEXTURE0)
}
private fun clearRadianceFrameSamplerBindings() {
for (unit in 6..7) {
GLES31.glBindImageTexture(
unit,
0,
0,
false,
0,
GLES31.GL_READ_ONLY,
GLES30.GL_RGBA16F,
)
}
for (unit in 0..8) {
GLES31.glActiveTexture(GLES31.GL_TEXTURE0 + unit)
GLES31.glBindTexture(GLES31.GL_TEXTURE_2D, 0)
}
GLES31.glBindBufferBase(
GLES31.GL_SHADER_STORAGE_BUFFER,
RADIANCE_FUSION_STATS_BUFFER_BINDING,
0,
)
GLES31.glActiveTexture(GLES31.GL_TEXTURE0)
}
private fun clearRadianceAccumulatorImageBindings() {
for (unit in intArrayOf(0, 1, 6, 7)) {
GLES31.glBindImageTexture(
unit,
0,
0,
false,
0,
GLES31.GL_READ_ONLY,
GLES30.GL_RGBA16F,
)
}
}
private fun clearRadianceNormalizeSamplerBindings() {
for (unit in intArrayOf(0, 1, 2, 7, 8, 10, 11, 12)) {
GLES31.glActiveTexture(GLES31.GL_TEXTURE0 + unit)
GLES31.glBindTexture(GLES31.GL_TEXTURE_2D, 0)
}
GLES31.glActiveTexture(GLES31.GL_TEXTURE0)
}
private fun beginRadianceGpuPass(
label: String,
reads: LongArray = longArrayOf(),
writes: LongArray = longArrayOf(),
) {
radiancePassWindow.beginPass(label, reads, writes)
}
private fun radianceTextureResources(vararg textures: Int): LongArray {
return textures
.map(GlesGpuScheduler::textureResource)
.filter { it != 0L }
.toLongArray()
}
private fun submitRadianceGpuCommands() {
radiancePassWindow.endPass()
}
private fun waitForRadianceGpuCheckpoint(label: String) {
val startNs = System.nanoTime()
/*RawStackRuntimeDebug.d(TAG) {
"Radiance GPU checkpoint waiting label=$label"
}*/
GlesGpuScheduler.waitForGpuCheckpoint(TAG, "Radiance $label")
/*RawStackRuntimeDebug.d(TAG) {
"Radiance GPU checkpoint complete label=$label " +
"elapsedMs=${(System.nanoTime() - startNs) / 1_000_000L}"
}*/
}
private fun runRadianceReferenceVgn(sourceRegion: RadianceTileRect, label: String) {
private fun acquireRadianceFrameSlot(label: String): RadianceFrameSlot? {
if (!radianceUsesVgnSemanticBackend) return null
check(radianceFrameSlots.isNotEmpty()) {
"Radiance frame input ring is unavailable before $label"
}
val slot = radianceFrameSlots[nextRadianceFrameSlotIndex % radianceFrameSlots.size]
radiancePassWindow.awaitResources(
"reuse frame input slot ${slot.index} for $label",
radianceTextureResources(slot.rawRegionTexture),
)
nextRadianceFrameSlotIndex += 1
return slot
}
private fun awaitRadianceFallbackInputReuse(
slot: RadianceFrameSlot?,
label: String,
) {
if (slot == null) {
waitForRadianceGpuCheckpoint(label)
radiancePassWindow.clearAfterCheckpoint()
}
}
private fun resetRadianceFrameInputSlots() {
nextRadianceFrameSlotIndex = 0
}
private fun runRadianceReferenceVgn(
sourceRegion: RadianceTileRect,
frameSlot: RadianceFrameSlot,
label: String,
) {
clearRadianceVgnBindings()
val geometry = RadianceVgnGeometry.forRegion(
sourceRegion.width,
sourceRegion.height,
@@ -6377,9 +6671,17 @@ internal class GlesRawRadianceStacker(
val edgeThreshold = 50
val vngThreshold = 400
beginRadianceGpuPass(
"$label VGN prepare",
reads = radianceTextureResources(
frameSlot.rawRegionTexture,
lensShadingTexture,
),
writes = radianceTextureResources(radianceVgnPackedFloatTexture),
)
val prepare = radianceVgnPrograms[VgnShaders.PROGRAM_PREPARE]
GLES31.glUseProgram(prepare)
bindTexture(prepare, "uRawRegion", 0, rcdRawRegionTexture)
bindTexture(prepare, "uRawRegion", 0, frameSlot.rawRegionTexture)
bindTexture(prepare, "uLensShadingMap", 1, lensShadingTexture)
GLES31.glUniform2i(
uniformLocation(prepare, "uRegionSize"),
@@ -6414,12 +6716,13 @@ internal class GlesRawRadianceStacker(
GLES31.glUniform1i(uniformLocation(prepare, "uReconstructHighlights"), 1)
bindImage(0, radianceVgnPackedFloatTexture, GLES31.GL_WRITE_ONLY, GLES30.GL_RGBA16F)
GLES31.glDispatchCompute(groupsPackedX, groupsWorkY, 1)
GLES31.glMemoryBarrier(GLES31.GL_ALL_BARRIER_BITS)
GlesGpuScheduler.memoryBarrier()
checkGlError("$label VGN prepare")
waitForRadianceGpuCheckpoint("$label VGN prepare")
clearRadianceVgnBindings()
submitRadianceGpuCommands()
dispatchRadianceVgnPass(
radianceVgnPrograms[VgnShaders.PROGRAM_NEUTRAL],
VgnShaders.PROGRAM_NEUTRAL,
groupsPackedX,
groupsWorkY,
"$label neutral",
@@ -6443,7 +6746,7 @@ internal class GlesRawRadianceStacker(
),
)
dispatchRadianceVgnPass(
radianceVgnPrograms[VgnShaders.PROGRAM_0A1],
VgnShaders.PROGRAM_0A1,
groupsPackedX,
groupsWorkY,
"$label pass 0A1",
@@ -6463,7 +6766,7 @@ internal class GlesRawRadianceStacker(
),
)
dispatchRadianceVgnPass(
radianceVgnPrograms[VgnShaders.PROGRAM_0A2],
VgnShaders.PROGRAM_0A2,
groupsWorkX,
groupsHalfHeight,
"$label pass 0A2",
@@ -6487,7 +6790,7 @@ internal class GlesRawRadianceStacker(
),
)
dispatchRadianceVgnPass(
radianceVgnPrograms[VgnShaders.PROGRAM_0B],
VgnShaders.PROGRAM_0B,
groupsPackedX,
groupsHalfHeight,
"$label pass 0B",
@@ -6507,7 +6810,7 @@ internal class GlesRawRadianceStacker(
),
)
dispatchRadianceVgnPass(
radianceVgnPrograms[VgnShaders.PROGRAM_0C],
VgnShaders.PROGRAM_0C,
groupsPackedX,
groupsWorkY,
"$label pass 0C",
@@ -6527,7 +6830,7 @@ internal class GlesRawRadianceStacker(
),
)
dispatchRadianceVgnPass(
radianceVgnPrograms[VgnShaders.PROGRAM_1],
VgnShaders.PROGRAM_1,
groupsWorkX,
groupsWorkY,
"$label pass 1",
@@ -6572,7 +6875,7 @@ internal class GlesRawRadianceStacker(
),
)
dispatchRadianceVgnPass(
radianceVgnPrograms[VgnShaders.PROGRAM_2],
VgnShaders.PROGRAM_2,
groupsWorkX,
groupsWorkY,
"$label pass 2",
@@ -6597,7 +6900,7 @@ internal class GlesRawRadianceStacker(
),
)
dispatchRadianceVgnPass(
radianceVgnPrograms[VgnShaders.PROGRAM_3],
VgnShaders.PROGRAM_3,
groupsWorkX,
groupsWorkY,
"$label pass 3",
@@ -6636,6 +6939,11 @@ internal class GlesRawRadianceStacker(
),
)
beginRadianceGpuPass(
"$label VGN camera RGB",
reads = radianceTextureResources(radianceVgnFull0Texture),
writes = radianceTextureResources(radianceRgbTileTexture),
)
GLES31.glUseProgram(radianceVgnFinalProgram)
GLES31.glUniform2i(
uniformLocation(radianceVgnFinalProgram, "uOutputSize"),
@@ -6666,15 +6974,29 @@ internal class GlesRawRadianceStacker(
GLES30.GL_RGBA16F,
)
GLES31.glDispatchCompute(groupCount(sourceRegion.width), groupCount(sourceRegion.height), 1)
GLES31.glMemoryBarrier(GLES31.GL_ALL_BARRIER_BITS)
GlesGpuScheduler.memoryBarrier()
checkGlError("$label VGN camera RGB")
waitForRadianceGpuCheckpoint("$label VGN camera RGB")
clearRadianceVgnBindings()
submitRadianceGpuCommands()
}
private fun runRadianceSemanticProxy(sourceRegion: RadianceTileRect, label: String) {
private fun runRadianceSemanticProxy(
sourceRegion: RadianceTileRect,
frameSlot: RadianceFrameSlot,
label: String,
) {
clearRadianceVgnBindings()
val seed = radianceSemanticSeedProgram
beginRadianceGpuPass(
"$label semantic seed",
reads = radianceTextureResources(
frameSlot.rawRegionTexture,
lensShadingTexture,
),
writes = radianceTextureResources(radianceSemanticSeedTexture),
)
GLES31.glUseProgram(seed)
bindTexture(seed, "uRawRegion", 0, rcdRawRegionTexture)
bindTexture(seed, "uRawRegion", 0, frameSlot.rawRegionTexture)
bindTexture(seed, "uLensShadingMap", 1, lensShadingTexture)
GLES31.glUniform2i(
uniformLocation(seed, "uRegionSize"),
@@ -6703,11 +7025,17 @@ internal class GlesRawRadianceStacker(
GLES30.GL_RGBA16F,
)
GLES31.glDispatchCompute(groupCount(sourceRegion.width), groupCount(sourceRegion.height), 1)
GLES31.glMemoryBarrier(GLES31.GL_ALL_BARRIER_BITS)
GlesGpuScheduler.memoryBarrier()
checkGlError("$label semantic seed")
waitForRadianceGpuCheckpoint("$label semantic seed")
clearRadianceVgnBindings()
submitRadianceGpuCommands()
val resolve = radianceSemanticResolveProgram
beginRadianceGpuPass(
"$label semantic resolve",
reads = radianceTextureResources(radianceSemanticSeedTexture),
writes = radianceTextureResources(radianceRgbTileTexture),
)
GLES31.glUseProgram(resolve)
GLES31.glUniform2i(
uniformLocation(resolve, "uRegionSize"),
@@ -6734,9 +7062,10 @@ internal class GlesRawRadianceStacker(
GLES30.GL_RGBA16F,
)
GLES31.glDispatchCompute(groupCount(sourceRegion.width), groupCount(sourceRegion.height), 1)
GLES31.glMemoryBarrier(GLES31.GL_ALL_BARRIER_BITS)
GlesGpuScheduler.memoryBarrier()
checkGlError("$label semantic resolve")
waitForRadianceGpuCheckpoint("$label semantic resolve")
clearRadianceVgnBindings()
submitRadianceGpuCommands()
}
private fun normalizeRadianceTile(
@@ -6745,8 +7074,10 @@ internal class GlesRawRadianceStacker(
acceptedFusionFrameCount: Int,
highlightAlignment: RadianceHighlightAlignment?,
highlightSourceRegion: RadianceTileRect?,
highlightRgbTexture: Int?,
) {
require((highlightAlignment == null) == (highlightSourceRegion == null))
require((highlightAlignment == null) == (highlightRgbTexture == null))
val program = if (highlightAlignment != null) {
check(radianceHighlightNormalizeProgram != 0)
radianceHighlightNormalizeProgram
@@ -6754,6 +7085,28 @@ internal class GlesRawRadianceStacker(
normalizeSuperResolutionProgram
}
val chromaTarget = radianceVgnChromaPostprocessor?.normalizationTargetTexture()
beginRadianceGpuPass(
"normalize tile ${tile.index + 1}",
reads = radianceTextureResources(
radianceNrAccumulatorTexture,
radianceDetailAccumulatorTexture,
radianceReferenceBaseTexture,
if (visualizeRadianceFusionRejections) {
radianceFusionRejectionTexture
} else {
0
},
if (visualizeRadianceLongParticipation) {
radianceLongParticipationTexture
} else {
0
},
highlightRgbTexture ?: 0,
highlightAlignment?.flowTexture ?: 0,
if (highlightAlignment != null) refRaw else 0,
),
writes = radianceTextureResources(chromaTarget ?: outputTexture),
)
bindFramebufferOutput(chromaTarget ?: outputTexture, "normalizeRadianceTile")
if (chromaTarget != null) {
GLES30.glViewport(
@@ -6820,7 +7173,7 @@ internal class GlesRawRadianceStacker(
)
}
if (highlightAlignment != null && highlightSourceRegion != null) {
bindTexture(program, "uHighlightRgb", 8, radianceRgbTileTexture)
bindTexture(program, "uHighlightRgb", 8, checkNotNull(highlightRgbTexture))
bindTexture(program, "uHighlightFlow", 10, highlightAlignment.flowTexture)
bindTexture(program, "uReferenceRaw", 11, refRaw)
GLES31.glUniform2i(
@@ -6852,6 +7205,8 @@ internal class GlesRawRadianceStacker(
setRadianceNormalizeUniforms(program)
GLES30.glDrawArrays(GLES30.GL_TRIANGLES, 0, 3)
finishFramebufferPass("normalizeRadianceTile ${tile.index}")
clearRadianceNormalizeSamplerBindings()
submitRadianceGpuCommands()
}
private fun setRadianceNormalizeUniforms(program: Int = normalizeSuperResolutionProgram) {
@@ -8017,8 +8372,11 @@ internal class GlesRawRadianceStacker(
private fun release() {
if (eglDisplay != EGL14.EGL_NO_DISPLAY) {
radiancePassWindow.drain("Radiance release")
radianceVgnChromaPostprocessor?.release()
radianceVgnChromaPostprocessor = null
resetRadianceFrameInputSlots()
radianceFrameSlots.clear()
if (programs.isNotEmpty()) {
for (program in programs) {
GLES30.glDeleteProgram(program)
@@ -8060,6 +8418,7 @@ internal class GlesRawRadianceStacker(
private const val TAG = "GlesRawRadianceStacker"
private const val EGL_OPENGL_ES3_BIT_KHR = 0x00000040
private const val RADIANCE_PASS_WINDOW_SIZE = 2
private const val LOCAL_SIZE = GlesComputeWorkGroup.IMAGE_TILE_SIZE
private const val RAW_BYTES_PER_PIXEL = 2
private const val PREWARM_TRACKING_SCALE = 4
@@ -238,6 +238,8 @@ class RawDemosaicProcessor {
// It is also above the native level-35 gate, so the complete IIR2 pass 1/2/3 chain runs.
private const val VGN_COLOR_NOISE_LEVEL = 50
private const val VGN_ADVANCED_COLOR_NOISE_ENABLED = true
private const val VGN_DISPATCH_UBO_SLOT_COUNT = 2
private const val VGN_PASS_WINDOW_SIZE = 2
private const val RAW_TILE_CORE_EDGE_PX = 3072
private const val RAW_PREWARM_CORE_EDGE_PX = 2048
// Phocus GetStripMargin(50) returns 60 pixels for gradient/color-noise interpolation.
@@ -855,6 +857,7 @@ class RawDemosaicProcessor {
private var rcdStep43Program = 0
private var rcdWriteOutputProgram = 0
private val vgnPrograms = IntArray(VgnShaders.PROGRAM_SOURCES.size)
private var activeVgnPassWindow: GlesGpuScheduler.PassWindow? = null
private var quadPopulateProgram = 0
private var quadGreenProgram = 0
private var quadChromaProgram = 0
@@ -6554,6 +6557,7 @@ class RawDemosaicProcessor {
)
finishLinearRawUint16ToFloat(
"LinearRaw RGBA16UI to RGBA16F ${width}x$height",
waitForCpuReuse = false,
)
return
}
@@ -6612,6 +6616,7 @@ class RawDemosaicProcessor {
)
finishLinearRawUint16ToFloat(
"LinearRaw RGB16UI to RGBA16F rows=$sourceY..${sourceY + rowCount}",
waitForCpuReuse = true,
)
sourceY += rowCount
}
@@ -6701,8 +6706,15 @@ class RawDemosaicProcessor {
GLES31.glDispatchCompute(GlesComputeWorkGroup.imageGroupCount(width), GlesComputeWorkGroup.imageGroupCount(rowCount), 1)
}
private fun finishLinearRawUint16ToFloat(label: String) {
GLES31.glMemoryBarrier(GLES31.GL_ALL_BARRIER_BITS)
private fun finishLinearRawUint16ToFloat(
label: String,
waitForCpuReuse: Boolean,
) {
GLES31.glMemoryBarrier(
GLES31.GL_SHADER_IMAGE_ACCESS_BARRIER_BIT or
GLES31.GL_TEXTURE_FETCH_BARRIER_BIT or
GLES31.GL_FRAMEBUFFER_BARRIER_BIT
)
GLES31.glBindImageTexture(
0,
0,
@@ -6722,6 +6734,7 @@ class RawDemosaicProcessor {
GLES31.GL_RGBA16F
)
checkGlError(label)
if (!waitForCpuReuse) return
val startNs = System.nanoTime()
PLog.d(TAG, "RAW GPU checkpoint waiting label=$label")
GlesGpuScheduler.waitForGpuCheckpoint(TAG, label)
@@ -7046,6 +7059,25 @@ class RawDemosaicProcessor {
ubo: ByteBuffer? = null,
vararg images: VgnImageBinding,
) {
val passWindow = checkNotNull(activeVgnPassWindow) {
"VGN pass window is unavailable for $label"
}
val imageReads = images
.filter { it.access != GLES31.GL_WRITE_ONLY }
.map { GlesGpuScheduler.textureResource(it.texture) }
val imageWrites = images
.filter { it.access != GLES31.GL_READ_ONLY }
.map { GlesGpuScheduler.textureResource(it.texture) }
val uboResource = if (uboBinding != null && ubo != null) {
GlesGpuScheduler.bufferResource(uboId)
} else {
0L
}
passWindow.beginPass(
label,
reads = (imageReads + uboResource).filter { it != 0L }.toLongArray(),
writes = (imageWrites + uboResource).filter { it != 0L }.toLongArray(),
)
val program = vgnPrograms[programIndex]
check(program != 0) { "VGN program unavailable: $label" }
GLES31.glUseProgram(program)
@@ -7072,12 +7104,13 @@ class RawDemosaicProcessor {
GLES31.glBindBuffer(GLES31.GL_UNIFORM_BUFFER, 0)
}
GLES31.glDispatchCompute(groupCountX.coerceAtLeast(1), groupCountY.coerceAtLeast(1), 1)
GLES31.glMemoryBarrier(GLES31.GL_ALL_BARRIER_BITS)
GlesGpuScheduler.memoryBarrier()
checkGlError("VGN $label")
// Bound the background compute queue to one full-resolution pass. This provides an
// inter-context scheduling point for RenderThread/SurfaceFlinger and lets the driver
// reclaim VGN intermediates as soon as their last pass has completed.
GlesGpuScheduler.waitForGpuCheckpoint(TAG, "VGN $label")
unbindVgnImages()
if (uboBinding != null) {
GLES31.glBindBufferBase(GLES31.GL_UNIFORM_BUFFER, uboBinding, 0)
}
passWindow.endPass()
}
private fun unbindVgnImages() {
@@ -7188,9 +7221,18 @@ class RawDemosaicProcessor {
}
}
val uboIds = IntArray(1)
GLES31.glGenBuffers(1, uboIds, 0)
check(uboIds[0] != 0) { "Failed to allocate VGN UBO" }
val uboIds = IntArray(VGN_DISPATCH_UBO_SLOT_COUNT)
GLES31.glGenBuffers(uboIds.size, uboIds, 0)
check(uboIds.all { it != 0 }) { "Failed to allocate VGN dispatch UBO ring" }
var nextUboIndex = 0
fun nextVgnUboId(): Int {
val uboId = uboIds[nextUboIndex % uboIds.size]
nextUboIndex += 1
return uboId
}
check(activeVgnPassWindow == null) { "Nested VGN pass windows are unsupported" }
val passWindow = GlesGpuScheduler.PassWindow(TAG, VGN_PASS_WINDOW_SIZE)
activeVgnPassWindow = passWindow
try {
val packedFloat = allocate(GLES30.GL_RGBA16F, packedWidth, workHeight, "packed float")
@@ -7202,6 +7244,18 @@ class RawDemosaicProcessor {
val full0 = allocate(GLES30.GL_RGBA16UI, workWidth, workHeight, "full 0")
val full1 = allocate(GLES30.GL_RGBA16UI, workWidth, workHeight, "full 1")
unbindVgnImages()
for (binding in 2..5) {
GLES31.glBindBufferBase(GLES31.GL_UNIFORM_BUFFER, binding, 0)
}
passWindow.beginPass(
"prepare packed RAW",
reads = longArrayOf(
GlesGpuScheduler.textureResource(rawTextureId),
GlesGpuScheduler.textureResource(lensShadingTextureId),
),
writes = longArrayOf(GlesGpuScheduler.textureResource(packedFloat)),
)
val prepareProgram = vgnPrograms[VgnShaders.PROGRAM_PREPARE]
GLES31.glUseProgram(prepareProgram)
GLES31.glActiveTexture(GLES31.GL_TEXTURE0 + RCD_RAW_TEXTURE_UNIT)
@@ -7279,16 +7333,17 @@ class RawDemosaicProcessor {
GLES30.GL_RGBA16F,
)
GLES31.glDispatchCompute(groupsPackedX, groupsWorkY, 1)
GLES31.glMemoryBarrier(GLES31.GL_ALL_BARRIER_BITS)
GlesGpuScheduler.memoryBarrier()
checkGlError("VGN prepare packed RAW")
GlesGpuScheduler.waitForGpuCheckpoint(TAG, "VGN prepare packed RAW")
unbindVgnImages()
passWindow.endPass()
dispatchVgnPass(
VgnShaders.PROGRAM_NEUTRAL,
groupsPackedX,
groupsWorkY,
"neutral",
uboIds[0],
nextVgnUboId(),
2,
vgnUbo(48) {
putInt(0); putInt(0); putInt(packedWidth); putInt(workHeight)
@@ -7304,7 +7359,7 @@ class RawDemosaicProcessor {
groupsPackedX,
groupsWorkY,
"pass 0A1",
uboIds[0],
nextVgnUboId(),
2,
vgnBoundsUbo(0, 1, packedWidth - 1, workHeight - 1),
VgnImageBinding(0, packedBayer, GLES31.GL_READ_ONLY, GLES30.GL_RGBA16UI),
@@ -7316,7 +7371,7 @@ class RawDemosaicProcessor {
groupsWorkX,
groupsHalfHeight,
"pass 0A2",
uboIds[0],
nextVgnUboId(),
2,
vgnUbo(32) {
putInt(0); putInt(1); putInt(packedWidth - 1); putInt((workHeight - 2) / 2)
@@ -7331,7 +7386,7 @@ class RawDemosaicProcessor {
groupsPackedX,
groupsHalfHeight,
"pass 0B",
uboIds[0],
nextVgnUboId(),
2,
vgnBoundsUbo(1, 0, packedWidth - 1, workHeight - 4),
VgnImageBinding(0, scaleTexture, GLES31.GL_READ_ONLY, GLES30.GL_RGBA16F),
@@ -7343,7 +7398,7 @@ class RawDemosaicProcessor {
groupsPackedX,
groupsWorkY,
"pass 0C",
uboIds[0],
nextVgnUboId(),
2,
vgnBoundsUbo(0, 1, packedWidth - 1, workHeight - 1),
VgnImageBinding(0, packedSmooth, GLES31.GL_READ_ONLY, GLES30.GL_RGBA16UI),
@@ -7355,7 +7410,7 @@ class RawDemosaicProcessor {
groupsWorkX,
groupsWorkY,
"pass 1",
uboIds[0],
nextVgnUboId(),
5,
vgnThresholdBoundsUbo(
12,
@@ -7377,7 +7432,7 @@ class RawDemosaicProcessor {
groupsWorkX,
groupsWorkY,
"pass 2",
uboIds[0],
nextVgnUboId(),
2,
vgnBoundsUbo(13, 13, workWidth - 13, workHeight - 13),
VgnImageBinding(0, full0, GLES31.GL_READ_ONLY, GLES30.GL_RGBA16UI),
@@ -7389,7 +7444,7 @@ class RawDemosaicProcessor {
groupsWorkX,
groupsWorkY,
"pass 3",
uboIds[0],
nextVgnUboId(),
4,
vgnThresholdBoundsUbo(
16,
@@ -7406,6 +7461,17 @@ class RawDemosaicProcessor {
)
unbindVgnImages()
passWindow.awaitResources(
"release packed VGN intermediates",
longArrayOf(
GlesGpuScheduler.textureResource(packedFloat),
GlesGpuScheduler.textureResource(packedSmooth),
GlesGpuScheduler.textureResource(scaleTexture),
GlesGpuScheduler.textureResource(medianTexture),
GlesGpuScheduler.textureResource(edgeTexture),
GlesGpuScheduler.textureResource(packedBayer),
),
)
releaseTexture(packedFloat)
releaseTexture(packedSmooth)
releaseTexture(scaleTexture)
@@ -7420,7 +7486,7 @@ class RawDemosaicProcessor {
groupsWorkX,
groupsWorkY,
"color noise 1",
uboIds[0],
nextVgnUboId(),
2,
vgnBoundsUbo(8, 8, workWidth - 8, workHeight - 8),
VgnImageBinding(0, full0, GLES31.GL_READ_ONLY, GLES30.GL_RGBA16UI),
@@ -7432,7 +7498,7 @@ class RawDemosaicProcessor {
groupsWorkX,
groupsWorkY,
"color noise 2",
uboIds[0],
nextVgnUboId(),
2,
vgnBoundsUbo(8, 8, workWidth - 8, workHeight - 8),
VgnImageBinding(0, full1, GLES31.GL_READ_ONLY, GLES30.GL_RGBA16UI),
@@ -7447,7 +7513,7 @@ class RawDemosaicProcessor {
groupsWorkX,
groupsWorkY,
"color noise 3 YCCD",
uboIds[0],
nextVgnUboId(),
4,
vgnBoundsUbo(12, 12, workWidth - 12, workHeight - 12),
VgnImageBinding(0, full1, GLES31.GL_READ_ONLY, GLES30.GL_RGBA16UI),
@@ -7461,7 +7527,7 @@ class RawDemosaicProcessor {
1,
workHeight,
"IIR2 pass 1 init",
uboIds[0],
nextVgnUboId(),
3,
vgnIirUbo(workWidth, workHeight, 0, 0, vgnIirPass1Coefficients),
VgnImageBinding(0, full0, GLES31.GL_READ_ONLY, GLES30.GL_RGBA16UI),
@@ -7472,7 +7538,7 @@ class RawDemosaicProcessor {
VgnShaders.PROGRAM_IIR2_1,
full2,
full3,
uboIds[0],
nextVgnUboId(),
workWidth,
workHeight,
1,
@@ -7484,7 +7550,7 @@ class RawDemosaicProcessor {
VgnShaders.PROGRAM_IIR2_1,
full3,
full2,
uboIds[0],
nextVgnUboId(),
workWidth,
workHeight,
0,
@@ -7496,7 +7562,7 @@ class RawDemosaicProcessor {
VgnShaders.PROGRAM_IIR2_1,
full2,
full3,
uboIds[0],
nextVgnUboId(),
workWidth,
workHeight,
1,
@@ -7510,7 +7576,7 @@ class RawDemosaicProcessor {
groupsWorkX,
groupsWorkY,
"calculate color noise error",
uboIds[0],
nextVgnUboId(),
images = arrayOf(
VgnImageBinding(0, full0, GLES31.GL_READ_ONLY, GLES30.GL_RGBA16UI),
VgnImageBinding(1, full3, GLES31.GL_READ_ONLY, GLES30.GL_RGBA16UI),
@@ -7518,16 +7584,16 @@ class RawDemosaicProcessor {
),
)
runVgnIirPass(VgnShaders.PROGRAM_IIR2_2, full2, full3, uboIds[0], workWidth,
runVgnIirPass(VgnShaders.PROGRAM_IIR2_2, full2, full3, nextVgnUboId(), workWidth,
workHeight, 0, 0, vgnIirPass1Coefficients,
"IIR2 pass 2 horizontal forward")
runVgnIirPass(VgnShaders.PROGRAM_IIR2_2, full3, full2, uboIds[0], workWidth,
runVgnIirPass(VgnShaders.PROGRAM_IIR2_2, full3, full2, nextVgnUboId(), workWidth,
workHeight, 1, 0, vgnIirPass1Coefficients,
"IIR2 pass 2 horizontal reverse")
runVgnIirPass(VgnShaders.PROGRAM_IIR2_2, full2, full3, uboIds[0], workWidth,
runVgnIirPass(VgnShaders.PROGRAM_IIR2_2, full2, full3, nextVgnUboId(), workWidth,
workHeight, 0, 1, vgnIirPass1Coefficients,
"IIR2 pass 2 vertical forward")
runVgnIirPass(VgnShaders.PROGRAM_IIR2_2, full3, full2, uboIds[0], workWidth,
runVgnIirPass(VgnShaders.PROGRAM_IIR2_2, full3, full2, nextVgnUboId(), workWidth,
workHeight, 1, 1, vgnIirPass1Coefficients,
"IIR2 pass 2 vertical reverse")
@@ -7536,7 +7602,7 @@ class RawDemosaicProcessor {
groupsWorkX,
groupsWorkY,
"color noise filter",
uboIds[0],
nextVgnUboId(),
images = arrayOf(
VgnImageBinding(0, full0, GLES31.GL_READ_ONLY, GLES30.GL_RGBA16UI),
VgnImageBinding(1, full1, GLES31.GL_WRITE_ONLY, GLES30.GL_RGBA16UI),
@@ -7544,16 +7610,16 @@ class RawDemosaicProcessor {
),
)
runVgnIirPass(VgnShaders.PROGRAM_IIR2_3, full1, full0, uboIds[0], workWidth,
runVgnIirPass(VgnShaders.PROGRAM_IIR2_3, full1, full0, nextVgnUboId(), workWidth,
workHeight, 0, 0, vgnIirPass3Coefficients,
"IIR2 pass 3 horizontal forward")
runVgnIirPass(VgnShaders.PROGRAM_IIR2_3, full0, full1, uboIds[0], workWidth,
runVgnIirPass(VgnShaders.PROGRAM_IIR2_3, full0, full1, nextVgnUboId(), workWidth,
workHeight, 1, 0, vgnIirPass3Coefficients,
"IIR2 pass 3 horizontal reverse")
runVgnIirPass(VgnShaders.PROGRAM_IIR2_3, full1, full0, uboIds[0], workWidth,
runVgnIirPass(VgnShaders.PROGRAM_IIR2_3, full1, full0, nextVgnUboId(), workWidth,
workHeight, 0, 1, vgnIirPass3Coefficients,
"IIR2 pass 3 vertical forward")
runVgnIirPass(VgnShaders.PROGRAM_IIR2_3, full0, full1, uboIds[0], workWidth,
runVgnIirPass(VgnShaders.PROGRAM_IIR2_3, full0, full1, nextVgnUboId(), workWidth,
workHeight, 1, 1, vgnIirPass3Coefficients,
"IIR2 pass 3 vertical reverse")
@@ -7562,7 +7628,7 @@ class RawDemosaicProcessor {
groupsOutputX,
groupsOutputY,
"YUV to RGB",
uboIds[0],
nextVgnUboId(),
2,
vgnUbo(32) {
putInt(roiLeft); putInt(roiTop); putInt(roiRight); putInt(roiBottom)
@@ -7581,7 +7647,7 @@ class RawDemosaicProcessor {
groupsOutputX,
groupsOutputY,
"color noise 3 RGB",
uboIds[0],
nextVgnUboId(),
3,
vgnUbo(32) {
putInt(roiLeft); putInt(roiTop); putInt(roiRight); putInt(roiBottom)
@@ -7595,6 +7661,15 @@ class RawDemosaicProcessor {
PLog.d(TAG, "Single-frame VGN color-noise IIR chain disabled")
}
passWindow.beginPass(
"composite camera RGB",
reads = longArrayOf(
GlesGpuScheduler.textureResource(linearOutputTextureId),
),
writes = longArrayOf(
GlesGpuScheduler.textureResource(demosaicTextureId),
),
)
val compositeProgram = vgnPrograms[VgnShaders.PROGRAM_COMPOSITE]
GLES31.glUseProgram(compositeProgram)
GLES31.glUniform2i(
@@ -7613,8 +7688,11 @@ class RawDemosaicProcessor {
GLES31.glBindImageTexture(1, demosaicTextureId, 0, false, 0,
GLES31.GL_WRITE_ONLY, GLES30.GL_RGBA16F)
GLES31.glDispatchCompute(groupsOutputX, groupsOutputY, 1)
GLES31.glMemoryBarrier(GLES31.GL_ALL_BARRIER_BITS)
GlesGpuScheduler.memoryBarrier()
checkGlError("VGN composite camera RGB")
unbindVgnImages()
passWindow.endPass()
passWindow.drain("VGN camera RGB handoff")
PLog.d(
TAG,
@@ -7627,11 +7705,13 @@ class RawDemosaicProcessor {
"lsc=${lensShadingLogString(metadata)}",
)
} finally {
passWindow.drain("VGN resource release")
activeVgnPassWindow = null
unbindVgnImages()
for (binding in 0..5) {
GLES31.glBindBufferBase(GLES31.GL_UNIFORM_BUFFER, binding, 0)
}
if (uboIds[0] != 0) GLES31.glDeleteBuffers(1, uboIds, 0)
GLES31.glDeleteBuffers(uboIds.size, uboIds, 0)
if (liveTextures.isNotEmpty()) {
liveTextures.forEach(::recycleVgnTexture)
liveTextures.clear()
+20 -49
View File
@@ -330,63 +330,34 @@ image load/store 访问。若同一纹理接下来改由 sampler 读取,或作
- GPU 纹理跨组件交接的真机测试必须实际执行 `imageStore -> barrier -> sampler fetch`,并覆盖
左上角、图像内部和右下角,不能只验证 program 编译或 CPU readback。
## Mali 后台 compute 队列与可变资源复用
## 后台 compute 的资源安全调度
已确认设备:OPPO PKD130,MT6835,Mali-G57 MC2,驱动 `v1.r38p1`。
### 问题
Radiance/VGN 连续提交 compute、fusion 和 chroma pass 时,CPU 可能覆写 GPU 尚在读取的
RAW texture 或 UBO。只限制队列长度、只加 barrier 或逐 pass 等待都不完整:前两者没有
资源所有权,后者会破坏流水。
Radiance tiled reconstruction 会在一个 tile 内连续提交多帧 VGN/semantic compute 和
framebuffer fusion,并为下一帧重复使用同一组 image、UBO、RGB tile,以及通过
`glTexSubImage2D` 覆写同一张 RAW region texture。仅在各 pass 后调用 `glMemoryBarrier`,
最后才 `glFlush`/`Thread.yield`,可能让后台队列长期保持大量未完成工作。该设备会在第一个
Radiance tile 内停止推进,应用没有 Java/native crash 或 ANR;关闭 long frame 只能少提交一帧,
不能消除问题。只限制 tiled reconstruction 后,12 个 tile 可以完成,但未切片的全帧 chroma
local/IIR 链、最终导出和紧随其后的 `RGBA16UI → RGBA16F` 转换仍会把同类停滞后移到
EngineTone 开始处。相同分辨率的单帧 VGN 使用分 pass checkpoint 时可以正常完成。
### 实现规则
`glMemoryBarrier` 只声明指定访问类型之间的内存可见性和顺序,不表示 GPU 已完成,也不保证
CPU 紧接着覆写的 UBO/texture 已不再被旧命令读取。`glFlush` 只提交命令,同样不是资源复用
完成边界。
### 错误做法
- 把一个 tile 的所有帧和 pass 一次性排入后台 context,只在 tile 末尾 `glFlush`。
- 只增加 barrier bits,然后立即用 `glBufferData` 或 `glTexSubImage2D` 更新仍可能被旧命令
使用的同一资源。
- 认为关闭 long frame 后仍卡住,说明问题与多帧 GPU 队列无关。
- 用一个覆盖整条 Radiance 链的 `glFinish` 代替调度;这会长期阻塞 CPU,也不给 UI renderer
留出稳定调度窗口。
### 正确做法
- VGN prepare、每个 VGN compute pass、最终 camera RGB,以及 semantic seed/resolve 完成后,
先使用 `GL_ALL_BARRIER_BITS` 建立完整访问交接,再通过
`GlesGpuScheduler.waitForGpuCheckpoint` 限制后台队列深度。
- 每帧 fusion 完成后建立 checkpoint,确认该帧对 RAW region、semantic/RGB tile、UBO 和
accumulator 的访问结束,再上传下一帧到复用资源。
- reference fusion 与 reference-base capture 作为一个资源复用单元;两者完成后再开始下一帧。
- 每个 tile normalization 和输出标记/回读后建立 checkpoint,再清零并复用 accumulator 处理
下一 tile。
- 全帧 chroma local pass、每个水平/垂直 IIR direction 和最终 camera RGB 导出同样建立
checkpoint。ping-pong texture 交换 Java/Kotlin 变量不代表 GPU 已结束旧角色的访问。
- 下游把导出的 `RGBA16UI` 转成 `RGBA16F` 后建立 checkpoint,再允许 EngineTone fragment
sampler 读取目标 texture。三通道条带转换还必须在每个条带结束后等待,才能覆写复用的
expansion texture。
- checkpoint 使用 fence 加短周期等待,并在完成后为 UI renderer 留出短暂调度窗口;保留等待
前后的 stage label 和耗时日志,出现驱动停滞时能定位到具体 pass/frame/tile。
- 这里只在后台重计算链的资源复用边界等待。已经完成、只读且要交给下游的输出 texture 仍按
GPU→GPU 所有权交接处理,不额外执行 `glFinish` 或 CPU materialization。
- VGN、semantic、fusion、normalization 和 chroma 共用容量为 2 的资源依赖窗口。pass
声明 texture/buffer 的读写集合;存在 RAW、WAR 或 WAW 冲突时,在提交 consumer 前等待
最新冲突 fence,无冲突时才允许两个 pass 同时在途。
- CPU 会覆写的 RAW texture 和 UBO 各使用 A/B ring;回卷前只等待该槽最后一个使用者。
GPU-only 的 RGB、semantic、中间纹理和 accumulator 保持单份。
- pass 结束后插入 fence,但不逐 pass `glFlush`。等待目标 fence 时,第一次
`glClientWaitSync` 使用 `GL_SYNC_FLUSH_COMMANDS_BIT`,后续轮询使用 flags=0。
- VGN/Radiance compute 统一使用 `GL_ALL_BARRIER_BITS`,并在 pass 后解除 image、sampler
和 indexed buffer 绑定。
- 不做逐 pass 或逐 tile checkpoint。只在资源冲突、ring 槽复用、CPU readback、纹理回收
和组件最终交接时等待。
- 调度不得改变 shader、pass 数、帧选择、参数、累加顺序或输出格式。
### 验证
- 同一设备分别测试 long frame 开启和关闭,确认所有 tile、色度后处理和最终导出均完成。
- 检查 checkpoint 的 waiting/complete 日志成对出现;若停滞,最后一个 waiting label 必须能
唯一定位对应 VGN pass、semantic pass、frame fusion、chroma/IIR direction 或 LinearRaw
格式转换。
- 拍照处理期间持续操作预览 UI,确认 renderer 可推进且应用可响应。
- 对修复前后的可正常完成设备比较输出;checkpoint 只改变命令完成边界,不应改变帧选择、
shader 参数、累加顺序或像素结果。
- long frame 开启和关闭时,Radiance、chroma、导出及单帧 RAW 都必须完成。
- pending fence 不得超过 2;等待只能来自声明的资源冲突或所有权交接。
- 修复前后输出像素应一致,并比较 Radiance、chroma 和单帧 RAW 总耗时。
## IMG/PowerVR `imageSize` 研究线索