feat: rawmax 2.0 (5) - fix

This commit is contained in:
zhoubinjia committed 2026-08-07 15:13:37 +08:00
1 parent 270b2840c6
commit a2700c2d9e
27 files changed
+8487 -3806

No files matched your search

+2 -1
View File
@@ -13,7 +13,7 @@ set(
)
set(
MGC_DENOISE_CAPSULE_SHA256
"ab17d95f5f07abec50a21af8534a3866777bcd043e29324e36f367d21c288879"
"312c3b2e5ccee00604034fb1e8161dba65ace86197eb6c9fe75556d700505432"
)
if(NOT EXISTS "${MGC_DENOISE_CAPSULE}")
message(
@@ -127,6 +127,7 @@ add_library(my-native-lib SHARED
dcp_parser.cpp
mgc_denoise_static/mgc_denoise_static.cpp
mgc_denoise_static/mgc_full_resolution_denoise_jni.cpp
mgc_denoise_static/mgc_spatial_strength_jni.cpp
"${MGC_DENOISE_ASM}"
${LIBRAW_SOURCES}
${ADOBE_DNG_SOURCES}
@@ -7,11 +7,13 @@
#include <algorithm>
#include <atomic>
#include <cmath>
#include <cstring>
#include <vector>
namespace photon::mgc_denoise {
namespace {
constexpr char kTag[] = "MgcDenoiseStatic";
constexpr char kTag[] = "PLog_MgcDenoiseStatic";
struct HalideType {
uint8_t code;
@@ -85,6 +87,57 @@ using YuvToRgbFn = int (*)(
void*,
HalideBuffer*,
HalideBuffer*);
using DownsampleRawFn = int (*)(
void*,
HalideBuffer*,
int32_t,
HalideBuffer*,
float,
float,
HalideBuffer*);
using DownsampleRgbFn = int (*)(
void*,
HalideBuffer*,
HalideBuffer*,
float,
float,
HalideBuffer*);
using ComputeBayerNoiseModelFn = int (*)(
void*,
int32_t,
HalideBuffer*,
HalideBuffer*,
HalideBuffer*,
float,
HalideBuffer*,
HalideBuffer*,
HalideBuffer*,
HalideBuffer*,
HalideBuffer*,
HalideBuffer*,
HalideBuffer*,
HalideBuffer*,
HalideBuffer*);
using ComputeRgbNoiseModelFn = int (*)(
void*,
int32_t,
HalideBuffer*,
HalideBuffer*,
HalideBuffer*,
float,
HalideBuffer*,
HalideBuffer*,
HalideBuffer*,
HalideBuffer*,
HalideBuffer*,
HalideBuffer*,
HalideBuffer*,
HalideBuffer*,
HalideBuffer*);
using DownsampleRgbModeFn = int (*)(
int,
HalideBuffer*,
HalideBuffer*);
extern "C" int photon_mgc_compute_denoise_strength_maps_u16(
void*,
@@ -130,6 +183,61 @@ extern "C" int photon_mgc_yuv_to_rgb_s16(
void*,
HalideBuffer*,
HalideBuffer*);
extern "C" int photon_mgc_downsample_raw_f16_to_float_tile_size_16(
void*,
HalideBuffer*,
int32_t,
HalideBuffer*,
float,
float,
HalideBuffer*);
extern "C" int photon_mgc_downsample_rgb_f16_to_float_tile_size_16(
void*,
HalideBuffer*,
HalideBuffer*,
float,
float,
HalideBuffer*);
extern "C" int photon_mgc_compute_bayer_noise_model_f32_tile_size_16(
void*,
int32_t,
HalideBuffer*,
HalideBuffer*,
HalideBuffer*,
float,
HalideBuffer*,
HalideBuffer*,
HalideBuffer*,
HalideBuffer*,
HalideBuffer*,
HalideBuffer*,
HalideBuffer*,
HalideBuffer*,
HalideBuffer*);
extern "C" int photon_mgc_compute_rgb_noise_model_f32_tile_size_16(
void*,
int32_t,
HalideBuffer*,
HalideBuffer*,
HalideBuffer*,
float,
HalideBuffer*,
HalideBuffer*,
HalideBuffer*,
HalideBuffer*,
HalideBuffer*,
HalideBuffer*,
HalideBuffer*,
HalideBuffer*,
HalideBuffer*);
extern "C" int photon_mgc_downsample_rgb_mode_0(
int,
HalideBuffer*,
HalideBuffer*);
extern "C" int photon_mgc_downsample_rgb_mode_1(
int,
HalideBuffer*,
HalideBuffer*);
void* HalideMalloc(void*, size_t size) {
void* result = nullptr;
@@ -405,6 +513,26 @@ photon_mgc_halide_do_par_for(
return HalideDoParFor(user_context, task, minimum, size, closure);
}
extern "C" __attribute__((visibility("hidden"))) int
photon_mgc_downsample_rgb_dispatch(
int mode,
HalideBuffer* input,
HalideBuffer* output,
int argument) {
DownsampleRgbModeFn function = nullptr;
if (mode == 0) {
function = &photon_mgc_downsample_rgb_mode_0;
} else if (mode == 1) {
function = &photon_mgc_downsample_rgb_mode_1;
} else {
return -1;
}
// The original dispatcher at 0x5dae16c deliberately discards the
// specialized function's return value for modes 0/1.
function(argument, input, output);
return 0;
}
#define PHOTON_MGC_DEFINE_HALIDE_ERROR(address) \
extern "C" __attribute__((visibility("hidden"))) uintptr_t \
photon_mgc_halide_error_##address( \
@@ -430,7 +558,6 @@ photon_mgc_halide_do_par_for(
PHOTON_MGC_DEFINE_HALIDE_ERROR(5ef604c)
PHOTON_MGC_DEFINE_HALIDE_ERROR(5ef6140)
PHOTON_MGC_DEFINE_HALIDE_ERROR(5ef61ac)
PHOTON_MGC_DEFINE_HALIDE_ERROR(5ef6294)
PHOTON_MGC_DEFINE_HALIDE_ERROR(5ef636c)
PHOTON_MGC_DEFINE_HALIDE_ERROR(5ef63f8)
PHOTON_MGC_DEFINE_HALIDE_ERROR(5ef64dc)
@@ -445,9 +572,46 @@ PHOTON_MGC_DEFINE_HALIDE_ERROR(5ef6bd8)
PHOTON_MGC_DEFINE_HALIDE_ERROR(5ef6c38)
PHOTON_MGC_DEFINE_HALIDE_ERROR(5ef6cd0)
PHOTON_MGC_DEFINE_HALIDE_ERROR(5ef7030)
PHOTON_MGC_DEFINE_HALIDE_ERROR(20239a0)
PHOTON_MGC_DEFINE_HALIDE_ERROR(256406c)
PHOTON_MGC_DEFINE_HALIDE_ERROR(5dac60c)
PHOTON_MGC_DEFINE_HALIDE_ERROR(5dac85c)
PHOTON_MGC_DEFINE_HALIDE_ERROR(5daca0c)
PHOTON_MGC_DEFINE_HALIDE_ERROR(5dae204)
PHOTON_MGC_DEFINE_HALIDE_ERROR(5dae37c)
PHOTON_MGC_DEFINE_HALIDE_ERROR(5dae540)
PHOTON_MGC_DEFINE_HALIDE_ERROR(5dae6b8)
PHOTON_MGC_DEFINE_HALIDE_ERROR(5f57538)
PHOTON_MGC_DEFINE_HALIDE_ERROR(5f59544)
PHOTON_MGC_DEFINE_HALIDE_ERROR(5f595a0)
#undef PHOTON_MGC_DEFINE_HALIDE_ERROR
extern "C" __attribute__((visibility("hidden"))) uintptr_t
photon_mgc_halide_error_5ef6294(
uintptr_t user_context,
uintptr_t buffer_name,
uintptr_t expected_type,
uintptr_t actual_type,
uintptr_t,
uintptr_t,
uintptr_t,
uintptr_t) {
(void)user_context;
const char* name = reinterpret_cast<const char*>(buffer_name);
__android_log_print(
ANDROID_LOG_ERROR,
kTag,
"MGC Halide buffer type mismatch name=%s expected=0x%zx "
"actual=0x%zx",
name != nullptr ? name : "<null>",
static_cast<size_t>(expected_type),
static_cast<size_t>(actual_type));
// Original MGC helper 0x5ef6294 returns Halide's
// halide_error_code_bad_type (-3).
return static_cast<uintptr_t>(static_cast<intptr_t>(-3));
}
bool BuildNoiseBuffers(
float read_noise,
float shot_noise,
@@ -641,6 +805,251 @@ int ComputeStrengthMap(
sample_rate_y);
}
int ComputeSpatialStrengthMap(
SpatialStrengthInputLayout layout,
const uint16_t* fused_f16,
int width,
int height,
int cfa_pattern,
const float* alignment,
int alignment_width,
int alignment_height,
const uint8_t* rejection,
int rejection_width,
int rejection_height,
int frame_count,
const float* input_read_noise,
const float* input_shot_noise,
const float* frame_weights,
const float* kernel_sigmas,
float rejected_denoise_multiplier,
uint16_t* output_strength_q8,
SpatialStrengthResult* diagnostics) {
if (fused_f16 == nullptr || alignment == nullptr ||
rejection == nullptr || input_read_noise == nullptr ||
input_shot_noise == nullptr || frame_weights == nullptr ||
kernel_sigmas == nullptr || output_strength_q8 == nullptr ||
diagnostics == nullptr || width <= 0 || height <= 0 ||
alignment_width <= 0 || alignment_height <= 0 ||
rejection_width <= 0 || rejection_height <= 0 ||
frame_count <= 1 || cfa_pattern < 0 || cfa_pattern > 3 ||
!std::isfinite(rejected_denoise_multiplier)) {
return -1;
}
const bool is_bayer = layout == SpatialStrengthInputLayout::Bayer;
if (!is_bayer && layout != SpatialStrengthInputLayout::Rgba) {
return -1;
}
const int expected_alignment_width =
(width + (is_bayer ? 7 : 15)) / (is_bayer ? 8 : 16);
const int expected_alignment_height =
(height + (is_bayer ? 7 : 15)) / (is_bayer ? 8 : 16);
if (alignment_width != expected_alignment_width ||
alignment_height != expected_alignment_height ||
rejection_width != (width + 3) / 4 ||
rejection_height != (height + 3) / 4) {
return -1;
}
const size_t pixel_count =
static_cast<size_t>(width) * static_cast<size_t>(height);
std::vector<uint16_t> rgb_planar;
const uint16_t* downsample_input = fused_f16;
if (!is_bayer) {
rgb_planar.resize(pixel_count * 3);
for (size_t pixel = 0; pixel < pixel_count; ++pixel) {
for (int channel = 0; channel < 3; ++channel) {
rgb_planar[
static_cast<size_t>(channel) * pixel_count + pixel] =
fused_f16[pixel * 4 + channel];
}
}
downsample_input = rgb_planar.data();
}
const int signal_count = alignment_width * alignment_height;
std::vector<float> signal(static_cast<size_t>(signal_count) * 3);
float black[4] = {};
const HalideDimension input_dimensions_bayer[] = {
{0, width, 1, 0},
{0, height, width, 0},
};
const HalideDimension input_dimensions_rgb[] = {
{0, width, 1, 0},
{0, height, width, 0},
{0, 3, static_cast<int32_t>(pixel_count), 0},
};
const HalideDimension black_dimensions[] = {
{0, is_bayer ? 4 : 3, 1, 0},
};
const HalideDimension signal_dimensions[] = {
{0, alignment_width, 1, 0},
{0, alignment_height, alignment_width, 0},
{0, 3, signal_count, 0},
};
HalideBuffer input_buffer = MakeBuffer(
const_cast<uint16_t*>(downsample_input),
{2, 16, 1},
is_bayer ? 2 : 3,
is_bayer ? input_dimensions_bayer : input_dimensions_rgb);
HalideBuffer black_buffer = MakeBuffer(
black,
{2, 32, 1},
1,
black_dimensions);
HalideBuffer signal_buffer = MakeBuffer(
signal.data(),
{2, 32, 1},
3,
signal_dimensions);
int result = 0;
if (is_bayer) {
const auto function = reinterpret_cast<DownsampleRawFn>(
&photon_mgc_downsample_raw_f16_to_float_tile_size_16);
result = function(
nullptr,
&input_buffer,
cfa_pattern,
&black_buffer,
1.0f,
1.0f,
&signal_buffer);
} else {
const auto function = reinterpret_cast<DownsampleRgbFn>(
&photon_mgc_downsample_rgb_f16_to_float_tile_size_16);
result = function(
nullptr,
&input_buffer,
&black_buffer,
1.0f,
1.0f,
&signal_buffer);
}
if (result != 0) return result;
const int alignment_plane = alignment_width * alignment_height;
const int rejection_plane = rejection_width * rejection_height;
const HalideDimension alignment_dimensions[] = {
{0, alignment_width, 1, 0},
{0, alignment_height, alignment_width, 0},
{0, frame_count, alignment_plane, 0},
{0, 2, alignment_plane * frame_count, 0},
};
const HalideDimension temporal_dimensions[] = {
{0, frame_count, 1, 0},
};
const HalideDimension noise_dimensions[] = {
{0, frame_count, 1, 0},
{0, 3, frame_count, 0},
};
const HalideDimension rejection_dimensions[] = {
{0, rejection_width, 1, 0},
{0, rejection_height, rejection_width, 0},
{0, frame_count, rejection_plane, 0},
};
const HalideDimension vector_dimensions[] = {
{0, 3, 1, 0},
};
const HalideDimension strength_dimensions[] = {
{0, rejection_width, 1, 0},
{0, rejection_height, rejection_width, 0},
};
HalideBuffer alignment_buffer = MakeBuffer(
const_cast<float*>(alignment),
{2, 32, 1},
4,
alignment_dimensions);
HalideBuffer kernel_buffer = MakeBuffer(
const_cast<float*>(kernel_sigmas),
{2, 32, 1},
1,
temporal_dimensions);
HalideBuffer read_buffer = MakeBuffer(
const_cast<float*>(input_read_noise),
{2, 32, 1},
2,
noise_dimensions);
HalideBuffer shot_buffer = MakeBuffer(
const_cast<float*>(input_shot_noise),
{2, 32, 1},
2,
noise_dimensions);
HalideBuffer frame_weight_buffer = MakeBuffer(
const_cast<float*>(frame_weights),
{2, 32, 1},
1,
temporal_dimensions);
HalideBuffer rejection_buffer = MakeBuffer(
const_cast<uint8_t*>(rejection),
{1, 8, 1},
3,
rejection_dimensions);
HalideBuffer output_noise_0_buffer = MakeBuffer(
diagnostics->output_noise_model_0,
{2, 32, 1},
1,
vector_dimensions);
HalideBuffer output_noise_1_buffer = MakeBuffer(
diagnostics->output_noise_model_1,
{2, 32, 1},
1,
vector_dimensions);
HalideBuffer output_diag_0_buffer = MakeBuffer(
diagnostics->output_weights_sum_total_diag_0,
{2, 32, 1},
1,
vector_dimensions);
HalideBuffer output_diag_1_buffer = MakeBuffer(
diagnostics->output_weights_sum_total_diag_1,
{2, 32, 1},
1,
vector_dimensions);
HalideBuffer output_strength_buffer = MakeBuffer(
output_strength_q8,
{1, 16, 1},
2,
strength_dimensions);
if (is_bayer) {
const auto function = reinterpret_cast<ComputeBayerNoiseModelFn>(
&photon_mgc_compute_bayer_noise_model_f32_tile_size_16);
return function(
nullptr,
cfa_pattern,
&alignment_buffer,
&signal_buffer,
&kernel_buffer,
rejected_denoise_multiplier,
&read_buffer,
&shot_buffer,
&frame_weight_buffer,
&rejection_buffer,
&output_noise_0_buffer,
&output_noise_1_buffer,
&output_diag_0_buffer,
&output_diag_1_buffer,
&output_strength_buffer);
}
const auto function = reinterpret_cast<ComputeRgbNoiseModelFn>(
&photon_mgc_compute_rgb_noise_model_f32_tile_size_16);
return function(
nullptr,
cfa_pattern,
&alignment_buffer,
&signal_buffer,
&kernel_buffer,
rejected_denoise_multiplier,
&read_buffer,
&shot_buffer,
&frame_weight_buffer,
&rejection_buffer,
&output_noise_0_buffer,
&output_noise_1_buffer,
&output_diag_0_buffer,
&output_diag_1_buffer,
&output_strength_buffer);
}
int RunRgbRawToYuv(
const uint16_t* input,
int width,
@@ -23,6 +23,18 @@ struct ChromaDenoiseNoiseBuffers {
uint8_t outlier_threshold[8] = {};
};
enum class SpatialStrengthInputLayout {
Bayer = 0,
Rgba = 1,
};
struct SpatialStrengthResult {
float output_noise_model_0[3] = {};
float output_noise_model_1[3] = {};
float output_weights_sum_total_diag_0[3] = {};
float output_weights_sum_total_diag_1[3] = {};
};
/**
* Reproduces CreateLumaDenoiseNoiseBuffers for one luma noise channel.
* correlation is MGC's 128-bin normalized power correlation spectrum. A
@@ -69,6 +81,35 @@ int ComputeStrengthMap(
float sample_rate_y,
uint16_t* output);
/**
* Runs MGC's exact Spatial Compute*NoiseModelF32TileSize16 pipeline.
*
* fused_f16 is either one F16 Bayer plane or interleaved RGBA F16. Alignment
* is planar [x,y,frame,xy], rejection is [x,y,frame], and per-frame RGB noise
* coefficients are planar [frame,rgb]. Equal-exposure Spatial uses
* frame_weights=kernel_sigmas=1 and rejected_denoise_multiplier=-1.
*/
int ComputeSpatialStrengthMap(
SpatialStrengthInputLayout layout,
const uint16_t* fused_f16,
int width,
int height,
int cfa_pattern,
const float* alignment,
int alignment_width,
int alignment_height,
const uint8_t* rejection,
int rejection_width,
int rejection_height,
int frame_count,
const float* input_read_noise,
const float* input_shot_noise,
const float* frame_weights,
const float* kernel_sigmas,
float rejected_denoise_multiplier,
uint16_t* output_strength_q8,
SpatialStrengthResult* diagnostics);
/** Runs the statically linked RgbRawToYuv1xS16 with neutral corrections. */
int RunRgbRawToYuv(
const uint16_t* input,
@@ -46,30 +46,6 @@ uint16_t FloatToHalf(float value) {
return bits;
}
float BilinearGain(
const float* gain_map,
int gain_width,
int gain_height,
int channel,
float x,
float y) {
x = std::clamp(x, 0.0f, static_cast<float>(gain_width - 1));
y = std::clamp(y, 0.0f, static_cast<float>(gain_height - 1));
const int x0 = static_cast<int>(std::floor(x));
const int y0 = static_cast<int>(std::floor(y));
const int x1 = std::min(x0 + 1, gain_width - 1);
const int y1 = std::min(y0 + 1, gain_height - 1);
const float fx = x - static_cast<float>(x0);
const float fy = y - static_cast<float>(y0);
const auto value = [&](int px, int py) {
return gain_map[(py * gain_width + px) * 4 + channel];
};
const float top = value(x0, y0) + (value(x1, y0) - value(x0, y0)) * fx;
const float bottom =
value(x0, y1) + (value(x1, y1) - value(x0, y1)) * fx;
return std::max(top + (bottom - top) * fy, 0.0f);
}
bool CopyFive(JNIEnv* env, jfloatArray source, float output[5]) {
if (source == nullptr || env->GetArrayLength(source) != 5) return false;
env->GetFloatArrayRegion(source, 0, 5, output);
@@ -287,7 +263,11 @@ Java_com_hinnka_mycamera_raw_MgcFullResolutionDenoise_nativeDenoiseRgba16f(
jint lens_height,
jfloatArray normalized_rgb_shot_array,
jfloatArray normalized_rgb_read_array,
jfloatArray normalized_rgb_white_balance_array,
jfloatArray correlation_array,
jshortArray spatial_strength_q8_array,
jint spatial_strength_width,
jint spatial_strength_height,
jboolean luma_enabled,
jboolean chroma_enabled,
jfloatArray luma_strength_array,
@@ -311,6 +291,7 @@ Java_com_hinnka_mycamera_raw_MgcFullResolutionDenoise_nativeDenoiseRgba16f(
float normalized_rgb_shot[3] = {};
float normalized_rgb_read[3] = {};
float normalized_rgb_white_balance[3] = {};
float luma_strength[5] = {};
float luma_outlier[5] = {};
float luma_revert[5] = {};
@@ -318,6 +299,10 @@ Java_com_hinnka_mycamera_raw_MgcFullResolutionDenoise_nativeDenoiseRgba16f(
float chroma_outlier[5] = {};
if (!CopyThree(env, normalized_rgb_shot_array, normalized_rgb_shot) ||
!CopyThree(env, normalized_rgb_read_array, normalized_rgb_read) ||
!CopyThree(
env,
normalized_rgb_white_balance_array,
normalized_rgb_white_balance) ||
!CopyFive(env, luma_strength_array, luma_strength) ||
!CopyFive(env, luma_outlier_array, luma_outlier) ||
!CopyFive(env, luma_revert_array, luma_revert) ||
@@ -325,6 +310,12 @@ Java_com_hinnka_mycamera_raw_MgcFullResolutionDenoise_nativeDenoiseRgba16f(
!CopyFive(env, chroma_outlier_array, chroma_outlier)) {
return -1;
}
for (int channel = 0; channel < 3; ++channel) {
if (!std::isfinite(normalized_rgb_white_balance[channel]) ||
normalized_rgb_white_balance[channel] <= 0.0f) {
return -1;
}
}
float correlation[128];
std::fill_n(correlation, 128, 1.0f);
@@ -360,7 +351,10 @@ Java_com_hinnka_mycamera_raw_MgcFullResolutionDenoise_nativeDenoiseRgba16f(
static_cast<size_t>(y) * padded_width + x;
for (int channel = 0; channel < 3; ++channel) {
const float normalized = std::clamp(
std::max(
HalfToFloat(rgba[source_index + channel]),
0.0f) *
normalized_rgb_white_balance[channel],
0.0f,
1.0f);
rgb_input[
@@ -374,6 +368,76 @@ Java_com_hinnka_mycamera_raw_MgcFullResolutionDenoise_nativeDenoiseRgba16f(
std::vector<uint16_t> base_strength(strength_count, 256);
std::vector<uint16_t> strength(strength_count * 3, 256);
if (spatial_strength_q8_array != nullptr) {
const int expected_full_strength_width =
(full_width + 3) / 4;
const int expected_full_strength_height =
(full_height + 3) / 4;
if (spatial_strength_width != expected_full_strength_width ||
spatial_strength_height != expected_full_strength_height ||
env->GetArrayLength(spatial_strength_q8_array) !=
spatial_strength_width * spatial_strength_height) {
return -1;
}
std::vector<uint16_t> spatial_strength(
static_cast<size_t>(spatial_strength_width) *
spatial_strength_height);
env->GetShortArrayRegion(
spatial_strength_q8_array,
0,
static_cast<jsize>(spatial_strength.size()),
reinterpret_cast<jshort*>(spatial_strength.data()));
if (env->ExceptionCheck()) return -1;
for (int y = 0; y < strength_height; ++y) {
const int local_pixel_y = std::min(y * 4, height - 1);
const int source_y = std::clamp(
(global_origin_y + local_pixel_y) / 4,
0,
spatial_strength_height - 1);
for (int x = 0; x < strength_width; ++x) {
const int local_pixel_x = std::min(x * 4, width - 1);
const int source_x = std::clamp(
(global_origin_x + local_pixel_x) / 4,
0,
spatial_strength_width - 1);
base_strength[
static_cast<size_t>(y) * strength_width + x] =
spatial_strength[
static_cast<size_t>(source_y) *
spatial_strength_width +
source_x];
}
}
} else if (spatial_strength_width != 0 ||
spatial_strength_height != 0) {
return -1;
}
uint16_t base_strength_min = std::numeric_limits<uint16_t>::max();
uint16_t base_strength_max = 0;
uint64_t base_strength_sum = 0;
for (const uint16_t value : base_strength) {
base_strength_min = std::min(base_strength_min, value);
base_strength_max = std::max(base_strength_max, value);
base_strength_sum += value;
}
__android_log_print(
ANDROID_LOG_INFO,
kLogTag,
"MGC denoise base Spatial strengthQ8=%u..%u/%.3f "
"source=%s logical=%dx%d padded=%dx%d origin=(%d,%d)",
base_strength_min,
base_strength_max,
base_strength.empty()
? 0.0
: static_cast<double>(base_strength_sum) /
static_cast<double>(base_strength.size()),
spatial_strength_q8_array == nullptr ? "identity" : "spatial-aot",
spatial_strength_width,
spatial_strength_height,
strength_width,
strength_height,
global_origin_x,
global_origin_y);
if (lens_shading != nullptr && lens_width > 0 && lens_height > 0) {
const jsize lens_count = env->GetArrayLength(lens_shading);
if (lens_count != lens_width * lens_height * 4) return -1;
@@ -385,66 +449,36 @@ Java_com_hinnka_mycamera_raw_MgcFullResolutionDenoise_nativeDenoiseRgba16f(
lens_count,
lens.data());
if (env->ExceptionCheck()) return -1;
std::vector<float> local_gain(strength_count * 4);
const int valid_strength_width = std::max(1, (width + 3) / 4);
const int valid_strength_height = std::max(1, (height + 3) / 4);
for (int y = 0; y < strength_height; ++y) {
const int valid_y = std::min(y, valid_strength_height - 1);
const float local_y = valid_strength_height > 1
? static_cast<float>(valid_y) *
static_cast<float>(height - 1) /
static_cast<float>(valid_strength_height - 1)
: 0.0f;
const float global_y = std::clamp(
static_cast<float>(global_origin_y) + local_y,
0.0f,
static_cast<float>(full_height - 1));
const float gain_y = full_height > 1
? global_y * static_cast<float>(lens_height - 1) /
static_cast<float>(full_height - 1)
: 0.0f;
for (int x = 0; x < strength_width; ++x) {
const int valid_x = std::min(x, valid_strength_width - 1);
const float local_x = valid_strength_width > 1
? static_cast<float>(valid_x) *
static_cast<float>(width - 1) /
static_cast<float>(valid_strength_width - 1)
: 0.0f;
const float global_x = std::clamp(
static_cast<float>(global_origin_x) + local_x,
0.0f,
static_cast<float>(full_width - 1));
const float gain_x = full_width > 1
? global_x * static_cast<float>(lens_width - 1) /
static_cast<float>(full_width - 1)
: 0.0f;
const size_t index =
(static_cast<size_t>(y) * strength_width + x) * 4;
for (int channel = 0; channel < 4; ++channel) {
local_gain[index + channel] = BilinearGain(
lens.data(),
lens_width,
lens_height,
channel,
gain_x,
gain_y);
}
}
}
const float sample_rate_x = strength_width > 1
? static_cast<float>(lens_width - 1) /
static_cast<float>(strength_width - 1)
: 1.0f;
const float sample_rate_y = strength_height > 1
? static_cast<float>(lens_height - 1) /
static_cast<float>(strength_height - 1)
: 1.0f;
const int strength_result =
photon::mgc_denoise::ComputeStrengthMap(
base_strength.data(),
strength_width,
strength_height,
local_gain.data(),
strength_width,
strength_height,
1.0f,
1.0f,
lens.data(),
lens_width,
lens_height,
sample_rate_x,
sample_rate_y,
strength.data());
if (strength_result != 0) {
return LogStageFailure("strength_map", strength_result);
}
} else {
for (int channel = 0; channel < 3; ++channel) {
std::copy_n(
base_strength.data(),
strength_count,
strength.data() +
static_cast<size_t>(channel) * strength_count);
}
}
const float white = static_cast<float>(kWhiteLevel);
@@ -470,13 +504,17 @@ Java_com_hinnka_mycamera_raw_MgcFullResolutionDenoise_nativeDenoiseRgba16f(
const float matrix_value =
rgb_to_yuv[output_channel * 3 + input_channel];
const float matrix_squared = matrix_value * matrix_value;
const float channel_gain =
normalized_rgb_white_balance[input_channel];
yuv_read[output_channel] +=
matrix_squared *
std::max(normalized_rgb_read[input_channel], 0.0f) *
channel_gain * channel_gain *
white * white;
yuv_shot[output_channel] +=
matrix_squared *
std::max(normalized_rgb_shot[input_channel], 0.0f) *
channel_gain *
white;
}
}
@@ -591,7 +629,8 @@ Java_com_hinnka_mycamera_raw_MgcFullResolutionDenoise_nativeDenoiseRgba16f(
planar_b[
static_cast<size_t>(channel) * pixel_count +
source_index]) /
static_cast<float>(kWhiteLevel);
static_cast<float>(kWhiteLevel) /
normalized_rgb_white_balance[channel];
rgba[destination_index + channel] =
FloatToHalf(normalized);
}
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,205 @@
#include "mgc_denoise_static.h"
#include <android/log.h>
#include <jni.h>
#include <algorithm>
#include <cstdint>
#include <limits>
#include <new>
#include <vector>
namespace {
constexpr char kTag[] = "PLog_MgcSpatialStrength";
bool CopyFloatArray(
JNIEnv* env,
jfloatArray source,
int expected,
std::vector<float>* output) {
if (source == nullptr || expected <= 0 ||
env->GetArrayLength(source) != expected) {
return false;
}
output->resize(static_cast<size_t>(expected));
env->GetFloatArrayRegion(source, 0, expected, output->data());
return !env->ExceptionCheck();
}
} // namespace
extern "C" JNIEXPORT jint JNICALL
Java_com_hinnka_mycamera_processor_MgcSpatialStrengthMapGenerator_nativeCompute(
JNIEnv* env,
jobject,
jint layout,
jobject fused_f16_buffer,
jint width,
jint height,
jint cfa_pattern,
jobject alignment_buffer,
jint alignment_width,
jint alignment_height,
jobject rejection_buffer,
jint rejection_width,
jint rejection_height,
jint frame_count,
jfloatArray input_read_noise_array,
jfloatArray input_shot_noise_array,
jfloatArray frame_weights_array,
jfloatArray kernel_sigmas_array,
jfloat rejected_denoise_multiplier,
jshortArray output_strength_array) {
if (fused_f16_buffer == nullptr || alignment_buffer == nullptr ||
rejection_buffer == nullptr || output_strength_array == nullptr ||
width <= 0 || height <= 0 || alignment_width <= 0 ||
alignment_height <= 0 || rejection_width <= 0 ||
rejection_height <= 0 || frame_count <= 1) {
return -1;
}
auto* fused_f16 = static_cast<uint16_t*>(
env->GetDirectBufferAddress(fused_f16_buffer));
auto* alignment = static_cast<float*>(
env->GetDirectBufferAddress(alignment_buffer));
auto* rejection = static_cast<uint8_t*>(
env->GetDirectBufferAddress(rejection_buffer));
if (fused_f16 == nullptr || alignment == nullptr || rejection == nullptr) {
return -1;
}
const int64_t fused_samples =
static_cast<int64_t>(width) * height * (layout == 0 ? 1 : 4);
const int64_t alignment_values =
static_cast<int64_t>(alignment_width) * alignment_height *
frame_count * 2;
const int64_t rejection_values =
static_cast<int64_t>(rejection_width) * rejection_height *
frame_count;
const int64_t output_values =
static_cast<int64_t>(rejection_width) * rejection_height;
if (env->GetDirectBufferCapacity(fused_f16_buffer) <
fused_samples * static_cast<int64_t>(sizeof(uint16_t)) ||
env->GetDirectBufferCapacity(alignment_buffer) <
alignment_values * static_cast<int64_t>(sizeof(float)) ||
env->GetDirectBufferCapacity(rejection_buffer) < rejection_values ||
env->GetArrayLength(output_strength_array) != output_values) {
return -1;
}
try {
std::vector<float> input_read_noise;
std::vector<float> input_shot_noise;
std::vector<float> frame_weights;
std::vector<float> kernel_sigmas;
if (!CopyFloatArray(
env,
input_read_noise_array,
frame_count * 3,
&input_read_noise) ||
!CopyFloatArray(
env,
input_shot_noise_array,
frame_count * 3,
&input_shot_noise) ||
!CopyFloatArray(
env,
frame_weights_array,
frame_count,
&frame_weights) ||
!CopyFloatArray(
env,
kernel_sigmas_array,
frame_count,
&kernel_sigmas)) {
return -1;
}
std::vector<uint16_t> output(static_cast<size_t>(output_values));
photon::mgc_denoise::SpatialStrengthResult diagnostics;
const int result = photon::mgc_denoise::ComputeSpatialStrengthMap(
layout == 0
? photon::mgc_denoise::SpatialStrengthInputLayout::Bayer
: photon::mgc_denoise::SpatialStrengthInputLayout::Rgba,
fused_f16,
width,
height,
cfa_pattern,
alignment,
alignment_width,
alignment_height,
rejection,
rejection_width,
rejection_height,
frame_count,
input_read_noise.data(),
input_shot_noise.data(),
frame_weights.data(),
kernel_sigmas.data(),
rejected_denoise_multiplier,
output.data(),
&diagnostics);
if (result != 0) {
__android_log_print(
ANDROID_LOG_ERROR,
kTag,
"MGC Spatial strength AOT failed result=%d layout=%d "
"image=%dx%d alignment=%dx%dx%d rejection=%dx%dx%d",
result,
layout,
width,
height,
alignment_width,
alignment_height,
frame_count,
rejection_width,
rejection_height,
frame_count);
return result;
}
uint16_t minimum = std::numeric_limits<uint16_t>::max();
uint16_t maximum = 0;
uint64_t sum = 0;
for (const uint16_t value : output) {
minimum = std::min(minimum, value);
maximum = std::max(maximum, value);
sum += value;
}
env->SetShortArrayRegion(
output_strength_array,
0,
static_cast<jsize>(output.size()),
reinterpret_cast<const jshort*>(output.data()));
if (env->ExceptionCheck()) return -1;
__android_log_print(
ANDROID_LOG_INFO,
kTag,
"MGC Spatial strength complete layout=%s size=%dx%d frames=%d "
"q8=%u..%u/%.3f noise0=[%.6g,%.6g,%.6g] "
"noise1=[%.6g,%.6g,%.6g] diag0=[%.6g,%.6g,%.6g] "
"diag1=[%.6g,%.6g,%.6g]",
layout == 0 ? "BAYER" : "RGB",
rejection_width,
rejection_height,
frame_count,
minimum,
maximum,
output.empty()
? 0.0
: static_cast<double>(sum) /
static_cast<double>(output.size()),
diagnostics.output_noise_model_0[0],
diagnostics.output_noise_model_0[1],
diagnostics.output_noise_model_0[2],
diagnostics.output_noise_model_1[0],
diagnostics.output_noise_model_1[1],
diagnostics.output_noise_model_1[2],
diagnostics.output_weights_sum_total_diag_0[0],
diagnostics.output_weights_sum_total_diag_0[1],
diagnostics.output_weights_sum_total_diag_0[2],
diagnostics.output_weights_sum_total_diag_1[0],
diagnostics.output_weights_sum_total_diag_1[1],
diagnostics.output_weights_sum_total_diag_1[2]);
return 0;
} catch (const std::bad_alloc&) {
return -2;
}
}
@@ -3,6 +3,12 @@ package com.hinnka.mycamera.camera
import kotlin.math.roundToInt
object MultiFrameConfig {
/**
* Controls the post-Spatial MGC luma/chroma pass as one closed stage.
* Spatial fusion and Bayer/RGB materialization remain active when disabled.
*/
const val ENABLE_MGC_SPATIAL_DEFAULT_DENOISE = false
const val MIN_FRAME_COUNT = 3
const val MAX_FRAME_COUNT = 20
const val DEFAULT_FRAME_COUNT = 7
@@ -3062,6 +3062,7 @@ object GalleryManager {
frameCount = finalStackResult.mergedFrameCount,
mgcDenoiseCorrelation = finalStackResult.mgcDenoiseCorrelation,
mgcDenoiseNoiseScale = finalStackResult.mgcDenoiseNoiseScale,
mgcSpatialStrengthMap = finalStackResult.mgcSpatialStrengthMap,
)
val defaultDenoised = processor.materializeMgcSpatialLinearRgb(
context = context,
@@ -3075,16 +3076,19 @@ object GalleryManager {
sourcePixelsIncludeLensShadingCorrection =
finalStackResult.lensShadingCorrectionApplied,
applyLensShadingCorrection = applyRawLensShading,
mode = if (finalStackResult.mgcSpatialReferenceOnlyDiagnostic) {
MgcSpatialMaterializationMode.DIAGNOSTIC_BYPASS_DENOISE
} else {
mode = if (
MultiFrameConfig.ENABLE_MGC_SPATIAL_DEFAULT_DENOISE &&
!finalStackResult.mgcSpatialReferenceOnlyDiagnostic
) {
MgcSpatialMaterializationMode.DEFAULT_DENOISE
} else {
MgcSpatialMaterializationMode.BYPASS_DEFAULT_DENOISE
},
)
if (defaultDenoised == null) {
PLog.e(
TAG,
"RAW stack aborted: MGC Spatial default denoise did not produce " +
"RAW stack aborted: MGC Spatial materialization did not produce " +
"persistable LinearRaw pixels",
)
return@withContext
@@ -3101,6 +3105,7 @@ object GalleryManager {
frameCount = 1,
mgcDenoiseCorrelation = null,
mgcDenoiseNoiseScale = null,
mgcSpatialStrengthMap = null,
)
val outputRawBlackBorderCrop =
@@ -1,15 +1,11 @@
package com.hinnka.mycamera.processor
/**
* GLES transport of the Spatial Bayer shaders embedded in MGC 9.6.080 V24
* libgcastartup.so.
* GLES stages for the MGC-compatible Spatial Bayer pipeline.
*
* The guide, rejection, dilation and merge equations below retain the embedded GLSL equations and
* constants. The original program first extracts RAW16 into a half-resolution Bayer texture.
* Photon reads R16UI directly instead; [rawQuad] and [gainedRaw] are the only transport adaptation.
*
* Alignment and unblocker are compiled Halide in MGC. Their ports below follow the generated
* AArch64 kernels and the stage graph recovered from the same build.
*/
internal object GlesMgcRawSpatialShaders {
val guide = """
@@ -26,13 +22,8 @@ internal object GlesMgcRawSpatialShaders {
uniform sampler2D uNoiseEstimates;
uniform vec4 uNoiseTextureScaleBias;
uniform float uGreenClippingPoint;
uniform vec4 uCovarianceParameters1;
uniform vec4 uCovarianceParameters2;
uniform vec4 uCovRangeRgFactors;
uniform vec2 uCovRangeBFactor;
uniform float uForceReferenceColorRgb;
layout(location = 0) out vec4 oGuide;
layout(location = 1) out vec4 oCovariance;
out vec4 oGuide;
vec4 rawQuad(ivec2 quad) {
ivec2 p = clamp(quad * 2, ivec2(0), uRawSize - ivec2(2));
@@ -48,132 +39,6 @@ internal object GlesMgcRawSpatialShaders {
return raw * uGains + uBlackLevelsTimesGains;
}
vec4 rotateStructureTensor(vec4 s) {
float c0 = 0.5 * (s.x + s.y);
float c1 = 0.5 * (s.y - s.x);
return vec4(c0 + s.z, c0 - s.z, c1, s.w);
}
void analyzeStructureTensor(
vec4 s,
float greenVariance,
out vec2 eigenvector1,
out vec2 eigenvector2,
out float strength,
out float coherence
) {
float trace = s.x + s.y;
float diff = s.x - s.y;
float sqrtD = sqrt(max(diff * diff + 4.0 * s.z * s.z, 0.0));
float eigenvalue1 = (trace + sqrtD) * 0.5;
float eigenvalue2 = (trace - sqrtD) * 0.5;
eigenvector1 = vec2(1.0, 0.0);
eigenvector2 = vec2(0.0, 1.0);
if (abs(s.z) > 0.0001) {
eigenvector1 =
normalize(vec2(s.z, eigenvalue1 - s.x)) * -sign(s.z);
eigenvector2 = vec2(-eigenvector1.y, eigenvector1.x);
} else if (s.x < s.y) {
eigenvector1 = vec2(0.0, 1.0);
eigenvector2 = vec2(1.0, 0.0);
}
float singularValue1 = sqrt(eigenvalue1);
float singularValue2 = sqrt(max(eigenvalue2, 0.0));
float correction = s.w * greenVariance;
eigenvalue1 *= eigenvalue1 / (eigenvalue1 + correction);
strength = sqrt(eigenvalue1);
coherence = (singularValue1 - singularValue2) /
(singularValue1 + singularValue2 + 1.0e-6);
}
float gradientBlurring(float strength, float greenStdDev) {
float dominantFeature = max(strength, greenStdDev) -
uCovarianceParameters1.z;
return clamp(
1.0 - dominantFeature * uCovarianceParameters2.y,
0.0,
1.0
);
}
vec3 constructCovariance(
vec2 eigenvector1,
vec2 eigenvector2,
float strength,
float coherence,
float greenStdDev
) {
float blur = gradientBlurring(strength, greenStdDev);
float baseSigma = uCovarianceParameters1.w;
float shrinkedSigma = uCovarianceParameters1.x;
float stretchedSigma = uCovarianceParameters1.y;
float blurredSigma = uCovarianceParameters2.x;
float anisotropicShrinking = mix(
baseSigma,
shrinkedSigma,
min(coherence, strength * 5.0)
);
float singularValue1 = mix(anisotropicShrinking, blurredSigma, blur);
float singularValue2 = mix(
mix(baseSigma, stretchedSigma, coherence),
blurredSigma,
blur
);
mat2 rotation = mat2(eigenvector1, eigenvector2);
mat2 covariance = transpose(rotation) *
mat2(
singularValue1 * singularValue1, 0.0,
0.0, singularValue2 * singularValue2
) * rotation;
return vec3(covariance[0].x, covariance[1].y, covariance[0].y);
}
void accumulateGradient(float dx, float dy, inout vec4 s) {
s += vec4(dx * dx, dy * dy, dx * dy, 0.0);
}
vec4 structureTensor(float green0[9], float green1[9]) {
vec4 s = vec4(0.0);
for (int y = 0; y < 2; ++y) {
for (int x = 0; x < 2; ++x) {
float g00 = green0[y * 3 + x];
float g01 = green0[y * 3 + x + 1];
float g10 = green1[y * 3 + x];
float g11 = green1[y * 3 + x + 1];
float g20 = green0[(y + 1) * 3 + x];
float g21 = green0[(y + 1) * 3 + x + 1];
float g30 = green1[(y + 1) * 3 + x];
float g31 = green1[(y + 1) * 3 + x + 1];
float bdx;
float bdy;
float rdx;
float rdy;
if (uCfaPattern == 1 || uCfaPattern == 2) {
bdx = 0.5 * ((g11 - g01) + (g21 - g10));
bdy = 0.5 * ((g01 - g10) + (g11 - g21));
rdx = 0.5 * ((g21 - g10) + (g30 - g20));
rdy = 0.5 * ((g21 - g30) + (g10 - g20));
} else {
bdx = 0.5 * ((g11 - g00) + (g20 - g10));
bdy = 0.5 * ((g00 - g10) + (g11 - g20));
rdx = 0.5 * ((g21 - g11) + (g31 - g20));
rdy = 0.5 * ((g21 - g31) + (g11 - g20));
}
float g1dx = 0.5 * (g21 - g00);
float g1dy = 0.5 * (g01 - g20);
float g2dx = 0.5 * (g31 - g10);
float g2dy = 0.5 * (g11 - g30);
accumulateGradient(bdx, bdy, s);
accumulateGradient(rdx, rdy, s);
accumulateGradient(g1dx, g1dy, s);
accumulateGradient(g2dx, g2dy, s);
}
}
s /= 16.0;
s.w = 3.0 / 4.0;
return s;
}
float luma(vec3 rgb) {
return dot(rgb, vec3(0.25, 0.5, 0.25));
}
@@ -189,21 +54,11 @@ internal object GlesMgcRawSpatialShaders {
float m0Green = 0.0;
float m1Green = 0.0;
vec3 averageRgb = vec3(0.0);
float green0[9];
float green1[9];
float centerGreen = 0.0;
for (int y = -1; y <= 1; ++y) {
for (int x = -1; x <= 1; ++x) {
vec4 rggb = rawQuad(center * 2 + ivec2(x, y));
vec3 rgb = vec3(rggb.x, 0.5 * (rggb.y + rggb.z), rggb.w);
int index = (y + 1) * 3 + x + 1;
if (uCfaPattern == 2 || uCfaPattern == 3) {
green0[index] = rggb.z;
green1[index] = rggb.y;
} else {
green0[index] = rggb.y;
green1[index] = rggb.z;
}
averageRgb += rgb * kernelWeight(x) * kernelWeight(y);
if (x == 0 && y == 0) centerGreen = rgb.y;
m0Rgb += rgb;
@@ -237,43 +92,7 @@ internal object GlesMgcRawSpatialShaders {
if (centerGreen >= uGreenClippingPoint) {
referenceColor = vec3(10000.0);
}
vec4 tensor = rotateStructureTensor(structureTensor(green0, green1));
vec2 eigenvector1;
vec2 eigenvector2;
float strength;
float coherence;
analyzeStructureTensor(
tensor,
greenVarianceNoise,
eigenvector1,
eigenvector2,
strength,
coherence
);
float correctedGreenStdDev = sqrt(
greenVariance * greenVariance /
(greenVariance + greenVarianceNoise)
);
oGuide = vec4(referenceColor, referenceVariance * 1024.0);
vec3 covariance = constructCovariance(
eigenvector1,
eigenvector2,
strength,
coherence,
correctedGreenStdDev
);
vec2 packedRg = clamp(
covariance.xy * uCovRangeRgFactors.yw +
uCovRangeRgFactors.xz,
0.0,
1.0
);
float packedB = clamp(
covariance.z * uCovRangeBFactor.y + uCovRangeBFactor.x,
0.0,
1.0
);
oCovariance = vec4(packedRg, packedB, 0.0);
}
""".trimIndent()
@@ -360,7 +179,13 @@ internal object GlesMgcRawSpatialShaders {
robustnessBoost = uExtraMotionRobustnessBoost;
}
pixelVariance *= 2.0;
vec3 combinedNoise = referenceNoise + currentNoise;
// Noise estimates are transported through RGBA16F and can quantize to zero at the
// dark end. Keep the recovered equations defined without changing any positive
// estimate.
vec3 combinedNoise = max(
referenceNoise + currentNoise,
vec3(1.0e-8)
);
vec3 difference = current.rgb - reference.rgb;
vec3 differenceSquared = max(
difference * difference - combinedNoise,
@@ -593,7 +418,9 @@ internal object GlesMgcRawSpatialShaders {
weightSum += weight;
}
}
oFilteredRejection = weightedRejection / weightSum;
oFilteredRejection = weightSum > 0.0
? weightedRejection / weightSum
: centerRejection;
}
""".trimIndent()
@@ -662,6 +489,11 @@ internal object GlesMgcRawSpatialShaders {
}
""".trimIndent()
/**
* Bento UpdateLinearKernelMaskHalide. MGC invokes this once on the rejection-buffer slice
* selected by the accepted ultrashort index. It is not a temporal union of normal-frame
* rejection maps.
*/
val updateLinearKernelMask = """
#version 300 es
precision highp float;
@@ -820,116 +652,11 @@ internal object GlesMgcRawSpatialShaders {
}
""".trimIndent()
val merge = """
#version 300 es
precision highp float;
precision highp int;
precision highp usampler2D;
uniform highp usampler2D uRaw;
uniform sampler2D uFlow;
uniform sampler2D uFrameWeight;
uniform sampler2D uCovariance;
uniform ivec2 uRawSize;
uniform ivec2 uOutputSize;
uniform vec4 uFlowScaleOffset;
uniform vec4 uCovRangeRg;
uniform vec2 uCovRangeB;
uniform int uCfaPattern;
uniform vec4 uGains;
uniform vec4 uBlackLevelsTimesGains;
uniform int uUseFrameWeight;
layout(location = 0) out vec4 oColorAndRWeight;
layout(location = 1) out vec4 oGbWeights;
vec2 mirrorUv(vec2 uv) {
uv = mod(uv, 2.0);
return mix(uv, 2.0 - uv, greaterThan(uv, vec2(1.0)));
}
int canonicalChannel(ivec2 p) {
int phase = ((p.y & 1) << 1) + (p.x & 1);
if (uCfaPattern == 0) {
if (phase == 0) return 0;
if (phase == 1) return 1;
if (phase == 2) return 2;
return 3;
}
if (uCfaPattern == 1) {
if (phase == 0) return 1;
if (phase == 1) return 0;
if (phase == 2) return 3;
return 2;
}
if (uCfaPattern == 2) {
if (phase == 0) return 2;
if (phase == 1) return 3;
if (phase == 2) return 0;
return 1;
}
if (phase == 0) return 3;
if (phase == 1) return 2;
if (phase == 2) return 1;
return 0;
}
float gainedRaw(ivec2 p, int channel) {
p = clamp(p, ivec2(0), uRawSize - ivec2(1));
return float(texelFetch(uRaw, p, 0).r) * uGains[channel] +
uBlackLevelsTimesGains[channel];
}
float kernelWeight(vec2 pixelOffset, vec3 covariance) {
float distance =
pixelOffset.x * pixelOffset.x * covariance.x +
pixelOffset.y * pixelOffset.y * covariance.y +
pixelOffset.x * pixelOffset.y * covariance.z * 2.0;
return exp2(-0.5 * distance) + 0.00005;
}
void main() {
vec2 uv = gl_FragCoord.xy / vec2(uOutputSize);
vec2 flowUv = uv * uFlowScaleOffset.xy + uFlowScaleOffset.zw;
vec4 flow = texture(uFlow, flowUv);
float frameWeight = uUseFrameWeight != 0
? texture(uFrameWeight, uv).r
: 1.0;
vec2 sampleUv = mirrorUv(uv + flow.xy);
vec3 packedCovariance = texture(uCovariance, sampleUv).xyz;
vec3 covariance = vec3(
packedCovariance.xy * uCovRangeRg.yw + uCovRangeRg.xz,
packedCovariance.z * uCovRangeB.y + uCovRangeB.x
);
vec2 scaled = sampleUv * vec2(uRawSize);
ivec2 anchor = ivec2(scaled);
vec2 subpixelOffset = floor(scaled) + 0.5 - scaled;
vec3 intensities = vec3(0.0);
vec3 weights = vec3(0.0);
for (int y = -1; y <= 1; ++y) {
for (int x = -1; x <= 1; ++x) {
ivec2 p = anchor + ivec2(x, y);
int channel = canonicalChannel(p);
int rgbChannel = channel == 3 ? 2 : min(channel, 1);
float weight = kernelWeight(
subpixelOffset + vec2(x, y),
covariance
);
intensities[rgbChannel] += gainedRaw(p, channel) * weight;
weights[rgbChannel] += weight;
}
}
intensities *= frameWeight;
weights *= frameWeight;
oColorAndRWeight = vec4(intensities, weights.r);
oGbWeights = vec4(weights.gb, 0.0, 0.0);
}
""".trimIndent()
/**
* MergeBayerRaw transport recovered from the Halide AOT contract.
*
* Unlike MergeRgbRaw, this branch never demosaics or applies white balance. Alignment and the
* covariance kernel operate on Bayer quads, and every output sample is reconstructed only from
* the same CFA phase in neighboring quads. This preserves the original Bayer lattice exactly.
* Alignment and the spatial kernel operate on Bayer quads, and every output sample is
* reconstructed only from the same CFA phase in neighboring quads.
*/
val mergeBayer = """
#version 300 es
@@ -937,35 +664,40 @@ internal object GlesMgcRawSpatialShaders {
precision highp int;
precision highp usampler2D;
uniform highp usampler2D uRaw;
uniform sampler2D uFlow;
uniform sampler2D uAlignment;
uniform sampler2D uFrameWeight;
uniform sampler2D uCovariance;
uniform sampler2D uLinearKernelMask;
uniform ivec2 uRawSize;
uniform ivec2 uRejectionSize;
uniform vec4 uCovRangeRg;
uniform vec2 uCovRangeB;
uniform vec4 uGains;
uniform vec4 uBlackLevelsTimesGains;
uniform float uKernelSigma;
uniform int uCfaPattern;
uniform int uUseFrameWeight;
out vec4 oBayerAndWeight;
vec2 mirrorUv(vec2 uv) {
uv = mod(uv, 2.0);
return mix(uv, 2.0 - uv, greaterThan(uv, vec2(1.0)));
}
int phaseIndex(ivec2 phase) {
return (phase.y << 1) + phase.x;
}
float kernelWeight(vec2 quadOffset, vec3 covariance) {
float distance =
quadOffset.x * quadOffset.x * covariance.x +
quadOffset.y * quadOffset.y * covariance.y +
quadOffset.x * quadOffset.y * covariance.z * 2.0;
return exp2(-0.5 * distance) + 0.00005;
int mirrorCoordinate(int coordinate, int extent) {
if (extent <= 1) return 0;
if (coordinate < 0) coordinate = -coordinate - 1;
if (coordinate >= extent) coordinate = 2 * extent - coordinate - 1;
return clamp(coordinate, 0, extent - 1);
}
ivec2 mirrorQuad(ivec2 quad, ivec2 extent) {
return ivec2(
mirrorCoordinate(quad.x, extent.x),
mirrorCoordinate(quad.y, extent.y)
);
}
float kernelWeight(vec2 pixelOffset, float kernelSigmaSquared) {
return exp(
-0.5 * dot(pixelOffset * pixelOffset, vec2(kernelSigmaSquared))
);
}
float linearKernelWeight(vec2 pixelOffset) {
@@ -977,8 +709,23 @@ internal object GlesMgcRawSpatialShaders {
ivec2 phase = outputPixel & ivec2(1);
int phaseChannel = phaseIndex(phase);
ivec2 outputQuad = outputPixel / 2;
vec2 uv = gl_FragCoord.xy / vec2(uRawSize);
vec4 flow = texture(uFlow, uv);
// MergeBayerRaw16 addresses the converted alignment as one texel per
// 8x8 Bayer-quad tile. X/Y are displacements in Bayer-quad units.
// There is no normalized-UV conversion or filtering at this stage.
ivec2 tileId = outputQuad / 8;
ivec2 offsetWithinTile = outputQuad - tileId * 8;
ivec2 alignmentSize = max(textureSize(uAlignment, 0), ivec2(1));
vec2 alignmentQuadOffset = texelFetch(
uAlignment,
clamp(tileId, ivec2(0), alignmentSize - ivec2(1)),
0
).xy;
vec2 tilePosition =
vec2(tileId * 8) + alignmentQuadOffset;
ivec2 alignedTileQuad = ivec2(roundEven(tilePosition));
vec2 subquadPixelOffset =
2.0 * (vec2(alignedTileQuad) - tilePosition);
ivec2 anchor = alignedTileQuad + offsetWithinTile;
// MergeBayerRaw consumes one byte/float from the quarter-resolution rejection
// domain. The recovered AOT performs integer loads here; interpolating adjacent
// rejection cells changes the temporal support around rejection boundaries.
@@ -987,49 +734,66 @@ internal object GlesMgcRawSpatialShaders {
ivec2(0),
uRejectionSize - ivec2(1)
);
ivec2 frameWeightSize = max(textureSize(uFrameWeight, 0), ivec2(1));
ivec2 frameWeightPixel = clamp(
rejectionPixel,
ivec2(0),
frameWeightSize - ivec2(1)
);
float frameWeight = uUseFrameWeight != 0
? texelFetch(uFrameWeight, rejectionPixel, 0).r
? texelFetch(uFrameWeight, frameWeightPixel, 0).r
: 1.0;
float linearKernelMix =
texelFetch(uLinearKernelMask, rejectionPixel, 0).r;
vec2 sampleUv = mirrorUv(uv + flow.xy);
vec3 packedCovariance = texture(uCovariance, sampleUv).xyz;
vec3 covariance = vec3(
packedCovariance.xy * uCovRangeRg.yw + uCovRangeRg.xz,
packedCovariance.z * uCovRangeB.y + uCovRangeB.x
ivec2 linearKernelSize = max(
textureSize(uLinearKernelMask, 0),
ivec2(1)
);
// Pixel-center coordinates are converted to the same-phase Bayer-quad lattice.
vec2 samplePixel = sampleUv * vec2(uRawSize) - vec2(0.5);
vec2 quadPosition = (samplePixel - vec2(phase)) * 0.5;
ivec2 anchor = ivec2(floor(quadPosition));
ivec2 maximumQuad = max(
(uRawSize - ivec2(1) - phase) / 2,
ivec2(0)
ivec2 linearKernelPixel = clamp(
rejectionPixel,
ivec2(0),
linearKernelSize - ivec2(1)
);
float linearKernelMix = texelFetch(
uLinearKernelMask,
linearKernelPixel,
0
).r;
ivec2 quadExtent = max(uRawSize / 2, ivec2(1));
float kernelSigmaSquared = uKernelSigma * uKernelSigma;
float intensity = 0.0;
float accumulatedWeight = 0.0;
for (int y = -1; y <= 1; ++y) {
float sampleOffsetY =
subquadPixelOffset.y + 2.0 * float(y);
if (abs(sampleOffsetY) > 2.5) continue;
for (int x = -1; x <= 1; ++x) {
ivec2 quad = clamp(
vec2 sampleOffset =
subquadPixelOffset + 2.0 * vec2(x, y);
ivec2 quad = mirrorQuad(
anchor + ivec2(x, y),
ivec2(0),
maximumQuad
quadExtent
);
ivec2 rawPixel = quad * 2 + phase;
float rawValue = float(texelFetch(uRaw, rawPixel, 0).r);
if (
abs(sampleOffset.x) <= 1.5 &&
abs(sampleOffset.y) <= 1.5
) {
float rawValue = float(
texelFetch(uRaw, rawPixel, 0).r
);
float normalized =
rawValue * uGains[phaseChannel] +
uBlackLevelsTimesGains[phaseChannel];
vec2 quadOffset =
vec2(anchor + ivec2(x, y)) - quadPosition;
float weight = mix(
kernelWeight(quadOffset, covariance),
linearKernelWeight(2.0 * quadOffset),
kernelWeight(
sampleOffset,
kernelSigmaSquared
),
linearKernelWeight(sampleOffset),
linearKernelMix
);
intensity += normalized * weight;
accumulatedWeight += weight;
}
bool diagonalGreenPair =
(uCfaPattern == 0 || uCfaPattern == 3) &&
@@ -1037,7 +801,10 @@ internal object GlesMgcRawSpatialShaders {
bool cornerGreenPair =
(uCfaPattern == 1 || uCfaPattern == 2) &&
(phaseChannel == 0 || phaseChannel == 3);
if (linearKernelMix > 0.0 && (diagonalGreenPair || cornerGreenPair)) {
if (
linearKernelMix > 0.0 &&
(diagonalGreenPair || cornerGreenPair)
) {
int otherPhase = phaseChannel;
vec2 diagonalOffset = vec2(0.0);
if (diagonalGreenPair) {
@@ -1056,7 +823,7 @@ internal object GlesMgcRawSpatialShaders {
diagonalOffset = vec2(-1.0);
}
vec2 otherPixelOffset =
2.0 * quadOffset + diagonalOffset;
sampleOffset + diagonalOffset;
if (
abs(otherPixelOffset.x) <= 1.5 &&
abs(otherPixelOffset.y) <= 1.5
@@ -1073,9 +840,14 @@ internal object GlesMgcRawSpatialShaders {
float otherNormalized =
otherRawValue * uGains[otherPhase] +
uBlackLevelsTimesGains[otherPhase];
float otherWeight =
linearKernelWeight(otherPixelOffset) *
linearKernelMix;
float otherWeight = mix(
kernelWeight(
otherPixelOffset,
kernelSigmaSquared
),
linearKernelWeight(otherPixelOffset),
linearKernelMix
);
intensity += otherNormalized * otherWeight;
accumulatedWeight += otherWeight;
}
@@ -1110,6 +882,24 @@ internal object GlesMgcRawSpatialShaders {
}
""".trimIndent()
val normalizeBayerF16 = """
#version 300 es
precision highp float;
precision highp int;
uniform sampler2D uBayerAndWeight;
uniform ivec2 uOutputSize;
layout(location = 0) out highp float oBayer;
void main() {
ivec2 p = clamp(
ivec2(gl_FragCoord.xy),
ivec2(0),
uOutputSize - ivec2(1)
);
vec2 valueAndWeight = texelFetch(uBayerAndWeight, p, 0).rg;
oBayer = max(valueAndWeight.x / max(valueAndWeight.y, 1.0e-8), 0.0);
}
""".trimIndent()
/**
* Raw16ToGrayHalide (0x3bbaf98): one value per Bayer quad, phase black
* subtraction, scalar gain, equal RGGB average and separable 1:2:1 filtering.
@@ -1152,7 +942,7 @@ internal object GlesMgcRawSpatialShaders {
float wy = y == 0 ? 0.5 : 0.25;
for (int x = -1; x <= 1; ++x) {
float wx = x == 0 ? 0.5 : 0.25;
value += grayAt(q * 2 + ivec2(x, y)) * wx * wy;
value += grayAt(q + ivec2(x, y)) * wx * wy;
}
}
// DownsampleRawToGrayHalide hands AlignPyramid an S16 buffer.
@@ -1229,13 +1019,15 @@ internal object GlesMgcRawSpatialShaders {
}
void main() {
ivec2 tile = ivec2(gl_FragCoord.xy);
ivec2 origin = tile * uTileStride;
// Halide's LK buffers have min=(1,1); the texture stores only that
// interior extent, so local texel zero is logical tile (1,1).
ivec2 origin = (tile + ivec2(1)) * uTileStride;
float count = float(uTileSize * uTileSize);
float meanBase = 0.0;
if (uNormalize != 0) {
for (int y = 0; y < 16; ++y) {
for (int y = 0; y < 64; ++y) {
if (y >= uTileSize) break;
for (int x = 0; x < 16; ++x) {
for (int x = 0; x < 64; ++x) {
if (x >= uTileSize) break;
meanBase += valueAt(origin + ivec2(x, y));
}
@@ -1248,9 +1040,9 @@ internal object GlesMgcRawSpatialShaders {
float xy = 0.0;
float baseX = 0.0;
float baseY = 0.0;
for (int y = 0; y < 16; ++y) {
for (int y = 0; y < 64; ++y) {
if (y >= uTileSize) break;
for (int x = 0; x < 16; ++x) {
for (int x = 0; x < 64; ++x) {
if (x >= uTileSize) break;
ivec2 p = origin + ivec2(x, y);
vec2 gradient = gradientAt(p);
@@ -1273,10 +1065,120 @@ internal object GlesMgcRawSpatialShaders {
}
""".trimIndent()
/**
* UpsampleAlignmentI16Halide (0x3be8da0, three-candidate worker 0x3be8048).
* The nearest coarse flow and the next-nearest flow on each axis are evaluated
* against the target-level S16 images. Keeping the best whole candidate avoids
* synthesizing a false motion vector across an alignment discontinuity.
*/
val upsampleAlignment = """
#version 300 es
precision highp float;
precision highp int;
precision highp usampler2D;
uniform highp usampler2D uReference;
uniform highp usampler2D uCurrent;
uniform sampler2D uInitialAlignment;
uniform ivec2 uImageSize;
uniform ivec2 uInitialGridSize;
uniform int uInitialGridMin;
uniform int uTargetGridMin;
uniform int uInitialTileStride;
uniform int uTargetTileStride;
uniform int uTargetTileSize;
uniform float uInitialScale;
out vec4 oAlignment;
float valueAt(highp usampler2D image, ivec2 p) {
return min(
float(texelFetch(
image,
clamp(p, ivec2(0), uImageSize - ivec2(1)),
0
).r),
32767.0
);
}
ivec2 boundedInitialTile(ivec2 p) {
return clamp(p, ivec2(0), uInitialGridSize - ivec2(1));
}
vec2 candidateFlow(ivec2 p) {
return texelFetch(
uInitialAlignment,
boundedInitialTile(p),
0
).xy * uInitialScale;
}
float candidateCost(ivec2 origin, vec2 flow) {
// The AArch64 worker rounds each candidate to an integer S16-image
// displacement for the block L1 comparison.
ivec2 displacement = ivec2(roundEven(flow));
float cost = 0.0;
for (int y = 0; y < 64; ++y) {
if (y >= uTargetTileSize) break;
for (int x = 0; x < 64; ++x) {
if (x >= uTargetTileSize) break;
ivec2 p = origin + ivec2(x, y);
cost += abs(
valueAt(uReference, p) -
valueAt(uCurrent, p + displacement)
);
}
}
return cost / float(uTargetTileSize * uTargetTileSize);
}
void main() {
ivec2 targetTile = ivec2(gl_FragCoord.xy);
ivec2 targetLogicalTile =
targetTile + ivec2(uTargetGridMin);
vec2 initialGrid =
vec2(targetLogicalTile * uTargetTileStride) /
(uInitialScale * float(uInitialTileStride)) -
vec2(float(uInitialGridMin));
vec2 nearestPosition = roundEven(initialGrid);
ivec2 nearest = ivec2(nearestPosition);
ivec2 nextX = nearest + ivec2(
initialGrid.x < nearestPosition.x ? -1 : 1,
0
);
ivec2 nextY = nearest + ivec2(
0,
initialGrid.y < nearestPosition.y ? -1 : 1
);
nearest = boundedInitialTile(nearest);
nextX = boundedInitialTile(nextX);
nextY = boundedInitialTile(nextY);
ivec2 origin = targetLogicalTile * uTargetTileStride;
vec2 bestFlow = candidateFlow(nearest);
float bestCost = candidateCost(origin, bestFlow);
float candidateIndex = 0.0;
vec2 flowX = candidateFlow(nextX);
float costX = candidateCost(origin, flowX);
if (costX < bestCost) {
bestFlow = flowX;
bestCost = costX;
candidateIndex = 1.0;
}
vec2 flowY = candidateFlow(nextY);
float costY = candidateCost(origin, flowY);
if (costY < bestCost) {
bestFlow = flowY;
bestCost = costY;
candidateIndex = 2.0;
}
oAlignment = vec4(bestFlow, bestCost, candidateIndex);
}
""".trimIndent()
/**
* BlockLucasKanadeHalide (0x3b9be68, workers 0x3b9cb5c/0x3b9e72c). One draw is
* one generated-kernel iteration. Bilinear weights retain the S16 Q15 conversion and
* saturating rounded shift used by the AArch64 worker.
* one generated-kernel iteration. Its input has already been expanded onto this LK
* grid by UpsampleAlignment. Bilinear weights below are the image-warp S16 Q15
* conversion and saturating rounded shift used by the AArch64 worker.
*/
val blockLucasKanade = """
#version 300 es
@@ -1290,11 +1192,9 @@ internal object GlesMgcRawSpatialShaders {
uniform sampler2D uInitialAlignment;
uniform ivec2 uImageSize;
uniform ivec2 uGridSize;
uniform ivec2 uInitialGridSize;
uniform int uTileStride;
uniform int uTileSize;
uniform int uNormalize;
uniform float uInitialScale;
uniform int uHasInitialAlignment;
out vec4 oAlignment;
@@ -1358,26 +1258,20 @@ internal object GlesMgcRawSpatialShaders {
}
void main() {
ivec2 tile = ivec2(gl_FragCoord.xy);
ivec2 initialTile = clamp(
ivec2(
floor(
(vec2(tile) + 0.5) *
vec2(uInitialGridSize) / vec2(uGridSize)
)
),
ivec2(0),
uInitialGridSize - ivec2(1)
);
vec2 flow = uHasInitialAlignment != 0
? texelFetch(uInitialAlignment, initialTile, 0).xy * uInitialScale
? texelFetch(
uInitialAlignment,
clamp(tile, ivec2(0), uGridSize - ivec2(1)),
0
).xy
: vec2(0.0);
ivec2 origin = tile * uTileStride;
ivec2 origin = (tile + ivec2(1)) * uTileStride;
float count = float(uTileSize * uTileSize);
float meanCurrent = 0.0;
if (uNormalize != 0) {
for (int y = 0; y < 16; ++y) {
for (int y = 0; y < 64; ++y) {
if (y >= uTileSize) break;
for (int x = 0; x < 16; ++x) {
for (int x = 0; x < 64; ++x) {
if (x >= uTileSize) break;
meanCurrent += warpedCurrentAt(
vec2(origin + ivec2(x, y)) + flow
@@ -1389,9 +1283,9 @@ internal object GlesMgcRawSpatialShaders {
float targetX = 0.0;
float targetY = 0.0;
for (int y = 0; y < 16; ++y) {
for (int y = 0; y < 64; ++y) {
if (y >= uTileSize) break;
for (int x = 0; x < 16; ++x) {
for (int x = 0; x < 64; ++x) {
if (x >= uTileSize) break;
ivec2 p = origin + ivec2(x, y);
float current = warpedCurrentAt(vec2(p) + flow) - meanCurrent;
@@ -1567,6 +1461,9 @@ internal object GlesMgcRawSpatialShaders {
uniform ivec2 uOutputSize;
uniform float uTileStride;
uniform float uAlignmentScale;
uniform float uOutputToAlignmentScale;
uniform float uGridMin;
uniform vec2 uFlowNormalizationSize;
out vec4 oFlow;
vec2 flowAt(ivec2 p) {
return texelFetch(
@@ -1577,7 +1474,9 @@ internal object GlesMgcRawSpatialShaders {
}
void main() {
vec2 pixel = gl_FragCoord.xy - vec2(0.5);
vec2 grid = pixel / uTileStride;
vec2 grid =
pixel * uOutputToAlignmentScale / uTileStride -
vec2(uGridMin);
ivec2 p0 = ivec2(floor(grid));
vec2 f = fract(grid);
vec2 a = mix(flowAt(p0), flowAt(p0 + ivec2(1, 0)), f.x);
@@ -1593,9 +1492,10 @@ internal object GlesMgcRawSpatialShaders {
maximumFlow = max(maximumFlow, v);
}
}
vec2 uvFlow = flowPixels / vec2(uOutputSize);
vec2 uvFlow = flowPixels / uFlowNormalizationSize;
vec2 normalizedRange =
(maximumFlow - minimumFlow) / max(vec2(uOutputSize), vec2(1.0));
(maximumFlow - minimumFlow) /
max(uFlowNormalizationSize, vec2(1.0));
// ConvertAlignmentHalide stores the Euclidean length of the normalized
// min/max flow extent. X and Y use their own output dimensions.
float localFlowVariation = length(normalizedRange);
@@ -1603,6 +1503,47 @@ internal object GlesMgcRawSpatialShaders {
}
""".trimIndent()
/**
* Transport from the internal LK grid to MergeBayerRaw16's alignment contract.
*
* Runtime buffer inspection gives a 255x192 Float32x3 alignment and a 255x192
* Float16x4 ConvertAlignment output for a 4080x3064 RAW. X/Y remain Bayer-quad
* displacements; they are not normalized UV coordinates. MergeBayer consumes one
* alignment texel per 8x8 Bayer-quad tile with nearest integer addressing.
*/
val convertBayerAlignment = """
#version 300 es
precision highp float;
precision highp int;
uniform sampler2D uAlignment;
uniform ivec2 uGridSize;
uniform float uAlignmentToBayerQuads;
out vec4 oAlignment;
void main() {
ivec2 outputTile = ivec2(gl_FragCoord.xy);
vec2 flowInBayerQuads = texelFetch(
uAlignment,
clamp(outputTile, ivec2(0), uGridSize - ivec2(1)),
0
).xy * uAlignmentToBayerQuads;
oAlignment = vec4(flowInBayerQuads, 0.0, 0.0);
}
""".trimIndent()
val strengthAlignment = """
#version 300 es
precision highp float;
precision highp int;
uniform sampler2D uFlow;
uniform ivec2 uOutputSize;
out vec4 oAlignment;
void main() {
vec2 uv = gl_FragCoord.xy / vec2(uOutputSize);
oAlignment = vec4(texture(uFlow, uv).xy, 0.0, 0.0);
}
""".trimIndent()
/**
* UnblockerRaw10Halide (0x35dd50c), operating on unpacked native RAW values.
*
@@ -1710,54 +1651,4 @@ internal object GlesMgcRawSpatialShaders {
}
""".trimIndent()
val normalize = """
#version 300 es
precision highp float;
precision highp int;
uniform sampler2D uColorAndRWeight;
uniform sampler2D uGbWeights;
uniform sampler2D uLensShading;
uniform int uUseLensShading;
uniform ivec2 uOutputSize;
uniform vec3 uCameraDomainScale;
out vec4 oLinearRgb;
void main() {
ivec2 p = clamp(
ivec2(gl_FragCoord.xy),
ivec2(0),
uOutputSize - ivec2(1)
);
vec4 colorAndR = texelFetch(uColorAndRWeight, p, 0);
vec2 gb = texelFetch(uGbWeights, p, 0).rg;
vec3 rgb = colorAndR.rgb /
max(vec3(colorAndR.a, gb.x, gb.y), vec3(1.0e-8));
if (uUseLensShading != 0) {
vec2 uv = (vec2(p) + 0.5) / vec2(uOutputSize);
vec4 shading = texture(uLensShading, uv);
rgb *= vec3(shading.r, 0.5 * (shading.g + shading.b), shading.a);
}
// Spatial merge is calculated with WB gains, while Photon LINEAR_RGB is camera RGB.
// This is the same output-domain conversion used by RCD WRITE_OUTPUT.
rgb *= uCameraDomainScale;
oLinearRgb = vec4(max(rgb, vec3(0.0)), 1.0);
}
""".trimIndent()
val transferToRgb16 = """
#version 300 es
precision highp float;
precision highp int;
uniform sampler2D uLinearRgb;
uniform ivec2 uOutputSize;
layout(location = 0) out highp uvec4 oRgb16;
void main() {
ivec2 p = clamp(
ivec2(gl_FragCoord.xy),
ivec2(0),
uOutputSize - ivec2(1)
);
vec3 rgb = clamp(texelFetch(uLinearRgb, p, 0).rgb, 0.0, 1.0);
oRgb16 = uvec4(round(rgb * 65535.0), 65535.0);
}
""".trimIndent()
}
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,128 @@
package com.hinnka.mycamera.processor
import com.hinnka.mycamera.raw.MgcSpatialStrengthMap
import com.hinnka.mycamera.utils.PLog
import java.nio.ByteBuffer
/**
* Thin host boundary around MGC's mechanically lifted Spatial noise-model
* kernels. No strength approximation is performed here.
*/
internal object MgcSpatialStrengthMapGenerator {
private const val TAG = "MgcSpatialStrength"
private const val REJECTED_DENOISE_MULTIPLIER = -1f
init {
System.loadLibrary("my-native-lib")
}
fun compute(
outputMode: MgcSpatialOutputMode,
fusedF16: ByteBuffer,
width: Int,
height: Int,
cfaPattern: Int,
alignment: ByteBuffer,
alignmentWidth: Int,
alignmentHeight: Int,
rejection: ByteBuffer,
rejectionWidth: Int,
rejectionHeight: Int,
frameCount: Int,
inputReadNoise: FloatArray,
inputShotNoise: FloatArray,
frameWeights: FloatArray,
kernelSigmas: FloatArray,
): MgcSpatialStrengthMap? {
val expectedFusedSamples = width.toLong() * height.toLong() *
if (outputMode == MgcSpatialOutputMode.BAYER) 1L else 4L
val expectedAlignmentValues =
alignmentWidth.toLong() * alignmentHeight.toLong() * frameCount * 2L
val expectedRejectionValues =
rejectionWidth.toLong() * rejectionHeight.toLong() * frameCount
val valid = fusedF16.isDirect && alignment.isDirect && rejection.isDirect &&
width > 0 && height > 0 && cfaPattern in 0..3 && frameCount > 1 &&
fusedF16.capacity().toLong() >= expectedFusedSamples * Short.SIZE_BYTES &&
alignment.capacity().toLong() >= expectedAlignmentValues * Float.SIZE_BYTES &&
rejection.capacity().toLong() >= expectedRejectionValues &&
inputReadNoise.size == frameCount * 3 &&
inputShotNoise.size == frameCount * 3 &&
frameWeights.size == frameCount &&
kernelSigmas.size == frameCount &&
inputReadNoise.all(Float::isFinite) &&
inputShotNoise.all(Float::isFinite) &&
frameWeights.all { it.isFinite() && it >= 0f } &&
kernelSigmas.all { it.isFinite() && it > 0f }
if (!valid) {
PLog.e(
TAG,
"Rejected malformed MGC strength input: mode=$outputMode " +
"image=${width}x$height frames=$frameCount " +
"alignment=${alignmentWidth}x$alignmentHeight " +
"rejection=${rejectionWidth}x$rejectionHeight",
)
return null
}
fusedF16.position(0)
alignment.position(0)
rejection.position(0)
val output = ShortArray(rejectionWidth * rejectionHeight)
val result = nativeCompute(
layout = if (outputMode == MgcSpatialOutputMode.BAYER) 0 else 1,
fusedF16 = fusedF16,
width = width,
height = height,
cfaPattern = cfaPattern,
alignment = alignment,
alignmentWidth = alignmentWidth,
alignmentHeight = alignmentHeight,
rejection = rejection,
rejectionWidth = rejectionWidth,
rejectionHeight = rejectionHeight,
frameCount = frameCount,
inputReadNoise = inputReadNoise,
inputShotNoise = inputShotNoise,
frameWeights = frameWeights,
kernelSigmas = kernelSigmas,
rejectedDenoiseMultiplier = REJECTED_DENOISE_MULTIPLIER,
outputStrengthQ8 = output,
)
fusedF16.position(0)
alignment.position(0)
rejection.position(0)
if (result != 0) {
PLog.e(
TAG,
"MGC strength AOT failed: result=$result mode=$outputMode " +
"image=${width}x$height frames=$frameCount",
)
return null
}
return MgcSpatialStrengthMap(
width = rejectionWidth,
height = rejectionHeight,
q8 = output,
)
}
private external fun nativeCompute(
layout: Int,
fusedF16: ByteBuffer,
width: Int,
height: Int,
cfaPattern: Int,
alignment: ByteBuffer,
alignmentWidth: Int,
alignmentHeight: Int,
rejection: ByteBuffer,
rejectionWidth: Int,
rejectionHeight: Int,
frameCount: Int,
inputReadNoise: FloatArray,
inputShotNoise: FloatArray,
frameWeights: FloatArray,
kernelSigmas: FloatArray,
rejectedDenoiseMultiplier: Float,
outputStrengthQ8: ShortArray,
): Int
}
@@ -8,6 +8,7 @@ import com.hinnka.mycamera.camera.AspectRatio
import com.hinnka.mycamera.camera.MultiFrameConfig
import com.hinnka.mycamera.model.SafeImage
import com.hinnka.mycamera.raw.DngProfileGainTableMap
import com.hinnka.mycamera.raw.MgcSpatialStrengthMap
import com.hinnka.mycamera.raw.RawProfileToneMapMode
import com.hinnka.mycamera.utils.BitmapUtils
@@ -66,6 +67,11 @@ data class RawStackResult(
* Spatial merge. Null has the same unsupported meaning as [mgcDenoiseCorrelation].
*/
val mgcDenoiseNoiseScale: Float? = null,
/**
* Exact Q8 variance multiplier emitted by MGC's Spatial noise-model kernel.
* It is process-local and consumed before DNG write.
*/
val mgcSpatialStrengthMap: MgcSpatialStrengthMap? = null,
/**
* True only for the debug reference-only isolation path. This state is process-local and is
* never persisted into RAW/DNG metadata.
@@ -126,7 +126,11 @@ internal object MgcFullResolutionDenoise {
null
}
if (useSpatialModel && metadata.frameCount > 1 &&
(correlation == null || metadata.mgcDenoiseNoiseScale == null)
(
correlation == null ||
metadata.mgcDenoiseNoiseScale == null ||
metadata.mgcSpatialStrengthMap == null
)
) {
PLog.w(
TAG,
@@ -151,6 +155,24 @@ internal object MgcFullResolutionDenoise {
PLog.e(TAG, "MGC denoise rejected noise scale=$noiseScale")
return false
}
val spatialStrengthMap = metadata.mgcSpatialStrengthMap.takeIf {
useSpatialModel
}
if (useSpatialModel && spatialStrengthMap?.let {
it.width == (fullWidth + 3) / 4 &&
it.height == (fullHeight + 3) / 4 &&
it.q8.size == it.width * it.height
} != true
) {
PLog.e(
TAG,
"MGC denoise rejected Spatial strength map: " +
"full=${fullWidth}x$fullHeight map=${spatialStrengthMap?.let {
"${it.width}x${it.height}/${it.q8.size}"
} ?: "none"}",
)
return false
}
val rawNoise = RawNoiseModel.fromCamera2NoiseProfile(
metadata.channelNoiseProfile.takeIf { it.size >= 2 }
@@ -164,6 +186,7 @@ internal object MgcFullResolutionDenoise {
}
val rgbShot = bayerNoiseToRgb(shot, noiseScale)
val rgbRead = bayerNoiseToRgb(read, noiseScale)
val rgbWhiteBalance = normalizedRgbWhiteBalance(metadata.whiteBalanceGains)
val lumaTuning = interpolateTuning(tuningGain, lumaTuningPoints)
.withStrengthScale(finiteLumaScale)
val chromaTuning = interpolateTuning(tuningGain, chromaTuningPoints)
@@ -182,7 +205,11 @@ internal object MgcFullResolutionDenoise {
lensHeight = if (useSpatialModel) metadata.lensShadingMapHeight else 0,
normalizedRgbShot = rgbShot,
normalizedRgbRead = rgbRead,
normalizedRgbWhiteBalance = rgbWhiteBalance,
correlation = correlation,
spatialStrengthQ8 = spatialStrengthMap?.q8,
spatialStrengthWidth = spatialStrengthMap?.width ?: 0,
spatialStrengthHeight = spatialStrengthMap?.height ?: 0,
lumaEnabled = lumaEnabled,
chromaEnabled = chromaEnabled,
lumaStrength = lumaTuning.strength,
@@ -209,7 +236,11 @@ internal object MgcFullResolutionDenoise {
"luma=$lumaEnabled($finiteLumaScale) " +
"chroma=$chromaEnabled($finiteChromaScale) " +
"rgbShot=${rgbShot.contentToString()} " +
"rgbRead=${rgbRead.contentToString()} noiseScale=$noiseScale " +
"rgbRead=${rgbRead.contentToString()} " +
"rgbWb=${rgbWhiteBalance.contentToString()} noiseScale=$noiseScale " +
"strengthMap=${spatialStrengthMap?.let {
"${it.width}x${it.height}"
} ?: "identity"} " +
"lsc=${if (useSpatialModel) {
"${metadata.lensShadingMapWidth}x${metadata.lensShadingMapHeight}"
} else {
@@ -239,6 +270,29 @@ internal object MgcFullResolutionDenoise {
return floatArrayOf(red * scale, green * scale, blue * scale)
}
/**
* MGC's BayerRawToYuv/RgbRawToYuv boundary applies channel gains before
* denoising. Spatial/VGN exports un-white-balanced camera RGB for Linear
* DNG, so the native bridge enters that same working domain and removes
* the gains again after YUV -> RGB.
*/
private fun normalizedRgbWhiteBalance(gains: FloatArray): FloatArray {
fun safeGain(index: Int, fallback: Float): Float {
val value = gains.getOrElse(index) { fallback }
return value.takeIf { it.isFinite() && it > 0f } ?: fallback
}
val greenEven = safeGain(1, 1f)
val greenOdd = safeGain(2, greenEven)
val green = (0.5f * (greenEven + greenOdd))
.takeIf { it.isFinite() && it > 0f }
?: 1f
return floatArrayOf(
(safeGain(0, green) / green).coerceIn(1e-3f, 64f),
1f,
(safeGain(3, green) / green).coerceIn(1e-3f, 64f),
)
}
private fun interpolateTuning(
gain: Float,
points: List<TuningPoint>,
@@ -246,8 +300,8 @@ internal object MgcFullResolutionDenoise {
val finiteGain = gain.takeIf { it.isFinite() && it > 0f }
?: points.first().gain
val upperIndex = points.indexOfFirst { it.gain >= finiteGain }
if (upperIndex <= 0) return points.first().tuning.copyArrays()
if (upperIndex < 0) return points.last().tuning.copyArrays()
if (upperIndex == 0) return points.first().tuning.copyArrays()
val lower = points[upperIndex - 1]
val upper = points[upperIndex]
val logLower = ln(lower.gain)
@@ -421,7 +475,11 @@ internal object MgcFullResolutionDenoise {
lensHeight: Int,
normalizedRgbShot: FloatArray,
normalizedRgbRead: FloatArray,
normalizedRgbWhiteBalance: FloatArray,
correlation: FloatArray?,
spatialStrengthQ8: ShortArray?,
spatialStrengthWidth: Int,
spatialStrengthHeight: Int,
lumaEnabled: Boolean,
chromaEnabled: Boolean,
lumaStrength: FloatArray,
@@ -0,0 +1,31 @@
package com.hinnka.mycamera.raw
/**
* Process-local Q8 variance multiplier produced by MGC Spatial.
*
* It is consumed by the default pre-DNG denoise pass and is deliberately not
* serialized into DNG metadata.
*/
class MgcSpatialStrengthMap(
val width: Int,
val height: Int,
val q8: ShortArray,
) {
init {
require(width > 0 && height > 0)
require(q8.size == width * height)
}
override fun equals(other: Any?): Boolean =
other is MgcSpatialStrengthMap &&
width == other.width &&
height == other.height &&
q8.contentEquals(other.q8)
override fun hashCode(): Int {
var result = width
result = 31 * result + height
result = 31 * result + q8.contentHashCode()
return result
}
}
@@ -78,7 +78,7 @@ internal data class MgcSpatialDefaultDenoiseResult(
internal enum class MgcSpatialMaterializationMode {
DEFAULT_DENOISE,
DIAGNOSTIC_BYPASS_DENOISE,
BYPASS_DEFAULT_DENOISE,
}
/**
@@ -208,6 +208,7 @@ class RawDemosaicProcessor {
frameCount = baseMetadata?.frameCount ?: 1,
mgcDenoiseCorrelation = baseMetadata?.mgcDenoiseCorrelation,
mgcDenoiseNoiseScale = baseMetadata?.mgcDenoiseNoiseScale,
mgcSpatialStrengthMap = baseMetadata?.mgcSpatialStrengthMap,
mgcDenoiseTuningGain = baseMetadata?.mgcDenoiseTuningGain,
rotation = dngRawData.rotation,
profileGainTableMap = baseMetadata?.profileGainTableMap
@@ -845,9 +846,9 @@ class RawDemosaicProcessor {
/**
* Materializes Spatial output as standard LinearRaw RGB16. Bayer input is converted to
* un-white-balanced camera RGB first; Spatial RGB input stays in the same camera domain.
* The production mode consumes the merge noise model exactly once and runs MGC luma/chroma
* defaults. The debug isolation mode preserves the same conversion but bypasses only that
* post-merge denoise, so reference-frame Spatial reconstruction can be inspected.
* DEFAULT_DENOISE consumes the merge noise model exactly once and runs MGC luma/chroma
* defaults. BYPASS_DEFAULT_DENOISE preserves the same conversion while omitting only that
* post-merge denoise stage.
*/
internal suspend fun materializeMgcSpatialLinearRgb(
context: Context,
@@ -873,7 +874,12 @@ class RawDemosaicProcessor {
val validSpatialModel = !applyDefaultDenoise || (
metadata.frameCount > 1 &&
metadata.mgcDenoiseCorrelation?.size == 128 &&
metadata.mgcDenoiseNoiseScale?.let { it.isFinite() && it > 0f } == true
metadata.mgcDenoiseNoiseScale?.let { it.isFinite() && it > 0f } == true &&
metadata.mgcSpatialStrengthMap?.let {
it.width == (width + 3) / 4 &&
it.height == (height + 3) / 4 &&
it.q8.size == it.width * it.height
} == true
)
if (!validGeometry || !validLayout || !validSource || rowStride <= 0 ||
!validSpatialModel
@@ -887,7 +893,10 @@ class RawDemosaicProcessor {
else -> "none"
}} frames=${metadata.frameCount} " +
"correlation=${metadata.mgcDenoiseCorrelation?.size ?: 0} " +
"noiseScale=${metadata.mgcDenoiseNoiseScale}",
"noiseScale=${metadata.mgcDenoiseNoiseScale} " +
"strengthMap=${metadata.mgcSpatialStrengthMap?.let {
"${it.width}x${it.height}"
} ?: "none"}",
)
return@withContext null
}
@@ -970,7 +979,7 @@ class RawDemosaicProcessor {
val rgbaReadback = LargeDirectBuffer.allocate(
rgbaBytes,
"MGC Spatial default denoise RGBA16F",
"MGC Spatial materialization RGBA16F",
)?.order(ByteOrder.nativeOrder()) ?: return@withContext null
var packedOutput: ByteBuffer? = null
var completed = false
@@ -1080,7 +1089,7 @@ class RawDemosaicProcessor {
check(
GLES30.glCheckFramebufferStatus(GLES30.GL_FRAMEBUFFER) ==
GLES30.GL_FRAMEBUFFER_COMPLETE
) { "MGC Spatial default denoise readback framebuffer is incomplete" }
) { "MGC Spatial materialization readback framebuffer is incomplete" }
GLES30.glPixelStorei(GLES30.GL_PACK_ALIGNMENT, 8)
rgbaReadback.clear()
rgbaReadback.limit(rgbaBytes.toInt())
@@ -1094,7 +1103,7 @@ class RawDemosaicProcessor {
GLES30.GL_HALF_FLOAT,
rgbaReadback,
)
checkGlError("MGC Spatial default denoise camera RGB readback")
checkGlError("MGC Spatial materialization camera RGB readback")
rgbaReadback.position(0)
val readbackMs = (System.nanoTime() - readbackStartNs) / 1_000_000L
@@ -1124,16 +1133,16 @@ class RawDemosaicProcessor {
} else {
PLog.i(
TAG,
"MGC Spatial diagnostic materialization: default luma/chroma denoise bypassed",
"MGC Spatial materialization: default luma/chroma denoise bypassed",
)
}
val nativeMs = (System.nanoTime() - nativeStartNs) / 1_000_000L
val output = LargeDirectBuffer.allocate(
rgbBytes,
"MGC Spatial default denoised LinearRaw RGB16",
"MGC Spatial materialized LinearRaw RGB16",
)?.order(ByteOrder.nativeOrder())
?: error("Unable to allocate MGC default-denoised LinearRaw buffer")
?: error("Unable to allocate MGC Spatial LinearRaw buffer")
packedOutput = output
rgbaReadback.position(0)
output.clear()
@@ -1155,11 +1164,14 @@ class RawDemosaicProcessor {
"size=${width}x$height pass=${if (applyDefaultDenoise) {
"SPATIAL_DEFAULT"
} else {
"DIAGNOSTIC_BYPASS_DENOISE"
"BYPASS_DEFAULT_DENOISE"
}} " +
"luma=${if (applyDefaultDenoise) 1.0 else 0.0} " +
"chroma=${if (applyDefaultDenoise) 1.0 else 0.0} " +
"frames=${metadata.frameCount} noiseScale=${metadata.mgcDenoiseNoiseScale} " +
"strengthMap=${metadata.mgcSpatialStrengthMap?.let {
"${it.width}x${it.height}"
} ?: "none"} " +
"lscIn=$sourcePixelsIncludeLensShadingCorrection " +
"lscAppliedToBayer=$applyLensShadingToBayer " +
"lscOut=$outputIncludesLensShading " +
@@ -1172,7 +1184,7 @@ class RawDemosaicProcessor {
pixelsIncludeLensShadingCorrection = outputIncludesLensShading,
)
} catch (error: Exception) {
PLog.e(TAG, "Failed to materialize MGC Spatial default denoise", error)
PLog.e(TAG, "Failed to materialize MGC Spatial output", error)
null
} finally {
GLES30.glPixelStorei(GLES30.GL_PACK_ALIGNMENT, 1)
@@ -2143,6 +2155,7 @@ class RawDemosaicProcessor {
frameCount = 1,
mgcDenoiseCorrelation = null,
mgcDenoiseNoiseScale = null,
mgcSpatialStrengthMap = null,
)
profileGainTableMap?.let {
PLog.d(
@@ -116,6 +116,8 @@ data class RawMetadata(
val mgcDenoiseCorrelation: FloatArray? = null,
/** Scale applied to shot/read coefficients by an equal-exposure MGC Spatial merge. */
val mgcDenoiseNoiseScale: Float? = null,
/** Exact process-local Q8 Spatial variance multiplier; never serialized into DNG. */
val mgcSpatialStrengthMap: MgcSpatialStrengthMap? = null,
/** Gain coordinate used by luma_denoise_default.binarypb. */
val mgcDenoiseTuningGain: Float? = null,
val rotation: Int? = null,
@@ -1001,6 +1003,7 @@ data class RawMetadata(
if (!mgcDenoiseCorrelation.contentEquals(other.mgcDenoiseCorrelation)) return false
} else if (other.mgcDenoiseCorrelation != null) return false
if (mgcDenoiseNoiseScale != other.mgcDenoiseNoiseScale) return false
if (mgcSpatialStrengthMap != other.mgcSpatialStrengthMap) return false
if (mgcDenoiseTuningGain != other.mgcDenoiseTuningGain) return false
if (rotation != other.rotation) return false
@@ -1028,6 +1031,7 @@ data class RawMetadata(
result = 31 * result + frameCount
result = 31 * result + (mgcDenoiseCorrelation?.contentHashCode() ?: 0)
result = 31 * result + (mgcDenoiseNoiseScale?.hashCode() ?: 0)
result = 31 * result + (mgcSpatialStrengthMap?.hashCode() ?: 0)
result = 31 * result + (mgcDenoiseTuningGain?.hashCode() ?: 0)
result = 31 * result + (rotation ?: 0)
return result
@@ -39,6 +39,36 @@ class CodeRange:
CODE_RANGES = (
CodeRange(
"ComputeBayerNoiseModelF32TileSize16",
0x037A6E14,
0x037AAB68,
0x037B9AF4,
),
CodeRange(
"ComputeRGBNoiseModelF32TileSize16",
0x037B9AF4,
0x037B9AF4,
0x037BECDC,
),
CodeRange(
"DownsampleRawF16ToFloatTileSize16",
0x037BECDC,
0x037BECDC,
0x037C1A8C,
),
CodeRange(
"DownsampleRgbF16ToFloatTileSize16",
0x037C1A8C,
0x037C1A8C,
0x037DB248,
),
CodeRange(
"DownsampleRgbF16ToFloatTileSize16CopyHelper",
0x038561A4,
0x03856414,
0x0385642C,
),
CodeRange("BayerRawToYuv1xS16", 0x049C3484, 0x049C7B64, 0x049CAA54),
CodeRange("RgbRawToYuv1xS16", 0x04A17EA8, 0x04A198B8, 0x04A1C3E8),
CodeRange(
@@ -67,6 +97,18 @@ CODE_RANGES = (
0x054DCD34,
0x054DE730,
),
CodeRange(
"DownsampleRgbF16ToFloatTileSize16Mode0",
0x05DACC58,
0x05DACC58,
0x05DAD588,
),
CodeRange(
"DownsampleRgbF16ToFloatTileSize16Mode1",
0x05DAD588,
0x05DAD588,
0x05DAE16C,
),
)
# Successful oracle runs reached only malloc/free/trace/par-for. memset is
@@ -78,6 +120,7 @@ HOST_TARGETS = {
0x05EF54BC: "halide_trace",
0x05A7FEF0: "halide_do_par_for",
0x05FB8540: "memset",
0x05DAE16C: "downsample_rgb_dispatch",
}
@@ -0,0 +1,52 @@
#include <idc.idc>
static dump_function_containing(ea)
{
auto start, end, result;
start = get_func_attr(ea, FUNCATTR_START);
end = get_func_attr(ea, FUNCATTR_END);
msg("\n===== callsite %x function %x..%x =====\n", ea, start, end);
if (start == BADADDR)
return;
result = decompile(start);
if (result != 0)
msg("%s\n", result.text);
else
msg("Decompile failed\n");
}
static force_and_dump(start, end)
{
auto result;
del_func(start);
if (!add_func(start, end))
{
msg("Unable to create function %x..%x\n", start, end);
return;
}
msg("\n===== forced function %x..%x =====\n", start, end);
result = decompile(start);
if (result != 0)
msg("%s\n", result.text);
else
msg("Decompile failed\n");
}
static dump_callers(target)
{
auto ref;
ref = get_first_cref_to(target);
while (ref != BADADDR)
{
dump_function_containing(ref);
ref = get_next_cref_to(target, ref);
}
}
static main()
{
load_and_run_plugin("hexarm64", 0);
force_and_dump(0x35A8E84, 0x35AC470);
force_and_dump(0x35B027C, 0x35B325C);
qexit(0);
}
@@ -0,0 +1,17 @@
#include <idc.idc>
static main()
{
auto result;
load_and_run_plugin("hexarm64", 0);
del_items(0x22C5BBC, DELIT_EXPAND, 0x22C60EC - 0x22C5BBC);
create_insn(0x22C5BBC);
add_func(0x22C5BBC, 0x22C60EC);
plan_and_wait(0x22C5BBC, 0x22C60EC);
result = decompile(0x22C5BBC);
if (result != 0)
msg("%s\n", result.text);
else
msg("Decompile failed for Spatial options constructor\n");
qexit(0);
}
@@ -0,0 +1,26 @@
#include <idc.idc>
static dump_containing(ea)
{
auto start, end, result;
start = get_func_attr(ea, FUNCATTR_START);
end = get_func_attr(ea, FUNCATTR_END);
msg("\n===== candidate %x function %x..%x =====\n", ea, start, end);
if (start == BADADDR)
return;
result = decompile(start);
if (result != 0)
msg("%s\n", result.text);
else
msg("Decompile failed\n");
}
static main()
{
load_and_run_plugin("hexarm64", 0);
dump_containing(0x235C23C);
dump_containing(0x24E2B88);
dump_containing(0x35AA0B0);
dump_containing(0x35ABE80);
qexit(0);
}
@@ -0,0 +1,24 @@
#include <idc.idc>
static dump_function(start, end)
{
auto result;
del_items(start, DELIT_EXPAND, end - start);
create_insn(start);
add_func(start, end);
plan_and_wait(start, end);
msg("\n===== function %x..%x =====\n", start, end);
result = decompile(start);
if (result != 0)
msg("%s\n", result.text);
else
msg("Decompile failed\n");
}
static main()
{
load_and_run_plugin("hexarm64", 0);
dump_function(0x37AAB68, 0x37B9AF4);
dump_function(0x37B9AF4, 0x37BECDC);
qexit(0);
}
@@ -0,0 +1,24 @@
#include <idc.idc>
static dump_function(start, end, label)
{
auto result;
del_items(start, DELIT_EXPAND, end - start);
create_insn(start);
add_func(start, end);
plan_and_wait(start, end);
msg("\n===== %s %x..%x =====\n", label, start, end);
result = decompile(start);
if (result != 0)
msg("%s\n", result.text);
else
msg("Decompile failed\n");
}
static main()
{
load_and_run_plugin("hexarm64", 0);
dump_function(0x37A99BC, 0x37AAB68, "Bayer strength task");
dump_function(0x37B8948, 0x37B9AF4, "RGB strength task");
qexit(0);
}
@@ -0,0 +1,22 @@
#include <idc.idc>
static dump_refs(target)
{
auto ref;
msg("\n===== xrefs to %x =====\n", target);
ref = get_first_cref_to(target);
while (ref != BADADDR)
{
msg("%08x %s %s\n", ref, print_insn_mnem(ref), print_operand(ref, 0));
ref = get_next_cref_to(target, ref);
}
}
static main()
{
dump_refs(0x35A4B00);
dump_refs(0x35A8E84);
dump_refs(0x3631290);
dump_refs(0x3629BAC);
qexit(0);
}
@@ -0,0 +1,41 @@
#include <idc.idc>
static main()
{
auto ea, end, mnem, op0, op1, op2;
ea = 0;
end = 0x4000000;
while (ea != BADADDR && ea < end)
{
mnem = print_insn_mnem(ea);
if (mnem == "LDR" || mnem == "STR" ||
mnem == "LDUR" || mnem == "STUR" ||
mnem == "LDP" || mnem == "STP")
{
op0 = print_operand(ea, 0);
op1 = print_operand(ea, 1);
op2 = print_operand(ea, 2);
if (strstr(op1, "#0x2B4") != -1 ||
strstr(op2, "#0x2B4") != -1 ||
strstr(op1, "#0x298") != -1 ||
strstr(op2, "#0x298") != -1 ||
strstr(op1, "#0x2A8") != -1 ||
strstr(op2, "#0x2A8") != -1 ||
strstr(op1, "#0x5B8") != -1 ||
strstr(op2, "#0x5B8") != -1 ||
strstr(op1, "#0x2B8") != -1 ||
strstr(op2, "#0x2B8") != -1 ||
strstr(op1, "#0x2BC") != -1 ||
strstr(op2, "#0x2BC") != -1 ||
strstr(op1, "#0x2C0") != -1 ||
strstr(op2, "#0x2C0") != -1 ||
strstr(op1, "#0xFB0") != -1 ||
strstr(op2, "#0xFB0") != -1)
{
msg("%08x %s %s, %s, %s\n", ea, mnem, op0, op1, op2);
}
}
ea = next_head(ea, end);
}
qexit(0);
}
@@ -37,6 +37,40 @@ class CodeRange:
CODE_RANGES = (
CodeRange(
"ComputeBayerNoiseModelF32TileSize16",
0x037A6E14,
0x037AAB68,
0x037B9AF4,
"photon_mgc_compute_bayer_noise_model_f32_tile_size_16",
),
CodeRange(
"ComputeRGBNoiseModelF32TileSize16",
0x037B9AF4,
0x037B9AF4,
0x037BECDC,
"photon_mgc_compute_rgb_noise_model_f32_tile_size_16",
),
CodeRange(
"DownsampleRawF16ToFloatTileSize16",
0x037BECDC,
0x037BECDC,
0x037C1A8C,
"photon_mgc_downsample_raw_f16_to_float_tile_size_16",
),
CodeRange(
"DownsampleRgbF16ToFloatTileSize16",
0x037C1A8C,
0x037C1A8C,
0x037DB248,
"photon_mgc_downsample_rgb_f16_to_float_tile_size_16",
),
CodeRange(
"DownsampleRgbF16ToFloatTileSize16CopyHelper",
0x038561A4,
0x03856414,
0x0385642C,
),
CodeRange("BayerRawToYuv1xS16", 0x049C3484, 0x049C7B64, 0x049CAA54),
CodeRange(
"RgbRawToYuv1xS16",
@@ -85,6 +119,20 @@ CODE_RANGES = (
0x054DE730,
"photon_mgc_compute_denoise_strength_maps_u16",
),
CodeRange(
"DownsampleRgbF16ToFloatTileSize16Mode0",
0x05DACC58,
0x05DACC58,
0x05DAD588,
"photon_mgc_downsample_rgb_mode_0",
),
CodeRange(
"DownsampleRgbF16ToFloatTileSize16Mode1",
0x05DAD588,
0x05DAD588,
0x05DAE16C,
"photon_mgc_downsample_rgb_mode_1",
),
)
HOST_TARGETS = {
@@ -93,6 +141,7 @@ HOST_TARGETS = {
0x05EF54BC: "photon_mgc_halide_trace",
0x05A7FEF0: "photon_mgc_halide_do_par_for",
0x05FB8540: "memset",
0x05DAE16C: "photon_mgc_downsample_rgb_dispatch",
}
@@ -312,18 +361,33 @@ def generate(
lines.append(f" .hidden {symbol}")
lines.append("")
for code_range in CODE_RANGES:
code_groups: list[list[CodeRange]] = []
for code_range in sorted(CODE_RANGES, key=lambda value: value.start):
section_start = page_floor(code_range.start)
section_end = page_ceil(code_range.end)
if (
not code_groups
or section_start >= max(
page_ceil(value.end) for value in code_groups[-1]
)
):
code_groups.append([code_range])
else:
code_groups[-1].append(code_range)
for code_group in code_groups:
section_start = min(page_floor(value.start) for value in code_group)
section_end = max(page_ceil(value.end) for value in code_group)
section_name = "__".join(value.name for value in code_group)
lines.extend(
[
(
f'.section .text.photon_mgc.{code_range.name},'
f'.section .text.photon_mgc.{section_name},'
'"ax",@progbits'
),
" .p2align 12",
]
)
for code_range in code_group:
if code_range.symbol is not None:
lines.extend(
[
@@ -1,5 +1,35 @@
{
"code_ranges": [
{
"end": "0x37b9af4",
"entry": "0x37aab68",
"name": "ComputeBayerNoiseModelF32TileSize16",
"start": "0x37a6e14"
},
{
"end": "0x37becdc",
"entry": "0x37b9af4",
"name": "ComputeRGBNoiseModelF32TileSize16",
"start": "0x37b9af4"
},
{
"end": "0x37c1a8c",
"entry": "0x37becdc",
"name": "DownsampleRawF16ToFloatTileSize16",
"start": "0x37becdc"
},
{
"end": "0x37db248",
"entry": "0x37c1a8c",
"name": "DownsampleRgbF16ToFloatTileSize16",
"start": "0x37c1a8c"
},
{
"end": "0x385642c",
"entry": "0x3856414",
"name": "DownsampleRgbF16ToFloatTileSize16CopyHelper",
"start": "0x38561a4"
},
{
"end": "0x49caa54",
"entry": "0x49c7b64",
@@ -47,6 +77,18 @@
"entry": "0x54dcd34",
"name": "ComputeDenoiseStrengthMapsU16",
"start": "0x54dbe04"
},
{
"end": "0x5dad588",
"entry": "0x5dacc58",
"name": "DownsampleRgbF16ToFloatTileSize16Mode0",
"start": "0x5dacc58"
},
{
"end": "0x5dae16c",
"entry": "0x5dad588",
"name": "DownsampleRgbF16ToFloatTileSize16Mode1",
"start": "0x5dad588"
}
],
"direct_external_targets": {
@@ -326,6 +368,76 @@
"target": "0x5ef6bd8"
}
],
"ComputeBayerNoiseModelF32TileSize16": [
{
"host": "halide_do_par_for",
"target": "0x5a7fef0"
},
{
"host": "halide_malloc",
"target": "0x5ef2634"
},
{
"host": "halide_free",
"target": "0x5ef2650"
},
{
"host": "halide_trace",
"target": "0x5ef54bc"
},
{
"host": "halide_error_path",
"target": "0x5ef61ac"
},
{
"host": "halide_error_path",
"target": "0x5ef6294"
},
{
"host": "halide_error_path",
"target": "0x5ef636c"
},
{
"host": "halide_error_path",
"target": "0x5ef63f8"
},
{
"host": "halide_error_path",
"target": "0x5ef64dc"
},
{
"host": "halide_error_path",
"target": "0x5ef6568"
},
{
"host": "halide_error_path",
"target": "0x5ef6600"
},
{
"host": "halide_error_path",
"target": "0x5ef6794"
},
{
"host": "halide_error_path",
"target": "0x5ef6a74"
},
{
"host": "halide_error_path",
"target": "0x5ef6a94"
},
{
"host": "halide_error_path",
"target": "0x5ef6b6c"
},
{
"host": "halide_error_path",
"target": "0x5ef6bd8"
},
{
"host": "memset",
"target": "0x5fb8540"
}
],
"ComputeDenoiseStrengthMapsU16": [
{
"host": "halide_do_par_for",
@@ -396,6 +508,286 @@
"target": "0x5fb8540"
}
],
"ComputeRGBNoiseModelF32TileSize16": [
{
"host": "halide_do_par_for",
"target": "0x5a7fef0"
},
{
"host": "halide_malloc",
"target": "0x5ef2634"
},
{
"host": "halide_free",
"target": "0x5ef2650"
},
{
"host": "halide_trace",
"target": "0x5ef54bc"
},
{
"host": "halide_error_path",
"target": "0x5ef61ac"
},
{
"host": "halide_error_path",
"target": "0x5ef6294"
},
{
"host": "halide_error_path",
"target": "0x5ef636c"
},
{
"host": "halide_error_path",
"target": "0x5ef63f8"
},
{
"host": "halide_error_path",
"target": "0x5ef64dc"
},
{
"host": "halide_error_path",
"target": "0x5ef6568"
},
{
"host": "halide_error_path",
"target": "0x5ef6600"
},
{
"host": "halide_error_path",
"target": "0x5ef6794"
},
{
"host": "halide_error_path",
"target": "0x5ef6a74"
},
{
"host": "halide_error_path",
"target": "0x5ef6a94"
},
{
"host": "halide_error_path",
"target": "0x5ef6b6c"
},
{
"host": "halide_error_path",
"target": "0x5ef6bd8"
}
],
"DownsampleRawF16ToFloatTileSize16": [
{
"host": "halide_do_par_for",
"target": "0x5a7fef0"
},
{
"host": "halide_trace",
"target": "0x5ef54bc"
},
{
"host": "halide_error_path",
"target": "0x5ef61ac"
},
{
"host": "halide_error_path",
"target": "0x5ef6294"
},
{
"host": "halide_error_path",
"target": "0x5ef636c"
},
{
"host": "halide_error_path",
"target": "0x5ef63f8"
},
{
"host": "halide_error_path",
"target": "0x5ef64dc"
},
{
"host": "halide_error_path",
"target": "0x5ef6568"
},
{
"host": "halide_error_path",
"target": "0x5ef6600"
},
{
"host": "halide_error_path",
"target": "0x5ef6794"
},
{
"host": "halide_error_path",
"target": "0x5ef6a94"
},
{
"host": "halide_error_path",
"target": "0x5ef6b6c"
},
{
"host": "halide_error_path",
"target": "0x5ef6bd8"
},
{
"host": "memset",
"target": "0x5fb8540"
}
],
"DownsampleRgbF16ToFloatTileSize16": [
{
"host": "halide_do_par_for",
"target": "0x5a7fef0"
},
{
"host": "halide_malloc",
"target": "0x5ef2634"
},
{
"host": "halide_free",
"target": "0x5ef2650"
},
{
"host": "halide_trace",
"target": "0x5ef54bc"
},
{
"host": "halide_error_path",
"target": "0x5ef604c"
},
{
"host": "halide_error_path",
"target": "0x5ef6140"
},
{
"host": "halide_error_path",
"target": "0x5ef61ac"
},
{
"host": "halide_error_path",
"target": "0x5ef6294"
},
{
"host": "halide_error_path",
"target": "0x5ef636c"
},
{
"host": "halide_error_path",
"target": "0x5ef63f8"
},
{
"host": "halide_error_path",
"target": "0x5ef64dc"
},
{
"host": "halide_error_path",
"target": "0x5ef6568"
},
{
"host": "halide_error_path",
"target": "0x5ef6600"
},
{
"host": "halide_error_path",
"target": "0x5ef6794"
},
{
"host": "halide_error_path",
"target": "0x5ef6a94"
},
{
"host": "halide_error_path",
"target": "0x5ef6b6c"
},
{
"host": "halide_error_path",
"target": "0x5ef6bd8"
}
],
"DownsampleRgbF16ToFloatTileSize16CopyHelper": [
{
"host": "downsample_rgb_dispatch",
"target": "0x5dae16c"
}
],
"DownsampleRgbF16ToFloatTileSize16Mode0": [
{
"host": "halide_error_path",
"target": "0x20239a0"
},
{
"host": "halide_error_path",
"target": "0x256406c"
},
{
"host": "halide_error_path",
"target": "0x5dac60c"
},
{
"host": "halide_error_path",
"target": "0x5daca0c"
},
{
"host": "halide_error_path",
"target": "0x5dae204"
},
{
"host": "halide_error_path",
"target": "0x5dae37c"
},
{
"host": "halide_error_path",
"target": "0x5f57538"
},
{
"host": "halide_error_path",
"target": "0x5f59544"
},
{
"host": "halide_error_path",
"target": "0x5f595a0"
},
{
"host": "memset",
"target": "0x5fb8540"
}
],
"DownsampleRgbF16ToFloatTileSize16Mode1": [
{
"host": "halide_error_path",
"target": "0x20239a0"
},
{
"host": "halide_error_path",
"target": "0x256406c"
},
{
"host": "halide_error_path",
"target": "0x5dac85c"
},
{
"host": "halide_error_path",
"target": "0x5dae540"
},
{
"host": "halide_error_path",
"target": "0x5dae6b8"
},
{
"host": "halide_error_path",
"target": "0x5f57538"
},
{
"host": "halide_error_path",
"target": "0x5f59544"
},
{
"host": "halide_error_path",
"target": "0x5f595a0"
},
{
"host": "memset",
"target": "0x5fb8540"
}
],
"PecanLumaDenoiseS16": [
{
"host": "halide_do_par_for",
@@ -607,11 +999,22 @@
}
]
},
"do_par_for_call_count": 12,
"do_par_for_call_count": 23,
"format": "mgc-full-resolution-denoise-static-lift-v1",
"page_count": 181,
"page_count": 257,
"page_size": 4096,
"pages": [
"0x4fd000",
"0x50f000",
"0x53e000",
"0x54e000",
"0x56e000",
"0x5bf000",
"0x5e3000",
"0x614000",
"0x634000",
"0x687000",
"0x6a7000",
"0x6a8000",
"0x6a9000",
"0x6aa000",
@@ -627,10 +1030,16 @@
"0x6b5000",
"0x6b6000",
"0x6b7000",
"0x6b8000",
"0x6b9000",
"0x6ba000",
"0x6bb000",
"0x6bc000",
"0x6bd000",
"0xbc0000",
"0xbc1000",
"0xbc2000",
"0xbc3000",
"0xd4d000",
"0xd51000",
"0xd5f000",
@@ -644,6 +1053,61 @@
"0xf39000",
"0xf3a000",
"0x10a9000",
"0x37a6000",
"0x37a7000",
"0x37a8000",
"0x37a9000",
"0x37aa000",
"0x37ab000",
"0x37ac000",
"0x37ad000",
"0x37ae000",
"0x37af000",
"0x37b0000",
"0x37b1000",
"0x37b2000",
"0x37b3000",
"0x37b4000",
"0x37b5000",
"0x37b6000",
"0x37b7000",
"0x37b8000",
"0x37b9000",
"0x37ba000",
"0x37bb000",
"0x37bc000",
"0x37bd000",
"0x37be000",
"0x37bf000",
"0x37c0000",
"0x37c1000",
"0x37c2000",
"0x37c3000",
"0x37c4000",
"0x37c5000",
"0x37c6000",
"0x37c7000",
"0x37c8000",
"0x37c9000",
"0x37ca000",
"0x37cb000",
"0x37cc000",
"0x37cd000",
"0x37ce000",
"0x37cf000",
"0x37d0000",
"0x37d1000",
"0x37d2000",
"0x37d3000",
"0x37d4000",
"0x37d5000",
"0x37d6000",
"0x37d7000",
"0x37d8000",
"0x37d9000",
"0x37da000",
"0x37db000",
"0x3856000",
"0x49c3000",
"0x49c4000",
"0x49c5000",
@@ -790,6 +1254,10 @@
"0x54dc000",
"0x54dd000",
"0x54de000",
"0x5dac000",
"0x5dad000",
"0x5dae000",
"0x6146000",
"0x614f000",
"0x6150000",
"0x6152000"
@@ -871,6 +1339,17 @@
"source": "MGC/MGC_9.6.080_V24_MGC/lib/arm64-v8a/libgcastartup.so",
"source_sha256": "2103c54ebba1627733b79e3646105595ed1ccefa2b1629f63fb7e1785a48d6a0",
"task_relocations": {
"0x6146550": "0x37a6e14",
"0x6146558": "0x37a99bc",
"0x6146560": "0x37ae9a8",
"0x6146568": "0x37b1150",
"0x6146570": "0x37b61a0",
"0x6146578": "0x37b8948",
"0x6146580": "0x37bd934",
"0x6146588": "0x37bea94",
"0x6146590": "0x37bfc00",
"0x6146598": "0x37c1348",
"0x61465a0": "0x37c298c",
"0x614fd58": "0x49c3484",
"0x614fda8": "0x4a17ea8",
"0x614ffb0": "0x4bee520",