diff --git a/app/src/main/cpp/CMakeLists.txt b/app/src/main/cpp/CMakeLists.txt index a5f586a1..8e0364a1 100644 --- a/app/src/main/cpp/CMakeLists.txt +++ b/app/src/main/cpp/CMakeLists.txt @@ -8,6 +8,7 @@ include_directories(${LIB_PATH}/include) include_directories(${CMAKE_CURRENT_SOURCE_DIR}/LibRaw) include_directories(${CMAKE_CURRENT_SOURCE_DIR}/libjpeg-turbo/src) include_directories(${CMAKE_CURRENT_BINARY_DIR}/libjpeg-turbo) +include_directories(${CMAKE_CURRENT_SOURCE_DIR}/../../../../rawtherapee-5.12/rtengine) file(GLOB JXL_LIBS "${LIB_PATH}/lib/${ANDROID_ABI}/*.a") diff --git a/app/src/main/cpp/LibRaw/libraw/libraw.h b/app/src/main/cpp/LibRaw/libraw/libraw.h index bbe8244e..7af23ee3 100644 --- a/app/src/main/cpp/LibRaw/libraw/libraw.h +++ b/app/src/main/cpp/LibRaw/libraw/libraw.h @@ -450,6 +450,7 @@ protected: void cielab(ushort rgb[3], short lab[3]); void xtrans_interpolate(int); void ahd_interpolate(); + void amaze_interpolate(); void dht_interpolate(); void aahd_interpolate(); void lmmse_interpolate(int gamma_apply); diff --git a/app/src/main/cpp/LibRaw/src/demosaic/amaze_demosaic.cpp b/app/src/main/cpp/LibRaw/src/demosaic/amaze_demosaic.cpp new file mode 100644 index 00000000..ce067ec9 --- /dev/null +++ b/app/src/main/cpp/LibRaw/src/demosaic/amaze_demosaic.cpp @@ -0,0 +1,1653 @@ +//////////////////////////////////////////////////////////////// +// +// AMaZE demosaic algorithm +// (Aliasing Minimization and Zipper Elimination) +// +// copyright (c) 2008-2010 Emil Martinec +// optimized for speed by Ingo Weyrich +// +// incorporating ideas of Luis Sanz Rodrigues and Paul Lee +// +// code dated: May 27, 2010 +// latest modification: Ingo Weyrich, January 25, 2016 +// +// amaze_interpolate_RT.cc is free software: you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. +// +// You should have received a copy of the GNU General Public License +// along with this program. If not, see . +// +//////////////////////////////////////////////////////////////// + +#include "../../internal/dcraw_defs.h" +#undef width +#undef height +#undef SQR +#undef LIM +#undef CLIP +#undef MAX +#undef MIN +#include "array2D.h" +#include "rt_math.h" +#include "sleef.h" +#include "opthelper.h" +#include "median.h" +#include +#include + +#define AMAZE_LOG_TAG "PLog_AMaZE" +#define AMAZE_LOGD(...) __android_log_print(ANDROID_LOG_DEBUG, AMAZE_LOG_TAG, __VA_ARGS__) + +namespace +{ +unsigned fc(const unsigned int cfa[2][2], int r, int c) { + return cfa[r & 1][c & 1]; +} + +unsigned libraw_fc(LibRaw* libraw, int r, int c) +{ + const unsigned f = libraw->FC(r, c); + return f == 3 ? 1 : f; +} + +unsigned short toUshort(float value) +{ + const float clamped = std::max(0.f, std::min(65535.f, value)); + return static_cast(clamped + 0.5f); +} +} + +using namespace rtengine; + +void LibRaw::amaze_interpolate() +{ + const int fullWidth = imgdata.sizes.width; + const int fullHeight = imgdata.sizes.height; + + if (fullWidth < 96 || fullHeight < 96) { + ahd_interpolate(); + return; + } + + RUN_CALLBACK(LIBRAW_PROGRESS_INTERPOLATE, 0, 1); + + const int winx = 0; + const int winy = 0; + const int winw = fullWidth; + const int winh = fullHeight; + const size_t chunkSize = 1; + + array2D rawData(fullWidth, fullHeight, ARRAY2D_CLEAR_DATA); + array2D red(fullWidth, fullHeight, ARRAY2D_CLEAR_DATA); + array2D green(fullWidth, fullHeight, ARRAY2D_CLEAR_DATA); + array2D blue(fullWidth, fullHeight, ARRAY2D_CLEAR_DATA); + + for (int row = 0; row < fullHeight; ++row) { + for (int col = 0; col < fullWidth; ++col) { + const unsigned rawChannel = FC(row, col); + const unsigned rtChannel = rawChannel == 3 ? 1 : rawChannel; + const float sample = image[row * fullWidth + col][rawChannel]; + rawData[row][col] = sample; + switch (rtChannel) { + case 0: red[row][col] = image[row * fullWidth + col][rawChannel]; break; + case 1: green[row][col] = image[row * fullWidth + col][rawChannel]; break; + case 2: blue[row][col] = image[row * fullWidth + col][rawChannel]; break; + } + } + } + + const unsigned int cfarray[2][2] = {{libraw_fc(this, 0,0), libraw_fc(this, 0,1)}, {libraw_fc(this, 1,0), libraw_fc(this, 1,1)}}; + const int width = winw, height = winh; + float initialGain = 1.0f; + for (int c = 0; c < 4; ++c) { + const float gain = pre_mul[c]; + if (gain > initialGain) { + initialGain = gain; + } + } + const float clip_pt = 1.0f / initialGain; + const float clip_pt8 = 0.8f / initialGain; + AMAZE_LOGD("amaze_interpolate: initialGain=%f clip_pt=%f clip_pt8=%f pre_mul=[%f,%f,%f,%f]", + initialGain, + clip_pt, + clip_pt8, + pre_mul[0], + pre_mul[1], + pre_mul[2], + pre_mul[3]); + +// this allows to pass AMAZETS to the code. On some machines larger AMAZETS is faster +// If AMAZETS is undefined it will be set to 160, which is the fastest on modern x86/64 machines +#ifndef AMAZETS +#define AMAZETS 160 +#endif + // Tile size; the image is processed in square tiles to lower memory requirements and facilitate multi-threading + // We assure that Tile size is a multiple of 32 in the range [96;992] + constexpr int ts = (AMAZETS & 992) < 96 ? 96 : (AMAZETS & 992); + constexpr int tsh = ts / 2; // half of Tile size + + //offset of R pixel within a Bayer quartet + int ex, ey; + + //determine GRBG coset; (ey,ex) is the offset of the R subarray + if (fc(cfarray, 0, 0) == 1) { //first pixel is G + if (fc(cfarray, 0, 1) == 0) { + ey = 0; + ex = 1; + } else { + ey = 1; + ex = 0; + } + } else {//first pixel is R or B + if (fc(cfarray, 0, 0) == 0) { + ey = 0; + ex = 0; + } else { + ey = 1; + ex = 1; + } + } + + //shifts of pointer value to access pixels in vertical and diagonal directions + constexpr int v1 = ts, v2 = 2 * ts, v3 = 3 * ts, p1 = -ts + 1, p2 = -2 * ts + 2, p3 = -3 * ts + 3, m1 = ts + 1, m2 = 2 * ts + 2, m3 = 3 * ts + 3; + + //tolerance to avoid dividing by zero + constexpr float eps = 1e-5, epssq = 1e-10; //tolerance to avoid dividing by zero + + //adaptive ratios threshold + constexpr float arthresh = 0.75; + + //gaussian on 5x5 quincunx, sigma=1.2 + constexpr float gaussodd[4] = {0.14659727707323927f, 0.103592713382435f, 0.0732036125103057f, 0.0365543548389495f}; + //nyquist texture test threshold + constexpr float nyqthresh = 0.5; + //gaussian on 5x5, sigma=1.2, multiplied with nyqthresh to save some time later in loop + // Is this really sigma=1.2????, seems more like sigma = 1.672 + constexpr float gaussgrad[6] = {nyqthresh * 0.07384411893421103f, nyqthresh * 0.06207511968171489f, nyqthresh * 0.0521818194747806f, + nyqthresh * 0.03687419286733595f, nyqthresh * 0.03099732204057846f, nyqthresh * 0.018413194161458882f + }; + //gaussian on 5x5 alt quincunx, sigma=1.5 + constexpr float gausseven[2] = {0.13719494435797422f, 0.05640252782101291f}; + //gaussian on quincunx grid + constexpr float gquinc[4] = {0.169917f, 0.108947f, 0.069855f, 0.0287182f}; + + typedef struct { + float h; + float v; + } s_hv; + +#ifdef _OPENMP + #pragma omp parallel +#endif + { + constexpr int cldf = 2; // factor to multiply cache line distance. 1 = 64 bytes, 2 = 128 bytes ... + // assign working space + char *buffer = (char *) calloc(14 * sizeof(float) * ts * ts + sizeof(char) * ts * tsh + 18 * cldf * 64 + 63, 1); + // aligned to 64 byte boundary + char *data = (char*)( ( uintptr_t(buffer) + uintptr_t(63)) / 64 * 64); + + // green values + float *rgbgreen = (float (*)) data; + // sum of square of horizontal gradient and square of vertical gradient + float *delhvsqsum = (float (*)) ((char*)rgbgreen + sizeof(float) * ts * ts + cldf * 64); // 1 + // gradient based directional weights for interpolation + float *dirwts0 = (float (*)) ((char*)delhvsqsum + sizeof(float) * ts * ts + cldf * 64); // 1 + float *dirwts1 = (float (*)) ((char*)dirwts0 + sizeof(float) * ts * ts + cldf * 64); // 1 + // vertically interpolated colour differences G-R, G-B + float *vcd = (float (*)) ((char*)dirwts1 + sizeof(float) * ts * ts + cldf * 64); // 1 + // horizontally interpolated colour differences + float *hcd = (float (*)) ((char*)vcd + sizeof(float) * ts * ts + cldf * 64); // 1 + // alternative vertical interpolation + float *vcdalt = (float (*)) ((char*)hcd + sizeof(float) * ts * ts + cldf * 64); // 1 + // alternative horizontal interpolation + float *hcdalt = (float (*)) ((char*)vcdalt + sizeof(float) * ts * ts + cldf * 64); // 1 + // square of average colour difference + float *cddiffsq = (float (*)) ((char*)hcdalt + sizeof(float) * ts * ts + cldf * 64); // 1 + // weight to give horizontal vs vertical interpolation + float *hvwt = (float (*)) ((char*)cddiffsq + sizeof(float) * ts * ts + 2 * cldf * 64); // 1 + // final interpolated colour difference + float (*Dgrb)[ts * tsh] = (float (*)[ts * tsh])vcdalt; // there is no overlap in buffer usage => share + // gradient in plus (NE/SW) direction + float *delp = (float (*))cddiffsq; // there is no overlap in buffer usage => share + // gradient in minus (NW/SE) direction + float *delm = (float (*)) ((char*)delp + sizeof(float) * ts * tsh + cldf * 64); + // diagonal interpolation of R+B + float *rbint = (float (*))delm; // there is no overlap in buffer usage => share + // horizontal and vertical curvature of interpolated G (used to refine interpolation in Nyquist texture regions) + s_hv *Dgrb2 = (s_hv (*)) ((char*)hvwt + sizeof(float) * ts * tsh + cldf * 64); // 1 + // difference between up/down interpolations of G + float *dgintv = (float (*))Dgrb2; // there is no overlap in buffer usage => share + // difference between left/right interpolations of G + float *dginth = (float (*)) ((char*)dgintv + sizeof(float) * ts * ts + cldf * 64); // 1 + // square of diagonal colour differences + float *Dgrbsq1m = (float (*)) ((char*)dginth + sizeof(float) * ts * ts + cldf * 64); // 1 + float *Dgrbsq1p = (float (*)) ((char*)Dgrbsq1m + sizeof(float) * ts * tsh + cldf * 64); // 1 + // tile raw data + float *cfa = (float (*)) ((char*)Dgrbsq1p + sizeof(float) * ts * tsh + cldf * 64); // 1 + // relative weight for combining plus and minus diagonal interpolations + float *pmwt = (float (*))delhvsqsum; // there is no overlap in buffer usage => share + // interpolated colour difference R-B in minus and plus direction + float *rbm = (float (*))vcd; // there is no overlap in buffer usage => share + float *rbp = (float (*)) ((char*)rbm + sizeof(float) * ts * tsh + cldf * 64); + // nyquist texture flags 1=nyquist, 0=not nyquist + unsigned char *nyquist = (unsigned char (*)) ((char*)cfa + sizeof(float) * ts * ts + cldf * 64); // 1 + unsigned char *nyquist2 = (unsigned char (*))cddiffsq; + float *nyqutest = (float(*)) ((char*)nyquist + sizeof(unsigned char) * ts * tsh + cldf * 64); // 1 + + // Main algorithm: Tile loop + // use collapse(2) to collapse the 2 loops to one large loop, so there is better scaling +#ifdef _OPENMP + #pragma omp for schedule(dynamic, chunkSize) collapse(2) nowait +#endif + + for (int top = winy - 16; top < winy + height; top += ts - 32) { + for (int left = winx - 16; left < winx + width; left += ts - 32) { + memset(&nyquist[3 * tsh], 0, sizeof(unsigned char) * (ts - 6) * tsh); + //location of tile bottom edge + int bottom = min(top + ts, winy + height + 16); + //location of tile right edge + int right = min(left + ts, winx + width + 16); + //tile width (=ts except for right edge of image) + int rr1 = bottom - top; + //tile height (=ts except for bottom edge of image) + int cc1 = right - left; + // bookkeeping for borders + // min and max row/column in the tile + int rrmin = top < winy ? 16 : 0; + int ccmin = left < winx ? 16 : 0; + int rrmax = bottom > (winy + height) ? winy + height - top : rr1; + int ccmax = right > (winx + width) ? winx + width - left : cc1; + + // rgb from input CFA data + // rgb values should be floating point number between 0 and 1 + // after white balance multipliers are applied + // a 16 pixel border is added to each side of the image + + // begin of tile initialization +#ifdef __SSE2__ + vfloat c65535v = F2V( 65535.f ); + + //fill upper border + if (rrmin > 0) { + for (int rr = 0; rr < 16; rr++) { + int row = 32 - rr + top; + + for (int cc = ccmin; cc < ccmax; cc += 4) { + int indx1 = rr * ts + cc; + vfloat tempv = LVFU(rawData[row][cc + left]) / c65535v; + STVF(cfa[indx1], tempv); + STVF(rgbgreen[indx1], tempv ); + } + } + } + + // fill inner part + for (int rr = rrmin; rr < rrmax; rr++) { + int row = rr + top; + int cc = ccmin; + for (; cc < ccmax - 3; cc += 4) { + int indx1 = rr * ts + cc; + vfloat tempv = LVFU(rawData[row][cc + left]) / c65535v; + STVF(cfa[indx1], tempv ); + STVF(rgbgreen[indx1], tempv ); + } + for (; cc < ccmax; ++cc) { + int indx1 = rr * ts + cc; + float temp = rawData[row][cc + left] / 65535.f; + cfa[indx1] = temp; + rgbgreen[indx1] = temp; + } + } + + //fill lower border + if (rrmax < rr1) { + for (int rr = 0; rr < 16; rr++) + for (int cc = ccmin; cc < ccmax; cc += 4) { + int indx1 = (rrmax + rr) * ts + cc; + vfloat tempv = LVFU(rawData[(winy + height - rr - 2)][left + cc]) / c65535v; + STVF(cfa[indx1], tempv ); + STVF(rgbgreen[indx1], tempv ); + } + } + +#else + + //fill upper border + if (rrmin > 0) { + for (int rr = 0; rr < 16; rr++) + for (int cc = ccmin, row = 32 - rr + top; cc < ccmax; cc++) { + cfa[rr * ts + cc] = (rawData[row][cc + left]) / 65535.f; + rgbgreen[rr * ts + cc] = cfa[rr * ts + cc]; + } + } + + // fill inner part + for (int rr = rrmin; rr < rrmax; rr++) { + int row = rr + top; + + for (int cc = ccmin; cc < ccmax; cc++) { + int indx1 = rr * ts + cc; + cfa[indx1] = (rawData[row][cc + left]) / 65535.f; + rgbgreen[indx1] = cfa[indx1]; + } + } + + //fill lower border + if (rrmax < rr1) { + for (int rr = 0; rr < 16; rr++) + for (int cc = ccmin; cc < ccmax; cc++) { + cfa[(rrmax + rr)*ts + cc] = (rawData[(winy + height - rr - 2)][left + cc]) / 65535.f; + rgbgreen[(rrmax + rr)*ts + cc] = cfa[(rrmax + rr) * ts + cc]; + } + } + +#endif + + //fill left border + if (ccmin > 0) { + for (int rr = rrmin; rr < rrmax; rr++) + for (int cc = 0, row = rr + top; cc < 16; cc++) { + cfa[rr * ts + cc] = (rawData[row][32 - cc + left]) / 65535.f; + rgbgreen[rr * ts + cc] = cfa[rr * ts + cc]; + } + } + + //fill right border + if (ccmax < cc1) { + for (int rr = rrmin; rr < rrmax; rr++) + for (int cc = 0; cc < 16; cc++) { + cfa[rr * ts + ccmax + cc] = (rawData[(top + rr)][(winx + width - cc - 2)]) / 65535.f; + rgbgreen[rr * ts + ccmax + cc] = cfa[rr * ts + ccmax + cc]; + } + } + + //also, fill the image corners + if (rrmin > 0 && ccmin > 0) { + for (int rr = 0; rr < 16; rr++) + for (int cc = 0; cc < 16; cc++) { + cfa[(rr)*ts + cc] = (rawData[winy + 32 - rr][winx + 32 - cc]) / 65535.f; + rgbgreen[(rr)*ts + cc] = cfa[(rr) * ts + cc]; + } + } + + if (rrmax < rr1 && ccmax < cc1) { + for (int rr = 0; rr < 16; rr++) + for (int cc = 0; cc < 16; cc++) { + cfa[(rrmax + rr)*ts + ccmax + cc] = (rawData[(winy + height - rr - 2)][(winx + width - cc - 2)]) / 65535.f; + rgbgreen[(rrmax + rr)*ts + ccmax + cc] = cfa[(rrmax + rr) * ts + ccmax + cc]; + } + } + + if (rrmin > 0 && ccmax < cc1) { + for (int rr = 0; rr < 16; rr++) + for (int cc = 0; cc < 16; cc++) { + cfa[(rr)*ts + ccmax + cc] = (rawData[(winy + 32 - rr)][(winx + width - cc - 2)]) / 65535.f; + rgbgreen[(rr)*ts + ccmax + cc] = cfa[(rr) * ts + ccmax + cc]; + } + } + + if (rrmax < rr1 && ccmin > 0) { + for (int rr = 0; rr < 16; rr++) + for (int cc = 0; cc < 16; cc++) { + cfa[(rrmax + rr)*ts + cc] = (rawData[(winy + height - rr - 2)][(winx + 32 - cc)]) / 65535.f; + rgbgreen[(rrmax + rr)*ts + cc] = cfa[(rrmax + rr) * ts + cc]; + } + } + + // end of tile initialization + + // horizontal and vertical gradients +#ifdef __SSE2__ + vfloat epsv = F2V( eps ); + + for (int rr = 2; rr < rr1 - 2; rr++) { + for (int indx = rr * ts; indx < rr * ts + cc1; indx += 4) { + vfloat delhv = vabsf( LVFU( cfa[indx + 1] ) - LVFU( cfa[indx - 1] ) ); + vfloat delvv = vabsf( LVF( cfa[indx + v1] ) - LVF( cfa[indx - v1] ) ); + STVF(dirwts1[indx], epsv + vabsf( LVFU( cfa[indx + 2] ) - LVF( cfa[indx] )) + vabsf( LVF( cfa[indx] ) - LVFU( cfa[indx - 2] )) + delhv ); + STVF(dirwts0[indx], epsv + vabsf( LVF( cfa[indx + v2] ) - LVF( cfa[indx] )) + vabsf( LVF( cfa[indx] ) - LVF( cfa[indx - v2] )) + delvv ); + STVF(delhvsqsum[indx], SQRV(delhv) + SQRV(delvv)); + } + } + +#else + + for (int rr = 2; rr < rr1 - 2; rr++) + for (int cc = 2, indx = (rr) * ts + cc; cc < cc1 - 2; cc++, indx++) { + float delh = fabsf(cfa[indx + 1] - cfa[indx - 1]); + float delv = fabsf(cfa[indx + v1] - cfa[indx - v1]); + dirwts0[indx] = eps + fabsf(cfa[indx + v2] - cfa[indx]) + fabsf(cfa[indx] - cfa[indx - v2]) + delv; + dirwts1[indx] = eps + fabsf(cfa[indx + 2] - cfa[indx]) + fabsf(cfa[indx] - cfa[indx - 2]) + delh; + delhvsqsum[indx] = SQR(delh) + SQR(delv); + } + +#endif + + //interpolate vertical and horizontal colour differences +#ifdef __SSE2__ + vfloat sgnv; + + if( !(fc(cfarray, 4, 4) & 1) ) { + sgnv = _mm_set_ps( 1.f, -1.f, 1.f, -1.f ); + } else { + sgnv = _mm_set_ps( -1.f, 1.f, -1.f, 1.f ); + } + + vfloat zd5v = F2V( 0.5f ); + vfloat onev = F2V( 1.f ); + vfloat arthreshv = F2V( arthresh ); + vfloat clip_pt8v = F2V( clip_pt8 ); + + for (int rr = 4; rr < rr1 - 4; rr++) { + sgnv = -sgnv; + + for (int indx = rr * ts + 4; indx < rr * ts + cc1 - 7; indx += 4) { + //colour ratios in each cardinal direction + vfloat cfav = LVF(cfa[indx]); + vfloat cruv = LVF(cfa[indx - v1]) * (LVF(dirwts0[indx - v2]) + LVF(dirwts0[indx])) / (LVF(dirwts0[indx - v2]) * (epsv + cfav) + LVF(dirwts0[indx]) * (epsv + LVF(cfa[indx - v2]))); + vfloat crdv = LVF(cfa[indx + v1]) * (LVF(dirwts0[indx + v2]) + LVF(dirwts0[indx])) / (LVF(dirwts0[indx + v2]) * (epsv + cfav) + LVF(dirwts0[indx]) * (epsv + LVF(cfa[indx + v2]))); + vfloat crlv = LVFU(cfa[indx - 1]) * (LVFU(dirwts1[indx - 2]) + LVF(dirwts1[indx])) / (LVFU(dirwts1[indx - 2]) * (epsv + cfav) + LVF(dirwts1[indx]) * (epsv + LVFU(cfa[indx - 2]))); + vfloat crrv = LVFU(cfa[indx + 1]) * (LVFU(dirwts1[indx + 2]) + LVF(dirwts1[indx])) / (LVFU(dirwts1[indx + 2]) * (epsv + cfav) + LVF(dirwts1[indx]) * (epsv + LVFU(cfa[indx + 2]))); + + //G interpolated in vert/hor directions using Hamilton-Adams method + vfloat guhav = LVF(cfa[indx - v1]) + zd5v * (cfav - LVF(cfa[indx - v2])); + vfloat gdhav = LVF(cfa[indx + v1]) + zd5v * (cfav - LVF(cfa[indx + v2])); + vfloat glhav = LVFU(cfa[indx - 1]) + zd5v * (cfav - LVFU(cfa[indx - 2])); + vfloat grhav = LVFU(cfa[indx + 1]) + zd5v * (cfav - LVFU(cfa[indx + 2])); + + //G interpolated in vert/hor directions using adaptive ratios + vfloat guarv = vself(vmaskf_lt(vabsf(onev - cruv), arthreshv), cfav * cruv, guhav); + vfloat gdarv = vself(vmaskf_lt(vabsf(onev - crdv), arthreshv), cfav * crdv, gdhav); + vfloat glarv = vself(vmaskf_lt(vabsf(onev - crlv), arthreshv), cfav * crlv, glhav); + vfloat grarv = vself(vmaskf_lt(vabsf(onev - crrv), arthreshv), cfav * crrv, grhav); + + //adaptive weights for vertical/horizontal directions + vfloat hwtv = LVFU(dirwts1[indx - 1]) / (LVFU(dirwts1[indx - 1]) + LVFU(dirwts1[indx + 1])); + vfloat vwtv = LVF(dirwts0[indx - v1]) / (LVF(dirwts0[indx + v1]) + LVF(dirwts0[indx - v1])); + + //interpolated G via adaptive weights of cardinal evaluations + vfloat Ginthhav = vintpf(hwtv, grhav, glhav); + vfloat Gintvhav = vintpf(vwtv, gdhav, guhav); + + //interpolated colour differences + vfloat hcdaltv = sgnv * (Ginthhav - cfav); + vfloat vcdaltv = sgnv * (Gintvhav - cfav); + STVF(hcdalt[indx], hcdaltv); + STVF(vcdalt[indx], vcdaltv); + + vmask clipmask = vorm( vorm( vmaskf_gt( cfav, clip_pt8v ), vmaskf_gt( Gintvhav, clip_pt8v ) ), vmaskf_gt( Ginthhav, clip_pt8v )); + guarv = vself( clipmask, guhav, guarv); + gdarv = vself( clipmask, gdhav, gdarv); + glarv = vself( clipmask, glhav, glarv); + grarv = vself( clipmask, grhav, grarv); + + //use HA if highlights are (nearly) clipped + STVF(vcd[indx], vself( clipmask, vcdaltv, sgnv * (vintpf(vwtv, gdarv, guarv) - cfav))); + STVF(hcd[indx], vself( clipmask, hcdaltv, sgnv * (vintpf(hwtv, grarv, glarv) - cfav))); + + //differences of interpolations in opposite directions + STVF(dgintv[indx], vminf(SQRV(guhav - gdhav), SQRV(guarv - gdarv))); + STVF(dginth[indx], vminf(SQRV(glhav - grhav), SQRV(glarv - grarv))); + } + } + +#else + + for (int rr = 4; rr < rr1 - 4; rr++) { + bool fcswitch = fc(cfarray, rr, 4) & 1; + + for (int cc = 4, indx = rr * ts + cc; cc < cc1 - 4; cc++, indx++) { + + //colour ratios in each cardinal direction + float cru = cfa[indx - v1] * (dirwts0[indx - v2] + dirwts0[indx]) / (dirwts0[indx - v2] * (eps + cfa[indx]) + dirwts0[indx] * (eps + cfa[indx - v2])); + float crd = cfa[indx + v1] * (dirwts0[indx + v2] + dirwts0[indx]) / (dirwts0[indx + v2] * (eps + cfa[indx]) + dirwts0[indx] * (eps + cfa[indx + v2])); + float crl = cfa[indx - 1] * (dirwts1[indx - 2] + dirwts1[indx]) / (dirwts1[indx - 2] * (eps + cfa[indx]) + dirwts1[indx] * (eps + cfa[indx - 2])); + float crr = cfa[indx + 1] * (dirwts1[indx + 2] + dirwts1[indx]) / (dirwts1[indx + 2] * (eps + cfa[indx]) + dirwts1[indx] * (eps + cfa[indx + 2])); + + //G interpolated in vert/hor directions using Hamilton-Adams method + float guha = cfa[indx - v1] + xdiv2f(cfa[indx] - cfa[indx - v2]); + float gdha = cfa[indx + v1] + xdiv2f(cfa[indx] - cfa[indx + v2]); + float glha = cfa[indx - 1] + xdiv2f(cfa[indx] - cfa[indx - 2]); + float grha = cfa[indx + 1] + xdiv2f(cfa[indx] - cfa[indx + 2]); + + //G interpolated in vert/hor directions using adaptive ratios + float guar, gdar, glar, grar; + + if (fabsf(1.f - cru) < arthresh) { + guar = cfa[indx] * cru; + } else { + guar = guha; + } + + if (fabsf(1.f - crd) < arthresh) { + gdar = cfa[indx] * crd; + } else { + gdar = gdha; + } + + if (fabsf(1.f - crl) < arthresh) { + glar = cfa[indx] * crl; + } else { + glar = glha; + } + + if (fabsf(1.f - crr) < arthresh) { + grar = cfa[indx] * crr; + } else { + grar = grha; + } + + //adaptive weights for vertical/horizontal directions + float hwt = dirwts1[indx - 1] / (dirwts1[indx - 1] + dirwts1[indx + 1]); + float vwt = dirwts0[indx - v1] / (dirwts0[indx + v1] + dirwts0[indx - v1]); + + //interpolated G via adaptive weights of cardinal evaluations + float Gintvha = vwt * gdha + (1.f - vwt) * guha; + float Ginthha = hwt * grha + (1.f - hwt) * glha; + + //interpolated colour differences + if (fcswitch) { + vcd[indx] = cfa[indx] - (vwt * gdar + (1.f - vwt) * guar); + hcd[indx] = cfa[indx] - (hwt * grar + (1.f - hwt) * glar); + vcdalt[indx] = cfa[indx] - Gintvha; + hcdalt[indx] = cfa[indx] - Ginthha; + } else { + //interpolated colour differences + vcd[indx] = (vwt * gdar + (1.f - vwt) * guar) - cfa[indx]; + hcd[indx] = (hwt * grar + (1.f - hwt) * glar) - cfa[indx]; + vcdalt[indx] = Gintvha - cfa[indx]; + hcdalt[indx] = Ginthha - cfa[indx]; + } + + fcswitch = !fcswitch; + + if (cfa[indx] > clip_pt8 || Gintvha > clip_pt8 || Ginthha > clip_pt8) { + //use HA if highlights are (nearly) clipped + guar = guha; + gdar = gdha; + glar = glha; + grar = grha; + vcd[indx] = vcdalt[indx]; + hcd[indx] = hcdalt[indx]; + } + + //differences of interpolations in opposite directions + dgintv[indx] = min(SQR(guha - gdha), SQR(guar - gdar)); + dginth[indx] = min(SQR(glha - grha), SQR(glar - grar)); + + } + } + +#endif + + + +#ifdef __SSE2__ + vfloat clip_ptv = F2V( clip_pt ); + vfloat sgn3v; + + if( !(fc(cfarray, 4, 4) & 1) ) { + sgnv = _mm_set_ps( 1.f, -1.f, 1.f, -1.f ); + } else { + sgnv = _mm_set_ps( -1.f, 1.f, -1.f, 1.f ); + } + + sgn3v = sgnv + sgnv + sgnv; + + for (int rr = 4; rr < rr1 - 4; rr++) { + vfloat nsgnv = sgnv; + sgnv = -sgnv; + sgn3v = -sgn3v; + + for (int indx = rr * ts + 4; indx < rr * ts + cc1 - 4; indx += 4) { + vfloat hcdv = LVF( hcd[indx] ); + vfloat hcdvarv = SQRV(LVFU(hcd[indx - 2]) - hcdv) + SQRV(LVFU(hcd[indx - 2]) - LVFU(hcd[indx + 2])) + SQRV(hcdv - LVFU(hcd[indx + 2])); + vfloat hcdaltv = LVF( hcdalt[indx] ); + vfloat hcdaltvarv = SQRV(LVFU(hcdalt[indx - 2]) - hcdaltv) + SQRV(LVFU(hcdalt[indx - 2]) - LVFU(hcdalt[indx + 2])) + SQRV(hcdaltv - LVFU(hcdalt[indx + 2])); + vfloat vcdv = LVF( vcd[indx] ); + vfloat vcdvarv = SQRV(LVF(vcd[indx - v2]) - vcdv) + SQRV(LVF(vcd[indx - v2]) - LVF(vcd[indx + v2])) + SQRV(vcdv - LVF(vcd[indx + v2])); + vfloat vcdaltv = LVF( vcdalt[indx] ); + vfloat vcdaltvarv = SQRV(LVF(vcdalt[indx - v2]) - vcdaltv) + SQRV(LVF(vcdalt[indx - v2]) - LVF(vcdalt[indx + v2])) + SQRV(vcdaltv - LVF(vcdalt[indx + v2])); + + //choose the smallest variance; this yields a smoother interpolation + hcdv = vself( vmaskf_lt( hcdaltvarv, hcdvarv ), hcdaltv, hcdv); + vcdv = vself( vmaskf_lt( vcdaltvarv, vcdvarv ), vcdaltv, vcdv); + + //bound the interpolation in regions of high saturation + //vertical and horizontal G interpolations + vfloat Ginthv = sgnv * hcdv + LVF( cfa[indx] ); + vfloat temp2v = sgn3v * hcdv; + vfloat hwtv = onev + temp2v / ( epsv + Ginthv + LVF( cfa[indx])); + vmask hcdmask = vmaskf_gt( nsgnv * hcdv, ZEROV ); + vfloat hcdoldv = hcdv; + vfloat tempv = nsgnv * (LVF(cfa[indx]) - median( Ginthv, LVFU(cfa[indx - 1]), LVFU(cfa[indx + 1]) )); + hcdv = vself( vmaskf_lt( temp2v, -(LVF(cfa[indx]) + Ginthv)), tempv, vintpf(hwtv, hcdv, tempv)); + hcdv = vself( hcdmask, hcdv, hcdoldv ); + hcdv = vself( vmaskf_gt( Ginthv, clip_ptv), tempv, hcdv); + STVF(hcd[indx], hcdv); + + vfloat Gintvv = sgnv * vcdv + LVF( cfa[indx] ); + temp2v = sgn3v * vcdv; + vfloat vwtv = onev + temp2v / ( epsv + Gintvv + LVF( cfa[indx])); + vmask vcdmask = vmaskf_gt( nsgnv * vcdv, ZEROV ); + vfloat vcdoldv = vcdv; + tempv = nsgnv * (LVF(cfa[indx]) - median( Gintvv, LVF(cfa[indx - v1]), LVF(cfa[indx + v1]) )); + vcdv = vself( vmaskf_lt( temp2v, -(LVF(cfa[indx]) + Gintvv)), tempv, vintpf(vwtv, vcdv, tempv)); + vcdv = vself( vcdmask, vcdv, vcdoldv ); + vcdv = vself( vmaskf_gt( Gintvv, clip_ptv), tempv, vcdv); + STVF(vcd[indx], vcdv); + STVFU(cddiffsq[indx], SQRV(vcdv - hcdv)); + } + + } + +#else + + for (int rr = 4; rr < rr1 - 4; rr++) { + for (int cc = 4, indx = rr * ts + cc, c = fc(cfarray, rr, cc) & 1; cc < cc1 - 4; cc++, indx++) { + float hcdvar = 3.f * (SQR(hcd[indx - 2]) + SQR(hcd[indx]) + SQR(hcd[indx + 2])) - SQR(hcd[indx - 2] + hcd[indx] + hcd[indx + 2]); + float hcdaltvar = 3.f * (SQR(hcdalt[indx - 2]) + SQR(hcdalt[indx]) + SQR(hcdalt[indx + 2])) - SQR(hcdalt[indx - 2] + hcdalt[indx] + hcdalt[indx + 2]); + float vcdvar = 3.f * (SQR(vcd[indx - v2]) + SQR(vcd[indx]) + SQR(vcd[indx + v2])) - SQR(vcd[indx - v2] + vcd[indx] + vcd[indx + v2]); + float vcdaltvar = 3.f * (SQR(vcdalt[indx - v2]) + SQR(vcdalt[indx]) + SQR(vcdalt[indx + v2])) - SQR(vcdalt[indx - v2] + vcdalt[indx] + vcdalt[indx + v2]); + + //choose the smallest variance; this yields a smoother interpolation + if (hcdaltvar < hcdvar) { + hcd[indx] = hcdalt[indx]; + } + + if (vcdaltvar < vcdvar) { + vcd[indx] = vcdalt[indx]; + } + + //bound the interpolation in regions of high saturation + //vertical and horizontal G interpolations + float Gintv, Ginth; + + if (c) {//G site + Ginth = -hcd[indx] + cfa[indx]; //R or B + Gintv = -vcd[indx] + cfa[indx]; //B or R + + if (hcd[indx] > 0) { + if (3.f * hcd[indx] > (Ginth + cfa[indx])) { + hcd[indx] = -median(Ginth, cfa[indx - 1], cfa[indx + 1]) + cfa[indx]; + } else { + float hwt = 1.f - 3.f * hcd[indx] / (eps + Ginth + cfa[indx]); + hcd[indx] = hwt * hcd[indx] + (1.f - hwt) * (-median(Ginth, cfa[indx - 1], cfa[indx + 1]) + cfa[indx]); + } + } + + if (vcd[indx] > 0) { + if (3.f * vcd[indx] > (Gintv + cfa[indx])) { + vcd[indx] = -median(Gintv, cfa[indx - v1], cfa[indx + v1]) + cfa[indx]; + } else { + float vwt = 1.f - 3.f * vcd[indx] / (eps + Gintv + cfa[indx]); + vcd[indx] = vwt * vcd[indx] + (1.f - vwt) * (-median(Gintv, cfa[indx - v1], cfa[indx + v1]) + cfa[indx]); + } + } + + if (Ginth > clip_pt) { + hcd[indx] = -median(Ginth, cfa[indx - 1], cfa[indx + 1]) + cfa[indx]; + } + + if (Gintv > clip_pt) { + vcd[indx] = -median(Gintv, cfa[indx - v1], cfa[indx + v1]) + cfa[indx]; + } + + + } else {//R or B site + + Ginth = hcd[indx] + cfa[indx]; //interpolated G + Gintv = vcd[indx] + cfa[indx]; + + if (hcd[indx] < 0) { + if (3.f * hcd[indx] < -(Ginth + cfa[indx])) { + hcd[indx] = median(Ginth, cfa[indx - 1], cfa[indx + 1]) - cfa[indx]; + } else { + float hwt = 1.f + 3.f * hcd[indx] / (eps + Ginth + cfa[indx]); + hcd[indx] = hwt * hcd[indx] + (1.f - hwt) * (median(Ginth, cfa[indx - 1], cfa[indx + 1]) - cfa[indx]); + } + } + + if (vcd[indx] < 0) { + if (3.f * vcd[indx] < -(Gintv + cfa[indx])) { + vcd[indx] = median(Gintv, cfa[indx - v1], cfa[indx + v1]) - cfa[indx]; + } else { + float vwt = 1.f + 3.f * vcd[indx] / (eps + Gintv + cfa[indx]); + vcd[indx] = vwt * vcd[indx] + (1.f - vwt) * (median(Gintv, cfa[indx - v1], cfa[indx + v1]) - cfa[indx]); + } + } + + if (Ginth > clip_pt) { + hcd[indx] = median(Ginth, cfa[indx - 1], cfa[indx + 1]) - cfa[indx]; + } + + if (Gintv > clip_pt) { + vcd[indx] = median(Gintv, cfa[indx - v1], cfa[indx + v1]) - cfa[indx]; + } + + cddiffsq[indx] = SQR(vcd[indx] - hcd[indx]); + } + + c = !c; + } + } + +#endif + + + +#ifdef __SSE2__ + vfloat epssqv = F2V( epssq ); + + for (int rr = 6; rr < rr1 - 6; rr++) { + for (int indx = rr * ts + 6 + (fc(cfarray, rr, 2) & 1); indx < rr * ts + cc1 - 6; indx += 8) { + //compute colour difference variances in cardinal directions + vfloat tempv = LC2VFU(vcd[indx]); + vfloat uavev = tempv + LC2VFU(vcd[indx - v1]) + LC2VFU(vcd[indx - v2]) + LC2VFU(vcd[indx - v3]); + vfloat davev = tempv + LC2VFU(vcd[indx + v1]) + LC2VFU(vcd[indx + v2]) + LC2VFU(vcd[indx + v3]); + vfloat Dgrbvvaruv = SQRV(tempv - uavev) + SQRV(LC2VFU(vcd[indx - v1]) - uavev) + SQRV(LC2VFU(vcd[indx - v2]) - uavev) + SQRV(LC2VFU(vcd[indx - v3]) - uavev); + vfloat Dgrbvvardv = SQRV(tempv - davev) + SQRV(LC2VFU(vcd[indx + v1]) - davev) + SQRV(LC2VFU(vcd[indx + v2]) - davev) + SQRV(LC2VFU(vcd[indx + v3]) - davev); + + vfloat hwtv = vadivapb(LC2VFU(dirwts1[indx - 1]), LC2VFU(dirwts1[indx + 1])); + vfloat vwtv = vadivapb(LC2VFU(dirwts0[indx - v1]), LC2VFU(dirwts0[indx + v1])); + + tempv = LC2VFU(hcd[indx]); + vfloat lavev = tempv + vaddc2vfu(hcd[indx - 3]) + LC2VFU(hcd[indx - 1]); + vfloat ravev = tempv + vaddc2vfu(hcd[indx + 1]) + LC2VFU(hcd[indx + 3]); + + vfloat Dgrbhvarlv = SQRV(tempv - lavev) + SQRV(LC2VFU(hcd[indx - 1]) - lavev) + SQRV(LC2VFU(hcd[indx - 2]) - lavev) + SQRV(LC2VFU(hcd[indx - 3]) - lavev); + vfloat Dgrbhvarrv = SQRV(tempv - ravev) + SQRV(LC2VFU(hcd[indx + 1]) - ravev) + SQRV(LC2VFU(hcd[indx + 2]) - ravev) + SQRV(LC2VFU(hcd[indx + 3]) - ravev); + + + vfloat vcdvarv = epssqv + vintpf(vwtv, Dgrbvvardv, Dgrbvvaruv); + vfloat hcdvarv = epssqv + vintpf(hwtv, Dgrbhvarrv, Dgrbhvarlv); + + //compute fluctuations in up/down and left/right interpolations of colours + Dgrbvvaruv = LC2VFU(dgintv[indx - v1]) + LC2VFU(dgintv[indx - v2]); + Dgrbvvardv = LC2VFU(dgintv[indx + v1]) + LC2VFU(dgintv[indx + v2]); + + Dgrbhvarlv = vaddc2vfu(dginth[indx - 2]); + Dgrbhvarrv = vaddc2vfu(dginth[indx + 1]); + + vfloat vcdvar1v = epssqv + LC2VFU(dgintv[indx]) + vintpf(vwtv, Dgrbvvardv, Dgrbvvaruv); + vfloat hcdvar1v = epssqv + LC2VFU(dginth[indx]) + vintpf(hwtv, Dgrbhvarrv, Dgrbhvarlv); + + //determine adaptive weights for G interpolation + vfloat varwtv = hcdvarv / (vcdvarv + hcdvarv); + vfloat diffwtv = hcdvar1v / (vcdvar1v + hcdvar1v); + + //if both agree on interpolation direction, choose the one with strongest directional discrimination; + //otherwise, choose the u/d and l/r difference fluctuation weights + vmask decmask = vandm( vmaskf_gt( (zd5v - varwtv) * (zd5v - diffwtv), ZEROV ), vmaskf_lt( vabsf( zd5v - diffwtv), vabsf( zd5v - varwtv) ) ); + STVFU(hvwt[indx >> 1], vself( decmask, varwtv, diffwtv)); + } + } + +#else + + for (int rr = 6; rr < rr1 - 6; rr++) { + for (int cc = 6 + (fc(cfarray, rr, 2) & 1), indx = rr * ts + cc; cc < cc1 - 6; cc += 2, indx += 2) { + + //compute colour difference variances in cardinal directions + + float uave = vcd[indx] + vcd[indx - v1] + vcd[indx - v2] + vcd[indx - v3]; + float dave = vcd[indx] + vcd[indx + v1] + vcd[indx + v2] + vcd[indx + v3]; + float lave = hcd[indx] + hcd[indx - 1] + hcd[indx - 2] + hcd[indx - 3]; + float rave = hcd[indx] + hcd[indx + 1] + hcd[indx + 2] + hcd[indx + 3]; + + //colour difference (G-R or G-B) variance in up/down/left/right directions + float Dgrbvvaru = SQR(vcd[indx] - uave) + SQR(vcd[indx - v1] - uave) + SQR(vcd[indx - v2] - uave) + SQR(vcd[indx - v3] - uave); + float Dgrbvvard = SQR(vcd[indx] - dave) + SQR(vcd[indx + v1] - dave) + SQR(vcd[indx + v2] - dave) + SQR(vcd[indx + v3] - dave); + float Dgrbhvarl = SQR(hcd[indx] - lave) + SQR(hcd[indx - 1] - lave) + SQR(hcd[indx - 2] - lave) + SQR(hcd[indx - 3] - lave); + float Dgrbhvarr = SQR(hcd[indx] - rave) + SQR(hcd[indx + 1] - rave) + SQR(hcd[indx + 2] - rave) + SQR(hcd[indx + 3] - rave); + + float hwt = dirwts1[indx - 1] / (dirwts1[indx - 1] + dirwts1[indx + 1]); + float vwt = dirwts0[indx - v1] / (dirwts0[indx + v1] + dirwts0[indx - v1]); + + float vcdvar = epssq + vwt * Dgrbvvard + (1.f - vwt) * Dgrbvvaru; + float hcdvar = epssq + hwt * Dgrbhvarr + (1.f - hwt) * Dgrbhvarl; + + //compute fluctuations in up/down and left/right interpolations of colours + Dgrbvvaru = (dgintv[indx]) + (dgintv[indx - v1]) + (dgintv[indx - v2]); + Dgrbvvard = (dgintv[indx]) + (dgintv[indx + v1]) + (dgintv[indx + v2]); + Dgrbhvarl = (dginth[indx]) + (dginth[indx - 1]) + (dginth[indx - 2]); + Dgrbhvarr = (dginth[indx]) + (dginth[indx + 1]) + (dginth[indx + 2]); + + float vcdvar1 = epssq + vwt * Dgrbvvard + (1.f - vwt) * Dgrbvvaru; + float hcdvar1 = epssq + hwt * Dgrbhvarr + (1.f - hwt) * Dgrbhvarl; + + //determine adaptive weights for G interpolation + float varwt = hcdvar / (vcdvar + hcdvar); + float diffwt = hcdvar1 / (vcdvar1 + hcdvar1); + + //if both agree on interpolation direction, choose the one with strongest directional discrimination; + //otherwise, choose the u/d and l/r difference fluctuation weights + if ((0.5f - varwt) * (0.5f - diffwt) > 0.f && fabsf(0.5f - diffwt) < fabsf(0.5f - varwt)) { + hvwt[indx >> 1] = varwt; + } else { + hvwt[indx >> 1] = diffwt; + } + } + } + +#endif + +#ifdef __SSE2__ + vfloat gaussg0 = F2V(gaussgrad[0]); + vfloat gaussg1 = F2V(gaussgrad[1]); + vfloat gaussg2 = F2V(gaussgrad[2]); + vfloat gaussg3 = F2V(gaussgrad[3]); + vfloat gaussg4 = F2V(gaussgrad[4]); + vfloat gaussg5 = F2V(gaussgrad[5]); + vfloat gausso0 = F2V(gaussodd[0]); + vfloat gausso1 = F2V(gaussodd[1]); + vfloat gausso2 = F2V(gaussodd[2]); + vfloat gausso3 = F2V(gaussodd[3]); + +#endif + + // precompute nyquist + for (int rr = 6; rr < rr1 - 6; rr++) { + int cc = 6 + (fc(cfarray, rr, 2) & 1); + int indx = rr * ts + cc; + +#ifdef __SSE2__ + + for (; cc < cc1 - 7; cc += 8, indx += 8) { + vfloat valv = (gausso0 * LC2VFU(cddiffsq[indx]) + + gausso1 * (LC2VFU(cddiffsq[(indx - m1)]) + LC2VFU(cddiffsq[(indx + p1)]) + + LC2VFU(cddiffsq[(indx - p1)]) + LC2VFU(cddiffsq[(indx + m1)])) + + gausso2 * (LC2VFU(cddiffsq[(indx - v2)]) + LC2VFU(cddiffsq[(indx - 2)]) + + LC2VFU(cddiffsq[(indx + 2)]) + LC2VFU(cddiffsq[(indx + v2)])) + + gausso3 * (LC2VFU(cddiffsq[(indx - m2)]) + LC2VFU(cddiffsq[(indx + p2)]) + + LC2VFU(cddiffsq[(indx - p2)]) + LC2VFU(cddiffsq[(indx + m2)]))) - + (gaussg0 * LC2VFU(delhvsqsum[indx]) + + gaussg1 * (LC2VFU(delhvsqsum[indx - v1]) + LC2VFU(delhvsqsum[indx - 1]) + + LC2VFU(delhvsqsum[indx + 1]) + LC2VFU(delhvsqsum[indx + v1])) + + gaussg2 * (LC2VFU(delhvsqsum[indx - m1]) + LC2VFU(delhvsqsum[indx + p1]) + + LC2VFU(delhvsqsum[indx - p1]) + LC2VFU(delhvsqsum[indx + m1])) + + gaussg3 * (LC2VFU(delhvsqsum[indx - v2]) + LC2VFU(delhvsqsum[indx - 2]) + + LC2VFU(delhvsqsum[indx + 2]) + LC2VFU(delhvsqsum[indx + v2])) + + gaussg4 * (LC2VFU(delhvsqsum[indx - v2 - 1]) + LC2VFU(delhvsqsum[indx - v2 + 1]) + + LC2VFU(delhvsqsum[indx - ts - 2]) + LC2VFU(delhvsqsum[indx - ts + 2]) + + LC2VFU(delhvsqsum[indx + ts - 2]) + LC2VFU(delhvsqsum[indx + ts + 2]) + + LC2VFU(delhvsqsum[indx + v2 - 1]) + LC2VFU(delhvsqsum[indx + v2 + 1])) + + gaussg5 * (LC2VFU(delhvsqsum[indx - m2]) + LC2VFU(delhvsqsum[indx + p2]) + + LC2VFU(delhvsqsum[indx - p2]) + LC2VFU(delhvsqsum[indx + m2]))); + STVFU(nyqutest[indx >> 1], valv); + + } + +#endif + + for (; cc < cc1 - 6; cc += 2, indx += 2) { + nyqutest[indx >> 1] = (gaussodd[0] * cddiffsq[indx] + + gaussodd[1] * (cddiffsq[(indx - m1)] + cddiffsq[(indx + p1)] + + cddiffsq[(indx - p1)] + cddiffsq[(indx + m1)]) + + gaussodd[2] * (cddiffsq[(indx - v2)] + cddiffsq[(indx - 2)] + + cddiffsq[(indx + 2)] + cddiffsq[(indx + v2)]) + + gaussodd[3] * (cddiffsq[(indx - m2)] + cddiffsq[(indx + p2)] + + cddiffsq[(indx - p2)] + cddiffsq[(indx + m2)])) - + (gaussgrad[0] * delhvsqsum[indx] + + gaussgrad[1] * (delhvsqsum[indx - v1] + delhvsqsum[indx + 1] + + delhvsqsum[indx - 1] + delhvsqsum[indx + v1]) + + gaussgrad[2] * (delhvsqsum[indx - m1] + delhvsqsum[indx + p1] + + delhvsqsum[indx - p1] + delhvsqsum[indx + m1]) + + gaussgrad[3] * (delhvsqsum[indx - v2] + delhvsqsum[indx - 2] + + delhvsqsum[indx + 2] + delhvsqsum[indx + v2]) + + gaussgrad[4] * (delhvsqsum[indx - v2 - 1] + delhvsqsum[indx - v2 + 1] + + delhvsqsum[indx - ts - 2] + delhvsqsum[indx - ts + 2] + + delhvsqsum[indx + ts - 2] + delhvsqsum[indx + ts + 2] + + delhvsqsum[indx + v2 - 1] + delhvsqsum[indx + v2 + 1]) + + gaussgrad[5] * (delhvsqsum[indx - m2] + delhvsqsum[indx + p2] + + delhvsqsum[indx - p2] + delhvsqsum[indx + m2])); + } + } + + // Nyquist test + int nystartrow = 0; + int nyendrow = 0; + int nystartcol = ts + 1; + int nyendcol = 0; + + for (int rr = 6; rr < rr1 - 6; rr++) { + for (int cc = 6 + (fc(cfarray, rr, 2) & 1), indx = rr * ts + cc; cc < cc1 - 6; cc += 2, indx += 2) { + + //nyquist texture test: ask if difference of vcd compared to hcd is larger or smaller than RGGB gradients + if(nyqutest[indx >> 1] > 0.f) { + nyquist[indx >> 1] = 1; //nyquist=1 for nyquist region + nystartrow = nystartrow ? nystartrow : rr; + nyendrow = rr; + nystartcol = nystartcol > cc ? cc : nystartcol; + nyendcol = nyendcol < cc ? cc : nyendcol; + } + } + } + + + bool doNyquist = nystartrow != nyendrow && nystartcol != nyendcol; + + if(doNyquist) { + nyendrow ++; // because of < condition + nyendcol ++; // because of < condition + nystartcol -= (nystartcol & 1); + nystartrow = std::max(8, nystartrow); + nyendrow = std::min(rr1 - 8, nyendrow); + nystartcol = std::max(8, nystartcol); + nyendcol = std::min(cc1 - 8, nyendcol); + memset(&nyquist2[4 * tsh], 0, sizeof(char) * (ts - 8) * tsh); + +#ifdef __SSE2__ + vint fourvb = _mm_set1_epi8(4); + vint onevb = _mm_set1_epi8(1); + +#endif + + for (int rr = nystartrow; rr < nyendrow; rr++) { +#ifdef __SSE2__ + + for (int indx = rr * ts; indx < rr * ts + cc1; indx += 32) { + vint nyquisttemp1v = _mm_adds_epi8(_mm_load_si128((vint*)&nyquist[(indx - v2) >> 1]), _mm_loadu_si128((vint*)&nyquist[(indx - m1) >> 1])); + vint nyquisttemp2v = _mm_adds_epi8(_mm_loadu_si128((vint*)&nyquist[(indx + p1) >> 1]), _mm_loadu_si128((vint*)&nyquist[(indx - 2) >> 1])); + vint nyquisttemp3v = _mm_adds_epi8(_mm_loadu_si128((vint*)&nyquist[(indx + 2) >> 1]), _mm_loadu_si128((vint*)&nyquist[(indx - p1) >> 1])); + vint valv = _mm_load_si128((vint*)&nyquist[indx >> 1]); + vint nyquisttemp4v = _mm_adds_epi8(_mm_loadu_si128((vint*)&nyquist[(indx + m1) >> 1]), _mm_load_si128((vint*)&nyquist[(indx + v2) >> 1])); + nyquisttemp1v = _mm_adds_epi8(nyquisttemp1v, nyquisttemp3v); + nyquisttemp2v = _mm_adds_epi8(nyquisttemp2v, nyquisttemp4v); + nyquisttemp1v = _mm_adds_epi8(nyquisttemp1v, nyquisttemp2v); + valv = vselc(_mm_cmpgt_epi8(nyquisttemp1v, fourvb), onevb, valv); + valv = vselinotzero(_mm_cmplt_epi8(nyquisttemp1v, fourvb), valv); + _mm_store_si128((vint*)&nyquist2[indx >> 1], valv); + } + +#else + + for (int indx = rr * ts + nystartcol + (fc(cfarray, rr, 2) & 1); indx < rr * ts + nyendcol; indx += 2) { + unsigned int nyquisttemp = (nyquist[(indx - v2) >> 1] + nyquist[(indx - m1) >> 1] + nyquist[(indx + p1) >> 1] + + nyquist[(indx - 2) >> 1] + nyquist[(indx + 2) >> 1] + + nyquist[(indx - p1) >> 1] + nyquist[(indx + m1) >> 1] + nyquist[(indx + v2) >> 1]); + //if most of your neighbours are named Nyquist, it's likely that you're one too, or not + nyquist2[indx >> 1] = nyquisttemp > 4 ? 1 : (nyquisttemp < 4 ? 0 : nyquist[indx >> 1]); + } + +#endif + } + + // end of Nyquist test + + // in areas of Nyquist texture, do area interpolation + for (int rr = nystartrow; rr < nyendrow; rr++) + for (int indx = rr * ts + nystartcol + (fc(cfarray, rr, 2) & 1); indx < rr * ts + nyendcol; indx += 2) { + + if (nyquist2[indx >> 1]) { + // area interpolation + + float sumcfa = 0.f, sumh = 0.f, sumv = 0.f, sumsqh = 0.f, sumsqv = 0.f, areawt = 0.f; + + for (int i = -6; i < 7; i += 2) { + int indx1 = indx + (i * ts) - 6; + + for (int j = -6; j < 7; j += 2, indx1 += 2) { + if (nyquist2[indx1 >> 1]) { + float cfatemp = cfa[indx1]; + sumcfa += cfatemp; + sumh += (cfa[indx1 - 1] + cfa[indx1 + 1]); + sumv += (cfa[indx1 - v1] + cfa[indx1 + v1]); + sumsqh += SQR(cfatemp - cfa[indx1 - 1]) + SQR(cfatemp - cfa[indx1 + 1]); + sumsqv += SQR(cfatemp - cfa[indx1 - v1]) + SQR(cfatemp - cfa[indx1 + v1]); + areawt += 1; + } + } + } + + //horizontal and vertical colour differences, and adaptive weight + sumh = sumcfa - xdiv2f(sumh); + sumv = sumcfa - xdiv2f(sumv); + areawt = xdiv2f(areawt); + float hcdvar = epssq + fabsf(areawt * sumsqh - sumh * sumh); + float vcdvar = epssq + fabsf(areawt * sumsqv - sumv * sumv); + hvwt[indx >> 1] = hcdvar / (vcdvar + hcdvar); + + // end of area interpolation + + } + } + } + + + //populate G at R/B sites + for (int rr = 8; rr < rr1 - 8; rr++) + for (int indx = rr * ts + 8 + (fc(cfarray, rr, 2) & 1); indx < rr * ts + cc1 - 8; indx += 2) { + + //first ask if one gets more directional discrimination from nearby B/R sites + float hvwtalt = xdivf(hvwt[(indx - m1) >> 1] + hvwt[(indx + p1) >> 1] + hvwt[(indx - p1) >> 1] + hvwt[(indx + m1) >> 1], 2); + + hvwt[indx >> 1] = fabsf(0.5f - hvwt[indx >> 1]) < fabsf(0.5f - hvwtalt) ? hvwtalt : hvwt[indx >> 1]; + //a better result was obtained from the neighbours + + Dgrb[0][indx >> 1] = intp(hvwt[indx >> 1], vcd[indx], hcd[indx]); //evaluate colour differences + + rgbgreen[indx] = cfa[indx] + Dgrb[0][indx >> 1]; //evaluate G (finally!) + + //local curvature in G (preparation for nyquist refinement step) + Dgrb2[indx >> 1].h = nyquist2[indx >> 1] ? SQR(rgbgreen[indx] - xdiv2f(rgbgreen[indx - 1] + rgbgreen[indx + 1])) : 0.f; + Dgrb2[indx >> 1].v = nyquist2[indx >> 1] ? SQR(rgbgreen[indx] - xdiv2f(rgbgreen[indx - v1] + rgbgreen[indx + v1])) : 0.f; + } + + + //end of standard interpolation + + // refine Nyquist areas using G curvatures + if(doNyquist) { + for (int rr = nystartrow; rr < nyendrow; rr++) + for (int indx = rr * ts + nystartcol + (fc(cfarray, rr, 2) & 1); indx < rr * ts + nyendcol; indx += 2) { + + if (nyquist2[indx >> 1]) { + //local averages (over Nyquist pixels only) of G curvature squared + float gvarh = epssq + (gquinc[0] * Dgrb2[indx >> 1].h + + gquinc[1] * (Dgrb2[(indx - m1) >> 1].h + Dgrb2[(indx + p1) >> 1].h + Dgrb2[(indx - p1) >> 1].h + Dgrb2[(indx + m1) >> 1].h) + + gquinc[2] * (Dgrb2[(indx - v2) >> 1].h + Dgrb2[(indx - 2) >> 1].h + Dgrb2[(indx + 2) >> 1].h + Dgrb2[(indx + v2) >> 1].h) + + gquinc[3] * (Dgrb2[(indx - m2) >> 1].h + Dgrb2[(indx + p2) >> 1].h + Dgrb2[(indx - p2) >> 1].h + Dgrb2[(indx + m2) >> 1].h)); + float gvarv = epssq + (gquinc[0] * Dgrb2[indx >> 1].v + + gquinc[1] * (Dgrb2[(indx - m1) >> 1].v + Dgrb2[(indx + p1) >> 1].v + Dgrb2[(indx - p1) >> 1].v + Dgrb2[(indx + m1) >> 1].v) + + gquinc[2] * (Dgrb2[(indx - v2) >> 1].v + Dgrb2[(indx - 2) >> 1].v + Dgrb2[(indx + 2) >> 1].v + Dgrb2[(indx + v2) >> 1].v) + + gquinc[3] * (Dgrb2[(indx - m2) >> 1].v + Dgrb2[(indx + p2) >> 1].v + Dgrb2[(indx - p2) >> 1].v + Dgrb2[(indx + m2) >> 1].v)); + //use the results as weights for refined G interpolation + Dgrb[0][indx >> 1] = (hcd[indx] * gvarv + vcd[indx] * gvarh) / (gvarv + gvarh); + rgbgreen[indx] = cfa[indx] + Dgrb[0][indx >> 1]; + } + } + } + + +#ifdef __SSE2__ + + for (int rr = 6; rr < rr1 - 6; rr++) { + if((fc(cfarray, rr, 2) & 1) == 0) { + for (int cc = 6, indx = rr * ts + cc; cc < cc1 - 6; cc += 8, indx += 8) { + vfloat tempv = LC2VFU(cfa[indx + 1]); + vfloat Dgrbsq1pv = (SQRV(tempv - LC2VFU(cfa[indx + 1 - p1])) + SQRV(tempv - LC2VFU(cfa[indx + 1 + p1]))); + STVFU(delp[indx >> 1], vabsf(LC2VFU(cfa[indx + p1]) - LC2VFU(cfa[indx - p1]))); + STVFU(delm[indx >> 1], vabsf(LC2VFU(cfa[indx + m1]) - LC2VFU(cfa[indx - m1]))); + vfloat Dgrbsq1mv = (SQRV(tempv - LC2VFU(cfa[indx + 1 - m1])) + SQRV(tempv - LC2VFU(cfa[indx + 1 + m1]))); + STVFU(Dgrbsq1m[indx >> 1], Dgrbsq1mv ); + STVFU(Dgrbsq1p[indx >> 1], Dgrbsq1pv ); + } + } else { + for (int cc = 6, indx = rr * ts + cc; cc < cc1 - 6; cc += 8, indx += 8) { + vfloat tempv = LC2VFU(cfa[indx]); + vfloat Dgrbsq1pv = (SQRV(tempv - LC2VFU(cfa[indx - p1])) + SQRV(tempv - LC2VFU(cfa[indx + p1]))); + STVFU(delp[indx >> 1], vabsf(LC2VFU(cfa[indx + 1 + p1]) - LC2VFU(cfa[indx + 1 - p1]))); + STVFU(delm[indx >> 1], vabsf(LC2VFU(cfa[indx + 1 + m1]) - LC2VFU(cfa[indx + 1 - m1]))); + vfloat Dgrbsq1mv = (SQRV(tempv - LC2VFU(cfa[indx - m1])) + SQRV(tempv - LC2VFU(cfa[indx + m1]))); + STVFU(Dgrbsq1m[indx >> 1], Dgrbsq1mv ); + STVFU(Dgrbsq1p[indx >> 1], Dgrbsq1pv ); + } + } + } + +#else + + for (int rr = 6; rr < rr1 - 6; rr++) { + if((fc(cfarray, rr, 2) & 1) == 0) { + for (int cc = 6, indx = rr * ts + cc; cc < cc1 - 6; cc += 2, indx += 2) { + delp[indx >> 1] = fabsf(cfa[indx + p1] - cfa[indx - p1]); + delm[indx >> 1] = fabsf(cfa[indx + m1] - cfa[indx - m1]); + Dgrbsq1p[indx >> 1] = (SQR(cfa[indx + 1] - cfa[indx + 1 - p1]) + SQR(cfa[indx + 1] - cfa[indx + 1 + p1])); + Dgrbsq1m[indx >> 1] = (SQR(cfa[indx + 1] - cfa[indx + 1 - m1]) + SQR(cfa[indx + 1] - cfa[indx + 1 + m1])); + } + } else { + for (int cc = 6, indx = rr * ts + cc; cc < cc1 - 6; cc += 2, indx += 2) { + Dgrbsq1p[indx >> 1] = (SQR(cfa[indx] - cfa[indx - p1]) + SQR(cfa[indx] - cfa[indx + p1])); + Dgrbsq1m[indx >> 1] = (SQR(cfa[indx] - cfa[indx - m1]) + SQR(cfa[indx] - cfa[indx + m1])); + delp[indx >> 1] = fabsf(cfa[indx + 1 + p1] - cfa[indx + 1 - p1]); + delm[indx >> 1] = fabsf(cfa[indx + 1 + m1] - cfa[indx + 1 - m1]); + } + } + } + +#endif + + // diagonal interpolation correction + +#ifdef __SSE2__ + vfloat gausseven0v = F2V(gausseven[0]); + vfloat gausseven1v = F2V(gausseven[1]); +#endif + + for (int rr = 8; rr < rr1 - 8; rr++) { +#ifdef __SSE2__ + + for (int indx = rr * ts + 8 + (fc(cfarray, rr, 2) & 1), indx1 = indx >> 1; indx < rr * ts + cc1 - 8; indx += 8, indx1 += 4) { + + //diagonal colour ratios + vfloat cfav = LC2VFU(cfa[indx]); + + vfloat temp1v = LC2VFU(cfa[indx + m1]); + vfloat temp2v = LC2VFU(cfa[indx + m2]); + vfloat rbsev = vmul2f(temp1v) / (epsv + cfav + temp2v ); + rbsev = vself(vmaskf_lt(vabsf(onev - rbsev), arthreshv), cfav * rbsev, temp1v + zd5v * (cfav - temp2v)); + + temp1v = LC2VFU(cfa[indx - m1]); + temp2v = LC2VFU(cfa[indx - m2]); + vfloat rbnwv = vmul2f(temp1v) / (epsv + cfav + temp2v ); + rbnwv = vself(vmaskf_lt(vabsf(onev - rbnwv), arthreshv), cfav * rbnwv, temp1v + zd5v * (cfav - temp2v)); + + temp1v = epsv + LVFU(delm[indx1]); + vfloat wtsev = temp1v + LVFU(delm[(indx + m1) >> 1]) + LVFU(delm[(indx + m2) >> 1]); //same as for wtu,wtd,wtl,wtr + vfloat wtnwv = temp1v + LVFU(delm[(indx - m1) >> 1]) + LVFU(delm[(indx - m2) >> 1]); + + vfloat rbmv = (wtsev * rbnwv + wtnwv * rbsev) / (wtsev + wtnwv); + + temp1v = median(rbmv , LC2VFU(cfa[indx - m1]), LC2VFU(cfa[indx + m1])); + vfloat wtv = vmul2f(cfav - rbmv) / (epsv + rbmv + cfav); + temp2v = vintpf(wtv, rbmv, temp1v); + + temp2v = vself(vmaskf_lt(rbmv + rbmv, cfav), temp1v, temp2v); + temp2v = vself(vmaskf_lt(rbmv, cfav), temp2v, rbmv); + STVFU(rbm[indx1], vself(vmaskf_gt(temp2v, clip_ptv), median(temp2v , LC2VFU(cfa[indx - m1]), LC2VFU(cfa[indx + m1])), temp2v )); + + + temp1v = LC2VFU(cfa[indx + p1]); + temp2v = LC2VFU(cfa[indx + p2]); + vfloat rbnev = vmul2f(temp1v) / (epsv + cfav + temp2v ); + rbnev = vself(vmaskf_lt(vabsf(onev - rbnev), arthreshv), cfav * rbnev, temp1v + zd5v * (cfav - temp2v)); + + temp1v = LC2VFU(cfa[indx - p1]); + temp2v = LC2VFU(cfa[indx - p2]); + vfloat rbswv = vmul2f(temp1v) / (epsv + cfav + temp2v ); + rbswv = vself(vmaskf_lt(vabsf(onev - rbswv), arthreshv), cfav * rbswv, temp1v + zd5v * (cfav - temp2v)); + + temp1v = epsv + LVFU(delp[indx1]); + vfloat wtnev = temp1v + LVFU(delp[(indx + p1) >> 1]) + LVFU(delp[(indx + p2) >> 1]); + vfloat wtswv = temp1v + LVFU(delp[(indx - p1) >> 1]) + LVFU(delp[(indx - p2) >> 1]); + + vfloat rbpv = (wtnev * rbswv + wtswv * rbnev) / (wtnev + wtswv); + + temp1v = median(rbpv , LC2VFU(cfa[indx - p1]), LC2VFU(cfa[indx + p1])); + wtv = vmul2f(cfav - rbpv) / (epsv + rbpv + cfav); + temp2v = vintpf(wtv, rbpv, temp1v); + + temp2v = vself(vmaskf_lt(rbpv + rbpv, cfav), temp1v, temp2v); + temp2v = vself(vmaskf_lt(rbpv, cfav), temp2v, rbpv); + STVFU(rbp[indx1], vself(vmaskf_gt(temp2v, clip_ptv), median(temp2v , LC2VFU(cfa[indx - p1]), LC2VFU(cfa[indx + p1])), temp2v )); + + vfloat rbvarmv = epssqv + (gausseven0v * (LVFU(Dgrbsq1m[(indx - v1) >> 1]) + LVFU(Dgrbsq1m[(indx - 1) >> 1]) + LVFU(Dgrbsq1m[(indx + 1) >> 1]) + LVFU(Dgrbsq1m[(indx + v1) >> 1])) + + gausseven1v * (LVFU(Dgrbsq1m[(indx - v2 - 1) >> 1]) + LVFU(Dgrbsq1m[(indx - v2 + 1) >> 1]) + LVFU(Dgrbsq1m[(indx - 2 - v1) >> 1]) + LVFU(Dgrbsq1m[(indx + 2 - v1) >> 1]) + + LVFU(Dgrbsq1m[(indx - 2 + v1) >> 1]) + LVFU(Dgrbsq1m[(indx + 2 + v1) >> 1]) + LVFU(Dgrbsq1m[(indx + v2 - 1) >> 1]) + LVFU(Dgrbsq1m[(indx + v2 + 1) >> 1]))); + STVFU(pmwt[indx1] , rbvarmv / ((epssqv + (gausseven0v * (LVFU(Dgrbsq1p[(indx - v1) >> 1]) + LVFU(Dgrbsq1p[(indx - 1) >> 1]) + LVFU(Dgrbsq1p[(indx + 1) >> 1]) + LVFU(Dgrbsq1p[(indx + v1) >> 1])) + + gausseven1v * (LVFU(Dgrbsq1p[(indx - v2 - 1) >> 1]) + LVFU(Dgrbsq1p[(indx - v2 + 1) >> 1]) + LVFU(Dgrbsq1p[(indx - 2 - v1) >> 1]) + LVFU(Dgrbsq1p[(indx + 2 - v1) >> 1]) + + LVFU(Dgrbsq1p[(indx - 2 + v1) >> 1]) + LVFU(Dgrbsq1p[(indx + 2 + v1) >> 1]) + LVFU(Dgrbsq1p[(indx + v2 - 1) >> 1]) + LVFU(Dgrbsq1p[(indx + v2 + 1) >> 1])))) + rbvarmv)); + + } + +#else + + for (int cc = 8 + (fc(cfarray, rr, 2) & 1), indx = rr * ts + cc, indx1 = indx >> 1; cc < cc1 - 8; cc += 2, indx += 2, indx1++) { + + //diagonal colour ratios + float crse = xmul2f(cfa[indx + m1]) / (eps + cfa[indx] + (cfa[indx + m2])); + float crnw = xmul2f(cfa[indx - m1]) / (eps + cfa[indx] + (cfa[indx - m2])); + float crne = xmul2f(cfa[indx + p1]) / (eps + cfa[indx] + (cfa[indx + p2])); + float crsw = xmul2f(cfa[indx - p1]) / (eps + cfa[indx] + (cfa[indx - p2])); + //colour differences in diagonal directions + float rbse, rbnw, rbne, rbsw; + + //assign B/R at R/B sites + if (fabsf(1.f - crse) < arthresh) { + rbse = cfa[indx] * crse; //use this if more precise diag interp is necessary + } else { + rbse = (cfa[indx + m1]) + xdiv2f(cfa[indx] - cfa[indx + m2]); + } + + if (fabsf(1.f - crnw) < arthresh) { + rbnw = cfa[indx] * crnw; + } else { + rbnw = (cfa[indx - m1]) + xdiv2f(cfa[indx] - cfa[indx - m2]); + } + + if (fabsf(1.f - crne) < arthresh) { + rbne = cfa[indx] * crne; + } else { + rbne = (cfa[indx + p1]) + xdiv2f(cfa[indx] - cfa[indx + p2]); + } + + if (fabsf(1.f - crsw) < arthresh) { + rbsw = cfa[indx] * crsw; + } else { + rbsw = (cfa[indx - p1]) + xdiv2f(cfa[indx] - cfa[indx - p2]); + } + + float wtse = eps + delm[indx1] + delm[(indx + m1) >> 1] + delm[(indx + m2) >> 1]; //same as for wtu,wtd,wtl,wtr + float wtnw = eps + delm[indx1] + delm[(indx - m1) >> 1] + delm[(indx - m2) >> 1]; + float wtne = eps + delp[indx1] + delp[(indx + p1) >> 1] + delp[(indx + p2) >> 1]; + float wtsw = eps + delp[indx1] + delp[(indx - p1) >> 1] + delp[(indx - p2) >> 1]; + + + rbm[indx1] = (wtse * rbnw + wtnw * rbse) / (wtse + wtnw); + rbp[indx1] = (wtne * rbsw + wtsw * rbne) / (wtne + wtsw); + + //variance of R-B in plus/minus directions + float rbvarm = epssq + (gausseven[0] * (Dgrbsq1m[(indx - v1) >> 1] + Dgrbsq1m[(indx - 1) >> 1] + Dgrbsq1m[(indx + 1) >> 1] + Dgrbsq1m[(indx + v1) >> 1]) + + gausseven[1] * (Dgrbsq1m[(indx - v2 - 1) >> 1] + Dgrbsq1m[(indx - v2 + 1) >> 1] + Dgrbsq1m[(indx - 2 - v1) >> 1] + Dgrbsq1m[(indx + 2 - v1) >> 1] + + Dgrbsq1m[(indx - 2 + v1) >> 1] + Dgrbsq1m[(indx + 2 + v1) >> 1] + Dgrbsq1m[(indx + v2 - 1) >> 1] + Dgrbsq1m[(indx + v2 + 1) >> 1])); + pmwt[indx1] = rbvarm / ((epssq + (gausseven[0] * (Dgrbsq1p[(indx - v1) >> 1] + Dgrbsq1p[(indx - 1) >> 1] + Dgrbsq1p[(indx + 1) >> 1] + Dgrbsq1p[(indx + v1) >> 1]) + + gausseven[1] * (Dgrbsq1p[(indx - v2 - 1) >> 1] + Dgrbsq1p[(indx - v2 + 1) >> 1] + Dgrbsq1p[(indx - 2 - v1) >> 1] + Dgrbsq1p[(indx + 2 - v1) >> 1] + + Dgrbsq1p[(indx - 2 + v1) >> 1] + Dgrbsq1p[(indx + 2 + v1) >> 1] + Dgrbsq1p[(indx + v2 - 1) >> 1] + Dgrbsq1p[(indx + v2 + 1) >> 1]))) + rbvarm); + + //bound the interpolation in regions of high saturation + + if (rbp[indx1] < cfa[indx]) { + if (xmul2f(rbp[indx1]) < cfa[indx]) { + rbp[indx1] = median(rbp[indx1] , cfa[indx - p1], cfa[indx + p1]); + } else { + float pwt = xmul2f(cfa[indx] - rbp[indx1]) / (eps + rbp[indx1] + cfa[indx]); + rbp[indx1] = pwt * rbp[indx1] + (1.f - pwt) * median(rbp[indx1], cfa[indx - p1], cfa[indx + p1]); + } + } + + if (rbm[indx1] < cfa[indx]) { + if (xmul2f(rbm[indx1]) < cfa[indx]) { + rbm[indx1] = median(rbm[indx1] , cfa[indx - m1], cfa[indx + m1]); + } else { + float mwt = xmul2f(cfa[indx] - rbm[indx1]) / (eps + rbm[indx1] + cfa[indx]); + rbm[indx1] = mwt * rbm[indx1] + (1.f - mwt) * median(rbm[indx1], cfa[indx - m1], cfa[indx + m1]); + } + } + + if (rbp[indx1] > clip_pt) { + rbp[indx1] = median(rbp[indx1], cfa[indx - p1], cfa[indx + p1]); + } + + if (rbm[indx1] > clip_pt) { + rbm[indx1] = median(rbm[indx1], cfa[indx - m1], cfa[indx + m1]); + } + } + +#endif + } + +#ifdef __SSE2__ + vfloat zd25v = F2V(0.25f); +#endif + + for (int rr = 10; rr < rr1 - 10; rr++) +#ifdef __SSE2__ + for (int indx = rr * ts + 10 + (fc(cfarray, rr, 2) & 1), indx1 = indx >> 1; indx < rr * ts + cc1 - 10; indx += 8, indx1 += 4) { + + //first ask if one gets more directional discrimination from nearby B/R sites + vfloat pmwtaltv = zd25v * (LVFU(pmwt[(indx - m1) >> 1]) + LVFU(pmwt[(indx + p1) >> 1]) + LVFU(pmwt[(indx - p1) >> 1]) + LVFU(pmwt[(indx + m1) >> 1])); + vfloat tempv = LVFU(pmwt[indx1]); + tempv = vself(vmaskf_lt(vabsf(zd5v - tempv), vabsf(zd5v - pmwtaltv)), pmwtaltv, tempv); + STVFU(pmwt[indx1], tempv); + STVFU(rbint[indx1], zd5v * (LC2VFU(cfa[indx]) + vintpf(tempv, LVFU(rbp[indx1]), LVFU(rbm[indx1])))); + } + +#else + + for (int cc = 10 + (fc(cfarray, rr, 2) & 1), indx = rr * ts + cc, indx1 = indx >> 1; cc < cc1 - 10; cc += 2, indx += 2, indx1++) { + + //first ask if one gets more directional discrimination from nearby B/R sites + float pmwtalt = xdivf(pmwt[(indx - m1) >> 1] + pmwt[(indx + p1) >> 1] + pmwt[(indx - p1) >> 1] + pmwt[(indx + m1) >> 1], 2); + + if (fabsf(0.5f - pmwt[indx1]) < fabsf(0.5f - pmwtalt)) { + pmwt[indx1] = pmwtalt; //a better result was obtained from the neighbours + } + + rbint[indx1] = xdiv2f(cfa[indx] + rbm[indx1] * (1.f - pmwt[indx1]) + rbp[indx1] * pmwt[indx1]); //this is R+B, interpolated + } + +#endif + + for (int rr = 12; rr < rr1 - 12; rr++) +#ifdef __SSE2__ + for (int indx = rr * ts + 12 + (fc(cfarray, rr, 2) & 1), indx1 = indx >> 1; indx < rr * ts + cc1 - 12; indx += 8, indx1 += 4) { + vmask copymask = vmaskf_ge(vabsf(zd5v - LVFU(pmwt[indx1])), vabsf(zd5v - LVFU(hvwt[indx1]))); + + if(_mm_movemask_ps((vfloat)copymask)) { // if for any of the 4 pixels the condition is true, do the maths for all 4 pixels and mask the unused out at the end + //now interpolate G vertically/horizontally using R+B values + //unfortunately, since G interpolation cannot be done diagonally this may lead to colour shifts + //colour ratios for G interpolation + vfloat rbintv = LVFU(rbint[indx1]); + + //interpolated G via adaptive ratios or Hamilton-Adams in each cardinal direction + vfloat cruv = vmul2f(LC2VFU(cfa[indx - v1])) / (epsv + rbintv + LVFU(rbint[(indx1 - v1)])); + vfloat guv = rbintv * cruv; + vfloat gu2v = LC2VFU(cfa[indx - v1]) + zd5v * (rbintv - LVFU(rbint[(indx1 - v1)])); + guv = vself(vmaskf_lt(vabsf(onev - cruv), arthreshv), guv, gu2v); + + vfloat crdv = vmul2f(LC2VFU(cfa[indx + v1])) / (epsv + rbintv + LVFU(rbint[(indx1 + v1)])); + vfloat gdv = rbintv * crdv; + vfloat gd2v = LC2VFU(cfa[indx + v1]) + zd5v * (rbintv - LVFU(rbint[(indx1 + v1)])); + gdv = vself(vmaskf_lt(vabsf(onev - crdv), arthreshv), gdv, gd2v); + + vfloat Gintvv = (LC2VFU(dirwts0[indx - v1]) * gdv + LC2VFU(dirwts0[indx + v1]) * guv) / (LC2VFU(dirwts0[indx + v1]) + LC2VFU(dirwts0[indx - v1])); + vfloat Gint1v = median(Gintvv , LC2VFU(cfa[indx - v1]), LC2VFU(cfa[indx + v1])); + vfloat vwtv = vmul2f(rbintv - Gintvv) / (epsv + Gintvv + rbintv); + vfloat Gint2v = vintpf(vwtv, Gintvv, Gint1v); + Gint1v = vself(vmaskf_lt(vmul2f(Gintvv), rbintv), Gint1v, Gint2v); + Gintvv = vself(vmaskf_lt(Gintvv, rbintv), Gint1v, Gintvv); + Gintvv = vself(vmaskf_gt(Gintvv, clip_ptv), median(Gintvv, LC2VFU(cfa[indx - v1]), LC2VFU(cfa[indx + v1])), Gintvv); + + vfloat crlv = vmul2f(LC2VFU(cfa[indx - 1])) / (epsv + rbintv + LVFU(rbint[(indx1 - 1)])); + vfloat glv = rbintv * crlv; + vfloat gl2v = LC2VFU(cfa[indx - 1]) + zd5v * (rbintv - LVFU(rbint[(indx1 - 1)])); + glv = vself(vmaskf_lt(vabsf(onev - crlv), arthreshv), glv, gl2v); + + vfloat crrv = vmul2f(LC2VFU(cfa[indx + 1])) / (epsv + rbintv + LVFU(rbint[(indx1 + 1)])); + vfloat grv = rbintv * crrv; + vfloat gr2v = LC2VFU(cfa[indx + 1]) + zd5v * (rbintv - LVFU(rbint[(indx1 + 1)])); + grv = vself(vmaskf_lt(vabsf(onev - crrv), arthreshv), grv, gr2v); + + vfloat Ginthv = (LC2VFU(dirwts1[indx - 1]) * grv + LC2VFU(dirwts1[indx + 1]) * glv) / (LC2VFU(dirwts1[indx - 1]) + LC2VFU(dirwts1[indx + 1])); + vfloat Gint1h = median(Ginthv , LC2VFU(cfa[indx - 1]), LC2VFU(cfa[indx + 1])); + vfloat hwtv = vmul2f(rbintv - Ginthv) / (epsv + Ginthv + rbintv); + vfloat Gint2h = vintpf(hwtv, Ginthv, Gint1h); + Gint1h = vself(vmaskf_lt(vmul2f(Ginthv), rbintv), Gint1h, Gint2h); + Ginthv = vself(vmaskf_lt(Ginthv, rbintv), Gint1h, Ginthv); + Ginthv = vself(vmaskf_gt(Ginthv, clip_ptv), median(Ginthv, LC2VFU(cfa[indx - 1]), LC2VFU(cfa[indx + 1])), Ginthv); + + vfloat greenv = vself(copymask, vintpf(LVFU(hvwt[indx1]), Gintvv, Ginthv), LC2VFU(rgbgreen[indx])); + STC2VFU(rgbgreen[indx], greenv); + + STVFU(Dgrb[0][indx1], vself(copymask, greenv - LC2VFU(cfa[indx]), LVFU(Dgrb[0][indx1]))); + } + } + +#else + + for (int cc = 12 + (fc(cfarray, rr, 2) & 1), indx = rr * ts + cc, indx1 = indx >> 1; cc < cc1 - 12; cc += 2, indx += 2, indx1++) { + + if (fabsf(0.5f - pmwt[indx >> 1]) < fabsf(0.5f - hvwt[indx >> 1]) ) { + continue; + } + + //now interpolate G vertically/horizontally using R+B values + //unfortunately, since G interpolation cannot be done diagonally this may lead to colour shifts + + //colour ratios for G interpolation + float cru = cfa[indx - v1] * 2.0 / (eps + rbint[indx1] + rbint[(indx1 - v1)]); + float crd = cfa[indx + v1] * 2.0 / (eps + rbint[indx1] + rbint[(indx1 + v1)]); + float crl = cfa[indx - 1] * 2.0 / (eps + rbint[indx1] + rbint[(indx1 - 1)]); + float crr = cfa[indx + 1] * 2.0 / (eps + rbint[indx1] + rbint[(indx1 + 1)]); + + //interpolation of G in four directions + float gu, gd, gl, gr; + + //interpolated G via adaptive ratios or Hamilton-Adams in each cardinal direction + if (fabsf(1.f - cru) < arthresh) { + gu = rbint[indx1] * cru; + } else { + gu = cfa[indx - v1] + xdiv2f(rbint[indx1] - rbint[(indx1 - v1)]); + } + + if (fabsf(1.f - crd) < arthresh) { + gd = rbint[indx1] * crd; + } else { + gd = cfa[indx + v1] + xdiv2f(rbint[indx1] - rbint[(indx1 + v1)]); + } + + if (fabsf(1.f - crl) < arthresh) { + gl = rbint[indx1] * crl; + } else { + gl = cfa[indx - 1] + xdiv2f(rbint[indx1] - rbint[(indx1 - 1)]); + } + + if (fabsf(1.f - crr) < arthresh) { + gr = rbint[indx1] * crr; + } else { + gr = cfa[indx + 1] + xdiv2f(rbint[indx1] - rbint[(indx1 + 1)]); + } + + //interpolated G via adaptive weights of cardinal evaluations + float Gintv = (dirwts0[indx - v1] * gd + dirwts0[indx + v1] * gu) / (dirwts0[indx + v1] + dirwts0[indx - v1]); + float Ginth = (dirwts1[indx - 1] * gr + dirwts1[indx + 1] * gl) / (dirwts1[indx - 1] + dirwts1[indx + 1]); + + //bound the interpolation in regions of high saturation + if (Gintv < rbint[indx1]) { + if (2 * Gintv < rbint[indx1]) { + Gintv = median(Gintv , cfa[indx - v1], cfa[indx + v1]); + } else { + float vwt = 2.0 * (rbint[indx1] - Gintv) / (eps + Gintv + rbint[indx1]); + Gintv = vwt * Gintv + (1.f - vwt) * median(Gintv, cfa[indx - v1], cfa[indx + v1]); + } + } + + if (Ginth < rbint[indx1]) { + if (2 * Ginth < rbint[indx1]) { + Ginth = median(Ginth , cfa[indx - 1], cfa[indx + 1]); + } else { + float hwt = 2.0 * (rbint[indx1] - Ginth) / (eps + Ginth + rbint[indx1]); + Ginth = hwt * Ginth + (1.f - hwt) * median(Ginth, cfa[indx - 1], cfa[indx + 1]); + } + } + + if (Ginth > clip_pt) { + Ginth = median(Ginth, cfa[indx - 1], cfa[indx + 1]); + } + + if (Gintv > clip_pt) { + Gintv = median(Gintv, cfa[indx - v1], cfa[indx + v1]); + } + + rgbgreen[indx] = Ginth * (1.f - hvwt[indx1]) + Gintv * hvwt[indx1]; + Dgrb[0][indx >> 1] = rgbgreen[indx] - cfa[indx]; + } + +#endif + + //end of diagonal interpolation correction + + //fancy chrominance interpolation + //(ey,ex) is location of R site + for (int rr = 13 - ey; rr < rr1 - 12; rr += 2) + for (int indx1 = (rr * ts + 13 - ex) >> 1; indx1 < (rr * ts + cc1 - 12) >> 1; indx1++) { //B coset + Dgrb[1][indx1] = Dgrb[0][indx1]; //split out G-B from G-R + Dgrb[0][indx1] = 0; + } + +#ifdef __SSE2__ + vfloat oned325v = F2V( 1.325f ); + vfloat zd175v = F2V( 0.175f ); + vfloat zd075v = F2V( 0.075f ); +#endif + + for (int rr = 14; rr < rr1 - 14; rr++) +#ifdef __SSE2__ + for (int cc = 14 + (fc(cfarray, rr, 2) & 1), indx = rr * ts + cc, c = 1 - fc(cfarray, rr, cc) / 2; cc < cc1 - 14; cc += 8, indx += 8) { + vfloat tempv = epsv + vabsf(LVFU(Dgrb[c][(indx - m1) >> 1]) - LVFU(Dgrb[c][(indx + m1) >> 1])); + vfloat temp2v = epsv + vabsf(LVFU(Dgrb[c][(indx + p1) >> 1]) - LVFU(Dgrb[c][(indx - p1) >> 1])); + vfloat wtnwv = onev / (tempv + vabsf(LVFU(Dgrb[c][(indx - m1) >> 1]) - LVFU(Dgrb[c][(indx - m3) >> 1])) + vabsf(LVFU(Dgrb[c][(indx + m1) >> 1]) - LVFU(Dgrb[c][(indx - m3) >> 1]))); + vfloat wtnev = onev / (temp2v + vabsf(LVFU(Dgrb[c][(indx + p1) >> 1]) - LVFU(Dgrb[c][(indx + p3) >> 1])) + vabsf(LVFU(Dgrb[c][(indx - p1) >> 1]) - LVFU(Dgrb[c][(indx + p3) >> 1]))); + vfloat wtswv = onev / (temp2v + vabsf(LVFU(Dgrb[c][(indx - p1) >> 1]) - LVFU(Dgrb[c][(indx + m3) >> 1])) + vabsf(LVFU(Dgrb[c][(indx + p1) >> 1]) - LVFU(Dgrb[c][(indx - p3) >> 1]))); + vfloat wtsev = onev / (tempv + vabsf(LVFU(Dgrb[c][(indx + m1) >> 1]) - LVFU(Dgrb[c][(indx - p3) >> 1])) + vabsf(LVFU(Dgrb[c][(indx - m1) >> 1]) - LVFU(Dgrb[c][(indx + m3) >> 1]))); + + STVFU(Dgrb[c][indx >> 1], (wtnwv * (oned325v * LVFU(Dgrb[c][(indx - m1) >> 1]) - zd175v * LVFU(Dgrb[c][(indx - m3) >> 1]) - zd075v * (LVFU(Dgrb[c][(indx - m1 - 2) >> 1]) + LVFU(Dgrb[c][(indx - m1 - v2) >> 1])) ) + + wtnev * (oned325v * LVFU(Dgrb[c][(indx + p1) >> 1]) - zd175v * LVFU(Dgrb[c][(indx + p3) >> 1]) - zd075v * (LVFU(Dgrb[c][(indx + p1 + 2) >> 1]) + LVFU(Dgrb[c][(indx + p1 + v2) >> 1])) ) + + wtswv * (oned325v * LVFU(Dgrb[c][(indx - p1) >> 1]) - zd175v * LVFU(Dgrb[c][(indx - p3) >> 1]) - zd075v * (LVFU(Dgrb[c][(indx - p1 - 2) >> 1]) + LVFU(Dgrb[c][(indx - p1 - v2) >> 1])) ) + + wtsev * (oned325v * LVFU(Dgrb[c][(indx + m1) >> 1]) - zd175v * LVFU(Dgrb[c][(indx + m3) >> 1]) - zd075v * (LVFU(Dgrb[c][(indx + m1 + 2) >> 1]) + LVFU(Dgrb[c][(indx + m1 + v2) >> 1])) )) / (wtnwv + wtnev + wtswv + wtsev)); + } + +#else + + for (int cc = 14 + (fc(cfarray, rr, 2) & 1), indx = rr * ts + cc, c = 1 - fc(cfarray, rr, cc) / 2; cc < cc1 - 14; cc += 2, indx += 2) { + float wtnw = 1.f / (eps + fabsf(Dgrb[c][(indx - m1) >> 1] - Dgrb[c][(indx + m1) >> 1]) + fabsf(Dgrb[c][(indx - m1) >> 1] - Dgrb[c][(indx - m3) >> 1]) + fabsf(Dgrb[c][(indx + m1) >> 1] - Dgrb[c][(indx - m3) >> 1])); + float wtne = 1.f / (eps + fabsf(Dgrb[c][(indx + p1) >> 1] - Dgrb[c][(indx - p1) >> 1]) + fabsf(Dgrb[c][(indx + p1) >> 1] - Dgrb[c][(indx + p3) >> 1]) + fabsf(Dgrb[c][(indx - p1) >> 1] - Dgrb[c][(indx + p3) >> 1])); + float wtsw = 1.f / (eps + fabsf(Dgrb[c][(indx - p1) >> 1] - Dgrb[c][(indx + p1) >> 1]) + fabsf(Dgrb[c][(indx - p1) >> 1] - Dgrb[c][(indx + m3) >> 1]) + fabsf(Dgrb[c][(indx + p1) >> 1] - Dgrb[c][(indx - p3) >> 1])); + float wtse = 1.f / (eps + fabsf(Dgrb[c][(indx + m1) >> 1] - Dgrb[c][(indx - m1) >> 1]) + fabsf(Dgrb[c][(indx + m1) >> 1] - Dgrb[c][(indx - p3) >> 1]) + fabsf(Dgrb[c][(indx - m1) >> 1] - Dgrb[c][(indx + m3) >> 1])); + + Dgrb[c][indx >> 1] = (wtnw * (1.325f * Dgrb[c][(indx - m1) >> 1] - 0.175f * Dgrb[c][(indx - m3) >> 1] - 0.075f * Dgrb[c][(indx - m1 - 2) >> 1] - 0.075f * Dgrb[c][(indx - m1 - v2) >> 1] ) + + wtne * (1.325f * Dgrb[c][(indx + p1) >> 1] - 0.175f * Dgrb[c][(indx + p3) >> 1] - 0.075f * Dgrb[c][(indx + p1 + 2) >> 1] - 0.075f * Dgrb[c][(indx + p1 + v2) >> 1] ) + + wtsw * (1.325f * Dgrb[c][(indx - p1) >> 1] - 0.175f * Dgrb[c][(indx - p3) >> 1] - 0.075f * Dgrb[c][(indx - p1 - 2) >> 1] - 0.075f * Dgrb[c][(indx - p1 - v2) >> 1] ) + + wtse * (1.325f * Dgrb[c][(indx + m1) >> 1] - 0.175f * Dgrb[c][(indx + m3) >> 1] - 0.075f * Dgrb[c][(indx + m1 + 2) >> 1] - 0.075f * Dgrb[c][(indx + m1 + v2) >> 1] )) / (wtnw + wtne + wtsw + wtse); + } + +#endif + +#ifdef __SSE2__ + int offset; + vfloat twov = F2V(2.f); + vmask selmask; + + if((fc(cfarray, 16, 2) & 1) == 1) { + selmask = _mm_set_epi32(0xffffffff, 0, 0xffffffff, 0); + offset = 1; + } else { + selmask = _mm_set_epi32(0, 0xffffffff, 0, 0xffffffff); + offset = 0; + } + +#endif + + for (int rr = 16; rr < rr1 - 16; rr++) { + int row = rr + top; + int col = left + 16; + int indx = rr * ts + 16; +#ifdef __SSE2__ + offset = 1 - offset; + selmask = vnotm(selmask); + + for (; indx < rr * ts + cc1 - 18 - (cc1 & 1); indx += 4, col += 4) { + vfloat greenv = LVF(rgbgreen[indx]); + vfloat temp00v = vdup(LVFU(hvwt[(indx - v1) >> 1])); + vfloat temp01v = vdup(LVFU(hvwt[(indx + v1) >> 1])); + vfloat tempv = onev / (temp00v + twov - vdup(LVFU(hvwt[(indx + 1 + offset) >> 1])) - vdup(LVFU(hvwt[(indx - 1 + offset) >> 1])) + temp01v); + + vfloat redv1 = greenv - (temp00v * vdup(LVFU(Dgrb[0][(indx - v1) >> 1])) + (onev - vdup(LVFU(hvwt[(indx + 1 + offset) >> 1]))) * vdup(LVFU(Dgrb[0][(indx + 1 + offset) >> 1])) + (onev - vdup(LVFU(hvwt[(indx - 1 + offset) >> 1]))) * vdup(LVFU(Dgrb[0][(indx - 1 + offset) >> 1])) + temp01v * vdup(LVFU(Dgrb[0][(indx + v1) >> 1]))) * tempv; + vfloat bluev1 = greenv - (temp00v * vdup(LVFU(Dgrb[1][(indx - v1) >> 1])) + (onev - vdup(LVFU(hvwt[(indx + 1 + offset) >> 1]))) * vdup(LVFU(Dgrb[1][(indx + 1 + offset) >> 1])) + (onev - vdup(LVFU(hvwt[(indx - 1 + offset) >> 1]))) * vdup(LVFU(Dgrb[1][(indx - 1 + offset) >> 1])) + temp01v * vdup(LVFU(Dgrb[1][(indx + v1) >> 1]))) * tempv; + vfloat redv2 = greenv - vdup(LVFU(Dgrb[0][indx >> 1])); + vfloat bluev2 = greenv - vdup(LVFU(Dgrb[1][indx >> 1])); + STVFU(red[row][col], vmaxf(c65535v * vself(selmask, redv1, redv2), ZEROV)); + STVFU(blue[row][col], vmaxf(c65535v * vself(selmask, bluev1, bluev2), ZEROV)); + } + + if(offset == 0) { + for (; indx < rr * ts + cc1 - 16 - (cc1 & 1); indx++, col++) { + float temp = 1.f / (hvwt[(indx - v1) >> 1] + 2.f - hvwt[(indx + 1) >> 1] - hvwt[(indx - 1) >> 1] + hvwt[(indx + v1) >> 1]); + red[row][col] = std::max(0.f, 65535.f * (rgbgreen[indx] - ((hvwt[(indx - v1) >> 1]) * Dgrb[0][(indx - v1) >> 1] + (1.f - hvwt[(indx + 1) >> 1]) * Dgrb[0][(indx + 1) >> 1] + (1.f - hvwt[(indx - 1) >> 1]) * Dgrb[0][(indx - 1) >> 1] + (hvwt[(indx + v1) >> 1]) * Dgrb[0][(indx + v1) >> 1]) * + temp)); + blue[row][col] = std::max(0.f, 65535.f * (rgbgreen[indx] - ((hvwt[(indx - v1) >> 1]) * Dgrb[1][(indx - v1) >> 1] + (1.f - hvwt[(indx + 1) >> 1]) * Dgrb[1][(indx + 1) >> 1] + (1.f - hvwt[(indx - 1) >> 1]) * Dgrb[1][(indx - 1) >> 1] + (hvwt[(indx + v1) >> 1]) * Dgrb[1][(indx + v1) >> 1]) * + temp)); + + indx++; + col++; + red[row][col] = std::max(0.f, 65535.f * (rgbgreen[indx] - Dgrb[0][indx >> 1])); + blue[row][col] = std::max(0.f, 65535.f * (rgbgreen[indx] - Dgrb[1][indx >> 1])); + } + + if(cc1 & 1) { // width of tile is odd + float temp = 1.f / (hvwt[(indx - v1) >> 1] + 2.f - hvwt[(indx + 1) >> 1] - hvwt[(indx - 1) >> 1] + hvwt[(indx + v1) >> 1]); + red[row][col] = std::max(0.f, 65535.f * (rgbgreen[indx] - ((hvwt[(indx - v1) >> 1]) * Dgrb[0][(indx - v1) >> 1] + (1.f - hvwt[(indx + 1) >> 1]) * Dgrb[0][(indx + 1) >> 1] + (1.f - hvwt[(indx - 1) >> 1]) * Dgrb[0][(indx - 1) >> 1] + (hvwt[(indx + v1) >> 1]) * Dgrb[0][(indx + v1) >> 1]) * + temp)); + blue[row][col] = std::max(0.f, 65535.f * (rgbgreen[indx] - ((hvwt[(indx - v1) >> 1]) * Dgrb[1][(indx - v1) >> 1] + (1.f - hvwt[(indx + 1) >> 1]) * Dgrb[1][(indx + 1) >> 1] + (1.f - hvwt[(indx - 1) >> 1]) * Dgrb[1][(indx - 1) >> 1] + (hvwt[(indx + v1) >> 1]) * Dgrb[1][(indx + v1) >> 1]) * + temp)); + } + } else { + for (; indx < rr * ts + cc1 - 16 - (cc1 & 1); indx++, col++) { + red[row][col] = std::max(0.f, 65535.f * (rgbgreen[indx] - Dgrb[0][indx >> 1])); + blue[row][col] = std::max(0.f, 65535.f * (rgbgreen[indx] - Dgrb[1][indx >> 1])); + + indx++; + col++; + float temp = 1.f / (hvwt[(indx - v1) >> 1] + 2.f - hvwt[(indx + 1) >> 1] - hvwt[(indx - 1) >> 1] + hvwt[(indx + v1) >> 1]); + red[row][col] = std::max(0.f, 65535.f * (rgbgreen[indx] - ((hvwt[(indx - v1) >> 1]) * Dgrb[0][(indx - v1) >> 1] + (1.f - hvwt[(indx + 1) >> 1]) * Dgrb[0][(indx + 1) >> 1] + (1.f - hvwt[(indx - 1) >> 1]) * Dgrb[0][(indx - 1) >> 1] + (hvwt[(indx + v1) >> 1]) * Dgrb[0][(indx + v1) >> 1]) * + temp)); + blue[row][col] = std::max(0.f, 65535.f * (rgbgreen[indx] - ((hvwt[(indx - v1) >> 1]) * Dgrb[1][(indx - v1) >> 1] + (1.f - hvwt[(indx + 1) >> 1]) * Dgrb[1][(indx + 1) >> 1] + (1.f - hvwt[(indx - 1) >> 1]) * Dgrb[1][(indx - 1) >> 1] + (hvwt[(indx + v1) >> 1]) * Dgrb[1][(indx + v1) >> 1]) * + temp)); + } + + if(cc1 & 1) { // width of tile is odd + red[row][col] = std::max(0.f, 65535.f * (rgbgreen[indx] - Dgrb[0][indx >> 1])); + blue[row][col] = std::max(0.f, 65535.f * (rgbgreen[indx] - Dgrb[1][indx >> 1])); + } + } + +#else + + if((fc(cfarray, rr, 2) & 1) == 1) { + for (; indx < rr * ts + cc1 - 16 - (cc1 & 1); indx++, col++) { + float temp = 1.f / (hvwt[(indx - v1) >> 1] + 2.f - hvwt[(indx + 1) >> 1] - hvwt[(indx - 1) >> 1] + hvwt[(indx + v1) >> 1]); + red[row][col] = std::max(0.f, 65535.f * (rgbgreen[indx] - ((hvwt[(indx - v1) >> 1]) * Dgrb[0][(indx - v1) >> 1] + (1.f - hvwt[(indx + 1) >> 1]) * Dgrb[0][(indx + 1) >> 1] + (1.f - hvwt[(indx - 1) >> 1]) * Dgrb[0][(indx - 1) >> 1] + (hvwt[(indx + v1) >> 1]) * Dgrb[0][(indx + v1) >> 1]) * + temp)); + blue[row][col] = std::max(0.f, 65535.f * (rgbgreen[indx] - ((hvwt[(indx - v1) >> 1]) * Dgrb[1][(indx - v1) >> 1] + (1.f - hvwt[(indx + 1) >> 1]) * Dgrb[1][(indx + 1) >> 1] + (1.f - hvwt[(indx - 1) >> 1]) * Dgrb[1][(indx - 1) >> 1] + (hvwt[(indx + v1) >> 1]) * Dgrb[1][(indx + v1) >> 1]) * + temp)); + + indx++; + col++; + red[row][col] = std::max(0.f, 65535.f * (rgbgreen[indx] - Dgrb[0][indx >> 1])); + blue[row][col] = std::max(0.f, 65535.f * (rgbgreen[indx] - Dgrb[1][indx >> 1])); + } + + if(cc1 & 1) { // width of tile is odd + float temp = 1.f / (hvwt[(indx - v1) >> 1] + 2.f - hvwt[(indx + 1) >> 1] - hvwt[(indx - 1) >> 1] + hvwt[(indx + v1) >> 1]); + red[row][col] = std::max(0.f, 65535.f * (rgbgreen[indx] - ((hvwt[(indx - v1) >> 1]) * Dgrb[0][(indx - v1) >> 1] + (1.f - hvwt[(indx + 1) >> 1]) * Dgrb[0][(indx + 1) >> 1] + (1.f - hvwt[(indx - 1) >> 1]) * Dgrb[0][(indx - 1) >> 1] + (hvwt[(indx + v1) >> 1]) * Dgrb[0][(indx + v1) >> 1]) * + temp)); + blue[row][col] = std::max(0.f, 65535.f * (rgbgreen[indx] - ((hvwt[(indx - v1) >> 1]) * Dgrb[1][(indx - v1) >> 1] + (1.f - hvwt[(indx + 1) >> 1]) * Dgrb[1][(indx + 1) >> 1] + (1.f - hvwt[(indx - 1) >> 1]) * Dgrb[1][(indx - 1) >> 1] + (hvwt[(indx + v1) >> 1]) * Dgrb[1][(indx + v1) >> 1]) * + temp)); + } + } else { + for (; indx < rr * ts + cc1 - 16 - (cc1 & 1); indx++, col++) { + red[row][col] = std::max(0.f, 65535.f * (rgbgreen[indx] - Dgrb[0][indx >> 1])); + blue[row][col] = std::max(0.f, 65535.f * (rgbgreen[indx] - Dgrb[1][indx >> 1])); + + indx++; + col++; + float temp = 1.f / (hvwt[(indx - v1) >> 1] + 2.f - hvwt[(indx + 1) >> 1] - hvwt[(indx - 1) >> 1] + hvwt[(indx + v1) >> 1]); + red[row][col] = std::max(0.f, 65535.f * (rgbgreen[indx] - ((hvwt[(indx - v1) >> 1]) * Dgrb[0][(indx - v1) >> 1] + (1.f - hvwt[(indx + 1) >> 1]) * Dgrb[0][(indx + 1) >> 1] + (1.f - hvwt[(indx - 1) >> 1]) * Dgrb[0][(indx - 1) >> 1] + (hvwt[(indx + v1) >> 1]) * Dgrb[0][(indx + v1) >> 1]) * + temp)); + blue[row][col] = std::max(0.f, 65535.f * (rgbgreen[indx] - ((hvwt[(indx - v1) >> 1]) * Dgrb[1][(indx - v1) >> 1] + (1.f - hvwt[(indx + 1) >> 1]) * Dgrb[1][(indx + 1) >> 1] + (1.f - hvwt[(indx - 1) >> 1]) * Dgrb[1][(indx - 1) >> 1] + (hvwt[(indx + v1) >> 1]) * Dgrb[1][(indx + v1) >> 1]) * + temp)); + } + + if(cc1 & 1) { // width of tile is odd + red[row][col] = std::max(0.f, 65535.f * (rgbgreen[indx] - Dgrb[0][indx >> 1])); + blue[row][col] = std::max(0.f, 65535.f * (rgbgreen[indx] - Dgrb[1][indx >> 1])); + } + } + +#endif + } + + // copy smoothed results back to image matrix + for (int rr = 16; rr < rr1 - 16; rr++) { + int row = rr + top; + int cc = 16; +#ifdef __SSE2__ + + for (; cc < cc1 - 19; cc += 4) { + STVFU(green[row][cc + left], vmaxf(LVF(rgbgreen[rr * ts + cc]) * c65535v, ZEROV)); + } + +#endif + + for (; cc < cc1 - 16; cc++) { + green[row][cc + left] = std::max(0.f, 65535.f * rgbgreen[rr * ts + cc]); + } + } + + } + } //end of main loop + + // clean up + free(buffer); + } + + for (int row = 0; row < fullHeight; ++row) { + for (int col = 0; col < fullWidth; ++col) { + ushort* pix = image[row * fullWidth + col]; + pix[0] = toUshort(red[row][col]); + pix[1] = pix[3] = toUshort(green[row][col]); + pix[2] = toUshort(blue[row][col]); + } + } + + border_interpolate(16); + RUN_CALLBACK(LIBRAW_PROGRESS_INTERPOLATE, 1, 1); +} diff --git a/app/src/main/cpp/LibRaw/src/postprocessing/dcraw_process.cpp b/app/src/main/cpp/LibRaw/src/postprocessing/dcraw_process.cpp index 2f60dd95..aea9aff1 100644 --- a/app/src/main/cpp/LibRaw/src/postprocessing/dcraw_process.cpp +++ b/app/src/main/cpp/LibRaw/src/postprocessing/dcraw_process.cpp @@ -185,6 +185,8 @@ int LibRaw::dcraw_process(void) aahd_interpolate(); else if (quality == 13) lmmse_interpolate(0); + else if (quality == 14) + amaze_interpolate(); // fallback to AHD else { diff --git a/app/src/main/cpp/native-lib.cpp b/app/src/main/cpp/native-lib.cpp index d7561592..eae0077b 100644 --- a/app/src/main/cpp/native-lib.cpp +++ b/app/src/main/cpp/native-lib.cpp @@ -30,6 +30,210 @@ #define LOGE(...) __android_log_print(ANDROID_LOG_ERROR, LOG_TAG, __VA_ARGS__) #endif +static jbyteArray encodeBitmapThumbnailToJpeg(JNIEnv *env, + const libraw_processed_image_t *thumb, + int quality = 90) { + if (!thumb || !thumb->data || thumb->width <= 0 || thumb->height <= 0) { + return nullptr; + } + + if (thumb->colors != 1 && thumb->colors != 3) { + LOGI("encodeBitmapThumbnailToJpeg: unsupported colors=%d", thumb->colors); + return nullptr; + } + + const int pixelFormat = thumb->colors == 3 ? TJPF_RGB : TJPF_GRAY; + const int rowStride = thumb->width * thumb->colors; + std::vector converted; + const unsigned char *src = thumb->data; + + if (thumb->bits == 16) { + converted.resize(static_cast(rowStride) * thumb->height); + const auto *src16 = reinterpret_cast(thumb->data); + const size_t sampleCount = + static_cast(thumb->width) * thumb->height * thumb->colors; + for (size_t i = 0; i < sampleCount; ++i) { + converted[i] = static_cast(src16[i] >> 8); + } + src = converted.data(); + } else if (thumb->bits != 8) { + LOGI("encodeBitmapThumbnailToJpeg: unsupported bits=%d", thumb->bits); + return nullptr; + } + + tjhandle handle = tjInitCompress(); + if (!handle) { + LOGE("encodeBitmapThumbnailToJpeg: tjInitCompress failed: %s", + tjGetErrorStr()); + return nullptr; + } + + unsigned char *jpegBuf = nullptr; + unsigned long jpegSize = 0; + const int ret = + tjCompress2(handle, src, thumb->width, rowStride, thumb->height, + pixelFormat, &jpegBuf, &jpegSize, TJSAMP_420, quality, + TJFLAG_NOREALLOC | TJFLAG_FASTDCT); + if (ret != 0 || !jpegBuf || jpegSize == 0) { + LOGE("encodeBitmapThumbnailToJpeg: tjCompress2 failed: %s", + tjGetErrorStr()); + if (jpegBuf) { + tjFree(jpegBuf); + } + tjDestroy(handle); + return nullptr; + } + + jbyteArray result = env->NewByteArray(static_cast(jpegSize)); + env->SetByteArrayRegion(result, 0, static_cast(jpegSize), + reinterpret_cast(jpegBuf)); + tjFree(jpegBuf); + tjDestroy(handle); + return result; +} + +static jobject createArgb8888Bitmap(JNIEnv *env, int width, int height) { + jclass bitmapClass = env->FindClass("android/graphics/Bitmap"); + jclass configClass = env->FindClass("android/graphics/Bitmap$Config"); + jfieldID argb8888Field = + env->GetStaticFieldID(configClass, "ARGB_8888", + "Landroid/graphics/Bitmap$Config;"); + jobject argb8888 = env->GetStaticObjectField(configClass, argb8888Field); + jmethodID createBitmapMethod = + env->GetStaticMethodID(bitmapClass, "createBitmap", + "(IILandroid/graphics/Bitmap$Config;)Landroid/graphics/Bitmap;"); + return env->CallStaticObjectMethod(bitmapClass, createBitmapMethod, width, + height, argb8888); +} + +static jobject createBitmapFromRgba(JNIEnv *env, int width, int height, + const unsigned char *rgbaData, + int strideBytes) { + if (!rgbaData || width <= 0 || height <= 0) { + return nullptr; + } + + jobject bitmap = createArgb8888Bitmap(env, width, height); + if (!bitmap) { + LOGE("createBitmapFromRgba: failed to allocate Bitmap %dx%d", width, + height); + return nullptr; + } + + void *pixels = nullptr; + if (AndroidBitmap_lockPixels(env, bitmap, &pixels) != ANDROID_BITMAP_RESULT_SUCCESS || + !pixels) { + LOGE("createBitmapFromRgba: failed to lock pixels"); + return nullptr; + } + + AndroidBitmapInfo info; + if (AndroidBitmap_getInfo(env, bitmap, &info) != ANDROID_BITMAP_RESULT_SUCCESS) { + AndroidBitmap_unlockPixels(env, bitmap); + LOGE("createBitmapFromRgba: failed to query bitmap info"); + return nullptr; + } + + const auto *src = rgbaData; + auto *dst = reinterpret_cast(pixels); + for (int y = 0; y < height; ++y) { + std::memcpy(dst + y * info.stride, src + y * strideBytes, + static_cast(width) * 4); + } + + AndroidBitmap_unlockPixels(env, bitmap); + return bitmap; +} + +static jobject decodeJpegPreviewToBitmap(JNIEnv *env, const unsigned char *jpegData, + unsigned long jpegSize) { + if (!jpegData || jpegSize == 0) { + return nullptr; + } + + tjhandle handle = tjInitDecompress(); + if (!handle) { + LOGE("decodeJpegPreviewToBitmap: tjInitDecompress failed: %s", + tjGetErrorStr()); + return nullptr; + } + + int width = 0; + int height = 0; + int subsamp = 0; + auto *mutableJpegData = const_cast(jpegData); + if (tjDecompressHeader2(handle, mutableJpegData, jpegSize, &width, &height, + &subsamp) != 0) { + LOGE("decodeJpegPreviewToBitmap: header decode failed: %s", + tjGetErrorStr()); + tjDestroy(handle); + return nullptr; + } + + std::vector rgba(static_cast(width) * height * 4); + if (tjDecompress2(handle, mutableJpegData, jpegSize, rgba.data(), width, width * 4, + height, TJPF_RGBA, TJFLAG_FASTUPSAMPLE | + TJFLAG_FASTDCT) != 0) { + LOGE("decodeJpegPreviewToBitmap: jpeg decode failed: %s", tjGetErrorStr()); + tjDestroy(handle); + return nullptr; + } + + tjDestroy(handle); + return createBitmapFromRgba(env, width, height, rgba.data(), width * 4); +} + +static jobject convertBitmapThumbnailToBitmap(JNIEnv *env, + const libraw_processed_image_t *thumb) { + if (!thumb || !thumb->data || thumb->width <= 0 || thumb->height <= 0) { + return nullptr; + } + + if (thumb->colors != 1 && thumb->colors != 3) { + LOGI("convertBitmapThumbnailToBitmap: unsupported colors=%d", thumb->colors); + return nullptr; + } + + const size_t pixelCount = static_cast(thumb->width) * thumb->height; + std::vector rgba(pixelCount * 4); + + if (thumb->bits == 8) { + for (size_t i = 0; i < pixelCount; ++i) { + const size_t srcIndex = i * thumb->colors; + const unsigned char r = thumb->colors == 3 ? thumb->data[srcIndex] : thumb->data[i]; + const unsigned char g = thumb->colors == 3 ? thumb->data[srcIndex + 1] : thumb->data[i]; + const unsigned char b = thumb->colors == 3 ? thumb->data[srcIndex + 2] : thumb->data[i]; + const size_t dstIndex = i * 4; + rgba[dstIndex] = r; + rgba[dstIndex + 1] = g; + rgba[dstIndex + 2] = b; + rgba[dstIndex + 3] = 255; + } + } else if (thumb->bits == 16) { + const auto *src16 = reinterpret_cast(thumb->data); + for (size_t i = 0; i < pixelCount; ++i) { + const size_t srcIndex = i * thumb->colors; + const unsigned char r = + static_cast((thumb->colors == 3 ? src16[srcIndex] : src16[i]) >> 8); + const unsigned char g = static_cast( + (thumb->colors == 3 ? src16[srcIndex + 1] : src16[i]) >> 8); + const unsigned char b = static_cast( + (thumb->colors == 3 ? src16[srcIndex + 2] : src16[i]) >> 8); + const size_t dstIndex = i * 4; + rgba[dstIndex] = r; + rgba[dstIndex + 1] = g; + rgba[dstIndex + 2] = b; + rgba[dstIndex + 3] = 255; + } + } else { + LOGI("convertBitmapThumbnailToBitmap: unsupported bits=%d", thumb->bits); + return nullptr; + } + + return createBitmapFromRgba(env, thumb->width, thumb->height, rgba.data(), + thumb->width * 4); +} + struct Matrix3x3 { float m[9]; @@ -1181,6 +1385,39 @@ Java_com_hinnka_mycamera_raw_RawDemosaicProcessor_processDngNative( return nullptr; } + jobject embeddedPreviewBitmap = nullptr; + ret = RawProcessor.unpack_thumb(); + if (ret == LIBRAW_SUCCESS) { + libraw_processed_image_t *thumb = RawProcessor.dcraw_make_mem_thumb(&ret); + if (thumb && ret == LIBRAW_SUCCESS) { + if (thumb->type == LIBRAW_IMAGE_JPEG && thumb->data && + thumb->data_size > 0) { + embeddedPreviewBitmap = + decodeJpegPreviewToBitmap(env, thumb->data, thumb->data_size); + LOGI("processDngNative: extracted embedded JPEG preview (%d bytes)", + (int)thumb->data_size); + } else if (thumb->type == LIBRAW_IMAGE_BITMAP) { + embeddedPreviewBitmap = convertBitmapThumbnailToBitmap(env, thumb); + if (embeddedPreviewBitmap) { + LOGI("processDngNative: converted embedded bitmap preview %dx%d c=%d b=%d", + thumb->width, thumb->height, thumb->colors, thumb->bits); + } else { + LOGI("processDngNative: failed to convert embedded bitmap preview %dx%d c=%d b=%d", + thumb->width, thumb->height, thumb->colors, thumb->bits); + } + } else { + LOGI("processDngNative: embedded preview present but unsupported type=%d", + thumb->type); + } + LibRaw::dcraw_clear_mem(thumb); + } else { + LOGI("processDngNative: dcraw_make_mem_thumb failed ret=%d", ret); + } + } else { + LOGI("processDngNative: unpack_thumb failed ret=%d err=%s", ret, + libraw_strerror(ret)); + } + // 配置处理参数 RawProcessor.imgdata.params.output_bps = 16; RawProcessor.imgdata.params.gamm[0] = 1.0; // Linear @@ -1188,7 +1425,7 @@ Java_com_hinnka_mycamera_raw_RawDemosaicProcessor_processDngNative( RawProcessor.imgdata.params.no_auto_bright = 1; RawProcessor.imgdata.params.use_camera_wb = 1; RawProcessor.imgdata.params.output_color = 0; // Raw color space - RawProcessor.imgdata.params.user_qual = 12; + RawProcessor.imgdata.params.user_qual = 14; RawProcessor.imgdata.params.fbdd_noiserd = 0; RawProcessor.imgdata.params.threshold = 0; RawProcessor.imgdata.params.med_passes = 0; @@ -1218,7 +1455,7 @@ Java_com_hinnka_mycamera_raw_RawDemosaicProcessor_processDngNative( jclass dngDataClass = env->FindClass("com/hinnka/mycamera/raw/DngRawData"); jmethodID constructor = env->GetMethodID(dngDataClass, "", - "(Ljava/nio/ByteBuffer;IIIF[F[F[FIIF[FIIFIJF[I[F)V"); + "(Ljava/nio/ByteBuffer;IIIF[F[F[F[FIIF[FIIFIJF[I[FLandroid/graphics/Bitmap;)V"); jfloatArray blackLevelArray = env->NewFloatArray(4); for (int i = 0; i < 4; i++) { @@ -1227,6 +1464,14 @@ Java_com_hinnka_mycamera_raw_RawDemosaicProcessor_processDngNative( env->SetFloatArrayRegion(blackLevelArray, i, 1, &val); } + jfloatArray preMulArray = env->NewFloatArray(4); + float preMul[4] = {1.0f, 1.0f, 1.0f, 1.0f}; + for (int i = 0; i < 4; i++) { + const float val = RawProcessor.imgdata.color.pre_mul[i]; + preMul[i] = val > 0.0f ? val : 1.0f; + } + env->SetFloatArrayRegion(preMulArray, 0, 4, preMul); + // 白平衡 jfloatArray wbArray = env->NewFloatArray(4); float wb[4] = {1.0f, 1.0f, 1.0f, 1.0f}; @@ -1534,9 +1779,10 @@ Java_com_hinnka_mycamera_raw_RawDemosaicProcessor_processDngNative( jobject dngData = env->NewObject( dngDataClass, constructor, rawDataBuffer, width, height, rowStride, - whiteLevel, blackLevelArray, wbArray, colorMatrixArray, cfaPattern, 0, - baselineExposure, nullptr, 0, 0, exposureBias, iso, shutterSpeedLong, - aperture, activeArray, noiseProfileArray); + whiteLevel, blackLevelArray, preMulArray, wbArray, colorMatrixArray, + cfaPattern, 0, baselineExposure, nullptr, 0, 0, exposureBias, iso, + shutterSpeedLong, aperture, activeArray, noiseProfileArray, + embeddedPreviewBitmap); // 释放资源 LibRaw::dcraw_clear_mem(image); diff --git a/app/src/main/java/com/hinnka/mycamera/gallery/PhotoManager.kt b/app/src/main/java/com/hinnka/mycamera/gallery/PhotoManager.kt index 73f8bef7..3c46dddc 100644 --- a/app/src/main/java/com/hinnka/mycamera/gallery/PhotoManager.kt +++ b/app/src/main/java/com/hinnka/mycamera/gallery/PhotoManager.kt @@ -23,9 +23,9 @@ import com.hinnka.mycamera.hdr.UnifiedGainmapProducer import com.hinnka.mycamera.livephoto.MotionPhotoWriter import com.hinnka.mycamera.model.SafeImage import com.hinnka.mycamera.processor.MultiFrameStacker -import com.hinnka.mycamera.raw.MeteringSystem import com.hinnka.mycamera.raw.RawDemosaicProcessor import com.hinnka.mycamera.raw.RawMetadata +import com.hinnka.mycamera.raw.RawProcessingPreferences import com.hinnka.mycamera.utils.BitmapUtils import com.hinnka.mycamera.utils.PLog import com.hinnka.mycamera.utils.RawProcessor @@ -817,6 +817,7 @@ object PhotoManager { context: Context, photoId: String, image: SafeImage, + thumbnail: Bitmap?, rotation: Int, aspectRatio: AspectRatio, characteristics: CameraCharacteristics, @@ -828,7 +829,7 @@ object PhotoManager { chromaNoiseReductionValue: Float, photoQuality: Int = 95, exposureBias: Float? = null, - droMode: MeteringSystem.DROMode = MeteringSystem.DROMode.OFF + droMode: RawProcessingPreferences.DROMode = RawProcessingPreferences.DROMode.OFF ) = withContext(Dispatchers.IO) { try { val photoDir = getPhotoDir(context, photoId, true) @@ -846,7 +847,14 @@ object PhotoManager { byteOutstream.use { outputStream -> image.use { try { - RawProcessor.saveToDng(image, characteristics, captureResult, outputStream, rotation) + RawProcessor.saveToDng( + image, + characteristics, + captureResult, + outputStream, + rotation, + thumbnail + ) } catch (e: Throwable) { PLog.e(TAG, "DNG save failed", e) } @@ -867,8 +875,7 @@ object PhotoManager { cropRegion = metadata.cropRegion, rotation = rotation, exposureBias = exposureBias ?: 0f, - sharpeningValue = 0.4f, - droMode = droMode + sharpeningValue = 0.4f ) ?: return@withContext var bitmap = rawResult.sdrBitmap @@ -949,6 +956,7 @@ object PhotoManager { context: Context, photoId: String, image: SafeImage, + thumbnail: Bitmap? = null, rotation: Int, aspectRatio: AspectRatio, characteristics: CameraCharacteristics, @@ -960,7 +968,7 @@ object PhotoManager { chromaNoiseReductionValue: Float, photoQuality: Int = 95, exposureBias: Float? = null, - droMode: MeteringSystem.DROMode = MeteringSystem.DROMode.OFF + droMode: RawProcessingPreferences.DROMode = RawProcessingPreferences.DROMode.OFF ) { // 根据图像格式处理 when (val format = image.format) { @@ -985,6 +993,7 @@ object PhotoManager { context, photoId, image, + thumbnail, rotation, aspectRatio, characteristics, @@ -1317,7 +1326,7 @@ object PhotoManager { useSuperResolution: Boolean = false, useGpuAcceleration: Boolean = true, exposureBias: Float? = null, - droMode: MeteringSystem.DROMode = MeteringSystem.DROMode.OFF + droMode: RawProcessingPreferences.DROMode = RawProcessingPreferences.DROMode.OFF ) = withContext(Dispatchers.IO) { try { val photoDir = getPhotoDir(context, photoId, true) @@ -1341,7 +1350,6 @@ object PhotoManager { characteristics, captureResult, exposureBias, - droMode, RawDemosaicProcessor.getInstance().getRawColorSpace() ) @@ -1462,7 +1470,7 @@ object PhotoManager { useSuperResolution: Boolean = false, useGpuAcceleration: Boolean = true, exposureBias: Float? = null, - droMode: MeteringSystem.DROMode = MeteringSystem.DROMode.OFF + droMode: RawProcessingPreferences.DROMode = RawProcessingPreferences.DROMode.OFF ) = withContext(Dispatchers.IO) { when (val format = images[0].format) { ImageFormat.YUV_420_888, ImageFormat.YCBCR_P010, ImageFormat.NV21 -> { @@ -2113,7 +2121,7 @@ object PhotoManager { } } - suspend fun refreshRawPreview(context: Context, photoId: String, droMode: MeteringSystem.DROMode): Bitmap? { + suspend fun refreshRawPreview(context: Context, photoId: String, droMode: RawProcessingPreferences.DROMode): Bitmap? { return withContext(Dispatchers.IO) { try { val photoDir = getPhotoDir(context, photoId, true) @@ -2132,7 +2140,6 @@ object PhotoManager { context, dngFile.absolutePath, metadata?.ratio, metadata?.cropRegion, 0, sharpeningValue = 0.4f, - droMode = metadata?.droMode?.let { MeteringSystem.DROMode.valueOf(it) } ?: droMode, onMetadata = { raw -> updatedMetadata = updatedMetadata?.merge(raw) ?: PhotoMetadata().merge(raw) } diff --git a/app/src/main/java/com/hinnka/mycamera/gallery/PhotoMetadata.kt b/app/src/main/java/com/hinnka/mycamera/gallery/PhotoMetadata.kt index f0941a1e..c099053f 100644 --- a/app/src/main/java/com/hinnka/mycamera/gallery/PhotoMetadata.kt +++ b/app/src/main/java/com/hinnka/mycamera/gallery/PhotoMetadata.kt @@ -278,7 +278,7 @@ data class PhotoMetadata( shutterSpeed = formatShutterSpeed(raw.shutterSpeed).takeIf { it.isNotEmpty() } ?: shutterSpeed, aperture = formatAperture(raw.aperture).takeIf { it.isNotEmpty() } ?: aperture, exposureBias = raw.exposureBias, - droMode = raw.droMode.name, + droMode = null, width = raw.width.takeIf { it > 0 } ?: width, height = raw.height.takeIf { it > 0 } ?: height ) diff --git a/app/src/main/java/com/hinnka/mycamera/gallery/PhotoProcessor.kt b/app/src/main/java/com/hinnka/mycamera/gallery/PhotoProcessor.kt index e022fa14..c8260aaa 100644 --- a/app/src/main/java/com/hinnka/mycamera/gallery/PhotoProcessor.kt +++ b/app/src/main/java/com/hinnka/mycamera/gallery/PhotoProcessor.kt @@ -15,7 +15,6 @@ import com.hinnka.mycamera.hdr.SourceKind import com.hinnka.mycamera.lut.LutImageProcessor import com.hinnka.mycamera.lut.LutManager import com.hinnka.mycamera.processor.DepthBokehProcessor -import com.hinnka.mycamera.raw.MeteringSystem import com.hinnka.mycamera.raw.RawDemosaicProcessor import com.hinnka.mycamera.raw.RawHdrRenderResult import com.hinnka.mycamera.utils.BitmapUtils @@ -321,10 +320,6 @@ class PhotoProcessor( noiseReduction: Float = 0f, chromaNoiseReduction: Float = 0f ): GainmapSourceSet? = withContext(Dispatchers.IO) { - val droMode = metadata.droMode?.let { - runCatching { MeteringSystem.DROMode.valueOf(it) }.getOrDefault(MeteringSystem.DROMode.OFF) - } ?: MeteringSystem.DROMode.OFF - val rawResult = RawDemosaicProcessor.getInstance().processForHdrSources( context = context, dngFilePath = dngPath, @@ -332,8 +327,7 @@ class PhotoProcessor( cropRegion = metadata.cropRegion, rotation = metadata.rotation, exposureBias = metadata.exposureBias ?: 0f, - sharpeningValue = 0.4f, - droMode = droMode + sharpeningValue = 0.4f ) ?: return@withContext null prepareUltraHdrSourceFromRawResult( context = context, diff --git a/app/src/main/java/com/hinnka/mycamera/raw/DefaultToneCurve.kt b/app/src/main/java/com/hinnka/mycamera/raw/DefaultToneCurve.kt new file mode 100644 index 00000000..016d03c5 --- /dev/null +++ b/app/src/main/java/com/hinnka/mycamera/raw/DefaultToneCurve.kt @@ -0,0 +1,108 @@ +package com.hinnka.mycamera.raw + +import com.hinnka.mycamera.utils.PLog +import com.hinnka.mycamera.utils.SplineInterpolator +import java.nio.FloatBuffer +import kotlin.math.roundToInt + +/** + * Percentile-driven fallback tone curve for cases where we do not have an + * embedded preview for histogram matching. The curve stays gentle on both ends + * while lifting mids enough for large-DR scenes to feel less flat. + */ +object DefaultToneCurve { + private const val TAG = "DefaultToneCurve" + private const val LUT_SIZE = 256 + + fun analyze( + neutralBuffer: FloatBuffer, + width: Int, + height: Int, + logCurve: LogCurve + ): FloatArray { + val histogram = buildHistogramFromNeutral(neutralBuffer, width, height, logCurve) + val cdf = buildCdf(histogram) + + val p01 = findPercentile(cdf, 0.01f) + val p50 = findPercentile(cdf, 0.50f) + val p99 = findPercentile(cdf, 0.99f) + val dynamicRange = (p99 - p01).coerceIn(0.18f, 0.98f) + val headroom = (1f - p99).coerceIn(0.02f, 0.35f) + + val midLift = (0.12f - (dynamicRange - 0.55f).coerceAtLeast(0f) * 0.10f) + .coerceIn(0.06f, 0.12f) + val shadowToe = (p01 * 0.38f).coerceIn(0f, 0.08f) + val shoulderPush = (headroom * 0.45f).coerceIn(0.01f, 0.05f) + + val midOut = (p50 + midLift).coerceAtMost((p99 - 0.08f).coerceAtLeast(p50 + 0.03f)) + val highOut = (p99 + shoulderPush).coerceIn(midOut + 0.08f, 0.985f) + + val x = floatArrayOf( + 0f, + (p01 * 0.5f).coerceIn(0f, 0.08f), + p01, + p50, + p99, + 1f + ) + val y = floatArrayOf( + 0f, + logCurve.logToLinear(shadowToe * 0.28f).coerceAtLeast(0f), + logCurve.logToLinear(shadowToe).coerceAtLeast(0f), + logCurve.logToLinear(midOut).coerceAtLeast(0f), + logCurve.logToLinear(highOut).coerceAtLeast(0f), + logCurve.logToLinear(1f).coerceAtLeast(0f) + ) + + PLog.d( + TAG, + "analyze: p01=$p01 p50=$p50 p99=$p99 dr=$dynamicRange headroom=$headroom midOut=$midOut highOut=$highOut" + ) + + return SplineInterpolator(x, y).generateLut(LUT_SIZE) + } + + private fun buildHistogramFromNeutral( + neutralBuffer: FloatBuffer, + width: Int, + height: Int, + logCurve: LogCurve + ): IntArray { + val histogram = IntArray(LUT_SIZE) + neutralBuffer.position(0) + repeat(width * height) { + val r = neutralBuffer.get() + val g = neutralBuffer.get() + val b = neutralBuffer.get() + neutralBuffer.get() + + val luma = (r * 0.2126f + g * 0.7152f + b * 0.0722f).coerceAtLeast(0f) + val logValue = logCurve.linearToLog(luma).coerceIn(0f, 1f) + val bin = (logValue * (LUT_SIZE - 1)).roundToInt().coerceIn(0, LUT_SIZE - 1) + histogram[bin]++ + } + neutralBuffer.position(0) + return histogram + } + + private fun buildCdf(histogram: IntArray): FloatArray { + val total = histogram.sum().coerceAtLeast(1) + val cdf = FloatArray(histogram.size) + var running = 0 + for (i in histogram.indices) { + running += histogram[i] + cdf[i] = running.toFloat() / total + } + return cdf + } + + private fun findPercentile(cdf: FloatArray, percentile: Float): Float { + val target = percentile.coerceIn(0f, 1f) + for (i in cdf.indices) { + if (cdf[i] >= target) { + return i.toFloat() / (cdf.size - 1) + } + } + return 1f + } +} diff --git a/app/src/main/java/com/hinnka/mycamera/raw/DngRawData.kt b/app/src/main/java/com/hinnka/mycamera/raw/DngRawData.kt index 82a46182..ff2d221e 100644 --- a/app/src/main/java/com/hinnka/mycamera/raw/DngRawData.kt +++ b/app/src/main/java/com/hinnka/mycamera/raw/DngRawData.kt @@ -1,5 +1,6 @@ package com.hinnka.mycamera.raw +import android.graphics.Bitmap import androidx.annotation.Keep import java.nio.ByteBuffer @@ -29,6 +30,7 @@ data class DngRawData @Keep constructor( val rowStride: Int, val whiteLevel: Float, val blackLevel: FloatArray, + val preMul: FloatArray, val whiteBalance: FloatArray, val colorMatrix: FloatArray, val cfaPattern: Int, // 0=RGGB, 1=GRBG, 2=GBRG, 3=BGGR @@ -43,6 +45,7 @@ data class DngRawData @Keep constructor( val aperture: Float, val activeArray: IntArray?, // [left, top, right, bottom] val noiseProfile: FloatArray?, // NoiseProfile [S1, O1, S2, O2, ...] + val embeddedPreview: Bitmap? = null, ) : AutoCloseable { @Volatile @@ -82,6 +85,7 @@ data class DngRawData @Keep constructor( if (rowStride != other.rowStride) return false if (whiteLevel != other.whiteLevel) return false if (!blackLevel.contentEquals(other.blackLevel)) return false + if (!preMul.contentEquals(other.preMul)) return false if (!whiteBalance.contentEquals(other.whiteBalance)) return false if (!colorMatrix.contentEquals(other.colorMatrix)) return false if (cfaPattern != other.cfaPattern) return false @@ -93,6 +97,10 @@ data class DngRawData @Keep constructor( } else if (other.lensShadingMap != null) return false if (lensShadingMapWidth != other.lensShadingMapWidth) return false if (lensShadingMapHeight != other.lensShadingMapHeight) return false + if (embeddedPreview != null) { + if (other.embeddedPreview == null) return false + if (!embeddedPreview.sameAs(other.embeddedPreview)) return false + } else if (other.embeddedPreview != null) return false return true } @@ -104,6 +112,7 @@ data class DngRawData @Keep constructor( result = 31 * result + rowStride result = 31 * result + whiteLevel.hashCode() result = 31 * result + blackLevel.contentHashCode() + result = 31 * result + preMul.contentHashCode() result = 31 * result + whiteBalance.contentHashCode() result = 31 * result + colorMatrix.contentHashCode() result = 31 * result + cfaPattern @@ -112,6 +121,7 @@ data class DngRawData @Keep constructor( result = 31 * result + (lensShadingMap?.contentHashCode() ?: 0) result = 31 * result + lensShadingMapWidth result = 31 * result + lensShadingMapHeight + result = 31 * result + (embeddedPreview?.hashCode() ?: 0) return result } diff --git a/app/src/main/java/com/hinnka/mycamera/raw/ExposureNormalization.kt b/app/src/main/java/com/hinnka/mycamera/raw/ExposureNormalization.kt new file mode 100644 index 00000000..3636181b --- /dev/null +++ b/app/src/main/java/com/hinnka/mycamera/raw/ExposureNormalization.kt @@ -0,0 +1,94 @@ +package com.hinnka.mycamera.raw + +import com.hinnka.mycamera.utils.PLog +import kotlin.math.pow + +/** + * RAW-domain exposure normalization inspired by RawTherapee's white-point / + * scale-mul logic. The goal is to keep camera-WB-applied renders from looking + * arbitrarily dark when there is no histogram-matched tone curve available. + */ +object ExposureNormalization { + private const val TAG = "ExposureNormalization" + + fun compute(metadata: RawMetadata): Float { + val whiteLevel = metadata.whiteLevel.coerceAtLeast(1f) + val black = metadata.blackLevel + val preMul = metadata.preMul + val wb = metadata.whiteBalanceGains + + val rtLikeGain = computeRtLikeGain(preMul, whiteLevel, black) + var gain = if (rtLikeGain > 0f) { + rtLikeGain + } else { + computeFallbackGain(wb, whiteLevel, black) + } + + if (metadata.baselineExposure.isFinite() && metadata.baselineExposure != 0f) { + gain *= 2.0f.pow(metadata.baselineExposure) + } + + PLog.d( + TAG, + "compute: gain=$gain preMul=${preMul.joinToString()} wb=${wb.joinToString()} black=${black.joinToString()} white=${metadata.whiteLevel} baseline=${metadata.baselineExposure}" + ) + return gain.coerceIn(1f, 8f) + } + + private fun computeRtLikeGain(preMul: FloatArray, whiteLevel: Float, black: FloatArray): Float { + if (preMul.isEmpty()) { + return 0f + } + + val localPreMul = FloatArray(4) { index -> + when { + index < preMul.size && preMul[index] > 0f -> preMul[index] + index == 3 && preMul.size > 1 && preMul[1] > 0f -> preMul[1] + else -> 1f + } + } + + if (localPreMul[3] <= 0f) { + localPreMul[3] = localPreMul[1] + } + + val maxPreMul = localPreMul.maxOrNull()?.coerceAtLeast(1e-6f) ?: return 0f + var maxScaleMul = 0f + var minScaleMul = Float.MAX_VALUE + + for (i in 0 until 4) { + val channelBlack = black.getOrElse(i) { black.lastOrNull() ?: 0f } + val channelHeadroom = (whiteLevel - channelBlack).coerceAtLeast(1f) + val scaleMul = (localPreMul[i] / maxPreMul) * 65535f / channelHeadroom + maxScaleMul = maxOf(maxScaleMul, scaleMul) + minScaleMul = minOf(minScaleMul, scaleMul) + } + + return if (minScaleMul > 0f && maxScaleMul >= minScaleMul) { + maxScaleMul / minScaleMul + } else { + 0f + } + } + + private fun computeFallbackGain(wb: FloatArray, whiteLevel: Float, black: FloatArray): Float { + var maxWeightedGain = 0f + var validChannels = 0 + + for (i in 0 until minOf(4, black.size, wb.size)) { + val headroom = (whiteLevel - black[i]).coerceAtLeast(1f) + val normalizedHeadroom = headroom / whiteLevel + val weightedGain = wb[i].coerceAtLeast(0f) * normalizedHeadroom + if (weightedGain > 0f) { + maxWeightedGain = maxOf(maxWeightedGain, weightedGain) + validChannels++ + } + } + + return if (validChannels > 0) { + maxWeightedGain.coerceAtLeast(1f) + } else { + 1f + } + } +} diff --git a/app/src/main/java/com/hinnka/mycamera/raw/HistogramMatching.kt b/app/src/main/java/com/hinnka/mycamera/raw/HistogramMatching.kt new file mode 100644 index 00000000..34b1000a --- /dev/null +++ b/app/src/main/java/com/hinnka/mycamera/raw/HistogramMatching.kt @@ -0,0 +1,178 @@ +package com.hinnka.mycamera.raw + +import android.graphics.Bitmap +import com.hinnka.mycamera.utils.PLog +import com.hinnka.mycamera.utils.SplineInterpolator +import java.nio.FloatBuffer +import kotlin.math.abs +import kotlin.math.max +import kotlin.math.pow +import kotlin.math.roundToInt + +/** + * RawTherapee-style histogram matching: + * use an embedded preview/JPEG as source and a neutral RAW rendering as target, + * then build a monotonic tone curve by matching both luminance CDFs. + */ +object HistogramMatching { + private const val TAG = "HistogramMatching" + private const val LUT_SIZE = 256 + private const val MIN_REFERENCE_PIXELS = 19_200 + + data class AnalysisResult( + val curveLut: FloatArray? + ) + + fun analyze( + neutralBuffer: FloatBuffer, + width: Int, + height: Int, + logCurve: LogCurve, + referenceBitmap: Bitmap? + ): AnalysisResult { + if (referenceBitmap == null) { + PLog.d(TAG, "No embedded preview found, using neutral curve") + return AnalysisResult(null) + } + + val reference = prepareReference(referenceBitmap, width, height) ?: run { + PLog.d(TAG, "Embedded preview too small or invalid, using neutral curve") + return AnalysisResult(null) + } + + val targetHistogram = buildHistogramFromNeutral(neutralBuffer, width, height, logCurve) + val sourceHistogram = buildHistogramFromBitmap(reference, logCurve) + val mapping = buildMapping(targetHistogram, sourceHistogram) + val curve = mappingToCurve(mapping, logCurve) + + return AnalysisResult(curve) + } + + private fun prepareReference(bitmap: Bitmap, targetWidth: Int, targetHeight: Int): Bitmap? { + val sourcePixels = bitmap.width * bitmap.height + if (sourcePixels < MIN_REFERENCE_PIXELS) { + return null + } + + val sourceRatio = bitmap.width.toFloat() / max(bitmap.height, 1) + val targetRatio = targetWidth.toFloat() / max(targetHeight, 1) + val ratioDiff = abs(sourceRatio - targetRatio) + + val cropped = if (ratioDiff > 0.01f) { + cropToAspect(bitmap, targetRatio) + } else { + bitmap + } + + val scaledWidth = targetWidth.coerceAtLeast(1) + val scaledHeight = targetHeight.coerceAtLeast(1) + return if (cropped.width != scaledWidth || cropped.height != scaledHeight) { + Bitmap.createScaledBitmap(cropped, scaledWidth, scaledHeight, false) + } else { + cropped + } + } + + private fun cropToAspect(bitmap: Bitmap, targetRatio: Float): Bitmap { + val currentRatio = bitmap.width.toFloat() / max(bitmap.height, 1) + return if (currentRatio > targetRatio) { + val newWidth = (bitmap.height * targetRatio).roundToInt().coerceAtMost(bitmap.width) + val x = ((bitmap.width - newWidth) / 2).coerceAtLeast(0) + Bitmap.createBitmap(bitmap, x, 0, newWidth, bitmap.height) + } else { + val newHeight = (bitmap.width / targetRatio).roundToInt().coerceAtMost(bitmap.height) + val y = ((bitmap.height - newHeight) / 2).coerceAtLeast(0) + Bitmap.createBitmap(bitmap, 0, y, bitmap.width, newHeight) + } + } + + private fun buildHistogramFromNeutral( + neutralBuffer: FloatBuffer, + width: Int, + height: Int, + logCurve: LogCurve + ): IntArray { + val histogram = IntArray(LUT_SIZE) + neutralBuffer.position(0) + repeat(width * height) { + val r = neutralBuffer.get() + val g = neutralBuffer.get() + val b = neutralBuffer.get() + neutralBuffer.get() + + val luma = (r * 0.2126f + g * 0.7152f + b * 0.0722f).coerceAtLeast(0f) + val logValue = logCurve.linearToLog(luma).coerceIn(0f, 1f) + val bin = (logValue * (LUT_SIZE - 1)).roundToInt().coerceIn(0, LUT_SIZE - 1) + histogram[bin]++ + } + neutralBuffer.position(0) + return histogram + } + + private fun buildHistogramFromBitmap(bitmap: Bitmap, logCurve: LogCurve): IntArray { + val histogram = IntArray(LUT_SIZE) + val pixels = IntArray(bitmap.width * bitmap.height) + bitmap.getPixels(pixels, 0, bitmap.width, 0, 0, bitmap.width, bitmap.height) + for (pixel in pixels) { + val r = ((pixel shr 16) and 0xFF) / 255f + val g = ((pixel shr 8) and 0xFF) / 255f + val b = (pixel and 0xFF) / 255f + val linearR = srgbToLinear(r) + val linearG = srgbToLinear(g) + val linearB = srgbToLinear(b) + val luma = linearR * 0.2126f + linearG * 0.7152f + linearB * 0.0722f + val logValue = logCurve.linearToLog(luma).coerceIn(0f, 1f) + val bin = (logValue * (LUT_SIZE - 1)).roundToInt().coerceIn(0, LUT_SIZE - 1) + histogram[bin]++ + } + return histogram + } + + private fun buildMapping(targetHistogram: IntArray, sourceHistogram: IntArray): IntArray { + val targetCdf = buildCdf(targetHistogram) + val sourceCdf = buildCdf(sourceHistogram) + val mapping = IntArray(LUT_SIZE) + var j = 0 + + for (i in 0 until LUT_SIZE) { + val targetValue = targetCdf[i] + while (j < LUT_SIZE - 1 && sourceCdf[j] < targetValue) { + j++ + } + mapping[i] = j + } + return mapping + } + + private fun buildCdf(histogram: IntArray): FloatArray { + val total = histogram.sum().coerceAtLeast(1) + val cdf = FloatArray(histogram.size) + var running = 0 + for (i in histogram.indices) { + running += histogram[i] + cdf[i] = running.toFloat() / total + } + return cdf + } + + private fun mappingToCurve(mapping: IntArray, logCurve: LogCurve): FloatArray { + val x = FloatArray(LUT_SIZE) + val y = FloatArray(LUT_SIZE) + for (i in 0 until LUT_SIZE) { + val input = i.toFloat() / (LUT_SIZE - 1) + val mapped = mapping[i].toFloat() / (LUT_SIZE - 1) + x[i] = input + y[i] = logCurve.logToLinear(mapped).coerceAtLeast(0f) + } + val interpolator = SplineInterpolator(x, y) + return interpolator.generateLut(LUT_SIZE) + } + + private fun srgbToLinear(v: Float): Float { + return if (v <= 0.04045f) { + v / 12.92f + } else { + ((v + 0.055f) / 1.055f).toDouble().pow(2.4).toFloat() + } + } +} diff --git a/app/src/main/java/com/hinnka/mycamera/raw/MeteringSystem.kt b/app/src/main/java/com/hinnka/mycamera/raw/MeteringSystem.kt deleted file mode 100644 index fdd955a3..00000000 --- a/app/src/main/java/com/hinnka/mycamera/raw/MeteringSystem.kt +++ /dev/null @@ -1,307 +0,0 @@ -package com.hinnka.mycamera.raw - -import com.hinnka.mycamera.utils.PLog -import com.hinnka.mycamera.utils.SplineInterpolator -import java.nio.FloatBuffer -import kotlin.math.log10 -import kotlin.math.log2 -import kotlin.math.pow - -/** - * 评价测光与场景分析系统 - */ -object MeteringSystem { - private const val TAG = "MeteringSystem" - - enum class DROMode { - OFF, LOW, HIGH - } - - data class AnalysisResult( - val exposureGain: Float, - val curveLut: FloatArray, - ) { - override fun equals(other: Any?): Boolean { - if (this === other) return true - if (javaClass != other?.javaClass) return false - - other as AnalysisResult - - if (exposureGain != other.exposureGain) return false - if (!curveLut.contentEquals(other.curveLut)) return false - - return true - } - - override fun hashCode(): Int { - var result = exposureGain.hashCode() - result = 31 * result + curveLut.contentHashCode() - return result - } - } - - /** - * 将线性反射率 (Scene Linear Reflection) 转换为 Log (0..1) - */ - private fun linearToLog(reflection: Float, logCurve: LogCurve): Float { - return logCurve.linearToLog(reflection) - } - - /** - * 将 Log (0..1) 还原为线性反射率 - */ - private fun logToLinear(logValue: Float, logCurve: LogCurve): Float { - return logCurve.logToLinear(logValue) - } - - fun analyze( - floatBuffer: FloatBuffer, - width: Int, - height: Int, - focusX: Float, - focusY: Float, - logCurve: LogCurve, - metadata: RawMetadata? - ): AnalysisResult { - val pixelCount = width * height - val allLumas = FloatArray(pixelCount) - var validPixelCount = 0 - - val gridRows = 12 - val gridCols = 12 - val zoneSumLog = DoubleArray(gridRows * gridCols) - val zonePixCount = IntArray(gridRows * gridCols) - val zoneMaxL = FloatArray(gridRows * gridCols) - val zoneSkinCount = IntArray(gridRows * gridCols) - - var maxLuma = 0.0f - - floatBuffer.position(0) - for (y in 0 until height) { - val gy = (y.toFloat() / height * gridRows).toInt().coerceIn(0, gridRows - 1) - for (x in 0 until width) { - val gx = (x.toFloat() / width * gridCols).toInt().coerceIn(0, gridCols - 1) - val zi = gy * gridCols + gx - - val r = floatBuffer.get() - val g = floatBuffer.get() - val b = floatBuffer.get() - floatBuffer.get() // skip alpha - - val luma = r * 0.2126f + g * 0.7152f + b * 0.0722f - if (luma.isNaN() || luma < 0f) continue - - if (luma > maxLuma) maxLuma = luma - allLumas[validPixelCount++] = luma - - val logLuma = linearToLog(luma, logCurve) - zoneSumLog[zi] += logLuma.toDouble() - zonePixCount[zi]++ - if (luma > zoneMaxL[zi]) zoneMaxL[zi] = luma - - // 2. 肤色检测逻辑 - if (r > g && g > b && g > 0.001f) { - val rgRatio = r / g - val gbRatio = g / b - if (rgRatio in 1.1f..2.5f && gbRatio in 1.0f..3.0f) { - zoneSkinCount[zi]++ - } - } - } - } - - if (validPixelCount == 0) { - return AnalysisResult(1.0f, floatArrayOf(0f, 1f)) - } - - // --------------------------------------------------------- - // 区域评价测光算法 (Evaluative Metering Algorithm) - // --------------------------------------------------------- - var totalWeight = 0.0 - var weightedSumLog = 0.0 - - // 计算全局平均亮度,用于逆光检测对比 - var globalTotalLog = 0.0 - var globalTotalPixels = 0 - for (i in 0 until gridRows * gridCols) { - globalTotalLog += zoneSumLog[i] - globalTotalPixels += zonePixCount[i] - } - val globalAvgLog = if (globalTotalPixels > 0) globalTotalLog / globalTotalPixels else 0.0 - - for (i in 0 until gridRows * gridCols) { - if (zonePixCount[i] == 0) continue - - val gy = i / gridCols - val gx = i % gridCols - val pzx = (gx + 0.5f) / gridCols - val pzy = (gy + 0.5f) / gridRows - - val zoneAvgLog = zoneSumLog[i] / zonePixCount[i] - val zoneAvgLuma = logToLinear(zoneAvgLog.toFloat(), logCurve) - - // 1. 基础权重:对焦点 + 画面中心 - val distSqF = (pzx - focusX).let { it * it } + (pzy - focusY).let { it * it } - val distSqC = (pzx - 0.5f).let { it * it } + (pzy - 0.5f).let { it * it } - - // 对焦点权重分布(较窄) - val focusW = kotlin.math.exp(-distSqF / 0.05) - // 中心权重分布(较宽) - val centerW = kotlin.math.exp(-distSqC / 0.2) - - // 混合基础权重,并加入极小底噪权重保证全局参与 - var weight = focusW * 4.0 + centerW * 1.5 + 0.2 - - // 2. 肤色密度补偿 - val skinDensity = zoneSkinCount[i].toDouble() / zonePixCount[i] - if (skinDensity > 0.05) { - weight *= (1.0 + skinDensity * 12.0) - } - - // 3. 高光评价逻辑 (Sky/Highlight handling) - // 如果是非对焦区域且亮度很高,判定为背景/天空,降低权重避免压黑主体 - if (zoneAvgLuma > 0.75f && distSqF > 0.1) { - weight *= 0.15 - } - - // 4. 逆光补偿 (Backlight compensation) - // 如果对焦中心区域明显暗于全局平均,说明可能处于大面积强光背后的阴影中,大幅增加权重以拉亮主体 - if (distSqF < 0.04 && zoneAvgLog < globalAvgLog - 0.05) { - weight *= 3.0 - } - - weightedSumLog += zoneAvgLog * weight - totalWeight += weight - } - - // 计算 Log 空间的加权平均亮度 - val avgLog = (weightedSumLog / totalWeight).toFloat() - - // 映射回线性空间,得到场景的“代表性亮度” - val representativeLinearLuma = logToLinear(avgLog, logCurve) - - val aperture = metadata?.aperture ?: 2f - val shutterSpeed = metadata?.shutterSpeed?.let { it * 1f / 1_000_000_000L } ?: 0.01f - val iso = metadata?.iso?.let { if (it > 0) it else 100 } ?: 100 - val exposureBias = metadata?.exposureBias?.let { if (it > -10 && it < 10) it else 0f } ?: 0f - val biasMultiplier = 2.0f.pow(exposureBias) - - val ev = log2((aperture * aperture) / shutterSpeed) - val lv = (ev - log2(iso / 100f)).coerceAtLeast(0f) - - // 计算 P98 和 P05 用于动态范围分析 - val sortedLumas = allLumas.copyOfRange(0, validPixelCount) - sortedLumas.sort() - val p99Index = (validPixelCount * 0.99f).toInt().coerceIn(0, validPixelCount - 1) - val p99Luma = sortedLumas[p99Index] - val p999Index = (validPixelCount * 0.999f).toInt().coerceIn(0, validPixelCount - 1) - val p999Luma = sortedLumas[p999Index] - val p01Index = (validPixelCount * 0.001f).toInt().coerceIn(0, validPixelCount - 1) - val blackPoint = sortedLumas[p01Index] - - if (p99Luma <= 0.001f || p999Luma <= 0.001f || representativeLinearLuma <= 0.001f) { - return AnalysisResult(1.0f, floatArrayOf(0f, 1f)) - } - - val highlightSpan = p999Luma - p99Luma - val rawHighlightAnchor = if (highlightSpan > 0.2f) { - p999Luma - } else { - p99Luma - } - - // 防止在高光不足时(如曝光保守或低对比度场景)过度提升增益 - // 在明亮场景下(LV较大),我们预期“代表性高光”不应低于某个阈值。 - // 如果 RAW 里的高光远低于该阈值,说明场景本身可能偏暗或曝光非常保守,此时不应强行拉亮。 - val anchorFloor = when { - lv >= 13 -> 0.50f - lv >= 10 -> 0.40f - else -> 0.30f - } - val highlightAnchor = if (lv >= 8) maxOf(rawHighlightAnchor, anchorFloor) else rawHighlightAnchor - - val sceneContrast = highlightAnchor / representativeLinearLuma - var droMode = DROMode.OFF - var drBoost = 0f - - val preferredDROMode = metadata?.droMode ?: DROMode.OFF - - if (lv >= 10.0f) { - if (sceneContrast > 15.0f && preferredDROMode >= DROMode.HIGH) { - droMode = DROMode.HIGH - drBoost = 1.0f // 增加 1.0 EV 曝光 - } else if (sceneContrast > 8.0f && preferredDROMode >= DROMode.LOW) { - droMode = DROMode.LOW - drBoost = 0.5f // 增加 0.5 EV 曝光 - } - } - - // LV -> Luma 拟合函数 - // 1 -> 0.26 - // 4 -> 0.391 - // 8 -> 0.42 - // 13 -> 0.45 - val logCurveForTarget = logCurve - val targetLumaIRE = logCurve.middleGray * (1f + 0.3f * log10(lv / 4)) - var gain = logToLinear(targetLumaIRE, logCurveForTarget) * biasMultiplier / representativeLinearLuma - - gain = gain.coerceAtLeast(1f) - - // 应用 DR 增益补偿 - if (drBoost > 0f) { - gain *= 2.0f.pow(drBoost) - } - - // 7. 绝对剪裁保护 - if (logCurve != LogCurve.SRGB && maxLuma * gain > logCurve.maxLinear) { - gain = logCurve.maxLinear / maxLuma - } - - // 6. 动态生成 S 曲线控制点 - val points = mutableListOf>() - if (blackPoint <= 0.005f) { - points.add(blackPoint to 0f) - } else { - points.add(0f to 0f) - } - points.add(0.015f to 0.005f) - points.add(0.052f to 0.036f) - points.add(0.217f to 0.217f) - points.add(0.531f to 0.579f) - - val maxTarget = maxLuma * gain - if (maxTarget > logCurve.maxLinear) { - points.add(logCurve.maxLinear to logCurve.maxLinear * 0.9f) - points.add(maxTarget to logCurve.maxLinear) - } else { - if (maxTarget > 0.531f) { - points.add(maxTarget to maxTarget) - } - points.add(logCurve.maxLinear to logCurve.maxLinear) - } - - val finalX = mutableListOf() - val finalY = mutableListOf() - - for (i in 0 until points.size) { - finalX.add(linearToLog(points[i].first, logCurve)) - // LUT 存储物理线性目标亮度,配合 Shader 在线性域应用 - finalY.add(points[i].second) - } - - // 生成最终曲线 LUT - val interpolator = SplineInterpolator(finalX.toFloatArray(), finalY.toFloatArray()) - val curveLut = interpolator.generateLut(256) - - PLog.d( - TAG, "Log Analysis: EV=${ev.toInt()}, LV=${lv.toInt()}, DRO=$droMode, Contrast=$sceneContrast, " + - "p99=$p99Luma p999=$p999Luma p001=$blackPoint bias=$biasMultiplier max=$maxLuma gain=$gain points=$finalX,$finalY" - ) - - return AnalysisResult( - exposureGain = gain, - curveLut = curveLut - ) - } - -} diff --git a/app/src/main/java/com/hinnka/mycamera/raw/RawDemosaicProcessor.kt b/app/src/main/java/com/hinnka/mycamera/raw/RawDemosaicProcessor.kt index 0d92a7e0..c2457d76 100644 --- a/app/src/main/java/com/hinnka/mycamera/raw/RawDemosaicProcessor.kt +++ b/app/src/main/java/com/hinnka/mycamera/raw/RawDemosaicProcessor.kt @@ -12,7 +12,6 @@ import com.hinnka.mycamera.lut.LutParser import com.hinnka.mycamera.utils.BitmapUtils import com.hinnka.mycamera.utils.PLog import com.hinnka.mycamera.utils.RawProcessor -import com.hinnka.mycamera.utils.SplineInterpolator import kotlinx.coroutines.asCoroutineDispatcher import kotlinx.coroutines.withContext @@ -53,14 +52,14 @@ class RawDemosaicProcessor { */ private fun convertDngRawDataToMetadata( dngRawData: DngRawData, - exposureBias: Float, - droMode: MeteringSystem.DROMode = MeteringSystem.DROMode.OFF + exposureBias: Float ): RawMetadata { // CFA 模式:使用从 JNI 传递过来的实际值 val cfaPattern = dngRawData.cfaPattern // 黑电平:DngRawData 提供的是 [R, Gr, Gb, B] 四通道 val blackLevel = dngRawData.blackLevel + val preMul = dngRawData.preMul // 白电平 val whiteLevel = dngRawData.whiteLevel @@ -96,6 +95,7 @@ class RawDemosaicProcessor { blackLevel = blackLevel, whiteLevel = whiteLevel, whiteBalanceGains = whiteBalanceGains, + preMul = preMul, colorCorrectionMatrix = colorCorrectionMatrix, lensShadingMap = dngRawData.lensShadingMap, lensShadingMapWidth = dngRawData.lensShadingMapWidth, @@ -106,8 +106,7 @@ class RawDemosaicProcessor { shutterSpeed = dngRawData.shutterSpeed, aperture = dngRawData.aperture, activeArray = activeArray, - noiseProfile = dngRawData.noiseProfile ?: floatArrayOf(0f, 0f), - droMode = droMode + noiseProfile = dngRawData.noiseProfile ?: floatArrayOf(0f, 0f) ) } @@ -316,7 +315,6 @@ class RawDemosaicProcessor { rotation: Int, exposureBias: Float = 0f, sharpeningValue: Float = 0f, - droMode: MeteringSystem.DROMode = MeteringSystem.DROMode.OFF, onMetadata: ((RawMetadata) -> Unit)? = null ): Bitmap? = withContext(glDispatcher) { val dngFile = File(dngFilePath) @@ -333,7 +331,6 @@ class RawDemosaicProcessor { rotation = rotation, exposureBias = exposureBias, sharpeningValue = sharpeningValue, - droMode = droMode, dngFile = dngFile, onMetadata = onMetadata )?.sdrBitmap @@ -392,7 +389,6 @@ class RawDemosaicProcessor { rotation: Int, exposureBias: Float = 0f, sharpeningValue: Float = 0f, - droMode: MeteringSystem.DROMode = MeteringSystem.DROMode.OFF, onMetadata: ((RawMetadata) -> Unit)? = null ): RawHdrRenderResult? = withContext(glDispatcher) { val dngFile = File(dngFilePath) @@ -409,7 +405,6 @@ class RawDemosaicProcessor { rotation = rotation, exposureBias = exposureBias, sharpeningValue = sharpeningValue, - droMode = droMode, dngFile = dngFile, onMetadata = onMetadata, includeHdrReference = true @@ -435,7 +430,6 @@ class RawDemosaicProcessor { rotation: Int, exposureBias: Float = 0f, sharpeningValue: Float = 0f, - droMode: MeteringSystem.DROMode = MeteringSystem.DROMode.OFF, dngFile: File? = null, onMetadata: ((RawMetadata) -> Unit)? = null, includeHdrReference: Boolean = false @@ -470,7 +464,7 @@ class RawDemosaicProcessor { actualWidth = dngRawData.width actualHeight = dngRawData.height actualRowStride = dngRawData.rowStride - actualMetadata = convertDngRawDataToMetadata(dngRawData, exposureBias, droMode) + actualMetadata = convertDngRawDataToMetadata(dngRawData, exposureBias) actualRotation = dngRawData.rotation onMetadata?.invoke(actualMetadata) } @@ -564,10 +558,18 @@ class RawDemosaicProcessor { ) renderLinearPass(actualMetadata) - // 场景分析: 从 GPU demosaic 纹理读回精确的 Linear RGB 数据 - // 计算平均亮度 + // RT-style histogram matching uses the embedded preview as source and + // our neutral RAW render as target. When no preview is available, it + // falls back to a neutral curve. val sceneStats = - analyzeFromGpuTexture(demosaicTextureId, actualWidth, actualHeight, logCurve, actualMetadata) + analyzeFromGpuTexture( + demosaicTextureId, + actualWidth, + actualHeight, + logCurve, + actualMetadata, + dngRawDataCleanup?.embeddedPreview + ) val renderPlan = sceneStats.toRenderPlan() val workingColorSpace = resolveWorkingColorSpace() @@ -1693,7 +1695,8 @@ class RawDemosaicProcessor { width: Int, height: Int, logCurve: LogCurve, - metadata: RawMetadata? = null + metadata: RawMetadata, + referencePreview: Bitmap? = null ): SceneStats { // 1. 生成 mipmap GLES30.glBindTexture(GLES30.GL_TEXTURE_2D, textureId) @@ -1749,42 +1752,24 @@ class RawDemosaicProcessor { GLES30.glTexParameteri(GLES30.GL_TEXTURE_2D, GLES30.GL_TEXTURE_MIN_FILTER, GLES30.GL_LINEAR) GLES30.glBindFramebuffer(GLES30.GL_FRAMEBUFFER, 0) - // Determine focus point in normalized (0..1) coordinates - var focusX = 0.5f - var focusY = 0.5f - - metadata?.let { meta -> - val afRegion = meta.afRegions?.firstOrNull() - val activeArray = meta.activeArray - if (afRegion != null && activeArray != null) { - // Map AF region center to 0..1 based on ACTIVE_ARRAY - focusX = (afRegion.rect.centerX().toFloat() - activeArray.left) / activeArray.width() - focusY = (afRegion.rect.centerY().toFloat() - activeArray.top) / activeArray.height() - - // Clamp to 0..1 - focusX = focusX.coerceIn(0f, 1f) - focusY = focusY.coerceIn(0f, 1f) - - // Adjust for Y-axis inversion (OpenGLES texture has origin at bottom-left) - focusY = 1.0f - focusY - } - } - - // 5. 调用外部测光系统进行分析 - val analysis = MeteringSystem.analyze( - floatBuffer, - mipWidth, - mipHeight, - focusX, - focusY, - logCurve, - metadata + val analysis = HistogramMatching.analyze( + neutralBuffer = floatBuffer, + width = mipWidth, + height = mipHeight, + logCurve = logCurve, + referenceBitmap = referencePreview ) - return SceneStats(analysis.exposureGain, analysis.curveLut) + val normalizationGain = ExposureNormalization.compute(metadata) + val curveLut = analysis.curveLut ?: DefaultToneCurve.analyze( + neutralBuffer = floatBuffer, + width = mipWidth, + height = mipHeight, + logCurve = logCurve + ) + return SceneStats(normalizationGain, curveLut) } - // 辅助函数: 3x3 矩阵转置 (行主序 -> 列主序) private fun transposeMatrix3x3(matrix: FloatArray): FloatArray { require(matrix.size >= 9) { "Matrix must have at least 9 elements" } diff --git a/app/src/main/java/com/hinnka/mycamera/raw/RawMetadata.kt b/app/src/main/java/com/hinnka/mycamera/raw/RawMetadata.kt index 94f6e559..c5b11757 100644 --- a/app/src/main/java/com/hinnka/mycamera/raw/RawMetadata.kt +++ b/app/src/main/java/com/hinnka/mycamera/raw/RawMetadata.kt @@ -44,6 +44,12 @@ data class RawMetadata( */ val whiteBalanceGains: FloatArray, + /** + * 相机预乘子(LibRaw/RT pre_mul 语义) + * 顺序: [R, Gr, Gb, B] + */ + val preMul: FloatArray = floatArrayOf(1f, 1f, 1f, 1f), + /** * 色彩校正矩阵(CCM) * 3x3 矩阵,行优先存储(9 个元素) @@ -72,8 +78,7 @@ data class RawMetadata( val exposureBias: Float = 0f, val iso: Int = 100, val shutterSpeed: Long = 0L, - val aperture: Float = 0f, - val droMode: MeteringSystem.DROMode = MeteringSystem.DROMode.OFF + val aperture: Float = 0f ) { companion object { private const val TAG = "RawMetadata" @@ -94,7 +99,6 @@ data class RawMetadata( characteristics: CameraCharacteristics, captureResult: CaptureResult, userExposureCompensation: Float? = null, - droMode: MeteringSystem.DROMode = MeteringSystem.DROMode.OFF, colorSpace: ColorSpace = ColorSpace.BT2020 ): RawMetadata { // 1. 获取 CFA 排列模式 @@ -268,6 +272,7 @@ data class RawMetadata( blackLevel = blackLevel, whiteLevel = whiteLevel, whiteBalanceGains = whiteBalanceGains, + preMul = whiteBalanceGains.copyOf(), colorCorrectionMatrix = colorCorrectionMatrix, lensShadingMap = lensShadingMap, lensShadingMapWidth = shadingWidth, @@ -282,8 +287,7 @@ data class RawMetadata( exposureBias = userExposureCompensation ?: exposureCompensation, iso = iso, shutterSpeed = shutterSpeed, - aperture = aperture, - droMode = droMode + aperture = aperture ) } diff --git a/app/src/main/java/com/hinnka/mycamera/raw/RawProcessingPreferences.kt b/app/src/main/java/com/hinnka/mycamera/raw/RawProcessingPreferences.kt new file mode 100644 index 00000000..8f90cc74 --- /dev/null +++ b/app/src/main/java/com/hinnka/mycamera/raw/RawProcessingPreferences.kt @@ -0,0 +1,12 @@ +package com.hinnka.mycamera.raw + +/** + * Legacy RAW processing preferences kept separate from the histogram matching + * implementation so UI settings can remain compatible while the metering logic + * is removed from the processing pipeline. + */ +object RawProcessingPreferences { + enum class DROMode { + OFF, LOW, HIGH + } +} diff --git a/app/src/main/java/com/hinnka/mycamera/ui/gallery/PhotoEditScreen.kt b/app/src/main/java/com/hinnka/mycamera/ui/gallery/PhotoEditScreen.kt index 1e7e0811..a7fb228d 100644 --- a/app/src/main/java/com/hinnka/mycamera/ui/gallery/PhotoEditScreen.kt +++ b/app/src/main/java/com/hinnka/mycamera/ui/gallery/PhotoEditScreen.kt @@ -52,7 +52,7 @@ import com.hinnka.mycamera.gallery.PhotoMetadata import com.hinnka.mycamera.model.ColorRecipeParams import com.hinnka.mycamera.raw.ColorSpace import com.hinnka.mycamera.raw.LogCurve -import com.hinnka.mycamera.raw.MeteringSystem +import com.hinnka.mycamera.raw.RawProcessingPreferences import com.hinnka.mycamera.ui.camera.LutEditBottomSheet import com.hinnka.mycamera.ui.components.* import com.hinnka.mycamera.ui.theme.AccentOrange @@ -681,7 +681,7 @@ fun PhotoEditScreen( } else if (editTab == 2) { RawEditPanel( viewModel = cameraViewModel, - editDroMode = MeteringSystem.DROMode.valueOf(droMode), + editDroMode = RawProcessingPreferences.DROMode.valueOf(droMode), editColorSpace = colorSpace, editLogCurve = logCurve, editRawLut = rawLut, @@ -974,7 +974,7 @@ private fun ZoomableEditImage( @Composable private fun RawEditPanel( viewModel: CameraViewModel, - editDroMode: MeteringSystem.DROMode, + editDroMode: RawProcessingPreferences.DROMode, editColorSpace: ColorSpace, editLogCurve: LogCurve, editRawLut: String?, @@ -1001,14 +1001,14 @@ private fun RawEditPanel( // DRO Mode SegmentedControl( title = stringResource(R.string.settings_dro_mode), - items = MeteringSystem.DROMode.entries, + items = RawProcessingPreferences.DROMode.entries, selectedItem = editDroMode, onItemSelected = { viewModel.setDroMode(it.name) }, itemLabel = { when (it) { - MeteringSystem.DROMode.OFF -> droOff - MeteringSystem.DROMode.LOW -> droLow - MeteringSystem.DROMode.HIGH -> droHigh + RawProcessingPreferences.DROMode.OFF -> droOff + RawProcessingPreferences.DROMode.LOW -> droLow + RawProcessingPreferences.DROMode.HIGH -> droHigh } } ) diff --git a/app/src/main/java/com/hinnka/mycamera/utils/RawProcessor.kt b/app/src/main/java/com/hinnka/mycamera/utils/RawProcessor.kt index a5db35cd..f8a781bd 100644 --- a/app/src/main/java/com/hinnka/mycamera/utils/RawProcessor.kt +++ b/app/src/main/java/com/hinnka/mycamera/utils/RawProcessor.kt @@ -106,7 +106,8 @@ object RawProcessor { characteristics: CameraCharacteristics, captureResult: CaptureResult, outputStream: java.io.OutputStream, - rotation: Int = 0 + rotation: Int = 0, + thumbnail: Bitmap? = null ) { if (!isRawImage(image)) { throw IllegalArgumentException("Image is not RAW format: ${image.format}") @@ -121,6 +122,10 @@ object RawProcessor { else -> ExifInterface.ORIENTATION_NORMAL } dngCreator.setOrientation(orientation) + buildDngThumbnail(thumbnail)?.let { + dngCreator.setThumbnail(it) + PLog.d(TAG, "Embedded DNG thumbnail written: ${it.width}x${it.height}") + } dngCreator.writeImage(outputStream, image.image) } catch (e: Exception) { PLog.e(TAG, "Failed to save DNG", e) @@ -128,4 +133,23 @@ object RawProcessor { dngCreator.close() } } + + private fun buildDngThumbnail(source: Bitmap?): Bitmap? { + if (source == null || source.isRecycled) { + return null + } + + val maxEdge = 256 + val width = source.width.coerceAtLeast(1) + val height = source.height.coerceAtLeast(1) + val scale = minOf(maxEdge.toFloat() / width, maxEdge.toFloat() / height, 1f) + val targetWidth = (width * scale).toInt().coerceAtLeast(1) + val targetHeight = (height * scale).toInt().coerceAtLeast(1) + + return if (targetWidth == width && targetHeight == height) { + source + } else { + Bitmap.createScaledBitmap(source, targetWidth, targetHeight, true) + } + } } diff --git a/app/src/main/java/com/hinnka/mycamera/viewmodel/CameraViewModel.kt b/app/src/main/java/com/hinnka/mycamera/viewmodel/CameraViewModel.kt index 6f648f16..d2f15881 100644 --- a/app/src/main/java/com/hinnka/mycamera/viewmodel/CameraViewModel.kt +++ b/app/src/main/java/com/hinnka/mycamera/viewmodel/CameraViewModel.kt @@ -1899,9 +1899,9 @@ class CameraViewModel(application: Application) : AndroidViewModel(application) val photoQualityValue = photoQuality.firstOrNull() ?: 95 val droModeString = droMode.value val droModeForProcessing = try { - com.hinnka.mycamera.raw.MeteringSystem.DROMode.valueOf(droModeString) + com.hinnka.mycamera.raw.RawProcessingPreferences.DROMode.valueOf(droModeString) } catch (e: Exception) { - com.hinnka.mycamera.raw.MeteringSystem.DROMode.OFF + com.hinnka.mycamera.raw.RawProcessingPreferences.DROMode.OFF } val currentCameraId = cameraController.getCurrentCameraId() @@ -1993,6 +1993,7 @@ class CameraViewModel(application: Application) : AndroidViewModel(application) context, photoId, image, + previewThumbnail, rotation, aspectRatio, characteristics, @@ -2035,9 +2036,9 @@ class CameraViewModel(application: Application) : AndroidViewModel(application) val photoQualityValue = photoQuality.firstOrNull() ?: 95 val droModeString = droMode.value val droModeForProcessing = try { - com.hinnka.mycamera.raw.MeteringSystem.DROMode.valueOf(droModeString) + com.hinnka.mycamera.raw.RawProcessingPreferences.DROMode.valueOf(droModeString) } catch (e: Exception) { - com.hinnka.mycamera.raw.MeteringSystem.DROMode.OFF + com.hinnka.mycamera.raw.RawProcessingPreferences.DROMode.OFF } val currentCameraId = cameraController.getCurrentCameraId() diff --git a/app/src/main/java/com/hinnka/mycamera/viewmodel/GalleryViewModel.kt b/app/src/main/java/com/hinnka/mycamera/viewmodel/GalleryViewModel.kt index c2725a5c..cb09ef0d 100644 --- a/app/src/main/java/com/hinnka/mycamera/viewmodel/GalleryViewModel.kt +++ b/app/src/main/java/com/hinnka/mycamera/viewmodel/GalleryViewModel.kt @@ -28,7 +28,7 @@ import com.hinnka.mycamera.lut.LutConfig import com.hinnka.mycamera.lut.LutInfo import com.hinnka.mycamera.lut.PhotoTransformation import com.hinnka.mycamera.model.ColorRecipeParams -import com.hinnka.mycamera.raw.MeteringSystem +import com.hinnka.mycamera.raw.RawProcessingPreferences import com.hinnka.mycamera.utils.PLog import com.hinnka.mycamera.ui.gallery.CropAspectOption import com.hinnka.mycamera.ui.gallery.calculateInitialCropRect @@ -1864,7 +1864,11 @@ class GalleryViewModel(application: Application) : AndroidViewModel(application) refreshingPhotos.add(photo.id) try { val context = getApplication() - val result = PhotoManager.refreshRawPreview(context, photo.id, MeteringSystem.DROMode.valueOf(droMode.value)) + val result = PhotoManager.refreshRawPreview( + context, + photo.id, + RawProcessingPreferences.DROMode.valueOf(droMode.value) + ) if (result != null) { // 更新刷新密钥以强制 UI 重新加载 photoRefreshKeys[photo.id] = System.currentTimeMillis()