fix: dng warp rectilinear

This commit is contained in:
zhoubinjia committed 2026-07-28 13:29:23 +08:00
1 parent 618a9f1d5e
commit b6b4ddb323
7 files changed
+429 -85

No files matched your search

+16 -4
View File
@@ -585,6 +585,7 @@ struct DngRawTagInfo {
std::vector<double> blackDeltaV;
bool hasFixBadPixelsList = false;
std::vector<float> warpRectilinear;
std::vector<int> warpRectilinearFlags;
};
static int bayerBlackLevelIndexForPattern(int cfaPattern, int col, int row) {
@@ -2513,6 +2514,7 @@ static void parseDngOpcodeList(const std::vector<unsigned char> &data,
if (offset + 16 > data.size())
return;
const uint32_t id = dngOpcodeReadU32(data.data() + offset);
const uint32_t flags = dngOpcodeReadU32(data.data() + offset + 8);
const uint32_t payloadSize = dngOpcodeReadU32(data.data() + offset + 12);
offset += 16;
if (payloadSize > data.size() - offset)
@@ -2544,8 +2546,10 @@ static void parseDngOpcodeList(const std::vector<unsigned char> &data,
valid = valid && std::isfinite(value);
warp[i] = static_cast<float>(value);
}
if (valid)
if (valid) {
info.warpRectilinear.insert(info.warpRectilinear.end(), warp.begin(), warp.end());
info.warpRectilinearFlags.push_back(static_cast<int>(flags));
}
}
}
offset += payloadSize;
@@ -3313,7 +3317,7 @@ Java_com_hinnka_mycamera_raw_RawDemosaicProcessor_processDngNative(
jclass dngDataClass = env->FindClass("com/hinnka/mycamera/raw/DngRawData");
jmethodID constructor =
env->GetMethodID(dngDataClass, "<init>",
"(Ljava/nio/ByteBuffer;IIIIF[F[F[F[F[F[FLjava/lang/String;Ljava/lang/String;IIFF[FII[FFIJF[I[I[F[FLandroid/graphics/Bitmap;)V");
"(Ljava/nio/ByteBuffer;IIIIF[F[F[F[F[F[FLjava/lang/String;Ljava/lang/String;IIFF[FII[FFIJF[I[I[F[F[ILandroid/graphics/Bitmap;)V");
jfloatArray blackLevelArray = env->NewFloatArray(4);
for (int i = 0; i < 4; i++) {
@@ -3616,12 +3620,20 @@ Java_com_hinnka_mycamera_raw_RawDemosaicProcessor_processDngNative(
env->SetFloatArrayRegion(noiseProfileArray, 0, 8, ed.noiseProfile);
}
jfloatArray warpRectilinearArray = nullptr;
jintArray warpRectilinearFlagsArray = nullptr;
if (!dngRawTagInfo.warpRectilinear.empty() &&
dngRawTagInfo.warpRectilinear.size() % 8 == 0) {
dngRawTagInfo.warpRectilinear.size() % 8 == 0 &&
dngRawTagInfo.warpRectilinearFlags.size() ==
dngRawTagInfo.warpRectilinear.size() / 8) {
warpRectilinearArray = env->NewFloatArray(dngRawTagInfo.warpRectilinear.size());
env->SetFloatArrayRegion(warpRectilinearArray, 0,
dngRawTagInfo.warpRectilinear.size(),
dngRawTagInfo.warpRectilinear.data());
warpRectilinearFlagsArray =
env->NewIntArray(dngRawTagInfo.warpRectilinearFlags.size());
env->SetIntArrayRegion(warpRectilinearFlagsArray, 0,
dngRawTagInfo.warpRectilinearFlags.size(),
dngRawTagInfo.warpRectilinearFlags.data());
}
jobject dngData = env->NewObject(
@@ -3633,7 +3645,7 @@ Java_com_hinnka_mycamera_raw_RawDemosaicProcessor_processDngNative(
exportedLscHeight,
exportedLscGridArray, exposureBias, iso,
shutterSpeedLong, aperture, activeArray, defaultCropArray, noiseProfileArray,
warpRectilinearArray,
warpRectilinearArray, warpRectilinearFlagsArray,
embeddedPreviewBitmap);
// 释放资源
@@ -62,6 +62,7 @@ data class DngRawData @Keep constructor(
val defaultCrop: IntArray?, // [left, top, right, bottom] relative to rawData
val noiseProfile: FloatArray?, // NoiseProfile [S1, O1, S2, O2, ...]
val warpRectilinear: FloatArray?, // repeated [k0, k1, k2, k3, t0, t1, centerH, centerV]
val warpRectilinearFlags: IntArray?, // one DNG opcode flags value per warp
val embeddedPreview: Bitmap? = null,
) : AutoCloseable {
@@ -132,6 +133,10 @@ data class DngRawData @Keep constructor(
if (other.warpRectilinear == null) return false
if (!warpRectilinear.contentEquals(other.warpRectilinear)) return false
} else if (other.warpRectilinear != null) return false
if (warpRectilinearFlags != null) {
if (other.warpRectilinearFlags == null) return false
if (!warpRectilinearFlags.contentEquals(other.warpRectilinearFlags)) return false
} else if (other.warpRectilinearFlags != null) return false
if (embeddedPreview != null) {
if (other.embeddedPreview == null) return false
if (!embeddedPreview.sameAs(other.embeddedPreview)) return false
@@ -165,6 +170,7 @@ data class DngRawData @Keep constructor(
result = 31 * result + (lensShadingMapGrid?.contentHashCode() ?: 0)
result = 31 * result + (defaultCrop?.contentHashCode() ?: 0)
result = 31 * result + (warpRectilinear?.contentHashCode() ?: 0)
result = 31 * result + (warpRectilinearFlags?.contentHashCode() ?: 0)
result = 31 * result + (embeddedPreview?.hashCode() ?: 0)
return result
}
@@ -0,0 +1,153 @@
package com.hinnka.mycamera.raw
import kotlin.math.max
import kotlin.math.sqrt
/**
* Validation and source-coverage policy for DNG 1.3 WarpRectilinear opcodes.
*
* DNG maps corrected destination pixels back into the uncorrected Stage 3 image. Optional
* opcodes may be skipped. In particular, an optional warp must not turn an otherwise valid
* DefaultCrop into repeated edge pixels by mapping that crop outside the available source.
*/
internal object DngWarpRectilinear {
const val OPTIONAL_FLAG = 1
enum class Rejection {
NONE,
MALFORMED_OR_UNSAFE,
OPTIONAL_REQUIRES_EDGE_CLAMPING,
}
data class Decision(
val apply: Boolean,
val rejection: Rejection,
)
fun decide(
parameters: FloatArray,
flags: Int,
width: Int,
height: Int,
left: Int,
top: Int,
right: Int,
bottom: Int,
): Decision {
if (!isNumericallySafe(parameters, width, height)) {
return Decision(false, Rejection.MALFORMED_OR_UNSAFE)
}
val hasCoverage = hasSourceCoverage(
parameters = parameters,
width = width,
height = height,
left = left,
top = top,
right = right,
bottom = bottom,
)
if (!hasCoverage && flags and OPTIONAL_FLAG != 0) {
return Decision(false, Rejection.OPTIONAL_REQUIRES_EDGE_CLAMPING)
}
return Decision(true, Rejection.NONE)
}
fun hasSourceCoverage(
parameters: FloatArray,
width: Int,
height: Int,
left: Int,
top: Int,
right: Int,
bottom: Int,
): Boolean {
if (parameters.size != 8 || width <= 1 || height <= 1 ||
left < 0 || top < 0 || right > width || bottom > height ||
left >= right || top >= bottom
) {
return false
}
fun covered(x: Int, y: Int): Boolean {
val source = mapDestinationToSource(parameters, width, height, x.toFloat(), y.toFloat())
?: return false
// AOSP DngCreator accepts coordinates inside the continuous image rectangle
// [0,width) x [0,height). Values above the last pixel center by less than one pixel
// are handled by the resampler without creating a multi-pixel repeated border.
return source.first >= -1e-3f && source.first < width.toFloat() &&
source.second >= -1e-3f && source.second < height.toFloat()
}
val lastX = right - 1
val lastY = bottom - 1
for (x in left until right) {
if (!covered(x, top) || !covered(x, lastY)) return false
}
for (y in (top + 1) until lastY) {
if (!covered(left, y) || !covered(lastX, y)) return false
}
return true
}
private fun isNumericallySafe(parameters: FloatArray, width: Int, height: Int): Boolean {
if (parameters.size != 8 || parameters.any { !it.isFinite() } ||
width <= 1 || height <= 1
) {
return false
}
if (parameters[6] !in 0f..1f || parameters[7] !in 0f..1f) return false
for (gridY in 0..16) {
for (gridX in 0..16) {
val destinationX = (width - 1) * gridX / 16f
val destinationY = (height - 1) * gridY / 16f
val source = mapDestinationToSource(
parameters,
width,
height,
destinationX,
destinationY,
) ?: return false
val limitX = width * 4f
val limitY = height * 4f
if (source.first !in -limitX..limitX * 2f ||
source.second !in -limitY..limitY * 2f
) {
return false
}
}
}
return true
}
private fun mapDestinationToSource(
parameters: FloatArray,
width: Int,
height: Int,
destinationX: Float,
destinationY: Float,
): Pair<Float, Float>? {
val centerX = parameters[6] * width
val centerY = parameters[7] * height
val farX = max(centerX, width - centerX)
val farY = max(centerY, height - centerY)
val normRadius = sqrt(farX * farX + farY * farY).coerceAtLeast(1f)
val dx = (destinationX - centerX) / normRadius
val dy = (destinationY - centerY) / normRadius
val r2 = (dx * dx + dy * dy).coerceAtMost(1f)
val ratio = parameters[0] + parameters[1] * r2 +
parameters[2] * r2 * r2 + parameters[3] * r2 * r2 * r2
if (!ratio.isFinite() || ratio <= 0f) return null
val tangentX = parameters[5] * (r2 + 2f * dx * dx) +
2f * parameters[4] * dx * dy
val tangentY = parameters[4] * (r2 + 2f * dy * dy) +
2f * parameters[5] * dx * dy
val sourceX = centerX + normRadius * (dx * ratio + tangentX)
val sourceY = centerY + normRadius * (dy * ratio + tangentY)
return if (sourceX.isFinite() && sourceY.isFinite()) {
sourceX to sourceY
} else {
null
}
}
}
@@ -1686,6 +1686,7 @@ class RawDemosaicProcessor {
var dngRawDataCleanup: DngRawData? = null
var embeddedDngJpegPreview: Bitmap? = null
var dngWarpRectilinear: FloatArray? = null
var dngWarpRectilinearFlags: IntArray? = null
val requestedColorEngine = rawRenderingEngine
val hasDcpSelection = dcpRenderPlan != null || rawDcpId != null
val profileWorkingColorSpace = if (requestedColorEngine.isHncs) {
@@ -1731,10 +1732,12 @@ class RawDemosaicProcessor {
"RAW_CROP_TRACE stage=DNG_READ raw=${dngRawData.width}x${dngRawData.height} " +
"activeArray=${dngRawData.activeArray?.contentToString()} " +
"defaultCrop=${dngRawData.defaultCrop?.contentToString()} " +
"warpCount=${dngRawData.warpRectilinear?.size?.div(8) ?: 0}"
"warpCount=${dngRawData.warpRectilinear?.size?.div(8) ?: 0} " +
"warpFlags=${dngRawData.warpRectilinearFlags?.contentToString()}"
)
embeddedDngJpegPreview = dngRawData.embeddedPreview
dngWarpRectilinear = dngRawData.warpRectilinear
dngWarpRectilinearFlags = dngRawData.warpRectilinearFlags
actualRawData = dngRawData.rawData
actualWidth = dngRawData.width
actualHeight = dngRawData.height
@@ -1890,19 +1893,20 @@ class RawDemosaicProcessor {
"aspectRatio=$aspectRatio rotation=$actualRotation outputSourceBounds=$outputSourceBounds"
)
val rawOutputBounds = outputSourceBounds.toOutputBounds(actualRotation)
val applicableDngWarpRectilinear = filterApplicableWarpRectilinear(
warps = dngWarpRectilinear,
flags = dngWarpRectilinearFlags,
width = actualWidth,
height = actualHeight,
outputSourceBounds = outputSourceBounds,
)
// Photon has historically processed the whole sensor before the final crop, so a small
// output crop does not make a 100 MP input cheap. Trigger on either effective output or
// source processing footprint.
val highResolutionOutput =
RawTilePlanner.shouldTile(outputSourceBounds.width(), outputSourceBounds.height()) ||
RawTilePlanner.shouldTile(actualWidth, actualHeight)
val hasActiveWarp = dngWarpRectilinear
?.takeIf { it.isNotEmpty() && it.size % 8 == 0 }
?.let { warps ->
warps.indices.step(8).any { offset ->
!isNoOpWarpRectilinear(warps.copyOfRange(offset, offset + 8))
}
} == true
val hasActiveWarp = applicableDngWarpRectilinear?.isNotEmpty() == true
val tileBlockingReason = when {
!highResolutionOutput -> null
actualSamplesPerPixel !in setOf(1, 3, 4) ->
@@ -2058,7 +2062,7 @@ class RawDemosaicProcessor {
hueSatMapSupportsOverrange =
requestedProfileToneMapMode != RawProfileToneMapMode.Photon &&
resolvedDcpRenderPlan?.supportsOverrange == true,
warpRectilinear = dngWarpRectilinear,
warpRectilinear = applicableDngWarpRectilinear,
)?.takeIf { it.isValid }
if (generated != null) {
profileGainTableMap = generated
@@ -2313,7 +2317,7 @@ class RawDemosaicProcessor {
)
}
}
dngWarpRectilinear?.takeIf { it.isNotEmpty() && it.size % 8 == 0 }?.let { warps ->
applicableDngWarpRectilinear?.let { warps ->
var appliedWarpCount = 0
for (offset in warps.indices step 8) {
val parameters = warps.copyOfRange(offset, offset + 8)
@@ -2323,13 +2327,6 @@ class RawDemosaicProcessor {
PLog.d(TAG, "Skipping no-op DNG WarpRectilinear")
continue
}
if (!isSafeWarpRectilinear(parameters, actualWidth, actualHeight)) {
PLog.w(
TAG,
"Skipping unsafe optional DNG WarpRectilinear: ${parameters.contentToString()}"
)
continue
}
PLog.d(TAG, "Applying DNG WarpRectilinear: ${parameters.contentToString()}")
val warped = renderWarpRectilinearPass(
sourceTextureId = demosaicTextureId,
@@ -2409,7 +2406,7 @@ class RawDemosaicProcessor {
cameraWhite = linearCameraWhite,
hueSatMap = activeDcpRenderPlan?.hueSatMap,
hueSatMapSupportsOverrange = hueSatMapSupportsOverrange,
warpRectilinear = dngWarpRectilinear,
warpRectilinear = applicableDngWarpRectilinear,
)
else -> null
}
@@ -3378,9 +3375,6 @@ class RawDemosaicProcessor {
for (offset in warps.indices step 8) {
val parameters = warps.copyOfRange(offset, offset + 8)
if (isNoOpWarpRectilinear(parameters)) continue
if (!isSafeWarpRectilinear(parameters, rawTextureWidth, rawTextureHeight)) {
continue
}
parameters.forEach { activeWarpParameters += it }
}
}
@@ -6475,45 +6469,67 @@ class RawDemosaicProcessor {
return parameters[0] == 1f && (1..5).all { index -> parameters[index] == 0f }
}
private fun isSafeWarpRectilinear(
parameters: FloatArray,
private fun filterApplicableWarpRectilinear(
warps: FloatArray?,
flags: IntArray?,
width: Int,
height: Int,
): Boolean {
if (parameters.size != 8 || parameters.any { !it.isFinite() }) return false
val centerX = parameters[6]
val centerY = parameters[7]
if (centerX !in 0f..1f || centerY !in 0f..1f || width <= 1 || height <= 1) return false
val centerPxX = centerX * width
val centerPxY = centerY * height
val farX = maxOf(centerPxX, width - centerPxX)
val farY = maxOf(centerPxY, height - centerPxY)
val normRadius = kotlin.math.sqrt(farX * farX + farY * farY).coerceAtLeast(1f)
for (gridY in 0..16) {
for (gridX in 0..16) {
val dstX = width * gridX / 16f
val dstY = height * gridY / 16f
val dx = (dstX - centerPxX) / normRadius
val dy = (dstY - centerPxY) / normRadius
val r2 = (dx * dx + dy * dy).coerceAtMost(1f)
val ratio = parameters[0] + parameters[1] * r2 +
parameters[2] * r2 * r2 + parameters[3] * r2 * r2 * r2
if (!ratio.isFinite() || ratio !in 0.5f..2f) return false
val tangentX = parameters[5] * (r2 + 2f * dx * dx) +
2f * parameters[4] * dx * dy
val tangentY = parameters[4] * (r2 + 2f * dy * dy) +
2f * parameters[5] * dx * dy
val srcX = centerPxX + normRadius * (dx * ratio + tangentX)
val srcY = centerPxY + normRadius * (dy * ratio + tangentY)
if (!srcX.isFinite() || !srcY.isFinite()) return false
val toleranceX = width * 0.02f
val toleranceY = height * 0.02f
if (srcX !in -toleranceX..(width + toleranceX) ||
srcY !in -toleranceY..(height + toleranceY)
) return false
outputSourceBounds: Rect,
): FloatArray? {
if (warps == null || warps.isEmpty()) return null
if (warps.size % 8 != 0) {
PLog.w(TAG, "Ignoring malformed DNG WarpRectilinear array size=${warps.size}")
return null
}
val opcodeCount = warps.size / 8
if (flags != null && flags.size != opcodeCount) {
PLog.w(
TAG,
"DNG WarpRectilinear flags count=${flags.size} does not match opcodes=$opcodeCount",
)
}
val applicable = ArrayList<Float>(warps.size)
for (opcodeIndex in 0 until opcodeCount) {
val offset = opcodeIndex * 8
val parameters = warps.copyOfRange(offset, offset + 8)
if (isNoOpWarpRectilinear(parameters)) {
PLog.d(TAG, "Skipping no-op DNG WarpRectilinear")
continue
}
val opcodeFlags = flags?.getOrNull(opcodeIndex) ?: 0
val decision = DngWarpRectilinear.decide(
parameters = parameters,
flags = opcodeFlags,
width = width,
height = height,
left = outputSourceBounds.left,
top = outputSourceBounds.top,
right = outputSourceBounds.right,
bottom = outputSourceBounds.bottom,
)
when (decision.rejection) {
DngWarpRectilinear.Rejection.NONE -> {
parameters.forEach(applicable::add)
}
DngWarpRectilinear.Rejection.MALFORMED_OR_UNSAFE -> {
PLog.w(
TAG,
"Skipping malformed or numerically unsafe DNG WarpRectilinear " +
"flags=$opcodeFlags parameters=${parameters.contentToString()}",
)
}
DngWarpRectilinear.Rejection.OPTIONAL_REQUIRES_EDGE_CLAMPING -> {
PLog.w(
TAG,
"Skipping optional DNG WarpRectilinear without source coverage for " +
"DefaultCrop=$outputSourceBounds; applying it would repeat edge pixels. " +
"parameters=${parameters.contentToString()}",
)
}
}
}
return true
return applicable.takeIf { it.isNotEmpty() }?.toFloatArray()
}
private fun roundUp(value: Int, multiple: Int): Int {
@@ -18,6 +18,7 @@ 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.DngWarpRectilinear
import com.hinnka.mycamera.raw.RawCfaCorrection
import com.hinnka.mycamera.raw.RawMetadata
import com.hinnka.mycamera.raw.RawWhiteLevelCorrection
@@ -36,6 +37,35 @@ import kotlin.math.roundToInt
import kotlin.math.roundToLong
import kotlin.math.sqrt
/**
* Converts AOSP DngCreator's normalized Camera2 distortion vector into the six DNG 1.3
* WarpRectilinear coefficients.
*
* normalizeLensDistortion scales element zero as well as the higher-order terms. That first
* element is the zoom-out needed to keep the corrected frame inside the available RAW source;
* replacing it with 1.0 makes the edge of the warp sample outside the image.
*/
internal fun camera2DistortionToDngWarpCoefficients(
normalizedDistortion: DoubleArray,
maxRadius: Double,
focal: Double,
): DoubleArray {
require(normalizedDistortion.size == 6)
require(maxRadius.isFinite() && maxRadius > 0.0)
require(focal.isFinite() && focal > 0.0)
val radiusOverFocal = maxRadius / focal
val radiusOverFocalSquared = radiusOverFocal * radiusOverFocal
return doubleArrayOf(
normalizedDistortion[0],
normalizedDistortion[1] * radiusOverFocalSquared,
normalizedDistortion[2] * radiusOverFocalSquared * radiusOverFocalSquared,
normalizedDistortion[3] * radiusOverFocalSquared * radiusOverFocalSquared *
radiusOverFocalSquared,
normalizedDistortion[4] * radiusOverFocal,
normalizedDistortion[5] * radiusOverFocal,
)
}
object SuperResolutionDngWriter {
private const val TAG = "SuperResolutionDngWriter"
@@ -1124,38 +1154,76 @@ object SuperResolutionDngWriter {
val normalizeCy = if (geometry.bufferIncludesPixelArray) cy + geometry.sourceOriginY else cy
val xMin = if (geometry.bufferIncludesPixelArray) geometry.sourceOriginX else 0
val yMin = if (geometry.bufferIncludesPixelArray) geometry.sourceOriginY else 0
normalizeLensDistortion(
normalizedDistortion,
normalizeCx.toDouble(),
normalizeCy.toDouble(),
focal.toDouble(),
geometry.sourceWidth,
geometry.sourceHeight,
xMin,
yMin,
)
if (!normalizeLensDistortion(
normalizedDistortion,
normalizeCx.toDouble(),
normalizeCy.toDouble(),
focal.toDouble(),
geometry.sourceWidth,
geometry.sourceHeight,
xMin,
yMin,
)
) {
PLog.w(TAG, "Skipping WarpRectilinear because no source-covered normalization exists")
return null
}
val maxX = maxOf(geometry.sourceWidth - cx, cx).toDouble()
val maxY = maxOf(geometry.sourceHeight - cy, cy).toDouble()
val maxRadius = sqrt(maxX * maxX + maxY * maxY)
val focalSquared = focal.toDouble() * focal.toDouble()
if (!maxRadius.isFinite() || maxRadius <= 0.0 || focalSquared <= 0.0) return null
val radiusSquared = maxRadius * maxRadius
val coefficients = doubleArrayOf(
1.0,
normalizedDistortion[1] * radiusSquared / focalSquared,
normalizedDistortion[2] * radiusSquared * radiusSquared / (focalSquared * focalSquared),
normalizedDistortion[3] * radiusSquared * radiusSquared * radiusSquared /
(focalSquared * focalSquared * focalSquared),
normalizedDistortion[4] * maxRadius / focal,
normalizedDistortion[5] * maxRadius / focal,
if (!maxRadius.isFinite() || maxRadius <= 0.0) return null
val coefficients = camera2DistortionToDngWarpCoefficients(
normalizedDistortion = normalizedDistortion,
maxRadius = maxRadius,
focal = focal.toDouble(),
)
if (coefficients.any { !it.isFinite() }) return null
val stage3Width = if (geometry.bufferIncludesPixelArray) {
geometry.sourceWidth
} else {
geometry.width
}
val stage3Height = if (geometry.bufferIncludesPixelArray) {
geometry.sourceHeight
} else {
geometry.height
}
val centerH = (cx / geometry.sourceWidth).toDouble().coerceIn(0.0, 1.0)
val centerV = (cy / geometry.sourceHeight).toDouble().coerceIn(0.0, 1.0)
val parameters = FloatArray(8) { index ->
when {
index < 6 -> coefficients[index].toFloat()
index == 6 -> centerH.toFloat()
else -> centerV.toFloat()
}
}
val cropRight = (geometry.defaultCropLeft + geometry.defaultCropWidth).roundToInt()
val cropBottom = (geometry.defaultCropTop + geometry.defaultCropHeight).roundToInt()
if (!DngWarpRectilinear.hasSourceCoverage(
parameters = parameters,
width = stage3Width,
height = stage3Height,
left = geometry.defaultCropLeft.roundToInt(),
top = geometry.defaultCropTop.roundToInt(),
right = cropRight,
bottom = cropBottom,
)
) {
PLog.w(
TAG,
"Skipping WarpRectilinear because DefaultCrop lacks source coverage: " +
"stage3=${stage3Width}x$stage3Height " +
"crop=${geometry.defaultCropLeft},${geometry.defaultCropTop}," +
"$cropRight,$cropBottom coefficients=${coefficients.contentToString()}",
)
return null
}
val payload = ByteArrayOutputStream()
payload.write(beUInt(1))
coefficients.forEach { payload.write(beDouble(it)) }
payload.write(beDouble((cx / geometry.sourceWidth).toDouble().coerceIn(0.0, 1.0)))
payload.write(beDouble((cy / geometry.sourceHeight).toDouble().coerceIn(0.0, 1.0)))
payload.write(beDouble(centerH))
payload.write(beDouble(centerV))
val opcode = buildOpcode(id = 1, flags = 1, payload = payload.toByteArray())
return ByteArrayOutputStream().apply {
write(beUInt(1))
@@ -1173,7 +1241,7 @@ object SuperResolutionDngWriter {
preCorrectionHeight: Int,
xMin: Int,
yMin: Int,
) {
): Boolean {
val scale = findPostCorrectionScale(
distortion,
cx,
@@ -1183,12 +1251,13 @@ object SuperResolutionDngWriter {
preCorrectionHeight,
xMin,
yMin,
) ?: return
) ?: return false
val scalePowers = intArrayOf(1, 3, 5, 7, 2, 2)
distortion.indices.forEach { index ->
distortion[index] *= Math.pow(scale, scalePowers[index].toDouble())
}
PLog.d(TAG, "DNG WarpRectilinear post-correction scale=$scale")
return true
}
private fun findPostCorrectionScale(
@@ -0,0 +1,72 @@
package com.hinnka.mycamera.raw
import org.junit.Assert.assertEquals
import org.junit.Assert.assertFalse
import org.junit.Assert.assertTrue
import org.junit.Test
class DngWarpRectilinearTest {
private val malformedPhotonSample = floatArrayOf(
1f,
0.016676925f,
0.001357187f,
-0.0038023079f,
0f,
0f,
0.5009297f,
0.5010741f,
)
@Test
fun optionalWarpThatMapsDefaultCropOutsideRawIsSkipped() {
val decision = decide(malformedPhotonSample, DngWarpRectilinear.OPTIONAL_FLAG)
assertFalse(decision.apply)
assertEquals(
DngWarpRectilinear.Rejection.OPTIONAL_REQUIRES_EDGE_CLAMPING,
decision.rejection,
)
}
@Test
fun mandatoryWarpIsNotSilentlyDiscardedForCoverage() {
val decision = decide(malformedPhotonSample, flags = 0)
assertTrue(decision.apply)
assertEquals(DngWarpRectilinear.Rejection.NONE, decision.rejection)
}
@Test
fun normalizedRadialOffsetKeepsFullDefaultCropInsideSource() {
val normalized = malformedPhotonSample.copyOf().also { it[0] = 0.984f }
assertTrue(
DngWarpRectilinear.hasSourceCoverage(
parameters = normalized,
width = WIDTH,
height = HEIGHT,
left = 0,
top = 0,
right = WIDTH,
bottom = HEIGHT,
)
)
}
private fun decide(parameters: FloatArray, flags: Int): DngWarpRectilinear.Decision =
DngWarpRectilinear.decide(
parameters = parameters,
flags = flags,
width = WIDTH,
height = HEIGHT,
left = 0,
top = 0,
right = WIDTH,
bottom = HEIGHT,
)
private companion object {
const val WIDTH = 4032
const val HEIGHT = 3024
}
}
@@ -8,6 +8,22 @@ import java.nio.ByteBuffer
import java.nio.ByteOrder
class SuperResolutionDngWriterIfdTest {
@Test
fun `WarpRectilinear keeps DngCreator normalization scale as radial offset`() {
val coefficients = camera2DistortionToDngWarpCoefficients(
normalizedDistortion = doubleArrayOf(0.984, 0.01, 0.002, -0.0005, 0.0002, -0.0003),
maxRadius = 2.0,
focal = 4.0,
)
assertEquals(0.984, coefficients[0], 0.0)
assertEquals(0.0025, coefficients[1], 1e-12)
assertEquals(0.000125, coefficients[2], 1e-12)
assertEquals(-0.0000078125, coefficients[3], 1e-12)
assertEquals(0.0001, coefficients[4], 1e-12)
assertEquals(-0.00015, coefficients[5], 1e-12)
}
@Test
fun `header links ExifIFD and keeps focal length out of IFD0`() {
val primaryEntries = listOf(