feat: vulkan stacker caching and tile-based optimization

This commit is contained in:
zhoubinjia committed 2026-04-16 17:21:06 +08:00
1 parent 9336c7a35b
commit 3f6bcb1fae
6 files changed
+238 -26

No files matched your search

+10
View File
@@ -6,6 +6,7 @@
#include <algorithm>
#include <android/bitmap.h>
#include <cmath>
#include <chrono>
#include <cstring>
#include <fstream>
#include <jni.h>
@@ -852,6 +853,15 @@ Java_com_hinnka_mycamera_processor_MultiFrameStacker_releaseVulkanStackerNative(
delete stacker;
}
JNIEXPORT jboolean JNICALL
Java_com_hinnka_mycamera_processor_MultiFrameStacker_resetVulkanStackerNative(
JNIEnv *env, jobject /* this */, jlong stackerPtr) {
auto *stacker = reinterpret_cast<VulkanImageStacker *>(stackerPtr);
if (!stacker)
return JNI_FALSE;
return stacker->resetForReuse() ? JNI_TRUE : JNI_FALSE;
}
/**
* Raw Stacking JNI Interface
*/
+4 -2
View File
@@ -15,6 +15,8 @@ layout(push_constant, scalar) uniform PushConstants {
float t0, t1, t2, t3, t4, t5;
uint outWidth;
uint outHeight;
uint outOriginX;
uint outOriginY;
uint sensorWidth; // Global sensor width
uint sensorHeight; // Global sensor height
uint tileX;
@@ -50,8 +52,8 @@ vec3 ycbcr2rgb(vec3 ycc) {
}
void main() {
uint X = gl_GlobalInvocationID.x;
uint Y = gl_GlobalInvocationID.y;
uint X = gl_GlobalInvocationID.x + pc.outOriginX;
uint Y = gl_GlobalInvocationID.y + pc.outOriginY;
if (X >= pc.outWidth || Y >= pc.outHeight) return;
+113 -17
View File
@@ -190,10 +190,7 @@ VulkanImageStacker::VulkanImageStacker(uint32_t w, uint32_t h, bool sr)
}
VulkanImageStacker::~VulkanImageStacker() {
for (auto &frame : pendingFrames) {
AHardwareBuffer_release(frame.buffer);
}
pendingFrames.clear();
releasePendingFrames();
releaseVulkanResources();
}
@@ -814,7 +811,7 @@ bool VulkanImageStacker::processFrame(AHardwareBuffer *buffer, float frameScore,
VulkanManager &vm = VulkanManager::getInstance();
VkDevice device = vm.getDevice();
if (currentIsFirstFrame) {
if (immutableSampler == VK_NULL_HANDLE) {
// Steal the first frame's sampler and conversion for long-lived pipelines
this->immutableSampler = input.sampler;
this->ycbcrConversion = input.ycbcrConversion;
@@ -1503,15 +1500,7 @@ bool VulkanImageStacker::processStack(uint32_t *outBitmap, uint32_t outWidth,
pendingFrames.clear();
vkQueueWaitIdle(vm.getComputeQueue());
vkResetDescriptorPool(device, descriptorPool, 0);
// Reset descriptor set handles as they are now invalid
yuvToRgbaSet = VK_NULL_HANDLE;
std::fill(accumSets.begin(), accumSets.end(),
(VkDescriptorSet)VK_NULL_HANDLE);
std::fill(tensorSets.begin(), tensorSets.end(),
(VkDescriptorSet)VK_NULL_HANDLE);
std::fill(normalizeSets.begin(), normalizeSets.end(),
(VkDescriptorSet)VK_NULL_HANDLE);
resetDescriptorHandles();
TIME_END(allFramesProcessing);
@@ -1620,6 +1609,8 @@ bool VulkanImageStacker::processStack(uint32_t *outBitmap, uint32_t outWidth,
float t0, t1, t2, t3, t4, t5;
uint32_t outWidth;
uint32_t outHeight;
uint32_t outOriginX;
uint32_t outOriginY;
uint32_t sensorWidth;
uint32_t sensorHeight;
uint32_t tileX;
@@ -1631,8 +1622,6 @@ bool VulkanImageStacker::processStack(uint32_t *outBitmap, uint32_t outWidth,
memcpy(&npc, transform, 6 * sizeof(float));
npc.outWidth = outWidth;
npc.outHeight = outHeight;
npc.sensorWidth = fullW;
npc.sensorHeight = fullH;
int tx = i % numTilesX;
int ty = i / numTilesX;
npc.tileX = tx * tileW;
@@ -1640,6 +1629,72 @@ bool VulkanImageStacker::processStack(uint32_t *outBitmap, uint32_t outWidth,
npc.tileW = std::min(tileW, fullW - npc.tileX);
npc.tileH = std::min(tileH, fullH - npc.tileY);
npc.bufferStride = tileW + 16;
npc.sensorWidth = fullW;
npc.sensorHeight = fullH;
const int tileStartX = static_cast<int>(npc.tileX);
const int tileStartY = static_cast<int>(npc.tileY);
const int tileEndX = tileStartX + static_cast<int>(npc.tileW);
const int tileEndY = tileStartY + static_cast<int>(npc.tileH);
int dispatchMinX = 0;
int dispatchMinY = 0;
int dispatchMaxX = static_cast<int>(outWidth);
int dispatchMaxY = static_cast<int>(outHeight);
switch (rotation) {
case 0:
dispatchMinX = std::max(0, static_cast<int>(std::floor(tileStartX - cropX)) - 1);
dispatchMaxX = std::min(static_cast<int>(outWidth),
static_cast<int>(std::ceil(tileEndX - cropX)) + 1);
dispatchMinY = std::max(0, static_cast<int>(std::floor(tileStartY - cropY)) - 1);
dispatchMaxY = std::min(static_cast<int>(outHeight),
static_cast<int>(std::ceil(tileEndY - cropY)) + 1);
break;
case 90:
dispatchMinX =
std::max(0, static_cast<int>(std::floor(sH - cropX - tileEndY)) - 1);
dispatchMaxX =
std::min(static_cast<int>(outWidth),
static_cast<int>(std::ceil(sH - cropX - tileStartY)) + 1);
dispatchMinY = std::max(0, static_cast<int>(std::floor(tileStartX - cropY)) - 1);
dispatchMaxY = std::min(static_cast<int>(outHeight),
static_cast<int>(std::ceil(tileEndX - cropY)) + 1);
break;
case 180:
dispatchMinX =
std::max(0, static_cast<int>(std::floor(sW - cropX - tileEndX)) - 1);
dispatchMaxX =
std::min(static_cast<int>(outWidth),
static_cast<int>(std::ceil(sW - cropX - tileStartX)) + 1);
dispatchMinY =
std::max(0, static_cast<int>(std::floor(sH - cropY - tileEndY)) - 1);
dispatchMaxY =
std::min(static_cast<int>(outHeight),
static_cast<int>(std::ceil(sH - cropY - tileStartY)) + 1);
break;
case 270:
dispatchMinX = std::max(0, static_cast<int>(std::floor(tileStartY - cropX)) - 1);
dispatchMaxX = std::min(static_cast<int>(outWidth),
static_cast<int>(std::ceil(tileEndY - cropX)) + 1);
dispatchMinY =
std::max(0, static_cast<int>(std::floor(sW - cropY - tileEndX)) - 1);
dispatchMaxY =
std::min(static_cast<int>(outHeight),
static_cast<int>(std::ceil(sW - cropY - tileStartX)) + 1);
break;
default:
break;
}
if (dispatchMinX >= dispatchMaxX || dispatchMinY >= dispatchMaxY)
continue;
const uint32_t dispatchW =
static_cast<uint32_t>(dispatchMaxX - dispatchMinX);
const uint32_t dispatchH =
static_cast<uint32_t>(dispatchMaxY - dispatchMinY);
npc.outOriginX = static_cast<uint32_t>(dispatchMinX);
npc.outOriginY = static_cast<uint32_t>(dispatchMinY);
vkCmdBindDescriptorSets(cb, VK_PIPELINE_BIND_POINT_COMPUTE,
normalizePipelineLayout, 0, 1, &normalizeSets[i], 0,
@@ -1648,7 +1703,7 @@ bool VulkanImageStacker::processStack(uint32_t *outBitmap, uint32_t outWidth,
vkCmdPushConstants(cb, normalizePipelineLayout, VK_SHADER_STAGE_COMPUTE_BIT,
0, sizeof(npc), &npc);
vkCmdDispatch(cb, (outWidth + 15) / 16, (outHeight + 15) / 16, 1);
vkCmdDispatch(cb, (dispatchW + 15) / 16, (dispatchH + 15) / 16, 1);
}
// Transition staging buffer
@@ -1684,10 +1739,51 @@ bool VulkanImageStacker::processStack(uint32_t *outBitmap, uint32_t outWidth,
TIME_END(outputCopy);
vkFreeDescriptorSets(device, descriptorPool, numTiles, normalizeSets.data());
std::fill(normalizeSets.begin(), normalizeSets.end(),
(VkDescriptorSet)VK_NULL_HANDLE);
return true;
}
bool VulkanImageStacker::resetForReuse() {
VulkanManager &vm = VulkanManager::getInstance();
VkDevice device = vm.getDevice();
if (device == VK_NULL_HANDLE) {
LOGE("resetForReuse: Vulkan device is NULL");
return false;
}
vkQueueWaitIdle(vm.getComputeQueue());
releasePendingFrames();
referencePyramid.clear();
referenceFrameScore = 0.0f;
isFirstFrame = true;
if (descriptorPool != VK_NULL_HANDLE) {
vkResetDescriptorPool(device, descriptorPool, 0);
}
resetDescriptorHandles();
return true;
}
void VulkanImageStacker::resetDescriptorHandles() {
yuvToRgbaSet = VK_NULL_HANDLE;
std::fill(accumSets.begin(), accumSets.end(), (VkDescriptorSet)VK_NULL_HANDLE);
std::fill(tensorSets.begin(), tensorSets.end(), (VkDescriptorSet)VK_NULL_HANDLE);
std::fill(normalizeSets.begin(), normalizeSets.end(),
(VkDescriptorSet)VK_NULL_HANDLE);
}
void VulkanImageStacker::releasePendingFrames() {
for (auto &frame : pendingFrames) {
frame.grayY.data.clear();
if (frame.buffer != nullptr) {
AHardwareBuffer_release(frame.buffer);
}
}
pendingFrames.clear();
}
void VulkanImageStacker::releaseVulkanResources() {
VkDevice device = VulkanManager::getInstance().getDevice();
if (device == VK_NULL_HANDLE)
+3
View File
@@ -13,6 +13,7 @@ public:
bool addFrame(AHardwareBuffer *buffer);
bool processStack(uint32_t *outBitmap, uint32_t outWidth, uint32_t outHeight,
uint32_t stride, int rotation);
bool resetForReuse();
private:
uint32_t width, height;
@@ -122,4 +123,6 @@ private:
void createPipelines(VkSampler immutableSampler);
bool processFrame(AHardwareBuffer *buffer, float frameScore,
GrayImage &cachedGray);
void resetDescriptorHandles();
void releasePendingFrames();
};
@@ -27,6 +27,7 @@ import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asStateFlow
import com.hinnka.mycamera.livephoto.LivePhotoRecorder
import com.hinnka.mycamera.model.SafeImage
import com.hinnka.mycamera.processor.MultiFrameStacker
import com.hinnka.mycamera.utils.DeviceUtil
import com.hinnka.mycamera.utils.OrientationObserver
import com.hinnka.mycamera.video.CaptureMode
@@ -744,6 +745,20 @@ class Camera2Controller(private val context: Context) {
}
}, cameraHandler)
}
if ((state.value.useMFNR || state.value.useMFSR) &&
captureFormat != ImageFormat.RAW_SENSOR
) {
val prewarmOk = MultiFrameStacker.prewarmVulkanStacker(
width = captureSize.width,
height = captureSize.height,
enableSuperResolution = state.value.useMFSR,
)
PLog.i(
TAG,
"Vulkan stacker prewarm after ImageReader creation: size=${captureSize.width}x${captureSize.height}, SR=${state.value.useMFSR}, ok=$prewarmOk"
)
}
} else {
safeCloseImageReader(imageReader)
imageReader = null
@@ -32,6 +32,15 @@ data class RawStackResult(
object MultiFrameStacker {
private const val TAG = "MultiFrameStacker"
private data class CachedVulkanStacker(
val ptr: Long,
val width: Int,
val height: Int,
val enableSuperResolution: Boolean,
)
private var cachedVulkanStacker: CachedVulkanStacker? = null
init {
try {
System.loadLibrary("my-native-lib")
@@ -46,6 +55,7 @@ object MultiFrameStacker {
* @param images List of captured Images (YUV_420_888).
* @return Stacked Bitmap (ARGB_8888), or null if failed.
*/
@Synchronized
fun processBurst(
images: List<SafeImage>,
rotation: Int,
@@ -68,7 +78,7 @@ object MultiFrameStacker {
TAG,
"Starting Vulkan stacking process for ${images.size} frames ($width x $height). SR=$enableSuperResolution"
)
val stackerPtr = createVulkanStackerNative(width, height, enableSuperResolution)
val stackerPtr = obtainVulkanStacker(width, height, enableSuperResolution, resetForUse = true)
if (stackerPtr != 0L) {
try {
for (image in images) {
@@ -93,14 +103,17 @@ object MultiFrameStacker {
return null
}
processVulkanStackNative(stackerPtr, previewBitmap, rotation)
PLog.i(TAG, "Vulkan stacking completed in ${System.currentTimeMillis() - startTime}ms")
return previewBitmap
val processOk = processVulkanStackNative(stackerPtr, previewBitmap, rotation)
if (!processOk) {
PLog.w(TAG, "Vulkan stack processing failed, invalidating cached stacker")
invalidateCachedVulkanStacker(stackerPtr)
} else {
PLog.i(TAG, "Vulkan stacking completed in ${System.currentTimeMillis() - startTime}ms")
return previewBitmap
}
} catch (e: Exception) {
PLog.e(TAG, "Error during Vulkan stacking", e)
} finally {
releaseVulkanStackerNative(stackerPtr)
invalidateCachedVulkanStacker(stackerPtr)
}
}
}
@@ -159,6 +172,78 @@ object MultiFrameStacker {
}
}
@Synchronized
fun prewarmVulkanStacker(
width: Int,
height: Int,
enableSuperResolution: Boolean = false,
): Boolean {
val stackerPtr = obtainVulkanStacker(width, height, enableSuperResolution, resetForUse = false)
val success = stackerPtr != 0L
if (success) {
PLog.i(
TAG,
"Prewarmed Vulkan stacker for ${width}x$height SR=$enableSuperResolution"
)
}
return success
}
@Synchronized
fun releaseCachedVulkanStacker() {
cachedVulkanStacker?.let {
releaseVulkanStackerNative(it.ptr)
PLog.i(
TAG,
"Released cached Vulkan stacker for ${it.width}x${it.height} SR=${it.enableSuperResolution}"
)
}
cachedVulkanStacker = null
}
private fun obtainVulkanStacker(
width: Int,
height: Int,
enableSuperResolution: Boolean,
resetForUse: Boolean,
): Long {
val cached = cachedVulkanStacker
if (cached != null &&
cached.width == width &&
cached.height == height &&
cached.enableSuperResolution == enableSuperResolution
) {
if (!resetForUse || resetVulkanStackerNative(cached.ptr)) {
return cached.ptr
}
PLog.w(TAG, "Failed to reset cached Vulkan stacker, recreating")
releaseVulkanStackerNative(cached.ptr)
cachedVulkanStacker = null
} else if (cached != null) {
releaseVulkanStackerNative(cached.ptr)
cachedVulkanStacker = null
}
val stackerPtr = createVulkanStackerNative(width, height, enableSuperResolution)
if (stackerPtr != 0L) {
cachedVulkanStacker = CachedVulkanStacker(
ptr = stackerPtr,
width = width,
height = height,
enableSuperResolution = enableSuperResolution,
)
}
return stackerPtr
}
private fun invalidateCachedVulkanStacker(stackerPtr: Long) {
val cached = cachedVulkanStacker
if (cached != null && cached.ptr == stackerPtr) {
releaseVulkanStackerNative(stackerPtr)
cachedVulkanStacker = null
}
}
fun processBurstRaw(
images: List<SafeImage>,
cfaPattern: Int,
@@ -372,6 +457,7 @@ object MultiFrameStacker {
private external fun processVulkanStackNative(stackerPtr: Long, outBitmap: Bitmap?, rotation: Int): Boolean
private external fun releaseVulkanStackerNative(stackerPtr: Long)
private external fun resetVulkanStackerNative(stackerPtr: Long): Boolean
private external fun createRawStackerNative(width: Int, height: Int, enableSuperRes: Boolean): Long
private external fun stageRawFrameNative(stackerPtr: Long, rawData: ByteBuffer, rowStride: Int, cfaPattern: Int)