diff --git a/app/src/main/java/com/hinnka/mycamera/lut/ColorPassProgram.kt b/app/src/main/java/com/hinnka/mycamera/lut/ColorPassProgram.kt index cb26185e..fa78d4ee 100644 --- a/app/src/main/java/com/hinnka/mycamera/lut/ColorPassProgram.kt +++ b/app/src/main/java/com/hinnka/mycamera/lut/ColorPassProgram.kt @@ -8,6 +8,7 @@ internal data class ColorPassLocations( val uMVPMatrixLocation: Int, val uSTMatrixLocation: Int, val uCameraTextureLocation: Int, + val uEnginePreviewLutLocation: Int, val uLutTextureLocation: Int, val uLutSizeLocation: Int, val uLutIntensityLocation: Int, @@ -114,6 +115,7 @@ internal class PreviewColorProgramCache { uMVPMatrixLocation = GLES30.glGetUniformLocation(program, "uMVPMatrix"), uSTMatrixLocation = GLES30.glGetUniformLocation(program, "uSTMatrix"), uCameraTextureLocation = GLES30.glGetUniformLocation(program, "uCameraTexture"), + uEnginePreviewLutLocation = GLES30.glGetUniformLocation(program, "uEnginePreviewLut"), uLutTextureLocation = GLES30.glGetUniformLocation(program, "uLutTexture"), uLutSizeLocation = GLES30.glGetUniformLocation(program, "uLutSize"), uLutIntensityLocation = GLES30.glGetUniformLocation(program, "uLutIntensity"), diff --git a/app/src/main/java/com/hinnka/mycamera/lut/LutRenderer.kt b/app/src/main/java/com/hinnka/mycamera/lut/LutRenderer.kt index c61f2729..f6e44e29 100644 --- a/app/src/main/java/com/hinnka/mycamera/lut/LutRenderer.kt +++ b/app/src/main/java/com/hinnka/mycamera/lut/LutRenderer.kt @@ -779,6 +779,7 @@ class LutRenderer(context: Context) : GLSurfaceView.Renderer { lutEnabled: Boolean, params: com.hinnka.mycamera.model.ColorRecipeParams, enableVideoLog: Boolean, + includeEnginePreview: Boolean = false, ): ColorPassLocations? { val variant = PreviewColorShaderVariant.forPass( textureSource = textureSource, @@ -787,7 +788,7 @@ class LutRenderer(context: Context) : GLSurfaceView.Renderer { lutEnabled = lutEnabled && lutConfig != null, videoLogEnabled = enableVideoLog && videoLogProfile.isEnabled, ) - return colorProgramCache.get(variant) + return colorProgramCache.get(variant.copy(includeEnginePreview = includeEnginePreview)) } private fun drawColorPass( @@ -814,6 +815,7 @@ class LutRenderer(context: Context) : GLSurfaceView.Renderer { GLES30.glClear(GLES30.GL_COLOR_BUFFER_BIT) GLES30.glUseProgram(locations.programId) colorProgramCache.bindLogInput(locations) + enginePreview.bind(locations.uEnginePreviewLutLocation) GLES30.glActiveTexture(GLES30.GL_TEXTURE0) GLES30.glBindTexture(sourceTextureTarget, sourceTextureId) @@ -1006,7 +1008,13 @@ class LutRenderer(context: Context) : GLSurfaceView.Renderer { stabilizationSessionStarted = session?.start() == true } if (stabilizationSessionStarted) { - val completedFrame = session?.dequeueFrame() + val completedFrame = if (previewStabilizationUseCase == StabilizationUseCase.PHOTO_PREVIEW && + livePhotoRecorder == null + ) { + session?.dequeueLatestFrame() + } else { + session?.dequeueFrame() + } if (completedFrame != null) { val holdPreviousPhotoPreviewFrame = previewStabilizationUseCase == StabilizationUseCase.PHOTO_PREVIEW && @@ -1362,15 +1370,7 @@ class LutRenderer(context: Context) : GLSurfaceView.Renderer { suppressCameraEngine: Boolean = false, ) { val plan = if (suppressCameraEngine) null else enginePreviewPlan - val sourceTexture = if (plan != null) { - val stabilized = currentCameraTextureSource == PreviewColorTextureSource.TEXTURE_2D - enginePreview.render( - plan, currentCameraTextureSource, currentCameraTextureTarget, currentCameraTextureId, - currentFrameTimestampNs, - if (stabilized) stabilizationInputWidth else previewWidth, - if (stabilized) stabilizationInputHeight else previewHeight, - ).takeIf { it != 0 } ?: return - } else currentCameraTextureId + if (plan != null && !enginePreview.prepare(plan)) return val baselineLayerAvailable = hasBaselineLayer() && !suppressBaselineLayer val creativeLayerAvailable = hasCreativeLayer() && !suppressCreativeLayer val useCreativeLayer = creativeLayerAvailable && (!preferBaselineLayer || !baselineLayerAvailable) @@ -1408,19 +1408,20 @@ class LutRenderer(context: Context) : GLSurfaceView.Renderer { } val enableVideoLog = true val locations = getColorPassLocations( - textureSource = if (plan != null) PreviewColorTextureSource.TEXTURE_2D else currentCameraTextureSource, + textureSource = currentCameraTextureSource, lutConfig = layerLutConfig, lutEnabled = layerLutEnabled, params = layerParams, enableVideoLog = enableVideoLog, + includeEnginePreview = plan != null, ) ?: return drawColorPass( locations = locations, targetFboId = fboId, width = width, height = height, - sourceTextureTarget = if (plan != null) GLES30.GL_TEXTURE_2D else currentCameraTextureTarget, - sourceTextureId = sourceTexture, + sourceTextureTarget = currentCameraTextureTarget, + sourceTextureId = currentCameraTextureId, sourceStMatrix = currentCameraTextureMatrix, sourceCropRect = cropRect, targetMvpMatrix = targetMvpMatrix, @@ -2249,8 +2250,11 @@ class LutRenderer(context: Context) : GLSurfaceView.Renderer { setLutInternal(lutConfig) } - fun setEnginePreview(plan: RawEnginePreviewPlan?) { + /** Returns whether the immutable CPU plan changed and needs another draw. */ + fun setEnginePreview(plan: RawEnginePreviewPlan?): Boolean { + if (enginePreviewPlan === plan) return false enginePreviewPlan = plan + return true } fun setBaselineLut(lutConfig: LutConfig?) { diff --git a/app/src/main/java/com/hinnka/mycamera/lut/PreviewColorShader.kt b/app/src/main/java/com/hinnka/mycamera/lut/PreviewColorShader.kt index c476da62..07b9a276 100644 --- a/app/src/main/java/com/hinnka/mycamera/lut/PreviewColorShader.kt +++ b/app/src/main/java/com/hinnka/mycamera/lut/PreviewColorShader.kt @@ -143,6 +143,13 @@ internal object PreviewColorShader { ${PreviewColorShaderModules.PRIMARY_CALIBRATION} ${PreviewColorShaderModules.LUT_COLOR_SPACE} + ${if (variant.includeEnginePreview) RawEnginePreviewGl.SAMPLING_GLSL else ""} + vec4 samplePreviewSource(vec2 uv) { + vec4 sampled = texture(uCameraTexture, uv); + ${if (variant.includeEnginePreview) "sampled.rgb = sampleEnginePreview(sampled.rgb);" else ""} + return sampled; + } + void main() { vec2 rcCoord = vRawCoord; // The vertex stage already applies crop and the SurfaceTexture transform. @@ -157,29 +164,30 @@ internal object PreviewColorShader { rcCoord = mix(rcCoord, gridRC, 0.95); } + ${if (variant.includeChromaticAberration) """ vec4 color; - if (uChromaticAberration > 0.001) { + { vec2 center = vec2(0.5); vec2 dir = rcCoord - center; float dist = length(dir); float offset = pow(dist, 1.5) * uChromaticAberration * 0.08; vec2 rCoord = (uSTMatrix * vec4(rcCoord + dir * offset, 0.0, 1.0)).xy; vec2 bCoord = (uSTMatrix * vec4(rcCoord - dir * offset, 0.0, 1.0)).xy; - float r = texture(uCameraTexture, rCoord).r; - float g = texture(uCameraTexture, uvCoord).g; - float b = texture(uCameraTexture, bCoord).b; - float a = texture(uCameraTexture, uvCoord).a; + float r = samplePreviewSource(rCoord).r; + vec4 centerSample = samplePreviewSource(uvCoord); + float g = centerSample.g; + float b = samplePreviewSource(bCoord).b; + float a = centerSample.a; color = vec4(r, g, b, a); - } else { - color = texture(uCameraTexture, uvCoord); } + """ else "vec4 color = samplePreviewSource(uvCoord);"} ${if (variant.includeJpegInputToneCurve) """ color.rgb = applyJpegInputToneCurve(color.rgb); color.rgb = sanitizeColor(color.rgb); """ else ""} - if (uColorRecipeEnabled) { + if (${if (variant.includeColorRecipe) "uColorRecipeEnabled" else "false"}) { if (abs(uExposure) > 0.001) { color.rgb = applyExposureInLinearSpace(color.rgb, uExposure); color.rgb = sanitizeColor(color.rgb); @@ -352,22 +360,18 @@ internal object PreviewColorShader { if (uColorRecipeEnabled && abs(uSharpening) > 0.0001) { vec2 rawDx = vec2(uTexelSize.x, 0.0); vec2 rawDy = vec2(0.0, uTexelSize.y); - float centerLuma = getLuma(texture(uCameraTexture, uvCoord).rgb); + float centerLuma = getLuma(samplePreviewSource(uvCoord).rgb); float neighborLuma = 0.0; - neighborLuma += getLuma(texture( - uCameraTexture, + neighborLuma += getLuma(samplePreviewSource( (uSTMatrix * vec4(rcCoord - rawDx, 0.0, 1.0)).xy ).rgb); - neighborLuma += getLuma(texture( - uCameraTexture, + neighborLuma += getLuma(samplePreviewSource( (uSTMatrix * vec4(rcCoord + rawDx, 0.0, 1.0)).xy ).rgb); - neighborLuma += getLuma(texture( - uCameraTexture, + neighborLuma += getLuma(samplePreviewSource( (uSTMatrix * vec4(rcCoord - rawDy, 0.0, 1.0)).xy ).rgb); - neighborLuma += getLuma(texture( - uCameraTexture, + neighborLuma += getLuma(samplePreviewSource( (uSTMatrix * vec4(rcCoord + rawDy, 0.0, 1.0)).xy ).rgb); float delta = centerLuma - neighborLuma * 0.25; diff --git a/app/src/main/java/com/hinnka/mycamera/lut/PreviewColorShaderVariant.kt b/app/src/main/java/com/hinnka/mycamera/lut/PreviewColorShaderVariant.kt index a5a2c4fe..2c951533 100644 --- a/app/src/main/java/com/hinnka/mycamera/lut/PreviewColorShaderVariant.kt +++ b/app/src/main/java/com/hinnka/mycamera/lut/PreviewColorShaderVariant.kt @@ -20,6 +20,9 @@ internal data class PreviewColorShaderVariant( val includeSpatialRecipeEffects: Boolean = false, val includeVideoLog: Boolean = false, val includeSharpening: Boolean = false, + val includeEnginePreview: Boolean = false, + val includeChromaticAberration: Boolean = false, + val includeColorRecipe: Boolean = true, ) { companion object { fun forPass( @@ -43,6 +46,8 @@ internal data class PreviewColorShaderVariant( includeVideoLog = videoLogEnabled, // Match the shader's activation threshold, including negative (softening) values. includeSharpening = abs(params.sharpness) > 0.0001f, + includeChromaticAberration = params.chromaticAberration > 0.001f, + includeColorRecipe = !params.isDefault(), ) } diff --git a/app/src/main/java/com/hinnka/mycamera/lut/RawEnginePreviewGl.kt b/app/src/main/java/com/hinnka/mycamera/lut/RawEnginePreviewGl.kt index 49481bec..4945a909 100644 --- a/app/src/main/java/com/hinnka/mycamera/lut/RawEnginePreviewGl.kt +++ b/app/src/main/java/com/hinnka/mycamera/lut/RawEnginePreviewGl.kt @@ -1,6 +1,7 @@ package com.hinnka.mycamera.lut import android.opengl.GLES30 +import android.os.SystemClock import com.hinnka.mycamera.raw.DcpTextureResources import com.hinnka.mycamera.raw.RawCurveTextureResources import com.hinnka.mycamera.raw.RawEnginePreviewPlan @@ -11,40 +12,38 @@ import com.hinnka.mycamera.raw.RawToneMappingGl import com.hinnka.mycamera.utils.PLog /** - * One engine pass in the source texture's UV space, before crop/rotation and recipe layers. - * The output is display sRGB in RGBA16F. Original snapshots keep sampling the ISP texture. - * Engine resources/bindings and GLSL are shared with RAW, on this preview's EGL context. + * Bakes the pointwise ISP sRGB -> engine -> linear sRGB mapping when its plan changes. + * A 65-cube RGBA16F atlas keeps the expensive RAW shader independent of camera resolution. + * The color pass interpolates, then clips/encodes sRGB before recipe layers. Retaining signed + * linear output avoids interpolating across the final display clipping/gamma discontinuity. + * Original snapshots bypass it entirely. + * Grid coordinates are encoded sRGB (not linear RGB), retaining dense shadow sampling. + * Interpolation approximates the engine between grid nodes; capture still renders directly. */ internal class RawEnginePreviewGl { private val quad = RawFullscreenQuad() private var engines = newEnginePass() private val inverseAcr = LogInputGl() - private val programs = mutableMapOf, Int>() + private val programs = mutableMapOf() private var texture = 0 private var framebuffer = 0 - private var width = 0 - private var height = 0 private var lastPlan: RawEnginePreviewPlan? = null - private var lastTimestamp = Long.MIN_VALUE - private var lastInput = 0 - private var lastSource: PreviewColorTextureSource? = null + private var logStartNs = 0L + private var preparationCount = 0 + private var bakeCount = 0 + private var bakeSubmitNs = 0L - fun render( - plan: RawEnginePreviewPlan, - source: PreviewColorTextureSource, - inputTarget: Int, - inputTexture: Int, - timestamp: Long, - width: Int, - height: Int, - ): Int { - if (texture != 0 && this.width == width && this.height == height && - lastPlan === plan && lastTimestamp == timestamp && lastInput == inputTexture && lastSource == source - ) return texture - val program = programs.getOrPut(plan.engine to source) { - quad.createProgram(shader(plan.engine, source), "previewEngine${plan.engine}-$source") + fun prepare(plan: RawEnginePreviewPlan): Boolean { + preparationCount++ + if (texture != 0 && lastPlan === plan) { + logWork(plan) + return true } - if (program == 0 || !ensureTarget(width, height)) return 0 + val startNs = SystemClock.elapsedRealtimeNanos() + val program = programs.getOrPut(plan.engine) { + quad.createProgram(shader(plan.engine), "previewEngineLut${plan.engine}") + } + if (program == 0 || !ensureTarget()) return false GLES30.glUseProgram(program) // Unit 4 is the RAW HDR reference curve's slot, unused by SDR engine resources. inverseAcr.bind(GLES30.glGetUniformLocation(program, "uInverseAcr3Texture"), 4) @@ -63,29 +62,49 @@ internal class RawEnginePreviewGl { ) // Resource uploads may alter active bindings. Establish all draw inputs explicitly. GLES30.glBindFramebuffer(GLES30.GL_FRAMEBUFFER, framebuffer) - GLES30.glViewport(0, 0, width, height) + GLES30.glViewport(0, 0, ATLAS_WIDTH, ATLAS_HEIGHT) GLES30.glDisable(GLES30.GL_BLEND) - GLES30.glActiveTexture(GLES30.GL_TEXTURE0) - GLES30.glBindTexture(inputTarget, inputTexture) - GLES30.glUniform1i(GLES30.glGetUniformLocation(program, "uPreviewSource"), 0) GLES30.glBindBuffer(GLES30.GL_ARRAY_BUFFER, 0) GLES30.glBindBuffer(GLES30.GL_ELEMENT_ARRAY_BUFFER, 0) quad.bindIdentityTextureMatrix(program) quad.draw(program) val error = GLES30.glGetError() if (error != GLES30.GL_NO_ERROR) { - PLog.e(TAG, "Draw failed engine=${plan.engine} restore=${plan.restoration} source=$source error=$error") - return 0 + PLog.e(TAG, "LUT bake failed engine=${plan.engine} restore=${plan.restoration} error=$error") + lastPlan = null + return false } lastPlan = plan - lastTimestamp = timestamp - lastInput = inputTexture - lastSource = source - return texture + bakeCount++ + bakeSubmitNs += SystemClock.elapsedRealtimeNanos() - startNs + logWork(plan) + return true } - private fun ensureTarget(w: Int, h: Int): Boolean { - if (texture != 0 && framebuffer != 0 && width == w && height == h) return true + fun bind(location: Int) { + if (location < 0) return + GLES30.glActiveTexture(GLES30.GL_TEXTURE5) + GLES30.glBindTexture(GLES30.GL_TEXTURE_2D, texture) + GLES30.glUniform1i(location, 5) + } + + // CPU submission only: GL calls are asynchronous, so this is not GPU duration. + private fun logWork(plan: RawEnginePreviewPlan) { + val now = SystemClock.elapsedRealtimeNanos() + if (logStartNs == 0L) logStartNs = now + if (now - logStartNs < 5_000_000_000L) return + PLog.d(TAG, "LUT engine=${plan.engine} draws=$preparationCount bakes=$bakeCount " + + "bakeCpuSubmitMs=${bakeSubmitNs / 1_000_000.0} grid=$GRID_SIZE atlas=${ATLAS_WIDTH}x$ATLAS_HEIGHT") + logStartNs = now + preparationCount = 0 + bakeCount = 0 + bakeSubmitNs = 0L + } + + private fun ensureTarget(): Boolean { + if (texture != 0 && framebuffer != 0) return true + val w = ATLAS_WIDTH + val h = ATLAS_HEIGHT releaseTarget() val limit = IntArray(1) GLES30.glGetIntegerv(GLES30.GL_MAX_TEXTURE_SIZE, limit, 0) @@ -111,8 +130,6 @@ internal class RawEnginePreviewGl { releaseTarget() return false } - width = w - height = h return true } @@ -131,12 +148,11 @@ internal class RawEnginePreviewGl { programs.clear() texture = 0 framebuffer = 0 - width = 0 - height = 0 lastPlan = null - lastTimestamp = Long.MIN_VALUE - lastInput = 0 - lastSource = null + logStartNs = 0L + preparationCount = 0 + bakeCount = 0 + bakeSubmitNs = 0L } private fun releaseTarget() { @@ -153,7 +169,29 @@ internal class RawEnginePreviewGl { private const val TAG = "RawEnginePreview" private val WHITE = floatArrayOf(1f, 1f, 1f) - fun shader(engine: RawRenderingEngine, source: PreviewColorTextureSource): String { + const val GRID_SIZE = 65 + private const val TILES_PER_ROW = 9 + private const val ATLAS_WIDTH = GRID_SIZE * TILES_PER_ROW + private const val ATLAS_HEIGHT = GRID_SIZE * ((GRID_SIZE + TILES_PER_ROW - 1) / TILES_PER_ROW) + + val SAMPLING_GLSL = """ + uniform highp sampler2D uEnginePreviewLut; + vec2 engineLutCoordinate(vec2 rg, float blue) { + vec2 tile = vec2(mod(blue, $TILES_PER_ROW.0), floor(blue / $TILES_PER_ROW.0)); + return (tile * $GRID_SIZE.0 + rg + 0.5) / vec2($ATLAS_WIDTH.0, $ATLAS_HEIGHT.0); + } + vec3 sampleEnginePreview(vec3 srgb) { + vec3 position = clamp(srgb, 0.0, 1.0) * ${GRID_SIZE - 1}.0; + float lower = floor(position.b); + float upper = min(lower + 1.0, ${GRID_SIZE - 1}.0); + vec3 lo = texture(uEnginePreviewLut, engineLutCoordinate(position.rg, lower)).rgb; + vec3 hi = texture(uEnginePreviewLut, engineLutCoordinate(position.rg, upper)).rgb; + return linearToSrgb(clamp(mix(lo, hi, position.b - lower), 0.0, 1.0)); + } + """.trimIndent() + + // A source variant is retained for direct-render numerical/driver diagnostics. + fun shader(engine: RawRenderingEngine, source: PreviewColorTextureSource? = null): String { val definition = RawEngineTonePass.shaderDefinitionFor(engine) val external = source == PreviewColorTextureSource.EXTERNAL_OES val prepare = if (definition.includeAdobeProfilePipeline) { @@ -172,7 +210,7 @@ internal class RawEnginePreviewGl { precision highp sampler3D; in vec2 vTexCoord; out vec4 fragColor; - uniform highp ${if (external) "samplerExternalOES" else "sampler2D"} uPreviewSource; + ${if (source != null) "uniform highp ${if (external) "samplerExternalOES" else "sampler2D"} uPreviewSource;" else ""} uniform mat3 uPreviewRestore; uniform mat3 uPreviewInput; uniform mat3 uPreviewOutput; @@ -185,7 +223,12 @@ internal class RawEnginePreviewGl { ${definition.profileFunctions} ${definition.engineFunctions} void main() { - vec4 sampled = texture(uPreviewSource, vTexCoord); + ${if (source != null) "vec4 sampled = texture(uPreviewSource, vTexCoord);" else """ + ivec2 pixel = ivec2(gl_FragCoord.xy); + ivec2 tile = pixel / $GRID_SIZE; + int blue = min(tile.y * $TILES_PER_ROW + tile.x, ${GRID_SIZE - 1}); + vec4 sampled = vec4(vec3(pixel % $GRID_SIZE, blue) / ${GRID_SIZE - 1}.0, 1.0); + """} vec3 linear = srgbToLinear(clamp(sampled.rgb, 0.0, 1.0)); vec3 scene = vec3(inverseAcr3(linear.r), inverseAcr3(linear.g), inverseAcr3(linear.b)); vec3 restored = uPreviewRestore * scene; @@ -194,7 +237,7 @@ internal class RawEnginePreviewGl { $prepare color = applyEngineTone(color); $output - fragColor = vec4(linearToSrgb(clamp(color, 0.0, 1.0)), sampled.a); + fragColor = vec4(${if (source != null) "linearToSrgb(clamp(color, 0.0, 1.0))" else "color"}, sampled.a); } """.trimIndent().trimStart() } diff --git a/app/src/main/java/com/hinnka/mycamera/raw/DcpProfile.kt b/app/src/main/java/com/hinnka/mycamera/raw/DcpProfile.kt index f453dced..8fcb5393 100644 --- a/app/src/main/java/com/hinnka/mycamera/raw/DcpProfile.kt +++ b/app/src/main/java/com/hinnka/mycamera/raw/DcpProfile.kt @@ -70,7 +70,13 @@ data class DcpProfile( val analogBalance: FloatArray? = null, val cameraCalibration1: FloatArray? = null, val cameraCalibration2: FloatArray? = null -) +) { + // Parsed profile assets are immutable. Share this curve across AWB-dependent + // render plans; a reloaded or copied profile owns a fresh lazy cache. + internal val toneCurveLut: FloatArray? by lazy { + toneCurve?.takeIf { it.isValid }?.toLut() + } +} data class DcpRenderPlan( val profileName: String, @@ -186,7 +192,7 @@ object DcpProfileParser { cameraWhite = selectedCameraWhite, hueSatMap = selectedHueSat, lookTable = profile.lookTable?.takeIf { it.isValid }, - toneCurveLut = profile.toneCurve?.takeIf { it.isValid }?.toLut() + toneCurveLut = profile.toneCurveLut ) } diff --git a/app/src/main/java/com/hinnka/mycamera/stabilization/RealtimeStabilizationCoordinator.kt b/app/src/main/java/com/hinnka/mycamera/stabilization/RealtimeStabilizationCoordinator.kt index 5f7ed80e..bea40f4a 100644 --- a/app/src/main/java/com/hinnka/mycamera/stabilization/RealtimeStabilizationCoordinator.kt +++ b/app/src/main/java/com/hinnka/mycamera/stabilization/RealtimeStabilizationCoordinator.kt @@ -993,8 +993,10 @@ class RealtimeStabilizationCoordinator(context: Context) { } } - private fun nextNativeResult(afterSequence: Long): SequencedNativeResult? = - synchronized(lock) { nativeResults.firstOrNull { it.sequence > afterSequence } } + private fun nextNativeResult(afterSequence: Long, throughSequence: Long): SequencedNativeResult? = + synchronized(lock) { + nativeResults.firstOrNull { it.sequence > afterSequence && it.sequence <= throughSequence } + } private fun pendingNativeResultCount(afterSequence: Long): Int = synchronized(lock) { nativeResults.count { it.sequence > afterSequence } @@ -1107,10 +1109,30 @@ class RealtimeStabilizationCoordinator(context: Context) { } @Synchronized - fun dequeueFrame(): StabilizationFrame? { + fun dequeueFrame(): StabilizationFrame? = dequeueFrameThrough(Long.MAX_VALUE) + + /** Photo preview presents the freshest pose; recording keeps the sequential API. */ + @Synchronized + fun dequeueLatestFrame(): StabilizationFrame? { + if (!active) return null + // Bound the drain to a snapshot so a producing camera cannot keep this GL call busy. + val throughSequence = coordinator.currentResultSequence() + var latest: StabilizationFrame? = null + while (true) { + val next = dequeueFrameThrough(throughSequence) ?: return latest + if (next.transform == null && latest?.transform != null) { + next.image.close() + } else { + latest?.image?.close() + latest = next + } + } + } + + private fun dequeueFrameThrough(throughSequence: Long): StabilizationFrame? { if (!active) return null while (true) { - val next = coordinator.nextNativeResult(lastConsumedSequence) ?: return null + val next = coordinator.nextNativeResult(lastConsumedSequence, throughSequence) ?: return null lastConsumedSequence = next.sequence val timestampNs = when (val result = next.result) { is MgcEisNativeEngine.FrameResult.Stabilized -> result.sensorTimestampNs @@ -1158,8 +1180,8 @@ class RealtimeStabilizationCoordinator(context: Context) { * Number of native results not yet consumed by this session. * * GLSurfaceView collapses repeated requestRender() calls into one draw. The preview - * renderer uses this authoritative cursor distance after each draw to request the next - * draw until every timestamped result has been presented exactly once. + * renderer uses this cursor distance to request another draw for unconsumed results. + * Recording consumes sequentially; photo preview drains to the latest available pose. */ @Synchronized fun pendingResultCount(): Int = if (active) { diff --git a/app/src/main/java/com/hinnka/mycamera/ui/camera/CameraGLSurfaceView.kt b/app/src/main/java/com/hinnka/mycamera/ui/camera/CameraGLSurfaceView.kt index 337f1943..7d16e2aa 100644 --- a/app/src/main/java/com/hinnka/mycamera/ui/camera/CameraGLSurfaceView.kt +++ b/app/src/main/java/com/hinnka/mycamera/ui/camera/CameraGLSurfaceView.kt @@ -228,8 +228,7 @@ class CameraGLSurfaceView @JvmOverloads constructor( } fun setEnginePreview(plan: RawEnginePreviewPlan?) { - renderer.setEnginePreview(plan) - requestRender() + if (renderer.setEnginePreview(plan)) requestRender() } fun setBaselineLut(lutConfig: LutConfig?) { @@ -464,6 +463,8 @@ class CameraGLSurfaceView @JvmOverloads constructor( override fun onResume() { renderer.setRenderingPaused(false) super.onResume() + // Resume redraws independently of whether the CPU engine plan changed. + requestRender() PLog.d(TAG, "onResume") }