AgentSkillsCN

ffmpeg-command-syntax

完整版FFmpeg命令语法参考,涵盖选项排序、输入与输出选项、流标识符以及对位置敏感的选项。主动启用此技能,可用于:(1) 命令语法相关的问题;(2) 选项位置的困惑;(3) 输入与输出选项的混淆;(4) 流标识符的语法;(5) -ss/-t/-to位置相关的问题;(6) 全局选项与文件级选项的区分;(7) 多路输入与输出的处理;(8) 选项顺序的错误。提供正确的选项放置规则、仅输入或仅输出的选项、对位置敏感的选项行为、流标识符的语法,以及常见的错误与修正方法。

SKILL.md
--- frontmatter
name: ffmpeg-command-syntax
description: Complete FFmpeg command syntax reference covering option ordering, input vs output options, stream specifiers, and position-sensitive options. PROACTIVELY activate for: (1) Command syntax questions, (2) Option placement issues, (3) Input vs output option confusion, (4) Stream specifier syntax, (5) -ss/-t/-to position questions, (6) Global vs per-file options, (7) Multiple input/output handling, (8) Option order errors. Provides: Correct option placement rules, input-only vs output-only options, position-sensitive option behavior, stream specifier syntax, common mistakes and fixes.

CRITICAL: FFmpeg Option Ordering Rules

The most common FFmpeg mistake is putting options in the wrong place. Options in FFmpeg are position-sensitive and apply to the NEXT file specified after them.

The Golden Rule

code
ffmpeg [global_options] {[input_options] -i input}... {[output_options] output}...

Key principle: Options are applied to the next file. They are reset between files.


Option Categories

1. Global Options (First, Before Everything)

Global options affect the entire FFmpeg process and must come first, before any inputs:

OptionDescriptionExample
-yOverwrite output without askingffmpeg -y -i in.mp4 out.mp4
-nNever overwrite outputffmpeg -n -i in.mp4 out.mp4
-v / -loglevelSet logging verbosityffmpeg -v error -i in.mp4 out.mp4
-statsPrint encoding progressffmpeg -stats -i in.mp4 out.mp4
-progressSend progress to file/URLffmpeg -progress - -i in.mp4 out.mp4
-reportGenerate ffmpeg-*.log fileffmpeg -report -i in.mp4 out.mp4
-hide_bannerSuppress copyright bannerffmpeg -hide_banner -i in.mp4 out.mp4
-filter_complexComplex filtergraph (global)ffmpeg -i a.mp4 -i b.mp4 -filter_complex "[0][1]overlay" out.mp4
-filter_complex_threadsFiltergraph thread countffmpeg -filter_complex_threads 4 ...
bash
# Correct: Global options first
ffmpeg -y -hide_banner -v warning -i input.mp4 output.mp4

# Wrong: Global option after -i
ffmpeg -i input.mp4 -y output.mp4  # -y works but is not idiomatic

2. Input Options (Before -i)

Input options affect how a file is read/decoded. They must be placed immediately before the -i for the file they apply to.

Input-Only Options

OptionDescriptionPlacement
-ss (as input)Seek position (fast, may be imprecise)Before -i
-t (as input)Limit input read durationBefore -i
-to (as input)Read until timestampBefore -i
-itsoffsetTime offset for input timestampsBefore -i
-itsscaleInput timestamp scale factorBefore -i
-reRead input at native frame rate (streaming)Before -i
-readrateRead input at specified rateBefore -i
-stream_loopLoop input N times (-1 = infinite)Before -i
-hwaccelHardware acceleration methodBefore -i
-hwaccel_deviceHardware device to useBefore -i
-hwaccel_output_formatPixel format for hwaccel outputBefore -i
-c:v (as decoder)Video decoder selectionBefore -i
-c:a (as decoder)Audio decoder selectionBefore -i
-r (as input)Input frame rate (raw formats)Before -i
-s (as input)Input frame size (raw formats)Before -i
-pix_fmt (as input)Input pixel format (raw formats)Before -i
-f (as input)Force input formatBefore -i
-accurate_seekEnable accurate seeking (default)Before -i
-noaccurate_seekDisable accurate seekingBefore -i
-seek_timestampSeek by timestamp vs byte positionBefore -i
-thread_queue_sizeInput thread queue sizeBefore -i
-guess_layout_maxMax channels for layout guessingBefore -i
bash
# Correct: Input options before their -i
ffmpeg -ss 00:01:00 -t 30 -i input.mp4 output.mp4

# Wrong: Input options after -i
ffmpeg -i input.mp4 -ss 00:01:00 output.mp4  # -ss is now an OUTPUT option (slower!)

Hardware Acceleration Input Options

bash
# Correct: hwaccel before -i
ffmpeg -hwaccel cuda -hwaccel_output_format cuda -i input.mp4 \
  -c:v h264_nvenc output.mp4

# Correct: Different hwaccel per input
ffmpeg -hwaccel cuda -i input1.mp4 \
       -hwaccel vaapi -i input2.mp4 \
       -filter_complex "[0][1]overlay" output.mp4

# Wrong: hwaccel after -i (won't work)
ffmpeg -i input.mp4 -hwaccel cuda -c:v h264_nvenc output.mp4

3. Output Options (After Last -i, Before Output File)

Output options affect how a file is encoded/written. They must be placed after all inputs and before the output file they apply to.

Output-Only Options

OptionDescriptionPlacement
-c:v (as encoder)Video encoder selectionBefore output
-c:a (as encoder)Audio encoder selectionBefore output
-c:sSubtitle codec selectionBefore output
-b:vVideo bitrateBefore output
-b:aAudio bitrateBefore output
-crfConstant Rate Factor (quality)Before output
-presetEncoding preset (speed/quality)Before output
-tuneEncoding tuning profileBefore output
-profile:vVideo profileBefore output
-levelCodec levelBefore output
-r (as output)Output frame rateBefore output
-s (as output)Output frame sizeBefore output
-aspectOutput aspect ratioBefore output
-pix_fmt (as output)Output pixel formatBefore output
-vf / -filter:vVideo filter chainBefore output
-af / -filter:aAudio filter chainBefore output
-mapStream mappingBefore output
-ss (as output)Start time (accurate but slow)Before output
-t (as output)Output duration limitBefore output
-to (as output)End time for outputBefore output
-fsFile size limit (bytes)Before output
-frames:vNumber of video frames to outputBefore output
-frames:aNumber of audio frames to outputBefore output
-f (as output)Force output formatBefore output
-movflagsMOV/MP4 muxer flagsBefore output
-metadataSet metadataBefore output
-dispositionSet stream dispositionBefore output
-shortestStop when shortest stream endsBefore output
-copytsCopy timestampsBefore output
-start_at_zeroStart timestamps at zeroBefore output
-avoid_negative_tsHandle negative timestampsBefore output
-anDisable audioBefore output
-vnDisable videoBefore output
-snDisable subtitlesBefore output
-dnDisable data streamsBefore output
bash
# Correct: Output options before output file
ffmpeg -i input.mp4 -c:v libx264 -crf 23 -preset medium output.mp4

# With multiple outputs - each needs its own options
ffmpeg -i input.mp4 \
  -c:v libx264 -crf 23 output_h264.mp4 \
  -c:v libx265 -crf 28 output_h265.mp4

4. Options That Work as Both Input AND Output

Some options have different behavior depending on position:

-ss (Seek/Start Time) - Position Critical

bash
# BEFORE -i (INPUT): Fast seek, may not be frame-accurate
# Seeks by keyframes, then decodes to precise position if -accurate_seek (default)
ffmpeg -ss 00:01:00 -i input.mp4 -t 30 -c copy output.mp4

# AFTER -i (OUTPUT): Frame-accurate but slower
# Decodes all frames from start, discards until seek point
ffmpeg -i input.mp4 -ss 00:01:00 -t 30 -c:v libx264 output.mp4

# BOTH (Recommended for accuracy + speed):
# Fast seek to near position, then accurate decode
ffmpeg -ss 00:00:55 -i input.mp4 -ss 00:00:05 -t 30 -c:v libx264 output.mp4

Important: When -ss is before -i, timestamps are reset to 0. Use -copyts to preserve original timestamps.

-t and -to (Duration/End Time)

bash
# -t BEFORE -i: Limits how much of input to READ
ffmpeg -t 60 -i input.mp4 -c copy output.mp4  # Read first 60 seconds

# -t AFTER -i: Limits output DURATION
ffmpeg -i input.mp4 -t 60 -c copy output.mp4  # Output first 60 seconds

# -to: End timestamp (works with -ss timestamp reset)
# With -ss before -i, timestamps reset, so -to is relative to new zero
ffmpeg -ss 00:01:00 -i input.mp4 -to 00:00:30 output.mp4  # 30 seconds from seek point

# To get 1:00 to 1:30, use -t instead, or -copyts with -to
ffmpeg -ss 00:01:00 -i input.mp4 -t 00:00:30 output.mp4  # Correct: 30 sec duration
ffmpeg -ss 00:01:00 -copyts -i input.mp4 -to 00:01:30 output.mp4  # Also correct

-r (Frame Rate)

bash
# BEFORE -i: Input frame rate (for raw/image sequences)
ffmpeg -r 30 -i frame_%04d.png output.mp4  # Input at 30fps

# AFTER -i: Output frame rate (adds/drops frames to match)
ffmpeg -i input.mp4 -r 24 output.mp4  # Convert to 24fps

-s (Size/Resolution)

bash
# BEFORE -i: Input size (for raw formats)
ffmpeg -s 1920x1080 -pix_fmt yuv420p -i raw.yuv output.mp4

# AFTER -i: Output size (scales video) - prefer -vf scale instead
ffmpeg -i input.mp4 -s 1280x720 output.mp4

-c / -codec (Codec Selection)

bash
# BEFORE -i: Selects DECODER (rarely needed)
ffmpeg -c:v h264_cuvid -i input.mp4 -c:v h264_nvenc output.mp4

# AFTER -i: Selects ENCODER (common usage)
ffmpeg -i input.mp4 -c:v libx264 -c:a aac output.mp4

Stream Specifiers

Stream specifiers target specific streams for per-stream options. Appended with colon after option name.

Syntax

code
-option[:stream_specifier] value

Stream Specifier Types

SpecifierMeaningExample
:vAll video streams-c:v libx264
:VVideo streams (not thumbnails/covers)-c:V libx264
:aAll audio streams-c:a aac
:sAll subtitle streams-c:s mov_text
:dAll data streams-c:d copy
:tAll attachment streams...
:v:0First video stream-b:v:0 5M
:a:1Second audio stream-c:a:1 ac3
:0First stream (any type)-c:0 copy
:1Second stream (any type)-c:1 libx264
:#0x1234Stream with specific PID-c:#0x1234 copy
:i:0x100Stream with specific ID-c:i:0x100 copy
:m:key:valueStream with matching metadata-c:m:language:eng aac
:p:0Streams in program 0-c:p:0 copy
:uUsable configuration streams-c:u copy

Input Index Prefix

For multi-input commands, prefix with input index:

bash
# Stream 0 from input 1
ffmpeg -i a.mp4 -i b.mp4 -map 1:0 -c copy output.mp4

# Video from input 0, audio from input 1
ffmpeg -i video.mp4 -i audio.mp3 -map 0:v -map 1:a output.mp4

# Second audio stream from third input
ffmpeg -i a.mp4 -i b.mp4 -i c.mp4 -map 2:a:1 output.mp4

Per-Stream Option Examples

bash
# Different codecs per stream type
ffmpeg -i input.mkv -c:v libx264 -c:a aac -c:s mov_text output.mp4

# Different bitrates per stream index
ffmpeg -i input.mkv -map 0 \
  -c:v libx264 -b:v:0 5M \
  -c:a:0 aac -b:a:0 192k \
  -c:a:1 ac3 -b:a:1 384k \
  output.mkv

# Different settings for each audio stream
ffmpeg -i multichannel.mxf -map 0:v:0 -map 0:a:0 -map 0:a:0 \
  -c:a:0 ac3 -b:a:0 640k \
  -ac:a:1 2 -c:a:1 aac -b:a:1 128k \
  output.mp4

Multiple Inputs and Outputs

Multiple Inputs

bash
# Options apply to immediately following -i
ffmpeg \
  -ss 10 -i first.mp4 \      # Seek 10s in first input
  -ss 5 -i second.mp4 \      # Seek 5s in second input
  -filter_complex "[0:v][1:v]overlay" \
  output.mp4

Multiple Outputs

bash
# Each output needs its own options - they reset between outputs
ffmpeg -i input.mp4 \
  -c:v libx264 -crf 23 output_h264.mp4 \
  -c:v libx265 -crf 28 output_h265.mp4 \
  -c:v libvpx-vp9 -crf 30 output_vp9.webm

# Same codec, different resolutions
ffmpeg -i input.mp4 \
  -vf "scale=1920:1080" -c:v libx264 -crf 23 hd.mp4 \
  -vf "scale=1280:720" -c:v libx264 -crf 23 sd.mp4

# WRONG: Options don't carry over
ffmpeg -i input.mp4 -c:v libx264 -crf 23 out1.mp4 out2.mp4
# out2.mp4 will NOT have libx264/crf 23 settings!

Common Mistakes and Fixes

Mistake 1: Input Option After -i

bash
# WRONG: -hwaccel after -i has no effect
ffmpeg -i input.mp4 -hwaccel cuda -c:v h264_nvenc output.mp4

# CORRECT: -hwaccel before -i
ffmpeg -hwaccel cuda -i input.mp4 -c:v h264_nvenc output.mp4

Mistake 2: Output Option Before -i

bash
# WRONG: -c:v before -i tries to select decoder (may fail)
ffmpeg -c:v libx264 -i input.mp4 output.mp4

# CORRECT: -c:v after -i selects encoder
ffmpeg -i input.mp4 -c:v libx264 output.mp4

Mistake 3: Expecting Options to Persist Across Outputs

bash
# WRONG: Second output won't have the encoding settings
ffmpeg -i input.mp4 -c:v libx264 -crf 23 out1.mp4 out2.mp4

# CORRECT: Repeat options for each output
ffmpeg -i input.mp4 \
  -c:v libx264 -crf 23 out1.mp4 \
  -c:v libx264 -crf 23 out2.mp4

Mistake 4: Wrong -ss Position for Accuracy

bash
# Fast but may be imprecise (seeks to keyframe)
ffmpeg -ss 00:05:00 -i input.mp4 -t 30 -c copy output.mp4

# Slow but frame-accurate (decodes everything)
ffmpeg -i input.mp4 -ss 00:05:00 -t 30 -c:v libx264 output.mp4

# BEST: Fast AND accurate (two-pass seek)
ffmpeg -ss 00:04:55 -i input.mp4 -ss 5 -t 30 -c:v libx264 output.mp4

Mistake 5: Mixing Input/Output Files

bash
# WRONG: Mixing inputs and outputs
ffmpeg -i input1.mp4 -c:v libx264 output1.mp4 -i input2.mp4 output2.mp4

# CORRECT: All inputs first, then all outputs
ffmpeg -i input1.mp4 -i input2.mp4 \
  -map 0 -c:v libx264 output1.mp4 \
  -map 1 -c:v libx264 output2.mp4

Mistake 6: -t vs -to Confusion with -ss

bash
# -ss before -i resets timestamps to 0
# -to 00:00:30 means 30 seconds from new timestamp 0
ffmpeg -ss 00:01:00 -i input.mp4 -to 00:00:30 output.mp4  # 30 sec clip

# To end at original timestamp, use -copyts
ffmpeg -ss 00:01:00 -copyts -i input.mp4 -to 00:01:30 output.mp4  # 30 sec clip

# Or use -t for duration (unaffected by timestamp reset)
ffmpeg -ss 00:01:00 -i input.mp4 -t 00:00:30 output.mp4  # 30 sec clip

Mistake 7: Filter vs Global -filter_complex

bash
# -vf is per-output, applies to single input
ffmpeg -i input.mp4 -vf "scale=1280:720" output.mp4

# -filter_complex is GLOBAL, for multi-input operations
ffmpeg -i video.mp4 -i overlay.png \
  -filter_complex "[0:v][1:v]overlay=10:10" \
  output.mp4

# WRONG: Using -vf with multiple inputs
ffmpeg -i video.mp4 -i overlay.png -vf "overlay=10:10" output.mp4  # Error!

Command Structure Examples

Basic Transcode

bash
ffmpeg -i input.mp4 -c:v libx264 -crf 23 -c:a aac output.mp4
#      ^input       ^output options                 ^output

With Input Seeking

bash
ffmpeg -ss 60 -i input.mp4 -t 30 -c:v libx264 output.mp4
#      ^input opt ^input    ^output options    ^output

Hardware Acceleration

bash
ffmpeg -hwaccel cuda -hwaccel_output_format cuda -i input.mp4 \
#      ^input options (must be before -i)        ^input
  -c:v h264_nvenc -preset p4 output.mp4
# ^output options            ^output

Multiple Inputs with Filters

bash
ffmpeg -i main.mp4 -i overlay.png \
#      ^input1     ^input2
  -filter_complex "[0:v][1:v]overlay=10:10[v]" \
# ^global option
  -map "[v]" -map 0:a -c:v libx264 -c:a copy output.mp4
# ^output options                            ^output

Streaming with Real-time Read

bash
ffmpeg -re -i input.mp4 -c:v libx264 -f flv rtmp://server/live/stream
#      ^input opt       ^output options      ^output

Complete Structure

bash
ffmpeg \
  -y -hide_banner \                           # Global options
  -hwaccel cuda -ss 10 -i input1.mp4 \        # Input 1 options + input
  -stream_loop -1 -i input2.mp4 \             # Input 2 options + input
  -filter_complex "[0:v][1:v]overlay[v]" \    # Global filter
  -map "[v]" -map 0:a \                       # Output mapping
  -c:v h264_nvenc -b:v 5M \                   # Output video options
  -c:a aac -b:a 192k \                        # Output audio options
  -movflags +faststart \                      # Output muxer options
  output.mp4                                  # Output file

Quick Reference Card

Option Placement Cheatsheet

OptionBefore -iAfter -iNotes
-ssFast seekAccurate seekBefore = keyframe seek, After = decode all
-tInput limitOutput limitLimits read vs write
-toInput endOutput endAffected by timestamp reset
-rInput FPSOutput FPSFor raw/output conversion
-sInput sizeOutput sizeFor raw/scaling
-c:vDecoderEncoderBefore = decode, After = encode
-c:aDecoderEncoderBefore = decode, After = encode
-hwaccelRequiredN/AMust be before -i
-reRequiredN/AMust be before -i
-itsoffsetRequiredN/AMust be before -i
-stream_loopRequiredN/AMust be before -i
-vfN/ARequiredOutput filter only
-afN/ARequiredOutput filter only
-mapN/ARequiredOutput option only
-crfN/ARequiredOutput option only
-presetN/ARequiredOutput option only
-movflagsN/ARequiredOutput option only
-yGlobalGlobalCan be anywhere (prefer first)
-vGlobalGlobalCan be anywhere (prefer first)
-filter_complexGlobalGlobalMust be used for multi-input

Complete FFmpeg 8.0+ Option Reference

Global Options (Complete List)

OptionDescription
-yOverwrite output files without asking
-nNever overwrite output files
-v level / -loglevel levelSet logging verbosity (quiet, panic, fatal, error, warning, info, verbose, debug, trace)
-statsPrint encoding progress statistics
-stats_period timeSet statistics output period
-progress urlSend progress info to URL/file
-stdinEnable stdin interaction
-nostdinDisable stdin interaction
-reportGenerate ffmpeg-*.log debug file
-hide_bannerSuppress program banner
-max_alloc bytesMaximum allocation size limit
-cpuflags flagsSet CPU flags mask
-cpucount countOverride CPU count detection
-max_error_rate ratioMaximum decoding error ratio
-xerrorExit on error
-abort_on flagsConditions to abort (empty_output, empty_output_stream)
-filter_complex graphGlobal complex filtergraph
-filter_complex_threads nFiltergraph thread count
-filter_threads nSet filter processing threads
-filter_buffered_frames nMax buffered frames in filtergraph
-lavfi graphAlias for -filter_complex
-filter_complex_script fileRead filtergraph from file
-sdp_file fileWrite SDP info to file
-init_hw_device type=nameInitialize hardware device
-filter_hw_device nameHardware device for filters
-hwaccelsList available hardware accelerations
-benchmarkShow benchmarking info
-benchmark_allShow per-step benchmarking
-timelimit durationExit after duration seconds
-dumpDump each input packet
-hexDump packets in hex
-debug_tsPrint timestamp/latency debugging info
-recast_mediaForce decoder of different media type
-vsync modeVideo sync method (deprecated, use -fps_mode)
-fps_mode modeFrame rate mode (passthrough, cfr, vfr, auto)
-frame_drop_threshold thresholdFrame drop threshold
-async samples_per_secondAudio sync method
-adrift_threshold thresholdAudio drift threshold
-copytsCopy timestamps from input
-start_at_zeroShift input timestamps to start at 0
-copytb modeCopy input timebase (0=decoder, 1=demuxer, -1=auto)
-dts_delta_threshold thresholdDTS discontinuity threshold
-dts_error_threshold thresholdDTS error timestamp threshold
-muxdelay secondsMaximum mux delay
-muxpreload secondsInitial mux delay
-streamid output_index:new_idSet stream ID in output
-override_ffserverOverride ffserver input specifications
-bitexactUse only bit-exact algorithms
-default_mode modeDefault stream selection mode
-vstatsDump video coding stats to vstats_HHMMSS.log
-vstats_file fileDump video coding stats to specified file
-vstats_version nSet vstats format version
-print_graphsPrint execution graph to stderr
-print_graphs_file fileWrite execution graph to file
-print_graphs_format fmtSet graph output format (default, compact, json, mermaid)

Input-Only Options (Complete List)

OptionDescription
-i urlInput file URL
-f fmtForce input format
-c:v decoder / -vcodec decoderVideo decoder
-c:a decoder / -acodec decoderAudio decoder
-c:s decoder / -scodec decoderSubtitle decoder
-ss positionSeek to position (fast, keyframe-based)
-sseof positionSeek relative to end of file (negative value)
-t durationLimit input duration
-to positionLimit input to position
-itsoffset offsetInput timestamp offset
-itsscale scaleInput timestamp scale (per-stream)
-isync input_indexAssign input as sync source
-reRead at native frame rate
-readrate speedRead at specified rate
-readrate_initial_burst durationInitial burst before rate limiting
-readrate_catchup speedCatchup rate when behind
-stream_loop countLoop input (-1 = infinite)
-hwaccel methodHardware acceleration (none, auto, cuda, vaapi, qsv, d3d11va, dxva2, videotoolbox, vdpau, vulkan)
-hwaccel_device deviceHardware device path/name
-hwaccel_output_format formatHardware output pixel format
-autorotateAutomatically rotate video (enabled by default)
-noautorotateDisable automatic rotation
-r fpsInput frame rate (raw formats)
-s sizeInput frame size (raw formats)
-pix_fmt formatInput pixel format (raw formats)
-sample_fmt formatInput sample format (raw audio)
-ar rateInput audio sample rate
-ac channelsInput audio channel count
-channel_layout layoutInput audio channel layout
-accurate_seekEnable accurate seeking (default)
-noaccurate_seekDisable accurate seeking
-seek_timestampEnable seeking by timestamp
-thread_queue_size countInput thread queue size
-guess_layout_max channelsMax channels for layout guessing
-discard modeDiscard frames (none, default, noref, bidir, nokey, all)
-reinit_filterReinitialize filters on input change (per-stream)
-drop_changedDrop frames with changed parameters (per-stream)
-display_rotation degreesSet display rotation metadata
-display_hflipSet horizontal flip metadata
-display_vflipSet vertical flip metadata
-fix_sub_durationFix subtitle durations
-canvas_size sizeSubtitle canvas size
-ignore_loopIgnore loop metadata (GIF)
-dump_attachment:stream filenameExtract attachment to file (per-stream)

Output-Only Options (Complete List)

OptionDescription
-f fmtForce output format
-c:v encoder / -vcodec encoderVideo encoder (or copy)
-c:a encoder / -acodec encoderAudio encoder (or copy)
-c:s encoder / -scodec encoderSubtitle encoder (or copy)
-c:d codec / -dcodec codecData stream codec
-ss positionStart time (accurate, slow)
-t durationOutput duration limit
-to positionOutput end position
-fs sizeFile size limit (bytes)
-frames:v count / -vframes countVideo frame count limit
-frames:a count / -aframes countAudio frame count limit
-frames:d count / -dframes countData frame count limit
-r fpsOutput frame rate
-fpsmax fpsMaximum output frame rate
-s sizeOutput frame size
-aspect ratioDisplay aspect ratio
-pix_fmt formatOutput pixel format
-sample_fmt formatOutput sample format
-ar rateOutput audio sample rate
-ac channelsOutput audio channel count
-channel_layout layoutOutput audio channel layout
-vf filtergraph / -filter:vVideo filter chain
-af filtergraph / -filter:aAudio filter chain
-map input:streamStream mapping
-map_metadata specifierMetadata mapping (see below)
-map_chapters input_indexChapter mapping from input
-b:v bitrateVideo bitrate
-b:a bitrateAudio bitrate
-maxrate bitrateMaximum bitrate
-minrate bitrateMinimum bitrate
-bufsize sizeRate control buffer size
-crf valueConstant Rate Factor (quality)
-qp valueConstant QP value
-q:v value / -qscale:v valueVideo quality scale (VBR)
-q:a value / -qscale:a valueAudio quality scale (VBR)
-preset nameEncoder preset
-tune nameEncoder tuning
-profile:v nameVideo profile
-level valueCodec level
-g framesGOP size / keyframe interval
-keyint_min framesMinimum keyframe interval
-sc_threshold valueScene change threshold
-bf framesB-frame count
-refs framesReference frames
-pass nMulti-pass encoding (1 or 2)
-passlogfile prefixPass log file prefix
-rc_lookahead framesRate control lookahead
-anDisable audio output
-vnDisable video output
-snDisable subtitle output
-dnDisable data stream output
-metadata key=valueSet global metadata
-metadata:s:v key=valueSet video stream metadata
-metadata:s:a key=valueSet audio stream metadata
-metadata:c:0 key=valueSet chapter metadata
-disposition:s:0 flagsSet stream disposition
-program title=name:st=0:st=1Create program in output
-stream_group type=value:...Create stream group
-target typeTarget format (vcd, svcd, dvd, dv, dv50)
-shortestStop at shortest stream
-shortest_buf_duration durationBuffer for shortest detection
-apadPad audio to match video (use with -shortest)
-copypriorss nCopy frames before start time (0=no, 1=yes, -1=auto)
-avoid_negative_ts modeHandle negative timestamps (make_non_negative, make_zero, auto, disabled)
-timestamp dateSet recording timestamp
-movflags flagsMOV/MP4 flags (+faststart, +frag_keyframe, etc.)
-fflags flagsFormat flags (+genpts, +igndts, +discardcorrupt, etc.)
-bsf:v filterVideo bitstream filter
-bsf:a filterAudio bitstream filter
-tag:v fourcc / -vtag fourccVideo tag/fourcc
-tag:a fourcc / -atag fourccAudio tag/fourcc
-timecode hh:mm:ss:ffSet initial timecode
-force_key_frames exprForce keyframe positions
-copyinkfCopy initial non-keyframes (stream copy)
-init_hw_device type=nameInitialize hw device for output
-enc_time_base modeEncoder timebase (demux, filter, auto)
-attach filenameAdd attachment (fonts, images)
-pre preset_nameUse preset file (per-stream)
-fpre preset_fileUse preset file (per-file)
-max_muxing_queue_size packetsMuxing queue size
-muxing_queue_data_threshold bytesQueue data threshold
-dcodec codecData stream codec (alias for -c:d)
-intraUse only intra frames (deprecated, use -g 1)
-vol volumeAudio volume (256=normal, deprecated, use -af volume)
-autoscaleAuto-scale video (enabled by default)
-noautoscaleDisable auto-scaling
-autorotateAuto-rotate video on output (enabled by default)
-noautorotateDisable auto-rotation on output

Video Color/HDR Options (Output)

OptionDescription
-color_range rangeColor range (tv/pc, limited/full, mpeg/jpeg)
-color_primaries primariesColor primaries (bt709, bt2020, smpte170m, etc.)
-color_trc trcTransfer characteristics (bt709, smpte2084/pq, arib-std-b67/hlg, etc.)
-colorspace spaceColorspace (bt709, bt2020nc, smpte170m, etc.)
-chroma_sample_location locChroma sample location
-top nTop field first (1) or bottom field first (0)
-bits_per_raw_sample nBits per raw sample
-dc precisionIntra DC precision
-qphistShow QP histogram

Subtitle Options

OptionDescriptionType
-snDisable subtitlesInput/Output
-scodec codecSubtitle codecInput/Output
-stag fourccSubtitle tag/fourccOutput
-fix_sub_durationFix subtitle durationsInput
-canvas_size sizeSubtitle canvas sizeInput

FFmpeg 8.0+ Specific Options

OptionDescriptionType
-vaapi_device pathVAAPI device pathInput/Global
-qsv_device pathIntel QSV deviceInput/Global
-vulkan_device deviceVulkan device selectionInput/Global
-fps_mode modeFrame rate mode (replaces -vsync)Output
-enc_stats_pre filePre-encoding stats outputOutput
-enc_stats_post filePost-encoding stats outputOutput
-enc_stats_pre_fmt fmtPre-encoding stats formatOutput
-enc_stats_post_fmt fmtPost-encoding stats formatOutput
-autoscaleAuto-scale to encoder (default)Output
-noautoscaleDisable auto-scalingOutput
-bits_per_raw_sample nSet bits per raw sampleOutput

Threading Options

OptionDescriptionType
-threads nEncoding/decoding threads (0=auto)Per-stream/Output
-thread_type typeThread type (frame, slice)Per-stream
-filter_threads nFilter processing threadsGlobal
-filter_complex_threads nComplex filtergraph threadsGlobal
bash
# Auto-detect threads for encoding
ffmpeg -i input.mp4 -c:v libx264 -threads 0 output.mp4

# Specific thread count
ffmpeg -i input.mp4 -c:v libx264 -threads 8 output.mp4

# Per-stream threading
ffmpeg -i input.mp4 -threads:v 8 -threads:a 2 -c:v libx264 -c:a aac output.mp4

# Filter threads
ffmpeg -filter_threads 4 -i input.mp4 -vf "scale=1920:1080" output.mp4

Format Flags (-fflags)

FlagDescription
+genptsGenerate PTS if missing
+igndtsIgnore DTS (use PTS only)
+ignidxIgnore index
+discardcorruptDiscard corrupted frames
+sortdtsSort packets by DTS
+fastseekEnable fast seeking
+nobufferDisable buffering
+flush_packetsFlush packets immediately
+bitexactBit-exact output
+shortestStop at shortest stream
+autobsfAuto-insert bitstream filters

Format-Specific Options (Not Main Options)

These options belong to specific muxers/demuxers/protocols, not the main FFmpeg options. They are passed using -option value syntax but only work with their specific format.

HLS Muxer Options (Output)

bash
ffmpeg -i input.mp4 -c copy \
  -hls_time 10 \               # Segment duration (seconds)
  -hls_list_size 6 \           # Playlist entries (0=all)
  -hls_segment_filename "seg_%03d.ts" \
  -hls_flags delete_segments \
  playlist.m3u8

Segment Muxer Options (Output)

bash
ffmpeg -i input.mp4 -c copy \
  -f segment \
  -segment_time 60 \           # Segment duration
  -segment_list playlist.txt \
  -segment_format mp4 \
  output_%03d.mp4

DASH Muxer Options (Output)

bash
ffmpeg -i input.mp4 -c copy \
  -f dash \
  -seg_duration 4 \
  -init_seg_name "init_$RepresentationID$.m4s" \
  manifest.mpd

RTSP/RTMP Protocol Options (Input)

bash
ffmpeg -rtsp_transport tcp -i "rtsp://server/stream" output.mp4
ffmpeg -rtmp_buffer 1000 -i "rtmp://server/live/stream" output.mp4

Raw Video Input Options

bash
ffmpeg -f rawvideo -video_size 1920x1080 -pix_fmt yuv420p -framerate 30 \
  -i input.yuv output.mp4

Important: These are NOT position-sensitive like main options. They are format/protocol parameters and only apply when using that specific format.


Hardware Acceleration Device Initialization

CUDA (NVIDIA)

bash
# Basic CUDA
ffmpeg -hwaccel cuda -i input.mp4 -c:v h264_nvenc output.mp4

# Specify device
ffmpeg -hwaccel cuda -hwaccel_device 0 -i input.mp4 -c:v h264_nvenc output.mp4

# Full GPU pipeline (decode + filter + encode on GPU)
ffmpeg -hwaccel cuda -hwaccel_output_format cuda -i input.mp4 \
  -vf "scale_cuda=1920:1080" -c:v h264_nvenc output.mp4

# Initialize named device for filters
ffmpeg -init_hw_device cuda=gpu0:0 -filter_hw_device gpu0 \
  -i input.mp4 -vf "hwupload_cuda,scale_cuda=1920:1080,hwdownload" \
  -c:v libx264 output.mp4

VAAPI (AMD/Intel Linux)

bash
# Basic VAAPI
ffmpeg -hwaccel vaapi -hwaccel_device /dev/dri/renderD128 -i input.mp4 \
  -c:v h264_vaapi output.mp4

# VAAPI with output format
ffmpeg -hwaccel vaapi -hwaccel_output_format vaapi \
  -hwaccel_device /dev/dri/renderD128 -i input.mp4 \
  -vf "scale_vaapi=1920:1080" -c:v h264_vaapi output.mp4

# Using -vaapi_device shortcut
ffmpeg -vaapi_device /dev/dri/renderD128 -i input.mp4 \
  -vf "hwupload,scale_vaapi=1920:1080" -c:v h264_vaapi output.mp4

QSV (Intel)

bash
# Basic QSV
ffmpeg -hwaccel qsv -i input.mp4 -c:v h264_qsv output.mp4

# QSV with device specification
ffmpeg -qsv_device /dev/dri/renderD128 -hwaccel qsv \
  -i input.mp4 -c:v h264_qsv output.mp4

# Full QSV pipeline
ffmpeg -hwaccel qsv -hwaccel_output_format qsv -i input.mp4 \
  -vf "scale_qsv=1920:1080" -c:v h264_qsv output.mp4

Vulkan (Cross-platform FFmpeg 7.1+/8.0+)

bash
# Vulkan hardware acceleration
ffmpeg -init_hw_device vulkan=vk:0 -filter_hw_device vk \
  -i input.mp4 -vf "hwupload,scale_vulkan=1920:1080,hwdownload" \
  -c:v libx264 output.mp4

# Vulkan encoder (FFmpeg 8.0+)
ffmpeg -hwaccel vulkan -hwaccel_output_format vulkan -i input.mp4 \
  -c:v h264_vulkan output.mp4

D3D11VA (Windows)

bash
# D3D11 hardware acceleration
ffmpeg -hwaccel d3d11va -i input.mp4 -c:v h264_nvenc output.mp4

# With specific adapter
ffmpeg -hwaccel d3d11va -hwaccel_device 0 -i input.mp4 \
  -c:v hevc_amf output.mp4

VideoToolbox (macOS)

bash
# VideoToolbox decode + encode
ffmpeg -hwaccel videotoolbox -i input.mp4 \
  -c:v h264_videotoolbox output.mp4

# With ProRes
ffmpeg -i input.mov -c:v prores_videotoolbox output.mov

Advanced Timestamp Handling

Timestamp Options Explained

bash
# Copy timestamps exactly from input
ffmpeg -copyts -i input.mp4 -c copy output.mp4

# Shift timestamps to start at zero
ffmpeg -start_at_zero -i input.mp4 -c copy output.mp4

# Both: copy but start at zero
ffmpeg -copyts -start_at_zero -i input.mp4 -c copy output.mp4

# Offset input timestamps
ffmpeg -itsoffset 5 -i input.mp4 -c copy output.mp4  # Delay by 5 seconds

# Scale input timestamps (2x speed)
ffmpeg -itsscale 0.5 -i input.mp4 -c copy output.mp4

# Handle negative timestamps
ffmpeg -i input.mp4 -avoid_negative_ts make_zero output.mp4

Timestamp Modes

ModeDescription
make_non_negativeShift timestamps to be non-negative
make_zeroShift to start at exactly zero
autoAuto-select based on format
disabledDon't adjust timestamps

Muxer-Specific Options

MP4/MOV Muxer Flags (-movflags)

bash
# Fast start (move moov atom to beginning for web)
ffmpeg -i input.mp4 -c copy -movflags +faststart output.mp4

# Fragmented MP4 (for DASH/streaming)
ffmpeg -i input.mp4 -c copy -movflags +frag_keyframe+empty_moov output.mp4

# Separate moov atom
ffmpeg -i input.mp4 -c copy -movflags +frag_keyframe+separate_moof output.mp4

# All common streaming flags
ffmpeg -i input.mp4 -c copy \
  -movflags +faststart+frag_keyframe+empty_moov+default_base_moof \
  output.mp4
FlagDescription
faststartMove moov before mdat (web streaming)
frag_keyframeFragment at each keyframe
empty_moovEmpty initial moov (DASH)
separate_moofSeparate moof for each track
default_base_moofBase offset at moof (DASH)
negative_cts_offsetsAllow negative CTS offsets
ismlIIS Smooth Streaming
omit_tfhd_offsetOmit offset in tfhd
disable_chplDisable chapter track
write_colrWrite colr atom
write_gamaWrite gama atom

MPEG-TS Muxer Options

bash
# MPEG-TS with PCR
ffmpeg -i input.mp4 -c copy -mpegts_copyts 1 output.ts

# Set service info
ffmpeg -i input.mp4 -c copy \
  -mpegts_service_id 1 \
  -mpegts_service_type digital_tv \
  output.ts

Matroska/WebM Muxer Options

bash
# Cue points at clusters
ffmpeg -i input.mp4 -c:v libvpx-vp9 -cues_to_front 1 output.webm

# Set cluster size
ffmpeg -i input.mp4 -c copy -cluster_size_limit 2M output.mkv

Bitstream Filters (-bsf)

bash
# Extract AnnexB NAL units for H.264
ffmpeg -i input.mp4 -c:v copy -bsf:v h264_mp4toannexb output.h264

# Add SEI recovery point for broadcast
ffmpeg -i input.mp4 -c:v copy -bsf:v h264_redundant_pps output.mp4

# HEVC HVC1 to HEV1
ffmpeg -i input.mp4 -c:v copy -bsf:v hevc_mp4toannexb output.hevc

# Insert ADTS headers for AAC
ffmpeg -i input.mp4 -c:a copy -bsf:a aac_adtstoasc output.aac

# Remove filler data
ffmpeg -i input.mp4 -c:v copy -bsf:v filter_units=remove_types=6 output.mp4

# Metadata injection
ffmpeg -i input.mp4 -c:v copy -bsf:v h264_metadata=level=4.1 output.mp4

Common Bitstream Filters

FilterDescription
h264_mp4toannexbConvert H.264 to AnnexB format
hevc_mp4toannexbConvert HEVC to AnnexB format
aac_adtstoascConvert AAC ADTS to ASC
extract_extradataExtract codec extradata
h264_redundant_ppsAdd redundant PPS
h264_metadataModify H.264 metadata
hevc_metadataModify HEVC metadata
filter_unitsFilter NAL units
dump_extraDump extradata to packets
prores_metadataModify ProRes metadata
vp9_superframeVP9 superframe handling
av1_metadataModify AV1 metadata

Metadata Mapping (-map_metadata)

The -map_metadata option copies metadata between files with fine-grained control.

Syntax

bash
-map_metadata[:metadata_spec_out] infile[:metadata_spec_in]

Metadata Specifiers

SpecifierTarget
gGlobal file metadata
s:stream_indexStream metadata
s:v / s:a / s:sAll video/audio/subtitle streams
c:chapter_indexChapter metadata
p:program_indexProgram metadata

Examples

bash
# Copy all metadata from input to output
ffmpeg -i input.mp4 -map_metadata 0 -c copy output.mp4

# Copy global metadata only
ffmpeg -i input.mp4 -map_metadata:g 0:g -c copy output.mp4

# Strip all metadata
ffmpeg -i input.mp4 -map_metadata -1 -c copy output.mp4

# Copy metadata from second input file
ffmpeg -i video.mp4 -i metadata_source.mp4 -map 0 -map_metadata 1 -c copy output.mp4

# Copy stream metadata from input stream 0 to output stream 0
ffmpeg -i input.mp4 -map_metadata:s:0 0:s:0 -c copy output.mp4

# Copy chapter metadata
ffmpeg -i input.mp4 -map_metadata:c 0:c -map_chapters 0 -c copy output.mp4

# Copy all metadata, but set specific values
ffmpeg -i input.mp4 -map_metadata 0 -metadata title="New Title" -c copy output.mp4

Metadata Manipulation

bash
# Add/modify metadata
ffmpeg -i input.mp4 -metadata title="Video Title" -metadata artist="Creator" output.mp4

# Set stream-specific metadata
ffmpeg -i input.mp4 -metadata:s:v:0 title="Main Video" -metadata:s:a:0 language=eng output.mp4

# Set chapter metadata
ffmpeg -i input.mp4 -metadata:c:0 title="Chapter 1" output.mp4

# Remove specific metadata (set to empty)
ffmpeg -i input.mp4 -metadata comment= -c copy output.mp4

Attachments

Adding Attachments (-attach)

bash
# Attach font file (for subtitles)
ffmpeg -i input.mkv -attach DejaVuSans.ttf \
  -metadata:s:t:0 mimetype=application/x-truetype-font \
  -c copy output.mkv

# Attach cover art
ffmpeg -i input.mp4 -attach cover.jpg \
  -metadata:s:t:0 mimetype=image/jpeg \
  -c copy output.mkv

# Multiple attachments
ffmpeg -i input.mkv \
  -attach font1.ttf -metadata:s:t:0 mimetype=application/x-truetype-font \
  -attach font2.ttf -metadata:s:t:1 mimetype=application/x-truetype-font \
  -c copy output.mkv

Extracting Attachments (-dump_attachment)

bash
# Extract first attachment to specific file
ffmpeg -dump_attachment:t:0 extracted_font.ttf -i input.mkv

# Extract all attachments (uses filename metadata)
ffmpeg -dump_attachment:t "" -i input.mkv

# Extract specific stream by index
ffmpeg -dump_attachment:3 attachment.bin -i input.mkv

Disposition Flags

bash
# Set stream as default
ffmpeg -i input.mkv -c copy -disposition:a:0 default output.mkv

# Set as default and forced subtitle
ffmpeg -i input.mkv -c copy -disposition:s:0 default+forced output.mkv

# Clear all dispositions
ffmpeg -i input.mkv -c copy -disposition:a:1 0 output.mkv

# Multiple dispositions
ffmpeg -i input.mkv -c copy \
  -disposition:v:0 default \
  -disposition:a:0 default \
  -disposition:a:1 0 \
  output.mkv

Disposition Values

ValueDescription
defaultDefault stream for playback
dubDubbed audio track
originalOriginal language
commentCommentary track
lyricsLyrics track
karaokeKaraoke version
forcedForced subtitles
hearing_impairedSubtitles for hearing impaired
visual_impairedAudio for visually impaired
clean_effectsClean audio effects
attached_picAttached picture (cover art)
captionsClosed captions
descriptionsAudio descriptions
metadataMetadata stream
dependentDependent stream
still_imageStill image stream

References