feat: video soft light effect and lens switch transition optimizations

This commit is contained in:
zhoubinjia committed 2026-10-21 11:20:26 +08:00
1 parent 2eb10b2721
commit 270b1e48ed
8 files changed
+408 -95

No files matched your search

@@ -5017,17 +5017,29 @@ class Camera2Controller(private val context: Context) {
return return
} }
val enhancedPhotoPreview = state.photoPreviewStabilizationEnabled && !isCapture
// 部分 HAL 的预览模板默认开启厂商 EIS,EIS+ 预览需与视频分支一致显式关闭。
if (enhancedPhotoPreview &&
availableVideoStabilizationModes.contains(
CaptureRequest.CONTROL_VIDEO_STABILIZATION_MODE_OFF
)
) {
builder.set(
CaptureRequest.CONTROL_VIDEO_STABILIZATION_MODE,
CaptureRequest.CONTROL_VIDEO_STABILIZATION_MODE_OFF
)
}
if (availableOpticalStabilizationModes.contains(CaptureRequest.LENS_OPTICAL_STABILIZATION_MODE_ON)) { if (availableOpticalStabilizationModes.contains(CaptureRequest.LENS_OPTICAL_STABILIZATION_MODE_ON)) {
builder.set( builder.set(
CaptureRequest.LENS_OPTICAL_STABILIZATION_MODE, CaptureRequest.LENS_OPTICAL_STABILIZATION_MODE,
if (state.photoPreviewStabilizationEnabled && !isCapture) { if (enhancedPhotoPreview) {
CaptureRequest.LENS_OPTICAL_STABILIZATION_MODE_OFF CaptureRequest.LENS_OPTICAL_STABILIZATION_MODE_OFF
} else { } else {
CaptureRequest.LENS_OPTICAL_STABILIZATION_MODE_ON CaptureRequest.LENS_OPTICAL_STABILIZATION_MODE_ON
} }
) )
} }
applyOisDataMode(builder, state.photoPreviewStabilizationEnabled && !isCapture) applyOisDataMode(builder, enhancedPhotoPreview)
} catch (e: Exception) { } catch (e: Exception) {
PLog.e(TAG, "Failed to apply stabilization settings", e) PLog.e(TAG, "Failed to apply stabilization settings", e)
} }
@@ -69,6 +69,14 @@ internal class HighlightDiffusionGl(private val logTag: String) {
private val halationEffect = Effect(true, 512, 5.0) private val halationEffect = Effect(true, 512, 5.0)
private val bloomEffect = Effect(false, 256, 17.5) private val bloomEffect = Effect(false, 256, 17.5)
fun prepare(): Boolean = try {
ensurePrograms()
true
} catch (failure: IllegalStateException) {
PLog.e(logTag, "Highlight diffusion programs unavailable: ${failure.message}")
false
}
fun renderToTexture( fun renderToTexture(
sourceTextureId: Int, sourceTextureId: Int,
width: Int, width: Int,
@@ -90,6 +90,22 @@ class RealtimeVideoRenderer(
private val finalFilmGrainEnabled: Boolean private val finalFilmGrainEnabled: Boolean
get() = filmGrainAmount > 0.001f && get() = filmGrainAmount > 0.001f &&
encoderColorConfig.pipeline != VideoEncodedColorPipeline.CUSTOM_LOG encoderColorConfig.pipeline != VideoEncodedColorPipeline.CUSTOM_LOG
// Log 录制保留后期空间:柔光与高光扩散只作用于监看画面,不烘焙进编码。
private val spatialEffectsAllowed = !videoLogProfile.isEnabled
private val softLightAmount = spatialEffectAmount { it.softLight }
private val bloomAmount = spatialEffectAmount { it.bloom }
private val redHalationAmount = spatialEffectAmount { it.redHalation }
private val softLightEnabled = softLightAmount > 0.001f
private val highlightDiffusionEnabled = bloomAmount > 0.001f || redHalationAmount > 0.001f
private val postProcessEnabled: Boolean
get() = softLightEnabled || highlightDiffusionEnabled || finalFilmGrainEnabled
private val softLightGl = SoftLightGl(TAG)
private val highlightDiffusionGl = HighlightDiffusionGl(TAG)
private fun spatialEffectAmount(select: (ColorRecipeParams) -> Float): Float {
if (!spatialEffectsAllowed) return 0f
return layers.lastOrNull { select(it.params) > 0.001f }?.params?.let(select) ?: 0f
}
private val identityMatrix = FloatArray(16).also { Matrix.setIdentityM(it, 0) } private val identityMatrix = FloatArray(16).also { Matrix.setIdentityM(it, 0) }
private val firstPassMvpMatrix = FloatArray(16).also { private val firstPassMvpMatrix = FloatArray(16).also {
Matrix.setIdentityM(it, 0) Matrix.setIdentityM(it, 0)
@@ -141,10 +157,10 @@ class RealtimeVideoRenderer(
check(makeCurrent()) { "Cannot make realtime video EGL context current" } check(makeCurrent()) { "Cannot make realtime video EGL context current" }
initializeGeometry() initializeGeometry()
initializeLayerTextures() initializeLayerTextures()
if (layers.size > 1 || finalFilmGrainEnabled) { if (layers.size > 1 || postProcessEnabled) {
initializeIntermediateFramebuffer() initializeIntermediateFramebuffer()
} }
if (layers.size > 1 && finalFilmGrainEnabled) { if (layers.size > 1 && postProcessEnabled) {
val finalTarget = createColorFramebuffer("final color") val finalTarget = createColorFramebuffer("final color")
finalColorTextureId = finalTarget.first finalColorTextureId = finalTarget.first
finalColorFboId = finalTarget.second finalColorFboId = finalTarget.second
@@ -152,6 +168,12 @@ class RealtimeVideoRenderer(
if (finalFilmGrainEnabled) { if (finalFilmGrainEnabled) {
check(filmGrainGl.prepare()) { "Cannot create realtime video film grain program" } check(filmGrainGl.prepare()) { "Cannot create realtime video film grain program" }
} }
if (softLightEnabled) {
check(softLightGl.prepare()) { "Cannot create realtime video soft light programs" }
}
if (highlightDiffusionEnabled) {
check(highlightDiffusionGl.prepare()) { "Cannot create realtime video highlight diffusion programs" }
}
cameraTextureId = GlUtils.createOESTexture() cameraTextureId = GlUtils.createOESTexture()
check(cameraTextureId != 0) { "Cannot create realtime video OES texture" } check(cameraTextureId != 0) { "Cannot create realtime video OES texture" }
@@ -247,8 +269,8 @@ class RealtimeVideoRenderer(
if (presentationTimeNs <= 0L) return null if (presentationTimeNs <= 0L) return null
val firstLayer = layers.first() val firstLayer = layers.first()
val grainEnabled = finalFilmGrainEnabled val postProcess = postProcessEnabled
val firstTargetFbo = if (layers.size > 1 || grainEnabled) intermediateFboId else 0 val firstTargetFbo = if (layers.size > 1 || postProcess) intermediateFboId else 0
drawLayer( drawLayer(
layer = firstLayer, layer = firstLayer,
targetFboId = firstTargetFbo, targetFboId = firstTargetFbo,
@@ -268,7 +290,7 @@ class RealtimeVideoRenderer(
drawLayer( drawLayer(
layer = layer, layer = layer,
targetFboId = if (isLast) { targetFboId = if (isLast) {
if (grainEnabled) finalColorFboId else 0 if (postProcess) finalColorFboId else 0
} else { } else {
intermediateFboId intermediateFboId
}, },
@@ -284,21 +306,12 @@ class RealtimeVideoRenderer(
} }
} }
if (grainEnabled) { if (postProcess) {
val sourceTextureId = if (layers.size > 1) finalColorTextureId else intermediateTextureId drawPostProcess(
check( colorTextureId = if (layers.size > 1) finalColorTextureId else intermediateTextureId,
filmGrainGl.drawToFramebuffer( colorFramebufferId = if (layers.size > 1) finalColorFboId else intermediateFboId,
targetFramebufferId = 0, timestampNs = timestampNs,
sourceTextureId = sourceTextureId, )
width = encoderOutputSize.width,
height = encoderOutputSize.height,
amount = filmGrainAmount,
frameSeed = FilmGrainShaders.frameSeed(timestampNs),
drawQuad = ::drawSimpleQuad,
)
) {
"Realtime video film grain pass failed"
}
} }
EGLExt.eglPresentationTimeANDROID(eglDisplay, encoderEglSurface, presentationTimeNs) EGLExt.eglPresentationTimeANDROID(eglDisplay, encoderEglSurface, presentationTimeNs)
@@ -310,6 +323,55 @@ class RealtimeVideoRenderer(
return presentationTimeNs return presentationTimeNs
} }
/** 与预览一致的顺序:色彩 -> 柔光 -> Halation -> Bloom -> 颗粒,最后写入编码器 Surface。 */
private fun drawPostProcess(colorTextureId: Int, colorFramebufferId: Int, timestampNs: Long) {
val width = encoderOutputSize.width
val height = encoderOutputSize.height
var textureId = colorTextureId
var framebufferId = colorFramebufferId
if (softLightEnabled) {
val output = checkNotNull(
softLightGl.renderToTexture(textureId, width, height, softLightAmount, ::drawSimpleQuad)
) { "Realtime video soft light pass failed" }
textureId = output.textureId
framebufferId = output.framebufferId
}
if (highlightDiffusionEnabled) {
val output = checkNotNull(
highlightDiffusionGl.renderToTexture(
textureId, width, height, bloomAmount, redHalationAmount, ::drawSimpleQuad,
)
) { "Realtime video highlight diffusion pass failed" }
textureId = output.textureId
framebufferId = output.framebufferId
}
if (finalFilmGrainEnabled) {
check(
filmGrainGl.drawToFramebuffer(
targetFramebufferId = 0,
sourceTextureId = textureId,
width = width,
height = height,
amount = filmGrainAmount,
frameSeed = FilmGrainShaders.frameSeed(timestampNs),
drawQuad = ::drawSimpleQuad,
)
) {
"Realtime video film grain pass failed"
}
return
}
GLES30.glBindFramebuffer(GLES30.GL_READ_FRAMEBUFFER, framebufferId)
GLES30.glBindFramebuffer(GLES30.GL_DRAW_FRAMEBUFFER, 0)
GLES30.glBlitFramebuffer(
0, 0, width, height, 0, 0, width, height,
GLES30.GL_COLOR_BUFFER_BIT, GLES30.GL_NEAREST,
)
val error = GLES30.glGetError()
GLES30.glBindFramebuffer(GLES30.GL_FRAMEBUFFER, 0)
check(error == GLES30.GL_NO_ERROR) { "Realtime video post-process output glError=$error" }
}
private fun acquireLatestCameraFrame(surfaceTexture: SurfaceTexture): Boolean { private fun acquireLatestCameraFrame(surfaceTexture: SurfaceTexture): Boolean {
return try { return try {
surfaceTexture.updateTexImage() surfaceTexture.updateTexImage()
@@ -835,18 +897,23 @@ class RealtimeVideoRenderer(
positions.position(0) positions.position(0)
textureCoordinates.position(0) textureCoordinates.position(0)
indices.position(0) indices.position(0)
GLES30.glEnableVertexAttribArray(positionLocation) // gl_FragCoord-based passes (diffusion reduce/normalize) let the linker drop aTexCoord.
GLES30.glVertexAttribPointer(positionLocation, 2, GLES30.GL_FLOAT, false, 0, positions) if (positionLocation >= 0) {
GLES30.glEnableVertexAttribArray(textureLocation) GLES30.glEnableVertexAttribArray(positionLocation)
GLES30.glVertexAttribPointer(textureLocation, 2, GLES30.GL_FLOAT, false, 0, textureCoordinates) GLES30.glVertexAttribPointer(positionLocation, 2, GLES30.GL_FLOAT, false, 0, positions)
}
if (textureLocation >= 0) {
GLES30.glEnableVertexAttribArray(textureLocation)
GLES30.glVertexAttribPointer(textureLocation, 2, GLES30.GL_FLOAT, false, 0, textureCoordinates)
}
GLES30.glDrawElements( GLES30.glDrawElements(
GLES30.GL_TRIANGLES, GLES30.GL_TRIANGLES,
Shaders.DRAW_ORDER.size, Shaders.DRAW_ORDER.size,
GLES30.GL_UNSIGNED_SHORT, GLES30.GL_UNSIGNED_SHORT,
indices, indices,
) )
GLES30.glDisableVertexAttribArray(positionLocation) if (positionLocation >= 0) GLES30.glDisableVertexAttribArray(positionLocation)
GLES30.glDisableVertexAttribArray(textureLocation) if (textureLocation >= 0) GLES30.glDisableVertexAttribArray(textureLocation)
} }
@Synchronized @Synchronized
@@ -908,6 +975,8 @@ class RealtimeVideoRenderer(
finalColorFboId = 0 finalColorFboId = 0
} }
filmGrainGl.release() filmGrainGl.release()
softLightGl.release()
highlightDiffusionGl.release()
mgcEisHardwareBufferRenderer.release() mgcEisHardwareBufferRenderer.release()
mgcEisYuvRenderer.release() mgcEisYuvRenderer.release()
colorProgramCache.release() colorProgramCache.release()
@@ -0,0 +1,174 @@
package com.hinnka.mycamera.lut
import android.opengl.GLES30
import com.hinnka.mycamera.utils.PLog
import kotlin.math.roundToInt
/**
* Context-local Soft Light for video recording and export, using the preview shader sources.
*
* The blur runs on a fixed working long edge so the diffusion radius is a fraction of the
* frame, independent of the encoded resolution. 480 matches the preview's quarter-resolution
* blur of the 1080p-class video viewfinder stream.
*/
internal class SoftLightGl(private val logTag: String) {
companion object {
private const val WORKING_LONG_EDGE = 480
}
private class Program(val source: String) {
var id = 0
private val locations = mutableMapOf<String, Int>()
fun location(name: String) = locations.getOrPut(name) { GLES30.glGetUniformLocation(id, name) }
fun reset() { id = 0; locations.clear() }
}
private class Target(val floating: Boolean) {
var texture = 0
var framebuffer = 0
var width = 0
var height = 0
fun reset() { texture = 0; framebuffer = 0; width = 0; height = 0 }
fun release() {
if (texture != 0) GLES30.glDeleteTextures(1, intArrayOf(texture), 0)
if (framebuffer != 0) GLES30.glDeleteFramebuffers(1, intArrayOf(framebuffer), 0)
reset()
}
}
private val blurH = Program(Shaders.SOFT_LIGHT_PREVIEW_BLUR_H)
private val blurV = Program(Shaders.HDF_PREVIEW_BLUR_V)
private val composite = Program(Shaders.HDF_PREVIEW_COMPOSITE)
private val programs = listOf(blurH, blurV, composite)
private val ping = Target(true)
private val pong = Target(true)
private val output = Target(false)
fun prepare(): Boolean = try {
ensurePrograms()
true
} catch (failure: IllegalStateException) {
PLog.e(logTag, "Soft light program unavailable: ${failure.message}")
false
}
/** Returns the composited display-encoded frame, or null when disabled or on GL failure. */
fun renderToTexture(
sourceTextureId: Int,
width: Int,
height: Int,
strength: Float,
drawQuad: (Int) -> Unit,
): HighlightDiffusionOutput? {
if (strength <= 0.001f) return null
return try {
checkGl("upstream")
ensurePrograms()
val scale = WORKING_LONG_EDGE.toFloat() / maxOf(width, height).coerceAtLeast(1)
val w = (width * scale).roundToInt().coerceAtLeast(1)
val h = (height * scale).roundToInt().coerceAtLeast(1)
ensureTarget(ping, w, h)
ensureTarget(pong, w, h)
ensureTarget(output, width, height)
check(sourceTextureId != output.texture) { "Source aliases soft light output" }
pass(blurH, ping, drawQuad) {
bind(blurH, "uInputTexture", 0, sourceTextureId)
GLES30.glUniform2f(blurH.location("uTexelSize"), 1f / w, 1f / h)
}
pass(blurV, pong, drawQuad) {
bind(blurV, "uInputTexture", 0, ping.texture)
GLES30.glUniform2f(blurV.location("uTexelSize"), 1f / w, 1f / h)
}
pass(composite, output, drawQuad) {
bind(composite, "uOriginalTexture", 0, sourceTextureId)
// The legacy HDF branch is disabled; bind a valid texture to its sampler.
bind(composite, "uBloomTexture", 1, sourceTextureId)
GLES30.glUniform1f(composite.location("uHalation"), 0f)
bind(composite, "uSoftLightTexture", 2, pong.texture)
GLES30.glUniform1f(composite.location("uSoftLight"), strength.coerceIn(0f, 1f))
}
HighlightDiffusionOutput(output.texture, output.framebuffer)
} catch (failure: IllegalStateException) {
PLog.e(logTag, "Soft light failed: ${failure.message}")
null
} finally {
GLES30.glBindFramebuffer(GLES30.GL_FRAMEBUFFER, 0)
for (unit in 2 downTo 0) {
GLES30.glActiveTexture(GLES30.GL_TEXTURE0 + unit)
GLES30.glBindTexture(GLES30.GL_TEXTURE_2D, 0)
}
GLES30.glUseProgram(0)
}
}
private fun pass(program: Program, target: Target, drawQuad: (Int) -> Unit, uniforms: () -> Unit) {
GLES30.glDisable(GLES30.GL_BLEND)
GLES30.glBindFramebuffer(GLES30.GL_FRAMEBUFFER, target.framebuffer)
GLES30.glViewport(0, 0, target.width, target.height)
GLES30.glUseProgram(program.id)
uniforms()
drawQuad(program.id)
checkGl("draw program=${program.id} target=${target.width}x${target.height}")
}
private fun bind(program: Program, name: String, unit: Int, texture: Int) {
GLES30.glActiveTexture(GLES30.GL_TEXTURE0 + unit)
GLES30.glBindTexture(GLES30.GL_TEXTURE_2D, texture)
GLES30.glUniform1i(program.location(name), unit)
}
private fun ensurePrograms() {
for (program in programs) {
if (program.id != 0) continue
val vertex = GlUtils.compileShader(GLES30.GL_VERTEX_SHADER, Shaders.SIMPLE_VERTEX_SHADER)
val fragment = GlUtils.compileShader(GLES30.GL_FRAGMENT_SHADER, program.source)
if (vertex != 0 && fragment != 0) program.id = GlUtils.linkProgram(vertex, fragment)
if (vertex != 0) GLES30.glDeleteShader(vertex)
if (fragment != 0) GLES30.glDeleteShader(fragment)
check(program.id != 0) { "Shader compile/link failed (${programs.indexOf(program)})" }
}
}
private fun ensureTarget(target: Target, width: Int, height: Int) {
if (target.texture != 0 && target.width == width && target.height == height) return
val limit = IntArray(1)
GLES30.glGetIntegerv(GLES30.GL_MAX_TEXTURE_SIZE, limit, 0)
check(width in 1..limit[0] && height in 1..limit[0]) { "Invalid target ${width}x$height, limit=${limit[0]}" }
target.release()
try {
val ids = IntArray(1)
GLES30.glGenTextures(1, ids, 0)
target.texture = ids[0]
GLES30.glActiveTexture(GLES30.GL_TEXTURE0)
GLES30.glBindTexture(GLES30.GL_TEXTURE_2D, target.texture)
val format = if (target.floating) GLES30.GL_RGBA16F else GLES30.GL_RGBA8
GLES30.glTexStorage2D(GLES30.GL_TEXTURE_2D, 1, format, width, height)
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)
GLES30.glGenFramebuffers(1, ids, 0)
target.framebuffer = ids[0]
GLES30.glBindFramebuffer(GLES30.GL_FRAMEBUFFER, target.framebuffer)
GLES30.glFramebufferTexture2D(GLES30.GL_FRAMEBUFFER, GLES30.GL_COLOR_ATTACHMENT0, GLES30.GL_TEXTURE_2D, target.texture, 0)
val status = GLES30.glCheckFramebufferStatus(GLES30.GL_FRAMEBUFFER)
checkGl("allocation ${width}x$height format=$format")
check(status == GLES30.GL_FRAMEBUFFER_COMPLETE) { "Framebuffer status=$status format=$format" }
target.width = width
target.height = height
} catch (failure: IllegalStateException) {
target.release()
throw failure
}
}
private fun checkGl(stage: String) {
val error = GLES30.glGetError()
check(error == GLES30.GL_NO_ERROR) { "$stage glError=$error" }
}
fun release() {
programs.forEach { GlUtils.deleteProgram(it.id); it.reset() }
listOf(ping, pong, output).forEach { it.release() }
}
}
@@ -708,7 +708,7 @@ private class VideoLutShaderProgram(
private var curveTextureId = 0 private var curveTextureId = 0
private val basicToneTextures = BasicToneGlTextures() private val basicToneTextures = BasicToneGlTextures()
private val logInput = LogInputGl() private val logInput = LogInputGl()
private val highlightDiffusion = VideoHighlightDiffusionGl(TAG) private val spatialEffects = VideoSpatialEffectsGl(TAG)
private var lastLutConfig: LutConfig? = null private var lastLutConfig: LutConfig? = null
private var lastRecipeParams: ColorRecipeParams? = null private var lastRecipeParams: ColorRecipeParams? = null
@@ -757,12 +757,16 @@ private class VideoLutShaderProgram(
throw VideoFrameProcessingException("LUT input does not match source Log profile ${effect.sourceLogProfile}", presentationTimeUs) throw VideoFrameProcessingException("LUT input does not match source Log profile ${effect.sourceLogProfile}", presentationTimeUs)
} }
val currentRecipeParams = effect.recipeParams val currentRecipeParams = effect.recipeParams
val softLight = currentRecipeParams?.softLight ?: 0f
val bloom = currentRecipeParams?.bloom ?: 0f val bloom = currentRecipeParams?.bloom ?: 0f
val halation = currentRecipeParams?.redHalation ?: 0f val halation = currentRecipeParams?.redHalation ?: 0f
val diffusionEnabled = bloom > 0.001f || halation > 0.001f val spatialEffectsEnabled = softLight > 0.001f || bloom > 0.001f || halation > 0.001f
// Media3 1.10 defaults to display-encoded SDR, but uses linear RGB for HDR output. // Media3 1.10 defaults to display-encoded SDR, but uses linear RGB for HDR output.
if (diffusionEnabled && useHdr) { if (spatialEffectsEnabled && useHdr) {
throw VideoFrameProcessingException("Bloom and Halation require an SDR video working space", presentationTimeUs) throw VideoFrameProcessingException(
"Soft Light, Bloom and Halation require an SDR video working space",
presentationTimeUs,
)
} }
val previousVao = IntArray(1) val previousVao = IntArray(1)
if (isGles3Context) { if (isGles3Context) {
@@ -770,9 +774,9 @@ private class VideoLutShaderProgram(
GLES30.glBindVertexArray(0) GLES30.glBindVertexArray(0)
} }
try { try {
if (diffusionEnabled) { if (spatialEffectsEnabled) {
highlightDiffusion.drawFrame( spatialEffects.drawFrame(
inputWidth, inputHeight, bloom, halation, inputWidth, inputHeight, softLight, bloom, halation,
currentRecipeParams?.filmGrain ?: 0f, presentationTimeUs, ::drawQuad, currentRecipeParams?.filmGrain ?: 0f, presentationTimeUs, ::drawQuad,
) { ) {
drawColorFrame(inputTexId, presentationTimeUs, currentLutConfig, currentRecipeParams, deferFilmGrain = true) drawColorFrame(inputTexId, presentationTimeUs, currentLutConfig, currentRecipeParams, deferFilmGrain = true)
@@ -974,7 +978,10 @@ private class VideoLutShaderProgram(
} }
GLES30.glUniform1i(GLES30.glGetUniformLocation(programId, "uInputColorSpace"), 0) // 默认 sRGB GLES30.glUniform1i(GLES30.glGetUniformLocation(programId, "uInputColorSpace"), 0) // 默认 sRGB
GLES30.glUniform1f(GLES30.glGetUniformLocation(programId, "uChromaticAberration"), 0f) GLES30.glUniform1f(
GLES30.glGetUniformLocation(programId, "uChromaticAberration"),
currentRecipeParams?.chromaticAberration ?: 0f,
)
GLES30.glUniform1f( GLES30.glUniform1f(
GLES30.glGetUniformLocation(programId, "uSharpening"), GLES30.glGetUniformLocation(programId, "uSharpening"),
currentRecipeParams?.sharpness?.coerceIn(-1f, 1f) ?: 0f, currentRecipeParams?.sharpness?.coerceIn(-1f, 1f) ?: 0f,
@@ -1111,7 +1118,7 @@ private class VideoLutShaderProgram(
deleteCurveTexture() deleteCurveTexture()
basicToneTextures.release() basicToneTextures.release()
logInput.release() logInput.release()
highlightDiffusion.release() spatialEffects.release()
if (positionVbo != 0) { if (positionVbo != 0) {
GLES30.glDeleteBuffers(1, intArrayOf(positionVbo), 0) GLES30.glDeleteBuffers(1, intArrayOf(positionVbo), 0)
positionVbo = 0 positionVbo = 0
@@ -2,8 +2,9 @@ package com.hinnka.mycamera.lut
import android.opengl.GLES30 import android.opengl.GLES30
/** Adapts display-encoded diffusion passes to Media3's caller-owned output framebuffer. */ /** Adapts display-encoded Soft Light and diffusion passes to Media3's caller-owned output framebuffer. */
internal class VideoHighlightDiffusionGl(logTag: String) { internal class VideoSpatialEffectsGl(logTag: String) {
private val softLightGl = SoftLightGl(logTag)
private val diffusion = HighlightDiffusionGl(logTag) private val diffusion = HighlightDiffusionGl(logTag)
private val grain = FilmGrainGl(logTag) private val grain = FilmGrainGl(logTag)
private var colorTexture = 0 private var colorTexture = 0
@@ -14,10 +15,11 @@ internal class VideoHighlightDiffusionGl(logTag: String) {
private val readFramebuffer = IntArray(1) private val readFramebuffer = IntArray(1)
private val viewport = IntArray(4) private val viewport = IntArray(4)
/** Called only when Bloom or Halation is enabled. [drawColor] must defer film grain. */ /** Called only when Soft Light, Bloom or Halation is enabled. [drawColor] must defer film grain. */
fun drawFrame( fun drawFrame(
width: Int, width: Int,
height: Int, height: Int,
softLight: Float,
bloom: Float, bloom: Float,
halation: Float, halation: Float,
filmGrain: Float, filmGrain: Float,
@@ -35,9 +37,18 @@ internal class VideoHighlightDiffusionGl(logTag: String) {
GLES30.glDisable(GLES30.GL_BLEND) GLES30.glDisable(GLES30.GL_BLEND)
drawColor() drawColor()
checkGl("video color pass") checkGl("video color pass")
val output = checkNotNull( // 与预览一致的顺序:柔光 -> Halation -> Bloom -> 颗粒。
diffusion.renderToTexture(colorTexture, width, height, bloom, halation, drawQuad) var output = HighlightDiffusionOutput(colorTexture, colorFramebuffer)
) { "Video highlight diffusion produced no output" } if (softLight > 0.001f) {
output = checkNotNull(
softLightGl.renderToTexture(output.textureId, width, height, softLight, drawQuad)
) { "Video soft light produced no output" }
}
if (bloom > 0.001f || halation > 0.001f) {
output = checkNotNull(
diffusion.renderToTexture(output.textureId, width, height, bloom, halation, drawQuad)
) { "Video highlight diffusion produced no output" }
}
if (filmGrain > 0.001f) { if (filmGrain > 0.001f) {
check(grain.drawToFramebuffer( check(grain.drawToFramebuffer(
targetFramebufferId = drawFramebuffer[0], targetFramebufferId = drawFramebuffer[0],
@@ -55,7 +66,7 @@ internal class VideoHighlightDiffusionGl(logTag: String) {
0, 0, width, height, 0, 0, width, height, 0, 0, width, height, 0, 0, width, height,
GLES30.GL_COLOR_BUFFER_BIT, GLES30.GL_NEAREST, GLES30.GL_COLOR_BUFFER_BIT, GLES30.GL_NEAREST,
) )
checkGl("video diffusion output") checkGl("video spatial effects output")
} }
} finally { } finally {
// Media3 owns this framebuffer, including its lifetime and downstream texture consumers. // Media3 owns this framebuffer, including its lifetime and downstream texture consumers.
@@ -116,6 +127,7 @@ internal class VideoHighlightDiffusionGl(logTag: String) {
} }
fun release() { fun release() {
softLightGl.release()
diffusion.release() diffusion.release()
grain.release() grain.release()
releaseColorTarget() releaseColorTarget()
@@ -67,21 +67,29 @@ internal class LensSwitchTransitionState(
private set private set
private var snapshotZoom = 1f private var snapshotZoom = 1f
private var job: Job? = null private var job: Job? = null
private var switchPending = false private var snapshotAnimationJob: Job? = null
// 为 true 时,正在进行的切换仍接受排队请求;进入淡出阶段后关闭,新请求重新开始一次过渡。
private var acceptsQueuedRequest = false
private data class Request(val cameraId: String, val targetZoom: Float, val onSwitch: () -> Unit) private data class Request(val cameraId: String, val targetZoom: Float, val onSwitch: () -> Unit)
private var pendingRequest: Request? = null private var pendingRequest: Request? = null
private var awaitedCameraId: String? = null
private var previousTimestamp: Long? = null
fun switchLens(cameraId: String, targetZoom: Float, onSwitch: () -> Unit) { fun switchLens(cameraId: String, targetZoom: Float, onSwitch: () -> Unit) {
require(targetZoom.isFinite() && targetZoom > 0f) require(targetZoom.isFinite() && targetZoom > 0f)
// Coalesce gestures while the screenshot is being prepared. Once a switch has // 只保留最新请求。当前切换等待目标镜头首帧期间,新请求排队并沿用同一冻结帧,
// started, replace its waiter but keep the frozen frame across subsequent switches. // 待当前镜头真正出帧后再发起,避免连续跨越多个焦段时相机重开请求互相覆盖。
pendingRequest = Request(cameraId, targetZoom, onSwitch) pendingRequest = Request(cameraId, targetZoom, onSwitch)
if (switchPending && job?.isActive == true) return if (acceptsQueuedRequest && job?.isActive == true) {
// 当前目标镜头出帧后无需等完整快照动画,直接衔接下一次切换。
snapshotAnimationJob?.cancel()
return
}
job?.cancel() job?.cancel()
if (job != null) {
// 淡出中的冻结帧已不是当前镜头画面,重新截取。
clearSnapshot()
}
isActive = true isActive = true
switchPending = true acceptsQueuedRequest = true
job = scope.launch { job = scope.launch {
try { try {
opacity.snapTo(1f) opacity.snapTo(1f)
@@ -97,60 +105,62 @@ internal class LensSwitchTransitionState(
// Let Compose submit the overlay before the camera can release its surface. // Let Compose submit the overlay before the camera can release its surface.
withFrameNanos { } withFrameNanos { }
withFrameNanos { } withFrameNanos { }
val request = pendingRequest while (true) {
pendingRequest = null val request = pendingRequest ?: break
switchPending = false pendingRequest = null
if (request != null) { val stateBeforeSwitch = viewModel.state.value
previousTimestamp = viewModel.state.value.previewFirstFrameTimestampNs if (stateBeforeSwitch.currentCameraId == request.cameraId &&
awaitedCameraId = request.cameraId stateBeforeSwitch.isPreviewActive
) {
// 排队期间目标镜头已处于工作状态,不会产生新的首帧,直接应用请求。
request.onSwitch()
continue
}
val timestampBeforeSwitch = stateBeforeSwitch.previewFirstFrameTimestampNs
request.onSwitch() request.onSwitch()
} coroutineScope {
if (awaitedCameraId == null) { val animation = launch { animateSnapshotTo(request.targetZoom) }
clearSnapshot() snapshotAnimationJob = animation
isActive = false val readyState = viewModel.state.first {
return@launch it.currentCameraId == request.cameraId && it.isPreviewActive &&
} it.previewFirstFrameTimestampNs != null &&
coroutineScope { it.previewFirstFrameTimestampNs != timestampBeforeSwitch
val animation = launch { }
animateSnapshotTo(request?.targetZoom ?: viewModel.zoomRatioByMain) // Follow the current SurfaceView if preview dimensions change.
} val rendered = CompletableDeferred<Unit>()
val readyState = viewModel.state.first { val waiter = launch {
it.currentCameraId == awaitedCameraId && it.isPreviewActive && snapshotFlow { viewModel.glSurfaceView }.collectLatest { preview ->
it.previewFirstFrameTimestampNs != null && if (preview != null) {
it.previewFirstFrameTimestampNs != previousTimestamp preview.awaitPreviewFrame(readyState.previewFirstFrameTimestampNs!!)
} rendered.complete(Unit)
// Follow the current SurfaceView if preview dimensions change. }
val rendered = CompletableDeferred<Unit>()
val waiter = launch {
snapshotFlow { viewModel.glSurfaceView }.collectLatest { preview ->
if (preview != null) {
preview.awaitPreviewFrame(readyState.previewFirstFrameTimestampNs!!)
rendered.complete(Unit)
} }
} }
try {
rendered.await()
} finally {
waiter.cancel()
}
if (pendingRequest != null) animation.cancel()
animation.join()
snapshotAnimationJob = null
} }
try {
rendered.await()
} finally {
waiter.cancel()
}
animation.join()
} }
acceptsQueuedRequest = false
// Renderer callbacks run before GLSurfaceView swaps buffers. // Renderer callbacks run before GLSurfaceView swaps buffers.
withFrameNanos { } withFrameNanos { }
withFrameNanos { } withFrameNanos { }
opacity.animateTo(0f, tween(160)) opacity.animateTo(0f, tween(160))
clearSnapshot() clearSnapshot()
isActive = false isActive = false
awaitedCameraId = null
} catch (error: CancellationException) { } catch (error: CancellationException) {
throw error throw error
} catch (error: Exception) { } catch (error: Exception) {
PLog.e("LensSwitchTransition", "Lens preview transition failed", error) PLog.e("LensSwitchTransition", "Lens preview transition failed", error)
clearSnapshot() clearSnapshot()
isActive = false isActive = false
switchPending = false acceptsQueuedRequest = false
awaitedCameraId = null snapshotAnimationJob = null
pendingRequest = null pendingRequest = null
} }
} }
@@ -159,11 +169,11 @@ internal class LensSwitchTransitionState(
fun cancel() { fun cancel() {
job?.cancel() job?.cancel()
job = null job = null
snapshotAnimationJob = null
clearSnapshot() clearSnapshot()
isActive = false isActive = false
switchPending = false acceptsQueuedRequest = false
pendingRequest = null pendingRequest = null
awaitedCameraId = null
} }
fun cancelPendingSwitch() { fun cancelPendingSwitch() {
@@ -17,6 +17,9 @@ object VideoCapabilitiesResolver {
private const val TAG = "VideoCapabilitiesResolver" private const val TAG = "VideoCapabilitiesResolver"
private const val VIDEO_PREVIEW_SHORT_EDGE = 1080 private const val VIDEO_PREVIEW_SHORT_EDGE = 1080
private const val VIDEO_PREVIEW_ASPECT_TOLERANCE = 0.01f private const val VIDEO_PREVIEW_ASPECT_TOLERANCE = 0.01f
private const val EIGHT_MP_SOURCE_MIN_PIXELS = 7_500_000L
private const val EIGHT_MP_SOURCE_MAX_PIXELS = 12_000_000L
private const val EIGHT_MP_SOURCE_ASPECT_TOLERANCE = 0.04f
fun resolve( fun resolve(
characteristics: CameraCharacteristics, characteristics: CameraCharacteristics,
@@ -40,10 +43,16 @@ object VideoCapabilitiesResolver {
val yuvOutputSizes = streamConfigMap?.getOutputSizes(ImageFormat.YUV_420_888)?.toList().orEmpty() val yuvOutputSizes = streamConfigMap?.getOutputSizes(ImageFormat.YUV_420_888)?.toList().orEmpty()
// Dedicated recording uses a SurfaceTexture input, including full-sensor sizes // Dedicated recording uses a SurfaceTexture input, including full-sensor sizes
// that may not be advertised for MediaRecorder. // that may not be advertised for MediaRecorder.
val recordingOutputSizes = if (requestedConfig.aspectRatio == VideoAspectRatio.OPEN_GATE) { // 无原生 4K 录制流但存在 8MP 级 4:3 源时,同样以 SurfaceTexture 流作为录制门控。
previewOutputSizes val advertisedRecordingSizes = resolveRecordingOutputSizes(characteristics)
} else { val hasNativeUhdRecordingSize = advertisedRecordingSizes.any {
resolveRecordingOutputSizes(characteristics) maxOf(it.width, it.height) >= VideoResolutionPreset.UHD_2160P.longEdge
}
val recordingOutputSizes = when {
requestedConfig.aspectRatio == VideoAspectRatio.OPEN_GATE -> previewOutputSizes
!hasNativeUhdRecordingSize && previewOutputSizes.any(::isEightMpFourThreeSource) ->
previewOutputSizes
else -> advertisedRecordingSizes
} }
val sensorOrientation = characteristics.get(CameraCharacteristics.SENSOR_ORIENTATION) ?: 0 val sensorOrientation = characteristics.get(CameraCharacteristics.SENSOR_ORIENTATION) ?: 0
val activeArray = characteristics.get(CameraCharacteristics.SENSOR_INFO_ACTIVE_ARRAY_SIZE) val activeArray = characteristics.get(CameraCharacteristics.SENSOR_INFO_ACTIVE_ARRAY_SIZE)
@@ -220,7 +229,7 @@ object VideoCapabilitiesResolver {
) )
} }
} }
return outputSizes val coveringSize = outputSizes
.filter { maxOf(it.width, it.height) >= preset.longEdge } .filter { maxOf(it.width, it.height) >= preset.longEdge }
.sortedWith( .sortedWith(
compareBy<Size> { abs(getPortraitAspectRatio(it) - targetAspect) } compareBy<Size> { abs(getPortraitAspectRatio(it) - targetAspect) }
@@ -228,6 +237,18 @@ object VideoCapabilitiesResolver {
.thenByDescending { it.width.toLong() * it.height.toLong() } .thenByDescending { it.width.toLong() * it.height.toLong() }
) )
.firstOrNull() .firstOrNull()
if (coveringSize != null || preset != VideoResolutionPreset.UHD_2160P) return coveringSize
// 8MP 级 4:3 传感器(常见于前摄/超广角)没有长边 ≥3840 的流,但像素量与 4K 相当;
// 录制经 GL 渲染裁切缩放到编码尺寸,因此允许以该流作为 4K 输入源。
return outputSizes
.filter(::isEightMpFourThreeSource)
.maxByOrNull { it.width.toLong() * it.height.toLong() }
}
private fun isEightMpFourThreeSource(size: Size): Boolean {
val pixels = size.width.toLong() * size.height.toLong()
return pixels in EIGHT_MP_SOURCE_MIN_PIXELS until EIGHT_MP_SOURCE_MAX_PIXELS &&
abs(getPortraitAspectRatio(size) - 3f / 4f) <= EIGHT_MP_SOURCE_ASPECT_TOLERANCE
} }
private fun findFixedPreviewOutputSize( private fun findFixedPreviewOutputSize(