feat: gles prewarm

This commit is contained in:
zhoubinjia committed 2026-07-21 15:15:37 +08:00
1 parent 0a877e36d3
commit c8a37c7983
13 files changed
+1080 -126

No files matched your search

@@ -187,7 +187,6 @@ class MainActivity : ComponentActivity() {
arrayOf(Manifest.permission.CAMERA, Manifest.permission.RECORD_AUDIO)
private var hasPermissions by mutableStateOf(false)
private var mlPreloadComplete by mutableStateOf(false)
private var pendingRoute by mutableStateOf<String?>(null)
private var pendingLutImportUris by mutableStateOf<List<Uri>>(emptyList())
@@ -284,15 +283,14 @@ class MainActivity : ComponentActivity() {
preferences = cameraViewModel.userPreferences.value
)
} finally {
mlPreloadComplete = true
StartupTrace.mark("MainActivity.mlPreloadComplete")
StartupTrace.mark("MainActivity.mlPreloadFinished")
}
}
splashScreen.setKeepOnScreenCondition {
val cameraInitialized = cameraViewModel.isInitialized.value
val galleryInitialized = galleryViewModel.isInitialized.value
!(cameraInitialized && galleryInitialized && mlPreloadComplete)
!(cameraInitialized && galleryInitialized)
}
@@ -31,6 +31,7 @@ import com.hinnka.mycamera.lut.applyEffectsToVideoFile
import com.hinnka.mycamera.lut.isVideoTransformerExportSupported
import com.hinnka.mycamera.model.SafeImage
import com.hinnka.mycamera.processor.MultiFrameStacker
import com.hinnka.mycamera.processor.GpuLinearRgbSource
import com.hinnka.mycamera.processor.RawNoiseModel
import com.hinnka.mycamera.processor.RawStackBufferLayout
import com.hinnka.mycamera.processor.RawStackFrame
@@ -2595,6 +2596,8 @@ object GalleryManager {
frameFocusDistances: List<Float?> = emptyList(),
rawStackFrames: List<RawStackFrame> = emptyList(),
) = withContext(Dispatchers.IO) {
var stackProcessor: RawDemosaicProcessor? = null
var gpuSourceToRelease: GpuLinearRgbSource? = null
try {
val photoDir = getPhotoDir(context, photoId, true)
@@ -2668,22 +2671,29 @@ object GalleryManager {
)
}
}
val rawStackResult = MultiFrameStacker.processBurstRaw(
frames = effectiveRawStackFrames,
cfaPattern = stackCfaPattern,
outputScale = if (currentUseSuperResolution) superResolutionScale else 1f,
masterBlackLevel = stackBlackLevel,
whiteLevel = stackWhiteLevel,
whiteBalanceGains = rawMetadata.whiteBalanceGains,
noiseModel = rawMetadata.noiseProfile,
rawNoiseModel = RawNoiseModel.fromCamera2NoiseProfile(rawMetadata.channelNoiseProfile),
lensShading = rawMetadata.lensShadingMap,
lensShadingWidth = rawMetadata.lensShadingMapWidth,
lensShadingHeight = rawMetadata.lensShadingMapHeight,
applyLensShadingCorrection = applyRawLensShading,
)
val processor = RawDemosaicProcessor.getInstance()
stackProcessor = processor
val rawStackResult = processor.runStackingOnGlContext {
MultiFrameStacker.processBurstRaw(
frames = effectiveRawStackFrames,
cfaPattern = stackCfaPattern,
outputScale = if (currentUseSuperResolution) superResolutionScale else 1f,
masterBlackLevel = stackBlackLevel,
whiteLevel = stackWhiteLevel,
whiteBalanceGains = rawMetadata.whiteBalanceGains,
noiseModel = rawMetadata.noiseProfile,
rawNoiseModel = RawNoiseModel.fromCamera2NoiseProfile(rawMetadata.channelNoiseProfile),
lensShading = rawMetadata.lensShadingMap,
lensShadingWidth = rawMetadata.lensShadingMapWidth,
lensShadingHeight = rawMetadata.lensShadingMapHeight,
applyLensShadingCorrection = applyRawLensShading,
useCurrentGlContext = true,
exportGpuLinearRgbSource = true,
)
}
val finalStackResult = rawStackResult ?: return@withContext
gpuSourceToRelease = finalStackResult.gpuLinearRgbSource
val stackedMetadata = if (finalStackResult.isNormalizedSensorData) {
metadata.withNormalizedRawLevelCorrectionsCleared("RAW stack")
@@ -2709,7 +2719,6 @@ object GalleryManager {
?: ChromaDenoiseDefaults.forRawCapture(chromaNoiseReductionValue)
var pendingDngWrite: Deferred<Boolean>? = null
val rawResult = try {
val processor = RawDemosaicProcessor.getInstance()
val imageLayout = finalStackResult.bufferLayout.toDngImageLayout()
val inputSamplesPerPixel = finalStackResult.inputColStepSamples
val inputRowStepSamples = finalStackResult.inputRowStepSamples
@@ -2731,6 +2740,7 @@ object GalleryManager {
)
val dngProfilePreparation = RawProcessor.prepareRawDngProfile(
rawBuffer = fusedBayerBuffer,
gpuLinearRgbSource = finalStackResult.gpuLinearRgbSource,
width = finalStackResult.width,
height = finalStackResult.height,
characteristics = characteristics,
@@ -2868,6 +2878,7 @@ object GalleryManager {
height = finalStackResult.height,
rowStride = checkNotNull(inputRowStepSamples) * Short.SIZE_BYTES,
samplesPerPixel = checkNotNull(inputSamplesPerPixel),
gpuLinearRgbSource = finalStackResult.gpuLinearRgbSource,
metadata = checkNotNull(renderMetadata),
aspectRatio = aspectRatio,
cropRegion = updatedMetadata.cropRegion,
@@ -3050,6 +3061,10 @@ object GalleryManager {
}
} catch (e: Exception) {
PLog.e(TAG, "Failed to savePhoto", e)
} finally {
withContext(NonCancellable) {
stackProcessor?.releaseGpuLinearRgbSource(gpuSourceToRelease)
}
}
}
@@ -191,6 +191,21 @@ class LutImageProcessor {
// 曲线纹理
private var curveTextureId = 0
/** Initializes the persistent LUT/HDR GL pipeline before the first captured photo needs it. */
suspend fun prewarmCapturePipeline(): Boolean = withContext(glDispatcher) {
if (isReleased) return@withContext false
val start = System.currentTimeMillis()
val ready = initialize()
if (ready) {
GLES30.glFinish()
}
PLog.d(
TAG,
"LUT capture pipeline prewarmed ready=$ready, took=${System.currentTimeMillis() - start}ms",
)
ready
}
/**
* 初始化 EGL 环境
*/
@@ -15,10 +15,13 @@ object StartupMlPreloader {
val appContext = context.applicationContext
StartupTrace.mark(
"StartupMlPreloader.preloadForStartup start",
"useRaw=${preferences.useRaw}, defaultVirtualAperture=${preferences.defaultVirtualAperture}, aiFocus=${preferences.aiFocusTargetMode}"
"defaultVirtualAperture=${preferences.defaultVirtualAperture}, " +
"aiFocus=${preferences.aiFocusTargetMode}"
)
if (preferences.useRaw || preferences.defaultVirtualAperture > 0f) {
// RAW processing does not consume a depth map. Keep the model resident only when the
// configured virtual-aperture path will actually use it.
if (preferences.defaultVirtualAperture > 0f) {
prewarm("DepthEstimator") {
SharedDepthEstimator.prewarm(appContext)
}
@@ -4,6 +4,7 @@ import android.opengl.GLES30
import android.opengl.GLES31
import com.hinnka.mycamera.utils.DirectBufferPixelPacker
import com.hinnka.mycamera.utils.LargeDirectBuffer
import com.hinnka.mycamera.utils.PLog
import java.nio.ByteBuffer
import kotlin.math.acos
import kotlin.math.ceil
@@ -30,6 +31,7 @@ internal class GlesRadianceVgnChromaPostprocessor(
calculationWbGains: FloatArray,
outputScale: Float,
private val backend: Backend,
private val exportFullSizeTexture: Boolean = false,
) {
interface Backend {
fun linkComputeProgram(source: String, name: String): Int
@@ -48,6 +50,11 @@ internal class GlesRadianceVgnChromaPostprocessor(
val allocMs: Long,
)
data class ProcessResult(
val readbackTiming: ReadbackTiming,
val exportedTextureId: Int,
)
private val calculationRgbGains = floatArrayOf(
calculationWbGains.getOrElse(0) { 1f },
1f,
@@ -81,6 +88,8 @@ internal class GlesRadianceVgnChromaPostprocessor(
private var capturedRgb = 0
private var originalYccd = 0
private var smoothYccd = 0
private var fullSizeCameraRgb = 0
private var gpuExportEnabled = exportFullSizeTexture
private var readbackFbo = 0
private val ownedTextures = ArrayList<Int>(3)
@@ -154,10 +163,27 @@ internal class GlesRadianceVgnChromaPostprocessor(
GlesRadianceVgnChromaShaders.colorNoiseFilter,
"raw_radiance_vgn_chroma_filter",
)
finalProgram = backend.linkComputeProgram(
GlesRadianceVgnChromaShaders.finalCameraRgb,
"raw_radiance_vgn_chroma_final_camera_rgb",
)
finalProgram = if (gpuExportEnabled) {
runCatching {
backend.linkComputeProgram(
GlesRadianceVgnChromaShaders.finalCameraRgb(exportFullSizeTexture = true),
"raw_radiance_vgn_chroma_final_camera_rgb_2d",
)
}.onFailure { error ->
gpuExportEnabled = false
PLog.w(TAG, "Full-size Radiance GPU export shader unavailable; using CPU handoff", error)
}.getOrElse {
backend.linkComputeProgram(
GlesRadianceVgnChromaShaders.finalCameraRgb(exportFullSizeTexture = false),
"raw_radiance_vgn_chroma_final_camera_rgb_array",
)
}
} else {
backend.linkComputeProgram(
GlesRadianceVgnChromaShaders.finalCameraRgb(exportFullSizeTexture = false),
"raw_radiance_vgn_chroma_final_camera_rgb_array",
)
}
}
fun initStorage() {
@@ -194,7 +220,7 @@ internal class GlesRadianceVgnChromaPostprocessor(
backend.checkGlError("Radiance VGN chroma capture tile ${tile.index}")
}
fun processAndReadback(outputBuffer: ByteBuffer): ReadbackTiming {
fun processAndReadback(outputBuffer: ByteBuffer): ProcessResult {
check(capturedRgb != 0) { "Radiance VGN chroma has no captured Radiance output" }
originalYccd = createArrayTexture()
smoothYccd = createArrayTexture()
@@ -239,10 +265,46 @@ internal class GlesRadianceVgnChromaPostprocessor(
originalYccd = result.first
scratch = result.second
}
dispatchFinal(scratch)
originalYccd = scratch.also { scratch = originalYccd }
val timing = readback(outputBuffer)
if (gpuExportEnabled) {
// One of the three working arrays is dead before the final conversion. Reclaim it so
// the full-size 2D handoff does not increase the legacy peak texture storage.
ownedTextures.firstOrNull { it != originalYccd && it != scratch }?.let { disposable ->
deleteTexture(disposable)
if (capturedRgb == disposable) capturedRgb = 0
if (smoothYccd == disposable) smoothYccd = 0
}
}
val gpuTiming = if (gpuExportEnabled) {
runCatching {
fullSizeCameraRgb = createFullSizeTexture()
dispatchFinal(destination = 0, fullSize = true)
readbackFullSize(outputBuffer)
}.onFailure { error ->
deleteTexture(fullSizeCameraRgb)
fullSizeCameraRgb = 0
gpuExportEnabled = false
PLog.w(TAG, "Full-size Radiance GPU export failed; using CPU handoff", error)
finalProgram = backend.linkComputeProgram(
GlesRadianceVgnChromaShaders.finalCameraRgb(exportFullSizeTexture = false),
"raw_radiance_vgn_chroma_final_camera_rgb_array_fallback",
)
}.getOrNull()
} else {
null
}
val timing = gpuTiming ?: run {
dispatchFinal(scratch)
originalYccd = scratch.also { scratch = originalYccd }
readback(outputBuffer)
}
if (gpuTiming != null) {
val releasedScratch = scratch
deleteTexture(releasedScratch)
if (capturedRgb == releasedScratch) capturedRgb = 0
if (originalYccd == releasedScratch) originalYccd = 0
if (smoothYccd == releasedScratch) smoothYccd = 0
scratch = 0
}
for (unit in 0..2) {
GLES31.glBindImageTexture(
unit,
@@ -260,7 +322,15 @@ internal class GlesRadianceVgnChromaPostprocessor(
capturedRgb = 0
originalYccd = 0
smoothYccd = 0
return timing
val exportedTextureId = fullSizeCameraRgb
if (exportedTextureId != 0) {
ownedTextures.removeAll { it == exportedTextureId }
fullSizeCameraRgb = 0
}
return ProcessResult(
readbackTiming = timing,
exportedTextureId = exportedTextureId,
)
}
fun release() {
@@ -271,6 +341,7 @@ internal class GlesRadianceVgnChromaPostprocessor(
capturedRgb = 0
originalYccd = 0
smoothYccd = 0
fullSizeCameraRgb = 0
if (readbackFbo != 0) {
GLES30.glDeleteFramebuffers(1, intArrayOf(readbackFbo), 0)
readbackFbo = 0
@@ -342,7 +413,7 @@ internal class GlesRadianceVgnChromaPostprocessor(
dispatchImage(colorNoiseFilterProgram, "color noise filter")
}
private fun dispatchFinal(destination: Int) {
private fun dispatchFinal(destination: Int, fullSize: Boolean = false) {
GLES31.glUseProgram(finalProgram)
setTiledUniforms(finalProgram)
GLES31.glUniform3fv(
@@ -352,7 +423,19 @@ internal class GlesRadianceVgnChromaPostprocessor(
0,
)
bindArrayImage(0, originalYccd, GLES31.GL_READ_ONLY)
bindArrayImage(1, destination, GLES31.GL_WRITE_ONLY)
if (fullSize) {
GLES31.glBindImageTexture(
2,
fullSizeCameraRgb,
0,
false,
0,
GLES31.GL_WRITE_ONLY,
GLES30.GL_RGBA16UI,
)
} else {
bindArrayImage(1, destination, GLES31.GL_WRITE_ONLY)
}
dispatchImage(finalProgram, "final camera RGB")
}
@@ -506,6 +589,29 @@ internal class GlesRadianceVgnChromaPostprocessor(
return texture
}
private fun createFullSizeTexture(): Int {
val ids = IntArray(1)
GLES30.glGenTextures(1, ids, 0)
val texture = ids[0]
check(texture != 0) { "Failed to allocate full-size Radiance RGB texture" }
GLES30.glBindTexture(GLES30.GL_TEXTURE_2D, texture)
GLES30.glTexParameteri(GLES30.GL_TEXTURE_2D, GLES30.GL_TEXTURE_MIN_FILTER, GLES30.GL_NEAREST)
GLES30.glTexParameteri(GLES30.GL_TEXTURE_2D, GLES30.GL_TEXTURE_MAG_FILTER, GLES30.GL_NEAREST)
GLES30.glTexParameteri(GLES30.GL_TEXTURE_2D, GLES30.GL_TEXTURE_WRAP_S, GLES30.GL_CLAMP_TO_EDGE)
GLES30.glTexParameteri(GLES30.GL_TEXTURE_2D, GLES30.GL_TEXTURE_WRAP_T, GLES30.GL_CLAMP_TO_EDGE)
GLES30.glTexStorage2D(
GLES30.GL_TEXTURE_2D,
1,
GLES30.GL_RGBA16UI,
imageWidth,
imageHeight,
)
GLES30.glBindTexture(GLES30.GL_TEXTURE_2D, 0)
ownedTextures += texture
backend.checkGlError("full-size Radiance RGB ${imageWidth}x$imageHeight")
return texture
}
private fun deleteTexture(texture: Int) {
if (texture == 0) return
GLES30.glDeleteTextures(1, intArrayOf(texture), 0)
@@ -592,7 +698,88 @@ internal class GlesRadianceVgnChromaPostprocessor(
)
}
private fun readbackFullSize(outputBuffer: ByteBuffer): ReadbackTiming {
val allocationStart = System.currentTimeMillis()
val scratchBytes = layerWidth.toLong() * layerHeight.toLong() * 8L
val scratch = LargeDirectBuffer.allocate(scratchBytes, "Radiance full-size RGB readback")
?: throw IllegalStateException("Unable to allocate full-size Radiance 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,
fullSizeCameraRgb,
0,
)
GLES30.glReadBuffer(GLES30.GL_COLOR_ATTACHMENT0)
val status = GLES30.glCheckFramebufferStatus(GLES30.GL_FRAMEBUFFER)
check(status == GLES30.GL_FRAMEBUFFER_COMPLETE) {
"Full-size Radiance 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 Radiance 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 Radiance 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 = allocationMs + glReadMs + copyMs,
glReadMs = glReadMs,
copyMs = copyMs,
allocMs = allocationMs,
)
}
private fun groupCount(value: Int): Int = (value + 15) / 16
private companion object {
const val TAG = "GlesRadianceVgnChroma"
}
}
internal data class RadianceVgnChromaIirCoefficients(
@@ -1331,15 +1518,30 @@ internal object GlesRadianceVgnChromaShaders {
}
""".trimIndent()
val finalCameraRgb = """
val finalCameraRgb: String
get() = finalCameraRgb(exportFullSizeTexture = false)
fun finalCameraRgb(exportFullSizeTexture: Boolean): String {
val outputDeclaration = if (exportFullSizeTexture) {
"layout(rgba16ui, binding = 2) writeonly uniform highp uimage2D uFullSizeOutput;"
} else {
"layout(rgba16ui, binding = 1) writeonly uniform highp uimage2DArray uOutput;"
}
val outputStore = if (exportFullSizeTexture) {
"imageStore(uFullSizeOutput, p, outputPixel);"
} else {
"imageStore(uOutput, storage, outputPixel);"
}
return """
#version 310 es
precision highp float;
precision highp int;
precision highp uimage2DArray;
precision highp uimage2D;
layout(local_size_x = 16, local_size_y = 16) in;
layout(rgba16ui, binding = 0) readonly uniform highp uimage2DArray uInput;
layout(rgba16ui, binding = 1) writeonly uniform highp uimage2DArray uOutput;
$outputDeclaration
uniform vec3 uCalculationGains;
$tiledImageCommon
@@ -1361,10 +1563,12 @@ internal object GlesRadianceVgnChromaShaders {
uvec4 encoded = imageLoad(uInput, storage);
vec3 cameraRgb = yccdToCalculationRgb(encoded) /
max(uCalculationGains, vec3(1e-6));
imageStore(uOutput, storage, uvec4(
uvec4 outputPixel = uvec4(
uvec3(clamp(cameraRgb, vec3(0.0), vec3(65504.0)) + vec3(0.5)),
65535u
));
);
$outputStore
}
""".trimIndent()
""".trimIndent()
}
}
@@ -261,6 +261,8 @@ class GlesRawRadianceFusion(
outputScale: Float,
private val debugConfig: RawStackDebugConfig = RawStackDebugConfig.Disabled,
private val fusionTuning: RawRadianceFusionTuning = RawRadianceFusionTuning(),
private val useCurrentGlContext: Boolean = false,
private val exportGpuLinearRgbSource: Boolean = false,
) {
private val outputScale = MultiFrameConfig.normalizeOutputScale(outputScale)
@@ -369,6 +371,8 @@ class GlesRawRadianceFusion(
tuning = tuning,
debugConfig = debugConfig,
radianceFusionTuning = fusionTuning,
useCurrentGlContext = useCurrentGlContext,
exportGpuLinearRgbSource = exportGpuLinearRgbSource,
).processFrames(
frames = fusionFrames,
highlightFrame = highlightFrame,
@@ -37,6 +37,10 @@ internal class GlesRawRadianceStacker(
private val tuning: RawStackTuningProfile = RawStackTuningProfile(),
debugConfig: RawStackDebugConfig = RawStackDebugConfig.Disabled,
private val radianceFusionTuning: RawRadianceFusionTuning = RawRadianceFusionTuning(),
private val useCurrentGlContext: Boolean = false,
private val exportGpuLinearRgbSource: Boolean = false,
private val prewarmHighlightPrograms: Boolean = false,
private val prewarmLongPrograms: Boolean = false,
) {
private data class TextureLevel(val texture: Int, val width: Int, val height: Int)
private data class TemporalGraphSeedResources(
@@ -144,6 +148,10 @@ internal class GlesRawRadianceStacker(
val allocMs: Long,
val mode: String,
)
private data class ReconstructionResult(
val readTiming: ReadOutputTiming,
val exportedTextureId: Int = 0,
)
private data class RadianceVgnImageBinding(
val unit: Int,
val texture: Int,
@@ -211,6 +219,7 @@ internal class GlesRawRadianceStacker(
private var eglDisplay: EGLDisplay = EGL14.EGL_NO_DISPLAY
private var eglContext: EGLContext = EGL14.EGL_NO_CONTEXT
private var eglSurface: EGLSurface = EGL14.EGL_NO_SURFACE
private var ownsEglContext = false
private val textures = ArrayList<Int>()
private val programs = ArrayList<Int>()
@@ -426,11 +435,109 @@ internal class GlesRawRadianceStacker(
private var activeRadianceHighlightFrame: RawRadianceHighlightFrame? = null
private var activeRadianceLongFrames: List<RawRadianceLongFramePlan> = emptyList()
/** Compiles RAW Max programs and executes representative GPU paths in the idle GL context. */
internal fun prewarmCapturePipeline(frameCount: Int) {
require(useCurrentGlContext) {
"RAW Max capture prewarm requires the caller-owned current EGL context"
}
val start = System.currentTimeMillis()
try {
attachCurrentEgl()
ensureGles31()
initPrograms()
applyRawRenderState()
prewarmAlignmentProgramExecution()
PLog.d(
TAG,
"RAW Max reusable programs prewarmed size=${width}x$height frames=$frameCount " +
"took=${System.currentTimeMillis() - start}ms",
)
} finally {
release()
}
}
private fun prewarmAlignmentProgramExecution() {
renderFbo = createFramebuffer()
val trackingTextures = IntArray(2) {
createTexture2D(
PREWARM_TRACKING_WIDTH,
PREWARM_TRACKING_HEIGHT,
GLES30.GL_RGBA16F,
GLES30.GL_LINEAR,
)
}
// Program execution is deliberately representative rather than production-sized. Real
// RAW uploads, temporal graph construction and CPU flow solving depend on captured frames
// and cannot produce reusable results during prewarm.
val syntheticRawTexture = createTexture2D(
PREWARM_RAW_WIDTH,
PREWARM_RAW_HEIGHT,
GLES30.GL_R16UI,
GLES30.GL_NEAREST,
)
trackingTextures.forEachIndexed { index, texture ->
buildTrackingProxy(
rawTexture = syntheticRawTexture,
outputTexture = texture,
outputWidth = PREWARM_TRACKING_WIDTH,
outputHeight = PREWARM_TRACKING_HEIGHT,
levelScale = PREWARM_TRACKING_SCALE,
exposureScale = 1f,
label = "program prewarm frame $index",
)
}
val edgeTexture = createTexture2D(
PREWARM_GRID_WIDTH,
PREWARM_GRID_HEIGHT,
GLES30.GL_RGBA16F,
GLES30.GL_LINEAR,
)
drawAlignment(
reference = TextureLevel(
trackingTextures[0],
PREWARM_TRACKING_WIDTH,
PREWARM_TRACKING_HEIGHT,
),
current = TextureLevel(
trackingTextures[1],
PREWARM_TRACKING_WIDTH,
PREWARM_TRACKING_HEIGHT,
),
levelScale = PREWARM_TRACKING_SCALE,
outputTexture = edgeTexture,
outputGridWidth = PREWARM_GRID_WIDTH,
outputGridHeight = PREWARM_GRID_HEIGHT,
outputTileSpacing = PREWARM_GRID_SPACING,
preAlignment = null,
alignWindowSize = max(
hwmfPrefilter.alignWindowSize,
PREWARM_TRACKING_SCALE * MIN_TEMPORAL_WINDOW_LEVEL_PIXELS,
),
label = "program prewarm edge",
)
readFlowTextures(
textures = listOf(edgeTexture),
textureWidth = PREWARM_GRID_WIDTH,
textureHeight = PREWARM_GRID_HEIGHT,
label = "program prewarm readback",
)
PLog.d(
TAG,
"RAW Max alignment programs executed during prewarm: " +
"tracking=${PREWARM_TRACKING_WIDTH}x$PREWARM_TRACKING_HEIGHT " +
"grid=${PREWARM_GRID_WIDTH}x$PREWARM_GRID_HEIGHT",
)
}
internal fun processFrames(
frames: List<RawStackFrame>,
highlightFrame: RawRadianceHighlightFrame? = null,
longFrames: List<RawRadianceLongFramePlan> = emptyList(),
): RawStackResult? {
require(!exportGpuLinearRgbSource || useCurrentGlContext) {
"A GPU LinearRaw export requires the caller-owned current EGL context"
}
val images = frames.map { it.image }
activeRadianceHighlightFrame = highlightFrame
activeRadianceLongFrames = longFrames
@@ -459,6 +566,7 @@ internal class GlesRawRadianceStacker(
val referenceFocusDistance = frames.first().focusDistanceDiopters
val frameExposureScales = List(frames.size) { 1f }
var outputBuffer: ByteBuffer? = null
var exportedTextureId = 0
var returned = false
val startTime = System.currentTimeMillis()
val originalThreadPriority = GlesGpuScheduler.lowerCurrentThreadPriority(TAG)
@@ -469,7 +577,11 @@ internal class GlesRawRadianceStacker(
)
?.order(ByteOrder.nativeOrder()) ?: return null
initEgl()
if (useCurrentGlContext) {
attachCurrentEgl()
} else {
initEgl()
}
ensureGles31()
validateGpuResourceLimits()
initPrograms()
@@ -637,7 +749,7 @@ internal class GlesRawRadianceStacker(
"highlightAccepted=${highlightAlignment != null}"
}
val superResolutionDecision = decideSuperResolutionOutput(alignedFrameCount)
val reconstructionReadTiming = reconstructRadianceTiles(
val reconstructionResult = reconstructRadianceTiles(
referenceImage = images[0],
frames = frames,
acceptedFrames = acceptedSuperResolutionFrames,
@@ -648,7 +760,8 @@ internal class GlesRawRadianceStacker(
longAlignments = longAlignments,
)
GlesGpuScheduler.yieldToUiRenderer()
val readTiming = reconstructionReadTiming
val readTiming = reconstructionResult.readTiming
exportedTextureId = reconstructionResult.exportedTextureId
outputBuffer.rewind()
val diagnostics = if (hwmfDebug.collectMetrics) {
collectFinalDiagnostics(
@@ -664,7 +777,8 @@ internal class GlesRawRadianceStacker(
RawStackRuntimeDebug.i(TAG) {
"GLES RAW stacking completed in ${System.currentTimeMillis() - startTime}ms " +
"readback=${readTiming.elapsedMs}ms glRead=${readTiming.glReadMs}ms " +
"copy=${readTiming.copyMs}ms alloc=${readTiming.allocMs}ms mode=${readTiming.mode}"
"copy=${readTiming.copyMs}ms alloc=${readTiming.allocMs}ms " +
"gpuHandoff=${exportedTextureId != 0} mode=${readTiming.mode}"
}
RawStackResult(
fusedBayerBuffer = outputBuffer,
@@ -678,6 +792,13 @@ internal class GlesRawRadianceStacker(
inputRowStepSamples = outputWidth * 3,
inputColStepSamples = 3,
baselineExposureEv = highlightAlignment?.frame?.baselineExposureEv,
gpuLinearRgbSource = exportedTextureId.takeIf { it != 0 }?.let { textureId ->
GpuLinearRgbSource(
textureId = textureId,
width = outputWidth,
height = outputHeight,
)
},
)
} catch (e: Exception) {
PLog.e(TAG, "GLES RAW stacking failed", e)
@@ -688,11 +809,15 @@ internal class GlesRawRadianceStacker(
GlesGpuScheduler.restoreCurrentThreadPriority(originalThreadPriority, TAG)
if (!returned) {
LargeDirectBuffer.free(outputBuffer)
if (exportedTextureId != 0) {
GLES30.glDeleteTextures(1, intArrayOf(exportedTextureId), 0)
}
}
}
}
private fun initEgl() {
ownsEglContext = true
eglDisplay = EGL14.eglGetDisplay(EGL14.EGL_DEFAULT_DISPLAY)
if (eglDisplay == EGL14.EGL_NO_DISPLAY) {
throw IllegalStateException("eglGetDisplay failed")
@@ -721,6 +846,22 @@ internal class GlesRawRadianceStacker(
}
}
private fun attachCurrentEgl() {
eglDisplay = EGL14.eglGetCurrentDisplay()
eglContext = EGL14.eglGetCurrentContext()
eglSurface = EGL14.eglGetCurrentSurface(EGL14.EGL_DRAW)
ownsEglContext = false
check(eglDisplay != EGL14.EGL_NO_DISPLAY) {
"GLES RAW stack requires a current EGL display"
}
check(eglContext != EGL14.EGL_NO_CONTEXT) {
"GLES RAW stack requires a current EGL context"
}
check(eglSurface != EGL14.EGL_NO_SURFACE) {
"GLES RAW stack requires a current EGL draw surface"
}
}
private fun chooseConfig(renderableType: Int): EGLConfig? {
val attribs = intArrayOf(
EGL14.EGL_RED_SIZE, 8,
@@ -750,6 +891,8 @@ internal class GlesRawRadianceStacker(
}
private fun initPrograms() {
val needsHighlightPrograms = activeRadianceHighlightFrame != null || prewarmHighlightPrograms
val needsLongPrograms = activeRadianceLongFrames.isNotEmpty() || prewarmLongPrograms
proxyProgram = linkComputeProgram(RAW_PROXY_COMPUTE_SHADER, "raw_proxy")
trackingProxyProgram = linkComputeProgram(RAW_TRACKING_PROXY_COMPUTE_SHADER, "raw_tracking_proxy")
downsampleProgram = linkGraphicsProgram(FULLSCREEN_VERTEX_SHADER, DOWNSAMPLE_FRAGMENT_SHADER, "raw_downsample")
@@ -826,7 +969,7 @@ internal class GlesRawRadianceStacker(
),
"raw_radiance_normalize_r32ui_usampler",
)
if (activeRadianceHighlightFrame != null) {
if (needsHighlightPrograms) {
radianceHighlightNormalizeProgram = linkGraphicsProgram(
FULLSCREEN_VERTEX_SHADER,
GlesRawRadianceFusionShaders.normalize(
@@ -839,7 +982,7 @@ internal class GlesRawRadianceStacker(
"raw_radiance_highlight_normalize_r32ui_usampler",
)
}
if (activeRadianceHighlightFrame != null || activeRadianceLongFrames.isNotEmpty()) {
if (needsHighlightPrograms || needsLongPrograms) {
radianceHighlightValidateFlowProgram = linkGraphicsProgram(
FULLSCREEN_VERTEX_SHADER,
GlesRawRadianceFusionShaders.validateHighlightFlow,
@@ -856,7 +999,7 @@ internal class GlesRawRadianceStacker(
"raw_radiance_highlight_compose_flow",
)
}
if (activeRadianceLongFrames.isNotEmpty()) {
if (needsLongPrograms) {
radianceLongEligibilityProgram = linkGraphicsProgram(
FULLSCREEN_VERTEX_SHADER,
GlesRawRadianceFusionShaders.longEligibility,
@@ -945,6 +1088,7 @@ internal class GlesRawRadianceStacker(
tiles = radianceTiles,
calculationWbGains = demosaicCalculationWbGains,
outputScale = superResolutionScale,
exportFullSizeTexture = exportGpuLinearRgbSource,
backend = object : GlesRadianceVgnChromaPostprocessor.Backend {
override fun linkComputeProgram(source: String, name: String): Int =
this@GlesRawRadianceStacker.linkComputeProgram(source, name)
@@ -1213,9 +1357,27 @@ internal class GlesRawRadianceStacker(
}
val byteOffset = firstRow * plane.rowStride
val uploadBuffer = plane.buffer.duplicate().order(ByteOrder.nativeOrder()).apply { position(byteOffset) }
uploadRawBufferRows(
uploadBuffer = uploadBuffer,
texture = texture,
rowStridePixels = plane.rowStride / RAW_BYTES_PER_PIXEL,
firstRow = firstRow,
rowCount = rowCount,
label = label,
)
}
private fun uploadRawBufferRows(
uploadBuffer: ByteBuffer,
texture: Int,
rowStridePixels: Int,
firstRow: Int,
rowCount: Int,
label: String,
) {
GLES30.glBindTexture(GLES30.GL_TEXTURE_2D, texture)
GLES30.glPixelStorei(GLES30.GL_UNPACK_ALIGNMENT, 1)
GLES30.glPixelStorei(GLES30.GL_UNPACK_ROW_LENGTH, plane.rowStride / 2)
GLES30.glPixelStorei(GLES30.GL_UNPACK_ROW_LENGTH, rowStridePixels)
GLES30.glTexSubImage2D(
GLES30.GL_TEXTURE_2D,
0,
@@ -5396,7 +5558,7 @@ internal class GlesRawRadianceStacker(
outputBuffer: ByteBuffer,
highlightAlignment: RadianceHighlightAlignment?,
longAlignments: List<RadianceLongAlignment>,
): ReadOutputTiming {
): ReconstructionResult {
check(radianceTiles.isNotEmpty())
var requiredRcdWidth = 1
var requiredRcdHeight = 1
@@ -5463,6 +5625,7 @@ internal class GlesRawRadianceStacker(
}
var totalGlReadMs = 0L
var totalCopyMs = 0L
var exportedTextureId = 0
val referenceFrameNoiseModel = frameNoiseModel(frames.first())
RawStackRuntimeDebug.i(TAG) {
"Radiance tiled reconstruction tiles=${radianceTiles.size} " +
@@ -5610,37 +5773,42 @@ internal class GlesRawRadianceStacker(
candidateFrameCount = candidateFrameCount,
)
}
chromaPostprocessor?.processAndReadback(outputBuffer)?.let { timing ->
chromaPostprocessor?.processAndReadback(outputBuffer)?.let { result ->
val timing = result.readbackTiming
readbackAllocMs += timing.allocMs
totalGlReadMs += timing.glReadMs
totalCopyMs += timing.copyMs
exportedTextureId = result.exportedTextureId
}
} finally {
LargeDirectBuffer.free(readbackScratch)
}
outputBuffer.rewind()
return ReadOutputTiming(
elapsedMs = readbackAllocMs + totalGlReadMs + totalCopyMs,
glReadMs = totalGlReadMs,
copyMs = totalCopyMs,
allocMs = readbackAllocMs,
mode = if (radianceUsesVgnSemanticBackend) {
if (chromaPostprocessor != null && highlightAlignment != null) {
"radiance-vgn-semantic-highlight-chroma-iir-rgb16-tiled"
} else if (chromaPostprocessor != null) {
"radiance-vgn-semantic-chroma-iir-rgb16-tiled"
} else if (highlightAlignment != null) {
"radiance-vgn-semantic-highlight-rgb16-tiled"
return ReconstructionResult(
readTiming = ReadOutputTiming(
elapsedMs = readbackAllocMs + totalGlReadMs + totalCopyMs,
glReadMs = totalGlReadMs,
copyMs = totalCopyMs,
allocMs = readbackAllocMs,
mode = if (radianceUsesVgnSemanticBackend) {
if (chromaPostprocessor != null && highlightAlignment != null) {
"radiance-vgn-semantic-highlight-chroma-iir-rgb16-tiled"
} else if (chromaPostprocessor != null) {
"radiance-vgn-semantic-chroma-iir-rgb16-tiled"
} else if (highlightAlignment != null) {
"radiance-vgn-semantic-highlight-rgb16-tiled"
} else {
"radiance-vgn-semantic-rgb16-tiled"
}
} else {
"radiance-vgn-semantic-rgb16-tiled"
}
} else {
if (highlightAlignment != null) {
"radiance-rcd-fallback-highlight-rgb16-tiled"
} else {
"radiance-rcd-fallback-rgb16-tiled"
}
},
if (highlightAlignment != null) {
"radiance-rcd-fallback-highlight-rgb16-tiled"
} else {
"radiance-rcd-fallback-rgb16-tiled"
}
},
),
exportedTextureId = exportedTextureId,
)
}
@@ -7404,18 +7572,26 @@ internal class GlesRawRadianceStacker(
if (buffers.isNotEmpty()) {
GLES31.glDeleteBuffers(buffers.size, buffers.toIntArray(), 0)
}
EGL14.eglMakeCurrent(eglDisplay, EGL14.EGL_NO_SURFACE, EGL14.EGL_NO_SURFACE, EGL14.EGL_NO_CONTEXT)
if (eglSurface != EGL14.EGL_NO_SURFACE) {
EGL14.eglDestroySurface(eglDisplay, eglSurface)
if (ownsEglContext) {
EGL14.eglMakeCurrent(
eglDisplay,
EGL14.EGL_NO_SURFACE,
EGL14.EGL_NO_SURFACE,
EGL14.EGL_NO_CONTEXT,
)
if (eglSurface != EGL14.EGL_NO_SURFACE) {
EGL14.eglDestroySurface(eglDisplay, eglSurface)
}
if (eglContext != EGL14.EGL_NO_CONTEXT) {
EGL14.eglDestroyContext(eglDisplay, eglContext)
}
EGL14.eglTerminate(eglDisplay)
}
if (eglContext != EGL14.EGL_NO_CONTEXT) {
EGL14.eglDestroyContext(eglDisplay, eglContext)
}
EGL14.eglTerminate(eglDisplay)
}
eglDisplay = EGL14.EGL_NO_DISPLAY
eglContext = EGL14.EGL_NO_CONTEXT
eglSurface = EGL14.EGL_NO_SURFACE
ownsEglContext = false
}
companion object {
@@ -7423,6 +7599,15 @@ internal class GlesRawRadianceStacker(
private const val EGL_OPENGL_ES3_BIT_KHR = 0x00000040
private const val LOCAL_SIZE = 16
private const val RAW_BYTES_PER_PIXEL = 2
private const val PREWARM_TRACKING_SCALE = 4
private const val PREWARM_TRACKING_WIDTH = 64
private const val PREWARM_TRACKING_HEIGHT = 48
private const val PREWARM_RAW_WIDTH = PREWARM_TRACKING_WIDTH * PREWARM_TRACKING_SCALE * 2
private const val PREWARM_RAW_HEIGHT = PREWARM_TRACKING_HEIGHT * PREWARM_TRACKING_SCALE * 2
private const val PREWARM_GRID_WIDTH = 4
private const val PREWARM_GRID_HEIGHT = 3
private const val PREWARM_GRID_SPACING = 16
private const val MIN_TEMPORAL_GRAPH_FRAME_COUNT = 3
private const val MIN_TEMPORAL_TRACKING_LEVEL = 2
private const val MIN_TEMPORAL_WINDOW_LEVEL_PIXELS = 8
@@ -16,6 +16,17 @@ enum class RawStackBufferLayout {
LINEAR_RGB,
}
/**
* Opaque LinearRaw texture exported by the stacker into the persistent RAW renderer context.
* It may only be consumed or released on that context's GL dispatcher.
*/
data class GpuLinearRgbSource(
val textureId: Int,
val width: Int,
val height: Int,
val samplesPerPixel: Int = 4,
)
data class RawStackResult(
var fusedBayerBuffer: ByteBuffer?,
val width: Int,
@@ -30,6 +41,7 @@ data class RawStackResult(
val inputRowStepSamples: Int? = null,
val inputColStepSamples: Int? = null,
val baselineExposureEv: Float? = null,
val gpuLinearRgbSource: GpuLinearRgbSource? = null,
)
enum class YuvHdrStackFrameRole {
@@ -170,6 +182,8 @@ object MultiFrameStacker {
lensShadingWidth: Int = 0,
lensShadingHeight: Int = 0,
applyLensShadingCorrection: Boolean = true,
useCurrentGlContext: Boolean = false,
exportGpuLinearRgbSource: Boolean = false,
): RawStackResult? {
if (frames.isEmpty()) return null
val images = frames.map { it.image }
@@ -202,6 +216,8 @@ object MultiFrameStacker {
lensShadingHeight = if (stackLensShading != null) lensShadingHeight else 0,
outputScale = normalizedOutputScale,
debugConfig = RawStackRuntimeDebug.debugConfig,
useCurrentGlContext = useCurrentGlContext,
exportGpuLinearRgbSource = exportGpuLinearRgbSource,
).processFrames(frames)
}
@@ -20,12 +20,18 @@ import com.hinnka.mycamera.lut.ChromaDenoiseShaders
import com.hinnka.mycamera.lut.ShadowsHighlightsShader
import com.hinnka.mycamera.ml.SharedDepthEstimator
import com.hinnka.mycamera.processor.GlesGpuScheduler
import com.hinnka.mycamera.processor.GlesRawRadianceStacker
import com.hinnka.mycamera.processor.GpuLinearRgbSource
import com.hinnka.mycamera.processor.RawNoiseModel
import com.hinnka.mycamera.processor.RawStackResult
import com.hinnka.mycamera.utils.BitmapUtils
import com.hinnka.mycamera.utils.LargeDirectBuffer
import com.hinnka.mycamera.utils.PLog
import com.hinnka.mycamera.utils.RawProcessor
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.asCoroutineDispatcher
import kotlinx.coroutines.currentCoroutineContext
import kotlinx.coroutines.ensureActive
import kotlinx.coroutines.withContext
import java.io.File
import java.nio.ByteBuffer
@@ -198,6 +204,7 @@ class RawDemosaicProcessor {
private const val RCD_PQ_WRITE_BINDING = 5
private const val RCD_PQ_READ_BINDING = 4
private const val RCD_VH_DIR_BINDING = 4
private const val CAPTURE_PROGRAM_PREWARM_LONG_EDGE = 256
private const val RCD_HIGHLIGHT_RECONSTRUCTION_MIN_WB_GAIN = 1e-3f
private const val RCD_HIGHLIGHT_RECONSTRUCTION_MAX_WB_GAIN = 64.0f
// PASS_3 needs 16 pixels, and the following color-noise stages consume another
@@ -259,6 +266,316 @@ class RawDemosaicProcessor {
).apply { isDaemon = true }
}.asCoroutineDispatcher()
private val exportedStackTextureIds = mutableSetOf<Int>()
/** Prepares the persistent RAW renderer and first-use capture passes during camera idle time. */
suspend fun prewarmCapturePipeline(
colorEngine: RawRenderingEngine,
profileToneMapMode: RawProfileToneMapMode,
captureWidth: Int,
captureHeight: Int,
rawMaxFrameCount: Int,
rawMaxEnabled: Boolean,
): Boolean =
withContext(glDispatcher) {
val start = System.currentTimeMillis()
val warmupWidth = captureWidth.coerceAtLeast(1)
val warmupHeight = captureHeight.coerceAtLeast(1)
if (!isInitialized && !initialize()) {
PLog.e(TAG, "Unable to prewarm RAW capture pipeline")
return@withContext false
}
val captureProfileReady = runCatching {
prewarmCaptureProfilePasses(
profileToneMapMode = profileToneMapMode,
captureWidth = warmupWidth,
captureHeight = warmupHeight,
frameCount = rawMaxFrameCount,
)
}.onFailure { error ->
PLog.w(TAG, "RAW capture profile pass prewarm failed", error)
}.getOrDefault(false)
currentCoroutineContext().ensureActive()
val renderEngineReady = runCatching {
prewarmRenderEnginePass(
colorEngine = colorEngine,
captureWidth = warmupWidth,
captureHeight = warmupHeight,
inputTextureId = linearOutputTextureId,
)
}.onFailure { error ->
PLog.w(TAG, "RAW render engine prewarm failed", error)
}.getOrDefault(false)
currentCoroutineContext().ensureActive()
val rawMaxReady = if (rawMaxEnabled) {
runCatching {
GlesRawRadianceStacker(
width = warmupWidth,
height = warmupHeight,
cfaPattern = 0,
blackLevel = FloatArray(4),
whiteLevel = 1023,
noiseModel = FloatArray(2),
rawNoiseModel = RawNoiseModel.EMPTY,
lensShading = null,
lensShadingWidth = 0,
lensShadingHeight = 0,
useCurrentGlContext = true,
exportGpuLinearRgbSource = true,
prewarmHighlightPrograms = true,
prewarmLongPrograms = true,
).prewarmCapturePipeline(rawMaxFrameCount)
true
}.onFailure { error ->
PLog.w(TAG, "RAW Max program prewarm failed", error)
}.getOrDefault(false)
} else {
true
}
GLES30.glFinish()
val ready = captureProfileReady && renderEngineReady && rawMaxReady
PLog.d(
TAG,
"RAW capture pipeline prewarmed ready=$ready engine=$colorEngine " +
"profileToneMap=$profileToneMapMode " +
"capture=${warmupWidth}x$warmupHeight rawMax=$rawMaxEnabled " +
"frames=$rawMaxFrameCount " +
"took=${System.currentTimeMillis() - start}ms",
)
ready
}
/**
* Executes the same shader paths used by capture-time exposure matching and PGTM generation.
* Linking alone is insufficient on drivers that defer pipeline compilation until first draw.
*/
private fun prewarmCaptureProfilePasses(
profileToneMapMode: RawProfileToneMapMode,
captureWidth: Int,
captureHeight: Int,
frameCount: Int,
): Boolean {
val programSize = resolveLongEdgePreviewSize(
captureWidth,
captureHeight,
CAPTURE_PROGRAM_PREWARM_LONG_EDGE,
)
val identity = identityMatrix3x3()
val metadata = RawMetadata(
width = programSize.width,
height = programSize.height,
cfaPattern = RawMetadata.CFA_RGGB,
blackLevel = FloatArray(4),
whiteLevel = 65535f,
whiteBalanceGains = FloatArray(4) { 1f },
colorCorrectionMatrix = identity,
cameraWhite = floatArrayOf(1f, 1f, 1f),
frameCount = frameCount.coerceAtLeast(1),
)
val textures = IntArray(1)
GLES30.glGenTextures(textures.size, textures, 0)
return try {
val linearRawTexture = textures[0]
createCaptureWarmupTexture(
textureId = linearRawTexture,
internalFormat = GLES30.GL_RGBA16UI,
format = GLES30.GL_RGBA_INTEGER,
type = GLES30.GL_UNSIGNED_SHORT,
width = programSize.width,
height = programSize.height,
pixels = null,
)
// These two full-resolution working textures remain attached to the persistent RAW
// renderer and are reused by capture. Only their allocation belongs in prewarm.
setupFullResFramebuffer(captureWidth, captureHeight)
renderLinearRawRgbToFramebuffer(
sourceTextureId = linearRawTexture,
targetFramebufferId = demosaicFramebufferId,
width = programSize.width,
height = programSize.height,
)
val exposureReady = renderExposurePreviewRequest(
request = RawExposurePreviewRequest(
width = programSize.width,
height = programSize.height,
solve = { renderSample -> if (renderSample(0f) != null) 0f else null },
),
metadata = metadata,
samplesPerPixel = 4,
sourceTextureId = demosaicTextureId,
rawBlackPointCorrection = 0f,
rawWhitePointCorrection = 0f,
colorCorrectionMatrix = identity,
cameraWhite = metadata.cameraWhite,
dcpRenderPlan = null,
applyLinearDngBaselineExposure = false,
applyProfileDngBaselineExposure = false,
applyProfileGainTableMap = false,
clampProfileRgb = true,
outputBounds = Rect(0, 0, programSize.width, programSize.height),
outputRotation = 0,
spectralFilmLut = null,
colorEngine = RawRenderingEngine.AdobeCurve,
outputWorkingColorSpace = ColorSpace.ProPhoto,
profileToEngineTransform = identity,
rawToneMappingParameters = RawToneMappingParameters.DEFAULT,
useProfileExposureRamp = true,
applyProfileDcpBaselineExposureOffset = false,
supportProfileOverrange = false,
) != null
val warmedProfileMap = when (profileToneMapMode) {
RawProfileToneMapMode.Photon,
RawProfileToneMapMode.GooglePixel -> generateProfileGainTableMapOnGpu(
rawTextureId = linearRawTexture,
width = programSize.width,
height = programSize.height,
samplesPerPixel = 4,
metadata = metadata,
statsBounds = Rect(0, 0, programSize.width, programSize.height),
baselineExposureEv = 0f,
profileToneMapMode = profileToneMapMode,
colorCorrectionMatrix = identity,
cameraWhite = metadata.cameraWhite,
hueSatMap = null,
)
else -> null
}
val profileReady = when (profileToneMapMode) {
RawProfileToneMapMode.Photon,
RawProfileToneMapMode.GooglePixel -> warmedProfileMap != null
else -> true
}
// Execute only a small viewport to force deferred driver compilation. PGTM output is
// scene-dependent, so the synthetic map is deliberately not uploaded or retained.
renderLinearRcdPass(
metadata = metadata,
sourceTextureId = demosaicTextureId,
targetFramebufferId = linearOutputFramebufferId,
viewportWidth = programSize.width,
viewportHeight = programSize.height,
rawExposureCompensation = 0f,
colorCorrectionMatrix = identity,
cameraWhite = metadata.cameraWhite,
hueSatMap = null,
applyDngBaselineExposure = false,
applyProfileGainTableMap = false,
profileBaselineExposureOffsetEv = 0f,
clampProfileRgb = true,
supportProfileOverrange = false,
label = "CaptureWarmupLinearRcdPass",
)
PLog.d(
TAG,
"RAW reusable capture state prewarmed: capture=${captureWidth}x$captureHeight " +
"programViewport=${programSize.width}x${programSize.height} " +
"profile=$profileToneMapMode",
)
exposureReady && profileReady
} finally {
GLES30.glBindTexture(GLES30.GL_TEXTURE_2D, 0)
GLES30.glDeleteTextures(textures.size, textures, 0)
}
}
private fun prewarmRenderEnginePass(
colorEngine: RawRenderingEngine,
captureWidth: Int,
captureHeight: Int,
inputTextureId: Int,
): Boolean {
check(inputTextureId != 0) { "Full-resolution RAW warmup input is unavailable" }
val programSize = resolveLongEdgePreviewSize(
captureWidth,
captureHeight,
CAPTURE_PROGRAM_PREWARM_LONG_EDGE,
)
// Allocate the render targets at capture size because these objects remain reusable, but
// draw only a small viewport: full-frame tone mapping is real capture work, not prewarm.
setupEngineToneFramebuffer(captureWidth, captureHeight)
val engineToneReady = renderEngineTonePass(
inputTextureId = inputTextureId,
dcpRenderPlan = null,
applyDcpHueSatMap = false,
spectralFilmLut = null,
colorEngine = colorEngine,
profileToEngineTransform = identityMatrix3x3(),
profileExposureUniforms = ProfileExposureUniforms.NEUTRAL,
rawToneMappingParameters = RawToneMappingParameters.DEFAULT,
outputTransform = computeWorkingToOutputTransform(
colorEngine.workingColorSpace,
ColorSpace.SRGB,
),
viewportWidth = programSize.width,
viewportHeight = programSize.height,
)
setupCombinedFramebuffer(captureWidth, captureHeight)
return engineToneReady && renderSrgbPass(
inputTextureId = engineToneTextureId,
viewportWidth = programSize.width,
viewportHeight = programSize.height,
)
}
private fun createCaptureWarmupTexture(
textureId: Int,
internalFormat: Int,
format: Int,
type: Int,
width: Int,
height: Int,
pixels: ByteBuffer?,
) {
check(textureId != 0) { "Unable to allocate capture warmup texture" }
GLES30.glBindTexture(GLES30.GL_TEXTURE_2D, textureId)
GLES30.glTexParameteri(GLES30.GL_TEXTURE_2D, GLES30.GL_TEXTURE_MIN_FILTER, GLES30.GL_NEAREST)
GLES30.glTexParameteri(GLES30.GL_TEXTURE_2D, GLES30.GL_TEXTURE_MAG_FILTER, GLES30.GL_NEAREST)
GLES30.glTexParameteri(GLES30.GL_TEXTURE_2D, GLES30.GL_TEXTURE_WRAP_S, GLES30.GL_CLAMP_TO_EDGE)
GLES30.glTexParameteri(GLES30.GL_TEXTURE_2D, GLES30.GL_TEXTURE_WRAP_T, GLES30.GL_CLAMP_TO_EDGE)
GLES30.glPixelStorei(GLES30.GL_UNPACK_ALIGNMENT, 2)
GLES30.glTexImage2D(
GLES30.GL_TEXTURE_2D,
0,
internalFormat,
width,
height,
0,
format,
type,
pixels,
)
checkGlError("createCaptureWarmupTexture")
}
/** Runs the stacker in this renderer's persistent EGL context and registers its GPU result. */
internal suspend fun runStackingOnGlContext(
block: () -> RawStackResult?,
): RawStackResult? = withContext(glDispatcher) {
if (!isInitialized && !initialize()) {
PLog.e(TAG, "Unable to initialize shared RAW stacking context")
return@withContext null
}
block()?.also { result ->
result.gpuLinearRgbSource?.let { source ->
check(source.textureId != 0)
exportedStackTextureIds += source.textureId
}
}
}
internal suspend fun releaseGpuLinearRgbSource(source: GpuLinearRgbSource?) {
if (source == null) return
withContext(glDispatcher) {
if (exportedStackTextureIds.remove(source.textureId)) {
GLES30.glDeleteTextures(1, intArrayOf(source.textureId), 0)
checkGlError("release stacked LinearRaw texture")
}
}
}
// EGL 资源
private var eglDisplay: EGLDisplay = EGL14.EGL_NO_DISPLAY
private var eglContext: EGLContext = EGL14.EGL_NO_CONTEXT
@@ -739,6 +1056,7 @@ class RawDemosaicProcessor {
height = input.height,
rowStride = input.rowStride,
samplesPerPixel = input.samplesPerPixel,
gpuLinearRgbSource = input.gpuLinearRgbSource,
metadata = input.metadata.copy(profileGainTableMap = null),
aspectRatio = aspectRatio,
cropRegion = cropRegion,
@@ -862,6 +1180,7 @@ class RawDemosaicProcessor {
height: Int,
rowStride: Int,
samplesPerPixel: Int,
gpuLinearRgbSource: GpuLinearRgbSource? = null,
metadata: RawMetadata,
aspectRatio: AspectRatio?,
cropRegion: Rect?,
@@ -939,6 +1258,7 @@ class RawDemosaicProcessor {
height = height,
rowStride = rowStride,
samplesPerPixel = samplesPerPixel,
gpuLinearRgbSource = gpuLinearRgbSource,
metadata = renderMetadata,
aspectRatio = aspectRatio,
cropRegion = cropRegion,
@@ -987,6 +1307,7 @@ class RawDemosaicProcessor {
height: Int = 0,
rowStride: Int = 0,
samplesPerPixel: Int = 1,
gpuLinearRgbSource: GpuLinearRgbSource? = null,
metadata: RawMetadata? = null,
aspectRatio: AspectRatio?,
cropRegion: Rect?,
@@ -1030,6 +1351,24 @@ class RawDemosaicProcessor {
var actualHeight = height
var actualRowStride = rowStride
var actualSamplesPerPixel = samplesPerPixel.coerceAtLeast(1)
val borrowedGpuSource = gpuLinearRgbSource?.takeIf { source ->
val valid = source.textureId != 0 &&
source.width == width && source.height == height &&
source.samplesPerPixel in 3..4 &&
exportedStackTextureIds.contains(source.textureId)
if (!valid) {
PLog.w(
TAG,
"Ignoring invalid or stale stacked GPU source texture=${source.textureId} " +
"source=${source.width}x${source.height}x${source.samplesPerPixel} " +
"buffer=${width}x${height}x$samplesPerPixel",
)
}
valid
}
if (borrowedGpuSource != null) {
actualSamplesPerPixel = borrowedGpuSource.samplesPerPixel
}
var actualMetadata = metadata
var actualRotation = rotation
var dngRawDataCleanup: DngRawData? = null
@@ -1216,7 +1555,17 @@ class RawDemosaicProcessor {
return@withContext null
}
setupFullResFramebuffer(actualWidth, actualHeight)
if (actualSamplesPerPixel in 3..4) {
if (borrowedGpuSource != null) {
if (rawTextureId != 0 && rawTextureId != borrowedGpuSource.textureId) {
GLES30.glDeleteTextures(1, intArrayOf(rawTextureId), 0)
}
rawTextureId = borrowedGpuSource.textureId
PLog.d(
TAG,
"Using GPU-resident LinearRaw input: ${actualWidth}x${actualHeight} " +
"samplesPerPixel=$actualSamplesPerPixel texture=$rawTextureId",
)
} else if (actualSamplesPerPixel in 3..4) {
uploadLinearRawRgbTextureFromBuffer(
actualRawData,
actualWidth,
@@ -1467,17 +1816,24 @@ class RawDemosaicProcessor {
// keep the raw-domain repair enabled before Filmic HR.
val rawDomainHighlightReconstructionEnabled = true
if (RawMetadata.isQuadBayer(actualMetadata.cfaPattern)) {
check(ensureQuadBayerPrograms()) {
"Unable to initialize Quad Bayer demosaic programs"
}
runQuadBayerDemosaic(
actualMetadata,
actualWidth,
actualHeight,
highlightReconstructionEnabled = rawDomainHighlightReconstructionEnabled
)
} else {
if (actualMetadata.frameCount > 1) {
} else if (actualMetadata.frameCount > 1) {
check(ensureStandardBayerRcdPrograms()) {
"Unable to initialize Standard Bayer RCD programs"
}
runStandardBayerRcdDemosaic(actualMetadata, actualWidth, actualHeight)
} else {
// Linear HDR/MFSR helpers below also call the old RCD method directly.
check(ensureVgnPrograms()) {
"Unable to initialize single-frame VGN demosaic programs"
}
runSingleFrameVgnDemosaic(
metadata = actualMetadata,
width = actualWidth,
@@ -1485,7 +1841,6 @@ class RawDemosaicProcessor {
highlightReconstructionEnabled = rawDomainHighlightReconstructionEnabled,
)
}
}
}
dngWarpRectilinear?.takeIf { it.isNotEmpty() && it.size % 8 == 0 }?.let { warps ->
var appliedWarpCount = 0
@@ -1735,7 +2090,9 @@ class RawDemosaicProcessor {
releaseDenoiseProfileFramebuffers()
// rawTextureId 已被 RCD populate 消费,提前释放 GPU 显存
if (rawTextureId != 0) {
GLES30.glDeleteTextures(1, intArrayOf(rawTextureId), 0)
if (rawTextureId != borrowedGpuSource?.textureId) {
GLES30.glDeleteTextures(1, intArrayOf(rawTextureId), 0)
}
rawTextureId = 0
}
val workingColorSpace = resolveWorkingColorSpace()
@@ -1861,6 +2218,9 @@ class RawDemosaicProcessor {
)
}
} finally {
if (rawTextureId == borrowedGpuSource?.textureId) {
rawTextureId = 0
}
embeddedDngJpegPreview?.takeIf { !it.isRecycled }?.recycle()
dngRawDataCleanup?.close()
}
@@ -1870,6 +2230,8 @@ class RawDemosaicProcessor {
rawTextureId: Int,
width: Int,
height: Int,
rawTextureWidth: Int = width,
rawTextureHeight: Int = height,
samplesPerPixel: Int,
metadata: RawMetadata,
statsBounds: Rect?,
@@ -1879,11 +2241,13 @@ class RawDemosaicProcessor {
cameraWhite: FloatArray,
hueSatMap: DcpHueSatMap?,
): DngProfileGainTableMap? {
if (rawTextureId == 0 || width <= 0 || height <= 0 || metadata.whiteLevel <= 0f) {
if (rawTextureId == 0 || width <= 0 || height <= 0 ||
rawTextureWidth <= 0 || rawTextureHeight <= 0 || metadata.whiteLevel <= 0f
) {
PLog.e(
TAG,
"GPU RAW PGTM input invalid: texture=$rawTextureId size=${width}x$height " +
"white=${metadata.whiteLevel}",
"source=${rawTextureWidth}x$rawTextureHeight white=${metadata.whiteLevel}",
)
return null
}
@@ -1905,8 +2269,16 @@ class RawDemosaicProcessor {
return null
}
val exposureGain = DngBaselineExposure.exactGain(baselineExposureEv)
val safeStatsBounds = sanitizePgtmStatsBounds(statsBounds, width, height) ?: run {
PLog.e(TAG, "GPU RAW PGTM stats bounds invalid: source=${width}x$height bounds=$statsBounds")
val safeStatsBounds = sanitizePgtmStatsBounds(
statsBounds,
rawTextureWidth,
rawTextureHeight,
) ?: run {
PLog.e(
TAG,
"GPU RAW PGTM stats bounds invalid: source=${rawTextureWidth}x$rawTextureHeight " +
"bounds=$statsBounds",
)
return null
}
val gridSize = DngHdrProfileGainTableGenerator.gridSizeFor(width, height)
@@ -1963,8 +2335,8 @@ class RawDemosaicProcessor {
)
GLES31.glUniform2i(
GLES31.glGetUniformLocation(pgtmCellStatsProgram, "uImageSize"),
width,
height,
rawTextureWidth,
rawTextureHeight,
)
GLES31.glUniform4i(
GLES31.glGetUniformLocation(pgtmCellStatsProgram, "uStatsBounds"),
@@ -2239,6 +2611,7 @@ class RawDemosaicProcessor {
PLog.d(
TAG,
"GPU RAW PGTM prepared: mode=$profileToneMapMode size=${width}x$height " +
"source=${rawTextureWidth}x$rawTextureHeight " +
"grid=${gridWidth}x$gridHeight samplesPerPixel=$samplesPerPixel " +
photonSummary +
"statsGpuMs=${(statsGpuReadyNs - statsGpuStartNs) / 1_000_000.0} " +
@@ -2547,27 +2920,14 @@ class RawDemosaicProcessor {
initShaderProgram()
if (sharpenProgram == 0 || passthroughProgram == 0 ||
chromaDenoiseGuideProgram == 0 || chromaDenoiseProgram == 0 ||
rcdPopulateProgram == 0 || rcdStep1Program == 0 || rcdStep2Program == 0 ||
rcdStep3Program == 0 || rcdStep40Program == 0 || rcdStep41Program == 0 ||
rcdStep42Program == 0 || rcdStep43Program == 0 || rcdWriteOutputProgram == 0 ||
quadPopulateProgram == 0 || quadGreenProgram == 0 || quadChromaProgram == 0 ||
quadRefineProgram == 0 || quadWriteOutputProgram == 0 ||
linearRcdProgram == 0 || linearRawRgbProgram == 0 ||
vgnPrograms.any { it == 0 }
linearRcdProgram == 0 || linearRawRgbProgram == 0
) {
PLog.e(
TAG, "Critical shader programs failed to compile or link. " +
"sharpen=$sharpenProgram pass=$passthroughProgram " +
"chromaGuide=$chromaDenoiseGuideProgram " +
"chromaDenoise=$chromaDenoiseProgram " +
"populate=$rcdPopulateProgram step1=$rcdStep1Program step2=$rcdStep2Program " +
"step3=$rcdStep3Program step40=$rcdStep40Program step41=$rcdStep41Program " +
"step42=$rcdStep42Program step43=$rcdStep43Program write=$rcdWriteOutputProgram " +
"quadPopulate=$quadPopulateProgram quadGreen=$quadGreenProgram " +
"quadChroma=$quadChromaProgram quadRefine=$quadRefineProgram " +
"quadWrite=$quadWriteOutputProgram " +
"linearRcd=$linearRcdProgram linearRawRgb=$linearRawRgbProgram " +
"vgn=${vgnPrograms.contentToString()}"
"linearRcd=$linearRcdProgram linearRawRgb=$linearRawRgbProgram"
)
return false
}
@@ -2708,8 +3068,9 @@ class RawDemosaicProcessor {
GLES30.glDeleteShader(fShaderPass)
}
// 2.8 RCD Programs
initRcdPrograms(vShader)
// LinearRaw/Profile programs are common to both CFA and pre-demosaiced inputs.
// Expensive CFA demosaic programs are compiled only if a CFA input actually needs them.
initLinearRawPrograms(vShader)
GLES30.glDeleteShader(vShader)
PLog.d(
@@ -2999,24 +3360,7 @@ class RawDemosaicProcessor {
}
""".trimIndent()
private fun initRcdPrograms(vShader: Int) {
rcdPopulateProgram = compileComputeProgram(RcdShaders.POPULATE, "POPULATE")
rcdStep1Program = compileComputeProgram(RcdShaders.STEP_1, "STEP_1")
rcdStep2Program = compileComputeProgram(RcdShaders.STEP_2, "STEP_2")
rcdStep3Program = compileComputeProgram(RcdShaders.STEP_3, "STEP_3")
rcdStep40Program = compileComputeProgram(RcdShaders.STEP_4_0, "STEP_4_0")
rcdStep41Program = compileComputeProgram(RcdShaders.STEP_4_1, "STEP_4_1")
rcdStep42Program = compileComputeProgram(RcdShaders.STEP_4_2, "STEP_4_2")
rcdStep43Program = compileComputeProgram(RcdShaders.STEP_4_3, "STEP_4_3")
rcdWriteOutputProgram = compileComputeProgram(RcdShaders.WRITE_OUTPUT, "WRITE_OUTPUT")
VgnShaders.PROGRAM_SOURCES.forEachIndexed { index, (label, source) ->
vgnPrograms[index] = compileComputeProgram(source, "VGN_${label.uppercase(Locale.ROOT)}")
}
quadPopulateProgram = compileComputeProgram(QuadBayerShaders.POPULATE, "QUAD_POPULATE")
quadGreenProgram = compileComputeProgram(QuadBayerShaders.GREEN, "QUAD_GREEN")
quadChromaProgram = compileComputeProgram(QuadBayerShaders.CHROMA, "QUAD_CHROMA")
quadRefineProgram = compileComputeProgram(QuadBayerShaders.REFINE, "QUAD_REFINE")
quadWriteOutputProgram = compileComputeProgram(QuadBayerShaders.WRITE_OUTPUT, "QUAD_WRITE_OUTPUT")
private fun initLinearRawPrograms(vShader: Int) {
pgtmCellStatsProgram = compileComputeProgram(
DngHdrProfileGainTableGpuShaders.CELL_STATS,
"DNG_PGTM_CELL_STATS",
@@ -3058,6 +3402,92 @@ class RawDemosaicProcessor {
)
}
private fun ensureStandardBayerRcdPrograms(): Boolean {
if (rcdPopulateProgram != 0 && rcdStep1Program != 0 && rcdStep2Program != 0 &&
rcdStep3Program != 0 && rcdStep40Program != 0 && rcdStep41Program != 0 &&
rcdStep42Program != 0 && rcdStep43Program != 0 && rcdWriteOutputProgram != 0
) {
return true
}
val start = System.currentTimeMillis()
if (rcdPopulateProgram == 0) {
rcdPopulateProgram = compileComputeProgram(RcdShaders.POPULATE, "POPULATE")
}
if (rcdStep1Program == 0) {
rcdStep1Program = compileComputeProgram(RcdShaders.STEP_1, "STEP_1")
}
if (rcdStep2Program == 0) {
rcdStep2Program = compileComputeProgram(RcdShaders.STEP_2, "STEP_2")
}
if (rcdStep3Program == 0) {
rcdStep3Program = compileComputeProgram(RcdShaders.STEP_3, "STEP_3")
}
if (rcdStep40Program == 0) {
rcdStep40Program = compileComputeProgram(RcdShaders.STEP_4_0, "STEP_4_0")
}
if (rcdStep41Program == 0) {
rcdStep41Program = compileComputeProgram(RcdShaders.STEP_4_1, "STEP_4_1")
}
if (rcdStep42Program == 0) {
rcdStep42Program = compileComputeProgram(RcdShaders.STEP_4_2, "STEP_4_2")
}
if (rcdStep43Program == 0) {
rcdStep43Program = compileComputeProgram(RcdShaders.STEP_4_3, "STEP_4_3")
}
if (rcdWriteOutputProgram == 0) {
rcdWriteOutputProgram = compileComputeProgram(RcdShaders.WRITE_OUTPUT, "WRITE_OUTPUT")
}
val ready = rcdPopulateProgram != 0 && rcdStep1Program != 0 && rcdStep2Program != 0 &&
rcdStep3Program != 0 && rcdStep40Program != 0 && rcdStep41Program != 0 &&
rcdStep42Program != 0 && rcdStep43Program != 0 && rcdWriteOutputProgram != 0
PLog.d(TAG, "Standard Bayer RCD programs ready=$ready, took=${System.currentTimeMillis() - start}ms")
return ready
}
private fun ensureVgnPrograms(): Boolean {
if (vgnPrograms.all { it != 0 }) return true
val start = System.currentTimeMillis()
VgnShaders.PROGRAM_SOURCES.forEachIndexed { index, (label, source) ->
if (vgnPrograms[index] == 0) {
vgnPrograms[index] = compileComputeProgram(
source,
"VGN_${label.uppercase(Locale.ROOT)}",
)
}
}
val ready = vgnPrograms.all { it != 0 }
PLog.d(TAG, "Single-frame VGN programs ready=$ready, took=${System.currentTimeMillis() - start}ms")
return ready
}
private fun ensureQuadBayerPrograms(): Boolean {
if (quadPopulateProgram != 0 && quadGreenProgram != 0 && quadChromaProgram != 0 &&
quadRefineProgram != 0 && quadWriteOutputProgram != 0
) {
return true
}
val start = System.currentTimeMillis()
if (quadPopulateProgram == 0) {
quadPopulateProgram = compileComputeProgram(QuadBayerShaders.POPULATE, "QUAD_POPULATE")
}
if (quadGreenProgram == 0) {
quadGreenProgram = compileComputeProgram(QuadBayerShaders.GREEN, "QUAD_GREEN")
}
if (quadChromaProgram == 0) {
quadChromaProgram = compileComputeProgram(QuadBayerShaders.CHROMA, "QUAD_CHROMA")
}
if (quadRefineProgram == 0) {
quadRefineProgram = compileComputeProgram(QuadBayerShaders.REFINE, "QUAD_REFINE")
}
if (quadWriteOutputProgram == 0) {
quadWriteOutputProgram = compileComputeProgram(QuadBayerShaders.WRITE_OUTPUT, "QUAD_WRITE_OUTPUT")
}
val ready = quadPopulateProgram != 0 && quadGreenProgram != 0 && quadChromaProgram != 0 &&
quadRefineProgram != 0 && quadWriteOutputProgram != 0
PLog.d(TAG, "Quad Bayer programs ready=$ready, took=${System.currentTimeMillis() - start}ms")
return ready
}
private fun linkFragmentProgram(
vShader: Int,
fragmentSource: String,
@@ -8814,6 +9244,17 @@ class RawDemosaicProcessor {
denoiseNlmMaxSsboBytes = 0L
releaseDarktableFilmicHighlightReconstructionFramebuffers()
if (exportedStackTextureIds.isNotEmpty()) {
if (rawTextureId in exportedStackTextureIds) {
rawTextureId = 0
}
GLES30.glDeleteTextures(
exportedStackTextureIds.size,
exportedStackTextureIds.toIntArray(),
0,
)
exportedStackTextureIds.clear()
}
if (rawTextureId != 0) GLES30.glDeleteTextures(1, intArrayOf(rawTextureId), 0)
if (profileGainTableTextureId != 0) {
GLES30.glDeleteTextures(1, intArrayOf(profileGainTableTextureId), 0)
@@ -1,6 +1,7 @@
package com.hinnka.mycamera.raw
import android.graphics.Rect
import com.hinnka.mycamera.processor.GpuLinearRgbSource
import java.nio.ByteBuffer
/** Metadata generated before a RAW buffer is written as DNG. */
@@ -21,6 +22,7 @@ data class RawDngCaptureProfileInput(
val rowStride: Int,
val samplesPerPixel: Int,
val metadata: RawMetadata,
val gpuLinearRgbSource: GpuLinearRgbSource? = null,
)
data class RawDngCaptureProfileResult(
@@ -10,6 +10,7 @@ import android.util.Log
import android.util.Size
import com.hinnka.mycamera.camera.AspectRatio
import com.hinnka.mycamera.model.SafeImage
import com.hinnka.mycamera.processor.GpuLinearRgbSource
import com.hinnka.mycamera.raw.DngProfileGainTableMap
import com.hinnka.mycamera.raw.DngBaselineExposure
import com.hinnka.mycamera.raw.DngProfileToneCurve
@@ -463,6 +464,7 @@ object RawProcessor {
suspend fun prepareRawDngProfile(
rawBuffer: ByteBuffer,
gpuLinearRgbSource: GpuLinearRgbSource? = null,
width: Int,
height: Int,
characteristics: CameraCharacteristics,
@@ -533,6 +535,7 @@ object RawProcessor {
rowStride = inputRowStrideBytes,
samplesPerPixel = inputSamplesPerPixel,
metadata = statsMetadata.copy(profileGainTableMap = null),
gpuLinearRgbSource = gpuLinearRgbSource,
)
)
val exposureOffsetEv = captureProfile?.exposureOffsetEv
@@ -57,6 +57,8 @@ import com.hinnka.mycamera.model.EffectParams
import com.hinnka.mycamera.raw.RawProcessingPreferences
import com.hinnka.mycamera.raw.RawProfile
import com.hinnka.mycamera.raw.RawCfaCorrection
import com.hinnka.mycamera.raw.RawDemosaicProcessor
import com.hinnka.mycamera.raw.RawProfileToneMapMode
import com.hinnka.mycamera.raw.RawRenderingEngine
import com.hinnka.mycamera.raw.RawSharpeningDefaults
import com.hinnka.mycamera.raw.RawToneMappingParameters
@@ -2097,12 +2099,59 @@ class CameraViewModel(application: Application) : AndroidViewModel(application)
}
}
fun prewarmDepthEstimator() {
fun prewarmCapturePipeline() {
if (startupPrewarmJob?.isActive == true) return
startupPrewarmJob = viewModelScope.launch {
val prefs = userPreferencesRepository.userPreferences.firstOrNull()
prewarmRawDcp(prefs?.rawDcpIdForLens(state.value.currentCameraId))
val currentState = state.value
val captureSize = currentState.currentCaptureSize
val rawCaptureEnabled = prefs?.useRaw == true
val rawMaxFrameCount = MultiFrameConfig.normalFrameCount(
prefs?.multiFrameCount ?: MultiFrameConfig.DEFAULT_FRAME_COUNT,
)
supervisorScope {
val dcpPrewarmJob = if (rawCaptureEnabled) {
async {
runCatching {
prewarmRawDcp(prefs.rawDcpIdForLens(currentState.currentCameraId))
}.onFailure { error ->
if (error is CancellationException) throw error
PLog.w(TAG, "RAW DCP prewarm failed", error)
}
}
} else {
null
}
// Keep the two GL warmups sequential. They use independent contexts but still
// share one GPU with preview, so running both at once only increases contention.
if (rawCaptureEnabled) {
runCatching {
RawDemosaicProcessor.getInstance().prewarmCapturePipeline(
prefs.rawRenderingEngine,
prefs.rawToneMappingParameters
.normalized()
.profileToneMapMode,
captureWidth = captureSize.width,
captureHeight = captureSize.height,
rawMaxFrameCount = rawMaxFrameCount,
rawMaxEnabled = currentState.isMultiFrameEnabled,
)
}.onFailure { error ->
if (error is CancellationException) throw error
PLog.w(TAG, "RAW capture pipeline prewarm failed", error)
}
}
currentCoroutineContext().ensureActive()
runCatching {
contentRepository.imageProcessor.prewarmCapturePipeline()
}.onFailure { error ->
if (error is CancellationException) throw error
PLog.w(TAG, "LUT capture pipeline prewarm failed", error)
}
dcpPrewarmJob?.await()
}
}
}
@@ -2542,6 +2591,11 @@ class CameraViewModel(application: Application) : AndroidViewModel(application)
return
}
startupPrewarmJob?.takeIf { it.isActive }?.let { job ->
PLog.d(TAG, "Canceling idle capture prewarm for shutter priority")
job.cancel()
}
if (userPreferences.value.saveLocation) {
val location = locationManager.getCurrentLocation()
cameraController.setLocation(location?.latitude, location?.longitude)
@@ -5795,7 +5849,7 @@ class CameraViewModel(application: Application) : AndroidViewModel(application)
// Delay prewarming to avoid stuttering during the initial reveal animation
// 150ms initial delay + 800ms animation + 250ms buffer
delay(1200)
prewarmDepthEstimator()
prewarmCapturePipeline()
}
}
@@ -48,6 +48,19 @@ class GlesRadianceVgnChromaPostprocessorTest {
assertTrue(GlesRadianceVgnChromaShaders.iirError.contains("for (int i = 0; i < innerSize; ++i)"))
}
@Test
fun gpuHandoffVariantWritesTheSameFinalPixelToAFullSizeTexture() {
val tiled = GlesRadianceVgnChromaShaders.finalCameraRgb(exportFullSizeTexture = false)
val fullSize = GlesRadianceVgnChromaShaders.finalCameraRgb(exportFullSizeTexture = true)
assertTrue(tiled.contains("uimage2DArray uOutput"))
assertTrue(tiled.contains("imageStore(uOutput, storage, outputPixel)"))
assertTrue(!tiled.contains("uFullSizeOutput"))
assertTrue(fullSize.contains("uimage2D uFullSizeOutput"))
assertTrue(fullSize.contains("imageStore(uFullSizeOutput, p, outputPixel)"))
assertTrue(!fullSize.contains("uimage2DArray uOutput"))
}
@Test
fun nativeScaleRetainsReferenceVgnCoefficientsAndSrScaleLowersDigitalCutoff() {
val native = RadianceVgnChromaIirCoefficients.forOutputScale(1f)
@@ -95,6 +108,7 @@ class GlesRadianceVgnChromaPostprocessorTest {
GlesRadianceVgnChromaShaders.iirError,
GlesRadianceVgnChromaShaders.colorNoiseFilter,
GlesRadianceVgnChromaShaders.finalCameraRgb,
GlesRadianceVgnChromaShaders.finalCameraRgb(exportFullSizeTexture = true),
)
sources.forEachIndexed { index, source ->
val sourceFile = File.createTempFile("radiance-vgn-chroma-$index-", ".compute")