feat: implement Room-based metadata persistence and migrate legacy JSON storage
This commit is contained in:
1 parent
9c1c7e1060
commit
ac20989dc1
19 files changed
+965
-537
No files matched your search
@@ -4,6 +4,7 @@ plugins {
|
||||
alias(libs.plugins.android.application)
|
||||
alias(libs.plugins.kotlin.android)
|
||||
alias(libs.plugins.kotlin.compose)
|
||||
alias(libs.plugins.ksp)
|
||||
}
|
||||
|
||||
val localProperties = Properties().apply {
|
||||
@@ -202,6 +203,9 @@ dependencies {
|
||||
implementation(libs.androidx.animation.core)
|
||||
implementation(libs.androidx.lifecycle.process)
|
||||
implementation(libs.androidx.core.splashscreen)
|
||||
implementation(libs.androidx.room.runtime)
|
||||
implementation(libs.androidx.room.ktx)
|
||||
ksp(libs.androidx.room.compiler)
|
||||
|
||||
implementation(libs.okhttp)
|
||||
implementation(libs.gson)
|
||||
|
||||
@@ -15,6 +15,7 @@ import androidx.core.graphics.createBitmap
|
||||
import androidx.exifinterface.media.ExifInterface
|
||||
import com.hinnka.mycamera.camera.AspectRatio
|
||||
import com.hinnka.mycamera.data.ContentRepository
|
||||
import com.hinnka.mycamera.gallery.db.GalleryMediaStore
|
||||
import com.hinnka.mycamera.hdr.GainmapResult
|
||||
import com.hinnka.mycamera.hdr.GainmapSourceSet
|
||||
import com.hinnka.mycamera.hdr.HdrGainmapStrength
|
||||
@@ -77,7 +78,6 @@ object GalleryManager {
|
||||
private const val HDR_FILE = "original_hdr.bin"
|
||||
private const val VIDEO_FILE = "video.mp4"
|
||||
private const val DNG_FILE = "original.dng"
|
||||
private const val METADATA_FILE = "metadata.json"
|
||||
private const val AI_DENOISE_FILE = "ai_denoise.jpg"
|
||||
private const val THUMBNAIL_FILE = "thumbnail.jpg"
|
||||
private const val BOKEH_FILE = "bokeh.jpg"
|
||||
@@ -186,10 +186,6 @@ object GalleryManager {
|
||||
return File(getPhotoDir(context, photoId), DNG_FILE)
|
||||
}
|
||||
|
||||
fun getMetadataFile(context: Context, photoId: String): File {
|
||||
return File(getPhotoDir(context, photoId), METADATA_FILE)
|
||||
}
|
||||
|
||||
fun getAiDenoiseFile(context: Context, photoId: String): File {
|
||||
return File(getPhotoDir(context, photoId), AI_DENOISE_FILE)
|
||||
}
|
||||
@@ -910,7 +906,6 @@ object GalleryManager {
|
||||
val photoFile = File(photoDir, PHOTO_FILE)
|
||||
val videoFile = File(photoDir, VIDEO_FILE)
|
||||
val thumbnailFile = File(photoDir, THUMBNAIL_FILE)
|
||||
val metadataFile = File(photoDir, METADATA_FILE)
|
||||
|
||||
var cropRegion = captureResult?.get(CaptureResult.SCALER_CROP_REGION)
|
||||
if (superResolutionScale > 1.0f && cropRegion != null) {
|
||||
@@ -2125,11 +2120,9 @@ object GalleryManager {
|
||||
* 获取所有照片 ID 列表(按时间降序)
|
||||
*/
|
||||
fun getPhotoIds(context: Context): List<String> {
|
||||
val baseDir = getPhotosBaseDir(context)
|
||||
return baseDir.listFiles()
|
||||
?.filter { it.isDirectory }
|
||||
?.map { it.name }
|
||||
?: emptyList()
|
||||
return runBlocking {
|
||||
GalleryMediaStore.getPhotoIds(context)
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -2217,6 +2210,7 @@ object GalleryManager {
|
||||
if (photoDir.exists()) {
|
||||
photoDir.deleteRecursively()
|
||||
}
|
||||
GalleryMediaStore.deleteMedia(context, photoId)
|
||||
PLog.d(TAG, "Photo deleted: $photoId")
|
||||
deleteEmptyDirs(getPhotosBaseDir(context))
|
||||
true
|
||||
@@ -2261,24 +2255,7 @@ object GalleryManager {
|
||||
}
|
||||
|
||||
private suspend fun loadMetadataInternal(context: Context, photoId: String): MediaMetadata? {
|
||||
return withContext(Dispatchers.IO) {
|
||||
try {
|
||||
val file = getMetadataFile(context, photoId)
|
||||
if (file.exists()) {
|
||||
val content = file.readText()
|
||||
val metadata = MediaMetadata.fromJson(content)
|
||||
if (metadata == null) {
|
||||
PLog.e(TAG, "loadMetadata: fromJson returned null for $photoId, content length=${content.length}")
|
||||
}
|
||||
metadata
|
||||
} else {
|
||||
null
|
||||
}
|
||||
} catch (e: Exception) {
|
||||
PLog.e(TAG, "Failed to load metadata for photo: $photoId", e)
|
||||
null
|
||||
}
|
||||
}
|
||||
return GalleryMediaStore.loadMetadata(context, photoId)
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -2291,18 +2268,8 @@ object GalleryManager {
|
||||
}
|
||||
|
||||
private suspend fun saveMetadataInternal(context: Context, photoId: String, metadata: MediaMetadata): Boolean {
|
||||
return withContext(Dispatchers.IO) {
|
||||
try {
|
||||
val dir = getPhotoDir(context, photoId, true)
|
||||
val file = File(dir, METADATA_FILE)
|
||||
val json = metadata.toJson()
|
||||
file.writeText(json)
|
||||
true
|
||||
} catch (e: Exception) {
|
||||
PLog.e(TAG, "Failed to save metadata for photo: $photoId", e)
|
||||
false
|
||||
}
|
||||
}
|
||||
getPhotoDir(context, photoId, true)
|
||||
return GalleryMediaStore.saveMetadata(context, photoId, metadata)
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -2314,13 +2281,7 @@ object GalleryManager {
|
||||
update: (MediaMetadata) -> MediaMetadata
|
||||
): MediaMetadata? {
|
||||
return metadataMutex.withLock {
|
||||
val current = loadMetadataInternal(context, photoId) ?: return@withLock null
|
||||
val updated = update(current)
|
||||
if (saveMetadataInternal(context, photoId, updated)) {
|
||||
updated
|
||||
} else {
|
||||
null
|
||||
}
|
||||
GalleryMediaStore.updateMetadata(context, photoId, update)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -2361,78 +2322,6 @@ object GalleryManager {
|
||||
photoId
|
||||
}
|
||||
|
||||
suspend fun buildPhotoData(context: Context, photoId: String): MediaData? = withContext(Dispatchers.IO) {
|
||||
val metadata = loadMetadata(context, photoId) ?: return@withContext null
|
||||
val thumbnailFile = getThumbnailFile(context, photoId)
|
||||
val thumbnailUri = when {
|
||||
thumbnailFile.exists() -> Uri.fromFile(thumbnailFile)
|
||||
metadata.sourceUri != null -> metadata.sourceUri.toUri()
|
||||
else -> return@withContext null
|
||||
}
|
||||
if (metadata.mediaType == MediaType.VIDEO) {
|
||||
val sourceUri = metadata.sourceUri?.let(Uri::parse) ?: return@withContext null
|
||||
// val info = readVideoRecordInfo(context, sourceUri)
|
||||
val id = photoId
|
||||
val resolvedWidth = metadata.videoWidth ?: metadata.width
|
||||
val resolvedHeight = metadata.videoHeight ?: metadata.height
|
||||
val resolvedDurationMs = metadata.durationMs
|
||||
val resolvedMimeType = metadata.mimeType
|
||||
val resolvedMetadata = metadata.copy(
|
||||
width = resolvedWidth,
|
||||
height = resolvedHeight,
|
||||
mimeType = resolvedMimeType,
|
||||
durationMs = resolvedDurationMs,
|
||||
frameRate = metadata.frameRate,
|
||||
bitrate = metadata.bitrate,
|
||||
rotationDegrees = metadata.rotationDegrees,
|
||||
hasAudio = metadata.hasAudio,
|
||||
videoWidth = resolvedWidth,
|
||||
videoHeight = resolvedHeight
|
||||
)
|
||||
val result = MediaData(
|
||||
id = id,
|
||||
uri = sourceUri,
|
||||
thumbnailUri = thumbnailUri,
|
||||
displayName = (sourceUri.lastPathSegment ?: "video_$id"),
|
||||
dateAdded = metadata.dateTaken ?: getPhotoDir(context, id).lastModified(),
|
||||
size = 0L,
|
||||
width = resolvedWidth,
|
||||
height = resolvedHeight,
|
||||
mediaType = MediaType.VIDEO,
|
||||
mimeType = resolvedMimeType,
|
||||
durationMs = resolvedDurationMs,
|
||||
sourceUri = sourceUri,
|
||||
metadata = resolvedMetadata
|
||||
)
|
||||
return@withContext result
|
||||
}
|
||||
|
||||
val photoFile = getPhotoFile(context, photoId)
|
||||
val originalFile = getDngFile(context, photoId).takeIf { it.exists() } ?: getYuvFile(context, photoId).takeIf { it.exists() } ?: photoFile
|
||||
|
||||
if (!photoFile.exists()) return@withContext null
|
||||
val videoFile = getVideoFile(context, photoId)
|
||||
val isBurstPhoto = hasBurstPhotos(context, photoId)
|
||||
|
||||
val result = MediaData(
|
||||
id = photoId,
|
||||
uri = Uri.fromFile(photoFile),
|
||||
thumbnailUri = thumbnailUri,
|
||||
displayName = photoFile.name,
|
||||
dateAdded = originalFile.lastModified().takeIf { it > 0 } ?: getPhotoDir(context, photoId).lastModified(),
|
||||
size = photoFile.length(),
|
||||
width = metadata.width,
|
||||
height = metadata.height,
|
||||
mediaType = MediaType.IMAGE,
|
||||
mimeType = metadata.mimeType ?: "image/jpeg",
|
||||
sourceUri = metadata.sourceUri?.let(Uri::parse),
|
||||
isMotionPhoto = videoFile.exists(),
|
||||
isBurstPhoto = isBurstPhoto,
|
||||
metadata = metadata
|
||||
)
|
||||
return@withContext result
|
||||
}
|
||||
|
||||
fun loadYuvData(context: Context, photoId: String): ByteBuffer? {
|
||||
val yuvFile = getYuvFile(context, photoId)
|
||||
if (!yuvFile.exists()) {
|
||||
@@ -2678,7 +2567,6 @@ object GalleryManager {
|
||||
val photoDir = getPhotoDir(context, photoId, true)
|
||||
val photoFile = File(photoDir, PHOTO_FILE)
|
||||
val dngFile = File(photoDir, DNG_FILE)
|
||||
val metadataFile = File(photoDir, METADATA_FILE)
|
||||
val thumbnailFile = File(photoDir, THUMBNAIL_FILE)
|
||||
|
||||
if (photoFile.exists()) {
|
||||
@@ -2762,12 +2650,12 @@ object GalleryManager {
|
||||
} else {
|
||||
// 降级:如果 RAW 处理失败,尝试直接解码(某些 DNG 包含内置预览图)
|
||||
// 传递元数据确保旋转信息被正确处理
|
||||
tempImportJpeg(uri, context, metadata, photoFile, metadataFile, thumbnailFile)
|
||||
tempImportJpeg(uri, context, metadata, photoFile, thumbnailFile)
|
||||
}
|
||||
} else {
|
||||
// --- 常规 JPEG 处理逻辑 ---
|
||||
// 传递元数据确保旋转信息被正确处理
|
||||
tempImportJpeg(uri, context, metadata, photoFile, metadataFile, thumbnailFile)
|
||||
tempImportJpeg(uri, context, metadata, photoFile, thumbnailFile)
|
||||
val hasEmbeddedGainmap = detectEmbeddedGainmap(context, photoFile)
|
||||
updateMetadata(context, photoId) { current ->
|
||||
current.copy(
|
||||
@@ -2890,7 +2778,6 @@ object GalleryManager {
|
||||
context: Context,
|
||||
metadata: MediaMetadata,
|
||||
photoFile: File,
|
||||
metadataFile: File,
|
||||
thumbnailFile: File
|
||||
) {
|
||||
val photoDir = photoFile.parentFile ?: return
|
||||
|
||||
@@ -3,6 +3,7 @@ package com.hinnka.mycamera.gallery
|
||||
import android.content.Context
|
||||
import android.content.ContentUris
|
||||
import android.provider.MediaStore
|
||||
import com.hinnka.mycamera.gallery.db.GalleryMediaStore
|
||||
import com.hinnka.mycamera.utils.StartupTrace
|
||||
import com.hinnka.mycamera.utils.PLog
|
||||
import kotlinx.coroutines.Dispatchers
|
||||
@@ -20,10 +21,6 @@ import kotlinx.coroutines.withContext
|
||||
*/
|
||||
class GalleryRepository(private val context: Context) {
|
||||
|
||||
private val queryPhotosMutex = Mutex()
|
||||
private val querySystemPhotosMutex = Mutex()
|
||||
private val querySystemVideosMutex = Mutex()
|
||||
|
||||
companion object {
|
||||
private const val TAG = "GalleryRepository"
|
||||
}
|
||||
@@ -53,7 +50,7 @@ class GalleryRepository(private val context: Context) {
|
||||
* 获取最新的一张照片
|
||||
*/
|
||||
suspend fun getLatestPhoto(): MediaData? = withContext(Dispatchers.IO) {
|
||||
queryPhotos(limit = 1).firstOrNull()
|
||||
GalleryMediaStore.queryLatestPhoto(context)
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -152,199 +149,188 @@ class GalleryRepository(private val context: Context) {
|
||||
* 查询私有存储中的照片
|
||||
*/
|
||||
private suspend fun queryPhotos(offset: Int = 0, limit: Int = Int.MAX_VALUE): List<MediaData> {
|
||||
StartupTrace.mark("queryPhotos limit=$limit")
|
||||
return queryPhotosMutex.withLock {
|
||||
val ids = GalleryManager.getPhotoIds(context)
|
||||
val photos = ids.mapNotNull { GalleryManager.buildPhotoData(context, it) }
|
||||
val sorted = photos.sortedByDescending { it.dateAdded }
|
||||
val result = sorted.drop(offset).take(limit)
|
||||
result
|
||||
}
|
||||
return GalleryMediaStore.queryPhotos(context, offset, limit)
|
||||
}
|
||||
|
||||
private suspend fun querySystemImages(offset: Int = 0, limit: Int? = null): List<MediaData> {
|
||||
return querySystemPhotosMutex.withLock {
|
||||
val items = mutableListOf<MediaData>()
|
||||
val projection = arrayOf(
|
||||
MediaStore.Images.Media._ID,
|
||||
MediaStore.Images.Media.DISPLAY_NAME,
|
||||
MediaStore.Images.Media.DATE_TAKEN,
|
||||
MediaStore.Images.Media.DATE_ADDED,
|
||||
MediaStore.Images.Media.SIZE,
|
||||
MediaStore.Images.Media.WIDTH,
|
||||
MediaStore.Images.Media.HEIGHT,
|
||||
MediaStore.Images.Media.MIME_TYPE
|
||||
)
|
||||
val cursor = if (limit != null || offset > 0) {
|
||||
val queryArgs = android.os.Bundle().apply {
|
||||
putInt(android.content.ContentResolver.QUERY_ARG_OFFSET, offset)
|
||||
limit?.let { putInt(android.content.ContentResolver.QUERY_ARG_LIMIT, it) }
|
||||
putString(
|
||||
android.content.ContentResolver.QUERY_ARG_SQL_SORT_ORDER,
|
||||
"${MediaStore.Images.Media.DATE_ADDED} DESC"
|
||||
)
|
||||
}
|
||||
context.contentResolver.query(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, projection, queryArgs, null)
|
||||
} else {
|
||||
context.contentResolver.query(
|
||||
MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
|
||||
projection,
|
||||
null,
|
||||
null,
|
||||
val items = mutableListOf<MediaData>()
|
||||
val projection = arrayOf(
|
||||
MediaStore.Images.Media._ID,
|
||||
MediaStore.Images.Media.DISPLAY_NAME,
|
||||
MediaStore.Images.Media.DATE_TAKEN,
|
||||
MediaStore.Images.Media.DATE_ADDED,
|
||||
MediaStore.Images.Media.SIZE,
|
||||
MediaStore.Images.Media.WIDTH,
|
||||
MediaStore.Images.Media.HEIGHT,
|
||||
MediaStore.Images.Media.MIME_TYPE
|
||||
)
|
||||
val cursor = if (limit != null || offset > 0) {
|
||||
val queryArgs = android.os.Bundle().apply {
|
||||
putInt(android.content.ContentResolver.QUERY_ARG_OFFSET, offset)
|
||||
limit?.let { putInt(android.content.ContentResolver.QUERY_ARG_LIMIT, it) }
|
||||
putString(
|
||||
android.content.ContentResolver.QUERY_ARG_SQL_SORT_ORDER,
|
||||
"${MediaStore.Images.Media.DATE_ADDED} DESC"
|
||||
)
|
||||
}
|
||||
cursor
|
||||
?.use { cursor ->
|
||||
PLog.d(TAG, "querySystemImages offset=$offset limit=$limit cursorCount=${cursor.count}")
|
||||
val idColumn = cursor.getColumnIndex(MediaStore.Images.Media._ID)
|
||||
if (idColumn < 0) {
|
||||
PLog.e(TAG, "querySystemImages missing required _ID column")
|
||||
return@use
|
||||
}
|
||||
val nameColumn = cursor.getColumnIndex(MediaStore.Images.Media.DISPLAY_NAME)
|
||||
val dateTakenColumn = cursor.getColumnIndex(MediaStore.Images.Media.DATE_TAKEN)
|
||||
val dateColumn = cursor.getColumnIndex(MediaStore.Images.Media.DATE_ADDED)
|
||||
val sizeColumn = cursor.getColumnIndex(MediaStore.Images.Media.SIZE)
|
||||
val widthColumn = cursor.getColumnIndex(MediaStore.Images.Media.WIDTH)
|
||||
val heightColumn = cursor.getColumnIndex(MediaStore.Images.Media.HEIGHT)
|
||||
val mimeColumn = cursor.getColumnIndex(MediaStore.Images.Media.MIME_TYPE)
|
||||
context.contentResolver.query(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, projection, queryArgs, null)
|
||||
} else {
|
||||
context.contentResolver.query(
|
||||
MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
|
||||
projection,
|
||||
null,
|
||||
null,
|
||||
"${MediaStore.Images.Media.DATE_ADDED} DESC"
|
||||
)
|
||||
}
|
||||
cursor
|
||||
?.use { cursor ->
|
||||
PLog.d(TAG, "querySystemImages offset=$offset limit=$limit cursorCount=${cursor.count}")
|
||||
val idColumn = cursor.getColumnIndex(MediaStore.Images.Media._ID)
|
||||
if (idColumn < 0) {
|
||||
PLog.e(TAG, "querySystemImages missing required _ID column")
|
||||
return@use
|
||||
}
|
||||
val nameColumn = cursor.getColumnIndex(MediaStore.Images.Media.DISPLAY_NAME)
|
||||
val dateTakenColumn = cursor.getColumnIndex(MediaStore.Images.Media.DATE_TAKEN)
|
||||
val dateColumn = cursor.getColumnIndex(MediaStore.Images.Media.DATE_ADDED)
|
||||
val sizeColumn = cursor.getColumnIndex(MediaStore.Images.Media.SIZE)
|
||||
val widthColumn = cursor.getColumnIndex(MediaStore.Images.Media.WIDTH)
|
||||
val heightColumn = cursor.getColumnIndex(MediaStore.Images.Media.HEIGHT)
|
||||
val mimeColumn = cursor.getColumnIndex(MediaStore.Images.Media.MIME_TYPE)
|
||||
|
||||
while (cursor.moveToNext()) {
|
||||
try {
|
||||
val id = cursor.getLong(idColumn)
|
||||
val contentUri = ContentUris.withAppendedId(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, id)
|
||||
val displayDate = resolveSystemMediaDate(
|
||||
dateTakenMillis = cursor.getOptionalLong(dateTakenColumn),
|
||||
dateAddedSeconds = cursor.getOptionalLong(dateColumn),
|
||||
mediaId = "image_$id"
|
||||
while (cursor.moveToNext()) {
|
||||
try {
|
||||
val id = cursor.getLong(idColumn)
|
||||
val contentUri = ContentUris.withAppendedId(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, id)
|
||||
val displayDate = resolveSystemMediaDate(
|
||||
dateTakenMillis = cursor.getOptionalLong(dateTakenColumn),
|
||||
dateAddedSeconds = cursor.getOptionalLong(dateColumn),
|
||||
mediaId = "image_$id"
|
||||
)
|
||||
items.add(
|
||||
MediaData(
|
||||
id = "image_$id",
|
||||
uri = contentUri,
|
||||
thumbnailUri = contentUri,
|
||||
displayName = cursor.getOptionalString(nameColumn) ?: "image_$id",
|
||||
dateAdded = displayDate,
|
||||
size = cursor.getOptionalLong(sizeColumn),
|
||||
width = cursor.getOptionalInt(widthColumn),
|
||||
height = cursor.getOptionalInt(heightColumn),
|
||||
mediaType = MediaType.IMAGE,
|
||||
mimeType = cursor.getOptionalString(mimeColumn),
|
||||
sourceUri = contentUri
|
||||
)
|
||||
items.add(
|
||||
MediaData(
|
||||
id = "image_$id",
|
||||
uri = contentUri,
|
||||
thumbnailUri = contentUri,
|
||||
displayName = cursor.getOptionalString(nameColumn) ?: "image_$id",
|
||||
dateAdded = displayDate,
|
||||
size = cursor.getOptionalLong(sizeColumn),
|
||||
width = cursor.getOptionalInt(widthColumn),
|
||||
height = cursor.getOptionalInt(heightColumn),
|
||||
mediaType = MediaType.IMAGE,
|
||||
mimeType = cursor.getOptionalString(mimeColumn),
|
||||
sourceUri = contentUri
|
||||
)
|
||||
)
|
||||
} catch (e: Exception) {
|
||||
PLog.e(TAG, "Failed to build system image item, skipping", e)
|
||||
}
|
||||
)
|
||||
} catch (e: Exception) {
|
||||
PLog.e(TAG, "Failed to build system image item, skipping", e)
|
||||
}
|
||||
}
|
||||
items
|
||||
}
|
||||
}
|
||||
return items
|
||||
}
|
||||
|
||||
private suspend fun querySystemVideos(offset: Int = 0, limit: Int? = null): List<MediaData> {
|
||||
return querySystemVideosMutex.withLock {
|
||||
val items = mutableListOf<MediaData>()
|
||||
val projection = arrayOf(
|
||||
MediaStore.Video.Media._ID,
|
||||
MediaStore.Video.Media.DISPLAY_NAME,
|
||||
MediaStore.Video.Media.DATE_TAKEN,
|
||||
MediaStore.Video.Media.DATE_ADDED,
|
||||
MediaStore.Video.Media.SIZE,
|
||||
MediaStore.Video.Media.WIDTH,
|
||||
MediaStore.Video.Media.HEIGHT,
|
||||
MediaStore.Video.Media.ORIENTATION,
|
||||
MediaStore.Video.Media.MIME_TYPE,
|
||||
MediaStore.Video.Media.DURATION
|
||||
)
|
||||
val cursor = if (limit != null || offset > 0) {
|
||||
val queryArgs = android.os.Bundle().apply {
|
||||
putInt(android.content.ContentResolver.QUERY_ARG_OFFSET, offset)
|
||||
limit?.let { putInt(android.content.ContentResolver.QUERY_ARG_LIMIT, it) }
|
||||
putString(
|
||||
android.content.ContentResolver.QUERY_ARG_SQL_SORT_ORDER,
|
||||
"${MediaStore.Video.Media.DATE_ADDED} DESC"
|
||||
)
|
||||
}
|
||||
context.contentResolver.query(MediaStore.Video.Media.EXTERNAL_CONTENT_URI, projection, queryArgs, null)
|
||||
} else {
|
||||
context.contentResolver.query(
|
||||
MediaStore.Video.Media.EXTERNAL_CONTENT_URI,
|
||||
projection,
|
||||
null,
|
||||
null,
|
||||
val items = mutableListOf<MediaData>()
|
||||
val projection = arrayOf(
|
||||
MediaStore.Video.Media._ID,
|
||||
MediaStore.Video.Media.DISPLAY_NAME,
|
||||
MediaStore.Video.Media.DATE_TAKEN,
|
||||
MediaStore.Video.Media.DATE_ADDED,
|
||||
MediaStore.Video.Media.SIZE,
|
||||
MediaStore.Video.Media.WIDTH,
|
||||
MediaStore.Video.Media.HEIGHT,
|
||||
MediaStore.Video.Media.ORIENTATION,
|
||||
MediaStore.Video.Media.MIME_TYPE,
|
||||
MediaStore.Video.Media.DURATION
|
||||
)
|
||||
val cursor = if (limit != null || offset > 0) {
|
||||
val queryArgs = android.os.Bundle().apply {
|
||||
putInt(android.content.ContentResolver.QUERY_ARG_OFFSET, offset)
|
||||
limit?.let { putInt(android.content.ContentResolver.QUERY_ARG_LIMIT, it) }
|
||||
putString(
|
||||
android.content.ContentResolver.QUERY_ARG_SQL_SORT_ORDER,
|
||||
"${MediaStore.Video.Media.DATE_ADDED} DESC"
|
||||
)
|
||||
}
|
||||
cursor
|
||||
?.use { cursor ->
|
||||
PLog.d(TAG, "querySystemVideos offset=$offset limit=$limit cursorCount=${cursor.count}")
|
||||
val idColumn = cursor.getColumnIndex(MediaStore.Video.Media._ID)
|
||||
if (idColumn < 0) {
|
||||
PLog.e(TAG, "querySystemVideos missing required _ID column")
|
||||
return@use
|
||||
}
|
||||
val nameColumn = cursor.getColumnIndex(MediaStore.Video.Media.DISPLAY_NAME)
|
||||
val dateTakenColumn = cursor.getColumnIndex(MediaStore.Video.Media.DATE_TAKEN)
|
||||
val dateColumn = cursor.getColumnIndex(MediaStore.Video.Media.DATE_ADDED)
|
||||
val sizeColumn = cursor.getColumnIndex(MediaStore.Video.Media.SIZE)
|
||||
val widthColumn = cursor.getColumnIndex(MediaStore.Video.Media.WIDTH)
|
||||
val heightColumn = cursor.getColumnIndex(MediaStore.Video.Media.HEIGHT)
|
||||
val orientationColumn = cursor.getColumnIndex(MediaStore.Video.Media.ORIENTATION)
|
||||
val mimeColumn = cursor.getColumnIndex(MediaStore.Video.Media.MIME_TYPE)
|
||||
val durationColumn = cursor.getColumnIndex(MediaStore.Video.Media.DURATION)
|
||||
context.contentResolver.query(MediaStore.Video.Media.EXTERNAL_CONTENT_URI, projection, queryArgs, null)
|
||||
} else {
|
||||
context.contentResolver.query(
|
||||
MediaStore.Video.Media.EXTERNAL_CONTENT_URI,
|
||||
projection,
|
||||
null,
|
||||
null,
|
||||
"${MediaStore.Video.Media.DATE_ADDED} DESC"
|
||||
)
|
||||
}
|
||||
cursor
|
||||
?.use { cursor ->
|
||||
PLog.d(TAG, "querySystemVideos offset=$offset limit=$limit cursorCount=${cursor.count}")
|
||||
val idColumn = cursor.getColumnIndex(MediaStore.Video.Media._ID)
|
||||
if (idColumn < 0) {
|
||||
PLog.e(TAG, "querySystemVideos missing required _ID column")
|
||||
return@use
|
||||
}
|
||||
val nameColumn = cursor.getColumnIndex(MediaStore.Video.Media.DISPLAY_NAME)
|
||||
val dateTakenColumn = cursor.getColumnIndex(MediaStore.Video.Media.DATE_TAKEN)
|
||||
val dateColumn = cursor.getColumnIndex(MediaStore.Video.Media.DATE_ADDED)
|
||||
val sizeColumn = cursor.getColumnIndex(MediaStore.Video.Media.SIZE)
|
||||
val widthColumn = cursor.getColumnIndex(MediaStore.Video.Media.WIDTH)
|
||||
val heightColumn = cursor.getColumnIndex(MediaStore.Video.Media.HEIGHT)
|
||||
val orientationColumn = cursor.getColumnIndex(MediaStore.Video.Media.ORIENTATION)
|
||||
val mimeColumn = cursor.getColumnIndex(MediaStore.Video.Media.MIME_TYPE)
|
||||
val durationColumn = cursor.getColumnIndex(MediaStore.Video.Media.DURATION)
|
||||
|
||||
while (cursor.moveToNext()) {
|
||||
try {
|
||||
val id = cursor.getLong(idColumn)
|
||||
val contentUri = ContentUris.withAppendedId(MediaStore.Video.Media.EXTERNAL_CONTENT_URI, id)
|
||||
val mimeType = cursor.getOptionalString(mimeColumn)
|
||||
val durationMs = cursor.getOptionalLong(durationColumn)
|
||||
val displayDate = resolveSystemMediaDate(
|
||||
dateTakenMillis = cursor.getOptionalLong(dateTakenColumn),
|
||||
dateAddedSeconds = cursor.getOptionalLong(dateColumn),
|
||||
mediaId = "video_$id"
|
||||
)
|
||||
val width = cursor.getOptionalInt(widthColumn)
|
||||
val height = cursor.getOptionalInt(heightColumn)
|
||||
val orientation = cursor.getOptionalInt(orientationColumn)
|
||||
while (cursor.moveToNext()) {
|
||||
try {
|
||||
val id = cursor.getLong(idColumn)
|
||||
val contentUri = ContentUris.withAppendedId(MediaStore.Video.Media.EXTERNAL_CONTENT_URI, id)
|
||||
val mimeType = cursor.getOptionalString(mimeColumn)
|
||||
val durationMs = cursor.getOptionalLong(durationColumn)
|
||||
val displayDate = resolveSystemMediaDate(
|
||||
dateTakenMillis = cursor.getOptionalLong(dateTakenColumn),
|
||||
dateAddedSeconds = cursor.getOptionalLong(dateColumn),
|
||||
mediaId = "video_$id"
|
||||
)
|
||||
val width = cursor.getOptionalInt(widthColumn)
|
||||
val height = cursor.getOptionalInt(heightColumn)
|
||||
val orientation = cursor.getOptionalInt(orientationColumn)
|
||||
|
||||
items.add(
|
||||
MediaData(
|
||||
id = "video_$id",
|
||||
uri = contentUri,
|
||||
thumbnailUri = contentUri,
|
||||
displayName = cursor.getOptionalString(nameColumn) ?: "video_$id",
|
||||
dateAdded = displayDate,
|
||||
size = cursor.getOptionalLong(sizeColumn),
|
||||
items.add(
|
||||
MediaData(
|
||||
id = "video_$id",
|
||||
uri = contentUri,
|
||||
thumbnailUri = contentUri,
|
||||
displayName = cursor.getOptionalString(nameColumn) ?: "video_$id",
|
||||
dateAdded = displayDate,
|
||||
size = cursor.getOptionalLong(sizeColumn),
|
||||
width = width,
|
||||
height = height,
|
||||
mediaType = MediaType.VIDEO,
|
||||
mimeType = mimeType,
|
||||
durationMs = durationMs,
|
||||
sourceUri = contentUri,
|
||||
metadata = MediaMetadata(
|
||||
mediaType = MediaType.VIDEO,
|
||||
dateTaken = displayDate,
|
||||
width = width,
|
||||
height = height,
|
||||
mediaType = MediaType.VIDEO,
|
||||
sourceUri = contentUri.toString(),
|
||||
mimeType = mimeType,
|
||||
durationMs = durationMs,
|
||||
sourceUri = contentUri,
|
||||
metadata = MediaMetadata(
|
||||
mediaType = MediaType.VIDEO,
|
||||
dateTaken = displayDate,
|
||||
width = width,
|
||||
height = height,
|
||||
sourceUri = contentUri.toString(),
|
||||
mimeType = mimeType,
|
||||
durationMs = durationMs,
|
||||
rotationDegrees = orientation,
|
||||
videoWidth = width,
|
||||
videoHeight = height
|
||||
)
|
||||
rotationDegrees = orientation,
|
||||
videoWidth = width,
|
||||
videoHeight = height
|
||||
)
|
||||
)
|
||||
} catch (e: Exception) {
|
||||
PLog.e(TAG, "Failed to build system video item, skipping", e)
|
||||
}
|
||||
)
|
||||
} catch (e: Exception) {
|
||||
PLog.e(TAG, "Failed to build system video item, skipping", e)
|
||||
}
|
||||
}
|
||||
items
|
||||
}
|
||||
}
|
||||
return items
|
||||
}
|
||||
|
||||
private fun resolveSystemMediaDate(
|
||||
|
||||
@@ -25,6 +25,7 @@ data class MediaData(
|
||||
val sourceUri: Uri? = null,
|
||||
var isMotionPhoto: Boolean = false,
|
||||
var isBurstPhoto: Boolean = false,
|
||||
// 复杂编辑元数据:LUT、边框、水印、RAW 参数、导出 URI 等。列表轻量查询不要填充它。
|
||||
var metadata: MediaMetadata? = null,
|
||||
var relatedPhoto: MediaData? = null
|
||||
) {
|
||||
|
||||
@@ -11,8 +11,8 @@ import com.hinnka.mycamera.lut.BaselineColorCorrectionTarget
|
||||
import com.hinnka.mycamera.model.ColorRecipeParams
|
||||
import com.hinnka.mycamera.hdr.HdrGainmapStrength
|
||||
import com.hinnka.mycamera.utils.PLog
|
||||
import org.json.JSONObject
|
||||
import com.hinnka.mycamera.raw.RawMetadata
|
||||
import org.json.JSONObject
|
||||
import java.text.SimpleDateFormat
|
||||
import java.util.*
|
||||
import kotlin.math.log2
|
||||
@@ -159,120 +159,6 @@ data class MediaMetadata(
|
||||
val resolution: String
|
||||
get() = "${width}x${height}"
|
||||
|
||||
fun toJson(): String {
|
||||
return JSONObject().apply {
|
||||
put("version", version)
|
||||
put("mediaType", mediaType.name.lowercase(Locale.US))
|
||||
put("lutId", lutId ?: JSONObject.NULL)
|
||||
// 色彩配方配置
|
||||
if (colorRecipeParams != null) {
|
||||
put("colorRecipeParams", JSONObject(colorRecipeParams.toJson()))
|
||||
} else {
|
||||
put("colorRecipeParams", JSONObject.NULL)
|
||||
}
|
||||
put("baselineTarget", baselineTarget?.name ?: JSONObject.NULL)
|
||||
put("baselineLutId", baselineLutId ?: JSONObject.NULL)
|
||||
if (baselineColorRecipeParams != null) {
|
||||
put("baselineColorRecipeParams", JSONObject(baselineColorRecipeParams.toJson()))
|
||||
} else {
|
||||
put("baselineColorRecipeParams", JSONObject.NULL)
|
||||
}
|
||||
// 软件处理参数
|
||||
put("sharpening", sharpening?.toDouble() ?: JSONObject.NULL)
|
||||
put("noiseReduction", noiseReduction?.toDouble() ?: JSONObject.NULL)
|
||||
put("chromaNoiseReduction", chromaNoiseReduction?.toDouble() ?: JSONObject.NULL)
|
||||
put("denoiseValue", rawDenoiseValue?.toDouble() ?: JSONObject.NULL)
|
||||
put("rawExposureCompensation", rawExposureCompensation?.toDouble() ?: JSONObject.NULL)
|
||||
put("rawAutoExposure", rawAutoExposure ?: JSONObject.NULL)
|
||||
put("rawBlackPointCorrection", rawBlackPointCorrection?.toDouble() ?: JSONObject.NULL)
|
||||
put("rawWhitePointCorrection", rawWhitePointCorrection?.toDouble() ?: JSONObject.NULL)
|
||||
put("rawAutoWhiteBalanceEstimate", rawAutoWhiteBalanceEstimate ?: JSONObject.NULL)
|
||||
put("rawDcpId", rawDcpId ?: JSONObject.NULL)
|
||||
put("rawBlackLevelMode", rawBlackLevelMode ?: JSONObject.NULL)
|
||||
put("rawCustomBlackLevel", rawCustomBlackLevel?.toDouble() ?: JSONObject.NULL)
|
||||
put("cameraId", cameraId ?: JSONObject.NULL)
|
||||
|
||||
put("frameId", frameId ?: JSONObject.NULL)
|
||||
put("width", width)
|
||||
put("height", height)
|
||||
put("ratio", ratio?.getDisplayName() ?: JSONObject.NULL)
|
||||
put(
|
||||
"cropRegion", if (cropRegion != null) {
|
||||
JSONObject().apply {
|
||||
put("left", cropRegion.left)
|
||||
put("top", cropRegion.top)
|
||||
put("right", cropRegion.right)
|
||||
put("bottom", cropRegion.bottom)
|
||||
}
|
||||
} else {
|
||||
JSONObject.NULL
|
||||
})
|
||||
put(
|
||||
"postCropRegion", if (postCropRegion != null) {
|
||||
JSONObject().apply {
|
||||
put("left", postCropRegion.left)
|
||||
put("top", postCropRegion.top)
|
||||
put("right", postCropRegion.right)
|
||||
put("bottom", postCropRegion.bottom)
|
||||
}
|
||||
} else {
|
||||
JSONObject.NULL
|
||||
})
|
||||
put("rotation", rotation)
|
||||
// 拍摄信息
|
||||
put("deviceModel", deviceModel ?: JSONObject.NULL)
|
||||
put("brand", brand ?: JSONObject.NULL)
|
||||
put("dateTaken", dateTaken ?: JSONObject.NULL)
|
||||
put("location", location ?: JSONObject.NULL)
|
||||
put("latitude", latitude ?: JSONObject.NULL)
|
||||
put("longitude", longitude ?: JSONObject.NULL)
|
||||
put("altitude", altitude ?: JSONObject.NULL)
|
||||
put("iso", iso ?: JSONObject.NULL)
|
||||
put("shutterSpeed", shutterSpeed ?: JSONObject.NULL)
|
||||
put("focalLength", focalLength ?: JSONObject.NULL)
|
||||
put("focalLength35mm", focalLength35mm ?: JSONObject.NULL)
|
||||
put("aperture", aperture ?: JSONObject.NULL)
|
||||
put("exposureBias", exposureBias ?: JSONObject.NULL)
|
||||
put("isImported", isImported)
|
||||
put("sourceUri", sourceUri ?: JSONObject.NULL)
|
||||
put("mimeType", mimeType ?: JSONObject.NULL)
|
||||
put("durationMs", durationMs ?: JSONObject.NULL)
|
||||
put("frameRate", frameRate ?: JSONObject.NULL)
|
||||
put("bitrate", bitrate ?: JSONObject.NULL)
|
||||
put("rotationDegrees", rotationDegrees ?: JSONObject.NULL)
|
||||
put("hasAudio", hasAudio ?: JSONObject.NULL)
|
||||
put("videoWidth", videoWidth ?: JSONObject.NULL)
|
||||
put("videoHeight", videoHeight ?: JSONObject.NULL)
|
||||
// 边框水印自定义
|
||||
val customPropsObj = JSONObject()
|
||||
customProperties.forEach { (k, v) -> customPropsObj.put(k, v) }
|
||||
put("customProperties", customPropsObj)
|
||||
// 导出的 URI 列表
|
||||
put("exportedUris", org.json.JSONArray(exportedUris))
|
||||
|
||||
// 计算摄影光圈与焦点
|
||||
put("computationalAperture", computationalAperture?.toDouble() ?: JSONObject.NULL)
|
||||
put("focusPointX", focusPointX?.toDouble() ?: JSONObject.NULL)
|
||||
put("focusPointY", focusPointY?.toDouble() ?: JSONObject.NULL)
|
||||
|
||||
// Live Photo 时间戳
|
||||
put("presentationTimestampUs", presentationTimestampUs ?: JSONObject.NULL)
|
||||
// DRO 模式
|
||||
put("droMode", droMode ?: JSONObject.NULL)
|
||||
put("software", software ?: JSONObject.NULL)
|
||||
put("isMirrored", isMirrored)
|
||||
put("colorSpace", colorSpace.name)
|
||||
put("manualHdrEffectEnabled", manualHdrEffectEnabled)
|
||||
put("hdrEffectStrength", hdrEffectStrength.toDouble())
|
||||
put("hasEmbeddedGainmap", hasEmbeddedGainmap)
|
||||
put("dynamicRangeProfile", dynamicRangeProfile ?: JSONObject.NULL)
|
||||
put("captureMode", captureMode ?: JSONObject.NULL)
|
||||
put("multipleExposureFrameCount", multipleExposureFrameCount ?: JSONObject.NULL)
|
||||
put("hasAiDenoisedBase", hasAiDenoisedBase)
|
||||
put("aiDenoiseStrength", aiDenoiseStrength?.toDouble() ?: JSONObject.NULL)
|
||||
}.toString(2)
|
||||
}
|
||||
|
||||
/**
|
||||
* 从 RawMetadata 补齐信息
|
||||
*/
|
||||
@@ -306,7 +192,8 @@ data class MediaMetadata(
|
||||
companion object {
|
||||
private const val TAG = "PhotoMetadata"
|
||||
|
||||
fun fromJson(json: String): MediaMetadata? {
|
||||
// 旧格式,以后不再更新
|
||||
fun fromLegacyJson(json: String): MediaMetadata? {
|
||||
return try {
|
||||
val obj = JSONObject(json)
|
||||
|
||||
|
||||
@@ -0,0 +1,16 @@
|
||||
package com.hinnka.mycamera.gallery.db
|
||||
|
||||
import androidx.room.TypeConverter
|
||||
|
||||
class GalleryConverters {
|
||||
@TypeConverter
|
||||
fun fromFloatArray(value: FloatArray?): String? {
|
||||
return value?.joinToString(";")
|
||||
}
|
||||
|
||||
@TypeConverter
|
||||
fun toFloatArray(value: String?): FloatArray? {
|
||||
if (value.isNullOrEmpty()) return null
|
||||
return value.split(";").mapNotNull { it.toFloatOrNull() }.toFloatArray()
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,33 @@
|
||||
package com.hinnka.mycamera.gallery.db
|
||||
|
||||
import android.content.Context
|
||||
import androidx.room.Database
|
||||
import androidx.room.Room
|
||||
import androidx.room.RoomDatabase
|
||||
|
||||
@Database(
|
||||
entities = [GalleryMediaEntity::class],
|
||||
version = 1,
|
||||
exportSchema = false
|
||||
)
|
||||
@androidx.room.TypeConverters(GalleryConverters::class)
|
||||
abstract class GalleryDatabase : RoomDatabase() {
|
||||
abstract fun galleryMediaDao(): GalleryMediaDao
|
||||
|
||||
companion object {
|
||||
@Volatile
|
||||
private var INSTANCE: GalleryDatabase? = null
|
||||
|
||||
fun getInstance(context: Context): GalleryDatabase {
|
||||
return INSTANCE ?: synchronized(this) {
|
||||
INSTANCE ?: Room.databaseBuilder(
|
||||
context.applicationContext,
|
||||
GalleryDatabase::class.java,
|
||||
"gallery_media.db"
|
||||
)
|
||||
.build()
|
||||
.also { INSTANCE = it }
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,95 @@
|
||||
package com.hinnka.mycamera.gallery.db
|
||||
|
||||
import com.hinnka.mycamera.model.ColorRecipeParams
|
||||
|
||||
object GalleryDelimitedCodec {
|
||||
fun encodeList(values: List<String>): String? {
|
||||
if (values.isEmpty()) return null
|
||||
return values.joinToString(separator = ",") { escape(it) }
|
||||
}
|
||||
|
||||
fun decodeList(value: String?): List<String> {
|
||||
if (value.isNullOrEmpty()) return emptyList()
|
||||
return splitEscaped(value, ',').map { unescape(it) }
|
||||
}
|
||||
|
||||
fun encodeMap(values: Map<String, String>): String? {
|
||||
if (values.isEmpty()) return null
|
||||
return values.entries.joinToString(separator = ",") { (key, value) ->
|
||||
"${escape(key)}=${escape(value)}"
|
||||
}
|
||||
}
|
||||
|
||||
fun decodeMap(value: String?): Map<String, String> {
|
||||
if (value.isNullOrEmpty()) return emptyMap()
|
||||
return splitEscaped(value, ',').mapNotNull { entry ->
|
||||
val index = firstUnescapedIndexOf(entry, '=')
|
||||
if (index < 0) return@mapNotNull null
|
||||
unescape(entry.substring(0, index)) to unescape(entry.substring(index + 1))
|
||||
}.toMap()
|
||||
}
|
||||
|
||||
private fun escape(value: String): String {
|
||||
return buildString(value.length) {
|
||||
value.forEach { char ->
|
||||
if (char == '\\' || char == ',' || char == '=') append('\\')
|
||||
append(char)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private fun unescape(value: String): String {
|
||||
return buildString(value.length) {
|
||||
var escaping = false
|
||||
value.forEach { char ->
|
||||
if (escaping) {
|
||||
append(char)
|
||||
escaping = false
|
||||
} else if (char == '\\') {
|
||||
escaping = true
|
||||
} else {
|
||||
append(char)
|
||||
}
|
||||
}
|
||||
if (escaping) append('\\')
|
||||
}
|
||||
}
|
||||
|
||||
private fun splitEscaped(value: String, delimiter: Char): List<String> {
|
||||
val result = mutableListOf<String>()
|
||||
val current = StringBuilder()
|
||||
var escaping = false
|
||||
value.forEach { char ->
|
||||
when {
|
||||
escaping -> {
|
||||
current.append('\\')
|
||||
current.append(char)
|
||||
escaping = false
|
||||
}
|
||||
char == '\\' -> escaping = true
|
||||
char == delimiter -> {
|
||||
result.add(current.toString())
|
||||
current.clear()
|
||||
}
|
||||
else -> current.append(char)
|
||||
}
|
||||
}
|
||||
if (escaping) current.append('\\')
|
||||
result.add(current.toString())
|
||||
return result
|
||||
}
|
||||
|
||||
private fun firstUnescapedIndexOf(value: String, target: Char): Int {
|
||||
var escaping = false
|
||||
value.forEachIndexed { index, char ->
|
||||
if (escaping) {
|
||||
escaping = false
|
||||
} else if (char == '\\') {
|
||||
escaping = true
|
||||
} else if (char == target) {
|
||||
return index
|
||||
}
|
||||
}
|
||||
return -1
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,36 @@
|
||||
package com.hinnka.mycamera.gallery.db
|
||||
|
||||
import androidx.room.Dao
|
||||
import androidx.room.Delete
|
||||
import androidx.room.Query
|
||||
import androidx.room.Upsert
|
||||
|
||||
@Dao
|
||||
interface GalleryMediaDao {
|
||||
@Query("SELECT * FROM gallery_media WHERE id = :id LIMIT 1")
|
||||
suspend fun getById(id: String): GalleryMediaEntity?
|
||||
|
||||
@Query("SELECT * FROM gallery_media ORDER BY dateAdded DESC LIMIT :limit OFFSET :offset")
|
||||
suspend fun queryPage(offset: Int, limit: Int): List<GalleryMediaEntity>
|
||||
|
||||
@Query("SELECT * FROM gallery_media ORDER BY dateAdded DESC LIMIT 1")
|
||||
suspend fun queryLatest(): GalleryMediaEntity?
|
||||
|
||||
@Query("SELECT id FROM gallery_media ORDER BY dateAdded DESC")
|
||||
suspend fun getIds(): List<String>
|
||||
|
||||
@Query("SELECT COUNT(*) FROM gallery_media")
|
||||
suspend fun count(): Int
|
||||
|
||||
@Upsert
|
||||
suspend fun upsert(entity: GalleryMediaEntity)
|
||||
|
||||
@Upsert
|
||||
suspend fun upsertAll(entities: List<GalleryMediaEntity>)
|
||||
|
||||
@Delete
|
||||
suspend fun delete(entity: GalleryMediaEntity)
|
||||
|
||||
@Query("DELETE FROM gallery_media WHERE id = :id")
|
||||
suspend fun deleteById(id: String)
|
||||
}
|
||||
@@ -0,0 +1,109 @@
|
||||
package com.hinnka.mycamera.gallery.db
|
||||
|
||||
import androidx.room.Embedded
|
||||
import androidx.room.Entity
|
||||
import androidx.room.Index
|
||||
import androidx.room.PrimaryKey
|
||||
import com.hinnka.mycamera.model.ColorRecipeParams
|
||||
|
||||
@Entity(
|
||||
tableName = "gallery_media",
|
||||
indices = [
|
||||
Index(value = ["dateAdded"]),
|
||||
Index(value = ["mediaType"])
|
||||
]
|
||||
)
|
||||
data class GalleryMediaEntity(
|
||||
@PrimaryKey val id: String,
|
||||
val mediaType: String,
|
||||
val dateAdded: Long,
|
||||
val size: Long,
|
||||
val photoPath: String?,
|
||||
val thumbnailPath: String?,
|
||||
val videoPath: String?,
|
||||
val dngPath: String?,
|
||||
val yuvPath: String?,
|
||||
val hasOriginal: Boolean,
|
||||
val hasThumbnail: Boolean,
|
||||
val hasVideo: Boolean,
|
||||
val hasDng: Boolean,
|
||||
val hasYuv: Boolean,
|
||||
val isBurstPhoto: Boolean,
|
||||
val updatedAt: Long,
|
||||
|
||||
val version: Int,
|
||||
val lutId: String?,
|
||||
@Embedded(prefix = "recipe_")
|
||||
val colorRecipeParams: ColorRecipeParams?,
|
||||
val baselineTarget: String?,
|
||||
val baselineLutId: String?,
|
||||
@Embedded(prefix = "baseline_recipe_")
|
||||
val baselineColorRecipeParams: ColorRecipeParams?,
|
||||
val sharpening: Float?,
|
||||
val noiseReduction: Float?,
|
||||
val chromaNoiseReduction: Float?,
|
||||
val rawDenoiseValue: Float?,
|
||||
val rawExposureCompensation: Float?,
|
||||
val rawAutoExposure: Boolean?,
|
||||
val rawBlackPointCorrection: Float?,
|
||||
val rawWhitePointCorrection: Float?,
|
||||
val rawAutoWhiteBalanceEstimate: Boolean?,
|
||||
val rawDcpId: String?,
|
||||
val frameId: String?,
|
||||
val width: Int,
|
||||
val height: Int,
|
||||
val ratio: String?,
|
||||
val cropLeft: Int?,
|
||||
val cropTop: Int?,
|
||||
val cropRight: Int?,
|
||||
val cropBottom: Int?,
|
||||
val rotation: Int,
|
||||
val deviceModel: String?,
|
||||
val brand: String?,
|
||||
val dateTaken: Long?,
|
||||
val location: String?,
|
||||
val latitude: Double?,
|
||||
val longitude: Double?,
|
||||
val altitude: Double?,
|
||||
val iso: Int?,
|
||||
val shutterSpeed: String?,
|
||||
val focalLength: String?,
|
||||
val focalLength35mm: String?,
|
||||
val aperture: String?,
|
||||
val exposureBias: Float?,
|
||||
val isImported: Boolean,
|
||||
val sourceUri: String?,
|
||||
val mimeType: String?,
|
||||
val durationMs: Long?,
|
||||
val frameRate: Int?,
|
||||
val bitrate: Long?,
|
||||
val rotationDegrees: Int?,
|
||||
val hasAudio: Boolean?,
|
||||
val videoWidth: Int?,
|
||||
val videoHeight: Int?,
|
||||
val customProperties: String?,
|
||||
val exportedUris: String?,
|
||||
val computationalAperture: Float?,
|
||||
val focusPointX: Float?,
|
||||
val focusPointY: Float?,
|
||||
val postCropLeft: Int?,
|
||||
val postCropTop: Int?,
|
||||
val postCropRight: Int?,
|
||||
val postCropBottom: Int?,
|
||||
val presentationTimestampUs: Long?,
|
||||
val droMode: String?,
|
||||
val software: String?,
|
||||
val isMirrored: Boolean,
|
||||
val colorSpace: String,
|
||||
val manualHdrEffectEnabled: Boolean,
|
||||
val hdrEffectStrength: Float,
|
||||
val hasEmbeddedGainmap: Boolean,
|
||||
val dynamicRangeProfile: String?,
|
||||
val captureMode: String?,
|
||||
val multipleExposureFrameCount: Int?,
|
||||
val hasAiDenoisedBase: Boolean,
|
||||
val aiDenoiseStrength: Float?,
|
||||
val rawBlackLevelMode: String?,
|
||||
val rawCustomBlackLevel: Float?,
|
||||
val cameraId: String?
|
||||
)
|
||||
@@ -0,0 +1,407 @@
|
||||
package com.hinnka.mycamera.gallery.db
|
||||
|
||||
import android.content.Context
|
||||
import android.graphics.BitmapFactory
|
||||
import android.graphics.ColorSpace
|
||||
import android.graphics.Rect
|
||||
import android.net.Uri
|
||||
import android.os.Environment
|
||||
import androidx.core.net.toUri
|
||||
import com.hinnka.mycamera.camera.AspectRatio
|
||||
import com.hinnka.mycamera.gallery.GalleryManager
|
||||
import com.hinnka.mycamera.gallery.MediaData
|
||||
import com.hinnka.mycamera.gallery.MediaMetadata
|
||||
import com.hinnka.mycamera.gallery.MediaType
|
||||
import com.hinnka.mycamera.hdr.HdrGainmapStrength
|
||||
import com.hinnka.mycamera.lut.BaselineColorCorrectionTarget
|
||||
import com.hinnka.mycamera.utils.PLog
|
||||
import com.hinnka.mycamera.utils.StartupTrace
|
||||
import kotlinx.coroutines.Dispatchers
|
||||
import kotlinx.coroutines.sync.Mutex
|
||||
import kotlinx.coroutines.sync.withLock
|
||||
import kotlinx.coroutines.withContext
|
||||
import java.io.File
|
||||
|
||||
object GalleryMediaStore {
|
||||
private const val TAG = "GalleryMediaStore"
|
||||
private const val PREFS_NAME = "gallery_media_store"
|
||||
private const val KEY_FILE_INDEXED = "file_indexed_v2"
|
||||
private const val PHOTOS_DIR = "photos"
|
||||
private const val BURST_DIR = "burst"
|
||||
private const val PHOTO_FILE = "original.jpg"
|
||||
private const val YUV_FILE = "original.jxl"
|
||||
private const val VIDEO_FILE = "video.mp4"
|
||||
private const val DNG_FILE = "original.dng"
|
||||
private const val THUMBNAIL_FILE = "thumbnail.jpg"
|
||||
|
||||
private val migrationMutex = Mutex()
|
||||
|
||||
@Volatile
|
||||
private var migrationChecked = false
|
||||
|
||||
suspend fun ensureMigrated(context: Context) {
|
||||
if (migrationChecked) return
|
||||
val appContext = context.applicationContext
|
||||
migrationMutex.withLock {
|
||||
if (migrationChecked) return
|
||||
withContext(Dispatchers.IO) {
|
||||
val prefs = appContext.getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE)
|
||||
val dao = GalleryDatabase.getInstance(appContext).galleryMediaDao()
|
||||
val shouldIndex = !prefs.getBoolean(KEY_FILE_INDEXED, false) || dao.count() == 0
|
||||
if (shouldIndex) {
|
||||
val entities = getPhotosBaseDir(appContext)
|
||||
.listFiles()
|
||||
?.asSequence()
|
||||
?.filter { it.isDirectory }
|
||||
?.mapNotNull { buildMigrateEntity(appContext, it) }
|
||||
?.toList()
|
||||
?: emptyList()
|
||||
if (entities.isNotEmpty()) dao.upsertAll(entities)
|
||||
prefs.edit().putBoolean(KEY_FILE_INDEXED, true).apply()
|
||||
PLog.d(TAG, "File gallery index complete: ${entities.size} records")
|
||||
}
|
||||
migrationChecked = true
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
suspend fun loadMetadata(context: Context, photoId: String): MediaMetadata? {
|
||||
ensureMigrated(context)
|
||||
return withContext(Dispatchers.IO) {
|
||||
val dao = GalleryDatabase.getInstance(context.applicationContext).galleryMediaDao()
|
||||
val entity = dao.getById(photoId) ?: return@withContext null
|
||||
entity.toMetadata()
|
||||
}
|
||||
}
|
||||
|
||||
suspend fun saveMetadata(context: Context, photoId: String, metadata: MediaMetadata): Boolean {
|
||||
ensureMigrated(context)
|
||||
return withContext(Dispatchers.IO) {
|
||||
try {
|
||||
GalleryDatabase.getInstance(context.applicationContext)
|
||||
.galleryMediaDao()
|
||||
.upsert(buildEntity(context.applicationContext, photoId, metadata))
|
||||
true
|
||||
} catch (e: Exception) {
|
||||
PLog.e(TAG, "Failed to save metadata to DB for photo: $photoId", e)
|
||||
false
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
suspend fun updateMetadata(
|
||||
context: Context,
|
||||
photoId: String,
|
||||
update: (MediaMetadata) -> MediaMetadata
|
||||
): MediaMetadata? {
|
||||
val current = loadMetadata(context, photoId) ?: return null
|
||||
val updated = update(current)
|
||||
return if (saveMetadata(context, photoId, updated)) updated else null
|
||||
}
|
||||
|
||||
suspend fun deleteMedia(context: Context, photoId: String) {
|
||||
ensureMigrated(context)
|
||||
withContext(Dispatchers.IO) {
|
||||
GalleryDatabase.getInstance(context.applicationContext).galleryMediaDao().deleteById(photoId)
|
||||
}
|
||||
}
|
||||
|
||||
suspend fun queryPhotos(context: Context, offset: Int, limit: Int): List<MediaData> {
|
||||
ensureMigrated(context)
|
||||
return withContext(Dispatchers.IO) {
|
||||
val dao = GalleryDatabase.getInstance(context.applicationContext).galleryMediaDao()
|
||||
val list = dao.queryPage(offset, limit)
|
||||
val result = list.mapNotNull { entity ->
|
||||
entity.toMediaData(context.applicationContext, entity.toMetadata())
|
||||
}
|
||||
result
|
||||
}
|
||||
}
|
||||
|
||||
suspend fun queryLatestPhoto(context: Context): MediaData? {
|
||||
ensureMigrated(context)
|
||||
return withContext(Dispatchers.IO) {
|
||||
val dao = GalleryDatabase.getInstance(context.applicationContext).galleryMediaDao()
|
||||
dao.queryPage(offset = 0, limit = 1).firstNotNullOfOrNull { entity ->
|
||||
entity.toMediaData(context.applicationContext, entity.toMetadata())
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
suspend fun getPhotoData(context: Context, photoId: String): MediaData? {
|
||||
ensureMigrated(context)
|
||||
return withContext(Dispatchers.IO) {
|
||||
val dao = GalleryDatabase.getInstance(context.applicationContext).galleryMediaDao()
|
||||
val entity = dao.getById(photoId) ?: return@withContext null
|
||||
entity.toMediaData(context.applicationContext, entity.toMetadata())
|
||||
}
|
||||
}
|
||||
|
||||
suspend fun getPhotoIds(context: Context): List<String> {
|
||||
ensureMigrated(context)
|
||||
return withContext(Dispatchers.IO) {
|
||||
GalleryDatabase.getInstance(context.applicationContext).galleryMediaDao().getIds()
|
||||
}
|
||||
}
|
||||
|
||||
private fun buildMigrateEntity(context: Context, photoDir: File): GalleryMediaEntity? {
|
||||
val metadataFile = File(photoDir, "metadata.json")
|
||||
if (!metadataFile.exists()) return null
|
||||
val content = metadataFile.readText()
|
||||
val metadata = MediaMetadata.fromLegacyJson(content) ?: return null
|
||||
return buildEntity(context, photoDir.name, metadata)
|
||||
}
|
||||
|
||||
private fun buildEntity(context: Context, photoId: String, metadata: MediaMetadata): GalleryMediaEntity {
|
||||
val photoDir = getPhotoDir(context, photoId)
|
||||
val photoFile = File(photoDir, PHOTO_FILE)
|
||||
val thumbnailFile = File(photoDir, THUMBNAIL_FILE)
|
||||
val videoFile = File(photoDir, VIDEO_FILE)
|
||||
val dngFile = File(photoDir, DNG_FILE)
|
||||
val yuvFile = File(photoDir, YUV_FILE)
|
||||
val originalFile = dngFile.takeIf { it.exists() } ?: yuvFile.takeIf { it.exists() } ?: photoFile
|
||||
val isVideo = metadata.mediaType == MediaType.VIDEO
|
||||
val dateAdded = if (isVideo) {
|
||||
metadata.dateTaken ?: photoDir.lastModified().takeIf { it > 0L } ?: System.currentTimeMillis()
|
||||
} else {
|
||||
originalFile.lastModified().takeIf { originalFile.exists() && it > 0L }
|
||||
?: metadata.dateTaken
|
||||
?: photoDir.lastModified().takeIf { it > 0L }
|
||||
?: System.currentTimeMillis()
|
||||
}
|
||||
return GalleryMediaEntity(
|
||||
id = photoId,
|
||||
mediaType = metadata.mediaType.name,
|
||||
dateAdded = dateAdded,
|
||||
size = if (photoFile.exists()) photoFile.length() else 0L,
|
||||
photoPath = photoFile.absolutePath,
|
||||
thumbnailPath = thumbnailFile.absolutePath,
|
||||
videoPath = videoFile.absolutePath,
|
||||
dngPath = dngFile.absolutePath,
|
||||
yuvPath = yuvFile.absolutePath,
|
||||
hasOriginal = photoFile.exists(),
|
||||
hasThumbnail = thumbnailFile.exists(),
|
||||
hasVideo = videoFile.exists(),
|
||||
hasDng = dngFile.exists(),
|
||||
hasYuv = yuvFile.exists(),
|
||||
isBurstPhoto = hasBurstPhotos(photoDir),
|
||||
updatedAt = System.currentTimeMillis(),
|
||||
version = metadata.version,
|
||||
lutId = metadata.lutId,
|
||||
colorRecipeParams = metadata.colorRecipeParams,
|
||||
baselineTarget = metadata.baselineTarget?.name,
|
||||
baselineLutId = metadata.baselineLutId,
|
||||
baselineColorRecipeParams = metadata.baselineColorRecipeParams,
|
||||
sharpening = metadata.sharpening,
|
||||
noiseReduction = metadata.noiseReduction,
|
||||
chromaNoiseReduction = metadata.chromaNoiseReduction,
|
||||
rawDenoiseValue = metadata.rawDenoiseValue,
|
||||
rawExposureCompensation = metadata.rawExposureCompensation,
|
||||
rawAutoExposure = metadata.rawAutoExposure,
|
||||
rawBlackPointCorrection = metadata.rawBlackPointCorrection,
|
||||
rawWhitePointCorrection = metadata.rawWhitePointCorrection,
|
||||
rawAutoWhiteBalanceEstimate = metadata.rawAutoWhiteBalanceEstimate,
|
||||
rawDcpId = metadata.rawDcpId,
|
||||
frameId = metadata.frameId,
|
||||
width = metadata.width,
|
||||
height = metadata.height,
|
||||
ratio = metadata.ratio?.name,
|
||||
cropLeft = metadata.cropRegion?.left,
|
||||
cropTop = metadata.cropRegion?.top,
|
||||
cropRight = metadata.cropRegion?.right,
|
||||
cropBottom = metadata.cropRegion?.bottom,
|
||||
rotation = metadata.rotation,
|
||||
deviceModel = metadata.deviceModel,
|
||||
brand = metadata.brand,
|
||||
dateTaken = metadata.dateTaken,
|
||||
location = metadata.location,
|
||||
latitude = metadata.latitude,
|
||||
longitude = metadata.longitude,
|
||||
altitude = metadata.altitude,
|
||||
iso = metadata.iso,
|
||||
shutterSpeed = metadata.shutterSpeed,
|
||||
focalLength = metadata.focalLength,
|
||||
focalLength35mm = metadata.focalLength35mm,
|
||||
aperture = metadata.aperture,
|
||||
exposureBias = metadata.exposureBias,
|
||||
isImported = metadata.isImported,
|
||||
sourceUri = metadata.sourceUri,
|
||||
mimeType = metadata.mimeType ?: if (isVideo) null else "image/jpeg",
|
||||
durationMs = metadata.durationMs,
|
||||
frameRate = metadata.frameRate,
|
||||
bitrate = metadata.bitrate,
|
||||
rotationDegrees = metadata.rotationDegrees,
|
||||
hasAudio = metadata.hasAudio,
|
||||
videoWidth = metadata.videoWidth,
|
||||
videoHeight = metadata.videoHeight,
|
||||
customProperties = GalleryDelimitedCodec.encodeMap(metadata.customProperties),
|
||||
exportedUris = GalleryDelimitedCodec.encodeList(metadata.exportedUris),
|
||||
computationalAperture = metadata.computationalAperture,
|
||||
focusPointX = metadata.focusPointX,
|
||||
focusPointY = metadata.focusPointY,
|
||||
postCropLeft = metadata.postCropRegion?.left,
|
||||
postCropTop = metadata.postCropRegion?.top,
|
||||
postCropRight = metadata.postCropRegion?.right,
|
||||
postCropBottom = metadata.postCropRegion?.bottom,
|
||||
presentationTimestampUs = metadata.presentationTimestampUs,
|
||||
droMode = metadata.droMode,
|
||||
software = metadata.software,
|
||||
isMirrored = metadata.isMirrored,
|
||||
colorSpace = metadata.colorSpace.name,
|
||||
manualHdrEffectEnabled = metadata.manualHdrEffectEnabled,
|
||||
hdrEffectStrength = metadata.hdrEffectStrength,
|
||||
hasEmbeddedGainmap = metadata.hasEmbeddedGainmap,
|
||||
dynamicRangeProfile = metadata.dynamicRangeProfile,
|
||||
captureMode = metadata.captureMode,
|
||||
multipleExposureFrameCount = metadata.multipleExposureFrameCount,
|
||||
hasAiDenoisedBase = metadata.hasAiDenoisedBase,
|
||||
aiDenoiseStrength = metadata.aiDenoiseStrength,
|
||||
rawBlackLevelMode = metadata.rawBlackLevelMode,
|
||||
rawCustomBlackLevel = metadata.rawCustomBlackLevel,
|
||||
cameraId = metadata.cameraId
|
||||
)
|
||||
}
|
||||
|
||||
private fun GalleryMediaEntity.toMediaData(context: Context, metadata: MediaMetadata): MediaData? {
|
||||
val photoDir = getPhotoDir(context, id)
|
||||
val photoFile = File(photoDir, PHOTO_FILE)
|
||||
val thumbnailFile = File(photoDir, THUMBNAIL_FILE)
|
||||
val videoFile = File(photoDir, VIDEO_FILE)
|
||||
val dngFile = File(photoDir, DNG_FILE)
|
||||
val yuvFile = File(photoDir, YUV_FILE)
|
||||
val thumbnailUri = when {
|
||||
thumbnailFile.exists() -> Uri.fromFile(thumbnailFile)
|
||||
sourceUri != null -> sourceUri.toUri()
|
||||
else -> return null
|
||||
}
|
||||
val resolvedType = runCatching { MediaType.valueOf(mediaType) }.getOrDefault(MediaType.IMAGE)
|
||||
if (resolvedType == MediaType.VIDEO) {
|
||||
val resolvedSourceUri = sourceUri?.let(Uri::parse) ?: return null
|
||||
return MediaData(
|
||||
id = id,
|
||||
uri = resolvedSourceUri,
|
||||
thumbnailUri = thumbnailUri,
|
||||
displayName = resolvedSourceUri.lastPathSegment ?: "video_$id",
|
||||
dateAdded = dateTaken ?: dateAdded,
|
||||
size = size,
|
||||
width = videoWidth ?: width,
|
||||
height = videoHeight ?: height,
|
||||
mediaType = MediaType.VIDEO,
|
||||
mimeType = mimeType,
|
||||
durationMs = durationMs,
|
||||
sourceUri = resolvedSourceUri,
|
||||
metadata = metadata
|
||||
)
|
||||
}
|
||||
|
||||
if (!photoFile.exists()) return null
|
||||
val originalFile = dngFile.takeIf { it.exists() } ?: yuvFile.takeIf { it.exists() } ?: photoFile
|
||||
return MediaData(
|
||||
id = id,
|
||||
uri = Uri.fromFile(photoFile),
|
||||
thumbnailUri = thumbnailUri,
|
||||
displayName = photoFile.name,
|
||||
dateAdded = originalFile.lastModified().takeIf { it > 0L } ?: dateAdded,
|
||||
size = photoFile.length(),
|
||||
width = width,
|
||||
height = height,
|
||||
mediaType = MediaType.IMAGE,
|
||||
mimeType = mimeType ?: "image/jpeg",
|
||||
sourceUri = sourceUri?.let(Uri::parse),
|
||||
isMotionPhoto = videoFile.exists(),
|
||||
isBurstPhoto = hasBurstPhotos(photoDir),
|
||||
metadata = metadata
|
||||
)
|
||||
}
|
||||
|
||||
private fun GalleryMediaEntity.toMetadata(): MediaMetadata {
|
||||
return MediaMetadata(
|
||||
version = version.takeIf { it > 0 } ?: MediaMetadata().version,
|
||||
mediaType = runCatching { MediaType.valueOf(mediaType) }.getOrDefault(MediaType.IMAGE),
|
||||
lutId = lutId,
|
||||
colorRecipeParams = colorRecipeParams,
|
||||
baselineTarget = baselineTarget?.let { runCatching { BaselineColorCorrectionTarget.valueOf(it) }.getOrNull() },
|
||||
baselineLutId = baselineLutId,
|
||||
baselineColorRecipeParams = baselineColorRecipeParams,
|
||||
sharpening = sharpening,
|
||||
noiseReduction = noiseReduction,
|
||||
chromaNoiseReduction = chromaNoiseReduction,
|
||||
rawDenoiseValue = rawDenoiseValue,
|
||||
rawExposureCompensation = rawExposureCompensation,
|
||||
rawAutoExposure = rawAutoExposure,
|
||||
rawBlackPointCorrection = rawBlackPointCorrection,
|
||||
rawWhitePointCorrection = rawWhitePointCorrection,
|
||||
rawAutoWhiteBalanceEstimate = rawAutoWhiteBalanceEstimate,
|
||||
rawDcpId = rawDcpId,
|
||||
frameId = frameId,
|
||||
width = width,
|
||||
height = height,
|
||||
ratio = ratio?.let { runCatching { AspectRatio.valueOf(it) }.getOrNull() },
|
||||
cropRegion = rectOrNull(cropLeft, cropTop, cropRight, cropBottom),
|
||||
rotation = rotation,
|
||||
deviceModel = deviceModel,
|
||||
brand = brand,
|
||||
dateTaken = dateTaken,
|
||||
location = location,
|
||||
latitude = latitude,
|
||||
longitude = longitude,
|
||||
altitude = altitude,
|
||||
iso = iso,
|
||||
shutterSpeed = shutterSpeed,
|
||||
focalLength = focalLength,
|
||||
focalLength35mm = focalLength35mm,
|
||||
aperture = aperture,
|
||||
exposureBias = exposureBias,
|
||||
isImported = isImported,
|
||||
sourceUri = sourceUri,
|
||||
mimeType = mimeType,
|
||||
durationMs = durationMs,
|
||||
frameRate = frameRate,
|
||||
bitrate = bitrate,
|
||||
rotationDegrees = rotationDegrees,
|
||||
hasAudio = hasAudio,
|
||||
videoWidth = videoWidth,
|
||||
videoHeight = videoHeight,
|
||||
customProperties = GalleryDelimitedCodec.decodeMap(customProperties),
|
||||
exportedUris = GalleryDelimitedCodec.decodeList(exportedUris),
|
||||
computationalAperture = computationalAperture,
|
||||
focusPointX = focusPointX,
|
||||
focusPointY = focusPointY,
|
||||
postCropRegion = rectOrNull(postCropLeft, postCropTop, postCropRight, postCropBottom),
|
||||
presentationTimestampUs = presentationTimestampUs,
|
||||
droMode = droMode,
|
||||
software = software,
|
||||
isMirrored = isMirrored,
|
||||
colorSpace = runCatching { ColorSpace.Named.valueOf(colorSpace) }.getOrDefault(ColorSpace.Named.SRGB),
|
||||
manualHdrEffectEnabled = manualHdrEffectEnabled,
|
||||
hdrEffectStrength = HdrGainmapStrength.coerce(hdrEffectStrength),
|
||||
hasEmbeddedGainmap = hasEmbeddedGainmap,
|
||||
dynamicRangeProfile = dynamicRangeProfile,
|
||||
captureMode = captureMode,
|
||||
multipleExposureFrameCount = multipleExposureFrameCount,
|
||||
hasAiDenoisedBase = hasAiDenoisedBase,
|
||||
aiDenoiseStrength = aiDenoiseStrength,
|
||||
rawBlackLevelMode = rawBlackLevelMode,
|
||||
rawCustomBlackLevel = rawCustomBlackLevel,
|
||||
cameraId = cameraId
|
||||
)
|
||||
}
|
||||
|
||||
private fun rectOrNull(left: Int?, top: Int?, right: Int?, bottom: Int?): Rect? {
|
||||
if (left == null || top == null || right == null || bottom == null) return null
|
||||
return Rect(left, top, right, bottom)
|
||||
}
|
||||
|
||||
private fun getPhotosBaseDir(context: Context): File {
|
||||
return File(context.getExternalFilesDir(Environment.DIRECTORY_PICTURES), PHOTOS_DIR)
|
||||
}
|
||||
|
||||
private fun getPhotoDir(context: Context, photoId: String): File {
|
||||
return File(getPhotosBaseDir(context), photoId)
|
||||
}
|
||||
|
||||
private fun hasBurstPhotos(photoDir: File): Boolean {
|
||||
val burstDir = File(photoDir, BURST_DIR)
|
||||
return burstDir.exists() && (burstDir.listFiles()?.isNotEmpty() == true)
|
||||
}
|
||||
}
|
||||
@@ -24,7 +24,7 @@ class PhotoTransformation(
|
||||
private val chromaNoiseReduction: Float = 0f
|
||||
) : Transformation {
|
||||
|
||||
override val cacheKey: String = "photo_${metadata.toJson().hashCode()}_s${sharpening}_n${noiseReduction}_c${chromaNoiseReduction}"
|
||||
override val cacheKey: String = "photo_${metadata.hashCode()}_s${sharpening}_n${noiseReduction}_c${chromaNoiseReduction}"
|
||||
|
||||
override suspend fun transform(input: Bitmap, size: Size): Bitmap {
|
||||
return photoProcessor.processBitmap(
|
||||
@@ -32,4 +32,3 @@ class PhotoTransformation(
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -47,6 +47,7 @@ import androidx.compose.ui.graphics.StrokeCap
|
||||
import androidx.compose.ui.graphics.asImageBitmap
|
||||
import androidx.compose.ui.graphics.Brush
|
||||
import androidx.compose.ui.graphics.drawscope.Stroke
|
||||
import androidx.compose.ui.graphics.graphicsLayer
|
||||
import androidx.compose.ui.graphics.vector.ImageVector
|
||||
import androidx.compose.ui.input.pointer.pointerInput
|
||||
import androidx.compose.ui.layout.ContentScale
|
||||
@@ -94,7 +95,7 @@ enum class ActivePanel {
|
||||
LUT_EDIT
|
||||
}
|
||||
|
||||
private const val InitialPreviewTransitionDelayMillis = 0L
|
||||
private const val InitialPreviewTransitionDelayMillis = 150L
|
||||
private const val PreviewTransitionRevealDurationMillis = 800
|
||||
|
||||
@Composable
|
||||
@@ -260,7 +261,7 @@ fun CameraScreen(
|
||||
|
||||
val previewSize = state.currentPreviewSize
|
||||
val previewAspectRatio = state.getPreviewAspectRatio()
|
||||
val previewTransitionCoverFraction by animateFloatAsState(
|
||||
val previewTransitionCoverFractionState = animateFloatAsState(
|
||||
targetValue = when {
|
||||
previewTransitionActive && !previewTransitionRevealing -> 1f
|
||||
previewTransitionActive -> 0f
|
||||
@@ -276,6 +277,7 @@ fun CameraScreen(
|
||||
},
|
||||
label = "previewTransitionCoverFraction"
|
||||
)
|
||||
val previewTransitionCoverFraction = previewTransitionCoverFractionState.value
|
||||
|
||||
fun runPreviewTransition(onSwitch: () -> Unit) {
|
||||
previewTransitionActive = true
|
||||
@@ -766,24 +768,33 @@ fun CameraScreen(
|
||||
modifier = Modifier.fillMaxSize()
|
||||
)
|
||||
|
||||
if (previewTransitionActive || previewTransitionCoverFraction > 0.001f) {
|
||||
val shutterHeightFraction = (previewTransitionCoverFraction / 2f).coerceIn(0f, 0.5f)
|
||||
Box(modifier = Modifier.fillMaxSize()) {
|
||||
Box(
|
||||
modifier = Modifier
|
||||
.fillMaxWidth()
|
||||
.fillMaxHeight(shutterHeightFraction)
|
||||
.align(Alignment.TopCenter)
|
||||
.background(Color.Black)
|
||||
)
|
||||
Box(
|
||||
modifier = Modifier
|
||||
.fillMaxWidth()
|
||||
.fillMaxHeight(shutterHeightFraction)
|
||||
.align(Alignment.BottomCenter)
|
||||
.background(Color.Black)
|
||||
)
|
||||
}
|
||||
Box(
|
||||
modifier = Modifier
|
||||
.fillMaxSize()
|
||||
.graphicsLayer {
|
||||
alpha = if (previewTransitionActive || previewTransitionCoverFractionState.value > 0.001f) 1f else 0f
|
||||
}
|
||||
) {
|
||||
Box(
|
||||
modifier = Modifier
|
||||
.fillMaxWidth()
|
||||
.fillMaxHeight(0.5f)
|
||||
.align(Alignment.TopCenter)
|
||||
.graphicsLayer {
|
||||
translationY = -size.height * (1f - previewTransitionCoverFractionState.value)
|
||||
}
|
||||
.background(Color.Black)
|
||||
)
|
||||
Box(
|
||||
modifier = Modifier
|
||||
.fillMaxWidth()
|
||||
.fillMaxHeight(0.5f)
|
||||
.align(Alignment.BottomCenter)
|
||||
.graphicsLayer {
|
||||
translationY = size.height * (1f - previewTransitionCoverFractionState.value)
|
||||
}
|
||||
.background(Color.Black)
|
||||
)
|
||||
}
|
||||
|
||||
// Live Photo Indicator
|
||||
|
||||
@@ -577,7 +577,7 @@ private fun ZoomableImage(
|
||||
contentAlignment = Alignment.Center
|
||||
) {
|
||||
val metadataHash = remember(photo.metadata) {
|
||||
photo.metadata?.toJson()?.hashCode() ?: 0
|
||||
photo.metadata?.hashCode() ?: 0
|
||||
}
|
||||
|
||||
var bitmap by remember { mutableStateOf<Bitmap?>(null) }
|
||||
|
||||
@@ -1089,8 +1089,8 @@ private class GalleryRecyclerAdapter : RecyclerView.Adapter<RecyclerView.ViewHol
|
||||
|
||||
private fun MediaData.shouldUseFullLineSpan(): Boolean {
|
||||
if (!isImage) return false
|
||||
val width = (metadata?.width ?: width).takeIf { it > 0 } ?: return false
|
||||
val height = (metadata?.height ?: height).takeIf { it > 0 } ?: return false
|
||||
val width = width.takeIf { it > 0 } ?: return false
|
||||
val height = height.takeIf { it > 0 } ?: return false
|
||||
return width.toFloat() / height.toFloat() >= 2.2f
|
||||
}
|
||||
|
||||
@@ -1157,7 +1157,7 @@ private class GalleryPhotoItemView(context: Context) : FrameLayout(context) {
|
||||
burstIcon.visibility = if (photo.isBurstPhoto) VISIBLE else GONE
|
||||
rawBadge.visibility = if (photo.isImage && viewModel.isRawInGallery(photo.id)) VISIBLE else GONE
|
||||
importedBadge.visibility =
|
||||
if (viewModel.selectedTab == GalleryTab.PHOTON && photo.metadata?.isImported == true) VISIBLE else GONE
|
||||
if (viewModel.selectedTab == GalleryTab.PHOTON && photo.sourceUri != null) VISIBLE else GONE
|
||||
importedBadge.text = context.getString(R.string.imported)
|
||||
relatedBadge.visibility =
|
||||
if (viewModel.selectedTab == GalleryTab.SYSTEM && photo.relatedPhoto != null) VISIBLE else GONE
|
||||
@@ -1237,14 +1237,14 @@ private class GalleryPhotoItemView(context: Context) : FrameLayout(context) {
|
||||
|
||||
private fun MediaData.galleryAspectRatio(isLandscape: Boolean): Float {
|
||||
val rawWidth = if (isVideo) {
|
||||
metadata?.videoWidth ?: width
|
||||
width
|
||||
} else {
|
||||
metadata?.width ?: width
|
||||
width
|
||||
}
|
||||
val rawHeight = if (isVideo) {
|
||||
metadata?.videoHeight ?: height
|
||||
height
|
||||
} else {
|
||||
metadata?.height ?: height
|
||||
height
|
||||
}
|
||||
val rotationDegrees = if (isVideo) metadata?.rotationDegrees ?: 0 else 0
|
||||
val shouldSwapDimensions = rotationDegrees == 90 || rotationDegrees == 270
|
||||
|
||||
@@ -667,6 +667,9 @@ class CameraViewModel(application: Application) : AndroidViewModel(application)
|
||||
val defaultLut = availableLutList.firstOrNull { it.isDefault }
|
||||
defaultLut?.let { setLut(it.id) }
|
||||
}
|
||||
|
||||
_isInitialized.value = true
|
||||
StartupTrace.mark("CameraViewModel.isInitialized set to true")
|
||||
}
|
||||
|
||||
// 监听相机状态,用于同步预览渲染参数
|
||||
@@ -708,15 +711,6 @@ class CameraViewModel(application: Application) : AndroidViewModel(application)
|
||||
}
|
||||
}
|
||||
|
||||
// 标记初始化完成
|
||||
viewModelScope.launch {
|
||||
// 等待首选配置加载完成
|
||||
userPreferencesRepository.userPreferences.firstOrNull()
|
||||
// 确保 LUT 列表已加载(虽然 ContentRepository 是同步初始化的,但在 ViewModel 中可能需要一点时间同步)
|
||||
_isInitialized.value = true
|
||||
StartupTrace.mark("CameraViewModel.isInitialized set to true")
|
||||
}
|
||||
|
||||
StartupTrace.mark("CameraViewModel.init end")
|
||||
}
|
||||
|
||||
|
||||
@@ -601,6 +601,11 @@ class GalleryViewModel(application: Application) : AndroidViewModel(application)
|
||||
checkGalleryPermission()
|
||||
}
|
||||
|
||||
refreshLatestPhoto()
|
||||
viewModelScope.launch {
|
||||
loadPhotos()
|
||||
}
|
||||
|
||||
viewModelScope.launch {
|
||||
GalleryManager.detailHdrReadyEvents.collect { photoId ->
|
||||
invalidatePreviewCache(photoId)
|
||||
@@ -653,15 +658,6 @@ class GalleryViewModel(application: Application) : AndroidViewModel(application)
|
||||
}
|
||||
}
|
||||
|
||||
viewModelScope.launch {
|
||||
// 等待初始照片加载完成
|
||||
StartupTrace.measure("GalleryViewModel.loadPhotos") {
|
||||
loadPhotos()
|
||||
}
|
||||
_isInitialized.value = true
|
||||
StartupTrace.mark("GalleryViewModel.isInitialized set to true")
|
||||
}
|
||||
|
||||
StartupTrace.mark("GalleryViewModel.init end")
|
||||
}
|
||||
|
||||
@@ -755,7 +751,7 @@ class GalleryViewModel(application: Application) : AndroidViewModel(application)
|
||||
val newList = repository.getPhotosSync()
|
||||
val currentMap = _photos.value.associateBy { it.id }
|
||||
|
||||
// 保留运行时状态,但使用最新加载到的 metadata/sourceUri 等持久化信息
|
||||
// 保留运行时状态和已加载的复杂 metadata,同时刷新列表基础信息。
|
||||
val mergedList = newList.map { fresh ->
|
||||
currentMap[fresh.id]?.let { existing ->
|
||||
existing.copy(
|
||||
@@ -772,7 +768,7 @@ class GalleryViewModel(application: Application) : AndroidViewModel(application)
|
||||
sourceUri = fresh.sourceUri,
|
||||
isMotionPhoto = fresh.isMotionPhoto,
|
||||
isBurstPhoto = fresh.isBurstPhoto,
|
||||
metadata = fresh.metadata,
|
||||
metadata = existing.metadata ?: fresh.metadata,
|
||||
relatedPhoto = fresh.relatedPhoto
|
||||
)
|
||||
} ?: fresh
|
||||
@@ -852,51 +848,15 @@ class GalleryViewModel(application: Application) : AndroidViewModel(application)
|
||||
viewModelScope.launch {
|
||||
val photo = repository.getLatestPhoto()
|
||||
photo?.let {
|
||||
if (it.isVideo) {
|
||||
_latestPhoto.value = it
|
||||
if (_photos.value.none { existing -> existing.id == it.id }) {
|
||||
_photos.value = listOf(it) + _photos.value
|
||||
}
|
||||
return@let
|
||||
}
|
||||
val context = getApplication<Application>()
|
||||
val metadata = GalleryManager.loadMetadata(context, it.id)
|
||||
var updatedPhoto = if (metadata != null) {
|
||||
it.copy(
|
||||
metadata = metadata,
|
||||
width = if (metadata.width > 0) metadata.width else it.width,
|
||||
height = if (metadata.height > 0) metadata.height else it.height
|
||||
)
|
||||
} else {
|
||||
it
|
||||
}
|
||||
|
||||
// If dimensions are missing, load from file (same as loadPhotos)
|
||||
if (updatedPhoto.width == 0 || updatedPhoto.height == 0) {
|
||||
try {
|
||||
val photoFile = GalleryManager.getPhotoFile(context, it.id)
|
||||
val options = BitmapFactory.Options().apply { inJustDecodeBounds = true }
|
||||
BitmapFactory.decodeFile(photoFile.absolutePath, options)
|
||||
updatedPhoto =
|
||||
updatedPhoto.copy(width = options.outWidth, height = options.outHeight)
|
||||
|
||||
metadata?.let { m ->
|
||||
val newMetadata =
|
||||
m.copy(width = options.outWidth, height = options.outHeight)
|
||||
GalleryManager.saveMetadata(context, it.id, newMetadata)
|
||||
}
|
||||
} catch (e: Exception) {
|
||||
PLog.e(TAG, "Failed to load dimensions for latest photo", e)
|
||||
}
|
||||
}
|
||||
_latestPhoto.value = updatedPhoto
|
||||
|
||||
// Also update the photos list if it's not already in it
|
||||
val currentPhotos = _photos.value
|
||||
if (currentPhotos.none { it.id == updatedPhoto.id }) {
|
||||
_photos.value = listOf(updatedPhoto) + currentPhotos
|
||||
_latestPhoto.value = it
|
||||
if (_photos.value.none { existing -> existing.id == it.id }) {
|
||||
_photos.value = listOf(it) + _photos.value
|
||||
}
|
||||
}
|
||||
if (!_isInitialized.value) {
|
||||
_isInitialized.value = true
|
||||
StartupTrace.mark("GalleryViewModel.isInitialized set to true")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -935,40 +895,28 @@ class GalleryViewModel(application: Application) : AndroidViewModel(application)
|
||||
}
|
||||
}
|
||||
|
||||
fun registerRecordedVideo(uri: Uri, onComplete: (String?) -> Unit = {}) {
|
||||
viewModelScope.launch {
|
||||
val context = getApplication<Application>()
|
||||
val mediaId = GalleryManager.recordVideoCapture(context, uri)
|
||||
if (mediaId != null) {
|
||||
loadPhotos()
|
||||
refreshLatestPhoto()
|
||||
}
|
||||
onComplete(mediaId)
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 加载当前照片的元数据
|
||||
*/
|
||||
fun loadCurrentPhotoMetadata() {
|
||||
val photo = getCurrentPhoto() ?: return
|
||||
|
||||
// 如果已经加载了该照片的元数据,且不是正在编辑模式(编辑模式下可能需要刷新),则跳过
|
||||
if (!isEditing && currentPhotoMetadataId == photo.id) {
|
||||
// Photon 列表只携带轻量 metadata;只有 currentMediaMetadata 才代表详情所需完整 metadata 已加载。
|
||||
if (!isEditing && currentPhotoMetadataId == photo.id && currentMediaMetadata != null) {
|
||||
return
|
||||
}
|
||||
|
||||
// 优先使用 PhotoData 中已有的元数据(由 loadPhotos 预加载)
|
||||
photo.metadata?.let { m ->
|
||||
currentPhotoMetadataId = photo.id
|
||||
applyMetadataToEditState(m)
|
||||
return
|
||||
}
|
||||
|
||||
photo.relatedPhoto?.metadata?.let { m ->
|
||||
currentPhotoMetadataId = photo.id
|
||||
applyMetadataToEditState(m)
|
||||
return
|
||||
if (selectedTab == GalleryTab.SYSTEM) {
|
||||
photo.metadata?.let { m ->
|
||||
currentPhotoMetadataId = photo.id
|
||||
applyMetadataToEditState(m)
|
||||
return
|
||||
}
|
||||
photo.relatedPhoto?.metadata?.let { m ->
|
||||
currentPhotoMetadataId = photo.id
|
||||
applyMetadataToEditState(m)
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
viewModelScope.launch {
|
||||
@@ -1008,8 +956,8 @@ class GalleryViewModel(application: Application) : AndroidViewModel(application)
|
||||
return
|
||||
}
|
||||
|
||||
val cw = metadata.width.takeIf { it > 0 } ?: photo?.metadata?.width ?: photo?.width ?: 0
|
||||
val ch = metadata.height.takeIf { it > 0 } ?: photo?.metadata?.height ?: photo?.height ?: 0
|
||||
val cw = metadata.width.takeIf { it > 0 } ?: photo?.width ?: 0
|
||||
val ch = metadata.height.takeIf { it > 0 } ?: photo?.height ?: 0
|
||||
if (metadata.postCropRegion != null && cw > 0 && ch > 0) {
|
||||
val cropRect = RectF(
|
||||
metadata.postCropRegion.left.toFloat() / cw,
|
||||
@@ -1579,9 +1527,17 @@ class GalleryViewModel(application: Application) : AndroidViewModel(application)
|
||||
|
||||
if (currentMediaMetadata == null || currentPhotoMetadataId != targetPhoto.id) {
|
||||
val context = getApplication<Application>()
|
||||
val metadata = targetPhoto.metadata ?: runBlocking {
|
||||
withContext(Dispatchers.IO) {
|
||||
GalleryManager.loadMetadata(context, targetPhoto.id)
|
||||
val metadata = if (selectedTab == GalleryTab.PHOTON) {
|
||||
runBlocking {
|
||||
withContext(Dispatchers.IO) {
|
||||
GalleryManager.loadMetadata(context, targetPhoto.id)
|
||||
}
|
||||
}
|
||||
} else {
|
||||
targetPhoto.metadata ?: runBlocking {
|
||||
withContext(Dispatchers.IO) {
|
||||
GalleryManager.loadMetadata(context, targetPhoto.id)
|
||||
}
|
||||
}
|
||||
}
|
||||
applyMetadataToEditState(metadata)
|
||||
@@ -1968,7 +1924,7 @@ class GalleryViewModel(application: Application) : AndroidViewModel(application)
|
||||
*/
|
||||
private fun previewCacheKey(mediaData: MediaData, metadata: MediaMetadata, showOrigin: Boolean, maxEdge: Int = 4096): String {
|
||||
val photoId = mediaData.id
|
||||
val metadataHash = metadata.toJson().hashCode()
|
||||
val metadataHash = metadata.hashCode()
|
||||
val refreshKey = photoRefreshKeys[photoId] ?: 0L
|
||||
return if (showOrigin) {
|
||||
"${photoId}_${refreshKey}"
|
||||
|
||||
Reference in new issue
Block a user