fix: dng creator

This commit is contained in:
Hinnka committed 2026-07-11 11:09:11 +08:00
1 parent 2d6f2b60b7
commit e025509f41
6 files changed
+676 -72

No files matched your search

+109 -45
View File
@@ -582,6 +582,8 @@ struct DngRawTagInfo {
std::vector<double> blackLevel;
std::vector<double> blackDeltaH;
std::vector<double> blackDeltaV;
bool hasFixBadPixelsList = false;
std::vector<float> warpRectilinear;
};
static int bayerBlackLevelIndexForPattern(int cfaPattern, int col, int row) {
@@ -1580,18 +1582,6 @@ static bool dngSdkCameraToPcsForWhite(const DngSdkPreparedColor &prepared,
const DngSdkMatrixForWhite matrices =
dngSdkFindXyzToCamera(prepared, whiteXy);
std::array<float, 3> whiteXyz;
if (!xyToXyz(whiteXy, whiteXyz)) {
return false;
}
std::array<float, 3> cameraWhite =
multiplyMatrixVector(matrices.colorMatrix, whiteXyz);
const float whiteScale =
1.0f / std::max(maxVectorEntry(cameraWhite), 1e-6f);
for (float &value : cameraWhite) {
value = std::clamp(value * whiteScale, 0.001f, 1.0f);
}
Matrix3x3 pcsToCamera =
matrices.colorMatrix.multiply(dngMapWhiteMatrix(d50Xy, whiteXy));
const std::array<float, 3> pcsWhite =
@@ -1601,28 +1591,9 @@ static bool dngSdkCameraToPcsForWhite(const DngSdkPreparedColor &prepared,
value *= pcsScale;
}
if (matrices.hasForwardMatrix) {
const Matrix3x3 individualToReference =
diagonalMatrix3x3(prepared.analogBalance)
.multiply(matrices.cameraCalibration)
.invert();
const std::array<float, 3> referenceCameraWhite =
multiplyMatrixVector(individualToReference, cameraWhite);
if (referenceCameraWhite[0] <= 1e-6f ||
referenceCameraWhite[1] <= 1e-6f ||
referenceCameraWhite[2] <= 1e-6f) {
return false;
}
const Matrix3x3 inverseWhite = diagonalMatrix3x3({
1.0f / referenceCameraWhite[0],
1.0f / referenceCameraWhite[1],
1.0f / referenceCameraWhite[2],
});
cameraToPcs =
matrices.forwardMatrix.multiply(inverseWhite).multiply(individualToReference);
return true;
}
// PhotonCamera deliberately renders from the interpolated ColorMatrix path.
// ForwardMatrix remains preserved in DNG metadata for external renderers, but
// must not override the app's established ColorMatrix rendering behavior.
cameraToPcs = pcsToCamera.invert();
return true;
}
@@ -2596,6 +2567,76 @@ static bool parseDngCfaInfo(const char *path, DngCfaInfo &info) {
return info.repeatRows > 0 && info.repeatCols > 0 && info.patternLen > 0;
}
static uint32_t dngOpcodeReadU32(const unsigned char *p) {
return (static_cast<uint32_t>(p[0]) << 24) |
(static_cast<uint32_t>(p[1]) << 16) |
(static_cast<uint32_t>(p[2]) << 8) |
static_cast<uint32_t>(p[3]);
}
static double dngOpcodeReadDouble(const unsigned char *p) {
const uint64_t bits = (static_cast<uint64_t>(p[0]) << 56) |
(static_cast<uint64_t>(p[1]) << 48) |
(static_cast<uint64_t>(p[2]) << 40) |
(static_cast<uint64_t>(p[3]) << 32) |
(static_cast<uint64_t>(p[4]) << 24) |
(static_cast<uint64_t>(p[5]) << 16) |
(static_cast<uint64_t>(p[6]) << 8) |
static_cast<uint64_t>(p[7]);
double value;
memcpy(&value, &bits, sizeof(value));
return value;
}
static void parseDngOpcodeList(const std::vector<unsigned char> &data,
DngRawTagInfo &info, int opcodeStage) {
if (data.size() < 4)
return;
const uint32_t count = std::min<uint32_t>(dngOpcodeReadU32(data.data()), 1024);
size_t offset = 4;
for (uint32_t index = 0; index < count; ++index) {
if (offset + 16 > data.size())
return;
const uint32_t id = dngOpcodeReadU32(data.data() + offset);
const uint32_t payloadSize = dngOpcodeReadU32(data.data() + offset + 12);
offset += 16;
if (payloadSize > data.size() - offset)
return;
if (opcodeStage == 2 && id == 5 && payloadSize >= 12) {
const unsigned char *payload = data.data() + offset;
const uint32_t bayerPhase = dngOpcodeReadU32(payload);
const uint32_t pointCount = dngOpcodeReadU32(payload + 4);
const uint32_t rectCount = dngOpcodeReadU32(payload + 8);
const uint64_t expectedSize = 12ull + 8ull * pointCount + 16ull * rectCount;
if (bayerPhase <= 3 && expectedSize == payloadSize &&
(pointCount > 0 || rectCount > 0)) {
info.hasFixBadPixelsList = true;
LOGI("DNG FixBadPixelsList: phase=%u points=%u rects=%u",
bayerPhase, pointCount, rectCount);
} else {
LOGW("Ignoring malformed DNG FixBadPixelsList: phase=%u points=%u rects=%u payload=%u expected=%llu",
bayerPhase, pointCount, rectCount, payloadSize,
static_cast<unsigned long long>(expectedSize));
}
} else if (opcodeStage == 3 && id == 1 && payloadSize >= 68) {
const unsigned char *payload = data.data() + offset;
const uint32_t planes = dngOpcodeReadU32(payload);
if (planes == 1 && payloadSize == 68) {
std::vector<float> warp(8);
bool valid = true;
for (int i = 0; i < 8; ++i) {
const double value = dngOpcodeReadDouble(payload + 4 + i * 8);
valid = valid && std::isfinite(value);
warp[i] = static_cast<float>(value);
}
if (valid)
info.warpRectilinear.insert(info.warpRectilinear.end(), warp.begin(), warp.end());
}
}
offset += payloadSize;
}
}
static void parseDngRawTagIfd(std::ifstream &file, bool littleEndian,
uint32_t ifdOffset, DngRawTagInfo &info, int depth) {
if (ifdOffset == 0 || depth > 8)
@@ -2621,7 +2662,10 @@ static void parseDngRawTagIfd(std::ifstream &file, bool littleEndian,
const uint32_t count = tiffReadU32(entry + 4, littleEndian);
std::vector<unsigned char> data;
if (tag == 0xc68d && count >= 4 &&
if ((tag == 0xc741 || tag == 0xc74e) && count > 0 &&
tiffEntryData(file, entry, littleEndian, type, count, data)) {
parseDngOpcodeList(data, info, tag == 0xc741 ? 2 : 3);
} else if (tag == 0xc68d && count >= 4 &&
tiffEntryData(file, entry, littleEndian, type, count, data)) {
info.hasActiveArea = true;
for (int i = 0; i < 4; ++i) {
@@ -2967,7 +3011,15 @@ Java_com_hinnka_mycamera_raw_RawDemosaicProcessor_processDngNative(
LibRaw RawProcessor;
ExifData ed;
RawProcessor.imgdata.rawparams.use_dngsdk = 0;
DngRawTagInfo dngRawTagInfo;
parseDngRawTagInfo(path, dngRawTagInfo);
if (dngRawTagInfo.hasFixBadPixelsList) {
RawProcessor.imgdata.rawparams.use_dngsdk = LIBRAW_DNG_ALL;
RawProcessor.imgdata.rawparams.options |= LIBRAW_RAWOPTIONS_DNG_STAGE2_IFPRESENT;
LOGI("processDngNative: enabling DNG SDK Stage2 for FixBadPixelsList");
} else {
RawProcessor.imgdata.rawparams.use_dngsdk = 0;
}
RawProcessor.set_exifparser_handler(exif_callback, &ed);
int ret = RawProcessor.open_file(path);
@@ -2983,6 +3035,8 @@ Java_com_hinnka_mycamera_raw_RawDemosaicProcessor_processDngNative(
env->ReleaseStringUTFChars(filePath, path);
return nullptr;
}
const bool dngStage2Applied =
(RawProcessor.imgdata.process_warnings & LIBRAW_WARN_DNG_STAGE2_APPLIED) != 0;
jobject embeddedPreviewBitmap = nullptr;
ret = RawProcessor.unpack_thumb();
@@ -3035,8 +3089,6 @@ Java_com_hinnka_mycamera_raw_RawDemosaicProcessor_processDngNative(
const jint samplesPerPixel = useLinearRawRgb ? 3 : 1;
const bool isDngInput = RawProcessor.imgdata.idata.dng_version != 0;
DngRawTagInfo dngRawTagInfo;
parseDngRawTagInfo(path, dngRawTagInfo);
jint cfaPattern = 0;
// 判定 CFA 模式。LibRaw COLOR()/FC() folds DNG CFAPattern into the dcraw
@@ -3126,14 +3178,15 @@ Java_com_hinnka_mycamera_raw_RawDemosaicProcessor_processDngNative(
static_cast<int>(levels.dng_cblack[5]));
const bool blackDeltaApplied =
useLinearRawRgb ? false : applyDngBlackLevelDeltas(RawProcessor, dngRawTagInfo);
useLinearRawRgb || dngStage2Applied ? false
: applyDngBlackLevelDeltas(RawProcessor, dngRawTagInfo);
// Read the TOTAL effective black level per LibRaw channel.
// LibRaw stores it as: color.black + cblack[channel] + repeat_pattern[position].
float librawBlackLevels[4] = {};
float activeBlackLevels[4] = {};
float exportedBlackLevels[4] = {};
if (!useLinearRawRgb) {
if (!useLinearRawRgb && !dngStage2Applied) {
computeEffectiveBlackLevels(RawProcessor, cfaPattern, left, top, librawBlackLevels);
mapLibRawBlackLevelsForGpu(RawProcessor, cfaPattern, left, top,
librawBlackLevels, activeBlackLevels,
@@ -3184,7 +3237,7 @@ Java_com_hinnka_mycamera_raw_RawDemosaicProcessor_processDngNative(
0.0f, 0.0f, 1.0f, 1.0f,
0.0f, 0.0f, static_cast<float>(std::max(1, width)), static_cast<float>(std::max(1, height))};
jfloatArray exportedLscArray = nullptr;
if (!useLinearRawRgb) {
if (!useLinearRawRgb && !dngStage2Applied) {
exportedLscArray = buildDngLensShadingArray(
env, RawProcessor, cfaPattern, left, top, exportedLscWidth,
exportedLscHeight, exportedLscGrid);
@@ -3194,8 +3247,9 @@ Java_com_hinnka_mycamera_raw_RawDemosaicProcessor_processDngNative(
exportedLscGridArray = env->NewFloatArray(8);
env->SetFloatArrayRegion(exportedLscGridArray, 0, 8, exportedLscGrid);
}
LOGI("dng gain map: opcode2_len=%u native_apply=0 exported=%d",
LOGI("dng gain map: opcode2_len=%u stage2Applied=%d exported=%d",
RawProcessor.imgdata.color.dng_levels.rawopcodes[1].len,
dngStage2Applied ? 1 : 0,
exportedLscArray ? 1 : 0);
RawProcessor.imgdata.params.output_bps = 16;
@@ -3344,7 +3398,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[FIIFF[FII[FFIJF[I[I[FLandroid/graphics/Bitmap;)V");
"(Ljava/nio/ByteBuffer;IIIIF[F[F[F[FIIFF[FII[FFIJF[I[I[F[FLandroid/graphics/Bitmap;)V");
jfloatArray blackLevelArray = env->NewFloatArray(4);
for (int i = 0; i < 4; i++) {
@@ -3549,8 +3603,9 @@ Java_com_hinnka_mycamera_raw_RawDemosaicProcessor_processDngNative(
finalCCM.m[5], finalCCM.m[6], finalCCM.m[7], finalCCM.m[8]);
// 其它
jfloat whiteLevel =
(jfloat)RawProcessor.imgdata.color.dng_levels.dng_whitelevel[0];
jfloat whiteLevel = dngStage2Applied
? 65535.0f
: (jfloat)RawProcessor.imgdata.color.dng_levels.dng_whitelevel[0];
if (whiteLevel <= 0 && useLinearRawRgb)
whiteLevel = 65535.0f;
else if (whiteLevel <= 0)
@@ -3613,6 +3668,14 @@ Java_com_hinnka_mycamera_raw_RawDemosaicProcessor_processDngNative(
noiseProfileArray = env->NewFloatArray(8);
env->SetFloatArrayRegion(noiseProfileArray, 0, 8, ed.noiseProfile);
}
jfloatArray warpRectilinearArray = nullptr;
if (!dngRawTagInfo.warpRectilinear.empty() &&
dngRawTagInfo.warpRectilinear.size() % 8 == 0) {
warpRectilinearArray = env->NewFloatArray(dngRawTagInfo.warpRectilinear.size());
env->SetFloatArrayRegion(warpRectilinearArray, 0,
dngRawTagInfo.warpRectilinear.size(),
dngRawTagInfo.warpRectilinear.data());
}
jobject dngData = env->NewObject(
dngDataClass, constructor, rawDataBuffer, width, height, rowStride,
@@ -3620,6 +3683,7 @@ Java_com_hinnka_mycamera_raw_RawDemosaicProcessor_processDngNative(
cfaPattern, ed.rotation, baselineExposure, shadowScale, exportedLscArray, exportedLscWidth, exportedLscHeight,
exportedLscGridArray, exposureBias, iso,
shutterSpeedLong, aperture, activeArray, defaultCropArray, noiseProfileArray,
warpRectilinearArray,
embeddedPreviewBitmap);
// 释放资源
@@ -3335,7 +3335,7 @@ object GalleryManager {
metadata: MediaMetadata,
shouldAutoSave: Boolean,
exportDngWithRawExport: Boolean,
baselineExposureEv: Float = 0f,
baselineExposureEv: Float? = null,
profileGainTableMap: DngProfileGainTableMap? = null,
profileToneMapMode: RawProfileToneMapMode = RawProfileToneMapMode.GooglePixel,
imageLayout: SuperResolutionDngWriter.ImageLayout = SuperResolutionDngWriter.ImageLayout.CFA,
@@ -55,6 +55,7 @@ data class DngRawData @Keep constructor(
val activeArray: IntArray?, // [left, top, right, bottom]
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 embeddedPreview: Bitmap? = null,
) : AutoCloseable {
@@ -117,6 +118,10 @@ data class DngRawData @Keep constructor(
if (other.defaultCrop == null) return false
if (!defaultCrop.contentEquals(other.defaultCrop)) return false
} else if (other.defaultCrop != null) return false
if (warpRectilinear != null) {
if (other.warpRectilinear == null) return false
if (!warpRectilinear.contentEquals(other.warpRectilinear)) return false
} else if (other.warpRectilinear != null) return false
if (embeddedPreview != null) {
if (other.embeddedPreview == null) return false
if (!embeddedPreview.sameAs(other.embeddedPreview)) return false
@@ -145,6 +150,7 @@ data class DngRawData @Keep constructor(
result = 31 * result + lensShadingMapHeight
result = 31 * result + (lensShadingMapGrid?.contentHashCode() ?: 0)
result = 31 * result + (defaultCrop?.contentHashCode() ?: 0)
result = 31 * result + (warpRectilinear?.contentHashCode() ?: 0)
result = 31 * result + (embeddedPreview?.hashCode() ?: 0)
return result
}
@@ -265,6 +265,7 @@ class RawDemosaicProcessor {
private var quadRefineProgram = 0
private var quadWriteOutputProgram = 0
private var linearRcdProgram = 0
private var warpRectilinearProgram = 0
private var linearRawRgbProgram = 0
private var rawHdrLinearAccumulateProgram = 0
private var rawHdrLinearNormalizeProgram = 0
@@ -1272,6 +1273,7 @@ class RawDemosaicProcessor {
var actualRotation = rotation
var dngRawDataCleanup: DngRawData? = null
var embeddedDngJpegPreview: Bitmap? = null
var dngWarpRectilinear: FloatArray? = null
val requestedColorEngine = rawRenderingEngine
val hasDcpSelection = dcpRenderPlan != null || rawDcpId != null
val profileWorkingColorSpace = ColorSpace.ProPhoto
@@ -1311,6 +1313,7 @@ class RawDemosaicProcessor {
}
dngRawDataCleanup = dngRawData
embeddedDngJpegPreview = dngRawData.embeddedPreview
dngWarpRectilinear = dngRawData.warpRectilinear
actualRawData = dngRawData.rawData
actualWidth = dngRawData.width
actualHeight = dngRawData.height
@@ -2004,6 +2007,43 @@ class RawDemosaicProcessor {
}
}
dngWarpRectilinear?.takeIf { it.isNotEmpty() && it.size % 8 == 0 }?.let { warps ->
var appliedWarpCount = 0
for (offset in warps.indices step 8) {
val parameters = warps.copyOfRange(offset, offset + 8)
// dng_opcode_BaseWarpRectilinear::IsNOP skips an identity radial
// transform with zero tangential terms. Preserve that Stage 3 behavior.
if (isNoOpWarpRectilinear(parameters)) {
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,
targetFramebufferId = linearOutputFramebufferId,
width = actualWidth,
height = actualHeight,
parameters = parameters,
)
if (!warped) break
val tempTex = demosaicTextureId
demosaicTextureId = linearOutputTextureId
linearOutputTextureId = tempTex
val tempFbo = demosaicFramebufferId
demosaicFramebufferId = linearOutputFramebufferId
linearOutputFramebufferId = tempFbo
appliedWarpCount++
}
PLog.d(TAG, "Applied $appliedWarpCount/${warps.size / 8} DNG WarpRectilinear opcode(s) before color conversion")
}
// RAW AE 使用低分辨率实际渲染结果测光,使高光压缩和最终输出保持一致。
val meteringResult = resolveRawAutoExposureEv(
metadata = actualMetadata,
@@ -3162,6 +3202,69 @@ class RawDemosaicProcessor {
}
""".trimIndent()
private val WARP_RECTILINEAR_FRAGMENT_SHADER = """
#version 300 es
precision highp float;
in vec2 vTexCoord;
out vec4 fragColor;
uniform sampler2D uSourceTexture;
uniform vec2 uImageSize;
uniform vec4 uRadial;
uniform vec2 uTangential;
uniform vec2 uCenter;
float bicubicWeight(float x) {
const float A = -0.75;
x = abs(x);
if (x >= 2.0) return 0.0;
if (x >= 1.0) return ((A * x - 5.0 * A) * x + 8.0 * A) * x - 4.0 * A;
return ((A + 2.0) * x - (A + 3.0)) * x * x + 1.0;
}
vec4 sampleDngBicubic(vec2 sourcePixel) {
ivec2 imageMax = ivec2(uImageSize) - ivec2(1);
sourcePixel = clamp(sourcePixel, vec2(0.0), uImageSize - vec2(1.0));
vec2 base = floor(sourcePixel);
// dng_filter_warp uses a 32-entry fractional weight table.
vec2 fraction = floor((sourcePixel - base) * 32.0) * (1.0 / 32.0);
vec4 total = vec4(0.0);
float totalWeight = 0.0;
for (int y = -1; y <= 2; ++y) {
float wy = bicubicWeight(float(y) - fraction.y);
for (int x = -1; x <= 2; ++x) {
float weight = bicubicWeight(float(x) - fraction.x) * wy;
ivec2 pixel = clamp(ivec2(base) + ivec2(x, y), ivec2(0), imageMax);
total += texelFetch(uSourceTexture, pixel, 0) * weight;
totalWeight += weight;
}
}
return total / max(totalWeight, 1e-8);
}
void main() {
vec2 centerPx = uCenter * uImageSize;
// DNG pixel centers are integer coordinates; fragment centers are n + 0.5.
vec2 dstPx = gl_FragCoord.xy - vec2(0.5);
vec2 diff = dstPx - centerPx;
vec2 farthest = max(centerPx, uImageSize - centerPx);
float normRadius = max(length(farthest), 1.0);
vec2 normalized = diff / normRadius;
float r2 = min(dot(normalized, normalized), 1.0);
float ratio = uRadial.x + uRadial.y * r2 +
uRadial.z * r2 * r2 + uRadial.w * r2 * r2 * r2;
float dh = normalized.x;
float dv = normalized.y;
vec2 tangent = vec2(
uTangential.y * (r2 + 2.0 * dh * dh) + 2.0 * uTangential.x * dh * dv,
uTangential.x * (r2 + 2.0 * dv * dv) + 2.0 * uTangential.y * dh * dv
);
vec2 srcPx = centerPx + normRadius * (normalized * ratio + tangent);
fragColor = sampleDngBicubic(srcPx);
}
""".trimIndent()
private fun initRcdPrograms(vShader: Int) {
rcdPopulateProgram = compileComputeProgram(RcdShaders.POPULATE, "POPULATE")
rcdStep1Program = compileComputeProgram(RcdShaders.STEP_1, "STEP_1")
@@ -3214,6 +3317,11 @@ class RawDemosaicProcessor {
RAW_HDR_LINEAR_PREVIEW_FRAGMENT_SHADER,
"rawHdrLinearPreview"
)
warpRectilinearProgram = linkFragmentProgram(
vShader,
WARP_RECTILINEAR_FRAGMENT_SHADER,
"warpRectilinear"
)
}
private fun linkFragmentProgram(
@@ -3923,6 +4031,102 @@ class RawDemosaicProcessor {
checkGlError("DenoiseProfile passthrough")
}
private fun renderWarpRectilinearPass(
sourceTextureId: Int,
targetFramebufferId: Int,
width: Int,
height: Int,
parameters: FloatArray,
): Boolean {
if (warpRectilinearProgram == 0 || parameters.size != 8) return false
GLES30.glBindFramebuffer(GLES30.GL_FRAMEBUFFER, targetFramebufferId)
GLES30.glViewport(0, 0, width, height)
GLES30.glUseProgram(warpRectilinearProgram)
val textureMatrix = FloatArray(16)
GlMatrix.setIdentityM(textureMatrix, 0)
GLES30.glUniformMatrix4fv(
GLES30.glGetUniformLocation(warpRectilinearProgram, "uTexMatrix"),
1,
false,
textureMatrix,
0,
)
GLES30.glActiveTexture(GLES30.GL_TEXTURE0)
GLES30.glBindTexture(GLES30.GL_TEXTURE_2D, sourceTextureId)
GLES30.glUniform1i(
GLES30.glGetUniformLocation(warpRectilinearProgram, "uSourceTexture"),
0
)
GLES30.glUniform2f(
GLES30.glGetUniformLocation(warpRectilinearProgram, "uImageSize"),
width.toFloat(),
height.toFloat()
)
GLES30.glUniform4f(
GLES30.glGetUniformLocation(warpRectilinearProgram, "uRadial"),
parameters[0], parameters[1], parameters[2], parameters[3]
)
GLES30.glUniform2f(
GLES30.glGetUniformLocation(warpRectilinearProgram, "uTangential"),
parameters[4], parameters[5]
)
GLES30.glUniform2f(
GLES30.glGetUniformLocation(warpRectilinearProgram, "uCenter"),
parameters[6], parameters[7]
)
drawQuad(warpRectilinearProgram)
GLES30.glBindTexture(GLES30.GL_TEXTURE_2D, 0)
GLES30.glBindFramebuffer(GLES30.GL_FRAMEBUFFER, 0)
checkGlError("WarpRectilinearPass")
return true
}
private fun isNoOpWarpRectilinear(parameters: FloatArray): Boolean {
if (parameters.size != 8) return false
return parameters[0] == 1f && (1..5).all { index -> parameters[index] == 0f }
}
private fun isSafeWarpRectilinear(
parameters: FloatArray,
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
}
}
return true
}
private fun roundUp(value: Int, multiple: Int): Int {
return ((value + multiple - 1) / multiple) * multiple
}
@@ -8325,6 +8529,7 @@ class RawDemosaicProcessor {
if (quadRefineProgram != 0) GLES31.glDeleteProgram(quadRefineProgram)
if (quadWriteOutputProgram != 0) GLES31.glDeleteProgram(quadWriteOutputProgram)
if (linearRcdProgram != 0) GLES31.glDeleteProgram(linearRcdProgram)
if (warpRectilinearProgram != 0) GLES31.glDeleteProgram(warpRectilinearProgram)
if (linearRawRgbProgram != 0) GLES31.glDeleteProgram(linearRawRgbProgram)
if (rawHdrLinearAccumulateProgram != 0) GLES31.glDeleteProgram(rawHdrLinearAccumulateProgram)
if (rawHdrLinearNormalizeProgram != 0) GLES31.glDeleteProgram(rawHdrLinearNormalizeProgram)
@@ -271,7 +271,7 @@ object RawProcessor {
whiteLevelMode: String? = null,
customWhiteLevel: Float? = null,
cfaCorrectionMode: String? = null,
baselineExposureEv: Float = 0f,
baselineExposureEv: Float? = null,
profileGainTableMap: DngProfileGainTableMap? = null,
profileName: String? = null,
profileToneCurve: FloatArray? = null,
@@ -6,9 +6,11 @@ import android.hardware.camera2.CaptureResult
import android.hardware.camera2.params.ColorSpaceTransform
import android.hardware.camera2.params.LensShadingMap
import android.os.Build
import android.os.SystemClock
import com.hinnka.mycamera.raw.DngProfileGainTableMap
import com.hinnka.mycamera.raw.DngProfileToneCurve
import com.hinnka.mycamera.raw.RawCfaCorrection
import com.hinnka.mycamera.raw.RawMetadata
import com.hinnka.mycamera.raw.RawWhiteLevelCorrection
import java.io.ByteArrayOutputStream
import java.io.FileOutputStream
@@ -93,6 +95,8 @@ object SuperResolutionDngWriter {
private const val TAG_DEFAULT_CROP_SIZE = 50720
private const val TAG_COLOR_MATRIX_1 = 50721
private const val TAG_COLOR_MATRIX_2 = 50722
private const val TAG_CAMERA_CALIBRATION_1 = 50723
private const val TAG_CAMERA_CALIBRATION_2 = 50724
private const val TAG_PROFILE_NAME = 50936
private const val TAG_PROFILE_TONE_CURVE = 50940
private const val TAG_AS_SHOT_NEUTRAL = 50728
@@ -101,6 +105,7 @@ object SuperResolutionDngWriter {
private const val TAG_CALIBRATION_ILLUMINANT_2 = 50779
private const val TAG_ACTIVE_AREA = 50829
private const val TAG_OPCODE_LIST_2 = 51009
private const val TAG_OPCODE_LIST_3 = 51022
private const val TAG_NOISE_PROFILE = 51041
private const val TAG_DEFAULT_BLACK_RENDER = 51110
private const val TAG_PROFILE_GAIN_TABLE_MAP_2 = DngProfileGainTableMap.TAG_PROFILE_GAIN_TABLE_MAP2
@@ -135,7 +140,7 @@ object SuperResolutionDngWriter {
customBlackLevel: Float? = null,
whiteLevelMode: String? = null,
customWhiteLevel: Float? = null,
baselineExposureEv: Float = 0f,
baselineExposureEv: Float? = null,
profileGainTableMap: DngProfileGainTableMap? = null,
profileName: String? = null,
profileToneCurve: FloatArray? = null,
@@ -272,7 +277,7 @@ object SuperResolutionDngWriter {
blackLevel: FloatArray,
whiteLevel: Int,
imageByteCount: Long,
baselineExposureEv: Float,
baselineExposureEv: Float?,
profileGainTableMap: DngProfileGainTableMap?,
profileName: String?,
profileToneCurve: FloatArray?,
@@ -288,21 +293,25 @@ object SuperResolutionDngWriter {
val defaultScaleX = 1.0
val defaultScaleY = 1.0
val cameraModel = buildCameraModel(characteristics)
val geometry = resolveDngGeometry(width, height, characteristics)
val illuminant1 = characteristics.get(CameraCharacteristics.SENSOR_REFERENCE_ILLUMINANT1) ?: 21
val illuminant2 = characteristics.get(CameraCharacteristics.SENSOR_REFERENCE_ILLUMINANT2)?.toInt()
val colorMatrix1 = characteristics.get(CameraCharacteristics.SENSOR_COLOR_TRANSFORM1)
val colorMatrix2 = characteristics.get(CameraCharacteristics.SENSOR_COLOR_TRANSFORM2)
val calibrationMatrix1 = characteristics.get(CameraCharacteristics.SENSOR_CALIBRATION_TRANSFORM1)
val calibrationMatrix2 = characteristics.get(CameraCharacteristics.SENSOR_CALIBRATION_TRANSFORM2)
val noiseProfile = buildNoiseProfile(captureResult)
val dateTime = SimpleDateFormat("yyyy:MM:dd HH:mm:ss", Locale.US).format(Date())
val dateTime = SimpleDateFormat("yyyy:MM:dd HH:mm:ss", Locale.US).format(
captureResult.get(CaptureResult.SENSOR_TIMESTAMP)?.let { timestampNs ->
Date(System.currentTimeMillis() - SystemClock.elapsedRealtime() + timestampNs / 1_000_000L)
} ?: Date()
)
val exposureTimeSeconds = captureResult.get(CaptureResult.SENSOR_EXPOSURE_TIME)
?.takeIf { it > 0L }
?.let { it.toDouble() / 1_000_000_000.0 }
val iso = captureResult.get(CaptureResult.SENSOR_SENSITIVITY)?.takeIf { it > 0 }
val aperture = captureResult.get(CaptureResult.LENS_APERTURE)?.takeIf { it > 0f }
val focalLength = captureResult.get(CaptureResult.LENS_FOCAL_LENGTH)?.takeIf { it > 0f }
?: characteristics.get(CameraCharacteristics.LENS_INFO_AVAILABLE_FOCAL_LENGTHS)
?.firstOrNull()
?.takeIf { it > 0f }
val focalLength35mm = calculate35mmEquivalent(characteristics, focalLength)
val exifWhiteBalance = captureResult.get(CaptureResult.CONTROL_AWB_MODE)?.let { awbMode ->
if (awbMode == CameraMetadata.CONTROL_AWB_MODE_AUTO) 0 else 1
@@ -313,12 +322,17 @@ object SuperResolutionDngWriter {
buildOpcodeList2(
captureResult = captureResult,
cfaPattern = cfaPattern,
width = width,
height = height
geometry = geometry,
)
} else {
null
}
val opcodeList3 = if (isCfa) buildOpcodeList3(captureResult, geometry) else null
val resolvedBaselineExposureEv = baselineExposureEv ?: captureResult
.get(CaptureResult.CONTROL_POST_RAW_SENSITIVITY_BOOST)
?.takeIf { it > 0 }
?.let { kotlin.math.log2(it / 100.0).toFloat() }
?: 0f
val blackLevelRepeatDim = RawCfaCorrection.repeatPatternDim(cfaPattern)
val encodedBlackLevels = if (isCfa) {
blackLevelByCfaPosition(cfaPattern, blackLevel)
@@ -383,15 +397,19 @@ object SuperResolutionDngWriter {
add(longArray(TAG_WHITE_LEVEL, LongArray(samplesPerPixel) { whiteLevel.coerceAtLeast(1).toLong() }))
}
add(rationalArray(TAG_DEFAULT_SCALE, listOf(defaultScaleX, defaultScaleY)))
add(rationalArray(TAG_DEFAULT_CROP_ORIGIN, listOf(0.0, 0.0)))
add(rationalArray(TAG_DEFAULT_CROP_SIZE, listOf(width.toDouble(), height.toDouble())))
add(rationalArray(TAG_DEFAULT_CROP_ORIGIN, listOf(geometry.defaultCropLeft, geometry.defaultCropTop)))
add(rationalArray(TAG_DEFAULT_CROP_SIZE, listOf(geometry.defaultCropWidth, geometry.defaultCropHeight)))
colorMatrix1?.let { add(sRationalArray(TAG_COLOR_MATRIX_1, colorTransformToDngMatrix(it))) }
colorMatrix2?.let { add(sRationalArray(TAG_COLOR_MATRIX_2, colorTransformToDngMatrix(it))) }
calibrationMatrix1?.let { add(sRationalArray(TAG_CAMERA_CALIBRATION_1, colorTransformToExactDngMatrix(it))) }
if (illuminant2 != null) {
calibrationMatrix2?.let { add(sRationalArray(TAG_CAMERA_CALIBRATION_2, colorTransformToExactDngMatrix(it))) }
}
add(rationalArray(TAG_AS_SHOT_NEUTRAL, asShotNeutral(captureResult)))
if (!isCfa) {
add(long(TAG_DEFAULT_BLACK_RENDER, 1))
}
add(sRationalArray(TAG_BASELINE_EXPOSURE, listOf(baselineExposureEv.toDouble())))
add(sRationalArray(TAG_BASELINE_EXPOSURE, listOf(resolvedBaselineExposureEv.toDouble())))
if (profileGainTableMap != null) {
add(ascii(TAG_PROFILE_NAME, profileName?.takeIf { it.isNotBlank() }
?: DngProfileToneCurve.GOOGLE_HDR_PROFILE_NAME))
@@ -402,8 +420,9 @@ object SuperResolutionDngWriter {
if (illuminant2 != null && colorMatrix2 != null) {
add(short(TAG_CALIBRATION_ILLUMINANT_2, illuminant2))
}
add(longArray(TAG_ACTIVE_AREA, longArrayOf(0, 0, height.toLong(), width.toLong())))
add(longArray(TAG_ACTIVE_AREA, geometry.activeArea))
opcodeList2?.let { add(undefined(TAG_OPCODE_LIST_2, it)) }
opcodeList3?.let { add(undefined(TAG_OPCODE_LIST_3, it)) }
noiseProfile?.let { add(doubleArray(TAG_NOISE_PROFILE, it)) }
profileGainTableMap?.let {
add(undefined(TAG_PROFILE_GAIN_TABLE_MAP_2, it.encodeProfileGainTableMap2(ByteOrder.LITTLE_ENDIAN)))
@@ -530,26 +549,74 @@ object SuperResolutionDngWriter {
private fun buildOpcodeList2(
captureResult: CaptureResult,
cfaPattern: Int,
width: Int,
height: Int,
geometry: DngGeometry,
): ByteArray? {
val lensShadingMap = captureResult.get(CaptureResult.STATISTICS_LENS_SHADING_CORRECTION_MAP)
?: return null
if (lensShadingMap.columnCount <= 0 || lensShadingMap.rowCount <= 0) return null
val dim = RawCfaCorrection.repeatPatternDim(cfaPattern)
val opcodeCount = dim[0] * dim[1]
val opcodes = ByteArrayOutputStream()
opcodes.write(beUInt(opcodeCount.toLong()))
for (top in 0 until dim[0]) {
for (left in 0 until dim[1]) {
val channel = RawCfaCorrection.camera2LensShadingChannelIndexForPixel(cfaPattern, left, top)
opcodes.write(buildGainMapOpcode(lensShadingMap, channel, top, left, dim[0], dim[1], width, height))
val encodedOpcodes = mutableListOf<ByteArray>()
if (lensShadingMap != null && lensShadingMap.columnCount > 0 && lensShadingMap.rowCount > 0) {
for (top in 0 until dim[0]) {
for (left in 0 until dim[1]) {
val channel = RawCfaCorrection.camera2LensShadingChannelIndexForPixel(cfaPattern, left, top)
encodedOpcodes += buildGainMapOpcode(
lensShadingMap, channel, top, left, dim[0], dim[1], geometry.width, geometry.height
)
}
}
}
buildBadPixelOpcode(captureResult, cfaPattern, geometry)?.let(encodedOpcodes::add)
if (encodedOpcodes.isEmpty()) return null
val opcodes = ByteArrayOutputStream()
opcodes.write(beUInt(encodedOpcodes.size.toLong()))
encodedOpcodes.forEach(opcodes::write)
return opcodes.toByteArray()
}
private fun buildBadPixelOpcode(
captureResult: CaptureResult,
cfaPattern: Int,
geometry: DngGeometry,
): ByteArray? {
if (cfaPattern !in RawMetadata.CFA_RGGB..RawMetadata.CFA_BGGR) return null
// A Camera2 hot-pixel map addresses physical sensor samples. It cannot be
// represented as isolated CFA points after spatial resampling.
if (geometry.scaleX != 1.0 || geometry.scaleY != 1.0) {
PLog.d(TAG, "Skipping FixBadPixelsList for resampled DNG geometry")
return null
}
val points = captureResult.get(CaptureResult.STATISTICS_HOT_PIXEL_MAP)
?.mapNotNull { point ->
val x = ((point.x - geometry.sourceOriginX) * geometry.scaleX).roundToInt()
val y = ((point.y - geometry.sourceOriginY) * geometry.scaleY).roundToInt()
if (x in 0 until geometry.width && y in 0 until geometry.height) x to y else null
}
?.distinct()
.orEmpty()
if (points.isEmpty()) return null
val payload = ByteArrayOutputStream()
payload.write(beUInt(dngSdkBayerPhase(cfaPattern).toLong()))
payload.write(beUInt(points.size.toLong()))
payload.write(beUInt(0))
points.forEach { (x, y) ->
payload.write(beUInt(y.toLong()))
payload.write(beUInt(x.toLong()))
}
PLog.d(
TAG,
"Writing DNG FixBadPixelsList: phase=${dngSdkBayerPhase(cfaPattern)} points=${points.size}"
)
return buildOpcode(id = 5, flags = 1, payload = payload.toByteArray())
}
/** DNG SDK Bayer phase order is GRBG=0, RGGB=1, BGGR=2, GBRG=3. */
private fun dngSdkBayerPhase(cfaPattern: Int): Int = when (cfaPattern) {
RawMetadata.CFA_GRBG -> 0
RawMetadata.CFA_RGGB -> 1
RawMetadata.CFA_BGGR -> 2
RawMetadata.CFA_GBRG -> 3
else -> error("Unsupported Bayer CFA pattern: $cfaPattern")
}
private fun buildGainMapOpcode(
lensShadingMap: LensShadingMap,
channel: Int,
@@ -592,15 +659,270 @@ object SuperResolutionDngWriter {
return opcode.toByteArray()
}
private fun buildOpcodeList3(captureResult: CaptureResult, geometry: DngGeometry): ByteArray? {
if (kotlin.math.abs(geometry.scaleX - geometry.scaleY) > 1e-9) {
PLog.w(TAG, "Skipping WarpRectilinear for non-uniformly scaled DNG geometry")
return null
}
val intrinsics = captureResult.get(CaptureResult.LENS_INTRINSIC_CALIBRATION)
?.takeIf { it.size == 5 }
?: return null
val distortion = captureResult.get(CaptureResult.LENS_DISTORTION)
?.takeIf { it.size == 5 }
?: return null
val focal = intrinsics[0].takeIf { it.isFinite() && it > 0f } ?: return null
// Camera2 intrinsic coordinates are relative to the pre-correction active array.
val cx = intrinsics[2]
val cy = intrinsics[3]
val normalizedDistortion = doubleArrayOf(
1.0,
distortion[0].toDouble(),
distortion[1].toDouble(),
distortion[2].toDouble(),
distortion[3].toDouble(),
distortion[4].toDouble(),
)
val normalizeCx = if (geometry.bufferIncludesPixelArray) cx + geometry.sourceOriginX else cx
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,
)
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 (coefficients.any { !it.isFinite() }) 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)))
val opcode = buildOpcode(id = 1, flags = 1, payload = payload.toByteArray())
return ByteArrayOutputStream().apply {
write(beUInt(1))
write(opcode)
}.toByteArray()
}
/** Mirrors AOSP DngCreator normalizeLensDistortion exactly. */
private fun normalizeLensDistortion(
distortion: DoubleArray,
cx: Double,
cy: Double,
focal: Double,
preCorrectionWidth: Int,
preCorrectionHeight: Int,
xMin: Int,
yMin: Int,
) {
val scale = findPostCorrectionScale(
distortion,
cx,
cy,
focal,
preCorrectionWidth,
preCorrectionHeight,
xMin,
yMin,
) ?: return
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")
}
private fun findPostCorrectionScale(
distortion: DoubleArray,
cx: Double,
cy: Double,
focal: Double,
width: Int,
height: Int,
xMin: Int,
yMin: Int,
): Double? {
var scale = 1.0
while (scale > 0.5) {
if (scaledBoxWithinPreCorrectionArray(
scale, distortion, cx, cy, focal, width, height, xMin, yMin
)
) return scale
scale -= 0.002
}
PLog.w(TAG, "Unable to find DngCreator-compatible post-correction scale; retaining original distortion")
return null
}
private fun scaledBoxWithinPreCorrectionArray(
scale: Double,
distortion: DoubleArray,
cx: Double,
cy: Double,
focal: Double,
width: Int,
height: Int,
xMin: Int,
yMin: Int,
): Boolean {
val left = cx * (1.0 - scale)
val right = (width - 1) * scale + cx * (1.0 - scale)
val top = cy * (1.0 - scale)
val bottom = (height - 1) * scale + cy * (1.0 - scale)
val points = arrayOf(
left to top, cx to top, right to top,
left to cy, right to cy,
left to bottom, cx to bottom, right to bottom,
)
return points.all { (x, y) ->
undistortedPointWithinPreCorrectionArray(
x, y, distortion, cx, cy, focal, width, height, xMin, yMin
)
}
}
private fun undistortedPointWithinPreCorrectionArray(
x: Double,
y: Double,
distortion: DoubleArray,
cx: Double,
cy: Double,
focal: Double,
width: Int,
height: Int,
xMin: Int,
yMin: Int,
): Boolean {
val xp = (x - cx) / focal
val yp = (y - cy) / focal
val x2 = xp * xp
val y2 = yp * yp
val r2 = x2 + y2
val twiceXy = 2.0 * xp * yp
val radial = distortion[0] +
((distortion[3] * r2 + distortion[2]) * r2 + distortion[1]) * r2
val mappedX = (xp * radial + distortion[4] * twiceXy +
distortion[5] * (r2 + 2.0 * x2)) * focal + cx
val mappedY = (yp * radial + distortion[4] * (r2 + 2.0 * y2) +
distortion[5] * twiceXy) * focal + cy
return mappedX >= xMin && mappedY >= yMin &&
mappedX < xMin + width && mappedY < yMin + height
}
private fun buildOpcode(id: Int, flags: Int, payload: ByteArray): ByteArray =
ByteArrayOutputStream().apply {
write(beUInt(id.toLong()))
write(beUInt(0x01030000L))
write(beUInt(flags.toLong()))
write(beUInt(payload.size.toLong()))
write(payload)
}.toByteArray()
private fun asShotNeutral(captureResult: CaptureResult): List<Double> {
val neutralColorPoint = captureResult.get(CaptureResult.SENSOR_NEUTRAL_COLOR_POINT)
if (neutralColorPoint != null && neutralColorPoint.size >= 3) {
val neutral = neutralColorPoint.take(3).map { value ->
value.numerator.toDouble() / value.denominator.toDouble()
}
if (neutral.all { it.isFinite() && it > 0.0 }) {
return neutral
}
PLog.w(TAG, "Ignoring invalid SENSOR_NEUTRAL_COLOR_POINT: ${neutral.joinToString()}")
}
val gains = captureResult.get(CaptureResult.COLOR_CORRECTION_GAINS)
?: return listOf(1.0, 1.0, 1.0)
if (gains == null) {
PLog.w(TAG, "Missing SENSOR_NEUTRAL_COLOR_POINT and COLOR_CORRECTION_GAINS; using unity AsShotNeutral")
return listOf(1.0, 1.0, 1.0)
}
val green = ((gains.greenEven + gains.greenOdd) * 0.5f).takeIf { it > 0f } ?: 1f
val r = gains.red.takeIf { it > 0f } ?: green
val b = gains.blue.takeIf { it > 0f } ?: green
PLog.w(TAG, "Missing SENSOR_NEUTRAL_COLOR_POINT; deriving AsShotNeutral from COLOR_CORRECTION_GAINS")
return listOf((green / r).toDouble(), 1.0, (green / b).toDouble())
}
private data class DngGeometry(
val width: Int,
val height: Int,
val activeArea: LongArray,
val defaultCropLeft: Double,
val defaultCropTop: Double,
val defaultCropWidth: Double,
val defaultCropHeight: Double,
val sourceOriginX: Int,
val sourceOriginY: Int,
val sourceWidth: Int,
val sourceHeight: Int,
val bufferIncludesPixelArray: Boolean,
val scaleX: Double,
val scaleY: Double,
)
private fun resolveDngGeometry(
width: Int,
height: Int,
characteristics: CameraCharacteristics,
): DngGeometry {
val pre = characteristics.get(CameraCharacteristics.SENSOR_INFO_PRE_CORRECTION_ACTIVE_ARRAY_SIZE)
val pixel = characteristics.get(CameraCharacteristics.SENSOR_INFO_PIXEL_ARRAY_SIZE)
val preWidth = pre?.width()?.takeIf { it > 0 } ?: width
val preHeight = pre?.height()?.takeIf { it > 0 } ?: height
val matchesPixelArray = pixel != null && pixel.width == width && pixel.height == height
val matchesPreCorrection = preWidth == width && preHeight == height
val scaleX = if (matchesPixelArray) 1.0 else width.toDouble() / preWidth.toDouble()
val scaleY = if (matchesPixelArray) 1.0 else height.toDouble() / preHeight.toDouble()
val activeArea = if (matchesPixelArray && pre != null) {
longArrayOf(pre.top.toLong(), pre.left.toLong(), pre.bottom.toLong(), pre.right.toLong())
} else {
longArrayOf(0L, 0L, height.toLong(), width.toLong())
}
val marginX = (8.0 * scaleX).coerceAtMost((activeArea[3] - activeArea[1]).toDouble() / 2.0)
val marginY = (8.0 * scaleY).coerceAtMost((activeArea[2] - activeArea[0]).toDouble() / 2.0)
val cropWidth = ((activeArea[3] - activeArea[1]).toDouble() - marginX * 2.0).coerceAtLeast(1.0)
val cropHeight = ((activeArea[2] - activeArea[0]).toDouble() - marginY * 2.0).coerceAtLeast(1.0)
if (!matchesPixelArray && !matchesPreCorrection) {
PLog.d(TAG, "Mapping derived DNG ${width}x${height} from pre-correction ${preWidth}x${preHeight}")
}
return DngGeometry(
width = width,
height = height,
activeArea = activeArea,
defaultCropLeft = marginX,
defaultCropTop = marginY,
defaultCropWidth = cropWidth,
defaultCropHeight = cropHeight,
sourceOriginX = pre?.left ?: 0,
sourceOriginY = pre?.top ?: 0,
sourceWidth = preWidth,
sourceHeight = preHeight,
bufferIncludesPixelArray = matchesPixelArray,
scaleX = scaleX,
scaleY = scaleY,
)
}
private fun buildNoiseProfile(captureResult: CaptureResult): List<Double>? {
val profile = captureResult.get(CaptureResult.SENSOR_NOISE_PROFILE)
?.takeIf { it.size >= 3 }
@@ -642,6 +964,13 @@ object SuperResolutionDngWriter {
return normalizeDngColorMatrix(values)
}
private fun colorTransformToExactDngMatrix(transform: ColorSpaceTransform): List<Double> =
buildList(9) {
for (row in 0 until 3) {
for (col in 0 until 3) add(transform.getElement(col, row).toDouble())
}
}
private fun normalizeDngColorMatrix(values: List<Double>): List<Double> {
if (values.size != 9) return values
val coords = DoubleArray(3) { row ->