diff --git a/app/src/main/assets/dcp/Apple iPhone18,2 back camera Adobe Standard.dcp b/app/src/main/assets/dcp/Apple iPhone18,2 back camera Adobe Standard.dcp deleted file mode 100644 index c7fb2b26..00000000 Binary files a/app/src/main/assets/dcp/Apple iPhone18,2 back camera Adobe Standard.dcp and /dev/null differ diff --git a/app/src/main/assets/dcp/OnePlus 12 back camera 6.06mm f1.6 Adobe Standard.dcp b/app/src/main/assets/dcp/OnePlus 12 back camera 6.06mm f1.6 Adobe Standard.dcp deleted file mode 100644 index 164dfbc5..00000000 Binary files a/app/src/main/assets/dcp/OnePlus 12 back camera 6.06mm f1.6 Adobe Standard.dcp and /dev/null differ diff --git a/app/src/main/assets/dcp/Sony ILCE-7M4 Camera ST.dcp b/app/src/main/assets/dcp/Sony ILCE-7M4 Camera ST.dcp deleted file mode 100644 index 0be74e20..00000000 Binary files a/app/src/main/assets/dcp/Sony ILCE-7M4 Camera ST.dcp and /dev/null differ diff --git a/app/src/main/assets/device_configurations/oneplus_ace2.json b/app/src/main/assets/device_configurations/oneplus_ace2.json new file mode 100644 index 00000000..51042784 --- /dev/null +++ b/app/src/main/assets/device_configurations/oneplus_ace2.json @@ -0,0 +1,10 @@ +{ + "format": "photon_device_configuration", + "version": 1, + "name": "OnePlus Ace 2", + "manufacturer": "OnePlus", + "models": ["PHK110"], + "overrides": { + "raw_dcp_id": "builtin_dcp_OPPO Find X8 Ultra back camera 8.67mm f1.8 Adobe Standard" + } +} diff --git a/app/src/main/assets/device_configurations/oppo_x8_ultra.json b/app/src/main/assets/device_configurations/oppo_x8_ultra.json new file mode 100644 index 00000000..f9908b0d --- /dev/null +++ b/app/src/main/assets/device_configurations/oppo_x8_ultra.json @@ -0,0 +1,13 @@ +{ + "format": "photon_device_configuration", + "version": 1, + "name": "OPPO X8 Ultra", + "manufacturer": "OPPO", + "models": ["PKJ110", "PKU110"], + "overrides": { + "preferred_main_camera_id": "2", + "hdr_plus_frame_count": 8, + "raw_black_level_modes": { "2": "Custom", "3": "Custom", "4": "Custom" }, + "raw_custom_black_levels": { "2": 59, "3": 0, "4": 0 } + } +} diff --git a/app/src/main/assets/device_configurations/oppo_x9_ultra.json b/app/src/main/assets/device_configurations/oppo_x9_ultra.json new file mode 100644 index 00000000..a44a555b --- /dev/null +++ b/app/src/main/assets/device_configurations/oppo_x9_ultra.json @@ -0,0 +1,33 @@ +{ + "format": "photon_device_configuration", + "version": 1, + "name": "OPPO X9 Ultra", + "manufacturer": "OPPO", + "models": ["PMA110"], + "overrides": { + "preferred_main_camera_id": "2", + "hdr_plus_frame_count": 8, + "isz_lens_configs": [ + { + "base_camera_id": "2", + "isz_zoom_ratio": 2, + "vendor_capture_profile_id": "oplus_agingtest_mode_select_22", + "raw_black_border_crop_left_px": 508 + }, + { + "base_camera_id": "4", + "isz_zoom_ratio": 2, + "vendor_capture_profile_id": "oplus_agingtest_mode_select_19", + "raw_black_border_crop_left_px": 508 + } + ], + "vendor_capture_settings": { + "isz:2:2:oplus_agingtest_mode_select_22": { "oplus_agingtest_mode_select": 22 }, + "isz:4:2:oplus_agingtest_mode_select_19": { "oplus_agingtest_mode_select": 19 } + }, + "raw_noise_profile_ids_by_lens": { + "2": "builtin_noise_x9_ultra", + "4": "builtin_noise_x9_ultra_3x" + } + } +} diff --git a/app/src/main/java/com/hinnka/mycamera/data/BackupPreferenceSanitizer.kt b/app/src/main/java/com/hinnka/mycamera/data/BackupPreferenceSanitizer.kt index 828ecfcc..a64d8284 100644 --- a/app/src/main/java/com/hinnka/mycamera/data/BackupPreferenceSanitizer.kt +++ b/app/src/main/java/com/hinnka/mycamera/data/BackupPreferenceSanitizer.kt @@ -62,6 +62,7 @@ internal object BackupPreferenceSanitizer { "video_audio_input_id", "oppo_super_stabilization_enabled", "camera_startup_defaults_restored_v1", + BuiltInDeviceConfigurationMigration.APPLIED_DEVICE_KEY_NAME, ) private val deviceSpecificPresetFields = setOf( diff --git a/app/src/main/java/com/hinnka/mycamera/data/BuiltInDeviceConfigurationMigration.kt b/app/src/main/java/com/hinnka/mycamera/data/BuiltInDeviceConfigurationMigration.kt new file mode 100644 index 00000000..b6a1584f --- /dev/null +++ b/app/src/main/java/com/hinnka/mycamera/data/BuiltInDeviceConfigurationMigration.kt @@ -0,0 +1,108 @@ +package com.hinnka.mycamera.data + +import android.content.Context +import android.os.Build +import androidx.datastore.core.DataMigration +import androidx.datastore.preferences.core.Preferences +import androidx.datastore.preferences.core.stringPreferencesKey +import com.hinnka.mycamera.raw.DcpManager +import com.hinnka.mycamera.raw.RawNoiseProfileManager +import com.hinnka.mycamera.utils.PLog +import java.util.Locale + +/** Installs hardware defaults before any preference reader (including camera discovery) runs. */ +internal class BuiltInDeviceConfigurationMigration( + manufacturer: String, + model: String, + private val loadConfigurations: () -> List, + private val validateAssets: (DeviceConfiguration) -> Unit = {}, + private val onApplied: (DeviceConfiguration) -> Unit = {}, +) : DataMigration { + private val deviceManufacturer = manufacturer.trim().lowercase(Locale.ROOT) + private val deviceModel = model.trim().lowercase(Locale.ROOT) + private val deviceIdentity = "$deviceManufacturer/$deviceModel" + private var migratedConfiguration: DeviceConfiguration? = null + + private val matchingConfiguration: DeviceConfiguration? by lazy { + val configurations = loadConfigurations() + configurations.forEach { configuration -> + require(!configuration.manufacturer.isNullOrBlank() && configuration.models.isNotEmpty()) { + "Built-in configuration must declare manufacturer and models: ${configuration.name}" + } + } + val matches = configurations.filter { configuration -> + configuration.manufacturer?.trim()?.equals(deviceManufacturer, ignoreCase = true) == true && + configuration.models.any { it.equals(deviceModel, ignoreCase = true) } + } + require(matches.size <= 1) { "Multiple built-in configurations match $deviceIdentity" } + matches.singleOrNull() + } + + override suspend fun shouldMigrate(currentData: Preferences): Boolean { + if (currentData[APPLIED_DEVICE] == deviceIdentity) return false + return matchingConfiguration != null + } + + override suspend fun migrate(currentData: Preferences): Preferences { + if (currentData[APPLIED_DEVICE] == deviceIdentity) return currentData + val configuration = matchingConfiguration ?: return currentData + validateAssets(configuration) + return currentData.toMutablePreferences().apply { + DeviceConfigurationFields.apply(this, configuration) + this[APPLIED_DEVICE] = deviceIdentity + }.also { migratedConfiguration = configuration } + } + + override suspend fun cleanUp() { + migratedConfiguration?.let(onApplied) + migratedConfiguration = null + } + + companion object { + const val APPLIED_DEVICE_KEY_NAME = "builtin_device_configuration_applied_v1" + val APPLIED_DEVICE = stringPreferencesKey(APPLIED_DEVICE_KEY_NAME) + private const val ASSET_DIRECTORY = "device_configurations" + + fun create(context: Context): BuiltInDeviceConfigurationMigration { + val appContext = context.applicationContext + return BuiltInDeviceConfigurationMigration( + manufacturer = Build.MANUFACTURER, + model = Build.MODEL, + loadConfigurations = { + appContext.assets.list(ASSET_DIRECTORY).orEmpty() + .filter { it.endsWith(".json") }.sorted().map { file -> + appContext.assets.open("$ASSET_DIRECTORY/$file").use(DeviceConfiguration::read) + } + }, + validateAssets = { configuration -> + val overrides = configuration.overrides + fun requireProfiles(single: String, perLens: String, availableIds: () -> Set) { + val requested = buildList { + overrides[single]?.takeUnless { it.isJsonNull }?.let { add(it.asString) } + overrides[perLens]?.takeUnless { it.isJsonNull }?.asJsonObject + ?.entrySet()?.forEach { (_, value) -> + if (!value.isJsonNull) add(value.asString) + } + } + if (requested.isNotEmpty()) { + val missing = requested.toSet() - availableIds() + require(missing.isEmpty()) { "Missing built-in calibration assets: $missing" } + } + } + requireProfiles("raw_dcp_id", "raw_dcp_ids_by_lens") { + DcpManager(appContext).getAvailableDcps() + .filter { it.isBuiltIn }.map { it.id }.toSet() + } + requireProfiles("raw_noise_profile_id", "raw_noise_profile_ids_by_lens") { + RawNoiseProfileManager(appContext).getAvailableProfiles() + .filter { it.isBuiltIn && it.id != RawNoiseProfileManager.ADAPTIVE_PROFILE_ID } + .map { it.id }.toSet() + } + }, + onApplied = { configuration -> + PLog.i("DeviceConfiguration", "Applied built-in defaults: ${configuration.name} (${Build.MODEL})") + }, + ) + } + } +} diff --git a/app/src/main/java/com/hinnka/mycamera/data/DeviceConfiguration.kt b/app/src/main/java/com/hinnka/mycamera/data/DeviceConfiguration.kt new file mode 100644 index 00000000..745bcd11 --- /dev/null +++ b/app/src/main/java/com/hinnka/mycamera/data/DeviceConfiguration.kt @@ -0,0 +1,358 @@ +package com.hinnka.mycamera.data + +import androidx.datastore.preferences.core.MutablePreferences +import androidx.datastore.preferences.core.Preferences +import androidx.datastore.preferences.core.booleanPreferencesKey +import androidx.datastore.preferences.core.floatPreferencesKey +import androidx.datastore.preferences.core.intPreferencesKey +import androidx.datastore.preferences.core.stringPreferencesKey +import com.google.gson.GsonBuilder +import com.google.gson.JsonArray +import com.google.gson.JsonElement +import com.google.gson.JsonObject +import com.google.gson.JsonParser +import com.google.gson.JsonPrimitive +import com.google.gson.Strictness +import com.google.gson.stream.JsonReader +import com.google.gson.stream.JsonToken +import com.hinnka.mycamera.camera.CustomVendorKey +import com.hinnka.mycamera.camera.CustomFocalLengthValue +import com.hinnka.mycamera.camera.CustomVendorKeyTarget +import com.hinnka.mycamera.camera.CustomVendorKeyValueType +import com.hinnka.mycamera.camera.IszLensConfig +import com.hinnka.mycamera.camera.MultiFrameConfig +import com.hinnka.mycamera.camera.VendorCaptureKey +import com.hinnka.mycamera.camera.VendorCaptureSettings +import com.hinnka.mycamera.raw.RawCfaCorrection +import com.hinnka.mycamera.raw.RawRenderingEngine +import java.io.ByteArrayOutputStream +import java.io.InputStream + +/** A versioned, partial hardware configuration, independent of app backups and personal settings. */ +class DeviceConfiguration private constructor(private val document: JsonObject) { + val name: String get() = document["name"].asString + val manufacturer: String? get() = document["manufacturer"]?.asString + val models: List get() = document["models"]?.asJsonArray?.map { it.asString }.orEmpty() + val overrides: JsonObject get() = document["overrides"].asJsonObject.deepCopy() + + fun serialize(): String = GsonBuilder().setPrettyPrinting().serializeNulls().create().toJson(document) + + companion object { + const val MAX_FILE_BYTES = 1024 * 1024 + const val FORMAT = "photon_device_configuration" + + fun read(input: InputStream): DeviceConfiguration { + val output = ByteArrayOutputStream() + val buffer = ByteArray(8192) + while (true) { + val count = input.read(buffer) + if (count < 0) break + require(output.size() + count <= MAX_FILE_BYTES) { "Device configuration exceeds size limit" } + output.write(buffer, 0, count) + } + return parse(output.toString(Charsets.UTF_8.name())) + } + + fun parse(json: String): DeviceConfiguration { + val root = JsonReader(json.reader()).use { reader -> + reader.strictness = Strictness.STRICT + JsonParser.parseReader(reader).asJsonObject.also { + require(reader.peek() == JsonToken.END_DOCUMENT) + } + } + require(root.keySet().all { it in setOf("format", "version", "name", "manufacturer", "models", "model", "overrides") }) + require(root["format"].asString == FORMAT) + require(root["version"].isJsonPrimitive && root["version"].asJsonPrimitive.isNumber) + require(root["version"].asBigDecimal.intValueExact() == 1) + require(root["name"].isJsonPrimitive && root["name"].asJsonPrimitive.isString && root["name"].asString.isNotBlank()) + for (key in listOf("manufacturer", "model")) { + root[key]?.let { require(it.isJsonPrimitive && it.asJsonPrimitive.isString && it.asString.isNotBlank()) } + } + require(!(root.has("model") && root.has("models"))) { "Use either model or models, not both" } + // Accept existing single-model files, but keep one representation for built-in model matching. + root.remove("model")?.let { model -> + root.add("models", JsonArray().apply { add(model.asString.trim()) }) + } + root["models"]?.let { models -> + require(models.isJsonArray && models.asJsonArray.size() > 0) + models.asJsonArray.forEach { model -> + require(model.isJsonPrimitive && model.asJsonPrimitive.isString) + require(model.asString.isNotBlank() && model.asString == model.asString.trim()) + } + require(models.asJsonArray.map { it.asString }.distinct().size == models.asJsonArray.size()) + } + DeviceConfigurationFields.validate(root["overrides"].asJsonObject) + return DeviceConfiguration(root.deepCopy()) + } + } +} + +/** Each field owns its validation, persisted representation and partial-override semantics. */ +internal object DeviceConfigurationFields { + private enum class Storage { STRING, BOOLEAN, INT, FLOAT, CSV_LIST, CSV_MAP, JSON } + + private class Field( + val name: String, + val storage: Storage, + val validateValue: (JsonElement) -> Unit, + val merge: (JsonElement?, JsonElement) -> JsonElement = { _, incoming -> incoming }, + ) { + fun read(preferences: Preferences): JsonElement? = when (storage) { + Storage.BOOLEAN -> preferences[booleanPreferencesKey(name)]?.let(::JsonPrimitive) + Storage.INT -> preferences[intPreferencesKey(name)]?.let(::JsonPrimitive) + Storage.FLOAT -> preferences[floatPreferencesKey(name)]?.let(::JsonPrimitive) + else -> preferences[stringPreferencesKey(name)]?.let { stored -> + when (storage) { + Storage.CSV_LIST -> JsonArray().apply { + stored.split(',').filter(String::isNotEmpty).forEach { + add(when (name) { + "custom_focal_lengths" -> JsonPrimitive(requireNotNull(CustomFocalLengthValue.parsePersisted(it))) + "hidden_focal_lengths" -> JsonPrimitive(it.toFloat()) + else -> JsonPrimitive(it) + }) + } + } + Storage.CSV_MAP -> JsonObject().apply { + stored.split(',').filter(String::isNotEmpty).forEach { + val separator = it.lastIndexOf(':') + require(separator > 0) + val value = it.substring(separator + 1) + add(it.substring(0, separator), when (name) { + "camera_orientation_offsets" -> JsonPrimitive(value.toInt()) + "raw_custom_black_levels", "raw_custom_white_levels" -> JsonPrimitive(value.toFloat()) + else -> JsonPrimitive(value) + }) + } + } + Storage.JSON -> JsonParser.parseString(stored) + else -> JsonPrimitive(stored) + } + } + } + + fun write(preferences: MutablePreferences, incoming: JsonElement) { + if (incoming.isJsonNull) { + when (storage) { + Storage.BOOLEAN -> preferences.remove(booleanPreferencesKey(name)) + Storage.INT -> preferences.remove(intPreferencesKey(name)) + Storage.FLOAT -> preferences.remove(floatPreferencesKey(name)) + else -> preferences.remove(stringPreferencesKey(name)) + } + return + } + val value = merge(read(preferences), incoming) + when (storage) { + Storage.BOOLEAN -> preferences[booleanPreferencesKey(name)] = value.asBoolean + Storage.INT -> preferences[intPreferencesKey(name)] = value.asInt + Storage.FLOAT -> preferences[floatPreferencesKey(name)] = value.asFloat + else -> preferences[stringPreferencesKey(name)] = when (storage) { + Storage.CSV_LIST -> value.asJsonArray.joinToString(",") { it.asString } + Storage.CSV_MAP -> value.asJsonObject.entrySet().joinToString(",") { "${it.key}:${it.value.asString}" } + Storage.JSON -> value.toString() + else -> value.asString + } + } + } + } + + private fun text(value: JsonElement) { + require(value.isJsonPrimitive && value.asJsonPrimitive.isString && value.asString.isNotBlank()) + require(value.asString == value.asString.trim() && value.asString.none { it.isISOControl() || it == ',' }) + } + + private fun number(value: JsonElement, min: Float = 0f, max: Float = Float.MAX_VALUE) { + require(value.isJsonPrimitive && value.asJsonPrimitive.isNumber) + require(value.asFloat.isFinite() && value.asFloat in min..max) + } + + private fun integer(value: JsonElement, min: Int = Int.MIN_VALUE, max: Int = Int.MAX_VALUE): Int { + require(value.isJsonPrimitive && value.asJsonPrimitive.isNumber) + return value.asBigDecimal.intValueExact().also { require(it in min..max) } + } + + private fun choice(vararg values: String): (JsonElement) -> Unit = { value -> + text(value) + require(value.asString in values) + } + + private fun mergeMap(current: JsonElement?, incoming: JsonElement): JsonElement = + (current?.asJsonObject?.deepCopy() ?: JsonObject()).apply { + incoming.asJsonObject.entrySet().forEach { (key, value) -> + if (value.isJsonNull) remove(key) else add(key, value.deepCopy()) + } + } + + private fun mapField(name: String, json: Boolean = false, nullableValues: Boolean = false, + validateEntry: (JsonElement) -> Unit): Field = Field( + name, if (json) Storage.JSON else Storage.CSV_MAP, + validateValue = { value -> + require(value.isJsonObject) + value.asJsonObject.entrySet().forEach { (key, entry) -> + text(JsonPrimitive(key)) + if (!entry.isJsonNull) validateEntry(entry) + } + }, + merge = if (nullableValues) { current, incoming -> + (current?.asJsonObject?.deepCopy() ?: JsonObject()).apply { + incoming.asJsonObject.entrySet().forEach { (key, value) -> add(key, value.deepCopy()) } + } + } else ::mergeMap, + ) + + private fun stringField(name: String, validate: (JsonElement) -> Unit = ::text) = + Field(name, Storage.STRING, validate) + private fun booleanField(name: String) = Field(name, Storage.BOOLEAN, { + require(it.isJsonPrimitive && it.asJsonPrimitive.isBoolean) + }) + private fun listField(name: String, validateEntry: (JsonElement) -> Unit = ::text) = + Field(name, Storage.CSV_LIST, { value -> + require(value.isJsonArray) + value.asJsonArray.forEach(validateEntry) + require(value.asJsonArray.toList().distinct().size == value.asJsonArray.size()) + }) + + private fun mergeById(current: JsonElement?, incoming: JsonElement, id: (JsonElement) -> String): JsonElement { + val entries = current?.asJsonArray?.associateByTo(linkedMapOf(), id) ?: linkedMapOf() + incoming.asJsonArray.forEach { entries[id(it)] = it } + return JsonArray().apply { entries.values.forEach { add(it.deepCopy()) } } + } + + private val fields = listOf( + stringField("preferred_main_camera_id"), + Field("hdr_plus_frame_count", Storage.INT, { + integer(it, MultiFrameConfig.MIN_HDR_PLUS_FRAME_COUNT, MultiFrameConfig.MAX_FRAME_COUNT) + }), + stringField("preferred_macro_camera_id"), + listField("custom_lens_ids"), + listField("lens_id_blacklist"), + booleanField("enable_logical_multi_camera_discovery"), + listField("logical_camera_binding_whitelist") { + text(it) + require(it.asString.split('/').let { parts -> parts.size == 2 && parts.all(String::isNotBlank) && parts[0] != parts[1] }) + }, + Field("default_focal_length", Storage.FLOAT, { number(it, -Float.MAX_VALUE) }), + listField("custom_focal_lengths") { number(it, -Float.MAX_VALUE); require(it.asFloat != 0f) }, + listField("hidden_focal_lengths") { number(it); require(it.asFloat > 0f) }, + mapField("camera_orientation_offsets") { require(integer(it) in listOf(0, 90, 180, 270)) }, + mapField("raw_black_level_modes", validateEntry = choice("Default", "Custom")), + mapField("raw_custom_black_levels") { number(it, 0f, 65535f) }, + mapField("raw_white_level_modes", + validateEntry = choice("Default", "RAW10", "RAW12", "RAW14", "RAW_SENSOR_65535", "Custom")), + mapField("raw_custom_white_levels") { number(it, 0f, 65535f) }, + mapField("raw_cfa_correction_modes", validateEntry = choice(*RawCfaCorrection.allModes.toTypedArray())), + booleanField("raw_lens_shading_correction_enabled"), + stringField("raw_dcp_id"), + mapField("raw_dcp_ids_by_lens", json = true, nullableValues = true, validateEntry = ::text), + stringField("raw_noise_profile_id"), + mapField("raw_noise_profile_ids_by_lens", json = true, validateEntry = ::text), + stringField("raw_color_engine", choice(*RawRenderingEngine.entries.map { it.name }.toTypedArray())), + booleanField("use_p010"), + booleanField("use_p3_color_space"), + booleanField("oppo_super_stabilization_enabled"), + stringField("video_audio_input_id"), + Field("nr_level", Storage.INT, { integer(it, 0, 4) }), + Field("edge_level", Storage.INT, { integer(it, 0, 3) }), + Field("video_nr_level", Storage.INT, { integer(it, 0, 4) }), + Field("video_edge_level", Storage.INT, { integer(it, 0, 3) }), + Field("isz_lens_configs", Storage.JSON, ::validateIsz, + merge = { current, incoming -> mergeById(current, incoming, ::iszId) }), + mapField("vendor_capture_settings", json = true) { value -> + require(value.isJsonObject) + value.asJsonObject.entrySet().forEach { (name, entry) -> + val key = requireNotNull(VendorCaptureKey.fromPersistedName(name)) + val int = integer(entry) + require(key.normalizeValue(int) == int) + } + }, + Field("custom_vendor_key_settings", Storage.JSON, ::validateCustomVendorKeys, + merge = { current, incoming -> mergeById(current, incoming) { it.asJsonObject["id"].asString } }), + ).associateBy { it.name } + + fun validate(overrides: JsonObject) { + require(overrides.size() > 0) + overrides.entrySet().forEach { (key, value) -> + val field = requireNotNull(fields[key]) { "Unknown device setting: $key" } + if (!value.isJsonNull) { + try { field.validateValue(value) } catch (error: Exception) { + throw IllegalArgumentException("Invalid device setting: $key", error) + } + } + } + } + + fun apply(preferences: MutablePreferences, configuration: DeviceConfiguration) { + val overrides = configuration.overrides + validate(overrides) + overrides.entrySet().forEach { (name, value) -> fields.getValue(name).write(preferences, value) } + // Validate the resulting linked settings inside the same transaction; failures roll back every write. + if (overrides.has("custom_vendor_key_settings")) { + preferences[stringPreferencesKey("custom_vendor_key_settings")]?.let { + validateCustomVendorKeys(JsonParser.parseString(it)) + } + } + val lenses = overrides["isz_lens_configs"]?.takeUnless { it.isJsonNull }?.let { + IszLensConfig.deserializeList(it.toString()) + }.orEmpty() + val vendorSettings = preferences[stringPreferencesKey("vendor_capture_settings")] + ?.let { JsonParser.parseString(it).asJsonObject } + lenses.filter { it.vendorCaptureProfileId != null }.forEach { lens -> + val values = vendorSettings?.getAsJsonObject(lens.virtualCameraId)?.entrySet() + ?.associate { requireNotNull(VendorCaptureKey.fromPersistedName(it.key)) to it.value.asInt } + .orEmpty() + require(lens.vendorCaptureProfileId == VendorCaptureSettings(values).toVirtualLensProfileId()) { + "ISZ vendor profile does not match lens ${lens.virtualCameraId}" + } + } + } + + private fun iszId(value: JsonElement): String = IszLensConfig.deserializeList("[$value]").single().virtualCameraId + + private fun validateIsz(value: JsonElement) { + require(value.isJsonArray) + val ids = mutableSetOf() + value.asJsonArray.forEach { element -> + val lens = element.asJsonObject + val common = setOf("base_camera_id", "isz_zoom_ratio", "is_macro", "vendor_capture_profile_id") + val portrait = setOf("raw_black_border_crop_left_px", "raw_black_border_crop_top_px", "raw_black_border_crop_right_px", "raw_black_border_crop_bottom_px") + val sensor = setOf("raw_black_border_crop_sensor_left_px", "raw_black_border_crop_sensor_top_px", "raw_black_border_crop_sensor_right_px", "raw_black_border_crop_sensor_bottom_px") + require(lens.keySet().all { it in common || it in portrait || it in sensor }) + require(!(lens.keySet().any { it in portrait } && lens.keySet().any { it in sensor })) + text(lens["base_camera_id"]) + number(lens["isz_zoom_ratio"], 1f, 100f) + lens["is_macro"]?.let { require(it.isJsonPrimitive && it.asJsonPrimitive.isBoolean) } + lens["vendor_capture_profile_id"]?.let { + text(it) + require(IszLensConfig.sanitizeVendorCaptureProfileId(it.asString) == it.asString) + } + (portrait + sensor).forEach { key -> lens[key]?.let { integer(it, 0, 4096) } } + require(ids.add(iszId(element))) + } + } + + private fun validateCustomVendorKeys(value: JsonElement) { + require(value.isJsonArray) + val ids = mutableSetOf() + val validated = mutableListOf() + value.asJsonArray.forEach { element -> + val key = element.asJsonObject + require(key.keySet().all { it in setOf("id", "key_name", "target", "value_type", "value", "lens_id") }) + text(key["id"]) + require(ids.add(key["id"].asString)) + text(key["key_name"]) + require(CustomVendorKey.isValidKeyName(key["key_name"].asString)) + choice(*CustomVendorKeyTarget.entries.map { it.name }.toTypedArray())(key["target"]) + choice(*CustomVendorKeyValueType.entries.map { it.name }.toTypedArray())(key["value_type"]) + val type = CustomVendorKeyValueType.valueOf(key["value_type"].asString) + require(type.isValid(integer(key["value"]))) + key["lens_id"]?.takeUnless { it.isJsonNull }?.let(::text) + val lensId = key["lens_id"]?.takeUnless { it.isJsonNull }?.asString + require(validated.none { existing -> + val existingLensId = existing["lens_id"]?.takeUnless { it.isJsonNull }?.asString + existing["key_name"] == key["key_name"] && existing["target"] == key["target"] && + (existingLensId == lensId || + ((existingLensId == null || lensId == null) && existing["value_type"] != key["value_type"])) + }) { "Conflicting custom vendor keys" } + validated.add(key) + } + } +} 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 b0b71fbe..945d9e53 100644 --- a/app/src/main/java/com/hinnka/mycamera/data/UserPreferencesRepository.kt +++ b/app/src/main/java/com/hinnka/mycamera/data/UserPreferencesRepository.kt @@ -69,8 +69,11 @@ import org.json.JSONObject */ private val Context.dataStore: DataStore by preferencesDataStore( name = "user_preferences", - produceMigrations = { - listOf(OpenAiApiKeyEncryptionMigration()) + produceMigrations = { context -> + listOf( + OpenAiApiKeyEncryptionMigration(), + BuiltInDeviceConfigurationMigration.create(context), + ) }, ) diff --git a/app/src/main/java/com/hinnka/mycamera/processor/MultiFrameStacker.kt b/app/src/main/java/com/hinnka/mycamera/processor/MultiFrameStacker.kt index 447fd0ec..3bed0f8b 100644 --- a/app/src/main/java/com/hinnka/mycamera/processor/MultiFrameStacker.kt +++ b/app/src/main/java/com/hinnka/mycamera/processor/MultiFrameStacker.kt @@ -38,7 +38,7 @@ enum class MgcRawMaxMode { SPATIAL; companion object { - val DEFAULT: MgcRawMaxMode = SPATIAL + val DEFAULT: MgcRawMaxMode = SABRE } val supportsBracketExposure: Boolean diff --git a/app/src/test/java/com/hinnka/mycamera/data/BackupPreferenceSanitizerTest.kt b/app/src/test/java/com/hinnka/mycamera/data/BackupPreferenceSanitizerTest.kt index 65b347d6..329f1436 100644 --- a/app/src/test/java/com/hinnka/mycamera/data/BackupPreferenceSanitizerTest.kt +++ b/app/src/test/java/com/hinnka/mycamera/data/BackupPreferenceSanitizerTest.kt @@ -71,6 +71,7 @@ class BackupPreferenceSanitizerTest { PreferenceMap.newBuilder() .putPreferences("preferred_main_camera_id", stringValue("backup-camera")) .putPreferences("raw_dcp_ids_by_lens", stringValue("backup-dcp-map")) + .putPreferences(BuiltInDeviceConfigurationMigration.APPLIED_DEVICE_KEY_NAME, stringValue("oppo/pma110")) .putPreferences("raw_color_engine", stringValue("HncsLut")) .putPreferences("custom_lens_ids", stringValue("backup-custom-lens")) .putPreferences("photo_save_path", stringValue("BACKUP_PATH")) @@ -91,6 +92,7 @@ class BackupPreferenceSanitizerTest { PreferenceMap.newBuilder() .putPreferences("preferred_main_camera_id", stringValue("current-camera")) .putPreferences("raw_dcp_ids_by_lens", stringValue("current-dcp-map")) + .putPreferences(BuiltInDeviceConfigurationMigration.APPLIED_DEVICE_KEY_NAME, stringValue("oppo/pkj110")) .putPreferences("raw_color_engine", stringValue("AdobeCurve")) .putPreferences("photo_save_path", stringValue("CURRENT_PATH")) .putPreferences( @@ -111,6 +113,7 @@ class BackupPreferenceSanitizerTest { val sanitizedMap = FileInputStream(restoredPreferencesFile).use(PreferenceMap::parseFrom) assertEquals("current-camera", sanitizedMap.preferencesMap.getValue("preferred_main_camera_id").string) assertEquals("current-dcp-map", sanitizedMap.preferencesMap.getValue("raw_dcp_ids_by_lens").string) + assertEquals("oppo/pkj110", sanitizedMap.preferencesMap.getValue(BuiltInDeviceConfigurationMigration.APPLIED_DEVICE_KEY_NAME).string) assertEquals("AdobeCurve", sanitizedMap.preferencesMap.getValue("raw_color_engine").string) assertEquals("CURRENT_PATH", sanitizedMap.preferencesMap.getValue("photo_save_path").string) assertFalse(sanitizedMap.containsPreferences("custom_lens_ids")) diff --git a/app/src/test/java/com/hinnka/mycamera/data/BuiltInDeviceConfigurationMigrationTest.kt b/app/src/test/java/com/hinnka/mycamera/data/BuiltInDeviceConfigurationMigrationTest.kt new file mode 100644 index 00000000..80ac0a02 --- /dev/null +++ b/app/src/test/java/com/hinnka/mycamera/data/BuiltInDeviceConfigurationMigrationTest.kt @@ -0,0 +1,137 @@ +package com.hinnka.mycamera.data + +import androidx.datastore.preferences.core.PreferenceDataStoreFactory +import androidx.datastore.preferences.core.booleanPreferencesKey +import androidx.datastore.preferences.core.edit +import androidx.datastore.preferences.core.emptyPreferences +import androidx.datastore.preferences.core.mutablePreferencesOf +import androidx.datastore.preferences.core.stringPreferencesKey +import kotlinx.coroutines.CoroutineScope +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.SupervisorJob +import kotlinx.coroutines.cancelAndJoin +import kotlinx.coroutines.flow.first +import kotlinx.coroutines.runBlocking +import org.junit.Assert.* +import org.junit.Rule +import org.junit.Test +import org.junit.rules.TemporaryFolder +import java.io.File + +class BuiltInDeviceConfigurationMigrationTest { + @get:Rule val temporaryFolder = TemporaryFolder() + + private fun configurations(): List = + File("src/main/assets/device_configurations").listFiles()!! + .filter { it.extension == "json" }.map { it.inputStream().use(DeviceConfiguration::read) } + + @Test + fun firstDatastoreEmissionIncludesDefaultsAndRestartPreservesUserChanges() = runBlocking { + val file = File(temporaryFolder.root, "startup.preferences_pb") + val firstJob = SupervisorJob() + val firstStore = PreferenceDataStoreFactory.create( + migrations = listOf(BuiltInDeviceConfigurationMigration("OPPO", "PMA110", ::configurations)), + scope = CoroutineScope(firstJob + Dispatchers.IO), + produceFile = { file }, + ) + try { + val firstPreferences = firstStore.data.first() + assertEquals("2", firstPreferences[stringPreferencesKey("preferred_main_camera_id")]) + assertEquals("oppo/pma110", firstPreferences[BuiltInDeviceConfigurationMigration.APPLIED_DEVICE]) + assertNotNull(firstPreferences[stringPreferencesKey("isz_lens_configs")]) + assertNotNull(firstPreferences[stringPreferencesKey("raw_noise_profile_ids_by_lens")]) + firstStore.edit { + it[stringPreferencesKey("preferred_main_camera_id")] = "0" + it.remove(stringPreferencesKey("isz_lens_configs")) + it[booleanPreferencesKey("show_grid")] = true + } + } finally { + firstJob.cancelAndJoin() + } + + val restartJob = SupervisorJob() + val restartedStore = PreferenceDataStoreFactory.create( + migrations = listOf(BuiltInDeviceConfigurationMigration("oppo", "pma110", { + error("An applied device must not reload or reapply defaults on restart") + })), + scope = CoroutineScope(restartJob + Dispatchers.IO), + produceFile = { file }, + ) + try { + val preferences = restartedStore.data.first() + assertEquals("0", preferences[stringPreferencesKey("preferred_main_camera_id")]) + assertNull(preferences[stringPreferencesKey("isz_lens_configs")]) + assertEquals(true, preferences[booleanPreferencesKey("show_grid")]) + } finally { + restartJob.cancelAndJoin() + } + } + + @Test + fun bothX8ModelsMatchWithNormalizedDeviceIdentity() = runBlocking { + for (model in listOf("PKJ110", " pku110 ")) { + val migration = BuiltInDeviceConfigurationMigration(" OPPO ", model, ::configurations) + assertTrue(migration.shouldMigrate(emptyPreferences())) + val preferences = migration.migrate(mutablePreferencesOf(booleanPreferencesKey("show_grid") to true)) + assertEquals("2", preferences[stringPreferencesKey("preferred_main_camera_id")]) + assertEquals("2:59,3:0,4:0", preferences[stringPreferencesKey("raw_custom_black_levels")]) + assertEquals(true, preferences[booleanPreferencesKey("show_grid")]) + assertFalse(migration.shouldMigrate(preferences)) + } + } + + @Test + fun unknownDeviceOrDifferentManufacturerDoesNotReceiveDefaults() = runBlocking { + for ((manufacturer, model) in listOf("OPPO" to "PMA110-extra", "Other" to "PMA110", "OPPO" to "")) { + val migration = BuiltInDeviceConfigurationMigration(manufacturer, model, ::configurations) + val current = mutablePreferencesOf(stringPreferencesKey("preferred_main_camera_id") to "custom") + assertFalse(migration.shouldMigrate(current)) + assertEquals(current, migration.migrate(current)) + assertNull(current[BuiltInDeviceConfigurationMigration.APPLIED_DEVICE]) + } + } + + @Test + fun duplicateMatchesAndMissingHardwareIdentityAreRejected() = runBlocking { + val x9 = configurations().first { "PMA110" in it.models } + val duplicate = BuiltInDeviceConfigurationMigration("OPPO", "PMA110", { listOf(x9, x9) }) + try { + duplicate.shouldMigrate(emptyPreferences()) + fail("Expected duplicate match rejection") + } catch (_: IllegalArgumentException) { } + val generic = DeviceConfiguration.parse("""{ + "format":"photon_device_configuration","version":1,"name":"Generic", + "overrides":{"preferred_main_camera_id":"2"} + }""") + val missingIdentity = BuiltInDeviceConfigurationMigration("OPPO", "PMA110", { listOf(generic) }) + try { + missingIdentity.shouldMigrate(emptyPreferences()) + fail("Expected missing hardware identity rejection") + } catch (_: IllegalArgumentException) { } + } + + @Test + fun failedAssetValidationDoesNotCommitAnAppliedMarkerAndCanRetry() = runBlocking { + var missingAsset = true + var appliedCount = 0 + val migration = BuiltInDeviceConfigurationMigration( + "OPPO", "PMA110", ::configurations, + validateAssets = { require(!missingAsset) }, + onApplied = { appliedCount++ }, + ) + val current = mutablePreferencesOf(stringPreferencesKey("preferred_main_camera_id") to "0") + try { + migration.migrate(current) + fail("Expected asset validation failure") + } catch (_: IllegalArgumentException) { } + assertEquals("0", current[stringPreferencesKey("preferred_main_camera_id")]) + assertNull(current[BuiltInDeviceConfigurationMigration.APPLIED_DEVICE]) + assertEquals(0, appliedCount) + assertTrue(migration.shouldMigrate(current)) + missingAsset = false + val applied = migration.migrate(current) + migration.cleanUp() + assertEquals("2", applied[stringPreferencesKey("preferred_main_camera_id")]) + assertEquals(1, appliedCount) + } +} diff --git a/app/src/test/java/com/hinnka/mycamera/data/DeviceConfigurationTest.kt b/app/src/test/java/com/hinnka/mycamera/data/DeviceConfigurationTest.kt new file mode 100644 index 00000000..5fe086ae --- /dev/null +++ b/app/src/test/java/com/hinnka/mycamera/data/DeviceConfigurationTest.kt @@ -0,0 +1,176 @@ +package com.hinnka.mycamera.data + +import androidx.datastore.preferences.core.PreferenceDataStoreFactory +import androidx.datastore.preferences.core.booleanPreferencesKey +import androidx.datastore.preferences.core.edit +import androidx.datastore.preferences.core.floatPreferencesKey +import androidx.datastore.preferences.core.mutablePreferencesOf +import androidx.datastore.preferences.core.stringPreferencesKey +import com.google.gson.JsonParser +import com.hinnka.mycamera.camera.IszLensConfig +import com.hinnka.mycamera.camera.RawBlackBorderCrop +import kotlinx.coroutines.CoroutineScope +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.SupervisorJob +import kotlinx.coroutines.cancel +import kotlinx.coroutines.flow.first +import kotlinx.coroutines.runBlocking +import org.junit.Assert.* +import org.junit.Rule +import org.junit.Test +import org.junit.rules.TemporaryFolder +import java.io.File + +class DeviceConfigurationTest { + @get:Rule val temporaryFolder = TemporaryFolder() + + private fun configuration(overrides: String): DeviceConfiguration = DeviceConfiguration.parse( + """{"format":"photon_device_configuration","version":1,"name":"Example","overrides":$overrides}""", + ) + + private fun builtIn(name: String): DeviceConfiguration = + File("src/main/assets/device_configurations/$name.json").inputStream().use(DeviceConfiguration::read) + + @Test + fun multipleModelsAndLegacySingleModelUseTheSameRepresentation() { + val x8 = builtIn("oppo_x8_ultra") + assertEquals(listOf("PKJ110", "PKU110"), x8.models) + assertEquals(x8.models, DeviceConfiguration.parse(x8.serialize()).models) + assertEquals(listOf("PMA110"), builtIn("oppo_x9_ultra").models) + + val legacy = DeviceConfiguration.parse( + """{"format":"photon_device_configuration","version":1,"name":"Legacy","model":"PKJ110","overrides":{"preferred_main_camera_id":"2"}}""", + ) + assertEquals(listOf("PKJ110"), legacy.models) + val serialized = JsonParser.parseString(legacy.serialize()).asJsonObject + assertFalse(serialized.has("model")) + assertEquals("PKJ110", serialized["models"].asJsonArray.single().asString) + assertTrue(configuration("""{"preferred_main_camera_id":"2"}""").models.isEmpty()) + } + + @Test + fun rejectsInvalidOrAmbiguousModelLists() { + listOf( + """"models":"PKJ110"""", + """"models":[]""", + """"models":null""", + """"models":[" "]""", + """"models":[" PKJ110"]""", + """"models":[110]""", + """"models":[null]""", + """"models":["PKJ110","PKJ110"]""", + """"model":"PKJ110","models":["PKU110"]""", + ).forEach { metadata -> + assertThrows(Exception::class.java) { + DeviceConfiguration.parse( + """{"format":"photon_device_configuration","version":1,"name":"Invalid",$metadata,"overrides":{"preferred_main_camera_id":"2"}}""", + ) + } + } + } + + @Test + fun builtInsApplyExactValuesAndPreserveUnspecifiedSettings() { + val preferences = mutablePreferencesOf( + booleanPreferencesKey("show_grid") to true, + stringPreferencesKey("raw_custom_black_levels") to "99:20.0", + ) + DeviceConfigurationFields.apply(preferences, builtIn("oppo_x8_ultra")) + assertEquals("2", preferences[stringPreferencesKey("preferred_main_camera_id")]) + assertEquals("99:20.0,2:59,3:0,4:0", preferences[stringPreferencesKey("raw_custom_black_levels")]) + assertEquals("2:Custom,3:Custom,4:Custom", preferences[stringPreferencesKey("raw_black_level_modes")]) + assertEquals(true, preferences[booleanPreferencesKey("show_grid")]) + + val x9 = builtIn("oppo_x9_ultra") + DeviceConfigurationFields.apply(preferences, x9) + val firstApply = preferences.toPreferences() + DeviceConfigurationFields.apply(preferences, x9) + assertEquals(firstApply, preferences.toPreferences()) + val lenses = IszLensConfig.deserializeList(preferences[stringPreferencesKey("isz_lens_configs")]) + assertEquals(listOf("2", "4"), lenses.map { it.baseCameraId }) + assertEquals(listOf(2f, 2f), lenses.map { it.iszZoomRatio }) + assertEquals(listOf("oplus_agingtest_mode_select_22", "oplus_agingtest_mode_select_19"), lenses.map { it.vendorCaptureProfileId }) + lenses.forEach { + assertEquals(RawBlackBorderCrop(leftPx = 508), it.migrateLegacyPortraitCrop(90).rawBlackBorderCropForPortraitDisplay(90)) + } + val noise = JsonParser.parseString(preferences[stringPreferencesKey("raw_noise_profile_ids_by_lens")]).asJsonObject + assertEquals("builtin_noise_x9_ultra", noise["2"].asString) + assertEquals("builtin_noise_x9_ultra_3x", noise["4"].asString) + } + + @Test + fun mapRemovalDcpDisableAndScalarResetRemainDistinct() { + val preferences = mutablePreferencesOf( + stringPreferencesKey("raw_custom_black_levels") to "2:10.0,3:20.0", + stringPreferencesKey("raw_dcp_ids_by_lens") to """{"2":"old","3":"keep"}""", + stringPreferencesKey("preferred_macro_camera_id") to "4", + ) + DeviceConfigurationFields.apply(preferences, configuration("""{ + "raw_custom_black_levels":{"2":null,"4":0}, + "raw_dcp_ids_by_lens":{"2":null}, + "preferred_macro_camera_id":null + }""")) + assertEquals("3:20.0,4:0", preferences[stringPreferencesKey("raw_custom_black_levels")]) + val dcp = JsonParser.parseString(preferences[stringPreferencesKey("raw_dcp_ids_by_lens")]).asJsonObject + assertTrue(dcp["2"].isJsonNull) + assertEquals("keep", dcp["3"].asString) + assertNull(preferences[stringPreferencesKey("preferred_macro_camera_id")]) + } + + @Test + fun applyingConfigurationHandlesLegacyZoomEncodingAndVirtualLensMapKeys() { + val preferences = mutablePreferencesOf( + floatPreferencesKey("default_focal_length") to -2f, + stringPreferencesKey("custom_focal_lengths") to "2x,35,1.5x", + stringPreferencesKey("raw_custom_black_levels") to "isz:2:2:profile:59.0", + stringPreferencesKey("openai_api_key_encrypted_v1") to "private", + ) + DeviceConfigurationFields.apply(preferences, configuration("""{ + "custom_focal_lengths":[-2,35,-1.5], + "raw_custom_black_levels":{"2":60} + }""")) + assertEquals("-2,35,-1.5", preferences[stringPreferencesKey("custom_focal_lengths")]) + assertEquals(-2f, preferences[floatPreferencesKey("default_focal_length")]) + assertEquals("isz:2:2:profile:59.0,2:60", preferences[stringPreferencesKey("raw_custom_black_levels")]) + assertEquals("private", preferences[stringPreferencesKey("openai_api_key_encrypted_v1")]) + } + + @Test + fun rejectsInvalidValuesAndUnrecognizedFieldsBeforeApplying() { + listOf( + """{"openai_api_key":"no"}""", + """{"preferred_main_camera_id":2}""", + """{"use_p010":"true"}""", + """{"nr_level":1.5}""", + """{"raw_custom_black_levels":{"2":-1}}""", + """{"vendor_capture_settings":{"2":{"oplus_agingtest_mode_select":128}}}""", + """{"isz_lens_configs":[{"base_camera_id":"2","isz_zoom_ratio":2,"raw_black_border_crop_left_px":508,"raw_black_border_crop_sensor_left_px":508}]}""", + ).forEach { invalid -> assertThrows(Exception::class.java) { configuration(invalid) } } + assertThrows(Exception::class.java) { DeviceConfiguration.parse(builtIn("oppo_x8_ultra").serialize().replace("\"version\": 1", "\"version\": 2")) } + assertThrows(Exception::class.java) { configuration("{use_p010:true}") } + assertThrows(Exception::class.java) { DeviceConfiguration.read(ByteArray(DeviceConfiguration.MAX_FILE_BYTES + 1) { 32 }.inputStream()) } + } + + @Test + fun inconsistentIszVendorProfileRollsBackWholeDatastoreTransaction() = runBlocking { + val scope = CoroutineScope(SupervisorJob() + Dispatchers.IO) + val store = PreferenceDataStoreFactory.create(scope = scope) { + File(temporaryFolder.root, "device.preferences_pb") + } + try { + store.edit { it[stringPreferencesKey("preferred_main_camera_id")] = "0" } + val before = store.data.first() + val inconsistent = configuration("""{ + "preferred_main_camera_id":"2", + "isz_lens_configs":[{"base_camera_id":"2","isz_zoom_ratio":2,"vendor_capture_profile_id":"oplus_agingtest_mode_select_22"}] + }""") + try { + store.edit { DeviceConfigurationFields.apply(it, inconsistent) } + fail("Expected mismatched ISZ configuration to be rejected") + } catch (_: IllegalArgumentException) { } + assertEquals(before, store.data.first()) + } finally { + scope.cancel() + } + } +} diff --git a/docs/device-configurations.md b/docs/device-configurations.md new file mode 100644 index 00000000..8d2fea57 --- /dev/null +++ b/docs/device-configurations.md @@ -0,0 +1,187 @@ +# 设备覆盖配置 + +设备覆盖配置用于为已知机型提供相机、RAW、视频或厂商参数覆盖。配置文件随应用打包在 `app/src/main/assets/device_configurations/*.json`,应用启动时按设备信息自动选择并默认应用;不存在用户配置选择、导入或导出入口。JSON 是开发者维护的随包格式,不是面向用户的设置文件。 + +仓库内的完整示例: + +- [全字段 demo](examples/device-configuration.full.json):包含当前支持的全部 33 个覆盖字段、多型号、两种裁切坐标和完整的镜头关联。该文件只用于文档和开发参考,不会被打包,也不会自动加载。示例说明见下节。 +- [OPPO X8 Ultra](../app/src/main/assets/device_configurations/oppo_x8_ultra.json):`models` 为 `["PKJ110", "PKU110"]`,普通版与卫星通信版共用一份配置([普通版官方参数](https://www.oppo.com/cn/smartphones/series-find-x/find-x8-ultra/specs/)、[卫星通信版官方参数](https://www.oppo.com/cn/smartphones/series-find-x/find-x8-ultra-satellite/specs/))。 +- [OPPO X9 Ultra](../app/src/main/assets/device_configurations/oppo_x9_ultra.json):`models` 为 `["PMA110"]`。 +- [OnePlus Ace 2](../app/src/main/assets/device_configurations/oneplus_ace2.json):`manufacturer` 为 `OnePlus`,`models` 为 `["PHK110"]`([设备信息](https://gitlab.com/fdroid/fdroidclient/-/issues/2837));默认 DCP 为 `OPPO Find X8 Ultra back camera 8.67mm f1.8 Adobe Standard.dcp`。 + +## 全字段 demo + +[device-configuration.full.json](examples/device-configuration.full.json) 是不含注释的纯 JSON 示例,放在文档目录中,不会作为内置机型配置显示、打包或自动加载。它用于展示写法,参数组合不是任何真实机型的适配结果。开发者使用时应将其复制到 `assets/device_configurations/`,把 `manufacturer`、`models`、镜头 ID 和校准值换成目标设备的实际值,再删除不需要覆盖的字段。 + +示例包含以下关联和取值方式: + +- **多型号与镜头发现**:`DEMO_MODEL_A`、`DEMO_MODEL_B` 共用全部设置。主摄为 `2`,微距为 `4`;`0/2` 表示逻辑镜头 `0` 绑定物理镜头 `2`。自动逻辑多摄发现关闭时,显式白名单仍生效。`99` 仅演示黑名单。 +- **焦段**:`default_focal_length: -2` 表示默认 2×,`custom_focal_lengths` 中正数为 35mm 等效毫米数,负数绝对值为倍率;`hidden_focal_lengths` 使用正数毫米值。默认焦段也可用 `0` 表示不指定。 +- **RAW 校正**:分别为物理镜头和 ISZ 虚拟镜头指定黑电平、白电平及 CFA。选择 `Custom` 时,同一镜头应在对应的 `raw_custom_*_levels` 中提供实际校准值;选择 `Default` 时使用原始元数据。 +- **DCP 与降噪**:引用的是仓库中实际存在的内置资源 ID,仅演示引用格式,不代表适合 demo 的传感器。物理镜头和 ISZ 的模型映射分别填写;ISZ 不会自动继承物理镜头的降噪映射。`raw_dcp_ids_by_lens` 中镜头 `3` 的 `null` 表示关闭该镜头的 DCP,不是回退到全局 DCP。 +- **两种 ISZ 裁切坐标**:镜头 `2` 演示竖屏左侧裁切 508,镜头 `4` 演示传感器底部裁切 508。两种写法位于不同镜头对象中;它们只有在传感器方向为 90° 时才表示相同的边。`is_macro: true` 演示将第二个虚拟镜头设为微距。 +- **厂商参数关联**:两个 ISZ 的 `vendor_capture_profile_id` 与虚拟镜头 ID、`vendor_capture_settings` 一一对应。demo 同时列出 Qualcomm、vivo、MediaTek、OPPO 五种内置键;实际机型配置只保留该设备支持的键,不能把这组跨厂商示例当成通用参数一起启用。 +- **自定义键**:`com.example.*` 是需要替换的示例键名,展示拍摄请求/会话参数、`INT32`/`U8`、全局/物理镜头/ISZ 作用域。同名拍摄键在全局值为 `1`,镜头 `2` 的同类型覆盖值为 `2`;条目的稳定 `id` 不同。 +- **删除映射**:普通 map 中的 `legacy_lens: null` 用于移除已有条目;未出现该条目时无操作。`video_audio_input_id: "auto"` 使用系统自动选择的音频输入。 + +要重置整项设置,可将对应字段改为 `null`,例如: + +```json +{ + "format": "photon_device_configuration", + "version": 1, + "name": "Reset selected device overrides", + "manufacturer": "DEMO", + "models": ["DEMO_MODEL_A", "DEMO_MODEL_B"], + "overrides": { + "preferred_macro_camera_id": null, + "raw_dcp_ids_by_lens": null, + "custom_vendor_key_settings": null + } +} +``` + +只需保留当前值时,直接省略字段;`null` 会重置,不能用来表达“保持不变”。普通列表的 `[]` 会清空列表,而按 ID 合并的 ISZ/自定义厂商键数组的 `[]` 不会删除已有条目。 + +## 文件格式 + +文件必须是一个 JSON 对象,格式如下: + +```json +{ + "format": "photon_device_configuration", + "version": 1, + "name": "配置名称", + "manufacturer": "厂商", + "models": ["PKJ110", "PKU110"], + "overrides": { + "字段名": "字段值" + } +} +``` + +顶层只允许 `format`、`version`、`name`、`manufacturer`、`models`、旧字段 `model` 和 `overrides`。`format` 必须是 `photon_device_configuration`,`version` 当前必须是数字 `1`;`name` 必须是非空字符串,`manufacturer` 必须声明且为非空字符串。`overrides` 必须是包含至少一个字段的对象。 + +`models` 是必需的设备型号代码数组,一份配置中的全部覆盖设置共同适用于列出的型号。数组不能为空,每项必须是非空字符串、无首尾空格,且不可重复。`manufacturer` 与 `models` 必须同时声明,不能创建只有厂商或只有型号的通配配置。 + +已有开发者文件中的单型号字符串 `model` 仅为内部解析兼容字段,读取时转换为单元素 `models` 数组;不允许同时提供 `model` 和 `models`。新文件必须使用 `models`,应用不会生成或导出此格式。 + +内置文件最大为 1 MiB。未知顶层字段、未知覆盖字段、未知版本、JSON 语法错误或任何不符合下表类型/范围的值都会拒绝整个文件,不会部分应用。 + +### 自动匹配和应用 + +应用在首次读取设备配置 DataStore、发现镜头之前,读取 `Build.MANUFACTURER` 和 `Build.MODEL`,分别 trim 后按大小写不敏感规则与配置的 `manufacturer` 和 `models` 匹配。只有厂商和型号都声明且同时匹配的配置才算匹配。 + +全部内置文件中必须恰好有一份匹配:没有匹配时不修改任何现有设置;恰好一份匹配时,在一次事务内应用该文件声明的覆盖并写入“本设备已应用”标记;重复匹配属于配置错误,不能依赖文件顺序选择。后续启动只依据该标记跳过自动覆盖,不重写用户手动修改的设置。应用配置文件的内容发生变化,也不会自动重写已经标记为已应用的设备;当前没有新增版本或重新应用机制。 + +“本设备已应用”标记属于设备本地状态。跨设备恢复设置时必须保留目标设备自己的标记,不能用源设备的已应用状态替换它。 + +### 合并和重置 + +配置是覆盖集合,不要求包含所有设置。标量字段只覆盖自己;写入 `null` 会移除该字段当前保存的显式值,使其回到应用默认或其他基础设置。 + +普通列表字段(`custom_lens_ids`、`lens_id_blacklist`、`logical_camera_binding_whitelist`、`custom_focal_lengths`、`hidden_focal_lengths`)整体替换当前列表;列表元素不可重复。列表字段写入 `null` 会重置整个字段。 + +普通 map 字段按镜头 ID 合并:只更新文件中列出的镜头键,值为 `null` 的键会删除当前镜头条目。`raw_dcp_ids_by_lens` 是例外:它允许镜头值为 `null`,该 `null` 表示明确禁用该镜头的 DCP 映射;整个字段写入 `null` 才会重置整张 map。其他 map 字段中的 `null` 表示删除对应镜头键。 + +`isz_lens_configs` 和 `custom_vendor_key_settings` 是按稳定 ID 合并的数组:同一 ID 的条目更新原条目,未出现的条目保留;字段整体写入 `null` 会清空整个数组。`isz_lens_configs` 的稳定 ID 是由 `base_camera_id`、`isz_zoom_ratio` 和 `vendor_capture_profile_id` 生成的虚拟镜头 ID;自定义厂商键使用条目的 `id`。 + +`vendor_capture_settings` 按镜头 ID 合并,但每个镜头对应的对象是整体替换;镜头值为 `null` 会删除该镜头的厂商设置。其对象内部不能用 `null` 删除单个厂商键。字段整体写入 `null` 会重置全部镜头设置。 + +自动应用覆盖时会在同一事务内验证结果;如果 ISZ 镜头配置与对应镜头的厂商 profile 不一致,整次应用回滚。DCP、降噪 profile 等引用必须指向随应用打包的内置资源;维护机型配置时应同时提交所需资源,不能依赖用户导入或自定义模型。 + +## 支持的覆盖字段 + +下表中的覆盖字段字符串(以及 map 的镜头 ID)必须非空、首尾不能有空格,且不能包含逗号或控制字符;JSON 数字必须是有限值。顶层元数据仅适用上一节所述的顶层规则。 + +| 字段 | JSON 类型 | 取值和说明 | +| --- | --- | --- | +| `preferred_main_camera_id` | string | 主摄 Camera ID。 | +| `hdr_plus_frame_count` | integer | HDR+ 总帧数,范围 `1..20`;开启包围曝光时实际最少为 2 帧。X8 Ultra、X9 Ultra 内置为 8 帧。 | +| `preferred_macro_camera_id` | string | 微距 Camera ID。 | +| `custom_lens_ids` | array of string | 自定义镜头 ID 列表。 | +| `lens_id_blacklist` | array of string | 从所有发现来源中排除的镜头 ID 列表。 | +| `enable_logical_multi_camera_discovery` | boolean | 是否启用逻辑多摄发现。 | +| `logical_camera_binding_whitelist` | array of string | 每项必须是 `逻辑ID/物理ID`,两部分均非空且不能相同。 | +| `default_focal_length` | number | 有限数值;负数表示精确倍率,`0` 表示不指定,正数表示等效焦距。 | +| `custom_focal_lengths` | array of number | 自定义焦距;有限数值,范围 `[-Float.MAX_VALUE..Float.MAX_VALUE]`,不能为 `0`。 | +| `hidden_focal_lengths` | array of number | 要隐藏的焦距;有限正数,范围 `(0..Float.MAX_VALUE]`。 | +| `camera_orientation_offsets` | object<string, integer> | 按镜头 ID 的方向偏移;值只能是 `0`、`90`、`180` 或 `270` 度。 | +| `raw_black_level_modes` | object<string, string> | 每个镜头为 `Default` 或 `Custom`。 | +| `raw_custom_black_levels` | object<string, number> | 每个镜头的黑电平,范围 `0..65535`。 | +| `raw_white_level_modes` | object<string, string> | 每个镜头为 `Default`、`RAW10`、`RAW12`、`RAW14`、`RAW_SENSOR_65535` 或 `Custom`。 | +| `raw_custom_white_levels` | object<string, number> | 每个镜头的白电平,范围 `0..65535`。 | +| `raw_cfa_correction_modes` | object<string, string> | `Default`、`2x2_RGGB`、`2x2_GRBG`、`2x2_GBRG`、`2x2_BGGR`、`4x4_RGGB`、`4x4_GRBG`、`4x4_GBRG`、`4x4_BGGR`、`8x8_RGGB`、`8x8_GRBG`、`8x8_GBRG` 或 `8x8_BGGR`。 | +| `raw_lens_shading_correction_enabled` | boolean | 是否启用 RAW 镜头阴影校正。 | +| `raw_dcp_id` | string | 全局 DCP 配置 ID。 | +| `raw_dcp_ids_by_lens` | object<string, string\|null> | 按镜头的 DCP ID;值为 `null` 表示禁用该镜头映射。 | +| `raw_noise_profile_id` | string | 全局 RAW 噪声 profile ID。 | +| `raw_noise_profile_ids_by_lens` | object<string, string> | 按镜头的 RAW 噪声 profile ID。 | +| `raw_color_engine` | string | 当前支持的 `RawRenderingEngine` 名称。 | +| `use_p010` | boolean | 是否使用 P010。 | +| `use_p3_color_space` | boolean | 是否使用 P3 色彩空间。 | +| `oppo_super_stabilization_enabled` | boolean | 是否启用 OPPO 超级防抖。 | +| `video_audio_input_id` | string | 视频音频输入 ID。 | +| `nr_level` | integer | 照片降噪等级,范围 `0..4`。 | +| `edge_level` | integer | 照片锐化等级,范围 `0..3`。 | +| `video_nr_level` | integer | 视频降噪等级,范围 `0..4`。 | +| `video_edge_level` | integer | 视频锐化等级,范围 `0..3`。 | +| `isz_lens_configs` | array of object | 见下文。 | +| `vendor_capture_settings` | object<string, object> | 按镜头 ID 的内置厂商拍摄参数,见下文。 | +| `custom_vendor_key_settings` | array of object | 自定义的 Camera2 厂商键,见下文。 | + +### ISZ 镜头对象 + +`isz_lens_configs` 的每个对象只允许以下字段: + +```json +{ + "base_camera_id": "2", + "isz_zoom_ratio": 2, + "is_macro": false, + "vendor_capture_profile_id": "oplus_agingtest_mode_select_22", + "raw_black_border_crop_sensor_left_px": 508, + "raw_black_border_crop_sensor_top_px": 0, + "raw_black_border_crop_sensor_right_px": 0, + "raw_black_border_crop_sensor_bottom_px": 0 +} +``` + +`base_camera_id` 是非空字符串;`isz_zoom_ratio` 是 `1..100` 的有限数值;`is_macro` 是布尔值;`vendor_capture_profile_id`(如存在)是非空、经过允许字符清理的字符串。每个裁切值都是 `0..4096` 的整数。旧的 `raw_black_border_crop_left_px`、`top_px`、`right_px`、`bottom_px` 字段表示竖屏显示方向;新的 `raw_black_border_crop_sensor_left_px`、`top_px`、`right_px`、`bottom_px` 字段表示传感器方向。一个对象不能同时出现旧字段和新 sensor 字段;不要混用两套坐标。新配置应使用 sensor 字段。 + +上例的虚拟镜头 ID 为 `isz:2:2:oplus_agingtest_mode_select_22`。该 ID 对应的 `vendor_capture_settings` 必须配置为 `{"oplus_agingtest_mode_select":22}`(在同一文件中提供,或已存在于当前设置中)。完整关联示例见 OPPO X9 Ultra 配置文件。 + +### 内置厂商拍摄参数 + +`vendor_capture_settings` 的镜头 ID 对象只允许以下键,值必须是整数,并且处于该键可表示的范围(代码会拒绝需要归一化的值): + +| 键 | 类型/范围 | +| --- | --- | +| `insensor_zoom` | INT,任意 32 位整数 | +| `qcom_sensor_current_mode` | INT,任意 32 位整数 | +| `vivo_force_sensor_mode` | INT,任意 32 位整数 | +| `mtk_raw_bpp` | INT,任意 32 位整数 | +| `oplus_agingtest_mode_select` | BYTE,`-128..127` | + +### 自定义厂商键对象 + +每个 `custom_vendor_key_settings` 条目只允许以下字段: + +```json +{ + "id": "unique-id", + "key_name": "vendor.key.name", + "target": "CAPTURE_REQUEST", + "value_type": "INT32", + "value": 1, + "lens_id": "2" +} +``` + +`id` 必须唯一且非空;合并后,如果同名键的 `target` 和作用域相同会冲突,作用域重叠且值类型不同也会冲突;`key_name` 必须非空,不能包含空白或控制字符;`target` 为 `CAPTURE_REQUEST` 或 `SESSION_PARAMETER`;`value_type` 为 `INT32` 或 `U8`;`value` 是整数,`INT32` 为任意 32 位整数,`U8` 为 `0..255`;`lens_id` 可省略或为 `null`(表示应用于所有镜头),存在时必须是非空字符串。 + +## 机型配置维护 + +新增或修改机型时,在 `app/src/main/assets/device_configurations/` 增加或更新 JSON,并确保 `manufacturer`、`models`、`overrides` 均符合上文规则。提交前应检查全部内置文件的匹配集合:同一设备若有匹配,必须恰好只有一份;重复匹配是配置错误,未匹配设备应保持现有设置不变。 + +DCP、RAW 噪声 profile 及其他被配置引用的资源必须随应用一起打包,并在配置中使用对应的内置资源 ID。机型配置不能要求用户导入模型或提供用户自定义资源。配置文件格式版本仍为数字 `1`;版本号表示 JSON 格式版本,不提供按版本重新应用已标记设备的机制。 diff --git a/docs/examples/device-configuration.full.json b/docs/examples/device-configuration.full.json new file mode 100644 index 00000000..47729fb6 --- /dev/null +++ b/docs/examples/device-configuration.full.json @@ -0,0 +1,156 @@ +{ + "format": "photon_device_configuration", + "version": 1, + "name": "Complete device configuration demo", + "manufacturer": "DEMO", + "models": ["DEMO_MODEL_A", "DEMO_MODEL_B"], + "overrides": { + "preferred_main_camera_id": "2", + "hdr_plus_frame_count": 8, + "preferred_macro_camera_id": "4", + "custom_lens_ids": ["2", "3", "4"], + "lens_id_blacklist": ["99"], + "enable_logical_multi_camera_discovery": false, + "logical_camera_binding_whitelist": ["0/2", "0/3", "0/4"], + "default_focal_length": -2, + "custom_focal_lengths": [35, 50, 85, -1.5, -2, -4], + "hidden_focal_lengths": [15], + "camera_orientation_offsets": { + "2": 0, + "3": 90, + "4": 270, + "isz:2:2:oplus_agingtest_mode_select_22": 0, + "isz:4:2:oplus_agingtest_mode_select_19": 270, + "legacy_lens": null + }, + "raw_black_level_modes": { + "2": "Custom", + "3": "Default", + "4": "Custom", + "isz:2:2:oplus_agingtest_mode_select_22": "Custom", + "isz:4:2:oplus_agingtest_mode_select_19": "Custom" + }, + "raw_custom_black_levels": { + "2": 59, + "4": 0, + "isz:2:2:oplus_agingtest_mode_select_22": 59, + "isz:4:2:oplus_agingtest_mode_select_19": 0 + }, + "raw_white_level_modes": { + "2": "Custom", + "3": "Default", + "4": "RAW14", + "isz:2:2:oplus_agingtest_mode_select_22": "Custom", + "isz:4:2:oplus_agingtest_mode_select_19": "RAW14" + }, + "raw_custom_white_levels": { + "2": 16383, + "isz:2:2:oplus_agingtest_mode_select_22": 16383 + }, + "raw_cfa_correction_modes": { + "2": "Default", + "3": "2x2_RGGB", + "4": "4x4_RGGB", + "isz:2:2:oplus_agingtest_mode_select_22": "2x2_RGGB", + "isz:4:2:oplus_agingtest_mode_select_19": "2x2_RGGB" + }, + "raw_lens_shading_correction_enabled": true, + "raw_dcp_id": "builtin_dcp_OPPO Find X8 Ultra back camera 8.67mm f1.8 Adobe Standard", + "raw_dcp_ids_by_lens": { + "2": "builtin_dcp_OPPO Find X8 Ultra back camera 8.67mm f1.8 Adobe Standard", + "3": null, + "isz:2:2:oplus_agingtest_mode_select_22": "builtin_dcp_OPPO Find X8 Ultra back camera 8.67mm f1.8 Adobe Standard" + }, + "raw_noise_profile_id": "system_camera2", + "raw_noise_profile_ids_by_lens": { + "2": "builtin_noise_x9_ultra", + "3": "builtin_noise_pixel8_pro", + "4": "builtin_noise_x9_ultra_3x", + "isz:2:2:oplus_agingtest_mode_select_22": "builtin_noise_x9_ultra", + "isz:4:2:oplus_agingtest_mode_select_19": "builtin_noise_x9_ultra_3x", + "legacy_lens": null + }, + "raw_color_engine": "AdobeCurve", + "use_p010": false, + "use_p3_color_space": false, + "oppo_super_stabilization_enabled": false, + "video_audio_input_id": "auto", + "nr_level": 2, + "edge_level": 1, + "video_nr_level": 1, + "video_edge_level": 1, + "isz_lens_configs": [ + { + "base_camera_id": "2", + "isz_zoom_ratio": 2, + "is_macro": false, + "vendor_capture_profile_id": "oplus_agingtest_mode_select_22", + "raw_black_border_crop_left_px": 508, + "raw_black_border_crop_top_px": 0, + "raw_black_border_crop_right_px": 0, + "raw_black_border_crop_bottom_px": 0 + }, + { + "base_camera_id": "4", + "isz_zoom_ratio": 2, + "is_macro": true, + "vendor_capture_profile_id": "oplus_agingtest_mode_select_19", + "raw_black_border_crop_sensor_left_px": 0, + "raw_black_border_crop_sensor_top_px": 0, + "raw_black_border_crop_sensor_right_px": 0, + "raw_black_border_crop_sensor_bottom_px": 508 + } + ], + "vendor_capture_settings": { + "2": { + "insensor_zoom": 1, + "qcom_sensor_current_mode": 0 + }, + "3": { + "vivo_force_sensor_mode": 1, + "mtk_raw_bpp": 14 + }, + "isz:2:2:oplus_agingtest_mode_select_22": { + "oplus_agingtest_mode_select": 22 + }, + "isz:4:2:oplus_agingtest_mode_select_19": { + "oplus_agingtest_mode_select": 19 + }, + "legacy_lens": null + }, + "custom_vendor_key_settings": [ + { + "id": "demo-global-capture-int32", + "key_name": "com.example.camera.capture.strength", + "target": "CAPTURE_REQUEST", + "value_type": "INT32", + "value": 1, + "lens_id": null + }, + { + "id": "demo-main-capture-int32", + "key_name": "com.example.camera.capture.strength", + "target": "CAPTURE_REQUEST", + "value_type": "INT32", + "value": 2, + "lens_id": "2" + }, + { + "id": "demo-tele-session-u8", + "key_name": "com.example.camera.session.mode", + "target": "SESSION_PARAMETER", + "value_type": "U8", + "value": 1, + "lens_id": "4" + }, + { + "id": "demo-isz-session-int32", + "key_name": "com.example.camera.session.sensorMode", + "target": "SESSION_PARAMETER", + "value_type": "INT32", + "value": 0, + "lens_id": "isz:2:2:oplus_agingtest_mode_select_22" + } + ] + } +}