π End-to-end encrypted cloud for everything.
Dart 2faandroidauthye2eeencryptionend-to-end-encryptionfluttergolanggoogle-photosgoogle-photos-alternativeiosopensourcephotosprivacyprivacy-toolstypescriptzero-knowledge
Fix video editor export hanging and add progress tracking
Prateek Sunal7d3225e1954d
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 17dbcaaa4b..18e2410f3f 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,13 +1,12 @@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/session_state.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';@@ -30,93 +29,127 @@ class ExportService {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}');+ final completer = Completer<void>();+ FFmpegSession? activeSession;+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,- ),- );+ // Run FFmpeg with async callbacks+ activeSession = await FFmpegKit.executeAsync(+ execute.command,+ (session) async {+ // Session complete callback+ final returnCode = await session.getReturnCode();+ final output = await session.getOutput();++ if (returnCode != null && ReturnCode.isSuccess(returnCode)) {+ final outputFile = File(execute.outputPath);++ if (!outputFile.existsSync()) {+ _logger.warning(+ 'Output file does not exist at ${execute.outputPath}',+ );+ }++ onCompleted(outputFile);+ } else {+ final errorCode = returnCode?.getValue() ?? -1;+ _logger.severe('FFmpeg process failed with return code $errorCode');- // 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+ final error = Exception(+ 'FFmpeg process exited with return code $errorCode.\n$output',+ );++ if (onError != null) {+ onError(error, StackTrace.current);}- } else if (message['type'] == 'complete') {- final returnCode = message['returnCode'];- final output = message['output'] ?? '';+ }- _logger.info('[FFmpeg] Session completed with return code: $returnCode');+ if (!completer.isCompleted) {+ completer.complete();+ }+ },+ null, // No log callback+ (statistics) {+ // Statistics callback for progress+ if (onProgress != null) {+ onProgress(statistics);+ }+ },+ );++ // Poll session state to ensure we wait for completion+ bool callbackTriggered = false;+ Timer.periodic(const Duration(milliseconds: 500), (timer) async {+ if (activeSession != null) {+ final state = await activeSession.getState();+ final statisticsList = await activeSession.getStatistics();++ if (statisticsList != null &&+ statisticsList.isNotEmpty &&+ onProgress != null) {+ final statistics = statisticsList.last;+ onProgress(statistics);+ }++ if (state == SessionState.completed) {+ timer.cancel();- if (returnCode == 0) {- _logger.info('[FFmpeg] Success! Creating output file');- final outputFile = File(execute.outputPath);+ // If callback hasn't been triggered yet, do it manually+ if (!callbackTriggered && !completer.isCompleted) {+ callbackTriggered = true;- if (!outputFile.existsSync()) {- _logger.warning('[FFmpeg] Output file does not exist at ${execute.outputPath}');+ // Get the return code and handle completion+ final returnCode = await activeSession.getReturnCode();++ if (returnCode != null && ReturnCode.isSuccess(returnCode)) {+ final outputFile = File(execute.outputPath);++ if (!outputFile.existsSync()) {+ _logger.warning(+ 'Output file does not exist at ${execute.outputPath}',+ );+ }++ onCompleted(outputFile);} else {- _logger.info(- '[FFmpeg] Output file size: ${outputFile.lengthSync()} bytes',+ final errorCode = returnCode?.getValue() ?? -1;+ _logger.severe(+ 'FFmpeg process failed with return code $errorCode',);- }- 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 $errorCode',+ );- final error = Exception(- 'FFmpeg process exited with return code $returnCode.\n$output',- );+ if (onError != null) {+ onError(error, StackTrace.current);+ }+ }+ completer.complete();+ }+ } else if (state == SessionState.failed) {+ timer.cancel();+ if (!completer.isCompleted) {+ final error = Exception('FFmpeg process failed');if (onError != null) {onError(error, StackTrace.current);}+ completer.complete();}-- // 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;}}- }+ });++ // Wait for the session to complete+ await completer.future;} catch (e, stackTrace) {- _logger.severe('[FFmpeg] Exception during execution: $e', e, stackTrace);+ _logger.severe('FFmpeg execution error: $e');+ if (activeSession != null) {+ await FFmpegKit.cancel(activeSession.getSessionId());+ }if (onError != null) {onError(e, stackTrace);} else {@@ -125,44 +158,3 @@ class ExportService {}}}--// 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 76931c1ea0..c7944f43c8 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@@ -59,7 +59,6 @@ class _VideoEditorPageState extends State<VideoEditorPage> {@overridevoid initState() {- _logger.info("Initializing video editor page");super.initState();Future.microtask(() {@@ -108,7 +107,6 @@ class _VideoEditorPageState extends State<VideoEditorPage> {@overrideWidget build(BuildContext context) {- _logger.info("Building video editor page");return PopScope(canPop: false,onPopInvokedWithResult: (didPop, _) {@@ -225,7 +223,6 @@ class _VideoEditorPageState extends State<VideoEditorPage> {}void exportVideo() async {- _logger.info("[VideoExport] Starting export process");_isExporting.value = true;final dialogKey = GlobalKey<LinearProgressDialogState>();@@ -234,7 +231,6 @@ class _VideoEditorPageState extends State<VideoEditorPage> {key: dialogKey,);- _logger.info("[VideoExport] Showing progress dialog");unawaited(showDialog(useRootNavigator: false,@@ -245,60 +241,37 @@ 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}";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(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(progress);}},onError: (e, s) {- _logger.severe("[VideoExport] Error exporting video", e, s);- _logger.severe("[VideoExport] Error details: $e");+ _logger.severe("Error exporting video", e, s);},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) {- _logger.warning("[VideoExport] Widget not mounted, returning");return;}@@ -306,29 +279,19 @@ class _VideoEditorPageState extends State<VideoEditorPage> {"_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 {- _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,@@ -348,29 +311,17 @@ class _VideoEditorPageState extends State<VideoEditorPage> {}}- _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(- "[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@@ -382,12 +333,8 @@ class _VideoEditorPageState extends State<VideoEditorPage> {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(@@ -397,22 +344,17 @@ class _VideoEditorPageState extends State<VideoEditorPage> {),),);- _logger.info("[VideoExport] Export process completed successfully");} catch (e, s) {- _logger.severe("[VideoExport] Error in post-processing", e, s);+ _logger.severe("Error in post-processing", e, s);Navigator.of(dialogKey.currentContext!).pop('dialog');}},);} catch (e, s) {- _logger.severe("[VideoExport] Unexpected error in export process", e, s);+ _logger.severe("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");}}