From d55fe08c700a334a875ba1cf4086579eb7f2ccfc Mon Sep 17 00:00:00 2001 From: zhoubinjia Date: Thu, 18 Jun 2026 13:15:55 +0800 Subject: [PATCH] feat: photo/video save path --- .../mycamera/camera/Camera2Controller.kt | 12 + .../data/UserPreferencesRepository.kt | 38 +- .../hinnka/mycamera/gallery/GalleryManager.kt | 460 +++++++++++------- .../hinnka/mycamera/gallery/PhotoSavePath.kt | 14 + .../mycamera/ui/settings/SettingsScreen.kt | 153 ++++++ .../mycamera/video/VideoMediaStoreWriter.kt | 87 +++- .../hinnka/mycamera/video/VideoRecorder.kt | 23 +- .../com/hinnka/mycamera/video/VideoTypes.kt | 14 + .../mycamera/viewmodel/CameraViewModel.kt | 29 ++ app/src/main/res/values-zh-rCN/strings.xml | 10 + app/src/main/res/values-zh-rHK/strings.xml | 10 + app/src/main/res/values/strings.xml | 10 + 12 files changed, 662 insertions(+), 198 deletions(-) create mode 100644 app/src/main/java/com/hinnka/mycamera/gallery/PhotoSavePath.kt diff --git a/app/src/main/java/com/hinnka/mycamera/camera/Camera2Controller.kt b/app/src/main/java/com/hinnka/mycamera/camera/Camera2Controller.kt index 38f42794..5199c0cf 100644 --- a/app/src/main/java/com/hinnka/mycamera/camera/Camera2Controller.kt +++ b/app/src/main/java/com/hinnka/mycamera/camera/Camera2Controller.kt @@ -40,6 +40,7 @@ import com.hinnka.mycamera.video.VideoFpsPreset import com.hinnka.mycamera.video.VideoEncoderColorRequest import com.hinnka.mycamera.video.VideoLogProfile import com.hinnka.mycamera.video.VideoRecorder +import com.hinnka.mycamera.video.VideoRecordingPath import com.hinnka.mycamera.video.VideoResolutionPreset import com.hinnka.mycamera.video.VideoRecordingState import com.hinnka.mycamera.video.VideoStabilizationMode @@ -3398,6 +3399,15 @@ class Camera2Controller(private val context: Context) { videoRecorder.setPreferredAudioInputId(normalizedAudioInputId) } + fun setVideoRecordingPath(recordingPath: VideoRecordingPath, recordingTreeUri: String? = null) { + _state.value = _state.value.copy( + videoConfig = _state.value.videoConfig.copy( + recordingPath = recordingPath, + recordingTreeUri = recordingTreeUri?.takeIf { it.isNotBlank() } + ) + ) + } + fun setVideoTorchEnabled(enabled: Boolean) { _state.value = _state.value.copy( videoConfig = _state.value.videoConfig.copy( @@ -3438,6 +3448,8 @@ class Camera2Controller(private val context: Context) { ), orientationHintDegrees = resolveVideoOrientationHintDegrees(), flipEncodedFrame = shouldFlipEncodedFrame, + recordingPath = _state.value.videoConfig.recordingPath, + recordingTreeUri = _state.value.videoConfig.recordingTreeUri, onError = { message -> PLog.e(TAG, "Video recording error: $message") onCameraError?.invoke(-1, message, false) diff --git a/app/src/main/java/com/hinnka/mycamera/data/UserPreferencesRepository.kt b/app/src/main/java/com/hinnka/mycamera/data/UserPreferencesRepository.kt index 20f7c709..711e4348 100644 --- a/app/src/main/java/com/hinnka/mycamera/data/UserPreferencesRepository.kt +++ b/app/src/main/java/com/hinnka/mycamera/data/UserPreferencesRepository.kt @@ -17,6 +17,7 @@ import com.hinnka.mycamera.camera.MultiFrameConfig import com.hinnka.mycamera.camera.MeteringMode import com.hinnka.mycamera.camera.VendorCaptureSettings import com.hinnka.mycamera.camera.VendorCaptureSettingsByLens +import com.hinnka.mycamera.gallery.PhotoSavePath import com.hinnka.mycamera.lut.BaselineColorCorrectionTarget import com.hinnka.mycamera.lut.DEFAULT_RAW_BASELINE_LUT_ID import com.hinnka.mycamera.raw.ColorSpace @@ -35,6 +36,7 @@ import com.hinnka.mycamera.video.VIDEO_AUDIO_INPUT_AUTO import com.hinnka.mycamera.video.VideoBitratePreset import com.hinnka.mycamera.video.VideoFpsPreset import com.hinnka.mycamera.video.VideoLogProfile +import com.hinnka.mycamera.video.VideoRecordingPath import com.hinnka.mycamera.video.VideoResolutionPreset import com.hinnka.mycamera.model.EffectParams import com.hinnka.mycamera.model.CameraPreset @@ -116,6 +118,8 @@ data class UserPreferences( val vibrationEnabled: Boolean = true, // 拍摄震动 val volumeKeyAction: VolumeKeyAction = VolumeKeyAction.CAPTURE, // 音量键操作 val autoSaveAfterCapture: Boolean = true, // 自动保存 + val photoSavePath: PhotoSavePath = PhotoSavePath.DCIM_PHOTON, + val photoSaveTreeUri: String? = null, val nrLevel: Int = 5, // 降噪等级:0=Off, 1=Fast, 2=High Quality, 3=ZSL, 4=Minimal, 5=Auto val edgeLevel: Int = 1, // 锐化等级:0=Off, 1=Fast, 2=High Quality, 3=Real-time val vendorCaptureSettingsByLens: VendorCaptureSettingsByLens = VendorCaptureSettingsByLens.Empty, @@ -163,6 +167,8 @@ data class UserPreferences( val videoLogProfile: VideoLogProfile = VideoLogProfile.OFF, val videoBitrate: VideoBitratePreset = VideoBitratePreset.P1, val videoAudioInputId: String = VIDEO_AUDIO_INPUT_AUTO, + val videoRecordingPath: VideoRecordingPath = VideoRecordingPath.DCIM_PHOTON, + val videoRecordingTreeUri: String? = null, val videoStabilizationMode: com.hinnka.mycamera.video.VideoStabilizationMode = com.hinnka.mycamera.video.VideoStabilizationMode.OIS, val videoTorchEnabled: Boolean = false, val videoCodec: com.hinnka.mycamera.video.VideoCodec = com.hinnka.mycamera.video.VideoCodec.H264, @@ -276,6 +282,8 @@ class UserPreferencesRepository(private val context: Context) { private val VIBRATION_ENABLED = booleanPreferencesKey("vibration_enabled") private val VOLUME_KEY_ACTION = stringPreferencesKey("volume_key_action") private val AUTO_SAVE_AFTER_CAPTURE = booleanPreferencesKey("auto_save_after_capture") + private val PHOTO_SAVE_PATH = stringPreferencesKey("photo_save_path") + private val PHOTO_SAVE_TREE_URI = stringPreferencesKey("photo_save_tree_uri") private val NR_LEVEL = intPreferencesKey("nr_level") private val EDGE_LEVEL = intPreferencesKey("edge_level") private val VENDOR_CAPTURE_SETTINGS = stringPreferencesKey("vendor_capture_settings") @@ -330,6 +338,8 @@ class UserPreferencesRepository(private val context: Context) { private val VIDEO_LOG_PROFILE = stringPreferencesKey("video_log_profile") private val VIDEO_BITRATE = stringPreferencesKey("video_bitrate") private val VIDEO_AUDIO_INPUT_ID = stringPreferencesKey("video_audio_input_id") + private val VIDEO_RECORDING_PATH = stringPreferencesKey("video_recording_path") + private val VIDEO_RECORDING_TREE_URI = stringPreferencesKey("video_recording_tree_uri") private val VIDEO_STABILIZATION_MODE = stringPreferencesKey("video_stabilization_mode") private val VIDEO_TORCH_ENABLED = booleanPreferencesKey("video_torch_enabled") private val VIDEO_CODEC = stringPreferencesKey("video_codec") @@ -425,6 +435,8 @@ class UserPreferencesRepository(private val context: Context) { preferences[VOLUME_KEY_ACTION] ?: VolumeKeyAction.CAPTURE.name ), autoSaveAfterCapture = preferences[AUTO_SAVE_AFTER_CAPTURE] ?: true, + photoSavePath = PhotoSavePath.fromPersistedName(preferences[PHOTO_SAVE_PATH]), + photoSaveTreeUri = preferences[PHOTO_SAVE_TREE_URI]?.takeIf { it.isNotBlank() }, nrLevel = preferences[NR_LEVEL] ?: 5, edgeLevel = preferences[EDGE_LEVEL] ?: 1, vendorCaptureSettingsByLens = VendorCaptureSettingsByLens.deserialize( @@ -491,6 +503,8 @@ class UserPreferencesRepository(private val context: Context) { preferences[VIDEO_BITRATE] ?: VideoBitratePreset.P1.name ), videoAudioInputId = preferences[VIDEO_AUDIO_INPUT_ID] ?: VIDEO_AUDIO_INPUT_AUTO, + videoRecordingPath = VideoRecordingPath.fromPersistedName(preferences[VIDEO_RECORDING_PATH]), + videoRecordingTreeUri = preferences[VIDEO_RECORDING_TREE_URI]?.takeIf { it.isNotBlank() }, videoStabilizationMode = com.hinnka.mycamera.video.VideoStabilizationMode.valueOf( preferences[VIDEO_STABILIZATION_MODE] ?: com.hinnka.mycamera.video.VideoStabilizationMode.OIS.name ), @@ -1007,6 +1021,18 @@ class UserPreferencesRepository(private val context: Context) { } } + suspend fun savePhotoSavePath(savePath: PhotoSavePath, treeUri: String? = null) { + context.dataStore.edit { preferences -> + preferences[PHOTO_SAVE_PATH] = savePath.name + val normalizedTreeUri = treeUri?.takeIf { it.isNotBlank() } + if (savePath == PhotoSavePath.EXTERNAL_TREE && normalizedTreeUri != null) { + preferences[PHOTO_SAVE_TREE_URI] = normalizedTreeUri + } else { + preferences.remove(PHOTO_SAVE_TREE_URI) + } + } + } + /** * 保存降噪等级 */ @@ -1486,7 +1512,17 @@ class UserPreferencesRepository(private val context: Context) { } } - + suspend fun saveVideoRecordingPath(recordingPath: VideoRecordingPath, treeUri: String? = null) { + context.dataStore.edit { preferences -> + preferences[VIDEO_RECORDING_PATH] = recordingPath.name + val normalizedTreeUri = treeUri?.takeIf { it.isNotBlank() } + if (recordingPath == VideoRecordingPath.EXTERNAL_TREE && normalizedTreeUri != null) { + preferences[VIDEO_RECORDING_TREE_URI] = normalizedTreeUri + } else { + preferences.remove(VIDEO_RECORDING_TREE_URI) + } + } + } suspend fun saveVideoTorchEnabled(enabled: Boolean) { context.dataStore.edit { preferences -> diff --git a/app/src/main/java/com/hinnka/mycamera/gallery/GalleryManager.kt b/app/src/main/java/com/hinnka/mycamera/gallery/GalleryManager.kt index e7232766..aa7b2931 100644 --- a/app/src/main/java/com/hinnka/mycamera/gallery/GalleryManager.kt +++ b/app/src/main/java/com/hinnka/mycamera/gallery/GalleryManager.kt @@ -10,6 +10,7 @@ import android.media.MediaMetadataRetriever import android.net.Uri import android.os.Build import android.os.Environment +import android.provider.DocumentsContract import android.provider.MediaStore import androidx.core.graphics.createBitmap import androidx.exifinterface.media.ExifInterface @@ -47,6 +48,7 @@ import kotlinx.coroutines.sync.Mutex import kotlinx.coroutines.sync.withLock import java.io.File import java.io.FileOutputStream +import java.io.OutputStream import java.nio.ByteBuffer import java.nio.ByteOrder import java.nio.IntBuffer @@ -122,6 +124,11 @@ object GalleryManager { val usesLargeDirectAllocator: Boolean = false, ) + private data class PhotoExportDestination( + val savePath: PhotoSavePath, + val treeUri: String? + ) + val processingScope = CoroutineScope(Dispatchers.Default + SupervisorJob()) private val gainmapProducer = UnifiedGainmapProducer() @@ -562,6 +569,132 @@ object GalleryManager { detailHdrBuildJobs[photoId] = job } + private suspend fun resolvePhotoExportDestination(context: Context): PhotoExportDestination { + val preferences = ContentRepository.getInstance(context) + .userPreferencesRepository + .userPreferences + .firstOrNull() + val savePath = preferences?.photoSavePath ?: PhotoSavePath.DCIM_PHOTON + val treeUri = preferences?.photoSaveTreeUri?.takeIf { it.isNotBlank() } + return if (savePath == PhotoSavePath.EXTERNAL_TREE && treeUri != null) { + PhotoExportDestination(savePath, treeUri) + } else { + if (savePath == PhotoSavePath.EXTERNAL_TREE) { + PLog.w(TAG, "Photo external save path selected without tree URI, falling back to MediaStore") + } + PhotoExportDestination(PhotoSavePath.DCIM_PHOTON, null) + } + } + + private fun createPhotoExportUri( + context: Context, + destination: PhotoExportDestination, + collectionUri: Uri, + displayName: String, + mimeType: String + ): Uri? { + return if (destination.savePath == PhotoSavePath.EXTERNAL_TREE) { + createPhotoExportTreeUri(context, destination.treeUri, displayName, mimeType) + } else { + val relativePath = destination.savePath.relativePath ?: PhotoSavePath.DCIM_PHOTON.relativePath + val contentValues = ContentValues().apply { + put(MediaStore.MediaColumns.DISPLAY_NAME, displayName) + put(MediaStore.MediaColumns.MIME_TYPE, mimeType) + put(MediaStore.MediaColumns.RELATIVE_PATH, relativePath) + } + context.contentResolver.insert(collectionUri, contentValues) + } + } + + private fun createPhotoExportTreeUri( + context: Context, + treeUriString: String?, + displayName: String, + mimeType: String + ): Uri? { + if (treeUriString.isNullOrBlank()) return null + return try { + val treeUri = Uri.parse(treeUriString) + val treeDocumentId = DocumentsContract.getTreeDocumentId(treeUri) + val parentUri = DocumentsContract.buildDocumentUriUsingTree(treeUri, treeDocumentId) + DocumentsContract.createDocument(context.contentResolver, parentUri, mimeType, displayName) + } catch (e: Exception) { + PLog.e(TAG, "Failed to create photo export document: $displayName", e) + null + } + } + + private fun discardPhotoExportUri(context: Context, uri: Uri) { + runCatching { + if (DocumentsContract.isDocumentUri(context, uri)) { + DocumentsContract.deleteDocument(context.contentResolver, uri) + } else { + context.contentResolver.delete(uri, null, null) + } + }.onFailure { + PLog.w(TAG, "Failed to discard photo export URI $uri: ${it.message}") + } + } + + private fun writeToPhotoExportUri( + context: Context, + uri: Uri, + write: (OutputStream) -> Unit + ): Boolean { + return try { + context.contentResolver.openOutputStream(uri)?.use { output -> + write(output) + } ?: return false + true + } catch (e: Exception) { + PLog.e(TAG, "Failed to write photo export URI: $uri", e) + false + } + } + + private fun exportFileToConfiguredPhotoStorage( + context: Context, + destination: PhotoExportDestination, + collectionUri: Uri, + displayName: String, + mimeType: String, + sourceFile: File + ): Uri? { + if (!sourceFile.exists() || sourceFile.length() <= 0L) return null + val uri = createPhotoExportUri(context, destination, collectionUri, displayName, mimeType) + ?: return null + val written = writeToPhotoExportUri(context, uri) { output -> + sourceFile.inputStream().use { input -> + input.copyTo(output) + } + } + if (!written) { + discardPhotoExportUri(context, uri) + return null + } + return uri + } + + private fun exportBytesToConfiguredPhotoStorage( + context: Context, + destination: PhotoExportDestination, + collectionUri: Uri, + displayName: String, + mimeType: String, + data: ByteArray + ): Uri? { + val uri = createPhotoExportUri(context, destination, collectionUri, displayName, mimeType) + ?: return null + val written = writeToPhotoExportUri(context, uri) { output -> + output.write(data) + } + if (!written) { + discardPhotoExportUri(context, uri) + return null + } + return uri + } + @androidx.annotation.OptIn(androidx.media3.common.util.UnstableApi::class) suspend fun exportPhoto( context: Context, @@ -584,6 +717,7 @@ object GalleryManager { val shouldPreferHeic = preferHeicExport ?: (ContentRepository.getInstance(context).userPreferencesRepository.userPreferences.firstOrNull() ?.useHeicExport ?: false) + val exportDestination = resolvePhotoExportDestination(context) if (!shouldPreferHeic && bitmap == null && canReuseEmbeddedGainmap(metadata)) { val embeddedBitmap = loadOriginalBitmap(context, id) @@ -595,7 +729,8 @@ object GalleryManager { bitmap = embeddedBitmap, metadata = metadata, photoQuality = photoQuality, - suffix = suffix + suffix = suffix, + destination = exportDestination ) } } @@ -679,7 +814,8 @@ object GalleryManager { baseFilename = baseFilename, extension = HeicExportEncoder.EXTENSION, mimeType = HeicExportEncoder.MIME_TYPE, - gainmapResult = gainmapResult + gainmapResult = gainmapResult, + destination = exportDestination ) if (heicExported) { processedBitmap.recycle() @@ -689,144 +825,135 @@ object GalleryManager { } val filename = "$baseFilename.jpg" - val contentValues = ContentValues().apply { - put(MediaStore.MediaColumns.DISPLAY_NAME, filename) - put(MediaStore.MediaColumns.MIME_TYPE, "image/jpeg") - put(MediaStore.MediaColumns.RELATIVE_PATH, Environment.DIRECTORY_DCIM + "/PhotonCamera") + val exportWriteElapsed = measureTimeMillis { + FileOutputStream(tempExportFile).use { outputStream -> + writeFinalJpeg( + bitmap = processedBitmap, + outputStream = outputStream, + quality = photoQuality, + gainmapResult = if (isLivePhoto) null else gainmapResult + ) + } } + PLog.d(TAG, "exportPhoto writeFinalJpeg wrapper took ${exportWriteElapsed}ms") - val uri = context.contentResolver.insert( - MediaStore.Images.Media.EXTERNAL_CONTENT_URI, - contentValues + ExifWriter.writeExif( + tempExportFile, metadata.toCaptureInfo().copy( + imageWidth = processedBitmap.width, + imageHeight = processedBitmap.height + ) ) - uri?.let { - val exportWriteElapsed = measureTimeMillis { - FileOutputStream(tempExportFile).use { outputStream -> - writeFinalJpeg( - bitmap = processedBitmap, - outputStream = outputStream, - quality = photoQuality, - gainmapResult = if (isLivePhoto) null else gainmapResult - ) - } - } - PLog.d(TAG, "exportPhoto writeFinalJpeg wrapper took ${exportWriteElapsed}ms") - - ExifWriter.writeExif( - tempExportFile, metadata.toCaptureInfo().copy( - imageWidth = processedBitmap.width, - imageHeight = processedBitmap.height + val uri = if (isLivePhoto) { + val tempMotionPhotoFile = File(context.cacheDir, "temp_motion_${System.nanoTime()}.jpg") + var tempProcessedVideoFile: File? = null + try { + PLog.d( + TAG, + "Attempting to create Motion Photo for export: JPEG=${tempExportFile.length()}, Video=${videoFile.length()}" ) - ) - if (isLivePhoto) { - val tempMotionPhotoFile = File(context.cacheDir, "temp_motion_${System.nanoTime()}.jpg") - var tempProcessedVideoFile: File? = null - try { - PLog.d( - TAG, - "Attempting to create Motion Photo for export: JPEG=${tempExportFile.length()}, Video=${videoFile.length()}" - ) + // 重新从磁盘加载最新元数据,以获取可能刚写回的 presentationTimestampUs + val latestMetadata = loadMetadata(context, id) ?: metadata - // 重新从磁盘加载最新元数据,以获取可能刚写回的 presentationTimestampUs - val latestMetadata = loadMetadata(context, id) ?: metadata - - var finalVideoPath = videoFile.absolutePath - if (latestMetadata.applyEffectsToVideo) { - val lutId = latestMetadata.lutId - val colorRecipeParams = latestMetadata.colorRecipeParams - PLog.d(TAG, "exportPhoto: applyEffectsToVideo is true. lutId: $lutId, colorRecipe: ${colorRecipeParams != null}") - - val lutConfig = if (lutId != null) { - ContentRepository.getInstance(context).lutManager.loadLut(lutId) - } else { - null - } - - val processedFile = File(context.cacheDir, "temp_processed_video_${System.nanoTime()}.mp4") - val success = applyEffectsToVideoFile( - context = context, - inputUri = Uri.fromFile(videoFile), - outputFile = processedFile, - lutConfig = lutConfig, - recipeParams = colorRecipeParams - ) - if (success && processedFile.exists() && processedFile.length() > 0) { - tempProcessedVideoFile = processedFile - finalVideoPath = processedFile.absolutePath - PLog.d(TAG, "exportPhoto: Successfully processed video effects. Size: ${processedFile.length()}") - } else { - processedFile.delete() - PLog.e(TAG, "exportPhoto: Failed to apply video effects, falling back to original video") - } + var finalVideoPath = videoFile.absolutePath + if (latestMetadata.applyEffectsToVideo) { + val lutId = latestMetadata.lutId + val colorRecipeParams = latestMetadata.colorRecipeParams + PLog.d(TAG, "exportPhoto: applyEffectsToVideo is true. lutId: $lutId, colorRecipe: ${colorRecipeParams != null}") + + val lutConfig = if (lutId != null) { + ContentRepository.getInstance(context).lutManager.loadLut(lutId) + } else { + null } - val success = MotionPhotoWriter.write( - tempExportFile.absolutePath, - finalVideoPath, - tempMotionPhotoFile.absolutePath, - latestMetadata.presentationTimestampUs ?: 0L, - context + val processedFile = File(context.cacheDir, "temp_processed_video_${System.nanoTime()}.mp4") + val success = applyEffectsToVideoFile( + context = context, + inputUri = Uri.fromFile(videoFile), + outputFile = processedFile, + lutConfig = lutConfig, + recipeParams = colorRecipeParams ) - - PLog.d(TAG, "MotionPhotoWriter result: $success") - - context.contentResolver.openOutputStream(uri)?.use { outputStream -> - if (success) { - tempMotionPhotoFile.inputStream().use { input -> input.copyTo(outputStream) } - PLog.d( - TAG, - "Exported Live Photo successfully: ${tempMotionPhotoFile.length()} bytes" - ) - } else { - // Fallback to normal JPEG (with EXIF) - PLog.w(TAG, "Motion Photo synthesis failed, falling back to JPEG") - tempExportFile.inputStream().use { input -> input.copyTo(outputStream) } - } + if (success && processedFile.exists() && processedFile.length() > 0) { + tempProcessedVideoFile = processedFile + finalVideoPath = processedFile.absolutePath + PLog.d(TAG, "exportPhoto: Successfully processed video effects. Size: ${processedFile.length()}") + } else { + processedFile.delete() + PLog.e(TAG, "exportPhoto: Failed to apply video effects, falling back to original video") } + } - if (Build.MANUFACTURER.lowercase().contains("vivo")) { - val filename = filename.replace(".jpg", ".mp4") - val contentValues = ContentValues().apply { - put(MediaStore.MediaColumns.DISPLAY_NAME, filename) - put(MediaStore.MediaColumns.MIME_TYPE, "video/mp4") - put( - MediaStore.MediaColumns.RELATIVE_PATH, - Environment.DIRECTORY_DCIM + "/PhotonCamera" - ) - } + val success = MotionPhotoWriter.write( + tempExportFile.absolutePath, + finalVideoPath, + tempMotionPhotoFile.absolutePath, + latestMetadata.presentationTimestampUs ?: 0L, + context + ) - val uri = context.contentResolver.insert( - MediaStore.Video.Media.EXTERNAL_CONTENT_URI, - contentValues - ) - uri?.let { uri -> context.contentResolver.openOutputStream(uri) }?.use { outputStream -> - val tempMotionVideoFile = - File(tempMotionPhotoFile.absolutePath.replace(".jpg", ".mp4")) - if (tempMotionVideoFile.exists()) { - tempMotionVideoFile.inputStream().use { input -> input.copyTo(outputStream) } - } - tempMotionVideoFile.delete() + PLog.d(TAG, "MotionPhotoWriter result: $success") + val photoExportFile = if (success) { + PLog.d(TAG, "Exported Live Photo successfully: ${tempMotionPhotoFile.length()} bytes") + tempMotionPhotoFile + } else { + PLog.w(TAG, "Motion Photo synthesis failed, falling back to JPEG") + tempExportFile + } - updateMetadata(context, id) { current -> - current.copy( - exportedUris = current.exportedUris + uri.toString() - ) + val exportedPhotoUri = exportFileToConfiguredPhotoStorage( + context = context, + destination = exportDestination, + collectionUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI, + displayName = filename, + mimeType = "image/jpeg", + sourceFile = photoExportFile + ) + + if (exportedPhotoUri != null && Build.MANUFACTURER.lowercase().contains("vivo")) { + val videoFilename = filename.replace(".jpg", ".mp4") + val tempMotionVideoFile = File(tempMotionPhotoFile.absolutePath.replace(".jpg", ".mp4")) + try { + if (tempMotionVideoFile.exists()) { + exportFileToConfiguredPhotoStorage( + context = context, + destination = exportDestination, + collectionUri = MediaStore.Video.Media.EXTERNAL_CONTENT_URI, + displayName = videoFilename, + mimeType = "video/mp4", + sourceFile = tempMotionVideoFile + )?.let { videoUri -> + updateMetadata(context, id) { current -> + current.copy( + exportedUris = current.exportedUris + videoUri.toString() + ) + } } } + } finally { + tempMotionVideoFile.delete() } - } finally { - tempMotionPhotoFile.delete() - tempProcessedVideoFile?.delete() - } - } else { - // 3b. Normal Export: Copy Temp File (with EXIF) to MediaStore - context.contentResolver.openOutputStream(uri)?.use { outputStream -> - tempExportFile.inputStream().use { input -> input.copyTo(outputStream) } } + + exportedPhotoUri + } finally { + tempMotionPhotoFile.delete() + tempProcessedVideoFile?.delete() } + } else { + exportFileToConfiguredPhotoStorage( + context = context, + destination = exportDestination, + collectionUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI, + displayName = filename, + mimeType = "image/jpeg", + sourceFile = tempExportFile + ) + } + uri?.let { // Save exported URI to metadata updateMetadata(context, id) { current -> current.copy( @@ -856,6 +983,7 @@ object GalleryManager { metadata: MediaMetadata, photoQuality: Int, suffix: String?, + destination: PhotoExportDestination, ): Boolean { val tempExportFile = File(context.cacheDir, "temp_export_${System.nanoTime()}.jpg") try { @@ -866,15 +994,6 @@ object GalleryManager { lutName?.let { withSuffix += ".$it" } val filename = "PhotonCamera_${SimpleDateFormat("yyyyMMdd_HHmmss", Locale.US).format(Date(date))}$withSuffix.jpg" - val contentValues = ContentValues().apply { - put(MediaStore.MediaColumns.DISPLAY_NAME, filename) - put(MediaStore.MediaColumns.MIME_TYPE, "image/jpeg") - put(MediaStore.MediaColumns.RELATIVE_PATH, Environment.DIRECTORY_DCIM + "/PhotonCamera") - } - val uri = context.contentResolver.insert( - MediaStore.Images.Media.EXTERNAL_CONTENT_URI, - contentValues - ) ?: return false FileOutputStream(tempExportFile).use { outputStream -> writeFinalJpeg(bitmap, outputStream, photoQuality) @@ -885,9 +1004,14 @@ object GalleryManager { imageHeight = bitmap.height ) ) - context.contentResolver.openOutputStream(uri)?.use { output -> - tempExportFile.inputStream().use { input -> input.copyTo(output) } - } + val uri = exportFileToConfiguredPhotoStorage( + context = context, + destination = destination, + collectionUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI, + displayName = filename, + mimeType = "image/jpeg", + sourceFile = tempExportFile + ) ?: return false updateMetadata(context, id) { current -> current.copy( @@ -911,6 +1035,7 @@ object GalleryManager { extension: String, mimeType: String, gainmapResult: GainmapResult? = null, + destination: PhotoExportDestination, ): Boolean { val tempExportFile = File(context.cacheDir, "temp_export_${System.nanoTime()}.$extension") try { @@ -936,20 +1061,15 @@ object GalleryManager { if (!encoded) return false val filename = "$baseFilename.$extension" - val contentValues = ContentValues().apply { - put(MediaStore.MediaColumns.DISPLAY_NAME, filename) - put(MediaStore.MediaColumns.MIME_TYPE, mimeType) - put(MediaStore.MediaColumns.RELATIVE_PATH, Environment.DIRECTORY_DCIM + "/PhotonCamera") - } - val uri = context.contentResolver.insert( - MediaStore.Images.Media.EXTERNAL_CONTENT_URI, - contentValues + val uri = exportFileToConfiguredPhotoStorage( + context = context, + destination = destination, + collectionUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI, + displayName = filename, + mimeType = mimeType, + sourceFile = tempExportFile ) ?: return false - context.contentResolver.openOutputStream(uri)?.use { output -> - tempExportFile.inputStream().use { input -> input.copyTo(output) } - } ?: return false - updateMetadata(context, id) { current -> current.copy( exportedUris = current.exportedUris + uri.toString() @@ -971,24 +1091,17 @@ object GalleryManager { val timestamp = SimpleDateFormat("yyyyMMdd_HHmmss", Locale.US) .format(Date()) val dngFilename = "PhotonCamera_${timestamp}.dng" - val dngContentValues = ContentValues().apply { - put(MediaStore.MediaColumns.DISPLAY_NAME, dngFilename) - put(MediaStore.MediaColumns.MIME_TYPE, "image/x-adobe-dng") - put( - MediaStore.MediaColumns.RELATIVE_PATH, - Environment.DIRECTORY_DCIM + "/PhotonCamera" - ) - } - - val dngUri = context.contentResolver.insert( - MediaStore.Images.Media.EXTERNAL_CONTENT_URI, - dngContentValues + val destination = resolvePhotoExportDestination(context) + val uri = exportBytesToConfiguredPhotoStorage( + context = context, + destination = destination, + collectionUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI, + displayName = dngFilename, + mimeType = "image/x-adobe-dng", + data = data ) - dngUri?.let { uri -> - context.contentResolver.openOutputStream(uri)?.use { outputStream -> - outputStream.write(data) - } + uri?.let { PLog.d(TAG, "DNG exported: $uri") updateMetadata(context, photoId) { current -> @@ -1014,26 +1127,17 @@ object GalleryManager { val timestamp = SimpleDateFormat("yyyyMMdd_HHmmss", Locale.US) .format(Date()) val dngFilename = "PhotonCamera_${timestamp}.dng" - val dngContentValues = ContentValues().apply { - put(MediaStore.MediaColumns.DISPLAY_NAME, dngFilename) - put(MediaStore.MediaColumns.MIME_TYPE, "image/x-adobe-dng") - put( - MediaStore.MediaColumns.RELATIVE_PATH, - Environment.DIRECTORY_DCIM + "/PhotonCamera" - ) - } - - val dngUri = context.contentResolver.insert( - MediaStore.Images.Media.EXTERNAL_CONTENT_URI, - dngContentValues + val destination = resolvePhotoExportDestination(context) + val uri = exportFileToConfiguredPhotoStorage( + context = context, + destination = destination, + collectionUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI, + displayName = dngFilename, + mimeType = "image/x-adobe-dng", + sourceFile = sourceFile ) - dngUri?.let { uri -> - context.contentResolver.openOutputStream(uri)?.use { outputStream -> - sourceFile.inputStream().use { inputStream -> - inputStream.copyTo(outputStream) - } - } + uri?.let { PLog.d(TAG, "DNG exported from file: $uri") updateMetadata(context, photoId) { current -> diff --git a/app/src/main/java/com/hinnka/mycamera/gallery/PhotoSavePath.kt b/app/src/main/java/com/hinnka/mycamera/gallery/PhotoSavePath.kt new file mode 100644 index 00000000..b822a256 --- /dev/null +++ b/app/src/main/java/com/hinnka/mycamera/gallery/PhotoSavePath.kt @@ -0,0 +1,14 @@ +package com.hinnka.mycamera.gallery + +import android.os.Environment + +enum class PhotoSavePath(val relativePath: String?) { + DCIM_PHOTON(Environment.DIRECTORY_DCIM + "/PhotonCamera"), + EXTERNAL_TREE(null); + + companion object { + fun fromPersistedName(name: String?): PhotoSavePath { + return entries.firstOrNull { it.name == name } ?: DCIM_PHOTON + } + } +} diff --git a/app/src/main/java/com/hinnka/mycamera/ui/settings/SettingsScreen.kt b/app/src/main/java/com/hinnka/mycamera/ui/settings/SettingsScreen.kt index 9aa2fef1..e08b9c81 100644 --- a/app/src/main/java/com/hinnka/mycamera/ui/settings/SettingsScreen.kt +++ b/app/src/main/java/com/hinnka/mycamera/ui/settings/SettingsScreen.kt @@ -116,6 +116,7 @@ import com.hinnka.mycamera.camera.VendorCaptureValueType import com.hinnka.mycamera.data.AiFocusTargetMode import com.hinnka.mycamera.data.VolumeKeyAction import com.hinnka.mycamera.frame.FrameInfo +import com.hinnka.mycamera.gallery.PhotoSavePath import com.hinnka.mycamera.gallery.HeicExportEncoder import com.hinnka.mycamera.lut.BaselineColorCorrectionTarget import com.hinnka.mycamera.lut.LutInfo @@ -135,6 +136,7 @@ import com.hinnka.mycamera.ui.components.rememberBackgroundPainter import com.hinnka.mycamera.update.AppUpdateManager import com.hinnka.mycamera.utils.DeviceUtil import com.hinnka.mycamera.viewmodel.CameraViewModel +import com.hinnka.mycamera.video.VideoRecordingPath import java.io.File import kotlin.math.roundToInt @@ -183,6 +185,29 @@ private fun openExternalUrl(context: Context, url: String) { runCatching { context.startActivity(intent) } } +private fun formatPersistedTreeLabel(uriString: String?): String { + if (uriString.isNullOrBlank()) return "" + return runCatching { + Uri.decode(Uri.parse(uriString).lastPathSegment ?: uriString) + }.getOrDefault(uriString) +} + +@Composable +private fun PhotoSavePath.displayName(): String { + return when (this) { + PhotoSavePath.DCIM_PHOTON -> stringResource(R.string.settings_storage_path_dcim) + PhotoSavePath.EXTERNAL_TREE -> stringResource(R.string.settings_storage_path_external_tree) + } +} + +@Composable +private fun VideoRecordingPath.displayName(): String { + return when (this) { + VideoRecordingPath.DCIM_PHOTON -> stringResource(R.string.settings_storage_path_dcim) + VideoRecordingPath.EXTERNAL_TREE -> stringResource(R.string.settings_storage_path_external_tree) + } +} + @Composable private fun AiFocusTargetMode.displayName(): String { return when (this) { @@ -267,6 +292,10 @@ fun SettingsScreen( val mirrorFrontCamera by viewModel.mirrorFrontCamera.collectAsState(initial = true) val widgetTheme by viewModel.widgetTheme.collectAsState() val saveLocation by viewModel.saveLocationEnabled.collectAsState(initial = false) + val photoSavePath by viewModel.photoSavePath.collectAsState() + val photoSaveTreeUri by viewModel.photoSaveTreeUri.collectAsState() + val videoRecordingPath by viewModel.videoRecordingPath.collectAsState() + val videoRecordingTreeUri by viewModel.videoRecordingTreeUri.collectAsState() val openAIApiKey by viewModel.openAIApiKey.collectAsState() val openAIUrl by viewModel.openAIUrl.collectAsState() val openAIModel by viewModel.openAIModel.collectAsState() @@ -364,6 +393,26 @@ fun SettingsScreen( val coroutineScope = androidx.compose.runtime.rememberCoroutineScope() val isHdrSettingsSupported = remember { Build.VERSION.SDK_INT >= Build.VERSION_CODES.UPSIDE_DOWN_CAKE && !DeviceUtil.isHarmonyOS } val isHeicExportSupported = remember { HeicExportEncoder.isSupported } + val photoSavePathOptions = PhotoSavePath.entries.toList() + val photoSavePathLabels = photoSavePathOptions.map { it.displayName() } + val photoSaveTreeLabel = remember(photoSaveTreeUri) { + formatPersistedTreeLabel(photoSaveTreeUri) + } + val photoSavePathValue = when { + photoSavePath == PhotoSavePath.EXTERNAL_TREE && photoSaveTreeLabel.isNotBlank() -> + stringResource(R.string.settings_storage_path_external_selected, photoSaveTreeLabel) + else -> photoSavePath.displayName() + } + val videoRecordingPathOptions = VideoRecordingPath.entries.toList() + val videoRecordingPathLabels = videoRecordingPathOptions.map { it.displayName() } + val videoRecordingTreeLabel = remember(videoRecordingTreeUri) { + formatPersistedTreeLabel(videoRecordingTreeUri) + } + val videoRecordingPathValue = when { + videoRecordingPath == VideoRecordingPath.EXTERNAL_TREE && videoRecordingTreeLabel.isNotBlank() -> + stringResource(R.string.settings_storage_path_external_selected, videoRecordingTreeLabel) + else -> videoRecordingPath.displayName() + } val backupLauncher = rememberLauncherForActivityResult( ActivityResultContracts.CreateDocument("application/zip") @@ -444,6 +493,46 @@ fun SettingsScreen( } } + val photoSaveTreeLauncher = rememberLauncherForActivityResult( + ActivityResultContracts.OpenDocumentTree() + ) { uri -> + uri?.let { + val flags = Intent.FLAG_GRANT_READ_URI_PERMISSION or Intent.FLAG_GRANT_WRITE_URI_PERMISSION + val permissionSaved = runCatching { + context.contentResolver.takePersistableUriPermission(it, flags) + }.isSuccess + if (permissionSaved) { + viewModel.setPhotoSavePath(PhotoSavePath.EXTERNAL_TREE, it.toString()) + } else { + android.widget.Toast.makeText( + context, + R.string.settings_storage_path_permission_failed, + android.widget.Toast.LENGTH_SHORT + ).show() + } + } + } + + val videoRecordingTreeLauncher = rememberLauncherForActivityResult( + ActivityResultContracts.OpenDocumentTree() + ) { uri -> + uri?.let { + val flags = Intent.FLAG_GRANT_READ_URI_PERMISSION or Intent.FLAG_GRANT_WRITE_URI_PERMISSION + val permissionSaved = runCatching { + context.contentResolver.takePersistableUriPermission(it, flags) + }.isSuccess + if (permissionSaved) { + viewModel.setVideoRecordingPath(VideoRecordingPath.EXTERNAL_TREE, it.toString()) + } else { + android.widget.Toast.makeText( + context, + R.string.settings_storage_path_permission_failed, + android.widget.Toast.LENGTH_SHORT + ).show() + } + } + } + val locationPermissionLauncher = androidx.activity.compose.rememberLauncherForActivityResult( androidx.activity.result.contract.ActivityResultContracts.RequestMultiplePermissions() ) { permissions -> @@ -978,6 +1067,70 @@ fun SettingsScreen( modifier = Modifier.padding(vertical = 8.dp) ) + DropdownSettingItem( + title = stringResource( + R.string.settings_storage_path_title, + stringResource(R.string.settings_storage_path_photo_title_arg) + ), + description = stringResource( + R.string.settings_storage_path_description, + stringResource(R.string.settings_storage_path_photo_description_arg) + ), + value = photoSavePathValue, + options = photoSavePathLabels, + isLoading = false, + onExpanded = {}, + onOptionSelected = { selected -> + val selectedIndex = photoSavePathLabels.indexOf(selected) + when (photoSavePathOptions.getOrNull(selectedIndex)) { + PhotoSavePath.DCIM_PHOTON -> { + viewModel.setPhotoSavePath(PhotoSavePath.DCIM_PHOTON) + } + PhotoSavePath.EXTERNAL_TREE -> { + photoSaveTreeLauncher.launch(null) + } + null -> Unit + } + } + ) + + HorizontalDivider( + color = Color.White.copy(alpha = 0.1f), + modifier = Modifier.padding(vertical = 8.dp) + ) + + DropdownSettingItem( + title = stringResource( + R.string.settings_storage_path_title, + stringResource(R.string.settings_storage_path_video_title_arg) + ), + description = stringResource( + R.string.settings_storage_path_description, + stringResource(R.string.settings_storage_path_video_description_arg) + ), + value = videoRecordingPathValue, + options = videoRecordingPathLabels, + isLoading = false, + onExpanded = {}, + onOptionSelected = { selected -> + val selectedIndex = videoRecordingPathLabels.indexOf(selected) + when (videoRecordingPathOptions.getOrNull(selectedIndex)) { + VideoRecordingPath.DCIM_PHOTON -> { + viewModel.setVideoRecordingPath(VideoRecordingPath.DCIM_PHOTON) + } + VideoRecordingPath.EXTERNAL_TREE -> { + videoRecordingTreeLauncher.launch(null) + } + null -> Unit + } + } + ) + + HorizontalDivider( + color = Color.White.copy(alpha = 0.1f), + modifier = Modifier.padding(vertical = 8.dp) + ) + SwitchSettingItem( title = stringResource(R.string.settings_auto_save), description = stringResource(R.string.settings_auto_save_description), diff --git a/app/src/main/java/com/hinnka/mycamera/video/VideoMediaStoreWriter.kt b/app/src/main/java/com/hinnka/mycamera/video/VideoMediaStoreWriter.kt index 9ba8f1df..f3125874 100644 --- a/app/src/main/java/com/hinnka/mycamera/video/VideoMediaStoreWriter.kt +++ b/app/src/main/java/com/hinnka/mycamera/video/VideoMediaStoreWriter.kt @@ -3,8 +3,8 @@ package com.hinnka.mycamera.video import android.content.ContentValues import android.content.Context import android.net.Uri -import android.os.Environment import android.os.ParcelFileDescriptor +import android.provider.DocumentsContract import android.provider.MediaStore import com.hinnka.mycamera.utils.PLog import kotlinx.coroutines.Dispatchers @@ -20,18 +20,25 @@ object VideoMediaStoreWriter { data class PendingVideo( val uri: Uri, - val descriptor: ParcelFileDescriptor + val descriptor: ParcelFileDescriptor, + val isMediaStorePending: Boolean ) fun createPendingVideo( context: Context, - dateTakenMs: Long = System.currentTimeMillis() + dateTakenMs: Long = System.currentTimeMillis(), + recordingPath: VideoRecordingPath = VideoRecordingPath.DCIM_PHOTON, + recordingTreeUri: String? = null ): PendingVideo? { val fileName = buildFileName(dateTakenMs) + if (recordingPath == VideoRecordingPath.EXTERNAL_TREE) { + return createTreeVideo(context, recordingTreeUri, fileName) + } + val values = ContentValues().apply { put(MediaStore.MediaColumns.DISPLAY_NAME, fileName) put(MediaStore.MediaColumns.MIME_TYPE, "video/mp4") - put(MediaStore.MediaColumns.RELATIVE_PATH, Environment.DIRECTORY_DCIM + "/PhotonCamera") + put(MediaStore.MediaColumns.RELATIVE_PATH, recordingPath.relativePath) put(MediaStore.MediaColumns.DATE_ADDED, dateTakenMs / 1000) put(MediaStore.MediaColumns.DATE_MODIFIED, dateTakenMs / 1000) put(MediaStore.MediaColumns.IS_PENDING, 1) @@ -42,7 +49,7 @@ object VideoMediaStoreWriter { return try { val descriptor = context.contentResolver.openFileDescriptor(uri, "rw") ?: throw IllegalStateException("Cannot open output descriptor") - PendingVideo(uri, descriptor) + PendingVideo(uri, descriptor, isMediaStorePending = true) } catch (e: Exception) { PLog.e(TAG, "Failed to create pending video output", e) context.contentResolver.delete(uri, null, null) @@ -50,23 +57,58 @@ object VideoMediaStoreWriter { } } - fun publishPendingVideo(context: Context, uri: Uri): Uri? { + private fun createTreeVideo( + context: Context, + treeUriString: String?, + fileName: String + ): PendingVideo? { + if (treeUriString.isNullOrBlank()) { + PLog.e(TAG, "External video output requested without a tree URI") + return null + } + return try { + val treeUri = Uri.parse(treeUriString) + val treeDocumentId = DocumentsContract.getTreeDocumentId(treeUri) + val parentUri = DocumentsContract.buildDocumentUriUsingTree(treeUri, treeDocumentId) + val uri = DocumentsContract.createDocument( + context.contentResolver, + parentUri, + "video/mp4", + fileName + ) ?: throw IllegalStateException("Cannot create output document") + val descriptor = context.contentResolver.openFileDescriptor(uri, "rw") + ?: throw IllegalStateException("Cannot open output descriptor") + PendingVideo(uri, descriptor, isMediaStorePending = false) + } catch (e: Exception) { + PLog.e(TAG, "Failed to create external video output", e) + null + } + } + + fun publishPendingVideo(context: Context, pendingVideo: PendingVideo): Uri? { + if (!pendingVideo.isMediaStorePending) { + return pendingVideo.uri + } return try { val values = ContentValues().apply { put(MediaStore.MediaColumns.IS_PENDING, 0) put(MediaStore.MediaColumns.DATE_MODIFIED, System.currentTimeMillis() / 1000) } - context.contentResolver.update(uri, values, null, null) - uri + context.contentResolver.update(pendingVideo.uri, values, null, null) + pendingVideo.uri } catch (e: Exception) { PLog.e(TAG, "Failed to publish pending video", e) null } } - fun discardPendingVideo(context: Context, uri: Uri) { + fun discardPendingVideo(context: Context, pendingVideo: PendingVideo) { try { - context.contentResolver.delete(uri, null, null) + if (pendingVideo.isMediaStorePending) { + context.contentResolver.delete(pendingVideo.uri, null, null) + } else { + DocumentsContract.deleteDocument(context.contentResolver, pendingVideo.uri) + } } catch (e: Exception) { PLog.w(TAG, "Failed to discard pending video: ${e.message}") } @@ -75,17 +117,38 @@ object VideoMediaStoreWriter { suspend fun publishVideo( context: Context, sourceFile: File, - dateTakenMs: Long = System.currentTimeMillis() + dateTakenMs: Long = System.currentTimeMillis(), + recordingPath: VideoRecordingPath = VideoRecordingPath.DCIM_PHOTON, + recordingTreeUri: String? = null ): Uri? = withContext(Dispatchers.IO) { if (!sourceFile.exists() || sourceFile.length() <= 0L) { return@withContext null } val fileName = buildFileName(dateTakenMs) + if (recordingPath == VideoRecordingPath.EXTERNAL_TREE) { + val output = createTreeVideo(context, recordingTreeUri, fileName) + ?: return@withContext null + return@withContext try { + output.descriptor.use { descriptor -> + ParcelFileDescriptor.AutoCloseOutputStream(descriptor).use { outputStream -> + sourceFile.inputStream().use { input -> + input.copyTo(outputStream) + } + } + } + output.uri + } catch (e: Exception) { + PLog.e(TAG, "Failed to publish external video", e) + discardPendingVideo(context, output) + null + } + } + val values = ContentValues().apply { put(MediaStore.MediaColumns.DISPLAY_NAME, fileName) put(MediaStore.MediaColumns.MIME_TYPE, "video/mp4") - put(MediaStore.MediaColumns.RELATIVE_PATH, Environment.DIRECTORY_DCIM + "/PhotonCamera") + put(MediaStore.MediaColumns.RELATIVE_PATH, recordingPath.relativePath) put(MediaStore.MediaColumns.DATE_ADDED, dateTakenMs / 1000) put(MediaStore.MediaColumns.DATE_MODIFIED, dateTakenMs / 1000) } diff --git a/app/src/main/java/com/hinnka/mycamera/video/VideoRecorder.kt b/app/src/main/java/com/hinnka/mycamera/video/VideoRecorder.kt index 27810298..cb471069 100644 --- a/app/src/main/java/com/hinnka/mycamera/video/VideoRecorder.kt +++ b/app/src/main/java/com/hinnka/mycamera/video/VideoRecorder.kt @@ -105,6 +105,8 @@ class VideoRecorder( private var requestedCodecMime: String = MediaFormat.MIMETYPE_VIDEO_AVC private var requestedOrientationHintDegrees: Int = 0 private var requestedFlipEncodedFrame: Boolean = false + private var requestedRecordingPath: VideoRecordingPath = VideoRecordingPath.DCIM_PHOTON + private var requestedRecordingTreeUri: String? = null private var preferredAudioInputId: String = VIDEO_AUDIO_INPUT_AUTO private var requestedColorConfig: VideoEncoderColorRequest = VideoEncoderColorRequest() private var preparedEncoderColorConfig: VideoEncoderColorConfig? = null @@ -159,6 +161,8 @@ class VideoRecorder( colorConfig: VideoEncoderColorRequest = VideoEncoderColorRequest(), orientationHintDegrees: Int = 0, flipEncodedFrame: Boolean = false, + recordingPath: VideoRecordingPath = VideoRecordingPath.DCIM_PHOTON, + recordingTreeUri: String? = null, onError: ((String) -> Unit)? = null, onFinished: ((Uri?) -> Unit)? = null ): Boolean { @@ -171,6 +175,8 @@ class VideoRecorder( requestedColorConfig = colorConfig requestedOrientationHintDegrees = normalizeOrientationHint(orientationHintDegrees) requestedFlipEncodedFrame = flipEncodedFrame + requestedRecordingPath = recordingPath + requestedRecordingTreeUri = recordingTreeUri?.takeIf { it.isNotBlank() } outputDateTakenMs = System.currentTimeMillis() this.errorCallback = onError this.finishCallback = onFinished @@ -208,7 +214,8 @@ class VideoRecorder( PLog.d( TAG, "Video recording prepared: ${requestedSize.width}x${requestedSize.height} @ " + - "${requestedFps}fps, orientationHint=$requestedOrientationHintDegrees" + "${requestedFps}fps, orientationHint=$requestedOrientationHintDegrees, " + + "path=${requestedRecordingPath.name}, uri=${requestedRecordingTreeUri?.take(48)}" ) return true } @@ -518,7 +525,9 @@ class VideoRecorder( private fun createMuxer() { val output = VideoMediaStoreWriter.createPendingVideo( context = context, - dateTakenMs = outputDateTakenMs + dateTakenMs = outputDateTakenMs, + recordingPath = requestedRecordingPath, + recordingTreeUri = requestedRecordingTreeUri ) ?: throw IllegalStateException("Failed to create video output") pendingVideoOutput = output muxer = MediaMuxer(output.descriptor.fileDescriptor, MediaMuxer.OutputFormat.MUXER_OUTPUT_MPEG_4).apply { @@ -1007,13 +1016,13 @@ class VideoRecorder( pendingVideoOutput = null if (!muxerStopSucceeded) { - VideoMediaStoreWriter.discardPendingVideo(context, output.uri) + VideoMediaStoreWriter.discardPendingVideo(context, output) return null } - val uri = VideoMediaStoreWriter.publishPendingVideo(context, output.uri) + val uri = VideoMediaStoreWriter.publishPendingVideo(context, output) if (uri == null) { - VideoMediaStoreWriter.discardPendingVideo(context, output.uri) + VideoMediaStoreWriter.discardPendingVideo(context, output) } return uri } @@ -1080,7 +1089,7 @@ class VideoRecorder( output.descriptor.close() } catch (_: Exception) { } - VideoMediaStoreWriter.discardPendingVideo(context, output.uri) + VideoMediaStoreWriter.discardPendingVideo(context, output) } pendingVideoOutput = null isRecording = false @@ -1153,7 +1162,7 @@ class VideoRecorder( output.descriptor.close() } catch (_: Exception) { } - VideoMediaStoreWriter.discardPendingVideo(context, output.uri) + VideoMediaStoreWriter.discardPendingVideo(context, output) } pendingVideoOutput = null try { diff --git a/app/src/main/java/com/hinnka/mycamera/video/VideoTypes.kt b/app/src/main/java/com/hinnka/mycamera/video/VideoTypes.kt index 1dbb865b..8c4c2ef9 100644 --- a/app/src/main/java/com/hinnka/mycamera/video/VideoTypes.kt +++ b/app/src/main/java/com/hinnka/mycamera/video/VideoTypes.kt @@ -1,6 +1,7 @@ package com.hinnka.mycamera.video import android.graphics.Rect +import android.os.Environment import android.util.Size import com.hinnka.mycamera.raw.ColorSpace import com.hinnka.mycamera.color.TransferCurve @@ -82,6 +83,17 @@ enum class VideoCodec(val displayName: String, val mimeType: String) { H265("H.265", "video/hevc"); } +enum class VideoRecordingPath(val relativePath: String?) { + DCIM_PHOTON(Environment.DIRECTORY_DCIM + "/PhotonCamera"), + EXTERNAL_TREE(null); + + companion object { + fun fromPersistedName(name: String?): VideoRecordingPath { + return entries.firstOrNull { it.name == name } ?: DCIM_PHOTON + } + } +} + enum class VideoLogProfile( val displayName: String, val logCurve: TransferCurve, @@ -107,6 +119,8 @@ data class VideoConfig( val bitrate: VideoBitratePreset = VideoBitratePreset.P1, val codec: VideoCodec = VideoCodec.H264, val audioInputId: String = VIDEO_AUDIO_INPUT_AUTO, + val recordingPath: VideoRecordingPath = VideoRecordingPath.DCIM_PHOTON, + val recordingTreeUri: String? = null, val stabilizationMode: VideoStabilizationMode = VideoStabilizationMode.OIS, val torchEnabled: Boolean = false ) { diff --git a/app/src/main/java/com/hinnka/mycamera/viewmodel/CameraViewModel.kt b/app/src/main/java/com/hinnka/mycamera/viewmodel/CameraViewModel.kt index e3a55cf6..6a26c61f 100644 --- a/app/src/main/java/com/hinnka/mycamera/viewmodel/CameraViewModel.kt +++ b/app/src/main/java/com/hinnka/mycamera/viewmodel/CameraViewModel.kt @@ -29,6 +29,7 @@ import com.hinnka.mycamera.frame.FrameInfo import com.hinnka.mycamera.frame.FramePreviewFactory import com.hinnka.mycamera.gallery.GalleryManager import com.hinnka.mycamera.gallery.MediaMetadata +import com.hinnka.mycamera.gallery.PhotoSavePath import com.hinnka.mycamera.lut.BaselineColorCorrectionTarget import com.hinnka.mycamera.lut.BakedLutExporter import com.hinnka.mycamera.lut.LutConfig @@ -63,6 +64,7 @@ import com.hinnka.mycamera.video.VideoAspectRatio import com.hinnka.mycamera.video.VideoBitratePreset import com.hinnka.mycamera.video.VideoFpsPreset import com.hinnka.mycamera.video.VideoLogProfile +import com.hinnka.mycamera.video.VideoRecordingPath import com.hinnka.mycamera.video.VideoResolutionPreset import kotlinx.coroutines.* import kotlinx.coroutines.flow.first @@ -784,6 +786,12 @@ class CameraViewModel(application: Application) : AndroidViewModel(application) userPreferencesRepository.userPreferences.map { it.volumeKeyAction } .stateIn(viewModelScope, SharingStarted.Eagerly, initialValue = VolumeKeyAction.NONE) val autoSaveAfterCapture: Flow = userPreferencesRepository.userPreferences.map { it.autoSaveAfterCapture } + val photoSavePath: StateFlow = userPreferencesRepository.userPreferences + .map { it.photoSavePath } + .stateIn(viewModelScope, SharingStarted.Eagerly, PhotoSavePath.DCIM_PHOTON) + val photoSaveTreeUri: StateFlow = userPreferencesRepository.userPreferences + .map { it.photoSaveTreeUri } + .stateIn(viewModelScope, SharingStarted.Eagerly, null) val topSheetAspectRatios: StateFlow> = userPreferencesRepository.userPreferences .map { it.topSheetAspectRatios } .stateIn(viewModelScope, SharingStarted.Eagerly, AspectRatio.defaultTopSheetRatios) @@ -1000,6 +1008,12 @@ class CameraViewModel(application: Application) : AndroidViewModel(application) val videoCodec: StateFlow = userPreferencesRepository.userPreferences .map { it.videoCodec } .stateIn(viewModelScope, SharingStarted.Eagerly, com.hinnka.mycamera.video.VideoCodec.H264) + val videoRecordingPath: StateFlow = userPreferencesRepository.userPreferences + .map { it.videoRecordingPath } + .stateIn(viewModelScope, SharingStarted.Eagerly, VideoRecordingPath.DCIM_PHOTON) + val videoRecordingTreeUri: StateFlow = userPreferencesRepository.userPreferences + .map { it.videoRecordingTreeUri } + .stateIn(viewModelScope, SharingStarted.Eagerly, null) val videoAudioInputOptions: StateFlow> = videoAudioInputManager.availableInputs val phantomButtonHidden: StateFlow = userPreferencesRepository.userPreferences @@ -1239,6 +1253,7 @@ class CameraViewModel(application: Application) : AndroidViewModel(application) cameraController.setVideoLogProfile(it.videoLogProfile) cameraController.setVideoBitrate(it.videoBitrate) cameraController.setVideoAudioInputId(it.videoAudioInputId) + cameraController.setVideoRecordingPath(it.videoRecordingPath, it.videoRecordingTreeUri) cameraController.setVideoStabilizationMode(it.videoStabilizationMode) cameraController.setVideoTorchEnabled(it.videoTorchEnabled) cameraController.setVideoCodec(it.videoCodec) @@ -1369,6 +1384,7 @@ class CameraViewModel(application: Application) : AndroidViewModel(application) cameraController.setVideoLogProfile(prefs.videoLogProfile) cameraController.setVideoBitrate(prefs.videoBitrate) cameraController.setVideoAudioInputId(prefs.videoAudioInputId) + cameraController.setVideoRecordingPath(prefs.videoRecordingPath, prefs.videoRecordingTreeUri) cameraController.setVideoStabilizationMode(prefs.videoStabilizationMode) cameraController.setVideoTorchEnabled(prefs.videoTorchEnabled) cameraController.setVideoCodec(prefs.videoCodec) @@ -2427,6 +2443,19 @@ class CameraViewModel(application: Application) : AndroidViewModel(application) } } + fun setVideoRecordingPath(recordingPath: VideoRecordingPath, treeUri: String? = null) { + cameraController.setVideoRecordingPath(recordingPath, treeUri) + viewModelScope.launch { + userPreferencesRepository.saveVideoRecordingPath(recordingPath, treeUri) + } + } + + fun setPhotoSavePath(savePath: PhotoSavePath, treeUri: String? = null) { + viewModelScope.launch { + userPreferencesRepository.savePhotoSavePath(savePath, treeUri) + } + } + fun cycleVideoStabilizationMode() { val currentMode = state.value.videoConfig.stabilizationMode val availableModes = state.value.videoCapabilities.availableStabilizationModes diff --git a/app/src/main/res/values-zh-rCN/strings.xml b/app/src/main/res/values-zh-rCN/strings.xml index 3eb8914b..4797d293 100644 --- a/app/src/main/res/values-zh-rCN/strings.xml +++ b/app/src/main/res/values-zh-rCN/strings.xml @@ -229,6 +229,16 @@ 快门/拍摄 曝光补偿 焦距切换 + 照片 + 照片 + 视频 + 视频 + %1$s保存路径 + 选择%1$s的保存位置 + 默认(DCIM/PhotonCamera) + 文件夹... + 文件夹:%1$s + 无法保存文件夹权限 拍摄后自动保存 拍摄后自动保存照片,否则需要手动确认 保存地理位置 diff --git a/app/src/main/res/values-zh-rHK/strings.xml b/app/src/main/res/values-zh-rHK/strings.xml index 4792f046..67e31328 100644 --- a/app/src/main/res/values-zh-rHK/strings.xml +++ b/app/src/main/res/values-zh-rHK/strings.xml @@ -142,6 +142,16 @@ 快門/拍攝 曝光補償 焦距切換 + 照片 + 照片 + 視頻 + 視頻 + %1$s儲存路徑 + 選擇%1$s的儲存位置 + 預設(DCIM/PhotonCamera) + 資料夾... + 資料夾:%1$s + 無法儲存資料夾權限 拍攝後自動儲存 拍攝後自動儲存相片,否則需要手動確認 儲存地理位置 diff --git a/app/src/main/res/values/strings.xml b/app/src/main/res/values/strings.xml index ed833d48..74c52774 100644 --- a/app/src/main/res/values/strings.xml +++ b/app/src/main/res/values/strings.xml @@ -231,6 +231,16 @@ Shutter Exposure Comp. Focal Switch + Photo + photos + Video + videos + %1$s Save Path + Choose where to save %1$s + Default (DCIM/PhotonCamera) + Folder... + Folder: %1$s + Failed to save folder permission Auto Save Automatically save photos after capture Save Location