feat: share photo preview YUV input with EIS and streamline renderers

This commit is contained in:
zhoubinjia committed 2026-11-12 12:03:06 +08:00
1 parent d23e4431d5
commit e657e62e87
11 files changed
+359 -873

No files matched your search

@@ -269,6 +269,9 @@ class Camera2Controller(private val context: Context) {
private var captureSession: CameraCaptureSession? = null
private var previewRequestBuilder: CaptureRequest.Builder? = null
private var previewSessionGeneration: Long = 0L
// Camera-thread state: only this configured input and its request epoch may feed EIS.
private var activeStabilizationInput: StabilizationImageReader? = null
private var stabilizationInputFirstTimestampNs: Long = 0L
private val previewUpdateScheduled = AtomicBoolean(false)
private var pendingVendorSessionParameterRestart = false
private var oppoSuperStabilizationEnabled = false
@@ -276,7 +279,7 @@ class Camera2Controller(private val context: Context) {
private var previewSurface: Surface? = null
private var previewSurfaceTexture: SurfaceTexture? = null
/** Photo-mode viewfinder stream; when set, [previewSurface] is its surface. */
private var previewYuvReader: PreviewYuvImageReader? = null
private var previewYuvReader: StabilizationImageReader? = null
val previewYuvChannel = PreviewYuvFrameChannel()
private var imageReader: ImageReader? = null
private var stabilizationImageReader: StabilizationImageReader? = null
@@ -1161,11 +1164,7 @@ class Camera2Controller(private val context: Context) {
}
}
realtimeStabilizationCoordinator.submitCaptureResult(
result = result,
request = request,
outputPhysicalCameraId = activeOutputPhysicalCameraId,
)
submitCurrentStabilizationResult(session, request, result)
lastCaptureResult = result
logVideoCaptureStats(result)
@@ -1441,19 +1440,10 @@ class Camera2Controller(private val context: Context) {
val previewTarget = checkNotNull(previewSurface) {
"Preview surface unavailable for photo preparation"
}
val stabilizationTarget = if (shouldUseAlgorithmicStabilization()) {
checkNotNull(stabilizationImageReader) {
"Stabilization reader unavailable for photo preparation"
}.surface
} else {
null
}
return device.createCaptureRequest(CameraDevice.TEMPLATE_PREVIEW).apply {
// Preserve the configured preview outputs, including the EIS YUV reader. Both
// repeating and trigger requests must keep feeding it through previewCallback
// so each stabilization image has matching CaptureResult metadata.
// The photo viewfinder is also the EIS input. Keep feeding it through
// previewCallback so trigger frames retain matching CaptureResult metadata.
addTarget(previewTarget)
stabilizationTarget?.let(::addTarget)
}
}
@@ -2190,22 +2180,48 @@ class Camera2Controller(private val context: Context) {
previewYuvReader = null
try {
// The reader owns its surface and outlives frames still leased to the renderer.
if (yuvReader != null) yuvReader.close() else surface?.release()
if (yuvReader != null) retirePreviewYuvReader(yuvReader) else surface?.release()
} catch (e: Exception) {
PLog.w(TAG, "Ignoring error while releasing preview surface ($reason): ${e.message}")
}
}
private fun createPreviewYuvReader(size: Size): PreviewYuvImageReader {
previewYuvReader?.close()
return PreviewYuvImageReader(
private fun retirePreviewYuvReader(reader: StabilizationImageReader) {
reader.close()
previewYuvChannel.discardFrom(reader)
realtimeStabilizationCoordinator.discardStabilizationImages(reader)
}
private fun createPreviewYuvReader(size: Size): StabilizationImageReader {
val handler = checkNotNull(cameraHandler) { "Camera thread is not running" }
previewYuvReader?.let(::retirePreviewYuvReader)
return StabilizationImageReader(
width = size.width,
height = size.height,
handler = checkNotNull(cameraHandler) { "Camera thread is not running" },
channel = previewYuvChannel,
).also {
previewYuvReader = it
PLog.i(TAG, "Preview YUV stream configured: ${size.width}x${size.height}")
maxImages = RealtimeStabilizationCoordinator.STABILIZATION_IMAGE_READER_MAX_IMAGES,
).also { reader ->
reader.setOnImageAvailableListener(handler) { source ->
val stabilize = shouldUseAlgorithmicStabilization()
while (true) {
val image = try {
// EIS requires every boundary; ordinary preview only needs the latest.
if (stabilize) source.acquireNextImage() else source.acquireLatestImage()
} catch (error: IllegalStateException) {
PLog.w(TAG, "Cannot acquire photo preview YUV image: ${error.message}")
null
} ?: break
if (stabilize) {
submitCurrentStabilizationImage(image)
} else {
previewYuvChannel.publish(image)
break
}
}
}
previewYuvReader = reader
stabilizationInputStatsFirstTimestampNs = 0L
stabilizationInputStatsFrames = 0
PLog.i(TAG, "Shared photo preview YUV input configured: ${size.width}x${size.height}")
}
}
@@ -3176,6 +3192,11 @@ class Camera2Controller(private val context: Context) {
val captureMode = _state.value.captureMode
val reader = imageReader
val stabilizationReader = ensureStabilizationImageReader()
val stabilizationInput = if (shouldUseAlgorithmicStabilization()) {
if (captureMode == CaptureMode.PHOTO) previewYuvReader else stabilizationReader
} else {
null
}
val useEnhancedStabilization = shouldUseVideoEnhancedStabilization()
val videoSurface = if (
captureMode == CaptureMode.VIDEO &&
@@ -3254,7 +3275,7 @@ class Camera2Controller(private val context: Context) {
return
}
closeUnusedStabilizationImageReader(stabilizationReader)
onSessionConfigured(session, openGeneration, sessionGeneration)
onSessionConfigured(session, openGeneration, sessionGeneration, stabilizationInput)
}
override fun onConfigureFailed(session: CameraCaptureSession) {
@@ -3321,7 +3342,7 @@ class Camera2Controller(private val context: Context) {
return
}
closeUnusedStabilizationImageReader(stabilizationReader)
onSessionConfigured(session, openGeneration, sessionGeneration)
onSessionConfigured(session, openGeneration, sessionGeneration, stabilizationInput)
}
override fun onConfigureFailed(session: CameraCaptureSession) {
@@ -3407,13 +3428,11 @@ class Camera2Controller(private val context: Context) {
private fun ensureStabilizationImageReader(): StabilizationImageReader? {
val handler = cameraHandler ?: return null
val state = _state.value
if (!shouldUseAlgorithmicStabilization()) return null
val size = when (state.captureMode) {
CaptureMode.PHOTO -> state.currentPreviewSize
CaptureMode.VIDEO -> state.videoCapabilities
.enhancedStabilizationInputSizesByResolution[state.videoConfig.resolution]
?: return null
}
// Photo mode feeds EIS from previewYuvReader; only video needs a separate input.
if (state.captureMode != CaptureMode.VIDEO || !shouldUseAlgorithmicStabilization()) return null
val size = state.videoCapabilities
.enhancedStabilizationInputSizesByResolution[state.videoConfig.resolution]
?: return null
if (size.width <= 0 || size.height <= 0) return null
stabilizationImageReader?.let { existing ->
if (existing.width == size.width && existing.height == size.height) {
@@ -3434,8 +3453,7 @@ class Camera2Controller(private val context: Context) {
PLog.e(TAG, "Cannot acquire MGC YUV image", error)
null
} ?: break
logStabilizationInputStats(image)
realtimeStabilizationCoordinator.submitStabilizationImage(image)
submitCurrentStabilizationImage(image)
}
}
stabilizationImageReader = reader
@@ -3445,6 +3463,65 @@ class Camera2Controller(private val context: Context) {
}
}
private fun submitCurrentStabilizationResult(
session: CameraCaptureSession,
request: CaptureRequest,
result: TotalCaptureResult,
) {
// Old sessions can finish requests after their replacement's onConfigured callback.
// Check the configured input as well as mutable UI state: selecting EIS can precede
// camera-thread reconfiguration, while the current session still runs OIS requests.
if (session !== captureSession || activeStabilizationInput == null ||
!shouldUseAlgorithmicStabilization()
) {
return
}
val physicalCameraId = activeOutputPhysicalCameraId
?: result.get(CaptureResult.LOGICAL_MULTI_CAMERA_ACTIVE_PHYSICAL_ID)
val timestampNs = physicalCameraId?.let { result.physicalCameraResults[it] }
?.get(CaptureResult.SENSOR_TIMESTAMP)
?: result.get(CaptureResult.SENSOR_TIMESTAMP)
?: return
if (timestampNs <= 0L) return
if (stabilizationInputFirstTimestampNs == 0L) {
stabilizationInputFirstTimestampNs = timestampNs
PLog.i(
TAG,
"EIS+ current request confirmed: generation=$previewSessionGeneration, " +
"firstTimestamp=$timestampNs, frame=${result.frameNumber}, " +
"videoRequested=${request.get(CaptureRequest.CONTROL_VIDEO_STABILIZATION_MODE)}, " +
"opticalRequested=${request.get(CaptureRequest.LENS_OPTICAL_STABILIZATION_MODE)}",
)
}
if (timestampNs < stabilizationInputFirstTimestampNs) return
realtimeStabilizationCoordinator.submitCaptureResult(
result = result,
request = request,
outputPhysicalCameraId = activeOutputPhysicalCameraId,
captureRequestGeneration = previewSessionGeneration,
)
}
private fun submitCurrentStabilizationImage(image: StabilizationImageReader.AcquiredImage) {
val firstTimestampNs = stabilizationInputFirstTimestampNs
if (!shouldUseAlgorithmicStabilization() || image.owner !== activeStabilizationInput ||
firstTimestampNs == 0L || image.timestampNs < firstTimestampNs
) {
// The photo reader is shared across sessions and can still contain old OIS frames.
image.close()
return
}
logStabilizationInputStats(image)
realtimeStabilizationCoordinator.submitStabilizationImage(image)
}
private fun clearStabilizationInput() {
val input = activeStabilizationInput
activeStabilizationInput = null
stabilizationInputFirstTimestampNs = 0L
input?.let(realtimeStabilizationCoordinator::discardStabilizationImages)
}
private fun logStabilizationInputStats(image: StabilizationImageReader.AcquiredImage) {
val timestampNs = image.timestampNs
if (timestampNs <= 0L) return
@@ -3850,8 +3927,9 @@ class Camera2Controller(private val context: Context) {
private fun onSessionConfigured(
session: CameraCaptureSession,
openGeneration: Long = cameraOpenGeneration,
sessionGeneration: Long = previewSessionGeneration
openGeneration: Long,
sessionGeneration: Long,
stabilizationInput: StabilizationImageReader?,
) {
if (openGeneration != cameraOpenGeneration || sessionGeneration != previewSessionGeneration) {
PLog.w(TAG, "Ignoring stale configured session")
@@ -3859,6 +3937,8 @@ class Camera2Controller(private val context: Context) {
return
}
captureSession = session
activeStabilizationInput = stabilizationInput
stabilizationInputFirstTimestampNs = 0L
_state.update { it.copy(previewFirstFrameTimestampNs = null) }
try {
@@ -8843,6 +8923,7 @@ class Camera2Controller(private val context: Context) {
private fun invalidateCaptureSession(session: CameraCaptureSession?, reason: String) {
// A delayed close callback from the old session must not clear its replacement.
if (session == null || captureSession !== session) return
clearStabilizationInput()
captureSession = null
_enginePreviewSource.value = null
previewRequestBuilder = null
@@ -46,7 +46,7 @@ object CameraUtils {
val sensorRatio = aspectRatio.getValue(true)
// Mandatory stream combinations only guarantee PREVIEW-bounded sizes:
// long side <= 1920 and short side <= 1080 (CameraDevice#createCaptureSession).
// Photo mode's viewfinder is a YUV_420_888 ImageReader (PreviewYuvImageReader).
// Photo mode shares one YUV_420_888 ImageReader between viewfinder and EIS.
val previewSizes = map.getOutputSizes(ImageFormat.YUV_420_888)
?.filter { isWithinPreviewBound(it) }
.orEmpty()
@@ -1,115 +1,24 @@
package com.hinnka.mycamera.camera
import android.graphics.ImageFormat
import android.media.Image
import android.media.ImageReader
import android.os.Build
import android.os.Handler
import com.hinnka.mycamera.utils.PLog
import java.util.concurrent.atomic.AtomicBoolean
import com.hinnka.mycamera.stabilization.StabilizationImageReader
import java.util.concurrent.atomic.AtomicReference
/**
* Photo-mode viewfinder stream: a YUV_420_888 ImageReader instead of a SurfaceTexture.
*
* The PRIVATE preview stream is ISP-tuned independently of the YUV capture stream, and some HALs
* deliver it as limited-range YCbCr with an unknown dataspace. A YUV_420_888 stream carries an
* explicit dataspace (JFIF on Camera2) and comes from the same ISP path as the capture stream.
* Follows Chromium's VideoCaptureCamera2: latest-frame-wins delivery and per-frame dataspace.
*
* The reader keeps the default usage, the same as the capture and MGC readers. Requesting
* USAGE_GPU_SAMPLED_IMAGE (as Chromium does) made the Xiaomi 11 HAL write Cr/Cb into a buffer
* whose planes are reported as Cb/Cr, so both the EGLImage and the CPU planes showed swapped red
* and blue. Default-usage buffers still import into EGL for GPU sampling.
*/
internal class PreviewYuvImageReader(
val width: Int,
val height: Int,
handler: Handler,
private val channel: PreviewYuvFrameChannel,
) : AutoCloseable {
private val lock = Any()
private val reader = ImageReader.newInstance(width, height, ImageFormat.YUV_420_888, MAX_IMAGES)
val surface = reader.surface
private var acquiredImageCount = 0
private var closed = false
init {
reader.setOnImageAvailableListener({ onImageAvailable() }, handler)
}
private fun onImageAvailable() {
val frame = synchronized(lock) {
if (closed) return
val image = try {
reader.acquireLatestImage()
} catch (error: IllegalStateException) {
PLog.w(TAG, "Cannot acquire preview image: ${error.message}")
null
} ?: return
acquiredImageCount += 1
PreviewYuvFrame(this, image)
}
channel.publish(frame)
}
override fun close() {
synchronized(lock) {
if (closed) return
closed = true
reader.setOnImageAvailableListener(null, null)
if (acquiredImageCount == 0) reader.close()
}
channel.discardFrom(this)
}
internal fun release(image: Image) {
synchronized(lock) {
image.close()
acquiredImageCount -= 1
if (closed && acquiredImageCount == 0) reader.close()
}
}
private companion object {
const val TAG = "PreviewYuvImageReader"
// One frame waiting in the channel, one being sampled on the GL thread, and the two that
// acquireLatestImage holds while skipping to the newest frame.
const val MAX_IMAGES = 4
}
}
/** A leased preview image; [close] returns it to its reader. */
internal class PreviewYuvFrame(
val owner: PreviewYuvImageReader,
val image: Image,
) : AutoCloseable {
val timestampNs: Long = image.timestamp
val dataSpace: Int = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) image.dataSpace else 0
private val closed = AtomicBoolean(false)
override fun close() {
if (closed.compareAndSet(false, true)) owner.release(image)
}
}
/** Latest-frame-wins hand-off from the camera thread to the GL thread. */
/** Latest-frame-wins hand-off for the shared photo YUV stream when stabilization is off. */
class PreviewYuvFrameChannel {
private val latest = AtomicReference<PreviewYuvFrame?>(null)
private val latest = AtomicReference<StabilizationImageReader.AcquiredImage?>(null)
@Volatile
var onFrameAvailable: (() -> Unit)? = null
internal fun publish(frame: PreviewYuvFrame) {
internal fun publish(frame: StabilizationImageReader.AcquiredImage) {
latest.getAndSet(frame)?.close()
onFrameAvailable?.invoke()
}
/** The caller owns the returned frame and must close it. */
internal fun take(): PreviewYuvFrame? = latest.getAndSet(null)
internal fun take(): StabilizationImageReader.AcquiredImage? = latest.getAndSet(null)
internal fun discardFrom(owner: PreviewYuvImageReader) {
internal fun discardFrom(owner: StabilizationImageReader) {
val frame = latest.get() ?: return
if (frame.owner === owner && latest.compareAndSet(frame, null)) frame.close()
}
@@ -15,7 +15,7 @@ import com.hinnka.mycamera.preview.EyeFocusProcessingTiming
import com.hinnka.mycamera.raw.ColorSpace
import com.hinnka.mycamera.screencapture.PhantomPipCrop
import com.hinnka.mycamera.camera.MeteringMode
import com.hinnka.mycamera.camera.PreviewYuvFrame
import com.hinnka.mycamera.stabilization.StabilizationImageReader
import com.hinnka.mycamera.camera.PreviewYuvFrameChannel
import com.hinnka.mycamera.stabilization.DEFAULT_VIDEO_STABILIZATION_LOOKAHEAD
import com.hinnka.mycamera.stabilization.RealtimeStabilizationCoordinator
@@ -78,8 +78,7 @@ class LutRenderer(context: Context) : GLSurfaceView.Renderer {
private val colorProgramCache = PreviewColorProgramCache()
private val enginePreview = RawEnginePreviewGl()
private val mgcEisHardwareBufferRenderer = MgcEisHardwareBufferRenderer(TAG)
private val mgcEisYuvRenderer = MgcEisYuvRenderer(TAG)
private val mgcEisRenderer = MgcEisRenderer(TAG)
private val previewYuvRenderer = PreviewYuvRenderer(TAG)
private var previewYuvChannel: PreviewYuvFrameChannel? = null
private val previewYuvMatrix = FloatArray(16).apply { Matrix.setIdentityM(this, 0) }
@@ -624,8 +623,7 @@ class LutRenderer(context: Context) : GLSurfaceView.Renderer {
previewLiteEffects.reset()
toneBase.reset()
enginePreview.reset()
mgcEisHardwareBufferRenderer.resetAfterContextLoss()
mgcEisYuvRenderer.resetAfterContextLoss()
mgcEisRenderer.resetAfterContextLoss()
previewYuvRenderer.resetAfterContextLoss()
cameraTextureId = 0
currentCameraTextureId = 0
@@ -1152,12 +1150,8 @@ class LutRenderer(context: Context) : GLSurfaceView.Renderer {
var yuvFrameUpdated = false
previewYuvChannel?.take()?.let { frame ->
if (delayedStabilizationEnabled) {
// Stabilized frames come from the MGC reader; this stream only proves the
// orientation, which no OES frame provides while the viewfinder is a YUV reader.
// Discard an ordinary frame queued before the shared input switched to EIS.
frame.close()
if (!mgcEisPresentationTransform.captureFromSensorOrientation(sensorOrientation)) {
PLog.w(TAG, "MGC cannot derive presentation from sensor orientation $sensorOrientation")
}
} else if (usePreviewYuvFrame(frame)) {
yuvFrameUpdated = true
cameraFrameUpdated = true
@@ -1165,6 +1159,10 @@ class LutRenderer(context: Context) : GLSurfaceView.Renderer {
}
if (delayedStabilizationEnabled) {
// Photo mode has no OES stream or ordinary YUV notifications while EIS is active.
if (!mgcEisPresentationTransform.captureFromSensorOrientation(sensorOrientation)) {
PLog.w(TAG, "MGC cannot derive presentation from sensor orientation $sensorOrientation")
}
val session = stabilizationSession
if (!stabilizationSessionStarted) {
stabilizationSessionStarted = session?.start() == true
@@ -1452,9 +1450,9 @@ class LutRenderer(context: Context) : GLSurfaceView.Renderer {
}
/** Converts a viewfinder YUV frame and makes it the camera texture. Always closes [frame]. */
private fun usePreviewYuvFrame(frame: PreviewYuvFrame): Boolean {
private fun usePreviewYuvFrame(frame: StabilizationImageReader.AcquiredImage): Boolean {
val timestampNs = frame.timestampNs
val textureId = previewYuvRenderer.render(frame)
val textureId = frame.use { previewYuvRenderer.render(it.image) }
if (textureId == 0) return false
val matrix = resolvePreviewYuvPresentationMatrix(sensorOrientation, lensFacing == 0) ?: run {
PLog.w(TAG, "Preview YUV frame has non-cardinal sensor orientation $sensorOrientation")
@@ -2547,8 +2545,7 @@ class LutRenderer(context: Context) : GLSurfaceView.Renderer {
previewHeight = height
surfaceTexture?.setDefaultBufferSize(width, height)
if (sizeChanged && previewStabilizationUseCase != null) {
mgcEisHardwareBufferRenderer.release()
mgcEisYuvRenderer.release()
mgcEisRenderer.release()
recreatePreviewStabilizationSession()
}
// 更新 MVP 矩阵以处理 center crop
@@ -2565,8 +2562,7 @@ class LutRenderer(context: Context) : GLSurfaceView.Renderer {
stabilizationInputWidth = width
stabilizationInputHeight = height
if (previewStabilizationUseCase != null) {
mgcEisHardwareBufferRenderer.release()
mgcEisYuvRenderer.release()
mgcEisRenderer.release()
recreatePreviewStabilizationSession()
}
}
@@ -2624,21 +2620,20 @@ class LutRenderer(context: Context) : GLSurfaceView.Renderer {
currentFrameTimestampNs = 0L
}
/**
* Uses MGC's HardwareBuffer/EGLImage renderer whenever the camera buffer and current EGL
* context support it. The CPU YUV implementation is retained only for devices without that
* platform import path.
*/
/** Converts with the ordinary preview's color rules, then applies only EIS geometry. */
private fun renderMgcEisFrame(
frame: com.hinnka.mycamera.stabilization.StabilizationFrame,
): MgcEisHardwareBufferRenderer.Frame? {
val hardwareRendered = mgcEisHardwareBufferRenderer.render(frame)
if (hardwareRendered != null) {
frame.image.close()
return hardwareRendered
}
return mgcEisYuvRenderer.render(frame)?.let { rendered ->
MgcEisHardwareBufferRenderer.Frame(rendered.timestampNs, rendered.textureId)
): MgcEisRenderer.Frame? {
return frame.image.use { image ->
val textureId = previewYuvRenderer.render(image.image)
if (textureId == 0) return null
mgcEisRenderer.render(
textureId = textureId,
width = image.width,
height = image.height,
timestampNs = frame.timestampNs,
rowHomographies = frame.transform?.rowHomographies,
)
}
}
@@ -3539,8 +3534,7 @@ class LutRenderer(context: Context) : GLSurfaceView.Renderer {
stackTextureId = 0
}
basicToneTextures.release()
mgcEisHardwareBufferRenderer.release()
mgcEisYuvRenderer.release()
mgcEisRenderer.release()
previewYuvChannel?.take()?.close()
previewYuvRenderer.release()
// 删除程序
@@ -1,279 +0,0 @@
package com.hinnka.mycamera.lut
import android.media.Image
import android.opengl.EGL14
import android.opengl.EGL15
import android.opengl.EGLSync
import android.opengl.GLES11Ext
import android.opengl.GLES30
import android.opengl.GLES31
import com.hinnka.mycamera.processor.GlesHardwareBufferImage
import com.hinnka.mycamera.stabilization.STABILIZATION_ROW_COUNT
import com.hinnka.mycamera.stabilization.StabilizationFrame
import com.hinnka.mycamera.utils.PLog
/**
* MGC's production image path: Camera2 HardwareBuffer -> EGLImage -> external texture -> mesh.
*
* This mirrors the original jxg renderer. The caller retains ownership of [StabilizationFrame]'s
* Image and closes it after a successful draw; a null result leaves it available for the explicit
* CPU YUV fallback on devices that cannot import the buffer into EGL.
*/
internal class MgcEisHardwareBufferRenderer(private val tag: String) {
data class Frame(val timestampNs: Long, val textureId: Int)
private val mesh = MgcEisMesh()
// Native output matrices pass through convertPixelHomographyToClip then
// applyCropZoomToClipHomography(kOutputCropZoom), where:
// kLookaheadCropMargin = 0.05
// kOutputCropZoom = 1.0 / (1.0 - 2.0 * 0.05) ≈ 1.1111
// applyCropZoomToClipHomography divides the W row (h20, h21, h22) by zoom.
// A Dropped frame must use the same crop so that the viewport does not jump
// between 1.0x and 1.111x on every stabilization gap.
private val droppedFrameHomographies = FloatArray(STABILIZATION_ROW_COUNT * 9).also { values ->
val h22 = 1.0f - 2.0f * 0.05f // = 1.0f / kOutputCropZoom = 0.9f
repeat(STABILIZATION_ROW_COUNT) { row ->
val offset = row * 9
values[offset] = 1f // h00
values[offset + 4] = 1f // h11
values[offset + 8] = h22 // h22: W-row crop zoom
}
}
private var programId = 0
private var positionLocation = -1
private var textureCoordinateLocation = -1
private var sourceSamplerLocation = -1
private var sourceTextureId = 0
private var outputTextureId = 0
private var outputFramebufferId = 0
private var width = 0
private var height = 0
private var loggedImportFailure = false
private var loggedZeroCopy = false
/**
* Attempts the zero-copy path without closing the source image. The image must remain open
* until this function returns because the EGLImage is created from its HardwareBuffer.
*/
fun render(frame: StabilizationFrame): Frame? {
val width = frame.image.width
val height = frame.image.height
if (width <= 0 || height <= 0) return null
val source = frame.image.image
val hardwareBuffer = try {
source.hardwareBuffer
} catch (error: IllegalStateException) {
PLog.w(tag, "MGC cannot access HardwareBuffer ts=${frame.timestampNs}: ${error.message}")
return null
} ?: return null
if (!ensure(width, height)) return null
val imageHandle = GlesHardwareBufferImage.create(hardwareBuffer)
if (imageHandle == 0L) {
if (!loggedImportFailure) {
loggedImportFailure = true
PLog.w(tag, "MGC EGLImage import unavailable; using CPU YUV fallback")
}
return null
}
return try {
if (!GlesHardwareBufferImage.bind(imageHandle, sourceTextureId)) {
PLog.w(tag, "MGC EGLImage bind failed ts=${frame.timestampNs}")
return null
}
GLES30.glBindFramebuffer(GLES30.GL_FRAMEBUFFER, outputFramebufferId)
GLES30.glViewport(0, 0, source.width, source.height)
GLES30.glClearColor(0f, 0f, 0f, 1f)
GLES30.glClear(GLES30.GL_COLOR_BUFFER_BIT)
GLES30.glUseProgram(programId)
GLES30.glActiveTexture(GLES30.GL_TEXTURE0)
GLES30.glBindTexture(GLES11Ext.GL_TEXTURE_EXTERNAL_OES, sourceTextureId)
GLES30.glUniform1i(sourceSamplerLocation, 0)
mesh.draw(
positionLocation = positionLocation,
textureCoordinateLocation = textureCoordinateLocation,
rowHomographies = frame.transform?.rowHomographies ?: droppedFrameHomographies,
)
// The camera owns this HardwareBuffer and may recycle it as soon as Image.close()
// returns. A GL draw only enqueues sampling work, so a memory barrier alone cannot
// protect that lifetime. MGC's jwn/jxg renderers insert and wait on an EGL fence at
// this exact hand-off before releasing their input EGLImage/HardwareBuffer.
awaitSourceSampling()
GLES30.glBindFramebuffer(GLES30.GL_FRAMEBUFFER, 0)
GLES31.glMemoryBarrier(
GLES31.GL_FRAMEBUFFER_BARRIER_BIT or GLES31.GL_TEXTURE_FETCH_BARRIER_BIT,
)
GLES30.glBindTexture(GLES11Ext.GL_TEXTURE_EXTERNAL_OES, 0)
GLES30.glActiveTexture(GLES30.GL_TEXTURE0)
if (!loggedZeroCopy) {
loggedZeroCopy = true
PLog.i(tag, "MGC HardwareBuffer EGLImage renderer active")
}
Frame(frame.timestampNs, outputTextureId)
} catch (error: RuntimeException) {
PLog.w(tag, "MGC EGLImage draw failed ts=${frame.timestampNs}: ${error.message}")
null
} finally {
GlesHardwareBufferImage.destroy(imageHandle)
}
}
/**
* Completes the submitted external-texture sampling before its Camera2 buffer is returned to
* ImageReader. The normal path is the same EGL fence hand-off used by MGC. If this context
* cannot create a fence, glFinish is the only safe fallback: returning the buffer early would
* let a later camera frame overwrite pixels while this draw still reads them.
*/
private fun awaitSourceSampling() {
val display = EGL14.eglGetCurrentDisplay()
if (display == EGL14.EGL_NO_DISPLAY) {
GLES30.glFinish()
return
}
val fence: EGLSync = EGL15.eglCreateSync(
display,
EGL15.EGL_SYNC_FENCE,
longArrayOf(EGL14.EGL_NONE.toLong()),
0,
)
if (fence == EGL15.EGL_NO_SYNC) {
GLES30.glFinish()
return
}
try {
val waitResult = EGL15.eglClientWaitSync(
display,
fence,
EGL15.EGL_SYNC_FLUSH_COMMANDS_BIT,
EGL15.EGL_FOREVER,
)
if (waitResult != EGL15.EGL_CONDITION_SATISFIED) {
PLog.w(tag, "MGC EGL fence wait failed result=$waitResult; forcing GL completion")
GLES30.glFinish()
}
} finally {
EGL15.eglDestroySync(display, fence)
}
}
fun resetAfterContextLoss() {
programId = 0
positionLocation = -1
textureCoordinateLocation = -1
sourceSamplerLocation = -1
sourceTextureId = 0
outputTextureId = 0
outputFramebufferId = 0
width = 0
height = 0
mesh.resetAfterContextLoss()
}
fun release() {
val textures = intArrayOf(sourceTextureId, outputTextureId)
.filter { it != 0 }
.toIntArray()
if (textures.isNotEmpty()) GLES30.glDeleteTextures(textures.size, textures, 0)
if (outputFramebufferId != 0) {
GLES30.glDeleteFramebuffers(1, intArrayOf(outputFramebufferId), 0)
}
if (programId != 0) GLES30.glDeleteProgram(programId)
mesh.release()
resetAfterContextLoss()
}
private fun ensure(requestedWidth: Int, requestedHeight: Int): Boolean {
if (programId != 0 && width == requestedWidth && height == requestedHeight) return true
release()
val vertexShader = GlUtils.compileShader(GLES30.GL_VERTEX_SHADER, VERTEX_SHADER)
val fragmentShader = GlUtils.compileShader(GLES30.GL_FRAGMENT_SHADER, FRAGMENT_SHADER)
programId = GlUtils.linkProgram(vertexShader, fragmentShader)
GLES30.glDeleteShader(vertexShader)
GLES30.glDeleteShader(fragmentShader)
if (programId == 0) return false
positionLocation = GLES30.glGetAttribLocation(programId, "aPosition")
textureCoordinateLocation = GLES30.glGetAttribLocation(programId, "aTexCoord")
sourceSamplerLocation = GLES30.glGetUniformLocation(programId, "uCameraTexture")
mesh.initialize()
sourceTextureId = GlUtils.createOESTexture()
outputTextureId = createTexture(requestedWidth, requestedHeight)
if (sourceTextureId == 0 || outputTextureId == 0 ||
!createOutputTarget(outputTextureId)
) {
release()
return false
}
width = requestedWidth
height = requestedHeight
return true
}
private fun createTexture(textureWidth: Int, textureHeight: Int): Int {
val ids = IntArray(1)
GLES30.glGenTextures(1, ids, 0)
GLES30.glBindTexture(GLES30.GL_TEXTURE_2D, ids[0])
GLES30.glTexParameteri(GLES30.GL_TEXTURE_2D, GLES30.GL_TEXTURE_MIN_FILTER, GLES30.GL_LINEAR)
GLES30.glTexParameteri(GLES30.GL_TEXTURE_2D, GLES30.GL_TEXTURE_MAG_FILTER, GLES30.GL_LINEAR)
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.glTexImage2D(
GLES30.GL_TEXTURE_2D,
0,
GLES30.GL_RGBA8,
textureWidth,
textureHeight,
0,
GLES30.GL_RGBA,
GLES30.GL_UNSIGNED_BYTE,
null,
)
GLES30.glBindTexture(GLES30.GL_TEXTURE_2D, 0)
return ids[0]
}
private fun createOutputTarget(textureId: Int): Boolean {
val framebuffers = IntArray(1)
GLES30.glGenFramebuffers(1, framebuffers, 0)
outputFramebufferId = framebuffers[0]
GLES30.glBindFramebuffer(GLES30.GL_FRAMEBUFFER, outputFramebufferId)
GLES30.glFramebufferTexture2D(
GLES30.GL_FRAMEBUFFER,
GLES30.GL_COLOR_ATTACHMENT0,
GLES30.GL_TEXTURE_2D,
textureId,
0,
)
val complete = GLES30.glCheckFramebufferStatus(GLES30.GL_FRAMEBUFFER) ==
GLES30.GL_FRAMEBUFFER_COMPLETE
GLES30.glBindFramebuffer(GLES30.GL_FRAMEBUFFER, 0)
if (!complete) PLog.e(tag, "Cannot allocate MGC HardwareBuffer output ${width}x$height")
return complete
}
private companion object {
val VERTEX_SHADER = """
#version 300 es
in vec4 aPosition;
in vec2 aTexCoord;
out vec2 vTexCoord;
void main() {
gl_Position = aPosition;
vTexCoord = aTexCoord;
}
""".trimIndent()
val FRAGMENT_SHADER = """
#version 300 es
#extension GL_OES_EGL_image_external_essl3 : require
precision highp float;
uniform samplerExternalOES uCameraTexture;
in vec2 vTexCoord;
out vec4 fragColor;
void main() {
fragColor = texture(uCameraTexture, vTexCoord);
}
""".trimIndent()
}
}
@@ -0,0 +1,155 @@
package com.hinnka.mycamera.lut
import android.opengl.GLES30
import android.opengl.GLES31
import com.hinnka.mycamera.stabilization.STABILIZATION_ROW_COUNT
import com.hinnka.mycamera.utils.PLog
/** Applies only MGC's rolling-strip geometry to the RGB output of [PreviewYuvRenderer]. */
internal class MgcEisRenderer(private val tag: String) {
data class Frame(val timestampNs: Long, val textureId: Int)
private val mesh = MgcEisMesh()
// Match native kOutputCropZoom = 1 / (1 - 2 * 0.05) even for a dropped pose.
private val droppedFrameHomographies = FloatArray(STABILIZATION_ROW_COUNT * 9).also { values ->
repeat(STABILIZATION_ROW_COUNT) { row ->
val offset = row * 9
values[offset] = 1f
values[offset + 4] = 1f
values[offset + 8] = 0.9f
}
}
private var programId = 0
private var positionLocation = -1
private var textureCoordinateLocation = -1
private var sourceSamplerLocation = -1
private var outputTextureId = 0
private var outputFramebufferId = 0
private var width = 0
private var height = 0
fun render(
textureId: Int,
width: Int,
height: Int,
timestampNs: Long,
rowHomographies: FloatArray?,
): Frame? {
if (textureId == 0 || width <= 0 || height <= 0 || !ensure(width, height)) return null
GLES30.glBindFramebuffer(GLES30.GL_FRAMEBUFFER, outputFramebufferId)
GLES30.glViewport(0, 0, width, height)
GLES30.glDisable(GLES30.GL_BLEND)
GLES30.glClearColor(0f, 0f, 0f, 1f)
GLES30.glClear(GLES30.GL_COLOR_BUFFER_BIT)
GLES30.glUseProgram(programId)
GLES30.glActiveTexture(GLES30.GL_TEXTURE0)
GLES30.glBindTexture(GLES30.GL_TEXTURE_2D, textureId)
GLES30.glUniform1i(sourceSamplerLocation, 0)
mesh.draw(
positionLocation = positionLocation,
textureCoordinateLocation = textureCoordinateLocation,
rowHomographies = rowHomographies ?: droppedFrameHomographies,
)
GLES30.glBindFramebuffer(GLES30.GL_FRAMEBUFFER, 0)
GLES30.glBindTexture(GLES30.GL_TEXTURE_2D, 0)
GLES31.glMemoryBarrier(GLES31.GL_FRAMEBUFFER_BARRIER_BIT or GLES31.GL_TEXTURE_FETCH_BARRIER_BIT)
return Frame(timestampNs, outputTextureId)
}
fun resetAfterContextLoss() {
programId = 0
positionLocation = -1
textureCoordinateLocation = -1
sourceSamplerLocation = -1
outputTextureId = 0
outputFramebufferId = 0
width = 0
height = 0
mesh.resetAfterContextLoss()
}
fun release() {
if (outputTextureId != 0) GLES30.glDeleteTextures(1, intArrayOf(outputTextureId), 0)
if (outputFramebufferId != 0) GLES30.glDeleteFramebuffers(1, intArrayOf(outputFramebufferId), 0)
if (programId != 0) GLES30.glDeleteProgram(programId)
mesh.release()
resetAfterContextLoss()
}
private fun ensure(requestedWidth: Int, requestedHeight: Int): Boolean {
if (programId != 0 && width == requestedWidth && height == requestedHeight) return true
release()
val vertexShader = GlUtils.compileShader(GLES30.GL_VERTEX_SHADER, VERTEX_SHADER)
val fragmentShader = GlUtils.compileShader(GLES30.GL_FRAGMENT_SHADER, FRAGMENT_SHADER)
if (vertexShader == 0 || fragmentShader == 0) {
if (vertexShader != 0) GLES30.glDeleteShader(vertexShader)
if (fragmentShader != 0) GLES30.glDeleteShader(fragmentShader)
return false
}
programId = GlUtils.linkProgram(vertexShader, fragmentShader)
GLES30.glDeleteShader(vertexShader)
GLES30.glDeleteShader(fragmentShader)
if (programId == 0) return false
positionLocation = GLES30.glGetAttribLocation(programId, "aPosition")
textureCoordinateLocation = GLES30.glGetAttribLocation(programId, "aTexCoord")
sourceSamplerLocation = GLES30.glGetUniformLocation(programId, "uCameraTexture")
mesh.initialize()
val textures = IntArray(1)
GLES30.glGenTextures(1, textures, 0)
outputTextureId = textures[0]
GLES30.glActiveTexture(GLES30.GL_TEXTURE0)
GLES30.glBindTexture(GLES30.GL_TEXTURE_2D, outputTextureId)
GLES30.glTexParameteri(GLES30.GL_TEXTURE_2D, GLES30.GL_TEXTURE_MIN_FILTER, GLES30.GL_LINEAR)
GLES30.glTexParameteri(GLES30.GL_TEXTURE_2D, GLES30.GL_TEXTURE_MAG_FILTER, GLES30.GL_LINEAR)
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.glTexImage2D(
GLES30.GL_TEXTURE_2D, 0, GLES30.GL_RGBA8, requestedWidth, requestedHeight,
0, GLES30.GL_RGBA, GLES30.GL_UNSIGNED_BYTE, null,
)
GLES30.glBindTexture(GLES30.GL_TEXTURE_2D, 0)
val framebuffers = IntArray(1)
GLES30.glGenFramebuffers(1, framebuffers, 0)
outputFramebufferId = framebuffers[0]
GLES30.glBindFramebuffer(GLES30.GL_FRAMEBUFFER, outputFramebufferId)
GLES30.glFramebufferTexture2D(
GLES30.GL_FRAMEBUFFER, GLES30.GL_COLOR_ATTACHMENT0,
GLES30.GL_TEXTURE_2D, outputTextureId, 0,
)
val complete = GLES30.glCheckFramebufferStatus(GLES30.GL_FRAMEBUFFER) == GLES30.GL_FRAMEBUFFER_COMPLETE
GLES30.glBindFramebuffer(GLES30.GL_FRAMEBUFFER, 0)
if (outputTextureId == 0 || !complete) {
PLog.e(tag, "Cannot allocate MGC geometry output ${requestedWidth}x$requestedHeight")
release()
return false
}
width = requestedWidth
height = requestedHeight
return true
}
private companion object {
val VERTEX_SHADER = """
#version 300 es
in vec4 aPosition;
in vec2 aTexCoord;
out vec2 vTexCoord;
void main() {
gl_Position = aPosition;
vTexCoord = aTexCoord;
}
""".trimIndent()
val FRAGMENT_SHADER = """
#version 300 es
precision highp float;
uniform highp sampler2D uCameraTexture;
in vec2 vTexCoord;
out vec4 fragColor;
void main() {
// Mesh V starts at the top camera row; RGB framebuffer row zero is at V=1.
fragColor = texture(uCameraTexture, vec2(vTexCoord.x, 1.0 - vTexCoord.y));
}
""".trimIndent()
}
}
@@ -1,377 +0,0 @@
package com.hinnka.mycamera.lut
import android.media.Image
import android.opengl.GLES30
import android.opengl.GLES31
import com.hinnka.mycamera.stabilization.STABILIZATION_ROW_COUNT
import com.hinnka.mycamera.stabilization.StabilizationFrame
import com.hinnka.mycamera.utils.PLog
import java.nio.ByteBuffer
/**
* Materializes one timestamp-matched Camera2 image after applying MGC's rolling-strip mesh.
*
* Center crop, orientation, mirroring and color effects remain in the normal preview or encoder
* presentation pass.
*/
internal class MgcEisYuvRenderer(private val tag: String) {
data class Frame(val timestampNs: Long, val textureId: Int)
private val mesh = MgcEisMesh()
// Native output matrices pass through convertPixelHomographyToClip then
// applyCropZoomToClipHomography(kOutputCropZoom), where:
// kLookaheadCropMargin = 0.05
// kOutputCropZoom = 1.0 / (1.0 - 2.0 * 0.05) ≈ 1.1111
// applyCropZoomToClipHomography divides the W row (h20, h21, h22) by zoom.
// A Dropped frame must use the same crop so that the viewport does not jump
// between 1.0x and 1.111x on every stabilization gap.
private val droppedFrameHomographies = FloatArray(STABILIZATION_ROW_COUNT * 9).also { values ->
val h22 = 1.0f - 2.0f * 0.05f // = 1.0f / kOutputCropZoom = 0.9f
repeat(STABILIZATION_ROW_COUNT) { row ->
val offset = row * 9
values[offset] = 1f // h00
values[offset + 4] = 1f // h11
values[offset + 8] = h22 // h22: W-row crop zoom
}
}
private var programId = 0
private var positionLocation = -1
private var textureCoordinateLocation = -1
private var ySamplerLocation = -1
private var cbSamplerLocation = -1
private var crSamplerLocation = -1
private var imageSizeLocation = -1
private var cbSizeLocation = -1
private var crSizeLocation = -1
private var cbStepLocation = -1
private var crStepLocation = -1
private var yTextureId = 0
private var cbTextureId = 0
private var crTextureId = 0
private var outputTextureId = 0
private var outputFramebufferId = 0
private var width = 0
private var height = 0
private var cbWidth = 0
private var crWidth = 0
private var chromaHeight = 0
/** Consumes ownership of [frame.image], including when rendering fails. */
fun render(frame: StabilizationFrame): Frame? {
val source = frame.image.image
return try {
if (source.planes.size < 3 || source.width <= 0 || source.height <= 0) return null
val cbPlane = source.planes[1]
val crPlane = source.planes[2]
val logicalChromaWidth = (source.width + 1) / 2
val logicalChromaHeight = (source.height + 1) / 2
val requestedCbWidth = (logicalChromaWidth - 1) * cbPlane.pixelStride + 1
val requestedCrWidth = (logicalChromaWidth - 1) * crPlane.pixelStride + 1
if (!ensure(
source.width,
source.height,
requestedCbWidth,
requestedCrWidth,
logicalChromaHeight,
)
) {
return null
}
if (!uploadPlane(source.planes[0], yTextureId, source.width, source.height, "Y") ||
!uploadPlane(cbPlane, cbTextureId, requestedCbWidth, logicalChromaHeight, "Cb") ||
!uploadPlane(crPlane, crTextureId, requestedCrWidth, logicalChromaHeight, "Cr")
) {
return null
}
GLES30.glBindFramebuffer(GLES30.GL_FRAMEBUFFER, outputFramebufferId)
GLES30.glViewport(0, 0, source.width, source.height)
GLES30.glClearColor(0f, 0f, 0f, 1f)
GLES30.glClear(GLES30.GL_COLOR_BUFFER_BIT)
GLES30.glUseProgram(programId)
bindTexture(0, yTextureId, ySamplerLocation)
bindTexture(1, cbTextureId, cbSamplerLocation)
bindTexture(2, crTextureId, crSamplerLocation)
GLES30.glUniform2i(imageSizeLocation, source.width, source.height)
GLES30.glUniform2i(cbSizeLocation, requestedCbWidth, logicalChromaHeight)
GLES30.glUniform2i(crSizeLocation, requestedCrWidth, logicalChromaHeight)
GLES30.glUniform1i(cbStepLocation, cbPlane.pixelStride)
GLES30.glUniform1i(crStepLocation, crPlane.pixelStride)
mesh.draw(
positionLocation = positionLocation,
textureCoordinateLocation = textureCoordinateLocation,
rowHomographies = frame.transform?.rowHomographies ?: droppedFrameHomographies,
)
GLES30.glBindFramebuffer(GLES30.GL_FRAMEBUFFER, 0)
GLES31.glMemoryBarrier(
GLES31.GL_FRAMEBUFFER_BARRIER_BIT or GLES31.GL_TEXTURE_FETCH_BARRIER_BIT,
)
repeat(3) { unit ->
GLES30.glActiveTexture(GLES30.GL_TEXTURE0 + unit)
GLES30.glBindTexture(GLES30.GL_TEXTURE_2D, 0)
}
GLES30.glActiveTexture(GLES30.GL_TEXTURE0)
Frame(frame.timestampNs, outputTextureId)
} catch (error: IllegalStateException) {
// Camera2 may revoke an acquired Image when the underlying
// ImageReader is torn down during a delayed-EIS session change.
// The timestamped result is no longer renderable, but it must not
// take the GL thread down with it.
PLog.w(tag, "MGC dropped revoked YUV image ts=${frame.timestampNs}: ${error.message}")
null
} finally {
// glTexSubImage2D has consumed the client memory when it returns; the Camera2 image
// is no longer referenced by later GPU commands in the CPU fallback path.
frame.image.close()
}
}
fun resetAfterContextLoss() {
programId = 0
positionLocation = -1
textureCoordinateLocation = -1
ySamplerLocation = -1
cbSamplerLocation = -1
crSamplerLocation = -1
imageSizeLocation = -1
cbSizeLocation = -1
crSizeLocation = -1
cbStepLocation = -1
crStepLocation = -1
yTextureId = 0
cbTextureId = 0
crTextureId = 0
outputTextureId = 0
outputFramebufferId = 0
width = 0
height = 0
cbWidth = 0
crWidth = 0
chromaHeight = 0
mesh.resetAfterContextLoss()
}
fun release() {
val textures = intArrayOf(
yTextureId,
cbTextureId,
crTextureId,
outputTextureId,
)
.filter { it != 0 }
.toIntArray()
if (textures.isNotEmpty()) GLES30.glDeleteTextures(textures.size, textures, 0)
if (outputFramebufferId != 0) {
GLES30.glDeleteFramebuffers(1, intArrayOf(outputFramebufferId), 0)
}
if (programId != 0) GLES30.glDeleteProgram(programId)
mesh.release()
resetAfterContextLoss()
}
private fun ensure(
requestedWidth: Int,
requestedHeight: Int,
requestedCbWidth: Int,
requestedCrWidth: Int,
requestedChromaHeight: Int,
): Boolean {
if (programId != 0 && width == requestedWidth && height == requestedHeight &&
cbWidth == requestedCbWidth && crWidth == requestedCrWidth &&
chromaHeight == requestedChromaHeight
) {
return true
}
release()
val vertexShader = GlUtils.compileShader(GLES30.GL_VERTEX_SHADER, VERTEX_SHADER)
val fragmentShader = GlUtils.compileShader(GLES30.GL_FRAGMENT_SHADER, FRAGMENT_SHADER)
programId = GlUtils.linkProgram(vertexShader, fragmentShader)
GLES30.glDeleteShader(vertexShader)
GLES30.glDeleteShader(fragmentShader)
if (programId == 0) return false
positionLocation = GLES30.glGetAttribLocation(programId, "aPosition")
textureCoordinateLocation = GLES30.glGetAttribLocation(programId, "aTexCoord")
ySamplerLocation = GLES30.glGetUniformLocation(programId, "uY")
cbSamplerLocation = GLES30.glGetUniformLocation(programId, "uCb")
crSamplerLocation = GLES30.glGetUniformLocation(programId, "uCr")
imageSizeLocation = GLES30.glGetUniformLocation(programId, "uImageSize")
cbSizeLocation = GLES30.glGetUniformLocation(programId, "uCbSize")
crSizeLocation = GLES30.glGetUniformLocation(programId, "uCrSize")
cbStepLocation = GLES30.glGetUniformLocation(programId, "uCbStep")
crStepLocation = GLES30.glGetUniformLocation(programId, "uCrStep")
mesh.initialize()
yTextureId = createTexture(requestedWidth, requestedHeight, GLES30.GL_R8)
cbTextureId = createTexture(requestedCbWidth, requestedChromaHeight, GLES30.GL_R8)
crTextureId = createTexture(requestedCrWidth, requestedChromaHeight, GLES30.GL_R8)
if (!createOutputTarget(requestedWidth, requestedHeight)) return false
width = requestedWidth
height = requestedHeight
cbWidth = requestedCbWidth
crWidth = requestedCrWidth
chromaHeight = requestedChromaHeight
return true
}
private fun createOutputTarget(requestedWidth: Int, requestedHeight: Int): Boolean {
outputTextureId = createTexture(requestedWidth, requestedHeight, GLES30.GL_RGBA8)
val framebuffer = IntArray(1)
GLES30.glGenFramebuffers(1, framebuffer, 0)
outputFramebufferId = framebuffer[0]
GLES30.glBindFramebuffer(GLES30.GL_FRAMEBUFFER, outputFramebufferId)
GLES30.glFramebufferTexture2D(
GLES30.GL_FRAMEBUFFER,
GLES30.GL_COLOR_ATTACHMENT0,
GLES30.GL_TEXTURE_2D,
outputTextureId,
0,
)
val complete = GLES30.glCheckFramebufferStatus(GLES30.GL_FRAMEBUFFER) ==
GLES30.GL_FRAMEBUFFER_COMPLETE
GLES30.glBindFramebuffer(GLES30.GL_FRAMEBUFFER, 0)
if (!complete) {
PLog.e(tag, "Cannot allocate MGC canonical output ${requestedWidth}x$requestedHeight")
release()
return false
}
return true
}
private fun createTexture(textureWidth: Int, textureHeight: Int, internalFormat: Int): Int {
val ids = IntArray(1)
GLES30.glGenTextures(1, ids, 0)
GLES30.glBindTexture(GLES30.GL_TEXTURE_2D, ids[0])
GLES30.glTexParameteri(GLES30.GL_TEXTURE_2D, GLES30.GL_TEXTURE_MIN_FILTER, GLES30.GL_LINEAR)
GLES30.glTexParameteri(GLES30.GL_TEXTURE_2D, GLES30.GL_TEXTURE_MAG_FILTER, GLES30.GL_LINEAR)
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)
val format = if (internalFormat == GLES30.GL_RGBA8) GLES30.GL_RGBA else GLES30.GL_RED
GLES30.glTexImage2D(
GLES30.GL_TEXTURE_2D,
0,
internalFormat,
textureWidth,
textureHeight,
0,
format,
GLES30.GL_UNSIGNED_BYTE,
null,
)
GLES30.glBindTexture(GLES30.GL_TEXTURE_2D, 0)
return ids[0]
}
private fun uploadPlane(
plane: Image.Plane,
textureId: Int,
uploadWidth: Int,
uploadHeight: Int,
label: String,
): Boolean {
if (plane.pixelStride <= 0 || plane.rowStride < uploadWidth || uploadWidth <= 0 ||
uploadHeight <= 0
) {
PLog.w(tag, "MGC $label invalid plane row=${plane.rowStride} pixel=${plane.pixelStride}")
return false
}
val buffer = plane.buffer.duplicate().apply { position(0) }
val required = (uploadHeight - 1).toLong() * plane.rowStride + uploadWidth
if (required > buffer.limit().toLong()) {
PLog.w(tag, "MGC $label buffer too small: required=$required available=${buffer.limit()}")
return false
}
uploadTexture(textureId, uploadWidth, uploadHeight, plane.rowStride, buffer)
return true
}
private fun uploadTexture(
textureId: Int,
uploadWidth: Int,
uploadHeight: Int,
rowLength: Int,
buffer: ByteBuffer,
) {
GLES30.glBindTexture(GLES30.GL_TEXTURE_2D, textureId)
GLES30.glPixelStorei(GLES30.GL_UNPACK_ALIGNMENT, 1)
GLES30.glPixelStorei(GLES30.GL_UNPACK_ROW_LENGTH, rowLength)
GLES30.glTexSubImage2D(
GLES30.GL_TEXTURE_2D,
0,
0,
0,
uploadWidth,
uploadHeight,
GLES30.GL_RED,
GLES30.GL_UNSIGNED_BYTE,
buffer,
)
GLES30.glPixelStorei(GLES30.GL_UNPACK_ROW_LENGTH, 0)
GLES30.glPixelStorei(GLES30.GL_UNPACK_ALIGNMENT, 4)
GLES30.glBindTexture(GLES30.GL_TEXTURE_2D, 0)
}
private fun bindTexture(unit: Int, textureId: Int, samplerLocation: Int) {
GLES30.glActiveTexture(GLES30.GL_TEXTURE0 + unit)
GLES30.glBindTexture(GLES30.GL_TEXTURE_2D, textureId)
GLES30.glUniform1i(samplerLocation, unit)
}
private companion object {
val VERTEX_SHADER = """
#version 300 es
in vec4 aPosition;
in vec2 aTexCoord;
out vec2 vTexCoord;
void main() {
gl_Position = aPosition;
vTexCoord = aTexCoord;
}
""".trimIndent()
val FRAGMENT_SHADER = """
#version 300 es
precision highp float;
uniform sampler2D uY;
uniform sampler2D uCb;
uniform sampler2D uCr;
uniform ivec2 uImageSize;
uniform ivec2 uCbSize;
uniform ivec2 uCrSize;
uniform int uCbStep;
uniform int uCrStep;
in vec2 vTexCoord;
out vec4 fragColor;
void main() {
ivec2 p = clamp(
ivec2(vTexCoord * vec2(uImageSize)),
ivec2(0),
uImageSize - ivec2(1)
);
ivec2 cbP = clamp(
ivec2((p.x / 2) * uCbStep, p.y / 2),
ivec2(0),
uCbSize - ivec2(1)
);
ivec2 crP = clamp(
ivec2((p.x / 2) * uCrStep, p.y / 2),
ivec2(0),
uCrSize - ivec2(1)
);
float y = texelFetch(uY, p, 0).r;
float cb = texelFetch(uCb, cbP, 0).r - 0.5;
float cr = texelFetch(uCr, crP, 0).r - 0.5;
vec3 rgb = vec3(
y + 1.402 * cr,
y - 0.344136 * cb - 0.714136 * cr,
y + 1.772 * cb
);
fragColor = vec4(clamp(rgb, 0.0, 1.0), 1.0);
}
""".trimIndent()
}
}
@@ -9,7 +9,6 @@ import android.opengl.GLES30
import android.opengl.GLES31
import android.opengl.Matrix
import android.os.Build
import com.hinnka.mycamera.camera.PreviewYuvFrame
import com.hinnka.mycamera.processor.GlesHardwareBufferImage
import com.hinnka.mycamera.utils.PLog
import java.nio.ByteBuffer
@@ -19,15 +18,15 @@ import java.nio.ByteOrder
* Converts one YUV_420_888 preview image into an RGBA8 texture with the image's own YCbCr matrix
* and range, in the MGC output layout (buffer row 0 at the top framebuffer row).
*
* Paths, in order: HardwareBuffer EGLImage read as raw YCbCr through GL_EXT_YUV_target; the same
* EGLImage converted by the driver's samplerExternalOES when the extension is missing; and plane
* upload when the buffer cannot be imported into EGL.
* HardwareBuffer EGLImage raw YCbCr sampling and CPU plane upload use the same explicit matrix
* and range. Without GL_EXT_YUV_target, use planes rather than a driver-specific RGB conversion.
* Shared by ordinary preview and EIS; stabilization operates only on this converter's RGB output.
* Readers retain their default usage: GPU_SAMPLED_IMAGE caused swapped Cb/Cr on Xiaomi 11.
*/
internal class PreviewYuvRenderer(private val tag: String) {
private enum class Path { RAW_YUV, DRIVER_RGB, PLANES }
private enum class Path { RAW_YUV, PLANES }
private var y2yProgram: Program? = null
private var driverProgram: Program? = null
private var planeProgram: Program? = null
private var yuvTargetSupported: Boolean? = null
private var importDisabled = false
@@ -46,25 +45,24 @@ internal class PreviewYuvRenderer(private val tag: String) {
private val conversion = FloatArray(9)
private val offset = FloatArray(3)
/** Always closes [frame]. Returns the output texture, or 0 when the frame cannot be drawn. */
fun render(frame: PreviewYuvFrame): Int {
/** Borrows [image] through GPU sampling completion; the caller retains ownership. */
fun render(image: Image): Int {
try {
val image = frame.image
if (image.width <= 0 || image.height <= 0) return 0
if (!ensureTarget(image.width, image.height)) return 0
resolveConversion(frame.dataSpace)
resolveConversion(if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) image.dataSpace else 0)
val drawn = (!importDisabled && drawImported(image)) || drawPlanes(image)
return if (drawn) outputTextureId else 0
} catch (error: IllegalStateException) {
// The reader may be torn down while a frame is still queued for the GL thread.
PLog.w(tag, "Preview YUV frame revoked ts=${frame.timestampNs}: ${error.message}")
PLog.w(tag, "Preview YUV frame revoked: ${error.message}")
return 0
} finally {
frame.close()
}
}
private fun drawImported(image: Image): Boolean {
val rawYuv = yuvTargetSupported ?: queryYuvTarget().also { yuvTargetSupported = it }
if (!rawYuv) return disableImport("GL_EXT_YUV_target unavailable")
val buffer = image.hardwareBuffer ?: return disableImport("Image has no HardwareBuffer")
val handle = buffer.use { GlesHardwareBufferImage.create(it) }
if (handle == 0L) return disableImport("EGLImage import failed")
@@ -73,12 +71,8 @@ internal class PreviewYuvRenderer(private val tag: String) {
if (!GlesHardwareBufferImage.bind(handle, externalTextureId)) {
return disableImport("EGLImage bind failed")
}
val rawYuv = yuvTargetSupported ?: queryYuvTarget().also { yuvTargetSupported = it }
val program = if (rawYuv) {
y2yProgram ?: buildProgram(Y2Y_FRAGMENT_SHADER).also { y2yProgram = it }
} else {
driverProgram ?: buildProgram(DRIVER_FRAGMENT_SHADER).also { driverProgram = it }
} ?: return disableImport("External program unavailable")
val program = y2yProgram ?: buildProgram(Y2Y_FRAGMENT_SHADER)?.also { y2yProgram = it }
?: return disableImport("External program unavailable")
beginDraw(program)
GLES30.glActiveTexture(GLES30.GL_TEXTURE0)
GLES30.glBindTexture(GLES11Ext.GL_TEXTURE_EXTERNAL_OES, externalTextureId)
@@ -88,7 +82,7 @@ internal class PreviewYuvRenderer(private val tag: String) {
awaitGpu()
GLES30.glBindTexture(GLES11Ext.GL_TEXTURE_EXTERNAL_OES, 0)
endDraw()
reportPath(if (rawYuv) Path.RAW_YUV else Path.DRIVER_RGB)
reportPath(Path.RAW_YUV)
return true
} finally {
GlesHardwareBufferImage.destroy(handle)
@@ -358,14 +352,14 @@ internal class PreviewYuvRenderer(private val tag: String) {
releasePlaneTextures()
if (externalTextureId != 0) GlUtils.deleteTexture(externalTextureId)
if (quadBufferId != 0) GLES30.glDeleteBuffers(1, intArrayOf(quadBufferId), 0)
listOfNotNull(y2yProgram, driverProgram, planeProgram).forEach { GLES30.glDeleteProgram(it.id) }
listOfNotNull(y2yProgram, planeProgram).forEach { GLES30.glDeleteProgram(it.id) }
resetAfterContextLoss()
}
/** Forgets GL names without deleting them; the context that owned them is gone. */
fun resetAfterContextLoss() {
y2yProgram = null
driverProgram = null
importDisabled = false
planeProgram = null
yuvTargetSupported = null
activePath = null
@@ -416,7 +410,7 @@ internal class PreviewYuvRenderer(private val tag: String) {
#version 300 es
#extension GL_EXT_YUV_target : require
precision highp float;
uniform __samplerExternal2DY2YEXT uInput;
uniform highp __samplerExternal2DY2YEXT uInput;
uniform mat3 uYuvToRgb;
uniform vec3 uYuvOffset;
in vec2 vTexCoord;
@@ -427,22 +421,10 @@ internal class PreviewYuvRenderer(private val tag: String) {
}
""".trimIndent()
// Without GL_EXT_YUV_target the driver applies its own YCbCr conversion.
val DRIVER_FRAGMENT_SHADER = """
#version 300 es
#extension GL_OES_EGL_image_external_essl3 : require
precision highp float;
uniform samplerExternalOES uInput;
in vec2 vTexCoord;
out vec4 fragColor;
void main() {
fragColor = vec4(texture(uInput, vTexCoord).rgb, 1.0);
}
""".trimIndent()
val PLANE_FRAGMENT_SHADER = """
#version 300 es
precision highp float;
precision highp int;
uniform highp sampler2D uInput;
uniform highp sampler2D uCb;
uniform highp sampler2D uCr;
@@ -84,8 +84,8 @@ class RealtimeVideoRenderer(
private val toneBase = ToneBaseGl(TAG)
private val basicToneTextures = BasicToneGlTextures()
private val filmGrainGl = FilmGrainGl(TAG)
private val mgcEisHardwareBufferRenderer = MgcEisHardwareBufferRenderer(TAG)
private val mgcEisYuvRenderer = MgcEisYuvRenderer(TAG)
private val mgcEisRenderer = MgcEisRenderer(TAG)
private val previewYuvRenderer = PreviewYuvRenderer(TAG)
private val filmGrainAmount: Float
get() = layers.lastOrNull { it.params.filmGrain > 0.001f }?.params?.filmGrain ?: 0f
private val finalFilmGrainEnabled: Boolean
@@ -398,14 +398,17 @@ class RealtimeVideoRenderer(
private fun renderMgcEisFrame(
frame: com.hinnka.mycamera.stabilization.StabilizationFrame,
): MgcEisHardwareBufferRenderer.Frame? {
val hardwareRendered = mgcEisHardwareBufferRenderer.render(frame)
if (hardwareRendered != null) {
frame.image.close()
return hardwareRendered
}
return mgcEisYuvRenderer.render(frame)?.let { rendered ->
MgcEisHardwareBufferRenderer.Frame(rendered.timestampNs, rendered.textureId)
): MgcEisRenderer.Frame? {
return frame.image.use { image ->
val textureId = previewYuvRenderer.render(image.image)
if (textureId == 0) return null
mgcEisRenderer.render(
textureId = textureId,
width = image.width,
height = image.height,
timestampNs = frame.timestampNs,
rowHomographies = frame.transform?.rowHomographies,
)
}
}
@@ -1005,8 +1008,8 @@ class RealtimeVideoRenderer(
filmGrainGl.release()
softLightGl.release()
highlightDiffusionGl.release()
mgcEisHardwareBufferRenderer.release()
mgcEisYuvRenderer.release()
mgcEisRenderer.release()
previewYuvRenderer.release()
colorProgramCache.release()
toneBase.release()
basicToneTextures.release()
@@ -247,6 +247,7 @@ class RealtimeStabilizationCoordinator(context: Context) {
private var resultSequence = 0L
private var boundaryCount = 0L
private var nativeFrameAttemptCount = 0L
private var currentCaptureRequestGeneration = -1L
private var captureResultCount = 0L
private var consecutiveHalStabilizationConflictCount = 0
private var rawGyroCallbackCount = 0L
@@ -427,6 +428,7 @@ class RealtimeStabilizationCoordinator(context: Context) {
fun submitCaptureResult(
result: CaptureResult,
captureRequestGeneration: Long,
request: CaptureRequest? = null,
outputPhysicalCameraId: String? = null,
) {
@@ -468,6 +470,11 @@ class RealtimeStabilizationCoordinator(context: Context) {
emptyList()
}
synchronized(lock) {
if (currentCaptureRequestGeneration != captureRequestGeneration) {
currentCaptureRequestGeneration = captureRequestGeneration
captureResultCount = 0L
consecutiveHalStabilizationConflictCount = 0
}
captureResultCount += 1L
val requestedVideoStabilization = request?.get(
CaptureRequest.CONTROL_VIDEO_STABILIZATION_MODE,
@@ -768,6 +775,7 @@ class RealtimeStabilizationCoordinator(context: Context) {
resultSequence = 0L
boundaryCount = 0L
nativeFrameAttemptCount = 0L
currentCaptureRequestGeneration = -1L
captureResultCount = 0L
consecutiveHalStabilizationConflictCount = 0
rawGyroCallbackCount = 0L
@@ -7,7 +7,10 @@ import android.os.Handler
import com.hinnka.mycamera.utils.PLog
import java.util.concurrent.atomic.AtomicBoolean
/** Owns the reader until every acquired frame, including renderer leases, has been released. */
/**
* Camera YUV input for photo preview and EIS. Supports latest-frame display or FIFO stabilization,
* retaining the reader until every acquired frame, including renderer leases, has been released.
*/
internal class StabilizationImageReader(
val width: Int,
val height: Int,
@@ -37,6 +40,13 @@ internal class StabilizationImageReader(
AcquiredImage(this, image)
}
fun acquireLatestImage(): AcquiredImage? = synchronized(lock) {
if (isClosed) return@synchronized null
val image = reader.acquireLatestImage() ?: return@synchronized null
acquiredImageCount += 1
AcquiredImage(this, image)
}
override fun close() {
synchronized(lock) {
if (isClosed) return