feat: radiance performance
This commit is contained in:
1 parent
c71e5c31d9
commit
433eca21ca
35 files changed
+1699
-1038
No files matched your search
+7
-12
@@ -111,20 +111,15 @@ class GlesRawRadianceStackerShaderTest {
|
||||
invokePrivate(stacker, "normalizeRadianceTile", tile, 1, 1)
|
||||
val chromaPostprocessor = readPrivateAny(stacker, "radianceVgnChromaPostprocessor")
|
||||
assertNotNull("Radiance must initialize its VGN chroma postprocessor", chromaPostprocessor)
|
||||
val postprocessor = checkNotNull(chromaPostprocessor)
|
||||
invokePrivate(
|
||||
postprocessor,
|
||||
"capture",
|
||||
readPrivateInt(stacker, "outputTexture"),
|
||||
tile,
|
||||
)
|
||||
val postprocessor =
|
||||
checkNotNull(chromaPostprocessor) as GlesRadianceVgnChromaPostprocessor
|
||||
postprocessor.markTileWritten(tile)
|
||||
val chromaOutput = ByteBuffer.allocateDirect(96 * 96 * 3 * 2)
|
||||
.order(ByteOrder.nativeOrder())
|
||||
val chromaResult = invokePrivate(
|
||||
postprocessor,
|
||||
"processAndReadback",
|
||||
chromaOutput,
|
||||
) as GlesRadianceVgnChromaPostprocessor.ProcessResult
|
||||
val chromaResult = postprocessor.process(
|
||||
obtainOutputBuffer = { chromaOutput },
|
||||
deferFullSizeReadback = false,
|
||||
)
|
||||
assertNotNull(chromaResult)
|
||||
assertEquals(0, chromaOutput.position())
|
||||
assertTrue(chromaResult.exportedTextureId != 0)
|
||||
|
||||
@@ -5499,6 +5499,10 @@ class Camera2Controller(private val context: Context) {
|
||||
_state.value = _state.value.copy(useJpgMaxHdrComposition = enabled)
|
||||
}
|
||||
|
||||
fun setUseRawMaxHdrComposition(enabled: Boolean) {
|
||||
_state.value = _state.value.copy(useRawMaxHdrComposition = enabled)
|
||||
}
|
||||
|
||||
|
||||
fun setCapturingLivePhoto(enabled: Boolean) {
|
||||
_state.value = _state.value.copy(isCapturingLivePhoto = enabled)
|
||||
@@ -6486,8 +6490,6 @@ class Camera2Controller(private val context: Context) {
|
||||
// Burst Mode
|
||||
val requestedFrameCount = currentState.multiFrameCount
|
||||
val frameCount = MultiFrameConfig.normalizeFrameCount(requestedFrameCount)
|
||||
val normalFrameCount = MultiFrameConfig.normalFrameCount(frameCount)
|
||||
val longFrameCount = MultiFrameConfig.longFrameCount(frameCount)
|
||||
if (frameCount != requestedFrameCount) {
|
||||
PLog.w(
|
||||
TAG,
|
||||
@@ -6496,9 +6498,13 @@ class Camera2Controller(private val context: Context) {
|
||||
}
|
||||
captureBuilder.setTag(MultiFrameCaptureRole.BASE)
|
||||
val baseRequest = captureBuilder.build()
|
||||
val requests = if (currentState.isJpgMaxEnabled || rawMaxFlashDenoise) {
|
||||
val useRawMaxHdrExposurePlan =
|
||||
currentState.isRawMaxHdrEnabled && !rawMaxFlashDenoise
|
||||
val requests = if (!useRawMaxHdrExposurePlan) {
|
||||
List(frameCount) { baseRequest }
|
||||
} else {
|
||||
val normalFrameCount = MultiFrameConfig.normalFrameCount(frameCount)
|
||||
val longFrameCount = MultiFrameConfig.longFrameCount(frameCount)
|
||||
val shortRequest = buildMultiFrameShortCaptureRequest(
|
||||
device = device,
|
||||
reader = reader,
|
||||
@@ -6551,6 +6557,12 @@ class Camera2Controller(private val context: Context) {
|
||||
"aeLock=${baseRequest.get(CaptureRequest.CONTROL_AE_LOCK)} " +
|
||||
"flashMode=${baseRequest.get(CaptureRequest.FLASH_MODE)}",
|
||||
)
|
||||
} else if (!useRawMaxHdrExposurePlan) {
|
||||
PLog.i(
|
||||
TAG,
|
||||
"RAWmax same-exposure burst plan: baseFrames=${requests.size} " +
|
||||
"hdr=false shortFrames=0 longFrames=0",
|
||||
)
|
||||
}
|
||||
|
||||
var completedCaptureCount = 0
|
||||
|
||||
@@ -347,6 +347,7 @@ data class CameraState(
|
||||
val multiFrameOutputScale: Float? = null,
|
||||
val multiFrameCount: Int = MultiFrameConfig.DEFAULT_FRAME_COUNT,
|
||||
val useJpgMaxHdrComposition: Boolean = false,
|
||||
val useRawMaxHdrComposition: Boolean = true,
|
||||
val useRaw: Boolean = false,
|
||||
val useMultipleExposure: Boolean = false,
|
||||
val rawMinShutterSpeedNs: Long = 0L,
|
||||
@@ -403,6 +404,9 @@ data class CameraState(
|
||||
val isRawMaxEnabled: Boolean
|
||||
get() = isMultiFrameEnabled && useRaw
|
||||
|
||||
val isRawMaxHdrEnabled: Boolean
|
||||
get() = isRawMaxEnabled && useRawMaxHdrComposition
|
||||
|
||||
/**
|
||||
* 获取当前相机信息
|
||||
*/
|
||||
|
||||
@@ -172,6 +172,7 @@ data class UserPreferences(
|
||||
val useMultipleExposure: Boolean = false, // 是否启用多重曝光
|
||||
val multipleExposureCount: Int = 2, // 多重曝光张数
|
||||
val useRawMax: Boolean = false, // RAWmax:RAW Radiance 管线
|
||||
val useRawMaxHdrComposition: Boolean = true, // RAWmax:包围曝光 HDR 融合
|
||||
val rawMaxOutputScale: Float = MultiFrameConfig.DEFAULT_SUPER_RESOLUTION_SCALE, // RAWmax 输出倍率
|
||||
val photoQuality: Int = 95, // 照片质量: 90, 95, 100
|
||||
val useHeicExport: Boolean = false, // 是否优先使用 HEIC 导出
|
||||
@@ -385,6 +386,8 @@ class UserPreferencesRepository(private val context: Context) {
|
||||
private val USE_JPG_MAX_HDR_COMPOSITION =
|
||||
booleanPreferencesKey("use_jpg_max_hdr_composition")
|
||||
private val USE_RAW_MAX = booleanPreferencesKey("use_raw_max")
|
||||
private val USE_RAW_MAX_HDR_COMPOSITION =
|
||||
booleanPreferencesKey("use_raw_max_hdr_composition")
|
||||
private val LEGACY_USE_MULTI_FRAME = booleanPreferencesKey("use_multi_frame")
|
||||
private val LEGACY_USE_HDR_COMPOSITION = booleanPreferencesKey("use_hdr_composition")
|
||||
private val MULTI_FRAME_COUNT = intPreferencesKey("multi_frame_count")
|
||||
@@ -609,6 +612,7 @@ class UserPreferencesRepository(private val context: Context) {
|
||||
useMultipleExposure = preferences[USE_MULTIPLE_EXPOSURE] ?: false,
|
||||
multipleExposureCount = preferences[MULTIPLE_EXPOSURE_COUNT] ?: 2,
|
||||
useRawMax = useRawMax,
|
||||
useRawMaxHdrComposition = preferences[USE_RAW_MAX_HDR_COMPOSITION] ?: true,
|
||||
rawMaxOutputScale = (preferences[RAW_MAX_OUTPUT_SCALE]
|
||||
?: preferences[LEGACY_RAW_SUPER_RESOLUTION_SCALE])?.let {
|
||||
MultiFrameConfig.normalizeOutputScale(
|
||||
@@ -1700,6 +1704,12 @@ class UserPreferencesRepository(private val context: Context) {
|
||||
}
|
||||
}
|
||||
|
||||
suspend fun saveUseRawMaxHdrComposition(enabled: Boolean) {
|
||||
context.dataStore.edit { preferences ->
|
||||
preferences[USE_RAW_MAX_HDR_COMPOSITION] = enabled
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 保存是否使用多重曝光
|
||||
*/
|
||||
|
||||
@@ -2786,9 +2786,12 @@ object GalleryManager {
|
||||
frameExposureProducts: List<Double?> = emptyList(),
|
||||
frameFocusDistances: List<Float?> = emptyList(),
|
||||
rawStackFrames: List<RawStackFrame> = emptyList(),
|
||||
rawMaxHdrFusionEnabled: Boolean = true,
|
||||
) = withContext(Dispatchers.IO) {
|
||||
var stackProcessor: RawDemosaicProcessor? = null
|
||||
var gpuSourceToRelease: GpuLinearRgbSource? = null
|
||||
var pendingDngWrite: Deferred<Boolean>? = null
|
||||
var releaseStackCpuBuffer: (() -> Unit)? = null
|
||||
try {
|
||||
val photoDir = getPhotoDir(context, photoId, true)
|
||||
|
||||
@@ -2885,6 +2888,7 @@ object GalleryManager {
|
||||
applyLensShadingCorrection = applyRawLensShading,
|
||||
useCurrentGlContext = true,
|
||||
exportGpuLinearRgbSource = true,
|
||||
enableHdrFusion = rawMaxHdrFusionEnabled,
|
||||
)
|
||||
}
|
||||
|
||||
@@ -2909,24 +2913,21 @@ object GalleryManager {
|
||||
"output=$outputRawBlackBorderCrop"
|
||||
)
|
||||
}
|
||||
val fusedBayerBuffer = finalStackResult.fusedBayerBuffer ?: return@withContext
|
||||
var fusedBufferReleased = false
|
||||
fun releaseFusedBuffer() {
|
||||
if (fusedBufferReleased) return
|
||||
fusedBufferReleased = true
|
||||
fun releaseInitialFusedBuffer() {
|
||||
val buffer = finalStackResult.fusedBayerBuffer ?: return
|
||||
finalStackResult.fusedBayerBuffer = null
|
||||
if (finalStackResult.fusedBayerUsesNativeAllocator) {
|
||||
LargeDirectBuffer.free(fusedBayerBuffer)
|
||||
PLog.d(TAG, "Released stacked RAW fused Bayer buffer")
|
||||
LargeDirectBuffer.free(buffer)
|
||||
PLog.d(TAG, "Released initial stacked RAW CPU buffer")
|
||||
}
|
||||
}
|
||||
releaseStackCpuBuffer = ::releaseInitialFusedBuffer
|
||||
|
||||
var updatedMetadata: MediaMetadata = stackedMetadata
|
||||
val rawSharpening = updatedMetadata.sharpening ?: RawSharpeningDefaults.forCapture(sharpeningValue)
|
||||
val rawNoiseReduction = resolveNoiseReduction(updatedMetadata, noiseReductionValue)
|
||||
val rawChromaNoiseReduction = updatedMetadata.chromaNoiseReduction
|
||||
?: ChromaDenoiseDefaults.forRawCapture(chromaNoiseReductionValue)
|
||||
var pendingDngWrite: Deferred<Boolean>? = null
|
||||
val rawResult = try {
|
||||
val imageLayout = finalStackResult.bufferLayout.toDngImageLayout()
|
||||
val inputSamplesPerPixel = finalStackResult.inputColStepSamples
|
||||
@@ -2948,8 +2949,9 @@ object GalleryManager {
|
||||
capturePreviewThumbnail = capturePreviewThumbnail,
|
||||
captureResult = captureResult,
|
||||
)
|
||||
val profileStartMs = System.currentTimeMillis()
|
||||
val dngProfilePreparation = RawProcessor.prepareRawDngProfile(
|
||||
rawBuffer = fusedBayerBuffer,
|
||||
rawBuffer = finalStackResult.fusedBayerBuffer,
|
||||
gpuLinearRgbSource = finalStackResult.gpuLinearRgbSource,
|
||||
width = finalStackResult.width,
|
||||
height = finalStackResult.height,
|
||||
@@ -2975,35 +2977,59 @@ object GalleryManager {
|
||||
PLog.e(TAG, "Failed to prepare shared RAW render/DNG profile")
|
||||
return@withContext
|
||||
}
|
||||
val profileElapsedMs = System.currentTimeMillis() - profileStartMs
|
||||
|
||||
suspend fun persistDng(): Boolean = trySaveStackedRawDng(
|
||||
context = context,
|
||||
photoId = photoId,
|
||||
dngFile = dngFile,
|
||||
fusedBayerBuffer = fusedBayerBuffer,
|
||||
width = finalStackResult.width,
|
||||
height = finalStackResult.height,
|
||||
rawMetadata = rawMetadata,
|
||||
stackBlackLevel = finalStackResult.blackLevel,
|
||||
stackWhiteLevel = stackWhiteLevel,
|
||||
isNormalizedSensorData = finalStackResult.isNormalizedSensorData,
|
||||
characteristics = characteristics,
|
||||
captureResult = captureResult,
|
||||
rotation = rotation,
|
||||
aspectRatio = aspectRatio,
|
||||
capturePreviewThumbnail = capturePreviewThumbnail,
|
||||
thumbnail = null,
|
||||
metadata = stackedMetadata,
|
||||
shouldAutoSave = shouldAutoSave,
|
||||
exportDngWithRawExport = exportDngWithRawExport,
|
||||
imageLayout = imageLayout,
|
||||
compression = finalStackResult.bufferLayout.toDngCompression(),
|
||||
inputRowStepSamples = inputRowStepSamples,
|
||||
inputColStepSamples = inputSamplesPerPixel,
|
||||
baselineExposureEv = finalStackResult.baselineExposureEv,
|
||||
preparedDngProfile = dngProfilePreparation,
|
||||
preparedProfileOptions = profileOptions,
|
||||
)
|
||||
suspend fun persistDng(fusedBayerBuffer: ByteBuffer): Boolean =
|
||||
trySaveStackedRawDng(
|
||||
context = context,
|
||||
photoId = photoId,
|
||||
dngFile = dngFile,
|
||||
fusedBayerBuffer = fusedBayerBuffer,
|
||||
width = finalStackResult.width,
|
||||
height = finalStackResult.height,
|
||||
rawMetadata = rawMetadata,
|
||||
stackBlackLevel = finalStackResult.blackLevel,
|
||||
stackWhiteLevel = stackWhiteLevel,
|
||||
isNormalizedSensorData = finalStackResult.isNormalizedSensorData,
|
||||
characteristics = characteristics,
|
||||
captureResult = captureResult,
|
||||
rotation = rotation,
|
||||
aspectRatio = aspectRatio,
|
||||
capturePreviewThumbnail = capturePreviewThumbnail,
|
||||
thumbnail = null,
|
||||
metadata = stackedMetadata,
|
||||
shouldAutoSave = shouldAutoSave,
|
||||
exportDngWithRawExport = exportDngWithRawExport,
|
||||
imageLayout = imageLayout,
|
||||
compression = finalStackResult.bufferLayout.toDngCompression(),
|
||||
inputRowStepSamples = inputRowStepSamples,
|
||||
inputColStepSamples = inputSamplesPerPixel,
|
||||
baselineExposureEv = finalStackResult.baselineExposureEv,
|
||||
preparedDngProfile = dngProfilePreparation,
|
||||
preparedProfileOptions = profileOptions,
|
||||
)
|
||||
|
||||
suspend fun materializeAndPersistDng(): Boolean {
|
||||
val initialBuffer = finalStackResult.fusedBayerBuffer
|
||||
val materializedBuffer = initialBuffer
|
||||
?: finalStackResult.gpuLinearRgbSource?.let { source ->
|
||||
processor.materializeGpuLinearRgbSource(source)
|
||||
}
|
||||
if (materializedBuffer == null) {
|
||||
PLog.e(TAG, "No CPU LinearRaw source available for stacked DNG")
|
||||
return false
|
||||
}
|
||||
return try {
|
||||
persistDng(materializedBuffer)
|
||||
} finally {
|
||||
if (materializedBuffer === finalStackResult.fusedBayerBuffer) {
|
||||
releaseInitialFusedBuffer()
|
||||
} else if (finalStackResult.fusedBayerUsesNativeAllocator) {
|
||||
LargeDirectBuffer.free(materializedBuffer)
|
||||
PLog.d(TAG, "Released deferred stacked RAW CPU buffer")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
suspend fun renderPersistedDng() = processor.processForHdrSources(
|
||||
context,
|
||||
@@ -3081,12 +3107,10 @@ object GalleryManager {
|
||||
renderMetadata != null && embeddedRenderPlan != null
|
||||
|
||||
if (canBypassDngPixels) {
|
||||
val parallelStartMs = System.currentTimeMillis()
|
||||
val dngWrite = async(Dispatchers.IO) { persistDng() }
|
||||
pendingDngWrite = dngWrite
|
||||
val renderStartMs = System.currentTimeMillis()
|
||||
val inMemoryResult = processor.processLinearDngBufferForHdrSources(
|
||||
context = context,
|
||||
rawData = fusedBayerBuffer,
|
||||
rawData = finalStackResult.fusedBayerBuffer,
|
||||
width = finalStackResult.width,
|
||||
height = finalStackResult.height,
|
||||
rowStride = checkNotNull(inputRowStepSamples) * Short.SIZE_BYTES,
|
||||
@@ -3130,26 +3154,39 @@ object GalleryManager {
|
||||
onMetadata = { raw -> updatedMetadata = updatedMetadata.merge(raw) },
|
||||
)
|
||||
val renderCompletedMs = System.currentTimeMillis()
|
||||
val dngWritten = dngWrite.await()
|
||||
val parallelCompletedMs = System.currentTimeMillis()
|
||||
PLog.i(
|
||||
TAG,
|
||||
"RAW_LINEAR_DNG_BYPASS timing render=${renderCompletedMs - parallelStartMs}ms " +
|
||||
"parallelTotal=${parallelCompletedMs - parallelStartMs}ms " +
|
||||
"writeTail=${parallelCompletedMs - renderCompletedMs}ms"
|
||||
"RAW GPU handoff timing profile=${profileElapsedMs}ms " +
|
||||
"render=${renderCompletedMs - renderStartMs}ms " +
|
||||
"cpuMaterializationBeforeRender=false",
|
||||
)
|
||||
if (!dngWritten) {
|
||||
inMemoryResult?.sdrBitmap?.takeIf { !it.isRecycled }?.recycle()
|
||||
inMemoryResult?.hdrReferenceBitmap?.takeIf { !it.isRecycled }?.recycle()
|
||||
PLog.e(TAG, "Failed to persist stacked RAW DNG")
|
||||
return@withContext
|
||||
}
|
||||
if (inMemoryResult != null) {
|
||||
PLog.i(TAG, "RAW_LINEAR_DNG_BYPASS completed with concurrent DNG write")
|
||||
pendingDngWrite = async(Dispatchers.IO) {
|
||||
try {
|
||||
val dngStartMs = System.currentTimeMillis()
|
||||
val written = materializeAndPersistDng()
|
||||
PLog.i(
|
||||
TAG,
|
||||
"Deferred stacked DNG timing total=" +
|
||||
"${System.currentTimeMillis() - dngStartMs}ms success=$written",
|
||||
)
|
||||
written
|
||||
} catch (error: Exception) {
|
||||
PLog.e(TAG, "Deferred stacked DNG task failed", error)
|
||||
false
|
||||
}
|
||||
}
|
||||
PLog.i(
|
||||
TAG,
|
||||
"RAW GPU render completed; deferred DNG materialization started",
|
||||
)
|
||||
inMemoryResult
|
||||
} else {
|
||||
PLog.w(TAG, "In-memory LinearRaw render failed; using persisted DNG fallback")
|
||||
releaseFusedBuffer()
|
||||
if (!materializeAndPersistDng()) {
|
||||
PLog.e(TAG, "Failed to persist stacked RAW DNG for render fallback")
|
||||
return@withContext
|
||||
}
|
||||
@Suppress("ExplicitGarbageCollectionCall")
|
||||
System.gc()
|
||||
renderPersistedDng() ?: return@withContext
|
||||
@@ -3162,27 +3199,20 @@ object GalleryManager {
|
||||
"bufferCompatible=$directBufferCompatible embeddedProfile=${embeddedRenderPlan != null}; " +
|
||||
"using persisted DNG"
|
||||
)
|
||||
if (!persistDng()) {
|
||||
if (!materializeAndPersistDng()) {
|
||||
PLog.e(TAG, "Failed to persist stacked RAW DNG before rendering preview")
|
||||
return@withContext
|
||||
}
|
||||
releaseFusedBuffer()
|
||||
@Suppress("ExplicitGarbageCollectionCall")
|
||||
System.gc()
|
||||
renderPersistedDng() ?: return@withContext
|
||||
}
|
||||
} finally {
|
||||
pendingDngWrite?.let { write ->
|
||||
if (!write.isCompleted) {
|
||||
withContext(NonCancellable) {
|
||||
runCatching { write.await() }
|
||||
.onFailure { error ->
|
||||
PLog.w(TAG, "Waiting for concurrent DNG write failed", error)
|
||||
}
|
||||
}
|
||||
}
|
||||
// A deferred DNG owns its materialized buffer. The initial buffer is released
|
||||
// here only when no DNG task consumed it (for example, an early render failure).
|
||||
if (pendingDngWrite == null) {
|
||||
releaseInitialFusedBuffer()
|
||||
}
|
||||
releaseFusedBuffer()
|
||||
}
|
||||
var bitmap = rawResult.sdrBitmap
|
||||
|
||||
@@ -3283,6 +3313,18 @@ object GalleryManager {
|
||||
PLog.e(TAG, "Failed to savePhoto", e)
|
||||
} finally {
|
||||
withContext(NonCancellable) {
|
||||
pendingDngWrite?.let { write ->
|
||||
runCatching { write.await() }
|
||||
.onSuccess { written ->
|
||||
if (!written) {
|
||||
PLog.e(TAG, "Deferred stacked DNG write did not complete successfully")
|
||||
}
|
||||
}
|
||||
.onFailure { error ->
|
||||
PLog.e(TAG, "Deferred stacked DNG write failed", error)
|
||||
}
|
||||
}
|
||||
releaseStackCpuBuffer?.invoke()
|
||||
stackProcessor?.releaseGpuLinearRgbSource(gpuSourceToRelease)
|
||||
}
|
||||
}
|
||||
@@ -3664,6 +3706,7 @@ object GalleryManager {
|
||||
frameExposureProducts: List<Double?> = emptyList(),
|
||||
frameFocusDistances: List<Float?> = emptyList(),
|
||||
rawStackFrames: List<RawStackFrame> = emptyList(),
|
||||
rawMaxHdrFusionEnabled: Boolean = true,
|
||||
) = withContext(Dispatchers.IO) {
|
||||
when (val format = images[0].format) {
|
||||
ImageFormat.YUV_420_888, ImageFormat.YCBCR_P010, ImageFormat.NV21 -> {
|
||||
@@ -3707,6 +3750,7 @@ object GalleryManager {
|
||||
frameExposureProducts,
|
||||
frameFocusDistances,
|
||||
rawStackFrames,
|
||||
rawMaxHdrFusionEnabled,
|
||||
)
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,174 @@
|
||||
package com.hinnka.mycamera.processor
|
||||
|
||||
import android.opengl.GLES30
|
||||
import com.hinnka.mycamera.utils.PLog
|
||||
|
||||
internal enum class GpuStackCompletionStage(val logKey: String) {
|
||||
NORMAL_ALIGNMENT("normalAlignment"),
|
||||
LONG_ALIGNMENT("longAlignment"),
|
||||
HIGHLIGHT_ALIGNMENT("highlightAlignment"),
|
||||
TILED_RECONSTRUCTION("tiledReconstruction"),
|
||||
CHROMA_POSTPROCESS("chromaPostprocess"),
|
||||
FINAL_EXPORT("finalExport"),
|
||||
}
|
||||
|
||||
internal data class GpuStackStageWait(
|
||||
val stage: GpuStackCompletionStage,
|
||||
val waitMs: Long,
|
||||
)
|
||||
|
||||
internal data class GpuStackQueueTiming(
|
||||
val stageWaits: List<GpuStackStageWait>,
|
||||
) {
|
||||
val totalWaitMs: Long = stageWaits.sumOf(GpuStackStageWait::waitMs)
|
||||
|
||||
fun logFields(): String = stageWaits.joinToString(separator = " ") {
|
||||
"${it.stage.logKey}=${it.waitMs}ms"
|
||||
}
|
||||
}
|
||||
|
||||
internal data class GpuStackCompletionCheckpoint(
|
||||
val stage: GpuStackCompletionStage,
|
||||
val sync: Long,
|
||||
)
|
||||
|
||||
/**
|
||||
* Ordered stacker completion checkpoints whose ownership follows the exported GPU texture.
|
||||
*
|
||||
* Checkpoints are inserted without waiting. The first CPU synchronization consumer waits them in
|
||||
* order, which attributes the outstanding queue tail to the stage that submitted it while the GPU
|
||||
* continues processing later checkpoints.
|
||||
*/
|
||||
class GpuStackCompletionTimeline internal constructor(
|
||||
private val checkpoints: MutableList<GpuStackCompletionCheckpoint>,
|
||||
) {
|
||||
internal fun awaitPending(
|
||||
syncPoint: String,
|
||||
checkGlError: (String) -> Unit,
|
||||
): GpuStackQueueTiming? {
|
||||
if (checkpoints.isEmpty()) return null
|
||||
val pending = checkpoints.toList()
|
||||
checkpoints.clear()
|
||||
val waits = ArrayList<GpuStackStageWait>(pending.size)
|
||||
try {
|
||||
pending.forEach { checkpoint ->
|
||||
val waitMs = GlesGpuCompletion.awaitSync(
|
||||
sync = checkpoint.sync,
|
||||
label = "RAW stack ${checkpoint.stage.logKey} at $syncPoint",
|
||||
)
|
||||
waits += GpuStackStageWait(checkpoint.stage, waitMs)
|
||||
}
|
||||
checkGlError("RAW stack completion timeline $syncPoint")
|
||||
} finally {
|
||||
pending.forEach { checkpoint ->
|
||||
GLES30.glDeleteSync(checkpoint.sync)
|
||||
}
|
||||
}
|
||||
return GpuStackQueueTiming(waits).also { timing ->
|
||||
PLog.i(
|
||||
TAG,
|
||||
"GLES RAW stacking GPU queue timing syncPoint=$syncPoint " +
|
||||
"total=${timing.totalWaitMs}ms ${timing.logFields()}",
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
internal fun releasePending() {
|
||||
checkpoints.forEach { checkpoint ->
|
||||
GLES30.glDeleteSync(checkpoint.sync)
|
||||
}
|
||||
checkpoints.clear()
|
||||
}
|
||||
|
||||
private companion object {
|
||||
const val TAG = "GlesGpuCompletion"
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Separates completion of previously submitted GPU work from the transfer that follows it.
|
||||
*
|
||||
* Measuring only glReadPixels() attributes all queued GPU work to "readback", because that call is
|
||||
* commonly the first synchronization point. Waiting on an explicit fence first makes subsequent
|
||||
* transfer timings describe the transfer itself instead of the whole pending command queue.
|
||||
*/
|
||||
internal object GlesGpuCompletion {
|
||||
private const val WAIT_SLICE_NS = 100_000_000L
|
||||
private const val TAG = "GlesGpuCompletion"
|
||||
|
||||
internal class StackTimelineRecorder {
|
||||
private val checkpoints = mutableListOf<GpuStackCompletionCheckpoint>()
|
||||
private var disabled = false
|
||||
private var ownershipTransferred = false
|
||||
|
||||
fun mark(stage: GpuStackCompletionStage) {
|
||||
if (disabled || ownershipTransferred) return
|
||||
val sync = GLES30.glFenceSync(GLES30.GL_SYNC_GPU_COMMANDS_COMPLETE, 0)
|
||||
if (sync == 0L) {
|
||||
PLog.w(
|
||||
TAG,
|
||||
"Unable to create RAW stack GPU checkpoint stage=${stage.logKey}; " +
|
||||
"stage timing disabled",
|
||||
)
|
||||
disabled = true
|
||||
releasePending()
|
||||
return
|
||||
}
|
||||
checkpoints += GpuStackCompletionCheckpoint(stage, sync)
|
||||
}
|
||||
|
||||
fun finish(): GpuStackCompletionTimeline? {
|
||||
if (disabled || ownershipTransferred || checkpoints.isEmpty()) {
|
||||
releasePending()
|
||||
return null
|
||||
}
|
||||
ownershipTransferred = true
|
||||
GLES30.glFlush()
|
||||
return GpuStackCompletionTimeline(checkpoints.toMutableList()).also {
|
||||
checkpoints.clear()
|
||||
}
|
||||
}
|
||||
|
||||
fun releasePending() {
|
||||
if (ownershipTransferred) return
|
||||
checkpoints.forEach { checkpoint ->
|
||||
GLES30.glDeleteSync(checkpoint.sync)
|
||||
}
|
||||
checkpoints.clear()
|
||||
}
|
||||
}
|
||||
|
||||
fun awaitSubmittedWork(label: String, checkGlError: (String) -> Unit): Long {
|
||||
val sync = GLES30.glFenceSync(GLES30.GL_SYNC_GPU_COMMANDS_COMPLETE, 0)
|
||||
check(sync != 0L) { "Unable to create GPU completion fence for $label" }
|
||||
GLES30.glFlush()
|
||||
try {
|
||||
val waitMs = awaitSync(sync, label)
|
||||
checkGlError("GPU completion fence $label")
|
||||
return waitMs
|
||||
} finally {
|
||||
GLES30.glDeleteSync(sync)
|
||||
}
|
||||
}
|
||||
|
||||
internal fun awaitSync(sync: Long, label: String): Long {
|
||||
val startNs = System.nanoTime()
|
||||
while (true) {
|
||||
when (
|
||||
GLES30.glClientWaitSync(
|
||||
sync,
|
||||
GLES30.GL_SYNC_FLUSH_COMMANDS_BIT,
|
||||
WAIT_SLICE_NS,
|
||||
)
|
||||
) {
|
||||
GLES30.GL_ALREADY_SIGNALED,
|
||||
GLES30.GL_CONDITION_SATISFIED -> break
|
||||
|
||||
GLES30.GL_TIMEOUT_EXPIRED -> Unit
|
||||
GLES30.GL_WAIT_FAILED -> error("GPU completion wait failed for $label")
|
||||
else -> error("Unexpected GPU completion wait result for $label")
|
||||
}
|
||||
}
|
||||
return (System.nanoTime() - startNs) / 1_000_000L
|
||||
}
|
||||
}
|
||||
+255
-464
File diff suppressed because it is too large.
Load diff
@@ -29,6 +29,7 @@ internal object RawRadianceExposurePlanner {
|
||||
frameRoles: List<RawBurstFrameRole> = List(exposureProducts.size) {
|
||||
RawBurstFrameRole.NORMAL
|
||||
},
|
||||
enableHdrFusion: Boolean = true,
|
||||
): RawRadianceExposurePlan {
|
||||
require(frameRoles.size == exposureProducts.size) {
|
||||
"Exposure products and frame roles must have the same size"
|
||||
@@ -42,6 +43,15 @@ internal object RawRadianceExposurePlanner {
|
||||
excludedIndices = IntArray(0),
|
||||
)
|
||||
}
|
||||
if (!enableHdrFusion) {
|
||||
return RawRadianceExposurePlan(
|
||||
baseExposureProduct = null,
|
||||
normalIndices = exposureProducts.indices.toList().toIntArray(),
|
||||
shortIndex = null,
|
||||
longIndices = IntArray(0),
|
||||
excludedIndices = IntArray(0),
|
||||
)
|
||||
}
|
||||
val taggedShortIndices = frameRoles.indices.filter { index ->
|
||||
frameRoles[index] == RawBurstFrameRole.HIGHLIGHT_SHORT
|
||||
}
|
||||
@@ -255,6 +265,7 @@ class GlesRawRadianceFusion(
|
||||
private val fusionTuning: RawRadianceFusionTuning = RawRadianceFusionTuning(),
|
||||
private val useCurrentGlContext: Boolean = false,
|
||||
private val exportGpuLinearRgbSource: Boolean = false,
|
||||
private val enableHdrFusion: Boolean = true,
|
||||
) {
|
||||
private val outputScale = MultiFrameConfig.normalizeOutputScale(outputScale)
|
||||
|
||||
@@ -263,6 +274,7 @@ class GlesRawRadianceFusion(
|
||||
val exposurePlan = RawRadianceExposurePlanner.plan(
|
||||
exposureProducts = frames.map { it.exposureProduct },
|
||||
frameRoles = frames.map { it.role },
|
||||
enableHdrFusion = enableHdrFusion,
|
||||
)
|
||||
exposurePlan.excludedIndices.forEach { index ->
|
||||
frames[index].image.close()
|
||||
@@ -306,8 +318,14 @@ class GlesRawRadianceFusion(
|
||||
"Radiance short frame has no usable exposure ratio; highlight reconstruction disabled",
|
||||
)
|
||||
shortFrame.image.close()
|
||||
} else {
|
||||
} else if (enableHdrFusion) {
|
||||
PLog.w(TAG, "Radiance fusion received no valid one-third short frame")
|
||||
} else {
|
||||
PLog.i(
|
||||
TAG,
|
||||
"RAWmax HDR fusion disabled; processing ${fusionFrames.size} same-exposure frames " +
|
||||
"without highlight or long-exposure resources",
|
||||
)
|
||||
}
|
||||
|
||||
val longFramePlans = if (PROCESS_LONG_FRAMES) {
|
||||
@@ -886,12 +904,8 @@ internal object GlesRawRadianceFusionShaders {
|
||||
precision highp float;
|
||||
precision highp int;
|
||||
layout(local_size_x = 16, local_size_y = 16) in;
|
||||
layout(r32ui, binding = 0) writeonly uniform highp uimage2D uNrSumRg;
|
||||
layout(r32ui, binding = 1) writeonly uniform highp uimage2D uNrSumBw;
|
||||
layout(r32ui, binding = 2) writeonly uniform highp uimage2D uNrWeightRg;
|
||||
layout(r32ui, binding = 3) writeonly uniform highp uimage2D uDetailSumRg;
|
||||
layout(r32ui, binding = 4) writeonly uniform highp uimage2D uDetailSumBw;
|
||||
layout(r32ui, binding = 5) writeonly uniform highp uimage2D uDetailWeightRg;
|
||||
layout(rgba16f, binding = 0) writeonly uniform highp image2D uNrAccumulator;
|
||||
layout(rgba16f, binding = 1) writeonly uniform highp image2D uDetailAccumulator;
|
||||
$rejectionDeclaration
|
||||
$longParticipationDeclaration
|
||||
uniform ivec2 uImageSize;
|
||||
@@ -899,12 +913,8 @@ internal object GlesRawRadianceFusionShaders {
|
||||
void main() {
|
||||
ivec2 p = ivec2(gl_GlobalInvocationID.xy);
|
||||
if (p.x >= uImageSize.x || p.y >= uImageSize.y) return;
|
||||
imageStore(uNrSumRg, p, uvec4(0u));
|
||||
imageStore(uNrSumBw, p, uvec4(0u));
|
||||
imageStore(uNrWeightRg, p, uvec4(0u));
|
||||
imageStore(uDetailSumRg, p, uvec4(0u));
|
||||
imageStore(uDetailSumBw, p, uvec4(0u));
|
||||
imageStore(uDetailWeightRg, p, uvec4(0u));
|
||||
imageStore(uNrAccumulator, p, vec4(0.0));
|
||||
imageStore(uDetailAccumulator, p, vec4(0.0));
|
||||
$rejectionClear
|
||||
$longParticipationClear
|
||||
}
|
||||
@@ -1143,8 +1153,11 @@ internal object GlesRawRadianceFusionShaders {
|
||||
}
|
||||
return """
|
||||
#version 310 es
|
||||
precision highp float;
|
||||
precision highp int;
|
||||
$rawCommon
|
||||
layout(local_size_x = 16, local_size_y = 16) in;
|
||||
layout(location = 0) out highp vec4 nrContribution;
|
||||
layout(location = 1) out highp vec4 detailContribution;
|
||||
uniform sampler2D uRcdRgbTile;
|
||||
uniform sampler2D uFlowGrid;
|
||||
uniform sampler2D uRobustness;
|
||||
@@ -1153,12 +1166,6 @@ internal object GlesRawRadianceFusionShaders {
|
||||
uniform sampler2D uLensShadingMap;
|
||||
uniform sampler2D uReferenceBase;
|
||||
uniform highp usampler2D uRawRegion;
|
||||
layout(r32ui, binding = 0) uniform highp uimage2D uNrSumRg;
|
||||
layout(r32ui, binding = 1) uniform highp uimage2D uNrSumBw;
|
||||
layout(r32ui, binding = 2) uniform highp uimage2D uNrWeightRg;
|
||||
layout(r32ui, binding = 3) uniform highp uimage2D uDetailSumRg;
|
||||
layout(r32ui, binding = 4) uniform highp uimage2D uDetailSumBw;
|
||||
layout(r32ui, binding = 5) uniform highp uimage2D uDetailWeightRg;
|
||||
$rejectionDeclaration
|
||||
$longParticipationDeclaration
|
||||
$participationDeclaration
|
||||
@@ -1460,7 +1467,9 @@ internal object GlesRawRadianceFusionShaders {
|
||||
}
|
||||
|
||||
void main() {
|
||||
ivec2 accumulatorP = ivec2(gl_GlobalInvocationID.xy);
|
||||
nrContribution = vec4(0.0);
|
||||
detailContribution = vec4(0.0);
|
||||
ivec2 accumulatorP = ivec2(gl_FragCoord.xy);
|
||||
ivec2 outputP = accumulatorP + uAccumulatorOrigin;
|
||||
if (accumulatorP.x >= uAccumulatorSize.x ||
|
||||
accumulatorP.y >= uAccumulatorSize.y ||
|
||||
@@ -1607,54 +1616,8 @@ internal object GlesRawRadianceFusionShaders {
|
||||
$participationStore
|
||||
$longParticipationStore
|
||||
|
||||
if (any(greaterThan(nrWeight, vec3(1e-7)))) {
|
||||
vec2 nrRg = unpackHalf2x16(imageLoad(uNrSumRg, accumulatorP).r);
|
||||
vec2 nrBw = unpackHalf2x16(imageLoad(uNrSumBw, accumulatorP).r);
|
||||
vec2 nrWeightRg = unpackHalf2x16(imageLoad(uNrWeightRg, accumulatorP).r);
|
||||
nrRg += rgb.denoise.rg * nrWeight.rg;
|
||||
nrBw += vec2(rgb.denoise.b * nrWeight.b, nrWeight.b);
|
||||
nrWeightRg += nrWeight.rg;
|
||||
imageStore(
|
||||
uNrSumRg,
|
||||
accumulatorP,
|
||||
uvec4(packHalf2x16(nrRg), 0u, 0u, 0u)
|
||||
);
|
||||
imageStore(
|
||||
uNrSumBw,
|
||||
accumulatorP,
|
||||
uvec4(packHalf2x16(nrBw), 0u, 0u, 0u)
|
||||
);
|
||||
imageStore(
|
||||
uNrWeightRg,
|
||||
accumulatorP,
|
||||
uvec4(packHalf2x16(nrWeightRg), 0u, 0u, 0u)
|
||||
);
|
||||
}
|
||||
if (any(greaterThan(detailWeight, vec3(1e-7)))) {
|
||||
vec2 detailRg = unpackHalf2x16(imageLoad(uDetailSumRg, accumulatorP).r);
|
||||
vec2 detailBw = unpackHalf2x16(imageLoad(uDetailSumBw, accumulatorP).r);
|
||||
vec2 detailWeightRg = unpackHalf2x16(
|
||||
imageLoad(uDetailWeightRg, accumulatorP).r
|
||||
);
|
||||
detailRg += rgb.detail.rg * detailWeight.rg;
|
||||
detailBw += vec2(rgb.detail.b * detailWeight.b, detailWeight.b);
|
||||
detailWeightRg += detailWeight.rg;
|
||||
imageStore(
|
||||
uDetailSumRg,
|
||||
accumulatorP,
|
||||
uvec4(packHalf2x16(detailRg), 0u, 0u, 0u)
|
||||
);
|
||||
imageStore(
|
||||
uDetailSumBw,
|
||||
accumulatorP,
|
||||
uvec4(packHalf2x16(detailBw), 0u, 0u, 0u)
|
||||
);
|
||||
imageStore(
|
||||
uDetailWeightRg,
|
||||
accumulatorP,
|
||||
uvec4(packHalf2x16(detailWeightRg), 0u, 0u, 0u)
|
||||
);
|
||||
}
|
||||
nrContribution = vec4(rgb.denoise * nrWeight.x, nrWeight.x);
|
||||
detailContribution = vec4(rgb.detail * detailWeight.x, detailWeight.x);
|
||||
}
|
||||
""".trimIndent()
|
||||
}
|
||||
@@ -1663,28 +1626,20 @@ internal object GlesRawRadianceFusionShaders {
|
||||
#version 310 es
|
||||
precision highp float;
|
||||
precision highp int;
|
||||
precision highp usampler2D;
|
||||
layout(local_size_x = 16, local_size_y = 16) in;
|
||||
uniform highp usampler2D uNrSumRg;
|
||||
uniform highp usampler2D uNrSumBw;
|
||||
uniform highp usampler2D uNrWeightRg;
|
||||
uniform highp sampler2D uNrAccumulator;
|
||||
layout(rgba16f, binding = 0) writeonly uniform highp image2D uReferenceBase;
|
||||
uniform ivec2 uImageSize;
|
||||
|
||||
void main() {
|
||||
ivec2 p = ivec2(gl_GlobalInvocationID.xy);
|
||||
if (p.x >= uImageSize.x || p.y >= uImageSize.y) return;
|
||||
vec2 rg = unpackHalf2x16(texelFetch(uNrSumRg, p, 0).r);
|
||||
vec2 bw = unpackHalf2x16(texelFetch(uNrSumBw, p, 0).r);
|
||||
vec2 weightRg = max(
|
||||
unpackHalf2x16(texelFetch(uNrWeightRg, p, 0).r),
|
||||
vec2(1e-6)
|
||||
);
|
||||
float weightB = max(bw.y, 1e-6);
|
||||
vec4 accumulated = texelFetch(uNrAccumulator, p, 0);
|
||||
float weight = max(accumulated.a, 1e-6);
|
||||
imageStore(
|
||||
uReferenceBase,
|
||||
p,
|
||||
vec4(clamp(vec3(rg / weightRg, bw.x / weightB), 0.0, 1.0), 1.0)
|
||||
vec4(clamp(accumulated.rgb / weight, 0.0, 1.0), 1.0)
|
||||
);
|
||||
}
|
||||
""".trimIndent()
|
||||
@@ -2036,15 +1991,10 @@ internal object GlesRawRadianceFusionShaders {
|
||||
#version 300 es
|
||||
precision highp float;
|
||||
precision highp int;
|
||||
precision highp usampler2D;
|
||||
in vec2 vTexCoord;
|
||||
layout(location = 0) out highp uvec4 fragColor;
|
||||
uniform highp usampler2D uNrSumRg;
|
||||
uniform highp usampler2D uNrSumBw;
|
||||
uniform highp usampler2D uNrWeightRg;
|
||||
uniform highp usampler2D uDetailSumRg;
|
||||
uniform highp usampler2D uDetailSumBw;
|
||||
uniform highp usampler2D uDetailWeightRg;
|
||||
uniform highp sampler2D uNrAccumulator;
|
||||
uniform highp sampler2D uDetailAccumulator;
|
||||
uniform sampler2D uReferenceBase;
|
||||
$rejectionUniforms
|
||||
$longParticipationUniform
|
||||
@@ -2105,37 +2055,19 @@ internal object GlesRawRadianceFusionShaders {
|
||||
), vec3(1e-10));
|
||||
}
|
||||
|
||||
WeightedRgb packedRgbWeightAt(
|
||||
highp usampler2D rgTexture,
|
||||
highp usampler2D bwTexture,
|
||||
highp usampler2D weightRgTexture,
|
||||
ivec2 p
|
||||
) {
|
||||
WeightedRgb accumulatedRgbAt(highp sampler2D accumulator, ivec2 p) {
|
||||
p = clampAccumulatorPos(p);
|
||||
vec2 rg = unpackHalf2x16(texelFetch(rgTexture, p, 0).r);
|
||||
vec2 bw = unpackHalf2x16(texelFetch(bwTexture, p, 0).r);
|
||||
vec2 weightRg = max(
|
||||
unpackHalf2x16(texelFetch(weightRgTexture, p, 0).r),
|
||||
vec2(0.0)
|
||||
);
|
||||
vec3 weight = vec3(weightRg, max(bw.y, 0.0));
|
||||
vec3 value = vec3(
|
||||
weight.r > 1e-7 ? rg.r / weight.r : 0.0,
|
||||
weight.g > 1e-7 ? rg.g / weight.g : 0.0,
|
||||
weight.b > 1e-7 ? bw.x / weight.b : 0.0
|
||||
);
|
||||
return WeightedRgb(clamp(value, 0.0, 1.0), weight);
|
||||
vec4 accumulated = texelFetch(accumulator, p, 0);
|
||||
float sharedWeight = max(accumulated.a, 0.0);
|
||||
vec3 value = sharedWeight > 1e-7 ?
|
||||
accumulated.rgb / sharedWeight : vec3(0.0);
|
||||
return WeightedRgb(clamp(value, 0.0, 1.0), vec3(sharedWeight));
|
||||
}
|
||||
|
||||
NrState nrStateAt(ivec2 p) {
|
||||
p = clampAccumulatorPos(p);
|
||||
vec3 base = referenceBaseAt(p);
|
||||
WeightedRgb sampleValue = packedRgbWeightAt(
|
||||
uNrSumRg,
|
||||
uNrSumBw,
|
||||
uNrWeightRg,
|
||||
p
|
||||
);
|
||||
WeightedRgb sampleValue = accumulatedRgbAt(uNrAccumulator, p);
|
||||
vec3 weight = sampleValue.weight;
|
||||
vec3 nr = vec3(
|
||||
weight.r > 1e-7 ? sampleValue.value.r : base.r,
|
||||
@@ -2209,12 +2141,7 @@ internal object GlesRawRadianceFusionShaders {
|
||||
gradient
|
||||
);
|
||||
|
||||
WeightedRgb detailSample = packedRgbWeightAt(
|
||||
uDetailSumRg,
|
||||
uDetailSumBw,
|
||||
uDetailWeightRg,
|
||||
p
|
||||
);
|
||||
WeightedRgb detailSample = accumulatedRgbAt(uDetailAccumulator, p);
|
||||
vec3 detail = vec3(
|
||||
detailSample.weight.r > 1e-7 ? detailSample.value.r : center.base.r,
|
||||
detailSample.weight.g > 1e-7 ? detailSample.value.g : center.base.g,
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
@@ -25,9 +25,11 @@ data class GpuLinearRgbSource(
|
||||
val width: Int,
|
||||
val height: Int,
|
||||
val samplesPerPixel: Int = 4,
|
||||
val stackCompletionTimeline: GpuStackCompletionTimeline? = null,
|
||||
)
|
||||
|
||||
data class RawStackResult(
|
||||
/** Null when a GPU source is exported and CPU/DNG materialization has been deferred. */
|
||||
var fusedBayerBuffer: ByteBuffer?,
|
||||
val width: Int,
|
||||
val height: Int,
|
||||
@@ -184,6 +186,7 @@ object MultiFrameStacker {
|
||||
applyLensShadingCorrection: Boolean = true,
|
||||
useCurrentGlContext: Boolean = false,
|
||||
exportGpuLinearRgbSource: Boolean = false,
|
||||
enableHdrFusion: Boolean = true,
|
||||
): RawStackResult? {
|
||||
if (frames.isEmpty()) return null
|
||||
val images = frames.map { it.image }
|
||||
@@ -218,6 +221,7 @@ object MultiFrameStacker {
|
||||
debugConfig = RawStackRuntimeDebug.debugConfig,
|
||||
useCurrentGlContext = useCurrentGlContext,
|
||||
exportGpuLinearRgbSource = exportGpuLinearRgbSource,
|
||||
enableHdrFusion = enableHdrFusion,
|
||||
).processFrames(frames)
|
||||
}
|
||||
|
||||
|
||||
@@ -68,6 +68,6 @@ data class RawStackDebugConfig(
|
||||
private const val ENABLE_RADIANCE_SR_DETAIL_OVERLAY = false
|
||||
private const val ENABLE_RADIANCE_HIGHLIGHT_RECONSTRUCTION_OVERLAY = false
|
||||
private const val ENABLE_RADIANCE_LONG_PARTICIPATION_OVERLAY = false
|
||||
private const val ENABLE_RADIANCE_FUSION_PARTICIPATION_LOG = true
|
||||
private const val ENABLE_RADIANCE_FUSION_PARTICIPATION_LOG = false
|
||||
}
|
||||
}
|
||||
@@ -22,12 +22,15 @@ import com.hinnka.mycamera.lut.ChromaDenoiseDefaults
|
||||
import com.hinnka.mycamera.lut.ChromaDenoiseShaders
|
||||
import com.hinnka.mycamera.lut.ShadowsHighlightsShader
|
||||
import com.hinnka.mycamera.ml.SharedDepthEstimator
|
||||
import com.hinnka.mycamera.processor.GlesGpuCompletion
|
||||
import com.hinnka.mycamera.processor.GlesGpuScheduler
|
||||
import com.hinnka.mycamera.processor.GlesRawRadianceStacker
|
||||
import com.hinnka.mycamera.processor.GpuLinearRgbSource
|
||||
import com.hinnka.mycamera.processor.GpuStackCompletionTimeline
|
||||
import com.hinnka.mycamera.processor.RawNoiseModel
|
||||
import com.hinnka.mycamera.processor.RawStackResult
|
||||
import com.hinnka.mycamera.utils.BitmapUtils
|
||||
import com.hinnka.mycamera.utils.DirectBufferPixelPacker
|
||||
import com.hinnka.mycamera.utils.LargeDirectBuffer
|
||||
import com.hinnka.mycamera.utils.PLog
|
||||
import com.hinnka.mycamera.utils.RawProcessor
|
||||
@@ -298,6 +301,7 @@ class RawDemosaicProcessor {
|
||||
captureHeight: Int,
|
||||
rawMaxFrameCount: Int,
|
||||
rawMaxEnabled: Boolean,
|
||||
rawMaxHdrCompositionEnabled: Boolean,
|
||||
): Boolean =
|
||||
withContext(glDispatcher) {
|
||||
val start = System.currentTimeMillis()
|
||||
@@ -345,8 +349,8 @@ class RawDemosaicProcessor {
|
||||
lensShadingHeight = 0,
|
||||
useCurrentGlContext = true,
|
||||
exportGpuLinearRgbSource = true,
|
||||
prewarmHighlightPrograms = true,
|
||||
prewarmLongPrograms = true,
|
||||
prewarmHighlightPrograms = rawMaxHdrCompositionEnabled,
|
||||
prewarmLongPrograms = rawMaxHdrCompositionEnabled,
|
||||
).prewarmCapturePipeline(rawMaxFrameCount)
|
||||
true
|
||||
}.onFailure { error ->
|
||||
@@ -362,7 +366,7 @@ class RawDemosaicProcessor {
|
||||
"RAW capture pipeline prewarmed ready=$ready engine=$colorEngine " +
|
||||
"profileToneMap=$profileToneMapMode " +
|
||||
"capture=${warmupWidth}x$warmupHeight rawMax=$rawMaxEnabled " +
|
||||
"frames=$rawMaxFrameCount " +
|
||||
"rawMaxHdr=$rawMaxHdrCompositionEnabled frames=$rawMaxFrameCount " +
|
||||
"took=${System.currentTimeMillis() - start}ms",
|
||||
)
|
||||
ready
|
||||
@@ -637,6 +641,7 @@ class RawDemosaicProcessor {
|
||||
internal suspend fun releaseGpuLinearRgbSource(source: GpuLinearRgbSource?) {
|
||||
if (source == null) return
|
||||
withContext(glDispatcher) {
|
||||
source.stackCompletionTimeline?.releasePending()
|
||||
if (exportedStackTextureIds.remove(source.textureId)) {
|
||||
GLES30.glDeleteTextures(1, intArrayOf(source.textureId), 0)
|
||||
checkGlError("release stacked LinearRaw texture")
|
||||
@@ -644,6 +649,162 @@ class RawDemosaicProcessor {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Materializes a stacked RGBA16UI texture as packed RGB16 only when a CPU/DNG consumer asks
|
||||
* for it. The foreground RAW renderer consumes the texture directly before this work starts.
|
||||
*/
|
||||
internal suspend fun materializeGpuLinearRgbSource(
|
||||
source: GpuLinearRgbSource,
|
||||
): ByteBuffer? = withContext(glDispatcher) {
|
||||
val valid = source.textureId != 0 &&
|
||||
source.width > 0 && source.height > 0 &&
|
||||
source.samplesPerPixel == 4 &&
|
||||
exportedStackTextureIds.contains(source.textureId)
|
||||
if (!valid) {
|
||||
PLog.e(
|
||||
TAG,
|
||||
"Unable to materialize invalid stacked GPU source texture=${source.textureId} " +
|
||||
"size=${source.width}x${source.height}x${source.samplesPerPixel}",
|
||||
)
|
||||
return@withContext null
|
||||
}
|
||||
|
||||
val totalStartNs = System.nanoTime()
|
||||
GLES31.glMemoryBarrier(
|
||||
GLES31.GL_SHADER_IMAGE_ACCESS_BARRIER_BIT or
|
||||
GLES31.GL_FRAMEBUFFER_BARRIER_BIT or
|
||||
GLES31.GL_TEXTURE_FETCH_BARRIER_BIT,
|
||||
)
|
||||
val upstreamStackTiming = source.stackCompletionTimeline?.awaitPending(
|
||||
syncPoint = "DNG_MATERIALIZATION",
|
||||
checkGlError = ::checkGlError,
|
||||
)
|
||||
val gpuQueueWaitMs = GlesGpuCompletion.awaitSubmittedWork(
|
||||
label = "stacked LinearRaw before DNG materialization",
|
||||
checkGlError = ::checkGlError,
|
||||
)
|
||||
|
||||
val tileEdge = 1024
|
||||
val scratchWidth = min(source.width, tileEdge)
|
||||
val scratchHeight = min(source.height, tileEdge)
|
||||
val outputBytes = source.width.toLong() * source.height.toLong() * 3L * Short.SIZE_BYTES
|
||||
val scratchBytes = scratchWidth.toLong() * scratchHeight.toLong() * 4L * Short.SIZE_BYTES
|
||||
val allocationStartNs = System.nanoTime()
|
||||
val output = LargeDirectBuffer.allocate(
|
||||
outputBytes,
|
||||
"Stacked LinearRaw deferred RGB16 materialization",
|
||||
)?.order(ByteOrder.nativeOrder()) ?: return@withContext null
|
||||
val scratch = LargeDirectBuffer.allocate(
|
||||
scratchBytes,
|
||||
"Stacked LinearRaw deferred RGBA16 tile",
|
||||
)?.order(ByteOrder.nativeOrder())
|
||||
if (scratch == null) {
|
||||
LargeDirectBuffer.free(output)
|
||||
return@withContext null
|
||||
}
|
||||
val allocationMs = (System.nanoTime() - allocationStartNs) / 1_000_000L
|
||||
|
||||
val framebufferIds = IntArray(1)
|
||||
GLES30.glGenFramebuffers(1, framebufferIds, 0)
|
||||
val framebuffer = framebufferIds[0]
|
||||
if (framebuffer == 0) {
|
||||
LargeDirectBuffer.free(scratch)
|
||||
LargeDirectBuffer.free(output)
|
||||
return@withContext null
|
||||
}
|
||||
|
||||
var pixelTransferMs = 0L
|
||||
var cpuPackMs = 0L
|
||||
var completed = false
|
||||
try {
|
||||
GLES30.glBindFramebuffer(GLES30.GL_FRAMEBUFFER, framebuffer)
|
||||
GLES30.glFramebufferTexture2D(
|
||||
GLES30.GL_FRAMEBUFFER,
|
||||
GLES30.GL_COLOR_ATTACHMENT0,
|
||||
GLES30.GL_TEXTURE_2D,
|
||||
source.textureId,
|
||||
0,
|
||||
)
|
||||
GLES30.glReadBuffer(GLES30.GL_COLOR_ATTACHMENT0)
|
||||
check(
|
||||
GLES30.glCheckFramebufferStatus(GLES30.GL_FRAMEBUFFER) ==
|
||||
GLES30.GL_FRAMEBUFFER_COMPLETE
|
||||
) { "Stacked LinearRaw materialization framebuffer is incomplete" }
|
||||
GLES30.glPixelStorei(GLES30.GL_PACK_ALIGNMENT, 8)
|
||||
|
||||
for (top in 0 until source.height step tileEdge) {
|
||||
val tileHeight = min(tileEdge, source.height - top)
|
||||
for (left in 0 until source.width step tileEdge) {
|
||||
val tileWidth = min(tileEdge, source.width - left)
|
||||
scratch.clear()
|
||||
val transferStartNs = System.nanoTime()
|
||||
GLES30.glReadPixels(
|
||||
left,
|
||||
top,
|
||||
tileWidth,
|
||||
tileHeight,
|
||||
GLES30.GL_RGBA_INTEGER,
|
||||
GLES30.GL_UNSIGNED_SHORT,
|
||||
scratch,
|
||||
)
|
||||
pixelTransferMs += (System.nanoTime() - transferStartNs) / 1_000_000L
|
||||
checkGlError("materialize stacked LinearRaw tile ($left,$top)")
|
||||
|
||||
val packStartNs = System.nanoTime()
|
||||
check(
|
||||
DirectBufferPixelPacker.unpackRgba16TileToRgb16(
|
||||
source = scratch,
|
||||
sourceWidth = tileWidth,
|
||||
sourceHeight = tileHeight,
|
||||
destination = output,
|
||||
destinationWidth = source.width,
|
||||
destinationHeight = source.height,
|
||||
destinationLeft = left,
|
||||
destinationTop = top,
|
||||
)
|
||||
) { "Unable to pack stacked LinearRaw tile ($left,$top)" }
|
||||
cpuPackMs += (System.nanoTime() - packStartNs) / 1_000_000L
|
||||
GlesGpuScheduler.yieldToUiRenderer()
|
||||
}
|
||||
}
|
||||
output.rewind()
|
||||
completed = true
|
||||
val totalMs = (System.nanoTime() - totalStartNs) / 1_000_000L
|
||||
val upstreamStackWaitMs = upstreamStackTiming?.totalWaitMs ?: 0L
|
||||
val accountedMs = upstreamStackWaitMs + gpuQueueWaitMs + allocationMs +
|
||||
pixelTransferMs + cpuPackMs
|
||||
PLog.i(
|
||||
TAG,
|
||||
"Stacked LinearRaw DNG materialization timing total=${totalMs}ms " +
|
||||
"upstreamStackGpuWait=${upstreamStackWaitMs}ms " +
|
||||
"materializationGpuWait=${gpuQueueWaitMs}ms " +
|
||||
"pixelTransfer=${pixelTransferMs}ms " +
|
||||
"cpuPack=${cpuPackMs}ms allocation=${allocationMs}ms " +
|
||||
"setup=${(totalMs - accountedMs).coerceAtLeast(0L)}ms " +
|
||||
"bytes=$outputBytes",
|
||||
)
|
||||
output
|
||||
} catch (error: Exception) {
|
||||
PLog.e(TAG, "Failed to materialize stacked LinearRaw GPU source", error)
|
||||
null
|
||||
} finally {
|
||||
GLES30.glPixelStorei(GLES30.GL_PACK_ALIGNMENT, 1)
|
||||
GLES30.glFramebufferTexture2D(
|
||||
GLES30.GL_FRAMEBUFFER,
|
||||
GLES30.GL_COLOR_ATTACHMENT0,
|
||||
GLES30.GL_TEXTURE_2D,
|
||||
0,
|
||||
0,
|
||||
)
|
||||
GLES30.glBindFramebuffer(GLES30.GL_FRAMEBUFFER, 0)
|
||||
GLES30.glDeleteFramebuffers(1, framebufferIds, 0)
|
||||
LargeDirectBuffer.free(scratch)
|
||||
if (!completed) {
|
||||
LargeDirectBuffer.free(output)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// EGL 资源
|
||||
private var eglDisplay: EGLDisplay = EGL14.EGL_NO_DISPLAY
|
||||
private var eglContext: EGLContext = EGL14.EGL_NO_CONTEXT
|
||||
@@ -1313,7 +1474,7 @@ class RawDemosaicProcessor {
|
||||
*/
|
||||
suspend fun processLinearDngBufferForHdrSources(
|
||||
context: Context,
|
||||
rawData: ByteBuffer,
|
||||
rawData: ByteBuffer?,
|
||||
width: Int,
|
||||
height: Int,
|
||||
rowStride: Int,
|
||||
@@ -1353,7 +1514,9 @@ class RawDemosaicProcessor {
|
||||
rawBlackBorderCrop: RawBlackBorderCrop = RawBlackBorderCrop(),
|
||||
onMetadata: ((RawMetadata) -> Unit)? = null,
|
||||
): RawHdrRenderResult? = withContext(glDispatcher) {
|
||||
if (samplesPerPixel !in 3..4 || width <= 0 || height <= 0 || rowStride <= 0) {
|
||||
if ((rawData == null && gpuLinearRgbSource == null) ||
|
||||
samplesPerPixel !in 3..4 || width <= 0 || height <= 0 || rowStride <= 0
|
||||
) {
|
||||
PLog.e(
|
||||
TAG,
|
||||
"Invalid in-memory LinearRaw DNG source: ${width}x$height " +
|
||||
@@ -1376,7 +1539,9 @@ class RawDemosaicProcessor {
|
||||
onMetadata?.invoke(renderMetadata)
|
||||
PLog.i(
|
||||
TAG,
|
||||
"RAW_LINEAR_DNG_BYPASS source=IN_MEMORY_RGB16 metadata=SHARED_DNG_PARAMS " +
|
||||
"RAW_LINEAR_DNG_BYPASS source=" +
|
||||
"${if (gpuLinearRgbSource != null) "GPU_STACK_TEXTURE" else "CPU_RGB16_BUFFER"} " +
|
||||
"metadata=SHARED_DNG_PARAMS " +
|
||||
"size=${width}x$height samplesPerPixel=$samplesPerPixel rowStride=$rowStride " +
|
||||
"baselineExposure=${renderMetadata.baselineExposure} " +
|
||||
"defaultCrop=${renderMetadata.defaultCrop} " +
|
||||
@@ -1394,7 +1559,7 @@ class RawDemosaicProcessor {
|
||||
try {
|
||||
processInternal(
|
||||
context = context,
|
||||
rawData = rawData.duplicate().order(ByteOrder.nativeOrder()),
|
||||
rawData = rawData?.duplicate()?.order(ByteOrder.nativeOrder()),
|
||||
width = width,
|
||||
height = height,
|
||||
rowStride = rowStride,
|
||||
@@ -1603,7 +1768,7 @@ class RawDemosaicProcessor {
|
||||
onMetadata?.invoke(actualMetadata)
|
||||
}
|
||||
|
||||
if (actualRawData == null || actualMetadata == null) {
|
||||
if ((actualRawData == null && borrowedGpuSource == null) || actualMetadata == null) {
|
||||
PLog.e(TAG, "Missing source data or metadata")
|
||||
return@withContext null
|
||||
}
|
||||
@@ -1768,7 +1933,14 @@ class RawDemosaicProcessor {
|
||||
} else {
|
||||
emptyList()
|
||||
}
|
||||
if (highResolutionOutput && tileBlockingReason != null) {
|
||||
if (highResolutionOutput && borrowedGpuSource != null) {
|
||||
PLog.i(
|
||||
TAG,
|
||||
"RAW render path=GPU_FULL_FRAME source=STACKED_TEXTURE " +
|
||||
"size=${outputSourceBounds.width()}x${outputSourceBounds.height()} " +
|
||||
"tiledCpuUpload=false",
|
||||
)
|
||||
} else if (highResolutionOutput && tileBlockingReason != null) {
|
||||
PLog.w(
|
||||
TAG,
|
||||
"RAW tiled rendering unavailable for this pipeline: $tileBlockingReason; " +
|
||||
@@ -1811,7 +1983,7 @@ class RawDemosaicProcessor {
|
||||
)
|
||||
} else if (actualSamplesPerPixel in 3..4) {
|
||||
uploadLinearRawRgbTextureFromBuffer(
|
||||
actualRawData,
|
||||
requireNotNull(actualRawData),
|
||||
actualWidth,
|
||||
actualHeight,
|
||||
actualRowStride,
|
||||
@@ -1819,7 +1991,7 @@ class RawDemosaicProcessor {
|
||||
)
|
||||
} else {
|
||||
uploadRawTextureFromBuffer(
|
||||
actualRawData,
|
||||
requireNotNull(actualRawData),
|
||||
actualWidth,
|
||||
actualHeight,
|
||||
actualRowStride,
|
||||
@@ -2208,6 +2380,7 @@ class RawDemosaicProcessor {
|
||||
supportProfileOverrange = supportProfileOverrange,
|
||||
hueSatMapSupportsOverrange = hueSatMapSupportsOverrange,
|
||||
hncsCameraDomainGains = hncsCameraDomainGains,
|
||||
stackCompletionTimeline = borrowedGpuSource?.stackCompletionTimeline,
|
||||
)
|
||||
}
|
||||
solvedExposureEv?.let { exposureEv ->
|
||||
@@ -2559,10 +2732,25 @@ class RawDemosaicProcessor {
|
||||
}
|
||||
sharpenWidth = 0; sharpenHeight = 0
|
||||
|
||||
// 8. 读取结果
|
||||
// 8. 读取结果。先单独等待 GPU,避免把前面所有异步 shader 工作记到 readPixels。
|
||||
val upstreamStackTiming = borrowedGpuSource?.stackCompletionTimeline?.awaitPending(
|
||||
syncPoint = "RAW_DISPLAY_OUTPUT",
|
||||
checkGlError = ::checkGlError,
|
||||
)
|
||||
val outputGpuQueueWaitMs = GlesGpuCompletion.awaitSubmittedWork(
|
||||
label = "RAW display output",
|
||||
checkGlError = ::checkGlError,
|
||||
)
|
||||
val readStart = System.currentTimeMillis()
|
||||
val finalBitmap = readPixels(finalWidth, finalHeight, workingColorSpace)
|
||||
PLog.d(TAG, "readPixels took: ${System.currentTimeMillis() - readStart}ms")
|
||||
val outputMaterializationMs = System.currentTimeMillis() - readStart
|
||||
PLog.d(
|
||||
TAG,
|
||||
"RAW output materialization timing " +
|
||||
"upstreamStackGpuWait=${upstreamStackTiming?.totalWaitMs ?: 0L}ms " +
|
||||
"renderGpuQueueWait=${outputGpuQueueWaitMs}ms " +
|
||||
"pixelTransferAndBitmap=${outputMaterializationMs}ms",
|
||||
)
|
||||
|
||||
PLog.d(TAG, "RAW processing complete: ${finalBitmap?.width}x${finalBitmap?.height}")
|
||||
finalBitmap?.let {
|
||||
@@ -11097,6 +11285,7 @@ class RawDemosaicProcessor {
|
||||
supportProfileOverrange: Boolean,
|
||||
hueSatMapSupportsOverrange: Boolean,
|
||||
hncsCameraDomainGains: FloatArray? = null,
|
||||
stackCompletionTimeline: GpuStackCompletionTimeline? = null,
|
||||
): Float? {
|
||||
val previewSize = resolveLongEdgePreviewSize(
|
||||
sourceWidth = metadata.width,
|
||||
@@ -11162,7 +11351,11 @@ class RawDemosaicProcessor {
|
||||
PLog.i(
|
||||
TAG,
|
||||
"RAW_VIEWFINDER_BASELINE stage=METERING_SOURCE " +
|
||||
"source=WRITER_INPUT_BUFFER " +
|
||||
"source=${if (exportedStackTextureIds.contains(sourceTextureId)) {
|
||||
"GPU_STACK_TEXTURE"
|
||||
} else {
|
||||
"WRITER_INPUT_BUFFER"
|
||||
}} " +
|
||||
"layout=${if (samplesPerPixel >= 3) "LINEAR_RAW_RGB" else "CFA_RAW"} " +
|
||||
"samplesPerPixel=$samplesPerPixel size=${metadata.width}x${metadata.height} " +
|
||||
"sourceBaselineEv=$sourceBaselineEv " +
|
||||
@@ -11240,6 +11433,7 @@ class RawDemosaicProcessor {
|
||||
readbackHeight = request.height.coerceAtLeast(1),
|
||||
outputRotation = outputRotation,
|
||||
readbackBuffer = readbackBuffer,
|
||||
stackCompletionTimeline = stackCompletionTimeline,
|
||||
)
|
||||
}
|
||||
} finally {
|
||||
@@ -11353,7 +11547,8 @@ class RawDemosaicProcessor {
|
||||
readbackWidth: Int,
|
||||
readbackHeight: Int,
|
||||
outputRotation: Int,
|
||||
readbackBuffer: ByteBuffer
|
||||
readbackBuffer: ByteBuffer,
|
||||
stackCompletionTimeline: GpuStackCompletionTimeline?,
|
||||
): RawExposurePreviewFrame? {
|
||||
val clampedExposureEv = exposureEv.coerceIn(-4f, 4f)
|
||||
val profileExposureUniforms = computeProfileExposureUniforms(
|
||||
@@ -11401,7 +11596,8 @@ class RawDemosaicProcessor {
|
||||
return readExposurePreviewFrame(
|
||||
width = readbackWidth,
|
||||
height = readbackHeight,
|
||||
pixelBuffer = readbackBuffer
|
||||
pixelBuffer = readbackBuffer,
|
||||
stackCompletionTimeline = stackCompletionTimeline,
|
||||
)
|
||||
}
|
||||
|
||||
@@ -11468,7 +11664,8 @@ class RawDemosaicProcessor {
|
||||
private fun readExposurePreviewFrame(
|
||||
width: Int,
|
||||
height: Int,
|
||||
pixelBuffer: ByteBuffer
|
||||
pixelBuffer: ByteBuffer,
|
||||
stackCompletionTimeline: GpuStackCompletionTimeline?,
|
||||
): RawExposurePreviewFrame? {
|
||||
if (width <= 0 || height <= 0) {
|
||||
return null
|
||||
@@ -11478,6 +11675,15 @@ class RawDemosaicProcessor {
|
||||
pixelBuffer.limit(pixelCount * 4)
|
||||
GLES30.glBindFramebuffer(GLES30.GL_FRAMEBUFFER, srgbExposurePreviewFramebufferId)
|
||||
GLES30.glPixelStorei(GLES30.GL_PACK_ALIGNMENT, 1)
|
||||
val upstreamStackTiming = stackCompletionTimeline?.awaitPending(
|
||||
syncPoint = "RAW_EXPOSURE_PREVIEW",
|
||||
checkGlError = ::checkGlError,
|
||||
)
|
||||
val previewGpuQueueWaitMs = GlesGpuCompletion.awaitSubmittedWork(
|
||||
label = "RAW exposure preview ${width}x$height",
|
||||
checkGlError = ::checkGlError,
|
||||
)
|
||||
val pixelTransferStartNs = System.nanoTime()
|
||||
GLES30.glReadPixels(
|
||||
0,
|
||||
0,
|
||||
@@ -11487,9 +11693,11 @@ class RawDemosaicProcessor {
|
||||
GLES30.GL_UNSIGNED_BYTE,
|
||||
pixelBuffer
|
||||
)
|
||||
val pixelTransferMs = (System.nanoTime() - pixelTransferStartNs) / 1_000_000L
|
||||
checkGlError("RAW exposure preview readback")
|
||||
pixelBuffer.position(0)
|
||||
|
||||
val cpuPackStartNs = System.nanoTime()
|
||||
val argbPixels = IntArray(pixelCount)
|
||||
for (i in 0 until pixelCount) {
|
||||
val r = pixelBuffer.get().toInt() and 0xff
|
||||
@@ -11498,6 +11706,15 @@ class RawDemosaicProcessor {
|
||||
val a = pixelBuffer.get().toInt() and 0xff
|
||||
argbPixels[i] = (a shl 24) or (r shl 16) or (g shl 8) or b
|
||||
}
|
||||
val cpuPackMs = (System.nanoTime() - cpuPackStartNs) / 1_000_000L
|
||||
PLog.d(
|
||||
TAG,
|
||||
"RAW exposure preview timing size=${width}x$height " +
|
||||
"upstreamStackGpuWait=${upstreamStackTiming?.totalWaitMs ?: 0L}ms " +
|
||||
"previewGpuQueueWait=${previewGpuQueueWaitMs}ms " +
|
||||
"pixelTransfer=${pixelTransferMs}ms " +
|
||||
"cpuPack=${cpuPackMs}ms",
|
||||
)
|
||||
return RawExposurePreviewFrame(
|
||||
width = width,
|
||||
height = height,
|
||||
|
||||
@@ -16,7 +16,7 @@ fun interface RawDngCaptureProfilePreparer {
|
||||
}
|
||||
|
||||
data class RawDngCaptureProfileInput(
|
||||
val rawData: ByteBuffer,
|
||||
val rawData: ByteBuffer?,
|
||||
val width: Int,
|
||||
val height: Int,
|
||||
val rowStride: Int,
|
||||
|
||||
@@ -294,6 +294,7 @@ fun SettingsScreen(
|
||||
val logicalCameraBindingWhitelist by viewModel.logicalCameraBindingWhitelist.collectAsState(initial = emptyList())
|
||||
val multiFrameCount by viewModel.multiFrameCount.collectAsState()
|
||||
val useJpgMaxHdrComposition by viewModel.useJpgMaxHdrComposition.collectAsState()
|
||||
val useRawMaxHdrComposition by viewModel.useRawMaxHdrComposition.collectAsState()
|
||||
val useMultipleExposure by viewModel.useMultipleExposure.collectAsState()
|
||||
val multipleExposureCount by viewModel.multipleExposureCount.collectAsState()
|
||||
val useLivePhoto by viewModel.useLivePhoto.collectAsState()
|
||||
@@ -1609,6 +1610,18 @@ fun SettingsScreen(
|
||||
modifier = Modifier.padding(vertical = 12.dp)
|
||||
)
|
||||
|
||||
SwitchSettingItem(
|
||||
title = stringResource(R.string.settings_raw_max_hdr_composition),
|
||||
description = stringResource(R.string.settings_raw_max_hdr_composition_description),
|
||||
checked = useRawMaxHdrComposition,
|
||||
onCheckedChange = viewModel::setUseRawMaxHdrComposition
|
||||
)
|
||||
|
||||
HorizontalDivider(
|
||||
color = Color.White.copy(alpha = 0.1f),
|
||||
modifier = Modifier.padding(vertical = 12.dp)
|
||||
)
|
||||
|
||||
SliderSettingItem(
|
||||
title = stringResource(R.string.settings_max_frame_count),
|
||||
description = stringResource(R.string.settings_max_frame_count_description),
|
||||
@@ -2676,6 +2689,7 @@ private fun SettingsCategoryOverview(
|
||||
title = stringResource(R.string.settings_section_multiframe_exposure),
|
||||
description = listOf(
|
||||
stringResource(R.string.settings_jpg_max_hdr_composition),
|
||||
stringResource(R.string.settings_raw_max_hdr_composition),
|
||||
stringResource(R.string.settings_max_frame_count),
|
||||
stringResource(R.string.settings_multiple_exposure_count)
|
||||
).joinToString(" · "),
|
||||
|
||||
@@ -483,7 +483,7 @@ object RawProcessor {
|
||||
}
|
||||
|
||||
suspend fun prepareRawDngProfile(
|
||||
rawBuffer: ByteBuffer,
|
||||
rawBuffer: ByteBuffer?,
|
||||
gpuLinearRgbSource: GpuLinearRgbSource? = null,
|
||||
width: Int,
|
||||
height: Int,
|
||||
@@ -566,7 +566,7 @@ object RawProcessor {
|
||||
)
|
||||
val captureProfile = options.captureProfilePreparer?.prepare(
|
||||
com.hinnka.mycamera.raw.RawDngCaptureProfileInput(
|
||||
rawData = rawBuffer.duplicate().order(ByteOrder.nativeOrder()),
|
||||
rawData = rawBuffer?.duplicate()?.order(ByteOrder.nativeOrder()),
|
||||
width = width,
|
||||
height = height,
|
||||
rowStride = inputRowStrideBytes,
|
||||
|
||||
@@ -1277,6 +1277,9 @@ class CameraViewModel(application: Application) : AndroidViewModel(application)
|
||||
val useRawMax: StateFlow<Boolean> = userPreferencesRepository.userPreferences
|
||||
.map { it.useRawMax }
|
||||
.stateIn(viewModelScope, SharingStarted.Eagerly, false)
|
||||
val useRawMaxHdrComposition: StateFlow<Boolean> = userPreferencesRepository.userPreferences
|
||||
.map { it.useRawMaxHdrComposition }
|
||||
.stateIn(viewModelScope, SharingStarted.Eagerly, true)
|
||||
val rawMaxOutputScale: StateFlow<Float> = userPreferencesRepository.userPreferences
|
||||
.map {
|
||||
MultiFrameConfig.normalizeOutputScale(
|
||||
@@ -1498,10 +1501,12 @@ class CameraViewModel(application: Application) : AndroidViewModel(application)
|
||||
val chronologicalFrames = pendingRawStackFrames
|
||||
.sortedBy { it.frame.sensorTimestampNs }
|
||||
pendingRawStackFrames.clear()
|
||||
val rawMaxHdrFusionEnabled = state.value.isRawMaxHdrEnabled
|
||||
viewModelScope.launch {
|
||||
val exposurePlan = RawRadianceExposurePlanner.plan(
|
||||
exposureProducts = chronologicalFrames.map { it.frame.exposureProduct },
|
||||
frameRoles = chronologicalFrames.map { it.frame.role },
|
||||
enableHdrFusion = rawMaxHdrFusionEnabled,
|
||||
)
|
||||
val normalFrames = exposurePlan.normalIndices.map(chronologicalFrames::get)
|
||||
val auxiliaryFrames = chronologicalFrames.indices
|
||||
@@ -1558,6 +1563,7 @@ class CameraViewModel(application: Application) : AndroidViewModel(application)
|
||||
captureInfo = referenceCaptureInfo,
|
||||
characteristics = characteristics,
|
||||
captureResult = referenceCaptureResult,
|
||||
rawMaxHdrFusionEnabled = rawMaxHdrFusionEnabled,
|
||||
)
|
||||
}
|
||||
}
|
||||
@@ -1680,6 +1686,9 @@ class CameraViewModel(application: Application) : AndroidViewModel(application)
|
||||
if (currentCameraState.useJpgMaxHdrComposition != it.useJpgMaxHdrComposition) {
|
||||
cameraController.setUseJpgMaxHdrComposition(it.useJpgMaxHdrComposition)
|
||||
}
|
||||
if (currentCameraState.useRawMaxHdrComposition != it.useRawMaxHdrComposition) {
|
||||
cameraController.setUseRawMaxHdrComposition(it.useRawMaxHdrComposition)
|
||||
}
|
||||
if (multipleExposureEnabled && (it.useRaw || it.useJpgMax || it.useRawMax)) {
|
||||
viewModelScope.launch {
|
||||
userPreferencesRepository.saveCameraFeaturePreferences(
|
||||
@@ -1884,6 +1893,7 @@ class CameraViewModel(application: Application) : AndroidViewModel(application)
|
||||
)
|
||||
cameraController.setMultiFrameCount(prefs.multiFrameCount)
|
||||
cameraController.setUseJpgMaxHdrComposition(prefs.useJpgMaxHdrComposition)
|
||||
cameraController.setUseRawMaxHdrComposition(prefs.useRawMaxHdrComposition)
|
||||
cameraController.setUseLivePhoto(
|
||||
prefs.useLivePhoto && !prefs.useJpgMax && prefs.captureMode == CaptureMode.PHOTO
|
||||
)
|
||||
@@ -2226,9 +2236,17 @@ class CameraViewModel(application: Application) : AndroidViewModel(application)
|
||||
val currentState = state.value
|
||||
val captureSize = currentState.currentCaptureSize
|
||||
val rawCaptureEnabled = prefs?.useRaw == true
|
||||
val rawMaxFrameCount = MultiFrameConfig.normalFrameCount(
|
||||
val rawMaxEnabled = currentState.isRawMaxEnabled
|
||||
val rawMaxHdrCompositionEnabled =
|
||||
rawMaxEnabled && (prefs?.useRawMaxHdrComposition ?: true)
|
||||
val totalRawMaxFrameCount = MultiFrameConfig.normalizeFrameCount(
|
||||
prefs?.multiFrameCount ?: MultiFrameConfig.DEFAULT_FRAME_COUNT,
|
||||
)
|
||||
val rawMaxFrameCount = if (rawMaxHdrCompositionEnabled) {
|
||||
MultiFrameConfig.normalFrameCount(totalRawMaxFrameCount)
|
||||
} else {
|
||||
totalRawMaxFrameCount
|
||||
}
|
||||
supervisorScope {
|
||||
val dcpPrewarmJob = if (rawCaptureEnabled) {
|
||||
async {
|
||||
@@ -2256,7 +2274,8 @@ class CameraViewModel(application: Application) : AndroidViewModel(application)
|
||||
captureWidth = captureSize.width,
|
||||
captureHeight = captureSize.height,
|
||||
rawMaxFrameCount = rawMaxFrameCount,
|
||||
rawMaxEnabled = currentState.isMultiFrameEnabled,
|
||||
rawMaxEnabled = rawMaxEnabled,
|
||||
rawMaxHdrCompositionEnabled = rawMaxHdrCompositionEnabled,
|
||||
)
|
||||
}.onFailure { error ->
|
||||
if (error is CancellationException) throw error
|
||||
@@ -3928,6 +3947,13 @@ class CameraViewModel(application: Application) : AndroidViewModel(application)
|
||||
}
|
||||
}
|
||||
|
||||
fun setUseRawMaxHdrComposition(enabled: Boolean) {
|
||||
cameraController.setUseRawMaxHdrComposition(enabled)
|
||||
viewModelScope.launch {
|
||||
userPreferencesRepository.saveUseRawMaxHdrComposition(enabled)
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 设置多帧合成帧数
|
||||
*/
|
||||
@@ -5332,6 +5358,7 @@ class CameraViewModel(application: Application) : AndroidViewModel(application)
|
||||
captureInfo: CaptureInfo,
|
||||
characteristics: CameraCharacteristics?,
|
||||
captureResult: CaptureResult?,
|
||||
rawMaxHdrFusionEnabled: Boolean,
|
||||
) {
|
||||
try {
|
||||
val images = frames.map { it.image }
|
||||
@@ -5534,6 +5561,7 @@ class CameraViewModel(application: Application) : AndroidViewModel(application)
|
||||
exportDngWithRawExport = exportDngWithRawExport.value,
|
||||
capturePreviewThumbnail = previewThumbnail,
|
||||
rawStackFrames = frames,
|
||||
rawMaxHdrFusionEnabled = rawMaxHdrFusionEnabled,
|
||||
)
|
||||
}
|
||||
PLog.d(TAG, "Image saved: $photoId, LUT: $lutIdToSave, Frame: $frameIdToSave")
|
||||
|
||||
@@ -196,6 +196,8 @@
|
||||
<string name="settings_jpg_max_hdr_composition">JPGmax HDR 合成</string>
|
||||
<string name="settings_jpg_max_hdr_composition_description">在 JPGmax 中使用包圍曝光進行 HDR 融合。拍攝時請保持手部穩定或使用三腳架。關閉時,JPGmax 只進行多幀降噪。</string>
|
||||
<string name="settings_use_raw_max">RAWmax</string>
|
||||
<string name="settings_raw_max_hdr_composition">RAWmax HDR 合成</string>
|
||||
<string name="settings_raw_max_hdr_composition_description">在 RAWmax 中使用包圍曝光進行 HDR 融合。關閉可提升處理效能。</string>
|
||||
<string name="settings_use_multiple_exposure">多重曝光</string>
|
||||
<string name="multiple_exposure_finish">完成</string>
|
||||
<string name="multiple_exposure_undo">復原</string>
|
||||
|
||||
@@ -247,4 +247,6 @@
|
||||
<string name="settings_use_p010">P010 (10-Bit YUV)</string>
|
||||
<string name="settings_use_p010_description">Aktiviert die 10-Bit YUV-Ausgabe für eine bessere Bildpräzision. Wirksam auf unterstützten Geräten, wenn RAW deaktiviert ist.</string>
|
||||
<string name="settings_raw_color_engine_hncs_description">Hasselblad Natural Colour Solution: ein von Hasselblad unabhängig entwickeltes Farbmanagementsystem</string>
|
||||
<string name="settings_raw_max_hdr_composition">RAWmax-HDR-Zusammenführung</string>
|
||||
<string name="settings_raw_max_hdr_composition_description">Verwendet Belichtungsreihen für die HDR-Zusammenführung in RAWmax. Das Deaktivieren verbessert die Verarbeitungsgeschwindigkeit.</string>
|
||||
</resources>
|
||||
@@ -247,4 +247,6 @@
|
||||
<string name="settings_use_p010">P010 (YUV 10 bits)</string>
|
||||
<string name="settings_use_p010_description">Active la sortie YUV 10 bits pour une meilleure précision des données d\'image. Efficace sur les appareils compatibles lorsque le mode RAW est désactivé.</string>
|
||||
<string name="settings_raw_color_engine_hncs_description">Hasselblad Natural Colour Solution : un système de gestion des couleurs développé indépendamment par Hasselblad</string>
|
||||
<string name="settings_raw_max_hdr_composition">Fusion HDR RAWmax</string>
|
||||
<string name="settings_raw_max_hdr_composition_description">Utilise le bracketing d’exposition pour la fusion HDR dans RAWmax. Désactivez cette option pour accélérer le traitement.</string>
|
||||
</resources>
|
||||
@@ -247,4 +247,6 @@
|
||||
<string name="settings_use_p010">P010 (10-bit YUV)</string>
|
||||
<string name="settings_use_p010_description">Aktifkan output YUV 10-bit untuk presisi data gambar yang lebih baik. Efektif pada perangkat yang didukung saat RAW dinonaktifkan.</string>
|
||||
<string name="settings_raw_color_engine_hncs_description">Hasselblad Natural Colour Solution: sistem manajemen warna yang dikembangkan secara independen oleh Hasselblad</string>
|
||||
<string name="settings_raw_max_hdr_composition">Penggabungan HDR RAWmax</string>
|
||||
<string name="settings_raw_max_hdr_composition_description">Gunakan pencahayaan bertingkat untuk penggabungan HDR di RAWmax. Nonaktifkan untuk meningkatkan kecepatan pemrosesan.</string>
|
||||
</resources>
|
||||
@@ -247,4 +247,6 @@
|
||||
<string name="settings_dro_dr200">DR200</string>
|
||||
<string name="settings_dro_dr400">DR400</string>
|
||||
<string name="settings_raw_color_engine_hncs_description">Hasselblad Natural Colour Solution:ハッセルブラッドが独自に開発したカラーマネジメントシステム</string>
|
||||
<string name="settings_raw_max_hdr_composition">RAWmax HDR 合成</string>
|
||||
<string name="settings_raw_max_hdr_composition_description">RAWmax でブラケット露出を使用して HDR 合成します。オフにすると処理速度が向上します。</string>
|
||||
</resources>
|
||||
@@ -248,4 +248,6 @@
|
||||
<string name="settings_dro_dr200">DR200</string>
|
||||
<string name="settings_dro_dr400">DR400</string>
|
||||
<string name="settings_raw_color_engine_hncs_description">Hasselblad Natural Colour Solution: 핫셀블라드가 독자적으로 개발한 컬러 매니지먼트 시스템</string>
|
||||
<string name="settings_raw_max_hdr_composition">RAWmax HDR 합성</string>
|
||||
<string name="settings_raw_max_hdr_composition_description">RAWmax에서 브래킷 노출을 사용해 HDR을 합성합니다. 끄면 처리 속도가 향상됩니다.</string>
|
||||
</resources>
|
||||
@@ -248,4 +248,6 @@
|
||||
<string name="settings_use_p010">P010 (YUV de 10 bits)</string>
|
||||
<string name="settings_use_p010_description">Ativa a saída YUV de 10 bits para melhor precisão dos dados da imagem. Eficaz em dispositivos suportados quando o RAW está desativado.</string>
|
||||
<string name="settings_raw_color_engine_hncs_description">Hasselblad Natural Colour Solution: um sistema de gerenciamento de cores desenvolvido de forma independente pela Hasselblad</string>
|
||||
<string name="settings_raw_max_hdr_composition">Fusão HDR RAWmax</string>
|
||||
<string name="settings_raw_max_hdr_composition_description">Usa exposições escalonadas para fusão HDR no RAWmax. Desative para melhorar a velocidade de processamento.</string>
|
||||
</resources>
|
||||
@@ -885,4 +885,6 @@
|
||||
<string name="preset_custom_badge">ปรับแต่ง</string>
|
||||
<string name="preset_builtin_badge">ในตัว</string>
|
||||
<string name="settings_raw_color_engine_hncs_description">Hasselblad Natural Colour Solution: ระบบจัดการสีที่ Hasselblad พัฒนาขึ้นอย่างอิสระ</string>
|
||||
<string name="settings_raw_max_hdr_composition">การรวม HDR ของ RAWmax</string>
|
||||
<string name="settings_raw_max_hdr_composition_description">ใช้การถ่ายคร่อมแสงสำหรับการรวม HDR ใน RAWmax ปิดเพื่อเพิ่มความเร็วในการประมวลผล</string>
|
||||
</resources>
|
||||
@@ -196,6 +196,8 @@
|
||||
<string name="settings_jpg_max_hdr_composition">JPGmax HDR 合成</string>
|
||||
<string name="settings_jpg_max_hdr_composition_description">在 JPGmax 中使用包围曝光进行 HDR 融合。拍摄时请保持手部稳定或使用三脚架。关闭时,JPGmax 只进行多帧降噪。</string>
|
||||
<string name="settings_use_raw_max">RAWmax</string>
|
||||
<string name="settings_raw_max_hdr_composition">RAWmax HDR 合成</string>
|
||||
<string name="settings_raw_max_hdr_composition_description">在 RAWmax 中使用包围曝光进行 HDR 融合。关闭可提升处理性能。</string>
|
||||
<string name="settings_use_multiple_exposure">多重曝光</string>
|
||||
<string name="multiple_exposure_finish">完成</string>
|
||||
<string name="multiple_exposure_undo">撤销</string>
|
||||
|
||||
@@ -196,6 +196,8 @@
|
||||
<string name="settings_jpg_max_hdr_composition">JPGmax HDR 合成</string>
|
||||
<string name="settings_jpg_max_hdr_composition_description">在 JPGmax 中使用包圍曝光進行 HDR 融合。拍攝時請保持手部穩定或使用三腳架。關閉時,JPGmax 只進行多幀降噪。</string>
|
||||
<string name="settings_use_raw_max">RAWmax</string>
|
||||
<string name="settings_raw_max_hdr_composition">RAWmax HDR 合成</string>
|
||||
<string name="settings_raw_max_hdr_composition_description">在 RAWmax 中使用包圍曝光進行 HDR 融合。關閉可提升處理效能。</string>
|
||||
<string name="settings_use_multiple_exposure">多重曝光</string>
|
||||
<string name="multiple_exposure_finish">完成</string>
|
||||
<string name="multiple_exposure_undo">復原</string>
|
||||
|
||||
@@ -196,6 +196,8 @@
|
||||
<string name="settings_jpg_max_hdr_composition">JPGmax HDR 合成</string>
|
||||
<string name="settings_jpg_max_hdr_composition_description">在 JPGmax 中使用包圍曝光進行 HDR 融合。拍攝時請保持手部穩定或使用三腳架。關閉時,JPGmax 只進行多幀降噪。</string>
|
||||
<string name="settings_use_raw_max">RAWmax</string>
|
||||
<string name="settings_raw_max_hdr_composition">RAWmax HDR 合成</string>
|
||||
<string name="settings_raw_max_hdr_composition_description">在 RAWmax 中使用包圍曝光進行 HDR 融合。關閉可提升處理效能。</string>
|
||||
<string name="settings_use_multiple_exposure">多重曝光</string>
|
||||
<string name="multiple_exposure_finish">完成</string>
|
||||
<string name="multiple_exposure_undo">復原</string>
|
||||
|
||||
@@ -198,6 +198,8 @@
|
||||
<string name="settings_jpg_max_hdr_composition">JPGmax HDR Composition</string>
|
||||
<string name="settings_jpg_max_hdr_composition_description">Use bracketed exposures for HDR fusion in JPGmax. Keep the camera steady or use a tripod while shooting. When disabled, JPGmax only performs multi-frame noise reduction.</string>
|
||||
<string name="settings_use_raw_max">RAWmax</string>
|
||||
<string name="settings_raw_max_hdr_composition">RAWmax HDR Composition</string>
|
||||
<string name="settings_raw_max_hdr_composition_description">Use bracketed exposures for HDR fusion in RAWmax. Turn it off to improve processing performance.</string>
|
||||
<string name="settings_use_multiple_exposure">Multiple Exposure</string>
|
||||
<string name="multiple_exposure_finish">Finish</string>
|
||||
<string name="multiple_exposure_undo">Undo</string>
|
||||
|
||||
@@ -30,6 +30,8 @@ class MultiFrameConfigTest {
|
||||
assertFalse(jpgMax.isRawMaxEnabled)
|
||||
assertTrue(jpgMaxHdr.isJpgMaxHdrEnabled)
|
||||
assertTrue(rawMax.isRawMaxEnabled)
|
||||
assertTrue(rawMax.isRawMaxHdrEnabled)
|
||||
assertFalse(rawMax.copy(useRawMaxHdrComposition = false).isRawMaxHdrEnabled)
|
||||
assertFalse(rawMax.isJpgMaxEnabled)
|
||||
assertFalse(rawMax.isJpgMaxHdrEnabled)
|
||||
}
|
||||
|
||||
@@ -0,0 +1,34 @@
|
||||
package com.hinnka.mycamera.processor
|
||||
|
||||
import org.junit.Assert.assertEquals
|
||||
import org.junit.Test
|
||||
|
||||
class GlesGraphicsShaderSourcesTest {
|
||||
@Test
|
||||
fun fullscreenVertexLanguageMatchesEveryRadianceFragmentLanguage() {
|
||||
val fragments = listOf(
|
||||
GlesRawRadianceFusionShaders.accumulate(rawCommon = ""),
|
||||
GlesRawRadianceFusionShaders.normalize(showRejections = false),
|
||||
GlesRawRadianceFusionShaders.validateHighlightFlow,
|
||||
GlesRawRadianceFusionShaders.longEligibility,
|
||||
GlesRadianceHighlightShaders.buildSupport,
|
||||
)
|
||||
|
||||
fragments.forEach { fragment ->
|
||||
val vertex = GlesGraphicsShaderSources.fullscreenVertexFor(fragment)
|
||||
assertEquals(
|
||||
GlesGraphicsShaderSources.languageVersionOf(fragment),
|
||||
GlesGraphicsShaderSources.languageVersionOf(vertex),
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
fun radianceAccumulatorUsesGlslEs310Pair() {
|
||||
val fragment = GlesRawRadianceFusionShaders.accumulate(rawCommon = "")
|
||||
val vertex = GlesGraphicsShaderSources.fullscreenVertexFor(fragment)
|
||||
|
||||
assertEquals(310, GlesGraphicsShaderSources.languageVersionOf(fragment))
|
||||
assertEquals(310, GlesGraphicsShaderSources.languageVersionOf(vertex))
|
||||
}
|
||||
}
|
||||
+14
-15
@@ -24,7 +24,7 @@ class GlesRadianceVgnChromaPostprocessorTest {
|
||||
}
|
||||
|
||||
@Test
|
||||
fun everyFilterUsesGlobalCoordinatesOverTiledStorage() {
|
||||
fun everyFilterUsesDirectCoordinatesOverFullSize2dStorage() {
|
||||
val globalShaders = listOf(
|
||||
GlesRadianceVgnChromaShaders.seed,
|
||||
GlesRadianceVgnChromaShaders.colorNoise1,
|
||||
@@ -39,26 +39,27 @@ class GlesRadianceVgnChromaPostprocessorTest {
|
||||
)
|
||||
|
||||
globalShaders.forEach { shader ->
|
||||
assertTrue(shader.contains("ivec3 tiledPosition"))
|
||||
assertTrue(shader.contains("uTileLefts"))
|
||||
assertTrue(shader.contains("uTileTops"))
|
||||
assertTrue(shader.contains("uimage2D"))
|
||||
assertTrue(!shader.contains("uimage2DArray"))
|
||||
assertTrue(!shader.contains("uTileLefts"))
|
||||
assertTrue(!shader.contains("uTileTops"))
|
||||
assertTrue(!shader.contains("tiledPosition"))
|
||||
}
|
||||
assertTrue(GlesRadianceVgnChromaShaders.iirRgb.contains("innerSize = uAxis == 0 ? uImageSize.x"))
|
||||
assertTrue(GlesRadianceVgnChromaShaders.iirRgb.contains("for (int i = 0; i < innerSize; ++i)"))
|
||||
assertTrue(GlesRadianceVgnChromaShaders.iirRgb.contains("ivec2 storage = p;"))
|
||||
assertTrue(GlesRadianceVgnChromaShaders.iirRgb.contains("imageStore(uOutput, storage"))
|
||||
assertTrue(GlesRadianceVgnChromaShaders.iirError.contains("for (int i = 0; i < innerSize; ++i)"))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun gpuHandoffVariantWritesTheSameFinalPixelToAFullSizeTexture() {
|
||||
val tiled = GlesRadianceVgnChromaShaders.finalCameraRgb(exportFullSizeTexture = false)
|
||||
val fullSize = GlesRadianceVgnChromaShaders.finalCameraRgb(exportFullSizeTexture = true)
|
||||
fun finalHandoffUsesOneGlobal2dSurface() {
|
||||
val finish = GlesRadianceVgnChromaShaders.finalCameraRgb
|
||||
|
||||
assertTrue(tiled.contains("uimage2DArray uOutput"))
|
||||
assertTrue(tiled.contains("imageStore(uOutput, storage, outputPixel)"))
|
||||
assertTrue(!tiled.contains("uFullSizeOutput"))
|
||||
assertTrue(fullSize.contains("uimage2D uFullSizeOutput"))
|
||||
assertTrue(fullSize.contains("imageStore(uFullSizeOutput, p, outputPixel)"))
|
||||
assertTrue(!fullSize.contains("uimage2DArray uOutput"))
|
||||
assertTrue(finish.contains("uimage2D uInput"))
|
||||
assertTrue(finish.contains("uimage2D uOutput"))
|
||||
assertTrue(finish.contains("imageStore(uOutput, p, outputPixel)"))
|
||||
assertTrue(!finish.contains("uimage2DArray"))
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -97,7 +98,6 @@ class GlesRadianceVgnChromaPostprocessorTest {
|
||||
assumeTrue("Android NDK glslc is unavailable", validator != null)
|
||||
|
||||
val sources = listOf(
|
||||
GlesRadianceVgnChromaShaders.capture,
|
||||
GlesRadianceVgnChromaShaders.seed,
|
||||
GlesRadianceVgnChromaShaders.colorNoise1,
|
||||
GlesRadianceVgnChromaShaders.colorNoise2,
|
||||
@@ -108,7 +108,6 @@ class GlesRadianceVgnChromaPostprocessorTest {
|
||||
GlesRadianceVgnChromaShaders.iirError,
|
||||
GlesRadianceVgnChromaShaders.colorNoiseFilter,
|
||||
GlesRadianceVgnChromaShaders.finalCameraRgb,
|
||||
GlesRadianceVgnChromaShaders.finalCameraRgb(exportFullSizeTexture = true),
|
||||
)
|
||||
sources.forEachIndexed { index, source ->
|
||||
val sourceFile = File.createTempFile("radiance-vgn-chroma-$index-", ".compute")
|
||||
|
||||
+14
-10
@@ -334,12 +334,14 @@ class GlesRawRadianceFusionShadersTest {
|
||||
|
||||
val rawCommonStub = "int bayerIndexAt(int cfaPattern, ivec2 p) { return 0; }"
|
||||
val sources = listOf(
|
||||
"compute" to GlesRawRadianceFusionShaders.accumulate(
|
||||
"fragment" to GlesRawRadianceFusionShaders.accumulate(
|
||||
rawCommon = rawCommonStub,
|
||||
trackRejections = true,
|
||||
trackParticipation = true,
|
||||
trackLongParticipation = true,
|
||||
),
|
||||
"compute" to GlesRawRadianceStacker.FLOW_BOUNDS_SUMMARY_COMPUTE_SHADER,
|
||||
"fragment" to GlesRawRadianceStacker.ROBUSTNESS_FRAGMENT_SHADER,
|
||||
"fragment" to GlesRawRadianceFusionShaders.longEligibility,
|
||||
"fragment" to GlesRawRadianceFusionShaders.normalize(showRejections = false),
|
||||
"fragment" to GlesRadianceHighlightShaders.buildSupport,
|
||||
@@ -404,18 +406,20 @@ class GlesRawRadianceFusionShadersTest {
|
||||
val reference = GlesRawRadianceFusionShaders.captureReferenceBase
|
||||
val normalize = GlesRawRadianceFusionShaders.normalize(showRejections = false)
|
||||
|
||||
assertTrue(clear.contains("uNrWeightRg"))
|
||||
assertTrue(clear.contains("uDetailWeightRg"))
|
||||
assertTrue(clear.contains("layout(rgba16f, binding = 0)"))
|
||||
assertTrue(clear.contains("image2D uNrAccumulator"))
|
||||
assertTrue(clear.contains("layout(rgba16f, binding = 1)"))
|
||||
assertTrue(clear.contains("image2D uDetailAccumulator"))
|
||||
assertFalse(clear.contains("layout(r32ui"))
|
||||
assertTrue(accumulate.contains("vec3 nrWeight"))
|
||||
assertTrue(accumulate.contains("nrWeight = vec3(sharedNrWeight)"))
|
||||
assertTrue(accumulate.contains("detailWeight = vec3(sharedDetailWeight)"))
|
||||
assertTrue(accumulate.contains("rgb.denoise.rg * nrWeight.rg"))
|
||||
assertTrue(accumulate.contains("rgb.denoise.b * nrWeight.b"))
|
||||
assertTrue(reference.contains("rg / weightRg"))
|
||||
assertTrue(reference.contains("bw.x / weightB"))
|
||||
assertTrue(normalize.contains("uniform highp usampler2D uNrWeightRg"))
|
||||
assertTrue(normalize.contains("uniform highp usampler2D uDetailWeightRg"))
|
||||
assertTrue(normalize.contains("vec3 weight = vec3(weightRg, max(bw.y, 0.0))"))
|
||||
assertTrue(accumulate.contains("rgb.denoise * nrWeight.x"))
|
||||
assertTrue(accumulate.contains("rgb.detail * detailWeight.x"))
|
||||
assertTrue(reference.contains("accumulated.rgb / weight"))
|
||||
assertTrue(normalize.contains("uniform highp sampler2D uNrAccumulator"))
|
||||
assertTrue(normalize.contains("uniform highp sampler2D uDetailAccumulator"))
|
||||
assertTrue(normalize.contains("vec3(sharedWeight)"))
|
||||
assertTrue(normalize.contains("vec3 confidence = vec3(sharedConfidence)"))
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,27 @@
|
||||
package com.hinnka.mycamera.processor
|
||||
|
||||
import org.junit.Assert.assertEquals
|
||||
import org.junit.Test
|
||||
|
||||
class GpuStackQueueTimingTest {
|
||||
@Test
|
||||
fun totalsPendingWaitAndKeepsStableStageFields() {
|
||||
val timing = GpuStackQueueTiming(
|
||||
stageWaits = listOf(
|
||||
GpuStackStageWait(GpuStackCompletionStage.NORMAL_ALIGNMENT, 0L),
|
||||
GpuStackStageWait(GpuStackCompletionStage.LONG_ALIGNMENT, 7L),
|
||||
GpuStackStageWait(GpuStackCompletionStage.HIGHLIGHT_ALIGNMENT, 11L),
|
||||
GpuStackStageWait(GpuStackCompletionStage.TILED_RECONSTRUCTION, 29L),
|
||||
GpuStackStageWait(GpuStackCompletionStage.CHROMA_POSTPROCESS, 2_137L),
|
||||
GpuStackStageWait(GpuStackCompletionStage.FINAL_EXPORT, 35L),
|
||||
),
|
||||
)
|
||||
|
||||
assertEquals(2_219L, timing.totalWaitMs)
|
||||
assertEquals(
|
||||
"normalAlignment=0ms longAlignment=7ms highlightAlignment=11ms " +
|
||||
"tiledReconstruction=29ms chromaPostprocess=2137ms finalExport=35ms",
|
||||
timing.logFields(),
|
||||
)
|
||||
}
|
||||
}
|
||||
@@ -92,4 +92,22 @@ class RawRadianceExposurePlannerTest {
|
||||
assertArrayEquals(intArrayOf(3), plan.longIndices)
|
||||
assertArrayEquals(IntArray(0), plan.excludedIndices)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun hdrDisabledTreatsEveryFrameAsSameExposureWithoutAuxiliaryResources() {
|
||||
val plan = RawRadianceExposurePlanner.plan(
|
||||
exposureProducts = listOf(100.0, 33.0, 420.0),
|
||||
frameRoles = listOf(
|
||||
RawBurstFrameRole.NORMAL,
|
||||
RawBurstFrameRole.HIGHLIGHT_SHORT,
|
||||
RawBurstFrameRole.SHADOW_LONG,
|
||||
),
|
||||
enableHdrFusion = false,
|
||||
)
|
||||
|
||||
assertArrayEquals(intArrayOf(0, 1, 2), plan.normalIndices)
|
||||
assertNull(plan.shortIndex)
|
||||
assertArrayEquals(IntArray(0), plan.longIndices)
|
||||
assertArrayEquals(IntArray(0), plan.excludedIndices)
|
||||
}
|
||||
}
|
||||
@@ -7,6 +7,31 @@
|
||||
本文,并在代表设备上运行实际的 compile、bind、dispatch、readback 和后续采样测试。不能仅凭
|
||||
GLES 版本号、扩展列表或桌面 GLSL 编译结果判断移动端可用性。
|
||||
|
||||
## Graphics program 的 GLSL ES 版本必须一致
|
||||
|
||||
已确认设备会严格拒绝使用不同 GLSL ES 版本的 vertex/fragment shader 链接:
|
||||
|
||||
```text
|
||||
Shader languages do not match.
|
||||
```
|
||||
|
||||
shader 分别编译成功不代表可以跨版本链接。例如 `#version 300 es` 的 fullscreen vertex
|
||||
不能与使用 image/SSBO 能力的 `#version 310 es` fragment 组成同一个 program。
|
||||
|
||||
### 错误做法
|
||||
|
||||
- 所有 fullscreen fragment 固定复用一份 `#version 300 es` vertex shader。
|
||||
- 为了继续复用 vertex shader,把需要 3.1 能力的 fragment 降级到 300。
|
||||
- 只检查 fragment 的编译结果,不检查 program 两端的版本契约。
|
||||
|
||||
### 正确做法
|
||||
|
||||
- 从 fragment 的 `#version` 生成相同版本的 fullscreen vertex shader。
|
||||
- 创建 program 前显式校验 vertex/fragment 的 GLSL ES 版本相同,让错误在进入驱动前暴露。
|
||||
- 需要 image、SSBO 或其他 GLES 3.1 能力的 fragment 保持 `#version 310 es`,配套使用
|
||||
`#version 310 es` vertex;普通 3.0 fragment 继续使用 300 配对。
|
||||
- 新增动态生成的 fragment shader 时,将 300/310 两种来源都纳入版本配对单元测试。
|
||||
|
||||
## SSBO binding 点数量
|
||||
|
||||
### 问题
|
||||
@@ -107,6 +132,19 @@ write-only 可用不代表同格式的 read/write 也可用。
|
||||
- dispatch 后交换两张纹理的角色;
|
||||
- 每个 pass 都显式区分只读 source 和只写 destination。
|
||||
|
||||
如果算法只是逐帧加法累加,不需要在 shader 中读取旧值,优先使用 framebuffer additive
|
||||
blending:
|
||||
|
||||
- 将 NR sum/weight 和 detail sum/weight 分别存入两张 `RGBA16F` attachment;
|
||||
- fragment shader 只输出本帧的 `vec4(rgb * weight, weight)` contribution;
|
||||
- MRT 的两个 draw buffer 都使用 `GL_FUNC_ADD + GL_ONE, GL_ONE`;
|
||||
- 每次 draw 后恢复 blend 状态,切回单 attachment 前显式 detach 第二个 attachment;
|
||||
- accumulator 由 write-only image 清零后,进入 framebuffer blending 前必须包含
|
||||
`GL_FRAMEBUFFER_BARRIER_BIT`。
|
||||
|
||||
这条路径保留每帧写回 FP16 的舍入语义,同时避免非法的 `RGBA16F` image 原位读写。不能把
|
||||
包含非加法更新、次序相关替换或任意读改写的算法机械改成 blending。
|
||||
|
||||
同时还应查询 image unit 上限,保证单个 compute pass 的并发 image 数量不超过设备能力。
|
||||
|
||||
## `RGBA16UI` attachment 回读
|
||||
@@ -259,6 +297,60 @@ image load/store 访问。若同一纹理接下来改由 sampler 读取,或作
|
||||
研究来源见
|
||||
[`research/phocus_glsl/04_color_tone/README.md`](../research/phocus_glsl/04_color_tone/README.md)。
|
||||
|
||||
## GPU 纹理交接与延迟 CPU 回读
|
||||
|
||||
### 问题
|
||||
|
||||
`glReadPixels` 往往是异步 GPU 命令后的第一个 CPU 同步点。直接用它的调用耗时表示
|
||||
“readback”会把此前尚未完成的 compute、fragment、barrier 和实际像素传输混在一起,既无法
|
||||
判断真正瓶颈,也会错误地让只需要 GPU texture 的后续显影等待 CPU Buffer。
|
||||
|
||||
### 正确做法
|
||||
|
||||
- 同一 EGL context 和 GL dispatcher 内,stacker 通过 `imageStore` 写完输出并声明
|
||||
`GL_SHADER_IMAGE_ACCESS_BARRIER_BIT | GL_TEXTURE_FETCH_BARRIER_BIT |
|
||||
GL_FRAMEBUFFER_BARRIER_BIT` 后,直接把 texture 所有权交给 RAW 显影。
|
||||
- 需要整行/整列递归扫描的全帧滤波,输入必须是连续的全尺寸 `uimage2D`。上游 tile fragment
|
||||
pass 应直接用全局 viewport 写入这张完整 texture;不要先写临时 tile texture,再为每个 tile
|
||||
dispatch 一次 capture/copy。不能在 IIR 内循环里通过 uniform 数组动态查找 tile,再访问
|
||||
`uimage2DArray` layer;不同移动驱动对这类动态循环的展开和分支 lowering 差异很大,而且会
|
||||
破坏跨 layer 的缓存局部性。
|
||||
- 分配全尺寸工作纹理前查询 `GL_MAX_TEXTURE_SIZE`。Radiance VGN 色度链使用三张
|
||||
`RGBA16UI` 2D texture 做 ping-pong,最终 YCCD → RGB 写入已经空闲的工作纹理并移交所有权,
|
||||
不再为 GPU handoff 分配第四张同尺寸纹理。
|
||||
- CPU/DNG Buffer 不是 GPU 交接结果的必填字段。DNG 消费者应在前台显影完成后单独请求
|
||||
materialization,并保持 texture 存活到该消费者结束。
|
||||
- 已完成且后续只读的 flow、robustness 和 tile mask 应直接转移 texture 所有权,立即为下一帧
|
||||
分配工作纹理;不要为了形成 cache 再执行三次全表面 copy。诊断采样必须发生在所有权转移前。
|
||||
- 普通对齐帧只需要 flow bounds 时,在 GPU 上将每帧 grid 归约成一个
|
||||
`vec4(minX,maxX,minY,maxY)`,所有帧提交结束后一次 map 小型 SSBO。不能逐帧回读完整
|
||||
`RGBA16F` flow grid 并在 CPU 上扫描。
|
||||
- 需要拆分计时时,在读回前插入 `glFenceSync(GL_SYNC_GPU_COMMANDS_COMPLETE, 0)`,提交后使用
|
||||
`glClientWaitSync` 单独记录 `gpuQueueWait`;fence 已完成后再分别记录 `glReadPixels` 的
|
||||
`pixelTransfer` 和 RGBA16 → RGB16 的 `cpuPack`。
|
||||
- 需要继续定位 stacker 的异步队列尾部时,在 normal alignment、long alignment、
|
||||
highlight alignment、tiled reconstruction、chroma postprocess 和 final export 的命令边界
|
||||
插入有序 fence,但不能在 stacker 内逐段等待。fence 所有权随导出的 texture 传给消费者,
|
||||
首个 CPU 同步点再按顺序等待并记录各阶段尚未完成的队列时间。
|
||||
- 阶段 fence 的结果表示“到达首个同步点时仍待执行的 queue tail”,不是该阶段从头到尾的完整
|
||||
GPU 执行时长。已经在 CPU 提交期间完成的阶段会记录为 `0ms`;如需完整 shader GPU duration,
|
||||
应另行使用驱动支持的非阻塞 timer query,并处理 disjoint 状态。
|
||||
- 首个消费者必须分别记录 `upstreamStackGpuWait` 和自身的 GPU 等待,例如曝光预览使用
|
||||
`previewGpuQueueWait`、DNG materialization 使用 `materializationGpuWait`,不能再次把两者
|
||||
合并为笼统的 `gpuQueueWait`。
|
||||
- 同一 context 内的显影依赖命令队列顺序,不要为了 GPU→GPU 交接调用 `glFinish`。跨共享
|
||||
context 才需要额外验证 sync object 的共享和等待行为。
|
||||
- fence 必须在所有退出路径调用 `glDeleteSync`;framebuffer、scratch buffer 和导出的 texture
|
||||
也必须按消费者生命周期分别释放。
|
||||
|
||||
### 验证
|
||||
|
||||
- 日志必须明确区分 CPU 命令提交、`gpuQueueWait`、`pixelTransfer`、`cpuPack` 和 allocation。
|
||||
- 真机确认 stacker 返回 GPU texture 时没有发生全尺寸 `glReadPixels`。
|
||||
- 真机确认 RAW 显影完成后才开始 DNG materialization,并验证取消、写入失败和显影失败路径
|
||||
不泄漏 texture、sync、framebuffer 或 native buffer。
|
||||
- 对同一输出比较延迟 materialization DNG 与原同步路径的 RGB16 数值,要求逐通道一致。
|
||||
|
||||
## 通用验证要求
|
||||
|
||||
- 不根据 `GL_MAX_TEXTURE_SIZE` 推断 image load/store 格式支持。
|
||||
|
||||
Reference in new issue
Block a user