feat: EIS+
This commit is contained in:
1 parent
a9c0449c01
commit
ef7bb72add
25 files changed
+3031
-43
No files matched your search
@@ -40,6 +40,7 @@ import com.hinnka.mycamera.lut.LutConfig
|
||||
import com.hinnka.mycamera.lut.VideoColorEffectLayer
|
||||
import com.hinnka.mycamera.model.SafeImage
|
||||
import com.hinnka.mycamera.model.ColorRecipeParams
|
||||
import com.hinnka.mycamera.stabilization.RealtimeStabilizationCoordinator
|
||||
import com.hinnka.mycamera.utils.DeviceUtil
|
||||
import com.hinnka.mycamera.utils.OrientationObserver
|
||||
import com.hinnka.mycamera.video.CaptureMode
|
||||
@@ -342,7 +343,8 @@ class Camera2Controller(private val context: Context) {
|
||||
|
||||
// Live Photo 录制器
|
||||
val livePhotoRecorder = LivePhotoRecorder(context)
|
||||
val videoRecorder = VideoRecorder(context)
|
||||
val realtimeStabilizationCoordinator = RealtimeStabilizationCoordinator(context)
|
||||
val videoRecorder = VideoRecorder(context, realtimeStabilizationCoordinator)
|
||||
var onVideoSaved: ((Uri?) -> Unit)? = null
|
||||
|
||||
private var videoRecordingStartElapsedMs: Long = 0L
|
||||
@@ -690,6 +692,8 @@ class Camera2Controller(private val context: Context) {
|
||||
) {
|
||||
super.onCaptureCompleted(session, request, result)
|
||||
|
||||
realtimeStabilizationCoordinator.submitCaptureResult(result)
|
||||
|
||||
val timestamp = result.get(CaptureResult.SENSOR_TIMESTAMP)
|
||||
if (timestamp != null && isRawCaptureReader(imageReader)) {
|
||||
val pendingImage = pendingImages.remove(timestamp)
|
||||
@@ -1911,6 +1915,8 @@ class Camera2Controller(private val context: Context) {
|
||||
availableTonemapModes = availableTonemapModes,
|
||||
availableVideoStabilizationModes = availableVideoStabilizationModes,
|
||||
availableOpticalStabilizationModes = availableOpticalStabilizationModes,
|
||||
algorithmicStabilizationSupported =
|
||||
realtimeStabilizationCoordinator.isCameraSupported(resolvedCharacteristics),
|
||||
isFlashSupported = isFlashSupported
|
||||
)
|
||||
|
||||
@@ -2082,6 +2088,10 @@ class Camera2Controller(private val context: Context) {
|
||||
openCharacteristics
|
||||
}
|
||||
}
|
||||
realtimeStabilizationCoordinator.configureCamera(
|
||||
characteristics = capabilityCharacteristics,
|
||||
timingCharacteristics = openCharacteristics,
|
||||
)
|
||||
isManualSensorSupported =
|
||||
capabilities.contains(CameraCharacteristics.REQUEST_AVAILABLE_CAPABILITIES_MANUAL_SENSOR)
|
||||
isManualPostProcessingSupported =
|
||||
@@ -4378,7 +4388,15 @@ class Camera2Controller(private val context: Context) {
|
||||
try {
|
||||
if (state.captureMode == CaptureMode.VIDEO) {
|
||||
val mode = state.videoConfig.stabilizationMode
|
||||
resolveVideoStabilizationRequestMode(mode)?.let { videoStabilizationMode ->
|
||||
val enhancedSelected = mode == VideoStabilizationMode.ENHANCED
|
||||
val requestedVideoMode = if (enhancedSelected) {
|
||||
CaptureRequest.CONTROL_VIDEO_STABILIZATION_MODE_OFF.takeIf {
|
||||
availableVideoStabilizationModes.contains(it)
|
||||
}
|
||||
} else {
|
||||
resolveVideoStabilizationRequestMode(mode)
|
||||
}
|
||||
requestedVideoMode?.let { videoStabilizationMode ->
|
||||
builder.set(
|
||||
CaptureRequest.CONTROL_VIDEO_STABILIZATION_MODE,
|
||||
videoStabilizationMode
|
||||
@@ -4420,6 +4438,7 @@ class Camera2Controller(private val context: Context) {
|
||||
else -> null
|
||||
}
|
||||
|
||||
VideoStabilizationMode.ENHANCED,
|
||||
VideoStabilizationMode.OIS,
|
||||
VideoStabilizationMode.OFF -> {
|
||||
CaptureRequest.CONTROL_VIDEO_STABILIZATION_MODE_OFF
|
||||
@@ -6153,12 +6172,40 @@ class Camera2Controller(private val context: Context) {
|
||||
}
|
||||
|
||||
fun setVideoResolution(resolution: VideoResolutionPreset) {
|
||||
_state.value = _state.value.copy(videoConfig = _state.value.videoConfig.copy(resolution = resolution))
|
||||
val currentConfig = _state.value.videoConfig
|
||||
val stabilizationMode = if (
|
||||
currentConfig.stabilizationMode == VideoStabilizationMode.ENHANCED &&
|
||||
resolution != VideoResolutionPreset.FHD_1080P
|
||||
) {
|
||||
preferredHardwareVideoStabilizationMode()
|
||||
} else {
|
||||
currentConfig.stabilizationMode
|
||||
}
|
||||
_state.value = _state.value.copy(
|
||||
videoConfig = currentConfig.copy(
|
||||
resolution = resolution,
|
||||
stabilizationMode = stabilizationMode
|
||||
)
|
||||
)
|
||||
refreshVideoCapabilities()
|
||||
}
|
||||
|
||||
fun setVideoFps(fps: VideoFpsPreset) {
|
||||
_state.value = _state.value.copy(videoConfig = _state.value.videoConfig.copy(fps = fps))
|
||||
val currentConfig = _state.value.videoConfig
|
||||
val stabilizationMode = if (
|
||||
currentConfig.stabilizationMode == VideoStabilizationMode.ENHANCED &&
|
||||
fps != VideoFpsPreset.FPS_30
|
||||
) {
|
||||
preferredHardwareVideoStabilizationMode()
|
||||
} else {
|
||||
currentConfig.stabilizationMode
|
||||
}
|
||||
_state.value = _state.value.copy(
|
||||
videoConfig = currentConfig.copy(
|
||||
fps = fps,
|
||||
stabilizationMode = stabilizationMode
|
||||
)
|
||||
)
|
||||
refreshVideoCapabilities()
|
||||
previewRequestBuilder?.apply {
|
||||
applyBaseCameraSettings(this, isCapture = false)
|
||||
@@ -6186,17 +6233,30 @@ class Camera2Controller(private val context: Context) {
|
||||
}
|
||||
|
||||
fun setVideoStabilizationMode(mode: VideoStabilizationMode) {
|
||||
val previousMode = _state.value.videoConfig.stabilizationMode
|
||||
val previousConfig = _state.value.videoConfig
|
||||
_state.value = _state.value.copy(
|
||||
videoConfig = _state.value.videoConfig.copy(
|
||||
stabilizationMode = mode
|
||||
videoConfig = previousConfig.copy(
|
||||
resolution = if (mode == VideoStabilizationMode.ENHANCED) {
|
||||
VideoResolutionPreset.FHD_1080P
|
||||
} else {
|
||||
previousConfig.resolution
|
||||
},
|
||||
fps = if (mode == VideoStabilizationMode.ENHANCED) {
|
||||
VideoFpsPreset.FPS_30
|
||||
} else {
|
||||
previousConfig.fps
|
||||
},
|
||||
stabilizationMode = mode,
|
||||
)
|
||||
)
|
||||
refreshVideoCapabilities()
|
||||
val resolvedMode = _state.value.videoConfig.stabilizationMode
|
||||
val resolvedConfig = _state.value.videoConfig
|
||||
val outputGeometryChanged = previousConfig.resolution != resolvedConfig.resolution ||
|
||||
previousConfig.fps != resolvedConfig.fps
|
||||
if (_state.value.captureMode == CaptureMode.VIDEO &&
|
||||
!_state.value.videoRecordingState.isRecording &&
|
||||
previousMode != resolvedMode
|
||||
previousConfig.stabilizationMode != resolvedConfig.stabilizationMode &&
|
||||
!outputGeometryChanged
|
||||
) {
|
||||
createPreviewSession()
|
||||
return
|
||||
@@ -6225,6 +6285,10 @@ class Camera2Controller(private val context: Context) {
|
||||
videoRecorder.setPreferredAudioInputId(normalizedAudioInputId)
|
||||
}
|
||||
|
||||
fun setPhotoPreviewStabilizationEnabled(enabled: Boolean) {
|
||||
_state.value = _state.value.copy(photoPreviewStabilizationEnabled = enabled)
|
||||
}
|
||||
|
||||
fun setVideoRecordingPath(recordingPath: VideoRecordingPath, recordingTreeUri: String? = null) {
|
||||
_state.value = _state.value.copy(
|
||||
videoConfig = _state.value.videoConfig.copy(
|
||||
@@ -6292,6 +6356,7 @@ class Camera2Controller(private val context: Context) {
|
||||
_state.value.videoConfig.resolution
|
||||
] ?: _state.value.currentPreviewSize
|
||||
val isFrontCamera = isCurrentCameraFrontFacing()
|
||||
val useEnhancedStabilization = shouldUseVideoEnhancedStabilization()
|
||||
val shouldFlipEncodedFrame = isFrontCamera && mirrorFrontCameraEnabled
|
||||
val colorLayers = buildList {
|
||||
if (!_state.value.videoConfig.logProfile.isEnabled &&
|
||||
@@ -6320,6 +6385,7 @@ class Camera2Controller(private val context: Context) {
|
||||
?: CameraCharacteristics.SENSOR_INFO_TIMESTAMP_SOURCE_UNKNOWN,
|
||||
orientationHintDegrees = resolveDedicatedVideoOrientationHintDegrees(orientationOffsetDegrees),
|
||||
flipEncodedFrame = shouldFlipEncodedFrame,
|
||||
enhancedStabilization = useEnhancedStabilization,
|
||||
recordingPath = _state.value.videoConfig.recordingPath,
|
||||
recordingTreeUri = _state.value.videoConfig.recordingTreeUri,
|
||||
onError = { message ->
|
||||
@@ -6340,7 +6406,6 @@ class Camera2Controller(private val context: Context) {
|
||||
if (!started) {
|
||||
return
|
||||
}
|
||||
|
||||
_state.value = _state.value.copy(
|
||||
videoRecordingState = VideoRecordingState(isRecording = true, elapsedMs = 0L)
|
||||
)
|
||||
@@ -6353,6 +6418,25 @@ class Camera2Controller(private val context: Context) {
|
||||
_state.value.getCurrentCameraInfo()?.lensType == LensType.FRONT
|
||||
}
|
||||
|
||||
private fun shouldUseVideoEnhancedStabilization(): Boolean {
|
||||
val state = _state.value
|
||||
return state.videoConfig.stabilizationMode == VideoStabilizationMode.ENHANCED &&
|
||||
state.captureMode == CaptureMode.VIDEO &&
|
||||
state.videoConfig.resolution == VideoResolutionPreset.FHD_1080P &&
|
||||
state.videoConfig.fps == VideoFpsPreset.FPS_30 &&
|
||||
!isCurrentCameraFrontFacing() &&
|
||||
realtimeStabilizationCoordinator.isCurrentCameraSupported
|
||||
}
|
||||
|
||||
private fun preferredHardwareVideoStabilizationMode(): VideoStabilizationMode {
|
||||
val availableModes = _state.value.videoCapabilities.availableStabilizationModes
|
||||
return when {
|
||||
VideoStabilizationMode.OIS in availableModes -> VideoStabilizationMode.OIS
|
||||
VideoStabilizationMode.EIS in availableModes -> VideoStabilizationMode.EIS
|
||||
else -> VideoStabilizationMode.OFF
|
||||
}
|
||||
}
|
||||
|
||||
fun pauseVideoRecording() {
|
||||
if (!_state.value.videoRecordingState.isRecording || _state.value.videoRecordingState.isPaused) return
|
||||
videoRecorder.pauseRecording()
|
||||
|
||||
@@ -377,6 +377,7 @@ data class CameraState(
|
||||
val isP3Supported: Boolean = false,
|
||||
val currentDynamicRangeProfile: String = "STANDARD",
|
||||
val captureMode: CaptureMode = CaptureMode.PHOTO,
|
||||
val photoPreviewStabilizationEnabled: Boolean = false,
|
||||
val videoConfig: VideoConfig = VideoConfig(),
|
||||
val videoCapabilities: VideoCapabilities = VideoCapabilities(),
|
||||
val videoRecordingState: VideoRecordingState = VideoRecordingState(),
|
||||
|
||||
@@ -48,6 +48,7 @@ import com.hinnka.mycamera.video.VideoFpsPreset
|
||||
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.model.EffectParams
|
||||
import com.hinnka.mycamera.model.CameraPreset
|
||||
import com.hinnka.mycamera.model.LutSelectorMode
|
||||
@@ -233,7 +234,8 @@ data class UserPreferences(
|
||||
val videoAudioInputId: String = VIDEO_AUDIO_INPUT_AUTO,
|
||||
val videoRecordingPath: VideoRecordingPath = VideoRecordingPath.DCIM_PHOTON,
|
||||
val videoRecordingTreeUri: String? = null,
|
||||
val videoStabilizationMode: com.hinnka.mycamera.video.VideoStabilizationMode = com.hinnka.mycamera.video.VideoStabilizationMode.OIS,
|
||||
val videoStabilizationMode: VideoStabilizationMode = VideoStabilizationMode.OIS,
|
||||
val photoPreviewStabilizationEnabled: Boolean = false,
|
||||
val videoTorchEnabled: Boolean = false,
|
||||
val videoLensLockEnabled: Boolean = false,
|
||||
val videoWhiteBalanceLockEnabled: Boolean = false,
|
||||
@@ -492,6 +494,10 @@ class UserPreferencesRepository(private val context: Context) {
|
||||
private val VIDEO_RECORDING_PATH = stringPreferencesKey("video_recording_path")
|
||||
private val VIDEO_RECORDING_TREE_URI = stringPreferencesKey("video_recording_tree_uri")
|
||||
private val VIDEO_STABILIZATION_MODE = stringPreferencesKey("video_stabilization_mode")
|
||||
private val VIDEO_ENHANCED_STABILIZATION_ENABLED =
|
||||
booleanPreferencesKey("video_enhanced_stabilization_enabled")
|
||||
private val PHOTO_PREVIEW_STABILIZATION_ENABLED =
|
||||
booleanPreferencesKey("photo_preview_stabilization_enabled")
|
||||
private val VIDEO_TORCH_ENABLED = booleanPreferencesKey("video_torch_enabled")
|
||||
private val VIDEO_LENS_LOCK_ENABLED = booleanPreferencesKey("video_lens_lock_enabled")
|
||||
private val VIDEO_WHITE_BALANCE_LOCK_ENABLED = booleanPreferencesKey("video_white_balance_lock_enabled")
|
||||
@@ -568,6 +574,22 @@ class UserPreferencesRepository(private val context: Context) {
|
||||
(preferences[USE_JPEG_444_EXPORT] ?: false) && !useHeicExport
|
||||
val hdrPlusBracketExposureEnabled = preferences[HDR_PLUS_BRACKET_EXPOSURE_ENABLED]
|
||||
?: MultiFrameConfig.DEFAULT_HDR_PLUS_BRACKET_EXPOSURE
|
||||
val storedVideoStabilizationMode = VideoStabilizationMode.entries.firstOrNull {
|
||||
it.name == preferences[VIDEO_STABILIZATION_MODE]
|
||||
} ?: VideoStabilizationMode.OIS
|
||||
val videoStabilizationMode = if (
|
||||
preferences[VIDEO_ENHANCED_STABILIZATION_ENABLED] == true
|
||||
) {
|
||||
VideoStabilizationMode.ENHANCED
|
||||
} else {
|
||||
storedVideoStabilizationMode
|
||||
}
|
||||
val storedVideoResolution = VideoResolutionPreset.entries.firstOrNull {
|
||||
it.name == preferences[VIDEO_RESOLUTION]
|
||||
} ?: VideoResolutionPreset.FHD_1080P
|
||||
val storedVideoFps = VideoFpsPreset.entries.firstOrNull {
|
||||
it.name == preferences[VIDEO_FPS]
|
||||
} ?: VideoFpsPreset.FPS_30
|
||||
UserPreferences(
|
||||
captureMode = CaptureMode.entries.firstOrNull {
|
||||
it.name == preferences[CAPTURE_MODE]
|
||||
@@ -764,12 +786,16 @@ class UserPreferencesRepository(private val context: Context) {
|
||||
useHlg10 = preferences[USE_HLG10] ?: false,
|
||||
hlgHardwareCompatibilityEnabled = preferences[HLG_HARDWARE_COMPATIBILITY_ENABLED] ?: false,
|
||||
useP3ColorSpace = preferences[USE_P3_COLOR_SPACE] ?: false,
|
||||
videoResolution = VideoResolutionPreset.valueOf(
|
||||
preferences[VIDEO_RESOLUTION] ?: VideoResolutionPreset.FHD_1080P.name
|
||||
),
|
||||
videoFps = VideoFpsPreset.valueOf(
|
||||
preferences[VIDEO_FPS] ?: VideoFpsPreset.FPS_30.name
|
||||
),
|
||||
videoResolution = if (videoStabilizationMode == VideoStabilizationMode.ENHANCED) {
|
||||
VideoResolutionPreset.FHD_1080P
|
||||
} else {
|
||||
storedVideoResolution
|
||||
},
|
||||
videoFps = if (videoStabilizationMode == VideoStabilizationMode.ENHANCED) {
|
||||
VideoFpsPreset.FPS_30
|
||||
} else {
|
||||
storedVideoFps
|
||||
},
|
||||
videoAspectRatio = VideoAspectRatio.valueOf(
|
||||
preferences[VIDEO_ASPECT_RATIO] ?: VideoAspectRatio.RATIO_16_9.name
|
||||
),
|
||||
@@ -782,9 +808,9 @@ class UserPreferencesRepository(private val context: Context) {
|
||||
videoAudioInputId = preferences[VIDEO_AUDIO_INPUT_ID] ?: VIDEO_AUDIO_INPUT_AUTO,
|
||||
videoRecordingPath = VideoRecordingPath.fromPersistedName(preferences[VIDEO_RECORDING_PATH]),
|
||||
videoRecordingTreeUri = preferences[VIDEO_RECORDING_TREE_URI]?.takeIf { it.isNotBlank() },
|
||||
videoStabilizationMode = com.hinnka.mycamera.video.VideoStabilizationMode.valueOf(
|
||||
preferences[VIDEO_STABILIZATION_MODE] ?: com.hinnka.mycamera.video.VideoStabilizationMode.OIS.name
|
||||
),
|
||||
videoStabilizationMode = videoStabilizationMode,
|
||||
photoPreviewStabilizationEnabled =
|
||||
preferences[PHOTO_PREVIEW_STABILIZATION_ENABLED] ?: false,
|
||||
videoTorchEnabled = preferences[VIDEO_TORCH_ENABLED] ?: false,
|
||||
videoLensLockEnabled = preferences[VIDEO_LENS_LOCK_ENABLED] ?: false,
|
||||
videoWhiteBalanceLockEnabled = preferences[VIDEO_WHITE_BALANCE_LOCK_ENABLED] ?: false,
|
||||
@@ -1573,12 +1599,22 @@ class UserPreferencesRepository(private val context: Context) {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 保存视频防抖模式
|
||||
*/
|
||||
suspend fun saveVideoStabilizationMode(mode: com.hinnka.mycamera.video.VideoStabilizationMode) {
|
||||
suspend fun saveVideoStabilizationConfig(
|
||||
mode: VideoStabilizationMode,
|
||||
resolution: VideoResolutionPreset,
|
||||
fps: VideoFpsPreset,
|
||||
) {
|
||||
context.dataStore.edit { preferences ->
|
||||
preferences[VIDEO_STABILIZATION_MODE] = mode.name
|
||||
preferences[VIDEO_RESOLUTION] = resolution.name
|
||||
preferences[VIDEO_FPS] = fps.name
|
||||
preferences.remove(VIDEO_ENHANCED_STABILIZATION_ENABLED)
|
||||
}
|
||||
}
|
||||
|
||||
suspend fun savePhotoPreviewStabilizationEnabled(enabled: Boolean) {
|
||||
context.dataStore.edit { preferences ->
|
||||
preferences[PHOTO_PREVIEW_STABILIZATION_ENABLED] = enabled
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -56,6 +56,8 @@ internal data class ColorPassLocations(
|
||||
val uPrimaryCalibrationMatrixLocation: Int,
|
||||
val uSTMatrixFragLocation: Int,
|
||||
val uCropRectLocation: Int,
|
||||
val uStabilizationEnabledLocation: Int,
|
||||
val uStabilizationRowsLocation: Int,
|
||||
val uTexelSizeLocation: Int,
|
||||
val uCurveTextureLocation: Int,
|
||||
val uCurveEnabledLocation: Int,
|
||||
@@ -161,6 +163,14 @@ internal class PreviewColorProgramCache {
|
||||
uPrimaryCalibrationMatrixLocation = GLES30.glGetUniformLocation(program, "uPrimaryCalibrationMatrix"),
|
||||
uSTMatrixFragLocation = GLES30.glGetUniformLocation(program, "uSTMatrix"),
|
||||
uCropRectLocation = GLES30.glGetUniformLocation(program, "uCropRect"),
|
||||
uStabilizationEnabledLocation = GLES30.glGetUniformLocation(
|
||||
program,
|
||||
"uStabilizationEnabled",
|
||||
),
|
||||
uStabilizationRowsLocation = GLES30.glGetUniformLocation(
|
||||
program,
|
||||
"uStabilizationRows[0]",
|
||||
),
|
||||
uTexelSizeLocation = GLES30.glGetUniformLocation(program, "uTexelSize"),
|
||||
uCurveTextureLocation = GLES30.glGetUniformLocation(program, "uCurveTexture"),
|
||||
uCurveEnabledLocation = GLES30.glGetUniformLocation(program, "uCurveEnabled"),
|
||||
|
||||
@@ -14,6 +14,10 @@ import com.hinnka.mycamera.preview.EyeFocusProcessingTiming
|
||||
import com.hinnka.mycamera.raw.ColorSpace
|
||||
import com.hinnka.mycamera.screencapture.PhantomPipCrop
|
||||
import com.hinnka.mycamera.camera.MeteringMode
|
||||
import com.hinnka.mycamera.stabilization.AlgorithmicStabilizationTransform
|
||||
import com.hinnka.mycamera.stabilization.RealtimeStabilizationCoordinator
|
||||
import com.hinnka.mycamera.stabilization.STABILIZATION_ROW_COUNT
|
||||
import com.hinnka.mycamera.stabilization.StabilizationUseCase
|
||||
import com.hinnka.mycamera.utils.PLog
|
||||
import com.hinnka.mycamera.video.VideoLogProfile
|
||||
import java.nio.ByteBuffer
|
||||
@@ -231,6 +235,13 @@ class LutRenderer(context: Context) : GLSurfaceView.Renderer {
|
||||
// 相机 SurfaceTexture
|
||||
private var surfaceTexture: SurfaceTexture? = null
|
||||
private val frameAvailable = AtomicBoolean(false)
|
||||
private var stabilizationCoordinator: RealtimeStabilizationCoordinator? = null
|
||||
@Volatile
|
||||
private var stabilizationSession: RealtimeStabilizationCoordinator.Session? = null
|
||||
@Volatile
|
||||
private var stabilizationSessionStarted = false
|
||||
private var photoPreviewStabilizationEnabled = false
|
||||
private var currentStabilizationTransform: AlgorithmicStabilizationTransform? = null
|
||||
|
||||
// 标记 Surface 是否已创建(GL 上下文是否可用)
|
||||
private var surfaceReady = false
|
||||
@@ -818,6 +829,7 @@ class LutRenderer(context: Context) : GLSurfaceView.Renderer {
|
||||
curveEnabled: Boolean,
|
||||
enableVideoLog: Boolean,
|
||||
treatSourceAsHlgInput: Boolean,
|
||||
stabilizationTransform: AlgorithmicStabilizationTransform? = null,
|
||||
) {
|
||||
GLES30.glBindFramebuffer(GLES30.GL_FRAMEBUFFER, targetFboId)
|
||||
GLES30.glViewport(0, 0, width, height)
|
||||
@@ -845,6 +857,21 @@ class LutRenderer(context: Context) : GLSurfaceView.Renderer {
|
||||
sourceCropRect[2],
|
||||
sourceCropRect[3]
|
||||
)
|
||||
val stabilizationEnabled = stabilizationTransform != null &&
|
||||
stabilizationTransform.rowHomographies.size == STABILIZATION_ROW_COUNT * 9
|
||||
GLES30.glUniform1i(
|
||||
locations.uStabilizationEnabledLocation,
|
||||
if (stabilizationEnabled) 1 else 0,
|
||||
)
|
||||
if (stabilizationEnabled) {
|
||||
GLES30.glUniformMatrix3fv(
|
||||
locations.uStabilizationRowsLocation,
|
||||
STABILIZATION_ROW_COUNT,
|
||||
false,
|
||||
stabilizationTransform.rowHomographies,
|
||||
0,
|
||||
)
|
||||
}
|
||||
GLES30.glUniform1f(locations.uLutSizeLocation, lutSize)
|
||||
GLES30.glUniform1f(locations.uLutIntensityLocation, params.lutIntensity)
|
||||
GLES30.glUniform1i(locations.uLutEnabledLocation, if (lutEnabled && lutTextureId != 0) 1 else 0)
|
||||
@@ -1001,6 +1028,33 @@ class LutRenderer(context: Context) : GLSurfaceView.Renderer {
|
||||
}
|
||||
}
|
||||
|
||||
if (cameraFrameUpdated && photoPreviewStabilizationEnabled) {
|
||||
val session = stabilizationSession
|
||||
if (stabilizationSessionStarted &&
|
||||
stabilizationCoordinator?.isCurrentCameraSupported == false
|
||||
) {
|
||||
session?.stop()
|
||||
stabilizationSessionStarted = false
|
||||
}
|
||||
if (!stabilizationSessionStarted) {
|
||||
stabilizationSessionStarted = session?.start() == true
|
||||
}
|
||||
currentStabilizationTransform = if (stabilizationSessionStarted) {
|
||||
surfaceTexture?.timestamp?.let { timestampNs ->
|
||||
session?.transformForFrame(
|
||||
timestampNs = timestampNs,
|
||||
baseCropRect = cropRect,
|
||||
textureAxesSwapped = isTextureTransformAxesSwapped(stMatrix),
|
||||
displayRotationDegrees = deviceRotation,
|
||||
)
|
||||
}
|
||||
} else {
|
||||
null
|
||||
}
|
||||
} else if (!photoPreviewStabilizationEnabled) {
|
||||
currentStabilizationTransform = null
|
||||
}
|
||||
|
||||
val liveRecorder = livePhotoRecorder
|
||||
val hdfEnabled = halation > 0.001f
|
||||
val halationEnabled = redHalation > 0.001f
|
||||
@@ -1341,7 +1395,7 @@ class LutRenderer(context: Context) : GLSurfaceView.Renderer {
|
||||
sourceTextureTarget = GLES11Ext.GL_TEXTURE_EXTERNAL_OES,
|
||||
sourceTextureId = cameraTextureId,
|
||||
sourceStMatrix = stMatrix,
|
||||
sourceCropRect = cropRect,
|
||||
sourceCropRect = currentStabilizationTransform?.cropRect ?: cropRect,
|
||||
targetMvpMatrix = targetMvpMatrix,
|
||||
lutConfig = layerLutConfig,
|
||||
lutTextureId = layerLutTextureId,
|
||||
@@ -1351,7 +1405,8 @@ class LutRenderer(context: Context) : GLSurfaceView.Renderer {
|
||||
curveTextureId = layerCurveTextureId,
|
||||
curveEnabled = layerCurveEnabled,
|
||||
enableVideoLog = enableVideoLog,
|
||||
treatSourceAsHlgInput = isHlgInput
|
||||
treatSourceAsHlgInput = isHlgInput,
|
||||
stabilizationTransform = currentStabilizationTransform,
|
||||
)
|
||||
|
||||
// 测光和直方图(按需)
|
||||
@@ -2519,6 +2574,26 @@ class LutRenderer(context: Context) : GLSurfaceView.Renderer {
|
||||
updateCaptureSize()
|
||||
}
|
||||
|
||||
fun setStabilizationCoordinator(coordinator: RealtimeStabilizationCoordinator?) {
|
||||
if (stabilizationCoordinator === coordinator) return
|
||||
stabilizationSession?.stop()
|
||||
stabilizationCoordinator = coordinator
|
||||
stabilizationSession = coordinator?.createSession(StabilizationUseCase.PHOTO_PREVIEW)
|
||||
stabilizationSessionStarted = false
|
||||
currentStabilizationTransform = null
|
||||
}
|
||||
|
||||
fun setPhotoPreviewStabilizationEnabled(enabled: Boolean) {
|
||||
if (photoPreviewStabilizationEnabled == enabled) return
|
||||
photoPreviewStabilizationEnabled = enabled
|
||||
PLog.i(TAG, "Photo preview stabilization enabled=$enabled")
|
||||
if (!enabled) {
|
||||
stabilizationSession?.stop()
|
||||
stabilizationSessionStarted = false
|
||||
currentStabilizationTransform = null
|
||||
}
|
||||
}
|
||||
|
||||
fun setCaptureSize(width: Int, height: Int) {
|
||||
photoCaptureWidth = width.coerceAtLeast(0)
|
||||
photoCaptureHeight = height.coerceAtLeast(0)
|
||||
@@ -3059,6 +3134,11 @@ class LutRenderer(context: Context) : GLSurfaceView.Renderer {
|
||||
|
||||
fun setRenderingPaused(paused: Boolean) {
|
||||
renderingPaused = paused
|
||||
if (paused) {
|
||||
stabilizationSession?.stop()
|
||||
stabilizationSessionStarted = false
|
||||
currentStabilizationTransform = null
|
||||
}
|
||||
}
|
||||
|
||||
private fun calculateMeteringResults(meteringBytes: ByteArray, focus: PointF?, mode: MeteringMode) {
|
||||
@@ -3203,6 +3283,11 @@ class LutRenderer(context: Context) : GLSurfaceView.Renderer {
|
||||
* 释放资源
|
||||
*/
|
||||
fun release() {
|
||||
stabilizationSession?.stop()
|
||||
stabilizationSession = null
|
||||
stabilizationCoordinator = null
|
||||
stabilizationSessionStarted = false
|
||||
currentStabilizationTransform = null
|
||||
try {
|
||||
meteringExecutor.shutdown()
|
||||
} catch (e: Exception) {
|
||||
|
||||
@@ -14,6 +14,8 @@ internal object PreviewColorShader {
|
||||
}
|
||||
val needsOklab = variant.includeOklchDensity || variant.includeLchMixer
|
||||
val needsClassifiers = variant.includeLchMixer || variant.includeLutMask
|
||||
val supportsStabilization =
|
||||
variant.textureSource == PreviewColorTextureSource.EXTERNAL_OES
|
||||
|
||||
return """
|
||||
#version 300 es
|
||||
@@ -22,6 +24,7 @@ internal object PreviewColorShader {
|
||||
|
||||
in vec2 vTexCoord;
|
||||
in vec2 vRawCoord;
|
||||
in vec2 vOutputCoord;
|
||||
out vec4 fragColor;
|
||||
|
||||
uniform $sampler uCameraTexture;
|
||||
@@ -40,6 +43,10 @@ internal object PreviewColorShader {
|
||||
|
||||
uniform bool uColorRecipeEnabled;
|
||||
uniform mat4 uSTMatrix;
|
||||
${if (supportsStabilization) """
|
||||
uniform bool uStabilizationEnabled;
|
||||
uniform mat3 uStabilizationRows[16];
|
||||
""" else ""}
|
||||
uniform float uExposure;
|
||||
uniform float uContrast;
|
||||
uniform float uSaturation;
|
||||
@@ -178,16 +185,38 @@ internal object PreviewColorShader {
|
||||
${PreviewColorShaderModules.PRIMARY_CALIBRATION}
|
||||
${PreviewColorShaderModules.LUT_COLOR_SPACE}
|
||||
|
||||
${if (supportsStabilization) """
|
||||
vec2 applyStabilization(vec2 coordinate, float outputRow) {
|
||||
if (!uStabilizationEnabled) {
|
||||
return coordinate;
|
||||
}
|
||||
float rowPosition = clamp(outputRow, 0.0, 1.0) * 15.0;
|
||||
int lowerIndex = clamp(int(floor(rowPosition)), 0, 14);
|
||||
int upperIndex = lowerIndex + 1;
|
||||
float amount = rowPosition - float(lowerIndex);
|
||||
vec3 point = vec3(coordinate, 1.0);
|
||||
vec3 lowerPoint = uStabilizationRows[lowerIndex] * point;
|
||||
vec3 upperPoint = uStabilizationRows[upperIndex] * point;
|
||||
vec2 lowerCoordinate = lowerPoint.xy / max(abs(lowerPoint.z), 0.000001);
|
||||
vec2 upperCoordinate = upperPoint.xy / max(abs(upperPoint.z), 0.000001);
|
||||
return mix(lowerCoordinate, upperCoordinate, amount);
|
||||
}
|
||||
""" else """
|
||||
vec2 applyStabilization(vec2 coordinate, float outputRow) {
|
||||
return coordinate;
|
||||
}
|
||||
"""}
|
||||
|
||||
void main() {
|
||||
vec2 uvCoord = vTexCoord;
|
||||
vec2 rcCoord = vRawCoord;
|
||||
vec2 rcCoord = applyStabilization(vRawCoord, vOutputCoord.y);
|
||||
vec2 uvCoord = (uSTMatrix * vec4(rcCoord, 0.0, 1.0)).xy;
|
||||
if (uLowRes > 0.005) {
|
||||
float blocksX = mix(512.0, 32.0, uLowRes);
|
||||
vec2 gridSize = vec2(1.0 / blocksX, 1.0 / (blocksX / uAspectRatio));
|
||||
vec2 gridUV = floor(vTexCoord / gridSize) * gridSize + gridSize * 0.5;
|
||||
vec2 gridRC = floor(vRawCoord / gridSize) * gridSize + gridSize * 0.5;
|
||||
uvCoord = mix(vTexCoord, gridUV, 0.95);
|
||||
rcCoord = mix(vRawCoord, gridRC, 0.95);
|
||||
vec2 gridRC = floor(rcCoord / gridSize) * gridSize + gridSize * 0.5;
|
||||
vec2 gridUV = (uSTMatrix * vec4(gridRC, 0.0, 1.0)).xy;
|
||||
uvCoord = mix(uvCoord, gridUV, 0.95);
|
||||
rcCoord = mix(rcCoord, gridRC, 0.95);
|
||||
}
|
||||
|
||||
vec4 color;
|
||||
|
||||
@@ -15,6 +15,10 @@ import android.util.Size
|
||||
import android.view.Surface
|
||||
import com.hinnka.mycamera.model.ColorPaletteMapper
|
||||
import com.hinnka.mycamera.model.ColorRecipeParams
|
||||
import com.hinnka.mycamera.stabilization.AlgorithmicStabilizationTransform
|
||||
import com.hinnka.mycamera.stabilization.RealtimeStabilizationCoordinator
|
||||
import com.hinnka.mycamera.stabilization.STABILIZATION_ROW_COUNT
|
||||
import com.hinnka.mycamera.stabilization.StabilizationUseCase
|
||||
import com.hinnka.mycamera.utils.PLog
|
||||
import com.hinnka.mycamera.video.VideoEncoderColorConfig
|
||||
import com.hinnka.mycamera.video.VideoEncodedColorPipeline
|
||||
@@ -43,6 +47,8 @@ class RealtimeVideoRenderer(
|
||||
private val mirrorHorizontally: Boolean,
|
||||
private val mirrorVertically: Boolean,
|
||||
private val encoderColorConfig: VideoEncoderColorConfig,
|
||||
private val stabilizationCoordinator: RealtimeStabilizationCoordinator?,
|
||||
private val enhancedStabilizationEnabled: Boolean,
|
||||
) {
|
||||
companion object {
|
||||
private const val TAG = "RealtimeVideoRenderer"
|
||||
@@ -115,6 +121,10 @@ class RealtimeVideoRenderer(
|
||||
private var textureCoordinateBuffer: FloatBuffer? = null
|
||||
private var indexBuffer: ShortBuffer? = null
|
||||
private var initialized = false
|
||||
@Volatile
|
||||
private var stabilizationSession: RealtimeStabilizationCoordinator.Session? = null
|
||||
@Volatile
|
||||
private var stabilizationSessionStarted = false
|
||||
|
||||
val inputSurface: Surface?
|
||||
get() = cameraSurface
|
||||
@@ -147,12 +157,20 @@ class RealtimeVideoRenderer(
|
||||
setOnFrameAvailableListener { onFrameAvailable() }
|
||||
}
|
||||
cameraSurface = Surface(cameraSurfaceTexture)
|
||||
if (enhancedStabilizationEnabled) {
|
||||
stabilizationSession = stabilizationCoordinator?.createSession(StabilizationUseCase.VIDEO)
|
||||
stabilizationSessionStarted = stabilizationSession?.start() == true
|
||||
if (!stabilizationSessionStarted) {
|
||||
PLog.w(TAG, "Enhanced stabilization requested but the gyro/camera session is unavailable")
|
||||
}
|
||||
}
|
||||
initialized = true
|
||||
PLog.i(
|
||||
TAG,
|
||||
"Initialized: camera=${cameraInputSize.width}x${cameraInputSize.height}, " +
|
||||
"encoder=${encoderOutputSize.width}x${encoderOutputSize.height}, " +
|
||||
"layers=${layers.size}, log=${videoLogProfile.name}, hlgInput=$hlgInput, " +
|
||||
"enhancedStabilization=$enhancedStabilizationEnabled, " +
|
||||
"mirrorH=$mirrorHorizontally, mirrorV=$mirrorVertically, " +
|
||||
"color=${encoderColorConfig.debugName}"
|
||||
)
|
||||
@@ -183,6 +201,15 @@ class RealtimeVideoRenderer(
|
||||
if (timestampNs <= 0L) return null
|
||||
val presentationTimeNs = mapPresentationTimeNs(timestampNs)
|
||||
if (presentationTimeNs <= 0L) return null
|
||||
val stabilizationTransform = if (stabilizationSessionStarted) {
|
||||
stabilizationSession?.transformForFrame(
|
||||
timestampNs = timestampNs,
|
||||
baseCropRect = cameraCropRect,
|
||||
textureAxesSwapped = cameraTransformAxesSwapped == true,
|
||||
)
|
||||
} else {
|
||||
null
|
||||
}
|
||||
|
||||
val firstLayer = layers.first()
|
||||
val grainEnabled = finalFilmGrainEnabled
|
||||
@@ -194,11 +221,12 @@ class RealtimeVideoRenderer(
|
||||
textureTarget = GLES11Ext.GL_TEXTURE_EXTERNAL_OES,
|
||||
textureId = cameraTextureId,
|
||||
sourceStMatrix = stMatrix,
|
||||
cropRect = cameraCropRect,
|
||||
cropRect = stabilizationTransform?.cropRect ?: cameraCropRect,
|
||||
mvpMatrix = firstPassMvpMatrix,
|
||||
enableVideoLog = videoLogProfile.isEnabled,
|
||||
treatSourceAsHlgInput = hlgInput,
|
||||
presentationTimeNs = timestampNs,
|
||||
stabilizationTransform = stabilizationTransform,
|
||||
)
|
||||
|
||||
if (layers.size > 1) {
|
||||
@@ -282,6 +310,7 @@ class RealtimeVideoRenderer(
|
||||
enableVideoLog: Boolean,
|
||||
treatSourceAsHlgInput: Boolean,
|
||||
presentationTimeNs: Long,
|
||||
stabilizationTransform: AlgorithmicStabilizationTransform? = null,
|
||||
) {
|
||||
val lutEnabled = layer.lutConfig != null && layer.lutTextureId != 0
|
||||
val variant = PreviewColorShaderVariant.forPass(
|
||||
@@ -321,6 +350,21 @@ class RealtimeVideoRenderer(
|
||||
cropRect[2],
|
||||
cropRect[3],
|
||||
)
|
||||
val stabilizationEnabled = stabilizationTransform != null &&
|
||||
stabilizationTransform.rowHomographies.size == STABILIZATION_ROW_COUNT * 9
|
||||
GLES30.glUniform1i(
|
||||
locations.uStabilizationEnabledLocation,
|
||||
if (stabilizationEnabled) 1 else 0,
|
||||
)
|
||||
if (stabilizationEnabled) {
|
||||
GLES30.glUniformMatrix3fv(
|
||||
locations.uStabilizationRowsLocation,
|
||||
STABILIZATION_ROW_COUNT,
|
||||
false,
|
||||
stabilizationTransform.rowHomographies,
|
||||
0,
|
||||
)
|
||||
}
|
||||
GLES30.glUniform1f(
|
||||
locations.uLutSizeLocation,
|
||||
layer.lutConfig?.size?.toFloat() ?: 1f,
|
||||
@@ -769,7 +813,22 @@ class RealtimeVideoRenderer(
|
||||
GLES30.glDisableVertexAttribArray(textureLocation)
|
||||
}
|
||||
|
||||
@Synchronized
|
||||
fun pauseStabilization() {
|
||||
stabilizationSession?.stop()
|
||||
stabilizationSessionStarted = false
|
||||
}
|
||||
|
||||
@Synchronized
|
||||
fun resumeStabilization() {
|
||||
if (!enhancedStabilizationEnabled || stabilizationSessionStarted) return
|
||||
stabilizationSessionStarted = stabilizationSession?.start() == true
|
||||
}
|
||||
|
||||
fun release() {
|
||||
stabilizationSession?.stop()
|
||||
stabilizationSession = null
|
||||
stabilizationSessionStarted = false
|
||||
if (eglDisplay != EGL14.EGL_NO_DISPLAY &&
|
||||
eglContext != EGL14.EGL_NO_CONTEXT &&
|
||||
encoderEglSurface != EGL14.EGL_NO_SURFACE
|
||||
|
||||
@@ -25,6 +25,7 @@ object Shaders {
|
||||
// 输出到片元着色器
|
||||
out vec2 vTexCoord;
|
||||
out vec2 vRawCoord; // 原始坐标用于色散计算
|
||||
out vec2 vOutputCoord;
|
||||
|
||||
// MVP 变换矩阵(用于 center crop 缩放)
|
||||
uniform mat4 uMVPMatrix;
|
||||
@@ -40,6 +41,7 @@ object Shaders {
|
||||
mix(uCropRect.x, uCropRect.z, aTexCoord.x),
|
||||
mix(uCropRect.y, uCropRect.w, aTexCoord.y)
|
||||
);
|
||||
vOutputCoord = aTexCoord;
|
||||
// 应用 SurfaceTexture 变换矩阵
|
||||
vTexCoord = (uSTMatrix * vec4(croppedCoord, 0.0, 1.0)).xy;
|
||||
vRawCoord = croppedCoord;
|
||||
|
||||
+778
@@ -0,0 +1,778 @@
|
||||
package com.hinnka.mycamera.stabilization
|
||||
|
||||
import android.content.Context
|
||||
import android.graphics.Rect
|
||||
import android.hardware.Sensor
|
||||
import android.hardware.SensorEvent
|
||||
import android.hardware.SensorEventListener
|
||||
import android.hardware.SensorManager
|
||||
import android.hardware.camera2.CameraCharacteristics
|
||||
import android.hardware.camera2.CaptureResult
|
||||
import android.os.Handler
|
||||
import android.os.HandlerThread
|
||||
import android.util.SizeF
|
||||
import com.hinnka.mycamera.utils.PLog
|
||||
import java.util.ArrayDeque
|
||||
import kotlin.math.acos
|
||||
import kotlin.math.cos
|
||||
import kotlin.math.exp
|
||||
import kotlin.math.max
|
||||
import kotlin.math.min
|
||||
import kotlin.math.sin
|
||||
import kotlin.math.sqrt
|
||||
|
||||
const val STABILIZATION_ROW_COUNT = 16
|
||||
|
||||
enum class StabilizationUseCase(
|
||||
internal val smoothingTimeSeconds: Double,
|
||||
internal val cropMarginFraction: Float,
|
||||
) {
|
||||
VIDEO(
|
||||
smoothingTimeSeconds = 0.28,
|
||||
cropMarginFraction = 0.10f,
|
||||
),
|
||||
PHOTO_PREVIEW(
|
||||
smoothingTimeSeconds = 0.14,
|
||||
cropMarginFraction = 0.07f,
|
||||
),
|
||||
}
|
||||
|
||||
data class AlgorithmicStabilizationTransform(
|
||||
/** 16 column-major output-to-input homographies, ready for glUniformMatrix3fv. */
|
||||
val rowHomographies: FloatArray,
|
||||
/** Crop applied before the homographies, in normalized SurfaceTexture coordinates. */
|
||||
val cropRect: FloatArray,
|
||||
val hasPoseCoverage: Boolean,
|
||||
val appliedStrength: Float,
|
||||
val tripodMode: Boolean,
|
||||
)
|
||||
|
||||
private data class CameraCalibration(
|
||||
val activeArray: Rect,
|
||||
val physicalSizeMm: SizeF?,
|
||||
val lensFacing: Int,
|
||||
val timestampSource: Int,
|
||||
)
|
||||
|
||||
private data class FrameMetadata(
|
||||
val timestampNs: Long,
|
||||
val exposureTimeNs: Long,
|
||||
val rollingShutterSkewNs: Long,
|
||||
val cropRegion: Rect?,
|
||||
val zoomRatio: Float,
|
||||
val focalLengthMm: Float,
|
||||
)
|
||||
|
||||
private data class PoseSample(
|
||||
val timestampNs: Long,
|
||||
val orientation: Quaternion,
|
||||
val angularSpeedRadPerSecond: Double,
|
||||
)
|
||||
|
||||
private data class ResolvedFrameMotion(
|
||||
val centerOrientation: Quaternion,
|
||||
val rowOrientations: List<Quaternion>,
|
||||
val metadata: FrameMetadata?,
|
||||
val calibration: CameraCalibration,
|
||||
val tripodMode: Boolean,
|
||||
)
|
||||
|
||||
/**
|
||||
* Shared sensor and Camera2 metadata source for the screen-preview and recording renderers.
|
||||
*
|
||||
* Gyroscope and SENSOR_TIMESTAMP are both expressed against elapsedRealtimeNanos on Android.
|
||||
* A renderer owns a lightweight [Session]; the high-rate sensor listener is reference counted so
|
||||
* the gyro is only active while at least one algorithmic stabilization path is actually rendering.
|
||||
*/
|
||||
class RealtimeStabilizationCoordinator(context: Context) {
|
||||
companion object {
|
||||
private const val TAG = "RealtimeStabilization"
|
||||
private const val MAX_POSE_AGE_NS = 3_000_000_000L
|
||||
private const val MAX_METADATA_AGE_NS = 3_000_000_000L
|
||||
private const val MAX_GYRO_STEP_NS = 50_000_000L
|
||||
private const val METADATA_MATCH_TOLERANCE_NS = 12_000_000L
|
||||
private const val TRIPOD_SPEED_THRESHOLD_RAD_S = 0.012
|
||||
private const val TRIPOD_HOLD_NS = 800_000_000L
|
||||
}
|
||||
|
||||
private val sensorManager = context.applicationContext
|
||||
.getSystemService(Context.SENSOR_SERVICE) as SensorManager
|
||||
private val gyroSensor = sensorManager.getDefaultSensor(Sensor.TYPE_GYROSCOPE_UNCALIBRATED)
|
||||
?: sensorManager.getDefaultSensor(Sensor.TYPE_GYROSCOPE)
|
||||
private val lock = Any()
|
||||
private val poses = ArrayDeque<PoseSample>()
|
||||
private val frameMetadata = ArrayDeque<FrameMetadata>()
|
||||
|
||||
@Volatile
|
||||
private var calibration: CameraCalibration? = null
|
||||
|
||||
private var sensorThread: HandlerThread? = null
|
||||
private var activeSessionCount = 0
|
||||
private var integratedOrientation = Quaternion.IDENTITY
|
||||
private var previousRate = Vec3.ZERO
|
||||
private var previousGyroTimestampNs = 0L
|
||||
private var stillSinceTimestampNs = 0L
|
||||
private var tripodMode = false
|
||||
|
||||
val isGyroscopeAvailable: Boolean
|
||||
get() = gyroSensor != null
|
||||
|
||||
val isCurrentCameraSupported: Boolean
|
||||
get() {
|
||||
val current = calibration
|
||||
return isGyroscopeAvailable &&
|
||||
current?.lensFacing == CameraCharacteristics.LENS_FACING_BACK &&
|
||||
current.timestampSource ==
|
||||
CameraCharacteristics.SENSOR_INFO_TIMESTAMP_SOURCE_REALTIME
|
||||
}
|
||||
|
||||
fun isCameraSupported(
|
||||
characteristics: CameraCharacteristics,
|
||||
timingCharacteristics: CameraCharacteristics = characteristics,
|
||||
): Boolean {
|
||||
val lensFacing = characteristics.get(CameraCharacteristics.LENS_FACING)
|
||||
?: timingCharacteristics.get(CameraCharacteristics.LENS_FACING)
|
||||
val timestampSource = timingCharacteristics.get(
|
||||
CameraCharacteristics.SENSOR_INFO_TIMESTAMP_SOURCE
|
||||
) ?: CameraCharacteristics.SENSOR_INFO_TIMESTAMP_SOURCE_UNKNOWN
|
||||
return isGyroscopeAvailable &&
|
||||
characteristics.get(CameraCharacteristics.SENSOR_INFO_ACTIVE_ARRAY_SIZE) != null &&
|
||||
lensFacing == CameraCharacteristics.LENS_FACING_BACK &&
|
||||
timestampSource == CameraCharacteristics.SENSOR_INFO_TIMESTAMP_SOURCE_REALTIME
|
||||
}
|
||||
|
||||
private val sensorListener = object : SensorEventListener {
|
||||
override fun onSensorChanged(event: SensorEvent) {
|
||||
if (event.values.size < 3) return
|
||||
val uncalibrated = event.sensor.type == Sensor.TYPE_GYROSCOPE_UNCALIBRATED &&
|
||||
event.values.size >= 6
|
||||
val rate = Vec3(
|
||||
x = (event.values[0] - if (uncalibrated) event.values[3] else 0f).toDouble(),
|
||||
y = (event.values[1] - if (uncalibrated) event.values[4] else 0f).toDouble(),
|
||||
z = (event.values[2] - if (uncalibrated) event.values[5] else 0f).toDouble(),
|
||||
)
|
||||
appendGyro(event.timestamp, rate)
|
||||
}
|
||||
|
||||
override fun onAccuracyChanged(sensor: Sensor?, accuracy: Int) = Unit
|
||||
}
|
||||
|
||||
fun configureCamera(
|
||||
characteristics: CameraCharacteristics,
|
||||
timingCharacteristics: CameraCharacteristics = characteristics,
|
||||
) {
|
||||
val activeArray = characteristics.get(CameraCharacteristics.SENSOR_INFO_ACTIVE_ARRAY_SIZE)
|
||||
if (activeArray == null) {
|
||||
calibration = null
|
||||
return
|
||||
}
|
||||
calibration = CameraCalibration(
|
||||
activeArray = Rect(activeArray),
|
||||
physicalSizeMm = characteristics.get(CameraCharacteristics.SENSOR_INFO_PHYSICAL_SIZE),
|
||||
lensFacing = characteristics.get(CameraCharacteristics.LENS_FACING)
|
||||
?: timingCharacteristics.get(CameraCharacteristics.LENS_FACING)
|
||||
?: CameraCharacteristics.LENS_FACING_BACK,
|
||||
timestampSource = timingCharacteristics.get(
|
||||
CameraCharacteristics.SENSOR_INFO_TIMESTAMP_SOURCE
|
||||
) ?: CameraCharacteristics.SENSOR_INFO_TIMESTAMP_SOURCE_UNKNOWN,
|
||||
)
|
||||
}
|
||||
|
||||
fun submitCaptureResult(result: CaptureResult) {
|
||||
val timestampNs = result.get(CaptureResult.SENSOR_TIMESTAMP) ?: return
|
||||
val metadata = FrameMetadata(
|
||||
timestampNs = timestampNs,
|
||||
exposureTimeNs = result.get(CaptureResult.SENSOR_EXPOSURE_TIME)?.coerceAtLeast(0L) ?: 0L,
|
||||
rollingShutterSkewNs = result.get(CaptureResult.SENSOR_ROLLING_SHUTTER_SKEW)
|
||||
?.coerceAtLeast(0L) ?: 0L,
|
||||
cropRegion = result.get(CaptureResult.SCALER_CROP_REGION)?.let(::Rect),
|
||||
zoomRatio = result.get(CaptureResult.CONTROL_ZOOM_RATIO)?.coerceAtLeast(1f) ?: 1f,
|
||||
focalLengthMm = result.get(CaptureResult.LENS_FOCAL_LENGTH)?.coerceAtLeast(0f) ?: 0f,
|
||||
)
|
||||
synchronized(lock) {
|
||||
if (frameMetadata.isNotEmpty() && timestampNs <= frameMetadata.last().timestampNs) {
|
||||
frameMetadata.removeAll { it.timestampNs == timestampNs }
|
||||
}
|
||||
frameMetadata.addLast(metadata)
|
||||
val oldestAllowed = timestampNs - MAX_METADATA_AGE_NS
|
||||
while (frameMetadata.firstOrNull()?.timestampNs?.let { it < oldestAllowed } == true) {
|
||||
frameMetadata.removeFirst()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fun createSession(useCase: StabilizationUseCase): Session = Session(this, useCase)
|
||||
|
||||
private fun acquireSensor(): Boolean {
|
||||
synchronized(lock) {
|
||||
activeSessionCount += 1
|
||||
if (activeSessionCount > 1) return true
|
||||
val sensor = gyroSensor ?: run {
|
||||
activeSessionCount = 0
|
||||
return false
|
||||
}
|
||||
poses.clear()
|
||||
integratedOrientation = Quaternion.IDENTITY
|
||||
previousRate = Vec3.ZERO
|
||||
previousGyroTimestampNs = 0L
|
||||
stillSinceTimestampNs = 0L
|
||||
tripodMode = false
|
||||
val thread = HandlerThread("Photon-Stabilization-Gyro").apply { start() }
|
||||
val registered = sensorManager.registerListener(
|
||||
sensorListener,
|
||||
sensor,
|
||||
SensorManager.SENSOR_DELAY_FASTEST,
|
||||
Handler(thread.looper),
|
||||
)
|
||||
if (!registered) {
|
||||
thread.quitSafely()
|
||||
activeSessionCount = 0
|
||||
PLog.w(TAG, "Unable to register gyroscope listener")
|
||||
return false
|
||||
}
|
||||
sensorThread = thread
|
||||
PLog.i(TAG, "Gyroscope stream started: ${sensor.name}")
|
||||
return true
|
||||
}
|
||||
}
|
||||
|
||||
private fun releaseSensor() {
|
||||
synchronized(lock) {
|
||||
if (activeSessionCount <= 0) return
|
||||
activeSessionCount -= 1
|
||||
if (activeSessionCount > 0) return
|
||||
sensorManager.unregisterListener(sensorListener)
|
||||
sensorThread?.quitSafely()
|
||||
sensorThread = null
|
||||
poses.clear()
|
||||
previousGyroTimestampNs = 0L
|
||||
PLog.i(TAG, "Gyroscope stream stopped")
|
||||
}
|
||||
}
|
||||
|
||||
private fun appendGyro(timestampNs: Long, rate: Vec3) {
|
||||
synchronized(lock) {
|
||||
if (activeSessionCount <= 0) return
|
||||
if (previousGyroTimestampNs == 0L) {
|
||||
previousGyroTimestampNs = timestampNs
|
||||
previousRate = rate
|
||||
poses.addLast(PoseSample(timestampNs, integratedOrientation, rate.length()))
|
||||
updateTripodState(timestampNs, rate.length())
|
||||
return
|
||||
}
|
||||
val stepNs = timestampNs - previousGyroTimestampNs
|
||||
if (stepNs <= 0L) return
|
||||
if (stepNs > MAX_GYRO_STEP_NS) {
|
||||
integratedOrientation = Quaternion.IDENTITY
|
||||
poses.clear()
|
||||
} else {
|
||||
val dt = stepNs.toDouble() * 1.0e-9
|
||||
val midpointRate = (previousRate + rate) * 0.5
|
||||
integratedOrientation = (
|
||||
integratedOrientation * Quaternion.fromRotationVector(midpointRate * dt)
|
||||
).normalized()
|
||||
}
|
||||
previousGyroTimestampNs = timestampNs
|
||||
previousRate = rate
|
||||
val angularSpeed = rate.length()
|
||||
poses.addLast(PoseSample(timestampNs, integratedOrientation, angularSpeed))
|
||||
updateTripodState(timestampNs, angularSpeed)
|
||||
|
||||
val oldestAllowed = timestampNs - MAX_POSE_AGE_NS
|
||||
while (poses.firstOrNull()?.timestampNs?.let { it < oldestAllowed } == true) {
|
||||
poses.removeFirst()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private fun updateTripodState(timestampNs: Long, angularSpeed: Double) {
|
||||
if (angularSpeed <= TRIPOD_SPEED_THRESHOLD_RAD_S) {
|
||||
if (stillSinceTimestampNs == 0L) stillSinceTimestampNs = timestampNs
|
||||
tripodMode = timestampNs - stillSinceTimestampNs >= TRIPOD_HOLD_NS
|
||||
} else {
|
||||
stillSinceTimestampNs = 0L
|
||||
tripodMode = false
|
||||
}
|
||||
}
|
||||
|
||||
private fun resolveFrameMotion(timestampNs: Long): ResolvedFrameMotion? {
|
||||
val currentCalibration = calibration ?: return null
|
||||
synchronized(lock) {
|
||||
if (poses.size < 2) return null
|
||||
val metadata = nearestMetadataLocked(timestampNs)
|
||||
val exposureNs = metadata?.exposureTimeNs ?: 0L
|
||||
val rollingSkewNs = metadata?.rollingShutterSkewNs ?: 0L
|
||||
val activeHeight = currentCalibration.activeArray.height().coerceAtLeast(1)
|
||||
val crop = metadata?.cropRegion ?: currentCalibration.activeArray
|
||||
val cropStartFraction = (crop.top - currentCalibration.activeArray.top)
|
||||
.toDouble() / activeHeight.toDouble()
|
||||
val cropHeightFraction = crop.height().toDouble() / activeHeight.toDouble()
|
||||
val firstRowCenterNs = timestampNs + exposureNs / 2L +
|
||||
(rollingSkewNs * cropStartFraction).toLong()
|
||||
val rowSpanNs = (rollingSkewNs * cropHeightFraction).toLong()
|
||||
val centerTimestampNs = firstRowCenterNs + rowSpanNs / 2L
|
||||
val firstPoseTimestamp = poses.first().timestampNs
|
||||
val lastPoseTimestamp = poses.last().timestampNs
|
||||
if (centerTimestampNs < firstPoseTimestamp - METADATA_MATCH_TOLERANCE_NS ||
|
||||
centerTimestampNs > lastPoseTimestamp + METADATA_MATCH_TOLERANCE_NS
|
||||
) {
|
||||
return null
|
||||
}
|
||||
|
||||
val center = orientationAtLocked(centerTimestampNs) ?: return null
|
||||
val rows = List(STABILIZATION_ROW_COUNT) { index ->
|
||||
val fraction = index.toDouble() / (STABILIZATION_ROW_COUNT - 1).toDouble()
|
||||
orientationAtLocked(firstRowCenterNs + (rowSpanNs * fraction).toLong()) ?: center
|
||||
}
|
||||
return ResolvedFrameMotion(
|
||||
centerOrientation = center,
|
||||
rowOrientations = rows,
|
||||
metadata = metadata,
|
||||
calibration = currentCalibration,
|
||||
tripodMode = tripodMode,
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
private fun nearestMetadataLocked(timestampNs: Long): FrameMetadata? {
|
||||
var best: FrameMetadata? = null
|
||||
var bestDistance = Long.MAX_VALUE
|
||||
frameMetadata.forEach { candidate ->
|
||||
val distance = absoluteDifference(candidate.timestampNs, timestampNs)
|
||||
if (distance < bestDistance) {
|
||||
best = candidate
|
||||
bestDistance = distance
|
||||
}
|
||||
}
|
||||
return best?.takeIf { bestDistance <= METADATA_MATCH_TOLERANCE_NS }
|
||||
}
|
||||
|
||||
private fun orientationAtLocked(timestampNs: Long): Quaternion? {
|
||||
if (poses.isEmpty()) return null
|
||||
if (timestampNs <= poses.first().timestampNs) return poses.first().orientation
|
||||
if (timestampNs >= poses.last().timestampNs) return poses.last().orientation
|
||||
var before = poses.first()
|
||||
poses.forEach { after ->
|
||||
if (after.timestampNs >= timestampNs) {
|
||||
val span = after.timestampNs - before.timestampNs
|
||||
if (span <= 0L) return before.orientation
|
||||
val fraction = (timestampNs - before.timestampNs).toDouble() / span.toDouble()
|
||||
return Quaternion.slerp(before.orientation, after.orientation, fraction)
|
||||
}
|
||||
before = after
|
||||
}
|
||||
return poses.last().orientation
|
||||
}
|
||||
|
||||
class Session internal constructor(
|
||||
private val coordinator: RealtimeStabilizationCoordinator,
|
||||
private val useCase: StabilizationUseCase,
|
||||
) {
|
||||
private var active = false
|
||||
private var smoothedOrientation: Quaternion? = null
|
||||
private var lastFrameTimestampNs = 0L
|
||||
|
||||
@Synchronized
|
||||
fun start(): Boolean {
|
||||
if (active) return true
|
||||
if (!coordinator.isCurrentCameraSupported) return false
|
||||
active = coordinator.acquireSensor()
|
||||
smoothedOrientation = null
|
||||
lastFrameTimestampNs = 0L
|
||||
return active
|
||||
}
|
||||
|
||||
@Synchronized
|
||||
fun stop() {
|
||||
if (!active) return
|
||||
active = false
|
||||
smoothedOrientation = null
|
||||
lastFrameTimestampNs = 0L
|
||||
coordinator.releaseSensor()
|
||||
}
|
||||
|
||||
@Synchronized
|
||||
fun transformForFrame(
|
||||
timestampNs: Long,
|
||||
baseCropRect: FloatArray,
|
||||
textureAxesSwapped: Boolean,
|
||||
displayRotationDegrees: Int = 0,
|
||||
): AlgorithmicStabilizationTransform? {
|
||||
if (!active || !coordinator.isCurrentCameraSupported ||
|
||||
timestampNs <= 0L || baseCropRect.size < 4
|
||||
) {
|
||||
return null
|
||||
}
|
||||
val stabilizedCrop = insetCrop(baseCropRect, useCase.cropMarginFraction)
|
||||
val motion = coordinator.resolveFrameMotion(timestampNs)
|
||||
?: return identityTransform(stabilizedCrop, hasCoverage = false)
|
||||
|
||||
val currentSmooth = smoothedOrientation
|
||||
val frameDeltaNs = timestampNs - lastFrameTimestampNs
|
||||
val nextSmooth = if (currentSmooth == null || frameDeltaNs <= 0L ||
|
||||
frameDeltaNs > 500_000_000L
|
||||
) {
|
||||
motion.centerOrientation
|
||||
} else {
|
||||
val timeConstant = if (motion.tripodMode) {
|
||||
max(useCase.smoothingTimeSeconds, 0.72)
|
||||
} else {
|
||||
useCase.smoothingTimeSeconds
|
||||
}
|
||||
val alpha = 1.0 - exp(-frameDeltaNs.toDouble() * 1.0e-9 / timeConstant)
|
||||
Quaternion.slerp(currentSmooth, motion.centerOrientation, alpha.coerceIn(0.0, 1.0))
|
||||
}
|
||||
smoothedOrientation = nextSmooth
|
||||
lastFrameTimestampNs = timestampNs
|
||||
|
||||
val focal = resolveNormalizedFocalLength(
|
||||
calibration = motion.calibration,
|
||||
metadata = motion.metadata,
|
||||
axesSwapped = textureAxesSwapped,
|
||||
)
|
||||
val rowCorrections = motion.rowOrientations.map { rowOrientation ->
|
||||
val outputToInput = rowOrientation.inverse() * nextSmooth
|
||||
mapDeviceRotationToDisplay(
|
||||
Quaternion.log(outputToInput),
|
||||
displayRotationDegrees,
|
||||
)
|
||||
}
|
||||
val safeStrength = constrainStrength(
|
||||
rotations = rowCorrections,
|
||||
focalX = focal.first,
|
||||
focalY = focal.second,
|
||||
stabilizedCrop = stabilizedCrop,
|
||||
availableCrop = baseCropRect,
|
||||
)
|
||||
val matrices = FloatArray(STABILIZATION_ROW_COUNT * 9)
|
||||
rowCorrections.forEachIndexed { index, rotationVector ->
|
||||
val homography = homographyForRotation(
|
||||
rotationVector = rotationVector * safeStrength.toDouble(),
|
||||
focalX = focal.first,
|
||||
focalY = focal.second,
|
||||
)
|
||||
homography.writeColumnMajor(matrices, index * 9)
|
||||
}
|
||||
return AlgorithmicStabilizationTransform(
|
||||
rowHomographies = matrices,
|
||||
cropRect = stabilizedCrop,
|
||||
hasPoseCoverage = true,
|
||||
appliedStrength = safeStrength,
|
||||
tripodMode = motion.tripodMode,
|
||||
)
|
||||
}
|
||||
|
||||
private fun constrainStrength(
|
||||
rotations: List<Vec3>,
|
||||
focalX: Double,
|
||||
focalY: Double,
|
||||
stabilizedCrop: FloatArray,
|
||||
availableCrop: FloatArray,
|
||||
): Float {
|
||||
fun safe(strength: Double): Boolean {
|
||||
rotations.forEach { rotation ->
|
||||
val h = homographyForRotation(rotation * strength, focalX, focalY)
|
||||
if (!cornersStayInside(h, stabilizedCrop, availableCrop)) return false
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
if (safe(1.0)) return 1f
|
||||
var low = 0.0
|
||||
var high = 1.0
|
||||
repeat(10) {
|
||||
val middle = (low + high) * 0.5
|
||||
if (safe(middle)) low = middle else high = middle
|
||||
}
|
||||
return low.toFloat()
|
||||
}
|
||||
|
||||
private fun identityTransform(
|
||||
crop: FloatArray,
|
||||
hasCoverage: Boolean,
|
||||
): AlgorithmicStabilizationTransform {
|
||||
val matrices = FloatArray(STABILIZATION_ROW_COUNT * 9)
|
||||
repeat(STABILIZATION_ROW_COUNT) { index ->
|
||||
Mat3.IDENTITY.writeColumnMajor(matrices, index * 9)
|
||||
}
|
||||
return AlgorithmicStabilizationTransform(
|
||||
rowHomographies = matrices,
|
||||
cropRect = crop,
|
||||
hasPoseCoverage = hasCoverage,
|
||||
appliedStrength = 0f,
|
||||
tripodMode = false,
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private fun resolveNormalizedFocalLength(
|
||||
calibration: CameraCalibration,
|
||||
metadata: FrameMetadata?,
|
||||
axesSwapped: Boolean,
|
||||
): Pair<Double, Double> {
|
||||
val physical = calibration.physicalSizeMm
|
||||
val focalMm = metadata?.focalLengthMm?.toDouble()?.takeIf { it > 0.0 }
|
||||
if (physical == null || focalMm == null || physical.width <= 0f || physical.height <= 0f) {
|
||||
return 1.20 to 1.20
|
||||
}
|
||||
|
||||
val active = calibration.activeArray
|
||||
val crop = metadata.cropRegion ?: active
|
||||
val zoom = metadata.zoomRatio.toDouble().coerceAtLeast(1.0)
|
||||
val effectiveWidth = min(crop.width().toDouble(), active.width().toDouble() / zoom).coerceAtLeast(1.0)
|
||||
val effectiveHeight = min(crop.height().toDouble(), active.height().toDouble() / zoom).coerceAtLeast(1.0)
|
||||
val horizontal = focalMm / physical.width.toDouble() * active.width().toDouble() / effectiveWidth
|
||||
val vertical = focalMm / physical.height.toDouble() * active.height().toDouble() / effectiveHeight
|
||||
return if (axesSwapped) vertical to horizontal else horizontal to vertical
|
||||
}
|
||||
|
||||
private fun mapDeviceRotationToDisplay(rotation: Vec3, displayRotationDegrees: Int): Vec3 {
|
||||
val normalizedRotation = ((displayRotationDegrees % 360) + 360) % 360
|
||||
val radians = Math.toRadians(normalizedRotation.toDouble())
|
||||
val c = cos(radians)
|
||||
val s = sin(radians)
|
||||
val screenRight = Vec3(c, -s, 0.0)
|
||||
val screenDown = Vec3(-s, -c, 0.0)
|
||||
val sceneForward = Vec3(0.0, 0.0, -1.0)
|
||||
return Vec3(
|
||||
rotation.dot(screenRight),
|
||||
rotation.dot(screenDown),
|
||||
rotation.dot(sceneForward),
|
||||
)
|
||||
}
|
||||
|
||||
private fun homographyForRotation(
|
||||
rotationVector: Vec3,
|
||||
focalX: Double,
|
||||
focalY: Double,
|
||||
): Mat3 {
|
||||
val safeFocalX = focalX.coerceIn(0.25, 20.0)
|
||||
val safeFocalY = focalY.coerceIn(0.25, 20.0)
|
||||
val intrinsics = Mat3(
|
||||
doubleArrayOf(
|
||||
safeFocalX, 0.0, 0.5,
|
||||
0.0, safeFocalY, 0.5,
|
||||
0.0, 0.0, 1.0,
|
||||
)
|
||||
)
|
||||
val rotation = Quaternion.fromRotationVector(rotationVector).toMatrix3()
|
||||
return intrinsics * rotation * intrinsics.inverse()
|
||||
}
|
||||
|
||||
private fun cornersStayInside(
|
||||
homography: Mat3,
|
||||
sourceCrop: FloatArray,
|
||||
bounds: FloatArray,
|
||||
): Boolean {
|
||||
val corners = arrayOf(
|
||||
Vec2(sourceCrop[0].toDouble(), sourceCrop[1].toDouble()),
|
||||
Vec2(sourceCrop[2].toDouble(), sourceCrop[1].toDouble()),
|
||||
Vec2(sourceCrop[0].toDouble(), sourceCrop[3].toDouble()),
|
||||
Vec2(sourceCrop[2].toDouble(), sourceCrop[3].toDouble()),
|
||||
)
|
||||
return corners.all { corner ->
|
||||
val point = homography.transform(corner) ?: return@all false
|
||||
point.x >= bounds[0] && point.x <= bounds[2] &&
|
||||
point.y >= bounds[1] && point.y <= bounds[3]
|
||||
}
|
||||
}
|
||||
|
||||
private fun insetCrop(crop: FloatArray, marginFraction: Float): FloatArray {
|
||||
val margin = marginFraction.coerceIn(0f, 0.24f)
|
||||
val widthInset = (crop[2] - crop[0]) * margin
|
||||
val heightInset = (crop[3] - crop[1]) * margin
|
||||
return floatArrayOf(
|
||||
crop[0] + widthInset,
|
||||
crop[1] + heightInset,
|
||||
crop[2] - widthInset,
|
||||
crop[3] - heightInset,
|
||||
)
|
||||
}
|
||||
|
||||
private data class Vec2(val x: Double, val y: Double)
|
||||
|
||||
private data class Vec3(val x: Double, val y: Double, val z: Double) {
|
||||
operator fun plus(other: Vec3) = Vec3(x + other.x, y + other.y, z + other.z)
|
||||
operator fun times(scale: Double) = Vec3(x * scale, y * scale, z * scale)
|
||||
fun dot(other: Vec3): Double = x * other.x + y * other.y + z * other.z
|
||||
fun length(): Double = sqrt(dot(this))
|
||||
|
||||
companion object {
|
||||
val ZERO = Vec3(0.0, 0.0, 0.0)
|
||||
}
|
||||
}
|
||||
|
||||
private data class Quaternion(
|
||||
val w: Double,
|
||||
val x: Double,
|
||||
val y: Double,
|
||||
val z: Double,
|
||||
) {
|
||||
operator fun times(other: Quaternion): Quaternion = Quaternion(
|
||||
w = w * other.w - x * other.x - y * other.y - z * other.z,
|
||||
x = w * other.x + x * other.w + y * other.z - z * other.y,
|
||||
y = w * other.y - x * other.z + y * other.w + z * other.x,
|
||||
z = w * other.z + x * other.y - y * other.x + z * other.w,
|
||||
)
|
||||
|
||||
fun normalized(): Quaternion {
|
||||
val magnitude = sqrt(w * w + x * x + y * y + z * z)
|
||||
return if (magnitude <= 1.0e-12) IDENTITY else Quaternion(
|
||||
w / magnitude,
|
||||
x / magnitude,
|
||||
y / magnitude,
|
||||
z / magnitude,
|
||||
)
|
||||
}
|
||||
|
||||
fun inverse(): Quaternion = Quaternion(w, -x, -y, -z).normalized()
|
||||
|
||||
fun toMatrix3(): Mat3 {
|
||||
val q = normalized()
|
||||
val xx = q.x * q.x
|
||||
val yy = q.y * q.y
|
||||
val zz = q.z * q.z
|
||||
val xy = q.x * q.y
|
||||
val xz = q.x * q.z
|
||||
val yz = q.y * q.z
|
||||
val wx = q.w * q.x
|
||||
val wy = q.w * q.y
|
||||
val wz = q.w * q.z
|
||||
return Mat3(
|
||||
doubleArrayOf(
|
||||
1.0 - 2.0 * (yy + zz), 2.0 * (xy - wz), 2.0 * (xz + wy),
|
||||
2.0 * (xy + wz), 1.0 - 2.0 * (xx + zz), 2.0 * (yz - wx),
|
||||
2.0 * (xz - wy), 2.0 * (yz + wx), 1.0 - 2.0 * (xx + yy),
|
||||
)
|
||||
)
|
||||
}
|
||||
|
||||
companion object {
|
||||
val IDENTITY = Quaternion(1.0, 0.0, 0.0, 0.0)
|
||||
|
||||
fun fromRotationVector(vector: Vec3): Quaternion {
|
||||
val angle = vector.length()
|
||||
if (angle <= 1.0e-12) return IDENTITY
|
||||
val half = angle * 0.5
|
||||
val scale = sin(half) / angle
|
||||
return Quaternion(cos(half), vector.x * scale, vector.y * scale, vector.z * scale)
|
||||
.normalized()
|
||||
}
|
||||
|
||||
fun log(value: Quaternion): Vec3 {
|
||||
val q = value.normalized().let { if (it.w < 0.0) Quaternion(-it.w, -it.x, -it.y, -it.z) else it }
|
||||
val vectorLength = sqrt(q.x * q.x + q.y * q.y + q.z * q.z)
|
||||
if (vectorLength <= 1.0e-12) return Vec3.ZERO
|
||||
val angle = 2.0 * kotlin.math.atan2(vectorLength, q.w.coerceIn(-1.0, 1.0))
|
||||
val scale = angle / vectorLength
|
||||
return Vec3(q.x * scale, q.y * scale, q.z * scale)
|
||||
}
|
||||
|
||||
fun slerp(from: Quaternion, to: Quaternion, amount: Double): Quaternion {
|
||||
val a = from.normalized()
|
||||
var b = to.normalized()
|
||||
var dot = a.w * b.w + a.x * b.x + a.y * b.y + a.z * b.z
|
||||
if (dot < 0.0) {
|
||||
b = Quaternion(-b.w, -b.x, -b.y, -b.z)
|
||||
dot = -dot
|
||||
}
|
||||
val t = amount.coerceIn(0.0, 1.0)
|
||||
if (dot > 0.9995) {
|
||||
return Quaternion(
|
||||
a.w + (b.w - a.w) * t,
|
||||
a.x + (b.x - a.x) * t,
|
||||
a.y + (b.y - a.y) * t,
|
||||
a.z + (b.z - a.z) * t,
|
||||
).normalized()
|
||||
}
|
||||
val theta = acos(dot.coerceIn(-1.0, 1.0))
|
||||
val denominator = sin(theta)
|
||||
val fromWeight = sin((1.0 - t) * theta) / denominator
|
||||
val toWeight = sin(t * theta) / denominator
|
||||
return Quaternion(
|
||||
a.w * fromWeight + b.w * toWeight,
|
||||
a.x * fromWeight + b.x * toWeight,
|
||||
a.y * fromWeight + b.y * toWeight,
|
||||
a.z * fromWeight + b.z * toWeight,
|
||||
).normalized()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private class Mat3(private val values: DoubleArray) {
|
||||
init {
|
||||
require(values.size == 9)
|
||||
}
|
||||
|
||||
operator fun times(other: Mat3): Mat3 {
|
||||
val out = DoubleArray(9)
|
||||
for (row in 0..2) {
|
||||
for (column in 0..2) {
|
||||
out[row * 3 + column] = (0..2).sumOf { index ->
|
||||
values[row * 3 + index] * other.values[index * 3 + column]
|
||||
}
|
||||
}
|
||||
}
|
||||
return Mat3(out)
|
||||
}
|
||||
|
||||
fun inverse(): Mat3 {
|
||||
val a = values[0]
|
||||
val b = values[1]
|
||||
val c = values[2]
|
||||
val d = values[3]
|
||||
val e = values[4]
|
||||
val f = values[5]
|
||||
val g = values[6]
|
||||
val h = values[7]
|
||||
val i = values[8]
|
||||
val determinant = a * (e * i - f * h) - b * (d * i - f * g) + c * (d * h - e * g)
|
||||
if (kotlin.math.abs(determinant) <= 1.0e-12) return IDENTITY
|
||||
val reciprocal = 1.0 / determinant
|
||||
return Mat3(
|
||||
doubleArrayOf(
|
||||
(e * i - f * h) * reciprocal,
|
||||
(c * h - b * i) * reciprocal,
|
||||
(b * f - c * e) * reciprocal,
|
||||
(f * g - d * i) * reciprocal,
|
||||
(a * i - c * g) * reciprocal,
|
||||
(c * d - a * f) * reciprocal,
|
||||
(d * h - e * g) * reciprocal,
|
||||
(b * g - a * h) * reciprocal,
|
||||
(a * e - b * d) * reciprocal,
|
||||
)
|
||||
)
|
||||
}
|
||||
|
||||
fun transform(point: Vec2): Vec2? {
|
||||
val denominator = values[6] * point.x + values[7] * point.y + values[8]
|
||||
if (kotlin.math.abs(denominator) <= 1.0e-9) return null
|
||||
return Vec2(
|
||||
x = (values[0] * point.x + values[1] * point.y + values[2]) / denominator,
|
||||
y = (values[3] * point.x + values[4] * point.y + values[5]) / denominator,
|
||||
)
|
||||
}
|
||||
|
||||
fun writeColumnMajor(destination: FloatArray, offset: Int) {
|
||||
for (row in 0..2) {
|
||||
for (column in 0..2) {
|
||||
destination[offset + column * 3 + row] = values[row * 3 + column].toFloat()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
companion object {
|
||||
val IDENTITY = Mat3(
|
||||
doubleArrayOf(
|
||||
1.0, 0.0, 0.0,
|
||||
0.0, 1.0, 0.0,
|
||||
0.0, 0.0, 1.0,
|
||||
)
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
private fun absoluteDifference(a: Long, b: Long): Long {
|
||||
return if (a >= b) a - b else b - a
|
||||
}
|
||||
@@ -17,6 +17,7 @@ import com.hinnka.mycamera.lut.PreviewCaptureSource
|
||||
import com.hinnka.mycamera.model.ColorRecipeParams
|
||||
import com.hinnka.mycamera.model.ColorPaletteMapper
|
||||
import com.hinnka.mycamera.screencapture.PhantomPipCrop
|
||||
import com.hinnka.mycamera.stabilization.RealtimeStabilizationCoordinator
|
||||
import com.hinnka.mycamera.utils.PLog
|
||||
import com.hinnka.mycamera.video.VideoLogProfile
|
||||
|
||||
@@ -36,6 +37,8 @@ class CameraGLSurfaceView @JvmOverloads constructor(
|
||||
}
|
||||
|
||||
private val renderer: LutRenderer = LutRenderer(context.applicationContext)
|
||||
private var currentStabilizationCoordinator: RealtimeStabilizationCoordinator? = null
|
||||
private var currentPhotoPreviewStabilizationEnabled = false
|
||||
|
||||
var onHistogramUpdated: ((IntArray) -> Unit)? = null
|
||||
var onMeteringUpdated: ((Double, Double) -> Unit)? = null
|
||||
@@ -154,6 +157,24 @@ class CameraGLSurfaceView @JvmOverloads constructor(
|
||||
}
|
||||
}
|
||||
|
||||
fun setStabilizationCoordinator(coordinator: RealtimeStabilizationCoordinator?) {
|
||||
if (currentStabilizationCoordinator === coordinator) return
|
||||
currentStabilizationCoordinator = coordinator
|
||||
queueEvent {
|
||||
renderer.setStabilizationCoordinator(coordinator)
|
||||
requestRender()
|
||||
}
|
||||
}
|
||||
|
||||
fun setPhotoPreviewStabilizationEnabled(enabled: Boolean) {
|
||||
if (currentPhotoPreviewStabilizationEnabled == enabled) return
|
||||
currentPhotoPreviewStabilizationEnabled = enabled
|
||||
queueEvent {
|
||||
renderer.setPhotoPreviewStabilizationEnabled(enabled)
|
||||
requestRender()
|
||||
}
|
||||
}
|
||||
|
||||
fun setFocusPoint(point: PointF?) {
|
||||
renderer.focusPoint = point
|
||||
}
|
||||
|
||||
@@ -24,6 +24,7 @@ import com.hinnka.mycamera.camera.MeteringMode
|
||||
import com.hinnka.mycamera.lut.LutConfig
|
||||
import com.hinnka.mycamera.model.ColorRecipeParams
|
||||
import com.hinnka.mycamera.preview.EyeFocusPreviewFrame
|
||||
import com.hinnka.mycamera.stabilization.RealtimeStabilizationCoordinator
|
||||
import com.hinnka.mycamera.ui.components.FocusIndicator
|
||||
import com.hinnka.mycamera.utils.OrientationObserver
|
||||
import com.hinnka.mycamera.video.CaptureMode
|
||||
@@ -69,6 +70,8 @@ fun CameraPreviewGL(
|
||||
onGLSurfaceViewReady: ((CameraGLSurfaceView) -> Unit)? = null,
|
||||
isAutoFocus: Boolean = true,
|
||||
focusPeakingEnabled: Boolean = true,
|
||||
stabilizationCoordinator: RealtimeStabilizationCoordinator? = null,
|
||||
photoPreviewStabilizationEnabled: Boolean = false,
|
||||
modifier: Modifier = Modifier
|
||||
) {
|
||||
val rotationDegrees = OrientationObserver.rotationDegrees
|
||||
@@ -218,6 +221,10 @@ fun CameraPreviewGL(
|
||||
glSurfaceView.setDeviceRotation(rotationDegrees.toInt())
|
||||
glSurfaceView.setCalibrationOffset(calibrationOffset)
|
||||
glSurfaceView.setCaptureAspectRatio(aspectRatio)
|
||||
glSurfaceView.setStabilizationCoordinator(stabilizationCoordinator)
|
||||
glSurfaceView.setPhotoPreviewStabilizationEnabled(
|
||||
photoPreviewStabilizationEnabled && captureMode == CaptureMode.PHOTO
|
||||
)
|
||||
|
||||
// 当 SurfaceTexture 准备好且尺寸已就绪时,通知外部打开相机。
|
||||
// 对 previewSize 变化使用 key 重建 GLSurfaceView,避免旧 SurfaceTexture
|
||||
|
||||
@@ -1191,6 +1191,9 @@ fun CameraScreen(
|
||||
isEyeFocusBusy = viewModel.isEyeFocusBusy,
|
||||
isAutoFocus = state.isAutoFocus,
|
||||
focusPeakingEnabled = focusPeakingEnabled && !state.isHyperfocalFocusEnabled,
|
||||
stabilizationCoordinator = viewModel.realtimeStabilizationCoordinator,
|
||||
photoPreviewStabilizationEnabled =
|
||||
state.photoPreviewStabilizationEnabled,
|
||||
modifier = Modifier.fillMaxSize()
|
||||
)
|
||||
}
|
||||
|
||||
@@ -156,6 +156,7 @@ import com.hinnka.mycamera.update.AppUpdateManager
|
||||
import com.hinnka.mycamera.utils.DeviceUtil
|
||||
import com.hinnka.mycamera.viewmodel.CameraViewModel
|
||||
import com.hinnka.mycamera.video.VideoRecordingPath
|
||||
import com.hinnka.mycamera.video.VideoStabilizationMode
|
||||
import java.io.File
|
||||
import java.util.UUID
|
||||
import kotlin.math.roundToInt
|
||||
@@ -375,6 +376,8 @@ fun SettingsScreen(
|
||||
val videoLutId by viewModel.videoLutId.collectAsState()
|
||||
val videoLensLockEnabled by viewModel.videoLensLockEnabled.collectAsState()
|
||||
val videoWhiteBalanceLockEnabled by viewModel.videoWhiteBalanceLockEnabled.collectAsState()
|
||||
val photoPreviewStabilizationEnabled by
|
||||
viewModel.photoPreviewStabilizationEnabled.collectAsState()
|
||||
val openAIApiKey by viewModel.openAIApiKey.collectAsState()
|
||||
val openAIUrl by viewModel.openAIUrl.collectAsState()
|
||||
val openAIModel by viewModel.openAIModel.collectAsState()
|
||||
@@ -1105,6 +1108,23 @@ fun SettingsScreen(
|
||||
checked = focusPeakingEnabled,
|
||||
onCheckedChange = { viewModel.setFocusPeakingEnabled(it) }
|
||||
)
|
||||
|
||||
HorizontalDivider(
|
||||
color = Color.White.copy(alpha = 0.1f),
|
||||
modifier = Modifier.padding(vertical = 8.dp)
|
||||
)
|
||||
|
||||
SwitchSettingItem(
|
||||
title = stringResource(
|
||||
R.string.settings_photo_preview_stabilization
|
||||
),
|
||||
description = stringResource(
|
||||
R.string.settings_photo_preview_stabilization_description
|
||||
),
|
||||
checked = photoPreviewStabilizationEnabled,
|
||||
onCheckedChange = viewModel::setPhotoPreviewStabilizationEnabled,
|
||||
enabled = viewModel.isAlgorithmicStabilizationSupported,
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1530,10 +1550,51 @@ fun SettingsScreen(
|
||||
}
|
||||
|
||||
SettingsPage.VIDEO -> {
|
||||
val stabilizationModes = VideoStabilizationMode.entries.filter { mode ->
|
||||
mode != VideoStabilizationMode.ENHANCED ||
|
||||
viewModel.isAlgorithmicStabilizationSupported
|
||||
}
|
||||
val stabilizationModeLabels = stabilizationModes.map { mode ->
|
||||
mode to when (mode) {
|
||||
VideoStabilizationMode.OFF ->
|
||||
stringResource(R.string.settings_video_stabilization_mode_off)
|
||||
VideoStabilizationMode.EIS ->
|
||||
stringResource(R.string.settings_video_stabilization_mode_eis)
|
||||
VideoStabilizationMode.OIS ->
|
||||
stringResource(R.string.settings_video_stabilization_mode_ois)
|
||||
VideoStabilizationMode.ENHANCED ->
|
||||
stringResource(R.string.settings_video_stabilization_mode_enhanced)
|
||||
}
|
||||
}
|
||||
val selectedStabilizationModeLabel = stabilizationModeLabels
|
||||
.firstOrNull { it.first == userPreferences.videoStabilizationMode }
|
||||
?.second
|
||||
?: userPreferences.videoStabilizationMode.displayName
|
||||
SettingsSection(
|
||||
title = stringResource(R.string.settings_section_video),
|
||||
showTitle = false
|
||||
) {
|
||||
DropdownSettingItem(
|
||||
title = stringResource(R.string.settings_video_stabilization_default),
|
||||
description = stringResource(
|
||||
R.string.settings_video_stabilization_default_description
|
||||
),
|
||||
value = selectedStabilizationModeLabel,
|
||||
options = stabilizationModeLabels.map { it.second },
|
||||
isLoading = false,
|
||||
onExpanded = {},
|
||||
onOptionSelected = { selectedLabel ->
|
||||
stabilizationModeLabels.firstOrNull { it.second == selectedLabel }
|
||||
?.first
|
||||
?.let(viewModel::setVideoStabilizationMode)
|
||||
},
|
||||
)
|
||||
|
||||
HorizontalDivider(
|
||||
color = Color.White.copy(alpha = 0.1f),
|
||||
modifier = Modifier.padding(vertical = 8.dp)
|
||||
)
|
||||
|
||||
SwitchSettingItem(
|
||||
title = stringResource(R.string.settings_separate_video_lut),
|
||||
description = stringResource(R.string.settings_separate_video_lut_description),
|
||||
|
||||
@@ -22,6 +22,7 @@ object VideoCapabilitiesResolver {
|
||||
availableTonemapModes: IntArray = intArrayOf(),
|
||||
availableVideoStabilizationModes: IntArray = intArrayOf(),
|
||||
availableOpticalStabilizationModes: IntArray = intArrayOf(),
|
||||
algorithmicStabilizationSupported: Boolean = false,
|
||||
isFlashSupported: Boolean = false
|
||||
): VideoCapabilitySnapshot {
|
||||
val streamConfigMap = characteristics.get(CameraCharacteristics.SCALER_STREAM_CONFIGURATION_MAP)
|
||||
@@ -98,6 +99,17 @@ object VideoCapabilitiesResolver {
|
||||
if (availableOpticalStabilizationModes.contains(CaptureRequest.LENS_OPTICAL_STABILIZATION_MODE_ON)) {
|
||||
availableStabilizationModes.add(VideoStabilizationMode.OIS)
|
||||
}
|
||||
val enhancedCameraInputSize = cameraInputSizesByResolution[VideoResolutionPreset.FHD_1080P]
|
||||
val enhancedStabilizationAvailable = algorithmicStabilizationSupported &&
|
||||
enhancedCameraInputSize != null &&
|
||||
resolveAvailableFps(
|
||||
characteristics = characteristics,
|
||||
cameraInputSize = enhancedCameraInputSize,
|
||||
previewSize = previewSize
|
||||
).contains(VideoFpsPreset.FPS_30)
|
||||
if (enhancedStabilizationAvailable) {
|
||||
availableStabilizationModes.add(VideoStabilizationMode.ENHANCED)
|
||||
}
|
||||
|
||||
val resolvedStabilizationMode = if (availableStabilizationModes.contains(requestedConfig.stabilizationMode)) {
|
||||
requestedConfig.stabilizationMode
|
||||
|
||||
@@ -20,6 +20,7 @@ import android.view.Surface
|
||||
import androidx.core.app.ActivityCompat
|
||||
import com.hinnka.mycamera.lut.RealtimeVideoRenderer
|
||||
import com.hinnka.mycamera.lut.VideoColorEffectLayer
|
||||
import com.hinnka.mycamera.stabilization.RealtimeStabilizationCoordinator
|
||||
import com.hinnka.mycamera.utils.PLog
|
||||
import kotlinx.coroutines.CoroutineScope
|
||||
import kotlinx.coroutines.Dispatchers
|
||||
@@ -36,7 +37,8 @@ import java.nio.ByteBuffer
|
||||
import java.util.concurrent.Executors
|
||||
|
||||
class VideoRecorder(
|
||||
private val context: Context
|
||||
private val context: Context,
|
||||
private val stabilizationCoordinator: RealtimeStabilizationCoordinator? = null,
|
||||
) {
|
||||
|
||||
companion object {
|
||||
@@ -119,6 +121,7 @@ class VideoRecorder(
|
||||
private var requestedOutputSize = Size(1080, 1920)
|
||||
private var requestedCameraInputSize = Size(1920, 1080)
|
||||
private var requestedColorLayers: List<VideoColorEffectLayer> = emptyList()
|
||||
private var requestedEnhancedStabilization = false
|
||||
private var cameraInputStarted = false
|
||||
private var hlgCameraInput = false
|
||||
private var requestedCameraTimestampSource = CameraCharacteristics.SENSOR_INFO_TIMESTAMP_SOURCE_UNKNOWN
|
||||
@@ -184,6 +187,7 @@ class VideoRecorder(
|
||||
cameraTimestampSource: Int = CameraCharacteristics.SENSOR_INFO_TIMESTAMP_SOURCE_UNKNOWN,
|
||||
orientationHintDegrees: Int = 0,
|
||||
flipEncodedFrame: Boolean = false,
|
||||
enhancedStabilization: Boolean = false,
|
||||
recordingPath: VideoRecordingPath = VideoRecordingPath.DCIM_PHOTON,
|
||||
recordingTreeUri: String? = null,
|
||||
onError: ((String) -> Unit)? = null,
|
||||
@@ -205,6 +209,7 @@ class VideoRecorder(
|
||||
hlgCameraInput = hlgInput
|
||||
requestedCameraTimestampSource = cameraTimestampSource
|
||||
requestedFlipEncodedFrame = flipEncodedFrame
|
||||
requestedEnhancedStabilization = enhancedStabilization
|
||||
requestedRecordingPath = recordingPath
|
||||
requestedRecordingTreeUri = recordingTreeUri?.takeIf { it.isNotBlank() }
|
||||
outputDateTakenMs = System.currentTimeMillis()
|
||||
@@ -241,6 +246,7 @@ class VideoRecorder(
|
||||
"Video recording prepared: encoder=${requestedSize.width}x${requestedSize.height}, " +
|
||||
"output=${requestedOutputSize.width}x${requestedOutputSize.height} @ " +
|
||||
"${requestedFps}fps, orientationHint=$requestedOrientationHintDegrees, " +
|
||||
"enhancedStabilization=$requestedEnhancedStabilization, " +
|
||||
"input=dedicated-surface-texture, " +
|
||||
"cameraTimestampSource=$requestedCameraTimestampSource, " +
|
||||
"path=${requestedRecordingPath.name}, uri=${requestedRecordingTreeUri?.take(48)}"
|
||||
@@ -304,6 +310,7 @@ class VideoRecorder(
|
||||
activePauseStartTimeUs = nowUs
|
||||
}
|
||||
isPaused = true
|
||||
renderer?.pauseStabilization()
|
||||
PLog.d(TAG, "Video recording paused")
|
||||
}
|
||||
|
||||
@@ -317,6 +324,7 @@ class VideoRecorder(
|
||||
}
|
||||
activePauseStartTimeUs = UNSET_TIMESTAMP
|
||||
}
|
||||
renderer?.resumeStabilization()
|
||||
isPaused = false
|
||||
PLog.d(TAG, "Video recording resumed")
|
||||
}
|
||||
@@ -342,6 +350,8 @@ class VideoRecorder(
|
||||
mirrorVertically =
|
||||
requestedFlipEncodedFrame && requestedOrientationHintDegrees % 180 != 0,
|
||||
encoderColorConfig = encoderColorConfig,
|
||||
stabilizationCoordinator = stabilizationCoordinator,
|
||||
enhancedStabilizationEnabled = requestedEnhancedStabilization,
|
||||
)
|
||||
renderer = realtimeRenderer
|
||||
realtimeRenderer.initialize(
|
||||
|
||||
@@ -10,9 +10,10 @@ import kotlin.math.min
|
||||
import kotlin.math.roundToInt
|
||||
|
||||
enum class VideoStabilizationMode(val displayName: String) {
|
||||
OIS("OIS"),
|
||||
OFF("OFF"),
|
||||
EIS("EIS"),
|
||||
OFF("OFF")
|
||||
OIS("OIS"),
|
||||
ENHANCED("EIS+")
|
||||
}
|
||||
|
||||
enum class CaptureMode {
|
||||
|
||||
@@ -547,6 +547,9 @@ class CameraViewModel(application: Application) : AndroidViewModel(application)
|
||||
|
||||
val state: StateFlow<CameraState> = cameraController.state
|
||||
val livePhotoRecorder get() = cameraController.livePhotoRecorder
|
||||
val realtimeStabilizationCoordinator get() = cameraController.realtimeStabilizationCoordinator
|
||||
val isAlgorithmicStabilizationSupported: Boolean
|
||||
get() = cameraController.realtimeStabilizationCoordinator.isGyroscopeAvailable
|
||||
|
||||
// 照片保存完成事件
|
||||
private val _imageSavedEvent = MutableSharedFlow<Unit>()
|
||||
@@ -1745,6 +1748,10 @@ class CameraViewModel(application: Application) : AndroidViewModel(application)
|
||||
val videoWhiteBalanceLockEnabled: StateFlow<Boolean> = userPreferencesRepository.userPreferences
|
||||
.map { it.videoWhiteBalanceLockEnabled }
|
||||
.stateIn(viewModelScope, SharingStarted.Eagerly, false)
|
||||
val photoPreviewStabilizationEnabled: StateFlow<Boolean> =
|
||||
userPreferencesRepository.userPreferences
|
||||
.map { it.photoPreviewStabilizationEnabled }
|
||||
.stateIn(viewModelScope, SharingStarted.Eagerly, false)
|
||||
val videoAudioInputOptions: StateFlow<List<VideoAudioInputOption>> = videoAudioInputManager.availableInputs
|
||||
|
||||
val phantomButtonHidden: StateFlow<Boolean> = userPreferencesRepository.userPreferences
|
||||
@@ -2174,6 +2181,9 @@ class CameraViewModel(application: Application) : AndroidViewModel(application)
|
||||
cameraController.setVideoAudioInputId(it.videoAudioInputId)
|
||||
cameraController.setVideoRecordingPath(it.videoRecordingPath, it.videoRecordingTreeUri)
|
||||
cameraController.setVideoStabilizationMode(it.videoStabilizationMode)
|
||||
cameraController.setPhotoPreviewStabilizationEnabled(
|
||||
it.photoPreviewStabilizationEnabled
|
||||
)
|
||||
cameraController.setVideoTorchEnabled(it.videoTorchEnabled)
|
||||
cameraController.setVideoLensLockEnabled(it.videoLensLockEnabled)
|
||||
cameraController.setVideoWhiteBalanceLockEnabled(it.videoWhiteBalanceLockEnabled)
|
||||
@@ -3626,17 +3636,27 @@ class CameraViewModel(application: Application) : AndroidViewModel(application)
|
||||
|
||||
fun setVideoResolution(resolution: VideoResolutionPreset) {
|
||||
cameraController.setVideoResolution(resolution)
|
||||
val resolvedConfig = state.value.videoConfig
|
||||
reopenCamera()
|
||||
viewModelScope.launch {
|
||||
userPreferencesRepository.saveVideoResolution(resolution)
|
||||
userPreferencesRepository.saveVideoStabilizationConfig(
|
||||
mode = resolvedConfig.stabilizationMode,
|
||||
resolution = resolvedConfig.resolution,
|
||||
fps = resolvedConfig.fps,
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
fun setVideoFps(fps: VideoFpsPreset) {
|
||||
cameraController.setVideoFps(fps)
|
||||
val resolvedConfig = state.value.videoConfig
|
||||
reopenCamera()
|
||||
viewModelScope.launch {
|
||||
userPreferencesRepository.saveVideoFps(fps)
|
||||
userPreferencesRepository.saveVideoStabilizationConfig(
|
||||
mode = resolvedConfig.stabilizationMode,
|
||||
resolution = resolvedConfig.resolution,
|
||||
fps = resolvedConfig.fps,
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -3649,9 +3669,28 @@ 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()
|
||||
}
|
||||
viewModelScope.launch {
|
||||
userPreferencesRepository.saveVideoStabilizationMode(mode)
|
||||
userPreferencesRepository.saveVideoStabilizationConfig(
|
||||
mode = resolvedConfig.stabilizationMode,
|
||||
resolution = resolvedConfig.resolution,
|
||||
fps = resolvedConfig.fps,
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
fun setPhotoPreviewStabilizationEnabled(enabled: Boolean) {
|
||||
cameraController.setPhotoPreviewStabilizationEnabled(enabled)
|
||||
viewModelScope.launch {
|
||||
userPreferencesRepository.savePhotoPreviewStabilizationEnabled(enabled)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -3710,10 +3749,7 @@ class CameraViewModel(application: Application) : AndroidViewModel(application)
|
||||
val availableModes = state.value.videoCapabilities.availableStabilizationModes
|
||||
if (availableModes.isEmpty()) return
|
||||
val nextMode = availableModes[(availableModes.indexOf(currentMode) + 1) % availableModes.size]
|
||||
cameraController.setVideoStabilizationMode(nextMode)
|
||||
viewModelScope.launch {
|
||||
userPreferencesRepository.saveVideoStabilizationMode(nextMode)
|
||||
}
|
||||
setVideoStabilizationMode(nextMode)
|
||||
}
|
||||
|
||||
fun setVideoTorchEnabled(enabled: Boolean) {
|
||||
|
||||
@@ -192,6 +192,12 @@
|
||||
<string name="settings_video_lut_description">目前選擇:%1$s</string>
|
||||
<string name="settings_video_lock_lens">鎖定鏡頭</string>
|
||||
<string name="settings_video_lock_lens_description">影片錄製過程中變焦不切換鏡頭。</string>
|
||||
<string name="settings_video_stabilization_default">預設影片防震模式</string>
|
||||
<string name="settings_video_stabilization_default_description">選擇進入影片模式時使用的防震方式。EIS+ 在後置相機使用陀螺儀與滾動快門校正,並會將錄影規格切換為 1080p/30 fps。</string>
|
||||
<string name="settings_video_stabilization_mode_off">關閉</string>
|
||||
<string name="settings_video_stabilization_mode_eis">電子防震 (EIS)</string>
|
||||
<string name="settings_video_stabilization_mode_ois">光學防震 (OIS)</string>
|
||||
<string name="settings_video_stabilization_mode_enhanced">增強防震 (EIS+)</string>
|
||||
<string name="settings_video_lock_white_balance">鎖定白平衡</string>
|
||||
<string name="settings_video_lock_white_balance_description">影片錄製過程中鎖定白平衡。</string>
|
||||
<string name="settings_section_quality_perf">畫質與性能</string>
|
||||
@@ -210,6 +216,8 @@
|
||||
<string name="settings_level_description">在拍攝時顯示水平儀,幫助保持畫面水平</string>
|
||||
<string name="settings_focus_peaking">峰值對焦</string>
|
||||
<string name="settings_focus_peaking_description">手動對焦時顯示峰值對焦高亮</string>
|
||||
<string name="settings_photo_preview_stabilization">照片預覽防震</string>
|
||||
<string name="settings_photo_preview_stabilization_description">使用陀螺儀穩定照片取景畫面,不改變最終照片;僅支援後置相機。</string>
|
||||
<string name="settings_grid_lines">網格線顯示</string>
|
||||
<string name="settings_grid_description">在拍攝時顯示網格線,輔助構圖</string>
|
||||
<string name="settings_use_jpg_max">多幀降噪</string>
|
||||
|
||||
@@ -192,6 +192,12 @@
|
||||
<string name="settings_video_lut_description">当前选择:%1$s</string>
|
||||
<string name="settings_video_lock_lens">锁定镜头</string>
|
||||
<string name="settings_video_lock_lens_description">视频录制过程中变焦不切换镜头。</string>
|
||||
<string name="settings_video_stabilization_default">默认视频防抖模式</string>
|
||||
<string name="settings_video_stabilization_default_description">选择进入视频模式时使用的防抖方式。EIS+ 在后摄使用陀螺仪和滚动快门校正,并会将录像规格切换为 1080p/30 fps。</string>
|
||||
<string name="settings_video_stabilization_mode_off">关闭</string>
|
||||
<string name="settings_video_stabilization_mode_eis">电子防抖 (EIS)</string>
|
||||
<string name="settings_video_stabilization_mode_ois">光学防抖 (OIS)</string>
|
||||
<string name="settings_video_stabilization_mode_enhanced">增强防抖 (EIS+)</string>
|
||||
<string name="settings_video_lock_white_balance">锁定白平衡</string>
|
||||
<string name="settings_video_lock_white_balance_description">视频录制过程中锁定白平衡。</string>
|
||||
<string name="settings_section_quality_perf">画质与性能</string>
|
||||
@@ -210,6 +216,8 @@
|
||||
<string name="settings_level_description">在拍摄时显示水平仪,帮助保持画面水平</string>
|
||||
<string name="settings_focus_peaking">峰值对焦</string>
|
||||
<string name="settings_focus_peaking_description">手动对焦时显示峰值对焦高亮</string>
|
||||
<string name="settings_photo_preview_stabilization">照片预览防抖</string>
|
||||
<string name="settings_photo_preview_stabilization_description">使用陀螺仪稳定照片取景画面,不改变最终照片;仅支持后置相机。</string>
|
||||
<string name="settings_grid_lines">网格线显示</string>
|
||||
<string name="settings_grid_description">在拍摄时显示网格线,辅助构图</string>
|
||||
<string name="settings_use_jpg_max">多帧降噪</string>
|
||||
|
||||
@@ -192,6 +192,12 @@
|
||||
<string name="settings_video_lut_description">目前選擇:%1$s</string>
|
||||
<string name="settings_video_lock_lens">鎖定鏡頭</string>
|
||||
<string name="settings_video_lock_lens_description">影片錄製過程中變焦不切換鏡頭。</string>
|
||||
<string name="settings_video_stabilization_default">預設影片防震模式</string>
|
||||
<string name="settings_video_stabilization_default_description">選擇進入影片模式時使用的防震方式。EIS+ 在後置相機使用陀螺儀與滾動快門校正,並會將錄影規格切換為 1080p/30 fps。</string>
|
||||
<string name="settings_video_stabilization_mode_off">關閉</string>
|
||||
<string name="settings_video_stabilization_mode_eis">電子防震 (EIS)</string>
|
||||
<string name="settings_video_stabilization_mode_ois">光學防震 (OIS)</string>
|
||||
<string name="settings_video_stabilization_mode_enhanced">增強防震 (EIS+)</string>
|
||||
<string name="settings_video_lock_white_balance">鎖定白平衡</string>
|
||||
<string name="settings_video_lock_white_balance_description">影片錄製過程中鎖定白平衡。</string>
|
||||
<string name="settings_section_quality_perf">畫質與性能</string>
|
||||
@@ -210,6 +216,8 @@
|
||||
<string name="settings_level_description">在拍攝時顯示水平儀,幫助保持畫面水平</string>
|
||||
<string name="settings_focus_peaking">峰值對焦</string>
|
||||
<string name="settings_focus_peaking_description">手動對焦時顯示峰值對焦高亮</string>
|
||||
<string name="settings_photo_preview_stabilization">照片預覽防震</string>
|
||||
<string name="settings_photo_preview_stabilization_description">使用陀螺儀穩定照片取景畫面,不改變最終照片;僅支援後置相機。</string>
|
||||
<string name="settings_grid_lines">網格線顯示</string>
|
||||
<string name="settings_grid_description">在拍攝時顯示網格線,輔助構圖</string>
|
||||
<string name="settings_use_jpg_max">多幀降噪</string>
|
||||
|
||||
@@ -192,6 +192,12 @@
|
||||
<string name="settings_video_lut_description">目前選擇:%1$s</string>
|
||||
<string name="settings_video_lock_lens">鎖定鏡頭</string>
|
||||
<string name="settings_video_lock_lens_description">影片錄製過程中變焦不切換鏡頭。</string>
|
||||
<string name="settings_video_stabilization_default">預設影片防震模式</string>
|
||||
<string name="settings_video_stabilization_default_description">選擇進入影片模式時使用的防震方式。EIS+ 在後置相機使用陀螺儀與滾動快門校正,並會將錄影規格切換為 1080p/30 fps。</string>
|
||||
<string name="settings_video_stabilization_mode_off">關閉</string>
|
||||
<string name="settings_video_stabilization_mode_eis">電子防震 (EIS)</string>
|
||||
<string name="settings_video_stabilization_mode_ois">光學防震 (OIS)</string>
|
||||
<string name="settings_video_stabilization_mode_enhanced">增強防震 (EIS+)</string>
|
||||
<string name="settings_video_lock_white_balance">鎖定白平衡</string>
|
||||
<string name="settings_video_lock_white_balance_description">影片錄製過程中鎖定白平衡。</string>
|
||||
<string name="settings_section_quality_perf">畫質與性能</string>
|
||||
@@ -210,6 +216,8 @@
|
||||
<string name="settings_level_description">在拍攝時顯示水平儀,幫助保持畫面水平</string>
|
||||
<string name="settings_focus_peaking">峰值對焦</string>
|
||||
<string name="settings_focus_peaking_description">手動對焦時顯示峰值對焦高亮</string>
|
||||
<string name="settings_photo_preview_stabilization">照片預覽防震</string>
|
||||
<string name="settings_photo_preview_stabilization_description">使用陀螺儀穩定照片取景畫面,不改變最終照片;僅支援後置相機。</string>
|
||||
<string name="settings_grid_lines">網格線顯示</string>
|
||||
<string name="settings_grid_description">在拍攝時顯示網格線,輔助構圖</string>
|
||||
<string name="settings_use_jpg_max">多幀降噪</string>
|
||||
|
||||
@@ -196,6 +196,12 @@
|
||||
<string name="settings_video_lut_description">Selected LUT: %1$s</string>
|
||||
<string name="settings_video_lock_lens">Lock Lens</string>
|
||||
<string name="settings_video_lock_lens_description">Prevent zooming from switching cameras while video is recording.</string>
|
||||
<string name="settings_video_stabilization_default">Default Video Stabilization</string>
|
||||
<string name="settings_video_stabilization_default_description">Choose the stabilization mode used when video mode starts. EIS+ uses gyro-driven rolling-shutter correction on rear cameras and switches recording to 1080p/30 fps.</string>
|
||||
<string name="settings_video_stabilization_mode_off">Off</string>
|
||||
<string name="settings_video_stabilization_mode_eis">Electronic (EIS)</string>
|
||||
<string name="settings_video_stabilization_mode_ois">Optical (OIS)</string>
|
||||
<string name="settings_video_stabilization_mode_enhanced">Enhanced (EIS+)</string>
|
||||
<string name="settings_video_lock_white_balance">Lock White Balance</string>
|
||||
<string name="settings_video_lock_white_balance_description">Keep automatic white balance fixed while video is recording.</string>
|
||||
<string name="settings_section_quality_perf">Quality & Performance</string>
|
||||
@@ -214,6 +220,8 @@
|
||||
<string name="settings_level_description">Show horizontal level indicator while shooting</string>
|
||||
<string name="settings_focus_peaking">Focus Peaking</string>
|
||||
<string name="settings_focus_peaking_description">Show focus peaking highlights during manual focus</string>
|
||||
<string name="settings_photo_preview_stabilization">Photo Preview Stabilization</string>
|
||||
<string name="settings_photo_preview_stabilization_description">Stabilize the photo viewfinder using gyro motion. The saved photo is unchanged; rear cameras only.</string>
|
||||
<string name="settings_grid_lines">Grid Lines</string>
|
||||
<string name="settings_grid_description">Show grid lines for composition</string>
|
||||
<string name="settings_use_jpg_max">Multi-frame denoise</string>
|
||||
|
||||
Reference in new issue
Block a user