feat: photon denoise base for non-raw photos and high-res capture fallback
This commit is contained in:
1 parent
70dff68795
commit
3fb230d051
9 files changed
+394
-67
No files matched your search
@@ -296,6 +296,9 @@ class Camera2Controller(private val context: Context) {
|
||||
private var activeOpenCameraId: String = ""
|
||||
private var activeOutputPhysicalCameraId: String? = null
|
||||
private val failedPhysicalOutputProfiles = mutableSetOf<PhysicalOutputFailureKey>()
|
||||
// "streamCameraId:format" profiles whose high-resolution-only capture size failed session configuration
|
||||
private val failedHighResolutionCaptureProfiles = mutableSetOf<String>()
|
||||
private var activeHighResolutionCaptureProfile: String? = null
|
||||
private var cachedSensorOrientation: Int = 0
|
||||
private var cachedLensFacing: Int = CameraCharacteristics.LENS_FACING_BACK
|
||||
private var cachedHardwareLevel: Int = CameraCharacteristics.INFO_SUPPORTED_HARDWARE_LEVEL_LIMITED
|
||||
@@ -2818,10 +2821,29 @@ class Camera2Controller(private val context: Context) {
|
||||
}
|
||||
previewSize = CameraUtils.getFixedPreviewSize(outputCharacteristicsForStreams, aspectRatio)
|
||||
surfaceTexture.setDefaultBufferSize(previewSize.width, previewSize.height)
|
||||
val captureSize = if (rawOutput != null) {
|
||||
rawOutput.size
|
||||
val highResolutionProfile = "$outputCameraIdForStreams:$captureFormat"
|
||||
val captureSizeSelection = if (rawOutput != null) {
|
||||
null
|
||||
} else {
|
||||
CameraUtils.getBestCaptureSize(outputCharacteristicsForStreams, aspectRatio, captureFormat)
|
||||
CameraUtils.selectCaptureSize(
|
||||
outputCharacteristicsForStreams,
|
||||
aspectRatio,
|
||||
captureFormat,
|
||||
includeHighResolution = highResolutionProfile !in failedHighResolutionCaptureProfiles
|
||||
)
|
||||
}
|
||||
val captureSize = rawOutput?.size ?: captureSizeSelection!!.size
|
||||
activeHighResolutionCaptureProfile =
|
||||
highResolutionProfile.takeIf { captureSizeSelection?.isHighResolution == true }
|
||||
captureSizeSelection?.let { selection ->
|
||||
PLog.i(
|
||||
TAG,
|
||||
"Capture size candidates: selected=${selection.size.width}x${selection.size.height}, " +
|
||||
"highResolution=${selection.isHighResolution}, " +
|
||||
"maxStandard=${selection.maxStandardSize?.let { "${it.width}x${it.height}" }}, " +
|
||||
"maxHighResolution=${selection.maxHighResolutionSize?.let { "${it.width}x${it.height}" }}, " +
|
||||
"highResolutionDisabled=${highResolutionProfile in failedHighResolutionCaptureProfiles}"
|
||||
)
|
||||
}
|
||||
|
||||
val isP3Supported = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.UPSIDE_DOWN_CAKE) {
|
||||
@@ -2872,6 +2894,7 @@ class Camera2Controller(private val context: Context) {
|
||||
} else {
|
||||
safeCloseImageReader(imageReader)
|
||||
imageReader = null
|
||||
activeHighResolutionCaptureProfile = null
|
||||
_state.value = _state.value.copy(isP3Supported = false)
|
||||
}
|
||||
|
||||
@@ -3289,6 +3312,9 @@ class Camera2Controller(private val context: Context) {
|
||||
) {
|
||||
return
|
||||
}
|
||||
if (retryPhotoSessionWithoutHighResolutionCapture("photo configure failed", openGeneration)) {
|
||||
return
|
||||
}
|
||||
if (retryPreviewSessionWithoutPhysicalOutput("photo configure failed", openGeneration)) {
|
||||
return
|
||||
}
|
||||
@@ -3545,6 +3571,24 @@ class Camera2Controller(private val context: Context) {
|
||||
return true
|
||||
}
|
||||
|
||||
private fun retryPhotoSessionWithoutHighResolutionCapture(
|
||||
reason: String,
|
||||
openGeneration: Long
|
||||
): Boolean {
|
||||
val profile = activeHighResolutionCaptureProfile ?: return false
|
||||
val surfaceTexture = previewSurfaceTexture ?: return false
|
||||
val handler = cameraHandler ?: return false
|
||||
if (!failedHighResolutionCaptureProfiles.add(profile)) return false
|
||||
activeHighResolutionCaptureProfile = null
|
||||
PLog.w(TAG, "Retrying photo session without high-resolution capture size: profile=$profile, reason=$reason")
|
||||
// The standard-size capture needs a new ImageReader.
|
||||
return handler.post {
|
||||
if (openGeneration == cameraOpenGeneration) {
|
||||
openCamera(surfaceTexture)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private fun retryPreviewSessionWithoutPhysicalOutput(
|
||||
reason: String,
|
||||
openGeneration: Long
|
||||
|
||||
@@ -5,6 +5,7 @@ import android.graphics.ImageFormat
|
||||
import android.graphics.SurfaceTexture
|
||||
import android.hardware.camera2.CameraCharacteristics
|
||||
import android.hardware.camera2.CameraManager
|
||||
import android.hardware.camera2.params.StreamConfigurationMap
|
||||
import android.util.Log
|
||||
import android.util.Size
|
||||
import com.hinnka.mycamera.utils.PLog
|
||||
@@ -68,8 +69,9 @@ object CameraUtils {
|
||||
// 两者裁切到 65:24 时,4:3 的水平 FOV 更大,导致拍到的画面比预览多。
|
||||
//
|
||||
// 策略:找到 getBestCaptureSize 会选择的比例,然后选择该比例的预览尺寸
|
||||
val captureSizes = map.getOutputSizes(android.graphics.ImageFormat.YUV_420_888)?.toList() ?: emptyList()
|
||||
val bestCaptureSize = captureSizes.maxByOrNull { it.width * it.height }
|
||||
val captureSizes = map.getOutputSizes(ImageFormat.YUV_420_888)?.toList().orEmpty() +
|
||||
getHighResolutionOutputSizes(map, ImageFormat.YUV_420_888)
|
||||
val bestCaptureSize = captureSizes.maxByOrNull { it.width.toLong() * it.height }
|
||||
|
||||
if (bestCaptureSize != null) {
|
||||
val captureRatio = bestCaptureSize.width.toFloat() / bestCaptureSize.height
|
||||
@@ -116,31 +118,75 @@ object CameraUtils {
|
||||
characteristics: CameraCharacteristics,
|
||||
aspectRatio: AspectRatio,
|
||||
format: Int = ImageFormat.YUV_420_888
|
||||
): Size {
|
||||
): Size = selectCaptureSize(characteristics, aspectRatio, format).size
|
||||
|
||||
/**
|
||||
* 拍照尺寸选择结果
|
||||
* @param isHighResolution 尺寸仅出现在 getHighResolutionOutputSizes 中(无法保证 20fps,部分 HAL 可能配置失败)
|
||||
*/
|
||||
data class CaptureSizeSelection(
|
||||
val size: Size,
|
||||
val isHighResolution: Boolean,
|
||||
val maxStandardSize: Size?,
|
||||
val maxHighResolutionSize: Size?
|
||||
)
|
||||
|
||||
/**
|
||||
* 选择拍照尺寸
|
||||
*
|
||||
* 不支持 BURST_CAPTURE 的设备会把达不到 20fps 的全尺寸只放在 getHighResolutionOutputSizes 中,
|
||||
* 只看 getOutputSizes 会选到 1920x1440 之类的低分辨率。
|
||||
*/
|
||||
fun selectCaptureSize(
|
||||
characteristics: CameraCharacteristics,
|
||||
aspectRatio: AspectRatio,
|
||||
format: Int = ImageFormat.YUV_420_888,
|
||||
includeHighResolution: Boolean = true
|
||||
): CaptureSizeSelection {
|
||||
val fallback = CaptureSizeSelection(Size(1920, 1080), false, null, null)
|
||||
return try {
|
||||
val map = characteristics.get(CameraCharacteristics.SCALER_STREAM_CONFIGURATION_MAP)
|
||||
val sizes = map?.getOutputSizes(format)
|
||||
?: map?.getOutputSizes(ImageFormat.YUV_420_888)
|
||||
?: arrayOf(Size(1920, 1080))
|
||||
val sensorRatio = aspectRatio.getValue(true)
|
||||
|
||||
// 寻找比例最匹配传感器原生比例
|
||||
val matchingSizes = sizes.filter {
|
||||
val ratio = it.width.toFloat() / it.height
|
||||
abs(ratio - sensorRatio) < 0.01
|
||||
}
|
||||
|
||||
val bestMatching = matchingSizes.filter { it.height >= 2160 }.maxByOrNull { it.width * it.height }
|
||||
|
||||
if (bestMatching != null) return bestMatching
|
||||
|
||||
// 选择最大的尺寸
|
||||
sizes.maxByOrNull { it.width * it.height } ?: Size(1920, 1080)
|
||||
?: return fallback
|
||||
val outputFormat = if (map.getOutputSizes(format) != null) format else ImageFormat.YUV_420_888
|
||||
val standardSizes = map.getOutputSizes(outputFormat)?.toList().orEmpty()
|
||||
val highResolutionSizes = getHighResolutionOutputSizes(map, outputFormat)
|
||||
.filterNot { it in standardSizes }
|
||||
val candidates = if (includeHighResolution) standardSizes + highResolutionSizes else standardSizes
|
||||
val size = chooseCaptureSize(candidates, aspectRatio.getValue(true)) ?: return fallback
|
||||
CaptureSizeSelection(
|
||||
size = size,
|
||||
isHighResolution = size in highResolutionSizes,
|
||||
maxStandardSize = standardSizes.maxByOrNull { it.width.toLong() * it.height },
|
||||
maxHighResolutionSize = highResolutionSizes.maxByOrNull { it.width.toLong() * it.height }
|
||||
)
|
||||
} catch (e: Exception) {
|
||||
// PLog.e(TAG, "Failed to get capture size", e)
|
||||
Size(1920, 1080)
|
||||
PLog.w("CameraUtils", "selectCaptureSize failed: ${e.message}")
|
||||
fallback
|
||||
}
|
||||
}
|
||||
|
||||
private fun getHighResolutionOutputSizes(map: StreamConfigurationMap, format: Int): List<Size> {
|
||||
return try {
|
||||
map.getHighResolutionOutputSizes(format)?.toList().orEmpty()
|
||||
} catch (e: Exception) {
|
||||
emptyList()
|
||||
}
|
||||
}
|
||||
|
||||
private fun chooseCaptureSize(sizes: List<Size>, sensorRatio: Float): Size? {
|
||||
// 寻找比例最匹配传感器原生比例
|
||||
val matchingSizes = sizes.filter {
|
||||
val ratio = it.width.toFloat() / it.height
|
||||
abs(ratio - sensorRatio) < 0.01
|
||||
}
|
||||
|
||||
val bestMatching = matchingSizes.filter { it.height >= 2160 }.maxByOrNull { it.width.toLong() * it.height }
|
||||
|
||||
if (bestMatching != null) return bestMatching
|
||||
|
||||
// 选择最大的尺寸
|
||||
return sizes.maxByOrNull { it.width.toLong() * it.height }
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取 RAW 拍照尺寸
|
||||
|
||||
@@ -138,6 +138,8 @@ object GalleryManager {
|
||||
private const val VIDEO_FILE = "video.mp4"
|
||||
private const val DNG_FILE = "original.dng"
|
||||
private const val AI_DENOISE_FILE = "ai_denoise.jpg"
|
||||
private const val PHOTON_DENOISE_FILE = "photon_denoise.jpg"
|
||||
private const val PHOTON_DENOISE_KEY_FILE = "photon_denoise.key"
|
||||
private const val THUMBNAIL_FILE = "thumbnail.jpg"
|
||||
private const val BOKEH_FILE = "bokeh.jpg"
|
||||
private const val DETAIL_HDR_FILE = "detail_hdr.jpg"
|
||||
@@ -600,6 +602,14 @@ object GalleryManager {
|
||||
return File(getPhotoDir(context, photoId), AI_DENOISE_FILE)
|
||||
}
|
||||
|
||||
fun getPhotonDenoiseFile(context: Context, photoId: String): File {
|
||||
return File(getPhotoDir(context, photoId), PHOTON_DENOISE_FILE)
|
||||
}
|
||||
|
||||
fun getPhotonDenoiseKeyFile(context: Context, photoId: String): File {
|
||||
return File(getPhotoDir(context, photoId), PHOTON_DENOISE_KEY_FILE)
|
||||
}
|
||||
|
||||
fun getDepthFile(context: Context, photoId: String): File {
|
||||
return File(getPhotoDir(context, photoId), "depthmap.png")
|
||||
}
|
||||
|
||||
@@ -38,9 +38,14 @@ import com.hinnka.mycamera.raw.SpectralFilmTuning
|
||||
import com.hinnka.mycamera.utils.BitmapUtils
|
||||
import com.hinnka.mycamera.raw.fotufilm.FotufilmDocumentStorage
|
||||
import com.hinnka.mycamera.utils.PLog
|
||||
import android.net.Uri
|
||||
import com.hinnka.mycamera.processor.DenoiseStrength
|
||||
import kotlinx.coroutines.flow.firstOrNull
|
||||
import kotlinx.coroutines.Dispatchers
|
||||
import kotlinx.coroutines.sync.Mutex
|
||||
import kotlinx.coroutines.sync.withLock
|
||||
import kotlinx.coroutines.withContext
|
||||
import java.io.File
|
||||
import kotlin.math.abs
|
||||
import kotlin.math.roundToInt
|
||||
|
||||
@@ -60,6 +65,7 @@ class PhotoProcessor(
|
||||
private val userPreferencesRepository: UserPreferencesRepository,
|
||||
) {
|
||||
private val colorCorrectionPipelineResolver = ColorCorrectionPipelineResolver(lutManager)
|
||||
private val photonDenoiseBaseMutex = Mutex()
|
||||
|
||||
data class HdrFrameOutput(
|
||||
val bitmap: Bitmap,
|
||||
@@ -82,6 +88,101 @@ class PhotoProcessor(
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 非 RAW 照片的降噪基底(对应 RAW 烘焙进 original.jpg 的降噪):对 [source] 全分辨率跑一次
|
||||
* Photon 降噪并持久化为 photon_denoise.jpg,预览/导出直接加载基底并以 0 强度走 LUT。
|
||||
* key 绑定源文件与强度;两个强度都为 0 时删除基底。返回基底文件是否发生了变化。
|
||||
*/
|
||||
suspend fun updatePhotonDenoiseBase(
|
||||
context: Context,
|
||||
photoId: String,
|
||||
source: File,
|
||||
noiseReduction: Float,
|
||||
chromaNoiseReduction: Float,
|
||||
): Boolean {
|
||||
val luma = DenoiseStrength.clamp(noiseReduction)
|
||||
val chroma = DenoiseStrength.clamp(chromaNoiseReduction)
|
||||
val baseFile = GalleryManager.getPhotonDenoiseFile(context, photoId)
|
||||
val keyFile = GalleryManager.getPhotonDenoiseKeyFile(context, photoId)
|
||||
val key = "${photonDenoiseSourceKey(source)}|$luma|$chroma"
|
||||
photonDenoiseBaseMutex.withLock {
|
||||
if (luma <= 0f && chroma <= 0f) {
|
||||
return withContext(Dispatchers.IO) {
|
||||
val existed = baseFile.exists()
|
||||
keyFile.delete()
|
||||
baseFile.delete()
|
||||
existed
|
||||
}
|
||||
}
|
||||
if (withContext(Dispatchers.IO) { readPhotonDenoiseKey(baseFile, keyFile) == key }) return false
|
||||
withContext(Dispatchers.IO) { keyFile.delete() }
|
||||
val input = GalleryManager.loadBitmap(context, Uri.fromFile(source)) ?: return false
|
||||
val denoised = try {
|
||||
lutImageProcessor.applyBitmapDenoise(input, luma, chroma)
|
||||
} catch (e: Throwable) {
|
||||
input.recycle()
|
||||
throw e
|
||||
}
|
||||
input.recycle()
|
||||
if (denoised === input) return false
|
||||
val written = withContext(Dispatchers.IO) {
|
||||
val tmp = File(baseFile.parentFile, "${baseFile.name}.tmp")
|
||||
try {
|
||||
tmp.outputStream().use { denoised.compress(Bitmap.CompressFormat.JPEG, 95, it) }
|
||||
} finally {
|
||||
denoised.recycle()
|
||||
}
|
||||
(tmp.renameTo(baseFile) || run { tmp.delete(); false }).also {
|
||||
if (it) keyFile.writeText(key)
|
||||
}
|
||||
}
|
||||
if (written) PLog.d("PhotoProcessor", "Photon denoise base rebuilt: $photoId luma=$luma chroma=$chroma")
|
||||
return written
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 加载 [source] 的降噪基底,不可用时返回 null(调用方按原路径处理)。给出强度时缺失或过期的
|
||||
* 基底会先重建;强度为 null(编辑预览)只读取已有基底,和 RAW 一样在松手时才由
|
||||
* [updatePhotonDenoiseBase] 按新强度生成,拖动过程中保持旧结果。
|
||||
*/
|
||||
suspend fun loadPhotonDenoiseBase(
|
||||
context: Context,
|
||||
photoId: String,
|
||||
source: File,
|
||||
noiseReduction: Float?,
|
||||
chromaNoiseReduction: Float?,
|
||||
maxEdge: Int? = null,
|
||||
): Bitmap? {
|
||||
if (noiseReduction != null && chromaNoiseReduction != null) {
|
||||
if (DenoiseStrength.clamp(noiseReduction) <= 0f && DenoiseStrength.clamp(chromaNoiseReduction) <= 0f) {
|
||||
return null
|
||||
}
|
||||
updatePhotonDenoiseBase(context, photoId, source, noiseReduction, chromaNoiseReduction)
|
||||
}
|
||||
val baseFile = GalleryManager.getPhotonDenoiseFile(context, photoId)
|
||||
val keyFile = GalleryManager.getPhotonDenoiseKeyFile(context, photoId)
|
||||
return photonDenoiseBaseMutex.withLock {
|
||||
withContext(Dispatchers.IO) {
|
||||
val key = readPhotonDenoiseKey(baseFile, keyFile) ?: return@withContext null
|
||||
val expected = if (noiseReduction != null && chromaNoiseReduction != null) {
|
||||
"${photonDenoiseSourceKey(source)}|${DenoiseStrength.clamp(noiseReduction)}|" +
|
||||
"${DenoiseStrength.clamp(chromaNoiseReduction)}"
|
||||
} else {
|
||||
null
|
||||
}
|
||||
val matches = expected?.let { key == it } ?: key.startsWith("${photonDenoiseSourceKey(source)}|")
|
||||
if (matches) GalleryManager.loadBitmap(context, Uri.fromFile(baseFile), maxEdge) else null
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private fun photonDenoiseSourceKey(source: File) =
|
||||
"v1|${source.name}|${source.lastModified()}|${source.length()}"
|
||||
|
||||
private fun readPhotonDenoiseKey(baseFile: File, keyFile: File): String? =
|
||||
if (baseFile.exists() && keyFile.exists()) keyFile.readText() else null
|
||||
|
||||
private fun resolveNoiseReduction(metadata: MediaMetadata, fallback: Float): Float {
|
||||
return metadata.noiseReduction ?: (if (metadata.isImported) 0f else fallback)
|
||||
}
|
||||
@@ -515,17 +616,8 @@ class PhotoProcessor(
|
||||
if (metadata.hasAiDenoisedBase) {
|
||||
val aiFile = GalleryManager.getAiDenoiseFile(context, photoId)
|
||||
if (aiFile.exists()) {
|
||||
val bitmap = GalleryManager.loadBitmap(context, android.net.Uri.fromFile(aiFile)) ?: return null
|
||||
return processBitmap(
|
||||
context,
|
||||
photoId,
|
||||
bitmap,
|
||||
metadata,
|
||||
sharpening,
|
||||
noiseReduction,
|
||||
chromaNoiseReduction,
|
||||
true
|
||||
)
|
||||
return processBitmapSource(context, photoId, aiFile, metadata, sharpening, noiseReduction,
|
||||
chromaNoiseReduction) { GalleryManager.loadBitmap(context, Uri.fromFile(aiFile)) }
|
||||
}
|
||||
return null
|
||||
}
|
||||
@@ -541,20 +633,48 @@ class PhotoProcessor(
|
||||
chromaNoiseReduction,
|
||||
onRawMetadata
|
||||
)
|
||||
} else if (GalleryManager.getOriginalImageFile(context, photoId) != null) {
|
||||
val bitmap = GalleryManager.loadOriginalBitmap(context, photoId) ?: return null
|
||||
} else {
|
||||
val originalFile = GalleryManager.getOriginalImageFile(context, photoId) ?: return null
|
||||
return processBitmapSource(context, photoId, originalFile, metadata, sharpening, noiseReduction,
|
||||
chromaNoiseReduction) { GalleryManager.loadOriginalBitmap(context, photoId) }
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* [processBitmap] of a non-RAW source file through its Photon denoise base when one applies.
|
||||
* With a computational aperture the bokeh pass would persist the denoised pixels into
|
||||
* bokeh.jpg, which is denoised again on its own base, so that case keeps the in-LUT denoise.
|
||||
*/
|
||||
private suspend fun processBitmapSource(
|
||||
context: Context,
|
||||
photoId: String,
|
||||
source: File,
|
||||
metadata: MediaMetadata,
|
||||
sharpening: Float,
|
||||
noiseReduction: Float,
|
||||
chromaNoiseReduction: Float,
|
||||
loadSource: () -> Bitmap?,
|
||||
): Bitmap? {
|
||||
val base = if ((metadata.computationalAperture ?: 0f) <= 0f) {
|
||||
loadPhotonDenoiseBase(
|
||||
context = context,
|
||||
photoId = photoId,
|
||||
source = source,
|
||||
noiseReduction = resolveNoiseReduction(metadata, noiseReduction),
|
||||
chromaNoiseReduction = resolveChromaNoiseReduction(metadata, chromaNoiseReduction),
|
||||
)
|
||||
} else {
|
||||
null
|
||||
}
|
||||
if (base != null) {
|
||||
return processBitmap(
|
||||
context,
|
||||
photoId,
|
||||
bitmap,
|
||||
metadata,
|
||||
sharpening,
|
||||
noiseReduction,
|
||||
chromaNoiseReduction,
|
||||
true
|
||||
context, photoId, base,
|
||||
metadata.copy(noiseReduction = 0f, chromaNoiseReduction = 0f),
|
||||
sharpening, 0f, 0f, true
|
||||
)
|
||||
}
|
||||
return null
|
||||
val bitmap = loadSource() ?: return null
|
||||
return processBitmap(context, photoId, bitmap, metadata, sharpening, noiseReduction, chromaNoiseReduction, true)
|
||||
}
|
||||
|
||||
private suspend fun processDngForUltraHdr(
|
||||
|
||||
@@ -87,7 +87,7 @@ class LutImageProcessor(context: Context? = null) {
|
||||
private var bitmapDenoisePassthroughProgram = 0
|
||||
private var computeCapabilitiesChecked = false
|
||||
private var computeCapabilitiesSupported = false
|
||||
private val bitmapPhotonDenoiser = PhotonMultiScaleDenoiser()
|
||||
private val bitmapPhotonDenoiser = PhotonMultiScaleDenoiser(PhotonMultiScaleDenoiser.UI_SLICE_PIXELS)
|
||||
private var lutSharpenProgram = 0
|
||||
private var lutLuminanceGainProgram = 0
|
||||
|
||||
@@ -732,7 +732,15 @@ class LutImageProcessor(context: Context? = null) {
|
||||
if (uploadBitmap !== bitmap) uploadBitmap.recycle()
|
||||
}
|
||||
|
||||
suspend fun applyChromaDenoise(bitmap: Bitmap, strength: Float = 0.1f): Bitmap = withContext(glDispatcher) {
|
||||
suspend fun applyChromaDenoise(bitmap: Bitmap, strength: Float = 0.1f): Bitmap =
|
||||
applyBitmapDenoise(bitmap, 0f, strength)
|
||||
|
||||
/** Photon Bitmap 降噪(不含 LUT/配方),两个强度都为 0 时原样返回。 */
|
||||
suspend fun applyBitmapDenoise(
|
||||
bitmap: Bitmap,
|
||||
lumaStrength: Float,
|
||||
chromaStrength: Float,
|
||||
): Bitmap = withContext(glDispatcher) {
|
||||
currentCoroutineContext().ensureActive()
|
||||
if (!isInitialized) {
|
||||
if (!initialize()) {
|
||||
@@ -747,7 +755,8 @@ class LutImageProcessor(context: Context? = null) {
|
||||
setupFramebuffer(width, height)
|
||||
uploadImageTexture(bitmap)
|
||||
|
||||
val denoised = renderBitmapPhotonDenoise(imageTextureId, width, height, 0f, strength)
|
||||
val denoised = renderBitmapPhotonDenoise(imageTextureId, width, height, lumaStrength, chromaStrength)
|
||||
if (!denoised) return@withContext bitmap
|
||||
performRender(
|
||||
width = width,
|
||||
height = height,
|
||||
|
||||
@@ -35,7 +35,9 @@ internal object PhotonDenoiseShaders {
|
||||
|
||||
layout(local_size_x = $LOCAL, local_size_y = $LOCAL) in;
|
||||
|
||||
ivec2 groupId() { return ivec2(gl_WorkGroupID.xy); }
|
||||
// Work-group origin of a sliced dispatch (PhotonMultiScaleDenoiser.sliceBudgetPixels).
|
||||
uniform ivec2 uGroupOffset;
|
||||
ivec2 groupId() { return ivec2(gl_WorkGroupID.xy) + uGroupOffset; }
|
||||
ivec2 globalId() { return groupId() * $LOCAL + ivec2(gl_LocalInvocationID.xy); }
|
||||
|
||||
const float LUMA_TAPS[7] = float[7](
|
||||
|
||||
@@ -18,8 +18,14 @@ import java.nio.ByteOrder
|
||||
* the LSC gains restored. Only the Gaussian levels and two adjacent denoised levels are held
|
||||
* (§10.2). A [PassSink] receives every pass output for parity checks; it adds a parity dispatch
|
||||
* per level that emits the fused pass's band, base, noise and pilot tiles.
|
||||
*
|
||||
* [sliceBudgetPixels] > 0 splits every Analyze/Synthesize dispatch into row slices of about that
|
||||
* many pixels with a GPU checkpoint after each. Callers that hand over a whole image in one call
|
||||
* (the Bitmap edit path) need it: a full-image dispatch chain cannot be preempted on many GPUs,
|
||||
* so the compositor starves (black, frozen screen) or the driver watchdog resets the GPU. The
|
||||
* tiled RAW pipelines already checkpoint between tiles and keep whole-level dispatches.
|
||||
*/
|
||||
internal class PhotonMultiScaleDenoiser {
|
||||
internal class PhotonMultiScaleDenoiser(private val sliceBudgetPixels: Int = 0) {
|
||||
/** Receives pass outputs while their textures are alive (debug parity, §12.4). */
|
||||
fun interface PassSink {
|
||||
fun onPass(name: String, textureId: Int, width: Int, height: Int, float32: Boolean)
|
||||
@@ -371,15 +377,33 @@ internal class PhotonMultiScaleDenoiser {
|
||||
/**
|
||||
* One whole-level dispatch. As in GlesMgcRawSpatialStacker, the UI renderer is kept responsive
|
||||
* by the low-priority EGL context and a flush + yield between levels, never by fence waits
|
||||
* inside a level: those drain the GPU and leave it idle until this thread wakes up.
|
||||
* inside a level: those drain the GPU and leave it idle until this thread wakes up. With a
|
||||
* [sliceBudgetPixels] the level is dispatched in row slices instead, each followed by a
|
||||
* checkpoint, trading that idle time for bounded GPU occupancy.
|
||||
*/
|
||||
private fun dispatch(program: Int, size: IntArray) {
|
||||
GLES31.glDispatchCompute(GlesComputeWorkGroup.imageGroupCount(size[0]),
|
||||
GlesComputeWorkGroup.imageGroupCount(size[1]), 1)
|
||||
val groupsX = GlesComputeWorkGroup.imageGroupCount(size[0])
|
||||
val groupsY = GlesComputeWorkGroup.imageGroupCount(size[1])
|
||||
val offset = location(program, "uGroupOffset")
|
||||
val sliceRows = if (sliceBudgetPixels > 0) {
|
||||
maxOf(1, sliceBudgetPixels / (groupsX * GlesComputeWorkGroup.IMAGE_TILE_SIZE * GlesComputeWorkGroup.IMAGE_TILE_SIZE))
|
||||
} else {
|
||||
groupsY
|
||||
}
|
||||
var row = 0
|
||||
while (row < groupsY) {
|
||||
val rows = minOf(sliceRows, groupsY - row)
|
||||
GLES31.glUniform2i(offset, 0, row)
|
||||
GLES31.glDispatchCompute(groupsX, rows, 1)
|
||||
row += rows
|
||||
if (row < groupsY) GlesGpuScheduler.waitForGpuCheckpoint(TAG, "slice")
|
||||
}
|
||||
GLES31.glUniform2i(offset, 0, 0)
|
||||
GLES31.glMemoryBarrier(
|
||||
GLES31.GL_SHADER_IMAGE_ACCESS_BARRIER_BIT or GLES31.GL_TEXTURE_FETCH_BARRIER_BIT or
|
||||
GLES31.GL_FRAMEBUFFER_BARRIER_BIT,
|
||||
)
|
||||
if (sliceRows < groupsY) GlesGpuScheduler.waitForGpuCheckpoint(TAG, "level")
|
||||
}
|
||||
|
||||
private fun bindImage(unit: Int, texture: Int, format: Int) {
|
||||
@@ -400,12 +424,16 @@ internal class PhotonMultiScaleDenoiser {
|
||||
private fun uniform3f(program: Int, name: String, v: FloatArray) =
|
||||
GLES31.glUniform3f(location(program, name), v[0], v[1], v[2])
|
||||
|
||||
private companion object {
|
||||
const val UNIT_INPUT = 0
|
||||
const val UNIT_LSC = 1
|
||||
const val UNIT_FINE = 2
|
||||
const val UNIT_NOISY_COARSE = 3
|
||||
const val UNIT_DENOISED_COARSE = 4
|
||||
const val UNIT_MERGE = 5
|
||||
companion object {
|
||||
/** [sliceBudgetPixels] for whole-image callers: about 1 MP of work per GPU submission. */
|
||||
const val UI_SLICE_PIXELS = 1 shl 20
|
||||
|
||||
private const val TAG = "PhotonMultiScaleDenoiser"
|
||||
private const val UNIT_INPUT = 0
|
||||
private const val UNIT_LSC = 1
|
||||
private const val UNIT_FINE = 2
|
||||
private const val UNIT_NOISY_COARSE = 3
|
||||
private const val UNIT_DENOISED_COARSE = 4
|
||||
private const val UNIT_MERGE = 5
|
||||
}
|
||||
}
|
||||
@@ -414,8 +414,9 @@ fun GalleryEditScreen(
|
||||
editFrameId = editFrameId,
|
||||
editFrameCustomProperties = editFrameCustomProperties.toMap(),
|
||||
editSharpening = if (rawDevelopIsBaked) 0f else editSharpening,
|
||||
editNoiseReduction = if (fast || rawDevelopIsBaked) 0f else editNoiseReduction,
|
||||
editChromaNoiseReduction = if (fast || rawDevelopIsBaked) 0f else editChromaNoiseReduction,
|
||||
// 降噪烘焙在底图里(RAW 开发 / JPG 降噪基底),松手后通过 refreshKey 刷新。
|
||||
editNoiseReduction = 0f,
|
||||
editChromaNoiseReduction = 0f,
|
||||
editRawExposureCompensation = if (fast || rawDevelopIsBaked) 0f else editRawExposureCompensation,
|
||||
editRawAutoExposure = if (fast || rawDevelopIsBaked) false else editRawAutoExposure,
|
||||
editRawHighlightsAdjustment = if (fast || rawDevelopIsBaked) 0f else editRawHighlightsAdjustment,
|
||||
@@ -545,6 +546,12 @@ fun GalleryEditScreen(
|
||||
cropPreviewBitmap = null
|
||||
}
|
||||
|
||||
// 进入编辑或底图(虚化 / AI 降噪)变化后,按当前强度补齐 JPG 降噪基底;无变化时不会刷新。
|
||||
LaunchedEffect(editSourcePhoto?.id, refreshKey, isRaw) {
|
||||
val photo = editSourcePhoto ?: return@LaunchedEffect
|
||||
if (!isRaw) viewModel.refreshPhotonDenoiseBase(photo)
|
||||
}
|
||||
|
||||
LaunchedEffect(editSourcePhoto?.id, refreshKey) {
|
||||
val photo = editSourcePhoto ?: return@LaunchedEffect
|
||||
if (photo.isVideo) return@LaunchedEffect
|
||||
@@ -1788,6 +1795,8 @@ fun GalleryEditScreen(
|
||||
viewModel.persistCurrentRawEditMetadata(currentEditSourcePhoto) { success ->
|
||||
if (success) requestRawPreviewRefresh()
|
||||
}
|
||||
} else {
|
||||
viewModel.refreshPhotonDenoiseBase(currentEditSourcePhoto)
|
||||
}
|
||||
}
|
||||
)
|
||||
@@ -1802,6 +1811,8 @@ fun GalleryEditScreen(
|
||||
viewModel.persistCurrentRawEditMetadata(currentEditSourcePhoto) { success ->
|
||||
if (success) requestRawPreviewRefresh()
|
||||
}
|
||||
} else {
|
||||
viewModel.refreshPhotonDenoiseBase(currentEditSourcePhoto)
|
||||
}
|
||||
}
|
||||
)
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
package com.hinnka.mycamera.viewmodel
|
||||
|
||||
import android.app.Application
|
||||
import android.content.Context
|
||||
import android.content.Intent
|
||||
import android.graphics.Bitmap
|
||||
import android.graphics.BitmapFactory
|
||||
@@ -3380,6 +3381,47 @@ class GalleryViewModel(application: Application) : AndroidViewModel(application)
|
||||
/**
|
||||
* 清除指定照片的预览缓存
|
||||
*/
|
||||
/** 非 RAW 照片降噪基底的源图:与预览底图同序(虚化 > AI 降噪 > 原图)。 */
|
||||
private fun photonDenoiseSource(context: Context, photoId: String, metadata: MediaMetadata): File? {
|
||||
val bokehFile = GalleryManager.getBokehFile(context, photoId)
|
||||
return when {
|
||||
bokehFile.exists() -> bokehFile
|
||||
metadata.hasAiDenoisedBase -> GalleryManager.getAiDenoiseFile(context, photoId).takeIf { it.exists() }
|
||||
else -> GalleryManager.getOriginalImageFile(context, photoId)
|
||||
}
|
||||
}
|
||||
|
||||
private var photonDenoiseBaseJob: Job? = null
|
||||
|
||||
/**
|
||||
* 按当前编辑强度生成非 RAW 照片的降噪基底(松手、进入编辑、源图变化时调用),
|
||||
* 基底有变化时刷新预览。RAW 照片的降噪在 RAW 开发中烘焙,不走这里。
|
||||
*/
|
||||
fun refreshPhotonDenoiseBase(photo: MediaData) {
|
||||
if (photo.isVideo || isRawInGallery(photo.id)) return
|
||||
val noiseReduction = editNoiseReduction.value
|
||||
val chromaNoiseReduction = editChromaNoiseReduction.value
|
||||
photonDenoiseBaseJob?.cancel()
|
||||
photonDenoiseBaseJob = viewModelScope.launch(Dispatchers.IO) {
|
||||
val context = getApplication<Application>()
|
||||
try {
|
||||
val metadata = currentMediaMetadata ?: photo.metadata ?: MediaMetadata()
|
||||
val source = photonDenoiseSource(context, photo.id, metadata) ?: return@launch
|
||||
val changed = contentRepository.photoProcessor.updatePhotonDenoiseBase(
|
||||
context, photo.id, source, noiseReduction, chromaNoiseReduction,
|
||||
)
|
||||
if (changed) {
|
||||
invalidatePreviewCache(photo.id)
|
||||
photoRefreshKeys[photo.id] = System.currentTimeMillis()
|
||||
}
|
||||
} catch (e: CancellationException) {
|
||||
throw e
|
||||
} catch (e: Exception) {
|
||||
PLog.e(TAG, "Failed to build Photon denoise base", e)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fun invalidatePreviewCache(photoId: String) {
|
||||
val snapshot = previewBitmapCache.snapshot()
|
||||
snapshot.keys.filter { it.startsWith("${photoId}_") }.forEach {
|
||||
@@ -3555,6 +3597,22 @@ class GalleryViewModel(application: Application) : AndroidViewModel(application)
|
||||
val canLoadExternalUri = isSystemExternal || sourceBackedUri != null
|
||||
val externalUri = sourceBackedUri ?: photo.uri
|
||||
val preserveExternalHdr = isSystemExternal && showOrigin && !useGlobalEdit
|
||||
val skipPreviewDenoise = maxEdge < FULL_QUALITY_PREVIEW_MAX_EDGE
|
||||
|
||||
// 非 RAW 照片的降噪基底(同 RAW 烘焙的降噪):编辑中只读取松手时生成的基底,拖动时保持旧结果,
|
||||
// 不在预览渲染里跑降噪;编辑之外按元数据强度惰性生成。
|
||||
val photonDenoiseBase = if (bitmap == null && !showOrigin && !isRawPhoto &&
|
||||
(useGlobalEdit || !skipPreviewDenoise)
|
||||
) {
|
||||
photonDenoiseSource(context, photo.id, finalMetadata)?.let { source ->
|
||||
contentRepository.photoProcessor.loadPhotonDenoiseBase(
|
||||
context, photo.id, source,
|
||||
finalNR.takeUnless { useGlobalEdit }, finalCNR.takeUnless { useGlobalEdit }, maxEdge,
|
||||
)
|
||||
}
|
||||
} else {
|
||||
null
|
||||
}
|
||||
|
||||
// 2. 原始底图缓存(按 maxEdge 加载,快速预览走小尺寸,正式预览走高分辨率)
|
||||
val currentBitmap = bitmap ?: if (showOrigin) {
|
||||
@@ -3566,7 +3624,7 @@ class GalleryViewModel(application: Application) : AndroidViewModel(application)
|
||||
}
|
||||
} else {
|
||||
val bokehFile = GalleryManager.getBokehFile(context, photo.id)
|
||||
when {
|
||||
photonDenoiseBase ?: when {
|
||||
bokehFile.exists() -> GalleryManager.loadBitmap(context, Uri.fromFile(bokehFile), maxEdge)
|
||||
finalMetadata.hasAiDenoisedBase -> GalleryManager.loadBitmap(
|
||||
context,
|
||||
@@ -3585,9 +3643,8 @@ class GalleryViewModel(application: Application) : AndroidViewModel(application)
|
||||
if (showOrigin) {
|
||||
currentBitmap
|
||||
} else {
|
||||
val skipPreviewDenoise = maxEdge < FULL_QUALITY_PREVIEW_MAX_EDGE
|
||||
val applyBitmapSharpening = !isRawPhoto
|
||||
val applyBitmapDenoise = !isRawPhoto && !skipPreviewDenoise
|
||||
val applyBitmapDenoise = !isRawPhoto && !skipPreviewDenoise && !useGlobalEdit && photonDenoiseBase == null
|
||||
val previewMetadata = if (!applyBitmapSharpening || !applyBitmapDenoise) {
|
||||
finalMetadata.copy(
|
||||
sharpening = if (applyBitmapSharpening) finalMetadata.sharpening else 0f,
|
||||
|
||||
Reference in new issue
Block a user