Skip to content

armgit / ente

Public Imported from GitHub
0

πŸ’š End-to-end encrypted cloud for everything.

[mob][photos] native video editor (#7437)

Prateek Sunal0e0853fc1ead
diff --git a/mobile/apps/photos/ios/Runner.xcodeproj/project.pbxproj b/mobile/apps/photos/ios/Runner.xcodeproj/project.pbxproj
index 8dadf6e970..efd7fe5941 100644
--- a/mobile/apps/photos/ios/Runner.xcodeproj/project.pbxproj
+++ b/mobile/apps/photos/ios/Runner.xcodeproj/project.pbxproj
@@ -556,6 +556,7 @@
"${BUILT_PRODUCTS_DIR}/motionphoto/motionphoto.framework",
"${BUILT_PRODUCTS_DIR}/move_to_background/move_to_background.framework",
"${BUILT_PRODUCTS_DIR}/nanopb/nanopb.framework",
+ "${BUILT_PRODUCTS_DIR}/native_video_editor/native_video_editor.framework",
"${BUILT_PRODUCTS_DIR}/native_video_player/native_video_player.framework",
"${BUILT_PRODUCTS_DIR}/objective_c/objective_c.framework",
"${BUILT_PRODUCTS_DIR}/open_mail_app/open_mail_app.framework",
@@ -655,6 +656,7 @@
"${TARGET_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}/motionphoto.framework",
"${TARGET_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}/move_to_background.framework",
"${TARGET_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}/nanopb.framework",
+ "${TARGET_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}/native_video_editor.framework",
"${TARGET_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}/native_video_player.framework",
"${TARGET_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}/objective_c.framework",
"${TARGET_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}/open_mail_app.framework",
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.dart
index 92ded1b497..d1cf9cc405 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
@@ -1,5 +1,4 @@
import 'dart:async';
-import 'dart:developer';
import 'dart:io';
import 'package:ffmpeg_kit_flutter/ffmpeg_kit.dart';
@@ -14,11 +13,8 @@ class ExportService {
static final _logger = Logger('ExportService');
static Future<void> dispose() async {
- _logger.info('[FFmpeg] Disposing export service');
final executions = await FFmpegKit.listSessions();
- _logger.info('[FFmpeg] Found ${executions.length} active sessions');
if (executions.isNotEmpty) {
- _logger.info('[FFmpeg] Cancelling all sessions');
await FFmpegKit.cancel();
}
}
@@ -29,8 +25,6 @@ class ExportService {
void Function(Object, StackTrace)? onError,
void Function(Statistics)? onProgress,
}) async {
- log('FFmpeg start process with command = ${execute.command}');
-
final completer = Completer<void>();
FFmpegSession? activeSession;
@@ -155,4 +149,60 @@ class ExportService {
}
}
}
+
+ /// Export video using FFmpeg
+ static Future<File> exportVideo({
+ required VideoEditorController controller,
+ required String outputPath,
+ void Function(double)? onProgress,
+ void Function(Object, StackTrace)? onError,
+ }) async {
+ final config = VideoFFmpegVideoEditorConfig(
+ controller,
+ format: VideoExportFormat.mp4,
+ commandBuilder: (config, videoPath, outputPath) {
+ final List<String> filters = config.getExportFilters();
+
+ final String startTrimCmd = "-ss ${controller.startTrim}";
+ final String toTrimCmd = "-t ${controller.trimmedDuration}";
+
+ // Use hardware acceleration if available
+ String hwAccel = "";
+ if (Platform.isIOS) {
+ hwAccel = "-hwaccel videotoolbox";
+ } else if (Platform.isAndroid) {
+ hwAccel = "-hwaccel mediacodec";
+ }
+
+ return '$hwAccel $startTrimCmd -i $videoPath $toTrimCmd ${config.filtersCmd(filters)} -c:v libx264 -preset ultrafast -c:a aac $outputPath';
+ },
+ );
+
+ final completer = Completer<File>();
+
+ await runFFmpegCommand(
+ await config.getExecuteConfig(),
+ onProgress: (Statistics stats) {
+ if (onProgress != null) {
+ final progress = config.getFFmpegProgress(stats.getTime().toInt());
+ onProgress(progress);
+ }
+ },
+ onError: (error, stackTrace) {
+ if (onError != null) {
+ onError(error, stackTrace);
+ }
+ if (!completer.isCompleted) {
+ completer.completeError(error, stackTrace);
+ }
+ },
+ onCompleted: (File file) {
+ if (!completer.isCompleted) {
+ completer.complete(file);
+ }
+ },
+ );
+
+ return completer.future;
+ }
}
diff --git a/mobile/apps/photos/lib/ui/tools/editor/native_video_export_service.dart b/mobile/apps/photos/lib/ui/tools/editor/native_video_export_service.dart
new file mode 100644
index 0000000000..83c74bac9a
--- /dev/null
+++ b/mobile/apps/photos/lib/ui/tools/editor/native_video_export_service.dart
@@ -0,0 +1,255 @@
+import 'dart:async';
+import 'dart:io';
+import 'dart:ui';
+
+import 'package:native_video_editor/native_video_editor.dart';
+import 'package:photos/ui/tools/editor/export_video_service.dart';
+import 'package:photos/ui/tools/editor/video_crop_util.dart';
+import 'package:video_editor/video_editor.dart';
+
+class DebugExportSummary {
+ DebugExportSummary({
+ required this.videoSize,
+ required this.trimStart,
+ required this.trimEnd,
+ required this.nativeRotateDegrees,
+ required this.nativeDisplayCrop,
+ required this.nativeFileCrop,
+ required this.nativeOutputSize,
+ required this.ffmpegFileCrop,
+ required this.ffmpegCropFilter,
+ required this.ffmpegCommand,
+ });
+
+ final Size videoSize;
+ final Duration? trimStart;
+ final Duration? trimEnd;
+ final int? nativeRotateDegrees;
+ final Rect? nativeDisplayCrop;
+ final CropCalculation? nativeFileCrop;
+ final Size? nativeOutputSize;
+ final CropCalculation? ffmpegFileCrop;
+ final String? ffmpegCropFilter;
+ final String? ffmpegCommand;
+}
+
+/// Service that uses native video editing operations when possible
+/// Falls back to FFmpeg for operations that require re-encoding
+class NativeVideoExportService {
+ static const Duration _nativeFallbackThreshold = Duration(seconds: 3);
+
+ static Future<DebugExportSummary> buildDebugSummary({
+ required VideoEditorController controller,
+ }) async {
+ final videoSize = controller.video.value.size;
+ final Duration? trimStart =
+ controller.isTrimmed ? controller.startTrim : null;
+ final Duration? trimEnd = controller.isTrimmed ? controller.endTrim : null;
+ final int? nativeRotateDegrees =
+ controller.rotation != 0 ? controller.rotation : null;
+
+ Rect? nativeDisplayCrop;
+ CropCalculation? nativeFileCrop;
+ Size? nativeOutputSize;
+ CropCalculation? ffmpegFileCrop;
+
+ final needsCrop = controller.minCrop != Offset.zero ||
+ controller.maxCrop != const Offset(1.0, 1.0);
+
+ if (needsCrop) {
+ nativeDisplayCrop = VideoCropUtil.calculateDisplaySpaceCropRect(
+ controller: controller,
+ );
+ try {
+ nativeFileCrop = VideoCropUtil.calculateFileSpaceCrop(
+ controller: controller,
+ );
+ } catch (_) {
+ nativeFileCrop = null;
+ }
+
+ if (nativeFileCrop != null) {
+ nativeOutputSize = Size(
+ nativeFileCrop.width.toDouble(),
+ nativeFileCrop.height.toDouble(),
+ );
+ if (nativeRotateDegrees != null && nativeRotateDegrees % 180 != 0) {
+ nativeOutputSize = Size(
+ nativeOutputSize.height,
+ nativeOutputSize.width,
+ );
+ }
+ }
+
+ try {
+ ffmpegFileCrop = VideoCropUtil.calculateFileSpaceCrop(
+ controller: controller,
+ );
+ } catch (_) {
+ ffmpegFileCrop = null;
+ }
+ }
+
+ String? ffmpegCropFilter;
+ if (ffmpegFileCrop != null) {
+ ffmpegCropFilter = ffmpegFileCrop.toFFmpegFilter();
+ }
+
+ // Build approximate FFmpeg command for debugging
+ String? ffmpegCommand;
+ if (ffmpegCropFilter != null || trimStart != null || trimEnd != null) {
+ final List<String> cmdParts = ['ffmpeg -i input.mp4'];
+
+ if (trimStart != null || trimEnd != null) {
+ final ss = trimStart?.inMilliseconds ?? 0;
+ final to =
+ trimEnd?.inMilliseconds ?? controller.videoDuration.inMilliseconds;
+ cmdParts.add('-ss ${ss}ms -to ${to}ms');
+ }
+
+ final vfFilters = <String>[];
+ if (ffmpegCropFilter != null) {
+ vfFilters.add(ffmpegCropFilter);
+ }
+ vfFilters.add('setpts=PTS-STARTPTS');
+
+ cmdParts.add('-vf "${vfFilters.join(',')}"');
+ cmdParts.add('-c:v libx264 -preset ultrafast -c:a copy output.mp4');
+
+ ffmpegCommand = cmdParts.join(' ');
+ }
+
+ return DebugExportSummary(
+ videoSize: videoSize,
+ trimStart: trimStart,
+ trimEnd: trimEnd,
+ nativeRotateDegrees: nativeRotateDegrees,
+ nativeDisplayCrop: nativeDisplayCrop,
+ nativeFileCrop: nativeFileCrop,
+ nativeOutputSize: nativeOutputSize,
+ ffmpegFileCrop: ffmpegFileCrop,
+ ffmpegCropFilter: ffmpegCropFilter,
+ ffmpegCommand: ffmpegCommand,
+ );
+ }
+
+ /// Export video using native operations
+ static Future<File> exportVideo({
+ required VideoEditorController controller,
+ required String outputPath,
+ void Function(double)? onProgress,
+ void Function(Object, StackTrace)? onError,
+ }) async {
+ final startTime = DateTime.now();
+ try {
+ final inputPath = controller.file.path;
+
+ // Always use the unified native operations path
+ final result = await _performNativeOperations(
+ inputPath: inputPath,
+ outputPath: outputPath,
+ controller: controller,
+ onProgress: onProgress,
+ );
+
+ return File(result.outputPath);
+ } catch (error, stackTrace) {
+ final elapsed = DateTime.now().difference(startTime);
+
+ if (onError != null) {
+ onError(error, stackTrace);
+ }
+
+ // If native export fails quickly, attempt FFmpeg fallback automatically
+ if (elapsed <= _nativeFallbackThreshold) {
+ return await ExportService.exportVideo(
+ controller: controller,
+ outputPath: outputPath,
+ onProgress: onProgress,
+ onError: onError,
+ );
+ }
+
+ rethrow;
+ }
+ }
+
+ /// Perform native video operations
+ static Future<VideoEditResult> _performNativeOperations({
+ required String inputPath,
+ required String outputPath,
+ required VideoEditorController controller,
+ void Function(double)? onProgress,
+ }) async {
+ // Use the combined native path only when needed; otherwise do a fast copy.
+ // Note: despite legacy comments, Android cropping is supported via Media3
+ // Transformer, so we keep native for crop/trim/rotate combinations.
+ final needsCrop = controller.minCrop != Offset.zero ||
+ controller.maxCrop != const Offset(1.0, 1.0);
+ final needsRotate = controller.rotation != 0;
+ final needsTrim = controller.isTrimmed;
+
+ if (!(needsCrop || needsRotate || needsTrim)) {
+ await File(inputPath).copy(outputPath);
+ return VideoEditResult(
+ outputPath: outputPath,
+ isReEncoded: false,
+ processingTime: Duration.zero,
+ );
+ }
+
+ Duration? trimStart;
+ Duration? trimEnd;
+ if (needsTrim) {
+ trimStart = controller.startTrim;
+ trimEnd = controller.endTrim;
+ }
+
+ final int? rotateDegrees = needsRotate ? controller.rotation : null;
+ Rect? cropRect;
+ if (needsCrop) {
+ // Always compute a display-space crop; both iOS & Android plugins
+ // take display coordinates and do the right transform internally.
+ final displayCrop = VideoCropUtil.calculateDisplaySpaceCropRect(
+ controller: controller,
+ );
+ if (displayCrop.width <= 0 || displayCrop.height <= 0) {
+ throw ArgumentError('Invalid crop rectangle computed: $displayCrop');
+ }
+ cropRect = displayCrop;
+ }
+
+ final result = await NativeVideoEditor.processVideo(
+ inputPath: inputPath,
+ outputPath: outputPath,
+ trimStart: trimStart,
+ trimEnd: trimEnd,
+ rotateDegrees: rotateDegrees,
+ cropRect: cropRect,
+ onProgress: onProgress,
+ );
+ return result;
+ }
+
+ /// Get video information using native methods
+ static Future<Map<String, dynamic>> getVideoInfo(String videoPath) async {
+ try {
+ return await NativeVideoEditor.getVideoInfo(videoPath);
+ } catch (e) {
+ // Fallback to MediaInfo or FFprobe if needed
+ return {};
+ }
+ }
+
+ /// Cancel any ongoing export operation
+ static Future<void> cancelExport() async {
+ try {
+ // Cancel native operation
+ await NativeVideoEditor.cancelProcessing();
+ } catch (e) {
+ // Silently fail
+ }
+ }
+
+ // No extra helpers needed; crop mapping is centralized in VideoCropUtil
+}
diff --git a/mobile/apps/photos/lib/ui/tools/editor/video_crop_page.dart b/mobile/apps/photos/lib/ui/tools/editor/video_crop_page.dart
index 0df0c8a66b..431d6aa5ff 100644
--- a/mobile/apps/photos/lib/ui/tools/editor/video_crop_page.dart
+++ b/mobile/apps/photos/lib/ui/tools/editor/video_crop_page.dart
@@ -9,11 +9,9 @@ import "package:photos/ui/tools/editor/video_editor/video_editor_player_control.
import 'package:video_editor/video_editor.dart';
class VideoCropPage extends StatefulWidget {
- final int quarterTurnsForRotationCorrection;
const VideoCropPage({
super.key,
required this.controller,
- required this.quarterTurnsForRotationCorrection,
});
final VideoEditorController controller;
@@ -23,6 +21,46 @@ class VideoCropPage extends StatefulWidget {
}
class _VideoCropPageState extends State<VideoCropPage> {
+ CropValue? _selectedCropValue;
+
+ @override
+ void initState() {
+ super.initState();
+ _initializeSelectedValue();
+ }
+
+ void _initializeSelectedValue() {
+ final currentRatio = widget.controller.preferredCropAspectRatio;
+ if (currentRatio == null) {
+ _selectedCropValue = null;
+ return;
+ }
+
+ // Check if we need to account for rotation
+ final rotation = widget.controller.rotation;
+ final isRotated = rotation % 180 != 0;
+
+ // Find which crop value matches the current ratio
+ for (final value in CropValue.values) {
+ if (value == CropValue.original || value == CropValue.free) continue;
+
+ final valueRatio = value.getFraction()?.toDouble();
+ if (valueRatio == null) continue;
+
+ // For rotated videos, check both the normal and swapped ratios
+ if (isRotated && value != CropValue.ratio_1_1) {
+ final swappedRatio = 1.0 / valueRatio;
+ if ((currentRatio - swappedRatio).abs() < 0.01) {
+ _selectedCropValue = value;
+ return;
+ }
+ } else if ((currentRatio - valueRatio).abs() < 0.01) {
+ _selectedCropValue = value;
+ return;
+ }
+ }
+ }
+
@override
Widget build(BuildContext context) {
final colorScheme = getEnteColorScheme(context);
@@ -45,38 +83,31 @@ class _VideoCropPageState extends State<VideoCropPage> {
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
Expanded(
- child: ClipRRect(
- borderRadius: BorderRadius.circular(24),
- child: Stack(
- fit: StackFit.expand,
- children: [
- Positioned.fill(
- child: Hero(
- tag: "video-editor-preview",
- child: RotatedBox(
- quarterTurns:
- widget.quarterTurnsForRotationCorrection,
- child: CropGridViewer.edit(
- controller: widget.controller,
- rotateCropArea: false,
- margin: const EdgeInsets.symmetric(
- horizontal: 12,
- ),
- ),
+ child: Stack(
+ fit: StackFit.expand,
+ children: [
+ Positioned.fill(
+ child: Hero(
+ tag: "video-editor-preview",
+ child: CropGridViewer.edit(
+ controller: widget.controller,
+ rotateCropArea: true,
+ margin: const EdgeInsets.symmetric(
+ horizontal: 12,
),
),
),
- Align(
- alignment: Alignment.bottomCenter,
- child: Padding(
- padding: const EdgeInsets.only(bottom: 20),
- child: VideoEditorPlayerControl(
- controller: widget.controller,
- ),
+ ),
+ Align(
+ alignment: Alignment.bottomCenter,
+ child: Padding(
+ padding: const EdgeInsets.only(bottom: 20),
+ child: VideoEditorPlayerControl(
+ controller: widget.controller,
),
),
- ],
- ),
+ ),
+ ],
),
),
AnimatedBuilder(
@@ -105,19 +136,36 @@ class _VideoCropPageState extends State<VideoCropPage> {
}
Widget _buildCropButton(BuildContext context, CropValue value) {
- final f = value.getFraction();
+ final aspectRatio = value.getFraction()?.toDouble();
+
+ // Check if this button is selected
+ final isSelected = _selectedCropValue == value;
return VideoEditorBottomAction(
label: value.displayName,
- isSelected: value != CropValue.original &&
- widget.controller.preferredCropAspectRatio == f?.toDouble(),
+ isSelected: isSelected,
onPressed: () {
if (value == CropValue.original) {
widget.controller.updateCrop(Offset.zero, const Offset(1.0, 1.0));
widget.controller.cropAspectRatio(null);
+ _selectedCropValue = null;
+ setState(() {});
+ } else if (value == CropValue.free) {
+ widget.controller.preferredCropAspectRatio = null;
+ _selectedCropValue = value;
+ setState(() {});
+ } else if (aspectRatio != null) {
+ _selectedCropValue = value;
+
+ // Store the visual aspect ratio, accounting for rotation
+ final rotation = widget.controller.rotation;
+ final isRotated = rotation % 180 != 0;
+ final ratioToStore = (isRotated && value != CropValue.ratio_1_1)
+ ? 1.0 / aspectRatio
+ : aspectRatio;
+
+ widget.controller.preferredCropAspectRatio = ratioToStore;
setState(() {});
- } else {
- widget.controller.preferredCropAspectRatio = f?.toDouble();
}
},
svgPath: "assets/video-editor/video-crop-${value.name}-action.svg",
diff --git a/mobile/apps/photos/lib/ui/tools/editor/video_crop_util.dart b/mobile/apps/photos/lib/ui/tools/editor/video_crop_util.dart
new file mode 100644
index 0000000000..867f1f06aa
--- /dev/null
+++ b/mobile/apps/photos/lib/ui/tools/editor/video_crop_util.dart
@@ -0,0 +1,180 @@
+import 'dart:ui';
+import 'package:flutter/foundation.dart' show visibleForTesting;
+import 'package:video_editor/video_editor.dart';
+
+/// Crop calculation result
+class CropCalculation {
+ final int x;
+ final int y;
+ final int width;
+ final int height;
+
+ CropCalculation({
+ required this.x,
+ required this.y,
+ required this.width,
+ required this.height,
+ });
+
+ /// Create Rect from crop calculation
+ Rect toRect() => Rect.fromLTWH(
+ x.toDouble(),
+ y.toDouble(),
+ width.toDouble(),
+ height.toDouble(),
+ );
+
+ /// FFmpeg crop filter string: crop=w:h:x:y
+ String toFFmpegFilter() => 'crop=$width:$height:$x:$y';
+}
+
+class VideoCropException implements Exception {
+ VideoCropException(this.message);
+ final String message;
+
+ @override
+ String toString() => 'VideoCropException: $message';
+}
+
+/// Helpers to derive display- and file-space crop rectangles for native export
+class VideoCropUtil {
+ static double _clampNormalized(double value) {
+ return value.clamp(0.0, 1.0);
+ }
+
+ static int _clampInt(int value, int min, int max) {
+ if (value < min) return min;
+ if (value > max) return max;
+ return value;
+ }
+
+ /// Calculate the crop rectangle in display-space pixels.
+ ///
+ /// Returns a Rect in display-space so the native plugins can transform to file-space.
+ static Rect calculateDisplaySpaceCropRect({
+ required VideoEditorController controller,
+ }) {
+ return calculateDisplaySpaceCropRectFromData(
+ minCrop: controller.minCrop,
+ maxCrop: controller.maxCrop,
+ videoSize: controller.video.value.size,
+ );
+ }
+
+ /// Testability helper: bypasses controller and platform checks by accepting
+ /// raw crop data. Only used in unit tests.
+ @visibleForTesting
+ static Rect calculateDisplaySpaceCropRectFromData({
+ required Offset minCrop,
+ required Offset maxCrop,
+ required Size videoSize,
+ }) {
+ // Both platforms use same path - no rotation-specific logic
+ double minX = _clampNormalized(minCrop.dx);
+ double maxX = _clampNormalized(maxCrop.dx);
+ double minY = _clampNormalized(minCrop.dy);
+ double maxY = _clampNormalized(maxCrop.dy);
+
+ if (minX > maxX) {
+ final temp = minX;
+ minX = maxX;
+ maxX = temp;
+ }
+ if (minY > maxY) {
+ final temp = minY;
+ minY = maxY;
+ maxY = temp;
+ }
+
+ // Use raw video dimensions - no special handling for rotation
+ final displayWidth = videoSize.width;
+ final displayHeight = videoSize.height;
+
+ final widthNormalized = maxX - minX;
+ final heightNormalized = maxY - minY;
+
+ if (widthNormalized <= 0 || heightNormalized <= 0) {
+ throw VideoCropException('Invalid crop selection: zero or negative span');
+ }
+
+ final x = minX * displayWidth;
+ final y = minY * displayHeight;
+ final w = widthNormalized * displayWidth;
+ final h = heightNormalized * displayHeight;
+
+ if (w <= 0 || h <= 0) {
+ throw VideoCropException('Invalid crop rectangle after scaling');
+ }
+
+ return Rect.fromLTWH(x, y, w, h);
+ }
+
+ /// Convert the normalised crop selection into file-space coordinates.
+ static CropCalculation calculateFileSpaceCrop({
+ required VideoEditorController controller,
+ }) {
+ final videoSize = controller.video.value.size;
+ return calculateFileSpaceCropFromData(
+ minCrop: controller.minCrop,
+ maxCrop: controller.maxCrop,
+ videoSize: videoSize,
+ );
+ }
+
+ /// Testability helper: skips controller/platform usage to make unit tests
+ /// deterministic. Not for production callers.
+ @visibleForTesting
+ static CropCalculation calculateFileSpaceCropFromData({
+ required Offset minCrop,
+ required Offset maxCrop,
+ required Size videoSize,
+ }) {
+ final displayCrop = calculateDisplaySpaceCropRectFromData(
+ minCrop: minCrop,
+ maxCrop: maxCrop,
+ videoSize: videoSize,
+ );
+
+ // Both iOS and Android produce displayCrop in raw file dimensions,
+ // so we use standard file-space crop for both
+ return _calculateStandardFileSpaceCrop(videoSize, displayCrop);
+ }
+
+ static CropCalculation _calculateStandardFileSpaceCrop(
+ Size videoSize,
+ Rect displayCrop,
+ ) {
+ final minX = _clampInt(
+ displayCrop.left.round(),
+ 0,
+ videoSize.width.toInt(),
+ );
+ final minY = _clampInt(
+ displayCrop.top.round(),
+ 0,
+ videoSize.height.toInt(),
+ );
+ final maxX = _clampInt(
+ displayCrop.right.round(),
+ 0,
+ videoSize.width.toInt(),
+ );
+ final maxY = _clampInt(
+ displayCrop.bottom.round(),
+ 0,
+ videoSize.height.toInt(),
+ );
+
+ final w = maxX - minX;
+ final h = maxY - minY;
+
+ // Note: we round to the nearest pixel before clamping so that symmetric
+ // crops retain parity after multiple transformations. This avoids repeated
+ // floor/ceil adjustments that previously caused Β±1px drift.
+ if (w <= 0 || h <= 0) {
+ throw VideoCropException('Invalid crop dimensions after normalization');
+ }
+
+ return CropCalculation(x: minX, y: minY, width: w, height: h);
+ }
+}
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.dart
index 527a3c83d3..d1fb1642d4 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
@@ -21,10 +21,12 @@ class VideoEditorPlayerControl extends StatelessWidget {
]),
builder: (_, __) {
final duration = controller.trimmedDuration;
- final pos = Duration(
- seconds: (controller.videoPosition.inSeconds -
- controller.startTrim.inSeconds),
- );
+ Duration pos = controller.videoPosition - controller.startTrim;
+ if (pos.isNegative) {
+ pos = Duration.zero;
+ } else if (pos > duration) {
+ pos = duration;
+ }
final isPlaying = controller.isPlaying;
return GestureDetector(
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.dart
index f1c8310e99..6f9b55eee6 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
@@ -4,6 +4,7 @@ import "dart:math";
import 'package:flutter/material.dart';
import "package:logging/logging.dart";
+import 'package:native_video_editor/native_video_editor.dart';
import 'package:path/path.dart' as path;
import "package:photo_manager/photo_manager.dart";
import "package:photos/core/event_bus.dart";
@@ -13,11 +14,13 @@ import "package:photos/events/local_photos_updated_event.dart";
import "package:photos/generated/l10n.dart";
import "package:photos/models/file/file.dart";
import "package:photos/models/location/location.dart";
+import "package:photos/service_locator.dart";
import "package:photos/services/sync/sync_service.dart";
import "package:photos/theme/ente_theme.dart";
import "package:photos/ui/common/linear_progress_dialog.dart";
import "package:photos/ui/notification/toast.dart";
import "package:photos/ui/tools/editor/export_video_service.dart";
+import "package:photos/ui/tools/editor/native_video_export_service.dart";
import 'package:photos/ui/tools/editor/video_crop_page.dart';
import "package:photos/ui/tools/editor/video_editor/video_editor_app_bar.dart";
import "package:photos/ui/tools/editor/video_editor/video_editor_bottom_action.dart";
@@ -26,7 +29,6 @@ import "package:photos/ui/tools/editor/video_editor/video_editor_player_control.
import "package:photos/ui/tools/editor/video_rotate_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/exif_util.dart";
import "package:photos/utils/navigation_util.dart";
import "package:video_editor/video_editor.dart";
@@ -51,51 +53,66 @@ class _VideoEditorPageState extends State<VideoEditorPage> {
final _logger = Logger("VideoEditor");
/// Some videos have a non-zero 'rotation' property in exif which causes the
- /// video to appear rotated in the video editor preview on Andoird.
+ /// video to appear rotated in the video editor preview on Android.
/// This variable is used as a workaround to rotate the video back to its
/// expected orientation in the viewer.
int? _quarterTurnsForRotationCorrection;
VideoEditorController? _controller;
+ /// Toggle state for internal users to switch between native and FFmpeg export
+ /// Initially set to the flag service value
+ late bool _useNativeExport;
+
@override
void initState() {
super.initState();
- Future.microtask(
- () {
- _controller = VideoEditorController.file(
- widget.ioFile,
- minDuration: const Duration(seconds: 1),
- cropStyle: CropGridStyle(
- background: Theme.of(context).colorScheme.surface,
- selectedBoundariesColor:
- const ColorScheme.dark().videoPlayerPrimaryColor,
- ),
- trimStyle: TrimSliderStyle(
- onTrimmedColor: const ColorScheme.dark().videoPlayerPrimaryColor,
- onTrimmingColor: const ColorScheme.dark().videoPlayerPrimaryColor,
- background: Theme.of(context).colorScheme.editorBackgroundColor,
- positionLineColor:
- Theme.of(context).colorScheme.videoPlayerBorderColor,
- lineColor: Theme.of(context)
- .colorScheme
- .videoPlayerBorderColor
- .withValues(alpha: 0.6),
- ),
- );
-
- _controller!.initialize().then((_) => setState(() {})).catchError(
- (error) {
- // handle minumum duration bigger than video duration error
- Navigator.pop(context);
- },
- test: (e) => e is VideoMinDurationError,
- );
- },
- );
+ // Initialize toggle with flagService value
+ _useNativeExport = flagService.useNativeVideoEditor;
+
+ // First determine rotation correction for Android
+ _doRotationCorrectionIfAndroid().then((_) {
+ // Then initialize the controller
+ _controller = VideoEditorController.file(
+ widget.ioFile,
+ minDuration: const Duration(seconds: 1),
+ cropStyle: CropGridStyle(
+ background: Theme.of(context).colorScheme.surface,
+ selectedBoundariesColor:
+ const ColorScheme.dark().videoPlayerPrimaryColor,
+ ),
+ trimStyle: TrimSliderStyle(
+ onTrimmedColor: const ColorScheme.dark().videoPlayerPrimaryColor,
+ onTrimmingColor: const ColorScheme.dark().videoPlayerPrimaryColor,
+ background: Theme.of(context).colorScheme.editorBackgroundColor,
+ positionLineColor: Theme.of(
+ context,
+ ).colorScheme.videoPlayerBorderColor,
+ lineColor: Theme.of(
+ context,
+ ).colorScheme.videoPlayerBorderColor.withValues(alpha: 0.6),
+ ),
+ );
- _doRotationCorrectionIfAndroid();
+ _controller!.initialize().then((_) {
+ // Apply metadata rotation to the video player
+ if (_quarterTurnsForRotationCorrection != null &&
+ _quarterTurnsForRotationCorrection! != 0) {
+ final rotationDegrees = _quarterTurnsForRotationCorrection! * 90;
+ _controller!.video.value = _controller!.video.value.copyWith(
+ rotationCorrection: rotationDegrees,
+ );
+ }
+ setState(() {});
+ }).catchError(
+ (error) {
+ // handle minumum duration bigger than video duration error
+ Navigator.pop(context);
+ },
+ test: (e) => e is VideoMinDurationError,
+ );
+ });
}
@override
@@ -157,20 +174,17 @@ class _VideoEditorPageState extends State<VideoEditorPage> {
Positioned.fill(
child: Hero(
tag: "video-editor-preview",
- child: RotatedBox(
- quarterTurns:
- _quarterTurnsForRotationCorrection!,
- child: CropGridViewer.preview(
- controller: _controller!,
- ),
+ child: CropGridViewer.preview(
+ controller: _controller!,
),
),
),
Align(
alignment: Alignment.bottomCenter,
child: Padding(
- padding:
- const EdgeInsets.only(bottom: 24),
+ padding: const EdgeInsets.only(
+ bottom: 24,
+ ),
child: VideoEditorPlayerControl(
controller: _controller!,
),
@@ -181,6 +195,39 @@ class _VideoEditorPageState extends State<VideoEditorPage> {
),
),
const SizedBox(height: 12),
+ if (flagService.internalUser)
+ Padding(
+ padding: const EdgeInsets.symmetric(
+ horizontal: 8,
+ ),
+ child: Row(
+ mainAxisAlignment: MainAxisAlignment.center,
+ children: [
+ Text(
+ "Native (i)",
+ style: getEnteTextTheme(context)
+ .mini
+ .copyWith(color: colorScheme.textMuted),
+ ),
+ const SizedBox(width: 4),
+ Transform.scale(
+ scale: 0.8,
+ child: Switch(
+ value: _useNativeExport,
+ onChanged: (value) {
+ setState(() {
+ _useNativeExport = value;
+ });
+ },
+ materialTapTargetSize:
+ MaterialTapTargetSize.shrinkWrap,
+ ),
+ ),
+ ],
+ ),
+ ),
+ if (flagService.internalUser)
+ const SizedBox(height: 8),
VideoEditorMainActions(
children: [
VideoEditorBottomAction(
@@ -190,8 +237,6 @@ class _VideoEditorPageState extends State<VideoEditorPage> {
onPressed: () => _openSubEditor(
VideoTrimPage(
controller: _controller!,
- quarterTurnsForRotationCorrection:
- _quarterTurnsForRotationCorrection!,
),
),
),
@@ -203,8 +248,6 @@ class _VideoEditorPageState extends State<VideoEditorPage> {
onPressed: () => _openSubEditor(
VideoCropPage(
controller: _controller!,
- quarterTurnsForRotationCorrection:
- _quarterTurnsForRotationCorrection!,
),
),
),
@@ -216,8 +259,6 @@ class _VideoEditorPageState extends State<VideoEditorPage> {
onPressed: () => _openSubEditor(
VideoRotatePage(
controller: _controller!,
- quarterTurnsForRotationCorrection:
- _quarterTurnsForRotationCorrection!,
),
),
),
@@ -236,6 +277,10 @@ class _VideoEditorPageState extends State<VideoEditorPage> {
}
void exportVideo() async {
+ final shouldUseNative = flagService.internalUser
+ ? _useNativeExport
+ : flagService.useNativeVideoEditor;
+
_isExporting.value = true;
final dialogKey = GlobalKey<LinearProgressDialogState>();
@@ -254,6 +299,78 @@ class _VideoEditorPageState extends State<VideoEditorPage> {
),
);
+ try {
+ final result = await _performExport(
+ shouldUseNative: shouldUseNative,
+ dialogKey: dialogKey,
+ );
+ await _handleExportCompletion(result, dialogKey);
+ } catch (e, s) {
+ _logger.severe("Unexpected error in export process", e, s);
+ _isExporting.value = false;
+
+ if (dialogKey.currentState != null && dialogKey.currentState!.mounted) {
+ Navigator.of(dialogKey.currentContext!).pop();
+ }
+
+ showShortToast(context, AppLocalizations.of(context).somethingWentWrong);
+ }
+ }
+
+ Future<File> _performExport({
+ required bool shouldUseNative,
+ required GlobalKey<LinearProgressDialogState> dialogKey,
+ }) async {
+ if (shouldUseNative) {
+ final tempDir = Directory.systemTemp.createTempSync(
+ 'ente_video_export',
+ );
+ final outputPath = path.join(
+ tempDir.path,
+ 'export_${DateTime.now().millisecondsSinceEpoch}.mp4',
+ );
+
+ try {
+ return await NativeVideoExportService.exportVideo(
+ controller: _controller!,
+ outputPath: outputPath,
+ onProgress: (progress) {
+ if (dialogKey.currentState != null) {
+ dialogKey.currentState!.setProgress(progress);
+ }
+ },
+ onError: (e, s) {
+ _logger.severe("Error exporting video with native", e, s);
+ },
+ );
+ } catch (nativeError, _) {
+ _logger.warning(
+ "Native export failed, attempting FFmpeg fallback",
+ nativeError,
+ );
+
+ if (flagService.internalUser && mounted) {
+ showShortToast(context, "(i) Switching to FFmpeg fallback");
+ }
+
+ if (dialogKey.currentState != null) {
+ dialogKey.currentState!.setProgress(0.0);
+ }
+
+ return await _runFfmpegExport(
+ dialogKey: dialogKey,
+ );
+ }
+ }
+
+ return await _runFfmpegExport(
+ dialogKey: dialogKey,
+ );
+ }
+
+ Future<File> _runFfmpegExport({
+ required GlobalKey<LinearProgressDialogState> dialogKey,
+ }) async {
final config = VideoFFmpegVideoEditorConfig(
_controller!,
format: VideoExportFormat.mp4,
@@ -268,104 +385,114 @@ class _VideoEditorPageState extends State<VideoEditorPage> {
},
);
- try {
- final executeConfig = await config.getExecuteConfig();
-
- await ExportService.runFFmpegCommand(
- executeConfig,
- onProgress: (stats) {
- final progress = config.getFFmpegProgress(stats.getTime().toInt());
- if (dialogKey.currentState != null) {
- dialogKey.currentState!.setProgress(progress);
- }
- },
- onError: (e, s) {
- _logger.severe("Error exporting video", e, s);
- },
- onCompleted: (result) async {
- _isExporting.value = false;
- if (!mounted) {
- return;
- }
-
- final fileName = path.basenameWithoutExtension(widget.file.title!) +
- "_edited_" +
- DateTime.now().microsecondsSinceEpoch.toString() +
- ".mp4";
+ final executeConfig = await config.getExecuteConfig();
+ final completer = Completer<File>();
- //Disabling notifications for assets changing to insert the file into
- //files db before triggering a sync.
- await PhotoManager.stopChangeNotify();
+ await ExportService.runFFmpegCommand(
+ executeConfig,
+ onProgress: (stats) {
+ final progress = config.getFFmpegProgress(stats.getTime().toInt());
+ if (dialogKey.currentState != null) {
+ dialogKey.currentState!.setProgress(progress);
+ }
+ },
+ onError: (e, s) {
+ _logger.severe("Error exporting video with FFmpeg", e, s);
+ if (!completer.isCompleted) {
+ completer.completeError(e, s);
+ }
+ },
+ onCompleted: (file) {
+ if (!completer.isCompleted) {
+ completer.complete(file);
+ }
+ },
+ );
- try {
- final AssetEntity newAsset = await (PhotoManager.editor.saveVideo(
- result,
- title: fileName,
- ));
+ return completer.future;
+ }
- result.deleteSync();
+ Future<void> _handleExportCompletion(
+ File result,
+ GlobalKey<LinearProgressDialogState> dialogKey,
+ ) async {
+ try {
+ _isExporting.value = false;
+ if (!mounted) {
+ return;
+ }
+
+ final fileName = path.basenameWithoutExtension(widget.file.title!) +
+ "_edited_" +
+ DateTime.now().microsecondsSinceEpoch.toString() +
+ ".mp4";
+
+ //Disabling notifications for assets changing to insert the file into
+ //files db before triggering a sync.
+ await PhotoManager.stopChangeNotify();
+
+ try {
+ final AssetEntity newAsset = await (PhotoManager.editor.saveVideo(
+ result,
+ title: fileName,
+ ));
+
+ result.deleteSync();
+
+ final newFile = await EnteFile.fromAsset(
+ widget.file.deviceFolder ?? '',
+ newAsset,
+ );
- final newFile = await EnteFile.fromAsset(
- widget.file.deviceFolder ?? '',
- newAsset,
+ newFile.creationTime = widget.file.creationTime;
+ newFile.collectionID = widget.file.collectionID;
+ newFile.location = widget.file.location;
+ if (!newFile.hasLocation && widget.file.localID != null) {
+ final assetEntity = await widget.file.getAsset;
+ if (assetEntity != null) {
+ final latLong = await assetEntity.latlngAsync();
+ newFile.location = Location(
+ latitude: latLong.latitude,
+ longitude: latLong.longitude,
);
+ }
+ }
- newFile.creationTime = widget.file.creationTime;
- newFile.collectionID = widget.file.collectionID;
- newFile.location = widget.file.location;
- if (!newFile.hasLocation && widget.file.localID != null) {
- final assetEntity = await widget.file.getAsset;
- if (assetEntity != null) {
- final latLong = await assetEntity.latlngAsync();
- newFile.location = Location(
- latitude: latLong.latitude,
- longitude: latLong.longitude,
- );
- }
- }
-
- newFile.generatedID = await FilesDB.instance.insertAndGetId(
- newFile,
- );
+ newFile.generatedID = await FilesDB.instance.insertAndGetId(newFile);
- Bus.instance.fire(
- LocalPhotosUpdatedEvent([newFile], source: "editSave"),
- );
+ Bus.instance.fire(
+ LocalPhotosUpdatedEvent([newFile], source: "editSave"),
+ );
- SyncService.instance.sync().ignore();
+ SyncService.instance.sync().ignore();
- showShortToast(context, AppLocalizations.of(context).editsSaved);
- final files = widget.detailPageConfig.files;
+ showShortToast(context, AppLocalizations.of(context).editsSaved);
+ final files = widget.detailPageConfig.files;
- // the index could be -1 if the files fetched doesn't contain the newly
- // edited files
- int selectionIndex = files.indexWhere(
- (file) => file.generatedID == newFile.generatedID,
- );
- if (selectionIndex == -1) {
- files.add(newFile);
- selectionIndex = files.length - 1;
- }
- Navigator.of(dialogKey.currentContext!).pop('dialog');
-
- replacePage(
- context,
- DetailPage(
- widget.detailPageConfig.copyWith(
- files: files,
- selectedIndex: min(selectionIndex, files.length - 1),
- ),
- ),
- );
- } catch (e, s) {
- _logger.severe("Error in post-processing", e, s);
- Navigator.of(dialogKey.currentContext!).pop('dialog');
- }
- },
- );
- } catch (e, s) {
- _logger.severe("Unexpected error in export process", e, s);
- Navigator.of(dialogKey.currentContext!).pop('dialog');
+ // the index could be -1 if the files fetched doesn't contain the newly
+ // edited files
+ int selectionIndex = files.indexWhere(
+ (file) => file.generatedID == newFile.generatedID,
+ );
+ if (selectionIndex == -1) {
+ files.add(newFile);
+ selectionIndex = files.length - 1;
+ }
+ Navigator.of(dialogKey.currentContext!).pop('dialog');
+
+ replacePage(
+ context,
+ DetailPage(
+ widget.detailPageConfig.copyWith(
+ files: files,
+ selectedIndex: min(selectionIndex, files.length - 1),
+ ),
+ ),
+ );
+ } catch (e, s) {
+ _logger.severe("Error in post-processing", e, s);
+ Navigator.of(dialogKey.currentContext!).pop('dialog');
+ }
} finally {
await PhotoManager.startChangeNotify();
}
@@ -375,18 +502,29 @@ class _VideoEditorPageState extends State<VideoEditorPage> {
return Navigator.of(context).push(_VideoEditorSubPageRoute(child));
}
- void _doRotationCorrectionIfAndroid() {
+ Future<void> _doRotationCorrectionIfAndroid() async {
if (Platform.isAndroid) {
- getVideoPropsAsync(widget.ioFile).then((props) async {
- if (props?.rotation != null) {
- _quarterTurnsForRotationCorrection = -(props!.rotation! / 90).round();
+ try {
+ // Use native method to get video info more efficiently
+ final videoInfo = await NativeVideoEditor.getVideoInfo(
+ widget.ioFile.path,
+ );
+ final rotation = videoInfo['rotation'] as int? ?? 0;
+
+ if (rotation != 0) {
+ _quarterTurnsForRotationCorrection = (rotation / 90).round();
} else {
_quarterTurnsForRotationCorrection = 0;
}
setState(() {});
- });
+ } catch (e) {
+ _logger.warning('Failed to get video info, using fallback', e);
+ _quarterTurnsForRotationCorrection = 0;
+ setState(() {});
+ }
} else {
_quarterTurnsForRotationCorrection = 0;
+ setState(() {});
}
}
}
diff --git a/mobile/apps/photos/lib/ui/tools/editor/video_rotate_page.dart b/mobile/apps/photos/lib/ui/tools/editor/video_rotate_page.dart
index ae2c832e5e..c11a3eb0ef 100644
--- a/mobile/apps/photos/lib/ui/tools/editor/video_rotate_page.dart
+++ b/mobile/apps/photos/lib/ui/tools/editor/video_rotate_page.dart
@@ -8,11 +8,9 @@ import "package:photos/ui/tools/editor/video_editor/video_editor_player_control.
import 'package:video_editor/video_editor.dart';
class VideoRotatePage extends StatelessWidget {
- final int quarterTurnsForRotationCorrection;
const VideoRotatePage({
super.key,
required this.controller,
- required this.quarterTurnsForRotationCorrection,
});
final VideoEditorController controller;
@@ -44,33 +42,27 @@ class VideoRotatePage extends StatelessWidget {
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
Expanded(
- child: ClipRRect(
- borderRadius: BorderRadius.circular(24),
- child: Stack(
- fit: StackFit.expand,
- children: [
- Positioned.fill(
- child: Hero(
- tag: "video-editor-preview",
- child: RotatedBox(
- quarterTurns: quarterTurnsForRotationCorrection,
- child: CropGridViewer.preview(
- controller: controller,
- ),
- ),
+ child: Stack(
+ fit: StackFit.expand,
+ children: [
+ Positioned.fill(
+ child: Hero(
+ tag: "video-editor-preview",
+ child: CropGridViewer.preview(
+ controller: controller,
),
),
- Align(
- alignment: Alignment.bottomCenter,
- child: Padding(
- padding: const EdgeInsets.only(bottom: 20),
- child: VideoEditorPlayerControl(
- controller: controller,
- ),
+ ),
+ Align(
+ alignment: Alignment.bottomCenter,
+ child: Padding(
+ padding: const EdgeInsets.only(bottom: 20),
+ child: VideoEditorPlayerControl(
+ controller: controller,
),
),
- ],
- ),
+ ),
+ ],
),
),
VideoEditorMainActions(
diff --git a/mobile/apps/photos/lib/ui/tools/editor/video_trim_page.dart b/mobile/apps/photos/lib/ui/tools/editor/video_trim_page.dart
index a5174c19e4..ea199e6dff 100644
--- a/mobile/apps/photos/lib/ui/tools/editor/video_trim_page.dart
+++ b/mobile/apps/photos/lib/ui/tools/editor/video_trim_page.dart
@@ -6,11 +6,9 @@ import "package:photos/ui/tools/editor/video_editor/video_editor_player_control.
import 'package:video_editor/video_editor.dart';
class VideoTrimPage extends StatefulWidget {
- final int quarterTurnsForRotationCorrection;
const VideoTrimPage({
super.key,
required this.controller,
- required this.quarterTurnsForRotationCorrection,
});
final VideoEditorController controller;
@@ -37,7 +35,6 @@ class _VideoTrimPageState extends State<VideoTrimPage> {
},
primaryActionLabel: AppLocalizations.of(context).done,
onPrimaryAction: () {
- widget.controller.applyCacheCrop();
Navigator.pop(context);
},
),
@@ -50,34 +47,27 @@ class _VideoTrimPageState extends State<VideoTrimPage> {
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
Expanded(
- child: ClipRRect(
- borderRadius: BorderRadius.circular(24),
- child: Stack(
- fit: StackFit.expand,
- children: [
- Positioned.fill(
- child: Hero(
- tag: "video-editor-preview",
- child: RotatedBox(
- quarterTurns:
- widget.quarterTurnsForRotationCorrection,
- child: CropGridViewer.preview(
- controller: widget.controller,
- ),
- ),
+ child: Stack(
+ fit: StackFit.expand,
+ children: [
+ Positioned.fill(
+ child: Hero(
+ tag: "video-editor-preview",
+ child: CropGridViewer.preview(
+ controller: widget.controller,
),
),
- Align(
- alignment: Alignment.bottomCenter,
- child: Padding(
- padding: const EdgeInsets.only(bottom: 20),
- child: VideoEditorPlayerControl(
- controller: widget.controller,
- ),
+ ),
+ Align(
+ alignment: Alignment.bottomCenter,
+ child: Padding(
+ padding: const EdgeInsets.only(bottom: 20),
+ child: VideoEditorPlayerControl(
+ controller: widget.controller,
),
),
- ],
- ),
+ ),
+ ],
),
),
_buildTrimSlider(context),
diff --git a/mobile/apps/photos/plugins/ente_feature_flag/lib/src/service.dart b/mobile/apps/photos/plugins/ente_feature_flag/lib/src/service.dart
index d30267d908..f97ea89353 100644
--- a/mobile/apps/photos/plugins/ente_feature_flag/lib/src/service.dart
+++ b/mobile/apps/photos/plugins/ente_feature_flag/lib/src/service.dart
@@ -71,6 +71,10 @@ class FlagService {
bool get addToAlbumFeature => internalUser;
+ bool get widgetSharedAlbums => internalUser;
+
+ bool get useNativeVideoEditor => internalUser && Platform.isAndroid;
+
bool hasSyncedAccountFlags() {
return _prefs.containsKey("remote_flags");
}
diff --git a/mobile/apps/photos/pubspec.lock b/mobile/apps/photos/pubspec.lock
index 725ae89f5d..43fc965232 100644
--- a/mobile/apps/photos/pubspec.lock
+++ b/mobile/apps/photos/pubspec.lock
@@ -1769,6 +1769,13 @@ packages:
url: "https://pub.dev"
source: hosted
version: "1.4.0"
+ native_video_editor:
+ dependency: "direct main"
+ description:
+ path: "../../packages/native_video_editor"
+ relative: true
+ source: path
+ version: "1.0.0"
native_video_player:
dependency: "direct main"
description:
@@ -2853,7 +2860,7 @@ packages:
dependency: "direct main"
description:
path: "."
- ref: HEAD
+ ref: master
resolved-ref: "1eeb18e2b1ce36bd8ca70178c0d4b485e9982257"
url: "https://github.com/ente-io/video_editor_fork.git"
source: git
@@ -2861,12 +2868,11 @@ packages:
video_player:
dependency: "direct main"
description:
- path: "packages/video_player/video_player"
- ref: android_video_roation_fix
- resolved-ref: "0acef25ca43206e02a0758b51d5fd176e3d8c6b8"
- url: "https://github.com/ente-io/packages.git"
- source: git
- version: "2.7.0"
+ name: video_player
+ sha256: "0d55b1f1a31e5ad4c4967bfaa8ade0240b07d20ee4af1dfef5f531056512961a"
+ url: "https://pub.dev"
+ source: hosted
+ version: "2.10.0"
video_player_android:
dependency: transitive
description:
diff --git a/mobile/apps/photos/pubspec.yaml b/mobile/apps/photos/pubspec.yaml
index 78cf9b4cec..a7458764aa 100644
--- a/mobile/apps/photos/pubspec.yaml
+++ b/mobile/apps/photos/pubspec.yaml
@@ -151,6 +151,8 @@ dependencies:
ref: v2-only
nanoid: ^1.0.0
native_dio_adapter: ^1.4.0
+ native_video_editor:
+ path: ../../packages/native_video_editor
native_video_player: ^4.0.0
onnx_dart:
path: plugins/onnx_dart
@@ -214,11 +216,8 @@ dependencies:
video_editor: # edge cases handled in fork
git:
url: https://github.com/ente-io/video_editor_fork.git
- video_player:
- git:
- url: https://github.com/ente-io/packages.git
- ref: android_video_roation_fix
- path: packages/video_player/video_player/
+ ref: master
+ video_player: ^2.10.0
video_thumbnail: ^0.5.6
visibility_detector: ^0.4.0+2
wakelock_plus: ^1.1.1
@@ -254,11 +253,6 @@ dependency_overrides:
url: https://github.com/media-kit/media-kit
path: media_kit_video
protobuf: ^3.1.0
- video_player: # remove this dep as soon as we move to one player for all
- git:
- url: https://github.com/ente-io/packages.git
- ref: android_video_roation_fix
- path: packages/video_player/video_player/
watcher: ^1.1.0
win32: "5.10.1"
diff --git a/mobile/apps/photos/pubspec_overrides.yaml b/mobile/apps/photos/pubspec_overrides.yaml
index b5a1bd35f2..4634ead20a 100644
--- a/mobile/apps/photos/pubspec_overrides.yaml
+++ b/mobile/apps/photos/pubspec_overrides.yaml
@@ -34,11 +34,7 @@ dependency_overrides:
url: https://github.com/media-kit/media-kit
path: media_kit_video
protobuf: ^3.1.0
- video_player:
- git:
- url: https://github.com/ente-io/packages.git
- ref: android_video_roation_fix
- path: packages/video_player/video_player/
+ video_player: ^2.10.0
watcher: ^1.1.0
win32: 5.10.1
log_viewer:
diff --git a/mobile/apps/photos/scripts/internal_changes.txt b/mobile/apps/photos/scripts/internal_changes.txt
index 73d385eb1c..94cfb8c4d5 100644
--- a/mobile/apps/photos/scripts/internal_changes.txt
+++ b/mobile/apps/photos/scripts/internal_changes.txt
@@ -1,3 +1,14 @@
+- Prateek: (i) Add native video editor to boost performance
+- Neeraj: Remove feature flags from manage_links_widget (album layout, allow joining album, copy embed HTML)
+- Ashil: Use better copy on auto-add people selection page
+- Ashil: Add more logs to debug app stuck at splash screen issue
+- Prateek: Tag Sentry errors with execution_context for background vs foreground
+- Prateek: Upgrade WorkManager to 0.9.0 and ExistingWorkPolicy to update
+- Neeraj: (i) Copy embed link option
+- Prateek: Fix background uploads on Android 15 by skipping permission request in background mode
+- Prateek: Fix CronetException during background sync by disabling NativeAdapter on Android
+- Laurens: Change similar images labels copy
+- Laurens: Fix flipped thumbnails issue by removing use of ColorFiltered widget
- Neeraj: [CustomerIssue] Handle corrupt asset timestamps with detailed error reporting
- Neeraj: Fix video aspect ratio when shared from external apps
- Prateek: Add logging for background task execution
diff --git a/mobile/packages/native_video_editor/android/build.gradle b/mobile/packages/native_video_editor/android/build.gradle
new file mode 100644
index 0000000000..4d73f05516
--- /dev/null
+++ b/mobile/packages/native_video_editor/android/build.gradle
@@ -0,0 +1,61 @@
+group 'io.ente.native_video_editor'
+version '1.0'
+
+buildscript {
+ ext.kotlin_version = '1.9.25'
+ repositories {
+ google()
+ mavenCentral()
+ }
+
+ dependencies {
+ classpath 'com.android.tools.build:gradle:8.7.3'
+ classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
+ }
+}
+
+rootProject.allprojects {
+ repositories {
+ google()
+ mavenCentral()
+ }
+}
+
+apply plugin: 'com.android.library'
+apply plugin: 'kotlin-android'
+
+android {
+ namespace 'io.ente.native_video_editor'
+ compileSdkVersion 33
+
+ compileOptions {
+ sourceCompatibility JavaVersion.VERSION_1_8
+ targetCompatibility JavaVersion.VERSION_1_8
+ }
+
+ kotlinOptions {
+ jvmTarget = '1.8'
+ }
+
+ sourceSets {
+ main.java.srcDirs += 'src/main/kotlin'
+ }
+
+ defaultConfig {
+ minSdkVersion 21
+ }
+}
+
+dependencies {
+ implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlin_version"
+ implementation "org.jetbrains.kotlinx:kotlinx-coroutines-android:1.7.3"
+
+ // Media3 Transformer for efficient video operations
+ implementation "androidx.media3:media3-transformer:1.1.1"
+ implementation "androidx.media3:media3-common:1.1.1"
+ implementation "androidx.media3:media3-effect:1.1.1"
+ implementation "androidx.media3:media3-extractor:1.1.1"
+
+ // Guava for ImmutableList
+ implementation "com.google.guava:guava:31.1-android"
+}
\ No newline at end of file
diff --git a/mobile/packages/native_video_editor/android/src/main/AndroidManifest.xml b/mobile/packages/native_video_editor/android/src/main/AndroidManifest.xml
new file mode 100644
index 0000000000..c7e7078dcd
--- /dev/null
+++ b/mobile/packages/native_video_editor/android/src/main/AndroidManifest.xml
@@ -0,0 +1,2 @@
+<manifest xmlns:android="http://schemas.android.com/apk/res/android">
+</manifest>
\ No newline at end of file
diff --git a/mobile/packages/native_video_editor/android/src/main/kotlin/io/ente/native_video_editor/Media3TransformerProcessor.kt b/mobile/packages/native_video_editor/android/src/main/kotlin/io/ente/native_video_editor/Media3TransformerProcessor.kt
new file mode 100644
index 0000000000..517d599c57
--- /dev/null
+++ b/mobile/packages/native_video_editor/android/src/main/kotlin/io/ente/native_video_editor/Media3TransformerProcessor.kt
@@ -0,0 +1,445 @@
+package io.ente.native_video_editor
+
+import android.content.Context
+import android.util.Log
+import android.net.Uri
+import androidx.media3.common.Effect
+import androidx.media3.common.MediaItem
+import androidx.media3.common.MimeTypes
+import androidx.media3.common.util.Size
+import androidx.media3.effect.*
+import androidx.media3.transformer.*
+import kotlinx.coroutines.*
+import java.io.File
+import java.util.concurrent.CountDownLatch
+import kotlin.math.roundToInt
+
+/**
+ * Processor using Media3 Transformer for efficient video editing operations.
+ * Handles trim, rotate, and crop operations with proper effect chaining.
+ */
+class Media3TransformerProcessor(private val context: Context) {
+ companion object {
+ private const val TAG = "Media3Transformer"
+
+ // Logging levels for debugging (enabled only for debug builds when available)
+ private val IS_DEBUG_BUILD: Boolean = try {
+ val field = Class.forName("io.ente.native_video_editor.BuildConfig")
+ .getField("DEBUG")
+ field.getBoolean(null)
+ } catch (_: Exception) {
+ false
+ }
+
+ private val LOG_VERBOSE = IS_DEBUG_BUILD
+ private val LOG_PROGRESS = IS_DEBUG_BUILD
+ private val LOG_ERRORS = true // Keep error logging enabled
+ private const val ROTATION_90 = 90
+ private const val ROTATION_270 = 270
+ }
+
+ /**
+ * Process video with multiple transformations in a single pass
+ */
+ suspend fun processVideo(
+ inputPath: String,
+ outputPath: String,
+ trimStartMs: Long? = null,
+ trimEndMs: Long? = null,
+ rotateDegrees: Int? = null,
+ cropX: Int? = null,
+ cropY: Int? = null,
+ cropWidth: Int? = null,
+ cropHeight: Int? = null,
+ onProgress: ((Float) -> Unit)? = null
+ ): ProcessingResult = withContext(Dispatchers.Main) {
+ val startTime = System.currentTimeMillis()
+ val latch = CountDownLatch(1)
+ var processingError: Exception? = null
+ var hasVideoEffects = false
+
+ logVerbose("Starting video processing:")
+ logVerbose(" Input: $inputPath")
+ logVerbose(" Output: $outputPath")
+ logVerbose(" Trim: ${if (trimStartMs != null) "$trimStartMs-$trimEndMs ms" else "none"}")
+ logVerbose(" Rotate: ${rotateDegrees ?: "none"} degrees")
+ logVerbose(" Crop: ${if (cropX != null) "[$cropX,$cropY ${cropWidth}x$cropHeight]" else "none"}")
+
+ try {
+ // Get video info first
+ val videoInfo = getVideoInfo(inputPath)
+ val originalWidth = videoInfo.width
+ val originalHeight = videoInfo.height
+ val originalRotation = videoInfo.rotation
+
+ logVerbose("Original video: ${originalWidth}x$originalHeight, rotation=$originalRotation")
+
+ // Build MediaItem with optional clipping
+ val mediaItemBuilder = MediaItem.Builder().setUri(Uri.fromFile(File(inputPath)))
+
+ if (trimStartMs != null && trimEndMs != null) {
+ logVerbose("Applying trim: $trimStartMs-$trimEndMs ms")
+ mediaItemBuilder.setClippingConfiguration(
+ MediaItem.ClippingConfiguration.Builder()
+ .setStartPositionMs(trimStartMs)
+ .setEndPositionMs(trimEndMs)
+ .setStartsAtKeyFrame(false) // Allow precise cuts
+ .build()
+ )
+ }
+
+ val mediaItem = mediaItemBuilder.build()
+
+ // Build effects list
+ val videoEffects = mutableListOf<Effect>()
+
+ // Add crop effect if needed BEFORE rotation
+ // Flutter sends crop coordinates in display space.
+ // Like FFmpeg and iOS, we'll use these coordinates directly without transformation.
+ var outDimsFromCrop: Size? = null
+ if (cropX != null && cropY != null && cropWidth != null && cropHeight != null) {
+ logVerbose("Crop input: x=$cropX, y=$cropY, w=$cropWidth, h=$cropHeight")
+ logVerbose("Video dims: ${originalWidth}x$originalHeight, rotation=$originalRotation")
+
+ // Use crop coordinates as-is, just like FFmpeg does
+ // No special treatment for metadata rotation
+ val fileX = cropX
+ val fileY = cropY
+ val fileW = cropWidth
+ val fileH = cropHeight
+
+ logVerbose("Using crop coordinates as-is: x=$fileX, y=$fileY, w=$fileW, h=$fileH")
+
+ // When video has rotation metadata, swap dimensions for crop fraction calculation
+ // This is because Flutter sends display-space coordinates (after rotation)
+ val effectiveWidth: Int
+ val effectiveHeight: Int
+ if (originalRotation == 90 || originalRotation == 270) {
+ effectiveWidth = originalHeight
+ effectiveHeight = originalWidth
+ logVerbose("Video has 90/270 rotation, swapping dimensions for crop calculation: ${effectiveWidth}x$effectiveHeight")
+ } else {
+ effectiveWidth = originalWidth
+ effectiveHeight = originalHeight
+ }
+
+ // Calculate crop as a fraction of the effective video dimensions
+ val cropLeftFraction = fileX.toFloat() / effectiveWidth
+ val cropRightFraction = (fileX + fileW).toFloat() / effectiveWidth
+ val cropTopFraction = fileY.toFloat() / effectiveHeight
+ val cropBottomFraction = (fileY + fileH).toFloat() / effectiveHeight
+
+ logVerbose("Crop fractions: L=$cropLeftFraction, R=$cropRightFraction, T=$cropTopFraction, B=$cropBottomFraction")
+
+ // Use Crop effect with NDC coordinates (-1 to 1)
+ val ndcLeft = -1f + 2f * cropLeftFraction
+ val ndcRight = -1f + 2f * cropRightFraction
+ val ndcBottom = 1f - 2f * cropBottomFraction
+ val ndcTop = 1f - 2f * cropTopFraction
+
+ logVerbose("NDC coordinates: left=$ndcLeft, right=$ndcRight, bottom=$ndcBottom, top=$ndcTop")
+ logVerbose("Expected crop output: ${cropWidth}x$cropHeight pixels")
+
+ val cropEffect = Crop(
+ /* left = */ ndcLeft,
+ /* right = */ ndcRight,
+ /* bottom = */ ndcBottom,
+ /* top = */ ndcTop
+ )
+
+ // Preserve output dimensions from the crop
+ outDimsFromCrop = Size(cropWidth, cropHeight)
+
+ videoEffects.add(cropEffect)
+ hasVideoEffects = true
+ }
+
+ // Add rotation effect AFTER crop
+ if (rotateDegrees != null && rotateDegrees != 0) {
+ val normalizedDegrees = rotateDegrees % 360
+ logVerbose("Adding rotation effect: $normalizedDegrees degrees")
+
+ // Validate rotation degrees
+ if (normalizedDegrees !in listOf(0, 90, 180, 270)) {
+ throw IllegalArgumentException("Rotation degrees must be 0, 90, 180, or 270")
+ }
+
+ // Use ScaleAndRotateTransformation for proper rotation support
+ // Media3 uses positive degrees for clockwise rotation
+ val rotationEffect = ScaleAndRotateTransformation.Builder()
+ .setRotationDegrees(normalizedDegrees.toFloat())
+ .build()
+
+ videoEffects.add(rotationEffect)
+ logVerbose("Added ScaleAndRotateTransformation with rotation: $normalizedDegrees degrees (clockwise)")
+
+ hasVideoEffects = true
+ }
+
+ // Add Presentation effect to set output dimensions
+ // Base output on the file-space crop dimensions we actually applied.
+ if (outDimsFromCrop != null) {
+ var outputWidth = outDimsFromCrop!!.width
+ var outputHeight = outDimsFromCrop!!.height
+
+ // If a user-requested rotation (not metadata) is applied after crop,
+ // swap output dimensions for 90/270 degrees.
+ if (rotateDegrees != null && (rotateDegrees % 180) != 0) {
+ val tmp = outputWidth
+ outputWidth = outputHeight
+ outputHeight = tmp
+ }
+
+ val presentationEffect = Presentation.createForWidthAndHeight(
+ outputWidth,
+ outputHeight,
+ Presentation.LAYOUT_SCALE_TO_FIT_WITH_CROP
+ )
+ videoEffects.add(presentationEffect)
+ }
+
+ // Configure Transformer
+ val transformerBuilder = Transformer.Builder(context)
+ .setTransformationRequest(
+ TransformationRequest.Builder()
+ .setVideoMimeType(MimeTypes.VIDEO_H264) // Use H.264 for compatibility
+ .build()
+ )
+ .addListener(object : Transformer.Listener {
+ override fun onCompleted(composition: Composition, exportResult: ExportResult) {
+ logVerbose("Export completed successfully")
+ logVerbose("Export result: duration=${exportResult.durationMs}ms, " +
+ "size=${exportResult.fileSizeBytes} bytes")
+ latch.countDown()
+ }
+
+ override fun onError(
+ composition: Composition,
+ exportResult: ExportResult,
+ exportException: ExportException
+ ) {
+ logError("Export failed", exportException)
+ logError("Error code: ${exportException.errorCode}")
+ logError("Export result: ${exportResult}")
+ processingError = exportException
+ latch.countDown()
+ }
+ })
+
+ val transformer = transformerBuilder.build()
+
+ // Create EditedMediaItem with effects
+ val editedMediaItemBuilder = EditedMediaItem.Builder(mediaItem)
+
+ // Apply effects if any
+ if (videoEffects.isNotEmpty()) {
+ logVerbose("Applying ${videoEffects.size} video effects to EditedMediaItem")
+ val effects = Effects(
+ /* audioProcessors = */ emptyList(),
+ /* videoEffects = */ videoEffects
+ )
+ editedMediaItemBuilder.setEffects(effects)
+ }
+
+ val editedMediaItem = editedMediaItemBuilder.build()
+ val sequence = EditedMediaItemSequence(listOf(editedMediaItem))
+ val composition = Composition.Builder(listOf(sequence)).build()
+
+ // Start export
+ logVerbose("Starting export...")
+ transformer.start(composition, outputPath)
+
+ // Monitor progress
+ val progressJob = launch {
+ while (latch.count > 0) {
+ val progressHolder = ProgressHolder()
+ val progressState = transformer.getProgress(progressHolder)
+
+ when (progressState) {
+ Transformer.PROGRESS_STATE_NOT_STARTED -> {
+ logProgress("Progress: Not started")
+ }
+ Transformer.PROGRESS_STATE_WAITING_FOR_AVAILABILITY -> {
+ logProgress("Progress: Waiting for availability")
+ }
+ Transformer.PROGRESS_STATE_AVAILABLE -> {
+ val progress = progressHolder.progress / 100f
+ logProgress("Progress: ${(progress * 100).roundToInt()}%")
+ onProgress?.invoke(progress)
+ }
+ Transformer.PROGRESS_STATE_UNAVAILABLE -> {
+ logProgress("Progress: Unavailable")
+ }
+ }
+
+ delay(100)
+ }
+ }
+
+ // Wait for completion
+ withContext(Dispatchers.IO) {
+ latch.await()
+ }
+ progressJob.cancel()
+
+ // Check for errors
+ processingError?.let { throw it }
+
+ val processingTime = System.currentTimeMillis() - startTime
+ logVerbose("Processing completed in ${processingTime}ms")
+
+ // Verify output file exists
+ val outputFile = File(outputPath)
+ if (!outputFile.exists()) {
+ throw VideoProcessingException("Output file was not created")
+ }
+
+ logVerbose("Output file size: ${outputFile.length()} bytes")
+
+ ProcessingResult(
+ outputPath = outputPath,
+ processingTimeMs = processingTime,
+ isReEncoded = hasVideoEffects || (trimStartMs != null),
+ method = "Media3 Transformer"
+ )
+
+ } catch (e: Exception) {
+ logError("Failed to process video", e)
+ throw VideoProcessingException("Video processing failed: ${e.message}", e)
+ }
+ }
+
+ /**
+ * Dedicated trim operation for optimal performance
+ */
+ suspend fun trimVideo(
+ inputPath: String,
+ outputPath: String,
+ startTimeMs: Long,
+ endTimeMs: Long,
+ onProgress: ((Float) -> Unit)? = null
+ ): ProcessingResult {
+ return processVideo(
+ inputPath = inputPath,
+ outputPath = outputPath,
+ trimStartMs = startTimeMs,
+ trimEndMs = endTimeMs,
+ onProgress = onProgress
+ )
+ }
+
+ /**
+ * Dedicated rotate operation
+ */
+ suspend fun rotateVideo(
+ inputPath: String,
+ outputPath: String,
+ degrees: Int,
+ onProgress: ((Float) -> Unit)? = null
+ ): ProcessingResult {
+ return processVideo(
+ inputPath = inputPath,
+ outputPath = outputPath,
+ rotateDegrees = degrees,
+ onProgress = onProgress
+ )
+ }
+
+ /**
+ * Dedicated crop operation
+ */
+ suspend fun cropVideo(
+ inputPath: String,
+ outputPath: String,
+ cropX: Int,
+ cropY: Int,
+ cropWidth: Int,
+ cropHeight: Int,
+ onProgress: ((Float) -> Unit)? = null
+ ): ProcessingResult {
+ return processVideo(
+ inputPath = inputPath,
+ outputPath = outputPath,
+ cropX = cropX,
+ cropY = cropY,
+ cropWidth = cropWidth,
+ cropHeight = cropHeight,
+ onProgress = onProgress
+ )
+ }
+
+ /**
+ * Get video information
+ */
+ private fun getVideoInfo(videoPath: String): VideoInfo {
+ val retriever = android.media.MediaMetadataRetriever()
+ return try {
+ retriever.setDataSource(videoPath)
+
+ VideoInfo(
+ width = retriever.extractMetadata(
+ android.media.MediaMetadataRetriever.METADATA_KEY_VIDEO_WIDTH
+ )?.toIntOrNull() ?: 0,
+ height = retriever.extractMetadata(
+ android.media.MediaMetadataRetriever.METADATA_KEY_VIDEO_HEIGHT
+ )?.toIntOrNull() ?: 0,
+ rotation = retriever.extractMetadata(
+ android.media.MediaMetadataRetriever.METADATA_KEY_VIDEO_ROTATION
+ )?.toIntOrNull() ?: 0,
+ duration = retriever.extractMetadata(
+ android.media.MediaMetadataRetriever.METADATA_KEY_DURATION
+ )?.toLongOrNull() ?: 0L,
+ bitrate = retriever.extractMetadata(
+ android.media.MediaMetadataRetriever.METADATA_KEY_BITRATE
+ )?.toLongOrNull() ?: 0L
+ )
+ } finally {
+ retriever.release()
+ }
+ }
+
+ // Logging helpers
+ private fun logVerbose(message: String) {
+ if (LOG_VERBOSE) Log.d(TAG, message)
+ }
+
+ private fun logProgress(message: String) {
+ if (LOG_PROGRESS) Log.i(TAG, message)
+ }
+
+ private fun logError(message: String, throwable: Throwable? = null) {
+ if (LOG_ERRORS) {
+ if (throwable != null) {
+ Log.e(TAG, message, throwable)
+ } else {
+ Log.e(TAG, message)
+ }
+ }
+ }
+}
+
+/**
+ * Video information data class
+ */
+private data class VideoInfo(
+ val width: Int,
+ val height: Int,
+ val rotation: Int,
+ val duration: Long,
+ val bitrate: Long
+)
+
+/**
+ * Result of video processing operation
+ */
+data class ProcessingResult(
+ val outputPath: String,
+ val processingTimeMs: Long,
+ val isReEncoded: Boolean,
+ val method: String
+)
+
+/**
+ * Custom exception for video processing errors
+ */
+class VideoProcessingException(message: String, cause: Throwable? = null) : Exception(message, cause)
diff --git a/mobile/packages/native_video_editor/android/src/main/kotlin/io/ente/native_video_editor/NativeVideoEditorPlugin.kt b/mobile/packages/native_video_editor/android/src/main/kotlin/io/ente/native_video_editor/NativeVideoEditorPlugin.kt
new file mode 100644
index 0000000000..bb3ecf6fc3
--- /dev/null
+++ b/mobile/packages/native_video_editor/android/src/main/kotlin/io/ente/native_video_editor/NativeVideoEditorPlugin.kt
@@ -0,0 +1,342 @@
+package io.ente.native_video_editor
+
+import android.content.Context
+import android.media.*
+import android.os.Build
+import android.util.Log
+import androidx.annotation.NonNull
+import io.flutter.embedding.engine.plugins.FlutterPlugin
+import io.flutter.plugin.common.EventChannel
+import io.flutter.plugin.common.MethodCall
+import io.flutter.plugin.common.MethodChannel
+import io.flutter.plugin.common.MethodChannel.MethodCallHandler
+import io.flutter.plugin.common.MethodChannel.Result
+import kotlinx.coroutines.*
+import java.io.File
+import java.nio.ByteBuffer
+
+class NativeVideoEditorPlugin : FlutterPlugin, MethodCallHandler, EventChannel.StreamHandler {
+ private lateinit var channel: MethodChannel
+ private lateinit var progressChannel: EventChannel
+ private var progressEventSink: EventChannel.EventSink? = null
+ private lateinit var context: Context
+ private val scope = CoroutineScope(Dispatchers.IO + SupervisorJob())
+ private var currentJob: Job? = null
+
+ // Unified Media3 Transformer processor for all operations
+ private lateinit var media3Processor: Media3TransformerProcessor
+
+ companion object {
+ private const val TAG = "NativeVideoEditorPlugin"
+ }
+
+ override fun onAttachedToEngine(@NonNull flutterPluginBinding: FlutterPlugin.FlutterPluginBinding) {
+ context = flutterPluginBinding.applicationContext
+ channel = MethodChannel(flutterPluginBinding.binaryMessenger, "native_video_editor")
+ channel.setMethodCallHandler(this)
+
+ progressChannel = EventChannel(flutterPluginBinding.binaryMessenger, "native_video_editor/progress")
+ progressChannel.setStreamHandler(this)
+
+ // Initialize unified Media3 processor
+ media3Processor = Media3TransformerProcessor(context)
+ }
+
+ override fun onMethodCall(@NonNull call: MethodCall, @NonNull result: Result) {
+ when (call.method) {
+ "trimVideo" -> {
+ val inputPath = call.argument<String>("inputPath")!!
+ val outputPath = call.argument<String>("outputPath")!!
+ val startTimeMs = call.argument<Int>("startTimeMs")!!.toLong()
+ val endTimeMs = call.argument<Int>("endTimeMs")!!.toLong()
+
+ currentJob = scope.launch {
+ try {
+ // Use unified Media3 Transformer for optimized trimming
+ val processingResult = media3Processor.trimVideo(
+ inputPath = inputPath,
+ outputPath = outputPath,
+ startTimeMs = startTimeMs,
+ endTimeMs = endTimeMs,
+ onProgress = { progress ->
+ scope.launch(Dispatchers.Main) {
+ progressEventSink?.success(progress)
+ }
+ }
+ )
+
+ withContext(Dispatchers.Main) {
+ result.success(
+ mapOf(
+ "outputPath" to processingResult.outputPath,
+ "isReEncoded" to processingResult.isReEncoded,
+ "processingTimeMs" to processingResult.processingTimeMs,
+ "method" to processingResult.method
+ )
+ )
+ }
+ } catch (e: Exception) {
+ // Log.e(TAG, "Trim failed", e)
+ withContext(Dispatchers.Main) {
+ result.error("TRIM_ERROR", e.message, null)
+ }
+ } finally {
+ currentJob = null
+ }
+ }
+ }
+
+ "rotateVideo" -> {
+ val inputPath = call.argument<String>("inputPath")!!
+ val outputPath = call.argument<String>("outputPath")!!
+ val degrees = call.argument<Int>("degrees")!!
+
+ currentJob = scope.launch {
+ try {
+ // Use unified Media3 Transformer for rotation with proper effects
+ val processingResult = media3Processor.rotateVideo(
+ inputPath = inputPath,
+ outputPath = outputPath,
+ degrees = degrees,
+ onProgress = { progress ->
+ scope.launch(Dispatchers.Main) {
+ progressEventSink?.success(progress)
+ }
+ }
+ )
+
+ withContext(Dispatchers.Main) {
+ result.success(
+ mapOf(
+ "outputPath" to processingResult.outputPath,
+ "isReEncoded" to processingResult.isReEncoded,
+ "processingTimeMs" to processingResult.processingTimeMs,
+ "method" to processingResult.method
+ )
+ )
+ }
+ } catch (e: Exception) {
+ // Log.e(TAG, "Rotation failed", e)
+ withContext(Dispatchers.Main) {
+ result.error("ROTATE_ERROR", e.message, null)
+ }
+ } finally {
+ currentJob = null
+ }
+ }
+ }
+
+ "cropVideo" -> {
+ val inputPath = call.argument<String>("inputPath")!!
+ val outputPath = call.argument<String>("outputPath")!!
+ val x = call.argument<Int>("x")!!
+ val y = call.argument<Int>("y")!!
+ val width = call.argument<Int>("width")!!
+ val height = call.argument<Int>("height")!!
+
+ currentJob = scope.launch {
+ try {
+ // Use unified Media3 Transformer for cropping with proper effects
+ val processingResult = media3Processor.cropVideo(
+ inputPath = inputPath,
+ outputPath = outputPath,
+ cropX = x,
+ cropY = y,
+ cropWidth = width,
+ cropHeight = height,
+ onProgress = { progress ->
+ scope.launch(Dispatchers.Main) {
+ progressEventSink?.success(progress)
+ }
+ }
+ )
+
+ withContext(Dispatchers.Main) {
+ result.success(
+ mapOf(
+ "outputPath" to processingResult.outputPath,
+ "isReEncoded" to processingResult.isReEncoded,
+ "processingTimeMs" to processingResult.processingTimeMs,
+ "method" to processingResult.method
+ )
+ )
+ }
+ } catch (e: Exception) {
+ // Log.e(TAG, "Crop failed", e)
+ withContext(Dispatchers.Main) {
+ result.error("CROP_ERROR", e.message, null)
+ }
+ } finally {
+ currentJob = null
+ }
+ }
+ }
+
+ "processVideo" -> {
+ handleProcessVideo(call, result)
+ }
+
+ "getVideoInfo" -> {
+ val videoPath = call.argument<String>("videoPath")!!
+ currentJob = scope.launch {
+ try {
+ val info = getVideoInfo(videoPath)
+ withContext(Dispatchers.Main) {
+ result.success(info)
+ }
+ } catch (e: Exception) {
+ withContext(Dispatchers.Main) {
+ result.error("INFO_ERROR", e.message, null)
+ }
+ } finally {
+ currentJob = null
+ }
+ }
+ }
+
+ "cancelProcessing" -> {
+ currentJob?.cancel()
+ result.success(null)
+ }
+
+ else -> result.notImplemented()
+ }
+ }
+
+ private fun getVideoInfo(videoPath: String): Map<String, Any> {
+ val retriever = MediaMetadataRetriever()
+ return try {
+ retriever.setDataSource(videoPath)
+
+ val duration = retriever.extractMetadata(
+ MediaMetadataRetriever.METADATA_KEY_DURATION
+ )?.toLongOrNull() ?: run {
+ Log.w(TAG, "Failed to extract duration metadata from video: $videoPath")
+ 0L
+ }
+
+ val width = retriever.extractMetadata(
+ MediaMetadataRetriever.METADATA_KEY_VIDEO_WIDTH
+ )?.toIntOrNull() ?: run {
+ Log.w(TAG, "Failed to extract width metadata from video: $videoPath")
+ 0
+ }
+
+ val height = retriever.extractMetadata(
+ MediaMetadataRetriever.METADATA_KEY_VIDEO_HEIGHT
+ )?.toIntOrNull() ?: run {
+ Log.w(TAG, "Failed to extract height metadata from video: $videoPath")
+ 0
+ }
+
+ val rotation = retriever.extractMetadata(
+ MediaMetadataRetriever.METADATA_KEY_VIDEO_ROTATION
+ )?.toIntOrNull() ?: run {
+ Log.w(TAG, "Failed to extract rotation metadata from video: $videoPath")
+ 0
+ }
+
+ val bitrate = retriever.extractMetadata(
+ MediaMetadataRetriever.METADATA_KEY_BITRATE
+ )?.toLongOrNull() ?: run {
+ Log.w(TAG, "Failed to extract bitrate metadata from video: $videoPath")
+ 0L
+ }
+
+ val frameRate = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
+ retriever.extractMetadata(
+ MediaMetadataRetriever.METADATA_KEY_CAPTURE_FRAMERATE
+ )?.toFloatOrNull() ?: run {
+ Log.w(TAG, "Failed to extract frame rate metadata from video: $videoPath")
+ 0f
+ }
+ } else {
+ 0f
+ }
+
+ mapOf(
+ "duration" to duration,
+ "width" to width,
+ "height" to height,
+ "rotation" to rotation,
+ "bitrate" to bitrate,
+ "frameRate" to frameRate
+ )
+ } finally {
+ retriever.release()
+ }
+ }
+
+ private fun handleProcessVideo(call: MethodCall, result: Result) {
+ val inputPath = call.argument<String>("inputPath")!!
+ val outputPath = call.argument<String>("outputPath")!!
+
+ currentJob = scope.launch {
+ try {
+ // Collect all transformation parameters
+ val trimStartMs = call.argument<Int>("trimStartMs")?.toLong()
+ val trimEndMs = call.argument<Int>("trimEndMs")?.toLong()
+ val rotateDegrees = call.argument<Int>("rotateDegrees")
+ val cropX = call.argument<Int>("cropX")
+ val cropY = call.argument<Int>("cropY")
+ val cropWidth = call.argument<Int>("cropWidth")
+ val cropHeight = call.argument<Int>("cropHeight")
+
+ // Process all transformations in a single pass with Media3 Transformer
+ val processingResult = media3Processor.processVideo(
+ inputPath = inputPath,
+ outputPath = outputPath,
+ trimStartMs = trimStartMs,
+ trimEndMs = trimEndMs,
+ rotateDegrees = rotateDegrees,
+ cropX = cropX,
+ cropY = cropY,
+ cropWidth = cropWidth,
+ cropHeight = cropHeight,
+ onProgress = { progress ->
+ scope.launch(Dispatchers.Main) {
+ progressEventSink?.success(progress)
+ }
+ }
+ )
+
+ val processingSteps = mutableListOf<String>()
+ if (trimStartMs != null) processingSteps.add("Trim")
+ if (rotateDegrees != null && rotateDegrees != 0) processingSteps.add("Rotate")
+ if (cropX != null) processingSteps.add("Crop")
+
+ withContext(Dispatchers.Main) {
+ result.success(
+ mapOf(
+ "outputPath" to outputPath,
+ "isReEncoded" to processingResult.isReEncoded,
+ "processingTimeMs" to processingResult.processingTimeMs,
+ "processingSteps" to processingSteps
+ )
+ )
+ }
+ } catch (e: Exception) {
+ // Log.e(TAG, "Process video failed", e)
+ withContext(Dispatchers.Main) {
+ result.error("PROCESS_ERROR", e.message, null)
+ }
+ } finally {
+ currentJob = null
+ }
+ }
+ }
+
+ override fun onDetachedFromEngine(@NonNull binding: FlutterPlugin.FlutterPluginBinding) {
+ channel.setMethodCallHandler(null)
+ progressChannel.setStreamHandler(null)
+ scope.cancel()
+ }
+
+ override fun onListen(arguments: Any?, events: EventChannel.EventSink?) {
+ progressEventSink = events
+ }
+
+ override fun onCancel(arguments: Any?) {
+ progressEventSink = null
+ }
+}
diff --git a/mobile/packages/native_video_editor/ios/Classes/NativeVideoEditorPlugin.swift b/mobile/packages/native_video_editor/ios/Classes/NativeVideoEditorPlugin.swift
new file mode 100644
index 0000000000..9d65b0c2b3
--- /dev/null
+++ b/mobile/packages/native_video_editor/ios/Classes/NativeVideoEditorPlugin.swift
@@ -0,0 +1,642 @@
+import Flutter
+import UIKit
+import AVFoundation
+import Photos
+
+public class NativeVideoEditorPlugin: NSObject, FlutterPlugin {
+ private var currentExportSession: AVAssetExportSession?
+ private var progressEventSink: FlutterEventSink?
+ private var progressTimer: Timer?
+
+ public static func register(with registrar: FlutterPluginRegistrar) {
+ let channel = FlutterMethodChannel(name: "native_video_editor", binaryMessenger: registrar.messenger())
+ let instance = NativeVideoEditorPlugin()
+ registrar.addMethodCallDelegate(instance, channel: channel)
+
+ let progressChannel = FlutterEventChannel(name: "native_video_editor/progress", binaryMessenger: registrar.messenger())
+ progressChannel.setStreamHandler(instance)
+ }
+
+ public func handle(_ call: FlutterMethodCall, result: @escaping FlutterResult) {
+ switch call.method {
+ case "trimVideo":
+ guard let args = call.arguments as? [String: Any],
+ let inputPath = args["inputPath"] as? String,
+ let outputPath = args["outputPath"] as? String,
+ let startTimeMs = args["startTimeMs"] as? Int,
+ let endTimeMs = args["endTimeMs"] as? Int else {
+ result(flutterError("INVALID_ARGS", message: "Invalid arguments"))
+ return
+ }
+
+ trimVideo(inputPath: inputPath, outputPath: outputPath,
+ startTimeMs: startTimeMs, endTimeMs: endTimeMs, result: result)
+
+ case "rotateVideo":
+ guard let args = call.arguments as? [String: Any],
+ let inputPath = args["inputPath"] as? String,
+ let outputPath = args["outputPath"] as? String,
+ let degrees = args["degrees"] as? Int else {
+ result(flutterError("INVALID_ARGS", message: "Invalid arguments"))
+ return
+ }
+
+ rotateVideo(inputPath: inputPath, outputPath: outputPath,
+ degrees: degrees, result: result)
+
+ case "cropVideo":
+ guard let args = call.arguments as? [String: Any],
+ let inputPath = args["inputPath"] as? String,
+ let outputPath = args["outputPath"] as? String,
+ let x = args["x"] as? Int,
+ let y = args["y"] as? Int,
+ let width = args["width"] as? Int,
+ let height = args["height"] as? Int else {
+ result(flutterError("INVALID_ARGS", message: "Invalid arguments"))
+ return
+ }
+
+ cropVideo(inputPath: inputPath, outputPath: outputPath,
+ x: x, y: y, width: width, height: height, result: result)
+
+ case "processVideo":
+ handleProcessVideo(call: call, result: result)
+
+ case "getVideoInfo":
+ guard let args = call.arguments as? [String: Any],
+ let videoPath = args["videoPath"] as? String else {
+ result(flutterError("INVALID_ARGS", message: "Invalid arguments"))
+ return
+ }
+
+ getVideoInfo(videoPath: videoPath, result: result)
+
+ case "cancelProcessing":
+ currentExportSession?.cancelExport()
+ result(nil)
+
+ default:
+ result(FlutterMethodNotImplemented)
+ }
+ }
+
+ private func trimVideo(inputPath: String, outputPath: String,
+ startTimeMs: Int, endTimeMs: Int, result: @escaping FlutterResult) {
+ let asset = AVAsset(url: URL(fileURLWithPath: inputPath))
+
+ guard let exportSession = AVAssetExportSession(asset: asset,
+ presetName: AVAssetExportPresetPassthrough) else {
+ result(flutterError("EXPORT_ERROR", message: "Failed to create export session"))
+ return
+ }
+
+ currentExportSession = exportSession
+
+ let startTime = CMTime(value: CMTimeValue(startTimeMs), timescale: 1000)
+ let endTime = CMTime(value: CMTimeValue(endTimeMs), timescale: 1000)
+ let timeRange = CMTimeRange(start: startTime, end: endTime)
+
+ exportSession.timeRange = timeRange
+ exportSession.outputURL = URL(fileURLWithPath: outputPath)
+ exportSession.outputFileType = .mp4
+ exportSession.shouldOptimizeForNetworkUse = true
+
+ startProgressReporting()
+ exportSession.exportAsynchronously {
+ DispatchQueue.main.async {
+ self.stopProgressReporting()
+ switch exportSession.status {
+ case .completed:
+ result([
+ "outputPath": outputPath,
+ "isReEncoded": false
+ ])
+ case .failed:
+ result(self.flutterError("TRIM_ERROR", message: "Failed to trim video", error: exportSession.error))
+ case .cancelled:
+ result(self.flutterError("CANCELLED", message: "Export cancelled"))
+ default:
+ result(self.flutterError("UNKNOWN", message: "Unknown export status", error: exportSession.error))
+ }
+ self.currentExportSession = nil
+ }
+ }
+ }
+
+ private func rotateVideo(inputPath: String, outputPath: String,
+ degrees: Int, result: @escaping FlutterResult) {
+ let asset = AVAsset(url: URL(fileURLWithPath: inputPath))
+
+ guard let videoTrack = asset.tracks(withMediaType: .video).first else {
+ result(flutterError("NO_VIDEO", message: "No video track found"))
+ return
+ }
+
+ let composition = AVMutableComposition()
+ guard let compositionVideoTrack = composition.addMutableTrack(
+ withMediaType: .video,
+ preferredTrackID: kCMPersistentTrackID_Invalid) else {
+ result(flutterError("COMPOSITION_ERROR", message: "Failed to create composition track"))
+ return
+ }
+
+ var compositionAudioTrack: AVMutableCompositionTrack?
+ if let audioTrack = asset.tracks(withMediaType: .audio).first {
+ compositionAudioTrack = composition.addMutableTrack(
+ withMediaType: .audio,
+ preferredTrackID: kCMPersistentTrackID_Invalid)
+ }
+
+ do {
+ try compositionVideoTrack.insertTimeRange(
+ CMTimeRange(start: .zero, duration: asset.duration),
+ of: videoTrack,
+ at: .zero)
+
+ if let audioTrack = asset.tracks(withMediaType: .audio).first,
+ let compAudioTrack = compositionAudioTrack {
+ try compAudioTrack.insertTimeRange(
+ CMTimeRange(start: .zero, duration: asset.duration),
+ of: audioTrack,
+ at: .zero)
+ }
+ } catch {
+ result(flutterError("INSERT_ERROR", message: "Failed to insert track", error: error))
+ return
+ }
+
+ let videoComposition = AVMutableVideoComposition()
+ videoComposition.frameDuration = frameDuration(for: videoTrack)
+
+ let naturalSize = videoTrack.naturalSize
+ var renderSize = naturalSize
+ var transform = CGAffineTransform.identity
+
+ switch degrees {
+ case 90:
+ transform = CGAffineTransform(rotationAngle: .pi / 2)
+ .translatedBy(x: 0, y: -naturalSize.width)
+ renderSize = CGSize(width: naturalSize.height, height: naturalSize.width)
+ case 180:
+ transform = CGAffineTransform(rotationAngle: .pi)
+ .translatedBy(x: -naturalSize.width, y: -naturalSize.height)
+ case 270:
+ transform = CGAffineTransform(rotationAngle: -.pi / 2)
+ .translatedBy(x: -naturalSize.height, y: 0)
+ renderSize = CGSize(width: naturalSize.height, height: naturalSize.width)
+ default:
+ result(flutterError("INVALID_DEGREES", message: "Degrees must be 90, 180, or 270"))
+ return
+ }
+
+ videoComposition.renderSize = renderSize
+
+ let instruction = AVMutableVideoCompositionInstruction()
+ instruction.timeRange = CMTimeRange(start: .zero, duration: composition.duration)
+
+ let layerInstruction = AVMutableVideoCompositionLayerInstruction(assetTrack: compositionVideoTrack)
+ layerInstruction.setTransform(transform, at: .zero)
+
+ instruction.layerInstructions = [layerInstruction]
+ videoComposition.instructions = [instruction]
+
+ guard let exportSession = AVAssetExportSession(
+ asset: composition,
+ presetName: AVAssetExportPresetHighestQuality) else {
+ result(flutterError("EXPORT_ERROR", message: "Failed to create export session"))
+ return
+ }
+
+ currentExportSession = exportSession
+
+ exportSession.videoComposition = videoComposition
+ exportSession.outputURL = URL(fileURLWithPath: outputPath)
+ exportSession.outputFileType = .mp4
+ exportSession.shouldOptimizeForNetworkUse = true
+
+ startProgressReporting()
+ exportSession.exportAsynchronously {
+ DispatchQueue.main.async {
+ self.stopProgressReporting()
+ switch exportSession.status {
+ case .completed:
+ result([
+ "outputPath": outputPath,
+ "isReEncoded": true
+ ])
+ case .failed:
+ result(self.flutterError("ROTATE_ERROR", message: "Failed to rotate video", error: exportSession.error))
+ case .cancelled:
+ result(self.flutterError("CANCELLED", message: "Export cancelled"))
+ default:
+ result(self.flutterError("UNKNOWN", message: "Unknown export status", error: exportSession.error))
+ }
+ self.currentExportSession = nil
+ }
+ }
+ }
+
+ private func cropVideo(inputPath: String, outputPath: String,
+ x: Int, y: Int, width: Int, height: Int, result: @escaping FlutterResult) {
+ let asset = AVAsset(url: URL(fileURLWithPath: inputPath))
+
+ guard let videoTrack = asset.tracks(withMediaType: .video).first else {
+ result(flutterError("NO_VIDEO", message: "No video track found"))
+ return
+ }
+
+ let composition = AVMutableComposition()
+ guard let compositionVideoTrack = composition.addMutableTrack(
+ withMediaType: .video,
+ preferredTrackID: kCMPersistentTrackID_Invalid) else {
+ result(flutterError("COMPOSITION_ERROR", message: "Failed to create composition track"))
+ return
+ }
+
+ var compositionAudioTrack: AVMutableCompositionTrack?
+ if let audioTrack = asset.tracks(withMediaType: .audio).first {
+ compositionAudioTrack = composition.addMutableTrack(
+ withMediaType: .audio,
+ preferredTrackID: kCMPersistentTrackID_Invalid)
+ }
+
+ do {
+ try compositionVideoTrack.insertTimeRange(
+ CMTimeRange(start: .zero, duration: asset.duration),
+ of: videoTrack,
+ at: .zero)
+
+ if let audioTrack = asset.tracks(withMediaType: .audio).first,
+ let compAudioTrack = compositionAudioTrack {
+ try compAudioTrack.insertTimeRange(
+ CMTimeRange(start: .zero, duration: asset.duration),
+ of: audioTrack,
+ at: .zero)
+ }
+ } catch {
+ result(flutterError("INSERT_ERROR", message: "Failed to insert track", error: error))
+ return
+ }
+
+ // Create video composition for cropping
+ let videoComposition = AVMutableVideoComposition()
+ videoComposition.frameDuration = frameDuration(for: videoTrack)
+ videoComposition.renderSize = CGSize(width: width, height: height)
+
+ // Create layer instruction with crop transform
+ let instruction = AVMutableVideoCompositionInstruction()
+ instruction.timeRange = CMTimeRange(start: .zero, duration: composition.duration)
+
+ let layerInstruction = AVMutableVideoCompositionLayerInstruction(assetTrack: compositionVideoTrack)
+
+ let originalTransform = videoTrack.preferredTransform
+ let cropTransform = CGAffineTransform(translationX: CGFloat(-x), y: CGFloat(-y))
+ let finalTransform = originalTransform.concatenating(cropTransform)
+
+ layerInstruction.setTransform(finalTransform, at: .zero)
+ // Note: setCropRectangle is deprecated in iOS 15.0+, but we continue to use it for backward compatibility
+ // TODO: Migrate to using CIFilter-based cropping when minimum iOS version allows
+ layerInstruction.setCropRectangle(CGRect(x: 0, y: 0, width: CGFloat(width), height: CGFloat(height)), at: .zero)
+
+ instruction.layerInstructions = [layerInstruction]
+ videoComposition.instructions = [instruction]
+
+ guard let exportSession = AVAssetExportSession(
+ asset: composition,
+ presetName: AVAssetExportPresetHighestQuality) else {
+ result(flutterError("EXPORT_ERROR", message: "Failed to create export session"))
+ return
+ }
+
+ currentExportSession = exportSession
+
+ exportSession.videoComposition = videoComposition
+ exportSession.outputURL = URL(fileURLWithPath: outputPath)
+ exportSession.outputFileType = .mp4
+ exportSession.shouldOptimizeForNetworkUse = true
+
+ startProgressReporting()
+ exportSession.exportAsynchronously {
+ DispatchQueue.main.async {
+ self.stopProgressReporting()
+ switch exportSession.status {
+ case .completed:
+ result([
+ "outputPath": outputPath,
+ "isReEncoded": true
+ ])
+ case .failed:
+ result(self.flutterError("CROP_ERROR", message: "Failed to crop video", error: exportSession.error))
+ case .cancelled:
+ result(self.flutterError("CANCELLED", message: "Export cancelled"))
+ default:
+ result(self.flutterError("UNKNOWN", message: "Unknown export status", error: exportSession.error))
+ }
+ self.currentExportSession = nil
+ }
+ }
+ }
+
+ private func handleProcessVideo(call: FlutterMethodCall, result: @escaping FlutterResult) {
+ guard let args = call.arguments as? [String: Any],
+ let inputPath = args["inputPath"] as? String,
+ let outputPath = args["outputPath"] as? String else {
+ result(flutterError("INVALID_ARGS", message: "Invalid arguments"))
+ return
+ }
+
+ let asset = AVAsset(url: URL(fileURLWithPath: inputPath))
+ var composition = AVMutableComposition()
+ var videoComposition: AVMutableVideoComposition?
+
+ // Handle trim
+ var timeRange = CMTimeRange(start: .zero, duration: asset.duration)
+ if let trimStartMs = args["trimStartMs"] as? Int,
+ let trimEndMs = args["trimEndMs"] as? Int {
+ let startTime = CMTime(value: CMTimeValue(trimStartMs), timescale: 1000)
+ let endTime = CMTime(value: CMTimeValue(trimEndMs), timescale: 1000)
+ timeRange = CMTimeRange(start: startTime, end: endTime)
+ }
+
+ guard let videoTrack = asset.tracks(withMediaType: .video).first,
+ let compositionVideoTrack = composition.addMutableTrack(
+ withMediaType: .video,
+ preferredTrackID: kCMPersistentTrackID_Invalid) else {
+ result(flutterError("COMPOSITION_ERROR", message: "Failed to create composition"))
+ return
+ }
+
+ do {
+ try compositionVideoTrack.insertTimeRange(timeRange, of: videoTrack, at: .zero)
+
+ if let audioTrack = asset.tracks(withMediaType: .audio).first,
+ let compositionAudioTrack = composition.addMutableTrack(
+ withMediaType: .audio,
+ preferredTrackID: kCMPersistentTrackID_Invalid) {
+ try compositionAudioTrack.insertTimeRange(timeRange, of: audioTrack, at: .zero)
+ }
+ } catch {
+ result(flutterError("INSERT_ERROR", message: "Failed to insert track", error: error))
+ return
+ }
+
+ var isReEncoded = false
+
+ let naturalSize = videoTrack.naturalSize
+ let preferredTransform = videoTrack.preferredTransform
+ var finalTransform = preferredTransform
+ var renderSize = naturalSize
+
+ if let cropX = args["cropX"] as? Int,
+ let cropY = args["cropY"] as? Int,
+ let cropWidth = args["cropWidth"] as? Int,
+ let cropHeight = args["cropHeight"] as? Int {
+ isReEncoded = true
+
+ renderSize = CGSize(width: CGFloat(cropWidth), height: CGFloat(cropHeight))
+
+ let transformedBounds = CGRect(origin: .zero, size: naturalSize).applying(preferredTransform)
+ var transform = preferredTransform
+
+ var translateX: CGFloat = 0
+ var translateY: CGFloat = 0
+
+ if transformedBounds.minX < 0 {
+ translateX = -transformedBounds.minX
+ }
+ if transformedBounds.minY < 0 {
+ translateY = -transformedBounds.minY
+ }
+
+ translateX -= CGFloat(cropX)
+ translateY -= CGFloat(cropY)
+
+ transform = transform.concatenating(CGAffineTransform(translationX: translateX, y: translateY))
+
+ if let rotateDegrees = args["rotateDegrees"] as? Int, rotateDegrees != 0 {
+ // iOS CGAffineTransform rotates counter-clockwise for positive angles
+ // To match Android behavior (positive = clockwise), we negate the radians
+ let radians = CGFloat(rotateDegrees) * .pi / 180
+ let clockwiseRadians = -radians
+
+ let oldCenterX = renderSize.width / 2
+ let oldCenterY = renderSize.height / 2
+
+ if abs(rotateDegrees) == 90 || abs(rotateDegrees) == 270 {
+ renderSize = CGSize(width: renderSize.height, height: renderSize.width)
+ }
+
+ let rotationTransform = CGAffineTransform(translationX: oldCenterX, y: oldCenterY)
+ .rotated(by: clockwiseRadians)
+ .translatedBy(x: -oldCenterX, y: -oldCenterY)
+
+ transform = transform.concatenating(rotationTransform)
+
+ let testRect = CGRect(origin: .zero, size: CGSize(width: cropWidth, height: cropHeight))
+ let finalBounds = testRect.applying(transform)
+
+ var additionalTranslateX: CGFloat = 0
+ var additionalTranslateY: CGFloat = 0
+
+ if finalBounds.minX < 0 {
+ additionalTranslateX = -finalBounds.minX
+ }
+ if finalBounds.minY < 0 {
+ additionalTranslateY = -finalBounds.minY
+ }
+
+ if additionalTranslateX != 0 || additionalTranslateY != 0 {
+ transform = transform.concatenating(CGAffineTransform(translationX: additionalTranslateX, y: additionalTranslateY))
+ }
+ }
+
+ finalTransform = transform
+
+ } else if let rotateDegrees = args["rotateDegrees"] as? Int, rotateDegrees != 0 {
+ isReEncoded = true
+
+ var orientedSize = naturalSize.applying(preferredTransform)
+ orientedSize = CGSize(width: abs(orientedSize.width), height: abs(orientedSize.height))
+
+ var transform = preferredTransform
+
+ // iOS CGAffineTransform rotates counter-clockwise for positive angles
+ // To match Android behavior (positive = clockwise), we negate the radians
+ let radians = CGFloat(rotateDegrees) * .pi / 180
+ let clockwiseRadians = -radians
+
+ // Rotate around the center of the input video
+ let centerX = orientedSize.width / 2
+ let centerY = orientedSize.height / 2
+
+ transform = transform.translatedBy(x: centerX, y: centerY)
+ transform = transform.rotated(by: clockwiseRadians)
+ transform = transform.translatedBy(x: -centerX, y: -centerY)
+
+ // Set renderSize based on rotation
+ if abs(rotateDegrees) == 90 || abs(rotateDegrees) == 270 {
+ renderSize = CGSize(width: orientedSize.height, height: orientedSize.width)
+ } else {
+ renderSize = orientedSize
+ }
+
+ // Use bounds testing to calculate the necessary translation to center the video
+ let testRect = CGRect(origin: .zero, size: orientedSize)
+ let finalBounds = testRect.applying(transform)
+
+ // Center the video in the renderSize
+ let targetMinX: CGFloat = (renderSize.width - finalBounds.width) / 2
+ let additionalTranslateX = targetMinX - finalBounds.minX
+
+ let targetMinY: CGFloat = (renderSize.height - finalBounds.height) / 2
+ let additionalTranslateY = targetMinY - finalBounds.minY
+
+ transform = transform.concatenating(CGAffineTransform(translationX: additionalTranslateX, y: additionalTranslateY))
+
+ finalTransform = transform
+ }
+
+ if isReEncoded {
+ videoComposition = AVMutableVideoComposition()
+ videoComposition!.frameDuration = frameDuration(for: videoTrack)
+ videoComposition!.renderSize = renderSize
+
+ let instruction = AVMutableVideoCompositionInstruction()
+ instruction.timeRange = CMTimeRange(start: .zero, duration: composition.duration)
+
+ let layerInstruction = AVMutableVideoCompositionLayerInstruction(assetTrack: compositionVideoTrack)
+ layerInstruction.setTransform(finalTransform, at: .zero)
+
+ instruction.layerInstructions = [layerInstruction]
+ videoComposition!.instructions = [instruction]
+ }
+
+ // Export
+ let presetName = isReEncoded ? AVAssetExportPresetHighestQuality : AVAssetExportPresetPassthrough
+ guard let exportSession = AVAssetExportSession(asset: composition, presetName: presetName) else {
+ result(flutterError("EXPORT_ERROR", message: "Failed to create export session"))
+ return
+ }
+
+ currentExportSession = exportSession
+
+ if let videoComp = videoComposition {
+ exportSession.videoComposition = videoComp
+ }
+
+ exportSession.outputURL = URL(fileURLWithPath: outputPath)
+ exportSession.outputFileType = .mp4
+ exportSession.shouldOptimizeForNetworkUse = true
+
+ if !isReEncoded {
+ exportSession.timeRange = timeRange
+ }
+
+ startProgressReporting()
+ exportSession.exportAsynchronously {
+ DispatchQueue.main.async {
+ self.stopProgressReporting()
+ switch exportSession.status {
+ case .completed:
+ result([
+ "outputPath": outputPath,
+ "isReEncoded": isReEncoded
+ ])
+ case .failed:
+ result(self.flutterError("PROCESS_ERROR", message: "Failed to process video", error: exportSession.error))
+ case .cancelled:
+ result(self.flutterError("CANCELLED", message: "Export cancelled"))
+ default:
+ result(self.flutterError("UNKNOWN", message: "Unknown export status", error: exportSession.error))
+ }
+ self.currentExportSession = nil
+ }
+ }
+ }
+
+ private func frameDuration(for track: AVAssetTrack) -> CMTime {
+ let nominal = track.nominalFrameRate
+ if nominal.isFinite && nominal > 0 {
+ return CMTime(value: 1, timescale: Int32(round(nominal)))
+ }
+ if track.minFrameDuration.isValid && track.minFrameDuration.value != 0 {
+ return track.minFrameDuration
+ }
+ return CMTime(value: 1, timescale: 30)
+ }
+
+ private func flutterError(_ code: String, message: String, error: Error? = nil, details: Any? = nil) -> FlutterError {
+ let resolvedMessage = error?.localizedDescription ?? message
+ let resolvedDetails: Any?
+ if let details = details {
+ resolvedDetails = details
+ } else if let error = error {
+ resolvedDetails = String(describing: error)
+ } else {
+ resolvedDetails = nil
+ }
+ return FlutterError(code: code, message: resolvedMessage, details: resolvedDetails)
+ }
+
+ private func getVideoInfo(videoPath: String, result: @escaping FlutterResult) {
+ let asset = AVAsset(url: URL(fileURLWithPath: videoPath))
+
+ // Use the synchronous properties for iOS compatibility
+ let duration = asset.duration
+ let tracks = asset.tracks
+
+ var info: [String: Any] = [
+ "duration": CMTimeGetSeconds(duration) * 1000, // Convert to milliseconds
+ ]
+
+ if let videoTrack = tracks.first(where: { $0.mediaType == .video }) {
+ let naturalSize = videoTrack.naturalSize
+ let preferredTransform = videoTrack.preferredTransform
+ let nominalFrameRate = videoTrack.nominalFrameRate
+
+ info["width"] = Int(naturalSize.width)
+ info["height"] = Int(naturalSize.height)
+ info["frameRate"] = nominalFrameRate
+
+ let angle = atan2(preferredTransform.b, preferredTransform.a)
+ let rotation = Int(angle * 180 / .pi)
+ info["rotation"] = rotation
+ }
+
+ if let audioTrack = tracks.first(where: { $0.mediaType == .audio }) {
+ info["hasAudio"] = true
+ }
+
+ result(info)
+ }
+
+ private func startProgressReporting() {
+ progressTimer?.invalidate()
+ progressTimer = Timer.scheduledTimer(withTimeInterval: 0.1, repeats: true) { [weak self] _ in
+ guard let self = self,
+ let session = self.currentExportSession,
+ let sink = self.progressEventSink else { return }
+
+ let progress = Double(session.progress)
+ sink(progress)
+ }
+ }
+
+ private func stopProgressReporting() {
+ progressTimer?.invalidate()
+ progressTimer = nil
+ }
+}
+
+extension NativeVideoEditorPlugin: FlutterStreamHandler {
+ public func onListen(withArguments arguments: Any?, eventSink events: @escaping FlutterEventSink) -> FlutterError? {
+ progressEventSink = events
+ return nil
+ }
+
+ public func onCancel(withArguments arguments: Any?) -> FlutterError? {
+ progressEventSink = nil
+ stopProgressReporting()
+ return nil
+ }
+}
diff --git a/mobile/packages/native_video_editor/ios/native_video_editor.podspec b/mobile/packages/native_video_editor/ios/native_video_editor.podspec
new file mode 100644
index 0000000000..82b9cc023f
--- /dev/null
+++ b/mobile/packages/native_video_editor/ios/native_video_editor.podspec
@@ -0,0 +1,19 @@
+Pod::Spec.new do |s|
+ s.name = 'native_video_editor'
+ s.version = '0.0.1'
+ s.summary = 'Native video editing operations for iOS'
+ s.description = <<-DESC
+Native video editing operations for trim, crop, and rotate without re-encoding.
+ DESC
+ s.homepage = 'https://github.com/ente-io/ente'
+ s.license = { :file => '../LICENSE' }
+ s.author = { 'Ente' => '[email protected]' }
+ s.source = { :path => '.' }
+ s.source_files = 'Classes/**/*'
+ s.dependency 'Flutter'
+ s.platform = :ios, '11.0'
+ s.swift_version = '5.0'
+
+ # Flutter.framework does not contain a i386 slice.
+ s.pod_target_xcconfig = { 'DEFINES_MODULE' => 'YES', 'EXCLUDED_ARCHS[sdk=iphonesimulator*]' => 'i386' }
+end
\ No newline at end of file
diff --git a/mobile/packages/native_video_editor/lib/native_video_editor.dart b/mobile/packages/native_video_editor/lib/native_video_editor.dart
new file mode 100644
index 0000000000..3d1d9234be
--- /dev/null
+++ b/mobile/packages/native_video_editor/lib/native_video_editor.dart
@@ -0,0 +1,312 @@
+import 'dart:async';
+import 'dart:io';
+
+import 'package:flutter/services.dart';
+
+class VideoEditResult {
+ final String outputPath;
+ final bool isReEncoded;
+ final Duration? processingTime;
+
+ VideoEditResult({
+ required this.outputPath,
+ required this.isReEncoded,
+ this.processingTime,
+ });
+}
+
+class VideoTrimParams {
+ final String inputPath;
+ final String outputPath;
+ final Duration startTime;
+ final Duration endTime;
+
+ VideoTrimParams({
+ required this.inputPath,
+ required this.outputPath,
+ required this.startTime,
+ required this.endTime,
+ });
+
+ Map<String, dynamic> toMap() => {
+ 'inputPath': inputPath,
+ 'outputPath': outputPath,
+ 'startTimeMs': startTime.inMilliseconds,
+ 'endTimeMs': endTime.inMilliseconds,
+ };
+}
+
+class VideoRotateParams {
+ final String inputPath;
+ final String outputPath;
+ final int degrees; // Must be 90, 180, or 270
+
+ VideoRotateParams({
+ required this.inputPath,
+ required this.outputPath,
+ required this.degrees,
+ }) : assert(degrees == 90 || degrees == 180 || degrees == 270);
+
+ Map<String, dynamic> toMap() => {
+ 'inputPath': inputPath,
+ 'outputPath': outputPath,
+ 'degrees': degrees,
+ };
+}
+
+class VideoCropParams {
+ final String inputPath;
+ final String outputPath;
+ final int x;
+ final int y;
+ final int width;
+ final int height;
+ final bool forceReEncode;
+
+ VideoCropParams({
+ required this.inputPath,
+ required this.outputPath,
+ required this.x,
+ required this.y,
+ required this.width,
+ required this.height,
+ this.forceReEncode = false,
+ });
+
+ Map<String, dynamic> toMap() => {
+ 'inputPath': inputPath,
+ 'outputPath': outputPath,
+ 'x': x,
+ 'y': y,
+ 'width': width,
+ 'height': height,
+ 'forceReEncode': forceReEncode,
+ };
+}
+
+class NativeVideoEditor {
+ static const MethodChannel _channel = MethodChannel('native_video_editor');
+ static const EventChannel _progressChannel =
+ EventChannel('native_video_editor/progress');
+
+ /// Trim video without re-encoding when possible
+ /// Returns the output file path
+ static Future<VideoEditResult> trimVideo(VideoTrimParams params) async {
+ _ensureInputPathExists(params.inputPath);
+ if (params.startTime >= params.endTime) {
+ throw ArgumentError('startTime must be earlier than endTime');
+ }
+
+ try {
+ final stopwatch = Stopwatch()..start();
+
+ final result = await _channel.invokeMethod<Map<dynamic, dynamic>>(
+ 'trimVideo',
+ params.toMap(),
+ );
+
+ stopwatch.stop();
+
+ if (result == null) {
+ throw Exception('Failed to trim video: no result');
+ }
+
+ return VideoEditResult(
+ outputPath: result['outputPath'] as String,
+ isReEncoded: result['isReEncoded'] as bool? ?? false,
+ processingTime: stopwatch.elapsed,
+ );
+ } on PlatformException catch (e) {
+ throw Exception('Failed to trim video: ${e.message}');
+ }
+ }
+
+ /// Rotate video using metadata when possible (Android) or transform (iOS)
+ /// Avoids re-encoding when possible
+ static Future<VideoEditResult> rotateVideo(VideoRotateParams params) async {
+ _ensureInputPathExists(params.inputPath);
+ _validateRotationDegrees(params.degrees);
+
+ try {
+ final stopwatch = Stopwatch()..start();
+
+ final result = await _channel.invokeMethod<Map<dynamic, dynamic>>(
+ 'rotateVideo',
+ params.toMap(),
+ );
+
+ stopwatch.stop();
+
+ if (result == null) {
+ throw Exception('Failed to rotate video: no result');
+ }
+
+ return VideoEditResult(
+ outputPath: result['outputPath'] as String,
+ isReEncoded: result['isReEncoded'] as bool? ?? false,
+ processingTime: stopwatch.elapsed,
+ );
+ } on PlatformException catch (e) {
+ throw Exception('Failed to rotate video: ${e.message}');
+ }
+ }
+
+ /// Crop video - may require re-encoding depending on the format
+ static Future<VideoEditResult> cropVideo(VideoCropParams params) async {
+ _ensureInputPathExists(params.inputPath);
+ _validateCropDimensions(params.width, params.height);
+
+ try {
+ final stopwatch = Stopwatch()..start();
+
+ final result = await _channel.invokeMethod<Map<dynamic, dynamic>>(
+ 'cropVideo',
+ params.toMap(),
+ );
+
+ stopwatch.stop();
+
+ if (result == null) {
+ throw Exception('Failed to crop video: no result');
+ }
+
+ return VideoEditResult(
+ outputPath: result['outputPath'] as String,
+ isReEncoded: result['isReEncoded'] as bool? ?? true,
+ processingTime: stopwatch.elapsed,
+ );
+ } on PlatformException catch (e) {
+ throw Exception('Failed to crop video: ${e.message}');
+ }
+ }
+
+ /// Combined operation: trim, rotate, and crop in a single pass
+ /// More efficient when multiple operations are needed
+ static Future<VideoEditResult> processVideo({
+ required String inputPath,
+ required String outputPath,
+ Duration? trimStart,
+ Duration? trimEnd,
+ int? rotateDegrees,
+ Rect? cropRect,
+ void Function(double progress)? onProgress,
+ }) async {
+ _ensureInputPathExists(inputPath);
+ if (trimStart != null && trimEnd != null && trimStart >= trimEnd) {
+ throw ArgumentError('trimStart must be earlier than trimEnd');
+ }
+ if (rotateDegrees != null && rotateDegrees != 0) {
+ _validateRotationDegrees(rotateDegrees);
+ }
+ if (cropRect != null && (cropRect.width <= 0 || cropRect.height <= 0)) {
+ throw ArgumentError('cropRect must have positive width and height');
+ }
+
+ try {
+ final stopwatch = Stopwatch()..start();
+
+ final params = <String, dynamic>{
+ 'inputPath': inputPath,
+ 'outputPath': outputPath,
+ };
+
+ if (trimStart != null && trimEnd != null) {
+ params['trimStartMs'] = trimStart.inMilliseconds;
+ params['trimEndMs'] = trimEnd.inMilliseconds;
+ }
+
+ if (rotateDegrees != null) {
+ params['rotateDegrees'] = rotateDegrees;
+ }
+
+ if (cropRect != null) {
+ params['cropX'] = cropRect.left.toInt();
+ params['cropY'] = cropRect.top.toInt();
+ params['cropWidth'] = cropRect.width.toInt();
+ params['cropHeight'] = cropRect.height.toInt();
+ }
+
+ StreamSubscription? progressSubscription;
+ if (onProgress != null) {
+ progressSubscription = _progressChannel.receiveBroadcastStream().listen(
+ (dynamic event) {
+ if (event is double) {
+ onProgress(event);
+ } else if (event is int) {
+ onProgress(event.toDouble());
+ }
+ },
+ onError: (error) {},
+ );
+ }
+
+ try {
+ final result = await _channel.invokeMethod<Map<dynamic, dynamic>>(
+ 'processVideo',
+ params,
+ );
+
+ stopwatch.stop();
+
+ if (result == null) {
+ throw Exception('Failed to process video: no result');
+ }
+
+ return VideoEditResult(
+ outputPath: result['outputPath'] as String,
+ isReEncoded: result['isReEncoded'] as bool? ?? false,
+ processingTime: stopwatch.elapsed,
+ );
+ } finally {
+ await progressSubscription?.cancel();
+ }
+ } on PlatformException catch (e) {
+ throw Exception('Failed to process video: ${e.message}');
+ }
+ }
+
+ /// Get video information without processing
+ static Future<Map<String, dynamic>> getVideoInfo(String videoPath) async {
+ try {
+ final result = await _channel.invokeMethod<Map<dynamic, dynamic>>(
+ 'getVideoInfo',
+ {'videoPath': videoPath},
+ );
+
+ if (result == null) {
+ throw Exception('Failed to get video info: no result');
+ }
+
+ return Map<String, dynamic>.from(result);
+ } on PlatformException catch (e) {
+ throw Exception('Failed to get video info: ${e.message}');
+ }
+ }
+
+ /// Cancel any ongoing video processing
+ static Future<void> cancelProcessing() async {
+ try {
+ await _channel.invokeMethod('cancelProcessing');
+ } on PlatformException catch (e) {
+ throw Exception('Failed to cancel processing: ${e.message}');
+ }
+ }
+
+ static void _ensureInputPathExists(String inputPath) {
+ if (!File(inputPath).existsSync()) {
+ throw ArgumentError('Input file does not exist: $inputPath');
+ }
+ }
+
+ static void _validateRotationDegrees(int degrees) {
+ if (degrees != 90 && degrees != 180 && degrees != 270) {
+ throw ArgumentError('Rotation degrees must be 90, 180, or 270');
+ }
+ }
+
+ static void _validateCropDimensions(int width, int height) {
+ if (width <= 0 || height <= 0) {
+ throw ArgumentError('Crop dimensions must be greater than zero');
+ }
+ }
+}
diff --git a/mobile/packages/native_video_editor/lib/src/video_preview_widget.dart b/mobile/packages/native_video_editor/lib/src/video_preview_widget.dart
new file mode 100644
index 0000000000..535b1fdcac
--- /dev/null
+++ b/mobile/packages/native_video_editor/lib/src/video_preview_widget.dart
@@ -0,0 +1,111 @@
+import 'dart:io';
+
+import 'package:flutter/material.dart';
+import 'package:logging/logging.dart';
+import 'package:native_video_editor/native_video_editor.dart';
+import 'package:video_editor/video_editor.dart';
+
+/// A wrapper widget that properly handles video preview with rotation correction
+/// on Android, maintaining the correct aspect ratio.
+class NativeVideoPreview extends StatefulWidget {
+ final VideoEditorController controller;
+ final int? quarterTurnsForRotationCorrection;
+
+ const NativeVideoPreview({
+ Key? key,
+ required this.controller,
+ this.quarterTurnsForRotationCorrection,
+ }) : super(key: key);
+
+ @override
+ State<NativeVideoPreview> createState() => _NativeVideoPreviewState();
+}
+
+class _NativeVideoPreviewState extends State<NativeVideoPreview> {
+ final _logger = Logger('NativeVideoPreview');
+ bool _isLoading = true;
+
+ @override
+ void initState() {
+ super.initState();
+ _loadVideoInfo();
+ }
+
+ Future<void> _loadVideoInfo() async {
+ if (Platform.isAndroid) {
+ try {
+ // Validate rotation metadata from native code
+ // This ensures the rotation correction is needed
+ final videoPath = widget.controller.file.path;
+ final videoInfo = await NativeVideoEditor.getVideoInfo(videoPath);
+
+ final rotation = videoInfo['rotation'] as int? ?? 0;
+ final needsDimensionSwap = rotation == 90 ||
+ rotation == 270 ||
+ rotation == -90 ||
+ rotation == -270;
+
+ _logger.info(
+ 'NativeVideoPreview - Video info from native: '
+ 'width=${videoInfo['width']}, height=${videoInfo['height']}, '
+ 'rotation=${videoInfo['rotation']} '
+ '${needsDimensionSwap ? "(dimensions swapped for display due to rotation)" : ""}',
+ );
+ _logger.info(
+ 'NativeVideoPreview - Controller video: '
+ 'width=${widget.controller.video.value.size.width}, '
+ 'height=${widget.controller.video.value.size.height}',
+ );
+ _logger.info(
+ 'NativeVideoPreview - quarterTurnsForRotationCorrection=${widget.quarterTurnsForRotationCorrection}',
+ );
+
+ // The controller already has the correct aspect ratio from FFProbeProps
+ // which handles rotation internally. We only apply visual rotation correction.
+
+ setState(() {
+ _isLoading = false;
+ });
+ } catch (e) {
+ // Failed to get video info, fallback to default behavior
+ _logger.warning('Failed to get video info: $e');
+ setState(() {
+ _isLoading = false;
+ });
+ }
+ } else {
+ setState(() {
+ _isLoading = false;
+ });
+ }
+ }
+
+ @override
+ Widget build(BuildContext context) {
+ if (widget.quarterTurnsForRotationCorrection != null &&
+ widget.quarterTurnsForRotationCorrection != 0) {
+ final controllerWidth = widget.controller.video.value.size.width;
+ final controllerHeight = widget.controller.video.value.size.height;
+
+ final displayWidth = controllerHeight;
+ final displayHeight = controllerWidth;
+
+ _logger.info(
+ 'NativeVideoPreview build - '
+ 'quarterTurns=${widget.quarterTurnsForRotationCorrection}, '
+ 'Controller: ${controllerWidth}x${controllerHeight}, '
+ 'Display: ${displayWidth}x${displayHeight}',
+ );
+
+ return RotatedBox(
+ quarterTurns: widget.quarterTurnsForRotationCorrection!,
+ child: CropGridViewer.preview(
+ controller: widget.controller,
+ overrideWidth: displayWidth,
+ overrideHeight: displayHeight,
+ ),
+ );
+ }
+ return CropGridViewer.preview(controller: widget.controller);
+ }
+}
diff --git a/mobile/packages/native_video_editor/pubspec.lock b/mobile/packages/native_video_editor/pubspec.lock
new file mode 100644
index 0000000000..cf6f8f6ba3
--- /dev/null
+++ b/mobile/packages/native_video_editor/pubspec.lock
@@ -0,0 +1,387 @@
+# Generated by pub
+# See https://dart.dev/tools/pub/glossary#lockfile
+packages:
+ async:
+ dependency: transitive
+ description:
+ name: async
+ sha256: "758e6d74e971c3e5aceb4110bfd6698efc7f501675bcfe0c775459a8140750eb"
+ url: "https://pub.dev"
+ source: hosted
+ version: "2.13.0"
+ boolean_selector:
+ dependency: transitive
+ description:
+ name: boolean_selector
+ sha256: "8aab1771e1243a5063b8b0ff68042d67334e3feab9e95b9490f9a6ebf73b42ea"
+ url: "https://pub.dev"
+ source: hosted
+ version: "2.1.2"
+ characters:
+ dependency: transitive
+ description:
+ name: characters
+ sha256: f71061c654a3380576a52b451dd5532377954cf9dbd272a78fc8479606670803
+ url: "https://pub.dev"
+ source: hosted
+ version: "1.4.0"
+ clock:
+ dependency: transitive
+ description:
+ name: clock
+ sha256: fddb70d9b5277016c77a80201021d40a2247104d9f4aa7bab7157b7e3f05b84b
+ url: "https://pub.dev"
+ source: hosted
+ version: "1.1.2"
+ collection:
+ dependency: transitive
+ description:
+ name: collection
+ sha256: "2f5709ae4d3d59dd8f7cd309b4e023046b57d8a6c82130785d2b0e5868084e76"
+ url: "https://pub.dev"
+ source: hosted
+ version: "1.19.1"
+ csslib:
+ dependency: transitive
+ description:
+ name: csslib
+ sha256: "09bad715f418841f976c77db72d5398dc1253c21fb9c0c7f0b0b985860b2d58e"
+ url: "https://pub.dev"
+ source: hosted
+ version: "1.0.2"
+ fake_async:
+ dependency: transitive
+ description:
+ name: fake_async
+ sha256: "5368f224a74523e8d2e7399ea1638b37aecfca824a3cc4dfdf77bf1fa905ac44"
+ url: "https://pub.dev"
+ source: hosted
+ version: "1.3.3"
+ ffi:
+ dependency: transitive
+ description:
+ name: ffi
+ sha256: "289279317b4b16eb2bb7e271abccd4bf84ec9bdcbe999e278a94b804f5630418"
+ url: "https://pub.dev"
+ source: hosted
+ version: "2.1.4"
+ flutter:
+ dependency: "direct main"
+ description: flutter
+ source: sdk
+ version: "0.0.0"
+ flutter_lints:
+ dependency: "direct dev"
+ description:
+ name: flutter_lints
+ sha256: a25a15ebbdfc33ab1cd26c63a6ee519df92338a9c10f122adda92938253bef04
+ url: "https://pub.dev"
+ source: hosted
+ version: "2.0.3"
+ flutter_test:
+ dependency: "direct dev"
+ description: flutter
+ source: sdk
+ version: "0.0.0"
+ flutter_web_plugins:
+ dependency: transitive
+ description: flutter
+ source: sdk
+ version: "0.0.0"
+ html:
+ dependency: transitive
+ description:
+ name: html
+ sha256: "6d1264f2dffa1b1101c25a91dff0dc2daee4c18e87cd8538729773c073dbf602"
+ url: "https://pub.dev"
+ source: hosted
+ version: "0.15.6"
+ leak_tracker:
+ dependency: transitive
+ description:
+ name: leak_tracker
+ sha256: "6bb818ecbdffe216e81182c2f0714a2e62b593f4a4f13098713ff1685dfb6ab0"
+ url: "https://pub.dev"
+ source: hosted
+ version: "10.0.9"
+ leak_tracker_flutter_testing:
+ dependency: transitive
+ description:
+ name: leak_tracker_flutter_testing
+ sha256: f8b613e7e6a13ec79cfdc0e97638fddb3ab848452eff057653abd3edba760573
+ url: "https://pub.dev"
+ source: hosted
+ version: "3.0.9"
+ leak_tracker_testing:
+ dependency: transitive
+ description:
+ name: leak_tracker_testing
+ sha256: "6ba465d5d76e67ddf503e1161d1f4a6bc42306f9d66ca1e8f079a47290fb06d3"
+ url: "https://pub.dev"
+ source: hosted
+ version: "3.0.1"
+ lints:
+ dependency: transitive
+ description:
+ name: lints
+ sha256: "0a217c6c989d21039f1498c3ed9f3ed71b354e69873f13a8dfc3c9fe76f1b452"
+ url: "https://pub.dev"
+ source: hosted
+ version: "2.1.1"
+ logging:
+ dependency: "direct main"
+ description:
+ name: logging
+ sha256: c8245ada5f1717ed44271ed1c26b8ce85ca3228fd2ffdb75468ab01979309d61
+ url: "https://pub.dev"
+ source: hosted
+ version: "1.3.0"
+ matcher:
+ dependency: transitive
+ description:
+ name: matcher
+ sha256: dc58c723c3c24bf8d3e2d3ad3f2f9d7bd9cf43ec6feaa64181775e60190153f2
+ url: "https://pub.dev"
+ source: hosted
+ version: "0.12.17"
+ material_color_utilities:
+ dependency: transitive
+ description:
+ name: material_color_utilities
+ sha256: f7142bb1154231d7ea5f96bc7bde4bda2a0945d2806bb11670e30b850d56bdec
+ url: "https://pub.dev"
+ source: hosted
+ version: "0.11.1"
+ meta:
+ dependency: transitive
+ description:
+ name: meta
+ sha256: e3641ec5d63ebf0d9b41bd43201a66e3fc79a65db5f61fc181f04cd27aab950c
+ url: "https://pub.dev"
+ source: hosted
+ version: "1.16.0"
+ path:
+ dependency: transitive
+ description:
+ name: path
+ sha256: "75cca69d1490965be98c73ceaea117e8a04dd21217b37b292c9ddbec0d955bc5"
+ url: "https://pub.dev"
+ source: hosted
+ version: "1.9.1"
+ path_provider:
+ dependency: transitive
+ description:
+ name: path_provider
+ sha256: "50c5dd5b6e1aaf6fb3a78b33f6aa3afca52bf903a8a5298f53101fdaee55bbcd"
+ url: "https://pub.dev"
+ source: hosted
+ version: "2.1.5"
+ path_provider_android:
+ dependency: transitive
+ description:
+ name: path_provider_android
+ sha256: "993381400e94d18469750e5b9dcb8206f15bc09f9da86b9e44a9b0092a0066db"
+ url: "https://pub.dev"
+ source: hosted
+ version: "2.2.18"
+ path_provider_foundation:
+ dependency: transitive
+ description:
+ name: path_provider_foundation
+ sha256: "16eef174aacb07e09c351502740fa6254c165757638eba1e9116b0a781201bbd"
+ url: "https://pub.dev"
+ source: hosted
+ version: "2.4.2"
+ path_provider_linux:
+ dependency: transitive
+ description:
+ name: path_provider_linux
+ sha256: f7a1fe3a634fe7734c8d3f2766ad746ae2a2884abe22e241a8b301bf5cac3279
+ url: "https://pub.dev"
+ source: hosted
+ version: "2.2.1"
+ path_provider_platform_interface:
+ dependency: transitive
+ description:
+ name: path_provider_platform_interface
+ sha256: "88f5779f72ba699763fa3a3b06aa4bf6de76c8e5de842cf6f29e2e06476c2334"
+ url: "https://pub.dev"
+ source: hosted
+ version: "2.1.2"
+ path_provider_windows:
+ dependency: transitive
+ description:
+ name: path_provider_windows
+ sha256: bd6f00dbd873bfb70d0761682da2b3a2c2fccc2b9e84c495821639601d81afe7
+ url: "https://pub.dev"
+ source: hosted
+ version: "2.3.0"
+ platform:
+ dependency: transitive
+ description:
+ name: platform
+ sha256: "5d6b1b0036a5f331ebc77c850ebc8506cbc1e9416c27e59b439f917a902a4984"
+ url: "https://pub.dev"
+ source: hosted
+ version: "3.1.6"
+ plugin_platform_interface:
+ dependency: "direct main"
+ description:
+ name: plugin_platform_interface
+ sha256: "4820fbfdb9478b1ebae27888254d445073732dae3d6ea81f0b7e06d5dedc3f02"
+ url: "https://pub.dev"
+ source: hosted
+ version: "2.1.8"
+ sky_engine:
+ dependency: transitive
+ description: flutter
+ source: sdk
+ version: "0.0.0"
+ source_span:
+ dependency: transitive
+ description:
+ name: source_span
+ sha256: "254ee5351d6cb365c859e20ee823c3bb479bf4a293c22d17a9f1bf144ce86f7c"
+ url: "https://pub.dev"
+ source: hosted
+ version: "1.10.1"
+ stack_trace:
+ dependency: transitive
+ description:
+ name: stack_trace
+ sha256: "8b27215b45d22309b5cddda1aa2b19bdfec9df0e765f2de506401c071d38d1b1"
+ url: "https://pub.dev"
+ source: hosted
+ version: "1.12.1"
+ stream_channel:
+ dependency: transitive
+ description:
+ name: stream_channel
+ sha256: "969e04c80b8bcdf826f8f16579c7b14d780458bd97f56d107d3950fdbeef059d"
+ url: "https://pub.dev"
+ source: hosted
+ version: "2.1.4"
+ string_scanner:
+ dependency: transitive
+ description:
+ name: string_scanner
+ sha256: "921cd31725b72fe181906c6a94d987c78e3b98c2e205b397ea399d4054872b43"
+ url: "https://pub.dev"
+ source: hosted
+ version: "1.4.1"
+ term_glyph:
+ dependency: transitive
+ description:
+ name: term_glyph
+ sha256: "7f554798625ea768a7518313e58f83891c7f5024f88e46e7182a4558850a4b8e"
+ url: "https://pub.dev"
+ source: hosted
+ version: "1.2.2"
+ test_api:
+ dependency: transitive
+ description:
+ name: test_api
+ sha256: fb31f383e2ee25fbbfe06b40fe21e1e458d14080e3c67e7ba0acfde4df4e0bbd
+ url: "https://pub.dev"
+ source: hosted
+ version: "0.7.4"
+ transparent_image:
+ dependency: transitive
+ description:
+ name: transparent_image
+ sha256: e8991d955a2094e197ca24c645efec2faf4285772a4746126ca12875e54ca02f
+ url: "https://pub.dev"
+ source: hosted
+ version: "2.0.1"
+ vector_math:
+ dependency: transitive
+ description:
+ name: vector_math
+ sha256: "80b3257d1492ce4d091729e3a67a60407d227c27241d6927be0130c98e741803"
+ url: "https://pub.dev"
+ source: hosted
+ version: "2.1.4"
+ video_editor:
+ dependency: "direct main"
+ description:
+ path: "."
+ ref: master
+ resolved-ref: "1eeb18e2b1ce36bd8ca70178c0d4b485e9982257"
+ url: "https://github.com/ente-io/video_editor_fork.git"
+ source: git
+ version: "3.0.0"
+ video_player:
+ dependency: transitive
+ description:
+ name: video_player
+ sha256: "0d55b1f1a31e5ad4c4967bfaa8ade0240b07d20ee4af1dfef5f531056512961a"
+ url: "https://pub.dev"
+ source: hosted
+ version: "2.10.0"
+ video_player_android:
+ dependency: transitive
+ description:
+ name: video_player_android
+ sha256: "59e5a457ddcc1688f39e9aef0efb62aa845cf0cbbac47e44ac9730dc079a2385"
+ url: "https://pub.dev"
+ source: hosted
+ version: "2.8.13"
+ video_player_avfoundation:
+ dependency: transitive
+ description:
+ name: video_player_avfoundation
+ sha256: f9a780aac57802b2892f93787e5ea53b5f43cc57dc107bee9436458365be71cd
+ url: "https://pub.dev"
+ source: hosted
+ version: "2.8.4"
+ video_player_platform_interface:
+ dependency: transitive
+ description:
+ name: video_player_platform_interface
+ sha256: cf2a1d29a284db648fd66cbd18aacc157f9862d77d2cc790f6f9678a46c1db5a
+ url: "https://pub.dev"
+ source: hosted
+ version: "6.4.0"
+ video_player_web:
+ dependency: transitive
+ description:
+ name: video_player_web
+ sha256: "9f3c00be2ef9b76a95d94ac5119fb843dca6f2c69e6c9968f6f2b6c9e7afbdeb"
+ url: "https://pub.dev"
+ source: hosted
+ version: "2.4.0"
+ video_thumbnail:
+ dependency: transitive
+ description:
+ name: video_thumbnail
+ sha256: "181a0c205b353918954a881f53a3441476b9e301641688a581e0c13f00dc588b"
+ url: "https://pub.dev"
+ source: hosted
+ version: "0.5.6"
+ vm_service:
+ dependency: transitive
+ description:
+ name: vm_service
+ sha256: ddfa8d30d89985b96407efce8acbdd124701f96741f2d981ca860662f1c0dc02
+ url: "https://pub.dev"
+ source: hosted
+ version: "15.0.0"
+ web:
+ dependency: transitive
+ description:
+ name: web
+ sha256: "868d88a33d8a87b18ffc05f9f030ba328ffefba92d6c127917a2ba740f9cfe4a"
+ url: "https://pub.dev"
+ source: hosted
+ version: "1.1.1"
+ xdg_directories:
+ dependency: transitive
+ description:
+ name: xdg_directories
+ sha256: "7a3f37b05d989967cdddcbb571f1ea834867ae2faa29725fd085180e0883aa15"
+ url: "https://pub.dev"
+ source: hosted
+ version: "1.1.0"
+sdks:
+ dart: ">=3.7.0 <4.0.0"
+ flutter: ">=3.29.0"
diff --git a/mobile/packages/native_video_editor/pubspec.yaml b/mobile/packages/native_video_editor/pubspec.yaml
new file mode 100644
index 0000000000..3d9b99308d
--- /dev/null
+++ b/mobile/packages/native_video_editor/pubspec.yaml
@@ -0,0 +1,32 @@
+name: native_video_editor
+description: Native video editing operations for trim, crop, and rotate without re-encoding
+version: 1.0.0
+homepage: https://github.com/ente-io/ente
+
+environment:
+ sdk: ">=2.17.0 <4.0.0"
+ flutter: ">=2.5.0"
+
+dependencies:
+ flutter:
+ sdk: flutter
+ plugin_platform_interface: ^2.0.0
+ logging: ^1.2.0
+ video_editor:
+ git:
+ url: https://github.com/ente-io/video_editor_fork.git
+ ref: master
+
+dev_dependencies:
+ flutter_test:
+ sdk: flutter
+ flutter_lints: ^2.0.0
+
+flutter:
+ plugin:
+ platforms:
+ android:
+ package: io.ente.native_video_editor
+ pluginClass: NativeVideoEditorPlugin
+ ios:
+ pluginClass: NativeVideoEditorPlugin
\ No newline at end of file