perf: photon denoise shader caching and pass timing
This commit is contained in:
1 parent
1c7a519fd8
commit
74b91e815d
5 files changed
+288
-63
No files matched your search
@@ -314,14 +314,14 @@ internal class HncsToneAlgorithm(quad: RawFullscreenQuad) :
|
||||
uploaded = true
|
||||
}
|
||||
}
|
||||
if (uploaded) {
|
||||
/*if (uploaded) {
|
||||
PLog.d(
|
||||
TAG,
|
||||
"HNCS resources uploaded: profile=${renderPlan.profileId} " +
|
||||
"map=${renderPlan.colorMap.width}x${renderPlan.colorMap.height} " +
|
||||
"curves=${HncsProfileManager.CURVE_SAMPLE_COUNT}",
|
||||
)
|
||||
}
|
||||
}*/
|
||||
}
|
||||
|
||||
private fun uploadRgbaTexture(
|
||||
|
||||
@@ -125,10 +125,13 @@ internal object PhotonDenoiseShaders {
|
||||
uniform float uScale;
|
||||
uniform vec3 uWb;
|
||||
|
||||
vec3 working0(ivec2 p) {
|
||||
// gain = lscGain(levelCentre(p, 0)), for callers that also need it.
|
||||
vec3 working0Gain(ivec2 p, vec3 gain) {
|
||||
vec3 rgb = texelFetch(uInput, p, 0).rgb;
|
||||
return uScale * yccFromRgb(uWb * (rgb / lscGain(levelCentre(p, 0))));
|
||||
return uScale * yccFromRgb(uWb * (rgb / gain));
|
||||
}
|
||||
|
||||
vec3 working0(ivec2 p) { return working0Gain(p, lscGain(levelCentre(p, 0))); }
|
||||
"""
|
||||
|
||||
/** ↑2 of a coarse level at a fine pixel (uCoarseSize is the coarse level's size). */
|
||||
@@ -161,7 +164,8 @@ internal object PhotonDenoiseShaders {
|
||||
uniform float uKappaChroma[4];
|
||||
|
||||
// (σ²_Y, σ²_Cb, σ²_Cr, σ_CbCr) at level pixel p; mu receives the camera signal.
|
||||
vec4 modelNoise(ivec2 p, vec3 base, out vec3 mu) {
|
||||
// gain = lscGain(levelCentre(p, uLevel)).
|
||||
vec4 modelNoiseGain(ivec2 p, vec3 base, vec3 gain, out vec3 mu) {
|
||||
mu = max(rgbFromYcc(base) / uScale / uWb, vec3(0.0));
|
||||
vec2 merge = mergeRatio(levelCentre(p, uLevel));
|
||||
vec3 v = merge.x * uRead + merge.y * uShot * mu;
|
||||
@@ -178,10 +182,14 @@ internal object PhotonDenoiseShaders {
|
||||
kc * dot(aCb * aCb, v) * t.y * t.y,
|
||||
kc * dot(aCr * aCr, v) * t.z * t.z,
|
||||
kc * dot(aCb * aCr, v) * t.y * t.z);
|
||||
vec3 camera = mu * lscGain(levelCentre(p, uLevel));
|
||||
vec3 camera = mu * gain;
|
||||
if (any(greaterThanEqual(camera, vec3(CLIP_LEVEL)))) noise = vec4(0.0);
|
||||
return noise;
|
||||
}
|
||||
|
||||
vec4 modelNoise(ivec2 p, vec3 base, out vec3 mu) {
|
||||
return modelNoiseGain(p, base, lscGain(levelCentre(p, uLevel)), mu);
|
||||
}
|
||||
"""
|
||||
|
||||
/** Analyze: G_{l+1} = ↓2(h * G_l), luma taps on Y and chroma taps on Cb/Cr. */
|
||||
@@ -221,8 +229,9 @@ internal object PhotonDenoiseShaders {
|
||||
*
|
||||
* 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 image coordinate and every neighbourhood is mirrored first,
|
||||
* exactly as in the unfused reference, so border pixels see the same values. L, base and pilot
|
||||
* 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.
|
||||
*
|
||||
@@ -524,6 +533,32 @@ internal object PhotonDenoiseShaders {
|
||||
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; }
|
||||
@@ -541,30 +576,35 @@ internal object PhotonDenoiseShaders {
|
||||
return s0 + f * (s1 - s0);
|
||||
}
|
||||
|
||||
// Band at image pixel p: L = G_l − ↑G_{l+1}, base = ↑G̃_{l+1}, noise = §2.1 × §5.1.
|
||||
void computeBand(ivec2 p) {
|
||||
vec3 fine = uFineIsInput == 1 ? working0(p) : texelFetch(uFine, p, 0).rgb;
|
||||
vec3 base = upAt(uDenoisedCoarse, p);
|
||||
vec3 lap = fine - upAt(uNoisyCoarse, p);
|
||||
// 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;
|
||||
vec3 base = upCached(1, p);
|
||||
vec3 lap = fine - upCached(0, p);
|
||||
vec3 mu;
|
||||
vec3 s = strengthAt(base.x);
|
||||
vec4 noise = modelNoise(p, base, mu) * vec4(s, sqrt(s.y * s.z));
|
||||
int index = bandIndex(p);
|
||||
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(mirror2(p, uSize))];
|
||||
uvec3 u = sLapBase[bandIndex(p)];
|
||||
return vec3(unpackHalf2x16(u.x), unpackHalf2x16(u.y).x);
|
||||
}
|
||||
vec3 baseAt(ivec2 p) {
|
||||
uvec3 u = sLapBase[bandIndex(mirror2(p, uSize))];
|
||||
uvec3 u = sLapBase[bandIndex(p)];
|
||||
return vec3(unpackHalf2x16(u.y).y, unpackHalf2x16(u.z));
|
||||
}
|
||||
vec4 noiseAt(ivec2 p) { return sNoise[bandIndex(mirror2(p, uSize))]; }
|
||||
vec4 noiseAt(ivec2 p) { return sNoise[bandIndex(p)]; }
|
||||
vec4 pilotAt(ivec2 p) {
|
||||
uvec2 u = sPilot[pilotIndex(mirror2(p, uSize))];
|
||||
uvec2 u = sPilot[pilotIndex(p)];
|
||||
return vec4(unpackHalf2x16(u.x), unpackHalf2x16(u.y));
|
||||
}
|
||||
|
||||
@@ -703,19 +743,29 @@ internal object PhotonDenoiseShaders {
|
||||
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);
|
||||
if (all(greaterThanEqual(c, ivec2(0))) && all(lessThan(c, uSize))) computeBand(c);
|
||||
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);
|
||||
if (all(greaterThanEqual(c, ivec2(0))) && all(lessThan(c, uSize))) {
|
||||
vec4 pilot = computePilot(c);
|
||||
sPilot[pilotIndex(c)] = uvec2(packHalf2x16(pilot.xy), packHalf2x16(pilot.zw));
|
||||
}
|
||||
vec4 pilot = computePilot(mirror2(c, uSize));
|
||||
sPilot[pilotIndex(c)] = uvec2(packHalf2x16(pilot.xy), packHalf2x16(pilot.zw));
|
||||
}
|
||||
}
|
||||
memoryBarrierShared();
|
||||
|
||||
@@ -0,0 +1,99 @@
|
||||
package com.hinnka.mycamera.raw.denoise
|
||||
|
||||
import android.opengl.GLES30
|
||||
import com.hinnka.mycamera.processor.RawStackRuntimeDebug
|
||||
import com.hinnka.mycamera.utils.PLog
|
||||
import com.hinnka.mycamera.utils.SystemPropertiesUtil
|
||||
import java.util.Locale
|
||||
|
||||
/**
|
||||
* Per-pass timing of one [PhotonMultiScaleDenoiser.denoise] call, selected through
|
||||
* debug.photon.denoise.timing (debug builds only):
|
||||
* - `true`: submit time and GPU time of every pass;
|
||||
* - `ablation`: additionally re-runs each synthesis level into a scratch image with luma, chroma
|
||||
* and the chroma bilateral toggled, so the fused dispatch's cost splits into its parts; the
|
||||
* fastest of the repeated rounds is reported.
|
||||
*
|
||||
* GPU time is the wall time from submission to glFinish with the queue drained beforehand:
|
||||
* GL_EXT_disjoint_timer_query reports ~0 for compute dispatches on some drivers, so it cannot
|
||||
* time this pipeline. Enabling timing therefore serializes the denoise pass by pass.
|
||||
*/
|
||||
internal class PhotonDenoiseTiming(width: Int, height: Int, params: PhotonDenoiseParams) {
|
||||
private class Sample(val stage: String, val detail: String, val cpuNs: Long, val gpuNs: Long)
|
||||
|
||||
private val mode = if (RawStackRuntimeDebug.enabled) SystemPropertiesUtil.get("debug.photon.denoise.timing") else null
|
||||
val enabled = mode == "true" || mode == "ablation"
|
||||
val ablation = mode == "ablation"
|
||||
private val samples = ArrayList<Sample>()
|
||||
private val startNs = System.nanoTime()
|
||||
private val description = if (enabled) {
|
||||
"${width}x$height levels=${params.levels} lumaLevels=${params.lumaLevels} " +
|
||||
"luma=${params.lumaStrength} chroma=${params.chromaStrength} bilateralLevels=${params.bilateralLevels} " +
|
||||
"fixedStrength=${params.strengthTable != null} lsc=${params.lensShading != null} " +
|
||||
"merge=${params.mergeMapWidth}x${params.mergeMapHeight}"
|
||||
} else ""
|
||||
|
||||
init {
|
||||
if (enabled) {
|
||||
// The caller's queued work is not part of the denoise.
|
||||
val drainStart = System.nanoTime()
|
||||
GLES30.glFinish()
|
||||
PLog.i(TAG, "begin $description gpu=${GLES30.glGetString(GLES30.GL_RENDERER)} " +
|
||||
"callerBacklogMs=${ms(System.nanoTime() - drainStart)}")
|
||||
}
|
||||
}
|
||||
|
||||
/** GL work submitted by [block]; its GPU time is measured up to a glFinish. */
|
||||
fun <T> gpu(stage: String, detail: String = "", block: () -> T): T {
|
||||
if (!enabled) return block()
|
||||
val start = System.nanoTime()
|
||||
val result = block()
|
||||
val submitted = System.nanoTime()
|
||||
GLES30.glFinish()
|
||||
samples += Sample(stage, detail, submitted - start, System.nanoTime() - start)
|
||||
return result
|
||||
}
|
||||
|
||||
/** CPU-only scope, e.g. a buffer map. */
|
||||
fun <T> cpu(stage: String, detail: String = "", block: () -> T): T {
|
||||
if (!enabled) return block()
|
||||
val start = System.nanoTime()
|
||||
val result = block()
|
||||
samples += Sample(stage, detail, System.nanoTime() - start, -1)
|
||||
return result
|
||||
}
|
||||
|
||||
fun report() {
|
||||
if (!enabled) return
|
||||
for (sample in samples) {
|
||||
PLog.i(TAG, "pass ${sample.stage} ${sample.detail} submitMs=${ms(sample.cpuNs)} " +
|
||||
"gpuMs=${if (sample.gpuNs >= 0) ms(sample.gpuNs) else "NA"}")
|
||||
}
|
||||
val pipeline = samples.filterNot { it.stage.startsWith(ABLATION) }
|
||||
val pipelineNs = pipeline.sumOf { if (it.gpuNs >= 0) it.gpuNs else it.cpuNs }
|
||||
for ((stage, group) in pipeline.groupBy { it.stage }) {
|
||||
val ns = group.sumOf { if (it.gpuNs >= 0) it.gpuNs else it.cpuNs }
|
||||
PLog.i(TAG, "stage $stage calls=${group.size} ms=${ms(ns)} " +
|
||||
"share=${String.format(Locale.US, "%.1f%%", 100.0 * ns / maxOf(pipelineNs, 1L))}")
|
||||
}
|
||||
samples.filter { it.stage.startsWith(ABLATION) }.groupBy { it.detail }.forEach { (level, group) ->
|
||||
// Fastest of the repeated rounds per variant.
|
||||
val byStage = group.groupBy { it.stage.removePrefix(ABLATION) }.mapValues { (_, runs) -> runs.minOf { it.gpuNs } }
|
||||
val none = byStage["none"] ?: return@forEach
|
||||
fun delta(part: String, reference: Long) = byStage[part]?.let { ms(it - reference) } ?: "NA"
|
||||
PLog.i(TAG, "ablation $level fullMs=${byStage["full"]?.let(::ms) ?: "NA"} bandOnlyMs=${ms(none)} " +
|
||||
"lumaMs=+${delta("luma", none)} chromaGateMs=+${delta("chroma", none)} " +
|
||||
"bilateralMs=+${byStage["chroma"]?.let { delta("bilateral", it) } ?: "NA"}")
|
||||
}
|
||||
PLog.i(TAG, "end $description pipelineMs=${ms(pipelineNs)} wallMs=${ms(System.nanoTime() - startNs)} " +
|
||||
"passes=${pipeline.size}" + if (ablation) " (wallMs includes ablation passes)" else "")
|
||||
samples.clear()
|
||||
}
|
||||
|
||||
private fun ms(ns: Long): String = String.format(Locale.US, "%.3f", ns / 1_000_000.0)
|
||||
|
||||
companion object {
|
||||
const val ABLATION = "ablation."
|
||||
private const val TAG = "PhotonDenoiseTiming"
|
||||
}
|
||||
}
|
||||
@@ -74,13 +74,18 @@ internal class PhotonMultiScaleDenoiser {
|
||||
sink: PassSink? = null,
|
||||
): Int? {
|
||||
if (!initialize(debug = sink != null)) return null
|
||||
val timing = PhotonDenoiseTiming(width, height, params)
|
||||
val sizes = ArrayList<IntArray>(params.levels + 1)
|
||||
sizes += intArrayOf(width, height)
|
||||
repeat(params.levels) { val s = sizes.last(); sizes += intArrayOf((s[0] + 1) / 2, (s[1] + 1) / 2) }
|
||||
val owned = ArrayList<Int>()
|
||||
fun texture(size: IntArray, format: Int) = createTexture(size[0], size[1], format).also(owned::add)
|
||||
val lscTexture = params.lensShading?.let { createLscTexture(it).also(owned::add) } ?: 0
|
||||
val mergeTexture = createMergeTexture(params).also(owned::add)
|
||||
val lscTexture = timing.gpu("upload.lsc") {
|
||||
params.lensShading?.let { createLscTexture(it).also(owned::add) } ?: 0
|
||||
}
|
||||
val mergeTexture = timing.gpu("upload.merge", "${params.mergeMapWidth}x${params.mergeMapHeight}") {
|
||||
createMergeTexture(params).also(owned::add)
|
||||
}
|
||||
val output = createTexture(width, height, GLES30.GL_RGBA16F)
|
||||
val buffers = IntArray(2)
|
||||
GLES31.glGenBuffers(2, buffers, 0)
|
||||
@@ -90,15 +95,17 @@ internal class PhotonMultiScaleDenoiser {
|
||||
val gaussians = IntArray(params.levels + 1)
|
||||
for (level in 0 until params.levels) {
|
||||
val coarse = sizes[level + 1]
|
||||
gaussians[level + 1] = texture(coarse, GLES30.GL_RGBA16F)
|
||||
GLES31.glUseProgram(analyzeProgram)
|
||||
bindCommon(analyzeProgram, inputTexture, lscTexture, params)
|
||||
bindSampler(analyzeProgram, "uFine", UNIT_FINE, if (level == 0) inputTexture else gaussians[level])
|
||||
uniform1i(analyzeProgram, "uFineIsInput", if (level == 0) 1 else 0)
|
||||
uniform2i(analyzeProgram, "uFineSize", sizes[level])
|
||||
uniform2i(analyzeProgram, "uCoarseSize", coarse)
|
||||
bindImage(0, gaussians[level + 1], GLES30.GL_RGBA16F)
|
||||
dispatch(analyzeProgram, coarse)
|
||||
timing.gpu("analyze", "G${level + 1} ${coarse[0]}x${coarse[1]}") {
|
||||
gaussians[level + 1] = texture(coarse, GLES30.GL_RGBA16F)
|
||||
GLES31.glUseProgram(analyzeProgram)
|
||||
bindCommon(analyzeProgram, inputTexture, lscTexture, params)
|
||||
bindSampler(analyzeProgram, "uFine", UNIT_FINE, if (level == 0) inputTexture else gaussians[level])
|
||||
uniform1i(analyzeProgram, "uFineIsInput", if (level == 0) 1 else 0)
|
||||
uniform2i(analyzeProgram, "uFineSize", sizes[level])
|
||||
uniform2i(analyzeProgram, "uCoarseSize", coarse)
|
||||
bindImage(0, gaussians[level + 1], GLES30.GL_RGBA16F)
|
||||
dispatch(analyzeProgram, coarse)
|
||||
}
|
||||
GlesGpuScheduler.yieldToUiRenderer()
|
||||
sink?.onPass("G${level + 1}", gaussians[level + 1], coarse[0], coarse[1], false)
|
||||
}
|
||||
@@ -107,13 +114,14 @@ internal class PhotonMultiScaleDenoiser {
|
||||
val fixedTable = params.strengthTable
|
||||
if (fixedTable != null) {
|
||||
require(fixedTable.size == tableSize) { "Strength table has ${fixedTable.size} values, expected $tableSize" }
|
||||
uploadBuffer(strengthBuffer, floatBuffer(fixedTable))
|
||||
timing.gpu("strength.upload") { uploadBuffer(strengthBuffer, floatBuffer(fixedTable)) }
|
||||
} else {
|
||||
estimateStrength(inputTexture, lscTexture, mergeTexture, gaussians, sizes, params,
|
||||
histogramBuffer, strengthBuffer)
|
||||
histogramBuffer, strengthBuffer, timing)
|
||||
}
|
||||
if (strengthOut != null || sink != null) {
|
||||
val table = readStrength(strengthBuffer, tableSize)
|
||||
// Mapping waits for the estimate: the CPU time here is the GPU backlog it drains.
|
||||
val table = timing.cpu("strength.readback") { readStrength(strengthBuffer, tableSize) }
|
||||
strengthOut?.let { table.copyInto(it, 0, 0, minOf(it.size, tableSize)) }
|
||||
sink?.onStrength(table)
|
||||
}
|
||||
@@ -123,6 +131,8 @@ internal class PhotonMultiScaleDenoiser {
|
||||
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.
|
||||
@@ -130,14 +140,16 @@ internal class PhotonMultiScaleDenoiser {
|
||||
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
|
||||
GLES31.glUseProgram(synthesizeDebugProgram)
|
||||
bindSynthesize(synthesizeDebugProgram, inputTexture, lscTexture, mergeTexture, gaussians,
|
||||
denoisedCoarse, sizes, level, lumaEnabled, 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)
|
||||
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)
|
||||
@@ -149,13 +161,20 @@ internal class PhotonMultiScaleDenoiser {
|
||||
}
|
||||
|
||||
val result = if (level == 0) output else texture(size, GLES30.GL_RGBA16F)
|
||||
GLES31.glUseProgram(synthesizeProgram)
|
||||
bindSynthesize(synthesizeProgram, inputTexture, lscTexture, mergeTexture, gaussians,
|
||||
denoisedCoarse, sizes, level, lumaEnabled, params)
|
||||
bindImage(0, result, GLES30.GL_RGBA16F)
|
||||
dispatch(synthesizeProgram, size)
|
||||
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)
|
||||
dispatch(synthesizeProgram, size)
|
||||
}
|
||||
GlesGpuScheduler.yieldToUiRenderer()
|
||||
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 (denoisedCoarse != gaussians[params.levels]) {
|
||||
GLES30.glDeleteTextures(1, intArrayOf(denoisedCoarse), 0)
|
||||
@@ -164,6 +183,7 @@ internal class PhotonMultiScaleDenoiser {
|
||||
denoisedCoarse = result
|
||||
}
|
||||
RawGlesProgram.logErrors("PhotonMultiScaleDenoiser")
|
||||
timing.report()
|
||||
return output
|
||||
} catch (error: Throwable) {
|
||||
GLES30.glDeleteTextures(1, intArrayOf(output), 0)
|
||||
@@ -177,6 +197,54 @@ 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.
|
||||
*/
|
||||
private fun synthesizeAblation(
|
||||
timing: PhotonDenoiseTiming,
|
||||
inputTexture: Int,
|
||||
lscTexture: Int,
|
||||
mergeTexture: Int,
|
||||
gaussians: IntArray,
|
||||
denoisedCoarse: Int,
|
||||
sizes: List<IntArray>,
|
||||
level: Int,
|
||||
lumaEnabled: Boolean,
|
||||
chromaEnabled: Boolean,
|
||||
bilateralEnabled: Boolean,
|
||||
params: PhotonDenoiseParams,
|
||||
) {
|
||||
val size = sizes[level]
|
||||
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)
|
||||
dispatch(synthesizeProgram, size)
|
||||
}
|
||||
GlesGpuScheduler.yieldToUiRenderer()
|
||||
}
|
||||
}
|
||||
} finally {
|
||||
GLES30.glDeleteTextures(1, intArrayOf(scratch), 0)
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* §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
|
||||
@@ -191,6 +259,7 @@ internal class PhotonMultiScaleDenoiser {
|
||||
params: PhotonDenoiseParams,
|
||||
histogramBuffer: Int,
|
||||
strengthBuffer: Int,
|
||||
timing: PhotonDenoiseTiming,
|
||||
) {
|
||||
val entries = PhotonDenoiseShaders.STRENGTH_BINS * 3 * PhotonDenoiseShaders.HIST_BUCKETS
|
||||
val zeros = ByteBuffer.allocateDirect(params.levels * entries * Int.SIZE_BYTES).order(ByteOrder.nativeOrder())
|
||||
@@ -201,11 +270,11 @@ internal class PhotonMultiScaleDenoiser {
|
||||
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.
|
||||
uploadBuffer(histogramBuffer, 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) {
|
||||
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])
|
||||
@@ -226,14 +295,16 @@ internal class PhotonMultiScaleDenoiser {
|
||||
}
|
||||
GLES31.glMemoryBarrier(GLES31.GL_SHADER_STORAGE_BARRIER_BIT)
|
||||
|
||||
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)
|
||||
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()
|
||||
}
|
||||
GLES31.glBindBufferBase(GLES31.GL_SHADER_STORAGE_BUFFER, 1, 0)
|
||||
@@ -302,6 +373,8 @@ internal class PhotonMultiScaleDenoiser {
|
||||
sizes: List<IntArray>,
|
||||
level: Int,
|
||||
lumaEnabled: Boolean,
|
||||
chromaEnabled: Boolean,
|
||||
bilateralEnabled: Boolean,
|
||||
params: PhotonDenoiseParams,
|
||||
) {
|
||||
bindCommon(program, inputTexture, lscTexture, params)
|
||||
@@ -316,7 +389,6 @@ internal class PhotonMultiScaleDenoiser {
|
||||
uniform1f(program, "uAlpha", params.lumaAlpha(level))
|
||||
uniform1i(program, "uLumaEnabled", if (lumaEnabled) 1 else 0)
|
||||
uniform1f(program, "uGrain", params.lumaGrain(level))
|
||||
val chromaEnabled = params.chromaStrength > 0f
|
||||
uniform1i(program, "uChromaEnabled", if (chromaEnabled) 1 else 0)
|
||||
uniform1f(program, "uChromaStrength", minOf(params.chromaStrength, 1f))
|
||||
val thresholdScale = params.chromaThresholdScale()
|
||||
@@ -324,7 +396,7 @@ internal class PhotonMultiScaleDenoiser {
|
||||
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 (chromaEnabled && level >= params.levels - params.bilateralLevels) 1 else 0)
|
||||
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)
|
||||
@@ -400,7 +472,10 @@ 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 UNIT_INPUT = 0
|
||||
const val UNIT_LSC = 1
|
||||
const val UNIT_FINE = 2
|
||||
|
||||
@@ -24,6 +24,7 @@
|
||||
| `imageStore` 可见性 | 跨驱动约束 | barrier 必须覆盖下一位 consumer,而非只覆盖 producer |
|
||||
| CPU/GPU Float 除法 | 已确认,Adreno;跨驱动精度约束 | CPU 算法迁到 GPU 时不能假定 `/` 与 JVM Float 逐位一致 |
|
||||
| 后台 compute 调度 | 已确认,Mali | 以资源 RAW/WAR/WAW 冲突和 fence 管理并发,不以队列长度代替所有权 |
|
||||
| `GL_EXT_disjoint_timer_query` 计时 compute | 已确认,Adreno 840 | `GL_TIME_ELAPSED` 包住 `glDispatchCompute` 读数约为 0(非 disjoint);compute 耗时用排空队列后的 `glFinish` 墙钟测,仅限调试 |
|
||||
| IMG/PowerVR `imageSize` | 研究线索,项目未复现 | 只做对照验证,复现前不建立全局兼容分支 |
|
||||
|
||||
## 全局基线
|
||||
|
||||
Reference in new issue
Block a user