feat: video record pipeline

This commit is contained in:
zhoubinjia committed 2026-07-31 18:21:54 +08:00
1 parent d9dbc1c0b4
commit 9de915f169
15 files changed
+1184 -336

No files matched your search

@@ -34,7 +34,10 @@ import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asStateFlow
import com.hinnka.mycamera.livephoto.LivePhotoRecorder
import com.hinnka.mycamera.lut.LutConfig
import com.hinnka.mycamera.lut.VideoColorEffectLayer
import com.hinnka.mycamera.model.SafeImage
import com.hinnka.mycamera.model.ColorRecipeParams
import com.hinnka.mycamera.utils.DeviceUtil
import com.hinnka.mycamera.utils.OrientationObserver
import com.hinnka.mycamera.video.CaptureMode
@@ -52,6 +55,7 @@ import com.hinnka.mycamera.video.VideoRecordingPath
import com.hinnka.mycamera.video.VideoResolutionPreset
import com.hinnka.mycamera.video.VideoRecordingState
import com.hinnka.mycamera.video.VideoStabilizationMode
import com.hinnka.mycamera.video.resolveSurfaceTextureVideoOrientationDegrees
import java.util.concurrent.ConcurrentHashMap
import java.util.concurrent.Executors
import java.util.concurrent.atomic.AtomicBoolean
@@ -1261,6 +1265,10 @@ class Camera2Controller(private val context: Context) {
} else {
PLog.e(TAG, "Preview session failed: $reason")
}
if (videoRecorder.isRecording()) {
videoRecorder.forceStop()
stopVideoRecordingTicker()
}
closeCameraDeviceSafely(cameraDevice, "preview session failure: $reason")
cameraDevice = null
clearCameraRuntimeState("preview session failure: $reason")
@@ -1979,6 +1987,11 @@ class Camera2Controller(private val context: Context) {
val surface = previewSurface ?: return
val captureMode = _state.value.captureMode
val reader = imageReader
val videoSurface = if (captureMode == CaptureMode.VIDEO) {
videoRecorder.cameraInputSurface
} else {
null
}
val sessionGeneration = ++previewSessionGeneration
pendingVendorSessionParameterRestart = false
val templateType = if (captureMode == CaptureMode.VIDEO) {
@@ -1991,12 +2004,14 @@ class Camera2Controller(private val context: Context) {
try {
previewRequestBuilder = device.createCaptureRequest(templateType).apply {
addTarget(surface)
videoSurface?.let(::addTarget)
// 应用所有相机参数(曝光、白平衡、闪光灯、变焦、色调映射)
applyBaseCameraSettings(this, isCapture = false)
}
val surfaces = mutableListOf(surface)
videoSurface?.let(surfaces::add)
if (captureMode == CaptureMode.PHOTO) {
val captureReader = reader ?: return
surfaces += captureReader.surface
@@ -2006,12 +2021,23 @@ class Camera2Controller(private val context: Context) {
val useHlgCapture = _state.value.useHlg10 && activeOutputPhysicalCameraId == null && !forceStandardSession
val sessionConfig = SessionConfiguration(
SessionConfiguration.SESSION_REGULAR,
surfaces.map { outputSurface ->
createOutputConfiguration(
surface = outputSurface,
useHlgCapture = useHlgCapture,
outputType = CameraOutputType.VIDEO_RECORD
buildList {
add(
createOutputConfiguration(
surface = surface,
useHlgCapture = useHlgCapture,
outputType = CameraOutputType.PREVIEW
)
)
videoSurface?.let { encoderSurface ->
add(
createOutputConfiguration(
surface = encoderSurface,
useHlgCapture = useHlgCapture,
outputType = CameraOutputType.VIDEO_RECORD
)
)
}
},
Executors.newSingleThreadExecutor(),
object : CameraCaptureSession.StateCallback() {
@@ -2481,6 +2507,11 @@ class Camera2Controller(private val context: Context) {
previewRequestBuilder?.let { builder ->
session.setRepeatingRequest(builder.build(), previewCallback, cameraHandler)
}
if (_state.value.captureMode == CaptureMode.VIDEO && videoRecorder.cameraInputSurface != null) {
if (videoRecorder.onCameraInputStarted()) {
startVideoRecordingTicker()
}
}
_state.value = _state.value.copy(isPreviewActive = true)
PLog.d(TAG, "Preview started")
@@ -5224,7 +5255,12 @@ class Camera2Controller(private val context: Context) {
}
fun setCaptureMode(mode: CaptureMode) {
if (_state.value.captureMode == mode || _state.value.videoRecordingState.isRecording) return
if (_state.value.captureMode == mode ||
_state.value.videoRecordingState.isRecording ||
_state.value.videoRecordingState.isProcessing
) {
return
}
val nextVideoConfig = if (mode == CaptureMode.VIDEO) {
_state.value.videoConfig
} else {
@@ -5372,8 +5408,17 @@ class Camera2Controller(private val context: Context) {
mirrorFrontCameraEnabled = enabled
}
fun startVideoRecording() {
if (_state.value.captureMode != CaptureMode.VIDEO || _state.value.videoRecordingState.isRecording) {
fun startVideoRecording(
creativeLutConfig: LutConfig? = null,
creativeRecipeParams: ColorRecipeParams? = null,
baselineLutConfig: LutConfig? = null,
baselineRecipeParams: ColorRecipeParams? = null,
orientationOffsetDegrees: Int = 0
) {
if (_state.value.captureMode != CaptureMode.VIDEO ||
_state.value.videoRecordingState.isRecording ||
_state.value.videoRecordingState.isProcessing
) {
return
}
@@ -5383,10 +5428,24 @@ class Camera2Controller(private val context: Context) {
val outputSize = _state.value.videoConfig.resolveOutputSize(
_state.value.videoCapabilities.openGatePortraitAspectRatio
)
val cameraInputSize = _state.value.videoCapabilities.previewSizesByResolution[
_state.value.videoConfig.resolution
] ?: _state.value.currentPreviewSize
val isFrontCamera = isCurrentCameraFrontFacing()
val shouldFlipEncodedFrame = isFrontCamera && !mirrorFrontCameraEnabled
val shouldFlipEncodedFrame = isFrontCamera && mirrorFrontCameraEnabled
val colorLayers = buildList {
if (!_state.value.videoConfig.logProfile.isEnabled &&
(baselineLutConfig != null || baselineRecipeParams?.isDefault() == false)
) {
add(VideoColorEffectLayer(baselineLutConfig, baselineRecipeParams))
}
if (creativeLutConfig != null || creativeRecipeParams?.isDefault() == false) {
add(VideoColorEffectLayer(creativeLutConfig, creativeRecipeParams))
}
}
val started = videoRecorder.startRecording(
size = outputSize,
cameraInputSize = cameraInputSize,
fps = _state.value.videoConfig.fps.fps,
bitrateMbps = _state.value.videoConfig.bitrate.bitrateMbps,
codecMime = _state.value.videoConfig.codec.mimeType,
@@ -5394,7 +5453,9 @@ class Camera2Controller(private val context: Context) {
logProfile = _state.value.videoConfig.logProfile,
hasActiveLut = _state.value.lutEnabled && _state.value.currentLutName != null
),
orientationHintDegrees = resolveVideoOrientationHintDegrees(),
colorLayers = colorLayers,
hlgInput = _state.value.useHlg10,
orientationHintDegrees = resolveDedicatedVideoOrientationHintDegrees(orientationOffsetDegrees),
flipEncodedFrame = shouldFlipEncodedFrame,
recordingPath = _state.value.videoConfig.recordingPath,
recordingTreeUri = _state.value.videoConfig.recordingTreeUri,
@@ -5404,8 +5465,14 @@ class Camera2Controller(private val context: Context) {
}
) { uri ->
PLog.i(TAG, "Video saved: $uri")
_state.value = _state.value.copy(videoRecordingState = VideoRecordingState())
onVideoSaved?.invoke(uri)
val completeRecording = Runnable {
_state.value = _state.value.copy(videoRecordingState = VideoRecordingState())
if (cameraDevice != null && previewSurface != null) {
createPreviewSession(openGeneration = cameraOpenGeneration)
}
onVideoSaved?.invoke(uri)
}
cameraHandler?.post(completeRecording) ?: completeRecording.run()
}
if (!started) {
return
@@ -5415,7 +5482,7 @@ class Camera2Controller(private val context: Context) {
videoRecordingState = VideoRecordingState(isRecording = true, elapsedMs = 0L)
)
videoRecordingPausedMs = 0L
startVideoRecordingTicker()
createPreviewSession(openGeneration = cameraOpenGeneration)
}
private fun isCurrentCameraFrontFacing(): Boolean {
@@ -5426,6 +5493,9 @@ class Camera2Controller(private val context: Context) {
fun pauseVideoRecording() {
if (!_state.value.videoRecordingState.isRecording || _state.value.videoRecordingState.isPaused) return
videoRecorder.pauseRecording()
if (videoRecorder.usesDedicatedCameraInput) {
updateDedicatedVideoRepeatingTarget(includeVideoSurface = false)
}
videoRecordingPauseStartElapsedMs = SystemClock.elapsedRealtime()
_state.value = _state.value.copy(
videoRecordingState = _state.value.videoRecordingState.copy(isPaused = true)
@@ -5434,6 +5504,12 @@ class Camera2Controller(private val context: Context) {
fun resumeVideoRecording() {
if (!_state.value.videoRecordingState.isRecording || !_state.value.videoRecordingState.isPaused) return
if (videoRecorder.usesDedicatedCameraInput &&
!updateDedicatedVideoRepeatingTarget(includeVideoSurface = true)
) {
PLog.e(TAG, "Cannot resume dedicated video input because the recording surface is unavailable")
return
}
videoRecorder.resumeRecording()
videoRecordingPausedMs += SystemClock.elapsedRealtime() - videoRecordingPauseStartElapsedMs
_state.value = _state.value.copy(
@@ -5448,8 +5524,15 @@ class Camera2Controller(private val context: Context) {
videoCaptureStatsLastTimestampNs = 0L
stopVideoRecordingTicker()
_state.value = _state.value.copy(
videoRecordingState = _state.value.videoRecordingState.copy(isRecording = false)
videoRecordingState = _state.value.videoRecordingState.copy(
isRecording = false,
isPaused = false,
isProcessing = videoRecorder.usesDedicatedCameraInput
)
)
if (videoRecorder.usesDedicatedCameraInput && !_state.value.videoRecordingState.isPaused) {
updateDedicatedVideoRepeatingTarget(includeVideoSurface = false)
}
videoRecorder.stopRecording()
if (pendingVendorSessionParameterRestart && cameraDevice != null && previewSurface != null) {
PLog.d(TAG, "Restarting preview session after recording for pending vendor session parameter change")
@@ -5457,9 +5540,37 @@ class Camera2Controller(private val context: Context) {
}
}
private fun resolveVideoOrientationHintDegrees(): Int {
val deviceRotation = OrientationObserver.rotationDegrees.toInt()
return ((deviceRotation % 360) + 360) % 360
private fun updateDedicatedVideoRepeatingTarget(includeVideoSurface: Boolean): Boolean {
val device = cameraDevice ?: return false
val session = captureSession ?: return false
val previewTarget = previewSurface ?: return false
val encoderTarget = videoRecorder.cameraInputSurface
if (includeVideoSurface && encoderTarget == null) return false
return try {
val builder = device.createCaptureRequest(CameraDevice.TEMPLATE_RECORD).apply {
addTarget(previewTarget)
encoderTarget?.takeIf { includeVideoSurface }?.let(::addTarget)
applyBaseCameraSettings(this, isCapture = false)
}
previewRequestBuilder = builder
session.setRepeatingRequest(builder.build(), previewCallback, cameraHandler)
true
} catch (e: Exception) {
PLog.e(
TAG,
"Failed to ${if (includeVideoSurface) "attach" else "detach"} dedicated video target",
e
)
false
}
}
private fun resolveDedicatedVideoOrientationHintDegrees(orientationOffsetDegrees: Int): Int {
return resolveSurfaceTextureVideoOrientationDegrees(
deviceRotationDegrees = OrientationObserver.rotationDegrees.toInt(),
calibrationOffsetDegrees = orientationOffsetDegrees,
)
}
// ==================== 延时拍摄和网格线 ====================
@@ -6954,12 +7065,13 @@ class Camera2Controller(private val context: Context) {
pendingFrameMetadata.clear()
cameraOpenGeneration++
val keepVideoRecording = preserveVideoRecording && _state.value.videoRecordingState.isRecording
val keepVideoProcessing = _state.value.videoRecordingState.isProcessing
if (keepVideoRecording) {
PLog.d(TAG, "Closing camera while keeping active video recording")
}
if (_state.value.videoRecordingState.isRecording && !keepVideoRecording) {
stopVideoRecording()
} else if (!keepVideoRecording) {
} else if (!keepVideoRecording && !_state.value.videoRecordingState.isProcessing) {
videoRecorder.forceStop()
stopVideoRecordingTicker()
_state.value = _state.value.copy(videoRecordingState = VideoRecordingState())
@@ -6975,7 +7087,11 @@ class Camera2Controller(private val context: Context) {
} else {
_state.value.copy(
isPreviewActive = false,
videoRecordingState = VideoRecordingState()
videoRecordingState = if (keepVideoProcessing) {
_state.value.videoRecordingState
} else {
VideoRecordingState()
}
)
}
@@ -22,10 +22,11 @@ import java.nio.FloatBuffer
import java.nio.ShortBuffer
/**
* 视频帧渲染引擎 (重构版)
* GL 纹理编码渲染引擎
*
* 专门负责将纹理(GL_TEXTURE_2D)渲染到 MediaCodec 的 InputSurface。
* 此版本不再处理 LUT 和色彩配方,而是直接接受已经处理好的 FBO 纹理。
* 此类仅由 Live Photo 使用;常规视频使用独立 Camera2 SurfaceTexture 和
* RealtimeVideoRenderer,不再消费屏幕预览纹理。
*/
class HardwareLutVideoRenderer(
private val width: Int,
@@ -22,7 +22,6 @@ import com.hinnka.mycamera.screencapture.PhantomPipCrop
import com.hinnka.mycamera.camera.MeteringMode
import com.hinnka.mycamera.utils.PLog
import com.hinnka.mycamera.video.VideoLogProfile
import com.hinnka.mycamera.video.VideoRecorder
import java.nio.ByteBuffer
import java.nio.ByteOrder
import java.util.ArrayDeque
@@ -107,10 +106,6 @@ class LutRenderer(context: Context) : GLSurfaceView.Renderer {
private val meteringDispatchInFlight = AtomicBoolean(false)
private var captureFboId: Int = 0
private var captureTextureId: Int = 0
private var recordFboId: Int = 0
private var recordTextureId: Int = 0
private var recordFboWidth: Int = 0
private var recordFboHeight: Int = 0
private var passthroughProgramId: Int = 0
private var uPassMVPMatrixLocation: Int = 0
private var uPassSTMatrixLocation: Int = 0
@@ -496,11 +491,7 @@ class LutRenderer(context: Context) : GLSurfaceView.Renderer {
// Live Photo 录制器
var livePhotoRecorder: LivePhotoRecorder? = null
@Volatile
var videoRecorder: VideoRecorder? = null
@Volatile
var videoLogProfile: VideoLogProfile = VideoLogProfile.OFF
private var videoRenderStatsWindowStartMs: Long = 0L
private var videoRenderStatsFrames: Int = 0
// 预览帧捕获请求仅在 GL 线程中写入和消费。
private val pendingPreviewCaptureRequests = ArrayDeque<PreviewCaptureRequest>()
@@ -585,10 +576,6 @@ class LutRenderer(context: Context) : GLSurfaceView.Renderer {
meteringTextureId = 0
captureFboId = 0
captureTextureId = 0
recordFboId = 0
recordTextureId = 0
recordFboWidth = 0
recordFboHeight = 0
passthroughProgramId = 0
depthInputFboId = 0
depthInputTextureId = 0
@@ -1552,12 +1539,10 @@ class LutRenderer(context: Context) : GLSurfaceView.Renderer {
if (viewportWidth <= 0 || viewportHeight <= 0) return
// 更新 SurfaceTexture
var hasFreshCameraFrame = false
if (frameAvailable.getAndSet(false)) {
try {
surfaceTexture?.updateTexImage()
surfaceTexture?.getTransformMatrix(stMatrix)
hasFreshCameraFrame = true
} catch (e: RuntimeException) {
PLog.e(
TAG,
@@ -1568,11 +1553,6 @@ class LutRenderer(context: Context) : GLSurfaceView.Renderer {
}
val liveRecorder = livePhotoRecorder
val activeVideoRecorder = videoRecorder?.takeIf { it.isRecording() }
if (activeVideoRecorder == null) {
videoRenderStatsWindowStartMs = 0L
videoRenderStatsFrames = 0
}
val hdfEnabled = halation > 0.001f
val halationEnabled = redHalation > 0.001f
val bloomEnabled = bloom > 0.001f
@@ -1588,7 +1568,6 @@ class LutRenderer(context: Context) : GLSurfaceView.Renderer {
uploadPendingCurveTextures()
val requestedFbo = rawPreviewNeeded ||
liveRecorder != null ||
activeVideoRecorder != null ||
postProcessEffectEnabled ||
bokehNeeded ||
aiFocusInputNeeded ||
@@ -1705,41 +1684,6 @@ class LutRenderer(context: Context) : GLSurfaceView.Renderer {
)
}
// 5. 视频录制输出
if (hasFreshCameraFrame) {
activeVideoRecorder?.targetSize?.let { targetSize ->
ensureRecordFbo(targetSize.width, targetSize.height)
if (recordFboId != 0 && recordTextureId != 0) {
if (postProcessEffectEnabled) {
drawPostProcessEffects(recordFboId, targetSize.width, targetSize.height, currentTexId)
} else if (bokehNeeded) {
drawFboToScreen(recordFboId, targetSize.width, targetSize.height, currentTexId)
} else {
drawFboToScreen(
fboId = recordFboId,
width = targetSize.width,
height = targetSize.height,
sourceTextureId = currentTexId,
targetMvpMatrix = buildTextureMvpMatrix(
sourceWidth = viewportWidth,
sourceHeight = viewportHeight,
targetWidth = targetSize.width,
targetHeight = targetSize.height
)
)
}
GLES30.glFlush()
activeVideoRecorder.onPreviewFrame(
textureId = recordTextureId,
transformMatrix = identityMatrix,
timestampNs = surfaceTexture?.timestamp ?: 0L,
sharedContext = EGL14.eglGetCurrentContext(),
sharedDisplay = EGL14.eglGetCurrentDisplay()
)
}
}
}
// 3.5. Focus Peaking (Only for preview, not for recording)
if (!isAutoFocus && focusPeakingEnabled) {
currentTexId = renderFocusPeaking(currentTexId, currentWidth, currentHeight)
@@ -1762,7 +1706,7 @@ class LutRenderer(context: Context) : GLSurfaceView.Renderer {
finalDisplayHeight = finalDisplayHeight,
compositeFinalDisplay = needsHdfCompositeForSampling
)
if (meteringEnabled && activeVideoRecorder == null) {
if (meteringEnabled) {
runMeteringInternal(
sourceTextureId = finalDisplayTextureId,
sourceWidth = finalDisplayWidth,
@@ -1922,7 +1866,7 @@ class LutRenderer(context: Context) : GLSurfaceView.Renderer {
)
// 测光和直方图(按需)
if (fboId == 0 && meteringEnabled && videoRecorder?.isRecording() != true) {
if (fboId == 0 && meteringEnabled) {
runMeteringInternal()
}
@@ -2688,49 +2632,6 @@ class LutRenderer(context: Context) : GLSurfaceView.Renderer {
GLES30.glBindFramebuffer(GLES30.GL_FRAMEBUFFER, 0)
}
private fun ensureRecordFbo(width: Int, height: Int) {
if (width <= 0 || height <= 0) return
if (recordFboId != 0 && recordFboWidth == width && recordFboHeight == height) return
if (recordFboId != 0) {
GLES30.glDeleteFramebuffers(1, intArrayOf(recordFboId), 0)
recordFboId = 0
}
if (recordTextureId != 0) {
GLES30.glDeleteTextures(1, intArrayOf(recordTextureId), 0)
recordTextureId = 0
}
val fbos = IntArray(1)
val textures = IntArray(1)
GLES30.glGenFramebuffers(1, fbos, 0)
GLES30.glGenTextures(1, textures, 0)
recordFboId = fbos[0]
recordTextureId = textures[0]
recordFboWidth = width
recordFboHeight = height
GLES30.glBindTexture(GLES30.GL_TEXTURE_2D, recordTextureId)
GLES30.glTexImage2D(
GLES30.GL_TEXTURE_2D, 0, GLES30.GL_RGBA16F,
width, height, 0, GLES30.GL_RGBA, GLES30.GL_HALF_FLOAT, null
)
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.glBindFramebuffer(GLES30.GL_FRAMEBUFFER, recordFboId)
GLES30.glFramebufferTexture2D(
GLES30.GL_FRAMEBUFFER,
GLES30.GL_COLOR_ATTACHMENT0,
GLES30.GL_TEXTURE_2D,
recordTextureId,
0
)
GLES30.glBindFramebuffer(GLES30.GL_FRAMEBUFFER, 0)
}
/**
* 初始化顶点缓冲
*/
@@ -3855,14 +3756,6 @@ class LutRenderer(context: Context) : GLSurfaceView.Renderer {
GLES30.glDeleteTextures(1, intArrayOf(aiFocusInputTextureId), 0)
aiFocusInputTextureId = 0
}
if (recordFboId != 0) {
GLES30.glDeleteFramebuffers(1, intArrayOf(recordFboId), 0)
recordFboId = 0
}
if (recordTextureId != 0) {
GLES30.glDeleteTextures(1, intArrayOf(recordTextureId), 0)
recordTextureId = 0
}
if (fboId != 0) {
GLES30.glDeleteFramebuffers(1, intArrayOf(fboId), 0)
fboId = 0
@@ -3880,9 +3773,6 @@ class LutRenderer(context: Context) : GLSurfaceView.Renderer {
stackTextureId = 0
}
basicToneTextures.release()
recordFboWidth = 0
recordFboHeight = 0
// 删除程序
colorProgramCache.release()
GlUtils.deleteProgram(passthroughProgramId)
@@ -0,0 +1,747 @@
package com.hinnka.mycamera.lut
import android.content.Context
import android.graphics.SurfaceTexture
import android.opengl.EGL14
import android.opengl.EGLConfig
import android.opengl.EGLContext
import android.opengl.EGLDisplay
import android.opengl.EGLExt
import android.opengl.EGLSurface
import android.opengl.GLES11Ext
import android.opengl.GLES30
import android.opengl.Matrix
import android.util.Size
import android.view.Surface
import com.hinnka.mycamera.model.ColorPaletteMapper
import com.hinnka.mycamera.model.ColorRecipeParams
import com.hinnka.mycamera.utils.PLog
import com.hinnka.mycamera.video.VideoEncoderColorConfig
import com.hinnka.mycamera.video.VideoLogProfile
import java.nio.ByteBuffer
import java.nio.ByteOrder
import java.nio.FloatBuffer
import java.nio.ShortBuffer
import kotlin.math.abs
import kotlin.math.max
/**
* Camera2 录像专用实时渲染器。
*
* Camera2 将录像流写入此类拥有的独立 [SurfaceTexture];同一个专用 EGL context
* 随后把 OES 帧经过色彩层实时绘制到 MediaCodec input surface。该链路与屏幕预览
* 完全分离,因此录像帧率不再受 GLSurfaceView 调度或预览 FBO 负载影响。
*/
class RealtimeVideoRenderer(
context: Context,
private val cameraInputSize: Size,
private val encoderOutputSize: Size,
colorLayers: List<VideoColorEffectLayer>,
private val videoLogProfile: VideoLogProfile,
private val hlgInput: Boolean,
private val mirrorHorizontally: Boolean,
private val mirrorVertically: Boolean,
private val encoderColorConfig: VideoEncoderColorConfig,
) {
companion object {
private const val TAG = "RealtimeVideoRenderer"
private const val EGL_RECORDABLE_ANDROID = 0x3142
private const val EGL_OPENGL_ES3_BIT_KHR = 0x0040
}
private data class LayerResources(
val lutConfig: LutConfig?,
val params: ColorRecipeParams,
var lutTextureId: Int = 0,
var curveTextureId: Int = 0,
)
private val appContext = context.applicationContext
private val layers = colorLayers
.map { layer ->
LayerResources(
lutConfig = layer.lutConfig,
params = layer.recipeParams
?.let(ColorPaletteMapper::mergeIntoEffectiveParams)
?: ColorRecipeParams.DEFAULT,
)
}
.ifEmpty {
listOf(LayerResources(lutConfig = null, params = ColorRecipeParams.DEFAULT))
}
.also { resolved ->
require(resolved.size <= 2) {
"Realtime video supports the baseline and creative color layers only"
}
}
private val colorProgramCache = PreviewColorProgramCache()
private val basicToneTextures = BasicToneGlTextures()
private val identityMatrix = FloatArray(16).also { Matrix.setIdentityM(it, 0) }
private val firstPassMvpMatrix = FloatArray(16).also {
Matrix.setIdentityM(it, 0)
if (mirrorHorizontally || mirrorVertically) {
Matrix.scaleM(
it,
0,
if (mirrorHorizontally) -1f else 1f,
if (mirrorVertically) -1f else 1f,
1f,
)
}
}
private val fullCropRect = floatArrayOf(0f, 0f, 1f, 1f)
private var cameraCropRect = fullCropRect
private var cameraTransformAxesSwapped: Boolean? = null
private val stMatrix = FloatArray(16).also { Matrix.setIdentityM(it, 0) }
private var eglDisplay: EGLDisplay = EGL14.EGL_NO_DISPLAY
private var eglContext: EGLContext = EGL14.EGL_NO_CONTEXT
private var encoderEglSurface: EGLSurface = EGL14.EGL_NO_SURFACE
private var cameraTextureId = 0
private var cameraSurfaceTexture: SurfaceTexture? = null
private var cameraSurface: Surface? = null
private var intermediateTextureId = 0
private var intermediateFboId = 0
private var vertexBuffer: FloatBuffer? = null
private var textureCoordinateBuffer: FloatBuffer? = null
private var indexBuffer: ShortBuffer? = null
private var initialized = false
val inputSurface: Surface?
get() = cameraSurface
fun initialize(
encoderSurface: Surface,
onFrameAvailable: () -> Unit,
) {
check(!initialized) { "Realtime video renderer is already initialized" }
initializeEgl(encoderSurface)
check(makeCurrent()) { "Cannot make realtime video EGL context current" }
initializeGeometry()
initializeLayerTextures()
if (layers.size > 1) {
initializeIntermediateFramebuffer()
}
cameraTextureId = GlUtils.createOESTexture()
check(cameraTextureId != 0) { "Cannot create realtime video OES texture" }
cameraSurfaceTexture = SurfaceTexture(cameraTextureId).apply {
setDefaultBufferSize(cameraInputSize.width, cameraInputSize.height)
setOnFrameAvailableListener { onFrameAvailable() }
}
cameraSurface = Surface(cameraSurfaceTexture)
initialized = true
PLog.i(
TAG,
"Initialized: camera=${cameraInputSize.width}x${cameraInputSize.height}, " +
"encoder=${encoderOutputSize.width}x${encoderOutputSize.height}, " +
"layers=${layers.size}, log=${videoLogProfile.name}, hlgInput=$hlgInput, " +
"mirrorH=$mirrorHorizontally, mirrorV=$mirrorVertically, " +
"color=${encoderColorConfig.debugName}"
)
}
/**
* 消费 SurfaceTexture 中最新的一帧并写入编码器。必须在初始化所用的录像 GL 线程调用。
*
* @return 相机帧时间戳(纳秒);没有有效帧时返回 null。
*/
fun renderLatestFrame(): Long? {
if (!initialized || !makeCurrent()) return null
val surfaceTexture = cameraSurfaceTexture ?: return null
try {
surfaceTexture.updateTexImage()
surfaceTexture.getTransformMatrix(stMatrix)
updateCameraTransformGeometry()
} catch (error: RuntimeException) {
PLog.e(TAG, "Failed to acquire realtime video frame", error)
return null
}
val timestampNs = surfaceTexture.timestamp
if (timestampNs <= 0L) return null
val firstLayer = layers.first()
val firstTargetFbo = if (layers.size > 1) intermediateFboId else 0
drawLayer(
layer = firstLayer,
targetFboId = firstTargetFbo,
textureSource = PreviewColorTextureSource.EXTERNAL_OES,
textureTarget = GLES11Ext.GL_TEXTURE_EXTERNAL_OES,
textureId = cameraTextureId,
sourceStMatrix = stMatrix,
cropRect = cameraCropRect,
mvpMatrix = firstPassMvpMatrix,
enableVideoLog = videoLogProfile.isEnabled,
treatSourceAsHlgInput = hlgInput,
presentationTimeNs = timestampNs,
)
if (layers.size > 1) {
layers.drop(1).forEachIndexed { index, layer ->
val isLast = index == layers.lastIndex - 1
drawLayer(
layer = layer,
targetFboId = if (isLast) 0 else intermediateFboId,
textureSource = PreviewColorTextureSource.TEXTURE_2D,
textureTarget = GLES30.GL_TEXTURE_2D,
textureId = intermediateTextureId,
sourceStMatrix = identityMatrix,
cropRect = fullCropRect,
mvpMatrix = identityMatrix,
enableVideoLog = false,
treatSourceAsHlgInput = false,
presentationTimeNs = timestampNs,
)
}
}
EGLExt.eglPresentationTimeANDROID(eglDisplay, encoderEglSurface, timestampNs)
if (!EGL14.eglSwapBuffers(eglDisplay, encoderEglSurface)) {
throw IllegalStateException(
"Realtime video eglSwapBuffers failed: 0x${Integer.toHexString(EGL14.eglGetError())}"
)
}
return timestampNs
}
private fun updateCameraTransformGeometry() {
val axesSwapped = isTextureTransformAxesSwapped(stMatrix)
if (cameraTransformAxesSwapped == axesSwapped) return
cameraTransformAxesSwapped = axesSwapped
val orientedInputSize = if (axesSwapped) {
Size(cameraInputSize.height, cameraInputSize.width)
} else {
cameraInputSize
}
cameraCropRect = resolveCenterCropRect(orientedInputSize, encoderOutputSize)
PLog.i(
TAG,
"Camera texture transform: axesSwapped=$axesSwapped, " +
"effective=${orientedInputSize.width}x${orientedInputSize.height}, " +
"crop=${cameraCropRect.joinToString(prefix = "[", postfix = "]")}, " +
"matrix=${stMatrix.joinToString(prefix = "[", postfix = "]")}"
)
}
private fun drawLayer(
layer: LayerResources,
targetFboId: Int,
textureSource: PreviewColorTextureSource,
textureTarget: Int,
textureId: Int,
sourceStMatrix: FloatArray,
cropRect: FloatArray,
mvpMatrix: FloatArray,
enableVideoLog: Boolean,
treatSourceAsHlgInput: Boolean,
presentationTimeNs: Long,
) {
val lutEnabled = layer.lutConfig != null && layer.lutTextureId != 0
val variant = PreviewColorShaderVariant.forPass(
textureSource = textureSource,
params = layer.params,
lutConfig = layer.lutConfig,
lutEnabled = lutEnabled,
videoLogEnabled = enableVideoLog,
hlgInput = treatSourceAsHlgInput,
)
val locations = colorProgramCache.get(variant)
?: throw IllegalStateException("Cannot create realtime video color shader: $variant")
GLES30.glBindFramebuffer(GLES30.GL_FRAMEBUFFER, targetFboId)
GLES30.glViewport(0, 0, encoderOutputSize.width, encoderOutputSize.height)
GLES30.glClearColor(0f, 0f, 0f, 1f)
GLES30.glClear(GLES30.GL_COLOR_BUFFER_BIT)
GLES30.glUseProgram(locations.programId)
GLES30.glActiveTexture(GLES30.GL_TEXTURE0)
GLES30.glBindTexture(textureTarget, textureId)
GLES30.glUniform1i(locations.uCameraTextureLocation, 0)
GLES30.glActiveTexture(GLES30.GL_TEXTURE1)
GLES30.glBindTexture(
GLES30.GL_TEXTURE_3D,
if (lutEnabled) layer.lutTextureId else 0,
)
GLES30.glUniform1i(locations.uLutTextureLocation, 1)
GLES30.glUniformMatrix4fv(locations.uMVPMatrixLocation, 1, false, mvpMatrix, 0)
GLES30.glUniformMatrix4fv(locations.uSTMatrixLocation, 1, false, sourceStMatrix, 0)
GLES30.glUniform4f(
locations.uCropRectLocation,
cropRect[0],
cropRect[1],
cropRect[2],
cropRect[3],
)
GLES30.glUniform1f(
locations.uLutSizeLocation,
layer.lutConfig?.size?.toFloat() ?: 1f,
)
GLES30.glUniform1f(locations.uLutIntensityLocation, layer.params.lutIntensity)
GLES30.glUniform1i(locations.uLutEnabledLocation, if (lutEnabled) 1 else 0)
GLES30.glUniform1i(locations.uLutMaskTypeLocation, 0)
GLES30.glUniform1i(
locations.uLutCurveLocation,
LutShaderMappings.transferCurveId(layer.lutConfig?.curve),
)
GLES30.glUniform1i(
locations.uLutColorSpaceLocation,
LutShaderMappings.colorSpaceId(
layer.lutConfig?.colorSpace ?: com.hinnka.mycamera.raw.ColorSpace.SRGB
),
)
GLES30.glUniform1i(
locations.uVideoLogEnabledLocation,
if (enableVideoLog && videoLogProfile.isEnabled) 1 else 0,
)
GLES30.glUniform1i(
locations.uVideoLogCurveLocation,
LutShaderMappings.transferCurveId(videoLogProfile.logCurve),
)
GLES30.glUniform1i(
locations.uVideoColorSpaceLocation,
LutShaderMappings.colorSpaceId(videoLogProfile.colorSpace),
)
GLES30.glUniform1i(
locations.uIsHlgInputLocation,
if (treatSourceAsHlgInput) 1 else 0,
)
bindRecipeUniforms(
locations = locations,
params = layer.params,
presentationTimeNs = presentationTimeNs,
)
val curveEnabled = layer.curveTextureId != 0
GLES30.glActiveTexture(GLES30.GL_TEXTURE2)
GLES30.glBindTexture(
GLES30.GL_TEXTURE_2D,
if (curveEnabled) layer.curveTextureId else 0,
)
GLES30.glUniform1i(locations.uCurveTextureLocation, 2)
GLES30.glUniform1i(locations.uCurveEnabledLocation, if (curveEnabled) 1 else 0)
basicToneTextures.bind(
context = appContext,
textureUnit = 3,
samplerLocation = locations.uBasicToneLutLocation,
intensityLocation = locations.uBasicToneIntensityLocation,
amount = ColorPaletteMapper.basicToneAmount(layer.params),
)
GLES30.glUniform1f(locations.uApertureLocation, 0f)
GLES30.glUniform2f(locations.uFocusPointLocation, 0.5f, 0.5f)
GLES30.glUniform2f(
locations.uTexelSizeLocation,
1f / max(1, encoderOutputSize.width).toFloat(),
1f / max(1, encoderOutputSize.height).toFloat(),
)
val positions = vertexBuffer ?: return
val textureCoordinates = textureCoordinateBuffer ?: return
val indices = indexBuffer ?: return
positions.position(0)
textureCoordinates.position(0)
indices.position(0)
GLES30.glEnableVertexAttribArray(locations.aPositionLocation)
GLES30.glVertexAttribPointer(
locations.aPositionLocation,
2,
GLES30.GL_FLOAT,
false,
0,
positions,
)
GLES30.glEnableVertexAttribArray(locations.aTexCoordLocation)
GLES30.glVertexAttribPointer(
locations.aTexCoordLocation,
2,
GLES30.GL_FLOAT,
false,
0,
textureCoordinates,
)
GLES30.glDrawElements(
GLES30.GL_TRIANGLES,
Shaders.DRAW_ORDER.size,
GLES30.GL_UNSIGNED_SHORT,
indices,
)
GLES30.glDisableVertexAttribArray(locations.aPositionLocation)
GLES30.glDisableVertexAttribArray(locations.aTexCoordLocation)
GlUtils.checkGlError("RealtimeVideoRenderer.drawLayer")
}
private fun bindRecipeUniforms(
locations: ColorPassLocations,
params: ColorRecipeParams,
presentationTimeNs: Long,
) {
val enabled = !params.isDefault()
GLES30.glUniform1i(locations.uColorRecipeEnabledLocation, if (enabled) 1 else 0)
// 低像素和色散采样位于 shader 的 recipeEnabled 分支之前,必须每个 pass
// 都显式赋值,避免复用同一 program 时继承上一层的 uniform。
GLES30.glUniform1f(locations.uChromaticAberrationLocation, params.chromaticAberration)
GLES30.glUniform1f(locations.uLowResLocation, params.lowRes)
GLES30.glUniform1f(
locations.uAspectRatioLocation,
encoderOutputSize.width.toFloat() / max(1, encoderOutputSize.height).toFloat(),
)
if (!enabled) return
GLES30.glUniform1f(locations.uExposureLocation, params.exposure)
GLES30.glUniform1f(locations.uContrastLocation, params.contrast)
GLES30.glUniform1f(locations.uSaturationLocation, params.saturation)
GLES30.glUniform1f(locations.uTemperatureLocation, params.temperature)
GLES30.glUniform1f(locations.uTintLocation, params.tint)
GLES30.glUniform1f(locations.uFadeLocation, params.fade)
GLES30.glUniform1f(locations.uVibranceLocation, params.color)
ShadowsHighlightsShader.bindUniformLocations(
highlightsLocation = locations.uHighlightsLocation,
shadowsLocation = locations.uShadowsLocation,
highlights = params.highlights,
shadows = params.shadows,
)
GLES30.glUniform1f(locations.uToneToeLocation, params.toneToe)
GLES30.glUniform1f(locations.uToneShoulderLocation, params.toneShoulder)
GLES30.glUniform1f(locations.uTonePivotLocation, params.tonePivot)
GLES30.glUniform1f(locations.uFilmGrainLocation, params.filmGrain)
GLES30.glUniform1f(locations.uVignetteLocation, params.vignette)
GLES30.glUniform1f(locations.uFlashLocation, params.flash)
GLES30.glUniform1f(locations.uBleachBypassLocation, params.bleachBypass)
GLES30.glUniform1f(locations.uNoiseLocation, params.noise)
GLES30.glUniform1f(
locations.uNoiseSeedLocation,
(presentationTimeNs % 10_000_000_000L) / 1_000_000_000f,
)
GLES30.glUniform3f(
locations.uGradingHuesLocation,
params.gradingShadowHue,
params.gradingMidtoneHue,
params.gradingHighlightHue,
)
GLES30.glUniform3f(
locations.uGradingAmountsLocation,
params.gradingShadowAmount,
params.gradingMidtoneAmount,
params.gradingHighlightAmount,
)
GLES30.glUniform1f(locations.uGradingBalanceLocation, params.gradingBalance)
GLES30.glUniform1f(locations.uGradingBlendingLocation, params.gradingBlending)
ColorRecipeGl.bindLchAdjustments(
locations.uLchHueAdjustmentsLocation,
locations.uLchChromaAdjustmentsLocation,
locations.uLchLightnessAdjustmentsLocation,
ColorRecipeGl.lchAdjustments(params),
)
GLES30.glUniformMatrix3fv(
locations.uPrimaryCalibrationMatrixLocation,
1,
false,
CameraRawCalibrationMatrix.build(params),
0,
)
}
private fun initializeEgl(encoderSurface: Surface) {
eglDisplay = EGL14.eglGetDisplay(EGL14.EGL_DEFAULT_DISPLAY)
check(eglDisplay != EGL14.EGL_NO_DISPLAY) { "Cannot obtain EGL display" }
val major = IntArray(1)
val minor = IntArray(1)
check(EGL14.eglInitialize(eglDisplay, major, 0, minor, 0)) {
"Cannot initialize EGL display"
}
val candidates = buildList {
if (encoderColorConfig.prefer10BitInputSurface) {
chooseConfig(red = 10, green = 10, blue = 10, alpha = 2)
?.let { add("RGB10_A2" to it) }
}
chooseConfig(red = 8, green = 8, blue = 8, alpha = 8)
?.let { add("RGBA8888" to it) }
}
check(candidates.isNotEmpty()) { "Cannot choose recordable EGL config" }
var lastError = EGL14.EGL_SUCCESS
candidates.forEach { (label, config) ->
eglContext = EGL14.eglCreateContext(
eglDisplay,
config,
EGL14.EGL_NO_CONTEXT,
intArrayOf(EGL14.EGL_CONTEXT_CLIENT_VERSION, 3, EGL14.EGL_NONE),
0,
)
if (eglContext == EGL14.EGL_NO_CONTEXT) {
lastError = EGL14.eglGetError()
PLog.w(TAG, "$label realtime EGL context unavailable: 0x${Integer.toHexString(lastError)}")
return@forEach
}
encoderEglSurface = EGL14.eglCreateWindowSurface(
eglDisplay,
config,
encoderSurface,
intArrayOf(EGL14.EGL_NONE),
0,
)
if (encoderEglSurface != EGL14.EGL_NO_SURFACE && makeCurrent()) {
if (encoderColorConfig.prefer10BitInputSurface && label != "RGB10_A2") {
PLog.w(
TAG,
"10-bit encoder EGL surface unavailable; using RGBA8888 for " +
"${encoderColorConfig.debugName}"
)
} else {
PLog.i(TAG, "Using $label recordable EGL surface for ${encoderColorConfig.debugName}")
}
return
}
lastError = EGL14.eglGetError()
PLog.w(TAG, "$label encoder EGL surface unavailable: 0x${Integer.toHexString(lastError)}")
if (encoderEglSurface != EGL14.EGL_NO_SURFACE) {
EGL14.eglDestroySurface(eglDisplay, encoderEglSurface)
encoderEglSurface = EGL14.EGL_NO_SURFACE
}
EGL14.eglDestroyContext(eglDisplay, eglContext)
eglContext = EGL14.EGL_NO_CONTEXT
}
if (encoderColorConfig.prefer10BitInputSurface) {
PLog.w(TAG, "10-bit encoder EGL surface unavailable; the Log path cannot preserve 10-bit precision")
}
throw IllegalStateException(
"Cannot create encoder EGL surface: 0x${Integer.toHexString(lastError)}"
)
}
private fun chooseConfig(red: Int, green: Int, blue: Int, alpha: Int): EGLConfig? {
return chooseConfig(red, green, blue, alpha, EGL_OPENGL_ES3_BIT_KHR)
?: chooseConfig(red, green, blue, alpha, EGL14.EGL_OPENGL_ES2_BIT)
}
private fun chooseConfig(
red: Int,
green: Int,
blue: Int,
alpha: Int,
renderableType: Int,
): EGLConfig? {
val configs = arrayOfNulls<EGLConfig>(1)
val count = IntArray(1)
val attributes = intArrayOf(
EGL14.EGL_RED_SIZE, red,
EGL14.EGL_GREEN_SIZE, green,
EGL14.EGL_BLUE_SIZE, blue,
EGL14.EGL_ALPHA_SIZE, alpha,
EGL14.EGL_RENDERABLE_TYPE, renderableType,
EGL_RECORDABLE_ANDROID, 1,
EGL14.EGL_NONE,
)
val success = EGL14.eglChooseConfig(
eglDisplay,
attributes,
0,
configs,
0,
configs.size,
count,
0,
)
return if (success && count[0] > 0) configs[0] else null
}
private fun makeCurrent(): Boolean {
if (eglDisplay == EGL14.EGL_NO_DISPLAY ||
eglContext == EGL14.EGL_NO_CONTEXT ||
encoderEglSurface == EGL14.EGL_NO_SURFACE
) {
return false
}
return EGL14.eglMakeCurrent(
eglDisplay,
encoderEglSurface,
encoderEglSurface,
eglContext,
)
}
private fun initializeGeometry() {
vertexBuffer = ByteBuffer.allocateDirect(Shaders.FULL_QUAD_VERTICES.size * Float.SIZE_BYTES)
.order(ByteOrder.nativeOrder())
.asFloatBuffer()
.apply {
put(Shaders.FULL_QUAD_VERTICES)
position(0)
}
textureCoordinateBuffer =
ByteBuffer.allocateDirect(Shaders.TEXTURE_COORDS.size * Float.SIZE_BYTES)
.order(ByteOrder.nativeOrder())
.asFloatBuffer()
.apply {
put(Shaders.TEXTURE_COORDS)
position(0)
}
indexBuffer = ByteBuffer.allocateDirect(Shaders.DRAW_ORDER.size * Short.SIZE_BYTES)
.order(ByteOrder.nativeOrder())
.asShortBuffer()
.apply {
put(Shaders.DRAW_ORDER)
position(0)
}
}
private fun initializeLayerTextures() {
layers.forEach { layer ->
layer.lutConfig?.let { config ->
layer.lutTextureId = GlUtils.create3DTexture(config)
check(layer.lutTextureId != 0) {
"Cannot upload realtime video LUT ${config.title}"
}
}
val params = layer.params
val hasCurve = params.masterCurvePoints != null ||
params.redCurvePoints != null ||
params.greenCurvePoints != null ||
params.blueCurvePoints != null
if (hasCurve) {
layer.curveTextureId = ColorRecipeGl.ensureCurveTextureUploaded(
textureId = 0,
pendingBuffer = CurveUtils.buildCurveTextureBuffer(
params.masterCurvePoints,
params.redCurvePoints,
params.greenCurvePoints,
params.blueCurvePoints,
),
)
check(layer.curveTextureId != 0) {
"Cannot upload realtime video curve texture"
}
}
}
}
private fun initializeIntermediateFramebuffer() {
val textures = IntArray(1)
GLES30.glGenTextures(1, textures, 0)
intermediateTextureId = textures[0]
GLES30.glBindTexture(GLES30.GL_TEXTURE_2D, intermediateTextureId)
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,
encoderOutputSize.width,
encoderOutputSize.height,
0,
GLES30.GL_RGBA,
GLES30.GL_UNSIGNED_BYTE,
null,
)
val framebuffers = IntArray(1)
GLES30.glGenFramebuffers(1, framebuffers, 0)
intermediateFboId = framebuffers[0]
GLES30.glBindFramebuffer(GLES30.GL_FRAMEBUFFER, intermediateFboId)
GLES30.glFramebufferTexture2D(
GLES30.GL_FRAMEBUFFER,
GLES30.GL_COLOR_ATTACHMENT0,
GLES30.GL_TEXTURE_2D,
intermediateTextureId,
0,
)
check(GLES30.glCheckFramebufferStatus(GLES30.GL_FRAMEBUFFER) == GLES30.GL_FRAMEBUFFER_COMPLETE) {
"Realtime video intermediate framebuffer is incomplete"
}
GLES30.glBindFramebuffer(GLES30.GL_FRAMEBUFFER, 0)
}
fun release() {
if (eglDisplay != EGL14.EGL_NO_DISPLAY &&
eglContext != EGL14.EGL_NO_CONTEXT &&
encoderEglSurface != EGL14.EGL_NO_SURFACE
) {
makeCurrent()
}
cameraSurfaceTexture?.setOnFrameAvailableListener(null)
cameraSurface?.release()
cameraSurface = null
cameraSurfaceTexture?.release()
cameraSurfaceTexture = null
layers.forEach { layer ->
if (layer.lutTextureId != 0) {
GLES30.glDeleteTextures(1, intArrayOf(layer.lutTextureId), 0)
layer.lutTextureId = 0
}
if (layer.curveTextureId != 0) {
GLES30.glDeleteTextures(1, intArrayOf(layer.curveTextureId), 0)
layer.curveTextureId = 0
}
}
if (cameraTextureId != 0) {
GLES30.glDeleteTextures(1, intArrayOf(cameraTextureId), 0)
cameraTextureId = 0
}
if (intermediateTextureId != 0) {
GLES30.glDeleteTextures(1, intArrayOf(intermediateTextureId), 0)
intermediateTextureId = 0
}
if (intermediateFboId != 0) {
GLES30.glDeleteFramebuffers(1, intArrayOf(intermediateFboId), 0)
intermediateFboId = 0
}
colorProgramCache.release()
basicToneTextures.release()
if (eglDisplay != EGL14.EGL_NO_DISPLAY) {
EGL14.eglMakeCurrent(
eglDisplay,
EGL14.EGL_NO_SURFACE,
EGL14.EGL_NO_SURFACE,
EGL14.EGL_NO_CONTEXT,
)
if (encoderEglSurface != EGL14.EGL_NO_SURFACE) {
EGL14.eglDestroySurface(eglDisplay, encoderEglSurface)
}
if (eglContext != EGL14.EGL_NO_CONTEXT) {
EGL14.eglDestroyContext(eglDisplay, eglContext)
}
}
encoderEglSurface = EGL14.EGL_NO_SURFACE
eglContext = EGL14.EGL_NO_CONTEXT
eglDisplay = EGL14.EGL_NO_DISPLAY
initialized = false
}
}
private fun resolveCenterCropRect(source: Size, target: Size): FloatArray {
val sourceAspect = source.width.toFloat() / max(1, source.height).toFloat()
val targetAspect = target.width.toFloat() / max(1, target.height).toFloat()
return when {
sourceAspect > targetAspect -> {
val visibleWidth = targetAspect / sourceAspect
val inset = (1f - visibleWidth) / 2f
floatArrayOf(inset, 0f, 1f - inset, 1f)
}
sourceAspect < targetAspect -> {
val visibleHeight = sourceAspect / targetAspect
val inset = (1f - visibleHeight) / 2f
floatArrayOf(0f, inset, 1f, 1f - inset)
}
else -> floatArrayOf(0f, 0f, 1f, 1f)
}
}
internal fun isTextureTransformAxesSwapped(matrix: FloatArray): Boolean {
if (matrix.size < 6) return false
val transformedXAxisFollowsY = abs(matrix[1]) > abs(matrix[0])
val transformedYAxisFollowsX = abs(matrix[4]) > abs(matrix[5])
return transformedXAxisFollowsY && transformedYAxisFollowsX
}
@@ -0,0 +1,9 @@
package com.hinnka.mycamera.lut
import com.hinnka.mycamera.model.ColorRecipeParams
/** 一层可实时烘焙到录像的 LUT 与色彩配方快照。 */
data class VideoColorEffectLayer(
val lutConfig: LutConfig?,
val recipeParams: ColorRecipeParams?,
)
@@ -20,7 +20,6 @@ import com.hinnka.mycamera.raw.RawToneMappingParameters
import com.hinnka.mycamera.screencapture.PhantomPipCrop
import com.hinnka.mycamera.utils.PLog
import com.hinnka.mycamera.video.VideoLogProfile
import com.hinnka.mycamera.video.VideoRecorder
/**
* 相机预览 GLSurfaceView
@@ -372,10 +371,6 @@ class CameraGLSurfaceView @JvmOverloads constructor(
renderer.livePhotoRecorder = recorder
}
fun setVideoRecorder(recorder: VideoRecorder?) {
renderer.videoRecorder = recorder
}
fun setVideoLogProfile(profile: VideoLogProfile) {
renderer.videoLogProfile = profile
requestRender()
@@ -30,7 +30,6 @@ import com.hinnka.mycamera.ui.components.FocusIndicator
import com.hinnka.mycamera.utils.OrientationObserver
import com.hinnka.mycamera.video.CaptureMode
import com.hinnka.mycamera.video.VideoLogProfile
import com.hinnka.mycamera.video.VideoRecorder
/**
* 相机预览组件 - OpenGL ES 版本(Camera2 适配)
@@ -66,7 +65,6 @@ fun CameraPreviewGL(
onDepthInputAvailable: ((android.graphics.Bitmap) -> Unit)? = null,
onAiFocusInputAvailable: ((android.graphics.Bitmap) -> Unit)? = null,
livePhotoRecorder: LivePhotoRecorder? = null,
videoRecorder: VideoRecorder? = null,
videoLogProfile: VideoLogProfile = VideoLogProfile.OFF,
isHlgInput: Boolean = false,
naturalLightEnabled: Boolean = false,
@@ -277,7 +275,6 @@ fun CameraPreviewGL(
})
glSurfaceView.setMeteringMode(meteringMode)
glSurfaceView.setLivePhotoRecorder(livePhotoRecorder)
glSurfaceView.setVideoRecorder(videoRecorder)
glSurfaceView.setVideoLogProfile(videoLogProfile)
glSurfaceView.setIsHlgInput(isHlgInput)
glSurfaceView.setRawPreviewSettings(
@@ -1084,7 +1084,6 @@ fun CameraScreen(
viewModel.glSurfaceView = it
},
livePhotoRecorder = viewModel.livePhotoRecorder,
videoRecorder = viewModel.videoRecorder,
videoLogProfile = state.videoConfig.logProfile,
isHlgInput = if (hlgHardwareCompatibilityEnabled) state.isHLG else false,
naturalLightEnabled = naturalLightEnabled,
@@ -1923,6 +1922,7 @@ fun Controls(
captureMode = state.captureMode,
isCapturing = state.isCapturing,
isVideoRecording = state.videoRecordingState.isRecording,
isVideoProcessing = state.videoRecordingState.isProcessing,
isPaused = state.videoRecordingState.isPaused,
allowLongPress = state.captureMode == CaptureMode.QUICK_SHOT ||
(!naturalLightEnabled &&
@@ -1976,7 +1976,11 @@ fun Controls(
}
} else {
PhysicalButton(
onClick = onSwitchCameraClick,
onClick = {
if (!state.videoRecordingState.isProcessing) {
onSwitchCameraClick()
}
},
modifier = Modifier
.align(Alignment.CenterEnd)
.padding(end = 40.dp)
@@ -1987,7 +1991,9 @@ fun Controls(
Icon(
imageVector = AppIcons.Cameraswitch,
contentDescription = stringResource(R.string.switch_camera),
tint = Color.White,
tint = Color.White.copy(
alpha = if (state.videoRecordingState.isProcessing) 0.35f else 1f
),
modifier = Modifier.size(24.dp)
)
}
@@ -1998,7 +2004,8 @@ fun Controls(
CaptureModeSwitcher(
captureMode = state.captureMode,
enabled = !state.videoRecordingState.isRecording,
enabled = !state.videoRecordingState.isRecording &&
!state.videoRecordingState.isProcessing,
onModeSelected = onCaptureModeSelected
)
}
@@ -2014,6 +2021,7 @@ fun CaptureButton(
captureMode: CaptureMode,
isCapturing: Boolean,
isVideoRecording: Boolean,
isVideoProcessing: Boolean,
isPaused: Boolean,
allowLongPress: Boolean,
multipleExposureEnabled: Boolean,
@@ -2027,7 +2035,7 @@ fun CaptureButton(
var isPressed by remember { mutableStateOf(false) }
val scale by animateFloatAsState(
targetValue = if (isPressed || isCapturing || isVideoRecording) 0.95f else 1f,
targetValue = if (isPressed || isCapturing || isVideoRecording || isVideoProcessing) 0.95f else 1f,
animationSpec = spring(dampingRatio = 0.5f),
label = "captureScale"
)
@@ -2049,7 +2057,11 @@ fun CaptureButton(
label = "livePhotoRotation"
)
val currentDisabled by rememberUpdatedState(isCapturing || (captureMode == CaptureMode.VIDEO && isVideoRecording))
val currentDisabled by rememberUpdatedState(
isCapturing ||
isVideoProcessing ||
(captureMode == CaptureMode.VIDEO && isVideoRecording)
)
PhysicalButton(
modifier = modifier
@@ -2059,7 +2071,7 @@ fun CaptureButton(
var isLongPressStarted = false
detectTapGestures(
onTap = {
if (!isCapturing) {
if (!isCapturing && !isVideoProcessing) {
onTap()
}
},
@@ -2107,6 +2119,8 @@ fun CaptureButton(
}
val ringColor = when {
captureMode == CaptureMode.VIDEO && isVideoProcessing ->
Color.White.copy(alpha = 0.5f)
captureMode == CaptureMode.VIDEO && isVideoRecording -> {
if (isPaused) Color.White.copy(alpha = 0.8f)
else Color.Red.copy(alpha = pulseAlpha)
@@ -2174,6 +2188,13 @@ fun CaptureButton(
.clip(RoundedCornerShape(centerCorner))
.background(centerBrush)
)
if (captureMode == CaptureMode.VIDEO && isVideoProcessing) {
CircularProgressIndicator(
modifier = Modifier.size(34.dp),
color = Color.White,
strokeWidth = 3.dp
)
}
}
}
@@ -37,6 +37,10 @@ object VideoCapabilitiesResolver {
?: availableResolutions.firstOrNull()
?: VideoResolutionPreset.FHD_1080P
val recordingSizesByResolution = availableResolutions.mapNotNull { preset ->
findBestOutputSize(recordingOutputSizes, preset, requestedConfig.aspectRatio, openGateAspect)
?.let { preset to it }
}.toMap()
val previewSizesByResolution = availableResolutions.associateWith { preset ->
findBestOutputSize(previewOutputSizes, preset, requestedConfig.aspectRatio, openGateAspect)
?: requestedConfig.resolution.resolveOutputSize(
@@ -44,12 +48,8 @@ object VideoCapabilitiesResolver {
)
}
val recordingSize = findBestOutputSize(
recordingOutputSizes,
resolvedResolution,
requestedConfig.aspectRatio,
openGateAspect
) ?: resolvedResolution.resolveOutputSize(
val recordingSize = recordingSizesByResolution[resolvedResolution]
?: resolvedResolution.resolveOutputSize(
requestedConfig.aspectRatio.getPortraitAspectRatio(openGateAspect)
)
@@ -115,12 +115,14 @@ object VideoCapabilitiesResolver {
availableLogProfiles = availableLogProfiles,
availableBitrates = VideoBitratePreset.entries.toList(),
previewSizesByResolution = previewSizesByResolution,
recordingSizesByResolution = recordingSizesByResolution,
openGatePortraitAspectRatio = openGateAspect,
availableStabilizationModes = availableStabilizationModes,
supportsTorch = isFlashSupported,
linearTonemapSupported = linearTonemapSupported
),
previewSize = previewSize
previewSize = previewSize,
recordingSize = recordingSize
)
}
@@ -0,0 +1,12 @@
package com.hinnka.mycamera.video
/**
* SurfaceTexture 的变换矩阵已经把 Camera2 buffer 转到自然显示方向,因此容器只需要记录
* 设备相对自然方向的旋转;不能再次叠加 SENSOR_ORIENTATION。
*/
internal fun resolveSurfaceTextureVideoOrientationDegrees(
deviceRotationDegrees: Int,
calibrationOffsetDegrees: Int,
): Int {
return Math.floorMod(deviceRotationDegrees + calibrationOffsetDegrees, 360)
}
@@ -12,12 +12,11 @@ import android.media.MediaFormat
import android.media.MediaMuxer
import android.media.MediaRecorder
import android.net.Uri
import android.opengl.EGL14
import android.opengl.EGLContext
import android.opengl.EGLDisplay
import android.util.Size
import android.view.Surface
import androidx.core.app.ActivityCompat
import com.hinnka.mycamera.livephoto.HardwareLutVideoRenderer
import com.hinnka.mycamera.lut.RealtimeVideoRenderer
import com.hinnka.mycamera.lut.VideoColorEffectLayer
import com.hinnka.mycamera.utils.PLog
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
@@ -29,6 +28,7 @@ import kotlinx.coroutines.cancel
import kotlinx.coroutines.delay
import kotlinx.coroutines.isActive
import kotlinx.coroutines.launch
import kotlinx.coroutines.runBlocking
import kotlinx.coroutines.withContext
import java.nio.ByteBuffer
import java.util.concurrent.Executors
@@ -67,20 +67,12 @@ class VideoRecorder(
val info: MediaCodec.BufferInfo
)
private data class PendingFrame(
val textureId: Int,
val transformMatrix: FloatArray,
val timestampUs: Long,
val sharedContext: EGLContext,
val sharedDisplay: EGLDisplay
)
private val scope = CoroutineScope(Dispatchers.Default + SupervisorJob())
private val audioManager = context.getSystemService(AudioManager::class.java)
private val renderDispatcher: ExecutorCoroutineDispatcher =
Executors.newSingleThreadExecutor().asCoroutineDispatcher()
private val muxerLock = Any()
private val pendingFrameLock = Any()
private val realtimeFrameLock = Any()
private val videoCodecLock = Any()
private val audioCodecLock = Any()
@@ -98,9 +90,7 @@ class VideoRecorder(
private var audioEncoder: MediaCodec? = null
private var audioRecord: AudioRecord? = null
private var inputSurface: Surface? = null
private var renderer: HardwareLutVideoRenderer? = null
private var lastSharedContext: EGLContext = EGL14.EGL_NO_CONTEXT
private var lastSharedDisplay: EGLDisplay = EGL14.EGL_NO_DISPLAY
private var renderer: RealtimeVideoRenderer? = null
private var requestedBitrateMbps: Int = 30
private var requestedCodecMime: String = MediaFormat.MIMETYPE_VIDEO_AVC
private var requestedOrientationHintDegrees: Int = 0
@@ -110,8 +100,14 @@ class VideoRecorder(
private var preferredAudioInputId: String = VIDEO_AUDIO_INPUT_AUTO
private var requestedColorConfig: VideoEncoderColorRequest = VideoEncoderColorRequest()
private var preparedEncoderColorConfig: VideoEncoderColorConfig? = null
private var requestedOutputSize = Size(1080, 1920)
private var requestedCameraInputSize = Size(1920, 1080)
private var requestedColorLayers: List<VideoColorEffectLayer> = emptyList()
private var cameraInputStarted = false
private var hlgCameraInput = false
private var firstVideoPresentationTimeUs = Long.MIN_VALUE
private var requestedSize = android.util.Size(1080, 1920)
private var requestedSize = Size(1080, 1920)
private var requestedFps = 30
private var outputDateTakenMs: Long = 0L
private var pendingVideoOutput: VideoMediaStoreWriter.PendingVideo? = null
@@ -128,13 +124,9 @@ class VideoRecorder(
private var finishCallback: ((Uri?) -> Unit)? = null
private var audioBytesQueued = 0L
private var activeAudioConfig = monoAudioConfig()
private var lastAcceptedFrameTimestampUs = Long.MIN_VALUE
private var frameSelectionStartTimestampUs = Long.MIN_VALUE
private var lastAcceptedFrameSlot = Long.MIN_VALUE
private var lastEncodedFrameSlot = Long.MIN_VALUE
private var lastMuxedVideoPresentationTimeUs = Long.MIN_VALUE
private var lastMuxedAudioPresentationTimeUs = Long.MIN_VALUE
private var pendingFrame: PendingFrame? = null
private var pendingRealtimeFrame = false
private var totalPausedDurationUs: Long = 0L
private var pauseStartTimeUs: Long = 0L
private var renderLoopRunning = false
@@ -150,15 +142,23 @@ class VideoRecorder(
private var audioDrainJob: Job? = null
private var audioRecordJob: Job? = null
val targetSize: android.util.Size?
get() = requestedSize.takeIf { isRecording }
val usesDedicatedCameraInput: Boolean
get() = isRecording
val cameraInputSurface: Surface?
get() = renderer?.inputSurface.takeIf {
isRecording && !stopRequested
}
fun startRecording(
size: android.util.Size,
size: Size,
cameraInputSize: Size = size,
fps: Int,
bitrateMbps: Int,
codecMime: String,
colorConfig: VideoEncoderColorRequest = VideoEncoderColorRequest(),
colorLayers: List<VideoColorEffectLayer> = emptyList(),
hlgInput: Boolean = false,
orientationHintDegrees: Int = 0,
flipEncodedFrame: Boolean = false,
recordingPath: VideoRecordingPath = VideoRecordingPath.DCIM_PHOTON,
@@ -168,12 +168,18 @@ class VideoRecorder(
): Boolean {
if (isRecording) return false
requestedSize = android.util.Size(size.width.align16(), size.height.align16())
requestedOrientationHintDegrees = normalizeOrientationHint(orientationHintDegrees)
requestedOutputSize = Size(size.width.align16(), size.height.align16())
requestedCameraInputSize = cameraInputSize
// SurfaceTexture 变换后的 OES 内容已经处于自然显示方向,编码画布必须继续使用
// VideoResolutionPreset 的显示尺寸。设备横竖屏差异只通过容器 rotation metadata 表达。
requestedSize = requestedOutputSize
requestedFps = fps
requestedBitrateMbps = bitrateMbps
requestedCodecMime = codecMime
requestedColorConfig = colorConfig
requestedOrientationHintDegrees = normalizeOrientationHint(orientationHintDegrees)
requestedColorLayers = colorLayers.toList()
hlgCameraInput = hlgInput
requestedFlipEncodedFrame = flipEncodedFrame
requestedRecordingPath = recordingPath
requestedRecordingTreeUri = recordingTreeUri?.takeIf { it.isNotBlank() }
@@ -181,10 +187,6 @@ class VideoRecorder(
this.errorCallback = onError
this.finishCallback = onFinished
resetMuxerState()
frameSelectionStartTimestampUs = Long.MIN_VALUE
lastAcceptedFrameSlot = Long.MIN_VALUE
lastAcceptedFrameTimestampUs = Long.MIN_VALUE
lastEncodedFrameSlot = Long.MIN_VALUE
totalPausedDurationUs = 0L
pauseStartTimeUs = 0L
isPaused = false
@@ -196,8 +198,13 @@ class VideoRecorder(
statsRenderTimeTotalMs = 0L
statsRenderTimeMaxMs = 0L
stopRequested = false
cameraInputStarted = false
firstVideoPresentationTimeUs = Long.MIN_VALUE
try {
prepareVideoEncoder()
runBlocking(renderDispatcher) {
initializeRealtimeRenderer()
}
createMuxer()
audioEnabled = initAudioEncoder(startLoop = false)
startDrains()
@@ -208,39 +215,51 @@ class VideoRecorder(
return false
}
isRecording = true
PLog.d(
TAG,
"Video recording prepared: encoder=${requestedSize.width}x${requestedSize.height}, " +
"output=${requestedOutputSize.width}x${requestedOutputSize.height} @ " +
"${requestedFps}fps, orientationHint=$requestedOrientationHintDegrees, " +
"input=dedicated-surface-texture, " +
"path=${requestedRecordingPath.name}, uri=${requestedRecordingTreeUri?.take(48)}"
)
return true
}
fun onCameraInputStarted(): Boolean {
if (!isRecording || stopRequested || cameraInputStarted) return false
cameraInputStarted = true
if (audioEnabled) {
startAudioLoop()
}
PLog.d(
TAG,
"Video recording prepared: ${requestedSize.width}x${requestedSize.height} @ " +
"${requestedFps}fps, orientationHint=$requestedOrientationHintDegrees, " +
"path=${requestedRecordingPath.name}, uri=${requestedRecordingTreeUri?.take(48)}"
)
PLog.d(TAG, "Dedicated Camera2 recording input started")
return true
}
fun stopRecording() {
if (!isRecording || stopRequested) return
stopRequested = true
val completion = finishCallback
scope.launch {
var publishedUri: Uri? = null
try {
audioRecordJob?.join()
withContext(renderDispatcher) {
drainPendingFrames()
drainRealtimeFrames(allowWhenStopping = true)
signalVideoEndOfInputStream()
}
queueAudioEndOfStream()
videoDrainJob?.join()
audioDrainJob?.join()
val publishedUri = finalizeOutput()
finishCallback?.invoke(publishedUri)
releaseCaptureResources()
isRecording = false
publishedUri = finalizeOutput()
} catch (e: Exception) {
PLog.e(TAG, "Failed to stop recording cleanly", e)
finishCallback?.invoke(null)
} finally {
cleanup()
completion?.invoke(publishedUri)
}
}
}
@@ -248,10 +267,11 @@ class VideoRecorder(
fun forceStop() {
if (!isRecording) return
stopRequested = true
val completion = finishCallback
scope.launch {
errorCallback?.invoke("Recording stopped unexpectedly")
finishCallback?.invoke(null)
cleanup()
completion?.invoke(null)
}
}
@@ -270,68 +290,54 @@ class VideoRecorder(
PLog.d(TAG, "Video recording resumed")
}
fun onPreviewFrame(
textureId: Int,
transformMatrix: FloatArray,
timestampNs: Long,
sharedContext: EGLContext,
sharedDisplay: EGLDisplay
) {
if (!isRecording || stopRequested || isPaused) return
if (textureId == 0 || sharedContext == EGL14.EGL_NO_CONTEXT) return
val frameTimestampUs = timestampNs / 1000
statsIncomingFrames += 1
if (!shouldEncodeFrame(frameTimestampUs)) return
statsAcceptedFrames += 1
synchronized(pendingFrameLock) {
if (pendingFrame != null) {
statsReplacedPendingFrames += 1
}
pendingFrame = PendingFrame(
textureId = textureId,
transformMatrix = transformMatrix.clone(),
timestampUs = frameTimestampUs,
sharedContext = sharedContext,
sharedDisplay = sharedDisplay
)
if (!renderLoopRunning) {
renderLoopRunning = true
scope.launch(renderDispatcher) {
drainPendingFrames()
}
}
}
}
fun isRecording(): Boolean = isRecording && !stopRequested
fun setPreferredAudioInputId(audioInputId: String) {
preferredAudioInputId = audioInputId.ifBlank { VIDEO_AUDIO_INPUT_AUTO }
}
private fun initEncoders(sharedContext: EGLContext, sharedDisplay: EGLDisplay) {
val width = requestedSize.width
val height = requestedSize.height
if (videoEncoder == null) {
prepareVideoEncoder()
}
private fun initializeRealtimeRenderer() {
val encoderSurface = inputSurface ?: throw IllegalStateException("Video encoder input surface is not prepared")
val encoderColorConfig = preparedEncoderColorConfig ?: VideoEncoderColorConfig.sdrDisplay()
renderer = HardwareLutVideoRenderer(
width = width,
height = height,
lutConfig = null,
colorRecipeParams = null,
encoderColorConfig = encoderColorConfig
).apply {
initialize(encoderSurface, sharedContext, sharedDisplay)
}
val realtimeRenderer = RealtimeVideoRenderer(
context = context,
cameraInputSize = requestedCameraInputSize,
encoderOutputSize = requestedSize,
colorLayers = requestedColorLayers,
videoLogProfile = requestedColorConfig.logProfile,
hlgInput = hlgCameraInput,
mirrorHorizontally =
requestedFlipEncodedFrame && requestedOrientationHintDegrees % 180 == 0,
mirrorVertically =
requestedFlipEncodedFrame && requestedOrientationHintDegrees % 180 != 0,
encoderColorConfig = encoderColorConfig,
)
renderer = realtimeRenderer
realtimeRenderer.initialize(
encoderSurface = encoderSurface,
onFrameAvailable = ::onRealtimeFrameAvailable,
)
PLog.d(
TAG,
"Realtime video renderer initialized: ${requestedSize.width}x${requestedSize.height} @ ${requestedFps}fps"
)
}
lastSharedContext = sharedContext
lastSharedDisplay = sharedDisplay
PLog.d(TAG, "Video renderer initialized: ${width}x${height} @ ${requestedFps}fps")
private fun onRealtimeFrameAvailable() {
if (!isRecording || stopRequested || isPaused) return
statsIncomingFrames += 1
synchronized(realtimeFrameLock) {
if (pendingRealtimeFrame) {
statsReplacedPendingFrames += 1
}
pendingRealtimeFrame = true
if (!renderLoopRunning) {
renderLoopRunning = true
scope.launch(renderDispatcher) {
drainRealtimeFrames(allowWhenStopping = false)
}
}
}
}
private fun prepareVideoEncoder() {
@@ -620,94 +626,48 @@ class VideoRecorder(
return activeAudioConfig.channelCount * AUDIO_BYTES_PER_SAMPLE
}
private fun presentationTimeForSlot(slot: Long): Long {
val fps = requestedFps.coerceAtLeast(1)
return (slot.coerceAtLeast(0L) * 1_000_000L) / fps.toLong()
}
private fun shouldEncodeFrame(timestampUs: Long): Boolean {
if (timestampUs <= 0L) return false
if (lastAcceptedFrameTimestampUs != Long.MIN_VALUE && timestampUs <= lastAcceptedFrameTimestampUs) {
return false
}
val fps = requestedFps.coerceAtLeast(1)
if (frameSelectionStartTimestampUs == Long.MIN_VALUE) {
frameSelectionStartTimestampUs = timestampUs
lastAcceptedFrameSlot = 0L
lastAcceptedFrameTimestampUs = timestampUs
return true
}
val elapsedUs = (timestampUs - frameSelectionStartTimestampUs - totalPausedDurationUs).coerceAtLeast(0L)
val slot = (elapsedUs * fps.toLong()) / 1_000_000L
if (slot <= lastAcceptedFrameSlot) {
return false
}
lastAcceptedFrameSlot = slot
lastAcceptedFrameTimestampUs = timestampUs
return true
}
private fun drainPendingFrames() {
private fun drainRealtimeFrames(allowWhenStopping: Boolean) {
while (true) {
var frame = synchronized(pendingFrameLock) {
val nextFrame = pendingFrame
if (nextFrame == null) {
val hasFrame = synchronized(realtimeFrameLock) {
if (!pendingRealtimeFrame) {
renderLoopRunning = false
return
}
pendingFrame = null
nextFrame
pendingRealtimeFrame = false
true
}
if (!isRecording || stopRequested) {
if (!hasFrame ||
!isRecording ||
(stopRequested && !allowWhenStopping) ||
isPaused
) {
continue
}
try {
if (renderer == null) {
try {
initEncoders(frame.sharedContext, frame.sharedDisplay)
} catch (e: Exception) {
val diagnostic = if (e is MediaCodec.CodecException) {
"isTransient=${e.isTransient}, isRecoverable=${e.isRecoverable}, errorCode=${e.errorCode}"
} else ""
val errorMessage = "Failed to initialize encoders: ${e.localizedMessage ?: "Unknown error"}. $diagnostic"
PLog.e(TAG, errorMessage, e)
errorCallback?.invoke(errorMessage)
forceStop()
return
}
}
val videoRenderer = renderer ?: continue
val frameSlot = lastAcceptedFrameSlot.takeIf { it != Long.MIN_VALUE } ?: 0L
if (lastEncodedFrameSlot != Long.MIN_VALUE && frameSlot <= lastEncodedFrameSlot) {
continue
}
val presentationTimeUs = presentationTimeForSlot(frameSlot)
val renderStartMs = android.os.SystemClock.elapsedRealtime()
videoRenderer.renderFrame(
textureId = frame.textureId,
stMatrix = frame.transformMatrix,
timestampUs = presentationTimeUs,
mirrorHorizontally = requestedFlipEncodedFrame && requestedOrientationHintDegrees % 180 == 0,
mirrorVertically = requestedFlipEncodedFrame && requestedOrientationHintDegrees % 180 != 0
)
videoRenderer.renderLatestFrame() ?: continue
val renderCostMs = (android.os.SystemClock.elapsedRealtime() - renderStartMs).coerceAtLeast(0L)
statsAcceptedFrames += 1
statsRenderedFrames += 1
statsRenderTimeTotalMs += renderCostMs
if (renderCostMs > statsRenderTimeMaxMs) {
statsRenderTimeMaxMs = renderCostMs
}
lastEncodedFrameSlot = frameSlot
// logRenderStatsIfNeeded()
logRenderStatsIfNeeded()
} catch (e: Exception) {
val diagnostic = if (e is MediaCodec.CodecException) {
"isTransient=${e.isTransient}, isRecoverable=${e.isRecoverable}, errorCode=${e.errorCode}"
} else ""
PLog.e(TAG, "Failed to render frame to encoder. $diagnostic", e)
val message = "Failed to render dedicated recording frame. $diagnostic"
PLog.e(TAG, message, e)
errorCallback?.invoke(message)
if (!stopRequested) {
forceStop()
}
return
}
}
}
@@ -885,6 +845,12 @@ class VideoRecorder(
buffer: ByteBuffer,
info: MediaCodec.BufferInfo
) {
if (info.size <= 0 ||
info.flags and MediaCodec.BUFFER_FLAG_CODEC_CONFIG != 0 ||
(isVideo && isPaused)
) {
return
}
synchronized(muxerLock) {
if (!muxerStarted) {
val pending = if (isVideo) pendingVideoSamples else pendingAudioSamples
@@ -937,10 +903,22 @@ class VideoRecorder(
} else {
lastMuxedAudioPresentationTimeUs
}
val sanitizedPresentationTimeUs = if (lastPresentationTimeUs == Long.MIN_VALUE) {
info.presentationTimeUs.coerceAtLeast(0L)
val sourcePresentationTimeUs = if (isVideo) {
if (firstVideoPresentationTimeUs == Long.MIN_VALUE) {
firstVideoPresentationTimeUs = info.presentationTimeUs
}
(
info.presentationTimeUs -
firstVideoPresentationTimeUs -
totalPausedDurationUs
).coerceAtLeast(0L)
} else {
info.presentationTimeUs.coerceAtLeast(lastPresentationTimeUs + 1L)
info.presentationTimeUs
}
val sanitizedPresentationTimeUs = if (lastPresentationTimeUs == Long.MIN_VALUE) {
sourcePresentationTimeUs.coerceAtLeast(0L)
} else {
sourcePresentationTimeUs.coerceAtLeast(lastPresentationTimeUs + 1L)
}
val sanitizedInfo = MediaCodec.BufferInfo().apply {
set(0, info.size, sanitizedPresentationTimeUs, info.flags)
@@ -1017,10 +995,10 @@ class VideoRecorder(
output.descriptor.close()
} catch (_: Exception) {
}
pendingVideoOutput = null
if (!muxerStopSucceeded) {
VideoMediaStoreWriter.discardPendingVideo(context, output)
pendingVideoOutput = null
return null
}
@@ -1028,10 +1006,11 @@ class VideoRecorder(
if (uri == null) {
VideoMediaStoreWriter.discardPendingVideo(context, output)
}
pendingVideoOutput = null
return uri
}
private suspend fun cleanup() {
private suspend fun releaseCaptureResources() {
videoDrainJob?.cancel()
audioDrainJob?.cancel()
audioRecordJob?.cancel()
@@ -1083,11 +1062,13 @@ class VideoRecorder(
}
audioEncoder = null
}
}
private suspend fun cleanup() {
releaseCaptureResources()
resetMuxerState()
finishCallback = null
lastSharedContext = EGL14.EGL_NO_CONTEXT
lastSharedDisplay = EGL14.EGL_NO_DISPLAY
pendingVideoOutput?.let { output ->
try {
output.descriptor.close()
@@ -1111,21 +1092,22 @@ class VideoRecorder(
audioFormat = null
audioBytesQueued = 0L
activeAudioConfig = monoAudioConfig()
lastAcceptedFrameTimestampUs = Long.MIN_VALUE
lastEncodedFrameSlot = Long.MIN_VALUE
firstVideoPresentationTimeUs = Long.MIN_VALUE
lastMuxedVideoPresentationTimeUs = Long.MIN_VALUE
lastMuxedAudioPresentationTimeUs = Long.MIN_VALUE
}
synchronized(pendingFrameLock) {
pendingFrame = null
synchronized(realtimeFrameLock) {
pendingRealtimeFrame = false
renderLoopRunning = false
}
}
private fun cleanupPreparedStart() {
try {
renderer?.release()
} catch (_: Exception) {
runBlocking(renderDispatcher) {
try {
renderer?.release()
} catch (_: Exception) {
}
}
renderer = null
try {
@@ -1180,7 +1162,12 @@ class VideoRecorder(
}
fun release() {
forceStop()
if (isRecording || renderer != null || videoEncoder != null || audioEncoder != null) {
stopRequested = true
runBlocking {
cleanup()
}
}
scope.cancel()
renderDispatcher.close()
}
@@ -141,6 +141,7 @@ data class VideoCapabilities(
val availableBitrates: List<VideoBitratePreset> = VideoBitratePreset.entries.toList(),
val availableCodecs: List<VideoCodec> = VideoCodec.entries.toList(),
val previewSizesByResolution: Map<VideoResolutionPreset, Size> = emptyMap(),
val recordingSizesByResolution: Map<VideoResolutionPreset, Size> = emptyMap(),
val openGatePortraitAspectRatio: Float = 3f / 4f,
val availableStabilizationModes: List<VideoStabilizationMode> = emptyList(),
val supportsTorch: Boolean = false,
@@ -150,13 +151,15 @@ data class VideoCapabilities(
data class VideoRecordingState(
val isRecording: Boolean = false,
val isPaused: Boolean = false,
val isProcessing: Boolean = false,
val elapsedMs: Long = 0L
)
data class VideoCapabilitySnapshot(
val config: VideoConfig,
val capabilities: VideoCapabilities,
val previewSize: Size
val previewSize: Size,
val recordingSize: Size
)
fun resolveOpenGatePortraitAspectRatio(
@@ -392,7 +392,6 @@ class CameraViewModel(application: Application) : AndroidViewModel(application)
val state: StateFlow<CameraState> = cameraController.state
val livePhotoRecorder get() = cameraController.livePhotoRecorder
val videoRecorder get() = cameraController.videoRecorder
// 照片保存完成事件
private val _imageSavedEvent = MutableSharedFlow<Unit>()
@@ -1940,7 +1939,6 @@ class CameraViewModel(application: Application) : AndroidViewModel(application)
} else {
view.setAperture(0f)
}
view.setVideoRecorder(cameraController.videoRecorder)
view.setVideoLogProfile(currentState.videoConfig.logProfile)
view.setIsHlgInput(shouldTreatPreviewAsHlgInput(currentState))
currentState.focusPoint?.let { fp ->
@@ -2359,7 +2357,6 @@ class CameraViewModel(application: Application) : AndroidViewModel(application)
0f
})
view.setColorRecipeEnabled(!currentRecipeParams.value.isDefault())
view.setVideoRecorder(cameraController.videoRecorder)
view.setVideoLogProfile(currentState.videoConfig.logProfile)
view.setIsHlgInput(shouldTreatPreviewAsHlgInput(currentState))
view.restoreRenderStateAfterResume()
@@ -2730,10 +2727,23 @@ class CameraViewModel(application: Application) : AndroidViewModel(application)
}
if (state.value.captureMode == CaptureMode.VIDEO) {
if (state.value.videoRecordingState.isProcessing) {
return
}
if (state.value.videoRecordingState.isRecording) {
cameraController.stopVideoRecording()
} else {
cameraController.startVideoRecording()
val currentState = state.value
val orientationOffset = userPreferences.value.cameraOrientationOffsets[
currentState.currentCameraId
] ?: 0
cameraController.startVideoRecording(
creativeLutConfig = currentLutConfig.takeIf { currentState.lutEnabled },
creativeRecipeParams = getMergedRecipeParams(),
baselineLutConfig = currentBaselineLutConfig,
baselineRecipeParams = currentBaselineRecipeParams.value,
orientationOffsetDegrees = orientationOffset
)
}
return
}
@@ -0,0 +1,35 @@
package com.hinnka.mycamera.lut
import org.junit.Assert.assertFalse
import org.junit.Assert.assertTrue
import org.junit.Test
class RealtimeVideoRendererTransformTest {
@Test
fun identityAndFlipDoNotSwapAxes() {
assertFalse(
isTextureTransformAxesSwapped(
floatArrayOf(
1f, 0f, 0f, 0f,
0f, -1f, 0f, 0f,
0f, 0f, 1f, 0f,
0f, 1f, 0f, 1f,
)
)
)
}
@Test
fun quarterTurnSwapsAxes() {
assertTrue(
isTextureTransformAxesSwapped(
floatArrayOf(
0f, 1f, 0f, 0f,
1f, 0f, 0f, 0f,
0f, 0f, 1f, 0f,
0f, 0f, 0f, 1f,
)
)
)
}
}
@@ -0,0 +1,23 @@
package com.hinnka.mycamera.video
import org.junit.Assert.assertEquals
import org.junit.Test
class VideoOrientationTest {
@Test
fun portraitDoesNotReapplySensorOrientation() {
assertEquals(0, resolveSurfaceTextureVideoOrientationDegrees(0, 0))
}
@Test
fun landscapeUsesDeviceDisplayRotation() {
assertEquals(90, resolveSurfaceTextureVideoOrientationDegrees(90, 0))
assertEquals(270, resolveSurfaceTextureVideoOrientationDegrees(270, 0))
}
@Test
fun cameraCalibrationOffsetIsAppliedAndNormalized() {
assertEquals(0, resolveSurfaceTextureVideoOrientationDegrees(270, 90))
assertEquals(270, resolveSurfaceTextureVideoOrientationDegrees(0, -90))
}
}