How to Manipulate MKV Files with FFmpeg
This article provides a practical guide on how to use FFmpeg, a powerful command-line tool, to manipulate MKV (Matroska) video files. You will learn how to perform essential video editing tasks such as converting formats without losing quality, cutting and trimming segments, extracting audio tracks, and re-encoding video codecs using simple, direct commands.
Remuxing MKV to MP4 (Without Re-encoding)
Remuxing changes the container format from MKV to MP4 without altering the underlying video and audio data. Because it does not re-encode the stream, this process is incredibly fast and preserves original quality.
ffmpeg -i input.mkv -c copy output.mp4-i input.mkv: Specifies the input file.-c copy: Directs FFmpeg to copy the video, audio, and subtitle streams directly without re-encoding them.
Trimming and Cutting MKV Videos
You can cut a specific segment out of an MKV file by defining a start time and duration. Using the copy codec ensures the cut is instantaneous.
ffmpeg -ss 00:01:30 -i input.mkv -to 00:02:45 -c copy output.mkv-ss 00:01:30: Sets the start time (1 minute and 30 seconds). Placing this before-ispeeds up the seeking process.-to 00:02:45: Sets the stop time (2 minutes and 45 seconds). Alternatively, use-t 00:01:15to specify a duration of 1 minute and 15 seconds.-c copy: Copies the streams without re-encoding.
Extracting Audio from an MKV File
If you only need the audio track from an MKV file, you can extract it into an audio container.
To extract the original audio stream without re-encoding (e.g., extracting AC3 or AAC audio):
ffmpeg -i input.mkv -vn -c:a copy output.mka-vn: Disables video recording/processing.-c:a copy: Copies the audio stream directly.
To convert the extracted audio to a highly compatible MP3 file:
ffmpeg -i input.mkv -vn -c:a libmp3lame -q:a 2 output.mp3-c:a libmp3lame: Uses the MP3 encoder.-q:a 2: Sets a high-quality variable bitrate (VBR).
Re-encoding Video and Audio Codecs
Sometimes you need to compress an MKV file or convert its codecs for better device compatibility. The command below transcodes the video to H.264 and the audio to AAC.
ffmpeg -i input.mkv -c:v libx264 -crf 23 -c:a aac -b:a 192k output.mkv-c:v libx264: Encodes the video stream to H.264.-crf 23: Sets the Constant Rate Factor for quality. Lower numbers mean better quality (18-28 is the standard range).-c:a aac: Encodes the audio to AAC format.-b:a 192k: Sets the audio bitrate to 192 kbps.