feat: strip-based photon denoiser synthesis and estimation optimizations

This commit is contained in:
zhoubinjia committed 2026-11-05 12:47:00 +08:00
1 parent 1adf028bcb
commit 39c2351398
3 files changed
+697 -464

No files matched your search

@@ -52,7 +52,7 @@ internal object PhotonDenoiseDump {
val directory = directory(context)
val stem = "${System.currentTimeMillis()}_${label}_${params.originX}_${params.originY}"
runCatching {
val pixels = readTexture(inputTexture, width, height, float32 = false)
val pixels = readTexture(inputTexture, 0, 0, width, height, float32 = false)
FileOutputStream(File(directory, "$stem.rgba16f")).use { Channels.newChannel(it).write(pixels) }
File(directory, "$stem.json").writeText(describe(width, height, metadata, params, lensShadingSource).toString(2))
File(directory, "$stem.params.json").writeText(params.toJson().toString(2))
@@ -71,7 +71,8 @@ internal object PhotonDenoiseDump {
private fun directory(context: Context) = File(context.getExternalFilesDir(null), DIRECTORY).apply { mkdirs() }
private fun readTexture(texture: Int, width: Int, height: Int, float32: Boolean): ByteBuffer {
/** Reads the [width] × [height] region at ([x], [y]) of [texture]. */
private fun readTexture(texture: Int, x: Int, y: Int, width: Int, height: Int, float32: Boolean): ByteBuffer {
val buffer = ByteBuffer.allocateDirect(width * height * 4 * if (float32) 4 else 2).order(ByteOrder.nativeOrder())
val framebuffer = IntArray(1)
GLES30.glGenFramebuffers(1, framebuffer, 0)
@@ -83,7 +84,7 @@ internal object PhotonDenoiseDump {
"Texture $texture is not readable"
}
GLES30.glPixelStorei(GLES30.GL_PACK_ALIGNMENT, 4)
GLES30.glReadPixels(0, 0, width, height, GLES30.GL_RGBA,
GLES30.glReadPixels(x, y, width, height, GLES30.GL_RGBA,
if (float32) GLES30.GL_FLOAT else GLES30.GL_HALF_FLOAT, buffer)
} finally {
GLES30.glBindFramebuffer(GLES30.GL_FRAMEBUFFER, 0)
@@ -104,8 +105,16 @@ internal object PhotonDenoiseDump {
runCatching {
var strength: FloatArray? = null
val sink = object : PhotonMultiScaleDenoiser.PassSink {
override fun onPass(name: String, textureId: Int, width: Int, height: Int, float32: Boolean) {
val buffer = readTexture(textureId, width, height, float32)
override fun onPass(
name: String,
textureId: Int,
x: Int,
y: Int,
width: Int,
height: Int,
float32: Boolean,
) {
val buffer = readTexture(textureId, x, y, width, height, float32)
val suffix = if (float32) "f32" else "f16"
FileOutputStream(File(directory, "$stem.$name.$suffix")).use { Channels.newChannel(it).write(buffer) }
passes.put(JSONObject().apply {
@@ -10,6 +10,16 @@ import com.hinnka.mycamera.raw.RawDenoiseHistory
* Band = band, Pilot = pilot, Final = final + output. Arithmetic is highp; stores round to the
* image format (RGBA16F, noise RGBA32F). Pyramid borders reflect without edge repetition.
*/
/** Stage switches of one synthesis program; [prefilter] applies only with [fineIsInput]. */
internal data class PhotonSynthesisVariant(
val fineIsInput: Boolean,
val writeOutput: Boolean,
val prefilter: Boolean,
val luma: Boolean,
val chroma: Boolean,
val bilateral: Boolean,
)
internal object PhotonDenoiseShaders {
private const val LOCAL = GlesComputeWorkGroup.IMAGE_TILE_SIZE
@@ -38,10 +48,7 @@ internal object PhotonDenoiseShaders {
layout(local_size_x = $LOCAL, local_size_y = $LOCAL) in;
// Work-group offset of a partial dispatch (row bands of the synthesis); 0 for a whole level.
uniform ivec2 uGroupOffset;
ivec2 groupId() { return ivec2(gl_WorkGroupID.xy) + uGroupOffset; }
ivec2 globalId() { return groupId() * $LOCAL + ivec2(gl_LocalInvocationID.xy); }
ivec2 globalId() { return ivec2(gl_GlobalInvocationID.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);
@@ -217,14 +224,11 @@ internal object PhotonDenoiseShaders {
"""
/**
* §6.0 level-0 outlier correction: a luma sample far from its 3×3 median whose deviation has at
* most PREFILTER_GUARD same-signed neighbours (a dot, not a line) in a noise-like neighbourhood
* (mean L0² of the 5×5 ring below PREFILTER_FLAT σ²) is moved to the median, scaled by
* uAmount = min(luma strength, 1). Writes that correction (R32F, 0 elsewhere); σ² is the L0
* model noise times the §5.1 strength at the noisy base.
* Declarations of both prefilter programs. The samples image covers the strip plus 2 pixels on
* every side; uSampleOrigin is the raw coordinate of its texel (0, 0), uExtent the size of the
* dispatched region.
*/
val PREFILTER = """
#version 310 es
private val PREFILTER_COMMON = """
$COMMON
$LENS_SHADING
$WORKING
@@ -232,41 +236,57 @@ internal object PhotonDenoiseShaders {
uniform ivec2 uSize;
uniform ivec2 uCoarseSize;
uniform float uAmount;
uniform ivec2 uSampleOrigin;
uniform ivec2 uExtent;
$UPSAMPLE
$MODEL_NOISE
$STRENGTH_LOOKUP
layout(r32f, binding = 0) writeonly uniform highp image2D uDelta;
"""
const int TILE = $LOCAL;
const int BORDER = 2;
const int SIDE = TILE + 2 * BORDER;
shared float sFine[SIDE * SIDE];
shared float sLap[SIDE * SIDE];
shared float sNoise[SIDE * SIDE];
int sideIndex(ivec2 c) { ivec2 r = c - (groupId() * TILE - BORDER); return r.y * SIDE + r.x; }
/**
* §6.0 level-0 outlier correction: a luma sample far from its 3×3 median whose deviation has at
* most PREFILTER_GUARD same-signed neighbours (a dot, not a line) in a noise-like neighbourhood
* (mean L0² of the 5×5 ring below PREFILTER_FLAT σ²) is moved to the median, scaled by
* uAmount = min(luma strength, 1). Writes that correction (R32F, 0 elsewhere); σ² is the L0
* model noise times the §5.1 strength at the noisy base. Per row strip this program writes the
* samples (fine luma, L rounded to float16, σ²) of the strip and its border, [PREFILTER] the
* correction.
*/
val PREFILTER_SAMPLES = """
#version 310 es
$PREFILTER_COMMON
layout(rgba32f, binding = 0) writeonly uniform highp image2D uSamplesOut;
void main() {
int lid = int(gl_LocalInvocationIndex);
ivec2 origin = groupId() * TILE;
for (int i = lid; i < SIDE * SIDE; i += TILE * TILE) {
ivec2 c = origin - BORDER + ivec2(i % SIDE, i / SIDE);
ivec2 p = mirror2(c, uSize);
float fine = working0(p).x;
vec3 base = upAt(uNoisyCoarse, p);
vec3 mu;
float noise = modelNoise(p, base, mu).x * strengthAt(base.x).x;
sFine[i] = fine;
sLap[i] = unpackHalf2x16(packHalf2x16(vec2(fine - base.x, 0.0))).x;
sNoise[i] = noise;
}
memoryBarrierShared();
barrier();
ivec2 t = globalId();
if (any(greaterThanEqual(t, uExtent))) return;
ivec2 p = mirror2(uSampleOrigin + t, uSize);
float fine = working0(p).x;
vec3 base = upAt(uNoisyCoarse, p);
vec3 mu;
float noise = modelNoise(p, base, mu).x * strengthAt(base.x).x;
float lap = unpackHalf2x16(packHalf2x16(vec2(fine - base.x, 0.0))).x;
imageStore(uSamplesOut, t, vec4(fine, lap, noise, 0.0));
}
""".trimIndent()
ivec2 p = globalId();
if (any(greaterThanEqual(p, uSize))) return;
/** §6.0 correction of the strip rows from the [PREFILTER_SAMPLES] image (uSamples). */
val PREFILTER = """
#version 310 es
$PREFILTER_COMMON
uniform sampler2D uSamples;
uniform ivec2 uOutputOrigin; // pixel of texel 0
layout(r32f, binding = 0) writeonly uniform highp image2D uDelta;
// Raw coordinates: the samples hold the values of the mirrored coordinate.
vec4 sampleAt(ivec2 c) { return texelFetch(uSamples, c - uSampleOrigin, 0); }
void main() {
ivec2 t = globalId();
if (any(greaterThanEqual(t, uExtent))) return;
ivec2 p = uOutputOrigin + t;
float v[9];
for (int j = 0; j < 9; ++j) v[j] = sFine[sideIndex(p + ivec2(j % 3 - 1, j / 3 - 1))];
for (int j = 0; j < 9; ++j) v[j] = sampleAt(p + ivec2(j % 3 - 1, j / 3 - 1)).x;
for (int i = 1; i < 9; ++i) {
float x = v[i];
int j = i - 1;
@@ -277,26 +297,27 @@ internal object PhotonDenoiseShaders {
v[j + 1] = x;
}
float m = v[4];
float fineP = sFine[sideIndex(p)];
float sigma = sqrt(sNoise[sideIndex(p)]);
vec4 centre = sampleAt(p);
float fineP = centre.x;
float sigma = sqrt(centre.z);
float dev = fineP - m;
float delta = 0.0;
if (sigma > 0.0 && abs(dev) > $PREFILTER_K * sigma) {
int count = 0;
for (int j = 0; j < 9; ++j) {
if (j == 4) continue;
float d = sFine[sideIndex(p + ivec2(j % 3 - 1, j / 3 - 1))] - m;
float d = sampleAt(p + ivec2(j % 3 - 1, j / 3 - 1)).x - m;
if (abs(d) > $PREFILTER_K * sigma && sign(d) == sign(dev)) ++count;
}
if (count <= $PREFILTER_GUARD) {
float sum = 0.0;
for (int dy = -2; dy <= 2; ++dy) {
for (int dx = -2; dx <= 2; ++dx) {
float l = sLap[sideIndex(p + ivec2(dx, dy))];
float l = sampleAt(p + ivec2(dx, dy)).y;
sum += l * l;
}
}
float lp = sLap[sideIndex(p)];
float lp = centre.y;
float energy = (sum - lp * lp) / 24.0;
if (energy < $PREFILTER_FLAT * sigma * sigma) delta = (m - fineP) * uAmount;
}
@@ -305,6 +326,7 @@ internal object PhotonDenoiseShaders {
}
""".trimIndent()
/** Analyze: G_{l+1} = ↓2(h * G_l), luma taps on Y and chroma taps on Cb/Cr. */
val ANALYZE = """
#version 310 es
@@ -337,42 +359,13 @@ internal object PhotonDenoiseShaders {
}
""".trimIndent()
/**
* Fused per-level synthesis: Band → Pilot → Final in one dispatch (§10.1).
*
* A work group owns an 8×8 output tile. Band values (L, base, noise) are computed into shared
* memory for the tile plus a 4-pixel border, pilot values for the tile plus a 2-pixel border.
* Shared memory is addressed by raw image coordinate and holds the value of the mirrored
* coordinate (the reference's reflection without edge repetition), so neighbourhood reads are
* plain offsets and border pixels see the same values as the unfused reference. L, base and pilot
* are stored as packed float16 bits, rounding them exactly as their textures were rounded in
* the unfused passes.
*
* [debugOutputs] compiles the parity variant: instead of the result it writes band, base,
* noise and pilot of the tile core (tools/photon_denoise/compare_passes.py); four images, the
* GLES 3.1 minimum. The production variant writes only the result.
*/
private const val DEBUG_IMAGES = """
layout(rgba16f, binding = 0) writeonly uniform highp image2D uBandOut;
layout(rgba16f, binding = 1) writeonly uniform highp image2D uBaseOut;
layout(rgba32f, binding = 2) writeonly uniform highp image2D uNoiseOut;
layout(rgba16f, binding = 3) writeonly uniform highp image2D uPilotOut;
"""
private const val RESULT_IMAGE = """
layout(rgba16f, binding = 0) writeonly uniform highp image2D uResult;
"""
private const val DEBUG_STORE = """
imageStore(uBandOut, p, vec4(lapAt(p), 0.0));
imageStore(uBaseOut, p, vec4(baseAt(p), 0.0));
imageStore(uNoiseOut, p, noiseAt(p));
if (uLumaEnabled == 1) imageStore(uPilotOut, p, pilotAt(p));
"""
private const val RESULT_STORE = """
vec3 result = computeFinal(p);
if (uWriteOutput == 1) {
if (WRITE_OUTPUT) {
vec3 rgb = rgbFromYcc(result) / uScale / uWb * lscGain(levelCentre(p, 0));
imageStore(uResult, p, vec4(rgb, 1.0));
} else {
@@ -381,32 +374,40 @@ internal object PhotonDenoiseShaders {
"""
/**
* §5.1 estimate, steps 1–3 at one level: a work group histograms ESTIMATE_BLOCK² samples per
* invocation into shared memory and adds its non-zero counts to the global histogram
* [level][bin][Y, Cb, Cr][bucket]. Samples: every uStride-th pixel, each 2×2 block of samples
* offset so that all four Bayer phases occur. After the first pass the flat gate's noise is
* scaled by the median luma strength of this level in the previous pass's table.
* Declarations of [ESTIMATE] and [ESTIMATE_RECORDS]: the histograms, the sample records (from
* uRecordOffset three planes of uRecordCount uints, row-major over the sample grid: packed bin
* and buckets, gradient, σ²_Y; planes keep every store contiguous across lanes), the flat-gate
* scale and the counting of one record into the shared histogram.
*
* The shared histogram is split to spread the atomics: HIST_COPIES copies, invocation i counting
* into copy i % HIST_COPIES, so the lanes of a warp hit the same word less often; each copy packs
* buckets k and k + HIST_BUCKETS / 2 as the low and high 16 bits of one word (a copy counts at
* most 64 / HIST_COPIES × ESTIMATE_BLOCK² samples per entry), keeping all copies within the
* 16KB shared-memory baseline. The flush sums the copies, so the counts are unchanged.
*/
val ESTIMATE = """
#version 310 es
private val ESTIMATE_DECLS = """
$COMMON
$LENS_SHADING
$WORKING
uniform sampler2D uFine;
uniform int uFineIsInput;
uniform sampler2D uCoarse;
uniform ivec2 uSize;
uniform ivec2 uCoarseSize;
uniform int uStride;
$UPSAMPLE
$MODEL_NOISE
layout(std430, binding = 0) buffer Histogram { uint uHistogram[]; };
layout(std430, binding = 1) readonly buffer PreviousTable { float uPrevious[]; };
layout(std430, binding = 2) buffer Records { uint uRecords[]; };
uniform int uHasPrevious;
uniform int uRecordOffset;
uniform int uRecordCount;
const int ENTRIES = $STRENGTH_BINS * 3 * $HIST_BUCKETS;
const int BLOCK = $ESTIMATE_BLOCK;
shared uint sHistogram[ENTRIES];
const int BIN_BITS = 4;
const int BUCKET_BITS = 6;
const uint NO_RECORD = 0xFFFFFFFFu;
const int HIST_COPIES = 4;
const int HALF_BUCKETS = $HIST_BUCKETS / 2;
const int WORDS = ENTRIES / 2;
shared uint sHistogram[HIST_COPIES * WORDS];
$MEDIAN8
@@ -420,35 +421,96 @@ internal object PhotonDenoiseShaders {
return median8(v);
}
void addSample(ivec2 p, float gate) {
int recordIndex(ivec2 q, ivec2 sampleSize) { return uRecordOffset + q.y * sampleSize.x + q.x; }
// Counts a record whose base gradient passes the flat gate scaled by gate.
void countRecord(uvec3 record, float gate) {
if (record.x == NO_RECORD) return;
float gradient = uintBitsToFloat(record.y);
float noiseY = uintBitsToFloat(record.z);
if (!(gradient < $FLAT_GATE * sqrt(gate * noiseY))) return;
int bin = int(record.x & ((1u << uint(BIN_BITS)) - 1u));
int copy = (int(gl_LocalInvocationIndex) % HIST_COPIES) * WORDS;
for (int ch = 0; ch < 3; ++ch) {
int k = int((record.x >> uint(BIN_BITS + ch * BUCKET_BITS)) & ((1u << uint(BUCKET_BITS)) - 1u));
int word = (bin * 3 + ch) * HALF_BUCKETS + k % HALF_BUCKETS;
atomicAdd(sHistogram[copy + word], k < HALF_BUCKETS ? 1u : 0x10000u);
}
}
void clearHistogram() {
for (int i = int(gl_LocalInvocationIndex); i < HIST_COPIES * WORDS; i += $LOCAL * $LOCAL) {
sHistogram[i] = 0u;
}
memoryBarrierShared();
barrier();
}
// Sums the copies of each word and adds the non-zero counts of its two entries.
void flushHistogram() {
memoryBarrierShared();
barrier();
for (int i = int(gl_LocalInvocationIndex); i < WORDS; i += $LOCAL * $LOCAL) {
uint low = 0u;
uint high = 0u;
for (int c = 0; c < HIST_COPIES; ++c) {
uint packed = sHistogram[c * WORDS + i];
low += packed & 0xFFFFu;
high += packed >> 16u;
}
int entry = uLevel * ENTRIES + (i / HALF_BUCKETS) * $HIST_BUCKETS + i % HALF_BUCKETS;
if (low != 0u) atomicAdd(uHistogram[entry], low);
if (high != 0u) atomicAdd(uHistogram[entry + HALF_BUCKETS], high);
}
}
"""
/**
* §5.1 estimate, steps 1–3 at one level: a work group histograms ESTIMATE_BLOCK² samples per
* invocation into shared memory and adds its non-zero counts to the global histogram
* [level][bin][Y, Cb, Cr][bucket]. Samples: every uStride-th pixel, each 2×2 block of samples
* offset so that all four Bayer phases occur. This first pass also stores every sample's record
* for [ESTIMATE_RECORDS]; after the first pass the flat gate's noise is scaled by the median
* luma strength of this level in the previous pass's table.
*/
val ESTIMATE = """
#version 310 es
$ESTIMATE_DECLS
uniform sampler2D uFine;
uniform int uFineIsInput;
uniform sampler2D uCoarse;
uniform ivec2 uCoarseSize;
$UPSAMPLE
// The record of the sample at p (NO_RECORD where the noise or the signal is not positive):
// packed bin and Y, Cb, Cr buckets, the base gradient and σ²_Y of the flat gate.
uvec3 sampleRecord(ivec2 p) {
vec3 fine = uFineIsInput == 1 ? working0(p) : texelFetch(uFine, p, 0).rgb;
vec3 base = upAt(uCoarse, p);
vec3 lap = fine - base;
vec3 mu;
vec4 noise = modelNoise(p, base, mu);
if (!(noise.x > 0.0 && noise.y > 0.0 && noise.z > 0.0 && mu.g > 0.0)) return;
if (!(noise.x > 0.0 && noise.y > 0.0 && noise.z > 0.0 && mu.g > 0.0)) return uvec3(NO_RECORD, 0u, 0u);
ivec2 c = p / 2;
float gx = 0.25 * (texelFetch(uCoarse, ivec2(mirrorIndex(c.x + 1, uCoarseSize.x), c.y), 0).x -
texelFetch(uCoarse, ivec2(mirrorIndex(c.x - 1, uCoarseSize.x), c.y), 0).x);
float gy = 0.25 * (texelFetch(uCoarse, ivec2(c.x, mirrorIndex(c.y + 1, uCoarseSize.y)), 0).x -
texelFetch(uCoarse, ivec2(c.x, mirrorIndex(c.y - 1, uCoarseSize.y)), 0).x);
if (!(sqrt(gx * gx + gy * gy) < $FLAT_GATE * sqrt(gate * noise.x))) return;
int bin = clamp(int(floor(log2(max(base.x / uScale, 1e-12)) - $STRENGTH_LOW)), 0, $STRENGTH_BINS - 1);
const float BUCKET_SCALE = float($HIST_BUCKETS) / ($HIST_HIGH - $HIST_LOW);
uint packed = uint(bin);
for (int ch = 0; ch < 3; ++ch) {
float v = lap[ch] * lap[ch] / noise[ch];
int k = clamp(int(floor((log2(max(v, 1e-30)) - $HIST_LOW) * BUCKET_SCALE)), 0, $HIST_BUCKETS - 1);
atomicAdd(sHistogram[(bin * 3 + ch) * $HIST_BUCKETS + k], 1u);
packed |= uint(k) << uint(BIN_BITS + ch * BUCKET_BITS);
}
return uvec3(packed, floatBitsToUint(sqrt(gx * gx + gy * gy)), floatBitsToUint(noise.x));
}
void main() {
int lid = int(gl_LocalInvocationIndex);
for (int i = lid; i < ENTRIES; i += $LOCAL * $LOCAL) sHistogram[i] = 0u;
memoryBarrierShared();
barrier();
clearHistogram();
ivec2 sampleSize = (uSize + uStride - 1) / uStride;
ivec2 origin = groupId() * ($LOCAL * BLOCK);
ivec2 origin = ivec2(gl_WorkGroupID.xy) * ($LOCAL * BLOCK);
ivec2 lane = ivec2(gl_LocalInvocationID.xy);
float gate = gateScale();
for (int by = 0; by < BLOCK; ++by) {
@@ -456,16 +518,43 @@ internal object PhotonDenoiseShaders {
ivec2 q = origin + ivec2(bx, by) * $LOCAL + lane;
if (any(greaterThanEqual(q, sampleSize))) continue;
ivec2 p = uStride > 1 ? q * uStride + ivec2(q.y & 1, q.x & 1) : q;
if (any(greaterThanEqual(p, uSize))) continue;
addSample(p, gate);
uvec3 record = any(greaterThanEqual(p, uSize)) ? uvec3(NO_RECORD, 0u, 0u) : sampleRecord(p);
int index = recordIndex(q, sampleSize);
uRecords[index] = record.x;
uRecords[index + uRecordCount] = record.y;
uRecords[index + 2 * uRecordCount] = record.z;
countRecord(record, gate);
}
}
memoryBarrierShared();
barrier();
for (int i = lid; i < ENTRIES; i += $LOCAL * $LOCAL) {
uint n = sHistogram[i];
if (n != 0u) atomicAdd(uHistogram[uLevel * ENTRIES + i], n);
flushHistogram();
}
""".trimIndent()
/**
* §5.1 estimate passes after the first: the histogram of [ESTIMATE] recounted from the sample
* records the first pass stored, with the flat gate of this pass. The counts equal a full
* recomputation; the textures and the noise model are not read again.
*/
val ESTIMATE_RECORDS = """
#version 310 es
$ESTIMATE_DECLS
void main() {
clearHistogram();
ivec2 sampleSize = (uSize + uStride - 1) / uStride;
ivec2 origin = ivec2(gl_WorkGroupID.xy) * ($LOCAL * BLOCK);
ivec2 lane = ivec2(gl_LocalInvocationID.xy);
float gate = gateScale();
for (int by = 0; by < BLOCK; ++by) {
for (int bx = 0; bx < BLOCK; ++bx) {
ivec2 q = origin + ivec2(bx, by) * $LOCAL + lane;
if (any(greaterThanEqual(q, sampleSize))) continue;
int index = recordIndex(q, sampleSize);
countRecord(uvec3(uRecords[index], uRecords[index + uRecordCount],
uRecords[index + 2 * uRecordCount]), gate);
}
}
flushHistogram();
}
""".trimIndent()
@@ -603,119 +692,12 @@ internal object PhotonDenoiseShaders {
}
""".trimIndent()
fun synthesize(debugOutputs: Boolean): String = """
#version 310 es
$COMMON
$LENS_SHADING
$WORKING
uniform sampler2D uFine;
uniform int uFineIsInput;
uniform sampler2D uNoisyCoarse;
uniform sampler2D uDenoisedCoarse;
uniform ivec2 uSize;
uniform ivec2 uCoarseSize;
$UPSAMPLE
$MODEL_NOISE
$STRENGTH_LOOKUP
// §6.0 level-0 isolated-outlier correction of the input luma (PREFILTER); used when uFineIsInput.
uniform sampler2D uPrefilter;
uniform int uPrefilterEnabled;
uniform float uOutlier;
uniform float uAlpha;
uniform int uLumaEnabled;
uniform float uGrain;
uniform float uGamma; // §6.1 exponent of the second-stage gain
uniform int uChromaEnabled;
uniform float uChromaStrength; // min(s, 1)
uniform vec2 uGateLuma;
uniform vec2 uGateChroma;
uniform int uBilateral;
uniform float uBilateralLuma;
uniform float uBilateralChroma;
uniform int uWriteOutput; // level 0: camera RGB with gains restored
${if (debugOutputs) DEBUG_IMAGES else RESULT_IMAGE}
const int TILE = $LOCAL;
const int BAND_BORDER = 4;
const int PILOT_BORDER = 2;
const int BAND_SIDE = TILE + 2 * BAND_BORDER;
const int PILOT_SIDE = TILE + 2 * PILOT_BORDER;
const float BASE_RADIUS = 1.25;
const float GAMMA_LOW = 0.25;
const float GAMMA_HIGH = 0.5;
const float CENTRE_LOW = 6.0;
const float CENTRE_HIGH = 10.0;
// L and base (six halves) and the pilot (four halves) are held as packed float16 bits.
// Integer storage makes the float16 rounding unconditional: a compiler may legally fold
// unpackHalf2x16(packHalf2x16(x)) back to x, which left unrounded values in a float array.
shared uvec3 sLapBase[BAND_SIDE * BAND_SIDE];
shared vec4 sNoise[BAND_SIDE * BAND_SIDE];
shared uvec2 sPilot[PILOT_SIDE * PILOT_SIDE];
// ↑2 inputs of the band region: G_{l+1} (slot 0) and G̃_{l+1} (slot 1) at coarse coordinates
// gCoarseLo + [0, COARSE_SIDE)², each entry the texel of the mirrored coordinate. Pixels of
// the band region map into a span of at most 16 fine pixels, i.e. 12 coarse taps.
const int COARSE_SIDE = 12;
shared vec4 sCoarse[2 * COARSE_SIDE * COARSE_SIDE];
ivec2 gCoarseLo;
// upAt over the cached coarse texels: the same taps in the same order.
vec3 upCached(int slot, ivec2 p) {
int offset = slot * COARSE_SIDE * COARSE_SIDE;
float y = 0.0;
vec2 c = vec2(0.0);
for (int j = -3; j <= 3; ++j) {
if (((p.y - j) & 1) != 0) continue;
int cy = (p.y - j) / 2 - gCoarseLo.y;
for (int i = -3; i <= 3; ++i) {
if (((p.x - i) & 1) != 0) continue;
int cx = (p.x - i) / 2 - gCoarseLo.x;
vec3 v = sCoarse[offset + cy * COARSE_SIDE + cx].rgb;
y += 4.0 * LUMA_TAPS[i + 3] * LUMA_TAPS[j + 3] * v.x;
if (abs(i) <= 2 && abs(j) <= 2) c += 4.0 * CHROMA_TAPS[i + 2] * CHROMA_TAPS[j + 2] * v.yz;
}
}
return vec3(y, c);
}
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; }
// Band at image pixel p = mirror(c): L = G_l − ↑G_{l+1}, base = ↑G̃_{l+1}, noise = §2.1 × §5.1.
// Stored at c, so shared memory holds the mirrored values at their raw coordinates.
void computeBand(ivec2 c) {
ivec2 p = mirror2(c, uSize);
// Level 0 reads the input at uLevel = 0: one gain serves the input and the clip test.
vec3 gain = lscGain(levelCentre(p, uLevel));
vec3 fine = uFineIsInput == 1 ? working0Gain(p, gain) : texelFetch(uFine, p, 0).rgb;
if (uFineIsInput == 1 && uPrefilterEnabled == 1) fine.x += texelFetch(uPrefilter, p, 0).r;
vec3 base = upCached(1, p);
vec3 lap = fine - upCached(0, p);
vec3 mu;
vec3 s = strengthAt(base.x);
vec4 noise = modelNoiseGain(p, base, gain, mu) * vec4(s, sqrt(s.y * s.z));
int index = bandIndex(c);
sLapBase[index] = uvec3(packHalf2x16(lap.xy), packHalf2x16(vec2(lap.z, base.x)), packHalf2x16(base.yz));
sNoise[index] = noise;
}
// Raw coordinates: the arrays already hold the mirrored values (computeBand, main).
vec3 lapAt(ivec2 p) {
uvec3 u = sLapBase[bandIndex(p)];
return vec3(unpackHalf2x16(u.x), unpackHalf2x16(u.y).x);
}
vec3 baseAt(ivec2 p) {
uvec3 u = sLapBase[bandIndex(p)];
return vec3(unpackHalf2x16(u.y).y, unpackHalf2x16(u.z));
}
vec4 noiseAt(ivec2 p) { return sNoise[bandIndex(p)]; }
vec4 pilotAt(ivec2 p) {
uvec2 u = sPilot[pilotIndex(p)];
return vec4(unpackHalf2x16(u.x), unpackHalf2x16(u.y));
}
/**
* Pilot and final of one pixel (§6.1–6.2, §7.2–7.3) over the accessors lapAt, baseAt, noiseAt and
* pilotAt at raw coordinates (the values of the mirrored coordinate); shared by the pilot and final
* programs.
*/
private const val SYNTH_STAGES = """
// §6.1 steps 1–2: anisotropic spatial weight × Huber weight of window offset d.
float windowWeight(ivec2 d, float lapP, float lapQ, float sigma, float anisotropy, float c, float s) {
float rPar = BASE_RADIUS * (1.0 + anisotropy);
@@ -793,7 +775,7 @@ internal object PhotonDenoiseShaders {
vec4 noise = noiseAt(p);
float lumaBand = lap.x;
if (uLumaEnabled == 1) {
if (LUMA_ENABLED) {
vec4 pilotP = pilotAt(p);
float sigma = sqrt(noise.x);
float num = 0.0;
@@ -817,13 +799,13 @@ internal object PhotonDenoiseShaders {
vec2 chromaBand = lap.yz;
vec2 baseChroma = base.yz;
if (uChromaEnabled == 1) {
if (CHROMA_ENABLED) {
float sumL2 = 0.0;
float sumS2 = 0.0;
for (int dy = -1; dy <= 1; ++dy) {
for (int dx = -1; dx <= 1; ++dx) {
// §7.2: denoised luma (the pilot) opens the gate, not a luma noise sample.
float l = uLumaEnabled == 1 ? pilotAt(p + ivec2(dx, dy)).x : lapAt(p + ivec2(dx, dy)).x;
float l = LUMA_ENABLED ? pilotAt(p + ivec2(dx, dy)).x : lapAt(p + ivec2(dx, dy)).x;
sumL2 += l * l;
sumS2 += noiseAt(p + ivec2(dx, dy)).x;
}
@@ -834,7 +816,7 @@ internal object PhotonDenoiseShaders {
float gate = max(gateY, gateC);
chromaBand = (uChromaStrength * gate + (1.0 - uChromaStrength)) * lap.yz;
if (uBilateral == 1) {
if (BILATERAL_ENABLED) {
vec2 sum = vec2(0.0);
float weight = 0.0;
for (int dy = -2; dy <= 2; ++dy) {
@@ -856,41 +838,148 @@ internal object PhotonDenoiseShaders {
}
return vec3(base.x + lumaBand, baseChroma + chromaBand);
}
"""
/**
* Uniforms, stage switches and constants of every synthesis program (no #version, no images).
* The stage switches of [variant] are compile-time constants: with uniform switches the compiler
* allocates registers for every stage, also where a stage is off.
*/
private fun synthesisHeader(variant: PhotonSynthesisVariant) = """
$COMMON
$LENS_SHADING
$WORKING
const bool FINE_IS_INPUT = ${variant.fineIsInput}; // level 0: fine is computed from uInput
const bool WRITE_OUTPUT = ${variant.writeOutput}; // level 0: camera RGB with gains restored
const bool PREFILTER_ENABLED = ${variant.prefilter};
const bool LUMA_ENABLED = ${variant.luma};
const bool CHROMA_ENABLED = ${variant.chroma};
const bool BILATERAL_ENABLED = ${variant.bilateral};
uniform sampler2D uFine;
uniform sampler2D uNoisyCoarse;
uniform sampler2D uDenoisedCoarse;
uniform ivec2 uSize;
uniform ivec2 uCoarseSize;
$UPSAMPLE
$MODEL_NOISE
$STRENGTH_LOOKUP
// §6.0 level-0 isolated-outlier correction of the input luma (PREFILTER); used when FINE_IS_INPUT.
uniform sampler2D uPrefilter;
uniform float uOutlier;
uniform float uAlpha;
uniform float uGrain;
uniform float uGamma; // §6.1 exponent of the second-stage gain
uniform float uChromaStrength; // min(s, 1)
uniform vec2 uGateLuma;
uniform vec2 uGateChroma;
uniform float uBilateralLuma;
uniform float uBilateralChroma;
const float BASE_RADIUS = 1.25;
const float GAMMA_LOW = 0.25;
const float GAMMA_HIGH = 0.5;
const float CENTRE_LOW = 6.0;
const float CENTRE_HIGH = 10.0;
// Band at image pixel p: L = G_l − ↑G_{l+1}, base = ↑G̃_{l+1}, noise = §2.1 × §5.1. The program
// defines upNoisy and upDenoised, the ↑2 of G_{l+1} and G̃_{l+1} at p.
vec3 upNoisy(ivec2 p);
vec3 upDenoised(ivec2 p);
void bandValues(ivec2 p, out vec3 lap, out vec3 base, out vec4 noise) {
// Level 0 reads the input at uLevel = 0: one gain serves the input and the clip test.
vec3 gain = lscGain(levelCentre(p, uLevel));
vec3 fine = FINE_IS_INPUT ? working0Gain(p, gain) : texelFetch(uFine, p, 0).rgb;
if (FINE_IS_INPUT && PREFILTER_ENABLED) fine.x += texelFetch(uPrefilter, p, 0).r;
base = upDenoised(p);
lap = fine - upNoisy(p);
vec3 mu;
vec3 s = strengthAt(base.x);
noise = modelNoiseGain(p, base, gain, mu) * vec4(s, sqrt(s.y * s.z));
}
"""
/**
* Synthesis (§10.1): Band, Pilot and Final as separate per-pixel dispatches over one row strip,
* without shared memory or barriers. The band and pilot images cover the strip plus
* BAND_BORDER / PILOT_BORDER (4 / 2) on every side and hold the values of the mirrored
* coordinate (the reference's reflection without edge repetition) at raw coordinates, so
* neighbourhood reads are plain offsets and border pixels see the reference's values. uBandOrigin / uPilotOrigin are the raw coordinates of their
* texel (0, 0); uExtent is the size of the dispatched region.
*/
fun synthesizeBand(variant: PhotonSynthesisVariant): String = """
#version 310 es
${synthesisHeader(variant)}
layout(rgba16f, binding = 0) writeonly uniform highp image2D uLapOut;
layout(rgba16f, binding = 1) writeonly uniform highp image2D uBaseOut;
layout(rgba32f, binding = 2) writeonly uniform highp image2D uNoiseOut;
uniform ivec2 uBandOrigin;
uniform ivec2 uExtent;
vec3 upNoisy(ivec2 p) { return upAt(uNoisyCoarse, p); }
vec3 upDenoised(ivec2 p) { return upAt(uDenoisedCoarse, p); }
void main() {
int lid = int(gl_LocalInvocationIndex);
ivec2 origin = tileOrigin();
// Fine pixels the band region reads (mirrored), and the coarse taps of their ↑2.
ivec2 lo = ivec2(1 << 30);
for (int i = 0; i < BAND_SIDE; ++i) lo = min(lo, mirror2(origin - BAND_BORDER + ivec2(i), uSize));
gCoarseLo = (lo - 3) >> 1;
for (int i = lid; i < 2 * COARSE_SIDE * COARSE_SIDE; i += TILE * TILE) {
int slot = i / (COARSE_SIDE * COARSE_SIDE);
int r = i - slot * COARSE_SIDE * COARSE_SIDE;
ivec2 k = mirror2(gCoarseLo + ivec2(r % COARSE_SIDE, r / COARSE_SIDE), uCoarseSize);
sCoarse[i] = slot == 0 ? texelFetch(uNoisyCoarse, k, 0) : texelFetch(uDenoisedCoarse, k, 0);
}
memoryBarrierShared();
barrier();
for (int i = lid; i < BAND_SIDE * BAND_SIDE; i += TILE * TILE) {
ivec2 c = origin - BAND_BORDER + ivec2(i % BAND_SIDE, i / BAND_SIDE);
computeBand(c);
}
memoryBarrierShared();
barrier();
if (uLumaEnabled == 1) {
for (int i = lid; i < PILOT_SIDE * PILOT_SIDE; i += TILE * TILE) {
ivec2 c = origin - PILOT_BORDER + ivec2(i % PILOT_SIDE, i / PILOT_SIDE);
vec4 pilot = computePilot(mirror2(c, uSize));
sPilot[pilotIndex(c)] = uvec2(packHalf2x16(pilot.xy), packHalf2x16(pilot.zw));
}
}
memoryBarrierShared();
barrier();
ivec2 p = globalId();
if (any(greaterThanEqual(p, uSize))) return;
${if (debugOutputs) DEBUG_STORE else RESULT_STORE}
ivec2 t = globalId();
if (any(greaterThanEqual(t, uExtent))) return;
vec3 lap;
vec3 base;
vec4 noise;
bandValues(mirror2(uBandOrigin + t, uSize), lap, base, noise);
imageStore(uLapOut, t, vec4(lap, 0.0));
imageStore(uBaseOut, t, vec4(base, 0.0));
imageStore(uNoiseOut, t, noise);
}
""".trimIndent()
/** Pilot of the unfused synthesis (see [synthesizeBand]). */
fun synthesizePilot(variant: PhotonSynthesisVariant): String = """
#version 310 es
${synthesisHeader(variant)}
layout(rgba16f, binding = 0) writeonly uniform highp image2D uPilotOut;
uniform ivec2 uExtent;
$STRIP_ACCESS
vec3 upNoisy(ivec2 p) { return vec3(0.0); }
vec3 upDenoised(ivec2 p) { return vec3(0.0); }
$SYNTH_STAGES
void main() {
ivec2 t = globalId();
if (any(greaterThanEqual(t, uExtent))) return;
imageStore(uPilotOut, t, computePilot(mirror2(uPilotOrigin + t, uSize)));
}
""".trimIndent()
/** Final of the unfused synthesis (see [synthesizeBand]); uOutputOrigin is the pixel of texel 0. */
fun synthesizeFinal(variant: PhotonSynthesisVariant): String = """
#version 310 es
${synthesisHeader(variant)}
$RESULT_IMAGE
uniform ivec2 uExtent;
uniform ivec2 uOutputOrigin;
$STRIP_ACCESS
vec3 upNoisy(ivec2 p) { return vec3(0.0); }
vec3 upDenoised(ivec2 p) { return vec3(0.0); }
$SYNTH_STAGES
void main() {
ivec2 t = globalId();
if (any(greaterThanEqual(t, uExtent))) return;
ivec2 p = uOutputOrigin + t;
$RESULT_STORE
}
""".trimIndent()
/** Band and pilot images of the unfused synthesis at raw coordinates (see [synthesizeBand]). */
private const val STRIP_ACCESS = """
uniform sampler2D uLap;
uniform sampler2D uBase;
uniform sampler2D uNoise;
uniform sampler2D uPilot;
uniform ivec2 uBandOrigin;
uniform ivec2 uPilotOrigin;
vec3 lapAt(ivec2 c) { return texelFetch(uLap, c - uBandOrigin, 0).rgb; }
vec3 baseAt(ivec2 c) { return texelFetch(uBase, c - uBandOrigin, 0).rgb; }
vec4 noiseAt(ivec2 c) { return texelFetch(uNoise, c - uBandOrigin, 0); }
vec4 pilotAt(ivec2 c) { return texelFetch(uPilot, c - uPilotOrigin, 0); }
"""
}
@@ -13,59 +13,97 @@ import java.nio.ByteOrder
* GLES orchestration of the Photon denoiser (docs/photon-multiscale-denoise.md §4.3, §10).
*
* Analyze builds G_1..G_N (G_0 is computed from the input on the fly); the §5.1 strength table is
* then estimated from G_0..G_N unless the params carry one; synthesis runs the fused
* Band → Pilot → Final dispatch per level from coarse to fine, and level 0 writes camera RGB with
* the LSC gains restored. Only the Gaussian levels and two adjacent denoised levels are held
* (§10.2). A [PassSink] receives every pass output for parity checks; it adds a parity dispatch
* per level that emits the fused pass's band, base, noise and pilot tiles.
* then estimated from G_0..G_N unless the params carry one. The §6.0 prefilter and the synthesis
* run per row strip as separate per-pixel dispatches without shared memory: prefilter samples →
* correction, and per level from coarse to fine Band → Pilot → Final, level 0 writing camera RGB
* with the LSC gains restored. The strip images are shared by every strip and level; besides
* them only the Gaussian levels and two adjacent denoised levels are held (§10.2). A [PassSink]
* receives every pass output for parity checks; the synthesis then runs each level as one strip
* so its band, base, noise and pilot images cover the whole level.
*/
internal class PhotonMultiScaleDenoiser {
/** Receives pass outputs while their textures are alive (debug parity, §12.4). */
fun interface PassSink {
fun onPass(name: String, textureId: Int, width: Int, height: Int, float32: Boolean)
/** The [width] × [height] region at ([x], [y]) of [textureId] holds the pass output. */
fun onPass(name: String, textureId: Int, x: Int, y: Int, width: Int, height: Int, float32: Boolean)
/** The §5.1 strength table the synthesis used. */
fun onStrength(table: FloatArray) {}
}
private var analyzeProgram = 0
private var synthesizeProgram = 0
private var synthesizeDebugProgram = 0
/** Synthesis programs by kind and variant, compiled on first use. */
private val synthesizePrograms = HashMap<Pair<SynthesisKind, PhotonSynthesisVariant>, Int>()
private var estimateProgram = 0
private var estimateRecordsProgram = 0
private var prefilterSamplesProgram = 0
private var prefilterProgram = 0
/** §6.0 level-0 luma correction of the current [denoise] call (R32F), 0 when not run. */
private var prefilterTexture = 0
private var resolveProgram = 0
fun initialize(debug: Boolean = false): Boolean {
fun initialize(): Boolean {
if (analyzeProgram == 0) analyzeProgram = RawGlesProgram.compileCompute(PhotonDenoiseShaders.ANALYZE, "PhotonDenoiseAnalyze")
if (synthesizeProgram == 0) {
synthesizeProgram = RawGlesProgram.compileCompute(PhotonDenoiseShaders.synthesize(false), "PhotonDenoiseSynthesize")
if (prefilterSamplesProgram == 0) {
prefilterSamplesProgram =
RawGlesProgram.compileCompute(PhotonDenoiseShaders.PREFILTER_SAMPLES, "PhotonDenoisePrefilterSamples")
}
if (prefilterProgram == 0) {
prefilterProgram = RawGlesProgram.compileCompute(PhotonDenoiseShaders.PREFILTER, "PhotonDenoisePrefilter")
}
if (estimateProgram == 0) estimateProgram = RawGlesProgram.compileCompute(PhotonDenoiseShaders.ESTIMATE, "PhotonDenoiseEstimate")
if (resolveProgram == 0) resolveProgram = RawGlesProgram.compileCompute(PhotonDenoiseShaders.RESOLVE, "PhotonDenoiseResolve")
if (debug && synthesizeDebugProgram == 0) {
synthesizeDebugProgram =
RawGlesProgram.compileCompute(PhotonDenoiseShaders.synthesize(true), "PhotonDenoiseSynthesizeDebug")
if (estimateRecordsProgram == 0) {
estimateRecordsProgram =
RawGlesProgram.compileCompute(PhotonDenoiseShaders.ESTIMATE_RECORDS, "PhotonDenoiseEstimateRecords")
}
return analyzeProgram != 0 && synthesizeProgram != 0 && estimateProgram != 0 && resolveProgram != 0 &&
prefilterProgram != 0 &&
(!debug || synthesizeDebugProgram != 0)
if (resolveProgram == 0) resolveProgram = RawGlesProgram.compileCompute(PhotonDenoiseShaders.RESOLVE, "PhotonDenoiseResolve")
return analyzeProgram != 0 && estimateProgram != 0 && estimateRecordsProgram != 0 && resolveProgram != 0 &&
prefilterSamplesProgram != 0 && prefilterProgram != 0
}
/**
* The [kind] synthesis program of [variant], 0 when it does not compile. The variant is reduced
* to the switches the kind reads, so levels that differ only elsewhere share a program.
*/
private fun synthesizeProgram(kind: SynthesisKind, variant: PhotonSynthesisVariant): Int {
val key = when (kind) {
SynthesisKind.BAND -> variant.copy(writeOutput = false, luma = false, chroma = false, bilateral = false)
SynthesisKind.PILOT -> PhotonSynthesisVariant(false, false, false, false, false, false)
SynthesisKind.FINAL -> variant.copy(fineIsInput = false, prefilter = false)
}
return synthesizePrograms.getOrPut(kind to key) {
val name = "PhotonDenoiseSynthesize${kind.name}" +
"[input=${key.fineIsInput} output=${key.writeOutput} prefilter=${key.prefilter} " +
"luma=${key.luma} chroma=${key.chroma} bilateral=${key.bilateral}]"
val source = when (kind) {
SynthesisKind.BAND -> PhotonDenoiseShaders.synthesizeBand(key)
SynthesisKind.PILOT -> PhotonDenoiseShaders.synthesizePilot(key)
SynthesisKind.FINAL -> PhotonDenoiseShaders.synthesizeFinal(key)
}
RawGlesProgram.compileCompute(source, name)
}
}
/** Band, pilot (-1 without luma) and final programs of one level of [variant]. */
private fun levelPrograms(variant: PhotonSynthesisVariant): IntArray = intArrayOf(
synthesizeProgram(SynthesisKind.BAND, variant),
if (variant.luma) synthesizeProgram(SynthesisKind.PILOT, variant) else -1,
synthesizeProgram(SynthesisKind.FINAL, variant),
)
fun release() {
intArrayOf(analyzeProgram, synthesizeProgram, synthesizeDebugProgram, estimateProgram, resolveProgram,
prefilterProgram).forEach {
(intArrayOf(analyzeProgram, estimateProgram, estimateRecordsProgram, resolveProgram, prefilterSamplesProgram,
prefilterProgram) +
synthesizePrograms.values).forEach {
if (it != 0) GLES31.glDeleteProgram(it)
}
synthesizePrograms.clear()
analyzeProgram = 0
synthesizeProgram = 0
synthesizeDebugProgram = 0
estimateProgram = 0
estimateRecordsProgram = 0
prefilterSamplesProgram = 0
prefilterProgram = 0
resolveProgram = 0
}
@@ -83,7 +121,21 @@ internal class PhotonMultiScaleDenoiser {
strengthOut: FloatArray? = null,
sink: PassSink? = null,
): Int? {
if (!initialize(debug = sink != null)) return null
if (!initialize()) return null
val prefilterEnabled = params.lumaLevels > 0 && params.lumaStrength > 0f
val variants = List(params.levels) { level ->
val chroma = params.chromaStrength > 0f
PhotonSynthesisVariant(
fineIsInput = level == 0,
writeOutput = level == 0,
prefilter = level == 0 && prefilterEnabled,
luma = level < params.lumaLevels && params.lumaStrength > 0f,
chroma = chroma,
bilateral = chroma && level >= params.levels - params.bilateralLevels,
)
}
val programs = variants.map(::levelPrograms)
if (programs.any { 0 in it }) return null
val timing = PhotonDenoiseTiming(width, height, params)
val sizes = ArrayList<IntArray>(params.levels + 1)
sizes += intArrayOf(width, height)
@@ -117,7 +169,7 @@ internal class PhotonMultiScaleDenoiser {
dispatch(analyzeProgram, coarse)
}
GlesGpuScheduler.yieldToUiRenderer()
sink?.onPass("G${level + 1}", gaussians[level + 1], coarse[0], coarse[1], false)
sink?.onPass("G${level + 1}", gaussians[level + 1], 0, 0, coarse[0], coarse[1], false)
}
val tableSize = params.levels * RawDenoiseHistory.STRENGTH_ENTRIES
@@ -137,76 +189,50 @@ internal class PhotonMultiScaleDenoiser {
}
GLES31.glBindBufferBase(GLES31.GL_SHADER_STORAGE_BUFFER, 0, strengthBuffer)
// Strip images plus the band / pilot borders, reused by every strip and level; the
// parity run takes the whole height so a level is one strip.
val rows = if (sink != null) height else minOf(STRIP_ROWS, height)
val bandSize = intArrayOf(width + 2 * BAND_BORDER, rows + 2 * BAND_BORDER)
val pilotSize = intArrayOf(width + 2 * PILOT_BORDER, rows + 2 * PILOT_BORDER)
val strips = StripImages(rows, lap = texture(bandSize, GLES30.GL_RGBA16F),
base = texture(bandSize, GLES30.GL_RGBA16F), noise = texture(bandSize, GLES30.GL_RGBA32F),
pilot = texture(pilotSize, GLES30.GL_RGBA16F))
val frame = SynthesisFrame(inputTexture, lscTexture, mergeTexture, gaussians, sizes, params, strips)
prefilterTexture = 0
if (params.lumaLevels > 0 && params.lumaStrength > 0f) {
if (prefilterEnabled) {
prefilterTexture = texture(sizes[0], GLES30.GL_R32F)
timing.gpu("prefilter", "L0 ${width}x$height") {
GLES31.glUseProgram(prefilterProgram)
bindCommon(prefilterProgram, inputTexture, lscTexture, params)
bindModelNoise(prefilterProgram, mergeTexture, 0, params)
bindSampler(prefilterProgram, "uNoisyCoarse", UNIT_NOISY_COARSE, gaussians[1])
uniform2i(prefilterProgram, "uSize", sizes[0])
uniform2i(prefilterProgram, "uCoarseSize", sizes[1])
uniform1f(prefilterProgram, "uAmount", minOf(params.lumaStrength, 1f))
bindImage(0, prefilterTexture, GLES30.GL_R32F)
dispatch(prefilterProgram, sizes[0])
}
sink?.onPass("prefilter0", prefilterTexture, width, height, true)
timing.gpu("prefilter", "L0 ${width}x$height") { prefilter(frame, prefilterTexture) }
sink?.onPass("prefilter0", prefilterTexture, 0, 0, width, height, true)
}
var denoisedCoarse = gaussians[params.levels]
frame.denoisedCoarse = gaussians[params.levels]
for (level in params.levels - 1 downTo 0) {
val size = sizes[level]
val lumaEnabled = level < params.lumaLevels && params.lumaStrength > 0f
val chromaEnabled = params.chromaStrength > 0f
val bilateralEnabled = chromaEnabled && level >= params.levels - params.bilateralLevels
if (sink != null) {
// Parity variant: the same fused computation, emitting its band, base, noise
// and pilot tiles instead of the result.
val band = texture(size, GLES30.GL_RGBA16F)
val base = texture(size, GLES30.GL_RGBA16F)
val noise = texture(size, GLES30.GL_RGBA32F)
val pilot = if (lumaEnabled) texture(size, GLES30.GL_RGBA16F) else band
timing.gpu("synthesize.parity", "L$level ${size[0]}x${size[1]}") {
GLES31.glUseProgram(synthesizeDebugProgram)
bindSynthesize(synthesizeDebugProgram, inputTexture, lscTexture, mergeTexture, gaussians,
denoisedCoarse, sizes, level, lumaEnabled, chromaEnabled, bilateralEnabled, params)
bindImage(0, band, GLES30.GL_RGBA16F)
bindImage(1, base, GLES30.GL_RGBA16F)
bindImage(2, noise, GLES30.GL_RGBA32F)
bindImage(3, pilot, GLES30.GL_RGBA16F)
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)
if (lumaEnabled) sink.onPass("pilot$level", pilot, size[0], size[1], false)
listOf(band, base, noise, pilot).distinct().forEach { scratch ->
GLES30.glDeleteTextures(1, intArrayOf(scratch), 0)
owned.remove(scratch)
}
}
val variant = variants[level]
val result = if (level == 0) output else texture(size, GLES30.GL_RGBA16F)
timing.gpu("synthesize", "L$level ${size[0]}x${size[1]} luma=$lumaEnabled chroma=$chromaEnabled " +
"bilateral=$bilateralEnabled") {
GLES31.glUseProgram(synthesizeProgram)
bindSynthesize(synthesizeProgram, inputTexture, lscTexture, mergeTexture, gaussians,
denoisedCoarse, sizes, level, lumaEnabled, chromaEnabled, bilateralEnabled, params)
bindImage(0, result, GLES30.GL_RGBA16F)
dispatchBands(synthesizeProgram, size)
timing.gpu("synthesize", "L$level ${size[0]}x${size[1]} luma=${variant.luma} " +
"chroma=${variant.chroma} bilateral=${variant.bilateral}") {
synthesizeLevel(frame, level, programs[level], result)
}
sink?.onPass(if (level == 0) "output" else "denoised$level", result, size[0], size[1], false)
if (timing.ablation) {
synthesizeAblation(timing, inputTexture, lscTexture, mergeTexture, gaussians, denoisedCoarse,
sizes, level, lumaEnabled, chromaEnabled, bilateralEnabled, params)
if (sink != null) {
// One strip: the strip images hold this level's passes at their border offsets.
sink.onPass("band$level", strips.lap, BAND_BORDER, BAND_BORDER, size[0], size[1], false)
sink.onPass("base$level", strips.base, BAND_BORDER, BAND_BORDER, size[0], size[1], false)
sink.onPass("noise$level", strips.noise, BAND_BORDER, BAND_BORDER, size[0], size[1], true)
if (variant.luma) {
sink.onPass("pilot$level", strips.pilot, PILOT_BORDER, PILOT_BORDER, size[0], size[1], false)
}
sink.onPass(if (level == 0) "output" else "denoised$level", result, 0, 0, size[0], size[1], false)
}
if (timing.ablation) synthesizeAblation(timing, frame, level, variant)
if (denoisedCoarse != gaussians[params.levels]) {
GLES30.glDeleteTextures(1, intArrayOf(denoisedCoarse), 0)
owned.remove(denoisedCoarse)
val previous = frame.denoisedCoarse
if (previous != gaussians[params.levels]) {
GLES30.glDeleteTextures(1, intArrayOf(previous), 0)
owned.remove(previous)
}
denoisedCoarse = result
frame.denoisedCoarse = result
}
RawGlesProgram.logErrors("PhotonMultiScaleDenoiser")
timing.report()
@@ -225,44 +251,79 @@ internal class PhotonMultiScaleDenoiser {
}
/**
* Timing only: re-runs the fused synthesis of [level] into a scratch image with the luma,
* chroma gate and chroma bilateral stages switched on one at a time, and with all of them as in
* the real pass; the differences to the band-only run are each stage's GPU cost. Every variant
* runs [ABLATION_REPEATS] rounds and the report keeps the fastest, which drops the runs slowed
* by the GPU clocking down between serialized passes.
* §6.0 per row strip: the luma samples (fine, rounded L, σ²) of the strip plus PREFILTER_BORDER
* into the strip noise image, then the correction of the strip's rows into [target].
*/
private fun prefilter(frame: SynthesisFrame, target: Int) {
val strips = frame.strips
val size = frame.sizes[0]
var y = 0
while (y < size[1]) {
val rows = minOf(strips.rows, size[1] - y)
val sampleOrigin = intArrayOf(-PREFILTER_BORDER, y - PREFILTER_BORDER)
val sampleExtent = intArrayOf(size[0] + 2 * PREFILTER_BORDER, rows + 2 * PREFILTER_BORDER)
GLES31.glUseProgram(prefilterSamplesProgram)
bindPrefilter(prefilterSamplesProgram, frame)
uniform2i(prefilterSamplesProgram, "uSampleOrigin", sampleOrigin)
uniform2i(prefilterSamplesProgram, "uExtent", sampleExtent)
bindImage(0, strips.noise, GLES30.GL_RGBA32F)
dispatch(prefilterSamplesProgram, sampleExtent)
val extent = intArrayOf(size[0], rows)
GLES31.glUseProgram(prefilterProgram)
bindPrefilter(prefilterProgram, frame)
bindSampler(prefilterProgram, "uSamples", UNIT_NOISE, strips.noise)
uniform2i(prefilterProgram, "uSampleOrigin", sampleOrigin)
uniform2i(prefilterProgram, "uOutputOrigin", intArrayOf(0, y))
uniform2i(prefilterProgram, "uExtent", extent)
bindImage(0, target, GLES30.GL_R32F)
dispatch(prefilterProgram, extent)
GlesGpuScheduler.yieldToUiRenderer()
y += rows
}
}
private fun bindPrefilter(program: Int, frame: SynthesisFrame) {
val params = frame.params
bindCommon(program, frame.input, frame.lsc, params)
bindModelNoise(program, frame.merge, 0, params)
bindSampler(program, "uNoisyCoarse", UNIT_NOISY_COARSE, frame.gaussians[1])
uniform2i(program, "uSize", frame.sizes[0])
uniform2i(program, "uCoarseSize", frame.sizes[1])
uniform1f(program, "uAmount", minOf(params.lumaStrength, 1f))
}
/**
* Timing only: re-runs the synthesis of [level] into a scratch image with the luma, chroma gate
* and chroma bilateral stages switched on one at a time, and with all of them as in the real
* pass; the differences to the band-only run are each stage's GPU cost. Every variant runs
* [ABLATION_REPEATS] rounds and the report keeps the fastest, which drops the runs slowed by the
* GPU clocking down between serialized passes.
*/
private fun synthesizeAblation(
timing: PhotonDenoiseTiming,
inputTexture: Int,
lscTexture: Int,
mergeTexture: Int,
gaussians: IntArray,
denoisedCoarse: Int,
sizes: List<IntArray>,
frame: SynthesisFrame,
level: Int,
lumaEnabled: Boolean,
chromaEnabled: Boolean,
bilateralEnabled: Boolean,
params: PhotonDenoiseParams,
full: PhotonSynthesisVariant,
) {
val size = sizes[level]
val size = frame.sizes[level]
val none = full.copy(luma = false, chroma = false, bilateral = false)
val runs = buildList {
add("full" to full)
add("none" to none)
if (full.luma) add("luma" to none.copy(luma = true))
if (full.chroma) add("chroma" to none.copy(chroma = true))
if (full.bilateral) add("bilateral" to none.copy(chroma = true, bilateral = true))
}.map { (name, variant) ->
name to levelPrograms(variant).also { check(0 !in it) { "Ablation program $name does not compile" } }
}
val scratch = createTexture(size[0], size[1], GLES30.GL_RGBA16F)
try {
val variants = buildList {
add(AblationVariant("full", lumaEnabled, chromaEnabled, bilateralEnabled))
add(AblationVariant("none", false, false, false))
if (lumaEnabled) add(AblationVariant("luma", true, false, false))
if (chromaEnabled) add(AblationVariant("chroma", false, true, false))
if (bilateralEnabled) add(AblationVariant("bilateral", false, true, true))
}
repeat(ABLATION_REPEATS) {
for (variant in variants) {
timing.gpu(PhotonDenoiseTiming.ABLATION + variant.name, "L$level ${size[0]}x${size[1]}") {
GLES31.glUseProgram(synthesizeProgram)
bindSynthesize(synthesizeProgram, inputTexture, lscTexture, mergeTexture, gaussians,
denoisedCoarse, sizes, level, variant.luma, variant.chroma, variant.bilateral, params)
bindImage(0, scratch, GLES30.GL_RGBA16F)
dispatchBands(synthesizeProgram, size)
for ((name, programs) in runs) {
timing.gpu(PhotonDenoiseTiming.ABLATION + name, "L$level ${size[0]}x${size[1]}") {
synthesizeLevel(frame, level, programs, scratch)
}
}
}
@@ -271,6 +332,65 @@ internal class PhotonMultiScaleDenoiser {
}
}
/**
* Synthesizes [level] with [programs] ([levelPrograms]) into [target]: per row strip the band,
* pilot (luma only) and final dispatches, each strip flushed with a yield so the UI renderer
* gets GPU slots inside a level. As in GlesMgcRawSpatialStacker the UI is kept responsive by the
* low-priority EGL context and these yields, never by fence waits inside a level.
*/
private fun synthesizeLevel(frame: SynthesisFrame, level: Int, programs: IntArray, target: Int) {
val strips = frame.strips
val size = frame.sizes[level]
val (band, pilot, final) = programs
var y = 0
while (y < size[1]) {
val rows = minOf(strips.rows, size[1] - y)
val bandOrigin = intArrayOf(-BAND_BORDER, y - BAND_BORDER)
val pilotOrigin = intArrayOf(-PILOT_BORDER, y - PILOT_BORDER)
val bandExtent = intArrayOf(size[0] + 2 * BAND_BORDER, rows + 2 * BAND_BORDER)
GLES31.glUseProgram(band)
bindSynthesize(band, frame, level)
uniform2i(band, "uBandOrigin", bandOrigin)
uniform2i(band, "uExtent", bandExtent)
bindImage(0, strips.lap, GLES30.GL_RGBA16F)
bindImage(1, strips.base, GLES30.GL_RGBA16F)
bindImage(2, strips.noise, GLES30.GL_RGBA32F)
dispatch(band, bandExtent)
if (pilot > 0) {
val pilotExtent = intArrayOf(size[0] + 2 * PILOT_BORDER, rows + 2 * PILOT_BORDER)
GLES31.glUseProgram(pilot)
bindStrip(pilot, frame, level, bandOrigin, pilotOrigin)
uniform2i(pilot, "uExtent", pilotExtent)
bindImage(0, strips.pilot, GLES30.GL_RGBA16F)
dispatch(pilot, pilotExtent)
}
val finalExtent = intArrayOf(size[0], rows)
GLES31.glUseProgram(final)
bindStrip(final, frame, level, bandOrigin, pilotOrigin)
uniform2i(final, "uOutputOrigin", intArrayOf(0, y))
uniform2i(final, "uExtent", finalExtent)
bindImage(0, target, GLES30.GL_RGBA16F)
dispatch(final, finalExtent)
GlesGpuScheduler.yieldToUiRenderer()
y += rows
}
}
/** [bindSynthesize] plus the strip images the pilot and final read. */
private fun bindStrip(program: Int, frame: SynthesisFrame, level: Int, bandOrigin: IntArray, pilotOrigin: IntArray) {
val strips = frame.strips
bindSynthesize(program, frame, level)
bindSampler(program, "uLap", UNIT_LAP, strips.lap)
bindSampler(program, "uBase", UNIT_BASE, strips.base)
bindSampler(program, "uNoise", UNIT_NOISE, strips.noise)
bindSampler(program, "uPilot", UNIT_PILOT, strips.pilot)
uniform2i(program, "uBandOrigin", bandOrigin)
uniform2i(program, "uPilotOrigin", pilotOrigin)
}
/**
* §5.1: [PhotonDenoiseShaders.ESTIMATE_PASSES] rounds of histograms of every level followed by
* the resolve into [strengthBuffer]; every round after the first gates with the table of the
@@ -294,46 +414,75 @@ internal class PhotonMultiScaleDenoiser {
val capLuma = FloatArray(PhotonDenoiseTuning.MAX_LEVELS).also { params.strengthCapLuma.copyInto(it) }
val capChroma = FloatArray(PhotonDenoiseTuning.MAX_LEVELS).also { params.strengthCapChroma.copyInto(it) }
val span = GlesComputeWorkGroup.IMAGE_TILE_SIZE * PhotonDenoiseShaders.ESTIMATE_BLOCK
repeat(PhotonDenoiseShaders.ESTIMATE_PASSES) { pass ->
// glBufferData(null) leaves the contents undefined: the counts start from explicit zeros.
timing.gpu("estimate.clear", "pass$pass") { uploadBuffer(histogramBuffer, zeros) }
GLES31.glUseProgram(estimateProgram)
GLES31.glBindBufferBase(GLES31.GL_SHADER_STORAGE_BUFFER, 0, histogramBuffer)
GLES31.glBindBufferBase(GLES31.GL_SHADER_STORAGE_BUFFER, 1, strengthBuffer)
for (level in 0 until params.levels) timing.gpu("estimate.histogram", "pass$pass L$level") {
bindCommon(estimateProgram, inputTexture, lscTexture, params)
bindModelNoise(estimateProgram, mergeTexture, level, params)
bindSampler(estimateProgram, "uFine", UNIT_FINE, if (level == 0) inputTexture else gaussians[level])
bindSampler(estimateProgram, "uCoarse", UNIT_NOISY_COARSE, gaussians[level + 1])
uniform1i(estimateProgram, "uFineIsInput", if (level == 0) 1 else 0)
uniform2i(estimateProgram, "uSize", sizes[level])
uniform2i(estimateProgram, "uCoarseSize", sizes[level + 1])
uniform1i(estimateProgram, "uHasPrevious", if (pass > 0) 1 else 0)
val stride = when (level) {
0 -> 4
1 -> 2
else -> 1
}
uniform1i(estimateProgram, "uStride", stride)
val samplesX = (sizes[level][0] + stride - 1) / stride
val samplesY = (sizes[level][1] + stride - 1) / stride
GLES31.glDispatchCompute((samplesX + span - 1) / span, (samplesY + span - 1) / span, 1)
// Sample grid of every level and the offset of its records (three planes of one uint per sample).
val strides = IntArray(params.levels) { level ->
when (level) {
0 -> 4
1 -> 2
else -> 1
}
GLES31.glMemoryBarrier(GLES31.GL_SHADER_STORAGE_BARRIER_BIT)
timing.gpu("estimate.resolve", "pass$pass") {
GLES31.glUseProgram(resolveProgram)
}
val samples = List(params.levels) { level ->
intArrayOf((sizes[level][0] + strides[level] - 1) / strides[level],
(sizes[level][1] + strides[level] - 1) / strides[level])
}
val recordOffsets = IntArray(params.levels + 1)
for (level in 0 until params.levels) {
recordOffsets[level + 1] = recordOffsets[level] + RECORD_UINTS * samples[level][0] * samples[level][1]
}
val recordBuffer = IntArray(1)
GLES31.glGenBuffers(1, recordBuffer, 0)
try {
// The first pass writes every record before any is read, so the contents may start undefined.
GLES31.glBindBuffer(GLES31.GL_SHADER_STORAGE_BUFFER, recordBuffer[0])
GLES31.glBufferData(GLES31.GL_SHADER_STORAGE_BUFFER, recordOffsets[params.levels] * Int.SIZE_BYTES,
null, GLES31.GL_DYNAMIC_COPY)
GLES31.glBindBuffer(GLES31.GL_SHADER_STORAGE_BUFFER, 0)
repeat(PhotonDenoiseShaders.ESTIMATE_PASSES) { pass ->
// glBufferData(null) leaves the contents undefined: the counts start from explicit zeros.
timing.gpu("estimate.clear", "pass$pass") { uploadBuffer(histogramBuffer, zeros) }
// The first pass computes the samples and stores their records; the later passes
// recount the records with their own flat gate.
val program = if (pass == 0) estimateProgram else estimateRecordsProgram
GLES31.glUseProgram(program)
GLES31.glBindBufferBase(GLES31.GL_SHADER_STORAGE_BUFFER, 0, histogramBuffer)
GLES31.glBindBufferBase(GLES31.GL_SHADER_STORAGE_BUFFER, 1, strengthBuffer)
uniform1i(resolveProgram, "uLevels", params.levels)
GLES31.glUniform1fv(location(resolveProgram, "uCapLuma"), capLuma.size, capLuma, 0)
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)
GLES31.glBindBufferBase(GLES31.GL_SHADER_STORAGE_BUFFER, 2, recordBuffer[0])
for (level in 0 until params.levels) timing.gpu("estimate.histogram", "pass$pass L$level") {
bindCommon(program, inputTexture, lscTexture, params)
bindModelNoise(program, mergeTexture, level, params)
if (pass == 0) {
bindSampler(program, "uFine", UNIT_FINE, if (level == 0) inputTexture else gaussians[level])
bindSampler(program, "uCoarse", UNIT_NOISY_COARSE, gaussians[level + 1])
uniform1i(program, "uFineIsInput", if (level == 0) 1 else 0)
uniform2i(program, "uCoarseSize", sizes[level + 1])
}
uniform2i(program, "uSize", sizes[level])
uniform1i(program, "uHasPrevious", if (pass > 0) 1 else 0)
uniform1i(program, "uStride", strides[level])
uniform1i(program, "uRecordOffset", recordOffsets[level])
uniform1i(program, "uRecordCount", samples[level][0] * samples[level][1])
GLES31.glDispatchCompute((samples[level][0] + span - 1) / span, (samples[level][1] + span - 1) / span, 1)
}
GLES31.glMemoryBarrier(GLES31.GL_SHADER_STORAGE_BARRIER_BIT)
timing.gpu("estimate.resolve", "pass$pass") {
GLES31.glUseProgram(resolveProgram)
GLES31.glBindBufferBase(GLES31.GL_SHADER_STORAGE_BUFFER, 0, histogramBuffer)
GLES31.glBindBufferBase(GLES31.GL_SHADER_STORAGE_BUFFER, 1, strengthBuffer)
uniform1i(resolveProgram, "uLevels", params.levels)
GLES31.glUniform1fv(location(resolveProgram, "uCapLuma"), capLuma.size, capLuma, 0)
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()
}
GlesGpuScheduler.yieldToUiRenderer()
} finally {
GLES31.glBindBufferBase(GLES31.GL_SHADER_STORAGE_BUFFER, 1, 0)
GLES31.glBindBufferBase(GLES31.GL_SHADER_STORAGE_BUFFER, 2, 0)
GLES31.glDeleteBuffers(1, recordBuffer, 0)
}
GLES31.glBindBufferBase(GLES31.GL_SHADER_STORAGE_BUFFER, 1, 0)
}
private fun readStrength(buffer: Int, size: Int): FloatArray {
@@ -389,47 +538,29 @@ internal class PhotonMultiScaleDenoiser {
GLES31.glUniform2i(location(program, "uFullSize"), params.fullWidth, params.fullHeight)
}
private fun bindSynthesize(
program: Int,
inputTexture: Int,
lscTexture: Int,
mergeTexture: Int,
gaussians: IntArray,
denoisedCoarse: Int,
sizes: List<IntArray>,
level: Int,
lumaEnabled: Boolean,
chromaEnabled: Boolean,
bilateralEnabled: Boolean,
params: PhotonDenoiseParams,
) {
bindCommon(program, inputTexture, lscTexture, params)
bindSampler(program, "uFine", UNIT_FINE, if (level == 0) inputTexture else gaussians[level])
bindSampler(program, "uNoisyCoarse", UNIT_NOISY_COARSE, gaussians[level + 1])
private fun bindSynthesize(program: Int, frame: SynthesisFrame, level: Int) {
val params = frame.params
bindCommon(program, frame.input, frame.lsc, params)
bindSampler(program, "uFine", UNIT_FINE, if (level == 0) frame.input else frame.gaussians[level])
bindSampler(program, "uNoisyCoarse", UNIT_NOISY_COARSE, frame.gaussians[level + 1])
// The sampler needs a valid texture even when the correction is off.
bindSampler(program, "uPrefilter", UNIT_PREFILTER, if (prefilterTexture != 0) prefilterTexture else inputTexture)
uniform1i(program, "uPrefilterEnabled", if (prefilterTexture != 0) 1 else 0)
bindSampler(program, "uDenoisedCoarse", UNIT_DENOISED_COARSE, denoisedCoarse)
uniform1i(program, "uFineIsInput", if (level == 0) 1 else 0)
uniform2i(program, "uSize", sizes[level])
uniform2i(program, "uCoarseSize", sizes[level + 1])
bindModelNoise(program, mergeTexture, level, params)
bindSampler(program, "uPrefilter", UNIT_PREFILTER, if (prefilterTexture != 0) prefilterTexture else frame.input)
bindSampler(program, "uDenoisedCoarse", UNIT_DENOISED_COARSE, frame.denoisedCoarse)
uniform2i(program, "uSize", frame.sizes[level])
uniform2i(program, "uCoarseSize", frame.sizes[level + 1])
bindModelNoise(program, frame.merge, level, params)
uniform1f(program, "uOutlier", params.outlier[level])
uniform1f(program, "uAlpha", params.lumaAlpha(level))
uniform1i(program, "uLumaEnabled", if (lumaEnabled) 1 else 0)
uniform1f(program, "uGrain", params.lumaGrain(level))
uniform1f(program, "uGamma", params.gamma[level])
uniform1i(program, "uChromaEnabled", if (chromaEnabled) 1 else 0)
uniform1f(program, "uChromaStrength", minOf(params.chromaStrength, 1f))
val thresholdScale = params.chromaThresholdScale()
GLES31.glUniform2f(location(program, "uGateLuma"),
params.gateLuma[0] * thresholdScale, params.gateLuma[1] * thresholdScale)
GLES31.glUniform2f(location(program, "uGateChroma"),
params.gateChroma[0] * thresholdScale, params.gateChroma[1] * thresholdScale)
uniform1i(program, "uBilateral", if (bilateralEnabled) 1 else 0)
uniform1f(program, "uBilateralLuma", params.bilateralLuma)
uniform1f(program, "uBilateralChroma", params.bilateralChroma * thresholdScale)
uniform1i(program, "uWriteOutput", if (level == 0) 1 else 0)
}
private fun createTexture(width: Int, height: Int, format: Int): Int {
@@ -471,9 +602,9 @@ internal class PhotonMultiScaleDenoiser {
}
/**
* 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.
* One dispatch over [size]. As in GlesMgcRawSpatialStacker, the UI renderer is kept responsive
* by the low-priority EGL context and a flush + yield between strips and levels, never by fence
* waits: 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]),
@@ -484,31 +615,6 @@ internal class PhotonMultiScaleDenoiser {
)
}
/**
* The fused synthesis in row bands of [SYNTHESIS_BAND_GROUPS] work-group rows, each flushed with
* a yield so the UI renderer gets GPU slots inside a level (L0 alone is ~300ms in one dispatch).
* Tiles read only the inputs and write disjoint pixels, so bands need no barrier between them
* and the result is the same as one whole-level dispatch.
*/
private fun dispatchBands(program: Int, size: IntArray) {
val groupsX = GlesComputeWorkGroup.imageGroupCount(size[0])
val groupsY = GlesComputeWorkGroup.imageGroupCount(size[1])
val offset = location(program, "uGroupOffset")
var row = 0
while (row < groupsY) {
val rows = minOf(SYNTHESIS_BAND_GROUPS, groupsY - row)
GLES31.glUniform2i(offset, 0, row)
GLES31.glDispatchCompute(groupsX, rows, 1)
GlesGpuScheduler.yieldToUiRenderer()
row += rows
}
GLES31.glUniform2i(offset, 0, 0)
GLES31.glMemoryBarrier(
GLES31.GL_SHADER_IMAGE_ACCESS_BARRIER_BIT or GLES31.GL_TEXTURE_FETCH_BARRIER_BIT or
GLES31.GL_FRAMEBUFFER_BARRIER_BIT,
)
}
private fun bindImage(unit: Int, texture: Int, format: Int) {
GLES31.glBindImageTexture(unit, texture, 0, false, 0, GLES31.GL_WRITE_ONLY, format)
}
@@ -519,6 +625,29 @@ internal class PhotonMultiScaleDenoiser {
GLES31.glUniform1i(location(program, name), unit)
}
private enum class SynthesisKind { BAND, PILOT, FINAL }
/** What every prefilter and synthesis dispatch of one [denoise] call binds. */
private class SynthesisFrame(
val input: Int,
val lsc: Int,
val merge: Int,
val gaussians: IntArray,
val sizes: List<IntArray>,
val params: PhotonDenoiseParams,
val strips: StripImages,
) {
/** G̃_{l+1} of the level being synthesized. */
var denoisedCoarse = 0
}
/**
* Images of one row strip of [rows] rows (PhotonDenoiseShaders.synthesizeBand): L, base and
* noise with BAND_BORDER, the pilot with PILOT_BORDER on every side. The prefilter samples use
* the noise image with PREFILTER_BORDER.
*/
private class StripImages(val rows: Int, val lap: Int, val base: Int, val noise: Int, val pilot: Int)
private fun location(program: Int, name: String) = GLES31.glGetUniformLocation(program, name)
private fun uniform1i(program: Int, name: String, value: Int) = GLES31.glUniform1i(location(program, name), value)
private fun uniform1f(program: Int, name: String, value: Float) = GLES31.glUniform1f(location(program, name), value)
@@ -527,11 +656,13 @@ internal class PhotonMultiScaleDenoiser {
private fun uniform3f(program: Int, name: String, v: FloatArray) =
GLES31.glUniform3f(location(program, name), v[0], v[1], v[2])
private class AblationVariant(val name: String, val luma: Boolean, val chroma: Boolean, val bilateral: Boolean)
private companion object {
const val ABLATION_REPEATS = 3
const val SYNTHESIS_BAND_GROUPS = 64
const val RECORD_UINTS = 3
const val STRIP_ROWS = 256
const val BAND_BORDER = 4
const val PILOT_BORDER = 2
const val PREFILTER_BORDER = 2
const val UNIT_INPUT = 0
const val UNIT_LSC = 1
const val UNIT_FINE = 2
@@ -539,5 +670,9 @@ internal class PhotonMultiScaleDenoiser {
const val UNIT_DENOISED_COARSE = 4
const val UNIT_MERGE = 5
const val UNIT_PREFILTER = 6
const val UNIT_LAP = 7
const val UNIT_BASE = 8
const val UNIT_NOISE = 9
const val UNIT_PILOT = 10
}
}