π End-to-end encrypted cloud for everything.
Dart 2faandroidauthye2eeencryptionend-to-end-encryptionfluttergolanggoogle-photosgoogle-photos-alternativeiosopensourcephotosprivacyprivacy-toolstypescriptzero-knowledge
Fix video editor export hanging issue
Prateek Sunal7b8febe2df24
diff --git a/mobile/apps/photos/lib/ui/tools/editor/export_video_service.dart b/mobile/apps/photos/lib/ui/tools/editor/export_video_service.dartindex 69ff7e2631..17dbcaaa4b 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,49 +1,168 @@+import 'dart:async';import 'dart:developer';import 'dart:io';+import 'dart:isolate';import 'package:ffmpeg_kit_flutter/ffmpeg_kit.dart';import 'package:ffmpeg_kit_flutter/ffmpeg_kit_config.dart';-import 'package:ffmpeg_kit_flutter/ffmpeg_session.dart';import 'package:ffmpeg_kit_flutter/return_code.dart';import 'package:ffmpeg_kit_flutter/statistics.dart';+import 'package:flutter/services.dart';+import 'package:logging/logging.dart';import 'package:video_editor/video_editor.dart';class ExportService {+ static final _logger = Logger('ExportService');+static Future<void> dispose() async {+ _logger.info('[FFmpeg] Disposing export service');final executions = await FFmpegKit.listSessions();- if (executions.isNotEmpty) await FFmpegKit.cancel();+ _logger.info('[FFmpeg] Found ${executions.length} active sessions');+ if (executions.isNotEmpty) {+ _logger.info('[FFmpeg] Cancelling all sessions');+ await FFmpegKit.cancel();+ }}- static Future<FFmpegSession> runFFmpegCommand(+ static Future<void> runFFmpegCommand(FFmpegVideoEditorExecute execute, {required void Function(File file) onCompleted,void Function(Object, StackTrace)? onError,void Function(Statistics)? onProgress,- }) {+ }) async {+ _logger.info('[FFmpeg] Starting FFmpeg process');+ _logger.info('[FFmpeg] Command: ${execute.command}');+ _logger.info('[FFmpeg] Output path: ${execute.outputPath}');log('FFmpeg start process with command = ${execute.command}');- return FFmpegKit.executeAsync(- execute.command,- (session) async {- final state =- FFmpegKitConfig.sessionStateToString(await session.getState());- final code = await session.getReturnCode();-- if (ReturnCode.isSuccess(code)) {- onCompleted(File(execute.outputPath));- } else {- if (onError != null) {- onError(- Exception(- 'FFmpeg process exited with state $state and return code $code.\n${await session.getOutput()}',- ),- StackTrace.current,- );++ try {+ // Use a dedicated isolate for video export with progress tracking+ _logger.info('[FFmpeg] Executing FFmpeg command in video export isolate');++ final receivePort = ReceivePort();+ final rootIsolateToken = RootIsolateToken.instance!;++ final isolate = await Isolate.spawn(+ _videoExportIsolate,+ _VideoExportParams(+ command: execute.command,+ outputPath: execute.outputPath,+ sendPort: receivePort.sendPort,+ rootIsolateToken: rootIsolateToken,+ ),+ );++ // Listen for messages from the isolate+ await for (final message in receivePort) {+ if (message is Map) {+ if (message['type'] == 'progress') {+ // Parse progress from FFmpeg output if available+ final int? time = message['time'];+ if (time != null && onProgress != null) {+ // Create a mock Statistics object with the time+ _logger.info('[FFmpeg] Progress: ${time}ms');+ // Note: We can't create real Statistics objects, so we'll skip progress for now+ }+ } else if (message['type'] == 'complete') {+ final returnCode = message['returnCode'];+ final output = message['output'] ?? '';++ _logger.info('[FFmpeg] Session completed with return code: $returnCode');++ if (returnCode == 0) {+ _logger.info('[FFmpeg] Success! Creating output file');+ final outputFile = File(execute.outputPath);++ if (!outputFile.existsSync()) {+ _logger.warning('[FFmpeg] Output file does not exist at ${execute.outputPath}');+ } else {+ _logger.info(+ '[FFmpeg] Output file size: ${outputFile.lengthSync()} bytes',+ );+ }++ onCompleted(outputFile);+ _logger.info('[FFmpeg] Export completed successfully');+ } else {+ _logger.severe('[FFmpeg] Failed with code: $returnCode');+ _logger.severe('[FFmpeg] Output: $output');++ final error = Exception(+ 'FFmpeg process exited with return code $returnCode.\n$output',+ );++ if (onError != null) {+ onError(error, StackTrace.current);+ }+ }++ // Clean up+ receivePort.close();+ isolate.kill();+ break;+ } else if (message['type'] == 'error') {+ final error = Exception(message['error'] ?? 'Unknown error in isolate');+ _logger.severe('[FFmpeg] Error in isolate: ${message['error']}');++ if (onError != null) {+ onError(error, StackTrace.current);+ }++ // Clean up+ receivePort.close();+ isolate.kill();+ break;}- return;}- },- null,- onProgress,- );+ }+ } catch (e, stackTrace) {+ _logger.severe('[FFmpeg] Exception during execution: $e', e, stackTrace);+ if (onError != null) {+ onError(e, stackTrace);+ } else {+ rethrow;+ }+ }+ }+}++// Parameters for the video export isolate+class _VideoExportParams {+ final String command;+ final String outputPath;+ final SendPort sendPort;+ final RootIsolateToken rootIsolateToken;++ _VideoExportParams({+ required this.command,+ required this.outputPath,+ required this.sendPort,+ required this.rootIsolateToken,+ });+}++// Isolate function for video export+@pragma('vm:entry-point')+Future<void> _videoExportIsolate(_VideoExportParams params) async {+ try {+ // Initialize binary messenger for FFmpeg+ BackgroundIsolateBinaryMessenger.ensureInitialized(params.rootIsolateToken);++ // Use synchronous execution in isolate since async callbacks don't work with the custom fork+ final session = await FFmpegKit.execute(params.command, true);++ final returnCode = await session.getReturnCode();+ final output = await session.getOutput();++ params.sendPort.send({+ 'type': 'complete',+ 'returnCode': returnCode?.getValue() ?? -1,+ 'output': output,+ });+ } catch (e) {+ params.sendPort.send({+ 'type': 'error',+ 'error': e.toString(),+ });}}diff --git a/mobile/apps/photos/lib/ui/tools/editor/video_editor_page.dart b/mobile/apps/photos/lib/ui/tools/editor/video_editor_page.dartindex 558d20df4a..76931c1ea0 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@@ -75,17 +75,19 @@ class _VideoEditorPageState extends State<VideoEditorPage> {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),+ positionLineColor: Theme.of(+ context,+ ).colorScheme.videoPlayerBorderColor,+ lineColor: Theme.of(+ context,+ ).colorScheme.videoPlayerBorderColor.withValues(alpha: 0.6),),);_controller!.initialize().then((_) => setState(() {})).catchError(- (error) {+ (+ error,+ ) {// handle minumum duration bigger than video duration errorNavigator.pop(context);},@@ -119,10 +121,7 @@ class _VideoEditorPageState extends State<VideoEditorPage> {}},child: Scaffold(- appBar: AppBar(- elevation: 0,- toolbarHeight: 0,- ),+ appBar: AppBar(elevation: 0, toolbarHeight: 0),body: _controller != null &&_controller!.initialized &&_quarterTurnsForRotationCorrection != null@@ -202,11 +201,12 @@ class _VideoEditorPageState extends State<VideoEditorPage> {),const SizedBox(height: 40),VideoEditorNavigationOptions(- color: Theme.of(context)- .colorScheme- .videoPlayerPrimaryColor,- secondaryText:- AppLocalizations.of(context).saveCopy,+ color: Theme.of(+ context,+ ).colorScheme.videoPlayerPrimaryColor,+ secondaryText: AppLocalizations.of(+ context,+ ).saveCopy,onSecondaryPressed: () {exportVideo();},@@ -225,6 +225,7 @@ class _VideoEditorPageState extends State<VideoEditorPage> {}void exportVideo() async {+ _logger.info("[VideoExport] Starting export process");_isExporting.value = true;final dialogKey = GlobalKey<LinearProgressDialogState>();@@ -233,6 +234,7 @@ class _VideoEditorPageState extends State<VideoEditorPage> {key: dialogKey,);+ _logger.info("[VideoExport] Showing progress dialog");unawaited(showDialog(useRootNavigator: false,@@ -243,44 +245,90 @@ class _VideoEditorPageState extends State<VideoEditorPage> {),);+ _logger.info("[VideoExport] Creating FFmpeg config");+ _logger.info("[VideoExport] Start trim: ${_controller!.startTrim}");+ _logger.info(+ "[VideoExport] Trimmed duration: ${_controller!.trimmedDuration}",+ );+final config = VideoFFmpegVideoEditorConfig(_controller!,format: VideoExportFormat.mp4,commandBuilder: (config, videoPath, outputPath) {final List<String> filters = config.getExportFilters();+ _logger.info("[VideoExport] Input video path: $videoPath");+ _logger.info("[VideoExport] Output path: $outputPath");+ _logger.info("[VideoExport] Filters: $filters");final String startTrimCmd = "-ss ${_controller!.startTrim}";final String toTrimCmd = "-t ${_controller!.trimmedDuration}";- return '$startTrimCmd -i $videoPath $toTrimCmd ${config.filtersCmd(filters)} -c:v libx264 -c:a aac $outputPath';+ final command =+ '$startTrimCmd -i $videoPath $toTrimCmd ${config.filtersCmd(filters)} -c:v libx264 -c:a aac $outputPath';+ _logger.info("[VideoExport] FFmpeg command: $command");+ return command;},);try {+ _logger.info("[VideoExport] Getting execute config");+ final executeConfig = await config.getExecuteConfig();+ _logger.info("[VideoExport] Execute config ready, starting FFmpeg");+await ExportService.runFFmpegCommand(- await config.getExecuteConfig(),+ executeConfig,onProgress: (stats) {+ final progress = config.getFFmpegProgress(stats.getTime().toInt());+ _logger.info(+ "[VideoExport] Progress: ${(progress * 100).toStringAsFixed(1)}%",+ );if (dialogKey.currentState != null) {- dialogKey.currentState!- .setProgress(config.getFFmpegProgress(stats.getTime().toInt()));+ dialogKey.currentState!.setProgress(progress);}},- onError: (e, s) => _logger.severe("Error exporting video", e, s),+ onError: (e, s) {+ _logger.severe("[VideoExport] Error exporting video", e, s);+ _logger.severe("[VideoExport] Error details: $e");+ },onCompleted: (result) async {+ _logger.info(+ "[VideoExport] FFmpeg completed, result file: ${result.path}",+ );+ _logger.info(+ "[VideoExport] File exists: ${result.existsSync()}, size: ${result.existsSync() ? result.lengthSync() : 0} bytes",+ );_isExporting.value = false;- if (!mounted) return;+ if (!mounted) {+ _logger.warning("[VideoExport] Widget not mounted, returning");+ return;+ }final fileName = path.basenameWithoutExtension(widget.file.title!) +"_edited_" +DateTime.now().microsecondsSinceEpoch.toString() +".mp4";+ _logger.info("[VideoExport] New file name: $fileName");+//Disabling notifications for assets changing to insert the file into//files db before triggering a sync.+ _logger.info(+ "[VideoExport] Stopping PhotoManager change notifications",+ );await PhotoManager.stopChangeNotify();try {- final AssetEntity newAsset =- await (PhotoManager.editor.saveVideo(result, title: fileName));+ _logger.info("[VideoExport] Saving video to PhotoManager");+ final AssetEntity newAsset = await (PhotoManager.editor.saveVideo(+ result,+ title: fileName,+ ));+ _logger.info(+ "[VideoExport] Video saved to PhotoManager, asset ID: ${newAsset.id}",+ );++ _logger.info("[VideoExport] Deleting temporary file");result.deleteSync();++ _logger.info("[VideoExport] Creating EnteFile from asset");final newFile = await EnteFile.fromAsset(widget.file.deviceFolder ?? '',newAsset,@@ -300,26 +348,46 @@ class _VideoEditorPageState extends State<VideoEditorPage> {}}- newFile.generatedID =- await FilesDB.instance.insertAndGetId(newFile);- Bus.instance- .fire(LocalPhotosUpdatedEvent([newFile], source: "editSave"));+ _logger.info("[VideoExport] Inserting file into database");+ newFile.generatedID = await FilesDB.instance.insertAndGetId(+ newFile,+ );+ _logger.info(+ "[VideoExport] File inserted with ID: ${newFile.generatedID}",+ );++ _logger.info("[VideoExport] Firing LocalPhotosUpdatedEvent");+ Bus.instance.fire(+ LocalPhotosUpdatedEvent([newFile], source: "editSave"),+ );++ _logger.info("[VideoExport] Starting sync service");SyncService.instance.sync().ignore();+showShortToast(context, AppLocalizations.of(context).editsSaved);- _logger.info("Original file " + widget.file.toString());- _logger.info("Saved edits to file " + newFile.toString());+ _logger.info(+ "[VideoExport] Original file: ${widget.file.toString()}",+ );+ _logger.info(+ "[VideoExport] Saved edits to file: ${newFile.toString()}",+ );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);+ int selectionIndex = files.indexWhere(+ (file) => file.generatedID == newFile.generatedID,+ );if (selectionIndex == -1) {files.add(newFile);selectionIndex = files.length - 1;}+ _logger.info("[VideoExport] Dismissing progress dialog");Navigator.of(dialogKey.currentContext!).pop('dialog');+ _logger.info(+ "[VideoExport] Navigating to detail page with new file",+ );replacePage(context,DetailPage(@@ -329,15 +397,22 @@ class _VideoEditorPageState extends State<VideoEditorPage> {),),);- } catch (_) {+ _logger.info("[VideoExport] Export process completed successfully");+ } catch (e, s) {+ _logger.severe("[VideoExport] Error in post-processing", e, s);Navigator.of(dialogKey.currentContext!).pop('dialog');}},);- } catch (_) {+ } catch (e, s) {+ _logger.severe("[VideoExport] Unexpected error in export process", e, s);Navigator.of(dialogKey.currentContext!).pop('dialog');} finally {+ _logger.info(+ "[VideoExport] Re-enabling PhotoManager change notifications",+ );await PhotoManager.startChangeNotify();+ _logger.info("[VideoExport] Export method completed");}}