From 8c1f5248c156fed8b1e27f3558f61c441fa26d85 Mon Sep 17 00:00:00 2001 From: zhoubinjia Date: Thu, 3 Sep 2026 13:19:52 +0800 Subject: [PATCH] feat: external lens stabilization --- .../mycamera/camera/Camera2Controller.kt | 6 + .../data/UserPreferencesRepository.kt | 30 ++ .../ExternalLensStabilizationConfig.kt | 48 +++ .../RealtimeStabilizationCoordinator.kt | 79 +++- .../mycamera/ui/settings/SettingsScreen.kt | 347 ++++++++++++++++++ .../mycamera/viewmodel/CameraViewModel.kt | 15 + app/src/main/res/values-b+zh+Hant/strings.xml | 14 + app/src/main/res/values-zh-rCN/strings.xml | 14 + app/src/main/res/values-zh-rHK/strings.xml | 14 + app/src/main/res/values-zh-rTW/strings.xml | 14 + app/src/main/res/values/strings.xml | 14 + 11 files changed, 585 insertions(+), 10 deletions(-) create mode 100644 app/src/main/java/com/hinnka/mycamera/stabilization/ExternalLensStabilizationConfig.kt diff --git a/app/src/main/java/com/hinnka/mycamera/camera/Camera2Controller.kt b/app/src/main/java/com/hinnka/mycamera/camera/Camera2Controller.kt index e4760e97..4e70321c 100644 --- a/app/src/main/java/com/hinnka/mycamera/camera/Camera2Controller.kt +++ b/app/src/main/java/com/hinnka/mycamera/camera/Camera2Controller.kt @@ -38,6 +38,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.ExternalLensStabilizationConfig import com.hinnka.mycamera.stabilization.RealtimeStabilizationCoordinator import com.hinnka.mycamera.stabilization.normalizeStabilizationLookahead import com.hinnka.mycamera.stabilization.normalizeStabilizationStrength @@ -2143,6 +2144,7 @@ class Camera2Controller(private val context: Context) { } } realtimeStabilizationCoordinator.configureCamera( + cameraId = capabilityCameraId, characteristics = capabilityCharacteristics, timingCharacteristics = openCharacteristics, ) @@ -6360,6 +6362,10 @@ class Camera2Controller(private val context: Context) { ) } + fun setExternalLensStabilizationConfig(config: ExternalLensStabilizationConfig) { + realtimeStabilizationCoordinator.setExternalLensStabilizationConfig(config) + } + fun setPhotoPreviewStabilizationEnabled(enabled: Boolean) { if (enabled && cameraDevice != null && !realtimeStabilizationCoordinator.isCurrentCameraSupported diff --git a/app/src/main/java/com/hinnka/mycamera/data/UserPreferencesRepository.kt b/app/src/main/java/com/hinnka/mycamera/data/UserPreferencesRepository.kt index e97027ee..b9a07f17 100644 --- a/app/src/main/java/com/hinnka/mycamera/data/UserPreferencesRepository.kt +++ b/app/src/main/java/com/hinnka/mycamera/data/UserPreferencesRepository.kt @@ -39,6 +39,7 @@ import com.hinnka.mycamera.raw.RawSharpeningDefaults import com.hinnka.mycamera.screencapture.PhantomPipCrop import com.hinnka.mycamera.stabilization.DEFAULT_VIDEO_STABILIZATION_LOOKAHEAD import com.hinnka.mycamera.stabilization.DEFAULT_VIDEO_STABILIZATION_STRENGTH +import com.hinnka.mycamera.stabilization.ExternalLensStabilizationConfig import com.hinnka.mycamera.stabilization.normalizeStabilizationLookahead import com.hinnka.mycamera.stabilization.normalizeStabilizationStrength import kotlinx.coroutines.flow.Flow @@ -204,6 +205,8 @@ data class UserPreferences( val videoStabilizationMode: VideoStabilizationMode = VideoStabilizationMode.OIS, val videoEnhancedStabilizationStrength: Float = DEFAULT_VIDEO_STABILIZATION_STRENGTH, val videoEnhancedStabilizationLookahead: Int = DEFAULT_VIDEO_STABILIZATION_LOOKAHEAD, + val externalLensStabilizationConfig: ExternalLensStabilizationConfig = + ExternalLensStabilizationConfig.Disabled, val photoPreviewStabilizationEnabled: Boolean = false, val videoTorchEnabled: Boolean = false, val videoLensLockEnabled: Boolean = false, @@ -453,6 +456,10 @@ class UserPreferencesRepository(private val context: Context) { floatPreferencesKey("video_enhanced_stabilization_strength") private val VIDEO_ENHANCED_STABILIZATION_LOOKAHEAD = intPreferencesKey("video_enhanced_stabilization_lookahead") + private val EXTERNAL_LENS_STABILIZATION_CAMERA_ID = + stringPreferencesKey("external_lens_stabilization_camera_id") + private val EXTERNAL_LENS_STABILIZATION_MAGNIFICATION = + floatPreferencesKey("external_lens_stabilization_magnification") private val PHOTO_PREVIEW_STABILIZATION_ENABLED = booleanPreferencesKey("photo_preview_stabilization_enabled") private val VIDEO_TORCH_ENABLED = booleanPreferencesKey("video_torch_enabled") @@ -743,6 +750,12 @@ class UserPreferencesRepository(private val context: Context) { preferences[VIDEO_ENHANCED_STABILIZATION_LOOKAHEAD] ?: DEFAULT_VIDEO_STABILIZATION_LOOKAHEAD ), + externalLensStabilizationConfig = ExternalLensStabilizationConfig( + physicalCameraId = preferences[EXTERNAL_LENS_STABILIZATION_CAMERA_ID] + .orEmpty(), + magnification = preferences[EXTERNAL_LENS_STABILIZATION_MAGNIFICATION] + ?: ExternalLensStabilizationConfig.Disabled.magnification, + ).normalized(), photoPreviewStabilizationEnabled = preferences[PHOTO_PREVIEW_STABILIZATION_ENABLED] ?: false, videoTorchEnabled = preferences[VIDEO_TORCH_ENABLED] ?: false, @@ -1541,6 +1554,23 @@ class UserPreferencesRepository(private val context: Context) { } } + suspend fun saveExternalLensStabilizationConfig( + config: ExternalLensStabilizationConfig, + ) { + val normalized = config.normalized() + context.dataStore.edit { preferences -> + if (normalized.isEnabled) { + preferences[EXTERNAL_LENS_STABILIZATION_CAMERA_ID] = + normalized.physicalCameraId + preferences[EXTERNAL_LENS_STABILIZATION_MAGNIFICATION] = + normalized.magnification + } else { + preferences.remove(EXTERNAL_LENS_STABILIZATION_CAMERA_ID) + preferences.remove(EXTERNAL_LENS_STABILIZATION_MAGNIFICATION) + } + } + } + suspend fun savePhotoPreviewStabilizationEnabled(enabled: Boolean) { context.dataStore.edit { preferences -> preferences[PHOTO_PREVIEW_STABILIZATION_ENABLED] = enabled diff --git a/app/src/main/java/com/hinnka/mycamera/stabilization/ExternalLensStabilizationConfig.kt b/app/src/main/java/com/hinnka/mycamera/stabilization/ExternalLensStabilizationConfig.kt new file mode 100644 index 00000000..cacc3662 --- /dev/null +++ b/app/src/main/java/com/hinnka/mycamera/stabilization/ExternalLensStabilizationConfig.kt @@ -0,0 +1,48 @@ +package com.hinnka.mycamera.stabilization + +const val MIN_EXTERNAL_LENS_MAGNIFICATION = 1f +const val MAX_EXTERNAL_LENS_MAGNIFICATION = 4f + +/** Optical calibration applied only while a teleconverter covers [physicalCameraId]. */ +data class ExternalLensStabilizationConfig( + val physicalCameraId: String = "", + val magnification: Float = MIN_EXTERNAL_LENS_MAGNIFICATION, +) { + val isEnabled: Boolean + get() = physicalCameraId.isNotBlank() && + magnification.isFinite() && magnification > MIN_EXTERNAL_LENS_MAGNIFICATION + + fun normalized(): ExternalLensStabilizationConfig { + val normalizedCameraId = physicalCameraId.trim() + val normalizedMagnification = if (magnification.isFinite()) { + magnification.coerceIn( + MIN_EXTERNAL_LENS_MAGNIFICATION, + MAX_EXTERNAL_LENS_MAGNIFICATION, + ) + } else { + MIN_EXTERNAL_LENS_MAGNIFICATION + } + return if (normalizedCameraId.isEmpty() || + normalizedMagnification <= MIN_EXTERNAL_LENS_MAGNIFICATION + ) { + Disabled + } else { + ExternalLensStabilizationConfig( + physicalCameraId = normalizedCameraId, + magnification = normalizedMagnification, + ) + } + } + + fun magnificationFor(cameraId: String?): Float = if ( + isEnabled && cameraId == physicalCameraId + ) { + magnification + } else { + MIN_EXTERNAL_LENS_MAGNIFICATION + } + + companion object { + val Disabled = ExternalLensStabilizationConfig() + } +} diff --git a/app/src/main/java/com/hinnka/mycamera/stabilization/RealtimeStabilizationCoordinator.kt b/app/src/main/java/com/hinnka/mycamera/stabilization/RealtimeStabilizationCoordinator.kt index 96e8dfea..cc989022 100644 --- a/app/src/main/java/com/hinnka/mycamera/stabilization/RealtimeStabilizationCoordinator.kt +++ b/app/src/main/java/com/hinnka/mycamera/stabilization/RealtimeStabilizationCoordinator.kt @@ -83,6 +83,7 @@ class StabilizationImage internal constructor( } private data class CameraCalibration( + val cameraId: String, val activeArray: Rect, val preCorrectionActiveArray: Rect, val physicalSizeMm: SizeF, @@ -148,6 +149,26 @@ private fun isPlausibleDynamicLensIntrinsics( kotlin.math.abs(values[4] - nominal[4]) <= preWidth * 0.25f } +private fun magnifyDynamicLensIntrinsics( + values: FloatArray, + nominal: FloatArray?, + magnification: Float, +): FloatArray { + if (magnification <= MIN_EXTERNAL_LENS_MAGNIFICATION || + nominal == null || nominal.size != 5 || values.size != 5 + ) { + return values + } + return values.copyOf().also { adjusted -> + // The native engine applies dynamic fx/fy as ratios against the nominal calibration; + // the frame's effective focal length already carries the external magnification. Keep + // those ratios unchanged and magnify only the OIS-induced optical-center/skew deltas. + adjusted[2] = nominal[2] + (values[2] - nominal[2]) * magnification + adjusted[3] = nominal[3] + (values[3] - nominal[3]) * magnification + adjusted[4] = nominal[4] + (values[4] - nominal[4]) * magnification + } +} + private data class SequencedNativeResult( val sequence: Long, val result: MgcEisNativeEngine.FrameResult, @@ -201,6 +222,9 @@ class RealtimeStabilizationCoordinator(context: Context) { @Volatile private var calibration: CameraCalibration? = null + @Volatile + private var externalLensStabilizationConfig = ExternalLensStabilizationConfig.Disabled + @Volatile private var gyroSourceReady = false @@ -247,6 +271,22 @@ class RealtimeStabilizationCoordinator(context: Context) { val isPoseSourceReady: Boolean get() = gyroSourceReady + fun setExternalLensStabilizationConfig(config: ExternalLensStabilizationConfig) { + val normalized = config.normalized() + if (externalLensStabilizationConfig == normalized) return + externalLensStabilizationConfig = normalized + PLog.i( + TAG, + if (normalized.isEnabled) { + "MGC external lens stabilization enabled: " + + "camera=${normalized.physicalCameraId}, " + + "magnification=${normalized.magnification}x" + } else { + "MGC external lens stabilization disabled" + }, + ) + } + val isCurrentCameraSupported: Boolean get() { val current = calibration @@ -312,6 +352,7 @@ class RealtimeStabilizationCoordinator(context: Context) { } fun configureCamera( + cameraId: String, characteristics: CameraCharacteristics, timingCharacteristics: CameraCharacteristics = characteristics, ) { @@ -350,6 +391,7 @@ class RealtimeStabilizationCoordinator(context: Context) { nominalLensIntrinsics != null && resultKeyNames.contains(CaptureResult.STATISTICS_LENS_INTRINSICS_SAMPLES.name) calibration = CameraCalibration( + cameraId = cameraId, activeArray = Rect(activeArray), preCorrectionActiveArray = Rect( characteristics.get( @@ -372,11 +414,13 @@ class RealtimeStabilizationCoordinator(context: Context) { ) PLog.i( TAG, - "MGC camera calibration: active=$activeArray, physical=$physicalSize, " + + "MGC camera calibration: camera=$cameraId, active=$activeArray, physical=$physicalSize, " + "orientation=${calibration?.sensorOrientationDegrees}, " + "facing=${calibration?.lensFacing}, timestampSource=${calibration?.timestampSource}, " + "oisSamples=$supportsOisSamples, " + - "lensIntrinsicsSamples=$supportsLensIntrinsicsSamples", + "lensIntrinsicsSamples=$supportsLensIntrinsicsSamples, " + + "externalMagnification=" + + externalLensStabilizationConfig.magnificationFor(cameraId), ) } @@ -385,16 +429,22 @@ class RealtimeStabilizationCoordinator(context: Context) { request: CaptureRequest? = null, outputPhysicalCameraId: String? = null, ) { - val physicalResult = (result as? TotalCaptureResult)?.let { totalResult -> - val physicalId = outputPhysicalCameraId - ?: totalResult.get(CaptureResult.LOGICAL_MULTI_CAMERA_ACTIVE_PHYSICAL_ID) - physicalId?.let(totalResult.physicalCameraResults::get) + val totalResult = result as? TotalCaptureResult + val resultPhysicalCameraId = outputPhysicalCameraId + ?: totalResult?.get(CaptureResult.LOGICAL_MULTI_CAMERA_ACTIVE_PHYSICAL_ID) + val physicalResult = resultPhysicalCameraId?.let { + totalResult?.physicalCameraResults?.get(it) } fun value(key: CaptureResult.Key): T? = physicalResult?.get(key) ?: result.get(key) val currentCalibration = calibration ?: return + val stabilizationCameraId = resultPhysicalCameraId ?: currentCalibration.cameraId + val externalMagnification = externalLensStabilizationConfig + .magnificationFor(stabilizationCameraId) val timestampNs = value(CaptureResult.SENSOR_TIMESTAMP) ?: return + val reportedFocalLengthMm = value(CaptureResult.LENS_FOCAL_LENGTH) + ?.coerceAtLeast(0f) ?: 0f val metadata = FrameMetadata( timestampNs = timestampNs, exposureTimeNs = value(CaptureResult.SENSOR_EXPOSURE_TIME)?.coerceAtLeast(0L) ?: 0L, @@ -402,7 +452,7 @@ class RealtimeStabilizationCoordinator(context: Context) { ?.coerceAtLeast(0L) ?: 0L, cropRegion = value(CaptureResult.SCALER_CROP_REGION)?.let(::Rect) ?: Rect(currentCalibration.activeArray), - focalLengthMm = value(CaptureResult.LENS_FOCAL_LENGTH)?.coerceAtLeast(0f) ?: 0f, + focalLengthMm = reportedFocalLengthMm * externalMagnification, ) val oisSamples = value(CaptureResult.STATISTICS_OIS_SAMPLES).orEmpty() val dynamicLensIntrinsics = if ( @@ -442,7 +492,11 @@ class RealtimeStabilizationCoordinator(context: Context) { return@forEach } if (nativeEngine.processLensIntrinsics( - intrinsics = sample.values, + intrinsics = magnifyDynamicLensIntrinsics( + values = sample.values, + nominal = currentCalibration.nominalLensIntrinsics, + magnification = externalMagnification, + ), timestampNs = sample.timestampNs, cameraType = 0, ) @@ -467,8 +521,8 @@ class RealtimeStabilizationCoordinator(context: Context) { return@forEach } if (nativeEngine.processLensOffset( - xShiftPixels = sample.xshift, - yShiftPixels = sample.yshift, + xShiftPixels = sample.xshift * externalMagnification, + yShiftPixels = sample.yshift * externalMagnification, timestampNs = sample.timestamp, cameraType = 0, ) @@ -487,6 +541,10 @@ class RealtimeStabilizationCoordinator(context: Context) { PLog.i( TAG, "MGC CaptureResult #$captureResultCount: ts=$timestampNs, " + + "camera=$stabilizationCameraId, " + + "reportedFocal=$reportedFocalLengthMm, " + + "externalMagnification=$externalMagnification, " + + "effectiveFocal=${metadata.focalLengthMm}, " + "requestedVideoStabilization=" + requestedVideoStabilization + ", requestedOpticalStabilization=" + @@ -1117,6 +1175,7 @@ internal fun remapMgcGyroForTest( frontFacing: Boolean, ): Triple { val calibration = CameraCalibration( + cameraId = "test", activeArray = Rect(0, 0, 1, 1), preCorrectionActiveArray = Rect(0, 0, 1, 1), physicalSizeMm = SizeF(1f, 1f), diff --git a/app/src/main/java/com/hinnka/mycamera/ui/settings/SettingsScreen.kt b/app/src/main/java/com/hinnka/mycamera/ui/settings/SettingsScreen.kt index 0a65ea9f..54b5c566 100644 --- a/app/src/main/java/com/hinnka/mycamera/ui/settings/SettingsScreen.kt +++ b/app/src/main/java/com/hinnka/mycamera/ui/settings/SettingsScreen.kt @@ -142,8 +142,11 @@ import com.hinnka.mycamera.raw.HncsProfileManager import com.hinnka.mycamera.raw.SpectralFilmSelection import com.hinnka.mycamera.stabilization.DEFAULT_VIDEO_STABILIZATION_LOOKAHEAD import com.hinnka.mycamera.stabilization.DEFAULT_VIDEO_STABILIZATION_STRENGTH +import com.hinnka.mycamera.stabilization.ExternalLensStabilizationConfig import com.hinnka.mycamera.stabilization.MIN_VIDEO_STABILIZATION_LOOKAHEAD import com.hinnka.mycamera.stabilization.MAX_VIDEO_STABILIZATION_LOOKAHEAD +import com.hinnka.mycamera.stabilization.MAX_EXTERNAL_LENS_MAGNIFICATION +import com.hinnka.mycamera.stabilization.MIN_EXTERNAL_LENS_MAGNIFICATION import com.hinnka.mycamera.stabilization.normalizeStabilizationLookahead import com.hinnka.mycamera.stabilization.normalizeStabilizationStrength import com.hinnka.mycamera.ui.camera.LutEditBottomSheet @@ -165,6 +168,7 @@ 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.Locale import java.util.UUID import kotlin.math.roundToInt import com.hinnka.mycamera.ui.icons.AppIcons @@ -436,6 +440,7 @@ fun SettingsScreen( } var showAspectRatioDialog by remember { mutableStateOf(false) } var showAddIszLensDialog by remember { mutableStateOf(false) } + var showExternalLensStabilizationDialog by remember { mutableStateOf(false) } var showCustomVendorKeysDialog by remember { mutableStateOf(false) } var backupOperation by remember { mutableStateOf(null) } @@ -1660,6 +1665,43 @@ fun SettingsScreen( modifier = Modifier.padding(vertical = 8.dp) ) + val externalLensConfig = + userPreferences.externalLensStabilizationConfig + val externalLensOptions = remember(state.availableCameras) { + externalLensStabilizationOptions(state.availableCameras) + } + val configuredExternalLens = externalLensOptions.firstOrNull { + it.cameraId == externalLensConfig.physicalCameraId + } + val externalLensSummary = if (externalLensConfig.isEnabled) { + stringResource( + R.string.settings_external_lens_stabilization_configured, + configuredExternalLens?.let { + externalLensStabilizationLabel(it) + } ?: externalLensConfig.physicalCameraId, + IszLensConfig.displayRatioLabel( + externalLensConfig.magnification + ), + ) + } else { + stringResource( + R.string.settings_external_lens_stabilization_description + ) + } + NavigationSettingItem( + title = stringResource( + R.string.settings_external_lens_stabilization + ), + description = externalLensSummary, + enabled = viewModel.isAlgorithmicStabilizationSupported, + onClick = { showExternalLensStabilizationDialog = true }, + ) + + 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), @@ -2771,6 +2813,18 @@ fun SettingsScreen( ) } + if (showExternalLensStabilizationDialog) { + ExternalLensStabilizationDialog( + availableCameras = state.availableCameras, + currentConfig = userPreferences.externalLensStabilizationConfig, + onApply = { config -> + viewModel.setExternalLensStabilizationConfig(config) + showExternalLensStabilizationDialog = false + }, + onDismiss = { showExternalLensStabilizationDialog = false }, + ) + } + if (showCustomVendorKeysDialog) { CustomVendorKeysDialog( availableCameras = state.availableCameras, @@ -4438,6 +4492,299 @@ private fun customVendorKeyTextFieldColors() = cursorColor = Color(0xFFE5A324) ) +/** + * Physical camera selected for external-lens stabilization calibration. + */ +private data class ExternalLensStabilizationOption( + val cameraId: String, + val lensFacing: Int, + val focalLength35mmEquivalent: Float, +) + +private fun externalLensStabilizationOptions( + availableCameras: List, +): List = buildList { + availableCameras + .filter { + !it.isVirtualIszLens && + it.lensFacing == android.hardware.camera2.CameraCharacteristics.LENS_FACING_BACK + } + .forEach { camera -> + val fixedPhysicalCameraId = camera.outputPhysicalCameraId + when { + fixedPhysicalCameraId != null -> { + val physical = camera.physicalCameras.firstOrNull { + it.cameraId == fixedPhysicalCameraId + } + add( + ExternalLensStabilizationOption( + cameraId = fixedPhysicalCameraId, + lensFacing = camera.lensFacing, + focalLength35mmEquivalent = + physical?.focalLength35mmEquivalent + ?.takeIf { it > 0f } + ?: camera.focalLength35mmEquivalent, + ) + ) + } + + camera.physicalCameras.isNotEmpty() -> { + camera.physicalCameras.forEach { physical -> + add( + ExternalLensStabilizationOption( + cameraId = physical.cameraId, + lensFacing = camera.lensFacing, + focalLength35mmEquivalent = + physical.focalLength35mmEquivalent, + ) + ) + } + } + + else -> add( + ExternalLensStabilizationOption( + cameraId = camera.cameraId, + lensFacing = camera.lensFacing, + focalLength35mmEquivalent = camera.focalLength35mmEquivalent, + ) + ) + } + } +}.filter { it.cameraId.isNotBlank() } + .distinctBy { it.cameraId } + .sortedWith( + compareBy { + it.focalLength35mmEquivalent.takeIf { focal -> focal > 0f } ?: Float.MAX_VALUE + }.thenBy { it.cameraId } + ) + +@Composable +private fun externalLensStabilizationLabel( + option: ExternalLensStabilizationOption, +): String { + val prefix = when (option.lensFacing) { + android.hardware.camera2.CameraCharacteristics.LENS_FACING_BACK -> + stringResource(R.string.rear_camera) + android.hardware.camera2.CameraCharacteristics.LENS_FACING_FRONT -> + stringResource(R.string.front_camera) + else -> stringResource(R.string.camera) + } + val focalLength = if (option.focalLength35mmEquivalent > 0f) { + stringResource( + R.string.settings_isz_lens_focal_length, + option.focalLength35mmEquivalent.roundToInt(), + ) + } else { + stringResource(R.string.settings_isz_lens_unknown_focal_length) + } + return stringResource( + R.string.settings_isz_lens_label, + prefix, + option.cameraId, + focalLength, + ) +} + +@Composable +private fun ExternalLensStabilizationDialog( + availableCameras: List, + currentConfig: ExternalLensStabilizationConfig, + onApply: (ExternalLensStabilizationConfig) -> Unit, + onDismiss: () -> Unit, +) { + val discoveredOptions = remember(availableCameras) { + externalLensStabilizationOptions(availableCameras) + } + val options = remember(discoveredOptions, currentConfig.physicalCameraId) { + if (currentConfig.isEnabled && + discoveredOptions.none { it.cameraId == currentConfig.physicalCameraId } + ) { + discoveredOptions + ExternalLensStabilizationOption( + cameraId = currentConfig.physicalCameraId, + lensFacing = android.hardware.camera2.CameraCharacteristics.LENS_FACING_BACK, + focalLength35mmEquivalent = 0f, + ) + } else { + discoveredOptions + } + } + var enabled by remember(currentConfig) { mutableStateOf(currentConfig.isEnabled) } + var selectedCameraId by remember(options, currentConfig) { + mutableStateOf( + currentConfig.physicalCameraId.takeIf { configuredId -> + options.any { it.cameraId == configuredId } + } ?: options.firstOrNull()?.cameraId.orEmpty() + ) + } + var magnificationText by remember(currentConfig) { + mutableStateOf( + editableExternalLensMagnification( + currentConfig.magnification.takeIf { currentConfig.isEnabled } ?: 2f + ) + ) + } + val magnification = magnificationText.replace(',', '.').toFloatOrNull() + val magnificationValid = magnification != null && + magnification > MIN_EXTERNAL_LENS_MAGNIFICATION && + magnification <= MAX_EXTERNAL_LENS_MAGNIFICATION + val lensLabels = options.map { it.cameraId to externalLensStabilizationLabel(it) } + val selectedLensLabel = lensLabels.firstOrNull { it.first == selectedCameraId } + ?.second.orEmpty() + val canApply = !enabled || + (selectedCameraId.isNotBlank() && magnificationValid) + + AlertDialog( + onDismissRequest = onDismiss, + containerColor = Color(0xFF1A1A1A), + title = { Text(stringResource(R.string.settings_external_lens_stabilization)) }, + text = { + Column(modifier = Modifier.verticalScroll(rememberScrollState())) { + SwitchSettingItem( + title = stringResource( + R.string.settings_external_lens_stabilization_enabled + ), + description = stringResource( + R.string.settings_external_lens_stabilization_enabled_description + ), + checked = enabled, + enabled = options.isNotEmpty(), + onCheckedChange = { enabled = it }, + ) + + if (options.isEmpty()) { + Spacer(modifier = Modifier.height(8.dp)) + Text( + text = stringResource( + R.string.settings_external_lens_stabilization_no_physical_lens + ), + color = Color.White.copy(alpha = 0.65f), + fontSize = 13.sp, + lineHeight = 18.sp, + ) + } else if (enabled) { + HorizontalDivider( + color = Color.White.copy(alpha = 0.1f), + modifier = Modifier.padding(vertical = 12.dp), + ) + DropdownSettingItem( + title = stringResource( + R.string.settings_external_lens_stabilization_physical_lens + ), + description = stringResource( + R.string.settings_external_lens_stabilization_physical_lens_description + ), + value = selectedLensLabel, + options = lensLabels.map { it.second }, + isLoading = false, + onExpanded = {}, + onOptionSelected = { label -> + lensLabels.firstOrNull { it.second == label }?.let { + selectedCameraId = it.first + } + }, + ) + + HorizontalDivider( + color = Color.White.copy(alpha = 0.1f), + modifier = Modifier.padding(vertical = 12.dp), + ) + QualityLevelSetting( + title = stringResource( + R.string.settings_external_lens_stabilization_magnification + ), + description = stringResource( + R.string.settings_external_lens_stabilization_magnification_description + ), + levels = listOf(1.5f, 2f, 3f).map { + it to IszLensConfig.displayRatioLabel(it) + }, + currentLevel = magnification ?: Float.NaN, + onLevelSelected = { + magnificationText = editableExternalLensMagnification(it) + }, + ) + Spacer(modifier = Modifier.height(12.dp)) + androidx.compose.material3.OutlinedTextField( + value = magnificationText, + onValueChange = { + magnificationText = sanitizeExternalLensMagnificationInput(it) + }, + modifier = Modifier.fillMaxWidth(), + label = { + Text( + stringResource( + R.string.settings_external_lens_stabilization_custom_magnification + ) + ) + }, + supportingText = { + Text( + stringResource( + if (magnificationValid) { + R.string.settings_external_lens_stabilization_custom_magnification_hint + } else { + R.string.settings_external_lens_stabilization_magnification_error + }, + MAX_EXTERNAL_LENS_MAGNIFICATION, + ) + ) + }, + isError = !magnificationValid, + singleLine = true, + keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Decimal), + colors = customVendorKeyTextFieldColors(), + ) + } + } + }, + confirmButton = { + TextButton( + enabled = canApply, + onClick = { + onApply( + if (enabled) { + ExternalLensStabilizationConfig( + physicalCameraId = selectedCameraId, + magnification = requireNotNull(magnification), + ).normalized() + } else { + ExternalLensStabilizationConfig.Disabled + } + ) + }, + ) { + Text(stringResource(R.string.settings_external_lens_stabilization_apply)) + } + }, + dismissButton = { + TextButton(onClick = onDismiss) { + Text(stringResource(R.string.cancel)) + } + }, + ) +} + +private fun editableExternalLensMagnification(magnification: Float): String = + String.format(Locale.US, "%.2f", magnification) + .trimEnd('0') + .trimEnd('.') + +private fun sanitizeExternalLensMagnificationInput(value: String): String { + val normalized = value.replace(',', '.') + val result = StringBuilder() + var decimalSeen = false + normalized.forEach { character -> + when { + character.isDigit() -> result.append(character) + character == '.' && !decimalSeen -> { + decimalSeen = true + result.append(character) + } + } + } + return result.toString().take(5) +} + /** * 图像质量等级设置(通用组件) */ diff --git a/app/src/main/java/com/hinnka/mycamera/viewmodel/CameraViewModel.kt b/app/src/main/java/com/hinnka/mycamera/viewmodel/CameraViewModel.kt index c25572ef..bed27d5a 100644 --- a/app/src/main/java/com/hinnka/mycamera/viewmodel/CameraViewModel.kt +++ b/app/src/main/java/com/hinnka/mycamera/viewmodel/CameraViewModel.kt @@ -81,6 +81,7 @@ import com.hinnka.mycamera.raw.RawWhiteLevelCorrection import com.hinnka.mycamera.raw.SpectralFilmSelection import com.hinnka.mycamera.raw.SpectralFilmTuning import com.hinnka.mycamera.screencapture.PhantomPipCrop +import com.hinnka.mycamera.stabilization.ExternalLensStabilizationConfig import com.hinnka.mycamera.ui.camera.CameraGLSurfaceView import com.hinnka.mycamera.ui.camera.ZoomDisplayMode import com.hinnka.mycamera.utils.* @@ -2015,6 +2016,9 @@ class CameraViewModel(application: Application) : AndroidViewModel(application) cameraController.setVideoEnhancedStabilizationLookahead( it.videoEnhancedStabilizationLookahead ) + cameraController.setExternalLensStabilizationConfig( + it.externalLensStabilizationConfig + ) cameraController.setPhotoPreviewStabilizationEnabled( it.photoPreviewStabilizationEnabled ) @@ -2163,6 +2167,9 @@ class CameraViewModel(application: Application) : AndroidViewModel(application) cameraController.setVideoEnhancedStabilizationLookahead( prefs.videoEnhancedStabilizationLookahead ) + cameraController.setExternalLensStabilizationConfig( + prefs.externalLensStabilizationConfig + ) cameraController.setVideoTorchEnabled(prefs.videoTorchEnabled) cameraController.setVideoLensLockEnabled(prefs.videoLensLockEnabled) cameraController.setVideoWhiteBalanceLockEnabled(prefs.videoWhiteBalanceLockEnabled) @@ -3521,6 +3528,14 @@ class CameraViewModel(application: Application) : AndroidViewModel(application) } } + fun setExternalLensStabilizationConfig(config: ExternalLensStabilizationConfig) { + val normalized = config.normalized() + cameraController.setExternalLensStabilizationConfig(normalized) + viewModelScope.launch { + userPreferencesRepository.saveExternalLensStabilizationConfig(normalized) + } + } + fun setVideoLogProfile(logProfile: VideoLogProfile) { cameraController.setVideoLogProfile(logProfile) reopenCamera() diff --git a/app/src/main/res/values-b+zh+Hant/strings.xml b/app/src/main/res/values-b+zh+Hant/strings.xml index 7214127f..18176934 100644 --- a/app/src/main/res/values-b+zh+Hant/strings.xml +++ b/app/src/main/res/values-b+zh+Hant/strings.xml @@ -204,6 +204,20 @@ EIS+ 前瞻影格數 影格數越少,畫面延遲越低、跟手性越強;影格數越多,畫面防震越平滑穩定。預設為 7 幀。 %1$d 幀 + 外接鏡頭防震 + 安裝增倍鏡時校正 EIS+ 的光學參數。 + %1$s · 外接倍率 %2$s + 已安裝增倍鏡 + 拆下外接鏡頭後請關閉,否則 EIS+ 會使用錯誤的光學校準。 + 物理鏡頭 + 選擇實際被外接鏡頭覆蓋的物理 Camera ID。 + 外接倍率 + 填寫增倍鏡的實際光學倍率,用於校正 EIS+ 的焦距和 OIS 位移。 + 自訂倍率 + 大於 1.0x,最大 %1$.1fx + 請輸入大於 1.0x 且不超過 %1$.1fx 的倍率 + 未發現相容的後置物理鏡頭。 + 套用 鎖定白平衡 影片錄製過程中鎖定白平衡。 畫質與性能 diff --git a/app/src/main/res/values-zh-rCN/strings.xml b/app/src/main/res/values-zh-rCN/strings.xml index 3877c001..a219fa60 100644 --- a/app/src/main/res/values-zh-rCN/strings.xml +++ b/app/src/main/res/values-zh-rCN/strings.xml @@ -204,6 +204,20 @@ EIS+ 前瞻帧数 帧数越少,画面延时越低、跟手性越强;帧数越多,画面防抖越平滑稳定。默认为 7 帧。 %1$d 帧 + 外接镜头防抖 + 安装增倍镜时校正 EIS+ 的光学参数。 + %1$s · 外接倍率 %2$s + 已安装增倍镜 + 拆下外接镜头后请关闭,否则 EIS+ 会使用错误的光学校准。 + 物理镜头 + 选择实际被外接镜头覆盖的物理 Camera ID。 + 外接倍率 + 填写增倍镜的实际光学倍率,用于校正 EIS+ 的焦距和 OIS 位移。 + 自定义倍率 + 大于 1.0x,最大 %1$.1fx + 请输入大于 1.0x 且不超过 %1$.1fx 的倍率 + 未发现兼容的后置物理镜头。 + 应用 锁定白平衡 视频录制过程中锁定白平衡。 画质与性能 diff --git a/app/src/main/res/values-zh-rHK/strings.xml b/app/src/main/res/values-zh-rHK/strings.xml index dd33945b..4aebf489 100644 --- a/app/src/main/res/values-zh-rHK/strings.xml +++ b/app/src/main/res/values-zh-rHK/strings.xml @@ -204,6 +204,20 @@ EIS+ 前瞻影格數 影格數越少,畫面延遲越低、跟手性越強;影格數越多,畫面防震越平滑穩定。預設為 7 幀。 %1$d 幀 + 外接鏡頭防震 + 安裝增倍鏡時校正 EIS+ 的光學參數。 + %1$s · 外接倍率 %2$s + 已安裝增倍鏡 + 拆下外接鏡頭後請關閉,否則 EIS+ 會使用錯誤的光學校準。 + 物理鏡頭 + 選擇實際被外接鏡頭覆蓋的物理 Camera ID。 + 外接倍率 + 填寫增倍鏡的實際光學倍率,用於校正 EIS+ 的焦距和 OIS 位移。 + 自訂倍率 + 大於 1.0x,最大 %1$.1fx + 請輸入大於 1.0x 且不超過 %1$.1fx 的倍率 + 未發現相容的後置物理鏡頭。 + 套用 鎖定白平衡 影片錄製過程中鎖定白平衡。 畫質與性能 diff --git a/app/src/main/res/values-zh-rTW/strings.xml b/app/src/main/res/values-zh-rTW/strings.xml index 68557a3b..d0f41935 100644 --- a/app/src/main/res/values-zh-rTW/strings.xml +++ b/app/src/main/res/values-zh-rTW/strings.xml @@ -204,6 +204,20 @@ EIS+ 前瞻影格數 影格數越少,畫面延遲越低、跟手性越強;影格數越多,畫面防震越平滑穩定。預設為 7 幀。 %1$d 幀 + 外接鏡頭防震 + 安裝增倍鏡時校正 EIS+ 的光學參數。 + %1$s · 外接倍率 %2$s + 已安裝增倍鏡 + 拆下外接鏡頭後請關閉,否則 EIS+ 會使用錯誤的光學校準。 + 物理鏡頭 + 選擇實際被外接鏡頭覆蓋的物理 Camera ID。 + 外接倍率 + 填寫增倍鏡的實際光學倍率,用於校正 EIS+ 的焦距和 OIS 位移。 + 自訂倍率 + 大於 1.0x,最大 %1$.1fx + 請輸入大於 1.0x 且不超過 %1$.1fx 的倍率 + 未發現相容的後置物理鏡頭。 + 套用 鎖定白平衡 影片錄製過程中鎖定白平衡。 畫質與性能 diff --git a/app/src/main/res/values/strings.xml b/app/src/main/res/values/strings.xml index bbb9f94b..1eabd0b7 100644 --- a/app/src/main/res/values/strings.xml +++ b/app/src/main/res/values/strings.xml @@ -208,6 +208,20 @@ EIS+ Lookahead Frames Lower frames reduce latency for better responsiveness; higher frames provide smoother stabilization. Default is 7 frames. %1$d frames + External Lens Stabilization + Correct EIS+ optics when a teleconverter is installed. + %1$s · %2$s external magnification + Teleconverter installed + Disable this after removing the external lens, otherwise EIS+ will apply incorrect optical calibration. + Physical lens + Select the physical Camera ID actually covered by the external lens. + External magnification + Use the real optical magnification of the teleconverter. This corrects focal length and OIS motion for EIS+. + Custom magnification + Greater than 1.0x, up to %1$.1fx + Enter a value greater than 1.0x and no more than %1$.1fx + No compatible rear physical lens was discovered. + Apply Lock White Balance Keep automatic white balance fixed while video is recording. Quality & Performance