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 8469ff3f..5406c4ec 100644 --- a/app/src/main/java/com/hinnka/mycamera/camera/Camera2Controller.kt +++ b/app/src/main/java/com/hinnka/mycamera/camera/Camera2Controller.kt @@ -2313,8 +2313,17 @@ class Camera2Controller(private val context: Context) { } else { emptyMap() } + val customVendorSessionKeys = if (includeVendorSessionParameters) { + customVendorSessionParameterKeys(state) + } else { + emptyList() + } - if (!shouldApplyStandardSessionParameters && vendorSessionValues.isEmpty()) { + if ( + !shouldApplyStandardSessionParameters && + vendorSessionValues.isEmpty() && + customVendorSessionKeys.isEmpty() + ) { return InitialSessionParametersResult(applied = false, usedVendorParameters = false) } @@ -2331,15 +2340,23 @@ class Camera2Controller(private val context: Context) { target = "session" ) } + applyCustomVendorKeys( + builder = builder, + lensId = state.currentCameraId, + keys = customVendorSessionKeys, + target = "session" + ) sessionConfig.setSessionParameters(builder.build()) PLog.d( TAG, "Initial session parameters applied: standard=$shouldApplyStandardSessionParameters, " + - "vendorKeys=${vendorSessionValues.keys.map { it.requestKeyName }}" + "vendorKeys=${vendorSessionValues.keys.map { it.requestKeyName }}, " + + "customVendorKeys=${customVendorSessionKeys.map { it.keyName }}" ) return InitialSessionParametersResult( applied = true, - usedVendorParameters = vendorSessionValues.isNotEmpty() + usedVendorParameters = + vendorSessionValues.isNotEmpty() || customVendorSessionKeys.isNotEmpty() ) } catch (e: Exception) { PLog.w(TAG, "Failed to set initial session parameters", e) @@ -2591,6 +2608,7 @@ class Camera2Controller(private val context: Context) { setZslDisabledIfSupported(builder) } applyVendorCaptureSettings(builder, isCapture) + applyCustomVendorCaptureRequestKeys(builder, isCapture) if (isCapture) { PLog.i( TAG, @@ -2614,6 +2632,13 @@ class Camera2Controller(private val context: Context) { } } + private fun customVendorSessionParameterKeys(state: CameraState): List { + return state.customVendorKeySettings.keysFor( + cameraId = state.currentCameraId, + target = CustomVendorKeyTarget.SESSION_PARAMETER + ) + } + private fun applyVendorCaptureSettings(builder: CaptureRequest.Builder, isCapture: Boolean) { val state = _state.value val lensId = state.currentCameraId @@ -2659,6 +2684,64 @@ class Camera2Controller(private val context: Context) { } } + private fun applyCustomVendorCaptureRequestKeys( + builder: CaptureRequest.Builder, + isCapture: Boolean + ) { + val state = _state.value + val lensId = state.currentCameraId + val keys = state.customVendorKeySettings.keysFor( + cameraId = lensId, + target = CustomVendorKeyTarget.CAPTURE_REQUEST + ) + applyCustomVendorKeys( + builder = builder, + lensId = lensId, + keys = keys, + target = if (isCapture) "capture" else "preview" + ) + } + + private fun applyCustomVendorKeys( + builder: CaptureRequest.Builder, + lensId: String, + keys: List, + target: String + ) { + keys.forEach { key -> + try { + when (key.valueType) { + CustomVendorKeyValueType.INT32 -> { + builder.set( + CaptureRequest.Key(key.keyName, Int::class.java), + key.normalizedValue + ) + } + + CustomVendorKeyValueType.U8 -> { + // Camera2 exposes byte vendor tags as Java Byte. Values 128..255 + // keep their unsigned bit pattern when converted to Byte. + builder.set( + CaptureRequest.Key(key.keyName, Byte::class.java), + key.normalizedValue.toByte() + ) + } + } + PLog.d( + TAG, + "Applied custom vendor $target key for lens $lensId: " + + "${key.keyName}=${key.normalizedValue} (${key.valueType})" + ) + } catch (e: Exception) { + PLog.w( + TAG, + "Failed to apply custom vendor $target key for lens $lensId: ${key.keyName}", + e + ) + } + } + } + private fun isCaptureRequestKeyAvailable(requestKeyName: String): Boolean { val keyNames = availableCaptureRequestKeyNames ?: loadAvailableCaptureRequestKeyNames(getActiveOpenCameraCharacteristics()).also { @@ -3791,6 +3874,55 @@ class Camera2Controller(private val context: Context) { } } + fun setCustomVendorKeySettings(settings: CustomVendorKeySettings) { + val handler = cameraHandler + if (handler != null && Looper.myLooper() != handler.looper) { + handler.post { + setCustomVendorKeySettings(settings) + } + return + } + + val previousState = _state.value + if (previousState.customVendorKeySettings == settings) return + + val previousSessionKeys = customVendorSessionParameterKeys(previousState) + val updatedState = previousState.copy(customVendorKeySettings = settings) + val updatedSessionKeys = customVendorSessionParameterKeys(updatedState) + + _state.value = updatedState + PLog.d(TAG, "Custom vendor key count: ${settings.keys.size}") + + val shouldRecreateSession = + previousSessionKeys != updatedSessionKeys && + cameraDevice != null && + previewSurface != null + if (shouldRecreateSession) { + if (_state.value.videoRecordingState.isRecording) { + pendingVendorSessionParameterRestart = true + PLog.w( + TAG, + "Custom vendor session parameter changed during recording; " + + "keeping active request until session restart" + ) + return + } + PLog.d( + TAG, + "Recreating preview session for custom vendor session parameter change: " + + "old=${previousSessionKeys.map { it.keyName }}, " + + "new=${updatedSessionKeys.map { it.keyName }}" + ) + createPreviewSession(openGeneration = cameraOpenGeneration) + return + } + + previewRequestBuilder?.apply { + applyBaseCameraSettings(this, isCapture = false) + updatePreview() + } + } + /** * 设置是否使用 RAW 格式拍照 */ diff --git a/app/src/main/java/com/hinnka/mycamera/camera/CameraState.kt b/app/src/main/java/com/hinnka/mycamera/camera/CameraState.kt index 2c18747e..1c718624 100644 --- a/app/src/main/java/com/hinnka/mycamera/camera/CameraState.kt +++ b/app/src/main/java/com/hinnka/mycamera/camera/CameraState.kt @@ -341,6 +341,7 @@ data class CameraState( val nrLevel: Int = 5, val availableNrModes: IntArray = intArrayOf(), val vendorCaptureSettingsByLens: VendorCaptureSettingsByLens = VendorCaptureSettingsByLens.Empty, + val customVendorKeySettings: CustomVendorKeySettings = CustomVendorKeySettings.Empty, val isRawSupported: Boolean = false, val multiFrameOutputScale: Float? = null, diff --git a/app/src/main/java/com/hinnka/mycamera/camera/CustomVendorKeySettings.kt b/app/src/main/java/com/hinnka/mycamera/camera/CustomVendorKeySettings.kt new file mode 100644 index 00000000..d07172b9 --- /dev/null +++ b/app/src/main/java/com/hinnka/mycamera/camera/CustomVendorKeySettings.kt @@ -0,0 +1,161 @@ +package com.hinnka.mycamera.camera + +import org.json.JSONArray +import org.json.JSONObject + +/** + * User-defined Camera2 vendor keys. + * + * A null [lensId] means that the key applies to every lens. Lens-specific keys + * are evaluated after global keys so an explicitly targeted value can override + * a global value with the same key name. + */ +data class CustomVendorKey( + val id: String, + val keyName: String, + val target: CustomVendorKeyTarget, + val valueType: CustomVendorKeyValueType, + val value: Int, + val lensId: String? = null +) { + val normalizedValue: Int + get() = valueType.normalize(value) + + fun appliesTo(cameraId: String): Boolean = lensId == null || lensId == cameraId + + fun normalized(): CustomVendorKey = copy( + keyName = keyName.trim(), + value = normalizedValue, + lensId = lensId?.trim()?.takeIf { it.isNotEmpty() } + ) + + internal fun toJsonObject(): JSONObject { + val normalized = normalized() + return JSONObject().apply { + put(KEY_ID, normalized.id) + put(KEY_NAME, normalized.keyName) + put(KEY_TARGET, normalized.target.name) + put(KEY_VALUE_TYPE, normalized.valueType.name) + put(KEY_VALUE, normalized.value) + normalized.lensId?.let { put(KEY_LENS_ID, it) } + } + } + + companion object { + private const val KEY_ID = "id" + private const val KEY_NAME = "key_name" + private const val KEY_TARGET = "target" + private const val KEY_VALUE_TYPE = "value_type" + private const val KEY_VALUE = "value" + private const val KEY_LENS_ID = "lens_id" + + internal fun fromJsonObject(json: JSONObject): CustomVendorKey? { + val id = json.optString(KEY_ID).trim() + val keyName = json.optString(KEY_NAME).trim() + if (id.isEmpty() || !isValidKeyName(keyName) || !json.has(KEY_VALUE)) return null + + val target = runCatching { + CustomVendorKeyTarget.valueOf(json.optString(KEY_TARGET)) + }.getOrNull() ?: return null + val valueType = runCatching { + CustomVendorKeyValueType.valueOf(json.optString(KEY_VALUE_TYPE)) + }.getOrNull() ?: return null + val lensId = json.optString(KEY_LENS_ID) + .trim() + .takeIf { + json.has(KEY_LENS_ID) && + !json.isNull(KEY_LENS_ID) && + it.isNotEmpty() + } + + return CustomVendorKey( + id = id, + keyName = keyName, + target = target, + valueType = valueType, + value = valueType.normalize(json.optInt(KEY_VALUE)), + lensId = lensId + ) + } + + fun isValidKeyName(value: String): Boolean { + val normalized = value.trim() + return normalized.isNotEmpty() && + normalized.all { !it.isWhitespace() && !it.isISOControl() } + } + } +} + +data class CustomVendorKeySettings( + val keys: List = emptyList() +) { + val isEnabled: Boolean + get() = keys.isNotEmpty() + + fun keysFor(cameraId: String, target: CustomVendorKeyTarget): List { + return keys + .asSequence() + .filter { it.target == target && it.appliesTo(cameraId) } + .sortedBy { it.lensId != null } + .toList() + } + + fun upsert(key: CustomVendorKey): CustomVendorKeySettings { + val normalized = key.normalized() + if ( + normalized.id.isBlank() || + !CustomVendorKey.isValidKeyName(normalized.keyName) + ) { + return this + } + return CustomVendorKeySettings( + keys.filterNot { it.id == normalized.id } + normalized + ) + } + + fun remove(id: String): CustomVendorKeySettings { + return CustomVendorKeySettings(keys.filterNot { it.id == id }) + } + + fun serialize(): String { + return JSONArray().apply { + keys.forEach { put(it.toJsonObject()) } + }.toString() + } + + companion object { + val Empty = CustomVendorKeySettings() + + fun deserialize(value: String?): CustomVendorKeySettings { + if (value.isNullOrBlank()) return Empty + val array = runCatching { JSONArray(value) }.getOrNull() ?: return Empty + val parsed = buildList { + for (index in 0 until array.length()) { + val key = array.optJSONObject(index)?.let(CustomVendorKey::fromJsonObject) + key ?: continue + if (none { it.id == key.id }) add(key) + } + } + return CustomVendorKeySettings(parsed) + } + } +} + +enum class CustomVendorKeyTarget { + CAPTURE_REQUEST, + SESSION_PARAMETER +} + +enum class CustomVendorKeyValueType { + INT32, + U8; + + fun normalize(value: Int): Int { + return when (this) { + INT32 -> value + U8 -> value.coerceIn(UByte.MIN_VALUE.toInt(), UByte.MAX_VALUE.toInt()) + } + } + + fun isValid(value: Int): Boolean = normalize(value) == value +} 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 18f08239..0909190a 100644 --- a/app/src/main/java/com/hinnka/mycamera/data/UserPreferencesRepository.kt +++ b/app/src/main/java/com/hinnka/mycamera/data/UserPreferencesRepository.kt @@ -12,6 +12,8 @@ import androidx.datastore.preferences.core.stringPreferencesKey import androidx.datastore.preferences.preferencesDataStore import com.hinnka.mycamera.camera.AspectRatio import com.hinnka.mycamera.camera.CustomFocalLengthValue +import com.hinnka.mycamera.camera.CustomVendorKey +import com.hinnka.mycamera.camera.CustomVendorKeySettings import com.hinnka.mycamera.camera.IszLensConfig import com.hinnka.mycamera.camera.IszRawDngMetadataCorrections import com.hinnka.mycamera.camera.MultiFrameConfig @@ -149,6 +151,7 @@ data class UserPreferences( val nrLevel: Int = 5, // 降噪等级:0=Off, 1=Fast, 2=High Quality, 3=ZSL, 4=Minimal, 5=Auto val edgeLevel: Int = 1, // 锐化等级:0=Off, 1=Fast, 2=High Quality, 3=Real-time val vendorCaptureSettingsByLens: VendorCaptureSettingsByLens = VendorCaptureSettingsByLens.Empty, + val customVendorKeySettings: CustomVendorKeySettings = CustomVendorKeySettings.Empty, val useRaw: Boolean = false, // 使用 RAW 格式拍摄 val meteringMode: MeteringMode = MeteringMode.SYSTEM_DEFAULT, // 测光模式 val sharpening: Float = 0f, // 0.0 ~ 1.0 锐化强度 @@ -354,6 +357,7 @@ class UserPreferencesRepository(private val context: Context) { private val NR_LEVEL = intPreferencesKey("nr_level") private val EDGE_LEVEL = intPreferencesKey("edge_level") private val VENDOR_CAPTURE_SETTINGS = stringPreferencesKey("vendor_capture_settings") + private val CUSTOM_VENDOR_KEY_SETTINGS = stringPreferencesKey("custom_vendor_key_settings") private val USE_RAW = booleanPreferencesKey("use_raw") private val RAW_LENS_SHADING_CORRECTION_ENABLED = booleanPreferencesKey("raw_lens_shading_correction_enabled") private val METERING_MODE = stringPreferencesKey("metering_mode") @@ -571,6 +575,9 @@ class UserPreferencesRepository(private val context: Context) { vendorCaptureSettingsByLens = VendorCaptureSettingsByLens.deserialize( preferences[VENDOR_CAPTURE_SETTINGS] ), + customVendorKeySettings = CustomVendorKeySettings.deserialize( + preferences[CUSTOM_VENDOR_KEY_SETTINGS] + ), useRaw = when { useRawMax -> true useJpgMax -> false @@ -1430,6 +1437,34 @@ class UserPreferencesRepository(private val context: Context) { } } + suspend fun upsertCustomVendorKey(key: CustomVendorKey) { + context.dataStore.edit { preferences -> + val current = CustomVendorKeySettings.deserialize( + preferences[CUSTOM_VENDOR_KEY_SETTINGS] + ) + val updated = current.upsert(key) + if (updated.isEnabled) { + preferences[CUSTOM_VENDOR_KEY_SETTINGS] = updated.serialize() + } else { + preferences.remove(CUSTOM_VENDOR_KEY_SETTINGS) + } + } + } + + suspend fun removeCustomVendorKey(id: String) { + context.dataStore.edit { preferences -> + val current = CustomVendorKeySettings.deserialize( + preferences[CUSTOM_VENDOR_KEY_SETTINGS] + ) + val updated = current.remove(id) + if (updated.isEnabled) { + preferences[CUSTOM_VENDOR_KEY_SETTINGS] = updated.serialize() + } else { + preferences.remove(CUSTOM_VENDOR_KEY_SETTINGS) + } + } + } + /** * 保存是否使用 RAW 格式 */ 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 6537b51b..7dc9d6dd 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 @@ -26,6 +26,7 @@ import androidx.compose.foundation.layout.Spacer import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.height +import androidx.compose.foundation.layout.heightIn import androidx.compose.foundation.layout.navigationBarsPadding import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.size @@ -43,6 +44,8 @@ import androidx.compose.material.icons.automirrored.filled.ArrowBack import androidx.compose.material.icons.filled.Check import androidx.compose.material.icons.filled.Add import androidx.compose.material.icons.filled.Close +import androidx.compose.material.icons.filled.Delete +import androidx.compose.material.icons.filled.Edit import androidx.compose.material.ripple.RippleAlpha import androidx.compose.material3.AlertDialog import androidx.compose.material3.Card @@ -99,6 +102,10 @@ import com.hinnka.mycamera.R import com.hinnka.mycamera.camera.AspectRatio import com.hinnka.mycamera.camera.CameraInfo import com.hinnka.mycamera.camera.CustomFocalLengthValue +import com.hinnka.mycamera.camera.CustomVendorKey +import com.hinnka.mycamera.camera.CustomVendorKeySettings +import com.hinnka.mycamera.camera.CustomVendorKeyTarget +import com.hinnka.mycamera.camera.CustomVendorKeyValueType import com.hinnka.mycamera.camera.IszLensConfig import com.hinnka.mycamera.camera.IszRawDngMetadataCorrections import com.hinnka.mycamera.camera.LensType @@ -138,6 +145,7 @@ import com.hinnka.mycamera.utils.DeviceUtil import com.hinnka.mycamera.viewmodel.CameraViewModel import com.hinnka.mycamera.video.VideoRecordingPath import java.io.File +import java.util.UUID import kotlin.math.roundToInt import com.hinnka.mycamera.ui.icons.AppIcons @@ -259,6 +267,7 @@ fun SettingsScreen( val nrLevel by viewModel.nrLevel.collectAsState(initial = 5) val edgeLevel by viewModel.edgeLevel.collectAsState(initial = 1) val vendorCaptureSettingsByLens by viewModel.vendorCaptureSettingsByLens.collectAsState() + val customVendorKeySettings by viewModel.customVendorKeySettings.collectAsState() val useRaw by viewModel.useRaw.collectAsState(initial = false) val exportDngWithRawExport by viewModel.exportDngWithRawExport.collectAsState(initial = true) // 软件处理参数 @@ -362,6 +371,7 @@ fun SettingsScreen( var windowScreenBrightnessEnabled by remember { mutableStateOf(windowScreenBrightness != null) } var showAspectRatioDialog by remember { mutableStateOf(false) } var showAddIszLensDialog by remember { mutableStateOf(false) } + var showCustomVendorKeysDialog by remember { mutableStateOf(false) } var backupOperation by remember { mutableStateOf(null) } LaunchedEffect( @@ -986,6 +996,20 @@ fun SettingsScreen( onClick = { showAddIszLensDialog = true } ) + HorizontalDivider( + color = Color.White.copy(alpha = 0.1f), + modifier = Modifier.padding(vertical = 8.dp) + ) + + NavigationSettingItem( + title = stringResource(R.string.settings_custom_vendor_keys), + description = stringResource( + R.string.settings_custom_vendor_keys_description, + customVendorKeySettings.keys.size + ), + onClick = { showCustomVendorKeysDialog = true } + ) + if (mainCameraIdOptions.size > 1) { HorizontalDivider( color = Color.White.copy(alpha = 0.1f), @@ -2431,6 +2455,16 @@ fun SettingsScreen( ) } + if (showCustomVendorKeysDialog) { + CustomVendorKeysDialog( + availableCameras = state.availableCameras, + settings = customVendorKeySettings, + onSave = viewModel::upsertCustomVendorKey, + onDelete = viewModel::removeCustomVendorKey, + onDismiss = { showCustomVendorKeysDialog = false } + ) + } + baselinePickerTarget?.let { target -> val currentBaselineLutId = when (target) { BaselineColorCorrectionTarget.JPG -> jpgBaselineLutId @@ -3516,6 +3550,369 @@ private fun PremiumCard( } +@Composable +private fun CustomVendorKeysDialog( + availableCameras: List, + settings: CustomVendorKeySettings, + onSave: (CustomVendorKey) -> Unit, + onDelete: (String) -> Unit, + onDismiss: () -> Unit +) { + var showEditor by remember { mutableStateOf(false) } + var editingId by remember { mutableStateOf(null) } + var keyNameText by remember { mutableStateOf("") } + var target by remember { mutableStateOf(CustomVendorKeyTarget.CAPTURE_REQUEST) } + var valueType by remember { mutableStateOf(CustomVendorKeyValueType.INT32) } + var valueText by remember { mutableStateOf("0") } + var lensId by remember { mutableStateOf(null) } + + val lensIds = remember(availableCameras, settings.keys) { + (availableCameras.map { it.cameraId } + settings.keys.mapNotNull { it.lensId }) + .distinct() + } + val allLensesLabel = stringResource(R.string.settings_custom_vendor_key_all_lenses) + val captureTargetLabel = stringResource(R.string.settings_custom_vendor_key_target_capture) + val sessionTargetLabel = stringResource(R.string.settings_custom_vendor_key_target_session) + val int32TypeLabel = stringResource(R.string.settings_custom_vendor_key_type_int32) + val u8TypeLabel = stringResource(R.string.settings_custom_vendor_key_type_u8) + val targetOptions = listOf( + CustomVendorKeyTarget.CAPTURE_REQUEST to captureTargetLabel, + CustomVendorKeyTarget.SESSION_PARAMETER to sessionTargetLabel + ) + val valueTypeOptions = listOf( + CustomVendorKeyValueType.INT32 to int32TypeLabel, + CustomVendorKeyValueType.U8 to u8TypeLabel + ) + val lensOptions = listOf(null) + lensIds + val lensLabels = lensOptions.map { id -> + id to if (id == null) { + allLensesLabel + } else { + stringResource(R.string.settings_custom_vendor_key_lens_id, id) + } + } + + fun beginAdd() { + editingId = null + keyNameText = "" + target = CustomVendorKeyTarget.CAPTURE_REQUEST + valueType = CustomVendorKeyValueType.INT32 + valueText = "0" + lensId = null + showEditor = true + } + + fun beginEdit(key: CustomVendorKey) { + editingId = key.id + keyNameText = key.keyName + target = key.target + valueType = key.valueType + valueText = key.normalizedValue.toString() + lensId = key.lensId + showEditor = true + } + + val normalizedKeyName = keyNameText.trim() + val isKeyNameValid = CustomVendorKey.isValidKeyName(normalizedKeyName) + val parsedValue = valueText.toIntOrNull() + val isValueValid = parsedValue != null && valueType.isValid(parsedValue) + val hasDuplicate = settings.keys.any { existing -> + if ( + existing.id == editingId || + existing.keyName != normalizedKeyName || + existing.target != target + ) { + false + } else { + val lensScopesOverlap = + existing.lensId == null || lensId == null || existing.lensId == lensId + existing.lensId == lensId || + (lensScopesOverlap && existing.valueType != valueType) + } + } + val isDraftValid = isKeyNameValid && isValueValid && !hasDuplicate + + AlertDialog( + onDismissRequest = onDismiss, + title = { + Text( + text = stringResource( + if (showEditor) { + R.string.settings_custom_vendor_key_editor_title + } else { + R.string.settings_custom_vendor_keys + } + ) + ) + }, + text = { + Column( + modifier = Modifier + .fillMaxWidth() + .heightIn(max = 560.dp) + .verticalScroll(rememberScrollState()) + ) { + Text( + text = stringResource(R.string.settings_custom_vendor_keys_warning), + color = Color(0xFFFFB74D), + fontSize = 13.sp, + lineHeight = 18.sp + ) + + Spacer(modifier = Modifier.height(12.dp)) + + if (showEditor) { + androidx.compose.material3.OutlinedTextField( + value = keyNameText, + onValueChange = { keyNameText = it }, + modifier = Modifier.fillMaxWidth(), + label = { Text(stringResource(R.string.settings_custom_vendor_key_name)) }, + supportingText = { + Text( + when { + hasDuplicate -> + stringResource(R.string.settings_custom_vendor_key_duplicate) + keyNameText.isNotEmpty() && !isKeyNameValid -> + stringResource(R.string.settings_custom_vendor_key_invalid_name) + else -> + stringResource(R.string.settings_custom_vendor_key_name_description) + } + ) + }, + isError = hasDuplicate || (keyNameText.isNotEmpty() && !isKeyNameValid), + singleLine = true, + colors = customVendorKeyTextFieldColors() + ) + + Spacer(modifier = Modifier.height(6.dp)) + + DropdownSettingItem( + title = stringResource(R.string.settings_custom_vendor_key_target), + description = stringResource( + if (target == CustomVendorKeyTarget.CAPTURE_REQUEST) { + R.string.settings_custom_vendor_key_target_capture_description + } else { + R.string.settings_custom_vendor_key_target_session_description + } + ), + value = targetOptions.first { it.first == target }.second, + options = targetOptions.map { it.second }, + isLoading = false, + onExpanded = {}, + onOptionSelected = { selected -> + targetOptions.firstOrNull { it.second == selected }?.let { + target = it.first + } + } + ) + + DropdownSettingItem( + title = stringResource(R.string.settings_custom_vendor_key_value_type), + value = valueTypeOptions.first { it.first == valueType }.second, + options = valueTypeOptions.map { it.second }, + isLoading = false, + onExpanded = {}, + onOptionSelected = { selected -> + valueTypeOptions.firstOrNull { it.second == selected }?.let { + valueType = it.first + } + } + ) + + androidx.compose.material3.OutlinedTextField( + value = valueText, + onValueChange = { valueText = it }, + modifier = Modifier.fillMaxWidth(), + label = { Text(stringResource(R.string.settings_custom_vendor_key_value)) }, + supportingText = { + Text( + if (isValueValid) { + stringResource( + if (valueType == CustomVendorKeyValueType.INT32) { + R.string.settings_custom_vendor_key_int32_range + } else { + R.string.settings_custom_vendor_key_u8_range + } + ) + } else { + stringResource(R.string.settings_custom_vendor_key_invalid_value) + } + ) + }, + isError = !isValueValid, + singleLine = true, + keyboardOptions = KeyboardOptions( + keyboardType = if (valueType == CustomVendorKeyValueType.INT32) { + KeyboardType.Ascii + } else { + KeyboardType.Number + } + ), + colors = customVendorKeyTextFieldColors() + ) + + Spacer(modifier = Modifier.height(6.dp)) + + DropdownSettingItem( + title = stringResource(R.string.settings_custom_vendor_key_lens), + value = lensLabels.firstOrNull { it.first == lensId }?.second ?: allLensesLabel, + options = lensLabels.map { it.second }, + isLoading = false, + onExpanded = {}, + onOptionSelected = { selected -> + lensLabels.firstOrNull { it.second == selected }?.let { + lensId = it.first + } + } + ) + } else { + if (settings.keys.isEmpty()) { + Text( + text = stringResource(R.string.settings_custom_vendor_keys_empty), + color = Color.White.copy(alpha = 0.6f), + fontSize = 14.sp, + modifier = Modifier.padding(vertical = 12.dp) + ) + } else { + settings.keys.forEachIndexed { index, key -> + if (index > 0) { + HorizontalDivider( + color = Color.White.copy(alpha = 0.08f), + modifier = Modifier.padding(vertical = 8.dp) + ) + } + val keyTargetLabel = when (key.target) { + CustomVendorKeyTarget.CAPTURE_REQUEST -> captureTargetLabel + CustomVendorKeyTarget.SESSION_PARAMETER -> sessionTargetLabel + } + val keyTypeLabel = when (key.valueType) { + CustomVendorKeyValueType.INT32 -> int32TypeLabel + CustomVendorKeyValueType.U8 -> u8TypeLabel + } + val keyLensLabel = lensLabels.firstOrNull { it.first == key.lensId } + ?.second + ?: key.lensId.orEmpty() + + Row( + modifier = Modifier.fillMaxWidth(), + verticalAlignment = Alignment.CenterVertically + ) { + Column( + modifier = Modifier + .weight(1f) + .clickable { beginEdit(key) } + .padding(vertical = 6.dp) + ) { + Text( + text = key.keyName, + color = Color.White, + fontSize = 14.sp, + maxLines = 2, + overflow = TextOverflow.Ellipsis + ) + Spacer(modifier = Modifier.height(4.dp)) + Text( + text = stringResource( + R.string.settings_custom_vendor_key_summary, + keyTargetLabel, + keyTypeLabel, + key.normalizedValue, + keyLensLabel + ), + color = Color.White.copy(alpha = 0.6f), + fontSize = 12.sp, + lineHeight = 17.sp + ) + } + IconButton(onClick = { beginEdit(key) }) { + Icon( + imageVector = Icons.Default.Edit, + contentDescription = stringResource(R.string.edit), + tint = Color.White.copy(alpha = 0.7f) + ) + } + IconButton(onClick = { onDelete(key.id) }) { + Icon( + imageVector = Icons.Default.Delete, + contentDescription = stringResource(R.string.delete), + tint = Color(0xFFFF8A80) + ) + } + } + } + } + + TextButton( + onClick = ::beginAdd, + modifier = Modifier.align(Alignment.End) + ) { + Icon( + imageVector = Icons.Default.Add, + contentDescription = null, + modifier = Modifier.size(18.dp) + ) + Spacer(modifier = Modifier.width(6.dp)) + Text(stringResource(R.string.settings_custom_vendor_key_add)) + } + } + } + }, + confirmButton = { + if (showEditor) { + TextButton( + enabled = isDraftValid, + onClick = { + val validValue = parsedValue ?: return@TextButton + onSave( + CustomVendorKey( + id = editingId ?: UUID.randomUUID().toString(), + keyName = normalizedKeyName, + target = target, + valueType = valueType, + value = validValue, + lensId = lensId + ) + ) + showEditor = false + } + ) { + Text(stringResource(R.string.save)) + } + } else { + TextButton(onClick = onDismiss) { + Text(stringResource(R.string.close)) + } + } + }, + dismissButton = if (showEditor) { + { + TextButton(onClick = { showEditor = false }) { + Text(stringResource(R.string.cancel)) + } + } + } else { + null + } + ) +} + +@Composable +private fun customVendorKeyTextFieldColors() = + androidx.compose.material3.OutlinedTextFieldDefaults.colors( + focusedTextColor = Color.White, + unfocusedTextColor = Color.White, + focusedBorderColor = Color(0xFFE5A324), + unfocusedBorderColor = Color.White.copy(alpha = 0.2f), + focusedLabelColor = Color(0xFFE5A324), + unfocusedLabelColor = Color.White.copy(alpha = 0.6f), + focusedSupportingTextColor = Color.White.copy(alpha = 0.55f), + unfocusedSupportingTextColor = Color.White.copy(alpha = 0.55f), + errorTextColor = Color.White, + errorSupportingTextColor = Color(0xFFFF8A80), + errorBorderColor = Color(0xFFFF8A80), + cursorColor = Color(0xFFE5A324) + ) + /** * 图像质量等级设置(通用组件) */ 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 5d078d02..29a2b8d6 100644 --- a/app/src/main/java/com/hinnka/mycamera/viewmodel/CameraViewModel.kt +++ b/app/src/main/java/com/hinnka/mycamera/viewmodel/CameraViewModel.kt @@ -1121,6 +1121,10 @@ class CameraViewModel(application: Application) : AndroidViewModel(application) userPreferencesRepository.userPreferences .map { it.vendorCaptureSettingsByLens } .stateIn(viewModelScope, SharingStarted.Eagerly, VendorCaptureSettingsByLens.Empty) + val customVendorKeySettings: StateFlow = + userPreferencesRepository.userPreferences + .map { it.customVendorKeySettings } + .stateIn(viewModelScope, SharingStarted.Eagerly, CustomVendorKeySettings.Empty) val rawRenderingEngine: StateFlow = userPreferencesRepository.userPreferences .map { it.rawRenderingEngine } .stateIn(viewModelScope, SharingStarted.Eagerly, RawRenderingEngine.AdobeCurve) @@ -1632,6 +1636,9 @@ class CameraViewModel(application: Application) : AndroidViewModel(application) if (currentCameraState.vendorCaptureSettingsByLens != it.vendorCaptureSettingsByLens) { cameraController.setVendorCaptureSettingsByLens(it.vendorCaptureSettingsByLens) } + if (currentCameraState.customVendorKeySettings != it.customVendorKeySettings) { + cameraController.setCustomVendorKeySettings(it.customVendorKeySettings) + } if (currentCameraState.quickShotConfig.resolution != it.quickShotResolution) { cameraController.setQuickShotResolution(it.quickShotResolution) } @@ -3112,6 +3119,10 @@ class CameraViewModel(application: Application) : AndroidViewModel(application) if (cameraController.state.value.vendorCaptureSettingsByLens != settings) { cameraController.setVendorCaptureSettingsByLens(settings) } + val customSettings = customVendorKeySettings.value + if (cameraController.state.value.customVendorKeySettings != customSettings) { + cameraController.setCustomVendorKeySettings(customSettings) + } } /** @@ -4515,6 +4526,18 @@ class CameraViewModel(application: Application) : AndroidViewModel(application) } } + fun upsertCustomVendorKey(key: CustomVendorKey) { + viewModelScope.launch { + userPreferencesRepository.upsertCustomVendorKey(key) + } + } + + fun removeCustomVendorKey(id: String) { + viewModelScope.launch { + userPreferencesRepository.removeCustomVendorKey(id) + } + } + /** * 设置照片质量 */ 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 4ff86fce..1717241f 100644 --- a/app/src/main/res/values-b+zh+Hant/strings.xml +++ b/app/src/main/res/values-b+zh+Hant/strings.xml @@ -320,6 +320,32 @@ Int 數值 Byte 數值,范圍 -128 到 127 數值無效 + 自訂 Vendor Key + 新增 Camera2 Vendor Key,並指定鏡頭 ID 或套用至所有鏡頭。已設定:%1$d + Vendor Key 與裝置相關,不支援的 Key 可能導致工作階段建立、預覽、錄影或拍攝失敗;出現問題時請刪除對應 Key。 + 尚未設定自訂 Vendor Key。 + 新增自訂 Key + 自訂 Vendor Key + Key 名稱 + 完整的 Camera2 Vendor Key 名稱,不允許包含空白字元。 + 請輸入不包含空白字元的 Key 名稱。 + 相同 Key 已用於同一範圍,或重疊範圍使用了不同的數值類型。 + Key 目標 + Capture Key + Session Key + 套用至預覽、錄影及靜態拍攝的 CaptureRequest Builder。 + 建立 Camera2 工作階段時套用;儲存變更後會重建目前工作階段。 + 數值類型 + int32 + u8 + 數值 + 有號 32 位元整數 + 無號 8 位元整數,範圍 0 到 255 + 數值超出所選類型的範圍。 + 鏡頭 ID + 所有鏡頭 + 鏡頭 ID:%1$s + %1$s · %2$s=%3$d · %4$s 銳化 增強圖像銳度和邊緣清晰度 降噪 diff --git a/app/src/main/res/values-zh-rCN/strings.xml b/app/src/main/res/values-zh-rCN/strings.xml index 9b23a404..b89b85c5 100644 --- a/app/src/main/res/values-zh-rCN/strings.xml +++ b/app/src/main/res/values-zh-rCN/strings.xml @@ -320,6 +320,32 @@ Int 数值 Byte 数值,范围 -128 到 127 数值无效 + 自定义 Vendor Key + 新建 Camera2 Vendor Key,并指定镜头 ID 或应用于所有镜头。已配置:%1$d + Vendor Key 与设备相关,不受支持的 Key 可能导致会话创建、预览、录像或拍摄失败;出现问题时请删除对应 Key。 + 尚未配置自定义 Vendor Key。 + 新增自定义 Key + 自定义 Vendor Key + Key 名称 + 完整的 Camera2 Vendor Key 名称,不允许包含空白字符。 + 请输入不包含空白字符的 Key 名称。 + 相同 Key 已用于同一范围,或重叠范围使用了不同的数值类型。 + Key 目标 + Capture Key + Session Key + 应用到预览、录像和静态拍摄的 CaptureRequest Builder。 + 创建 Camera2 会话时应用;保存变更后会重建当前会话。 + 数值类型 + int32 + u8 + 数值 + 有符号 32 位整数 + 无符号 8 位整数,范围 0 到 255 + 数值超出所选类型的范围。 + 镜头 ID + 所有镜头 + 镜头 ID:%1$s + %1$s · %2$s=%3$d · %4$s 锐化 增强图像锐度和边缘清晰度 降噪 diff --git a/app/src/main/res/values-zh-rHK/strings.xml b/app/src/main/res/values-zh-rHK/strings.xml index da26561b..17c0b402 100644 --- a/app/src/main/res/values-zh-rHK/strings.xml +++ b/app/src/main/res/values-zh-rHK/strings.xml @@ -320,6 +320,32 @@ Int 數值 Byte 數值,范圍 -128 到 127 數值無效 + 自訂 Vendor Key + 新增 Camera2 Vendor Key,並指定鏡頭 ID 或套用至所有鏡頭。已設定:%1$d + Vendor Key 與裝置相關,不支援的 Key 可能導致工作階段建立、預覽、錄影或拍攝失敗;出現問題時請刪除對應 Key。 + 尚未設定自訂 Vendor Key。 + 新增自訂 Key + 自訂 Vendor Key + Key 名稱 + 完整的 Camera2 Vendor Key 名稱,不允許包含空白字元。 + 請輸入不包含空白字元的 Key 名稱。 + 相同 Key 已用於同一範圍,或重疊範圍使用了不同的數值類型。 + Key 目標 + Capture Key + Session Key + 套用至預覽、錄影及靜態拍攝的 CaptureRequest Builder。 + 建立 Camera2 工作階段時套用;儲存變更後會重建目前工作階段。 + 數值類型 + int32 + u8 + 數值 + 有號 32 位元整數 + 無號 8 位元整數,範圍 0 到 255 + 數值超出所選類型的範圍。 + 鏡頭 ID + 所有鏡頭 + 鏡頭 ID:%1$s + %1$s · %2$s=%3$d · %4$s 銳化 增強圖像銳度和邊緣清晰度 降噪 diff --git a/app/src/main/res/values-zh-rTW/strings.xml b/app/src/main/res/values-zh-rTW/strings.xml index 4ff86fce..1717241f 100644 --- a/app/src/main/res/values-zh-rTW/strings.xml +++ b/app/src/main/res/values-zh-rTW/strings.xml @@ -320,6 +320,32 @@ Int 數值 Byte 數值,范圍 -128 到 127 數值無效 + 自訂 Vendor Key + 新增 Camera2 Vendor Key,並指定鏡頭 ID 或套用至所有鏡頭。已設定:%1$d + Vendor Key 與裝置相關,不支援的 Key 可能導致工作階段建立、預覽、錄影或拍攝失敗;出現問題時請刪除對應 Key。 + 尚未設定自訂 Vendor Key。 + 新增自訂 Key + 自訂 Vendor Key + Key 名稱 + 完整的 Camera2 Vendor Key 名稱,不允許包含空白字元。 + 請輸入不包含空白字元的 Key 名稱。 + 相同 Key 已用於同一範圍,或重疊範圍使用了不同的數值類型。 + Key 目標 + Capture Key + Session Key + 套用至預覽、錄影及靜態拍攝的 CaptureRequest Builder。 + 建立 Camera2 工作階段時套用;儲存變更後會重建目前工作階段。 + 數值類型 + int32 + u8 + 數值 + 有號 32 位元整數 + 無號 8 位元整數,範圍 0 到 255 + 數值超出所選類型的範圍。 + 鏡頭 ID + 所有鏡頭 + 鏡頭 ID:%1$s + %1$s · %2$s=%3$d · %4$s 銳化 增強圖像銳度和邊緣清晰度 降噪 diff --git a/app/src/main/res/values/strings.xml b/app/src/main/res/values/strings.xml index 40321c4d..7dae0246 100644 --- a/app/src/main/res/values/strings.xml +++ b/app/src/main/res/values/strings.xml @@ -322,6 +322,32 @@ Int value Byte value, -128 to 127 Invalid value + Custom Vendor Keys + Create Camera2 vendor keys and assign them to a lens or every lens. Configured: %1$d + Vendor keys are device-specific and may prevent a camera session or request from working. Remove an unsupported key if camera startup, preview, recording, or capture fails. + No custom vendor keys configured. + Add custom key + Custom Vendor Key + Key name + Full Camera2 vendor key name; whitespace is not allowed. + Enter a key name without whitespace. + This key already targets the same scope, or an overlapping scope uses a different value type. + Key target + Capture key + Session key + Applied to preview, video, and still CaptureRequest builders. + Applied when the Camera2 session is created. Saving a change recreates the active session. + Value type + int32 + u8 + Value + Signed 32-bit integer + Unsigned 8-bit integer, 0 to 255 + Value is outside the selected type range. + Lens ID + All lenses + Lens ID: %1$s + %1$s · %2$s=%3$d · %4$s Sharpening Enhance image sharpness and edge definition Noise Reduction diff --git a/app/src/test/java/com/hinnka/mycamera/camera/CustomVendorKeySettingsTest.kt b/app/src/test/java/com/hinnka/mycamera/camera/CustomVendorKeySettingsTest.kt new file mode 100644 index 00000000..1126e173 --- /dev/null +++ b/app/src/test/java/com/hinnka/mycamera/camera/CustomVendorKeySettingsTest.kt @@ -0,0 +1,105 @@ +package com.hinnka.mycamera.camera + +import org.junit.Assert.assertEquals +import org.junit.Assert.assertFalse +import org.junit.Assert.assertTrue +import org.junit.Test + +class CustomVendorKeySettingsTest { + @Test + fun keysFor_filtersTargetAndLensWithSpecificOverrideLast() { + val globalCapture = customKey( + id = "global", + value = 1, + lensId = null + ) + val lensCapture = customKey( + id = "lens", + value = 2, + lensId = "2" + ) + val otherLensCapture = customKey( + id = "other", + value = 3, + lensId = "3" + ) + val session = customKey( + id = "session", + value = 4, + lensId = "2", + target = CustomVendorKeyTarget.SESSION_PARAMETER + ) + val settings = CustomVendorKeySettings( + listOf(lensCapture, session, otherLensCapture, globalCapture) + ) + + assertEquals( + listOf(globalCapture, lensCapture), + settings.keysFor("2", CustomVendorKeyTarget.CAPTURE_REQUEST) + ) + assertEquals( + listOf(session), + settings.keysFor("2", CustomVendorKeyTarget.SESSION_PARAMETER) + ) + assertEquals( + listOf(globalCapture), + settings.keysFor("0", CustomVendorKeyTarget.CAPTURE_REQUEST) + ) + } + + @Test + fun u8NormalizationUsesUnsignedRangeWhileInt32IsUnchanged() { + assertEquals(0, CustomVendorKeyValueType.U8.normalize(-1)) + assertEquals(255, CustomVendorKeyValueType.U8.normalize(300)) + assertTrue(CustomVendorKeyValueType.U8.isValid(255)) + assertFalse(CustomVendorKeyValueType.U8.isValid(256)) + assertEquals(Int.MIN_VALUE, CustomVendorKeyValueType.INT32.normalize(Int.MIN_VALUE)) + assertEquals(Int.MAX_VALUE, CustomVendorKeyValueType.INT32.normalize(Int.MAX_VALUE)) + } + + @Test + fun upsertNormalizesFieldsAndRemoveUsesStableId() { + val original = customKey( + id = "stable", + value = 300, + lensId = " 2 ", + valueType = CustomVendorKeyValueType.U8, + keyName = " vendor.key " + ) + val inserted = CustomVendorKeySettings.Empty.upsert(original) + + assertEquals(1, inserted.keys.size) + assertEquals("vendor.key", inserted.keys.single().keyName) + assertEquals("2", inserted.keys.single().lensId) + assertEquals(255, inserted.keys.single().value) + assertFalse(inserted.remove("stable").isEnabled) + } + + @Test + fun invalidKeyNamesAreRejectedBeforeTheyCanReachCamera2() { + assertTrue(CustomVendorKey.isValidKeyName("com.vendor.control.mode")) + assertFalse(CustomVendorKey.isValidKeyName("")) + assertFalse(CustomVendorKey.isValidKeyName("com.vendor bad")) + + val settings = CustomVendorKeySettings.Empty.upsert( + customKey(id = "bad", value = 1, keyName = "com.vendor bad") + ) + assertFalse(settings.isEnabled) + } + + private fun customKey( + id: String, + value: Int, + lensId: String? = null, + target: CustomVendorKeyTarget = CustomVendorKeyTarget.CAPTURE_REQUEST, + valueType: CustomVendorKeyValueType = CustomVendorKeyValueType.INT32, + keyName: String = "com.vendor.control.mode" + ) = CustomVendorKey( + id = id, + keyName = keyName, + target = target, + valueType = valueType, + value = value, + lensId = lensId + ) +}