feat: support applying effects to motion photo embedded videos

This commit is contained in:
Hinnka committed 2026-05-30 16:26:14 +08:00
1 parent b725297dfe
commit f206af55cf
12 files changed
+206 -8

No files matched your search

@@ -23,6 +23,7 @@ import com.hinnka.mycamera.hdr.SourceKind
import com.hinnka.mycamera.hdr.UltraHdrWriter
import com.hinnka.mycamera.hdr.UnifiedGainmapProducer
import com.hinnka.mycamera.livephoto.MotionPhotoWriter
import com.hinnka.mycamera.lut.applyEffectsToVideoFile
import com.hinnka.mycamera.model.SafeImage
import com.hinnka.mycamera.processor.MultiFrameStacker
import com.hinnka.mycamera.raw.RawDemosaicProcessor
@@ -518,6 +519,7 @@ object GalleryManager {
detailHdrBuildJobs[photoId] = job
}
@androidx.annotation.OptIn(androidx.media3.common.util.UnstableApi::class)
suspend fun exportPhoto(
context: Context,
id: String,
@@ -651,6 +653,7 @@ object GalleryManager {
if (isLivePhoto) {
val tempMotionPhotoFile = File(context.cacheDir, "temp_motion_${System.nanoTime()}.jpg")
var tempProcessedVideoFile: File? = null
try {
PLog.d(
TAG,
@@ -659,9 +662,40 @@ object GalleryManager {
// 重新从磁盘加载最新元数据,以获取可能刚写回的 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")
}
}
val success = MotionPhotoWriter.write(
tempExportFile.absolutePath,
videoFile.absolutePath,
finalVideoPath,
tempMotionPhotoFile.absolutePath,
latestMetadata.presentationTimestampUs ?: 0L,
context
@@ -715,6 +749,7 @@ object GalleryManager {
}
} finally {
tempMotionPhotoFile.delete()
tempProcessedVideoFile?.delete()
}
} else {
// 3b. Normal Export: Copy Temp File (with EXIF) to MediaStore
@@ -104,6 +104,7 @@ data class MediaMetadata(
val rawBlackLevelMode: String? = null,
val rawCustomBlackLevel: Float? = null,
val cameraId: String? = null,
val applyEffectsToVideo: Boolean = false,
) {
/**
* 将元数据转换为 CaptureInfo,用于写入 EXIF
@@ -334,6 +335,7 @@ data class MediaMetadata(
multipleExposureFrameCount = if (obj.isNull("multipleExposureFrameCount")) null else obj.optInt("multipleExposureFrameCount"),
hasAiDenoisedBase = obj.optBoolean("hasAiDenoisedBase", false),
aiDenoiseStrength = if (obj.isNull("aiDenoiseStrength")) null else obj.optDouble("aiDenoiseStrength").toFloat(),
applyEffectsToVideo = obj.optBoolean("applyEffectsToVideo", false),
)
} catch (e: Exception) {
PLog.e(TAG, "Failed to parse JSON", e)
@@ -7,7 +7,7 @@ import androidx.room.RoomDatabase
@Database(
entities = [GalleryMediaEntity::class],
version = 2,
version = 3,
exportSchema = false
)
@androidx.room.TypeConverters(GalleryConverters::class)
@@ -24,6 +24,12 @@ abstract class GalleryDatabase : RoomDatabase() {
}
}
private val MIGRATION_2_3 = object : androidx.room.migration.Migration(2, 3) {
override fun migrate(db: androidx.sqlite.db.SupportSQLiteDatabase) {
db.execSQL("ALTER TABLE gallery_media ADD COLUMN applyEffectsToVideo INTEGER NOT NULL DEFAULT 0")
}
}
fun getInstance(context: Context): GalleryDatabase {
return INSTANCE ?: synchronized(this) {
INSTANCE ?: Room.databaseBuilder(
@@ -31,7 +37,7 @@ abstract class GalleryDatabase : RoomDatabase() {
GalleryDatabase::class.java,
"gallery_media.db"
)
.addMigrations(MIGRATION_1_2)
.addMigrations(MIGRATION_1_2, MIGRATION_2_3)
.build()
.also { INSTANCE = it }
}
@@ -106,5 +106,6 @@ data class GalleryMediaEntity(
val rawBlackLevelMode: String?,
val rawCustomBlackLevel: Float?,
val rawDROEnabled: Boolean?,
val cameraId: String?
val cameraId: String?,
val applyEffectsToVideo: Boolean
)
@@ -260,7 +260,8 @@ object GalleryMediaStore {
rawBlackLevelMode = metadata.rawBlackLevelMode,
rawCustomBlackLevel = metadata.rawCustomBlackLevel,
rawDROEnabled = false,
cameraId = metadata.cameraId
cameraId = metadata.cameraId,
applyEffectsToVideo = metadata.applyEffectsToVideo
)
}
@@ -383,9 +384,9 @@ object GalleryMediaStore {
multipleExposureFrameCount = multipleExposureFrameCount,
hasAiDenoisedBase = hasAiDenoisedBase,
aiDenoiseStrength = aiDenoiseStrength,
rawBlackLevelMode = rawBlackLevelMode,
rawCustomBlackLevel = rawCustomBlackLevel,
cameraId = cameraId
cameraId = cameraId,
applyEffectsToVideo = applyEffectsToVideo
)
}
@@ -121,6 +121,76 @@ suspend fun exportVideoWithEffects(
}
}
/**
* Applies LUT and recipe effects to a video and writes the result directly to a local file.
*
* @param context Application context
* @param inputUri Source video Uri
* @param outputFile Target file to write the processed video to
* @param lutConfig LUT configuration to apply
* @param recipeParams Recipe parameters to apply
* @return True if successful, false otherwise
*/
@UnstableApi
suspend fun applyEffectsToVideoFile(
context: Context,
inputUri: Uri,
outputFile: File,
lutConfig: LutConfig?,
recipeParams: ColorRecipeParams?,
): Boolean = withContext(Dispatchers.Main) {
val originalMime = detectVideoMime(context, inputUri)
PLog.d(TAG, "applyEffectsToVideoFile: Input video MIME: $originalMime")
outputFile.parentFile?.mkdirs()
try {
val effect = VideoLutEffect(lutConfig, recipeParams)
val mediaItem = MediaItem.fromUri(inputUri)
val editedMediaItem = EditedMediaItem.Builder(mediaItem)
.setEffects(
Effects(
/* audioProcessors= */ emptyList(),
/* videoEffects= */ listOf(effect)
)
)
.build()
val transformer = Transformer.Builder(context)
.also { builder ->
val targetMime = when {
originalMime == MimeTypes.VIDEO_H265 -> MimeTypes.VIDEO_H265
else -> MimeTypes.VIDEO_H264
}
PLog.d(TAG, "applyEffectsToVideoFile: Target video MIME: $targetMime")
builder.setVideoMimeType(targetMime)
}
.build()
val exportResult = runTransformer(
transformer = transformer,
editedMediaItem = editedMediaItem,
outputPath = outputFile.absolutePath,
onProgress = null
)
if (exportResult == null) {
PLog.e(TAG, "applyEffectsToVideoFile: Transformer returned null result")
false
} else {
PLog.d(TAG, "applyEffectsToVideoFile: Succeeded, size: ${outputFile.length()} bytes")
true
}
} catch (e: CancellationException) {
PLog.d(TAG, "applyEffectsToVideoFile: Cancelled")
throw e
} catch (e: Exception) {
PLog.e(TAG, "applyEffectsToVideoFile: Failed", e)
false
}
}
/**
* 在协程中运行 Transformer,通过 listener 回调转为 suspend 函数。
* 同时轮询进度并上报给 [onProgress]。
@@ -1624,6 +1624,48 @@ fun MotionPhotoPlayer(
if (!photo.isMotionPhoto) return
val context = LocalContext.current
val contentRepository = remember {
com.hinnka.mycamera.data.ContentRepository.getInstance(context)
}
var lutConfig by remember { mutableStateOf<com.hinnka.mycamera.lut.LutConfig?>(null) }
var recipeParams by remember { mutableStateOf<com.hinnka.mycamera.model.ColorRecipeParams?>(null) }
val refreshKey = viewModel.photoRefreshKeys[photo.id] ?: 0L
LaunchedEffect(photo.id, refreshKey) {
withContext(Dispatchers.IO) {
PLog.d("MotionPhotoPlayer", "Loading video metadata from DB.")
val metadata = com.hinnka.mycamera.gallery.GalleryManager.loadMetadata(context, photo.id) ?: photo.metadata
val applyEffects = metadata?.applyEffectsToVideo == true
val lutId = if (applyEffects) metadata?.lutId else null
val params = if (applyEffects) metadata?.colorRecipeParams else null
PLog.d("MotionPhotoPlayer", "Metadata loaded. applyEffects: $applyEffects, lutId: $lutId, recipeEnabled: ${params != null}")
val config = if (lutId != null) {
contentRepository.lutManager.loadLut(lutId)
} else {
null
}
withContext(Dispatchers.Main) {
lutConfig = config
recipeParams = params
}
}
}
// Maintain the video LUT effect
val videoLutEffect = remember {
PLog.d("MotionPhotoPlayer", "Instantiating new VideoLutEffect.")
VideoLutEffect(lutConfig, recipeParams)
}
// Update effect parameters dynamically on the GL pipeline without reconstruction
LaunchedEffect(lutConfig, recipeParams) {
PLog.d("MotionPhotoPlayer", "Updating VideoLutEffect params. lut: ${lutConfig?.title}, recipe: ${recipeParams != null}")
videoLutEffect.update(lutConfig, recipeParams)
}
var isReadyToShow by remember(photo.id, isPlaying) { mutableStateOf(false) }
val exoPlayer = remember(photo.id, isPlaying) {
@@ -1634,6 +1676,7 @@ fun MotionPhotoPlayer(
ExoPlayer.Builder(context).build().apply {
setMediaItem(MediaItem.fromUri(Uri.fromFile(videoFile)))
repeatMode = Player.REPEAT_MODE_ONE
setVideoEffects(listOf(videoLutEffect))
addListener(object : Player.Listener {
override fun onRenderedFirstFrame() {
isReadyToShow = true
@@ -841,6 +841,32 @@ fun GalleryEditScreen(
val currentLut = availableLuts.find { it.id == editLutId }
val lutTitle = currentLut?.getName() ?: ""
if (currentPhoto.isMotionPhoto) {
val applyEffectsToVideo by viewModel.editApplyEffectsToVideo.collectAsState()
Row(
modifier = Modifier
.fillMaxWidth()
.padding(top = 12.dp, bottom = 4.dp),
verticalAlignment = Alignment.CenterVertically
) {
Checkbox(
checked = applyEffectsToVideo,
onCheckedChange = { viewModel.setApplyEffectsToVideo(it) },
colors = CheckboxDefaults.colors(
checkedColor = AccentOrange,
uncheckedColor = Color.White.copy(alpha = 0.6f),
checkmarkColor = Color.Black
)
)
Spacer(modifier = Modifier.width(8.dp))
Text(
text = stringResource(R.string.edit_embedded_video_simultaneously),
color = Color.White,
fontSize = 14.sp
)
}
}
Spacer(modifier = Modifier.height(16.dp))
Row(
modifier = Modifier.fillMaxWidth(),
@@ -205,6 +205,13 @@ class GalleryViewModel(application: Application) : AndroidViewModel(application)
var editLutId = MutableStateFlow<String?>(null)
private set
var editApplyEffectsToVideo = MutableStateFlow(false)
private set
fun setApplyEffectsToVideo(apply: Boolean) {
editApplyEffectsToVideo.value = apply
}
@OptIn(ExperimentalCoroutinesApi::class)
var editLutRecipeParams = editLutId.flatMapLatest { id ->
if (id == null) {
@@ -1588,6 +1595,7 @@ class GalleryViewModel(application: Application) : AndroidViewModel(application)
editLutId.value = metadata.lutId
editFrameId.value = metadata.frameId
editPhotoRecipeParams.value = metadata.colorRecipeParams
editApplyEffectsToVideo.value = metadata.applyEffectsToVideo
if (!targetPhoto.isVideo) {
editRawDcpId.value = metadata.rawDcpId
@@ -1614,6 +1622,7 @@ class GalleryViewModel(application: Application) : AndroidViewModel(application)
} ?: run {
editLutId.value = null
editFrameId.value = null
editApplyEffectsToVideo.value = false
if (!targetPhoto.isVideo) {
// 这里一般是本 App 预览或拍摄进入,保持跟随全局
@@ -1654,6 +1663,7 @@ class GalleryViewModel(application: Application) : AndroidViewModel(application)
editLutConfig = null
editFrameId.value = null
editPhotoRecipeParams.value = null
editApplyEffectsToVideo.value = false
editCropRect.value = null
editCropAspectOption.value = CropAspectOption.Free
editRawDenoise.value = 0.2f
@@ -2390,7 +2400,8 @@ class GalleryViewModel(application: Application) : AndroidViewModel(application)
computationalAperture = editComputationalAperture.value,
focusPointX = editFocusPointX.value,
focusPointY = editFocusPointY.value,
postCropRegion = finalCropRegion
postCropRegion = finalCropRegion,
applyEffectsToVideo = editApplyEffectsToVideo.value
)
}
@@ -955,4 +955,5 @@
<string name="puzzle_background">背景颜色</string>
<string name="puzzle_background_white">纯白</string>
<string name="puzzle_background_black">纯黑</string>
<string name="edit_embedded_video_simultaneously">同时编辑内嵌视频</string>
</resources>
@@ -646,4 +646,5 @@
<string name="puzzle_background">背景顏色</string>
<string name="puzzle_background_white">純白</string>
<string name="puzzle_background_black">純黑</string>
<string name="edit_embedded_video_simultaneously">同時編輯內嵌視頻</string>
</resources>
+1
View File
@@ -955,4 +955,5 @@
<string name="puzzle_background">Background Color</string>
<string name="puzzle_background_white">White</string>
<string name="puzzle_background_black">Black</string>
<string name="edit_embedded_video_simultaneously">Simultaneously edit embedded video</string>
</resources>