feat: half-float texture transfer support

This commit is contained in:
Hinnka committed 2026-09-19 20:39:59 +08:00
1 parent 9005cfe0d5
commit 6f29864e7e
5 files changed
+299 -362

No files matched your search

@@ -13,6 +13,7 @@ import android.util.Half
import com.hinnka.mycamera.camera.MultiFrameConfig
import com.hinnka.mycamera.model.SafeImage
import com.hinnka.mycamera.raw.MgcSpatialStrengthMap
import com.hinnka.mycamera.raw.RawFloatTextureTransfer
import com.hinnka.mycamera.raw.RawSceneAERawStats
import com.hinnka.mycamera.utils.DngCaptureDiagnostics
import com.hinnka.mycamera.utils.DirectBufferPixelPacker
@@ -2095,7 +2096,7 @@ internal class GlesMgcRawSpatialStacker(
return null
}
var cpuOutput: ByteBuffer? = null
var sabreAccumulatedReadback: ByteBuffer? = null
val sabreTransfer = RawFloatTextureTransfer(RawFloatTextureTransfer.Layout.HALF)
var sabreResolvedRgb: ByteBuffer? = null
var exportedTexture = 0
var postprocessedUi = 0
@@ -2108,6 +2109,7 @@ internal class GlesMgcRawSpatialStacker(
if (useCurrentGlContext) attachCurrentEgl() else initEgl()
ensureGles3()
initSabrePrograms()
sabreTransfer.prepare(width, height)
renderFbo = createFramebuffer()
applyRawRenderState()
@@ -2404,7 +2406,6 @@ internal class GlesMgcRawSpatialStacker(
// The original merge shaders write normalized, white-balanced half floats. The
// Resolve AOT accepts those RGBA16F bit patterns directly; rawScale applies only to
// the black/white scalar parameters below.
sabreAccumulatedReadback = readSabreAccumulatedRgba16f(accumulatedColor)
sabreResolvedRgb = checkNotNull(
LargeDirectBuffer.allocate(
width.toLong() * height * 3L * Short.SIZE_BYTES,
@@ -2427,24 +2428,28 @@ internal class GlesMgcRawSpatialStacker(
"outputWhite=${sabreResolveParameters.outputWhiteLevel} " +
"demosaicSharpness=${sabreResolveParameters.demosaicSharpness}",
)
MgcSabreResolver.resolve(
accumulatedColorRgba16f = sabreAccumulatedReadback,
outputRgb16Planar = sabreResolvedRgb,
width = width,
height = height,
cfaPattern = cfaPattern,
finalBlackLevel = sabreResolveFinalBlackLevel,
finalGains = sabreResolveFinalGains,
demosaicWhiteLevel = demosaicWhiteLevel,
outputWhiteLevel = sabreResolveParameters.outputWhiteLevel,
demosaicBlendScale = -demosaicBlendRange * frames.size,
demosaicBlendBias = SABRE_DEMOSAIC_BLEND_END / demosaicBlendRange,
demosaicSharpnessScale =
demosaicWhiteLevel * sabreResolveParameters.demosaicSharpness,
)
sabreTransfer.read(
accumulatedColor, width, height, label = "MGC Sabre Resolve",
writable = false,
) { accumulated ->
MgcSabreResolver.resolve(
accumulatedColorRgba16f = accumulated,
outputRgb16Planar = checkNotNull(sabreResolvedRgb),
width = width,
height = height,
cfaPattern = cfaPattern,
finalBlackLevel = sabreResolveFinalBlackLevel,
finalGains = sabreResolveFinalGains,
demosaicWhiteLevel = demosaicWhiteLevel,
outputWhiteLevel = sabreResolveParameters.outputWhiteLevel,
demosaicBlendScale = -demosaicBlendRange * frames.size,
demosaicBlendBias = SABRE_DEMOSAIC_BLEND_END / demosaicBlendRange,
demosaicSharpnessScale =
demosaicWhiteLevel * sabreResolveParameters.demosaicSharpness,
)
}
logSabreResolvedRgbStats(sabreResolvedRgb)
LargeDirectBuffer.free(sabreAccumulatedReadback)
sabreAccumulatedReadback = null
sabreTransfer.releaseBuffers()
val nativeResolvedPlanes = IntArray(3) {
createTexture(
@@ -2586,9 +2591,9 @@ internal class GlesMgcRawSpatialStacker(
null
} finally {
images.forEach { it.close() }
sabreTransfer.release()
release()
GlesGpuScheduler.restoreCurrentThreadPriority(originalThreadPriority, SABRE_TAG)
LargeDirectBuffer.free(sabreAccumulatedReadback)
LargeDirectBuffer.free(sabreResolvedRgb)
if (!returned) {
exportedCompletionTimeline?.releasePending()
@@ -2995,37 +3000,6 @@ internal class GlesMgcRawSpatialStacker(
draw(program, width, height, intArrayOf(output))
}
private fun readSabreAccumulatedRgba16f(texture: Int): ByteBuffer {
val output = checkNotNull(
LargeDirectBuffer.allocate(
width.toLong() * height * 4L * Short.SIZE_BYTES,
"MGC Sabre accumulated RGBA16F",
),
) { "Unable to allocate MGC Sabre accumulated-color readback" }
try {
bindRenderTargets(intArrayOf(texture), "MGC Sabre accumulated-color readback")
GLES30.glBindBuffer(GLES30.GL_PIXEL_PACK_BUFFER, 0)
GLES30.glPixelStorei(GLES30.GL_PACK_ALIGNMENT, 1)
GLES30.glReadPixels(
0,
0,
width,
height,
GLES30.GL_RGBA,
GLES30.GL_HALF_FLOAT,
output,
)
GLES30.glBindFramebuffer(GLES30.GL_FRAMEBUFFER, 0)
checkGlError("read MGC Sabre accumulated RGBA16F")
output.position(0)
output.limit(output.capacity())
return output
} catch (error: Exception) {
LargeDirectBuffer.free(output)
throw error
}
}
private fun uploadSabreResolvedRgb16Planar(buffer: ByteBuffer, textures: IntArray) {
require(textures.size == 3)
val planeBytes = Math.multiplyExact(
@@ -29,7 +29,6 @@ import com.hinnka.mycamera.processor.GlesGpuCompletion
import com.hinnka.mycamera.processor.GlesGpuScheduler
import com.hinnka.mycamera.processor.GlesComputeWorkGroup
import com.hinnka.mycamera.processor.DenoiseStrength
import com.hinnka.mycamera.processor.GlesPixelBufferTransfer
import com.hinnka.mycamera.processor.GpuBayerSource
import com.hinnka.mycamera.processor.GpuLinearRgbSource
import com.hinnka.mycamera.processor.GpuLinearRgbStorage
@@ -998,10 +997,6 @@ class RawDemosaicProcessor {
lensShadingMapGrid = null,
)
}
val rgbaByteCount = rgbaBytes.toInt()
var transferBuffer = 0
var transferBufferMapped = false
var blackBoxFramebuffer = 0
var exportedTexture = 0
var createdExportedTexture = false
var completed = false
@@ -1010,6 +1005,7 @@ class RawDemosaicProcessor {
var demosaicNoiseTransfer: DemosaicNoiseTransfer? = null
val totalStartNs = System.nanoTime()
try {
if (applyDefaultDenoise) denoiseTransfer.prepare(width, height)
val hasDirectFloatSource =
gpuLinearRgbSource?.storage == GpuLinearRgbStorage.RGBA16F
if (!hasDirectFloatSource) {
@@ -1220,150 +1216,71 @@ class RawDemosaicProcessor {
var blackBoxUploadSubmitMs = 0L
var nativeMs = 0L
if (applyDefaultDenoise) {
val bufferIds = IntArray(1)
GLES30.glGenBuffers(1, bufferIds, 0)
transferBuffer = bufferIds[0]
check(transferBuffer != 0) {
"Unable to allocate MGC Spatial black-box transfer buffer"
lateinit var defaultDenoiseMetadata: RawMetadata
lateinit var defaultDenoisePass: MgcFullResolutionDenoise.Pass
var tuningSnr = 0f
val readTiming = denoiseTransfer.read(
workingFloatTexture, width, height, label = "MGC $mode default denoise",
beforeMap = {
val parameterStartNs = System.nanoTime()
defaultDenoiseMetadata = when (mode) {
MgcSpatialGpuDenoiseMode.SPATIAL_DEFAULT ->
spatialOutputNoiseMetadata(denoiseMetadata)
MgcSpatialGpuDenoiseMode.SABRE_DEFAULT ->
sabreOutputNoiseMetadata(denoiseMetadata)
MgcSpatialGpuDenoiseMode.BYPASS_DEFAULT_DENOISE ->
error("Bypass mode entered the MGC default-denoise boundary")
}
defaultDenoisePass = when (mode) {
MgcSpatialGpuDenoiseMode.SPATIAL_DEFAULT ->
MgcFullResolutionDenoise.Pass.SPATIAL_DEFAULT
MgcSpatialGpuDenoiseMode.SABRE_DEFAULT ->
MgcFullResolutionDenoise.Pass.SABRE_DEFAULT
MgcSpatialGpuDenoiseMode.BYPASS_DEFAULT_DENOISE ->
error("Bypass mode has no MGC full-resolution pass")
}
tuningSnr = checkNotNull(metadata.mgcDenoiseTuningSnr?.takeIf {
it.isFinite() && it >= 0f
}) {
"MGC $mode default denoise is missing output-frame SNR"
}
blackBoxParameterMs =
(System.nanoTime() - parameterStartNs) / 1_000_000L
},
) { mapped ->
val nativeStartNs = System.nanoTime()
check(
MgcFullResolutionDenoise.denoise(
rgba16f = mapped,
width = width,
height = height,
globalOriginX = 0,
globalOriginY = 0,
fullWidth = width,
fullHeight = height,
outputScale = 1f,
metadata = defaultDenoiseMetadata,
preparedYuvNoiseModel = demosaicNoiseTransfer.takeIf {
mode == MgcSpatialGpuDenoiseMode.SPATIAL_DEFAULT
},
applyLensShadingToDenoiseStrength =
mode == MgcSpatialGpuDenoiseMode.SABRE_DEFAULT,
tuningSnr = tuningSnr,
pass = defaultDenoisePass,
lumaStrengthScale = resolvedLumaStrength,
chromaStrengthScale = resolvedChromaStrength,
)
) { "MGC $mode luma/chroma denoise failed" }
nativeMs = (System.nanoTime() - nativeStartNs) / 1_000_000L
}
val transferFramebuffer = if (workingFloatTexture == demosaicTextureId) {
demosaicFramebufferId
} else {
val framebufferIds = IntArray(1)
GLES30.glGenFramebuffers(1, framebufferIds, 0)
blackBoxFramebuffer = framebufferIds[0]
GLES30.glBindFramebuffer(GLES30.GL_FRAMEBUFFER, blackBoxFramebuffer)
GLES30.glFramebufferTexture2D(
GLES30.GL_FRAMEBUFFER,
GLES30.GL_COLOR_ATTACHMENT0,
GLES30.GL_TEXTURE_2D,
workingFloatTexture,
0,
)
blackBoxFramebuffer
}
GLES30.glBindFramebuffer(GLES30.GL_FRAMEBUFFER, transferFramebuffer)
check(
GLES30.glCheckFramebufferStatus(GLES30.GL_FRAMEBUFFER) ==
GLES30.GL_FRAMEBUFFER_COMPLETE
) { "MGC Spatial black-box framebuffer is incomplete" }
GLES30.glBindBuffer(GLES30.GL_PIXEL_PACK_BUFFER, transferBuffer)
GLES30.glBufferData(
GLES30.GL_PIXEL_PACK_BUFFER,
rgbaByteCount,
null,
GLES30.GL_STREAM_COPY,
)
GLES30.glPixelStorei(GLES30.GL_PACK_ALIGNMENT, 8)
val transferStartNs = System.nanoTime()
GLES30.glReadPixels(
0,
0,
width,
height,
GLES30.GL_RGBA,
GLES30.GL_HALF_FLOAT,
0,
)
checkGlError("MGC Spatial black-box PBO readback")
blackBoxReadSubmitMs =
(System.nanoTime() - transferStartNs) / 1_000_000L
// Do all CPU-only setup after queuing the readback and before mapping. This lets
// parameter preparation overlap the GPU transfer without creating another wait.
val parameterStartNs = System.nanoTime()
val defaultDenoiseMetadata = when (mode) {
MgcSpatialGpuDenoiseMode.SPATIAL_DEFAULT ->
spatialOutputNoiseMetadata(denoiseMetadata)
MgcSpatialGpuDenoiseMode.SABRE_DEFAULT ->
sabreOutputNoiseMetadata(denoiseMetadata)
MgcSpatialGpuDenoiseMode.BYPASS_DEFAULT_DENOISE ->
error("Bypass mode entered the MGC default-denoise boundary")
}
val defaultDenoisePass = when (mode) {
MgcSpatialGpuDenoiseMode.SPATIAL_DEFAULT ->
MgcFullResolutionDenoise.Pass.SPATIAL_DEFAULT
MgcSpatialGpuDenoiseMode.SABRE_DEFAULT ->
MgcFullResolutionDenoise.Pass.SABRE_DEFAULT
MgcSpatialGpuDenoiseMode.BYPASS_DEFAULT_DENOISE ->
error("Bypass mode has no MGC full-resolution pass")
}
val tuningSnr = checkNotNull(metadata.mgcDenoiseTuningSnr?.takeIf {
it.isFinite() && it >= 0f
}) {
"MGC $mode default denoise is missing output-frame SNR"
}
blackBoxParameterMs =
(System.nanoTime() - parameterStartNs) / 1_000_000L
val mapStartNs = System.nanoTime()
val mapped = GLES30.glMapBufferRange(
GLES30.GL_PIXEL_PACK_BUFFER,
0,
rgbaByteCount,
GLES30.GL_MAP_READ_BIT or GLES30.GL_MAP_WRITE_BIT,
) as? ByteBuffer ?: error("Unable to map MGC Spatial black-box PBO")
transferBufferMapped = true
mapped.order(ByteOrder.nativeOrder()).apply {
position(0)
limit(rgbaByteCount)
}
blackBoxMapWaitMs =
(System.nanoTime() - mapStartNs) / 1_000_000L
GLES30.glBindBuffer(GLES30.GL_PIXEL_PACK_BUFFER, 0)
val nativeStartNs = System.nanoTime()
check(
MgcFullResolutionDenoise.denoise(
rgba16f = mapped,
width = width,
height = height,
globalOriginX = 0,
globalOriginY = 0,
fullWidth = width,
fullHeight = height,
outputScale = 1f,
metadata = defaultDenoiseMetadata,
preparedYuvNoiseModel = demosaicNoiseTransfer.takeIf {
mode == MgcSpatialGpuDenoiseMode.SPATIAL_DEFAULT
},
applyLensShadingToDenoiseStrength =
mode == MgcSpatialGpuDenoiseMode.SABRE_DEFAULT,
tuningSnr = tuningSnr,
pass = defaultDenoisePass,
lumaStrengthScale = resolvedLumaStrength,
chromaStrengthScale = resolvedChromaStrength,
)
) { "MGC $mode luma/chroma denoise failed" }
nativeMs = (System.nanoTime() - nativeStartNs) / 1_000_000L
GLES30.glBindBuffer(GLES30.GL_PIXEL_PACK_BUFFER, transferBuffer)
check(GLES30.glUnmapBuffer(GLES30.GL_PIXEL_PACK_BUFFER)) {
"MGC Spatial black-box transfer contents became invalid"
}
transferBufferMapped = false
GLES30.glBindBuffer(GLES30.GL_PIXEL_PACK_BUFFER, 0)
blackBoxReadSubmitMs = readTiming.submitMs.toLong()
blackBoxMapWaitMs = readTiming.mapMs.toLong()
val returnStartNs = System.nanoTime()
GLES30.glBindFramebuffer(GLES30.GL_FRAMEBUFFER, 0)
check(
GlesPixelBufferTransfer.uploadRgba16fPboToTexture(
pixelBufferObject = transferBuffer,
textureId = workingFloatTexture,
width = width,
height = height,
)
) { "Unable to return MGC black-box output to GPU" }
GLES31.glMemoryBarrier(
GLES31.GL_TEXTURE_UPDATE_BARRIER_BIT or
GLES31.GL_SHADER_IMAGE_ACCESS_BARRIER_BIT,
)
checkGlError("MGC Spatial black-box PBO return")
denoiseTransfer.upload(workingFloatTexture, width, height)
blackBoxUploadSubmitMs =
(System.nanoTime() - returnStartNs) / 1_000_000L
// Deleting a referenced GL buffer is deferred by the driver until the queued
// texture upload completes, while releasing application ownership immediately.
GLES30.glDeleteBuffers(1, intArrayOf(transferBuffer), 0)
transferBuffer = 0
} else {
PLog.i(
TAG,
@@ -1444,19 +1361,9 @@ class RawDemosaicProcessor {
} finally {
GLES30.glPixelStorei(GLES30.GL_PACK_ALIGNMENT, 1)
GLES30.glPixelStorei(GLES30.GL_UNPACK_ALIGNMENT, 1)
if (transferBufferMapped) {
GLES30.glBindBuffer(GLES30.GL_PIXEL_PACK_BUFFER, transferBuffer)
GLES30.glUnmapBuffer(GLES30.GL_PIXEL_PACK_BUFFER)
transferBufferMapped = false
}
denoiseTransfer.releaseBuffers()
GLES30.glBindBuffer(GLES30.GL_PIXEL_PACK_BUFFER, 0)
GLES30.glBindBuffer(GLES30.GL_PIXEL_UNPACK_BUFFER, 0)
if (transferBuffer != 0) {
GLES30.glDeleteBuffers(1, intArrayOf(transferBuffer), 0)
}
if (blackBoxFramebuffer != 0) {
GLES30.glDeleteFramebuffers(1, intArrayOf(blackBoxFramebuffer), 0)
}
if (demosaicFramebufferId != 0 && demosaicTextureId != 0) {
GLES30.glBindFramebuffer(GLES30.GL_FRAMEBUFFER, demosaicFramebufferId)
GLES30.glFramebufferTexture2D(
@@ -1503,6 +1410,7 @@ class RawDemosaicProcessor {
private val srgbPass = RawSrgbPass(fullscreenQuad)
private val sharpenPass = RawSharpenPass(fullscreenQuad)
private val mgcSharpen = MgcSharpen()
private val denoiseTransfer = RawFloatTextureTransfer(RawFloatTextureTransfer.Layout.HALF)
private val outputPass = RawOutputPass(fullscreenQuad)
private val linearUintToFloatPass = RawLinearUintToFloatPass()
private val linearRgbExpandPass = RawLinearRgbExpandPass()
@@ -5323,135 +5231,81 @@ class RawDemosaicProcessor {
setupLegacyAccumulator = false,
)
renderPassthroughToTexture(
sourceTextureId,
width,
height,
gfFboId[0],
)
GLES30.glBindFramebuffer(GLES30.GL_FRAMEBUFFER, gfFboId[0])
checkGlError("MGC denoise prepare camera RGB")
val byteCountLong =
width.toLong() * height.toLong() * 4L * Short.SIZE_BYTES
if (byteCountLong <= 0L || byteCountLong > Int.MAX_VALUE) {
PLog.e(TAG, "MGC denoise readback size is invalid: $byteCountLong")
return null
}
val byteCount = byteCountLong.toInt()
val readback = try {
obtainReadbackBuffer(byteCount)
} catch (error: OutOfMemoryError) {
PLog.e(
TAG,
"Unable to allocate MGC denoise readback ${width}x$height",
error,
)
return null
}
GLES30.glBindBuffer(GLES30.GL_PIXEL_PACK_BUFFER, 0)
GLES30.glPixelStorei(GLES30.GL_PACK_ALIGNMENT, 8)
readback.clear()
readback.limit(byteCount)
val readbackStartNs = System.nanoTime()
GLES30.glReadPixels(
0,
0,
width,
height,
GLES30.GL_RGBA,
GLES30.GL_HALF_FLOAT,
readback,
)
checkGlError("MGC denoise camera RGB readback")
readback.position(0)
val nativeStartNs = System.nanoTime()
// Ordinary CFA RAW sources receive a measured single-frame SNR in withMgcRenderTuning().
// Keep the legacy coordinate only for editing sources whose layout/noise profile cannot
// produce that physical measurement; Spatial/Sabre defaults never enter this fallback.
val tuningSnr = metadata.mgcDenoiseTuningSnr ?: (
metadata.iso.toFloat() / 100.0f *
metadata.postRawSensitivityBoost
).coerceAtLeast(0.001f).also { fallbackSnr ->
PLog.w(
TAG,
"MGC USER_ADJUSTMENT uses legacy tuning coordinate: " +
"layout=${metadata.noiseProfileLayout} iso=${metadata.iso} " +
"postRawBoost=${metadata.postRawSensitivityBoost} snr=$fallbackSnr",
)
}
if (!MgcFullResolutionDenoise.denoise(
rgba16f = readback,
width = width,
height = height,
globalOriginX = globalOriginX,
globalOriginY = globalOriginY,
fullWidth = fullImageWidth,
fullHeight = fullImageHeight,
metadata = metadata,
preparedYuvNoiseModel = demosaicNoiseTransfer,
applyLensShadingToDenoiseStrength = hasValidLensShadingMap(metadata),
tuningSnr = tuningSnr,
pass = MgcFullResolutionDenoise.Pass.USER_ADJUSTMENT,
lumaStrengthScale = lumaStrength,
chromaStrengthScale = chromaStrength,
)
) {
return null
}
GLES30.glBindTexture(GLES30.GL_TEXTURE_2D, gfTexId[0])
readback.position(0)
readback.limit(byteCount)
GLES30.glBindBuffer(GLES30.GL_PIXEL_UNPACK_BUFFER, 0)
GLES30.glPixelStorei(GLES30.GL_UNPACK_ROW_LENGTH, 0)
GLES30.glPixelStorei(GLES30.GL_UNPACK_ALIGNMENT, 8)
try {
GLES30.glTexSubImage2D(
GLES30.GL_TEXTURE_2D,
0,
0,
0,
denoiseTransfer.prepare(width, height)
renderPassthroughToTexture(sourceTextureId, width, height, gfFboId[0])
var nativeMs = 0L
var succeeded = false
val timing = denoiseTransfer.read(
gfTexId[0], width, height, label = "MGC USER_ADJUSTMENT denoise",
) { readback ->
val nativeStartNs = System.nanoTime()
// Ordinary CFA RAW sources receive a measured single-frame SNR in withMgcRenderTuning().
// Keep the legacy coordinate only for editing sources whose layout/noise profile cannot
// produce that physical measurement; Spatial/Sabre defaults never enter this fallback.
val tuningSnr = metadata.mgcDenoiseTuningSnr ?: (
metadata.iso.toFloat() / 100.0f *
metadata.postRawSensitivityBoost
).coerceAtLeast(0.001f).also { fallbackSnr ->
PLog.w(
TAG,
"MGC USER_ADJUSTMENT uses legacy tuning coordinate: " +
"layout=${metadata.noiseProfileLayout} iso=${metadata.iso} " +
"postRawBoost=${metadata.postRawSensitivityBoost} snr=$fallbackSnr",
)
}
succeeded = MgcFullResolutionDenoise.denoise(
rgba16f = readback,
width = width,
height = height,
globalOriginX = globalOriginX,
globalOriginY = globalOriginY,
fullWidth = fullImageWidth,
fullHeight = fullImageHeight,
metadata = metadata,
preparedYuvNoiseModel = demosaicNoiseTransfer,
applyLensShadingToDenoiseStrength = hasValidLensShadingMap(metadata),
tuningSnr = tuningSnr,
pass = MgcFullResolutionDenoise.Pass.USER_ADJUSTMENT,
lumaStrengthScale = lumaStrength,
chromaStrengthScale = chromaStrength,
)
nativeMs = (System.nanoTime() - nativeStartNs) / 1_000_000L
}
if (!succeeded) return null
GLES30.glBindFramebuffer(GLES30.GL_FRAMEBUFFER, 0)
denoiseTransfer.upload(gfTexId[0], width, height)
renderPassthroughToTexture(
gfTexId[0],
width,
height,
GLES30.GL_RGBA,
GLES30.GL_HALF_FLOAT,
readback,
gfFboId[1],
)
GLES30.glBindTexture(GLES30.GL_TEXTURE_2D, 0)
GLES30.glBindFramebuffer(GLES30.GL_FRAMEBUFFER, 0)
checkGlError("MGC denoise output RGB")
PLog.d(
TAG,
"MGC static denoise timing size=${width}x$height " +
"pass=USER_ADJUSTMENT " +
"luma=$lumaEnabled($lumaStrength) " +
"chroma=$chromaEnabled($chromaStrength) " +
"noiseTransfer=${demosaicNoiseTransfer?.let {
if (RawMetadata.isQuadBayer(metadata.cfaPattern)) {
"QUAD_BAYER"
} else {
"STANDARD_BAYER_VGN"
}
} ?: "identity"} " +
"lscStrength=${lensShadingLogString(metadata)} " +
"transferSubmitMs=${timing.submitMs} mapMs=${timing.mapMs} " +
"nativeMs=$nativeMs",
)
return gfTexId[1]
} finally {
GLES30.glPixelStorei(GLES30.GL_UNPACK_ROW_LENGTH, 0)
GLES30.glPixelStorei(GLES30.GL_UNPACK_ALIGNMENT, 1)
// Buffer deletion defers storage reclamation until the queued upload has consumed it.
denoiseTransfer.releaseBuffers()
}
checkGlError("MGC denoise camera RGB upload")
renderPassthroughToTexture(
gfTexId[0],
width,
height,
gfFboId[1],
)
GLES30.glBindTexture(GLES30.GL_TEXTURE_2D, 0)
GLES30.glBindFramebuffer(GLES30.GL_FRAMEBUFFER, 0)
checkGlError("MGC denoise output RGB")
PLog.d(
TAG,
"MGC static denoise timing size=${width}x$height " +
"pass=USER_ADJUSTMENT " +
"luma=$lumaEnabled($lumaStrength) " +
"chroma=$chromaEnabled($chromaStrength) " +
"noiseTransfer=${demosaicNoiseTransfer?.let {
if (RawMetadata.isQuadBayer(metadata.cfaPattern)) {
"QUAD_BAYER"
} else {
"STANDARD_BAYER_VGN"
}
} ?: "identity"} " +
"lscStrength=${lensShadingLogString(metadata)} " +
"readbackMs=${(nativeStartNs - readbackStartNs) / 1_000_000L} " +
"nativeMs=${(System.nanoTime() - nativeStartNs) / 1_000_000L}",
)
return gfTexId[1]
}
/**
@@ -9242,6 +9096,7 @@ class RawDemosaicProcessor {
srgbPass.release()
sharpenPass.release()
mgcSharpen.release()
denoiseTransfer.release()
outputPass.release()
hdrReferencePass.release()
chromaDenoiseAlgorithm.release()
@@ -3,12 +3,20 @@ package com.hinnka.mycamera.raw
import android.opengl.GLES30
import android.opengl.GLES31
import com.hinnka.mycamera.processor.GlesGpuCompletion
import com.hinnka.mycamera.processor.GlesPixelBufferTransfer
import com.hinnka.mycamera.utils.PLog
import java.nio.ByteBuffer
import java.nio.ByteOrder
/** Float transport shared by the linear guide and encoded sharpening boundaries. */
internal class RawFloatTextureTransfer {
/** Floating-point transport preserving the native ABI at each CPU/AOT boundary. */
internal class RawFloatTextureTransfer(private val layout: Layout = Layout.FLOAT) {
enum class Layout(val bytesPerPixel: Int, val pixelType: Int) {
FLOAT(16, GLES30.GL_FLOAT),
HALF(8, GLES30.GL_HALF_FLOAT),
}
data class ReadTiming(val submitMs: Double, val mapMs: Double)
private var buffer = 0
private var capacity = 0
private var framebuffer = 0
@@ -18,32 +26,50 @@ internal class RawFloatTextureTransfer {
private var maxSsboBytes = 0L
private var ssboOffsetAlignment = 1
fun read(texture: Int, width: Int, height: Int, capacityPixels: Long = width.toLong() * height,
label: String,
consume: (ByteBuffer) -> Unit) {
val start = System.nanoTime()
val inputBytes = width.toLong() * height * 16
val bytes = capacityPixels * 16
require(width > 0 && height > 0 && bytes >= inputBytes && bytes <= Int.MAX_VALUE)
/** Allocate before producing the input so allocation/compilation cannot drain that work. */
fun prepare(width: Int, height: Int, capacityPixels: Long = width.toLong() * height) {
val bytes = byteCount(width, height, capacityPixels)
initialize()
if (buffer == 0) {
val names = IntArray(1)
GLES30.glGenBuffers(1, names, 0)
buffer = names[0]
check(buffer != 0) { "Unable to allocate float transfer buffer" }
}
GLES30.glBindBuffer(GLES30.GL_PIXEL_PACK_BUFFER, buffer)
if (capacity < bytes) {
GLES30.glBufferData(GLES30.GL_PIXEL_PACK_BUFFER, bytes.toInt(), null, GLES30.GL_STREAM_COPY)
checkGl("allocate float transfer")
capacity = bytes.toInt()
try {
if (capacity < bytes) {
GLES30.glBufferData(GLES30.GL_PIXEL_PACK_BUFFER, bytes, null, GLES30.GL_STREAM_COPY)
checkGl("allocate float transfer")
capacity = bytes
}
} finally {
GLES30.glBindBuffer(GLES30.GL_PIXEL_PACK_BUFFER, 0)
}
}
fun read(texture: Int, width: Int, height: Int, capacityPixels: Long = width.toLong() * height,
label: String,
writable: Boolean = true,
beforeMap: (() -> Unit)? = null,
consume: (ByteBuffer) -> Unit): ReadTiming {
val start = System.nanoTime()
val inputBytes = width.toLong() * height * layout.bytesPerPixel
val bytes = byteCount(width, height, capacityPixels)
prepare(width, height, capacityPixels)
val allocationMs = elapsedMs(start)
val stripeRows = if (program != 0) {
RawFloatTransferLayout.stripeRows(width, height, maxSsboBytes, ssboOffsetAlignment)
RawFloatTransferLayout.stripeRows(width, height, maxSsboBytes, ssboOffsetAlignment,
layout.bytesPerPixel)
} else 0
val upstreamWaitMs = GlesGpuCompletion.awaitSubmittedWork("MGC float $label", checkGlError = ::checkGl)
// Compute packing stays in the producer's queue; map is the only required CPU wait.
// Retain the separate upstream timing only for the synchronous framebuffer fallback.
val upstreamWaitMs = if (stripeRows == 0) {
GlesGpuCompletion.awaitSubmittedWork("MGC float $label", checkGlError = ::checkGl)
} else 0L
val transferStart = System.nanoTime()
try {
GLES30.glBindBuffer(GLES30.GL_PIXEL_PACK_BUFFER, buffer)
if (stripeRows > 0) {
GLES31.glUseProgram(program)
GLES31.glActiveTexture(GLES31.GL_TEXTURE0)
@@ -67,13 +93,22 @@ internal class RawFloatTextureTransfer {
GLES30.glReadBuffer(GLES30.GL_COLOR_ATTACHMENT0)
GLES30.glPixelStorei(GLES30.GL_PACK_ALIGNMENT, 1)
GLES30.glPixelStorei(GLES30.GL_PACK_ROW_LENGTH, 0)
GLES30.glReadPixels(0, 0, width, height, GLES30.GL_RGBA, GLES30.GL_FLOAT, 0)
GLES30.glReadPixels(0, 0, width, height, GLES30.GL_RGBA, layout.pixelType, 0)
}
checkGl("read float texture")
GLES30.glBindBuffer(GLES30.GL_PIXEL_PACK_BUFFER, 0)
if (beforeMap != null) {
// Submit before CPU-only parameter preparation to allow useful overlap.
GLES30.glFlush()
}
val submitMs = elapsedMs(transferStart)
beforeMap?.invoke()
val mapStart = System.nanoTime()
GLES30.glBindBuffer(GLES30.GL_PIXEL_PACK_BUFFER, buffer)
val access = GLES30.GL_MAP_READ_BIT or (if (writable) GLES30.GL_MAP_WRITE_BIT else 0)
val mapped = checkNotNull(GLES30.glMapBufferRange(GLES30.GL_PIXEL_PACK_BUFFER,
0, bytes.toInt(), GLES30.GL_MAP_READ_BIT or GLES30.GL_MAP_WRITE_BIT) as? ByteBuffer)
0, bytes, access) as? ByteBuffer)
GLES30.glBindBuffer(GLES30.GL_PIXEL_PACK_BUFFER, 0)
val mapMs = elapsedMs(mapStart)
val nativeStart = System.nanoTime()
var nativeMs = 0.0
@@ -83,16 +118,22 @@ internal class RawFloatTextureTransfer {
} finally {
nativeMs = elapsedMs(nativeStart)
val unmapStart = System.nanoTime()
GLES30.glBindBuffer(GLES30.GL_PIXEL_PACK_BUFFER, buffer)
check(GLES30.glUnmapBuffer(GLES30.GL_PIXEL_PACK_BUFFER)) { "Invalid float transfer mapping" }
unmapMs = elapsedMs(unmapStart)
}
PLog.i(TAG, "$label size=${width}x$height inputBytes=$inputBytes capacityBytes=$bytes " +
PLog.i(TAG, "$label layout=$layout size=${width}x$height inputBytes=$inputBytes capacityBytes=$bytes " +
"transfer=${if (stripeRows > 0) "SSBO" else "PBO"} stripeRows=$stripeRows " +
"maxSsboBytes=$maxSsboBytes allocationMs=$allocationMs upstreamGpuWaitMs=$upstreamWaitMs " +
"transferSubmitMs=$submitMs mapMs=$mapMs nativeMs=$nativeMs unmapMs=$unmapMs " +
"totalCpuMs=${elapsedMs(start)}")
return ReadTiming(submitMs, mapMs)
} finally {
if (stripeRows > 0) GLES31.glBindBufferBase(GLES31.GL_SHADER_STORAGE_BUFFER, 0, 0)
if (stripeRows > 0) {
GLES31.glBindBufferBase(GLES31.GL_SHADER_STORAGE_BUFFER, 0, 0)
GLES30.glActiveTexture(GLES30.GL_TEXTURE0)
GLES30.glBindTexture(GLES30.GL_TEXTURE_2D, 0)
}
GLES30.glBindBuffer(GLES30.GL_PIXEL_PACK_BUFFER, 0)
if (framebuffer != 0) {
GLES30.glBindFramebuffer(GLES30.GL_READ_FRAMEBUFFER, framebuffer)
@@ -105,10 +146,11 @@ internal class RawFloatTextureTransfer {
/** The destination uses immutable RGBA16F storage for write-only image access. */
fun upload(texture: Int, width: Int, height: Int) {
require(width > 0 && height > 0 && width.toLong() * height * 16 <= capacity)
require(width > 0 && height > 0 && width.toLong() * height * layout.bytesPerPixel <= capacity)
val start = System.nanoTime()
val stripeRows = if (uploadProgram != 0) {
RawFloatTransferLayout.stripeRows(width, height, maxSsboBytes, ssboOffsetAlignment)
RawFloatTransferLayout.stripeRows(width, height, maxSsboBytes, ssboOffsetAlignment,
layout.bytesPerPixel)
} else 0
if (stripeRows > 0) {
try {
@@ -125,9 +167,15 @@ internal class RawFloatTextureTransfer {
GLES31.glBindBufferBase(GLES31.GL_SHADER_STORAGE_BUFFER, 0, 0)
}
} else {
check(nativeUpload(buffer, texture, width, height)) { "Float PBO upload failed" }
GLES30.glActiveTexture(GLES30.GL_TEXTURE0)
GLES30.glPixelStorei(GLES30.GL_UNPACK_ROW_LENGTH, 0)
val uploaded = when (layout) {
Layout.FLOAT -> nativeUpload(buffer, texture, width, height)
Layout.HALF -> GlesPixelBufferTransfer.uploadRgba16fPboToTexture(buffer, texture, width, height)
}
check(uploaded) { "Float PBO upload failed" }
}
PLog.i(TAG, "upload size=${width}x$height transfer=${if (stripeRows > 0) "SSBO_IMAGE" else "PBO"} " +
PLog.i(TAG, "upload layout=$layout size=${width}x$height transfer=${if (stripeRows > 0) "SSBO_IMAGE" else "PBO"} " +
"stripeRows=$stripeRows uploadSubmitMs=${elapsedMs(start)}")
}
@@ -135,7 +183,7 @@ internal class RawFloatTextureTransfer {
GLES31.glUniform2i(GLES31.glGetUniformLocation(computeProgram, "uSize"), width, height)
val rowOffsetLocation = GLES31.glGetUniformLocation(computeProgram, "uRowOffset")
val rowsLocation = GLES31.glGetUniformLocation(computeProgram, "uRows")
val rowBytes = width * 16
val rowBytes = width * layout.bytesPerPixel
for (row in 0 until height step stripeRows) {
val rows = minOf(stripeRows, height - row)
GLES31.glUniform1i(rowOffsetLocation, row)
@@ -146,6 +194,12 @@ internal class RawFloatTextureTransfer {
}
}
private fun byteCount(width: Int, height: Int, capacityPixels: Long): Int {
require(width > 0 && height > 0 && capacityPixels >= width.toLong() * height &&
capacityPixels <= Int.MAX_VALUE / layout.bytesPerPixel)
return (capacityPixels * layout.bytesPerPixel).toInt()
}
fun releaseBuffers() {
if (buffer != 0) GLES30.glDeleteBuffers(1, intArrayOf(buffer), 0)
if (framebuffer != 0) GLES30.glDeleteFramebuffers(1, intArrayOf(framebuffer), 0)
@@ -173,13 +227,15 @@ internal class RawFloatTextureTransfer {
GLES31.glGetIntegerv(GLES31.GL_SHADER_STORAGE_BUFFER_OFFSET_ALIGNMENT, alignment, 0)
check(alignment[0] > 0) { "Invalid SSBO offset alignment: ${alignment[0]}" }
ssboOffsetAlignment = alignment[0]
program = RawGlesProgram.compileCompute(PACK, "MgcFloatTransfer")
program = RawGlesProgram.compileCompute(
if (layout == Layout.HALF) PACK_HALF else PACK, "Mgc${layout}Transfer")
val imageUnits = IntArray(1)
val computeImages = IntArray(1)
GLES31.glGetIntegerv(GLES31.GL_MAX_IMAGE_UNITS, imageUnits, 0)
GLES31.glGetIntegerv(GLES31.GL_MAX_COMPUTE_IMAGE_UNIFORMS, computeImages, 0)
if (imageUnits[0] > 0 && computeImages[0] > 0) {
uploadProgram = RawGlesProgram.compileCompute(UNPACK, "MgcFloatUpload")
uploadProgram = RawGlesProgram.compileCompute(
if (layout == Layout.HALF) UNPACK_HALF else UNPACK, "Mgc${layout}Upload")
}
}
}
@@ -228,5 +284,43 @@ internal class RawFloatTextureTransfer {
imageStore(uOutput, p + ivec2(0, uRowOffset), value);
}
""".trimIndent()
// Two little-endian words per pixel retain the RGBA16F ABI without expanding to Float32.
internal val PACK_HALF = """
#version 310 es
precision highp float;
precision highp int;
layout(local_size_x = 8, local_size_y = 8) in;
uniform highp sampler2D uInput;
uniform ivec2 uSize;
uniform int uRowOffset;
uniform int uRows;
layout(std430, binding = 0) writeonly buffer Pixels { uvec2 pixels[]; };
void main() {
ivec2 p = ivec2(gl_GlobalInvocationID.xy);
if (p.x >= uSize.x || p.y >= uRows) return;
vec4 value = texelFetch(uInput, p + ivec2(0, uRowOffset), 0);
pixels[p.y * uSize.x + p.x] = uvec2(packHalf2x16(value.rg), packHalf2x16(value.ba));
}
""".trimIndent()
internal val UNPACK_HALF = """
#version 310 es
precision highp float;
precision highp int;
layout(local_size_x = 8, local_size_y = 8) in;
layout(std430, binding = 0) readonly buffer Pixels { uvec2 pixels[]; };
layout(rgba16f, binding = 0) writeonly uniform highp image2D uOutput;
uniform ivec2 uSize;
uniform int uRowOffset;
uniform int uRows;
void main() {
ivec2 p = ivec2(gl_GlobalInvocationID.xy);
if (p.x >= uSize.x || p.y >= uRows) return;
uvec2 encoded = pixels[p.y * uSize.x + p.x];
vec4 value = vec4(unpackHalf2x16(encoded.x), unpackHalf2x16(encoded.y));
imageStore(uOutput, p + ivec2(0, uRowOffset), value);
}
""".trimIndent()
}
}
@@ -2,9 +2,15 @@ package com.hinnka.mycamera.raw
/** Each SSBO range covers whole rows and starts at a driver-aligned byte offset. */
internal object RawFloatTransferLayout {
fun stripeRows(width: Int, height: Int, maxBlockBytes: Long, offsetAlignment: Int): Int {
require(width > 0 && height > 0 && offsetAlignment > 0)
val rowBytes = width.toLong() * 16
fun stripeRows(
width: Int,
height: Int,
maxBlockBytes: Long,
offsetAlignment: Int,
bytesPerPixel: Int = 16,
): Int {
require(width > 0 && height > 0 && offsetAlignment > 0 && bytesPerPixel > 0)
val rowBytes = width.toLong() * bytesPerPixel
if (rowBytes * height <= maxBlockBytes) return height
var a = rowBytes
var b = offsetAlignment.toLong()
@@ -25,18 +25,26 @@ class RawFloatTransferLayoutTest {
assertEquals(3, RawFloatTransferLayout.stripeRows(37, 3, 37L * 16 * 3, 256))
}
private fun checkCoverage(width: Int, height: Int, limit: Long, alignment: Int) {
val stripeRows = RawFloatTransferLayout.stripeRows(width, height, limit, alignment)
@Test
fun halfRgbaUsesEightBytePixelsIncludingOddWidthAndTail() {
checkCoverage(4033, 3025, 16L * 1024 * 1024, 256, bytesPerPixel = 8)
checkCoverage(37, 67, 37L * 8 * 32, 256, bytesPerPixel = 8)
assertEquals(0, RawFloatTransferLayout.stripeRows(37, 67, 37L * 8 * 31, 256, 8))
assertEquals(3, RawFloatTransferLayout.stripeRows(37, 3, 37L * 8 * 3, 256, 8))
}
private fun checkCoverage(width: Int, height: Int, limit: Long, alignment: Int, bytesPerPixel: Int = 16) {
val stripeRows = RawFloatTransferLayout.stripeRows(width, height, limit, alignment, bytesPerPixel)
assertTrue(stripeRows > 0)
var covered = 0L
for (row in 0 until height step stripeRows) {
val offset = row.toLong() * width * 16
val bytes = minOf(stripeRows, height - row).toLong() * width * 16
val offset = row.toLong() * width * bytesPerPixel
val bytes = minOf(stripeRows, height - row).toLong() * width * bytesPerPixel
assertEquals(covered, offset)
assertEquals(0L, offset % alignment)
assertTrue(bytes in 1..limit)
covered += bytes
}
assertEquals(width.toLong() * height * 16, covered)
assertEquals(width.toLong() * height * bytesPerPixel, covered)
}
}