diff --git a/app/src/main/java/com/hinnka/mycamera/camera/Camera2Controller.kt b/app/src/main/java/com/hinnka/mycamera/camera/Camera2Controller.kt index ca10025c..f5519c84 100644 --- a/app/src/main/java/com/hinnka/mycamera/camera/Camera2Controller.kt +++ b/app/src/main/java/com/hinnka/mycamera/camera/Camera2Controller.kt @@ -275,6 +275,9 @@ 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 + val previewYuvChannel = PreviewYuvFrameChannel() private var imageReader: ImageReader? = null private var stabilizationImageReader: StabilizationImageReader? = null @@ -2181,15 +2184,31 @@ class Camera2Controller(private val context: Context) { private fun safeReleasePreviewSurface(reason: String) { val surface = previewSurface + val yuvReader = previewYuvReader previewSurface = null previewSurfaceTexture = null + previewYuvReader = null try { - surface?.release() + // The reader owns its surface and outlives frames still leased to the renderer. + if (yuvReader != null) yuvReader.close() 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( + 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}") + } + } + private fun clearCameraRuntimeState(reason: String, closeImageReader: Boolean = true) { clearCameraSessionState(reason, closeImageReader) clearCameraCapabilityCache() @@ -2783,9 +2802,11 @@ class Camera2Controller(private val context: Context) { return } - // 配置 SurfaceTexture + // 拍照模式的预览 Surface 是 YUV ImageReader,在下面确定最终预览尺寸后创建 previewSurfaceTexture = surfaceTexture - previewSurface = Surface(surfaceTexture) + if (captureMode != CaptureMode.PHOTO) { + previewSurface = Surface(surfaceTexture) + } if (captureMode == CaptureMode.PHOTO) { val aspectRatio = state.value.aspectRatio @@ -2830,6 +2851,7 @@ class Camera2Controller(private val context: Context) { } previewSize = CameraUtils.getFixedPreviewSize(outputCharacteristicsForStreams, aspectRatio) surfaceTexture.setDefaultBufferSize(previewSize.width, previewSize.height) + previewSurface = createPreviewYuvReader(previewSize).surface val highResolutionProfile = "$outputCameraIdForStreams:$captureFormat" val captureSizeSelection = if (rawOutput != null) { null diff --git a/app/src/main/java/com/hinnka/mycamera/camera/CameraUtils.kt b/app/src/main/java/com/hinnka/mycamera/camera/CameraUtils.kt index 9c3956b9..450f7d25 100644 --- a/app/src/main/java/com/hinnka/mycamera/camera/CameraUtils.kt +++ b/app/src/main/java/com/hinnka/mycamera/camera/CameraUtils.kt @@ -2,7 +2,6 @@ package com.hinnka.mycamera.camera import android.content.Context import android.graphics.ImageFormat -import android.graphics.SurfaceTexture import android.hardware.camera2.CameraCharacteristics import android.hardware.camera2.CameraManager import android.hardware.camera2.params.StreamConfigurationMap @@ -17,7 +16,7 @@ import kotlin.math.abs object CameraUtils { /** - * 获取固定的预览尺寸 + * 获取拍照模式的固定预览尺寸(YUV_420_888 预览流) * 使用固定尺寸可以避免切换画面比例时频繁重新配置相机会话, * 不同的画面比例通过 UI 裁切实现 */ @@ -44,57 +43,47 @@ object CameraUtils { val map = characteristics.get(CameraCharacteristics.SCALER_STREAM_CONFIGURATION_MAP) ?: return Size(1440, 1080) - // 首先获取最大的拍照尺寸,以此作为传感器的原生比例 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). + val previewSizes = map.getOutputSizes(ImageFormat.YUV_420_888) + ?.filter { isWithinPreviewBound(it) } + .orEmpty() - val previewSizes = map.getOutputSizes(SurfaceTexture::class.java)?.toList() ?: emptyList() + largestWithRatio(previewSizes, sensorRatio)?.let { return it } - // 寻找比例最匹配传感器原生比例且高度不超过 1080 的预览尺寸 - val matchingSizes = previewSizes.filter { - val ratio = it.width.toFloat() / it.height - abs(ratio - sensorRatio) < 0.01 - } - - // 优先选择匹配比例中,高度最接近 1080 的尺寸 - val bestMatching = matchingSizes.filter { it.height <= 1080 }.maxByOrNull { it.width * it.height } - ?: matchingSizes.minByOrNull { it.width * it.height } - - if (bestMatching != null) return bestMatching - - // 没有精确匹配的比例时(如 XPAN 65:24),需要选择一个能覆盖目标比例的预览尺寸。 - // 关键:必须与 getBestCaptureSize 使用相同的选择策略(选择最宽的尺寸), + // 没有该比例的 PREVIEW 尺寸时(如 XPAN 65:24),用拍照会选择的基础比例的预览尺寸, + // 再由 UI 裁切到目标比例。必须与 getBestCaptureSize 的基础比例一致(选择最宽的尺寸), // 否则预览和拍摄从不同基础比例裁切到目标比例时,FOV 会不一致。 - // - // 例如 XPAN (2.708:1):如果预览选了 1:1 (1080x1080),拍照选了 4:3 (4096x3072), - // 两者裁切到 65:24 时,4:3 的水平 FOV 更大,导致拍到的画面比预览多。 - // - // 策略:找到 getBestCaptureSize 会选择的比例,然后选择该比例的预览尺寸 val captureSizes = map.getOutputSizes(ImageFormat.YUV_420_888)?.toList().orEmpty() + getHighResolutionOutputSizes(map, ImageFormat.YUV_420_888) - val bestCaptureSize = captureSizes.maxByOrNull { it.width.toLong() * it.height } - - if (bestCaptureSize != null) { + captureSizes.maxByOrNull { it.width.toLong() * it.height }?.let { bestCaptureSize -> val captureRatio = bestCaptureSize.width.toFloat() / bestCaptureSize.height - val captureMatchingSizes = previewSizes.filter { - val ratio = it.width.toFloat() / it.height - abs(ratio - captureRatio) < 0.01 - } - val bestCaptureMatching = captureMatchingSizes - .filter { it.height <= 1080 } - .maxByOrNull { it.width * it.height } - ?: captureMatchingSizes.minByOrNull { it.width * it.height } - - if (bestCaptureMatching != null) return bestCaptureMatching + largestWithRatio(previewSizes, captureRatio)?.let { return it } } - // 最终回退:选择高度 >= 1080 中最小的一个 - return previewSizes.filter { it.height >= 1080 }.minByOrNull { it.width } ?: Size(1440, 1080) + previewSizes.maxByOrNull { it.width * it.height } ?: Size(1440, 1080) } catch (e: Exception) { PLog.d("CameraUtils", "getFixedPreviewSize: ${e.message}") - return Size(1440, 1080) + Size(1440, 1080) } } + private const val PREVIEW_BOUND_LONG = 1920 + private const val PREVIEW_BOUND_SHORT = 1080 + + private fun isWithinPreviewBound(size: Size): Boolean { + return maxOf(size.width, size.height) <= PREVIEW_BOUND_LONG && + minOf(size.width, size.height) <= PREVIEW_BOUND_SHORT + } + + private fun largestWithRatio(sizes: List, ratio: Float): Size? { + return sizes + .filter { abs(it.width.toFloat() / it.height - ratio) < 0.01f } + .maxByOrNull { it.width * it.height } + } + /** * 获取最佳拍照尺寸 */ diff --git a/app/src/main/java/com/hinnka/mycamera/camera/PreviewYuvStream.kt b/app/src/main/java/com/hinnka/mycamera/camera/PreviewYuvStream.kt new file mode 100644 index 00000000..831b29be --- /dev/null +++ b/app/src/main/java/com/hinnka/mycamera/camera/PreviewYuvStream.kt @@ -0,0 +1,116 @@ +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 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. */ +class PreviewYuvFrameChannel { + private val latest = AtomicReference(null) + + @Volatile + var onFrameAvailable: (() -> Unit)? = null + + internal fun publish(frame: PreviewYuvFrame) { + 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 discardFrom(owner: PreviewYuvImageReader) { + val frame = latest.get() ?: return + if (frame.owner === owner && latest.compareAndSet(frame, null)) frame.close() + } +} diff --git a/app/src/main/java/com/hinnka/mycamera/data/UserPreferences.kt b/app/src/main/java/com/hinnka/mycamera/data/UserPreferences.kt index a164bace..4cdb692c 100644 --- a/app/src/main/java/com/hinnka/mycamera/data/UserPreferences.kt +++ b/app/src/main/java/com/hinnka/mycamera/data/UserPreferences.kt @@ -156,7 +156,6 @@ class UserPreferences internal constructor( var deletedBuiltInIds by string("deleted_built_in_ids", "") var showLevelIndicator by bool("show_level_indicator", false) // 水平仪显示 var focusPeakingEnabled by bool("focus_peaking_enabled", true) // 手动对焦峰值显示 - var previewLimitedRange by bool("preview_limited_range", false) // 预览流为有限范围 YUV 时展开到全范围 var showHistogram by bool("show_histogram", true) var showGrid by bool("show_grid", false) // 网格线显示 var eyeFocusEnabled by bool("eye_focus_enabled", false) // MediaPipe 人眼对焦 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 9e2a2fed..a089c1f7 100644 --- a/app/src/main/java/com/hinnka/mycamera/lut/ColorPassProgram.kt +++ b/app/src/main/java/com/hinnka/mycamera/lut/ColorPassProgram.kt @@ -12,7 +12,6 @@ internal data class ColorPassLocations( val uLutTextureLocation: Int, val uNightToneTextureLocation: Int, val uNightWhitePointLocation: Int, - val uPreviewLimitedRangeLocation: Int, val uLutSizeLocation: Int, val uLutIntensityLocation: Int, val uLutEnabledLocation: Int, @@ -179,7 +178,6 @@ internal class PreviewColorProgramCache { uCurveTextureLocation = GLES30.glGetUniformLocation(program, "uCurveTexture"), uNightToneTextureLocation = GLES30.glGetUniformLocation(program, "uNightToneTexture"), uNightWhitePointLocation = GLES30.glGetUniformLocation(program, "uNightWhitePoint"), - uPreviewLimitedRangeLocation = GLES30.glGetUniformLocation(program, "uPreviewLimitedRange"), uCurveEnabledLocation = GLES30.glGetUniformLocation(program, "uCurveEnabled"), uPreviewBlurLocation = GLES30.glGetUniformLocation(program, "uPreviewBlur"), uPreviewClarityLocation = GLES30.glGetUniformLocation(program, "uPreviewClarity"), 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 2440fa85..54a1483c 100644 --- a/app/src/main/java/com/hinnka/mycamera/lut/LutRenderer.kt +++ b/app/src/main/java/com/hinnka/mycamera/lut/LutRenderer.kt @@ -15,6 +15,8 @@ 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.camera.PreviewYuvFrameChannel import com.hinnka.mycamera.stabilization.DEFAULT_VIDEO_STABILIZATION_LOOKAHEAD import com.hinnka.mycamera.stabilization.RealtimeStabilizationCoordinator import com.hinnka.mycamera.stabilization.StabilizationUseCase @@ -78,6 +80,9 @@ class LutRenderer(context: Context) : GLSurfaceView.Renderer { private val enginePreview = RawEnginePreviewGl() private val mgcEisHardwareBufferRenderer = MgcEisHardwareBufferRenderer(TAG) private val mgcEisYuvRenderer = MgcEisYuvRenderer(TAG) + private val previewYuvRenderer = PreviewYuvRenderer(TAG) + private var previewYuvChannel: PreviewYuvFrameChannel? = null + private val previewYuvMatrix = FloatArray(16).apply { Matrix.setIdentityM(this, 0) } private data class PreviewCaptureRequest( val width: Int, @@ -254,9 +259,6 @@ class LutRenderer(context: Context) : GLSurfaceView.Renderer { // 相机 SurfaceTexture private var surfaceTexture: SurfaceTexture? = null - /** Expands a limited-range preview stream to full range ([PreviewSignalRange]). */ - @Volatile - var previewLimitedRange: Boolean = false private val frameAvailable = AtomicBoolean(false) private var stabilizationCoordinator: RealtimeStabilizationCoordinator? = null @Volatile @@ -624,6 +626,7 @@ class LutRenderer(context: Context) : GLSurfaceView.Renderer { enginePreview.reset() mgcEisHardwareBufferRenderer.resetAfterContextLoss() mgcEisYuvRenderer.resetAfterContextLoss() + previewYuvRenderer.resetAfterContextLoss() cameraTextureId = 0 currentCameraTextureId = 0 currentCameraTextureSource = PreviewColorTextureSource.EXTERNAL_OES @@ -869,7 +872,6 @@ class LutRenderer(context: Context) : GLSurfaceView.Renderer { enableVideoLog: Boolean, toneBaseOnly: Boolean = false, nightVisionTone: Boolean = false, - expandRange: Boolean = false, ) { val shadowsHighlightsActive = ShadowsHighlightsShader.isActive(params.highlights, params.shadows) @@ -896,7 +898,6 @@ class LutRenderer(context: Context) : GLSurfaceView.Renderer { enableVideoLog = enableVideoLog, toneBaseOnly = true, nightVisionTone = nightVisionTone, - expandRange = expandRange, ) toneBase.buildLevels(::drawSimpleQuad) } @@ -907,7 +908,6 @@ class LutRenderer(context: Context) : GLSurfaceView.Renderer { sourceTextureId = sourceTextureId, sourceWidth = if (oesSource) previewWidth else width, sourceHeight = if (oesSource) previewHeight else height, - limitedRange = expandRange, drawQuad = ::drawSimpleQuad, ) } else { @@ -920,7 +920,6 @@ class LutRenderer(context: Context) : GLSurfaceView.Renderer { } GLES30.glUseProgram(locations.programId) GLES30.glUniform1i(locations.uToneBaseOnlyLocation, if (toneBaseOnly) 1 else 0) - GLES30.glUniform1i(locations.uPreviewLimitedRangeLocation, if (expandRange) 1 else 0) if (locations.previewBlur) { GLES30.glActiveTexture(GLES30.GL_TEXTURE0 + PreviewLiteEffectsGl.TEXTURE_UNIT) GLES30.glBindTexture(GLES30.GL_TEXTURE_2D, previewBlurTextureId) @@ -1150,6 +1149,20 @@ class LutRenderer(context: Context) : GLSurfaceView.Renderer { } val oesFrameUpdated = frameAvailable.getAndSet(false) && acquireLatestCameraFrame() var cameraFrameUpdated = oesFrameUpdated + 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. + 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 + } + } if (delayedStabilizationEnabled) { val session = stabilizationSession @@ -1194,7 +1207,7 @@ class LutRenderer(context: Context) : GLSurfaceView.Renderer { GLES30.glClear(GLES30.GL_COLOR_BUFFER_BIT) return } - } else if (cameraFrameUpdated) { + } else if (oesFrameUpdated && !yuvFrameUpdated) { useCurrentOesFrame() } @@ -1438,6 +1451,34 @@ 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 { + val timestampNs = frame.timestampNs + val textureId = previewYuvRenderer.render(frame) + if (textureId == 0) return false + val matrix = resolvePreviewYuvPresentationMatrix(sensorOrientation, lensFacing == 0) ?: run { + PLog.w(TAG, "Preview YUV frame has non-cardinal sensor orientation $sensorOrientation") + return false + } + System.arraycopy(matrix, 0, previewYuvMatrix, 0, previewYuvMatrix.size) + currentCameraTextureSource = PreviewColorTextureSource.TEXTURE_2D + currentCameraTextureTarget = GLES30.GL_TEXTURE_2D + currentCameraTextureId = textureId + currentCameraTextureMatrix = previewYuvMatrix + currentFrameTimestampNs = timestampNs + return true + } + + fun setPreviewYuvChannel(channel: PreviewYuvFrameChannel?) { + if (previewYuvChannel === channel) return + previewYuvChannel?.let { previous -> + previous.onFrameAvailable = null + previous.take()?.close() + } + previewYuvChannel = channel + channel?.onFrameAvailable = { onRequestRender?.invoke() } + } + private fun useCurrentOesFrame() { currentCameraTextureSource = PreviewColorTextureSource.EXTERNAL_OES currentCameraTextureTarget = GLES11Ext.GL_TEXTURE_EXTERNAL_OES @@ -1529,7 +1570,6 @@ class LutRenderer(context: Context) : GLSurfaceView.Renderer { suppressNightVisionTone: Boolean = false, ) { val plan = if (suppressCameraEngine) null else enginePreviewPlan - val expandRange = previewLimitedRange val nightVisionTone = !suppressNightVisionTone && nightVisionEnabled && nightToneActive && nightToneTextureId != 0 if (plan != null && !enginePreview.prepare(plan)) return @@ -1597,7 +1637,6 @@ class LutRenderer(context: Context) : GLSurfaceView.Renderer { curveEnabled = layerCurveEnabled, enableVideoLog = enableVideoLog, nightVisionTone = nightVisionTone, - expandRange = expandRange, ) // 测光和直方图(按需) @@ -3502,6 +3541,8 @@ class LutRenderer(context: Context) : GLSurfaceView.Renderer { basicToneTextures.release() mgcEisHardwareBufferRenderer.release() mgcEisYuvRenderer.release() + previewYuvChannel?.take()?.close() + previewYuvRenderer.release() // 删除程序 colorProgramCache.release() enginePreview.release() 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 d62208fb..1a6ed72b 100644 --- a/app/src/main/java/com/hinnka/mycamera/lut/PreviewColorShader.kt +++ b/app/src/main/java/com/hinnka/mycamera/lut/PreviewColorShader.kt @@ -96,7 +96,6 @@ internal object PreviewColorShader { ${PreviewColorShaderModules.SANITIZE} ${BasicToneLutShader.GLSL} - ${PreviewSignalRange.GLSL} ${if (variant.includeNightVisionTone) NightVisionToneGl.GLSL else ""} float getLuma(vec3 color) { @@ -121,7 +120,6 @@ internal object PreviewColorShader { ${if (variant.includeEnginePreview) RawEnginePreviewGl.SAMPLING_GLSL else ""} vec4 samplePreviewSource(vec2 uv) { vec4 sampled = texture(uCameraTexture, uv); - sampled.rgb = expandPreviewRange(sampled.rgb); ${if (variant.includeEnginePreview) "sampled.rgb = sampleEnginePreview(sampled.rgb);" else ""} return sampled; } diff --git a/app/src/main/java/com/hinnka/mycamera/lut/PreviewLiteEffectsGl.kt b/app/src/main/java/com/hinnka/mycamera/lut/PreviewLiteEffectsGl.kt index 798df127..b692dbf1 100644 --- a/app/src/main/java/com/hinnka/mycamera/lut/PreviewLiteEffectsGl.kt +++ b/app/src/main/java/com/hinnka/mycamera/lut/PreviewLiteEffectsGl.kt @@ -29,7 +29,6 @@ internal class PreviewLiteEffectsGl(private val tag: String) { sourceTextureId: Int, sourceWidth: Int, sourceHeight: Int, - limitedRange: Boolean, drawQuad: (Int) -> Unit, ): Int { val program = ensureProgram(sourceTarget) @@ -43,7 +42,6 @@ internal class PreviewLiteEffectsGl(private val tag: String) { GLES30.glActiveTexture(GLES30.GL_TEXTURE0) GLES30.glBindTexture(sourceTarget, sourceTextureId) GLES30.glUniform1i(GLES30.glGetUniformLocation(program, "uSource"), 0) - GLES30.glUniform1i(GLES30.glGetUniformLocation(program, "uPreviewLimitedRange"), if (limitedRange) 1 else 0) GLES30.glUniform2f( GLES30.glGetUniformLocation(program, "uSourceTexel"), 1f / max(1, sourceWidth), @@ -142,14 +140,13 @@ internal class PreviewLiteEffectsGl(private val tag: String) { out vec4 fragColor; uniform ${if (oes) "samplerExternalOES" else "sampler2D"} uSource; uniform vec2 uSourceTexel; - ${PreviewSignalRange.GLSL} void main() { vec2 d = uSourceTexel; vec3 color = texture(uSource, vTexCoord + vec2(-d.x, -d.y)).rgb; color += texture(uSource, vTexCoord + vec2(d.x, -d.y)).rgb; color += texture(uSource, vTexCoord + vec2(-d.x, d.y)).rgb; color += texture(uSource, vTexCoord + vec2(d.x, d.y)).rgb; - color = expandPreviewRange(clamp(color * 0.25, 0.0, 1.0)); + color = clamp(color * 0.25, 0.0, 1.0); float y = dot(color, vec3(0.299, 0.587, 0.114)); fragColor = vec4(color, clamp((y - $BLOOM_THRESHOLD) / (1.0 - $BLOOM_THRESHOLD), 0.0, 1.0)); } diff --git a/app/src/main/java/com/hinnka/mycamera/lut/PreviewSignalRange.kt b/app/src/main/java/com/hinnka/mycamera/lut/PreviewSignalRange.kt deleted file mode 100644 index 9fd9862c..00000000 --- a/app/src/main/java/com/hinnka/mycamera/lut/PreviewSignalRange.kt +++ /dev/null @@ -1,29 +0,0 @@ -package com.hinnka.mycamera.lut - -/** - * Limited-range correction for the camera preview stream. - * - * The preview buffer format is implementation defined. Some HALs (e.g. Xiaomi 11) emit limited - * range YCbCr (Y 16..235) with an UNKNOWN dataspace, and the GPU driver converts it to RGB as - * full range: lifted blacks, 235 whites, low contrast, while the capture ImageReader stream - * (JFIF, full range) is correct. The range is not reported reliably, so the user enables the - * correction in settings. - */ -internal object PreviewSignalRange { - /** - * `uniform bool uPreviewLimitedRange` and `vec3 expandPreviewRange(vec3)`. Inverts the - * driver's BT.601 full-range matrix to recover Y and chroma, then rescales them with the - * limited-range spans (Y 219, chroma 224) back into full range. - */ - const val GLSL = """ - uniform bool uPreviewLimitedRange; - - vec3 expandPreviewRange(vec3 color) { - if (!uPreviewLimitedRange) return color; - float y = dot(color, vec3(0.299, 0.587, 0.114)); - vec3 chroma = color - vec3(y); - vec3 expanded = vec3((y - 16.0 / 255.0) * (255.0 / 219.0)) + chroma * (255.0 / 224.0); - return clamp(expanded, 0.0, 1.0); - } - """ -} diff --git a/app/src/main/java/com/hinnka/mycamera/lut/PreviewYuvRenderer.kt b/app/src/main/java/com/hinnka/mycamera/lut/PreviewYuvRenderer.kt new file mode 100644 index 00000000..333f489f --- /dev/null +++ b/app/src/main/java/com/hinnka/mycamera/lut/PreviewYuvRenderer.kt @@ -0,0 +1,486 @@ +package com.hinnka.mycamera.lut + +import android.hardware.DataSpace +import android.media.Image +import android.opengl.EGL14 +import android.opengl.EGL15 +import android.opengl.GLES11Ext +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 +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. + */ +internal class PreviewYuvRenderer(private val tag: String) { + private enum class Path { RAW_YUV, DRIVER_RGB, 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 + private var activePath: Path? = null + + private var externalTextureId = 0 + private val planeTextureIds = IntArray(3) + private val planeWidths = IntArray(3) + private var planeHeight = 0 + private var outputTextureId = 0 + private var outputFramebufferId = 0 + private var outputWidth = 0 + private var outputHeight = 0 + private var quadBufferId = 0 + + 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 { + 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) + 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}") + return 0 + } finally { + frame.close() + } + } + + private fun drawImported(image: Image): Boolean { + 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") + try { + if (externalTextureId == 0) externalTextureId = GlUtils.createOESTexture() + 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") + beginDraw(program) + GLES30.glActiveTexture(GLES30.GL_TEXTURE0) + GLES30.glBindTexture(GLES11Ext.GL_TEXTURE_EXTERNAL_OES, externalTextureId) + GLES30.glUniform1i(program.samplers[0], 0) + drawQuad(program) + // The camera recycles the buffer once the Image is closed; sampling must complete first. + awaitGpu() + GLES30.glBindTexture(GLES11Ext.GL_TEXTURE_EXTERNAL_OES, 0) + endDraw() + reportPath(if (rawYuv) Path.RAW_YUV else Path.DRIVER_RGB) + return true + } finally { + GlesHardwareBufferImage.destroy(handle) + } + } + + private fun drawPlanes(image: Image): Boolean { + if (image.planes.size < 3) return false + val chromaWidth = (image.width + 1) / 2 + val chromaHeight = (image.height + 1) / 2 + val widths = intArrayOf( + image.width, + (chromaWidth - 1) * image.planes[1].pixelStride + 1, + (chromaWidth - 1) * image.planes[2].pixelStride + 1, + ) + if (!ensurePlaneTextures(widths, image.height, chromaHeight)) return false + for (index in 0..2) { + val planeHeightValue = if (index == 0) image.height else chromaHeight + if (!uploadPlane(image.planes[index], planeTextureIds[index], widths[index], planeHeightValue)) { + return false + } + } + val program = planeProgram ?: buildProgram(PLANE_FRAGMENT_SHADER)?.also { planeProgram = it } + ?: return false + beginDraw(program) + for (index in 0..2) { + GLES30.glActiveTexture(GLES30.GL_TEXTURE0 + index) + GLES30.glBindTexture(GLES30.GL_TEXTURE_2D, planeTextureIds[index]) + GLES30.glUniform1i(program.samplers[index], index) + } + GLES30.glUniform2i(program.imageSizeLocation, image.width, image.height) + GLES30.glUniform2i(program.chromaStepLocation, image.planes[1].pixelStride, image.planes[2].pixelStride) + drawQuad(program) + for (index in 2 downTo 0) { + GLES30.glActiveTexture(GLES30.GL_TEXTURE0 + index) + GLES30.glBindTexture(GLES30.GL_TEXTURE_2D, 0) + } + endDraw() + reportPath(Path.PLANES) + return true + } + + private fun beginDraw(program: Program) { + GLES30.glBindFramebuffer(GLES30.GL_FRAMEBUFFER, outputFramebufferId) + GLES30.glViewport(0, 0, outputWidth, outputHeight) + GLES30.glDisable(GLES30.GL_BLEND) + GLES30.glUseProgram(program.id) + GLES30.glUniformMatrix3fv(program.conversionLocation, 1, false, conversion, 0) + GLES30.glUniform3fv(program.offsetLocation, 1, offset, 0) + } + + private fun endDraw() { + GLES30.glBindFramebuffer(GLES30.GL_FRAMEBUFFER, 0) + GLES31.glMemoryBarrier(GLES31.GL_FRAMEBUFFER_BARRIER_BIT or GLES31.GL_TEXTURE_FETCH_BARRIER_BIT) + GLES30.glActiveTexture(GLES30.GL_TEXTURE0) + } + + private fun drawQuad(program: Program) { + GLES30.glBindBuffer(GLES30.GL_ARRAY_BUFFER, quadBufferId) + GLES30.glEnableVertexAttribArray(program.positionLocation) + GLES30.glVertexAttribPointer(program.positionLocation, 2, GLES30.GL_FLOAT, false, 16, 0) + GLES30.glEnableVertexAttribArray(program.texCoordLocation) + GLES30.glVertexAttribPointer(program.texCoordLocation, 2, GLES30.GL_FLOAT, false, 16, 8) + GLES30.glDrawArrays(GLES30.GL_TRIANGLE_STRIP, 0, 4) + GLES30.glDisableVertexAttribArray(program.positionLocation) + GLES30.glDisableVertexAttribArray(program.texCoordLocation) + GLES30.glBindBuffer(GLES30.GL_ARRAY_BUFFER, 0) + } + + /** + * Fills [conversion] and [offset] so that rgb = conversion * (yuv - offset) for normalized + * 8-bit samples. Camera2 YUV_420_888 is JFIF (BT.601 full range) when the dataspace is absent. + */ + private fun resolveConversion(dataSpace: Int) { + var kr = 0.299f + var kb = 0.114f + var limited = false + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU && dataSpace != 0) { + when (DataSpace.getStandard(dataSpace)) { + DataSpace.STANDARD_BT709 -> { kr = 0.2126f; kb = 0.0722f } + DataSpace.STANDARD_BT2020, + DataSpace.STANDARD_BT2020_CONSTANT_LUMINANCE -> { kr = 0.2627f; kb = 0.0593f } + } + limited = DataSpace.getRange(dataSpace) == DataSpace.RANGE_LIMITED + } + val kg = 1f - kr - kb + val yScale = if (limited) 255f / 219f else 1f + val cScale = if (limited) 255f / 224f else 1f + val crToR = 2f * (1f - kr) * cScale + val cbToB = 2f * (1f - kb) * cScale + val cbToG = -kb * 2f * (1f - kb) / kg * cScale + val crToG = -kr * 2f * (1f - kr) / kg * cScale + // Column-major: columns are the Y, Cb and Cr contributions. + conversion[0] = yScale; conversion[1] = yScale; conversion[2] = yScale + conversion[3] = 0f; conversion[4] = cbToG; conversion[5] = cbToB + conversion[6] = crToR; conversion[7] = crToG; conversion[8] = 0f + offset[0] = if (limited) 16f / 255f else 0f + offset[1] = 128f / 255f + offset[2] = 128f / 255f + } + + private fun ensureTarget(width: Int, height: Int): Boolean { + if (outputTextureId != 0 && outputWidth == width && outputHeight == height) return true + releaseTarget() + if (quadBufferId == 0) { + val quad = ByteBuffer.allocateDirect(QUAD.size * 4).order(ByteOrder.nativeOrder()) + .asFloatBuffer().put(QUAD).also { it.position(0) } + val ids = IntArray(1) + GLES30.glGenBuffers(1, ids, 0) + quadBufferId = ids[0] + GLES30.glBindBuffer(GLES30.GL_ARRAY_BUFFER, quadBufferId) + GLES30.glBufferData(GLES30.GL_ARRAY_BUFFER, QUAD.size * 4, quad, GLES30.GL_STATIC_DRAW) + GLES30.glBindBuffer(GLES30.GL_ARRAY_BUFFER, 0) + } + outputTextureId = createTexture(width, height, GLES30.GL_RGBA8, GLES30.GL_RGBA) + 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 (!complete) { + PLog.e(tag, "Cannot allocate preview YUV output ${width}x$height") + releaseTarget() + return false + } + outputWidth = width + outputHeight = height + return true + } + + private fun ensurePlaneTextures(widths: IntArray, height: Int, chromaHeight: Int): Boolean { + if (planeTextureIds[0] != 0 && widths.contentEquals(planeWidths) && planeHeight == height) return true + releasePlaneTextures() + for (index in 0..2) { + val textureHeight = if (index == 0) height else chromaHeight + planeTextureIds[index] = createTexture(widths[index], textureHeight, GLES30.GL_R8, GLES30.GL_RED) + planeWidths[index] = widths[index] + } + planeHeight = height + return planeTextureIds.all { it != 0 } + } + + private fun uploadPlane(plane: Image.Plane, textureId: Int, width: Int, height: Int): Boolean { + val buffer = plane.buffer.duplicate().apply { position(0) } + val required = (height - 1).toLong() * plane.rowStride + width + if (plane.rowStride < width || required > buffer.limit()) { + PLog.w(tag, "Invalid preview YUV plane row=${plane.rowStride} pixel=${plane.pixelStride}") + return false + } + GLES30.glBindTexture(GLES30.GL_TEXTURE_2D, textureId) + GLES30.glPixelStorei(GLES30.GL_UNPACK_ALIGNMENT, 1) + GLES30.glPixelStorei(GLES30.GL_UNPACK_ROW_LENGTH, plane.rowStride) + GLES30.glTexSubImage2D(GLES30.GL_TEXTURE_2D, 0, 0, 0, width, height, 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) + return true + } + + private fun createTexture(width: Int, height: Int, internalFormat: Int, format: 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, internalFormat, width, height, 0, format, GLES30.GL_UNSIGNED_BYTE, null) + GLES30.glBindTexture(GLES30.GL_TEXTURE_2D, 0) + return ids[0] + } + + /** EGL fence before the Image returns to Camera2; glFinish only when no fence can be created. */ + private fun awaitGpu() { + val display = EGL14.eglGetCurrentDisplay() + val fence = if (display == EGL14.EGL_NO_DISPLAY) { + EGL15.EGL_NO_SYNC + } else { + EGL15.eglCreateSync(display, EGL15.EGL_SYNC_FENCE, longArrayOf(EGL14.EGL_NONE.toLong()), 0) + } + if (fence == EGL15.EGL_NO_SYNC) { + GLES30.glFinish() + return + } + try { + val result = EGL15.eglClientWaitSync(display, fence, EGL15.EGL_SYNC_FLUSH_COMMANDS_BIT, EGL15.EGL_FOREVER) + if (result != EGL15.EGL_CONDITION_SATISFIED) GLES30.glFinish() + } finally { + EGL15.eglDestroySync(display, fence) + } + } + + private fun queryYuvTarget(): Boolean { + val count = IntArray(1) + GLES30.glGetIntegerv(GLES30.GL_NUM_EXTENSIONS, count, 0) + return (0 until count[0]).any { GLES30.glGetStringi(GLES30.GL_EXTENSIONS, it) == "GL_EXT_YUV_target" } + } + + private fun disableImport(reason: String): Boolean { + importDisabled = true + PLog.w(tag, "Preview YUV HardwareBuffer import unavailable ($reason); using plane upload") + return false + } + + private fun reportPath(path: Path) { + if (activePath == path) return + activePath = path + PLog.i(tag, "Preview YUV conversion path: $path ${outputWidth}x$outputHeight") + } + + private fun buildProgram(fragmentSource: String): Program? { + val vertexShader = GlUtils.compileShader(GLES30.GL_VERTEX_SHADER, VERTEX_SHADER) + val fragmentShader = GlUtils.compileShader(GLES30.GL_FRAGMENT_SHADER, fragmentSource) + if (vertexShader == 0 || fragmentShader == 0) { + if (vertexShader != 0) GLES30.glDeleteShader(vertexShader) + if (fragmentShader != 0) GLES30.glDeleteShader(fragmentShader) + return null + } + val id = GlUtils.linkProgram(vertexShader, fragmentShader) + GLES30.glDeleteShader(vertexShader) + GLES30.glDeleteShader(fragmentShader) + if (id == 0) return null + return Program( + id = id, + positionLocation = GLES30.glGetAttribLocation(id, "aPosition"), + texCoordLocation = GLES30.glGetAttribLocation(id, "aTexCoord"), + samplers = intArrayOf( + GLES30.glGetUniformLocation(id, "uInput"), + GLES30.glGetUniformLocation(id, "uCb"), + GLES30.glGetUniformLocation(id, "uCr"), + ), + conversionLocation = GLES30.glGetUniformLocation(id, "uYuvToRgb"), + offsetLocation = GLES30.glGetUniformLocation(id, "uYuvOffset"), + imageSizeLocation = GLES30.glGetUniformLocation(id, "uImageSize"), + chromaStepLocation = GLES30.glGetUniformLocation(id, "uChromaStep"), + ) + } + + private fun releaseTarget() { + if (outputTextureId != 0) GLES30.glDeleteTextures(1, intArrayOf(outputTextureId), 0) + if (outputFramebufferId != 0) GLES30.glDeleteFramebuffers(1, intArrayOf(outputFramebufferId), 0) + outputTextureId = 0 + outputFramebufferId = 0 + outputWidth = 0 + outputHeight = 0 + } + + private fun releasePlaneTextures() { + val ids = planeTextureIds.filter { it != 0 }.toIntArray() + if (ids.isNotEmpty()) GLES30.glDeleteTextures(ids.size, ids, 0) + planeTextureIds.fill(0) + planeWidths.fill(0) + planeHeight = 0 + } + + /** Must run on the GL thread with the owning context current. */ + fun release() { + releaseTarget() + 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) } + resetAfterContextLoss() + } + + /** Forgets GL names without deleting them; the context that owned them is gone. */ + fun resetAfterContextLoss() { + y2yProgram = null + driverProgram = null + planeProgram = null + yuvTargetSupported = null + activePath = null + externalTextureId = 0 + planeTextureIds.fill(0) + planeWidths.fill(0) + planeHeight = 0 + outputTextureId = 0 + outputFramebufferId = 0 + outputWidth = 0 + outputHeight = 0 + quadBufferId = 0 + } + + private class Program( + val id: Int, + val positionLocation: Int, + val texCoordLocation: Int, + val samplers: IntArray, + val conversionLocation: Int, + val offsetLocation: Int, + val imageSizeLocation: Int, + val chromaStepLocation: Int, + ) + + private companion object { + // Triangle strip: clip position, then source texture coordinate. Buffer row 0 lands on + // the top framebuffer row, matching the MGC output that the presentation matrix targets. + val QUAD = floatArrayOf( + -1f, -1f, 0f, 1f, + 1f, -1f, 1f, 1f, + -1f, 1f, 0f, 0f, + 1f, 1f, 1f, 0f, + ) + + val VERTEX_SHADER = """ + #version 300 es + in vec4 aPosition; + in vec2 aTexCoord; + out vec2 vTexCoord; + void main() { + gl_Position = aPosition; + vTexCoord = aTexCoord; + } + """.trimIndent() + + val Y2Y_FRAGMENT_SHADER = """ + #version 300 es + #extension GL_EXT_YUV_target : require + precision highp float; + uniform __samplerExternal2DY2YEXT uInput; + uniform mat3 uYuvToRgb; + uniform vec3 uYuvOffset; + in vec2 vTexCoord; + out vec4 fragColor; + void main() { + vec3 yuv = texture(uInput, vTexCoord).rgb; + fragColor = vec4(clamp(uYuvToRgb * (yuv - uYuvOffset), 0.0, 1.0), 1.0); + } + """.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; + uniform highp sampler2D uInput; + uniform highp sampler2D uCb; + uniform highp sampler2D uCr; + uniform ivec2 uImageSize; + uniform ivec2 uChromaStep; + uniform mat3 uYuvToRgb; + uniform vec3 uYuvOffset; + in vec2 vTexCoord; + out vec4 fragColor; + void main() { + ivec2 p = clamp(ivec2(vTexCoord * vec2(uImageSize)), ivec2(0), uImageSize - 1); + ivec2 c = p / 2; + vec3 yuv = vec3( + texelFetch(uInput, p, 0).r, + texelFetch(uCb, ivec2(c.x * uChromaStep.x, c.y), 0).r, + texelFetch(uCr, ivec2(c.x * uChromaStep.y, c.y), 0).r + ); + fragColor = vec4(clamp(uYuvToRgb * (yuv - uYuvOffset), 0.0, 1.0), 1.0); + } + """.trimIndent() + } +} + +/** + * Maps natural-orientation output coordinates to the camera-layout YUV texture: the sensor + * rotation of [resolveMgcEisPresentationMatrix], plus the horizontal mirror Camera2 applies to + * front-camera preview streams. + */ +internal fun resolvePreviewYuvPresentationMatrix( + sensorOrientationDegrees: Int, + frontFacing: Boolean, +): FloatArray? { + val rotation = resolveMgcEisPresentationMatrix(sensorOrientationDegrees) ?: return null + if (!frontFacing) return rotation + val mirror = FloatArray(16).also { + Matrix.setIdentityM(it, 0) + it[0] = -1f + it[12] = 1f + } + return FloatArray(16).also { Matrix.multiplyMM(it, 0, rotation, 0, mirror, 0) } +} 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 d4c8b151..3910a18a 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 @@ -1,5 +1,6 @@ package com.hinnka.mycamera.ui.camera +import com.hinnka.mycamera.camera.PreviewYuvFrameChannel import android.content.Context import android.graphics.Bitmap import android.graphics.PointF @@ -170,6 +171,17 @@ class CameraGLSurfaceView @JvmOverloads constructor( } } + private var currentPreviewYuvChannel: PreviewYuvFrameChannel? = null + + fun setPreviewYuvChannel(channel: PreviewYuvFrameChannel?) { + if (currentPreviewYuvChannel === channel) return + currentPreviewYuvChannel = channel + queueEvent { + renderer.setPreviewYuvChannel(channel) + requestRender() + } + } + fun setStabilizationCoordinator(coordinator: RealtimeStabilizationCoordinator?) { if (currentStabilizationCoordinator === coordinator) return currentStabilizationCoordinator = coordinator @@ -219,13 +231,6 @@ class CameraGLSurfaceView @JvmOverloads constructor( renderer.nightVisionEnabled = enabled } - /** Expands a limited-range preview stream to full range. */ - fun setPreviewLimitedRange(enabled: Boolean) { - if (renderer.previewLimitedRange == enabled) return - renderer.previewLimitedRange = enabled - requestRender() - } - /** * 设置 LUT * diff --git a/app/src/main/java/com/hinnka/mycamera/ui/camera/CameraPreviewGL.kt b/app/src/main/java/com/hinnka/mycamera/ui/camera/CameraPreviewGL.kt index 43e0f235..0c1f5f5b 100644 --- a/app/src/main/java/com/hinnka/mycamera/ui/camera/CameraPreviewGL.kt +++ b/app/src/main/java/com/hinnka/mycamera/ui/camera/CameraPreviewGL.kt @@ -1,5 +1,6 @@ package com.hinnka.mycamera.ui.camera +import com.hinnka.mycamera.camera.PreviewYuvFrameChannel import android.graphics.SurfaceTexture import android.util.Size import androidx.compose.foundation.background @@ -76,12 +77,12 @@ fun CameraPreviewGL( livePhotoRecorder: LivePhotoRecorder? = null, videoLogProfile: VideoLogProfile = VideoLogProfile.OFF, nightVisionEnabled: Boolean = false, - previewLimitedRange: Boolean = false, isEyeFocusBusy: Boolean = false, onGLSurfaceViewReady: ((CameraGLSurfaceView) -> Unit)? = null, isAutoFocus: Boolean = true, focusPeakingEnabled: Boolean = true, stabilizationCoordinator: RealtimeStabilizationCoordinator? = null, + previewYuvChannel: PreviewYuvFrameChannel? = null, stabilizationInputSize: Size = previewSize, photoPreviewStabilizationEnabled: Boolean = false, videoPreviewStabilizationEnabled: Boolean = false, @@ -251,6 +252,7 @@ fun CameraPreviewGL( stabilizationInputSize.height, ) glSurfaceView.setStabilizationCoordinator(stabilizationCoordinator) + glSurfaceView.setPreviewYuvChannel(previewYuvChannel) val previewStabilizationUseCase = when { captureMode == CaptureMode.VIDEO && videoPreviewStabilizationEnabled -> StabilizationUseCase.VIDEO @@ -331,7 +333,6 @@ fun CameraPreviewGL( glSurfaceView.setLivePhotoRecorder(livePhotoRecorder) glSurfaceView.setVideoLogProfile(videoLogProfile) glSurfaceView.setNightVisionEnabled(nightVisionEnabled) - glSurfaceView.setPreviewLimitedRange(previewLimitedRange) glSurfaceView.setAutoFocus(isAutoFocus) glSurfaceView.setFocusPeakingEnabled(focusPeakingEnabled) glSurfaceView.setEyeFocusBusy(isEyeFocusBusy) diff --git a/app/src/main/java/com/hinnka/mycamera/ui/camera/CameraScreen.kt b/app/src/main/java/com/hinnka/mycamera/ui/camera/CameraScreen.kt index dfb92a26..fc694f90 100644 --- a/app/src/main/java/com/hinnka/mycamera/ui/camera/CameraScreen.kt +++ b/app/src/main/java/com/hinnka/mycamera/ui/camera/CameraScreen.kt @@ -256,7 +256,6 @@ fun CameraScreen( val latestPhoto by galleryViewModel.latestPhoto.collectAsState() val showLevelIndicator by preferenceValue { it.showLevelIndicator } val focusPeakingEnabled by preferenceValue { it.focusPeakingEnabled } - val previewLimitedRange by preferenceValue { it.previewLimitedRange } val eyeFocusEnabled by preferenceValue { it.eyeFocusEnabled } val keepScreenOn by preferenceValue { it.keepScreenOn } val currentLutId by viewModel.currentLutId.collectAsState() @@ -1352,11 +1351,11 @@ fun CameraScreen( livePhotoRecorder = viewModel.livePhotoRecorder, videoLogProfile = state.videoConfig.logProfile, nightVisionEnabled = state.isNightVisionActive, - previewLimitedRange = previewLimitedRange, isEyeFocusBusy = viewModel.isEyeFocusBusy, isAutoFocus = state.isAutoFocus, focusPeakingEnabled = focusPeakingEnabled && !state.isHyperfocalFocusEnabled, stabilizationCoordinator = viewModel.realtimeStabilizationCoordinator, + previewYuvChannel = viewModel.previewYuvChannel, stabilizationInputSize = if ( state.captureMode == CaptureMode.VIDEO && state.videoConfig.stabilizationMode == diff --git a/app/src/main/java/com/hinnka/mycamera/ui/settings/SettingsScreen.kt b/app/src/main/java/com/hinnka/mycamera/ui/settings/SettingsScreen.kt index 95509817..497e97c3 100644 --- a/app/src/main/java/com/hinnka/mycamera/ui/settings/SettingsScreen.kt +++ b/app/src/main/java/com/hinnka/mycamera/ui/settings/SettingsScreen.kt @@ -330,7 +330,6 @@ fun SettingsScreen( val userPreferences by viewModel.userPreferences.collectAsState() var showLevelIndicator by rememberPreference(UserPreferences::showLevelIndicator) var focusPeakingEnabled by rememberPreference(UserPreferences::focusPeakingEnabled) - var previewLimitedRange by rememberPreference(UserPreferences::previewLimitedRange) val eyeFocusEnabled by preferenceValue { it.eyeFocusEnabled } var showGrid by rememberPreference(UserPreferences::showGrid) var shutterSoundEnabled by rememberPreference(UserPreferences::shutterSoundEnabled) @@ -1153,17 +1152,6 @@ fun SettingsScreen( modifier = Modifier.padding(vertical = 8.dp) ) - SwitchSettingItem( - title = stringResource(R.string.settings_preview_limited_range), - description = stringResource(R.string.settings_preview_limited_range_description), - checked = previewLimitedRange, - onCheckedChange = { previewLimitedRange = it } - ) - - HorizontalDivider( - color = Color.White.copy(alpha = 0.1f), - modifier = Modifier.padding(vertical = 8.dp) - ) SwitchSettingItem( title = stringResource( diff --git a/app/src/main/java/com/hinnka/mycamera/viewmodel/CameraViewModel.kt b/app/src/main/java/com/hinnka/mycamera/viewmodel/CameraViewModel.kt index 8e27a078..e2f9e29d 100644 --- a/app/src/main/java/com/hinnka/mycamera/viewmodel/CameraViewModel.kt +++ b/app/src/main/java/com/hinnka/mycamera/viewmodel/CameraViewModel.kt @@ -629,6 +629,7 @@ class CameraViewModel(application: Application) : AndroidViewModel(application) val state: StateFlow = cameraController.state val livePhotoRecorder get() = cameraController.livePhotoRecorder val realtimeStabilizationCoordinator get() = cameraController.realtimeStabilizationCoordinator + val previewYuvChannel get() = cameraController.previewYuvChannel val isAlgorithmicStabilizationSupported: Boolean get() = cameraController.realtimeStabilizationCoordinator.isGyroscopeAvailable diff --git a/app/src/main/res/values-b+zh+Hant/strings.xml b/app/src/main/res/values-b+zh+Hant/strings.xml index dbe277b5..52b7f2ef 100644 --- a/app/src/main/res/values-b+zh+Hant/strings.xml +++ b/app/src/main/res/values-b+zh+Hant/strings.xml @@ -1434,6 +1434,4 @@ 在相簿列表顯示評分 瀏覽時在背景為照片評分。 評分來自端側 CLIP 美學模型(LAION Aesthetic Predictor),以大規模人類審美評分訓練,反映大眾視覺偏好而非創作意圖,僅供參考。 - 修正預覽發灰 - 預覽偏灰、對比度低而成片正常時開啟。部分裝置的預覽訊號為有限範圍。 diff --git a/app/src/main/res/values-de/strings.xml b/app/src/main/res/values-de/strings.xml index d7fa7c03..65e832a8 100644 --- a/app/src/main/res/values-de/strings.xml +++ b/app/src/main/res/values-de/strings.xml @@ -487,6 +487,4 @@ %1$s J. Als Preset speichern - Blasse Vorschau korrigieren - Einschalten, wenn die Vorschau grau und kontrastarm wirkt, die Fotos aber normal sind. Manche Geräte liefern ein Vorschausignal mit begrenztem Bereich. diff --git a/app/src/main/res/values-fr/strings.xml b/app/src/main/res/values-fr/strings.xml index 5655326c..8c515b01 100644 --- a/app/src/main/res/values-fr/strings.xml +++ b/app/src/main/res/values-fr/strings.xml @@ -1472,6 +1472,4 @@ Afficher les scores dans la galerie Évalue les photos en arrière-plan pendant la navigation. Évalué par un modèle esthétique CLIP sur l\'appareil (LAION Aesthetic Predictor), entraîné sur un grand nombre de notes humaines. Il reflète l\'attrait visuel général plutôt que l\'intention artistique : à utiliser comme référence. - Corriger l\'aperçu délavé - À activer si l\'aperçu paraît gris et peu contrasté alors que les photos sont normales. Certains appareils fournissent un signal d\'aperçu à plage limitée. diff --git a/app/src/main/res/values-in/strings.xml b/app/src/main/res/values-in/strings.xml index 6fee3eca..e46e8c3c 100644 --- a/app/src/main/res/values-in/strings.xml +++ b/app/src/main/res/values-in/strings.xml @@ -487,6 +487,4 @@ %1$s thn Simpan sebagai preset - Perbaiki pratinjau pudar - Aktifkan jika pratinjau tampak abu-abu dan kontrasnya rendah, sedangkan foto normal. Beberapa perangkat mengeluarkan sinyal pratinjau rentang terbatas. diff --git a/app/src/main/res/values-ja/strings.xml b/app/src/main/res/values-ja/strings.xml index 77a10f00..5db13a9f 100644 --- a/app/src/main/res/values-ja/strings.xml +++ b/app/src/main/res/values-ja/strings.xml @@ -1327,6 +1327,4 @@ ギャラリーにスコアを表示 閲覧中にバックグラウンドで写真を評価します。 端末上の CLIP 美的モデル(LAION Aesthetic Predictor)による評価で、大規模な人間の評価データで学習されています。芸術的意図ではなく一般的な見た目の魅力を反映するため、参考としてご利用ください。 - プレビューの白っぽさを補正 - 写真は正常なのにプレビューが白っぽくコントラストが低い場合にオンにします。一部の端末はプレビュー信号が限定レンジです。 diff --git a/app/src/main/res/values-ko/strings.xml b/app/src/main/res/values-ko/strings.xml index c6e1b320..6160d6d7 100644 --- a/app/src/main/res/values-ko/strings.xml +++ b/app/src/main/res/values-ko/strings.xml @@ -488,6 +488,4 @@ %1$s년 프리셋으로 저장 - 흐린 미리보기 보정 - 사진은 정상인데 미리보기가 회색빛이고 대비가 낮으면 켜세요. 일부 기기는 제한 범위 미리보기 신호를 출력합니다. diff --git a/app/src/main/res/values-pt-rBR/strings.xml b/app/src/main/res/values-pt-rBR/strings.xml index a4112c0d..cf35274a 100644 --- a/app/src/main/res/values-pt-rBR/strings.xml +++ b/app/src/main/res/values-pt-rBR/strings.xml @@ -488,6 +488,4 @@ %1$s anos Salvar como predefinição - Corrigir prévia desbotada - Ative se a prévia parecer acinzentada e com pouco contraste enquanto as fotos ficam normais. Alguns aparelhos geram sinal de prévia em faixa limitada. diff --git a/app/src/main/res/values-th/strings.xml b/app/src/main/res/values-th/strings.xml index e0d96c0d..e127c238 100644 --- a/app/src/main/res/values-th/strings.xml +++ b/app/src/main/res/values-th/strings.xml @@ -1109,6 +1109,4 @@ แสดงคะแนนในแกลเลอรี ให้คะแนนรูปภาพในพื้นหลังขณะเลื่อนดู ให้คะแนนโดยโมเดลความสวยงาม CLIP บนอุปกรณ์ (LAION Aesthetic Predictor) ที่ฝึกจากคะแนนของมนุษย์จำนวนมาก สะท้อนความน่าดึงดูดทางสายตาโดยทั่วไป ไม่ใช่เจตนาทางศิลปะ ควรใช้เป็นข้อมูลอ้างอิงเท่านั้น - แก้พรีวิวซีดจาง - เปิดเมื่อพรีวิวดูซีดและคอนทราสต์ต่ำ แต่ภาพถ่ายปกติ อุปกรณ์บางรุ่นส่งสัญญาณพรีวิวแบบช่วงจำกัด diff --git a/app/src/main/res/values-zh-rCN/strings.xml b/app/src/main/res/values-zh-rCN/strings.xml index 5ac74840..a2355b7b 100644 --- a/app/src/main/res/values-zh-rCN/strings.xml +++ b/app/src/main/res/values-zh-rCN/strings.xml @@ -1490,6 +1490,4 @@ 在相册列表显示评分 浏览时在后台为照片评分。 评分来自端侧 CLIP 美学模型(LAION Aesthetic Predictor),基于大规模人类审美打分训练,反映大众视觉偏好而非创作意图,仅供参考。 - 修正预览发灰 - 预览偏灰、对比度低而成片正常时开启。部分设备的预览信号为有限范围。 diff --git a/app/src/main/res/values-zh-rHK/strings.xml b/app/src/main/res/values-zh-rHK/strings.xml index b179db84..c10e2173 100644 --- a/app/src/main/res/values-zh-rHK/strings.xml +++ b/app/src/main/res/values-zh-rHK/strings.xml @@ -1428,6 +1428,4 @@ 在相簿列表顯示評分 瀏覽時在背景為照片評分。 評分來自端側 CLIP 美學模型(LAION Aesthetic Predictor),以大規模人類審美評分訓練,反映大眾視覺偏好而非創作意圖,僅供參考。 - 修正預覽發灰 - 預覽偏灰、對比度低而成片正常時開啟。部分裝置的預覽訊號為有限範圍。 diff --git a/app/src/main/res/values-zh-rTW/strings.xml b/app/src/main/res/values-zh-rTW/strings.xml index dbe277b5..52b7f2ef 100644 --- a/app/src/main/res/values-zh-rTW/strings.xml +++ b/app/src/main/res/values-zh-rTW/strings.xml @@ -1434,6 +1434,4 @@ 在相簿列表顯示評分 瀏覽時在背景為照片評分。 評分來自端側 CLIP 美學模型(LAION Aesthetic Predictor),以大規模人類審美評分訓練,反映大眾視覺偏好而非創作意圖,僅供參考。 - 修正預覽發灰 - 預覽偏灰、對比度低而成片正常時開啟。部分裝置的預覽訊號為有限範圍。 diff --git a/app/src/main/res/values/strings.xml b/app/src/main/res/values/strings.xml index d86ae262..3b26d00e 100644 --- a/app/src/main/res/values/strings.xml +++ b/app/src/main/res/values/strings.xml @@ -1515,6 +1515,4 @@ Show scores in gallery Scores photos in the background as you browse. Scored by an on-device CLIP aesthetic model (LAION Aesthetic Predictor) trained on large-scale human ratings. It reflects broad visual appeal rather than artistic intent, so use it as a reference. - Fix Washed-out Preview - Turn on if the preview looks grey with weak contrast while photos look normal. Some devices output a limited-range preview signal.