feat: video recording and gallery playback support

This commit is contained in:
zhoubinjia committed 2026-04-08 17:42:54 +08:00
1 parent 96b6d9d09d
commit 37773f6074
24 files changed
+1039 -502

No files matched your search

+1 -1
View File
@@ -1,6 +1,6 @@
# Camera App
这是一个 Android 相机 App,专注于静态摄影,模拟现代数码无反相机的操作手感
这是一个 Android 相机 App,模拟现代数码无反相机的操作手感
## 技术框架
+1
View File
@@ -13,6 +13,7 @@
android:name="android.permission.READ_EXTERNAL_STORAGE"
android:maxSdkVersion="32" />
<uses-permission android:name="android.permission.READ_MEDIA_IMAGES" />
<uses-permission android:name="android.permission.READ_MEDIA_VIDEO" />
<uses-feature
android:name="android.hardware.camera"
@@ -58,7 +58,7 @@ import com.hinnka.mycamera.ui.settings.PhantomPipCropScreen
import com.hinnka.mycamera.ui.camera.CameraScreen
import com.hinnka.mycamera.ui.gallery.BurstDetailScreen
import com.hinnka.mycamera.ui.gallery.GalleryScreen
import com.hinnka.mycamera.ui.gallery.PhotoDetailScreen
import com.hinnka.mycamera.ui.gallery.MediaDetailScreen
import com.hinnka.mycamera.ui.gallery.PhotoEditScreen
import com.hinnka.mycamera.ui.settings.FilterManagementScreen
import com.hinnka.mycamera.ui.settings.FrameManagementScreen
@@ -72,7 +72,7 @@ import com.hinnka.mycamera.viewmodel.GalleryViewModel
import com.hinnka.mycamera.lut.creator.LutCreatorScreen
import com.hinnka.mycamera.lut.creator.LutCreatorViewModel
import com.hinnka.mycamera.utils.DeviceUtil
import com.hinnka.mycamera.gallery.PhotoManager
import com.hinnka.mycamera.gallery.MediaManager
import com.hinnka.mycamera.utils.PLog
/**
@@ -138,9 +138,9 @@ class MainActivity : ComponentActivity() {
OrientationObserver.observe(this)
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.UPSIDE_DOWN_CAKE) {
PhotoManager.hdrSdrRatio = display?.hdrSdrRatio ?: 0f
MediaManager.hdrSdrRatio = display?.hdrSdrRatio ?: 0f
}
PLog.d("MainActivity", "hdrSdrRatio=${PhotoManager.hdrSdrRatio}")
PLog.d("MainActivity", "hdrSdrRatio=${MediaManager.hdrSdrRatio}")
// 检查权限
hasPermissions = permissions.all {
@@ -316,7 +316,7 @@ fun NavigationHost(
},
modifier = Modifier.weight(1f)
)
PhotoDetailScreen(
MediaDetailScreen(
viewModel = galleryViewModel,
isExpanded = true,
onEdit = {
@@ -381,7 +381,7 @@ fun NavigationHost(
val tab = backStackEntry.arguments?.getString("tab") ?: GalleryTab.PHOTON.name
val photoId = backStackEntry.arguments?.getString("photoId")
galleryViewModel.selectTab(GalleryTab.valueOf(tab))
PhotoDetailScreen(
MediaDetailScreen(
viewModel = galleryViewModel,
initialIndex = index,
photoId = photoId,
@@ -19,6 +19,7 @@ import android.os.HandlerThread
import android.os.SystemClock
import android.util.Size
import android.view.Surface
import android.net.Uri
import androidx.exifinterface.media.ExifInterface
import com.hinnka.mycamera.utils.PLog
import kotlinx.coroutines.flow.MutableStateFlow
@@ -135,6 +136,7 @@ class Camera2Controller(private val context: Context) {
// Live Photo 录制器
val livePhotoRecorder = LivePhotoRecorder(context)
val videoRecorder = VideoRecorder(context)
var onVideoSaved: ((Uri?) -> Unit)? = null
private var videoRecordingStartElapsedMs: Long = 0L
private val videoRecordingTicker = object : Runnable {
@@ -2243,6 +2245,7 @@ class Camera2Controller(private val context: Context) {
) { uri ->
PLog.i(TAG, "Video saved: $uri")
_state.value = _state.value.copy(videoRecordingState = VideoRecordingState())
onVideoSaved?.invoke(uri)
}
if (!started) {
return
@@ -5,7 +5,7 @@ import android.graphics.*
import android.util.TypedValue
import androidx.core.graphics.drawable.toBitmap
import com.hinnka.mycamera.R
import com.hinnka.mycamera.gallery.PhotoMetadata
import com.hinnka.mycamera.gallery.MediaMetadata
import java.text.SimpleDateFormat
import java.util.*
import androidx.core.graphics.createBitmap
@@ -42,7 +42,7 @@ class FrameRenderer(private val context: Context) {
fun render(
originalBitmap: Bitmap,
template: FrameTemplate,
metadata: PhotoMetadata,
metadata: MediaMetadata,
): Bitmap {
PLog.d(TAG, "render: $metadata")
@@ -228,7 +228,7 @@ class FrameRenderer(private val context: Context) {
private fun drawFrameContent(
canvas: Canvas,
elements: List<FrameElement>,
metadata: PhotoMetadata,
metadata: MediaMetadata,
left: Float,
top: Float,
right: Float,
@@ -378,7 +378,7 @@ class FrameRenderer(private val context: Context) {
private fun measureElementsWidth(
elements: List<FrameElement>,
metadata: PhotoMetadata,
metadata: MediaMetadata,
showAppBranding: Boolean,
scale: Float = 1f
): Float {
@@ -401,7 +401,7 @@ class FrameRenderer(private val context: Context) {
return xPerLine.values.maxOrNull() ?: 0f
}
private fun isElementVisible(element: FrameElement, metadata: PhotoMetadata): Boolean {
private fun isElementVisible(element: FrameElement, metadata: MediaMetadata): Boolean {
return when (element) {
is FrameElement.Text -> getTextContent(element, metadata) != null
is FrameElement.Logo -> {
@@ -416,7 +416,7 @@ class FrameRenderer(private val context: Context) {
private fun filterVisibleGroup(
elements: List<FrameElement>,
metadata: PhotoMetadata,
metadata: MediaMetadata,
): List<FrameElement> {
val initiallyVisible = elements.filter { isElementVisible(it, metadata) }
val result = mutableListOf<FrameElement>()
@@ -447,7 +447,7 @@ class FrameRenderer(private val context: Context) {
*/
private fun measureElementWidth(
element: FrameElement,
metadata: PhotoMetadata,
metadata: MediaMetadata,
scale: Float = 1f
): Float {
return when (element) {
@@ -487,7 +487,7 @@ class FrameRenderer(private val context: Context) {
private fun drawElement(
canvas: Canvas,
element: FrameElement,
metadata: PhotoMetadata,
metadata: MediaMetadata,
x: Float,
centerY: Float,
leftToRight: Boolean,
@@ -525,7 +525,7 @@ class FrameRenderer(private val context: Context) {
private fun drawTextElement(
canvas: Canvas,
element: FrameElement.Text,
metadata: PhotoMetadata,
metadata: MediaMetadata,
x: Float,
centerY: Float,
leftToRight: Boolean,
@@ -553,7 +553,7 @@ class FrameRenderer(private val context: Context) {
*/
private fun getTextContent(
element: FrameElement.Text,
metadata: PhotoMetadata,
metadata: MediaMetadata,
): String? {
val content = when (element.textType) {
TextType.DEVICE_MODEL -> metadata.deviceModel
@@ -591,7 +591,7 @@ class FrameRenderer(private val context: Context) {
private fun measureLogoSize(
element: FrameElement.Logo,
metadata: PhotoMetadata?,
metadata: MediaMetadata?,
scale: Float = 1f
): Pair<Int, Int> {
val size = (dpToPx(element.sizeDp) * scale).toInt()
@@ -647,7 +647,7 @@ class FrameRenderer(private val context: Context) {
x: Float,
centerY: Float,
leftToRight: Boolean,
metadata: PhotoMetadata? = null,
metadata: MediaMetadata? = null,
scale: Float = 1f
): Float {
// 如果是 App Logo 且不显示品牌,则跳过
@@ -968,7 +968,7 @@ class FrameRenderer(private val context: Context) {
val scaledBitmap = Bitmap.createScaledBitmap(originalBitmap, scaledWidth, scaledHeight, true)
// 渲染边框
val metadata = PhotoMetadata.createDefault(scaledWidth, scaledHeight)
val metadata = MediaMetadata.createDefault(scaledWidth, scaledHeight)
return render(scaledBitmap, template, metadata)
}
@@ -1025,7 +1025,7 @@ class FrameRenderer(private val context: Context) {
}
}
private fun getTextTypeface(element: FrameElement.Text, metadata: PhotoMetadata): Typeface {
private fun getTextTypeface(element: FrameElement.Text, metadata: MediaMetadata): Typeface {
if (element.textType == TextType.DEVICE_MODEL) {
val customFont = metadata.customProperties["DEVICE_MODEL_FONT"]
if (customFont == "Default") {
@@ -1,14 +1,14 @@
package com.hinnka.mycamera.gallery
import android.content.Context
import android.net.Uri
import android.content.ContentUris
import android.media.MediaMetadataRetriever
import android.provider.MediaStore
import android.util.Log
import com.hinnka.mycamera.utils.PLog
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.flow
import kotlinx.coroutines.flow.flowOn
import kotlinx.coroutines.runBlocking
import kotlinx.coroutines.withContext
/**
@@ -24,35 +24,35 @@ class GalleryRepository(private val context: Context) {
/**
* 获取所有照片(按时间倒序)
*/
fun getPhotos(): Flow<List<PhotoData>> = flow {
fun getPhotos(): Flow<List<MediaData>> = flow {
emit(queryPhotos())
}.flowOn(Dispatchers.IO)
/**
* 同步获取所有照片
*/
suspend fun getPhotosSync(): List<PhotoData> = withContext(Dispatchers.IO) {
suspend fun getPhotosSync(): List<MediaData> = withContext(Dispatchers.IO) {
queryPhotos()
}
/**
* 获取最新的一张照片
*/
suspend fun getLatestPhoto(): PhotoData? = withContext(Dispatchers.IO) {
suspend fun getLatestPhoto(): MediaData? = withContext(Dispatchers.IO) {
queryPhotos(limit = 1).firstOrNull()
}
/**
* 删除单张照片
*/
suspend fun deletePhoto(photo: PhotoData): Boolean = withContext(Dispatchers.IO) {
PhotoManager.deletePhoto(context, photo.id)
suspend fun deletePhoto(photo: MediaData): Boolean = withContext(Dispatchers.IO) {
MediaManager.deletePhoto(context, photo.id)
}
/**
* 批量删除照片
*/
suspend fun deletePhotos(photos: List<PhotoData>): Int = withContext(Dispatchers.IO) {
suspend fun deletePhotos(photos: List<MediaData>): Int = withContext(Dispatchers.IO) {
var deletedCount = 0
photos.forEach { photo ->
if (deletePhoto(photo)) {
@@ -65,92 +65,162 @@ class GalleryRepository(private val context: Context) {
/**
* 查询系统相册照片
*/
suspend fun getSystemPhotos(offset: Int, limit: Int): List<PhotoData> = withContext(Dispatchers.IO) {
val photos = mutableListOf<PhotoData>()
suspend fun getSystemPhotos(offset: Int, limit: Int): List<MediaData> = withContext(Dispatchers.IO) {
val imageItems = querySystemImages(offset = 0, limit = offset + limit)
val videoItems = querySystemVideos(offset = 0, limit = offset + limit)
(imageItems + videoItems)
.sortedByDescending { it.dateAdded }
.drop(offset)
.take(limit)
}
/**
* 查询私有存储中的照片
*/
private fun queryPhotos(limit: Int = Int.MAX_VALUE): List<MediaData> {
return MediaManager.getPhotoIds(context)
.mapNotNull { id -> runBlocking { MediaManager.buildPhotoData(context, id) } }
.take(limit)
}
private fun querySystemImages(offset: Int, limit: Int): List<MediaData> {
val items = mutableListOf<MediaData>()
val projection = arrayOf(
MediaStore.Images.Media._ID,
MediaStore.Images.Media.DISPLAY_NAME,
MediaStore.Images.Media.DATE_ADDED,
MediaStore.Images.Media.SIZE,
MediaStore.Images.Media.WIDTH,
MediaStore.Images.Media.HEIGHT
MediaStore.Images.Media.HEIGHT,
MediaStore.Images.Media.MIME_TYPE
)
val sortOrder = "${MediaStore.Images.Media.DATE_ADDED} DESC"
val queryArgs = android.os.Bundle().apply {
putInt(android.content.ContentResolver.QUERY_ARG_OFFSET, offset)
putInt(android.content.ContentResolver.QUERY_ARG_LIMIT, limit)
putString(android.content.ContentResolver.QUERY_ARG_SQL_SORT_ORDER, sortOrder)
}
val cursor = context.contentResolver.query(
MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
projection,
queryArgs,
null
putInt(android.content.ContentResolver.QUERY_ARG_OFFSET, offset)
putInt(android.content.ContentResolver.QUERY_ARG_LIMIT, limit)
putString(
android.content.ContentResolver.QUERY_ARG_SQL_SORT_ORDER,
"${MediaStore.Images.Media.DATE_ADDED} DESC"
)
cursor?.use {
val idColumn = it.getColumnIndexOrThrow(MediaStore.Images.Media._ID)
val nameColumn = it.getColumnIndexOrThrow(MediaStore.Images.Media.DISPLAY_NAME)
val dateColumn = it.getColumnIndexOrThrow(MediaStore.Images.Media.DATE_ADDED)
val sizeColumn = it.getColumnIndexOrThrow(MediaStore.Images.Media.SIZE)
val widthColumn = it.getColumnIndexOrThrow(MediaStore.Images.Media.WIDTH)
val heightColumn = it.getColumnIndexOrThrow(MediaStore.Images.Media.HEIGHT)
while (it.moveToNext()) {
val id = it.getLong(idColumn)
val contentUri = android.content.ContentUris.withAppendedId(
MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
id
)
photos.add(
PhotoData(
id = id.toString(),
uri = contentUri,
thumbnailUri = contentUri, // Coil can load thumbnails from content URIs
displayName = it.getString(nameColumn),
dateAdded = it.getLong(dateColumn) * 1000, // MediaStore is in seconds
size = it.getLong(sizeColumn),
width = it.getInt(widthColumn),
height = it.getInt(heightColumn)
)
)
}
}
photos
context.contentResolver.query(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, projection, queryArgs, null)
?.use { cursor ->
val idColumn = cursor.getColumnIndexOrThrow(MediaStore.Images.Media._ID)
val nameColumn = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DISPLAY_NAME)
val dateColumn = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATE_ADDED)
val sizeColumn = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.SIZE)
val widthColumn = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.WIDTH)
val heightColumn = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.HEIGHT)
val mimeColumn = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.MIME_TYPE)
while (cursor.moveToNext()) {
val id = cursor.getLong(idColumn)
val contentUri = ContentUris.withAppendedId(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, id)
items.add(
MediaData(
id = "image_$id",
uri = contentUri,
thumbnailUri = contentUri,
displayName = cursor.getString(nameColumn),
dateAdded = cursor.getLong(dateColumn) * 1000L,
size = cursor.getLong(sizeColumn),
width = cursor.getInt(widthColumn),
height = cursor.getInt(heightColumn),
mediaType = MediaType.IMAGE,
mimeType = cursor.getString(mimeColumn),
sourceUri = contentUri
)
)
}
}
return items
}
/**
* 查询私有存储中的照片
*/
private fun queryPhotos(limit: Int = Int.MAX_VALUE): List<PhotoData> {
val photos = mutableListOf<PhotoData>()
val photoIds = PhotoManager.getPhotoIds(context)
photoIds.forEach { id ->
val photoFile = PhotoManager.getPhotoFile(context, id)
if (photoFile.exists()) {
val videoFile = PhotoManager.getVideoFile(context, id)
val isBurstPhoto = PhotoManager.hasBurstPhotos(context, id)
photos.add(
PhotoData(
id = id,
uri = Uri.fromFile(photoFile),
thumbnailUri = Uri.fromFile(PhotoManager.getThumbnailFile(context, id)),
displayName = photoFile.name,
dateAdded = photoFile.lastModified(),
size = photoFile.length(),
isMotionPhoto = videoFile.exists(),
isBurstPhoto = isBurstPhoto
)
)
}
private fun querySystemVideos(offset: Int, limit: Int): List<MediaData> {
val items = mutableListOf<MediaData>()
val projection = arrayOf(
MediaStore.Video.Media._ID,
MediaStore.Video.Media.DISPLAY_NAME,
MediaStore.Video.Media.DATE_ADDED,
MediaStore.Video.Media.SIZE,
MediaStore.Video.Media.WIDTH,
MediaStore.Video.Media.HEIGHT,
MediaStore.Video.Media.MIME_TYPE,
MediaStore.Video.Media.DURATION
)
val queryArgs = android.os.Bundle().apply {
putInt(android.content.ContentResolver.QUERY_ARG_OFFSET, offset)
putInt(android.content.ContentResolver.QUERY_ARG_LIMIT, limit)
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)
?.use { cursor ->
val idColumn = cursor.getColumnIndexOrThrow(MediaStore.Video.Media._ID)
val nameColumn = cursor.getColumnIndexOrThrow(MediaStore.Video.Media.DISPLAY_NAME)
val dateColumn = cursor.getColumnIndexOrThrow(MediaStore.Video.Media.DATE_ADDED)
val sizeColumn = cursor.getColumnIndexOrThrow(MediaStore.Video.Media.SIZE)
val widthColumn = cursor.getColumnIndexOrThrow(MediaStore.Video.Media.WIDTH)
val heightColumn = cursor.getColumnIndexOrThrow(MediaStore.Video.Media.HEIGHT)
val mimeColumn = cursor.getColumnIndexOrThrow(MediaStore.Video.Media.MIME_TYPE)
val durationColumn = cursor.getColumnIndexOrThrow(MediaStore.Video.Media.DURATION)
return photos.take(limit)
while (cursor.moveToNext()) {
val id = cursor.getLong(idColumn)
val contentUri = ContentUris.withAppendedId(MediaStore.Video.Media.EXTERNAL_CONTENT_URI, id)
val mimeType = cursor.getString(mimeColumn)
val durationMs = cursor.getLong(durationColumn)
var frameRate: Int? = null
var bitrate: Long? = null
var rotationDegrees: Int? = null
var hasAudio: Boolean? = null
val retriever = MediaMetadataRetriever()
try {
retriever.setDataSource(context, contentUri)
frameRate = retriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_CAPTURE_FRAMERATE)
?.toFloatOrNull()?.toInt()
bitrate = retriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_BITRATE)?.toLongOrNull()
rotationDegrees = retriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_VIDEO_ROTATION)?.toIntOrNull()
hasAudio = retriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_HAS_AUDIO)?.let {
it == "yes" || it == "true" || it == "1"
}
} finally {
retriever.release()
}
items.add(
MediaData(
id = "video_$id",
uri = contentUri,
thumbnailUri = contentUri,
displayName = cursor.getString(nameColumn),
dateAdded = cursor.getLong(dateColumn) * 1000L,
size = cursor.getLong(sizeColumn),
width = cursor.getInt(widthColumn),
height = cursor.getInt(heightColumn),
mediaType = MediaType.VIDEO,
mimeType = mimeType,
durationMs = durationMs,
sourceUri = contentUri,
metadata = MediaMetadata(
mediaType = MediaType.VIDEO,
dateTaken = cursor.getLong(dateColumn) * 1000L,
width = cursor.getInt(widthColumn),
height = cursor.getInt(heightColumn),
sourceUri = contentUri.toString(),
mimeType = mimeType,
durationMs = durationMs,
frameRate = frameRate,
bitrate = bitrate,
rotationDegrees = rotationDegrees,
hasAudio = hasAudio,
videoWidth = cursor.getInt(widthColumn),
videoHeight = cursor.getInt(heightColumn)
)
)
)
}
}
return items
}
}
@@ -2,10 +2,15 @@ package com.hinnka.mycamera.gallery
import android.net.Uri
enum class MediaType {
IMAGE,
VIDEO
}
/**
* 照片数据模型
*/
data class PhotoData(
data class MediaData(
val id: String,
val uri: Uri,
val thumbnailUri: Uri,
@@ -14,11 +19,21 @@ data class PhotoData(
val size: Long,
val width: Int = 0,
val height: Int = 0,
val mediaType: MediaType = MediaType.IMAGE,
val mimeType: String? = null,
val durationMs: Long? = null,
val sourceUri: Uri? = null,
var isMotionPhoto: Boolean = false,
var isBurstPhoto: Boolean = false,
var metadata: PhotoMetadata? = null,
var relatedPhoto: PhotoData? = null
var metadata: MediaMetadata? = null,
var relatedPhoto: MediaData? = null
) {
val isVideo: Boolean
get() = mediaType == MediaType.VIDEO
val isImage: Boolean
get() = mediaType == MediaType.IMAGE
/**
* 格式化的拍摄时间
*/
@@ -43,4 +58,16 @@ data class PhotoData(
* 分辨率字符串
*/
fun getResolution(): String = "${width}x${height}"
fun getFormattedDuration(): String {
val totalSeconds = ((durationMs ?: 0L) / 1000L).coerceAtLeast(0L)
val hours = totalSeconds / 3600L
val minutes = (totalSeconds % 3600L) / 60L
val seconds = totalSeconds % 60L
return if (hours > 0L) {
String.format("%d:%02d:%02d", hours, minutes, seconds)
} else {
String.format("%02d:%02d", minutes, seconds)
}
}
}
@@ -6,6 +6,7 @@ import android.content.Context
import android.graphics.*
import android.hardware.camera2.CameraCharacteristics
import android.hardware.camera2.CaptureResult
import android.media.MediaMetadataRetriever
import android.media.ThumbnailUtils
import android.net.Uri
import android.os.Build
@@ -60,7 +61,7 @@ import kotlin.use
* 统一管理照片文件、元数据、缩略图等
* 存储路径: context.filesDir/photos/<photoId>/
*/
object PhotoManager {
object MediaManager {
private const val TAG = "PhotoManager"
private const val PHOTOS_DIR = "photos"
private const val BURST_DIR = "burst"
@@ -76,6 +77,21 @@ object PhotoManager {
private const val MULTIPLE_EXPOSURE_DIR = "multiple_exposure_sessions"
private const val MULTIPLE_EXPOSURE_PREVIEW_FILE = "preview.jpg"
data class VideoRecordInfo(
val uri: Uri,
val displayName: String,
val dateTaken: Long,
val size: Long,
val width: Int,
val height: Int,
val durationMs: Long,
val mimeType: String?,
val frameRate: Int?,
val bitrate: Long?,
val rotationDegrees: Int?,
val hasAudio: Boolean?
)
val processingScope = CoroutineScope(Dispatchers.Default + SupervisorJob())
private val gainmapProducer = UnifiedGainmapProducer()
@@ -187,6 +203,116 @@ object PhotoManager {
return File(getPhotoDir(context, photoId), VIDEO_FILE)
}
private fun getExistingMediaFile(context: Context, photoId: String): File? {
val photoFile = getPhotoFile(context, photoId)
if (photoFile.exists()) return photoFile
val videoFile = getVideoFile(context, photoId)
if (videoFile.exists()) return videoFile
return null
}
private fun readVideoRecordInfo(context: Context, uri: Uri): VideoRecordInfo? {
return try {
val projection = arrayOf(
MediaStore.Video.Media.DISPLAY_NAME,
MediaStore.Video.Media.DATE_ADDED,
MediaStore.Video.Media.SIZE,
MediaStore.Video.Media.WIDTH,
MediaStore.Video.Media.HEIGHT,
MediaStore.Video.Media.DURATION,
MediaStore.Video.Media.MIME_TYPE
)
context.contentResolver.query(uri, projection, null, null, null)?.use { cursor ->
if (!cursor.moveToFirst()) return@use null
val displayName = cursor.getString(cursor.getColumnIndexOrThrow(MediaStore.Video.Media.DISPLAY_NAME))
val dateTaken = cursor.getLong(cursor.getColumnIndexOrThrow(MediaStore.Video.Media.DATE_ADDED)) * 1000L
val size = cursor.getLong(cursor.getColumnIndexOrThrow(MediaStore.Video.Media.SIZE))
val width = cursor.getInt(cursor.getColumnIndexOrThrow(MediaStore.Video.Media.WIDTH))
val height = cursor.getInt(cursor.getColumnIndexOrThrow(MediaStore.Video.Media.HEIGHT))
val durationMs = cursor.getLong(cursor.getColumnIndexOrThrow(MediaStore.Video.Media.DURATION))
val mimeType = cursor.getString(cursor.getColumnIndexOrThrow(MediaStore.Video.Media.MIME_TYPE))
var frameRate: Int? = null
var bitrate: Long? = null
var rotationDegrees: Int? = null
var hasAudio: Boolean? = null
var resolvedWidth = width
var resolvedHeight = height
var resolvedDurationMs = durationMs
val retriever = MediaMetadataRetriever()
try {
retriever.setDataSource(context, uri)
resolvedWidth = retriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_VIDEO_WIDTH)
?.toIntOrNull()
?.takeIf { it > 0 } ?: resolvedWidth
resolvedHeight = retriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_VIDEO_HEIGHT)
?.toIntOrNull()
?.takeIf { it > 0 } ?: resolvedHeight
resolvedDurationMs = retriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_DURATION)
?.toLongOrNull()
?.takeIf { it > 0L } ?: resolvedDurationMs
frameRate = retriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_CAPTURE_FRAMERATE)
?.toFloatOrNull()?.roundToInt()
if (frameRate == null) {
val frameCount = retriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_VIDEO_FRAME_COUNT)
?.toLongOrNull()
if (frameCount != null && resolvedDurationMs > 0L) {
frameRate = ((frameCount * 1000f) / resolvedDurationMs).roundToInt().takeIf { it > 0 }
}
}
bitrate = retriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_BITRATE)?.toLongOrNull()
rotationDegrees = retriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_VIDEO_ROTATION)?.toIntOrNull()
hasAudio = retriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_HAS_AUDIO)?.let {
it == "yes" || it == "true" || it == "1"
}
} finally {
retriever.release()
}
VideoRecordInfo(
uri = uri,
displayName = displayName,
dateTaken = dateTaken,
size = size,
width = resolvedWidth,
height = resolvedHeight,
durationMs = resolvedDurationMs,
mimeType = mimeType,
frameRate = frameRate,
bitrate = bitrate,
rotationDegrees = rotationDegrees,
hasAudio = hasAudio
)
}
} catch (e: Exception) {
PLog.e(TAG, "Failed to read video record info: $uri", e)
null
}
}
private fun saveVideoThumbnail(context: Context, uri: Uri, outputFile: File): Boolean {
return try {
val retriever = MediaMetadataRetriever()
val bitmap = try {
retriever.setDataSource(context, uri)
retriever.getFrameAtTime(0, MediaMetadataRetriever.OPTION_CLOSEST_SYNC)
} finally {
retriever.release()
} ?: return false
outputFile.parentFile?.mkdirs()
FileOutputStream(outputFile).use { out ->
bitmap.compress(Bitmap.CompressFormat.JPEG, 90, out)
}
bitmap.recycle()
true
} catch (e: Exception) {
PLog.e(TAG, "Failed to save video thumbnail for $uri", e)
false
}
}
private fun hasBitmapGainmap(bitmap: Bitmap?): Boolean {
if (bitmap == null || Build.VERSION.SDK_INT < Build.VERSION_CODES.UPSIDE_DOWN_CAKE) return false
return try {
@@ -197,7 +323,7 @@ object PhotoManager {
}
}
private fun canReuseEmbeddedGainmap(metadata: PhotoMetadata): Boolean {
private fun canReuseEmbeddedGainmap(metadata: MediaMetadata): Boolean {
return metadata.manualHdrEffectEnabled &&
metadata.hasEmbeddedGainmap &&
metadata.lutId == null &&
@@ -238,7 +364,7 @@ object PhotoManager {
suspend fun buildDetailHdrCache(
context: Context,
photoId: String,
metadata: PhotoMetadata? = null,
metadata: MediaMetadata? = null,
sharpening: Float = 0f,
noiseReduction: Float = 0f,
chromaNoiseReduction: Float = 0f,
@@ -309,7 +435,7 @@ object PhotoManager {
fun queueDetailHdrCacheBuild(
context: Context,
photoId: String,
metadata: PhotoMetadata? = null,
metadata: MediaMetadata? = null,
sharpening: Float = 0f,
noiseReduction: Float = 0f,
chromaNoiseReduction: Float = 0f
@@ -340,7 +466,7 @@ object PhotoManager {
id: String,
bitmap: Bitmap? = null,
photoProcessor: PhotoProcessor,
metadata: PhotoMetadata,
metadata: MediaMetadata,
sharpeningValue: Float,
noiseReductionValue: Float,
chromaNoiseReductionValue: Float,
@@ -551,7 +677,7 @@ object PhotoManager {
context: Context,
id: String,
bitmap: Bitmap,
metadata: PhotoMetadata,
metadata: MediaMetadata,
photoQuality: Int,
suffix: String?,
): Boolean {
@@ -599,7 +725,7 @@ object PhotoManager {
}
}
suspend fun exportDng(context: Context, photoId: String, data: ByteArray, metadata: PhotoMetadata) =
suspend fun exportDng(context: Context, photoId: String, data: ByteArray, metadata: MediaMetadata) =
withContext(Dispatchers.IO) {
try {
val timestamp = SimpleDateFormat("yyyyMMdd_HHmmss", Locale.US)
@@ -637,7 +763,7 @@ object PhotoManager {
}
}
suspend fun exportDng(context: Context, photoId: String, sourceFile: File, metadata: PhotoMetadata) =
suspend fun exportDng(context: Context, photoId: String, sourceFile: File, metadata: MediaMetadata) =
withContext(Dispatchers.IO) {
try {
if (!sourceFile.exists() || sourceFile.length() <= 0L) {
@@ -684,7 +810,7 @@ object PhotoManager {
suspend fun preparePhoto(
context: Context,
metadata: PhotoMetadata,
metadata: MediaMetadata,
captureResult: CaptureResult?,
thumbnail: Bitmap?,
useLivePhoto: Boolean,
@@ -781,7 +907,7 @@ object PhotoManager {
}
}
suspend fun generateBokehPhoto(context: Context, photoId: String, metadata: PhotoMetadata, bitmap: Bitmap) {
suspend fun generateBokehPhoto(context: Context, photoId: String, metadata: MediaMetadata, bitmap: Bitmap) {
val aperture = metadata.computationalAperture ?: 0f
val focusPointX = metadata.focusPointX
val focusPointY = metadata.focusPointY
@@ -1578,7 +1704,7 @@ object PhotoManager {
captureResult: CaptureResult,
rotation: Int,
thumbnail: Bitmap?,
metadata: PhotoMetadata,
metadata: MediaMetadata,
shouldAutoSave: Boolean,
): Boolean {
val tempDngFile = File(dngFile.parentFile, "temp_stacked.dng")
@@ -1912,7 +2038,13 @@ object PhotoManager {
val metadata = runBlocking {
loadMetadata(context, photoId)
}
val exportedUris = metadata?.exportedUris ?: emptyList()
val exportedUris = buildList {
addAll(metadata?.exportedUris ?: emptyList())
val sourceUri = metadata?.sourceUri
if (metadata?.mediaType == MediaType.VIDEO && !sourceUri.isNullOrBlank()) {
add(sourceUri)
}
}
if (exportedUris.isEmpty()) {
PLog.d(TAG, "No exported URIs to delete for photo: $photoId")
@@ -1995,12 +2127,12 @@ object PhotoManager {
/**
* 加载元数据
*/
suspend fun loadMetadata(context: Context, photoId: String): PhotoMetadata? {
suspend fun loadMetadata(context: Context, photoId: String): MediaMetadata? {
return withContext(Dispatchers.IO) {
try {
val file = getMetadataFile(context, photoId)
if (file.exists()) {
PhotoMetadata.fromJson(file.readText())
MediaMetadata.fromJson(file.readText())
} else {
null
}
@@ -2014,7 +2146,7 @@ object PhotoManager {
/**
* 更新元数据
*/
suspend fun saveMetadata(context: Context, photoId: String, metadata: PhotoMetadata): Boolean {
suspend fun saveMetadata(context: Context, photoId: String, metadata: MediaMetadata): Boolean {
return withContext(Dispatchers.IO) {
try {
val dir = getPhotoDir(context, photoId, true)
@@ -2028,6 +2160,109 @@ object PhotoManager {
}
}
suspend fun recordVideoCapture(
context: Context,
uri: Uri,
photoId: String = UUID.randomUUID().toString()
): String? = withContext(Dispatchers.IO) {
val info = readVideoRecordInfo(context, uri) ?: return@withContext null
val metadata = MediaMetadata(
mediaType = MediaType.VIDEO,
dateTaken = info.dateTaken,
width = info.width,
height = info.height,
sourceUri = uri.toString(),
mimeType = info.mimeType,
durationMs = info.durationMs,
frameRate = info.frameRate,
bitrate = info.bitrate,
rotationDegrees = info.rotationDegrees,
hasAudio = info.hasAudio,
videoWidth = info.width,
videoHeight = info.height,
captureMode = "video"
)
val dir = getPhotoDir(context, photoId, true)
val thumbnailSaved = saveVideoThumbnail(context, uri, getThumbnailFile(context, photoId))
if (!thumbnailSaved) {
PLog.w(TAG, "Video thumbnail not generated for $uri")
}
val metadataSaved = saveMetadata(context, photoId, metadata)
if (!metadataSaved) {
dir.deleteRecursively()
return@withContext null
}
dir.setLastModified(info.dateTaken)
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 -> Uri.parse(metadata.sourceUri)
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 = info?.width ?: metadata.videoWidth ?: metadata.width
val resolvedHeight = info?.height ?: metadata.videoHeight ?: metadata.height
val resolvedDurationMs = info?.durationMs ?: metadata.durationMs
val resolvedMimeType = info?.mimeType ?: metadata.mimeType
val resolvedMetadata = metadata.copy(
width = resolvedWidth,
height = resolvedHeight,
mimeType = resolvedMimeType,
durationMs = resolvedDurationMs,
frameRate = info?.frameRate ?: metadata.frameRate,
bitrate = info?.bitrate ?: metadata.bitrate,
rotationDegrees = info?.rotationDegrees ?: metadata.rotationDegrees,
hasAudio = info?.hasAudio ?: metadata.hasAudio,
videoWidth = resolvedWidth,
videoHeight = resolvedHeight
)
return@withContext MediaData(
id = id,
uri = sourceUri,
thumbnailUri = thumbnailUri,
displayName = info?.displayName ?: (sourceUri.lastPathSegment ?: "video_$id"),
dateAdded = info?.dateTaken ?: metadata.dateTaken ?: getPhotoDir(context, id).lastModified(),
size = info?.size ?: 0L,
width = resolvedWidth,
height = resolvedHeight,
mediaType = MediaType.VIDEO,
mimeType = resolvedMimeType,
durationMs = resolvedDurationMs,
sourceUri = sourceUri,
metadata = resolvedMetadata
)
}
val photoFile = getPhotoFile(context, photoId)
if (!photoFile.exists()) return@withContext null
val videoFile = getVideoFile(context, photoId)
val isBurstPhoto = hasBurstPhotos(context, photoId)
MediaData(
id = photoId,
uri = Uri.fromFile(photoFile),
thumbnailUri = thumbnailUri,
displayName = photoFile.name,
dateAdded = photoFile.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
)
}
fun loadYuvData(context: Context, photoId: String): ByteBuffer? {
val yuvFile = getYuvFile(context, photoId)
if (!yuvFile.exists()) {
@@ -2062,10 +2297,14 @@ object PhotoManager {
return loadBitmap(context, Uri.fromFile(bokehFile), maxEdge, preserveHdr)
}
val photoFile = getPhotoFile(context, photoId)
if (!photoFile.exists()) {
return null
if (photoFile.exists()) {
return loadBitmap(context, Uri.fromFile(photoFile), maxEdge, preserveHdr)
}
return loadBitmap(context, Uri.fromFile(photoFile), maxEdge, preserveHdr)
val thumbnailFile = getThumbnailFile(context, photoId)
if (thumbnailFile.exists()) {
return loadBitmap(context, Uri.fromFile(thumbnailFile), maxEdge, preserveHdr)
}
return null
}
fun loadOriginalBitmap(
@@ -2198,7 +2437,7 @@ object PhotoManager {
}
// 2. 读取元数据以获取旋转信息
val metadata = PhotoMetadata.fromUri(context, uri).copy(
val metadata = MediaMetadata.fromUri(context, uri).copy(
lutId = lutId,
computationalAperture = computationalAperture,
sourceUri = uri.toString()
@@ -2293,7 +2532,7 @@ object PhotoManager {
val videoFile = File(photoDir, VIDEO_FILE)
if (MotionPhotoWriter.extractVideo(photoFile.absolutePath, videoFile.absolutePath)) {
PLog.d(TAG, "Extracted video from imported Motion Photo: $photoId")
val metadata = loadMetadata(context, photoId) ?: PhotoMetadata()
val metadata = loadMetadata(context, photoId) ?: MediaMetadata()
val timestampUs = MotionPhotoWriter.getPresentationTimestampUs(photoFile.absolutePath)
saveMetadata(context, photoId, metadata.copy(presentationTimestampUs = timestampUs))
}
@@ -2341,9 +2580,9 @@ object PhotoManager {
context,
dngFile.absolutePath, metadata?.ratio, metadata?.cropRegion, 0,
sharpeningValue = 0.4f,
denoiseValue = (updatedMetadata ?: PhotoMetadata()).rawDenoiseValue,
denoiseValue = (updatedMetadata ?: MediaMetadata()).rawDenoiseValue,
onMetadata = { raw ->
updatedMetadata = updatedMetadata?.merge(raw) ?: PhotoMetadata().merge(raw)
updatedMetadata = updatedMetadata?.merge(raw) ?: MediaMetadata().merge(raw)
}
)
@@ -2370,7 +2609,7 @@ object PhotoManager {
private suspend fun tempImportJpeg(
uri: Uri,
context: Context,
metadata: PhotoMetadata,
metadata: MediaMetadata,
photoFile: File,
metadataFile: File,
thumbnailFile: File
@@ -20,8 +20,9 @@ import kotlin.math.log2
*
* 保存 LUT、边框水印、编辑信息和拍摄参数,用于非破坏性编辑和边框水印渲染
*/
data class PhotoMetadata(
val version: Int = 11, // Added multiple exposure metadata
data class MediaMetadata(
val version: Int = 12, // Added video media metadata
val mediaType: MediaType = MediaType.IMAGE,
// 编辑配置
val lutId: String? = null,
// 色彩配方配置
@@ -56,6 +57,14 @@ data class PhotoMetadata(
val exposureBias: Float? = null,
val isImported: Boolean = false,
val sourceUri: String? = null, // 原始系统相册 URI (用于关联)
val mimeType: String? = null,
val durationMs: Long? = null,
val frameRate: Int? = null,
val bitrate: Long? = null,
val rotationDegrees: Int? = null,
val hasAudio: Boolean? = null,
val videoWidth: Int? = null,
val videoHeight: Int? = null,
// 边框水印自定义
val customProperties: Map<String, String> = emptyMap(),
// 导出到系统相册的 URI 列表
@@ -136,6 +145,7 @@ data class PhotoMetadata(
fun toJson(): String {
return JSONObject().apply {
put("version", version)
put("mediaType", mediaType.name.lowercase(Locale.US))
put("lutId", lutId ?: JSONObject.NULL)
// 色彩配方配置
if (colorRecipeParams != null) {
@@ -192,6 +202,14 @@ data class PhotoMetadata(
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) }
@@ -222,7 +240,7 @@ data class PhotoMetadata(
/**
* 从 RawMetadata 补齐信息
*/
fun merge(raw: RawMetadata): PhotoMetadata {
fun merge(raw: RawMetadata): MediaMetadata {
return copy(
iso = raw.iso.takeIf { it > 0 } ?: iso,
shutterSpeed = formatShutterSpeed(raw.shutterSpeed).takeIf { it.isNotEmpty() } ?: shutterSpeed,
@@ -252,7 +270,7 @@ data class PhotoMetadata(
companion object {
private const val TAG = "PhotoMetadata"
fun fromJson(json: String): PhotoMetadata? {
fun fromJson(json: String): MediaMetadata? {
return try {
val obj = JSONObject(json)
@@ -277,8 +295,13 @@ data class PhotoMetadata(
null
}
PhotoMetadata(
MediaMetadata(
version = obj.optInt("version", 1),
mediaType = obj.optString("mediaType", MediaType.IMAGE.name).let {
MediaType.entries.firstOrNull { type ->
type.name.equals(it, ignoreCase = true)
} ?: MediaType.IMAGE
},
lutId = if (obj.isNull("lutId")) null else obj.optString("lutId"),
colorRecipeParams = colorRecipeParams,
sharpening = if (obj.isNull("sharpening")) null else obj.optDouble("sharpening").toFloat(),
@@ -326,6 +349,14 @@ data class PhotoMetadata(
exposureBias = if (obj.isNull("exposureBias")) null else obj.optDouble("exposureBias").toFloat(),
isImported = obj.optBoolean("isImported", false),
sourceUri = if (obj.isNull("sourceUri")) null else obj.optString("sourceUri"),
mimeType = if (obj.isNull("mimeType")) null else obj.optString("mimeType"),
durationMs = if (obj.isNull("durationMs")) null else obj.optLong("durationMs"),
frameRate = if (obj.isNull("frameRate")) null else obj.optInt("frameRate"),
bitrate = if (obj.isNull("bitrate")) null else obj.optLong("bitrate"),
rotationDegrees = if (obj.isNull("rotationDegrees")) null else obj.optInt("rotationDegrees"),
hasAudio = if (obj.isNull("hasAudio")) null else obj.optBoolean("hasAudio"),
videoWidth = if (obj.isNull("videoWidth")) null else obj.optInt("videoWidth"),
videoHeight = if (obj.isNull("videoHeight")) null else obj.optInt("videoHeight"),
customProperties = mutableMapOf<String, String>().apply {
val customPropsObj = obj.optJSONObject("customProperties")
customPropsObj?.keys()?.forEach { key ->
@@ -361,8 +392,8 @@ data class PhotoMetadata(
/**
* 从系统信息创建默认元数据
*/
fun createDefault(width: Int, height: Int): PhotoMetadata {
return PhotoMetadata(
fun createDefault(width: Int, height: Int): MediaMetadata {
return MediaMetadata(
deviceModel = Build.MODEL,
brand = Build.MANUFACTURER.replaceFirstChar { it.uppercase() },
dateTaken = System.currentTimeMillis(),
@@ -374,7 +405,7 @@ data class PhotoMetadata(
/**
* 从指定的 URI 加载 EXIF 元数据
*/
fun fromUri(context: Context, uri: Uri): PhotoMetadata {
fun fromUri(context: Context, uri: Uri): MediaMetadata {
return try {
context.contentResolver.openInputStream(uri)?.use { inputStream ->
val exif = ExifInterface(inputStream)
@@ -430,7 +461,7 @@ data class PhotoMetadata(
val altitude = exif.getAltitude(0.0)
.takeIf { it != 0.0 || exif.getAttribute(ExifInterface.TAG_GPS_ALTITUDE) != null }
PhotoMetadata(
MediaMetadata(
deviceModel = model,
brand = make?.replaceFirstChar { it.uppercase() },
dateTaken = dateTaken,
@@ -42,7 +42,7 @@ class PhotoProcessor(
suspend fun prepareUltraHdrSource(
context: Context,
photoId: String,
metadata: PhotoMetadata,
metadata: MediaMetadata,
sharpening: Float = 0f,
noiseReduction: Float = 0f,
chromaNoiseReduction: Float = 0f
@@ -51,7 +51,7 @@ class PhotoProcessor(
return null
}
val dngFile = PhotoManager.getDngFile(context, photoId)
val dngFile = MediaManager.getDngFile(context, photoId)
if (dngFile.exists()) {
return processDngForUltraHdr(
context = context,
@@ -64,12 +64,12 @@ class PhotoProcessor(
)
}
val yuvFile = PhotoManager.getYuvFile(context, photoId)
val yuvFile = MediaManager.getYuvFile(context, photoId)
if (hlgImageProcessor.isHlgCapture(metadata)) {
val prepareStart = System.currentTimeMillis()
val hdrData = PhotoManager.loadHdrData(context, photoId)
val hdrData = MediaManager.loadHdrData(context, photoId)
if (hdrData != null) {
val photoFile = PhotoManager.getPhotoFile(context, photoId)
val photoFile = MediaManager.getPhotoFile(context, photoId)
val photoBitmap = BitmapFactory.decodeFile(photoFile.absolutePath) ?: return null
val finalSharpening = metadata.sharpening ?: (if (metadata.isImported) 0f else sharpening)
val finalNoiseReduction = metadata.noiseReduction ?: (if (metadata.isImported) 0f else noiseReduction)
@@ -111,7 +111,7 @@ class PhotoProcessor(
if (!yuvFile.exists()) {
return null
}
val data = PhotoManager.loadYuvData(context, photoId) ?: return null
val data = MediaManager.loadYuvData(context, photoId) ?: return null
return try {
val finalSharpening = metadata.sharpening ?: (if (metadata.isImported) 0f else sharpening)
val finalNoiseReduction = metadata.noiseReduction ?: (if (metadata.isImported) 0f else noiseReduction)
@@ -163,7 +163,7 @@ class PhotoProcessor(
}
}
val photoFile = PhotoManager.getPhotoFile(context, photoId)
val photoFile = MediaManager.getPhotoFile(context, photoId)
if (photoFile.exists()) {
val bitmap = BitmapFactory.decodeFile(photoFile.absolutePath) ?: return null
val sdrBitmap = processBitmap(
@@ -188,17 +188,17 @@ class PhotoProcessor(
return null
}
fun hasDeferredHlgSource(metadata: PhotoMetadata): Boolean {
fun hasDeferredHlgSource(metadata: MediaMetadata): Boolean {
return hlgImageProcessor.isHlgCapture(metadata)
}
private fun readDisplayHdrSdrRatio(): Float = PhotoManager.hdrSdrRatio
private fun readDisplayHdrSdrRatio(): Float = MediaManager.hdrSdrRatio
suspend fun prepareUltraHdrSourceFromRawResult(
context: Context,
photoId: String?,
rawResult: RawHdrRenderResult,
metadata: PhotoMetadata,
metadata: MediaMetadata,
sharpening: Float = 0f,
noiseReduction: Float = 0f,
chromaNoiseReduction: Float = 0f,
@@ -241,7 +241,7 @@ class PhotoProcessor(
aperture
)
}
photoId?.let { id -> PhotoManager.saveBokehPhoto(context, id, sdrBitmap) }
photoId?.let { id -> MediaManager.saveBokehPhoto(context, id, sdrBitmap) }
}
sdrBitmap = lutImageProcessor.applyLut(
@@ -272,14 +272,14 @@ class PhotoProcessor(
}
suspend fun process(
context: Context, photoId: String, metadata: PhotoMetadata,
context: Context, photoId: String, metadata: MediaMetadata,
sharpening: Float = 0f,
noiseReduction: Float = 0f,
chromaNoiseReduction: Float = 0f
): Bitmap? {
val dngFile = PhotoManager.getDngFile(context, photoId)
val yuvFile = PhotoManager.getYuvFile(context, photoId)
val photoFile = PhotoManager.getPhotoFile(context, photoId)
val dngFile = MediaManager.getDngFile(context, photoId)
val yuvFile = MediaManager.getYuvFile(context, photoId)
val photoFile = MediaManager.getPhotoFile(context, photoId)
if (dngFile.exists()) {
return processDng(
@@ -292,7 +292,7 @@ class PhotoProcessor(
chromaNoiseReduction
)
} else if (yuvFile.exists()) {
val data = PhotoManager.loadYuvData(context, photoId) ?: return null
val data = MediaManager.loadYuvData(context, photoId) ?: return null
return processYuv(
context,
photoId,
@@ -322,7 +322,7 @@ class PhotoProcessor(
context: Context,
photoId: String?,
dngPath: String,
metadata: PhotoMetadata,
metadata: MediaMetadata,
sharpening: Float = 0f,
noiseReduction: Float = 0f,
chromaNoiseReduction: Float = 0f
@@ -361,7 +361,7 @@ class PhotoProcessor(
context: Context,
photoId: String?,
dngPath: String,
metadata: PhotoMetadata,
metadata: MediaMetadata,
sharpening: Float = 0f,
noiseReduction: Float = 0f,
chromaNoiseReduction: Float = 0f
@@ -399,7 +399,7 @@ class PhotoProcessor(
context, photoId, b,
metadata.focusPointX, metadata.focusPointY, aperture
)
photoId?.let { photoId -> PhotoManager.saveBokehPhoto(context, photoId, b) }
photoId?.let { photoId -> MediaManager.saveBokehPhoto(context, photoId, b) }
}
lutImageProcessor.applyLut(
@@ -432,7 +432,7 @@ class PhotoProcessor(
context: Context,
photoId: String?,
input: ByteBuffer,
metadata: PhotoMetadata,
metadata: MediaMetadata,
sharpening: Float = 0f,
noiseReduction: Float = 0f,
chromaNoiseReduction: Float = 0f
@@ -488,7 +488,7 @@ class PhotoProcessor(
context: Context,
photoId: String?,
input: Bitmap,
metadata: PhotoMetadata,
metadata: MediaMetadata,
sharpening: Float = 0f,
noiseReduction: Float = 0f,
chromaNoiseReduction: Float = 0f,
@@ -506,7 +506,7 @@ class PhotoProcessor(
context, photoId, result,
metadata.focusPointX, metadata.focusPointY, aperture
)
photoId?.let { photoId -> PhotoManager.saveBokehPhoto(context, photoId, result) }
photoId?.let { photoId -> MediaManager.saveBokehPhoto(context, photoId, result) }
}
}
@@ -527,7 +527,7 @@ class PhotoProcessor(
}
private fun applyCrop(input: Bitmap, metadata: PhotoMetadata): Bitmap {
private fun applyCrop(input: Bitmap, metadata: MediaMetadata): Bitmap {
val cropRegion = metadata.postCropRegion ?: return input
if (cropRegion.width() <= 0 || cropRegion.height() <= 0) return input
@@ -555,7 +555,7 @@ class PhotoProcessor(
private suspend fun applyFrame(
input: Bitmap,
metadata: PhotoMetadata,
metadata: MediaMetadata,
): Bitmap {
var result = input
// 2. 应用边框水印
@@ -4,7 +4,7 @@ import android.graphics.Bitmap
import android.graphics.Color
import android.graphics.ColorSpace
import android.util.Half
import com.hinnka.mycamera.gallery.PhotoMetadata
import com.hinnka.mycamera.gallery.MediaMetadata
import com.hinnka.mycamera.utils.PLog
import java.nio.ByteBuffer
import java.nio.ByteOrder
@@ -15,7 +15,7 @@ import kotlin.system.measureTimeMillis
class HlgImageProcessor {
fun isHlgCapture(metadata: PhotoMetadata): Boolean {
fun isHlgCapture(metadata: MediaMetadata): Boolean {
return metadata.dynamicRangeProfile == "HLG10"
}
@@ -4,7 +4,7 @@ import android.graphics.Bitmap
import coil.size.Size
import coil.transform.Transformation
import android.content.Context
import com.hinnka.mycamera.gallery.PhotoMetadata
import com.hinnka.mycamera.gallery.MediaMetadata
import com.hinnka.mycamera.gallery.PhotoProcessor
/**
@@ -17,7 +17,7 @@ import com.hinnka.mycamera.gallery.PhotoProcessor
*/
class PhotoTransformation(
private val context: Context,
private val metadata: PhotoMetadata,
private val metadata: MediaMetadata,
private val photoProcessor: PhotoProcessor,
private val sharpening: Float = 0f,
private val noiseReduction: Float = 0f,
@@ -34,7 +34,6 @@ import androidx.compose.foundation.layout.heightIn
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.layout.widthIn
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.foundation.lazy.rememberLazyListState
@@ -67,7 +66,6 @@ import androidx.compose.ui.input.pointer.pointerInput
import androidx.compose.ui.layout.onSizeChanged
import androidx.compose.ui.platform.AndroidUiDispatcher
import androidx.compose.ui.platform.ComposeView
import androidx.compose.ui.platform.LocalDensity
import androidx.compose.ui.platform.ViewCompositionStrategy
import androidx.compose.ui.platform.compositionContext
import androidx.compose.ui.res.painterResource
@@ -92,16 +90,15 @@ import com.hinnka.mycamera.MyCameraApplication
import com.hinnka.mycamera.R
import com.hinnka.mycamera.Routes
import com.hinnka.mycamera.data.ContentRepository
import com.hinnka.mycamera.model.ColorRecipeParams
import com.hinnka.mycamera.screencapture.PhantomPipPreviewCoordinator
import com.hinnka.mycamera.screencapture.ScreenCaptureForegroundServiceState
import com.hinnka.mycamera.screencapture.ScreenCapturePipState
import com.hinnka.mycamera.screencapture.ScreenCaptureRenderConfigStore
import com.hinnka.mycamera.data.UserPreferencesRepository
import com.hinnka.mycamera.gallery.ExifWriter
import com.hinnka.mycamera.gallery.PhotoManager
import com.hinnka.mycamera.gallery.PhotoManager.loadMetadata
import com.hinnka.mycamera.gallery.PhotoManager.saveMetadata
import com.hinnka.mycamera.gallery.MediaManager
import com.hinnka.mycamera.gallery.MediaManager.loadMetadata
import com.hinnka.mycamera.gallery.MediaManager.saveMetadata
import com.hinnka.mycamera.livephoto.GoogleLivePhotoCreator
import com.hinnka.mycamera.livephoto.MotionPhotoWriter
import com.hinnka.mycamera.livephoto.VivoLivePhotoCreator
@@ -112,17 +109,14 @@ import kotlinx.coroutines.async
import kotlinx.coroutines.delay
import kotlinx.coroutines.flow.combine
import kotlinx.coroutines.flow.distinctUntilChanged
import kotlinx.coroutines.flow.first
import kotlinx.coroutines.flow.firstOrNull
import kotlinx.coroutines.flow.map
import kotlinx.coroutines.isActive
import kotlinx.coroutines.Job
import kotlinx.coroutines.flow.first
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import java.io.File
import java.io.FileOutputStream
import kotlin.math.roundToInt
import kotlin.io.copyTo
import kotlin.io.inputStream
import kotlin.use
@@ -382,10 +376,10 @@ class PhantomService(val context: Context) : LifecycleOwner, SavedStateRegistryO
val computationalAperture = preferences?.defaultVirtualAperture?.let { if (it > 0f) it else null }
val existingPhotoId = if (processingInfo?.uri == uri) processingInfo?.photoId else null
val photoId =
PhotoManager.importPhoto(context, uri, lutId, computationalAperture, existingPhotoId) ?: run {
MediaManager.importPhoto(context, uri, lutId, computationalAperture, existingPhotoId) ?: run {
return@withContext
}
val metadata = PhotoManager.loadMetadata(context, photoId) ?: run {
val metadata = MediaManager.loadMetadata(context, photoId) ?: run {
return@withContext
}
if (!isActive) return@withContext
@@ -410,8 +404,8 @@ class PhantomService(val context: Context) : LifecycleOwner, SavedStateRegistryO
0f, 0f, 0f
) ?: return@withContext
val videoFile = PhotoManager.getVideoFile(context, photoId)
val photoFile = PhotoManager.getPhotoFile(context, photoId)
val videoFile = MediaManager.getVideoFile(context, photoId)
val photoFile = MediaManager.getPhotoFile(context, photoId)
FileOutputStream(tempExportFile).use { outputStream ->
processedBitmap.compress(Bitmap.CompressFormat.JPEG, 97, outputStream)
@@ -15,8 +15,8 @@ import com.hinnka.mycamera.MainActivity
import com.hinnka.mycamera.R
import com.hinnka.mycamera.data.ContentRepository
import com.hinnka.mycamera.screencapture.PhantomPipPreviewCoordinator
import com.hinnka.mycamera.gallery.PhotoData
import com.hinnka.mycamera.gallery.PhotoManager
import com.hinnka.mycamera.gallery.MediaData
import com.hinnka.mycamera.gallery.MediaManager
import com.hinnka.mycamera.utils.DeviceUtil
import com.hinnka.mycamera.utils.PLog
import kotlinx.coroutines.CoroutineScope
@@ -52,7 +52,7 @@ class PhantomWidgetProvider : AppWidgetProvider() {
val widgetTheme = prefs.widgetTheme
val latestPhoto = withContext(Dispatchers.IO) {
galleryRepository.getLatestPhoto()?.apply {
metadata = PhotoManager.loadMetadata(context, id)
metadata = MediaManager.loadMetadata(context, id)
}
}
for (appWidgetId in appWidgetIds) {
@@ -156,7 +156,7 @@ class PhantomWidgetProvider : AppWidgetProvider() {
appWidgetManager: AppWidgetManager,
appWidgetId: Int,
isActive: Boolean,
latestPhoto: PhotoData?,
latestPhoto: MediaData?,
widgetTheme: WidgetTheme
) {
val views = RemoteViews(context.packageName, R.layout.phantom_widget)
@@ -3,10 +3,8 @@ package com.hinnka.mycamera.processor
import android.content.Context
import android.graphics.Bitmap
import android.graphics.BitmapFactory
import android.graphics.PointF
import com.hinnka.mycamera.gallery.PhotoManager
import com.hinnka.mycamera.gallery.MediaManager
import com.hinnka.mycamera.ml.DepthEstimator
import com.hinnka.mycamera.utils.PLog
import kotlinx.coroutines.sync.Mutex
import kotlinx.coroutines.sync.withLock
@@ -44,7 +42,7 @@ class DepthBokehProcessor(context: Context) {
var depthMap: Bitmap? = null
var depthFile: java.io.File? = null
if (photoId != null) {
depthFile = PhotoManager.getDepthFile(context, photoId)
depthFile = MediaManager.getDepthFile(context, photoId)
if (depthFile.exists()) {
depthMap = BitmapFactory.decodeFile(depthFile.absolutePath)
}
@@ -1049,7 +1049,7 @@ fun Controls(
state: CameraState,
viewModel: CameraViewModel,
galleryViewModel: GalleryViewModel,
latestPhoto: com.hinnka.mycamera.gallery.PhotoData?,
latestPhoto: com.hinnka.mycamera.gallery.MediaData?,
useMultipleExposure: Boolean,
multipleExposureState: com.hinnka.mycamera.viewmodel.MultipleExposureSessionState,
onGalleryThumbnailBoundsChanged: (Rect) -> Unit,
@@ -9,6 +9,7 @@ import androidx.compose.foundation.layout.size
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.PhotoLibrary
import androidx.compose.material.icons.filled.PlayArrow
import androidx.compose.material3.Icon
import androidx.compose.runtime.Composable
import androidx.compose.runtime.remember
@@ -21,7 +22,7 @@ import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.unit.dp
import coil.compose.AsyncImage
import coil.request.ImageRequest
import com.hinnka.mycamera.gallery.PhotoData
import com.hinnka.mycamera.gallery.MediaData
import com.hinnka.mycamera.viewmodel.GalleryViewModel
/**
@@ -30,7 +31,7 @@ import com.hinnka.mycamera.viewmodel.GalleryViewModel
*/
@Composable
fun GalleryThumbnail(
latestPhoto: PhotoData?,
latestPhoto: MediaData?,
viewModel: GalleryViewModel,
onClick: () -> Unit,
modifier: Modifier = Modifier
@@ -64,6 +65,14 @@ fun GalleryThumbnail(
contentScale = ContentScale.Crop,
modifier = Modifier.fillMaxSize()
)
if (latestPhoto.isVideo) {
Icon(
imageVector = Icons.Default.PlayArrow,
contentDescription = null,
tint = Color.White,
modifier = Modifier.size(20.dp)
)
}
} else {
// 没有照片时显示图标
Icon(
@@ -1,10 +1,6 @@
package com.hinnka.mycamera.ui.gallery
import android.app.Activity
import android.net.Uri
import android.widget.Toast
import androidx.activity.compose.rememberLauncherForActivityResult
import androidx.activity.result.contract.ActivityResultContracts
import androidx.compose.foundation.background
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.*
@@ -33,7 +29,7 @@ import androidx.compose.ui.draw.clip
import coil.compose.AsyncImage
import coil.request.ImageRequest
import com.hinnka.mycamera.R
import com.hinnka.mycamera.gallery.PhotoManager
import com.hinnka.mycamera.gallery.MediaManager
import com.hinnka.mycamera.ui.theme.AccentOrange
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
@@ -43,7 +39,6 @@ import me.saket.telephoto.zoomable.coil.ZoomableAsyncImage
import me.saket.telephoto.zoomable.rememberZoomableImageState
import me.saket.telephoto.zoomable.rememberZoomableState
import java.io.File
import android.content.Intent
import android.graphics.Bitmap
import android.graphics.BitmapFactory
import androidx.compose.animation.AnimatedVisibility
@@ -52,8 +47,7 @@ import androidx.compose.ui.input.pointer.PointerEventPass
import androidx.compose.ui.input.pointer.PointerEventType
import androidx.compose.ui.input.pointer.pointerInput
import androidx.compose.ui.res.painterResource
import androidx.core.content.FileProvider
import com.hinnka.mycamera.gallery.PhotoData
import com.hinnka.mycamera.gallery.MediaData
import com.hinnka.mycamera.viewmodel.GalleryViewModel
import kotlinx.coroutines.delay
import kotlinx.coroutines.suspendCancellableCoroutine
@@ -81,7 +75,7 @@ fun BurstDetailScreen(
// Load burst files
LaunchedEffect(photoId) {
withContext(Dispatchers.IO) {
burstFiles = PhotoManager.getBurstPhotos(context, photoId)
burstFiles = MediaManager.getBurstPhotos(context, photoId)
}
isLoading = false
}
@@ -106,7 +100,7 @@ fun BurstDetailScreen(
val pagerState = rememberPagerState(pageCount = { burstFiles.size })
val currentFile = burstFiles.getOrNull(pagerState.currentPage)
val mainPhotoFile = remember(photoId) { PhotoManager.getPhotoFile(context, photoId) }
val mainPhotoFile = remember(photoId) { MediaManager.getPhotoFile(context, photoId) }
val refreshKey = viewModel.photoRefreshKeys[photoId] ?: 0L
val isMainPhoto = remember(currentFile, refreshKey) {
currentFile?.exists() == true && mainPhotoFile.exists() && currentFile.length() == mainPhotoFile.length()
@@ -431,7 +425,7 @@ fun BurstDetailScreen(
onClick = {
coroutineScope.launch(Dispatchers.IO) {
currentFile?.delete()
val updatedFiles = PhotoManager.getBurstPhotos(context, photoId)
val updatedFiles = MediaManager.getBurstPhotos(context, photoId)
withContext(Dispatchers.Main) {
burstFiles = updatedFiles
showDeleteDialog = false
@@ -558,7 +552,7 @@ fun BurstDetailScreen(
*/
@Composable
private fun ZoomableImage(
photo: PhotoData,
photo: MediaData,
photoFile: File,
showOrigin: Boolean,
isActive: Boolean,
@@ -1,8 +1,10 @@
package com.hinnka.mycamera.ui.gallery
import android.app.Activity
import android.graphics.Bitmap
import android.widget.Toast
import android.os.Build
import android.util.Size
import androidx.activity.compose.rememberLauncherForActivityResult
import androidx.activity.result.IntentSenderRequest
import androidx.activity.result.contract.ActivityResultContracts
@@ -27,6 +29,7 @@ import androidx.compose.material.icons.filled.AutoFixHigh
import androidx.compose.material.icons.filled.CheckCircle
import androidx.compose.material.icons.filled.Close
import androidx.compose.material.icons.filled.Delete
import androidx.compose.material.icons.filled.PlayArrow
import androidx.compose.material.icons.filled.RadioButtonUnchecked
import androidx.compose.material.icons.filled.SelectAll
import androidx.compose.material.icons.filled.Share
@@ -53,7 +56,7 @@ import androidx.compose.ui.text.font.FontWeight
import coil.compose.AsyncImage
import coil.request.ImageRequest
import com.hinnka.mycamera.R
import com.hinnka.mycamera.gallery.PhotoData
import com.hinnka.mycamera.gallery.MediaData
import com.hinnka.mycamera.ui.camera.autoRotate
import com.hinnka.mycamera.ui.theme.AccentOrange
import com.hinnka.mycamera.utils.OrientationObserver
@@ -89,9 +92,9 @@ fun GalleryScreen(
}
val permissionLauncher = rememberLauncherForActivityResult(
contract = ActivityResultContracts.RequestPermission()
) { granted ->
if (granted) {
contract = ActivityResultContracts.RequestMultiplePermissions()
) { grants ->
if (grants.values.all { it }) {
viewModel.checkGalleryPermission()
}
}
@@ -372,9 +375,12 @@ fun GalleryScreen(
Button(
onClick = {
val permission = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
android.Manifest.permission.READ_MEDIA_IMAGES
arrayOf(
android.Manifest.permission.READ_MEDIA_IMAGES,
android.Manifest.permission.READ_MEDIA_VIDEO
)
} else {
android.Manifest.permission.READ_EXTERNAL_STORAGE
arrayOf(android.Manifest.permission.READ_EXTERNAL_STORAGE)
}
permissionLauncher.launch(permission)
},
@@ -526,7 +532,7 @@ fun GalleryScreen(
@OptIn(ExperimentalFoundationApi::class)
@Composable
private fun PhotoGridItem(
photo: PhotoData,
photo: MediaData,
viewModel: GalleryViewModel,
isSelected: Boolean,
isSelectionMode: Boolean,
@@ -534,10 +540,35 @@ private fun PhotoGridItem(
onLongClick: () -> Unit
) {
val context = LocalContext.current
val videoThumbnail by produceState<Bitmap?>(initialValue = null, key1 = photo.id, key2 = photo.thumbnailUri) {
value = if (photo.isVideo && photo.thumbnailUri.scheme == "content") {
runCatching {
context.contentResolver.loadThumbnail(photo.thumbnailUri, Size(512, 512), null)
}.getOrNull()
} else {
null
}
}
val aspectRatio = remember(photo.width, photo.height, photo.metadata, OrientationObserver.isLandscape) {
val width = photo.metadata?.width ?: photo.width
val height = photo.metadata?.height ?: photo.height
val rawWidth = if (photo.isVideo) {
photo.metadata?.videoWidth ?: photo.width
} else {
photo.metadata?.width ?: photo.width
}
val rawHeight = if (photo.isVideo) {
photo.metadata?.videoHeight ?: photo.height
} else {
photo.metadata?.height ?: photo.height
}
val rotationDegrees = if (photo.isVideo) {
photo.metadata?.rotationDegrees ?: 0
} else {
0
}
val shouldSwapDimensions = rotationDegrees == 90 || rotationDegrees == 270
val width = if (shouldSwapDimensions) rawHeight else rawWidth
val height = if (shouldSwapDimensions) rawWidth else rawHeight
if (width > 0 && height > 0) {
if (OrientationObserver.isLandscape) height.toFloat() / width.toFloat() else width.toFloat() / height.toFloat()
} else {
@@ -574,7 +605,7 @@ private fun PhotoGridItem(
}
AsyncImage(
model = imageRequest,
model = videoThumbnail ?: imageRequest,
contentDescription = photo.displayName,
contentScale = ContentScale.Crop,
modifier = Modifier.fillMaxSize()
@@ -601,8 +632,32 @@ private fun PhotoGridItem(
)
}
// Live Photo 标记
if (photo.isMotionPhoto) {
// 媒体类型标记
if (photo.isVideo) {
Box(
modifier = Modifier
.align(Alignment.TopStart)
.padding(4.dp)
.background(Color.Black.copy(alpha = 0.55f), RoundedCornerShape(999.dp))
.padding(horizontal = 6.dp, vertical = 4.dp)
) {
Row(verticalAlignment = Alignment.CenterVertically) {
Icon(
imageVector = Icons.Default.PlayArrow,
contentDescription = stringResource(R.string.video),
tint = Color.White,
modifier = Modifier.size(14.dp)
)
Spacer(modifier = Modifier.width(2.dp))
Text(
text = photo.getFormattedDuration(),
color = Color.White,
fontSize = 10.sp,
fontWeight = FontWeight.SemiBold
)
}
}
} else if (photo.isMotionPhoto) {
Box(
modifier = Modifier
.align(Alignment.TopStart)
@@ -641,7 +696,7 @@ private fun PhotoGridItem(
.align(Alignment.BottomStart)
) {
// RAW 标记
val isRaw = remember(photo.id) { viewModel.isRaw(photo.id) }
val isRaw = remember(photo.id) { photo.isImage && viewModel.isRaw(photo.id) }
if (isRaw) {
Box(
modifier = Modifier
@@ -39,7 +39,7 @@ import androidx.compose.ui.unit.sp
import androidx.compose.ui.text.font.FontWeight
import com.hinnka.mycamera.R
import androidx.compose.ui.res.painterResource
import com.hinnka.mycamera.gallery.PhotoData
import com.hinnka.mycamera.gallery.MediaData
import com.hinnka.mycamera.ui.theme.AccentOrange
import com.hinnka.mycamera.viewmodel.GalleryViewModel
import kotlinx.coroutines.delay
@@ -64,7 +64,7 @@ import kotlin.math.min
*/
@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun PhotoDetailScreen(
fun MediaDetailScreen(
viewModel: GalleryViewModel,
initialIndex: Int = 0,
photoId: String? = null,
@@ -221,7 +221,7 @@ fun PhotoDetailScreen(
}
}
}
if (currentPhoto != null && viewModel.isRaw(currentPhoto.id)) {
if (currentPhoto != null && currentPhoto.isImage && viewModel.isRaw(currentPhoto.id)) {
val isRefreshing = viewModel.refreshingPhotos.contains(currentPhoto.id)
val infiniteTransition = rememberInfiniteTransition(label = "refresh")
val rotation by infiniteTransition.animateFloat(
@@ -258,7 +258,7 @@ fun PhotoDetailScreen(
)
}
}
if (currentPhoto != null && currentPhoto.isBurstPhoto) {
if (currentPhoto != null && currentPhoto.isImage && currentPhoto.isBurstPhoto) {
IconButton(onClick = { onViewBurst?.invoke(currentPhoto.id) }) {
Icon(
imageVector = Icons.Default.BurstMode,
@@ -267,7 +267,7 @@ fun PhotoDetailScreen(
)
}
}
if (currentPhoto != null && Build.VERSION.SDK_INT >= Build.VERSION_CODES.UPSIDE_DOWN_CAKE && !DeviceUtil.isHarmonyOS) {
if (currentPhoto != null && currentPhoto.isImage && Build.VERSION.SDK_INT >= Build.VERSION_CODES.UPSIDE_DOWN_CAKE && !DeviceUtil.isHarmonyOS) {
val hdrEnabled = viewModel.isManualHdrEnhanceEnabled(currentPhoto)
TextButton(
onClick = {
@@ -288,7 +288,7 @@ fun PhotoDetailScreen(
IconButton(onClick = { showInfoDialog = true }) {
Icon(
imageVector = Icons.Default.Info,
contentDescription = stringResource(R.string.photo_info),
contentDescription = stringResource(if (currentPhoto?.isVideo == true) R.string.video_info else R.string.photo_info),
tint = Color.White
)
}
@@ -333,25 +333,27 @@ fun PhotoDetailScreen(
}
// 编辑
IconButton(
onClick = {
viewModel.setCurrentPhoto(pagerState.currentPage)
viewModel.enterEditMode()
onEdit()
},
modifier = Modifier
.size(56.dp)
.background(Color.White.copy(alpha = 0.1f), CircleShape)
) {
Icon(
imageVector = Icons.Default.Edit,
contentDescription = stringResource(R.string.edit),
tint = Color.White
)
if (currentPhoto?.isImage == true) {
IconButton(
onClick = {
viewModel.setCurrentPhoto(pagerState.currentPage)
viewModel.enterEditMode()
onEdit()
},
modifier = Modifier
.size(56.dp)
.background(Color.White.copy(alpha = 0.1f), CircleShape)
) {
Icon(
imageVector = Icons.Default.Edit,
contentDescription = stringResource(R.string.edit),
tint = Color.White
)
}
}
// 导出
if (viewModel.selectedTab == GalleryTab.PHOTON || currentPhoto?.relatedPhoto != null) {
if (currentPhoto?.isImage == true && (viewModel.selectedTab == GalleryTab.PHOTON || currentPhoto.relatedPhoto != null)) {
IconButton(
onClick = { currentPhoto?.let { showExportDialog = true } },
modifier = Modifier
@@ -421,51 +423,47 @@ fun PhotoDetailScreen(
var showOrigin by remember { mutableStateOf(false) }
var isPlaying by remember { mutableStateOf(false) }
Box(modifier = Modifier.fillMaxSize().pointerInput(Unit) {
awaitPointerEventScope {
while (true) {
// 确认第一个手指按下,且当前只有一个指针
val downEvent = awaitPointerEvent(PointerEventPass.Initial)
if (downEvent.type == PointerEventType.Press && downEvent.changes.size == 1) {
val touchSlop = viewConfiguration.touchSlop
val initialPosition = downEvent.changes[0].position
val longPressTimeout = viewConfiguration.longPressTimeoutMillis
var upEvent: PointerEvent? = null
var isMultiTouch = false
var isMoved = false
Box(
modifier = Modifier.fillMaxSize().pointerInput(photo.id, photo.isImage, photo.isMotionPhoto) {
if (!photo.isImage) return@pointerInput
awaitPointerEventScope {
while (true) {
val downEvent = awaitPointerEvent(PointerEventPass.Initial)
if (downEvent.type == PointerEventType.Press && downEvent.changes.size == 1) {
val touchSlop = viewConfiguration.touchSlop
val initialPosition = downEvent.changes[0].position
val longPressTimeout = viewConfiguration.longPressTimeoutMillis
var upEvent: PointerEvent? = null
var isMultiTouch = false
var isMoved = false
// 期间如果出现第二个手指,立即标志并退出
withTimeoutOrNull(longPressTimeout) {
while (true) {
val event = awaitPointerEvent(PointerEventPass.Initial)
if (event.changes.size > 1) {
isMultiTouch = true
break
}
withTimeoutOrNull(longPressTimeout) {
while (true) {
val event = awaitPointerEvent(PointerEventPass.Initial)
if (event.changes.size > 1) {
isMultiTouch = true
break
}
val currentPosition = event.changes[0].position
if ((currentPosition - initialPosition).getDistance() > touchSlop) {
isMoved = true
break
}
val currentPosition = event.changes[0].position
if ((currentPosition - initialPosition).getDistance() > touchSlop) {
isMoved = true
break
}
if (event.type == PointerEventType.Release) {
upEvent = event
break
if (event.type == PointerEventType.Release) {
upEvent = event
break
}
}
}
}
// 如果不是多指操作,才根据结果执行逻辑
if (!isMultiTouch && !isMoved) {
if (upEvent == null) {
// 确认为长按
if (!isMultiTouch && !isMoved && upEvent == null) {
if (photo.isMotionPhoto) {
isPlaying = true
} else {
showOrigin = true
}
// 继续监控直到手指抬起,或者变成多指(开始缩放)
while (true) {
val event = awaitPointerEvent(PointerEventPass.Initial)
if (event.type == PointerEventType.Release || event.changes.size > 1) {
@@ -479,43 +477,34 @@ fun PhotoDetailScreen(
}
}
}
}) {
ZoomableImage(
photo = photo,
colorSpace = currentColorSpace,
showOrigin = showOrigin,
isActive = page == pagerState.currentPage,
viewModel = viewModel,
onZoomChange = { zoomed ->
if (page == pagerState.currentPage) {
isZoomed = zoomed
}
},
modifier = Modifier.fillMaxSize()
)
MotionPhotoPlayer(
photo = photo,
isPlaying = isPlaying,
viewModel = viewModel,
modifier = Modifier.fillMaxSize()
)
/*val brightness = viewModel.currentBrightness[photo.id]
brightness?.let {
Box(
modifier = Modifier
.padding(16.dp)
.align(Alignment.TopEnd)
.background(Color.Black.copy(alpha = 0.5f), RoundedCornerShape(4.dp))
.padding(horizontal = 8.dp, vertical = 4.dp)
) {
Text(
text = "avg: ${String.format("%.2f", it)}",
color = Color.White,
fontSize = 12.sp,
fontWeight = FontWeight.Bold
)
}
}*/
) {
if (photo.isVideo) {
VideoDetailPlayer(
photo = photo,
isActive = page == pagerState.currentPage,
modifier = Modifier.fillMaxSize()
)
} else {
ZoomableImage(
photo = photo,
colorSpace = currentColorSpace,
showOrigin = showOrigin,
isActive = page == pagerState.currentPage,
viewModel = viewModel,
onZoomChange = { zoomed ->
if (page == pagerState.currentPage) {
isZoomed = zoomed
}
},
modifier = Modifier.fillMaxSize()
)
MotionPhotoPlayer(
photo = photo,
isPlaying = isPlaying,
viewModel = viewModel,
modifier = Modifier.fillMaxSize()
)
}
}
}
}
@@ -624,7 +613,7 @@ fun PhotoDetailScreen(
if (showInfoDialog && currentPhoto != null) {
AlertDialog(
onDismissRequest = { showInfoDialog = false },
title = { Text(stringResource(R.string.photo_info)) },
title = { Text(stringResource(if (currentPhoto.isVideo) R.string.video_info else R.string.photo_info)) },
text = {
Column {
if (viewModel.selectedTab == GalleryTab.SYSTEM) {
@@ -632,15 +621,24 @@ fun PhotoDetailScreen(
}
InfoRow(stringResource(R.string.photo_info_date), currentPhoto.getFormattedDate())
InfoRow(stringResource(R.string.photo_info_resolution), currentPhoto.getResolution())
// InfoRow(stringResource(R.string.photo_info_size), currentPhoto.getFormattedSize())
InfoRow(stringResource(R.string.photo_info_size), currentPhoto.getFormattedSize())
currentPhoto.metadata?.let {
InfoRow(stringResource(R.string.photo_info_focal_length), it.focalLength35mm ?: "N/A")
InfoRow(stringResource(R.string.photo_info_aperture), it.aperture ?: "N/A")
InfoRow(stringResource(R.string.photo_info_iso), it.iso?.toString() ?: "N/A")
InfoRow(stringResource(R.string.photo_info_shutter_speed), it.shutterSpeed ?: "N/A")
if (DeviceUtil.canShowPhantom) {
InfoRow("LV", "%.2f".format(it.lv))
InfoRow("平均亮度", "%.2f".format(viewModel.currentBrightness[currentPhoto.id]))
if (currentPhoto.isVideo) {
InfoRow(stringResource(R.string.video_info_duration), currentPhoto.getFormattedDuration())
InfoRow(stringResource(R.string.video_info_mime), it.mimeType ?: (currentPhoto.mimeType ?: "N/A"))
InfoRow(stringResource(R.string.video_info_frame_rate), it.frameRate?.toString() ?: "N/A")
InfoRow(stringResource(R.string.video_info_bitrate), it.bitrate?.let { bitrate -> "${bitrate / 1000} kbps" } ?: "N/A")
InfoRow(stringResource(R.string.video_info_has_audio), it.hasAudio?.let { hasAudio -> if (hasAudio) stringResource(R.string.yes) else stringResource(R.string.no) } ?: "N/A")
InfoRow(stringResource(R.string.video_info_rotation), it.rotationDegrees?.toString() ?: "N/A")
} else {
InfoRow(stringResource(R.string.photo_info_focal_length), it.focalLength35mm ?: "N/A")
InfoRow(stringResource(R.string.photo_info_aperture), it.aperture ?: "N/A")
InfoRow(stringResource(R.string.photo_info_iso), it.iso?.toString() ?: "N/A")
InfoRow(stringResource(R.string.photo_info_shutter_speed), it.shutterSpeed ?: "N/A")
if (DeviceUtil.canShowPhantom) {
InfoRow("LV", "%.2f".format(it.lv))
InfoRow("平均亮度", "%.2f".format(viewModel.currentBrightness[currentPhoto.id]))
}
}
}
currentColorSpace.value?.let {
@@ -682,13 +680,60 @@ private fun InfoRow(label: String, value: String) {
}
}
@androidx.annotation.OptIn(androidx.media3.common.util.UnstableApi::class)
@Composable
private fun VideoDetailPlayer(
photo: MediaData,
isActive: Boolean,
modifier: Modifier = Modifier
) {
val context = LocalContext.current
val mediaUri = remember(photo.id, photo.uri, photo.sourceUri) {
photo.sourceUri ?: photo.uri
}
val exoPlayer = remember(photo.id, mediaUri) {
ExoPlayer.Builder(context).build().apply {
setMediaItem(MediaItem.fromUri(mediaUri))
repeatMode = Player.REPEAT_MODE_OFF
prepare()
playWhenReady = true
}
}
DisposableEffect(exoPlayer) {
onDispose { exoPlayer.release() }
}
LaunchedEffect(exoPlayer, isActive) {
exoPlayer.playWhenReady = isActive
if (!isActive) {
exoPlayer.pause()
}
}
AndroidView(
factory = {
LayoutInflater.from(context).inflate(R.layout.view_motion_photo_player, null) as PlayerView
},
update = {
it.player = exoPlayer
it.resizeMode = AspectRatioFrameLayout.RESIZE_MODE_FIT
it.useController = true
it.controllerAutoShow = true
it.setShowBuffering(PlayerView.SHOW_BUFFERING_WHEN_PLAYING)
it.isVisible = true
},
modifier = modifier
)
}
/**
* 可缩放的图片组件
* 使用 Telephoto 库支持大尺寸图片查看
*/
@Composable
private fun ZoomableImage(
photo: PhotoData,
photo: MediaData,
colorSpace: MutableState<ColorSpace?>,
showOrigin: Boolean,
isActive: Boolean,
@@ -804,7 +849,7 @@ private fun ZoomableImage(
@androidx.annotation.OptIn(androidx.media3.common.util.UnstableApi::class)
@Composable
fun MotionPhotoPlayer(
photo: PhotoData,
photo: MediaData,
isPlaying: Boolean,
viewModel: GalleryViewModel,
modifier: Modifier = Modifier
@@ -19,8 +19,8 @@ import com.hinnka.mycamera.camera.*
import com.hinnka.mycamera.data.ContentRepository
import com.hinnka.mycamera.data.VolumeKeyAction
import com.hinnka.mycamera.frame.FrameInfo
import com.hinnka.mycamera.gallery.PhotoManager
import com.hinnka.mycamera.gallery.PhotoMetadata
import com.hinnka.mycamera.gallery.MediaManager
import com.hinnka.mycamera.gallery.MediaMetadata
import com.hinnka.mycamera.lut.LutConfig
import com.hinnka.mycamera.lut.LutConverter
import com.hinnka.mycamera.lut.LutInfo
@@ -315,7 +315,7 @@ class CameraViewModel(application: Application) : AndroidViewModel(application)
private var hasAppliedDefaultFocalLength = false
private val stackingImages = mutableListOf<SafeImage>()
private var multipleExposureMetadata: PhotoMetadata? = null
private var multipleExposureMetadata: MediaMetadata? = null
var multipleExposureState by mutableStateOf(MultipleExposureSessionState())
private set
@@ -360,6 +360,16 @@ class CameraViewModel(application: Application) : AndroidViewModel(application)
}
}
}
cameraController.onVideoSaved = { uri ->
if (uri != null) {
viewModelScope.launch {
val mediaId = MediaManager.recordVideoCapture(getApplication(), uri)
if (mediaId != null) {
_imageSavedEvent.emit(Unit)
}
}
}
}
cameraController.onCameraError = { code, message, canRetry ->
// 只记录错误日志,不在这里重试打开相机
@@ -608,7 +618,7 @@ class CameraViewModel(application: Application) : AndroidViewModel(application)
chromaNoiseReductionValue: Float = 0f,
captureMode: String? = null,
multipleExposureFrameCount: Int? = null
): PhotoMetadata {
): MediaMetadata {
val lutIdToSave = currentLutId.value
val aspectRatio = state.value.aspectRatio
val frameIdToSave = currentFrameId
@@ -635,7 +645,7 @@ class CameraViewModel(application: Application) : AndroidViewModel(application)
userPrefs = userPrefs
)
return PhotoMetadata(
return MediaMetadata(
lutId = lutIdToSave,
frameId = frameIdToSave,
colorRecipeParams = currentRecipeParams.value,
@@ -704,7 +714,7 @@ class CameraViewModel(application: Application) : AndroidViewModel(application)
fun cancelMultipleExposureSession() {
multipleExposureState.previewBitmap?.recycle()
multipleExposureState.sessionId?.let { sessionId ->
PhotoManager.clearMultipleExposureSession(getApplication(), sessionId)
MediaManager.clearMultipleExposureSession(getApplication(), sessionId)
}
multipleExposureMetadata = null
multipleExposureState = multipleExposureState.copy(
@@ -718,7 +728,7 @@ class CameraViewModel(application: Application) : AndroidViewModel(application)
fun undoLastMultipleExposureFrame() {
val sessionId = multipleExposureState.sessionId ?: return
if (!PhotoManager.removeLastMultipleExposureFrame(getApplication(), sessionId)) return
if (!MediaManager.removeLastMultipleExposureFrame(getApplication(), sessionId)) return
refreshMultipleExposurePreview(sessionId)
}
@@ -730,7 +740,7 @@ class CameraViewModel(application: Application) : AndroidViewModel(application)
multipleExposureState = multipleExposureState.copy(isProcessing = true)
try {
val context = getApplication<Application>()
val composedBitmap = PhotoManager.composeMultipleExposurePhoto(context, sessionId) ?: run {
val composedBitmap = MediaManager.composeMultipleExposurePhoto(context, sessionId) ?: run {
multipleExposureState = multipleExposureState.copy(isProcessing = false)
return@launch
}
@@ -740,7 +750,7 @@ class CameraViewModel(application: Application) : AndroidViewModel(application)
val noiseReductionValue = noiseReduction.firstOrNull() ?: 0f
val chromaNoiseReductionValue = chromaNoiseReduction.firstOrNull() ?: 0f
val photoId = PhotoManager.preparePhoto(
val photoId = MediaManager.preparePhoto(
context,
baseMetadata.copy(
width = composedBitmap.width,
@@ -758,7 +768,7 @@ class CameraViewModel(application: Application) : AndroidViewModel(application)
return@launch
}
PhotoManager.saveBitmapPhoto(
MediaManager.saveBitmapPhoto(
context,
photoId,
composedBitmap,
@@ -788,9 +798,9 @@ class CameraViewModel(application: Application) : AndroidViewModel(application)
private fun refreshMultipleExposurePreview(sessionId: String) {
viewModelScope.launch(Dispatchers.IO) {
val context = getApplication<Application>()
val frameFiles = PhotoManager.getMultipleExposureFrameFiles(context, sessionId)
val frameFiles = MediaManager.getMultipleExposureFrameFiles(context, sessionId)
val preview = if (frameFiles.isNotEmpty()) {
PhotoManager.composeMultipleExposurePreview(context, sessionId)
MediaManager.composeMultipleExposurePreview(context, sessionId)
} else {
null
}
@@ -833,7 +843,7 @@ class CameraViewModel(application: Application) : AndroidViewModel(application)
multipleExposureFrameCount = multipleExposureState.targetCount
).also { multipleExposureMetadata = it }
val frameFile = PhotoManager.saveMultipleExposureFrame(
val frameFile = MediaManager.saveMultipleExposureFrame(
context,
sessionId,
frameIndex,
@@ -2109,7 +2119,7 @@ class CameraViewModel(application: Application) : AndroidViewModel(application)
)
// 创建统一的 PhotoMetadata,包含编辑配置和拍摄信息
val metadata = PhotoMetadata(
val metadata = MediaMetadata(
lutId = lutIdToSave,
frameId = frameIdToSave,
colorRecipeParams = currentRecipeParams.value,
@@ -2152,7 +2162,7 @@ class CameraViewModel(application: Application) : AndroidViewModel(application)
characteristics ?: return
val photoId =
PhotoManager.preparePhoto(
MediaManager.preparePhoto(
context,
metadata,
captureResult,
@@ -2166,9 +2176,9 @@ class CameraViewModel(application: Application) : AndroidViewModel(application)
return
}
viewModelScope.launch(Dispatchers.IO) {
PhotoManager.saveVideo(context, photoId, livePhotoVideoDeferred)
MediaManager.saveVideo(context, photoId, livePhotoVideoDeferred)
PhotoManager.savePhoto(
MediaManager.savePhoto(
context,
photoId,
image,
@@ -2253,7 +2263,7 @@ class CameraViewModel(application: Application) : AndroidViewModel(application)
)
// 创建统一的 PhotoMetadata,包含编辑配置和拍摄信息
val metadata = PhotoMetadata(
val metadata = MediaMetadata(
lutId = lutIdToSave,
frameId = frameIdToSave,
colorRecipeParams = currentRecipeParams.value,
@@ -2297,7 +2307,7 @@ class CameraViewModel(application: Application) : AndroidViewModel(application)
} else null
characteristics ?: return
val photoId = PhotoManager.preparePhoto(
val photoId = MediaManager.preparePhoto(
context,
metadata,
captureResult,
@@ -2314,9 +2324,9 @@ class CameraViewModel(application: Application) : AndroidViewModel(application)
}
viewModelScope.launch(Dispatchers.IO) {
PhotoManager.saveVideo(context, photoId, livePhotoVideoDeferred)
MediaManager.saveVideo(context, photoId, livePhotoVideoDeferred)
PhotoManager.saveStackedPhoto(
MediaManager.saveStackedPhoto(
context,
photoId,
images,
@@ -2383,7 +2393,7 @@ class CameraViewModel(application: Application) : AndroidViewModel(application)
)
// 创建统一的 PhotoMetadata,包含编辑配置和拍摄信息
val metadata = PhotoMetadata(
val metadata = MediaMetadata(
lutId = lutIdToSave,
frameId = frameIdToSave,
colorRecipeParams = currentRecipeParams.value,
@@ -2414,7 +2424,7 @@ class CameraViewModel(application: Application) : AndroidViewModel(application)
manualHdrEffectEnabled = defaultHdrEffectEnabled
)
PhotoManager.preparePhoto(
MediaManager.preparePhoto(
context,
metadata,
null,
@@ -2448,13 +2458,13 @@ class CameraViewModel(application: Application) : AndroidViewModel(application)
}
burstImageCount++
try {
val metadata = PhotoManager.loadMetadata(context, photoId)
val metadata = MediaManager.loadMetadata(context, photoId)
if (metadata == null) {
prepareBurst(context, photoId, image, captureInfo)
}
val shouldAutoSave = autoSaveAfterCapture.firstOrNull() ?: false
val photoQualityValue = photoQuality.firstOrNull() ?: 95
PhotoManager.saveBurstPhoto(
MediaManager.saveBurstPhoto(
context,
photoId,
image,
@@ -2553,7 +2563,7 @@ class CameraViewModel(application: Application) : AndroidViewModel(application)
burstImages.clear()
burstImageCount = 0
multipleExposureState.previewBitmap?.recycle()
multipleExposureState.sessionId?.let { PhotoManager.clearMultipleExposureSession(getApplication(), it) }
multipleExposureState.sessionId?.let { MediaManager.clearMultipleExposureSession(getApplication(), it) }
}
/**
@@ -19,9 +19,9 @@ import androidx.lifecycle.AndroidViewModel
import androidx.lifecycle.viewModelScope
import com.hinnka.mycamera.data.ContentRepository
import com.hinnka.mycamera.frame.FrameInfo
import com.hinnka.mycamera.gallery.PhotoData
import com.hinnka.mycamera.gallery.PhotoManager
import com.hinnka.mycamera.gallery.PhotoMetadata
import com.hinnka.mycamera.gallery.MediaData
import com.hinnka.mycamera.gallery.MediaManager
import com.hinnka.mycamera.gallery.MediaMetadata
import com.hinnka.mycamera.hdr.UnifiedGainmapProducer
import com.hinnka.mycamera.lut.LutConfig
import com.hinnka.mycamera.lut.LutInfo
@@ -107,17 +107,18 @@ class GalleryViewModel(application: Application) : AndroidViewModel(application)
private set
// 照片列表
private val _photos = MutableStateFlow<List<PhotoData>>(emptyList())
private val _photos = MutableStateFlow<List<MediaData>>(emptyList())
val photos = _photos.asStateFlow()
private val _systemPhotos = MutableStateFlow<List<PhotoData>>(emptyList())
private val _systemPhotos = MutableStateFlow<List<MediaData>>(emptyList())
val systemPhotos = _systemPhotos.asStateFlow()
val currentPhotos = combine(photos, systemPhotos, snapshotFlow { selectedTab }) { p, s, tab ->
if (tab == GalleryTab.PHOTON) {
p
} else {
// Optimize lookup by creating a map of sourceUri to PhotoData
val photonMap = mutableMapOf<String, PhotoData>()
val photonMap = mutableMapOf<String, MediaData>()
p.forEach { photo ->
photo.sourceUri?.toString()?.let { photonMap[it] = photo }
photo.metadata?.sourceUri?.let { photonMap[it] = photo }
}
@@ -161,7 +162,7 @@ class GalleryViewModel(application: Application) : AndroidViewModel(application)
private set
// 选中的照片
val selectedPhotos = mutableStateListOf<PhotoData>()
val selectedPhotos = mutableStateListOf<MediaData>()
// 当前查看的照片索引
var currentPhotoIndex by mutableStateOf(0)
@@ -198,10 +199,10 @@ class GalleryViewModel(application: Application) : AndroidViewModel(application)
// 系统相册删除
var systemDeletePendingIntent by mutableStateOf<android.app.PendingIntent?>(null)
private set
private var pendingDeleteSystemPhoto: PhotoData? = null
private var pendingDeleteSystemPhoto: MediaData? = null
// 当前照片的元数据
var currentPhotoMetadata: PhotoMetadata? by mutableStateOf(null)
var currentMediaMetadata: MediaMetadata? by mutableStateOf(null)
private set
private var currentPhotoMetadataId: String? = null
@@ -290,8 +291,8 @@ class GalleryViewModel(application: Application) : AndroidViewModel(application)
val focusPointX = editFocusPointX.value
val focusPointY = editFocusPointY.value
val photoData = getCurrentPhoto() ?: return@launch
val bitmap = PhotoManager.loadOriginalBitmap(context, photoData.id)
?: PhotoManager.loadBitmap(context, photoData.uri) ?: return@launch
val bitmap = MediaManager.loadOriginalBitmap(context, photoData.id)
?: MediaManager.loadBitmap(context, photoData.uri) ?: return@launch
if (!isActive) return@launch
val bokeh = aperture?.let {
contentRepository.depthBokehProcessor.applyHighQualityBokeh(
@@ -304,24 +305,24 @@ class GalleryViewModel(application: Application) : AndroidViewModel(application)
)
} ?: bitmap
if (!isActive) return@launch
PhotoManager.saveBokehPhoto(context, photoData.id, bokeh)
MediaManager.saveBokehPhoto(context, photoData.id, bokeh)
photoRefreshKeys[photoData.id] = System.currentTimeMillis()
}
}
fun hasDepthInfo(photo: PhotoData?): Boolean {
fun hasDepthInfo(photo: MediaData?): Boolean {
if (photo == null) return false
if (selectedTab == GalleryTab.SYSTEM) return false
val context = getApplication<Application>()
return PhotoManager.getDepthFile(context, photo.id).exists()
return MediaManager.getDepthFile(context, photo.id).exists()
}
// 最新照片(用于相机界面显示入口)
private val _latestPhoto = MutableStateFlow<PhotoData?>(null)
val latestPhoto: StateFlow<PhotoData?> = _latestPhoto.asStateFlow()
private val _latestPhoto = MutableStateFlow<MediaData?>(null)
val latestPhoto: StateFlow<MediaData?> = _latestPhoto.asStateFlow()
// 待删除的照片(用于 Activity Result 回调)
var pendingDeletePhoto: PhotoData? by mutableStateOf(null)
var pendingDeletePhoto: MediaData? by mutableStateOf(null)
private set
// 删除请求的 PendingIntent(用于启动系统删除对话框)
@@ -329,7 +330,7 @@ class GalleryViewModel(application: Application) : AndroidViewModel(application)
private set
// 批量删除相关状态
private var pendingDeletePhotos: List<PhotoData> = emptyList()
private var pendingDeletePhotos: List<MediaData> = emptyList()
var batchDeletePendingIntent: android.app.PendingIntent? by mutableStateOf(null)
private set
@@ -340,7 +341,7 @@ class GalleryViewModel(application: Application) : AndroidViewModel(application)
checkGalleryPermission()
viewModelScope.launch {
PhotoManager.detailHdrReadyEvents.collect { photoId ->
MediaManager.detailHdrReadyEvents.collect { photoId ->
invalidatePreviewCache(photoId)
photoRefreshKeys[photoId] = System.currentTimeMillis()
PLog.d(TAG, "detail HDR ready, refreshed photo: $photoId")
@@ -405,7 +406,8 @@ class GalleryViewModel(application: Application) : AndroidViewModel(application)
fun checkGalleryPermission() {
val context = getApplication<Application>()
hasGalleryPermission = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
context.checkSelfPermission(android.Manifest.permission.READ_MEDIA_IMAGES) == android.content.pm.PackageManager.PERMISSION_GRANTED
context.checkSelfPermission(android.Manifest.permission.READ_MEDIA_IMAGES) == android.content.pm.PackageManager.PERMISSION_GRANTED &&
context.checkSelfPermission(android.Manifest.permission.READ_MEDIA_VIDEO) == android.content.pm.PackageManager.PERMISSION_GRANTED
} else {
context.checkSelfPermission(android.Manifest.permission.READ_EXTERNAL_STORAGE) == android.content.pm.PackageManager.PERMISSION_GRANTED
}
@@ -473,7 +475,7 @@ class GalleryViewModel(application: Application) : AndroidViewModel(application)
_isLoading.value = false
// 2. 辅助函数:分批异步加载元数据
suspend fun updateMetadata(items: List<PhotoData>) {
suspend fun updateMetadata(items: List<MediaData>) {
if (items.isEmpty()) return
val updatedItems = withContext(Dispatchers.IO) {
items.map { async { loadSpecificPhotoMetadata(context, it) } }.awaitAll()
@@ -495,9 +497,12 @@ class GalleryViewModel(application: Application) : AndroidViewModel(application)
}
}
private suspend fun loadSpecificPhotoMetadata(context: Context, photo: PhotoData): PhotoData =
private suspend fun loadSpecificPhotoMetadata(context: Context, photo: MediaData): MediaData =
withContext(Dispatchers.IO) {
val metadata = PhotoManager.loadMetadata(context, photo.id)
if (photo.isVideo) {
return@withContext MediaManager.buildPhotoData(context, photo.id) ?: photo
}
val metadata = MediaManager.loadMetadata(context, photo.id)
var updatedPhoto = if (metadata != null) {
photo.copy(
metadata = metadata,
@@ -510,7 +515,7 @@ class GalleryViewModel(application: Application) : AndroidViewModel(application)
// If dimensions are missing, load from file header
if (updatedPhoto.width == 0 || updatedPhoto.height == 0) {
try {
val photoFile = PhotoManager.getPhotoFile(context, photo.id)
val photoFile = MediaManager.getPhotoFile(context, photo.id)
if (photoFile.exists()) {
val options = BitmapFactory.Options().apply { inJustDecodeBounds = true }
BitmapFactory.decodeFile(photoFile.absolutePath, options)
@@ -518,10 +523,10 @@ class GalleryViewModel(application: Application) : AndroidViewModel(application)
updatedPhoto.copy(width = options.outWidth, height = options.outHeight)
// Cache dimensions back to metadata
val currentMeta = metadata ?: PhotoMetadata()
val currentMeta = metadata ?: MediaMetadata()
val newMetadata =
currentMeta.copy(width = options.outWidth, height = options.outHeight)
PhotoManager.saveMetadata(context, photo.id, newMetadata)
MediaManager.saveMetadata(context, photo.id, newMetadata)
updatedPhoto = updatedPhoto.copy(metadata = newMetadata)
}
} catch (e: Exception) {
@@ -544,8 +549,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 = PhotoManager.loadMetadata(context, it.id)
val metadata = MediaManager.loadMetadata(context, it.id)
var updatedPhoto = if (metadata != null) {
it.copy(
metadata = metadata,
@@ -559,7 +571,7 @@ class GalleryViewModel(application: Application) : AndroidViewModel(application)
// If dimensions are missing, load from file (same as loadPhotos)
if (updatedPhoto.width == 0 || updatedPhoto.height == 0) {
try {
val photoFile = PhotoManager.getPhotoFile(context, it.id)
val photoFile = MediaManager.getPhotoFile(context, it.id)
val options = BitmapFactory.Options().apply { inJustDecodeBounds = true }
BitmapFactory.decodeFile(photoFile.absolutePath, options)
updatedPhoto =
@@ -568,7 +580,7 @@ class GalleryViewModel(application: Application) : AndroidViewModel(application)
metadata?.let { m ->
val newMetadata =
m.copy(width = options.outWidth, height = options.outHeight)
PhotoManager.saveMetadata(context, it.id, newMetadata)
MediaManager.saveMetadata(context, it.id, newMetadata)
}
} catch (e: Exception) {
PLog.e(TAG, "Failed to load dimensions for latest photo", e)
@@ -592,22 +604,7 @@ class GalleryViewModel(application: Application) : AndroidViewModel(application)
viewModelScope.launch {
val context = getApplication<Application>()
val photo = withContext(Dispatchers.IO) {
val photoFile = PhotoManager.getPhotoFile(context, photoId)
if (!photoFile.exists()) return@withContext null
val videoFile = PhotoManager.getVideoFile(context, photoId)
val isBurstPhoto = PhotoManager.hasBurstPhotos(context, photoId)
val data = PhotoData(
id = photoId,
uri = Uri.fromFile(photoFile),
thumbnailUri = Uri.fromFile(PhotoManager.getThumbnailFile(context, photoId)),
displayName = photoFile.name,
dateAdded = photoFile.lastModified(),
size = photoFile.length(),
isMotionPhoto = videoFile.exists(),
isBurstPhoto = isBurstPhoto
)
loadSpecificPhotoMetadata(context, data)
MediaManager.buildPhotoData(context, photoId)
} ?: return@launch
val currentList = _photos.value.toMutableList()
@@ -628,7 +625,7 @@ class GalleryViewModel(application: Application) : AndroidViewModel(application)
fun importSharedImage(uri: android.net.Uri, onSuccess: (String) -> Unit = {}) {
viewModelScope.launch {
val context = getApplication<Application>()
val photoId = PhotoManager.importPhoto(context, uri, null)
val photoId = MediaManager.importPhoto(context, uri, null)
if (photoId != null) {
loadPhotos()
selectedTab = GalleryTab.PHOTON
@@ -648,7 +645,7 @@ class GalleryViewModel(application: Application) : AndroidViewModel(application)
val context = getApplication<Application>()
var lastPhotoId: String? = null
uris.forEach { uri ->
val id = PhotoManager.importPhoto(context, uri, null)
val id = MediaManager.importPhoto(context, uri, null)
if (id != null) lastPhotoId = id
}
if (lastPhotoId != null) {
@@ -661,6 +658,18 @@ class GalleryViewModel(application: Application) : AndroidViewModel(application)
}
}
fun registerRecordedVideo(uri: Uri, onComplete: (String?) -> Unit = {}) {
viewModelScope.launch {
val context = getApplication<Application>()
val mediaId = MediaManager.recordVideoCapture(context, uri)
if (mediaId != null) {
loadPhotos()
refreshLatestPhoto()
}
onComplete(mediaId)
}
}
/**
* 加载当前照片的元数据
*/
@@ -691,9 +700,9 @@ class GalleryViewModel(application: Application) : AndroidViewModel(application)
// 在 IO 线程加载元数据
val metadata = withContext(Dispatchers.IO) {
if (selectedTab == GalleryTab.SYSTEM) {
PhotoMetadata.fromUri(context, photo.uri)
MediaMetadata.fromUri(context, photo.uri)
} else {
PhotoManager.loadMetadata(context, photo.id)
MediaManager.loadMetadata(context, photo.id)
}
}
@@ -715,7 +724,7 @@ class GalleryViewModel(application: Application) : AndroidViewModel(application)
}
}
private fun restoreCropEditState(photo: PhotoData?, metadata: PhotoMetadata?) {
private fun restoreCropEditState(photo: MediaData?, metadata: MediaMetadata?) {
if (metadata == null) {
editCropRect.value = null
editCropAspectOption.value = CropAspectOption.Free
@@ -743,10 +752,10 @@ class GalleryViewModel(application: Application) : AndroidViewModel(application)
}
}
private fun applyMetadataToEditState(metadata: PhotoMetadata?) {
private fun applyMetadataToEditState(metadata: MediaMetadata?) {
val photo = getCurrentPhoto()
currentPhotoMetadataId = photo?.id
currentPhotoMetadata = metadata
currentMediaMetadata = metadata
metadata?.let { m ->
editLutId.value = m.lutId
editFrameId.value = m.frameId
@@ -767,7 +776,7 @@ class GalleryViewModel(application: Application) : AndroidViewModel(application)
} ?: restoreCropEditState(photo, null)
}
fun loadThumbnail(photo: PhotoData): Bitmap? {
fun loadThumbnail(photo: MediaData): Bitmap? {
val context = getApplication<Application>()
return try {
if (photo.thumbnailUri.scheme == "content") {
@@ -816,7 +825,7 @@ class GalleryViewModel(application: Application) : AndroidViewModel(application)
/**
* 切换照片选中状态
*/
fun togglePhotoSelection(photo: PhotoData) {
fun togglePhotoSelection(photo: MediaData) {
if (selectedPhotos.contains(photo)) {
selectedPhotos.remove(photo)
} else {
@@ -862,7 +871,7 @@ class GalleryViewModel(application: Application) : AndroidViewModel(application)
/**
* 获取当前照片
*/
fun getCurrentPhoto(): PhotoData? {
fun getCurrentPhoto(): MediaData? {
return currentPhotos.value.getOrNull(currentPhotoIndex)
}
@@ -871,9 +880,9 @@ class GalleryViewModel(application: Application) : AndroidViewModel(application)
*
* @return PendingIntent 如果有导出的照片需要删除,返回 PendingIntent;否则返回 null
*/
private fun getDeleteRequest(photo: PhotoData): android.app.PendingIntent? {
private fun getDeleteRequest(photo: MediaData): android.app.PendingIntent? {
val context = getApplication<Application>()
return PhotoManager.createDeleteRequest(context, photo.id)
return MediaManager.createDeleteRequest(context, photo.id)
}
/**
@@ -885,10 +894,10 @@ class GalleryViewModel(application: Application) : AndroidViewModel(application)
* 3. 如果有导出的照片,设置 deletePendingIntent 和 pendingDeletePhoto,UI 层需要监听这些状态并启动删除确认对话框
* 4. 如果没有导出的照片,或者在 Android 10 及以下,直接删除照片
*/
fun requestDeletePhoto(photo: PhotoData, deleteExported: Boolean = true) {
fun requestDeletePhoto(photo: MediaData, deleteExported: Boolean = true) {
if (selectedTab == GalleryTab.SYSTEM) {
// 系统相册删除
val pendingIntent = PhotoManager.createSystemDeleteRequest(getApplication(), photo.uri)
val pendingIntent = MediaManager.createSystemDeleteRequest(getApplication(), photo.uri)
if (pendingIntent != null) {
pendingDeleteSystemPhoto = photo
systemDeletePendingIntent = pendingIntent
@@ -920,10 +929,10 @@ class GalleryViewModel(application: Application) : AndroidViewModel(application)
/**
* 仅删除应用内部照片(不删除系统相册)
*/
private fun deletePhotoOnlyInternal(photo: PhotoData) {
private fun deletePhotoOnlyInternal(photo: MediaData) {
viewModelScope.launch {
val context = getApplication<Application>()
val success = PhotoManager.deletePhotoOnly(context, photo.id)
val success = MediaManager.deletePhotoOnly(context, photo.id)
if (success) {
loadPhotos()
// 如果删除的是当前照片,调整索引
@@ -962,7 +971,7 @@ class GalleryViewModel(application: Application) : AndroidViewModel(application)
val photo = pendingDeletePhoto ?: return
viewModelScope.launch {
val context = getApplication<Application>()
val success = PhotoManager.deletePhotoOnly(context, photo.id)
val success = MediaManager.deletePhotoOnly(context, photo.id)
if (success) {
loadPhotos()
@@ -983,6 +992,10 @@ class GalleryViewModel(application: Application) : AndroidViewModel(application)
*/
fun deleteSystemPhotoAfterConfirmation(onComplete: (Boolean) -> Unit = {}) {
viewModelScope.launch {
pendingDeleteSystemPhoto?.relatedPhoto?.takeIf { it.isVideo }?.let { relatedVideo ->
MediaManager.deletePhotoOnly(getApplication(), relatedVideo.id)
loadPhotos()
}
// 系统照片已经被 MediaStore 删除,我们只需要刷新列表
loadSystemPhotos(reset = true)
@@ -999,10 +1012,10 @@ class GalleryViewModel(application: Application) : AndroidViewModel(application)
/**
* 设为连拍主图
*/
fun setMainBurstPhoto(photo: PhotoData, burstFile: File, onComplete: (Boolean) -> Unit) {
fun setMainBurstPhoto(photo: MediaData, burstFile: File, onComplete: (Boolean) -> Unit) {
viewModelScope.launch {
val context = getApplication<Application>()
val success = PhotoManager.setMainBurstPhoto(context, photo.id, burstFile)
val success = MediaManager.setMainBurstPhoto(context, photo.id, burstFile)
if (success) {
photoRefreshKeys[photo.id] = System.currentTimeMillis()
loadPhotos()
@@ -1072,7 +1085,7 @@ class GalleryViewModel(application: Application) : AndroidViewModel(application)
withContext(Dispatchers.IO) {
toDelete.forEach { photo ->
val metadata = PhotoManager.loadMetadata(context, photo.id)
val metadata = MediaManager.loadMetadata(context, photo.id)
metadata?.exportedUris?.forEach { uriString ->
try {
allExportedUris.add(uriString.toUri())
@@ -1110,14 +1123,14 @@ class GalleryViewModel(application: Application) : AndroidViewModel(application)
/**
* 仅删除应用内部照片(批量,不删除系统相册)
*/
private fun deleteBatchPhotosOnlyInternal(photos: List<PhotoData>) {
private fun deleteBatchPhotosOnlyInternal(photos: List<MediaData>) {
viewModelScope.launch {
val context = getApplication<Application>()
var deletedCount = 0
withContext(Dispatchers.IO) {
photos.forEach { photo ->
val success = PhotoManager.deletePhotoOnly(context, photo.id)
val success = MediaManager.deletePhotoOnly(context, photo.id)
if (success) {
deletedCount++
}
@@ -1139,6 +1152,14 @@ class GalleryViewModel(application: Application) : AndroidViewModel(application)
viewModelScope.launch {
if (selectedTab == GalleryTab.SYSTEM) {
val relatedPhotonVideos = photos.mapNotNull { it.relatedPhoto }.filter { it.isVideo }
if (relatedPhotonVideos.isNotEmpty()) {
val context = getApplication<Application>()
withContext(Dispatchers.IO) {
relatedPhotonVideos.forEach { MediaManager.deletePhotoOnly(context, it.id) }
}
loadPhotos()
}
// 系统相册刷新
loadSystemPhotos(reset = true)
} else {
@@ -1148,7 +1169,7 @@ class GalleryViewModel(application: Application) : AndroidViewModel(application)
withContext(Dispatchers.IO) {
photos.forEach { photo ->
val success = PhotoManager.deletePhotoOnly(context, photo.id)
val success = MediaManager.deletePhotoOnly(context, photo.id)
if (success) {
deletedCount++
}
@@ -1167,37 +1188,32 @@ class GalleryViewModel(application: Application) : AndroidViewModel(application)
/**
* 获取 Motion Photo 视频文件
*/
fun getMotionPhotoVideo(photo: PhotoData): File? {
fun getMotionPhotoVideo(photo: MediaData): File? {
val context = getApplication<Application>()
val videoFile = PhotoManager.getVideoFile(context, photo.id)
val videoFile = MediaManager.getVideoFile(context, photo.id)
return if (videoFile.exists()) videoFile else null
}
/**
* 分享照片
*/
fun sharePhoto(photo: PhotoData) {
fun sharePhoto(photo: MediaData) {
viewModelScope.launch {
_isSharing.value = true
try {
val context = getApplication<Application>()
val sharedFile = prepareSharedPhoto(photo)
if (sharedFile != null) {
val shareUri = FileProvider.getUriForFile(
context,
"${context.packageName}.fileprovider",
sharedFile
)
val shareRequest = prepareShareRequest(photo)
if (shareRequest != null) {
val shareIntent = Intent(Intent.ACTION_SEND).apply {
type = "image/jpeg"
putExtra(Intent.EXTRA_STREAM, shareUri)
type = shareRequest.mimeType
putExtra(Intent.EXTRA_STREAM, shareRequest.uri)
addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION)
}
val chooser = Intent.createChooser(shareIntent, null).apply {
addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
}
context.startActivity(chooser)
context.startActivity(
Intent.createChooser(shareIntent, null).apply {
addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
}
)
}
} finally {
_isSharing.value = false
@@ -1215,18 +1231,17 @@ class GalleryViewModel(application: Application) : AndroidViewModel(application)
_isSharing.value = true
try {
val context = getApplication<Application>()
val files = selectedPhotos.mapNotNull { prepareSharedPhoto(it) }
if (files.isNotEmpty()) {
val uris = ArrayList(files.map { file ->
FileProvider.getUriForFile(
context,
"${context.packageName}.fileprovider",
file
)
})
val requests = selectedPhotos.mapNotNull { prepareShareRequest(it) }
if (requests.isNotEmpty()) {
val uris = ArrayList(requests.map { it.uri })
val mimeType = if (requests.any { it.mimeType.startsWith("video/") }) {
"*/*"
} else {
"image/jpeg"
}
val shareIntent = Intent(Intent.ACTION_SEND_MULTIPLE).apply {
type = "image/jpeg"
type = mimeType
putParcelableArrayListExtra(Intent.EXTRA_STREAM, uris)
addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION)
}
@@ -1246,12 +1261,13 @@ class GalleryViewModel(application: Application) : AndroidViewModel(application)
*/
fun enterEditMode() {
val targetPhoto = getCurrentPhoto() ?: return
if (targetPhoto.isVideo) return
if (currentPhotoMetadata == null || currentPhotoMetadataId != targetPhoto.id) {
if (currentMediaMetadata == null || currentPhotoMetadataId != targetPhoto.id) {
val context = getApplication<Application>()
val metadata = targetPhoto.metadata ?: runBlocking {
withContext(Dispatchers.IO) {
PhotoManager.loadMetadata(context, targetPhoto.id)
MediaManager.loadMetadata(context, targetPhoto.id)
}
}
applyMetadataToEditState(metadata)
@@ -1259,7 +1275,7 @@ class GalleryViewModel(application: Application) : AndroidViewModel(application)
isEditing = true
// 从当前元数据恢复编辑状态
currentPhotoMetadata?.let { metadata ->
currentMediaMetadata?.let { metadata ->
editLutId.value = metadata.lutId
editFrameId.value = metadata.frameId
editPhotoRecipeParams.value = metadata.colorRecipeParams
@@ -1371,7 +1387,7 @@ class GalleryViewModel(application: Application) : AndroidViewModel(application)
* 保存当前边框的自定义属性到持久化存储
*/
fun saveEditCustomProperties(properties: Map<String, String>) {
currentPhotoMetadata = currentPhotoMetadata?.copy(
currentMediaMetadata = currentMediaMetadata?.copy(
customProperties = properties
)
viewModelScope.launch {
@@ -1405,15 +1421,15 @@ class GalleryViewModel(application: Application) : AndroidViewModel(application)
editChromaNoiseReduction.value = value
}
fun saveRawDenoiseValue(photoData: PhotoData, value: Float) {
fun saveRawDenoiseValue(mediaData: MediaData, value: Float) {
editRawDenoise.value = value
viewModelScope.launch {
val metadata = photoData.metadata?.copy(
val metadata = mediaData.metadata?.copy(
rawDenoiseValue = editRawDenoise.value,
)
val context = getApplication<Application>()
metadata?.let {
PhotoManager.saveMetadata(context, photoData.id, it)
MediaManager.saveMetadata(context, mediaData.id, it)
}
}
}
@@ -1449,13 +1465,14 @@ class GalleryViewModel(application: Application) : AndroidViewModel(application)
fun isRaw(photoId: String): Boolean {
val context = getApplication<Application>()
return PhotoManager.getDngFile(context, photoId).exists()
return MediaManager.getDngFile(context, photoId).exists()
}
/**
* 获取指定照片的完整转换器(LUT + 边框)
*/
fun getPhotoTransformation(photo: PhotoData): PhotoTransformation? {
fun getPhotoTransformation(photo: MediaData): PhotoTransformation? {
if (photo.isVideo) return null
val metadata = photo.metadata ?: return null
// 使用照片自己的 metadata 中保存的处理参数,如果没有则使用全局设置
@@ -1481,8 +1498,8 @@ class GalleryViewModel(application: Application) : AndroidViewModel(application)
/**
* 生成预览缓存 key
*/
private fun previewCacheKey(photoData: PhotoData, metadata: PhotoMetadata, showOrigin: Boolean, maxEdge: Int = 4096): String {
val photoId = photoData.id
private fun previewCacheKey(mediaData: MediaData, metadata: MediaMetadata, showOrigin: Boolean, maxEdge: Int = 4096): String {
val photoId = mediaData.id
val metadataHash = metadata.toJson().hashCode()
val refreshKey = photoRefreshKeys[photoId] ?: 0L
return if (showOrigin) {
@@ -1494,11 +1511,11 @@ class GalleryViewModel(application: Application) : AndroidViewModel(application)
}
}
private fun detailCacheKey(photoData: PhotoData, metadata: PhotoMetadata, showOrigin: Boolean): String {
return "detail_${previewCacheKey(photoData, metadata, showOrigin)}"
private fun detailCacheKey(mediaData: MediaData, metadata: MediaMetadata, showOrigin: Boolean): String {
return "detail_${previewCacheKey(mediaData, metadata, showOrigin)}"
}
private fun shouldUseHdrDetail(metadata: PhotoMetadata): Boolean {
private fun shouldUseHdrDetail(metadata: MediaMetadata): Boolean {
return metadata.manualHdrEffectEnabled
}
@@ -1520,7 +1537,7 @@ class GalleryViewModel(application: Application) : AndroidViewModel(application)
* 获取应用 LUT 和边框后的预览 Bitmap
*/
suspend fun getPreviewBitmap(
photo: PhotoData,
photo: MediaData,
useGlobalEdit: Boolean = false,
showOrigin: Boolean = false,
bitmap: Bitmap? = null,
@@ -1529,11 +1546,12 @@ class GalleryViewModel(application: Application) : AndroidViewModel(application)
recipeParamsOverride: ColorRecipeParams? = null,
maxEdge: Int = 4096
): Bitmap? {
if (photo.isVideo) return null
return withContext(Dispatchers.IO) {
try {
val context = getApplication<Application>()
var finalMetadata: PhotoMetadata
var finalMetadata: MediaMetadata
var finalS = 0f
var finalNR = 0f
var finalCNR = 0f
@@ -1541,11 +1559,11 @@ class GalleryViewModel(application: Application) : AndroidViewModel(application)
val metadata =
photo.metadata
?: photo.relatedPhoto?.metadata
?: PhotoManager.loadMetadata(getApplication(), photo.id)
?: PhotoMetadata()
?: MediaManager.loadMetadata(getApplication(), photo.id)
?: MediaMetadata()
if (useGlobalEdit) {
finalMetadata = (currentPhotoMetadata ?: metadata).copy(
finalMetadata = (currentMediaMetadata ?: metadata).copy(
lutId = editLutId.value,
frameId = editFrameId.value,
colorRecipeParams = recipeParamsOverride ?: editPhotoRecipeParams.value ?: editLutRecipeParams.value,
@@ -1603,10 +1621,10 @@ class GalleryViewModel(application: Application) : AndroidViewModel(application)
// 2. 原始底图缓存(按 maxEdge 加载,快速预览走小尺寸,正式预览走高分辨率)
val currentBitmap = bitmap ?: if (selectedTab == GalleryTab.PHOTON) {
PhotoManager.loadBitmap(context, photo.id, maxEdge)
MediaManager.loadBitmap(context, photo.id, maxEdge)
} else {
PhotoManager.loadBitmap(context, photo.id, maxEdge)
?: PhotoManager.loadBitmap(context, photo.uri, maxEdge)
MediaManager.loadBitmap(context, photo.id, maxEdge)
?: MediaManager.loadBitmap(context, photo.uri, maxEdge)
} ?: return@withContext null
// 只在全分辨率路径下缓存原始底图(避免低分辨率污染 origin 缓存)
@@ -1642,16 +1660,17 @@ class GalleryViewModel(application: Application) : AndroidViewModel(application)
}
suspend fun getDetailBitmap(
photo: PhotoData,
photo: MediaData,
): Bitmap? {
if (photo.isVideo) return null
return withContext(Dispatchers.IO) {
try {
val context = getApplication<Application>()
val metadata =
photo.metadata
?: photo.relatedPhoto?.metadata
?: PhotoManager.loadMetadata(getApplication(), photo.id)
?: PhotoMetadata()
?: MediaManager.loadMetadata(getApplication(), photo.id)
?: MediaMetadata()
val detailCacheKey = detailCacheKey(photo, metadata, false)
val shouldUseHdrDetail = shouldUseHdrDetail(metadata)
@@ -1663,7 +1682,7 @@ class GalleryViewModel(application: Application) : AndroidViewModel(application)
return@withContext null
}
if (PhotoManager.isHdrWorkInFlight(photo.id)) {
if (MediaManager.isHdrWorkInFlight(photo.id)) {
PLog.d(TAG, "getDetailBitmap: HDR work in flight for ${photo.id}, using preview fallback")
return@withContext null
}
@@ -1674,9 +1693,9 @@ class GalleryViewModel(application: Application) : AndroidViewModel(application)
return@withContext cachedDetail
}
val detailFile = PhotoManager.getDetailHdrFile(context, photo.id)
val detailFile = MediaManager.getDetailHdrFile(context, photo.id)
if (detailFile.exists()) {
val diskCached = PhotoManager.loadBitmap(context, Uri.fromFile(detailFile), preserveHdr = true)
val diskCached = MediaManager.loadBitmap(context, Uri.fromFile(detailFile), preserveHdr = true)
if (diskCached != null) {
detailBitmapCache.put(detailCacheKey, diskCached)
// PLog.d(
@@ -1697,12 +1716,12 @@ class GalleryViewModel(application: Application) : AndroidViewModel(application)
}
}
fun shouldPrioritizeDetailBitmap(photo: PhotoData): Boolean {
fun shouldPrioritizeDetailBitmap(photo: MediaData): Boolean {
val context = getApplication<Application>()
val metadata =
photo.metadata
?: photo.relatedPhoto?.metadata
?: PhotoMetadata()
?: MediaMetadata()
if (!shouldUseHdrDetail(metadata)) {
return false
}
@@ -1711,7 +1730,7 @@ class GalleryViewModel(application: Application) : AndroidViewModel(application)
if (cachedDetail != null && !cachedDetail.isRecycled) {
return true
}
if (PhotoManager.getDetailHdrFile(context, photo.id).exists()) {
if (MediaManager.getDetailHdrFile(context, photo.id).exists()) {
return true
}
return metadata.hasEmbeddedGainmap
@@ -1720,7 +1739,7 @@ class GalleryViewModel(application: Application) : AndroidViewModel(application)
/**
* 保存编辑(只更新元数据,不修改原图)
*/
fun saveEditMetadata(photo: PhotoData, onComplete: (Boolean) -> Unit = {}) {
fun saveEditMetadata(photo: MediaData, onComplete: (Boolean) -> Unit = {}) {
// 检查 VIP 权限
val currentLut = availableLuts.find { it.id == editLutId.value }
if (currentLut?.isVip == true && !isPurchased.value) {
@@ -1735,14 +1754,14 @@ class GalleryViewModel(application: Application) : AndroidViewModel(application)
val targetPhotoId = if (selectedTab == GalleryTab.SYSTEM) {
photo.relatedPhoto?.id ?: run {
val importedId = PhotoManager.importPhoto(
val importedId = MediaManager.importPhoto(
context,
photo.uri,
editLutId.value
)
if (importedId != null) {
photo.metadata = PhotoManager.loadMetadata(context, importedId)
currentPhotoMetadata = photo.metadata
photo.metadata = MediaManager.loadMetadata(context, importedId)
currentMediaMetadata = photo.metadata
}
importedId
}
@@ -1769,7 +1788,7 @@ class GalleryViewModel(application: Application) : AndroidViewModel(application)
// Get AspectRatio enum if it was a preset, otherwise null
val finalRatio = (editCropAspectOption.value as? CropAspectOption.FromAspectRatio)?.ratio
val metadata = currentPhotoMetadata?.copy(
val metadata = currentMediaMetadata?.copy(
lutId = editLutId.value,
frameId = editFrameId.value,
colorRecipeParams = editPhotoRecipeParams.value ?: editLutRecipeParams.value,
@@ -1786,10 +1805,10 @@ class GalleryViewModel(application: Application) : AndroidViewModel(application)
onComplete(false)
return@launch
}
val success = PhotoManager.saveMetadata(context, targetPhotoId, metadata)
val success = MediaManager.saveMetadata(context, targetPhotoId, metadata)
if (success) {
currentPhotoMetadata = metadata
currentMediaMetadata = metadata
// 如果是新导入的,刷相册列表
if (selectedTab == GalleryTab.SYSTEM) {
@@ -1813,8 +1832,8 @@ class GalleryViewModel(application: Application) : AndroidViewModel(application)
exitEditMode()
invalidatePreviewCache(targetPhotoId)
PhotoManager.deleteDetailHdrFile(context, targetPhotoId)
PhotoManager.queueDetailHdrCacheBuild(
MediaManager.deleteDetailHdrFile(context, targetPhotoId)
MediaManager.queueDetailHdrCacheBuild(
context = context,
photoId = targetPhotoId,
metadata = metadata,
@@ -1834,14 +1853,14 @@ class GalleryViewModel(application: Application) : AndroidViewModel(application)
/**
* 刷新 RAW 照片的预览图
*/
fun refreshRawPreview(photo: PhotoData, onComplete: (Boolean) -> Unit = {}) {
fun refreshRawPreview(photo: MediaData, onComplete: (Boolean) -> Unit = {}) {
if (refreshingPhotos.contains(photo.id)) return
viewModelScope.launch {
refreshingPhotos.add(photo.id)
try {
val context = getApplication<Application>()
val result = PhotoManager.refreshRawPreview(
val result = MediaManager.refreshRawPreview(
context,
photo.id,
RawProcessingPreferences.DROMode.valueOf(droMode.value)
@@ -1874,20 +1893,24 @@ class GalleryViewModel(application: Application) : AndroidViewModel(application)
* 导出照片到公共目录(带 LUT 烘焙)
*/
fun exportPhoto(
photo: PhotoData,
photo: MediaData,
bitmap: Bitmap? = null,
suffix: String? = null,
onComplete: (Boolean) -> Unit = {}
) {
if (photo.isVideo) {
onComplete(false)
return
}
viewModelScope.launch {
var photoId = photo.id
if (selectedTab == GalleryTab.SYSTEM) {
photoId = photo.relatedPhoto?.id ?: photoId
}
val metadata = PhotoManager.loadMetadata(getApplication(), photoId) ?: photo.metadata
?: PhotoMetadata()
val metadata = MediaManager.loadMetadata(getApplication(), photoId) ?: photo.metadata
?: MediaMetadata()
val context = getApplication<Application>()
val success = PhotoManager.exportPhoto(
val success = MediaManager.exportPhoto(
context, photoId, bitmap, contentRepository.photoProcessor, metadata,
sharpening.value, noiseReduction.value,
chromaNoiseReduction.value, photoQuality.firstOrNull() ?: 95, suffix
@@ -1908,7 +1931,7 @@ class GalleryViewModel(application: Application) : AndroidViewModel(application)
viewModelScope.launch {
_isExporting.value = true
val toExport = selectedPhotos.toList()
val toExport = selectedPhotos.filter { it.isImage }
val total = toExport.size
exportProgress = 0 to total
@@ -1924,8 +1947,8 @@ class GalleryViewModel(application: Application) : AndroidViewModel(application)
photoId = photo.relatedPhoto?.id ?: return@forEachIndexed
}
val metadata = PhotoManager.loadMetadata(context, photoId) ?: photo.metadata ?: PhotoMetadata()
PhotoManager.exportPhoto(
val metadata = MediaManager.loadMetadata(context, photoId) ?: photo.metadata ?: MediaMetadata()
MediaManager.exportPhoto(
context, photoId, null, contentRepository.photoProcessor, metadata,
sharpening.value, noiseReduction.value,
chromaNoiseReduction.value, quality
@@ -1950,11 +1973,20 @@ class GalleryViewModel(application: Application) : AndroidViewModel(application)
}
}
private suspend fun prepareSharedPhoto(photo: PhotoData): File? = withContext(Dispatchers.IO) {
private data class ShareRequest(val uri: Uri, val mimeType: String)
private suspend fun prepareShareRequest(photo: MediaData): ShareRequest? = withContext(Dispatchers.IO) {
try {
val context = getApplication<Application>()
if (photo.isVideo) {
val shareUri = photo.sourceUri ?: photo.metadata?.sourceUri?.toUri() ?: photo.uri
return@withContext ShareRequest(
uri = shareUri,
mimeType = photo.mimeType ?: photo.metadata?.mimeType ?: "video/*"
)
}
val metadata =
photo.metadata ?: PhotoManager.loadMetadata(context, photo.id) ?: PhotoMetadata()
photo.metadata ?: MediaManager.loadMetadata(context, photo.id) ?: MediaMetadata()
// 处理照片:跟随用户设置
val processedBitmap = contentRepository.photoProcessor.process(
@@ -1978,7 +2010,14 @@ class GalleryViewModel(application: Application) : AndroidViewModel(application)
processedBitmap.recycle()
sharedFile
ShareRequest(
uri = FileProvider.getUriForFile(
context,
"${context.packageName}.fileprovider",
sharedFile
),
mimeType = "image/jpeg"
)
} catch (e: Exception) {
PLog.e(TAG, "Failed to prepare shared photo", e)
null
@@ -2002,7 +2041,7 @@ class GalleryViewModel(application: Application) : AndroidViewModel(application)
.firstOrNull { it.isDefault }?.id
val computationalAperture = defaultVirtualAperture.firstOrNull()?.let { if (it > 0f) it else null }
uris.forEach { uri ->
val photoId = PhotoManager.importPhoto(context, uri, lutId, computationalAperture)
val photoId = MediaManager.importPhoto(context, uri, lutId, computationalAperture)
if (photoId != null) {
successCount++
}
@@ -2063,20 +2102,22 @@ class GalleryViewModel(application: Application) : AndroidViewModel(application)
}
}
fun canToggleManualHdrEnhance(photo: PhotoData): Boolean {
fun canToggleManualHdrEnhance(photo: MediaData): Boolean {
if (photo.isVideo) return false
val metadata = photo.metadata ?: photo.relatedPhoto?.metadata ?: return false
return metadata.hasEmbeddedGainmap ||
metadata.dynamicRangeProfile == "HLG10" ||
PhotoManager.getDngFile(getApplication(), photo.id).exists() ||
PhotoManager.getPhotoFile(getApplication(), photo.id).exists()
MediaManager.getDngFile(getApplication(), photo.id).exists() ||
MediaManager.getPhotoFile(getApplication(), photo.id).exists()
}
fun isManualHdrEnhanceEnabled(photo: PhotoData): Boolean {
fun isManualHdrEnhanceEnabled(photo: MediaData): Boolean {
if (photo.isVideo) return false
val metadata = photo.metadata ?: photo.relatedPhoto?.metadata ?: return false
return metadata.manualHdrEffectEnabled
}
fun toggleManualHdrEnhance(photo: PhotoData, onComplete: (Boolean) -> Unit = {}) {
fun toggleManualHdrEnhance(photo: MediaData, onComplete: (Boolean) -> Unit = {}) {
if (!canToggleManualHdrEnhance(photo)) {
onComplete(false)
return
@@ -2091,7 +2132,7 @@ class GalleryViewModel(application: Application) : AndroidViewModel(application)
val updatedMetadata = currentMetadata.copy(
manualHdrEffectEnabled = !currentMetadata.manualHdrEffectEnabled
)
val success = PhotoManager.saveMetadata(context, photo.id, updatedMetadata)
val success = MediaManager.saveMetadata(context, photo.id, updatedMetadata)
if (success) {
val updatedPhotos = _photos.value.map { p ->
if (p.id == photo.id) p.copy(metadata = updatedMetadata) else p
@@ -2101,11 +2142,11 @@ class GalleryViewModel(application: Application) : AndroidViewModel(application)
_latestPhoto.value = _latestPhoto.value?.copy(metadata = updatedMetadata)
}
if (currentPhotoMetadataId == photo.id) {
currentPhotoMetadata = updatedMetadata
currentMediaMetadata = updatedMetadata
}
invalidatePreviewCache(photo.id)
if (updatedMetadata.manualHdrEffectEnabled) {
PhotoManager.queueDetailHdrCacheBuild(
MediaManager.queueDetailHdrCacheBuild(
context = context,
photoId = photo.id,
metadata = updatedMetadata,
@@ -2114,7 +2155,7 @@ class GalleryViewModel(application: Application) : AndroidViewModel(application)
chromaNoiseReduction = updatedMetadata.chromaNoiseReduction ?: 0f
)
} else {
PhotoManager.deleteDetailHdrFile(context, photo.id)
MediaManager.deleteDetailHdrFile(context, photo.id)
}
photoRefreshKeys[photo.id] = System.currentTimeMillis()
}
@@ -89,6 +89,7 @@
<string name="delete_exported_photos">同时删除系统相册中的导出图</string>
<string name="no_photos">暂无照片</string>
<string name="photo_info">照片信息</string>
<string name="video_info">视频信息</string>
<string name="filter">LUT</string>
<string name="intensity">强度</string>
<string name="original">原图</string>
@@ -104,6 +105,15 @@
<string name="photo_info_aperture">光圈</string>
<string name="photo_info_iso">ISO</string>
<string name="photo_info_shutter_speed">快门速度</string>
<string name="video">视频</string>
<string name="yes">是</string>
<string name="no">否</string>
<string name="video_info_duration">时长</string>
<string name="video_info_mime">格式</string>
<string name="video_info_frame_rate">帧率</string>
<string name="video_info_bitrate">码率</string>
<string name="video_info_has_audio">音轨</string>
<string name="video_info_rotation">旋转角</string>
<!-- Frame Watermark -->
<string name="frame">边框</string>
+10
View File
@@ -91,6 +91,7 @@
<string name="delete_exported_photos">Also delete from system gallery</string>
<string name="no_photos">No photos yet</string>
<string name="photo_info">Photo Info</string>
<string name="video_info">Video Info</string>
<string name="filter">LUT</string>
<string name="intensity">Intensity</string>
<string name="original">Original</string>
@@ -106,6 +107,15 @@
<string name="photo_info_aperture">Aperture</string>
<string name="photo_info_iso">ISO</string>
<string name="photo_info_shutter_speed">Shutter Speed</string>
<string name="video">Video</string>
<string name="yes">Yes</string>
<string name="no">No</string>
<string name="video_info_duration">Duration</string>
<string name="video_info_mime">Format</string>
<string name="video_info_frame_rate">Frame Rate</string>
<string name="video_info_bitrate">Bitrate</string>
<string name="video_info_has_audio">Audio</string>
<string name="video_info_rotation">Rotation</string>
<!-- Frame Watermark -->
<string name="frame">Frame</string>