feat: 8x8 cfa

This commit is contained in:
Hinnka committed 2026-06-19 11:01:33 +08:00
1 parent 7bed0817d0
commit 686a0d73f3
19 files changed
+599 -193

No files matched your search

+54 -11
View File
@@ -430,9 +430,11 @@ static float sampleDngGainMapBilinear(const DngGainMap &gainMap, float x, float
}
static int quadChannelIndexForPattern(int cfaPattern, int col, int row) {
const int pattern = cfaPattern >= 4 ? cfaPattern - 4 : cfaPattern;
const int blockCol = (col / 2) & 1;
const int blockRow = (row / 2) & 1;
const int pattern = cfaPattern >= 8 ? cfaPattern - 8
: (cfaPattern >= 4 ? cfaPattern - 4 : cfaPattern);
const int blockSize = cfaPattern >= 8 ? 4 : 2;
const int blockCol = (col / blockSize) & 1;
const int blockRow = (row / blockSize) & 1;
if (pattern == 0) { // Quad RGGB
return blockRow == 0 ? (blockCol == 0 ? 0 : 1) : (blockCol == 0 ? 2 : 3);
}
@@ -458,7 +460,7 @@ static int gcdInt(int a, int b) {
static bool computeQuadDngBlackLevels(LibRaw &rawProcessor, int cfaPattern,
int left, int top, float out[4]) {
if (cfaPattern < 4 || cfaPattern > 7)
if (cfaPattern < 4 || cfaPattern > 11)
return false;
const auto &levels = rawProcessor.imgdata.color.dng_levels;
@@ -475,8 +477,9 @@ static bool computeQuadDngBlackLevels(LibRaw &rawProcessor, int cfaPattern,
return true;
}
const int periodX = (4 / gcdInt(4, cols)) * cols;
const int periodY = (4 / gcdInt(4, rows)) * rows;
const int cfaPeriod = cfaPattern >= 8 ? 8 : 4;
const int periodX = (cfaPeriod / gcdInt(cfaPeriod, cols)) * cols;
const int periodY = (cfaPeriod / gcdInt(cfaPeriod, rows)) * rows;
double sums[4] = {0.0, 0.0, 0.0, 0.0};
int counts[4] = {0, 0, 0, 0};
bool hasRepeatValue = false;
@@ -686,14 +689,14 @@ static jfloatArray buildDngLensShadingArray(JNIEnv *env, LibRaw &rawProcessor,
return nullptr;
}
const bool isQuadBayer = cfaPattern >= 4 && cfaPattern <= 7;
const bool isQuadBayer = cfaPattern >= 4 && cfaPattern <= 11;
std::vector<float> packed(static_cast<size_t>(mapWidth) * mapHeight * 4, 1.0f);
for (const auto &gainMap : gainMaps) {
int outChannel;
if (isQuadBayer) {
const int relX = (static_cast<int>(gainMap.left) - activeLeft) & 1;
const int relY = (static_cast<int>(gainMap.top) - activeTop) & 1;
outChannel = relY == 0 ? (relX == 0 ? 0 : 1) : (relX == 0 ? 2 : 3);
const int relX = static_cast<int>(gainMap.left) - activeLeft;
const int relY = static_cast<int>(gainMap.top) - activeTop;
outChannel = quadChannelIndexForPattern(cfaPattern, relX, relY);
} else {
int cfa = rawProcessor.FC(gainMap.top, gainMap.left);
if (cfa == 0) {
@@ -1111,15 +1114,19 @@ static unsigned char mapCfaPatternToLibRaw(int cfaPattern) {
switch (cfaPattern) {
case 0:
case 4:
case 8:
return LIBRAW_OPENBAYER_RGGB;
case 1:
case 5:
case 9:
return LIBRAW_OPENBAYER_GRBG;
case 2:
case 6:
case 10:
return LIBRAW_OPENBAYER_GBRG;
case 3:
case 7:
case 11:
return LIBRAW_OPENBAYER_BGGR;
default:
return 0;
@@ -2208,6 +2215,37 @@ static bool matchesCfa4x4(const int actual[4][4], const int expected[4][4]) {
return true;
}
static int expandedCfaColorForBasePattern(int basePattern, int col, int row,
int blockSize) {
const int blockCol = (col / blockSize) & 1;
const int blockRow = (row / blockSize) & 1;
int channel;
if (basePattern == 0) { // RGGB
channel = blockRow == 0 ? (blockCol == 0 ? 0 : 1) : (blockCol == 0 ? 2 : 3);
} else if (basePattern == 1) { // GRBG
channel = blockRow == 0 ? (blockCol == 0 ? 1 : 0) : (blockCol == 0 ? 3 : 2);
} else if (basePattern == 2) { // GBRG
channel = blockRow == 0 ? (blockCol == 0 ? 2 : 3) : (blockCol == 0 ? 0 : 1);
} else { // BGGR
channel = blockRow == 0 ? (blockCol == 0 ? 3 : 2) : (blockCol == 0 ? 1 : 0);
}
return channel == 0 ? 0 : (channel == 3 ? 2 : 1);
}
static bool matchesExpandedCfa(const DngCfaInfo &info, int left, int top,
int blockSize, int basePattern) {
const int period = blockSize * 2;
for (int row = 0; row < period; ++row) {
for (int col = 0; col < period; ++col) {
const int actual = dngCfaColorAt(info, top + row, left + col);
const int expected = expandedCfaColorForBasePattern(basePattern, col, row, blockSize);
if (actual != expected)
return false;
}
}
return true;
}
static int identifyQuadCfaFromDng(const DngCfaInfo &info, int left, int top,
int out4x4[4][4]) {
for (int row = 0; row < 4; ++row) {
@@ -2215,6 +2253,11 @@ static int identifyQuadCfaFromDng(const DngCfaInfo &info, int left, int top,
out4x4[row][col] = dngCfaColorAt(info, top + row, left + col);
}
for (int basePattern = 0; basePattern < 4; ++basePattern) {
if (matchesExpandedCfa(info, left, top, 4, basePattern))
return 8 + basePattern;
}
const int quadRggb[4][4] = {{0, 0, 1, 1},
{0, 0, 1, 1},
{1, 1, 2, 2},
@@ -2415,7 +2458,7 @@ Java_com_hinnka_mycamera_raw_RawDemosaicProcessor_processDngNative(
if (hasDngCfaInfo) {
cfaPattern = identifyQuadCfaFromDng(dngCfaInfo, left, top, dngCfa4x4);
LOGI("processDngNative: DNG CFA tags repeat=%dx%d patternLen=%d "
"planeColorLen=%d active4x4=[%d,%d,%d,%d/%d,%d,%d,%d/%d,%d,%d,%d/%d,%d,%d,%d] quadPattern=%d",
"planeColorLen=%d active4x4=[%d,%d,%d,%d/%d,%d,%d,%d/%d,%d,%d,%d/%d,%d,%d,%d] expandedPattern=%d",
dngCfaInfo.repeatRows, dngCfaInfo.repeatCols, dngCfaInfo.patternLen,
dngCfaInfo.planeColorLen,
dngCfa4x4[0][0], dngCfa4x4[0][1], dngCfa4x4[0][2], dngCfa4x4[0][3],
+30 -16
View File
@@ -1298,12 +1298,22 @@ RawStacker::RawStacker(int width, int height, bool enableSuperRes)
}
int RawStacker::getPlaneIndex(int x, int y, int cfaPattern) const {
// cfaPattern: 0=RGGB, 1=GRBG, 2=GBRG, 3=BGGR
// cfaPattern: 0..3=Bayer, 4..7=4x4 expanded Bayer, 8..11=8x8 expanded Bayer
// Row 0, Col 0 maps to: R, G, G, B respectively
// We want output indices 0..3 for R, Gr, Gb, B
// x%2, y%2 -> 00, 10, 01, 11
int offset = (y % 2) * 2 + (x % 2);
int pattern = cfaPattern;
int blockSize = 1;
if (cfaPattern >= 8) {
pattern = cfaPattern - 8;
blockSize = 4;
} else if (cfaPattern >= 4) {
pattern = cfaPattern - 4;
blockSize = 2;
}
// x/y block parity -> 00, 10, 01, 11
int offset = ((y / blockSize) & 1) * 2 + ((x / blockSize) & 1);
// Mapping table based on pattern
static const int map[4][4] = {
@@ -1313,7 +1323,7 @@ int RawStacker::getPlaneIndex(int x, int y, int cfaPattern) const {
{3, 2, 1, 0} // BGGR
};
return map[cfaPattern][offset];
return map[std::max(0, std::min(3, pattern))][offset];
}
// 辅助函数:安全地计算 RAW 的自动曝光缩放因子
@@ -1409,23 +1419,27 @@ void RawStacker::stageFrame(const uint16_t *rawData, int rowStride,
uint16_t p01 = pRow1[ox];
uint16_t p11 = pRow1[ox + 1];
uint16_t g1, g2;
if (cfaPattern == 1 || cfaPattern == 2) {
g1 = p00;
g2 = p11;
float avgG;
if (cfaPattern >= 4) {
avgG = static_cast<float>(p00 + p10 + p01 + p11) * 0.25f;
} else {
g1 = p10;
g2 = p01;
uint16_t g1, g2;
if (cfaPattern == 1 || cfaPattern == 2) {
g1 = p00;
g2 = p11;
} else {
g1 = p10;
g2 = p01;
}
avgG = static_cast<float>(g1 + g2) * 0.5f;
}
float avgG = (float)(g1 + g2) * 0.5f;
frame.proxy.data[y * proxyW + x] =
(uint8_t)std::max(0.0f, std::min(255.0f, avgG * byteScale));
frame.planes[getPlaneIndex(ox, 0, cfaPattern)][y * proxyW + x] = p00;
frame.planes[getPlaneIndex(ox + 1, 0, cfaPattern)][y * proxyW + x] = p10;
frame.planes[getPlaneIndex(ox, 1, cfaPattern)][y * proxyW + x] = p01;
frame.planes[getPlaneIndex(ox + 1, 1, cfaPattern)][y * proxyW + x] = p11;
frame.planes[getPlaneIndex(ox, y * 2, cfaPattern)][y * proxyW + x] = p00;
frame.planes[getPlaneIndex(ox + 1, y * 2, cfaPattern)][y * proxyW + x] = p10;
frame.planes[getPlaneIndex(ox, y * 2 + 1, cfaPattern)][y * proxyW + x] = p01;
frame.planes[getPlaneIndex(ox + 1, y * 2 + 1, cfaPattern)][y * proxyW + x] = p11;
}
}
+1 -1
View File
@@ -170,7 +170,7 @@ public:
// Add a raw frame to the stack
// rawData: 16-bit single channel Bayer data
// cfaPattern: 0=RGGB, 1=GRBG, 2=GBRG, 3=BGGR
// cfaPattern: 0..3=Bayer, 4..7=4x4 expanded Bayer, 8..11=8x8 expanded Bayer
void addFrame(const uint16_t *rawData, int rowStride, int cfaPattern);
// New methods for faster image closing
@@ -1548,10 +1548,13 @@ object GalleryManager {
rawBlackPointCorrection = updatedMetadata.rawBlackPointCorrection ?: 0f,
rawWhitePointCorrection = updatedMetadata.rawWhitePointCorrection ?: 0f,
rawAutoWhiteBalanceEstimate = resolveRawAutoWhiteBalanceEstimate(context, updatedMetadata),
rawBlackLevelMode = updatedMetadata.rawBlackLevelMode,
rawCustomBlackLevel = updatedMetadata.rawCustomBlackLevel,
sharpeningValue = 0.4f,
denoiseValue = updatedMetadata.rawDenoiseValue,
rawDcpId = updatedMetadata.rawDcpId,
rawColorEngine = updatedMetadata.rawColorEngine,
rawCfaCorrectionMode = updatedMetadata.rawCfaCorrectionMode,
spectralFilmStock = updatedMetadata.spectralFilmStock,
spectralFilmPrint = updatedMetadata.spectralFilmPrint,
spectralFilmTuning = SpectralFilmTuning(
@@ -2376,10 +2379,13 @@ object GalleryManager {
rawBlackPointCorrection = updatedMetadata.rawBlackPointCorrection ?: 0f,
rawWhitePointCorrection = updatedMetadata.rawWhitePointCorrection ?: 0f,
rawAutoWhiteBalanceEstimate = resolveRawAutoWhiteBalanceEstimate(context, updatedMetadata),
rawBlackLevelMode = updatedMetadata.rawBlackLevelMode,
rawCustomBlackLevel = updatedMetadata.rawCustomBlackLevel,
sharpeningValue = 0.4f,
denoiseValue = updatedMetadata.rawDenoiseValue,
rawDcpId = updatedMetadata.rawDcpId,
rawColorEngine = updatedMetadata.rawColorEngine,
rawCfaCorrectionMode = updatedMetadata.rawCfaCorrectionMode,
spectralFilmStock = updatedMetadata.spectralFilmStock,
spectralFilmPrint = updatedMetadata.spectralFilmPrint,
spectralFilmTuning = SpectralFilmTuning(
@@ -2808,10 +2814,13 @@ object GalleryManager {
rawBlackPointCorrection = updatedMetadata.rawBlackPointCorrection ?: 0f,
rawWhitePointCorrection = updatedMetadata.rawWhitePointCorrection ?: 0f,
rawAutoWhiteBalanceEstimate = resolveRawAutoWhiteBalanceEstimate(context, updatedMetadata),
rawBlackLevelMode = updatedMetadata.rawBlackLevelMode,
rawCustomBlackLevel = updatedMetadata.rawCustomBlackLevel,
sharpeningValue = 0.4f,
denoiseValue = updatedMetadata.rawDenoiseValue,
rawDcpId = updatedMetadata.rawDcpId,
rawColorEngine = updatedMetadata.rawColorEngine,
rawCfaCorrectionMode = updatedMetadata.rawCfaCorrectionMode,
spectralFilmStock = updatedMetadata.spectralFilmStock,
spectralFilmPrint = updatedMetadata.spectralFilmPrint,
spectralFilmTuning = SpectralFilmTuning(
@@ -3963,10 +3972,13 @@ object GalleryManager {
rawBlackPointCorrection = updatedMetadata.rawBlackPointCorrection ?: 0f,
rawWhitePointCorrection = updatedMetadata.rawWhitePointCorrection ?: 0f,
rawAutoWhiteBalanceEstimate = resolveRawAutoWhiteBalanceEstimate(context, updatedMetadata),
rawBlackLevelMode = updatedMetadata.rawBlackLevelMode,
rawCustomBlackLevel = updatedMetadata.rawCustomBlackLevel,
sharpeningValue = 0.4f,
denoiseValue = updatedMetadata.rawDenoiseValue,
rawDcpId = updatedMetadata.rawDcpId,
rawColorEngine = updatedMetadata.rawColorEngine,
rawCfaCorrectionMode = updatedMetadata.rawCfaCorrectionMode,
spectralFilmStock = updatedMetadata.spectralFilmStock,
spectralFilmPrint = updatedMetadata.spectralFilmPrint,
spectralFilmTuning = SpectralFilmTuning(
@@ -4111,10 +4123,13 @@ object GalleryManager {
rawBlackPointCorrection = updatedMetadata?.rawBlackPointCorrection ?: 0f,
rawWhitePointCorrection = updatedMetadata?.rawWhitePointCorrection ?: 0f,
rawAutoWhiteBalanceEstimate = resolveRawAutoWhiteBalanceEstimate(context, updatedMetadata),
rawBlackLevelMode = updatedMetadata?.rawBlackLevelMode,
rawCustomBlackLevel = updatedMetadata?.rawCustomBlackLevel,
sharpeningValue = updatedMetadata?.sharpening ?: 0.4f,
denoiseValue = (updatedMetadata ?: MediaMetadata()).rawDenoiseValue,
rawDcpId = updatedMetadata?.rawDcpId,
rawColorEngine = updatedMetadata?.rawColorEngine ?: MediaMetadata().rawColorEngine,
rawCfaCorrectionMode = updatedMetadata?.rawCfaCorrectionMode,
spectralFilmStock = updatedMetadata?.spectralFilmStock,
spectralFilmPrint = updatedMetadata?.spectralFilmPrint,
spectralFilmTuning = SpectralFilmTuning(
@@ -457,10 +457,13 @@ class PhotoProcessor(
rawBlackPointCorrection = metadata.rawBlackPointCorrection ?: 0f,
rawWhitePointCorrection = metadata.rawWhitePointCorrection ?: 0f,
rawAutoWhiteBalanceEstimate = resolveRawAutoWhiteBalanceEstimate(metadata),
rawBlackLevelMode = metadata.rawBlackLevelMode,
rawCustomBlackLevel = metadata.rawCustomBlackLevel,
sharpeningValue = 0.4f,
denoiseValue = metadata.rawDenoiseValue,
rawDcpId = metadata.rawDcpId,
rawColorEngine = metadata.rawColorEngine,
rawCfaCorrectionMode = metadata.rawCfaCorrectionMode,
spectralFilmStock = metadata.spectralFilmStock,
spectralFilmPrint = metadata.spectralFilmPrint,
spectralFilmTuning = SpectralFilmTuning(
@@ -528,9 +531,12 @@ class PhotoProcessor(
rawBlackPointCorrection = metadata.rawBlackPointCorrection ?: 0f,
rawWhitePointCorrection = metadata.rawWhitePointCorrection ?: 0f,
rawAutoWhiteBalanceEstimate = resolveRawAutoWhiteBalanceEstimate(metadata),
rawBlackLevelMode = metadata.rawBlackLevelMode,
rawCustomBlackLevel = metadata.rawCustomBlackLevel,
denoiseValue = metadata.rawDenoiseValue,
rawDcpId = metadata.rawDcpId,
rawColorEngine = metadata.rawColorEngine,
rawCfaCorrectionMode = metadata.rawCfaCorrectionMode,
spectralFilmStock = metadata.spectralFilmStock,
spectralFilmPrint = metadata.spectralFilmPrint,
spectralFilmTuning = SpectralFilmTuning(
@@ -34,7 +34,7 @@ data class DngRawData @Keep constructor(
val preMul: FloatArray,
val whiteBalance: FloatArray,
val colorMatrix: FloatArray,
val cfaPattern: Int, // 0..3=Bayer RGGB/GRBG/GBRG/BGGR, 4..7=Quad Bayer variants
val cfaPattern: Int, // 0..3=Bayer, 4..7=4x4 expanded Bayer, 8..11=8x8 expanded Bayer
val rotation: Int,
val baselineExposure: Float,
val lensShadingMap: FloatArray?,
@@ -1,10 +1,10 @@
package com.hinnka.mycamera.raw
/**
* Quad Bayer 4x4 CFA demosaic shaders.
* Expanded Bayer 4x4/8x8 CFA demosaic shaders.
*
* The pipeline mirrors the RCD staging shape, but every CFA decision is based on
* a 2x2-expanded Bayer superpixel instead of the normal x/y parity pattern.
* an expanded Bayer block instead of the normal x/y parity pattern.
*/
object QuadBayerShaders {
private const val COMMON = """
@@ -13,7 +13,13 @@ object QuadBayerShaders {
const int BLUE = 2;
int baseBayerPattern(int cfaPattern) {
return (cfaPattern >= 4) ? (cfaPattern - 4) : cfaPattern;
if (cfaPattern >= 8) return cfaPattern - 8;
if (cfaPattern >= 4) return cfaPattern - 4;
return cfaPattern;
}
int expandedBayerBlockSize(int cfaPattern) {
return (cfaPattern >= 8) ? 4 : 2;
}
int colorFromChannelIndex(int channelIndex) {
@@ -24,8 +30,9 @@ object QuadBayerShaders {
int getQuadChannelIndex(int cfaPattern, int col, int row) {
int pattern = baseBayerPattern(cfaPattern);
int blockCol = (col / 2) & 1;
int blockRow = (row / 2) & 1;
int blockSize = expandedBayerBlockSize(cfaPattern);
int blockCol = (col / blockSize) & 1;
int blockRow = (row / blockSize) & 1;
if (pattern == 0) { // Quad RGGB
if (blockRow == 0) return (blockCol == 0) ? 0 : 1;
@@ -80,12 +87,7 @@ object QuadBayerShaders {
$COMMON
int getLensShadingIndex(ivec2 coord) {
int xParity = coord.x & 1;
int yParity = coord.y & 1;
if (yParity == 0) {
return (xParity == 0) ? 0 : 1;
}
return (xParity == 0) ? 2 : 3;
return getQuadChannelIndex(uCfaPattern, coord.x, coord.y);
}
float getLensShadingGain(ivec2 coord) {
@@ -128,8 +130,11 @@ object QuadBayerShaders {
float countGreen = 0.0;
float countBlue = 0.0;
for (int dy = -2; dy <= 2; dy++) {
for (int dx = -2; dx <= 2; dx++) {
int radius = expandedBayerBlockSize(uCfaPattern);
for (int dy = -4; dy <= 4; dy++) {
if (abs(dy) > radius) continue;
for (int dx = -4; dx <= 4; dx++) {
if (abs(dx) > radius) continue;
ivec2 sampleCoord = clampCoord(coord + ivec2(dx, dy), uImageSize);
int sampleChannel = getQuadChannelIndex(uCfaPattern, sampleCoord.x, sampleCoord.y);
int sampleColor = colorFromChannelIndex(sampleChannel);
@@ -302,9 +307,12 @@ object QuadBayerShaders {
float interpolateDiff(ivec2 coord, int targetColor, float centerGreen) {
float sum = 0.0;
float weight = 0.0;
int radius = max(3, expandedBayerBlockSize(uCfaPattern));
for (int dy = -3; dy <= 3; dy++) {
for (int dx = -3; dx <= 3; dx++) {
for (int dy = -4; dy <= 4; dy++) {
if (abs(dy) > radius) continue;
for (int dx = -4; dx <= 4; dx++) {
if (abs(dx) > radius) continue;
ivec2 p = clampCoord(coord + ivec2(dx, dy), uImageSize);
if (getQuadColor(uCfaPattern, p.x, p.y) != targetColor) continue;
@@ -10,6 +10,10 @@ object RawCfaCorrection {
const val MODE_4X4_GRBG = "4x4_GRBG"
const val MODE_4X4_GBRG = "4x4_GBRG"
const val MODE_4X4_BGGR = "4x4_BGGR"
const val MODE_8X8_RGGB = "8x8_RGGB"
const val MODE_8X8_GRBG = "8x8_GRBG"
const val MODE_8X8_GBRG = "8x8_GBRG"
const val MODE_8X8_BGGR = "8x8_BGGR"
val allModes: List<String> = listOf(
MODE_DEFAULT,
@@ -20,7 +24,11 @@ object RawCfaCorrection {
MODE_4X4_RGGB,
MODE_4X4_GRBG,
MODE_4X4_GBRG,
MODE_4X4_BGGR
MODE_4X4_BGGR,
MODE_8X8_RGGB,
MODE_8X8_GRBG,
MODE_8X8_GBRG,
MODE_8X8_BGGR
)
fun resolveCfaPattern(defaultCfaPattern: Int, mode: String?): Int {
@@ -33,6 +41,10 @@ object RawCfaCorrection {
MODE_4X4_GRBG -> RawMetadata.CFA_QUAD_GRBG
MODE_4X4_GBRG -> RawMetadata.CFA_QUAD_GBRG
MODE_4X4_BGGR -> RawMetadata.CFA_QUAD_BGGR
MODE_8X8_RGGB -> RawMetadata.CFA_QUAD_8X8_RGGB
MODE_8X8_GRBG -> RawMetadata.CFA_QUAD_8X8_GRBG
MODE_8X8_GBRG -> RawMetadata.CFA_QUAD_8X8_GBRG
MODE_8X8_BGGR -> RawMetadata.CFA_QUAD_8X8_BGGR
else -> defaultCfaPattern
}
}
@@ -47,6 +59,10 @@ object RawCfaCorrection {
MODE_4X4_GRBG -> RawMetadata.CFA_QUAD_GRBG
MODE_4X4_GBRG -> RawMetadata.CFA_QUAD_GBRG
MODE_4X4_BGGR -> RawMetadata.CFA_QUAD_BGGR
MODE_8X8_RGGB -> RawMetadata.CFA_QUAD_8X8_RGGB
MODE_8X8_GRBG -> RawMetadata.CFA_QUAD_8X8_GRBG
MODE_8X8_GBRG -> RawMetadata.CFA_QUAD_8X8_GBRG
MODE_8X8_BGGR -> RawMetadata.CFA_QUAD_8X8_BGGR
else -> null
}
}
@@ -56,16 +72,16 @@ object RawCfaCorrection {
}
fun repeatPatternDim(cfaPattern: Int): IntArray {
return if (RawMetadata.isQuadBayer(cfaPattern)) {
intArrayOf(4, 4)
} else {
intArrayOf(2, 2)
return when {
RawMetadata.isQuadBayer8x8(cfaPattern) -> intArrayOf(8, 8)
RawMetadata.isQuadBayer(cfaPattern) -> intArrayOf(4, 4)
else -> intArrayOf(2, 2)
}
}
fun cfaPatternBytes(cfaPattern: Int): ByteArray {
return if (RawMetadata.isQuadBayer(cfaPattern)) {
quadCfaPatternBytes(cfaPattern)
expandedCfaPatternBytes(cfaPattern)
} else {
bayerCfaPatternBytes(baseBayerPattern(cfaPattern))
}
@@ -73,7 +89,7 @@ object RawCfaCorrection {
fun channelIndexForPixel(cfaPattern: Int, x: Int, y: Int): Int {
return if (RawMetadata.isQuadBayer(cfaPattern)) {
quadChannelIndex(cfaPattern, x and 3, y and 3)
expandedChannelIndex(cfaPattern, x, y)
} else {
bayerChannelIndex(baseBayerPattern(cfaPattern), x and 1, y and 1)
}
@@ -88,10 +104,18 @@ object RawCfaCorrection {
}
fun baseBayerPattern(cfaPattern: Int): Int {
return if (RawMetadata.isQuadBayer(cfaPattern)) {
cfaPattern - RawMetadata.CFA_QUAD_RGGB
} else {
cfaPattern
return when {
RawMetadata.isQuadBayer8x8(cfaPattern) -> cfaPattern - RawMetadata.CFA_QUAD_8X8_RGGB
RawMetadata.isQuadBayer(cfaPattern) -> cfaPattern - RawMetadata.CFA_QUAD_RGGB
else -> cfaPattern
}
}
fun expandedBayerBlockSize(cfaPattern: Int): Int {
return when {
RawMetadata.isQuadBayer8x8(cfaPattern) -> 4
RawMetadata.isQuadBayer(cfaPattern) -> 2
else -> 1
}
}
@@ -104,11 +128,12 @@ object RawCfaCorrection {
}
}
private fun quadCfaPatternBytes(cfaPattern: Int): ByteArray {
val bytes = ByteArray(16)
private fun expandedCfaPatternBytes(cfaPattern: Int): ByteArray {
val dim = repeatPatternDim(cfaPattern)
val bytes = ByteArray(dim[0] * dim[1])
var index = 0
for (y in 0 until 4) {
for (x in 0 until 4) {
for (y in 0 until dim[0]) {
for (x in 0 until dim[1]) {
bytes[index++] = colorCodeForPixel(cfaPattern, x, y).toByte()
}
}
@@ -147,11 +172,12 @@ object RawCfaCorrection {
}
}
private fun quadChannelIndex(cfaPattern: Int, xMod4: Int, yMod4: Int): Int {
private fun expandedChannelIndex(cfaPattern: Int, x: Int, y: Int): Int {
val blockSize = expandedBayerBlockSize(cfaPattern)
return bayerChannelIndex(
cfaPattern = baseBayerPattern(cfaPattern),
xParity = xMod4 / 2,
yParity = yMod4 / 2
xParity = (x / blockSize) and 1,
yParity = (y / blockSize) and 1
)
}
}
@@ -379,6 +379,44 @@ class RawDemosaicProcessor {
return rawColorEngine.workingColorSpace
}
private fun applyCfaCorrectionOverride(metadata: RawMetadata, mode: String?): RawMetadata {
val resolvedCfaPattern = RawCfaCorrection.patternFromMode(mode) ?: return metadata
if (resolvedCfaPattern == metadata.cfaPattern) {
return metadata
}
PLog.d(TAG, "RAW DNG CFA override mode=$mode cfa=${metadata.cfaPattern}->$resolvedCfaPattern")
return metadata.copy(cfaPattern = resolvedCfaPattern)
}
private fun applyBlackLevelOverride(
metadata: RawMetadata,
mode: String?,
customBlackLevel: Float?
): RawMetadata {
val resolvedBlackLevel = RawProcessor.resolveBlackLevelForMode(
defaultBlackLevel = metadata.blackLevel,
blackLevelMode = mode,
customBlackLevel = customBlackLevel
)
if (metadata.blackLevel.contentEquals(resolvedBlackLevel)) {
return metadata
}
PLog.d(TAG, "RAW DNG black level override mode=$mode value=${resolvedBlackLevel.joinToString()}")
return metadata.copy(blackLevel = resolvedBlackLevel)
}
private fun applyDngMetadataOverrides(
metadata: RawMetadata,
rawBlackLevelMode: String?,
rawCustomBlackLevel: Float?,
rawCfaCorrectionMode: String?
): RawMetadata {
return applyCfaCorrectionOverride(
metadata = applyBlackLevelOverride(metadata, rawBlackLevelMode, rawCustomBlackLevel),
mode = rawCfaCorrectionMode
)
}
/**
* 处理 DNG 文件
*
@@ -402,6 +440,8 @@ class RawDemosaicProcessor {
rawBlackPointCorrection: Float = 0f,
rawWhitePointCorrection: Float = 0f,
rawAutoWhiteBalanceEstimate: Boolean = false,
rawBlackLevelMode: String? = null,
rawCustomBlackLevel: Float? = null,
sharpeningValue: Float = 0f,
denoiseValue: Float? = null,
rawDcpId: String? = null,
@@ -410,6 +450,7 @@ class RawDemosaicProcessor {
spectralFilmPrint: String? = null,
spectralFilmTuning: SpectralFilmTuning = SpectralFilmTuning.DEFAULT,
rawColorEngine: RawColorEngine = RawColorEngine.AdobeCurve,
rawCfaCorrectionMode: String? = null,
onRawAutoAdjustments: ((RawAutoAdjustments) -> Unit)? = null,
onMetadata: ((RawMetadata) -> Unit)? = null
): Bitmap? = withContext(glDispatcher) {
@@ -433,6 +474,8 @@ class RawDemosaicProcessor {
rawBlackPointCorrection = rawBlackPointCorrection,
rawWhitePointCorrection = rawWhitePointCorrection,
rawAutoWhiteBalanceEstimate = rawAutoWhiteBalanceEstimate,
rawBlackLevelMode = rawBlackLevelMode,
rawCustomBlackLevel = rawCustomBlackLevel,
sharpeningValue = sharpeningValue,
denoiseValue = denoiseValue,
rawDcpId = rawDcpId,
@@ -441,6 +484,7 @@ class RawDemosaicProcessor {
spectralFilmPrint = spectralFilmPrint,
spectralFilmTuning = spectralFilmTuning,
rawColorEngine = rawColorEngine,
rawCfaCorrectionMode = rawCfaCorrectionMode,
dngFile = dngFile,
onRawAutoAdjustments = onRawAutoAdjustments,
onMetadata = onMetadata
@@ -536,6 +580,8 @@ class RawDemosaicProcessor {
rawBlackPointCorrection: Float = 0f,
rawWhitePointCorrection: Float = 0f,
rawAutoWhiteBalanceEstimate: Boolean = false,
rawBlackLevelMode: String? = null,
rawCustomBlackLevel: Float? = null,
sharpeningValue: Float = 0f,
denoiseValue: Float? = null,
rawDcpId: String? = null,
@@ -544,6 +590,7 @@ class RawDemosaicProcessor {
spectralFilmPrint: String? = null,
spectralFilmTuning: SpectralFilmTuning = SpectralFilmTuning.DEFAULT,
rawColorEngine: RawColorEngine = RawColorEngine.AdobeCurve,
rawCfaCorrectionMode: String? = null,
onRawAutoAdjustments: ((RawAutoAdjustments) -> Unit)? = null,
onMetadata: ((RawMetadata) -> Unit)? = null
): RawHdrRenderResult? = withContext(glDispatcher) {
@@ -567,6 +614,8 @@ class RawDemosaicProcessor {
rawBlackPointCorrection = rawBlackPointCorrection,
rawWhitePointCorrection = rawWhitePointCorrection,
rawAutoWhiteBalanceEstimate = rawAutoWhiteBalanceEstimate,
rawBlackLevelMode = rawBlackLevelMode,
rawCustomBlackLevel = rawCustomBlackLevel,
sharpeningValue = sharpeningValue,
denoiseValue = denoiseValue,
rawDcpId = rawDcpId,
@@ -575,6 +624,7 @@ class RawDemosaicProcessor {
spectralFilmPrint = spectralFilmPrint,
spectralFilmTuning = spectralFilmTuning,
rawColorEngine = rawColorEngine,
rawCfaCorrectionMode = rawCfaCorrectionMode,
dngFile = dngFile,
onRawAutoAdjustments = onRawAutoAdjustments,
onMetadata = onMetadata,
@@ -607,6 +657,8 @@ class RawDemosaicProcessor {
rawBlackPointCorrection: Float = 0f,
rawWhitePointCorrection: Float = 0f,
rawAutoWhiteBalanceEstimate: Boolean = false,
rawBlackLevelMode: String? = null,
rawCustomBlackLevel: Float? = null,
sharpeningValue: Float = 0f,
denoiseValue: Float? = null,
chromaDenoiseValue: Float? = null,
@@ -616,6 +668,7 @@ class RawDemosaicProcessor {
spectralFilmPrint: String? = null,
spectralFilmTuning: SpectralFilmTuning = SpectralFilmTuning.DEFAULT,
rawColorEngine: RawColorEngine = RawColorEngine.AdobeCurve,
rawCfaCorrectionMode: String? = null,
dngFile: File? = null,
onRawAutoAdjustments: ((RawAutoAdjustments) -> Unit)? = null,
onMetadata: ((RawMetadata) -> Unit)? = null,
@@ -659,7 +712,12 @@ class RawDemosaicProcessor {
actualWidth = dngRawData.width
actualHeight = dngRawData.height
actualRowStride = dngRawData.rowStride
actualMetadata = convertDngRawDataToMetadata(dngRawData, exposureBias, actualMetadata)
actualMetadata = applyDngMetadataOverrides(
metadata = convertDngRawDataToMetadata(dngRawData, exposureBias, actualMetadata),
rawBlackLevelMode = rawBlackLevelMode,
rawCustomBlackLevel = rawCustomBlackLevel,
rawCfaCorrectionMode = rawCfaCorrectionMode
)
actualRotation = if (dngRawData.rotation != 0) dngRawData.rotation else rotation
onMetadata?.invoke(actualMetadata)
}
@@ -3078,6 +3136,8 @@ class RawDemosaicProcessor {
} else {
"none"
}
val expandedBlockSize = RawCfaCorrection.expandedBayerBlockSize(metadata.cfaPattern)
val outputBorder = (expandedBlockSize * 2).coerceAtLeast(4)
GLES31.glUseProgram(quadPopulateProgram)
GLES31.glActiveTexture(GLES31.GL_TEXTURE0 + RCD_RAW_TEXTURE_UNIT)
@@ -3122,7 +3182,8 @@ class RawDemosaicProcessor {
)
PLog.d(
TAG,
"Quad Bayer populate: cfa=${metadata.cfaPattern} black=${blackLevel4.contentToString()} " +
"Expanded Bayer populate: cfa=${metadata.cfaPattern} block=${expandedBlockSize}x$expandedBlockSize " +
"black=${blackLevel4.contentToString()} " +
"white=${metadata.whiteLevel} wb=${wbGains.contentToString()} lsc=$lscSize " +
"highlightThreshold=$RCD_HIGHLIGHT_RECONSTRUCTION_THRESHOLD " +
"highlightCeiling=$RCD_HIGHLIGHT_RECONSTRUCTION_CEILING"
@@ -3167,7 +3228,7 @@ class RawDemosaicProcessor {
width,
height
)
GLES31.glUniform1i(GLES31.glGetUniformLocation(quadWriteOutputProgram, "uBorder"), 4)
GLES31.glUniform1i(GLES31.glGetUniformLocation(quadWriteOutputProgram, "uBorder"), outputBorder)
GLES31.glBindImageTexture(
RCD_OUTPUT_IMAGE_UNIT,
demosaicTextureId,
@@ -634,22 +634,36 @@ object RawHdrFusionProcessor {
uniform vec2 uNoiseModel;
uniform int uUseDeghostMask;
int baseBayerPattern() {
if (uCfaPattern >= 8) return uCfaPattern - 8;
if (uCfaPattern >= 4) return uCfaPattern - 4;
return uCfaPattern;
}
int expandedBayerBlockSize() {
if (uCfaPattern >= 8) return 4;
if (uCfaPattern >= 4) return 2;
return 1;
}
int channelIndex(ivec2 p) {
int x = p.x - (p.x / 2) * 2;
int y = p.y - (p.y / 2) * 2;
if (uCfaPattern == 0) {
int blockSize = expandedBayerBlockSize();
int pattern = baseBayerPattern();
int x = (p.x / blockSize) & 1;
int y = (p.y / blockSize) & 1;
if (pattern == 0) {
if (y == 0 && x == 0) return 0;
if (y == 0 && x == 1) return 1;
if (y == 1 && x == 0) return 2;
return 3;
}
if (uCfaPattern == 1) {
if (pattern == 1) {
if (y == 0 && x == 0) return 1;
if (y == 0 && x == 1) return 0;
if (y == 1 && x == 0) return 3;
return 2;
}
if (uCfaPattern == 2) {
if (pattern == 2) {
if (y == 0 && x == 0) return 2;
if (y == 0 && x == 1) return 3;
if (y == 1 && x == 0) return 0;
@@ -25,6 +25,7 @@ data class RawMetadata(
* CFA(彩色滤波阵列)排列模式
* 0 = RGGB, 1 = GRBG, 2 = GBRG, 3 = BGGR
* 4 = Quad RGGB, 5 = Quad GRBG, 6 = Quad GBRG, 7 = Quad BGGR
* 8 = 8x8 RGGB, 9 = 8x8 GRBG, 10 = 8x8 GBRG, 11 = 8x8 BGGR
*/
val cfaPattern: Int,
@@ -95,9 +96,17 @@ data class RawMetadata(
const val CFA_QUAD_GRBG = 5
const val CFA_QUAD_GBRG = 6
const val CFA_QUAD_BGGR = 7
const val CFA_QUAD_8X8_RGGB = 8
const val CFA_QUAD_8X8_GRBG = 9
const val CFA_QUAD_8X8_GBRG = 10
const val CFA_QUAD_8X8_BGGR = 11
fun isQuadBayer(cfaPattern: Int): Boolean {
return cfaPattern in CFA_QUAD_RGGB..CFA_QUAD_BGGR
return cfaPattern in CFA_QUAD_RGGB..CFA_QUAD_8X8_BGGR
}
fun isQuadBayer8x8(cfaPattern: Int): Boolean {
return cfaPattern in CFA_QUAD_8X8_RGGB..CFA_QUAD_8X8_BGGR
}
/**
@@ -302,7 +302,11 @@ fun RawEditPanel(
RawCfaCorrection.MODE_4X4_RGGB to stringResource(R.string.settings_cfa_correction_4x4_rggb),
RawCfaCorrection.MODE_4X4_GRBG to stringResource(R.string.settings_cfa_correction_4x4_grbg),
RawCfaCorrection.MODE_4X4_GBRG to stringResource(R.string.settings_cfa_correction_4x4_gbrg),
RawCfaCorrection.MODE_4X4_BGGR to stringResource(R.string.settings_cfa_correction_4x4_bggr)
RawCfaCorrection.MODE_4X4_BGGR to stringResource(R.string.settings_cfa_correction_4x4_bggr),
RawCfaCorrection.MODE_8X8_RGGB to stringResource(R.string.settings_cfa_correction_8x8_rggb),
RawCfaCorrection.MODE_8X8_GRBG to stringResource(R.string.settings_cfa_correction_8x8_grbg),
RawCfaCorrection.MODE_8X8_GBRG to stringResource(R.string.settings_cfa_correction_8x8_gbrg),
RawCfaCorrection.MODE_8X8_BGGR to stringResource(R.string.settings_cfa_correction_8x8_bggr)
),
currentLevel = rawCfaCorrectionMode,
onLevelSelected = onRawCfaCorrectionModeChange
@@ -1682,7 +1682,11 @@ fun SettingsScreen(
RawCfaCorrection.MODE_4X4_RGGB to stringResource(R.string.settings_cfa_correction_4x4_rggb),
RawCfaCorrection.MODE_4X4_GRBG to stringResource(R.string.settings_cfa_correction_4x4_grbg),
RawCfaCorrection.MODE_4X4_GBRG to stringResource(R.string.settings_cfa_correction_4x4_gbrg),
RawCfaCorrection.MODE_4X4_BGGR to stringResource(R.string.settings_cfa_correction_4x4_bggr)
RawCfaCorrection.MODE_4X4_BGGR to stringResource(R.string.settings_cfa_correction_4x4_bggr),
RawCfaCorrection.MODE_8X8_RGGB to stringResource(R.string.settings_cfa_correction_8x8_rggb),
RawCfaCorrection.MODE_8X8_GRBG to stringResource(R.string.settings_cfa_correction_8x8_grbg),
RawCfaCorrection.MODE_8X8_GBRG to stringResource(R.string.settings_cfa_correction_8x8_gbrg),
RawCfaCorrection.MODE_8X8_BGGR to stringResource(R.string.settings_cfa_correction_8x8_bggr)
),
currentLevel = rawCfaCorrectionMode,
onLevelSelected = { viewModel.setRawCfaCorrectionMode(it) }
@@ -8,7 +8,17 @@ import kotlin.math.roundToInt
object DngBlackLevelPatcher {
private const val TAG = "DngBlackLevelPatcher"
private const val TIFF_TAG_SUB_IFDS = 330
private const val TIFF_TAG_BLACK_LEVEL = 50714
private const val TYPE_SHORT = 3
private const val TYPE_LONG = 4
private const val MAX_IFD_VISITS = 64
private data class IfdScanResult(
val blackLevelEntryOffset: Long,
val subIfdOffsets: List<Long>,
val nextIfdOffset: Long
)
fun patchFromMode(file: File, mode: String?, customBlackLevel: Float?): Boolean {
val level = resolveBlackLevel(mode, customBlackLevel) ?: return false
@@ -41,90 +51,168 @@ object DngBlackLevelPatcher {
val byteOrder = when {
header[0] == 'I'.code.toByte() && header[1] == 'I'.code.toByte() -> ByteOrder.LITTLE_ENDIAN
header[0] == 'M'.code.toByte() && header[1] == 'M'.code.toByte() -> ByteOrder.BIG_ENDIAN
else -> return false
else -> return@use false
}
val magic = readUnsignedShort(header, 2, byteOrder)
if (magic != 42) {
return false
return@use false
}
val firstIfdOffset = readUnsignedInt(header, 4, byteOrder)
if (firstIfdOffset <= 0L || firstIfdOffset + 2L > raf.length()) {
return false
return@use false
}
raf.seek(firstIfdOffset)
val entryCountBytes = ByteArray(2)
raf.readFully(entryCountBytes)
val entryCount = readUnsignedShort(entryCountBytes, 0, byteOrder)
val pendingIfds = mutableListOf(firstIfdOffset)
val visitedIfds = mutableSetOf<Long>()
var patchedCount = 0
// Detect if the DNG uses a normalized WhiteLevel (65535) and skip patching to prevent dark clipping
var isNormalizedDng = false
for (entryIndex in 0 until entryCount) {
val entryOffset = firstIfdOffset + 2L + entryIndex * 12L
if (entryOffset + 12L > raf.length()) break
raf.seek(entryOffset)
val entry = ByteArray(12)
raf.readFully(entry)
val tag = readUnsignedShort(entry, 0, byteOrder)
if (tag == 50717) { // TAG_WHITE_LEVEL
val type = readUnsignedShort(entry, 2, byteOrder)
val count = readUnsignedInt(entry, 4, byteOrder)
if (count == 1L) {
val value = if (type == 3) {
readUnsignedShort(entry, 8, byteOrder).toLong()
} else {
readUnsignedInt(entry, 8, byteOrder)
}
if (value == 65535L) {
isNormalizedDng = true
}
}
break
}
}
if (isNormalizedDng) {
PLog.i(TAG, "DNG has normalized WhiteLevel (65535), skipping physical BlackLevel patch to prevent color clipping")
return false
}
for (entryIndex in 0 until entryCount) {
val entryOffset = firstIfdOffset + 2L + entryIndex * 12L
if (entryOffset + 12L > raf.length()) {
break
}
val entry = ByteArray(12)
raf.seek(entryOffset)
raf.readFully(entry)
val tag = readUnsignedShort(entry, 0, byteOrder)
if (tag != TIFF_TAG_BLACK_LEVEL) {
while (pendingIfds.isNotEmpty() && visitedIfds.size < MAX_IFD_VISITS) {
val ifdOffset = pendingIfds.removeAt(0)
if (ifdOffset <= 0L || ifdOffset in visitedIfds) {
continue
}
visitedIfds += ifdOffset
val type = readUnsignedShort(entry, 2, byteOrder)
val count = readUnsignedInt(entry, 4, byteOrder)
val valueBytes = valueByteCount(type, count) ?: return false
val valueOffset = if (valueBytes <= 4L) {
entryOffset + 8L
} else {
readUnsignedInt(entry, 8, byteOrder)
}
if (valueOffset < 0L || valueOffset + valueBytes > raf.length()) {
return false
val scan = scanIfd(raf, ifdOffset, byteOrder) ?: continue
if (scan.blackLevelEntryOffset >= 0L) {
val entry = ByteArray(12)
raf.seek(scan.blackLevelEntryOffset)
raf.readFully(entry)
val type = readUnsignedShort(entry, 2, byteOrder)
val count = readUnsignedInt(entry, 4, byteOrder)
val valueBytes = valueByteCount(type, count) ?: continue
val valueOffset = valueOffsetForEntry(
entry = entry,
entryOffset = scan.blackLevelEntryOffset,
valueBytes = valueBytes,
byteOrder = byteOrder
)
if (valueOffset >= 0L && valueOffset + valueBytes <= raf.length()) {
writeBlackLevelValues(raf, valueOffset, type, count, byteOrder, level)
patchedCount++
PLog.d(TAG, "Patched DNG BlackLevel to $level ifd=$ifdOffset in ${file.name}")
}
}
writeBlackLevelValues(raf, valueOffset, type, count, byteOrder, level)
PLog.d(TAG, "Patched DNG BlackLevel to $level in ${file.name}")
return true
if (scan.nextIfdOffset > 0L) {
pendingIfds += scan.nextIfdOffset
}
scan.subIfdOffsets.forEach { subIfdOffset ->
if (subIfdOffset > 0L && subIfdOffset !in visitedIfds) {
pendingIfds += subIfdOffset
}
}
}
false
if (patchedCount == 0) {
PLog.w(TAG, "DNG BlackLevel tag missing in ${file.name}; scannedIfds=${visitedIfds.size}")
return@use false
}
true
}
}.onFailure {
PLog.w(TAG, "Failed to patch DNG BlackLevel: ${file.absolutePath}", it)
}.getOrDefault(false)
}
private fun scanIfd(raf: RandomAccessFile, ifdOffset: Long, byteOrder: ByteOrder): IfdScanResult? {
if (ifdOffset <= 0L || ifdOffset + 2L > raf.length()) {
return null
}
raf.seek(ifdOffset)
val entryCountBytes = ByteArray(2)
raf.readFully(entryCountBytes)
val entryCount = readUnsignedShort(entryCountBytes, 0, byteOrder)
val entriesStart = ifdOffset + 2L
val nextIfdPointerOffset = entriesStart + entryCount * 12L
if (nextIfdPointerOffset + 4L > raf.length()) {
return null
}
var blackLevelEntryOffset = -1L
val subIfdOffsets = mutableListOf<Long>()
for (entryIndex in 0 until entryCount) {
val entryOffset = entriesStart + entryIndex * 12L
val entry = ByteArray(12)
raf.seek(entryOffset)
raf.readFully(entry)
when (readUnsignedShort(entry, 0, byteOrder)) {
TIFF_TAG_BLACK_LEVEL -> blackLevelEntryOffset = entryOffset
TIFF_TAG_SUB_IFDS -> {
val type = readUnsignedShort(entry, 2, byteOrder)
val count = readUnsignedInt(entry, 4, byteOrder)
subIfdOffsets += readUnsignedValues(raf, entry, entryOffset, type, count, byteOrder)
}
}
}
raf.seek(nextIfdPointerOffset)
val nextIfdBytes = ByteArray(4)
raf.readFully(nextIfdBytes)
return IfdScanResult(
blackLevelEntryOffset = blackLevelEntryOffset,
subIfdOffsets = subIfdOffsets,
nextIfdOffset = readUnsignedInt(nextIfdBytes, 0, byteOrder)
)
}
private fun readUnsignedValues(
raf: RandomAccessFile,
entry: ByteArray,
entryOffset: Long,
type: Int,
count: Long,
byteOrder: ByteOrder
): List<Long> {
if (count <= 0L || count > 64L) {
return emptyList()
}
val typeSize = when (type) {
TYPE_SHORT -> 2L
TYPE_LONG -> 4L
else -> return emptyList()
}
val valueBytes = typeSize * count
val valueOffset = valueOffsetForEntry(entry, entryOffset, valueBytes, byteOrder)
if (valueOffset < 0L || valueOffset + valueBytes > raf.length()) {
return emptyList()
}
return buildList {
raf.seek(valueOffset)
repeat(count.toInt()) {
when (type) {
TYPE_SHORT -> {
val bytes = ByteArray(2)
raf.readFully(bytes)
add(readUnsignedShort(bytes, 0, byteOrder).toLong())
}
TYPE_LONG -> {
val bytes = ByteArray(4)
raf.readFully(bytes)
add(readUnsignedInt(bytes, 0, byteOrder))
}
}
}
}
}
private fun valueOffsetForEntry(
entry: ByteArray,
entryOffset: Long,
valueBytes: Long,
byteOrder: ByteOrder
): Long {
return if (valueBytes <= 4L) {
entryOffset + 8L
} else {
readUnsignedInt(entry, 8, byteOrder)
}
}
private fun writeBlackLevelValues(
raf: RandomAccessFile,
valueOffset: Long,
@@ -8,10 +8,20 @@ import java.nio.ByteOrder
object DngCfaPatternPatcher {
private const val TAG = "DngCfaPatternPatcher"
private const val TIFF_TAG_SUB_IFDS = 330
private const val TIFF_TAG_CFA_REPEAT_PATTERN_DIM = 33421
private const val TIFF_TAG_CFA_PATTERN = 33422
private const val TYPE_BYTE = 1
private const val TYPE_SHORT = 3
private const val TYPE_LONG = 4
private const val MAX_IFD_VISITS = 64
private data class IfdScanResult(
val cfaDimEntryOffset: Long,
val cfaPatternEntryOffset: Long,
val subIfdOffsets: List<Long>,
val nextIfdOffset: Long
)
fun patchFromMode(file: File, mode: String?): Boolean {
val cfaPattern = RawCfaCorrection.patternFromMode(mode) ?: return false
@@ -44,58 +54,59 @@ object DngCfaPatternPatcher {
return false
}
raf.seek(firstIfdOffset)
val entryCountBytes = ByteArray(2)
raf.readFully(entryCountBytes)
val entryCount = readUnsignedShort(entryCountBytes, 0, byteOrder)
val dim = RawCfaCorrection.repeatPatternDim(cfaPattern)
val patternBytes = RawCfaCorrection.cfaPatternBytes(cfaPattern)
val pendingIfds = mutableListOf(firstIfdOffset)
val visitedIfds = mutableSetOf<Long>()
var patchedCount = 0
var cfaDimEntryOffset = -1L
var cfaPatternEntryOffset = -1L
for (entryIndex in 0 until entryCount) {
val entryOffset = firstIfdOffset + 2L + entryIndex * 12L
if (entryOffset + 12L > raf.length()) {
break
while (pendingIfds.isNotEmpty() && visitedIfds.size < MAX_IFD_VISITS) {
val ifdOffset = pendingIfds.removeAt(0)
if (ifdOffset <= 0L || ifdOffset in visitedIfds) {
continue
}
visitedIfds += ifdOffset
val scan = scanIfd(raf, ifdOffset, byteOrder) ?: continue
if (scan.cfaDimEntryOffset >= 0L && scan.cfaPatternEntryOffset >= 0L) {
writeEntry(
raf = raf,
entryOffset = scan.cfaDimEntryOffset,
type = TYPE_SHORT,
count = 2,
value = shortBytes(dim[0], byteOrder) + shortBytes(dim[1], byteOrder),
byteOrder = byteOrder
)
writeEntry(
raf = raf,
entryOffset = scan.cfaPatternEntryOffset,
type = TYPE_BYTE,
count = patternBytes.size.toLong(),
value = patternBytes,
byteOrder = byteOrder
)
patchedCount++
PLog.d(
TAG,
"Patched DNG CFA pattern cfa=$cfaPattern dim=${dim.joinToString("x")} " +
"ifd=$ifdOffset bytes=${patternBytes.joinToString()} in ${file.name}"
)
}
val entry = ByteArray(12)
raf.seek(entryOffset)
raf.readFully(entry)
when (readUnsignedShort(entry, 0, byteOrder)) {
TIFF_TAG_CFA_REPEAT_PATTERN_DIM -> cfaDimEntryOffset = entryOffset
TIFF_TAG_CFA_PATTERN -> cfaPatternEntryOffset = entryOffset
if (scan.nextIfdOffset > 0L) {
pendingIfds += scan.nextIfdOffset
}
scan.subIfdOffsets.forEach { subIfdOffset ->
if (subIfdOffset > 0L && subIfdOffset !in visitedIfds) {
pendingIfds += subIfdOffset
}
}
}
if (cfaDimEntryOffset < 0L || cfaPatternEntryOffset < 0L) {
PLog.w(TAG, "DNG CFA tags missing in ${file.name}; dim=$cfaDimEntryOffset pattern=$cfaPatternEntryOffset")
if (patchedCount == 0) {
PLog.w(TAG, "DNG CFA tags missing in ${file.name}; scannedIfds=${visitedIfds.size}")
return false
}
val dim = RawCfaCorrection.repeatPatternDim(cfaPattern)
writeEntry(
raf = raf,
entryOffset = cfaDimEntryOffset,
type = TYPE_SHORT,
count = 2,
value = shortBytes(dim[0], byteOrder) + shortBytes(dim[1], byteOrder),
byteOrder = byteOrder
)
val patternBytes = RawCfaCorrection.cfaPatternBytes(cfaPattern)
writeEntry(
raf = raf,
entryOffset = cfaPatternEntryOffset,
type = TYPE_BYTE,
count = patternBytes.size.toLong(),
value = patternBytes,
byteOrder = byteOrder
)
PLog.d(
TAG,
"Patched DNG CFA pattern cfa=$cfaPattern dim=${dim.joinToString("x")} " +
"bytes=${patternBytes.joinToString()} in ${file.name}"
)
true
}
}.onFailure {
@@ -103,6 +114,97 @@ object DngCfaPatternPatcher {
}.getOrDefault(false)
}
private fun scanIfd(raf: RandomAccessFile, ifdOffset: Long, byteOrder: ByteOrder): IfdScanResult? {
if (ifdOffset <= 0L || ifdOffset + 2L > raf.length()) {
return null
}
raf.seek(ifdOffset)
val entryCountBytes = ByteArray(2)
raf.readFully(entryCountBytes)
val entryCount = readUnsignedShort(entryCountBytes, 0, byteOrder)
val entriesStart = ifdOffset + 2L
val nextIfdPointerOffset = entriesStart + entryCount * 12L
if (nextIfdPointerOffset + 4L > raf.length()) {
return null
}
var cfaDimEntryOffset = -1L
var cfaPatternEntryOffset = -1L
val subIfdOffsets = mutableListOf<Long>()
for (entryIndex in 0 until entryCount) {
val entryOffset = entriesStart + entryIndex * 12L
val entry = ByteArray(12)
raf.seek(entryOffset)
raf.readFully(entry)
when (readUnsignedShort(entry, 0, byteOrder)) {
TIFF_TAG_CFA_REPEAT_PATTERN_DIM -> cfaDimEntryOffset = entryOffset
TIFF_TAG_CFA_PATTERN -> cfaPatternEntryOffset = entryOffset
TIFF_TAG_SUB_IFDS -> {
val type = readUnsignedShort(entry, 2, byteOrder)
val count = readUnsignedInt(entry, 4, byteOrder)
subIfdOffsets += readUnsignedValues(raf, entry, entryOffset, type, count, byteOrder)
}
}
}
raf.seek(nextIfdPointerOffset)
val nextIfdBytes = ByteArray(4)
raf.readFully(nextIfdBytes)
return IfdScanResult(
cfaDimEntryOffset = cfaDimEntryOffset,
cfaPatternEntryOffset = cfaPatternEntryOffset,
subIfdOffsets = subIfdOffsets,
nextIfdOffset = readUnsignedInt(nextIfdBytes, 0, byteOrder)
)
}
private fun readUnsignedValues(
raf: RandomAccessFile,
entry: ByteArray,
entryOffset: Long,
type: Int,
count: Long,
byteOrder: ByteOrder
): List<Long> {
if (count <= 0L || count > 64L) {
return emptyList()
}
val typeSize = when (type) {
TYPE_SHORT -> 2L
TYPE_LONG -> 4L
else -> return emptyList()
}
val valueBytes = typeSize * count
val valueOffset = if (valueBytes <= 4L) {
entryOffset + 8L
} else {
readUnsignedInt(entry, 8, byteOrder)
}
if (valueOffset < 0L || valueOffset + valueBytes > raf.length()) {
return emptyList()
}
return buildList {
raf.seek(valueOffset)
repeat(count.toInt()) {
when (type) {
TYPE_SHORT -> {
val bytes = ByteArray(2)
raf.readFully(bytes)
add(readUnsignedShort(bytes, 0, byteOrder).toLong())
}
TYPE_LONG -> {
val bytes = ByteArray(4)
raf.readFully(bytes)
add(readUnsignedInt(bytes, 0, byteOrder))
}
}
}
}
}
private fun writeEntry(
raf: RandomAccessFile,
entryOffset: Long,
@@ -206,7 +206,7 @@ object SuperResolutionDngWriter {
add(long(TAG_ROWS_PER_STRIP, height.toLong()))
add(long(TAG_STRIP_BYTE_COUNTS, imageByteCount))
add(short(TAG_PLANAR_CONFIGURATION, 1))
add(ascii(TAG_SOFTWARE, "PhotonMGC"))
add(ascii(TAG_SOFTWARE, "PhotonCamera"))
add(ascii(TAG_DATETIME, SimpleDateFormat("yyyy:MM:dd HH:mm:ss", Locale.US).format(Date())))
add(shortArray(TAG_CFA_REPEAT_PATTERN_DIM, RawCfaCorrection.repeatPatternDim(cfaPattern)))
add(byteArray(TAG_CFA_PATTERN, RawCfaCorrection.cfaPatternBytes(cfaPattern)))
@@ -317,7 +317,7 @@ object SuperResolutionDngWriter {
Build.MANUFACTURER.takeIf { it.isNotBlank() },
Build.MODEL.takeIf { it.isNotBlank() },
hardwareLevel?.let { "Camera2-$it" }
).joinToString(" ").ifBlank { "PhotonMGC Camera" }
).joinToString(" ").ifBlank { "Photon Camera" }
}
private fun blackLevelByCfaPosition(cfaPattern: Int, blackLevel: FloatArray): List<Float> {
+8 -4
View File
@@ -672,10 +672,14 @@
<string name="settings_cfa_correction_2x2_grbg">2x2 GRBG</string>
<string name="settings_cfa_correction_2x2_gbrg">2x2 GBRG</string>
<string name="settings_cfa_correction_2x2_bggr">2x2 BGGR</string>
<string name="settings_cfa_correction_4x4_rggb">4x4 Quad RGGB</string>
<string name="settings_cfa_correction_4x4_grbg">4x4 Quad GRBG</string>
<string name="settings_cfa_correction_4x4_gbrg">4x4 Quad GBRG</string>
<string name="settings_cfa_correction_4x4_bggr">4x4 Quad BGGR</string>
<string name="settings_cfa_correction_4x4_rggb">4x4 RGGB</string>
<string name="settings_cfa_correction_4x4_grbg">4x4 GRBG</string>
<string name="settings_cfa_correction_4x4_gbrg">4x4 GBRG</string>
<string name="settings_cfa_correction_4x4_bggr">4x4 BGGR</string>
<string name="settings_cfa_correction_8x8_rggb">8x8 RGGB</string>
<string name="settings_cfa_correction_8x8_grbg">8x8 GRBG</string>
<string name="settings_cfa_correction_8x8_gbrg">8x8 GBRG</string>
<string name="settings_cfa_correction_8x8_bggr">8x8 BGGR</string>
<string name="ghost_mode">โหมดแฟนทอม</string>
<string name="close_ghost_mode">ปิดโหมดผี</string>
<string name="ghost_mode_dialog_title">เปิดโหมดผี</string>
+8 -4
View File
@@ -744,10 +744,14 @@
<string name="settings_cfa_correction_2x2_grbg">2x2 GRBG</string>
<string name="settings_cfa_correction_2x2_gbrg">2x2 GBRG</string>
<string name="settings_cfa_correction_2x2_bggr">2x2 BGGR</string>
<string name="settings_cfa_correction_4x4_rggb">4x4 Quad RGGB</string>
<string name="settings_cfa_correction_4x4_grbg">4x4 Quad GRBG</string>
<string name="settings_cfa_correction_4x4_gbrg">4x4 Quad GBRG</string>
<string name="settings_cfa_correction_4x4_bggr">4x4 Quad BGGR</string>
<string name="settings_cfa_correction_4x4_rggb">4x4 RGGB</string>
<string name="settings_cfa_correction_4x4_grbg">4x4 GRBG</string>
<string name="settings_cfa_correction_4x4_gbrg">4x4 GBRG</string>
<string name="settings_cfa_correction_4x4_bggr">4x4 BGGR</string>
<string name="settings_cfa_correction_8x8_rggb">8x8 RGGB</string>
<string name="settings_cfa_correction_8x8_grbg">8x8 GRBG</string>
<string name="settings_cfa_correction_8x8_gbrg">8x8 GBRG</string>
<string name="settings_cfa_correction_8x8_bggr">8x8 BGGR</string>
<string name="ghost_mode">幻影模式</string>
<string name="close_ghost_mode">关闭幻影模式</string>
<string name="ghost_mode_dialog_title">开启幻影模式</string>
+8 -4
View File
@@ -728,10 +728,14 @@
<string name="settings_cfa_correction_2x2_grbg">2x2 GRBG</string>
<string name="settings_cfa_correction_2x2_gbrg">2x2 GBRG</string>
<string name="settings_cfa_correction_2x2_bggr">2x2 BGGR</string>
<string name="settings_cfa_correction_4x4_rggb">4x4 Quad RGGB</string>
<string name="settings_cfa_correction_4x4_grbg">4x4 Quad GRBG</string>
<string name="settings_cfa_correction_4x4_gbrg">4x4 Quad GBRG</string>
<string name="settings_cfa_correction_4x4_bggr">4x4 Quad BGGR</string>
<string name="settings_cfa_correction_4x4_rggb">4x4 RGGB</string>
<string name="settings_cfa_correction_4x4_grbg">4x4 GRBG</string>
<string name="settings_cfa_correction_4x4_gbrg">4x4 GBRG</string>
<string name="settings_cfa_correction_4x4_bggr">4x4 BGGR</string>
<string name="settings_cfa_correction_8x8_rggb">8x8 RGGB</string>
<string name="settings_cfa_correction_8x8_grbg">8x8 GRBG</string>
<string name="settings_cfa_correction_8x8_gbrg">8x8 GBRG</string>
<string name="settings_cfa_correction_8x8_bggr">8x8 BGGR</string>
<string name="settings_use_p010">P010 (10-bit YUV)</string>
<string name="settings_use_p010_description">Enable 10-bit YUV output for better image data precision. Effective on supported devices when RAW is disabled.</string>
<string name="settings_use_hlg10">HLG10 HDR</string>