The FFmpegKit class provides a convenient interface for executing FFmpeg commands in your Flutter application.
FFmpegKit is the primary class for video and audio processing operations. It allows you to:
- Execute FFmpeg commands synchronously or asynchronously
- Monitor execution progress through callbacks
- Manage and track FFmpeg sessions
- Cancel running operations
Executes an FFmpeg command synchronously (blocking). The result and any output/logs are captured within the returned FFmpegSession object.
static FFmpegSession execute(String command)Parameters:
command(String): The FFmpeg command to execute (without theffmpegprefix)
Returns:
FFmpegSession: A session object containing execution results
Example:
final session = FFmpegKit.execute('-i input.mp4 -c:v libx264 output.mp4');
if (ReturnCode.isSuccess(session.getReturnCode())) {
print('Success!');
} else {
print('Failed: ${session.getOutput()}');
print('Logs: ${session.getLogs()}');
}Executes an FFmpeg command asynchronously (non-blocking). Execution is managed by the SessionQueueManager, which enforces global concurrency limits.
static Future<FFmpegSession> executeAsync(
String command, {
FFmpegSessionCompleteCallback? onComplete,
FFmpegLogCallback? onLog,
FFmpegStatisticsCallback? onStatistics,
})Parameters:
command(String): The FFmpeg command to executeonComplete(FFmpegSessionCompleteCallback?, optional): Callback invoked when execution completesonLog(FFmpegLogCallback?, optional): Callback invoked for each log messageonStatistics(FFmpegStatisticsCallback?, optional): Callback invoked for statistics updates
Returns:
Future<FFmpegSession>: A Future that completes with the session object
Example:
await FFmpegKit.executeAsync(
'-i input.mp4 -vf scale=1280:720 output.mp4',
onComplete: (session) {
print('Completed with code: ${session.getReturnCode()}');
},
onLog: (log) {
print('[${log.logLevel}] ${log.message}');
},
onStatistics: (stats) {
print('Frame: ${stats.videoFrameNumber}, Speed: ${stats.speed}x');
},
);Cancels a running FFmpeg session.
static void cancel(FFmpegSession session)Parameters:
session(FFmpegSession): The session to cancel
Example:
final session = FFmpegKit.execute('-i input.mp4 output.mp4');
// ... later
FFmpegKit.cancel(session);Creates a new FFmpeg session without executing it.
static FFmpegSession createSession(String command)Parameters:
command(String): The FFmpeg command for the session
Returns:
FFmpegSession: A new session object (not yet executed)
Example:
final session = FFmpegKit.createSession('-i input.mp4 output.mp4');
// Configure or inspect the session before execution
// ... then execute it manually if neededReturns the most recently executed FFmpeg session.
static FFmpegSession? getLastFFmpegSession()Returns:
FFmpegSession?: The last session, or null if no sessions have been executed
Example:
final lastSession = FFmpegKit.getLastFFmpegSession();
if (lastSession != null) {
print('Last command: ${lastSession.getCommand()}');
print('Return code: ${lastSession.getReturnCode()}');
}Returns all active FFmpeg sessions.
static List<FFmpegSession> getFFmpegSessions()Returns:
List<FFmpegSession>: A list of all active sessions
Example:
final sessions = FFmpegKit.getFFmpegSessions();
print('Active sessions: ${sessions.length}');
for (final session in sessions) {
print('Session ${session.getSessionId()}: ${session.getState()}');
}Called when an FFmpeg session completes.
typedef FFmpegSessionCompleteCallback = void Function(FFmpegSession session);Example:
void onComplete(FFmpegSession session) {
final code = session.getReturnCode();
if (ReturnCode.isSuccess(code)) {
print('Success!');
} else if (ReturnCode.isCancel(code)) {
print('Cancelled');
} else {
print('Failed with code: $code');
}
}Called for each log message emitted by FFmpeg.
typedef FFmpegLogCallback = void Function(Log log);Example:
void onLog(Log log) {
// Filter by log level
if (log.logLevel == LogLevel.error) {
print('ERROR: ${log.message}');
}
}Called periodically with encoding/decoding statistics.
typedef FFmpegStatisticsCallback = void Function(Statistics statistics);Example:
void onStatistics(Statistics stats) {
final progressPercent = (stats.time / totalDuration) * 100;
print('Progress: ${progressPercent.toStringAsFixed(1)}%');
print('Speed: ${stats.speed}x');
print('Bitrate: ${stats.bitrate} kbps');
}final session = FFmpegKit.execute(
'-i input.mp4 -c:v libx264 -preset medium -crf 23 output.mp4'
);await FFmpegKit.executeAsync(
'-i input.mp4 -vf scale=1280:720 -c:v libx264 -crf 28 compressed.mp4',
onStatistics: (stats) {
print('Compressing... ${stats.speed}x speed');
},
);FFmpegKit.execute('-i video.mp4 -vn -acodec copy audio.aac');// Extract 10 seconds starting at 00:00:30
FFmpegKit.execute('-i input.mp4 -ss 00:00:30 -t 10 -c copy output.mp4');FFmpegKit.execute(
'-i video.mp4 -i watermark.png '
'-filter_complex "overlay=W-w-10:H-h-10" '
'output.mp4'
);// Create a file list first
final fileList = 'file1.mp4\nfile2.mp4\nfile3.mp4';
// Then concatenate
FFmpegKit.execute('-f concat -safe 0 -i filelist.txt -c copy output.mp4');FFmpegKit.execute(
'-i input.mp4 -vf "fps=10,scale=320:-1:flags=lanczos" '
'-c:v gif output.gif'
);// Extract one frame per second
FFmpegKit.execute('-i video.mp4 -vf fps=1 frame_%04d.png');Always check the return code and handle errors appropriately:
final session = FFmpegKit.execute('-i input.mp4 output.mp4');
final returnCode = session.getReturnCode();
if (ReturnCode.isSuccess(returnCode)) {
print('Command executed successfully');
} else if (ReturnCode.isCancel(returnCode)) {
print('Command was cancelled');
} else {
print('Command failed with return code: $returnCode');
print('Output: ${session.getOutput()}');
print('Logs: ${session.getLogs()}');
// Check for specific errors in logs
final logs = session.getLogs() ?? '';
if (logs.contains('No such file')) {
print('Input file not found');
} else if (logs.contains('Invalid')) {
print('Invalid command or parameters');
}
}-
Use Async for Long Operations: For operations that take more than a few seconds, use
executeAsyncto avoid blocking the UI. -
Monitor Progress: Use the statistics callback to show progress to users:
await FFmpegKit.executeAsync( command, onStatistics: (stats) { setState(() { progress = stats.time / totalDuration; }); }, );
-
Handle Cancellation: Allow users to cancel long-running operations:
FFmpegSession? currentSession; void startConversion() { currentSession = FFmpegKit.execute(command); } void cancelConversion() { if (currentSession != null) { FFmpegKit.cancel(currentSession!); } }
-
Check File Paths: Ensure input files exist and output paths are writable before executing commands.
-
Use Appropriate Presets: Choose FFmpeg presets based on your needs:
ultrafast: Fastest encoding, larger file sizemedium: Balanced (default)sloworveryslow: Best compression, slower encoding
- FFmpegSession API - Session management details
- Video Processing Guide - Common video operations
- Callbacks Guide - Working with callbacks
- Error Handling Guide - Comprehensive error handling
- Session Queue Management - Concurrency control