feat: radiance (5)

This commit is contained in:
zhoubinjia committed 2026-07-20 19:40:31 +08:00
1 parent 7335f17013
commit 95670a7a96
19 files changed
+1374 -1253

No files matched your search

@@ -0,0 +1,63 @@
package com.hinnka.mycamera.utils
import androidx.test.ext.junit.runners.AndroidJUnit4
import java.nio.ByteBuffer
import java.nio.ByteOrder
import org.junit.Assert.assertEquals
import org.junit.Assert.assertTrue
import org.junit.Test
import org.junit.runner.RunWith
@RunWith(AndroidJUnit4::class)
class DirectBufferPixelPackerTest {
@Test
fun rgba16TileIsPackedIntoRgb16DestinationWithoutTouchingOtherPixels() {
val sourceWidth = 3
val sourceHeight = 2
val destinationWidth = 5
val destinationHeight = 4
val source = ByteBuffer.allocateDirect(sourceWidth * sourceHeight * 4 * 2)
.order(ByteOrder.nativeOrder())
val sourceSamples = source.asShortBuffer()
repeat(sourceWidth * sourceHeight) { pixel ->
sourceSamples.put(pixel * 4, (pixel * 10 + 1).toShort())
sourceSamples.put(pixel * 4 + 1, (pixel * 10 + 2).toShort())
sourceSamples.put(pixel * 4 + 2, (pixel * 10 + 3).toShort())
sourceSamples.put(pixel * 4 + 3, (pixel * 10 + 4).toShort())
}
val untouched = 0x7ff0.toShort()
val destination = ByteBuffer.allocateDirect(destinationWidth * destinationHeight * 3 * 2)
.order(ByteOrder.nativeOrder())
val destinationSamples = destination.asShortBuffer()
repeat(destinationSamples.capacity()) { destinationSamples.put(it, untouched) }
assertTrue(
DirectBufferPixelPacker.unpackRgba16TileToRgb16(
source = source,
sourceWidth = sourceWidth,
sourceHeight = sourceHeight,
destination = destination,
destinationWidth = destinationWidth,
destinationHeight = destinationHeight,
destinationLeft = 1,
destinationTop = 1,
)
)
for (y in 0 until destinationHeight) {
for (x in 0 until destinationWidth) {
val destinationPixel = (y * destinationWidth + x) * 3
if (x in 1..3 && y in 1..2) {
val sourcePixel = ((y - 1) * sourceWidth + x - 1) * 10
assertEquals((sourcePixel + 1).toShort(), destinationSamples[destinationPixel])
assertEquals((sourcePixel + 2).toShort(), destinationSamples[destinationPixel + 1])
assertEquals((sourcePixel + 3).toShort(), destinationSamples[destinationPixel + 2])
} else {
assertEquals(untouched, destinationSamples[destinationPixel])
assertEquals(untouched, destinationSamples[destinationPixel + 1])
assertEquals(untouched, destinationSamples[destinationPixel + 2])
}
}
}
}
}
+65
View File
@@ -6,6 +6,7 @@
#include <algorithm>
#include <android/bitmap.h>
#include <array>
#include <arm_neon.h>
#include <cmath>
#include <chrono>
#include <cstring>
@@ -3935,6 +3936,70 @@ Java_com_hinnka_mycamera_utils_DirectBufferAllocator_allocateNative(
return env->NewDirectByteBuffer(ptr, capacity);
}
JNIEXPORT jboolean JNICALL
Java_com_hinnka_mycamera_utils_DirectBufferPixelPacker_unpackRgba16TileToRgb16(
JNIEnv *env, jobject, jobject sourceBuffer, jint sourceWidth,
jint sourceHeight, jobject destinationBuffer, jint destinationWidth,
jint destinationHeight, jint destinationLeft, jint destinationTop) {
if (!sourceBuffer || !destinationBuffer || sourceWidth <= 0 ||
sourceHeight <= 0 || destinationWidth <= 0 || destinationHeight <= 0 ||
destinationLeft < 0 || destinationTop < 0 ||
static_cast<int64_t>(destinationLeft) + sourceWidth > destinationWidth ||
static_cast<int64_t>(destinationTop) + sourceHeight > destinationHeight) {
LOGE("unpackRgba16TileToRgb16: invalid geometry src=%dx%d dst=%dx%d at %d,%d",
sourceWidth, sourceHeight, destinationWidth, destinationHeight,
destinationLeft, destinationTop);
return JNI_FALSE;
}
auto *source = static_cast<const uint16_t *>(
env->GetDirectBufferAddress(sourceBuffer));
auto *destination = static_cast<uint16_t *>(
env->GetDirectBufferAddress(destinationBuffer));
const int64_t sourceRequiredBytes =
static_cast<int64_t>(sourceWidth) * sourceHeight * 4 * sizeof(uint16_t);
const int64_t destinationRequiredBytes =
static_cast<int64_t>(destinationWidth) * destinationHeight * 3 *
sizeof(uint16_t);
const jlong sourceCapacity = env->GetDirectBufferCapacity(sourceBuffer);
const jlong destinationCapacity =
env->GetDirectBufferCapacity(destinationBuffer);
if (!source || !destination || sourceCapacity < sourceRequiredBytes ||
destinationCapacity < destinationRequiredBytes) {
LOGE("unpackRgba16TileToRgb16: invalid buffers src=%p %lld/%lld dst=%p %lld/%lld",
source, static_cast<long long>(sourceCapacity),
static_cast<long long>(sourceRequiredBytes), destination,
static_cast<long long>(destinationCapacity),
static_cast<long long>(destinationRequiredBytes));
return JNI_FALSE;
}
for (int y = 0; y < sourceHeight; ++y) {
const uint16_t *sourceRow =
source + static_cast<size_t>(y) * sourceWidth * 4;
uint16_t *destinationRow =
destination +
(static_cast<size_t>(destinationTop + y) * destinationWidth +
destinationLeft) *
3;
int x = 0;
for (; x + 8 <= sourceWidth; x += 8) {
const uint16x8x4_t rgba = vld4q_u16(sourceRow + x * 4);
uint16x8x3_t rgb;
rgb.val[0] = rgba.val[0];
rgb.val[1] = rgba.val[1];
rgb.val[2] = rgba.val[2];
vst3q_u16(destinationRow + x * 3, rgb);
}
for (; x < sourceWidth; ++x) {
destinationRow[x * 3] = sourceRow[x * 4];
destinationRow[x * 3 + 1] = sourceRow[x * 4 + 1];
destinationRow[x * 3 + 2] = sourceRow[x * 4 + 2];
}
}
return JNI_TRUE;
}
JNIEXPORT jbyteArray JNICALL
Java_com_hinnka_mycamera_utils_SuperResolutionDngWriter_encodeLosslessJpegNative(
JNIEnv *env, jobject, jobject rawBuffer, jint width, jint height,
@@ -42,6 +42,7 @@ import com.hinnka.mycamera.raw.DngEmbeddedProfile
import com.hinnka.mycamera.raw.DngProfileGainTableMap
import com.hinnka.mycamera.raw.DngProfileToneCurve
import com.hinnka.mycamera.raw.RawDefaultCropOverride
import com.hinnka.mycamera.raw.RawDngProfilePreparation
import com.hinnka.mycamera.raw.RawDngProfilePreparationOptions
import com.hinnka.mycamera.raw.RawDngCaptureProfilePreparer
import com.hinnka.mycamera.raw.RawDemosaicProcessor
@@ -2757,8 +2758,72 @@ object GalleryManager {
metadata
}
val fusedBayerBuffer = finalStackResult.fusedBayerBuffer ?: return@withContext
val dngWritten = try {
trySaveStackedRawDng(
var fusedBufferReleased = false
fun releaseFusedBuffer() {
if (fusedBufferReleased) return
fusedBufferReleased = true
finalStackResult.fusedBayerBuffer = null
if (finalStackResult.fusedBayerUsesNativeAllocator) {
LargeDirectBuffer.free(fusedBayerBuffer)
PLog.d(TAG, "Released stacked RAW fused Bayer buffer")
}
}
var updatedMetadata: MediaMetadata = stackedMetadata
val rawSharpening = updatedMetadata.sharpening ?: RawSharpeningDefaults.forCapture(sharpeningValue)
val rawNoiseReduction = resolveNoiseReduction(updatedMetadata, noiseReductionValue)
val rawChromaNoiseReduction = updatedMetadata.chromaNoiseReduction
?: ChromaDenoiseDefaults.forRawCapture(chromaNoiseReductionValue)
var pendingDngWrite: Deferred<Boolean>? = null
val rawResult = try {
val processor = RawDemosaicProcessor.getInstance()
val imageLayout = finalStackResult.bufferLayout.toDngImageLayout()
val inputSamplesPerPixel = finalStackResult.inputColStepSamples
val inputRowStepSamples = finalStackResult.inputRowStepSamples
val dngDefaultCrop = RawProcessor.resolveCameraRawDefaultCrop(
width = finalStackResult.width,
height = finalStackResult.height,
characteristics = characteristics,
captureResult = captureResult,
)
val profileOptions = rawDngProfilePreparationOptions(
context = context,
metadata = stackedMetadata,
width = finalStackResult.width,
height = finalStackResult.height,
defaultCrop = dngDefaultCrop,
aspectRatio = aspectRatio,
rotation = rotation,
capturePreviewThumbnail = capturePreviewThumbnail,
)
val dngProfilePreparation = RawProcessor.prepareRawDngProfile(
rawBuffer = fusedBayerBuffer,
width = finalStackResult.width,
height = finalStackResult.height,
characteristics = characteristics,
captureResult = captureResult,
cfaPattern = rawMetadata.cfaPattern,
blackLevel = finalStackResult.blackLevel,
whiteLevel = stackWhiteLevel,
valueDomain = if (finalStackResult.isNormalizedSensorData) {
RawProcessor.RawBufferValueDomain.NORMALIZED_SENSOR_RANGE
} else {
RawProcessor.RawBufferValueDomain.SENSOR
},
cfaCorrectionMode = stackedMetadata.rawCfaCorrectionMode,
baselineExposureEv = finalStackResult.baselineExposureEv,
imageLayout = imageLayout,
inputRowStepSamples = inputRowStepSamples,
inputColStepSamples = inputSamplesPerPixel,
options = profileOptions,
defaultCrop = dngDefaultCrop,
)
if (dngProfilePreparation == null) {
PLog.e(TAG, "Failed to prepare shared RAW render/DNG profile")
return@withContext
}
suspend fun persistDng(): Boolean = trySaveStackedRawDng(
context = context,
photoId = photoId,
dngFile = dngFile,
@@ -2778,68 +2843,187 @@ object GalleryManager {
metadata = stackedMetadata,
shouldAutoSave = shouldAutoSave,
exportDngWithRawExport = exportDngWithRawExport,
imageLayout = finalStackResult.bufferLayout.toDngImageLayout(),
imageLayout = imageLayout,
compression = finalStackResult.bufferLayout.toDngCompression(),
inputRowStepSamples = finalStackResult.inputRowStepSamples,
inputColStepSamples = finalStackResult.inputColStepSamples,
inputRowStepSamples = inputRowStepSamples,
inputColStepSamples = inputSamplesPerPixel,
baselineExposureEv = finalStackResult.baselineExposureEv,
preparedDngProfile = dngProfilePreparation,
preparedProfileOptions = profileOptions,
)
} finally {
finalStackResult.fusedBayerBuffer = null
if (finalStackResult.fusedBayerUsesNativeAllocator) {
LargeDirectBuffer.free(fusedBayerBuffer)
PLog.d(TAG, "Released stacked RAW fused Bayer buffer")
}
}
if (!dngWritten) {
PLog.e(TAG, "Failed to persist stacked RAW DNG before rendering preview")
return@withContext
}
@Suppress("ExplicitGarbageCollectionCall")
System.gc()
var updatedMetadata: MediaMetadata = stackedMetadata
val rawSharpening = updatedMetadata.sharpening ?: RawSharpeningDefaults.forCapture(sharpeningValue)
val rawNoiseReduction = resolveNoiseReduction(updatedMetadata, noiseReductionValue)
val rawChromaNoiseReduction = updatedMetadata.chromaNoiseReduction
?: ChromaDenoiseDefaults.forRawCapture(chromaNoiseReductionValue)
val rawResult = RawDemosaicProcessor.getInstance().processForHdrSources(
context,
dngFile.absolutePath,
aspectRatio = aspectRatio,
cropRegion = updatedMetadata.cropRegion,
rotation = rotation,
exposureBias = exposureBias ?: 0f,
rawExposureCompensation = updatedMetadata.rawExposureCompensation ?: 0f,
rawHighlightsAdjustment = updatedMetadata.rawHighlightsAdjustment ?: 0f,
rawShadowsAdjustment = updatedMetadata.rawShadowsAdjustment ?: 0f,
rawBlackPointCorrection = updatedMetadata.rawBlackPointCorrection ?: 0f,
rawWhitePointCorrection = updatedMetadata.rawWhitePointCorrection ?: 0f,
rawAutoWhiteBalanceEstimate = resolveRawAutoWhiteBalanceEstimate(context, updatedMetadata),
applyLensShadingCorrection = resolveRawLensShadingCorrectionEnabled(context, updatedMetadata),
rawBlackLevelMode = updatedMetadata.rawBlackLevelMode,
rawCustomBlackLevel = updatedMetadata.rawCustomBlackLevel,
rawWhiteLevelMode = updatedMetadata.rawWhiteLevelMode,
rawCustomWhiteLevel = updatedMetadata.rawCustomWhiteLevel,
sharpeningValue = rawSharpening,
denoiseValue = rawNoiseReduction,
chromaDenoiseValue = rawChromaNoiseReduction,
rawDcpId = updatedMetadata.rawDcpId,
rawRenderingEngine = updatedMetadata.rawRenderingEngine,
rawToneMappingParameters = updatedMetadata.rawToneMappingParameters,
rawCfaCorrectionMode = updatedMetadata.rawCfaCorrectionMode,
rawBlackBorderCrop = updatedMetadata.rawBlackBorderCrop,
spectralFilmStock = updatedMetadata.spectralFilmStock,
spectralFilmPrint = updatedMetadata.spectralFilmPrint,
spectralFilmTuning = SpectralFilmTuning(
cDensityGain = updatedMetadata.spectralFilmCDensityGain,
mDensityGain = updatedMetadata.spectralFilmMDensityGain,
yDensityGain = updatedMetadata.spectralFilmYDensityGain
),
onMetadata = { raw ->
updatedMetadata = updatedMetadata.merge(raw)
suspend fun renderPersistedDng() = processor.processForHdrSources(
context,
dngFile.absolutePath,
aspectRatio = aspectRatio,
cropRegion = updatedMetadata.cropRegion,
rotation = rotation,
exposureBias = exposureBias ?: 0f,
rawExposureCompensation = updatedMetadata.rawExposureCompensation ?: 0f,
rawHighlightsAdjustment = updatedMetadata.rawHighlightsAdjustment ?: 0f,
rawShadowsAdjustment = updatedMetadata.rawShadowsAdjustment ?: 0f,
rawBlackPointCorrection = updatedMetadata.rawBlackPointCorrection ?: 0f,
rawWhitePointCorrection = updatedMetadata.rawWhitePointCorrection ?: 0f,
rawAutoWhiteBalanceEstimate = resolveRawAutoWhiteBalanceEstimate(context, updatedMetadata),
applyLensShadingCorrection = resolveRawLensShadingCorrectionEnabled(context, updatedMetadata),
rawBlackLevelMode = updatedMetadata.rawBlackLevelMode,
rawCustomBlackLevel = updatedMetadata.rawCustomBlackLevel,
rawWhiteLevelMode = updatedMetadata.rawWhiteLevelMode,
rawCustomWhiteLevel = updatedMetadata.rawCustomWhiteLevel,
sharpeningValue = rawSharpening,
denoiseValue = rawNoiseReduction,
chromaDenoiseValue = rawChromaNoiseReduction,
rawDcpId = updatedMetadata.rawDcpId,
rawRenderingEngine = updatedMetadata.rawRenderingEngine,
rawToneMappingParameters = updatedMetadata.rawToneMappingParameters,
rawCfaCorrectionMode = updatedMetadata.rawCfaCorrectionMode,
rawBlackBorderCrop = updatedMetadata.rawBlackBorderCrop,
spectralFilmStock = updatedMetadata.spectralFilmStock,
spectralFilmPrint = updatedMetadata.spectralFilmPrint,
spectralFilmTuning = SpectralFilmTuning(
cDensityGain = updatedMetadata.spectralFilmCDensityGain,
mDensityGain = updatedMetadata.spectralFilmMDensityGain,
yDensityGain = updatedMetadata.spectralFilmYDensityGain,
),
onMetadata = { raw -> updatedMetadata = updatedMetadata.merge(raw) },
)
val directBufferCompatible = finalStackResult.bufferLayout == RawStackBufferLayout.LINEAR_RGB &&
finalStackResult.isNormalizedSensorData &&
inputSamplesPerPixel != null && inputSamplesPerPixel in 3..4 &&
inputRowStepSamples != null &&
RawProcessor.canRenderLinearDngBufferDirectly(
width = finalStackResult.width,
height = finalStackResult.height,
characteristics = characteristics,
)
val renderMetadata = if (directBufferCompatible) {
RawProcessor.buildLinearDngRenderMetadata(
width = finalStackResult.width,
height = finalStackResult.height,
characteristics = characteristics,
captureResult = captureResult,
baseMetadata = rawMetadata,
defaultCrop = dngDefaultCrop,
rotation = rotation,
profilePreparation = dngProfilePreparation,
)
} else {
null
}
) ?: return@withContext
val profileToneMapMode = profileOptions.profileToneMapMode
val embeddedRenderPlan = renderMetadata?.let { preparedMetadata ->
SuperResolutionDngWriter.resolveEmbeddedRenderPlan(
characteristics = characteristics,
metadata = preparedMetadata,
imageLayout = imageLayout,
profileGainTableMap = dngProfilePreparation.profileGainTableMap,
profileToneCurve = profileToneCurveForPgtmMode(profileToneMapMode),
)
}
val canBypassDngPixels = directBufferCompatible &&
renderMetadata != null && embeddedRenderPlan != null
if (canBypassDngPixels) {
val parallelStartMs = System.currentTimeMillis()
val dngWrite = async(Dispatchers.IO) { persistDng() }
pendingDngWrite = dngWrite
val inMemoryResult = processor.processLinearDngBufferForHdrSources(
context = context,
rawData = fusedBayerBuffer,
width = finalStackResult.width,
height = finalStackResult.height,
rowStride = checkNotNull(inputRowStepSamples) * Short.SIZE_BYTES,
samplesPerPixel = checkNotNull(inputSamplesPerPixel),
metadata = checkNotNull(renderMetadata),
aspectRatio = aspectRatio,
cropRegion = updatedMetadata.cropRegion,
rotation = rotation,
exposureBias = exposureBias ?: 0f,
rawExposureCompensation = updatedMetadata.rawExposureCompensation ?: 0f,
rawHighlightsAdjustment = updatedMetadata.rawHighlightsAdjustment ?: 0f,
rawShadowsAdjustment = updatedMetadata.rawShadowsAdjustment ?: 0f,
rawBlackPointCorrection = updatedMetadata.rawBlackPointCorrection ?: 0f,
rawWhitePointCorrection = updatedMetadata.rawWhitePointCorrection ?: 0f,
rawAutoWhiteBalanceEstimate = resolveRawAutoWhiteBalanceEstimate(context, updatedMetadata),
applyLensShadingCorrection = resolveRawLensShadingCorrectionEnabled(context, updatedMetadata),
rawBlackLevelMode = updatedMetadata.rawBlackLevelMode,
rawCustomBlackLevel = updatedMetadata.rawCustomBlackLevel,
rawWhiteLevelMode = updatedMetadata.rawWhiteLevelMode,
rawCustomWhiteLevel = updatedMetadata.rawCustomWhiteLevel,
sharpeningValue = rawSharpening,
denoiseValue = rawNoiseReduction,
chromaDenoiseValue = rawChromaNoiseReduction,
rawDcpId = updatedMetadata.rawDcpId,
embeddedDngRenderPlan = checkNotNull(embeddedRenderPlan),
rawRenderingEngine = updatedMetadata.rawRenderingEngine,
rawToneMappingParameters = updatedMetadata.rawToneMappingParameters,
rawCfaCorrectionMode = updatedMetadata.rawCfaCorrectionMode,
rawBlackBorderCrop = updatedMetadata.rawBlackBorderCrop,
spectralFilmStock = updatedMetadata.spectralFilmStock,
spectralFilmPrint = updatedMetadata.spectralFilmPrint,
spectralFilmTuning = SpectralFilmTuning(
cDensityGain = updatedMetadata.spectralFilmCDensityGain,
mDensityGain = updatedMetadata.spectralFilmMDensityGain,
yDensityGain = updatedMetadata.spectralFilmYDensityGain,
),
onMetadata = { raw -> updatedMetadata = updatedMetadata.merge(raw) },
)
val renderCompletedMs = System.currentTimeMillis()
val dngWritten = dngWrite.await()
val parallelCompletedMs = System.currentTimeMillis()
PLog.i(
TAG,
"RAW_LINEAR_DNG_BYPASS timing render=${renderCompletedMs - parallelStartMs}ms " +
"parallelTotal=${parallelCompletedMs - parallelStartMs}ms " +
"writeTail=${parallelCompletedMs - renderCompletedMs}ms"
)
if (!dngWritten) {
inMemoryResult?.sdrBitmap?.takeIf { !it.isRecycled }?.recycle()
inMemoryResult?.hdrReferenceBitmap?.takeIf { !it.isRecycled }?.recycle()
PLog.e(TAG, "Failed to persist stacked RAW DNG")
return@withContext
}
if (inMemoryResult != null) {
PLog.i(TAG, "RAW_LINEAR_DNG_BYPASS completed with concurrent DNG write")
inMemoryResult
} else {
PLog.w(TAG, "In-memory LinearRaw render failed; using persisted DNG fallback")
releaseFusedBuffer()
@Suppress("ExplicitGarbageCollectionCall")
System.gc()
renderPersistedDng() ?: return@withContext
}
} else {
PLog.w(
TAG,
"RAW_LINEAR_DNG_BYPASS unavailable layout=${finalStackResult.bufferLayout} " +
"normalized=${finalStackResult.isNormalizedSensorData} " +
"bufferCompatible=$directBufferCompatible embeddedProfile=${embeddedRenderPlan != null}; " +
"using persisted DNG"
)
if (!persistDng()) {
PLog.e(TAG, "Failed to persist stacked RAW DNG before rendering preview")
return@withContext
}
releaseFusedBuffer()
@Suppress("ExplicitGarbageCollectionCall")
System.gc()
renderPersistedDng() ?: return@withContext
}
} finally {
pendingDngWrite?.let { write ->
if (!write.isCompleted) {
withContext(NonCancellable) {
runCatching { write.await() }
.onFailure { error ->
PLog.w(TAG, "Waiting for concurrent DNG write failed", error)
}
}
}
}
releaseFusedBuffer()
}
var bitmap = rawResult.sdrBitmap
if (updatedMetadata.isMirrored) {
@@ -3417,6 +3601,8 @@ object GalleryManager {
compression: SuperResolutionDngWriter.Compression = SuperResolutionDngWriter.Compression.UNCOMPRESSED,
inputRowStepSamples: Int? = null,
inputColStepSamples: Int? = null,
preparedDngProfile: RawDngProfilePreparation? = null,
preparedProfileOptions: RawDngProfilePreparationOptions? = null,
): Boolean {
val tempDngFile = File(dngFile.parentFile, "temp_stacked.dng")
val captureInfo = metadata.toCaptureInfo()
@@ -3460,19 +3646,21 @@ object GalleryManager {
compression = compression,
inputRowStepSamples = inputRowStepSamples,
inputColStepSamples = inputColStepSamples,
dngProfilePreparationOptions = rawDngProfilePreparationOptions(
context = context,
metadata = metadata,
width = width,
height = height,
defaultCrop = rawDngDefaultCrop,
aspectRatio = aspectRatio,
rotation = rotation,
capturePreviewThumbnail = capturePreviewThumbnail,
),
dngProfilePreparationOptions = preparedProfileOptions
?: rawDngProfilePreparationOptions(
context = context,
metadata = metadata,
width = width,
height = height,
defaultCrop = rawDngDefaultCrop,
aspectRatio = aspectRatio,
rotation = rotation,
capturePreviewThumbnail = capturePreviewThumbnail,
),
// Carry the Camera2 field of view into the DNG itself. The renderer consumes
// DefaultCrop after OpcodeList3, matching the DNG SDK processing order.
defaultCrop = rawDngDefaultCrop,
preparedDngProfile = preparedDngProfile,
)
}
} catch (e: Throwable) {
@@ -2,9 +2,9 @@ package com.hinnka.mycamera.processor
import android.opengl.GLES30
import android.opengl.GLES31
import com.hinnka.mycamera.utils.DirectBufferPixelPacker
import com.hinnka.mycamera.utils.LargeDirectBuffer
import java.nio.ByteBuffer
import java.nio.ByteOrder
import kotlin.math.acos
import kotlin.math.ceil
import kotlin.math.cos
@@ -518,7 +518,7 @@ internal class GlesRadianceVgnChromaPostprocessor(
val scratch = LargeDirectBuffer.allocate(scratchBytes, "Radiance VGN chroma tile readback")
?: throw IllegalStateException("Unable to allocate Radiance VGN chroma readback scratch")
val allocationMs = System.currentTimeMillis() - allocationStart
val output = outputBuffer.apply { clear() }.order(ByteOrder.nativeOrder()).asShortBuffer()
outputBuffer.clear()
var glReadMs = 0L
var copyMs = 0L
GLES31.glMemoryBarrier(
@@ -555,18 +555,19 @@ internal class GlesRadianceVgnChromaPostprocessor(
backend.checkGlError("Radiance VGN chroma read tile ${tile.index}")
val copyStart = System.currentTimeMillis()
val rgba = scratch.order(ByteOrder.nativeOrder()).asShortBuffer()
for (localY in 0 until tile.outputCore.height) {
for (localX in 0 until tile.outputCore.width) {
val sourceIndex = (localY * tile.outputCore.width + localX) * 4
val targetIndex = (
(tile.outputCore.top + localY) * imageWidth +
tile.outputCore.left + localX
) * 3
output.put(targetIndex, rgba.get(sourceIndex))
output.put(targetIndex + 1, rgba.get(sourceIndex + 1))
output.put(targetIndex + 2, rgba.get(sourceIndex + 2))
}
check(
DirectBufferPixelPacker.unpackRgba16TileToRgb16(
source = scratch,
sourceWidth = tile.outputCore.width,
sourceHeight = tile.outputCore.height,
destination = outputBuffer,
destinationWidth = imageWidth,
destinationHeight = imageHeight,
destinationLeft = tile.outputCore.left,
destinationTop = tile.outputCore.top,
)
) {
"Unable to pack Radiance VGN chroma tile ${tile.index} into RGB16 output"
}
copyMs += System.currentTimeMillis() - copyStart
backend.yieldToUiRenderer()
@@ -476,6 +476,7 @@ data class RawRadianceFusionTuning(
val longClipStart: Float = 0.90f,
val longClipFull: Float = 0.985f,
val longPrecisionWeightCap: Float = 24.0f,
val longNrWeightScale: Float = 3.0f,
val longDetailWeightScale: Float = 0.25f,
val longMergeFactorTarget: Float = 0.70f,
val longFlowFbConsistencyStartPx: Float = 0.75f,
@@ -1163,6 +1164,7 @@ internal object GlesRawRadianceFusionShaders {
uniform float uLongClipStart;
uniform float uLongClipFull;
uniform float uLongPrecisionWeightCap;
uniform float uLongNrWeightScale;
uniform float uLongDetailWeightScale;
uniform float uDenoiseSigmaRawPx;
uniform float uDenoiseSteeringStrength;
@@ -1537,6 +1539,15 @@ internal object GlesRawRadianceFusionShaders {
min(channelPrecision.r, channelPrecision.g),
channelPrecision.b
);
// Long brackets are deliberately allowed to carry more denoise precision than
// a normal non-reference frame. Keep this role boost inside the validated
// precision cap; all geometric, chroma, clipping, and robustness gates remain
// downstream and can still reduce the final weight to zero.
float nrPrecision = uIsLongFrame != 0 ?
min(
sharedPrecision * max(uLongNrWeightScale, 1.0),
precisionUpper
) : sharedPrecision;
float sharedConsistency = min(chromaConfidence.x, chromaConfidence.y);
float sharedHighlight = min(min(highlight.r, highlight.g), highlight.b);
float longNrRoleWeight = uIsLongFrame != 0 ? longClipConfidence : 1.0;
@@ -1555,7 +1566,7 @@ internal object GlesRawRadianceFusionShaders {
longPathConfidence;
$rejectionAssignment
float staticConfidence = denoiseStaticConfidence(tileConfidence.r, robust);
float sharedNrWeight = uFrameWeight * sharedPrecision * sharedConsistency *
float sharedNrWeight = uFrameWeight * nrPrecision * sharedConsistency *
nrCoverage * sharedHighlight * longNrRoleWeight * mix(
1.0,
max(uDenoiseNonReferenceWeightBoost, 1.0),
@@ -686,6 +686,7 @@ class GlesRawStacker(
GlesGpuScheduler.yieldToUiRenderer()
}
val longAlignmentStartMs = System.currentTimeMillis()
val longAlignments = prepareRadianceLongAlignments(
longFrames = activeRadianceLongFrames,
frames = frames,
@@ -693,8 +694,10 @@ class GlesRawStacker(
referencePyramid = refPyramid,
currentPyramid = curPyramid,
)
val longAlignmentElapsedMs = System.currentTimeMillis() - longAlignmentStartMs
// Highlight is prepared last because its composed flow currently occupies the shared
// auxiliary-flow texture. Long flows have already been copied into dedicated caches.
val highlightAlignmentStartMs = System.currentTimeMillis()
val highlightAlignment = activeRadianceHighlightFrame?.let { highlight ->
prepareRadianceHighlightAlignment(
highlight = highlight,
@@ -704,6 +707,15 @@ class GlesRawStacker(
currentPyramid = curPyramid,
)
}
val highlightAlignmentElapsedMs = System.currentTimeMillis() - highlightAlignmentStartMs
RawStackRuntimeDebug.i(TAG) {
"Radiance long/highlight alignment completed " +
"long=${longAlignmentElapsedMs}ms " +
"highlight=${highlightAlignmentElapsedMs}ms " +
"requestedLong=${activeRadianceLongFrames.size} " +
"acceptedLong=${longAlignments.size} " +
"highlightAccepted=${highlightAlignment != null}"
}
val superResolutionDecision = if (superResolutionEnabled) {
decideSuperResolutionOutput(alignedFrameCount)
} else {
@@ -2167,30 +2179,32 @@ class GlesRawStacker(
alignWindowSize = trackingWindow,
label = "Radiance long tracking source-to-anchor $frameIndex",
)
val (forward, reverse) = readFlowTextures(
textures = listOf(resources.forwardSeedTexture, resources.reverseSeedTexture),
textureWidth = resources.seedGridWidth,
textureHeight = resources.seedGridHeight,
label = "Radiance long tracking seeds $frameIndex",
)
val confidenceThreshold = hwmfPrefilter.temporalGraphMinimumSeedConfidence
.coerceIn(0f, 1f)
fun supported(values: FloatArray): Int {
var count = 0
var offset = 3
while (offset < values.size) {
if (values[offset].isFinite() && values[offset] >= confidenceThreshold) count++
offset += 4
if (hwmfDebug.collectMetrics) {
val (forward, reverse) = readFlowTextures(
textures = listOf(resources.forwardSeedTexture, resources.reverseSeedTexture),
textureWidth = resources.seedGridWidth,
textureHeight = resources.seedGridHeight,
label = "Radiance long tracking seeds $frameIndex",
)
val confidenceThreshold = hwmfPrefilter.temporalGraphMinimumSeedConfidence
.coerceIn(0f, 1f)
fun supported(values: FloatArray): Int {
var count = 0
var offset = 3
while (offset < values.size) {
if (values[offset].isFinite() && values[offset] >= confidenceThreshold) count++
offset += 4
}
return count
}
return count
PLog.i(
TAG,
"Radiance long tracking seed frame=$frameIndex " +
"scale=${resources.trackingScale} grid=${resources.seedGridWidth}x" +
"${resources.seedGridHeight} supported=${supported(forward)}/" +
"${supported(reverse)} requiredConfidence=$confidenceThreshold",
)
}
PLog.i(
TAG,
"Radiance long tracking seed frame=$frameIndex " +
"scale=${resources.trackingScale} grid=${resources.seedGridWidth}x" +
"${resources.seedGridHeight} supported=${supported(forward)}/${supported(reverse)} " +
"requiredConfidence=$confidenceThreshold",
)
}
private fun releaseRadianceLongTrackingSeedResources(
@@ -2999,8 +3013,7 @@ class GlesRawStacker(
gridHeight,
"Radiance highlight anchor flow copy",
)
uploadRawTexture(frames.first().image, curRaw, "Radiance highlight reference guide")
buildProxy(curRaw, refProxy, "Radiance highlight reference guide")
buildProxy(refRaw, refProxy, "Radiance highlight reference guide")
propagateRadianceHighlightFlow(
targetTexture = radianceHighlightAnchorFlowTexture,
guideProxyTexture = refProxy,
@@ -3026,125 +3039,178 @@ class GlesRawStacker(
add(0)
acceptedFrames.forEach { frame -> add(frame.frameIndex) }
}.distinct()
return longFrames.mapNotNull { plan ->
val anchorFrameIndex = acceptedNormalIndices.minByOrNull { frameIndex ->
timestampDistance(
frames[frameIndex].sensorTimestampNs,
plan.longFrame.sensorTimestampNs,
)
} ?: return@mapNotNull null
val anchorIsReference = anchorFrameIndex == 0
val anchorAlignment = if (anchorIsReference) {
null
} else {
acceptedFrames.firstOrNull { it.frameIndex == anchorFrameIndex }
?: return@mapNotNull null
}
runCatching {
val anchor = frames[anchorFrameIndex]
val photonExposureRatio = if (
anchor.exposureTimeNs > 0L && plan.longFrame.exposureTimeNs > 0L
) {
plan.longFrame.exposureTimeNs.toFloat() / anchor.exposureTimeNs.toFloat()
val trackingSeeds = createRadianceLongTrackingSeedResources()
var referenceGuideProxyTexture = 0
var activeAnchorFrameIndex = -1
var activeAnchorObservability: RadianceLongObservabilitySummary? = null
var anchorBuildCount = 0
var anchorReuseCount = 0
val alignmentStartMs = System.currentTimeMillis()
return try {
// Keep the output-reference proxy resident while refProxy/current referencePyramid
// hold the temporal anchor. This removes the per-long reference upload/rebuild and
// lets consecutive long frames reuse the exact same anchor pyramid.
referenceGuideProxyTexture = createTexture2D(
planeWidth,
planeHeight,
GLES30.GL_RGBA16F,
GLES30.GL_LINEAR,
)
buildProxy(
refRaw,
referenceGuideProxyTexture,
"Radiance long output reference guide",
noiseModel = frameNoiseModel(frames.first()),
useRegionalObservability = true,
)
val alignments = longFrames.mapNotNull { plan ->
val anchorFrameIndex = acceptedNormalIndices.minByOrNull { frameIndex ->
timestampDistance(
frames[frameIndex].sensorTimestampNs,
plan.longFrame.sensorTimestampNs,
)
} ?: return@mapNotNull null
val anchorIsReference = anchorFrameIndex == 0
val anchorAlignment = if (anchorIsReference) {
null
} else {
Float.NaN
acceptedFrames.firstOrNull { it.frameIndex == anchorFrameIndex }
?: return@mapNotNull null
}
val anchorNoiseModel = frameNoiseModel(anchor)
val longNoiseModel = frameNoiseModel(plan.longFrame)
val trackingSeeds = createRadianceLongTrackingSeedResources()
uploadRawTexture(anchor.image, curRaw, "Radiance long anchor")
val anchorObservability = summarizeRadianceLongObservabilityInput(
frameIndex = plan.sourceFrameIndex,
side = "anchor",
rawTexture = curRaw,
exposureScale = 1f,
noiseModel = anchorNoiseModel,
exposureTimeNs = anchor.exposureTimeNs,
sensitivityIso = anchor.sensitivityIso,
)
buildTrackingProxy(
rawTexture = curRaw,
outputTexture = trackingSeeds.anchorTrackingTexture,
outputWidth = trackingSeeds.trackingWidth,
outputHeight = trackingSeeds.trackingHeight,
levelScale = trackingSeeds.trackingScale,
exposureScale = 1f,
label = "Radiance long anchor ${plan.sourceFrameIndex}",
)
buildProxy(
curRaw,
refProxy,
"Radiance long anchor",
noiseModel = anchorNoiseModel,
useRegionalObservability = true,
)
buildPyramid(referencePyramid)
runCatching {
val anchor = frames[anchorFrameIndex]
val photonExposureRatio = if (
anchor.exposureTimeNs > 0L && plan.longFrame.exposureTimeNs > 0L
) {
plan.longFrame.exposureTimeNs.toFloat() / anchor.exposureTimeNs.toFloat()
} else {
Float.NaN
}
val longNoiseModel = frameNoiseModel(plan.longFrame)
if (activeAnchorFrameIndex != anchorFrameIndex) {
val anchorNoiseModel = frameNoiseModel(anchor)
uploadRawTexture(anchor.image, curRaw, "Radiance long anchor")
activeAnchorObservability = if (hwmfDebug.collectMetrics) {
summarizeRadianceLongObservabilityInput(
frameIndex = plan.sourceFrameIndex,
side = "anchor",
rawTexture = curRaw,
exposureScale = 1f,
noiseModel = anchorNoiseModel,
exposureTimeNs = anchor.exposureTimeNs,
sensitivityIso = anchor.sensitivityIso,
)
} else {
null
}
buildTrackingProxy(
rawTexture = curRaw,
outputTexture = trackingSeeds.anchorTrackingTexture,
outputWidth = trackingSeeds.trackingWidth,
outputHeight = trackingSeeds.trackingHeight,
levelScale = trackingSeeds.trackingScale,
exposureScale = 1f,
label = "Radiance long anchor ${plan.sourceFrameIndex}",
)
buildProxy(
curRaw,
refProxy,
"Radiance long anchor",
noiseModel = anchorNoiseModel,
useRegionalObservability = true,
)
buildPyramid(referencePyramid)
if (!anchorIsReference) {
copyRgbaTexture(
checkNotNull(anchorAlignment).flowTexture,
radianceHighlightAnchorFlowTexture,
gridWidth,
gridHeight,
"Radiance long anchor flow cache",
)
propagateRadianceHighlightFlow(
targetTexture = radianceHighlightAnchorFlowTexture,
guideProxyTexture = referenceGuideProxyTexture,
label = "long-reference-to-anchor",
)
}
activeAnchorFrameIndex = anchorFrameIndex
anchorBuildCount++
} else {
anchorReuseCount++
}
uploadRawTexture(plan.longFrame.image, curRaw, "Radiance long source")
val longObservability = summarizeRadianceLongObservabilityInput(
frameIndex = plan.sourceFrameIndex,
side = "long",
rawTexture = curRaw,
exposureScale = plan.exposureScale,
noiseModel = longNoiseModel,
exposureTimeNs = plan.longFrame.exposureTimeNs,
sensitivityIso = plan.longFrame.sensitivityIso,
)
buildTrackingProxy(
rawTexture = curRaw,
outputTexture = trackingSeeds.longTrackingTexture,
outputWidth = trackingSeeds.trackingWidth,
outputHeight = trackingSeeds.trackingHeight,
levelScale = trackingSeeds.trackingScale,
exposureScale = plan.exposureScale,
label = "Radiance long source ${plan.sourceFrameIndex}",
)
val limitingSide = when {
anchorObservability.observableTileCount <
longObservability.observableTileCount -> "ANCHOR"
longObservability.observableTileCount <
anchorObservability.observableTileCount -> "LONG"
else -> "BALANCED"
}
PLog.i(
TAG,
"Radiance long observability comparison frame=${plan.sourceFrameIndex} " +
"limitingSide=$limitingSide " +
"observableTiles=${anchorObservability.observableTileCount}/" +
"${anchorObservability.totalTileCount}:" +
"${longObservability.observableTileCount}/" +
"${longObservability.totalTileCount} " +
"meanSignal=${anchorObservability.meanSignal}/" +
"${longObservability.meanSignal} " +
"meanDetail=${anchorObservability.meanDetail}/" +
"${longObservability.meanDetail} " +
"meanNoiseSigma=${anchorObservability.meanNoiseSigma}/" +
"${longObservability.meanNoiseSigma} " +
"meanDetailSnr=${anchorObservability.meanDetailSnr}/" +
"${longObservability.meanDetailSnr} " +
"meanAlignmentObservability=" +
"${anchorObservability.meanAlignmentObservability}/" +
"${longObservability.meanAlignmentObservability} " +
"photonRatio=$photonExposureRatio",
)
buildProxy(
curRaw,
curProxy,
"Radiance long exposure-normalized",
exposureScale = plan.exposureScale,
noiseModel = longNoiseModel,
useRegionalObservability = true,
)
buildPyramid(currentPyramid)
buildRadianceLongTrackingSeeds(
frameIndex = plan.sourceFrameIndex,
anchor = anchor,
longFrame = plan.longFrame,
resources = trackingSeeds,
)
uploadRawTexture(plan.longFrame.image, curRaw, "Radiance long source")
val longObservability = if (hwmfDebug.collectMetrics) {
summarizeRadianceLongObservabilityInput(
frameIndex = plan.sourceFrameIndex,
side = "long",
rawTexture = curRaw,
exposureScale = plan.exposureScale,
noiseModel = longNoiseModel,
exposureTimeNs = plan.longFrame.exposureTimeNs,
sensitivityIso = plan.longFrame.sensitivityIso,
)
} else {
null
}
buildTrackingProxy(
rawTexture = curRaw,
outputTexture = trackingSeeds.longTrackingTexture,
outputWidth = trackingSeeds.trackingWidth,
outputHeight = trackingSeeds.trackingHeight,
levelScale = trackingSeeds.trackingScale,
exposureScale = plan.exposureScale,
label = "Radiance long source ${plan.sourceFrameIndex}",
)
val anchorObservability = activeAnchorObservability
if (anchorObservability != null && longObservability != null) {
val limitingSide = when {
anchorObservability.observableTileCount <
longObservability.observableTileCount -> "ANCHOR"
longObservability.observableTileCount <
anchorObservability.observableTileCount -> "LONG"
else -> "BALANCED"
}
PLog.i(
TAG,
"Radiance long observability comparison " +
"frame=${plan.sourceFrameIndex} limitingSide=$limitingSide " +
"observableTiles=${anchorObservability.observableTileCount}/" +
"${anchorObservability.totalTileCount}:" +
"${longObservability.observableTileCount}/" +
"${longObservability.totalTileCount} " +
"meanSignal=${anchorObservability.meanSignal}/" +
"${longObservability.meanSignal} " +
"meanDetail=${anchorObservability.meanDetail}/" +
"${longObservability.meanDetail} " +
"meanNoiseSigma=${anchorObservability.meanNoiseSigma}/" +
"${longObservability.meanNoiseSigma} " +
"meanDetailSnr=${anchorObservability.meanDetailSnr}/" +
"${longObservability.meanDetailSnr} " +
"meanAlignmentObservability=" +
"${anchorObservability.meanAlignmentObservability}/" +
"${longObservability.meanAlignmentObservability} " +
"photonRatio=$photonExposureRatio",
)
}
buildProxy(
curRaw,
curProxy,
"Radiance long exposure-normalized",
exposureScale = plan.exposureScale,
noiseModel = longNoiseModel,
useRegionalObservability = true,
)
buildPyramid(currentPyramid)
buildRadianceLongTrackingSeeds(
frameIndex = plan.sourceFrameIndex,
anchor = anchor,
longFrame = plan.longFrame,
resources = trackingSeeds,
)
val longAlignLevel = alignLevel.coerceAtMost(referencePyramid.lastIndex)
try {
val longAlignLevel = alignLevel.coerceAtMost(referencePyramid.lastIndex)
drawAlignment(
reference = referencePyramid[longAlignLevel],
current = currentPyramid[longAlignLevel],
@@ -3185,179 +3251,171 @@ class GlesRawStacker(
retainGraphSeedEvidence = true,
label = "Radiance long source-to-anchor",
)
} finally {
releaseRadianceLongTrackingSeedResources(trackingSeeds)
}
refineFlow(
referenceProxyTexture = curProxy,
currentProxyTexture = refProxy,
targetFlowTexture = radianceHighlightReverseFlowTexture,
scratchFlowTexture = flowScratchTexture,
)
smoothFlow(radianceHighlightReverseFlowTexture, flowScratchTexture)
logRadianceLongFineFlowEvidence(plan.sourceFrameIndex)
validateRadianceHighlightFlow(
consistencyStartPx = radianceFusionTuning.longFlowFbConsistencyStartPx,
consistencyFullPx = radianceFusionTuning.longFlowFbConsistencyFullPx,
label = "long",
)
propagateRadianceHighlightFlow(
targetTexture = flowTexture,
guideProxyTexture = refProxy,
label = "long-anchor-to-source",
)
// Admit the long frame on the direct anchor -> long edge. The normal anchor has
// already passed its own frame admission, so multiplying its reference -> anchor
// confidence into this global gate would test the same edge twice and makes the
// result depend on which normal frame happened to become the burst reference.
computeRadianceLongEligibility(
frameIndex = plan.sourceFrameIndex,
sourceFlowTexture = flowTexture,
stage = "direct",
)
val directSupport = summarizeRadianceLongFlow(
plan = plan,
anchorFrameIndex = anchorFrameIndex,
sourceFlowTexture = flowTexture,
stage = "direct",
enforceAdmission = true,
photonExposureRatio = photonExposureRatio,
) ?: return@runCatching null
if (!anchorIsReference) {
copyRgbaTexture(
checkNotNull(anchorAlignment).flowTexture,
radianceHighlightAnchorFlowTexture,
gridWidth,
gridHeight,
"Radiance long anchor flow copy",
refineFlow(
referenceProxyTexture = curProxy,
currentProxyTexture = refProxy,
targetFlowTexture = radianceHighlightReverseFlowTexture,
scratchFlowTexture = flowScratchTexture,
)
uploadRawTexture(frames.first().image, curRaw, "Radiance long reference guide")
buildProxy(
curRaw,
refProxy,
"Radiance long reference guide",
noiseModel = frameNoiseModel(frames.first()),
useRegionalObservability = true,
smoothFlow(radianceHighlightReverseFlowTexture, flowScratchTexture)
if (hwmfDebug.collectMetrics) {
logRadianceLongFineFlowEvidence(plan.sourceFrameIndex)
}
validateRadianceHighlightFlow(
consistencyStartPx = radianceFusionTuning.longFlowFbConsistencyStartPx,
consistencyFullPx = radianceFusionTuning.longFlowFbConsistencyFullPx,
label = "long",
)
propagateRadianceHighlightFlow(
targetTexture = radianceHighlightAnchorFlowTexture,
targetTexture = flowTexture,
guideProxyTexture = refProxy,
label = "long-reference-to-anchor",
label = "long-anchor-to-source",
)
}
logRadianceLongCompositionConfidence(
frameIndex = plan.sourceFrameIndex,
anchorIsReference = anchorIsReference,
)
composeRadianceHighlightFlow(
anchorIsReference = anchorIsReference,
useBottleneckConfidence = true,
confidenceStart = radianceFusionTuning.longFlowMinimumConfidence,
confidenceFull = radianceFusionTuning.longFlowFullConfidence,
)
copyRgbaTexture(
radianceHighlightComposedFlowTexture,
flowTexture,
gridWidth,
gridHeight,
"Radiance long composed flow refinement seed",
)
// The temporal graph keeps the hand-shake displacement small by composing
// through the nearest normal anchor. Refine that composed result once more in
// the actual output reference domain so the cached warp does not retain the
// residual error of two independently estimated edges.
refineFlow(
referenceProxyTexture = refProxy,
currentProxyTexture = curProxy,
targetFlowTexture = flowTexture,
scratchFlowTexture = flowScratchTexture,
)
smoothFlow(flowTexture, flowScratchTexture)
computeRadianceLongEligibility(
frameIndex = plan.sourceFrameIndex,
sourceFlowTexture = flowTexture,
stage = "composed-refined",
)
val composedSupport = checkNotNull(
summarizeRadianceLongFlow(
// Admit the long frame on the direct anchor -> long edge. The normal anchor has
// already passed its own frame admission, so multiplying its reference -> anchor
// confidence into this global gate would test the same edge twice and makes the
// result depend on which normal frame happened to become the burst reference.
computeRadianceLongEligibility(
frameIndex = plan.sourceFrameIndex,
sourceFlowTexture = flowTexture,
stage = "direct",
)
val directSupport = summarizeRadianceLongFlow(
plan = plan,
anchorFrameIndex = anchorFrameIndex,
sourceFlowTexture = flowTexture,
stage = "composed-refined",
enforceAdmission = false,
stage = "direct",
enforceAdmission = true,
photonExposureRatio = photonExposureRatio,
),
)
computeRobustness()
computeTileMask()
) ?: return@runCatching null
val cachedFlow = createTexture2D(
gridWidth,
gridHeight,
GLES30.GL_RGBA16F,
GLES30.GL_LINEAR,
)
val cachedRobustness = createTexture2D(
planeWidth,
planeHeight,
GLES30.GL_R16F,
GLES30.GL_NEAREST,
)
val cachedTileMask = createTexture2D(
gridWidth,
gridHeight,
GLES30.GL_RGBA16F,
GLES30.GL_LINEAR,
)
copyRgbaTexture(
flowTexture,
cachedFlow,
gridWidth,
gridHeight,
"Radiance long cached flow ${plan.sourceFrameIndex}",
)
copyScalarTexture(
robustnessTexture,
cachedRobustness,
planeWidth,
planeHeight,
"Radiance long cached robustness ${plan.sourceFrameIndex}",
)
copyRgbaTexture(
tileMaskTexture,
cachedTileMask,
gridWidth,
gridHeight,
"Radiance long cached tile mask ${plan.sourceFrameIndex}",
)
RadianceLongAlignment(
plan = plan,
anchorFrameIndex = anchorFrameIndex,
flowTexture = cachedFlow,
robustnessTexture = cachedRobustness,
tileMaskTexture = cachedTileMask,
// Admission is categorical and requires validated flow. Once admitted,
// robustness and the tile mask own local rejection; sparse seed coverage
// must not attenuate the whole frame a second time.
registrationWeight = directSupport.frameWeight,
detailWeight = directSupport.frameWeight,
precisionWeightCap = directSupport.precisionWeightCap,
minFlowXPlanePx = composedSupport.minFlowXPlanePx,
maxFlowXPlanePx = composedSupport.maxFlowXPlanePx,
minFlowYPlanePx = composedSupport.minFlowYPlanePx,
maxFlowYPlanePx = composedSupport.maxFlowYPlanePx,
validTileFraction = directSupport.validTileFraction,
coveredQuadrants = directSupport.coveredQuadrants,
)
}.onFailure { error ->
PLog.w(
TAG,
"Radiance long alignment failed frame=${plan.sourceFrameIndex}; excluded",
error,
)
}.getOrNull()
if (hwmfDebug.collectMetrics) {
logRadianceLongCompositionConfidence(
frameIndex = plan.sourceFrameIndex,
anchorIsReference = anchorIsReference,
)
}
composeRadianceHighlightFlow(
anchorIsReference = anchorIsReference,
useBottleneckConfidence = true,
confidenceStart = radianceFusionTuning.longFlowMinimumConfidence,
confidenceFull = radianceFusionTuning.longFlowFullConfidence,
)
copyRgbaTexture(
radianceHighlightComposedFlowTexture,
flowTexture,
gridWidth,
gridHeight,
"Radiance long composed flow refinement seed",
)
// The temporal graph keeps the hand-shake displacement small by composing
// through the nearest normal anchor. Refine that composed result once more in
// the actual output reference domain so the cached warp does not retain the
// residual error of two independently estimated edges.
refineFlow(
referenceProxyTexture = referenceGuideProxyTexture,
currentProxyTexture = curProxy,
targetFlowTexture = flowTexture,
scratchFlowTexture = flowScratchTexture,
)
smoothFlow(flowTexture, flowScratchTexture)
computeRadianceLongEligibility(
frameIndex = plan.sourceFrameIndex,
sourceFlowTexture = flowTexture,
stage = "composed-refined",
referenceProxyTexture = referenceGuideProxyTexture,
)
val composedSupport = checkNotNull(
summarizeRadianceLongFlow(
plan = plan,
anchorFrameIndex = anchorFrameIndex,
sourceFlowTexture = flowTexture,
stage = "composed-refined",
enforceAdmission = false,
photonExposureRatio = photonExposureRatio,
),
)
computeRobustness(referenceProxyTexture = referenceGuideProxyTexture)
computeTileMask(referenceProxyTexture = referenceGuideProxyTexture)
val cachedFlow = createTexture2D(
gridWidth,
gridHeight,
GLES30.GL_RGBA16F,
GLES30.GL_LINEAR,
)
val cachedRobustness = createTexture2D(
planeWidth,
planeHeight,
GLES30.GL_R16F,
GLES30.GL_NEAREST,
)
val cachedTileMask = createTexture2D(
gridWidth,
gridHeight,
GLES30.GL_RGBA16F,
GLES30.GL_LINEAR,
)
copyRgbaTexture(
flowTexture,
cachedFlow,
gridWidth,
gridHeight,
"Radiance long cached flow ${plan.sourceFrameIndex}",
)
copyScalarTexture(
robustnessTexture,
cachedRobustness,
planeWidth,
planeHeight,
"Radiance long cached robustness ${plan.sourceFrameIndex}",
)
copyRgbaTexture(
tileMaskTexture,
cachedTileMask,
gridWidth,
gridHeight,
"Radiance long cached tile mask ${plan.sourceFrameIndex}",
)
RadianceLongAlignment(
plan = plan,
anchorFrameIndex = anchorFrameIndex,
flowTexture = cachedFlow,
robustnessTexture = cachedRobustness,
tileMaskTexture = cachedTileMask,
// Admission is categorical and requires validated flow. Once admitted,
// robustness and the tile mask own local rejection; sparse seed coverage
// must not attenuate the whole frame a second time.
registrationWeight = directSupport.frameWeight,
detailWeight = directSupport.frameWeight,
precisionWeightCap = directSupport.precisionWeightCap,
minFlowXPlanePx = composedSupport.minFlowXPlanePx,
maxFlowXPlanePx = composedSupport.maxFlowXPlanePx,
minFlowYPlanePx = composedSupport.minFlowYPlanePx,
maxFlowYPlanePx = composedSupport.maxFlowYPlanePx,
validTileFraction = directSupport.validTileFraction,
coveredQuadrants = directSupport.coveredQuadrants,
)
}.onFailure { error ->
PLog.w(
TAG,
"Radiance long alignment failed frame=${plan.sourceFrameIndex}; excluded",
error,
)
}.getOrNull()
}
RawStackRuntimeDebug.i(TAG) {
"Radiance long alignment cache completed " +
"elapsed=${System.currentTimeMillis() - alignmentStartMs}ms " +
"requested=${longFrames.size} accepted=${alignments.size} " +
"anchorBuilds=$anchorBuildCount anchorReuses=$anchorReuseCount " +
"diagnosticReadback=${hwmfDebug.collectMetrics}"
}
alignments
} finally {
releaseRadianceLongTrackingSeedResources(trackingSeeds)
deleteTexture(referenceGuideProxyTexture)
}
}
@@ -3858,14 +3916,16 @@ class GlesRawStacker(
frameIndex: Int,
sourceFlowTexture: Int,
stage: String,
referenceProxyTexture: Int = refProxy,
currentProxyTexture: Int = curProxy,
) {
val program = radianceLongEligibilityProgram
check(program != 0)
bindFramebufferOutput(flowScratchTexture, "Radiance long $stage eligibility $frameIndex")
GLES30.glViewport(0, 0, gridWidth, gridHeight)
GLES30.glUseProgram(program)
bindTexture(program, "uReferenceProxy", 0, refProxy)
bindTexture(program, "uCurrentProxy", 1, curProxy)
bindTexture(program, "uReferenceProxy", 0, referenceProxyTexture)
bindTexture(program, "uCurrentProxy", 1, currentProxyTexture)
bindTexture(program, "uComposedFlow", 2, sourceFlowTexture)
GLES31.glUniform2i(uniformLocation(program, "uGridSize"), gridWidth, gridHeight)
GLES31.glUniform2i(uniformLocation(program, "uPlaneSize"), planeWidth, planeHeight)
@@ -4093,10 +4153,13 @@ class GlesRawStacker(
)
}
private fun computeRobustness() {
private fun computeRobustness(
referenceProxyTexture: Int = refProxy,
currentProxyTexture: Int = curProxy,
) {
GLES31.glUseProgram(robustnessProgram)
bindTexture(robustnessProgram, "uReference", 0, refProxy)
bindTexture(robustnessProgram, "uCurrent", 1, curProxy)
bindTexture(robustnessProgram, "uReference", 0, referenceProxyTexture)
bindTexture(robustnessProgram, "uCurrent", 1, currentProxyTexture)
bindTexture(robustnessProgram, "uFlowGrid", 2, flowTexture)
bindImage(3, robustnessTexture, GLES31.GL_WRITE_ONLY, GLES30.GL_R32F)
setCommonUniforms(robustnessProgram)
@@ -4109,18 +4172,21 @@ class GlesRawStacker(
checkGlError("computeRobustness")
}
private fun computeTileMask() {
private fun computeTileMask(
referenceProxyTexture: Int = refProxy,
currentProxyTexture: Int = curProxy,
) {
bindFramebufferOutput(tileMaskTexture, "computeTileMask")
GLES30.glViewport(0, 0, gridWidth, gridHeight)
GLES30.glUseProgram(tileMaskProgram)
bindTexture(tileMaskProgram, "uReference", 0, refProxy)
bindTexture(tileMaskProgram, "uReference", 0, referenceProxyTexture)
bindTexture(tileMaskProgram, "uRobustness", 1, robustnessTexture)
if (dualTileConfidence) {
bindTexture(tileMaskProgram, "uFlowGrid", 3, flowTexture)
setDetailConfidenceUniforms(tileMaskProgram)
}
if (visualizeRadianceFusionRejections) {
bindTexture(tileMaskProgram, "uCurrent", 2, curProxy)
bindTexture(tileMaskProgram, "uCurrent", 2, currentProxyTexture)
}
GLES31.glUniform2i(GLES31.glGetUniformLocation(tileMaskProgram, "uPlaneSize"), planeWidth, planeHeight)
GLES31.glUniform2i(GLES31.glGetUniformLocation(tileMaskProgram, "uGridSize"), gridWidth, gridHeight)
@@ -5668,6 +5734,10 @@ class GlesRawStacker(
longPrecisionWeightCap.coerceAtLeast(1f)
},
)
GLES31.glUniform1f(
uniformLocation(accumulateSuperResolutionProgram, "uLongNrWeightScale"),
radianceFusionTuning.longNrWeightScale.coerceAtLeast(1f),
)
GLES31.glUniform1f(
uniformLocation(accumulateSuperResolutionProgram, "uLongDetailWeightScale"),
radianceFusionTuning.longDetailWeightScale.coerceIn(0f, 1f),
@@ -6370,7 +6440,9 @@ class GlesRawStacker(
"longParticipationOverlay=$visualizeRadianceLongParticipation " +
"vgnChromaPostprocess=${chromaPostprocessor != null} " +
"candidates=$candidateFrameCount acceptedNormal=${acceptedFrames.size} " +
"acceptedLong=${longAlignments.size}"
"acceptedLong=${longAlignments.size} " +
"longNrScale=${radianceFusionTuning.longNrWeightScale} " +
"longPrecisionCap=${radianceFusionTuning.longPrecisionWeightCap}"
}
try {
radianceTiles.forEach { tile ->
@@ -1,155 +0,0 @@
package com.hinnka.mycamera.processor
import android.graphics.ImageFormat
import com.hinnka.mycamera.model.SafeImage
import java.nio.ByteOrder
import kotlin.math.abs
import kotlin.math.ln
import kotlin.math.max
import kotlin.math.min
data class RawAlignmentProxyConfig(
val cfaArrangement: Int,
val blackLevelByPosition: FloatArray,
val whiteLevel: Float,
val maxLongEdge: Int = 128,
)
data class RawAlignmentProxy(
val width: Int,
val height: Int,
val lowPass: FloatArray,
val bandPass: FloatArray,
val sharpness: Float,
val sourcePlaneWidth: Int = width,
val sourcePlaneHeight: Int = height,
)
object RawAlignmentProxyBuilder {
fun build(image: SafeImage, config: RawAlignmentProxyConfig): RawAlignmentProxy? {
if (image.format != ImageFormat.RAW_SENSOR || image.width < 4 || image.height < 4) return null
val plane = image.planes.firstOrNull() ?: return null
if (plane.pixelStride < 2 || plane.rowStride <= 0) return null
val sourceCellWidth = image.width / 2
val sourceCellHeight = image.height / 2
if (sourceCellWidth < 2 || sourceCellHeight < 2) return null
val scale = max(
1.0,
max(sourceCellWidth, sourceCellHeight).toDouble() / config.maxLongEdge.coerceAtLeast(32),
)
val width = max(2, (sourceCellWidth / scale).toInt())
val height = max(2, (sourceCellHeight / scale).toInt())
val buffer = plane.buffer.duplicate().order(ByteOrder.nativeOrder())
val positionBlack = FloatArray(4) { index ->
config.blackLevelByPosition.getOrElse(index) {
config.blackLevelByPosition.firstOrNull() ?: 0f
}
}
val greenOffsets = greenOffsets(config.cfaArrangement)
val linear = FloatArray(width * height)
for (y in 0 until height) {
val sourceCellY = min(sourceCellHeight - 1, ((y + 0.5) * sourceCellHeight / height).toInt())
val rawY = sourceCellY * 2
for (x in 0 until width) {
val sourceCellX = min(sourceCellWidth - 1, ((x + 0.5) * sourceCellWidth / width).toInt())
val rawX = sourceCellX * 2
var sum = 0f
for (offset in greenOffsets) {
val px = rawX + offset.first
val py = rawY + offset.second
val positionIndex = offset.second * 2 + offset.first
val byteOffset = py * plane.rowStride + px * plane.pixelStride
if (byteOffset < 0 || byteOffset + 1 >= buffer.limit()) continue
val raw = buffer.getShort(byteOffset).toInt() and 0xffff
val black = positionBlack[positionIndex]
val range = max(config.whiteLevel - black, 1f)
sum += ((raw - black) / range).coerceIn(0f, 1f)
}
val value = sum * 0.5f
linear[y * width + x] = (ln(1.0 + LOG_COMPRESSION * value) / LOG_COMPRESSION_DENOMINATOR).toFloat()
}
}
val lowPass = gaussian5(linear, width, height)
val wide = gaussian5(gaussian5(lowPass, width, height), width, height)
val bandPass = FloatArray(linear.size) { lowPass[it] - wide[it] }
normalizeZeroMeanUnitVariance(lowPass)
normalizeZeroMeanUnitVariance(bandPass)
val sharpness = laplacianSharpness(lowPass, width, height)
return RawAlignmentProxy(
width = width,
height = height,
lowPass = lowPass,
bandPass = bandPass,
sharpness = sharpness,
sourcePlaneWidth = sourceCellWidth,
sourcePlaneHeight = sourceCellHeight,
)
}
private fun greenOffsets(cfaArrangement: Int): Array<Pair<Int, Int>> {
return when (cfaArrangement) {
1, 2 -> arrayOf(0 to 0, 1 to 1) // GRBG / GBRG
else -> arrayOf(1 to 0, 0 to 1) // RGGB / BGGR and safe fallback
}
}
private fun gaussian5(input: FloatArray, width: Int, height: Int): FloatArray {
val temporary = FloatArray(input.size)
val output = FloatArray(input.size)
for (y in 0 until height) {
for (x in 0 until width) {
var sum = 0f
for (k in -2..2) {
val sx = (x + k).coerceIn(0, width - 1)
sum += input[y * width + sx] * GAUSSIAN_5[k + 2]
}
temporary[y * width + x] = sum * GAUSSIAN_5_NORMALIZER
}
}
for (y in 0 until height) {
for (x in 0 until width) {
var sum = 0f
for (k in -2..2) {
val sy = (y + k).coerceIn(0, height - 1)
sum += temporary[sy * width + x] * GAUSSIAN_5[k + 2]
}
output[y * width + x] = sum * GAUSSIAN_5_NORMALIZER
}
}
return output
}
private fun normalizeZeroMeanUnitVariance(values: FloatArray) {
if (values.isEmpty()) return
val mean = values.sum().toDouble() / values.size
var variance = 0.0
values.forEach { value ->
val delta = value - mean
variance += delta * delta
}
val scale = 1.0 / kotlin.math.sqrt(max(variance / values.size, 1.0e-8))
for (index in values.indices) values[index] = ((values[index] - mean) * scale).toFloat()
}
private fun laplacianSharpness(values: FloatArray, width: Int, height: Int): Float {
if (width < 3 || height < 3) return 0f
var sum = 0.0
var count = 0
for (y in 1 until height - 1) {
for (x in 1 until width - 1) {
val center = values[y * width + x]
val laplacian = values[y * width + x - 1] + values[y * width + x + 1] +
values[(y - 1) * width + x] + values[(y + 1) * width + x] - 4f * center
sum += abs(laplacian)
count++
}
}
return if (count > 0) (sum / count).toFloat() else 0f
}
private val GAUSSIAN_5 = floatArrayOf(1f, 4f, 6f, 4f, 1f)
private const val GAUSSIAN_5_NORMALIZER = 1f / 16f
private const val LOG_COMPRESSION = 8.0
private val LOG_COMPRESSION_DENOMINATOR = ln(1.0 + LOG_COMPRESSION)
}
@@ -1,249 +0,0 @@
package com.hinnka.mycamera.processor
import kotlin.math.abs
import kotlin.math.hypot
import kotlin.math.max
data class RawBurstReferencePlan(
val referenceOriginalIndex: Int,
val orderedIndices: IntArray,
val alignmentsToReference: List<RawGlobalAlignment?>,
val preAlignmentsToReference: List<RawFramePreAlignment?>,
val referenceCost: Float,
)
object RawBurstReferencePlanner {
fun plan(
frames: List<RawStackFrame>,
proxyConfig: RawAlignmentProxyConfig,
): RawBurstReferencePlan {
val proxies = frames.map { RawAlignmentProxyBuilder.build(it.image, proxyConfig) }
val gyroRisks = RawBurstGyroSelector.select(frames).blurRiskByIndex
return planProxies(proxies, gyroRisks, frames.map { it.sensorTimestampNs })
}
internal fun planProxies(
proxies: List<RawAlignmentProxy?>,
gyroRisks: FloatArray = FloatArray(proxies.size) { Float.NaN },
sensorTimestampsNs: List<Long> = proxies.indices.map(Int::toLong),
): RawBurstReferencePlan {
if (proxies.isEmpty()) {
return RawBurstReferencePlan(-1, IntArray(0), emptyList(), emptyList(), Float.POSITIVE_INFINITY)
}
val valid = proxies.indices.filter { proxies[it] != null }
if (valid.size < 2) return fallback(proxies.size, valid.firstOrNull() ?: 0)
val candidates = referenceCandidates(proxies, gyroRisks, valid)
var bestReference = candidates.first()
var bestCost = Float.POSITIVE_INFINITY
var bestAlignments: List<RawGlobalAlignment?> = List(proxies.size) { null }
val maxSharpness = valid.maxOf { proxies[it]!!.sharpness }.coerceAtLeast(1.0e-6f)
val medianGyro = gyroRisks
.filter(Float::isFinite)
.sorted()
.let { values ->
if (values.isEmpty()) Float.NaN else values[values.size / 2].coerceAtLeast(1.0e-6f)
}
for (candidate in candidates) {
val reference = proxies[candidate] ?: continue
val alignments = MutableList<RawGlobalAlignment?>(proxies.size) { null }
alignments[candidate] = RawGlobalAlignment(0f, 0f, 0f, 0f, 1f, 1f)
var geometryCost = 0f
var failed = 0
for (index in valid) {
if (index == candidate) continue
val alignment = RawGlobalPreAligner.align(reference, proxies[index]!!)
alignments[index] = alignment
if (alignment == null) {
failed++
geometryCost += FAILED_ALIGNMENT_COST
continue
}
geometryCost += GEOMETRY_TRANSLATION_WEIGHT * hypot(
alignment.dxProxyPx / reference.width,
alignment.dyProxyPx / reference.height,
)
geometryCost += GEOMETRY_ROTATION_WEIGHT * abs(alignment.rotationDegrees)
geometryCost += ALIGNMENT_SCORE_WEIGHT * alignment.score
geometryCost += COVERAGE_WEIGHT * (1f - alignment.coverage)
geometryCost += MARGIN_WEIGHT / max(alignment.margin, MIN_MARGIN)
}
val sharpnessPenalty = SHARPNESS_WEIGHT *
(1f - reference.sharpness / maxSharpness).coerceIn(0f, 1f)
val gyroPenalty = if (medianGyro.isFinite() && gyroRisks.getOrNull(candidate)?.isFinite() == true) {
GYRO_WEIGHT * (gyroRisks[candidate] / medianGyro).coerceIn(0f, 4f)
} else {
UNKNOWN_GYRO_PENALTY
}
val cost = geometryCost / max(1, valid.size - 1) + sharpnessPenalty + gyroPenalty +
failed * FAILED_REFERENCE_PENALTY
if (cost < bestCost) {
bestCost = cost
bestReference = candidate
bestAlignments = alignments
}
}
val remainder = proxies.indices
.asSequence()
.filter { it != bestReference }
.sortedWith(
compareBy<Int> { bestAlignments[it] == null }
.thenBy { index ->
bestAlignments[index]?.let { hypot(it.dxProxyPx, it.dyProxyPx) }
?: Float.POSITIVE_INFINITY
}
.thenBy { it }
)
.toList()
val directPreAlignments = bestAlignments.mapIndexed { index, alignment ->
val proxy = proxies[index]
if (index == bestReference) {
RawFramePreAlignment.Identity
} else if (alignment != null && proxy != null) {
alignment.toFramePreAlignment(proxy)
} else {
null
}
}
val graphPreAlignments = solveGlobalTemporalGraph(
proxies = proxies,
sensorTimestampsNs = sensorTimestampsNs,
referenceIndex = bestReference,
directAlignments = bestAlignments,
directPreAlignments = directPreAlignments,
)
return RawBurstReferencePlan(
referenceOriginalIndex = bestReference,
orderedIndices = intArrayOf(bestReference, *remainder.toIntArray()),
alignmentsToReference = bestAlignments,
preAlignmentsToReference = graphPreAlignments ?: directPreAlignments,
referenceCost = bestCost,
)
}
private fun referenceCandidates(
proxies: List<RawAlignmentProxy?>,
gyroRisks: FloatArray,
valid: List<Int>,
): List<Int> {
val candidates = LinkedHashSet<Int>()
candidates += valid[valid.size / 2]
valid.sortedByDescending { proxies[it]!!.sharpness }.take(2).forEach(candidates::add)
valid.asSequence()
.filter { gyroRisks.getOrNull(it)?.isFinite() == true }
.sortedBy { gyroRisks[it] }
.take(2)
.forEach(candidates::add)
if (candidates.size < MAX_REFERENCE_CANDIDATES) {
candidates += valid.first()
candidates += valid.last()
}
return candidates.take(MAX_REFERENCE_CANDIDATES)
}
private fun fallback(frameCount: Int, reference: Int): RawBurstReferencePlan {
val remainder = (0 until frameCount).filter { it != reference }
return RawBurstReferencePlan(
referenceOriginalIndex = reference,
orderedIndices = intArrayOf(reference, *remainder.toIntArray()),
alignmentsToReference = List(frameCount) { null },
preAlignmentsToReference = List(frameCount) { index ->
if (index == reference) RawFramePreAlignment.Identity else null
},
referenceCost = Float.POSITIVE_INFINITY,
)
}
private fun RawGlobalAlignment.toFramePreAlignment(proxy: RawAlignmentProxy): RawFramePreAlignment {
return RawFramePreAlignment(
translationXPlanePx = dxProxyPx * proxy.sourcePlaneWidth / proxy.width.coerceAtLeast(1),
translationYPlanePx = dyProxyPx * proxy.sourcePlaneHeight / proxy.height.coerceAtLeast(1),
rotationDegrees = rotationDegrees,
confidence = confidence(),
)
}
private fun RawGlobalAlignment.confidence(): Float {
val scoreConfidence = (1f - score / MAX_CONFIDENT_SCORE).coerceIn(0f, 1f)
val marginConfidence = (margin / FULL_CONFIDENCE_MARGIN).coerceIn(0f, 1f)
return coverage.coerceIn(0f, 1f) * scoreConfidence * marginConfidence
}
private fun solveGlobalTemporalGraph(
proxies: List<RawAlignmentProxy?>,
sensorTimestampsNs: List<Long>,
referenceIndex: Int,
directAlignments: List<RawGlobalAlignment?>,
directPreAlignments: List<RawFramePreAlignment?>,
): List<RawFramePreAlignment?>? {
if (sensorTimestampsNs.size != proxies.size || proxies.size < 3) return null
val graph = RawTemporalAlignmentGraphBuilder.build(
sensorTimestampsNs = sensorTimestampsNs,
referenceFrameIndex = referenceIndex,
includeSkipOne = proxies.size <= MAX_SKIP_ONE_FRAME_COUNT,
)
val observations = graph.edges.mapNotNull { edge ->
val fromProxy = proxies[edge.fromFrameIndex] ?: return@mapNotNull null
val toProxy = proxies[edge.toFrameIndex] ?: return@mapNotNull null
val alignment = if (
edge.type == RawTemporalEdgeType.REFERENCE && edge.fromFrameIndex == referenceIndex
) {
directAlignments[edge.toFrameIndex]
} else {
RawGlobalPreAligner.align(fromProxy, toProxy)
} ?: return@mapNotNull null
val preAlignment = alignment.toFramePreAlignment(fromProxy)
if (preAlignment.confidence < MIN_GRAPH_EDGE_CONFIDENCE) return@mapNotNull null
RawTemporalEdgeObservation(
edge = edge,
dxPlanePx = preAlignment.translationXPlanePx,
dyPlanePx = preAlignment.translationYPlanePx,
confidence = preAlignment.confidence,
)
}
val solution = RawTemporalAlignmentSolver.solve(graph, observations) ?: return null
if (solution.acceptedObservationIndices.size < proxies.size - 1) return null
val accepted = solution.acceptedObservationIndices.toSet()
return List(proxies.size) { frameIndex ->
if (frameIndex == referenceIndex) return@List RawFramePreAlignment.Identity
val incidentConfidence = observations.indices.asSequence()
.filter { it in accepted }
.map { observations[it] }
.filter { observation ->
observation.edge.fromFrameIndex == frameIndex || observation.edge.toFrameIndex == frameIndex
}
.map { it.confidence }
.toList()
.average()
.takeIf(Double::isFinite)
?.toFloat()
?: return@List directPreAlignments[frameIndex]
val position = solution.positions[frameIndex]
RawFramePreAlignment(
translationXPlanePx = position.xPlanePx,
translationYPlanePx = position.yPlanePx,
rotationDegrees = directPreAlignments[frameIndex]?.rotationDegrees ?: 0f,
confidence = incidentConfidence,
)
}
}
private const val MAX_REFERENCE_CANDIDATES = 4
private const val GEOMETRY_TRANSLATION_WEIGHT = 8f
private const val GEOMETRY_ROTATION_WEIGHT = 0.08f
private const val ALIGNMENT_SCORE_WEIGHT = 0.7f
private const val COVERAGE_WEIGHT = 0.3f
private const val MARGIN_WEIGHT = 0.0005f
private const val MIN_MARGIN = 0.002f
private const val SHARPNESS_WEIGHT = 0.4f
private const val GYRO_WEIGHT = 0.15f
private const val UNKNOWN_GYRO_PENALTY = 0.08f
private const val FAILED_ALIGNMENT_COST = 2f
private const val FAILED_REFERENCE_PENALTY = 0.5f
private const val MAX_CONFIDENT_SCORE = 0.8f
private const val FULL_CONFIDENCE_MARGIN = 0.02f
private const val MIN_GRAPH_EDGE_CONFIDENCE = 0.02f
private const val MAX_SKIP_ONE_FRAME_COUNT = 8
}
@@ -1,164 +0,0 @@
package com.hinnka.mycamera.processor
import kotlin.math.abs
import kotlin.math.cos
import kotlin.math.max
import kotlin.math.sin
import kotlin.math.sqrt
data class RawGlobalAlignment(
val dxProxyPx: Float,
val dyProxyPx: Float,
val rotationDegrees: Float,
val score: Float,
val margin: Float,
val coverage: Float,
)
object RawGlobalPreAligner {
fun align(reference: RawAlignmentProxy, current: RawAlignmentProxy): RawGlobalAlignment? {
if (reference.width != current.width || reference.height != current.height) return null
if (reference.width < 32 || reference.height < 32) return null
var best = Candidate.INVALID
var second = Candidate.INVALID
for (rotation in COARSE_ROTATIONS) {
var dy = -COARSE_RADIUS
while (dy <= COARSE_RADIUS) {
var dx = -COARSE_RADIUS
while (dx <= COARSE_RADIUS) {
val candidate = score(reference, current, dx.toFloat(), dy.toFloat(), rotation, COARSE_SAMPLE_STEP)
if (candidate.score < best.score) {
second = best
best = candidate
} else if (candidate.score < second.score) {
second = candidate
}
dx += COARSE_SHIFT_STEP
}
dy += COARSE_SHIFT_STEP
}
}
if (!best.score.isFinite()) return null
val refinedCandidates = ArrayList<Candidate>()
for (rotationOffset in FINE_ROTATION_OFFSETS) {
for (dyOffset in -FINE_RADIUS..FINE_RADIUS) {
for (dxOffset in -FINE_RADIUS..FINE_RADIUS) {
refinedCandidates += score(
reference,
current,
best.dx + dxOffset,
best.dy + dyOffset,
best.rotationDegrees + rotationOffset,
FINE_SAMPLE_STEP,
)
}
}
}
val sorted = refinedCandidates.filter { it.score.isFinite() }.sortedBy { it.score }
if (sorted.isEmpty()) return null
best = sorted.first()
second = sorted.firstOrNull { candidate ->
abs(candidate.dx - best.dx) >= 1f || abs(candidate.dy - best.dy) >= 1f ||
abs(candidate.rotationDegrees - best.rotationDegrees) >= 0.25f
} ?: second
return RawGlobalAlignment(
dxProxyPx = best.dx,
dyProxyPx = best.dy,
rotationDegrees = best.rotationDegrees,
score = best.score,
margin = (second.score - best.score).coerceAtLeast(0f),
coverage = best.coverage,
)
}
private fun score(
reference: RawAlignmentProxy,
current: RawAlignmentProxy,
dx: Float,
dy: Float,
rotationDegrees: Float,
sampleStep: Int,
): Candidate {
val width = reference.width
val height = reference.height
val radians = Math.toRadians(rotationDegrees.toDouble())
val cosTheta = cos(radians).toFloat()
val sinTheta = sin(radians).toFloat()
val centerX = (width - 1) * 0.5f
val centerY = (height - 1) * 0.5f
val border = max(4, minOf(width, height) / 12)
var sumReference2 = 0.0
var sumCurrent2 = 0.0
var sumCross = 0.0
var count = 0
var possible = 0
var y = border
while (y < height - border) {
var x = border
while (x < width - border) {
possible++
val centeredX = x - centerX
val centeredY = y - centerY
val sourceX = cosTheta * centeredX - sinTheta * centeredY + centerX + dx
val sourceY = sinTheta * centeredX + cosTheta * centeredY + centerY + dy
if (sourceX >= 1f && sourceY >= 1f && sourceX < width - 2f && sourceY < height - 2f) {
val refLow = reference.lowPass[y * width + x]
val curLow = bilinear(current.lowPass, width, height, sourceX, sourceY)
val refBand = reference.bandPass[y * width + x]
val curBand = bilinear(current.bandPass, width, height, sourceX, sourceY)
val ref = refLow + BAND_WEIGHT * refBand
val cur = curLow + BAND_WEIGHT * curBand
sumReference2 += ref * ref
sumCurrent2 += cur * cur
sumCross += ref * cur
count++
}
x += sampleStep
}
y += sampleStep
}
if (count < MIN_SAMPLES || possible == 0) return Candidate.INVALID
val denominator = sqrt(max(sumReference2 * sumCurrent2, 1.0e-12))
val correlation = (sumCross / denominator).coerceIn(-1.0, 1.0)
val coverage = count.toFloat() / possible
val cost = (1.0 - correlation).toFloat() + COVERAGE_PENALTY * (1f - coverage)
return Candidate(dx, dy, rotationDegrees, cost, coverage)
}
private fun bilinear(values: FloatArray, width: Int, height: Int, x: Float, y: Float): Float {
val x0 = x.toInt().coerceIn(0, width - 1)
val y0 = y.toInt().coerceIn(0, height - 1)
val x1 = (x0 + 1).coerceAtMost(width - 1)
val y1 = (y0 + 1).coerceAtMost(height - 1)
val fx = x - x0
val fy = y - y0
val a = values[y0 * width + x0] * (1f - fx) + values[y0 * width + x1] * fx
val b = values[y1 * width + x0] * (1f - fx) + values[y1 * width + x1] * fx
return a * (1f - fy) + b * fy
}
private data class Candidate(
val dx: Float,
val dy: Float,
val rotationDegrees: Float,
val score: Float,
val coverage: Float,
) {
companion object {
val INVALID = Candidate(0f, 0f, 0f, Float.POSITIVE_INFINITY, 0f)
}
}
private val COARSE_ROTATIONS = floatArrayOf(-1.0f, -0.5f, 0f, 0.5f, 1.0f)
private val FINE_ROTATION_OFFSETS = floatArrayOf(-0.25f, 0f, 0.25f)
private const val COARSE_RADIUS = 10
private const val COARSE_SHIFT_STEP = 2
private const val FINE_RADIUS = 2
private const val COARSE_SAMPLE_STEP = 4
private const val FINE_SAMPLE_STEP = 3
private const val BAND_WEIGHT = 0.75f
private const val COVERAGE_PENALTY = 0.15f
private const val MIN_SAMPLES = 256
}
@@ -991,6 +991,136 @@ class RawDemosaicProcessor {
}
}
/**
* Renders the original LinearRaw RGB buffer with the same prepared metadata/profile passed
* to the DNG writer. This keeps the established DNG rendering contract while avoiding
* lossless-JPEG decompression and the native pixel-buffer copy performed by [processDngNative].
*
* BaselineExposure, PGTM and the embedded color/tone plan are prepared once and shared by
* both consumers; the only permitted difference is numeric quantization during TIFF write.
*/
suspend fun processLinearDngBufferForHdrSources(
context: Context,
rawData: ByteBuffer,
width: Int,
height: Int,
rowStride: Int,
samplesPerPixel: Int,
metadata: RawMetadata,
aspectRatio: AspectRatio?,
cropRegion: Rect?,
rotation: Int,
exposureBias: Float = 0f,
rawExposureCompensation: Float = 0f,
rawHighlightsAdjustment: Float = 0f,
rawShadowsAdjustment: Float = 0f,
rawBlackPointCorrection: Float = 0f,
rawWhitePointCorrection: Float = 0f,
rawAutoWhiteBalanceEstimate: Boolean = false,
applyLensShadingCorrection: Boolean = true,
rawBlackLevelMode: String? = null,
rawCustomBlackLevel: Float? = null,
rawWhiteLevelMode: String? = null,
rawCustomWhiteLevel: Float? = null,
sharpeningValue: Float = 0f,
denoiseValue: Float? = null,
chromaDenoiseValue: Float? = null,
rawDcpId: String? = null,
dcpRenderPlan: DcpRenderPlan? = null,
embeddedDngRenderPlan: DcpRenderPlan,
spectralFilmStock: String? = null,
spectralFilmPrint: String? = null,
spectralFilmTuning: SpectralFilmTuning = SpectralFilmTuning.DEFAULT,
rawRenderingEngine: RawRenderingEngine = RawRenderingEngine.AdobeCurve,
rawToneMappingParameters: RawToneMappingParameters = RawToneMappingParameters.DEFAULT,
rawCfaCorrectionMode: String? = null,
rawBlackBorderCrop: RawBlackBorderCrop = RawBlackBorderCrop(),
onMetadata: ((RawMetadata) -> Unit)? = null,
): RawHdrRenderResult? = withContext(glDispatcher) {
if (samplesPerPixel !in 3..4 || width <= 0 || height <= 0 || rowStride <= 0) {
PLog.e(
TAG,
"Invalid in-memory LinearRaw DNG source: ${width}x$height " +
"samplesPerPixel=$samplesPerPixel rowStride=$rowStride"
)
return@withContext null
}
val renderMetadata = applyDngMetadataOverrides(
metadata = metadata,
rawBlackLevelMode = rawBlackLevelMode,
rawCustomBlackLevel = rawCustomBlackLevel,
rawWhiteLevelMode = rawWhiteLevelMode,
rawCustomWhiteLevel = rawCustomWhiteLevel,
rawCfaCorrectionMode = rawCfaCorrectionMode,
).copy(
colorCorrectionMatrix = embeddedDngRenderPlan.colorCorrectionMatrix.copyOf(),
cameraWhite = embeddedDngRenderPlan.cameraWhite.copyOf(),
exposureBias = exposureBias,
)
onMetadata?.invoke(renderMetadata)
PLog.i(
TAG,
"RAW_LINEAR_DNG_BYPASS source=IN_MEMORY_RGB16 metadata=SHARED_DNG_PARAMS " +
"size=${width}x$height samplesPerPixel=$samplesPerPixel rowStride=$rowStride " +
"baselineExposure=${renderMetadata.baselineExposure} " +
"defaultCrop=${renderMetadata.defaultCrop} " +
"black=${renderMetadata.blackLevel.contentToString()} white=${renderMetadata.whiteLevel} " +
"wb=${renderMetadata.whiteBalanceGains.contentToString()} " +
"cameraWhite=${renderMetadata.cameraWhite.contentToString()} " +
"ccm=${renderMetadata.colorCorrectionMatrix.contentToString()} " +
"noise=${renderMetadata.channelNoiseProfile.contentToString()} " +
"pgtm=${renderMetadata.profileGainTableMap?.let {
"${it.mapPointsH}x${it.mapPointsV}x${it.mapPointsN}:tag=${it.sourceTag}"
} ?: "none"} profile=${embeddedDngRenderPlan.profileName} " +
"rawAwbIgnoredForLinear=$rawAutoWhiteBalanceEstimate"
)
try {
processInternal(
context = context,
rawData = rawData.duplicate().order(ByteOrder.nativeOrder()),
width = width,
height = height,
rowStride = rowStride,
samplesPerPixel = samplesPerPixel,
metadata = renderMetadata,
aspectRatio = aspectRatio,
cropRegion = cropRegion,
rotation = rotation,
exposureBias = exposureBias,
rawExposureCompensation = rawExposureCompensation,
rawHighlightsAdjustment = rawHighlightsAdjustment,
rawShadowsAdjustment = rawShadowsAdjustment,
rawBlackPointCorrection = rawBlackPointCorrection,
rawWhitePointCorrection = rawWhitePointCorrection,
rawAutoWhiteBalanceEstimate = rawAutoWhiteBalanceEstimate,
applyLensShadingCorrection = applyLensShadingCorrection,
rawBlackLevelMode = rawBlackLevelMode,
rawCustomBlackLevel = rawCustomBlackLevel,
rawWhiteLevelMode = rawWhiteLevelMode,
rawCustomWhiteLevel = rawCustomWhiteLevel,
sharpeningValue = sharpeningValue,
denoiseValue = denoiseValue,
chromaDenoiseValue = chromaDenoiseValue,
rawDcpId = rawDcpId,
dcpRenderPlan = dcpRenderPlan,
spectralFilmStock = spectralFilmStock,
spectralFilmPrint = spectralFilmPrint,
spectralFilmTuning = spectralFilmTuning,
rawRenderingEngine = rawRenderingEngine,
rawToneMappingParameters = rawToneMappingParameters,
rawCfaCorrectionMode = rawCfaCorrectionMode,
rawBlackBorderCrop = rawBlackBorderCrop,
includeHdrReference = true,
sourceDngRenderPlan = embeddedDngRenderPlan,
defaultCropIsAuthoritative = true,
)
} catch (e: Exception) {
PLog.e(TAG, "Failed to process in-memory LinearRaw DNG source", e)
null
}
}
/**
* 内部处理方法(共享的核心处理逻辑)
*/
@@ -1036,6 +1166,8 @@ class RawDemosaicProcessor {
captureProfileToneMapMode: RawProfileToneMapMode? = null,
captureProfileStatsBounds: Rect? = null,
onCaptureProfilePrepared: ((RawDngCaptureProfileResult?) -> Unit)? = null,
sourceDngRenderPlan: DcpRenderPlan? = null,
defaultCropIsAuthoritative: Boolean = false,
): RawHdrRenderResult? = withContext(glDispatcher) {
var actualRawData = rawData
var actualWidth = width
@@ -1050,7 +1182,7 @@ class RawDemosaicProcessor {
val requestedColorEngine = rawRenderingEngine
val hasDcpSelection = dcpRenderPlan != null || rawDcpId != null
val profileWorkingColorSpace = ColorSpace.ProPhoto
var embeddedDngRenderPlan: DcpRenderPlan? = null
var embeddedDngRenderPlan: DcpRenderPlan? = sourceDngRenderPlan
if (dngFile != null) {
val hasClassicTiffHeader = DngProfileGainTableMap.hasClassicTiffHeader(dngFile)
@@ -1189,7 +1321,9 @@ class RawDemosaicProcessor {
metadataDefaultCrop = actualMetadata.defaultCrop
)
val effectiveDefaultCrop = rawBlackBorderDefaultCrop ?: actualMetadata.defaultCrop
val renderCropRegion = if (dngFile != null && effectiveDefaultCrop != null) {
val renderCropRegion = if (
(dngFile != null || defaultCropIsAuthoritative) && effectiveDefaultCrop != null
) {
if (cropRegion != null) {
PLog.d(TAG, "DNG DefaultCrop is authoritative; ignoring legacy Camera2 crop=$cropRegion")
}
@@ -29,7 +29,7 @@ data class RawDngCaptureProfileResult(
)
/** BaselineExposure and optional PGTM prepared before the DNG writer starts. */
internal data class RawDngProfilePreparation(
data class RawDngProfilePreparation(
val baselineExposureEv: Float,
val profileGainTableMap: DngProfileGainTableMap?,
)
@@ -0,0 +1,26 @@
package com.hinnka.mycamera.utils
import java.nio.ByteBuffer
/**
* Bulk pixel-layout transforms between native direct buffers.
*
* These transforms must stay out of per-pixel Kotlin loops: direct-buffer absolute access carries
* enough JNI and bounds-check overhead to dominate a full-resolution RAW readback.
*/
object DirectBufferPixelPacker {
init {
System.loadLibrary("my-native-lib")
}
external fun unpackRgba16TileToRgb16(
source: ByteBuffer,
sourceWidth: Int,
sourceHeight: Int,
destination: ByteBuffer,
destinationWidth: Int,
destinationHeight: Int,
destinationLeft: Int,
destinationTop: Int,
): Boolean
}
@@ -14,6 +14,7 @@ import com.hinnka.mycamera.raw.DngProfileGainTableMap
import com.hinnka.mycamera.raw.DngBaselineExposure
import com.hinnka.mycamera.raw.DngProfileToneCurve
import com.hinnka.mycamera.raw.RawCfaCorrection
import com.hinnka.mycamera.raw.RawDngProfilePreparation
import com.hinnka.mycamera.raw.RawDngProfilePreparationOptions
import com.hinnka.mycamera.raw.RawMetadata
import com.hinnka.mycamera.raw.RawDemosaicProcessor
@@ -71,6 +72,144 @@ object RawProcessor {
return RawWhiteLevelCorrection.resolveWhiteLevel(defaultWhiteLevel, whiteLevelMode, customWhiteLevel)
}
/**
* The custom LinearRaw DNG writer stores the full buffer as its active image unless the
* buffer is the physical pixel array with a smaller pre-correction active area. In that
* exceptional case LibRaw crops the file during unpack, so the original buffer cannot be
* substituted without applying the same crop first.
*/
fun canRenderLinearDngBufferDirectly(
width: Int,
height: Int,
characteristics: CameraCharacteristics,
): Boolean {
val pixelArray = characteristics.get(CameraCharacteristics.SENSOR_INFO_PIXEL_ARRAY_SIZE)
val activeArray = characteristics.get(
CameraCharacteristics.SENSOR_INFO_PRE_CORRECTION_ACTIVE_ARRAY_SIZE
)
val matchesPixelArray = pixelArray?.width == width && pixelArray.height == height
if (!matchesPixelArray || activeArray == null) return true
return activeArray.left == 0 && activeArray.top == 0 &&
activeArray.right == width && activeArray.bottom == height
}
/**
* Builds the metadata that LibRaw would expose after reopening a LinearRaw RGB DNG written
* by [saveRawBufferToDng]. Pixel-domain fields deliberately follow the serialized DNG rather
* than the sensor input: normalized black/white levels, no CFA lens-shading opcode, local
* active area, DNG three-plane noise profile, and the prepared BaselineExposure/PGTM.
*/
fun buildLinearDngRenderMetadata(
width: Int,
height: Int,
characteristics: CameraCharacteristics,
captureResult: CaptureResult,
baseMetadata: RawMetadata,
defaultCrop: Rect,
rotation: Int,
profilePreparation: RawDngProfilePreparation,
): RawMetadata {
val dngWhiteBalance = resolveDngWriterWhiteBalance(captureResult)
val dngChannelNoise = resolveDngWriterNoiseProfile(captureResult)
val metadata = RawMetadata.create(
width = width,
height = height,
characteristics = characteristics,
captureResult = captureResult,
userExposureCompensation = baseMetadata.exposureBias,
colorSpace = com.hinnka.mycamera.raw.ColorSpace.ProPhoto,
)
return metadata.copy(
width = width,
height = height,
blackLevel = floatArrayOf(0f, 0f, 0f, 0f),
whiteLevel = 65535f,
whiteBalanceGains = dngWhiteBalance,
preMul = dngWhiteBalance.copyOf(),
lensShadingMap = null,
lensShadingMapWidth = 0,
lensShadingMapHeight = 0,
lensShadingMapGrid = null,
postRawSensitivityBoost = 1f,
baselineExposure = DngBaselineExposure.sanitize(profilePreparation.baselineExposureEv),
shadowScale = 1f,
noiseProfile = RawMetadata.averageNoiseProfile(dngChannelNoise),
channelNoiseProfile = dngChannelNoise,
afRegions = null,
activeArray = Rect(0, 0, width, height),
defaultCrop = Rect(defaultCrop),
aeMode = CaptureResult.CONTROL_AE_MODE_ON,
exposureCompensation = 0f,
exposureBias = baseMetadata.exposureBias,
frameCount = 1,
rotation = rotation,
profileGainTableMap = profilePreparation.profileGainTableMap,
)
}
private fun resolveDngWriterWhiteBalance(captureResult: CaptureResult): FloatArray {
val neutral = captureResult.get(CaptureResult.SENSOR_NEUTRAL_COLOR_POINT)
?.takeIf { it.size >= 3 }
?.take(3)
?.map { value -> value.numerator.toDouble() / value.denominator.toDouble() }
?.takeIf { values -> values.all { it.isFinite() && it > 0.0 } }
if (neutral != null) {
val green = neutral[1]
return floatArrayOf(
(green / neutral[0]).toFloat(),
1f,
1f,
(green / neutral[2]).toFloat(),
)
}
val gains = captureResult.get(CaptureResult.COLOR_CORRECTION_GAINS)
?: return floatArrayOf(1f, 1f, 1f, 1f)
val green = ((gains.greenEven + gains.greenOdd) * 0.5f)
.takeIf { it.isFinite() && it > 0f }
?: 1f
return floatArrayOf(
gains.red.takeIf { it.isFinite() && it > 0f }?.div(green) ?: 1f,
1f,
1f,
gains.blue.takeIf { it.isFinite() && it > 0f }?.div(green) ?: 1f,
)
}
private fun resolveDngWriterNoiseProfile(captureResult: CaptureResult): FloatArray {
val source = captureResult.get(CaptureResult.SENSOR_NOISE_PROFILE)
?.takeIf { it.size >= 3 }
?: return floatArrayOf(0f, 0f)
fun safePair(index: Int): Pair<Float, Float>? {
val pair = source.getOrNull(index) ?: return null
val slope = pair.first.takeIf { it.isFinite() && it >= 0.0 }?.toFloat() ?: return null
val offset = pair.second.takeIf { it.isFinite() && it >= 0.0 }?.toFloat() ?: return null
return slope to offset
}
val red = safePair(0) ?: return floatArrayOf(0f, 0f)
val green = if (source.size >= 4) {
val even = safePair(1) ?: return floatArrayOf(0f, 0f)
val odd = safePair(2) ?: return floatArrayOf(0f, 0f)
(even.first + odd.first) * 0.5f to (even.second + odd.second) * 0.5f
} else {
safePair(1) ?: return floatArrayOf(0f, 0f)
}
val blue = safePair(if (source.size >= 4) 3 else 2)
?: return floatArrayOf(0f, 0f)
return floatArrayOf(
red.first,
red.second,
green.first,
green.second,
blue.first,
blue.second,
0f,
0f,
)
}
/**
* 检查图像是否为 RAW 格式
*/
@@ -322,6 +461,127 @@ object RawProcessor {
return output
}
suspend fun prepareRawDngProfile(
rawBuffer: ByteBuffer,
width: Int,
height: Int,
characteristics: CameraCharacteristics,
captureResult: CaptureResult,
captureMetadataResult: CaptureResult? = null,
cfaPattern: Int = RawMetadata.CFA_RGGB,
blackLevel: FloatArray = floatArrayOf(0f, 0f, 0f, 0f),
whiteLevel: Int = 65535,
valueDomain: RawBufferValueDomain = RawBufferValueDomain.SENSOR,
blackLevelMode: String? = null,
customBlackLevel: Float? = null,
whiteLevelMode: String? = null,
customWhiteLevel: Float? = null,
cfaCorrectionMode: String? = null,
baselineExposureEv: Float? = null,
imageLayout: SuperResolutionDngWriter.ImageLayout = SuperResolutionDngWriter.ImageLayout.CFA,
inputRowStepSamples: Int? = null,
inputColStepSamples: Int? = null,
options: RawDngProfilePreparationOptions,
defaultCrop: Rect,
): RawDngProfilePreparation? {
val resolvedCfaPattern = resolveCfaPatternForMode(cfaPattern, cfaCorrectionMode)
val resolvedBlackLevel = resolveBlackLevelForMode(blackLevel, blackLevelMode, customBlackLevel)
val resolvedWhiteLevel = resolveWhiteLevelForMode(
whiteLevel.toFloat(),
whiteLevelMode,
customWhiteLevel,
).toInt()
val sourceBaselineExposureEv = DngBaselineExposure.sanitize(
baselineExposureEv ?: captureResult
.get(CaptureResult.CONTROL_POST_RAW_SENSITIVITY_BOOST)
?.takeIf { it > 0 }
?.let { kotlin.math.log2(it / 100.0).toFloat() }
?: 0f
)
val inputSamplesPerPixel = inputColStepSamples ?: imageLayout.samplesPerPixel
val inputRowStrideBytes = (inputRowStepSamples
?: width * inputSamplesPerPixel) * Short.SIZE_BYTES
val statsBlackLevel = if (valueDomain == RawBufferValueDomain.NORMALIZED_SENSOR_RANGE) {
FloatArray(if (inputSamplesPerPixel >= 3) 3 else 4)
} else {
resolvedBlackLevel
}
val statsWhiteLevel = if (valueDomain == RawBufferValueDomain.NORMALIZED_SENSOR_RANGE) {
65535f
} else {
resolvedWhiteLevel.toFloat()
}
val statsMetadata = RawMetadata.create(
width = width,
height = height,
characteristics = characteristics,
captureResult = captureMetadataResult ?: captureResult,
).copy(
width = width,
height = height,
cfaPattern = resolvedCfaPattern,
blackLevel = statsBlackLevel,
whiteLevel = statsWhiteLevel,
baselineExposure = sourceBaselineExposureEv,
defaultCrop = defaultCrop,
)
val captureProfile = options.captureProfilePreparer?.prepare(
com.hinnka.mycamera.raw.RawDngCaptureProfileInput(
rawData = rawBuffer.duplicate().order(ByteOrder.nativeOrder()),
width = width,
height = height,
rowStride = inputRowStrideBytes,
samplesPerPixel = inputSamplesPerPixel,
metadata = statsMetadata.copy(profileGainTableMap = null),
)
)
val exposureOffsetEv = captureProfile?.exposureOffsetEv
?.takeIf { it.isFinite() }
?.coerceIn(
com.hinnka.mycamera.raw.MeteringSystem.RAW_EXPOSURE_MIN_EV,
com.hinnka.mycamera.raw.MeteringSystem.RAW_EXPOSURE_MAX_EV,
)
val finalBaselineExposureEv = DngBaselineExposure.sanitize(
sourceBaselineExposureEv + (exposureOffsetEv ?: 0f)
)
val profileRequired = options.profileToneMapMode == RawProfileToneMapMode.Photon ||
options.profileToneMapMode == RawProfileToneMapMode.GooglePixel
if (profileRequired && captureProfile?.profileGainTableMap == null) {
PLog.e(
TAG,
"GPU RAW profile preparation failed: mode=${options.profileToneMapMode} " +
"size=${width}x$height samplesPerPixel=$inputSamplesPerPixel"
)
return null
}
val profileGainTableMap = captureProfile?.profileGainTableMap?.let { map ->
if (map.sourceTag == DngProfileGainTableMap.TAG_PROFILE_GAIN_TABLE_MAP2) {
map
} else {
map.copy(sourceTag = DngProfileGainTableMap.TAG_PROFILE_GAIN_TABLE_MAP2)
}
}
return RawDngProfilePreparation(
baselineExposureEv = finalBaselineExposureEv,
profileGainTableMap = profileGainTableMap,
).also { finalProfile ->
PLog.i(
TAG,
"RAW_VIEWFINDER_BASELINE stage=SHARED_PROFILE_READY " +
"enabled=${options.captureProfilePreparer != null} " +
"matched=${exposureOffsetEv != null} " +
"sourceBaselineEv=$sourceBaselineExposureEv " +
"sourceBaselineGain=${DngBaselineExposure.exactGain(sourceBaselineExposureEv)} " +
"meteredExposureOffsetEv=${exposureOffsetEv ?: 0f} " +
"meteredExposureGain=${DngBaselineExposure.exactGain(exposureOffsetEv ?: 0f)} " +
"finalBaselineEv=${finalProfile.baselineExposureEv} " +
"finalBaselineGain=${DngBaselineExposure.exactGain(finalProfile.baselineExposureEv)} " +
"pgtm=${finalProfile.profileGainTableMap != null} " +
"pgtmSource=GPU mode=${options.profileToneMapMode} statsBounds=${options.statsBounds}"
)
}
}
suspend fun saveRawBufferToDng(
rawBuffer: ByteBuffer,
width: Int,
@@ -354,6 +614,7 @@ object RawProcessor {
inputColStepSamples: Int? = null,
dngProfilePreparationOptions: RawDngProfilePreparationOptions? = null,
defaultCrop: Rect,
preparedDngProfile: RawDngProfilePreparation? = null,
): Boolean {
val resolvedCfaPattern = resolveCfaPatternForMode(cfaPattern, cfaCorrectionMode)
val resolvedBlackLevel = resolveBlackLevelForMode(blackLevel, blackLevelMode, customBlackLevel)
@@ -370,90 +631,32 @@ object RawProcessor {
PLog.d(TAG, "RAW DNG white level override mode=$whiteLevelMode white=$whiteLevel->$resolvedWhiteLevel")
}
val sourceBaselineExposureEv = DngBaselineExposure.sanitize(
baselineExposureEv ?: captureResult
.get(CaptureResult.CONTROL_POST_RAW_SENSITIVITY_BOOST)
?.takeIf { it > 0 }
?.let { kotlin.math.log2(it / 100.0).toFloat() }
?: 0f
)
val preparedProfile = dngProfilePreparationOptions?.let { options ->
val inputSamplesPerPixel = inputColStepSamples ?: imageLayout.samplesPerPixel
val inputRowStrideBytes = (inputRowStepSamples
?: width * inputSamplesPerPixel) * Short.SIZE_BYTES
val statsBlackLevel = if (valueDomain == RawBufferValueDomain.NORMALIZED_SENSOR_RANGE) {
FloatArray(if (inputSamplesPerPixel >= 3) 3 else 4)
} else {
resolvedBlackLevel
}
val statsWhiteLevel = if (valueDomain == RawBufferValueDomain.NORMALIZED_SENSOR_RANGE) {
65535f
} else {
resolvedWhiteLevel.toFloat()
}
val statsMetadata = RawMetadata.create(
val preparedProfile = preparedDngProfile ?: dngProfilePreparationOptions?.let { options ->
prepareRawDngProfile(
rawBuffer = rawBuffer,
width = width,
height = height,
characteristics = characteristics,
captureResult = captureMetadataResult ?: captureResult,
).copy(
width = width,
height = height,
cfaPattern = resolvedCfaPattern,
blackLevel = statsBlackLevel,
whiteLevel = statsWhiteLevel,
baselineExposure = sourceBaselineExposureEv,
captureResult = captureResult,
captureMetadataResult = captureMetadataResult,
cfaPattern = cfaPattern,
blackLevel = blackLevel,
whiteLevel = whiteLevel,
valueDomain = valueDomain,
blackLevelMode = blackLevelMode,
customBlackLevel = customBlackLevel,
whiteLevelMode = whiteLevelMode,
customWhiteLevel = customWhiteLevel,
cfaCorrectionMode = cfaCorrectionMode,
baselineExposureEv = baselineExposureEv,
imageLayout = imageLayout,
inputRowStepSamples = inputRowStepSamples,
inputColStepSamples = inputColStepSamples,
options = options,
defaultCrop = defaultCrop,
)
val captureProfile = options.captureProfilePreparer?.prepare(
com.hinnka.mycamera.raw.RawDngCaptureProfileInput(
rawData = rawBuffer.duplicate().order(ByteOrder.nativeOrder()),
width = width,
height = height,
rowStride = inputRowStrideBytes,
samplesPerPixel = inputSamplesPerPixel,
metadata = statsMetadata.copy(profileGainTableMap = null),
)
)
val exposureOffsetEv = captureProfile?.exposureOffsetEv
?.takeIf { it.isFinite() }
?.coerceIn(
com.hinnka.mycamera.raw.MeteringSystem.RAW_EXPOSURE_MIN_EV,
com.hinnka.mycamera.raw.MeteringSystem.RAW_EXPOSURE_MAX_EV,
)
val finalBaselineExposureEv = DngBaselineExposure.sanitize(
sourceBaselineExposureEv + (exposureOffsetEv ?: 0f)
)
val profileRequired = options.profileToneMapMode == RawProfileToneMapMode.Photon ||
options.profileToneMapMode == RawProfileToneMapMode.GooglePixel
if (profileRequired && captureProfile?.profileGainTableMap == null) {
PLog.e(
TAG,
"GPU RAW profile preparation failed: mode=${options.profileToneMapMode} " +
"size=${width}x$height samplesPerPixel=$inputSamplesPerPixel"
)
return false
}
val finalProfile = com.hinnka.mycamera.raw.RawDngProfilePreparation(
baselineExposureEv = finalBaselineExposureEv,
profileGainTableMap = captureProfile?.profileGainTableMap,
)
PLog.i(
TAG,
"RAW_VIEWFINDER_BASELINE stage=DNG_WRITE_READY " +
"enabled=${options.captureProfilePreparer != null} " +
"matched=${exposureOffsetEv != null} " +
"sourceBaselineEv=$sourceBaselineExposureEv " +
"sourceBaselineGain=${DngBaselineExposure.exactGain(sourceBaselineExposureEv)} " +
"meteredExposureOffsetEv=${exposureOffsetEv ?: 0f} " +
"meteredExposureGain=${DngBaselineExposure.exactGain(exposureOffsetEv ?: 0f)} " +
"writtenBaselineEv=${finalProfile.baselineExposureEv} " +
"writtenBaselineGain=${DngBaselineExposure.exactGain(finalProfile.baselineExposureEv)} " +
"pgtm=${finalProfile.profileGainTableMap != null} " +
"pgtmSource=GPU mode=${options.profileToneMapMode} statsBounds=${options.statsBounds}"
)
finalProfile
}
if (dngProfilePreparationOptions != null && preparedProfile == null) return false
val writtenBaselineExposureEv = preparedProfile?.baselineExposureEv ?: baselineExposureEv
val writtenProfileGainTableMap = if (dngProfilePreparationOptions != null) {
preparedProfile?.profileGainTableMap
@@ -12,6 +12,12 @@ import android.os.SystemClock
import com.hinnka.mycamera.raw.DngProfileGainTableMap
import com.hinnka.mycamera.raw.DngProfileToneCurve
import com.hinnka.mycamera.raw.DngCameraRawProfileXmp
import com.hinnka.mycamera.raw.ColorSpace
import com.hinnka.mycamera.raw.DcpDefaultBlackRender
import com.hinnka.mycamera.raw.DcpProfile
import com.hinnka.mycamera.raw.DcpProfileParser
import com.hinnka.mycamera.raw.DcpRenderPlan
import com.hinnka.mycamera.raw.DcpToneCurve
import com.hinnka.mycamera.raw.RawCfaCorrection
import com.hinnka.mycamera.raw.RawMetadata
import com.hinnka.mycamera.raw.RawWhiteLevelCorrection
@@ -46,6 +52,73 @@ object SuperResolutionDngWriter {
JPEG_LOSSLESS(7),
}
/** Builds the same embedded color/tone plan that [write] serializes into the DNG IFD. */
fun resolveEmbeddedRenderPlan(
characteristics: CameraCharacteristics,
metadata: RawMetadata,
imageLayout: ImageLayout,
profileGainTableMap: DngProfileGainTableMap?,
profileToneCurve: FloatArray?,
): DcpRenderPlan? {
val colorMatrix1 = characteristics.get(CameraCharacteristics.SENSOR_COLOR_TRANSFORM1)
?.let(::colorTransformToDngMatrix)
?.map(Double::toFloat)
?.toFloatArray()
val colorMatrix2 = characteristics.get(CameraCharacteristics.SENSOR_COLOR_TRANSFORM2)
?.let(::colorTransformToDngMatrix)
?.map(Double::toFloat)
?.toFloatArray()
val illuminant2 = characteristics.get(CameraCharacteristics.SENSOR_REFERENCE_ILLUMINANT2)
?.toInt()
?.takeIf { colorMatrix2 != null }
?: 0
val calibration1 = characteristics.get(CameraCharacteristics.SENSOR_CALIBRATION_TRANSFORM1)
?.let(::colorTransformToExactDngMatrix)
?.map(Double::toFloat)
?.toFloatArray()
val calibration2 = characteristics.get(CameraCharacteristics.SENSOR_CALIBRATION_TRANSFORM2)
?.takeIf { illuminant2 != 0 }
?.let(::colorTransformToExactDngMatrix)
?.map(Double::toFloat)
?.toFloatArray()
val toneCurve = profileToneCurve
?.takeIf { profileGainTableMap != null && it.size >= 4 }
?.let(::DcpToneCurve)
?.takeIf { it.isValid }
val profile = DcpProfile(
profileName = "Embedded",
calibrationIlluminant1 = characteristics.get(
CameraCharacteristics.SENSOR_REFERENCE_ILLUMINANT1
) ?: 21,
calibrationIlluminant2 = illuminant2,
baselineExposureOffset = 0f,
defaultBlackRender = if (
profileGainTableMap != null || imageLayout == ImageLayout.LINEAR_RAW_RGB
) {
DcpDefaultBlackRender.None
} else {
DcpDefaultBlackRender.Auto
},
supportsOverrange = false,
colorMatrix1 = colorMatrix1,
colorMatrix2 = colorMatrix2,
forwardMatrix1 = null,
forwardMatrix2 = null,
hueSatDeltas1 = null,
hueSatDeltas2 = null,
lookTable = null,
toneCurve = toneCurve,
analogBalance = floatArrayOf(1f, 1f, 1f),
cameraCalibration1 = calibration1,
cameraCalibration2 = calibration2,
)
return DcpProfileParser.resolveRenderPlan(
profile = profile,
metadata = metadata,
workingColorSpace = ColorSpace.ProPhoto,
)
}
private const val TYPE_BYTE = 1
private const val TYPE_ASCII = 2
private const val TYPE_SHORT = 3
@@ -44,10 +44,8 @@ import com.hinnka.mycamera.model.ColorRecipeParams
import com.hinnka.mycamera.model.LutSelectorMode
import com.hinnka.mycamera.model.SafeImage
import com.hinnka.mycamera.phantom.PhantomWidgetProvider
import com.hinnka.mycamera.processor.RawAlignmentProxyConfig
import com.hinnka.mycamera.processor.RawBurstFrameRole
import com.hinnka.mycamera.processor.RawBurstGyroSelector
import com.hinnka.mycamera.processor.RawBurstReferencePlanner
import com.hinnka.mycamera.processor.RawRadianceExposurePlanner
import com.hinnka.mycamera.processor.RawStackFrame
import com.hinnka.mycamera.raw.ColorSpace
@@ -1437,6 +1435,7 @@ class CameraViewModel(application: Application) : AndroidViewModel(application)
)
)
if (pendingRawStackFrames.size >= count) {
val burstPlanningStartedAtMs = SystemClock.elapsedRealtime()
val chronologicalFrames = pendingRawStackFrames
.sortedBy { it.frame.sensorTimestampNs }
pendingRawStackFrames.clear()
@@ -1458,46 +1457,23 @@ class CameraViewModel(application: Application) : AndroidViewModel(application)
val gyroOrderedFrames = gyroSelection.orderedAcceptedIndices.map { index ->
normalFrames[index]
}
val proxyConfig = rawAlignmentProxyConfig(
characteristics = characteristics,
captureResult = gyroOrderedFrames.firstOrNull()?.captureResult ?: captureResult,
)
val referencePlan = if (proxyConfig != null && gyroOrderedFrames.size >= 2) {
runCatching {
withContext(Dispatchers.Default) {
RawBurstReferencePlanner.plan(
frames = gyroOrderedFrames.map { it.frame },
proxyConfig = proxyConfig,
)
}
}.onFailure { error ->
PLog.w(TAG, "RAW reference planning failed; keeping Gyro order", error)
}.getOrNull()
} else {
null
}
val orderedNormalFrames = referencePlan?.orderedIndices?.map { index ->
val pending = gyroOrderedFrames[index]
pending.copy(
frame = pending.frame.copy(
preAlignmentToReference = referencePlan.preAlignmentsToReference[index],
),
)
} ?: gyroOrderedFrames
// Geometry is planned by GlesRawStacker's coarse temporal-flow graph.
// Running a second exhaustive RAW proxy registration here blocks the
// post-capture path on CPU and duplicates the GLES registration work.
val orderedNormalFrames = gyroOrderedFrames
val orderedFrames = orderedNormalFrames + auxiliaryFrames
if (gyroSelection.rejectedIndices.isNotEmpty() || referencePlan != null) {
PLog.i(
TAG,
"RAW burst plan: gyroReference=${gyroSelection.referenceOriginalIndex}, " +
"reference=${referencePlan?.referenceOriginalIndex ?: 0}, " +
"accepted=${orderedFrames.size}, " +
"normal=${orderedNormalFrames.size}, " +
"short=${if (exposurePlan.shortIndex != null) 1 else 0}, " +
"long=${exposurePlan.longIndices.size}, " +
"rejected=${gyroSelection.rejectedIndices.joinToString()}, " +
"cost=${referencePlan?.referenceCost}",
)
}
PLog.i(
TAG,
"RAW burst plan: referenceSource=gyro, " +
"reference=${gyroSelection.referenceOriginalIndex}, " +
"accepted=${orderedFrames.size}, " +
"normal=${orderedNormalFrames.size}, " +
"short=${if (exposurePlan.shortIndex != null) 1 else 0}, " +
"long=${exposurePlan.longIndices.size}, " +
"rejected=${gyroSelection.rejectedIndices.joinToString()}, " +
"geometry=GLES_TEMPORAL_GRAPH, " +
"costMs=${SystemClock.elapsedRealtime() - burstPlanningStartedAtMs}",
)
val isRawStack = orderedNormalFrames.firstOrNull()?.frame?.image?.format
?.let(::isRawCaptureFormat) == true
val processingFrames = if (isRawStack) {
@@ -5140,63 +5116,6 @@ class CameraViewModel(application: Application) : AndroidViewModel(application)
)
}
private fun rawAlignmentProxyConfig(
characteristics: CameraCharacteristics?,
captureResult: CaptureResult?,
): RawAlignmentProxyConfig? {
characteristics ?: return null
var cfa = characteristics.get(CameraCharacteristics.SENSOR_INFO_COLOR_FILTER_ARRANGEMENT)
?: CameraCharacteristics.SENSOR_INFO_COLOR_FILTER_ARRANGEMENT_RGGB
val activeArray = characteristics.get(
CameraCharacteristics.SENSOR_INFO_PRE_CORRECTION_ACTIVE_ARRAY_SIZE
)
if (((activeArray?.left ?: 0) and 1) != 0) {
cfa = when (cfa) {
CameraCharacteristics.SENSOR_INFO_COLOR_FILTER_ARRANGEMENT_RGGB ->
CameraCharacteristics.SENSOR_INFO_COLOR_FILTER_ARRANGEMENT_GRBG
CameraCharacteristics.SENSOR_INFO_COLOR_FILTER_ARRANGEMENT_GRBG ->
CameraCharacteristics.SENSOR_INFO_COLOR_FILTER_ARRANGEMENT_RGGB
CameraCharacteristics.SENSOR_INFO_COLOR_FILTER_ARRANGEMENT_GBRG ->
CameraCharacteristics.SENSOR_INFO_COLOR_FILTER_ARRANGEMENT_BGGR
CameraCharacteristics.SENSOR_INFO_COLOR_FILTER_ARRANGEMENT_BGGR ->
CameraCharacteristics.SENSOR_INFO_COLOR_FILTER_ARRANGEMENT_GBRG
else -> cfa
}
}
if (((activeArray?.top ?: 0) and 1) != 0) {
cfa = when (cfa) {
CameraCharacteristics.SENSOR_INFO_COLOR_FILTER_ARRANGEMENT_RGGB ->
CameraCharacteristics.SENSOR_INFO_COLOR_FILTER_ARRANGEMENT_GBRG
CameraCharacteristics.SENSOR_INFO_COLOR_FILTER_ARRANGEMENT_GRBG ->
CameraCharacteristics.SENSOR_INFO_COLOR_FILTER_ARRANGEMENT_BGGR
CameraCharacteristics.SENSOR_INFO_COLOR_FILTER_ARRANGEMENT_GBRG ->
CameraCharacteristics.SENSOR_INFO_COLOR_FILTER_ARRANGEMENT_RGGB
CameraCharacteristics.SENSOR_INFO_COLOR_FILTER_ARRANGEMENT_BGGR ->
CameraCharacteristics.SENSOR_INFO_COLOR_FILTER_ARRANGEMENT_GRBG
else -> cfa
}
}
val dynamicBlack = captureResult?.get(CaptureResult.SENSOR_DYNAMIC_BLACK_LEVEL)
val staticBlack = characteristics.get(CameraCharacteristics.SENSOR_BLACK_LEVEL_PATTERN)
val blackByPosition = when {
dynamicBlack != null && dynamicBlack.size >= 4 -> dynamicBlack.copyOf(4)
staticBlack != null -> floatArrayOf(
staticBlack.getOffsetForIndex(0, 0).toFloat(),
staticBlack.getOffsetForIndex(1, 0).toFloat(),
staticBlack.getOffsetForIndex(0, 1).toFloat(),
staticBlack.getOffsetForIndex(1, 1).toFloat(),
)
else -> FloatArray(4)
}
return RawAlignmentProxyConfig(
cfaArrangement = cfa,
blackLevelByPosition = blackByPosition,
whiteLevel = characteristics.get(CameraCharacteristics.SENSOR_INFO_WHITE_LEVEL)
?.toFloat()
?: 1023f,
)
}
private suspend fun processStacking(
frames: List<RawStackFrame>,
captureInfo: CaptureInfo,
@@ -206,6 +206,32 @@ class GlesRawRadianceFusionShadersTest {
assertTrue(shader.contains("max(uLongPrecisionWeightCap, 1.0)"))
}
@Test
fun longNrPrecisionBoostIsCappedWithoutBoostingDetail() {
val shader = GlesRawRadianceFusionShaders.accumulate("", trackRejections = false)
assertEquals(3f, RawRadianceFusionTuning().longNrWeightScale, 0f)
assertTrue(shader.contains("uniform float uLongNrWeightScale"))
assertTrue(
Regex(
"""float nrPrecision = uIsLongFrame != 0 \?\s*min\(\s*""" +
"""sharedPrecision \* max\(uLongNrWeightScale, 1\.0\),\s*""" +
"""precisionUpper\s*\) : sharedPrecision;""",
).containsMatchIn(shader),
)
assertTrue(
shader.contains(
"float sharedNrWeight = uFrameWeight * nrPrecision * sharedConsistency",
),
)
assertTrue(
shader.contains(
"float sharedDetailWeight = uFrameWeight * sharedPrecision * sharedConsistency",
),
)
assertFalse(shader.contains("sharedDetailWeight = uFrameWeight * nrPrecision"))
}
@Test
fun longFramesRequireFinalComposedPathConfidencePerPixel() {
val shader = GlesRawRadianceFusionShaders.accumulate("", trackRejections = false)
@@ -1,94 +0,0 @@
package com.hinnka.mycamera.processor
import org.junit.Assert.assertEquals
import org.junit.Assert.assertNotNull
import org.junit.Assert.assertTrue
import org.junit.Test
import kotlin.math.abs
import kotlin.math.sin
class RawGlobalPreAlignerTest {
@Test
fun recoversIntegerTranslation() {
val reference = proxy(pattern(WIDTH, HEIGHT), WIDTH, HEIGHT)
val current = proxy(shift(reference.lowPass, WIDTH, HEIGHT, 4, -2), WIDTH, HEIGHT)
val alignment = RawGlobalPreAligner.align(reference, current)
assertNotNull(alignment)
alignment!!
assertEquals(4f, alignment.dxProxyPx, 1f)
assertEquals(-2f, alignment.dyProxyPx, 1f)
assertTrue(alignment.score < 0.2f)
assertTrue(alignment.coverage > 0.75f)
}
@Test
fun geometryCenterFrameIsSelectedAsReference() {
val base = pattern(WIDTH, HEIGHT)
val proxies = listOf(
proxy(shift(base, WIDTH, HEIGHT, -5, 0), WIDTH, HEIGHT).copy(sourcePlaneWidth = WIDTH * 2),
proxy(base, WIDTH, HEIGHT).copy(sourcePlaneWidth = WIDTH * 2),
proxy(shift(base, WIDTH, HEIGHT, 5, 0), WIDTH, HEIGHT).copy(sourcePlaneWidth = WIDTH * 2),
)
val plan = RawBurstReferencePlanner.planProxies(
proxies = proxies,
gyroRisks = floatArrayOf(0.001f, 0.001f, 0.001f),
)
assertEquals(1, plan.referenceOriginalIndex)
assertEquals(1, plan.orderedIndices.first())
assertEquals(-10f, plan.preAlignmentsToReference[0]!!.translationXPlanePx, 2f)
assertEquals(10f, plan.preAlignmentsToReference[2]!!.translationXPlanePx, 2f)
}
private fun proxy(values: FloatArray, width: Int, height: Int): RawAlignmentProxy {
val band = FloatArray(values.size)
for (y in 1 until height - 1) {
for (x in 1 until width - 1) {
val index = y * width + x
band[index] = values[index] - 0.25f * (
values[index - 1] + values[index + 1] +
values[index - width] + values[index + width]
)
}
}
return RawAlignmentProxy(width, height, values, band, sharpness = 1f)
}
private fun pattern(width: Int, height: Int): FloatArray {
return FloatArray(width * height) { index ->
val x = index % width
val y = index / width
val checker = if ((((x / 7) + (y / 5)) and 1) == 0) 0.7f else -0.5f
checker + 0.25f * sin(x * 0.19f) + 0.2f * sin(y * 0.13f) +
if (abs(x - 31) < 3 && abs(y - 57) < 5) 1.2f else 0f
}
}
private fun shift(
input: FloatArray,
width: Int,
height: Int,
dx: Int,
dy: Int,
): FloatArray {
val output = FloatArray(input.size)
for (y in 0 until height) {
for (x in 0 until width) {
val sourceX = x - dx
val sourceY = y - dy
if (sourceX in 0 until width && sourceY in 0 until height) {
output[y * width + x] = input[sourceY * width + sourceX]
}
}
}
return output
}
private companion object {
const val WIDTH = 96
const val HEIGHT = 96
}
}