feat: refine raw super-res fusion and robustness calculation
This commit is contained in:
1 parent
628447ba35
commit
692a5b4f73
4 files changed
+290
-296
No files matched your search
@@ -172,61 +172,69 @@ void main() {
|
||||
|
||||
float observationNorm = 0.0;
|
||||
float observationSupport = 0.0;
|
||||
float normalizedRaw = 0.0;
|
||||
float primaryConfidence = 0.0;
|
||||
if (primary.y > 0u || primaryNeighborSupport > 0.0) {
|
||||
float primaryVal = accumMean(primary);
|
||||
primaryConfidence = clamp(float(primary.y) / 768.0, 0.0, 1.0);
|
||||
observationSupport = max(primaryConfidence, 0.28 * primaryNeighborSupport);
|
||||
float val = (primary.y > 0u) ? primaryVal : primaryNeighborVal;
|
||||
float primaryVal = (primary.y > 0u) ? accumMean(primary) : 0.0;
|
||||
float primaryConfidence = clamp(float(primary.y) / 768.0, 0.0, 1.0);
|
||||
|
||||
if (primaryNeighborSupport > 0.0 && primaryConfidence < 0.999) {
|
||||
val = mix(primaryNeighborVal, val, primaryConfidence);
|
||||
// --- MERGED SPATIAL PASS (Performance Optimization) ---
|
||||
// Instead of three separate loops for gather, denoise, and BTV,
|
||||
// we do one 3x3 pass to collect all necessary neighborhood statistics.
|
||||
float neighborSum = 0.0;
|
||||
float neighborWeight = 0.0;
|
||||
float btvGrad = 0.0;
|
||||
float denoiseSum = primaryVal;
|
||||
float denoiseWeight = 1.0;
|
||||
|
||||
const float alpha = 0.7; // BTV decay
|
||||
const float sigmaRangeSq = mix(0.00008, 0.00030, smoothstep(0.85, 0.10, primaryConfidence));
|
||||
|
||||
for (int oy = -1; oy <= 1; ++oy) {
|
||||
for (int ox = -1; ox <= 1; ++ox) {
|
||||
if (ox == 0 && oy == 0) continue;
|
||||
uvec2 neighAccum = readGreenAccum(familyIndex, int(tx) + ox, int(ty) + oy);
|
||||
if (neighAccum.y == 0u) continue;
|
||||
|
||||
float val = accumMean(neighAccum);
|
||||
float conf = clamp(float(neighAccum.y) / 768.0, 0.0, 1.0);
|
||||
|
||||
// 1. Hole filling statistics
|
||||
float spatialW = 1.0 / (1.0 + float(ox * ox + oy * oy));
|
||||
neighborSum += val * spatialW * conf;
|
||||
neighborWeight += spatialW * conf;
|
||||
|
||||
// 2. BTV Gradient (L1 sign)
|
||||
float btvW = pow(alpha, float(abs(ox) + abs(oy)));
|
||||
btvGrad += btvW * sign(primaryVal - val);
|
||||
|
||||
// 3. Denoise (Bilateral)
|
||||
if (primaryConfidence < 0.85) {
|
||||
float d = val - primaryVal;
|
||||
float rangeW = exp(-(d * d) / max(2.0 * sigmaRangeSq, 1e-8));
|
||||
float dw = spatialW * conf * rangeW;
|
||||
denoiseSum += val * dw;
|
||||
denoiseWeight += dw;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (primary.y > 0u || neighborWeight > 0.0) {
|
||||
float neighborVal = (neighborWeight > 0.0) ? (neighborSum / neighborWeight) : 0.0;
|
||||
float support = (neighborWeight > 0.0) ? clamp(neighborWeight / 2.0, 0.0, 1.0) : 0.0;
|
||||
observationSupport = max(primaryConfidence, 0.28 * support);
|
||||
float val = (primary.y > 0u) ? primaryVal : neighborVal;
|
||||
|
||||
if (neighborWeight > 0.0 && primaryConfidence < 0.99) {
|
||||
val = mix(neighborVal, val, primaryConfidence);
|
||||
}
|
||||
observationNorm = computeObservationNorm(val, bayerIndex);
|
||||
}
|
||||
|
||||
float normalizedRaw = observationNorm;
|
||||
if (observationSupport > 0.0 && priorSupport > 0.0) {
|
||||
float obsBlend = observationSupport /
|
||||
max(observationSupport + priorSupport, 1e-5);
|
||||
float obsBlend = observationSupport / max(observationSupport + priorSupport, 1e-5);
|
||||
normalizedRaw = mix(priorNorm, observationNorm, obsBlend);
|
||||
} else if (observationSupport > 0.0) {
|
||||
normalizedRaw = observationNorm;
|
||||
} else if (priorSupport > 0.0) {
|
||||
normalizedRaw = priorNorm;
|
||||
}
|
||||
|
||||
// Mild Y-equivalent denoise on the green plane only when frame support is low.
|
||||
// Keep the range tight so edge detail stays in the luminance proxy.
|
||||
if (observationSupport > 0.0 && observationSupport < 0.85) {
|
||||
float centerNorm = normalizedRaw;
|
||||
float denoiseStrength =
|
||||
smoothstep(0.85, 0.10, max(observationSupport, 0.75 * primaryConfidence));
|
||||
float sigmaRangeSq = mix(0.00008, 0.00030, denoiseStrength);
|
||||
float sum = centerNorm;
|
||||
float wsum = 1.0;
|
||||
|
||||
for (int oy = -1; oy <= 1; ++oy) {
|
||||
for (int ox = -1; ox <= 1; ++ox) {
|
||||
if (ox == 0 && oy == 0) continue;
|
||||
uvec2 neighAccum = readGreenAccum(familyIndex, int(tx) + ox, int(ty) + oy);
|
||||
float neighSupport = clamp(float(neighAccum.y) / 768.0, 0.0, 1.0);
|
||||
if (neighSupport <= 0.0) continue;
|
||||
|
||||
float neighNorm = computeObservationNorm(accumMean(neighAccum), bayerIndex);
|
||||
float spatialW = (ox == 0 || oy == 0) ? 0.7 : 0.45;
|
||||
float d = neighNorm - centerNorm;
|
||||
float rangeW = exp(-(d * d) / max(2.0 * sigmaRangeSq, 1e-8));
|
||||
float w = spatialW * neighSupport * rangeW;
|
||||
sum += neighNorm * w;
|
||||
wsum += w;
|
||||
}
|
||||
}
|
||||
|
||||
float denoisedNorm = sum / max(wsum, 1e-4);
|
||||
normalizedRaw = mix(centerNorm, denoisedNorm, denoiseStrength);
|
||||
}
|
||||
|
||||
outputBuffer.data[outIndex] = uint16_t(clamp(normalizedRaw * 65535.0, 0.0, 65535.0));
|
||||
}
|
||||
@@ -195,27 +195,28 @@ void main() {
|
||||
vec2 trgPlane = vec2(nx, ny) + flow;
|
||||
float greenTrg = sampleTargetGreen(trgPlane);
|
||||
|
||||
// Squared difference
|
||||
// --- Principled Robustness Model (SIGGRAPH 2019 §6.4) ---
|
||||
float diff = greenRef - greenTrg;
|
||||
// Scale from UNORM to native 14-bit equivalent to match noise models roughly?
|
||||
// Actually, noise model expects UNORM.
|
||||
float d_ms_sq = diff * diff;
|
||||
float d_sq = diff * diff;
|
||||
|
||||
// Wiener shrinkage noise correction (Paper §6.4 & Python Reference)
|
||||
float sigma2_adapted = sigma2 * mix(1.0, 2.4, edgeRelax);
|
||||
float d_noise_sq = 2.0 * sigma2_adapted;
|
||||
float shrink = d_ms_sq / max(d_ms_sq + d_noise_sq, 1e-10);
|
||||
float d_corrected_sq = d_ms_sq * shrink * shrink; // Multiplied twice per paper
|
||||
|
||||
float baseRelax = (flowRange > 0.8) ? 0.0 : 1.0;
|
||||
float S_param = mix(2.0, 12.0, max(baseRelax, edgeRelax));
|
||||
float t_param = mix(0.12, 0.04, edgeRelax);
|
||||
|
||||
// Robustness calculation: R = S * exp(-d / sigma^2) - t
|
||||
float exponential = exp(-d_corrected_sq / max(sigma2_adapted, 1e-10));
|
||||
float R = clamp(S_param * exponential - t_param, 0.0, 1.0);
|
||||
// --- USER OPTIMIZED ADAPTIVE NOISE FLOOR ---
|
||||
// Flat areas: 4.5x multiplier on max variance (high SNR).
|
||||
// Sharp edges: 1.0x multiplier on physical noise (kill ghosting).
|
||||
float noise_floor = mix(4.5 * sigma2, sigma2_noise, edgeRelax);
|
||||
|
||||
// Apply pre-computed penalties
|
||||
// Normalization must also adapt. On edges, if we divide by sigma2
|
||||
// (which is huge), we mask the error. We must use the local floor as den.
|
||||
float den = mix(sigma2, sigma2_noise, edgeRelax);
|
||||
float residual = max(0.0, d_sq - noise_floor) / max(den, 1e-10);
|
||||
|
||||
// Robustness decay factor:
|
||||
// On edges, keep it tight.
|
||||
float tau = 1.0 + 1.2 * edgeRelax;
|
||||
|
||||
// 6th-order decay for brick-wall behavior.
|
||||
float R = exp(-0.5 * pow(residual / tau, 8.0));
|
||||
|
||||
// Combined with global flow-consistency penalty
|
||||
R *= globalPenalty;
|
||||
|
||||
float spatialWeight = (dx == 0 && dy == 0) ? 2.0 : 1.0;
|
||||
@@ -224,7 +225,7 @@ void main() {
|
||||
minRobustness = min(minRobustness, R);
|
||||
if (dx == 0 && dy == 0) {
|
||||
centerRobustness = R;
|
||||
centerResidualSq = d_corrected_sq;
|
||||
centerResidualSq = d_sq;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -232,12 +233,17 @@ void main() {
|
||||
// Output
|
||||
uint outIdx = planeY * pc.planeWidth + planeX;
|
||||
float avgRobustness = (weightSum > 0.0) ? (sumRobustness / weightSum) : minRobustness;
|
||||
float minMix = mix(0.22, 0.08, edgeRelax);
|
||||
float centerMix = mix(0.43, 0.56, edgeRelax);
|
||||
|
||||
// Balanced "Veto" logic:
|
||||
// Strong veto in non-edge areas to catch ghosting,
|
||||
// but relaxed on edges where edgeRelax handles the sharpening.
|
||||
float minMix = mix(0.35, 0.15, edgeRelax);
|
||||
float centerMix = mix(0.35, 0.55, edgeRelax);
|
||||
float avgMix = 1.0 - minMix - centerMix;
|
||||
float robustness = minMix * minRobustness +
|
||||
centerMix * centerRobustness +
|
||||
avgMix * avgRobustness;
|
||||
|
||||
robustness = clamp(robustness, 0.0, 1.0);
|
||||
|
||||
float residualRatio = centerResidualSq / max(sigma2, 1e-8);
|
||||
|
||||
@@ -28,7 +28,7 @@
|
||||
constexpr uint32_t kDenseAlignmentGridSpacing = 8;
|
||||
constexpr int kAlignmentRegularizationPasses = 2;
|
||||
constexpr float kAlignmentOutlierThreshold = 0.65f;
|
||||
constexpr bool kEnableRawSuperResPerfLogs = false;
|
||||
constexpr bool kEnableRawSuperResPerfLogs = true;
|
||||
constexpr bool kFastPath = false;
|
||||
|
||||
using PerfClock = std::chrono::steady_clock;
|
||||
@@ -113,14 +113,18 @@ struct RawSuperResPerfStats {
|
||||
size_t tileAlignedFrameInstances = 0;
|
||||
size_t tileScatterFrameInstances = 0;
|
||||
|
||||
double totalEffectiveFrames = 0.0;
|
||||
double avgRobustness = 0.0;
|
||||
double avgWeakFraction = 0.0;
|
||||
|
||||
void logSummary(uint32_t outputW, uint32_t outputH, float scale) const {
|
||||
if (!kEnableRawSuperResPerfLogs)
|
||||
return;
|
||||
LOGI(
|
||||
"RawSuperResPerf summary: total=%.3f ms output=%ux%u scale=%.2f "
|
||||
"frames=%zu kept=%zu skipped=%zu tiles=%zu",
|
||||
"frames=%zu kept=%zu skipped=%zu tiles=%zu effFrames=%.2f avgR=%.3f weakF=%.3f",
|
||||
totalMs, outputW, outputH, scale, totalFrames, keptFrames,
|
||||
skippedFrames, tilesProcessed);
|
||||
skippedFrames, tilesProcessed, totalEffectiveFrames, avgRobustness, avgWeakFraction);
|
||||
LOGI(
|
||||
"RawSuperResPerf phases: score=%.3f setup=%.3f upload=%.3f prior=%.3f "
|
||||
"tensor=%.3f coarse=%.3f reliability=%.3f tile=%.3f readback=%.3f "
|
||||
@@ -1211,27 +1215,6 @@ inline ScalarStats computeScalarStats(const float *data, size_t count) {
|
||||
return stats;
|
||||
}
|
||||
|
||||
inline void logAlignmentDiagnostics(const char *label, size_t frameIndex,
|
||||
const TileAlignment &alignment) {
|
||||
(void)label;
|
||||
(void)frameIndex;
|
||||
(void)alignment;
|
||||
}
|
||||
|
||||
inline void logRefinedFieldDiagnostics(VkDevice device, VkDeviceMemory alignMem,
|
||||
VkDeviceMemory robustMem, uint32_t gridW,
|
||||
uint32_t gridH, uint32_t planeW,
|
||||
uint32_t planeH, size_t frameIndex) {
|
||||
(void)device;
|
||||
(void)alignMem;
|
||||
(void)robustMem;
|
||||
(void)gridW;
|
||||
(void)gridH;
|
||||
(void)planeW;
|
||||
(void)planeH;
|
||||
(void)frameIndex;
|
||||
}
|
||||
|
||||
inline FlowSummary readFlowSummary(VkDevice device, VkDeviceMemory alignMem,
|
||||
uint32_t gridW, uint32_t gridH) {
|
||||
FlowSummary summary;
|
||||
@@ -1317,6 +1300,40 @@ inline RobustnessSummary readRobustnessSummary(const std::vector<float> &robustn
|
||||
return summary;
|
||||
}
|
||||
|
||||
inline void logAlignmentDiagnostics(const char *label, size_t frameIndex,
|
||||
const TileAlignment &alignment) {
|
||||
if (!kEnableRawSuperResPerfLogs)
|
||||
return;
|
||||
ScalarStats errStats = computeScalarStats(alignment.errorMap.data(),
|
||||
alignment.errorMap.size());
|
||||
LOGI("RawSuperResPerf %s[%zu]: errP50=%.2f errP90=%.2f", label, frameIndex,
|
||||
std::sqrt(std::max(errStats.p50, 0.0f)),
|
||||
std::sqrt(std::max(errStats.p90, 0.0f)));
|
||||
}
|
||||
|
||||
inline void logRefinedFieldDiagnostics(size_t frameIndex, float frameWeight,
|
||||
const RobustnessSummary &rs,
|
||||
const FlowSummary &flow) {
|
||||
if (!kEnableRawSuperResPerfLogs)
|
||||
return;
|
||||
LOGI("RawSuperResPerf frame[%zu]: weight=%.3f meanR=%.3f p50R=%.3f weak05F=%.3f "
|
||||
"flow90=%.2f contr=%.3f",
|
||||
frameIndex, frameWeight, rs.values.meanValue, rs.values.p50,
|
||||
rs.weak05Fraction, flow.magnitude.p90, frameWeight * rs.values.meanValue);
|
||||
}
|
||||
|
||||
inline void logRefinedFieldDiagnostics(VkDevice device, VkDeviceMemory alignMem,
|
||||
VkDeviceMemory robustMem, uint32_t gridW,
|
||||
uint32_t gridH, uint32_t planeW,
|
||||
uint32_t planeH, size_t frameIndex) {
|
||||
if (!kEnableRawSuperResPerfLogs)
|
||||
return;
|
||||
FlowSummary flow = readFlowSummary(device, alignMem, gridW, gridH);
|
||||
RobustnessSummary robustness =
|
||||
readRobustnessSummary(device, robustMem, planeW, planeH);
|
||||
logRefinedFieldDiagnostics(frameIndex, 1.0f, robustness, flow);
|
||||
}
|
||||
|
||||
inline bool uploadAlignmentField(VkDevice device, VkDeviceMemory alignMem,
|
||||
const std::vector<Point> &field) {
|
||||
if (field.empty())
|
||||
@@ -2074,40 +2091,45 @@ inline float computeYuvStyleCoarseFrameWeight(
|
||||
const TileAlignment &alignment, float sharpnessRatio,
|
||||
const CoarseReliabilitySummary &local) {
|
||||
if (alignment.errorMap.empty())
|
||||
return clamp01(0.70f + 0.25f * sharpnessRatio);
|
||||
return clamp01(0.75f + 0.25f * sharpnessRatio);
|
||||
|
||||
ScalarStats errStats = computeScalarStats(alignment.errorMap.data(),
|
||||
alignment.errorMap.size());
|
||||
const float errP90Rms = std::sqrt(std::max(errStats.p90, 0.0f));
|
||||
return computeSemanticFusionWeight(errP90Rms, sharpnessRatio,
|
||||
local.flatGoodFraction,
|
||||
local.flatAreaFraction,
|
||||
local.detailAreaFraction);
|
||||
|
||||
// 1. Error Likelihood: More generous exponential decay.
|
||||
float errorWeight = std::exp(-0.12f * std::max(0.0f, errP90Rms - 2.0f));
|
||||
|
||||
// 2. Consistency: Benefit from "flat and good" but don't penalize details too much.
|
||||
float consistencyWeight = 0.7f + 0.3f * local.flatGoodFraction;
|
||||
|
||||
// 3. Sharpness: Preference for sharper frames.
|
||||
float sharpnessWeight = 0.5f + 0.5f * clamp01(sharpnessRatio);
|
||||
|
||||
return clamp01(errorWeight * consistencyWeight * sharpnessWeight);
|
||||
}
|
||||
|
||||
inline float computeRobustnessFrameWeight(const FlowSummary &flow,
|
||||
const RobustnessSummary &robustness,
|
||||
const LocalReliabilitySummary &local) {
|
||||
float weakWeight =
|
||||
clamp01(1.0f - std::max(0.0f, robustness.weak05Fraction - 0.14f) / 0.22f);
|
||||
float weakTailWeight =
|
||||
clamp01(1.0f - std::max(0.0f, robustness.weak015Fraction - 0.02f) / 0.12f);
|
||||
float medianWeight = clamp01((robustness.values.p50 - 0.66f) / 0.10f);
|
||||
float refinedMotionWeight =
|
||||
clamp01(1.0f - std::max(0.0f, flow.magnitude.p90 - 3.4f) / 1.8f);
|
||||
float baseWeight = weakWeight * (0.55f + 0.45f * medianWeight) *
|
||||
weakTailWeight * refinedMotionWeight;
|
||||
// "Local-First" Weighting: Frame weight should be high if global alignment is okay.
|
||||
// The per-pixel robustness map handles moving objects.
|
||||
|
||||
// 1. Alignment Likelihood (Global):
|
||||
// Use mean robustness as a proxy for registration success.
|
||||
float alignmentScore = robustness.values.meanValue;
|
||||
|
||||
// 2. High confidence floor:
|
||||
// If the frame is registered, don't attenuate the static regions.
|
||||
float baseWeight = 0.85f + 0.15f * clamp01((alignmentScore - 0.5f) / 0.4f);
|
||||
|
||||
// 3. Flow Consistency: Still penalize if tracking is erratic.
|
||||
float flowConfidence = std::exp(-0.01f * std::max(0.0f, flow.magnitude.p90 - 20.0f));
|
||||
|
||||
float edgeWeight = clamp01((local.edgeGoodFraction - 0.40f) / 0.40f);
|
||||
float textWeight = clamp01((local.textGoodFraction - 0.32f) / 0.38f);
|
||||
float localConsistency =
|
||||
clamp01((local.tileRobustness.p50 - 0.68f) / 0.10f);
|
||||
float localBoost =
|
||||
(0.72f + 0.18f * edgeWeight + 0.10f * textWeight) *
|
||||
(0.80f + 0.20f * localConsistency);
|
||||
float rescueFloor = 0.24f * (0.65f * edgeWeight + 0.35f * textWeight);
|
||||
|
||||
return std::max(clamp01(baseWeight * localBoost), rescueFloor);
|
||||
float weight = baseWeight * flowConfidence;
|
||||
|
||||
// High floor to ensure static areas in aligned frames always fuse.
|
||||
return std::max(clamp01(weight), 0.70f);
|
||||
}
|
||||
|
||||
inline GreenPhaseSummary readGreenPhaseSummary(VkDevice device,
|
||||
@@ -2671,13 +2693,28 @@ bool VulkanRawStacker::processStack(uint16_t *outBuffer, size_t bufferSize) {
|
||||
if (skipFusionFrame[i]) {
|
||||
continue;
|
||||
}
|
||||
|
||||
// --- PERFORMANCE SHORTCUT ---
|
||||
// If coarse alignment is already excellent, skip the expensive
|
||||
// full-resolution refined alignment.
|
||||
ScalarStats errStats = computeScalarStats(frameAlignments[i].coarseAlign.errorMap.data(),
|
||||
frameAlignments[i].coarseAlign.errorMap.size());
|
||||
float errRms = std::sqrt(std::max(errStats.p50, 0.0f));
|
||||
if (errRms < 1.15f) {
|
||||
// Frame is perfectly aligned, reuse coarse field and skip refined check
|
||||
frameRefinedCaches[i].alignment = frameAlignments[i].seededFlow;
|
||||
frameRefinedCaches[i].robustness.assign((size_t)inputW * inputH, 1.0f);
|
||||
frameRefinedCaches[i].valid = true;
|
||||
runGlobalReliability[i] = false;
|
||||
continue;
|
||||
}
|
||||
|
||||
coarseCandidates.emplace_back(frameRetentionScores[i], i);
|
||||
}
|
||||
std::sort(coarseCandidates.begin(), coarseCandidates.end(),
|
||||
[](const auto &lhs, const auto &rhs) {
|
||||
return lhs.first > rhs.first;
|
||||
});
|
||||
|
||||
const size_t refinedBudget = std::min<size_t>(
|
||||
coarseCandidates.size(),
|
||||
std::clamp<size_t>(
|
||||
@@ -2750,57 +2787,6 @@ bool VulkanRawStacker::processStack(uint16_t *outBuffer, size_t bufferSize) {
|
||||
VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT, 0, 0, nullptr,
|
||||
2, hostBarriers, 0, nullptr);
|
||||
|
||||
vkCmdBindPipeline(cb, VK_PIPELINE_BIND_POINT_COMPUTE, alignLkPipeline);
|
||||
updateImageDescriptorSet(device, alignSet, uploadedFrames[0].view, sampler,
|
||||
0);
|
||||
updateImageDescriptorSet(device, alignSet, uploadedFrames[i].view, sampler,
|
||||
1);
|
||||
vkCmdBindDescriptorSets(cb, VK_PIPELINE_BIND_POINT_COMPUTE,
|
||||
alignLkPipelineLayout, 0, 1, &alignSet, 0,
|
||||
nullptr);
|
||||
vkCmdPushConstants(cb, alignLkPipelineLayout, VK_SHADER_STAGE_COMPUTE_BIT,
|
||||
0, sizeof(pc), &pc);
|
||||
|
||||
for (int iter = 0; iter < 5; ++iter) {
|
||||
vkCmdDispatch(cb, (gridW + 15) / 16, (gridH + 15) / 16, 1);
|
||||
VkBufferMemoryBarrier lkBarrier{
|
||||
VK_STRUCTURE_TYPE_BUFFER_MEMORY_BARRIER};
|
||||
lkBarrier.srcAccessMask = VK_ACCESS_SHADER_WRITE_BIT;
|
||||
lkBarrier.dstAccessMask =
|
||||
VK_ACCESS_SHADER_READ_BIT | VK_ACCESS_SHADER_WRITE_BIT;
|
||||
lkBarrier.buffer = alignmentBuffer;
|
||||
lkBarrier.size = VK_WHOLE_SIZE;
|
||||
vkCmdPipelineBarrier(cb, VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT,
|
||||
VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT, 0, 0, nullptr,
|
||||
1, &lkBarrier, 0, nullptr);
|
||||
}
|
||||
|
||||
vm.endSingleTimeCommands(cb);
|
||||
perf.globalReliabilityLkStage1Ms +=
|
||||
elapsedMillis(reliabilityLkStage1Start);
|
||||
|
||||
const auto reliabilityRegularize1Start = PerfClock::now();
|
||||
if (downloadAlignmentField(device, alignmentMemory, (uint32_t)gridW,
|
||||
(uint32_t)gridH, seededFlow)) {
|
||||
regularizeAlignmentField(seededFlow, (uint32_t)gridW, (uint32_t)gridH,
|
||||
(uint32_t)tileSize, uploadedFrames[0].proxy);
|
||||
uploadAlignmentField(device, alignmentMemory, seededFlow);
|
||||
}
|
||||
perf.globalReliabilityRegularize1Ms +=
|
||||
elapsedMillis(reliabilityRegularize1Start);
|
||||
|
||||
const auto reliabilityRobustness1AndLkStage2Start = PerfClock::now();
|
||||
cb = vm.beginSingleTimeCommands();
|
||||
VkBufferMemoryBarrier refinedHostBarrier{
|
||||
VK_STRUCTURE_TYPE_BUFFER_MEMORY_BARRIER};
|
||||
refinedHostBarrier.srcAccessMask = VK_ACCESS_HOST_WRITE_BIT;
|
||||
refinedHostBarrier.dstAccessMask = VK_ACCESS_SHADER_READ_BIT;
|
||||
refinedHostBarrier.buffer = alignmentBuffer;
|
||||
refinedHostBarrier.size = VK_WHOLE_SIZE;
|
||||
vkCmdPipelineBarrier(cb, VK_PIPELINE_STAGE_HOST_BIT,
|
||||
VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT, 0, 0, nullptr,
|
||||
1, &refinedHostBarrier, 0, nullptr);
|
||||
|
||||
vkCmdBindPipeline(cb, VK_PIPELINE_BIND_POINT_COMPUTE, robustnessPipeline);
|
||||
updateImageDescriptorSet(device, robustSet, uploadedFrames[0].view, sampler,
|
||||
0);
|
||||
@@ -2828,86 +2814,8 @@ bool VulkanRawStacker::processStack(uint16_t *outBuffer, size_t bufferSize) {
|
||||
VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT, 0, 0, nullptr, 2,
|
||||
rbBarriers, 0, nullptr);
|
||||
|
||||
vkCmdBindPipeline(cb, VK_PIPELINE_BIND_POINT_COMPUTE, alignLkPipeline);
|
||||
updateImageDescriptorSet(device, alignSet, uploadedFrames[0].view, sampler,
|
||||
0);
|
||||
updateImageDescriptorSet(device, alignSet, uploadedFrames[i].view, sampler,
|
||||
1);
|
||||
vkCmdBindDescriptorSets(cb, VK_PIPELINE_BIND_POINT_COMPUTE,
|
||||
alignLkPipelineLayout, 0, 1, &alignSet, 0,
|
||||
nullptr);
|
||||
vkCmdPushConstants(cb, alignLkPipelineLayout, VK_SHADER_STAGE_COMPUTE_BIT,
|
||||
0, sizeof(pc), &pc);
|
||||
for (int iter = 0; iter < 2; ++iter) {
|
||||
vkCmdDispatch(cb, (gridW + 15) / 16, (gridH + 15) / 16, 1);
|
||||
VkBufferMemoryBarrier lkBarrier{
|
||||
VK_STRUCTURE_TYPE_BUFFER_MEMORY_BARRIER};
|
||||
lkBarrier.srcAccessMask = VK_ACCESS_SHADER_WRITE_BIT;
|
||||
lkBarrier.dstAccessMask =
|
||||
VK_ACCESS_SHADER_READ_BIT | VK_ACCESS_SHADER_WRITE_BIT;
|
||||
lkBarrier.buffer = alignmentBuffer;
|
||||
lkBarrier.size = VK_WHOLE_SIZE;
|
||||
vkCmdPipelineBarrier(cb, VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT,
|
||||
VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT, 0, 0, nullptr,
|
||||
1, &lkBarrier, 0, nullptr);
|
||||
}
|
||||
|
||||
vm.endSingleTimeCommands(cb);
|
||||
perf.globalReliabilityRobustness1AndLkStage2Ms +=
|
||||
elapsedMillis(reliabilityRobustness1AndLkStage2Start);
|
||||
|
||||
const auto reliabilityRegularize2Start = PerfClock::now();
|
||||
if (downloadAlignmentField(device, alignmentMemory, (uint32_t)gridW,
|
||||
(uint32_t)gridH, seededFlow)) {
|
||||
regularizeAlignmentField(seededFlow, (uint32_t)gridW, (uint32_t)gridH,
|
||||
(uint32_t)tileSize, uploadedFrames[0].proxy);
|
||||
uploadAlignmentField(device, alignmentMemory, seededFlow);
|
||||
}
|
||||
perf.globalReliabilityRegularize2Ms +=
|
||||
elapsedMillis(reliabilityRegularize2Start);
|
||||
|
||||
const auto reliabilityRobustness2Start = PerfClock::now();
|
||||
cb = vm.beginSingleTimeCommands();
|
||||
VkBufferMemoryBarrier finalAlignBarrier{
|
||||
VK_STRUCTURE_TYPE_BUFFER_MEMORY_BARRIER};
|
||||
finalAlignBarrier.srcAccessMask = VK_ACCESS_HOST_WRITE_BIT;
|
||||
finalAlignBarrier.dstAccessMask = VK_ACCESS_SHADER_READ_BIT;
|
||||
finalAlignBarrier.buffer = alignmentBuffer;
|
||||
finalAlignBarrier.size = VK_WHOLE_SIZE;
|
||||
vkCmdPipelineBarrier(cb, VK_PIPELINE_STAGE_HOST_BIT,
|
||||
VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT, 0, 0, nullptr,
|
||||
1, &finalAlignBarrier, 0, nullptr);
|
||||
|
||||
vkCmdBindPipeline(cb, VK_PIPELINE_BIND_POINT_COMPUTE, robustnessPipeline);
|
||||
updateImageDescriptorSet(device, robustSet, uploadedFrames[0].view, sampler,
|
||||
0);
|
||||
updateImageDescriptorSet(device, robustSet, uploadedFrames[i].view, sampler,
|
||||
1);
|
||||
vkCmdBindDescriptorSets(cb, VK_PIPELINE_BIND_POINT_COMPUTE,
|
||||
robustnessPipelineLayout, 0, 1, &robustSet, 0,
|
||||
nullptr);
|
||||
vkCmdPushConstants(cb, robustnessPipelineLayout,
|
||||
VK_SHADER_STAGE_COMPUTE_BIT, 0, sizeof(pc), &pc);
|
||||
vkCmdDispatch(cb, (inputW + 15) / 16, (inputH + 15) / 16, 1);
|
||||
|
||||
VkBufferMemoryBarrier finalRbBarriers[2]{};
|
||||
finalRbBarriers[0].sType = VK_STRUCTURE_TYPE_BUFFER_MEMORY_BARRIER;
|
||||
finalRbBarriers[0].srcAccessMask = VK_ACCESS_SHADER_WRITE_BIT;
|
||||
finalRbBarriers[0].dstAccessMask = VK_ACCESS_SHADER_READ_BIT;
|
||||
finalRbBarriers[0].buffer = robustnessBuffer;
|
||||
finalRbBarriers[0].size = VK_WHOLE_SIZE;
|
||||
finalRbBarriers[1].sType = VK_STRUCTURE_TYPE_BUFFER_MEMORY_BARRIER;
|
||||
finalRbBarriers[1].srcAccessMask = VK_ACCESS_SHADER_WRITE_BIT;
|
||||
finalRbBarriers[1].dstAccessMask = VK_ACCESS_SHADER_READ_BIT;
|
||||
finalRbBarriers[1].buffer = flowVarianceBuffer;
|
||||
finalRbBarriers[1].size = VK_WHOLE_SIZE;
|
||||
vkCmdPipelineBarrier(cb, VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT,
|
||||
VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT, 0, 0, nullptr, 2,
|
||||
finalRbBarriers, 0, nullptr);
|
||||
|
||||
vm.endSingleTimeCommands(cb);
|
||||
perf.globalReliabilityRobustness2Ms +=
|
||||
elapsedMillis(reliabilityRobustness2Start);
|
||||
perf.globalReliabilityMs += elapsedMillis(reliabilityLkStage1Start);
|
||||
|
||||
const auto reliabilityReadbackStart = PerfClock::now();
|
||||
RefinedFrameCache &refinedCache = frameRefinedCaches[i];
|
||||
@@ -3949,6 +3857,41 @@ bool VulkanRawStacker::processStack(uint16_t *outBuffer, size_t bufferSize) {
|
||||
TIME_END(phase4_TileProcessing);
|
||||
perf.tileProcessingMs = elapsed_phase4_TileProcessing;
|
||||
|
||||
// =====================================================================
|
||||
// Phase 4B: Aggregate fusion statistics
|
||||
// =====================================================================
|
||||
if (kEnableRawSuperResPerfLogs) {
|
||||
perf.totalEffectiveFrames = 1.0; // Reference frame
|
||||
double sumRobustness = 1.0;
|
||||
double sumWeakFraction = 0.0;
|
||||
for (size_t i = 1; i < pendingFrames.size(); ++i) {
|
||||
if (!skipFusionFrame[i] && frameRefinedCaches[i].valid) {
|
||||
RobustnessSummary rs = readRobustnessSummary(
|
||||
frameRefinedCaches[i].robustness, inputW, inputH);
|
||||
float contr = frameFusionWeights[i] * rs.values.meanValue;
|
||||
perf.totalEffectiveFrames += contr;
|
||||
sumRobustness += rs.values.meanValue;
|
||||
sumWeakFraction += rs.weak05Fraction;
|
||||
|
||||
FlowSummary flow;
|
||||
if (!frameRefinedCaches[i].alignment.empty()) {
|
||||
std::vector<float> magnitudes;
|
||||
magnitudes.reserve(frameRefinedCaches[i].alignment.size());
|
||||
for (const Point &p : frameRefinedCaches[i].alignment) {
|
||||
magnitudes.push_back(std::sqrt(p.x * p.x + p.y * p.y));
|
||||
}
|
||||
flow.magnitude =
|
||||
computeScalarStats(magnitudes.data(), magnitudes.size());
|
||||
}
|
||||
logRefinedFieldDiagnostics(i, frameFusionWeights[i], rs, flow);
|
||||
}
|
||||
}
|
||||
if (perf.keptFrames > 0) {
|
||||
perf.avgRobustness = (double)sumRobustness / (double)perf.keptFrames;
|
||||
perf.avgWeakFraction = (double)sumWeakFraction / (double)perf.keptFrames;
|
||||
}
|
||||
}
|
||||
|
||||
// =====================================================================
|
||||
// Phase 5: Read back result from staging buffer
|
||||
// =====================================================================
|
||||
|
||||
@@ -1231,7 +1231,7 @@ object GalleryManager {
|
||||
preparedGainmapResult = preparedGainmapResult
|
||||
)
|
||||
}
|
||||
updateThumbnail(context, photoId, photoProcessor, metadata)
|
||||
updateThumbnail(context, photoId, photoProcessor, metadata, bitmap)
|
||||
if (shouldAutoSave) {
|
||||
exportPhoto(
|
||||
context,
|
||||
@@ -1701,24 +1701,6 @@ object GalleryManager {
|
||||
lensShadingHeight = 0,
|
||||
)
|
||||
|
||||
if (rawStackResult == null && currentUseSuperResolution) {
|
||||
PLog.w(TAG, "processBurstRaw failed with SR, retrying without SR")
|
||||
currentUseSuperResolution = false
|
||||
rawStackResult = MultiFrameStacker.processBurstRaw(
|
||||
images, rawMetadata.cfaPattern,
|
||||
false,
|
||||
1.0f,
|
||||
useGpuAcceleration,
|
||||
masterBlackLevel = rawMetadata.blackLevel,
|
||||
whiteLevel = rawMetadata.whiteLevel.toInt(),
|
||||
whiteBalanceGains = rawMetadata.whiteBalanceGains,
|
||||
noiseModel = rawMetadata.noiseProfile,
|
||||
lensShading = null,
|
||||
lensShadingWidth = 0,
|
||||
lensShadingHeight = 0,
|
||||
)
|
||||
}
|
||||
|
||||
val finalStackResult = rawStackResult ?: return@withContext
|
||||
|
||||
val dngWritten = trySaveStackedRawDng(
|
||||
@@ -1746,52 +1728,101 @@ object GalleryManager {
|
||||
@Suppress("ExplicitGarbageCollectionCall")
|
||||
System.gc()
|
||||
|
||||
val result: Bitmap = run {
|
||||
var bitmap = RawDemosaicProcessor.getInstance().process(
|
||||
context,
|
||||
dngFile.absolutePath,
|
||||
aspectRatio,
|
||||
metadata.cropRegion,
|
||||
rotation,
|
||||
exposureBias = exposureBias ?: 0f,
|
||||
rawExposureCompensation = metadata.rawExposureCompensation ?: 0f,
|
||||
rawAutoExposure = resolveRawAutoExposure(context, metadata),
|
||||
rawBlackPointCorrection = metadata.rawBlackPointCorrection ?: 0f,
|
||||
rawWhitePointCorrection = metadata.rawWhitePointCorrection ?: 0f,
|
||||
rawAutoWhiteBalanceEstimate = resolveRawAutoWhiteBalanceEstimate(context, metadata),
|
||||
sharpeningValue = 0.4f,
|
||||
denoiseValue = metadata.rawDenoiseValue,
|
||||
rawDcpId = metadata.rawDcpId
|
||||
) ?: return@run null
|
||||
if (metadata.isMirrored) {
|
||||
bitmap = BitmapUtils.flipHorizontal(bitmap)
|
||||
}
|
||||
val rawResult = RawDemosaicProcessor.getInstance().processForHdrSources(
|
||||
context,
|
||||
dngFile.absolutePath,
|
||||
aspectRatio = aspectRatio,
|
||||
cropRegion = metadata.cropRegion,
|
||||
rotation = rotation,
|
||||
exposureBias = exposureBias ?: 0f,
|
||||
rawExposureCompensation = metadata.rawExposureCompensation ?: 0f,
|
||||
rawAutoExposure = resolveRawAutoExposure(context, metadata),
|
||||
rawBlackPointCorrection = metadata.rawBlackPointCorrection ?: 0f,
|
||||
rawWhitePointCorrection = metadata.rawWhitePointCorrection ?: 0f,
|
||||
rawAutoWhiteBalanceEstimate = resolveRawAutoWhiteBalanceEstimate(context, metadata),
|
||||
sharpeningValue = 0.4f,
|
||||
denoiseValue = metadata.rawDenoiseValue,
|
||||
rawDcpId = metadata.rawDcpId
|
||||
) ?: return@withContext
|
||||
var bitmap = rawResult.sdrBitmap
|
||||
|
||||
bitmap
|
||||
} ?: return@withContext
|
||||
if (metadata.isMirrored) {
|
||||
bitmap = BitmapUtils.flipHorizontal(bitmap)
|
||||
}
|
||||
|
||||
// Save Original (Stacked Result)
|
||||
FileOutputStream(tempFile).use { outputStream ->
|
||||
writeFinalJpeg(result, outputStream, photoQuality)
|
||||
writeFinalJpeg(bitmap, outputStream, photoQuality)
|
||||
}
|
||||
tempFile.renameTo(photoFile)
|
||||
generateBokehPhoto(context, photoId, metadata, result)
|
||||
generateBokehPhoto(context, photoId, metadata, bitmap)
|
||||
|
||||
updateThumbnail(context, photoId, photoProcessor, metadata)
|
||||
val preparedUltraHdrSource = if (metadata.manualHdrEffectEnabled) {
|
||||
photoProcessor.prepareUltraHdrSourceFromRawResult(
|
||||
context = context,
|
||||
photoId = photoId,
|
||||
rawResult = rawResult,
|
||||
metadata = metadata,
|
||||
sharpening = sharpeningValue,
|
||||
noiseReduction = noiseReductionValue,
|
||||
chromaNoiseReduction = chromaNoiseReductionValue,
|
||||
applyMirror = true
|
||||
)
|
||||
} else {
|
||||
null
|
||||
}
|
||||
val preparedGainmapResult = preparedUltraHdrSource?.let { source ->
|
||||
var result: GainmapResult? = null
|
||||
val gainmapElapsed = measureTimeMillis {
|
||||
result = gainmapProducer.build(source, HdrGainmapStrength.coerce(metadata.hdrEffectStrength))
|
||||
}
|
||||
PLog.d(TAG, "saveRawStackedPhoto prepared gainmap for reuse, took=${gainmapElapsed}ms")
|
||||
result
|
||||
}
|
||||
preparedUltraHdrSource?.let {
|
||||
PLog.d(TAG, "saveRawStackedPhoto building detail HDR from in-memory RAW result: $photoId")
|
||||
buildDetailHdrCache(
|
||||
context = context,
|
||||
photoId = photoId,
|
||||
metadata = metadata,
|
||||
sharpening = sharpeningValue,
|
||||
noiseReduction = noiseReductionValue,
|
||||
chromaNoiseReduction = chromaNoiseReductionValue,
|
||||
preparedUltraHdrSource = it,
|
||||
preparedGainmapResult = preparedGainmapResult
|
||||
)
|
||||
}
|
||||
|
||||
updateThumbnail(context, photoId, photoProcessor, metadata, bitmap)
|
||||
// Auto Save
|
||||
if (shouldAutoSave) {
|
||||
exportPhoto(
|
||||
context,
|
||||
photoId,
|
||||
result,
|
||||
bitmap,
|
||||
photoProcessor,
|
||||
metadata,
|
||||
sharpeningValue,
|
||||
noiseReductionValue,
|
||||
chromaNoiseReductionValue,
|
||||
photoQuality
|
||||
photoQuality,
|
||||
preparedUltraHdrSource = preparedUltraHdrSource,
|
||||
preparedGainmapResult = preparedGainmapResult
|
||||
)
|
||||
}
|
||||
preparedUltraHdrSource?.hdrReference?.bitmap?.let {
|
||||
if (!it.isRecycled) {
|
||||
it.recycle()
|
||||
}
|
||||
}
|
||||
preparedUltraHdrSource?.sdrBase?.let {
|
||||
if (it !== bitmap && !it.isRecycled) {
|
||||
it.recycle()
|
||||
}
|
||||
}
|
||||
if (!bitmap.isRecycled) {
|
||||
bitmap.recycle()
|
||||
}
|
||||
} catch (e: Exception) {
|
||||
PLog.e(TAG, "Failed to savePhoto", e)
|
||||
}
|
||||
@@ -2427,15 +2458,18 @@ object GalleryManager {
|
||||
context: Context,
|
||||
photoId: String,
|
||||
photoProcessor: PhotoProcessor,
|
||||
metadata: MediaMetadata? = null
|
||||
metadata: MediaMetadata? = null,
|
||||
inputBitmap: Bitmap? = null
|
||||
) {
|
||||
withContext(Dispatchers.IO) {
|
||||
try {
|
||||
val resolvedMetadata = metadata ?: loadMetadata(context, photoId) ?: return@withContext
|
||||
// 加载原始位图,限制尺寸以提高性能
|
||||
val originalBitmap = loadOriginalBitmap(context, photoId, maxEdge = THUMBNAIL_MAX_EDGE)
|
||||
?: loadBitmap(context, photoId, maxEdge = THUMBNAIL_MAX_EDGE)
|
||||
?: return@withContext
|
||||
// Use provided bitmap or load from disk if unavailable
|
||||
val originalBitmap = inputBitmap?.let {
|
||||
createScaledThumbnail(it, THUMBNAIL_MAX_EDGE)
|
||||
} ?: loadOriginalBitmap(context, photoId, maxEdge = THUMBNAIL_MAX_EDGE)
|
||||
?: loadBitmap(context, photoId, maxEdge = THUMBNAIL_MAX_EDGE)
|
||||
?: return@withContext
|
||||
|
||||
// 应用所有效果(LUT、虚化、裁切、边框等)到缩略图尺寸的位图
|
||||
val processedBitmap = photoProcessor.processBitmap(
|
||||
@@ -2455,7 +2489,10 @@ object GalleryManager {
|
||||
if (processedBitmap !== originalBitmap) {
|
||||
processedBitmap.recycle()
|
||||
}
|
||||
originalBitmap.recycle()
|
||||
// Only recycle originalBitmap if it was newly loaded or scaled
|
||||
if (originalBitmap !== inputBitmap) {
|
||||
originalBitmap.recycle()
|
||||
}
|
||||
PLog.d(TAG, "Thumbnail updated for photo: $photoId")
|
||||
} catch (e: Exception) {
|
||||
PLog.e(TAG, "Failed to update thumbnail for photo: $photoId", e)
|
||||
|
||||
Reference in new issue
Block a user