refactor: remove night vision mode

This commit is contained in:
zhoubinjia committed 2026-11-13 12:25:32 +08:00
1 parent 51a38020dd
commit f3449a1a82
32 files changed
+19 -1173

No files matched your search

@@ -1,14 +0,0 @@
# CPGA-Net low-light tone model
Night vision mode uses this model only to estimate a global luma tone curve; the network output
image itself is never shown or saved.
- Source: https://huggingface.co/litert-community/CPGA-Net-LowLight-LiteRT (commit `e917b2a`), file `cpga_fp16.tflite`
- Upstream: https://github.com/Shyandram/CPGA-Net-Pytorch (IJPRAI), MIT; see `license/LICENSE.txt`.
- SHA-256: `8b125569618cbc342b3c0a095f712dfc899ac739e896208baf13cb1769c4c319`, 93,820 bytes.
## Tensor contract
- Input: FP32 `[1,3,256,256]` NCHW RGB in [0,1]. The whole frame is resized to 256x256 without crop.
- Output: FP32 `[1,3,256,256]` NCHW RGB in [0,1].
- XNNPACK rejects the FP16 graph (DEPTHWISE_CONV_2D); the model runs on the LiteRT GPU accelerator only.
Binary file not shown.
@@ -1,21 +0,0 @@
MIT License
Copyright (c) 2024 Shyandram
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
@@ -5275,10 +5275,7 @@ class Camera2Controller(private val context: Context) {
} else nrLevel
val isBurst = !isVideo && currentState.requiresMultiFrameCaptureSequence
val effectiveNrLevel = when {
// Cap every preview path before applying capture-only overrides such as night vision.
!isCapture && selectedNrLevel == NoiseReductionLevel.HIGH_QUALITY -> NoiseReductionLevel.FAST
// Night vision always asks the ISP for HIGH_QUALITY NR on every burst frame.
isCapture && !isVideo && currentState.isNightVisionActive -> NoiseReductionLevel.HIGH_QUALITY
isBurst && selectedNrLevel == NoiseReductionLevel.HIGH_QUALITY -> NoiseReductionLevel.FAST
else -> selectedNrLevel
}
@@ -7548,10 +7545,6 @@ class Camera2Controller(private val context: Context) {
)
}
fun setNightVisionEnabled(enabled: Boolean) {
_state.value = _state.value.copy(nightVisionEnabled = enabled)
}
fun setJpgMultiFrameDenoiseFrameCount(frameCount: Int) {
_state.value = _state.value.copy(
jpgMultiFrameDenoiseFrameCount = MultiFrameConfig.normalizeDenoiseFrameCount(frameCount),
@@ -382,8 +382,6 @@ data class CameraState(
val hdrPlusLongFrameExposureEv: Float = MultiFrameConfig.LONG_FRAME_EXPOSURE_EV.toFloat(),
val hdrPlusShortFrameExposureEv: Float = MultiFrameConfig.DEFAULT_SHORT_FRAME_EXPOSURE_EV,
val useRaw: Boolean = false,
/** Night vision mode: forced 8-frame YUV stack plus the model tone curve (PHOTO, non-RAW only). */
val nightVisionEnabled: Boolean = false,
val useMultipleExposure: Boolean = false,
val rawMinShutterSpeedNs: Long = 0L,
val useLivePhoto: Boolean = false,
@@ -449,10 +447,6 @@ data class CameraState(
val isJpgMaxEnabled: Boolean
get() = isMultiFrameEnabled && !useRaw
/** Night vision applies only to a PHOTO YUV stack. */
val isNightVisionActive: Boolean
get() = nightVisionEnabled && captureMode == CaptureMode.PHOTO && isJpgMaxEnabled
val isJpgMaxHdrEnabled: Boolean
get() = isJpgMaxEnabled && useJpgMaxHdrComposition
@@ -465,7 +459,6 @@ data class CameraState(
val activeMultiFrameCount: Int
get() = when {
isNightVisionActive -> MultiFrameConfig.NIGHT_VISION_FRAME_COUNT
isJpgMaxEnabled -> MultiFrameConfig.normalizeDenoiseFrameCount(
jpgMultiFrameDenoiseFrameCount
)
@@ -12,8 +12,6 @@ object MultiFrameConfig {
const val MIN_DENOISE_FRAME_COUNT = 3
const val DEFAULT_DENOISE_FRAME_COUNT = 5
/** Night vision always stacks this many YUV frames, independent of the JPGmax setting. */
const val NIGHT_VISION_FRAME_COUNT = 8
const val MIN_HDR_PLUS_FRAME_COUNT = 1
const val MIN_HDR_PLUS_BRACKET_FRAME_COUNT = 2
const val DEFAULT_HDR_PLUS_FRAME_COUNT = 3
@@ -371,15 +371,12 @@ class UserPreferences internal constructor(
val requested = if (hasCurrentMaxPreferences) p[K.USE_RAW_MAX] ?: false else storedUseRaw && legacyMultiFrameEnabled
requested || storedUseRaw
}) { p, v -> p[K.USE_RAW_MAX] = v }
/** 夜视模式:PHOTO 下强制 8 帧 YUV 多帧并叠加模型提亮曲线,与 RAW 互斥。 */
var nightVisionMode: Boolean by stored({ p -> p[K.NIGHT_VISION_MODE] ?: false }) { p, v -> p[K.NIGHT_VISION_MODE] = v }
/** 实际是否走 YUV 多帧:JPGmax 或夜视模式,且不是 RAW、多重曝光。 */
/** 实际是否走 YUV 多帧:JPGmax 已启用,且不是 RAW、多重曝光。 */
val effectiveUseJpgMax: Boolean
get() = (useJpgMax || nightVisionMode) && !useRaw && !useMultipleExposure
/** 使用 RAW 格式拍摄。读取结果综合 [useRawMax]/[useJpgMax]/[nightVisionMode];写入只记录 RAW 开关本身。 */
get() = useJpgMax && !useRaw && !useMultipleExposure
/** 使用 RAW 格式拍摄。读取结果综合 [useRawMax]/[useJpgMax];写入只记录 RAW 开关本身。 */
var useRaw: Boolean
get() = when {
nightVisionMode -> false
useRawMax -> true
useJpgMax -> false
else -> storedUseRaw
@@ -830,7 +827,6 @@ internal object PreferenceKeys {
val LUT_SELECTOR_MODE = stringPreferencesKey("lut_selector_mode")
val CAMERA_ORIENTATION_OFFSETS = stringPreferencesKey("camera_orientation_offsets")
val USE_JPG_MAX = booleanPreferencesKey("use_jpg_max")
val NIGHT_VISION_MODE = booleanPreferencesKey("night_vision_mode")
val USE_RAW_MAX = booleanPreferencesKey("use_raw_max")
val LEGACY_USE_MULTI_FRAME = booleanPreferencesKey("use_multi_frame")
val LEGACY_USE_HDR_COMPOSITION = booleanPreferencesKey("use_hdr_composition")
@@ -1,6 +1,5 @@
package com.hinnka.mycamera.gallery
import com.hinnka.mycamera.processor.NightVisionCapture
import android.app.PendingIntent
import android.content.ContentUris
import android.content.ContentValues
@@ -3237,7 +3236,6 @@ object GalleryManager {
photoQuality: Int = 95,
useSuperResolution: Boolean = false,
superResolutionScale: Float = 1.0f,
nightVision: Boolean = false,
) = withContext(Dispatchers.IO) {
try {
val photoDir = getPhotoDir(context, photoId, true)
@@ -3258,14 +3256,6 @@ object GalleryManager {
if (metadata.isMirrored) {
result = BitmapUtils.flipHorizontal(result)
}
if (nightVision) {
result = NightVisionCapture.process(
context = context,
bitmap = result,
sensorIso = metadata.iso,
photoProcessor = photoProcessor,
)
}
val previewBitmap = result
@@ -4559,7 +4549,6 @@ object GalleryManager {
rawMaxHdrFusionEnabled: Boolean = true,
rawMaxSpatialOutputMode: MgcSpatialOutputMode = MgcSpatialOutputMode.BAYER,
rawMaxMergeMethod: MgcMergeMethod = MgcMergeMethod.SPATIAL_BAYER,
nightVision: Boolean = false,
) = withContext(Dispatchers.IO) {
when (val format = images[0].format) {
ImageFormat.YUV_420_888, ImageFormat.YCBCR_P010, ImageFormat.NV21 -> {
@@ -4577,7 +4566,6 @@ object GalleryManager {
photoQuality,
useSuperResolution,
superResolutionScale,
nightVision,
)
}
@@ -1,6 +1,5 @@
package com.hinnka.mycamera.gallery
import com.hinnka.mycamera.processor.NightVisionToneCurve
import android.content.Context
import android.graphics.Bitmap
import android.graphics.BitmapFactory
@@ -93,19 +92,6 @@ class PhotoProcessor(
}
}
/**
* Night vision capture stage (MGC denoise, then tone curve) in one GL pass chain without LUT
* or recipe. Returns [bitmap] itself when there is nothing to do; otherwise a new bitmap and
* the caller owns both.
*/
internal suspend fun applyNightVision(
bitmap: Bitmap,
lumaStrength: Float,
chromaStrength: Float,
sensorIso: Int?,
curve: NightVisionToneCurve,
): Bitmap = lutImageProcessor.applyNightVision(bitmap, lumaStrength, chromaStrength, sensorIso, curve)
/**
* 非 RAW 照片的降噪基底(对应 RAW 烘焙进 original.jpg 的降噪):对 [source] 全分辨率跑一次
* Bitmap 降噪(LutImageProcessor.applyBitmapDenoise)并持久化,预览/导出直接加载基底并以 0 强度走 LUT。
@@ -10,8 +10,6 @@ internal data class ColorPassLocations(
val uCameraTextureLocation: Int,
val uEnginePreviewLutLocation: Int,
val uLutTextureLocation: Int,
val uNightToneTextureLocation: Int,
val uNightWhitePointLocation: Int,
val uLutSizeLocation: Int,
val uLutIntensityLocation: Int,
val uLutEnabledLocation: Int,
@@ -176,8 +174,6 @@ internal class PreviewColorProgramCache {
uCropRectLocation = GLES30.glGetUniformLocation(program, "uCropRect"),
uTexelSizeLocation = GLES30.glGetUniformLocation(program, "uTexelSize"),
uCurveTextureLocation = GLES30.glGetUniformLocation(program, "uCurveTexture"),
uNightToneTextureLocation = GLES30.glGetUniformLocation(program, "uNightToneTexture"),
uNightWhitePointLocation = GLES30.glGetUniformLocation(program, "uNightWhitePoint"),
uCurveEnabledLocation = GLES30.glGetUniformLocation(program, "uCurveEnabled"),
uPreviewBlurLocation = GLES30.glGetUniformLocation(program, "uPreviewBlur"),
uPreviewClarityLocation = GLES30.glGetUniformLocation(program, "uPreviewClarity"),
@@ -1,6 +1,5 @@
package com.hinnka.mycamera.lut
import com.hinnka.mycamera.processor.NightVisionToneCurve
import android.content.Context
import android.graphics.Bitmap
import android.graphics.ColorSpace
@@ -83,7 +82,6 @@ class LutImageProcessor(context: Context? = null) {
private var indexBuffer: ShortBuffer? = null
private val bitmapMgcDenoiser = BitmapMgcDenoiser()
private val nightVisionToneGl = NightVisionToneGl()
private var lutSharpenProgram = 0
private var lutLuminanceGainProgram = 0
private var lutSharpenTextureId = 0
@@ -726,54 +724,6 @@ class LutImageProcessor(context: Context? = null) {
)
}
/**
* Night vision capture stage in one GL round trip: MGC bitmap denoise (skipped when both
* strengths are 0), then the night vision tone (skipped for the identity curve), then readback.
* Returns [bitmap] itself when there is nothing to do.
*/
internal suspend fun applyNightVision(
bitmap: Bitmap,
lumaStrength: Float,
chromaStrength: Float,
sensorIso: Int?,
curve: NightVisionToneCurve,
): Bitmap = withContext(glDispatcher) {
currentCoroutineContext().ensureActive()
val luma = DenoiseStrength.clamp(lumaStrength)
val chroma = DenoiseStrength.clamp(chromaStrength)
if (luma <= 0f && chroma <= 0f && curve.isIdentity) return@withContext bitmap
if (!isInitialized) {
if (!initialize()) {
PLog.e(TAG, "Night vision stage skipped: GL processor failed to initialize")
return@withContext bitmap
}
}
EGL14.eglMakeCurrent(eglDisplay, eglSurface, eglSurface, eglContext)
val width = bitmap.width
val height = bitmap.height
setupFramebuffer(width, height)
uploadImageTexture(bitmap)
val denoisedTexId = renderBitmapDenoise(width, height, luma, chroma, sensorIso)
val tonedTexId = if (curve.isIdentity) {
denoisedTexId
} else {
nightVisionToneGl.apply(denoisedTexId, width, height, curve)
}
performRender(
width = width,
height = height,
inputTextureId = tonedTexId,
inputColorSpace = bitmap.colorSpace ?: ColorSpace.get(ColorSpace.Named.SRGB),
lutConfig = null,
colorRecipeParams = null,
sharpening = 0f,
lutMaskType = 0
)
}
/**
* 执行渲染操作(共享的渲染逻辑)
*/
@@ -2184,7 +2134,6 @@ class LutImageProcessor(context: Context? = null) {
releaseReadbackBuffer()
bitmapMgcDenoiser.release()
nightVisionToneGl.release()
if (lutSharpenProgram != 0) {
GLES30.glDeleteProgram(lutSharpenProgram)
lutSharpenProgram = 0
@@ -1,7 +1,5 @@
package com.hinnka.mycamera.lut
import com.hinnka.mycamera.processor.NightVisionTone
import com.hinnka.mycamera.processor.NightVisionToneCurve
import android.content.Context
import android.graphics.Bitmap
import android.graphics.PointF
@@ -54,10 +52,6 @@ class LutRenderer(context: Context) : GLSurfaceView.Renderer {
companion object {
private const val TAG = "LutRenderer"
/** Units 0-3 and 5/6/12 are taken by the color pass and its helpers. */
private const val NIGHT_TONE_TEXTURE_UNIT = 9
private const val NIGHT_VISION_SAMPLE_INTERVAL_MS = 200L
// 属性位置
private const val POSITION_COMPONENT_COUNT = 2
private const val TEXTURE_COORD_COMPONENT_COUNT = 2
@@ -115,30 +109,6 @@ class LutRenderer(context: Context) : GLSurfaceView.Renderer {
private var meteringTextureId: Int = 0
private val METERING_SIZE = 32
// Night vision: the camera input (no curve, layers or engine) is sampled at the model size,
// read back asynchronously, and the estimator posts a smoothed curve for the shader stage.
private val nightVisionPboIds = IntArray(2)
private val nightVisionPboFences = LongArray(2)
private var nightVisionPboIndex = 0
private var nightVisionFboId = 0
private var nightVisionTextureId = 0
private var lastNightVisionSampleTime = 0L
private var nightToneTextureId = 0
private var nightToneWhitePoint = 1f
private var nightToneActive = false
@Volatile
private var pendingNightTone: NightVisionToneCurve? = null
private val nightVisionEstimator = NightVisionPreviewEstimator(context) { pendingNightTone = it }
/** Enables the night vision preview curve; disabling drops the curve immediately. */
@Volatile
var nightVisionEnabled: Boolean = false
set(value) {
if (field == value) return
field = value
nightVisionEstimator.reset()
pendingNightTone = null
}
private val meteringExecutor: ExecutorService = Executors.newSingleThreadExecutor()
private val meteringDispatchInFlight = AtomicBoolean(false)
private var captureFboId: Int = 0
@@ -647,14 +617,6 @@ class LutRenderer(context: Context) : GLSurfaceView.Renderer {
pboId = 0
resetPixelPackState(meteringPboIds, meteringPboFences)
meteringPboIndex = 0
resetPixelPackState(nightVisionPboIds, nightVisionPboFences)
nightVisionPboIndex = 0
nightVisionFboId = 0
nightVisionTextureId = 0
nightToneTextureId = 0
nightToneActive = false
// The curve lived in the lost context; ask the estimator for a fresh one.
nightVisionEstimator.reset()
meteringFboId = 0
meteringTextureId = 0
captureFboId = 0
@@ -843,7 +805,6 @@ class LutRenderer(context: Context) : GLSurfaceView.Renderer {
params: com.hinnka.mycamera.model.ColorRecipeParams,
enableVideoLog: Boolean,
includeEnginePreview: Boolean = false,
nightVisionTone: Boolean = false,
): ColorPassLocations? {
val variant = PreviewColorShaderVariant.forPass(
textureSource = textureSource,
@@ -852,7 +813,6 @@ class LutRenderer(context: Context) : GLSurfaceView.Renderer {
lutEnabled = lutEnabled && lutConfig != null,
videoLogEnabled = enableVideoLog && videoLogProfile.isEnabled,
previewLite = previewLiteEffectsEnabled,
nightVisionTone = nightVisionTone,
)
return colorProgramCache.get(variant.copy(includeEnginePreview = includeEnginePreview))
}
@@ -876,7 +836,6 @@ class LutRenderer(context: Context) : GLSurfaceView.Renderer {
curveEnabled: Boolean,
enableVideoLog: Boolean,
toneBaseOnly: Boolean = false,
nightVisionTone: Boolean = false,
) {
val shadowsHighlightsActive =
ShadowsHighlightsShader.isActive(params.highlights, params.shadows)
@@ -902,7 +861,6 @@ class LutRenderer(context: Context) : GLSurfaceView.Renderer {
curveEnabled = curveEnabled,
enableVideoLog = enableVideoLog,
toneBaseOnly = true,
nightVisionTone = nightVisionTone,
)
toneBase.buildLevels(::drawSimpleQuad)
}
@@ -1046,13 +1004,6 @@ class LutRenderer(context: Context) : GLSurfaceView.Renderer {
GLES30.glUniform1i(locations.uCurveTextureLocation, 2)
GLES30.glUniform1i(locations.uCurveEnabledLocation, if (curveEnabled && curveTextureId != 0) 1 else 0)
if (nightVisionTone) {
GLES30.glActiveTexture(GLES30.GL_TEXTURE0 + NIGHT_TONE_TEXTURE_UNIT)
GLES30.glBindTexture(GLES30.GL_TEXTURE_2D, nightToneTextureId)
GLES30.glUniform1i(locations.uNightToneTextureLocation, NIGHT_TONE_TEXTURE_UNIT)
GLES30.glUniform1f(locations.uNightWhitePointLocation, nightToneWhitePoint)
}
basicToneTextures.bind(
context = appContext,
textureUnit = 3,
@@ -1101,25 +1052,6 @@ class LutRenderer(context: Context) : GLSurfaceView.Renderer {
GLES30.glBindBuffer(GLES30.GL_ELEMENT_ARRAY_BUFFER, 0)
}
private fun uploadPendingNightTone() {
if (!nightVisionEnabled) {
nightToneActive = false
return
}
val curve = pendingNightTone ?: return
pendingNightTone = null
if (curve.isIdentity) {
nightToneActive = false
return
}
if (nightToneTextureId == 0) {
nightToneTextureId = NightVisionToneGl.createCurveTexture()
}
NightVisionToneGl.uploadCurveValues(nightToneTextureId, curve)
nightToneWhitePoint = curve.whitePoint
nightToneActive = true
}
private fun uploadPendingCurveTextures() {
if (pendingCurveBuffer != null) {
curveTextureId = ColorRecipeGl.ensureCurveTextureUploaded(curveTextureId, pendingCurveBuffer)
@@ -1261,7 +1193,6 @@ class LutRenderer(context: Context) : GLSurfaceView.Renderer {
val hasCreativeLayer = hasCreativeLayer()
val hasDualLayer = hasBaselineLayer && hasCreativeLayer
uploadPendingCurveTextures()
uploadPendingNightTone()
val requestedFbo = liveRecorder != null ||
postProcessEffectEnabled ||
clarityEnabled ||
@@ -1445,19 +1376,13 @@ class LutRenderer(context: Context) : GLSurfaceView.Renderer {
compositeFinalDisplay = needsHdfCompositeForSampling
)
if (meteringEnabled) {
if (nightVisionEnabled) {
// AE must see the scene before the night vision lift, or it would undo it.
runMeteringInternal()
} else {
runMeteringInternal(
sourceTextureId = finalDisplayTextureId,
sourceWidth = finalDisplayWidth,
sourceHeight = finalDisplayHeight,
compositeWithHdf = needsHdfCompositeForSampling
)
}
runMeteringInternal(
sourceTextureId = finalDisplayTextureId,
sourceWidth = finalDisplayWidth,
sourceHeight = finalDisplayHeight,
compositeWithHdf = needsHdfCompositeForSampling
)
}
runNightVisionSampling()
} else {
// 直接渲染到屏幕
drawInternal(
@@ -1612,11 +1537,8 @@ class LutRenderer(context: Context) : GLSurfaceView.Renderer {
suppressBaselineLayer: Boolean = false,
suppressCreativeLayer: Boolean = false,
suppressCameraEngine: Boolean = false,
suppressNightVisionTone: Boolean = false,
) {
val plan = if (suppressCameraEngine) null else enginePreviewPlan
val nightVisionTone = !suppressNightVisionTone && nightVisionEnabled && nightToneActive &&
nightToneTextureId != 0
if (plan != null && !enginePreview.prepare(plan)) return
val baselineLayerAvailable = hasBaselineLayer() && !suppressBaselineLayer
val creativeLayerAvailable = hasCreativeLayer() && !suppressCreativeLayer
@@ -1661,7 +1583,6 @@ class LutRenderer(context: Context) : GLSurfaceView.Renderer {
params = layerParams,
enableVideoLog = enableVideoLog,
includeEnginePreview = plan != null,
nightVisionTone = nightVisionTone,
) ?: return
drawColorPass(
locations = locations,
@@ -1681,16 +1602,12 @@ class LutRenderer(context: Context) : GLSurfaceView.Renderer {
curveTextureId = layerCurveTextureId,
curveEnabled = layerCurveEnabled,
enableVideoLog = enableVideoLog,
nightVisionTone = nightVisionTone,
)
// 测光和直方图(按需)
if (fboId == 0 && meteringEnabled) {
runMeteringInternal()
}
if (fboId == 0) {
runNightVisionSampling()
}
GlUtils.checkGlError("onDrawFrame")
}
@@ -3086,7 +3003,6 @@ class LutRenderer(context: Context) : GLSurfaceView.Renderer {
suppressBaselineLayer = true,
suppressCreativeLayer = true,
suppressCameraEngine = true,
suppressNightVisionTone = true,
)
}
@@ -3101,93 +3017,6 @@ class LutRenderer(context: Context) : GLSurfaceView.Renderer {
dispatchMeteringCalculation(completedBytes, currentMeteringPoint, currentMode)
}
private fun runNightVisionSampling() {
if (!nightVisionEnabled) return
val size = NightVisionTone.MODEL_SIZE
val pixelSize = size * size * 4
if (!ensureNightVisionFbo() || !ensurePixelPackPbos(nightVisionPboIds, pixelSize)) return
val writeIndex = nightVisionPboIndex % 2
val readIndex = (nightVisionPboIndex + 1) % 2
if (nightVisionPboIndex > 0) {
readReadyPixelPackBuffer(nightVisionPboIds, nightVisionPboFences, readIndex, pixelSize)
?.let(nightVisionEstimator::submit)
}
val now = SystemClock.elapsedRealtime()
if (now - lastNightVisionSampleTime < NIGHT_VISION_SAMPLE_INTERVAL_MS) return
if (!isPixelPackBufferWritable(nightVisionPboFences, writeIndex)) return
lastNightVisionSampleTime = now
// Crop the capture composition first, then sample its central 2/3 in each dimension.
// The square viewport resizes that region to the same MODEL_SIZE² as capture input.
val samplingMatrix = buildMvpMatrix(captureWidth, captureHeight).apply {
val scale = 1f / NightVisionTone.SAMPLE_FRAME_FRACTION
Matrix.scaleM(this, 0, scale, scale, 1f)
}
try {
drawInternal(
fboId = nightVisionFboId,
width = size,
height = size,
targetMvpMatrix = samplingMatrix,
suppressBaselineLayer = true,
suppressCreativeLayer = true,
suppressCameraEngine = true,
suppressNightVisionTone = true,
)
GLES30.glBindBuffer(GLES30.GL_PIXEL_PACK_BUFFER, nightVisionPboIds[writeIndex])
GLES30.glReadPixels(0, 0, size, size, GLES30.GL_RGBA, GLES30.GL_UNSIGNED_BYTE, 0)
nightVisionPboFences[writeIndex] = GLES30.glFenceSync(GLES30.GL_SYNC_GPU_COMMANDS_COMPLETE, 0)
nightVisionPboIndex++
} finally {
restorePixelReadbackState()
}
}
private fun ensureNightVisionFbo(): Boolean {
if (nightVisionFboId != 0 && nightVisionTextureId != 0) return true
val size = NightVisionTone.MODEL_SIZE
val textures = IntArray(1)
GLES30.glGenTextures(1, textures, 0)
nightVisionTextureId = textures[0]
GLES30.glBindTexture(GLES30.GL_TEXTURE_2D, nightVisionTextureId)
GLES30.glTexImage2D(
GLES30.GL_TEXTURE_2D, 0, GLES30.GL_RGBA, size, size, 0,
GLES30.GL_RGBA, GLES30.GL_UNSIGNED_BYTE, null
)
GLES30.glTexParameteri(GLES30.GL_TEXTURE_2D, GLES30.GL_TEXTURE_MIN_FILTER, GLES30.GL_LINEAR)
GLES30.glTexParameteri(GLES30.GL_TEXTURE_2D, GLES30.GL_TEXTURE_MAG_FILTER, GLES30.GL_LINEAR)
GLES30.glTexParameteri(GLES30.GL_TEXTURE_2D, GLES30.GL_TEXTURE_WRAP_S, GLES30.GL_CLAMP_TO_EDGE)
GLES30.glTexParameteri(GLES30.GL_TEXTURE_2D, GLES30.GL_TEXTURE_WRAP_T, GLES30.GL_CLAMP_TO_EDGE)
val fbos = IntArray(1)
GLES30.glGenFramebuffers(1, fbos, 0)
nightVisionFboId = fbos[0]
GLES30.glBindFramebuffer(GLES30.GL_FRAMEBUFFER, nightVisionFboId)
GLES30.glFramebufferTexture2D(
GLES30.GL_FRAMEBUFFER, GLES30.GL_COLOR_ATTACHMENT0,
GLES30.GL_TEXTURE_2D, nightVisionTextureId, 0
)
val complete = GLES30.glCheckFramebufferStatus(GLES30.GL_FRAMEBUFFER) == GLES30.GL_FRAMEBUFFER_COMPLETE
GLES30.glBindFramebuffer(GLES30.GL_FRAMEBUFFER, 0)
GLES30.glBindTexture(GLES30.GL_TEXTURE_2D, 0)
if (!complete) {
PLog.e(TAG, "Failed to create night vision sampling FBO")
releaseNightVisionGl()
}
return complete
}
private fun releaseNightVisionGl() {
releasePixelPackPbos(nightVisionPboIds, nightVisionPboFences)
nightVisionPboIndex = 0
if (nightVisionFboId != 0) GLES30.glDeleteFramebuffers(1, intArrayOf(nightVisionFboId), 0)
if (nightVisionTextureId != 0) GLES30.glDeleteTextures(1, intArrayOf(nightVisionTextureId), 0)
if (nightToneTextureId != 0) GLES30.glDeleteTextures(1, intArrayOf(nightToneTextureId), 0)
nightVisionFboId = 0
nightVisionTextureId = 0
nightToneTextureId = 0
nightToneActive = false
}
private fun ensurePixelPackPbos(pboIds: IntArray, pixelSize: Int): Boolean {
if (pboIds[0] != 0 && pboIds[1] != 0) return true
if (pboIds.any { it != 0 }) {
@@ -3486,7 +3315,6 @@ class LutRenderer(context: Context) : GLSurfaceView.Renderer {
} catch (e: Exception) {
PLog.e(TAG, "Error shutting down metering executor", e)
}
nightVisionEstimator.close()
// 释放 SurfaceTexture
surfaceTexture?.release()
surfaceTexture = null
@@ -3586,7 +3414,6 @@ class LutRenderer(context: Context) : GLSurfaceView.Renderer {
pboId = 0
}
releasePixelPackPbos(meteringPboIds, meteringPboFences)
releaseNightVisionGl()
if (meteringFboId != 0) {
GLES30.glDeleteFramebuffers(1, intArrayOf(meteringFboId), 0)
@@ -1,87 +0,0 @@
package com.hinnka.mycamera.lut
import android.content.Context
import android.os.SystemClock
import com.hinnka.mycamera.ml.NightVisionToneModel
import com.hinnka.mycamera.processor.NightVisionTone
import com.hinnka.mycamera.processor.NightVisionToneCurve
import com.hinnka.mycamera.utils.PLog
import kotlinx.coroutines.CancellationException
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.SupervisorJob
import kotlinx.coroutines.cancel
import kotlinx.coroutines.launch
import java.util.concurrent.atomic.AtomicBoolean
import java.util.concurrent.atomic.AtomicInteger
import kotlin.math.exp
/**
* Turns preview samples (RGBA8, [NightVisionTone.MODEL_SIZE]², camera input before any curve)
* into a temporally smoothed night vision curve. At most one estimate runs at a time; samples
* arriving meanwhile are dropped, so the model never queues behind the preview.
*/
internal class NightVisionPreviewEstimator(
context: Context,
private val onCurve: (NightVisionToneCurve) -> Unit,
) {
private val appContext = context.applicationContext
private val scope = CoroutineScope(SupervisorJob() + Dispatchers.Default)
private val busy = AtomicBoolean(false)
private val generation = AtomicInteger(0)
@Volatile
private var smoothed: NightVisionToneCurve? = null
private var lastUpdateNanos = 0L
private var lastDiagnosticLogNanos = 0L
fun submit(rgba: ByteArray) {
if (!busy.compareAndSet(false, true)) return
val requestGeneration = generation.get()
scope.launch {
try {
val input = NightVisionTone.modelInputFromRgba(rgba)
val target = NightVisionToneModel.estimate(appContext, input) ?: return@launch
if (requestGeneration != generation.get()) return@launch
val now = SystemClock.elapsedRealtimeNanos()
if (now - lastDiagnosticLogNanos >= DIAGNOSTIC_LOG_INTERVAL_NANOS) {
PLog.d(TAG, "Estimated curve strength=${target.strength} whitePoint=${target.whitePoint}")
lastDiagnosticLogNanos = now
}
val previous = smoothed
val next = if (previous == null) {
target
} else {
val elapsedSeconds = (now - lastUpdateNanos) / 1_000_000_000f
previous.blendedToward(target, 1f - exp(-elapsedSeconds / SMOOTHING_TIME_CONSTANT_SECONDS))
}
smoothed = next
lastUpdateNanos = now
onCurve(next)
} catch (cancelled: CancellationException) {
throw cancelled
} catch (error: Exception) {
PLog.e(TAG, "Night vision preview curve estimation failed", error)
} finally {
busy.set(false)
}
}
}
/** Drops the smoothing history and discards estimates already in flight. */
fun reset() {
generation.incrementAndGet()
smoothed = null
}
fun close() {
reset()
scope.cancel()
}
private companion object {
const val TAG = "NightVisionPreview"
const val SMOOTHING_TIME_CONSTANT_SECONDS = 0.4f
const val DIAGNOSTIC_LOG_INTERVAL_NANOS = 2_000_000_000L
}
}
@@ -1,190 +0,0 @@
package com.hinnka.mycamera.lut
import android.opengl.GLES30
import com.hinnka.mycamera.processor.NightVisionTone
import com.hinnka.mycamera.processor.NightVisionToneCurve
import com.hinnka.mycamera.raw.RawFullscreenQuad
import java.nio.ByteBuffer
import java.nio.ByteOrder
/**
* GPU night vision tone: one full-screen pass from a source texture into an owned RGBA16F
* texture. [GLSL] is shared with the preview color pass, so preview and capture evaluate the
* same formula. Must be used on a single GL thread with a current context.
*/
internal class NightVisionToneGl {
private val quad = RawFullscreenQuad()
private var program = 0
private var curveTexture = 0
private var outputTexture = 0
private var framebuffer = 0
private var outputWidth = 0
private var outputHeight = 0
/** Returns a texture owned by this instance holding [sourceTextureId] with [curve] applied. */
fun apply(sourceTextureId: Int, width: Int, height: Int, curve: NightVisionToneCurve): Int {
ensureProgram()
uploadCurve(curve)
ensureOutput(width, height)
GLES30.glBindFramebuffer(GLES30.GL_FRAMEBUFFER, framebuffer)
GLES30.glViewport(0, 0, width, height)
GLES30.glUseProgram(program)
quad.bindIdentityTextureMatrix(program)
GLES30.glActiveTexture(GLES30.GL_TEXTURE0)
GLES30.glBindTexture(GLES30.GL_TEXTURE_2D, sourceTextureId)
GLES30.glUniform1i(GLES30.glGetUniformLocation(program, "uSource"), 0)
GLES30.glActiveTexture(GLES30.GL_TEXTURE1)
GLES30.glBindTexture(GLES30.GL_TEXTURE_2D, curveTexture)
GLES30.glUniform1i(GLES30.glGetUniformLocation(program, "uNightToneTexture"), 1)
GLES30.glUniform1f(GLES30.glGetUniformLocation(program, "uNightWhitePoint"), curve.whitePoint)
quad.draw(program)
GLES30.glBindFramebuffer(GLES30.GL_FRAMEBUFFER, 0)
GLES30.glActiveTexture(GLES30.GL_TEXTURE0)
return outputTexture
}
fun release() {
if (program != 0) GLES30.glDeleteProgram(program)
if (framebuffer != 0) GLES30.glDeleteFramebuffers(1, intArrayOf(framebuffer), 0)
val textures = intArrayOf(outputTexture, curveTexture).filter { it != 0 }.toIntArray()
if (textures.isNotEmpty()) GLES30.glDeleteTextures(textures.size, textures, 0)
program = 0
framebuffer = 0
outputTexture = 0
curveTexture = 0
outputWidth = 0
outputHeight = 0
}
private fun ensureProgram() {
if (program != 0) return
program = quad.createProgram(FRAGMENT_SHADER, "NightVisionTone")
check(program != 0) { "Night vision tone program failed to link" }
}
private fun uploadCurve(curve: NightVisionToneCurve) {
if (curveTexture == 0) curveTexture = createCurveTexture()
uploadCurveValues(curveTexture, curve)
}
private fun ensureOutput(width: Int, height: Int) {
if (outputTexture != 0 && outputWidth == width && outputHeight == height) return
if (framebuffer != 0) GLES30.glDeleteFramebuffers(1, intArrayOf(framebuffer), 0)
if (outputTexture != 0) GLES30.glDeleteTextures(1, intArrayOf(outputTexture), 0)
val textures = IntArray(1)
GLES30.glGenTextures(1, textures, 0)
GLES30.glBindTexture(GLES30.GL_TEXTURE_2D, textures[0])
GLES30.glTexStorage2D(GLES30.GL_TEXTURE_2D, 1, GLES30.GL_RGBA16F, width, height)
setNearestClamp()
GLES30.glBindTexture(GLES30.GL_TEXTURE_2D, 0)
val framebuffers = IntArray(1)
GLES30.glGenFramebuffers(1, framebuffers, 0)
GLES30.glBindFramebuffer(GLES30.GL_FRAMEBUFFER, framebuffers[0])
GLES30.glFramebufferTexture2D(
GLES30.GL_FRAMEBUFFER, GLES30.GL_COLOR_ATTACHMENT0, GLES30.GL_TEXTURE_2D, textures[0], 0,
)
val complete = GLES30.glCheckFramebufferStatus(GLES30.GL_FRAMEBUFFER) == GLES30.GL_FRAMEBUFFER_COMPLETE
GLES30.glBindFramebuffer(GLES30.GL_FRAMEBUFFER, 0)
outputTexture = textures[0]
framebuffer = framebuffers[0]
outputWidth = width
outputHeight = height
check(complete) { "Night vision tone framebuffer is incomplete" }
}
companion object {
/** Creates an R32F [NightVisionTone.CURVE_SIZE] x 1 curve texture for [uploadCurveValues]. */
fun createCurveTexture(): Int {
val textures = IntArray(1)
GLES30.glGenTextures(1, textures, 0)
GLES30.glBindTexture(GLES30.GL_TEXTURE_2D, textures[0])
GLES30.glTexImage2D(
GLES30.GL_TEXTURE_2D, 0, GLES30.GL_R32F,
NightVisionTone.CURVE_SIZE, 1, 0, GLES30.GL_RED, GLES30.GL_FLOAT, null,
)
setNearestClamp()
GLES30.glBindTexture(GLES30.GL_TEXTURE_2D, 0)
return textures[0]
}
fun uploadCurveValues(texture: Int, curve: NightVisionToneCurve) {
val buffer = ByteBuffer.allocateDirect(NightVisionTone.CURVE_SIZE * Float.SIZE_BYTES)
.order(ByteOrder.nativeOrder())
buffer.asFloatBuffer().put(curve.values)
GLES30.glBindTexture(GLES30.GL_TEXTURE_2D, texture)
GLES30.glPixelStorei(GLES30.GL_UNPACK_ALIGNMENT, 4)
GLES30.glTexSubImage2D(
GLES30.GL_TEXTURE_2D, 0, 0, 0,
NightVisionTone.CURVE_SIZE, 1, GLES30.GL_RED, GLES30.GL_FLOAT, buffer,
)
GLES30.glBindTexture(GLES30.GL_TEXTURE_2D, 0)
}
private fun setNearestClamp() {
GLES30.glTexParameteri(GLES30.GL_TEXTURE_2D, GLES30.GL_TEXTURE_MIN_FILTER, GLES30.GL_NEAREST)
GLES30.glTexParameteri(GLES30.GL_TEXTURE_2D, GLES30.GL_TEXTURE_MAG_FILTER, GLES30.GL_NEAREST)
GLES30.glTexParameteri(GLES30.GL_TEXTURE_2D, GLES30.GL_TEXTURE_WRAP_S, GLES30.GL_CLAMP_TO_EDGE)
GLES30.glTexParameteri(GLES30.GL_TEXTURE_2D, GLES30.GL_TEXTURE_WRAP_T, GLES30.GL_CLAMP_TO_EDGE)
}
/**
* Uniforms `uNightToneTexture` (R32F, [NightVisionTone.CURVE_SIZE] x 1) and
* `uNightWhitePoint`, and `vec3 applyNightVisionTone(vec3)`: luma-ratio gain from the
* curve, limited per pixel so the brightest channel uses at most
* [NightVisionTone.HIGHLIGHT_HEADROOM] of its headroom relative to the white point.
* [NightVisionTone.estimate] builds the curve and uses the same soft minimum.
*/
val GLSL = """
uniform highp sampler2D uNightToneTexture;
uniform highp float uNightWhitePoint;
const vec3 NIGHT_TONE_LUMA = vec3(0.2126, 0.7152, 0.0722);
float sampleNightTone(float value) {
float position = clamp(value, 0.0, 1.0) * ${NightVisionTone.CURVE_SIZE - 1}.0;
int lowerIndex = min(int(floor(position)), ${NightVisionTone.CURVE_SIZE - 2});
float amount = position - float(lowerIndex);
float lower = texelFetch(uNightToneTexture, ivec2(lowerIndex, 0), 0).r;
float upper = texelFetch(uNightToneTexture, ivec2(lowerIndex + 1, 0), 0).r;
return mix(lower, upper, amount);
}
float nightSoftMin(float a, float b) {
float hard = min(a, b);
float distance = abs(a - b) / ${NightVisionTone.SOFT_MIN_WIDTH};
if (distance > 12.0) return hard;
return hard - ${NightVisionTone.SOFT_MIN_WIDTH} * log(1.0 + exp(-distance));
}
vec3 applyNightVisionTone(vec3 color) {
vec3 c = clamp(color, 0.0, 1.0);
float y = dot(c, NIGHT_TONE_LUMA);
if (y <= 1e-4) return c;
float gain = sampleNightTone(y) / y;
float m = max(max(max(c.r, c.g), c.b), 1e-4);
float normalized = min(m / uNightWhitePoint, 1.0);
float limit = (normalized + (1.0 - normalized) * ${NightVisionTone.HIGHLIGHT_HEADROOM}) / m;
gain = max(nightSoftMin(gain, limit), min(1.0, gain));
return clamp(c * gain, 0.0, 1.0);
}
""".trimIndent()
private val FRAGMENT_SHADER = """
#version 300 es
precision highp float;
in vec2 vTexCoord;
out vec4 fragColor;
uniform sampler2D uSource;
$GLSL
void main() {
vec4 source = texture(uSource, vTexCoord);
fragColor = vec4(applyNightVisionTone(source.rgb), source.a);
}
""".trimIndent()
}
}
@@ -96,8 +96,6 @@ internal object PreviewColorShader {
${PreviewColorShaderModules.SANITIZE}
${BasicToneLutShader.GLSL}
${if (variant.includeNightVisionTone) NightVisionToneGl.GLSL else ""}
float getLuma(vec3 color) {
return dot(color, W);
}
@@ -156,10 +154,6 @@ internal object PreviewColorShader {
}
""" else "vec4 color = samplePreviewSource(uvCoord);"}
${if (variant.includeNightVisionTone) """
color.rgb = applyNightVisionTone(color.rgb);
color.rgb = sanitizeColor(color.rgb);
""" else ""}
${if (variant.includeLiteClarity) "float previewSourceLuma = getLuma(color.rgb);" else ""}
if (${if (variant.includeColorRecipe) "uColorRecipeEnabled" else "false"}) {
@@ -16,8 +16,6 @@ internal data class PreviewColorShaderVariant(
val includeLchMixer: Boolean,
val includePreLogFilmGrain: Boolean,
val includeLutMask: Boolean = false,
/** Night vision luma tone curve on the camera input, before recipe and LUT. */
val includeNightVisionTone: Boolean = false,
val includeSpatialRecipeEffects: Boolean = false,
val includeVideoLog: Boolean = false,
val includeSharpening: Boolean = false,
@@ -51,7 +49,6 @@ internal data class PreviewColorShaderVariant(
lutEnabled: Boolean,
videoLogEnabled: Boolean,
previewLite: Boolean = false,
nightVisionTone: Boolean = false,
): PreviewColorShaderVariant {
val lutCurve = lutConfig?.curve ?: TransferCurve.SRGB
val recipe = !params.isDefault()
@@ -62,7 +59,6 @@ internal data class PreviewColorShaderVariant(
val lite = previewLite && recipe
return PreviewColorShaderVariant(
textureSource = textureSource,
includeNightVisionTone = nightVisionTone,
includeExtendedLutCurves = videoLogEnabled ||
(lutEnabled && lutCurve.shaderId !in SIMPLE_LUT_CURVES),
includeOklchDensity = abs(params.color) > EPSILON,
@@ -1,77 +0,0 @@
package com.hinnka.mycamera.ml
import android.content.Context
import com.google.ai.edge.litert.CompiledModel
import com.hinnka.mycamera.processor.NightVisionTone
import com.hinnka.mycamera.processor.NightVisionToneCurve
import com.hinnka.mycamera.utils.PLog
import kotlinx.coroutines.asCoroutineDispatcher
import kotlinx.coroutines.withContext
import java.util.concurrent.Executors
/**
* Bundled CPGA-Net low-light model (assets/night_vision), used only to estimate the night vision
* tone curve. LiteRtGpuModel is not thread-safe, so preview and capture share one model confined
* to a single thread. XNNPACK rejects the FP16 graph; without the GPU accelerator the mode has no
* curve and [estimate] returns null.
*/
internal object NightVisionToneModel {
private const val TAG = "NightVisionToneModel"
private const val MODEL_ASSET = "night_vision/cpga_fp16.tflite"
private const val PLANE = NightVisionTone.MODEL_SIZE * NightVisionTone.MODEL_SIZE
private const val ELEMENT_COUNT = PLANE * 3
private val dispatcher = Executors.newSingleThreadExecutor { runnable ->
Thread(runnable, "NightVisionTone").apply { isDaemon = true }
}.asCoroutineDispatcher()
private var model: LiteRtGpuModel? = null
private var loadFailed = false
/** Runs the model on [input] (HWC RGB, see [NightVisionTone.modelInputFrom]) and fits the curve. */
suspend fun estimate(context: Context, input: FloatArray): NightVisionToneCurve? = withContext(dispatcher) {
require(input.size == ELEMENT_COUNT) { "Night vision model input must be ${ELEMENT_COUNT} floats" }
val loaded = obtainModel(context.applicationContext) ?: return@withContext null
val nchw = FloatArray(ELEMENT_COUNT)
for (i in 0 until PLANE) {
nchw[i] = input[i * 3]
nchw[PLANE + i] = input[i * 3 + 1]
nchw[2 * PLANE + i] = input[i * 3 + 2]
}
val outputNchw = loaded.run(nchw)
val output = FloatArray(ELEMENT_COUNT)
for (i in 0 until PLANE) {
output[i * 3] = outputNchw[i]
output[i * 3 + 1] = outputNchw[PLANE + i]
output[i * 3 + 2] = outputNchw[2 * PLANE + i]
}
NightVisionTone.estimate(input, output)
}
private fun obtainModel(context: Context): LiteRtGpuModel? {
model?.let { return it }
if (loadFailed) return null
return try {
val modelSize = context.assets.open(MODEL_ASSET).use { it.readBytes().size }
val cache = MlDelegateCacheFactory.create(
context = context,
tag = TAG,
cacheName = "cpga_night_vision_litert",
modelAssetName = MODEL_ASSET,
modelSizeBytes = modelSize,
)
LiteRtGpuModel.fromAsset(
context = context,
assetName = MODEL_ASSET,
cache = cache,
precision = CompiledModel.GpuOptions.Precision.DEFAULT,
inputElementCount = ELEMENT_COUNT,
outputElementCount = ELEMENT_COUNT,
).also { model = it }
} catch (error: Exception) {
loadFailed = true
PLog.e(TAG, "Night vision model unavailable on the GPU accelerator; tone curve disabled", error)
null
}
}
}
@@ -1,54 +0,0 @@
package com.hinnka.mycamera.processor
import android.content.Context
import android.graphics.Bitmap
import com.hinnka.mycamera.gallery.PhotoProcessor
import com.hinnka.mycamera.ml.NightVisionToneModel
import com.hinnka.mycamera.utils.PLog
/**
* Night vision post-processing of the stacked YUV frame, baked into the internal original before
* any LUT or recipe:
* 1. Estimate the tone curve on the stacked frame itself (not the preview curve: the capture
* exposure and ISP processing differ from the preview stream).
* 2. Extra MGC bitmap denoise whose strength follows the noise amplification of that curve; a
* daylight scene gets the identity curve and therefore no extra denoise.
* 3. Apply the curve.
*
* Denoise runs before the curve, while the noise is still at the level the ISO model describes.
* Steps 2 and 3 run on the GPU in one upload/readback ([PhotoProcessor.applyNightVision]).
*/
internal object NightVisionCapture {
private const val TAG = "NightVisionCapture"
/** Returns the processed bitmap; [bitmap] is recycled when a new one replaces it. */
suspend fun process(
context: Context,
bitmap: Bitmap,
sensorIso: Int?,
photoProcessor: PhotoProcessor,
): Bitmap {
val input = NightVisionTone.modelInputFrom(bitmap)
val curve = NightVisionToneModel.estimate(context, input) ?: return bitmap
if (curve.isIdentity) {
PLog.d(TAG, "Scene bright enough; night vision curve is identity, no extra denoise")
return bitmap
}
val strength = NightVisionTone.denoiseStrength(input, curve)
PLog.d(
TAG,
"curve strength=${curve.strength} whitePoint=${curve.whitePoint} " +
"denoise luma=${strength.luma} chroma=${strength.chroma} iso=$sensorIso",
)
val result = photoProcessor.applyNightVision(
bitmap = bitmap,
lumaStrength = strength.luma,
chromaStrength = strength.chroma,
sensorIso = sensorIso,
curve = curve,
)
if (result !== bitmap) bitmap.recycle()
return result
}
}
@@ -1,370 +0,0 @@
package com.hinnka.mycamera.processor
import android.graphics.Bitmap
import android.graphics.Canvas
import android.graphics.ColorSpace
import android.graphics.Matrix
import android.graphics.Paint
import android.graphics.RectF
import java.nio.ByteBuffer
import kotlin.math.abs
import kotlin.math.exp
import kotlin.math.ln
import kotlin.math.max
import kotlin.math.min
import kotlin.math.roundToInt
/**
* Night vision global tone curve, applied to luma only.
*
* Each pixel is scaled by `gain = curve(Y) / Y`, so hue and saturation stay unchanged. The gain is
* then limited per pixel so the brightest channel can use at most [NightVisionTone.HIGHLIGHT_HEADROOM]
* of its remaining headroom, measured against [whitePoint]. The preview shader
* and capture GPU pass share `applyNightVisionTone` ([com.hinnka.mycamera.lut.NightVisionToneGl.GLSL]),
* which implements the same formula.
*/
internal class NightVisionToneCurve(
/** [NightVisionTone.CURVE_SIZE] samples of output luma over input luma in [0, 1]. */
val values: FloatArray,
/** 99.5th percentile of the per-pixel max channel; the highlight cap is relative to it. */
val whitePoint: Float,
/** Scene gate in [0, 1]; 0 means the curve is the identity. */
val strength: Float,
) {
init {
require(values.size == NightVisionTone.CURVE_SIZE) { "Curve needs ${NightVisionTone.CURVE_SIZE} samples" }
}
val isIdentity: Boolean
get() = strength <= 0f
fun lumaAt(y: Float): Float {
val position = y.coerceIn(0f, 1f) * LAST_INDEX
val lower = position.toInt().coerceAtMost(LAST_INDEX - 1)
val amount = position - lower
return values[lower] + (values[lower + 1] - values[lower]) * amount
}
/** Per-pixel gain for encoded RGB in [0, 1]. */
fun pixelGain(r: Float, g: Float, b: Float): Float {
val y = NightVisionTone.luma(r, g, b)
if (y <= MIN_LUMA) return 1f
val gain = lumaAt(y) / y
return limitGain(gain, max(max(r, g), b))
}
/** Applies the highlight cap to [gain] for a pixel whose brightest channel is [maxChannel]. */
fun limitGain(gain: Float, maxChannel: Float): Float {
val m = max(maxChannel, MIN_LUMA)
val normalized = min(m / whitePoint, 1f)
val limit = (normalized + (1f - normalized) * NightVisionTone.HIGHLIGHT_HEADROOM) / m
return max(NightVisionTone.softMin(gain, limit), min(1f, gain))
}
/** Moves this curve toward [target] by [amount] in [0, 1]; used for preview temporal smoothing. */
fun blendedToward(target: NightVisionToneCurve, amount: Float): NightVisionToneCurve {
val t = amount.coerceIn(0f, 1f)
return NightVisionToneCurve(
values = FloatArray(values.size) { values[it] + (target.values[it] - values[it]) * t },
whitePoint = whitePoint + (target.whitePoint - whitePoint) * t,
strength = strength + (target.strength - strength) * t,
)
}
companion object {
private const val LAST_INDEX = NightVisionTone.CURVE_SIZE - 1
private const val MIN_LUMA = 1e-4f
val IDENTITY = NightVisionToneCurve(
values = FloatArray(NightVisionTone.CURVE_SIZE) { it / LAST_INDEX.toFloat() },
whitePoint = 1f,
strength = 0f,
)
}
}
/** MGC bitmap denoise strengths, in [DenoiseStrength] units. */
internal data class NightVisionDenoiseStrength(val luma: Float, val chroma: Float) {
val isZero: Boolean
get() = luma <= 0f && chroma <= 0f
}
/**
* Turns the CPGA-Net low-light output into a [NightVisionToneCurve] and derives the extra denoise
* that the brightening needs.
*
* Curve construction, on the model's 256x256 input and output:
* 1. Bin the input luma, average the output luma per bin, force monotone, smooth.
* 2. Gate by scene brightness: the geometric mean of the per-pixel max channel (as the RAW scene
* brightness measurement uses, on encoded values here). Full strength at <= [GATE_FULL_SIGNAL],
* identity at >= [GATE_OFF_SIGNAL], smoothstep between. The model brightens every image,
* daylight included.
* 3. Cap each tone so it uses at most [HIGHLIGHT_HEADROOM] of its headroom relative to the
* image white point; an underexposed frame keeps a white paper white.
* 4. A shadow-only toe below the median output luma restores the contrast the lift removes.
*
* The toe and the cap both scale with the gate, so a daylight scene gets the identity curve and
* therefore zero extra denoise.
*/
internal object NightVisionTone {
const val MODEL_SIZE = 256
/** Central fraction of the capture width and height sampled by both preview and capture. */
const val SAMPLE_FRAME_FRACTION = 2f / 3f
const val CURVE_SIZE = 256
const val HIGHLIGHT_HEADROOM = 0.55f
private const val BIN_COUNT = 64
private const val MIN_BIN_SAMPLES = 20
private const val SMOOTH_RADIUS = 7
/**
* Calibrated on 87 camera JPEGs labelled by EXIF EV100 (docs/night-vision-mode.md): night
* scenes (EV < 5) sit at 0.16-0.23, daylight (EV >= 10) mostly above 0.30.
*/
private const val GATE_FULL_SIGNAL = 0.18f
private const val GATE_OFF_SIGNAL = 0.30f
/** Floor of the log average: one 8-bit code value, so black pixels do not dominate. */
private const val GATE_SIGNAL_FLOOR = 1f / 255f
private const val TOE_AMOUNT = 0.8f
private const val MIN_TOE_PIVOT = 0.25f
private const val MAX_TOE_PIVOT = 0.75f
private const val WHITE_POINT_PERCENTILE = 0.995f
private const val MIN_WHITE_POINT = 0.2f
const val SOFT_MIN_WIDTH = 0.02f
/**
* Provisional fixed mapping, pending on-device tuning: the extra MGC strength rises linearly
* with the mean noise amplification, from 0 at 1x to the cap at [FULL_STRENGTH_GAIN]x. Luma
* noise follows the curve slope, chroma noise the gain. The bitmap noise calibration was made
* with ISP NR off, so it does not describe an ISP HIGH_QUALITY multi-frame stack; the strength
* is therefore set directly instead of derived from the residual noise.
*/
private const val FULL_STRENGTH_GAIN = 3f
private const val MAX_LUMA_STRENGTH = 0.3f
private const val MAX_CHROMA_STRENGTH = 1.0f
private const val SLOPE_STEP = 1f / 255f
private const val WR = 0.2126f
private const val WG = 0.7152f
private const val WB = 0.0722f
fun luma(r: Float, g: Float, b: Float): Float = WR * r + WG * g + WB * b
/** Smooth minimum: within about [SOFT_MIN_WIDTH] of the hard minimum, never above it. */
fun softMin(a: Float, b: Float): Float {
val hard = min(a, b)
val distance = abs(a - b) / SOFT_MIN_WIDTH
if (distance > 12f) return hard
return hard - SOFT_MIN_WIDTH * ln(1f + exp(-distance))
}
/**
* Builds the curve from the model's [input] and [output], both HWC RGB floats in [0, 1] of
* [MODEL_SIZE] x [MODEL_SIZE] pixels.
*/
fun estimate(input: FloatArray, output: FloatArray): NightVisionToneCurve {
val pixelCount = MODEL_SIZE * MODEL_SIZE
require(input.size == pixelCount * 3 && output.size == pixelCount * 3) {
"Night vision tone expects ${MODEL_SIZE}x$MODEL_SIZE RGB input and output"
}
val inputLuma = FloatArray(pixelCount)
val maxChannel = FloatArray(pixelCount)
val binSum = DoubleArray(BIN_COUNT)
val binCount = IntArray(BIN_COUNT)
var logSignalSum = 0.0
for (i in 0 until pixelCount) {
val o = i * 3
val r = input[o].coerceIn(0f, 1f)
val g = input[o + 1].coerceIn(0f, 1f)
val b = input[o + 2].coerceIn(0f, 1f)
val y = luma(r, g, b)
inputLuma[i] = y
maxChannel[i] = max(max(r, g), b)
logSignalSum += ln(maxChannel[i] + GATE_SIGNAL_FLOOR)
val outY = luma(
output[o].coerceIn(0f, 1f),
output[o + 1].coerceIn(0f, 1f),
output[o + 2].coerceIn(0f, 1f),
)
val bin = (y * BIN_COUNT).toInt().coerceIn(0, BIN_COUNT - 1)
binSum[bin] += outY
binCount[bin]++
}
val signal = exp(logSignalSum / pixelCount).toFloat() - GATE_SIGNAL_FLOOR
val strength = gate(signal)
val whitePoint = percentile(maxChannel, WHITE_POINT_PERCENTILE).coerceIn(MIN_WHITE_POINT, 1f)
if (strength <= 0f) {
return NightVisionToneCurve(NightVisionToneCurve.IDENTITY.values.copyOf(), whitePoint, 0f)
}
val modelCurve = fitModelCurve(binSum, binCount)
val curve = FloatArray(CURVE_SIZE)
for (i in 0 until CURVE_SIZE) {
val x = i / (CURVE_SIZE - 1f)
val lifted = x + strength * (modelCurve[i] - x)
val normalized = min(x / whitePoint, 1f)
val cap = normalized + (1f - normalized) * HIGHLIGHT_HEADROOM
curve[i] = max(softMin(lifted, cap), min(lifted, x))
}
val mapped = FloatArray(pixelCount) { interpolate(curve, inputLuma[it]) }
val pivot = percentile(mapped, 0.5f).coerceIn(MIN_TOE_PIVOT, MAX_TOE_PIVOT)
val toe = TOE_AMOUNT * strength
for (i in 0 until CURVE_SIZE) {
val c = curve[i]
if (c < pivot) {
val t = 1f - c / pivot
curve[i] = c - toe * c * t * t
}
}
enforceMonotone(curve)
curve[0] = 0f
return NightVisionToneCurve(curve, whitePoint, strength)
}
/**
* Mean noise amplification of [curve] over the model input [input] (HWC RGB), mapped to MGC
* strengths. The identity curve returns zero.
*/
fun denoiseStrength(input: FloatArray, curve: NightVisionToneCurve): NightVisionDenoiseStrength {
if (curve.isIdentity) return NightVisionDenoiseStrength(0f, 0f)
val pixelCount = input.size / 3
var lumaExcess = 0.0
var chromaExcess = 0.0
for (i in 0 until pixelCount) {
val o = i * 3
val r = input[o].coerceIn(0f, 1f)
val g = input[o + 1].coerceIn(0f, 1f)
val b = input[o + 2].coerceIn(0f, 1f)
val y = luma(r, g, b)
val gain = curve.pixelGain(r, g, b)
val lo = (y - SLOPE_STEP).coerceAtLeast(0f)
val hi = (y + SLOPE_STEP).coerceAtMost(1f)
val slope = (curve.lumaAt(hi) - curve.lumaAt(lo)) / (hi - lo)
// Where the highlight cap lowers the gain, the local luma slope drops by the same ratio.
val uncappedGain = if (y > 1e-4f) curve.lumaAt(y) / y else 1f
val capRatio = if (uncappedGain > 0f) gain / uncappedGain else 1f
lumaExcess += (slope * capRatio - 1f).coerceAtLeast(0f)
chromaExcess += (gain - 1f).coerceAtLeast(0f)
}
return NightVisionDenoiseStrength(
luma = scaledStrength(lumaExcess / pixelCount, MAX_LUMA_STRENGTH),
chroma = scaledStrength(chromaExcess / pixelCount, MAX_CHROMA_STRENGTH),
)
}
/**
* Resizes the central [SAMPLE_FRAME_FRACTION] of each capture dimension to [MODEL_SIZE]².
* Matches the preview sampling matrix; the fitted curve is still applied to the whole image.
* Returns HWC RGB floats in the bitmap's encoded color space.
*/
fun modelInputFrom(bitmap: Bitmap): FloatArray {
val scaled = Bitmap.createBitmap(
MODEL_SIZE,
MODEL_SIZE,
Bitmap.Config.ARGB_8888,
bitmap.hasAlpha(),
bitmap.colorSpace ?: ColorSpace.get(ColorSpace.Named.SRGB),
)
try {
val insetX = bitmap.width * (1f - SAMPLE_FRAME_FRACTION) * 0.5f
val insetY = bitmap.height * (1f - SAMPLE_FRAME_FRACTION) * 0.5f
val matrix = Matrix().apply {
setRectToRect(
RectF(insetX, insetY, bitmap.width - insetX, bitmap.height - insetY),
RectF(0f, 0f, MODEL_SIZE.toFloat(), MODEL_SIZE.toFloat()),
Matrix.ScaleToFit.FILL,
)
}
Canvas(scaled).drawBitmap(bitmap, matrix, Paint(Paint.FILTER_BITMAP_FLAG))
val bytes = ByteBuffer.allocate(scaled.rowBytes * scaled.height)
scaled.copyPixelsToBuffer(bytes)
return modelInputFromRgba(bytes.array(), scaled.rowBytes)
} finally {
scaled.recycle()
}
}
/** Converts [MODEL_SIZE]² RGBA8 pixels with [rowBytes] stride to HWC RGB floats. */
fun modelInputFromRgba(rgba: ByteArray, rowBytes: Int = MODEL_SIZE * 4): FloatArray {
val out = FloatArray(MODEL_SIZE * MODEL_SIZE * 3)
var o = 0
for (row in 0 until MODEL_SIZE) {
var p = row * rowBytes
for (col in 0 until MODEL_SIZE) {
out[o++] = (rgba[p].toInt() and 0xFF) / 255f
out[o++] = (rgba[p + 1].toInt() and 0xFF) / 255f
out[o++] = (rgba[p + 2].toInt() and 0xFF) / 255f
p += 4
}
}
return out
}
private fun scaledStrength(meanExcessGain: Double, maxStrength: Float): Float {
val fraction = (meanExcessGain / (FULL_STRENGTH_GAIN - 1f)).toFloat().coerceIn(0f, 1f)
return DenoiseStrength.clamp(maxStrength * fraction)
}
private fun gate(signal: Float): Float {
val t = ((GATE_OFF_SIGNAL - signal) / (GATE_OFF_SIGNAL - GATE_FULL_SIGNAL)).coerceIn(0f, 1f)
return t * t * (3f - 2f * t)
}
private fun fitModelCurve(binSum: DoubleArray, binCount: IntArray): FloatArray {
val xs = ArrayList<Float>(BIN_COUNT + 2)
val ys = ArrayList<Float>(BIN_COUNT + 2)
xs += 0f
ys += 0f
for (bin in 0 until BIN_COUNT) {
if (binCount[bin] >= MIN_BIN_SAMPLES) {
xs += (bin + 0.5f) / BIN_COUNT
ys += (binSum[bin] / binCount[bin]).toFloat()
}
}
xs += 1f
ys += 1f
for (i in 1 until ys.size) ys[i] = min(1f, max(ys[i], ys[i - 1]))
val sampled = FloatArray(CURVE_SIZE)
var segment = 0
for (i in 0 until CURVE_SIZE) {
val x = i / (CURVE_SIZE - 1f)
while (segment < xs.size - 2 && x > xs[segment + 1]) segment++
val x0 = xs[segment]
val x1 = xs[segment + 1]
val t = if (x1 > x0) ((x - x0) / (x1 - x0)).coerceIn(0f, 1f) else 0f
sampled[i] = ys[segment] + (ys[segment + 1] - ys[segment]) * t
}
val smoothed = FloatArray(CURVE_SIZE)
val window = 2 * SMOOTH_RADIUS + 1
for (i in 0 until CURVE_SIZE) {
var sum = 0f
for (k in -SMOOTH_RADIUS..SMOOTH_RADIUS) {
sum += sampled[(i + k).coerceIn(0, CURVE_SIZE - 1)]
}
smoothed[i] = sum / window
}
smoothed[0] = 0f
enforceMonotone(smoothed)
return smoothed
}
private fun interpolate(curve: FloatArray, x: Float): Float {
val position = x.coerceIn(0f, 1f) * (curve.size - 1)
val lower = position.toInt().coerceAtMost(curve.size - 2)
val t = position - lower
return curve[lower] + (curve[lower + 1] - curve[lower]) * t
}
private fun enforceMonotone(curve: FloatArray) {
for (i in 1 until curve.size) curve[i] = max(curve[i], curve[i - 1])
}
private fun percentile(values: FloatArray, fraction: Float): Float {
val sorted = values.copyOf()
sorted.sort()
return sorted[((sorted.size - 1) * fraction).roundToInt()]
}
}
@@ -239,10 +239,6 @@ class CameraGLSurfaceView @JvmOverloads constructor(
renderer.meteringEnabled = enabled
}
fun setNightVisionEnabled(enabled: Boolean) {
renderer.nightVisionEnabled = enabled
}
/**
* 设置 LUT
*
@@ -77,7 +77,6 @@ fun CameraPreviewGL(
onFirstPreviewFrame: (() -> Unit)? = null,
livePhotoRecorder: LivePhotoRecorder? = null,
videoLogProfile: VideoLogProfile = VideoLogProfile.OFF,
nightVisionEnabled: Boolean = false,
isEyeFocusBusy: Boolean = false,
onGLSurfaceViewReady: ((CameraGLSurfaceView) -> Unit)? = null,
isAutoFocus: Boolean = true,
@@ -337,7 +336,6 @@ fun CameraPreviewGL(
livePhotoRecorder.takeIf { captureMode == CaptureMode.PHOTO }
)
glSurfaceView.setVideoLogProfile(videoLogProfile)
glSurfaceView.setNightVisionEnabled(nightVisionEnabled)
glSurfaceView.setAutoFocus(isAutoFocus)
glSurfaceView.setFocusPeakingEnabled(focusPeakingEnabled)
glSurfaceView.setEyeFocusBusy(isEyeFocusBusy)
@@ -131,7 +131,6 @@ enum class ActivePanel {
private enum class CameraShootingMode {
PROFESSIONAL,
PHOTO,
NIGHT_VISION,
VIDEO
}
@@ -654,27 +653,17 @@ fun CameraScreen(
val targetCaptureMode = when (mode) {
CameraShootingMode.PROFESSIONAL,
CameraShootingMode.PHOTO,
CameraShootingMode.NIGHT_VISION -> CaptureMode.PHOTO
CameraShootingMode.PHOTO -> CaptureMode.PHOTO
CameraShootingMode.VIDEO -> CaptureMode.VIDEO
}
val targetUseRaw = when (mode) {
CameraShootingMode.PROFESSIONAL -> true
CameraShootingMode.PHOTO,
CameraShootingMode.NIGHT_VISION -> false
CameraShootingMode.VIDEO -> null
}
// Video keeps the night vision preference so returning to photo restores it.
val targetNightVision = when (mode) {
CameraShootingMode.NIGHT_VISION -> true
CameraShootingMode.PROFESSIONAL,
CameraShootingMode.PHOTO -> false
CameraShootingMode.VIDEO -> state.nightVisionEnabled
CameraShootingMode.VIDEO -> null
}
if (
targetCaptureMode == state.captureMode &&
(targetUseRaw == null || targetUseRaw == state.useRaw) &&
targetNightVision == state.nightVisionEnabled
(targetUseRaw == null || targetUseRaw == state.useRaw)
) {
return
}
@@ -683,7 +672,7 @@ fun CameraScreen(
if (targetCaptureMode == CaptureMode.VIDEO && state.aspectRatio == AspectRatio.XPAN) {
viewModel.setAspectRatio(AspectRatio.RATIO_4_3)
}
viewModel.setShootingMode(targetCaptureMode, targetUseRaw, targetNightVision)
viewModel.setShootingMode(targetCaptureMode, targetUseRaw)
}
}
@@ -1351,7 +1340,6 @@ fun CameraScreen(
},
livePhotoRecorder = viewModel.livePhotoRecorder,
videoLogProfile = state.videoConfig.logProfile,
nightVisionEnabled = state.isNightVisionActive,
isEyeFocusBusy = viewModel.isEyeFocusBusy,
isAutoFocus = state.isAutoFocus,
focusPeakingEnabled = focusPeakingEnabled && !state.isHyperfocalFocusEnabled,
@@ -1763,7 +1751,6 @@ fun CameraScreen(
CameraTopSheet(
visible = activePanel == ActivePanel.SETTINGS,
captureMode = state.captureMode,
nightVisionEnabled = state.nightVisionEnabled,
aspectRatio = state.aspectRatio,
topSheetAspectRatios = topSheetAspectRatios,
onAspectRatioChange = { runPreviewTransition { viewModel.setAspectRatio(it) } },
@@ -2237,7 +2224,6 @@ private fun Controls(
shootingMode = when {
state.captureMode == CaptureMode.VIDEO -> CameraShootingMode.VIDEO
state.useRaw && state.isRawSupported -> CameraShootingMode.PROFESSIONAL
state.nightVisionEnabled -> CameraShootingMode.NIGHT_VISION
else -> CameraShootingMode.PHOTO
},
professionalModeEnabled = state.isRawSupported,
@@ -2696,7 +2682,6 @@ private val CameraShootingMode.labelRes: Int
get() = when (this) {
CameraShootingMode.PROFESSIONAL -> R.string.capture_mode_professional
CameraShootingMode.PHOTO -> R.string.capture_mode_photo
CameraShootingMode.NIGHT_VISION -> R.string.capture_mode_night_vision
CameraShootingMode.VIDEO -> R.string.capture_mode_video
}
@@ -61,7 +61,6 @@ private val CameraTopSheetContentTopPadding = 32.dp
fun CameraTopSheet(
visible: Boolean,
captureMode: CaptureMode,
nightVisionEnabled: Boolean,
aspectRatio: AspectRatio,
topSheetAspectRatios: List<AspectRatio>,
onAspectRatioChange: (AspectRatio) -> Unit,
@@ -202,7 +201,7 @@ fun CameraTopSheet(
onClick = { showRenderingEngineSheet = true },
modifier = itemModifier
)
} else if (!nightVisionEnabled) {
} else {
QuickSettingToggle(
title = stringResource(R.string.settings_use_jpg_max),
checked = useJpgMax,
@@ -560,7 +560,6 @@ private data class CameraFeatureUpdate(
val rawBaselineLutId: SettingValue<String?>? = null,
val activePresetId: SettingValue<String?>? = null,
val useMultipleExposure: SettingValue<Boolean>? = null,
val nightVision: SettingValue<Boolean>? = null
)
/**
@@ -1000,10 +999,8 @@ class CameraViewModel(application: Application) : AndroidViewModel(application)
var desiredUseRawMax = prefs.useRawMax
var desiredUseMultipleExposure = prefs.useMultipleExposure
var desiredRawRenderingEngine = prefs.rawRenderingEngine
var desiredNightVision = prefs.nightVisionMode
update.useRaw?.let { desiredUseRaw = it.value }
update.nightVision?.let { desiredNightVision = it.value }
update.useJpgMax?.let { desiredUseJpgMax = it.value }
update.useRawMax?.let { desiredUseRawMax = it.value }
update.useMultipleExposure?.let { desiredUseMultipleExposure = it.value }
@@ -1029,19 +1026,9 @@ class CameraViewModel(application: Application) : AndroidViewModel(application)
desiredUseJpgMax = false
desiredUseRawMax = false
}
// 夜视模式与 RAW、多重曝光互斥:显式开启 RAW 或多重曝光时退出夜视,否则夜视优先。
if (update.useRaw?.value == true || update.useRawMax?.value == true ||
update.useMultipleExposure?.value == true
) {
desiredNightVision = false
}
if (desiredNightVision) {
desiredUseRaw = false
desiredUseMultipleExposure = false
}
// 专业模式与 HDR+ 是同一个拍摄能力,不再保留可独立关闭的状态。
desiredUseRawMax = desiredUseRaw
val activeUseJpgMax = (desiredUseJpgMax || desiredNightVision) && !desiredUseRaw
val activeUseJpgMax = desiredUseJpgMax && !desiredUseRaw
if (activeUseJpgMax && prefs.useLivePhoto) {
cameraController.setUseLivePhoto(false)
userPreferencesRepository.update { useLivePhoto = false }
@@ -1107,9 +1094,6 @@ class CameraViewModel(application: Application) : AndroidViewModel(application)
) {
cameraController.setMultiFrameOutputScale(desiredMultiFrameOutputScale)
}
if (desiredNightVision != currentState.nightVisionEnabled) {
cameraController.setNightVisionEnabled(desiredNightVision)
}
if (captureModeWillChange) {
cameraController.setCaptureMode(targetCaptureMode)
@@ -1188,9 +1172,6 @@ class CameraViewModel(application: Application) : AndroidViewModel(application)
if (update.useRaw != null || desiredUseRaw != prefs.useRaw) useRaw = desiredUseRaw
if (update.useJpgMax != null || desiredUseJpgMax != prefs.useJpgMax) useJpgMax = desiredUseJpgMax
if (update.useRawMax != null || desiredUseRawMax != prefs.useRawMax) useRawMax = desiredUseRawMax
if (update.nightVision != null || desiredNightVision != prefs.nightVisionMode) {
nightVisionMode = desiredNightVision
}
update.ultraHdrGainMapEnabled?.let { ultraHdrGainMapEnabled = it.value }
if (update.useMultipleExposure != null || desiredUseMultipleExposure != prefs.useMultipleExposure) {
useMultipleExposure = desiredUseMultipleExposure
@@ -1914,9 +1895,6 @@ class CameraViewModel(application: Application) : AndroidViewModel(application)
if (currentCameraState.multiFrameOutputScale != effectiveMultiFrameOutputScale) {
cameraController.setMultiFrameOutputScale(effectiveMultiFrameOutputScale)
}
if (currentCameraState.nightVisionEnabled != it.nightVisionMode) {
cameraController.setNightVisionEnabled(it.nightVisionMode)
}
if (
currentCameraState.jpgMultiFrameDenoiseFrameCount !=
it.jpgMultiFrameDenoiseFrameCount
@@ -2192,7 +2170,6 @@ class CameraViewModel(application: Application) : AndroidViewModel(application)
cameraController.setJpgMultiFrameDenoiseFrameCount(
prefs.jpgMultiFrameDenoiseFrameCount
)
cameraController.setNightVisionEnabled(prefs.nightVisionMode)
cameraController.setHdrPlusMergeMode(prefs.hdrPlusMergeMode)
cameraController.setHdrPlusFrameCount(prefs.hdrPlusFrameCount)
cameraController.setUseJpgMaxHdrComposition(prefs.useJpgMaxHdrComposition)
@@ -3592,18 +3569,18 @@ class CameraViewModel(application: Application) : AndroidViewModel(application)
}
fun setCaptureMode(mode: CaptureMode) {
setShootingMode(mode, useRaw = null, nightVision = state.value.nightVisionEnabled)
setShootingMode(mode, useRaw = null)
}
/**
* Applies the shooting mode selection (professional / photo / night vision / video) as one
* Applies the shooting mode selection (professional / photo / video) as one
* ordered operation.
*
* RAW is updated before leaving video mode so the public camera state never passes through
* the other photo mode (VIDEO -> PROFESSIONAL -> PHOTO, for example). The capture-mode
* change then owns the single camera restart required by the operation.
*/
fun setShootingMode(mode: CaptureMode, useRaw: Boolean?, nightVision: Boolean) {
fun setShootingMode(mode: CaptureMode, useRaw: Boolean?) {
if (state.value.videoRecordingState.isRecording ||
state.value.videoRecordingState.isProcessing
) {
@@ -3613,16 +3590,13 @@ class CameraViewModel(application: Application) : AndroidViewModel(application)
shootingModeSwitchJob?.cancel()
val rawNeedsUpdate = useRaw != null &&
(state.value.useRaw != useRaw || userPreferencesRepository.current.useRaw != useRaw)
val nightVisionNeedsUpdate = state.value.nightVisionEnabled != nightVision ||
userPreferencesRepository.current.nightVisionMode != nightVision
if (state.value.captureMode == mode && !rawNeedsUpdate && !nightVisionNeedsUpdate) return
if (state.value.captureMode == mode && !rawNeedsUpdate) return
shootingModeSwitchJob = viewModelScope.launch {
applyCameraFeatureUpdate(
CameraFeatureUpdate(
captureMode = SettingValue(mode),
useRaw = useRaw?.let(::SettingValue),
nightVision = SettingValue(nightVision),
)
)
}
@@ -5857,7 +5831,6 @@ class CameraViewModel(application: Application) : AndroidViewModel(application)
rawMaxHdrFusionEnabled = rawMaxHdrFusionEnabled,
rawMaxSpatialOutputMode = rawSpatialOutputMode,
rawMaxMergeMethod = rawMaxMergeMethod,
nightVision = settings.state.isNightVisionActive,
)
}
PLog.d(TAG, "Image saved: $photoId, LUT: $lutIdToSave, Frame: $frameIdToSave")
@@ -24,7 +24,6 @@
<string name="take_photo">拍照</string>
<string name="capture_mode_professional">專業</string>
<string name="capture_mode_photo">照片</string>
<string name="capture_mode_night_vision">夜視</string>
<string name="capture_mode_video">影片</string>
<!-- Exposure Controls -->
-1
View File
@@ -503,7 +503,6 @@
<string name="take_photo">Prendre une photo</string>
<string name="capture_mode_professional">Pro</string>
<string name="capture_mode_photo">Photo</string>
<string name="capture_mode_night_vision">Nuit</string>
<string name="capture_mode_video">Vidéo</string>
<string name="camera_focus_auto">AUTO</string>
<string name="camera_hyperfocal_label">HYP</string>
-1
View File
@@ -357,7 +357,6 @@
<string name="take_photo">撮影</string>
<string name="capture_mode_professional">プロ</string>
<string name="capture_mode_photo">写真</string>
<string name="capture_mode_night_vision">夜景</string>
<string name="capture_mode_video">動画</string>
<string name="camera_focus_auto">オート</string>
<string name="settings_top_sheet_aspect_ratios_summary">表示中: %1$s</string>
-1
View File
@@ -24,7 +24,6 @@
<string name="take_photo">ภาพถ่าย</string>
<string name="capture_mode_professional">โปร</string>
<string name="capture_mode_photo">ภาพถ่าย</string>
<string name="capture_mode_night_vision">กลางคืน</string>
<string name="capture_mode_video">วิดีโอ</string>
<!-- Exposure Controls -->
@@ -25,7 +25,6 @@
<string name="take_photo">拍照</string>
<string name="capture_mode_professional">专业</string>
<string name="capture_mode_photo">照片</string>
<string name="capture_mode_night_vision">夜视</string>
<string name="capture_mode_video">视频</string>
<!-- Exposure Controls -->
@@ -24,7 +24,6 @@
<string name="take_photo">拍照</string>
<string name="capture_mode_professional">專業</string>
<string name="capture_mode_photo">照片</string>
<string name="capture_mode_night_vision">夜視</string>
<string name="capture_mode_video">影片</string>
<!-- Exposure Controls -->
@@ -24,7 +24,6 @@
<string name="take_photo">拍照</string>
<string name="capture_mode_professional">專業</string>
<string name="capture_mode_photo">照片</string>
<string name="capture_mode_night_vision">夜視</string>
<string name="capture_mode_video">影片</string>
<!-- Exposure Controls -->
-1
View File
@@ -25,7 +25,6 @@
<string name="take_photo">Take Photo</string>
<string name="capture_mode_professional">Pro</string>
<string name="capture_mode_photo">Photo</string>
<string name="capture_mode_night_vision">Night</string>
<string name="capture_mode_video">Video</string>
<!-- Exposure Controls -->