feat: night vision mode
This commit is contained in:
1 parent
84bfa54773
commit
bf72729c27
32 files changed
+1295
-135
No files matched your search
@@ -0,0 +1,14 @@
|
||||
# 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.
@@ -0,0 +1,21 @@
|
||||
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.
|
||||
@@ -1468,10 +1468,13 @@ int RunLowFrequencyChromaCorrection(const LowFrequencyChromaRequest& request) {
|
||||
request.prepared_normalized_chroma_quadratic < 0.0f) {
|
||||
return -1;
|
||||
}
|
||||
// The same padded geometry as the in-call branch: the low image is the padded
|
||||
// full-resolution frame box-downsampled by 2^L, the strength map its quarter.
|
||||
const int padded_width = RoundUp(request.full_width, 128);
|
||||
const int padded_height = RoundUp(request.full_height, 16);
|
||||
// The low image is the padded full-resolution frame box-downsampled by 2^L, the strength
|
||||
// map its quarter. The MGC pipelines it runs through (RgbRawToYuv, chroma pyramid) need the
|
||||
// same 128 x 16 alignment as the in-call branch at the LOW resolution, so the full frame is
|
||||
// padded to (128 x 16) << L. Padding the full frame to only 128 x 16 leaves e.g. a portrait
|
||||
// 3060x4080 bitmap with low height 2040 (not a multiple of 16), which RgbRawToYuv rejects.
|
||||
const int padded_width = RoundUp(request.full_width, 128 << log2_factor);
|
||||
const int padded_height = RoundUp(request.full_height, 16 << log2_factor);
|
||||
const int low_width = padded_width >> log2_factor;
|
||||
const int low_height = padded_height >> log2_factor;
|
||||
const int strength_width = padded_width / 4;
|
||||
|
||||
@@ -5170,12 +5170,11 @@ class Camera2Controller(private val context: Context) {
|
||||
} else if (availableEdgeModes.contains(CaptureRequest.EDGE_MODE_FAST)) {
|
||||
builder.set(CaptureRequest.EDGE_MODE, CaptureRequest.EDGE_MODE_FAST)
|
||||
}
|
||||
val effectiveNrLevel = if (
|
||||
isBurst && selectedNrLevel == NoiseReductionLevel.HIGH_QUALITY
|
||||
) {
|
||||
NoiseReductionLevel.FAST
|
||||
} else {
|
||||
selectedNrLevel
|
||||
val effectiveNrLevel = when {
|
||||
// Night vision always asks the ISP for HIGH_QUALITY NR on every burst frame.
|
||||
!isVideo && currentState.isNightVisionActive -> NoiseReductionLevel.HIGH_QUALITY
|
||||
isBurst && selectedNrLevel == NoiseReductionLevel.HIGH_QUALITY -> NoiseReductionLevel.FAST
|
||||
else -> selectedNrLevel
|
||||
}
|
||||
val noiseReductionMode = when (effectiveNrLevel) {
|
||||
NoiseReductionLevel.OFF -> CaptureRequest.NOISE_REDUCTION_MODE_OFF
|
||||
@@ -7519,6 +7518,10 @@ 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,6 +382,8 @@ 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,
|
||||
@@ -447,6 +449,10 @@ 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
|
||||
|
||||
@@ -459,6 +465,7 @@ data class CameraState(
|
||||
|
||||
val activeMultiFrameCount: Int
|
||||
get() = when {
|
||||
isNightVisionActive -> MultiFrameConfig.NIGHT_VISION_FRAME_COUNT
|
||||
isJpgMaxEnabled -> MultiFrameConfig.normalizeDenoiseFrameCount(
|
||||
jpgMultiFrameDenoiseFrameCount
|
||||
)
|
||||
|
||||
@@ -12,6 +12,8 @@ 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
|
||||
|
||||
@@ -369,9 +369,15 @@ 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 }
|
||||
/** 使用 RAW 格式拍摄。读取结果综合 [useRawMax]/[useJpgMax];写入只记录 RAW 开关本身。 */
|
||||
/** 夜视模式: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、多重曝光。 */
|
||||
val effectiveUseJpgMax: Boolean
|
||||
get() = (useJpgMax || nightVisionMode) && !useRaw && !useMultipleExposure
|
||||
/** 使用 RAW 格式拍摄。读取结果综合 [useRawMax]/[useJpgMax]/[nightVisionMode];写入只记录 RAW 开关本身。 */
|
||||
var useRaw: Boolean
|
||||
get() = when {
|
||||
nightVisionMode -> false
|
||||
useRawMax -> true
|
||||
useJpgMax -> false
|
||||
else -> storedUseRaw
|
||||
@@ -810,6 +816,7 @@ 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,5 +1,6 @@
|
||||
package com.hinnka.mycamera.gallery
|
||||
|
||||
import com.hinnka.mycamera.processor.NightVisionCapture
|
||||
import android.app.PendingIntent
|
||||
import android.content.ContentUris
|
||||
import android.content.ContentValues
|
||||
@@ -3221,6 +3222,7 @@ 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)
|
||||
@@ -3241,6 +3243,14 @@ 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
|
||||
|
||||
@@ -4534,6 +4544,7 @@ 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 -> {
|
||||
@@ -4550,7 +4561,8 @@ object GalleryManager {
|
||||
chromaNoiseReductionValue,
|
||||
photoQuality,
|
||||
useSuperResolution,
|
||||
superResolutionScale
|
||||
superResolutionScale,
|
||||
nightVision,
|
||||
)
|
||||
}
|
||||
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
package com.hinnka.mycamera.gallery
|
||||
|
||||
import com.hinnka.mycamera.processor.NightVisionToneCurve
|
||||
import android.content.Context
|
||||
import android.graphics.Bitmap
|
||||
import android.graphics.BitmapFactory
|
||||
@@ -92,6 +93,19 @@ 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,6 +10,8 @@ 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,
|
||||
@@ -174,6 +176,8 @@ 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,5 +1,6 @@
|
||||
package com.hinnka.mycamera.lut
|
||||
|
||||
import com.hinnka.mycamera.processor.NightVisionToneCurve
|
||||
import android.content.Context
|
||||
import android.graphics.Bitmap
|
||||
import android.graphics.ColorSpace
|
||||
@@ -82,6 +83,7 @@ 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
|
||||
@@ -724,6 +726,54 @@ 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
|
||||
)
|
||||
}
|
||||
|
||||
/**
|
||||
* 执行渲染操作(共享的渲染逻辑)
|
||||
*/
|
||||
@@ -2134,6 +2184,7 @@ class LutImageProcessor(context: Context? = null) {
|
||||
releaseReadbackBuffer()
|
||||
|
||||
bitmapMgcDenoiser.release()
|
||||
nightVisionToneGl.release()
|
||||
if (lutSharpenProgram != 0) {
|
||||
GLES30.glDeleteProgram(lutSharpenProgram)
|
||||
lutSharpenProgram = 0
|
||||
|
||||
@@ -1,5 +1,7 @@
|
||||
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
|
||||
@@ -50,6 +52,10 @@ 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
|
||||
@@ -99,6 +105,31 @@ class LutRenderer(context: Context) : GLSurfaceView.Renderer {
|
||||
private var meteringFboId: Int = 0
|
||||
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
|
||||
@@ -604,6 +635,14 @@ 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
|
||||
@@ -792,6 +831,7 @@ 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,
|
||||
@@ -800,6 +840,7 @@ 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))
|
||||
}
|
||||
@@ -823,6 +864,7 @@ class LutRenderer(context: Context) : GLSurfaceView.Renderer {
|
||||
curveEnabled: Boolean,
|
||||
enableVideoLog: Boolean,
|
||||
toneBaseOnly: Boolean = false,
|
||||
nightVisionTone: Boolean = false,
|
||||
) {
|
||||
val shadowsHighlightsActive =
|
||||
ShadowsHighlightsShader.isActive(params.highlights, params.shadows)
|
||||
@@ -848,6 +890,7 @@ class LutRenderer(context: Context) : GLSurfaceView.Renderer {
|
||||
curveEnabled = curveEnabled,
|
||||
enableVideoLog = enableVideoLog,
|
||||
toneBaseOnly = true,
|
||||
nightVisionTone = nightVisionTone,
|
||||
)
|
||||
toneBase.buildLevels(::drawSimpleQuad)
|
||||
}
|
||||
@@ -991,6 +1034,13 @@ 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,
|
||||
@@ -1039,6 +1089,25 @@ 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)
|
||||
@@ -1140,6 +1209,7 @@ class LutRenderer(context: Context) : GLSurfaceView.Renderer {
|
||||
val hasCreativeLayer = hasCreativeLayer()
|
||||
val hasDualLayer = hasBaselineLayer && hasCreativeLayer
|
||||
uploadPendingCurveTextures()
|
||||
uploadPendingNightTone()
|
||||
val requestedFbo = liveRecorder != null ||
|
||||
postProcessEffectEnabled ||
|
||||
clarityEnabled ||
|
||||
@@ -1323,13 +1393,19 @@ class LutRenderer(context: Context) : GLSurfaceView.Renderer {
|
||||
compositeFinalDisplay = needsHdfCompositeForSampling
|
||||
)
|
||||
if (meteringEnabled) {
|
||||
runMeteringInternal(
|
||||
sourceTextureId = finalDisplayTextureId,
|
||||
sourceWidth = finalDisplayWidth,
|
||||
sourceHeight = finalDisplayHeight,
|
||||
compositeWithHdf = needsHdfCompositeForSampling
|
||||
)
|
||||
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
|
||||
)
|
||||
}
|
||||
}
|
||||
runNightVisionSampling()
|
||||
} else {
|
||||
// 直接渲染到屏幕
|
||||
drawInternal(
|
||||
@@ -1442,8 +1518,11 @@ 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
|
||||
@@ -1488,6 +1567,7 @@ class LutRenderer(context: Context) : GLSurfaceView.Renderer {
|
||||
params = layerParams,
|
||||
enableVideoLog = enableVideoLog,
|
||||
includeEnginePreview = plan != null,
|
||||
nightVisionTone = nightVisionTone,
|
||||
) ?: return
|
||||
drawColorPass(
|
||||
locations = locations,
|
||||
@@ -1507,12 +1587,16 @@ 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")
|
||||
}
|
||||
@@ -2907,6 +2991,7 @@ class LutRenderer(context: Context) : GLSurfaceView.Renderer {
|
||||
suppressBaselineLayer = true,
|
||||
suppressCreativeLayer = true,
|
||||
suppressCameraEngine = true,
|
||||
suppressNightVisionTone = true,
|
||||
)
|
||||
}
|
||||
|
||||
@@ -2921,6 +3006,87 @@ 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
|
||||
try {
|
||||
drawInternal(
|
||||
fboId = nightVisionFboId,
|
||||
width = size,
|
||||
height = size,
|
||||
targetMvpMatrix = buildMvpMatrix(size, size),
|
||||
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 }) {
|
||||
@@ -3288,6 +3454,8 @@ class LutRenderer(context: Context) : GLSurfaceView.Renderer {
|
||||
pboId = 0
|
||||
}
|
||||
releasePixelPackPbos(meteringPboIds, meteringPboFences)
|
||||
releaseNightVisionGl()
|
||||
nightVisionEstimator.close()
|
||||
|
||||
if (meteringFboId != 0) {
|
||||
GLES30.glDeleteFramebuffers(1, intArrayOf(meteringFboId), 0)
|
||||
|
||||
@@ -0,0 +1,81 @@
|
||||
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
|
||||
|
||||
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()
|
||||
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
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,190 @@
|
||||
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()
|
||||
}
|
||||
}
|
||||
@@ -1,5 +1,6 @@
|
||||
package com.hinnka.mycamera.lut
|
||||
|
||||
|
||||
internal object PreviewColorShader {
|
||||
fun source(variant: PreviewColorShaderVariant): String {
|
||||
val extension = if (variant.textureSource == PreviewColorTextureSource.EXTERNAL_OES) {
|
||||
@@ -82,10 +83,6 @@ internal object PreviewColorShader {
|
||||
uniform sampler2D uSoftLightTexture;
|
||||
uniform float uSoftLight;
|
||||
""" else ""}
|
||||
${if (variant.includeJpegInputToneCurve) """
|
||||
uniform highp sampler2D uJpegInputToneCurveTexture;
|
||||
uniform int uJpegInputToneCurveSize;
|
||||
""" else ""}
|
||||
|
||||
const vec3 W = vec3(0.2126, 0.7152, 0.0722);
|
||||
const float PI = 3.14159265359;
|
||||
@@ -99,34 +96,7 @@ internal object PreviewColorShader {
|
||||
${PreviewColorShaderModules.SANITIZE}
|
||||
${BasicToneLutShader.GLSL}
|
||||
|
||||
${if (variant.includeJpegInputToneCurve) """
|
||||
float sampleJpegInputToneCurve(float value) {
|
||||
int lastIndex = max(uJpegInputToneCurveSize - 1, 1);
|
||||
float position = clamp(value, 0.0, 1.0) * float(lastIndex);
|
||||
int lowerIndex = clamp(int(floor(position)), 0, lastIndex);
|
||||
int upperIndex = min(lowerIndex + 1, lastIndex);
|
||||
float amount = position - float(lowerIndex);
|
||||
float lower = texelFetch(
|
||||
uJpegInputToneCurveTexture,
|
||||
ivec2(lowerIndex, 0),
|
||||
0
|
||||
).r;
|
||||
float upper = texelFetch(
|
||||
uJpegInputToneCurveTexture,
|
||||
ivec2(upperIndex, 0),
|
||||
0
|
||||
).r;
|
||||
return mix(lower, upper, amount);
|
||||
}
|
||||
|
||||
vec3 applyJpegInputToneCurve(vec3 color) {
|
||||
return vec3(
|
||||
sampleJpegInputToneCurve(color.r),
|
||||
sampleJpegInputToneCurve(color.g),
|
||||
sampleJpegInputToneCurve(color.b)
|
||||
);
|
||||
}
|
||||
""" else ""}
|
||||
${if (variant.includeNightVisionTone) NightVisionToneGl.GLSL else ""}
|
||||
|
||||
float getLuma(vec3 color) {
|
||||
return dot(color, W);
|
||||
@@ -186,8 +156,8 @@ internal object PreviewColorShader {
|
||||
}
|
||||
""" else "vec4 color = samplePreviewSource(uvCoord);"}
|
||||
|
||||
${if (variant.includeJpegInputToneCurve) """
|
||||
color.rgb = applyJpegInputToneCurve(color.rgb);
|
||||
${if (variant.includeNightVisionTone) """
|
||||
color.rgb = applyNightVisionTone(color.rgb);
|
||||
color.rgb = sanitizeColor(color.rgb);
|
||||
""" else ""}
|
||||
${if (variant.includeLiteClarity) "float previewSourceLuma = getLuma(color.rgb);" else ""}
|
||||
|
||||
@@ -16,7 +16,8 @@ internal data class PreviewColorShaderVariant(
|
||||
val includeLchMixer: Boolean,
|
||||
val includePreLogFilmGrain: Boolean,
|
||||
val includeLutMask: Boolean = false,
|
||||
val includeJpegInputToneCurve: 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,
|
||||
@@ -50,6 +51,7 @@ 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()
|
||||
@@ -60,6 +62,7 @@ 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,
|
||||
|
||||
@@ -0,0 +1,77 @@
|
||||
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
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,54 @@
|
||||
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
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,340 @@
|
||||
package com.hinnka.mycamera.processor
|
||||
|
||||
import android.graphics.Bitmap
|
||||
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: full strength at mean luma <= [GATE_FULL_LUMA], identity at
|
||||
* >= [GATE_OFF_LUMA]. 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
|
||||
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
|
||||
private const val GATE_FULL_LUMA = 0.35f
|
||||
private const val GATE_OFF_LUMA = 0.65f
|
||||
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 lumaSum = 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)
|
||||
lumaSum += y
|
||||
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 strength = gate((lumaSum / pixelCount).toFloat())
|
||||
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 [bitmap] to the model input, HWC RGB floats of its encoded values (no color conversion). */
|
||||
fun modelInputFrom(bitmap: Bitmap): FloatArray {
|
||||
val scaled = Bitmap.createScaledBitmap(bitmap, MODEL_SIZE, MODEL_SIZE, true)
|
||||
try {
|
||||
val argb = if (scaled.config == Bitmap.Config.ARGB_8888) {
|
||||
scaled
|
||||
} else {
|
||||
scaled.copy(Bitmap.Config.ARGB_8888, false)
|
||||
}
|
||||
val bytes = ByteBuffer.allocate(argb.rowBytes * argb.height)
|
||||
argb.copyPixelsToBuffer(bytes)
|
||||
if (argb !== scaled) argb.recycle()
|
||||
return modelInputFromRgba(bytes.array(), argb.rowBytes)
|
||||
} finally {
|
||||
if (scaled !== bitmap) 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(meanLuma: Float): Float {
|
||||
val t = ((GATE_OFF_LUMA - meanLuma) / (GATE_OFF_LUMA - GATE_FULL_LUMA)).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()]
|
||||
}
|
||||
}
|
||||
@@ -215,6 +215,10 @@ class CameraGLSurfaceView @JvmOverloads constructor(
|
||||
renderer.meteringEnabled = enabled
|
||||
}
|
||||
|
||||
fun setNightVisionEnabled(enabled: Boolean) {
|
||||
renderer.nightVisionEnabled = enabled
|
||||
}
|
||||
|
||||
/**
|
||||
* 设置 LUT
|
||||
*
|
||||
|
||||
@@ -75,6 +75,7 @@ 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,
|
||||
@@ -328,6 +329,7 @@ fun CameraPreviewGL(
|
||||
glSurfaceView.setMeteringMode(meteringMode)
|
||||
glSurfaceView.setLivePhotoRecorder(livePhotoRecorder)
|
||||
glSurfaceView.setVideoLogProfile(videoLogProfile)
|
||||
glSurfaceView.setNightVisionEnabled(nightVisionEnabled)
|
||||
glSurfaceView.setAutoFocus(isAutoFocus)
|
||||
glSurfaceView.setFocusPeakingEnabled(focusPeakingEnabled)
|
||||
glSurfaceView.setEyeFocusBusy(isEyeFocusBusy)
|
||||
|
||||
@@ -1,5 +1,23 @@
|
||||
package com.hinnka.mycamera.ui.camera
|
||||
|
||||
import androidx.compose.runtime.mutableStateListOf
|
||||
import androidx.compose.ui.layout.onPlaced
|
||||
import androidx.compose.ui.layout.positionInParent
|
||||
import androidx.compose.foundation.layout.Arrangement
|
||||
import androidx.compose.runtime.mutableStateOf
|
||||
import androidx.compose.runtime.setValue
|
||||
import androidx.compose.runtime.getValue
|
||||
import androidx.compose.animation.core.Animatable
|
||||
import androidx.compose.foundation.gestures.detectHorizontalDragGestures
|
||||
import androidx.compose.ui.graphics.CompositingStrategy
|
||||
import androidx.compose.ui.draw.drawWithContent
|
||||
import androidx.compose.ui.graphics.BlendMode
|
||||
import androidx.compose.foundation.layout.wrapContentWidth
|
||||
import androidx.compose.runtime.rememberCoroutineScope
|
||||
import androidx.compose.runtime.LaunchedEffect
|
||||
import kotlin.math.abs
|
||||
import androidx.compose.runtime.rememberUpdatedState
|
||||
import androidx.compose.foundation.layout.offset
|
||||
import com.hinnka.mycamera.ui.prefs.rememberUserPreferencesRepository
|
||||
import com.hinnka.mycamera.data.UserPreferences
|
||||
import com.hinnka.mycamera.ui.prefs.rememberPreference
|
||||
@@ -113,6 +131,7 @@ enum class ActivePanel {
|
||||
private enum class CameraShootingMode {
|
||||
PROFESSIONAL,
|
||||
PHOTO,
|
||||
NIGHT_VISION,
|
||||
VIDEO
|
||||
}
|
||||
|
||||
@@ -634,17 +653,27 @@ fun CameraScreen(
|
||||
|
||||
val targetCaptureMode = when (mode) {
|
||||
CameraShootingMode.PROFESSIONAL,
|
||||
CameraShootingMode.PHOTO -> CaptureMode.PHOTO
|
||||
CameraShootingMode.PHOTO,
|
||||
CameraShootingMode.NIGHT_VISION -> CaptureMode.PHOTO
|
||||
CameraShootingMode.VIDEO -> CaptureMode.VIDEO
|
||||
}
|
||||
val targetUseRaw = when (mode) {
|
||||
CameraShootingMode.PROFESSIONAL -> true
|
||||
CameraShootingMode.PHOTO -> false
|
||||
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
|
||||
}
|
||||
if (
|
||||
targetCaptureMode == state.captureMode &&
|
||||
(targetUseRaw == null || targetUseRaw == state.useRaw)
|
||||
(targetUseRaw == null || targetUseRaw == state.useRaw) &&
|
||||
targetNightVision == state.nightVisionEnabled
|
||||
) {
|
||||
return
|
||||
}
|
||||
@@ -653,7 +682,7 @@ fun CameraScreen(
|
||||
if (targetCaptureMode == CaptureMode.VIDEO && state.aspectRatio == AspectRatio.XPAN) {
|
||||
viewModel.setAspectRatio(AspectRatio.RATIO_4_3)
|
||||
}
|
||||
viewModel.setShootingMode(targetCaptureMode, targetUseRaw)
|
||||
viewModel.setShootingMode(targetCaptureMode, targetUseRaw, targetNightVision)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1321,6 +1350,7 @@ fun CameraScreen(
|
||||
},
|
||||
livePhotoRecorder = viewModel.livePhotoRecorder,
|
||||
videoLogProfile = state.videoConfig.logProfile,
|
||||
nightVisionEnabled = state.isNightVisionActive,
|
||||
isEyeFocusBusy = viewModel.isEyeFocusBusy,
|
||||
isAutoFocus = state.isAutoFocus,
|
||||
focusPeakingEnabled = focusPeakingEnabled && !state.isHyperfocalFocusEnabled,
|
||||
@@ -2203,6 +2233,7 @@ 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,
|
||||
@@ -2529,6 +2560,11 @@ private fun rememberPhotoCaptureProgress(progress: PhotoCaptureProgress?): State
|
||||
return fraction
|
||||
}
|
||||
|
||||
/**
|
||||
* Full-width scrolling mode switcher: every mode is shown, and the selected one, drawn as a pill
|
||||
* in the accent color, is always scrolled to the horizontal centre. Tap a mode or drag the row;
|
||||
* a drag settles on the nearest selectable mode.
|
||||
*/
|
||||
@Composable
|
||||
private fun CaptureModeSwitcher(
|
||||
shootingMode: CameraShootingMode,
|
||||
@@ -2536,77 +2572,122 @@ private fun CaptureModeSwitcher(
|
||||
enabled: Boolean,
|
||||
onModeSelected: (CameraShootingMode) -> Unit
|
||||
) {
|
||||
val modes = CameraShootingMode.entries
|
||||
val selectedIndex = shootingMode.ordinal
|
||||
val currentSelectedIndex by rememberUpdatedState(selectedIndex)
|
||||
val currentOnModeSelected by rememberUpdatedState(onModeSelected)
|
||||
val scope = rememberCoroutineScope()
|
||||
// Item centres in row coordinates, filled in by onPlaced.
|
||||
val itemCenters = remember { mutableStateListOf(*Array(modes.size) { Float.NaN }) }
|
||||
// Horizontal offset of the row inside the switcher, in px.
|
||||
val rowOffset = remember { Animatable(0f) }
|
||||
var positioned by remember { mutableStateOf(false) }
|
||||
|
||||
fun isSelectable(mode: CameraShootingMode): Boolean =
|
||||
enabled && (mode != CameraShootingMode.PROFESSIONAL || professionalModeEnabled)
|
||||
|
||||
BoxWithConstraints(
|
||||
modifier = Modifier
|
||||
.width(228.dp)
|
||||
.height(CameraControlsLayoutDefaults.ModeSwitcherHeight)
|
||||
.clip(RoundedCornerShape(18.dp))
|
||||
.background(Color.Black.copy(alpha = 0.28f))
|
||||
.border(
|
||||
width = 0.5.dp,
|
||||
color = Color.White.copy(alpha = 0.18f),
|
||||
shape = RoundedCornerShape(18.dp)
|
||||
)
|
||||
.padding(3.dp)
|
||||
.fillMaxWidth()
|
||||
.height(CameraControlsLayoutDefaults.ModeSwitcherHeight),
|
||||
contentAlignment = Alignment.CenterStart
|
||||
) {
|
||||
val knobWidth = maxWidth / 3
|
||||
val selectedIndex = when (shootingMode) {
|
||||
CameraShootingMode.PROFESSIONAL -> 0
|
||||
CameraShootingMode.PHOTO -> 1
|
||||
CameraShootingMode.VIDEO -> 2
|
||||
}
|
||||
val knobOffset by animateDpAsState(
|
||||
targetValue = knobWidth * selectedIndex,
|
||||
animationSpec = tween(durationMillis = 220),
|
||||
label = "modeSwitcher"
|
||||
)
|
||||
val selectedBackground by animateColorAsState(
|
||||
targetValue = if (shootingMode == CameraShootingMode.PROFESSIONAL) {
|
||||
AccentColor
|
||||
val centerPx = constraints.maxWidth / 2f
|
||||
fun offsetFor(index: Int): Float = centerPx - itemCenters[index]
|
||||
val measured = itemCenters.none { it.isNaN() }
|
||||
|
||||
LaunchedEffect(selectedIndex, measured, centerPx) {
|
||||
if (!measured) return@LaunchedEffect
|
||||
val target = offsetFor(selectedIndex)
|
||||
if (positioned) {
|
||||
rowOffset.animateTo(target, tween(durationMillis = 220))
|
||||
} else {
|
||||
Color.White
|
||||
},
|
||||
animationSpec = tween(durationMillis = 220),
|
||||
label = "modeSwitcherColor"
|
||||
)
|
||||
Box(
|
||||
modifier = Modifier
|
||||
.offset(x = knobOffset)
|
||||
.width(knobWidth)
|
||||
.fillMaxHeight()
|
||||
.clip(RoundedCornerShape(15.dp))
|
||||
.background(selectedBackground)
|
||||
)
|
||||
rowOffset.snapTo(target)
|
||||
positioned = true
|
||||
}
|
||||
}
|
||||
|
||||
fun settleDrag() {
|
||||
if (!measured) return
|
||||
val target = modes.filter(::isSelectable)
|
||||
.minByOrNull { abs(offsetFor(it.ordinal) - rowOffset.value) }
|
||||
scope.launch {
|
||||
if (target == null || target.ordinal == currentSelectedIndex) {
|
||||
rowOffset.animateTo(offsetFor(currentSelectedIndex), tween(durationMillis = 220))
|
||||
return@launch
|
||||
}
|
||||
currentOnModeSelected(target)
|
||||
rowOffset.animateTo(offsetFor(target.ordinal), tween(durationMillis = 220))
|
||||
// The selection can be refused (recording, unsupported RAW); fall back to the
|
||||
// mode actually in effect once the switch had time to apply.
|
||||
delay(ModeSwitcherSettleTimeoutMillis)
|
||||
if (currentSelectedIndex != target.ordinal) {
|
||||
rowOffset.animateTo(offsetFor(currentSelectedIndex), tween(durationMillis = 220))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Row(
|
||||
modifier = Modifier.fillMaxSize(),
|
||||
modifier = Modifier
|
||||
.fillMaxSize()
|
||||
.pointerInput(enabled, professionalModeEnabled, measured) {
|
||||
if (!enabled || !measured) return@pointerInput
|
||||
detectHorizontalDragGestures(
|
||||
onDragEnd = { settleDrag() },
|
||||
onDragCancel = { settleDrag() },
|
||||
) { change, dragAmount ->
|
||||
change.consume()
|
||||
val min = offsetFor(modes.lastIndex)
|
||||
val max = offsetFor(0)
|
||||
scope.launch { rowOffset.snapTo((rowOffset.value + dragAmount).coerceIn(min, max)) }
|
||||
}
|
||||
}
|
||||
.graphicsLayer { compositingStrategy = CompositingStrategy.Offscreen }
|
||||
.drawWithContent {
|
||||
drawContent()
|
||||
drawRect(
|
||||
brush = Brush.horizontalGradient(
|
||||
0f to Color.Transparent,
|
||||
0.1f to Color.Black,
|
||||
0.9f to Color.Black,
|
||||
1f to Color.Transparent,
|
||||
),
|
||||
blendMode = BlendMode.DstIn,
|
||||
)
|
||||
}
|
||||
.wrapContentWidth(align = Alignment.Start, unbounded = true)
|
||||
.offset { IntOffset(rowOffset.value.roundToInt(), 0) }
|
||||
.graphicsLayer { alpha = if (positioned) 1f else 0f },
|
||||
horizontalArrangement = Arrangement.spacedBy(ModeSwitcherItemSpacing),
|
||||
verticalAlignment = Alignment.CenterVertically
|
||||
) {
|
||||
ModeSwitcherItem(
|
||||
label = stringResource(R.string.capture_mode_professional),
|
||||
selectedContentColor = accentContentColor(selectedBackground),
|
||||
selected = shootingMode == CameraShootingMode.PROFESSIONAL,
|
||||
enabled = enabled && professionalModeEnabled,
|
||||
onClick = { onModeSelected(CameraShootingMode.PROFESSIONAL) },
|
||||
modifier = Modifier.weight(1f)
|
||||
)
|
||||
ModeSwitcherItem(
|
||||
label = stringResource(R.string.capture_mode_photo),
|
||||
selected = shootingMode == CameraShootingMode.PHOTO,
|
||||
enabled = enabled,
|
||||
onClick = { onModeSelected(CameraShootingMode.PHOTO) },
|
||||
modifier = Modifier.weight(1f)
|
||||
)
|
||||
ModeSwitcherItem(
|
||||
label = stringResource(R.string.capture_mode_video),
|
||||
selected = shootingMode == CameraShootingMode.VIDEO,
|
||||
enabled = enabled,
|
||||
onClick = { onModeSelected(CameraShootingMode.VIDEO) },
|
||||
modifier = Modifier.weight(1f)
|
||||
)
|
||||
modes.forEachIndexed { index, mode ->
|
||||
ModeSwitcherItem(
|
||||
label = stringResource(mode.labelRes),
|
||||
selected = mode == shootingMode,
|
||||
enabled = isSelectable(mode),
|
||||
onClick = { currentOnModeSelected(mode) },
|
||||
modifier = Modifier.onPlaced { coordinates ->
|
||||
itemCenters[index] =
|
||||
coordinates.positionInParent().x + coordinates.size.width / 2f
|
||||
}
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private val ModeSwitcherItemSpacing = 8.dp
|
||||
private const val ModeSwitcherSettleTimeoutMillis = 1500L
|
||||
|
||||
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
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun ModeSwitcherItem(
|
||||
label: String,
|
||||
@@ -2614,22 +2695,40 @@ private fun ModeSwitcherItem(
|
||||
enabled: Boolean,
|
||||
onClick: () -> Unit,
|
||||
modifier: Modifier = Modifier,
|
||||
selectedContentColor: Color = Color.Black
|
||||
) {
|
||||
// The selected mode carries the capsule that used to frame the whole switcher.
|
||||
val capsuleBackground by animateColorAsState(
|
||||
targetValue = if (selected) Color.Black.copy(alpha = 0.28f) else Color.Transparent,
|
||||
animationSpec = tween(durationMillis = 220),
|
||||
label = "modeSwitcherCapsule"
|
||||
)
|
||||
val capsuleBorder by animateColorAsState(
|
||||
targetValue = if (selected) Color.White.copy(alpha = 0.18f) else Color.Transparent,
|
||||
animationSpec = tween(durationMillis = 220),
|
||||
label = "modeSwitcherCapsuleBorder"
|
||||
)
|
||||
val textColor by animateColorAsState(
|
||||
targetValue = when {
|
||||
selected -> AccentColor
|
||||
enabled -> Color.White.copy(alpha = 0.82f)
|
||||
else -> Color.White.copy(alpha = 0.3f)
|
||||
},
|
||||
animationSpec = tween(durationMillis = 220),
|
||||
label = "modeSwitcherText"
|
||||
)
|
||||
Box(
|
||||
modifier = modifier
|
||||
.fillMaxHeight()
|
||||
.clip(RoundedCornerShape(20.dp))
|
||||
.clickable(enabled = enabled, onClick = onClick),
|
||||
.clip(RoundedCornerShape(18.dp))
|
||||
.background(capsuleBackground)
|
||||
.border(width = 0.5.dp, color = capsuleBorder, shape = RoundedCornerShape(18.dp))
|
||||
.clickable(enabled = enabled, onClick = onClick)
|
||||
.padding(horizontal = 16.dp),
|
||||
contentAlignment = Alignment.Center
|
||||
) {
|
||||
Text(
|
||||
text = label,
|
||||
color = when {
|
||||
selected -> selectedContentColor.copy(alpha = 0.88f)
|
||||
enabled -> Color.White.copy(alpha = 0.82f)
|
||||
else -> Color.White.copy(alpha = 0.3f)
|
||||
},
|
||||
color = textColor,
|
||||
fontSize = 12.sp,
|
||||
lineHeight = 14.sp,
|
||||
fontWeight = if (selected) FontWeight.SemiBold else FontWeight.Medium,
|
||||
|
||||
@@ -559,7 +559,8 @@ private data class CameraFeatureUpdate(
|
||||
val droMode: SettingValue<String>? = null,
|
||||
val rawBaselineLutId: SettingValue<String?>? = null,
|
||||
val activePresetId: SettingValue<String?>? = null,
|
||||
val useMultipleExposure: SettingValue<Boolean>? = null
|
||||
val useMultipleExposure: SettingValue<Boolean>? = null,
|
||||
val nightVision: SettingValue<Boolean>? = null
|
||||
)
|
||||
|
||||
/**
|
||||
@@ -997,8 +998,10 @@ 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 }
|
||||
@@ -1024,9 +1027,19 @@ 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 && !desiredUseRaw
|
||||
val activeUseJpgMax = (desiredUseJpgMax || desiredNightVision) && !desiredUseRaw
|
||||
if (activeUseJpgMax && prefs.useLivePhoto) {
|
||||
cameraController.setUseLivePhoto(false)
|
||||
userPreferencesRepository.update { useLivePhoto = false }
|
||||
@@ -1092,6 +1105,9 @@ class CameraViewModel(application: Application) : AndroidViewModel(application)
|
||||
) {
|
||||
cameraController.setMultiFrameOutputScale(desiredMultiFrameOutputScale)
|
||||
}
|
||||
if (desiredNightVision != currentState.nightVisionEnabled) {
|
||||
cameraController.setNightVisionEnabled(desiredNightVision)
|
||||
}
|
||||
|
||||
if (captureModeWillChange) {
|
||||
cameraController.setCaptureMode(targetCaptureMode)
|
||||
@@ -1170,6 +1186,9 @@ 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
|
||||
@@ -1871,8 +1890,7 @@ class CameraViewModel(application: Application) : AndroidViewModel(application)
|
||||
}
|
||||
val multipleExposureEnabled = it.useMultipleExposure
|
||||
val effectiveUseRaw = it.useRaw && !multipleExposureEnabled
|
||||
val effectiveUseJpgMax =
|
||||
it.useJpgMax && !effectiveUseRaw && !multipleExposureEnabled
|
||||
val effectiveUseJpgMax = it.effectiveUseJpgMax
|
||||
val effectiveUseRawMax =
|
||||
it.useRawMax && effectiveUseRaw && !multipleExposureEnabled
|
||||
val effectiveMultiFrameOutputScale = resolveMultiFrameOutputScale(
|
||||
@@ -1896,6 +1914,9 @@ 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
|
||||
@@ -2164,8 +2185,7 @@ class CameraViewModel(application: Application) : AndroidViewModel(application)
|
||||
cameraController.setRawCfaCorrectionModes(prefs.rawCfaCorrectionModes)
|
||||
cameraController.setMultiFrameOutputScale(
|
||||
resolveMultiFrameOutputScale(
|
||||
useJpgMax = prefs.useJpgMax && !prefs.useRaw &&
|
||||
!prefs.useMultipleExposure,
|
||||
useJpgMax = prefs.effectiveUseJpgMax,
|
||||
useRawMax = prefs.useRawMax && prefs.useRaw &&
|
||||
!prefs.useMultipleExposure,
|
||||
rawMaxOutputScale = prefs.rawMaxOutputScale,
|
||||
@@ -2175,6 +2195,7 @@ 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)
|
||||
@@ -3554,17 +3575,18 @@ class CameraViewModel(application: Application) : AndroidViewModel(application)
|
||||
}
|
||||
|
||||
fun setCaptureMode(mode: CaptureMode) {
|
||||
setShootingMode(mode, useRaw = null)
|
||||
setShootingMode(mode, useRaw = null, nightVision = state.value.nightVisionEnabled)
|
||||
}
|
||||
|
||||
/**
|
||||
* Applies the three-way shooting mode selection as one ordered operation.
|
||||
* Applies the shooting mode selection (professional / photo / night vision / 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?) {
|
||||
fun setShootingMode(mode: CaptureMode, useRaw: Boolean?, nightVision: Boolean) {
|
||||
if (state.value.videoRecordingState.isRecording ||
|
||||
state.value.videoRecordingState.isProcessing
|
||||
) {
|
||||
@@ -3574,13 +3596,16 @@ class CameraViewModel(application: Application) : AndroidViewModel(application)
|
||||
shootingModeSwitchJob?.cancel()
|
||||
val rawNeedsUpdate = useRaw != null &&
|
||||
(state.value.useRaw != useRaw || userPreferencesRepository.current.useRaw != useRaw)
|
||||
if (state.value.captureMode == mode && !rawNeedsUpdate) return
|
||||
val nightVisionNeedsUpdate = state.value.nightVisionEnabled != nightVision ||
|
||||
userPreferencesRepository.current.nightVisionMode != nightVision
|
||||
if (state.value.captureMode == mode && !rawNeedsUpdate && !nightVisionNeedsUpdate) return
|
||||
|
||||
shootingModeSwitchJob = viewModelScope.launch {
|
||||
applyCameraFeatureUpdate(
|
||||
CameraFeatureUpdate(
|
||||
captureMode = SettingValue(mode),
|
||||
useRaw = useRaw?.let(::SettingValue),
|
||||
nightVision = SettingValue(nightVision),
|
||||
)
|
||||
)
|
||||
}
|
||||
@@ -5827,6 +5852,7 @@ 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,6 +24,7 @@
|
||||
<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 -->
|
||||
|
||||
@@ -503,6 +503,7 @@
|
||||
<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>
|
||||
|
||||
@@ -357,6 +357,7 @@
|
||||
<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>
|
||||
|
||||
@@ -24,6 +24,7 @@
|
||||
<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,6 +25,7 @@
|
||||
<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,6 +24,7 @@
|
||||
<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,6 +24,7 @@
|
||||
<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,6 +25,7 @@
|
||||
<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 -->
|
||||
|
||||
Reference in new issue
Block a user