π End-to-end encrypted cloud for everything.
Dart 2faandroidauthye2eeencryptionend-to-end-encryptionfluttergolanggoogle-photosgoogle-photos-alternativeiosopensourcephotosprivacyprivacy-toolstypescriptzero-knowledge
[mobile][photos] Add speed editing for videos
r4khula61afb172740
diff --git a/mobile/apps/photos/changes/edit-video-speed.md b/mobile/apps/photos/changes/edit-video-speed.mdnew file mode 100644index 0000000000..1adc7d568f--- /dev/null+++ b/mobile/apps/photos/changes/edit-video-speed.md@@ -0,0 +1 @@+- Added speed controls to the video editor so videos can be saved in slow motion or fast motion.diff --git a/mobile/apps/photos/lib/ui/common/video_speed_options.dart b/mobile/apps/photos/lib/ui/common/video_speed_options.dartnew file mode 100644index 0000000000..1647b4e4c7--- /dev/null+++ b/mobile/apps/photos/lib/ui/common/video_speed_options.dart@@ -0,0 +1,76 @@+import 'package:ente_components/ente_components.dart';+import 'package:flutter/material.dart';++const videoSpeedOptions = [0.25, 0.5, 1.0, 1.5, 2.0];++class VideoSpeedOptions extends StatelessWidget {+ const VideoSpeedOptions({+ super.key,+ required this.currentSpeed,+ required this.onSpeedSelected,+ });++ final double currentSpeed;+ final ValueChanged<double> onSpeedSelected;++ @override+ Widget build(BuildContext context) {+ return Row(+ children: [+ for (int i = 0; i < videoSpeedOptions.length; i++) ...[+ Expanded(+ child: _SpeedChip(+ speed: videoSpeedOptions[i],+ isSelected: currentSpeed == videoSpeedOptions[i],+ onTap: () => onSpeedSelected(videoSpeedOptions[i]),+ ),+ ),+ if (i < videoSpeedOptions.length - 1) const SizedBox(width: 4),+ ],+ ],+ );+ }+}++class _SpeedChip extends StatelessWidget {+ const _SpeedChip({+ required this.speed,+ required this.isSelected,+ required this.onTap,+ });++ final double speed;+ final bool isSelected;+ final VoidCallback onTap;++ @override+ Widget build(BuildContext context) {+ final colors = context.componentColors;+ final label = speed == 1.0 ? '1x' : '${speed}x';+ return Semantics(+ button: true,+ selected: isSelected,+ label: label,+ excludeSemantics: true,+ child: GestureDetector(+ onTap: onTap,+ child: Container(+ alignment: Alignment.center,+ decoration: BoxDecoration(+ color: isSelected+ ? colors.fillBase.withValues(alpha: 0.9)+ : colors.fillLight,+ borderRadius: BorderRadius.circular(25),+ ),+ padding: const EdgeInsets.symmetric(vertical: 8),+ child: Text(+ label,+ style: TextStyles.body.copyWith(+ color: isSelected ? colors.textReverse : colors.iconColor,+ ),+ ),+ ),+ ),+ );+ }+}diff --git a/mobile/apps/photos/lib/ui/tools/editor/export_video_service.dart b/mobile/apps/photos/lib/ui/tools/editor/export_video_service.dartindex 91026382a5..35dac68bd6 100644--- a/mobile/apps/photos/lib/ui/tools/editor/export_video_service.dart+++ b/mobile/apps/photos/lib/ui/tools/editor/export_video_service.dart@@ -33,7 +33,9 @@ class ExportService {final filters = buildFfmpegVideoFilters(crop: crop,rotation: controller.rotation,+ speed: controller.speed,);+ final audioFilters = buildFfmpegAudioTempoFilters(controller.speed);final start = _seconds(controller.startTrim);final duration = _seconds(controller.trimmedDuration);@@ -41,15 +43,16 @@ class ExportService {'-y','-ss',start,- '-i',- controller.file.path,'-t',duration,+ '-i',+ controller.file.path,'-map','0:v:0','-map','0:a?',if (filters.isNotEmpty) ...['-vf', filters.join(',')],+ if (audioFilters.isNotEmpty) ...['-af', audioFilters.join(',')],'-c:v','libx264','-preset',@@ -69,7 +72,7 @@ class ExportService {return FfmpegVideoExportPlan(arguments: arguments,outputPath: outputPath,- duration: controller.trimmedDuration,+ duration: controller.editedDuration,);}@@ -152,6 +155,7 @@ class ExportService {List<String> buildFfmpegVideoFilters({required CropCalculation? crop,required int rotation,+ double speed = 1.0,}) {final filters = <String>[];if (crop != null) filters.add(crop.toFFmpegFilter());@@ -169,5 +173,28 @@ List<String> buildFfmpegVideoFilters({throw ArgumentError.value(rotation, 'rotation');}filters.add('scale=trunc(iw/2)*2:trunc(ih/2)*2');+ if (speed != 1.0) {+ filters.add('setpts=(PTS-STARTPTS)/$speed');+ }+ return filters;+}++List<String> buildFfmpegAudioTempoFilters(double speed) {+ if (!speed.isFinite || speed <= 0) {+ throw ArgumentError.value(speed, 'speed');+ }+ if (speed == 1.0) return [];++ final filters = <String>[];+ var remaining = speed;+ while (remaining < 0.5) {+ filters.add('atempo=0.5');+ remaining /= 0.5;+ }+ while (remaining > 2.0) {+ filters.add('atempo=2.0');+ remaining /= 2.0;+ }+ filters.add('atempo=$remaining');return filters;}diff --git a/mobile/apps/photos/lib/ui/tools/editor/video_editor/video_editor_bottom_action.dart b/mobile/apps/photos/lib/ui/tools/editor/video_editor/video_editor_bottom_action.dartindex f52b6a27d9..26286e4bf4 100644--- a/mobile/apps/photos/lib/ui/tools/editor/video_editor/video_editor_bottom_action.dart+++ b/mobile/apps/photos/lib/ui/tools/editor/video_editor/video_editor_bottom_action.dart@@ -6,14 +6,18 @@ class VideoEditorBottomAction extends StatelessWidget {super.key,required this.label,this.icon,+ this.hugeIcon,this.svgPath,this.child,required this.onPressed,this.isSelected = false,- }) : assert(icon != null || svgPath != null || child != null);+ }) : assert(+ icon != null || hugeIcon != null || svgPath != null || child != null,+ );final String label;final IconData? icon;+ final List<List<dynamic>>? hugeIcon;final String? svgPath;final Widget? child;final VoidCallback onPressed;@@ -26,6 +30,7 @@ class VideoEditorBottomAction extends StatelessWidget {onTap: onPressed,svgPath: svgPath,icon: icon,+ hugeIcon: hugeIcon,size: 60,isSelected: isSelected,child: child,diff --git a/mobile/apps/photos/lib/ui/tools/editor/video_editor/video_editor_controller.dart b/mobile/apps/photos/lib/ui/tools/editor/video_editor/video_editor_controller.dartindex 0e35d14e59..1aec376db1 100644--- a/mobile/apps/photos/lib/ui/tools/editor/video_editor/video_editor_controller.dart+++ b/mobile/apps/photos/lib/ui/tools/editor/video_editor/video_editor_controller.dart@@ -8,6 +8,9 @@ import 'package:video_player/video_player.dart';enum VideoRotationDirection { left, right }+Duration scaledVideoDuration(Duration duration, double speed) =>+ Duration(microseconds: (duration.inMicroseconds / speed).round());+class VideoMinimumDurationError implements Exception {const VideoMinimumDurationError(this.minimum, this.actual);@@ -23,6 +26,7 @@ class VideoEditorState {required this.maxCrop,required this.rotation,required this.preferredCropAspectRatio,+ required this.speed,});final Duration startTrim;@@ -31,6 +35,7 @@ class VideoEditorState {final Offset maxCrop;final int rotation;final double? preferredCropAspectRatio;+ final double speed;}class VideoEditorController extends ChangeNotifier {@@ -53,6 +58,7 @@ class VideoEditorController extends ChangeNotifier {Offset _maxCrop = const Offset(1, 1);int _rotation = 0;double? _preferredCropAspectRatio;+ double _speed = 1.0;bool get initialized => _initialized;NativeVideoInfo get videoInfo => _videoInfo!;@@ -68,6 +74,20 @@ class VideoEditorController extends ChangeNotifier {Offset get maxCrop => _maxCrop;int get rotation => _rotation;double? get preferredCropAspectRatio => _preferredCropAspectRatio;+ double get speed => _speed;+ Duration get editedDuration => scaledVideoDuration(trimmedDuration, _speed);++ void updateSpeed(double speed) {+ if (!speed.isFinite || speed <= 0) {+ throw ArgumentError.value(speed, 'speed');+ }+ if (_speed == speed) return;+ _speed = speed;+ if (video.value.isInitialized) {+ unawaited(video.setPlaybackSpeed(speed));+ }+ notifyListeners();+ }set preferredCropAspectRatio(double? ratio) {if (ratio != null && (!ratio.isFinite || ratio <= 0)) {@@ -158,6 +178,7 @@ class VideoEditorController extends ChangeNotifier {maxCrop: _maxCrop,rotation: _rotation,preferredCropAspectRatio: _preferredCropAspectRatio,+ speed: _speed,);void restore(VideoEditorState state) {@@ -167,6 +188,7 @@ class VideoEditorController extends ChangeNotifier {_maxCrop = state.maxCrop;_rotation = state.rotation;_preferredCropAspectRatio = state.preferredCropAspectRatio;+ updateSpeed(state.speed);if (videoPosition < _startTrim || videoPosition > _endTrim) {unawaited(video.seekTo(_startTrim));}diff --git a/mobile/apps/photos/lib/ui/tools/editor/video_editor/video_editor_player_control.dart b/mobile/apps/photos/lib/ui/tools/editor/video_editor/video_editor_player_control.dartindex 41c9a835cf..6bb37eaa18 100644--- a/mobile/apps/photos/lib/ui/tools/editor/video_editor/video_editor_player_control.dart+++ b/mobile/apps/photos/lib/ui/tools/editor/video_editor/video_editor_player_control.dart@@ -14,8 +14,11 @@ class VideoEditorPlayerControl extends StatelessWidget {child: AnimatedBuilder(animation: Listenable.merge([controller, controller.video]),builder: (_, _) {- final duration = controller.trimmedDuration;- Duration pos = controller.videoPosition - controller.startTrim;+ final duration = controller.editedDuration;+ Duration pos = scaledVideoDuration(+ controller.videoPosition - controller.startTrim,+ controller.speed,+ );if (pos.isNegative) {pos = Duration.zero;} else if (pos > duration) {diff --git a/mobile/apps/photos/lib/ui/tools/editor/video_editor_page.dart b/mobile/apps/photos/lib/ui/tools/editor/video_editor_page.dartindex 94de533dd0..5d0b0f4277 100644--- a/mobile/apps/photos/lib/ui/tools/editor/video_editor_page.dart+++ b/mobile/apps/photos/lib/ui/tools/editor/video_editor_page.dart@@ -5,6 +5,7 @@ import "dart:math";import "package:ente_pure_utils/ente_pure_utils.dart";import "package:ente_strings/ente_strings.dart";import 'package:flutter/material.dart';+import 'package:hugeicons/hugeicons.dart';import "package:logging/logging.dart";import 'package:native_video_editor/native_video_editor.dart';import 'package:path/path.dart' as path;@@ -32,6 +33,7 @@ import "package:photos/ui/tools/editor/video_editor/video_editor_main_actions.daimport "package:photos/ui/tools/editor/video_editor/video_editor_player_control.dart";import "package:photos/ui/tools/editor/video_editor/video_editor_widgets.dart";import "package:photos/ui/tools/editor/video_rotate_page.dart";+import 'package:photos/ui/tools/editor/video_speed_page.dart';import "package:photos/ui/tools/editor/video_trim_page.dart";import "package:photos/ui/viewer/file/detail_page.dart";import "package:photos/utils/gallery_save_title.dart";@@ -222,6 +224,15 @@ class _VideoEditorPageState extends State<VideoEditorPage> {VideoRotatePage(controller: _controller!),),),+ const SizedBox(width: 24),+ VideoEditorBottomAction(+ label: context.strings.speed,+ hugeIcon:+ HugeIcons.strokeRoundedDashboardSpeed02,+ onPressed: () => _openSubEditor(+ VideoSpeedPage(controller: _controller!),+ ),+ ),],),const SizedBox(height: 12),@@ -240,9 +251,11 @@ class _VideoEditorPageState extends State<VideoEditorPage> {if (!await ensurePhotoLibraryAddPermission(context)) return;if (!mounted) return;- final shouldUseNative = flagService.internalUser- ? _useNativeExport- : flagService.useNativeVideoEditor;+ final shouldUseNative =+ (flagService.internalUser+ ? _useNativeExport+ : flagService.useNativeVideoEditor) &&+ _controller!.speed == 1.0;_logEditState(shouldUseNative: shouldUseNative);@@ -539,6 +552,7 @@ class _VideoEditorPageState extends State<VideoEditorPage> {final startTrimMs = controller.startTrim.inMilliseconds;final endTrimMs = controller.endTrim.inMilliseconds;final trimmedDurationMs = controller.trimmedDuration.inMilliseconds;+ final editedDurationMs = controller.editedDuration.inMilliseconds;final videoDurationMs = controller.videoDuration.inMilliseconds;String fileSpaceCropSummary;try {@@ -559,6 +573,7 @@ class _VideoEditorPageState extends State<VideoEditorPage> {"trim={startMs:$startTrimMs, endMs:$endTrimMs, durationMs:$trimmedDurationMs, ""minMs:0, maxMs:$videoDurationMs, ""videoDurationMs:$videoDurationMs} "+ "speed=${controller.speed}, editedDurationMs=$editedDurationMs ""crop={$cropInfo}",);}diff --git a/mobile/apps/photos/lib/ui/tools/editor/video_speed_page.dart b/mobile/apps/photos/lib/ui/tools/editor/video_speed_page.dartnew file mode 100644index 0000000000..feafc024a0--- /dev/null+++ b/mobile/apps/photos/lib/ui/tools/editor/video_speed_page.dart@@ -0,0 +1,28 @@+import 'package:flutter/material.dart';+import 'package:photos/ui/common/video_speed_options.dart';+import 'package:photos/ui/tools/editor/video_editor/video_editor_controller.dart';+import 'package:photos/ui/tools/editor/video_editor/video_editor_widgets.dart';++class VideoSpeedPage extends StatelessWidget {+ const VideoSpeedPage({super.key, required this.controller});++ final VideoEditorController controller;++ @override+ Widget build(BuildContext context) {+ return VideoEditorSubPage(+ controller: controller,+ preview: VideoEditorPreview(controller: controller),+ actions: Padding(+ padding: const EdgeInsets.fromLTRB(16, 48, 16, 12),+ child: AnimatedBuilder(+ animation: controller,+ builder: (_, _) => VideoSpeedOptions(+ currentSpeed: controller.speed,+ onSpeedSelected: controller.updateSpeed,+ ),+ ),+ ),+ );+ }+}diff --git a/mobile/apps/photos/lib/ui/viewer/file/video_control/video_speed_bottom_sheet.dart b/mobile/apps/photos/lib/ui/viewer/file/video_control/video_speed_bottom_sheet.dartindex ab51336425..7dbb317320 100644--- a/mobile/apps/photos/lib/ui/viewer/file/video_control/video_speed_bottom_sheet.dart+++ b/mobile/apps/photos/lib/ui/viewer/file/video_control/video_speed_bottom_sheet.dart@@ -1,6 +1,7 @@import "package:ente_components/ente_components.dart";import "package:ente_strings/ente_strings.dart";import "package:flutter/material.dart";+import 'package:photos/ui/common/video_speed_options.dart';Future<void> showVideoSpeedBottomSheet(BuildContext context, {@@ -11,79 +12,13 @@ Future<void> showVideoSpeedBottomSheet(context: context,builder: (context) => BottomSheetComponent(title: context.strings.playbackSpeed,- content: _VideoSpeedBottomSheetContent(+ content: VideoSpeedOptions(currentSpeed: currentSpeed,- onSpeedSelected: onSpeedSelected,+ onSpeedSelected: (speed) {+ onSpeedSelected(speed);+ Navigator.of(context).pop();+ },),),);}--class _VideoSpeedBottomSheetContent extends StatelessWidget {- const _VideoSpeedBottomSheetContent({- required this.currentSpeed,- required this.onSpeedSelected,- });-- final double currentSpeed;- final void Function(double) onSpeedSelected;-- static const _speeds = [0.25, 0.5, 1.0, 1.5, 2.0];-- @override- Widget build(BuildContext context) {- return Row(- children: [- for (int i = 0; i < _speeds.length; i++) ...[- Expanded(- child: _SpeedChip(- label: _speeds[i] == 1.0 ? "1x" : "${_speeds[i]}x",- isSelected: currentSpeed == _speeds[i],- onTap: () {- onSpeedSelected(_speeds[i]);- Navigator.of(context).pop();- },- ),- ),- if (i < _speeds.length - 1) const SizedBox(width: 4),- ],- ],- );- }-}--class _SpeedChip extends StatelessWidget {- const _SpeedChip({- required this.label,- required this.isSelected,- required this.onTap,- });-- final String label;- final bool isSelected;- final VoidCallback onTap;-- @override- Widget build(BuildContext context) {- final colors = context.componentColors;- final selectedBackground = colors.fillBase.withValues(alpha: 0.9);- final selectedForeground = colors.textReverse;- return GestureDetector(- onTap: onTap,- child: Container(- alignment: Alignment.center,- decoration: BoxDecoration(- color: isSelected ? selectedBackground : colors.fillLight,- borderRadius: BorderRadius.circular(25),- ),- padding: const EdgeInsets.symmetric(vertical: 8),- child: Text(- label,- style: TextStyles.body.copyWith(- color: isSelected ? selectedForeground : colors.iconColor,- ),- ),- ),- );- }-}diff --git a/mobile/apps/photos/test/ui/tools/editor/video_editor_contract_test.dart b/mobile/apps/photos/test/ui/tools/editor/video_editor_contract_test.dartindex 6aa0e32374..18103284e9 100644--- a/mobile/apps/photos/test/ui/tools/editor/video_editor_contract_test.dart+++ b/mobile/apps/photos/test/ui/tools/editor/video_editor_contract_test.dart@@ -55,6 +55,20 @@ void main() {'scale=trunc(iw/2)*2:trunc(ih/2)*2',]);});++ test('applies speed after spatial edits', () {+ expect(buildFfmpegVideoFilters(crop: null, rotation: 90, speed: 2), [+ 'transpose=1',+ 'scale=trunc(iw/2)*2:trunc(ih/2)*2',+ 'setpts=(PTS-STARTPTS)/2.0',+ ]);+ });+ });++ test('audio tempo chains supported filters for quarter speed', () {+ expect(buildFfmpegAudioTempoFilters(0.25), ['atempo=0.5', 'atempo=0.5']);+ expect(buildFfmpegAudioTempoFilters(2), ['atempo=2.0']);+ expect(buildFfmpegAudioTempoFilters(1), isEmpty);});test('FFmpeg plan preserves file paths as structured arguments', () {@@ -72,4 +86,28 @@ void main() {expect(plan.arguments, contains('/tmp/output video.mp4'));expect(plan.arguments, containsAllInOrder(['-map', '0:a?']));});++ test('FFmpeg reads only the trimmed source before changing speed', () {+ final controller = VideoEditorController.file(File('/tmp/input.mp4'));+ addTearDown(controller.dispose);+ controller.updateSpeed(0.25);++ final plan = ExportService.createPlan(+ controller: controller,+ outputPath: '/tmp/output.mp4',+ );++ expect(plan.arguments, containsAllInOrder(['-t', '0.000000', '-i']));+ expect(+ plan.arguments,+ containsAllInOrder([+ '-vf',+ 'scale=trunc(iw/2)*2:trunc(ih/2)*2,setpts=(PTS-STARTPTS)/0.25',+ ]),+ );+ expect(+ plan.arguments,+ containsAllInOrder(['-af', 'atempo=0.5,atempo=0.5']),+ );+ });}diff --git a/mobile/apps/photos/test/ui/tools/editor/video_editor_controller_test.dart b/mobile/apps/photos/test/ui/tools/editor/video_editor_controller_test.dartindex 14af0d7ca8..b1c5b29a6c 100644--- a/mobile/apps/photos/test/ui/tools/editor/video_editor_controller_test.dart+++ b/mobile/apps/photos/test/ui/tools/editor/video_editor_controller_test.dart@@ -1,3 +1,4 @@+import 'dart:io';import 'dart:ui';import 'package:flutter_test/flutter_test.dart';@@ -7,6 +8,31 @@ import 'package:photos/ui/tools/editor/video_editor/video_editor_widgets.dart';void main() {const sourceCrop = Rect.fromLTRB(0.1, 0.2, 0.6, 0.8);+ test('speed can be canceled or kept through editor snapshots', () {+ final controller = VideoEditorController.file(File('unused.mp4'));+ addTearDown(controller.dispose);+ final initialState = controller.snapshot();++ controller.updateSpeed(0.5);+ expect(controller.speed, 0.5);+ controller.restore(initialState);+ expect(controller.speed, 1.0);++ controller.updateSpeed(2.0);+ expect(controller.snapshot().speed, 2.0);+ expect(() => controller.updateSpeed(0), throwsArgumentError);+ expect(() => controller.updateSpeed(double.nan), throwsArgumentError);+ });++ test('edited durations follow the chosen speed', () {+ const sourceDuration = Duration(seconds: 8);+ expect(+ scaledVideoDuration(sourceDuration, 0.25),+ const Duration(seconds: 32),+ );+ expect(scaledVideoDuration(sourceDuration, 2), const Duration(seconds: 4));+ });+test('clockwise crop rotation preserves the selected visual region', () {_expectRectClose(rotateNormalizedRect(sourceCrop, 90),diff --git a/mobile/apps/photos/test/ui/tools/editor/video_speed_options_test.dart b/mobile/apps/photos/test/ui/tools/editor/video_speed_options_test.dartnew file mode 100644index 0000000000..c690a614ce--- /dev/null+++ b/mobile/apps/photos/test/ui/tools/editor/video_speed_options_test.dart@@ -0,0 +1,37 @@+import 'package:flutter/material.dart';+import 'package:flutter_test/flutter_test.dart';+import 'package:photos/ente_theme_data.dart';+import 'package:photos/ui/common/video_speed_options.dart';++void main() {+ testWidgets('selecting a speed updates the visible choice', (tester) async {+ double selectedSpeed = 1.0;++ await tester.pumpWidget(+ MaterialApp(+ theme: darkThemeData,+ home: Scaffold(+ body: StatefulBuilder(+ builder: (context, setState) => VideoSpeedOptions(+ currentSpeed: selectedSpeed,+ onSpeedSelected: (speed) {+ setState(() => selectedSpeed = speed);+ },+ ),+ ),+ ),+ ),+ );++ expect(find.text('1x'), findsOneWidget);+ await tester.tap(find.text('0.5x'));+ await tester.pump();+ expect(selectedSpeed, 0.5);+ expect(+ tester+ .widget<VideoSpeedOptions>(find.byType(VideoSpeedOptions))+ .currentSpeed,+ 0.5,+ );+ });+}diff --git a/mobile/packages/strings/lib/l10n/arb/strings_en.arb b/mobile/packages/strings/lib/l10n/arb/strings_en.arbindex b809d66f9d..e4bbd221ad 100644--- a/mobile/packages/strings/lib/l10n/arb/strings_en.arb+++ b/mobile/packages/strings/lib/l10n/arb/strings_en.arb@@ -4208,6 +4208,7 @@"sortNewestFirst": "Newest first","sortOldestFirst": "Oldest first","sortZToA": "Z-A",+ "speed": "Speed","sportsAction": "Game on","sportsWithThem": "Sports with {name}","@sportsWithThem": {