feat: SSBO float transfer and NEON conversion optimizations
This commit is contained in:
1 parent
87c9558d66
commit
eef80cb38e
12 files changed
+628
-61
No files matched your search
@@ -0,0 +1,80 @@
|
||||
#pragma once
|
||||
|
||||
#include <algorithm>
|
||||
#include <arm_neon.h>
|
||||
#include <cmath>
|
||||
#include <cstddef>
|
||||
#include <cstdint>
|
||||
|
||||
namespace photon::mgc_denoise {
|
||||
|
||||
// The GuidedUpsample guide has already received black-level/lens correction.
|
||||
// Its only remaining raw boundary is WB + unsigned Q14 quantization, followed
|
||||
// by RgbRawToYuv with black=0, gain=1, neutral gain map, white=16383.
|
||||
// Under those fixed inputs the AOT's gain interpolation is identity and its
|
||||
// final Q13 integer matrix is exactly the one below. Keep this specialization
|
||||
// local to the guided boundary; general raw conversion still uses the AOT.
|
||||
// Quantized RGB is in [0,16383], below the AOT's 29490 highlight knee;
|
||||
// neither its highlight compression nor signed-16 saturation changes RGB.
|
||||
// Matrix sums fit int32, and all rounded outputs fit int16. The V row retains
|
||||
// the AOT's R + round((-7441 G - 751 B)/8192) operation order.
|
||||
inline bool GuidedFloatRgbaToLinearYuv(const float *rgba, int width, int height,
|
||||
int padded_width, int padded_height,
|
||||
const float wb[3], int16_t *yuv) {
|
||||
if (!rgba || !wb || !yuv || width <= 0 || height <= 0 ||
|
||||
padded_width < width || padded_height < height || padded_width % 4 != 0)
|
||||
return false;
|
||||
for (int c = 0; c < 3; ++c)
|
||||
if (!std::isfinite(wb[c]) || wb[c] <= 0.f) return false;
|
||||
const size_t count = size_t(padded_width) * padded_height;
|
||||
int invalid = 0;
|
||||
#pragma omp parallel for schedule(static) num_threads(4) reduction(| : invalid)
|
||||
for (int y = 0; y < padded_height; ++y) {
|
||||
const float *row = rgba + size_t(std::min(y, height - 1)) * width * 4;
|
||||
for (int x = 0; x < padded_width; x += 4) {
|
||||
float32x4x4_t input;
|
||||
if (x + 4 <= width) {
|
||||
input = vld4q_f32(row + size_t(x) * 4);
|
||||
} else {
|
||||
// Replicate the original unpadded border, including incomplete groups.
|
||||
float edge[16];
|
||||
for (int lane = 0; lane < 4; ++lane)
|
||||
for (int c = 0; c < 4; ++c)
|
||||
edge[lane * 4 + c] = row[size_t(std::min(x + lane, width - 1)) * 4 + c];
|
||||
input = vld4q_f32(edge);
|
||||
}
|
||||
uint32x4_t nonfinite = vdupq_n_u32(0);
|
||||
int16x4_t rgb[3];
|
||||
for (int c = 0; c < 3; ++c) {
|
||||
const auto exponent = vandq_u32(vreinterpretq_u32_f32(input.val[c]),
|
||||
vdupq_n_u32(0x7f800000));
|
||||
nonfinite = vorrq_u32(nonfinite,
|
||||
vceqq_u32(exponent, vdupq_n_u32(0x7f800000)));
|
||||
}
|
||||
if (vmaxvq_u32(nonfinite)) {
|
||||
invalid = 1;
|
||||
continue;
|
||||
}
|
||||
for (int c = 0; c < 3; ++c) {
|
||||
const auto balanced = vmulq_n_f32(input.val[c], wb[c]);
|
||||
const auto bounded = vminq_f32(vmaxq_f32(balanced, vdupq_n_f32(0.f)),
|
||||
vdupq_n_f32(1.f));
|
||||
// lround rounds ties away from zero, independently of FPCR mode.
|
||||
rgb[c] = vreinterpret_s16_u16(vmovn_u32(
|
||||
vcvtaq_u32_f32(vmulq_n_f32(bounded, 16383.f))));
|
||||
}
|
||||
const auto r = rgb[0], g = rgb[1], b = rgb[2];
|
||||
const auto yy = vmlal_n_s16(vmlal_n_s16(vmull_n_s16(r, 1742), g, 5859), b, 591);
|
||||
const auto uu = vmlal_n_s16(vmlal_n_s16(vmull_n_s16(r, -1331), g, -4477), b, 5808);
|
||||
const auto vv = vmlal_n_s16(vmull_n_s16(g, -7441), b, -751);
|
||||
const size_t dest = size_t(y) * padded_width + x;
|
||||
// AOT uses signed rounding shifts (ties toward +infinity), not lrintf.
|
||||
vst1_s16(yuv + dest, vqrshrn_n_s32(yy, 13));
|
||||
vst1_s16(yuv + count + dest, vqrshrn_n_s32(uu, 13));
|
||||
vst1_s16(yuv + count * 2 + dest, vadd_s16(r, vqrshrn_n_s32(vv, 13)));
|
||||
}
|
||||
}
|
||||
return invalid == 0;
|
||||
}
|
||||
|
||||
} // namespace photon::mgc_denoise
|
||||
@@ -1,6 +1,9 @@
|
||||
#include "mgc_denoise_static.h"
|
||||
#include "mgc_guided_prepare_adapter.h"
|
||||
#include "mgc_sharpen_adapter.h"
|
||||
#include <algorithm>
|
||||
#include <android/log.h>
|
||||
#include <chrono>
|
||||
#include <cmath>
|
||||
#include <jni.h>
|
||||
#include <limits>
|
||||
@@ -8,6 +11,10 @@
|
||||
#include <vector>
|
||||
|
||||
namespace {
|
||||
using Clock = std::chrono::steady_clock;
|
||||
double Milliseconds(Clock::time_point begin, Clock::time_point end) {
|
||||
return std::chrono::duration<double, std::milli>(end - begin).count();
|
||||
}
|
||||
struct GuidedInputs {
|
||||
int width, height, padded_width, padded_height, scale;
|
||||
std::vector<int16_t> guide, low_guide;
|
||||
@@ -46,45 +53,49 @@ Java_com_hinnka_mycamera_raw_MgcGuidedUpsample_nativePrepare(
|
||||
env->GetDirectBufferCapacity(buffer) < jlong(ln * 16))
|
||||
return 0;
|
||||
try {
|
||||
const auto start = Clock::now();
|
||||
auto state = std::make_unique<GuidedInputs>();
|
||||
state->width = width;
|
||||
state->height = height;
|
||||
state->padded_width = pw;
|
||||
state->padded_height = ph;
|
||||
state->scale = scale;
|
||||
std::vector<uint16_t> rgb(n * 3);
|
||||
// Same white-balanced Q14 boundary as MgcFullResolutionDenoise.
|
||||
for (int y = 0; y < ph; ++y)
|
||||
for (int x = 0; x < pw; ++x) {
|
||||
const size_t source =
|
||||
(size_t(std::min(y, height - 1)) * width + std::min(x, width - 1)) *
|
||||
4;
|
||||
const size_t dest = size_t(y) * pw + x;
|
||||
for (int c = 0; c < 3; ++c) {
|
||||
const float value = rgba[source + c];
|
||||
if (!std::isfinite(value))
|
||||
return 0;
|
||||
rgb[c * n + dest] = uint16_t(
|
||||
std::lround(std::clamp(value * wb[c], 0.f, 1.f) * 16383.f));
|
||||
}
|
||||
}
|
||||
std::vector<int16_t> yuv(n * 3), low(ln * 3);
|
||||
if (RunRgbRawToYuv(rgb.data(), pw, ph, yuv.data()) != 0)
|
||||
return 0;
|
||||
if (RunGuidedBoxDownsample(yuv.data(), pw, ph, log2_scale, low.data()) != 0)
|
||||
return 0;
|
||||
state->guide.assign(yuv.begin(), yuv.begin() + n);
|
||||
Clock::time_point allocated, converted, boxed, guides;
|
||||
std::vector<int16_t> low(ln * 3);
|
||||
{
|
||||
std::vector<int16_t> yuv(n * 3);
|
||||
allocated = Clock::now();
|
||||
if (!GuidedFloatRgbaToLinearYuv(rgba, width, height, pw, ph, wb, yuv.data()))
|
||||
return 0;
|
||||
converted = Clock::now();
|
||||
if (RunGuidedBoxDownsample(yuv.data(), pw, ph, log2_scale, low.data()) != 0)
|
||||
return 0;
|
||||
boxed = Clock::now();
|
||||
state->guide.assign(yuv.begin(), yuv.begin() + n);
|
||||
// Release the two unused chroma planes before allocating low RGB.
|
||||
}
|
||||
state->low_guide.assign(low.begin(), low.begin() + ln);
|
||||
guides = Clock::now();
|
||||
// The low color branch starts before CCM/DCP/tone; never downsample an
|
||||
// encoded JPEG.
|
||||
std::vector<int16_t> low_rgb(ln * 3);
|
||||
if (RunYuvToRgb(low.data(), pw / scale, ph / scale, low_rgb.data()) != 0)
|
||||
return 0;
|
||||
const auto low_color = Clock::now();
|
||||
#pragma omp parallel for schedule(static) num_threads(4)
|
||||
for (size_t i = 0; i < ln; ++i) {
|
||||
for (int c = 0; c < 3; ++c)
|
||||
rgba[i * 4 + c] = low_rgb[c * ln + i] / 16383.f / wb[c];
|
||||
rgba[i * 4 + 3] = 1.f;
|
||||
}
|
||||
const auto finish = Clock::now();
|
||||
__android_log_print(ANDROID_LOG_INFO, "PLog_MgcGuidedUpsample",
|
||||
"prepare %dx%d scale=%d allocMs=%.1f q14YuvMs=%.1f boxMs=%.1f guidesMs=%.1f "
|
||||
"lowRgbMs=%.1f rgbaMs=%.1f totalNativeMs=%.1f",
|
||||
width, height, scale, Milliseconds(start, allocated),
|
||||
Milliseconds(allocated, converted), Milliseconds(converted, boxed),
|
||||
Milliseconds(boxed, guides), Milliseconds(guides, low_color),
|
||||
Milliseconds(low_color, finish), Milliseconds(start, finish));
|
||||
return reinterpret_cast<jlong>(state.release());
|
||||
} catch (const std::bad_alloc &) {
|
||||
OutOfMemory(env);
|
||||
@@ -121,18 +132,27 @@ Java_com_hinnka_mycamera_raw_MgcGuidedUpsample_nativeRender(
|
||||
return -1;
|
||||
}
|
||||
try {
|
||||
const auto start = Clock::now();
|
||||
std::vector<int16_t> yuv(ln * 3);
|
||||
std::vector<uint16_t> output(size_t(state->width) *
|
||||
((state->height + 1) & ~1) * 3);
|
||||
if (!SharpenFloatRgbaToYuv(rgba, ln, yuv.data()))
|
||||
return -1;
|
||||
const auto converted = Clock::now();
|
||||
const int result = RunGuidedUpsampleTo16Bit(
|
||||
state->guide.data(), state->padded_width, state->padded_height,
|
||||
state->low_guide.data(), yuv.data(), state->scale, state->width,
|
||||
state->height, curves, attenuation, output.data());
|
||||
if (result)
|
||||
return result;
|
||||
const auto reconstructed = Clock::now();
|
||||
SharpenRgbToFloatRgba(output.data(), n, rgba);
|
||||
const auto finish = Clock::now();
|
||||
__android_log_print(ANDROID_LOG_INFO, "PLog_MgcGuidedUpsample",
|
||||
"render %dx%d scale=%d yuvMs=%.1f guidedMs=%.1f rgbaMs=%.1f totalNativeMs=%.1f",
|
||||
state->width, state->height, state->scale, Milliseconds(start, converted),
|
||||
Milliseconds(converted, reconstructed), Milliseconds(reconstructed, finish),
|
||||
Milliseconds(start, finish));
|
||||
return 0;
|
||||
} catch (const std::bad_alloc &) {
|
||||
OutOfMemory(env);
|
||||
|
||||
@@ -98,13 +98,46 @@ void SharpenRgbToRgba(const uint16_t *rgb, size_t count, uint8_t *rgba) {
|
||||
}
|
||||
}
|
||||
bool SharpenFloatRgbaToYuv(const float *rgba, size_t count, int16_t *yuv) {
|
||||
for (size_t i = 0; i < count; ++i) {
|
||||
const size_t groups = count / 4;
|
||||
int invalid = 0;
|
||||
#pragma omp parallel for schedule(static) num_threads(4) reduction(| : invalid)
|
||||
for (size_t group = 0; group < groups; ++group) {
|
||||
const size_t i = group * 4;
|
||||
const float32x4x4_t input = vld4q_f32(rgba + i * 4);
|
||||
uint32x4_t nonfinite = vdupq_n_u32(0);
|
||||
for (int c = 0; c < 3; ++c) {
|
||||
const auto exponent = vandq_u32(vreinterpretq_u32_f32(input.val[c]),
|
||||
vdupq_n_u32(0x7f800000));
|
||||
nonfinite = vorrq_u32(nonfinite,
|
||||
vceqq_u32(exponent, vdupq_n_u32(0x7f800000)));
|
||||
}
|
||||
if (vmaxvq_u32(nonfinite)) {
|
||||
invalid = 1;
|
||||
continue;
|
||||
}
|
||||
const auto scaled = [](float32x4_t value) {
|
||||
return vmulq_n_f32(vminq_f32(vmaxq_f32(value, vdupq_n_f32(0.f)),
|
||||
vdupq_n_f32(1.f)), 4095.f);
|
||||
};
|
||||
const auto r = scaled(input.val[0]), g = scaled(input.val[1]),
|
||||
b = scaled(input.val[2]);
|
||||
for (int c = 0; c < 3; ++c) {
|
||||
const auto value = vaddq_f32(
|
||||
vaddq_f32(vmulq_n_f32(r, kMatrix[c * 3]),
|
||||
vmulq_n_f32(g, kMatrix[c * 3 + 1])),
|
||||
vmulq_n_f32(b, kMatrix[c * 3 + 2]));
|
||||
// Match lrintf's current rounding mode, retaining separate matrix adds.
|
||||
const auto rounded = vcvtq_s32_f32(vrndiq_f32(value));
|
||||
vst1_s16(yuv + c * count + i,
|
||||
vmovn_s32(vmaxq_s32(vdupq_n_s32(-4095),
|
||||
vminq_s32(vdupq_n_s32(4095), rounded))));
|
||||
}
|
||||
}
|
||||
if (invalid) return false;
|
||||
for (size_t i = groups * 4; i < count; ++i) {
|
||||
for (int c = 0; c < 3; ++c) {
|
||||
if (!std::isfinite(rgba[4 * i + c])) return false;
|
||||
}
|
||||
}
|
||||
#pragma omp parallel for schedule(static) num_threads(4)
|
||||
for (size_t i = 0; i < count; ++i) {
|
||||
const float r = std::clamp(rgba[4 * i], 0.f, 1.f) * 4095.f;
|
||||
const float g = std::clamp(rgba[4 * i + 1], 0.f, 1.f) * 4095.f;
|
||||
const float b = std::clamp(rgba[4 * i + 2], 0.f, 1.f) * 4095.f;
|
||||
@@ -118,8 +151,22 @@ bool SharpenFloatRgbaToYuv(const float *rgba, size_t count, int16_t *yuv) {
|
||||
}
|
||||
|
||||
void SharpenRgbToFloatRgba(const uint16_t *rgb, size_t count, float *rgba) {
|
||||
const size_t groups = count / 4;
|
||||
#pragma omp parallel for schedule(static) num_threads(4)
|
||||
for (size_t i = 0; i < count; ++i) {
|
||||
for (size_t group = 0; group < groups; ++group) {
|
||||
const size_t i = group * 4;
|
||||
const uint16x4x3_t input = vld3_u16(rgb + i * 3);
|
||||
float32x4x4_t output;
|
||||
for (int c = 0; c < 3; ++c) {
|
||||
const auto bounded = vmin_u16(input.val[c], vdup_n_u16(4095));
|
||||
// Division preserves the scalar boundary's rounding; a reciprocal does not.
|
||||
output.val[c] = vdivq_f32(vcvtq_f32_u32(vmovl_u16(bounded)),
|
||||
vdupq_n_f32(4095.f));
|
||||
}
|
||||
output.val[3] = vdupq_n_f32(1.f);
|
||||
vst4q_f32(rgba + i * 4, output);
|
||||
}
|
||||
for (size_t i = groups * 4; i < count; ++i) {
|
||||
for (int c = 0; c < 3; ++c) {
|
||||
rgba[4 * i + c] = std::min<uint16_t>(rgb[3 * i + c], 4095) / 4095.f;
|
||||
}
|
||||
|
||||
@@ -30,7 +30,7 @@ internal class MgcGuidedUpsample(private val transfer: RawFloatTextureTransfer)
|
||||
lowHeight = ((height + 15) and -16) / scale
|
||||
val capacityPixels = maxOf(width.toLong() * height, lowWidth.toLong() * lowHeight)
|
||||
try {
|
||||
transfer.read(texture, width, height, capacityPixels) { rgba ->
|
||||
transfer.read(texture, width, height, capacityPixels, label = "guidedPrepare") { rgba ->
|
||||
handle = nativePrepare(rgba, width, height, resolution.log2Downsample,
|
||||
MgcFullResolutionDenoise.normalizedRgbWhiteBalance(gains))
|
||||
check(handle != 0L) { "MGC linear guide/BoxDownsample preparation failed" }
|
||||
@@ -73,7 +73,7 @@ internal class MgcGuidedUpsample(private val transfer: RawFloatTextureTransfer)
|
||||
check(isPrepared && width == fullWidth && height == fullHeight)
|
||||
try {
|
||||
transfer.read(source, lowWidth, lowHeight,
|
||||
maxOf(width.toLong() * height, lowWidth.toLong() * lowHeight)) { rgba ->
|
||||
maxOf(width.toLong() * height, lowWidth.toLong() * lowHeight), label = "guidedRender") { rgba ->
|
||||
val result = nativeRender(handle, rgba, attenuation, curves)
|
||||
check(result == 0) { "MGC GuidedUpsample failed: $result" }
|
||||
}
|
||||
@@ -91,8 +91,7 @@ internal class MgcGuidedUpsample(private val transfer: RawFloatTextureTransfer)
|
||||
GLES30.glTexParameteri(GLES30.GL_TEXTURE_2D, GLES30.GL_TEXTURE_MAG_FILTER, GLES30.GL_LINEAR)
|
||||
GLES30.glTexParameteri(GLES30.GL_TEXTURE_2D, GLES30.GL_TEXTURE_WRAP_S, GLES30.GL_CLAMP_TO_EDGE)
|
||||
GLES30.glTexParameteri(GLES30.GL_TEXTURE_2D, GLES30.GL_TEXTURE_WRAP_T, GLES30.GL_CLAMP_TO_EDGE)
|
||||
GLES30.glTexImage2D(GLES30.GL_TEXTURE_2D, 0, GLES30.GL_RGBA16F, lowWidth, lowHeight,
|
||||
0, GLES30.GL_RGBA, GLES30.GL_HALF_FLOAT, null)
|
||||
GLES30.glTexStorage2D(GLES30.GL_TEXTURE_2D, 1, GLES30.GL_RGBA16F, lowWidth, lowHeight)
|
||||
check(GLES30.glGetError() == GLES30.GL_NO_ERROR)
|
||||
return texture
|
||||
} catch (error: Throwable) { GLES30.glDeleteTextures(1, names, 0); throw error }
|
||||
|
||||
@@ -30,7 +30,7 @@ internal class MgcSharpen {
|
||||
scratch = null
|
||||
scratch = checkNotNull(LargeDirectBuffer.allocate(scratchBytes, "MGC sharpen YUV/RGB"))
|
||||
}
|
||||
transfer.read(sourceTexture, width, height) { mapped ->
|
||||
transfer.read(sourceTexture, width, height, label = "sharpen") { mapped ->
|
||||
val result = nativeSharpenRgbaFloat(mapped, checkNotNull(scratch), width, height,
|
||||
snr, attenuation, curves.points)
|
||||
check(result == 0) { "MGC original sharpen failed: $result" }
|
||||
|
||||
@@ -6867,10 +6867,7 @@ class RawDemosaicProcessor {
|
||||
GLES30.glGenTextures(1, textures, 0)
|
||||
sharpenTextureId = textures[0]
|
||||
GLES30.glBindTexture(GLES30.GL_TEXTURE_2D, sharpenTextureId)
|
||||
GLES30.glTexImage2D(
|
||||
GLES30.GL_TEXTURE_2D, 0, GLES30.GL_RGBA16F, width, height, 0,
|
||||
GLES30.GL_RGBA, GLES30.GL_HALF_FLOAT, null
|
||||
)
|
||||
GLES30.glTexStorage2D(GLES30.GL_TEXTURE_2D, 1, GLES30.GL_RGBA16F, width, height)
|
||||
GLES30.glTexParameteri(GLES30.GL_TEXTURE_2D, GLES30.GL_TEXTURE_MIN_FILTER, GLES30.GL_LINEAR)
|
||||
GLES30.glTexParameteri(GLES30.GL_TEXTURE_2D, GLES30.GL_TEXTURE_MAG_FILTER, GLES30.GL_LINEAR)
|
||||
|
||||
|
||||
@@ -3,6 +3,7 @@ package com.hinnka.mycamera.raw
|
||||
import android.opengl.GLES30
|
||||
import android.opengl.GLES31
|
||||
import com.hinnka.mycamera.processor.GlesGpuCompletion
|
||||
import com.hinnka.mycamera.utils.PLog
|
||||
import java.nio.ByteBuffer
|
||||
import java.nio.ByteOrder
|
||||
|
||||
@@ -12,11 +13,15 @@ internal class RawFloatTextureTransfer {
|
||||
private var capacity = 0
|
||||
private var framebuffer = 0
|
||||
private var program = 0
|
||||
private var uploadProgram = 0
|
||||
private var initialized = false
|
||||
private var maxSsboBytes = 0L
|
||||
private var ssboOffsetAlignment = 1
|
||||
|
||||
fun read(texture: Int, width: Int, height: Int, capacityPixels: Long = width.toLong() * height,
|
||||
label: String,
|
||||
consume: (ByteBuffer) -> Unit) {
|
||||
val start = System.nanoTime()
|
||||
val inputBytes = width.toLong() * height * 16
|
||||
val bytes = capacityPixels * 16
|
||||
require(width > 0 && height > 0 && bytes >= inputBytes && bytes <= Int.MAX_VALUE)
|
||||
@@ -32,16 +37,21 @@ internal class RawFloatTextureTransfer {
|
||||
checkGl("allocate float transfer")
|
||||
capacity = bytes.toInt()
|
||||
}
|
||||
GlesGpuCompletion.awaitSubmittedWork("MGC float input", checkGlError = ::checkGl)
|
||||
val allocationMs = elapsedMs(start)
|
||||
val stripeRows = if (program != 0) {
|
||||
RawFloatTransferLayout.stripeRows(width, height, maxSsboBytes, ssboOffsetAlignment)
|
||||
} else 0
|
||||
val upstreamWaitMs = GlesGpuCompletion.awaitSubmittedWork("MGC float $label", checkGlError = ::checkGl)
|
||||
val transferStart = System.nanoTime()
|
||||
try {
|
||||
if (program != 0 && bytes <= maxSsboBytes) {
|
||||
if (stripeRows > 0) {
|
||||
GLES31.glUseProgram(program)
|
||||
GLES31.glActiveTexture(GLES31.GL_TEXTURE0)
|
||||
GLES31.glBindTexture(GLES31.GL_TEXTURE_2D, texture)
|
||||
GLES31.glUniform1i(GLES31.glGetUniformLocation(program, "uInput"), 0)
|
||||
GLES31.glUniform2i(GLES31.glGetUniformLocation(program, "uSize"), width, height)
|
||||
GLES31.glBindBufferBase(GLES31.GL_SHADER_STORAGE_BUFFER, 0, buffer)
|
||||
GLES31.glDispatchCompute((width + 7) / 8, (height + 7) / 8, 1)
|
||||
// Bind only the input region, independent of the larger native output capacity.
|
||||
// Disjoint ranges can be submitted together; map once at the CPU boundary.
|
||||
dispatchStripes(program, width, height, stripeRows)
|
||||
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 {
|
||||
@@ -60,14 +70,29 @@ internal class RawFloatTextureTransfer {
|
||||
GLES30.glReadPixels(0, 0, width, height, GLES30.GL_RGBA, GLES30.GL_FLOAT, 0)
|
||||
}
|
||||
checkGl("read float texture")
|
||||
val submitMs = elapsedMs(transferStart)
|
||||
val mapStart = System.nanoTime()
|
||||
val mapped = checkNotNull(GLES30.glMapBufferRange(GLES30.GL_PIXEL_PACK_BUFFER,
|
||||
0, bytes.toInt(), GLES30.GL_MAP_READ_BIT or GLES30.GL_MAP_WRITE_BIT) as? ByteBuffer)
|
||||
val mapMs = elapsedMs(mapStart)
|
||||
val nativeStart = System.nanoTime()
|
||||
var nativeMs = 0.0
|
||||
var unmapMs = 0.0
|
||||
try {
|
||||
consume(mapped.order(ByteOrder.nativeOrder()))
|
||||
} finally {
|
||||
nativeMs = elapsedMs(nativeStart)
|
||||
val unmapStart = System.nanoTime()
|
||||
check(GLES30.glUnmapBuffer(GLES30.GL_PIXEL_PACK_BUFFER)) { "Invalid float transfer mapping" }
|
||||
unmapMs = elapsedMs(unmapStart)
|
||||
}
|
||||
PLog.i(TAG, "$label size=${width}x$height inputBytes=$inputBytes capacityBytes=$bytes " +
|
||||
"transfer=${if (stripeRows > 0) "SSBO" else "PBO"} stripeRows=$stripeRows " +
|
||||
"maxSsboBytes=$maxSsboBytes allocationMs=$allocationMs upstreamGpuWaitMs=$upstreamWaitMs " +
|
||||
"transferSubmitMs=$submitMs mapMs=$mapMs nativeMs=$nativeMs unmapMs=$unmapMs " +
|
||||
"totalCpuMs=${elapsedMs(start)}")
|
||||
} finally {
|
||||
if (stripeRows > 0) GLES31.glBindBufferBase(GLES31.GL_SHADER_STORAGE_BUFFER, 0, 0)
|
||||
GLES30.glBindBuffer(GLES30.GL_PIXEL_PACK_BUFFER, 0)
|
||||
if (framebuffer != 0) {
|
||||
GLES30.glBindFramebuffer(GLES30.GL_READ_FRAMEBUFFER, framebuffer)
|
||||
@@ -78,8 +103,47 @@ internal class RawFloatTextureTransfer {
|
||||
}
|
||||
}
|
||||
|
||||
/** The destination uses immutable RGBA16F storage for write-only image access. */
|
||||
fun upload(texture: Int, width: Int, height: Int) {
|
||||
check(nativeUpload(buffer, texture, width, height)) { "Float PBO upload failed" }
|
||||
require(width > 0 && height > 0 && width.toLong() * height * 16 <= capacity)
|
||||
val start = System.nanoTime()
|
||||
val stripeRows = if (uploadProgram != 0) {
|
||||
RawFloatTransferLayout.stripeRows(width, height, maxSsboBytes, ssboOffsetAlignment)
|
||||
} else 0
|
||||
if (stripeRows > 0) {
|
||||
try {
|
||||
// Unmap made the CPU writes visible. Avoid the driver's GL_FLOAT -> RGBA16F
|
||||
// pixel-unpack path, which can block for hundreds of ms at some image sizes.
|
||||
GLES31.glUseProgram(uploadProgram)
|
||||
GLES31.glBindImageTexture(0, texture, 0, false, 0, GLES31.GL_WRITE_ONLY, GLES30.GL_RGBA16F)
|
||||
dispatchStripes(uploadProgram, width, height, stripeRows)
|
||||
GLES31.glMemoryBarrier(GLES31.GL_TEXTURE_FETCH_BARRIER_BIT or
|
||||
GLES31.GL_FRAMEBUFFER_BARRIER_BIT or GLES31.GL_SHADER_IMAGE_ACCESS_BARRIER_BIT)
|
||||
checkGl("upload float texture via image store")
|
||||
} finally {
|
||||
GLES31.glBindImageTexture(0, 0, 0, false, 0, GLES31.GL_WRITE_ONLY, GLES30.GL_RGBA16F)
|
||||
GLES31.glBindBufferBase(GLES31.GL_SHADER_STORAGE_BUFFER, 0, 0)
|
||||
}
|
||||
} else {
|
||||
check(nativeUpload(buffer, texture, width, height)) { "Float PBO upload failed" }
|
||||
}
|
||||
PLog.i(TAG, "upload size=${width}x$height transfer=${if (stripeRows > 0) "SSBO_IMAGE" else "PBO"} " +
|
||||
"stripeRows=$stripeRows uploadSubmitMs=${elapsedMs(start)}")
|
||||
}
|
||||
|
||||
private fun dispatchStripes(computeProgram: Int, width: Int, height: Int, stripeRows: Int) {
|
||||
GLES31.glUniform2i(GLES31.glGetUniformLocation(computeProgram, "uSize"), width, height)
|
||||
val rowOffsetLocation = GLES31.glGetUniformLocation(computeProgram, "uRowOffset")
|
||||
val rowsLocation = GLES31.glGetUniformLocation(computeProgram, "uRows")
|
||||
val rowBytes = width * 16
|
||||
for (row in 0 until height step stripeRows) {
|
||||
val rows = minOf(stripeRows, height - row)
|
||||
GLES31.glUniform1i(rowOffsetLocation, row)
|
||||
GLES31.glUniform1i(rowsLocation, rows)
|
||||
GLES31.glBindBufferRange(GLES31.GL_SHADER_STORAGE_BUFFER, 0, buffer,
|
||||
row * rowBytes, rows * rowBytes)
|
||||
GLES31.glDispatchCompute((width + 7) / 8, (rows + 7) / 8, 1)
|
||||
}
|
||||
}
|
||||
|
||||
fun releaseBuffers() {
|
||||
@@ -91,7 +155,8 @@ internal class RawFloatTextureTransfer {
|
||||
fun release() {
|
||||
releaseBuffers()
|
||||
if (program != 0) GLES30.glDeleteProgram(program)
|
||||
program = 0; initialized = false; maxSsboBytes = 0L
|
||||
if (uploadProgram != 0) GLES30.glDeleteProgram(uploadProgram)
|
||||
program = 0; uploadProgram = 0; initialized = false; maxSsboBytes = 0L; ssboOffsetAlignment = 1
|
||||
}
|
||||
|
||||
private fun initialize() {
|
||||
@@ -104,14 +169,27 @@ internal class RawFloatTextureTransfer {
|
||||
val limit = LongArray(1)
|
||||
GLES31.glGetInteger64v(GLES31.GL_MAX_SHADER_STORAGE_BLOCK_SIZE, limit, 0)
|
||||
maxSsboBytes = limit[0]
|
||||
val alignment = IntArray(1)
|
||||
GLES31.glGetIntegerv(GLES31.GL_SHADER_STORAGE_BUFFER_OFFSET_ALIGNMENT, alignment, 0)
|
||||
check(alignment[0] > 0) { "Invalid SSBO offset alignment: ${alignment[0]}" }
|
||||
ssboOffsetAlignment = alignment[0]
|
||||
program = RawGlesProgram.compileCompute(PACK, "MgcFloatTransfer")
|
||||
val imageUnits = IntArray(1)
|
||||
val computeImages = IntArray(1)
|
||||
GLES31.glGetIntegerv(GLES31.GL_MAX_IMAGE_UNITS, imageUnits, 0)
|
||||
GLES31.glGetIntegerv(GLES31.GL_MAX_COMPUTE_IMAGE_UNIFORMS, computeImages, 0)
|
||||
if (imageUnits[0] > 0 && computeImages[0] > 0) {
|
||||
uploadProgram = RawGlesProgram.compileCompute(UNPACK, "MgcFloatUpload")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private external fun nativeUpload(pbo: Int, texture: Int, width: Int, height: Int): Boolean
|
||||
|
||||
companion object {
|
||||
private const val TAG = "RawFloatTextureTransfer"
|
||||
init { System.loadLibrary("my-native-lib") }
|
||||
private fun elapsedMs(start: Long) = (System.nanoTime() - start) / 1_000_000.0
|
||||
private fun checkGl(label: String) {
|
||||
val error = GLES30.glGetError()
|
||||
check(error == GLES30.GL_NO_ERROR) { "$label: GL error 0x${error.toString(16)}" }
|
||||
@@ -123,11 +201,31 @@ internal class RawFloatTextureTransfer {
|
||||
layout(local_size_x = 8, local_size_y = 8) in;
|
||||
uniform highp sampler2D uInput;
|
||||
uniform ivec2 uSize;
|
||||
uniform int uRowOffset;
|
||||
uniform int uRows;
|
||||
layout(std430, binding = 0) writeonly buffer Pixels { vec4 pixels[]; };
|
||||
void main() {
|
||||
ivec2 p = ivec2(gl_GlobalInvocationID.xy);
|
||||
if (any(greaterThanEqual(p, uSize))) return;
|
||||
pixels[p.y * uSize.x + p.x] = texelFetch(uInput, p, 0);
|
||||
if (p.x >= uSize.x || p.y >= uRows) return;
|
||||
pixels[p.y * uSize.x + p.x] = texelFetch(uInput, p + ivec2(0, uRowOffset), 0);
|
||||
}
|
||||
""".trimIndent()
|
||||
|
||||
internal val UNPACK = """
|
||||
#version 310 es
|
||||
precision highp float;
|
||||
precision highp int;
|
||||
layout(local_size_x = 8, local_size_y = 8) in;
|
||||
layout(std430, binding = 0) readonly buffer Pixels { vec4 pixels[]; };
|
||||
layout(rgba16f, binding = 0) writeonly uniform highp image2D uOutput;
|
||||
uniform ivec2 uSize;
|
||||
uniform int uRowOffset;
|
||||
uniform int uRows;
|
||||
void main() {
|
||||
ivec2 p = ivec2(gl_GlobalInvocationID.xy);
|
||||
if (p.x >= uSize.x || p.y >= uRows) return;
|
||||
vec4 value = pixels[p.y * uSize.x + p.x];
|
||||
imageStore(uOutput, p + ivec2(0, uRowOffset), value);
|
||||
}
|
||||
""".trimIndent()
|
||||
}
|
||||
|
||||
@@ -0,0 +1,20 @@
|
||||
package com.hinnka.mycamera.raw
|
||||
|
||||
/** Each SSBO range covers whole rows and starts at a driver-aligned byte offset. */
|
||||
internal object RawFloatTransferLayout {
|
||||
fun stripeRows(width: Int, height: Int, maxBlockBytes: Long, offsetAlignment: Int): Int {
|
||||
require(width > 0 && height > 0 && offsetAlignment > 0)
|
||||
val rowBytes = width.toLong() * 16
|
||||
if (rowBytes * height <= maxBlockBytes) return height
|
||||
var a = rowBytes
|
||||
var b = offsetAlignment.toLong()
|
||||
while (b != 0L) {
|
||||
val remainder = a % b
|
||||
a = b
|
||||
b = remainder
|
||||
}
|
||||
val alignedRows = offsetAlignment / a
|
||||
// Zero means even one aligned stripe cannot fit: retain framebuffer readback.
|
||||
return (maxBlockBytes / rowBytes / alignedRows * alignedRows).toInt()
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,185 @@
|
||||
// Standalone ARM64 executable; never installs an APK or uses instrumentation.
|
||||
#include "mgc_denoise_static.h"
|
||||
#include "mgc_guided_prepare_adapter.h"
|
||||
#include <EGL/egl.h>
|
||||
#include <GLES3/gl31.h>
|
||||
#include <chrono>
|
||||
#include <cmath>
|
||||
#include <cstdio>
|
||||
#include <cstdlib>
|
||||
#include <cstring>
|
||||
#include <limits>
|
||||
#include <random>
|
||||
#include <jni.h>
|
||||
#include <vector>
|
||||
using namespace photon::mgc_denoise;
|
||||
using Clock = std::chrono::steady_clock;
|
||||
extern "C" jlong Java_com_hinnka_mycamera_raw_MgcGuidedUpsample_nativePrepare(
|
||||
JNIEnv *, jobject, jobject, jint, jint, jint, jfloatArray);
|
||||
extern "C" void Java_com_hinnka_mycamera_raw_MgcGuidedUpsample_nativeRelease(
|
||||
JNIEnv *, jobject, jlong);
|
||||
struct Buffer { void *data; jlong bytes; };
|
||||
static JNIEnv FakeJni() {
|
||||
static JNINativeInterface functions{};
|
||||
functions.GetDirectBufferAddress = [](JNIEnv *, jobject b) { return reinterpret_cast<Buffer *>(b)->data; };
|
||||
functions.GetDirectBufferCapacity = [](JNIEnv *, jobject b) { return reinterpret_cast<Buffer *>(b)->bytes; };
|
||||
functions.GetArrayLength = [](JNIEnv *, jarray a) { return jsize(reinterpret_cast<Buffer *>(a)->bytes / 4); };
|
||||
functions.GetFloatArrayRegion = [](JNIEnv *, jfloatArray a, jsize start, jsize n, jfloat *out) {
|
||||
auto *p = static_cast<float *>(reinterpret_cast<Buffer *>(a)->data);
|
||||
std::copy(p + start, p + start + n, out);
|
||||
};
|
||||
functions.ExceptionCheck = [](JNIEnv *) -> jboolean { return JNI_FALSE; };
|
||||
return JNIEnv{&functions};
|
||||
}
|
||||
static void Check(bool ok, const char *label) {
|
||||
if (!ok) { fprintf(stderr, "FAIL %s\n", label); std::exit(1); }
|
||||
}
|
||||
static double Ms(Clock::time_point a, Clock::time_point b) {
|
||||
return std::chrono::duration<double, std::milli>(b - a).count();
|
||||
}
|
||||
static void Original(const float *rgba, int w, int h, int pw, int ph,
|
||||
const float wb[3], uint16_t *rgb, int16_t *yuv,
|
||||
double *q14_ms = nullptr, double *yuv_ms = nullptr) {
|
||||
const size_t n = size_t(pw) * ph;
|
||||
const auto start = Clock::now();
|
||||
#pragma omp parallel for schedule(static) num_threads(4)
|
||||
for (int y = 0; y < ph; ++y)
|
||||
for (int x = 0; x < pw; ++x) {
|
||||
const size_t src = (size_t(std::min(y, h - 1)) * w + std::min(x, w - 1)) * 4;
|
||||
for (int c = 0; c < 3; ++c) {
|
||||
const float v = rgba[src + c];
|
||||
Check(std::isfinite(v), "reference finite");
|
||||
rgb[size_t(c) * n + size_t(y) * pw + x] = uint16_t(
|
||||
std::lround(std::clamp(v * wb[c], 0.f, 1.f) * 16383.f));
|
||||
}
|
||||
}
|
||||
const auto converted = Clock::now();
|
||||
Check(RunRgbRawToYuv(rgb, pw, ph, yuv) == 0, "original AOT");
|
||||
const auto end = Clock::now();
|
||||
if (q14_ms) *q14_ms = Ms(start, converted);
|
||||
if (yuv_ms) *yuv_ms = Ms(converted, end);
|
||||
}
|
||||
static void Compare(const std::vector<float> &rgba, int w, int h, const float wb[3]) {
|
||||
const int pw = (w + 127) & ~127, ph = (h + 15) & ~15;
|
||||
const size_t n = size_t(pw) * ph;
|
||||
std::vector<uint16_t> rgb(n * 3);
|
||||
std::vector<int16_t> old(n * 3), now(n * 3 + 32, 12345);
|
||||
Original(rgba.data(), w, h, pw, ph, wb, rgb.data(), old.data());
|
||||
Check(GuidedFloatRgbaToLinearYuv(rgba.data(), w, h, pw, ph, wb, now.data()), "fused valid");
|
||||
if (memcmp(old.data(), now.data(), n * 6)) {
|
||||
for (size_t i = 0; i < n * 3; ++i) if (old[i] != now[i]) {
|
||||
fprintf(stderr, "mismatch %dx%d wb=%g,%g,%g index=%zu old=%d new=%d\n",
|
||||
w, h, wb[0], wb[1], wb[2], i, old[i], now[i]); break;
|
||||
}
|
||||
std::exit(2);
|
||||
}
|
||||
for (size_t i = n * 3; i < now.size(); ++i) Check(now[i] == 12345, "output guard");
|
||||
}
|
||||
static void Numerics() {
|
||||
std::mt19937 random(1709);
|
||||
const float gains[][3] = {{1.f,1.f,1.f},{.001f,.73f,4.18f},{2.f,1.f,1.7f},
|
||||
{std::numeric_limits<float>::max(),.00001f,1000.f}};
|
||||
size_t checked = 0;
|
||||
for (auto shape : {std::pair<int,int>{1,1},{3,5},{127,15},{128,16},{129,17},
|
||||
{385,321},{1024,1024},{2728,2048}}) {
|
||||
const int w = shape.first, h = shape.second;
|
||||
std::vector<float> rgba(size_t(w) * h * 4);
|
||||
for (float &v : rgba) v = float(int(random() % 65536) - 16384) / 16383.f;
|
||||
for (const auto &wb : gains) { Compare(rgba, w, h, wb); checked += size_t(w) * h; }
|
||||
}
|
||||
// All Q14 levels on every axis; ties and neighbors exercise lround's rule.
|
||||
for (int axis = 0; axis < 3; ++axis) {
|
||||
std::vector<float> rgba(16384 * 4);
|
||||
for (int i = 0; i < 16384; ++i) for (int c = 0; c < 4; ++c)
|
||||
rgba[i * 4 + c] = c == axis ? float(i) / 16383.f : float(random() % 16384) / 16383.f;
|
||||
Compare(rgba, 128, 128, gains[0]);
|
||||
for (int delta = -1; delta <= 1; ++delta) {
|
||||
for (int i = 0; i < 16384; ++i) {
|
||||
const float tie = (float(i) + .5f) / 16383.f;
|
||||
rgba[i * 4 + axis] = delta == 0 ? tie : std::nextafter(tie, delta < 0 ? 0.f : 2.f);
|
||||
}
|
||||
Compare(rgba, 128, 128, gains[0]);
|
||||
}
|
||||
}
|
||||
for (float bad : {std::numeric_limits<float>::infinity(),
|
||||
-std::numeric_limits<float>::infinity(),
|
||||
std::numeric_limits<float>::quiet_NaN()})
|
||||
for (int pixel = 0; pixel < 15; ++pixel) for (int c = 0; c < 3; ++c) {
|
||||
std::vector<float> rgba(15 * 4, .5f); std::vector<int16_t> out(128 * 16 * 3);
|
||||
rgba[pixel * 4 + c] = bad;
|
||||
Check(!GuidedFloatRgbaToLinearYuv(rgba.data(), 3, 5, 128, 16, gains[0], out.data()), "nonfinite rejection");
|
||||
}
|
||||
{
|
||||
std::vector<float> rgba(3 * 5 * 4, .5f);
|
||||
std::vector<int16_t> out(128 * 16 * 3);
|
||||
Check(!GuidedFloatRgbaToLinearYuv(rgba.data(), 3, 5, 127, 16, gains[0], out.data()), "non-vector-aligned padding");
|
||||
Check(!GuidedFloatRgbaToLinearYuv(rgba.data(), 3, 5, 128, 4, gains[0], out.data()), "short padded height");
|
||||
Check(!GuidedFloatRgbaToLinearYuv(rgba.data(), 129, 5, 128, 16, gains[0], out.data()), "short padded width");
|
||||
for (size_t i = 0; i < rgba.size() / 4; ++i) rgba[i * 4 + 3] = std::numeric_limits<float>::quiet_NaN();
|
||||
Compare(rgba, 3, 5, gains[0]); // Alpha is not part of the camera RGB boundary.
|
||||
}
|
||||
printf("PASS AOT equivalence: %zu+ pixels, WB/clipping/overflow, Q14 axes/ties, odd padding, finite rejection\n", checked);
|
||||
}
|
||||
static void Benchmark(const char *kind, const float *rgba, int w, int h) {
|
||||
const int pw = (w + 127) & ~127, ph = (h + 15) & ~15;
|
||||
const size_t n = size_t(pw) * ph;
|
||||
const float wb[3] = {2.14f,1.f,1.62f};
|
||||
std::vector<uint16_t> rgb(n * 3);
|
||||
std::vector<int16_t> old(n * 3), now(n * 3);
|
||||
std::vector<double> q, y, fused;
|
||||
for (int iteration = 0; iteration < 10; ++iteration) {
|
||||
double qms, yms;
|
||||
Original(rgba, w, h, pw, ph, wb, rgb.data(), old.data(), &qms, &yms);
|
||||
const auto begin = Clock::now();
|
||||
Check(GuidedFloatRgbaToLinearYuv(rgba, w, h, pw, ph, wb, now.data()), "benchmark valid");
|
||||
const auto end = Clock::now();
|
||||
Check(old == now, "benchmark pixels");
|
||||
if (iteration >= 2) { q.push_back(qms); y.push_back(yms); fused.push_back(Ms(begin, end)); }
|
||||
}
|
||||
std::sort(q.begin(), q.end()); std::sort(y.begin(), y.end()); std::sort(fused.begin(), fused.end());
|
||||
printf("%s %dx%d median q14=%.2fms AOT=%.2fms fused=%.2fms (preallocated)\n",kind,w,h,q[4],y[4],fused[4]);
|
||||
}
|
||||
static void MappedBenchmark() {
|
||||
EGLDisplay display = eglGetDisplay(EGL_DEFAULT_DISPLAY);
|
||||
Check(eglInitialize(display, nullptr, nullptr), "EGL init");
|
||||
const EGLint attrs[] = {EGL_SURFACE_TYPE,EGL_PBUFFER_BIT,EGL_RENDERABLE_TYPE,EGL_OPENGL_ES3_BIT,EGL_NONE};
|
||||
EGLConfig config; EGLint count;
|
||||
Check(eglChooseConfig(display,attrs,&config,1,&count) && count,"EGL config");
|
||||
const EGLint context_attrs[] = {EGL_CONTEXT_CLIENT_VERSION,3,EGL_NONE};
|
||||
const EGLint surface_attrs[] = {EGL_WIDTH,1,EGL_HEIGHT,1,EGL_NONE};
|
||||
auto context = eglCreateContext(display,config,EGL_NO_CONTEXT,context_attrs);
|
||||
auto surface = eglCreatePbufferSurface(display,config,surface_attrs);
|
||||
Check(eglMakeCurrent(display,surface,surface,context),"EGL current");
|
||||
printf("GPU %s / %s\n",glGetString(GL_RENDERER),glGetString(GL_VERSION));
|
||||
const int w=2728,h=2048,n=w*h;
|
||||
const char *source="#version 310 es\nprecision highp float;precision highp int;layout(local_size_x=128) in;layout(std430,binding=0) writeonly buffer Pixels{vec4 pixels[];};uniform int uCount;void main(){uint i=gl_GlobalInvocationID.x;if(i>=uint(uCount))return;pixels[i]=vec4(float((i*13u)%16384u),float((i*47u)%16384u),float((i*101u)%16384u),16383.0)/16383.0;}";
|
||||
GLuint shader=glCreateShader(GL_COMPUTE_SHADER);glShaderSource(shader,1,&source,nullptr);glCompileShader(shader);
|
||||
GLint ok;glGetShaderiv(shader,GL_COMPILE_STATUS,&ok);Check(ok,"compute compile");
|
||||
GLuint program=glCreateProgram();glAttachShader(program,shader);glLinkProgram(program);
|
||||
glGetProgramiv(program,GL_LINK_STATUS,&ok);Check(ok,"compute link");
|
||||
GLuint buffer;glGenBuffers(1,&buffer);glBindBuffer(GL_SHADER_STORAGE_BUFFER,buffer);
|
||||
GLint64 limit;glGetInteger64v(GL_MAX_SHADER_STORAGE_BLOCK_SIZE,&limit);Check(int64_t(n)*16<=limit,"SSBO limit");
|
||||
glBufferData(GL_SHADER_STORAGE_BUFFER,size_t(n)*16,nullptr,GL_STREAM_COPY);
|
||||
glUseProgram(program);glUniform1i(glGetUniformLocation(program,"uCount"),n);
|
||||
glBindBufferBase(GL_SHADER_STORAGE_BUFFER,0,buffer);glDispatchCompute((n+127)/128,1,1);
|
||||
glMemoryBarrier(GL_SHADER_STORAGE_BARRIER_BIT|GL_BUFFER_UPDATE_BARRIER_BIT);
|
||||
glBindBufferBase(GL_SHADER_STORAGE_BUFFER,0,0);glBindBuffer(GL_PIXEL_PACK_BUFFER,buffer);
|
||||
auto mapped=static_cast<float*>(glMapBufferRange(GL_PIXEL_PACK_BUFFER,0,size_t(n)*16,GL_MAP_READ_BIT|GL_MAP_WRITE_BIT));
|
||||
Check(mapped && glGetError()==GL_NO_ERROR,"mapped GPU-produced input");
|
||||
std::vector<float> heap(mapped,mapped+size_t(n)*4);
|
||||
Benchmark("heap",heap.data(),w,h);Benchmark("GPU-mapped",mapped,w,h);
|
||||
auto env = FakeJni();
|
||||
float wb[] = {2.14f,1.f,1.62f};
|
||||
Buffer input{mapped,jlong(n)*16},gains{wb,12};
|
||||
const auto prepare_begin = Clock::now();
|
||||
const auto handle = Java_com_hinnka_mycamera_raw_MgcGuidedUpsample_nativePrepare(
|
||||
&env,nullptr,reinterpret_cast<jobject>(&input),w,h,1,reinterpret_cast<jfloatArray>(&gains));
|
||||
const auto prepare_end = Clock::now();
|
||||
Check(handle != 0,"complete mapped nativePrepare");
|
||||
printf("GPU-mapped %dx%d complete nativePrepare=%.2fms (fresh allocations, box, low RGB, mapped writeback)\n",w,h,Ms(prepare_begin,prepare_end));
|
||||
Java_com_hinnka_mycamera_raw_MgcGuidedUpsample_nativeRelease(&env,nullptr,handle);
|
||||
Check(glUnmapBuffer(GL_PIXEL_PACK_BUFFER),"unmap");glDeleteBuffers(1,&buffer);
|
||||
glDeleteProgram(program);glDeleteShader(shader);eglMakeCurrent(display,EGL_NO_SURFACE,EGL_NO_SURFACE,EGL_NO_CONTEXT);
|
||||
eglDestroySurface(display,surface);eglDestroyContext(display,context);eglTerminate(display);
|
||||
}
|
||||
int main() { Numerics(); MappedBenchmark(); }
|
||||
@@ -10,6 +10,7 @@
|
||||
#include <fstream>
|
||||
#include <iterator>
|
||||
#include <jni.h>
|
||||
#include <numeric>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
using namespace photon::mgc_denoise;
|
||||
@@ -112,7 +113,7 @@ static std::vector<float> Jni(int w, int h, int scale, int originX = 0, int orig
|
||||
pixels.resize(size_t(w) * h * 4);
|
||||
return pixels;
|
||||
}
|
||||
static void Gpu(const char *shaderPath, const char *boxPath) {
|
||||
static void Gpu(const char *shaderPath, const char *boxPath, const char *uploadPath) {
|
||||
EGLDisplay display = eglGetDisplay(EGL_DEFAULT_DISPLAY);
|
||||
Check(eglInitialize(display, nullptr, nullptr), "EGL initialize");
|
||||
EGLint attributes[] = {EGL_SURFACE_TYPE, EGL_PBUFFER_BIT, EGL_RENDERABLE_TYPE,
|
||||
@@ -135,14 +136,14 @@ static void Gpu(const char *shaderPath, const char *boxPath) {
|
||||
pixels[i * 4 + 2] = .25f;
|
||||
pixels[i * 4 + 3] = 1;
|
||||
}
|
||||
GLuint textures[2];
|
||||
glGenTextures(2, textures);
|
||||
GLuint textures[3];
|
||||
glGenTextures(3, textures);
|
||||
for (auto t : textures) {
|
||||
glBindTexture(GL_TEXTURE_2D, t);
|
||||
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
|
||||
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
|
||||
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA16F, w, h, 0, GL_RGBA, GL_FLOAT,
|
||||
pixels.data());
|
||||
glTexStorage2D(GL_TEXTURE_2D, 1, GL_RGBA16F, w, h);
|
||||
glTexSubImage2D(GL_TEXTURE_2D, 0, 0, 0, w, h, GL_RGBA, GL_FLOAT, pixels.data());
|
||||
}
|
||||
GLuint framebuffer, pbo;
|
||||
glGenFramebuffers(1, &framebuffer);
|
||||
@@ -182,8 +183,21 @@ static void Gpu(const char *shaderPath, const char *boxPath) {
|
||||
glBindTexture(GL_TEXTURE_2D, textures[0]);
|
||||
glUniform1i(glGetUniformLocation(program, "uInput"), 0);
|
||||
glUniform2i(glGetUniformLocation(program, "uSize"), w, h);
|
||||
glBindBufferBase(GL_SHADER_STORAGE_BUFFER, 0, pbo);
|
||||
glDispatchCompute((w + 7) / 8, (h + 7) / 8, 1);
|
||||
GLint alignment = 0;
|
||||
glGetIntegerv(GL_SHADER_STORAGE_BUFFER_OFFSET_ALIGNMENT, &alignment);
|
||||
Check(alignment > 0, "SSBO offset alignment");
|
||||
const int rowBytes = w * 16;
|
||||
const int stripeRows = alignment / std::gcd(rowBytes, alignment);
|
||||
// Artificially small block limit forces aligned range changes and a partial
|
||||
// final stripe without needing a huge texture on the diagnostic device.
|
||||
for (int row = 0; row < h; row += stripeRows) {
|
||||
const int rows = std::min(stripeRows, h - row);
|
||||
glUniform1i(glGetUniformLocation(program, "uRowOffset"), row);
|
||||
glUniform1i(glGetUniformLocation(program, "uRows"), rows);
|
||||
glBindBufferRange(GL_SHADER_STORAGE_BUFFER, 0, pbo, row * rowBytes,
|
||||
rows * rowBytes);
|
||||
glDispatchCompute((w + 7) / 8, (rows + 7) / 8, 1);
|
||||
}
|
||||
glMemoryBarrier(GL_SHADER_STORAGE_BARRIER_BIT | GL_BUFFER_UPDATE_BARRIER_BIT);
|
||||
glBindBufferBase(GL_SHADER_STORAGE_BUFFER, 0, 0);
|
||||
glBindBuffer(GL_PIXEL_PACK_BUFFER, pbo);
|
||||
@@ -191,7 +205,7 @@ static void Gpu(const char *shaderPath, const char *boxPath) {
|
||||
glMapBufferRange(GL_PIXEL_PACK_BUFFER, 0, pixels.size() * 4,
|
||||
GL_MAP_READ_BIT | GL_MAP_WRITE_BIT));
|
||||
Check(mapped && std::equal(pixels.begin(), pixels.end(), mapped),
|
||||
"float SSBO preserves all samples including tail");
|
||||
"float SSBO ranges preserve all samples including stripe tail");
|
||||
for (int i = 0; i < n; i++)
|
||||
mapped[i * 4] += .125f;
|
||||
Check(glUnmapBuffer(GL_PIXEL_PACK_BUFFER), "SSBO unmap");
|
||||
@@ -206,8 +220,36 @@ static void Gpu(const char *shaderPath, const char *boxPath) {
|
||||
for (int i = 0; i < n; i++)
|
||||
Check(result[i * 4] == pixels[i * 4] + .125f,
|
||||
"RGBA16F upload/sample precision");
|
||||
std::ifstream uploadFile(uploadPath);
|
||||
std::string uploadSource((std::istreambuf_iterator<char>(uploadFile)), {});
|
||||
Check(!uploadSource.empty(), "production upload shader");
|
||||
const char *uploadText = uploadSource.c_str();
|
||||
GLuint uploadShader = glCreateShader(GL_COMPUTE_SHADER);
|
||||
glShaderSource(uploadShader, 1, &uploadText, nullptr);
|
||||
glCompileShader(uploadShader);
|
||||
glGetShaderiv(uploadShader, GL_COMPILE_STATUS, &ok);
|
||||
Check(ok, "upload compute compile");
|
||||
GLuint uploadProgram = glCreateProgram();
|
||||
glAttachShader(uploadProgram, uploadShader);
|
||||
glLinkProgram(uploadProgram);
|
||||
glGetProgramiv(uploadProgram, GL_LINK_STATUS, &ok);
|
||||
Check(ok, "upload compute link");
|
||||
glUseProgram(uploadProgram);
|
||||
glBindImageTexture(0, textures[2], 0, GL_FALSE, 0, GL_WRITE_ONLY, GL_RGBA16F);
|
||||
glUniform2i(glGetUniformLocation(uploadProgram, "uSize"), w, h);
|
||||
for (int row = 0; row < h; row += stripeRows) {
|
||||
const int rows = std::min(stripeRows, h - row);
|
||||
glUniform1i(glGetUniformLocation(uploadProgram, "uRowOffset"), row);
|
||||
glUniform1i(glGetUniformLocation(uploadProgram, "uRows"), rows);
|
||||
glBindBufferRange(GL_SHADER_STORAGE_BUFFER, 0, pbo, row * rowBytes, rows * rowBytes);
|
||||
glDispatchCompute((w + 7) / 8, (rows + 7) / 8, 1);
|
||||
}
|
||||
glMemoryBarrier(GL_TEXTURE_FETCH_BARRIER_BIT | GL_FRAMEBUFFER_BARRIER_BIT |
|
||||
GL_SHADER_IMAGE_ACCESS_BARRIER_BIT);
|
||||
glBindImageTexture(0, 0, 0, GL_FALSE, 0, GL_WRITE_ONLY, GL_RGBA16F);
|
||||
glBindBufferBase(GL_SHADER_STORAGE_BUFFER, 0, 0);
|
||||
// Exercise Filmic's new padded linear-color branch with the production
|
||||
// shader.
|
||||
// shader immediately after image upload, without an intervening CPU wait/readback.
|
||||
std::ifstream boxFile(boxPath);
|
||||
std::string boxSource((std::istreambuf_iterator<char>(boxFile)), {});
|
||||
Check(!boxSource.empty(), "production box shader");
|
||||
@@ -232,12 +274,16 @@ static void Gpu(const char *shaderPath, const char *boxPath) {
|
||||
glLinkProgram(boxProgram);
|
||||
glGetProgramiv(boxProgram, GL_LINK_STATUS, &ok);
|
||||
Check(ok, "box program");
|
||||
GLuint boxTexture;
|
||||
glGenTextures(1, &boxTexture);
|
||||
for (int scale : {2, 4}) {
|
||||
const int lw = 128 / scale, lh = 32 / scale;
|
||||
glBindTexture(GL_TEXTURE_2D, textures[1]);
|
||||
glBindTexture(GL_TEXTURE_2D, boxTexture);
|
||||
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA16F, lw, lh, 0, GL_RGBA, GL_FLOAT,
|
||||
nullptr);
|
||||
glBindTexture(GL_TEXTURE_2D, textures[0]);
|
||||
glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, boxTexture, 0);
|
||||
Check(glCheckFramebufferStatus(GL_FRAMEBUFFER) == GL_FRAMEBUFFER_COMPLETE, "box framebuffer");
|
||||
glBindTexture(GL_TEXTURE_2D, textures[2]);
|
||||
glUseProgram(boxProgram);
|
||||
glUniform1i(glGetUniformLocation(boxProgram, "uInput"), 0);
|
||||
glUniform1i(glGetUniformLocation(boxProgram, "uScale"), scale);
|
||||
@@ -251,7 +297,7 @@ static void Gpu(const char *shaderPath, const char *boxPath) {
|
||||
float expected = 0;
|
||||
for (int dy = 0; dy < scale; dy++)
|
||||
for (int dx = 0; dx < scale; dx++)
|
||||
expected += pixels[(std::min(y * scale + dy, h - 1) * w +
|
||||
expected += result[(std::min(y * scale + dy, h - 1) * w +
|
||||
std::min(x * scale + dx, w - 1)) *
|
||||
4 +
|
||||
c] *
|
||||
@@ -260,12 +306,19 @@ static void Gpu(const char *shaderPath, const char *boxPath) {
|
||||
"padded linear box samples");
|
||||
}
|
||||
}
|
||||
glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, textures[2], 0);
|
||||
std::vector<float> uploaded(n * 4);
|
||||
glReadPixels(0, 0, w, h, GL_RGBA, GL_FLOAT, uploaded.data());
|
||||
Check(uploaded == result, "SSBO image upload matches PBO float upload exactly");
|
||||
glDeleteTextures(1, &boxTexture);
|
||||
glDeleteProgram(uploadProgram);
|
||||
glDeleteShader(uploadShader);
|
||||
glDeleteProgram(boxProgram);
|
||||
glDeleteShader(vs);
|
||||
glDeleteShader(fs);
|
||||
printf("GPU padded linear color box passed\n");
|
||||
Check(glGetError() == GL_NO_ERROR, "GPU errors");
|
||||
glDeleteTextures(2, textures);
|
||||
glDeleteTextures(3, textures);
|
||||
glDeleteBuffers(1, &pbo);
|
||||
glDeleteFramebuffers(1, &framebuffer);
|
||||
glDeleteProgram(program);
|
||||
@@ -278,8 +331,8 @@ static void Gpu(const char *shaderPath, const char *boxPath) {
|
||||
}
|
||||
|
||||
int main(int argc, char **argv) {
|
||||
Check(argc == 4, "fixture output directory, float and box shaders");
|
||||
Gpu(argv[2], argv[3]);
|
||||
Check(argc == 5, "fixture output directory, float, box and upload shaders");
|
||||
Gpu(argv[2], argv[3], argv[4]);
|
||||
for (int scale : {2, 4}) {
|
||||
auto full = Jni(768, 640, scale);
|
||||
for (int origin : {0, 8, 16, 24, 56, 112}) {
|
||||
|
||||
@@ -0,0 +1,42 @@
|
||||
package com.hinnka.mycamera.raw
|
||||
|
||||
import org.junit.Assert.assertEquals
|
||||
import org.junit.Assert.assertTrue
|
||||
import org.junit.Test
|
||||
|
||||
class RawFloatTransferLayoutTest {
|
||||
@Test
|
||||
fun twelveMegapixelFloatInputUsesBoundedAlignedRanges() {
|
||||
checkCoverage(4000, 3000, 128L * 1024 * 1024, 256)
|
||||
checkCoverage(4033, 3025, 128L * 1024 * 1024, 256)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun lowResolutionInputDoesNotDependOnFullResolutionOutputCapacity() {
|
||||
assertEquals(752, RawFloatTransferLayout.stripeRows(1024, 752, 128L * 1024 * 1024, 256))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun unalignedRowsAndPartialLastStripeStayWithinTheBinding() {
|
||||
checkCoverage(37, 35, 37L * 16 * 16, 256)
|
||||
checkCoverage(17, 19, 17L * 16 * 8, 64)
|
||||
assertEquals(0, RawFloatTransferLayout.stripeRows(37, 35, 37L * 16 * 15, 256))
|
||||
// A single range starts at zero and does not need its end aligned.
|
||||
assertEquals(3, RawFloatTransferLayout.stripeRows(37, 3, 37L * 16 * 3, 256))
|
||||
}
|
||||
|
||||
private fun checkCoverage(width: Int, height: Int, limit: Long, alignment: Int) {
|
||||
val stripeRows = RawFloatTransferLayout.stripeRows(width, height, limit, alignment)
|
||||
assertTrue(stripeRows > 0)
|
||||
var covered = 0L
|
||||
for (row in 0 until height step stripeRows) {
|
||||
val offset = row.toLong() * width * 16
|
||||
val bytes = minOf(stripeRows, height - row).toLong() * width * 16
|
||||
assertEquals(covered, offset)
|
||||
assertEquals(0L, offset % alignment)
|
||||
assertTrue(bytes in 1..limit)
|
||||
covered += bytes
|
||||
}
|
||||
assertEquals(width.toLong() * height * 16, covered)
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user