feat: preview limited range correction

This commit is contained in:
zhoubinjia committed 2026-11-11 16:49:51 +08:00
1 parent c916d0f831
commit f323fcd952
22 files changed
+96 -1

No files matched your search

@@ -156,6 +156,7 @@ class UserPreferences internal constructor(
var deletedBuiltInIds by string("deleted_built_in_ids", "")
var showLevelIndicator by bool("show_level_indicator", false) // 水平仪显示
var focusPeakingEnabled by bool("focus_peaking_enabled", true) // 手动对焦峰值显示
var previewLimitedRange by bool("preview_limited_range", false) // 预览流为有限范围 YUV 时展开到全范围
var showHistogram by bool("show_histogram", true)
var showGrid by bool("show_grid", false) // 网格线显示
var eyeFocusEnabled by bool("eye_focus_enabled", false) // MediaPipe 人眼对焦
@@ -12,6 +12,7 @@ internal data class ColorPassLocations(
val uLutTextureLocation: Int,
val uNightToneTextureLocation: Int,
val uNightWhitePointLocation: Int,
val uPreviewLimitedRangeLocation: Int,
val uLutSizeLocation: Int,
val uLutIntensityLocation: Int,
val uLutEnabledLocation: Int,
@@ -178,6 +179,7 @@ internal class PreviewColorProgramCache {
uCurveTextureLocation = GLES30.glGetUniformLocation(program, "uCurveTexture"),
uNightToneTextureLocation = GLES30.glGetUniformLocation(program, "uNightToneTexture"),
uNightWhitePointLocation = GLES30.glGetUniformLocation(program, "uNightWhitePoint"),
uPreviewLimitedRangeLocation = GLES30.glGetUniformLocation(program, "uPreviewLimitedRange"),
uCurveEnabledLocation = GLES30.glGetUniformLocation(program, "uCurveEnabled"),
uPreviewBlurLocation = GLES30.glGetUniformLocation(program, "uPreviewBlur"),
uPreviewClarityLocation = GLES30.glGetUniformLocation(program, "uPreviewClarity"),
@@ -253,6 +253,10 @@ class LutRenderer(context: Context) : GLSurfaceView.Renderer {
// 相机 SurfaceTexture
private var surfaceTexture: SurfaceTexture? = null
/** Expands a limited-range preview stream to full range ([PreviewSignalRange]). */
@Volatile
var previewLimitedRange: Boolean = false
private val frameAvailable = AtomicBoolean(false)
private var stabilizationCoordinator: RealtimeStabilizationCoordinator? = null
@Volatile
@@ -865,6 +869,7 @@ class LutRenderer(context: Context) : GLSurfaceView.Renderer {
enableVideoLog: Boolean,
toneBaseOnly: Boolean = false,
nightVisionTone: Boolean = false,
expandRange: Boolean = false,
) {
val shadowsHighlightsActive =
ShadowsHighlightsShader.isActive(params.highlights, params.shadows)
@@ -891,6 +896,7 @@ class LutRenderer(context: Context) : GLSurfaceView.Renderer {
enableVideoLog = enableVideoLog,
toneBaseOnly = true,
nightVisionTone = nightVisionTone,
expandRange = expandRange,
)
toneBase.buildLevels(::drawSimpleQuad)
}
@@ -901,6 +907,7 @@ class LutRenderer(context: Context) : GLSurfaceView.Renderer {
sourceTextureId = sourceTextureId,
sourceWidth = if (oesSource) previewWidth else width,
sourceHeight = if (oesSource) previewHeight else height,
limitedRange = expandRange,
drawQuad = ::drawSimpleQuad,
)
} else {
@@ -913,6 +920,7 @@ class LutRenderer(context: Context) : GLSurfaceView.Renderer {
}
GLES30.glUseProgram(locations.programId)
GLES30.glUniform1i(locations.uToneBaseOnlyLocation, if (toneBaseOnly) 1 else 0)
GLES30.glUniform1i(locations.uPreviewLimitedRangeLocation, if (expandRange) 1 else 0)
if (locations.previewBlur) {
GLES30.glActiveTexture(GLES30.GL_TEXTURE0 + PreviewLiteEffectsGl.TEXTURE_UNIT)
GLES30.glBindTexture(GLES30.GL_TEXTURE_2D, previewBlurTextureId)
@@ -1521,6 +1529,7 @@ class LutRenderer(context: Context) : GLSurfaceView.Renderer {
suppressNightVisionTone: Boolean = false,
) {
val plan = if (suppressCameraEngine) null else enginePreviewPlan
val expandRange = previewLimitedRange
val nightVisionTone = !suppressNightVisionTone && nightVisionEnabled && nightToneActive &&
nightToneTextureId != 0
if (plan != null && !enginePreview.prepare(plan)) return
@@ -1588,6 +1597,7 @@ class LutRenderer(context: Context) : GLSurfaceView.Renderer {
curveEnabled = layerCurveEnabled,
enableVideoLog = enableVideoLog,
nightVisionTone = nightVisionTone,
expandRange = expandRange,
)
// 测光和直方图(按需)
@@ -96,6 +96,7 @@ internal object PreviewColorShader {
${PreviewColorShaderModules.SANITIZE}
${BasicToneLutShader.GLSL}
${PreviewSignalRange.GLSL}
${if (variant.includeNightVisionTone) NightVisionToneGl.GLSL else ""}
float getLuma(vec3 color) {
@@ -120,6 +121,7 @@ internal object PreviewColorShader {
${if (variant.includeEnginePreview) RawEnginePreviewGl.SAMPLING_GLSL else ""}
vec4 samplePreviewSource(vec2 uv) {
vec4 sampled = texture(uCameraTexture, uv);
sampled.rgb = expandPreviewRange(sampled.rgb);
${if (variant.includeEnginePreview) "sampled.rgb = sampleEnginePreview(sampled.rgb);" else ""}
return sampled;
}
@@ -29,6 +29,7 @@ internal class PreviewLiteEffectsGl(private val tag: String) {
sourceTextureId: Int,
sourceWidth: Int,
sourceHeight: Int,
limitedRange: Boolean,
drawQuad: (Int) -> Unit,
): Int {
val program = ensureProgram(sourceTarget)
@@ -42,6 +43,7 @@ internal class PreviewLiteEffectsGl(private val tag: String) {
GLES30.glActiveTexture(GLES30.GL_TEXTURE0)
GLES30.glBindTexture(sourceTarget, sourceTextureId)
GLES30.glUniform1i(GLES30.glGetUniformLocation(program, "uSource"), 0)
GLES30.glUniform1i(GLES30.glGetUniformLocation(program, "uPreviewLimitedRange"), if (limitedRange) 1 else 0)
GLES30.glUniform2f(
GLES30.glGetUniformLocation(program, "uSourceTexel"),
1f / max(1, sourceWidth),
@@ -140,13 +142,14 @@ internal class PreviewLiteEffectsGl(private val tag: String) {
out vec4 fragColor;
uniform ${if (oes) "samplerExternalOES" else "sampler2D"} uSource;
uniform vec2 uSourceTexel;
${PreviewSignalRange.GLSL}
void main() {
vec2 d = uSourceTexel;
vec3 color = texture(uSource, vTexCoord + vec2(-d.x, -d.y)).rgb;
color += texture(uSource, vTexCoord + vec2(d.x, -d.y)).rgb;
color += texture(uSource, vTexCoord + vec2(-d.x, d.y)).rgb;
color += texture(uSource, vTexCoord + vec2(d.x, d.y)).rgb;
color = clamp(color * 0.25, 0.0, 1.0);
color = expandPreviewRange(clamp(color * 0.25, 0.0, 1.0));
float y = dot(color, vec3(0.299, 0.587, 0.114));
fragColor = vec4(color, clamp((y - $BLOOM_THRESHOLD) / (1.0 - $BLOOM_THRESHOLD), 0.0, 1.0));
}
@@ -0,0 +1,29 @@
package com.hinnka.mycamera.lut
/**
* Limited-range correction for the camera preview stream.
*
* The preview buffer format is implementation defined. Some HALs (e.g. Xiaomi 11) emit limited
* range YCbCr (Y 16..235) with an UNKNOWN dataspace, and the GPU driver converts it to RGB as
* full range: lifted blacks, 235 whites, low contrast, while the capture ImageReader stream
* (JFIF, full range) is correct. The range is not reported reliably, so the user enables the
* correction in settings.
*/
internal object PreviewSignalRange {
/**
* `uniform bool uPreviewLimitedRange` and `vec3 expandPreviewRange(vec3)`. Inverts the
* driver's BT.601 full-range matrix to recover Y and chroma, then rescales them with the
* limited-range spans (Y 219, chroma 224) back into full range.
*/
const val GLSL = """
uniform bool uPreviewLimitedRange;
vec3 expandPreviewRange(vec3 color) {
if (!uPreviewLimitedRange) return color;
float y = dot(color, vec3(0.299, 0.587, 0.114));
vec3 chroma = color - vec3(y);
vec3 expanded = vec3((y - 16.0 / 255.0) * (255.0 / 219.0)) + chroma * (255.0 / 224.0);
return clamp(expanded, 0.0, 1.0);
}
"""
}
@@ -219,6 +219,13 @@ class CameraGLSurfaceView @JvmOverloads constructor(
renderer.nightVisionEnabled = enabled
}
/** Expands a limited-range preview stream to full range. */
fun setPreviewLimitedRange(enabled: Boolean) {
if (renderer.previewLimitedRange == enabled) return
renderer.previewLimitedRange = enabled
requestRender()
}
/**
* 设置 LUT
*
@@ -76,6 +76,7 @@ fun CameraPreviewGL(
livePhotoRecorder: LivePhotoRecorder? = null,
videoLogProfile: VideoLogProfile = VideoLogProfile.OFF,
nightVisionEnabled: Boolean = false,
previewLimitedRange: Boolean = false,
isEyeFocusBusy: Boolean = false,
onGLSurfaceViewReady: ((CameraGLSurfaceView) -> Unit)? = null,
isAutoFocus: Boolean = true,
@@ -330,6 +331,7 @@ fun CameraPreviewGL(
glSurfaceView.setLivePhotoRecorder(livePhotoRecorder)
glSurfaceView.setVideoLogProfile(videoLogProfile)
glSurfaceView.setNightVisionEnabled(nightVisionEnabled)
glSurfaceView.setPreviewLimitedRange(previewLimitedRange)
glSurfaceView.setAutoFocus(isAutoFocus)
glSurfaceView.setFocusPeakingEnabled(focusPeakingEnabled)
glSurfaceView.setEyeFocusBusy(isEyeFocusBusy)
@@ -256,6 +256,7 @@ fun CameraScreen(
val latestPhoto by galleryViewModel.latestPhoto.collectAsState()
val showLevelIndicator by preferenceValue { it.showLevelIndicator }
val focusPeakingEnabled by preferenceValue { it.focusPeakingEnabled }
val previewLimitedRange by preferenceValue { it.previewLimitedRange }
val eyeFocusEnabled by preferenceValue { it.eyeFocusEnabled }
val keepScreenOn by preferenceValue { it.keepScreenOn }
val currentLutId by viewModel.currentLutId.collectAsState()
@@ -1351,6 +1352,7 @@ fun CameraScreen(
livePhotoRecorder = viewModel.livePhotoRecorder,
videoLogProfile = state.videoConfig.logProfile,
nightVisionEnabled = state.isNightVisionActive,
previewLimitedRange = previewLimitedRange,
isEyeFocusBusy = viewModel.isEyeFocusBusy,
isAutoFocus = state.isAutoFocus,
focusPeakingEnabled = focusPeakingEnabled && !state.isHyperfocalFocusEnabled,
@@ -330,6 +330,7 @@ fun SettingsScreen(
val userPreferences by viewModel.userPreferences.collectAsState()
var showLevelIndicator by rememberPreference(UserPreferences::showLevelIndicator)
var focusPeakingEnabled by rememberPreference(UserPreferences::focusPeakingEnabled)
var previewLimitedRange by rememberPreference(UserPreferences::previewLimitedRange)
val eyeFocusEnabled by preferenceValue { it.eyeFocusEnabled }
var showGrid by rememberPreference(UserPreferences::showGrid)
var shutterSoundEnabled by rememberPreference(UserPreferences::shutterSoundEnabled)
@@ -1158,6 +1159,18 @@ fun SettingsScreen(
modifier = Modifier.padding(vertical = 8.dp)
)
SwitchSettingItem(
title = stringResource(R.string.settings_preview_limited_range),
description = stringResource(R.string.settings_preview_limited_range_description),
checked = previewLimitedRange,
onCheckedChange = { previewLimitedRange = it }
)
HorizontalDivider(
color = Color.White.copy(alpha = 0.1f),
modifier = Modifier.padding(vertical = 8.dp)
)
SwitchSettingItem(
title = stringResource(
R.string.settings_photo_preview_stabilization
@@ -1436,4 +1436,6 @@
<string name="aesthetic_show_in_gallery">在相簿列表顯示評分</string>
<string name="aesthetic_show_in_gallery_description">瀏覽時在背景為照片評分。</string>
<string name="aesthetic_note">評分來自端側 CLIP 美學模型(LAION Aesthetic Predictor),以大規模人類審美評分訓練,反映大眾視覺偏好而非創作意圖,僅供參考。</string>
<string name="settings_preview_limited_range">修正預覽發灰</string>
<string name="settings_preview_limited_range_description">預覽偏灰、對比度低而成片正常時開啟。部分裝置的預覽訊號為有限範圍。</string>
</resources>
+2
View File
@@ -487,4 +487,6 @@
<string name="fotufilm_value_years">%1$s J.</string>
<!-- /Fotufilm controls -->
<string name="save_as_preset">Als Preset speichern</string>
<string name="settings_preview_limited_range">Blasse Vorschau korrigieren</string>
<string name="settings_preview_limited_range_description">Einschalten, wenn die Vorschau grau und kontrastarm wirkt, die Fotos aber normal sind. Manche Geräte liefern ein Vorschausignal mit begrenztem Bereich.</string>
</resources>
+2
View File
@@ -1474,4 +1474,6 @@
<string name="aesthetic_show_in_gallery">Afficher les scores dans la galerie</string>
<string name="aesthetic_show_in_gallery_description">Évalue les photos en arrière-plan pendant la navigation.</string>
<string name="aesthetic_note">Évalué par un modèle esthétique CLIP sur l\'appareil (LAION Aesthetic Predictor), entraîné sur un grand nombre de notes humaines. Il reflète l\'attrait visuel général plutôt que l\'intention artistique : à utiliser comme référence.</string>
<string name="settings_preview_limited_range">Corriger l\'aperçu délavé</string>
<string name="settings_preview_limited_range_description">À activer si l\'aperçu paraît gris et peu contrasté alors que les photos sont normales. Certains appareils fournissent un signal d\'aperçu à plage limitée.</string>
</resources>
+2
View File
@@ -487,4 +487,6 @@
<string name="fotufilm_value_years">%1$s thn</string>
<!-- /Fotufilm controls -->
<string name="save_as_preset">Simpan sebagai preset</string>
<string name="settings_preview_limited_range">Perbaiki pratinjau pudar</string>
<string name="settings_preview_limited_range_description">Aktifkan jika pratinjau tampak abu-abu dan kontrasnya rendah, sedangkan foto normal. Beberapa perangkat mengeluarkan sinyal pratinjau rentang terbatas.</string>
</resources>
+2
View File
@@ -1329,4 +1329,6 @@
<string name="aesthetic_show_in_gallery">ギャラリーにスコアを表示</string>
<string name="aesthetic_show_in_gallery_description">閲覧中にバックグラウンドで写真を評価します。</string>
<string name="aesthetic_note">端末上の CLIP 美的モデル(LAION Aesthetic Predictor)による評価で、大規模な人間の評価データで学習されています。芸術的意図ではなく一般的な見た目の魅力を反映するため、参考としてご利用ください。</string>
<string name="settings_preview_limited_range">プレビューの白っぽさを補正</string>
<string name="settings_preview_limited_range_description">写真は正常なのにプレビューが白っぽくコントラストが低い場合にオンにします。一部の端末はプレビュー信号が限定レンジです。</string>
</resources>
+2
View File
@@ -488,4 +488,6 @@
<string name="fotufilm_value_years">%1$s년</string>
<!-- /Fotufilm controls -->
<string name="save_as_preset">프리셋으로 저장</string>
<string name="settings_preview_limited_range">흐린 미리보기 보정</string>
<string name="settings_preview_limited_range_description">사진은 정상인데 미리보기가 회색빛이고 대비가 낮으면 켜세요. 일부 기기는 제한 범위 미리보기 신호를 출력합니다.</string>
</resources>
@@ -488,4 +488,6 @@
<string name="fotufilm_value_years">%1$s anos</string>
<!-- /Fotufilm controls -->
<string name="save_as_preset">Salvar como predefinição</string>
<string name="settings_preview_limited_range">Corrigir prévia desbotada</string>
<string name="settings_preview_limited_range_description">Ative se a prévia parecer acinzentada e com pouco contraste enquanto as fotos ficam normais. Alguns aparelhos geram sinal de prévia em faixa limitada.</string>
</resources>
+2
View File
@@ -1109,4 +1109,6 @@
<string name="aesthetic_show_in_gallery">แสดงคะแนนในแกลเลอรี</string>
<string name="aesthetic_show_in_gallery_description">ให้คะแนนรูปภาพในพื้นหลังขณะเลื่อนดู</string>
<string name="aesthetic_note">ให้คะแนนโดยโมเดลความสวยงาม CLIP บนอุปกรณ์ (LAION Aesthetic Predictor) ที่ฝึกจากคะแนนของมนุษย์จำนวนมาก สะท้อนความน่าดึงดูดทางสายตาโดยทั่วไป ไม่ใช่เจตนาทางศิลปะ ควรใช้เป็นข้อมูลอ้างอิงเท่านั้น</string>
<string name="settings_preview_limited_range">แก้พรีวิวซีดจาง</string>
<string name="settings_preview_limited_range_description">เปิดเมื่อพรีวิวดูซีดและคอนทราสต์ต่ำ แต่ภาพถ่ายปกติ อุปกรณ์บางรุ่นส่งสัญญาณพรีวิวแบบช่วงจำกัด</string>
</resources>
@@ -1492,4 +1492,6 @@
<string name="aesthetic_show_in_gallery">在相册列表显示评分</string>
<string name="aesthetic_show_in_gallery_description">浏览时在后台为照片评分。</string>
<string name="aesthetic_note">评分来自端侧 CLIP 美学模型(LAION Aesthetic Predictor),基于大规模人类审美打分训练,反映大众视觉偏好而非创作意图,仅供参考。</string>
<string name="settings_preview_limited_range">修正预览发灰</string>
<string name="settings_preview_limited_range_description">预览偏灰、对比度低而成片正常时开启。部分设备的预览信号为有限范围。</string>
</resources>
@@ -1430,4 +1430,6 @@
<string name="aesthetic_show_in_gallery">在相簿列表顯示評分</string>
<string name="aesthetic_show_in_gallery_description">瀏覽時在背景為照片評分。</string>
<string name="aesthetic_note">評分來自端側 CLIP 美學模型(LAION Aesthetic Predictor),以大規模人類審美評分訓練,反映大眾視覺偏好而非創作意圖,僅供參考。</string>
<string name="settings_preview_limited_range">修正預覽發灰</string>
<string name="settings_preview_limited_range_description">預覽偏灰、對比度低而成片正常時開啟。部分裝置的預覽訊號為有限範圍。</string>
</resources>
@@ -1436,4 +1436,6 @@
<string name="aesthetic_show_in_gallery">在相簿列表顯示評分</string>
<string name="aesthetic_show_in_gallery_description">瀏覽時在背景為照片評分。</string>
<string name="aesthetic_note">評分來自端側 CLIP 美學模型(LAION Aesthetic Predictor),以大規模人類審美評分訓練,反映大眾視覺偏好而非創作意圖,僅供參考。</string>
<string name="settings_preview_limited_range">修正預覽發灰</string>
<string name="settings_preview_limited_range_description">預覽偏灰、對比度低而成片正常時開啟。部分裝置的預覽訊號為有限範圍。</string>
</resources>
+2
View File
@@ -1517,4 +1517,6 @@
<string name="aesthetic_show_in_gallery">Show scores in gallery</string>
<string name="aesthetic_show_in_gallery_description">Scores photos in the background as you browse.</string>
<string name="aesthetic_note">Scored by an on-device CLIP aesthetic model (LAION Aesthetic Predictor) trained on large-scale human ratings. It reflects broad visual appeal rather than artistic intent, so use it as a reference.</string>
<string name="settings_preview_limited_range">Fix Washed-out Preview</string>
<string name="settings_preview_limited_range_description">Turn on if the preview looks grey with weak contrast while photos look normal. Some devices output a limited-range preview signal.</string>
</resources>