feat: video input processing mode and shared EIS RGB pipeline

This commit is contained in:
zhoubinjia committed 2026-11-12 16:00:48 +08:00
1 parent e657e62e87
commit 27122c19e4
31 files changed
+1621 -750

No files matched your search

+26 -21
View File
@@ -31,6 +31,25 @@ jlong toHardwareBufferImageJlong(HardwareBufferEglImage *value) {
return static_cast<jlong>(reinterpret_cast<uintptr_t>(value));
}
bool bindHardwareBufferImage(jlong image_handle, jint texture_id, GLenum target) {
auto *source = fromHardwareBufferImageJlong(image_handle);
if (!source || source->display != eglGetCurrentDisplay() || texture_id == 0) {
return false;
}
const auto bind_image =
eglProcedure<PFNGLEGLIMAGETARGETTEXTURE2DOESPROC>("glEGLImageTargetTexture2DOES");
if (!bind_image) return false;
glBindTexture(target, static_cast<GLuint>(texture_id));
bind_image(target, source->image);
const GLenum error = glGetError();
if (error != GL_NO_ERROR) {
__android_log_print(ANDROID_LOG_WARN, kLogTag,
"EGLImage texture bind failed: target=0x%x, error=0x%x", target, error);
return false;
}
return true;
}
} // namespace
extern "C" JNIEXPORT jlong JNICALL
@@ -88,27 +107,13 @@ Java_com_hinnka_mycamera_processor_GlesHardwareBufferImage_create(
extern "C" JNIEXPORT jboolean JNICALL
Java_com_hinnka_mycamera_processor_GlesHardwareBufferImage_bind(
JNIEnv *, jobject, jlong image_handle, jint texture_id) {
auto *source = fromHardwareBufferImageJlong(image_handle);
if (!source || source->display != eglGetCurrentDisplay() || texture_id == 0) {
return JNI_FALSE;
}
const auto bind_image = eglProcedure<PFNGLEGLIMAGETARGETTEXTURE2DOESPROC>(
"glEGLImageTargetTexture2DOES");
if (!bind_image) {
__android_log_print(ANDROID_LOG_WARN, kLogTag,
"glEGLImageTargetTexture2DOES unavailable");
return JNI_FALSE;
}
glBindTexture(GL_TEXTURE_EXTERNAL_OES, static_cast<GLuint>(texture_id));
bind_image(GL_TEXTURE_EXTERNAL_OES, source->image);
const GLenum error = glGetError();
if (error != GL_NO_ERROR) {
__android_log_print(ANDROID_LOG_WARN, kLogTag,
"EGLImage external texture bind failed: 0x%x",
error);
return JNI_FALSE;
}
return JNI_TRUE;
return bindHardwareBufferImage(image_handle, texture_id, GL_TEXTURE_EXTERNAL_OES);
}
extern "C" JNIEXPORT jboolean JNICALL
Java_com_hinnka_mycamera_processor_GlesHardwareBufferImage_bind2D(
JNIEnv *, jobject, jlong image_handle, jint texture_id) {
return bindHardwareBufferImage(image_handle, texture_id, GL_TEXTURE_2D);
}
extern "C" JNIEXPORT void JNICALL
@@ -1,5 +1,9 @@
package com.hinnka.mycamera.camera
import com.hinnka.mycamera.BuildConfig
import com.hinnka.mycamera.video.VideoInputMode
import com.hinnka.mycamera.video.VideoPipelineSettings
import com.hinnka.mycamera.lut.SharedEisRgbFrameChannel
import android.annotation.SuppressLint
import android.content.Context
import android.graphics.ColorSpace
@@ -278,11 +282,11 @@ 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. */
/** Shared photo/video YUV input; [previewSurface] is this reader's surface. */
private var previewYuvReader: StabilizationImageReader? = null
private var videoPreviewSurfaceSize: Size? = null
val previewYuvChannel = PreviewYuvFrameChannel()
private var imageReader: ImageReader? = null
private var stabilizationImageReader: StabilizationImageReader? = null
// 降噪等级 (0=Off, 1=Fast, 2=High Quality, 3=ZSL, 4=Minimal)
private var nrLevel = NoiseReductionLevel.DEFAULT
@@ -343,6 +347,8 @@ class Camera2Controller(private val context: Context) {
private var availableCaptureRequestKeyNames: Set<String>? = null
private var availableAeModes: IntArray = intArrayOf()
private var availableAwbModes: IntArray = intArrayOf()
private val videoTimingDiagnosticsEnabled = BuildConfig.DEBUG &&
com.hinnka.mycamera.utils.SystemPropertiesUtil.get("debug.photon.video.timing") == "true"
private var videoCaptureStatsWindowStartMs: Long = 0L
private var videoCaptureStatsFrames: Int = 0
private var videoCaptureStatsFirstTimestampNs: Long = 0L
@@ -365,7 +371,8 @@ class Camera2Controller(private val context: Context) {
// Live Photo 录制器
val livePhotoRecorder = LivePhotoRecorder(context)
val realtimeStabilizationCoordinator = RealtimeStabilizationCoordinator(context)
val videoRecorder = VideoRecorder(context, realtimeStabilizationCoordinator)
val sharedEisRgbFrames = SharedEisRgbFrameChannel()
val videoRecorder = VideoRecorder(context, realtimeStabilizationCoordinator, sharedEisRgbFrames)
var onEnhancedStabilizationUnavailable: ((EnhancedStabilizationFallback) -> Unit)? = null
var onVideoSaved: ((Uri?) -> Unit)? = null
private var previousVideoStabilizationMode = VideoStabilizationMode.OIS
@@ -1317,7 +1324,8 @@ class Camera2Controller(private val context: Context) {
private var lastAfState: Int? = null
private fun logVideoCaptureStats(result: TotalCaptureResult) {
if (!_state.value.videoRecordingState.isRecording) return
if (_state.value.captureMode != CaptureMode.VIDEO) return
if (!_state.value.videoRecordingState.isRecording && !videoTimingDiagnosticsEnabled) return
val sensorTimestampNs = result.get(CaptureResult.SENSOR_TIMESTAMP) ?: return
val nowMs = SystemClock.elapsedRealtime()
@@ -2168,13 +2176,13 @@ class Camera2Controller(private val context: Context) {
if (closeImageReader) {
safeCloseImageReader(imageReader)
imageReader = null
closeStabilizationImageReader()
}
}
private fun safeReleasePreviewSurface(reason: String) {
val surface = previewSurface
val yuvReader = previewYuvReader
videoPreviewSurfaceSize = null
previewSurface = null
previewSurfaceTexture = null
previewYuvReader = null
@@ -2202,26 +2210,30 @@ class Camera2Controller(private val context: Context) {
).also { reader ->
reader.setOnImageAvailableListener(handler) { source ->
val stabilize = shouldUseAlgorithmicStabilization()
val recordYuv = _state.value.captureMode == CaptureMode.VIDEO && videoRecorder.acceptsYuvFrames
val fifo = stabilize || recordYuv
while (true) {
val image = try {
// EIS requires every boundary; ordinary preview only needs the latest.
if (stabilize) source.acquireNextImage() else source.acquireLatestImage()
// EIS and recording require FIFO; preview alone only needs the latest.
if (fifo) source.acquireNextImage() else source.acquireLatestImage()
} catch (error: IllegalStateException) {
PLog.w(TAG, "Cannot acquire photo preview YUV image: ${error.message}")
PLog.w(TAG, "Cannot acquire shared preview YUV image: ${error.message}")
null
} ?: break
if (stabilize) {
submitCurrentStabilizationImage(image)
} else {
// Retain before publishing: preview may immediately consume and close its lease.
if (recordYuv) videoRecorder.submitYuvFrame(image.retain())
previewYuvChannel.publish(image)
break
if (!fifo) break
}
}
}
previewYuvReader = reader
stabilizationInputStatsFirstTimestampNs = 0L
stabilizationInputStatsFrames = 0
PLog.i(TAG, "Shared photo preview YUV input configured: ${size.width}x${size.height}")
PLog.i(TAG, "Shared preview/recording YUV input configured: ${size.width}x${size.height}")
}
}
@@ -2410,11 +2422,9 @@ class Camera2Controller(private val context: Context) {
}
private fun refreshVideoCapabilities(characteristics: CameraCharacteristics? = null): Size {
val openGeneration = cameraOpenGeneration
val openCameraId = getCurrentOpenCameraId()
if (openCameraId.isEmpty()) {
return _state.value.currentPreviewSize
}
if (openCameraId.isEmpty()) return _state.value.currentPreviewSize
val resolvedCharacteristics = characteristics
?: getCameraCharacteristicsOrNull(openCameraId, "video capabilities")
if (resolvedCharacteristics == null) {
@@ -2422,70 +2432,74 @@ class Camera2Controller(private val context: Context) {
return _state.value.currentPreviewSize
}
// Capability resolution may overlap a camera-thread pipeline change. All decisions
// must refer to this request, never to a newer stabilization mode in _state.
val requestedConfig = _state.value.videoConfig
val cameraSupported = realtimeStabilizationCoordinator.isCameraSupported(resolvedCharacteristics)
val runtimeUnavailable = isEnhancedStabilizationUnavailableForCurrentCamera()
val snapshot = VideoCapabilitiesResolver.resolve(
characteristics = resolvedCharacteristics,
requestedConfig = requestedConfig,
algorithmicStabilizationSupported =
realtimeStabilizationCoordinator.isCameraSupported(resolvedCharacteristics) &&
!isEnhancedStabilizationUnavailableForCurrentCamera(),
algorithmicStabilizationSupported = cameraSupported && !runtimeUnavailable,
)
if (snapshot.config.logProfile != requestedConfig.logProfile) {
PLog.w(
TAG,
"Video Log capability resolved: camera=$openCameraId, " +
"requested=${requestedConfig.logProfile.name}, resolved=${snapshot.config.logProfile.name}, " +
"available=${snapshot.capabilities.availableLogProfiles.map { it.name }}, " +
"lifecycle=$cameraDeviceLifecycle"
)
}
if (_state.value.videoConfig.stabilizationMode == VideoStabilizationMode.ENHANCED) {
val enhancedInput = snapshot.capabilities
.enhancedStabilizationInputSizesByResolution[snapshot.config.resolution]
if (snapshot.config.stabilizationMode == VideoStabilizationMode.ENHANCED) {
PLog.i(
TAG,
"EIS+ capability accepted: resolution=${snapshot.config.resolution.displayName}, " +
"fps=${snapshot.config.fps.fps}, yuvInput=$enhancedInput"
)
} else {
PLog.e(
TAG,
"EIS+ capability rejected: resolution=${snapshot.config.resolution.displayName}, " +
"fps=${snapshot.config.fps.fps}, yuvInput=$enhancedInput, " +
"reason=missing YUV output for the selected resolution"
)
}
}
val enhancedFallbackMode = if (
_state.value.videoConfig.stabilizationMode == VideoStabilizationMode.ENHANCED &&
requestedConfig.stabilizationMode == VideoStabilizationMode.ENHANCED &&
snapshot.config.stabilizationMode != VideoStabilizationMode.ENHANCED
) {
resolvePreviousVideoStabilizationMode(
snapshot.capabilities.availableStabilizationModes
)
} else {
null
}
val resolvedConfig = enhancedFallbackMode?.let { fallbackMode ->
snapshot.config.copy(stabilizationMode = fallbackMode)
} ?: snapshot.config
_state.value = _state.value.copy(
videoConfig = resolvedConfig,
videoCapabilities = snapshot.capabilities,
currentPreviewSize = if (_state.value.captureMode == CaptureMode.VIDEO) {
snapshot.previewSize
} else {
_state.value.currentPreviewSize
resolvePreviousVideoStabilizationMode(snapshot.capabilities.availableStabilizationModes)
} else null
val resolvedConfig = enhancedFallbackMode?.let { snapshot.config.copy(stabilizationMode = it) }
?: snapshot.config
// Commit only while the input configuration and camera still match. An old OFF/OES
// calculation must not overwrite a newer EIS+/YUV selection or publish a fallback.
while (true) {
val current = _state.value
if (current.videoConfig != requestedConfig || cameraOpenGeneration != openGeneration ||
getCurrentOpenCameraId() != openCameraId ||
isEnhancedStabilizationUnavailableForCurrentCamera() != runtimeUnavailable
) {
PLog.d(TAG, "Discarding stale video capabilities: requested=${requestedConfig.stabilizationMode}/" +
"${requestedConfig.effectiveInputMode}, current=${current.videoConfig.stabilizationMode}/" +
"${current.videoConfig.effectiveInputMode}")
return current.currentPreviewSize
}
)
val updated = current.copy(
videoConfig = resolvedConfig,
videoCapabilities = snapshot.capabilities,
currentPreviewSize = if (current.captureMode == CaptureMode.VIDEO) snapshot.previewSize
else current.currentPreviewSize,
)
if (_state.compareAndSet(current, updated)) break
}
if (snapshot.config.logProfile != requestedConfig.logProfile) {
PLog.w(TAG, "Video Log capability resolved: camera=$openCameraId, " +
"requested=${requestedConfig.logProfile.name}, resolved=${snapshot.config.logProfile.name}, " +
"available=${snapshot.capabilities.availableLogProfiles.map { it.name }}, " +
"lifecycle=$cameraDeviceLifecycle")
}
if (requestedConfig.stabilizationMode == VideoStabilizationMode.ENHANCED) {
val enhancedInput = snapshot.capabilities.enhancedStabilizationInputSizesByResolution[
snapshot.config.resolution
]
if (enhancedFallbackMode == null) {
PLog.i(TAG, "EIS+ capability accepted: resolution=${resolvedConfig.resolution.displayName}, " +
"fps=${resolvedConfig.fps.fps}, yuvInput=$enhancedInput")
} else {
val reason = when {
runtimeUnavailable -> "previous runtime stabilization failure for this camera"
!cameraSupported -> "camera calibration, timestamp source or gyroscope unsupported"
enhancedInput == null -> "missing YUV output for the selected resolution"
else -> "requested stabilization mode unavailable"
}
PLog.e(TAG, "EIS+ capability rejected: resolution=${resolvedConfig.resolution.displayName}, " +
"fps=${resolvedConfig.fps.fps}, yuvInput=$enhancedInput, reason=$reason")
}
}
if (enhancedFallbackMode != null) {
previousVideoStabilizationMode = enhancedFallbackMode
notifyEnhancedStabilizationUnavailable(
EnhancedStabilizationFallback.Video(enhancedFallbackMode)
)
notifyEnhancedStabilizationUnavailable(EnhancedStabilizationFallback.Video(enhancedFallbackMode))
}
return snapshot.previewSize
}
@@ -2820,8 +2834,11 @@ class Camera2Controller(private val context: Context) {
// 拍照模式的预览 Surface 是 YUV ImageReader,在下面确定最终预览尺寸后创建
previewSurfaceTexture = surfaceTexture
if (captureMode != CaptureMode.PHOTO) {
previewSurface = Surface(surfaceTexture)
if (captureMode == CaptureMode.VIDEO) {
previewSurface = if (_state.value.videoConfig.effectiveInputMode == VideoInputMode.YUV) {
createPreviewYuvReader(previewSize).surface
} else Surface(surfaceTexture)
videoPreviewSurfaceSize = previewSize
}
if (captureMode == CaptureMode.PHOTO) {
@@ -3171,6 +3188,27 @@ class Camera2Controller(private val context: Context) {
}
}
/** Recreate the consumer when its format or size changes, including EIS+ transitions. */
private fun configureVideoPreviewSurface() {
if (_state.value.captureMode != CaptureMode.VIDEO) return
val texture = previewSurfaceTexture ?: return
val size = _state.value.currentPreviewSize
val usesYuv = _state.value.videoConfig.effectiveInputMode == VideoInputMode.YUV
if (previewSurface != null && (previewYuvReader != null) == usesYuv &&
videoPreviewSurfaceSize == size
) return
val oldSession = captureSession
invalidateCaptureSession(oldSession, "video input changed")
safeCloseCaptureSession(oldSession, "video input changed")
clearStabilizationInput()
safeReleasePreviewSurface("video input changed")
previewSurfaceTexture = texture
texture.setDefaultBufferSize(size.width, size.height)
previewSurface = if (usesYuv) createPreviewYuvReader(size).surface else Surface(texture)
videoPreviewSurfaceSize = size
PLog.i(TAG, "Video preview input configured: ${_state.value.videoConfig.effectiveInputMode}, size=$size")
}
private fun createPreviewSession(
forceWithoutVendorSessionParameters: Boolean = false,
openGeneration: Long = cameraOpenGeneration
@@ -3185,27 +3223,28 @@ class Camera2Controller(private val context: Context) {
return
}
val device = cameraDevice ?: return
try {
configureVideoPreviewSurface()
} catch (error: Exception) {
handlePreviewSessionFailure("configure video input", openGeneration, error)
return
}
val surface = previewSurface ?: return
// createCaptureSession closes the previous session before onConfigured runs.
// Stop exposing it while the replacement is being configured.
invalidateCaptureSession(captureSession, "preview session replacement")
val captureMode = _state.value.captureMode
val reader = imageReader
val stabilizationReader = ensureStabilizationImageReader()
val stabilizationInput = if (shouldUseAlgorithmicStabilization()) {
if (captureMode == CaptureMode.PHOTO) previewYuvReader else stabilizationReader
previewYuvReader
} else {
null
}
val useEnhancedStabilization = shouldUseVideoEnhancedStabilization()
val videoSurface = if (
captureMode == CaptureMode.VIDEO &&
_state.value.videoRecordingState.shouldAttachCameraInput() &&
!useEnhancedStabilization
) {
videoRecorder.cameraInputSurface
} else {
null
// Keep the recorder surface configured while paused; only repeating targets change.
val videoSurface = videoRecorder.cameraInputSurface.takeIf {
captureMode == CaptureMode.VIDEO && _state.value.videoRecordingState.isRecording &&
_state.value.videoConfig.effectiveInputMode == VideoInputMode.OES
}
val sessionGeneration = ++previewSessionGeneration
pendingVendorSessionParameterRestart = false
@@ -3220,7 +3259,7 @@ class Camera2Controller(private val context: Context) {
PLog.i(
TAG,
"Creating repeating request: " +
"template=${if (templateType == CameraDevice.TEMPLATE_PREVIEW) "PREVIEW" else "RECORD"}, " +
"outputs=${if (captureMode == CaptureMode.VIDEO && videoSurface == null) 1 else 2}, input=${if (previewYuvReader != null) "YUV_420_888" else "OES"}, template=${if (templateType == CameraDevice.TEMPLATE_PREVIEW) "PREVIEW" else "RECORD"}, " +
"captureMode=$captureMode, enhancedStabilization=$useEnhancedStabilization"
)
var vendorSessionParametersApplied = false
@@ -3228,15 +3267,14 @@ class Camera2Controller(private val context: Context) {
try {
previewRequestBuilder = device.createCaptureRequest(templateType).apply {
addTarget(surface)
stabilizationReader?.surface?.let(::addTarget)
videoSurface?.let(::addTarget)
videoSurface?.takeIf { _state.value.videoRecordingState.shouldAttachCameraInput() }
?.let(::addTarget)
// 应用所有相机参数(曝光、白平衡、闪光灯、变焦)
applyBaseCameraSettings(this, isCapture = false)
}
val surfaces = mutableListOf(surface)
stabilizationReader?.surface?.let(surfaces::add)
videoSurface?.let(surfaces::add)
if (captureMode == CaptureMode.PHOTO) {
val captureReader = reader ?: return
@@ -3248,19 +3286,14 @@ class Camera2Controller(private val context: Context) {
PLog.i(
TAG,
"Creating video session: operatingMode=0x${sessionOperatingMode.toString(16)}, " +
"oppoSuperStabilization=$oppoSuperStabilizationEnabled, " +
"oppoSuperStabilization=${isOppoSuperStabilizationActive()}, " +
"lensFacing=${if (isCurrentCameraFrontFacing()) "front" else "rear"}"
)
val sessionConfig = SessionConfiguration(
sessionOperatingMode,
buildList {
add(createOutputConfiguration(surface))
stabilizationReader?.surface?.let { eisSurface ->
add(createOutputConfiguration(eisSurface))
}
videoSurface?.let { encoderSurface ->
add(createOutputConfiguration(encoderSurface))
}
videoSurface?.let { add(createOutputConfiguration(it)) }
},
Executor { handler.post(it) },
object : CameraCaptureSession.StateCallback() {
@@ -3274,7 +3307,6 @@ class Camera2Controller(private val context: Context) {
safeCloseCaptureSession(session, "stale video preview session")
return
}
closeUnusedStabilizationImageReader(stabilizationReader)
onSessionConfigured(session, openGeneration, sessionGeneration, stabilizationInput)
}
@@ -3319,9 +3351,6 @@ class Camera2Controller(private val context: Context) {
)
val outputConfigs = buildList {
add(createOutputConfiguration(surface))
stabilizationReader?.surface?.let { eisSurface ->
add(createOutputConfiguration(eisSurface))
}
reader?.surface?.let { captureSurface ->
add(createOutputConfiguration(captureSurface))
}
@@ -3341,7 +3370,6 @@ class Camera2Controller(private val context: Context) {
safeCloseCaptureSession(session, "stale preview session")
return
}
closeUnusedStabilizationImageReader(stabilizationReader)
onSessionConfigured(session, openGeneration, sessionGeneration, stabilizationInput)
}
@@ -3425,44 +3453,6 @@ class Camera2Controller(private val context: Context) {
}
}
private fun ensureStabilizationImageReader(): StabilizationImageReader? {
val handler = cameraHandler ?: return null
val state = _state.value
// Photo mode feeds EIS from previewYuvReader; only video needs a separate input.
if (state.captureMode != CaptureMode.VIDEO || !shouldUseAlgorithmicStabilization()) return null
val size = state.videoCapabilities
.enhancedStabilizationInputSizesByResolution[state.videoConfig.resolution]
?: return null
if (size.width <= 0 || size.height <= 0) return null
stabilizationImageReader?.let { existing ->
if (existing.width == size.width && existing.height == size.height) {
return existing
}
closeStabilizationImageReader()
}
return StabilizationImageReader(
size.width,
size.height,
RealtimeStabilizationCoordinator.STABILIZATION_IMAGE_READER_MAX_IMAGES,
).also { reader ->
reader.setOnImageAvailableListener(handler) { source ->
while (true) {
val image = try {
source.acquireNextImage()
} catch (error: IllegalStateException) {
PLog.e(TAG, "Cannot acquire MGC YUV image", error)
null
} ?: break
submitCurrentStabilizationImage(image)
}
}
stabilizationImageReader = reader
stabilizationInputStatsFirstTimestampNs = 0L
stabilizationInputStatsFrames = 0
PLog.i(TAG, "MGC YUV input configured: ${size.width}x${size.height}")
}
}
private fun submitCurrentStabilizationResult(
session: CameraCaptureSession,
request: CaptureRequest,
@@ -3652,20 +3642,6 @@ class Camera2Controller(private val context: Context) {
}
}
private fun closeUnusedStabilizationImageReader(activeReader: StabilizationImageReader?) {
if (activeReader != null) return
closeStabilizationImageReader()
}
private fun closeStabilizationImageReader() {
val reader = stabilizationImageReader ?: return
stabilizationImageReader = null
// Stop acquisition first, then release queued frames. Renderer leases retain both
// their source image and its reader until the upload/sampling has finished.
reader.close()
realtimeStabilizationCoordinator.discardStabilizationImages(reader)
}
private fun retryPreviewSessionWithoutVendorSessionParameters(
reason: String,
openGeneration: Long
@@ -3761,7 +3737,9 @@ class Camera2Controller(private val context: Context) {
null
}
val shouldApplyStandardSessionParameters =
val shouldApplyVideoQualitySessionParameters = state.captureMode == CaptureMode.VIDEO &&
sessionKeys?.contains(CaptureRequest.NOISE_REDUCTION_MODE) == true
val shouldApplyStandardSessionParameters = shouldApplyVideoQualitySessionParameters ||
sessionKeys?.contains(CaptureRequest.CONTROL_VIDEO_STABILIZATION_MODE) == true ||
sessionKeys?.contains(CaptureRequest.LENS_OPTICAL_STABILIZATION_MODE) == true
val vendorSessionValues = if (includeVendorSessionParameters) {
@@ -3788,6 +3766,9 @@ class Camera2Controller(private val context: Context) {
if (shouldApplyStandardSessionParameters) {
applyStabilizationSettings(builder, state)
}
if (shouldApplyVideoQualitySessionParameters) {
applyImageQualitySettings(builder, state)
}
if (vendorSessionValues.isNotEmpty()) {
applyVendorCaptureSettings(
builder = builder,
@@ -3954,8 +3935,7 @@ class Camera2Controller(private val context: Context) {
scheduleEnhancedStabilizationInputWatchdog(sessionGeneration)
}
if (_state.value.captureMode == CaptureMode.VIDEO &&
_state.value.videoRecordingState.shouldAttachCameraInput() &&
videoRecorder.cameraInputSurface != null
_state.value.videoRecordingState.shouldAttachCameraInput()
) {
if (videoRecorder.onCameraInputStarted()) {
startVideoRecordingTicker()
@@ -5252,7 +5232,9 @@ class Camera2Controller(private val context: Context) {
try {
val isVideo = currentState.captureMode == CaptureMode.VIDEO
val selectedEdgeLevel = if (isVideo) videoEdgeLevel else edgeLevel
val selectedNrLevel = if (isVideo) videoNrLevel else nrLevel
val selectedNrLevel = if (isVideo) {
currentState.videoConfig.effectiveInputMode.resolveNoiseReduction(videoNrLevel)
} else nrLevel
val isBurst = !isVideo && currentState.requiresMultiFrameCaptureSequence
val effectiveEdgeLevel = if (isBurst && selectedEdgeLevel == 2) 1 else selectedEdgeLevel
val edgeMode = when (effectiveEdgeLevel) {
@@ -5301,6 +5283,8 @@ class Camera2Controller(private val context: Context) {
builder.set(CaptureRequest.NOISE_REDUCTION_MODE, noiseReductionMode)
} else if (availableNoiseReductionModes.contains(CaptureRequest.NOISE_REDUCTION_MODE_FAST)) {
builder.set(CaptureRequest.NOISE_REDUCTION_MODE, CaptureRequest.NOISE_REDUCTION_MODE_FAST)
} else if (isVideo && currentState.videoConfig.effectiveInputMode == VideoInputMode.YUV) {
builder.set(CaptureRequest.NOISE_REDUCTION_MODE, CaptureRequest.NOISE_REDUCTION_MODE_OFF)
}
} catch (e: Exception) {
PLog.e(TAG, "Failed to apply image quality settings", e)
@@ -5413,28 +5397,6 @@ class Camera2Controller(private val context: Context) {
_state.value = _state.value.copy(nrLevel = normalizedLevel)
}
fun setVideoImageQualitySettings(nrLevel: Int, edgeLevel: Int) {
val handler = cameraHandler
if (handler != null && Looper.myLooper() != handler.looper) {
handler.post { setVideoImageQualitySettings(nrLevel, edgeLevel) }
return
}
val normalizedNrLevel = NoiseReductionLevel.normalize(nrLevel)
if (videoNrLevel == normalizedNrLevel && videoEdgeLevel == edgeLevel) return
videoNrLevel = normalizedNrLevel
videoEdgeLevel = edgeLevel
PLog.d(TAG, "Video image quality settings: nr=$videoNrLevel, edge=$videoEdgeLevel")
val currentState = _state.value
if (currentState.captureMode == CaptureMode.VIDEO) {
previewRequestBuilder?.let { builder ->
applyImageQualitySettings(builder, currentState)
updatePreview()
}
}
}
fun setVendorCaptureSettingsByLens(settingsByLens: VendorCaptureSettingsByLens) {
val handler = cameraHandler
if (handler != null && Looper.myLooper() != handler.looper) {
@@ -6999,24 +6961,19 @@ class Camera2Controller(private val context: Context) {
) {
return
}
val nextVideoConfig = if (mode == CaptureMode.VIDEO) {
_state.value.videoConfig
} else {
_state.value.videoConfig.copy(logProfile = VideoLogProfile.OFF)
}
val nextState = _state.value.copy(
captureMode = mode,
videoConfig = nextVideoConfig,
countdownValue = 0,
isCapturingLivePhoto = false
).let { state ->
if (mode == CaptureMode.VIDEO) {
state.copy(shutterSpeed = coerceManualShutterSpeed(state, state.shutterSpeed))
} else {
state
_state.update { current ->
current.copy(
captureMode = mode,
videoConfig = if (mode == CaptureMode.VIDEO) current.videoConfig
else current.videoConfig.copy(logProfile = VideoLogProfile.OFF),
countdownValue = 0,
isCapturingLivePhoto = false,
).let { next ->
if (mode == CaptureMode.VIDEO) {
next.copy(shutterSpeed = coerceManualShutterSpeed(next, next.shutterSpeed))
} else next
}
}
_state.value = nextState
if (mode == CaptureMode.VIDEO) {
livePhotoRecorder.stopRecording()
refreshVideoCapabilities()
@@ -7032,22 +6989,12 @@ class Camera2Controller(private val context: Context) {
private var resolutionBeforeOpenGate: VideoResolutionPreset? = null
fun setVideoResolution(resolution: VideoResolutionPreset) {
val currentConfig = _state.value.videoConfig
_state.value = _state.value.copy(
videoConfig = currentConfig.copy(
resolution = resolution,
)
)
_state.update { it.copy(videoConfig = it.videoConfig.copy(resolution = resolution)) }
refreshVideoCapabilities()
}
fun setVideoFps(fps: VideoFpsPreset) {
val currentConfig = _state.value.videoConfig
_state.value = _state.value.copy(
videoConfig = currentConfig.copy(
fps = fps,
)
)
_state.update { it.copy(videoConfig = it.videoConfig.copy(fps = fps)) }
refreshVideoCapabilities()
previewRequestBuilder?.apply {
applyBaseCameraSettings(this, isCapture = false)
@@ -7070,15 +7017,13 @@ class Camera2Controller(private val context: Context) {
resolutionBeforeOpenGate ?: currentConfig.resolution
else -> currentConfig.resolution
}
_state.value = _state.value.copy(
videoConfig = currentConfig.copy(aspectRatio = aspectRatio, resolution = resolution)
)
_state.update { it.copy(videoConfig = it.videoConfig.copy(aspectRatio = aspectRatio, resolution = resolution)) }
refreshVideoCapabilities()
}
fun setVideoLogLutMode(mode: VideoLogLutMode) {
if (_state.value.videoRecordingState.isRecording || _state.value.videoRecordingState.isProcessing) return
_state.value = _state.value.copy(videoConfig = _state.value.videoConfig.copy(logLutMode = mode))
_state.update { it.copy(videoConfig = it.videoConfig.copy(logLutMode = mode)) }
}
fun setVideoLogProfile(logProfile: VideoLogProfile) {
@@ -7088,7 +7033,7 @@ class Camera2Controller(private val context: Context) {
} else {
VideoLogProfile.OFF
}
_state.value = _state.value.copy(videoConfig = _state.value.videoConfig.copy(logProfile = resolvedProfile))
_state.update { it.copy(videoConfig = it.videoConfig.copy(logProfile = resolvedProfile)) }
refreshVideoCapabilities()
val appliedProfile = _state.value.videoConfig.logProfile
if (previousProfile != appliedProfile || logProfile != appliedProfile) {
@@ -7105,106 +7050,86 @@ class Camera2Controller(private val context: Context) {
}
}
fun setVideoStabilizationMode(mode: VideoStabilizationMode) {
val previousConfig = _state.value.videoConfig
if (mode == VideoStabilizationMode.ENHANCED &&
isEnhancedStabilizationUnavailableForCurrentCamera()
) {
PLog.w(
TAG,
"Ignoring EIS+ selection because it was already verified unavailable for " +
currentStabilizationCameraId()
)
fun setVideoPipelineSettings(settings: VideoPipelineSettings) {
val handler = cameraHandler
if (handler != null && Looper.myLooper() != handler.looper) {
handler.post { setVideoPipelineSettings(settings) }
return
}
when {
mode == VideoStabilizationMode.ENHANCED &&
previousConfig.stabilizationMode != VideoStabilizationMode.ENHANCED -> {
previousVideoStabilizationMode = previousConfig.stabilizationMode
}
mode != VideoStabilizationMode.ENHANCED -> {
previousVideoStabilizationMode = mode
}
val state = _state.value
if (state.videoRecordingState.isRecording || state.videoRecordingState.isProcessing) return
val previousConfig = state.videoConfig
val mode = if (settings.stabilizationMode == VideoStabilizationMode.ENHANCED &&
isEnhancedStabilizationUnavailableForCurrentCamera()
) previousConfig.stabilizationMode else settings.stabilizationMode
val nextConfig = previousConfig.copy(inputMode = settings.inputMode, stabilizationMode = mode)
val qualityChanged = videoNrLevel != settings.noiseReduction || videoEdgeLevel != settings.edge
val vendorChanged = oppoSuperStabilizationEnabled != (settings.oppoSuperStabilization && DeviceUtil.isOppo)
if (mode != settings.stabilizationMode) {
notifyEnhancedStabilizationUnavailable(EnhancedStabilizationFallback.Video(mode))
}
if (nextConfig == previousConfig && !qualityChanged && !vendorChanged) return
if (mode == VideoStabilizationMode.ENHANCED && previousConfig.stabilizationMode != mode) {
previousVideoStabilizationMode = previousConfig.stabilizationMode
} else if (mode != VideoStabilizationMode.ENHANCED) {
previousVideoStabilizationMode = mode
}
videoNrLevel = NoiseReductionLevel.normalize(settings.noiseReduction)
videoEdgeLevel = settings.edge
oppoSuperStabilizationEnabled = settings.oppoSuperStabilization && DeviceUtil.isOppo
_state.update {
it.copy(videoConfig = it.videoConfig.copy(inputMode = settings.inputMode, stabilizationMode = mode))
}
_state.value = _state.value.copy(
videoConfig = previousConfig.copy(
stabilizationMode = mode,
)
)
refreshVideoCapabilities()
val resolvedConfig = _state.value.videoConfig
if (
mode == VideoStabilizationMode.ENHANCED &&
resolvedConfig.stabilizationMode != VideoStabilizationMode.ENHANCED
) {
PLog.e(
TAG,
"EIS+ rejected for ${resolvedConfig.resolution.displayName}@" +
"${resolvedConfig.fps.fps}: camera does not expose a matching YUV input"
)
}
val outputGeometryChanged = previousConfig.resolution != resolvedConfig.resolution ||
previousConfig.fps != resolvedConfig.fps
if (_state.value.captureMode == CaptureMode.VIDEO &&
!_state.value.videoRecordingState.isRecording &&
previousConfig.stabilizationMode != resolvedConfig.stabilizationMode &&
!outputGeometryChanged
) {
PLog.i(TAG, "Video pipeline: selected=${settings.inputMode}, input=${resolvedConfig.effectiveInputMode}, " +
"stabilization=${resolvedConfig.stabilizationMode}, nr=${resolvedConfig.effectiveInputMode.resolveNoiseReduction(videoNrLevel)}, " +
"oppoSuperStabilization=${isOppoSuperStabilizationActive()}")
if (state.captureMode != CaptureMode.VIDEO) return
val sessionChanged = previousConfig.effectiveInputMode != resolvedConfig.effectiveInputMode ||
previousConfig.stabilizationMode != resolvedConfig.stabilizationMode || vendorChanged
if (sessionChanged && cameraDevice != null && previewSurface != null) {
createPreviewSession()
return
}
previewRequestBuilder?.apply {
applyBaseCameraSettings(this, isCapture = false)
updatePreview()
}
}
fun setOppoSuperStabilizationEnabled(enabled: Boolean) {
val resolvedEnabled = enabled && DeviceUtil.isOppo
if (oppoSuperStabilizationEnabled == resolvedEnabled) return
oppoSuperStabilizationEnabled = resolvedEnabled
PLog.i(TAG, "OPPO super stabilization enabled=$resolvedEnabled")
if (_state.value.captureMode == CaptureMode.VIDEO &&
!_state.value.videoRecordingState.isRecording &&
cameraDevice != null && previewSurface != null
) {
createPreviewSession(openGeneration = cameraOpenGeneration)
} else {
previewRequestBuilder?.let {
applyBaseCameraSettings(it, isCapture = false)
updatePreview()
}
}
}
fun setVideoBitrate(bitrate: VideoBitratePreset) {
_state.value = _state.value.copy(videoConfig = _state.value.videoConfig.copy(bitrate = bitrate))
_state.update { it.copy(videoConfig = it.videoConfig.copy(bitrate = bitrate)) }
refreshVideoCapabilities()
}
fun setVideoCodec(codec: com.hinnka.mycamera.video.VideoCodec) {
_state.value = _state.value.copy(videoConfig = _state.value.videoConfig.copy(codec = codec))
_state.update { it.copy(videoConfig = it.videoConfig.copy(codec = codec)) }
refreshVideoCapabilities()
}
fun setVideoAudioInputId(audioInputId: String) {
val normalizedAudioInputId = audioInputId.ifBlank { VIDEO_AUDIO_INPUT_AUTO }
_state.value = _state.value.copy(
videoConfig = _state.value.videoConfig.copy(audioInputId = normalizedAudioInputId)
)
_state.update { current ->
current.copy(videoConfig = current.videoConfig.copy(audioInputId = normalizedAudioInputId))
}
videoRecorder.setPreferredAudioInputId(normalizedAudioInputId)
}
fun setVideoEnhancedStabilizationStrength(strength: Float) {
_state.value = _state.value.copy(
videoConfig = _state.value.videoConfig.copy(
_state.update { current ->
current.copy(videoConfig = current.videoConfig.copy(
enhancedStabilizationStrength = normalizeStabilizationStrength(strength)
)
)
))
}
}
fun setVideoEnhancedStabilizationLookahead(lookahead: Int) {
_state.value = _state.value.copy(
videoConfig = _state.value.videoConfig.copy(
_state.update { current ->
current.copy(videoConfig = current.videoConfig.copy(
enhancedStabilizationLookahead = normalizeStabilizationLookahead(lookahead)
)
)
))
}
}
fun setExternalLensStabilizationConfig(config: ExternalLensStabilizationConfig) {
@@ -7241,20 +7166,20 @@ class Camera2Controller(private val context: Context) {
}
fun setVideoRecordingPath(recordingPath: VideoRecordingPath, recordingTreeUri: String? = null) {
_state.value = _state.value.copy(
videoConfig = _state.value.videoConfig.copy(
_state.update { current ->
current.copy(videoConfig = current.videoConfig.copy(
recordingPath = recordingPath,
recordingTreeUri = recordingTreeUri?.takeIf { it.isNotBlank() }
)
)
))
}
}
fun setVideoTorchEnabled(enabled: Boolean) {
_state.value = _state.value.copy(
videoConfig = _state.value.videoConfig.copy(
torchEnabled = enabled && _state.value.videoCapabilities.supportsTorch
)
)
_state.update { current ->
current.copy(videoConfig = current.videoConfig.copy(
torchEnabled = enabled && current.videoCapabilities.supportsTorch
))
}
previewRequestBuilder?.apply {
applyBaseCameraSettings(this, isCapture = false)
updatePreview()
@@ -7263,16 +7188,16 @@ class Camera2Controller(private val context: Context) {
fun setVideoLensLockEnabled(enabled: Boolean) {
if (_state.value.videoConfig.lensLockEnabled == enabled) return
_state.value = _state.value.copy(
videoConfig = _state.value.videoConfig.copy(lensLockEnabled = enabled)
)
_state.update { current ->
current.copy(videoConfig = current.videoConfig.copy(lensLockEnabled = enabled))
}
}
fun setVideoWhiteBalanceLockEnabled(enabled: Boolean) {
if (_state.value.videoConfig.whiteBalanceLockEnabled == enabled) return
_state.value = _state.value.copy(
videoConfig = _state.value.videoConfig.copy(whiteBalanceLockEnabled = enabled)
)
_state.update { current ->
current.copy(videoConfig = current.videoConfig.copy(whiteBalanceLockEnabled = enabled))
}
previewRequestBuilder?.apply {
applyWhiteBalanceSettings(this, _state.value, isCapture = false)
updatePreview()
@@ -7318,6 +7243,9 @@ class Camera2Controller(private val context: Context) {
_state.value.videoConfig.resolution
]
} ?: _state.value.currentPreviewSize
if (_state.value.videoConfig.effectiveInputMode == VideoInputMode.YUV) {
check(cameraInputSize == _state.value.currentPreviewSize) { "Recording must use the configured shared YUV input" }
}
val outputSize = _state.value.videoConfig.resolveOutputSize(
_state.value.videoCapabilities.openGatePortraitAspectRatio,
cameraInputSize
@@ -7358,6 +7286,7 @@ class Camera2Controller(private val context: Context) {
?: cachedSensorOrientation,
orientationHintDegrees = resolveDedicatedVideoOrientationHintDegrees(orientationOffsetDegrees),
flipEncodedFrame = shouldFlipEncodedFrame,
inputMode = _state.value.videoConfig.effectiveInputMode,
enhancedStabilization = useEnhancedStabilization,
enhancedStabilizationStrength =
_state.value.videoConfig.enhancedStabilizationStrength,
@@ -7395,8 +7324,12 @@ class Camera2Controller(private val context: Context) {
_state.value.getCurrentCameraInfo()?.lensType == LensType.FRONT
}
private fun isOppoSuperStabilizationActive(): Boolean =
oppoSuperStabilizationEnabled && DeviceUtil.isOppo &&
_state.value.videoConfig.effectiveInputMode.allowsOppoSuperStabilization()
private fun resolveVideoSessionOperatingMode(): Int {
if (!oppoSuperStabilizationEnabled || !DeviceUtil.isOppo) {
if (!isOppoSuperStabilizationActive()) {
return SessionConfiguration.SESSION_REGULAR
}
return if (isCurrentCameraFrontFacing()) {
@@ -7458,10 +7391,10 @@ class Camera2Controller(private val context: Context) {
fun pauseVideoRecording() {
if (!_state.value.videoRecordingState.isRecording || _state.value.videoRecordingState.isPaused) return
if (_state.value.videoConfig.effectiveInputMode == VideoInputMode.OES &&
!updateOesVideoRepeatingTarget(false)
) return
videoRecorder.pauseRecording()
if (videoRecorder.usesDedicatedCameraInput) {
updateDedicatedVideoRepeatingTarget(includeVideoSurface = false)
}
videoRecordingPauseStartElapsedMs = SystemClock.elapsedRealtime()
_state.value = _state.value.copy(
videoRecordingState = _state.value.videoRecordingState.copy(isPaused = true)
@@ -7470,12 +7403,9 @@ 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
}
if (_state.value.videoConfig.effectiveInputMode == VideoInputMode.OES &&
!updateOesVideoRepeatingTarget(true)
) return
videoRecorder.resumeRecording()
videoRecordingPausedMs += SystemClock.elapsedRealtime() - videoRecordingPauseStartElapsedMs
_state.value = _state.value.copy(
@@ -7493,16 +7423,15 @@ class Camera2Controller(private val context: Context) {
videoRecordingState = _state.value.videoRecordingState.copy(
isRecording = false,
isPaused = false,
isProcessing = videoRecorder.usesDedicatedCameraInput
isProcessing = videoRecorder.isRecording()
)
)
if (videoRecorder.usesDedicatedCameraInput && !_state.value.videoRecordingState.isPaused) {
updateDedicatedVideoRepeatingTarget(includeVideoSurface = false)
} else {
previewRequestBuilder?.apply {
applyWhiteBalanceSettings(this, _state.value, isCapture = false)
updatePreview()
}
previewRequestBuilder?.apply {
applyWhiteBalanceSettings(this, _state.value, isCapture = false)
updatePreview()
}
if (_state.value.videoConfig.effectiveInputMode == VideoInputMode.OES) {
updateOesVideoRepeatingTarget(false)
}
videoRecorder.stopRecording()
if (pendingVendorSessionParameterRestart && cameraDevice != null && previewSurface != null) {
@@ -7511,46 +7440,23 @@ class Camera2Controller(private val context: Context) {
}
}
private fun updateDedicatedVideoRepeatingTarget(includeVideoSurface: Boolean): Boolean {
private fun updateOesVideoRepeatingTarget(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
val videoTarget = videoRecorder.cameraInputSurface
if (includeVideoSurface && videoTarget == null) return false
return try {
val useEnhancedStabilization = shouldUseVideoEnhancedStabilization()
val templateType = if (useEnhancedStabilization) {
CameraDevice.TEMPLATE_PREVIEW
} else {
CameraDevice.TEMPLATE_RECORD
}
PLog.i(
TAG,
"Updating dedicated video repeating request: " +
"template=${if (templateType == CameraDevice.TEMPLATE_PREVIEW) "PREVIEW" else "RECORD"}, " +
"enhancedStabilization=$useEnhancedStabilization, " +
"includeVideoSurface=$includeVideoSurface"
)
val builder = device.createCaptureRequest(templateType).apply {
val builder = device.createCaptureRequest(CameraDevice.TEMPLATE_RECORD).apply {
addTarget(previewTarget)
stabilizationImageReader?.surface
?.takeIf { useEnhancedStabilization }
?.let(::addTarget)
encoderTarget
?.takeIf { includeVideoSurface && !useEnhancedStabilization }
?.let(::addTarget)
if (includeVideoSurface) videoTarget?.let(::addTarget)
applyBaseCameraSettings(this, isCapture = false)
}
previewRequestBuilder = builder
session.setRepeatingRequest(builder.build(), previewCallback, cameraHandler)
previewRequestBuilder = builder
true
} catch (e: Exception) {
PLog.e(
TAG,
"Failed to ${if (includeVideoSurface) "attach" else "detach"} dedicated video target",
e
)
} catch (error: Exception) {
PLog.e(TAG, "Failed to update OES recording target", error)
false
}
}
@@ -3,12 +3,16 @@ package com.hinnka.mycamera.camera
import com.hinnka.mycamera.stabilization.StabilizationImageReader
import java.util.concurrent.atomic.AtomicReference
/** Latest-frame-wins hand-off for the shared photo YUV stream when stabilization is off. */
/** Latest-frame-wins preview lease from the shared photo/video YUV input. */
class PreviewYuvFrameChannel {
private val latest = AtomicReference<StabilizationImageReader.AcquiredImage?>(null)
@Volatile
var onFrameAvailable: (() -> Unit)? = null
private val listener = AtomicReference<(() -> Unit)?>(null)
var onFrameAvailable: (() -> Unit)?
get() = listener.get()
set(value) { listener.set(value) }
internal fun clearListener(expected: () -> Unit): Boolean = listener.compareAndSet(expected, null)
internal fun publish(frame: StabilizationImageReader.AcquiredImage) {
latest.getAndSet(frame)?.close()
@@ -59,6 +59,8 @@ import com.hinnka.mycamera.video.VideoLogProfile
import com.hinnka.mycamera.video.VideoRecordingPath
import com.hinnka.mycamera.video.VideoResolutionPreset
import com.hinnka.mycamera.video.VideoStabilizationMode
import com.hinnka.mycamera.video.VideoInputMode
import com.hinnka.mycamera.video.VideoPipelineSettings
import kotlin.properties.ReadOnlyProperty
import kotlin.properties.ReadWriteProperty
import kotlin.reflect.KProperty
@@ -522,6 +524,18 @@ class UserPreferences internal constructor(
p[K.VIDEO_STABILIZATION_MODE] = v.name
p.remove(K.VIDEO_ENHANCED_STABILIZATION_ENABLED)
}
var videoInputMode by enum("video_input_mode", VideoInputMode.OES)
val effectiveVideoInputMode: VideoInputMode
get() = videoInputMode.withStabilization(videoStabilizationMode)
val effectiveVideoNrLevel: Int
get() = effectiveVideoInputMode.resolveNoiseReduction(videoNrLevel)
val effectiveOppoSuperStabilizationEnabled: Boolean
get() = effectiveVideoInputMode.allowsOppoSuperStabilization() && oppoSuperStabilizationEnabled
val videoPipelineSettings: VideoPipelineSettings
get() = VideoPipelineSettings(
videoInputMode, videoStabilizationMode, videoNrLevel, videoEdgeLevel,
oppoSuperStabilizationEnabled,
)
var videoEnhancedStabilizationStrength: Float by stored({ p ->
normalizeStabilizationStrength(p[K.VIDEO_ENHANCED_STABILIZATION_STRENGTH] ?: DEFAULT_VIDEO_STABILIZATION_STRENGTH)
}) { p, v -> p[K.VIDEO_ENHANCED_STABILIZATION_STRENGTH] = normalizeStabilizationStrength(v) }
@@ -0,0 +1,21 @@
package com.hinnka.mycamera.lut
import android.util.Size
/** Fits the complete source into the preview budget without upscaling or changing orientation. */
internal fun cameraPreviewTextureSize(width: Int, height: Int): Size {
require(width > 0 && height > 0)
val longEdge = maxOf(width, height)
val shortEdge = minOf(width, height)
if (longEdge <= 1920 && shortEdge <= 1080) return Size(width, height)
val outputLong: Int
val outputShort: Int
if (longEdge.toLong() * 1080 > shortEdge.toLong() * 1920) {
outputLong = 1920
outputShort = (shortEdge.toLong() * 1920 / longEdge).toInt().coerceAtLeast(1)
} else {
outputShort = 1080
outputLong = (longEdge.toLong() * 1080 / shortEdge).toInt().coerceAtLeast(1)
}
return if (width >= height) Size(outputLong, outputShort) else Size(outputShort, outputLong)
}
@@ -0,0 +1,46 @@
package com.hinnka.mycamera.lut
import android.opengl.EGL14
import android.opengl.EGL15
import android.opengl.EGLDisplay
import android.opengl.EGLSync
import android.opengl.GLES30
import java.util.concurrent.atomic.AtomicBoolean
/** A GPU completion lease; the originating display must outlive the lease. */
internal class GlSamplingFence private constructor(
private val display: EGLDisplay,
private val sync: EGLSync,
) : AutoCloseable {
private val closed = AtomicBoolean(false)
fun await() {
check(!closed.get())
if (sync == EGL15.EGL_NO_SYNC) return
val result = EGL15.eglClientWaitSync(
display, sync, EGL15.EGL_SYNC_FLUSH_COMMANDS_BIT, EGL15.EGL_FOREVER,
)
if (result != EGL15.EGL_CONDITION_SATISFIED) {
// Keep a failed consumer wait from returning a buffer still sampled by this context.
GLES30.glFinish()
error("GPU sampling fence wait failed: $result")
}
}
override fun close() {
if (closed.compareAndSet(false, true) && sync != EGL15.EGL_NO_SYNC) {
EGL15.eglDestroySync(display, sync)
}
}
companion object {
fun insert(): GlSamplingFence {
val display = EGL14.eglGetCurrentDisplay()
val sync = 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 (sync == EGL15.EGL_NO_SYNC) GLES30.glFinish()
return GlSamplingFence(display, sync)
}
}
}
@@ -79,8 +79,13 @@ class LutRenderer(context: Context) : GLSurfaceView.Renderer {
private val colorProgramCache = PreviewColorProgramCache()
private val enginePreview = RawEnginePreviewGl()
private val mgcEisRenderer = MgcEisRenderer(TAG)
private val previewYuvRenderer = PreviewYuvRenderer(TAG)
private val previewTiming = VideoRenderTiming.create("viewfinder")
private val previewYuvRenderer = PreviewYuvRenderer(TAG, previewTiming)
private val sharedRgbPreviewRenderer = SharedEisRgbPreviewRenderer(TAG)
private var sharedRgbChannel: SharedEisRgbFrameChannel? = null
private var sharedRgbConsumer: SharedEisRgbFrameChannel.Consumer? = null
private var previewYuvChannel: PreviewYuvFrameChannel? = null
private val previewYuvFrameAvailable: () -> Unit = { onRequestRender?.invoke() }
private val previewYuvMatrix = FloatArray(16).apply { Matrix.setIdentityM(this, 0) }
private data class PreviewCaptureRequest(
@@ -625,6 +630,8 @@ class LutRenderer(context: Context) : GLSurfaceView.Renderer {
enginePreview.reset()
mgcEisRenderer.resetAfterContextLoss()
previewYuvRenderer.resetAfterContextLoss()
previewTiming?.resetAfterContextLoss()
sharedRgbPreviewRenderer.resetAfterContextLoss()
cameraTextureId = 0
currentCameraTextureId = 0
currentCameraTextureSource = PreviewColorTextureSource.EXTERNAL_OES
@@ -1133,16 +1140,33 @@ class LutRenderer(context: Context) : GLSurfaceView.Renderer {
override fun onDrawFrame(gl: GL10?) {
if (renderingPaused) return
if (viewportWidth <= 0 || viewportHeight <= 0) return
previewTiming?.beginFrame()
try {
drawPreviewFrame()
} finally {
previewTiming?.endFrame()
}
}
private fun drawPreviewFrame() {
val delayedStabilizationRequested = previewStabilizationUseCase != null
val delayedStabilizationEnabled = delayedStabilizationRequested &&
stabilizationCoordinator?.isCurrentCameraSupported == true
val sharedVideoPreview = delayedStabilizationEnabled &&
previewStabilizationUseCase == StabilizationUseCase.VIDEO &&
sharedRgbConsumer?.isActive == true
if (sharedVideoPreview && stabilizationSessionStarted) {
stabilizationSession?.stop()
stabilizationSessionStarted = false
PLog.i(TAG, "Video preview switched to shared recording EIS RGB")
}
if (!delayedStabilizationEnabled && stabilizationSessionStarted) {
stabilizationSession?.stop()
stabilizationSessionStarted = false
mgcEisPresentationTransform.reset()
}
if (delayedStabilizationEnabled && !stabilizationSessionStarted) {
if (delayedStabilizationEnabled && !sharedVideoPreview && !stabilizationSessionStarted) {
stabilizationSessionStarted = stabilizationSession?.start() == true
}
val oesFrameUpdated = frameAvailable.getAndSet(false) && acquireLatestCameraFrame()
@@ -1164,13 +1188,22 @@ class LutRenderer(context: Context) : GLSurfaceView.Renderer {
PLog.w(TAG, "MGC cannot derive presentation from sensor orientation $sensorOrientation")
}
val session = stabilizationSession
if (!stabilizationSessionStarted) {
if (sharedVideoPreview) {
sharedRgbConsumer?.take()?.use { frame ->
currentCameraTextureId = sharedRgbPreviewRenderer.render(frame)
currentCameraTextureSource = PreviewColorTextureSource.TEXTURE_2D
currentCameraTextureTarget = GLES30.GL_TEXTURE_2D
currentCameraTextureMatrix = mgcEisPresentationTransform.matrix
currentFrameTimestampNs = frame.timestampNs
cameraFrameUpdated = true
}
} else if (!stabilizationSessionStarted) {
stabilizationSessionStarted = session?.start() == true
}
if (stabilizationSessionStarted) {
val completedFrame = if (previewStabilizationUseCase == StabilizationUseCase.PHOTO_PREVIEW &&
livePhotoRecorder == null
) {
// Video has its own FIFO recording consumer. Preview may skip completed
// frames independently; Live Photo still records through this renderer.
val completedFrame = if (livePhotoRecorder == null) {
session?.dequeueLatestFrame()
} else {
session?.dequeueFrame()
@@ -1452,7 +1485,12 @@ class LutRenderer(context: Context) : GLSurfaceView.Renderer {
/** Converts a viewfinder YUV frame and makes it the camera texture. Always closes [frame]. */
private fun usePreviewYuvFrame(frame: StabilizationImageReader.AcquiredImage): Boolean {
val timestampNs = frame.timestampNs
val textureId = frame.use { previewYuvRenderer.render(it.image) }
val textureId = previewTiming.cpu("yuv.total") {
frame.use {
val size = cameraPreviewTextureSize(it.width, it.height)
previewYuvRenderer.render(it.image, size.width, size.height)
}
}
if (textureId == 0) return false
val matrix = resolvePreviewYuvPresentationMatrix(sensorOrientation, lensFacing == 0) ?: run {
PLog.w(TAG, "Preview YUV frame has non-cardinal sensor orientation $sensorOrientation")
@@ -1470,11 +1508,20 @@ class LutRenderer(context: Context) : GLSurfaceView.Renderer {
fun setPreviewYuvChannel(channel: PreviewYuvFrameChannel?) {
if (previewYuvChannel === channel) return
previewYuvChannel?.let { previous ->
previous.onFrameAvailable = null
previous.take()?.close()
// A replacement view may already own this shared channel.
if (previous.clearListener(previewYuvFrameAvailable)) {
previous.take()?.close()
}
}
previewYuvChannel = channel
channel?.onFrameAvailable = { onRequestRender?.invoke() }
channel?.onFrameAvailable = previewYuvFrameAvailable
}
fun setSharedEisRgbFrames(channel: SharedEisRgbFrameChannel?) {
if (sharedRgbChannel === channel) return
sharedRgbConsumer?.close()
sharedRgbChannel = channel
sharedRgbConsumer = channel?.openConsumer { onRequestRender?.invoke() }
}
private fun useCurrentOesFrame() {
@@ -2612,7 +2659,10 @@ class LutRenderer(context: Context) : GLSurfaceView.Renderer {
onFrameAvailable = { onRequestRender?.invoke() },
)
}
stabilizationSessionStarted = stabilizationSession?.start() == true
val sharedVideoPreview = previewStabilizationUseCase == StabilizationUseCase.VIDEO &&
sharedRgbConsumer?.isActive == true
stabilizationSessionStarted = !renderingPaused && !sharedVideoPreview &&
stabilizationSession?.start() == true
currentCameraTextureSource = PreviewColorTextureSource.EXTERNAL_OES
currentCameraTextureTarget = GLES11Ext.GL_TEXTURE_EXTERNAL_OES
currentCameraTextureId = cameraTextureId
@@ -2625,12 +2675,13 @@ class LutRenderer(context: Context) : GLSurfaceView.Renderer {
frame: com.hinnka.mycamera.stabilization.StabilizationFrame,
): MgcEisRenderer.Frame? {
return frame.image.use { image ->
val textureId = previewYuvRenderer.render(image.image)
val size = cameraPreviewTextureSize(image.width, image.height)
val textureId = previewYuvRenderer.render(image.image, size.width, size.height)
if (textureId == 0) return null
mgcEisRenderer.render(
textureId = textureId,
width = image.width,
height = image.height,
width = size.width,
height = size.height,
timestampNs = frame.timestampNs,
rowHomographies = frame.transform?.rowHomographies,
)
@@ -3406,10 +3457,19 @@ class LutRenderer(context: Context) : GLSurfaceView.Renderer {
*/
fun getSurfaceTexture(): SurfaceTexture? = surfaceTexture
/**
* 释放资源
*/
fun release() {
/** Called only after GLSurfaceView has joined its GL thread and destroyed its EGL context. */
fun releaseAfterGlThreadExit() {
releaseNonGlResources()
resetGlResourceState()
PLog.d(TAG, "Released preview consumers after GL thread exit")
}
private fun releaseNonGlResources() {
renderingPaused = true
setPreviewYuvChannel(null)
sharedRgbConsumer?.close()
sharedRgbConsumer = null
sharedRgbChannel = null
stabilizationSession?.stop()
stabilizationSession = null
stabilizationCoordinator = null
@@ -3420,6 +3480,28 @@ class LutRenderer(context: Context) : GLSurfaceView.Renderer {
} catch (e: Exception) {
PLog.e(TAG, "Error shutting down metering executor", e)
}
nightVisionEstimator.close()
// 释放 SurfaceTexture
surfaceTexture?.release()
surfaceTexture = null
frameAvailable.set(false)
// 重置状态
surfaceReady = false
pendingLutConfig = null
pendingBaselineLutConfig = null
currentLutConfig = null
currentBaselineLutConfig = null
onEyeFocusInputAvailable = null
isEyeFocusBusy = false
resetEyeFocusTiming()
onRequestRender = null
onSurfaceTextureAvailable = null
}
fun release() {
releaseNonGlResources()
previewTiming?.closeGl()
// 删除纹理
if (cameraTextureId != 0) {
GlUtils.deleteTexture(cameraTextureId)
@@ -3499,7 +3581,6 @@ class LutRenderer(context: Context) : GLSurfaceView.Renderer {
}
releasePixelPackPbos(meteringPboIds, meteringPboFences)
releaseNightVisionGl()
nightVisionEstimator.close()
if (meteringFboId != 0) {
GLES30.glDeleteFramebuffers(1, intArrayOf(meteringFboId), 0)
@@ -3535,8 +3616,8 @@ class LutRenderer(context: Context) : GLSurfaceView.Renderer {
}
basicToneTextures.release()
mgcEisRenderer.release()
previewYuvChannel?.take()?.close()
previewYuvRenderer.release()
sharedRgbPreviewRenderer.release()
// 删除程序
colorProgramCache.release()
enginePreview.release()
@@ -3545,20 +3626,7 @@ class LutRenderer(context: Context) : GLSurfaceView.Renderer {
GlUtils.deleteProgram(copyProgramId)
copyProgramId = 0
// 释放 SurfaceTexture
surfaceTexture?.release()
surfaceTexture = null
frameAvailable.set(false)
// 重置状态
surfaceReady = false
pendingLutConfig = null
pendingBaselineLutConfig = null
currentLutConfig = null
currentBaselineLutConfig = null
onEyeFocusInputAvailable = null
isEyeFocusBusy = false
resetEyeFocusTiming()
}
/**
@@ -6,8 +6,9 @@ import com.hinnka.mycamera.stabilization.STABILIZATION_ROW_COUNT
import com.hinnka.mycamera.utils.PLog
/** Applies only MGC's rolling-strip geometry to the RGB output of [PreviewYuvRenderer]. */
internal class MgcEisRenderer(private val tag: String) {
internal class MgcEisRenderer(private val tag: String, private val timing: VideoRenderTiming? = null) {
data class Frame(val timestampNs: Long, val textureId: Int)
data class OutputTarget(val textureId: Int, val framebufferId: Int, val width: Int, val height: Int)
private val mesh = MgcEisMesh()
// Match native kOutputCropZoom = 1 / (1 - 2 * 0.05) even for a dropped pose.
@@ -34,26 +35,32 @@ internal class MgcEisRenderer(private val tag: String) {
height: Int,
timestampNs: Long,
rowHomographies: FloatArray?,
target: OutputTarget? = null,
): Frame? {
if (textureId == 0 || width <= 0 || height <= 0 || !ensure(width, height)) return null
GLES30.glBindFramebuffer(GLES30.GL_FRAMEBUFFER, outputFramebufferId)
GLES30.glViewport(0, 0, width, height)
GLES30.glDisable(GLES30.GL_BLEND)
GLES30.glClearColor(0f, 0f, 0f, 1f)
GLES30.glClear(GLES30.GL_COLOR_BUFFER_BIT)
GLES30.glUseProgram(programId)
GLES30.glActiveTexture(GLES30.GL_TEXTURE0)
GLES30.glBindTexture(GLES30.GL_TEXTURE_2D, textureId)
GLES30.glUniform1i(sourceSamplerLocation, 0)
mesh.draw(
positionLocation = positionLocation,
textureCoordinateLocation = textureCoordinateLocation,
rowHomographies = rowHomographies ?: droppedFrameHomographies,
)
if (textureId == 0 || width <= 0 || height <= 0 || !ensureProgram()) return null
if (target == null && !ensureTarget(width, height)) return null
val destination = target ?: OutputTarget(outputTextureId, outputFramebufferId, width, height)
GLES30.glBindFramebuffer(GLES30.GL_FRAMEBUFFER, destination.framebufferId)
GLES30.glViewport(0, 0, destination.width, destination.height)
// Keep elapsed-time queries inside the output FBO; CPU totals include target switches.
timing.gpu("geometry.draw") {
GLES30.glDisable(GLES30.GL_BLEND)
GLES30.glClearColor(0f, 0f, 0f, 1f)
GLES30.glClear(GLES30.GL_COLOR_BUFFER_BIT)
GLES30.glUseProgram(programId)
GLES30.glActiveTexture(GLES30.GL_TEXTURE0)
GLES30.glBindTexture(GLES30.GL_TEXTURE_2D, textureId)
GLES30.glUniform1i(sourceSamplerLocation, 0)
mesh.draw(
positionLocation = positionLocation,
textureCoordinateLocation = textureCoordinateLocation,
rowHomographies = rowHomographies ?: droppedFrameHomographies,
)
}
GLES30.glBindFramebuffer(GLES30.GL_FRAMEBUFFER, 0)
GLES30.glBindTexture(GLES30.GL_TEXTURE_2D, 0)
GLES31.glMemoryBarrier(GLES31.GL_FRAMEBUFFER_BARRIER_BIT or GLES31.GL_TEXTURE_FETCH_BARRIER_BIT)
return Frame(timestampNs, outputTextureId)
return Frame(timestampNs, destination.textureId)
}
fun resetAfterContextLoss() {
@@ -69,16 +76,23 @@ internal class MgcEisRenderer(private val tag: String) {
}
fun release() {
if (outputTextureId != 0) GLES30.glDeleteTextures(1, intArrayOf(outputTextureId), 0)
if (outputFramebufferId != 0) GLES30.glDeleteFramebuffers(1, intArrayOf(outputFramebufferId), 0)
releaseTarget()
if (programId != 0) GLES30.glDeleteProgram(programId)
mesh.release()
resetAfterContextLoss()
}
private fun ensure(requestedWidth: Int, requestedHeight: Int): Boolean {
if (programId != 0 && width == requestedWidth && height == requestedHeight) return true
release()
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
width = 0
height = 0
}
private fun ensureProgram(): Boolean {
if (programId != 0) return true
val vertexShader = GlUtils.compileShader(GLES30.GL_VERTEX_SHADER, VERTEX_SHADER)
val fragmentShader = GlUtils.compileShader(GLES30.GL_FRAGMENT_SHADER, FRAGMENT_SHADER)
if (vertexShader == 0 || fragmentShader == 0) {
@@ -94,6 +108,12 @@ internal class MgcEisRenderer(private val tag: String) {
textureCoordinateLocation = GLES30.glGetAttribLocation(programId, "aTexCoord")
sourceSamplerLocation = GLES30.glGetUniformLocation(programId, "uCameraTexture")
mesh.initialize()
return true
}
private fun ensureTarget(requestedWidth: Int, requestedHeight: Int): Boolean {
if (outputTextureId != 0 && width == requestedWidth && height == requestedHeight) return true
releaseTarget()
val textures = IntArray(1)
GLES30.glGenTextures(1, textures, 0)
outputTextureId = textures[0]
@@ -23,7 +23,7 @@ import java.nio.ByteOrder
* Shared by ordinary preview and EIS; stabilization operates only on this converter's RGB output.
* Readers retain their default usage: GPU_SAMPLED_IMAGE caused swapped Cb/Cr on Xiaomi 11.
*/
internal class PreviewYuvRenderer(private val tag: String) {
internal class PreviewYuvRenderer(private val tag: String, private val timing: VideoRenderTiming? = null) {
private enum class Path { RAW_YUV, PLANES }
private var y2yProgram: Program? = null
@@ -46,10 +46,11 @@ internal class PreviewYuvRenderer(private val tag: String) {
private val offset = FloatArray(3)
/** Borrows [image] through GPU sampling completion; the caller retains ownership. */
fun render(image: Image): Int {
fun render(image: Image, width: Int = image.width, height: Int = image.height): Int {
try {
if (image.width <= 0 || image.height <= 0) return 0
if (!ensureTarget(image.width, image.height)) return 0
require(width > 0 && height > 0)
if (!ensureTarget(width, height)) return 0
resolveConversion(if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) image.dataSpace else 0)
val drawn = (!importDisabled && drawImported(image)) || drawPlanes(image)
return if (drawn) outputTextureId else 0
@@ -64,28 +65,30 @@ internal class PreviewYuvRenderer(private val tag: String) {
val rawYuv = yuvTargetSupported ?: queryYuvTarget().also { yuvTargetSupported = it }
if (!rawYuv) return disableImport("GL_EXT_YUV_target unavailable")
val buffer = image.hardwareBuffer ?: return disableImport("Image has no HardwareBuffer")
val handle = buffer.use { GlesHardwareBufferImage.create(it) }
val handle = timing.cpu("yuv.import") { 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)) {
if (!timing.cpu("yuv.bind") { GlesHardwareBufferImage.bind(handle, externalTextureId) }) {
return disableImport("EGLImage bind failed")
}
val program = y2yProgram ?: buildProgram(Y2Y_FRAGMENT_SHADER)?.also { y2yProgram = it }
?: return disableImport("External program unavailable")
beginDraw(program)
GLES30.glActiveTexture(GLES30.GL_TEXTURE0)
GLES30.glBindTexture(GLES11Ext.GL_TEXTURE_EXTERNAL_OES, externalTextureId)
GLES30.glUniform1i(program.samplers[0], 0)
drawQuad(program)
timing.gpu("yuv.draw") {
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()
timing.cpu("yuv.wait") { awaitGpu() }
GLES30.glBindTexture(GLES11Ext.GL_TEXTURE_EXTERNAL_OES, 0)
endDraw()
reportPath(Path.RAW_YUV)
return true
} finally {
GlesHardwareBufferImage.destroy(handle)
timing.cpu("yuv.release") { GlesHardwareBufferImage.destroy(handle) }
}
}
@@ -107,15 +110,17 @@ internal class PreviewYuvRenderer(private val tag: String) {
}
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)
timing.gpu("yuv.draw") {
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)
}
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)
@@ -1,14 +1,15 @@
package com.hinnka.mycamera.lut
import android.content.Context
import android.media.Image
import android.graphics.SurfaceTexture
import android.opengl.GLES11Ext
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
@@ -20,6 +21,7 @@ import com.hinnka.mycamera.stabilization.StabilizationUseCase
import com.hinnka.mycamera.utils.PLog
import com.hinnka.mycamera.video.VideoEncoderColorConfig
import com.hinnka.mycamera.video.VideoEncodedColorPipeline
import com.hinnka.mycamera.video.VideoInputMode
import com.hinnka.mycamera.video.VideoLogProfile
import java.nio.ByteBuffer
import java.nio.ByteOrder
@@ -32,8 +34,8 @@ import kotlin.math.max
/**
* Camera2 录像专用实时渲染器。
*
* 普通录像从独立 [SurfaceTexture] 取 OES 帧;MGC 防抖录像改取与 CaptureResult 精确
* 对时的共享 YUV 图像。两条路径最终都在专用 EGL context 中写入 MediaCodec surface,
* OES 录像使用独立 SurfaceTexture;YUV 录像消费共享 FIFO,EIS+ 消费防抖 YUV。
* 普通 YUV 和防抖 YUV 共用颜色转换器;所有输入在专用 EGL context 中写入 MediaCodec surface,
* 因而录像帧率不受 GLSurfaceView 调度影响。
*/
class RealtimeVideoRenderer(
@@ -50,6 +52,8 @@ class RealtimeVideoRenderer(
private val enhancedStabilizationEnabled: Boolean,
private val enhancedStabilizationStrength: Float,
private val enhancedStabilizationLookahead: Int = DEFAULT_VIDEO_STABILIZATION_LOOKAHEAD,
private val inputMode: VideoInputMode = VideoInputMode.YUV,
private val sharedEisRgbFrames: SharedEisRgbFrameChannel? = null,
) {
companion object {
private const val TAG = "RealtimeVideoRenderer"
@@ -84,8 +88,9 @@ class RealtimeVideoRenderer(
private val toneBase = ToneBaseGl(TAG)
private val basicToneTextures = BasicToneGlTextures()
private val filmGrainGl = FilmGrainGl(TAG)
private val mgcEisRenderer = MgcEisRenderer(TAG)
private val previewYuvRenderer = PreviewYuvRenderer(TAG)
private val timing = VideoRenderTiming.create("record")
private val mgcEisRenderer = MgcEisRenderer(TAG, timing)
private val previewYuvRenderer = PreviewYuvRenderer(TAG, timing)
private val filmGrainAmount: Float
get() = layers.lastOrNull { it.params.filmGrain > 0.001f }?.params?.filmGrain ?: 0f
private val finalFilmGrainEnabled: Boolean
@@ -123,15 +128,17 @@ class RealtimeVideoRenderer(
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 val mgcEisPresentationTransform = MgcEisPresentationTransform()
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 val stMatrix = FloatArray(16).also { Matrix.setIdentityM(it, 0) }
private var cameraTextureId = 0
private var cameraSurfaceTexture: SurfaceTexture? = null
private var cameraSurface: Surface? = null
private val cameraFramePending = AtomicBoolean(false)
val inputSurface: Surface? get() = cameraSurface
private var intermediateTextureId = 0
private var intermediateFboId = 0
private var finalColorTextureId = 0
@@ -140,14 +147,14 @@ class RealtimeVideoRenderer(
private var textureCoordinateBuffer: FloatBuffer? = null
private var indexBuffer: ShortBuffer? = null
private var initialized = false
private val cameraFramePending = AtomicBoolean(false)
@Volatile
private var stabilizationSession: RealtimeStabilizationCoordinator.Session? = null
@Volatile
private var stabilizationSessionStarted = false
@Volatile
private var sharedRgbProducer: SharedEisRgbFrameChannel.Producer? = null
private var sharedRgbPool: SharedEisRgbOutputPool? = null
val inputSurface: Surface?
get() = cameraSurface
fun initialize(
encoderSurface: Surface,
@@ -176,29 +183,25 @@ class RealtimeVideoRenderer(
check(highlightDiffusionGl.prepare()) { "Cannot create realtime video highlight diffusion programs" }
}
cameraTextureId = GlUtils.createOESTexture()
check(cameraTextureId != 0) { "Cannot create realtime video OES texture" }
cameraSurfaceTexture = SurfaceTexture(cameraTextureId).apply {
setDefaultBufferSize(cameraInputSize.width, cameraInputSize.height)
setOnFrameAvailableListener {
cameraFramePending.set(true)
if (!enhancedStabilizationEnabled ||
stabilizationCoordinator?.isCurrentCameraSupported != true
) {
check(!enhancedStabilizationEnabled || inputMode == VideoInputMode.YUV)
if (inputMode == VideoInputMode.OES) {
cameraTextureId = GlUtils.createOESTexture()
check(cameraTextureId != 0) { "Cannot create realtime video OES texture" }
cameraSurfaceTexture = SurfaceTexture(cameraTextureId).apply {
setDefaultBufferSize(cameraInputSize.width, cameraInputSize.height)
setOnFrameAvailableListener {
cameraFramePending.set(true)
onFrameAvailable()
}
}
}
cameraSurface = Surface(cameraSurfaceTexture)
if (enhancedStabilizationEnabled) {
check(
mgcEisPresentationTransform.captureFromSensorOrientation(
sensorOrientationDegrees,
)
) {
cameraSurface = Surface(cameraSurfaceTexture)
} else {
check(mgcEisPresentationTransform.captureFromSensorOrientation(sensorOrientationDegrees)) {
"Camera reported non-cardinal sensor orientation $sensorOrientationDegrees"
}
updateCameraTransformGeometry(mgcEisPresentationTransform.matrix)
}
if (enhancedStabilizationEnabled) {
stabilizationSession = stabilizationCoordinator?.createSession(
useCase = StabilizationUseCase.VIDEO,
strength = enhancedStabilizationStrength,
@@ -223,7 +226,7 @@ class RealtimeVideoRenderer(
}
/**
* 消费 SurfaceTexture 中最新的一帧并写入编码器。必须在初始化所用的录像 GL 线程调用。
* 消费一帧 OES、共享 YUV 或防抖输出并写入编码器。必须在录像 GL 线程调用。
*
* [mapPresentationTimeNs] 将相机时间轴映射到编码器使用的公共时间轴。
*
@@ -231,95 +234,124 @@ class RealtimeVideoRenderer(
*/
fun renderLatestFrame(
mapPresentationTimeNs: (cameraTimestampNs: Long) -> Long,
yuvImage: Image? = null,
): Long? {
if (!initialized || !makeCurrent()) return null
val surfaceTexture = cameraSurfaceTexture ?: return null
val cameraFrameUpdated = cameraFramePending.getAndSet(false) &&
acquireLatestCameraFrame(surfaceTexture)
val cameraTimestampNs = surfaceTexture.timestamp
timing?.beginFrame()
try {
return renderCurrentFrame(mapPresentationTimeNs, yuvImage)
} finally {
timing?.endFrame()
}
}
var sourceTextureSource = PreviewColorTextureSource.EXTERNAL_OES
var sourceTextureTarget = GLES11Ext.GL_TEXTURE_EXTERNAL_OES
var sourceTextureId = cameraTextureId
var sourceStMatrix = stMatrix
private fun renderCurrentFrame(
mapPresentationTimeNs: (Long) -> Long,
yuvImage: Image?,
): Long? {
var sourceTextureSource = PreviewColorTextureSource.TEXTURE_2D
var sourceTextureTarget = GLES30.GL_TEXTURE_2D
val sourceTextureId: Int
var sourceStMatrix = mgcEisPresentationTransform.matrix
var sourceCropRect = cameraCropRect
var timestampNs = cameraTimestampNs
val timestampNs: Long
val session = stabilizationSession
val stabilizationOperational = enhancedStabilizationEnabled &&
stabilizationSessionStarted && session?.isOperational == true
if (stabilizationSessionStarted && !stabilizationOperational) {
sharedRgbProducer?.close()
sharedRgbProducer = null
session?.stop()
stabilizationSessionStarted = false
mgcEisPresentationTransform.reset()
}
if (stabilizationOperational) {
val frame = session.dequeueFrame() ?: return null
val frame = timing.cpu("source.dequeue") { session.dequeueFrame() } ?: return null
val rendered = renderMgcEisFrame(frame) ?: return null
sourceTextureSource = PreviewColorTextureSource.TEXTURE_2D
sourceTextureTarget = GLES30.GL_TEXTURE_2D
sourceTextureId = rendered.textureId
sourceStMatrix = mgcEisPresentationTransform.matrix
sourceCropRect = cameraCropRect
timestampNs = rendered.timestampNs
} else if (inputMode == VideoInputMode.OES) {
val surfaceTexture = cameraSurfaceTexture ?: return null
if (!cameraFramePending.getAndSet(false)) return null
timing.cpu("source.dequeue") {
surfaceTexture.updateTexImage()
surfaceTexture.getTransformMatrix(stMatrix)
}
updateCameraTransformGeometry(stMatrix)
sourceTextureSource = PreviewColorTextureSource.EXTERNAL_OES
sourceTextureTarget = GLES11Ext.GL_TEXTURE_EXTERNAL_OES
sourceTextureId = cameraTextureId
sourceStMatrix = stMatrix
sourceCropRect = cameraCropRect
timestampNs = surfaceTexture.timestamp
} else {
if (!cameraFrameUpdated || cameraTimestampNs <= 0L) return null
if (enhancedStabilizationEnabled) return null
val image = yuvImage ?: return null
sourceTextureId = timing.cpu("yuv.total") { previewYuvRenderer.render(image) }
if (sourceTextureId == 0) return null
timestampNs = image.timestamp
}
if (timestampNs <= 0L) return null
val presentationTimeNs = mapPresentationTimeNs(timestampNs)
if (presentationTimeNs <= 0L) return null
val firstLayer = layers.first()
val postProcess = postProcessEnabled
val firstTargetFbo = if (layers.size > 1 || postProcess) intermediateFboId else 0
drawLayer(
layer = firstLayer,
targetFboId = firstTargetFbo,
textureSource = sourceTextureSource,
textureTarget = sourceTextureTarget,
textureId = sourceTextureId,
sourceStMatrix = sourceStMatrix,
cropRect = sourceCropRect,
mvpMatrix = firstPassMvpMatrix,
enableVideoLog = videoLogProfile.isEnabled,
presentationTimeNs = timestampNs,
)
timing.gpu("color.draw") {
val firstLayer = layers.first()
val postProcess = postProcessEnabled
val firstTargetFbo = if (layers.size > 1 || postProcess) intermediateFboId else 0
drawLayer(
layer = firstLayer,
targetFboId = firstTargetFbo,
textureSource = sourceTextureSource,
textureTarget = sourceTextureTarget,
textureId = sourceTextureId,
sourceStMatrix = sourceStMatrix,
cropRect = sourceCropRect,
mvpMatrix = firstPassMvpMatrix,
enableVideoLog = videoLogProfile.isEnabled,
presentationTimeNs = timestampNs,
)
if (layers.size > 1) {
layers.drop(1).forEachIndexed { index, layer ->
val isLast = index == layers.lastIndex - 1
drawLayer(
layer = layer,
targetFboId = if (isLast) {
if (postProcess) finalColorFboId else 0
} else {
intermediateFboId
},
textureSource = PreviewColorTextureSource.TEXTURE_2D,
textureTarget = GLES30.GL_TEXTURE_2D,
textureId = intermediateTextureId,
sourceStMatrix = identityMatrix,
cropRect = fullCropRect,
mvpMatrix = identityMatrix,
enableVideoLog = false,
presentationTimeNs = timestampNs,
if (layers.size > 1) {
layers.drop(1).forEachIndexed { index, layer ->
val isLast = index == layers.lastIndex - 1
drawLayer(
layer = layer,
targetFboId = if (isLast) {
if (postProcess) finalColorFboId else 0
} else {
intermediateFboId
},
textureSource = PreviewColorTextureSource.TEXTURE_2D,
textureTarget = GLES30.GL_TEXTURE_2D,
textureId = intermediateTextureId,
sourceStMatrix = identityMatrix,
cropRect = fullCropRect,
mvpMatrix = identityMatrix,
enableVideoLog = false,
presentationTimeNs = timestampNs,
)
}
}
if (postProcess) {
drawPostProcess(
colorTextureId = if (layers.size > 1) finalColorTextureId else intermediateTextureId,
colorFramebufferId = if (layers.size > 1) finalColorFboId else intermediateFboId,
timestampNs = timestampNs,
)
}
}
if (postProcess) {
drawPostProcess(
colorTextureId = if (layers.size > 1) finalColorTextureId else intermediateTextureId,
colorFramebufferId = if (layers.size > 1) finalColorFboId else intermediateFboId,
timestampNs = timestampNs,
)
}
EGLExt.eglPresentationTimeANDROID(eglDisplay, encoderEglSurface, presentationTimeNs)
if (!EGL14.eglSwapBuffers(eglDisplay, encoderEglSurface)) {
throw IllegalStateException(
"Realtime video eglSwapBuffers failed: 0x${Integer.toHexString(EGL14.eglGetError())}"
)
timing.cpu("encoder.submit") {
EGLExt.eglPresentationTimeANDROID(eglDisplay, encoderEglSurface, presentationTimeNs)
if (!EGL14.eglSwapBuffers(eglDisplay, encoderEglSurface)) {
throw IllegalStateException(
"Realtime video eglSwapBuffers failed: 0x${Integer.toHexString(EGL14.eglGetError())}"
)
}
}
return presentationTimeNs
}
@@ -373,42 +405,43 @@ class RealtimeVideoRenderer(
check(error == GLES30.GL_NO_ERROR) { "Realtime video post-process output glError=$error" }
}
private fun acquireLatestCameraFrame(surfaceTexture: SurfaceTexture): Boolean {
return try {
surfaceTexture.updateTexImage()
surfaceTexture.getTransformMatrix(stMatrix)
if (enhancedStabilizationEnabled &&
!mgcEisPresentationTransform.captureFromOes(stMatrix)
) {
PLog.w(TAG, "MGC cannot derive a cardinal presentation orientation yet")
}
updateCameraTransformGeometry(
if (enhancedStabilizationEnabled) {
mgcEisPresentationTransform.matrix
} else {
stMatrix
},
)
true
} catch (error: RuntimeException) {
PLog.e(TAG, "Failed to acquire realtime video frame", error)
false
}
}
private fun renderMgcEisFrame(
frame: com.hinnka.mycamera.stabilization.StabilizationFrame,
): MgcEisRenderer.Frame? {
return frame.image.use { image ->
val textureId = previewYuvRenderer.render(image.image)
val textureId = timing.cpu("yuv.total") { previewYuvRenderer.render(image.image) }
if (textureId == 0) return null
mgcEisRenderer.render(
textureId = textureId,
width = image.width,
height = image.height,
timestampNs = frame.timestampNs,
rowHomographies = frame.transform?.rowHomographies,
)
val producer = sharedRgbProducer
val output = timing.cpu("geometry.target") {
val pool = if (producer != null) {
sharedRgbPool ?: SharedEisRgbOutputPool(image.width, image.height).also {
sharedRgbPool = it
PLog.i(TAG, "Shared EIS RGB producer configured: ${image.width}x${image.height}, slots=3")
}
} else null
var lease = pool?.acquire()
if (lease == null && pool != null) {
producer?.discardPendingFrame()
lease = pool.acquire()
}
lease
}
output.use { lease ->
val rendered = timing.cpu("geometry.total") {
mgcEisRenderer.render(
textureId = textureId,
width = image.width,
height = image.height,
timestampNs = frame.timestampNs,
rowHomographies = frame.transform?.rowHomographies,
target = lease?.target,
)
}
if (rendered != null && lease != null) {
timing.cpu("shared.publish") { producer?.publish(lease.finish(frame.timestampNs)) }
}
rendered
}
}
}
@@ -949,6 +982,8 @@ class RealtimeVideoRenderer(
@Synchronized
fun pauseStabilization() {
sharedRgbProducer?.close()
sharedRgbProducer = null
stabilizationSession?.stop()
stabilizationSessionStarted = false
}
@@ -957,9 +992,12 @@ class RealtimeVideoRenderer(
fun resumeStabilization() {
if (!enhancedStabilizationEnabled || stabilizationSessionStarted) return
stabilizationSessionStarted = stabilizationSession?.start() == true
if (stabilizationSessionStarted) sharedRgbProducer = sharedEisRgbFrames?.openProducer()
}
fun release() {
sharedRgbProducer?.close()
sharedRgbProducer = null
stabilizationSession?.stop()
stabilizationSession = null
stabilizationSessionStarted = false
@@ -974,7 +1012,14 @@ class RealtimeVideoRenderer(
cameraSurface = null
cameraSurfaceTexture?.release()
cameraSurfaceTexture = null
if (cameraTextureId != 0) {
GLES30.glDeleteTextures(1, intArrayOf(cameraTextureId), 0)
cameraTextureId = 0
}
cameraFramePending.set(false)
timing?.closeGl()
sharedRgbPool?.close()
sharedRgbPool = null
layers.forEach { layer ->
if (layer.lutTextureId != 0) {
GLES30.glDeleteTextures(1, intArrayOf(layer.lutTextureId), 0)
@@ -985,10 +1030,6 @@ class RealtimeVideoRenderer(
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
@@ -0,0 +1,105 @@
package com.hinnka.mycamera.lut
import android.hardware.HardwareBuffer
import java.util.concurrent.atomic.AtomicBoolean
/** Latest-only preview of the recording renderer's neutral, geometrically stabilized RGB. */
class SharedEisRgbFrameChannel {
private val lock = Any()
private var producer: Producer? = null
private var consumer: Consumer? = null
private var latest: SharedEisRgbFrame? = null
internal fun openProducer(): Producer {
val next = Producer()
val callback = synchronized(lock) {
check(producer == null) { "An EIS RGB producer is already active" }
producer = next
consumer?.onChanged
}
callback?.invoke()
return next
}
internal fun openConsumer(onChanged: () -> Unit): Consumer {
val next = Consumer(onChanged)
synchronized(lock) { consumer = next }
onChanged()
return next
}
internal inner class Producer : AutoCloseable {
fun publish(frame: SharedEisRgbFrame) {
var old: SharedEisRgbFrame? = null
val callback = synchronized(lock) {
if (producer !== this) {
frame.close()
return
}
old = latest
latest = frame
consumer?.onChanged
}
old?.close()
callback?.invoke()
}
fun discardPendingFrame() {
val old = synchronized(lock) {
if (producer !== this) return
latest.also { latest = null }
}
old?.close()
}
override fun close() {
var old: SharedEisRgbFrame? = null
val callback = synchronized(lock) {
if (producer !== this) return
producer = null
old = latest
latest = null
consumer?.onChanged
}
old?.close()
callback?.invoke()
}
}
internal inner class Consumer(internal val onChanged: () -> Unit) : AutoCloseable {
val isActive: Boolean
get() = synchronized(lock) { consumer === this && producer != null }
fun take(): SharedEisRgbFrame? = synchronized(lock) {
if (consumer !== this) null else latest.also { latest = null }
}
override fun close() {
val old = synchronized(lock) {
if (consumer !== this) return
consumer = null
latest.also { latest = null }
}
old?.close()
}
}
}
/** Owns a pool slot and its producer fence until preview has finished GPU sampling. */
internal class SharedEisRgbFrame(
val buffer: HardwareBuffer,
val timestampNs: Long,
val width: Int,
val height: Int,
val ready: GlSamplingFence,
private val releaseSlot: () -> Unit,
) : AutoCloseable {
private val closed = AtomicBoolean(false)
override fun close() {
if (closed.compareAndSet(false, true)) {
ready.close()
releaseSlot()
}
}
}
@@ -0,0 +1,118 @@
package com.hinnka.mycamera.lut
import android.hardware.HardwareBuffer
import android.opengl.GLES30
import com.hinnka.mycamera.processor.GlesHardwareBufferImage
/** Recording-thread targets: one preview in flight, one pending, and one producer slot. */
internal class SharedEisRgbOutputPool(private val width: Int, private val height: Int) : AutoCloseable {
private val slots = mutableListOf<Slot>()
private var closed = false
fun acquire(): Lease? {
check(!closed)
slots.firstOrNull { it.acquire() }?.let { return Lease(it) }
if (slots.size == 3) return null
val slot = Slot()
slots += slot
check(slot.acquire())
return Lease(slot)
}
inner class Lease internal constructor(private val slot: Slot) : AutoCloseable {
val target get() = slot.target
private var transferred = false
fun finish(timestampNs: Long): SharedEisRgbFrame {
check(!transferred)
val ready = GlSamplingFence.insert()
GLES30.glFlush()
transferred = true
return SharedEisRgbFrame(slot.buffer, timestampNs, width, height, ready, slot::releaseLease)
}
override fun close() {
if (!transferred) slot.releaseLease()
}
}
internal inner class Slot {
val buffer = HardwareBuffer.create(
width, height, HardwareBuffer.RGBA_8888, 1,
HardwareBuffer.USAGE_GPU_COLOR_OUTPUT or HardwareBuffer.USAGE_GPU_SAMPLED_IMAGE,
)
private var imageHandle = 0L
private var textureId = 0
private var framebufferId = 0
private var leased = false
private var retired = false
val target get() = MgcEisRenderer.OutputTarget(textureId, framebufferId, width, height)
init {
try {
imageHandle = GlesHardwareBufferImage.create(buffer)
check(imageHandle != 0L) { "Cannot import EIS RGB output buffer" }
val ids = IntArray(1)
GLES30.glActiveTexture(GLES30.GL_TEXTURE0)
GLES30.glGenTextures(1, ids, 0)
textureId = ids[0]
check(GlesHardwareBufferImage.bind2D(imageHandle, textureId)) { "Cannot bind EIS RGB output" }
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.glGenFramebuffers(1, ids, 0)
framebufferId = ids[0]
GLES30.glBindFramebuffer(GLES30.GL_FRAMEBUFFER, framebufferId)
GLES30.glFramebufferTexture2D(
GLES30.GL_FRAMEBUFFER, GLES30.GL_COLOR_ATTACHMENT0, GLES30.GL_TEXTURE_2D, textureId, 0,
)
check(GLES30.glCheckFramebufferStatus(GLES30.GL_FRAMEBUFFER) == GLES30.GL_FRAMEBUFFER_COMPLETE) {
"EIS RGB output framebuffer incomplete"
}
GLES30.glBindFramebuffer(GLES30.GL_FRAMEBUFFER, 0)
GLES30.glBindTexture(GLES30.GL_TEXTURE_2D, 0)
} catch (error: Throwable) {
retire()
throw error
}
}
@Synchronized
fun acquire(): Boolean {
if (retired || leased) return false
leased = true
return true
}
@Synchronized
fun releaseLease() {
check(leased)
leased = false
if (retired) buffer.close()
}
/** Producer GL names are local; a preview lease retains its own EGLImage import. */
@Synchronized
fun retire() {
if (retired) return
retired = true
if (framebufferId != 0) GLES30.glDeleteFramebuffers(1, intArrayOf(framebufferId), 0)
if (textureId != 0) GLES30.glDeleteTextures(1, intArrayOf(textureId), 0)
if (imageHandle != 0L) GlesHardwareBufferImage.destroy(imageHandle)
framebufferId = 0
textureId = 0
imageHandle = 0L
if (!leased) buffer.close()
}
}
override fun close() {
if (closed) return
closed = true
// Complete any encoder sampling before retiring producer-side imports.
GLES30.glFinish()
slots.forEach { it.retire() }
slots.clear()
}
}
@@ -0,0 +1,170 @@
package com.hinnka.mycamera.lut
import android.opengl.GLES30
import android.opengl.GLES31
import com.hinnka.mycamera.processor.GlesHardwareBufferImage
import com.hinnka.mycamera.utils.PLog
import java.nio.ByteBuffer
import java.nio.ByteOrder
/** Copies a shared neutral RGB frame into a preview-owned, size-bounded texture. */
internal class SharedEisRgbPreviewRenderer(private val tag: String) {
private val timing = VideoRenderTiming.create("shared-preview")
private var program = 0
private var positionLocation = -1
private var uvLocation = -1
private var samplerLocation = -1
private var quadBuffer = 0
private var sourceTexture = 0
private var texture = 0
private var framebuffer = 0
private var width = 0
private var height = 0
/** Borrows [frame]; callers close it only after this method completes GPU sampling. */
fun render(frame: SharedEisRgbFrame): Int {
timing?.beginFrame()
try {
return copyFrame(frame)
} finally {
timing?.endFrame()
}
}
private fun copyFrame(frame: SharedEisRgbFrame): Int {
timing.cpu("producer.wait") { frame.ready.await() }
val size = cameraPreviewTextureSize(frame.width, frame.height)
ensure(size.width, size.height)
val handle = timing.cpu("rgb.import") { GlesHardwareBufferImage.create(frame.buffer) }
check(handle != 0L) { "Cannot import shared EIS RGB frame" }
try {
timing.gpu("copy.draw") {
GLES30.glActiveTexture(GLES30.GL_TEXTURE0)
check(GlesHardwareBufferImage.bind2D(handle, sourceTexture)) { "Cannot bind shared EIS RGB frame" }
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, framebuffer)
GLES30.glViewport(0, 0, width, height)
GLES30.glDisable(GLES30.GL_BLEND)
GLES30.glUseProgram(program)
GLES30.glUniform1i(samplerLocation, 0)
GLES30.glBindBuffer(GLES30.GL_ARRAY_BUFFER, quadBuffer)
GLES30.glEnableVertexAttribArray(positionLocation)
GLES30.glVertexAttribPointer(positionLocation, 2, GLES30.GL_FLOAT, false, 16, 0)
GLES30.glEnableVertexAttribArray(uvLocation)
GLES30.glVertexAttribPointer(uvLocation, 2, GLES30.GL_FLOAT, false, 16, 8)
GLES30.glDrawArrays(GLES30.GL_TRIANGLE_STRIP, 0, 4)
}
timing.cpu("copy.wait") { GlSamplingFence.insert().use { it.await() } }
GLES30.glDisableVertexAttribArray(positionLocation)
GLES30.glDisableVertexAttribArray(uvLocation)
GLES30.glBindBuffer(GLES30.GL_ARRAY_BUFFER, 0)
GLES30.glBindTexture(GLES30.GL_TEXTURE_2D, 0)
GLES30.glBindFramebuffer(GLES30.GL_FRAMEBUFFER, 0)
GLES31.glMemoryBarrier(GLES31.GL_FRAMEBUFFER_BARRIER_BIT or GLES31.GL_TEXTURE_FETCH_BARRIER_BIT)
return texture
} finally {
GlesHardwareBufferImage.destroy(handle)
}
}
private fun ensure(targetWidth: Int, targetHeight: Int) {
if (program == 0) {
val vs = GlUtils.compileShader(GLES30.GL_VERTEX_SHADER, VERTEX_SHADER)
val fs = GlUtils.compileShader(GLES30.GL_FRAGMENT_SHADER, FRAGMENT_SHADER)
try {
check(vs != 0 && fs != 0) { "Cannot compile shared RGB preview shader" }
program = GlUtils.linkProgram(vs, fs)
check(program != 0) { "Cannot link shared RGB preview shader" }
} finally {
if (vs != 0) GLES30.glDeleteShader(vs)
if (fs != 0) GLES30.glDeleteShader(fs)
}
positionLocation = GLES30.glGetAttribLocation(program, "aPosition")
uvLocation = GLES30.glGetAttribLocation(program, "aTexCoord")
samplerLocation = GLES30.glGetUniformLocation(program, "uInput")
val ids = IntArray(1)
GLES30.glGenBuffers(1, ids, 0)
quadBuffer = ids[0]
val quad = ByteBuffer.allocateDirect(QUAD.size * 4).order(ByteOrder.nativeOrder())
.asFloatBuffer().put(QUAD).also { it.position(0) }
GLES30.glBindBuffer(GLES30.GL_ARRAY_BUFFER, quadBuffer)
GLES30.glBufferData(GLES30.GL_ARRAY_BUFFER, QUAD.size * 4, quad, GLES30.GL_STATIC_DRAW)
GLES30.glBindBuffer(GLES30.GL_ARRAY_BUFFER, 0)
GLES30.glGenTextures(1, ids, 0)
sourceTexture = ids[0]
}
if (texture != 0 && width == targetWidth && height == targetHeight) return
releaseTarget()
val ids = IntArray(1)
GLES30.glActiveTexture(GLES30.GL_TEXTURE0)
GLES30.glGenTextures(1, ids, 0)
texture = ids[0]
GLES30.glBindTexture(GLES30.GL_TEXTURE_2D, texture)
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.glTexStorage2D(GLES30.GL_TEXTURE_2D, 1, GLES30.GL_RGBA8, targetWidth, targetHeight)
GLES30.glGenFramebuffers(1, ids, 0)
framebuffer = ids[0]
GLES30.glBindFramebuffer(GLES30.GL_FRAMEBUFFER, framebuffer)
GLES30.glFramebufferTexture2D(
GLES30.GL_FRAMEBUFFER, GLES30.GL_COLOR_ATTACHMENT0, GLES30.GL_TEXTURE_2D, texture, 0,
)
check(GLES30.glCheckFramebufferStatus(GLES30.GL_FRAMEBUFFER) == GLES30.GL_FRAMEBUFFER_COMPLETE)
GLES30.glBindFramebuffer(GLES30.GL_FRAMEBUFFER, 0)
GLES30.glBindTexture(GLES30.GL_TEXTURE_2D, 0)
width = targetWidth
height = targetHeight
PLog.i(tag, "Shared EIS RGB preview configured: ${width}x$height (source bounded to 1920x1080)")
}
private fun releaseTarget() {
if (texture != 0) GLES30.glDeleteTextures(1, intArrayOf(texture), 0)
if (framebuffer != 0) GLES30.glDeleteFramebuffers(1, intArrayOf(framebuffer), 0)
texture = 0
framebuffer = 0
}
fun release() {
timing?.closeGl()
releaseTarget()
if (sourceTexture != 0) GLES30.glDeleteTextures(1, intArrayOf(sourceTexture), 0)
if (quadBuffer != 0) GLES30.glDeleteBuffers(1, intArrayOf(quadBuffer), 0)
if (program != 0) GLES30.glDeleteProgram(program)
resetAfterContextLoss()
}
fun resetAfterContextLoss() {
timing?.resetAfterContextLoss()
program = 0
quadBuffer = 0
sourceTexture = 0
texture = 0
framebuffer = 0
width = 0
height = 0
}
private companion object {
val QUAD = floatArrayOf(-1f, -1f, 0f, 0f, 1f, -1f, 1f, 0f, -1f, 1f, 0f, 1f, 1f, 1f, 1f, 1f)
val VERTEX_SHADER = """
#version 300 es
in vec4 aPosition;
in vec2 aTexCoord;
out vec2 vTexCoord;
void main() { gl_Position = aPosition; vTexCoord = aTexCoord; }
""".trimIndent()
val FRAGMENT_SHADER = """
#version 300 es
precision highp float;
uniform highp sampler2D uInput;
in vec2 vTexCoord;
out vec4 fragColor;
void main() { fragColor = texture(uInput, vTexCoord); }
""".trimIndent()
}
}
@@ -0,0 +1,196 @@
package com.hinnka.mycamera.lut
import android.opengl.GLES30
import com.hinnka.mycamera.BuildConfig
import com.hinnka.mycamera.processor.GlesGpuTimerQuery
import com.hinnka.mycamera.utils.PLog
import com.hinnka.mycamera.utils.SystemPropertiesUtil
import java.util.Locale
/** Opt-in, context-local diagnostics. GPU results are polled, never awaited. */
internal class VideoRenderTiming private constructor(private val role: String) {
private class Stats {
val cpu = ArrayList<Long>()
val gpu = ArrayList<Long>()
var rejected = 0
var rejectedMaxNs = 0L
var rejectedLifetimeMaxNs = 0L
}
private data class Query(val id: Int, val stage: String, val startNs: Long)
private val session = java.lang.Long.toString(System.nanoTime(), 36)
private val stats = linkedMapOf<String, Stats>()
private val pending = ArrayList<Query>()
private var active: Query? = null
private var contextReady = false
private var timerBits = 0
private var wrapNs = Long.MAX_VALUE
private var frame = 0L
private var sampledFrame = false
private var frameStartNs = 0L
private var windowStartNs = 0L
private var window = 0
private var disjointInWindow = false
private var discarded = 0
private var skipped = 0
fun beginFrame() {
if (!contextReady) {
contextReady = true
timerBits = GlesGpuTimerQuery.counterBits()
wrapNs = if (timerBits in 1..62) 1L shl timerBits else Long.MAX_VALUE
if (timerBits > 0) GlesGpuTimerQuery.isDisjoint()
PLog.i(TAG, "session=$session role=$role begin timerBits=$timerBits gpuEvery=10 " +
"cpuScopes=inclusive cpuGpu=overlap gpuResults=delayed " +
"gpu=${GLES30.glGetString(GLES30.GL_RENDERER)} driver=${GLES30.glGetString(GLES30.GL_VERSION)}")
}
collectReady()
frameStartNs = System.nanoTime()
if (windowStartNs == 0L) windowStartNs = frameStartNs
sampledFrame = frame++ % 10L == 0L
}
fun endFrame() {
recordCpu("frame.total", System.nanoTime() - frameStartNs)
collectReady()
if (System.nanoTime() - windowStartNs >= 2_000_000_000L) report()
}
fun recordCpu(stage: String, ns: Long) {
stats.getOrPut(stage) { Stats() }.cpu += ns
}
fun beginGpu(stage: String) {
check(active == null) { "Nested video GPU timing: ${active?.stage} / $stage" }
if (!sampledFrame || timerBits == 0) return
if (pending.size >= 24) {
skipped++
return
}
val start = System.nanoTime()
val id = GlesGpuTimerQuery.begin()
if (id != 0) active = Query(id, stage, start) else skipped++
}
fun endGpu() {
active?.let {
GlesGpuTimerQuery.end()
pending += it
active = null
}
}
private fun invalidateDisjoint() {
disjointInWindow = true
stats.values.forEach { it.gpu.clear() }
discarded += pending.size
pending.forEach { GlesGpuTimerQuery.delete(it.id) }
pending.clear()
}
private fun collectReady() {
if (timerBits == 0) return
if (GlesGpuTimerQuery.isDisjoint()) invalidateDisjoint()
val iterator = pending.iterator()
while (iterator.hasNext()) {
val query = iterator.next()
val ns = GlesGpuTimerQuery.poll(query.id)
if (ns < 0) continue
val lifetime = System.nanoTime() - query.startNs
val values = stats.getOrPut(query.stage) { Stats() }
if (lifetime >= wrapNs) discarded++
else if (ns > lifetime) {
// GPU execution cannot outlast submission-to-ready CPU time. Reject
// inconsistent results even with disjoint=false, preserving the evidence.
discarded++
values.rejected++
values.rejectedMaxNs = maxOf(values.rejectedMaxNs, ns)
values.rejectedLifetimeMaxNs = maxOf(values.rejectedLifetimeMaxNs, lifetime)
} else if (!disjointInWindow) values.gpu += ns
GlesGpuTimerQuery.delete(query.id)
iterator.remove()
}
if (GlesGpuTimerQuery.isDisjoint()) invalidateDisjoint()
}
private fun report() {
val now = System.nanoTime()
val status = when {
timerBits == 0 -> "unsupported"
disjointInWindow -> "disjoint"
else -> "valid"
}
for ((stage, values) in stats) {
val stageStatus = if (status == "valid" && values.rejected > 0) "invalid-lifetime" else status
PLog.i(TAG, "session=$session role=$role window=$window stage=$stage " +
"spanMs=${ms(now - windowStartNs)} ${summary("cpu", values.cpu)} " +
"${summary("gpu", values.gpu)} gpuStatus=$stageStatus pending=${pending.size} " +
"gpuRejected=${values.rejected} gpuRejectedMaxMs=${ms(values.rejectedMaxNs)} " +
"gpuLifetimeMaxMs=${ms(values.rejectedLifetimeMaxNs)} " +
"discarded=$discarded skipped=$skipped")
}
stats.clear()
window++
windowStartNs = now
disjointInWindow = false
discarded = 0
skipped = 0
}
/** Call with the owning GL context current, before EGL teardown. Adds no GPU wait. */
fun closeGl() {
if (!contextReady) return
check(active == null)
collectReady()
if (stats.isNotEmpty()) report()
pending.forEach { GlesGpuTimerQuery.delete(it.id) }
pending.clear()
contextReady = false
}
/** Old query names belong to the lost context and must not be deleted in the new one. */
fun resetAfterContextLoss() {
active = null
pending.clear()
stats.clear()
contextReady = false
windowStartNs = 0L
disjointInWindow = false
discarded = 0
skipped = 0
}
private fun summary(prefix: String, values: List<Long>): String {
if (values.isEmpty()) return "${prefix}N=0 ${prefix}AvgMs=NA ${prefix}P95Ms=NA ${prefix}MaxMs=NA"
val sorted = values.sorted()
return "${prefix}N=${values.size} ${prefix}AvgMs=${ms(values.sum() / values.size)} " +
"${prefix}P95Ms=${ms(sorted[((values.size * 95 + 99) / 100 - 1).coerceAtLeast(0)])} " +
"${prefix}MaxMs=${ms(sorted.last())}"
}
private fun ms(ns: Long) = String.format(Locale.US, "%.3f", ns / 1_000_000.0)
companion object {
private const val TAG = "VideoTiming"
fun create(role: String): VideoRenderTiming? =
if (BuildConfig.DEBUG && SystemPropertiesUtil.get("debug.photon.video.timing") == "true") {
VideoRenderTiming(role)
} else null
}
}
internal inline fun <T> VideoRenderTiming?.cpu(stage: String, block: () -> T): T {
if (this == null) return block()
val start = System.nanoTime()
try { return block() } finally { recordCpu(stage, System.nanoTime() - start) }
}
internal inline fun <T> VideoRenderTiming?.gpu(stage: String, block: () -> T): T {
if (this == null) return block()
val start = System.nanoTime()
beginGpu(stage)
try { return block() } finally {
endGpu()
recordCpu(stage, System.nanoTime() - start)
}
}
@@ -14,6 +14,9 @@ internal object GlesHardwareBufferImage {
/** The texture must be GL_TEXTURE_EXTERNAL_OES. Does not wait for GPU completion. */
external fun bind(handle: Long, textureId: Int): Boolean
/** RGBA HardwareBuffers can be sampled and attached to FBOs as GL_TEXTURE_2D. */
external fun bind2D(handle: Long, textureId: Int): Boolean
/** Call after the consumer has finished sampling, before destroying the EGL display. */
external fun destroy(handle: Long)
}
@@ -631,7 +631,9 @@ class RealtimeStabilizationCoordinator(context: Context) {
height = image.height,
pendingSessionIds = activeSessions.keys.toMutableSet(),
)
trimBufferedImagesLocked()
// ImageReader bounds the number of physical images. Preserve each recording
// consumer's FIFO lease; if it falls behind, reader capacity applies backpressure
// instead of evicting images whose timestamped results are still needed.
onFrameBoundaryLocked(timestampNs)
}
}
@@ -673,6 +675,7 @@ class RealtimeStabilizationCoordinator(context: Context) {
if (sameConfig) {
activeSessions[sessionId] = onFrameAvailable
activeSessionCount = activeSessions.size
PLog.i(TAG, "MGC consumer registered: session=$sessionId, active=$activeSessionCount")
return resultSequence
}
@@ -734,7 +737,7 @@ class RealtimeStabilizationCoordinator(context: Context) {
}
activeSessions[sessionId] = onFrameAvailable
activeSessionCount = activeSessions.size
PLog.i(TAG, "MGC htd feeder started with gyro=${sensor.name}")
PLog.i(TAG, "MGC htd feeder started with gyro=${sensor.name}, session=$sessionId, active=$activeSessionCount")
resultSequence
}
@@ -745,6 +748,7 @@ class RealtimeStabilizationCoordinator(context: Context) {
bufferedImages.values.forEach { it.pendingSessionIds.remove(sessionId) }
closeFullyConsumedImagesLocked()
activeSessionCount = activeSessions.size
PLog.i(TAG, "MGC consumer released: session=$sessionId, active=$activeSessionCount, bufferedImages=${bufferedImages.size}")
if (activeSessionCount > 0) return
sensorManager.unregisterListener(sensorListener)
sensorThread?.quitSafely()
@@ -903,6 +907,7 @@ class RealtimeStabilizationCoordinator(context: Context) {
TAG,
"MGC feeder state: boundary#$boundaryCount=$currentBoundaryNs, " +
"queuedBoundaries=${frameBoundaries.size}, metadata=${frameMetadata.size}, " +
"bufferedImages=${bufferedImages.size}, " +
"pendingGyro=${pendingGyroSamples.size}, " +
"gyroLagMs=${timestampLagMs(currentBoundaryNs, lastProcessedGyroTimestampNs)}" +
"(dead=$gyroDead), " +
@@ -1041,22 +1046,6 @@ class RealtimeStabilizationCoordinator(context: Context) {
}
}
private fun trimBufferedImagesLocked() {
while (bufferedImages.size > MAX_BUFFERED_STABILIZATION_IMAGES) {
val oldestEntry = bufferedImages.entries.firstOrNull {
it.value.acquiredLeaseCount == 0
} ?: return
val oldestTimestamp = oldestEntry.key
val oldest = bufferedImages.remove(oldestTimestamp) ?: continue
oldest.image.close()
PLog.w(
TAG,
"MGC YUV queue overflow; dropping source image $oldestTimestamp " +
"before native result, queued=${bufferedImages.size}",
)
}
}
private fun closeFullyConsumedImagesLocked() {
val iterator = bufferedImages.entries.iterator()
while (iterator.hasNext()) {
@@ -1119,7 +1108,7 @@ class RealtimeStabilizationCoordinator(context: Context) {
@Synchronized
fun dequeueFrame(): StabilizationFrame? = dequeueFrameThrough(Long.MAX_VALUE)
/** Photo preview presents the freshest pose; recording keeps the sequential API. */
/** Preview presents the freshest pose; recording keeps the sequential API. */
@Synchronized
fun dequeueLatestFrame(): StabilizationFrame? {
if (!active) return null
@@ -6,6 +6,7 @@ import android.media.ImageReader
import android.os.Handler
import com.hinnka.mycamera.utils.PLog
import java.util.concurrent.atomic.AtomicBoolean
import java.util.concurrent.atomic.AtomicInteger
/**
* Camera YUV input for photo preview and EIS. Supports latest-frame display or FIFO stabilization,
@@ -14,12 +15,14 @@ import java.util.concurrent.atomic.AtomicBoolean
internal class StabilizationImageReader(
val width: Int,
val height: Int,
maxImages: Int,
private val maxImages: Int,
) : AutoCloseable {
private val lock = Any()
private val reader = ImageReader.newInstance(width, height, ImageFormat.YUV_420_888, maxImages)
val surface = reader.surface
private var acquiredImageCount = 0
private var availabilityHandler: Handler? = null
private var availabilityListener: ((StabilizationImageReader) -> Unit)? = null
@Volatile
var isClosed = false
@@ -28,20 +31,22 @@ internal class StabilizationImageReader(
fun setOnImageAvailableListener(handler: Handler, listener: (StabilizationImageReader) -> Unit) {
synchronized(lock) {
check(!isClosed)
availabilityHandler = handler
availabilityListener = listener
reader.setOnImageAvailableListener({ listener(this) }, handler)
}
}
fun acquireNextImage(): AcquiredImage? = synchronized(lock) {
// A callback queued before retirement must not acquire another frame.
if (isClosed) return@synchronized null
if (isClosed || acquiredImageCount >= maxImages) return@synchronized null
val image = reader.acquireNextImage() ?: return@synchronized null
acquiredImageCount += 1
AcquiredImage(this, image)
}
fun acquireLatestImage(): AcquiredImage? = synchronized(lock) {
if (isClosed) return@synchronized null
if (isClosed || acquiredImageCount >= maxImages) return@synchronized null
val image = reader.acquireLatestImage() ?: return@synchronized null
acquiredImageCount += 1
AcquiredImage(this, image)
@@ -51,6 +56,8 @@ internal class StabilizationImageReader(
synchronized(lock) {
if (isClosed) return
isClosed = true
availabilityHandler = null
availabilityListener = null
reader.setOnImageAvailableListener(null, null)
if (acquiredImageCount == 0) {
reader.close()
@@ -62,26 +69,53 @@ internal class StabilizationImageReader(
private fun releaseImage(image: Image) {
synchronized(lock) {
val wasAtCapacity = acquiredImageCount == maxImages
image.close()
acquiredImageCount -= 1
if (isClosed && acquiredImageCount == 0) {
reader.close()
PLog.d("StabilizationImageReader", "Closed retired ${width}x$height reader after its last image")
} else if (!isClosed && wasAtCapacity) {
// FIFO consumers can hold every lease. Once one is returned, drain images
// already queued in ImageReader even if no new availability callback arrives.
availabilityHandler?.post {
val listener = synchronized(lock) { availabilityListener }
listener?.invoke(this)
}
}
}
}
class AcquiredImage internal constructor(
private class SharedImage(
val owner: StabilizationImageReader,
val image: Image,
) : AutoCloseable {
) {
val references = AtomicInteger(1)
}
class AcquiredImage private constructor(private val shared: SharedImage) : AutoCloseable {
internal constructor(owner: StabilizationImageReader, image: Image) : this(SharedImage(owner, image))
val owner get() = shared.owner
val image get() = shared.image
val timestampNs = image.timestamp
val width = image.width
val height = image.height
private val closed = AtomicBoolean(false)
fun retain(): AcquiredImage {
check(!closed.get()) { "Cannot retain a closed YUV lease" }
while (true) {
val count = shared.references.get()
check(count > 0) { "YUV image has already been released" }
if (shared.references.compareAndSet(count, count + 1)) return AcquiredImage(shared)
}
}
override fun close() {
if (closed.compareAndSet(false, true)) owner.releaseImage(image)
if (closed.compareAndSet(false, true) && shared.references.decrementAndGet() == 0) {
owner.releaseImage(image)
}
}
}
}
@@ -1,5 +1,6 @@
package com.hinnka.mycamera.ui.camera
import com.hinnka.mycamera.lut.SharedEisRgbFrameChannel
import com.hinnka.mycamera.camera.PreviewYuvFrameChannel
import android.content.Context
import android.graphics.Bitmap
@@ -171,6 +172,17 @@ class CameraGLSurfaceView @JvmOverloads constructor(
}
}
private var currentSharedEisRgbFrames: SharedEisRgbFrameChannel? = null
fun setSharedEisRgbFrames(channel: SharedEisRgbFrameChannel?) {
if (currentSharedEisRgbFrames === channel) return
currentSharedEisRgbFrames = channel
queueEvent {
renderer.setSharedEisRgbFrames(channel)
requestRender()
}
}
private var currentPreviewYuvChannel: PreviewYuvFrameChannel? = null
fun setPreviewYuvChannel(channel: PreviewYuvFrameChannel?) {
@@ -471,8 +483,10 @@ class CameraGLSurfaceView @JvmOverloads constructor(
}
override fun onPause() {
renderer.setRenderingPaused(true)
super.onPause()
// Stop consumers after the last draw has completed, so an in-flight draw cannot
// re-register a stabilization session after it has been stopped.
renderer.setRenderingPaused(true)
PLog.d(TAG, "onPause")
}
@@ -503,9 +517,9 @@ class CameraGLSurfaceView @JvmOverloads constructor(
currentSurface?.release()
currentSurface = null
// 在 GL 线程中释放资源
queueEvent {
renderer.release()
}
// super has joined the GL thread and destroyed its EGL context. Queuing cleanup
// now would never run, leaving the old EIS consumer holding every future image.
// GL objects are owned by that destroyed context; release CPU/native ownership here.
renderer.releaseAfterGlThreadExit()
}
}
@@ -1,5 +1,6 @@
package com.hinnka.mycamera.ui.camera
import com.hinnka.mycamera.lut.SharedEisRgbFrameChannel
import com.hinnka.mycamera.camera.PreviewYuvFrameChannel
import android.graphics.SurfaceTexture
import android.util.Size
@@ -83,6 +84,7 @@ fun CameraPreviewGL(
focusPeakingEnabled: Boolean = true,
stabilizationCoordinator: RealtimeStabilizationCoordinator? = null,
previewYuvChannel: PreviewYuvFrameChannel? = null,
sharedEisRgbFrames: SharedEisRgbFrameChannel? = null,
stabilizationInputSize: Size = previewSize,
photoPreviewStabilizationEnabled: Boolean = false,
videoPreviewStabilizationEnabled: Boolean = false,
@@ -253,6 +255,7 @@ fun CameraPreviewGL(
)
glSurfaceView.setStabilizationCoordinator(stabilizationCoordinator)
glSurfaceView.setPreviewYuvChannel(previewYuvChannel)
glSurfaceView.setSharedEisRgbFrames(sharedEisRgbFrames)
val previewStabilizationUseCase = when {
captureMode == CaptureMode.VIDEO &&
videoPreviewStabilizationEnabled -> StabilizationUseCase.VIDEO
@@ -330,7 +333,9 @@ fun CameraPreviewGL(
)
})
glSurfaceView.setMeteringMode(meteringMode)
glSurfaceView.setLivePhotoRecorder(livePhotoRecorder)
glSurfaceView.setLivePhotoRecorder(
livePhotoRecorder.takeIf { captureMode == CaptureMode.PHOTO }
)
glSurfaceView.setVideoLogProfile(videoLogProfile)
glSurfaceView.setNightVisionEnabled(nightVisionEnabled)
glSurfaceView.setAutoFocus(isAutoFocus)
@@ -324,6 +324,7 @@ fun CameraScreen(
}
LifecycleEventEffect(Lifecycle.Event.ON_PAUSE) {
lensSwitchTransition.cancel()
viewModel.pauseCameraScreen()
viewModel.setLocationTrackingForeground(false)
}
@@ -1356,6 +1357,7 @@ fun CameraScreen(
focusPeakingEnabled = focusPeakingEnabled && !state.isHyperfocalFocusEnabled,
stabilizationCoordinator = viewModel.realtimeStabilizationCoordinator,
previewYuvChannel = viewModel.previewYuvChannel,
sharedEisRgbFrames = viewModel.sharedEisRgbFrames,
stabilizationInputSize = if (
state.captureMode == CaptureMode.VIDEO &&
state.videoConfig.stabilizationMode ==
@@ -177,6 +177,7 @@ import com.hinnka.mycamera.ui.components.rememberBackgroundPainter
import com.hinnka.mycamera.update.AppUpdateManager
import com.hinnka.mycamera.utils.DeviceUtil
import com.hinnka.mycamera.viewmodel.CameraViewModel
import com.hinnka.mycamera.video.VideoInputMode
import com.hinnka.mycamera.video.VideoRecordingPath
import com.hinnka.mycamera.video.VideoStabilizationMode
import java.io.File
@@ -345,6 +346,7 @@ fun SettingsScreen(
var edgeLevel by rememberPreference(UserPreferences::edgeLevel)
val retainCaptureSettings by preferenceValue { it.retainCaptureSettings }
var videoNrLevel by rememberPreference(UserPreferences::videoNrLevel)
var videoInputMode by rememberPreference(UserPreferences::videoInputMode)
var videoEdgeLevel by rememberPreference(UserPreferences::videoEdgeLevel)
val vendorCaptureSettingsByLens by preferenceValue { it.vendorCaptureSettingsByLens }
val customVendorKeySettings by preferenceValue { it.customVendorKeySettings }
@@ -1590,6 +1592,15 @@ fun SettingsScreen(
}
SettingsPage.VIDEO -> {
val videoSettingsEnabled = !state.videoRecordingState.isRecording &&
!state.videoRecordingState.isProcessing
val eisRequiresYuv = userPreferences.videoStabilizationMode ==
VideoStabilizationMode.ENHANCED
val usesYuvInput = userPreferences.effectiveVideoInputMode == VideoInputMode.YUV
val videoInputLabels = listOf(
VideoInputMode.OES to stringResource(R.string.settings_video_input_oes),
VideoInputMode.YUV to stringResource(R.string.settings_video_input_yuv),
)
val stabilizationModes = state.videoCapabilities
.availableStabilizationModes
.ifEmpty {
@@ -1618,18 +1629,46 @@ fun SettingsScreen(
title = stringResource(R.string.settings_section_video),
showTitle = false
) {
DropdownSettingItem(
title = stringResource(R.string.settings_video_input_mode),
description = stringResource(
if (eisRequiresYuv) R.string.settings_video_input_eis_required
else R.string.settings_video_input_mode_description
),
value = videoInputLabels.first {
it.first == userPreferences.effectiveVideoInputMode
}.second,
options = videoInputLabels.map { it.second },
isLoading = false,
onExpanded = {},
onOptionSelected = { selectedLabel ->
videoInputLabels.firstOrNull { it.second == selectedLabel }
?.first?.let { videoInputMode = it }
},
enabled = videoSettingsEnabled && !eisRequiresYuv,
)
HorizontalDivider(
color = Color.White.copy(alpha = 0.1f),
modifier = Modifier.padding(vertical = 12.dp)
)
QualityLevelSetting(
title = stringResource(R.string.settings_nr_level),
description = stringResource(R.string.settings_video_nr_level_description),
description = stringResource(
if (usesYuvInput) R.string.settings_video_nr_yuv_description
else R.string.settings_video_nr_level_description
),
levels = listOf(
NoiseReductionLevel.OFF to stringResource(R.string.settings_nr_level_off),
NoiseReductionLevel.FAST to stringResource(R.string.settings_nr_level_fast),
NoiseReductionLevel.HIGH_QUALITY to stringResource(R.string.settings_nr_level_high_quality),
NoiseReductionLevel.ZERO_SHUTTER_LAG to stringResource(R.string.settings_nr_level_zsl),
NoiseReductionLevel.MINIMAL to stringResource(R.string.settings_nr_level_minimal)
),
currentLevel = videoNrLevel,
onLevelSelected = { videoNrLevel = it }
).filterNot { usesYuvInput && it.first == NoiseReductionLevel.HIGH_QUALITY },
currentLevel = userPreferences.effectiveVideoNrLevel,
onLevelSelected = { videoNrLevel = it },
enabled = videoSettingsEnabled,
)
HorizontalDivider(
@@ -1647,7 +1686,8 @@ fun SettingsScreen(
3 to stringResource(R.string.settings_nr_level_zsl)
),
currentLevel = videoEdgeLevel,
onLevelSelected = { videoEdgeLevel = it }
onLevelSelected = { videoEdgeLevel = it },
enabled = videoSettingsEnabled,
)
HorizontalDivider(
@@ -1669,6 +1709,7 @@ fun SettingsScreen(
?.first
?.let(viewModel::setVideoStabilizationMode)
},
enabled = videoSettingsEnabled,
)
if (DeviceUtil.isOppo) {
@@ -1682,11 +1723,13 @@ fun SettingsScreen(
R.string.settings_oppo_super_stabilization
),
description = stringResource(
R.string.settings_oppo_super_stabilization_description
if (usesYuvInput) R.string.settings_oppo_super_stabilization_yuv_disabled
else R.string.settings_oppo_super_stabilization_description
),
checked = userPreferences.oppoSuperStabilizationEnabled,
checked = userPreferences.effectiveOppoSuperStabilizationEnabled,
onCheckedChange =
viewModel::setOppoSuperStabilizationEnabled,
enabled = videoSettingsEnabled && !usesYuvInput,
)
}
@@ -3891,7 +3934,7 @@ fun DropdownSettingItem(
)
DropdownMenu(
expanded = expanded,
expanded = expanded && enabled,
onDismissRequest = { expanded = false },
modifier = Modifier.background(Color(0xFF2C2C2E))
) {
@@ -5444,14 +5487,15 @@ fun <T> QualityLevelSetting(
levels: List<Pair<T, String>>,
currentLevel: T,
onLevelSelected: (T) -> Unit,
modifier: Modifier = Modifier
modifier: Modifier = Modifier,
enabled: Boolean = true,
) {
Column(modifier = modifier.fillMaxWidth()) {
if (title != null) {
Text(
text = title,
color = Color.White,
color = Color.White.copy(alpha = if (enabled) 1f else 0.38f),
fontSize = 16.sp,
fontWeight = FontWeight.Normal,
modifier = Modifier.padding(bottom = 4.dp)
@@ -5460,7 +5504,7 @@ fun <T> QualityLevelSetting(
if (description != null) {
Text(
text = description,
color = Color.White.copy(alpha = 0.6f),
color = Color.White.copy(alpha = if (enabled) 0.6f else 0.38f),
fontSize = 13.sp,
lineHeight = 18.sp,
modifier = Modifier.padding(bottom = 12.dp)
@@ -5479,14 +5523,16 @@ fun <T> QualityLevelSetting(
.height(36.dp)
.clip(RoundedCornerShape(8.dp))
.background(
if (isSelected) AccentColor else Color.White.copy(alpha = 0.1f)
if (isSelected) AccentColor.copy(alpha = if (enabled) 1f else 0.38f)
else Color.White.copy(alpha = if (enabled) 0.1f else 0.04f)
)
.clickable { onLevelSelected(level) },
.clickable(enabled = enabled) { onLevelSelected(level) },
contentAlignment = Alignment.Center
) {
Text(
text = label,
color = if (isSelected) OnAccentColor else Color.White,
color = (if (isSelected) OnAccentColor else Color.White)
.copy(alpha = if (enabled) 1f else 0.38f),
fontSize = 12.sp,
fontWeight = if (isSelected) FontWeight.Bold else FontWeight.Normal,
textAlign = TextAlign.Center,
@@ -4,7 +4,6 @@ import android.graphics.ImageFormat
import android.graphics.SurfaceTexture
import android.hardware.camera2.CameraCharacteristics
import android.hardware.camera2.CaptureRequest
import android.media.MediaRecorder
import android.os.Build
import android.util.Range
import android.util.Size
@@ -15,7 +14,6 @@ import kotlin.math.abs
object VideoCapabilitiesResolver {
private const val TAG = "VideoCapabilitiesResolver"
private const val VIDEO_PREVIEW_SHORT_EDGE = 1080
private const val VIDEO_PREVIEW_ASPECT_TOLERANCE = 0.01f
private const val EIGHT_MP_SOURCE_MIN_PIXELS = 7_500_000L
private const val EIGHT_MP_SOURCE_MAX_PIXELS = 12_000_000L
@@ -36,39 +34,24 @@ object VideoCapabilitiesResolver {
) ?: intArrayOf()
val isFlashSupported = characteristics.get(CameraCharacteristics.FLASH_INFO_AVAILABLE) ?: false
val streamConfigMap = characteristics.get(CameraCharacteristics.SCALER_STREAM_CONFIGURATION_MAP)
val previewOutputSizes = streamConfigMap?.getOutputSizes(SurfaceTexture::class.java)?.toList().orEmpty()
val yuvOutputSizes = streamConfigMap?.getOutputSizes(ImageFormat.YUV_420_888)?.toList().orEmpty()
// Dedicated recording uses a SurfaceTexture input, including full-sensor sizes
// that may not be advertised for MediaRecorder.
// 无原生 4K 录制流但存在 8MP 级 4:3 源时,同样以 SurfaceTexture 流作为录制门控。
val advertisedRecordingSizes = resolveRecordingOutputSizes(characteristics)
val hasNativeUhdRecordingSize = advertisedRecordingSizes.any {
maxOf(it.width, it.height) >= VideoResolutionPreset.UHD_2160P.longEdge
}
val recordingOutputSizes = when {
requestedConfig.aspectRatio == VideoAspectRatio.OPEN_GATE -> previewOutputSizes
!hasNativeUhdRecordingSize && previewOutputSizes.any(::isEightMpFourThreeSource) ->
previewOutputSizes
else -> advertisedRecordingSizes
}
val usesYuv = requestedConfig.effectiveInputMode == VideoInputMode.YUV
val oesOutputSizes = streamConfigMap?.getOutputSizes(SurfaceTexture::class.java)?.toList().orEmpty()
val inputOutputSizes = if (usesYuv) yuvOutputSizes else oesOutputSizes
val sensorOrientation = characteristics.get(CameraCharacteristics.SENSOR_ORIENTATION) ?: 0
val activeArray = characteristics.get(CameraCharacteristics.SENSOR_INFO_ACTIVE_ARRAY_SIZE)
val openGateAspect = resolveOpenGatePortraitAspectRatio(activeArray, sensorOrientation)
val availableResolutions = VideoResolutionPreset.entries.filter { preset ->
preset.isAvailableFor(requestedConfig.aspectRatio) &&
findBestOutputSize(recordingOutputSizes, preset, requestedConfig.aspectRatio, openGateAspect) != null &&
findBestOutputSize(previewOutputSizes, preset, requestedConfig.aspectRatio, openGateAspect) != null
findBestOutputSize(inputOutputSizes, preset, requestedConfig.aspectRatio, openGateAspect) != null
}
val recordingSizesByResolution = availableResolutions.mapNotNull { preset ->
findBestOutputSize(recordingOutputSizes, preset, requestedConfig.aspectRatio, openGateAspect)
?.let { preset to it }
}.toMap()
val cameraInputSizesByResolution = availableResolutions.mapNotNull { preset ->
findBestOutputSize(previewOutputSizes, preset, requestedConfig.aspectRatio, openGateAspect)
findBestOutputSize(inputOutputSizes, preset, requestedConfig.aspectRatio, openGateAspect)
?.let { preset to it }
}.toMap()
val recordingSizesByResolution = cameraInputSizesByResolution
val enhancedStabilizationInputSizesByResolution = availableResolutions.mapNotNull { preset ->
findBestOutputSize(yuvOutputSizes, preset, requestedConfig.aspectRatio, openGateAspect)
?.let { preset to it }
@@ -83,19 +66,19 @@ object VideoCapabilitiesResolver {
requestedConfig.aspectRatio.getPortraitAspectRatio(openGateAspect)
)
val previewSize = findFixedPreviewOutputSize(
outputSizes = previewOutputSizes,
aspectRatio = requestedConfig.aspectRatio,
openGatePortraitAspectRatio = openGateAspect
) ?: VideoResolutionPreset.FHD_1080P.resolveOutputSize(
requestedConfig.aspectRatio.getPortraitAspectRatio(openGateAspect)
)
val cameraInputSize = cameraInputSizesByResolution[resolvedResolution] ?: previewSize
val cameraInputSize = cameraInputSizesByResolution[resolvedResolution]
?: inputOutputSizes.maxByOrNull { it.width.toLong() * it.height }
?: recordingSize
val previewSize = if (usesYuv) cameraInputSize else {
findFixedPreviewOutputSize(oesOutputSizes, requestedConfig.aspectRatio, openGateAspect)
?: cameraInputSize
}
val availableFps = resolveAvailableFps(
characteristics = characteristics,
cameraInputSize = cameraInputSize,
previewSize = previewSize
previewSize = previewSize,
usesYuv = usesYuv,
)
val resolvedFps = requestedConfig.fps.takeIf { availableFps.contains(it) }
?: availableFps.firstOrNull()
@@ -137,6 +120,13 @@ object VideoCapabilitiesResolver {
else VideoStabilizationMode.OFF
}
// A rejected EIS+ request must also resolve sizes for the restored input format.
if (requestedConfig.inputMode.withStabilization(resolvedStabilizationMode) !=
requestedConfig.effectiveInputMode
) {
return resolve(characteristics, requestedConfig.copy(stabilizationMode = resolvedStabilizationMode),
algorithmicStabilizationSupported = false)
}
return VideoCapabilitySnapshot(
config = requestedConfig.copy(
resolution = resolvedResolution,
@@ -256,7 +246,7 @@ object VideoCapabilitiesResolver {
}
val candidates = aspectMatchedSizes.ifEmpty { validSizes }
val sizesWithinLimit = candidates.filter {
minOf(it.width, it.height) <= VIDEO_PREVIEW_SHORT_EDGE
minOf(it.width, it.height) <= 1080 && maxOf(it.width, it.height) <= 1920
}
return if (sizesWithinLimit.isNotEmpty()) {
@@ -277,12 +267,13 @@ object VideoCapabilitiesResolver {
private fun resolveAvailableFps(
characteristics: CameraCharacteristics,
cameraInputSize: Size,
previewSize: Size
previewSize: Size,
usesYuv: Boolean,
): List<VideoFpsPreset> {
val outputRanges = characteristics.readMetadataOrNull(CameraCharacteristics.CONTROL_AE_AVAILABLE_TARGET_FPS_RANGES)
?: return emptyList()
if (outputRanges.isEmpty()) return emptyList()
val minFrameDurationNs = resolveMinFrameDurationNs(characteristics, cameraInputSize, previewSize)
val minFrameDurationNs = resolveMinFrameDurationNs(characteristics, cameraInputSize, previewSize, usesYuv)
val maxFpsByDuration = if (minFrameDurationNs > 0) {
(1_000_000_000.0 / minFrameDurationNs.toDouble()).toInt()
} else {
@@ -321,51 +312,26 @@ object VideoCapabilitiesResolver {
return range.upper >= fps && range.lower <= fps
}
private fun resolveRecordingOutputSizes(characteristics: CameraCharacteristics): List<Size> {
val streamConfigMap = characteristics.get(CameraCharacteristics.SCALER_STREAM_CONFIGURATION_MAP)
return try {
streamConfigMap?.getOutputSizes(MediaRecorder::class.java)?.toList().orEmpty()
} catch (e: Exception) {
PLog.w(TAG, "Failed to query MediaRecorder output sizes: ${e.message}")
emptyList()
}.ifEmpty {
streamConfigMap?.getOutputSizes(SurfaceTexture::class.java)?.toList().orEmpty()
}
}
private fun resolveMinFrameDurationNs(
characteristics: CameraCharacteristics,
cameraInputSize: Size,
previewSize: Size
previewSize: Size,
usesYuv: Boolean,
): Long {
val streamConfigMap = characteristics.get(CameraCharacteristics.SCALER_STREAM_CONFIGURATION_MAP)
if (streamConfigMap == null) return 0L
val cameraInputDurationNs = queryMinFrameDurationNs(
streamConfigMap = streamConfigMap,
outputClass = SurfaceTexture::class.java,
outputSize = cameraInputSize,
label = "recording SurfaceTexture"
)
val previewDurationNs = queryMinFrameDurationNs(
streamConfigMap = streamConfigMap,
outputClass = SurfaceTexture::class.java,
outputSize = previewSize,
label = "preview SurfaceTexture"
)
return maxOf(cameraInputDurationNs, previewDurationNs)
}
private fun <T> queryMinFrameDurationNs(
streamConfigMap: android.hardware.camera2.params.StreamConfigurationMap,
outputClass: Class<T>,
outputSize: Size,
label: String
): Long {
return try {
streamConfigMap.getOutputMinFrameDuration(outputClass, outputSize)
if (usesYuv) {
streamConfigMap.getOutputMinFrameDuration(ImageFormat.YUV_420_888, cameraInputSize)
} else {
maxOf(
streamConfigMap.getOutputMinFrameDuration(SurfaceTexture::class.java, cameraInputSize),
streamConfigMap.getOutputMinFrameDuration(SurfaceTexture::class.java, previewSize),
)
}
} catch (e: Exception) {
PLog.w(TAG, "Failed to query $label min frame duration for $outputSize: ${e.message}")
PLog.w(TAG, "Failed to query video input min frame duration for $cameraInputSize: ${e.message}")
0L
}
}
@@ -0,0 +1,26 @@
package com.hinnka.mycamera.video
import com.hinnka.mycamera.camera.NoiseReductionLevel
enum class VideoInputMode {
OES,
YUV;
fun withStabilization(mode: VideoStabilizationMode): VideoInputMode =
if (mode == VideoStabilizationMode.ENHANCED) YUV else this
fun resolveNoiseReduction(level: Int): Int =
if (this == YUV && level == NoiseReductionLevel.HIGH_QUALITY) NoiseReductionLevel.FAST
else NoiseReductionLevel.normalize(level)
fun allowsOppoSuperStabilization(): Boolean = this == OES
}
/** Apply interdependent video preferences as one camera configuration. */
data class VideoPipelineSettings(
val inputMode: VideoInputMode,
val stabilizationMode: VideoStabilizationMode,
val noiseReduction: Int,
val edge: Int,
val oppoSuperStabilization: Boolean,
)
@@ -1,5 +1,6 @@
package com.hinnka.mycamera.video
import com.hinnka.mycamera.lut.SharedEisRgbFrameChannel
import android.Manifest
import android.content.Context
import android.content.pm.PackageManager
@@ -23,6 +24,7 @@ import com.hinnka.mycamera.lut.VideoColorEffectLayer
import com.hinnka.mycamera.stabilization.DEFAULT_VIDEO_STABILIZATION_LOOKAHEAD
import com.hinnka.mycamera.stabilization.DEFAULT_VIDEO_STABILIZATION_STRENGTH
import com.hinnka.mycamera.stabilization.RealtimeStabilizationCoordinator
import com.hinnka.mycamera.stabilization.StabilizationImageReader
import com.hinnka.mycamera.stabilization.normalizeStabilizationLookahead
import com.hinnka.mycamera.stabilization.normalizeStabilizationStrength
import com.hinnka.mycamera.utils.PLog
@@ -38,11 +40,13 @@ import kotlinx.coroutines.launch
import kotlinx.coroutines.runBlocking
import kotlinx.coroutines.withContext
import java.nio.ByteBuffer
import java.util.ArrayDeque
import java.util.concurrent.Executors
class VideoRecorder(
private val context: Context,
private val stabilizationCoordinator: RealtimeStabilizationCoordinator? = null,
private val sharedEisRgbFrames: SharedEisRgbFrameChannel? = null,
) {
companion object {
@@ -125,6 +129,7 @@ class VideoRecorder(
private var requestedOutputSize = Size(1080, 1920)
private var requestedCameraInputSize = Size(1920, 1080)
private var requestedColorLayers: List<VideoColorEffectLayer> = emptyList()
private var requestedInputMode = VideoInputMode.OES
private var requestedEnhancedStabilization = false
private var requestedEnhancedStabilizationStrength = DEFAULT_VIDEO_STABILIZATION_STRENGTH
private var requestedEnhancedStabilizationLookahead = DEFAULT_VIDEO_STABILIZATION_LOOKAHEAD
@@ -161,11 +166,11 @@ class VideoRecorder(
private var lastMuxedVideoPresentationTimeUs = Long.MIN_VALUE
private var lastMuxedAudioPresentationTimeUs = Long.MIN_VALUE
private var pendingRealtimeFrameCount = 0
private val pendingYuvFrames = ArrayDeque<StabilizationImageReader.AcquiredImage>()
private var renderLoopRunning = false
private var statsWindowStartMs: Long = 0L
private var statsIncomingFrames: Int = 0
private var statsAcceptedFrames: Int = 0
private var statsReplacedPendingFrames: Int = 0
private var statsRenderedFrames: Int = 0
private var statsRenderTimeTotalMs: Long = 0L
private var statsRenderTimeMaxMs: Long = 0L
@@ -174,13 +179,24 @@ class VideoRecorder(
private var audioDrainJob: Job? = null
private var audioRecordJob: Job? = null
val usesDedicatedCameraInput: Boolean
get() = isRecording
val cameraInputSurface: Surface?
get() = renderer?.inputSurface.takeIf {
isRecording && !stopRequested
get() = renderer?.inputSurface.takeIf { isRecording && !stopRequested }
internal val acceptsYuvFrames: Boolean
get() = isRecording && cameraInputStarted && !stopRequested && !isPaused &&
requestedInputMode == VideoInputMode.YUV && !requestedEnhancedStabilization
/** Takes ownership of a recording lease; preview has an independent latest-only lease. */
internal fun submitYuvFrame(frame: StabilizationImageReader.AcquiredImage) {
synchronized(realtimeFrameLock) {
if (!acceptsYuvFrames) {
frame.close()
return
}
pendingYuvFrames.addLast(frame)
enqueueRealtimeFrameLocked()
}
}
fun startRecording(
size: Size,
@@ -194,6 +210,7 @@ class VideoRecorder(
sensorOrientationDegrees: Int = 0,
orientationHintDegrees: Int = 0,
flipEncodedFrame: Boolean = false,
inputMode: VideoInputMode = VideoInputMode.OES,
enhancedStabilization: Boolean = false,
enhancedStabilizationStrength: Float = DEFAULT_VIDEO_STABILIZATION_STRENGTH,
enhancedStabilizationLookahead: Int = DEFAULT_VIDEO_STABILIZATION_LOOKAHEAD,
@@ -207,8 +224,8 @@ class VideoRecorder(
requestedOrientationHintDegrees = normalizeOrientationHint(orientationHintDegrees)
requestedOutputSize = Size(size.width.align16(), size.height.align16())
requestedCameraInputSize = cameraInputSize
// SurfaceTexture 变换后的 OES 内容已经处于自然显示方向,编码画布必须继续使用
// 已解析的显示尺寸(片门全开使用最大相机输入尺寸)。设备横竖屏差异只通过容器 rotation metadata 表达。
// YUV 经传感器方向矩阵呈现到自然显示方向;编码画布使用解析后的显示尺寸。
// 片门全开使用最大相机输入尺寸,设备横竖屏差异通过容器 rotation metadata 表达。
requestedSize = requestedOutputSize
requestedFps = fps
requestedBitrateMbps = bitrateMbps
@@ -218,6 +235,7 @@ class VideoRecorder(
requestedCameraTimestampSource = cameraTimestampSource
requestedSensorOrientationDegrees = sensorOrientationDegrees
requestedFlipEncodedFrame = flipEncodedFrame
requestedInputMode = if (enhancedStabilization) VideoInputMode.YUV else inputMode
requestedEnhancedStabilization = enhancedStabilization
requestedEnhancedStabilizationStrength =
normalizeStabilizationStrength(enhancedStabilizationStrength)
@@ -233,7 +251,6 @@ class VideoRecorder(
statsWindowStartMs = 0L
statsIncomingFrames = 0
statsAcceptedFrames = 0
statsReplacedPendingFrames = 0
statsRenderedFrames = 0
statsRenderTimeTotalMs = 0L
statsRenderTimeMaxMs = 0L
@@ -262,7 +279,7 @@ class VideoRecorder(
"sensorOrientation=$requestedSensorOrientationDegrees, " +
"enhancedStabilization=$requestedEnhancedStabilization, " +
"stabilizationStrength=$requestedEnhancedStabilizationStrength, " +
"input=${if (requestedEnhancedStabilization) "timestamped-yuv" else "dedicated-surface-texture"}, " +
"input=${if (requestedEnhancedStabilization) "stabilized-shared-yuv" else requestedInputMode.name}, " +
"cameraTimestampSource=$requestedCameraTimestampSource, " +
"path=${requestedRecordingPath.name}, uri=${requestedRecordingTreeUri?.take(48)}"
)
@@ -276,7 +293,7 @@ class VideoRecorder(
if (audioEnabled) {
startAudioLoop()
}
PLog.d(TAG, "Dedicated Camera2 recording input started")
PLog.d(TAG, "Camera2 recording input started: $requestedInputMode")
return true
}
@@ -289,7 +306,7 @@ class VideoRecorder(
try {
audioRecordJob?.join()
withContext(renderDispatcher) {
drainRealtimeFrames(allowWhenStopping = true)
drainRealtimeFrames()
renderer?.pauseStabilization()
signalVideoEndOfInputStream()
}
@@ -368,6 +385,8 @@ class VideoRecorder(
requestedFlipEncodedFrame && requestedOrientationHintDegrees % 180 != 0,
encoderColorConfig = encoderColorConfig,
stabilizationCoordinator = stabilizationCoordinator,
sharedEisRgbFrames = sharedEisRgbFrames,
inputMode = requestedInputMode,
enhancedStabilizationEnabled = requestedEnhancedStabilization,
enhancedStabilizationStrength = requestedEnhancedStabilizationStrength,
enhancedStabilizationLookahead = requestedEnhancedStabilizationLookahead,
@@ -384,24 +403,21 @@ class VideoRecorder(
}
private fun onRealtimeFrameAvailable() {
if (!isRecording || stopRequested || isPaused) return
statsIncomingFrames += 1
synchronized(realtimeFrameLock) {
if (pendingRealtimeFrameCount > 0) {
statsReplacedPendingFrames += 1
}
pendingRealtimeFrameCount = if (requestedEnhancedStabilization) {
pendingRealtimeFrameCount + 1
} else {
// SurfaceTexture itself is latest-only; multiple callbacks before the GL
// consumer runs therefore represent one materializable OES frame.
1
}
if (!renderLoopRunning) {
renderLoopRunning = true
scope.launch(renderDispatcher) {
drainRealtimeFrames(allowWhenStopping = false)
}
if (!isRecording || stopRequested || isPaused) return
enqueueRealtimeFrameLocked()
}
}
private fun enqueueRealtimeFrameLocked() {
statsIncomingFrames += 1
// SurfaceTexture exposes only its newest frame; YUV leases and EIS results are FIFO.
pendingRealtimeFrameCount = if (requestedInputMode == VideoInputMode.OES) 1
else pendingRealtimeFrameCount + 1
if (!renderLoopRunning) {
renderLoopRunning = true
scope.launch(renderDispatcher) {
drainRealtimeFrames()
}
}
}
@@ -870,31 +886,38 @@ class VideoRecorder(
}
}
private fun drainRealtimeFrames(allowWhenStopping: Boolean) {
private fun drainRealtimeFrames() {
while (true) {
val hasFrame = synchronized(realtimeFrameLock) {
val yuvFrame = synchronized(realtimeFrameLock) {
if (pendingRealtimeFrameCount <= 0) {
renderLoopRunning = false
return
}
pendingRealtimeFrameCount -= 1
true
if (requestedInputMode == VideoInputMode.OES || requestedEnhancedStabilization) null else pendingYuvFrames.removeFirst()
}
if (!hasFrame ||
!isRecording ||
(stopRequested && !allowWhenStopping) ||
isPaused
) {
// Ordinary FIFO leases were captured before stop and must be drained. EIS
// notifications are wake-ups: consuming them after stop can select newer frames
// still being produced for preview and accidentally extend the recording.
if (!isRecording || isPaused || (stopRequested && (requestedEnhancedStabilization || requestedInputMode == VideoInputMode.OES))) {
yuvFrame?.close()
continue
}
try {
val videoRenderer = renderer ?: continue
val videoRenderer = renderer
if (videoRenderer == null) {
yuvFrame?.close()
continue
}
val renderStartMs = SystemClock.elapsedRealtime()
val presentationTimeNs = videoRenderer.renderLatestFrame(
mapPresentationTimeNs = ::mapCameraTimestampToBoottimeNs,
) ?: continue
val presentationTimeNs = yuvFrame.use { frame ->
videoRenderer.renderLatestFrame(
mapPresentationTimeNs = ::mapCameraTimestampToBoottimeNs,
yuvImage = frame?.image,
)
} ?: continue
establishTimelineOrigin(presentationTimeNs / 1_000L)
val renderCostMs = (SystemClock.elapsedRealtime() - renderStartMs).coerceAtLeast(0L)
statsAcceptedFrames += 1
@@ -940,14 +963,13 @@ class VideoRecorder(
TAG,
"Video encoder stats: requested=${requestedFps}, incomingFps=${"%.1f".format(incomingFps)}, " +
"acceptedFps=${"%.1f".format(acceptedFps)}, renderedFps=${"%.1f".format(renderedFps)}, " +
"pendingDrops=$statsReplacedPendingFrames, avgRenderMs=${"%.1f".format(avgRenderMs)}, " +
"pendingFrames=$pendingRealtimeFrameCount, avgRenderMs=${"%.1f".format(avgRenderMs)}, " +
"maxRenderMs=$statsRenderTimeMaxMs"
)
statsWindowStartMs = nowMs
statsIncomingFrames = 0
statsAcceptedFrames = 0
statsReplacedPendingFrames = 0
statsRenderedFrames = 0
statsRenderTimeTotalMs = 0L
statsRenderTimeMaxMs = 0L
@@ -1411,6 +1433,8 @@ class VideoRecorder(
activePauseStartTimeUs = UNSET_TIMESTAMP
}
synchronized(realtimeFrameLock) {
pendingYuvFrames.forEach { it.close() }
pendingYuvFrames.clear()
pendingRealtimeFrameCount = 0
renderLoopRunning = false
}
@@ -134,6 +134,7 @@ enum class VideoLogLutMode {
}
data class VideoConfig(
val inputMode: VideoInputMode = VideoInputMode.OES,
val resolution: VideoResolutionPreset = VideoResolutionPreset.FHD_1080P,
val fps: VideoFpsPreset = VideoFpsPreset.FPS_30,
val aspectRatio: VideoAspectRatio = VideoAspectRatio.RATIO_16_9,
@@ -151,6 +152,9 @@ data class VideoConfig(
val lensLockEnabled: Boolean = false,
val whiteBalanceLockEnabled: Boolean = false
) {
val effectiveInputMode: VideoInputMode
get() = inputMode.withStabilization(stabilizationMode)
fun resolveOutputSize(openGatePortraitAspectRatio: Float, cameraInputSize: Size): Size {
if (aspectRatio == VideoAspectRatio.OPEN_GATE) {
// Keep the full-sensor input aspect, scaled down to the selected preset.
@@ -630,6 +630,7 @@ class CameraViewModel(application: Application) : AndroidViewModel(application)
val livePhotoRecorder get() = cameraController.livePhotoRecorder
val realtimeStabilizationCoordinator get() = cameraController.realtimeStabilizationCoordinator
val previewYuvChannel get() = cameraController.previewYuvChannel
val sharedEisRgbFrames get() = cameraController.sharedEisRgbFrames
val isAlgorithmicStabilizationSupported: Boolean
get() = cameraController.realtimeStabilizationCoordinator.isGyroscopeAvailable
@@ -1588,6 +1589,8 @@ class CameraViewModel(application: Application) : AndroidViewModel(application)
// 保存当前的 SurfaceTexture 以便切换摄像头时重用
private var currentSurfaceTexture: SurfaceTexture? = null
private var cameraScreenResumed = false
private var cameraNeedsResume = false
private var cameraOpenInFlight = false
private var cameraReopenJob: Job? = null
private var cameraErrorRecoveryJob: Job? = null
@@ -1844,10 +1847,6 @@ class CameraViewModel(application: Application) : AndroidViewModel(application)
if (cameraController.state.value.nrLevel != level) cameraController.setNRLevel(level)
}
syncPreference({ it.edgeLevel }, cameraController::setEdgeLevel)
viewModelScope.launch {
userPreferencesRepository.flow { it.videoNrLevel to it.videoEdgeLevel }
.collect { (nr, edge) -> cameraController.setVideoImageQualitySettings(nr, edge) }
}
syncPreference({ it.rawMinShutterSpeedNs }) { value ->
if (cameraController.state.value.rawMinShutterSpeedNs != value) {
cameraController.setRawMinShutterSpeedNs(value)
@@ -1966,6 +1965,7 @@ class CameraViewModel(application: Application) : AndroidViewModel(application)
if (cameraController.state.value.meteringMode != it.meteringMode) {
cameraController.setMeteringMode(it.meteringMode)
}
cameraController.setVideoPipelineSettings(it.videoPipelineSettings)
cameraController.setCaptureMode(it.captureMode)
cameraController.setVideoResolution(it.videoResolution)
cameraController.setVideoFps(it.videoFps)
@@ -1974,10 +1974,6 @@ class CameraViewModel(application: Application) : AndroidViewModel(application)
cameraController.setVideoLogLutMode(it.videoLogLutMode)
cameraController.setVideoBitrate(it.videoBitrate)
cameraController.setVideoRecordingPath(it.videoRecordingPath, it.videoRecordingTreeUri)
cameraController.setVideoStabilizationMode(it.videoStabilizationMode)
cameraController.setOppoSuperStabilizationEnabled(
it.oppoSuperStabilizationEnabled
)
cameraController.setVideoEnhancedStabilizationStrength(
it.videoEnhancedStabilizationStrength
)
@@ -2141,6 +2137,7 @@ class CameraViewModel(application: Application) : AndroidViewModel(application)
} catch (e: IllegalArgumentException) {
// 如果保存的值无效,使用默认值
}
cameraController.setVideoPipelineSettings(prefs.videoPipelineSettings)
cameraController.setCaptureMode(prefs.captureMode)
cameraController.setVideoResolution(prefs.videoResolution)
cameraController.setVideoFps(prefs.videoFps)
@@ -2150,7 +2147,6 @@ class CameraViewModel(application: Application) : AndroidViewModel(application)
cameraController.setVideoBitrate(prefs.videoBitrate)
cameraController.setVideoAudioInputId(userPreferencesRepository.latest().videoAudioInputId)
cameraController.setVideoRecordingPath(prefs.videoRecordingPath, prefs.videoRecordingTreeUri)
cameraController.setVideoStabilizationMode(prefs.videoStabilizationMode)
cameraController.setVideoEnhancedStabilizationStrength(
prefs.videoEnhancedStabilizationStrength
)
@@ -2483,6 +2479,11 @@ class CameraViewModel(application: Application) : AndroidViewModel(application)
*/
fun openCamera(surfaceTexture: SurfaceTexture) {
PLog.d(TAG, "openCamera")
if (!cameraScreenResumed) {
currentSurfaceTexture = surfaceTexture
PLog.d(TAG, "Deferring camera open while camera screen is paused")
return
}
if (currentSurfaceTexture === surfaceTexture && (state.value.isPreviewActive || cameraOpenInFlight)) {
PLog.d(
TAG,
@@ -2498,12 +2499,14 @@ class CameraViewModel(application: Application) : AndroidViewModel(application)
surfaceTexture: SurfaceTexture,
preserveVideoRecording: Boolean = false,
) {
if (!cameraScreenResumed) return
cameraReopenJob?.cancel()
cameraOpenInFlight = true
cameraReopenJob = viewModelScope.launch {
isInitialized.first { it }
if (currentSurfaceTexture !== surfaceTexture) return@launch
if (!cameraScreenResumed || currentSurfaceTexture !== surfaceTexture) return@launch
syncVendorCaptureSettingsToController()
cameraNeedsResume = false
cameraController.openCamera(
surfaceTexture = surfaceTexture,
preserveVideoRecording = preserveVideoRecording,
@@ -2662,14 +2665,27 @@ class CameraViewModel(application: Application) : AndroidViewModel(application)
/**
* 检查相机状态并在必要时恢复
*/
fun pauseCameraScreen() {
cameraScreenResumed = false
cameraNeedsResume = true
cameraReopenJob?.cancel()
cameraOpenInFlight = false
// Keep the texture identity for a retained GL surface, but release the Camera2 device.
// A texture replacement on resume will supersede it through openCamera().
PLog.i(TAG, "Camera screen paused: releasing Camera2 device")
cameraController.closeCamera()
}
fun checkAndRecoverCamera() {
cameraScreenResumed = true
if (!state.value.isPreviewActive) {
resetExposureCompensationForCameraRestart()
}
// 如果有保存的 SurfaceTexture,重新打开相机
currentSurfaceTexture?.let { texture ->
if (!state.value.isPreviewActive && !cameraOpenInFlight) {
if ((cameraNeedsResume || !state.value.isPreviewActive) && !cameraOpenInFlight) {
PLog.i(TAG, "Camera screen resumed: reopening Camera2 device")
requestCameraOpen(texture)
} else {
PLog.d(
@@ -3647,21 +3663,9 @@ class CameraViewModel(application: Application) : AndroidViewModel(application)
}
fun setVideoStabilizationMode(mode: com.hinnka.mycamera.video.VideoStabilizationMode) {
val previousConfig = state.value.videoConfig
cameraController.setVideoStabilizationMode(mode)
val resolvedConfig = state.value.videoConfig
if (state.value.captureMode == CaptureMode.VIDEO &&
(previousConfig.resolution != resolvedConfig.resolution ||
previousConfig.fps != resolvedConfig.fps)
) {
reopenCamera()
}
if (state.value.videoRecordingState.isRecording || state.value.videoRecordingState.isProcessing) return
viewModelScope.launch {
userPreferencesRepository.update {
videoStabilizationMode = resolvedConfig.stabilizationMode
videoResolution = resolvedConfig.resolution
videoFps = resolvedConfig.fps
}
userPreferencesRepository.update { videoStabilizationMode = mode }
}
}
@@ -3674,7 +3678,7 @@ class CameraViewModel(application: Application) : AndroidViewModel(application)
}
fun setOppoSuperStabilizationEnabled(enabled: Boolean) {
cameraController.setOppoSuperStabilizationEnabled(enabled)
if (state.value.videoRecordingState.isRecording || state.value.videoRecordingState.isProcessing) return
viewModelScope.launch {
userPreferencesRepository.update { oppoSuperStabilizationEnabled = enabled }
}
@@ -1434,4 +1434,11 @@
<string name="aesthetic_show_in_gallery">在相簿列表顯示評分</string>
<string name="aesthetic_show_in_gallery_description">瀏覽時在背景為照片評分。</string>
<string name="aesthetic_note">評分來自端側 CLIP 美學模型(LAION Aesthetic Predictor),以大規模人類審美評分訓練,反映大眾視覺偏好而非創作意圖,僅供參考。</string>
<string name="settings_video_input_mode">影片處理方式</string>
<string name="settings_video_input_mode_description">選擇由系統或應用程式進行畫面色彩轉換。兩種方式皆支援濾鏡;EIS+ 需要使用應用程式處理。</string>
<string name="settings_video_input_eis_required">EIS+ 已啟用,固定使用應用程式處理。關閉 EIS+ 後可切換。</string>
<string name="settings_video_input_oes">系統處理</string>
<string name="settings_video_input_yuv">應用程式處理</string>
<string name="settings_video_nr_yuv_description">應用程式處理不支援高品質降噪;原設定為高品質時,改用快速模式。</string>
<string name="settings_oppo_super_stabilization_yuv_disabled">應用程式處理下無法使用,切換至系統處理後可使用超級防震。</string>
</resources>
@@ -1490,4 +1490,11 @@
<string name="aesthetic_show_in_gallery">在相册列表显示评分</string>
<string name="aesthetic_show_in_gallery_description">浏览时在后台为照片评分。</string>
<string name="aesthetic_note">评分来自端侧 CLIP 美学模型(LAION Aesthetic Predictor),基于大规模人类审美打分训练,反映大众视觉偏好而非创作意图,仅供参考。</string>
<string name="settings_video_input_mode">视频处理方式</string>
<string name="settings_video_input_mode_description">选择由系统或应用进行画面色彩转换。两种方式均支持滤镜;EIS+ 需要使用应用处理。</string>
<string name="settings_video_input_eis_required">EIS+ 已启用,固定使用应用处理。关闭 EIS+ 后可切换。</string>
<string name="settings_video_input_oes">系统处理</string>
<string name="settings_video_input_yuv">应用处理</string>
<string name="settings_video_nr_yuv_description">应用处理不支持高质量降噪;原设置为高质量时,改用快速模式。</string>
<string name="settings_oppo_super_stabilization_yuv_disabled">应用处理下不可用,切换至系统处理后可使用超级防抖。</string>
</resources>
@@ -1428,4 +1428,11 @@
<string name="aesthetic_show_in_gallery">在相簿列表顯示評分</string>
<string name="aesthetic_show_in_gallery_description">瀏覽時在背景為照片評分。</string>
<string name="aesthetic_note">評分來自端側 CLIP 美學模型(LAION Aesthetic Predictor),以大規模人類審美評分訓練,反映大眾視覺偏好而非創作意圖,僅供參考。</string>
<string name="settings_video_input_mode">影片處理方式</string>
<string name="settings_video_input_mode_description">選擇由系統或應用程式進行畫面色彩轉換。兩種方式皆支援濾鏡;EIS+ 需要使用應用程式處理。</string>
<string name="settings_video_input_eis_required">EIS+ 已啟用,固定使用應用程式處理。關閉 EIS+ 後可切換。</string>
<string name="settings_video_input_oes">系統處理</string>
<string name="settings_video_input_yuv">應用程式處理</string>
<string name="settings_video_nr_yuv_description">應用程式處理不支援高品質降噪;原設定為高品質時,改用快速模式。</string>
<string name="settings_oppo_super_stabilization_yuv_disabled">應用程式處理下無法使用,切換至系統處理後可使用超級防震。</string>
</resources>
@@ -1434,4 +1434,11 @@
<string name="aesthetic_show_in_gallery">在相簿列表顯示評分</string>
<string name="aesthetic_show_in_gallery_description">瀏覽時在背景為照片評分。</string>
<string name="aesthetic_note">評分來自端側 CLIP 美學模型(LAION Aesthetic Predictor),以大規模人類審美評分訓練,反映大眾視覺偏好而非創作意圖,僅供參考。</string>
<string name="settings_video_input_mode">影片處理方式</string>
<string name="settings_video_input_mode_description">選擇由系統或應用程式進行畫面色彩轉換。兩種方式皆支援濾鏡;EIS+ 需要使用應用程式處理。</string>
<string name="settings_video_input_eis_required">EIS+ 已啟用,固定使用應用程式處理。關閉 EIS+ 後可切換。</string>
<string name="settings_video_input_oes">系統處理</string>
<string name="settings_video_input_yuv">應用程式處理</string>
<string name="settings_video_nr_yuv_description">應用程式處理不支援高品質降噪;原設定為高品質時,改用快速模式。</string>
<string name="settings_oppo_super_stabilization_yuv_disabled">應用程式處理下無法使用,切換至系統處理後可使用超級防震。</string>
</resources>
+7
View File
@@ -1515,4 +1515,11 @@
<string name="aesthetic_show_in_gallery">Show scores in gallery</string>
<string name="aesthetic_show_in_gallery_description">Scores photos in the background as you browse.</string>
<string name="aesthetic_note">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.</string>
<string name="settings_video_input_mode">Video processing</string>
<string name="settings_video_input_mode_description">Choose who converts video colors: the system or the app. Both modes support filters; EIS+ requires App processing.</string>
<string name="settings_video_input_eis_required">EIS+ is enabled, so App processing is required. Turn off EIS+ to choose another mode.</string>
<string name="settings_video_input_oes">System processing</string>
<string name="settings_video_input_yuv">App processing</string>
<string name="settings_video_nr_yuv_description">App processing does not support High quality noise reduction. Fast is used instead when High quality is selected.</string>
<string name="settings_oppo_super_stabilization_yuv_disabled">Unavailable with App processing. Switch to System processing to use Ultra Steady.</string>
</resources>