feat: raw schedule

This commit is contained in:
zhoubinjia committed 2026-08-12 15:31:07 +08:00
1 parent 03d0380974
commit 85a1a79927
4 files changed
+259 -83

No files matched your search

@@ -12,6 +12,7 @@ import android.media.MediaMetadataRetriever
import android.net.Uri
import android.os.Build
import android.os.Environment
import android.os.FileObserver
import android.provider.DocumentsContract
import android.provider.MediaStore
import androidx.core.graphics.createBitmap
@@ -81,13 +82,16 @@ import kotlinx.coroutines.sync.Mutex
import kotlinx.coroutines.sync.withLock
import java.io.File
import java.io.FileOutputStream
import java.io.IOException
import java.io.OutputStream
import java.nio.ByteBuffer
import java.nio.IntBuffer
import java.text.SimpleDateFormat
import java.util.*
import java.util.concurrent.ConcurrentHashMap
import java.util.concurrent.atomic.AtomicBoolean
import java.util.concurrent.atomic.AtomicLong
import kotlin.coroutines.resume
import kotlin.io.copyTo
import kotlin.io.deleteRecursively
import kotlin.io.extension
@@ -450,6 +454,72 @@ object GalleryManager {
return File(getPhotoDir(context, photoId), PHOTO_FILE)
}
/**
* Suspends until a prepared Photon photo publishes a non-empty internal display file.
*
* Capture creates an empty [PHOTO_FILE] so the pending item can enter the gallery, then
* atomically moves the completed JPEG/HEIC into the same directory. Watching the directory
* is required because watching the empty file itself would remain attached to the replaced
* inode.
*/
suspend fun awaitInternalPhotoReady(context: Context, photoId: String): Boolean {
val photoDir = getPhotoDir(context, photoId)
if (!photoDir.isDirectory) return false
if (getOriginalImageFile(context, photoId) != null) return true
return suspendCancellableCoroutine { continuation ->
val completed = AtomicBoolean(false)
lateinit var observer: FileObserver
fun complete(result: Boolean) {
if (!completed.compareAndSet(false, true)) return
observer.stopWatching()
continuation.resume(result)
}
fun completeIfReady() {
if (getOriginalImageFile(context, photoId) != null) {
PLog.d(TAG, "Observed internal photo ready: $photoId")
complete(true)
}
}
observer = object : FileObserver(
photoDir,
FileObserver.CREATE or
FileObserver.CLOSE_WRITE or
FileObserver.MOVED_TO or
FileObserver.DELETE_SELF
) {
override fun onEvent(event: Int, path: String?) {
val eventType = event and FileObserver.ALL_EVENTS
if (eventType == FileObserver.DELETE_SELF) {
complete(false)
return
}
if (path != PHOTO_FILE && path != HIGH_QUALITY_PHOTO_FILE) return
if (
eventType == FileObserver.CREATE ||
eventType == FileObserver.CLOSE_WRITE ||
eventType == FileObserver.MOVED_TO
) {
completeIfReady()
}
}
}
// Start before registering cancellation/checking readiness so neither publication nor
// an already-cancelled continuation can leave an unowned observer running.
observer.startWatching()
continuation.invokeOnCancellation {
if (completed.compareAndSet(false, true)) {
observer.stopWatching()
}
}
completeIfReady()
}
}
fun getHighQualityPhotoFile(context: Context, photoId: String): File {
return File(getPhotoDir(context, photoId), HIGH_QUALITY_PHOTO_FILE)
}
@@ -2285,10 +2355,17 @@ object GalleryManager {
chromaNoiseReduction = rawChromaNoiseReduction
)
FileOutputStream(tempFile).use { outputStream ->
val jpegWritten = FileOutputStream(tempFile).use { outputStream ->
writeFinalJpeg(bitmap, outputStream, photoQuality)
}
tempFile.renameTo(photoFile)
if (!jpegWritten) {
tempFile.delete()
throw IOException("Failed to encode final JPEG for $photoId")
}
if (!tempFile.renameTo(photoFile)) {
tempFile.delete()
throw IOException("Failed to publish final JPEG for $photoId")
}
saveMetadata(context, photoId, updatedMetadata)
val bokehBitmap = renderAndSaveBokehPhoto(context, photoId, updatedMetadata, bitmap)
val preparedUltraHdrSource = if (updatedMetadata.manualHdrEffectEnabled) {
@@ -3417,7 +3494,10 @@ object GalleryManager {
"cpuMaterializationBeforeRender=false",
)
if (inMemoryResult != null) {
pendingDngWrite = async(Dispatchers.IO) {
pendingDngWrite = async(
context = Dispatchers.IO,
start = CoroutineStart.LAZY,
) {
try {
val dngStartMs = System.currentTimeMillis()
val written = materializeAndPersistDng()
@@ -3434,7 +3514,8 @@ object GalleryManager {
}
PLog.i(
TAG,
"RAW GPU render completed; deferred DNG materialization started",
"RAW GPU render completed; DNG materialization queued behind " +
"SDR JPEG publication",
)
inMemoryResult
} else {
@@ -3467,7 +3548,6 @@ object GalleryManager {
releaseInitialFusedBuffer()
}
var bitmap = rawResult.sdrBitmap
if (updatedMetadata.isMirrored) {
bitmap = BitmapUtils.flipHorizontal(bitmap)
}
@@ -3475,15 +3555,28 @@ object GalleryManager {
width = bitmap.width,
height = bitmap.height,
sharpening = rawSharpening,
chromaNoiseReduction = rawChromaNoiseReduction
chromaNoiseReduction = rawChromaNoiseReduction,
)
// Save Original (Stacked Result)
FileOutputStream(tempFile).use { outputStream ->
val jpegWritten = FileOutputStream(tempFile).use { outputStream ->
writeFinalJpeg(bitmap, outputStream, photoQuality)
}
tempFile.renameTo(photoFile)
if (!jpegWritten) {
tempFile.delete()
throw IOException("Failed to encode final stacked JPEG for $photoId")
}
if (!tempFile.renameTo(photoFile)) {
tempFile.delete()
throw IOException("Failed to publish final stacked JPEG for $photoId")
}
saveMetadata(context, photoId, updatedMetadata)
PLog.i(TAG, "RAW output schedule stage=SDR_JPEG_PUBLISHED")
pendingDngWrite?.let { write ->
PLog.i(
TAG,
"RAW output schedule stage=DNG_MATERIALIZATION_START",
)
write.start()
}
val bokehBitmap = renderAndSaveBokehPhoto(context, photoId, updatedMetadata, bitmap)
val preparedUltraHdrSource = if (updatedMetadata.manualHdrEffectEnabled) {
@@ -44,6 +44,7 @@ import com.hinnka.mycamera.utils.DirectBufferPixelPacker
import com.hinnka.mycamera.utils.LargeDirectBuffer
import com.hinnka.mycamera.utils.PLog
import com.hinnka.mycamera.utils.RawProcessor
import kotlinx.coroutines.CancellationException
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.asCoroutineDispatcher
import kotlinx.coroutines.currentCoroutineContext
@@ -3301,42 +3302,15 @@ class RawDemosaicProcessor {
)
}
// The HDR reference branches directly from undenoised, demosaicked camera RGB.
// It intentionally excludes denoise, ProfileGainMap, rendering engines, their
// additional tone mapping, and output sharpening. Explicit user RAW exposure is
// retained so the HDR reference stays exposure-aligned with the rendered SDR base.
// The complete ACR3 reference curve is applied. Its output contract is linear extended
// sRGB.
val hdrReferenceBitmap = if (includeHdrReference) {
setupHdrReferenceFramebuffer(actualWidth, actualHeight)
renderHdrReferencePass(
metadata = actualMetadata,
rawExposureCompensation = effectiveExposureCompensation,
inputTextureId = demosaicTextureId,
colorCorrectionMatrix = linearColorCorrectionMatrix,
cameraWhite = linearCameraWhite,
hueSatMap = activeDcpRenderPlan?.hueSatMap,
profileToLinearSrgb = profileToLinearSrgbTransform,
)
setupOutputFramebuffer(finalWidth, finalHeight)
renderOutputPass(
actualRotation,
actualWidth,
actualHeight,
bounds,
hdrReferenceTextureId,
)
val hdrPixels = readPixels(
finalWidth,
finalHeight,
android.graphics.ColorSpace.get(
android.graphics.ColorSpace.Named.LINEAR_EXTENDED_SRGB
),
)
releaseHdrReferenceFramebuffer()
hdrPixels
// Preserve the undenoised camera-RGB source identity for the lower-priority HDR
// branch. LinearRcdPass swaps the full-resolution ping-pong members below, so looking
// up demosaicTextureId after the SDR render would select the post-CCM texture instead.
// The source texture itself remains read-only and alive until the complete render ends.
val hdrReferenceSourceTextureId = if (includeHdrReference) {
check(demosaicTextureId != 0) { "HDR reference source texture is unavailable" }
demosaicTextureId
} else {
null
0
}
val denoiseProfileTextureId = renderMgcUserAdjustmentDenoise(
@@ -3538,24 +3512,107 @@ class RawDemosaicProcessor {
val outputMaterializationMs = System.currentTimeMillis() - readStart
PLog.d(
TAG,
"RAW output materialization timing " +
"RAW output materialization timing target=SDR " +
"upstreamStackGpuWait=${upstreamStackTiming?.totalWaitMs ?: 0L}ms " +
"renderGpuQueueWait=${outputGpuQueueWaitMs}ms " +
"pixelTransferAndBitmap=${outputMaterializationMs}ms",
)
PLog.d(TAG, "RAW processing complete: ${finalBitmap?.width}x${finalBitmap?.height}")
finalBitmap?.let {
RawHdrRenderResult(
sdrBitmap = it,
hdrReferenceBitmap = hdrReferenceBitmap,
rawInputWidth = actualWidth,
rawInputHeight = actualHeight,
outputSourceBounds = Rect(outputSourceBounds),
outputRotation = actualRotation,
effectiveDefaultCrop = effectiveDefaultCrop?.let(::Rect),
)
if (finalBitmap == null) {
PLog.e(TAG, "Unable to materialize RAW SDR output")
return@withContext null
}
PLog.i(
TAG,
"RAW output schedule stage=SDR_BITMAP_COMPLETE size=" +
"${finalBitmap.width}x${finalBitmap.height}",
)
// Keep both output materializations contiguous: HDR follows the completed SDR readback
// without yielding to JPEG encoding or another CPU consumer in between.
// It branches from the preserved undenoised camera RGB, excludes the SDR denoise/tone/
// sharpen chain, and reuses the existing rotated Output FBO after its SDR pixels have
// already been copied into the bitmap.
val hdrReferenceBitmap = if (includeHdrReference) {
val hdrStartNs = System.nanoTime()
try {
setupHdrReferenceFramebuffer(actualWidth, actualHeight)
renderHdrReferencePass(
metadata = actualMetadata,
rawExposureCompensation = effectiveExposureCompensation,
inputTextureId = hdrReferenceSourceTextureId,
colorCorrectionMatrix = linearColorCorrectionMatrix,
cameraWhite = linearCameraWhite,
hueSatMap = activeDcpRenderPlan?.hueSatMap,
profileToLinearSrgb = profileToLinearSrgbTransform,
)
renderOutputPass(
actualRotation,
actualWidth,
actualHeight,
bounds,
hdrReferenceTextureId,
)
val hdrGpuQueueWaitMs = GlesGpuCompletion.awaitSubmittedWork(
label = "RAW HDR reference output",
checkGlError = ::checkGlError,
)
val hdrReadStartNs = System.nanoTime()
val hdrPixels = readPixels(
finalWidth,
finalHeight,
android.graphics.ColorSpace.get(
android.graphics.ColorSpace.Named.LINEAR_EXTENDED_SRGB
),
)
val hdrMaterializationMs =
(System.nanoTime() - hdrReadStartNs) / 1_000_000L
PLog.i(
TAG,
"RAW output materialization timing target=HDR " +
"renderGpuQueueWait=${hdrGpuQueueWaitMs}ms " +
"pixelTransferAndBitmap=${hdrMaterializationMs}ms " +
"total=${(System.nanoTime() - hdrStartNs) / 1_000_000L}ms",
)
hdrPixels
} catch (cancellation: CancellationException) {
throw cancellation
} catch (error: OutOfMemoryError) {
PLog.e(
TAG,
"Unable to allocate RAW HDR output; preserving SDR",
error,
)
null
} catch (error: Exception) {
PLog.e(
TAG,
"Unable to materialize RAW HDR output; preserving SDR",
error,
)
null
} finally {
releaseHdrReferenceFramebuffer()
}
} else {
null
}
PLog.i(
TAG,
"RAW output schedule stage=HDR_BITMAP_COMPLETE enabled=$includeHdrReference " +
"success=${hdrReferenceBitmap != null}",
)
PLog.d(TAG, "RAW processing complete: ${finalBitmap.width}x${finalBitmap.height}")
RawHdrRenderResult(
sdrBitmap = finalBitmap,
hdrReferenceBitmap = hdrReferenceBitmap,
rawInputWidth = actualWidth,
rawInputHeight = actualHeight,
outputSourceBounds = Rect(outputSourceBounds),
outputRotation = actualRotation,
effectiveDefaultCrop = effectiveDefaultCrop?.let(::Rect),
)
} finally {
if (rawTextureId == borrowedGpuSource?.textureId) {
rawTextureId = 0
@@ -278,15 +278,19 @@ fun GalleryDetailScreen(
displayPhotoSize = photo.size
if (displayPhotoSize > 0L) return@LaunchedEffect
repeat(20) {
val resolvedSize = withContext(Dispatchers.IO) {
resolveCurrentMediaSize(context, photo)
var resolvedSize = withContext(Dispatchers.IO) {
resolveCurrentMediaSize(context, photo)
}
if (resolvedSize <= 0L && viewModel.awaitPreparedPhotoReady(photo)) {
resolvedSize = withContext(Dispatchers.IO) {
maxOf(
resolveCurrentMediaSize(context, photo),
viewModel.getInternalPhotoSize(photo.id)
)
}
if (resolvedSize > 0L) {
displayPhotoSize = resolvedSize
return@LaunchedEffect
}
delay(300L)
}
if (resolvedSize > 0L) {
displayPhotoSize = resolvedSize
}
}
@@ -2115,27 +2119,32 @@ private fun ZoomableImage(
val isSettledActive = isActive && !isScrollInProgress
LaunchedEffect(displayPhoto.id, metadataHash, showOrigin, refreshKey, isSettledActive) {
suspend fun loadBitmap() {
isLoading = bitmap == null
bitmap = viewModel.getPreviewBitmap(displayPhoto, showOrigin = showOrigin,
ignoreDenoise = !isSettledActive, maxEdge = if (isSettledActive) 4096 else 1024)
if (bitmap == null) {
delay(500)
loadBitmap()
}
colorSpace.value = bitmap?.colorSpace
isLoading = bitmap == null
isLoading = bitmap == null
bitmap = viewModel.getPreviewBitmap(
displayPhoto,
showOrigin = showOrigin,
ignoreDenoise = !isSettledActive,
maxEdge = if (isSettledActive) 4096 else 1024
)
if (bitmap == null && viewModel.awaitPreparedPhotoReady(displayPhoto)) {
bitmap = viewModel.getPreviewBitmap(
displayPhoto,
showOrigin = showOrigin,
ignoreDenoise = !isSettledActive,
maxEdge = if (isSettledActive) 4096 else 1024
)
}
colorSpace.value = bitmap?.colorSpace
isLoading = bitmap == null
if (displayPhoto.metadata?.manualHdrEffectEnabled == true && isSettledActive) {
hdrBitmap = viewModel.getDetailBitmap(displayPhoto)
hdrBitmap?.let {
colorSpace.value = it.colorSpace
}
} else {
hdrBitmap = null
if (displayPhoto.metadata?.manualHdrEffectEnabled == true && isSettledActive) {
hdrBitmap = viewModel.getDetailBitmap(displayPhoto)
hdrBitmap?.let {
colorSpace.value = it.colorSpace
}
} else {
hdrBitmap = null
}
loadBitmap()
}
LaunchedEffect(hdrBitmap, showOrigin, isActive) {
@@ -2956,6 +2956,23 @@ class GalleryViewModel(application: Application) : AndroidViewModel(application)
invalidateGridThumbnailCache(photoId)
}
/**
* Waits for an empty prepared-photo placeholder to be replaced by its final internal image.
* External and already-materialized media are not watched here.
*/
suspend fun awaitPreparedPhotoReady(photo: MediaData): Boolean {
val localPath = photo.uri.takeIf { it.scheme == "file" }?.path ?: return false
val context = getApplication<Application>()
val placeholderFile = GalleryManager.getPhotoFile(context, photo.id)
if (File(localPath).absolutePath != placeholderFile.absolutePath) return false
return GalleryManager.awaitInternalPhotoReady(context, photo.id)
}
fun getInternalPhotoSize(photoId: String): Long {
val context = getApplication<Application>()
return GalleryManager.getOriginalImageFile(context, photoId)?.length() ?: 0L
}
private fun invalidateGridThumbnailCache(photoId: String) {
val snapshot = gridThumbnailCache.snapshot()
snapshot.keys.filter { it.startsWith("${photoId}_") }.forEach {