Skip to content
systemcoding.dev
Media

The Complete Guide to the FFmpeg Command Line

A complete guide to the FFmpeg command line: the pipeline, option order, streams, codecs, quality settings, trimming, joining, subtitles, ffprobe and scripting.

25 min read
Summarize in AI
Flat illustration of video frames passing through a codec, with the FFmpeg, GStreamer and C logos.

FFmpeg is the tool behind most of the video and audio conversion on the internet. It runs inside web services, video editors, phone apps and the scripts of people who only wanted to turn one file into another. It is also the tool whose command lines look like noise to anyone who meets them cold: a long line of dashes, letters and numbers, copied from a forum, that works until the file changes. This guide is meant to end that. It builds the mental model first, because every option makes sense once you can say which part of a pipeline it controls, and then it works through the jobs people actually do: converting, trimming, joining, resizing, extracting, encoding for quality or size, subtitles, thumbnails, inspection and batch work. It targets FFmpeg 7.1 on Linux, macOS and Windows, and every command is written to be pasted.

The guide is the hub for a cluster of posts. Where a topic has its own deeper post, the text says so, and the short version here is enough to get the job done. If you already know the basics, jump to the section you need. If you are new, read it in order once, and keep the cheat sheet in the last section open afterwards.

What FFmpeg is, and what it is not

FFmpeg is a command-line program, ffmpeg, built on a set of libraries called libav: libavformat for containers, libavcodec for codecs, libavfilter for filters and libswscale and libswresample for converting pictures and sound. Two companion programs ship with it. ffprobe inspects media files and prints what is in them, and ffplay is a minimal player. When people say "FFmpeg" they usually mean the ffmpeg program.

It is not a video editor with a timeline, and it does not decide anything for you about taste. It does exactly what the command line says, and when the command line is silent about something, it picks a default. Much of learning FFmpeg is learning which defaults to override.

It is also not a single codec. FFmpeg includes its own implementations of many codecs, and it links external libraries for others, such as libx264 for H.264 and libx265 for HEVC. Which codecs your copy can use depends on how it was built. The next section starts there.

Install it and check what you have

On Debian and Ubuntu, sudo apt install ffmpeg installs a full build. On macOS with Homebrew, brew install ffmpeg. On Windows, winget install ffmpeg installs a build from one of the third-party builders that the FFmpeg site links to. On Fedora, enable RPM Fusion for the full build, since the default ffmpeg-free package leaves out patent-encumbered codecs.

Then check the version and the build configuration:

Shell
ffmpeg -version
Text
ffmpeg version 7.1 Copyright (c) 2000-2024 the FFmpeg developers
built with gcc 14 (Debian 14.2.0-12)
configuration: --prefix=/usr --enable-gpl --enable-libx264 --enable-libx265 --enable-libvpx --enable-libopus --enable-libmp3lame --enable-libsvtav1 --enable-libass --enable-libfreetype --enable-shared
libavutil      59. 39.100 / 59. 39.100
libavcodec     61. 19.100 / 61. 19.100
libavformat    61.  7.100 / 61.  7.100
libavfilter    10.  4.100 / 10.  4.100
libswscale      8.  3.100 /  8.  3.100
libswresample   5.  3.100 /  5.  3.100

The version and the paths on your machine will differ. The line to read is configuration:. Each --enable-libsomething flag is a library compiled in, and a missing one means a missing capability. If --enable-libx264 is absent, no command that names libx264 will ever work on that copy, and no change to the command will fix it. The install post in this cluster covers the listing options in detail: ffmpeg -encoders, -decoders, -formats, -filters and -pix_fmts each print what your build supports. Throughout this guide, add -hide_banner to commands to suppress the version banner that FFmpeg prints on every run.

The pipeline: the one idea that explains the command line

Every FFmpeg job moves data through five stages:

  1. The demuxer opens an input file, called a container, and separates it into streams of compressed packets.

  2. The decoder turns compressed packets into raw frames: pictures for video, samples for audio.

  3. The filter graph changes the raw frames: resize, crop, mix, delay.

  4. The encoder compresses the raw frames into new packets.

  5. The muxer interleaves the packets of all streams and writes the output container.

Hold on to the split between the outer stages and the inner ones. The demuxer and the muxer deal with containers, which are the file formats named by extensions such as .mp4, .mkv and .webm. The decoder and the encoder deal with codecs, such as H.264, AAC and VP9. A container is a box, and a codec is how the contents of the box are compressed. The words are often used loosely in conversation, and a command line punishes the looseness: choosing the box does not choose the compression.

The stream copy option, -c copy, bypasses stages two, three and four: packets go from the demuxer straight to the muxer. That is why copying is fast and lossless, and why it cannot be combined with filters. A filter needs decoded frames, and a copy never decodes.

Now read a command with the pipeline in mind:

Shell
ffmpeg -i holiday.mov -vf scale=1280:-2 -c:v libx264 -crf 23 -c:a aac -b:a 128k holiday.mp4

-i holiday.mov opens the input, which is the demuxer. -vf scale=1280:-2 is the filter graph for video. -c:v libx264 -crf 23 chooses and configures the video encoder. -c:a aac -b:a 128k chooses and configures the audio encoder. holiday.mp4 names the output, and its extension selects the MP4 muxer. No option names a decoder, because FFmpeg chooses one from what it finds in the input. The posts in this cluster on inputs, streams and codecs go deeper, and this is the picture they all depend on.

Options belong to the file that follows them

This rule explains most of the surprises beginners meet. An option applies to the next file name on the command line. Options placed before -i are input options, and they apply to that input. Options placed after the last -i and before an output file name are output options for that output.

Shell
ffmpeg -ss 30 -i holiday.mov -t 10 -c copy clip.mp4

-ss 30 is before -i, so the demuxer seeks to the thirty-second mark before reading. -t 10 is after, so the muxer stops after ten seconds of output. If you placed -c:v libx264 before the -i, FFmpeg would treat it as an input option asking for a decoder named libx264, which does not exist, and the command would fail.

A command can have several inputs and several outputs. Each output file name closes its own group of options:

Shell
ffmpeg -i holiday.mov -c:v libx264 -crf 23 -an small.mp4 -c:v libx265 -crf 28 -an smaller.mkv

The first group applies only to small.mp4, and the second only to smaller.mkv. The input is decoded once and feeds both encoders.

Streams and how they are addressed

A container holds streams: typically one video, one or more audio, perhaps subtitles. Inspect an input by running FFmpeg with just -i:

Shell
ffmpeg -hide_banner -i holiday.mov
Text
Input #0, mov,mp4,m4a,3gp,3g2,mj2, from 'holiday.mov':
  Duration: 00:02:14.40, start: 0.000000, bitrate: 18204 kb/s
  Stream #0:0(und): Video: h264 (High), yuv420p, 1920x1080, 17950 kb/s, 29.97 fps
  Stream #0:1(und): Audio: aac (LC), 48000 Hz, stereo, 254 kb/s
At least one output file must be specified

The numbers will differ for your file, and the final line is the expected complaint that no output was named. Stream #0:1 means input file 0, stream index 1. Input files are numbered from zero in the order of the -i options, and streams are numbered from zero within each file.

Option names use stream specifiers to say which streams they apply to: -c:v is the codec for all video streams, -c:a for all audio, -c:a:1 for the second audio stream of the output, and -c:s for subtitles. The -map option chooses which streams go into the output. Without it, FFmpeg picks the best video stream by resolution, the best audio stream by channel count, and the best subtitle stream. Once you write a single -map, that automatic choice is off for that output. The map post in this cluster covers this fully, and the key line for a beginner is -map 0, which keeps every stream of the first input.

Before it starts encoding, FFmpeg prints a block that shows its decisions:

Text
Stream mapping:
  Stream #0:0 -> #0:0 (h264 (native) -> h264 (libx264))
  Stream #0:1 -> #0:1 (aac (native) -> aac (native))

Read that block first whenever a result surprises you. Each line is an input stream, an output stream, the decoder and the encoder. The word native marks FFmpeg's built-in implementation, and an external library name such as libx264 marks a linked encoder. The question "why is there no sound" is answered there in five seconds, more often than you would expect.

Your first conversions

Convert to a widely playable MP4

The most requested job: take any video and make an MP4 that plays on phones, browsers and televisions.

Shell
ffmpeg -i input.mkv -c:v libx264 -crf 23 -preset medium -pix_fmt yuv420p -c:a aac -b:a 128k -movflags +faststart output.mp4

The components:

  • -c:v libx264 encodes video as H.264, the most compatible video codec.

  • -crf 23 is a constant quality target. Lower numbers give better quality and larger files, and the scale for x264 runs from 0 to 51 with 23 as the default.

  • -preset medium sets how much effort the encoder spends, trading time for compression. The ladder runs ultrafast, superfast, veryfast, faster, fast, medium, slow, slower, veryslow.

  • -pix_fmt yuv420p selects the pixel layout that every H.264 decoder supports. Some sources use layouts such as yuv444p that browsers and phones refuse, and this option converts to the safe one.

  • -c:a aac -b:a 128k encodes audio as AAC at 128 kilobits per second.

  • -movflags +faststart moves the file's index to the start, so a browser can begin playing before the whole file has downloaded.

The convert post in this cluster explains each of these, and the faststart post explains the index. Two situations need special handling. If the video has an odd width or height, H.264 in yuv420p refuses it with "width not divisible by 2", and the fix is a scale filter that rounds to even numbers: -vf "scale=trunc(iw/2)*2:trunc(ih/2)*2". If the input is already H.264 and AAC and only the wrapper is wrong, do not re-encode at all.

Change the container without re-encoding

Shell
ffmpeg -i input.mkv -map 0 -c copy output.mkv
ffmpeg -i input.mkv -c copy output.mp4

-c copy moves the compressed packets into a new container. It finishes in seconds and loses no quality, because nothing is decoded or encoded. The catch is the target container's list of accepted codecs: MP4 holds H.264, HEVC, AAC and a few others, but it rejects SRT subtitles and some audio, and the muxer says so with an error like "codec not currently supported in container". The fix is to convert only the stream that fails, as in -c copy -c:s mov_text, or choose a different container. The remux post and the compatibility cheat sheet in this cluster cover which container accepts which codec.

Remember -map 0 when you want everything. Without it, even a copy keeps one stream of each type and silently drops the other audio tracks.

Quality: CRF, presets and bit rate

There are two ways to tell an encoder how good to be. The first is a quality target, CRF, where the encoder spends bits where the picture needs them and the file size is the outcome. The second is a bit rate target, where you say how many bits per second the output may use and quality is the outcome. For files that live on disk, CRF is almost always right. For streaming, where a player has a fixed bandwidth, you need a bit rate cap, and the usual answer is CRF plus -maxrate and -bufsize.

The CRF and preset post in this cluster has the full table, and the short form is:

EncoderCRF defaultGood range
libx2642318 to 28
libx2652822 to 32

The scales are not interchangeable between encoders. The preset does not change the quality target. It changes how long the encoder works to reach it, and a slower preset gives a smaller file at the same CRF. The practical advice: choose the slowest preset you are willing to wait for. And test on your own footage: cut thirty seconds of representative video, encode it at three CRF values, look at the results on the device your viewers will use, and pick the highest CRF where you cannot see the difference.

Which codec

The codec comparison post covers this in full. In one paragraph: H.264 plays everywhere and is the safe default. HEVC compresses better and plays on most modern devices, though browser support is patchy. VP9 and AV1 are royalty-free, compress better still, and play in modern browsers, and AV1 takes much longer to encode. For video that must reach an unknown audience, use H.264, and offer a second source in a newer codec only if the bandwidth saving justifies the extra encode.

Trimming and cutting

Trimming uses three options: -ss for the start, -to for the end time, and -t for the duration. Position matters. Placed before -i, -ss seeks inside the demuxer and is fast. Placed after it, -ss decodes and discards everything before the position, which is slow on long files. Giving the length with -t is the clearest form:

Shell
ffmpeg -ss 00:01:00 -i input.mp4 -t 30 -c:v libx264 -crf 20 -c:a aac clip.mp4

This produces a thirty-second clip starting at one minute, with a frame-exact start, because re-encoding lets FFmpeg decode from the previous keyframe and discard frames up to the exact position. Since FFmpeg 2.1, an input seek combined with re-encoding is accurate.

For a fast, lossless cut, copy the streams:

Shell
ffmpeg -ss 00:01:00 -i input.mp4 -t 30 -c copy -avoid_negative_ts make_zero clip.mp4

The cost is that a stream copy can only start at a keyframe, so the clip begins at the last keyframe before your start time, possibly several seconds early. Use ffprobe to list keyframe times and choose a start that lands on one: ffprobe -v error -select_streams v:0 -skip_frame nokey -show_entries frame=pts_time -of csv=p=0 input.mp4. The trim post in this cluster explains the options in depth, including why -to after an input seek measures output time, which catches nearly everyone once.

Extracting and replacing audio

To pull the audio out of a video, drop the video with -vn:

Shell
ffmpeg -i video.mp4 -vn -c:a copy audio.m4a
ffmpeg -i video.mp4 -vn -c:a libmp3lame -q:a 2 audio.mp3

The first copies the existing AAC audio into an M4A file with no loss. The second converts to MP3 with variable bit rate quality level 2. The container must match the codec when copying: AAC fits in .m4a, MP3 in .mp3, Opus in .opus or .ogg. The audio post in this cluster has the table.

To replace the audio of a video with another file:

Shell
ffmpeg -i video.mp4 -i music.mp3 -map 0:v -map 1:a -c:v copy -c:a aac -shortest out.mp4

The map options take the video from input 0 and the audio from input 1. -shortest ends the output when the shorter input ends, which stops a long music track from extending the video with a frozen last frame. To remove audio entirely, use -an.

Resizing

The scale filter changes picture size. Give both dimensions, or give one and let FFmpeg compute the other with a negative number:

Shell
ffmpeg -i input.mp4 -vf scale=1280:-2 -c:v libx264 -crf 22 -c:a copy output.mp4

-1 keeps the aspect ratio, and -2 keeps it and rounds to an even number, which H.264 needs. Always prefer -2 for H.264 output. To fit inside a box without stretching, add force_original_aspect_ratio=decrease, and follow it with pad if you need an exact frame size. The scale post in this cluster has the full set, including scaling algorithms: flags=lanczos gives sharper downscales.

A filter requires re-encoding, so -vf and -c:v copy cannot be used together on the same stream. FFmpeg stops with an error when you try.

Joining files

Appending a second -i does not join videos. FFmpeg has three ways to concatenate, and the first to learn is the concat demuxer, which reads a list file:

Text
file 'part1.mp4'
file 'part2.mp4'
file 'part3.mp4'
Shell
ffmpeg -f concat -safe 0 -i list.txt -c copy joined.mp4

It copies packets, so it is instant and lossless, and it requires the clips to match: same codec, resolution, frame rate and audio layout. Parts cut from one source match. Clips from different cameras do not, and for those you use the concat filter in -filter_complex, which decodes everything and re-encodes. The join post in this cluster covers both, including the list-file rules about quoting and the zero-padded numbering that makes shell globs sort in the right order.

Subtitles

Soft subtitles are a track in the container that a player can switch on or off. Burned-in subtitles are drawn into the picture. Adding a soft track needs the right subtitle codec for the container: mov_text for MP4, srt or ass for MKV, webvtt for WebM.

Shell
ffmpeg -i video.mp4 -i subs.srt -c:v copy -c:a copy -c:s mov_text -metadata:s:s:0 language=eng out.mp4

To burn subtitles in, use the subtitles filter, which needs a build with libass and re-encodes the video:

Shell
ffmpeg -i video.mp4 -vf subtitles=subs.srt -c:v libx264 -crf 20 -c:a copy burned.mp4

Bitmap subtitles from Blu-ray discs, in the PGS format, cannot be converted to text by FFmpeg, and they can only be kept by copying them into an MKV. The subtitles post in this cluster covers extraction, styling and the traps.

Images from video

A thumbnail is one frame:

Shell
ffmpeg -ss 00:01:30 -i video.mp4 -frames:v 1 -q:v 2 thumb.jpg

-frames:v 1 stops after one video frame. For a frame every ten seconds, use the fps filter with a numbered output pattern:

Shell
ffmpeg -i video.mp4 -vf "fps=1/10,scale=320:-2" frame_%04d.jpg

The %04d is a zero-padded counter, and without a counter every frame overwrites one file. A contact sheet, a grid of frames on one image, adds the tile filter. The thumbnail post in this cluster builds it, along with the thumbnail filter that skips black opening frames.

To make an animated GIF with good colours, build a custom palette. The default palette is generic, and the result looks banded. The GIF post shows the palettegen and paletteuse pair, which produces a sharp GIF from the same clip.

Looking inside files with ffprobe

ffprobe reads container and stream properties without decoding the video. For people, ffprobe file prints a summary on standard error. For programs, use structured output:

Shell
ffprobe -v error -show_entries format=duration -of default=nw=1:nk=1 input.mp4
ffprobe -v error -select_streams v:0 -show_entries stream=codec_name,width,height,r_frame_rate -of json input.mp4
Text
134.400000

The first command prints a duration with no labels, which suits a shell variable. The second prints JSON that a script can parse. Never parse the human-readable summary, because its wording changes between releases and it goes to standard error. The ffprobe post covers the sections, the CSV and JSON writers and the keyframe and frame-count queries.

Use ffprobe before a job to learn the codec, size, frame rate and pixel format of the source, and after a job to confirm what you made. A one-line check of the output often finds a mistake that a watch-through would take ten minutes to see.

Filters: the language in brief

Everything between decoding and encoding is a filter. A filter takes decoded frames and returns changed ones. scale, crop, overlay, drawtext, hflip, fps and hundreds more exist. The syntax is a small language:

  • A filter is its name, then =, then colon-separated options: scale=1280:720 or scale=width=1280:height=720.

  • A comma chains filters: scale=1280:-2,hflip.

  • A semicolon separates chains in a graph.

  • Square brackets name the connection points between chains: [0:v]scale=640:-2[small].

-vf and -af take one chain for one video or audio stream. -filter_complex takes a full graph with several inputs and outputs, and its outputs must be selected with -map "[label]". The next guide in this cluster, on FFmpeg filters and filter_complex, is the complete treatment, and the filter-graph syntax post is the short primer. For now, remember two rules: the order of filters in a chain changes the result, and anything that touches pixels needs a re-encode.

Common single-purpose filters worth knowing early:

JobFilter
Resizescale=1280:-2
Cut a regioncrop=w:h:x:y
Add borderspad=w:h:x:y:color
Rotate 90 degreestranspose=1
Speed up videosetpts=0.5*PTS with atempo=2.0 for audio
Change frame ratefps=30
Place a logooverlay=W-w-20:H-h-20
Draw text or timedrawtext=text='...'
Remove interlacingbwdif=mode=1
Adjust loudnessloudnorm=I=-16:TP=-1.5:LRA=11

Hardware acceleration in one paragraph

Software encoders such as libx264 use the CPU, and they give the best compression per bit. Hardware encoders use dedicated silicon on your GPU or CPU, run much faster and use far less power, and give somewhat larger files at the same visual quality. FFmpeg exposes them by name: h264_nvenc for NVIDIA GPUs, h264_qsv for Intel Quick Sync, h264_vaapi on Linux with VA-API, h264_videotoolbox on macOS, and h264_amf for AMD. Use them for live work, screen capture and large batches where speed matters more than size, and use software encoders for final delivery where quality per byte matters. Check which your build includes with ffmpeg -hide_banner -encoders | grep -E "nvenc|qsv|vaapi|videotoolbox|amf".

Capturing the screen and devices

FFmpeg reads from devices as inputs, selected with -f. On Linux, -f x11grab records an X11 screen and -f v4l2 reads a webcam. On macOS, -f avfoundation handles screens, cameras and microphones. On Windows, -f gdigrab records the desktop and -f dshow reads cameras and microphones. Each system lists its devices differently, and each needs permissions. The capture post in this cluster gives the commands for all three. The advice that applies everywhere: encode in real time with -preset veryfast, write to MKV so a crash does not lose the file, and remux to MP4 afterwards.

Reading errors

FFmpeg's messages are terse, and a small set of them covers most failures.

MessageMeaningFix
Unknown encoder 'libx264'The build lacks the libraryInstall a fuller build
Codec not currently supported in containerThe muxer rejects the codecChange container or convert that stream
width not divisible by 2Odd size with yuv420pScale with -2
Stream map '0:a:1' matches no streamsThe file has no such streamCheck with ffprobe, or add ?
Non-monotonous DTS in output streamTimestamps out of orderLook at joins, copies and sources
Invalid data found when processing inputUnreadable or unsupported inputCheck the file and the format list
Output file does not contain any streamNothing was mappedCheck -map and the input
Filtergraph ... cannot be used with stream copyA filter on a copied streamRe-encode that stream

Two flags help when the message is not enough: -loglevel debug prints every decision, and -report writes the full log to a file named with the time. Keep the whole text of an error, including the lines before it, when you ask for help, because the cause is usually earlier than the line that says "error".

Scripting FFmpeg safely

One command is a tool, and a folder of files is a job. The common failures are all about names and input. Use null-separated names so spaces and odd characters cannot split a path:

Shell
find . -type f -name '*.mkv' -print0 | while IFS= read -r -d '' f; do
  ffmpeg -nostdin -hide_banner -loglevel error -n -i "$f" -c:v libx264 -crf 23 -pix_fmt yuv420p -c:a aac -movflags +faststart "${f%.mkv}.mp4"
done

The details matter. -print0 and read -d '' handle any file name. -nostdin stops FFmpeg from reading the loop's input, which would otherwise consume the file list. -n refuses to overwrite existing outputs, so the script is safe to run again. Quote "$f" always. For a larger job, write to a temporary name and rename on success, log each result, and check durations afterwards. The batch post in this cluster builds that version in full. We have lost more time to a missing -nostdin than to any codec setting, and it is the first thing we check in a script that stops after one file.

Habits that prevent most problems

  1. Keep the original. Every lossy encode loses something. Always encode delivery copies from the source, never from another delivery copy.

  2. Test on ten seconds. Add -t 10 to any new command and look at the result before running a long job.

  3. Read the mapping block. It shows the decisions FFmpeg made before it started.

  4. Check the output with ffprobe. Codec, pixel format, duration and size answer most questions.

  5. Write options in the order of the pipeline. Input options, then -i, then filters, encoder options and the output name. It reads better and avoids placement errors.

  6. Name the pixel format for delivery. -pix_fmt yuv420p costs nothing and prevents unplayable files.

  7. **Use -hide_banner.** It makes logs shorter and easier to read.

  8. Prefer copy when the codec already fits. It is faster and lossless.

  9. Do not trust a forum command blindly. Check each option against the documentation, since options change between versions, and FFmpeg's own ffmpeg -h output reflects your build.

Sync, timestamps and frame rate

Almost every sync problem in FFmpeg is a timestamp problem. Each packet carries a presentation timestamp (PTS), the time its frame is shown, and a decoding timestamp (DTS), the time it must be decoded. Both are integers counted in a time base, a fraction such as 1/90000 that gives the length of one tick in seconds. With B-frames, which predict from a later frame, packets are stored in decoding order and so presentation order jumps around, while decoding order never goes backwards. The timestamps post in this cluster works through a real packet listing, and what you need as a beginner fits in three rules.

First, the warning "Non-monotonous DTS in output stream" means the muxer received a packet whose decoding time did not increase. A single occurrence at a join between two clips is usually harmless. A stream of them points to a source with broken timestamps, and the remedy is to let FFmpeg regenerate them with -fflags +genpts on the input, or to re-encode once with a clean timeline.

Second, a variable frame rate source, common from phones and screen recorders, confuses tools that assume constant spacing. Check it with ffprobe -v error -select_streams v:0 -show_entries stream=r_frame_rate,avg_frame_rate -of csv=p=0 input.mp4. When the two values differ, the frame rate varies, and adding -fps_mode cfr or the filter fps=30 makes the output constant by duplicating or dropping frames. Do it before joining clips or stacking videos, because mismatched rates make one half stutter.

Third, audio and video start at different times in some files, and the difference shows in the stream start_time values. When the audio begins 0.8 seconds after the video, no trim option fixes it. Shift one input with -itsoffset 0.8 before its -i, and the two line up. Use -copyts only when you must preserve the original timestamps, because it leaves the output with an odd start time that some players handle badly.

Audio in more depth

Video gets most of the attention, and audio is where viewers notice mistakes first. A few settings cover nearly every case.

Bit rate. For AAC, 128 kilobits per second is acceptable for stereo speech and general video, and 192 or 256 kilobits suit music. For Opus, which is more efficient, 96 kilobits per second is excellent for speech and fine for music. For MP3, the variable bit rate quality scale -q:a 2 is a good default for music.

Channels and sample rate. -ac 2 downmixes to stereo, which phones and laptops expect. -ar 48000 sets the sample rate, and video files almost always use 48,000 Hz. Leave both alone unless a player complains, because FFmpeg keeps the source values by default.

Loudness. Two recordings with the same peak level can sound very different in volume. The loudnorm filter targets perceived loudness in LUFS under the EBU R128 standard, and it works best in two passes, one to measure and one to apply a fixed gain. The loudness post gives both commands and explains the measured values. To only look at levels without changing anything, volumedetect prints the mean and maximum volume in decibels, and ebur128 prints integrated loudness and true peak.

Mixing. The amix filter sums tracks into one, and amerge puts them in separate channels. amix halves each input by default, so voice over music sounds quieter than expected until you add normalize=0 and set levels with volume or weights. The mixing post covers ducking the music under a voice with sidechaincompress.

Keeping audio untouched. When you only change the picture, copy the audio with -c:a copy. It avoids a lossy generation and saves time. The one case where you cannot copy is when the audio itself needs a filter, such as a speed change, or when the target container does not accept the audio codec.

A complete delivery workflow

The following is a realistic job, written as a sequence of commands, that combines everything above. You have a recording from a camera, in a codec your editor finds slow, and you must deliver a web version and an archive copy.

Step one is to inspect the source and write down what you learn:

Shell
ffprobe -v error -show_entries stream=index,codec_type,codec_name,width,height,pix_fmt,r_frame_rate,sample_rate,channels -of csv=p=0 camera.mp4
Text
0,video,h264,3840,2160,yuv420p,30000/1001
1,audio,aac,48000,2

Step two is the archive copy. Keep all the picture information, and make a file that is easy to edit. If your editor works well with it, a mezzanine codec such as ProRes is the right choice, and the mezzanine post covers the options. If the source is already good and you only need to cut it, copy the cut and keep the original untouched.

Step three is the delivery copy. Scale to 1080p, encode H.264 for reach, set the safe pixel format, add faststart and normalise the audio loudness:

Shell
ffmpeg -i camera.mp4 -vf "scale=-2:1080" -c:v libx264 -crf 21 -preset slow -pix_fmt yuv420p -c:a aac -b:a 160k -movflags +faststart web.mp4

Step four is verification. Check the codec, size, pixel format and duration of the output, and compare the duration with the source:

Shell
ffprobe -v error -select_streams v:0 -show_entries stream=codec_name,width,height,pix_fmt -of csv=p=0 web.mp4
ffprobe -v error -show_entries format=duration -of default=nw=1:nk=1 web.mp4
Text
h264,1920,1080,yuv420p
134.400000

The duration should match the source to within a fraction of a second. If the picture is the issue, extract a frame near the middle and the end with -frames:v 1 and look at them. Step five, for a large library, is to wrap the commands in the batch script from the earlier section and run it with a log.

This is the pattern for almost every job: inspect, choose the stages you need, run the shortest command that does it, then verify. Resist the urge to add options you do not understand, since each one is a decision you did not make.

Where to go next

This guide gives you the whole map at the level of working commands. The posts in the FFmpeg command line cluster go deeper on each job: choosing codecs, streams with -map, AV1 and VP9 encoding, measuring quality with VMAF, constrained bit rate for streaming, mezzanine codecs, timestamps and time bases, and building a minimal FFmpeg. The filters guide is the next step if your jobs involve changing the picture or sound: it covers filter_complex in full, and every filter listed in the table above. Read the posts in the order of the problems you meet, and keep this page as the index.

The cheat sheet

JobCommand
Convert to web MP4ffmpeg -i in -c:v libx264 -crf 23 -pix_fmt yuv420p -c:a aac -movflags +faststart out.mp4
Remux with no re-encodeffmpeg -i in.mkv -map 0 -c copy out.mkv
Clip, accurateffmpeg -ss S -i in -t D -c:v libx264 -crf 20 -c:a aac out.mp4
Clip, fastffmpeg -ss S -i in -t D -c copy out.mp4
Resize to 720pffmpeg -i in -vf scale=-2:720 -c:v libx264 -crf 22 -c:a copy out.mp4
Extract audioffmpeg -i in -vn -c:a copy out.m4a
Remove audioffmpeg -i in -an -c:v copy out.mp4
Thumbnailffmpeg -ss S -i in -frames:v 1 -q:v 2 out.jpg
Join matching clipsffmpeg -f concat -safe 0 -i list.txt -c copy out.mp4
Soft subtitlesffmpeg -i in.mp4 -i s.srt -c copy -c:s mov_text out.mp4
Durationffprobe -v error -show_entries format=duration -of default=nw=1:nk=1 in
Share

Keep reading

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.