feat: migrate MGC spatial RGB merge AOT to GLES shaders

This commit is contained in:
zhoubinjia committed 2026-11-03 17:34:16 +08:00
1 parent 36e5622cfd
commit ccc6d53e8e
15 files changed
+820 -4352

No files matched your search

-41
View File
@@ -158,50 +158,11 @@ set_source_files_properties(
OBJECT_DEPENDS "${MGC_RAISR_FILTERS};${MGC_RAISR_RANDOMNESS_LUT}"
)
set(
MGC_SPATIAL_RGB_CAPSULE
"${CMAKE_CURRENT_SOURCE_DIR}/mgc_denoise_static/mgc_spatial_rgb_merge_capsule.bin"
)
set(
MGC_SPATIAL_RGB_CAPSULE_SHA256
"196c4fb671a4c1e0667518d334474afd6f81a35a01acfd9d385089630a58eddd"
)
if(NOT EXISTS "${MGC_SPATIAL_RGB_CAPSULE}")
message(
FATAL_ERROR
"MGC Spatial RGB Merge capsule is missing; regenerate it with "
"scripts/research/generate_mgc_spatial_rgb_merge_static_asm.py"
)
endif()
file(
SHA256
"${MGC_SPATIAL_RGB_CAPSULE}"
MGC_SPATIAL_RGB_CAPSULE_ACTUAL_SHA256
)
if(NOT MGC_SPATIAL_RGB_CAPSULE_ACTUAL_SHA256 STREQUAL MGC_SPATIAL_RGB_CAPSULE_SHA256)
message(FATAL_ERROR "MGC Spatial RGB Merge capsule hash mismatch")
endif()
set(
MGC_SPATIAL_RGB_ASM
"${CMAKE_CURRENT_BINARY_DIR}/mgc_spatial_rgb_merge_static.S"
)
configure_file(
"${CMAKE_CURRENT_SOURCE_DIR}/mgc_denoise_static/mgc_spatial_rgb_merge_static.S.in"
"${MGC_SPATIAL_RGB_ASM}"
@ONLY
)
set_source_files_properties(
"${MGC_SPATIAL_RGB_ASM}"
PROPERTIES
OBJECT_DEPENDS "${MGC_SPATIAL_RGB_CAPSULE}"
)
# These are configure-time outputs, so do not mark them GENERATED: Ninja clean
# would delete them without a build-time command to recreate them. Track them
# as configure dependencies so a missing output also causes CMake to regenerate it.
set_property(
DIRECTORY APPEND PROPERTY CMAKE_CONFIGURE_DEPENDS
"${MGC_SPATIAL_RGB_ASM}"
"${MGC_RAISR_ASM}"
"${MGC_RAISR_TABLES_ASM}"
"${MGC_POLYSHARP_ASM}"
@@ -316,7 +277,6 @@ add_library(my-native-lib SHARED
lut_processor.cpp
dcp_parser.cpp
mgc_denoise_static/mgc_halide_runtime.cpp
mgc_denoise_static/mgc_spatial_rgb_merge_jni.cpp
raw_float_texture_transfer_jni.cpp
mgc_denoise_static/mgc_raisr_jni.cpp
mgc_denoise_static/mgc_raisr_driver.cpp
@@ -324,7 +284,6 @@ add_library(my-native-lib SHARED
"${MGC_RAISR_ASM}"
"${MGC_RAISR_TABLES_ASM}"
"${MGC_POLYSHARP_ASM}"
"${MGC_SPATIAL_RGB_ASM}"
${LIBRAW_SOURCES}
${ADOBE_DNG_SOURCES}
)
@@ -1,377 +0,0 @@
#include <android/log.h>
#include <jni.h>
#include <algorithm>
#include <array>
#include <cmath>
#include <cstddef>
#include <cstdint>
#include <cstring>
#include <limits>
#include <vector>
namespace {
constexpr char kTag[] = "PLog_MgcSpatialRgbAot";
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);
constexpr HalideType kUInt8 = {1, 8, 1};
constexpr HalideType kUInt16 = {1, 16, 1};
constexpr HalideType kUInt64 = {1, 64, 1};
constexpr HalideType kFloat16 = {2, 16, 1};
constexpr HalideType kFloat32 = {2, 32, 1};
constexpr int32_t Camera2CfaToMgcBayerPattern(int cfa_pattern) {
switch (cfa_pattern) {
case 0:
return 1; // RGGB
case 1:
return 3; // GRBG
case 2:
return 4; // GBRG
case 3:
return 2; // BGGR
default:
return 0;
}
}
HalideBuffer MakeBuffer(
void* host,
HalideType type,
const HalideDimension* dimensions,
int dimension_count) {
HalideBuffer buffer = {};
buffer.host = static_cast<uint8_t*>(host);
buffer.type = type;
buffer.dimensions = dimension_count;
buffer.dim = dimensions;
return buffer;
}
bool CopyFloatArray(
JNIEnv* env,
jfloatArray source,
int expected_size,
std::vector<float>* output,
bool require_positive) {
if (source == nullptr || env->GetArrayLength(source) != expected_size) return false;
output->resize(expected_size);
env->GetFloatArrayRegion(source, 0, expected_size, output->data());
if (env->ExceptionCheck()) return false;
return std::all_of(output->begin(), output->end(), [require_positive](float value) {
return std::isfinite(value) && (!require_positive || value > 0.0f);
});
}
bool CheckedProduct(std::initializer_list<int64_t> factors, int64_t* result) {
int64_t value = 1;
for (const int64_t factor : factors) {
if (factor <= 0 || value > std::numeric_limits<int64_t>::max() / factor) return false;
value *= factor;
}
*result = value;
return true;
}
} // namespace
// Exact generated ABI at MGC 9.7.047 V25 libgcastartup.so+0x371990c.
extern "C" int photon_mgc_merge_rgb_raw16_f16_tile16_halide(
void* user_context,
int32_t bayer_pattern,
HalideBuffer* base_frame,
HalideBuffer* burst_ptrs,
HalideBuffer* alignment,
HalideBuffer* rejection_masks,
HalideBuffer* frame_weights,
HalideBuffer* wb_gains,
HalideBuffer* input_black_levels_rgb,
HalideBuffer* input_black_levels_rggb,
HalideBuffer* input_gains,
float overall_gain,
float merge_sharpness,
HalideBuffer* kernel_sigmas,
int32_t output_width,
int32_t output_height,
HalideBuffer* output);
extern "C" JNIEXPORT jint JNICALL
Java_com_hinnka_mycamera_processor_MgcSpatialRgbMerger_nativeMerge(
JNIEnv* env,
jobject,
jobjectArray raw_buffers,
jintArray raw_offsets_array,
jintArray raw_row_strides_array,
jobject alignment_buffer,
jint alignment_width,
jint alignment_height,
jobject rejection_buffer,
jint rejection_width,
jint rejection_height,
jfloatArray frame_weights_array,
jfloatArray wb_gains_array,
jfloatArray input_black_levels_rgb_array,
jfloatArray input_black_levels_rggb_array,
jfloatArray input_gains_array,
jfloat overall_gain,
jfloat merge_sharpness,
jfloatArray kernel_sigmas_array,
jint raw_width,
jint raw_height,
jint output_width,
jint output_height,
jint output_storage_width,
jint output_storage_height,
jint cfa_pattern,
jobject output_buffer) {
const int32_t mgc_pattern = Camera2CfaToMgcBayerPattern(cfa_pattern);
const int frame_count = raw_buffers != nullptr
? env->GetArrayLength(raw_buffers)
: 0;
const int64_t expected_alignment_width =
(static_cast<int64_t>(output_width) + 15) / 16;
const int64_t expected_alignment_height =
(static_cast<int64_t>(output_height) + 15) / 16;
// V25's rejection slices describe complete RAW/4 cells, not padded output
// storage. MergeRgb clamps sampling to the supplied rejection extents.
const int64_t expected_rejection_width = raw_width / 4;
const int64_t expected_rejection_height = raw_height / 4;
if (frame_count <= 0 || raw_offsets_array == nullptr ||
raw_row_strides_array == nullptr || alignment_buffer == nullptr ||
rejection_buffer == nullptr || output_buffer == nullptr ||
env->GetArrayLength(raw_offsets_array) != frame_count ||
env->GetArrayLength(raw_row_strides_array) != frame_count ||
raw_width <= 0 || raw_height <= 0 || output_width <= 0 ||
output_height <= 0 || output_storage_width <= 0 ||
output_storage_height <= 0 || (output_storage_width & 15) != 0 ||
(output_storage_height & 15) != 0 ||
output_storage_width != expected_alignment_width * 16 ||
output_storage_height != expected_alignment_height * 16 ||
alignment_width != expected_alignment_width ||
alignment_height != expected_alignment_height ||
rejection_width != expected_rejection_width ||
rejection_height != expected_rejection_height || mgc_pattern == 0 ||
!std::isfinite(overall_gain) || overall_gain <= 0.0f ||
!std::isfinite(merge_sharpness) || merge_sharpness < 0.0f) {
return -1;
}
int64_t raw_pixel_count = 0;
int64_t output_sample_count = 0;
int64_t alignment_sample_count = 0;
int64_t rejection_sample_count = 0;
if (!CheckedProduct({raw_width, raw_height}, &raw_pixel_count) ||
!CheckedProduct(
{output_storage_width, output_storage_height, 3},
&output_sample_count) ||
!CheckedProduct(
{alignment_width, alignment_height, frame_count, 2},
&alignment_sample_count) ||
!CheckedProduct(
{rejection_width, rejection_height, frame_count},
&rejection_sample_count) ||
raw_pixel_count > static_cast<int64_t>(
std::numeric_limits<size_t>::max() / sizeof(uint16_t))) {
return -1;
}
auto* alignment = static_cast<float*>(env->GetDirectBufferAddress(alignment_buffer));
auto* rejection = static_cast<uint8_t*>(env->GetDirectBufferAddress(rejection_buffer));
auto* output = static_cast<uint16_t*>(env->GetDirectBufferAddress(output_buffer));
if (alignment == nullptr || rejection == nullptr || output == nullptr ||
env->GetDirectBufferCapacity(alignment_buffer) <
alignment_sample_count * static_cast<int64_t>(sizeof(float)) ||
env->GetDirectBufferCapacity(rejection_buffer) < rejection_sample_count ||
env->GetDirectBufferCapacity(output_buffer) <
output_sample_count * static_cast<int64_t>(sizeof(uint16_t))) {
return -1;
}
std::vector<jint> raw_offsets(frame_count);
std::vector<jint> raw_row_strides(frame_count);
env->GetIntArrayRegion(raw_offsets_array, 0, frame_count, raw_offsets.data());
env->GetIntArrayRegion(
raw_row_strides_array,
0,
frame_count,
raw_row_strides.data());
if (env->ExceptionCheck()) return -1;
// Camera2 RAW planes are normally tight. Point the AOT directly at those direct buffers and
// allocate a packed copy only for the uncommon padded-row plane; copying the whole burst would
// otherwise duplicate hundreds of megabytes before Halide starts.
std::vector<std::vector<uint16_t>> packed_raw(frame_count);
std::vector<uint64_t> burst_ptrs(frame_count);
for (int frame = 0; frame < frame_count; ++frame) {
jobject raw_buffer = env->GetObjectArrayElement(raw_buffers, frame);
if (raw_buffer == nullptr) return -1;
auto* raw_base = static_cast<uint8_t*>(env->GetDirectBufferAddress(raw_buffer));
const int64_t raw_capacity = env->GetDirectBufferCapacity(raw_buffer);
const int64_t offset = raw_offsets[frame];
const int64_t row_stride = raw_row_strides[frame];
const int64_t required = offset +
static_cast<int64_t>(raw_height - 1) * row_stride +
static_cast<int64_t>(raw_width) * sizeof(uint16_t);
if (raw_base == nullptr || offset < 0 || (offset & 1LL) != 0 ||
row_stride < raw_width * 2LL ||
required > raw_capacity) {
env->DeleteLocalRef(raw_buffer);
return -1;
}
uint16_t* destination = nullptr;
if (row_stride == raw_width * static_cast<int64_t>(sizeof(uint16_t))) {
destination = reinterpret_cast<uint16_t*>(raw_base + offset);
} else {
packed_raw[frame].resize(static_cast<size_t>(raw_pixel_count));
destination = packed_raw[frame].data();
for (int y = 0; y < raw_height; ++y) {
std::memcpy(
destination + static_cast<int64_t>(y) * raw_width,
raw_base + offset + static_cast<int64_t>(y) * row_stride,
static_cast<size_t>(raw_width) * sizeof(uint16_t));
}
}
burst_ptrs[frame] = reinterpret_cast<uint64_t>(destination);
env->DeleteLocalRef(raw_buffer);
}
std::vector<float> frame_weights;
std::vector<float> wb_gains;
std::vector<float> black_rgb;
std::vector<float> black_rggb;
std::vector<float> input_gains;
std::vector<float> kernel_sigmas;
if (!CopyFloatArray(env, frame_weights_array, frame_count, &frame_weights, true) ||
!CopyFloatArray(env, wb_gains_array, 4, &wb_gains, true) ||
!CopyFloatArray(env, input_black_levels_rgb_array, 3, &black_rgb, false) ||
!CopyFloatArray(env, input_black_levels_rggb_array, 4, &black_rggb, false) ||
!CopyFloatArray(env, input_gains_array, frame_count, &input_gains, true) ||
!CopyFloatArray(env, kernel_sigmas_array, frame_count, &kernel_sigmas, true)) {
return -1;
}
const int32_t alignment_plane_stride = alignment_width * alignment_height;
const int32_t rejection_plane_stride = rejection_width * rejection_height;
const int32_t output_plane_stride = output_storage_width * output_storage_height;
const HalideDimension raw_dimensions[2] = {
{0, raw_width, 1, 0},
{0, raw_height, raw_width, 0},
};
const HalideDimension burst_dimensions[1] = {{0, frame_count, 1, 0}};
const HalideDimension alignment_dimensions[4] = {
{0, alignment_width, 1, 0},
{0, alignment_height, alignment_width, 0},
{0, frame_count, alignment_plane_stride, 0},
{0, 2, alignment_plane_stride * frame_count, 0},
};
const HalideDimension rejection_dimensions[3] = {
{0, rejection_width, 1, 0},
{0, rejection_height, rejection_width, 0},
{0, frame_count, rejection_plane_stride, 0},
};
const HalideDimension frame_dimensions[1] = {{0, frame_count, 1, 0}};
const HalideDimension wb_dimensions[1] = {{0, 4, 1, 0}};
const HalideDimension rgb_dimensions[1] = {{0, 3, 1, 0}};
const HalideDimension rggb_dimensions[1] = {{0, 4, 1, 0}};
// The generated schedule constrains the output buffer extents to complete 16x16 tiles. Keep
// those storage extents separate from output_width/output_height: the latter are semantic
// parameters used by MGC's sampling and rejection equations.
const HalideDimension output_dimensions[3] = {
{0, output_storage_width, 1, 0},
{0, output_storage_height, output_storage_width, 0},
{0, 3, output_plane_stride, 0},
};
HalideBuffer base = MakeBuffer(
reinterpret_cast<uint16_t*>(static_cast<uintptr_t>(burst_ptrs[0])),
kUInt16,
raw_dimensions,
2);
HalideBuffer burst = MakeBuffer(
burst_ptrs.data(), kUInt64, burst_dimensions, 1);
HalideBuffer alignment_halide = MakeBuffer(
alignment, kFloat32, alignment_dimensions, 4);
HalideBuffer rejection_halide = MakeBuffer(
rejection, kUInt8, rejection_dimensions, 3);
HalideBuffer weights_halide = MakeBuffer(
frame_weights.data(), kFloat32, frame_dimensions, 1);
HalideBuffer wb_halide = MakeBuffer(
wb_gains.data(), kFloat32, wb_dimensions, 1);
HalideBuffer black_rgb_halide = MakeBuffer(
black_rgb.data(), kFloat32, rgb_dimensions, 1);
HalideBuffer black_rggb_halide = MakeBuffer(
black_rggb.data(), kFloat32, rggb_dimensions, 1);
HalideBuffer gains_halide = MakeBuffer(
input_gains.data(), kFloat32, frame_dimensions, 1);
HalideBuffer sigmas_halide = MakeBuffer(
kernel_sigmas.data(), kFloat32, frame_dimensions, 1);
HalideBuffer output_halide = MakeBuffer(
output, kFloat16, output_dimensions, 3);
const int result = photon_mgc_merge_rgb_raw16_f16_tile16_halide(
nullptr,
mgc_pattern,
&base,
&burst,
&alignment_halide,
&rejection_halide,
&weights_halide,
&wb_halide,
&black_rgb_halide,
&black_rggb_halide,
&gains_halide,
overall_gain,
merge_sharpness,
&sigmas_halide,
output_width,
output_height,
&output_halide);
if (result != 0) {
__android_log_print(
ANDROID_LOG_ERROR,
kTag,
"MergeRgbRaw16F16 failed result=%d raw=%dx%d logical=%dx%d "
"storage=%dx%d frames=%d cfa=%d",
result,
raw_width,
raw_height,
output_width,
output_height,
output_storage_width,
output_storage_height,
frame_count,
cfa_pattern);
return result;
}
return 0;
}
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,345 @@
package com.hinnka.mycamera.processor
/**
* Green reconstruction shared by two MGC Halide AOTs that contain the same `g_gb` / `g_b` Funcs:
*
* - MGC 9.6.080 V24 `gcam::ResolveSabreHalide`, whose input is the quantized Sabre colour
* ([GlesMgcSabreResolveShaders]);
* - MGC 9.7.047 V25 `gcam::DemosaicGreenRaw16Halide` (libgcastartup.so wrapper 0x38AEE1C,
* worker 0x38AA69C), which MergeRgbRaw16F16 calls per burst frame through
* DemosaicGreenRawBurst. Its input is the RAW16 frame converted by [convertRaw16].
*
* Both AOTs work in a virtual RGGB frame whose (0, 0) is the red site of the sensor CFA, so for a
* non-RGGB sensor the output is shifted by the red-site offset. Every pass writes an int16 plane
* padded by [PLANE_PADDING] on each side; the conversion pass resolves the AOT's boundary
* condition, so the green passes evaluate out-of-range sites from those padded samples exactly as
* the AOT does. The algorithm notes live in tools/mgc_sabre_resolve and tools/mgc_demosaic_green.
*
* The integer demosaic keeps the NEON lane semantics of the AOTs: 16-bit wraparound, SHADD/SRHADD
* rounding, SABD magnitudes, SQADD/SQSUB saturation and SSHL by a signed byte.
*/
internal object GlesMgcGreenDemosaicShaders {
const val PLANE_PADDING = 4
val header = """
#version 310 es
precision highp float;
precision highp int;
precision highp sampler2D;
precision highp isampler2D;
precision highp usampler2D;
""".trimIndent()
val integerOps = """
const int PLANE_PADDING = $PLANE_PADDING;
int s16(int v) { return (v << 16) >> 16; }
int u16(int v) { return v & 0xffff; }
int clz16(int x) { return x == 0 ? 16 : 15 - findMSB(x); }
int clz32(uint x) { return x == 0u ? 32 : 31 - findMSB(x); }
// SSHL .8h: the shift is the signed low byte of the lane; negative shifts are arithmetic.
int sshl16(int x, int lane) {
int s = ((lane & 0xff) << 24) >> 24;
if (s >= 0) return s >= 16 ? 0 : s16(x << s);
if (s <= -16) return x < 0 ? -1 : 0;
return x >> (-s);
}
int shadd(int a, int b) { return (a + b) >> 1; }
int srhadd(int a, int b) { return (a + b + 1) >> 1; }
int sabd(int a, int b) { return abs(a - b); }
int urhadd(int a, int b) { return (a + b + 1) >> 1; }
int sqadd(int a, int b) { return clamp(a + b, -32768, 32767); }
int sqsub(int a, int b) { return clamp(a - b, -32768, 32767); }
// Inverse-gradient pair blend. Candidate A has error dA, candidate B has error dB.
struct Ig1 {
bool aIsNear;
int shift;
};
Ig1 makeIg1(int dA, int dB) {
int hA = dA >> 1;
int hB = dB >> 1;
int total = max(u16(hA + hB), 1);
return Ig1(hB > hA, clz16(total) - clz16(min(hA, hB)));
}
int blend1(Ig1 g, int xA, int xB) {
int nearValue = g.aIsNear ? xA : xB;
int farValue = g.aIsNear ? xB : xA;
return s16(nearValue + sshl16(s16(farValue - nearValue), g.shift));
}
// Inverse-squared-cost blend; X has cost cX and Y has cost cY.
int ig2(int cX, int cY, int x, int y) {
uint sX = (uint(cX) * uint(cX)) >> 1;
uint sY = (uint(cY) * uint(cY)) >> 1;
bool xIsNear = sY > sX;
int nearValue = xIsNear ? x : y;
int farValue = xIsNear ? y : x;
uint total = max(sX + sY, 1u);
int shift = clamp(s16(clz32(total) - clz32(min(sX, sY))), -15, 15);
return s16(nearValue + sshl16(s16(farValue - nearValue), shift));
}
// Bit below the leading one: the half-step fraction of log2(x).
int log2Fraction(int x) { return sshl16(x, clz16(u16(x)) - 14) & 1; }
// Log-domain ratio correction: xWeighted * g / gWeighted in half-step powers of two.
int ratioCorrect(int xWeighted, int g, int gWeighted) {
int xp = max(xWeighted, 0);
int m = max(xp, max(gWeighted, g));
int l = s16(
log2Fraction(xp) - 2 * clz16(u16(xp)) + 2 * clz16(u16(m)) - log2Fraction(m)
);
int t = sshl16(sqsub(g, gWeighted), max(s16(l >> 1), -15));
int odd = (l & 1) != 0 ? t >> 1 : 0;
return sqadd(xWeighted, s16(odd + t));
}
int planeAt(isampler2D plane, ivec2 planeSize, int u, int v) {
ivec2 p = clamp(
ivec2(u + PLANE_PADDING, v + PLANE_PADDING),
ivec2(0),
planeSize - ivec2(1)
);
return texelFetch(plane, p, 0).r;
}
""".trimIndent()
/**
* Chroma interpolation of the AOTs' integer demosaic: colour `wantBlue ? B : R` at a site of
* the virtual RGGB frame whose native colour differs. The including shader defines
* `int converted(int u, int v)` (R/B CFA samples) and `int green(int u, int v)`.
*/
val chromaOps = """
// Chroma of colour `wantBlue ? B : R` at a site whose native colour differs.
int chroma(int u, int v, bool wantBlue) {
int nativeOffset = wantBlue ? 1 : 0;
bool sameRow = ((v - nativeOffset) & 1) == 0;
bool sameColumn = ((u - nativeOffset) & 1) == 0;
int gc = green(u, v);
if (sameRow && !sameColumn) {
Ig1 g = makeIg1(sabd(gc, green(u + 1, v)), sabd(gc, green(u - 1, v)));
int xWeighted = blend1(g, converted(u + 1, v), converted(u - 1, v));
int gWeighted = blend1(g, green(u + 1, v), green(u - 1, v));
return ratioCorrect(xWeighted, gc, gWeighted);
}
if (!sameRow && sameColumn) {
Ig1 g = makeIg1(sabd(gc, green(u, v + 1)), sabd(gc, green(u, v - 1)));
int xWeighted = blend1(g, converted(u, v + 1), converted(u, v - 1));
int gWeighted = blend1(g, green(u, v + 1), green(u, v - 1));
return ratioCorrect(xWeighted, gc, gWeighted);
}
int center = converted(u, v);
int topLeft = converted(u - 1, v - 1);
int topRight = converted(u + 1, v - 1);
int bottomLeft = converted(u - 1, v + 1);
int bottomRight = converted(u + 1, v + 1);
Ig1 g1 = makeIg1(sabd(gc, green(u + 1, v - 1)), sabd(gc, green(u - 1, v + 1)));
int x1 = ratioCorrect(
blend1(g1, topRight, bottomLeft),
gc,
blend1(g1, green(u + 1, v - 1), green(u - 1, v + 1))
);
Ig1 g2 = makeIg1(sabd(gc, green(u + 1, v + 1)), sabd(gc, green(u - 1, v - 1)));
int x2 = ratioCorrect(
blend1(g2, bottomRight, topLeft),
gc,
blend1(g2, green(u + 1, v + 1), green(u - 1, v - 1))
);
int cost2 = urhadd(sabd(center, topLeft), sabd(center, bottomRight));
int cost1 = urhadd(sabd(center, bottomLeft), sabd(center, topRight));
return ig2(cost2, cost1, x2, x1);
}
""".trimIndent()
/**
* RAW16 access shared by DemosaicGreenRaw16 and MergeRgbRaw16F16: the sensor code at a site of
* the virtual RGGB frame under `mirror_image`, which mirrors the sensor's four colour planes
* (plane index -1 reads 0), so a virtual site outside the RAW keeps its colour, and its
* `wb_gains_applied` int16 conversion. The including shader declares uRaw, uRawSize, uRedSite,
* uBlackLevels and uConversionGains.
*/
val raw16Ops = """
// Halide mirror_image: period 2 * extent, index -1 reads 0 and extent reads extent - 1.
int mirrorIndex(int index, int extent) {
int period = 2 * extent;
// GLSL ES leaves % undefined for negative operands, so fold a non-negative index of
// the same residue.
int lifted = index < 0 ? index + period * ((period - 1 - index) / period) : index;
int folded = lifted % period;
return folded < extent ? folded : period - 1 - folded;
}
int mirrorSite(int site, int extent) {
return 2 * mirrorIndex(site >> 1, extent >> 1) + (site & 1);
}
float sensorValue(ivec2 virtualSite) {
ivec2 sensorSite = virtualSite + uRedSite;
ivec2 source = ivec2(
mirrorSite(sensorSite.x, uRawSize.x),
mirrorSite(sensorSite.y, uRawSize.y)
);
uint code = texelFetch(uRaw, source, 0).r;
// 2^23 + code is exact in binary32, so the subtraction yields float(code) exactly
// without an integer-to-float conversion a driver could lower to FP16.
return uintBitsToFloat(0x4B000000u | code) - 8388608.0;
}
// R, Gr, Gb, B index of a virtual site.
int cfaChannel(ivec2 virtualSite) {
return (virtualSite.x & 1) + 2 * (virtualSite.y & 1);
}
int saturateInt16(float value) {
return int(clamp(roundEven(value), -32768.0, 32767.0));
}
// `wb_gains_applied`; the including shader declares uBlackLevels and uConversionGains.
int convertedSample(ivec2 virtualSite) {
int channel = cfaChannel(virtualSite);
return saturateInt16(
(sensorValue(virtualSite) - uBlackLevels[channel]) * uConversionGains[channel]
);
}
""".trimIndent()
/**
* DemosaicGreenRaw16 pass 1, `wb_gains_applied` over the padded plane:
* int16(clamp(roundEven((raw - black[c]) * wb[c] * overallGain), -32768, 32767)).
*/
val convertRaw16 = """
${header.prependIndent(" ").trimStart()}
uniform highp usampler2D uRaw;
uniform ivec2 uRawSize;
uniform ivec2 uRedSite;
uniform vec4 uBlackLevels;
// whiteBalanceGains[c] * overallGain.
uniform vec4 uConversionGains;
layout(location = 0) out highp ivec4 oConverted;
${raw16Ops.prependIndent(" ").trimStart()}
void main() {
ivec2 virtualSite = ivec2(gl_FragCoord.xy) - ivec2($PLANE_PADDING);
oConverted = ivec4(convertedSample(virtualSite), 0, 0, 0);
}
""".trimIndent()
/**
* Pass 2, `g_gb`: blur = (4G + diagonal G + 4) >> 3 and
* G' = blur + (((G - blur) * k + 0x8000) >> 16), where k = 0 equalizes Gr/Gb fully.
*/
val greenBalance = """
${header.prependIndent(" ").trimStart()}
uniform highp isampler2D uConverted;
uniform ivec2 uPlaneSize;
uniform int uGreenImbalanceRetention;
layout(location = 0) out highp ivec4 oBalanced;
${integerOps.prependIndent(" ").trimStart()}
int converted(int u, int v) { return planeAt(uConverted, uPlaneSize, u, v); }
void main() {
ivec2 virtualSite = ivec2(gl_FragCoord.xy) - ivec2(PLANE_PADDING);
int u = virtualSite.x;
int v = virtualSite.y;
int g = converted(u, v);
if (((u + v) & 1) == 0) {
oBalanced = ivec4(g, 0, 0, 0);
return;
}
int total = 4 * g + converted(u - 1, v - 1) + converted(u + 1, v - 1) +
converted(u - 1, v + 1) + converted(u + 1, v + 1);
int blur = s16((total + 4) >> 3);
int difference = s16(g - blur);
int correction = s16(
int(uint(difference * uGreenImbalanceRetention) + 0x8000u) >> 16
);
oBalanced = ivec4(s16(correction + blur), 0, 0, 0);
}
""".trimIndent()
/**
* Pass 3, `g_b$1`: green at R/B sites from directional (G + C) / 2 estimates, inverse-gradient
* candidate blends, log-domain ratio correction and inverse-squared direction costs.
*/
val greenAtColor = """
${header.prependIndent(" ").trimStart()}
uniform highp isampler2D uBalanced;
uniform ivec2 uPlaneSize;
layout(location = 0) out highp ivec4 oGreen;
${integerOps.prependIndent(" ").trimStart()}
// R/B sites hold the converted value, G sites the balanced green.
int at(int u, int v) { return planeAt(uBalanced, uPlaneSize, u, v); }
void main() {
ivec2 virtualSite = ivec2(gl_FragCoord.xy) - ivec2(PLANE_PADDING);
int u = virtualSite.x;
int v = virtualSite.y;
int c = at(u, v);
if (((u + v) & 1) != 0) {
oGreen = ivec4(c, 0, 0, 0);
return;
}
int cL = at(u - 2, v);
int cR = at(u + 2, v);
int cU = at(u, v - 2);
int cD = at(u, v + 2);
int gl = at(u - 1, v);
int gr = at(u + 1, v);
int gu = at(u, v - 1);
int gd = at(u, v + 1);
int ul = at(u - 1, v - 1);
int ur = at(u + 1, v - 1);
int dl = at(u - 1, v + 1);
int dr = at(u + 1, v + 1);
int eH = srhadd(shadd(gl, gr), c);
int eR = srhadd(shadd(c, cR), gr);
int eL = srhadd(shadd(cL, c), gl);
int eV = srhadd(shadd(gu, gd), c);
int eD = srhadd(shadd(c, cD), gd);
int eU = srhadd(shadd(cU, c), gu);
Ig1 horizontal = makeIg1(sabd(eH, eR), sabd(eH, eL));
int eHWeighted = blend1(horizontal, eR, eL);
int gH = blend1(horizontal, gr, gl);
Ig1 vertical = makeIg1(sabd(eV, eD), sabd(eV, eU));
int eVWeighted = blend1(vertical, eD, eU);
int gV = blend1(vertical, gd, gu);
int cH = shadd(srhadd(gl, gr), c);
int cV = shadd(srhadd(gu, gd), c);
int eHUpDown = srhadd(
shadd(srhadd(at(u - 1, v - 2), at(u + 1, v - 2)), cU),
shadd(srhadd(at(u - 1, v + 2), at(u + 1, v + 2)), cD)
);
int eVLeftRight = srhadd(
shadd(srhadd(at(u - 2, v - 1), at(u - 2, v + 1)), cL),
shadd(srhadd(at(u + 2, v - 1), at(u + 2, v + 1)), cR)
);
int pl = shadd(srhadd(ul, dl), gl);
int pr = shadd(srhadd(ur, dr), gr);
int pu = shadd(srhadd(ul, ur), gu);
int pd = shadd(srhadd(dl, dr), gd);
// (|.| >> 2) * 9 is a wrapping 16-bit MUL then USHR #3; the sums are USRA mod 2^16.
int costA = u16(
(u16((sabd(cV, eVLeftRight) >> 2) * 9) >> 3) +
(sabd(cV, srhadd(pl, pr)) >> 3) + (sabd(pl, pr) >> 1)
);
int costB = u16(
(u16((sabd(cH, eHUpDown) >> 2) * 9) >> 3) +
(sabd(cH, srhadd(pu, pd)) >> 3) + (sabd(pu, pd) >> 1)
);
int greenH = ratioCorrect(gH, eH, eHWeighted);
int greenV = ratioCorrect(gV, eV, eVWeighted);
oGreen = ivec4(ig2(costB, costA, greenV, greenH), 0, 0, 0);
}
""".trimIndent()
}
@@ -1493,63 +1493,6 @@ internal object GlesMgcRawSpatialShaders {
}
""".trimIndent()
/** Converts native planar Q14 camera RGB to RGB16, without resampling before FinishRaw. */
val normalizeAotRgb16 = """
#version 300 es
precision highp float;
precision highp int;
precision highp sampler2D;
uniform sampler2D uChannelPlane;
uniform sampler2D uLensShading;
uniform sampler2D uUltrashortWeight;
uniform vec3 uCameraWhite;
uniform int uHasUltrashort;
uniform ivec2 uOutputSize;
uniform float uOutputExposureScale;
uniform int uUseLensShading;
uniform int uChannel;
layout(location = 0) out highp uvec4 oRgb16;
void main() {
ivec2 p = ivec2(gl_FragCoord.xy);
vec2 uv = (vec2(p) + vec2(0.5)) / vec2(uOutputSize);
float value = texelFetch(uChannelPlane, p, 0).r * (1.0 / 16384.0);
float channelShading = 1.0;
if (uUseLensShading != 0) {
vec4 shading = texture(uLensShading, clamp(uv, vec2(0.0), vec2(1.0)));
channelShading = uChannel == 0 ? shading.r :
(uChannel == 1 ? 0.5 * (shading.g + shading.b) : shading.a);
}
// Sensor saturation precedes lens-shading correction, so CameraWhite bounds the
// unshaded sensor-domain value and the shading gain applies to the clipped result.
// Clipping after shading would cap unsaturated off-axis samples at the reference
// white, outside the (unshaded) highlight mask the ultrashort replaces.
// CameraWhite must follow the exposures that actually supply this pixel.
// A rejected short leaves the reference's saturated RGB at 1/ratio in the
// exported short domain; clipping it later against short-domain CameraWhite
// misses the reference plateau and preserves its false magenta chroma.
// The selected short slice has weight m and unit frame weight, while the
// reference slice alone keeps (1 - m); the short's share of the merge is thus
// at most m, and the merged white is bounded by mix(referenceWhite, shortWhite, m).
// The bound must stay continuous in m: switching on m > 0 steps the cap along
// the RAW/4 weight texel grid and draws a staircase through the highlight.
float shortShare = uHasUltrashort != 0
? clamp(texture(uUltrashortWeight, uv).r, 0.0, 1.0)
: 0.0;
float whiteScale = mix(uOutputExposureScale, 1.0, shortShare);
float cameraWhite = uCameraWhite[uChannel] * whiteScale;
float outputValue =
min(value * uOutputExposureScale, cameraWhite) * channelShading;
uint encodedValue = uint(round(
clamp(outputValue, 0.0, 1.0) * 65535.0
));
// CPU-side glColorMask selects the destination RGB component for this pass.
// Avoid dynamically indexing a fragment output, which is rejected by strict ES
// compilers even though dynamically indexing an ordinary local vector is legal.
oRgb16 = uvec4(uvec3(encodedValue), 0u);
}
""".trimIndent()
/**
* First integer-to-float conversion stays in compute image load/store. Some Mali drivers
* incorrectly lower the equivalent fragment-sampler uint16 conversion to FP16.
File diff suppressed because it is too large. Load diff
@@ -1,5 +1,10 @@
package com.hinnka.mycamera.processor
import com.hinnka.mycamera.processor.GlesMgcGreenDemosaicShaders.PLANE_PADDING
import com.hinnka.mycamera.processor.GlesMgcGreenDemosaicShaders.chromaOps
import com.hinnka.mycamera.processor.GlesMgcGreenDemosaicShaders.header
import com.hinnka.mycamera.processor.GlesMgcGreenDemosaicShaders.integerOps
/**
* GLES implementation of MGC 9.6.080 V24 `gcam::ResolveSabreHalide`
* (libgcastartup.so entry 0x34A55D4, worker 0x349B1B8). The algorithm notes live in
@@ -12,6 +17,9 @@ package com.hinnka.mycamera.processor
* 1. `converted_to_int`: remosaic the dehomogenized RGBA16F colour into an int16 CFA.
* 2. `g_gb`: Gr/Gb balance at G sites; R/B sites keep their converted value.
* 3. `g_b$1`: adaptive green at R/B sites; G sites keep their balanced value.
*
* Passes 2 and 3 are the green reconstruction this AOT shares with V25's
* `gcam::DemosaicGreenRaw16Halide`; they live in [GlesMgcGreenDemosaicShaders].
* 4. `demosaic` + `output`: chroma interpolation, coverage blend, final gains and lens shading,
* written as the normalized RGBA16UI camera RGB the chroma stage consumes.
*
@@ -22,92 +30,6 @@ package com.hinnka.mycamera.processor
* SSHL by a signed byte. The float stages around it run in native binary32.
*/
internal object GlesMgcSabreResolveShaders {
const val PLANE_PADDING = 4
private val header = """
#version 310 es
precision highp float;
precision highp int;
precision highp sampler2D;
precision highp isampler2D;
""".trimIndent()
private val integerOps = """
const int PLANE_PADDING = $PLANE_PADDING;
int s16(int v) { return (v << 16) >> 16; }
int u16(int v) { return v & 0xffff; }
int clz16(int x) { return x == 0 ? 16 : 15 - findMSB(x); }
int clz32(uint x) { return x == 0u ? 32 : 31 - findMSB(x); }
// SSHL .8h: the shift is the signed low byte of the lane; negative shifts are arithmetic.
int sshl16(int x, int lane) {
int s = ((lane & 0xff) << 24) >> 24;
if (s >= 0) return s >= 16 ? 0 : s16(x << s);
if (s <= -16) return x < 0 ? -1 : 0;
return x >> (-s);
}
int shadd(int a, int b) { return (a + b) >> 1; }
int srhadd(int a, int b) { return (a + b + 1) >> 1; }
int sabd(int a, int b) { return abs(a - b); }
int urhadd(int a, int b) { return (a + b + 1) >> 1; }
int sqadd(int a, int b) { return clamp(a + b, -32768, 32767); }
int sqsub(int a, int b) { return clamp(a - b, -32768, 32767); }
// Inverse-gradient pair blend. Candidate A has error dA, candidate B has error dB.
struct Ig1 {
bool aIsNear;
int shift;
};
Ig1 makeIg1(int dA, int dB) {
int hA = dA >> 1;
int hB = dB >> 1;
int total = max(u16(hA + hB), 1);
return Ig1(hB > hA, clz16(total) - clz16(min(hA, hB)));
}
int blend1(Ig1 g, int xA, int xB) {
int nearValue = g.aIsNear ? xA : xB;
int farValue = g.aIsNear ? xB : xA;
return s16(nearValue + sshl16(s16(farValue - nearValue), g.shift));
}
// Inverse-squared-cost blend; X has cost cX and Y has cost cY.
int ig2(int cX, int cY, int x, int y) {
uint sX = (uint(cX) * uint(cX)) >> 1;
uint sY = (uint(cY) * uint(cY)) >> 1;
bool xIsNear = sY > sX;
int nearValue = xIsNear ? x : y;
int farValue = xIsNear ? y : x;
uint total = max(sX + sY, 1u);
int shift = clamp(s16(clz32(total) - clz32(min(sX, sY))), -15, 15);
return s16(nearValue + sshl16(s16(farValue - nearValue), shift));
}
// Bit below the leading one: the half-step fraction of log2(x).
int log2Fraction(int x) { return sshl16(x, clz16(u16(x)) - 14) & 1; }
// Log-domain ratio correction: xWeighted * g / gWeighted in half-step powers of two.
int ratioCorrect(int xWeighted, int g, int gWeighted) {
int xp = max(xWeighted, 0);
int m = max(xp, max(gWeighted, g));
int l = s16(
log2Fraction(xp) - 2 * clz16(u16(xp)) + 2 * clz16(u16(m)) - log2Fraction(m)
);
int t = sshl16(sqsub(g, gWeighted), max(s16(l >> 1), -15));
int odd = (l & 1) != 0 ? t >> 1 : 0;
return sqadd(xWeighted, s16(odd + t));
}
int planeAt(isampler2D plane, ivec2 planeSize, int u, int v) {
ivec2 p = clamp(
ivec2(u + PLANE_PADDING, v + PLANE_PADDING),
ivec2(0),
planeSize - ivec2(1)
);
return texelFetch(plane, p, 0).r;
}
""".trimIndent()
/** Pass 1, `converted_to_int`: int16(clamp(roundEven(c * S), -32768, 32767)). */
val convertToInt = """
${header.prependIndent(" ").trimStart()}
@@ -128,122 +50,6 @@ internal object GlesMgcSabreResolveShaders {
}
""".trimIndent()
/**
* Pass 2, `g_gb`: blur = (4G + diagonal G + 4) >> 3 and
* G' = blur + (((G - blur) * k + 0x8000) >> 16), where k = 0 equalizes Gr/Gb fully.
*/
val greenBalance = """
${header.prependIndent(" ").trimStart()}
uniform highp isampler2D uConverted;
uniform ivec2 uPlaneSize;
uniform int uGreenImbalanceRetention;
layout(location = 0) out highp ivec4 oBalanced;
${integerOps.prependIndent(" ").trimStart()}
int converted(int u, int v) { return planeAt(uConverted, uPlaneSize, u, v); }
void main() {
ivec2 virtualSite = ivec2(gl_FragCoord.xy) - ivec2(PLANE_PADDING);
int u = virtualSite.x;
int v = virtualSite.y;
int g = converted(u, v);
if (((u + v) & 1) == 0) {
oBalanced = ivec4(g, 0, 0, 0);
return;
}
int total = 4 * g + converted(u - 1, v - 1) + converted(u + 1, v - 1) +
converted(u - 1, v + 1) + converted(u + 1, v + 1);
int blur = s16((total + 4) >> 3);
int difference = s16(g - blur);
int correction = s16(
int(uint(difference * uGreenImbalanceRetention) + 0x8000u) >> 16
);
oBalanced = ivec4(s16(correction + blur), 0, 0, 0);
}
""".trimIndent()
/**
* Pass 3, `g_b$1`: green at R/B sites from directional (G + C) / 2 estimates, inverse-gradient
* candidate blends, log-domain ratio correction and inverse-squared direction costs.
*/
val greenAtColor = """
${header.prependIndent(" ").trimStart()}
uniform highp isampler2D uBalanced;
uniform ivec2 uPlaneSize;
layout(location = 0) out highp ivec4 oGreen;
${integerOps.prependIndent(" ").trimStart()}
// R/B sites hold the converted value, G sites the balanced green.
int at(int u, int v) { return planeAt(uBalanced, uPlaneSize, u, v); }
void main() {
ivec2 virtualSite = ivec2(gl_FragCoord.xy) - ivec2(PLANE_PADDING);
int u = virtualSite.x;
int v = virtualSite.y;
int c = at(u, v);
if (((u + v) & 1) != 0) {
oGreen = ivec4(c, 0, 0, 0);
return;
}
int cL = at(u - 2, v);
int cR = at(u + 2, v);
int cU = at(u, v - 2);
int cD = at(u, v + 2);
int gl = at(u - 1, v);
int gr = at(u + 1, v);
int gu = at(u, v - 1);
int gd = at(u, v + 1);
int ul = at(u - 1, v - 1);
int ur = at(u + 1, v - 1);
int dl = at(u - 1, v + 1);
int dr = at(u + 1, v + 1);
int eH = srhadd(shadd(gl, gr), c);
int eR = srhadd(shadd(c, cR), gr);
int eL = srhadd(shadd(cL, c), gl);
int eV = srhadd(shadd(gu, gd), c);
int eD = srhadd(shadd(c, cD), gd);
int eU = srhadd(shadd(cU, c), gu);
Ig1 horizontal = makeIg1(sabd(eH, eR), sabd(eH, eL));
int eHWeighted = blend1(horizontal, eR, eL);
int gH = blend1(horizontal, gr, gl);
Ig1 vertical = makeIg1(sabd(eV, eD), sabd(eV, eU));
int eVWeighted = blend1(vertical, eD, eU);
int gV = blend1(vertical, gd, gu);
int cH = shadd(srhadd(gl, gr), c);
int cV = shadd(srhadd(gu, gd), c);
int eHUpDown = srhadd(
shadd(srhadd(at(u - 1, v - 2), at(u + 1, v - 2)), cU),
shadd(srhadd(at(u - 1, v + 2), at(u + 1, v + 2)), cD)
);
int eVLeftRight = srhadd(
shadd(srhadd(at(u - 2, v - 1), at(u - 2, v + 1)), cL),
shadd(srhadd(at(u + 2, v - 1), at(u + 2, v + 1)), cR)
);
int pl = shadd(srhadd(ul, dl), gl);
int pr = shadd(srhadd(ur, dr), gr);
int pu = shadd(srhadd(ul, ur), gu);
int pd = shadd(srhadd(dl, dr), gd);
// (|.| >> 2) * 9 is a wrapping 16-bit MUL then USHR #3; the sums are USRA mod 2^16.
int costA = u16(
(u16((sabd(cV, eVLeftRight) >> 2) * 9) >> 3) +
(sabd(cV, srhadd(pl, pr)) >> 3) + (sabd(pl, pr) >> 1)
);
int costB = u16(
(u16((sabd(cH, eHUpDown) >> 2) * 9) >> 3) +
(sabd(cH, srhadd(pu, pd)) >> 3) + (sabd(pu, pd) >> 1)
);
int greenH = ratioCorrect(gH, eH, eHWeighted);
int greenV = ratioCorrect(gV, eV, eVWeighted);
oGreen = ivec4(ig2(costB, costA, greenV, greenH), 0, 0, 0);
}
""".trimIndent()
/**
* Pass 4, `demosaic` + `output`. The coverage weight blends the accumulated colour toward the
* demosaic; the result times the final gains and the lens shading is the black-free camera RGB,
@@ -271,45 +77,7 @@ internal object GlesMgcSabreResolveShaders {
int converted(int u, int v) { return planeAt(uBalanced, uPlaneSize, u, v); }
int green(int u, int v) { return planeAt(uGreen, uPlaneSize, u, v); }
// Chroma of colour `wantBlue ? B : R` at a site whose native colour differs.
int chroma(int u, int v, bool wantBlue) {
int nativeOffset = wantBlue ? 1 : 0;
bool sameRow = ((v - nativeOffset) & 1) == 0;
bool sameColumn = ((u - nativeOffset) & 1) == 0;
int gc = green(u, v);
if (sameRow && !sameColumn) {
Ig1 g = makeIg1(sabd(gc, green(u + 1, v)), sabd(gc, green(u - 1, v)));
int xWeighted = blend1(g, converted(u + 1, v), converted(u - 1, v));
int gWeighted = blend1(g, green(u + 1, v), green(u - 1, v));
return ratioCorrect(xWeighted, gc, gWeighted);
}
if (!sameRow && sameColumn) {
Ig1 g = makeIg1(sabd(gc, green(u, v + 1)), sabd(gc, green(u, v - 1)));
int xWeighted = blend1(g, converted(u, v + 1), converted(u, v - 1));
int gWeighted = blend1(g, green(u, v + 1), green(u, v - 1));
return ratioCorrect(xWeighted, gc, gWeighted);
}
int center = converted(u, v);
int topLeft = converted(u - 1, v - 1);
int topRight = converted(u + 1, v - 1);
int bottomLeft = converted(u - 1, v + 1);
int bottomRight = converted(u + 1, v + 1);
Ig1 g1 = makeIg1(sabd(gc, green(u + 1, v - 1)), sabd(gc, green(u - 1, v + 1)));
int x1 = ratioCorrect(
blend1(g1, topRight, bottomLeft),
gc,
blend1(g1, green(u + 1, v - 1), green(u - 1, v + 1))
);
Ig1 g2 = makeIg1(sabd(gc, green(u + 1, v + 1)), sabd(gc, green(u - 1, v - 1)));
int x2 = ratioCorrect(
blend1(g2, bottomRight, topLeft),
gc,
blend1(g2, green(u + 1, v + 1), green(u - 1, v - 1))
);
int cost2 = urhadd(sabd(center, topLeft), sabd(center, bottomRight));
int cost1 = urhadd(sabd(center, bottomLeft), sabd(center, topRight));
return ig2(cost2, cost1, x2, x1);
}
${chromaOps.prependIndent(" ").trimStart()}
void main() {
ivec2 site = ivec2(gl_FragCoord.xy);
@@ -0,0 +1,243 @@
package com.hinnka.mycamera.processor
import com.hinnka.mycamera.processor.GlesMgcGreenDemosaicShaders.PLANE_PADDING
import com.hinnka.mycamera.processor.GlesMgcGreenDemosaicShaders.chromaOps
import com.hinnka.mycamera.processor.GlesMgcGreenDemosaicShaders.integerOps
import com.hinnka.mycamera.processor.GlesMgcGreenDemosaicShaders.raw16Ops
/**
* GLES implementation of MGC 9.7.047 V25 `gcam::MergeRgbRaw16F16TileSize16Halide`
* (libgcastartup.so wrapper 0x371990C, worker 0x370F514). The algorithm notes live in
* tools/mgc_demosaic_green/MERGE.md.
*
* Everything runs in the virtual RGGB frame whose (0, 0) is the sensor's red site. Per burst frame
* f and 16x16 output tile T with alignment a (Bayer quads), the AOT
*
* 1. gathers the frame at the quad-aligned offset d = 2 * roundEven(a) (UnpackAlignedRaw), with the
* RAW mirrored per colour plane and the DemosaicGreenRaw16 output mirrored per pixel;
* 2. demosaics it with the integer chroma interpolation it shares with ResolveSabre, on the
* same `wb_gains_applied` int16(roundEven(wb[c] * overallGain * (raw - black[c]))) as
* DemosaicGreenRaw16, and divides by the white balance;
* 3. resamples it by the sub-quad remainder r = 2a - d with a 3x3 Gaussian
* w(i, j) = exp(-0.5 * ((i - r.x)^2 + (j - r.y)^2) * sigma_f^2);
* 4. weights it by frameWeight_f times the RAW/4 acceptance, bilinearly upsampled with half-pixel
* centres, and accumulates sum(R * inputGain_f * resampled) and sum(R * sum(w)).
*
* [resolve] divides the sums and applies the output normalization. Everything outside the
* integer demosaic runs in native binary32.
*/
internal object GlesMgcSpatialRgbMergeShaders {
const val TILE_SIZE = 16
// TILE_SIZE plus the one-pixel ring the 3x3 resampling reads.
private const val TILE_SPAN = 18
/**
* One burst frame into the four R32F accumulators. A work group owns one output tile: its 64
* invocations demosaic the tile's aligned 18x18 neighbourhood into shared memory, then each
* accumulates a 2x2 block of output pixels.
*/
val accumulateFrame = """
#version 310 es
layout(local_size_x = 8, local_size_y = 8) in;
precision highp float;
precision highp int;
precision highp sampler2D;
precision highp isampler2D;
precision highp usampler2D;
precision highp image2D;
uniform highp usampler2D uRaw;
uniform ivec2 uRawSize;
uniform ivec2 uRedSite;
uniform vec4 uBlackLevels;
// whiteBalanceGains[c] * overallGain.
uniform vec4 uConversionGains;
// DemosaicGreenRaw16 output of this frame, padded by PLANE_PADDING.
uniform highp isampler2D uGreen;
uniform highp sampler2D uAlignmentAtlas;
uniform ivec2 uAlignmentOriginX;
uniform ivec2 uAlignmentOriginY;
uniform highp sampler2D uRejectionAtlas;
uniform ivec2 uRejectionOrigin;
uniform ivec2 uRejectionSize;
// inputGain / white balance of R, G, B.
uniform vec3 uChannelScale;
uniform float uFrameWeight;
uniform float uKernelSigma;
uniform int uFirstFrame;
layout(r32f, binding = 0) uniform highp image2D uSumRed;
layout(r32f, binding = 1) uniform highp image2D uSumGreen;
layout(r32f, binding = 2) uniform highp image2D uSumBlue;
layout(r32f, binding = 3) uniform highp image2D uWeightSum;
const int TILE_SIZE = $TILE_SIZE;
const int TILE_SPAN = $TILE_SPAN;
shared int sRed[$TILE_SPAN * $TILE_SPAN];
shared int sGreen[$TILE_SPAN * $TILE_SPAN];
shared int sBlue[$TILE_SPAN * $TILE_SPAN];
${integerOps.prependIndent(" ").trimStart()}
${raw16Ops.prependIndent(" ").trimStart()}
int converted(int u, int v) { return convertedSample(ivec2(u, v)); }
// The gathered DemosaicGreenRaw16 output mirrors per pixel (index -1 reads 0).
int green(int u, int v) {
ivec2 p = ivec2(mirrorIndex(u, uRawSize.x), mirrorIndex(v, uRawSize.y));
return texelFetch(uGreen, p + ivec2(PLANE_PADDING), 0).r;
}
${chromaOps.prependIndent(" ").trimStart()}
// Quad-aligned shift d = 2 * roundEven(a) of the tile's alignment, and the remainder 2a - d.
void tileShift(ivec2 tile, out ivec2 shift, out vec2 remainder) {
vec2 alignment = vec2(
texelFetch(uAlignmentAtlas, uAlignmentOriginX + tile, 0).r,
texelFetch(uAlignmentAtlas, uAlignmentOriginY + tile, 0).r
);
shift = 2 * ivec2(roundEven(alignment));
remainder = 2.0 * alignment - vec2(shift);
}
// Bilinear 4x upsampling with half-pixel centres: pixel 4j + k lies at RAW/4 coordinate
// j + (2k - 3) / 8, so its second source cell carries (2k + 5) & 7 eighths.
int acceptanceCell(int p) { return (p >> 2) - 1 + ((p & 3) >= 2 ? 1 : 0); }
float acceptanceFraction(int p) { return float((2 * (p & 3) + 5) & 7) * 0.125; }
float acceptanceAt(int x, int y) {
ivec2 cell = clamp(ivec2(x, y), ivec2(0), uRejectionSize - ivec2(1));
return texelFetch(uRejectionAtlas, uRejectionOrigin + cell, 0).r;
}
// frameWeight times the upsampled acceptance.
float acceptance(ivec2 p) {
int x0 = acceptanceCell(p.x);
int y0 = acceptanceCell(p.y);
float fx = acceptanceFraction(p.x);
float top = mix(acceptanceAt(x0, y0), acceptanceAt(x0 + 1, y0), fx);
float bottom = mix(acceptanceAt(x0, y0 + 1), acceptanceAt(x0 + 1, y0 + 1), fx);
return uFrameWeight * mix(top, bottom, acceptanceFraction(p.y));
}
void loadTile(ivec2 origin) {
int lane = int(gl_LocalInvocationIndex);
for (int index = lane; index < TILE_SPAN * TILE_SPAN; index += 64) {
int u = origin.x + index % TILE_SPAN;
int v = origin.y + index / TILE_SPAN;
int cfaColor = (u & 1) + (v & 1);
sRed[index] = cfaColor == 0 ? converted(u, v) : chroma(u, v, false);
sGreen[index] = green(u, v);
sBlue[index] = cfaColor == 2 ? converted(u, v) : chroma(u, v, true);
}
}
void accumulateTile(ivec2 tile, vec2 remainder) {
float sigmaSquared = uKernelSigma * uKernelSigma;
float weights[9];
float weightTotal = 0.0;
for (int j = 0; j < 3; ++j) {
for (int i = 0; i < 3; ++i) {
vec2 d = vec2(i - 1, j - 1) - remainder;
float w = exp(-0.5 * dot(d, d) * sigmaSquared);
weights[j * 3 + i] = w;
weightTotal += w;
}
}
for (int by = 0; by < 2; ++by) {
for (int bx = 0; bx < 2; ++bx) {
ivec2 local = 2 * ivec2(gl_LocalInvocationID.xy) + ivec2(bx, by);
ivec2 p = tile * TILE_SIZE + local;
if (p.x >= uRawSize.x || p.y >= uRawSize.y) continue;
vec3 resampled = vec3(0.0);
for (int j = 0; j < 3; ++j) {
for (int i = 0; i < 3; ++i) {
int index = (local.y + j) * TILE_SPAN + local.x + i;
resampled += weights[j * 3 + i] *
vec3(sRed[index], sGreen[index], sBlue[index]);
}
}
float accepted = acceptance(p);
vec3 color = accepted * uChannelScale * resampled;
float weightSum = accepted * weightTotal;
if (uFirstFrame == 0) {
color += vec3(
imageLoad(uSumRed, p).r,
imageLoad(uSumGreen, p).r,
imageLoad(uSumBlue, p).r
);
weightSum += imageLoad(uWeightSum, p).r;
}
imageStore(uSumRed, p, vec4(color.r, 0.0, 0.0, 0.0));
imageStore(uSumGreen, p, vec4(color.g, 0.0, 0.0, 0.0));
imageStore(uSumBlue, p, vec4(color.b, 0.0, 0.0, 0.0));
imageStore(uWeightSum, p, vec4(weightSum, 0.0, 0.0, 0.0));
}
}
}
void main() {
ivec2 tile = ivec2(gl_WorkGroupID.xy);
ivec2 shift;
vec2 remainder;
tileShift(tile, shift, remainder);
loadTile(tile * TILE_SIZE + shift - ivec2(1));
barrier();
accumulateTile(tile, remainder);
}
""".trimIndent()
/**
* The merged ratio sum / weight (Q14 scale) followed by the output normalization: exposure
* scale, CameraWhite bound, lens shading and RGB16 encoding.
*/
val resolve = """
#version 310 es
precision highp float;
precision highp int;
precision highp sampler2D;
uniform highp sampler2D uSumRed;
uniform highp sampler2D uSumGreen;
uniform highp sampler2D uSumBlue;
uniform highp sampler2D uWeightSum;
// RGGB gains of the lens shading map; a 1x1 map of ones when the capture has none.
uniform highp sampler2D uLensShading;
uniform sampler2D uUltrashortWeight;
uniform vec3 uCameraWhite;
uniform int uHasUltrashort;
uniform ivec2 uOutputSize;
uniform float uOutputExposureScale;
layout(location = 0) out highp uvec4 oRgb16;
void main() {
ivec2 p = ivec2(gl_FragCoord.xy);
vec2 uv = (vec2(p) + vec2(0.5)) / vec2(uOutputSize);
vec3 sums = vec3(
texelFetch(uSumRed, p, 0).r,
texelFetch(uSumGreen, p, 0).r,
texelFetch(uSumBlue, p, 0).r
);
vec3 merged = sums / (texelFetch(uWeightSum, p, 0).r * 16384.0);
vec4 map = texture(uLensShading, uv);
vec3 shading = vec3(map.r, 0.5 * (map.g + map.b), map.a);
// Sensor saturation precedes lens-shading correction, so CameraWhite bounds the
// unshaded sensor-domain value and the shading gain applies to the clipped result.
// Clipping after shading would cap unsaturated off-axis samples at the reference
// white, outside the (unshaded) highlight mask the ultrashort replaces.
// CameraWhite must follow the exposures that actually supply this pixel.
// A rejected short leaves the reference's saturated RGB at 1/ratio in the
// exported short domain; clipping it later against short-domain CameraWhite
// misses the reference plateau and preserves its false magenta chroma.
// The selected short slice has weight m and unit frame weight, while the
// reference slice alone keeps (1 - m); the short's share of the merge is thus
// at most m, and the merged white is bounded by mix(referenceWhite, shortWhite, m).
// The bound must stay continuous in m: switching on m > 0 steps the cap along
// the RAW/4 weight texel grid and draws a staircase through the highlight.
float shortShare = uHasUltrashort != 0
? clamp(texture(uUltrashortWeight, uv).r, 0.0, 1.0)
: 0.0;
float whiteScale = mix(uOutputExposureScale, 1.0, shortShare);
vec3 outputValue =
min(merged * uOutputExposureScale, uCameraWhite * whiteScale) * shading;
oRgb16 = uvec4(uvec3(round(clamp(outputValue, 0.0, 1.0) * 65535.0)), 0u);
}
""".trimIndent()
}
@@ -7,9 +7,6 @@ internal data class MgcSpatialDiagnosticGeometry(
val alignmentHeight: Int,
val rejectionWidth: Int,
val rejectionHeight: Int,
val fixed16Width: Int,
val fixed16Height: Int,
val fixed16SampleCount: Long,
)
/** Exact host geometry required by the lifted Bayer/RGB Spatial noise-model AOT kernels. */
@@ -21,17 +18,6 @@ internal fun mgcSpatialDiagnosticGeometry(
require(imageWidth >= 4 && imageHeight >= 4)
val isBayer = outputMode == MgcSpatialOutputMode.BAYER
val alignmentTileSize = if (isBayer) 8 else 16
val fixed16Width = if (isBayer) {
ceilDiv(imageWidth, 16) * 8
} else {
ceilDiv(imageWidth, 16) * 16
}
val fixed16Height = if (isBayer) {
ceilDiv(imageHeight, 16) * 8
} else {
ceilDiv(imageHeight, 16) * 16
}
val fixed16Channels = if (isBayer) 4L else 3L
return MgcSpatialDiagnosticGeometry(
imageWidth = imageWidth,
imageHeight = imageHeight,
@@ -42,9 +28,6 @@ internal fun mgcSpatialDiagnosticGeometry(
// acceptance domain up makes the RGB atlas read past every source slice.
rejectionWidth = imageWidth / 4,
rejectionHeight = imageHeight / 4,
fixed16Width = fixed16Width,
fixed16Height = fixed16Height,
fixed16SampleCount = fixed16Width.toLong() * fixed16Height * fixed16Channels,
)
}
@@ -1,102 +0,0 @@
package com.hinnka.mycamera.processor
import java.nio.ByteBuffer
/**
* JNI boundary for MGC 9.7.047 V25's original Spatial RGB merge AOT.
*
* `outputWidth`/`outputHeight` are the logical AOT image geometry used by the merge equations;
* `outputStorageWidth`/`outputStorageHeight` describe only the 16x16-aligned Halide allocation.
*/
internal object MgcSpatialRgbMerger {
init {
System.loadLibrary("my-native-lib")
}
fun merge(
rawBuffers: Array<ByteBuffer>,
rawOffsets: IntArray,
rawRowStrides: IntArray,
alignment: ByteBuffer,
alignmentWidth: Int,
alignmentHeight: Int,
rejection: ByteBuffer,
rejectionWidth: Int,
rejectionHeight: Int,
frameWeights: FloatArray,
whiteBalanceGains: FloatArray,
inputBlackLevelsRgb: FloatArray,
inputBlackLevelsRggb: FloatArray,
inputGains: FloatArray,
overallGain: Float,
mergeSharpness: Float,
kernelSigmas: FloatArray,
rawWidth: Int,
rawHeight: Int,
outputWidth: Int,
outputHeight: Int,
outputStorageWidth: Int,
outputStorageHeight: Int,
cfaPattern: Int,
outputPlanarF16: ByteBuffer,
) {
val result = nativeMerge(
rawBuffers,
rawOffsets,
rawRowStrides,
alignment,
alignmentWidth,
alignmentHeight,
rejection,
rejectionWidth,
rejectionHeight,
frameWeights,
whiteBalanceGains,
inputBlackLevelsRgb,
inputBlackLevelsRggb,
inputGains,
overallGain,
mergeSharpness,
kernelSigmas,
rawWidth,
rawHeight,
outputWidth,
outputHeight,
outputStorageWidth,
outputStorageHeight,
cfaPattern,
outputPlanarF16,
)
check(result == 0) { "MGC MergeRgbRaw16F16 failed with status=$result" }
outputPlanarF16.position(0)
outputPlanarF16.limit(outputPlanarF16.capacity())
}
private external fun nativeMerge(
rawBuffers: Array<ByteBuffer>,
rawOffsets: IntArray,
rawRowStrides: IntArray,
alignment: ByteBuffer,
alignmentWidth: Int,
alignmentHeight: Int,
rejection: ByteBuffer,
rejectionWidth: Int,
rejectionHeight: Int,
frameWeights: FloatArray,
whiteBalanceGains: FloatArray,
inputBlackLevelsRgb: FloatArray,
inputBlackLevelsRggb: FloatArray,
inputGains: FloatArray,
overallGain: Float,
mergeSharpness: Float,
kernelSigmas: FloatArray,
rawWidth: Int,
rawHeight: Int,
outputWidth: Int,
outputHeight: Int,
outputStorageWidth: Int,
outputStorageHeight: Int,
cfaPattern: Int,
outputPlanarF16: ByteBuffer,
): Int
}
@@ -62,33 +62,5 @@ internal fun createMgcSpatialStrengthAtlasLayout(
}
}
internal data class MgcSpatialStrengthPackDispatch(
val groupsX: Int,
val groupsY: Int,
)
internal fun createMgcSpatialStrengthPackDispatch(
invocationCount: Long,
localSize: Int,
maximumGroupsX: Int,
maximumGroupsY: Int,
): MgcSpatialStrengthPackDispatch {
require(invocationCount > 0L)
require(localSize > 0 && maximumGroupsX > 0 && maximumGroupsY > 0)
val totalGroups = ceilDivPositive(invocationCount, localSize.toLong())
require(totalGroups <= maximumGroupsX.toLong() * maximumGroupsY) {
"MGC Spatial strength pack requires $totalGroups work groups, device supports " +
"${maximumGroupsX}x$maximumGroupsY"
}
val groupsX = minOf(totalGroups, maximumGroupsX.toLong()).toInt()
return MgcSpatialStrengthPackDispatch(
groupsX = groupsX,
groupsY = ceilDivPositive(totalGroups, groupsX.toLong()).toInt(),
)
}
private fun ceilDivPositive(value: Int, divisor: Int): Int =
((value.toLong() + divisor - 1L) / divisor).toInt()
private fun ceilDivPositive(value: Long, divisor: Long): Long =
(value + divisor - 1L) / divisor
@@ -1,154 +0,0 @@
package com.hinnka.mycamera.processor
/** Pack passes used for asynchronous diagnostic readback. */
internal object MgcStrengthReadbackShaders {
/** Exact RGB camera-domain signed-Q14 signal, packed after the isolated RGB merge pass. */
val RGB_FIXED16_FRAGMENT = """
#version 300 es
precision highp float;
precision highp int;
uniform highp sampler2D uColorAndRWeight;
uniform highp sampler2D uGbWeights;
uniform int uChannel;
uniform vec3 uCameraDomainScale;
uniform ivec2 uSourceSize;
layout(location = 0) out highp int oFixed16;
void main() {
ivec2 position = min(ivec2(gl_FragCoord.xy), uSourceSize - ivec2(1));
vec4 colorAndR = texelFetch(uColorAndRWeight, position, 0);
vec2 gbWeights = texelFetch(uGbWeights, position, 0).rg;
vec3 semantic = colorAndR.rgb / max(
vec3(colorAndR.a, gbWeights.x, gbWeights.y),
vec3(1.0e-8)
);
vec3 rgb = vec3(
semantic.r + semantic.g,
semantic.r,
semantic.r + semantic.b
) * uCameraDomainScale;
oFixed16 = int(round(
clamp(max(rgb[uChannel], 0.0) * 16384.0, 0.0, 32767.0)
));
}
""".trimIndent()
val FLOAT32 = """
#version 310 es
layout(local_size_x = 128) in;
precision highp float;
precision highp int;
uniform highp sampler2D uSource;
uniform ivec2 uPlaneSize;
uniform int uPlaneCount;
uniform int uAtlasColumns;
layout(std430, binding = 0) writeonly buffer OutputValues {
float values[];
};
ivec2 atlasPosition(int index) {
int planeArea = uPlaneSize.x * uPlaneSize.y;
int plane = index / planeArea;
int localIndex = index - plane * planeArea;
ivec2 local = ivec2(localIndex % uPlaneSize.x, localIndex / uPlaneSize.x);
ivec2 tile = ivec2(plane % uAtlasColumns, plane / uAtlasColumns);
return tile * uPlaneSize + local;
}
void main() {
int index = int(
gl_GlobalInvocationID.x +
gl_GlobalInvocationID.y * gl_NumWorkGroups.x * gl_WorkGroupSize.x
);
int count = uPlaneSize.x * uPlaneSize.y * uPlaneCount;
if (index >= count) return;
values[index] = texelFetch(uSource, atlasPosition(index), 0).r;
}
""".trimIndent()
val UNORM8 = """
#version 310 es
layout(local_size_x = 128) in;
precision highp float;
precision highp int;
uniform highp sampler2D uSource;
uniform ivec2 uPlaneSize;
uniform int uPlaneCount;
uniform int uAtlasColumns;
layout(std430, binding = 0) writeonly buffer OutputWords {
uint words[];
};
ivec2 atlasPosition(int index) {
int planeArea = uPlaneSize.x * uPlaneSize.y;
int plane = index / planeArea;
int localIndex = index - plane * planeArea;
ivec2 local = ivec2(localIndex % uPlaneSize.x, localIndex / uPlaneSize.x);
ivec2 tile = ivec2(plane % uAtlasColumns, plane / uAtlasColumns);
return tile * uPlaneSize + local;
}
void main() {
int wordIndex = int(
gl_GlobalInvocationID.x +
gl_GlobalInvocationID.y * gl_NumWorkGroups.x * gl_WorkGroupSize.x
);
int byteCount = uPlaneSize.x * uPlaneSize.y * uPlaneCount;
int first = wordIndex * 4;
if (first >= byteCount) return;
uint packed = 0u;
for (int lane = 0; lane < 4; ++lane) {
int index = first + lane;
if (index >= byteCount) break;
uint value = uint(round(clamp(
texelFetch(uSource, atlasPosition(index), 0).r,
0.0,
1.0
) * 255.0));
packed |= value << uint(lane * 8);
}
words[wordIndex] = packed;
}
""".trimIndent()
val SINT16 = """
#version 310 es
layout(local_size_x = 128) in;
precision highp float;
precision highp int;
uniform highp isampler2D uSource;
uniform ivec2 uPlaneSize;
uniform int uPlaneCount;
uniform int uAtlasColumns;
layout(std430, binding = 0) writeonly buffer OutputWords {
uint words[];
};
ivec2 atlasPosition(int index) {
int planeArea = uPlaneSize.x * uPlaneSize.y;
int plane = index / planeArea;
int localIndex = index - plane * planeArea;
ivec2 local = ivec2(localIndex % uPlaneSize.x, localIndex / uPlaneSize.x);
ivec2 tile = ivec2(plane % uAtlasColumns, plane / uAtlasColumns);
return tile * uPlaneSize + local;
}
void main() {
int wordIndex = int(
gl_GlobalInvocationID.x +
gl_GlobalInvocationID.y * gl_NumWorkGroups.x * gl_WorkGroupSize.x
);
int valueCount = uPlaneSize.x * uPlaneSize.y * uPlaneCount;
int first = wordIndex * 2;
if (first >= valueCount) return;
uint packed = 0u;
for (int lane = 0; lane < 2; ++lane) {
int index = first + lane;
if (index >= valueCount) break;
uint bits = uint(texelFetch(uSource, atlasPosition(index), 0).r) & 0xffffu;
packed |= bits << uint(lane * 16);
}
words[wordIndex] = packed;
}
""".trimIndent()
}
@@ -18,19 +18,6 @@ class MgcSpatialDiagnosticGeometryTest {
}
}
@Test
fun rgbFixed16PlanesCoverTheFinalCompleteAotTile() {
val geometry = mgcSpatialDiagnosticGeometry(
outputMode = MgcSpatialOutputMode.RGB,
imageWidth = 4080,
imageHeight = 3064,
)
assertEquals(4080, geometry.fixed16Width)
assertEquals(3072, geometry.fixed16Height)
assertEquals(4080L * 3072L * 3L, geometry.fixed16SampleCount)
}
@Test
fun rgbGeometryUsesOutputPixelsAndPlanarRgbSignal() {
val geometry = mgcSpatialDiagnosticGeometry(
@@ -43,9 +30,6 @@ class MgcSpatialDiagnosticGeometryTest {
assertEquals(288, geometry.alignmentHeight)
assertEquals(1530, geometry.rejectionWidth)
assertEquals(1149, geometry.rejectionHeight)
assertEquals(6128, geometry.fixed16Width)
assertEquals(4608, geometry.fixed16Height)
assertEquals(6128L * 4608L * 3L, geometry.fixed16SampleCount)
}
@Test
@@ -60,8 +44,5 @@ class MgcSpatialDiagnosticGeometryTest {
assertEquals(383, geometry.alignmentHeight)
assertEquals(1020, geometry.rejectionWidth)
assertEquals(766, geometry.rejectionHeight)
assertEquals(2040, geometry.fixed16Width)
assertEquals(1536, geometry.fixed16Height)
assertEquals(2040L * 1536L * 4L, geometry.fixed16SampleCount)
}
}
@@ -39,19 +39,4 @@ class MgcSpatialStrengthAtlasLayoutTest {
assertEquals(0, layout.originX(18))
assertEquals(13_788, layout.originY(18))
}
@Test
fun rejectionPackDispatchWrapsAcrossTheDeviceGroupCountLimit() {
val valueCount = 2_040L * 1_532L * 19L
val invocationCount = (valueCount + 3L) / 4L
val dispatch = createMgcSpatialStrengthPackDispatch(
invocationCount = invocationCount,
localSize = GlesComputeWorkGroup.LINEAR_SIZE,
maximumGroupsX = 65_535,
maximumGroupsY = 65_535,
)
assertEquals(65_535, dispatch.groupsX)
assertEquals(2, dispatch.groupsY)
}
}