feat: original SharpenTo16Bit integration

This commit is contained in:
zhoubinjia committed 2026-09-15 17:25:18 +08:00
1 parent 9c02146f90
commit d6e988505a
14 files changed
+1006 -21

No files matched your search

+40 -1
View File
@@ -113,6 +113,41 @@ set_source_files_properties(
OBJECT_DEPENDS "${MGC_SABRE_CAPSULE}"
)
set(
MGC_SHARPEN_CAPSULE
"${CMAKE_CURRENT_SOURCE_DIR}/mgc_denoise_static/mgc_sharpen_capsule.bin"
)
set(
MGC_SHARPEN_CAPSULE_SHA256
"733065cfec32ac752cc2088ea284b44a55b24a6171e5829f6971dcb098b1d7ce"
)
if(NOT EXISTS "${MGC_SHARPEN_CAPSULE}")
message(
FATAL_ERROR
"MGC SharpenTo16Bit capsule is missing; restore the tracked "
"mgc_denoise_static/mgc_sharpen_capsule.bin asset"
)
endif()
file(SHA256 "${MGC_SHARPEN_CAPSULE}" MGC_SHARPEN_CAPSULE_ACTUAL_SHA256)
if(NOT MGC_SHARPEN_CAPSULE_ACTUAL_SHA256 STREQUAL MGC_SHARPEN_CAPSULE_SHA256)
message(FATAL_ERROR "MGC SharpenTo16Bit capsule hash mismatch")
endif()
set(
MGC_SHARPEN_ASM
"${CMAKE_CURRENT_BINARY_DIR}/mgc_sharpen_static.S"
)
configure_file(
"${CMAKE_CURRENT_SOURCE_DIR}/mgc_denoise_static/mgc_sharpen_static.S.in"
"${MGC_SHARPEN_ASM}"
@ONLY
)
set_source_files_properties(
"${MGC_SHARPEN_ASM}"
PROPERTIES
GENERATED TRUE
OBJECT_DEPENDS "${MGC_SHARPEN_CAPSULE}"
)
set(
MGC_SPATIAL_RGB_CAPSULE
"${CMAKE_CURRENT_SOURCE_DIR}/mgc_denoise_static/mgc_spatial_rgb_merge_capsule.bin"
@@ -269,6 +304,8 @@ add_library(my-native-lib SHARED
mgc_denoise_static/mgc_sabre_resolve_jni.cpp
mgc_denoise_static/mgc_spatial_rgb_merge_jni.cpp
mgc_denoise_static/mgc_spatial_strength_jni.cpp
mgc_denoise_static/mgc_sharpen_jni.cpp
"${MGC_SHARPEN_ASM}"
"${MGC_DENOISE_ASM}"
"${MGC_DEMOIRE_ASM}"
"${MGC_SABRE_ASM}"
@@ -305,9 +342,11 @@ set_source_files_properties(
)
# RAW signal statistics define MGC's physical tuning coordinate, while PGTM validation must
# reliably reject non-finite values. Keep both independent of target-wide fast-math.
# reliably reject non-finite values. The sharpen adapter must preserve separate matrix
# multiply/adds and nearest-even U12 rounding. Keep these independent of fast-math.
set_source_files_properties(
raw_signal_stats_jni.cpp
mgc_denoise_static/mgc_sharpen_jni.cpp
PROPERTIES
COMPILE_OPTIONS "-fno-fast-math;-ffp-contract=off"
)
@@ -137,6 +137,13 @@ using YuvToRgbFn = int (*)(
void*,
HalideBuffer*,
HalideBuffer*);
using SharpenTo16BitFn = int (*)(
void*,
HalideBuffer*,
HalideBuffer*,
HalideBuffer*,
HalideBuffer*,
float);
using MeasureMoireFn = int (*)(
void*,
HalideBuffer*,
@@ -253,6 +260,13 @@ extern "C" int photon_mgc_yuv_to_rgb_s16(
void*,
HalideBuffer*,
HalideBuffer*);
extern "C" int photon_mgc_sharpen_to_16_bit_halide(
void*,
HalideBuffer*,
HalideBuffer*,
HalideBuffer*,
HalideBuffer*,
float);
extern "C" int photon_mgc_measure_moire_s16_halide(
void*,
HalideBuffer*,
@@ -1761,4 +1775,176 @@ int RunYuvToRgb(
return function(nullptr, &input_buffer, &output_buffer);
}
bool BuildDefaultSharpenCurves(
float snr,
const float interpolation_scales[3],
SharpenCurveSelection* output) {
if (output == nullptr || interpolation_scales == nullptr ||
!std::isfinite(snr) || snr <= 0.0f ||
!std::all_of(
interpolation_scales,
interpolation_scales + 3,
[](float value) { return std::isfinite(value); })) {
return false;
}
std::fill_n(output->relative_corner_acutance_correction, 3, 0.0f);
struct Node {
float snr;
float parameters[3][5];
};
// Decoded mechanically from MGC 9.6.080's generic
// sharpen_default.binarypb asset. BuildForSNR converts each node to
// piecewise points first, then interpolates those converted points.
constexpr Node nodes[] = {
{5.0f, {{1.6f, 0.05f, 1.0f, 1.0f, 0.0f},
{1.8f, 0.03f, 1.0f, 1.0f, 0.0f},
{1.2f, 0.02f, 1.0f, 1.0f, 0.0f}}},
{10.0f, {{2.5f, 0.05f, 1.0f, 1.0f, 0.0f},
{2.2f, 0.03f, 1.0f, 1.0f, 0.0f},
{1.3f, 0.02f, 1.0f, 1.0f, 0.0f}}},
{20.0f, {{3.2f, 0.05f, 1.0f, 1.0f, 0.0f},
{2.6f, 0.03f, 1.0f, 1.0f, 0.0f},
{1.4f, 0.02f, 1.0f, 1.0f, 0.0f}}},
{40.0f, {{5.2f, 0.02f, 1.0f, 1.0f, 0.0f},
{2.1f, 0.02f, 1.0f, 1.0f, 0.0f},
{1.4f, 0.02f, 1.0f, 1.0f, 0.0f}}},
{80.0f, {{4.7f, 0.02f, 1.0f, 1.0f, 0.0f},
{2.1f, 0.02f, 1.0f, 1.0f, 0.0f},
{1.4f, 0.02f, 1.0f, 1.0f, 0.0f}}},
};
const Node* lower = &nodes[0];
const Node* upper = &nodes[0];
if (snr >= nodes[std::size(nodes) - 1].snr) {
lower = upper = &nodes[std::size(nodes) - 1];
} else if (snr > nodes[0].snr) {
for (size_t index = 1; index < std::size(nodes); ++index) {
if (snr <= nodes[index].snr) {
lower = &nodes[index - 1];
upper = &nodes[index];
break;
}
}
}
const float interpolation = lower == upper
? 0.0f
: (snr - lower->snr) / (upper->snr - lower->snr);
const auto convert = [](const float parameters[5], float points[2][5]) {
const float gain = parameters[0];
const float first_x = parameters[1];
const float second_x = parameters[2];
const float transition_width = parameters[3];
const float transition_mix = parameters[4];
points[0][0] = 0.0f;
points[1][0] = 0.0f;
points[0][1] = first_x;
const float initial_gain = gain >= 1.0f
? std::max(gain * 0.5f, 1.0f)
: std::min(gain * 2.0f, 1.0f);
points[1][1] = initial_gain * first_x;
points[0][2] = second_x;
points[1][2] = gain * second_x;
points[0][3] = second_x + transition_width;
points[1][3] =
transition_mix *
((gain * second_x - second_x) +
(second_x + transition_width)) +
(second_x + transition_width) * (1.0f - transition_mix);
points[0][4] = points[0][3] + 1.0f;
points[1][4] = points[1][3] + 1.0f;
};
for (int frequency = 0; frequency < 3; ++frequency) {
// Photon exposes one independent interpolation scale per sharpening frequency group.
const float frequency_interpolation =
interpolation * interpolation_scales[frequency];
float lower_points[2][5] = {};
float upper_points[2][5] = {};
convert(lower->parameters[frequency], lower_points);
convert(upper->parameters[frequency], upper_points);
for (int coordinate = 0; coordinate < 2; ++coordinate) {
for (int point = 0; point < 5; ++point) {
const float lower_value = lower_points[coordinate][point];
const float upper_value = upper_points[coordinate][point];
output->curves[
point + 5 * frequency + 15 * coordinate] =
lower_value * (1.0f - frequency_interpolation) +
upper_value * frequency_interpolation;
}
}
}
output->lower_snr = lower->snr;
output->upper_snr = upper->snr;
output->interpolation = interpolation;
return true;
}
int RunSharpenTo16Bit(
const int16_t* input_yuv,
int width,
int height,
const float curves[30],
const float relative_corner_acutance_correction[3],
float sharpen_attenuation_scale,
uint16_t* output_interleaved_rgb) {
if (input_yuv == nullptr || curves == nullptr ||
relative_corner_acutance_correction == nullptr ||
output_interleaved_rgb == nullptr || width <= 0 || height <= 0 ||
!std::isfinite(sharpen_attenuation_scale)) {
return -1;
}
const int pixel_count = width * height;
const HalideDimension input_dimensions[] = {
{0, width, 1, 0},
{0, height, width, 0},
{0, 3, pixel_count, 0},
};
const HalideDimension curve_dimensions[] = {
{0, 1, 1, 0},
{0, 5, 1, 0},
{0, 3, 5, 0},
{0, 2, 15, 0},
};
const HalideDimension correction_dimensions[] = {
{0, 3, 1, 0},
};
const HalideDimension output_dimensions[] = {
{0, width, 3, 0},
// This AOT schedules two output rows per iteration, including its final tail.
// Input bounds stay exact so the kernel applies its original edge extension.
{0, (height + 1) & ~1, width * 3, 0},
{0, 3, 1, 0},
};
HalideBuffer input_buffer = MakeBuffer(
const_cast<int16_t*>(input_yuv),
{0, 16, 1},
3,
input_dimensions);
HalideBuffer curve_buffer = MakeBuffer(
const_cast<float*>(curves),
{2, 32, 1},
4,
curve_dimensions);
HalideBuffer correction_buffer = MakeBuffer(
const_cast<float*>(relative_corner_acutance_correction),
{2, 32, 1},
1,
correction_dimensions);
HalideBuffer output_buffer = MakeBuffer(
output_interleaved_rgb,
{1, 16, 1},
3,
output_dimensions);
const auto function = reinterpret_cast<SharpenTo16BitFn>(
&photon_mgc_sharpen_to_16_bit_halide);
return function(
nullptr,
&input_buffer,
&curve_buffer,
&correction_buffer,
&output_buffer,
sharpen_attenuation_scale);
}
} // namespace photon::mgc_denoise
@@ -37,6 +37,17 @@ struct SpatialStrengthResult {
float output_weights_sum_total_diag_1[3] = {};
};
struct SharpenCurveSelection {
float lower_snr = 0.0f;
float upper_snr = 0.0f;
float interpolation = 0.0f;
// Halide layout [guide=1, point=5, frequency=3, coordinate=2].
float curves[30] = {};
// Optional CurveParams field, one value per sharpening frequency. The
// generic sharpen_default.binarypb profile leaves all three unset.
float relative_corner_acutance_correction[3] = {};
};
/**
* Reproduces CreateLumaDenoiseNoiseBuffers for one luma noise channel.
* correlation is MGC's 128-bin normalized power correlation spectrum. A
@@ -211,4 +222,31 @@ int RunYuvToRgb(
int height,
int16_t* output);
/**
* Reproduces SharpenTuning::BuildForSNR for MGC's generic
* sharpen_default.binarypb profile.
*/
bool BuildDefaultSharpenCurves(
float snr,
const float interpolation_scales[3],
SharpenCurveSelection* output);
/**
* Runs MGC 9.6.080's exact SharpenTo16BitHalide FinishRaw kernel.
*
* input_yuv must be the tone-mapped U12 YUV emitted by ProcessLowFrequency
* and restored by GuidedUpsample. It is not compatible with RawToYuv or the
* full-resolution denoiser's signed-Q14 linear YUV boundary.
* Output storage must accommodate width * round_up(height, 2) * 3 uint16_t
* values for the AOT's two-row tail; only the first height rows are consumed.
*/
int RunSharpenTo16Bit(
const int16_t* input_yuv,
int width,
int height,
const float curves[30],
const float relative_corner_acutance_correction[3],
float sharpen_attenuation_scale,
uint16_t* output_interleaved_rgb);
} // namespace photon::mgc_denoise
@@ -0,0 +1,10 @@
#pragma once
#include <cstddef>
#include <cstdint>
namespace photon::mgc_denoise {
// Same U12 matrix and round-to-nearest-even boundary as the former scalar
// adapter.
void SharpenRgbaToYuv(const uint8_t *rgba, size_t count, int16_t *yuv);
void SharpenRgbToRgba(const uint16_t *rgb, size_t count, uint8_t *rgba);
} // namespace photon::mgc_denoise
@@ -0,0 +1,168 @@
#include "mgc_denoise_static.h"
#include "mgc_sharpen_adapter.h"
#include <GLES3/gl3.h>
#include <algorithm>
#include <android/log.h>
#include <arm_neon.h>
#include <chrono>
#include <cmath>
#include <jni.h>
#include <limits>
namespace photon::mgc_denoise {
namespace {
constexpr float kMatrix[9] = {
0.2125999927520752f, 0.7152000069618225f, 0.07219959795475006f,
-0.16245023906230927f, -0.5464943051338196f, 0.7089447379112244f,
0.9999967217445374f, -0.9083024859428406f, -0.09169333428144455f,
};
constexpr float kU8ToU12 = 4095.0f / 255.0f;
int16x4_t Convert4(float32x4_t r, float32x4_t g, float32x4_t b, int channel) {
// Deliberately separate multiply/adds: FMA changes U12 rounding boundaries.
const float32x4_t value =
vaddq_f32(vaddq_f32(vmulq_n_f32(r, kMatrix[channel * 3]),
vmulq_n_f32(g, kMatrix[channel * 3 + 1])),
vmulq_n_f32(b, kMatrix[channel * 3 + 2]));
return vmovn_s32(vmaxq_s32(
vdupq_n_s32(-4095), vminq_s32(vdupq_n_s32(4095), vcvtnq_s32_f32(value))));
}
} // namespace
void SharpenRgbaToYuv(const uint8_t *rgba, size_t count, int16_t *yuv) {
const size_t groups = count / 8;
#pragma omp parallel for schedule(static) num_threads(4)
for (size_t group = 0; group < groups; ++group) {
const size_t i = group * 8;
const uint8x8x4_t packed = vld4_u8(rgba + i * 4);
const uint16x8_t r16 = vmovl_u8(packed.val[0]);
const uint16x8_t g16 = vmovl_u8(packed.val[1]);
const uint16x8_t b16 = vmovl_u8(packed.val[2]);
const auto low = [](uint16x8_t v) {
return vmulq_n_f32(vcvtq_f32_u32(vmovl_u16(vget_low_u16(v))), kU8ToU12);
};
const auto high = [](uint16x8_t v) {
return vmulq_n_f32(vcvtq_f32_u32(vmovl_u16(vget_high_u16(v))), kU8ToU12);
};
const auto r0 = low(r16), g0 = low(g16), b0 = low(b16);
const auto r1 = high(r16), g1 = high(g16), b1 = high(b16);
for (int c = 0; c < 3; ++c) {
vst1q_s16(yuv + c * count + i,
vcombine_s16(Convert4(r0, g0, b0, c), Convert4(r1, g1, b1, c)));
}
}
for (size_t i = groups * 8; i < count; ++i) {
const float r = rgba[i * 4] * kU8ToU12;
const float g = rgba[i * 4 + 1] * kU8ToU12;
const float b = rgba[i * 4 + 2] * kU8ToU12;
for (int c = 0; c < 3; ++c) {
yuv[c * count + i] = static_cast<int16_t>(std::clamp<long>(
std::lrintf(kMatrix[c * 3] * r + kMatrix[c * 3 + 1] * g +
kMatrix[c * 3 + 2] * b),
-4095, 4095));
}
}
}
void SharpenRgbToRgba(const uint16_t *rgb, size_t count, uint8_t *rgba) {
const size_t groups = count / 8;
#pragma omp parallel for schedule(static) num_threads(4)
for (size_t group = 0; group < groups; ++group) {
const size_t i = group * 8;
const uint16x8x3_t input = vld3q_u16(rgb + i * 3);
uint8x8x4_t output;
for (int c = 0; c < 3; ++c) {
const uint16x8_t v = vminq_u16(input.val[c], vdupq_n_u16(4095));
const auto convert = [](uint16x4_t samples) {
const uint32x4_t numerator =
vaddq_u32(vmull_n_u16(samples, 255), vdupq_n_u32(2047));
// Exact floor(n / 4095) on this bounded numerator domain, not a float
// reciprocal.
return vmovn_u32(
vshrq_n_u32(vaddq_u32(vaddq_u32(numerator, vdupq_n_u32(1)),
vshrq_n_u32(numerator, 12)),
12));
};
output.val[c] = vmovn_u16(
vcombine_u16(convert(vget_low_u16(v)), convert(vget_high_u16(v))));
}
output.val[3] = vdup_n_u8(255);
vst4_u8(rgba + i * 4, output);
}
for (size_t i = groups * 8; i < count; ++i) {
for (size_t c = 0; c < 3; ++c) {
const uint32_t v = std::min<uint32_t>(rgb[i * 3 + c], 4095);
rgba[i * 4 + c] = static_cast<uint8_t>((v * 255 + 2047) / 4095);
}
rgba[i * 4 + 3] = 255;
}
}
} // namespace photon::mgc_denoise
extern "C" JNIEXPORT jint JNICALL
Java_com_hinnka_mycamera_raw_MgcSharpen_nativeSharpenRgba8(
JNIEnv *env, jobject, jobject rgba_buffer, jobject scratch_buffer,
jint width, jint height, jfloat snr, jfloat attenuation) {
using namespace photon::mgc_denoise;
if (!rgba_buffer || !scratch_buffer || width <= 0 || height <= 0 ||
!std::isfinite(snr) || snr <= 0 || !std::isfinite(attenuation) ||
attenuation < 0)
return -1;
const size_t count = size_t(width) * size_t(height);
const size_t output_count =
size_t(width) * ((size_t(height) + 1) & ~size_t(1));
const size_t scratch_bytes = (count + output_count) * 6;
if (scratch_bytes > size_t(std::numeric_limits<int>::max()))
return -1;
auto *rgba = static_cast<uint8_t *>(env->GetDirectBufferAddress(rgba_buffer));
auto *yuv =
static_cast<int16_t *>(env->GetDirectBufferAddress(scratch_buffer));
if (!rgba || !yuv ||
env->GetDirectBufferCapacity(rgba_buffer) < jlong(count * 4) ||
env->GetDirectBufferCapacity(scratch_buffer) < jlong(scratch_bytes))
return -1;
auto *rgb = reinterpret_cast<uint16_t *>(yuv + count * 3);
SharpenCurveSelection curves;
constexpr float scales[3] = {1, 1, 1};
if (!BuildDefaultSharpenCurves(snr, scales, &curves))
return -1;
using Clock = std::chrono::steady_clock;
const auto start = Clock::now();
SharpenRgbaToYuv(rgba, count, yuv);
const auto converted = Clock::now();
const int result = RunSharpenTo16Bit(
yuv, width, height, curves.curves,
curves.relative_corner_acutance_correction, attenuation, rgb);
if (result != 0)
return result;
const auto sharpened = Clock::now();
SharpenRgbToRgba(rgb, count, rgba);
const auto finish = Clock::now();
const auto ms = [](auto a, auto b) {
return std::chrono::duration<double, std::milli>(b - a).count();
};
__android_log_print(
ANDROID_LOG_INFO, "PLog_MgcSharpen",
"MGC original sharpen %dx%d snr=%.6g attenuation=%.6g convertInMs=%.3f "
"kernelMs=%.3f convertOutMs=%.3f totalNativeMs=%.3f",
width, height, snr, attenuation, ms(start, converted),
ms(converted, sharpened), ms(sharpened, finish), ms(start, finish));
return 0;
}
extern "C" JNIEXPORT jboolean JNICALL
Java_com_hinnka_mycamera_raw_MgcSharpen_nativeUploadRgba8(
JNIEnv *, jobject, jint pbo, jint texture, jint width, jint height) {
if (pbo <= 0 || texture <= 0 || width <= 0 || height <= 0)
return JNI_FALSE;
glActiveTexture(GL_TEXTURE0);
glBindTexture(GL_TEXTURE_2D, static_cast<GLuint>(texture));
glBindBuffer(GL_PIXEL_UNPACK_BUFFER, static_cast<GLuint>(pbo));
glPixelStorei(GL_UNPACK_ALIGNMENT, 1);
glPixelStorei(GL_UNPACK_ROW_LENGTH, 0);
glTexSubImage2D(GL_TEXTURE_2D, 0, 0, 0, width, height, GL_RGBA,
GL_UNSIGNED_BYTE, nullptr);
const GLenum error = glGetError();
glBindBuffer(GL_PIXEL_UNPACK_BUFFER, 0);
return error == GL_NO_ERROR ? JNI_TRUE : JNI_FALSE;
}
@@ -3442,6 +3442,7 @@ object GalleryManager {
mgcDenoiseShotNoise = finalStackResult.mgcDenoiseShotNoise,
mgcSpatialStrengthMap = finalStackResult.mgcSpatialStrengthMap,
mgcDenoiseTuningSnr = finalStackResult.mgcDenoiseTuningSnr,
mgcSharpenTuningSnr = finalStackResult.mgcSharpenTuningSnr,
mgcSharpenAttenuationScale =
finalStackResult.mgcSharpenAttenuationScale,
)
@@ -3708,6 +3709,7 @@ object GalleryManager {
sharpeningValue = rawSharpening,
processLocalQualityTuningSensorAreaMm2 =
PhotonSensorSizeTuning.areaFromProperties(updatedMetadata.customProperties),
processLocalMgcSharpenTuningSnr = finalStackResult.mgcSharpenTuningSnr,
processLocalMgcSharpenAttenuationScale =
finalStackResult.mgcSharpenAttenuationScale,
denoiseValue = rawNoiseReduction,
@@ -2014,6 +2014,7 @@ internal class GlesMgcRawSpatialStacker(
::mapSpatialStrengthToOutputCoordinates,
),
mgcDenoiseTuningSnr = finishRawDenoiseSnr,
mgcSharpenTuningSnr = bayerKernelTuning.referenceSnr,
mgcSharpenAttenuationScale = finishRawSharpenAttenuationScale,
mgcSpatialReferenceOnlyDiagnostic = referenceOnly,
fastMomentsRawStats = fastMomentsRawStats,
@@ -2634,6 +2635,7 @@ internal class GlesMgcRawSpatialStacker(
mgcDenoiseShotNoise = mergedNoiseModel.shot,
mgcDenoiseCorrelation = mergedNoiseModel.correlation,
mgcDenoiseTuningSnr = finishRawDenoiseSnr,
mgcSharpenTuningSnr = kernelTuning.referenceSnr,
mgcSharpenAttenuationScale = sabreResolveParameters.demosaicSharpness,
)
returned = true
@@ -140,7 +140,9 @@ data class RawStackResult(
* This is the linear signal-domain SNR, not ISO or sensor gain.
*/
val mgcDenoiseTuningSnr: Float? = null,
/** MGC-derived attenuation applied to Photon's final GLES sharpen strength. */
/** Reference-frame SNR for original MGC sharpen curve selection; not the merged SNR. */
val mgcSharpenTuningSnr: Float? = null,
/** MGC-derived attenuation applied to the final sharpen kernel. */
val mgcSharpenAttenuationScale: Float? = null,
/**
* True only for the debug reference-only isolation path. This state is process-local and is
@@ -0,0 +1,177 @@
package com.hinnka.mycamera.raw
import android.opengl.GLES30
import android.opengl.GLES31
import com.hinnka.mycamera.processor.GlesGpuCompletion
import com.hinnka.mycamera.utils.LargeDirectBuffer
import com.hinnka.mycamera.utils.PLog
import java.nio.ByteBuffer
import java.nio.ByteOrder
/** Original MGC AOT kernel at Photon's encoded RGBA8 boundary, with reusable native storage. */
internal class MgcSharpen {
private var transferBuffer = 0
private var transferSize = 0
private var scratch: ByteBuffer? = null
private var packProgram = 0
private var packAttempted = false
private var maxSsboBytes = 0L
fun render(
sourceTexture: Int,
sourceFramebuffer: Int,
targetTexture: Int,
width: Int,
height: Int,
snr: Float,
attenuation: Float,
) {
require(width > 0 && height > 0 && snr.isFinite() && snr > 0f)
require(attenuation.isFinite() && attenuation >= 0f)
val pixels = width.toLong() * height
val outputPixels = width.toLong() * ((height.toLong() + 1) and -2L)
val scratchBytes = (pixels + outputPixels) * 6
require(scratchBytes <= Int.MAX_VALUE)
val bytes = (pixels * 4).toInt()
val start = System.nanoTime()
ensureStorage(bytes, scratchBytes)
val allocationMs = elapsedMs(start)
val useCompute = bytes <= maxSsboBytes && packProgram != 0
val upstreamWaitMs = GlesGpuCompletion.awaitSubmittedWork(
label = "MGC sharpen input", checkGlError = ::checkGlError,
)
val transferStart = System.nanoTime()
try {
if (useCompute) {
GLES31.glUseProgram(packProgram)
GLES31.glActiveTexture(GLES31.GL_TEXTURE0)
GLES31.glBindTexture(GLES31.GL_TEXTURE_2D, sourceTexture)
GLES31.glUniform1i(GLES31.glGetUniformLocation(packProgram, "uInput"), 0)
GLES31.glUniform2i(GLES31.glGetUniformLocation(packProgram, "uSize"), width, height)
GLES31.glBindBufferBase(GLES31.GL_SHADER_STORAGE_BUFFER, 0, transferBuffer)
GLES31.glDispatchCompute((width + 7) / 8, (height + 7) / 8, 1)
GLES31.glMemoryBarrier(GLES31.GL_SHADER_STORAGE_BARRIER_BIT or GLES31.GL_BUFFER_UPDATE_BARRIER_BIT)
GLES31.glBindBufferBase(GLES31.GL_SHADER_STORAGE_BUFFER, 0, 0)
} else {
GLES30.glBindFramebuffer(GLES30.GL_READ_FRAMEBUFFER, sourceFramebuffer)
GLES30.glReadBuffer(GLES30.GL_COLOR_ATTACHMENT0)
GLES30.glBindBuffer(GLES30.GL_PIXEL_PACK_BUFFER, transferBuffer)
GLES30.glPixelStorei(GLES30.GL_PACK_ALIGNMENT, 1)
GLES30.glPixelStorei(GLES30.GL_PACK_ROW_LENGTH, 0)
GLES30.glReadPixels(0, 0, width, height, GLES30.GL_RGBA, GLES30.GL_UNSIGNED_BYTE, 0)
}
checkGlError("MGC sharpen transfer submission")
GLES30.glBindBuffer(GLES30.GL_PIXEL_PACK_BUFFER, transferBuffer)
val mapped = checkNotNull(GLES30.glMapBufferRange(
GLES30.GL_PIXEL_PACK_BUFFER, 0, bytes,
GLES30.GL_MAP_READ_BIT or GLES30.GL_MAP_WRITE_BIT,
) as? ByteBuffer) { "MGC sharpen transfer mapping failed" }
val transferMs = elapsedMs(transferStart)
val nativeStart = System.nanoTime()
try {
val result = nativeSharpenRgba8(mapped.order(ByteOrder.nativeOrder()),
checkNotNull(scratch), width, height, snr, attenuation)
check(result == 0) { "MGC original sharpen failed: $result" }
} finally {
check(GLES30.glUnmapBuffer(GLES30.GL_PIXEL_PACK_BUFFER)) {
"MGC sharpen mapped buffer became invalid"
}
}
val nativeMs = elapsedMs(nativeStart)
GLES30.glBindBuffer(GLES30.GL_PIXEL_PACK_BUFFER, 0)
val uploadStart = System.nanoTime()
check(nativeUploadRgba8(transferBuffer, targetTexture, width, height)) {
"MGC sharpen PBO upload failed"
}
PLog.i(TAG, "originalMgc=true size=${width}x$height referenceSnr=$snr " +
"attenuation=$attenuation transfer=${if (useCompute) "SSBO" else "PBO"} " +
"allocationMs=$allocationMs upstreamGpuWaitMs=$upstreamWaitMs " +
"transferAndMapMs=$transferMs nativeAndUnmapMs=$nativeMs " +
"uploadSubmitMs=${elapsedMs(uploadStart)} totalCpuMs=${elapsedMs(start)}")
} finally {
GLES30.glBindBuffer(GLES30.GL_PIXEL_PACK_BUFFER, 0)
GLES30.glBindBuffer(GLES30.GL_PIXEL_UNPACK_BUFFER, 0)
GLES30.glBindFramebuffer(GLES30.GL_READ_FRAMEBUFFER, 0)
}
}
private fun ensureStorage(bytes: Int, scratchBytes: Long) {
if (!packAttempted) {
packAttempted = true
val major = IntArray(1)
val minor = IntArray(1)
GLES30.glGetIntegerv(GLES30.GL_MAJOR_VERSION, major, 0)
GLES30.glGetIntegerv(GLES30.GL_MINOR_VERSION, minor, 0)
if (major[0] > 3 || major[0] == 3 && minor[0] >= 1) {
val limit = LongArray(1)
GLES31.glGetInteger64v(GLES31.GL_MAX_SHADER_STORAGE_BLOCK_SIZE, limit, 0)
maxSsboBytes = limit[0]
packProgram = RawGlesProgram.compileCompute(PACK_RGBA8, "MgcSharpenPackRgba8")
}
}
if (transferBuffer == 0) {
val names = IntArray(1)
GLES30.glGenBuffers(1, names, 0)
transferBuffer = names[0]
}
if (transferSize < bytes) {
GLES30.glBindBuffer(GLES30.GL_PIXEL_PACK_BUFFER, transferBuffer)
GLES30.glBufferData(GLES30.GL_PIXEL_PACK_BUFFER, bytes, null, GLES30.GL_STREAM_COPY)
GLES30.glBindBuffer(GLES30.GL_PIXEL_PACK_BUFFER, 0)
checkGlError("MGC sharpen transfer allocation")
transferSize = bytes
}
if ((scratch?.capacity()?.toLong() ?: 0) < scratchBytes) {
LargeDirectBuffer.free(scratch)
scratch = null
scratch = checkNotNull(LargeDirectBuffer.allocate(scratchBytes, "MGC sharpen YUV/RGB"))
}
}
/** Release frame storage after all tiles; programs live with the GL context. */
fun releaseBuffers() {
LargeDirectBuffer.free(scratch)
scratch = null
if (transferBuffer != 0) GLES30.glDeleteBuffers(1, intArrayOf(transferBuffer), 0)
transferBuffer = 0
transferSize = 0
}
fun release() {
releaseBuffers()
if (packProgram != 0) GLES30.glDeleteProgram(packProgram)
packProgram = 0
packAttempted = false
maxSsboBytes = 0
}
private external fun nativeSharpenRgba8(
rgba: ByteBuffer, scratch: ByteBuffer, width: Int, height: Int, snr: Float, attenuation: Float,
): Int
private external fun nativeUploadRgba8(pbo: Int, texture: Int, width: Int, height: Int): Boolean
companion object {
private const val TAG = "MgcSharpen"
init { System.loadLibrary("my-native-lib") }
private fun elapsedMs(start: Long) = (System.nanoTime() - start) / 1_000_000.0
private fun checkGlError(label: String) {
val error = GLES30.glGetError()
check(error == GLES30.GL_NO_ERROR) { "$label: GL error 0x${error.toString(16)}" }
}
internal val PACK_RGBA8 = """
#version 310 es
precision highp float;
precision highp int;
layout(local_size_x = 8, local_size_y = 8) in;
uniform highp sampler2D uInput;
uniform ivec2 uSize;
layout(std430, binding = 0) writeonly buffer Pixels { uint pixels[]; };
void main() {
ivec2 p = ivec2(gl_GlobalInvocationID.xy);
if (any(greaterThanEqual(p, uSize))) return;
uvec4 v = uvec4(round(texelFetch(uInput, p, 0) * 255.0));
pixels[p.y * uSize.x + p.x] = v.r | (v.g << 8u) | (v.b << 16u) | (v.a << 24u);
}
""".trimIndent()
}
}
@@ -226,6 +226,7 @@ class RawDemosaicProcessor {
mgcDenoiseShotNoise = baseMetadata?.mgcDenoiseShotNoise,
mgcSpatialStrengthMap = baseMetadata?.mgcSpatialStrengthMap,
mgcDenoiseTuningSnr = baseMetadata?.mgcDenoiseTuningSnr,
mgcSharpenTuningSnr = baseMetadata?.mgcSharpenTuningSnr,
mgcSharpenAttenuationScale = baseMetadata?.mgcSharpenAttenuationScale,
rawMaxQualityTuningSensorAreaMm2 = baseMetadata?.rawMaxQualityTuningSensorAreaMm2,
rotation = dngRawData.rotation,
@@ -1497,6 +1498,7 @@ class RawDemosaicProcessor {
private val adjustmentPass = RawAdjustmentPass(fullscreenQuad)
private val srgbPass = RawSrgbPass(fullscreenQuad)
private val sharpenPass = RawSharpenPass(fullscreenQuad)
private val mgcSharpen = MgcSharpen()
private val outputPass = RawOutputPass(fullscreenQuad)
private val linearUintToFloatPass = RawLinearUintToFloatPass()
private val linearRgbExpandPass = RawLinearRgbExpandPass()
@@ -2056,6 +2058,7 @@ class RawDemosaicProcessor {
rawCustomWhiteLevel: Float? = null,
sharpeningValue: Float = 0f,
processLocalQualityTuningSensorAreaMm2: Float? = null,
processLocalMgcSharpenTuningSnr: Float? = null,
processLocalMgcSharpenAttenuationScale: Float? = null,
denoiseValue: Float? = null,
chromaDenoiseValue: Float? = null,
@@ -2104,8 +2107,8 @@ class RawDemosaicProcessor {
rawCustomWhiteLevel = rawCustomWhiteLevel,
sharpeningValue = sharpeningValue,
processLocalQualityTuningSensorAreaMm2 = processLocalQualityTuningSensorAreaMm2,
processLocalMgcSharpenAttenuationScale =
processLocalMgcSharpenAttenuationScale,
processLocalMgcSharpenTuningSnr = processLocalMgcSharpenTuningSnr,
processLocalMgcSharpenAttenuationScale = processLocalMgcSharpenAttenuationScale,
denoiseValue = denoiseValue,
chromaDenoiseValue = chromaDenoiseValue,
rawDcpId = rawDcpId,
@@ -2321,6 +2324,7 @@ class RawDemosaicProcessor {
rawCustomWhiteLevel: Float? = null,
sharpeningValue: Float = 0f,
processLocalQualityTuningSensorAreaMm2: Float? = null,
processLocalMgcSharpenTuningSnr: Float? = null,
processLocalMgcSharpenAttenuationScale: Float? = null,
denoiseValue: Float? = null,
chromaDenoiseValue: Float? = null,
@@ -2523,6 +2527,7 @@ class RawDemosaicProcessor {
mgcDenoiseShotNoise = null,
mgcSpatialStrengthMap = null,
mgcDenoiseTuningSnr = null,
mgcSharpenTuningSnr = processLocalMgcSharpenTuningSnr,
mgcSharpenAttenuationScale =
processLocalMgcSharpenAttenuationScale,
)
@@ -2584,6 +2589,7 @@ class RawDemosaicProcessor {
rawData = actualRawData,
rowStride = actualRowStride,
samplesPerPixel = actualSamplesPerPixel,
needsSharpen = RawSharpeningDefaults.toAlgorithmStrength(sharpeningValue) > 0f,
)
}
@@ -3954,7 +3960,10 @@ class RawDemosaicProcessor {
// 6. 第三步:锐化 (Sharpen Pass)
setupSharpenFramebuffer(actualWidth, actualHeight)
val sharpenStart = System.currentTimeMillis()
renderFinalSharpenPass(actualMetadata, sharpeningValue, combinedOutput.encodedTextureId)
renderFinalSharpenPass(
actualMetadata, sharpeningValue, combinedOutput.encodedTextureId,
borrowedGpuSource?.stackCompletionTimeline,
)
PLog.d(TAG, "Sharpen Pass took: ${System.currentTimeMillis() - sharpenStart}ms")
// combinedTextureId 已被 sharpenPass 消费,提前释放
if (combinedTextureId != 0) {
@@ -4596,6 +4605,7 @@ class RawDemosaicProcessor {
}
private fun releaseTiledRenderFramebuffers() {
mgcSharpen.releaseBuffers()
vgnDemosaicAlgorithm.setTileTexturePoolingEnabled(false)
if (rawTextureId != 0) {
GLES30.glDeleteTextures(1, intArrayOf(rawTextureId), 0)
@@ -7482,15 +7492,17 @@ class RawDemosaicProcessor {
) { "RAW HDR reference pass failed" }
}
/** Measures the render source only when single-frame MGC denoise needs physical SNR. */
/** Share one native RAW measurement; merged captures already carry reference-frame SNR. */
private fun RawMetadata.withMgcRenderTuning(
rawData: ByteBuffer?,
rowStride: Int,
samplesPerPixel: Int,
needsSharpen: Boolean,
): RawMetadata {
val needsSingleFrameDenoiseSnr =
samplesPerPixel == 1 && frameCount == 1 && mgcDenoiseTuningSnr == null
if (!needsSingleFrameDenoiseSnr) {
val needsSharpenSnr = needsSharpen && frameCount == 1 && mgcSharpenTuningSnr == null
if (!needsSingleFrameDenoiseSnr && !needsSharpenSnr) {
return this
}
val source = rawData ?: return this
@@ -7540,9 +7552,11 @@ class RawDemosaicProcessor {
"MGC RAW render tuning signal=$signal snr=$snr " +
"greenShot=$greenShot greenRead=$greenRead " +
"singleFrameDenoise=$needsSingleFrameDenoiseSnr " +
"sharpen=$needsSharpenSnr " +
"signalSource=NATIVE_OMP signalMs=$signalElapsedMs",
)
return copy(
mgcSharpenTuningSnr = if (needsSharpenSnr) snr else mgcSharpenTuningSnr,
mgcDenoiseTuningSnr = if (needsSingleFrameDenoiseSnr) {
snr
} else {
@@ -7598,6 +7612,7 @@ class RawDemosaicProcessor {
metadata: RawMetadata,
sharpeningValue: Float,
inputTextureId: Int,
stackCompletionTimeline: GpuStackCompletionTimeline? = null,
) {
val sliderValue = RawSharpeningDefaults.normalize(sharpeningValue)
val algorithmStrength = RawSharpeningDefaults.toAlgorithmStrength(sliderValue)
@@ -7606,19 +7621,31 @@ class RawDemosaicProcessor {
"MGC sharpen attenuation is invalid: $attenuation"
}
} ?: 1f
val effectiveStrength = (algorithmStrength * runtimeAttenuation).coerceIn(
0f,
RawSharpeningDefaults.MAX_ALGORITHM_STRENGTH,
)
renderSharpenPass(metadata, effectiveStrength, inputTextureId)
if (metadata.mgcSharpenAttenuationScale != null) {
PLog.i(
TAG,
"MGC final sharpen uses GLES scale-supported USM size=${metadata.width}x${metadata.height} " +
"runtimeAttenuation=$runtimeAttenuation slider=$sliderValue " +
"algorithmStrength=$algorithmStrength effectiveStrength=$effectiveStrength " +
"cpuReadback=false",
val effectiveStrength = algorithmStrength * runtimeAttenuation
if (effectiveStrength <= 0f) {
renderSharpenPass(metadata, 0f, inputTextureId)
return
}
val snr = metadata.mgcSharpenTuningSnr
if (snr != null) {
check(snr.isFinite() && snr > 0f) { "MGC sharpen reference SNR is invalid: $snr" }
check(inputTextureId == combinedTextureId) { "MGC sharpen requires the encoded combined output" }
stackCompletionTimeline?.awaitPending(
syncPoint = "RAW_SHARPEN_INPUT", checkGlError = ::checkGlError,
)?.let { PLog.i(TAG, "MGC sharpen upstreamStackGpuWait=${it.totalWaitMs}ms") }
mgcSharpen.render(
sourceTexture = inputTextureId,
sourceFramebuffer = combinedFramebufferId,
targetTexture = sharpenTextureId,
width = metadata.width,
height = metadata.height,
snr = snr,
attenuation = effectiveStrength,
)
} else {
// Non-MGC GPU-only sources may have no reference RAW/statistics available.
PLog.w(TAG, "Original MGC sharpen unavailable: missing reference SNR; using GLES USM")
renderSharpenPass(metadata, effectiveStrength, inputTextureId)
}
}
@@ -8786,6 +8813,7 @@ class RawDemosaicProcessor {
}
private fun releaseSharpenFramebuffer() {
mgcSharpen.releaseBuffers()
if (sharpenTextureId != 0) {
GLES30.glDeleteTextures(1, intArrayOf(sharpenTextureId), 0)
sharpenTextureId = 0
@@ -8992,6 +9020,7 @@ class RawDemosaicProcessor {
adjustmentPass.release()
srgbPass.release()
sharpenPass.release()
mgcSharpen.release()
outputPass.release()
hdrReferencePass.release()
chromaDenoiseAlgorithm.release()
@@ -193,7 +193,9 @@ data class RawMetadata(
val mgcSpatialStrengthMap: MgcSpatialStrengthMap? = null,
/** Merged output-frame SNR used by MGC FinishRaw to select luma/chroma tuning. */
val mgcDenoiseTuningSnr: Float? = null,
/** MGC-derived attenuation applied to Photon's final GLES sharpen strength. */
/** Reference-frame SNR for original MGC sharpen curve selection; not the merged SNR. */
val mgcSharpenTuningSnr: Float? = null,
/** MGC-derived attenuation applied to the final sharpen kernel. */
val mgcSharpenAttenuationScale: Float? = null,
val rotation: Int? = null,
val profileGainTableMap: DngProfileGainTableMap? = null,
@@ -1217,6 +1219,7 @@ data class RawMetadata(
} else if (other.mgcDenoiseShotNoise != null) return false
if (mgcSpatialStrengthMap != other.mgcSpatialStrengthMap) return false
if (mgcDenoiseTuningSnr != other.mgcDenoiseTuningSnr) return false
if (mgcSharpenTuningSnr != other.mgcSharpenTuningSnr) return false
if (mgcSharpenAttenuationScale != other.mgcSharpenAttenuationScale) return false
if (rawMaxQualityTuningSensorAreaMm2 != other.rawMaxQualityTuningSensorAreaMm2) return false
if (rotation != other.rotation) return false
@@ -1255,6 +1258,7 @@ data class RawMetadata(
result = 31 * result + (mgcDenoiseShotNoise?.contentHashCode() ?: 0)
result = 31 * result + (mgcSpatialStrengthMap?.hashCode() ?: 0)
result = 31 * result + (mgcDenoiseTuningSnr?.hashCode() ?: 0)
result = 31 * result + (mgcSharpenTuningSnr?.hashCode() ?: 0)
result = 31 * result + (mgcSharpenAttenuationScale?.hashCode() ?: 0)
result = 31 * result + (rawMaxQualityTuningSensorAreaMm2?.hashCode() ?: 0)
result = 31 * result + (rotation ?: 0)
@@ -147,6 +147,7 @@ object RawProcessor {
exposureCompensation = baseMetadata.exposureCompensation,
exposureBias = baseMetadata.exposureBias,
frameCount = 1,
mgcSharpenTuningSnr = baseMetadata.mgcSharpenTuningSnr,
mgcSharpenAttenuationScale = baseMetadata.mgcSharpenAttenuationScale,
rotation = rotation,
profileGainTableMap = profilePreparation.profileGainTableMap,
+323
View File
@@ -0,0 +1,323 @@
// Standalone Android/arm64 probe. No APK or instrumentation test installation.
// Compile with the production MGC adapter/runtime/capsule, -fopenmp
// -static-openmp -fno-fast-math -ffp-contract=off -ffunction-sections
// -Wl,--gc-sections.
#include "mgc_denoise_static.h"
#include "mgc_sharpen_adapter.h"
#include <EGL/egl.h>
#include <GLES3/gl31.h>
#include <algorithm>
#include <chrono>
#include <cmath>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <fstream>
#include <iterator>
#include <jni.h>
#include <vector>
using namespace photon::mgc_denoise;
using Clock = std::chrono::steady_clock;
extern "C" jfloat
Java_com_hinnka_mycamera_raw_RawDemosaicProcessor_estimateMgcReferenceSignalNative(
JNIEnv *, jobject, jobject, jint, jint, jint, jint, jint, jint, jint,
jfloat, jint, jfloat);
// Only the two direct-buffer JNI functions used by the production statistics
// entry are stubbed. All validation, sampling, histogram coordinates, sqrt and
// reduction run in production code.
static void SignalStats(int w, int h) {
struct Buffer {
void *data;
jlong bytes;
};
std::vector<uint16_t> raw(size_t(w) * h, 512);
Buffer buffer{raw.data(), jlong(raw.size() * 2)};
JNINativeInterface functions{};
functions.GetDirectBufferAddress = [](JNIEnv *, jobject b) -> void * {
return reinterpret_cast<Buffer *>(b)->data;
};
functions.GetDirectBufferCapacity = [](JNIEnv *, jobject b) -> jlong {
return reinterpret_cast<Buffer *>(b)->bytes;
};
JNIEnv env{&functions};
for (int i = 0; i < 4; ++i) {
auto start = Clock::now();
float signal =
Java_com_hinnka_mycamera_raw_RawDemosaicProcessor_estimateMgcReferenceSignalNative(
&env, nullptr, reinterpret_cast<jobject>(&buffer), 0, buffer.bytes,
w, h, w * 2, 1, 1, 64.f, 4095, 4031.f);
double ms =
std::chrono::duration<double, std::milli>(Clock::now() - start).count();
if (!std::isfinite(signal) || std::abs(signal - 448.f / 4031.f) > 1e-6f)
std::exit(1);
printf("signalStats %dx%d run=%d nativeMs=%.3f signal=%.9g\n", w, h, i, ms,
signal);
}
}
static void Check(bool ok, const char *what) {
if (!ok) {
fprintf(stderr, "FAIL %s gl=%x\n", what, glGetError());
std::exit(1);
}
}
static double Ms(Clock::time_point t) {
return std::chrono::duration<double, std::milli>(Clock::now() - t).count();
}
static void Scalar(const uint8_t *rgba, size_t n, int16_t *out) {
constexpr float m[] = {
.2125999927520752f, .7152000069618225f, .07219959795475006f,
-.16245023906230927f, -.5464943051338196f, .7089447379112244f,
.9999967217445374f, -.9083024859428406f, -.09169333428144455f};
#pragma omp parallel for schedule(static) num_threads(4)
for (size_t i = 0; i < n; i++) {
float r = rgba[i * 4] * (4095.f / 255.f),
g = rgba[i * 4 + 1] * (4095.f / 255.f),
b = rgba[i * 4 + 2] * (4095.f / 255.f);
for (int c = 0; c < 3; c++)
out[c * n + i] = std::clamp<long>(
std::lrintf(m[c * 3] * r + m[c * 3 + 1] * g + m[c * 3 + 2] * b),
-4095, 4095);
}
}
static void VerifyConversions() {
constexpr size_t n = 65536;
std::vector<uint8_t> rgba(n * 4);
std::vector<int16_t> a(n * 3), b(n * 3);
for (int r = 0; r < 256; r++) {
for (size_t i = 0; i < n; i++) {
rgba[i * 4] = r;
rgba[i * 4 + 1] = i / 256;
rgba[i * 4 + 2] = i % 256;
rgba[i * 4 + 3] = 255;
}
Scalar(rgba.data(), n, a.data());
SharpenRgbaToYuv(rgba.data(), n, b.data());
Check(a == b, "all RGB8 -> YUV12 exact");
}
for (size_t tail = 1; tail < 24; tail++) {
Scalar(rgba.data(), tail, a.data());
SharpenRgbaToYuv(rgba.data(), tail, b.data());
Check(std::equal(a.begin(), a.begin() + tail * 3, b.begin()),
"NEON scalar tail");
}
std::vector<uint16_t> rgb(n * 3);
for (size_t i = 0; i < rgb.size(); i++)
rgb[i] = i % 65536;
SharpenRgbToRgba(rgb.data(), n, rgba.data());
for (size_t i = 0; i < n; i++)
for (int c = 0; c < 3; c++)
Check(rgba[i * 4 + c] ==
(std::min<unsigned>(rgb[i * 3 + c], 4095) * 255 + 2047) / 4095,
"U12 to U8 exact");
puts("PASS all 16777216 RGB8 colors, SIMD tails, all uint16 output values");
}
static void Sharpen(int16_t *in, uint16_t *out, int w, int h, float snr = 20) {
SharpenCurveSelection curves;
const float scales[] = {1, 1, 1};
Check(BuildDefaultSharpenCurves(snr, scales, &curves), "curves");
int rc =
RunSharpenTo16Bit(in, w, h, curves.curves,
curves.relative_corner_acutance_correction, .8f, out);
if (rc)
fprintf(stderr, "kernel size=%dx%d rc=%d\n", w, h, rc);
Check(rc == 0, "kernel");
}
static void VerifyTiles() {
const int w = 512, h = 384;
const size_t n = w * h;
std::vector<uint8_t> rgba(n * 4);
for (size_t i = 0; i < rgba.size(); i++)
rgba[i] = (i * 17 + i / 31) % 256;
std::vector<int16_t> in(n * 3);
std::vector<uint16_t> full(n * 3);
SharpenRgbaToYuv(rgba.data(), n, in.data());
Sharpen(in.data(), full.data(), w, h);
// CFA-only phase 2 and odd dimensions are deliberate; the kernel must not
// reset a pyramid phase.
for (int origin : {0, 2, 8, 16, 50, 112}) {
const int tw = 257, th = 193;
const size_t tn = tw * th;
std::vector<int16_t> ti(tn * 3);
std::vector<uint16_t> to(size_t(tw) * ((th + 1) & ~1) * 3);
for (int c = 0; c < 3; c++)
for (int y = 0; y < th; y++)
std::copy_n(in.data() + c * n + (y + origin) * w + origin, tw,
ti.data() + c * tn + y * tw);
Sharpen(ti.data(), to.data(), tw, th);
size_t mismatches = 0;
for (int y = 52; y < th - 52; y++)
for (int x = 52; x < tw - 52; x++)
for (int c = 0; c < 3; c++)
mismatches += to[(y * tw + x) * 3 + c] !=
full[((y + origin) * w + x + origin) * 3 + c];
printf("tile origin=%d mismatches=%zu\n", origin, mismatches);
Check(mismatches == 0,
"tile interior equivalence with 52px sharpen support");
}
}
static void Gpu(int w, int h, const char *shaderFile) {
EGLDisplay d = eglGetDisplay(EGL_DEFAULT_DISPLAY);
Check(eglInitialize(d, nullptr, nullptr), "eglInitialize");
EGLint attrs[] = {EGL_SURFACE_TYPE, EGL_PBUFFER_BIT, EGL_RENDERABLE_TYPE,
EGL_OPENGL_ES3_BIT, EGL_NONE},
num = 0;
EGLConfig cfg;
Check(eglChooseConfig(d, attrs, &cfg, 1, &num) && num > 0, "eglChooseConfig");
EGLint ca[] = {EGL_CONTEXT_CLIENT_VERSION, 3, EGL_NONE},
pa[] = {EGL_WIDTH, 1, EGL_HEIGHT, 1, EGL_NONE};
EGLContext ctx = eglCreateContext(d, cfg, EGL_NO_CONTEXT, ca);
EGLSurface surf = eglCreatePbufferSurface(d, cfg, pa);
Check(eglMakeCurrent(d, surf, surf, ctx), "eglMakeCurrent");
printf("GPU %s %s\n", glGetString(GL_RENDERER), glGetString(GL_VERSION));
std::ifstream f(shaderFile);
std::string src((std::istreambuf_iterator<char>(f)), {});
Check(!src.empty(), "shader source");
GLuint sh = glCreateShader(GL_COMPUTE_SHADER);
const char *p = src.c_str();
glShaderSource(sh, 1, &p, nullptr);
glCompileShader(sh);
GLint ok;
glGetShaderiv(sh, GL_COMPILE_STATUS, &ok);
if (!ok) {
char log[2048];
glGetShaderInfoLog(sh, 2048, nullptr, log);
puts(log);
}
Check(ok, "compute compile");
GLuint prog = glCreateProgram();
glAttachShader(prog, sh);
glLinkProgram(prog);
glGetProgramiv(prog, GL_LINK_STATUS, &ok);
Check(ok, "compute link");
size_t n = size_t(w) * h, bytes = n * 4;
std::vector<uint8_t> input(bytes), reference(bytes), result(bytes);
for (size_t i = 0; i < n; i++) {
input[i * 4] = (i * 13 + i / w) % 256;
input[i * 4 + 1] = (i * 19) % 256;
input[i * 4 + 2] = (i / 7) % 256;
input[i * 4 + 3] = 255;
}
std::vector<int16_t> yuv(n * 3);
std::vector<uint16_t> rgb(size_t(w) * ((h + 1) & ~1) * 3);
auto t = Clock::now();
Scalar(input.data(), n, yuv.data());
double oldMs = Ms(t);
t = Clock::now();
SharpenRgbaToYuv(input.data(), n, yuv.data());
double newMs = Ms(t);
t = Clock::now();
Sharpen(yuv.data(), rgb.data(), w, h);
double kernelMs = Ms(t);
t = Clock::now();
SharpenRgbToRgba(rgb.data(), n, reference.data());
double outputMs = Ms(t);
printf("CPU %dx%d oldConvertMs=%.3f neonConvertMs=%.3f kernelMs=%.3f "
"outMs=%.3f\n",
w, h, oldMs, newMs, kernelMs, outputMs);
GLuint tex[2], fb, buf;
glGenTextures(2, tex);
for (auto v : tex) {
glBindTexture(GL_TEXTURE_2D, v);
glTexStorage2D(GL_TEXTURE_2D, 1, GL_RGBA8, w, h);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
}
glBindTexture(GL_TEXTURE_2D, tex[0]);
glTexSubImage2D(GL_TEXTURE_2D, 0, 0, 0, w, h, GL_RGBA, GL_UNSIGNED_BYTE,
input.data());
glGenFramebuffers(1, &fb);
glBindFramebuffer(GL_FRAMEBUFFER, fb);
glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D,
tex[0], 0);
Check(glCheckFramebufferStatus(GL_FRAMEBUFFER) == GL_FRAMEBUFFER_COMPLETE,
"framebuffer");
glGenBuffers(1, &buf);
glBindBuffer(GL_PIXEL_PACK_BUFFER, buf);
glBufferData(GL_PIXEL_PACK_BUFFER, bytes, nullptr, GL_STREAM_COPY);
GLint64 limit;
glGetInteger64v(GL_MAX_SHADER_STORAGE_BLOCK_SIZE, &limit);
Check(bytes <= size_t(limit), "SSBO limit");
for (bool compute : {false, true})
for (int run = 0; run < 3; run++) {
glFinish();
t = Clock::now();
if (compute) {
glUseProgram(prog);
glActiveTexture(GL_TEXTURE0);
glBindTexture(GL_TEXTURE_2D, tex[0]);
glUniform1i(glGetUniformLocation(prog, "uInput"), 0);
glUniform2i(glGetUniformLocation(prog, "uSize"), w, h);
glBindBufferBase(GL_SHADER_STORAGE_BUFFER, 0, buf);
glDispatchCompute((w + 7) / 8, (h + 7) / 8, 1);
glMemoryBarrier(GL_SHADER_STORAGE_BARRIER_BIT |
GL_BUFFER_UPDATE_BARRIER_BIT);
glBindBufferBase(GL_SHADER_STORAGE_BUFFER, 0, 0);
} else {
glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0,
GL_TEXTURE_2D, tex[0], 0);
glBindBuffer(GL_PIXEL_PACK_BUFFER, buf);
glReadPixels(0, 0, w, h, GL_RGBA, GL_UNSIGNED_BYTE, 0);
}
glBindBuffer(GL_PIXEL_PACK_BUFFER, buf);
auto *mapped = (uint8_t *)glMapBufferRange(
GL_PIXEL_PACK_BUFFER, 0, bytes, GL_MAP_READ_BIT | GL_MAP_WRITE_BIT);
Check(mapped, "map");
double transfer = Ms(t);
Check(memcmp(mapped, input.data(), bytes) == 0,
"packed RGBA8 equals framebuffer input");
t = Clock::now();
SharpenRgbaToYuv(mapped, n, yuv.data());
double cin = Ms(t);
t = Clock::now();
Sharpen(yuv.data(), rgb.data(), w, h);
double kernel = Ms(t);
t = Clock::now();
SharpenRgbToRgba(rgb.data(), n, mapped);
double cout = Ms(t);
Check(glUnmapBuffer(GL_PIXEL_PACK_BUFFER), "unmap");
glBindBuffer(GL_PIXEL_PACK_BUFFER, 0);
t = Clock::now();
glBindBuffer(GL_PIXEL_UNPACK_BUFFER, buf);
glBindTexture(GL_TEXTURE_2D, tex[1]);
glTexSubImage2D(GL_TEXTURE_2D, 0, 0, 0, w, h, GL_RGBA, GL_UNSIGNED_BYTE,
nullptr);
glBindBuffer(GL_PIXEL_UNPACK_BUFFER, 0);
glFinish();
double upload = Ms(t);
glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0,
GL_TEXTURE_2D, tex[1], 0);
glReadPixels(0, 0, w, h, GL_RGBA, GL_UNSIGNED_BYTE, result.data());
Check(result == reference, "full original kernel transfer output exact");
Check(glGetError() == GL_NO_ERROR, "complete GL chain");
printf("GPU %dx%d %s run=%d transferMapMs=%.3f convertInMs=%.3f "
"kernelMs=%.3f convertOutMs=%.3f uploadGpuCompleteMs=%.3f "
"sumMs=%.3f exact=true\n",
w, h, compute ? "SSBO" : "PBO", run, transfer, cin, kernel, cout,
upload, transfer + cin + kernel + cout + upload);
fflush(stdout);
}
glDeleteBuffers(1, &buf);
glDeleteTextures(2, tex);
glDeleteFramebuffers(1, &fb);
glDeleteProgram(prog);
glDeleteShader(sh);
eglMakeCurrent(d, EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT);
eglDestroySurface(d, surf);
eglDestroyContext(d, ctx);
eglTerminate(d);
}
int main(int argc, char **argv) {
if (argc == 2 && std::strcmp(argv[1], "--stats") == 0) {
SignalStats(4000, 3000);
SignalStats(8192, 6144);
return 0;
}
if (argc == 1) {
VerifyConversions();
VerifyTiles();
return 0;
}
Check(argc == 4, "arguments width height shaderFile");
Gpu(atoi(argv[1]), atoi(argv[2]), argv[3]);
}