photos: add built-in video editor with trim, crop/rotate, mute, and color filters
- Commit
6e91ae87c94d754ae36c8f3a9a34a19a24842dfd- Author
- Vayun Mathur <[email protected]>
- When
- 2026-08-11 20:22 UTC (3 months ago)
- Parents
d388871
Diff
gradle/libs.versions.toml
diff --git a/gradle/libs.versions.toml b/gradle/libs.versions.tomlindex d4648d9147..6fbce2652a 100644--- a/gradle/libs.versions.toml+++ b/gradle/libs.versions.toml@@ -190,6 +190,9 @@ androidx-media3-exoplayer = { module = "androidx.media3:media3-exoplayer", versi androidx-media3-exoplayer-dash = { module = "androidx.media3:media3-exoplayer-dash", version.ref = "media3Exoplayer" } androidx-media3-session = { module = "androidx.media3:media3-session", version.ref = "media3Exoplayer" } androidx-media3-ui-compose-material3 = { module = "androidx.media3:media3-ui-compose-material3", version.ref = "media3Exoplayer" }+androidx-media3-transformer = { module = "androidx.media3:media3-transformer", version.ref = "media3Exoplayer" }+androidx-media3-effect = { module = "androidx.media3:media3-effect", version.ref = "media3Exoplayer" }+androidx-media3-common = { module = "androidx.media3:media3-common", version.ref = "media3Exoplayer" } # AndroidX – CameraX & images androidx-camera-core = { group = "androidx.camera", name = "camera-core", version.ref = "camerax" }
library/ui/src/main/java/com/vayunmathur/library/ui/Icons.kt
diff --git a/library/ui/src/main/java/com/vayunmathur/library/ui/Icons.kt b/library/ui/src/main/java/com/vayunmathur/library/ui/Icons.ktindex 50a482eedb..0fbb28cc5b 100644--- a/library/ui/src/main/java/com/vayunmathur/library/ui/Icons.kt+++ b/library/ui/src/main/java/com/vayunmathur/library/ui/Icons.kt@@ -119,6 +119,11 @@ import androidx.compose.material.icons.filled.ChevronRight import androidx.compose.material.icons.filled.Close import androidx.compose.material.icons.filled.Cloud import androidx.compose.material.icons.filled.ContentCopy+import androidx.compose.material.icons.filled.ContentCut+import androidx.compose.material.icons.filled.Flip+import androidx.compose.material.icons.filled.Tune+import androidx.compose.material.icons.filled.VolumeOff+import androidx.compose.material.icons.filled.VolumeUp import androidx.compose.material.icons.filled.ContentPaste import androidx.compose.material.icons.filled.Contrast import androidx.compose.material.icons.filled.Crop@@ -324,6 +329,26 @@ fun IconRotateLeft(modifier: Modifier = Modifier, tint: Color = LocalContentColo fun IconRotateRight(modifier: Modifier = Modifier, tint: Color = LocalContentColor.current) = AppIcon(Icons.AutoMirrored.Filled.RotateRight, "Rotate Right", modifier, tint) +@Composable+fun IconContentCut(modifier: Modifier = Modifier, tint: Color = LocalContentColor.current) =+ AppIcon(Icons.Filled.ContentCut, "Trim", modifier, tint)++@Composable+fun IconFlip(modifier: Modifier = Modifier, tint: Color = LocalContentColor.current) =+ AppIcon(Icons.Filled.Flip, "Flip", modifier, tint)++@Composable+fun IconTune(modifier: Modifier = Modifier, tint: Color = LocalContentColor.current) =+ AppIcon(Icons.Filled.Tune, "Adjustments", modifier, tint)++@Composable+fun IconVolumeOff(modifier: Modifier = Modifier, tint: Color = LocalContentColor.current) =+ AppIcon(Icons.Filled.VolumeOff, "Mute", modifier, tint)++@Composable+fun IconVolumeUp(modifier: Modifier = Modifier, tint: Color = LocalContentColor.current) =+ AppIcon(Icons.Filled.VolumeUp, "Audio on", modifier, tint)+ @Composable fun IconNavigation(navBack: () -> Unit) { IconButton({ navBack() }) {
library/ui/src/main/java/com/vayunmathur/library/ui/MaterialComponents.kt
diff --git a/library/ui/src/main/java/com/vayunmathur/library/ui/MaterialComponents.kt b/library/ui/src/main/java/com/vayunmathur/library/ui/MaterialComponents.ktindex 24cda84d03..28c785784b 100644--- a/library/ui/src/main/java/com/vayunmathur/library/ui/MaterialComponents.kt+++ b/library/ui/src/main/java/com/vayunmathur/library/ui/MaterialComponents.kt@@ -331,6 +331,21 @@ fun Slider( valueRange = valueRange, steps = steps, onValueChangeFinished = onValueChangeFinished, colors = colors, ) +@Composable+fun RangeSlider(+ value: ClosedFloatingPointRange<Float>,+ onValueChange: (ClosedFloatingPointRange<Float>) -> Unit,+ modifier: Modifier = Modifier,+ enabled: Boolean = true,+ valueRange: ClosedFloatingPointRange<Float> = 0f..1f,+ steps: Int = 0,+ onValueChangeFinished: (() -> Unit)? = null,+ colors: SliderColors = SliderDefaults.colors(),+) = androidx.compose.material3.RangeSlider(+ value = value, onValueChange = onValueChange, modifier = modifier, enabled = enabled,+ valueRange = valueRange, steps = steps, onValueChangeFinished = onValueChangeFinished, colors = colors,+)+ // --- Progress --- @Composable fun CircularProgressIndicator(
photos/build.gradle.kts
diff --git a/photos/build.gradle.kts b/photos/build.gradle.ktsindex a30e216262..e7564d28b5 100644--- a/photos/build.gradle.kts+++ b/photos/build.gradle.kts@@ -54,6 +54,9 @@ dependencies { implementation(libs.androidx.media3.exoplayer) implementation(libs.androidx.media3.ui.compose.material3)+ implementation(libs.androidx.media3.transformer)+ implementation(libs.androidx.media3.effect)+ implementation(libs.androidx.media3.common) implementation(project(":library:widgets"))
photos/src/main/AndroidManifest.xml
diff --git a/photos/src/main/AndroidManifest.xml b/photos/src/main/AndroidManifest.xmlindex 7ae695320d..2e8cf1f9b7 100644--- a/photos/src/main/AndroidManifest.xml+++ b/photos/src/main/AndroidManifest.xml@@ -68,6 +68,15 @@ <data android:mimeType="image/*" /> </intent-filter> </activity>+ <activity android:name=".ui.VideoEditActivity"+ android:exported="true"+ android:theme="@style/Theme.General">+ <intent-filter android:label="@string/video_edit_with_label">+ <action android:name="android.intent.action.EDIT" />+ <category android:name="android.intent.category.DEFAULT" />+ <data android:mimeType="video/*" />+ </intent-filter>+ </activity> <!-- Glance widget receiver --> <receiver android:name=".glance.PhotoGlanceWidgetReceiver"
photos/src/main/java/com/vayunmathur/photos/data/VideoEditState.kt
diff --git a/photos/src/main/java/com/vayunmathur/photos/data/VideoEditState.kt b/photos/src/main/java/com/vayunmathur/photos/data/VideoEditState.ktnew file mode 100644index 0000000000..325567d99f--- /dev/null+++ b/photos/src/main/java/com/vayunmathur/photos/data/VideoEditState.kt@@ -0,0 +1,61 @@+package com.vayunmathur.photos.data++/** Which tool panel is showing in the video editor's bottom bar. */+enum class VideoTool { Trim, CropRotate, Audio, Filters }++/**+ * One-tap color looks for video. Each maps to a small set of color effects in+ * [com.vayunmathur.photos.util.VideoEditViewModel.buildVideoEffects]; the+ * per-slider brightness/contrast/saturation are applied on top.+ */+enum class VideoFilterPreset { None, Mono, Warm, Cool, Vivid }++/**+ * Immutable, single source of truth for the video editor. Both the live preview+ * (ExoPlayer effects/clipping/volume) and the export (Media3 Transformer) derive+ * from one instance so what you see is what you get.+ *+ * - Trim: [trimStartMs]..[trimEndMs] within [durationMs].+ * - Crop/rotate: [rotationDegrees] (0/90/180/270), [flipHorizontal], and an+ * optional [cropLeft]/[cropTop]/[cropRight]/[cropBottom] rectangle in+ * normalized [0,1] coordinates (null bounds ⇒ full frame).+ * - Audio: [muted].+ * - Color: [brightness]/[contrast]/[saturation] (0f = neutral) + [filterPreset].+ */+data class VideoEditState(+ val durationMs: Long = 0L,+ val trimStartMs: Long = 0L,+ val trimEndMs: Long = 0L,+ val rotationDegrees: Int = 0,+ val flipHorizontal: Boolean = false,+ val cropLeft: Float? = null,+ val cropTop: Float? = null,+ val cropRight: Float? = null,+ val cropBottom: Float? = null,+ val muted: Boolean = false,+ val brightness: Float = 0f,+ val contrast: Float = 0f,+ val saturation: Float = 0f,+ val filterPreset: VideoFilterPreset = VideoFilterPreset.None,+) {+ /** True if the trim range is a strict sub-range of the full clip. */+ val isTrimmed: Boolean+ get() = durationMs > 0L && (trimStartMs > 0L || trimEndMs < durationMs)++ /** True if a crop rectangle smaller than the full frame is set. */+ val isCropped: Boolean+ get() = cropLeft != null && cropTop != null && cropRight != null && cropBottom != null &&+ (cropLeft > 0f || cropTop > 0f || cropRight < 1f || cropBottom < 1f)++ /** True if any edit is active — used to warn/enable Save. */+ val hasEdits: Boolean+ get() = isTrimmed || isCropped || rotationDegrees != 0 || flipHorizontal || muted ||+ brightness != 0f || contrast != 0f || saturation != 0f ||+ filterPreset != VideoFilterPreset.None++ /** True if any pixel-level (crop/rotate/flip/color) edit is active. */+ val hasVideoEffects: Boolean+ get() = isCropped || rotationDegrees != 0 || flipHorizontal ||+ brightness != 0f || contrast != 0f || saturation != 0f ||+ filterPreset != VideoFilterPreset.None+}
photos/src/main/java/com/vayunmathur/photos/ui/PhotoPage.kt
diff --git a/photos/src/main/java/com/vayunmathur/photos/ui/PhotoPage.kt b/photos/src/main/java/com/vayunmathur/photos/ui/PhotoPage.ktindex 52909e5ff1..942e3bb55c 100644--- a/photos/src/main/java/com/vayunmathur/photos/ui/PhotoPage.kt+++ b/photos/src/main/java/com/vayunmathur/photos/ui/PhotoPage.kt@@ -233,8 +233,11 @@ fun PhotoPage(galleryViewModel: GalleryViewModel, photoMapViewModel: PhotoMapVie onToggleMetadata = { isMetadataVisible = !isMetadataVisible }, refreshKey = refreshKey, onEditPhoto = {+ val activityClass =+ if (photo.videoData != null) VideoEditActivity::class.java+ else EditActivity::class.java val intent =- Intent(context, EditActivity::class.java).apply {+ Intent(context, activityClass).apply { putExtra("photo_id", photo.id) } context.startActivity(intent)@@ -538,9 +541,7 @@ fun PhotoDetailView( IconButton(onClick = { onSetWallpaper(photo) }) { IconWallpaper(tint = Color.White) }- if (photo.videoData == null) {- IconButton(onClick = onEditPhoto) { IconEdit(tint = Color.White) }- }+ IconButton(onClick = onEditPhoto) { IconEdit(tint = Color.White) } IconButton( onClick = { val intent =
photos/src/main/java/com/vayunmathur/photos/ui/VideoEditActivity.kt
diff --git a/photos/src/main/java/com/vayunmathur/photos/ui/VideoEditActivity.kt b/photos/src/main/java/com/vayunmathur/photos/ui/VideoEditActivity.ktnew file mode 100644index 0000000000..3b9da1b60f--- /dev/null+++ b/photos/src/main/java/com/vayunmathur/photos/ui/VideoEditActivity.kt@@ -0,0 +1,80 @@+package com.vayunmathur.photos.ui++import android.content.Intent+import android.os.Bundle+import androidx.activity.ComponentActivity+import androidx.activity.compose.setContent+import androidx.activity.enableEdgeToEdge+import androidx.activity.viewModels+import androidx.compose.runtime.Composable+import androidx.compose.runtime.LaunchedEffect+import androidx.compose.runtime.getValue+import androidx.compose.runtime.mutableLongStateOf+import androidx.compose.runtime.mutableStateOf+import androidx.compose.runtime.remember+import androidx.compose.runtime.setValue+import com.vayunmathur.library.ui.DynamicTheme+import com.vayunmathur.library.room.buildDatabase+import com.vayunmathur.library.util.MainNavigation+import com.vayunmathur.library.util.rememberNavBackStack+import com.vayunmathur.photos.data.PhotoDao+import com.vayunmathur.photos.data.PhotoDatabase+import com.vayunmathur.photos.util.VideoEditViewModel+import com.vayunmathur.photos.util.VideoEditViewModelFactory++class VideoEditActivity : ComponentActivity() {+ private lateinit var photoDao: PhotoDao+ private val videoEditViewModel: VideoEditViewModel by viewModels {+ VideoEditViewModelFactory(application, photoDao)+ }++ override fun onCreate(savedInstanceState: Bundle?) {+ super.onCreate(savedInstanceState)+ enableEdgeToEdge()++ val db = buildDatabase<PhotoDatabase>()+ photoDao = db.photoDao()++ setContent {+ DynamicTheme {+ var photoId by remember { mutableLongStateOf(intent.getLongExtra("photo_id", -1L)) }+ var photoUri by remember { mutableStateOf<String?>(null) }++ LaunchedEffect(Unit) {+ if (photoId == -1L && (intent.action == Intent.ACTION_EDIT || intent.action == Intent.ACTION_VIEW)) {+ intent.data?.let { uri ->+ val uriString = uri.toString()+ val existing = photoDao.getByUri(uriString)+ if (existing.isNotEmpty()) {+ photoId = existing.first().id+ } else {+ photoId = 0L+ photoUri = uriString+ }+ } ?: finish()+ } else if (photoId == -1L) {+ finish()+ }+ }++ if (photoId != -1L || photoUri != null) {+ VideoEditNavigation(videoEditViewModel, photoId, photoUri)+ }+ }+ }+ }+}++@Composable+fun VideoEditNavigation(+ videoEditViewModel: VideoEditViewModel,+ photoId: Long,+ photoUri: String?,+) {+ val backStack = rememberNavBackStack<VideoEditRoute>(VideoEditRoute.EditVideo(photoId, photoUri))+ MainNavigation(backStack) {+ entry<VideoEditRoute.EditVideo> {+ VideoEditPage(videoEditViewModel, it.id, it.uri)+ }+ }+}
photos/src/main/java/com/vayunmathur/photos/ui/VideoEditPage.kt
diff --git a/photos/src/main/java/com/vayunmathur/photos/ui/VideoEditPage.kt b/photos/src/main/java/com/vayunmathur/photos/ui/VideoEditPage.ktnew file mode 100644index 0000000000..e7553a4dc3--- /dev/null+++ b/photos/src/main/java/com/vayunmathur/photos/ui/VideoEditPage.kt@@ -0,0 +1,596 @@+package com.vayunmathur.photos.ui++import android.app.Activity+import androidx.activity.compose.rememberLauncherForActivityResult+import androidx.activity.result.IntentSenderRequest+import androidx.activity.result.contract.ActivityResultContracts+import androidx.annotation.OptIn+import androidx.compose.foundation.background+import androidx.compose.foundation.gestures.detectDragGestures+import androidx.compose.foundation.layout.Arrangement+import androidx.compose.foundation.layout.Box+import androidx.compose.foundation.layout.Column+import androidx.compose.foundation.layout.Row+import androidx.compose.foundation.layout.Spacer+import androidx.compose.foundation.layout.aspectRatio+import androidx.compose.foundation.layout.fillMaxSize+import androidx.compose.foundation.layout.fillMaxWidth+import androidx.compose.foundation.layout.height+import androidx.compose.foundation.layout.padding+import androidx.compose.foundation.layout.size+import androidx.compose.foundation.layout.width+import androidx.compose.foundation.Canvas+import androidx.compose.runtime.Composable+import androidx.compose.runtime.DisposableEffect+import androidx.compose.runtime.LaunchedEffect+import androidx.compose.runtime.collectAsState+import androidx.compose.runtime.getValue+import androidx.compose.runtime.mutableFloatStateOf+import androidx.compose.runtime.mutableIntStateOf+import androidx.compose.runtime.mutableLongStateOf+import androidx.compose.runtime.mutableStateOf+import androidx.compose.runtime.remember+import androidx.compose.runtime.setValue+import androidx.compose.ui.Alignment+import androidx.compose.ui.Modifier+import androidx.compose.ui.geometry.Offset+import androidx.compose.ui.geometry.Rect+import androidx.compose.ui.geometry.Size+import androidx.compose.ui.graphics.Color+import androidx.compose.ui.graphics.drawscope.Stroke+import androidx.compose.ui.input.pointer.pointerInput+import androidx.compose.ui.layout.onGloballyPositioned+import androidx.compose.ui.platform.LocalContext+import androidx.compose.ui.res.stringResource+import androidx.compose.ui.text.style.TextAlign+import androidx.compose.ui.unit.IntSize+import androidx.compose.ui.unit.dp+import androidx.core.net.toUri+import androidx.media3.common.MediaItem+import androidx.media3.common.Player+import androidx.media3.common.VideoSize+import androidx.media3.common.util.UnstableApi+import androidx.media3.exoplayer.ExoPlayer+import androidx.media3.ui.compose.PlayerSurface+import androidx.media3.ui.compose.SURFACE_TYPE_TEXTURE_VIEW+import com.vayunmathur.library.ui.Button+import com.vayunmathur.library.ui.CircularProgressIndicator+import com.vayunmathur.library.ui.FilledTonalButton+import com.vayunmathur.library.ui.IconBack+import com.vayunmathur.library.ui.IconButton+import com.vayunmathur.library.ui.IconContentCut+import com.vayunmathur.library.ui.IconCrop+import com.vayunmathur.library.ui.IconFlip+import com.vayunmathur.library.ui.IconPause+import com.vayunmathur.library.ui.IconPlayCircle+import com.vayunmathur.library.ui.IconRotateLeft+import com.vayunmathur.library.ui.IconRotateRight+import com.vayunmathur.library.ui.IconSave+import com.vayunmathur.library.ui.IconTune+import com.vayunmathur.library.ui.IconVolumeOff+import com.vayunmathur.library.ui.IconVolumeUp+import com.vayunmathur.library.ui.MaterialTheme+import com.vayunmathur.library.ui.OutlinedButton+import com.vayunmathur.library.ui.RangeSlider+import com.vayunmathur.library.ui.Scaffold+import com.vayunmathur.library.ui.Slider+import com.vayunmathur.library.ui.Text+import com.vayunmathur.library.ui.TextButton+import com.vayunmathur.library.ui.TopAppBar+import com.vayunmathur.photos.R+import com.vayunmathur.photos.data.VideoEditState+import com.vayunmathur.photos.data.VideoFilterPreset+import com.vayunmathur.photos.data.VideoTool+import com.vayunmathur.photos.util.VideoEditViewModel+import kotlinx.coroutines.delay+import kotlinx.coroutines.isActive++@OptIn(UnstableApi::class)+@Composable+fun VideoEditPage(vm: VideoEditViewModel, id: Long, uri: String?) {+ val context = LocalContext.current+ val activity = context as? Activity++ LaunchedEffect(id, uri) { vm.loadVideo(id, uri) }++ val photo by vm.photo.collectAsState()+ val state by vm.state.collectAsState()+ val exporting by vm.exporting.collectAsState()+ val progress by vm.progress.collectAsState()++ val writePermissionLauncher = rememberLauncherForActivityResult(+ ActivityResultContracts.StartIntentSenderForResult(),+ ) { result ->+ if (result.resultCode == Activity.RESULT_OK) vm.onWritePermissionGranted()+ else vm.onWritePermissionDenied()+ }+ val writePermissionRequest by vm.writePermissionRequest.collectAsState()+ LaunchedEffect(writePermissionRequest) {+ writePermissionRequest?.let {+ writePermissionLauncher.launch(IntentSenderRequest.Builder(it).build())+ }+ }++ var selectedTool by remember { mutableStateOf(VideoTool.Trim) }+ var showSaveDialog by remember { mutableStateOf(false) }++ val currentPhoto = photo+ if (currentPhoto == null) {+ Box(Modifier.fillMaxSize().background(Color.Black), contentAlignment = Alignment.Center) {+ CircularProgressIndicator()+ }+ return+ }++ Scaffold(+ containerColor = Color.Black,+ topBar = {+ TopAppBar(+ title = { Text(stringResource(R.string.title_edit_video), maxLines = 1) },+ navigationIcon = {+ IconButton(onClick = { activity?.finish() }) { IconBack() }+ },+ actions = {+ IconButton(onClick = { showSaveDialog = true }, enabled = !exporting) { IconSave() }+ },+ )+ },+ ) { padding ->+ Column(+ modifier = Modifier.fillMaxSize().padding(padding),+ ) {+ Box(+ modifier = Modifier.fillMaxWidth().weight(1f),+ contentAlignment = Alignment.Center,+ ) {+ VideoEditPreview(+ vm = vm,+ state = state,+ uri = currentPhoto.uri.toUri(),+ showCropOverlay = selectedTool == VideoTool.CropRotate,+ )+ }++ ToolPanel(vm = vm, state = state, tool = selectedTool)++ ToolTabs(selected = selectedTool, onSelect = { selectedTool = it })+ }+ }++ if (showSaveDialog) {+ SaveDialog(+ onDismiss = { showSaveDialog = false },+ onSaveCopy = {+ showSaveDialog = false+ vm.export(context, currentPhoto, asCopy = true) { activity?.finish() }+ },+ onOverwrite = {+ showSaveDialog = false+ vm.export(context, currentPhoto, asCopy = false) { activity?.finish() }+ },+ )+ }++ if (exporting) {+ ExportProgressDialog(progress = progress, onCancel = { vm.cancelExport() })+ }+}++@OptIn(UnstableApi::class)+@Composable+private fun VideoEditPreview(+ vm: VideoEditViewModel,+ state: VideoEditState,+ uri: android.net.Uri,+ showCropOverlay: Boolean,+) {+ val context = LocalContext.current+ var videoAspectRatio by remember { mutableFloatStateOf(16f / 9f) }+ var isPlaying by remember { mutableStateOf(true) }++ val exoPlayer = remember(uri) {+ ExoPlayer.Builder(context).build().apply {+ setMediaItem(MediaItem.fromUri(uri))+ prepare()+ playWhenReady = true+ repeatMode = Player.REPEAT_MODE_ONE+ }+ }++ // Report duration up to the view model once known.+ LaunchedEffect(exoPlayer) {+ while (isActive) {+ val d = exoPlayer.duration+ if (d > 0) {+ vm.setDuration(d)+ break+ }+ delay(150)+ }+ }++ // Live crop/rotate/filter effects.+ LaunchedEffect(+ state.rotationDegrees, state.flipHorizontal,+ state.cropLeft, state.cropTop, state.cropRight, state.cropBottom,+ state.brightness, state.contrast, state.saturation, state.filterPreset,+ ) {+ exoPlayer.setVideoEffects(vm.buildVideoEffects(state))+ }++ // Trim preview: re-clip the source when the committed range changes.+ LaunchedEffect(state.trimStartMs, state.trimEndMs, state.durationMs) {+ if (state.durationMs <= 0L) return@LaunchedEffect+ val item = MediaItem.Builder()+ .setUri(uri)+ .setClippingConfiguration(+ MediaItem.ClippingConfiguration.Builder()+ .setStartPositionMs(state.trimStartMs)+ .setEndPositionMs(if (state.trimEndMs > 0L) state.trimEndMs else state.durationMs)+ .build()+ )+ .build()+ val wasPlaying = exoPlayer.playWhenReady+ exoPlayer.setMediaItem(item)+ exoPlayer.prepare()+ exoPlayer.playWhenReady = wasPlaying+ }++ // Mute.+ LaunchedEffect(state.muted) {+ exoPlayer.volume = if (state.muted) 0f else 1f+ }++ DisposableEffect(exoPlayer) {+ val listener = object : Player.Listener {+ override fun onIsPlayingChanged(playing: Boolean) { isPlaying = playing }+ override fun onVideoSizeChanged(videoSize: VideoSize) {+ if (videoSize.width > 0 && videoSize.height > 0) {+ videoAspectRatio =+ (videoSize.width * videoSize.pixelWidthHeightRatio) / videoSize.height+ }+ }+ }+ exoPlayer.addListener(listener)+ onDispose {+ exoPlayer.removeListener(listener)+ exoPlayer.release()+ }+ }++ Box(modifier = Modifier.fillMaxSize(), contentAlignment = Alignment.Center) {+ Box(+ modifier = Modifier.fillMaxWidth().aspectRatio(videoAspectRatio),+ contentAlignment = Alignment.Center,+ ) {+ PlayerSurface(+ player = exoPlayer,+ modifier = Modifier.fillMaxSize(),+ surfaceType = SURFACE_TYPE_TEXTURE_VIEW,+ )+ if (showCropOverlay) {+ CropOverlay(+ state = state,+ onCrop = { r ->+ if (r.left <= 0.001f && r.top <= 0.001f && r.right >= 0.999f && r.bottom >= 0.999f) {+ vm.clearCrop()+ } else {+ vm.setCrop(r.left, r.top, r.right, r.bottom)+ }+ },+ modifier = Modifier.fillMaxSize(),+ )+ }+ }++ IconButton(onClick = { if (isPlaying) exoPlayer.pause() else exoPlayer.play() }) {+ if (isPlaying) {+ IconPause(modifier = Modifier.size(56.dp), tint = Color.White.copy(alpha = 0.85f))+ } else {+ IconPlayCircle(modifier = Modifier.size(56.dp), tint = Color.White.copy(alpha = 0.85f))+ }+ }+ }+}++@Composable+private fun CropOverlay(+ state: VideoEditState,+ onCrop: (Rect) -> Unit,+ modifier: Modifier = Modifier,+) {+ var boxSize by remember { mutableStateOf(IntSize.Zero) }+ var rect by remember {+ mutableStateOf(+ Rect(+ state.cropLeft ?: 0f, state.cropTop ?: 0f,+ state.cropRight ?: 1f, state.cropBottom ?: 1f,+ )+ )+ }+ var active by remember { mutableIntStateOf(-1) }+ val minSize = 0.15f++ Box(+ modifier = modifier+ .onGloballyPositioned { boxSize = it.size }+ .pointerInput(boxSize) {+ detectDragGestures(+ onDragStart = { pos ->+ val w = boxSize.width.toFloat().coerceAtLeast(1f)+ val h = boxSize.height.toFloat().coerceAtLeast(1f)+ val corners = listOf(+ Offset(rect.left * w, rect.top * h),+ Offset(rect.right * w, rect.top * h),+ Offset(rect.left * w, rect.bottom * h),+ Offset(rect.right * w, rect.bottom * h),+ )+ active = corners.indexOfFirst { (it - pos).getDistance() < 100f }+ },+ onDrag = { change, drag ->+ if (active < 0) return@detectDragGestures+ change.consume()+ val w = boxSize.width.toFloat().coerceAtLeast(1f)+ val h = boxSize.height.toFloat().coerceAtLeast(1f)+ val dx = drag.x / w+ val dy = drag.y / h+ rect = when (active) {+ 0 -> Rect(+ (rect.left + dx).coerceIn(0f, rect.right - minSize),+ (rect.top + dy).coerceIn(0f, rect.bottom - minSize),+ rect.right, rect.bottom,+ )+ 1 -> Rect(+ rect.left,+ (rect.top + dy).coerceIn(0f, rect.bottom - minSize),+ (rect.right + dx).coerceIn(rect.left + minSize, 1f),+ rect.bottom,+ )+ 2 -> Rect(+ (rect.left + dx).coerceIn(0f, rect.right - minSize),+ rect.top,+ rect.right,+ (rect.bottom + dy).coerceIn(rect.top + minSize, 1f),+ )+ else -> Rect(+ rect.left,+ rect.top,+ (rect.right + dx).coerceIn(rect.left + minSize, 1f),+ (rect.bottom + dy).coerceIn(rect.top + minSize, 1f),+ )+ }+ },+ onDragEnd = { active = -1; onCrop(rect) },+ )+ },+ ) {+ Canvas(Modifier.fillMaxSize()) {+ val w = size.width+ val h = size.height+ val l = rect.left * w+ val t = rect.top * h+ val r = rect.right * w+ val b = rect.bottom * h+ drawRect(+ color = Color.White,+ topLeft = Offset(l, t),+ size = Size(r - l, b - t),+ style = Stroke(width = 3.dp.toPx()),+ )+ listOf(Offset(l, t), Offset(r, t), Offset(l, b), Offset(r, b)).forEach {+ drawCircle(Color.White, radius = 8.dp.toPx(), center = it)+ }+ }+ }+}++@Composable+private fun ToolPanel(vm: VideoEditViewModel, state: VideoEditState, tool: VideoTool) {+ Column(+ modifier = Modifier.fillMaxWidth()+ .background(Color(0xFF121212))+ .padding(horizontal = 16.dp, vertical = 12.dp),+ ) {+ when (tool) {+ VideoTool.Trim -> TrimPanel(vm, state)+ VideoTool.CropRotate -> CropRotatePanel(vm, state)+ VideoTool.Audio -> AudioPanel(vm, state)+ VideoTool.Filters -> FiltersPanel(vm, state)+ }+ }+}++@Composable+private fun TrimPanel(vm: VideoEditViewModel, state: VideoEditState) {+ val duration = state.durationMs.coerceAtLeast(1L)+ var range by remember(state.durationMs) {+ mutableStateOf(+ state.trimStartMs.toFloat()..(if (state.trimEndMs > 0L) state.trimEndMs else duration).toFloat()+ )+ }+ Text(stringResource(R.string.video_trim), color = Color.White, style = MaterialTheme.typography.titleSmall)+ RangeSlider(+ value = range,+ onValueChange = { range = it },+ onValueChangeFinished = { vm.setTrim(range.start.toLong(), range.endInclusive.toLong()) },+ valueRange = 0f..duration.toFloat(),+ modifier = Modifier.fillMaxWidth(),+ )+ Row(modifier = Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.SpaceBetween) {+ Text(formatVideoTime(range.start.toLong()), color = Color.White, style = MaterialTheme.typography.labelMedium)+ Text(formatVideoTime(range.endInclusive.toLong()), color = Color.White, style = MaterialTheme.typography.labelMedium)+ }+}++@Composable+private fun CropRotatePanel(vm: VideoEditViewModel, state: VideoEditState) {+ Text(stringResource(R.string.video_crop_rotate), color = Color.White, style = MaterialTheme.typography.titleSmall)+ Spacer(Modifier.height(8.dp))+ Row(+ modifier = Modifier.fillMaxWidth(),+ horizontalArrangement = Arrangement.spacedBy(8.dp),+ verticalAlignment = Alignment.CenterVertically,+ ) {+ IconButton(onClick = { vm.rotateLeft() }) { IconRotateLeft(tint = Color.White) }+ IconButton(onClick = { vm.rotateRight() }) { IconRotateRight(tint = Color.White) }+ IconButton(onClick = { vm.toggleFlip() }) {+ IconFlip(tint = if (state.flipHorizontal) MaterialTheme.colorScheme.primary else Color.White)+ }+ Spacer(Modifier.weight(1f))+ TextButton(onClick = { vm.clearCrop() }) { Text(stringResource(R.string.reset)) }+ }+ Text(+ stringResource(R.string.video_crop_hint),+ color = Color.LightGray,+ style = MaterialTheme.typography.labelSmall,+ )+}++@Composable+private fun AudioPanel(vm: VideoEditViewModel, state: VideoEditState) {+ Text(stringResource(R.string.video_audio), color = Color.White, style = MaterialTheme.typography.titleSmall)+ Spacer(Modifier.height(8.dp))+ FilledTonalButton(onClick = { vm.setMuted(!state.muted) }) {+ if (state.muted) IconVolumeOff() else IconVolumeUp()+ Spacer(Modifier.width(8.dp))+ Text(stringResource(if (state.muted) R.string.video_muted else R.string.video_audio_on))+ }+}++@Composable+private fun FiltersPanel(vm: VideoEditViewModel, state: VideoEditState) {+ Row(+ modifier = Modifier.fillMaxWidth(),+ horizontalArrangement = Arrangement.spacedBy(8.dp),+ ) {+ VideoFilterPreset.entries.forEach { preset ->+ val selected = state.filterPreset == preset+ if (selected) {+ Button(onClick = { vm.setFilterPreset(preset) }) { Text(presetLabel(preset)) }+ } else {+ OutlinedButton(onClick = { vm.setFilterPreset(preset) }) { Text(presetLabel(preset)) }+ }+ }+ }+ Spacer(Modifier.height(8.dp))+ LabeledSlider(stringResource(R.string.video_brightness), state.brightness) { vm.setBrightness(it) }+ LabeledSlider(stringResource(R.string.video_contrast), state.contrast) { vm.setContrast(it) }+ LabeledSlider(stringResource(R.string.video_saturation), state.saturation) { vm.setSaturation(it) }+}++@Composable+private fun LabeledSlider(label: String, value: Float, onChange: (Float) -> Unit) {+ Column(Modifier.fillMaxWidth()) {+ Text(label, color = Color.White, style = MaterialTheme.typography.labelMedium)+ Slider(+ value = value,+ onValueChange = onChange,+ valueRange = -1f..1f,+ modifier = Modifier.fillMaxWidth(),+ )+ }+}++@Composable+private fun presetLabel(preset: VideoFilterPreset): String = when (preset) {+ VideoFilterPreset.None -> stringResource(R.string.video_filter_none)+ VideoFilterPreset.Mono -> stringResource(R.string.video_filter_mono)+ VideoFilterPreset.Warm -> stringResource(R.string.video_filter_warm)+ VideoFilterPreset.Cool -> stringResource(R.string.video_filter_cool)+ VideoFilterPreset.Vivid -> stringResource(R.string.video_filter_vivid)+}++@Composable+private fun ToolTabs(selected: VideoTool, onSelect: (VideoTool) -> Unit) {+ Row(+ modifier = Modifier.fillMaxWidth()+ .background(Color(0xFF1E1E1E))+ .padding(vertical = 8.dp),+ horizontalArrangement = Arrangement.SpaceEvenly,+ ) {+ ToolTab(VideoTool.Trim, selected, onSelect, stringResource(R.string.video_trim)) {+ IconContentCut(tint = it)+ }+ ToolTab(VideoTool.CropRotate, selected, onSelect, stringResource(R.string.video_crop_rotate)) {+ IconCrop(tint = it)+ }+ ToolTab(VideoTool.Audio, selected, onSelect, stringResource(R.string.video_audio)) {+ IconVolumeUp(tint = it)+ }+ ToolTab(VideoTool.Filters, selected, onSelect, stringResource(R.string.video_filters)) {+ IconTune(tint = it)+ }+ }+}++@Composable+private fun ToolTab(+ tool: VideoTool,+ selected: VideoTool,+ onSelect: (VideoTool) -> Unit,+ label: String,+ icon: @Composable (Color) -> Unit,+) {+ val tint = if (tool == selected) MaterialTheme.colorScheme.primary else Color.White+ Column(+ modifier = Modifier.width(72.dp),+ horizontalAlignment = Alignment.CenterHorizontally,+ ) {+ IconButton(onClick = { onSelect(tool) }) { icon(tint) }+ Text(label, color = tint, style = MaterialTheme.typography.labelSmall, textAlign = TextAlign.Center)+ }+}++@Composable+private fun SaveDialog(+ onDismiss: () -> Unit,+ onSaveCopy: () -> Unit,+ onOverwrite: () -> Unit,+) {+ com.vayunmathur.library.ui.AlertDialog(+ onDismissRequest = onDismiss,+ title = { Text(stringResource(R.string.action_save)) },+ text = { Text(stringResource(R.string.video_save_prompt)) },+ confirmButton = {+ TextButton(onClick = onSaveCopy) { Text(stringResource(R.string.video_save_copy)) }+ },+ dismissButton = {+ TextButton(onClick = onOverwrite) { Text(stringResource(R.string.video_overwrite)) }+ },+ )+}++@Composable+private fun ExportProgressDialog(progress: Float, onCancel: () -> Unit) {+ com.vayunmathur.library.ui.AlertDialog(+ onDismissRequest = {},+ title = { Text(stringResource(R.string.video_exporting)) },+ text = {+ Row(verticalAlignment = Alignment.CenterVertically) {+ if (progress > 0f) {+ CircularProgressIndicator(progress = { progress })+ } else {+ CircularProgressIndicator()+ }+ Spacer(Modifier.width(16.dp))+ Text("${(progress * 100).toInt()}%")+ }+ },+ confirmButton = {+ TextButton(onClick = onCancel) { Text(stringResource(com.vayunmathur.library.ui.R.string.cancel)) }+ },+ )+}++/** Formats a video position/duration in milliseconds as m:ss (or h:mm:ss past an hour). */+private fun formatVideoTime(ms: Long): String {+ val totalSeconds = (ms / 1000).coerceAtLeast(0)+ val hours = totalSeconds / 3600+ val minutes = (totalSeconds % 3600) / 60+ val seconds = totalSeconds % 60+ return if (hours > 0) {+ "%d:%02d:%02d".format(hours, minutes, seconds)+ } else {+ "%d:%02d".format(minutes, seconds)+ }+}
photos/src/main/java/com/vayunmathur/photos/ui/VideoEditRoute.kt
diff --git a/photos/src/main/java/com/vayunmathur/photos/ui/VideoEditRoute.kt b/photos/src/main/java/com/vayunmathur/photos/ui/VideoEditRoute.ktnew file mode 100644index 0000000000..2da25b7267--- /dev/null+++ b/photos/src/main/java/com/vayunmathur/photos/ui/VideoEditRoute.kt@@ -0,0 +1,10 @@+package com.vayunmathur.photos.ui++import com.vayunmathur.library.util.NavKey+import kotlinx.serialization.Serializable++@Serializable+sealed interface VideoEditRoute : NavKey {+ @Serializable+ data class EditVideo(val id: Long, val uri: String? = null) : VideoEditRoute+}
photos/src/main/java/com/vayunmathur/photos/util/VideoEditViewModel.kt
diff --git a/photos/src/main/java/com/vayunmathur/photos/util/VideoEditViewModel.kt b/photos/src/main/java/com/vayunmathur/photos/util/VideoEditViewModel.ktnew file mode 100644index 0000000000..66abe7a78d--- /dev/null+++ b/photos/src/main/java/com/vayunmathur/photos/util/VideoEditViewModel.kt@@ -0,0 +1,422 @@+package com.vayunmathur.photos.util++import android.app.Application+import android.content.ContentValues+import android.content.Context+import android.content.IntentSender+import android.net.Uri+import android.os.Environment+import android.provider.MediaStore+import android.util.Log+import androidx.core.net.toUri+import androidx.lifecycle.AndroidViewModel+import androidx.lifecycle.ViewModelProvider+import androidx.lifecycle.viewModelScope+import androidx.lifecycle.viewmodel.initializer+import androidx.lifecycle.viewmodel.viewModelFactory+import androidx.media3.common.Effect+import androidx.media3.common.MediaItem+import androidx.media3.common.util.UnstableApi+import androidx.media3.effect.Brightness+import androidx.media3.effect.Contrast+import androidx.media3.effect.Crop+import androidx.media3.effect.HslAdjustment+import androidx.media3.effect.RgbAdjustment+import androidx.media3.effect.RgbFilter+import androidx.media3.effect.ScaleAndRotateTransformation+import androidx.media3.transformer.Composition+import androidx.media3.transformer.EditedMediaItem+import androidx.media3.transformer.Effects+import androidx.media3.transformer.ExportException+import androidx.media3.transformer.ExportResult+import androidx.media3.transformer.ProgressHolder+import androidx.media3.transformer.Transformer+import com.vayunmathur.photos.data.Photo+import com.vayunmathur.photos.data.PhotoDao+import com.vayunmathur.photos.data.VideoEditState+import com.vayunmathur.photos.data.VideoFilterPreset+import kotlinx.coroutines.Dispatchers+import kotlinx.coroutines.Job+import kotlinx.coroutines.delay+import kotlinx.coroutines.flow.MutableStateFlow+import kotlinx.coroutines.flow.StateFlow+import kotlinx.coroutines.flow.asStateFlow+import kotlinx.coroutines.isActive+import kotlinx.coroutines.launch+import kotlinx.coroutines.withContext+import java.io.File++/**+ * Video editor view model. The single source of truth is [state]; both the live+ * preview (ExoPlayer `setVideoEffects` / clipping / volume in `VideoEditPage`)+ * and the export ([Transformer]) derive their transforms from it via+ * [buildVideoEffects], so what the user sees is what gets written.+ *+ * Save mirrors [PhotoEditViewModel]'s MediaStore conventions: a copy is inserted+ * into `MediaStore.Video`, and an overwrite falls back to+ * [MediaStore.createWriteRequest] + IntentSender when a direct write is denied.+ */+@UnstableApi+class VideoEditViewModel(+ application: Application,+ private val photoDao: PhotoDao,+) : AndroidViewModel(application) {++ private val _photo = MutableStateFlow<Photo?>(null)+ val photo: StateFlow<Photo?> = _photo.asStateFlow()+ private var photoJob: Job? = null++ private val _state = MutableStateFlow(VideoEditState())+ val state: StateFlow<VideoEditState> = _state.asStateFlow()++ private val _exporting = MutableStateFlow(false)+ val exporting: StateFlow<Boolean> = _exporting.asStateFlow()++ /** Export progress in 0f..1f while [exporting] is true. */+ private val _progress = MutableStateFlow(0f)+ val progress: StateFlow<Float> = _progress.asStateFlow()++ private val _writePermissionRequest = MutableStateFlow<IntentSender?>(null)+ val writePermissionRequest: StateFlow<IntentSender?> = _writePermissionRequest.asStateFlow()++ private var transformer: Transformer? = null+ private var progressJob: Job? = null++ // Kept alive across the overwrite-permission round-trip.+ private var pendingExportFile: File? = null+ private var pendingExportUri: Uri? = null+ private var pendingOnComplete: (() -> Unit)? = null++ /** Loads [id]'s video from the DB, falling back to a stand-in built from [initialUri]. */+ fun loadVideo(id: Long, initialUri: String?) {+ photoJob?.cancel()+ photoJob = viewModelScope.launch {+ photoDao.getByIdFlow(id).collect { fromDb ->+ _photo.value = fromDb ?: initialUri?.let { uri ->+ Photo(+ id = 0, name = uri.substringAfterLast("/"), uri = uri,+ date = System.currentTimeMillis(), width = 0, height = 0,+ dateModified = System.currentTimeMillis() / 1000, exifSet = false,+ lat = null, long = null, videoData = null, panoData = null,+ )+ }+ }+ }+ }++ // --- state mutation -------------------------------------------------------++ private inline fun update(transform: (VideoEditState) -> VideoEditState) {+ _state.value = transform(_state.value)+ }++ /** Called once the player reports the real duration; seeds the trim range. */+ fun setDuration(durationMs: Long) {+ if (durationMs <= 0L) return+ update {+ if (it.durationMs == durationMs) it+ else it.copy(+ durationMs = durationMs,+ trimStartMs = it.trimStartMs.coerceIn(0L, durationMs),+ trimEndMs = if (it.trimEndMs <= 0L || it.trimEndMs > durationMs) durationMs else it.trimEndMs,+ )+ }+ }++ fun setTrim(startMs: Long, endMs: Long) = update {+ val d = it.durationMs+ it.copy(+ trimStartMs = startMs.coerceIn(0L, d),+ trimEndMs = endMs.coerceIn(0L, d),+ )+ }++ fun rotateLeft() = update { it.copy(rotationDegrees = ((it.rotationDegrees - 90) % 360 + 360) % 360) }+ fun rotateRight() = update { it.copy(rotationDegrees = (it.rotationDegrees + 90) % 360) }+ fun toggleFlip() = update { it.copy(flipHorizontal = !it.flipHorizontal) }++ fun setCrop(left: Float?, top: Float?, right: Float?, bottom: Float?) = update {+ it.copy(cropLeft = left, cropTop = top, cropRight = right, cropBottom = bottom)+ }+ fun clearCrop() = update { it.copy(cropLeft = null, cropTop = null, cropRight = null, cropBottom = null) }++ fun setMuted(muted: Boolean) = update { it.copy(muted = muted) }++ fun setBrightness(v: Float) = update { it.copy(brightness = v.coerceIn(-1f, 1f)) }+ fun setContrast(v: Float) = update { it.copy(contrast = v.coerceIn(-1f, 1f)) }+ fun setSaturation(v: Float) = update { it.copy(saturation = v.coerceIn(-1f, 1f)) }+ fun setFilterPreset(preset: VideoFilterPreset) = update { it.copy(filterPreset = preset) }++ // --- effects (shared by preview + export) ---------------------------------++ /** Maps [state] to the ordered list of Media3 video effects. */+ fun buildVideoEffects(state: VideoEditState): List<Effect> {+ val effects = mutableListOf<Effect>()+ when (state.filterPreset) {+ VideoFilterPreset.None -> {}+ VideoFilterPreset.Mono -> effects.add(RgbFilter.createGrayscaleFilter())+ VideoFilterPreset.Warm ->+ effects.add(RgbAdjustment.Builder().setRedScale(1.1f).setBlueScale(0.9f).build())+ VideoFilterPreset.Cool ->+ effects.add(RgbAdjustment.Builder().setRedScale(0.9f).setBlueScale(1.1f).build())+ VideoFilterPreset.Vivid ->+ effects.add(HslAdjustment.Builder().adjustSaturation(40f).build())+ }+ if (state.brightness != 0f) effects.add(Brightness(state.brightness))+ if (state.contrast != 0f) effects.add(Contrast(state.contrast))+ if (state.saturation != 0f) {+ effects.add(HslAdjustment.Builder().adjustSaturation(state.saturation * 100f).build())+ }+ if (state.isCropped) {+ val l = state.cropLeft!!; val t = state.cropTop!!+ val r = state.cropRight!!; val b = state.cropBottom!!+ // Normalized [0,1] top-left rect → NDC [-1,1] (Crop: left, right, bottom, top).+ effects.add(Crop(l * 2f - 1f, r * 2f - 1f, 1f - b * 2f, 1f - t * 2f))+ }+ if (state.rotationDegrees != 0 || state.flipHorizontal) {+ val builder = ScaleAndRotateTransformation.Builder()+ if (state.flipHorizontal) builder.setScale(-1f, 1f)+ if (state.rotationDegrees != 0) builder.setRotationDegrees(state.rotationDegrees.toFloat())+ effects.add(builder.build())+ }+ return effects+ }++ // --- export ---------------------------------------------------------------++ private fun buildMediaItem(uri: Uri, state: VideoEditState): MediaItem {+ val builder = MediaItem.Builder().setUri(uri)+ if (state.isTrimmed) {+ builder.setClippingConfiguration(+ MediaItem.ClippingConfiguration.Builder()+ .setStartPositionMs(state.trimStartMs)+ .setEndPositionMs(state.trimEndMs)+ .build()+ )+ }+ return builder.build()+ }++ /**+ * Exports the edited video to a temp file, then writes it into MediaStore as+ * a copy ([asCopy] == true) or over the original. Must be called on the main+ * thread (Transformer requires a Looper). [onComplete] fires on success or+ * unrecoverable failure; the overwrite-permission path resumes via+ * [onWritePermissionGranted].+ */+ fun export(context: Context, photo: Photo, asCopy: Boolean, onComplete: () -> Unit) {+ if (_exporting.value) return+ val state = _state.value+ val tempFile = File(context.cacheDir, "video_edit_${System.currentTimeMillis()}.mp4")+ val mediaItem = buildMediaItem(photo.uri.toUri(), state)+ val editedItem = EditedMediaItem.Builder(mediaItem)+ .setRemoveAudio(state.muted)+ .setEffects(Effects(emptyList(), buildVideoEffects(state)))+ .build()++ val t = Transformer.Builder(context)+ .addListener(object : Transformer.Listener {+ override fun onCompleted(composition: Composition, exportResult: ExportResult) {+ stopProgress()+ finishExport(context, photo, asCopy, tempFile, onComplete)+ }++ override fun onError(+ composition: Composition,+ exportResult: ExportResult,+ exportException: ExportException,+ ) {+ Log.e(TAG, "Export failed", exportException)+ stopProgress()+ tempFile.delete()+ _exporting.value = false+ onComplete()+ }+ })+ .build()+ transformer = t+ _exporting.value = true+ _progress.value = 0f+ t.start(editedItem, tempFile.absolutePath)+ startProgress()+ }++ private fun startProgress() {+ progressJob?.cancel()+ progressJob = viewModelScope.launch {+ val holder = ProgressHolder()+ while (isActive) {+ val stateInt = transformer?.getProgress(holder) ?: Transformer.PROGRESS_STATE_NOT_STARTED+ if (stateInt == Transformer.PROGRESS_STATE_AVAILABLE) {+ _progress.value = holder.progress / 100f+ }+ delay(200)+ }+ }+ }++ private fun stopProgress() {+ progressJob?.cancel()+ progressJob = null+ transformer = null+ }++ fun cancelExport() {+ transformer?.cancel()+ stopProgress()+ pendingExportFile?.delete()+ pendingExportFile = null+ pendingExportUri = null+ pendingOnComplete = null+ _exporting.value = false+ }++ private fun finishExport(+ context: Context,+ photo: Photo,+ asCopy: Boolean,+ tempFile: File,+ onComplete: () -> Unit,+ ) {+ viewModelScope.launch {+ val result = withContext(Dispatchers.IO) {+ writeVideo(context, photo, tempFile, asCopy)+ }+ when (result) {+ is WriteResult.Success -> {+ _exporting.value = false+ onComplete()+ }+ is WriteResult.NeedsPermission -> {+ pendingExportFile = result.tempFile+ pendingExportUri = result.uri+ pendingOnComplete = onComplete+ _writePermissionRequest.value = result.intentSender+ }+ is WriteResult.Error -> {+ Log.e(TAG, "Save failed", result.exception)+ _exporting.value = false+ onComplete()+ }+ }+ }+ }++ fun onWritePermissionGranted() {+ val tempFile = pendingExportFile ?: return+ val uri = pendingExportUri ?: return+ val onComplete = pendingOnComplete ?: return+ pendingExportFile = null; pendingExportUri = null; pendingOnComplete = null+ _writePermissionRequest.value = null+ val ctx: Context = getApplication()+ viewModelScope.launch {+ withContext(Dispatchers.IO) {+ try {+ val resolver = ctx.contentResolver+ resolver.openOutputStream(uri, "w")?.use { out ->+ tempFile.inputStream().use { it.copyTo(out) }+ } ?: throw Exception("openOutputStream returned null after permission grant")+ val values = ContentValues().apply {+ put(MediaStore.Video.Media.DATE_MODIFIED, System.currentTimeMillis() / 1000)+ put(MediaStore.Video.Media.SIZE, tempFile.length())+ }+ resolver.update(uri, values, null, null)+ } catch (e: Exception) {+ Log.e(TAG, "Overwrite FAILED after permission grant", e)+ } finally {+ tempFile.delete()+ }+ }+ _exporting.value = false+ onComplete()+ }+ }++ fun onWritePermissionDenied() {+ pendingExportFile?.delete()+ pendingExportFile = null; pendingExportUri = null; pendingOnComplete = null+ _writePermissionRequest.value = null+ _exporting.value = false+ }++ override fun onCleared() {+ progressJob?.cancel()+ transformer?.cancel()+ transformer = null+ pendingExportFile?.delete()+ }++ companion object {+ private const val TAG = "VideoEditViewModel"++ private sealed class WriteResult {+ data object Success : WriteResult()+ data class NeedsPermission(+ val intentSender: IntentSender,+ val tempFile: File,+ val uri: Uri,+ ) : WriteResult()+ data class Error(val exception: Exception) : WriteResult()+ }++ private fun writeVideo(+ context: Context,+ photo: Photo,+ tempFile: File,+ asCopy: Boolean,+ ): WriteResult {+ val resolver = context.contentResolver+ val nowSeconds = System.currentTimeMillis() / 1000+ if (asCopy) {+ val baseName = photo.name.substringBeforeLast('.')+ val values = ContentValues().apply {+ put(MediaStore.Video.Media.DISPLAY_NAME, "Edited_$baseName.mp4")+ put(MediaStore.Video.Media.MIME_TYPE, "video/mp4")+ put(MediaStore.Video.Media.DATE_MODIFIED, nowSeconds)+ put(MediaStore.Video.Media.RELATIVE_PATH, Environment.DIRECTORY_MOVIES)+ put(MediaStore.Video.Media.IS_PENDING, 1)+ }+ return try {+ val uri = resolver.insert(MediaStore.Video.Media.EXTERNAL_CONTENT_URI, values)+ ?: return WriteResult.Error(Exception("MediaStore insert returned null"))+ resolver.openOutputStream(uri)?.use { out ->+ tempFile.inputStream().use { it.copyTo(out) }+ }+ val done = ContentValues().apply { put(MediaStore.Video.Media.IS_PENDING, 0) }+ resolver.update(uri, done, null, null)+ tempFile.delete()+ WriteResult.Success+ } catch (e: Exception) {+ WriteResult.Error(e)+ }+ }++ val uri = photo.uri.toUri()+ try {+ resolver.openOutputStream(uri, "w")?.use { out ->+ tempFile.inputStream().use { it.copyTo(out) }+ }+ val values = ContentValues().apply {+ put(MediaStore.Video.Media.DATE_MODIFIED, nowSeconds)+ put(MediaStore.Video.Media.SIZE, tempFile.length())+ }+ resolver.update(uri, values, null, null)+ tempFile.delete()+ return WriteResult.Success+ } catch (e: Exception) {+ Log.d(TAG, "Direct write failed, falling back to createWriteRequest", e)+ }+ val pendingIntent = MediaStore.createWriteRequest(resolver, listOf(uri))+ return WriteResult.NeedsPermission(pendingIntent.intentSender, tempFile, uri)+ }+ }+}++@Suppress("FunctionName")+fun VideoEditViewModelFactory(+ application: Application,+ photoDao: PhotoDao,+): ViewModelProvider.Factory =+ viewModelFactory {+ initializer { VideoEditViewModel(application, photoDao) }+ }
photos/src/main/res/values/strings.xml
diff --git a/photos/src/main/res/values/strings.xml b/photos/src/main/res/values/strings.xmlindex e193735f40..26111b7cc6 100644--- a/photos/src/main/res/values/strings.xml+++ b/photos/src/main/res/values/strings.xml@@ -108,6 +108,51 @@ <!-- Apply current transformation/adjustment baking it in. Verb --> <string name="apply">Apply</string> + <!-- TopAppBar title for video editor screen. Verb phrase -->+ <string name="title_edit_video">Edit Video</string>+ <!-- Video editor tool: trim clip length. Verb -->+ <string name="video_trim">Trim</string>+ <!-- Video editor tool: crop and rotate. Noun phrase -->+ <string name="video_crop_rotate">Crop & Rotate</string>+ <!-- Hint under crop/rotate tools: drag the corner handles on the preview to crop. Sentence instruction -->+ <string name="video_crop_hint">Drag the corners on the preview to crop.</string>+ <!-- Video editor tool: audio track. Noun -->+ <string name="video_audio">Audio</string>+ <!-- Button label: audio is currently on (tap to mute). Adjective phrase -->+ <string name="video_audio_on">Audio on</string>+ <!-- Button label: audio is currently muted (tap to unmute). Adjective -->+ <string name="video_muted">Muted</string>+ <!-- Video editor tool: color filters and adjustments. Noun -->+ <string name="video_filters">Filters</string>+ <!-- Filter preset: no filter. Noun -->+ <string name="video_filter_none">None</string>+ <!-- Filter preset: black & white. Noun -->+ <string name="video_filter_mono">Mono</string>+ <!-- Filter preset: warm tint. Adjective -->+ <string name="video_filter_warm">Warm</string>+ <!-- Filter preset: cool tint. Adjective -->+ <string name="video_filter_cool">Cool</string>+ <!-- Filter preset: vivid/saturated. Adjective -->+ <string name="video_filter_vivid">Vivid</string>+ <!-- Slider label: brightness adjustment. Noun -->+ <string name="video_brightness">Brightness</string>+ <!-- Slider label: contrast adjustment. Noun -->+ <string name="video_contrast">Contrast</string>+ <!-- Slider label: saturation adjustment. Noun -->+ <string name="video_saturation">Saturation</string>+ <!-- Save dialog body: ask whether to keep original or overwrite. Question -->+ <string name="video_save_prompt">Save the edited video as a new copy or overwrite the original?</string>+ <!-- Save dialog button: save as a new copy. Verb phrase -->+ <string name="video_save_copy">Save as copy</string>+ <!-- Save dialog button: overwrite the original video. Verb -->+ <string name="video_overwrite">Overwrite</string>+ <!-- Progress dialog title while exporting the video. Verb -->+ <string name="video_exporting">Exporting…</string>+ <!-- Toast/message when video export fails. Sentence -->+ <string name="video_export_failed">Video export failed.</string>+ <!-- "Edit with" chooser label for the external video edit intent -->+ <string name="video_edit_with_label">Edit video with My App</string>+ <!-- Slider label: opacity of brush stroke. Noun --> <string name="opacity">Opacity</string> <!-- Slider label: thickness of brush/line. Noun -->