diff --git a/app/src/main/cpp/raw_legacy_auto_exposure_solver.cpp b/app/src/main/cpp/raw_legacy_auto_exposure_solver.cpp index b5d36576..212b817f 100644 --- a/app/src/main/cpp/raw_legacy_auto_exposure_solver.cpp +++ b/app/src/main/cpp/raw_legacy_auto_exposure_solver.cpp @@ -1016,7 +1016,9 @@ public: } const float safe_minimum = std::clamp(minimum_ev, kMinExposureEv, kMaxExposureEv); const float safe_maximum = std::clamp(maximum_ev, kMinExposureEv, kMaxExposureEv); - if (safe_minimum > safe_maximum || safe_minimum > 0.0f || safe_maximum < 0.0f) { + // A RAW highlight guard may require the complete search range to stay below zero. The + // first candidate is still issued from zero and clamped into the configured interval. + if (safe_minimum > safe_maximum) { return false; } minimum_exposure_ev_ = safe_minimum; diff --git a/app/src/main/java/com/hinnka/mycamera/gallery/GalleryManager.kt b/app/src/main/java/com/hinnka/mycamera/gallery/GalleryManager.kt index cedb0c8c..6573acc7 100644 --- a/app/src/main/java/com/hinnka/mycamera/gallery/GalleryManager.kt +++ b/app/src/main/java/com/hinnka/mycamera/gallery/GalleryManager.kt @@ -4549,8 +4549,10 @@ object GalleryManager { useLegacyAutoExposure = metadata.rawAutoExposure ?: true, ) val generatePhotonPgtm = exposureMode.usesPhotonHdr - val legacyMeteringEnabled = exposureMode.usesLegacyAutoExposure && - kotlin.math.abs(metadata.rawExposureCompensation ?: 0f) <= 0.0001f + val scalarViewfinderMatchingEnabled = + exposureMode == RawAdaptiveExposureMode.OFF || + (exposureMode.usesLegacyAutoExposure && + kotlin.math.abs(metadata.rawExposureCompensation ?: 0f) <= 0.0001f) val blackBorderDefaultCrop = RawDefaultCropOverride.resolveRawBlackBorderDefaultCrop( width = width, @@ -4566,7 +4568,7 @@ object GalleryManager { metadataDefaultCrop = blackBorderDefaultCrop ?: defaultCrop, ).takeUnless { it.hasSameBounds(Rect(0, 0, width, height)) } val captureProfileRequired = generatePhotonPgtm || - (legacyMeteringEnabled && capturePreviewThumbnail != null) + (scalarViewfinderMatchingEnabled && capturePreviewThumbnail != null) val captureProfilePreparer = if (captureProfileRequired) { RawDngCaptureProfilePreparer { input -> RawCaptureProfileCoordinator.prepareCaptureProfile( @@ -4602,7 +4604,7 @@ object GalleryManager { "RAW_ADAPTIVE_EXPOSURE stage=DNG_PREPARE mode=$exposureMode " + "curve=DEFAULT blackBorderDefaultCrop=$blackBorderDefaultCrop " + "photonPgtm=$generatePhotonPgtm processingBounds=$statsBounds " + - "legacyMetering=$legacyMeteringEnabled " + + "scalarViewfinderMatching=$scalarViewfinderMatchingEnabled " + "capturePreview=${capturePreviewThumbnail != null} " + "portraitMask=${capturePortraitMask != null} " + "additionalExposureEv=${metadata.rawExposureCompensation ?: 0f}" diff --git a/app/src/main/java/com/hinnka/mycamera/raw/DngBaselineExposure.kt b/app/src/main/java/com/hinnka/mycamera/raw/DngBaselineExposure.kt index 6b10db69..6221d64d 100644 --- a/app/src/main/java/com/hinnka/mycamera/raw/DngBaselineExposure.kt +++ b/app/src/main/java/com/hinnka/mycamera/raw/DngBaselineExposure.kt @@ -17,9 +17,9 @@ object DngBaselineExposure { * Resolves ownership of the BaselineExposure written for a captured RAW. * * [sourceBaselineEv] preserves source-domain normalization such as a multi-frame stack that - * was normalized to its ultra-short frame. The legacy viewfinder matcher returns the display - * exposure offset relative to that source baseline for both classic AE and Photon HDR. Photon - * HDR then uses the written total as its reproducible global-exposure anchor. + * was normalized to its ultra-short frame. The viewfinder matcher returns the display exposure + * offset relative to that source baseline for both the unmapped and Local Tone Mapping paths. + * HDRNet uses the written source baseline as its reproducible global-exposure anchor. */ fun resolveCaptureBaseline( sourceBaselineEv: Float, diff --git a/app/src/main/java/com/hinnka/mycamera/raw/RawAdaptiveExposureMode.kt b/app/src/main/java/com/hinnka/mycamera/raw/RawAdaptiveExposureMode.kt index e9e85bde..3f06ac7e 100644 --- a/app/src/main/java/com/hinnka/mycamera/raw/RawAdaptiveExposureMode.kt +++ b/app/src/main/java/com/hinnka/mycamera/raw/RawAdaptiveExposureMode.kt @@ -3,11 +3,10 @@ package com.hinnka.mycamera.raw /** * The mutually exclusive capture/development modes for adaptive RAW exposure handling. * - * [OFF] leaves both paths disabled. [PHOTON_HDR] runs ML AE plus HDRNet and spatially matches the - * HDRNet result to the complete capture-time viewfinder thumbnail. [LEGACY_AUTO_EXPOSURE] writes - * its scalar viewfinder-matched exposure into BaselineExposure and generates the historical Local - * Laplacian profile gain table. Both enabled modes combine automatic metering with HDR mapping; - * only the target representation and mapping implementation differ. + * All modes preserve capture-time viewfinder brightness through BaselineExposure. [PHOTON_HDR] + * runs ML AE plus HDRNet and spatially matches the HDRNet result to the complete viewfinder. + * [LEGACY_AUTO_EXPOSURE] also generates the historical Local Laplacian profile gain table. [OFF] + * applies no HDR mapping and constrains its scalar viewfinder match with a RAW highlight guard. */ enum class RawAdaptiveExposureMode(val persistedValue: String) { OFF("OFF"), diff --git a/app/src/main/java/com/hinnka/mycamera/raw/RawCaptureProfileCoordinator.kt b/app/src/main/java/com/hinnka/mycamera/raw/RawCaptureProfileCoordinator.kt index 8d0c03a1..798fda49 100644 --- a/app/src/main/java/com/hinnka/mycamera/raw/RawCaptureProfileCoordinator.kt +++ b/app/src/main/java/com/hinnka/mycamera/raw/RawCaptureProfileCoordinator.kt @@ -37,11 +37,14 @@ internal object RawCaptureProfileCoordinator { } else { null } - val legacyRequest = if (mode.usesLegacyAutoExposure || mode.usesPhotonHdr) { - RawLegacyAutoExposureMatcher.createRequest(capturePreviewThumbnail) - } else { - null - } + val legacyRequest = RawLegacyAutoExposureMatcher.createRequest( + capturePreviewThumbnail = capturePreviewThumbnail, + highlightClippingConstraint = if (mode == RawAdaptiveExposureMode.OFF) { + RawLegacyHighlightClippingConstraint.HDR_PLUS_DISABLED + } else { + null + }, + ) return renderer.prepareCaptureProfile( context = context, input = input, diff --git a/app/src/main/java/com/hinnka/mycamera/raw/RawDemosaicProcessor.kt b/app/src/main/java/com/hinnka/mycamera/raw/RawDemosaicProcessor.kt index 14a8ed7c..c950d3ad 100644 --- a/app/src/main/java/com/hinnka/mycamera/raw/RawDemosaicProcessor.kt +++ b/app/src/main/java/com/hinnka/mycamera/raw/RawDemosaicProcessor.kt @@ -1507,6 +1507,7 @@ class RawDemosaicProcessor { private val hdrReferencePass = RawHdrReferencePass(engineTonePass) private val meteringDemosaicAlgorithm = RawMeteringDemosaicAlgorithm() private val fastMomentsStatsAlgorithm = RawAEStatsAlgorithm() + private val legacyHighlightHistogramAlgorithm = RawLegacyHighlightHistogramAlgorithm() private val quadBayerDemosaicAlgorithm = QuadBayerDemosaicAlgorithm() private val vgnDemosaicAlgorithm = VgnDemosaicAlgorithm() private val demosaicNoisePropagationCalibrator = DemosaicNoisePropagationCalibrator( @@ -3096,10 +3097,12 @@ class RawDemosaicProcessor { if (prepareCaptureProfile) { val captureUsesHdrNet = sceneExposureRequest != null - val captureUsesLocalLaplacian = + val captureUsesViewfinderBrightnessMatch = sceneExposureRequest == null && legacyAutoExposureRequest != null + val captureUsesLocalLaplacian = + captureUsesViewfinderBrightnessMatch && capturePhotonPgtmRequested val solvedExposureEv = legacyAutoExposureRequest - ?.takeIf { captureUsesLocalLaplacian } + ?.takeIf { captureUsesViewfinderBrightnessMatch } ?.let { request -> renderLegacyAutoExposureRequest( request = request, @@ -3148,7 +3151,7 @@ class RawDemosaicProcessor { solvedExposureEv?.let { exposureEv -> PLog.i( TAG, - "RAW_LEGACY_AUTO_EXPOSURE stage=METERING_COMPLETE " + + "RAW_VIEWFINDER_BRIGHTNESS_MATCH stage=METERING_COMPLETE " + "sourceBaselineEv=${actualMetadata.baselineExposure} " + "exposureOffsetEv=$exposureEv", ) @@ -3232,7 +3235,8 @@ class RawDemosaicProcessor { "HDRNet PGTM unavailable: complete viewfinder target, ML AE " + "HDR ratio, or final-short gain is missing" } else { - "Local Laplacian PGTM unavailable: legacy AE result is missing" + "Local Laplacian PGTM unavailable: " + + "viewfinder brightness-match result is missing" }, ) } @@ -8378,45 +8382,76 @@ class RawDemosaicProcessor { val readback = LargeDirectBuffer.allocate( (width * height * 4).toLong(), - "Classic RAW auto-exposure readback", + "RAW viewfinder brightness-match readback", ) ?: return null try { - request.solve { exposureEv -> - val clampedExposureEv = exposureEv.coerceIn( - MeteringSystem.RAW_EXPOSURE_MIN_EV, - MeteringSystem.RAW_EXPOSURE_MAX_EV, + val maximumExposureEv = request.highlightClippingConstraint?.let { constraint -> + val highlightBounds = RawLegacyAutoExposureMatcher.centeredHighlightBounds( + outputBounds = outputSourceBounds, + constraint = constraint, + ) ?: return null + val histogram = legacyHighlightHistogramAlgorithm.measure( + linearRawTextureId = sourceTextureId, + imageWidth = metadata.width, + imageHeight = metadata.height, + sourceBounds = highlightBounds, + ) ?: return null + val limit = RawLegacyAutoExposureMatcher.resolveHighlightExposureLimit( + histogram = histogram, + sourceBaselineExposureEv = metadata.baselineExposure, + constraint = constraint, + ) ?: return null + PLog.i( + TAG, + "RAW viewfinder highlight guard: bounds=$highlightBounds " + + "sourceBaselineEv=${metadata.baselineExposure} " + + "maximumExposureOffsetEv=${limit.maximumExposureOffsetEv} " + + "clippedAtLimit=${limit.conservativeClippedPixelCountAtLimit}/" + + "${limit.pixelCount} allowed=${limit.allowedClippedPixelCount} " + + "maximumClippedFraction=${constraint.maximumClippedFraction}", ) - val profileExposureUniforms = computeProfileExposureUniforms( - metadata = metadata, - profileExposureCompensation = clampedExposureEv, - dcpRenderPlan = dcpRenderPlan, - applyDcpBaselineExposureOffset = true, - applyDngBaselineExposure = true, - useRamp = true, - ) - val rendered = renderCombinedPass( - metadata = metadata, - inputTextureId = linearExposurePreviewTextureId, - dcpRenderPlan = dcpRenderPlan, - applyDcpHueSatMap = false, - colorEngine = RawRenderingEngine.AdobeCurve, - outputWorkingColorSpace = RawRenderingEngine.AdobeCurve.workingColorSpace, - profileExposureUniforms = profileExposureUniforms, - shadowsHighlightsParams = ShadowsHighlightsParams.NEUTRAL, - rawBlacksAdjustment = rawBlackPointCorrection, - rawWhitesAdjustment = rawWhitePointCorrection, - rawToneMappingParameters = RawToneMappingParameters.DEFAULT - .withPhotonHdr(false), - applyProfileGainTableMap = false, - viewportWidth = width, - viewportHeight = height, - ) - if (rendered == null) { - null - } else { - readLegacyExposurePreviewFrame(width, height, readback) - } + limit.maximumExposureOffsetEv } + request.solve( + { exposureEv -> + val clampedExposureEv = exposureEv.coerceIn( + MeteringSystem.RAW_EXPOSURE_MIN_EV, + MeteringSystem.RAW_EXPOSURE_MAX_EV, + ) + val profileExposureUniforms = computeProfileExposureUniforms( + metadata = metadata, + profileExposureCompensation = clampedExposureEv, + dcpRenderPlan = dcpRenderPlan, + applyDcpBaselineExposureOffset = true, + applyDngBaselineExposure = true, + useRamp = true, + ) + val rendered = renderCombinedPass( + metadata = metadata, + inputTextureId = linearExposurePreviewTextureId, + dcpRenderPlan = dcpRenderPlan, + applyDcpHueSatMap = false, + colorEngine = RawRenderingEngine.AdobeCurve, + outputWorkingColorSpace = + RawRenderingEngine.AdobeCurve.workingColorSpace, + profileExposureUniforms = profileExposureUniforms, + shadowsHighlightsParams = ShadowsHighlightsParams.NEUTRAL, + rawBlacksAdjustment = rawBlackPointCorrection, + rawWhitesAdjustment = rawWhitePointCorrection, + rawToneMappingParameters = RawToneMappingParameters.DEFAULT + .withPhotonHdr(false), + applyProfileGainTableMap = false, + viewportWidth = width, + viewportHeight = height, + ) + if (rendered == null) { + null + } else { + readLegacyExposurePreviewFrame(width, height, readback) + } + }, + maximumExposureEv, + ) } finally { LargeDirectBuffer.free(readback) } @@ -8785,6 +8820,7 @@ class RawDemosaicProcessor { profileGainTableAlgorithm.release() meteringDemosaicAlgorithm.release() fastMomentsStatsAlgorithm.release() + legacyHighlightHistogramAlgorithm.release() linearRcdPass.release() photonDehazePipeline.release() warpRectilinearPass.release() diff --git a/app/src/main/java/com/hinnka/mycamera/raw/RawDngProfilePreparation.kt b/app/src/main/java/com/hinnka/mycamera/raw/RawDngProfilePreparation.kt index 1ee2e7a4..4757a054 100644 --- a/app/src/main/java/com/hinnka/mycamera/raw/RawDngProfilePreparation.kt +++ b/app/src/main/java/com/hinnka/mycamera/raw/RawDngProfilePreparation.kt @@ -107,7 +107,7 @@ data class GpuDemosaicedRawSource( ) data class RawDngCaptureProfileResult( - /** Legacy auto-exposure EV relative to the source baseline; null for Photon HDR. */ + /** Scalar viewfinder-match EV relative to the source baseline; null for Photon HDR. */ val exposureOffsetEv: Float?, /** Photon HDR long/short TET ratio; always null for classic auto exposure. */ val hdrRatio: Float?, diff --git a/app/src/main/java/com/hinnka/mycamera/raw/RawLegacyAutoExposureMatcher.kt b/app/src/main/java/com/hinnka/mycamera/raw/RawLegacyAutoExposureMatcher.kt index 859ef965..b7a5efa1 100644 --- a/app/src/main/java/com/hinnka/mycamera/raw/RawLegacyAutoExposureMatcher.kt +++ b/app/src/main/java/com/hinnka/mycamera/raw/RawLegacyAutoExposureMatcher.kt @@ -1,8 +1,10 @@ package com.hinnka.mycamera.raw import android.graphics.Bitmap +import android.graphics.Rect import com.hinnka.mycamera.utils.PLog import kotlin.math.abs +import kotlin.math.floor import kotlin.math.max import kotlin.math.pow @@ -17,7 +19,56 @@ internal data class RawLegacyAutoExposureRequest( val height: Int, /** Complete capture-time viewfinder image retained for Photon HDR spatial matching. */ val referenceFrame: RawLegacyExposurePreviewFrame, - val solve: ((Float) -> RawLegacyExposurePreviewFrame?) -> Float?, + val highlightClippingConstraint: RawLegacyHighlightClippingConstraint?, + val solve: ( + renderSample: (Float) -> RawLegacyExposurePreviewFrame?, + maximumExposureEv: Float?, + ) -> Float?, +) + +/** RAW-domain highlight guard used only when HDR+ processing is disabled. */ +internal data class RawLegacyHighlightClippingConstraint( + /** Fraction retained on both axes, centered inside the final RAW output bounds. */ + val centerFractionPerAxis: Float, + /** Maximum fraction of pixels whose brightest linear RAW channel may reach one. */ + val maximumClippedFraction: Float, +) { + init { + require(centerFractionPerAxis.isFinite() && centerFractionPerAxis > 0f && + centerFractionPerAxis <= 1f) + require(maximumClippedFraction.isFinite() && maximumClippedFraction in 0f..1f) + } + + companion object { + val HDR_PLUS_DISABLED = RawLegacyHighlightClippingConstraint( + centerFractionPerAxis = 2f / 3f, + maximumClippedFraction = 0.005f, + ) + } +} + +/** Log2-domain peak-signal histogram produced from the linear RAW texture. */ +internal data class RawLegacyHighlightHistogram( + val counts: LongArray, + val minimumLog2Signal: Float, + val log2SignalStep: Float, + val pixelCount: Long, +) { + init { + require(counts.isNotEmpty()) + require(minimumLog2Signal.isFinite()) + require(log2SignalStep.isFinite() && log2SignalStep > 0f) + require(pixelCount > 0L) + require(counts.all { it >= 0L }) + require(counts.sum() == pixelCount) + } +} + +internal data class RawLegacyHighlightExposureLimit( + val maximumExposureOffsetEv: Float, + val allowedClippedPixelCount: Long, + val conservativeClippedPixelCountAtLimit: Long, + val pixelCount: Long, ) internal data class RawHdrNetExposureEvaluation( @@ -66,6 +117,7 @@ internal object RawLegacyAutoExposureMatcher { fun createRequest( capturePreviewThumbnail: Bitmap?, + highlightClippingConstraint: RawLegacyHighlightClippingConstraint? = null, ): RawLegacyAutoExposureRequest? { val reference = capturePreviewThumbnail?.let(::buildReference) if (capturePreviewThumbnail != null && reference == null) { @@ -76,11 +128,67 @@ internal object RawLegacyAutoExposureMatcher { width = it.frame.width, height = it.frame.height, referenceFrame = it.frame, - solve = { renderSample -> solve(it, renderSample) }, + highlightClippingConstraint = highlightClippingConstraint, + solve = { renderSample, maximumExposureEv -> + solve(it, renderSample, maximumExposureEv) + }, ) } } + fun centeredHighlightBounds( + outputBounds: Rect, + constraint: RawLegacyHighlightClippingConstraint, + ): Rect? { + if (outputBounds.isEmpty) return null + val constrainedWidth = floor( + outputBounds.width().toDouble() * constraint.centerFractionPerAxis.toDouble(), + ).toInt().coerceIn(1, outputBounds.width()) + val constrainedHeight = floor( + outputBounds.height().toDouble() * constraint.centerFractionPerAxis.toDouble(), + ).toInt().coerceIn(1, outputBounds.height()) + val left = outputBounds.left + (outputBounds.width() - constrainedWidth) / 2 + val top = outputBounds.top + (outputBounds.height() - constrainedHeight) / 2 + return Rect(left, top, left + constrainedWidth, top + constrainedHeight) + } + + /** + * Converts a conservative RAW peak histogram quantile into the largest additional EV whose + * total BaselineExposure cannot clip more than the configured pixel fraction. + */ + fun resolveHighlightExposureLimit( + histogram: RawLegacyHighlightHistogram, + sourceBaselineExposureEv: Float, + constraint: RawLegacyHighlightClippingConstraint, + ): RawLegacyHighlightExposureLimit? { + if (!sourceBaselineExposureEv.isFinite()) return null + val allowedClippedPixelCount = floor( + histogram.pixelCount.toDouble() * constraint.maximumClippedFraction.toDouble(), + ).toLong() + var clippedPixelCount = 0L + var thresholdBin = histogram.counts.size + for (bin in histogram.counts.lastIndex downTo 0) { + val countIncludingBin = clippedPixelCount + histogram.counts[bin] + if (countIncludingBin > allowedClippedPixelCount) break + clippedPixelCount = countIncludingBin + thresholdBin = bin + } + // Every value in thresholdBin is treated as clipped. Using its lower edge therefore makes + // the bound conservative even when many samples share the quantile boundary. + val clippingThresholdLog2 = histogram.minimumLog2Signal + + thresholdBin.toFloat() * histogram.log2SignalStep + val maximumTotalExposureEv = -clippingThresholdLog2 + val maximumExposureOffsetEv = + maximumTotalExposureEv - DngBaselineExposure.sanitize(sourceBaselineExposureEv) + if (!maximumExposureOffsetEv.isFinite()) return null + return RawLegacyHighlightExposureLimit( + maximumExposureOffsetEv = maximumExposureOffsetEv, + allowedClippedPixelCount = allowedClippedPixelCount, + conservativeClippedPixelCountAtLimit = clippedPixelCount, + pixelCount = histogram.pixelCount, + ) + } + private fun buildReference(bitmap: Bitmap): ViewfinderReference? { if (bitmap.isRecycled || bitmap.width <= 0 || bitmap.height <= 0) return null return try { @@ -240,16 +348,35 @@ internal object RawLegacyAutoExposureMatcher { private fun solve( reference: ViewfinderReference, renderSample: (Float) -> RawLegacyExposurePreviewFrame?, + maximumExposureEv: Float?, ): Float? { val solver = RawLegacyAutoExposureNativeBridge.Solver.create(reference.frame) ?: run { PLog.w( TAG, - "Classic auto exposure skipped: insufficient reliable non-endpoint cells", + "Viewfinder brightness matching skipped: " + + "insufficient reliable non-endpoint cells", ) return null } return solver.use { + maximumExposureEv?.let { requestedMaximum -> + if (!requestedMaximum.isFinite() || + requestedMaximum < MeteringSystem.RAW_EXPOSURE_MIN_EV || + !solver.configureExposureBounds( + MeteringSystem.RAW_EXPOSURE_MIN_EV, + minOf(requestedMaximum, MeteringSystem.RAW_EXPOSURE_MAX_EV), + ) + ) { + PLog.e( + TAG, + "Viewfinder brightness matching has no feasible highlight-safe range: " + + "maximumExposureEv=$requestedMaximum " + + "minimumExposureEv=${MeteringSystem.RAW_EXPOSURE_MIN_EV}", + ) + return@use null + } + } while (true) { val exposureEv = solver.nextExposureEv() ?: break val frame = renderSample(exposureEv) ?: return@use null @@ -257,7 +384,8 @@ internal object RawLegacyAutoExposureMatcher { solver.lastSample()?.let { sample -> PLog.d( TAG, - "Classic auto exposure sample: exposureEv=${sample.exposureEv} " + + "Viewfinder brightness matching sample: " + + "exposureEv=${sample.exposureEv} " + "matchedCells=${sample.matchedCellCount}/${sample.validCellCount} " + "matchRate=${sample.matchRate} " + "meanAbsoluteLog2Ratio=${sample.meanAbsoluteLog2Ratio} " + @@ -272,7 +400,8 @@ internal object RawLegacyAutoExposureMatcher { val result = solver.result() ?: return@use null PLog.i( TAG, - "Classic auto exposure result: exposureEv=${result.best.exposureEv} " + + "Viewfinder brightness matching result: " + + "exposureEv=${result.best.exposureEv} " + "matchedCells=${result.best.matchedCellCount}/${result.best.validCellCount} " + "matchRate=${result.best.matchRate} " + "meanAbsoluteLog2Ratio=${result.best.meanAbsoluteLog2Ratio} " + diff --git a/app/src/main/java/com/hinnka/mycamera/raw/RawLegacyHighlightHistogramAlgorithm.kt b/app/src/main/java/com/hinnka/mycamera/raw/RawLegacyHighlightHistogramAlgorithm.kt new file mode 100644 index 00000000..26b6b2ae --- /dev/null +++ b/app/src/main/java/com/hinnka/mycamera/raw/RawLegacyHighlightHistogramAlgorithm.kt @@ -0,0 +1,258 @@ +package com.hinnka.mycamera.raw + +import android.graphics.Rect +import android.opengl.GLES30 +import android.opengl.GLES31 +import com.hinnka.mycamera.processor.GlesComputeWorkGroup +import com.hinnka.mycamera.utils.PLog +import java.nio.ByteBuffer +import java.nio.ByteOrder + +/** Measures per-pixel peak signal from the full-resolution linear RAW texture. */ +internal class RawLegacyHighlightHistogramAlgorithm { + private var program = 0 + private var histogramBuffer = 0 + private val zeroHistogram = ByteBuffer.allocateDirect(HISTOGRAM_BUFFER_BYTES) + .order(ByteOrder.nativeOrder()) + + fun measure( + linearRawTextureId: Int, + imageWidth: Int, + imageHeight: Int, + sourceBounds: Rect, + ): RawLegacyHighlightHistogram? { + if (linearRawTextureId == 0 || imageWidth <= 0 || imageHeight <= 0 || + sourceBounds.isEmpty || sourceBounds.left < 0 || sourceBounds.top < 0 || + sourceBounds.right > imageWidth || sourceBounds.bottom > imageHeight + ) { + return null + } + if (!ensureResources()) return null + val pixelCount = sourceBounds.width().toLong() * sourceBounds.height().toLong() + if (pixelCount <= 0L || pixelCount > UINT_MAX) return null + + return try { + resetHistogram() + GLES31.glUseProgram(program) + GLES31.glUniform2i( + GLES31.glGetUniformLocation(program, "uImageSize"), + imageWidth, + imageHeight, + ) + GLES31.glUniform4i( + GLES31.glGetUniformLocation(program, "uSourceBounds"), + sourceBounds.left, + sourceBounds.top, + sourceBounds.right, + sourceBounds.bottom, + ) + GLES31.glBindImageTexture( + LINEAR_RAW_IMAGE_BINDING, + linearRawTextureId, + 0, + false, + 0, + GLES31.GL_READ_ONLY, + GLES30.GL_RGBA16F, + ) + GLES31.glBindBufferBase( + GLES31.GL_SHADER_STORAGE_BUFFER, + HISTOGRAM_BUFFER_BINDING, + histogramBuffer, + ) + // The linear RAW source may come from either framebuffer rendering or imageStore. + // Declare the next image-load consumer explicitly before dispatch. + GLES31.glMemoryBarrier(GLES31.GL_SHADER_IMAGE_ACCESS_BARRIER_BIT) + GLES31.glDispatchCompute( + GlesComputeWorkGroup.imageGroupCount(sourceBounds.width()), + GlesComputeWorkGroup.imageGroupCount(sourceBounds.height()), + 1, + ) + GLES31.glMemoryBarrier( + GLES31.GL_SHADER_STORAGE_BARRIER_BIT or + GLES31.GL_BUFFER_UPDATE_BARRIER_BIT, + ) + RawGlesProgram.logErrors("RAW viewfinder highlight histogram dispatch") + readHistogram(pixelCount) + } catch (error: Throwable) { + PLog.e(TAG, "Failed to measure RAW viewfinder highlight histogram", error) + null + } finally { + GLES31.glBindImageTexture( + LINEAR_RAW_IMAGE_BINDING, + 0, + 0, + false, + 0, + GLES31.GL_READ_ONLY, + GLES30.GL_RGBA16F, + ) + GLES31.glBindBufferBase( + GLES31.GL_SHADER_STORAGE_BUFFER, + HISTOGRAM_BUFFER_BINDING, + 0, + ) + GLES31.glBindBuffer(GLES31.GL_SHADER_STORAGE_BUFFER, 0) + } + } + + fun release() { + if (program != 0) { + GLES31.glDeleteProgram(program) + program = 0 + } + if (histogramBuffer != 0) { + GLES31.glDeleteBuffers(1, intArrayOf(histogramBuffer), 0) + histogramBuffer = 0 + } + } + + private fun ensureResources(): Boolean { + if (program == 0) { + program = RawGlesProgram.compileCompute(SHADER, "RawLegacyHighlightHistogram") + if (program == 0) return false + } + if (histogramBuffer != 0) return true + + val maximumBlockBytes = IntArray(1) + GLES31.glGetIntegerv( + GLES31.GL_MAX_SHADER_STORAGE_BLOCK_SIZE, + maximumBlockBytes, + 0, + ) + if (maximumBlockBytes[0] < HISTOGRAM_BUFFER_BYTES) { + PLog.e( + TAG, + "RAW highlight histogram SSBO unavailable: required=$HISTOGRAM_BUFFER_BYTES " + + "maximum=${maximumBlockBytes[0]}", + ) + return false + } + + val buffers = IntArray(1) + GLES31.glGenBuffers(1, buffers, 0) + histogramBuffer = buffers[0] + if (histogramBuffer == 0) return false + GLES31.glBindBuffer(GLES31.GL_SHADER_STORAGE_BUFFER, histogramBuffer) + zeroHistogram.clear() + GLES31.glBufferData( + GLES31.GL_SHADER_STORAGE_BUFFER, + HISTOGRAM_BUFFER_BYTES, + zeroHistogram, + GLES31.GL_DYNAMIC_READ, + ) + GLES31.glBindBuffer(GLES31.GL_SHADER_STORAGE_BUFFER, 0) + RawGlesProgram.logErrors("RAW viewfinder highlight histogram allocation") + return true + } + + private fun resetHistogram() { + GLES31.glBindBuffer(GLES31.GL_SHADER_STORAGE_BUFFER, histogramBuffer) + zeroHistogram.clear() + GLES31.glBufferSubData( + GLES31.GL_SHADER_STORAGE_BUFFER, + 0, + HISTOGRAM_BUFFER_BYTES, + zeroHistogram, + ) + GLES31.glBindBuffer(GLES31.GL_SHADER_STORAGE_BUFFER, 0) + GLES31.glMemoryBarrier( + GLES31.GL_BUFFER_UPDATE_BARRIER_BIT or + GLES31.GL_SHADER_STORAGE_BARRIER_BIT, + ) + } + + private fun readHistogram(expectedPixelCount: Long): RawLegacyHighlightHistogram? { + GLES31.glBindBuffer(GLES31.GL_SHADER_STORAGE_BUFFER, histogramBuffer) + val mapped = GLES31.glMapBufferRange( + GLES31.GL_SHADER_STORAGE_BUFFER, + 0, + HISTOGRAM_BUFFER_BYTES, + GLES31.GL_MAP_READ_BIT, + ) as? ByteBuffer ?: return null + return try { + mapped.order(ByteOrder.nativeOrder()) + val counts = LongArray(HISTOGRAM_BIN_COUNT) { bin -> + mapped.getInt(bin * Int.SIZE_BYTES).toLong() and UINT_MAX + } + val invalidPixelCount = + mapped.getInt(HISTOGRAM_BIN_COUNT * Int.SIZE_BYTES).toLong() and UINT_MAX + val measuredPixelCount = counts.sum() + if (invalidPixelCount != 0L || measuredPixelCount != expectedPixelCount) { + PLog.e( + TAG, + "Invalid RAW highlight histogram: measured=$measuredPixelCount " + + "expected=$expectedPixelCount invalid=$invalidPixelCount", + ) + return null + } + RawLegacyHighlightHistogram( + counts = counts, + minimumLog2Signal = MINIMUM_LOG2_SIGNAL, + log2SignalStep = LOG2_SIGNAL_STEP, + pixelCount = expectedPixelCount, + ) + } finally { + GLES31.glUnmapBuffer(GLES31.GL_SHADER_STORAGE_BUFFER) + GLES31.glBindBuffer(GLES31.GL_SHADER_STORAGE_BUFFER, 0) + } + } + + companion object { + private const val TAG = "RawLegacyHighlightHistogram" + private const val LINEAR_RAW_IMAGE_BINDING = 0 + private const val HISTOGRAM_BUFFER_BINDING = 0 + private const val HISTOGRAM_BIN_COUNT = 2048 + private const val MINIMUM_LOG2_SIGNAL = -16f + private const val MAXIMUM_LOG2_SIGNAL = 16f + private const val LOG2_SIGNAL_STEP = + (MAXIMUM_LOG2_SIGNAL - MINIMUM_LOG2_SIGNAL) / HISTOGRAM_BIN_COUNT + private const val HISTOGRAM_BUFFER_BYTES = + (HISTOGRAM_BIN_COUNT + 1) * Int.SIZE_BYTES + private const val UINT_MAX = 0xffff_ffffL + + private val SHADER = """ + #version 310 es + precision highp float; + precision highp int; + precision highp image2D; + + layout(local_size_x = 8, local_size_y = 8, local_size_z = 1) in; + layout(rgba16f, binding = 0) readonly uniform highp image2D uLinearRaw; + layout(std430, binding = 0) buffer HighlightHistogram { + uint bins[$HISTOGRAM_BIN_COUNT]; + uint invalidPixelCount; + } histogram; + uniform ivec2 uImageSize; + uniform ivec4 uSourceBounds; + const float MINIMUM_LOG2_SIGNAL = $MINIMUM_LOG2_SIGNAL; + const float MAXIMUM_LOG2_SIGNAL = $MAXIMUM_LOG2_SIGNAL; + + void main() { + ivec2 localPosition = ivec2(gl_GlobalInvocationID.xy); + ivec2 boundsSize = uSourceBounds.zw - uSourceBounds.xy; + if (any(greaterThanEqual(localPosition, boundsSize))) return; + ivec2 position = uSourceBounds.xy + localPosition; + if (any(lessThan(position, ivec2(0))) || + any(greaterThanEqual(position, uImageSize))) return; + + vec3 raw = imageLoad(uLinearRaw, position).rgb; + if (any(isnan(raw)) || any(isinf(raw))) { + atomicAdd(histogram.invalidPixelCount, 1u); + return; + } + float peak = max(max(raw.r, raw.g), max(raw.b, 0.0)); + float log2Signal = peak > 0.0 + ? clamp(log2(peak), MINIMUM_LOG2_SIGNAL, MAXIMUM_LOG2_SIGNAL) + : MINIMUM_LOG2_SIGNAL; + float coordinate = (log2Signal - MINIMUM_LOG2_SIGNAL) / + (MAXIMUM_LOG2_SIGNAL - MINIMUM_LOG2_SIGNAL); + int bin = min( + int(floor(coordinate * float($HISTOGRAM_BIN_COUNT))), + $HISTOGRAM_BIN_COUNT - 1 + ); + atomicAdd(histogram.bins[bin], 1u); + } + """.trimIndent() + } +} diff --git a/app/src/main/java/com/hinnka/mycamera/utils/RawProcessor.kt b/app/src/main/java/com/hinnka/mycamera/utils/RawProcessor.kt index 379da228..0adf126e 100644 --- a/app/src/main/java/com/hinnka/mycamera/utils/RawProcessor.kt +++ b/app/src/main/java/com/hinnka/mycamera/utils/RawProcessor.kt @@ -800,7 +800,7 @@ object RawProcessor { .fromCameraCharacteristics(characteristics), ) ) - val legacyExposureOffsetEv = captureProfile?.exposureOffsetEv + val viewfinderExposureOffsetEv = captureProfile?.exposureOffsetEv ?.takeIf { it.isFinite() } ?.coerceIn( com.hinnka.mycamera.raw.MeteringSystem.RAW_EXPOSURE_MIN_EV, @@ -808,7 +808,7 @@ object RawProcessor { ) val finalBaselineExposureEv = DngBaselineExposure.resolveCaptureBaseline( sourceBaselineEv = sourceBaselineExposureEv, - legacyExposureOffsetEv = legacyExposureOffsetEv, + legacyExposureOffsetEv = viewfinderExposureOffsetEv, ) val profileRequired = options.generatePhotonPgtm if (profileRequired && captureProfile?.profileGainTableMap == null) { @@ -838,12 +838,16 @@ object RawProcessor { TAG, "RAW_SCENE_EXPOSURE stage=SHARED_PROFILE_READY " + "enabled=${options.captureProfilePreparer != null} " + - "legacyAutoExposure=${legacyExposureOffsetEv != null} " + + "viewfinderBrightnessMatch=${viewfinderExposureOffsetEv != null} " + "sourceBaselineEv=$sourceBaselineExposureEv " + "sourceBaselineGain=${DngBaselineExposure.exactGain(sourceBaselineExposureEv)} " + - "legacyExposureOffsetEv=$legacyExposureOffsetEv " + + "viewfinderExposureOffsetEv=$viewfinderExposureOffsetEv " + "baselineExposureSource=" + - "${if (legacyExposureOffsetEv != null) "SOURCE_PLUS_LEGACY_AE" else "SOURCE_METADATA"} " + + "${if (viewfinderExposureOffsetEv != null) { + "SOURCE_PLUS_VIEWFINDER_MATCH" + } else { + "SOURCE_METADATA" + }} " + "finalBaselineEv=${finalProfile.baselineExposureEv} " + "finalBaselineGain=${DngBaselineExposure.exactGain(finalProfile.baselineExposureEv)} " + "pgtm=${finalProfile.profileGainTableMap != null} " + diff --git a/app/src/main/res/values-b+zh+Hant/strings.xml b/app/src/main/res/values-b+zh+Hant/strings.xml index 24760ed0..379bb400 100644 --- a/app/src/main/res/values-b+zh+Hant/strings.xml +++ b/app/src/main/res/values-b+zh+Hant/strings.xml @@ -858,14 +858,14 @@ 預設 內嵌 OPPO 大師 - 光子 HDR + HDRNet模型 在明暗反差較大的場景中保留更多高光與暗部細節,讓畫面亮度過渡更自然。 - 為目前照片啟用光子 HDR。即使拍攝時使用經典自動曝光,也可以重新開啟。 - RAW 自動曝光與 HDR - 兩種模式都會先自動測光確定曝光基準,再以不同方式完成 HDR 映射:光子 HDR 使用 ML AE 與 HDRNet,經典 HDR 使用局部拉普拉斯;關閉時不進行自動測光或 HDR 映射。 + 為目前照片套用 HDRNet模型,保留更多高光與暗部細節。 + HDR+ 算法 + 選擇 HDR+ 處理方式:HDRNet模型或局部色調映射。 關閉 - 光子 HDR - 經典 HDR + HDRNet模型 + 局部色調映射 AgX 白色相對曝光 AgX 黑色相對曝光 AgX 肩部 diff --git a/app/src/main/res/values-zh-rCN/strings.xml b/app/src/main/res/values-zh-rCN/strings.xml index 6c7b22b8..9cad8ee4 100644 --- a/app/src/main/res/values-zh-rCN/strings.xml +++ b/app/src/main/res/values-zh-rCN/strings.xml @@ -876,14 +876,14 @@ 默认 内嵌 OPPO 大师 - 光子 HDR + HDRNet模型 在明暗反差较大的场景中保留更多高光和暗部细节,让画面亮度过渡更自然。 - 为当前照片启用光子 HDR。即使拍摄时使用经典自动曝光,也可以重新开启。 - RAW 自动曝光与 HDR - 两种模式都会先自动测光确定曝光基准,再以不同方式完成 HDR 映射:光子 HDR 使用 ML AE 与 HDRNet,经典 HDR 使用局部拉普拉斯;关闭时不进行自动测光或 HDR 映射。 + 对当前照片应用 HDRNet模型,保留更多高光和暗部细节。 + HDR+ 算法 + 选择 HDR+ 处理方式:HDRNet模型或局部色调映射。 关闭 - 光子 HDR - 经典 HDR + HDRNet模型 + 局部色调映射 AgX 白色相对曝光 AgX 黑色相对曝光 AgX 肩部 diff --git a/app/src/main/res/values-zh-rHK/strings.xml b/app/src/main/res/values-zh-rHK/strings.xml index 585745d1..04cc36af 100644 --- a/app/src/main/res/values-zh-rHK/strings.xml +++ b/app/src/main/res/values-zh-rHK/strings.xml @@ -858,14 +858,14 @@ 預設 內嵌 OPPO 大師 - 光子 HDR + HDRNet模型 在明暗反差較大的場景中保留更多高光與暗部細節,讓畫面亮度過渡更自然。 - 為目前照片啟用光子 HDR。即使拍攝時使用經典自動曝光,也可以重新開啟。 - RAW 自動曝光與 HDR - 兩種模式都會先自動測光確定曝光基準,再以不同方式完成 HDR 映射:光子 HDR 使用 ML AE 與 HDRNet,經典 HDR 使用局部拉普拉斯;關閉時不進行自動測光或 HDR 映射。 + 為目前照片套用 HDRNet模型,保留更多高光與暗部細節。 + HDR+ 算法 + 選擇 HDR+ 處理方式:HDRNet模型或局部色調映射。 關閉 - 光子 HDR - 經典 HDR + HDRNet模型 + 局部色調映射 AgX 白色相對曝光 AgX 黑色相對曝光 AgX 肩部 diff --git a/app/src/main/res/values-zh-rTW/strings.xml b/app/src/main/res/values-zh-rTW/strings.xml index 5e81b285..8582e55a 100644 --- a/app/src/main/res/values-zh-rTW/strings.xml +++ b/app/src/main/res/values-zh-rTW/strings.xml @@ -858,14 +858,14 @@ 預設 內嵌 OPPO 大師 - 光子 HDR + HDRNet模型 在明暗反差較大的場景中保留更多高光與暗部細節,讓畫面亮度過渡更自然。 - 為目前照片啟用光子 HDR。即使拍攝時使用經典自動曝光,也可以重新開啟。 - RAW 自動曝光與 HDR - 兩種模式都會先自動測光確定曝光基準,再以不同方式完成 HDR 映射:光子 HDR 使用 ML AE 與 HDRNet,經典 HDR 使用局部拉普拉斯;關閉時不進行自動測光或 HDR 映射。 + 為目前照片套用 HDRNet模型,保留更多高光與暗部細節。 + HDR+ 算法 + 選擇 HDR+ 處理方式:HDRNet模型或局部色調映射。 關閉 - 光子 HDR - 經典 HDR + HDRNet模型 + 局部色調映射 AgX 白色相對曝光 AgX 黑色相對曝光 AgX 肩部 diff --git a/app/src/main/res/values/strings.xml b/app/src/main/res/values/strings.xml index f3f9b564..71c4a64c 100644 --- a/app/src/main/res/values/strings.xml +++ b/app/src/main/res/values/strings.xml @@ -862,14 +862,14 @@ Default Embedded OPPO Master - Photon HDR + HDRNet Model Preserves more highlight and shadow detail in high-contrast scenes for more natural tonal transitions. - Enable Photon HDR for this photo. It can also be enabled for photos captured with Classic Auto Exposure. - RAW Auto Exposure & HDR - Both modes meter the scene to establish an exposure baseline, then apply different HDR mapping: Photon HDR uses ML AE with HDRNet, while Classic HDR uses Local Laplacian mapping. Off disables automatic metering and HDR mapping. + Apply the HDRNet model to this photo to preserve more highlight and shadow detail. + HDR+ Algorithm + Choose an HDR+ processing method: HDRNet Model or Local Tone Mapping. Off - Photon HDR - Classic HDR + HDRNet Model + Local Tone Mapping AgX White Relative Exposure AgX Black Relative Exposure AgX Shoulder