diff --git a/app/src/main/cpp/native-lib.cpp b/app/src/main/cpp/native-lib.cpp index 69891fa2..cea00daa 100644 --- a/app/src/main/cpp/native-lib.cpp +++ b/app/src/main/cpp/native-lib.cpp @@ -11,7 +11,6 @@ #include #include #include -#include #include #include #include @@ -404,14 +403,11 @@ static bool parseDngGainMaps(const libraw_dng_rawopcode_t &opcodeData, return !gainMaps.empty(); } -static float sampleDngGainMapBilinear(const DngGainMap &gainMap, float x, float y, - int plane = 0) { +static float sampleDngGainMapBilinear(const DngGainMap &gainMap, float x, float y) { const float maxX = static_cast(std::max(0, gainMap.mapPointsH - 1)); const float maxY = static_cast(std::max(0, gainMap.mapPointsV - 1)); const float fx = std::clamp(x, 0.0f, maxX); const float fy = std::clamp(y, 0.0f, maxY); - const int mapPlane = - std::clamp(plane, 0, static_cast(std::max(1, gainMap.mapPlanes)) - 1); const int x0 = static_cast(std::floor(fx)); const int y0 = static_cast(std::floor(fy)); @@ -422,9 +418,7 @@ static float sampleDngGainMapBilinear(const DngGainMap &gainMap, float x, float auto at = [&](int sx, int sy) -> float { const size_t index = - (static_cast(sy) * gainMap.mapPointsH + static_cast(sx)) * - gainMap.mapPlanes + - static_cast(mapPlane); + (static_cast(sy) * gainMap.mapPointsH + static_cast(sx)) * gainMap.mapPlanes; return gainMap.mapGain[index]; }; @@ -437,20 +431,6 @@ static float sampleDngGainMapBilinear(const DngGainMap &gainMap, float x, float return top + (bottom - top) * ty; } -static float sampleDngGainMapAtPixel(const DngGainMap &gainMap, int x, int y, - int rawWidth, int rawHeight, - int plane = 0) { - const double spacingH = gainMap.mapSpacingH > 0.0 ? gainMap.mapSpacingH : 1.0; - const double spacingV = gainMap.mapSpacingV > 0.0 ? gainMap.mapSpacingV : 1.0; - const double relX = - (static_cast(x) + 0.5) / static_cast(std::max(1, rawWidth)); - const double relY = - (static_cast(y) + 0.5) / static_cast(std::max(1, rawHeight)); - const float mapX = static_cast((relX - gainMap.mapOriginH) / spacingH); - const float mapY = static_cast((relY - gainMap.mapOriginV) / spacingV); - return sampleDngGainMapBilinear(gainMap, mapX, mapY, plane); -} - static void computeEffectiveBlackLevels(LibRaw &rawProcessor, float out[4]) { const float base = static_cast(rawProcessor.imgdata.color.black); const unsigned cols = rawProcessor.imgdata.color.cblack[4]; @@ -537,94 +517,38 @@ static bool applySupportedDngGainMaps(LibRaw &rawProcessor, const float blackLev : rawWidth; auto *rawImage = rawProcessor.imgdata.rawdata.raw_image; + const float colScale = static_cast(gainMaps[0].mapPointsH - 1) / + std::max(1, rawWidth); + const float rowScale = static_cast(gainMaps[0].mapPointsV - 1) / + std::max(1, rawHeight); + const DngGainMap *mapByParity[2][2] = {}; for (const auto &gainMap : gainMaps) { mapByParity[gainMap.top & 1u][gainMap.left & 1u] = &gainMap; - LOGI("dng gain map: rect=%u,%u-%u,%u pitch=%u,%u points=%ux%u spacing=%f,%f origin=%f,%f planes=%u", - gainMap.left, gainMap.top, gainMap.right, gainMap.bottom, - gainMap.colPitch, gainMap.rowPitch, gainMap.mapPointsH, - gainMap.mapPointsV, gainMap.mapSpacingH, gainMap.mapSpacingV, - gainMap.mapOriginH, gainMap.mapOriginV, gainMap.mapPlanes); } - double gainSum = 0.0; - float gainMin = std::numeric_limits::max(); - float gainMax = 0.0f; - uint64_t gainCount = 0; for (int y = 0; y < rawHeight; ++y) { + const float ys = static_cast(y) * rowScale; const float rowBlack[2] = {blackLevels[rawProcessor.FC(y, 0)], blackLevels[rawProcessor.FC(y, 1)]}; - for (int x = 0; x < rawWidth; ++x) { + float xs = 0.0f; + for (int x = 0; x < rawWidth; ++x, xs += colScale) { const DngGainMap *gainMap = mapByParity[y & 1][x & 1]; if (!gainMap) { continue; } - if (static_cast(y) < gainMap->top || - static_cast(y) >= gainMap->bottom || - static_cast(x) < gainMap->left || - static_cast(x) >= gainMap->right || - ((static_cast(y) - gainMap->top) % gainMap->rowPitch) != 0u || - ((static_cast(x) - gainMap->left) % gainMap->colPitch) != 0u) { - continue; - } - const int mapPlane = - std::max(0, rawProcessor.FC(y, x) - static_cast(gainMap->plane)); - const float gain = - sampleDngGainMapAtPixel(*gainMap, x, y, rawWidth, rawHeight, mapPlane); + const float gain = sampleDngGainMapBilinear(*gainMap, xs, ys); const float black = rowBlack[x & 1]; float corrected = (static_cast(rawImage[y * rawPitch + x]) - black) * gain + black; corrected = std::max(corrected, 0.0f); rawImage[y * rawPitch + x] = static_cast(std::min(corrected, 65535.0f)); - gainSum += static_cast(gain); - gainMin = std::min(gainMin, gain); - gainMax = std::max(gainMax, gain); - ++gainCount; } } - LOGI("dng gain map: applied 4 maps size=%ux%u grid=%ux%u gain avg=%f min=%f max=%f count=%llu", - rawWidth, rawHeight, gainMaps[0].mapPointsH, gainMaps[0].mapPointsV, - gainCount > 0 ? static_cast(gainSum / static_cast(gainCount)) : 0.0f, - gainCount > 0 ? gainMin : 0.0f, gainMax, - static_cast(gainCount)); + LOGI("dng gain map: applied 4 maps size=%ux%u grid=%ux%u", + rawWidth, rawHeight, gainMaps[0].mapPointsH, gainMaps[0].mapPointsV); return true; } -static void logProcessedImageStats(const char *label, - const libraw_processed_image_t *image) { - if (!image || !image->data || image->width <= 0 || image->height <= 0 || - image->colors < 3 || image->bits != 16) { - return; - } - - const auto *pixels = reinterpret_cast(image->data); - const size_t pixelCount = - static_cast(image->width) * static_cast(image->height); - double sumR = 0.0; - double sumG = 0.0; - double sumB = 0.0; - uint64_t clipped = 0; - for (size_t i = 0; i < pixelCount; ++i) { - const ushort r = pixels[i * image->colors]; - const ushort g = pixels[i * image->colors + 1]; - const ushort b = pixels[i * image->colors + 2]; - sumR += r; - sumG += g; - sumB += b; - if (r >= 65535 || g >= 65535 || b >= 65535) { - ++clipped; - } - } - - const double invCount = pixelCount > 0 ? 1.0 / static_cast(pixelCount) : 0.0; - LOGI("%s rgb16 mean R=%f G=%f B=%f luma=%f clipped=%llu/%llu", - label, static_cast(sumR * invCount), - static_cast(sumG * invCount), static_cast(sumB * invCount), - static_cast((sumR * 0.2126 + sumG * 0.7152 + sumB * 0.0722) * - invCount), - static_cast(clipped), - static_cast(pixelCount)); -} - static bool estimateRawAutoWhiteBalance(LibRaw &rawProcessor, const float blackLevels[4], float outUserMul[4], int &sampleCount) { sampleCount = 0; @@ -1949,455 +1873,6 @@ static void exif_callback(void *datap, int tag, int type, int len, stream->seek(current_pos, SEEK_SET); } -/** - * Native 方法:直接从内存像素 Buffer 处理 RAW 数据 - * 接收纯 Bayer 数据(无 DNG 头),因此所有元数据必须由 Kotlin 提供 - */ -JNIEXPORT jobject JNICALL -Java_com_hinnka_mycamera_raw_RawDemosaicProcessor_processRawBufferNative( - JNIEnv *env, jobject /* this */, jobject rawBuffer, jint width, jint height, - jint rowStride, jint cfaPattern, jfloatArray blackLevel, jfloat whiteLevel, - jfloatArray wbGains, jfloatArray colorMatrix, jfloatArray noiseProfile, - jfloatArray lensShadingMap, jint lensShadingMapWidth, - jint lensShadingMapHeight, jfloat xr, jfloat yr, jfloat xg, jfloat yg, - jfloat xb, jfloat yb, jfloat xw, jfloat yw, - jboolean useRawAutoWhiteBalanceEstimate) { - - if (!rawBuffer) { - LOGE("processRawBufferNative: rawBuffer is null"); - return nullptr; - } - - auto *data = static_cast(env->GetDirectBufferAddress(rawBuffer)); - if (!data) { - LOGE("processRawBufferNative: Failed to get buffer address"); - return nullptr; - } - - if (width <= 1 || height <= 1 || rowStride < width * 2 || whiteLevel <= 0.0f) { - LOGE("processRawBufferNative: invalid input size=%dx%d rowStride=%d white=%f", - width, height, rowStride, whiteLevel); - return nullptr; - } - - float bl[4] = {0, 0, 0, 0}; - if (blackLevel) { - const jsize count = std::min(4, env->GetArrayLength(blackLevel)); - env->GetFloatArrayRegion(blackLevel, 0, count, bl); - } - - float wb[4] = {1, 1, 1, 1}; - if (wbGains) { - const jsize count = std::min(4, env->GetArrayLength(wbGains)); - env->GetFloatArrayRegion(wbGains, 0, count, wb); - } - float wbBase = (wb[1] > 0.0f && std::isfinite(wb[1])) ? wb[1] : 1.0f; - for (float &gain : wb) { - gain = (gain > 0.0f && std::isfinite(gain)) ? gain / wbBase : 1.0f; - } - - float cm[9] = { - 1.0f, 0.0f, 0.0f, - 0.0f, 1.0f, 0.0f, - 0.0f, 0.0f, 1.0f, - }; - if (colorMatrix) { - const jsize count = std::min(9, env->GetArrayLength(colorMatrix)); - env->GetFloatArrayRegion(colorMatrix, 0, count, cm); - } - - std::vector noiseValues; - if (noiseProfile) { - const jsize count = env->GetArrayLength(noiseProfile); - noiseValues.resize(static_cast(count)); - if (count > 0) { - env->GetFloatArrayRegion(noiseProfile, 0, count, noiseValues.data()); - } - } - - std::vector lscValues; - const bool hasLsc = - lensShadingMap && lensShadingMapWidth > 0 && lensShadingMapHeight > 0 && - env->GetArrayLength(lensShadingMap) >= lensShadingMapWidth * lensShadingMapHeight * 4; - if (hasLsc) { - const jsize count = lensShadingMapWidth * lensShadingMapHeight * 4; - lscValues.resize(static_cast(count)); - env->GetFloatArrayRegion(lensShadingMap, 0, count, lscValues.data()); - } - - { - LibRaw rawProcessor; - const auto *rawBytes = reinterpret_cast(data); - int ret = rawProcessor.open_bayer( - rawBytes, static_cast(width * height * sizeof(ushort)), - static_cast(width), static_cast(height), 0, 0, 0, 0, 0, - mapCfaPatternToLibRaw(cfaPattern), 0, 0, 0); - if (ret != LIBRAW_SUCCESS) { - LOGE("processRawBufferNative: open_bayer failed ret=%d", ret); - return nullptr; - } - - rawProcessor.imgdata.color.black = 0; - rawProcessor.imgdata.color.cblack[0] = static_cast(std::max(0.0f, bl[0])); - rawProcessor.imgdata.color.cblack[1] = static_cast(std::max(0.0f, bl[1])); - rawProcessor.imgdata.color.cblack[2] = static_cast(std::max(0.0f, bl[3])); - rawProcessor.imgdata.color.cblack[3] = static_cast(std::max(0.0f, bl[2])); - rawProcessor.imgdata.color.maximum = static_cast(std::max(1.0f, whiteLevel)); - rawProcessor.imgdata.color.dng_levels.dng_whitelevel[0] = - static_cast(std::max(1.0f, whiteLevel)); - rawProcessor.imgdata.color.cam_mul[0] = wb[0]; - rawProcessor.imgdata.color.cam_mul[1] = wb[1]; - rawProcessor.imgdata.color.cam_mul[2] = wb[3]; - rawProcessor.imgdata.color.cam_mul[3] = wb[2]; - LOGI("processRawBufferNative: black RGGB=%f,%f,%f,%f white=%f cam_mul RGBG=%f,%f,%f,%f", - bl[0], bl[1], bl[2], bl[3], whiteLevel, - rawProcessor.imgdata.color.cam_mul[0], - rawProcessor.imgdata.color.cam_mul[1], - rawProcessor.imgdata.color.cam_mul[2], - rawProcessor.imgdata.color.cam_mul[3]); - LOGI("processRawBufferNative: inputCCM=%f,%f,%f,%f,%f,%f,%f,%f,%f", - cm[0], cm[1], cm[2], cm[3], cm[4], cm[5], cm[6], cm[7], cm[8]); - - ret = rawProcessor.unpack(); - if (ret != LIBRAW_SUCCESS) { - LOGE("processRawBufferNative: unpack failed ret=%d", ret); - return nullptr; - } - - if (hasLsc && rawProcessor.imgdata.rawdata.raw_image) { - const int rawWidth = rawProcessor.imgdata.sizes.raw_width; - const int rawHeight = rawProcessor.imgdata.sizes.raw_height; - const int rawPitch = rawProcessor.imgdata.sizes.raw_pitch > 0 - ? rawProcessor.imgdata.sizes.raw_pitch / - static_cast(sizeof(ushort)) - : rawWidth; - auto *rawImage = rawProcessor.imgdata.rawdata.raw_image; - auto libRawChannelToAppChannel = [](int channel) -> int { - switch (channel) { - case 0: - return 0; // R - case 1: - return 1; // Gr - case 2: - return 3; // B - case 3: - return 2; // Gb - default: - return 1; - } - }; - auto sampleAndroidLsc = [&](int appChannel, int x, int y) -> float { - const float gx = (static_cast(x) + 0.5f) * - static_cast(std::max(0, lensShadingMapWidth - 1)) / - static_cast(std::max(1, rawWidth)); - const float gy = (static_cast(y) + 0.5f) * - static_cast(std::max(0, lensShadingMapHeight - 1)) / - static_cast(std::max(1, rawHeight)); - const int x0 = std::clamp(static_cast(std::floor(gx)), 0, - static_cast(lensShadingMapWidth) - 1); - const int y0 = std::clamp(static_cast(std::floor(gy)), 0, - static_cast(lensShadingMapHeight) - 1); - const int x1 = - std::min(x0 + 1, static_cast(lensShadingMapWidth) - 1); - const int y1 = - std::min(y0 + 1, static_cast(lensShadingMapHeight) - 1); - const float tx = gx - static_cast(x0); - const float ty = gy - static_cast(y0); - auto at = [&](int sx, int sy) -> float { - const size_t index = - (static_cast(sy) * lensShadingMapWidth + sx) * 4 + - appChannel; - return lscValues[index]; - }; - const float v00 = at(x0, y0); - const float v10 = at(x1, y0); - const float v01 = at(x0, y1); - const float v11 = at(x1, y1); - const float top = v00 + (v10 - v00) * tx; - const float bottom = v01 + (v11 - v01) * tx; - return std::max(0.0f, top + (bottom - top) * ty); - }; - - double gainSum = 0.0; - float gainMin = std::numeric_limits::max(); - float gainMax = 0.0f; - uint64_t gainCount = 0; - for (int y = 0; y < rawHeight; ++y) { - for (int x = 0; x < rawWidth; ++x) { - const int libRawChannel = rawProcessor.FC(y, x); - const int appChannel = libRawChannelToAppChannel(libRawChannel); - const float black = bl[appChannel]; - const float gain = sampleAndroidLsc(appChannel, x, y); - float corrected = - (static_cast(rawImage[y * rawPitch + x]) - black) * gain + - black; - rawImage[y * rawPitch + x] = - static_cast(std::clamp(corrected, 0.0f, 65535.0f)); - gainSum += static_cast(gain); - gainMin = std::min(gainMin, gain); - gainMax = std::max(gainMax, gain); - ++gainCount; - } - } - LOGI("processRawBufferNative: android lsc grid=%dx%d gain avg=%f min=%f max=%f count=%llu", - lensShadingMapWidth, lensShadingMapHeight, - gainCount > 0 ? static_cast(gainSum / static_cast(gainCount)) : 0.0f, - gainCount > 0 ? gainMin : 0.0f, gainMax, - static_cast(gainCount)); - } - - rawProcessor.imgdata.params.output_bps = 16; - rawProcessor.imgdata.params.gamm[0] = 1.0; - rawProcessor.imgdata.params.gamm[1] = 1.0; - rawProcessor.imgdata.params.no_auto_bright = 1; - rawProcessor.imgdata.params.use_camera_wb = 1; - rawProcessor.imgdata.params.output_color = 0; - rawProcessor.imgdata.params.user_qual = 14; - rawProcessor.imgdata.params.fbdd_noiserd = 0; - rawProcessor.imgdata.params.threshold = 0; - rawProcessor.imgdata.params.med_passes = 0; - - ret = rawProcessor.dcraw_process(); - if (ret != LIBRAW_SUCCESS) { - LOGE("processRawBufferNative: dcraw_process failed ret=%d", ret); - return nullptr; - } - - libraw_processed_image_t *image = rawProcessor.dcraw_make_mem_image(&ret); - if (!image || ret != LIBRAW_SUCCESS) { - LOGE("processRawBufferNative: dcraw_make_mem_image failed ret=%d", ret); - return nullptr; - } - logProcessedImageStats("processRawBufferNative", image); - - const size_t libRawOutputSize = - static_cast(image->width) * image->height * 3u * sizeof(ushort); - void *libRawOutData = malloc(libRawOutputSize); - if (!libRawOutData) { - LibRaw::dcraw_clear_mem(image); - LOGE("processRawBufferNative: malloc failed size=%zu", libRawOutputSize); - return nullptr; - } - memcpy(libRawOutData, image->data, libRawOutputSize); - jobject libRawBuffer = env->NewDirectByteBuffer(libRawOutData, libRawOutputSize); - if (!libRawBuffer) { - free(libRawOutData); - LibRaw::dcraw_clear_mem(image); - return nullptr; - } - - jclass dngDataClass = env->FindClass("com/hinnka/mycamera/raw/DngRawData"); - jmethodID constructor = - env->GetMethodID(dngDataClass, "", - "(Ljava/nio/ByteBuffer;IIIF[F[F[F[FIIF[FIIFIJF[I[FLandroid/graphics/Bitmap;)V"); - - jfloatArray blackLevelArray = env->NewFloatArray(4); - float linearBlack[4] = {0.0f, 0.0f, 0.0f, 0.0f}; - env->SetFloatArrayRegion(blackLevelArray, 0, 4, linearBlack); - - jfloatArray preMulArray = env->NewFloatArray(4); - float oneMul[4] = {1.0f, 1.0f, 1.0f, 1.0f}; - env->SetFloatArrayRegion(preMulArray, 0, 4, oneMul); - - jfloatArray wbArray = env->NewFloatArray(4); - env->SetFloatArrayRegion(wbArray, 0, 4, oneMul); - - jfloatArray colorMatrixArray = env->NewFloatArray(9); - env->SetFloatArrayRegion(colorMatrixArray, 0, 9, cm); - - jfloatArray noiseProfileArray = nullptr; - if (!noiseValues.empty()) { - noiseProfileArray = env->NewFloatArray(static_cast(noiseValues.size())); - env->SetFloatArrayRegion(noiseProfileArray, 0, - static_cast(noiseValues.size()), - noiseValues.data()); - } - - jintArray activeArray = env->NewIntArray(4); - jint aa[4] = {0, 0, static_cast(image->width), - static_cast(image->height)}; - env->SetIntArrayRegion(activeArray, 0, 4, aa); - - jobject dngData = env->NewObject( - dngDataClass, constructor, libRawBuffer, static_cast(image->width), - static_cast(image->height), static_cast(image->width * 6), - 65535.0f, blackLevelArray, preMulArray, wbArray, colorMatrixArray, -1, 0, - 0.0f, nullptr, 0, 0, 0.0f, 0, 0L, 0.0f, activeArray, - noiseProfileArray, nullptr); - LOGI("processRawBufferNative: LibRaw processed %dx%d lsc=%d cam_mul RGBG=%f,%f,%f,%f", - image->width, image->height, hasLsc ? 1 : 0, - rawProcessor.imgdata.color.cam_mul[0], - rawProcessor.imgdata.color.cam_mul[1], - rawProcessor.imgdata.color.cam_mul[2], - rawProcessor.imgdata.color.cam_mul[3]); - LibRaw::dcraw_clear_mem(image); - return dngData; - } - - const int srcStride = rowStride / static_cast(sizeof(ushort)); - auto cfaChannelAt = [cfaPattern](int x, int y) -> int { - const int xp = x & 1; - const int yp = y & 1; - switch (cfaPattern) { - case 1: // GRBG - return yp == 0 ? (xp == 0 ? 1 : 0) : (xp == 0 ? 3 : 2); - case 2: // GBRG - return yp == 0 ? (xp == 0 ? 2 : 3) : (xp == 0 ? 0 : 1); - case 3: // BGGR - return yp == 0 ? (xp == 0 ? 3 : 2) : (xp == 0 ? 1 : 0); - case 0: // RGGB - default: - return yp == 0 ? (xp == 0 ? 0 : 1) : (xp == 0 ? 2 : 3); - } - }; - - auto sampleLsc = [&](int channel, int x, int y) -> float { - if (!hasLsc) { - return 1.0f; - } - const float gx = (static_cast(x) + 0.5f) * - static_cast(lensShadingMapWidth) / - std::max(1, width) - - 0.5f; - const float gy = (static_cast(y) + 0.5f) * - static_cast(lensShadingMapHeight) / - std::max(1, height) - - 0.5f; - const int x0 = std::clamp(static_cast(std::floor(gx)), 0, - static_cast(lensShadingMapWidth) - 1); - const int y0 = std::clamp(static_cast(std::floor(gy)), 0, - static_cast(lensShadingMapHeight) - 1); - const int x1 = std::min(x0 + 1, static_cast(lensShadingMapWidth) - 1); - const int y1 = std::min(y0 + 1, static_cast(lensShadingMapHeight) - 1); - const float tx = gx - static_cast(x0); - const float ty = gy - static_cast(y0); - auto at = [&](int sx, int sy) -> float { - const size_t index = - (static_cast(sy) * lensShadingMapWidth + sx) * 4 + channel; - return lscValues[index]; - }; - const float v00 = at(x0, y0); - const float v10 = at(x1, y0); - const float v01 = at(x0, y1); - const float v11 = at(x1, y1); - const float top = v00 + (v10 - v00) * tx; - const float bottom = v01 + (v11 - v01) * tx; - return std::max(0.0f, top + (bottom - top) * ty); - }; - - auto correctedSensor = [&](int x, int y, int channel) -> float { - const int sx = std::clamp(x, 0, static_cast(width) - 1); - const int sy = std::clamp(y, 0, static_cast(height) - 1); - const float raw = static_cast(data[sy * srcStride + sx]); - const float black = bl[channel]; - const float range = std::max(1.0f, whiteLevel - black); - const float gain = sampleLsc(channel, sx, sy) * std::max(0.0f, wb[channel]); - return std::clamp((raw - black) * gain / range, 0.0f, 1.0f); - }; - - auto sampleChannel = [&](int x, int y, int channel) -> float { - const int ownChannel = cfaChannelAt(x, y); - if (ownChannel == channel || - ((ownChannel == 1 || ownChannel == 2) && (channel == 1 || channel == 2))) { - return correctedSensor(x, y, ownChannel); - } - - float sum = 0.0f; - int count = 0; - for (int dy = -1; dy <= 1; ++dy) { - for (int dx = -1; dx <= 1; ++dx) { - if (dx == 0 && dy == 0) { - continue; - } - const int sx = std::clamp(x + dx, 0, static_cast(width) - 1); - const int sy = std::clamp(y + dy, 0, static_cast(height) - 1); - const int neighborChannel = cfaChannelAt(sx, sy); - if (neighborChannel == channel || - ((neighborChannel == 1 || neighborChannel == 2) && - (channel == 1 || channel == 2))) { - sum += correctedSensor(sx, sy, neighborChannel); - ++count; - } - } - } - if (count == 0) { - return correctedSensor(x, y, ownChannel); - } - return sum / static_cast(count); - }; - - const size_t outputSize = - static_cast(width) * static_cast(height) * 3u * sizeof(ushort); - void *outData = malloc(outputSize); - if (!outData) { - LOGE("processRawBufferNative: malloc failed size=%zu", outputSize); - return nullptr; - } - auto *out = static_cast(outData); - -#pragma omp parallel for num_threads(8) - for (int y = 0; y < height; ++y) { - for (int x = 0; x < width; ++x) { - const size_t base = (static_cast(y) * width + x) * 3u; - out[base] = static_cast( - std::clamp(sampleChannel(x, y, 0) * 65535.0f, 0.0f, 65535.0f)); - out[base + 1] = static_cast( - std::clamp(sampleChannel(x, y, 1) * 65535.0f, 0.0f, 65535.0f)); - out[base + 2] = static_cast( - std::clamp(sampleChannel(x, y, 3) * 65535.0f, 0.0f, 65535.0f)); - } - } - - jobject rawDataBuffer = env->NewDirectByteBuffer(outData, outputSize); - if (!rawDataBuffer) { - free(outData); - return nullptr; - } - - jclass dngDataClass = env->FindClass("com/hinnka/mycamera/raw/DngRawData"); - jmethodID constructor = - env->GetMethodID(dngDataClass, "", - "(Ljava/nio/ByteBuffer;IIIF[F[F[F[FIIF[FIIFIJF[I[FLandroid/graphics/Bitmap;)V"); - - jfloatArray blackLevelArray = env->NewFloatArray(4); - float linearBlack[4] = {0.0f, 0.0f, 0.0f, 0.0f}; - env->SetFloatArrayRegion(blackLevelArray, 0, 4, linearBlack); - - jfloatArray preMulArray = env->NewFloatArray(4); - float preMul[4] = {1.0f, 1.0f, 1.0f, 1.0f}; - env->SetFloatArrayRegion(preMulArray, 0, 4, preMul); - - jfloatArray wbArray = env->NewFloatArray(4); - env->SetFloatArrayRegion(wbArray, 0, 4, preMul); - - jfloatArray colorMatrixArray = env->NewFloatArray(9); - env->SetFloatArrayRegion(colorMatrixArray, 0, 9, cm); - - jfloatArray noiseProfileArray = nullptr; - if (!noiseValues.empty()) { - noiseProfileArray = env->NewFloatArray(static_cast(noiseValues.size())); - env->SetFloatArrayRegion(noiseProfileArray, 0, - static_cast(noiseValues.size()), - noiseValues.data()); - } - - jintArray activeArray = env->NewIntArray(4); - jint aa[4] = {0, 0, width, height}; - env->SetIntArrayRegion(activeArray, 0, 4, aa); - - jobject dngData = env->NewObject( - dngDataClass, constructor, rawDataBuffer, width, height, - static_cast(width * 6), 65535.0f, blackLevelArray, preMulArray, - wbArray, colorMatrixArray, -1, 0, 0.0f, nullptr, 0, 0, 0.0f, 0, 0L, - 0.0f, activeArray, noiseProfileArray, nullptr); - - LOGI("processRawBufferNative: demosaiced %dx%d rowStride=%d lsc=%d", - width, height, rowStride, hasLsc ? 1 : 0); - LOGI("processRawBufferNative: wb RGGB=%f,%f,%f,%f", wb[0], wb[1], wb[2], - wb[3]); - return dngData; -} - /** * 使用 LibRaw 处理 DNG 文件 */ @@ -2469,13 +1944,6 @@ Java_com_hinnka_mycamera_raw_RawDemosaicProcessor_processDngNative( float dngBlackLevels[4] = {}; computeEffectiveBlackLevels(RawProcessor, dngBlackLevels); LOGI("dng black levels (metadata): %f %f %f %f", dngBlackLevels[0], dngBlackLevels[1], dngBlackLevels[2], dngBlackLevels[3]); - LOGI("dng levels: black=%u cblack=%u,%u,%u,%u maximum=%u white=%u cam_mul RGBG=%f,%f,%f,%f", - RawProcessor.imgdata.color.black, RawProcessor.imgdata.color.cblack[0], - RawProcessor.imgdata.color.cblack[1], RawProcessor.imgdata.color.cblack[2], - RawProcessor.imgdata.color.cblack[3], RawProcessor.imgdata.color.maximum, - RawProcessor.imgdata.color.dng_levels.dng_whitelevel[0], - RawProcessor.imgdata.color.cam_mul[0], RawProcessor.imgdata.color.cam_mul[1], - RawProcessor.imgdata.color.cam_mul[2], RawProcessor.imgdata.color.cam_mul[3]); const bool appliedDngGainMap = applySupportedDngGainMaps(RawProcessor, dngBlackLevels); LOGI("dng gain map: opcode2_len=%u applied=%d", RawProcessor.imgdata.color.dng_levels.rawopcodes[1].len, appliedDngGainMap ? 1 : 0); @@ -2534,7 +2002,6 @@ Java_com_hinnka_mycamera_raw_RawDemosaicProcessor_processDngNative( env->ReleaseStringUTFChars(filePath, path); return nullptr; } - logProcessedImageStats("processDngNative", image); // 准备返回结果 size_t outputSize = (size_t)image->width * image->height * 3 * 2; diff --git a/app/src/main/java/com/hinnka/mycamera/gallery/GalleryManager.kt b/app/src/main/java/com/hinnka/mycamera/gallery/GalleryManager.kt index 9b0e6d12..9235dafc 100644 --- a/app/src/main/java/com/hinnka/mycamera/gallery/GalleryManager.kt +++ b/app/src/main/java/com/hinnka/mycamera/gallery/GalleryManager.kt @@ -25,7 +25,6 @@ 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.processor.RawStackResult import com.hinnka.mycamera.raw.RawDemosaicProcessor import com.hinnka.mycamera.raw.RawMetadata import com.hinnka.mycamera.raw.RawProcessingPreferences @@ -1135,66 +1134,44 @@ object GalleryManager { return@withContext } - val firstImageWidth = image.width - val firstImageHeight = image.height - - val rawMetadata = RawMetadata.create( - firstImageWidth, - firstImageHeight, - characteristics, - resolvedCaptureResult, - exposureBias, - RawDemosaicProcessor.getInstance().getRawColorSpace() - ) - val rawProcessingBuffer = copyRawPlaneToCompactDirectBuffer( - source = image.planes[0].buffer, - width = firstImageWidth, - height = firstImageHeight, - rowStride = image.planes[0].rowStride - ) - - // Parallel DNG saving and RAW processing - val dngDeferred = processingScope.async(Dispatchers.IO) { - var dngSaveAttempted = false - FileOutputStream(tempDngFile).use { outputStream -> - image.use { - try { - RawProcessor.saveToDng( - image, - characteristics, - resolvedCaptureResult, - outputStream, - rotation, - thumbnail - ) - dngSaveAttempted = true - } catch (e: Throwable) { - PLog.e(TAG, "DNG save failed", e) - } + var dngSaveAttempted = false + FileOutputStream(tempDngFile).use { outputStream -> + image.use { + try { + RawProcessor.saveToDng( + image, + characteristics, + resolvedCaptureResult, + outputStream, + rotation, + thumbnail + ) + dngSaveAttempted = true + } catch (e: Throwable) { + PLog.e(TAG, "DNG save failed", e) } } - val dngWritten = dngSaveAttempted && tempDngFile.exists() && tempDngFile.length() > 0L - if (dngWritten) { - patchSavedDngBlackLevel(tempDngFile, metadata) - if (dngFile.exists()) dngFile.delete() - if (!tempDngFile.renameTo(dngFile)) { - tempDngFile.copyTo(dngFile, overwrite = true) - tempDngFile.delete() - } - if (shouldAutoSave && exportDngWithRawExport) { - exportDng(context, photoId, dngFile, metadata) - } - } - dngWritten + } + val dngWritten = dngSaveAttempted && tempDngFile.exists() && tempDngFile.length() > 0L + if (!dngWritten) { + tempDngFile.delete() + return@withContext + } + patchSavedDngBlackLevel(tempDngFile, metadata) + if (dngFile.exists()) { + dngFile.delete() + } + if (!tempDngFile.renameTo(dngFile)) { + tempDngFile.copyTo(dngFile, overwrite = true) + tempDngFile.delete() + } + if (shouldAutoSave && exportDngWithRawExport) { + exportDng(context, photoId, dngFile, metadata) } val rawResult = RawDemosaicProcessor.getInstance().processForHdrSources( - context = context, - rawBuffer = rawProcessingBuffer, - width = firstImageWidth, - height = firstImageHeight, - rowStride = firstImageWidth * 2, - metadata = rawMetadata, + context, + dngFile.absolutePath, aspectRatio = aspectRatio, cropRegion = metadata.cropRegion, rotation = rotation, @@ -1207,14 +1184,7 @@ object GalleryManager { sharpeningValue = 0.4f, denoiseValue = metadata.rawDenoiseValue, rawDcpId = metadata.rawDcpId - ) ?: run { - dngDeferred.await() - return@withContext - } - - // Wait for DNG save if needed later (though we process from buffer) - dngDeferred.await() - + ) ?: return@withContext var bitmap = rawResult.sdrBitmap if (metadata.isMirrored) { @@ -1726,42 +1696,41 @@ object GalleryManager { whiteLevel = rawMetadata.whiteLevel.toInt(), whiteBalanceGains = rawMetadata.whiteBalanceGains, noiseModel = rawMetadata.noiseProfile, - lensShading = rawMetadata.lensShadingMap, - lensShadingWidth = rawMetadata.lensShadingMapWidth, - lensShadingHeight = rawMetadata.lensShadingMapHeight, + lensShading = null, + lensShadingWidth = 0, + lensShadingHeight = 0, ) val finalStackResult = rawStackResult ?: return@withContext - val fusedBuffer = finalStackResult.fusedBayerBuffer ?: return@withContext - // Parallel DNG saving and RAW processing from memory buffer - val dngDeferred = processingScope.async(Dispatchers.IO) { - trySaveStackedRawDng( - context = context, - photoId = photoId, - dngFile = dngFile, - fusedBayerBuffer = fusedBuffer, - width = finalStackResult.width, - height = finalStackResult.height, - rawMetadata = rawMetadata, - isNormalizedSensorData = finalStackResult.isNormalizedSensorData, - characteristics = characteristics, - captureResult = captureResult, - rotation = rotation, - thumbnail = null, - metadata = metadata, - shouldAutoSave = shouldAutoSave, - exportDngWithRawExport = exportDngWithRawExport - ) - } - - val rawResult = RawDemosaicProcessor.getInstance().processForHdrSources( + val dngWritten = trySaveStackedRawDng( context = context, - rawBuffer = fusedBuffer, + photoId = photoId, + dngFile = dngFile, + fusedBayerBuffer = finalStackResult.fusedBayerBuffer ?: return@withContext, width = finalStackResult.width, height = finalStackResult.height, - rowStride = finalStackResult.width * 2, // 16-bit Bayer - metadata = rawMetadata.forStackRender(finalStackResult, images.size), + rawMetadata = rawMetadata, + isNormalizedSensorData = finalStackResult.isNormalizedSensorData, + characteristics = characteristics, + captureResult = captureResult, + rotation = rotation, + thumbnail = null, + metadata = metadata, + shouldAutoSave = shouldAutoSave, + exportDngWithRawExport = exportDngWithRawExport + ) + if (!dngWritten) { + PLog.e(TAG, "Failed to persist stacked RAW DNG before rendering preview") + return@withContext + } + finalStackResult.fusedBayerBuffer = null + @Suppress("ExplicitGarbageCollectionCall") + System.gc() + + val rawResult = RawDemosaicProcessor.getInstance().processForHdrSources( + context, + dngFile.absolutePath, aspectRatio = aspectRatio, cropRegion = metadata.cropRegion, rotation = rotation, @@ -1774,17 +1743,7 @@ object GalleryManager { sharpeningValue = 0.4f, denoiseValue = metadata.rawDenoiseValue, rawDcpId = metadata.rawDcpId - ) ?: run { - dngDeferred.await() - finalStackResult.release() - return@withContext - } - - // Wait for DNG save completion - dngDeferred.await() - - finalStackResult.release() - + ) ?: return@withContext var bitmap = rawResult.sdrBitmap if (metadata.isMirrored) { @@ -1954,42 +1913,6 @@ object GalleryManager { } } - private fun copyRawPlaneToCompactDirectBuffer( - source: ByteBuffer, - width: Int, - height: Int, - rowStride: Int, - ): ByteBuffer { - val bytesPerRow = width * 2 - val output = ByteBuffer.allocateDirect(bytesPerRow * height).order(ByteOrder.nativeOrder()) - val src = source.duplicate() - for (y in 0 until height) { - val rowStart = y * rowStride - src.limit(source.capacity()) - src.position(rowStart) - src.limit(rowStart + bytesPerRow) - output.put(src) - } - output.position(0) - return output - } - - private fun RawMetadata.forStackRender(stackResult: RawStackResult, frameCount: Int): RawMetadata { - if (!stackResult.isNormalizedSensorData) { - return this.copy(frameCount = frameCount) - } - return copy( - width = stackResult.width, - height = stackResult.height, - blackLevel = floatArrayOf(0f, 0f, 0f, 0f), - whiteLevel = 65535f, - lensShadingMap = null, - lensShadingMapWidth = 0, - lensShadingMapHeight = 0, - frameCount = frameCount - ) - } - /** * 保存堆栈合成后的照片 diff --git a/app/src/main/java/com/hinnka/mycamera/processor/MultiFrameStacker.kt b/app/src/main/java/com/hinnka/mycamera/processor/MultiFrameStacker.kt index 720d1a1f..bab4ad60 100644 --- a/app/src/main/java/com/hinnka/mycamera/processor/MultiFrameStacker.kt +++ b/app/src/main/java/com/hinnka/mycamera/processor/MultiFrameStacker.kt @@ -5,7 +5,6 @@ import android.graphics.ColorSpace import android.media.Image import android.util.Log import com.hinnka.mycamera.utils.PLog -import com.hinnka.mycamera.utils.DirectBufferAllocator import java.nio.ByteBuffer import androidx.core.graphics.createBitmap import com.hinnka.mycamera.camera.AspectRatio @@ -19,14 +18,7 @@ data class RawStackResult( val width: Int, val height: Int, val isNormalizedSensorData: Boolean, -) { - fun release() { - fusedBayerBuffer?.let { - DirectBufferAllocator.freeNative(it) - fusedBayerBuffer = null - } - } -} +) /** * Multi-Frame Stacker @@ -294,11 +286,11 @@ object MultiFrameStacker { val outWidth = (width * outputScale).roundToInt() val outHeight = (height * outputScale).roundToInt() - vulkanFusedBayer = DirectBufferAllocator.allocateNative((outWidth * outHeight * 2).toLong()) - ?.order(ByteOrder.nativeOrder()) - - if (vulkanFusedBayer == null) { - PLog.e(TAG, "Failed to allocate Vulkan fused Bayer buffer") + vulkanFusedBayer = try { + ByteBuffer.allocateDirect(outWidth * outHeight * 2) + .order(ByteOrder.nativeOrder()) + } catch (e: OutOfMemoryError) { + PLog.e(TAG, "OOM allocating Vulkan fused Bayer buffer", e) return null } @@ -314,17 +306,17 @@ object MultiFrameStacker { ) } else { PLog.w(TAG, "Vulkan RAW stacking failed, falling back to CPU") - DirectBufferAllocator.freeNative(vulkanFusedBayer) } } catch (e: Exception) { PLog.e(TAG, "Vulkan RAW stacking error: ${e.message}, falling back to CPU") - vulkanFusedBayer?.let { DirectBufferAllocator.freeNative(it) } } finally { releaseVulkanRawStackerNative(vulkanStackerPtr) } // fallback 到 CPU 路径前显式释放 Vulkan buffer 引用,避免与 CPU 路径的分配叠加 // 仅 fused Bayer 持续到 DNG 保存完成。 vulkanFusedBayer = null + @Suppress("ExplicitGarbageCollectionCall") + System.gc() } else { PLog.w(TAG, "Failed to create Vulkan RAW stacker, falling back to CPU") } @@ -355,9 +347,11 @@ object MultiFrameStacker { val stackedWidth = if (useNativeSuperResolution) width * 2 else width val stackedHeight = if (useNativeSuperResolution) height * 2 else height - val fusedBayerBuffer = DirectBufferAllocator.allocateNative((stackedWidth * stackedHeight * 2).toLong()) - ?.order(ByteOrder.nativeOrder()) ?: run { - PLog.e(TAG, "Failed to allocate fused Bayer buffer") + val fusedBayerBuffer = try { + ByteBuffer.allocateDirect(stackedWidth * stackedHeight * 2) + .order(ByteOrder.nativeOrder()) + } catch (e: OutOfMemoryError) { + PLog.e(TAG, "OOM allocating fused Bayer buffer", e) return null } processRawStackWithBufferNative(stackerPtr, fusedBayerBuffer) 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 9aeeaad7..6cea8627 100644 --- a/app/src/main/java/com/hinnka/mycamera/raw/RawDemosaicProcessor.kt +++ b/app/src/main/java/com/hinnka/mycamera/raw/RawDemosaicProcessor.kt @@ -130,80 +130,6 @@ class RawDemosaicProcessor { useRawAutoWhiteBalanceEstimate: Boolean ): DngRawData? - /** - * Native 方法:直接从内存 Buffer 处理 RAW 数据 - */ - private external fun processRawBufferNative( - rawBuffer: ByteBuffer, - width: Int, - height: Int, - rowStride: Int, - cfaPattern: Int, - blackLevel: FloatArray, - whiteLevel: Float, - wbGains: FloatArray, - colorMatrix: FloatArray, - noiseProfile: FloatArray, - lensShadingMap: FloatArray?, - lensShadingMapWidth: Int, - lensShadingMapHeight: Int, - xr: Float, yr: Float, - xg: Float, yg: Float, - xb: Float, yb: Float, - xw: Float, yw: Float, - useRawAutoWhiteBalanceEstimate: Boolean - ): DngRawData? - - suspend fun processForHdrSources( - context: Context, - rawBuffer: ByteBuffer, - width: Int, - height: Int, - rowStride: Int, - metadata: RawMetadata, - aspectRatio: AspectRatio?, - cropRegion: Rect?, - rotation: Int, - exposureBias: Float = 0f, - rawExposureCompensation: Float = 0f, - rawAutoExposure: Boolean = true, - rawBlackPointCorrection: Float = 0f, - rawWhitePointCorrection: Float = 0f, - rawAutoWhiteBalanceEstimate: Boolean = false, - sharpeningValue: Float = 0f, - denoiseValue: Float? = null, - rawDcpId: String? = null, - dcpRenderPlan: DcpRenderPlan? = null, - ): RawHdrRenderResult? = withContext(glDispatcher) { - try { - processInternal( - context = context, - rawData = rawBuffer, - width = width, - height = height, - rowStride = rowStride, - metadata = metadata, - aspectRatio = aspectRatio, - cropRegion = cropRegion, - rotation = rotation, - exposureBias = exposureBias, - rawExposureCompensation = rawExposureCompensation, - rawAutoExposure = rawAutoExposure, - rawBlackPointCorrection = rawBlackPointCorrection, - rawWhitePointCorrection = rawWhitePointCorrection, - rawAutoWhiteBalanceEstimate = rawAutoWhiteBalanceEstimate, - sharpeningValue = sharpeningValue, - denoiseValue = denoiseValue, - rawDcpId = rawDcpId, - dcpRenderPlan = dcpRenderPlan, - includeHdrReference = true - ) - } catch (e: Exception) { - PLog.e(TAG, "Failed to process RAW buffer HDR sources", e) - null - } - } - companion object { private const val TAG = "RawDemosaicProcessor" private const val RAW_HDR_HIGHLIGHT_START = 0.72f @@ -562,39 +488,6 @@ class RawDemosaicProcessor { return@withContext null } - if (dngFile == null && actualMetadata.cfaPattern != RawMetadata.CFA_LINEAR_RGB) { - val linearRawData = processRawBufferNative( - actualRawData, - actualWidth, - actualHeight, - actualRowStride, - actualMetadata.cfaPattern, - actualMetadata.blackLevel, - actualMetadata.whiteLevel, - actualMetadata.whiteBalanceGains, - actualMetadata.colorCorrectionMatrix, - actualMetadata.noiseProfile, - actualMetadata.lensShadingMap, - actualMetadata.lensShadingMapWidth, - actualMetadata.lensShadingMapHeight, - ColorSpace.ProPhoto.xr, ColorSpace.ProPhoto.yr, - ColorSpace.ProPhoto.xg, ColorSpace.ProPhoto.yg, - ColorSpace.ProPhoto.xb, ColorSpace.ProPhoto.yb, - ColorSpace.ProPhoto.xw, ColorSpace.ProPhoto.yw, - rawAutoWhiteBalanceEstimate - ) - if (linearRawData == null) { - PLog.e(TAG, "Native RAW buffer demosaic failed") - return@withContext null - } - dngRawDataCleanup = linearRawData - actualRawData = linearRawData.rawData - actualWidth = linearRawData.width - actualHeight = linearRawData.height - actualRowStride = linearRawData.rowStride - actualMetadata = convertDngRawDataToMetadata(linearRawData, exposureBias, actualMetadata) - } - val resolvedDcpRenderPlan = dcpRenderPlan ?: rawDcpId?.let { dcpId -> val dcpInfo = ContentRepository.getInstance(context).getAvailableDcps().firstOrNull { it.id == dcpId } if (dcpInfo == null) { @@ -713,9 +606,7 @@ class RawDemosaicProcessor { context = context, metadata = actualMetadata, sourceTextureId = demosaicTextureId, - dcpRenderPlan = resolvedDcpRenderPlan, - rotation = actualRotation, - bounds = bounds + dcpRenderPlan = resolvedDcpRenderPlan ) } else { 0f @@ -1948,8 +1839,7 @@ class RawDemosaicProcessor { inputTextureId: Int = demosaicTextureId, dcpRenderPlan: DcpRenderPlan? = null, viewportWidth: Int = metadata.width, - viewportHeight: Int = metadata.height, - texMatrix: FloatArray? = null + viewportHeight: Int = metadata.height ) { val curveLut = ACR3Curve.samples() val outputTransform = computeWorkingToOutputTransform(ColorSpace.ProPhoto, ColorSpace.SRGB) @@ -1988,12 +1878,11 @@ class RawDemosaicProcessor { 1, false, transposeMatrix3x3(outputTransform), 0 ) - val inputTexMatrix = texMatrix ?: FloatArray(16).also { - GlMatrix.setIdentityM(it, 0) - } + val identityMatrix = FloatArray(16) + GlMatrix.setIdentityM(identityMatrix, 0) GLES30.glUniformMatrix4fv( GLES30.glGetUniformLocation(combinedProgram, "uTexMatrix"), - 1, false, inputTexMatrix, 0 + 1, false, identityMatrix, 0 ) checkGlError("renderCombinedPass matrices") drawQuad(combinedProgram) @@ -2247,12 +2136,10 @@ class RawDemosaicProcessor { context: Context, metadata: RawMetadata, sourceTextureId: Int, - dcpRenderPlan: DcpRenderPlan?, - rotation: Int, - bounds: Rect + dcpRenderPlan: DcpRenderPlan? ): Float { - val meteringWidth = minOf(bounds.width(), 256).coerceAtLeast(1) - val meteringHeight = minOf(bounds.height(), 256).coerceAtLeast(1) + val meteringWidth = minOf(metadata.width, 256).coerceAtLeast(1) + val meteringHeight = minOf(metadata.height, 256).coerceAtLeast(1) return try { setupCombinedFramebuffer(meteringWidth, meteringHeight) renderCombinedPass( @@ -2260,8 +2147,7 @@ class RawDemosaicProcessor { inputTextureId = sourceTextureId, dcpRenderPlan = dcpRenderPlan, viewportWidth = meteringWidth, - viewportHeight = meteringHeight, - texMatrix = buildOutputTexMatrix(rotation, metadata.width, metadata.height, bounds) + viewportHeight = meteringHeight ) val buffer = ByteBuffer .allocateDirect(meteringWidth * meteringHeight * 4) @@ -2358,19 +2244,6 @@ class RawDemosaicProcessor { GLES30.glViewport(0, 0, bounds.width(), bounds.height()) GLES30.glClear(GLES30.GL_COLOR_BUFFER_BIT) GLES30.glUseProgram(passthroughProgram) - val texMatrix = buildOutputTexMatrix(rotation, width, height, bounds) - GLES30.glUniformMatrix4fv( - GLES30.glGetUniformLocation(passthroughProgram, "uTexMatrix"), - 1, false, texMatrix, 0 - ) - GLES30.glActiveTexture(GLES30.GL_TEXTURE0) - GLES30.glBindTexture(GLES30.GL_TEXTURE_2D, sourceTextureId) - GLES30.glUniform1i(GLES30.glGetUniformLocation(passthroughProgram, "uTexture"), 0) - drawQuad(passthroughProgram) - checkGlError("renderOutputPass") - } - - private fun buildOutputTexMatrix(rotation: Int, width: Int, height: Int, bounds: Rect): FloatArray { val isSwapped = rotation == 90 || rotation == 270 val cropW: Float val cropH: Float @@ -2393,7 +2266,15 @@ class RawDemosaicProcessor { GlMatrix.scaleM(texMatrix, 0, cropW / width, cropH / height, 1.0f) GlMatrix.rotateM(texMatrix, 0, -rotation.toFloat(), 0f, 0f, 1f) GlMatrix.translateM(texMatrix, 0, -0.5f, -0.5f, 0f) - return texMatrix + GLES30.glUniformMatrix4fv( + GLES30.glGetUniformLocation(passthroughProgram, "uTexMatrix"), + 1, false, texMatrix, 0 + ) + GLES30.glActiveTexture(GLES30.GL_TEXTURE0) + GLES30.glBindTexture(GLES30.GL_TEXTURE_2D, sourceTextureId) + GLES30.glUniform1i(GLES30.glGetUniformLocation(passthroughProgram, "uTexture"), 0) + drawQuad(passthroughProgram) + checkGlError("renderOutputPass") } private fun drawQuad(program: Int) { 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 33bddf6e..c3fae9c1 100644 --- a/app/src/main/java/com/hinnka/mycamera/raw/RawMetadata.kt +++ b/app/src/main/java/com/hinnka/mycamera/raw/RawMetadata.kt @@ -565,28 +565,20 @@ data class RawMetadata( mS[6] * sR, mS[7] * sG, mS[8] * sB ) - // 2. 色彩适应:从目标色域白点转换到 XYZ(D50) 基准。 - // ProPhoto 等 D50 色域不能再额外套一次 D65 -> D50,否则 RAW CCM 会整体偏色。 + // 2. 色彩适应:从 XYZ(D65) 转换到 XYZ(D50) 基准 + // 使用标准 Bradford 矩阵 val BRADFORD_D65_TO_D50 = floatArrayOf( 1.0478112f, 0.0228866f, -0.0501270f, 0.0295424f, 0.9904844f, -0.0170491f, -0.0092345f, 0.0150436f, 0.7521316f ) - val gamutToXYZD50 = if (isD50WhitePoint(xw, yw)) { - gamutToXYZD65 - } else { - multiplyMatrix3x3(BRADFORD_D65_TO_D50, gamutToXYZD65) - } + val gamutToXYZD50 = multiplyMatrix3x3(BRADFORD_D65_TO_D50, gamutToXYZD65) // 3. 求逆:得到最终的 XYZ(D50) -> Gamut 转换矩阵 return invertMatrix3x3(gamutToXYZD50) } - private fun isD50WhitePoint(x: Float, y: Float): Boolean { - return kotlin.math.abs(x - 0.3457f) < 0.002f && kotlin.math.abs(y - 0.3585f) < 0.002f - } - /** * 3x3 矩阵求逆 */ 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 7ecaf442..c5e12cc3 100644 --- a/app/src/main/java/com/hinnka/mycamera/utils/RawProcessor.kt +++ b/app/src/main/java/com/hinnka/mycamera/utils/RawProcessor.kt @@ -168,16 +168,7 @@ object RawProcessor { // PLog.d(TAG, "Embedded stacked DNG thumbnail written: ${it.width}x${it.height}") // } - val dngInputBuffer = if (valueDomain == RawBufferValueDomain.NORMALIZED_SENSOR_RANGE) { - val source = rawBuffer.duplicate().order(ByteOrder.nativeOrder()) - source.position(0) - val copy = ByteBuffer.allocateDirect(width * height * 2).order(ByteOrder.nativeOrder()) - copy.put(source) - copy.position(0) - copy - } else { - rawBuffer.duplicate().order(ByteOrder.nativeOrder()) - } + val dngInputBuffer = rawBuffer.duplicate().order(ByteOrder.nativeOrder()) if (valueDomain == RawBufferValueDomain.NORMALIZED_SENSOR_RANGE) { denormalizeNormalizedRawBufferInPlace( rawBuffer = dngInputBuffer,