feat: port MGC guided upsample to GLES

This commit is contained in:
zhoubinjia committed 2026-11-03 15:27:53 +08:00
1 parent 18b5e84094
commit 78297ea307
17 files changed
+1033 -2958

No files matched your search

+4 -46
View File
@@ -11,41 +11,6 @@ set(
)
option(PHOTON_ENABLE_DNG_JXL "Enable Adobe DNG SDK JPEG XL support" OFF)
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_RAISR_CAPSULE
"${CMAKE_CURRENT_SOURCE_DIR}/mgc_denoise_static/mgc_raisr_capsule.bin"
@@ -351,14 +316,11 @@ add_library(my-native-lib SHARED
lut_processor.cpp
dcp_parser.cpp
mgc_denoise_static/mgc_halide_runtime.cpp
mgc_denoise_static/mgc_denoise_static.cpp
mgc_denoise_static/mgc_spatial_rgb_merge_jni.cpp
mgc_denoise_static/mgc_guided_upsample_jni.cpp
mgc_denoise_static/mgc_sharpen_jni.cpp
raw_float_texture_transfer_jni.cpp
mgc_denoise_static/mgc_raisr_jni.cpp
mgc_denoise_static/mgc_raisr_driver.cpp
mgc_denoise_static/mgc_polysharp_driver.cpp
"${MGC_GUIDED_ASM}"
"${MGC_RAISR_ASM}"
"${MGC_RAISR_TABLES_ASM}"
"${MGC_POLYSHARP_ASM}"
@@ -394,12 +356,9 @@ set_source_files_properties(
)
# RAW signal statistics define MGC's physical tuning coordinate, while PGTM validation must
# reliably reject non-finite values. The sharpen adapter must preserve separate matrix
# multiply/adds and nearest-even U12 rounding. Keep these independent of fast-math.
# reliably reject non-finite values. 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"
)
@@ -425,11 +384,10 @@ set_source_files_properties(
COMPILE_OPTIONS "-fno-fast-math;-ffp-contract=off"
)
# The MGC Halide runtime and AOT wrappers rely on scalar IEEE behavior.
# Keep them independent of the target-wide fast-math flags.
# The MGC Halide runtime relies on scalar IEEE behavior.
# Keep it independent of the target-wide fast-math flags.
set_source_files_properties(
mgc_denoise_static/mgc_halide_runtime.cpp
mgc_denoise_static/mgc_denoise_static.cpp
PROPERTIES
COMPILE_OPTIONS "-fno-fast-math;-ffp-contract=off"
)
@@ -1,106 +0,0 @@
// Host wrappers of the MGC GuidedUpsample AOT kernels.
#include "mgc_denoise_static.h"
#include <cmath>
#include <cstddef>
#include <cstdint>
namespace photon::mgc_denoise {
namespace {
struct HalideType {
uint8_t code;
uint8_t bits;
uint16_t lanes;
};
struct HalideDimension {
int32_t min;
int32_t extent;
int32_t stride;
uint32_t flags;
};
struct HalideBuffer {
uint64_t device;
const void* device_interface;
uint8_t* host;
uint64_t flags;
HalideType type;
int32_t dimensions;
const HalideDimension* dim;
void* padding;
};
static_assert(sizeof(HalideBuffer) == 56);
static_assert(sizeof(HalideDimension) == 16);
static_assert(offsetof(HalideBuffer, type) == 32);
static_assert(offsetof(HalideBuffer, dimensions) == 36);
static_assert(offsetof(HalideBuffer, dim) == 40);
HalideBuffer MakeBuffer(
void* host,
HalideType type,
int dimensions,
const HalideDimension* dimension_data) {
return HalideBuffer{
0,
nullptr,
static_cast<uint8_t*>(host),
0,
type,
dimensions,
dimension_data,
nullptr,
};
}
} // namespace
// 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
@@ -1,16 +0,0 @@
#pragma once
#include <cstdint>
namespace photon::mgc_denoise {
/** 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
@@ -1,102 +0,0 @@
#pragma once
#include <algorithm>
#include <arm_neon.h>
#include <cmath>
#include <cstddef>
#include <cstdint>
namespace photon::mgc_denoise {
// The GuidedUpsample guide has already received black-level/lens correction.
// Its only remaining raw boundary is WB + unsigned Q14 quantization, followed
// by RgbRawToYuv with black=0, gain=1, neutral gain map, white=16383.
// Under those fixed inputs the AOT's gain interpolation is identity and its
// final Q13 integer matrix is exactly the one below. Keep this specialization
// local to the guided boundary; general raw conversion still uses the AOT.
// Quantized RGB is in [0,16383], below the AOT's 29490 highlight knee;
// neither its highlight compression nor signed-16 saturation changes RGB.
// Matrix sums fit int32, and all rounded outputs fit int16. The V row retains
// the AOT's R + round((-7441 G - 751 B)/8192) operation order.
inline bool GuidedFloatRgbaToLinearYuv(const float *rgba, int width, int height,
int padded_width, int padded_height,
const float wb[3], int16_t *yuv) {
if (!rgba || !wb || !yuv || width <= 0 || height <= 0 ||
padded_width < width || padded_height < height || padded_width % 4 != 0)
return false;
for (int c = 0; c < 3; ++c)
if (!std::isfinite(wb[c]) || wb[c] <= 0.f) return false;
const size_t count = size_t(padded_width) * padded_height;
int invalid = 0;
#pragma omp parallel for schedule(static) num_threads(4) reduction(| : invalid)
for (int y = 0; y < padded_height; ++y) {
const float *row = rgba + size_t(std::min(y, height - 1)) * width * 4;
for (int x = 0; x < padded_width; x += 4) {
float32x4x4_t input;
if (x + 4 <= width) {
input = vld4q_f32(row + size_t(x) * 4);
} else {
// Replicate the original unpadded border, including incomplete groups.
float edge[16];
for (int lane = 0; lane < 4; ++lane)
for (int c = 0; c < 4; ++c)
edge[lane * 4 + c] = row[size_t(std::min(x + lane, width - 1)) * 4 + c];
input = vld4q_f32(edge);
}
uint32x4_t nonfinite = vdupq_n_u32(0);
int16x4_t rgb[3];
for (int c = 0; c < 3; ++c) {
const auto exponent = vandq_u32(vreinterpretq_u32_f32(input.val[c]),
vdupq_n_u32(0x7f800000));
nonfinite = vorrq_u32(nonfinite,
vceqq_u32(exponent, vdupq_n_u32(0x7f800000)));
}
if (vmaxvq_u32(nonfinite)) {
invalid = 1;
continue;
}
for (int c = 0; c < 3; ++c) {
const auto balanced = vmulq_n_f32(input.val[c], wb[c]);
const auto bounded = vminq_f32(vmaxq_f32(balanced, vdupq_n_f32(0.f)),
vdupq_n_f32(1.f));
// lround rounds ties away from zero, independently of FPCR mode.
rgb[c] = vreinterpret_s16_u16(vmovn_u32(
vcvtaq_u32_f32(vmulq_n_f32(bounded, 16383.f))));
}
const auto r = rgb[0], g = rgb[1], b = rgb[2];
const auto yy = vmlal_n_s16(vmlal_n_s16(vmull_n_s16(r, 1742), g, 5859), b, 591);
const auto uu = vmlal_n_s16(vmlal_n_s16(vmull_n_s16(r, -1331), g, -4477), b, 5808);
const auto vv = vmlal_n_s16(vmull_n_s16(g, -7441), b, -751);
const size_t dest = size_t(y) * padded_width + x;
// AOT uses signed rounding shifts (ties toward +infinity), not lrintf.
vst1_s16(yuv + dest, vqrshrn_n_s32(yy, 13));
vst1_s16(yuv + count + dest, vqrshrn_n_s32(uu, 13));
vst1_s16(yuv + count * 2 + dest, vadd_s16(r, vqrshrn_n_s32(vv, 13)));
}
}
return invalid == 0;
}
// White-box YuvToRgbS16 (MGC 9.6.080 V24, photon_mgc_yuv_to_rgb_s16): the AOT's
// entry fixes four Q-format coefficients and its vector body computes, per pixel,
// R = Y + rshr(V * 25802, 15)
// G = Y + rshr(V * -15340 + U * -8658, 16)
// B = Y + rshr(U * 21442, 14)
// with rshr the signed rounding shift (ties toward +infinity) on the int32 product
// and a saturating narrow to int16. It inverts the matrix above. Verified bit-exact
// against the AOT body under emulation on edge grids and full-range random planes.
inline void GuidedLinearYuvToRgb(const int16_t *yuv, size_t count, int16_t *rgb) {
const int16_t *y_plane = yuv, *u_plane = yuv + count, *v_plane = yuv + count * 2;
const auto saturate = [](int32_t v) {
return int16_t(std::clamp<int32_t>(v, INT16_MIN, INT16_MAX));
};
#pragma omp parallel for schedule(static) num_threads(4)
for (size_t i = 0; i < count; ++i) {
const int32_t y = y_plane[i], u = u_plane[i], v = v_plane[i];
rgb[i] = saturate(y + ((v * 25802 + (1 << 14)) >> 15));
rgb[count + i] = saturate(y + ((v * -15340 + u * -8658 + (1 << 15)) >> 16));
rgb[count * 2 + i] = saturate(y + ((u * 21442 + (1 << 13)) >> 14));
}
}
} // namespace photon::mgc_denoise
@@ -1,215 +0,0 @@
#include "mgc_denoise_static.h"
#include "mgc_guided_prepare_adapter.h"
#include "mgc_sharpen_adapter.h"
#include <algorithm>
#include <android/log.h>
#include <chrono>
#include <cmath>
#include <jni.h>
#include <limits>
#include <memory>
#include <new>
#include <sys/mman.h>
#include <unistd.h>
#include <vector>
namespace {
using Clock = std::chrono::steady_clock;
double Milliseconds(Clock::time_point begin, Clock::time_point end) {
return std::chrono::duration<double, std::milli>(end - begin).count();
}
// Anonymous mapping for the full-resolution planar Q14 YUV. Pages are zero-filled lazily on
// first write, so there is no separate clearing pass; once BoxDownsample has consumed U/V their
// pages are unmapped and the Y plane remains in place as the guide, without a copy.
class PlanarYuvMapping {
public:
explicit PlanarYuvMapping(size_t plane_samples)
: bytes_(plane_samples * 3 * sizeof(int16_t)) {
void *base = mmap(nullptr, bytes_, PROT_READ | PROT_WRITE,
MAP_PRIVATE | MAP_ANONYMOUS, -1, 0);
if (base == MAP_FAILED)
throw std::bad_alloc();
base_ = static_cast<int16_t *>(base);
}
~PlanarYuvMapping() {
if (base_)
munmap(base_, bytes_);
}
PlanarYuvMapping(const PlanarYuvMapping &) = delete;
PlanarYuvMapping &operator=(const PlanarYuvMapping &) = delete;
int16_t *data() const { return base_; }
void RetainFirstPlane(size_t plane_samples) {
const size_t page = size_t(sysconf(_SC_PAGESIZE));
const size_t keep =
(plane_samples * sizeof(int16_t) + page - 1) / page * page;
if (keep < bytes_ &&
munmap(reinterpret_cast<uint8_t *>(base_) + keep, bytes_ - keep) == 0)
bytes_ = keep;
}
private:
int16_t *base_ = nullptr;
size_t bytes_;
};
struct GuidedInputs {
int width, height, padded_width, padded_height, scale;
std::unique_ptr<PlanarYuvMapping> guide;
std::vector<int16_t> 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 {
const auto start = Clock::now();
auto state = std::make_unique<GuidedInputs>();
state->width = width;
state->height = height;
state->padded_width = pw;
state->padded_height = ph;
state->scale = scale;
Clock::time_point allocated, converted, boxed, guides;
std::vector<int16_t> low(ln * 3);
state->guide = std::make_unique<PlanarYuvMapping>(n);
int16_t *yuv = state->guide->data();
allocated = Clock::now();
if (!GuidedFloatRgbaToLinearYuv(rgba, width, height, pw, ph, wb, yuv))
return 0;
converted = Clock::now();
if (RunGuidedBoxDownsample(yuv, pw, ph, log2_scale, low.data()) != 0)
return 0;
boxed = Clock::now();
// Release the two unused chroma planes before allocating low RGB.
state->guide->RetainFirstPlane(n);
state->low_guide.assign(low.begin(), low.begin() + ln);
guides = Clock::now();
// The low color branch starts before CCM/DCP/tone; never downsample an
// encoded JPEG.
std::vector<int16_t> low_rgb(ln * 3);
GuidedLinearYuvToRgb(low.data(), ln, low_rgb.data());
const auto low_color = Clock::now();
#pragma omp parallel for schedule(static) num_threads(4)
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;
}
const auto finish = Clock::now();
__android_log_print(ANDROID_LOG_INFO, "PLog_MgcGuidedUpsample",
"prepare %dx%d scale=%d allocMs=%.1f q14YuvMs=%.1f boxMs=%.1f guidesMs=%.1f "
"lowRgbMs=%.1f rgbaMs=%.1f totalNativeMs=%.1f",
width, height, scale, Milliseconds(start, allocated),
Milliseconds(allocated, converted), Milliseconds(converted, boxed),
Milliseconds(boxed, guides), Milliseconds(guides, low_color),
Milliseconds(low_color, finish), Milliseconds(start, finish));
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, jboolean u12_rgb_output) {
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();
const size_t output_samples =
size_t(state->width) * ((state->height + 1) & ~1) * 3;
if (!rgba ||
env->GetDirectBufferCapacity(buffer) < jlong(std::max(n, ln) * 16) ||
env->GetDirectBufferCapacity(buffer) <
jlong(output_samples * sizeof(uint16_t)))
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 {
const auto start = Clock::now();
// Every element below is written by its producer before it is read; skip value-init.
std::unique_ptr<int16_t[]> yuv(new int16_t[ln * 3]);
if (!SharpenFloatRgbaToYuv(rgba, ln, yuv.get()))
return -1;
const auto converted = Clock::now();
// The low-resolution input has been fully consumed, so the U12 RGB result can be written
// straight into the mapped transfer buffer and expanded on the GPU at upload.
std::unique_ptr<uint16_t[]> float_staging;
uint16_t *output = reinterpret_cast<uint16_t *>(rgba);
if (!u12_rgb_output) {
float_staging.reset(new uint16_t[output_samples]);
output = float_staging.get();
}
const int result = RunGuidedUpsampleTo16Bit(
state->guide->data(), state->padded_width, state->padded_height,
state->low_guide.data(), yuv.get(), state->scale, state->width,
state->height, curves, attenuation, output);
if (result)
return result;
const auto reconstructed = Clock::now();
if (!u12_rgb_output)
SharpenRgbToFloatRgba(output, n, rgba);
const auto finish = Clock::now();
__android_log_print(ANDROID_LOG_INFO, "PLog_MgcGuidedUpsample",
"render %dx%d scale=%d output=%s yuvMs=%.1f guidedMs=%.1f rgbaMs=%.1f "
"totalNativeMs=%.1f",
state->width, state->height, state->scale, u12_rgb_output ? "u12" : "float",
Milliseconds(start, converted), Milliseconds(converted, reconstructed),
Milliseconds(reconstructed, finish), Milliseconds(start, finish));
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
@@ -1,13 +0,0 @@
#pragma once
#include <cstddef>
#include <cstdint>
namespace photon::mgc_denoise {
// Same U12 matrix and round-to-nearest-even boundary as the former scalar
// 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
@@ -1,189 +0,0 @@
#include "mgc_sharpen_adapter.h"
#include <GLES3/gl3.h>
#include <algorithm>
#include <arm_neon.h>
#include <cmath>
#include <jni.h>
namespace photon::mgc_denoise {
namespace {
constexpr float kMatrix[9] = {
0.2125999927520752f, 0.7152000069618225f, 0.07219959795475006f,
-0.16245023906230927f, -0.5464943051338196f, 0.7089447379112244f,
0.9999967217445374f, -0.9083024859428406f, -0.09169333428144455f,
};
constexpr float kU8ToU12 = 4095.0f / 255.0f;
int16x4_t Convert4(float32x4_t r, float32x4_t g, float32x4_t b, int channel) {
// Deliberately separate multiply/adds: FMA changes U12 rounding boundaries.
const float32x4_t value =
vaddq_f32(vaddq_f32(vmulq_n_f32(r, kMatrix[channel * 3]),
vmulq_n_f32(g, kMatrix[channel * 3 + 1])),
vmulq_n_f32(b, kMatrix[channel * 3 + 2]));
return vmovn_s32(vmaxq_s32(
vdupq_n_s32(-4095), vminq_s32(vdupq_n_s32(4095), vcvtnq_s32_f32(value))));
}
} // namespace
void SharpenRgbaToYuv(const uint8_t *rgba, size_t count, int16_t *yuv) {
const size_t groups = count / 8;
#pragma omp parallel for schedule(static) num_threads(4)
for (size_t group = 0; group < groups; ++group) {
const size_t i = group * 8;
const uint8x8x4_t packed = vld4_u8(rgba + i * 4);
const uint16x8_t r16 = vmovl_u8(packed.val[0]);
const uint16x8_t g16 = vmovl_u8(packed.val[1]);
const uint16x8_t b16 = vmovl_u8(packed.val[2]);
const auto low = [](uint16x8_t v) {
return vmulq_n_f32(vcvtq_f32_u32(vmovl_u16(vget_low_u16(v))), kU8ToU12);
};
const auto high = [](uint16x8_t v) {
return vmulq_n_f32(vcvtq_f32_u32(vmovl_u16(vget_high_u16(v))), kU8ToU12);
};
const auto r0 = low(r16), g0 = low(g16), b0 = low(b16);
const auto r1 = high(r16), g1 = high(g16), b1 = high(b16);
for (int c = 0; c < 3; ++c) {
vst1q_s16(yuv + c * count + i,
vcombine_s16(Convert4(r0, g0, b0, c), Convert4(r1, g1, b1, c)));
}
}
for (size_t i = groups * 8; i < count; ++i) {
const float r = rgba[i * 4] * kU8ToU12;
const float g = rgba[i * 4 + 1] * kU8ToU12;
const float b = rgba[i * 4 + 2] * kU8ToU12;
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));
}
}
}
void SharpenRgbToRgba(const uint16_t *rgb, size_t count, uint8_t *rgba) {
const size_t groups = count / 8;
#pragma omp parallel for schedule(static) num_threads(4)
for (size_t group = 0; group < groups; ++group) {
const size_t i = group * 8;
const uint16x8x3_t input = vld3q_u16(rgb + i * 3);
uint8x8x4_t output;
for (int c = 0; c < 3; ++c) {
const uint16x8_t v = vminq_u16(input.val[c], vdupq_n_u16(4095));
const auto convert = [](uint16x4_t samples) {
const uint32x4_t numerator =
vaddq_u32(vmull_n_u16(samples, 255), vdupq_n_u32(2047));
// Exact floor(n / 4095) on this bounded numerator domain, not a float
// reciprocal.
return vmovn_u32(
vshrq_n_u32(vaddq_u32(vaddq_u32(numerator, vdupq_n_u32(1)),
vshrq_n_u32(numerator, 12)),
12));
};
output.val[c] = vmovn_u16(
vcombine_u16(convert(vget_low_u16(v)), convert(vget_high_u16(v))));
}
output.val[3] = vdup_n_u8(255);
vst4_u8(rgba + i * 4, output);
}
for (size_t i = groups * 8; i < count; ++i) {
for (size_t c = 0; c < 3; ++c) {
const uint32_t v = std::min<uint32_t>(rgb[i * 3 + c], 4095);
rgba[i * 4 + c] = static_cast<uint8_t>((v * 255 + 2047) / 4095);
}
rgba[i * 4 + 3] = 255;
}
}
bool SharpenFloatRgbaToYuv(const float *rgba, size_t count, int16_t *yuv) {
const size_t groups = count / 4;
int invalid = 0;
#pragma omp parallel for schedule(static) num_threads(4) reduction(| : invalid)
for (size_t group = 0; group < groups; ++group) {
const size_t i = group * 4;
const float32x4x4_t input = vld4q_f32(rgba + i * 4);
uint32x4_t nonfinite = vdupq_n_u32(0);
for (int c = 0; c < 3; ++c) {
const auto exponent = vandq_u32(vreinterpretq_u32_f32(input.val[c]),
vdupq_n_u32(0x7f800000));
nonfinite = vorrq_u32(nonfinite,
vceqq_u32(exponent, vdupq_n_u32(0x7f800000)));
}
if (vmaxvq_u32(nonfinite)) {
invalid = 1;
continue;
}
const auto scaled = [](float32x4_t value) {
return vmulq_n_f32(vminq_f32(vmaxq_f32(value, vdupq_n_f32(0.f)),
vdupq_n_f32(1.f)), 4095.f);
};
const auto r = scaled(input.val[0]), g = scaled(input.val[1]),
b = scaled(input.val[2]);
for (int c = 0; c < 3; ++c) {
const auto value = vaddq_f32(
vaddq_f32(vmulq_n_f32(r, kMatrix[c * 3]),
vmulq_n_f32(g, kMatrix[c * 3 + 1])),
vmulq_n_f32(b, kMatrix[c * 3 + 2]));
// Match lrintf's current rounding mode, retaining separate matrix adds.
const auto rounded = vcvtq_s32_f32(vrndiq_f32(value));
vst1_s16(yuv + c * count + i,
vmovn_s32(vmaxq_s32(vdupq_n_s32(-4095),
vminq_s32(vdupq_n_s32(4095), rounded))));
}
}
if (invalid) return false;
for (size_t i = groups * 4; i < count; ++i) {
for (int c = 0; c < 3; ++c) {
if (!std::isfinite(rgba[4 * i + c])) return false;
}
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) {
const size_t groups = count / 4;
#pragma omp parallel for schedule(static) num_threads(4)
for (size_t group = 0; group < groups; ++group) {
const size_t i = group * 4;
const uint16x4x3_t input = vld3_u16(rgb + i * 3);
float32x4x4_t output;
for (int c = 0; c < 3; ++c) {
const auto bounded = vmin_u16(input.val[c], vdup_n_u16(4095));
// Division preserves the scalar boundary's rounding; a reciprocal does not.
output.val[c] = vdivq_f32(vcvtq_f32_u32(vmovl_u16(bounded)),
vdupq_n_f32(4095.f));
}
output.val[3] = vdupq_n_f32(1.f);
vst4q_f32(rgba + i * 4, output);
}
for (size_t i = groups * 4; 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 jboolean JNICALL
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;
glActiveTexture(GL_TEXTURE0);
glBindTexture(GL_TEXTURE_2D, static_cast<GLuint>(texture));
glBindBuffer(GL_PIXEL_UNPACK_BUFFER, static_cast<GLuint>(pbo));
glPixelStorei(GL_UNPACK_ALIGNMENT, 1);
glPixelStorei(GL_UNPACK_ROW_LENGTH, 0);
glTexSubImage2D(GL_TEXTURE_2D, 0, 0, 0, width, height, GL_RGBA,
GL_FLOAT, nullptr);
const GLenum error = glGetError();
glBindBuffer(GL_PIXEL_UNPACK_BUFFER, 0);
return error == GL_NO_ERROR ? JNI_TRUE : JNI_FALSE;
}
@@ -0,0 +1,20 @@
// Pixel-unpack fallback of RawFloatTextureTransfer.upload.
#include <GLES3/gl3.h>
#include <jni.h>
extern "C" JNIEXPORT jboolean JNICALL
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;
glActiveTexture(GL_TEXTURE0);
glBindTexture(GL_TEXTURE_2D, static_cast<GLuint>(texture));
glBindBuffer(GL_PIXEL_UNPACK_BUFFER, static_cast<GLuint>(pbo));
glPixelStorei(GL_UNPACK_ALIGNMENT, 1);
glPixelStorei(GL_UNPACK_ROW_LENGTH, 0);
glTexSubImage2D(GL_TEXTURE_2D, 0, 0, 0, width, height, GL_RGBA,
GL_FLOAT, nullptr);
const GLenum error = glGetError();
glBindBuffer(GL_PIXEL_UNPACK_BUFFER, 0);
return error == GL_NO_ERROR ? JNI_TRUE : JNI_FALSE;
}
@@ -0,0 +1,683 @@
package com.hinnka.mycamera.raw
/**
* Bit-exact GLES translation of the MGC 9.7.047 V25 guided upsampling chain
* (`BoxDownsampleS16` 0x4D3686C and `GuidedUpsampleS16To16Bit` 0x4BA6500 in libgcastartup.so)
* together with the former CPU adapters around it. The independent reference, the algorithm notes
* and the oracle that checks these shaders against the original AOT live in
* tools/mgc_guided_upsample.
*
* Prepare (full-resolution float RGBA source):
* 1. `guide`: padded Q14 linear Y in the sqrt domain (R16I, padded size).
* 2. `lowGuide`: box-downsampled Q14 Y in the sqrt domain (R16I, padded size / scale).
* 3. `lowColor`: box-downsampled linear RGB / 16383 / white balance (RGBA16F, low size).
*
* Render (low-resolution encoded RGBA16F):
* 1. `lowYuv`: U12 Y, U, V (RGBA16I, low size).
* 2. `cellFit`: two-level weighted affine fit per grid cell (2 x RGBA32UI, cell grid).
* 3. `horizontal`: cell models interpolated to output columns (2 x RGBA32UI).
* 4. `guidedY`: vertical interpolation and the two-level blend (R16I, output grown by
* [GUIDED_PADDING] per side; the guided luma outside the image is its natural extension).
* 5. `level1`, `level2`, `output`: the V24 SharpenTo16Bit passes on the guided luma, plus the
* integer chroma upsampling and the Q12 YUV -> RGB of the original.
*
* GLSL ES 3.00 guarantees correct rounding only for finite +, - and * in highp. Everything that can
* become infinite or NaN (from the det on) travels as binary32 bit patterns and goes through
* the `*Bits` helpers, which resolve special operands explicitly and hand only finite operands to the
* hardware. Divisions are integer long divisions with round-to-nearest-even; the sqrt is a LUT.
*/
internal object GlesMgcGuidedUpsampleShaders {
const val GUIDED_PADDING = 7
const val LEVEL1_PADDING = 6
const val LEVEL2_PADDING = 4
private val header = """
#version 300 es
precision highp float;
precision highp int;
precision highp sampler2D;
precision highp isampler2D;
precision highp usampler2D;
""".trimIndent()
private val integerOps = """
const int GUIDED_PADDING = $GUIDED_PADDING;
const int LEVEL1_PADDING = $LEVEL1_PADDING;
const int LEVEL2_PADDING = $LEVEL2_PADDING;
int s16(int v) { return (v << 16) >> 16; }
// SHADD / SRHADD .8h; inputs are int16 so the halved sums never wrap.
int hadd(int a, int b) { return (a + b) >> 1; }
int rhadd(int a, int b) { return (a + b + 1) >> 1; }
""".trimIndent()
// GLSL ES has no `precise`. XOR with a zero uniform forces each product to be rounded to binary32
// before it is added, as the original's separate FMUL/FADD do.
private val floatOps = """
uniform uint uFloatFence;
float fenced(float value) { return uintBitsToFloat(floatBitsToUint(value) ^ uFloatFence); }
float unitToU12(float value) { return fenced(clamp(value, 0.0, 1.0) * 4095.0); }
// One row of the FinishRaw U12 matrix, rounded half to even and clamped to +-4095.
int u12Row(float r, float g, float b, float m0, float m1, float m2) {
float partial = fenced(fenced(r * m0) + fenced(g * m1));
return clamp(int(roundEven(partial + fenced(b * m2))), -4095, 4095);
}
""".trimIndent()
// binary32 arithmetic on bit patterns with AArch64 semantics (default NaN, no flush to zero).
// Results are only ever consumed as "NaN or not", so one canonical NaN suffices. Subnormal
// operands and results do not occur on this pipeline; the branches that would need them return
// trapBits(), whose subnormal product the oracle's checked float rejects.
private val bitOps = """
const uint SIGN_BIT = 0x80000000u;
const uint MAGNITUDE = 0x7fffffffu;
const uint INFINITY_BITS = 0x7f800000u;
const uint NAN_BITS = 0x7fc00000u;
const uint MANTISSA = 0x007fffffu;
bool isNanBits(uint a) { return (a & MAGNITUDE) > INFINITY_BITS; }
bool isInfBits(uint a) { return (a & MAGNITUDE) == INFINITY_BITS; }
bool isZeroBits(uint a) { return (a & MAGNITUDE) == 0u; }
int exponentBits(uint a) { return int((a >> 23) & 0xffu); }
uint trapBits() { return floatBitsToUint(fenced(uintBitsToFloat(0x00800000u) * 0.5)); }
uint mulBits(uint a, uint b) {
uint signBit = (a ^ b) & SIGN_BIT;
if (isNanBits(a) || isNanBits(b)) return NAN_BITS;
bool zero = isZeroBits(a) || isZeroBits(b);
if (isInfBits(a) || isInfBits(b)) return zero ? NAN_BITS : (signBit | INFINITY_BITS);
if (zero) return signBit;
if (exponentBits(a) == 0 || exponentBits(b) == 0) return trapBits();
int e = exponentBits(a) + exponentBits(b) - 254;
if (e >= 128) return signBit | INFINITY_BITS;
if (e >= -126 && e <= 125) {
return floatBitsToUint(fenced(uintBitsToFloat(a) * uintBitsToFloat(b)));
}
// |a * b| may reach 2^128 or fall below 2^-126: multiply the significands in [1, 2)
// and rebuild the exponent.
float ma = uintBitsToFloat((a & MANTISSA) | 0x3f800000u);
float mb = uintBitsToFloat((b & MANTISSA) | 0x3f800000u);
uint p = floatBitsToUint(fenced(ma * mb));
int biased = exponentBits(p) + e;
if (biased >= 255) return signBit | INFINITY_BITS;
if (biased <= 0) return trapBits();
return signBit | (uint(biased) << 23) | (p & MANTISSA);
}
uint addBits(uint a, uint b) {
if (isNanBits(a) || isNanBits(b)) return NAN_BITS;
if (isInfBits(a)) return isInfBits(b) && ((a ^ b) & SIGN_BIT) != 0u ? NAN_BITS : a;
if (isInfBits(b)) return b;
int ea = exponentBits(a);
int eb = exponentBits(b);
if (max(ea, eb) <= 253) {
return floatBitsToUint(fenced(uintBitsToFloat(a) + uintBitsToFloat(b)));
}
// One operand is at least 2^127. A far smaller one is below half an ulp.
if (isZeroBits(b) || eb < 224) return a;
if (isZeroBits(a) || ea < 224) return b;
float halved = fenced(uintBitsToFloat(a - 0x00800000u) + uintBitsToFloat(b - 0x00800000u));
uint s = floatBitsToUint(halved);
if (isZeroBits(s)) return s;
if (exponentBits(s) >= 254) return (s & SIGN_BIT) | INFINITY_BITS;
return s + 0x00800000u;
}
uint subBits(uint a, uint b) { return addBits(a, b ^ SIGN_BIT); }
// Correctly rounded (RNE) division by long division of the 24-bit significands.
uint divBits(uint a, uint b) {
uint signBit = (a ^ b) & SIGN_BIT;
if (isNanBits(a) || isNanBits(b)) return NAN_BITS;
if (isInfBits(a)) return isInfBits(b) ? NAN_BITS : (signBit | INFINITY_BITS);
if (isInfBits(b)) return signBit;
if (isZeroBits(b)) return isZeroBits(a) ? NAN_BITS : (signBit | INFINITY_BITS);
if (isZeroBits(a)) return signBit;
if (exponentBits(a) == 0 || exponentBits(b) == 0) return trapBits();
uint ma = (a & MANTISSA) | 0x00800000u;
uint mb = (b & MANTISSA) | 0x00800000u;
int e = exponentBits(a) - exponentBits(b) + 127;
if (ma < mb) {
ma <<= 1;
e -= 1;
}
uint q = 0u;
uint r = ma;
for (int i = 0; i < 25; ++i) {
q <<= 1;
if (r >= mb) {
r -= mb;
q |= 1u;
}
r <<= 1;
}
uint roundBit = q & 1u;
q >>= 1;
if (roundBit == 1u && (r != 0u || (q & 1u) == 1u)) q += 1u;
if (q == 0x01000000u) {
q >>= 1;
e += 1;
}
if (e >= 255) return signBit | INFINITY_BITS;
if (e <= 0) return trapBits();
return signBit | (uint(e) << 23) | (q & MANTISSA);
}
// SCVTF: int32 -> binary32, round to nearest even.
float intToFloat(int v) {
if (v >= -16777216 && v <= 16777216) return float(v);
uint signBit = v < 0 ? SIGN_BIT : 0u;
uint m = v < 0 ? uint(-(v + 1)) + 1u : uint(v);
int msb = findMSB(m);
int shift = msb - 23;
uint q = m >> uint(shift);
uint rest = m & ((1u << uint(shift)) - 1u);
uint halfway = 1u << uint(shift - 1);
if (rest > halfway || (rest == halfway && (q & 1u) == 1u)) q += 1u;
if (q == 0x01000000u) {
q >>= 1;
msb += 1;
}
return uintBitsToFloat(signBit | (uint(msb + 127) << 23) | (q & MANTISSA));
}
// FRINTN, then FMIN/FMAX against the int16 range and FCVTZS (NaN -> 0).
int roundSaturateS16(uint v) {
if (isNanBits(v)) return 0;
if (isInfBits(v)) return (v & SIGN_BIT) != 0u ? -32768 : 32767;
float f = uintBitsToFloat(v);
if (f >= 32768.0) return 32767;
if (f <= -32769.0) return -32768;
return clamp(int(roundEven(f)), -32768, 32767);
}
""".trimIndent()
// Q17 cell coordinate of a full-resolution pixel, u = (x + 0.5) / (2 * scale) - 0.5, and the
// matching Q16 low-resolution pixel coordinate (x + 0.5) / scale - 0.5. uCellStep = 32768 / scale.
private val gridOps = """
uniform int uCellStep;
// (left cell, Q16 fraction toward the next one)
ivec2 cellTap(int x) {
int p = (2 * x + 1) * uCellStep - 65536;
return ivec2(p >> 17, (p >> 1) & 0xffff);
}
ivec2 lowTap(int x) {
int p = (2 * x + 1) * uCellStep - 32768;
return ivec2(p >> 16, p & 0xffff);
}
// 1.52590219e-05 (0x37800080), the original's 1 / 65535.
float fractionScale() { return uintBitsToFloat(0x37800080u); }
""".trimIndent()
// -- prepare ----------------------------------------------------------------------------------
// GuidedFloatRgbaToLinearYuv: WB, clamp to [0, 1], ties-away Q14 quantisation, Q13 matrix with
// saturating rounding narrows. The source is replicated beyond its own size into the padding.
private val linearOps = """
uniform highp sampler2D uSource;
uniform ivec2 uSourceMax;
uniform float uWhiteBalance[3];
uniform highp isampler2D uSqrtLut;
int q14(float channel, float gain) {
uint balanced = mulBits(floatBitsToUint(channel), floatBitsToUint(gain));
float bounded;
if (isNanBits(balanced)) {
bounded = 0.0;
} else if (isInfBits(balanced)) {
bounded = (balanced & SIGN_BIT) != 0u ? 0.0 : 1.0;
} else {
bounded = clamp(uintBitsToFloat(balanced), 0.0, 1.0);
}
float scaled = fenced(bounded * 16383.0);
float whole = floor(scaled);
return int(whole) + (fenced(scaled - whole) >= 0.5 ? 1 : 0);
}
int narrow13(int v) { return clamp((v + 4096) >> 13, -32768, 32767); }
ivec3 linearYuv(ivec2 p) {
vec4 color = texelFetch(uSource, min(p, uSourceMax), 0);
int r = q14(color.r, uWhiteBalance[0]);
int g = q14(color.g, uWhiteBalance[1]);
int b = q14(color.b, uWhiteBalance[2]);
return ivec3(narrow13(1742 * r + 5859 * g + 591 * b),
narrow13(-1331 * r - 4477 * g + 5808 * b),
s16(r + narrow13(-7441 * g - 751 * b)));
}
// SqrtGuide: LUT of int16(sqrt(max(g, 0)) * 128) for g in [0, 32767], 256 x 128.
int sqrtGuide(int g) {
if (g <= 0) return 0;
return texelFetch(uSqrtLut, ivec2(g & 255, g >> 8), 0).r;
}
""".trimIndent()
private val boxOps = """
uniform int uLog2Scale;
// BoxDownsample: per column a rounded vertical mean, then a rounded horizontal mean (int32).
ivec3 boxYuv(ivec2 low) {
int scale = 1 << uLog2Scale;
int rounding = scale >> 1;
ivec3 sum = ivec3(0);
for (int i = 0; i < scale; ++i) {
ivec3 column = ivec3(0);
for (int j = 0; j < scale; ++j) column += linearYuv(low * scale + ivec2(i, j));
sum += (column + rounding) >> uLog2Scale;
}
return (sum + rounding) >> uLog2Scale;
}
""".trimIndent()
private val guide = """
layout(location = 0) out int oGuide;
void main() {
oGuide = sqrtGuide(linearYuv(ivec2(gl_FragCoord.xy)).x);
}
""".trimIndent()
private val lowGuide = """
layout(location = 0) out int oGuide;
void main() {
oGuide = sqrtGuide(boxYuv(ivec2(gl_FragCoord.xy)).x);
}
""".trimIndent()
// GuidedLinearYuvToRgb followed by rgb / 16383 / wb (two RNE divisions) and RNE to binary16,
// emitted as a float the RGBA16F attachment stores exactly.
private val lowColor = """
layout(location = 0) out vec4 oColor;
int saturate16(int v) { return clamp(v, -32768, 32767); }
float roundToHalf(uint v) {
uint signBit = v & SIGN_BIT;
float signValue = signBit != 0u ? -1.0 : 1.0;
if (isInfBits(v)) return uintBitsToFloat(v);
if (isZeroBits(v)) return uintBitsToFloat(signBit);
int e = exponentBits(v) - 127;
if (e >= 16) return uintBitsToFloat(signBit | INFINITY_BITS);
uint m = (v & MANTISSA) | 0x00800000u;
int shift = e >= -14 ? 13 : -1 - e;
if (shift >= 25) return uintBitsToFloat(signBit);
uint q = m >> uint(shift);
uint rest = m & ((1u << uint(shift)) - 1u);
uint halfway = 1u << uint(shift - 1);
if (rest > halfway || (rest == halfway && (q & 1u) == 1u)) q += 1u;
int unit = e >= -14 ? e - 10 : -24;
if (unit == 5 && q == 2048u) return uintBitsToFloat(signBit | INFINITY_BITS);
float power = uintBitsToFloat(uint(unit + 127) << 23);
return fenced(fenced(float(q) * power) * signValue);
}
float unitColor(int v, int channel) {
uint scaled = divBits(floatBitsToUint(float(v)), floatBitsToUint(16383.0));
return roundToHalf(divBits(scaled, floatBitsToUint(uWhiteBalance[channel])));
}
void main() {
ivec3 yuv = boxYuv(ivec2(gl_FragCoord.xy));
int y = yuv.x;
int u = yuv.y;
int v = yuv.z;
int r = saturate16(y + ((v * 25802 + 16384) >> 15));
int g = saturate16(y + ((v * -15340 + u * -8658 + 32768) >> 16));
int b = saturate16(y + ((u * 21442 + 8192) >> 14));
oColor = vec4(unitColor(r, 0), unitColor(g, 1), unitColor(b, 2), 1.0);
}
""".trimIndent()
// -- render -----------------------------------------------------------------------------------
private val lowYuv = """
uniform highp sampler2D uSource;
layout(location = 0) out ivec4 oYuv;
void main() {
vec4 color = texelFetch(uSource, ivec2(gl_FragCoord.xy), 0);
float r = unitToU12(color.r);
float g = unitToU12(color.g);
float b = unitToU12(color.b);
oYuv = ivec4(u12Row(r, g, b, 0.2125999927520752, 0.7152000069618225, 0.07219959795475006),
u12Row(r, g, b, -0.16245023906230927, -0.5464943051338196, 0.7089447379112244),
u12Row(r, g, b, 0.9999967217445374, -0.9083024859428406, -0.09169333428144455), 0);
}
""".trimIndent()
// Cell (kx, ky) fits out = a * g + b on the 4x4 low-resolution window starting at
// (2 kx - 1, 2 ky - 1) (clamped), for two levels softly split between min - 1 and max + 1 of the
// sqrt-domain guide, with tent spatial weights. Sums run serially in the original order.
private val cellFit = """
uniform highp isampler2D uLowGuide;
uniform highp isampler2D uLowYuv;
uniform ivec2 uLowMax;
uniform ivec2 uCellOrigin;
layout(location = 0) out uvec4 oCell0;
layout(location = 1) out uvec4 oCell1;
float tent(int i) { return i == 0 || i == 3 ? 0.625 : 0.875; }
uvec2 solve(float s0, float sg, float sgg, float sy, float sgy) {
float epsilon = uintBitsToFloat(0x38d1b717u);
float s0e = s0 + epsilon;
float sgge = sgg + epsilon;
float negativeSg = 0.0 - sg;
float det = fenced(s0e * sgge) - fenced(sg * sg);
uint reciprocal = divBits(floatBitsToUint(1.0), floatBitsToUint(det));
float bNumerator = fenced(sgge * sy) + fenced(negativeSg * sgy);
float aNumerator = fenced(negativeSg * sy) + fenced(s0e * sgy);
return uvec2(mulBits(reciprocal, floatBitsToUint(aNumerator)),
mulBits(reciprocal, floatBitsToUint(bNumerator)));
}
void main() {
ivec2 cell = ivec2(gl_FragCoord.xy) + uCellOrigin;
ivec2 origin = 2 * cell - ivec2(1);
int g[16];
int y[16];
int lowest = 32767;
int highest = -32768;
for (int r = 0; r < 4; ++r) {
for (int k = 0; k < 4; ++k) {
ivec2 p = clamp(origin + ivec2(k, r), ivec2(0), uLowMax);
g[r * 4 + k] = texelFetch(uLowGuide, p, 0).r;
y[r * 4 + k] = texelFetch(uLowYuv, p, 0).r;
lowest = min(lowest, g[r * 4 + k]);
highest = max(highest, g[r * 4 + k]);
}
}
float lo = float(lowest) + -1.0;
float hi = float(highest) + 1.0;
float reciprocal = uintBitsToFloat(divBits(floatBitsToUint(1.0), floatBitsToUint(hi - lo)));
uvec2 model[2];
for (int level = 0; level < 2; ++level) {
float w[16];
for (int r = 0; r < 4; ++r) {
for (int k = 0; k < 4; ++k) {
float t = fenced((hi - float(g[r * 4 + k])) * reciprocal);
float spatial = fenced(tent(r) * tent(k));
w[r * 4 + k] = fenced(spatial * (level == 0 ? t : 1.0 - t));
}
}
float s0 = 0.0;
float sg = 0.0;
float sgg = 0.0;
for (int i = 0; i < 16; ++i) {
s0 = s0 + w[i];
sg = sg + fenced(w[i] * float(g[i]));
sgg = sgg + fenced(w[i] * intToFloat(g[i] * g[i]));
}
float sy = 0.0;
float sgy = 0.0;
for (int i = 0; i < 16; ++i) {
sy = sy + fenced(w[i] * float(y[i]));
sgy = sgy + fenced(w[i] * intToFloat(g[i] * y[i]));
}
model[level] = solve(s0, sg, sgg, sy, sgy);
}
oCell0 = uvec4(floatBitsToUint(lo), floatBitsToUint(hi), model[0].x, model[0].y);
oCell1 = uvec4(model[1].x, model[1].y, 0u, 0u);
}
""".trimIndent()
// Row j holds cell row uCellOrigin.y + j interpolated to columns x = i - GUIDED_PADDING:
// c0 * (1 - f C) + (c1 * f) * C.
private val horizontal = """
uniform highp usampler2D uCell0;
uniform highp usampler2D uCell1;
uniform ivec2 uCellOrigin;
layout(location = 0) out uvec4 oRow0;
layout(location = 1) out uvec4 oRow1;
uint lerpBits(uint c0, uint c1, uint w0, uint f, uint scale) {
return addBits(mulBits(c0, w0), mulBits(mulBits(c1, f), scale));
}
void main() {
ivec2 p = ivec2(gl_FragCoord.xy);
ivec2 tap = cellTap(p.x - GUIDED_PADDING);
ivec2 left = ivec2(tap.x - uCellOrigin.x, p.y);
ivec2 right = left + ivec2(1, 0);
float f = float(tap.y);
float w0 = 1.0 - fenced(f * fractionScale());
uint w0Bits = floatBitsToUint(w0);
uint fBits = floatBitsToUint(f);
uint scale = floatBitsToUint(fractionScale());
uvec4 a0 = texelFetch(uCell0, left, 0);
uvec4 b0 = texelFetch(uCell0, right, 0);
uvec4 a1 = texelFetch(uCell1, left, 0);
uvec4 b1 = texelFetch(uCell1, right, 0);
oRow0 = uvec4(lerpBits(a0.r, b0.r, w0Bits, fBits, scale), lerpBits(a0.g, b0.g, w0Bits, fBits, scale),
lerpBits(a0.b, b0.b, w0Bits, fBits, scale), lerpBits(a0.a, b0.a, w0Bits, fBits, scale));
oRow1 = uvec4(lerpBits(a1.r, b1.r, w0Bits, fBits, scale), lerpBits(a1.g, b1.g, w0Bits, fBits, scale),
0u, 0u);
}
""".trimIndent()
// Vertical interpolation H0 * (1 - w1) + H1 * w1, then
// Y = sat16(rne((1 - t) (b0 + a0 G) + t (b1 + a1 G))), t = clamp((G - lo) / (hi - lo), 0, 1).
// Pixel (i, j) is image position (i, j) - GUIDED_PADDING.
private val guidedY = """
uniform highp usampler2D uRow0;
uniform highp usampler2D uRow1;
uniform highp isampler2D uGuide;
uniform ivec2 uGuideMax;
uniform int uCellOriginY;
layout(location = 0) out int oLuma;
uint vertical(uint top, uint bottom, uint w0, uint w1) {
return addBits(mulBits(top, w0), mulBits(bottom, w1));
}
void main() {
ivec2 p = ivec2(gl_FragCoord.xy);
ivec2 image = p - ivec2(GUIDED_PADDING);
ivec2 tap = cellTap(image.y);
ivec2 top = ivec2(p.x, tap.x - uCellOriginY);
ivec2 bottom = top + ivec2(0, 1);
float w1 = fenced(float(tap.y) * fractionScale());
uint w1Bits = floatBitsToUint(w1);
uint w0Bits = floatBitsToUint(1.0 - w1);
uvec4 t0 = texelFetch(uRow0, top, 0);
uvec4 d0 = texelFetch(uRow0, bottom, 0);
uvec4 t1 = texelFetch(uRow1, top, 0);
uvec4 d1 = texelFetch(uRow1, bottom, 0);
uint lo = vertical(t0.r, d0.r, w0Bits, w1Bits);
uint hi = vertical(t0.g, d0.g, w0Bits, w1Bits);
uint a0 = vertical(t0.b, d0.b, w0Bits, w1Bits);
uint b0 = vertical(t0.a, d0.a, w0Bits, w1Bits);
uint a1 = vertical(t1.r, d1.r, w0Bits, w1Bits);
uint b1 = vertical(t1.g, d1.g, w0Bits, w1Bits);
float guide = float(texelFetch(uGuide, clamp(image, ivec2(0), uGuideMax), 0).r);
uint guideBits = floatBitsToUint(guide);
float low = uintBitsToFloat(lo);
float t = uintBitsToFloat(divBits(floatBitsToUint(guide - low),
floatBitsToUint(uintBitsToFloat(hi) - low)));
t = max(min(t, 1.0), 0.0);
uint lowModel = addBits(b0, mulBits(a0, guideBits));
uint highModel = addBits(b1, mulBits(a1, guideBits));
uint blended = addBits(mulBits(floatBitsToUint(1.0 - t), lowModel),
mulBits(floatBitsToUint(t), highModel));
oLuma = roundSaturateS16(blended);
}
""".trimIndent()
private val level1 = """
uniform highp isampler2D uLuma;
layout(location = 0) out int oLevel;
int luma(ivec2 p) { return texelFetch(uLuma, p + ivec2(GUIDED_PADDING), 0).r; }
int column(ivec2 p) {
return rhadd(hadd(luma(p - ivec2(0, 1)), luma(p + ivec2(0, 1))), luma(p));
}
void main() {
ivec2 p = ivec2(gl_FragCoord.xy) - ivec2(LEVEL1_PADDING);
oLevel = hadd(rhadd(column(p - ivec2(1, 0)), column(p + ivec2(1, 0))), column(p));
}
""".trimIndent()
private val level2 = """
uniform highp isampler2D uLevel1;
layout(location = 0) out int oLevel;
int level1(ivec2 p) { return texelFetch(uLevel1, p + ivec2(LEVEL1_PADDING), 0).r; }
int column(ivec2 p) {
return rhadd(hadd(level1(p - ivec2(0, 2)), level1(p + ivec2(0, 2))), level1(p));
}
void main() {
ivec2 p = ivec2(gl_FragCoord.xy) - ivec2(LEVEL2_PADDING);
oLevel = hadd(rhadd(column(p - ivec2(2, 0)), column(p + ivec2(2, 0))), column(p));
}
""".trimIndent()
private val output = """
uniform highp isampler2D uLuma;
uniform highp isampler2D uLevel1;
uniform highp isampler2D uLevel2;
uniform highp isampler2D uLowYuv;
uniform ivec2 uLowMax;
// Per band: knots 1..3 (U12), then four segment slopes (Q8) and intercepts (U12).
uniform int uKnots[9];
uniform int uSlopes[12];
uniform int uIntercepts[12];
// (width >> 1, ((height + 1) & ~1) >> 1) and 1 / (cx^2 + cy^2).
uniform ivec2 uCenter;
uniform float uInverseMaxRadius2;
uniform float uCorner[3];
uniform float uLowerScale;
uniform float uUpperScale;
layout(location = 0) out vec4 oColor;
int luma(ivec2 p) { return texelFetch(uLuma, p + ivec2(GUIDED_PADDING), 0).r; }
int level1(ivec2 p) { return texelFetch(uLevel1, p + ivec2(LEVEL1_PADDING), 0).r; }
int level2(ivec2 p) { return texelFetch(uLevel2, p + ivec2(LEVEL2_PADDING), 0).r; }
int column(ivec2 p) {
return rhadd(hadd(level2(p - ivec2(0, 4)), level2(p + ivec2(0, 4))), level2(p));
}
// Segment by |d| (int16 abs: -32768 stays negative), slope on the signed d, mirrored intercept.
int curve(int band, int d) {
int magnitude = s16(abs(d));
int knot = band * 3;
int segment = magnitude >= uKnots[knot + 2] ? 3
: magnitude >= uKnots[knot + 1] ? 2
: magnitude >= uKnots[knot] ? 1 : 0;
int index = band * 4 + segment;
int scaled = clamp((uSlopes[index] * d) >> 8, -32768, 32767);
int intercept = d < 0 ? s16(-uIntercepts[index]) : uIntercepts[index];
return s16(scaled + intercept);
}
// FCVTZS to int32 (truncate, saturate) narrowed to int16.
int truncateS16(float value) {
if (value >= 2147483648.0) return -1;
if (value <= -2147483648.0) return 0;
return s16(int(value));
}
int bandTerm(int band, int d, float radius2) {
float gain = fenced(radius2 * uCorner[band]) + 1.0;
return truncateS16(fenced(gain * float(curve(band, d))));
}
int overshootBound(int value, float scale) {
return s16(int(clamp(float(value) * scale, -32768.0, 32767.0)));
}
// Truncating Q16 lerp with a wrapping int16 difference.
int lerp16(int a, int b, int f) { return s16(a + ((s16(b - a) * f) >> 16)); }
ivec2 lowChroma(int x, int y) {
ivec4 yuv = texelFetch(uLowYuv, clamp(ivec2(x, y), ivec2(0), uLowMax), 0);
return ivec2(yuv.g, yuv.b);
}
ivec2 chroma(ivec2 p) {
ivec2 tx = lowTap(p.x);
ivec2 ty = lowTap(p.y);
ivec2 c00 = lowChroma(tx.x, ty.x);
ivec2 c10 = lowChroma(tx.x + 1, ty.x);
ivec2 c01 = lowChroma(tx.x, ty.x + 1);
ivec2 c11 = lowChroma(tx.x + 1, ty.x + 1);
int u = lerp16(lerp16(c00.x, c10.x, tx.y), lerp16(c01.x, c11.x, tx.y), ty.y);
int v = lerp16(lerp16(c00.y, c10.y, tx.y), lerp16(c01.y, c11.y, tx.y), ty.y);
return ivec2(u, v);
}
// Exact binary16 value of RNE(v / 4095), the former float division followed by an RNE half
// conversion, so the attachment write does not depend on the driver's float -> half rounding.
float u12ToUnit(int v) {
if (v == 0) return 0.0;
int shift = 12 - findMSB(v);
if ((v << shift) >= 8190) shift -= 1;
int numerator = v << (shift + 10);
int quotient = numerator / 4095;
if (2 * (numerator - quotient * 4095) > 4095) quotient += 1;
return float(quotient) * uintBitsToFloat(uint(117 - shift) << 23);
}
void main() {
ivec2 p = ivec2(gl_FragCoord.xy);
int y0 = luma(p);
int y1 = level1(p);
int y2 = level2(p);
int y3 = hadd(rhadd(column(p - ivec2(4, 0)), column(p + ivec2(4, 0))), column(p));
float dx = float(p.x - uCenter.x);
float dy = float(p.y - uCenter.y);
float radius2 = fenced(fenced(dy * dy) + fenced(dx * dx)) * uInverseMaxRadius2;
int sharp = s16(y3 + bandTerm(0, s16(y0 - y1), radius2)
+ bandTerm(1, s16(y1 - y2), radius2) + bandTerm(2, s16(y2 - y3), radius2));
int lowest = y0;
int highest = y0;
for (int j = -2; j <= 2; ++j) {
for (int i = -2; i <= 2; ++i) {
int neighbour = luma(p + ivec2(i, j));
lowest = min(lowest, neighbour);
highest = max(highest, neighbour);
}
}
sharp = max(overshootBound(lowest, uLowerScale),
min(overshootBound(highest, uUpperScale), sharp));
sharp = clamp(sharp, 0, 4095);
ivec2 uv = chroma(p);
int u = uv.x;
int v = uv.y;
int red = clamp(sharp + ((3225 * v + 2048) >> 12), 0, 4095);
int green = clamp(sharp + ((-959 * v + -541 * u + 2048) >> 12), 0, 4095);
int blue = clamp(sharp + ((5360 * u + 2048) >> 12), 0, 4095);
oColor = vec4(u12ToUnit(red), u12ToUnit(green), u12ToUnit(blue), 1.0);
}
""".trimIndent()
val guideShader = join(header, integerOps, floatOps, bitOps, linearOps, guide)
val lowGuideShader = join(header, integerOps, floatOps, bitOps, linearOps, boxOps, lowGuide)
val lowColorShader = join(header, integerOps, floatOps, bitOps, linearOps, boxOps, lowColor)
val lowYuvShader = join(header, floatOps, lowYuv)
val cellFitShader = join(header, floatOps, bitOps, cellFit)
val horizontalShader = join(header, integerOps, floatOps, bitOps, gridOps, horizontal)
val guidedYShader = join(header, integerOps, floatOps, bitOps, gridOps, guidedY)
val level1Shader = join(header, integerOps, level1)
val level2Shader = join(header, integerOps, level2)
val outputShader = join(header, integerOps, floatOps, gridOps, output)
private fun join(vararg parts: String) = parts.joinToString("\n\n")
}
@@ -117,12 +117,14 @@ internal class GlesMgcSharpen {
try {
val level1Padding = 2 * GlesMgcSharpenShaders.LEVEL1_PADDING
val level2Padding = 2 * GlesMgcSharpenShaders.LEVEL2_PADDING
lumaTexture = createPlane(width, height)
level1Texture = createPlane(width + level1Padding, height + level1Padding)
level2Texture = createPlane(width + level2Padding, height + level2Padding)
lumaFramebuffer = createFramebuffer(lumaTexture)
level1Framebuffer = createFramebuffer(level1Texture)
level2Framebuffer = createFramebuffer(level2Texture)
lumaTexture = MgcGlesSurfaces.texture(GLES30.GL_R16I, width, height, "MGC sharpen luma")
level1Texture = MgcGlesSurfaces.texture(GLES30.GL_R16I, width + level1Padding,
height + level1Padding, "MGC sharpen level1")
level2Texture = MgcGlesSurfaces.texture(GLES30.GL_R16I, width + level2Padding,
height + level2Padding, "MGC sharpen level2")
lumaFramebuffer = MgcGlesSurfaces.framebuffer("MGC sharpen luma", lumaTexture)
level1Framebuffer = MgcGlesSurfaces.framebuffer("MGC sharpen level1", level1Texture)
level2Framebuffer = MgcGlesSurfaces.framebuffer("MGC sharpen level2", level2Texture)
outputFramebuffer = IntArray(1).also { GLES30.glGenFramebuffers(1, it, 0) }[0]
this.width = width
this.height = height
@@ -132,46 +134,9 @@ internal class GlesMgcSharpen {
}
}
// Integer textures are incomplete under linear filtering, so texelFetch would read zero.
private fun createPlane(width: Int, height: Int): Int {
val names = IntArray(1)
GLES30.glGenTextures(1, names, 0)
GLES30.glBindTexture(GLES30.GL_TEXTURE_2D, names[0])
GLES30.glTexParameteri(GLES30.GL_TEXTURE_2D, GLES30.GL_TEXTURE_MIN_FILTER, GLES30.GL_NEAREST)
GLES30.glTexParameteri(GLES30.GL_TEXTURE_2D, GLES30.GL_TEXTURE_MAG_FILTER, GLES30.GL_NEAREST)
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.glTexStorage2D(GLES30.GL_TEXTURE_2D, 1, GLES30.GL_R16I, width, height)
GLES30.glBindTexture(GLES30.GL_TEXTURE_2D, 0)
val error = GLES30.glGetError()
if (error != GLES30.GL_NO_ERROR) {
GLES30.glDeleteTextures(1, names, 0)
error("MGC sharpen R16I plane ${width}x$height failed: 0x${Integer.toHexString(error)}")
}
return names[0]
}
private fun createFramebuffer(texture: Int): Int {
val names = IntArray(1)
GLES30.glGenFramebuffers(1, names, 0)
GLES30.glBindFramebuffer(GLES30.GL_FRAMEBUFFER, names[0])
GLES30.glFramebufferTexture2D(GLES30.GL_FRAMEBUFFER, GLES30.GL_COLOR_ATTACHMENT0,
GLES30.GL_TEXTURE_2D, texture, 0)
val status = GLES30.glCheckFramebufferStatus(GLES30.GL_FRAMEBUFFER)
GLES30.glBindFramebuffer(GLES30.GL_FRAMEBUFFER, 0)
if (status != GLES30.GL_FRAMEBUFFER_COMPLETE) {
GLES30.glDeleteFramebuffers(1, names, 0)
error("MGC sharpen R16I framebuffer is incomplete: 0x${Integer.toHexString(status)}")
}
return names[0]
}
fun releaseBuffers() {
val framebuffers = intArrayOf(lumaFramebuffer, level1Framebuffer, level2Framebuffer, outputFramebuffer)
.filter { it != 0 }.toIntArray()
if (framebuffers.isNotEmpty()) GLES30.glDeleteFramebuffers(framebuffers.size, framebuffers, 0)
val textures = intArrayOf(lumaTexture, level1Texture, level2Texture).filter { it != 0 }.toIntArray()
if (textures.isNotEmpty()) GLES30.glDeleteTextures(textures.size, textures, 0)
MgcGlesSurfaces.deleteFramebuffers(lumaFramebuffer, level1Framebuffer, level2Framebuffer, outputFramebuffer)
MgcGlesSurfaces.deleteTextures(lumaTexture, level1Texture, level2Texture)
lumaFramebuffer = 0; level1Framebuffer = 0; level2Framebuffer = 0; outputFramebuffer = 0
lumaTexture = 0; level1Texture = 0; level2Texture = 0
width = 0; height = 0
@@ -193,9 +158,11 @@ internal class GlesMgcSharpen {
* The AOT entry's curve preparation, in the same unfused binary32 order (JVM Float arithmetic
* is never contracted): knots and y values become int16 U12 codes, then each of the four
* segments gets a Q8 slope and an intercept. Curves use [MgcSharpenCurveBuilder]'s
* [point, frequency, coordinate] layout.
* [point, frequency, coordinate] layout. The corner term is normalised over
* [cornerWidth] x [cornerHeight]: the image for SharpenTo16Bit, the two-row padded output for
* GuidedUpsample.
*/
class KernelUniforms(curves: FloatArray, width: Int, height: Int, attenuation: Float) {
class KernelUniforms(curves: FloatArray, cornerWidth: Int, cornerHeight: Int, attenuation: Float) {
val knots = IntArray(9)
val slopes = IntArray(12)
val intercepts = IntArray(12)
@@ -221,8 +188,8 @@ internal class GlesMgcSharpen {
intercepts[band * 4 + k] = toS16(intercept)
}
}
val halfWidth = width shr 1
val halfHeight = height shr 1
val halfWidth = cornerWidth shr 1
val halfHeight = cornerHeight shr 1
val maxRadius2 = (halfWidth * halfWidth).toFloat() + (halfHeight * halfHeight).toFloat()
radialValid = maxRadius2 > 0f
inverseMaxRadius2 = if (radialValid) 1f / maxRadius2 else 0f
@@ -0,0 +1,59 @@
package com.hinnka.mycamera.raw
import android.opengl.GLES30
/** Immutable render-target textures and framebuffers for the MGC GLES kernel ports. */
internal object MgcGlesSurfaces {
/**
* Integer formats are incomplete under linear filtering (texelFetch would read zero), so
* [filter] defaults to nearest; the kernels only use texelFetch.
*/
fun texture(format: Int, width: Int, height: Int, label: String, filter: Int = GLES30.GL_NEAREST): Int {
require(width > 0 && height > 0)
val names = IntArray(1)
GLES30.glGenTextures(1, names, 0)
GLES30.glBindTexture(GLES30.GL_TEXTURE_2D, names[0])
GLES30.glTexParameteri(GLES30.GL_TEXTURE_2D, GLES30.GL_TEXTURE_MIN_FILTER, filter)
GLES30.glTexParameteri(GLES30.GL_TEXTURE_2D, GLES30.GL_TEXTURE_MAG_FILTER, filter)
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.glTexStorage2D(GLES30.GL_TEXTURE_2D, 1, format, width, height)
GLES30.glBindTexture(GLES30.GL_TEXTURE_2D, 0)
val error = GLES30.glGetError()
if (error != GLES30.GL_NO_ERROR) {
GLES30.glDeleteTextures(1, names, 0)
error("$label texture ${width}x$height failed: 0x${Integer.toHexString(error)}")
}
return names[0]
}
/** A framebuffer drawing to [textures] as colour attachments 0..n-1, in order. */
fun framebuffer(label: String, vararg textures: Int): Int {
val names = IntArray(1)
GLES30.glGenFramebuffers(1, names, 0)
GLES30.glBindFramebuffer(GLES30.GL_FRAMEBUFFER, names[0])
textures.forEachIndexed { index, texture ->
GLES30.glFramebufferTexture2D(GLES30.GL_FRAMEBUFFER, GLES30.GL_COLOR_ATTACHMENT0 + index,
GLES30.GL_TEXTURE_2D, texture, 0)
}
val buffers = IntArray(textures.size) { GLES30.GL_COLOR_ATTACHMENT0 + it }
GLES30.glDrawBuffers(buffers.size, buffers, 0)
val status = GLES30.glCheckFramebufferStatus(GLES30.GL_FRAMEBUFFER)
GLES30.glBindFramebuffer(GLES30.GL_FRAMEBUFFER, 0)
if (status != GLES30.GL_FRAMEBUFFER_COMPLETE) {
GLES30.glDeleteFramebuffers(1, names, 0)
error("$label framebuffer is incomplete: 0x${Integer.toHexString(status)}")
}
return names[0]
}
fun deleteTextures(vararg textures: Int) {
val live = textures.filter { it != 0 }.toIntArray()
if (live.isNotEmpty()) GLES30.glDeleteTextures(live.size, live, 0)
}
fun deleteFramebuffers(vararg framebuffers: Int) {
val live = framebuffers.filter { it != 0 }.toIntArray()
if (live.isNotEmpty()) GLES30.glDeleteFramebuffers(live.size, live, 0)
}
}
@@ -2,132 +2,296 @@ package com.hinnka.mycamera.raw
import android.opengl.GLES30
import java.nio.ByteBuffer
import java.nio.ByteOrder
import kotlin.math.sqrt
/** Owns the three distinct inputs of V25's S16 GuidedUpsample until reconstruction. */
internal class MgcGuidedUpsample(private val transfer: RawFloatTextureTransfer) {
private var handle = 0L
/**
* MGC V25 guided finish on the GPU ([GlesMgcGuidedUpsampleShaders]).
*
* [prepare] keeps the full-resolution guide and the box-downsampled guide, and renders the
* low-resolution linear colour ([cameraTexture]) that the colour pipeline processes at
* [lowWidth] x [lowHeight] into [profileTexture]. [render] then reconstructs and sharpens the
* full-resolution result from that low-resolution output. The prepared inputs live until [render]
* or [releaseBuffers]; the source textures must hold finite values.
*/
internal class MgcGuidedUpsample {
private var fullWidth = 0
private var fullHeight = 0
private var scale = 0
private var paddedWidth = 0
private var paddedHeight = 0
private var log2Scale = 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 var guideTexture = 0
private var lowGuideTexture = 0
val isPrepared get() = guideTexture != 0
val globalWidth get() = lowWidth shl log2Scale
val globalHeight get() = lowHeight shl log2Scale
private val quad = RawFullscreenQuad()
private var colorDownsampleProgram = 0
private val programs = HashMap<String, Int>()
private var sqrtLutTexture = 0
fun prepare(texture: Int, width: Int, height: Int, gains: FloatArray,
resolution: MgcFinishResolution) {
require(resolution.needsGuidedUpsample)
releaseInputs()
scale = resolution.downsampleFactor
require(resolution.needsGuidedUpsample && width > 0 && height > 0 && texture != 0)
releaseBuffers()
val whiteBalance = normalizedRgbWhiteBalance(gains)
log2Scale = resolution.log2Downsample
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)
paddedWidth = (width + 127) and -128
paddedHeight = (height + 15) and -16
lowWidth = paddedWidth shr log2Scale
lowHeight = paddedHeight shr log2Scale
val framebuffers = IntArray(3)
try {
transfer.read(texture, width, height, capacityPixels, label = "guidedPrepare") { rgba ->
handle = nativePrepare(rgba, width, height, resolution.log2Downsample,
normalizedRgbWhiteBalance(gains))
check(handle != 0L) { "MGC linear guide/BoxDownsample preparation failed" }
guideTexture = MgcGlesSurfaces.texture(GLES30.GL_R16I, paddedWidth, paddedHeight, "MGC guide")
lowGuideTexture = MgcGlesSurfaces.texture(GLES30.GL_R16I, lowWidth, lowHeight, "MGC low guide")
cameraTexture = MgcGlesSurfaces.texture(GLES30.GL_RGBA16F, lowWidth, lowHeight,
"MGC low colour", GLES30.GL_LINEAR)
profileTexture = MgcGlesSurfaces.texture(GLES30.GL_RGBA16F, lowWidth, lowHeight,
"MGC low profile", GLES30.GL_LINEAR)
profileFramebuffer = MgcGlesSurfaces.framebuffer("MGC low profile", profileTexture)
val lut = sqrtLut()
val sourceSetup: (Int) -> Unit = { program ->
bindTexture(program, "uSource", 0, texture)
bindTexture(program, "uSqrtLut", 1, lut)
GLES30.glUniform2i(location(program, "uSourceMax"), width - 1, height - 1)
GLES30.glUniform1fv(location(program, "uWhiteBalance"), 3, whiteBalance, 0)
GLES30.glUniform1ui(location(program, "uFloatFence"), 0)
GLES30.glUniform1i(location(program, "uLog2Scale"), log2Scale)
}
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 }
framebuffers[0] = MgcGlesSurfaces.framebuffer("MGC guide", guideTexture)
draw("guide", framebuffers[0], paddedWidth, paddedHeight, sourceSetup)
framebuffers[1] = MgcGlesSurfaces.framebuffer("MGC low guide", lowGuideTexture)
draw("lowGuide", framebuffers[1], lowWidth, lowHeight, sourceSetup)
framebuffers[2] = MgcGlesSurfaces.framebuffer("MGC low colour", cameraTexture)
draw("lowColor", framebuffers[2], lowWidth, lowHeight, sourceSetup)
finishPasses("prepare")
} catch (error: Throwable) {
releaseBuffers()
throw error
} finally {
MgcGlesSurfaces.deleteFramebuffers(*framebuffers)
}
}
/** 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)
val program = programs.getOrPut("filmicColor") {
quad.createProgram(BOX_COLOR, "GuidedFilmicColor").also { check(it != 0) }
}
GLES30.glUseProgram(colorDownsampleProgram)
GLES30.glUseProgram(program)
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)
GLES30.glUniform1i(GLES30.glGetUniformLocation(program, "uInput"), 0)
GLES30.glUniform1i(GLES30.glGetUniformLocation(program, "uScale"), 1 shl log2Scale)
quad.bindIdentityTextureMatrix(program)
quad.draw(program)
check(GLES30.glGetError() == GLES30.GL_NO_ERROR)
}
/** Reconstructs [width] x [height] into the RGBA16F [target] from the low-resolution [source]. */
fun render(source: Int, target: Int, width: Int, height: Int, attenuation: Float, curves: FloatArray) {
check(isPrepared && width == fullWidth && height == fullHeight)
require(attenuation.isFinite() && attenuation >= 0f && source != 0 && target != 0)
val padding = GlesMgcGuidedUpsampleShaders.GUIDED_PADDING
val level1Padding = 2 * GlesMgcGuidedUpsampleShaders.LEVEL1_PADDING
val level2Padding = 2 * GlesMgcGuidedUpsampleShaders.LEVEL2_PADDING
val scale = 1 shl log2Scale
val cellStep = 32768 / scale
fun cellOf(x: Int) = ((2 * x + 1) * cellStep - 65536) shr 17
val cellX0 = cellOf(-padding)
val cellY0 = cellOf(-padding)
val cellColumns = cellOf(width - 1 + padding) + 1 - cellX0 + 1
val cellRows = cellOf(height - 1 + padding) + 1 - cellY0 + 1
val guidedWidth = width + 2 * padding
val guidedHeight = height + 2 * padding
val paddedOutputHeight = (height + 1) and -2
val kernel = GlesMgcSharpen.KernelUniforms(curves, width, paddedOutputHeight, attenuation)
val textures = IntArray(8)
val framebuffers = IntArray(7)
try {
val u12RgbOutput = transfer.supportsU12RgbUpload(width, height)
transfer.read(source, lowWidth, lowHeight,
maxOf(width.toLong() * height, lowWidth.toLong() * lowHeight), label = "guidedRender") { rgba ->
val result = nativeRender(handle, rgba, attenuation, curves, u12RgbOutput)
check(result == 0) { "MGC GuidedUpsample failed: $result" }
val lowYuv = MgcGlesSurfaces.texture(GLES30.GL_RGBA16I, lowWidth, lowHeight, "MGC low YUV")
.also { textures[0] = it }
val cell0 = MgcGlesSurfaces.texture(GLES30.GL_RGBA32UI, cellColumns, cellRows, "MGC cells 0")
.also { textures[1] = it }
val cell1 = MgcGlesSurfaces.texture(GLES30.GL_RGBA32UI, cellColumns, cellRows, "MGC cells 1")
.also { textures[2] = it }
val row0 = MgcGlesSurfaces.texture(GLES30.GL_RGBA32UI, guidedWidth, cellRows, "MGC rows 0")
.also { textures[3] = it }
val row1 = MgcGlesSurfaces.texture(GLES30.GL_RGBA32UI, guidedWidth, cellRows, "MGC rows 1")
.also { textures[4] = it }
val guided = MgcGlesSurfaces.texture(GLES30.GL_R16I, guidedWidth, guidedHeight, "MGC guided luma")
.also { textures[5] = it }
val level1 = MgcGlesSurfaces.texture(GLES30.GL_R16I, width + level1Padding,
height + level1Padding, "MGC guided level1").also { textures[6] = it }
val level2 = MgcGlesSurfaces.texture(GLES30.GL_R16I, width + level2Padding,
height + level2Padding, "MGC guided level2").also { textures[7] = it }
framebuffers[0] = MgcGlesSurfaces.framebuffer("MGC low YUV", lowYuv)
draw("lowYuv", framebuffers[0], lowWidth, lowHeight) { program ->
bindTexture(program, "uSource", 0, source)
GLES30.glUniform1ui(location(program, "uFloatFence"), 0)
}
if (u12RgbOutput) {
transfer.uploadU12Rgb(target, width, height)
} else {
transfer.upload(target, width, height)
framebuffers[1] = MgcGlesSurfaces.framebuffer("MGC cells", cell0, cell1)
draw("cellFit", framebuffers[1], cellColumns, cellRows) { program ->
bindTexture(program, "uLowGuide", 0, lowGuideTexture)
bindTexture(program, "uLowYuv", 1, lowYuv)
GLES30.glUniform2i(location(program, "uLowMax"), lowWidth - 1, lowHeight - 1)
GLES30.glUniform2i(location(program, "uCellOrigin"), cellX0, cellY0)
GLES30.glUniform1ui(location(program, "uFloatFence"), 0)
}
} finally { releaseInputs() }
framebuffers[2] = MgcGlesSurfaces.framebuffer("MGC rows", row0, row1)
draw("horizontal", framebuffers[2], guidedWidth, cellRows) { program ->
bindTexture(program, "uCell0", 0, cell0)
bindTexture(program, "uCell1", 1, cell1)
GLES30.glUniform2i(location(program, "uCellOrigin"), cellX0, cellY0)
GLES30.glUniform1i(location(program, "uCellStep"), cellStep)
GLES30.glUniform1ui(location(program, "uFloatFence"), 0)
}
framebuffers[3] = MgcGlesSurfaces.framebuffer("MGC guided luma", guided)
draw("guidedY", framebuffers[3], guidedWidth, guidedHeight) { program ->
bindTexture(program, "uRow0", 0, row0)
bindTexture(program, "uRow1", 1, row1)
bindTexture(program, "uGuide", 2, guideTexture)
GLES30.glUniform2i(location(program, "uGuideMax"), paddedWidth - 1, paddedHeight - 1)
GLES30.glUniform1i(location(program, "uCellOriginY"), cellY0)
GLES30.glUniform1i(location(program, "uCellStep"), cellStep)
GLES30.glUniform1ui(location(program, "uFloatFence"), 0)
}
framebuffers[4] = MgcGlesSurfaces.framebuffer("MGC guided level1", level1)
draw("level1", framebuffers[4], width + level1Padding, height + level1Padding) { program ->
bindTexture(program, "uLuma", 0, guided)
}
framebuffers[5] = MgcGlesSurfaces.framebuffer("MGC guided level2", level2)
draw("level2", framebuffers[5], width + level2Padding, height + level2Padding) { program ->
bindTexture(program, "uLevel1", 0, level1)
}
framebuffers[6] = MgcGlesSurfaces.framebuffer("MGC guided output", target)
draw("output", framebuffers[6], width, height) { program ->
bindTexture(program, "uLuma", 0, guided)
bindTexture(program, "uLevel1", 1, level1)
bindTexture(program, "uLevel2", 2, level2)
bindTexture(program, "uLowYuv", 3, lowYuv)
GLES30.glUniform2i(location(program, "uLowMax"), lowWidth - 1, lowHeight - 1)
GLES30.glUniform1i(location(program, "uCellStep"), cellStep)
GLES30.glUniform1iv(location(program, "uKnots"), kernel.knots.size, kernel.knots, 0)
GLES30.glUniform1iv(location(program, "uSlopes"), kernel.slopes.size, kernel.slopes, 0)
GLES30.glUniform1iv(location(program, "uIntercepts"), kernel.intercepts.size, kernel.intercepts, 0)
GLES30.glUniform2i(location(program, "uCenter"), width shr 1, paddedOutputHeight shr 1)
GLES30.glUniform1f(location(program, "uInverseMaxRadius2"), kernel.inverseMaxRadius2)
GLES30.glUniform1fv(location(program, "uCorner"), 3, RELATIVE_CORNER_ACUTANCE_CORRECTION, 0)
GLES30.glUniform1f(location(program, "uLowerScale"), kernel.lowerScale)
GLES30.glUniform1f(location(program, "uUpperScale"), kernel.upperScale)
GLES30.glUniform1ui(location(program, "uFloatFence"), 0)
}
finishPasses("render")
} finally {
MgcGlesSurfaces.deleteFramebuffers(*framebuffers)
MgcGlesSurfaces.deleteTextures(*textures)
releaseBuffers()
}
}
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.glTexStorage2D(GLES30.GL_TEXTURE_2D, 1, GLES30.GL_RGBA16F, lowWidth, lowHeight)
check(GLES30.glGetError() == GLES30.GL_NO_ERROR)
return texture
} catch (error: Throwable) { GLES30.glDeleteTextures(1, names, 0); throw error }
private fun draw(pass: String, framebuffer: Int, width: Int, height: Int, setup: (Int) -> Unit) {
val program = program(pass)
GLES30.glBindFramebuffer(GLES30.GL_FRAMEBUFFER, framebuffer)
GLES30.glViewport(0, 0, width, height)
GLES30.glUseProgram(program)
quad.bindIdentityTextureMatrix(program)
setup(program)
quad.draw(program)
}
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)
private fun finishPasses(stage: String) {
GLES30.glBindFramebuffer(GLES30.GL_FRAMEBUFFER, 0)
for (unit in 3 downTo 0) {
GLES30.glActiveTexture(GLES30.GL_TEXTURE0 + unit)
GLES30.glBindTexture(GLES30.GL_TEXTURE_2D, 0)
}
val error = GLES30.glGetError()
check(error == GLES30.GL_NO_ERROR) { "MGC guided $stage passes failed: 0x${Integer.toHexString(error)}" }
}
private fun program(pass: String): Int = programs.getOrPut(pass) {
val source = with(GlesMgcGuidedUpsampleShaders) {
when (pass) {
"guide" -> guideShader
"lowGuide" -> lowGuideShader
"lowColor" -> lowColorShader
"lowYuv" -> lowYuvShader
"cellFit" -> cellFitShader
"horizontal" -> horizontalShader
"guidedY" -> guidedYShader
"level1" -> level1Shader
"level2" -> level2Shader
"output" -> outputShader
else -> error("Unknown MGC guided pass $pass")
}
}
quad.createProgram(source, "MgcGuided_$pass").also { check(it != 0) { "Failed to link MGC guided $pass" } }
}
private fun location(program: Int, name: String) = GLES30.glGetUniformLocation(program, name)
private fun bindTexture(program: Int, name: String, unit: Int, texture: Int) {
GLES30.glActiveTexture(GLES30.GL_TEXTURE0 + unit)
GLES30.glBindTexture(GLES30.GL_TEXTURE_2D, texture)
GLES30.glUniform1i(location(program, name), unit)
}
/** SqrtGuide(g) for g in [0, 32767] at texel (g and 255, g shr 8). */
private fun sqrtLut(): Int {
if (sqrtLutTexture != 0) return sqrtLutTexture
val values = ByteBuffer.allocateDirect(32768 * 2).order(ByteOrder.nativeOrder())
// JVM float sqrt is correctly rounded; for g >= 1 the AOT's `s < 1 ? rne(s)` never applies
// and g = 0 gives 0, so this equals fcvtzs(sqrt(g) * 128) of the original.
for (g in 0 until 32768) values.putShort((sqrt(g.toFloat()) * 128f).toInt().toShort())
values.position(0)
val texture = MgcGlesSurfaces.texture(GLES30.GL_R16I, 256, 128, "MGC sqrt guide LUT")
GLES30.glBindTexture(GLES30.GL_TEXTURE_2D, texture)
GLES30.glPixelStorei(GLES30.GL_UNPACK_ALIGNMENT, 2)
GLES30.glTexSubImage2D(GLES30.GL_TEXTURE_2D, 0, 0, 0, 256, 128,
GLES30.GL_RED_INTEGER, GLES30.GL_SHORT, values)
GLES30.glPixelStorei(GLES30.GL_UNPACK_ALIGNMENT, 4)
GLES30.glBindTexture(GLES30.GL_TEXTURE_2D, 0)
val error = GLES30.glGetError()
if (error != GLES30.GL_NO_ERROR) {
MgcGlesSurfaces.deleteTextures(texture)
error("MGC sqrt guide LUT upload failed: 0x${Integer.toHexString(error)}")
}
sqrtLutTexture = texture
return texture
}
/** Drops the prepared guides and low-resolution textures; programs and the LUT are kept. */
fun releaseBuffers() {
MgcGlesSurfaces.deleteFramebuffers(profileFramebuffer)
MgcGlesSurfaces.deleteTextures(cameraTexture, profileTexture, guideTexture, lowGuideTexture)
profileFramebuffer = 0; cameraTexture = 0; profileTexture = 0
fullWidth = 0; fullHeight = 0; lowWidth = 0; lowHeight = 0
scale = 0
guideTexture = 0; lowGuideTexture = 0
fullWidth = 0; fullHeight = 0; paddedWidth = 0; paddedHeight = 0
lowWidth = 0; lowHeight = 0; log2Scale = 0
}
fun release() {
releaseInputs()
if (colorDownsampleProgram != 0) GLES30.glDeleteProgram(colorDownsampleProgram)
colorDownsampleProgram = 0
releaseBuffers()
programs.values.forEach { GLES30.glDeleteProgram(it) }
programs.clear()
MgcGlesSurfaces.deleteTextures(sqrtLutTexture)
sqrtLutTexture = 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,
u12RgbOutput: Boolean): Int
private external fun nativeRelease(handle: Long)
companion object {
init { System.loadLibrary("my-native-lib") }
private val BOX_COLOR = """
private companion object {
// FinishRaw's relative corner acutance correction; the original call site passes zeros.
val RELATIVE_CORNER_ACUTANCE_CORRECTION = floatArrayOf(0f, 0f, 0f)
val BOX_COLOR = """
#version 300 es
precision highp float;
precision highp int;
@@ -149,7 +313,7 @@ internal class MgcGuidedUpsample(private val transfer: RawFloatTextureTransfer)
/**
* The guide's linear YUV boundary applies channel gains normalized to the green mean; the
* native bridge removes them again after YUV -> RGB.
* low colour pass removes them again after YUV -> RGB.
*/
private fun normalizedRgbWhiteBalance(gains: FloatArray): FloatArray {
fun safeGain(index: Int, fallback: Float): Float {
@@ -3,10 +3,9 @@ package com.hinnka.mycamera.raw
import com.hinnka.mycamera.processor.PhotonCoreImagingTuning
import com.hinnka.mycamera.processor.PhotonSharpenTuning
/** MGC FinishRaw sharpening: the GLES SharpenTo16Bit port, or GuidedUpsample when prepared. */
/** MGC FinishRaw sharpening: the GLES SharpenTo16Bit port, or the GLES GuidedUpsample when prepared. */
internal class MgcSharpen {
private val transfer = RawFloatTextureTransfer()
val guided = MgcGuidedUpsample(transfer)
val guided = MgcGuidedUpsample()
private val sharpen = GlesMgcSharpen()
fun render(sourceTexture: Int, targetTexture: Int, width: Int, height: Int,
@@ -23,14 +22,12 @@ internal class MgcSharpen {
}
fun releaseBuffers() {
guided.release()
guided.releaseBuffers()
sharpen.releaseBuffers()
transfer.releaseBuffers()
}
fun release() {
releaseBuffers()
guided.release()
sharpen.release()
transfer.release()
}
}
@@ -1,185 +0,0 @@
// Standalone ARM64 executable; never installs an APK or uses instrumentation.
#include "mgc_denoise_static.h"
#include "mgc_guided_prepare_adapter.h"
#include <EGL/egl.h>
#include <GLES3/gl31.h>
#include <chrono>
#include <cmath>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <limits>
#include <random>
#include <jni.h>
#include <vector>
using namespace photon::mgc_denoise;
using Clock = std::chrono::steady_clock;
extern "C" jlong Java_com_hinnka_mycamera_raw_MgcGuidedUpsample_nativePrepare(
JNIEnv *, jobject, jobject, jint, jint, jint, jfloatArray);
extern "C" void Java_com_hinnka_mycamera_raw_MgcGuidedUpsample_nativeRelease(
JNIEnv *, jobject, jlong);
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 void Check(bool ok, const char *label) {
if (!ok) { fprintf(stderr, "FAIL %s\n", label); std::exit(1); }
}
static double Ms(Clock::time_point a, Clock::time_point b) {
return std::chrono::duration<double, std::milli>(b - a).count();
}
static void Original(const float *rgba, int w, int h, int pw, int ph,
const float wb[3], uint16_t *rgb, int16_t *yuv,
double *q14_ms = nullptr, double *yuv_ms = nullptr) {
const size_t n = size_t(pw) * ph;
const auto start = Clock::now();
#pragma omp parallel for schedule(static) num_threads(4)
for (int y = 0; y < ph; ++y)
for (int x = 0; x < pw; ++x) {
const size_t src = (size_t(std::min(y, h - 1)) * w + std::min(x, w - 1)) * 4;
for (int c = 0; c < 3; ++c) {
const float v = rgba[src + c];
Check(std::isfinite(v), "reference finite");
rgb[size_t(c) * n + size_t(y) * pw + x] = uint16_t(
std::lround(std::clamp(v * wb[c], 0.f, 1.f) * 16383.f));
}
}
const auto converted = Clock::now();
Check(RunRgbRawToYuv(rgb, pw, ph, yuv) == 0, "original AOT");
const auto end = Clock::now();
if (q14_ms) *q14_ms = Ms(start, converted);
if (yuv_ms) *yuv_ms = Ms(converted, end);
}
static void Compare(const std::vector<float> &rgba, int w, int h, const float wb[3]) {
const int pw = (w + 127) & ~127, ph = (h + 15) & ~15;
const size_t n = size_t(pw) * ph;
std::vector<uint16_t> rgb(n * 3);
std::vector<int16_t> old(n * 3), now(n * 3 + 32, 12345);
Original(rgba.data(), w, h, pw, ph, wb, rgb.data(), old.data());
Check(GuidedFloatRgbaToLinearYuv(rgba.data(), w, h, pw, ph, wb, now.data()), "fused valid");
if (memcmp(old.data(), now.data(), n * 6)) {
for (size_t i = 0; i < n * 3; ++i) if (old[i] != now[i]) {
fprintf(stderr, "mismatch %dx%d wb=%g,%g,%g index=%zu old=%d new=%d\n",
w, h, wb[0], wb[1], wb[2], i, old[i], now[i]); break;
}
std::exit(2);
}
for (size_t i = n * 3; i < now.size(); ++i) Check(now[i] == 12345, "output guard");
}
static void Numerics() {
std::mt19937 random(1709);
const float gains[][3] = {{1.f,1.f,1.f},{.001f,.73f,4.18f},{2.f,1.f,1.7f},
{std::numeric_limits<float>::max(),.00001f,1000.f}};
size_t checked = 0;
for (auto shape : {std::pair<int,int>{1,1},{3,5},{127,15},{128,16},{129,17},
{385,321},{1024,1024},{2728,2048}}) {
const int w = shape.first, h = shape.second;
std::vector<float> rgba(size_t(w) * h * 4);
for (float &v : rgba) v = float(int(random() % 65536) - 16384) / 16383.f;
for (const auto &wb : gains) { Compare(rgba, w, h, wb); checked += size_t(w) * h; }
}
// All Q14 levels on every axis; ties and neighbors exercise lround's rule.
for (int axis = 0; axis < 3; ++axis) {
std::vector<float> rgba(16384 * 4);
for (int i = 0; i < 16384; ++i) for (int c = 0; c < 4; ++c)
rgba[i * 4 + c] = c == axis ? float(i) / 16383.f : float(random() % 16384) / 16383.f;
Compare(rgba, 128, 128, gains[0]);
for (int delta = -1; delta <= 1; ++delta) {
for (int i = 0; i < 16384; ++i) {
const float tie = (float(i) + .5f) / 16383.f;
rgba[i * 4 + axis] = delta == 0 ? tie : std::nextafter(tie, delta < 0 ? 0.f : 2.f);
}
Compare(rgba, 128, 128, gains[0]);
}
}
for (float bad : {std::numeric_limits<float>::infinity(),
-std::numeric_limits<float>::infinity(),
std::numeric_limits<float>::quiet_NaN()})
for (int pixel = 0; pixel < 15; ++pixel) for (int c = 0; c < 3; ++c) {
std::vector<float> rgba(15 * 4, .5f); std::vector<int16_t> out(128 * 16 * 3);
rgba[pixel * 4 + c] = bad;
Check(!GuidedFloatRgbaToLinearYuv(rgba.data(), 3, 5, 128, 16, gains[0], out.data()), "nonfinite rejection");
}
{
std::vector<float> rgba(3 * 5 * 4, .5f);
std::vector<int16_t> out(128 * 16 * 3);
Check(!GuidedFloatRgbaToLinearYuv(rgba.data(), 3, 5, 127, 16, gains[0], out.data()), "non-vector-aligned padding");
Check(!GuidedFloatRgbaToLinearYuv(rgba.data(), 3, 5, 128, 4, gains[0], out.data()), "short padded height");
Check(!GuidedFloatRgbaToLinearYuv(rgba.data(), 129, 5, 128, 16, gains[0], out.data()), "short padded width");
for (size_t i = 0; i < rgba.size() / 4; ++i) rgba[i * 4 + 3] = std::numeric_limits<float>::quiet_NaN();
Compare(rgba, 3, 5, gains[0]); // Alpha is not part of the camera RGB boundary.
}
printf("PASS AOT equivalence: %zu+ pixels, WB/clipping/overflow, Q14 axes/ties, odd padding, finite rejection\n", checked);
}
static void Benchmark(const char *kind, const float *rgba, int w, int h) {
const int pw = (w + 127) & ~127, ph = (h + 15) & ~15;
const size_t n = size_t(pw) * ph;
const float wb[3] = {2.14f,1.f,1.62f};
std::vector<uint16_t> rgb(n * 3);
std::vector<int16_t> old(n * 3), now(n * 3);
std::vector<double> q, y, fused;
for (int iteration = 0; iteration < 10; ++iteration) {
double qms, yms;
Original(rgba, w, h, pw, ph, wb, rgb.data(), old.data(), &qms, &yms);
const auto begin = Clock::now();
Check(GuidedFloatRgbaToLinearYuv(rgba, w, h, pw, ph, wb, now.data()), "benchmark valid");
const auto end = Clock::now();
Check(old == now, "benchmark pixels");
if (iteration >= 2) { q.push_back(qms); y.push_back(yms); fused.push_back(Ms(begin, end)); }
}
std::sort(q.begin(), q.end()); std::sort(y.begin(), y.end()); std::sort(fused.begin(), fused.end());
printf("%s %dx%d median q14=%.2fms AOT=%.2fms fused=%.2fms (preallocated)\n",kind,w,h,q[4],y[4],fused[4]);
}
static void MappedBenchmark() {
EGLDisplay display = eglGetDisplay(EGL_DEFAULT_DISPLAY);
Check(eglInitialize(display, nullptr, nullptr), "EGL init");
const EGLint attrs[] = {EGL_SURFACE_TYPE,EGL_PBUFFER_BIT,EGL_RENDERABLE_TYPE,EGL_OPENGL_ES3_BIT,EGL_NONE};
EGLConfig config; EGLint count;
Check(eglChooseConfig(display,attrs,&config,1,&count) && count,"EGL config");
const EGLint context_attrs[] = {EGL_CONTEXT_CLIENT_VERSION,3,EGL_NONE};
const EGLint surface_attrs[] = {EGL_WIDTH,1,EGL_HEIGHT,1,EGL_NONE};
auto context = eglCreateContext(display,config,EGL_NO_CONTEXT,context_attrs);
auto surface = eglCreatePbufferSurface(display,config,surface_attrs);
Check(eglMakeCurrent(display,surface,surface,context),"EGL current");
printf("GPU %s / %s\n",glGetString(GL_RENDERER),glGetString(GL_VERSION));
const int w=2728,h=2048,n=w*h;
const char *source="#version 310 es\nprecision highp float;precision highp int;layout(local_size_x=128) in;layout(std430,binding=0) writeonly buffer Pixels{vec4 pixels[];};uniform int uCount;void main(){uint i=gl_GlobalInvocationID.x;if(i>=uint(uCount))return;pixels[i]=vec4(float((i*13u)%16384u),float((i*47u)%16384u),float((i*101u)%16384u),16383.0)/16383.0;}";
GLuint shader=glCreateShader(GL_COMPUTE_SHADER);glShaderSource(shader,1,&source,nullptr);glCompileShader(shader);
GLint ok;glGetShaderiv(shader,GL_COMPILE_STATUS,&ok);Check(ok,"compute compile");
GLuint program=glCreateProgram();glAttachShader(program,shader);glLinkProgram(program);
glGetProgramiv(program,GL_LINK_STATUS,&ok);Check(ok,"compute link");
GLuint buffer;glGenBuffers(1,&buffer);glBindBuffer(GL_SHADER_STORAGE_BUFFER,buffer);
GLint64 limit;glGetInteger64v(GL_MAX_SHADER_STORAGE_BLOCK_SIZE,&limit);Check(int64_t(n)*16<=limit,"SSBO limit");
glBufferData(GL_SHADER_STORAGE_BUFFER,size_t(n)*16,nullptr,GL_STREAM_COPY);
glUseProgram(program);glUniform1i(glGetUniformLocation(program,"uCount"),n);
glBindBufferBase(GL_SHADER_STORAGE_BUFFER,0,buffer);glDispatchCompute((n+127)/128,1,1);
glMemoryBarrier(GL_SHADER_STORAGE_BARRIER_BIT|GL_BUFFER_UPDATE_BARRIER_BIT);
glBindBufferBase(GL_SHADER_STORAGE_BUFFER,0,0);glBindBuffer(GL_PIXEL_PACK_BUFFER,buffer);
auto mapped=static_cast<float*>(glMapBufferRange(GL_PIXEL_PACK_BUFFER,0,size_t(n)*16,GL_MAP_READ_BIT|GL_MAP_WRITE_BIT));
Check(mapped && glGetError()==GL_NO_ERROR,"mapped GPU-produced input");
std::vector<float> heap(mapped,mapped+size_t(n)*4);
Benchmark("heap",heap.data(),w,h);Benchmark("GPU-mapped",mapped,w,h);
auto env = FakeJni();
float wb[] = {2.14f,1.f,1.62f};
Buffer input{mapped,jlong(n)*16},gains{wb,12};
const auto prepare_begin = Clock::now();
const auto handle = Java_com_hinnka_mycamera_raw_MgcGuidedUpsample_nativePrepare(
&env,nullptr,reinterpret_cast<jobject>(&input),w,h,1,reinterpret_cast<jfloatArray>(&gains));
const auto prepare_end = Clock::now();
Check(handle != 0,"complete mapped nativePrepare");
printf("GPU-mapped %dx%d complete nativePrepare=%.2fms (fresh allocations, box, low RGB, mapped writeback)\n",w,h,Ms(prepare_begin,prepare_end));
Java_com_hinnka_mycamera_raw_MgcGuidedUpsample_nativeRelease(&env,nullptr,handle);
Check(glUnmapBuffer(GL_PIXEL_PACK_BUFFER),"unmap");glDeleteBuffers(1,&buffer);
glDeleteProgram(program);glDeleteShader(shader);eglMakeCurrent(display,EGL_NO_SURFACE,EGL_NO_SURFACE,EGL_NO_CONTEXT);
eglDestroySurface(display,surface);eglDestroyContext(display,context);eglTerminate(display);
}
int main() { Numerics(); MappedBenchmark(); }
@@ -1,410 +0,0 @@
// 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 <numeric>
#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, const char *uploadPath) {
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[3];
glGenTextures(3, 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);
glTexStorage2D(GL_TEXTURE_2D, 1, GL_RGBA16F, w, h);
glTexSubImage2D(GL_TEXTURE_2D, 0, 0, 0, w, h, 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);
GLint alignment = 0;
glGetIntegerv(GL_SHADER_STORAGE_BUFFER_OFFSET_ALIGNMENT, &alignment);
Check(alignment > 0, "SSBO offset alignment");
const int rowBytes = w * 16;
const int stripeRows = alignment / std::gcd(rowBytes, alignment);
// Artificially small block limit forces aligned range changes and a partial
// final stripe without needing a huge texture on the diagnostic device.
for (int row = 0; row < h; row += stripeRows) {
const int rows = std::min(stripeRows, h - row);
glUniform1i(glGetUniformLocation(program, "uRowOffset"), row);
glUniform1i(glGetUniformLocation(program, "uRows"), rows);
glBindBufferRange(GL_SHADER_STORAGE_BUFFER, 0, pbo, row * rowBytes,
rows * rowBytes);
glDispatchCompute((w + 7) / 8, (rows + 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 ranges preserve all samples including stripe 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");
std::ifstream uploadFile(uploadPath);
std::string uploadSource((std::istreambuf_iterator<char>(uploadFile)), {});
Check(!uploadSource.empty(), "production upload shader");
const char *uploadText = uploadSource.c_str();
GLuint uploadShader = glCreateShader(GL_COMPUTE_SHADER);
glShaderSource(uploadShader, 1, &uploadText, nullptr);
glCompileShader(uploadShader);
glGetShaderiv(uploadShader, GL_COMPILE_STATUS, &ok);
Check(ok, "upload compute compile");
GLuint uploadProgram = glCreateProgram();
glAttachShader(uploadProgram, uploadShader);
glLinkProgram(uploadProgram);
glGetProgramiv(uploadProgram, GL_LINK_STATUS, &ok);
Check(ok, "upload compute link");
glUseProgram(uploadProgram);
glBindImageTexture(0, textures[2], 0, GL_FALSE, 0, GL_WRITE_ONLY, GL_RGBA16F);
glUniform2i(glGetUniformLocation(uploadProgram, "uSize"), w, h);
for (int row = 0; row < h; row += stripeRows) {
const int rows = std::min(stripeRows, h - row);
glUniform1i(glGetUniformLocation(uploadProgram, "uRowOffset"), row);
glUniform1i(glGetUniformLocation(uploadProgram, "uRows"), rows);
glBindBufferRange(GL_SHADER_STORAGE_BUFFER, 0, pbo, row * rowBytes, rows * rowBytes);
glDispatchCompute((w + 7) / 8, (rows + 7) / 8, 1);
}
glMemoryBarrier(GL_TEXTURE_FETCH_BARRIER_BIT | GL_FRAMEBUFFER_BARRIER_BIT |
GL_SHADER_IMAGE_ACCESS_BARRIER_BIT);
glBindImageTexture(0, 0, 0, GL_FALSE, 0, GL_WRITE_ONLY, GL_RGBA16F);
glBindBufferBase(GL_SHADER_STORAGE_BUFFER, 0, 0);
// Exercise Filmic's new padded linear-color branch with the production
// shader immediately after image upload, without an intervening CPU wait/readback.
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");
GLuint boxTexture;
glGenTextures(1, &boxTexture);
for (int scale : {2, 4}) {
const int lw = 128 / scale, lh = 32 / scale;
glBindTexture(GL_TEXTURE_2D, boxTexture);
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA16F, lw, lh, 0, GL_RGBA, GL_FLOAT,
nullptr);
glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, boxTexture, 0);
Check(glCheckFramebufferStatus(GL_FRAMEBUFFER) == GL_FRAMEBUFFER_COMPLETE, "box framebuffer");
glBindTexture(GL_TEXTURE_2D, textures[2]);
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 += result[(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");
}
}
glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, textures[2], 0);
std::vector<float> uploaded(n * 4);
glReadPixels(0, 0, w, h, GL_RGBA, GL_FLOAT, uploaded.data());
Check(uploaded == result, "SSBO image upload matches PBO float upload exactly");
glDeleteTextures(1, &boxTexture);
glDeleteProgram(uploadProgram);
glDeleteShader(uploadShader);
glDeleteProgram(boxProgram);
glDeleteShader(vs);
glDeleteShader(fs);
printf("GPU padded linear color box passed\n");
Check(glGetError() == GL_NO_ERROR, "GPU errors");
glDeleteTextures(3, 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 == 5, "fixture output directory, float, box and upload shaders");
Gpu(argv[2], argv[3], argv[4]);
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");
}