feat: MGC GuidedUpsample and float sharpen integration
This commit is contained in:
1 parent
bcdb078454
commit
e175865f75
37 files changed
+3257
-675
No files matched your search
@@ -148,6 +148,41 @@ set_source_files_properties(
|
||||
OBJECT_DEPENDS "${MGC_SHARPEN_CAPSULE}"
|
||||
)
|
||||
|
||||
set(
|
||||
MGC_GUIDED_CAPSULE
|
||||
"${CMAKE_CURRENT_SOURCE_DIR}/mgc_denoise_static/mgc_guided_upsample_capsule.bin"
|
||||
)
|
||||
set(
|
||||
MGC_GUIDED_CAPSULE_SHA256
|
||||
"d0708404b1d62561eafcae6b3fd2207f3340da5b0036d403c1c30da18bcd2b98"
|
||||
)
|
||||
if(NOT EXISTS "${MGC_GUIDED_CAPSULE}")
|
||||
message(
|
||||
FATAL_ERROR
|
||||
"MGC GuidedUpsample capsule is missing; restore the tracked "
|
||||
"mgc_denoise_static/mgc_guided_upsample_capsule.bin asset"
|
||||
)
|
||||
endif()
|
||||
file(SHA256 "${MGC_GUIDED_CAPSULE}" MGC_GUIDED_CAPSULE_ACTUAL_SHA256)
|
||||
if(NOT MGC_GUIDED_CAPSULE_ACTUAL_SHA256 STREQUAL MGC_GUIDED_CAPSULE_SHA256)
|
||||
message(FATAL_ERROR "MGC GuidedUpsample capsule hash mismatch")
|
||||
endif()
|
||||
set(
|
||||
MGC_GUIDED_ASM
|
||||
"${CMAKE_CURRENT_BINARY_DIR}/mgc_guided_upsample_static.S"
|
||||
)
|
||||
configure_file(
|
||||
"${CMAKE_CURRENT_SOURCE_DIR}/mgc_denoise_static/mgc_guided_upsample_static.S.in"
|
||||
"${MGC_GUIDED_ASM}"
|
||||
@ONLY
|
||||
)
|
||||
set_source_files_properties(
|
||||
"${MGC_GUIDED_ASM}"
|
||||
PROPERTIES
|
||||
GENERATED TRUE
|
||||
OBJECT_DEPENDS "${MGC_GUIDED_CAPSULE}"
|
||||
)
|
||||
|
||||
set(
|
||||
MGC_SPATIAL_RGB_CAPSULE
|
||||
"${CMAKE_CURRENT_SOURCE_DIR}/mgc_denoise_static/mgc_spatial_rgb_merge_capsule.bin"
|
||||
@@ -304,7 +339,9 @@ add_library(my-native-lib SHARED
|
||||
mgc_denoise_static/mgc_sabre_resolve_jni.cpp
|
||||
mgc_denoise_static/mgc_spatial_rgb_merge_jni.cpp
|
||||
mgc_denoise_static/mgc_spatial_strength_jni.cpp
|
||||
mgc_denoise_static/mgc_guided_upsample_jni.cpp
|
||||
mgc_denoise_static/mgc_sharpen_jni.cpp
|
||||
"${MGC_GUIDED_ASM}"
|
||||
"${MGC_SHARPEN_ASM}"
|
||||
"${MGC_DENOISE_ASM}"
|
||||
"${MGC_DEMOIRE_ASM}"
|
||||
@@ -346,6 +383,7 @@ set_source_files_properties(
|
||||
# multiply/adds and nearest-even U12 rounding. Keep these independent of fast-math.
|
||||
set_source_files_properties(
|
||||
raw_signal_stats_jni.cpp
|
||||
mgc_denoise_static/mgc_guided_upsample_jni.cpp
|
||||
mgc_denoise_static/mgc_sharpen_jni.cpp
|
||||
PROPERTIES
|
||||
COMPILE_OPTIONS "-fno-fast-math;-ffp-contract=off"
|
||||
|
||||
@@ -743,6 +743,11 @@ PHOTON_MGC_DEFINE_HALIDE_ERROR(5ff6938)
|
||||
PHOTON_MGC_DEFINE_HALIDE_ERROR(5ff8944)
|
||||
PHOTON_MGC_DEFINE_HALIDE_ERROR(5ff89a0)
|
||||
|
||||
PHOTON_MGC_DEFINE_HALIDE_ERROR(5f95158)
|
||||
PHOTON_MGC_DEFINE_HALIDE_ERROR(5f95704)
|
||||
PHOTON_MGC_DEFINE_HALIDE_ERROR(5f9579c)
|
||||
PHOTON_MGC_DEFINE_HALIDE_ERROR(5f95a4c)
|
||||
|
||||
#undef PHOTON_MGC_DEFINE_HALIDE_ERROR
|
||||
|
||||
extern "C" __attribute__((visibility("hidden"))) uintptr_t
|
||||
@@ -1883,4 +1888,51 @@ int RunSharpenTo16Bit(
|
||||
sharpen_attenuation_scale);
|
||||
}
|
||||
|
||||
|
||||
// V25 S16 guide uses the same padded Q14 linear YUV domain as FinishRaw.
|
||||
extern "C" int photon_mgc_box_downsample_s16(
|
||||
void*, HalideBuffer*, HalideBuffer*, int, HalideBuffer*);
|
||||
extern "C" int photon_mgc_guided_upsample_s16_to_16_bit(
|
||||
void*, HalideBuffer*, HalideBuffer*, HalideBuffer*, HalideBuffer*, HalideBuffer*,
|
||||
int, float, HalideBuffer*, float, HalideBuffer*, float, HalideBuffer*);
|
||||
|
||||
int RunGuidedBoxDownsample(const int16_t* linear_yuv, int width, int height,
|
||||
int log2_scale, int16_t* low_yuv) {
|
||||
if (!linear_yuv || !low_yuv || width <= 0 || height <= 0 ||
|
||||
width % 128 || height % 16 || log2_scale < 1 || log2_scale > 2) return -1;
|
||||
const int scale = 1 << log2_scale;
|
||||
const HalideDimension full[] = {{0,width,1,0},{0,height,width,0},{0,3,width*height,0}};
|
||||
const HalideDimension low[] = {{0,width/scale,1,0},
|
||||
{0,height/scale,width/scale,0},{0,3,(width/scale)*(height/scale),0}};
|
||||
auto y = MakeBuffer(const_cast<int16_t*>(linear_yuv), {0,16,1}, 2, full);
|
||||
auto uv = MakeBuffer(const_cast<int16_t*>(linear_yuv), {0,16,1}, 3, full);
|
||||
auto out = MakeBuffer(low_yuv, {0,16,1}, 3, low);
|
||||
return photon_mgc_box_downsample_s16(nullptr, &y, &uv, log2_scale, &out);
|
||||
}
|
||||
|
||||
int RunGuidedUpsampleTo16Bit(const int16_t* guide, int guide_width, int guide_height,
|
||||
const int16_t* low_guide, const int16_t* low_output_yuv, int scale,
|
||||
int width, int height, const float curves[30], float attenuation, uint16_t* output) {
|
||||
if (!guide || !low_guide || !low_output_yuv || !curves || !output ||
|
||||
guide_width <= 0 || guide_height <= 0 || guide_width % 128 || guide_height % 16 ||
|
||||
width <= 0 || height <= 0 || width > guide_width || height > guide_height ||
|
||||
(scale != 2 && scale != 4) || !std::isfinite(attenuation) || attenuation < 0) return -1;
|
||||
const int lw = guide_width / scale, lh = guide_height / scale;
|
||||
const HalideDimension full[] = {{0,guide_width,1,0},{0,guide_height,guide_width,0}};
|
||||
const HalideDimension low[] = {{0,lw,1,0},{0,lh,lw,0},{0,3,lw*lh,0}};
|
||||
const HalideDimension curve_dims[] = {{0,1,1,0},{0,5,1,0},{0,3,5,0},{0,2,15,0}};
|
||||
const HalideDimension corner_dims[] = {{0,3,1,0}};
|
||||
const HalideDimension out_dims[] = {{0,width,3,0},{0,(height+1)&~1,width*3,0},{0,3,1,0}};
|
||||
float corner[3] = {};
|
||||
auto g = MakeBuffer(const_cast<int16_t*>(guide), {0,16,1}, 2, full);
|
||||
auto lg = MakeBuffer(const_cast<int16_t*>(low_guide), {0,16,1}, 2, low);
|
||||
auto lo = MakeBuffer(const_cast<int16_t*>(low_output_yuv), {0,16,1}, 3, low);
|
||||
auto cv = MakeBuffer(const_cast<float*>(curves), {2,32,1}, 4, curve_dims);
|
||||
auto cc = MakeBuffer(corner, {2,32,1}, 1, corner_dims);
|
||||
auto out = MakeBuffer(output, {1,16,1}, 3, out_dims);
|
||||
// Non-skin S16 variant: skin buffers and the skin multiplier are unused.
|
||||
return photon_mgc_guided_upsample_s16_to_16_bit(
|
||||
nullptr, &g, nullptr, &lg, &lo, nullptr, scale, 0.f, &cv, attenuation, &cc, 0.f, &out);
|
||||
}
|
||||
|
||||
} // namespace photon::mgc_denoise
|
||||
@@ -229,4 +229,13 @@ int RunSharpenTo16Bit(
|
||||
float sharpen_attenuation_scale,
|
||||
uint16_t* output_interleaved_rgb);
|
||||
|
||||
/** V25 BoxDownsample: padded planar Q14 YUV; output dimensions divide by 2^log2_scale. */
|
||||
int RunGuidedBoxDownsample(const int16_t* linear_yuv, int width, int height,
|
||||
int log2_scale, int16_t* low_yuv);
|
||||
/** V25 GuidedUpsample+sharpen: Q14 linear guides and U12 encoded low YUV.
|
||||
* Output allocates width * round_up(height, 2) * 3 uint16 samples. */
|
||||
int RunGuidedUpsampleTo16Bit(const int16_t* guide, int guide_width, int guide_height,
|
||||
const int16_t* low_guide, const int16_t* low_output_yuv, int scale,
|
||||
int width, int height, const float curves[30], float attenuation, uint16_t* output);
|
||||
|
||||
} // namespace photon::mgc_denoise
|
||||
Binary file not shown.
@@ -0,0 +1,147 @@
|
||||
#include "mgc_denoise_static.h"
|
||||
#include "mgc_sharpen_adapter.h"
|
||||
#include <algorithm>
|
||||
#include <cmath>
|
||||
#include <jni.h>
|
||||
#include <limits>
|
||||
#include <memory>
|
||||
#include <vector>
|
||||
|
||||
namespace {
|
||||
struct GuidedInputs {
|
||||
int width, height, padded_width, padded_height, scale;
|
||||
std::vector<int16_t> guide, low_guide;
|
||||
};
|
||||
void OutOfMemory(JNIEnv *env) {
|
||||
auto type = env->FindClass("java/lang/OutOfMemoryError");
|
||||
if (type)
|
||||
env->ThrowNew(type, "MGC GuidedUpsample storage");
|
||||
}
|
||||
} // namespace
|
||||
|
||||
extern "C" JNIEXPORT jlong JNICALL
|
||||
Java_com_hinnka_mycamera_raw_MgcGuidedUpsample_nativePrepare(
|
||||
JNIEnv *env, jobject, jobject buffer, jint width, jint height, jint log2_scale,
|
||||
jfloatArray gains) {
|
||||
using namespace photon::mgc_denoise;
|
||||
if (!buffer || !gains || env->GetArrayLength(gains) != 3 || width <= 0 ||
|
||||
height <= 0 || width > 65536 || height > 65536 ||
|
||||
log2_scale < 1 || log2_scale > 2)
|
||||
return 0;
|
||||
auto *rgba = static_cast<float *>(env->GetDirectBufferAddress(buffer));
|
||||
if (!rgba ||
|
||||
env->GetDirectBufferCapacity(buffer) < int64_t(width) * height * 16)
|
||||
return 0;
|
||||
float wb[3];
|
||||
env->GetFloatArrayRegion(gains, 0, 3, wb);
|
||||
if (env->ExceptionCheck())
|
||||
return 0;
|
||||
for (float v : wb)
|
||||
if (!std::isfinite(v) || v <= 0)
|
||||
return 0;
|
||||
const int pw = (width + 127) & ~127, ph = (height + 15) & ~15;
|
||||
const int scale = 1 << log2_scale;
|
||||
const size_t n = size_t(pw) * ph, ln = n / (scale * scale);
|
||||
if (n > size_t(std::numeric_limits<int>::max() / 16) ||
|
||||
env->GetDirectBufferCapacity(buffer) < jlong(ln * 16))
|
||||
return 0;
|
||||
try {
|
||||
auto state = std::make_unique<GuidedInputs>();
|
||||
state->width = width;
|
||||
state->height = height;
|
||||
state->padded_width = pw;
|
||||
state->padded_height = ph;
|
||||
state->scale = scale;
|
||||
std::vector<uint16_t> rgb(n * 3);
|
||||
// Same white-balanced Q14 boundary as MgcFullResolutionDenoise.
|
||||
for (int y = 0; y < ph; ++y)
|
||||
for (int x = 0; x < pw; ++x) {
|
||||
const size_t source =
|
||||
(size_t(std::min(y, height - 1)) * width + std::min(x, width - 1)) *
|
||||
4;
|
||||
const size_t dest = size_t(y) * pw + x;
|
||||
for (int c = 0; c < 3; ++c) {
|
||||
const float value = rgba[source + c];
|
||||
if (!std::isfinite(value))
|
||||
return 0;
|
||||
rgb[c * n + dest] = uint16_t(
|
||||
std::lround(std::clamp(value * wb[c], 0.f, 1.f) * 16383.f));
|
||||
}
|
||||
}
|
||||
std::vector<int16_t> yuv(n * 3), low(ln * 3);
|
||||
if (RunRgbRawToYuv(rgb.data(), pw, ph, yuv.data()) != 0)
|
||||
return 0;
|
||||
if (RunGuidedBoxDownsample(yuv.data(), pw, ph, log2_scale, low.data()) != 0)
|
||||
return 0;
|
||||
state->guide.assign(yuv.begin(), yuv.begin() + n);
|
||||
state->low_guide.assign(low.begin(), low.begin() + ln);
|
||||
// The low color branch starts before CCM/DCP/tone; never downsample an
|
||||
// encoded JPEG.
|
||||
std::vector<int16_t> low_rgb(ln * 3);
|
||||
if (RunYuvToRgb(low.data(), pw / scale, ph / scale, low_rgb.data()) != 0)
|
||||
return 0;
|
||||
for (size_t i = 0; i < ln; ++i) {
|
||||
for (int c = 0; c < 3; ++c)
|
||||
rgba[i * 4 + c] = low_rgb[c * ln + i] / 16383.f / wb[c];
|
||||
rgba[i * 4 + 3] = 1.f;
|
||||
}
|
||||
return reinterpret_cast<jlong>(state.release());
|
||||
} catch (const std::bad_alloc &) {
|
||||
OutOfMemory(env);
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
|
||||
extern "C" JNIEXPORT jint JNICALL
|
||||
Java_com_hinnka_mycamera_raw_MgcGuidedUpsample_nativeRender(
|
||||
JNIEnv *env, jobject, jlong handle, jobject buffer, jfloat attenuation,
|
||||
jfloatArray points) {
|
||||
using namespace photon::mgc_denoise;
|
||||
auto *state = reinterpret_cast<GuidedInputs *>(handle);
|
||||
if (!state || !buffer || !points || env->GetArrayLength(points) != 30 ||
|
||||
!std::isfinite(attenuation) || attenuation < 0)
|
||||
return -1;
|
||||
auto *rgba = static_cast<float *>(env->GetDirectBufferAddress(buffer));
|
||||
const size_t n = size_t(state->width) * state->height;
|
||||
const size_t ln = state->low_guide.size();
|
||||
if (!rgba ||
|
||||
env->GetDirectBufferCapacity(buffer) < jlong(std::max(n, ln) * 16))
|
||||
return -1;
|
||||
float curves[30];
|
||||
env->GetFloatArrayRegion(points, 0, 30, curves);
|
||||
if (env->ExceptionCheck())
|
||||
return -1;
|
||||
for (int c = 0; c < 3; ++c)
|
||||
for (int p = 0; p < 5; ++p) {
|
||||
const int i = c * 5 + p;
|
||||
if (!std::isfinite(curves[i]) || !std::isfinite(curves[i + 15]) ||
|
||||
curves[i] < 0 || curves[i + 15] < 0 ||
|
||||
(p == 0 && (curves[i] != 0 || curves[i + 15] != 0)) ||
|
||||
(p > 0 && curves[i] <= curves[i - 1]))
|
||||
return -1;
|
||||
}
|
||||
try {
|
||||
std::vector<int16_t> yuv(ln * 3);
|
||||
std::vector<uint16_t> output(size_t(state->width) *
|
||||
((state->height + 1) & ~1) * 3);
|
||||
if (!SharpenFloatRgbaToYuv(rgba, ln, yuv.data()))
|
||||
return -1;
|
||||
const int result = RunGuidedUpsampleTo16Bit(
|
||||
state->guide.data(), state->padded_width, state->padded_height,
|
||||
state->low_guide.data(), yuv.data(), state->scale, state->width,
|
||||
state->height, curves, attenuation, output.data());
|
||||
if (result)
|
||||
return result;
|
||||
SharpenRgbToFloatRgba(output.data(), n, rgba);
|
||||
return 0;
|
||||
} catch (const std::bad_alloc &) {
|
||||
OutOfMemory(env);
|
||||
return -1;
|
||||
}
|
||||
}
|
||||
|
||||
extern "C" JNIEXPORT void JNICALL
|
||||
Java_com_hinnka_mycamera_raw_MgcGuidedUpsample_nativeRelease(JNIEnv *, jobject,
|
||||
jlong handle) {
|
||||
delete reinterpret_cast<GuidedInputs *>(handle);
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
@@ -7,4 +7,7 @@ namespace photon::mgc_denoise {
|
||||
// adapter.
|
||||
void SharpenRgbaToYuv(const uint8_t *rgba, size_t count, int16_t *yuv);
|
||||
void SharpenRgbToRgba(const uint16_t *rgb, size_t count, uint8_t *rgba);
|
||||
// Encoded RGB in [0,1], retained as float until the original U12 kernel boundary.
|
||||
bool SharpenFloatRgbaToYuv(const float *rgba, size_t count, int16_t *yuv);
|
||||
void SharpenRgbToFloatRgba(const uint16_t *rgb, size_t count, float *rgba);
|
||||
} // namespace photon::mgc_denoise
|
||||
@@ -97,15 +97,44 @@ void SharpenRgbToRgba(const uint16_t *rgb, size_t count, uint8_t *rgba) {
|
||||
rgba[i * 4 + 3] = 255;
|
||||
}
|
||||
}
|
||||
bool SharpenFloatRgbaToYuv(const float *rgba, size_t count, int16_t *yuv) {
|
||||
for (size_t i = 0; i < count; ++i) {
|
||||
for (int c = 0; c < 3; ++c) {
|
||||
if (!std::isfinite(rgba[4 * i + c])) return false;
|
||||
}
|
||||
}
|
||||
#pragma omp parallel for schedule(static) num_threads(4)
|
||||
for (size_t i = 0; i < count; ++i) {
|
||||
const float r = std::clamp(rgba[4 * i], 0.f, 1.f) * 4095.f;
|
||||
const float g = std::clamp(rgba[4 * i + 1], 0.f, 1.f) * 4095.f;
|
||||
const float b = std::clamp(rgba[4 * i + 2], 0.f, 1.f) * 4095.f;
|
||||
for (int c = 0; c < 3; ++c) {
|
||||
yuv[c * count + i] = static_cast<int16_t>(std::clamp<long>(
|
||||
std::lrintf(kMatrix[c * 3] * r + kMatrix[c * 3 + 1] * g +
|
||||
kMatrix[c * 3 + 2] * b), -4095, 4095));
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
void SharpenRgbToFloatRgba(const uint16_t *rgb, size_t count, float *rgba) {
|
||||
#pragma omp parallel for schedule(static) num_threads(4)
|
||||
for (size_t i = 0; i < count; ++i) {
|
||||
for (int c = 0; c < 3; ++c) {
|
||||
rgba[4 * i + c] = std::min<uint16_t>(rgb[3 * i + c], 4095) / 4095.f;
|
||||
}
|
||||
rgba[4 * i + 3] = 1.f;
|
||||
}
|
||||
}
|
||||
} // namespace photon::mgc_denoise
|
||||
|
||||
extern "C" JNIEXPORT jint JNICALL
|
||||
Java_com_hinnka_mycamera_raw_MgcSharpen_nativeSharpenRgba8(
|
||||
Java_com_hinnka_mycamera_raw_MgcSharpen_nativeSharpenRgbaFloat(
|
||||
JNIEnv *env, jobject, jobject rgba_buffer, jobject scratch_buffer,
|
||||
jint width, jint height, jfloat snr, jfloat attenuation, jfloatArray curve_points) {
|
||||
using namespace photon::mgc_denoise;
|
||||
if (!rgba_buffer || !scratch_buffer || !curve_points || width <= 0 || height <= 0 ||
|
||||
!std::isfinite(snr) || snr <= 0 || !std::isfinite(attenuation) ||
|
||||
!std::isfinite(snr) || snr < 0 || !std::isfinite(attenuation) ||
|
||||
attenuation < 0)
|
||||
return -1;
|
||||
const size_t count = size_t(width) * size_t(height);
|
||||
@@ -114,11 +143,11 @@ Java_com_hinnka_mycamera_raw_MgcSharpen_nativeSharpenRgba8(
|
||||
const size_t scratch_bytes = (count + output_count) * 6;
|
||||
if (scratch_bytes > size_t(std::numeric_limits<int>::max()))
|
||||
return -1;
|
||||
auto *rgba = static_cast<uint8_t *>(env->GetDirectBufferAddress(rgba_buffer));
|
||||
auto *rgba = static_cast<float *>(env->GetDirectBufferAddress(rgba_buffer));
|
||||
auto *yuv =
|
||||
static_cast<int16_t *>(env->GetDirectBufferAddress(scratch_buffer));
|
||||
if (!rgba || !yuv ||
|
||||
env->GetDirectBufferCapacity(rgba_buffer) < jlong(count * 4) ||
|
||||
env->GetDirectBufferCapacity(rgba_buffer) < jlong(count * 4 * sizeof(float)) ||
|
||||
env->GetDirectBufferCapacity(scratch_buffer) < jlong(scratch_bytes))
|
||||
return -1;
|
||||
auto *rgb = reinterpret_cast<uint16_t *>(yuv + count * 3);
|
||||
@@ -143,14 +172,14 @@ Java_com_hinnka_mycamera_raw_MgcSharpen_nativeSharpenRgba8(
|
||||
constexpr float corner_correction[3] = {0, 0, 0};
|
||||
using Clock = std::chrono::steady_clock;
|
||||
const auto start = Clock::now();
|
||||
SharpenRgbaToYuv(rgba, count, yuv);
|
||||
if (!SharpenFloatRgbaToYuv(rgba, count, yuv)) return -1;
|
||||
const auto converted = Clock::now();
|
||||
const int result = RunSharpenTo16Bit(
|
||||
yuv, width, height, curves, corner_correction, attenuation, rgb);
|
||||
if (result != 0)
|
||||
return result;
|
||||
const auto sharpened = Clock::now();
|
||||
SharpenRgbToRgba(rgb, count, rgba);
|
||||
SharpenRgbToFloatRgba(rgb, count, rgba);
|
||||
const auto finish = Clock::now();
|
||||
const auto ms = [](auto a, auto b) {
|
||||
return std::chrono::duration<double, std::milli>(b - a).count();
|
||||
@@ -165,7 +194,7 @@ Java_com_hinnka_mycamera_raw_MgcSharpen_nativeSharpenRgba8(
|
||||
}
|
||||
|
||||
extern "C" JNIEXPORT jboolean JNICALL
|
||||
Java_com_hinnka_mycamera_raw_MgcSharpen_nativeUploadRgba8(
|
||||
Java_com_hinnka_mycamera_raw_RawFloatTextureTransfer_nativeUpload(
|
||||
JNIEnv *, jobject, jint pbo, jint texture, jint width, jint height) {
|
||||
if (pbo <= 0 || texture <= 0 || width <= 0 || height <= 0)
|
||||
return JNI_FALSE;
|
||||
@@ -175,7 +204,7 @@ Java_com_hinnka_mycamera_raw_MgcSharpen_nativeUploadRgba8(
|
||||
glPixelStorei(GL_UNPACK_ALIGNMENT, 1);
|
||||
glPixelStorei(GL_UNPACK_ROW_LENGTH, 0);
|
||||
glTexSubImage2D(GL_TEXTURE_2D, 0, 0, 0, width, height, GL_RGBA,
|
||||
GL_UNSIGNED_BYTE, nullptr);
|
||||
GL_FLOAT, nullptr);
|
||||
const GLenum error = glGetError();
|
||||
glBindBuffer(GL_PIXEL_UNPACK_BUFFER, 0);
|
||||
return error == GL_NO_ERROR ? JNI_TRUE : JNI_FALSE;
|
||||
|
||||
@@ -58,6 +58,7 @@ import com.hinnka.mycamera.raw.RawDefaultCropOverride
|
||||
import com.hinnka.mycamera.raw.RawDngProfilePreparation
|
||||
import com.hinnka.mycamera.raw.RawDngProfilePreparationOptions
|
||||
import com.hinnka.mycamera.raw.RawDngCaptureProfilePreparer
|
||||
import com.hinnka.mycamera.raw.RawOutputScaling
|
||||
import com.hinnka.mycamera.raw.RawDemosaicProcessor
|
||||
import com.hinnka.mycamera.raw.RawMetadata
|
||||
import com.hinnka.mycamera.raw.RawRenderingEngine
|
||||
@@ -2393,6 +2394,7 @@ object GalleryManager {
|
||||
rawToneMappingParameters = updatedMetadata.rawToneMappingParameters,
|
||||
rawCfaCorrectionMode = updatedMetadata.rawCfaCorrectionMode,
|
||||
rawBlackBorderCrop = updatedMetadata.rawBlackBorderCrop,
|
||||
rawOutputScale = RawOutputScaling.read(updatedMetadata.customProperties),
|
||||
spectralFilmStock = updatedMetadata.spectralFilmStock,
|
||||
spectralFilmPrint = updatedMetadata.spectralFilmPrint,
|
||||
spectralFilmTuning = SpectralFilmTuning(
|
||||
@@ -2487,6 +2489,7 @@ object GalleryManager {
|
||||
rawToneMappingParameters = updatedMetadata.rawToneMappingParameters,
|
||||
rawCfaCorrectionMode = updatedMetadata.rawCfaCorrectionMode,
|
||||
rawBlackBorderCrop = updatedMetadata.rawBlackBorderCrop,
|
||||
rawOutputScale = RawOutputScaling.read(updatedMetadata.customProperties),
|
||||
spectralFilmStock = updatedMetadata.spectralFilmStock,
|
||||
spectralFilmPrint = updatedMetadata.spectralFilmPrint,
|
||||
spectralFilmTuning = SpectralFilmTuning(
|
||||
@@ -3394,7 +3397,6 @@ object GalleryManager {
|
||||
frames = effectiveRawStackFrames,
|
||||
cfaPattern = stackCfaPattern,
|
||||
outputMode = rawMaxSpatialOutputMode,
|
||||
outputScale = rawStackOutputScale,
|
||||
masterBlackLevel = stackBlackLevel,
|
||||
whiteLevel = stackWhiteLevel,
|
||||
whiteBalanceGains = rawMetadata.whiteBalanceGains,
|
||||
@@ -3508,7 +3510,6 @@ object GalleryManager {
|
||||
gpuLinearRgbSource = finalStackResult.gpuLinearRgbSource,
|
||||
gpuBayerSource = finalStackResult.gpuBayerSource,
|
||||
metadata = mergeOutputMetadata,
|
||||
outputScale = rawStackOutputScale,
|
||||
sourcePixelsIncludeLensShadingCorrection =
|
||||
finalStackResult.lensShadingCorrectionApplied,
|
||||
applyLensShadingCorrection = applyRawLensShading,
|
||||
@@ -3556,13 +3557,13 @@ object GalleryManager {
|
||||
mgcDenoiseTuningSnr = null,
|
||||
)
|
||||
|
||||
val outputRawBlackBorderCrop =
|
||||
metadata.rawBlackBorderCrop.scaledForOutput(rawStackOutputScale)
|
||||
val stackedMetadata = metadata
|
||||
.withNormalizedRawLevelCorrectionsCleared("MGC default-denoised RAW stack")
|
||||
.copy(
|
||||
cropRegion = null,
|
||||
rawBlackBorderCrop = outputRawBlackBorderCrop,
|
||||
customProperties = RawOutputScaling.write(
|
||||
metadata.customProperties, rawStackOutputScale,
|
||||
),
|
||||
// These fields describe the processor-specific FinishRaw denoise already
|
||||
// baked into LinearRaw; the merge itself remains represented by the pixels.
|
||||
rawDenoiseValue = if (defaultDenoiseRequested) {
|
||||
@@ -3576,14 +3577,6 @@ object GalleryManager {
|
||||
0f
|
||||
},
|
||||
)
|
||||
if (outputRawBlackBorderCrop != metadata.rawBlackBorderCrop) {
|
||||
PLog.i(
|
||||
TAG,
|
||||
"RAWmax black border crop mapped to output scale: " +
|
||||
"scale=$rawStackOutputScale native=${metadata.rawBlackBorderCrop} " +
|
||||
"output=$outputRawBlackBorderCrop"
|
||||
)
|
||||
}
|
||||
|
||||
var updatedMetadata: MediaMetadata = stackedMetadata
|
||||
val rawSharpening = updatedMetadata.sharpening
|
||||
@@ -3738,6 +3731,7 @@ object GalleryManager {
|
||||
rawToneMappingParameters = updatedMetadata.rawToneMappingParameters,
|
||||
rawCfaCorrectionMode = updatedMetadata.rawCfaCorrectionMode,
|
||||
rawBlackBorderCrop = updatedMetadata.rawBlackBorderCrop,
|
||||
rawOutputScale = RawOutputScaling.read(updatedMetadata.customProperties),
|
||||
spectralFilmStock = updatedMetadata.spectralFilmStock,
|
||||
spectralFilmPrint = updatedMetadata.spectralFilmPrint,
|
||||
spectralFilmTuning = SpectralFilmTuning(
|
||||
@@ -3830,6 +3824,7 @@ object GalleryManager {
|
||||
rawToneMappingParameters = updatedMetadata.rawToneMappingParameters,
|
||||
rawCfaCorrectionMode = updatedMetadata.rawCfaCorrectionMode,
|
||||
rawBlackBorderCrop = updatedMetadata.rawBlackBorderCrop,
|
||||
rawOutputScale = RawOutputScaling.read(updatedMetadata.customProperties),
|
||||
spectralFilmStock = updatedMetadata.spectralFilmStock,
|
||||
spectralFilmPrint = updatedMetadata.spectralFilmPrint,
|
||||
spectralFilmTuning = SpectralFilmTuning(
|
||||
@@ -4112,6 +4107,7 @@ object GalleryManager {
|
||||
rawToneMappingParameters = updatedMetadata.rawToneMappingParameters,
|
||||
rawCfaCorrectionMode = updatedMetadata.rawCfaCorrectionMode,
|
||||
rawBlackBorderCrop = updatedMetadata.rawBlackBorderCrop,
|
||||
rawOutputScale = RawOutputScaling.read(updatedMetadata.customProperties),
|
||||
spectralFilmStock = updatedMetadata.spectralFilmStock,
|
||||
spectralFilmPrint = updatedMetadata.spectralFilmPrint,
|
||||
spectralFilmTuning = SpectralFilmTuning(
|
||||
@@ -5563,6 +5559,7 @@ object GalleryManager {
|
||||
rawToneMappingParameters = updatedMetadata.rawToneMappingParameters,
|
||||
rawCfaCorrectionMode = updatedMetadata.rawCfaCorrectionMode,
|
||||
rawBlackBorderCrop = updatedMetadata.rawBlackBorderCrop,
|
||||
rawOutputScale = RawOutputScaling.read(updatedMetadata.customProperties),
|
||||
spectralFilmStock = updatedMetadata.spectralFilmStock,
|
||||
spectralFilmPrint = updatedMetadata.spectralFilmPrint,
|
||||
spectralFilmTuning = SpectralFilmTuning(
|
||||
@@ -5754,6 +5751,7 @@ object GalleryManager {
|
||||
),
|
||||
rawCfaCorrectionMode = updatedMetadata?.rawCfaCorrectionMode,
|
||||
rawBlackBorderCrop = rawMetadata.rawBlackBorderCrop,
|
||||
rawOutputScale = RawOutputScaling.read(rawMetadata.customProperties),
|
||||
spectralFilmStock = updatedMetadata?.spectralFilmStock,
|
||||
spectralFilmPrint = updatedMetadata?.spectralFilmPrint,
|
||||
spectralFilmTuning = SpectralFilmTuning(
|
||||
|
||||
@@ -26,6 +26,7 @@ import com.hinnka.mycamera.lut.LutManager
|
||||
import com.hinnka.mycamera.processor.PhotonSensorSizeTuning
|
||||
import com.hinnka.mycamera.processor.DepthBokehProcessor
|
||||
import com.hinnka.mycamera.processor.BokehStyle
|
||||
import com.hinnka.mycamera.raw.RawOutputScaling
|
||||
import com.hinnka.mycamera.raw.RawDemosaicProcessor
|
||||
import com.hinnka.mycamera.raw.RawHdrRenderResult
|
||||
import com.hinnka.mycamera.raw.RawMetadata
|
||||
@@ -604,6 +605,7 @@ class PhotoProcessor(
|
||||
rawToneMappingParameters = metadata.rawToneMappingParameters,
|
||||
rawCfaCorrectionMode = metadata.rawCfaCorrectionMode,
|
||||
rawBlackBorderCrop = metadata.rawBlackBorderCrop,
|
||||
rawOutputScale = RawOutputScaling.read(metadata.customProperties),
|
||||
spectralFilmStock = metadata.spectralFilmStock,
|
||||
spectralFilmPrint = metadata.spectralFilmPrint,
|
||||
spectralFilmTuning = SpectralFilmTuning(
|
||||
@@ -688,6 +690,7 @@ class PhotoProcessor(
|
||||
rawToneMappingParameters = metadata.rawToneMappingParameters,
|
||||
rawCfaCorrectionMode = metadata.rawCfaCorrectionMode,
|
||||
rawBlackBorderCrop = metadata.rawBlackBorderCrop,
|
||||
rawOutputScale = RawOutputScaling.read(metadata.customProperties),
|
||||
spectralFilmStock = metadata.spectralFilmStock,
|
||||
spectralFilmPrint = metadata.spectralFilmPrint,
|
||||
spectralFilmTuning = SpectralFilmTuning(
|
||||
|
||||
@@ -1,7 +1,6 @@
|
||||
package com.hinnka.mycamera.processor
|
||||
|
||||
import android.graphics.Rect
|
||||
import com.hinnka.mycamera.camera.MultiFrameConfig
|
||||
import com.hinnka.mycamera.utils.PLog
|
||||
|
||||
/**
|
||||
@@ -28,14 +27,12 @@ internal class GlesMgcRawFusion(
|
||||
private val lensShadingHeight: Int,
|
||||
private val outputMode: MgcSpatialOutputMode,
|
||||
private val mergeMethod: MgcMergeMethod,
|
||||
outputScale: Float,
|
||||
private val useCurrentGlContext: Boolean,
|
||||
private val exportGpuLinearRgbSource: Boolean,
|
||||
private val gpuLinearRgbStorage: GpuLinearRgbStorage,
|
||||
) {
|
||||
private val width = sourceBounds.width()
|
||||
private val height = sourceBounds.height()
|
||||
private val outputScale = MultiFrameConfig.normalizeOutputScale(outputScale)
|
||||
|
||||
fun processFrames(frames: List<RawStackFrame>): RawStackResult? {
|
||||
if (frames.isEmpty()) return null
|
||||
@@ -121,7 +118,6 @@ internal class GlesMgcRawFusion(
|
||||
lensShading = lensShading,
|
||||
lensShadingWidth = lensShadingWidth,
|
||||
lensShadingHeight = lensShadingHeight,
|
||||
outputScale = outputScale,
|
||||
useCurrentGlContext = useCurrentGlContext,
|
||||
exportGpuLinearRgbSource = exportGpuLinearRgbSource,
|
||||
gpuLinearRgbStorage = gpuLinearRgbStorage,
|
||||
@@ -198,7 +194,7 @@ internal class GlesMgcRawFusion(
|
||||
"normal=${normalIndices.size} long=${longIndices.size} " +
|
||||
"ultrashort=${if (shortIndex != null) 1 else 0} " +
|
||||
"shortRatio=${shortRatio ?: "none"} excluded=${excludedIndices.size} " +
|
||||
"outputScale=$outputScale AI alignment=disabled",
|
||||
"AI alignment=disabled",
|
||||
)
|
||||
return GlesMgcRawSpatialStacker(
|
||||
width = width,
|
||||
@@ -214,7 +210,6 @@ internal class GlesMgcRawFusion(
|
||||
lensShadingHeight = lensShadingHeight,
|
||||
outputMode = outputMode,
|
||||
mergeMethod = mergeMethod,
|
||||
outputScale = outputScale,
|
||||
useCurrentGlContext = useCurrentGlContext,
|
||||
exportGpuLinearRgbSource = exportGpuLinearRgbSource,
|
||||
gpuLinearRgbStorage = gpuLinearRgbStorage,
|
||||
|
||||
@@ -22,7 +22,6 @@ internal class GlesMgcRawSabreProcessor(
|
||||
private val lensShading: FloatArray?,
|
||||
private val lensShadingWidth: Int,
|
||||
private val lensShadingHeight: Int,
|
||||
private val outputScale: Float,
|
||||
private val useCurrentGlContext: Boolean,
|
||||
private val exportGpuLinearRgbSource: Boolean,
|
||||
private val gpuLinearRgbStorage: GpuLinearRgbStorage,
|
||||
@@ -71,7 +70,6 @@ internal class GlesMgcRawSabreProcessor(
|
||||
lensShadingHeight = lensShadingHeight,
|
||||
outputMode = MgcSpatialOutputMode.RGB,
|
||||
mergeMethod = MgcMergeMethod.SABRE,
|
||||
outputScale = outputScale,
|
||||
useCurrentGlContext = useCurrentGlContext,
|
||||
exportGpuLinearRgbSource = exportGpuLinearRgbSource,
|
||||
gpuLinearRgbStorage = gpuLinearRgbStorage,
|
||||
|
||||
@@ -769,28 +769,4 @@ internal object GlesMgcRawSabreShaders {
|
||||
}
|
||||
""".trimIndent()
|
||||
|
||||
/** Lanczos-3 export scaling after native-grid fusion, ResolveSabre and VGN. */
|
||||
val resampleOutputLanczos = """
|
||||
#version 300 es
|
||||
precision highp float;
|
||||
precision highp int;
|
||||
precision highp sampler2D;
|
||||
uniform sampler2D uSource;
|
||||
uniform ivec2 uSourceSize;
|
||||
uniform ivec2 uOutputSize;
|
||||
layout(location = 0) out highp uvec4 oRgb16;
|
||||
|
||||
vec3 lanczosSource(ivec2 p) {
|
||||
return texelFetch(uSource, clamp(p, ivec2(0), uSourceSize - ivec2(1)), 0).rgb;
|
||||
}
|
||||
|
||||
${GlesLanczosResampling.sampleRgb.prependIndent(" ")}
|
||||
|
||||
void main() {
|
||||
vec2 sourcePosition = gl_FragCoord.xy *
|
||||
vec2(uSourceSize) / vec2(uOutputSize) - vec2(0.5);
|
||||
vec3 rgb = sampleLanczosRgb(sourcePosition);
|
||||
oRgb16 = uvec4(uvec3(round(clamp(rgb, 0.0, 1.0) * 65504.0)), 65535u);
|
||||
}
|
||||
""".trimIndent()
|
||||
}
|
||||
@@ -1414,48 +1414,7 @@ internal object GlesMgcRawSpatialShaders {
|
||||
}
|
||||
""".trimIndent()
|
||||
|
||||
/** Horizontal half of the Lanczos-3 output-grid resampler. */
|
||||
val resampleAotRgbHorizontal = """
|
||||
#version 300 es
|
||||
precision highp float;
|
||||
precision highp int;
|
||||
precision highp sampler2D;
|
||||
uniform sampler2D uChannelPlane;
|
||||
uniform ivec2 uSourceSize;
|
||||
uniform int uOutputWidth;
|
||||
out float oChannel;
|
||||
|
||||
${GlesLanczosResampling.kernel.prependIndent(" ")}
|
||||
|
||||
void main() {
|
||||
ivec2 outputPixel = ivec2(gl_FragCoord.xy);
|
||||
float sourceX = (float(outputPixel.x) + 0.5) *
|
||||
float(uSourceSize.x) / float(uOutputWidth) - 0.5;
|
||||
int baseX = int(floor(sourceX));
|
||||
float fraction = sourceX - float(baseX);
|
||||
float total = 0.0;
|
||||
float totalWeight = 0.0;
|
||||
for (int x = -2; x <= 3; ++x) {
|
||||
float weight = lanczosWeight(float(x) - fraction);
|
||||
int sampleX = clamp(baseX + x, 0, uSourceSize.x - 1);
|
||||
total += texelFetch(
|
||||
uChannelPlane,
|
||||
ivec2(sampleX, outputPixel.y),
|
||||
0
|
||||
).r * weight;
|
||||
totalWeight += weight;
|
||||
}
|
||||
oChannel = total / max(totalWeight, 1.0e-8);
|
||||
}
|
||||
""".trimIndent()
|
||||
|
||||
/**
|
||||
* Converts the original MGC MergeRgbRaw16F16 planar Q14 output to the stacker's RGB16
|
||||
* boundary. The AOT output is already un-white-balanced camera RGB; WB is used only by the
|
||||
* AOT's internal green guide and must not be divided out again here. When the requested output
|
||||
* is larger than the native AOT grid, this pass applies the vertical half of the Lanczos-3
|
||||
* resampler after [resampleAotRgbHorizontal].
|
||||
*/
|
||||
/** Converts native planar Q14 camera RGB to RGB16, without resampling before FinishRaw. */
|
||||
val normalizeAotRgb16 = """
|
||||
#version 300 es
|
||||
precision highp float;
|
||||
@@ -1463,42 +1422,15 @@ internal object GlesMgcRawSpatialShaders {
|
||||
precision highp sampler2D;
|
||||
uniform sampler2D uChannelPlane;
|
||||
uniform sampler2D uLensShading;
|
||||
uniform ivec2 uSourceSize;
|
||||
uniform ivec2 uOutputSize;
|
||||
uniform float uOutputExposureScale;
|
||||
uniform int uUseLensShading;
|
||||
uniform int uResampleVertical;
|
||||
uniform int uChannel;
|
||||
layout(location = 0) out highp uvec4 oRgb16;
|
||||
|
||||
${GlesLanczosResampling.kernel.prependIndent(" ")}
|
||||
|
||||
float sampleChannel(ivec2 outputPixel) {
|
||||
if (uResampleVertical == 0) {
|
||||
return texelFetch(uChannelPlane, outputPixel, 0).r;
|
||||
}
|
||||
float sourceY = (float(outputPixel.y) + 0.5) *
|
||||
float(uSourceSize.y) / float(uOutputSize.y) - 0.5;
|
||||
int baseY = int(floor(sourceY));
|
||||
float fraction = sourceY - float(baseY);
|
||||
float total = 0.0;
|
||||
float totalWeight = 0.0;
|
||||
for (int y = -2; y <= 3; ++y) {
|
||||
float weight = lanczosWeight(float(y) - fraction);
|
||||
int sampleY = clamp(baseY + y, 0, uSourceSize.y - 1);
|
||||
total += texelFetch(
|
||||
uChannelPlane,
|
||||
ivec2(outputPixel.x, sampleY),
|
||||
0
|
||||
).r * weight;
|
||||
totalWeight += weight;
|
||||
}
|
||||
return total / max(totalWeight, 1.0e-8);
|
||||
}
|
||||
|
||||
void main() {
|
||||
ivec2 p = ivec2(gl_FragCoord.xy);
|
||||
float value = sampleChannel(p) * (1.0 / 16384.0);
|
||||
float value = texelFetch(uChannelPlane, p, 0).r * (1.0 / 16384.0);
|
||||
if (uUseLensShading != 0) {
|
||||
vec2 uv = (vec2(p) + vec2(0.5)) / vec2(uOutputSize);
|
||||
vec4 shading = texture(uLensShading, clamp(uv, vec2(0.0), vec2(1.0)));
|
||||
|
||||
@@ -47,10 +47,8 @@ internal fun resolveFusionReferenceSignal(
|
||||
* kernel units and SNR tuning range. The Bayer output preserves the CFA lattice. The RGB output
|
||||
* executes MGC 9.7.047 V25's complete native-grid MergeRgbRaw16F16 AOT, including its internal
|
||||
* full-resolution green reconstruction. Sabre likewise completes fusion, ResolveSabre and VGN on
|
||||
* the native grid. Requested larger RGB outputs are export-size transforms produced from those
|
||||
* completed camera-RGB results with the Lanczos-3 resampling kernel; they are not sensor-detail
|
||||
* super-resolution. MGC alignment, rejection, Bento admission and propagated-noise postprocessing
|
||||
* remain authoritative.
|
||||
* the native grid. Display scaling follows FinishRaw/GuidedUpsample in the RAW renderer.
|
||||
* MGC alignment, rejection, Bento admission and propagated-noise postprocessing remain authoritative.
|
||||
*/
|
||||
internal class GlesMgcRawSpatialStacker(
|
||||
private val width: Int,
|
||||
@@ -69,7 +67,6 @@ internal class GlesMgcRawSpatialStacker(
|
||||
MgcSpatialOutputMode.BAYER -> MgcMergeMethod.SPATIAL_BAYER
|
||||
MgcSpatialOutputMode.RGB -> MgcMergeMethod.SPATIAL_RGB
|
||||
},
|
||||
outputScale: Float,
|
||||
private val useCurrentGlContext: Boolean,
|
||||
private val exportGpuLinearRgbSource: Boolean,
|
||||
private val gpuLinearRgbStorage: GpuLinearRgbStorage = GpuLinearRgbStorage.RGBA16UI,
|
||||
@@ -413,20 +410,11 @@ internal class GlesMgcRawSpatialStacker(
|
||||
private val mergeWeightHeight = rejectionGeometry.mergeWeightHeight
|
||||
private val rejectionFilterWidth = rejectionGeometry.filterWidth
|
||||
private val rejectionFilterHeight = rejectionGeometry.filterHeight
|
||||
private val normalizedOutputScale = MultiFrameConfig.normalizeOutputScale(outputScale)
|
||||
private val outputWidth = if (outputMode == MgcSpatialOutputMode.RGB) {
|
||||
MultiFrameConfig.scaledRawOutputDimension(width, normalizedOutputScale)
|
||||
} else {
|
||||
width
|
||||
}
|
||||
private val outputHeight = if (outputMode == MgcSpatialOutputMode.RGB) {
|
||||
MultiFrameConfig.scaledRawOutputDimension(height, normalizedOutputScale)
|
||||
} else {
|
||||
height
|
||||
}
|
||||
private val outputWidth = width
|
||||
private val outputHeight = height
|
||||
// MergeRgbRaw16F16 is a native-grid merge: output coordinates are RAW coordinates and samples
|
||||
// outside the RAW extent use its mirror boundary. Only its private planar allocation is padded
|
||||
// to complete 16x16 tiles; scaling happens after the AOT result has been materialized.
|
||||
// to complete 16x16 tiles. Display scaling belongs after FinishRaw/GuidedUpsample.
|
||||
private val rgbAotStorageWidth = ceilDiv(width, RGB_AOT_TILE_SIZE) * RGB_AOT_TILE_SIZE
|
||||
private val rgbAotStorageHeight = ceilDiv(height, RGB_AOT_TILE_SIZE) * RGB_AOT_TILE_SIZE
|
||||
private val sensorWhiteLevelCode = max(1, whiteLevel)
|
||||
@@ -531,12 +519,10 @@ internal class GlesMgcRawSpatialStacker(
|
||||
private var sabreReciprocalGreenWeightProgram = 0
|
||||
private var sabreDehomogenizeProgram = 0
|
||||
private var sabreOutputTransformProgram = 0
|
||||
private var sabreResampleOutputProgram = 0
|
||||
private var currentMergeCovariance = 0
|
||||
private var mergeRgbProgram = 0
|
||||
private var normalizeBayerProgram = 0
|
||||
private var normalizeRgbProgram = 0
|
||||
private var resampleAotRgbHorizontalProgram = 0
|
||||
private var normalizeAotRgbProgram = 0
|
||||
private var copyRgb16ToFloatProgram = 0
|
||||
private var rgbChromaPostprocessor: GlesMgcSpatialRgbChromaPostprocessor? = null
|
||||
@@ -2470,7 +2456,6 @@ internal class GlesMgcRawSpatialStacker(
|
||||
sabreResolvedRgb = null
|
||||
releaseSabreMergePhaseTextures(nativeResolvedPlanes)
|
||||
val lensShadingTexture = createLensShadingTexture()
|
||||
val resampleOutput = outputWidth != width || outputHeight != height
|
||||
val fullOutput = MgcSpatialRgbRect(0, 0, width, height)
|
||||
val fullOutputTile = MgcSpatialRgbTile(index = 0, outputCore = fullOutput)
|
||||
val chromaPostprocessor = checkNotNull(rgbChromaPostprocessor) {
|
||||
@@ -2485,7 +2470,7 @@ internal class GlesMgcRawSpatialStacker(
|
||||
output = chromaPostprocessor.normalizationTargetTexture(),
|
||||
)
|
||||
chromaPostprocessor.markTileWritten(fullOutputTile)
|
||||
if (!exportGpuLinearRgbSource && !resampleOutput) {
|
||||
if (!exportGpuLinearRgbSource) {
|
||||
val outputBytes = width.toLong() * height * 3L * Short.SIZE_BYTES
|
||||
cpuOutput = LargeDirectBuffer.allocate(outputBytes, "MGC Sabre VGN RGB16 output")
|
||||
?.order(ByteOrder.nativeOrder()) ?: error(
|
||||
@@ -2497,85 +2482,14 @@ internal class GlesMgcRawSpatialStacker(
|
||||
exportGpuLinearRgbSource -> {
|
||||
{ completionRecorder.mark(GpuStackCompletionStage.CHROMA_POSTPROCESS) }
|
||||
}
|
||||
resampleOutput -> {
|
||||
{
|
||||
GlesGpuCompletion.awaitSubmittedWork(
|
||||
label = "MGC Sabre VGN-to-Lanczos handoff",
|
||||
checkGlError = ::checkGlError,
|
||||
)
|
||||
Unit
|
||||
}
|
||||
}
|
||||
else -> null
|
||||
}
|
||||
val chromaResult = chromaPostprocessor.process(
|
||||
obtainOutputBuffer = { checkNotNull(cpuOutput) },
|
||||
deferFullSizeReadback = exportGpuLinearRgbSource || resampleOutput,
|
||||
deferFullSizeReadback = exportGpuLinearRgbSource,
|
||||
onFinalSubmitted = onChromaFinalSubmitted,
|
||||
)
|
||||
postprocessedUi = chromaResult.exportedTextureId
|
||||
if (resampleOutput) {
|
||||
check(postprocessedUi != 0) {
|
||||
"MGC Sabre VGN did not export its native-grid texture for output scaling"
|
||||
}
|
||||
if (exportGpuLinearRgbSource) {
|
||||
GlesGpuCompletion.awaitSubmittedWork(
|
||||
label = "MGC Sabre VGN-to-Lanczos handoff",
|
||||
checkGlError = ::checkGlError,
|
||||
)
|
||||
}
|
||||
val nativePostprocessedUi = postprocessedUi
|
||||
postprocessedUi = 0
|
||||
val nativePostprocessedFloat = createTexture(
|
||||
width,
|
||||
height,
|
||||
GLES30.GL_RGBA16F,
|
||||
GLES30.GL_NEAREST,
|
||||
)
|
||||
try {
|
||||
renderRgb16ToFloat(
|
||||
source = nativePostprocessedUi,
|
||||
target = nativePostprocessedFloat,
|
||||
imageWidth = width,
|
||||
imageHeight = height,
|
||||
)
|
||||
} finally {
|
||||
GLES30.glDeleteTextures(1, intArrayOf(nativePostprocessedUi), 0)
|
||||
}
|
||||
val scaledPostprocessedUi = createTexture(
|
||||
outputWidth,
|
||||
outputHeight,
|
||||
GLES30.GL_RGBA16UI,
|
||||
GLES30.GL_NEAREST,
|
||||
)
|
||||
try {
|
||||
renderSabreResampledOutput(
|
||||
source = nativePostprocessedFloat,
|
||||
target = scaledPostprocessedUi,
|
||||
)
|
||||
if (exportGpuLinearRgbSource) {
|
||||
transferOwnedTexture(
|
||||
scaledPostprocessedUi,
|
||||
"MGC Sabre scaled RGB16 output",
|
||||
)
|
||||
}
|
||||
postprocessedUi = scaledPostprocessedUi
|
||||
} finally {
|
||||
releaseOwnedTexture(
|
||||
nativePostprocessedFloat,
|
||||
"MGC Sabre native RGBA16F scaling source",
|
||||
)
|
||||
}
|
||||
if (!exportGpuLinearRgbSource) {
|
||||
try {
|
||||
cpuOutput = readSabreRgb16Output(postprocessedUi)
|
||||
} finally {
|
||||
detachRenderTargets()
|
||||
releaseOwnedTexture(postprocessedUi, "MGC Sabre scaled RGB16 output")
|
||||
postprocessedUi = 0
|
||||
}
|
||||
}
|
||||
}
|
||||
if (exportGpuLinearRgbSource) {
|
||||
check(postprocessedUi != 0) {
|
||||
"MGC Sabre VGN color noise/IIR did not export its filtered texture"
|
||||
@@ -2624,7 +2538,7 @@ internal class GlesMgcRawSpatialStacker(
|
||||
PLog.i(
|
||||
SABRE_TAG,
|
||||
"MGC Sabre complete frames=${frames.size} native=${width}x$height " +
|
||||
"output=${outputWidth}x$outputHeight outputScale=$normalizedOutputScale " +
|
||||
"output=${outputWidth}x$outputHeight " +
|
||||
"referenceSnr=${kernelTuning.referenceSnr} " +
|
||||
"finishRawDenoiseSnr=$finishRawDenoiseSnr " +
|
||||
"result=${if (exportedTexture != 0) gpuLinearRgbStorage.name + "_GPU" else "RGB16_CPU"} " +
|
||||
@@ -3078,87 +2992,6 @@ internal class GlesMgcRawSpatialStacker(
|
||||
draw(program, width, height, intArrayOf(output))
|
||||
}
|
||||
|
||||
private fun renderSabreResampledOutput(source: Int, target: Int) {
|
||||
check(sabreResampleOutputProgram != 0) {
|
||||
"MGC Sabre Lanczos output program is not initialized"
|
||||
}
|
||||
GLES30.glUseProgram(sabreResampleOutputProgram)
|
||||
bindTexture(sabreResampleOutputProgram, "uSource", 0, source)
|
||||
uniform2i(sabreResampleOutputProgram, "uSourceSize", width, height)
|
||||
uniform2i(
|
||||
sabreResampleOutputProgram,
|
||||
"uOutputSize",
|
||||
outputWidth,
|
||||
outputHeight,
|
||||
)
|
||||
draw(
|
||||
sabreResampleOutputProgram,
|
||||
outputWidth,
|
||||
outputHeight,
|
||||
intArrayOf(target),
|
||||
)
|
||||
GlesGpuScheduler.memoryBarrier()
|
||||
}
|
||||
|
||||
private fun readSabreRgb16Output(texture: Int): ByteBuffer {
|
||||
val outputByteCount = outputWidth.toLong() * outputHeight * 3L * Short.SIZE_BYTES
|
||||
val scratchByteCount = outputWidth.toLong() * outputHeight * 4L * Short.SIZE_BYTES
|
||||
require(outputByteCount in 1..Int.MAX_VALUE.toLong())
|
||||
require(scratchByteCount in 1..Int.MAX_VALUE.toLong())
|
||||
val output = LargeDirectBuffer.allocate(outputByteCount, "MGC Sabre scaled RGB16 output")
|
||||
?.order(ByteOrder.nativeOrder()) ?: error(
|
||||
"Unable to allocate MGC Sabre scaled RGB16 output",
|
||||
)
|
||||
val scratch = LargeDirectBuffer.allocate(
|
||||
scratchByteCount,
|
||||
"MGC Sabre scaled RGBA16 readback",
|
||||
)?.order(ByteOrder.nativeOrder())
|
||||
if (scratch == null) {
|
||||
LargeDirectBuffer.free(output)
|
||||
error("Unable to allocate MGC Sabre scaled RGBA16 readback")
|
||||
}
|
||||
try {
|
||||
GlesGpuCompletion.awaitSubmittedWork(
|
||||
label = "MGC Sabre Lanczos RGB16 readback",
|
||||
checkGlError = ::checkGlError,
|
||||
)
|
||||
bindRenderTargets(intArrayOf(texture), "MGC Sabre Lanczos RGB16 readback")
|
||||
GLES30.glBindBuffer(GLES30.GL_PIXEL_PACK_BUFFER, 0)
|
||||
GLES30.glPixelStorei(GLES30.GL_PACK_ALIGNMENT, 8)
|
||||
GLES30.glReadPixels(
|
||||
0,
|
||||
0,
|
||||
outputWidth,
|
||||
outputHeight,
|
||||
GLES30.GL_RGBA_INTEGER,
|
||||
GLES30.GL_UNSIGNED_SHORT,
|
||||
scratch,
|
||||
)
|
||||
GLES30.glBindFramebuffer(GLES30.GL_FRAMEBUFFER, 0)
|
||||
checkGlError("MGC Sabre Lanczos RGBA16 readback")
|
||||
scratch.rewind()
|
||||
check(
|
||||
DirectBufferPixelPacker.unpackRgba16TileToRgb16(
|
||||
source = scratch,
|
||||
sourceWidth = outputWidth,
|
||||
sourceHeight = outputHeight,
|
||||
destination = output,
|
||||
destinationWidth = outputWidth,
|
||||
destinationHeight = outputHeight,
|
||||
destinationLeft = 0,
|
||||
destinationTop = 0,
|
||||
),
|
||||
) { "Unable to pack MGC Sabre Lanczos RGB16 output" }
|
||||
output.rewind()
|
||||
return output
|
||||
} catch (throwable: Throwable) {
|
||||
LargeDirectBuffer.free(output)
|
||||
throw throwable
|
||||
} finally {
|
||||
LargeDirectBuffer.free(scratch)
|
||||
}
|
||||
}
|
||||
|
||||
private fun readSabreAccumulatedRgba16f(texture: Int): ByteBuffer {
|
||||
val output = checkNotNull(
|
||||
LargeDirectBuffer.allocate(
|
||||
@@ -3331,14 +3164,7 @@ internal class GlesMgcRawSpatialStacker(
|
||||
GlesMgcRawSabreShaders.outputTransformUint16,
|
||||
"mgc_sabre_output_transform_rgba16ui",
|
||||
)
|
||||
if (outputWidth != width || outputHeight != height) {
|
||||
sabreResampleOutputProgram = linkProgram(
|
||||
GlesMgcRawSabreShaders.resampleOutputLanczos,
|
||||
"mgc_sabre_output_lanczos",
|
||||
)
|
||||
}
|
||||
if (outputWidth != width || outputHeight != height ||
|
||||
(exportGpuLinearRgbSource && gpuLinearRgbStorage == GpuLinearRgbStorage.RGBA16F)
|
||||
if (exportGpuLinearRgbSource && gpuLinearRgbStorage == GpuLinearRgbStorage.RGBA16F
|
||||
) {
|
||||
copyRgb16ToFloatProgram = linkComputeProgram(
|
||||
GlesMgcRawSpatialShaders.copyRgb16ToFloat,
|
||||
@@ -3346,11 +3172,10 @@ internal class GlesMgcRawSpatialStacker(
|
||||
)
|
||||
}
|
||||
// ResolveSabre and VGN stay on the native grid. A requested larger output is a separate
|
||||
// Lanczos export transform after VGN, so it cannot be mistaken for sensor-detail SR.
|
||||
// display transform after FinishRaw/GuidedUpsample in RawDemosaicProcessor.
|
||||
rgbChromaPostprocessor = createRgbChromaPostprocessor(
|
||||
imageWidth = width,
|
||||
imageHeight = height,
|
||||
iirOutputScale = 1f,
|
||||
exportFullSizeTexture = exportGpuLinearRgbSource ||
|
||||
outputWidth != width || outputHeight != height,
|
||||
).also { it.initPrograms() }
|
||||
@@ -3508,12 +3333,6 @@ internal class GlesMgcRawSpatialStacker(
|
||||
}
|
||||
// Color noise/IIR owns a fixed RGBA16UI boundary, matching the VGN/Radiance
|
||||
// contract. The original planar F16 AOT output enters that boundary exactly once.
|
||||
if (outputWidth != width || outputHeight != height) {
|
||||
resampleAotRgbHorizontalProgram = linkProgram(
|
||||
GlesMgcRawSpatialShaders.resampleAotRgbHorizontal,
|
||||
"mgc_spatial_v25_aot_rgb_resample_x",
|
||||
)
|
||||
}
|
||||
normalizeAotRgbProgram = linkProgram(
|
||||
GlesMgcRawSpatialShaders.normalizeAotRgb16,
|
||||
"mgc_spatial_v25_aot_rgb16ui",
|
||||
@@ -3564,14 +3383,13 @@ internal class GlesMgcRawSpatialStacker(
|
||||
private fun createRgbChromaPostprocessor(
|
||||
imageWidth: Int = outputWidth,
|
||||
imageHeight: Int = outputHeight,
|
||||
iirOutputScale: Float = normalizedOutputScale,
|
||||
exportFullSizeTexture: Boolean = exportGpuLinearRgbSource,
|
||||
): GlesMgcSpatialRgbChromaPostprocessor {
|
||||
return GlesMgcSpatialRgbChromaPostprocessor(
|
||||
imageWidth = imageWidth,
|
||||
imageHeight = imageHeight,
|
||||
calculationWbGains = calculationWhiteBalance,
|
||||
outputScale = iirOutputScale,
|
||||
outputScale = 1f,
|
||||
exportFullSizeTexture = exportFullSizeTexture,
|
||||
backend = object : GlesMgcSpatialRgbChromaPostprocessor.Backend {
|
||||
override fun linkComputeProgram(source: String, name: String): Int =
|
||||
@@ -8292,9 +8110,7 @@ internal class GlesMgcRawSpatialStacker(
|
||||
}
|
||||
|
||||
/**
|
||||
* Streams one native-grid planar F16 channel at a time into the requested RGBA16UI grid. A
|
||||
* separable Lanczos-3 pass performs scaling before lens shading and the chroma stage, while
|
||||
* keeping only one upload plane and one horizontal R16F intermediate live.
|
||||
* Streams native-grid planar F16 channels into RGBA16UI before lens shading and chroma denoise.
|
||||
*/
|
||||
private fun uploadAndNormalizeOriginalAotRgb(
|
||||
planarF16: ByteBuffer,
|
||||
@@ -8316,20 +8132,6 @@ internal class GlesMgcRawSpatialStacker(
|
||||
GLES30.GL_R16F,
|
||||
GLES30.GL_NEAREST,
|
||||
)
|
||||
val resampleOutput = outputWidth != width || outputHeight != height
|
||||
check(!resampleOutput || resampleAotRgbHorizontalProgram != 0) {
|
||||
"MGC Spatial RGB AOT resampling program is not initialized"
|
||||
}
|
||||
val horizontalTexture = if (resampleOutput) {
|
||||
createTexture(
|
||||
outputWidth,
|
||||
height,
|
||||
GLES30.GL_R16F,
|
||||
GLES30.GL_NEAREST,
|
||||
)
|
||||
} else {
|
||||
0
|
||||
}
|
||||
try {
|
||||
GLES30.glBindBuffer(GLES30.GL_PIXEL_UNPACK_BUFFER, 0)
|
||||
GLES30.glPixelStorei(GLES30.GL_UNPACK_ALIGNMENT, 1)
|
||||
@@ -8352,41 +8154,9 @@ internal class GlesMgcRawSpatialStacker(
|
||||
source,
|
||||
)
|
||||
GLES30.glBindTexture(GLES30.GL_TEXTURE_2D, 0)
|
||||
val normalizedSource = if (resampleOutput) {
|
||||
// The previous channel's normalization pass leaves a per-channel color
|
||||
// mask active. The horizontal target is R16F, so red must be writable for
|
||||
// every channel before this intermediate pass.
|
||||
GLES30.glColorMask(true, true, true, true)
|
||||
GLES30.glUseProgram(resampleAotRgbHorizontalProgram)
|
||||
bindTexture(
|
||||
resampleAotRgbHorizontalProgram,
|
||||
"uChannelPlane",
|
||||
0,
|
||||
planeTexture,
|
||||
)
|
||||
uniform2i(resampleAotRgbHorizontalProgram, "uSourceSize", width, height)
|
||||
uniform1i(resampleAotRgbHorizontalProgram, "uOutputWidth", outputWidth)
|
||||
draw(
|
||||
resampleAotRgbHorizontalProgram,
|
||||
outputWidth,
|
||||
height,
|
||||
intArrayOf(horizontalTexture),
|
||||
)
|
||||
// Framebuffer write -> sampler fetch in the vertical pass.
|
||||
GlesGpuScheduler.memoryBarrier()
|
||||
horizontalTexture
|
||||
} else {
|
||||
planeTexture
|
||||
}
|
||||
GLES30.glUseProgram(normalizeAotRgbProgram)
|
||||
bindTexture(normalizeAotRgbProgram, "uChannelPlane", 0, normalizedSource)
|
||||
bindTexture(normalizeAotRgbProgram, "uChannelPlane", 0, planeTexture)
|
||||
bindTexture(normalizeAotRgbProgram, "uLensShading", 1, lensShadingTexture)
|
||||
uniform2i(
|
||||
normalizeAotRgbProgram,
|
||||
"uSourceSize",
|
||||
if (resampleOutput) outputWidth else width,
|
||||
height,
|
||||
)
|
||||
uniform2i(normalizeAotRgbProgram, "uOutputSize", outputWidth, outputHeight)
|
||||
uniform1f(
|
||||
normalizeAotRgbProgram,
|
||||
@@ -8398,11 +8168,6 @@ internal class GlesMgcRawSpatialStacker(
|
||||
"uUseLensShading",
|
||||
if (hasLensShading()) 1 else 0,
|
||||
)
|
||||
uniform1i(
|
||||
normalizeAotRgbProgram,
|
||||
"uResampleVertical",
|
||||
if (resampleOutput) 1 else 0,
|
||||
)
|
||||
uniform1i(normalizeAotRgbProgram, "uChannel", channel)
|
||||
GLES30.glColorMask(
|
||||
channel == 0,
|
||||
@@ -8427,12 +8192,6 @@ internal class GlesMgcRawSpatialStacker(
|
||||
} finally {
|
||||
GLES30.glColorMask(true, true, true, true)
|
||||
GLES30.glBindTexture(GLES30.GL_TEXTURE_2D, 0)
|
||||
if (horizontalTexture != 0) {
|
||||
releaseOwnedTexture(
|
||||
horizontalTexture,
|
||||
"MGC V25 Spatial RGB AOT horizontal resample",
|
||||
)
|
||||
}
|
||||
releaseOwnedTexture(planeTexture, "MGC V25 Spatial RGB AOT upload plane")
|
||||
}
|
||||
}
|
||||
@@ -8576,7 +8335,7 @@ internal class GlesMgcRawSpatialStacker(
|
||||
PLog.i(
|
||||
TAG,
|
||||
"MGC Spatial strength coordinates mapped ${coveredSource.width}x${coveredSource.height} -> " +
|
||||
"${targetWidth}x$targetHeight for ${normalizedOutputScale}x RGB output " +
|
||||
"${targetWidth}x$targetHeight for native-grid RGB output " +
|
||||
"backend=native-openmp took=" +
|
||||
"${(System.nanoTime() - startNs) / 1_000_000L}ms",
|
||||
)
|
||||
|
||||
@@ -54,15 +54,6 @@ enum class MgcRawMaxMode {
|
||||
}
|
||||
}
|
||||
|
||||
internal fun resolveRawStackOutputScale(
|
||||
outputMode: MgcSpatialOutputMode,
|
||||
outputScale: Float,
|
||||
): Float = if (outputMode == MgcSpatialOutputMode.RGB) {
|
||||
MultiFrameConfig.normalizeOutputScale(outputScale)
|
||||
} else {
|
||||
1f
|
||||
}
|
||||
|
||||
/**
|
||||
* Physical storage of an opaque LinearRaw texture. RGBA16F is used only for the direct Spatial
|
||||
* default-denoise handoff; persistent render/DNG sources use RGBA16UI.
|
||||
@@ -293,7 +284,6 @@ object MultiFrameStacker {
|
||||
MgcSpatialOutputMode.BAYER -> MgcMergeMethod.SPATIAL_BAYER
|
||||
MgcSpatialOutputMode.RGB -> MgcMergeMethod.SPATIAL_RGB
|
||||
},
|
||||
outputScale: Float = 1f,
|
||||
masterBlackLevel: FloatArray = floatArrayOf(0f, 0f, 0f, 0f),
|
||||
whiteLevel: Int = 1023,
|
||||
whiteBalanceGains: FloatArray = floatArrayOf(1f, 1f, 1f, 1f),
|
||||
@@ -321,14 +311,12 @@ object MultiFrameStacker {
|
||||
(physicalSourceBounds.width() and 1) == 0 &&
|
||||
(physicalSourceBounds.height() and 1) == 0
|
||||
) { "RAW physical crop must contain complete Bayer cells: $physicalSourceBounds" }
|
||||
// Output scaling is an RGB export transform shared by Spatial and Sabre. Only the
|
||||
// Bayer-preserving path must remain on the native sensor lattice.
|
||||
val effectiveOutputScale = resolveRawStackOutputScale(outputMode, outputScale)
|
||||
// Fusion and FinishRaw consume the native sensor grid. Display scaling follows sharpening.
|
||||
RawStackRuntimeDebug.d(TAG) {
|
||||
"Starting MGC ${if (mergeMethod == MgcMergeMethod.SABRE) "Sabre" else "Spatial ${outputMode.name}"} " +
|
||||
"fusion for ${images.size} frames source=${sourceWidth}x$sourceHeight " +
|
||||
"physicalCrop=$physicalSourceBounds " +
|
||||
"Pattern=$cfaPattern outputScale=$effectiveOutputScale " +
|
||||
"Pattern=$cfaPattern " +
|
||||
"BL=${masterBlackLevel.joinToString()} WL=$whiteLevel " +
|
||||
"noiseProfile=${noiseProfileSelection.id} " +
|
||||
"legacyHdrFlag=$enableHdrFusion"
|
||||
@@ -353,7 +341,6 @@ object MultiFrameStacker {
|
||||
lensShadingHeight = if (stackLensShading != null) lensShadingHeight else 0,
|
||||
outputMode = outputMode,
|
||||
mergeMethod = mergeMethod,
|
||||
outputScale = effectiveOutputScale,
|
||||
useCurrentGlContext = useCurrentGlContext,
|
||||
exportGpuLinearRgbSource = exportGpuLinearRgbSource,
|
||||
gpuLinearRgbStorage = gpuLinearRgbStorage,
|
||||
|
||||
@@ -0,0 +1,34 @@
|
||||
package com.hinnka.mycamera.raw
|
||||
|
||||
import kotlin.math.ceil
|
||||
import kotlin.math.log2
|
||||
|
||||
/** V25 FinishShot -> CreateProcessRawParams resolution policy, independent of sharpening SNR. */
|
||||
internal class MgcFinishResolution private constructor(val log2Downsample: Int) {
|
||||
val downsampleFactor = 1 shl log2Downsample
|
||||
val needsGuidedUpsample = downsampleFactor > 1
|
||||
// GuidedUpsample's regression coefficients use a further 2x grid.
|
||||
val processingPeriod = if (needsGuidedUpsample) downsampleFactor * 2 else 1
|
||||
|
||||
companion object {
|
||||
/**
|
||||
* 0x2E8F62C: max(output / crop); 0x333889C: snap (0.9, 1.1) to 1.
|
||||
* 0x343B0F8: ceil(log2(4 / scale)), clamped to levels 1..2.
|
||||
* The original flag defaults to -1; a nonnegative value overrides the level.
|
||||
* Photon has no override setting and uses the original automatic policy.
|
||||
*/
|
||||
fun resolve(cropWidth: Int, cropHeight: Int, outputWidth: Int, outputHeight: Int,
|
||||
scaleOverride: Float = -1f, levelOverride: Int = -1): MgcFinishResolution {
|
||||
require(cropWidth > 0 && cropHeight > 0 && outputWidth > 0 && outputHeight > 0)
|
||||
var scale = if (scaleOverride > 0f) scaleOverride else
|
||||
maxOf(outputWidth.toFloat() / cropWidth, outputHeight.toFloat() / cropHeight)
|
||||
require(scale.isFinite() && scale > 0f)
|
||||
if (scale > 0.9f && scale < 1.1f) scale = 1f
|
||||
val level = if (levelOverride >= 0) levelOverride else
|
||||
if (ceil(log2(4f / scale)) > 1f) 2 else 1
|
||||
// These are the V25 BoxDownsample/GuidedUpsample specializations we carry.
|
||||
require(level in 0..2)
|
||||
return MgcFinishResolution(level)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -548,7 +548,7 @@ internal object MgcFullResolutionDenoise {
|
||||
* DNG, so the native bridge enters that same working domain and removes
|
||||
* the gains again after YUV -> RGB.
|
||||
*/
|
||||
private fun normalizedRgbWhiteBalance(gains: FloatArray): FloatArray {
|
||||
internal fun normalizedRgbWhiteBalance(gains: FloatArray): FloatArray {
|
||||
fun safeGain(index: Int, fallback: Float): Float {
|
||||
val value = gains.getOrElse(index) { fallback }
|
||||
return value.takeIf { it.isFinite() && it > 0f } ?: fallback
|
||||
|
||||
@@ -0,0 +1,143 @@
|
||||
package com.hinnka.mycamera.raw
|
||||
|
||||
import android.opengl.GLES30
|
||||
import java.nio.ByteBuffer
|
||||
|
||||
/** Owns the three distinct inputs of V25's S16 GuidedUpsample until reconstruction. */
|
||||
internal class MgcGuidedUpsample(private val transfer: RawFloatTextureTransfer) {
|
||||
private var handle = 0L
|
||||
private var fullWidth = 0
|
||||
private var fullHeight = 0
|
||||
private var scale = 0
|
||||
var lowWidth = 0; private set
|
||||
var lowHeight = 0; private set
|
||||
var cameraTexture = 0; private set
|
||||
var profileTexture = 0; private set
|
||||
var profileFramebuffer = 0; private set
|
||||
val isPrepared get() = handle != 0L
|
||||
val globalWidth get() = lowWidth * scale
|
||||
val globalHeight get() = lowHeight * scale
|
||||
private val quad = RawFullscreenQuad()
|
||||
private var colorDownsampleProgram = 0
|
||||
|
||||
fun prepare(texture: Int, width: Int, height: Int, gains: FloatArray,
|
||||
resolution: MgcFinishResolution) {
|
||||
require(resolution.needsGuidedUpsample)
|
||||
releaseInputs()
|
||||
scale = resolution.downsampleFactor
|
||||
fullWidth = width; fullHeight = height
|
||||
lowWidth = ((width + 127) and -128) / scale
|
||||
lowHeight = ((height + 15) and -16) / scale
|
||||
val capacityPixels = maxOf(width.toLong() * height, lowWidth.toLong() * lowHeight)
|
||||
try {
|
||||
transfer.read(texture, width, height, capacityPixels) { rgba ->
|
||||
handle = nativePrepare(rgba, width, height, resolution.log2Downsample,
|
||||
MgcFullResolutionDenoise.normalizedRgbWhiteBalance(gains))
|
||||
check(handle != 0L) { "MGC linear guide/BoxDownsample preparation failed" }
|
||||
}
|
||||
cameraTexture = createTexture()
|
||||
transfer.upload(cameraTexture, lowWidth, lowHeight)
|
||||
profileTexture = createTexture()
|
||||
val names = IntArray(1)
|
||||
GLES30.glGenFramebuffers(1, names, 0)
|
||||
profileFramebuffer = names[0]
|
||||
GLES30.glBindFramebuffer(GLES30.GL_FRAMEBUFFER, profileFramebuffer)
|
||||
GLES30.glFramebufferTexture2D(GLES30.GL_FRAMEBUFFER, GLES30.GL_COLOR_ATTACHMENT0,
|
||||
GLES30.GL_TEXTURE_2D, profileTexture, 0)
|
||||
check(GLES30.glCheckFramebufferStatus(GLES30.GL_FRAMEBUFFER) == GLES30.GL_FRAMEBUFFER_COMPLETE)
|
||||
GLES30.glBindFramebuffer(GLES30.GL_FRAMEBUFFER, 0)
|
||||
} catch (error: Throwable) { releaseInputs(); throw error }
|
||||
}
|
||||
|
||||
/** Filmic reconstructs highlights in full-resolution engine RGB before tone mapping.
|
||||
* Preserve that color stage, while retaining the independent camera-domain guides. */
|
||||
fun downsampleReconstructedColor(texture: Int) {
|
||||
check(isPrepared)
|
||||
if (colorDownsampleProgram == 0) {
|
||||
colorDownsampleProgram = quad.createProgram(BOX_COLOR, "GuidedFilmicColor")
|
||||
check(colorDownsampleProgram != 0)
|
||||
}
|
||||
GLES30.glUseProgram(colorDownsampleProgram)
|
||||
GLES30.glBindFramebuffer(GLES30.GL_FRAMEBUFFER, profileFramebuffer)
|
||||
GLES30.glViewport(0, 0, lowWidth, lowHeight)
|
||||
GLES30.glActiveTexture(GLES30.GL_TEXTURE0)
|
||||
GLES30.glBindTexture(GLES30.GL_TEXTURE_2D, texture)
|
||||
GLES30.glUniform1i(GLES30.glGetUniformLocation(colorDownsampleProgram, "uInput"), 0)
|
||||
GLES30.glUniform1i(GLES30.glGetUniformLocation(colorDownsampleProgram, "uScale"), scale)
|
||||
quad.bindIdentityTextureMatrix(colorDownsampleProgram)
|
||||
quad.draw(colorDownsampleProgram)
|
||||
check(GLES30.glGetError() == GLES30.GL_NO_ERROR)
|
||||
}
|
||||
|
||||
fun render(source: Int, target: Int, width: Int, height: Int, attenuation: Float, curves: FloatArray) {
|
||||
check(isPrepared && width == fullWidth && height == fullHeight)
|
||||
try {
|
||||
transfer.read(source, lowWidth, lowHeight,
|
||||
maxOf(width.toLong() * height, lowWidth.toLong() * lowHeight)) { rgba ->
|
||||
val result = nativeRender(handle, rgba, attenuation, curves)
|
||||
check(result == 0) { "MGC GuidedUpsample failed: $result" }
|
||||
}
|
||||
transfer.upload(target, width, height)
|
||||
} finally { releaseInputs() }
|
||||
}
|
||||
|
||||
private fun createTexture(): Int {
|
||||
val names = IntArray(1)
|
||||
GLES30.glGenTextures(1, names, 0)
|
||||
val texture = names[0]
|
||||
try {
|
||||
GLES30.glBindTexture(GLES30.GL_TEXTURE_2D, texture)
|
||||
GLES30.glTexParameteri(GLES30.GL_TEXTURE_2D, GLES30.GL_TEXTURE_MIN_FILTER, GLES30.GL_LINEAR)
|
||||
GLES30.glTexParameteri(GLES30.GL_TEXTURE_2D, GLES30.GL_TEXTURE_MAG_FILTER, GLES30.GL_LINEAR)
|
||||
GLES30.glTexParameteri(GLES30.GL_TEXTURE_2D, GLES30.GL_TEXTURE_WRAP_S, GLES30.GL_CLAMP_TO_EDGE)
|
||||
GLES30.glTexParameteri(GLES30.GL_TEXTURE_2D, GLES30.GL_TEXTURE_WRAP_T, GLES30.GL_CLAMP_TO_EDGE)
|
||||
GLES30.glTexImage2D(GLES30.GL_TEXTURE_2D, 0, GLES30.GL_RGBA16F, lowWidth, lowHeight,
|
||||
0, GLES30.GL_RGBA, GLES30.GL_HALF_FLOAT, null)
|
||||
check(GLES30.glGetError() == GLES30.GL_NO_ERROR)
|
||||
return texture
|
||||
} catch (error: Throwable) { GLES30.glDeleteTextures(1, names, 0); throw error }
|
||||
}
|
||||
|
||||
private fun releaseInputs() {
|
||||
if (handle != 0L) nativeRelease(handle)
|
||||
handle = 0L
|
||||
if (profileFramebuffer != 0) GLES30.glDeleteFramebuffers(1, intArrayOf(profileFramebuffer), 0)
|
||||
if (cameraTexture != 0) GLES30.glDeleteTextures(1, intArrayOf(cameraTexture), 0)
|
||||
if (profileTexture != 0) GLES30.glDeleteTextures(1, intArrayOf(profileTexture), 0)
|
||||
profileFramebuffer = 0; cameraTexture = 0; profileTexture = 0
|
||||
fullWidth = 0; fullHeight = 0; lowWidth = 0; lowHeight = 0
|
||||
scale = 0
|
||||
}
|
||||
|
||||
fun release() {
|
||||
releaseInputs()
|
||||
if (colorDownsampleProgram != 0) GLES30.glDeleteProgram(colorDownsampleProgram)
|
||||
colorDownsampleProgram = 0
|
||||
}
|
||||
|
||||
private external fun nativePrepare(rgba: ByteBuffer, width: Int, height: Int,
|
||||
log2Downsample: Int, gains: FloatArray): Long
|
||||
private external fun nativeRender(handle: Long, rgba: ByteBuffer, attenuation: Float, curves: FloatArray): Int
|
||||
private external fun nativeRelease(handle: Long)
|
||||
|
||||
companion object {
|
||||
init { System.loadLibrary("my-native-lib") }
|
||||
private val BOX_COLOR = """
|
||||
#version 300 es
|
||||
precision highp float;
|
||||
precision highp int;
|
||||
uniform highp sampler2D uInput;
|
||||
uniform int uScale;
|
||||
out vec4 fragColor;
|
||||
void main() {
|
||||
ivec2 p = ivec2(gl_FragCoord.xy) * uScale;
|
||||
ivec2 hi = textureSize(uInput, 0) - 1;
|
||||
vec4 sum = vec4(0.0);
|
||||
for (int y = 0; y < uScale; ++y)
|
||||
for (int x = 0; x < uScale; ++x)
|
||||
sum += texelFetch(uInput, min(p + ivec2(x, y), hi), 0);
|
||||
fragColor = sum / float(uScale * uScale);
|
||||
}
|
||||
""".trimIndent()
|
||||
}
|
||||
}
|
||||
@@ -1,184 +1,57 @@
|
||||
package com.hinnka.mycamera.raw
|
||||
|
||||
import android.opengl.GLES30
|
||||
import android.opengl.GLES31
|
||||
import com.hinnka.mycamera.processor.GlesGpuCompletion
|
||||
import com.hinnka.mycamera.processor.PhotonCoreImagingTuning
|
||||
import com.hinnka.mycamera.processor.PhotonSharpenTuning
|
||||
import com.hinnka.mycamera.utils.LargeDirectBuffer
|
||||
import com.hinnka.mycamera.utils.PLog
|
||||
import java.nio.ByteBuffer
|
||||
import java.nio.ByteOrder
|
||||
|
||||
/** Original MGC AOT kernel at Photon's encoded RGBA8 boundary, with reusable native storage. */
|
||||
/** Original MGC AOT kernels, retaining float RGB until their U12 boundary. */
|
||||
internal class MgcSharpen {
|
||||
private var transferBuffer = 0
|
||||
private var transferSize = 0
|
||||
private val transfer = RawFloatTextureTransfer()
|
||||
val guided = MgcGuidedUpsample(transfer)
|
||||
private var scratch: ByteBuffer? = null
|
||||
private var packProgram = 0
|
||||
private var packAttempted = false
|
||||
private var maxSsboBytes = 0L
|
||||
|
||||
fun render(
|
||||
sourceTexture: Int,
|
||||
sourceFramebuffer: Int,
|
||||
targetTexture: Int,
|
||||
width: Int,
|
||||
height: Int,
|
||||
snr: Float,
|
||||
attenuation: Float,
|
||||
tuning: PhotonSharpenTuning = PhotonCoreImagingTuning.sharpen,
|
||||
) {
|
||||
require(width > 0 && height > 0 && snr.isFinite() && snr > 0f)
|
||||
fun render(sourceTexture: Int, targetTexture: Int, width: Int, height: Int,
|
||||
snr: Float, attenuation: Float,
|
||||
tuning: PhotonSharpenTuning = PhotonCoreImagingTuning.sharpen) {
|
||||
require(width > 0 && height > 0 && snr.isFinite() && snr >= 0f)
|
||||
require(attenuation.isFinite() && attenuation >= 0f)
|
||||
val curves = MgcSharpenCurveBuilder.build(snr, tuning)
|
||||
if (guided.isPrepared) {
|
||||
guided.render(sourceTexture, targetTexture, width, height, attenuation, curves.points)
|
||||
return
|
||||
}
|
||||
val pixels = width.toLong() * height
|
||||
val outputPixels = width.toLong() * ((height.toLong() + 1) and -2L)
|
||||
val scratchBytes = (pixels + outputPixels) * 6
|
||||
require(scratchBytes <= Int.MAX_VALUE)
|
||||
val bytes = (pixels * 4).toInt()
|
||||
val start = System.nanoTime()
|
||||
ensureStorage(bytes, scratchBytes)
|
||||
val allocationMs = elapsedMs(start)
|
||||
val useCompute = bytes <= maxSsboBytes && packProgram != 0
|
||||
val upstreamWaitMs = GlesGpuCompletion.awaitSubmittedWork(
|
||||
label = "MGC sharpen input", checkGlError = ::checkGlError,
|
||||
)
|
||||
val transferStart = System.nanoTime()
|
||||
try {
|
||||
if (useCompute) {
|
||||
GLES31.glUseProgram(packProgram)
|
||||
GLES31.glActiveTexture(GLES31.GL_TEXTURE0)
|
||||
GLES31.glBindTexture(GLES31.GL_TEXTURE_2D, sourceTexture)
|
||||
GLES31.glUniform1i(GLES31.glGetUniformLocation(packProgram, "uInput"), 0)
|
||||
GLES31.glUniform2i(GLES31.glGetUniformLocation(packProgram, "uSize"), width, height)
|
||||
GLES31.glBindBufferBase(GLES31.GL_SHADER_STORAGE_BUFFER, 0, transferBuffer)
|
||||
GLES31.glDispatchCompute((width + 7) / 8, (height + 7) / 8, 1)
|
||||
GLES31.glMemoryBarrier(GLES31.GL_SHADER_STORAGE_BARRIER_BIT or GLES31.GL_BUFFER_UPDATE_BARRIER_BIT)
|
||||
GLES31.glBindBufferBase(GLES31.GL_SHADER_STORAGE_BUFFER, 0, 0)
|
||||
} else {
|
||||
GLES30.glBindFramebuffer(GLES30.GL_READ_FRAMEBUFFER, sourceFramebuffer)
|
||||
GLES30.glReadBuffer(GLES30.GL_COLOR_ATTACHMENT0)
|
||||
GLES30.glBindBuffer(GLES30.GL_PIXEL_PACK_BUFFER, transferBuffer)
|
||||
GLES30.glPixelStorei(GLES30.GL_PACK_ALIGNMENT, 1)
|
||||
GLES30.glPixelStorei(GLES30.GL_PACK_ROW_LENGTH, 0)
|
||||
GLES30.glReadPixels(0, 0, width, height, GLES30.GL_RGBA, GLES30.GL_UNSIGNED_BYTE, 0)
|
||||
}
|
||||
checkGlError("MGC sharpen transfer submission")
|
||||
GLES30.glBindBuffer(GLES30.GL_PIXEL_PACK_BUFFER, transferBuffer)
|
||||
val mapped = checkNotNull(GLES30.glMapBufferRange(
|
||||
GLES30.GL_PIXEL_PACK_BUFFER, 0, bytes,
|
||||
GLES30.GL_MAP_READ_BIT or GLES30.GL_MAP_WRITE_BIT,
|
||||
) as? ByteBuffer) { "MGC sharpen transfer mapping failed" }
|
||||
val transferMs = elapsedMs(transferStart)
|
||||
val nativeStart = System.nanoTime()
|
||||
try {
|
||||
val result = nativeSharpenRgba8(mapped.order(ByteOrder.nativeOrder()),
|
||||
checkNotNull(scratch), width, height, snr, attenuation, curves.points)
|
||||
check(result == 0) { "MGC original sharpen failed: $result" }
|
||||
} finally {
|
||||
check(GLES30.glUnmapBuffer(GLES30.GL_PIXEL_PACK_BUFFER)) {
|
||||
"MGC sharpen mapped buffer became invalid"
|
||||
}
|
||||
}
|
||||
val nativeMs = elapsedMs(nativeStart)
|
||||
GLES30.glBindBuffer(GLES30.GL_PIXEL_PACK_BUFFER, 0)
|
||||
val uploadStart = System.nanoTime()
|
||||
check(nativeUploadRgba8(transferBuffer, targetTexture, width, height)) {
|
||||
"MGC sharpen PBO upload failed"
|
||||
}
|
||||
PLog.i(TAG, "originalMgc=true size=${width}x$height referenceSnr=$snr " +
|
||||
"attenuation=$attenuation transfer=${if (useCompute) "SSBO" else "PBO"} " +
|
||||
"curveSnr=${curves.lowerSnr}:${curves.upperSnr} curveMix=${curves.interpolation} " +
|
||||
"bandAmount=${tuning.amount} mainGains=${curves.mainGains} " +
|
||||
"allocationMs=$allocationMs upstreamGpuWaitMs=$upstreamWaitMs " +
|
||||
"transferAndMapMs=$transferMs nativeAndUnmapMs=$nativeMs " +
|
||||
"uploadSubmitMs=${elapsedMs(uploadStart)} totalCpuMs=${elapsedMs(start)}")
|
||||
} finally {
|
||||
GLES30.glBindBuffer(GLES30.GL_PIXEL_PACK_BUFFER, 0)
|
||||
GLES30.glBindBuffer(GLES30.GL_PIXEL_UNPACK_BUFFER, 0)
|
||||
GLES30.glBindFramebuffer(GLES30.GL_READ_FRAMEBUFFER, 0)
|
||||
}
|
||||
}
|
||||
|
||||
private fun ensureStorage(bytes: Int, scratchBytes: Long) {
|
||||
if (!packAttempted) {
|
||||
packAttempted = true
|
||||
val major = IntArray(1)
|
||||
val minor = IntArray(1)
|
||||
GLES30.glGetIntegerv(GLES30.GL_MAJOR_VERSION, major, 0)
|
||||
GLES30.glGetIntegerv(GLES30.GL_MINOR_VERSION, minor, 0)
|
||||
if (major[0] > 3 || major[0] == 3 && minor[0] >= 1) {
|
||||
val limit = LongArray(1)
|
||||
GLES31.glGetInteger64v(GLES31.GL_MAX_SHADER_STORAGE_BLOCK_SIZE, limit, 0)
|
||||
maxSsboBytes = limit[0]
|
||||
packProgram = RawGlesProgram.compileCompute(PACK_RGBA8, "MgcSharpenPackRgba8")
|
||||
}
|
||||
}
|
||||
if (transferBuffer == 0) {
|
||||
val names = IntArray(1)
|
||||
GLES30.glGenBuffers(1, names, 0)
|
||||
transferBuffer = names[0]
|
||||
}
|
||||
if (transferSize < bytes) {
|
||||
GLES30.glBindBuffer(GLES30.GL_PIXEL_PACK_BUFFER, transferBuffer)
|
||||
GLES30.glBufferData(GLES30.GL_PIXEL_PACK_BUFFER, bytes, null, GLES30.GL_STREAM_COPY)
|
||||
GLES30.glBindBuffer(GLES30.GL_PIXEL_PACK_BUFFER, 0)
|
||||
checkGlError("MGC sharpen transfer allocation")
|
||||
transferSize = bytes
|
||||
}
|
||||
if ((scratch?.capacity()?.toLong() ?: 0) < scratchBytes) {
|
||||
LargeDirectBuffer.free(scratch)
|
||||
scratch = null
|
||||
scratch = checkNotNull(LargeDirectBuffer.allocate(scratchBytes, "MGC sharpen YUV/RGB"))
|
||||
}
|
||||
transfer.read(sourceTexture, width, height) { mapped ->
|
||||
val result = nativeSharpenRgbaFloat(mapped, checkNotNull(scratch), width, height,
|
||||
snr, attenuation, curves.points)
|
||||
check(result == 0) { "MGC original sharpen failed: $result" }
|
||||
}
|
||||
transfer.upload(targetTexture, width, height)
|
||||
}
|
||||
|
||||
/** Release frame storage after all tiles; programs live with the GL context. */
|
||||
fun releaseBuffers() {
|
||||
guided.release()
|
||||
LargeDirectBuffer.free(scratch)
|
||||
scratch = null
|
||||
if (transferBuffer != 0) GLES30.glDeleteBuffers(1, intArrayOf(transferBuffer), 0)
|
||||
transferBuffer = 0
|
||||
transferSize = 0
|
||||
transfer.releaseBuffers()
|
||||
}
|
||||
|
||||
fun release() {
|
||||
releaseBuffers()
|
||||
if (packProgram != 0) GLES30.glDeleteProgram(packProgram)
|
||||
packProgram = 0
|
||||
packAttempted = false
|
||||
maxSsboBytes = 0
|
||||
transfer.release()
|
||||
}
|
||||
|
||||
private external fun nativeSharpenRgba8(
|
||||
rgba: ByteBuffer, scratch: ByteBuffer, width: Int, height: Int, snr: Float, attenuation: Float,
|
||||
curves: FloatArray,
|
||||
): Int
|
||||
private external fun nativeUploadRgba8(pbo: Int, texture: Int, width: Int, height: Int): Boolean
|
||||
private external fun nativeSharpenRgbaFloat(rgba: ByteBuffer, scratch: ByteBuffer,
|
||||
width: Int, height: Int, snr: Float, attenuation: Float, curves: FloatArray): Int
|
||||
|
||||
companion object {
|
||||
private const val TAG = "MgcSharpen"
|
||||
init { System.loadLibrary("my-native-lib") }
|
||||
private fun elapsedMs(start: Long) = (System.nanoTime() - start) / 1_000_000.0
|
||||
private fun checkGlError(label: String) {
|
||||
val error = GLES30.glGetError()
|
||||
check(error == GLES30.GL_NO_ERROR) { "$label: GL error 0x${error.toString(16)}" }
|
||||
}
|
||||
internal val PACK_RGBA8 = """
|
||||
#version 310 es
|
||||
precision highp float;
|
||||
precision highp int;
|
||||
layout(local_size_x = 8, local_size_y = 8) in;
|
||||
uniform highp sampler2D uInput;
|
||||
uniform ivec2 uSize;
|
||||
layout(std430, binding = 0) writeonly buffer Pixels { uint pixels[]; };
|
||||
void main() {
|
||||
ivec2 p = ivec2(gl_GlobalInvocationID.xy);
|
||||
if (any(greaterThanEqual(p, uSize))) return;
|
||||
uvec4 v = uvec4(round(texelFetch(uInput, p, 0) * 255.0));
|
||||
pixels[p.y * uSize.x + p.x] = v.r | (v.g << 8u) | (v.b << 16u) | (v.a << 24u);
|
||||
}
|
||||
""".trimIndent()
|
||||
}
|
||||
companion object { init { System.loadLibrary("my-native-lib") } }
|
||||
}
|
||||
@@ -16,7 +16,7 @@ internal object MgcSharpenCurveBuilder {
|
||||
}
|
||||
|
||||
fun build(snr: Float, tuning: PhotonSharpenTuning): Selection {
|
||||
require(snr.isFinite() && snr > 0f)
|
||||
require(snr.isFinite() && snr >= 0f)
|
||||
val nodes = tuning.nodes
|
||||
// Revalidate the list at the boundary: callers may have supplied a mutable List.
|
||||
require(nodes.isNotEmpty() && nodes.zipWithNext().all { (a, b) -> a.snr < b.snr })
|
||||
|
||||
@@ -850,7 +850,6 @@ class RawDemosaicProcessor {
|
||||
gpuLinearRgbSource: GpuLinearRgbSource?,
|
||||
gpuBayerSource: GpuBayerSource?,
|
||||
metadata: RawMetadata,
|
||||
outputScale: Float,
|
||||
sourcePixelsIncludeLensShadingCorrection: Boolean,
|
||||
applyLensShadingCorrection: Boolean,
|
||||
mode: MgcSpatialGpuDenoiseMode = MgcSpatialGpuDenoiseMode.SPATIAL_DEFAULT,
|
||||
@@ -1320,7 +1319,7 @@ class RawDemosaicProcessor {
|
||||
globalOriginY = 0,
|
||||
fullWidth = width,
|
||||
fullHeight = height,
|
||||
outputScale = outputScale,
|
||||
outputScale = 1f,
|
||||
metadata = defaultDenoiseMetadata,
|
||||
preparedYuvNoiseModel = demosaicNoiseTransfer.takeIf {
|
||||
mode == MgcSpatialGpuDenoiseMode.SPATIAL_DEFAULT
|
||||
@@ -1390,7 +1389,7 @@ class RawDemosaicProcessor {
|
||||
PLog.i(
|
||||
TAG,
|
||||
"MGC Spatial GPU LinearRaw ready: source=$sourceLabel " +
|
||||
"size=${width}x$height outputScale=$outputScale " +
|
||||
"size=${width}x$height " +
|
||||
"pass=${if (applyDefaultDenoise) {
|
||||
mode.name
|
||||
} else {
|
||||
@@ -1639,6 +1638,7 @@ class RawDemosaicProcessor {
|
||||
val metadata: RawMetadata,
|
||||
val tiles: List<RawRenderTile>,
|
||||
val outputSourceBounds: Rect,
|
||||
val outputGeometry: RawOutputGeometry,
|
||||
val rotation: Int,
|
||||
val includeHdrReference: Boolean,
|
||||
val hdrReferenceSceneExposureGain: Float,
|
||||
@@ -1843,6 +1843,7 @@ class RawDemosaicProcessor {
|
||||
photonHdrNetInputExposureEv: Float? = null,
|
||||
rawCfaCorrectionMode: String? = null,
|
||||
rawBlackBorderCrop: RawBlackBorderCrop = RawBlackBorderCrop(),
|
||||
rawOutputScale: Float = 1f,
|
||||
onMetadata: ((RawMetadata) -> Unit)? = null
|
||||
): Bitmap? = withContext(glDispatcher) {
|
||||
val dngFile = File(dngFilePath)
|
||||
@@ -1892,6 +1893,7 @@ class RawDemosaicProcessor {
|
||||
photonHdrNetInputExposureEv = photonHdrNetInputExposureEv,
|
||||
rawCfaCorrectionMode = rawCfaCorrectionMode,
|
||||
rawBlackBorderCrop = rawBlackBorderCrop,
|
||||
rawOutputScale = rawOutputScale,
|
||||
dngFile = dngFile,
|
||||
onMetadata = onMetadata
|
||||
)?.sdrBitmap
|
||||
@@ -1938,6 +1940,7 @@ class RawDemosaicProcessor {
|
||||
rawRenderingEngine: RawRenderingEngine = RawRenderingEngine.AdobeCurve,
|
||||
rawToneMappingParameters: RawToneMappingParameters = RawToneMappingParameters.DEFAULT,
|
||||
rawBlackBorderCrop: RawBlackBorderCrop = RawBlackBorderCrop(),
|
||||
rawOutputScale: Float = 1f,
|
||||
): Bitmap? = withContext(glDispatcher) {
|
||||
try {
|
||||
if (!isInitialized) {
|
||||
@@ -1980,7 +1983,8 @@ class RawDemosaicProcessor {
|
||||
spectralFilmTuning = spectralFilmTuning,
|
||||
rawRenderingEngine = rawRenderingEngine,
|
||||
rawToneMappingParameters = rawToneMappingParameters,
|
||||
rawBlackBorderCrop = rawBlackBorderCrop
|
||||
rawBlackBorderCrop = rawBlackBorderCrop,
|
||||
rawOutputScale = rawOutputScale,
|
||||
)?.sdrBitmap
|
||||
} catch (e: Exception) {
|
||||
PLog.e(TAG, "Failed to process RAW buffer", e)
|
||||
@@ -2087,6 +2091,7 @@ class RawDemosaicProcessor {
|
||||
rawToneMappingParameters: RawToneMappingParameters = RawToneMappingParameters.DEFAULT,
|
||||
rawCfaCorrectionMode: String? = null,
|
||||
rawBlackBorderCrop: RawBlackBorderCrop = RawBlackBorderCrop(),
|
||||
rawOutputScale: Float = 1f,
|
||||
includeHdrReference: Boolean,
|
||||
photonHdrRatio: Float? = null,
|
||||
photonSourceToShortGain: Float? = null,
|
||||
@@ -2138,6 +2143,7 @@ class RawDemosaicProcessor {
|
||||
rawToneMappingParameters = rawToneMappingParameters,
|
||||
rawCfaCorrectionMode = rawCfaCorrectionMode,
|
||||
rawBlackBorderCrop = rawBlackBorderCrop,
|
||||
rawOutputScale = rawOutputScale,
|
||||
dngFile = dngFile,
|
||||
onMetadata = onMetadata,
|
||||
includeHdrReference = includeHdrReference,
|
||||
@@ -2201,6 +2207,7 @@ class RawDemosaicProcessor {
|
||||
rawToneMappingParameters: RawToneMappingParameters = RawToneMappingParameters.DEFAULT,
|
||||
rawCfaCorrectionMode: String? = null,
|
||||
rawBlackBorderCrop: RawBlackBorderCrop = RawBlackBorderCrop(),
|
||||
rawOutputScale: Float = 1f,
|
||||
includeHdrReference: Boolean,
|
||||
photonHdrRatio: Float? = null,
|
||||
photonSourceToShortGain: Float? = null,
|
||||
@@ -2298,6 +2305,7 @@ class RawDemosaicProcessor {
|
||||
rawToneMappingParameters = rawToneMappingParameters,
|
||||
rawCfaCorrectionMode = rawCfaCorrectionMode,
|
||||
rawBlackBorderCrop = rawBlackBorderCrop,
|
||||
rawOutputScale = rawOutputScale,
|
||||
includeHdrReference = includeHdrReference,
|
||||
sourceDngRenderPlan = embeddedDngRenderPlan,
|
||||
photonHdrRatio = photonHdrRatio,
|
||||
@@ -2366,6 +2374,7 @@ class RawDemosaicProcessor {
|
||||
photonHdrNetInputExposureEv: Float? = null,
|
||||
rawCfaCorrectionMode: String? = null,
|
||||
rawBlackBorderCrop: RawBlackBorderCrop = RawBlackBorderCrop(),
|
||||
rawOutputScale: Float = 1f,
|
||||
dngFile: File? = null,
|
||||
onMetadata: ((RawMetadata) -> Unit)? = null,
|
||||
includeHdrReference: Boolean = false,
|
||||
@@ -2612,7 +2621,6 @@ class RawDemosaicProcessor {
|
||||
rawData = actualRawData,
|
||||
rowStride = actualRowStride,
|
||||
samplesPerPixel = actualSamplesPerPixel,
|
||||
needsSharpen = RawSharpeningDefaults.toAlgorithmStrength(sharpeningValue) > 0f,
|
||||
)
|
||||
}
|
||||
|
||||
@@ -2753,6 +2761,11 @@ class RawDemosaicProcessor {
|
||||
"legacyCrop=$cropRegion appliedLegacyCrop=$renderCropRegion " +
|
||||
"aspectRatio=$aspectRatio rotation=$actualRotation outputSourceBounds=$outputSourceBounds"
|
||||
)
|
||||
val outputGeometry = RawOutputGeometry(
|
||||
RawTileRect(outputSourceBounds.left, outputSourceBounds.top,
|
||||
outputSourceBounds.right, outputSourceBounds.bottom),
|
||||
actualRotation, rawOutputScale,
|
||||
)
|
||||
val rawOutputBounds = outputSourceBounds.toOutputBounds(actualRotation)
|
||||
val applicableDngWarpRectilinear = filterApplicableWarpRectilinear(
|
||||
warps = dngWarpRectilinear,
|
||||
@@ -2811,8 +2824,9 @@ class RawDemosaicProcessor {
|
||||
),
|
||||
rotation = actualRotation,
|
||||
coreEdgePx = RAW_TILE_MAX_CORE_EDGE_PX,
|
||||
supportPx = RAW_TILE_SUPPORT_PX,
|
||||
supportPx = RAW_TILE_SUPPORT_PX + if (outputGeometry.resample) 3 else 0,
|
||||
cfaPeriod = RawCfaCorrection.repeatPatternDim(actualMetadata.cfaPattern)[0],
|
||||
processingPeriod = outputGeometry.mgcFinishResolution.processingPeriod,
|
||||
)
|
||||
} else {
|
||||
emptyList()
|
||||
@@ -3153,8 +3167,8 @@ class RawDemosaicProcessor {
|
||||
)
|
||||
|
||||
val bounds = rawOutputBounds
|
||||
val finalWidth = bounds.width()
|
||||
val finalHeight = bounds.height()
|
||||
val finalWidth = outputGeometry.width
|
||||
val finalHeight = outputGeometry.height
|
||||
|
||||
if (rawRenderTiles.isEmpty()) {
|
||||
// 4. A capture-profile pass may hand its full-resolution single-frame demosaic
|
||||
@@ -3775,6 +3789,7 @@ class RawDemosaicProcessor {
|
||||
metadata = actualMetadata,
|
||||
tiles = rawRenderTiles,
|
||||
outputSourceBounds = outputSourceBounds,
|
||||
outputGeometry = outputGeometry,
|
||||
rotation = actualRotation,
|
||||
includeHdrReference = includeHdrReference,
|
||||
hdrReferenceSceneExposureGain = hdrReferenceSceneExposureGain,
|
||||
@@ -3852,6 +3867,30 @@ class RawDemosaicProcessor {
|
||||
// the exact post-matrix 2^EV gain.
|
||||
checkGlError("Before LinearRcdPass")
|
||||
|
||||
if (outputGeometry.mgcFinishResolution.needsGuidedUpsample) {
|
||||
mgcSharpen.guided.prepare(denoiseProfileTextureId, actualWidth, actualHeight,
|
||||
actualMetadata.whiteBalanceGains, outputGeometry.mgcFinishResolution)
|
||||
renderLinearRcdPass(
|
||||
metadata = actualMetadata,
|
||||
sourceTextureId = mgcSharpen.guided.cameraTexture,
|
||||
targetFramebufferId = mgcSharpen.guided.profileFramebuffer,
|
||||
viewportWidth = mgcSharpen.guided.lowWidth,
|
||||
viewportHeight = mgcSharpen.guided.lowHeight,
|
||||
rawExposureCompensation = 0f,
|
||||
colorCorrectionMatrix = linearColorCorrectionMatrix,
|
||||
cameraWhite = linearCameraWhite,
|
||||
// HDRNet's PGTM contains HDRNet -> Dehaze/DHA, so its DCP color map is deferred
|
||||
// to the profile pass. Other paths retain their established linear-pass order.
|
||||
hueSatMap = activeDcpRenderPlan?.hueSatMap
|
||||
?.takeUnless { deferDcpHueSatUntilAfterPgtm },
|
||||
applyDngBaselineExposure = applyLinearDngBaselineExposure,
|
||||
clampProfileRgb = clampProfileRgb,
|
||||
hueSatMapSupportsOverrange = hueSatMapSupportsOverrange,
|
||||
hncsCameraDomainGains = hncsCameraDomainGains,
|
||||
label = "GuidedLowLinearRcdPass"
|
||||
)
|
||||
}
|
||||
|
||||
renderLinearRcdPass(
|
||||
metadata = actualMetadata,
|
||||
sourceTextureId = denoiseProfileTextureId,
|
||||
@@ -3934,13 +3973,23 @@ class RawDemosaicProcessor {
|
||||
} else {
|
||||
profileToEngineTransform
|
||||
}
|
||||
setupCombinedFramebuffer(actualWidth, actualHeight)
|
||||
if (mgcSharpen.guided.isPrepared && colorEngine == RawRenderingEngine.DarktableFilmic) {
|
||||
mgcSharpen.guided.downsampleReconstructedColor(combinedInputTexture)
|
||||
}
|
||||
val toneInputTexture = if (mgcSharpen.guided.isPrepared) {
|
||||
mgcSharpen.guided.profileTexture
|
||||
} else combinedInputTexture
|
||||
val toneWidth = if (mgcSharpen.guided.isPrepared) mgcSharpen.guided.lowWidth else actualWidth
|
||||
val toneHeight = if (mgcSharpen.guided.isPrepared) mgcSharpen.guided.lowHeight else actualHeight
|
||||
val toneGlobalWidth = if (mgcSharpen.guided.isPrepared) mgcSharpen.guided.globalWidth else actualWidth
|
||||
val toneGlobalHeight = if (mgcSharpen.guided.isPrepared) mgcSharpen.guided.globalHeight else actualHeight
|
||||
setupCombinedFramebuffer(toneWidth, toneHeight)
|
||||
val combinedStart = System.currentTimeMillis()
|
||||
var hdrReferencePreparedFromCombinedInput = false
|
||||
val combinedOutput = try {
|
||||
val output = renderCombinedPass(
|
||||
metadata = actualMetadata,
|
||||
inputTextureId = combinedInputTexture,
|
||||
inputTextureId = toneInputTexture,
|
||||
dcpRenderPlan = activeDcpRenderPlan,
|
||||
applyDcpHueSatMap = deferDcpHueSatUntilAfterPgtm,
|
||||
profileExposureUniforms = combinedProfileExposureUniforms,
|
||||
@@ -3957,6 +4006,10 @@ class RawDemosaicProcessor {
|
||||
rawToneMappingParameters = rawToneMappingParameters,
|
||||
applyProfileGainTableMap =
|
||||
hasProfileGainTableMap && colorEngine != RawRenderingEngine.DarktableFilmic,
|
||||
viewportWidth = toneWidth,
|
||||
viewportHeight = toneHeight,
|
||||
globalWidth = toneGlobalWidth,
|
||||
globalHeight = toneGlobalHeight,
|
||||
)
|
||||
// Filmic's wavelet reconstruction owns its prepared engine-domain source. Render
|
||||
// the HDR reference before releasing those framebuffers so SDR and HDR consume
|
||||
@@ -4046,7 +4099,8 @@ class RawDemosaicProcessor {
|
||||
actualWidth,
|
||||
actualHeight,
|
||||
bounds,
|
||||
sourceTextureForOutput
|
||||
sourceTextureForOutput,
|
||||
geometry = outputGeometry,
|
||||
)
|
||||
PLog.d(TAG, "Output Pass took: ${System.currentTimeMillis() - outputStart}ms")
|
||||
// HDR must use this exact finalized SDR color as well. Keep it through HDR output;
|
||||
@@ -4117,6 +4171,7 @@ class RawDemosaicProcessor {
|
||||
bounds,
|
||||
hdrReferenceTextureId,
|
||||
hdrSdrBaseTextureId = sourceTextureForOutput,
|
||||
geometry = outputGeometry,
|
||||
)
|
||||
val hdrGpuQueueWaitMs = GlesGpuCompletion.awaitSubmittedWork(
|
||||
label = "RAW HDR reference output",
|
||||
@@ -4203,16 +4258,8 @@ class RawDemosaicProcessor {
|
||||
}) {
|
||||
"RAW tile resource reuse requires a stable working size"
|
||||
}
|
||||
val outputWidth = if (config.rotation == 90 || config.rotation == 270) {
|
||||
config.outputSourceBounds.height()
|
||||
} else {
|
||||
config.outputSourceBounds.width()
|
||||
}
|
||||
val outputHeight = if (config.rotation == 90 || config.rotation == 270) {
|
||||
config.outputSourceBounds.width()
|
||||
} else {
|
||||
config.outputSourceBounds.height()
|
||||
}
|
||||
val outputWidth = config.outputGeometry.width
|
||||
val outputHeight = config.outputGeometry.height
|
||||
val workingColorSpace = resolveWorkingColorSpace()
|
||||
val hdrColorSpace = android.graphics.ColorSpace.get(
|
||||
android.graphics.ColorSpace.Named.LINEAR_EXTENDED_SRGB
|
||||
@@ -4257,8 +4304,8 @@ class RawDemosaicProcessor {
|
||||
isFilterBitmap = false
|
||||
blendMode = BlendMode.SRC
|
||||
}
|
||||
val maximumOutputWidth = config.tiles.maxOf { it.outputCore.width }
|
||||
val maximumOutputHeight = config.tiles.maxOf { it.outputCore.height }
|
||||
val maximumOutputWidth = config.tiles.maxOf { config.outputGeometry.scaleRegion(it.outputCore).width }
|
||||
val maximumOutputHeight = config.tiles.maxOf { config.outputGeometry.scaleRegion(it.outputCore).height }
|
||||
val estimatedTileGpuBytes =
|
||||
firstWorking.width.toLong() * firstWorking.height.toLong() * 96L
|
||||
val destinationBytes = outputWidth.toLong() * outputHeight.toLong() * 8L *
|
||||
@@ -4295,6 +4342,7 @@ class RawDemosaicProcessor {
|
||||
for (tile in config.tiles) {
|
||||
currentCoroutineContext().ensureActive()
|
||||
val tileStartNs = System.nanoTime()
|
||||
val scaledCore = config.outputGeometry.scaleRegion(tile.outputCore)
|
||||
val working = tile.sourceWorking
|
||||
val workWidth = working.width
|
||||
val workHeight = working.height
|
||||
@@ -4390,6 +4438,30 @@ class RawDemosaicProcessor {
|
||||
denoiseValue = config.denoiseValue,
|
||||
)
|
||||
}
|
||||
if (config.outputGeometry.mgcFinishResolution.needsGuidedUpsample) {
|
||||
val resolution = config.outputGeometry.mgcFinishResolution
|
||||
check(working.left % resolution.processingPeriod == 0 &&
|
||||
working.top % resolution.processingPeriod == 0)
|
||||
mgcSharpen.guided.prepare(denoisedTextureId, workWidth, workHeight,
|
||||
config.metadata.whiteBalanceGains, resolution)
|
||||
renderLinearRcdPass(
|
||||
metadata = config.metadata,
|
||||
sourceTextureId = mgcSharpen.guided.cameraTexture,
|
||||
targetFramebufferId = mgcSharpen.guided.profileFramebuffer,
|
||||
viewportWidth = mgcSharpen.guided.lowWidth,
|
||||
viewportHeight = mgcSharpen.guided.lowHeight,
|
||||
rawExposureCompensation = 0f,
|
||||
colorCorrectionMatrix = config.linearColorCorrectionMatrix,
|
||||
cameraWhite = config.linearCameraWhite,
|
||||
hueSatMap = config.hueSatMap
|
||||
?.takeUnless { config.deferDcpHueSatUntilAfterPgtm },
|
||||
applyDngBaselineExposure = config.applyLinearDngBaselineExposure,
|
||||
clampProfileRgb = config.clampProfileRgb,
|
||||
hueSatMapSupportsOverrange = config.hueSatMapSupportsOverrange,
|
||||
hncsCameraDomainGains = config.hncsCameraDomainGains,
|
||||
label = "GuidedLowLinearRcdTilePass",
|
||||
)
|
||||
}
|
||||
renderLinearRcdPass(
|
||||
metadata = config.metadata,
|
||||
sourceTextureId = denoisedTextureId,
|
||||
@@ -4417,7 +4489,7 @@ class RawDemosaicProcessor {
|
||||
|
||||
val combinedOutput = renderCombinedPass(
|
||||
metadata = config.metadata,
|
||||
inputTextureId = demosaicTextureId,
|
||||
inputTextureId = if (mgcSharpen.guided.isPrepared) mgcSharpen.guided.profileTexture else demosaicTextureId,
|
||||
dcpRenderPlan = config.activeDcpRenderPlan,
|
||||
applyDcpHueSatMap = config.deferDcpHueSatUntilAfterPgtm,
|
||||
profileExposureUniforms = config.profileExposureUniforms,
|
||||
@@ -4437,8 +4509,10 @@ class RawDemosaicProcessor {
|
||||
globalOriginY = working.top,
|
||||
fullImageWidth = config.fullWidth,
|
||||
fullImageHeight = config.fullHeight,
|
||||
viewportWidth = workWidth,
|
||||
viewportHeight = workHeight,
|
||||
viewportWidth = if (mgcSharpen.guided.isPrepared) mgcSharpen.guided.lowWidth else workWidth,
|
||||
viewportHeight = if (mgcSharpen.guided.isPrepared) mgcSharpen.guided.lowHeight else workHeight,
|
||||
globalWidth = if (mgcSharpen.guided.isPrepared) mgcSharpen.guided.globalWidth else workWidth,
|
||||
globalHeight = if (mgcSharpen.guided.isPrepared) mgcSharpen.guided.globalHeight else workHeight,
|
||||
)
|
||||
if (combinedOutput == null) {
|
||||
PLog.e(TAG, "Combined tile pass failed at tile=${tile.index}")
|
||||
@@ -4480,19 +4554,23 @@ class RawDemosaicProcessor {
|
||||
width = workWidth,
|
||||
height = workHeight,
|
||||
bounds = localOutputBounds,
|
||||
geometry = config.outputGeometry,
|
||||
outputRegion = scaledCore,
|
||||
sourceOriginX = working.left,
|
||||
sourceOriginY = working.top,
|
||||
sourceTextureId = hdrReferenceTextureId,
|
||||
hdrSdrBaseTextureId = sharpenTextureId,
|
||||
)
|
||||
val hdrTileBitmap = readTilePixels(
|
||||
width = tile.outputCore.width,
|
||||
height = tile.outputCore.height,
|
||||
width = scaledCore.width,
|
||||
height = scaledCore.height,
|
||||
colorSpace = hdrColorSpace,
|
||||
) ?: return null
|
||||
try {
|
||||
hdrCanvas?.drawBitmap(
|
||||
hdrTileBitmap,
|
||||
tile.outputCore.left.toFloat(),
|
||||
tile.outputCore.top.toFloat(),
|
||||
scaledCore.left.toFloat(),
|
||||
scaledCore.top.toFloat(),
|
||||
copyPaint,
|
||||
)
|
||||
} finally {
|
||||
@@ -4504,18 +4582,22 @@ class RawDemosaicProcessor {
|
||||
width = workWidth,
|
||||
height = workHeight,
|
||||
bounds = localOutputBounds,
|
||||
geometry = config.outputGeometry,
|
||||
outputRegion = scaledCore,
|
||||
sourceOriginX = working.left,
|
||||
sourceOriginY = working.top,
|
||||
sourceTextureId = sharpenTextureId,
|
||||
)
|
||||
val tileBitmap = readTilePixels(
|
||||
width = tile.outputCore.width,
|
||||
height = tile.outputCore.height,
|
||||
width = scaledCore.width,
|
||||
height = scaledCore.height,
|
||||
colorSpace = workingColorSpace,
|
||||
) ?: return null
|
||||
try {
|
||||
sdrCanvas.drawBitmap(
|
||||
tileBitmap,
|
||||
tile.outputCore.left.toFloat(),
|
||||
tile.outputCore.top.toFloat(),
|
||||
scaledCore.left.toFloat(),
|
||||
scaledCore.top.toFloat(),
|
||||
copyPaint,
|
||||
)
|
||||
} finally {
|
||||
@@ -6530,8 +6612,8 @@ class RawDemosaicProcessor {
|
||||
combinedTextureId = textures[0]
|
||||
GLES30.glBindTexture(GLES30.GL_TEXTURE_2D, combinedTextureId)
|
||||
GLES30.glTexImage2D(
|
||||
GLES30.GL_TEXTURE_2D, 0, GLES30.GL_RGBA8, width, height, 0,
|
||||
GLES30.GL_RGBA, GLES30.GL_UNSIGNED_BYTE, null
|
||||
GLES30.GL_TEXTURE_2D, 0, GLES30.GL_RGBA16F, width, height, 0,
|
||||
GLES30.GL_RGBA, GLES30.GL_HALF_FLOAT, null
|
||||
)
|
||||
GLES30.glTexParameteri(GLES30.GL_TEXTURE_2D, GLES30.GL_TEXTURE_MIN_FILTER, GLES30.GL_LINEAR)
|
||||
GLES30.glTexParameteri(GLES30.GL_TEXTURE_2D, GLES30.GL_TEXTURE_MAG_FILTER, GLES30.GL_LINEAR)
|
||||
@@ -6553,7 +6635,7 @@ class RawDemosaicProcessor {
|
||||
textureId = combinedTextureId,
|
||||
width = width,
|
||||
height = height,
|
||||
internalFormat = "RGBA8",
|
||||
internalFormat = "RGBA16F",
|
||||
)
|
||||
checkGlError("setupCombinedFramebuffer")
|
||||
}
|
||||
@@ -6736,6 +6818,8 @@ class RawDemosaicProcessor {
|
||||
)
|
||||
GLES30.glTexParameteri(GLES30.GL_TEXTURE_2D, GLES30.GL_TEXTURE_MIN_FILTER, GLES30.GL_LINEAR)
|
||||
GLES30.glTexParameteri(GLES30.GL_TEXTURE_2D, GLES30.GL_TEXTURE_MAG_FILTER, GLES30.GL_LINEAR)
|
||||
GLES30.glTexParameteri(GLES30.GL_TEXTURE_2D, GLES30.GL_TEXTURE_WRAP_S, GLES30.GL_CLAMP_TO_EDGE)
|
||||
GLES30.glTexParameteri(GLES30.GL_TEXTURE_2D, GLES30.GL_TEXTURE_WRAP_T, GLES30.GL_CLAMP_TO_EDGE)
|
||||
|
||||
val framebuffers = IntArray(1)
|
||||
GLES30.glGenFramebuffers(1, framebuffers, 0)
|
||||
@@ -6784,8 +6868,8 @@ class RawDemosaicProcessor {
|
||||
sharpenTextureId = textures[0]
|
||||
GLES30.glBindTexture(GLES30.GL_TEXTURE_2D, sharpenTextureId)
|
||||
GLES30.glTexImage2D(
|
||||
GLES30.GL_TEXTURE_2D, 0, GLES30.GL_RGBA8, width, height, 0,
|
||||
GLES30.GL_RGBA, GLES30.GL_UNSIGNED_BYTE, null
|
||||
GLES30.GL_TEXTURE_2D, 0, GLES30.GL_RGBA16F, width, height, 0,
|
||||
GLES30.GL_RGBA, GLES30.GL_HALF_FLOAT, null
|
||||
)
|
||||
GLES30.glTexParameteri(GLES30.GL_TEXTURE_2D, GLES30.GL_TEXTURE_MIN_FILTER, GLES30.GL_LINEAR)
|
||||
GLES30.glTexParameteri(GLES30.GL_TEXTURE_2D, GLES30.GL_TEXTURE_MAG_FILTER, GLES30.GL_LINEAR)
|
||||
@@ -6807,12 +6891,15 @@ class RawDemosaicProcessor {
|
||||
textureId = sharpenTextureId,
|
||||
width = width,
|
||||
height = height,
|
||||
internalFormat = "RGBA8",
|
||||
internalFormat = "RGBA16F",
|
||||
)
|
||||
checkGlError("setupSharpenFramebuffer")
|
||||
}
|
||||
|
||||
private fun setupOutputFramebuffer(width: Int, height: Int) {
|
||||
require(width in 1..maxTextureSize && height in 1..maxTextureSize) {
|
||||
"RAW output ${width}x$height exceeds GL_MAX_TEXTURE_SIZE=$maxTextureSize"
|
||||
}
|
||||
if (outputFramebufferId != 0) {
|
||||
GLES30.glDeleteFramebuffers(1, intArrayOf(outputFramebufferId), 0)
|
||||
GLES30.glDeleteTextures(1, intArrayOf(outputTextureId), 0)
|
||||
@@ -6875,7 +6962,7 @@ class RawDemosaicProcessor {
|
||||
* 1. engine tone pass
|
||||
* 2. HNCS only: decode FilmCurve companding + HNCS -> linear output RGB
|
||||
* 3. optional adjustment pass: shadows/highlights + black/white levels in linear output RGB
|
||||
* 4. sRGB pass: linear output RGB -> sRGB encoded RGBA8 for sharpen/output
|
||||
* 4. sRGB pass: linear output RGB -> sRGB encoded RGBA16F for GuidedUpsample/sharpen/output
|
||||
*/
|
||||
private fun renderCombinedPass(
|
||||
metadata: RawMetadata,
|
||||
@@ -7568,21 +7655,23 @@ class RawDemosaicProcessor {
|
||||
rawData: ByteBuffer?,
|
||||
rowStride: Int,
|
||||
samplesPerPixel: Int,
|
||||
needsSharpen: Boolean,
|
||||
): RawMetadata {
|
||||
val needsSingleFrameDenoiseSnr =
|
||||
samplesPerPixel == 1 && frameCount == 1 && mgcDenoiseTuningSnr == null
|
||||
val needsSharpenSnr = needsSharpen && frameCount == 1 && mgcSharpenTuningSnr == null
|
||||
// Guided reconstruction is still required when the sharpening slider is zero.
|
||||
val needsSharpenSnr = mgcSharpenTuningSnr == null
|
||||
if (!needsSingleFrameDenoiseSnr && !needsSharpenSnr) {
|
||||
return this
|
||||
}
|
||||
val source = rawData ?: return this
|
||||
val signalStartNs = System.nanoTime()
|
||||
val signal = estimateMgcReferenceSignal(
|
||||
rawData = source,
|
||||
val measuredSignal = rawData?.let { estimateMgcReferenceSignal(
|
||||
rawData = it,
|
||||
rowStride = rowStride,
|
||||
samplesPerPixel = samplesPerPixel,
|
||||
) ?: return this
|
||||
) }
|
||||
// V25 EstimateSnr (0x5EDD674): absent mean and unapplied gain use 0.18.
|
||||
// Photon does not carry MGC's unapplied gain; do not substitute display EV.
|
||||
val signal = measuredSignal ?: 0.18f
|
||||
val signalElapsedMs = (System.nanoTime() - signalStartNs) / 1_000_000L
|
||||
val noiseModel = when (noiseProfileLayout) {
|
||||
RawNoiseProfileLayout.CAMERA2_CFA ->
|
||||
@@ -7605,30 +7694,27 @@ class RawDemosaicProcessor {
|
||||
val greenShot = 0.5f * (shot[1] + shot[2])
|
||||
val greenRead = 0.5f * (read[1] + read[2])
|
||||
val variance = greenShot * signal + greenRead
|
||||
val snr = if (variance.isFinite() && variance > 1e-12f) {
|
||||
check(variance.isFinite() && signal.isFinite() && signal >= 0f)
|
||||
// V25 returns zero when modeled variance is not positive; curve lookup
|
||||
// then uses its first SNR node. Missing noise data does not change geometry.
|
||||
val snr = if (variance > 0f) {
|
||||
signal / sqrt(variance)
|
||||
} else {
|
||||
Float.NaN
|
||||
}
|
||||
if (!snr.isFinite() || snr <= 0f) {
|
||||
PLog.w(
|
||||
TAG,
|
||||
"MGC RAW render tuning unavailable: signal=$signal " +
|
||||
"greenShot=$greenShot greenRead=$greenRead layout=$noiseProfileLayout",
|
||||
)
|
||||
return this
|
||||
0f
|
||||
}
|
||||
check(snr.isFinite() && snr >= 0f)
|
||||
PLog.i(
|
||||
TAG,
|
||||
"MGC RAW render tuning signal=$signal snr=$snr " +
|
||||
"greenShot=$greenShot greenRead=$greenRead " +
|
||||
"singleFrameDenoise=$needsSingleFrameDenoiseSnr " +
|
||||
"sharpen=$needsSharpenSnr " +
|
||||
"signalSource=NATIVE_OMP signalMs=$signalElapsedMs",
|
||||
"signalSource=${if (measuredSignal != null) "NATIVE_OMP" else "MGC_MISSING_MEAN"} " +
|
||||
"signalMs=$signalElapsedMs",
|
||||
)
|
||||
return copy(
|
||||
mgcSharpenTuningSnr = if (needsSharpenSnr) snr else mgcSharpenTuningSnr,
|
||||
mgcDenoiseTuningSnr = if (needsSingleFrameDenoiseSnr) {
|
||||
mgcDenoiseTuningSnr = if (needsSingleFrameDenoiseSnr && measuredSignal != null && snr > 0f) {
|
||||
snr
|
||||
} else {
|
||||
mgcDenoiseTuningSnr
|
||||
@@ -7693,36 +7779,25 @@ class RawDemosaicProcessor {
|
||||
}
|
||||
} ?: 1f
|
||||
val effectiveStrength = algorithmStrength * runtimeAttenuation
|
||||
if (effectiveStrength <= 0f) {
|
||||
if (effectiveStrength <= 0f && !mgcSharpen.guided.isPrepared) {
|
||||
renderSharpenPass(metadata, 0f, inputTextureId)
|
||||
return
|
||||
}
|
||||
val snr = metadata.mgcSharpenTuningSnr
|
||||
if (snr != null) {
|
||||
check(snr.isFinite() && snr > 0f) { "MGC sharpen reference SNR is invalid: $snr" }
|
||||
check(inputTextureId == combinedTextureId) { "MGC sharpen requires the encoded combined output" }
|
||||
stackCompletionTimeline?.awaitPending(
|
||||
syncPoint = "RAW_SHARPEN_INPUT", checkGlError = ::checkGlError,
|
||||
)?.let { PLog.i(TAG, "MGC sharpen upstreamStackGpuWait=${it.totalWaitMs}ms") }
|
||||
mgcSharpen.render(
|
||||
sourceTexture = inputTextureId,
|
||||
sourceFramebuffer = combinedFramebufferId,
|
||||
targetTexture = sharpenTextureId,
|
||||
width = metadata.width,
|
||||
height = metadata.height,
|
||||
snr = snr,
|
||||
attenuation = effectiveStrength,
|
||||
tuning = PhotonQualitySharpenTuning.resolve(metadata.rawMaxQualityTuningEnabled),
|
||||
)
|
||||
} else {
|
||||
// Non-MGC GPU-only sources may have no reference RAW/statistics available.
|
||||
PLog.w(TAG, "Original MGC sharpen unavailable: missing reference SNR; using GLES USM")
|
||||
renderSharpenPass(
|
||||
metadata,
|
||||
RawSharpeningDefaults.toAlgorithmStrength(sliderValue) * runtimeAttenuation,
|
||||
inputTextureId,
|
||||
)
|
||||
}
|
||||
val snr = checkNotNull(metadata.mgcSharpenTuningSnr) { "MGC finish tuning was not prepared" }
|
||||
check(snr.isFinite() && snr >= 0f) { "MGC sharpen reference SNR is invalid: $snr" }
|
||||
check(inputTextureId == combinedTextureId) { "MGC sharpen requires the encoded combined output" }
|
||||
stackCompletionTimeline?.awaitPending(
|
||||
syncPoint = "RAW_SHARPEN_INPUT", checkGlError = ::checkGlError,
|
||||
)?.let { PLog.i(TAG, "MGC sharpen upstreamStackGpuWait=${it.totalWaitMs}ms") }
|
||||
mgcSharpen.render(
|
||||
sourceTexture = inputTextureId,
|
||||
targetTexture = sharpenTextureId,
|
||||
width = metadata.width,
|
||||
height = metadata.height,
|
||||
snr = snr,
|
||||
attenuation = effectiveStrength,
|
||||
tuning = PhotonQualitySharpenTuning.resolve(metadata.rawMaxQualityTuningEnabled),
|
||||
)
|
||||
}
|
||||
|
||||
private fun renderSharpenPass(
|
||||
@@ -8871,6 +8946,10 @@ class RawDemosaicProcessor {
|
||||
bounds: Rect,
|
||||
sourceTextureId: Int,
|
||||
hdrSdrBaseTextureId: Int? = null,
|
||||
geometry: RawOutputGeometry? = null,
|
||||
outputRegion: RawTileRect? = geometry?.fullRegion,
|
||||
sourceOriginX: Int = 0,
|
||||
sourceOriginY: Int = 0,
|
||||
) {
|
||||
checkNotNull(
|
||||
outputPass.render(
|
||||
@@ -8883,6 +8962,12 @@ class RawDemosaicProcessor {
|
||||
targetFramebufferId = outputFramebufferId,
|
||||
targetTextureId = outputTextureId,
|
||||
hdrSdrBaseTextureId = hdrSdrBaseTextureId,
|
||||
geometry = geometry,
|
||||
outputRegion = outputRegion,
|
||||
sourceOriginX = sourceOriginX,
|
||||
sourceOriginY = sourceOriginY,
|
||||
targetWidth = outputRegion?.width ?: bounds.width(),
|
||||
targetHeight = outputRegion?.height ?: bounds.height(),
|
||||
),
|
||||
),
|
||||
) { "RAW output pass failed" }
|
||||
|
||||
@@ -0,0 +1,134 @@
|
||||
package com.hinnka.mycamera.raw
|
||||
|
||||
import android.opengl.GLES30
|
||||
import android.opengl.GLES31
|
||||
import com.hinnka.mycamera.processor.GlesGpuCompletion
|
||||
import java.nio.ByteBuffer
|
||||
import java.nio.ByteOrder
|
||||
|
||||
/** Float transport shared by the linear guide and encoded sharpening boundaries. */
|
||||
internal class RawFloatTextureTransfer {
|
||||
private var buffer = 0
|
||||
private var capacity = 0
|
||||
private var framebuffer = 0
|
||||
private var program = 0
|
||||
private var initialized = false
|
||||
private var maxSsboBytes = 0L
|
||||
|
||||
fun read(texture: Int, width: Int, height: Int, capacityPixels: Long = width.toLong() * height,
|
||||
consume: (ByteBuffer) -> Unit) {
|
||||
val inputBytes = width.toLong() * height * 16
|
||||
val bytes = capacityPixels * 16
|
||||
require(width > 0 && height > 0 && bytes >= inputBytes && bytes <= Int.MAX_VALUE)
|
||||
initialize()
|
||||
if (buffer == 0) {
|
||||
val names = IntArray(1)
|
||||
GLES30.glGenBuffers(1, names, 0)
|
||||
buffer = names[0]
|
||||
}
|
||||
GLES30.glBindBuffer(GLES30.GL_PIXEL_PACK_BUFFER, buffer)
|
||||
if (capacity < bytes) {
|
||||
GLES30.glBufferData(GLES30.GL_PIXEL_PACK_BUFFER, bytes.toInt(), null, GLES30.GL_STREAM_COPY)
|
||||
checkGl("allocate float transfer")
|
||||
capacity = bytes.toInt()
|
||||
}
|
||||
GlesGpuCompletion.awaitSubmittedWork("MGC float input", checkGlError = ::checkGl)
|
||||
try {
|
||||
if (program != 0 && bytes <= maxSsboBytes) {
|
||||
GLES31.glUseProgram(program)
|
||||
GLES31.glActiveTexture(GLES31.GL_TEXTURE0)
|
||||
GLES31.glBindTexture(GLES31.GL_TEXTURE_2D, texture)
|
||||
GLES31.glUniform1i(GLES31.glGetUniformLocation(program, "uInput"), 0)
|
||||
GLES31.glUniform2i(GLES31.glGetUniformLocation(program, "uSize"), width, height)
|
||||
GLES31.glBindBufferBase(GLES31.GL_SHADER_STORAGE_BUFFER, 0, buffer)
|
||||
GLES31.glDispatchCompute((width + 7) / 8, (height + 7) / 8, 1)
|
||||
GLES31.glMemoryBarrier(GLES31.GL_SHADER_STORAGE_BARRIER_BIT or GLES31.GL_BUFFER_UPDATE_BARRIER_BIT)
|
||||
GLES31.glBindBufferBase(GLES31.GL_SHADER_STORAGE_BUFFER, 0, 0)
|
||||
} else {
|
||||
if (framebuffer == 0) {
|
||||
val names = IntArray(1)
|
||||
GLES30.glGenFramebuffers(1, names, 0)
|
||||
framebuffer = names[0]
|
||||
}
|
||||
GLES30.glBindFramebuffer(GLES30.GL_READ_FRAMEBUFFER, framebuffer)
|
||||
GLES30.glFramebufferTexture2D(GLES30.GL_READ_FRAMEBUFFER, GLES30.GL_COLOR_ATTACHMENT0,
|
||||
GLES30.GL_TEXTURE_2D, texture, 0)
|
||||
check(GLES30.glCheckFramebufferStatus(GLES30.GL_READ_FRAMEBUFFER) == GLES30.GL_FRAMEBUFFER_COMPLETE)
|
||||
GLES30.glReadBuffer(GLES30.GL_COLOR_ATTACHMENT0)
|
||||
GLES30.glPixelStorei(GLES30.GL_PACK_ALIGNMENT, 1)
|
||||
GLES30.glPixelStorei(GLES30.GL_PACK_ROW_LENGTH, 0)
|
||||
GLES30.glReadPixels(0, 0, width, height, GLES30.GL_RGBA, GLES30.GL_FLOAT, 0)
|
||||
}
|
||||
checkGl("read float texture")
|
||||
val mapped = checkNotNull(GLES30.glMapBufferRange(GLES30.GL_PIXEL_PACK_BUFFER,
|
||||
0, bytes.toInt(), GLES30.GL_MAP_READ_BIT or GLES30.GL_MAP_WRITE_BIT) as? ByteBuffer)
|
||||
try {
|
||||
consume(mapped.order(ByteOrder.nativeOrder()))
|
||||
} finally {
|
||||
check(GLES30.glUnmapBuffer(GLES30.GL_PIXEL_PACK_BUFFER)) { "Invalid float transfer mapping" }
|
||||
}
|
||||
} finally {
|
||||
GLES30.glBindBuffer(GLES30.GL_PIXEL_PACK_BUFFER, 0)
|
||||
if (framebuffer != 0) {
|
||||
GLES30.glBindFramebuffer(GLES30.GL_READ_FRAMEBUFFER, framebuffer)
|
||||
GLES30.glFramebufferTexture2D(GLES30.GL_READ_FRAMEBUFFER, GLES30.GL_COLOR_ATTACHMENT0,
|
||||
GLES30.GL_TEXTURE_2D, 0, 0)
|
||||
}
|
||||
GLES30.glBindFramebuffer(GLES30.GL_READ_FRAMEBUFFER, 0)
|
||||
}
|
||||
}
|
||||
|
||||
fun upload(texture: Int, width: Int, height: Int) {
|
||||
check(nativeUpload(buffer, texture, width, height)) { "Float PBO upload failed" }
|
||||
}
|
||||
|
||||
fun releaseBuffers() {
|
||||
if (buffer != 0) GLES30.glDeleteBuffers(1, intArrayOf(buffer), 0)
|
||||
if (framebuffer != 0) GLES30.glDeleteFramebuffers(1, intArrayOf(framebuffer), 0)
|
||||
buffer = 0; framebuffer = 0; capacity = 0
|
||||
}
|
||||
|
||||
fun release() {
|
||||
releaseBuffers()
|
||||
if (program != 0) GLES30.glDeleteProgram(program)
|
||||
program = 0; initialized = false; maxSsboBytes = 0L
|
||||
}
|
||||
|
||||
private fun initialize() {
|
||||
if (initialized) return
|
||||
initialized = true
|
||||
val major = IntArray(1); val minor = IntArray(1)
|
||||
GLES30.glGetIntegerv(GLES30.GL_MAJOR_VERSION, major, 0)
|
||||
GLES30.glGetIntegerv(GLES30.GL_MINOR_VERSION, minor, 0)
|
||||
if (major[0] > 3 || major[0] == 3 && minor[0] >= 1) {
|
||||
val limit = LongArray(1)
|
||||
GLES31.glGetInteger64v(GLES31.GL_MAX_SHADER_STORAGE_BLOCK_SIZE, limit, 0)
|
||||
maxSsboBytes = limit[0]
|
||||
program = RawGlesProgram.compileCompute(PACK, "MgcFloatTransfer")
|
||||
}
|
||||
}
|
||||
|
||||
private external fun nativeUpload(pbo: Int, texture: Int, width: Int, height: Int): Boolean
|
||||
|
||||
companion object {
|
||||
init { System.loadLibrary("my-native-lib") }
|
||||
private fun checkGl(label: String) {
|
||||
val error = GLES30.glGetError()
|
||||
check(error == GLES30.GL_NO_ERROR) { "$label: GL error 0x${error.toString(16)}" }
|
||||
}
|
||||
internal val PACK = """
|
||||
#version 310 es
|
||||
precision highp float;
|
||||
precision highp int;
|
||||
layout(local_size_x = 8, local_size_y = 8) in;
|
||||
uniform highp sampler2D uInput;
|
||||
uniform ivec2 uSize;
|
||||
layout(std430, binding = 0) writeonly buffer Pixels { vec4 pixels[]; };
|
||||
void main() {
|
||||
ivec2 p = ivec2(gl_GlobalInvocationID.xy);
|
||||
if (any(greaterThanEqual(p, uSize))) return;
|
||||
pixels[p.y * uSize.x + p.x] = texelFetch(uInput, p, 0);
|
||||
}
|
||||
""".trimIndent()
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,68 @@
|
||||
package com.hinnka.mycamera.raw
|
||||
|
||||
import com.hinnka.mycamera.camera.MultiFrameConfig
|
||||
import kotlin.math.roundToInt
|
||||
|
||||
/** Final display sampling grid. RAW, denoise and sharpen always keep their native grid. */
|
||||
internal class RawOutputGeometry(val sourceBounds: RawTileRect, val rotation: Int, scale: Float) {
|
||||
init {
|
||||
require(rotation in setOf(0, 90, 180, 270))
|
||||
}
|
||||
private val nativeWidth = if (rotation % 180 == 0) sourceBounds.width else sourceBounds.height
|
||||
private val nativeHeight = if (rotation % 180 == 0) sourceBounds.height else sourceBounds.width
|
||||
val width = MultiFrameConfig.scaledRawOutputDimension(nativeWidth, scale)
|
||||
val height = MultiFrameConfig.scaledRawOutputDimension(nativeHeight, scale)
|
||||
val mgcFinishResolution = MgcFinishResolution.resolve(nativeWidth, nativeHeight, width, height)
|
||||
val resample = width != nativeWidth || height != nativeHeight
|
||||
val fullRegion = RawTileRect(0, 0, width, height)
|
||||
|
||||
/** Round shared edges once on the global grid, never resize each tile independently. */
|
||||
fun scaleRegion(region: RawTileRect) = RawTileRect(
|
||||
(region.left.toDouble() * width / nativeWidth).roundToInt(),
|
||||
(region.top.toDouble() * height / nativeHeight).roundToInt(),
|
||||
(region.right.toDouble() * width / nativeWidth).roundToInt(),
|
||||
(region.bottom.toDouble() * height / nativeHeight).roundToInt(),
|
||||
)
|
||||
|
||||
fun textureMatrix(
|
||||
sourceWidth: Int,
|
||||
sourceHeight: Int,
|
||||
originX: Int,
|
||||
originY: Int,
|
||||
region: RawTileRect,
|
||||
): FloatArray {
|
||||
fun sourcePoint(x: Double, y: Double): Pair<Double, Double> {
|
||||
val u = x / width
|
||||
val v = y / height
|
||||
val (sx, sy) = when (rotation) {
|
||||
0 -> u to v
|
||||
90 -> v to 1.0 - u
|
||||
180 -> 1.0 - u to 1.0 - v
|
||||
270 -> 1.0 - v to u
|
||||
else -> error("Unsupported RAW output rotation: $rotation")
|
||||
}
|
||||
return (sourceBounds.left + sx * sourceBounds.width - originX) / sourceWidth to
|
||||
(sourceBounds.top + sy * sourceBounds.height - originY) / sourceHeight
|
||||
}
|
||||
val p = sourcePoint(region.left.toDouble(), region.top.toDouble())
|
||||
val x = sourcePoint(region.right.toDouble(), region.top.toDouble())
|
||||
val y = sourcePoint(region.left.toDouble(), region.bottom.toDouble())
|
||||
return floatArrayOf(
|
||||
(x.first - p.first).toFloat(), (x.second - p.second).toFloat(), 0f, 0f,
|
||||
(y.first - p.first).toFloat(), (y.second - p.second).toFloat(), 0f, 0f,
|
||||
0f, 0f, 1f, 0f,
|
||||
p.first.toFloat(), p.second.toFloat(), 0f, 1f,
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
/** Stored separately from native DNG dimensions; older already-scaled DNGs default to 1x. */
|
||||
object RawOutputScaling {
|
||||
private const val KEY = "rawDisplayOutputScale"
|
||||
|
||||
fun read(properties: Map<String, String>): Float =
|
||||
MultiFrameConfig.normalizeOutputScale(properties[KEY]?.toFloatOrNull() ?: 1f)
|
||||
|
||||
fun write(properties: Map<String, String>, scale: Float): Map<String, String> =
|
||||
properties + (KEY to MultiFrameConfig.normalizeOutputScale(scale).toString())
|
||||
}
|
||||
@@ -3,9 +3,10 @@ package com.hinnka.mycamera.raw
|
||||
import android.graphics.Rect
|
||||
import android.opengl.GLES30
|
||||
import android.opengl.Matrix
|
||||
import com.hinnka.mycamera.processor.GlesLanczosResampling
|
||||
import com.hinnka.mycamera.utils.PLog
|
||||
|
||||
/** Applies output crop/rotation while copying the final texture to the readback target. */
|
||||
/** Crops/rotates finalized color; optional Lanczos-3 scaling runs after GuidedUpsample/sharpen. */
|
||||
internal class RawOutputPass(
|
||||
private val quad: RawFullscreenQuad,
|
||||
) {
|
||||
@@ -21,6 +22,10 @@ internal class RawOutputPass(
|
||||
val targetHeight: Int = bounds.height(),
|
||||
/** When present, [textureId] contains HDR ratios applied to this finalized sRGB base. */
|
||||
val hdrSdrBaseTextureId: Int? = null,
|
||||
val geometry: RawOutputGeometry? = null,
|
||||
val outputRegion: RawTileRect? = null,
|
||||
val sourceOriginX: Int = 0,
|
||||
val sourceOriginY: Int = 0,
|
||||
)
|
||||
|
||||
data class Output(val textureId: Int, val width: Int, val height: Int)
|
||||
@@ -71,17 +76,29 @@ internal class RawOutputPass(
|
||||
)
|
||||
Matrix.rotateM(textureMatrix, 0, -input.rotation.toFloat(), 0f, 0f, 1f)
|
||||
Matrix.translateM(textureMatrix, 0, -0.5f, -0.5f, 0f)
|
||||
val samplingMatrix = input.geometry?.textureMatrix(
|
||||
input.sourceWidth, input.sourceHeight, input.sourceOriginX, input.sourceOriginY,
|
||||
input.outputRegion ?: input.geometry.fullRegion,
|
||||
) ?: textureMatrix
|
||||
GLES30.glUniformMatrix4fv(
|
||||
GLES30.glGetUniformLocation(activeProgram, "uTexMatrix"),
|
||||
1,
|
||||
false,
|
||||
textureMatrix,
|
||||
samplingMatrix,
|
||||
0,
|
||||
)
|
||||
GLES30.glActiveTexture(GLES30.GL_TEXTURE0)
|
||||
GLES30.glBindTexture(GLES30.GL_TEXTURE_2D, input.textureId)
|
||||
GLES30.glUniform1i(GLES30.glGetUniformLocation(activeProgram, "uTexture"), 0)
|
||||
bindHdrBase(activeProgram, input.hdrSdrBaseTextureId, input.textureId)
|
||||
GLES30.glUniform1i(
|
||||
GLES30.glGetUniformLocation(activeProgram, "uResample"),
|
||||
if (input.geometry?.resample == true) 1 else 0,
|
||||
)
|
||||
GLES30.glUniform1i(
|
||||
GLES30.glGetUniformLocation(activeProgram, "uNativeGrid"),
|
||||
if (input.geometry != null && !input.geometry.resample) 1 else 0,
|
||||
)
|
||||
quad.draw(activeProgram)
|
||||
RawGlesProgram.logErrors("RawOutputPass.render")
|
||||
return Output(input.targetTextureId, input.targetWidth, input.targetHeight)
|
||||
@@ -104,6 +121,8 @@ internal class RawOutputPass(
|
||||
GLES30.glBindTexture(GLES30.GL_TEXTURE_2D, textureId)
|
||||
GLES30.glUniform1i(GLES30.glGetUniformLocation(activeProgram, "uTexture"), 0)
|
||||
bindHdrBase(activeProgram, null, textureId)
|
||||
GLES30.glUniform1i(GLES30.glGetUniformLocation(activeProgram, "uResample"), 0)
|
||||
GLES30.glUniform1i(GLES30.glGetUniformLocation(activeProgram, "uNativeGrid"), 1)
|
||||
quad.draw(activeProgram)
|
||||
RawGlesProgram.logErrors("RawOutputPass.copy")
|
||||
return Output(targetTextureId, width, height)
|
||||
@@ -138,6 +157,8 @@ internal class RawOutputPass(
|
||||
val FRAGMENT_SHADER = """
|
||||
#version 300 es
|
||||
precision highp float;
|
||||
precision highp int;
|
||||
precision highp sampler2D;
|
||||
|
||||
in vec2 vTexCoord;
|
||||
out vec4 fragColor;
|
||||
@@ -145,6 +166,17 @@ internal class RawOutputPass(
|
||||
uniform sampler2D uTexture;
|
||||
uniform sampler2D uSdrBase;
|
||||
uniform int uApplyHdrGain;
|
||||
uniform int uResample;
|
||||
uniform int uNativeGrid;
|
||||
|
||||
vec3 lanczosSource(ivec2 p) {
|
||||
ivec2 size = textureSize(uTexture, 0);
|
||||
p = clamp(p, ivec2(0), size - ivec2(1));
|
||||
if (uApplyHdrGain != 0) return texelFetch(uSdrBase, p, 0).rgb;
|
||||
return texelFetch(uTexture, p, 0).rgb;
|
||||
}
|
||||
|
||||
${GlesLanczosResampling.sampleRgb.prependIndent(" ")}
|
||||
|
||||
vec3 srgbToLinear(vec3 color) {
|
||||
return mix(
|
||||
@@ -156,9 +188,25 @@ internal class RawOutputPass(
|
||||
|
||||
void main() {
|
||||
vec4 source = texture(uTexture, vTexCoord);
|
||||
vec3 sdr = uApplyHdrGain != 0 ? texture(uSdrBase, vTexCoord).rgb : source.rgb;
|
||||
if (uNativeGrid != 0) {
|
||||
// A 1x rotated crop is an exact pixel copy, with no bilinear filtering.
|
||||
ivec2 p = clamp(ivec2(vTexCoord * vec2(textureSize(uTexture, 0))),
|
||||
ivec2(0), textureSize(uTexture, 0) - ivec2(1));
|
||||
source = texelFetch(uTexture, p, 0);
|
||||
sdr = uApplyHdrGain != 0 ? texelFetch(uSdrBase, p, 0).rgb : source.rgb;
|
||||
}
|
||||
float hdrGain = source.r;
|
||||
if (uResample != 0) {
|
||||
sdr = clamp(sampleLanczosRgb(
|
||||
vTexCoord * vec2(textureSize(uTexture, 0)) - vec2(0.5)
|
||||
), 0.0, 1.0);
|
||||
source = vec4(sdr, 1.0);
|
||||
}
|
||||
if (uApplyHdrGain != 0) {
|
||||
vec3 sdrLinear = srgbToLinear(texture(uSdrBase, vTexCoord).rgb);
|
||||
source = vec4(sdrLinear * source.r, 1.0);
|
||||
// Use exactly the same reconstructed SDR as the display branch. The smooth
|
||||
// HDR ratio stays bilinear; sharpening/Lanczos must not ring that gain field.
|
||||
source = vec4(srgbToLinear(sdr) * hdrGain, 1.0);
|
||||
}
|
||||
fragColor = source;
|
||||
}
|
||||
|
||||
@@ -77,7 +77,8 @@ internal class RawSrgbPass(
|
||||
|
||||
void main() {
|
||||
vec3 color = texture(uInputTexture, vTexCoord).rgb;
|
||||
fragColor = vec4(linearToSrgb(color), 1.0);
|
||||
// Retain the former UNORM target's SDR range without its 8-bit quantization.
|
||||
fragColor = vec4(clamp(linearToSrgb(color), 0.0, 1.0), 1.0);
|
||||
}
|
||||
""".trimIndent()
|
||||
}
|
||||
|
||||
@@ -36,7 +36,7 @@ internal data class RawRenderTile(
|
||||
* Tiles own disjoint output cores. The overlap in [RawRenderTile.sourceWorking] is dependency
|
||||
* data only and is never copied to the destination. Working rectangles use a stable size wherever
|
||||
* the sensor permits it, so all GPU textures can be retained and reused by the serial tile
|
||||
* consumer. Their origins are aligned to the sensor CFA period.
|
||||
* consumer. Their origins preserve both the CFA and downstream reconstruction grid.
|
||||
*/
|
||||
internal object RawTilePlanner {
|
||||
/** Ordinary 12 MP 4:3 captures stay on the full-frame path in either orientation. */
|
||||
@@ -58,6 +58,7 @@ internal object RawTilePlanner {
|
||||
coreEdgePx: Int,
|
||||
supportPx: Int,
|
||||
cfaPeriod: Int,
|
||||
processingPeriod: Int = 1,
|
||||
): List<RawRenderTile> {
|
||||
require(sourceWidth > 0 && sourceHeight > 0)
|
||||
require(
|
||||
@@ -66,7 +67,10 @@ internal object RawTilePlanner {
|
||||
outputSourceBounds.bottom <= sourceHeight
|
||||
)
|
||||
require(rotation in setOf(0, 90, 180, 270))
|
||||
val phase = cfaPeriod.coerceAtLeast(2)
|
||||
require(processingPeriod > 0)
|
||||
val cfaPhase = cfaPeriod.coerceAtLeast(2)
|
||||
tailrec fun gcd(a: Int, b: Int): Int = if (b == 0) a else gcd(b, a % b)
|
||||
val phase = Math.multiplyExact(cfaPhase / gcd(cfaPhase, processingPeriod), processingPeriod)
|
||||
val maximumCoreEdge =
|
||||
alignDown(coreEdgePx.coerceAtLeast(phase), phase).coerceAtLeast(phase)
|
||||
val support = supportPx.coerceAtLeast(0)
|
||||
|
||||
@@ -0,0 +1,357 @@
|
||||
// Standalone ARM64 probe: no APK or Android instrumentation installation.
|
||||
#include "mgc_denoise_static.h"
|
||||
#include "mgc_sharpen_adapter.h"
|
||||
#include <EGL/egl.h>
|
||||
#include <GLES3/gl31.h>
|
||||
#include <algorithm>
|
||||
#include <cmath>
|
||||
#include <cstdio>
|
||||
#include <cstdlib>
|
||||
#include <fstream>
|
||||
#include <iterator>
|
||||
#include <jni.h>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
using namespace photon::mgc_denoise;
|
||||
extern "C" jlong Java_com_hinnka_mycamera_raw_MgcGuidedUpsample_nativePrepare(
|
||||
JNIEnv *, jobject, jobject, jint, jint, jint, jfloatArray);
|
||||
extern "C" jint Java_com_hinnka_mycamera_raw_MgcGuidedUpsample_nativeRender(
|
||||
JNIEnv *, jobject, jlong, jobject, jfloat, jfloatArray);
|
||||
extern "C" void
|
||||
Java_com_hinnka_mycamera_raw_MgcGuidedUpsample_nativeRelease(JNIEnv *, jobject,
|
||||
jlong);
|
||||
extern "C" jboolean
|
||||
Java_com_hinnka_mycamera_raw_RawFloatTextureTransfer_nativeUpload(JNIEnv *,
|
||||
jobject, jint,
|
||||
jint, jint,
|
||||
jint);
|
||||
static void Check(bool ok, const char *message) {
|
||||
if (!ok) {
|
||||
fprintf(stderr, "FAIL %s\n", message);
|
||||
exit(1);
|
||||
}
|
||||
}
|
||||
template <class T>
|
||||
static void Write(const std::string &path, const std::vector<T> &v) {
|
||||
FILE *f = fopen(path.c_str(), "wb");
|
||||
Check(f, "open fixture");
|
||||
Check(fwrite(v.data(), sizeof(T), v.size(), f) == v.size(), "write fixture");
|
||||
fclose(f);
|
||||
}
|
||||
struct Buffer {
|
||||
void *data;
|
||||
jlong bytes;
|
||||
};
|
||||
static JNIEnv FakeJni() {
|
||||
static JNINativeInterface functions{};
|
||||
functions.GetDirectBufferAddress = [](JNIEnv *, jobject b) {
|
||||
return reinterpret_cast<Buffer *>(b)->data;
|
||||
};
|
||||
functions.GetDirectBufferCapacity = [](JNIEnv *, jobject b) {
|
||||
return reinterpret_cast<Buffer *>(b)->bytes;
|
||||
};
|
||||
functions.GetArrayLength = [](JNIEnv *, jarray a) {
|
||||
return jsize(reinterpret_cast<Buffer *>(a)->bytes / 4);
|
||||
};
|
||||
functions.GetFloatArrayRegion = [](JNIEnv *, jfloatArray a, jsize start,
|
||||
jsize n, jfloat *out) {
|
||||
auto *p = static_cast<float *>(reinterpret_cast<Buffer *>(a)->data);
|
||||
std::copy(p + start, p + start + n, out);
|
||||
};
|
||||
functions.ExceptionCheck = [](JNIEnv *) -> jboolean { return JNI_FALSE; };
|
||||
return JNIEnv{&functions};
|
||||
}
|
||||
static std::vector<float> Curves() {
|
||||
std::vector<float> a(30);
|
||||
for (int c = 0; c < 3; c++)
|
||||
for (int p = 0; p < 5; p++) {
|
||||
a[c * 5 + p] = p * .25f;
|
||||
a[15 + c * 5 + p] = a[c * 5 + p] * 1.375f;
|
||||
}
|
||||
return a;
|
||||
}
|
||||
static std::vector<float> Jni(int w, int h, int scale, int originX = 0, int originY = 0) {
|
||||
auto env = FakeJni();
|
||||
const int pw = (w + 127) & ~127, ph = (h + 15) & ~15, lw = pw / scale,
|
||||
lh = ph / scale;
|
||||
const size_t count = std::max(size_t(w) * h, size_t(lw) * lh);
|
||||
std::vector<float> pixels(count * 4 + 16, 123.f);
|
||||
for (int i = 0; i < w * h; i++) {
|
||||
const int x = i % w + originX, y = i / w + originY;
|
||||
pixels[i * 4] = .18f + ((x * 17 + y * 3) % 113) * .0004f;
|
||||
pixels[i * 4 + 1] = .18f + ((x * 3 + y * 13) % 127) * .0003f;
|
||||
pixels[i * 4 + 2] = .18f;
|
||||
pixels[i * 4 + 3] = 1;
|
||||
}
|
||||
Buffer buffer{pixels.data(), jlong(count * 16)};
|
||||
float wb[] = {1, 1, 1};
|
||||
Buffer gains{wb, 12};
|
||||
auto handle = Java_com_hinnka_mycamera_raw_MgcGuidedUpsample_nativePrepare(
|
||||
&env, nullptr, reinterpret_cast<jobject>(&buffer), w, h, scale == 2 ? 1 : 2,
|
||||
reinterpret_cast<jfloatArray>(&gains));
|
||||
Check(handle != 0, "JNI prepare including original low YUV->RGB");
|
||||
for (int i = 0; i < lw * lh; i++)
|
||||
for (int c = 0; c < 3; c++)
|
||||
pixels[i * 4 + c] = sqrtf(std::max(0.f, pixels[i * 4 + c]));
|
||||
auto curves = Curves();
|
||||
Buffer curve{curves.data(), 120};
|
||||
int result = Java_com_hinnka_mycamera_raw_MgcGuidedUpsample_nativeRender(
|
||||
&env, nullptr, handle, reinterpret_cast<jobject>(&buffer), 1.f,
|
||||
reinterpret_cast<jfloatArray>(&curve));
|
||||
Java_com_hinnka_mycamera_raw_MgcGuidedUpsample_nativeRelease(&env, nullptr,
|
||||
handle);
|
||||
Check(result == 0, "JNI guided render");
|
||||
for (int i = 0; i < w * h; i++)
|
||||
for (int c = 0; c < 4; c++)
|
||||
Check(std::isfinite(pixels[i * 4 + c]) && pixels[i * 4 + c] >= 0 &&
|
||||
pixels[i * 4 + c] <= 1,
|
||||
"finite float output");
|
||||
for (size_t i = count * 4; i < pixels.size(); i++)
|
||||
Check(pixels[i] == 123.f, "JNI buffer guard");
|
||||
printf("JNI %dx%d passed\n", w, h);
|
||||
pixels.resize(size_t(w) * h * 4);
|
||||
return pixels;
|
||||
}
|
||||
static void Gpu(const char *shaderPath, const char *boxPath) {
|
||||
EGLDisplay display = eglGetDisplay(EGL_DEFAULT_DISPLAY);
|
||||
Check(eglInitialize(display, nullptr, nullptr), "EGL initialize");
|
||||
EGLint attributes[] = {EGL_SURFACE_TYPE, EGL_PBUFFER_BIT, EGL_RENDERABLE_TYPE,
|
||||
EGL_OPENGL_ES3_BIT, EGL_NONE};
|
||||
EGLConfig config;
|
||||
EGLint count;
|
||||
Check(eglChooseConfig(display, attributes, &config, 1, &count) && count > 0,
|
||||
"EGL config");
|
||||
EGLint ca[] = {EGL_CONTEXT_CLIENT_VERSION, 3, EGL_NONE},
|
||||
pa[] = {EGL_WIDTH, 1, EGL_HEIGHT, 1, EGL_NONE};
|
||||
auto context = eglCreateContext(display, config, EGL_NO_CONTEXT, ca);
|
||||
auto surface = eglCreatePbufferSurface(display, config, pa);
|
||||
Check(eglMakeCurrent(display, surface, surface, context), "EGL current");
|
||||
printf("GPU %s / %s\n", glGetString(GL_RENDERER), glGetString(GL_VERSION));
|
||||
const int w = 37, h = 19, n = w * h;
|
||||
std::vector<float> pixels(n * 4);
|
||||
for (int i = 0; i < n; i++) {
|
||||
pixels[i * 4] = i / 2048.f;
|
||||
pixels[i * 4 + 1] = (n - i) / 2048.f;
|
||||
pixels[i * 4 + 2] = .25f;
|
||||
pixels[i * 4 + 3] = 1;
|
||||
}
|
||||
GLuint textures[2];
|
||||
glGenTextures(2, textures);
|
||||
for (auto t : textures) {
|
||||
glBindTexture(GL_TEXTURE_2D, t);
|
||||
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
|
||||
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
|
||||
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA16F, w, h, 0, GL_RGBA, GL_FLOAT,
|
||||
pixels.data());
|
||||
}
|
||||
GLuint framebuffer, pbo;
|
||||
glGenFramebuffers(1, &framebuffer);
|
||||
glBindFramebuffer(GL_FRAMEBUFFER, framebuffer);
|
||||
glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D,
|
||||
textures[0], 0);
|
||||
Check(glCheckFramebufferStatus(GL_FRAMEBUFFER) == GL_FRAMEBUFFER_COMPLETE,
|
||||
"RGBA16F framebuffer");
|
||||
glGenBuffers(1, &pbo);
|
||||
glBindBuffer(GL_PIXEL_PACK_BUFFER, pbo);
|
||||
glBufferData(GL_PIXEL_PACK_BUFFER, pixels.size() * 4, nullptr,
|
||||
GL_STREAM_COPY);
|
||||
glReadPixels(0, 0, w, h, GL_RGBA, GL_FLOAT, nullptr);
|
||||
auto *mapped = static_cast<float *>(glMapBufferRange(
|
||||
GL_PIXEL_PACK_BUFFER, 0, pixels.size() * 4, GL_MAP_READ_BIT));
|
||||
Check(mapped && std::equal(pixels.begin(), pixels.end(), mapped),
|
||||
"float PBO fallback preserves all samples");
|
||||
Check(glUnmapBuffer(GL_PIXEL_PACK_BUFFER), "PBO unmap");
|
||||
glBindBuffer(GL_PIXEL_PACK_BUFFER, 0);
|
||||
std::ifstream file(shaderPath);
|
||||
std::string source((std::istreambuf_iterator<char>(file)), {});
|
||||
Check(!source.empty(), "production shader source");
|
||||
const char *text = source.c_str();
|
||||
GLuint shader = glCreateShader(GL_COMPUTE_SHADER);
|
||||
glShaderSource(shader, 1, &text, nullptr);
|
||||
glCompileShader(shader);
|
||||
GLint ok;
|
||||
glGetShaderiv(shader, GL_COMPILE_STATUS, &ok);
|
||||
Check(ok, "float compute compile");
|
||||
GLuint program = glCreateProgram();
|
||||
glAttachShader(program, shader);
|
||||
glLinkProgram(program);
|
||||
glGetProgramiv(program, GL_LINK_STATUS, &ok);
|
||||
Check(ok, "float compute link");
|
||||
glUseProgram(program);
|
||||
glActiveTexture(GL_TEXTURE0);
|
||||
glBindTexture(GL_TEXTURE_2D, textures[0]);
|
||||
glUniform1i(glGetUniformLocation(program, "uInput"), 0);
|
||||
glUniform2i(glGetUniformLocation(program, "uSize"), w, h);
|
||||
glBindBufferBase(GL_SHADER_STORAGE_BUFFER, 0, pbo);
|
||||
glDispatchCompute((w + 7) / 8, (h + 7) / 8, 1);
|
||||
glMemoryBarrier(GL_SHADER_STORAGE_BARRIER_BIT | GL_BUFFER_UPDATE_BARRIER_BIT);
|
||||
glBindBufferBase(GL_SHADER_STORAGE_BUFFER, 0, 0);
|
||||
glBindBuffer(GL_PIXEL_PACK_BUFFER, pbo);
|
||||
mapped = static_cast<float *>(
|
||||
glMapBufferRange(GL_PIXEL_PACK_BUFFER, 0, pixels.size() * 4,
|
||||
GL_MAP_READ_BIT | GL_MAP_WRITE_BIT));
|
||||
Check(mapped && std::equal(pixels.begin(), pixels.end(), mapped),
|
||||
"float SSBO preserves all samples including tail");
|
||||
for (int i = 0; i < n; i++)
|
||||
mapped[i * 4] += .125f;
|
||||
Check(glUnmapBuffer(GL_PIXEL_PACK_BUFFER), "SSBO unmap");
|
||||
glBindBuffer(GL_PIXEL_PACK_BUFFER, 0);
|
||||
Check(Java_com_hinnka_mycamera_raw_RawFloatTextureTransfer_nativeUpload(
|
||||
nullptr, nullptr, pbo, textures[1], w, h),
|
||||
"native float upload");
|
||||
glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D,
|
||||
textures[1], 0);
|
||||
std::vector<float> result(n * 4);
|
||||
glReadPixels(0, 0, w, h, GL_RGBA, GL_FLOAT, result.data());
|
||||
for (int i = 0; i < n; i++)
|
||||
Check(result[i * 4] == pixels[i * 4] + .125f,
|
||||
"RGBA16F upload/sample precision");
|
||||
// Exercise Filmic's new padded linear-color branch with the production
|
||||
// shader.
|
||||
std::ifstream boxFile(boxPath);
|
||||
std::string boxSource((std::istreambuf_iterator<char>(boxFile)), {});
|
||||
Check(!boxSource.empty(), "production box shader");
|
||||
const char *vertexSource =
|
||||
"#version 300 es\nvoid main(){vec2 "
|
||||
"p=vec2(float((gl_VertexID<<1)&2),float(gl_VertexID&2));gl_Position=vec4("
|
||||
"p*2.0-1.0,0.0,1.0);}";
|
||||
GLuint vs = glCreateShader(GL_VERTEX_SHADER),
|
||||
fs = glCreateShader(GL_FRAGMENT_SHADER);
|
||||
const char *boxText = boxSource.c_str();
|
||||
glShaderSource(vs, 1, &vertexSource, nullptr);
|
||||
glCompileShader(vs);
|
||||
glShaderSource(fs, 1, &boxText, nullptr);
|
||||
glCompileShader(fs);
|
||||
glGetShaderiv(vs, GL_COMPILE_STATUS, &ok);
|
||||
Check(ok, "box vertex compile");
|
||||
glGetShaderiv(fs, GL_COMPILE_STATUS, &ok);
|
||||
Check(ok, "box fragment compile");
|
||||
GLuint boxProgram = glCreateProgram();
|
||||
glAttachShader(boxProgram, vs);
|
||||
glAttachShader(boxProgram, fs);
|
||||
glLinkProgram(boxProgram);
|
||||
glGetProgramiv(boxProgram, GL_LINK_STATUS, &ok);
|
||||
Check(ok, "box program");
|
||||
for (int scale : {2, 4}) {
|
||||
const int lw = 128 / scale, lh = 32 / scale;
|
||||
glBindTexture(GL_TEXTURE_2D, textures[1]);
|
||||
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA16F, lw, lh, 0, GL_RGBA, GL_FLOAT,
|
||||
nullptr);
|
||||
glBindTexture(GL_TEXTURE_2D, textures[0]);
|
||||
glUseProgram(boxProgram);
|
||||
glUniform1i(glGetUniformLocation(boxProgram, "uInput"), 0);
|
||||
glUniform1i(glGetUniformLocation(boxProgram, "uScale"), scale);
|
||||
glViewport(0, 0, lw, lh);
|
||||
glDrawArrays(GL_TRIANGLES, 0, 3);
|
||||
std::vector<float> boxed(lw * lh * 4);
|
||||
glReadPixels(0, 0, lw, lh, GL_RGBA, GL_FLOAT, boxed.data());
|
||||
for (int y = 0; y < lh; y++)
|
||||
for (int x = 0; x < lw; x++)
|
||||
for (int c = 0; c < 4; c++) {
|
||||
float expected = 0;
|
||||
for (int dy = 0; dy < scale; dy++)
|
||||
for (int dx = 0; dx < scale; dx++)
|
||||
expected += pixels[(std::min(y * scale + dy, h - 1) * w +
|
||||
std::min(x * scale + dx, w - 1)) *
|
||||
4 +
|
||||
c] *
|
||||
(1.f / (scale * scale));
|
||||
Check(std::abs(boxed[(y * lw + x) * 4 + c] - expected) <= 1.f / 4096,
|
||||
"padded linear box samples");
|
||||
}
|
||||
}
|
||||
glDeleteProgram(boxProgram);
|
||||
glDeleteShader(vs);
|
||||
glDeleteShader(fs);
|
||||
printf("GPU padded linear color box passed\n");
|
||||
Check(glGetError() == GL_NO_ERROR, "GPU errors");
|
||||
glDeleteTextures(2, textures);
|
||||
glDeleteBuffers(1, &pbo);
|
||||
glDeleteFramebuffers(1, &framebuffer);
|
||||
glDeleteProgram(program);
|
||||
glDeleteShader(shader);
|
||||
eglMakeCurrent(display, EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT);
|
||||
eglDestroySurface(display, surface);
|
||||
eglDestroyContext(display, context);
|
||||
eglTerminate(display);
|
||||
printf("GPU float SSBO/PBO/upload 37x19 passed\n");
|
||||
}
|
||||
|
||||
int main(int argc, char **argv) {
|
||||
Check(argc == 4, "fixture output directory, float and box shaders");
|
||||
Gpu(argv[2], argv[3]);
|
||||
for (int scale : {2, 4}) {
|
||||
auto full = Jni(768, 640, scale);
|
||||
for (int origin : {0, 8, 16, 24, 56, 112}) {
|
||||
auto tile = Jni(385, 321, scale, origin, origin);
|
||||
size_t mismatch = 0;
|
||||
for (int y = 52; y < 321 - 52; y++)
|
||||
for (int x = 52; x < 385 - 52; x++)
|
||||
for (int c = 0; c < 3; c++)
|
||||
mismatch += tile[(y * 385 + x) * 4 + c] !=
|
||||
full[((y + origin) * 768 + x + origin) * 4 + c];
|
||||
printf("tile scale=%d origin=%d mismatches=%zu\n", scale, origin, mismatch);
|
||||
Check(!mismatch, "guided tile equivalence");
|
||||
}
|
||||
}
|
||||
for (auto size :
|
||||
{std::pair<int, int>{256, 64}, {129, 35}, {17, 19}, {1, 1}}) {
|
||||
int w = size.first, h = size.second, pw = (w + 127) & ~127,
|
||||
ph = (h + 15) & ~15;
|
||||
for (int scale : {2, 4}) Jni(w, h, scale);
|
||||
for (int scale : {2, 4})
|
||||
for (int strength : {0, 1}) {
|
||||
int lw = pw / scale, lh = ph / scale;
|
||||
size_t n = size_t(pw) * ph, ln = size_t(lw) * lh;
|
||||
std::vector<int16_t> input(n * 3), low(ln * 3), tone(ln * 3);
|
||||
for (int y = 0; y < ph; y++)
|
||||
for (int x = 0; x < pw; x++) {
|
||||
int xx = std::min(x, w - 1), yy = std::min(y, h - 1);
|
||||
size_t i = size_t(y) * pw + x;
|
||||
input[i] = 2000 + (xx * 31 + yy * 17) % 2000 +
|
||||
((xx + yy * 2) % 13 < 5 ? 1500 : 0) +
|
||||
(xx > w / 2 ? 2500 : 0);
|
||||
input[n + i] = (xx * 13 + yy * 23) % 400 - 200;
|
||||
input[n * 2 + i] = (xx * 17 + yy * 3) % 300 - 150;
|
||||
}
|
||||
Check(RunGuidedBoxDownsample(input.data(), pw, ph, scale == 2 ? 1 : 2,
|
||||
low.data()) == 0,
|
||||
"box");
|
||||
for (size_t i = 0; i < ln; i++) {
|
||||
tone[i] = std::min(4095, 200 + low[i] / 3);
|
||||
tone[ln + i] = low[ln + i] / 4;
|
||||
tone[ln * 2 + i] = low[ln * 2 + i] / 4;
|
||||
}
|
||||
auto curves = Curves();
|
||||
size_t outCount = size_t(w) * ((h + 1) & ~1) * 3;
|
||||
std::vector<uint16_t> out(outCount + 128, 65535);
|
||||
Check(RunGuidedUpsampleTo16Bit(input.data(), pw, ph, low.data(),
|
||||
tone.data(), scale, w, h, curves.data(),
|
||||
float(strength), out.data()) == 0,
|
||||
"guided");
|
||||
for (size_t i = outCount; i < out.size(); i++)
|
||||
Check(out[i] == 65535, "AOT output guard");
|
||||
out.resize(size_t(w) * h * 3);
|
||||
std::string base = std::string(argv[1]) + "/" + std::to_string(w) +
|
||||
"_" + std::to_string(h) + "_" +
|
||||
std::to_string(scale) + "_" +
|
||||
std::to_string(strength);
|
||||
Write(base + ".input", input);
|
||||
Write(base + ".low", low);
|
||||
Write(base + ".tone", tone);
|
||||
Write(base + ".curves", curves);
|
||||
Write(base + ".out", out);
|
||||
printf("AOT %dx%d scale=%d attenuation=%d passed\n", w, h, scale,
|
||||
strength);
|
||||
}
|
||||
}
|
||||
std::vector<float> rgba(16);
|
||||
for (int i = 0; i < 4; i++) {
|
||||
rgba[i * 4] = rgba[i * 4 + 1] = rgba[i * 4 + 2] = .5f + i / 4095.f;
|
||||
rgba[i * 4 + 3] = 1;
|
||||
}
|
||||
std::vector<int16_t> yuv(12);
|
||||
Check(SharpenFloatRgbaToYuv(rgba.data(), 4, yuv.data()), "float conversion");
|
||||
Check(yuv[0] < yuv[1] && yuv[1] < yuv[2] && yuv[2] < yuv[3],
|
||||
"sub-8bit detail preserved");
|
||||
}
|
||||
@@ -0,0 +1,244 @@
|
||||
#include <EGL/egl.h>
|
||||
#include <GLES3/gl3.h>
|
||||
#include <algorithm>
|
||||
#include <cmath>
|
||||
#include <cstdio>
|
||||
#include <cstdlib>
|
||||
#include <fstream>
|
||||
#include <iterator>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
void check(bool b, const char *msg) {
|
||||
if (!b) {
|
||||
fprintf(stderr, "FAIL %s GL=%x\n", msg, glGetError());
|
||||
exit(1);
|
||||
}
|
||||
}
|
||||
GLuint compile(GLenum type, const char *text) {
|
||||
GLuint s = glCreateShader(type);
|
||||
glShaderSource(s, 1, &text, nullptr);
|
||||
glCompileShader(s);
|
||||
GLint ok;
|
||||
glGetShaderiv(s, GL_COMPILE_STATUS, &ok);
|
||||
if (!ok) {
|
||||
char log[8192];
|
||||
glGetShaderInfoLog(s, 8192, nullptr, log);
|
||||
puts(log);
|
||||
}
|
||||
check(ok, "compile");
|
||||
return s;
|
||||
}
|
||||
GLuint texture(int w, int h, const std::vector<float> *data) {
|
||||
GLuint t;
|
||||
glGenTextures(1, &t);
|
||||
glBindTexture(GL_TEXTURE_2D, t);
|
||||
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA16F, w, h, 0, GL_RGBA, GL_FLOAT,
|
||||
data ? data->data() : nullptr);
|
||||
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
|
||||
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
|
||||
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
|
||||
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
|
||||
return t;
|
||||
}
|
||||
double weight(double x) {
|
||||
x = std::abs(x);
|
||||
if (x < 1e-6)
|
||||
return 1;
|
||||
if (x >= 3)
|
||||
return 0;
|
||||
double p = x * 3.141592653589793;
|
||||
return sin(p) / p * sin(p / 3) / (p / 3);
|
||||
}
|
||||
int main(int argc, char **argv) {
|
||||
check(argc == 3, "production fragment and vertex shader paths");
|
||||
EGLDisplay d = eglGetDisplay(EGL_DEFAULT_DISPLAY);
|
||||
check(eglInitialize(d, nullptr, nullptr), "egl");
|
||||
EGLint attrs[] = {EGL_SURFACE_TYPE, EGL_PBUFFER_BIT, EGL_RENDERABLE_TYPE,
|
||||
EGL_OPENGL_ES3_BIT, EGL_NONE};
|
||||
EGLConfig cfg;
|
||||
EGLint n;
|
||||
check(eglChooseConfig(d, attrs, &cfg, 1, &n) && n, "config");
|
||||
EGLint ca[] = {EGL_CONTEXT_CLIENT_VERSION, 3, EGL_NONE},
|
||||
pa[] = {EGL_WIDTH, 1, EGL_HEIGHT, 1, EGL_NONE};
|
||||
auto ctx = eglCreateContext(d, cfg, EGL_NO_CONTEXT, ca);
|
||||
auto surf = eglCreatePbufferSurface(d, cfg, pa);
|
||||
check(eglMakeCurrent(d, surf, surf, ctx), "current");
|
||||
printf("%s / %s\n", glGetString(GL_RENDERER), glGetString(GL_VERSION));
|
||||
std::ifstream ff(argv[1]), vf(argv[2]);
|
||||
std::string fs((std::istreambuf_iterator<char>(ff)), {}),
|
||||
vs((std::istreambuf_iterator<char>(vf)), {});
|
||||
check(fs.rfind("#version", 0) == 0 && vs.rfind("#version", 0) == 0,
|
||||
"version first byte");
|
||||
GLuint frag = compile(GL_FRAGMENT_SHADER, fs.c_str()),
|
||||
vert = compile(GL_VERTEX_SHADER, vs.c_str()), prog = glCreateProgram();
|
||||
glAttachShader(prog, frag);
|
||||
glAttachShader(prog, vert);
|
||||
glLinkProgram(prog);
|
||||
GLint ok;
|
||||
glGetProgramiv(prog, GL_LINK_STATUS, &ok);
|
||||
check(ok, "link");
|
||||
glUseProgram(prog);
|
||||
const float pos[] = {-1, -1, 1, -1, -1, 1, 1, 1},
|
||||
uv[] = {0, 0, 1, 0, 0, 1, 1, 1};
|
||||
GLuint vbo[2];
|
||||
glGenBuffers(2, vbo);
|
||||
int i = 0;
|
||||
for (const char *attr : {"aPosition", "aTexCoord"}) {
|
||||
auto a = glGetAttribLocation(prog, attr);
|
||||
glBindBuffer(GL_ARRAY_BUFFER, vbo[i]);
|
||||
glBufferData(GL_ARRAY_BUFFER, sizeof(pos), i ? uv : pos, GL_STATIC_DRAW);
|
||||
glVertexAttribPointer(a, 2, GL_FLOAT, GL_FALSE, 0, nullptr);
|
||||
glEnableVertexAttribArray(a);
|
||||
++i;
|
||||
}
|
||||
const int W = 37, H = 29;
|
||||
std::vector<float> input(W * H * 4), gain(W * H * 4, 2.f);
|
||||
for (int y = 0; y < H; y++)
|
||||
for (int x = 0; x < W; x++) {
|
||||
int k = (y * W + x) * 4;
|
||||
input[k] = ((x + y) % 2 ? 0.9f : 0.1f);
|
||||
input[k + 1] = (x * 13 + y * 17) % 1024 / 1024.f;
|
||||
input[k + 2] = .5f + ((x + y) % 4) / 4096.f;
|
||||
input[k + 3] = 1.f;
|
||||
for (int c = 0; c < 4; c++)
|
||||
input[k + c] = float((_Float16)input[k + c]);
|
||||
}
|
||||
GLuint src = texture(W, H, &input), hdr = texture(W, H, &gain), fbo;
|
||||
glGenFramebuffers(1, &fbo);
|
||||
glBindFramebuffer(GL_FRAMEBUFFER, fbo);
|
||||
glUniform1i(glGetUniformLocation(prog, "uTexture"), 0);
|
||||
glUniform1i(glGetUniformLocation(prog, "uSdrBase"), 1);
|
||||
double worst = 0;
|
||||
int cases = 0;
|
||||
for (int rotation : {0, 90, 180, 270})
|
||||
for (double scale : {1., 1.3, 1.5, 2.})
|
||||
for (bool cropped : {false, true})
|
||||
for (bool isHdr : {false, true}) {
|
||||
int l = cropped ? 3 : 0, t = cropped ? 5 : 0, r = cropped ? 34 : W,
|
||||
b = cropped ? 26 : H;
|
||||
int nw = rotation % 180 ? b - t : r - l,
|
||||
nh = rotation % 180 ? r - l : b - t;
|
||||
int ow = std::lround(nw * scale), oh = std::lround(nh * scale);
|
||||
if (scale > 1) {
|
||||
ow -= ow % 2;
|
||||
oh -= oh % 2;
|
||||
}
|
||||
GLuint out = texture(ow, oh, nullptr);
|
||||
glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0,
|
||||
GL_TEXTURE_2D, out, 0);
|
||||
check(glCheckFramebufferStatus(GL_FRAMEBUFFER) ==
|
||||
GL_FRAMEBUFFER_COMPLETE,
|
||||
"fbo");
|
||||
auto coord = [&](double x, double y) {
|
||||
double u = x / ow, v = y / oh, sx, sy;
|
||||
switch (rotation) {
|
||||
case 0:
|
||||
sx = u;
|
||||
sy = v;
|
||||
break;
|
||||
case 90:
|
||||
sx = v;
|
||||
sy = 1 - u;
|
||||
break;
|
||||
case 180:
|
||||
sx = 1 - u;
|
||||
sy = 1 - v;
|
||||
break;
|
||||
default:
|
||||
sx = 1 - v;
|
||||
sy = u;
|
||||
}
|
||||
return std::pair<double, double>{l + sx * (r - l),
|
||||
t + sy * (b - t)};
|
||||
};
|
||||
// Draw irregular output regions with the global phase and compare all
|
||||
// resulting pixels.
|
||||
for (int top = 0; top < oh; top += 13)
|
||||
for (int left = 0; left < ow; left += 17) {
|
||||
int tw = std::min(17, ow - left), th = std::min(13, oh - top);
|
||||
auto p = coord(left, top), px = coord(left + tw, top),
|
||||
py = coord(left, top + th);
|
||||
float m[] = {float((px.first - p.first) / W),
|
||||
float((px.second - p.second) / H),
|
||||
0,
|
||||
0,
|
||||
float((py.first - p.first) / W),
|
||||
float((py.second - p.second) / H),
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
1,
|
||||
0,
|
||||
float(p.first / W),
|
||||
float(p.second / H),
|
||||
0,
|
||||
1};
|
||||
glUniformMatrix4fv(glGetUniformLocation(prog, "uTexMatrix"), 1,
|
||||
GL_FALSE, m);
|
||||
glUniform1i(glGetUniformLocation(prog, "uResample"), scale > 1);
|
||||
glUniform1i(glGetUniformLocation(prog, "uNativeGrid"),
|
||||
scale == 1);
|
||||
glUniform1i(glGetUniformLocation(prog, "uApplyHdrGain"), isHdr);
|
||||
glActiveTexture(GL_TEXTURE0);
|
||||
glBindTexture(GL_TEXTURE_2D, isHdr ? hdr : src);
|
||||
glActiveTexture(GL_TEXTURE1);
|
||||
glBindTexture(GL_TEXTURE_2D, src);
|
||||
glViewport(left, top, tw, th);
|
||||
glDrawArrays(GL_TRIANGLE_STRIP, 0, 4);
|
||||
}
|
||||
std::vector<float> result(ow * oh * 4);
|
||||
glReadPixels(0, 0, ow, oh, GL_RGBA, GL_FLOAT, result.data());
|
||||
check(glGetError() == GL_NO_ERROR, "draw/readback");
|
||||
for (int y = 0; y < oh; y++)
|
||||
for (int x = 0; x < ow; x++) {
|
||||
auto p = coord(x + .5, y + .5);
|
||||
double sx = p.first - .5, sy = p.second - .5;
|
||||
for (int c = 0; c < 3; c++) {
|
||||
double total = 0, sum = 0;
|
||||
int bx = floor(sx), by = floor(sy);
|
||||
for (int dy = -2; dy <= 3; dy++)
|
||||
for (int dx = -2; dx <= 3; dx++) {
|
||||
double w = weight(bx + dx - sx) * weight(by + dy - sy);
|
||||
total += input[(std::clamp(by + dy, 0, H - 1) * W +
|
||||
std::clamp(bx + dx, 0, W - 1)) *
|
||||
4 +
|
||||
c] *
|
||||
w;
|
||||
sum += w;
|
||||
}
|
||||
double expected = std::clamp(total / sum, 0., 1.);
|
||||
if (isHdr)
|
||||
expected = 2 * (expected <= .04045
|
||||
? expected / 12.92
|
||||
: pow((expected + .055) / 1.055, 2.4));
|
||||
double err = std::abs(result[(y * ow + x) * 4 + c] - expected);
|
||||
worst = std::max(worst, err);
|
||||
if (err > .002) {
|
||||
fprintf(stderr,
|
||||
"case r=%d s=%g crop=%d hdr=%d xy=%d,%d c=%d "
|
||||
"expected=%g actual=%g error=%g\n",
|
||||
rotation, scale, cropped, isHdr, x, y, c, expected,
|
||||
result[(y * ow + x) * 4 + c], err);
|
||||
exit(1);
|
||||
}
|
||||
}
|
||||
}
|
||||
glDeleteTextures(1, &out);
|
||||
cases++;
|
||||
}
|
||||
printf("PASS %d cases: rotations, 1/1.3/1.5/2x, full/crop, SDR/HDR, "
|
||||
"fractional tile edges; max error=%g\n",
|
||||
cases, worst);
|
||||
glDeleteTextures(1, &src);
|
||||
glDeleteTextures(1, &hdr);
|
||||
glDeleteFramebuffers(1, &fbo);
|
||||
glDeleteBuffers(2, vbo);
|
||||
glDeleteProgram(prog);
|
||||
glDeleteShader(frag);
|
||||
glDeleteShader(vert);
|
||||
eglMakeCurrent(d, EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT);
|
||||
eglDestroySurface(d, surf);
|
||||
eglDestroyContext(d, ctx);
|
||||
eglTerminate(d);
|
||||
}
|
||||
@@ -1,5 +1,6 @@
|
||||
package com.hinnka.mycamera.processor
|
||||
|
||||
import com.hinnka.mycamera.raw.RawOutputPass
|
||||
import java.io.File
|
||||
import org.junit.Assert.assertEquals
|
||||
import org.junit.Assert.assertFalse
|
||||
@@ -66,17 +67,6 @@ class GlesMgcRawSpatialShadersTest {
|
||||
assertFalse(shader.contains("texelFetch"))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun sabreOutputScalingConsumesTheComputeConvertedFloatTexture() {
|
||||
val shader = GlesMgcRawSabreShaders.resampleOutputLanczos
|
||||
|
||||
assertTrue(shader.contains("uniform sampler2D uSource"))
|
||||
assertFalse(shader.contains("usampler2D"))
|
||||
assertTrue(shader.contains("float lanczosWeight(float distance)"))
|
||||
assertTrue(shader.contains("if (x >= 3.0) return 0.0"))
|
||||
assertTrue(shader.contains("vec2(uSourceSize) / vec2(uOutputSize)"))
|
||||
assertTrue(shader.contains("* 65504.0"))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun rgbOpponentInterpolationIsGuidedByTheSameGreenReconstruction() {
|
||||
@@ -118,9 +108,8 @@ class GlesMgcRawSpatialShadersTest {
|
||||
listOf(
|
||||
GlesMgcRawSpatialShaders.mergeRgb,
|
||||
GlesMgcRawSpatialShaders.normalizeRgb16,
|
||||
GlesMgcRawSpatialShaders.resampleAotRgbHorizontal,
|
||||
GlesMgcRawSpatialShaders.normalizeAotRgb16,
|
||||
GlesMgcRawSabreShaders.resampleOutputLanczos,
|
||||
RawOutputPass.FRAGMENT_SHADER,
|
||||
GlesYuvSpatialShaders.lanczosOutput,
|
||||
GlesYuvSpatialShaders.lanczosFrameOutput,
|
||||
).forEachIndexed { index, shader ->
|
||||
|
||||
@@ -20,19 +20,4 @@ class MgcMergeMethodTest {
|
||||
assertEquals(MgcMergeMethod.SPATIAL_RGB, MgcRawMaxMode.SPATIAL.mergeMethod)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun bothRawMaxModesPreserveRequestedRgbOutputScale() {
|
||||
MgcRawMaxMode.entries.forEach { mode ->
|
||||
assertEquals(
|
||||
1.5f,
|
||||
resolveRawStackOutputScale(mode.outputMode, 1.5f),
|
||||
0f,
|
||||
)
|
||||
}
|
||||
assertEquals(
|
||||
1f,
|
||||
resolveRawStackOutputScale(MgcSpatialOutputMode.BAYER, 1.5f),
|
||||
0f,
|
||||
)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,38 @@
|
||||
package com.hinnka.mycamera.raw
|
||||
|
||||
import org.junit.Assert.*
|
||||
import org.junit.Test
|
||||
|
||||
class MgcFinishResolutionTest {
|
||||
@Test
|
||||
fun originalAutomaticPolicyChangesAtTwoTimesOutput() {
|
||||
for ((output, factor) in listOf(4000 to 4, 5200 to 4, 6000 to 4, 7998 to 4,
|
||||
8000 to 2, 12000 to 2, 16000 to 2)) {
|
||||
val resolution = MgcFinishResolution.resolve(4000, 3000, output, output * 3 / 4)
|
||||
assertEquals(factor, resolution.downsampleFactor)
|
||||
assertEquals(factor * 2, resolution.processingPeriod)
|
||||
assertTrue(resolution.needsGuidedUpsample)
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
fun largerAxisAndExplicitOriginalOverridesDetermineTheLevel() {
|
||||
assertEquals(2, MgcFinishResolution.resolve(4000, 3000, 4000, 6000).downsampleFactor)
|
||||
assertEquals(4, MgcFinishResolution.resolve(4000, 3000, 8000, 6000,
|
||||
scaleOverride = 1f).downsampleFactor)
|
||||
assertEquals(2, MgcFinishResolution.resolve(4000, 3000, 4000, 3000,
|
||||
scaleOverride = 2f).downsampleFactor)
|
||||
val direct = MgcFinishResolution.resolve(4000, 3000, 4000, 3000, levelOverride = 0)
|
||||
assertFalse(direct.needsGuidedUpsample)
|
||||
assertEquals(1, direct.downsampleFactor)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun rotationAndTilesUseTheSameWholeImageDecision() {
|
||||
val bounds = RawTileRect(12, 20, 4012, 3020)
|
||||
for (rotation in listOf(0, 90, 180, 270)) {
|
||||
assertEquals(4, RawOutputGeometry(bounds, rotation, 1f).mgcFinishResolution.downsampleFactor)
|
||||
assertEquals(2, RawOutputGeometry(bounds, rotation, 2f).mgcFinishResolution.downsampleFactor)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -66,7 +66,7 @@ class MgcSharpenCurveBuilderTest {
|
||||
fun bandAmountWorksAtNodesBetweenNodesAndBeyondTableAndDoesNotMoveOtherBands() {
|
||||
val original = PhotonSharpenTuning.DEFAULT
|
||||
val adjusted = original.copy(amount = PhotonSharpenBands(.5f, 0f, 1f))
|
||||
for (snr in listOf(.1f, 5f, 7.5f, 20f, 30f, 80f, 160f)) {
|
||||
for (snr in listOf(0f, .1f, 5f, 7.5f, 20f, 30f, 80f, 160f)) {
|
||||
val baseline = MgcSharpenCurveBuilder.build(snr, original)
|
||||
val actual = MgcSharpenCurveBuilder.build(snr, adjusted)
|
||||
assertEquals(baseline.interpolation, actual.interpolation, 0f)
|
||||
@@ -103,7 +103,7 @@ class MgcSharpenCurveBuilderTest {
|
||||
assertThrows(IllegalArgumentException::class.java) { PhotonSharpenTuning(emptyList()) }
|
||||
val node = PhotonSharpenTuning.DEFAULT.nodes.first()
|
||||
assertThrows(IllegalArgumentException::class.java) { PhotonSharpenTuning(listOf(node, node)) }
|
||||
assertThrows(IllegalArgumentException::class.java) { MgcSharpenCurveBuilder.build(0f, PhotonSharpenTuning.DEFAULT) }
|
||||
assertThrows(IllegalArgumentException::class.java) { MgcSharpenCurveBuilder.build(-1f, PhotonSharpenTuning.DEFAULT) }
|
||||
val suppress = PhotonSharpenCurve(lowContrastGain = 0f)
|
||||
val invalidExtrapolation = PhotonSharpenTuning(
|
||||
listOf(PhotonSharpenSnrNode(5f, suppress, suppress, suppress)),
|
||||
|
||||
@@ -0,0 +1,71 @@
|
||||
package com.hinnka.mycamera.raw
|
||||
|
||||
import org.junit.Assert.assertEquals
|
||||
import org.junit.Assert.assertTrue
|
||||
import org.junit.Test
|
||||
|
||||
class RawOutputGeometryTest {
|
||||
@Test
|
||||
fun fractionalScalingKeepsTileSamplesOnTheFullImageGrid() {
|
||||
val crop = RawTileRect(7, 11, 4986, 3478)
|
||||
for (rotation in listOf(0, 90, 180, 270)) {
|
||||
for (scale in listOf(1f, 1.3f, 1.5f, 2f)) {
|
||||
val geometry = RawOutputGeometry(crop, rotation, scale)
|
||||
val tiles = RawTilePlanner.plan(
|
||||
5003, 3501, crop, rotation, 2048, 115, 2, 4,
|
||||
)
|
||||
val fullMatrix = geometry.textureMatrix(5003, 3501, 0, 0, geometry.fullRegion)
|
||||
val regions = tiles.map { geometry.scaleRegion(it.outputCore) }
|
||||
assertEquals(geometry.width.toLong() * geometry.height,
|
||||
regions.sumOf { it.width.toLong() * it.height })
|
||||
for ((index, tile) in tiles.withIndex()) {
|
||||
val region = regions[index]
|
||||
val work = tile.sourceWorking
|
||||
val matrix = geometry.textureMatrix(
|
||||
work.width, work.height, work.left, work.top, region,
|
||||
)
|
||||
// Compare pixel centers at every corner and the center of every tile.
|
||||
for (x in listOf(0, region.width / 2, region.width - 1)) {
|
||||
for (y in listOf(0, region.height / 2, region.height - 1)) {
|
||||
val u = (x + 0.5) / region.width
|
||||
val v = (y + 0.5) / region.height
|
||||
val gu = (region.left + x + 0.5) / geometry.width
|
||||
val gv = (region.top + y + 0.5) / geometry.height
|
||||
val sx = (matrix[0] * u + matrix[4] * v + matrix[12]) * work.width + work.left
|
||||
val sy = (matrix[1] * u + matrix[5] * v + matrix[13]) * work.height + work.top
|
||||
assertEquals((fullMatrix[0] * gu + fullMatrix[4] * gv + fullMatrix[12]) * 5003, sx, 0.001)
|
||||
assertEquals((fullMatrix[1] * gu + fullMatrix[5] * gv + fullMatrix[13]) * 3501, sy, 0.001)
|
||||
assertTrue(sx >= work.left && sx <= work.right)
|
||||
assertTrue(sy >= work.top && sy <= work.bottom)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
fun rotationMapsFirstPixelToTheCorrectSensorCornerWithoutHalfPixelShift() {
|
||||
val crop = RawTileRect(7, 11, 108, 84)
|
||||
val expected = listOf(7.5 to 11.5, 7.5 to 83.5, 107.5 to 83.5, 107.5 to 11.5)
|
||||
for ((index, rotation) in listOf(0, 90, 180, 270).withIndex()) {
|
||||
val geometry = RawOutputGeometry(crop, rotation, 1f)
|
||||
val matrix = geometry.textureMatrix(113, 91, 0, 0, geometry.fullRegion)
|
||||
val u = 0.5 / geometry.width
|
||||
val v = 0.5 / geometry.height
|
||||
assertEquals(expected[index].first,
|
||||
(matrix[0] * u + matrix[4] * v + matrix[12]) * 113, 0.00001)
|
||||
assertEquals(expected[index].second,
|
||||
(matrix[1] * u + matrix[5] * v + matrix[13]) * 91, 0.00001)
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
fun oldDngDoesNotScaleAgainAndNewScaleSurvivesMetadataRoundTrip() {
|
||||
assertEquals(1f, RawOutputScaling.read(emptyMap()), 0f)
|
||||
val properties = RawOutputScaling.write(mapOf("existing" to "value"), 1.5f)
|
||||
assertEquals("value", properties["existing"])
|
||||
assertEquals(1.5f, RawOutputScaling.read(properties.toMap()), 0f)
|
||||
assertEquals(1f, RawOutputScaling.read(mapOf("rawDisplayOutputScale" to "NaN")), 0f)
|
||||
}
|
||||
}
|
||||
@@ -5,6 +5,29 @@ import org.junit.Assert.assertTrue
|
||||
import org.junit.Test
|
||||
|
||||
class RawTilePlannerTest {
|
||||
@Test
|
||||
fun guidedUpsampleGridSurvivesUnevenDimensionsAndRotatedCrops() {
|
||||
for (period in listOf(4, 8)) for (cfa in listOf(2, 6, 8))
|
||||
for (rotation in listOf(0, 90, 180, 270)) {
|
||||
val bounds = RawTileRect(7, 11, 4_986, 3_478)
|
||||
val tiles = RawTilePlanner.plan(
|
||||
sourceWidth = 5_003, sourceHeight = 3_501, outputSourceBounds = bounds,
|
||||
rotation = rotation, coreEdgePx = 2_048, supportPx = 112,
|
||||
cfaPeriod = cfa, processingPeriod = period,
|
||||
)
|
||||
assertEquals(bounds.width.toLong() * bounds.height,
|
||||
tiles.sumOf { it.outputCore.width.toLong() * it.outputCore.height })
|
||||
assertEquals(1, tiles.map { it.sourceWorking.width to it.sourceWorking.height }.toSet().size)
|
||||
for (tile in tiles) {
|
||||
assertTrue(tile.sourceWorking.contains(tile.sourceCore))
|
||||
assertEquals(0, tile.sourceWorking.left % cfa)
|
||||
assertEquals(0, tile.sourceWorking.top % cfa)
|
||||
assertEquals(0, tile.sourceWorking.left % period)
|
||||
assertEquals(0, tile.sourceWorking.top % period)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
fun hundredMegapixelOutputUsesDisjointBoundedCores() {
|
||||
val bounds = RawTileRect(0, 0, 11_648, 8_736)
|
||||
|
||||
Reference in new issue
Block a user