perf: optimize sub-pixel refinement and GPU accumulation
This commit is contained in:
1 parent
bfc6163212
commit
afd9cba756
4 files changed
+522
-167
No files matched your search
@@ -85,75 +85,6 @@ vec3 rgb2ycbcr(vec3 rgb) {
|
||||
return vec3(Y, Cb, Cr);
|
||||
}
|
||||
|
||||
float sampleLumaAt(sampler2D s, vec2 uv, vec2 size, bool highQuality) {
|
||||
vec3 rgb = highQuality ? sampleBicubic(s, uv, size).rgb : texture(s, uv).rgb;
|
||||
return rgb2ycbcr(rgb).x;
|
||||
}
|
||||
|
||||
float computeGuidedProtectMask(sampler2D s, vec2 uv, vec2 size) {
|
||||
vec2 pixel = vec2(1.0) / size;
|
||||
|
||||
float sum = 0.0;
|
||||
float sumSq = 0.0;
|
||||
float sumWeighted = 0.0;
|
||||
float weightTotal = 0.0;
|
||||
float luma[9];
|
||||
int idx = 0;
|
||||
|
||||
for (int j = -1; j <= 1; ++j) {
|
||||
for (int i = -1; i <= 1; ++i) {
|
||||
vec2 sampleUV = uv + vec2(float(i) * pixel.x, float(j) * pixel.y);
|
||||
float y = sampleLumaAt(s, sampleUV, size, i == 0 && j == 0);
|
||||
float w = (i == 0 && j == 0) ? 4.0 : ((i == 0 || j == 0) ? 2.0 : 1.0);
|
||||
luma[idx++] = y;
|
||||
sum += y;
|
||||
sumSq += y * y;
|
||||
sumWeighted += y * w;
|
||||
weightTotal += w;
|
||||
}
|
||||
}
|
||||
|
||||
float mean = sum / 9.0;
|
||||
float var = max(sumSq / 9.0 - mean * mean, 0.0);
|
||||
float center = luma[4];
|
||||
|
||||
float eps = 0.0015;
|
||||
float a = var / (var + eps);
|
||||
float b = (1.0 - a) * mean;
|
||||
float guidedBase = a * center + b;
|
||||
|
||||
float weightedMean = sumWeighted / weightTotal;
|
||||
guidedBase = mix(weightedMean, guidedBase, 0.75);
|
||||
|
||||
float detailResidual = abs(center - guidedBase);
|
||||
|
||||
float l = luma[3];
|
||||
float r = luma[5];
|
||||
float u = luma[1];
|
||||
float d = luma[7];
|
||||
float gx = abs(r - l);
|
||||
float gy = abs(d - u);
|
||||
float gradPeak = max(gx, gy);
|
||||
float directional = max(gx, gy) / max(gx + gy, 1e-4);
|
||||
|
||||
float continuityH = 0.5 * (abs(luma[0] - luma[1]) + abs(luma[7] - luma[8]));
|
||||
float continuityV = 0.5 * (abs(luma[0] - luma[3]) + abs(luma[2] - luma[5]));
|
||||
float continuity = (gx >= gy) ? continuityH : continuityV;
|
||||
|
||||
float residualScore = smoothstep(0.008, 0.040, detailResidual);
|
||||
float varianceScore = smoothstep(0.0008, 0.010, var);
|
||||
float continuityScore = smoothstep(0.008, 0.035, continuity);
|
||||
float directionalScore = smoothstep(0.54, 0.90, directional);
|
||||
float noisePenalty = 1.0 - smoothstep(0.002, 0.018,
|
||||
max(0.0, gradPeak - detailResidual * 3.0));
|
||||
|
||||
float protect = residualScore * mix(0.58, 1.0, continuityScore);
|
||||
protect *= mix(0.60, 1.0, varianceScore);
|
||||
protect *= mix(0.74, 1.0, directionalScore);
|
||||
protect *= mix(1.0, 0.55, noisePenalty);
|
||||
return clamp(protect, 0.0, 1.0);
|
||||
}
|
||||
|
||||
float sampleLocalTileWeight(vec2 uv) {
|
||||
vec2 gridPos = uv * vec2(float(pc.gridW), float(pc.gridH));
|
||||
ivec2 g = ivec2(floor(gridPos));
|
||||
@@ -229,15 +160,19 @@ void main() {
|
||||
// [REPLACED BY PREVIOUS DEFINITION AT TOP]
|
||||
|
||||
// 1. Read reference accumulator state (used for both center robustness and per-sample checks)
|
||||
float currentW = accumulator.data[outIndex].a;
|
||||
vec4 accumValue = accumulator.data[outIndex];
|
||||
float currentW = accumValue.a;
|
||||
float refLuma = 0.0;
|
||||
float expectedSigma = 0.025;
|
||||
float centerRobustness = 1.0;
|
||||
|
||||
vec3 centerColor = vec3(0.0);
|
||||
vec3 centerYCC = vec3(0.0);
|
||||
|
||||
if (pc.isFirstFrame == 0 && currentW > 0.001) {
|
||||
refLuma = accumulator.data[outIndex].r / currentW;
|
||||
vec3 centerColor = sampleBicubic(rgbSampler, finalUV, nativeSize).rgb;
|
||||
vec3 centerYCC = rgb2ycbcr(centerColor);
|
||||
centerColor = sampleBicubic(rgbSampler, finalUV, nativeSize).rgb;
|
||||
centerYCC = rgb2ycbcr(centerColor);
|
||||
float diff = abs(centerYCC.x - refLuma);
|
||||
float expectedVar = pc.noiseAlpha * refLuma + pc.noiseBeta;
|
||||
expectedSigma = sqrt(max(expectedVar, 1e-7));
|
||||
@@ -257,7 +192,6 @@ void main() {
|
||||
}
|
||||
float localTileWeight = sampleLocalTileWeight(finalUV);
|
||||
float fusionMask = localTileWeight;
|
||||
float fineDetailMask = computeGuidedProtectMask(rgbSampler, finalUV, nativeSize);
|
||||
int supportRadius = 0;
|
||||
|
||||
if (pc.isFirstFrame == 0) {
|
||||
@@ -285,6 +219,8 @@ void main() {
|
||||
float kernelScale = 0.25 * pc.scale * pc.scale;
|
||||
float invVarU = kp.x * kernelScale;
|
||||
float invVarV = kp.y * kernelScale;
|
||||
float baseWeightScale = pc.frameWeight * fusionMask;
|
||||
float robustnessFloor = 0.25 * localTileWeight;
|
||||
|
||||
// Accumulate neighbors
|
||||
for (int j = -2; j <= 2; ++j) {
|
||||
@@ -292,6 +228,25 @@ void main() {
|
||||
if (abs(i) > supportRadius || abs(j) > supportRadius) {
|
||||
continue;
|
||||
}
|
||||
vec2 d = (centerSource + vec2(float(i), float(j)) - posInSource);
|
||||
|
||||
// Compute the anisotropic kernel weight before sampling texture.
|
||||
// This lets us skip neighbors whose theoretical contribution is already negligible.
|
||||
float u = d.x * cosT + d.y * sinT;
|
||||
float v = -d.x * sinT + d.y * cosT;
|
||||
float w = exp(-0.5 * (u*u * invVarU + v*v * invVarV));
|
||||
if (w <= 1e-4) {
|
||||
continue;
|
||||
}
|
||||
|
||||
float baseCombinedUpperBound = w * baseWeightScale;
|
||||
if (pc.isFirstFrame == 0) {
|
||||
baseCombinedUpperBound *= max(centerRobustness, robustnessFloor);
|
||||
}
|
||||
if (baseCombinedUpperBound <= 1e-6) {
|
||||
continue;
|
||||
}
|
||||
|
||||
vec2 samplePos = centerSource + vec2(float(i), float(j));
|
||||
vec2 sampleUV = samplePos / nativeSize;
|
||||
|
||||
@@ -299,21 +254,19 @@ void main() {
|
||||
// neighbors use hardware bilinear (1 texture() vs 16 texelFetch())
|
||||
vec3 sampleColor;
|
||||
if (i == 0 && j == 0) {
|
||||
sampleColor = sampleBicubic(rgbSampler, sampleUV, nativeSize).rgb;
|
||||
if (pc.isFirstFrame == 0 && currentW > 0.001) {
|
||||
sampleColor = centerColor;
|
||||
} else {
|
||||
sampleColor = sampleBicubic(rgbSampler, sampleUV, nativeSize).rgb;
|
||||
}
|
||||
} else {
|
||||
sampleColor = texture(rgbSampler, sampleUV).rgb;
|
||||
}
|
||||
vec3 sampleYCC = rgb2ycbcr(sampleColor);
|
||||
vec2 d = (samplePos - posInSource);
|
||||
|
||||
// Per-sample robustness
|
||||
float robustness = centerRobustness;
|
||||
|
||||
// Anisotropic Gaussian weight using pre-computed rotation and inv variance
|
||||
float u = d.x * cosT + d.y * sinT;
|
||||
float v = -d.x * sinT + d.y * cosT;
|
||||
float w = exp(-0.5 * (u*u * invVarU + v*v * invVarV));
|
||||
|
||||
float sampleFusionMask = fusionMask;
|
||||
if (pc.isFirstFrame == 0) {
|
||||
float sampleLumaDiff = abs(sampleYCC.x - refLuma);
|
||||
@@ -322,7 +275,7 @@ void main() {
|
||||
float largeLumaPenalty = smoothstep(5.5, 9.5, lumaDiffRatio);
|
||||
sampleFusionMask *= mix(1.0, 0.70, largeLumaPenalty);
|
||||
robustness *= sampleLumaRobustness;
|
||||
robustness = max(robustness, 0.25 * localTileWeight);
|
||||
robustness = max(robustness, robustnessFloor);
|
||||
}
|
||||
|
||||
float combinedWeight = w * robustness * pc.frameWeight * sampleFusionMask;
|
||||
@@ -337,8 +290,9 @@ void main() {
|
||||
combinedWeight
|
||||
);
|
||||
if (!any(isnan(increment)) && !any(isinf(increment))) {
|
||||
accumulator.data[outIndex] += increment;
|
||||
accumValue += increment;
|
||||
}
|
||||
}
|
||||
}
|
||||
accumulator.data[outIndex] = accumValue;
|
||||
}
|
||||
@@ -22,10 +22,46 @@ inline float getPixelF(const GrayImage &img, int x, int y) {
|
||||
return (float)img.data[y * img.width + x];
|
||||
}
|
||||
|
||||
inline float sampleBilinearGrayFast(const GrayImage &img, float x, float y) {
|
||||
int x0 = (int)std::floor(x);
|
||||
int y0 = (int)std::floor(y);
|
||||
float fx = x - x0;
|
||||
float fy = y - y0;
|
||||
|
||||
const uint8_t *row0 = &img.data[y0 * img.width];
|
||||
const uint8_t *row1 = row0 + img.width;
|
||||
float v00 = (float)row0[x0];
|
||||
float v10 = (float)row0[x0 + 1];
|
||||
float v01 = (float)row1[x0];
|
||||
float v11 = (float)row1[x0 + 1];
|
||||
|
||||
return (1.0f - fx) * (1.0f - fy) * v00 + fx * (1.0f - fy) * v10 +
|
||||
(1.0f - fx) * fy * v01 + fx * fy * v11;
|
||||
}
|
||||
|
||||
inline float sampleBilinearGrayFastConstFrac(const GrayImage &img, int x0,
|
||||
int y0, float fx, float fy) {
|
||||
const uint8_t *row0 = &img.data[(size_t)y0 * img.width];
|
||||
const uint8_t *row1 = row0 + img.width;
|
||||
float v00 = (float)row0[x0];
|
||||
float v10 = (float)row0[x0 + 1];
|
||||
float v01 = (float)row1[x0];
|
||||
float v11 = (float)row1[x0 + 1];
|
||||
|
||||
float w00 = (1.0f - fx) * (1.0f - fy);
|
||||
float w10 = fx * (1.0f - fy);
|
||||
float w01 = (1.0f - fx) * fy;
|
||||
float w11 = fx * fy;
|
||||
return w00 * v00 + w10 * v10 + w01 * v01 + w11 * v11;
|
||||
}
|
||||
|
||||
// Bilinear interpolation on grayscale image for LK optical flow
|
||||
inline float sampleBilinearGray(const GrayImage &img, float x, float y) {
|
||||
int x0 = (int)std::floor(x);
|
||||
int y0 = (int)std::floor(y);
|
||||
if (x0 >= 0 && x0 + 1 < img.width && y0 >= 0 && y0 + 1 < img.height) {
|
||||
return sampleBilinearGrayFast(img, x, y);
|
||||
}
|
||||
float fx = x - x0;
|
||||
float fy = y - y0;
|
||||
|
||||
@@ -124,6 +160,101 @@ inline float computeLocalVariance(const std::vector<uint16_t> &data, int width,
|
||||
return variance;
|
||||
}
|
||||
|
||||
struct ReferenceLkTileCache {
|
||||
int startX = 0;
|
||||
int endX = 0;
|
||||
int startY = 0;
|
||||
int endY = 0;
|
||||
int pointCount = 0;
|
||||
float sumIxIx = 0.0f;
|
||||
float sumIyIy = 0.0f;
|
||||
float sumIxIy = 0.0f;
|
||||
float det = 0.0f;
|
||||
};
|
||||
|
||||
struct ReferenceLkCache {
|
||||
const uint8_t *refDataPtr = nullptr;
|
||||
int width = 0;
|
||||
int height = 0;
|
||||
int tileSize = 0;
|
||||
int gridW = 0;
|
||||
int gridH = 0;
|
||||
int lkHalfWin = 0;
|
||||
std::vector<float> gradX;
|
||||
std::vector<float> gradY;
|
||||
std::vector<ReferenceLkTileCache> tiles;
|
||||
};
|
||||
|
||||
ReferenceLkCache &getReferenceLkCache(const GrayImage &refL0, int tileSize,
|
||||
int gridW, int gridH, int lkHalfWin) {
|
||||
static ReferenceLkCache cache;
|
||||
const uint8_t *refPtr = refL0.data.empty() ? nullptr : refL0.data.data();
|
||||
bool needsRebuild = cache.refDataPtr != refPtr || cache.width != refL0.width ||
|
||||
cache.height != refL0.height ||
|
||||
cache.tileSize != tileSize || cache.gridW != gridW ||
|
||||
cache.gridH != gridH || cache.lkHalfWin != lkHalfWin;
|
||||
if (!needsRebuild) {
|
||||
return cache;
|
||||
}
|
||||
|
||||
cache = {};
|
||||
cache.refDataPtr = refPtr;
|
||||
cache.width = refL0.width;
|
||||
cache.height = refL0.height;
|
||||
cache.tileSize = tileSize;
|
||||
cache.gridW = gridW;
|
||||
cache.gridH = gridH;
|
||||
cache.lkHalfWin = lkHalfWin;
|
||||
cache.gradX.assign((size_t)refL0.width * refL0.height, 0.0f);
|
||||
cache.gradY.assign((size_t)refL0.width * refL0.height, 0.0f);
|
||||
cache.tiles.resize((size_t)gridW * gridH);
|
||||
|
||||
#pragma omp parallel for num_threads(4)
|
||||
for (int y = 1; y < refL0.height - 1; ++y) {
|
||||
const uint8_t *row = &refL0.data[(size_t)y * refL0.width];
|
||||
const uint8_t *rowAbove = row - refL0.width;
|
||||
const uint8_t *rowBelow = row + refL0.width;
|
||||
float *gradXRow = &cache.gradX[(size_t)y * refL0.width];
|
||||
float *gradYRow = &cache.gradY[(size_t)y * refL0.width];
|
||||
for (int x = 1; x < refL0.width - 1; ++x) {
|
||||
gradXRow[x] = ((float)row[x + 1] - (float)row[x - 1]) * 0.5f;
|
||||
gradYRow[x] = ((float)rowBelow[x] - (float)rowAbove[x]) * 0.5f;
|
||||
}
|
||||
}
|
||||
|
||||
#pragma omp parallel for collapse(2) num_threads(4)
|
||||
for (int ty = 0; ty < gridH; ++ty) {
|
||||
for (int tx = 0; tx < gridW; ++tx) {
|
||||
int cx = tx * tileSize + tileSize / 2;
|
||||
int cy = ty * tileSize + tileSize / 2;
|
||||
|
||||
ReferenceLkTileCache tileCache;
|
||||
tileCache.startX = std::max(1, cx - lkHalfWin);
|
||||
tileCache.endX = std::min(refL0.width - 1, cx + lkHalfWin);
|
||||
tileCache.startY = std::max(1, cy - lkHalfWin);
|
||||
tileCache.endY = std::min(refL0.height - 1, cy + lkHalfWin);
|
||||
|
||||
for (int ry = tileCache.startY; ry < tileCache.endY; ++ry) {
|
||||
const float *gradXRow = &cache.gradX[(size_t)ry * refL0.width];
|
||||
const float *gradYRow = &cache.gradY[(size_t)ry * refL0.width];
|
||||
for (int rx = tileCache.startX; rx < tileCache.endX; ++rx) {
|
||||
float Ix = gradXRow[rx];
|
||||
float Iy = gradYRow[rx];
|
||||
tileCache.sumIxIx += Ix * Ix;
|
||||
tileCache.sumIyIy += Iy * Iy;
|
||||
tileCache.sumIxIy += Ix * Iy;
|
||||
tileCache.pointCount++;
|
||||
}
|
||||
}
|
||||
tileCache.det =
|
||||
tileCache.sumIxIx * tileCache.sumIyIy - tileCache.sumIxIy * tileCache.sumIxIy;
|
||||
cache.tiles[(size_t)ty * gridW + tx] = tileCache;
|
||||
}
|
||||
}
|
||||
|
||||
return cache;
|
||||
}
|
||||
|
||||
std::vector<GrayImage> buildPyramid(const uint8_t *src, int width, int height,
|
||||
int levels) {
|
||||
TIME_START(buildPyramid);
|
||||
@@ -292,7 +423,6 @@ TileAlignment computeTileAlignment(const std::vector<GrayImage> &refPyramid,
|
||||
Point globalOffset = {0, 0};
|
||||
int currentDx = 0;
|
||||
int currentDy = 0;
|
||||
|
||||
for (int i = refPyramid.size() - 1; i >= 1; --i) {
|
||||
currentDx *= 2;
|
||||
currentDy *= 2;
|
||||
@@ -321,6 +451,8 @@ TileAlignment computeTileAlignment(const std::vector<GrayImage> &refPyramid,
|
||||
// 2. Refine per tile at Level 1
|
||||
const GrayImage &refL1 = refPyramid[1];
|
||||
const GrayImage &tgtL1 = targetPyramid[1];
|
||||
const GrayImage &refL0 = refPyramid[0];
|
||||
const GrayImage &tgtL0 = targetPyramid[0];
|
||||
|
||||
// Grid step at L1 is tileSize/2 (16 pixels)
|
||||
int stepL1 = tileSize / 2;
|
||||
@@ -332,13 +464,25 @@ TileAlignment computeTileAlignment(const std::vector<GrayImage> &refPyramid,
|
||||
float gDxL1 = globalOffset.x; // Already at L1 scale from loop above
|
||||
float gDyL1 = globalOffset.y;
|
||||
|
||||
// Temporary buffer for raw vectors
|
||||
// Use a sparser control grid for small tiles, then interpolate back to the
|
||||
// dense output grid. This cuts the expensive LK solves by roughly 4x while
|
||||
// keeping a dense flow field for later fusion.
|
||||
int controlStrideTiles =
|
||||
(tileSize <= 16 && gridW >= 4 && gridH >= 4) ? 2 : 1;
|
||||
int controlGridW = (gridW + controlStrideTiles - 1) / controlStrideTiles;
|
||||
int controlGridH = (gridH + controlStrideTiles - 1) / controlStrideTiles;
|
||||
std::vector<Point> controlOffsets((size_t)controlGridW * controlGridH);
|
||||
std::vector<Point> rawOffsets(gridW * gridH);
|
||||
const int lkHalfWin = 12;
|
||||
const int lkMargin = lkHalfWin + 2;
|
||||
const ReferenceLkCache &referenceLkCache =
|
||||
getReferenceLkCache(refL0, tileSize, gridW, gridH, lkHalfWin);
|
||||
|
||||
#pragma omp parallel for collapse(2) num_threads(4)
|
||||
for (int ty = 0; ty < gridH; ++ty) {
|
||||
for (int tx = 0; tx < gridW; ++tx) {
|
||||
|
||||
for (int cty = 0; cty < controlGridH; ++cty) {
|
||||
for (int ctx = 0; ctx < controlGridW; ++ctx) {
|
||||
int tx = std::min(ctx * controlStrideTiles, gridW - 1);
|
||||
int ty = std::min(cty * controlStrideTiles, gridH - 1);
|
||||
int refX = tx * stepL1;
|
||||
int refY = ty * stepL1;
|
||||
|
||||
@@ -347,8 +491,6 @@ TileAlignment computeTileAlignment(const std::vector<GrayImage> &refPyramid,
|
||||
int baseDy = (int)std::round(gDyL1);
|
||||
int bestDx = baseDx;
|
||||
int bestDy = baseDy;
|
||||
float bestDx_f = 0.0f;
|
||||
float bestDy_f = 0.0f;
|
||||
|
||||
// Local search: Reduced range to 3x3 for performance
|
||||
for (int dy = -1; dy <= 1; ++dy) {
|
||||
@@ -384,71 +526,84 @@ TileAlignment computeTileAlignment(const std::vector<GrayImage> &refPyramid,
|
||||
|
||||
// 4. Lucas-Kanade refinement at L0 for sub-pixel accuracy
|
||||
// Scale L1 result to L0 as initial estimate
|
||||
const GrayImage &refL0 = refPyramid[0];
|
||||
const GrayImage &tgtL0 = targetPyramid[0];
|
||||
float lkDx = (float)(bestDx + subDx) * 2.0f;
|
||||
float lkDy = (float)(bestDy + subDy) * 2.0f;
|
||||
|
||||
int cx = tx * tileSize + tileSize / 2;
|
||||
int cy = ty * tileSize + tileSize / 2;
|
||||
|
||||
int lkHalfWin = 12;
|
||||
|
||||
// Pre-compute spatial gradients (Ix, Iy) and the Hessian matrix (sumIxIx,
|
||||
// sumIyIy, sumIxIy) These are static for the reference frame and DO NOT
|
||||
// change across iterations!
|
||||
float sumIxIx = 0, sumIyIy = 0, sumIxIy = 0;
|
||||
|
||||
const int maxPts = 600;
|
||||
float Ixs[maxPts], Iys[maxPts], Tvals[maxPts];
|
||||
int ptsx[maxPts], ptsy[maxPts];
|
||||
const ReferenceLkTileCache &tileCache =
|
||||
referenceLkCache.tiles[(size_t)ty * gridW + tx];
|
||||
int ptCount = 0;
|
||||
|
||||
for (int wy = -lkHalfWin; wy < lkHalfWin; ++wy) {
|
||||
for (int wx = -lkHalfWin; wx < lkHalfWin; ++wx) {
|
||||
int rx = cx + wx;
|
||||
int ry = cy + wy;
|
||||
if (rx < 1 || rx >= width - 1 || ry < 1 || ry >= height - 1)
|
||||
continue;
|
||||
|
||||
float Ix =
|
||||
(getPixelF(refL0, rx + 1, ry) - getPixelF(refL0, rx - 1, ry)) *
|
||||
0.5f;
|
||||
float Iy =
|
||||
(getPixelF(refL0, rx, ry + 1) - getPixelF(refL0, rx, ry - 1)) *
|
||||
0.5f;
|
||||
|
||||
sumIxIx += Ix * Ix;
|
||||
sumIyIy += Iy * Iy;
|
||||
sumIxIy += Ix * Iy;
|
||||
|
||||
if (ptCount < maxPts) {
|
||||
Ixs[ptCount] = Ix;
|
||||
Iys[ptCount] = Iy;
|
||||
Tvals[ptCount] = getPixelF(refL0, rx, ry);
|
||||
ptsx[ptCount] = rx;
|
||||
ptsy[ptCount] = ry;
|
||||
ptCount++;
|
||||
}
|
||||
for (int ry = tileCache.startY; ry < tileCache.endY; ++ry) {
|
||||
const float *gradXRow =
|
||||
&referenceLkCache.gradX[(size_t)ry * width];
|
||||
const float *gradYRow =
|
||||
&referenceLkCache.gradY[(size_t)ry * width];
|
||||
const uint8_t *refRow = &refL0.data[(size_t)ry * width];
|
||||
for (int rx = tileCache.startX; rx < tileCache.endX; ++rx) {
|
||||
if (ptCount >= maxPts)
|
||||
break;
|
||||
Ixs[ptCount] = gradXRow[rx];
|
||||
Iys[ptCount] = gradYRow[rx];
|
||||
Tvals[ptCount] = (float)refRow[rx];
|
||||
ptsx[ptCount] = rx;
|
||||
ptsy[ptCount] = ry;
|
||||
ptCount++;
|
||||
}
|
||||
}
|
||||
|
||||
float det = sumIxIx * sumIyIy - sumIxIy * sumIxIy;
|
||||
float sumIxIx = tileCache.sumIxIx;
|
||||
float sumIyIy = tileCache.sumIyIy;
|
||||
float sumIxIy = tileCache.sumIxIy;
|
||||
float det = tileCache.det;
|
||||
|
||||
// More iterations for smaller tiles to reach sub-pixel convergence
|
||||
int lkIters = (tileSize <= 16) ? 5 : 3;
|
||||
float convergenceThresh = (tileSize <= 16) ? 0.00005f : 0.0001f;
|
||||
bool refWindowInside =
|
||||
(cx - lkMargin >= 0) && (cx + lkMargin < width) &&
|
||||
(cy - lkMargin >= 0) && (cy + lkMargin < height);
|
||||
|
||||
if (std::abs(det) > 1e-6f) { // Only iterate if the patch has texture
|
||||
for (int iter = 0; iter < lkIters; ++iter) {
|
||||
float sumIxIt = 0, sumIyIt = 0;
|
||||
bool targetWindowInside =
|
||||
(lkDx >= (float)(-cx + lkMargin)) &&
|
||||
(lkDx <= (float)(width - 1 - cx - lkMargin)) &&
|
||||
(lkDy >= (float)(-cy + lkMargin)) &&
|
||||
(lkDy <= (float)(height - 1 - cy - lkMargin));
|
||||
bool useFastBilinear = refWindowInside && targetWindowInside;
|
||||
int baseDxInt = 0;
|
||||
int baseDyInt = 0;
|
||||
float fracX = 0.0f;
|
||||
float fracY = 0.0f;
|
||||
if (useFastBilinear) {
|
||||
baseDxInt = (int)std::floor(lkDx);
|
||||
baseDyInt = (int)std::floor(lkDy);
|
||||
fracX = lkDx - (float)baseDxInt;
|
||||
fracY = lkDy - (float)baseDyInt;
|
||||
}
|
||||
|
||||
// Only compute the temporal difference It = I(x+p) - T(x) inside the
|
||||
// loop
|
||||
for (int p = 0; p < ptCount; ++p) {
|
||||
float It =
|
||||
sampleBilinearGray(tgtL0, ptsx[p] + lkDx, ptsy[p] + lkDy) -
|
||||
Tvals[p];
|
||||
float targetValue;
|
||||
if (useFastBilinear) {
|
||||
targetValue = sampleBilinearGrayFastConstFrac(
|
||||
tgtL0, ptsx[p] + baseDxInt, ptsy[p] + baseDyInt, fracX,
|
||||
fracY);
|
||||
} else {
|
||||
float sampleX = ptsx[p] + lkDx;
|
||||
float sampleY = ptsy[p] + lkDy;
|
||||
targetValue = sampleBilinearGray(tgtL0, sampleX, sampleY);
|
||||
}
|
||||
float It = targetValue - Tvals[p];
|
||||
sumIxIt += Ixs[p] * It;
|
||||
sumIyIt += Iys[p] * It;
|
||||
}
|
||||
@@ -473,7 +628,38 @@ TileAlignment computeTileAlignment(const std::vector<GrayImage> &refPyramid,
|
||||
lkDy = (float)(bestDy + subDy) * 2.0f;
|
||||
}
|
||||
|
||||
rawOffsets[ty * gridW + tx] = {lkDx, lkDy};
|
||||
controlOffsets[(size_t)cty * controlGridW + ctx] = {lkDx, lkDy};
|
||||
}
|
||||
}
|
||||
|
||||
if (controlStrideTiles == 1) {
|
||||
rawOffsets = controlOffsets;
|
||||
} else {
|
||||
#pragma omp parallel for collapse(2) num_threads(4)
|
||||
for (int y = 0; y < gridH; ++y) {
|
||||
for (int x = 0; x < gridW; ++x) {
|
||||
float gx = (float)x / (float)controlStrideTiles;
|
||||
float gy = (float)y / (float)controlStrideTiles;
|
||||
int x0 = (int)std::floor(gx);
|
||||
int y0 = (int)std::floor(gy);
|
||||
int x1 = std::min(x0 + 1, controlGridW - 1);
|
||||
int y1 = std::min(y0 + 1, controlGridH - 1);
|
||||
x0 = std::max(0, std::min(x0, controlGridW - 1));
|
||||
y0 = std::max(0, std::min(y0, controlGridH - 1));
|
||||
float fx = gx - (float)x0;
|
||||
float fy = gy - (float)y0;
|
||||
|
||||
const Point &p00 = controlOffsets[(size_t)y0 * controlGridW + x0];
|
||||
const Point &p10 = controlOffsets[(size_t)y0 * controlGridW + x1];
|
||||
const Point &p01 = controlOffsets[(size_t)y1 * controlGridW + x0];
|
||||
const Point &p11 = controlOffsets[(size_t)y1 * controlGridW + x1];
|
||||
|
||||
rawOffsets[(size_t)y * gridW + x] = {
|
||||
(1.0f - fx) * (1.0f - fy) * p00.x + fx * (1.0f - fy) * p10.x +
|
||||
(1.0f - fx) * fy * p01.x + fx * fy * p11.x,
|
||||
(1.0f - fx) * (1.0f - fy) * p00.y + fx * (1.0f - fy) * p10.y +
|
||||
(1.0f - fx) * fy * p01.y + fx * fy * p11.y};
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -200,6 +200,7 @@ VulkanImageStacker::~VulkanImageStacker() {
|
||||
void VulkanImageStacker::initVulkanResources() {
|
||||
VulkanManager &vm = VulkanManager::getInstance();
|
||||
VkDevice device = vm.getDevice();
|
||||
VkPhysicalDevice physicalDevice = vm.getPhysicalDevice();
|
||||
|
||||
// Create Accumulator Tiles
|
||||
uint32_t scale = enableSuperRes ? 2 : 1;
|
||||
@@ -255,7 +256,8 @@ void VulkanImageStacker::initVulkanResources() {
|
||||
VkBufferCreateInfo alignInfo{};
|
||||
alignInfo.sType = VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO;
|
||||
alignInfo.size = alignBufferSize;
|
||||
alignInfo.usage = VK_BUFFER_USAGE_STORAGE_BUFFER_BIT;
|
||||
alignInfo.usage =
|
||||
VK_BUFFER_USAGE_STORAGE_BUFFER_BIT | VK_BUFFER_USAGE_TRANSFER_DST_BIT;
|
||||
alignInfo.sharingMode = VK_SHARING_MODE_EXCLUSIVE;
|
||||
VK_CHECK(vkCreateBuffer(device, &alignInfo, nullptr, &alignmentBuffer));
|
||||
|
||||
@@ -265,16 +267,36 @@ void VulkanImageStacker::initVulkanResources() {
|
||||
alignAlloc.sType = VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO;
|
||||
alignAlloc.allocationSize = alignMemReqs.size;
|
||||
alignAlloc.memoryTypeIndex = vm.findMemoryType(
|
||||
alignMemReqs.memoryTypeBits, VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT |
|
||||
VK_MEMORY_PROPERTY_HOST_COHERENT_BIT);
|
||||
alignMemReqs.memoryTypeBits, VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT);
|
||||
VK_CHECK(vkAllocateMemory(device, &alignAlloc, nullptr, &alignmentMemory));
|
||||
vkBindBufferMemory(device, alignmentBuffer, alignmentMemory, 0);
|
||||
|
||||
VkBufferCreateInfo alignUploadInfo{};
|
||||
alignUploadInfo.sType = VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO;
|
||||
alignUploadInfo.size = alignBufferSize;
|
||||
alignUploadInfo.usage = VK_BUFFER_USAGE_TRANSFER_SRC_BIT;
|
||||
alignUploadInfo.sharingMode = VK_SHARING_MODE_EXCLUSIVE;
|
||||
VK_CHECK(
|
||||
vkCreateBuffer(device, &alignUploadInfo, nullptr, &alignmentUploadBuffer));
|
||||
|
||||
VkMemoryRequirements alignUploadReqs;
|
||||
vkGetBufferMemoryRequirements(device, alignmentUploadBuffer,
|
||||
&alignUploadReqs);
|
||||
VkMemoryAllocateInfo alignUploadAlloc{};
|
||||
alignUploadAlloc.sType = VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO;
|
||||
alignUploadAlloc.allocationSize = alignUploadReqs.size;
|
||||
alignUploadAlloc.memoryTypeIndex = vm.findMemoryType(
|
||||
alignUploadReqs.memoryTypeBits, VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT |
|
||||
VK_MEMORY_PROPERTY_HOST_COHERENT_BIT);
|
||||
VK_CHECK(vkAllocateMemory(device, &alignUploadAlloc, nullptr,
|
||||
&alignmentUploadMemory));
|
||||
vkBindBufferMemory(device, alignmentUploadBuffer, alignmentUploadMemory, 0);
|
||||
|
||||
// Initial Clear for Alignment Buffer
|
||||
void *ptr;
|
||||
vkMapMemory(device, alignmentMemory, 0, alignBufferSize, 0, &ptr);
|
||||
vkMapMemory(device, alignmentUploadMemory, 0, alignBufferSize, 0, &ptr);
|
||||
memset(ptr, 0, (size_t)alignBufferSize);
|
||||
vkUnmapMemory(device, alignmentMemory);
|
||||
vkUnmapMemory(device, alignmentUploadMemory);
|
||||
|
||||
// Staging Buffer
|
||||
VkDeviceSize stagingSize = (VkDeviceSize)fullW * fullH * 4;
|
||||
@@ -317,6 +339,20 @@ void VulkanImageStacker::initVulkanResources() {
|
||||
poolInfo.pPoolSizes = poolSizes;
|
||||
VK_CHECK(vkCreateDescriptorPool(device, &poolInfo, nullptr, &descriptorPool));
|
||||
|
||||
VkPhysicalDeviceProperties deviceProperties{};
|
||||
vkGetPhysicalDeviceProperties(physicalDevice, &deviceProperties);
|
||||
gpuTimestampPeriodNs = deviceProperties.limits.timestampPeriod;
|
||||
gpuTimestampSupported =
|
||||
(deviceProperties.limits.timestampComputeAndGraphics == VK_TRUE);
|
||||
if (gpuTimestampSupported) {
|
||||
VkQueryPoolCreateInfo queryPoolInfo{};
|
||||
queryPoolInfo.sType = VK_STRUCTURE_TYPE_QUERY_POOL_CREATE_INFO;
|
||||
queryPoolInfo.queryType = VK_QUERY_TYPE_TIMESTAMP;
|
||||
queryPoolInfo.queryCount = 8;
|
||||
VK_CHECK(vkCreateQueryPool(device, &queryPoolInfo, nullptr,
|
||||
&gpuTimingQueryPool));
|
||||
}
|
||||
|
||||
// Initial Clear
|
||||
VkCommandBuffer cb = vm.beginSingleTimeCommands();
|
||||
for (int i = 0; i < numTiles; ++i) {
|
||||
@@ -373,7 +409,8 @@ void VulkanImageStacker::initVulkanResources() {
|
||||
VkBufferCreateInfo mpInfo{};
|
||||
mpInfo.sType = VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO;
|
||||
mpInfo.size = mpSize;
|
||||
mpInfo.usage = VK_BUFFER_USAGE_STORAGE_BUFFER_BIT;
|
||||
mpInfo.usage =
|
||||
VK_BUFFER_USAGE_STORAGE_BUFFER_BIT | VK_BUFFER_USAGE_TRANSFER_DST_BIT;
|
||||
mpInfo.sharingMode = VK_SHARING_MODE_EXCLUSIVE;
|
||||
VK_CHECK(vkCreateBuffer(device, &mpInfo, nullptr, &motionPriorBuffer));
|
||||
|
||||
@@ -384,15 +421,37 @@ void VulkanImageStacker::initVulkanResources() {
|
||||
mpAlloc.sType = VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO;
|
||||
mpAlloc.allocationSize = mpReqs.size;
|
||||
mpAlloc.memoryTypeIndex = vm.findMemoryType(
|
||||
mpReqs.memoryTypeBits, VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT |
|
||||
VK_MEMORY_PROPERTY_HOST_COHERENT_BIT);
|
||||
mpReqs.memoryTypeBits, VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT);
|
||||
VK_CHECK(vkAllocateMemory(device, &mpAlloc, nullptr, &motionPriorMemory));
|
||||
vkBindBufferMemory(device, motionPriorBuffer, motionPriorMemory, 0);
|
||||
|
||||
VkBufferCreateInfo mpUploadInfo{};
|
||||
mpUploadInfo.sType = VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO;
|
||||
mpUploadInfo.size = mpSize;
|
||||
mpUploadInfo.usage = VK_BUFFER_USAGE_TRANSFER_SRC_BIT;
|
||||
mpUploadInfo.sharingMode = VK_SHARING_MODE_EXCLUSIVE;
|
||||
VK_CHECK(vkCreateBuffer(device, &mpUploadInfo, nullptr,
|
||||
&motionPriorUploadBuffer));
|
||||
|
||||
VkMemoryRequirements mpUploadReqs;
|
||||
vkGetBufferMemoryRequirements(device, motionPriorUploadBuffer,
|
||||
&mpUploadReqs);
|
||||
VkMemoryAllocateInfo mpUploadAlloc{};
|
||||
mpUploadAlloc.sType = VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO;
|
||||
mpUploadAlloc.allocationSize = mpUploadReqs.size;
|
||||
mpUploadAlloc.memoryTypeIndex = vm.findMemoryType(
|
||||
mpUploadReqs.memoryTypeBits, VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT |
|
||||
VK_MEMORY_PROPERTY_HOST_COHERENT_BIT);
|
||||
VK_CHECK(vkAllocateMemory(device, &mpUploadAlloc, nullptr,
|
||||
&motionPriorUploadMemory));
|
||||
vkBindBufferMemory(device, motionPriorUploadBuffer, motionPriorUploadMemory,
|
||||
0);
|
||||
|
||||
VkBufferCreateInfo lmInfo{};
|
||||
lmInfo.sType = VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO;
|
||||
lmInfo.size = mpSize;
|
||||
lmInfo.usage = VK_BUFFER_USAGE_STORAGE_BUFFER_BIT;
|
||||
lmInfo.usage =
|
||||
VK_BUFFER_USAGE_STORAGE_BUFFER_BIT | VK_BUFFER_USAGE_TRANSFER_DST_BIT;
|
||||
lmInfo.sharingMode = VK_SHARING_MODE_EXCLUSIVE;
|
||||
VK_CHECK(vkCreateBuffer(device, &lmInfo, nullptr, &localTileMaskBuffer));
|
||||
|
||||
@@ -403,11 +462,32 @@ void VulkanImageStacker::initVulkanResources() {
|
||||
lmAlloc.sType = VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO;
|
||||
lmAlloc.allocationSize = lmReqs.size;
|
||||
lmAlloc.memoryTypeIndex = vm.findMemoryType(
|
||||
lmReqs.memoryTypeBits, VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT |
|
||||
VK_MEMORY_PROPERTY_HOST_COHERENT_BIT);
|
||||
lmReqs.memoryTypeBits, VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT);
|
||||
VK_CHECK(vkAllocateMemory(device, &lmAlloc, nullptr, &localTileMaskMemory));
|
||||
vkBindBufferMemory(device, localTileMaskBuffer, localTileMaskMemory, 0);
|
||||
|
||||
VkBufferCreateInfo lmUploadInfo{};
|
||||
lmUploadInfo.sType = VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO;
|
||||
lmUploadInfo.size = mpSize;
|
||||
lmUploadInfo.usage = VK_BUFFER_USAGE_TRANSFER_SRC_BIT;
|
||||
lmUploadInfo.sharingMode = VK_SHARING_MODE_EXCLUSIVE;
|
||||
VK_CHECK(vkCreateBuffer(device, &lmUploadInfo, nullptr,
|
||||
&localTileMaskUploadBuffer));
|
||||
|
||||
VkMemoryRequirements lmUploadReqs;
|
||||
vkGetBufferMemoryRequirements(device, localTileMaskUploadBuffer,
|
||||
&lmUploadReqs);
|
||||
VkMemoryAllocateInfo lmUploadAlloc{};
|
||||
lmUploadAlloc.sType = VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO;
|
||||
lmUploadAlloc.allocationSize = lmUploadReqs.size;
|
||||
lmUploadAlloc.memoryTypeIndex = vm.findMemoryType(
|
||||
lmUploadReqs.memoryTypeBits, VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT |
|
||||
VK_MEMORY_PROPERTY_HOST_COHERENT_BIT);
|
||||
VK_CHECK(vkAllocateMemory(device, &lmUploadAlloc, nullptr,
|
||||
&localTileMaskUploadMemory));
|
||||
vkBindBufferMemory(device, localTileMaskUploadBuffer,
|
||||
localTileMaskUploadMemory, 0);
|
||||
|
||||
// Initialize RGB Intermediate Image
|
||||
rgbFrame.width = width;
|
||||
rgbFrame.height = height;
|
||||
@@ -712,6 +792,11 @@ bool VulkanImageStacker::addFrame(AHardwareBuffer *buffer) {
|
||||
|
||||
bool VulkanImageStacker::processFrame(AHardwareBuffer *buffer, float frameScore,
|
||||
GrayImage &cachedGray) {
|
||||
using PerfClock = std::chrono::high_resolution_clock;
|
||||
auto elapsedMs = [](const PerfClock::time_point &start,
|
||||
const PerfClock::time_point &end) {
|
||||
return std::chrono::duration<double, std::milli>(end - start).count();
|
||||
};
|
||||
VulkanImage input;
|
||||
// Use existing conversion if available (from first frame) to compatible with
|
||||
// immutable sampler
|
||||
@@ -948,6 +1033,10 @@ bool VulkanImageStacker::processFrame(AHardwareBuffer *buffer, float frameScore,
|
||||
return true;
|
||||
}
|
||||
|
||||
double yuvToRgbaGpuMs = -1.0;
|
||||
double tensorGpuMs = -1.0;
|
||||
double accumulateGpuMs = -1.0;
|
||||
|
||||
// --- START PIPELINING SYNC POINT ---
|
||||
// Wait for the PREVIOUS frame's GPU task to finish before we start recording
|
||||
// new commands or mapping shared buffers.
|
||||
@@ -957,20 +1046,20 @@ bool VulkanImageStacker::processFrame(AHardwareBuffer *buffer, float frameScore,
|
||||
if (!currentIsFirstFrame && copyCount > 0) {
|
||||
void *mapPtr = nullptr;
|
||||
VkResult res =
|
||||
vkMapMemory(device, alignmentMemory, 0, VK_WHOLE_SIZE, 0, &mapPtr);
|
||||
vkMapMemory(device, alignmentUploadMemory, 0, VK_WHOLE_SIZE, 0, &mapPtr);
|
||||
if (res == VK_SUCCESS && mapPtr != nullptr) {
|
||||
memcpy(mapPtr, alignmentOffsets.data(), copyCount * sizeof(Point));
|
||||
vkUnmapMemory(device, alignmentMemory);
|
||||
vkUnmapMemory(device, alignmentUploadMemory);
|
||||
}
|
||||
|
||||
void *mpMapPtr = nullptr;
|
||||
VkResult resMP =
|
||||
vkMapMemory(device, motionPriorMemory, 0, VK_WHOLE_SIZE, 0, &mpMapPtr);
|
||||
vkMapMemory(device, motionPriorUploadMemory, 0, VK_WHOLE_SIZE, 0,
|
||||
&mpMapPtr);
|
||||
if (resMP == VK_SUCCESS && mpMapPtr != nullptr) {
|
||||
memcpy(mpMapPtr, alignmentErrorMap.data(), copyCount * sizeof(float));
|
||||
vkUnmapMemory(device, motionPriorMemory);
|
||||
vkUnmapMemory(device, motionPriorUploadMemory);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
if (localTileMask.empty()) {
|
||||
@@ -978,11 +1067,12 @@ bool VulkanImageStacker::processFrame(AHardwareBuffer *buffer, float frameScore,
|
||||
}
|
||||
void *lmMapPtr = nullptr;
|
||||
VkResult resLM =
|
||||
vkMapMemory(device, localTileMaskMemory, 0, VK_WHOLE_SIZE, 0, &lmMapPtr);
|
||||
vkMapMemory(device, localTileMaskUploadMemory, 0, VK_WHOLE_SIZE, 0,
|
||||
&lmMapPtr);
|
||||
if (resLM == VK_SUCCESS && lmMapPtr != nullptr && !localTileMask.empty()) {
|
||||
memcpy(lmMapPtr, localTileMask.data(),
|
||||
localTileMask.size() * sizeof(float));
|
||||
vkUnmapMemory(device, localTileMaskMemory);
|
||||
vkUnmapMemory(device, localTileMaskUploadMemory);
|
||||
}
|
||||
|
||||
// Update yuvToRgbaSet with current input
|
||||
@@ -1013,6 +1103,9 @@ bool VulkanImageStacker::processFrame(AHardwareBuffer *buffer, float frameScore,
|
||||
TIME_START(gpuDispatch);
|
||||
// 3. Command Buffer Recording
|
||||
VkCommandBuffer cb = vm.beginSingleTimeCommands();
|
||||
if (gpuTimestampSupported && gpuTimingQueryPool != VK_NULL_HANDLE) {
|
||||
vkCmdResetQueryPool(cb, gpuTimingQueryPool, 0, 8);
|
||||
}
|
||||
|
||||
// Transition Input Image Layout
|
||||
VkImageMemoryBarrier imageBarrier{};
|
||||
@@ -1055,6 +1148,10 @@ bool VulkanImageStacker::processFrame(AHardwareBuffer *buffer, float frameScore,
|
||||
nullptr, 1, &rgbWriteBarrier);
|
||||
|
||||
// Dispatch YUV to RGBA Conversion
|
||||
if (gpuTimestampSupported && gpuTimingQueryPool != VK_NULL_HANDLE) {
|
||||
vkCmdWriteTimestamp(cb, VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT,
|
||||
gpuTimingQueryPool, 0);
|
||||
}
|
||||
vkCmdBindPipeline(cb, VK_PIPELINE_BIND_POINT_COMPUTE, yuvToRgbaPipeline);
|
||||
vkCmdBindDescriptorSets(cb, VK_PIPELINE_BIND_POINT_COMPUTE,
|
||||
yuvToRgbaPipelineLayout, 0, 1, &yuvToRgbaSet, 0,
|
||||
@@ -1067,6 +1164,10 @@ bool VulkanImageStacker::processFrame(AHardwareBuffer *buffer, float frameScore,
|
||||
vkCmdPushConstants(cb, yuvToRgbaPipelineLayout, VK_SHADER_STAGE_COMPUTE_BIT,
|
||||
0, sizeof(convPc), &convPc);
|
||||
vkCmdDispatch(cb, (width + 15) / 16, (height + 15) / 16, 1);
|
||||
if (gpuTimestampSupported && gpuTimingQueryPool != VK_NULL_HANDLE) {
|
||||
vkCmdWriteTimestamp(cb, VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT,
|
||||
gpuTimingQueryPool, 1);
|
||||
}
|
||||
|
||||
// Transition RGB frame to SHADER_READ_ONLY_OPTIMAL for sampling
|
||||
VkImageMemoryBarrier rgbReadBarrier{};
|
||||
@@ -1109,20 +1210,76 @@ bool VulkanImageStacker::processFrame(AHardwareBuffer *buffer, float frameScore,
|
||||
&memBarrier, 0, nullptr, 0, nullptr);
|
||||
}
|
||||
|
||||
VkBufferMemoryBarrier localMaskBarrier{};
|
||||
localMaskBarrier.sType = VK_STRUCTURE_TYPE_BUFFER_MEMORY_BARRIER;
|
||||
localMaskBarrier.srcAccessMask = VK_ACCESS_HOST_WRITE_BIT;
|
||||
localMaskBarrier.dstAccessMask = VK_ACCESS_SHADER_READ_BIT;
|
||||
localMaskBarrier.buffer = localTileMaskBuffer;
|
||||
localMaskBarrier.size = VK_WHOLE_SIZE;
|
||||
bool needAlignmentUpload = (!currentIsFirstFrame && copyCount > 0);
|
||||
VkBufferMemoryBarrier uploadSrcBarriers[3] = {};
|
||||
uint32_t uploadSrcBarrierCount = 0;
|
||||
auto appendUploadSrcBarrier = [&](VkBuffer buffer) {
|
||||
VkBufferMemoryBarrier &barrier = uploadSrcBarriers[uploadSrcBarrierCount++];
|
||||
barrier.sType = VK_STRUCTURE_TYPE_BUFFER_MEMORY_BARRIER;
|
||||
barrier.srcAccessMask = VK_ACCESS_HOST_WRITE_BIT;
|
||||
barrier.dstAccessMask = VK_ACCESS_TRANSFER_READ_BIT;
|
||||
barrier.buffer = buffer;
|
||||
barrier.offset = 0;
|
||||
barrier.size = VK_WHOLE_SIZE;
|
||||
};
|
||||
if (needAlignmentUpload) {
|
||||
appendUploadSrcBarrier(alignmentUploadBuffer);
|
||||
appendUploadSrcBarrier(motionPriorUploadBuffer);
|
||||
}
|
||||
appendUploadSrcBarrier(localTileMaskUploadBuffer);
|
||||
vkCmdPipelineBarrier(cb, VK_PIPELINE_STAGE_HOST_BIT,
|
||||
VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT, 0, 0, nullptr, 1,
|
||||
&localMaskBarrier, 0, nullptr);
|
||||
VK_PIPELINE_STAGE_TRANSFER_BIT, 0, 0, nullptr,
|
||||
uploadSrcBarrierCount, uploadSrcBarriers, 0, nullptr);
|
||||
|
||||
if (needAlignmentUpload) {
|
||||
VkBufferCopy alignCopy{};
|
||||
alignCopy.size = copyCount * sizeof(Point);
|
||||
vkCmdCopyBuffer(cb, alignmentUploadBuffer, alignmentBuffer, 1, &alignCopy);
|
||||
|
||||
VkBufferCopy motionCopy{};
|
||||
motionCopy.size = copyCount * sizeof(float);
|
||||
vkCmdCopyBuffer(cb, motionPriorUploadBuffer, motionPriorBuffer, 1,
|
||||
&motionCopy);
|
||||
}
|
||||
if (!localTileMask.empty()) {
|
||||
VkBufferCopy localMaskCopy{};
|
||||
localMaskCopy.size = localTileMask.size() * sizeof(float);
|
||||
vkCmdCopyBuffer(cb, localTileMaskUploadBuffer, localTileMaskBuffer, 1,
|
||||
&localMaskCopy);
|
||||
}
|
||||
|
||||
VkBufferMemoryBarrier uploadDstBarriers[3] = {};
|
||||
uint32_t uploadDstBarrierCount = 0;
|
||||
auto appendUploadDstBarrier = [&](VkBuffer buffer) {
|
||||
VkBufferMemoryBarrier &barrier = uploadDstBarriers[uploadDstBarrierCount++];
|
||||
barrier.sType = VK_STRUCTURE_TYPE_BUFFER_MEMORY_BARRIER;
|
||||
barrier.srcAccessMask = VK_ACCESS_TRANSFER_WRITE_BIT;
|
||||
barrier.dstAccessMask = VK_ACCESS_SHADER_READ_BIT;
|
||||
barrier.buffer = buffer;
|
||||
barrier.offset = 0;
|
||||
barrier.size = VK_WHOLE_SIZE;
|
||||
};
|
||||
if (needAlignmentUpload) {
|
||||
appendUploadDstBarrier(alignmentBuffer);
|
||||
appendUploadDstBarrier(motionPriorBuffer);
|
||||
}
|
||||
if (!localTileMask.empty()) {
|
||||
appendUploadDstBarrier(localTileMaskBuffer);
|
||||
}
|
||||
if (uploadDstBarrierCount > 0) {
|
||||
vkCmdPipelineBarrier(cb, VK_PIPELINE_STAGE_TRANSFER_BIT,
|
||||
VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT, 0, 0, nullptr,
|
||||
uploadDstBarrierCount, uploadDstBarriers, 0, nullptr);
|
||||
}
|
||||
|
||||
// Phase 2: Compute Structure Tensor (only on first/reference frame)
|
||||
// The kernel shape is driven by the reference frame's local structure.
|
||||
// Subsequent frames reuse it — avoids (N-1) expensive GPU dispatches.
|
||||
if (currentIsFirstFrame) {
|
||||
if (gpuTimestampSupported && gpuTimingQueryPool != VK_NULL_HANDLE) {
|
||||
vkCmdWriteTimestamp(cb, VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT,
|
||||
gpuTimingQueryPool, 2);
|
||||
}
|
||||
vkCmdBindPipeline(cb, VK_PIPELINE_BIND_POINT_COMPUTE, tensorPipeline);
|
||||
|
||||
for (int y = 0; y < numTilesY; ++y) {
|
||||
@@ -1161,23 +1318,20 @@ bool VulkanImageStacker::processFrame(AHardwareBuffer *buffer, float frameScore,
|
||||
vkCmdPipelineBarrier(cb, VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT,
|
||||
VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT, 0, 0, nullptr, 1,
|
||||
&stBarrier, 0, nullptr);
|
||||
if (gpuTimestampSupported && gpuTimingQueryPool != VK_NULL_HANDLE) {
|
||||
vkCmdWriteTimestamp(cb, VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT,
|
||||
gpuTimingQueryPool, 3);
|
||||
}
|
||||
}
|
||||
|
||||
// Barrier between frames to ensure Accumulator writes are finished
|
||||
for (int i = 0; i < numTiles; ++i) {
|
||||
VkBufferMemoryBarrier postBarrier{};
|
||||
postBarrier.sType = VK_STRUCTURE_TYPE_BUFFER_MEMORY_BARRIER;
|
||||
postBarrier.srcAccessMask = VK_ACCESS_SHADER_WRITE_BIT;
|
||||
postBarrier.dstAccessMask =
|
||||
VK_ACCESS_SHADER_READ_BIT | VK_ACCESS_SHADER_WRITE_BIT;
|
||||
postBarrier.buffer = accumBuffers[i];
|
||||
postBarrier.size = VK_WHOLE_SIZE;
|
||||
vkCmdPipelineBarrier(cb, VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT,
|
||||
VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT, 0, 0, nullptr, 1,
|
||||
&postBarrier, 0, nullptr);
|
||||
}
|
||||
// The previous frame is already fully retired by vkQueueWaitIdle() above.
|
||||
// Avoid issuing redundant per-tile carry-over barriers here.
|
||||
|
||||
// Pass 2: Accumulate
|
||||
if (gpuTimestampSupported && gpuTimingQueryPool != VK_NULL_HANDLE) {
|
||||
vkCmdWriteTimestamp(cb, VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT,
|
||||
gpuTimingQueryPool, 4);
|
||||
}
|
||||
vkCmdBindPipeline(cb, VK_PIPELINE_BIND_POINT_COMPUTE, accumulatePipeline);
|
||||
|
||||
uint32_t fullW = pc.width;
|
||||
@@ -1212,8 +1366,46 @@ bool VulkanImageStacker::processFrame(AHardwareBuffer *buffer, float frameScore,
|
||||
vkCmdPipelineBarrier(cb, VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT,
|
||||
VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT, 0, 1, &postBarrier,
|
||||
0, nullptr, 0, nullptr);
|
||||
if (gpuTimestampSupported && gpuTimingQueryPool != VK_NULL_HANDLE) {
|
||||
vkCmdWriteTimestamp(cb, VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT,
|
||||
gpuTimingQueryPool, 5);
|
||||
}
|
||||
|
||||
vm.endSingleTimeCommands(cb);
|
||||
if (gpuTimestampSupported && gpuTimingQueryPool != VK_NULL_HANDLE) {
|
||||
auto ticksToMs = [&](uint64_t begin, uint64_t end) {
|
||||
return (double)(end - begin) * (double)gpuTimestampPeriodNs / 1.0e6;
|
||||
};
|
||||
|
||||
uint64_t yuvTimestamps[2] = {};
|
||||
VkResult yuvResult = vkGetQueryPoolResults(
|
||||
device, gpuTimingQueryPool, 0, 2, sizeof(yuvTimestamps), yuvTimestamps,
|
||||
sizeof(uint64_t), VK_QUERY_RESULT_64_BIT | VK_QUERY_RESULT_WAIT_BIT);
|
||||
if (yuvResult == VK_SUCCESS && gpuTimestampPeriodNs > 0.0f) {
|
||||
yuvToRgbaGpuMs = ticksToMs(yuvTimestamps[0], yuvTimestamps[1]);
|
||||
}
|
||||
|
||||
if (currentIsFirstFrame) {
|
||||
uint64_t tensorTimestamps[2] = {};
|
||||
VkResult tensorResult = vkGetQueryPoolResults(
|
||||
device, gpuTimingQueryPool, 2, 2, sizeof(tensorTimestamps),
|
||||
tensorTimestamps, sizeof(uint64_t),
|
||||
VK_QUERY_RESULT_64_BIT | VK_QUERY_RESULT_WAIT_BIT);
|
||||
if (tensorResult == VK_SUCCESS && gpuTimestampPeriodNs > 0.0f) {
|
||||
tensorGpuMs = ticksToMs(tensorTimestamps[0], tensorTimestamps[1]);
|
||||
}
|
||||
}
|
||||
|
||||
uint64_t accumulateTimestamps[2] = {};
|
||||
VkResult accumulateResult = vkGetQueryPoolResults(
|
||||
device, gpuTimingQueryPool, 4, 2, sizeof(accumulateTimestamps),
|
||||
accumulateTimestamps, sizeof(uint64_t),
|
||||
VK_QUERY_RESULT_64_BIT | VK_QUERY_RESULT_WAIT_BIT);
|
||||
if (accumulateResult == VK_SUCCESS && gpuTimestampPeriodNs > 0.0f) {
|
||||
accumulateGpuMs =
|
||||
ticksToMs(accumulateTimestamps[0], accumulateTimestamps[1]);
|
||||
}
|
||||
}
|
||||
TIME_END(gpuDispatch);
|
||||
|
||||
isFirstFrame = false;
|
||||
@@ -1515,6 +1707,8 @@ void VulkanImageStacker::releaseVulkanResources() {
|
||||
vkDestroyPipelineLayout(device, normalizePipelineLayout, nullptr);
|
||||
if (normalizePipeline != VK_NULL_HANDLE)
|
||||
vkDestroyPipeline(device, normalizePipeline, nullptr);
|
||||
if (gpuTimingQueryPool != VK_NULL_HANDLE)
|
||||
vkDestroyQueryPool(device, gpuTimingQueryPool, nullptr);
|
||||
|
||||
if (immutableSampler != VK_NULL_HANDLE)
|
||||
vkDestroySampler(device, immutableSampler, nullptr);
|
||||
@@ -1538,6 +1732,10 @@ void VulkanImageStacker::releaseVulkanResources() {
|
||||
if (stagingMemory != VK_NULL_HANDLE)
|
||||
vkFreeMemory(device, stagingMemory, nullptr);
|
||||
|
||||
if (alignmentUploadBuffer != VK_NULL_HANDLE)
|
||||
vkDestroyBuffer(device, alignmentUploadBuffer, nullptr);
|
||||
if (alignmentUploadMemory != VK_NULL_HANDLE)
|
||||
vkFreeMemory(device, alignmentUploadMemory, nullptr);
|
||||
if (alignmentBuffer != VK_NULL_HANDLE)
|
||||
vkDestroyBuffer(device, alignmentBuffer, nullptr);
|
||||
if (alignmentMemory != VK_NULL_HANDLE)
|
||||
@@ -1552,10 +1750,18 @@ void VulkanImageStacker::releaseVulkanResources() {
|
||||
vkDestroyBuffer(device, motionPriorBuffer, nullptr);
|
||||
if (motionPriorMemory != VK_NULL_HANDLE)
|
||||
vkFreeMemory(device, motionPriorMemory, nullptr);
|
||||
if (motionPriorUploadBuffer != VK_NULL_HANDLE)
|
||||
vkDestroyBuffer(device, motionPriorUploadBuffer, nullptr);
|
||||
if (motionPriorUploadMemory != VK_NULL_HANDLE)
|
||||
vkFreeMemory(device, motionPriorUploadMemory, nullptr);
|
||||
if (localTileMaskBuffer != VK_NULL_HANDLE)
|
||||
vkDestroyBuffer(device, localTileMaskBuffer, nullptr);
|
||||
if (localTileMaskMemory != VK_NULL_HANDLE)
|
||||
vkFreeMemory(device, localTileMaskMemory, nullptr);
|
||||
if (localTileMaskUploadBuffer != VK_NULL_HANDLE)
|
||||
vkDestroyBuffer(device, localTileMaskUploadBuffer, nullptr);
|
||||
if (localTileMaskUploadMemory != VK_NULL_HANDLE)
|
||||
vkFreeMemory(device, localTileMaskUploadMemory, nullptr);
|
||||
|
||||
if (tensorSetLayout != VK_NULL_HANDLE)
|
||||
vkDestroyDescriptorSetLayout(device, tensorSetLayout, nullptr);
|
||||
|
||||
@@ -30,6 +30,8 @@ private:
|
||||
uint32_t gridH = 0;
|
||||
VkBuffer alignmentBuffer = VK_NULL_HANDLE;
|
||||
VkDeviceMemory alignmentMemory = VK_NULL_HANDLE;
|
||||
VkBuffer alignmentUploadBuffer = VK_NULL_HANDLE;
|
||||
VkDeviceMemory alignmentUploadMemory = VK_NULL_HANDLE;
|
||||
|
||||
std::vector<VkBuffer> accumBuffers;
|
||||
std::vector<VkDeviceMemory> accumMemories;
|
||||
@@ -53,6 +55,9 @@ private:
|
||||
std::vector<VkDescriptorSet> normalizeSets;
|
||||
VkPipelineLayout normalizePipelineLayout = VK_NULL_HANDLE;
|
||||
VkPipeline normalizePipeline = VK_NULL_HANDLE;
|
||||
VkQueryPool gpuTimingQueryPool = VK_NULL_HANDLE;
|
||||
float gpuTimestampPeriodNs = 0.0f;
|
||||
bool gpuTimestampSupported = false;
|
||||
|
||||
// Staging buffer for result copy
|
||||
VkBuffer stagingBuffer = VK_NULL_HANDLE;
|
||||
@@ -104,8 +109,12 @@ private:
|
||||
// Phase 3: Motion Prior Buffer (Grid Resolution)
|
||||
VkBuffer motionPriorBuffer = VK_NULL_HANDLE;
|
||||
VkDeviceMemory motionPriorMemory = VK_NULL_HANDLE;
|
||||
VkBuffer motionPriorUploadBuffer = VK_NULL_HANDLE;
|
||||
VkDeviceMemory motionPriorUploadMemory = VK_NULL_HANDLE;
|
||||
VkBuffer localTileMaskBuffer = VK_NULL_HANDLE;
|
||||
VkDeviceMemory localTileMaskMemory = VK_NULL_HANDLE;
|
||||
VkBuffer localTileMaskUploadBuffer = VK_NULL_HANDLE;
|
||||
VkDeviceMemory localTileMaskUploadMemory = VK_NULL_HANDLE;
|
||||
float referenceFrameScore = 0.0f;
|
||||
|
||||
void initVulkanResources();
|
||||
|
||||
Reference in new issue
Block a user