feat: HDR+ optimize
This commit is contained in:
1 parent
9cf16a6bf7
commit
a1263d7afc
13 files changed
+1238
-319
No files matched your search
@@ -25,6 +25,28 @@ struct AxisSample {
|
||||
float amount;
|
||||
};
|
||||
|
||||
struct NormalizedImagePoint {
|
||||
float u;
|
||||
float v;
|
||||
};
|
||||
|
||||
// Shared RAW/Bitmap contract: row zero is the image top, and positive rotation is clockwise.
|
||||
// Returns the source point sampled by one point in the rotated output image.
|
||||
NormalizedImagePoint MapTopLeftOutputToSource(float output_u,
|
||||
float output_v,
|
||||
int clockwise_rotation) {
|
||||
if (clockwise_rotation == 90) {
|
||||
return {output_v, 1.0f - output_u};
|
||||
}
|
||||
if (clockwise_rotation == 180) {
|
||||
return {1.0f - output_u, 1.0f - output_v};
|
||||
}
|
||||
if (clockwise_rotation == 270) {
|
||||
return {1.0f - output_v, output_u};
|
||||
}
|
||||
return {output_u, output_v};
|
||||
}
|
||||
|
||||
class ScopedFloatArray {
|
||||
public:
|
||||
ScopedFloatArray(JNIEnv* env, jfloatArray array)
|
||||
@@ -288,19 +310,12 @@ Java_com_hinnka_mycamera_raw_DngHdrNetProfileGainTableNative_nativeEvaluateDispl
|
||||
const float output_u =
|
||||
(grid_x + (sample_x + 0.5f) / footprint_samples_per_axis) /
|
||||
output_grid_width;
|
||||
const float gl_v = 1.0f - output_v_top;
|
||||
float source_u = output_u;
|
||||
float source_v = gl_v;
|
||||
if (output_rotation == 90) {
|
||||
source_u = gl_v;
|
||||
source_v = 1.0f - output_u;
|
||||
} else if (output_rotation == 180) {
|
||||
source_u = 1.0f - output_u;
|
||||
source_v = 1.0f - gl_v;
|
||||
} else if (output_rotation == 270) {
|
||||
source_u = 1.0f - gl_v;
|
||||
source_v = output_u;
|
||||
}
|
||||
// HDRNet now samples the same top-left/clockwise coordinates as the RAW render and the
|
||||
// already-rotated Android Bitmap used as the viewfinder reference.
|
||||
const NormalizedImagePoint source = MapTopLeftOutputToSource(
|
||||
output_u, output_v_top, output_rotation);
|
||||
const float source_u = source.u;
|
||||
const float source_v = source.v;
|
||||
|
||||
const AxisSample input_x =
|
||||
MakeNormalizedAxisSample(source_u, input_width);
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
@@ -2378,6 +2378,11 @@ object GalleryManager {
|
||||
rotation = rotation,
|
||||
capturePreviewThumbnail = dngThumbnail,
|
||||
capturePortraitMask = capturePortraitMask,
|
||||
viewfinderMirroredHorizontally = characteristics.get(
|
||||
CameraCharacteristics.LENS_FACING,
|
||||
) == CameraCharacteristics.LENS_FACING_FRONT,
|
||||
viewfinderPreviewToCaptureRotationDegrees =
|
||||
viewfinderPreviewToCaptureRotationDegrees(rotation, characteristics),
|
||||
)
|
||||
val preparedProfile = RawProcessor.prepareRawDngProfile(
|
||||
rawBuffer = rawBuffer,
|
||||
@@ -3673,6 +3678,11 @@ object GalleryManager {
|
||||
rotation = rotation,
|
||||
capturePreviewThumbnail = capturePreviewThumbnail,
|
||||
capturePortraitMask = capturePortraitMask,
|
||||
viewfinderMirroredHorizontally = characteristics.get(
|
||||
CameraCharacteristics.LENS_FACING,
|
||||
) == CameraCharacteristics.LENS_FACING_FRONT,
|
||||
viewfinderPreviewToCaptureRotationDegrees =
|
||||
viewfinderPreviewToCaptureRotationDegrees(rotation, characteristics),
|
||||
)
|
||||
val profileStartMs = System.currentTimeMillis()
|
||||
val dngProfilePreparation = RawProcessor.prepareRawDngProfile(
|
||||
@@ -4367,6 +4377,14 @@ object GalleryManager {
|
||||
aspectRatio = aspectRatio,
|
||||
rotation = rotation,
|
||||
capturePreviewThumbnail = capturePreviewThumbnail,
|
||||
viewfinderMirroredHorizontally = characteristics.get(
|
||||
CameraCharacteristics.LENS_FACING,
|
||||
) == CameraCharacteristics.LENS_FACING_FRONT,
|
||||
viewfinderPreviewToCaptureRotationDegrees =
|
||||
viewfinderPreviewToCaptureRotationDegrees(
|
||||
rotation,
|
||||
characteristics,
|
||||
),
|
||||
),
|
||||
// Serialize the resolved Camera2/ISZ crop through the standard DNG tags.
|
||||
defaultCrop = writtenRawDngDefaultCrop,
|
||||
@@ -4542,6 +4560,8 @@ object GalleryManager {
|
||||
aspectRatio: AspectRatio?,
|
||||
rotation: Int,
|
||||
capturePreviewThumbnail: Bitmap?,
|
||||
viewfinderMirroredHorizontally: Boolean,
|
||||
viewfinderPreviewToCaptureRotationDegrees: Int,
|
||||
capturePortraitMask: PortraitMaskSnapshot? = null,
|
||||
): RawDngProfilePreparationOptions {
|
||||
val exposureMode = RawAdaptiveExposureMode.resolve(
|
||||
@@ -4581,6 +4601,9 @@ object GalleryManager {
|
||||
rotation = rotation,
|
||||
capturePreviewThumbnail = capturePreviewThumbnail,
|
||||
capturePortraitMask = capturePortraitMask,
|
||||
viewfinderMirroredHorizontally = viewfinderMirroredHorizontally,
|
||||
viewfinderPreviewToCaptureRotationDegrees =
|
||||
viewfinderPreviewToCaptureRotationDegrees,
|
||||
statsBounds = statsBounds,
|
||||
rawBlackPointCorrection = metadata.rawBlackPointCorrection ?: 0f,
|
||||
rawWhitePointCorrection = metadata.rawWhitePointCorrection ?: 0f,
|
||||
@@ -4697,6 +4720,19 @@ object GalleryManager {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* The captured preview bitmap is rotated from the already display-oriented preview, while
|
||||
* [rotation] also contains the sensor orientation. Removing that sensor component recovers
|
||||
* the exact clockwise rotation applied by CameraViewModel to the matching thumbnail.
|
||||
*/
|
||||
private fun viewfinderPreviewToCaptureRotationDegrees(
|
||||
rotation: Int,
|
||||
characteristics: CameraCharacteristics,
|
||||
): Int = Math.floorMod(
|
||||
rotation - (characteristics.get(CameraCharacteristics.SENSOR_ORIENTATION) ?: 0),
|
||||
360,
|
||||
)
|
||||
|
||||
suspend fun saveBitmapBurstPhoto(
|
||||
context: Context,
|
||||
photoId: String,
|
||||
|
||||
@@ -23,11 +23,14 @@ data class PortraitMaskSnapshot(
|
||||
val cameraId: String? = null,
|
||||
val sensorOrientationDegrees: Int = 0,
|
||||
val isFrontFacing: Boolean = false,
|
||||
/** Clockwise rotation applied to the original preview bitmap used for RAW matching. */
|
||||
val previewToCaptureRotationDegrees: Int = 0,
|
||||
) {
|
||||
init {
|
||||
require(width > 0 && height > 0)
|
||||
require(confidence.size == width * height)
|
||||
require(confidence.all { it.isFinite() && it in 0f..1f })
|
||||
require(sampleElapsedRealtimeNanos > 0L)
|
||||
require(Math.floorMod(previewToCaptureRotationDegrees, 90) == 0)
|
||||
}
|
||||
}
|
||||
@@ -1822,15 +1822,15 @@ internal class DngPhotonProfileGainTableAlgorithm {
|
||||
"mapInputDomain=RAW_X_FINAL_SHORT_GAIN " +
|
||||
"pgtmBaselineCancelledFromInputCoordinate=true " +
|
||||
"exposureSolve=${exposureResult != null} " +
|
||||
"exposureMetric=NATIVE_PAIRED_P20_P50_P80_CURVE_FIT " +
|
||||
"exposureMetric=PERCEPTUAL_LSTAR_GRID_MATCH_RATE " +
|
||||
"exposureCandidateDomain=DISPLAY_LINEAR_REC709_LUMA_GRID " +
|
||||
"exposureReferenceDomain=DISPLAY_LINEAR_REC709_LUMA_GRID " +
|
||||
"exposureSpatialWeight=CLASSIC_REFERENCE_ENDPOINT_RELIABILITY " +
|
||||
"exposureTarget=FULL_CAPTURE_VIEWFINDER_THUMBNAIL " +
|
||||
"exposureReferenceAvailable=${input.viewfinderReference != null} " +
|
||||
"exposureOutputRotation=${input.outputRotation} " +
|
||||
"exposureAdjustmentMode=DAMPED_NEWTON_SHORT_AND_HDR_RATIO_EV " +
|
||||
"exposureConvergenceCondition=P50_AND_P20_P80_SPAN_WITH_HUBER_GUARD " +
|
||||
"exposureAdjustmentMode=HIGHLIGHT_SHORT_SHADOW_LONG_GRID_GUIDED " +
|
||||
"exposureConvergenceCondition=GRID_MATCH_RATE_ONLY " +
|
||||
"exposureBaseShortGain=$baseShortGain " +
|
||||
"exposureBaseLongGain=$baseLongGain " +
|
||||
"exposureBaseHdrRatio=${basePlan.hdrRatio} " +
|
||||
@@ -1849,11 +1849,27 @@ internal class DngPhotonProfileGainTableAlgorithm {
|
||||
"${exposureResult?.evaluation?.curveSlopeError} " +
|
||||
"exposureReferenceSpanEv=" +
|
||||
"${exposureResult?.evaluation?.referenceSpanEv} " +
|
||||
"exposureHighlightTargetErrorEv=" +
|
||||
"${exposureResult?.evaluation?.highlightTargetErrorEv} " +
|
||||
"exposureShadowTargetErrorEv=" +
|
||||
"${exposureResult?.evaluation?.shadowTargetErrorEv} " +
|
||||
"exposureShortTargetCorrectionEv=" +
|
||||
"${exposureResult?.evaluation?.shortTargetCorrectionEv} " +
|
||||
"exposureLongTargetCorrectionEv=" +
|
||||
"${exposureResult?.evaluation?.longTargetCorrectionEv} " +
|
||||
"exposureRobustLog2Loss=" +
|
||||
"${exposureResult?.evaluation?.robustLog2Loss} " +
|
||||
"exposureMeanAbsoluteLog2Ratio=" +
|
||||
"${exposureResult?.evaluation?.meanAbsoluteLog2Ratio} " +
|
||||
"exposureMeanPerceptualLightnessError=" +
|
||||
"${exposureResult?.evaluation?.meanAbsolutePerceptualLightnessError} " +
|
||||
"exposureMatchRate=${exposureResult?.evaluation?.matchRate} " +
|
||||
"exposureCoordinateEdges=" +
|
||||
"${exposureResult?.evaluation?.coordinateComparedEdgeCount} " +
|
||||
"exposureCoordinateMatchRate=" +
|
||||
"${exposureResult?.evaluation?.coordinateMatchRate} " +
|
||||
"exposureCoordinatesMatched=" +
|
||||
"${exposureResult?.evaluation?.coordinatesMatched} " +
|
||||
"exposureRecommendedCorrectionEv=" +
|
||||
"${exposureResult?.evaluation?.recommendedExposureCorrectionEv} " +
|
||||
"exposureConverged=${exposureResult?.evaluation?.converged} " +
|
||||
|
||||
@@ -19,6 +19,8 @@ internal object RawCaptureProfileCoordinator {
|
||||
rotation: Int,
|
||||
capturePreviewThumbnail: Bitmap?,
|
||||
capturePortraitMask: PortraitMaskSnapshot?,
|
||||
viewfinderMirroredHorizontally: Boolean,
|
||||
viewfinderPreviewToCaptureRotationDegrees: Int,
|
||||
statsBounds: Rect?,
|
||||
rawBlackPointCorrection: Float = 0f,
|
||||
rawWhitePointCorrection: Float = 0f,
|
||||
@@ -39,6 +41,15 @@ internal object RawCaptureProfileCoordinator {
|
||||
}
|
||||
val legacyRequest = RawLegacyAutoExposureMatcher.createRequest(
|
||||
capturePreviewThumbnail = capturePreviewThumbnail,
|
||||
capturePortraitMask = capturePortraitMask,
|
||||
viewfinderMirroredHorizontally = viewfinderMirroredHorizontally,
|
||||
viewfinderPreviewToCaptureRotationDegrees =
|
||||
viewfinderPreviewToCaptureRotationDegrees,
|
||||
scalarMatchingCenterFractionPerAxis = if (mode.usesPhotonHdr) {
|
||||
1f
|
||||
} else {
|
||||
RawLegacyAutoExposureMatcher.SCALAR_MATCH_CENTER_FRACTION_PER_AXIS
|
||||
},
|
||||
highlightClippingConstraint = if (mode == RawAdaptiveExposureMode.OFF) {
|
||||
RawLegacyHighlightClippingConstraint.HDR_PLUS_DISABLED
|
||||
} else {
|
||||
|
||||
@@ -3292,11 +3292,43 @@ class RawDemosaicProcessor {
|
||||
"hdrNetExposureMeanAbsoluteLog2Ratio=" +
|
||||
evaluation.meanAbsoluteLog2Ratio,
|
||||
)
|
||||
appendLine(
|
||||
"hdrNetExposureMeanPerceptualLightnessError=" +
|
||||
evaluation.meanAbsolutePerceptualLightnessError,
|
||||
)
|
||||
appendLine("hdrNetExposureMatchRate=${evaluation.matchRate}")
|
||||
appendLine(
|
||||
"hdrNetExposureCoordinateEdges=" +
|
||||
evaluation.coordinateComparedEdgeCount,
|
||||
)
|
||||
appendLine(
|
||||
"hdrNetExposureCoordinateMatchRate=" +
|
||||
evaluation.coordinateMatchRate,
|
||||
)
|
||||
appendLine(
|
||||
"hdrNetExposureCoordinatesMatched=" +
|
||||
evaluation.coordinatesMatched,
|
||||
)
|
||||
appendLine(
|
||||
"hdrNetExposureRecommendedCorrectionEv=" +
|
||||
evaluation.recommendedExposureCorrectionEv,
|
||||
)
|
||||
appendLine(
|
||||
"hdrNetExposureHighlightTargetErrorEv=" +
|
||||
evaluation.highlightTargetErrorEv,
|
||||
)
|
||||
appendLine(
|
||||
"hdrNetExposureShadowTargetErrorEv=" +
|
||||
evaluation.shadowTargetErrorEv,
|
||||
)
|
||||
appendLine(
|
||||
"hdrNetExposureShortTargetCorrectionEv=" +
|
||||
evaluation.shortTargetCorrectionEv,
|
||||
)
|
||||
appendLine(
|
||||
"hdrNetExposureLongTargetCorrectionEv=" +
|
||||
evaluation.longTargetCorrectionEv,
|
||||
)
|
||||
appendLine("hdrNetExposureConverged=${evaluation.converged}")
|
||||
appendLine(
|
||||
"hdrNetExposureFallback1d=" +
|
||||
@@ -8345,11 +8377,15 @@ class RawDemosaicProcessor {
|
||||
val height = request.height.coerceAtLeast(1)
|
||||
return try {
|
||||
setupLinearExposurePreviewFramebuffer(width, height)
|
||||
val matchingSourceBounds = RawLegacyAutoExposureMatcher.centeredBounds(
|
||||
outputBounds = outputSourceBounds,
|
||||
centerFractionPerAxis = request.scalarMatchingCenterFractionPerAxis,
|
||||
) ?: return null
|
||||
val normalizedBounds = floatArrayOf(
|
||||
outputSourceBounds.left.toFloat() / metadata.width.toFloat(),
|
||||
outputSourceBounds.top.toFloat() / metadata.height.toFloat(),
|
||||
outputSourceBounds.right.toFloat() / metadata.width.toFloat(),
|
||||
outputSourceBounds.bottom.toFloat() / metadata.height.toFloat(),
|
||||
matchingSourceBounds.left.toFloat() / metadata.width.toFloat(),
|
||||
matchingSourceBounds.top.toFloat() / metadata.height.toFloat(),
|
||||
matchingSourceBounds.right.toFloat() / metadata.width.toFloat(),
|
||||
matchingSourceBounds.bottom.toFloat() / metadata.height.toFloat(),
|
||||
)
|
||||
val areaSampleFootprint = floatArrayOf(
|
||||
(normalizedBounds[2] - normalizedBounds[0]) / width.toFloat(),
|
||||
@@ -8373,7 +8409,7 @@ class RawDemosaicProcessor {
|
||||
textureBounds = normalizedBounds,
|
||||
areaSampleFootprint = areaSampleFootprint,
|
||||
textureRotation = outputRotation,
|
||||
label = "RawLegacyAutoExposureLinearPass",
|
||||
label = "RawViewfinderBrightnessMatchLinearPass",
|
||||
)
|
||||
GLES30.glBindFramebuffer(GLES30.GL_FRAMEBUFFER, 0)
|
||||
GLES31.glMemoryBarrier(
|
||||
|
||||
@@ -2,6 +2,7 @@ package com.hinnka.mycamera.raw
|
||||
|
||||
import android.graphics.Bitmap
|
||||
import android.graphics.Rect
|
||||
import com.hinnka.mycamera.preview.PortraitMaskSnapshot
|
||||
import com.hinnka.mycamera.utils.PLog
|
||||
import kotlin.math.abs
|
||||
import kotlin.math.floor
|
||||
@@ -12,6 +13,8 @@ internal data class RawLegacyExposurePreviewFrame(
|
||||
val width: Int,
|
||||
val height: Int,
|
||||
val argbPixels: IntArray,
|
||||
/** Optional per-pixel soft portrait target aligned exactly with [argbPixels]. */
|
||||
val portraitPriorityWeights: FloatArray? = null,
|
||||
)
|
||||
|
||||
internal data class RawLegacyAutoExposureRequest(
|
||||
@@ -19,6 +22,8 @@ internal data class RawLegacyAutoExposureRequest(
|
||||
val height: Int,
|
||||
/** Complete capture-time viewfinder image retained for Photon HDR spatial matching. */
|
||||
val referenceFrame: RawLegacyExposurePreviewFrame,
|
||||
/** Center fraction used by the scalar viewfinder matcher on both axes. */
|
||||
val scalarMatchingCenterFractionPerAxis: Float,
|
||||
val highlightClippingConstraint: RawLegacyHighlightClippingConstraint?,
|
||||
val solve: (
|
||||
renderSample: (Float) -> RawLegacyExposurePreviewFrame?,
|
||||
@@ -76,10 +81,18 @@ internal data class RawHdrNetExposureEvaluation(
|
||||
val spanErrorEv: Float,
|
||||
val curveSlopeError: Float,
|
||||
val referenceSpanEv: Float,
|
||||
val highlightTargetErrorEv: Float,
|
||||
val shadowTargetErrorEv: Float,
|
||||
val shortTargetCorrectionEv: Float,
|
||||
val longTargetCorrectionEv: Float,
|
||||
val medianLog2Ratio: Float,
|
||||
val robustLog2Loss: Float,
|
||||
val meanAbsoluteLog2Ratio: Float,
|
||||
val meanAbsolutePerceptualLightnessError: Float,
|
||||
val matchRate: Float,
|
||||
val coordinateComparedEdgeCount: Int,
|
||||
val coordinateMatchRate: Float,
|
||||
val coordinatesMatched: Boolean?,
|
||||
val recommendedExposureCorrectionEv: Float,
|
||||
val evaluatedCandidateCount: Int,
|
||||
val converged: Boolean,
|
||||
@@ -102,11 +115,18 @@ internal data class RawHdrNetExposureCandidate<T>(
|
||||
internal object RawLegacyAutoExposureMatcher {
|
||||
private const val TAG = "RawLegacyAutoExposureMatcher"
|
||||
private const val PREVIEW_LONG_EDGE = 256
|
||||
private const val PORTRAIT_PRIORITY_MINIMUM_AREA_FRACTION = 0.045f
|
||||
const val SCALAR_MATCH_CENTER_FRACTION_PER_AXIS = 2f / 3f
|
||||
|
||||
private data class ViewfinderReference(
|
||||
val frame: RawLegacyExposurePreviewFrame,
|
||||
)
|
||||
|
||||
private data class PortraitPrioritySource(
|
||||
val snapshot: PortraitMaskSnapshot,
|
||||
val areaFraction: Float,
|
||||
)
|
||||
|
||||
private data class HdrNetInference<T>(
|
||||
val shortEv: Float,
|
||||
val hdrRatioEv: Float,
|
||||
@@ -117,41 +137,120 @@ internal object RawLegacyAutoExposureMatcher {
|
||||
|
||||
fun createRequest(
|
||||
capturePreviewThumbnail: Bitmap?,
|
||||
capturePortraitMask: PortraitMaskSnapshot? = null,
|
||||
viewfinderMirroredHorizontally: Boolean = false,
|
||||
viewfinderPreviewToCaptureRotationDegrees: Int = 0,
|
||||
scalarMatchingCenterFractionPerAxis: Float = 1f,
|
||||
highlightClippingConstraint: RawLegacyHighlightClippingConstraint? = null,
|
||||
): RawLegacyAutoExposureRequest? {
|
||||
val reference = capturePreviewThumbnail?.let(::buildReference)
|
||||
if (capturePreviewThumbnail != null && reference == null) {
|
||||
if (!scalarMatchingCenterFractionPerAxis.isFinite() ||
|
||||
scalarMatchingCenterFractionPerAxis <= 0f ||
|
||||
scalarMatchingCenterFractionPerAxis > 1f
|
||||
) {
|
||||
return null
|
||||
}
|
||||
val normalizedViewfinderRotation = Math.floorMod(
|
||||
viewfinderPreviewToCaptureRotationDegrees,
|
||||
360,
|
||||
)
|
||||
if (viewfinderMirroredHorizontally &&
|
||||
normalizedViewfinderRotation != 0 && normalizedViewfinderRotation != 90 &&
|
||||
normalizedViewfinderRotation != 180 && normalizedViewfinderRotation != 270
|
||||
) {
|
||||
PLog.w(
|
||||
TAG,
|
||||
"Viewfinder matching skipped: unsupported mirrored preview rotation=" +
|
||||
normalizedViewfinderRotation,
|
||||
)
|
||||
return null
|
||||
}
|
||||
val bitmap = capturePreviewThumbnail ?: return null
|
||||
val portraitPriority = resolvePortraitPriority(
|
||||
snapshot = capturePortraitMask,
|
||||
expectedRotationDegrees = normalizedViewfinderRotation,
|
||||
)
|
||||
val detectedPortraitAreaFraction = portraitPriority?.areaFraction
|
||||
?: capturePortraitMask?.let(::portraitAreaFraction)
|
||||
// A portrait outside the historical center crop still has to be observable by the scalar
|
||||
// solver. The RAW highlight guard remains independently constrained to its center region.
|
||||
val effectiveScalarCenterFraction = if (portraitPriority != null) {
|
||||
1f
|
||||
} else {
|
||||
scalarMatchingCenterFractionPerAxis
|
||||
}
|
||||
PLog.i(
|
||||
TAG,
|
||||
"Viewfinder portrait target: available=${capturePortraitMask != null} " +
|
||||
"areaFraction=$detectedPortraitAreaFraction " +
|
||||
"minimumAreaFraction=$PORTRAIT_PRIORITY_MINIMUM_AREA_FRACTION " +
|
||||
"active=${portraitPriority != null} " +
|
||||
"previewToCaptureRotation=" +
|
||||
"$normalizedViewfinderRotation " +
|
||||
"portraitMaskRotation=${capturePortraitMask?.previewToCaptureRotationDegrees} " +
|
||||
"viewfinderMirroredHorizontally=$viewfinderMirroredHorizontally " +
|
||||
"scalarCenterFraction=$effectiveScalarCenterFraction",
|
||||
)
|
||||
val completeReference = buildReference(
|
||||
bitmap = bitmap,
|
||||
portraitPriority = portraitPriority,
|
||||
mirrorHorizontally = viewfinderMirroredHorizontally,
|
||||
previewToCaptureRotationDegrees = normalizedViewfinderRotation,
|
||||
)
|
||||
val scalarReference = when {
|
||||
completeReference == null -> null
|
||||
effectiveScalarCenterFraction >= 1f -> completeReference
|
||||
else -> buildReference(
|
||||
bitmap = bitmap,
|
||||
centerFractionPerAxis = effectiveScalarCenterFraction,
|
||||
portraitPriority = portraitPriority,
|
||||
mirrorHorizontally = viewfinderMirroredHorizontally,
|
||||
previewToCaptureRotationDegrees = normalizedViewfinderRotation,
|
||||
)
|
||||
}
|
||||
if (completeReference == null || scalarReference == null) {
|
||||
PLog.w(TAG, "Viewfinder matching skipped: capture preview is unavailable")
|
||||
}
|
||||
return reference?.let {
|
||||
return completeReference?.let { complete ->
|
||||
val scalar = scalarReference ?: return@let null
|
||||
RawLegacyAutoExposureRequest(
|
||||
width = it.frame.width,
|
||||
height = it.frame.height,
|
||||
referenceFrame = it.frame,
|
||||
width = scalar.frame.width,
|
||||
height = scalar.frame.height,
|
||||
referenceFrame = complete.frame,
|
||||
scalarMatchingCenterFractionPerAxis =
|
||||
effectiveScalarCenterFraction,
|
||||
highlightClippingConstraint = highlightClippingConstraint,
|
||||
solve = { renderSample, maximumExposureEv ->
|
||||
solve(it, renderSample, maximumExposureEv)
|
||||
solve(scalar, renderSample, maximumExposureEv)
|
||||
},
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
fun centeredHighlightBounds(
|
||||
fun centeredBounds(
|
||||
outputBounds: Rect,
|
||||
constraint: RawLegacyHighlightClippingConstraint,
|
||||
centerFractionPerAxis: Float,
|
||||
): Rect? {
|
||||
if (outputBounds.isEmpty) return null
|
||||
if (outputBounds.isEmpty || !centerFractionPerAxis.isFinite() ||
|
||||
centerFractionPerAxis <= 0f || centerFractionPerAxis > 1f
|
||||
) {
|
||||
return null
|
||||
}
|
||||
val constrainedWidth = floor(
|
||||
outputBounds.width().toDouble() * constraint.centerFractionPerAxis.toDouble(),
|
||||
outputBounds.width().toDouble() * centerFractionPerAxis.toDouble(),
|
||||
).toInt().coerceIn(1, outputBounds.width())
|
||||
val constrainedHeight = floor(
|
||||
outputBounds.height().toDouble() * constraint.centerFractionPerAxis.toDouble(),
|
||||
outputBounds.height().toDouble() * 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)
|
||||
}
|
||||
|
||||
fun centeredHighlightBounds(
|
||||
outputBounds: Rect,
|
||||
constraint: RawLegacyHighlightClippingConstraint,
|
||||
): Rect? = centeredBounds(outputBounds, constraint.centerFractionPerAxis)
|
||||
|
||||
/**
|
||||
* Converts a conservative RAW peak histogram quantile into the largest additional EV whose
|
||||
* total BaselineExposure cannot clip more than the configured pixel fraction.
|
||||
@@ -189,15 +288,48 @@ internal object RawLegacyAutoExposureMatcher {
|
||||
)
|
||||
}
|
||||
|
||||
private fun buildReference(bitmap: Bitmap): ViewfinderReference? {
|
||||
private fun buildReference(
|
||||
bitmap: Bitmap,
|
||||
centerFractionPerAxis: Float = 1f,
|
||||
portraitPriority: PortraitPrioritySource? = null,
|
||||
mirrorHorizontally: Boolean = false,
|
||||
previewToCaptureRotationDegrees: Int = 0,
|
||||
): ViewfinderReference? {
|
||||
if (bitmap.isRecycled || bitmap.width <= 0 || bitmap.height <= 0) return null
|
||||
return try {
|
||||
val size = longEdgeSize(bitmap.width, bitmap.height, PREVIEW_LONG_EDGE)
|
||||
val sourceBounds = centeredBounds(
|
||||
outputBounds = Rect(0, 0, bitmap.width, bitmap.height),
|
||||
centerFractionPerAxis = centerFractionPerAxis,
|
||||
) ?: return null
|
||||
val size = longEdgeSize(
|
||||
sourceBounds.width(),
|
||||
sourceBounds.height(),
|
||||
PREVIEW_LONG_EDGE,
|
||||
)
|
||||
ViewfinderReference(
|
||||
frame = RawLegacyExposurePreviewFrame(
|
||||
width = size.width,
|
||||
height = size.height,
|
||||
argbPixels = sampleBitmap(bitmap, size.width, size.height),
|
||||
argbPixels = sampleBitmap(
|
||||
bitmap = bitmap,
|
||||
width = size.width,
|
||||
height = size.height,
|
||||
sourceBounds = sourceBounds,
|
||||
mirrorHorizontally = mirrorHorizontally,
|
||||
previewToCaptureRotationDegrees = previewToCaptureRotationDegrees,
|
||||
),
|
||||
portraitPriorityWeights = portraitPriority?.let { priority ->
|
||||
samplePortraitPriorityWeights(
|
||||
portraitPriority = priority,
|
||||
rotatedBitmapWidth = bitmap.width,
|
||||
rotatedBitmapHeight = bitmap.height,
|
||||
width = size.width,
|
||||
height = size.height,
|
||||
sourceBounds = sourceBounds,
|
||||
mirrorHorizontally = mirrorHorizontally,
|
||||
previewToCaptureRotationDegrees = previewToCaptureRotationDegrees,
|
||||
)
|
||||
},
|
||||
),
|
||||
)
|
||||
} catch (error: Throwable) {
|
||||
@@ -209,9 +341,10 @@ internal object RawLegacyAutoExposureMatcher {
|
||||
/**
|
||||
* Drives the native two-dimensional HDRNet matcher.
|
||||
*
|
||||
* Native code owns P20-P80 curve fitting, the damped Newton/Broyden state, convergence,
|
||||
* step limits, Huber-loss guarding and the one-dimensional fallback. This method only maps
|
||||
* native `(short EV, HDR-ratio EV)` requests to gains and runs the expensive model callback.
|
||||
* Native code jointly searches independent short and long EV coordinates. Highlight-grid
|
||||
* error drives short, shadow-grid error drives long, and the measured cross-response is kept
|
||||
* in the Jacobian. Selection and convergence use the full-grid match rate. This maps native
|
||||
* requests back to short EV and HDR-ratio EV and runs the model callback.
|
||||
*/
|
||||
fun <T> solveHdrNetExposure(
|
||||
referenceFrame: RawLegacyExposurePreviewFrame,
|
||||
@@ -260,6 +393,7 @@ internal object RawLegacyAutoExposureMatcher {
|
||||
columns = DngPhotonProfileGainTableGenerator.HDRNET_PGTM_GRID_WIDTH,
|
||||
rows = DngPhotonProfileGainTableGenerator.HDRNET_PGTM_GRID_HEIGHT,
|
||||
) ?: return@use null
|
||||
val coordinatesMatched = solver.lastCandidateCoordinatesMatch()
|
||||
inferences += HdrNetInference(
|
||||
shortEv = parameters.shortEv,
|
||||
hdrRatioEv = parameters.hdrRatioEv,
|
||||
@@ -273,17 +407,27 @@ internal object RawLegacyAutoExposureMatcher {
|
||||
"HDRNet viewfinder probe: index=${inferences.size} " +
|
||||
"adjustmentAxis=${parameters.axis} " +
|
||||
"shortEv=${parameters.shortEv} ratioEv=${parameters.hdrRatioEv} " +
|
||||
"longEv=${parameters.shortEv + parameters.hdrRatioEv} " +
|
||||
"shortGain=$shortGain longGain=$longGain hdrRatio=$hdrRatio " +
|
||||
"matchedCells=${sample.matchedCellCount}/${sample.validCellCount} " +
|
||||
"curveFitCells=${sample.curveFitCellCount} " +
|
||||
"centerErrorEv=${sample.centerErrorEv} " +
|
||||
"spanErrorEv=${sample.spanErrorEv} " +
|
||||
"curveSlopeError=${sample.curveSlopeError} " +
|
||||
"highlightTargetErrorEv=${sample.highlightTargetErrorEv} " +
|
||||
"shadowTargetErrorEv=${sample.shadowTargetErrorEv} " +
|
||||
"shortTargetCorrectionEv=${sample.shortTargetCorrectionEv} " +
|
||||
"longTargetCorrectionEv=${sample.longTargetCorrectionEv} " +
|
||||
"referenceP20Ev=${sample.referenceP20Ev} " +
|
||||
"referenceP50Ev=${sample.referenceP50Ev} " +
|
||||
"referenceP80Ev=${sample.referenceP80Ev} " +
|
||||
"robustLog2Loss=${sample.robustLog2Loss} " +
|
||||
"matchRate=${sample.matchRate} " +
|
||||
"meanPerceptualLightnessError=" +
|
||||
"${sample.meanAbsolutePerceptualLightnessError} " +
|
||||
"coordinateEdges=${sample.coordinateComparedEdgeCount} " +
|
||||
"coordinateMatchRate=${sample.coordinateMatchRate} " +
|
||||
"coordinatesMatched=$coordinatesMatched " +
|
||||
"recommendedExposureCorrectionEv=" +
|
||||
"${sample.recommendedExposureCorrectionEv} " +
|
||||
"candidateMs=${(candidateReadyNs - probeStartNs) / 1_000_000f} " +
|
||||
@@ -292,6 +436,31 @@ internal object RawLegacyAutoExposureMatcher {
|
||||
)
|
||||
}
|
||||
val result = solver.hdrNetResult() ?: return@use null
|
||||
if (result.sample.coordinatesMatched == false) {
|
||||
PLog.w(
|
||||
TAG,
|
||||
"HDRNet viewfinder matching rejected: " +
|
||||
"reason=COORDINATE_MISMATCH " +
|
||||
"matchRate=${result.sample.matchRate} " +
|
||||
"coordinateEdges=${result.sample.coordinateComparedEdgeCount} " +
|
||||
"coordinateMatchRate=${result.sample.coordinateMatchRate} " +
|
||||
"coordinatesMatched=${result.sample.coordinatesMatched} " +
|
||||
"candidateCount=${result.evaluatedCandidateCount}",
|
||||
)
|
||||
return@use null
|
||||
}
|
||||
if (!result.converged) {
|
||||
PLog.w(
|
||||
TAG,
|
||||
"HDRNet viewfinder matching did not reach the early-convergence target; " +
|
||||
"using the highest-match-rate candidate: " +
|
||||
"matchRate=${result.sample.matchRate} " +
|
||||
"coordinateEdges=${result.sample.coordinateComparedEdgeCount} " +
|
||||
"coordinateMatchRate=${result.sample.coordinateMatchRate} " +
|
||||
"coordinatesMatched=${result.sample.coordinatesMatched} " +
|
||||
"candidateCount=${result.evaluatedCandidateCount}",
|
||||
)
|
||||
}
|
||||
val selectedInference = inferences.minByOrNull {
|
||||
abs(it.shortEv - result.shortEv) +
|
||||
abs(it.hdrRatioEv - result.hdrRatioEv)
|
||||
@@ -310,10 +479,19 @@ internal object RawLegacyAutoExposureMatcher {
|
||||
spanErrorEv = sample.spanErrorEv,
|
||||
curveSlopeError = sample.curveSlopeError,
|
||||
referenceSpanEv = sample.referenceSpanEv,
|
||||
highlightTargetErrorEv = sample.highlightTargetErrorEv,
|
||||
shadowTargetErrorEv = sample.shadowTargetErrorEv,
|
||||
shortTargetCorrectionEv = sample.shortTargetCorrectionEv,
|
||||
longTargetCorrectionEv = sample.longTargetCorrectionEv,
|
||||
medianLog2Ratio = sample.medianLog2Ratio,
|
||||
robustLog2Loss = sample.robustLog2Loss,
|
||||
meanAbsoluteLog2Ratio = sample.meanAbsoluteLog2Ratio,
|
||||
meanAbsolutePerceptualLightnessError =
|
||||
sample.meanAbsolutePerceptualLightnessError,
|
||||
matchRate = sample.matchRate,
|
||||
coordinateComparedEdgeCount = sample.coordinateComparedEdgeCount,
|
||||
coordinateMatchRate = sample.coordinateMatchRate,
|
||||
coordinatesMatched = sample.coordinatesMatched,
|
||||
recommendedExposureCorrectionEv =
|
||||
sample.recommendedExposureCorrectionEv,
|
||||
evaluatedCandidateCount = result.evaluatedCandidateCount,
|
||||
@@ -329,12 +507,22 @@ internal object RawLegacyAutoExposureMatcher {
|
||||
"longGain=${selected.longGain} " +
|
||||
"hdrRatio=${selected.longGain / selected.shortGain} " +
|
||||
"shortEv=${result.shortEv} ratioEv=${result.hdrRatioEv} " +
|
||||
"longEv=${result.shortEv + result.hdrRatioEv} " +
|
||||
"centerErrorEv=${sample.centerErrorEv} " +
|
||||
"spanErrorEv=${sample.spanErrorEv} " +
|
||||
"curveSlopeError=${sample.curveSlopeError} " +
|
||||
"highlightTargetErrorEv=${sample.highlightTargetErrorEv} " +
|
||||
"shadowTargetErrorEv=${sample.shadowTargetErrorEv} " +
|
||||
"shortTargetCorrectionEv=${sample.shortTargetCorrectionEv} " +
|
||||
"longTargetCorrectionEv=${sample.longTargetCorrectionEv} " +
|
||||
"referenceSpanEv=${sample.referenceSpanEv} " +
|
||||
"robustLog2Loss=${sample.robustLog2Loss} " +
|
||||
"matchRate=${sample.matchRate} " +
|
||||
"meanPerceptualLightnessError=" +
|
||||
"${sample.meanAbsolutePerceptualLightnessError} " +
|
||||
"coordinateEdges=${sample.coordinateComparedEdgeCount} " +
|
||||
"coordinateMatchRate=${sample.coordinateMatchRate} " +
|
||||
"coordinatesMatched=${sample.coordinatesMatched} " +
|
||||
"jacobianNormalizedDeterminant=" +
|
||||
"${result.jacobianNormalizedDeterminant} " +
|
||||
"fallback1d=${result.usedOneDimensionalFallback} " +
|
||||
@@ -381,6 +569,7 @@ internal object RawLegacyAutoExposureMatcher {
|
||||
val exposureEv = solver.nextExposureEv() ?: break
|
||||
val frame = renderSample(exposureEv) ?: return@use null
|
||||
if (!solver.submitCandidate(exposureEv, frame)) return@use null
|
||||
val coordinatesMatched = solver.lastCandidateCoordinatesMatch()
|
||||
solver.lastSample()?.let { sample ->
|
||||
PLog.d(
|
||||
TAG,
|
||||
@@ -388,34 +577,72 @@ internal object RawLegacyAutoExposureMatcher {
|
||||
"exposureEv=${sample.exposureEv} " +
|
||||
"matchedCells=${sample.matchedCellCount}/${sample.validCellCount} " +
|
||||
"matchRate=${sample.matchRate} " +
|
||||
"meanPerceptualLightnessError=" +
|
||||
"${sample.meanAbsolutePerceptualLightnessError} " +
|
||||
"meanAbsoluteLog2Ratio=${sample.meanAbsoluteLog2Ratio} " +
|
||||
"medianLog2Ratio=${sample.medianLog2Ratio} " +
|
||||
"robustLog2Loss=${sample.robustLog2Loss} " +
|
||||
"recommendedExposureCorrectionEv=" +
|
||||
"${sample.recommendedExposureCorrectionEv} " +
|
||||
"referenceWeightSum=${sample.referenceWeightSum}",
|
||||
"referenceWeightSum=${sample.referenceWeightSum} " +
|
||||
"coordinateEdges=${sample.coordinateComparedEdgeCount} " +
|
||||
"coordinateMatchRate=${sample.coordinateMatchRate} " +
|
||||
"coordinatesMatched=$coordinatesMatched",
|
||||
)
|
||||
}
|
||||
}
|
||||
val result = solver.result() ?: return@use null
|
||||
if (result.best.coordinatesMatched == false) {
|
||||
PLog.w(
|
||||
TAG,
|
||||
"Viewfinder brightness matching rejected: " +
|
||||
"reason=COORDINATE_MISMATCH " +
|
||||
"matchRate=${result.best.matchRate} " +
|
||||
"requiredMatchRate=${result.requiredGridMatchRate} " +
|
||||
"coordinateEdges=${result.best.coordinateComparedEdgeCount} " +
|
||||
"coordinateMatchRate=${result.best.coordinateMatchRate} " +
|
||||
"coordinatesMatched=${result.best.coordinatesMatched}",
|
||||
)
|
||||
return@use null
|
||||
}
|
||||
if (!solver.hasConverged()) {
|
||||
PLog.w(
|
||||
TAG,
|
||||
"Viewfinder brightness matching did not reach the early-convergence " +
|
||||
"target; using the highest-match-rate candidate: " +
|
||||
"matchRate=${result.best.matchRate} " +
|
||||
"requiredMatchRate=${result.requiredGridMatchRate} " +
|
||||
"coordinateEdges=${result.best.coordinateComparedEdgeCount} " +
|
||||
"coordinateMatchRate=${result.best.coordinateMatchRate} " +
|
||||
"coordinatesMatched=${result.best.coordinatesMatched}",
|
||||
)
|
||||
}
|
||||
PLog.i(
|
||||
TAG,
|
||||
"Viewfinder brightness matching result: " +
|
||||
"exposureEv=${result.best.exposureEv} " +
|
||||
"matchedCells=${result.best.matchedCellCount}/${result.best.validCellCount} " +
|
||||
"matchRate=${result.best.matchRate} " +
|
||||
"meanPerceptualLightnessError=" +
|
||||
"${result.best.meanAbsolutePerceptualLightnessError} " +
|
||||
"meanAbsoluteLog2Ratio=${result.best.meanAbsoluteLog2Ratio} " +
|
||||
"medianLog2Ratio=${result.best.medianLog2Ratio} " +
|
||||
"robustLog2Loss=${result.best.robustLog2Loss} " +
|
||||
"recommendedExposureCorrectionEv=" +
|
||||
"${result.best.recommendedExposureCorrectionEv} " +
|
||||
"referenceWeightSum=${result.best.referenceWeightSum} " +
|
||||
"coordinateEdges=${result.best.coordinateComparedEdgeCount} " +
|
||||
"coordinateMatchRate=${result.best.coordinateMatchRate} " +
|
||||
"coordinatesMatched=${result.best.coordinatesMatched} " +
|
||||
"sampleCount=${result.evaluatedSampleCount} " +
|
||||
"excludedShadowCells=${result.excludedShadowCellCount} " +
|
||||
"excludedHighlightCells=${result.excludedHighlightCellCount} " +
|
||||
"shadowWeightZeroLinear=${result.shadowWeightZeroLinear} " +
|
||||
"highlightWeightZeroLinear=${result.highlightWeightZeroLinear} " +
|
||||
"huberDeltaEv=${result.huberDeltaEv}",
|
||||
"huberDeltaEv=${result.huberDeltaEv} " +
|
||||
"perceptualLightnessTolerance=" +
|
||||
"${result.perceptualLightnessTolerance} " +
|
||||
"requiredGridMatchRate=${result.requiredGridMatchRate}",
|
||||
)
|
||||
result.best.exposureEv
|
||||
}
|
||||
@@ -425,6 +652,40 @@ internal object RawLegacyAutoExposureMatcher {
|
||||
|
||||
private const val HDRNET_PAYLOAD_LOOKUP_TOLERANCE_EV = 0.001f
|
||||
|
||||
private fun resolvePortraitPriority(
|
||||
snapshot: PortraitMaskSnapshot?,
|
||||
expectedRotationDegrees: Int,
|
||||
): PortraitPrioritySource? {
|
||||
val mask = snapshot ?: return null
|
||||
val rotation = Math.floorMod(mask.previewToCaptureRotationDegrees, 360)
|
||||
if (rotation != 0 && rotation != 90 && rotation != 180 && rotation != 270) {
|
||||
PLog.w(TAG, "Portrait target ignored: unsupported capture rotation=$rotation")
|
||||
return null
|
||||
}
|
||||
if (rotation != expectedRotationDegrees) {
|
||||
PLog.w(
|
||||
TAG,
|
||||
"Portrait target ignored: mask rotation=$rotation does not match " +
|
||||
"viewfinder rotation=$expectedRotationDegrees",
|
||||
)
|
||||
return null
|
||||
}
|
||||
val areaFraction = portraitAreaFraction(mask) ?: return null
|
||||
return PortraitPrioritySource(mask, areaFraction)
|
||||
.takeIf { areaFraction >= PORTRAIT_PRIORITY_MINIMUM_AREA_FRACTION }
|
||||
}
|
||||
|
||||
private fun portraitAreaFraction(snapshot: PortraitMaskSnapshot): Float? {
|
||||
if (snapshot.confidence.isEmpty()) return null
|
||||
var sum = 0.0
|
||||
for (weight in snapshot.confidence) {
|
||||
if (!weight.isFinite() || weight !in 0f..1f) return null
|
||||
sum += weight.toDouble()
|
||||
}
|
||||
return (sum / snapshot.confidence.size.toDouble()).toFloat()
|
||||
.takeIf(Float::isFinite)
|
||||
}
|
||||
|
||||
private fun longEdgeSize(sourceWidth: Int, sourceHeight: Int, maxLongEdge: Int): Size {
|
||||
val longEdge = minOf(max(sourceWidth, sourceHeight), maxLongEdge.coerceAtLeast(1))
|
||||
return if (sourceWidth >= sourceHeight) {
|
||||
@@ -442,19 +703,117 @@ internal object RawLegacyAutoExposureMatcher {
|
||||
}
|
||||
}
|
||||
|
||||
private fun sampleBitmap(bitmap: Bitmap, width: Int, height: Int): IntArray {
|
||||
private fun sampleBitmap(
|
||||
bitmap: Bitmap,
|
||||
width: Int,
|
||||
height: Int,
|
||||
sourceBounds: Rect,
|
||||
mirrorHorizontally: Boolean,
|
||||
previewToCaptureRotationDegrees: Int,
|
||||
): IntArray {
|
||||
val pixels = IntArray(width * height)
|
||||
val row = IntArray(bitmap.width)
|
||||
val mirrorVertically = mirrorHorizontally &&
|
||||
Math.floorMod(previewToCaptureRotationDegrees, 180) != 0
|
||||
for (y in 0 until height) {
|
||||
val sourceY = ((y + 0.5f) * bitmap.height / height).toInt()
|
||||
.coerceIn(0, bitmap.height - 1)
|
||||
val sampledSourceY = (
|
||||
sourceBounds.top + (y + 0.5f) * sourceBounds.height() / height
|
||||
).toInt().coerceIn(sourceBounds.top, sourceBounds.bottom - 1)
|
||||
val sourceY = if (mirrorVertically) {
|
||||
sourceBounds.bottom - 1 - (sampledSourceY - sourceBounds.top)
|
||||
} else {
|
||||
sampledSourceY
|
||||
}
|
||||
bitmap.getPixels(row, 0, bitmap.width, 0, sourceY, bitmap.width, 1)
|
||||
for (x in 0 until width) {
|
||||
val sourceX = ((x + 0.5f) * bitmap.width / width).toInt()
|
||||
.coerceIn(0, bitmap.width - 1)
|
||||
val sampledSourceX = (
|
||||
sourceBounds.left + (x + 0.5f) * sourceBounds.width() / width
|
||||
).toInt().coerceIn(sourceBounds.left, sourceBounds.right - 1)
|
||||
val sourceX = if (mirrorHorizontally && !mirrorVertically) {
|
||||
sourceBounds.right - 1 - (sampledSourceX - sourceBounds.left)
|
||||
} else {
|
||||
sampledSourceX
|
||||
}
|
||||
pixels[y * width + x] = row[sourceX]
|
||||
}
|
||||
}
|
||||
return pixels
|
||||
}
|
||||
|
||||
private fun samplePortraitPriorityWeights(
|
||||
portraitPriority: PortraitPrioritySource,
|
||||
rotatedBitmapWidth: Int,
|
||||
rotatedBitmapHeight: Int,
|
||||
width: Int,
|
||||
height: Int,
|
||||
sourceBounds: Rect,
|
||||
mirrorHorizontally: Boolean,
|
||||
previewToCaptureRotationDegrees: Int,
|
||||
): FloatArray {
|
||||
val snapshot = portraitPriority.snapshot
|
||||
val rotation = Math.floorMod(previewToCaptureRotationDegrees, 360)
|
||||
val mirrorVertically = mirrorHorizontally && rotation % 180 != 0
|
||||
val weights = FloatArray(width * height)
|
||||
for (y in 0 until height) {
|
||||
val sampledRotatedY = (
|
||||
sourceBounds.top + (y + 0.5f) * sourceBounds.height() / height
|
||||
) / rotatedBitmapHeight.toFloat()
|
||||
val rotatedY = if (mirrorVertically) {
|
||||
1f - sampledRotatedY
|
||||
} else {
|
||||
sampledRotatedY
|
||||
}
|
||||
for (x in 0 until width) {
|
||||
val sampledRotatedX = (
|
||||
sourceBounds.left + (x + 0.5f) * sourceBounds.width() / width
|
||||
) / rotatedBitmapWidth.toFloat()
|
||||
val rotatedX = if (mirrorHorizontally && !mirrorVertically) {
|
||||
1f - sampledRotatedX
|
||||
} else {
|
||||
sampledRotatedX
|
||||
}
|
||||
// BitmapUtils.rotate uses top-left coordinates and positive clockwise rotation.
|
||||
// Invert that transform to sample the detector's original-preview mask.
|
||||
val (previewX, previewY) = when (rotation) {
|
||||
0 -> rotatedX to rotatedY
|
||||
90 -> rotatedY to (1f - rotatedX)
|
||||
180 -> (1f - rotatedX) to (1f - rotatedY)
|
||||
270 -> (1f - rotatedY) to rotatedX
|
||||
else -> error("Unsupported portrait target rotation: $rotation")
|
||||
}
|
||||
weights[y * width + x] = bilinearMaskSample(
|
||||
values = snapshot.confidence,
|
||||
width = snapshot.width,
|
||||
height = snapshot.height,
|
||||
normalizedX = previewX,
|
||||
normalizedY = previewY,
|
||||
)
|
||||
}
|
||||
}
|
||||
return weights
|
||||
}
|
||||
|
||||
private fun bilinearMaskSample(
|
||||
values: FloatArray,
|
||||
width: Int,
|
||||
height: Int,
|
||||
normalizedX: Float,
|
||||
normalizedY: Float,
|
||||
): Float {
|
||||
val sourceX = (normalizedX.coerceIn(0f, 1f) * width - 0.5f)
|
||||
.coerceIn(0f, width - 1f)
|
||||
val sourceY = (normalizedY.coerceIn(0f, 1f) * height - 0.5f)
|
||||
.coerceIn(0f, height - 1f)
|
||||
val x0 = sourceX.toInt().coerceIn(0, width - 1)
|
||||
val y0 = sourceY.toInt().coerceIn(0, height - 1)
|
||||
val x1 = (x0 + 1).coerceAtMost(width - 1)
|
||||
val y1 = (y0 + 1).coerceAtMost(height - 1)
|
||||
val fractionX = sourceX - x0
|
||||
val fractionY = sourceY - y0
|
||||
val top = values[y0 * width + x0] * (1f - fractionX) +
|
||||
values[y0 * width + x1] * fractionX
|
||||
val bottom = values[y1 * width + x0] * (1f - fractionX) +
|
||||
values[y1 * width + x1] * fractionX
|
||||
return (top * (1f - fractionY) + bottom * fractionY).coerceIn(0f, 1f)
|
||||
}
|
||||
}
|
||||
@@ -19,6 +19,10 @@ internal object RawLegacyAutoExposureNativeBridge {
|
||||
val robustLog2Loss: Float,
|
||||
val referenceWeightSum: Float,
|
||||
val recommendedExposureCorrectionEv: Float,
|
||||
val meanAbsolutePerceptualLightnessError: Float,
|
||||
val coordinateComparedEdgeCount: Int,
|
||||
val coordinateMatchRate: Float,
|
||||
val coordinatesMatched: Boolean?,
|
||||
)
|
||||
|
||||
data class Result(
|
||||
@@ -29,6 +33,8 @@ internal object RawLegacyAutoExposureNativeBridge {
|
||||
val shadowWeightZeroLinear: Float,
|
||||
val highlightWeightZeroLinear: Float,
|
||||
val huberDeltaEv: Float,
|
||||
val perceptualLightnessTolerance: Float,
|
||||
val requiredGridMatchRate: Float,
|
||||
)
|
||||
|
||||
data class HdrNetCurveSample(
|
||||
@@ -48,15 +54,27 @@ internal object RawLegacyAutoExposureNativeBridge {
|
||||
val referenceP50Ev: Float,
|
||||
val referenceP80Ev: Float,
|
||||
val curveFitCellCount: Int,
|
||||
val shortTargetCorrectionEv: Float,
|
||||
val longTargetCorrectionEv: Float,
|
||||
val meanAbsolutePerceptualLightnessError: Float,
|
||||
val coordinateComparedEdgeCount: Int,
|
||||
val coordinateMatchRate: Float,
|
||||
val coordinatesMatched: Boolean?,
|
||||
) {
|
||||
val referenceSpanEv: Float
|
||||
get() = referenceP80Ev - referenceP20Ev
|
||||
|
||||
val highlightTargetErrorEv: Float
|
||||
get() = -shortTargetCorrectionEv
|
||||
|
||||
val shadowTargetErrorEv: Float
|
||||
get() = -longTargetCorrectionEv
|
||||
}
|
||||
|
||||
enum class HdrNetProbeAxis {
|
||||
BASE,
|
||||
SHORT_JACOBIAN,
|
||||
RATIO_JACOBIAN,
|
||||
LONG_JACOBIAN,
|
||||
JOINT_NEWTON,
|
||||
FALLBACK_SHORT,
|
||||
}
|
||||
@@ -80,6 +98,8 @@ internal object RawLegacyAutoExposureNativeBridge {
|
||||
class Solver private constructor(
|
||||
private var handle: Long,
|
||||
) : AutoCloseable {
|
||||
private var latestCoordinatesMatched: Boolean? = null
|
||||
|
||||
fun nextExposureEv(): Float? {
|
||||
check(handle != 0L) { "Native exposure solver is closed" }
|
||||
return nativeNextExposureEv(handle).takeIf { it.isFinite() }
|
||||
@@ -87,13 +107,18 @@ internal object RawLegacyAutoExposureNativeBridge {
|
||||
|
||||
fun submitCandidate(exposureEv: Float, frame: RawLegacyExposurePreviewFrame): Boolean {
|
||||
check(handle != 0L) { "Native exposure solver is closed" }
|
||||
return nativeSubmitCandidate(
|
||||
val submitted = nativeSubmitCandidate(
|
||||
handle = handle,
|
||||
exposureEv = exposureEv,
|
||||
candidatePixels = frame.argbPixels,
|
||||
width = frame.width,
|
||||
height = frame.height,
|
||||
)
|
||||
if (submitted) {
|
||||
latestCoordinatesMatched =
|
||||
nativeGetLastSample(handle)?.toSample()?.coordinatesMatched
|
||||
}
|
||||
return submitted
|
||||
}
|
||||
|
||||
fun submitCandidate(
|
||||
@@ -106,13 +131,18 @@ internal object RawLegacyAutoExposureNativeBridge {
|
||||
if (columns <= 0 || rows <= 0 || displayLinearLumas.size != columns * rows) {
|
||||
return false
|
||||
}
|
||||
return nativeSubmitGridCandidate(
|
||||
val submitted = nativeSubmitGridCandidate(
|
||||
handle = handle,
|
||||
exposureEv = exposureEv,
|
||||
candidateDisplayLinearLumas = displayLinearLumas,
|
||||
columns = columns,
|
||||
rows = rows,
|
||||
)
|
||||
if (submitted) {
|
||||
latestCoordinatesMatched =
|
||||
nativeGetLastSample(handle)?.toSample()?.coordinatesMatched
|
||||
}
|
||||
return submitted
|
||||
}
|
||||
|
||||
fun startHdrNetSolve(
|
||||
@@ -154,7 +184,9 @@ internal object RawLegacyAutoExposureNativeBridge {
|
||||
columns = columns,
|
||||
rows = rows,
|
||||
) ?: return null
|
||||
return values.toHdrNetCurveSample()
|
||||
return values.toHdrNetCurveSample()?.also {
|
||||
latestCoordinatesMatched = it.coordinatesMatched
|
||||
}
|
||||
}
|
||||
|
||||
fun hdrNetResult(): HdrNetResult? {
|
||||
@@ -165,10 +197,10 @@ internal object RawLegacyAutoExposureNativeBridge {
|
||||
shortEv = values[0],
|
||||
hdrRatioEv = values[1],
|
||||
sample = values.toHdrNetCurveSample(offset = 2) ?: return null,
|
||||
evaluatedCandidateCount = values[18].roundToInt(),
|
||||
converged = values[19] != 0f,
|
||||
usedOneDimensionalFallback = values[20] != 0f,
|
||||
jacobianNormalizedDeterminant = values[21],
|
||||
evaluatedCandidateCount = values[24].roundToInt(),
|
||||
converged = values[25] != 0f,
|
||||
usedOneDimensionalFallback = values[26] != 0f,
|
||||
jacobianNormalizedDeterminant = values[27],
|
||||
)
|
||||
}
|
||||
|
||||
@@ -182,9 +214,17 @@ internal object RawLegacyAutoExposureNativeBridge {
|
||||
return nativeHasConverged(handle)
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns whether the latest candidate uses the same spatial coordinates as the
|
||||
* viewfinder reference, or null when the scene has too little local contrast to decide.
|
||||
*/
|
||||
fun lastCandidateCoordinatesMatch(): Boolean? = latestCoordinatesMatched
|
||||
|
||||
fun lastSample(): Sample? {
|
||||
check(handle != 0L) { "Native exposure solver is closed" }
|
||||
return nativeGetLastSample(handle)?.toSample()
|
||||
return nativeGetLastSample(handle)?.toSample()?.also {
|
||||
latestCoordinatesMatched = it.coordinatesMatched
|
||||
}
|
||||
}
|
||||
|
||||
fun result(): Result? {
|
||||
@@ -193,12 +233,14 @@ internal object RawLegacyAutoExposureNativeBridge {
|
||||
if (values.size != RESULT_VALUE_COUNT) return null
|
||||
return Result(
|
||||
best = values.toSample() ?: return null,
|
||||
evaluatedSampleCount = values[10].roundToInt(),
|
||||
excludedShadowCellCount = values[11].roundToInt(),
|
||||
excludedHighlightCellCount = values[12].roundToInt(),
|
||||
shadowWeightZeroLinear = values[13],
|
||||
highlightWeightZeroLinear = values[14],
|
||||
huberDeltaEv = values[15],
|
||||
evaluatedSampleCount = values[14].roundToInt(),
|
||||
excludedShadowCellCount = values[15].roundToInt(),
|
||||
excludedHighlightCellCount = values[16].roundToInt(),
|
||||
shadowWeightZeroLinear = values[17],
|
||||
highlightWeightZeroLinear = values[18],
|
||||
huberDeltaEv = values[19],
|
||||
perceptualLightnessTolerance = values[20],
|
||||
requiredGridMatchRate = values[21],
|
||||
)
|
||||
}
|
||||
|
||||
@@ -206,6 +248,7 @@ internal object RawLegacyAutoExposureNativeBridge {
|
||||
val nativeHandle = handle
|
||||
if (nativeHandle == 0L) return
|
||||
handle = 0L
|
||||
latestCoordinatesMatched = null
|
||||
nativeDestroy(nativeHandle)
|
||||
}
|
||||
|
||||
@@ -213,6 +256,7 @@ internal object RawLegacyAutoExposureNativeBridge {
|
||||
fun create(reference: RawLegacyExposurePreviewFrame): Solver? {
|
||||
val handle = nativeCreate(
|
||||
referencePixels = reference.argbPixels,
|
||||
portraitPriorityWeights = reference.portraitPriorityWeights,
|
||||
width = reference.width,
|
||||
height = reference.height,
|
||||
)
|
||||
@@ -234,6 +278,10 @@ internal object RawLegacyAutoExposureNativeBridge {
|
||||
robustLog2Loss = this[7],
|
||||
referenceWeightSum = this[8],
|
||||
recommendedExposureCorrectionEv = this[9],
|
||||
meanAbsolutePerceptualLightnessError = this[10],
|
||||
coordinateComparedEdgeCount = this[11].roundToInt(),
|
||||
coordinateMatchRate = this[12],
|
||||
coordinatesMatched = this[13].toCoordinateMatch(),
|
||||
)
|
||||
}
|
||||
|
||||
@@ -256,8 +304,16 @@ internal object RawLegacyAutoExposureNativeBridge {
|
||||
referenceP50Ev = this[offset + 13],
|
||||
referenceP80Ev = this[offset + 14],
|
||||
curveFitCellCount = this[offset + 15].roundToInt(),
|
||||
shortTargetCorrectionEv = this[offset + 16],
|
||||
longTargetCorrectionEv = this[offset + 17],
|
||||
meanAbsolutePerceptualLightnessError = this[offset + 18],
|
||||
coordinateComparedEdgeCount = this[offset + 19].roundToInt(),
|
||||
coordinateMatchRate = this[offset + 20],
|
||||
coordinatesMatched = this[offset + 21].toCoordinateMatch(),
|
||||
).takeIf {
|
||||
it.matchRate.isFinite() &&
|
||||
it.meanAbsolutePerceptualLightnessError.isFinite() &&
|
||||
it.coordinateMatchRate.isFinite() &&
|
||||
it.meanAbsoluteLog2Ratio.isFinite() &&
|
||||
it.medianLog2Ratio.isFinite() &&
|
||||
it.robustLog2Loss.isFinite() &&
|
||||
@@ -266,8 +322,16 @@ internal object RawLegacyAutoExposureNativeBridge {
|
||||
}
|
||||
}
|
||||
|
||||
private fun Float.toCoordinateMatch(): Boolean? = when (roundToInt()) {
|
||||
-1 -> null
|
||||
0 -> false
|
||||
1 -> true
|
||||
else -> null
|
||||
}
|
||||
|
||||
private external fun nativeCreate(
|
||||
referencePixels: IntArray,
|
||||
portraitPriorityWeights: FloatArray?,
|
||||
width: Int,
|
||||
height: Int,
|
||||
): Long
|
||||
@@ -321,9 +385,9 @@ internal object RawLegacyAutoExposureNativeBridge {
|
||||
private external fun nativeGetResult(handle: Long): FloatArray?
|
||||
private external fun nativeDestroy(handle: Long)
|
||||
|
||||
private const val SAMPLE_VALUE_COUNT = 10
|
||||
private const val RESULT_VALUE_COUNT = 16
|
||||
private const val HDRNET_CURVE_SAMPLE_VALUE_COUNT = 16
|
||||
private const val SAMPLE_VALUE_COUNT = 14
|
||||
private const val RESULT_VALUE_COUNT = 22
|
||||
private const val HDRNET_CURVE_SAMPLE_VALUE_COUNT = 22
|
||||
private const val HDRNET_PARAMETER_VALUE_COUNT = 3
|
||||
private const val HDRNET_RESULT_VALUE_COUNT = 22
|
||||
private const val HDRNET_RESULT_VALUE_COUNT = 28
|
||||
}
|
||||
@@ -248,6 +248,8 @@ internal class RawLinearRcdPass(
|
||||
}
|
||||
|
||||
void main() {
|
||||
// Memory row zero is the image top throughout RAW readback and Android Bitmap.
|
||||
// This inverse mapping applies a clockwise output rotation in that shared space.
|
||||
vec2 orientedCoord = vTexCoord;
|
||||
if (uTextureRotation == 90) {
|
||||
orientedCoord = vec2(vTexCoord.y, 1.0 - vTexCoord.x);
|
||||
|
||||
@@ -1105,8 +1105,7 @@ fun CameraScreen(
|
||||
(state.focusPoint == null || state.focusPointSource == FocusPointSource.EYE)
|
||||
val portraitMaskActive = state.captureMode == CaptureMode.PHOTO &&
|
||||
state.useRaw &&
|
||||
state.isRawSupported &&
|
||||
rawToneMappingParameters.usePhotonHdr
|
||||
state.isRawSupported
|
||||
|
||||
// 相机准备完成后再创建 Surface,首次只打开最终选中的镜头。
|
||||
if (isCameraPrepared) {
|
||||
|
||||
@@ -159,6 +159,8 @@ object BitmapUtils {
|
||||
/**
|
||||
* 旋转 Bitmap。
|
||||
*
|
||||
* 坐标约定为左上原点,正角度顺时针,与 RAW 和 HDRNet 的输出坐标一致。
|
||||
*
|
||||
* 旋转角度为 0 时直接返回原图,避免额外创建 Bitmap。
|
||||
*/
|
||||
fun rotate(bitmap: Bitmap, rotationDegrees: Float): Bitmap {
|
||||
|
||||
@@ -1934,6 +1934,10 @@ class CameraViewModel(application: Application) : AndroidViewModel(application)
|
||||
sensorOrientationDegrees = cameraController.getSensorOrientation(),
|
||||
isFrontFacing = cameraController.getLensFacing() ==
|
||||
CameraCharacteristics.LENS_FACING_FRONT,
|
||||
previewToCaptureRotationDegrees = Math.floorMod(
|
||||
capturePreviewThumbnailRotation().roundToInt(),
|
||||
360,
|
||||
),
|
||||
)
|
||||
}
|
||||
previewEyeFocusProcessor.onTargetLost = {
|
||||
@@ -4553,7 +4557,6 @@ class CameraViewModel(application: Application) : AndroidViewModel(application)
|
||||
val acceptsPortraitMask = cameraState.captureMode == CaptureMode.PHOTO &&
|
||||
cameraState.useRaw &&
|
||||
cameraState.isRawSupported &&
|
||||
rawToneMappingParameters.value.usePhotonHdr &&
|
||||
cameraState.isPreviewActive &&
|
||||
!cameraState.isCapturing
|
||||
val acceptsEyeFocus = eyeFocusEnabled.value &&
|
||||
@@ -4665,6 +4668,8 @@ class CameraViewModel(application: Application) : AndroidViewModel(application)
|
||||
"size=$size " +
|
||||
"ageMs=$ageMs " +
|
||||
"sensorOrientation=${snapshot?.sensorOrientationDegrees} " +
|
||||
"previewToCaptureRotation=" +
|
||||
"${snapshot?.previewToCaptureRotationDegrees} " +
|
||||
"frontFacing=${snapshot?.isFrontFacing} " +
|
||||
"cameraId=${snapshot?.cameraId}",
|
||||
)
|
||||
|
||||
Reference in new issue
Block a user