feat: natural light (3)

This commit is contained in:
zhoubinjia committed 2026-06-25 15:40:21 +08:00
1 parent 7dac4c59df
commit d4fa95222b
6 files changed
+150 -20

No files matched your search

@@ -2015,7 +2015,18 @@ class Camera2Controller(private val context: Context) {
private fun applyToneMapSettings(builder: CaptureRequest.Builder, state: CameraState, isCapture: Boolean) {
val linearizePreviewInput = state.fixTonemapPreview && !isCapture
when (sanitizeTonemapMode(state.tonemapMode)) {
val tonemapMode = sanitizeTonemapMode(state.tonemapMode)
if (tonemapMode == "LINEAR_PIPELINE" && isCapture && state.useMultipleExposure) {
PLog.d(TAG, "Forcing default tone map for multiple exposure")
applyDefaultToneMapSettings(builder, state, isCapture)
return
}
if (tonemapMode == "LINEAR_PIPELINE" && shouldForceDefaultToneMapForHdrComposition(state, isCapture)) {
PLog.d(TAG, "Forcing default tone map for YUV HDR composition capture")
applyDefaultToneMapSettings(builder, state, isCapture)
return
}
when (tonemapMode) {
"SYSTEM_DEFAULT" -> applyDefaultToneMapSettings(builder, state, isCapture)
"SRGB" -> {
if (availableTonemapModes.contains(CaptureRequest.TONEMAP_MODE_CONTRAST_CURVE)) {
@@ -2041,6 +2052,13 @@ class Camera2Controller(private val context: Context) {
}
}
private fun shouldForceDefaultToneMapForHdrComposition(state: CameraState, isCapture: Boolean): Boolean {
return isCapture &&
state.captureMode == CaptureMode.PHOTO &&
state.useHdrComposition &&
!state.useRaw
}
private fun applyDefaultToneMapSettings(
builder: CaptureRequest.Builder,
state: CameraState,
@@ -2343,19 +2343,33 @@ object GalleryManager {
result = BitmapUtils.flipHorizontal(result)
}
var previewBitmap = result
if (metadata.usesLinearPipelineToneMap()) {
previewBitmap = photoProcessor.processCapturePreviewToneMap(result, metadata)
}
// Save Original (Stacked Result)
FileOutputStream(tempFile).use { outputStream ->
writeFinalJpeg(result, outputStream, photoQuality)
writeFinalJpeg(previewBitmap, outputStream, photoQuality)
}
tempFile.renameTo(photoFile)
generateBokehPhoto(context, photoId, metadata, result)
generateBokehPhoto(context, photoId, metadata, previewBitmap)
if (previewBitmap !== result && !previewBitmap.isRecycled) {
previewBitmap.recycle()
}
// Auto Save
if (shouldAutoSave) {
val metadata = loadMetadata(context, photoId) ?: return@withContext
val exportBitmap = if (yuvFile.exists() && yuvFile.length() > 0L) {
null
} else {
PLog.w(TAG, "YUV stack linear source missing; exporting stacked preview bitmap")
result
}
exportPhoto(
context,
photoId,
result,
exportBitmap,
photoProcessor,
metadata,
sharpeningValue,
@@ -15,6 +15,7 @@ import androidx.core.graphics.createBitmap
import com.hinnka.mycamera.model.SafeImage
import com.hinnka.mycamera.utils.LargeDirectBuffer
import com.hinnka.mycamera.utils.PLog
import com.hinnka.mycamera.utils.YuvProcessor
import java.nio.ByteBuffer
import kotlin.math.ln
import kotlin.math.max
@@ -28,6 +29,7 @@ class GlesYuvStacker(
private val rotation: Int,
private val colorSpace: ColorSpace,
private val inputFormat: Int,
private val outputPath: String? = null,
) {
data class HdrInputFrame(
val image: SafeImage,
@@ -151,6 +153,8 @@ class GlesYuvStacker(
private var hdrLowTexture = 0
private var outputTexture = 0
private var readbackTexture = 0
private var linearOutputTexture = 0
private var linearReadbackTexture = 0
private var gridWidth = 0
private var gridHeight = 0
@@ -223,6 +227,7 @@ class GlesYuvStacker(
}
normalizeOutput()
saveLinearStackOutputIfRequested()
GlesGpuScheduler.yieldToUiRenderer()
val bitmap = readOutputBitmap() ?: return null
PLog.i(TAG, "GLES YUV stacking completed in ${System.currentTimeMillis() - startTime}ms")
@@ -1538,14 +1543,84 @@ class GlesYuvStacker(
return bitmap
}
private fun resolveReadbackTexture(): Int {
if (!cpuRotateReadback) {
return outputTexture
private fun saveLinearStackOutputIfRequested() {
val path = outputPath ?: return
try {
ensureLinearOutputResources()
renderAccumulatorToTexture(
accumulatorTexture = currentAccumulatorTexture,
targetTexture = linearOutputTexture,
applyDenoise = true,
label = "normalizeLinearStackOutput",
)
val readTexture = resolveReadbackTexture(
inputTexture = linearOutputTexture,
rotatedTexture = linearReadbackTexture,
label = "resolveLinearStackReadbackRotation",
)
val bufferByteCount = renderOutputWidth.toLong() * renderOutputHeight.toLong() * 4L * 2L
val buffer = LargeDirectBuffer.allocate(bufferByteCount, "GLES YUV stack linear readback") ?: run {
PLog.w(TAG, "Unable to allocate GLES YUV stack linear readback buffer")
return
}
try {
GLES30.glBindFramebuffer(GLES30.GL_FRAMEBUFFER, readbackFbo)
GLES30.glFramebufferTexture2D(
GLES30.GL_FRAMEBUFFER,
GLES30.GL_COLOR_ATTACHMENT0,
GLES30.GL_TEXTURE_2D,
readTexture,
0,
)
GLES30.glReadBuffer(GLES30.GL_COLOR_ATTACHMENT0)
checkFramebuffer("saveLinearStackOutput")
GLES30.glPixelStorei(GLES30.GL_PACK_ALIGNMENT, 1)
GLES30.glViewport(0, 0, renderOutputWidth, renderOutputHeight)
GLES30.glReadPixels(
0,
0,
renderOutputWidth,
renderOutputHeight,
GLES30.GL_RGBA,
GLES30.GL_HALF_FLOAT,
buffer,
)
GLES30.glBindFramebuffer(GLES30.GL_FRAMEBUFFER, 0)
buffer.position(0)
val saved = YuvProcessor.saveCompressedArgb(buffer, renderOutputWidth, renderOutputHeight, path)
if (!saved) {
PLog.w(TAG, "Failed to save GLES YUV stack linear output: $path")
}
checkGlError("saveLinearStackOutput")
} finally {
LargeDirectBuffer.free(buffer)
}
} catch (e: Exception) {
PLog.e(TAG, "Failed to save GLES YUV stack linear output", e)
}
bindFramebufferOutput(readbackTexture, "resolveReadbackRotation")
}
private fun ensureLinearOutputResources() {
if (linearOutputTexture == 0) {
linearOutputTexture = createTexture2D(gpuOutputWidth, gpuOutputHeight, GLES30.GL_RGBA16F, GLES30.GL_NEAREST)
}
if (cpuRotateReadback && linearReadbackTexture == 0) {
linearReadbackTexture = createTexture2D(renderOutputWidth, renderOutputHeight, GLES30.GL_RGBA16F, GLES30.GL_NEAREST)
}
}
private fun resolveReadbackTexture(
inputTexture: Int = outputTexture,
rotatedTexture: Int = readbackTexture,
label: String = "resolveReadbackRotation",
): Int {
if (!cpuRotateReadback) {
return inputTexture
}
bindFramebufferOutput(rotatedTexture, label)
GLES30.glViewport(0, 0, renderOutputWidth, renderOutputHeight)
GLES30.glUseProgram(readbackResolveProgram)
bindTexture(readbackResolveProgram, "uInputTexture", 0, outputTexture)
bindTexture(readbackResolveProgram, "uInputTexture", 0, inputTexture)
GLES31.glUniform2i(
GLES31.glGetUniformLocation(readbackResolveProgram, "uInputSize"),
gpuOutputWidth,
@@ -1553,8 +1628,8 @@ class GlesYuvStacker(
)
GLES31.glUniform1i(GLES31.glGetUniformLocation(readbackResolveProgram, "uRotation"), normalizedRotation)
GLES30.glDrawArrays(GLES30.GL_TRIANGLES, 0, 3)
finishFramebufferPass("resolveReadbackRotation")
return readbackTexture
finishFramebufferPass(label)
return rotatedTexture
}
private fun createTexture2D(
@@ -106,6 +106,7 @@ object MultiFrameStacker {
rotation = rotation,
colorSpace = colorSpace,
inputFormat = inputFormat,
outputPath = outputPath,
).process(images)
if (glesBitmap != null) {
images.forEach { it.close() }
@@ -1174,6 +1174,7 @@ fun CameraScreen(
galleryViewModel = galleryViewModel,
latestPhoto = latestPhoto,
useMultipleExposure = useMultipleExposure,
tonemapMode = tonemapMode,
multipleExposureState = multipleExposureState,
onGalleryThumbnailBoundsChanged = { bounds ->
galleryThumbnailBounds = bounds
@@ -1698,6 +1699,7 @@ fun Controls(
galleryViewModel: GalleryViewModel,
latestPhoto: com.hinnka.mycamera.gallery.MediaData?,
useMultipleExposure: Boolean,
tonemapMode: String,
multipleExposureState: com.hinnka.mycamera.viewmodel.MultipleExposureSessionState,
onGalleryThumbnailBoundsChanged: (Rect) -> Unit,
onSwitchCameraClick: () -> Unit,
@@ -1742,8 +1744,10 @@ fun Controls(
isCapturing = state.isCapturing,
isVideoRecording = state.videoRecordingState.isRecording,
isPaused = state.videoRecordingState.isPaused,
allowLongPress = (state.captureMode == CaptureMode.PHOTO && !useMultipleExposure) ||
state.captureMode == CaptureMode.QUICK_SHOT,
allowLongPress = state.captureMode == CaptureMode.QUICK_SHOT ||
(tonemapMode != "LINEAR_PIPELINE" &&
state.captureMode == CaptureMode.PHOTO &&
!useMultipleExposure),
multipleExposureEnabled = useMultipleExposure && state.captureMode == CaptureMode.PHOTO,
multipleExposureProgress = multipleExposureState.capturedCount.toFloat() /
multipleExposureState.targetCount.coerceAtLeast(1).toFloat(),
@@ -1869,7 +1873,7 @@ fun CaptureButton(
modifier = modifier
.size(72.dp)
.scale(scale)
.pointerInput(Unit) {
.pointerInput(allowLongPress) {
var isLongPressStarted = false
detectTapGestures(
onTap = {
@@ -1877,12 +1881,14 @@ fun CaptureButton(
onTap()
}
},
onLongPress = {
if (allowLongPress && !currentDisabled) {
isLongPressStarted = true
onLongPressStart()
onLongPress = if (allowLongPress) {
{
if (!currentDisabled) {
isLongPressStarted = true
onLongPressStart()
}
}
},
} else null,
onPress = {
isLongPressStarted = false
try {
@@ -1879,6 +1879,7 @@ class CameraViewModel(application: Application) : AndroidViewModel(application)
return MediaMetadata(
lutId = lutIdToSave,
tonemapMode = userPrefs?.tonemapMode ?: "SYSTEM_DEFAULT",
frameId = frameIdToSave,
colorRecipeParams = getMergedRecipeParams(),
baselineTarget = baselineMetadata?.first,
@@ -2130,6 +2131,8 @@ class CameraViewModel(application: Application) : AndroidViewModel(application)
captureInfo = captureInfo,
captureMode = "multiple_exposure",
multipleExposureFrameCount = multipleExposureState.targetCount
).copy(
tonemapMode = "SYSTEM_DEFAULT"
).also { multipleExposureMetadata = it }
val frameFile = GalleryManager.saveMultipleExposureFrame(
@@ -2317,6 +2320,10 @@ class CameraViewModel(application: Application) : AndroidViewModel(application)
startQuickShotBurst()
return
}
if (tonemapMode.value == "LINEAR_PIPELINE") {
PLog.d(TAG, "Continuous photo burst disabled while Natural Light tone map is active")
return
}
if (state.value.useRaw && state.value.isRawSupported) return
generateThumbnail()
burstImages.clear()
@@ -4682,6 +4689,7 @@ class CameraViewModel(application: Application) : AndroidViewModel(application)
// 创建统一的 PhotoMetadata,包含编辑配置和拍摄信息
val metadata = MediaMetadata(
lutId = lutIdToSave,
tonemapMode = userPrefs?.tonemapMode ?: "SYSTEM_DEFAULT",
frameId = frameIdToSave,
colorRecipeParams = getMergedRecipeParams(),
baselineTarget = baselineMetadata?.first,
@@ -4908,7 +4916,14 @@ class CameraViewModel(application: Application) : AndroidViewModel(application)
captureMode = captureMode,
multipleExposureFrameCount = expectedFrameCount,
baselineTarget = BaselineColorCorrectionTarget.JPG,
)
).let { hdrMetadata ->
if (hdrMetadata.tonemapMode == "LINEAR_PIPELINE") {
PLog.d(TAG, "YUV HDR bracket stores SYSTEM_DEFAULT tonemap metadata")
hdrMetadata.copy(tonemapMode = "SYSTEM_DEFAULT")
} else {
hdrMetadata
}
}
val photoId = GalleryManager.preparePhoto(
context,
@@ -5204,6 +5219,7 @@ class CameraViewModel(application: Application) : AndroidViewModel(application)
// 创建统一的 PhotoMetadata,包含编辑配置和拍摄信息
val metadata = MediaMetadata(
lutId = lutIdToSave,
tonemapMode = userPrefs?.tonemapMode ?: "SYSTEM_DEFAULT",
frameId = frameIdToSave,
colorRecipeParams = getMergedRecipeParams(),
baselineTarget = baselineMetadata?.first,