perf: RAW processing pipeline optimizations
This commit is contained in:
1 parent
732432ea34
commit
2c7191082d
12 files changed
+459
-127
No files matched your search
@@ -8,6 +8,9 @@
|
||||
#include <jni.h>
|
||||
#include <limits>
|
||||
#include <memory>
|
||||
#include <new>
|
||||
#include <sys/mman.h>
|
||||
#include <unistd.h>
|
||||
#include <vector>
|
||||
|
||||
namespace {
|
||||
@@ -15,9 +18,43 @@ using Clock = std::chrono::steady_clock;
|
||||
double Milliseconds(Clock::time_point begin, Clock::time_point end) {
|
||||
return std::chrono::duration<double, std::milli>(end - begin).count();
|
||||
}
|
||||
// Anonymous mapping for the full-resolution planar Q14 YUV. Pages are zero-filled lazily on
|
||||
// first write, so there is no separate clearing pass; once BoxDownsample has consumed U/V their
|
||||
// pages are unmapped and the Y plane remains in place as the guide, without a copy.
|
||||
class PlanarYuvMapping {
|
||||
public:
|
||||
explicit PlanarYuvMapping(size_t plane_samples)
|
||||
: bytes_(plane_samples * 3 * sizeof(int16_t)) {
|
||||
void *base = mmap(nullptr, bytes_, PROT_READ | PROT_WRITE,
|
||||
MAP_PRIVATE | MAP_ANONYMOUS, -1, 0);
|
||||
if (base == MAP_FAILED)
|
||||
throw std::bad_alloc();
|
||||
base_ = static_cast<int16_t *>(base);
|
||||
}
|
||||
~PlanarYuvMapping() {
|
||||
if (base_)
|
||||
munmap(base_, bytes_);
|
||||
}
|
||||
PlanarYuvMapping(const PlanarYuvMapping &) = delete;
|
||||
PlanarYuvMapping &operator=(const PlanarYuvMapping &) = delete;
|
||||
int16_t *data() const { return base_; }
|
||||
void RetainFirstPlane(size_t plane_samples) {
|
||||
const size_t page = size_t(sysconf(_SC_PAGESIZE));
|
||||
const size_t keep =
|
||||
(plane_samples * sizeof(int16_t) + page - 1) / page * page;
|
||||
if (keep < bytes_ &&
|
||||
munmap(reinterpret_cast<uint8_t *>(base_) + keep, bytes_ - keep) == 0)
|
||||
bytes_ = keep;
|
||||
}
|
||||
|
||||
private:
|
||||
int16_t *base_ = nullptr;
|
||||
size_t bytes_;
|
||||
};
|
||||
struct GuidedInputs {
|
||||
int width, height, padded_width, padded_height, scale;
|
||||
std::vector<int16_t> guide, low_guide;
|
||||
std::unique_ptr<PlanarYuvMapping> guide;
|
||||
std::vector<int16_t> low_guide;
|
||||
};
|
||||
void OutOfMemory(JNIEnv *env) {
|
||||
auto type = env->FindClass("java/lang/OutOfMemoryError");
|
||||
@@ -62,18 +99,17 @@ Java_com_hinnka_mycamera_raw_MgcGuidedUpsample_nativePrepare(
|
||||
state->scale = scale;
|
||||
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->guide = std::make_unique<PlanarYuvMapping>(n);
|
||||
int16_t *yuv = state->guide->data();
|
||||
allocated = Clock::now();
|
||||
if (!GuidedFloatRgbaToLinearYuv(rgba, width, height, pw, ph, wb, yuv))
|
||||
return 0;
|
||||
converted = Clock::now();
|
||||
if (RunGuidedBoxDownsample(yuv, pw, ph, log2_scale, low.data()) != 0)
|
||||
return 0;
|
||||
boxed = Clock::now();
|
||||
// Release the two unused chroma planes before allocating low RGB.
|
||||
state->guide->RetainFirstPlane(n);
|
||||
state->low_guide.assign(low.begin(), low.begin() + ln);
|
||||
guides = Clock::now();
|
||||
// The low color branch starts before CCM/DCP/tone; never downsample an
|
||||
@@ -105,7 +141,7 @@ Java_com_hinnka_mycamera_raw_MgcGuidedUpsample_nativePrepare(
|
||||
extern "C" JNIEXPORT jint JNICALL
|
||||
Java_com_hinnka_mycamera_raw_MgcGuidedUpsample_nativeRender(
|
||||
JNIEnv *env, jobject, jlong handle, jobject buffer, jfloat attenuation,
|
||||
jfloatArray points) {
|
||||
jfloatArray points, jboolean u12_rgb_output) {
|
||||
using namespace photon::mgc_denoise;
|
||||
auto *state = reinterpret_cast<GuidedInputs *>(handle);
|
||||
if (!state || !buffer || !points || env->GetArrayLength(points) != 30 ||
|
||||
@@ -114,8 +150,12 @@ Java_com_hinnka_mycamera_raw_MgcGuidedUpsample_nativeRender(
|
||||
auto *rgba = static_cast<float *>(env->GetDirectBufferAddress(buffer));
|
||||
const size_t n = size_t(state->width) * state->height;
|
||||
const size_t ln = state->low_guide.size();
|
||||
const size_t output_samples =
|
||||
size_t(state->width) * ((state->height + 1) & ~1) * 3;
|
||||
if (!rgba ||
|
||||
env->GetDirectBufferCapacity(buffer) < jlong(std::max(n, ln) * 16))
|
||||
env->GetDirectBufferCapacity(buffer) < jlong(std::max(n, ln) * 16) ||
|
||||
env->GetDirectBufferCapacity(buffer) <
|
||||
jlong(output_samples * sizeof(uint16_t)))
|
||||
return -1;
|
||||
float curves[30];
|
||||
env->GetFloatArrayRegion(points, 0, 30, curves);
|
||||
@@ -132,26 +172,35 @@ Java_com_hinnka_mycamera_raw_MgcGuidedUpsample_nativeRender(
|
||||
}
|
||||
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()))
|
||||
// Every element below is written by its producer before it is read; skip value-init.
|
||||
std::unique_ptr<int16_t[]> yuv(new int16_t[ln * 3]);
|
||||
if (!SharpenFloatRgbaToYuv(rgba, ln, yuv.get()))
|
||||
return -1;
|
||||
const auto converted = Clock::now();
|
||||
// The low-resolution input has been fully consumed, so the U12 RGB result can be written
|
||||
// straight into the mapped transfer buffer and expanded on the GPU at upload.
|
||||
std::unique_ptr<uint16_t[]> float_staging;
|
||||
uint16_t *output = reinterpret_cast<uint16_t *>(rgba);
|
||||
if (!u12_rgb_output) {
|
||||
float_staging.reset(new uint16_t[output_samples]);
|
||||
output = float_staging.get();
|
||||
}
|
||||
const int result = RunGuidedUpsampleTo16Bit(
|
||||
state->guide.data(), state->padded_width, state->padded_height,
|
||||
state->low_guide.data(), yuv.data(), state->scale, state->width,
|
||||
state->height, curves, attenuation, output.data());
|
||||
state->guide->data(), state->padded_width, state->padded_height,
|
||||
state->low_guide.data(), yuv.get(), state->scale, state->width,
|
||||
state->height, curves, attenuation, output);
|
||||
if (result)
|
||||
return result;
|
||||
const auto reconstructed = Clock::now();
|
||||
SharpenRgbToFloatRgba(output.data(), n, rgba);
|
||||
if (!u12_rgb_output)
|
||||
SharpenRgbToFloatRgba(output, n, rgba);
|
||||
const auto finish = Clock::now();
|
||||
__android_log_print(ANDROID_LOG_INFO, "PLog_MgcGuidedUpsample",
|
||||
"render %dx%d scale=%d 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));
|
||||
"render %dx%d scale=%d output=%s yuvMs=%.1f guidedMs=%.1f rgbaMs=%.1f "
|
||||
"totalNativeMs=%.1f",
|
||||
state->width, state->height, state->scale, u12_rgb_output ? "u12" : "float",
|
||||
Milliseconds(start, converted), Milliseconds(converted, reconstructed),
|
||||
Milliseconds(reconstructed, finish), Milliseconds(start, finish));
|
||||
return 0;
|
||||
} catch (const std::bad_alloc &) {
|
||||
OutOfMemory(env);
|
||||
|
||||
@@ -43,6 +43,11 @@ constexpr float kMaximumInitialStepEv = 2.0f;
|
||||
constexpr float kRobustCorrectionToleranceEv = 0.025f;
|
||||
constexpr float kMinimumUsefulResponseSlope = 0.05f;
|
||||
constexpr int kMaximumSampleCount = 6;
|
||||
// HDRNet renormalizes local brightness, so output luma responds to input EV with a slope well
|
||||
// below 1 and the per-cell match rate stays low and noisy. Accept the best sample once its
|
||||
// robust correction is this small, and let the secant extrapolate further per step.
|
||||
constexpr float kHdrNetConvergedCorrectionEv = 0.05f;
|
||||
constexpr float kHdrNetExtrapolationWidths = 3.0f;
|
||||
constexpr float kScoreEqualityEpsilon = 0.000001f;
|
||||
constexpr float kSrgbTransferThreshold = 0.04045f;
|
||||
constexpr float kSrgbLinearScale = 12.92f;
|
||||
@@ -600,7 +605,10 @@ public:
|
||||
|
||||
bool HasConverged() const {
|
||||
if (!HasResult()) return false;
|
||||
return HasRequiredGridMatchRate(BestSample().match);
|
||||
const MatchResult& best = BestSample().match;
|
||||
if (HasRequiredGridMatchRate(best)) return true;
|
||||
return hdrnet_priority_configured_ && samples_.size() > 1 &&
|
||||
std::abs(best.recommended_exposure_correction_ev) <= kHdrNetConvergedCorrectionEv;
|
||||
}
|
||||
|
||||
const Sample& BestSample() const {
|
||||
@@ -901,10 +909,13 @@ private:
|
||||
lower.exposure_ev,
|
||||
upper.exposure_ev);
|
||||
} else {
|
||||
const float reach = hdrnet_priority_configured_
|
||||
? width * kHdrNetExtrapolationWidths
|
||||
: width;
|
||||
candidate_ev = std::clamp(
|
||||
candidate_ev,
|
||||
lower.exposure_ev - width,
|
||||
upper.exposure_ev + width);
|
||||
lower.exposure_ev - reach,
|
||||
upper.exposure_ev + reach);
|
||||
}
|
||||
const float acquisition =
|
||||
(brackets_optimum ? 4.0f : 3.0f) +
|
||||
|
||||
@@ -28,8 +28,53 @@ internal data class GlesMgcRawBaseFrameSelection(
|
||||
val prunedLatestIndex: Int?,
|
||||
val measurements: Map<Int, GlesMgcRawSharpnessMeasurement>,
|
||||
val fastMomentsRawStats: com.hinnka.mycamera.raw.RawSceneAERawStats? = null,
|
||||
/** Set instead of [fastMomentsRawStats] on a shared context; the caller must collect it. */
|
||||
val fastMomentsSubmission: GlesFastMomentsSubmission? = null,
|
||||
)
|
||||
|
||||
/**
|
||||
* Fast Moments statistics queued on the caller's EGL context. [collect] or [release] must run on
|
||||
* that context; both are idempotent and release the reference upload and statistics buffers.
|
||||
*/
|
||||
internal class GlesFastMomentsSubmission internal constructor(
|
||||
private val stats: GlesRawAEStats,
|
||||
private var rawTexture: Int,
|
||||
private val context: EGLContext,
|
||||
private val frameNumber: Long,
|
||||
private val sourceWidth: Int,
|
||||
private val sourceHeight: Int,
|
||||
private val uploadMs: Long,
|
||||
) {
|
||||
fun collect(): com.hinnka.mycamera.raw.RawSceneAERawStats? = try {
|
||||
val result = stats.collect()
|
||||
PLog.i(
|
||||
TAG,
|
||||
"Fast Moments GPU reference statistics deferred size=${result.stats.width}x" +
|
||||
"${result.stats.height} source=${sourceWidth}x$sourceHeight frame=$frameNumber " +
|
||||
"uploadMs=$uploadMs submitMs=${result.submitMs} gpuWaitMs=${result.gpuWaitMs} " +
|
||||
"mapMs=${result.mapMs}",
|
||||
)
|
||||
result.stats
|
||||
} catch (error: RuntimeException) {
|
||||
PLog.e(TAG, "Fast Moments deferred GPU statistics failed frame=$frameNumber", error)
|
||||
null
|
||||
} finally {
|
||||
release()
|
||||
}
|
||||
|
||||
fun release() {
|
||||
stats.release()
|
||||
if (rawTexture != 0 && EGL14.eglGetCurrentContext() == context) {
|
||||
GLES30.glDeleteTextures(1, intArrayOf(rawTexture), 0)
|
||||
}
|
||||
rawTexture = 0
|
||||
}
|
||||
|
||||
private companion object {
|
||||
const val TAG = "GlesMgcRawBaseFrameSelector"
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* GPU implementation of MGC 9.6.080 V24's RAW-content base-frame objective.
|
||||
*
|
||||
@@ -95,11 +140,14 @@ internal class GlesMgcRawBaseFrameSelector(
|
||||
) ?: return null
|
||||
}
|
||||
if (normalIndices.size > 1) logSelection(frames, normalIndices, selection)
|
||||
selection.copy(
|
||||
fastMomentsRawStats = buildFastMomentsRawStats(
|
||||
frames[selection.referenceIndex],
|
||||
),
|
||||
)
|
||||
val reference = frames[selection.referenceIndex]
|
||||
if (useCurrentGlContext) {
|
||||
// The caller keeps this context current through the merge, so the statistics are
|
||||
// collected after it instead of stalling the merge on their GPU wait and readback.
|
||||
selection.copy(fastMomentsSubmission = submitFastMomentsRawStats(reference))
|
||||
} else {
|
||||
selection.copy(fastMomentsRawStats = buildFastMomentsRawStats(reference))
|
||||
}
|
||||
} catch (error: RuntimeException) {
|
||||
PLog.e(TAG, "MGC GLES RAW base-frame selection failed", error)
|
||||
null
|
||||
@@ -327,6 +375,38 @@ internal class GlesMgcRawBaseFrameSelector(
|
||||
}
|
||||
}
|
||||
|
||||
private fun submitFastMomentsRawStats(frame: RawStackFrame): GlesFastMomentsSubmission {
|
||||
// The submission owns this upload until the deferred dispatch has been collected.
|
||||
val rawTexture = createRawTexture().also(textures::remove)
|
||||
val stats = GlesRawAEStats(
|
||||
width = width,
|
||||
height = height,
|
||||
cfaPattern = cfaPattern,
|
||||
blackLevel = canonicalBlackLevelForFrame(frame),
|
||||
whiteLevel = whiteLevel,
|
||||
maxShaderStorageBlockBytes = maxShaderStorageBlockBytes,
|
||||
)
|
||||
return try {
|
||||
val uploadStartNs = System.nanoTime()
|
||||
uploadRaw(frame, rawTexture, "Fast Moments reference ${frame.frameNumber}")
|
||||
val uploadMs = elapsedMs(uploadStartNs)
|
||||
stats.submit(rawTexture)
|
||||
GlesFastMomentsSubmission(
|
||||
stats = stats,
|
||||
rawTexture = rawTexture,
|
||||
context = EGL14.eglGetCurrentContext(),
|
||||
frameNumber = frame.frameNumber,
|
||||
sourceWidth = width,
|
||||
sourceHeight = height,
|
||||
uploadMs = uploadMs,
|
||||
)
|
||||
} catch (error: RuntimeException) {
|
||||
stats.release()
|
||||
GLES30.glDeleteTextures(1, intArrayOf(rawTexture), 0)
|
||||
throw error
|
||||
}
|
||||
}
|
||||
|
||||
private fun releaseTextures(textureIds: IntArray) {
|
||||
if (textureIds.isEmpty()) return
|
||||
GLES30.glDeleteTextures(textureIds.size, textureIds, 0)
|
||||
|
||||
@@ -84,6 +84,30 @@ internal class GlesMgcRawFusion(
|
||||
frames.forEach { it.image.close() }
|
||||
return null
|
||||
}
|
||||
val fastMomentsSubmission = baseFrameSelection.fastMomentsSubmission
|
||||
return try {
|
||||
processSelectedFrames(
|
||||
frames = frames,
|
||||
normalIndicesBeforeSelection = normalIndicesBeforeSelection,
|
||||
baseFrameSelection = baseFrameSelection,
|
||||
canReuseSpatialReferenceUpload = canReuseSpatialReferenceUpload,
|
||||
)?.let { result ->
|
||||
// Collected after the merge so the statistics never stall it.
|
||||
fastMomentsSubmission?.let { submission ->
|
||||
result.copy(fastMomentsRawStats = submission.collect())
|
||||
} ?: result
|
||||
}
|
||||
} finally {
|
||||
fastMomentsSubmission?.release()
|
||||
}
|
||||
}
|
||||
|
||||
private fun processSelectedFrames(
|
||||
frames: List<RawStackFrame>,
|
||||
normalIndicesBeforeSelection: List<Int>,
|
||||
baseFrameSelection: GlesMgcRawBaseFrameSelection,
|
||||
canReuseSpatialReferenceUpload: Boolean,
|
||||
): RawStackResult? {
|
||||
val selectedBaseIndex = baseFrameSelection.referenceIndex
|
||||
val referenceFirstFrames = if (selectedBaseIndex == 0) {
|
||||
frames
|
||||
|
||||
@@ -1,5 +1,7 @@
|
||||
package com.hinnka.mycamera.processor
|
||||
|
||||
import android.opengl.EGL14
|
||||
import android.opengl.EGLContext
|
||||
import android.opengl.GLES30
|
||||
import android.opengl.GLES31
|
||||
import com.hinnka.mycamera.raw.RawSceneExposureMath
|
||||
@@ -37,10 +39,26 @@ internal class GlesRawAEStats(
|
||||
private val buffers = mutableListOf<Int>()
|
||||
private val uniformLocations = HashMap<Pair<Int, String>, Int>()
|
||||
|
||||
fun build(rawTexture: Int): GlesRawAEStatsResult {
|
||||
private var submission: Submission? = null
|
||||
|
||||
/** Submits and immediately collects the statistics; owns every GL object it creates. */
|
||||
fun build(rawTexture: Int): GlesRawAEStatsResult =
|
||||
try {
|
||||
submit(rawTexture)
|
||||
collect()
|
||||
} finally {
|
||||
release()
|
||||
}
|
||||
|
||||
/**
|
||||
* Queues both statistics passes behind a fence without waiting for the GPU. [rawTexture] must
|
||||
* stay alive until [collect] or [release]; every other GL object stays owned by this instance.
|
||||
*/
|
||||
fun submit(rawTexture: Int) {
|
||||
require(rawTexture != 0)
|
||||
require(width > 0 && height > 0 && cfaPattern in 0..3 && whiteLevel > 0)
|
||||
require(blackLevel.all(Float::isFinite))
|
||||
check(submission == null) { "GPU statistics were already submitted" }
|
||||
val buildStartNs = System.nanoTime()
|
||||
val downsample = RawSceneExposureMath.FAST_MOMENTS_RAW_STATS_DOWNSAMPLE
|
||||
check(downsample > 0 && downsample % 2 == 0) {
|
||||
@@ -54,9 +72,10 @@ internal class GlesRawAEStats(
|
||||
STATS_CELL_BYTES,
|
||||
"Fast Moments block surface",
|
||||
)
|
||||
// Read back on the CPU, so request cached host memory instead of a write-combined mapping.
|
||||
val fastBuffer = createBuffer(
|
||||
fastBufferBytes,
|
||||
GLES30.GL_DYNAMIC_DRAW,
|
||||
GLES30.GL_STREAM_READ,
|
||||
"Fast Moments block surface",
|
||||
)
|
||||
|
||||
@@ -73,7 +92,7 @@ internal class GlesRawAEStats(
|
||||
} else {
|
||||
0
|
||||
}
|
||||
return try {
|
||||
try {
|
||||
val fastProgram = linkComputeProgram(
|
||||
GlesRawAEStatsShaders.FAST_MOMENTS,
|
||||
"Fast Moments selected-base block reduction",
|
||||
@@ -147,53 +166,21 @@ internal class GlesRawAEStats(
|
||||
GLES31.GL_SHADER_STORAGE_BARRIER_BIT or
|
||||
GLES31.GL_BUFFER_UPDATE_BARRIER_BIT,
|
||||
)
|
||||
GLES30.glBindTexture(GLES30.GL_TEXTURE_2D, 0)
|
||||
GLES31.glBindBufferBase(GLES31.GL_SHADER_STORAGE_BUFFER, 0, 0)
|
||||
GLES31.glBindBufferBase(GLES31.GL_SHADER_STORAGE_BUFFER, 1, 0)
|
||||
GLES31.glUseProgram(0)
|
||||
checkGlError("submit selected-base GPU statistics")
|
||||
val submitMs = elapsedMs(buildStartNs)
|
||||
val gpuWaitMs = GlesGpuCompletion.awaitSubmittedWork(
|
||||
"selected-base GPU statistics",
|
||||
::checkGlError,
|
||||
)
|
||||
|
||||
val mapStartNs = System.nanoTime()
|
||||
val fastReadback = mapBuffer(
|
||||
fastBuffer,
|
||||
fastBufferBytes,
|
||||
"Fast Moments block surface",
|
||||
) { mapped -> readFastStats(mapped, statsPixelCount) }
|
||||
val baseSensorRgb = if (meteringBuffer != 0) {
|
||||
mapBuffer(
|
||||
meteringBuffer,
|
||||
meteringPixelCount * VEC4_BYTES,
|
||||
"base metering",
|
||||
) { mapped -> readBaseFrameSensorRgb(mapped, meteringPixelCount) }
|
||||
} else {
|
||||
null
|
||||
}
|
||||
val mapMs = elapsedMs(mapStartNs)
|
||||
val stats = RawSceneAERawStats(
|
||||
width = statsWidth,
|
||||
height = statsHeight,
|
||||
sourceWidth = width,
|
||||
sourceHeight = height,
|
||||
channelMax = fastReadback,
|
||||
sensorNormalized = true,
|
||||
sourceBounds = floatArrayOf(0f, 0f, 1f, 1f),
|
||||
sourceRotationDegrees = 0,
|
||||
baseFrameMetering = baseSensorRgb?.let { sensorRgb ->
|
||||
RawSceneFastMomentsMeteringFrame(
|
||||
sensorRgb = sensorRgb,
|
||||
)
|
||||
},
|
||||
)
|
||||
GlesRawAEStatsResult(
|
||||
stats = stats,
|
||||
submitMs = submitMs,
|
||||
gpuWaitMs = gpuWaitMs,
|
||||
mapMs = mapMs,
|
||||
val fence = GLES30.glFenceSync(GLES30.GL_SYNC_GPU_COMMANDS_COMPLETE, 0)
|
||||
check(fence != 0L) { "Unable to create selected-base GPU statistics fence" }
|
||||
GLES30.glFlush()
|
||||
submission = Submission(
|
||||
context = EGL14.eglGetCurrentContext(),
|
||||
fence = fence,
|
||||
fastBuffer = fastBuffer,
|
||||
fastBufferBytes = fastBufferBytes,
|
||||
meteringBuffer = meteringBuffer,
|
||||
meteringPixelCount = meteringPixelCount,
|
||||
statsWidth = statsWidth,
|
||||
statsHeight = statsHeight,
|
||||
statsPixelCount = statsPixelCount,
|
||||
submitMs = elapsedMs(buildStartNs),
|
||||
)
|
||||
} finally {
|
||||
GLES30.glActiveTexture(GLES30.GL_TEXTURE0)
|
||||
@@ -202,44 +189,101 @@ internal class GlesRawAEStats(
|
||||
GLES31.glBindBufferBase(GLES31.GL_SHADER_STORAGE_BUFFER, 1, 0)
|
||||
GLES31.glBindBuffer(GLES31.GL_SHADER_STORAGE_BUFFER, 0)
|
||||
GLES31.glUseProgram(0)
|
||||
}
|
||||
}
|
||||
|
||||
/** Waits for the submitted fence and reads both surfaces; requires the submitting context. */
|
||||
fun collect(): GlesRawAEStatsResult {
|
||||
val pending = checkNotNull(submission) { "GPU statistics were not submitted" }
|
||||
check(EGL14.eglGetCurrentContext() == pending.context) {
|
||||
"GPU statistics must be collected on the submitting EGL context"
|
||||
}
|
||||
val gpuWaitMs = GlesGpuCompletion.awaitSync(pending.fence, "selected-base GPU statistics")
|
||||
checkGlError("GPU completion fence selected-base GPU statistics")
|
||||
|
||||
val mapStartNs = System.nanoTime()
|
||||
val fastReadback = mapBuffer(
|
||||
pending.fastBuffer,
|
||||
pending.fastBufferBytes,
|
||||
"Fast Moments block surface",
|
||||
) { mapped -> readFastStats(mapped, pending.statsPixelCount) }
|
||||
val baseSensorRgb = if (pending.meteringBuffer != 0) {
|
||||
mapBuffer(
|
||||
pending.meteringBuffer,
|
||||
pending.meteringPixelCount * VEC4_BYTES,
|
||||
"base metering",
|
||||
) { mapped -> readBaseFrameSensorRgb(mapped, pending.meteringPixelCount) }
|
||||
} else {
|
||||
null
|
||||
}
|
||||
val mapMs = elapsedMs(mapStartNs)
|
||||
val stats = RawSceneAERawStats(
|
||||
width = pending.statsWidth,
|
||||
height = pending.statsHeight,
|
||||
sourceWidth = width,
|
||||
sourceHeight = height,
|
||||
channelMax = fastReadback,
|
||||
sensorNormalized = true,
|
||||
sourceBounds = floatArrayOf(0f, 0f, 1f, 1f),
|
||||
sourceRotationDegrees = 0,
|
||||
baseFrameMetering = baseSensorRgb?.let { sensorRgb ->
|
||||
RawSceneFastMomentsMeteringFrame(
|
||||
sensorRgb = sensorRgb,
|
||||
)
|
||||
},
|
||||
)
|
||||
return GlesRawAEStatsResult(
|
||||
stats = stats,
|
||||
submitMs = pending.submitMs,
|
||||
gpuWaitMs = gpuWaitMs,
|
||||
mapMs = mapMs,
|
||||
)
|
||||
}
|
||||
|
||||
/**
|
||||
* Deletes the fence, programs and buffers. Idempotent. Off the submitting context the GL names
|
||||
* cannot be addressed, so they are left to that context's own teardown.
|
||||
*/
|
||||
fun release() {
|
||||
val pending = submission
|
||||
submission = null
|
||||
val current = EGL14.eglGetCurrentContext()
|
||||
val canDelete = current != EGL14.EGL_NO_CONTEXT &&
|
||||
(pending == null || current == pending.context)
|
||||
if (canDelete) {
|
||||
pending?.let { GLES30.glDeleteSync(it.fence) }
|
||||
programs.forEach { GLES31.glDeleteProgram(it) }
|
||||
if (buffers.isNotEmpty()) {
|
||||
GLES31.glDeleteBuffers(buffers.size, buffers.toIntArray(), 0)
|
||||
}
|
||||
programs.clear()
|
||||
buffers.clear()
|
||||
uniformLocations.clear()
|
||||
}
|
||||
programs.clear()
|
||||
buffers.clear()
|
||||
uniformLocations.clear()
|
||||
}
|
||||
|
||||
private fun readFastStats(mapped: ByteBuffer, pixelCount: Int): FloatArray {
|
||||
// One bulk copy out of the mapping; per-element reads of GPU-visible memory are slow.
|
||||
val cells = FloatArray(pixelCount * STATS_CELL_FLOATS)
|
||||
mapped.asFloatBuffer().get(cells)
|
||||
val channelMax = FloatArray(pixelCount * 4)
|
||||
for (pixel in 0 until pixelCount) {
|
||||
val inputOffset = pixel * STATS_CELL_BYTES
|
||||
val outputOffset = pixel * 4
|
||||
for (channel in 0..3) {
|
||||
channelMax[outputOffset + channel] = mapped.getFloat(
|
||||
inputOffset + channel * Float.SIZE_BYTES,
|
||||
)
|
||||
}
|
||||
System.arraycopy(cells, pixel * STATS_CELL_FLOATS, channelMax, pixel * 4, 4)
|
||||
}
|
||||
check(channelMax.all { it.isFinite() && it >= 0f })
|
||||
return channelMax
|
||||
}
|
||||
|
||||
private fun readBaseFrameSensorRgb(mapped: ByteBuffer, pixelCount: Int): FloatArray =
|
||||
FloatArray(pixelCount * 3).also { output ->
|
||||
private fun readBaseFrameSensorRgb(mapped: ByteBuffer, pixelCount: Int): FloatArray {
|
||||
val texels = FloatArray(pixelCount * 4)
|
||||
mapped.asFloatBuffer().get(texels)
|
||||
return FloatArray(pixelCount * 3).also { output ->
|
||||
for (pixel in 0 until pixelCount) {
|
||||
val inputOffset = pixel * VEC4_BYTES
|
||||
val outputOffset = pixel * 3
|
||||
for (channel in 0..2) {
|
||||
output[outputOffset + channel] = mapped.getFloat(
|
||||
inputOffset + channel * Float.SIZE_BYTES,
|
||||
)
|
||||
}
|
||||
System.arraycopy(texels, pixel * 4, output, pixel * 3, 3)
|
||||
}
|
||||
check(output.all { it.isFinite() && it >= 0f })
|
||||
}
|
||||
}
|
||||
|
||||
private inline fun <T> mapBuffer(
|
||||
buffer: Int,
|
||||
@@ -337,8 +381,22 @@ internal class GlesRawAEStats(
|
||||
private fun elapsedMs(startNs: Long): Long =
|
||||
(System.nanoTime() - startNs) / 1_000_000L
|
||||
|
||||
private class Submission(
|
||||
val context: EGLContext,
|
||||
val fence: Long,
|
||||
val fastBuffer: Int,
|
||||
val fastBufferBytes: Int,
|
||||
val meteringBuffer: Int,
|
||||
val meteringPixelCount: Int,
|
||||
val statsWidth: Int,
|
||||
val statsHeight: Int,
|
||||
val statsPixelCount: Int,
|
||||
val submitMs: Long,
|
||||
)
|
||||
|
||||
private companion object {
|
||||
const val VEC4_BYTES = 4 * Float.SIZE_BYTES
|
||||
const val STATS_CELL_BYTES = 2 * VEC4_BYTES
|
||||
const val STATS_CELL_FLOATS = STATS_CELL_BYTES / Float.SIZE_BYTES
|
||||
}
|
||||
}
|
||||
@@ -1633,9 +1633,10 @@ internal class DngPhotonProfileGainTableAlgorithm {
|
||||
// A candidate owns all data derived from its input exposure. In particular,
|
||||
// scaling an already-clipped tensor or reusing the previous inference/Dehaze
|
||||
// would evaluate a different response from the one baked into the selected PGTM.
|
||||
var cachedCandidate: HdrNetExposureCandidate? = null
|
||||
// Every candidate is kept: the solver's best sample is not necessarily its last one.
|
||||
val cachedCandidates = HashMap<Float, HdrNetExposureCandidate>()
|
||||
fun candidate(inputExposureEv: Float): HdrNetExposureCandidate? {
|
||||
cachedCandidate?.takeIf { it.inputExposureEv == inputExposureEv }?.let { return it }
|
||||
cachedCandidates[inputExposureEv]?.let { return it }
|
||||
if (!inputExposureEv.isFinite() || inputExposureEv !in
|
||||
MeteringSystem.RAW_EXPOSURE_MIN_EV..MeteringSystem.RAW_EXPOSURE_MAX_EV
|
||||
) return null
|
||||
@@ -1723,7 +1724,7 @@ internal class DngPhotonProfileGainTableAlgorithm {
|
||||
) ?: return null
|
||||
return HdrNetExposureCandidate(
|
||||
inputExposureEv, plan, modelInput, coefficients, evaluation,
|
||||
).also { cachedCandidate = it }
|
||||
).also { cachedCandidates[inputExposureEv] = it }
|
||||
}
|
||||
val restoredInputExposureEv = input.hdrNetInputExposureEv
|
||||
?.takeIf { it.isFinite() && it in
|
||||
|
||||
@@ -72,12 +72,17 @@ internal class MgcGuidedUpsample(private val transfer: RawFloatTextureTransfer)
|
||||
fun render(source: Int, target: Int, width: Int, height: Int, attenuation: Float, curves: FloatArray) {
|
||||
check(isPrepared && width == fullWidth && height == fullHeight)
|
||||
try {
|
||||
val u12RgbOutput = transfer.supportsU12RgbUpload(width, height)
|
||||
transfer.read(source, lowWidth, lowHeight,
|
||||
maxOf(width.toLong() * height, lowWidth.toLong() * lowHeight), label = "guidedRender") { rgba ->
|
||||
val result = nativeRender(handle, rgba, attenuation, curves)
|
||||
val result = nativeRender(handle, rgba, attenuation, curves, u12RgbOutput)
|
||||
check(result == 0) { "MGC GuidedUpsample failed: $result" }
|
||||
}
|
||||
transfer.upload(target, width, height)
|
||||
if (u12RgbOutput) {
|
||||
transfer.uploadU12Rgb(target, width, height)
|
||||
} else {
|
||||
transfer.upload(target, width, height)
|
||||
}
|
||||
} finally { releaseInputs() }
|
||||
}
|
||||
|
||||
@@ -116,7 +121,8 @@ internal class MgcGuidedUpsample(private val transfer: RawFloatTextureTransfer)
|
||||
|
||||
private external fun nativePrepare(rgba: ByteBuffer, width: Int, height: Int,
|
||||
log2Downsample: Int, gains: FloatArray): Long
|
||||
private external fun nativeRender(handle: Long, rgba: ByteBuffer, attenuation: Float, curves: FloatArray): Int
|
||||
private external fun nativeRender(handle: Long, rgba: ByteBuffer, attenuation: Float, curves: FloatArray,
|
||||
u12RgbOutput: Boolean): Int
|
||||
private external fun nativeRelease(handle: Long)
|
||||
|
||||
companion object {
|
||||
|
||||
@@ -3,6 +3,8 @@ package com.hinnka.mycamera.raw
|
||||
import android.hardware.camera2.CameraCharacteristics
|
||||
import android.hardware.camera2.params.ColorSpaceTransform
|
||||
import com.hinnka.mycamera.utils.PLog
|
||||
import java.util.Collections
|
||||
import java.util.WeakHashMap
|
||||
import kotlin.math.abs
|
||||
import kotlin.math.roundToInt
|
||||
|
||||
@@ -54,7 +56,14 @@ internal object RawColorCalibrationPolicy {
|
||||
return Selection(useForward = false, keepSlot2 = isUsableColorMatrix(colorMatrix2, illuminant2))
|
||||
}
|
||||
|
||||
fun fromCharacteristics(characteristics: CameraCharacteristics): CameraCalibration {
|
||||
// CameraCharacteristics is immutable; one capture resolves the same instance many times.
|
||||
private val characteristicsCache =
|
||||
Collections.synchronizedMap(WeakHashMap<CameraCharacteristics, CameraCalibration>())
|
||||
|
||||
fun fromCharacteristics(characteristics: CameraCharacteristics): CameraCalibration =
|
||||
characteristicsCache.getOrPut(characteristics) { resolveCharacteristics(characteristics) }
|
||||
|
||||
private fun resolveCharacteristics(characteristics: CameraCharacteristics): CameraCalibration {
|
||||
val illuminant1 = characteristics.get(CameraCharacteristics.SENSOR_REFERENCE_ILLUMINANT1) ?: 0
|
||||
val illuminant2 = characteristics.get(CameraCharacteristics.SENSOR_REFERENCE_ILLUMINANT2)?.toInt() ?: 0
|
||||
val cm1 = characteristics.get(CameraCharacteristics.SENSOR_COLOR_TRANSFORM1)
|
||||
|
||||
@@ -35,6 +35,12 @@ data class RawMergeVarianceMap(
|
||||
result = 31 * result + height
|
||||
return result
|
||||
}
|
||||
// Summary only: the full grid is thousands of floats and floods logcat.
|
||||
override fun toString(): String {
|
||||
if (values.isEmpty()) return "RawMergeVarianceMap(${width}x$height, empty)"
|
||||
return "RawMergeVarianceMap(${width}x$height, min=${values.min()}, max=${values.max()}, " +
|
||||
"mean=${values.average().toFloat()})"
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -96,6 +102,11 @@ data class RawDenoiseHistory(
|
||||
return result
|
||||
}
|
||||
|
||||
override fun toString(): String =
|
||||
"RawDenoiseHistory(pipeline=$pipeline, mergeRead=$mergeRead, mergeShot=$mergeShot, " +
|
||||
"residual=${residual?.joinToString(";", "[", "]") { it.joinToString(",") }}, " +
|
||||
"mergeMap=$mergeMap, signal=$signal, strength=${strength?.size?.let { "$it values" }})"
|
||||
|
||||
companion object {
|
||||
/** §5.1 luma bins × (Y, Cb, Cr) per level of [strength]. */
|
||||
const val STRENGTH_BINS = 8
|
||||
|
||||
@@ -25,6 +25,7 @@ internal class RawFloatTextureTransfer(private val layout: Layout = Layout.FLOAT
|
||||
private var framebuffer = 0
|
||||
private var program = 0
|
||||
private var uploadProgram = 0
|
||||
private var uploadU12Program = 0
|
||||
private var initialized = false
|
||||
private var maxSsboBytes = 0L
|
||||
private var ssboOffsetAlignment = 1
|
||||
@@ -210,17 +211,61 @@ internal class RawFloatTextureTransfer(private val layout: Layout = Layout.FLOAT
|
||||
"stripeRows=$stripeRows uploadSubmitMs=${elapsedMs(start)}")
|
||||
}
|
||||
|
||||
private fun dispatchStripes(computeProgram: Int, width: Int, height: Int, stripeRows: Int) {
|
||||
/** Whether [uploadU12Rgb] can expand the mapped buffer's interleaved U12 RGB on the GPU. */
|
||||
fun supportsU12RgbUpload(width: Int, height: Int): Boolean {
|
||||
initialize()
|
||||
return uploadU12Program != 0 &&
|
||||
RawFloatTransferLayout.stripeRows(width, height, maxSsboBytes, ssboOffsetAlignment,
|
||||
U12_RGB_BYTES_PER_PIXEL) > 0
|
||||
}
|
||||
|
||||
/**
|
||||
* Uploads interleaved uint16 RGB (U12 range, as written by the MGC 16-bit AOTs) from the
|
||||
* transfer buffer into immutable RGBA16F storage, expanding to [0, 1] in the shader. This
|
||||
* moves 6 instead of 16 bytes per pixel and skips the CPU float conversion.
|
||||
*/
|
||||
fun uploadU12Rgb(texture: Int, width: Int, height: Int) {
|
||||
require(width > 0 && height > 0 && width.toLong() * height * U12_RGB_BYTES_PER_PIXEL <= capacity)
|
||||
val stripeRows = RawFloatTransferLayout.stripeRows(width, height, maxSsboBytes, ssboOffsetAlignment,
|
||||
U12_RGB_BYTES_PER_PIXEL)
|
||||
check(uploadU12Program != 0 && stripeRows > 0) { "U12 RGB upload requires compute image store" }
|
||||
val start = System.nanoTime()
|
||||
uploadSourcesBuffer = true
|
||||
try {
|
||||
GLES31.glUseProgram(uploadU12Program)
|
||||
GLES31.glBindImageTexture(0, texture, 0, false, 0, GLES31.GL_WRITE_ONLY, GLES30.GL_RGBA16F)
|
||||
dispatchStripes(uploadU12Program, width, height, stripeRows, U12_RGB_BYTES_PER_PIXEL)
|
||||
GLES31.glMemoryBarrier(GLES31.GL_TEXTURE_FETCH_BARRIER_BIT or
|
||||
GLES31.GL_FRAMEBUFFER_BARRIER_BIT or GLES31.GL_SHADER_IMAGE_ACCESS_BARRIER_BIT or
|
||||
GLES31.GL_SHADER_STORAGE_BARRIER_BIT)
|
||||
checkGl("upload U12 RGB 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)
|
||||
}
|
||||
PLog.i(TAG, "upload layout=U12_RGB size=${width}x$height transfer=SSBO_IMAGE " +
|
||||
"stripeRows=$stripeRows uploadSubmitMs=${elapsedMs(start)}")
|
||||
}
|
||||
|
||||
private fun dispatchStripes(
|
||||
computeProgram: Int,
|
||||
width: Int,
|
||||
height: Int,
|
||||
stripeRows: Int,
|
||||
bytesPerPixel: Int = layout.bytesPerPixel,
|
||||
) {
|
||||
GLES31.glUniform2i(GLES31.glGetUniformLocation(computeProgram, "uSize"), width, height)
|
||||
val rowOffsetLocation = GLES31.glGetUniformLocation(computeProgram, "uRowOffset")
|
||||
val rowsLocation = GLES31.glGetUniformLocation(computeProgram, "uRows")
|
||||
val rowBytes = width * layout.bytesPerPixel
|
||||
val rowBytes = width * bytesPerPixel
|
||||
for (row in 0 until height step stripeRows) {
|
||||
val rows = minOf(stripeRows, height - row)
|
||||
GLES31.glUniform1i(rowOffsetLocation, row)
|
||||
GLES31.glUniform1i(rowsLocation, rows)
|
||||
// Word-addressed layouts need whole 32-bit words; the extra bytes stay in the buffer.
|
||||
val rangeBytes = minOf((rows * rowBytes + 3) and 3.inv(), capacity - row * rowBytes)
|
||||
GLES31.glBindBufferRange(GLES31.GL_SHADER_STORAGE_BUFFER, 0, buffer,
|
||||
row * rowBytes, rows * rowBytes)
|
||||
row * rowBytes, rangeBytes)
|
||||
GLES31.glDispatchCompute((width + 7) / 8, (rows + 7) / 8, 1)
|
||||
}
|
||||
}
|
||||
@@ -252,7 +297,9 @@ internal class RawFloatTextureTransfer(private val layout: Layout = Layout.FLOAT
|
||||
releaseBuffers()
|
||||
if (program != 0) GLES30.glDeleteProgram(program)
|
||||
if (uploadProgram != 0) GLES30.glDeleteProgram(uploadProgram)
|
||||
program = 0; uploadProgram = 0; initialized = false; maxSsboBytes = 0L; ssboOffsetAlignment = 1
|
||||
if (uploadU12Program != 0) GLES30.glDeleteProgram(uploadU12Program)
|
||||
program = 0; uploadProgram = 0; uploadU12Program = 0
|
||||
initialized = false; maxSsboBytes = 0L; ssboOffsetAlignment = 1
|
||||
}
|
||||
|
||||
private fun initialize() {
|
||||
@@ -278,6 +325,7 @@ internal class RawFloatTextureTransfer(private val layout: Layout = Layout.FLOAT
|
||||
if (imageUnits[0] > 0 && computeImages[0] > 0) {
|
||||
uploadProgram = RawGlesProgram.compileCompute(
|
||||
if (layout == Layout.HALF) UNPACK_HALF else UNPACK, "Mgc${layout}Upload")
|
||||
uploadU12Program = RawGlesProgram.compileCompute(UNPACK_U12_RGB, "MgcU12RgbUpload")
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -286,6 +334,7 @@ internal class RawFloatTextureTransfer(private val layout: Layout = Layout.FLOAT
|
||||
|
||||
companion object {
|
||||
private const val TAG = "RawFloatTextureTransfer"
|
||||
private const val U12_RGB_BYTES_PER_PIXEL = 6
|
||||
init { System.loadLibrary("my-native-lib") }
|
||||
private fun elapsedMs(start: Long) = (System.nanoTime() - start) / 1_000_000.0
|
||||
private fun checkGl(label: String) {
|
||||
@@ -327,6 +376,31 @@ internal class RawFloatTextureTransfer(private val layout: Layout = Layout.FLOAT
|
||||
}
|
||||
""".trimIndent()
|
||||
|
||||
// Interleaved little-endian uint16 RGB, three samples per pixel; matches the CPU
|
||||
// SharpenRgbToFloatRgba boundary (clamp to 4095, divide by 4095, alpha 1).
|
||||
internal val UNPACK_U12_RGB = """
|
||||
#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 { uint words[]; };
|
||||
layout(rgba16f, binding = 0) writeonly uniform highp image2D uOutput;
|
||||
uniform ivec2 uSize;
|
||||
uniform int uRowOffset;
|
||||
uniform int uRows;
|
||||
uint sample16(uint index) {
|
||||
uint word = words[index >> 1u];
|
||||
return (index & 1u) == 0u ? (word & 0xffffu) : (word >> 16u);
|
||||
}
|
||||
void main() {
|
||||
ivec2 p = ivec2(gl_GlobalInvocationID.xy);
|
||||
if (p.x >= uSize.x || p.y >= uRows) return;
|
||||
uint base = uint(p.y * uSize.x + p.x) * 3u;
|
||||
uvec3 rgb = min(uvec3(sample16(base), sample16(base + 1u), sample16(base + 2u)), uvec3(4095u));
|
||||
imageStore(uOutput, p + ivec2(0, uRowOffset), vec4(vec3(rgb) / 4095.0, 1.0));
|
||||
}
|
||||
""".trimIndent()
|
||||
|
||||
// Two little-endian words per pixel retain the RGBA16F ABI without expanding to Float32.
|
||||
internal val PACK_HALF = """
|
||||
#version 310 es
|
||||
|
||||
@@ -35,6 +35,9 @@ internal object PhotonDenoiseShaders {
|
||||
|
||||
layout(local_size_x = $LOCAL, local_size_y = $LOCAL) in;
|
||||
|
||||
ivec2 groupId() { return ivec2(gl_WorkGroupID.xy); }
|
||||
ivec2 globalId() { return groupId() * $LOCAL + ivec2(gl_LocalInvocationID.xy); }
|
||||
|
||||
const float LUMA_TAPS[7] = float[7](
|
||||
-1.0 / 32.0, 0.0, 9.0 / 32.0, 16.0 / 32.0, 9.0 / 32.0, 0.0, -1.0 / 32.0);
|
||||
const float CHROMA_TAPS[5] = float[5](
|
||||
@@ -198,7 +201,7 @@ internal object PhotonDenoiseShaders {
|
||||
}
|
||||
|
||||
void main() {
|
||||
ivec2 q = ivec2(gl_GlobalInvocationID.xy);
|
||||
ivec2 q = globalId();
|
||||
if (any(greaterThanEqual(q, uCoarseSize))) return;
|
||||
float y = 0.0;
|
||||
vec2 c = vec2(0.0);
|
||||
@@ -323,7 +326,7 @@ internal object PhotonDenoiseShaders {
|
||||
memoryBarrierShared();
|
||||
barrier();
|
||||
ivec2 sampleSize = (uSize + uStride - 1) / uStride;
|
||||
ivec2 origin = ivec2(gl_WorkGroupID.xy) * ($LOCAL * BLOCK);
|
||||
ivec2 origin = groupId() * ($LOCAL * BLOCK);
|
||||
ivec2 lane = ivec2(gl_LocalInvocationID.xy);
|
||||
float gate = gateScale();
|
||||
for (int by = 0; by < BLOCK; ++by) {
|
||||
@@ -521,7 +524,7 @@ internal object PhotonDenoiseShaders {
|
||||
shared vec4 sNoise[BAND_SIDE * BAND_SIDE];
|
||||
shared uvec2 sPilot[PILOT_SIDE * PILOT_SIDE];
|
||||
|
||||
ivec2 tileOrigin() { return ivec2(gl_WorkGroupID.xy) * TILE; }
|
||||
ivec2 tileOrigin() { return groupId() * TILE; }
|
||||
int bandIndex(ivec2 c) { ivec2 r = c - (tileOrigin() - BAND_BORDER); return r.y * BAND_SIDE + r.x; }
|
||||
int pilotIndex(ivec2 c) { ivec2 r = c - (tileOrigin() - PILOT_BORDER); return r.y * PILOT_SIDE + r.x; }
|
||||
|
||||
@@ -718,7 +721,7 @@ internal object PhotonDenoiseShaders {
|
||||
memoryBarrierShared();
|
||||
barrier();
|
||||
|
||||
ivec2 p = ivec2(gl_GlobalInvocationID.xy);
|
||||
ivec2 p = globalId();
|
||||
if (any(greaterThanEqual(p, uSize))) return;
|
||||
${if (debugOutputs) DEBUG_STORE else RESULT_STORE}
|
||||
}
|
||||
|
||||
@@ -3,6 +3,7 @@ package com.hinnka.mycamera.raw.denoise
|
||||
import android.opengl.GLES30
|
||||
import android.opengl.GLES31
|
||||
import com.hinnka.mycamera.processor.GlesComputeWorkGroup
|
||||
import com.hinnka.mycamera.processor.GlesGpuScheduler
|
||||
import com.hinnka.mycamera.raw.RawDenoiseHistory
|
||||
import com.hinnka.mycamera.raw.RawGlesProgram
|
||||
import java.nio.ByteBuffer
|
||||
@@ -97,7 +98,8 @@ internal class PhotonMultiScaleDenoiser {
|
||||
uniform2i(analyzeProgram, "uFineSize", sizes[level])
|
||||
uniform2i(analyzeProgram, "uCoarseSize", coarse)
|
||||
bindImage(0, gaussians[level + 1], GLES30.GL_RGBA16F)
|
||||
dispatch(coarse)
|
||||
dispatch(analyzeProgram, coarse)
|
||||
GlesGpuScheduler.yieldToUiRenderer()
|
||||
sink?.onPass("G${level + 1}", gaussians[level + 1], coarse[0], coarse[1], false)
|
||||
}
|
||||
|
||||
@@ -135,7 +137,7 @@ internal class PhotonMultiScaleDenoiser {
|
||||
bindImage(1, base, GLES30.GL_RGBA16F)
|
||||
bindImage(2, noise, GLES30.GL_RGBA32F)
|
||||
bindImage(3, pilot, GLES30.GL_RGBA16F)
|
||||
dispatch(size)
|
||||
dispatch(synthesizeDebugProgram, size)
|
||||
sink.onPass("band$level", band, size[0], size[1], false)
|
||||
sink.onPass("base$level", base, size[0], size[1], false)
|
||||
sink.onPass("noise$level", noise, size[0], size[1], true)
|
||||
@@ -151,7 +153,8 @@ internal class PhotonMultiScaleDenoiser {
|
||||
bindSynthesize(synthesizeProgram, inputTexture, lscTexture, mergeTexture, gaussians,
|
||||
denoisedCoarse, sizes, level, lumaEnabled, params)
|
||||
bindImage(0, result, GLES30.GL_RGBA16F)
|
||||
dispatch(size)
|
||||
dispatch(synthesizeProgram, size)
|
||||
GlesGpuScheduler.yieldToUiRenderer()
|
||||
sink?.onPass(if (level == 0) "output" else "denoised$level", result, size[0], size[1], false)
|
||||
|
||||
if (denoisedCoarse != gaussians[params.levels]) {
|
||||
@@ -231,6 +234,7 @@ internal class PhotonMultiScaleDenoiser {
|
||||
GLES31.glUniform1fv(location(resolveProgram, "uCapChroma"), capChroma.size, capChroma, 0)
|
||||
GLES31.glDispatchCompute(1, 1, 1)
|
||||
GLES31.glMemoryBarrier(GLES31.GL_SHADER_STORAGE_BARRIER_BIT or GLES31.GL_BUFFER_UPDATE_BARRIER_BIT)
|
||||
GlesGpuScheduler.yieldToUiRenderer()
|
||||
}
|
||||
GLES31.glBindBufferBase(GLES31.GL_SHADER_STORAGE_BUFFER, 1, 0)
|
||||
}
|
||||
@@ -364,12 +368,14 @@ internal class PhotonMultiScaleDenoiser {
|
||||
return texture
|
||||
}
|
||||
|
||||
private fun dispatch(size: IntArray) {
|
||||
GLES31.glDispatchCompute(
|
||||
GlesComputeWorkGroup.imageGroupCount(size[0]),
|
||||
GlesComputeWorkGroup.imageGroupCount(size[1]),
|
||||
1,
|
||||
)
|
||||
/**
|
||||
* One whole-level dispatch. As in GlesMgcRawSpatialStacker, the UI renderer is kept responsive
|
||||
* by the low-priority EGL context and a flush + yield between levels, never by fence waits
|
||||
* inside a level: those drain the GPU and leave it idle until this thread wakes up.
|
||||
*/
|
||||
private fun dispatch(program: Int, size: IntArray) {
|
||||
GLES31.glDispatchCompute(GlesComputeWorkGroup.imageGroupCount(size[0]),
|
||||
GlesComputeWorkGroup.imageGroupCount(size[1]), 1)
|
||||
GLES31.glMemoryBarrier(
|
||||
GLES31.GL_SHADER_IMAGE_ACCESS_BARRIER_BIT or GLES31.GL_TEXTURE_FETCH_BARRIER_BIT or
|
||||
GLES31.GL_FRAMEBUFFER_BARRIER_BIT,
|
||||
|
||||
Reference in new issue
Block a user