Thứ Sáu, 1 tháng 11, 2013

[Encoding] X264 Settings

Contents

[hide]
This page explains the purpose and use of all x264 parameters. Parameters are ordered the same as their appearance in x264 --fullhelp.
See also x264 Stats Output, x264 Stats File and x264 Encoding Suggestions.

x264 Settings

Help

x264 comes with some inbuilt documentation. To access this help, run x264 with --help, --longhelp or --fullhelp. Each successive option will give more detailed information.

Input

Specify the input video with a single positional argument. For example:
x264.exe --output NUL C:\input.avs
x264 --output /dev/null ~/input.y4m
When your input is raw YUV you must also tell x264 the input resolution. You probably want to specify the framerate with --fps as well:
x264.exe --output NUL --fps 25 --input-res 1280x720 D:\input.yuv 
x264 --output /dev/null --fps 30000/1001 --input-res 640x480 ~/input.yuv

Presets

A system designed to reduce the work needed to generate sane, efficient commandlines that do what you want. For information on what options these settings toggle, check the output of x264.exe --fullhelp.

profile

Default: not set
Limit the profile of the output stream. If you specify a profile, it overrides all other settings, so if you use it, you will be guaranteed a compatible stream. If you set this option, you cannot use lossless encoding (--qp 0 or --crf 0).
You should set this if you know your playback device only supports a certain profile. Most decoders support High profile, so there's no need to set this.
Values available: baseline, main, high, high10, high422, high444.

preset

Default: medium
Change options to trade off compression efficiency against encoding speed. If you specify a preset, the changes it makes will be applied before all other parameters are applied.
You should generally set this option to the slowest you can bear.
Values available: ultrafast, superfast, veryfast, faster, fast, medium, slow, slower, veryslow, placebo.

tune

Default: Not Set
Tune options to further optimize them for your input content. If you specify a tuning, the changes will be applied after --preset but before all other parameters.
If your source content matches one of the available tunings you can use this, otherwise leave unset.
Values available: film, animation, grain, stillimage, psnr, ssim, fastdecode, zerolatency.

slow-firstpass

Default: Not Set
Using --pass 1 applies the following settings at the end of parsing the command line:
You can set --slow-firstpass to disable this.
Note: --preset placebo enables --slow-firstpass.
See also: --pass.

Frame-type options

keyint

Default: 250
Sets the maximum interval between IDR-frames (aka keyframes) in x264's output. You can specify "infinite" to never insert non-scenecut IDR-frames.
IDR-frames are 'delimiters' in the stream - no frame can reference data from the other side of the IDR-frame. As well as this, IDR-frames are also I-frames, so they don't reference data from any other frame. This means they can be used as seek points in a video.
Note that I-frames are generally significantly larger than P/B-frames (often 10x or more in low motion scenes), so they can play havoc with ratecontrol when combined with aggressively low VBV settings (eg, sub-second buffer sizes). In these cases, investigate --intra-refresh.
The default setting is fine for most videos. When encoding for Blu-ray, broadcast, live streaming or certain other specialist scenarios you may require a significantly smaller GOP length (often ~1x fps).
See also: --min-keyint, --scenecut, --intra-refresh

min-keyint

Default: auto (MIN(--keyint / 10,--fps))
Sets the minimum length between IDR-frames.
See --keyint for an explanation of IDR-frames. Very small keyint ranges can cause "incorrect" IDR-frame placement (for example, a strobing scene). This option limits the minimum length in frames after each IDR-frame before another can be placed.
The maximum allowed value for min-keyint is --keyint/2+1
Recommendation: Default, or 1x your framerate.
See also: --keyint, --scenecut

no-scenecut

Default: Not Set
Completely disables adaptive I-frame decision.
See also: --scenecut

scenecut

Default: 40
Sets the threshold for I/IDR frame placement (read: scene change detection).
x264 calculates a metric for every frame to estimate how different it is from the previous frame. If the value is lower than scenecut, a 'scenecut' is detected. An I-frame is placed if it has been less than --min-keyint frames since the last IDR-frame, otherwise an IDR-frame is placed. Higher values of scenecut increase the number of scenecuts detected. For more information on how the scenecut comparison works, see this doom9 thread.
Setting scenecut to 0 is equivalent to setting --no-scenecut.
Recommendation: Default
See also: --keyint, --min-keyint, --no-scenecut

intra-refresh

Default: Off
Disables IDR-frames, instead x264 uses intra coding for each macroblock in the frame every --keyint frames. Blocks are refreshed in a horizontally scrolling column - the 'refresh wave'. This benefits low-latency streaming by making it possible to achieve more constant frame sizes than is possible with standard IDR-frames. It also increases the resilience of the video stream to packet loss. This option does reduce compression efficiency, hence only use it when needed.
Fun facts:
  • The first frame is still an IDR frame.
  • Intra-blocks are placed only in P-frames - the refresh wave is wider in the first P-frame after one or more B-frames.
  • The loss in compression efficiency comes primarily from the fact macroblocks on the 'new' (left) side of the refresh wave can't refer to data on the 'old' (right) side.

bframes

Default: 3
Sets the maximum number of concurrent B-frames that x264 can use.
Without B-frames, a typical x264 stream has frame types like so: IPPPPP...PI. With --bframes 2, up to two consecutive P-frames can be replaced with B-frames, like: IBPBBPBPPPB...PI.
B-frames are similar to P-frames, except they can use motion prediction from future frames as well. This can lead to significantly better efficiency in terms of compression ratio. Their average quality is controlled by --pbratio.
Fun facts:
  • x264 also occasionally distinguishes between two different sorts of B-frames. A 'B' can refer to a B-frame that is used as a reference by other frames (see --b-pyramid, while 'b' can refer to a B-frame that is not. If you see a mix of 'B' and 'b', it's usually related to the above. When the difference is not important, just 'B' is generally used to refer to all B-frames.
  • For more information about the choices x264 makes between P or B frames for each candidate frame, see this ffmpeg-devel mail. In this case, frame types will look like this (in display order) (assuming --bframes 3): IBBBPBBBPBPI.
See also: --no-b-adapt, --b-bias, --b-pyramid, --ref, --pbratio, --partitions, --weightb

b-adapt

Default: 1
Set the adaptive B-frame placement decision algorithm. This setting controls how x264 decides between placing a P- or B-frame.
0. Disabled. Pick B-frames always. This is the same as what the older no-b-adapt setting did.
1. 'Fast' algorithm, faster, speed slightly increases with higher --b-frames setting. When using this mode, you basically always want to use --bframes 16.
2. 'Optimal' algorithm, slower, speed significantly decreases with higher --b-frames setting.
Note: For a multi-pass encode, this option is only needed for the first pass where frame types are decided.

b-bias

Default: 0
Controls the likelihood of B-frames being used instead of P-frames. Values greater than 0 increase the weighting towards B-frames, while values less than 0 do the opposite. This number is an arbitrary metric. The range is from -100 to 100. A value of 100/-100 does not guarantee every/no P-frame will be converted (use --b-adapt 0 for that).
Only use this if you think you make better ratecontrol decisions than x264.
See also: --b-frames, --ipratio

b-pyramid

Default: normal
Allow the use of B-frames as references for other frames. Without this setting, frames can only reference I- or P-frames. Although I/P-frames are more valued as references because of their higher quality, B-frames can also be useful. B-frames designated as references will get a quantizer halfway between P-frames and normal B-frames. You need to use at least two B-frames before B-pyramid will work.
If you're encoding for Blu-ray, use 'none' or 'strict'.
  • none: do not allow B-frames to be used as references.
  • strict: allow one B-frame per minigop to be used as reference; enforces restrictions imposed by the Blu-ray standard.
  • normal: allow numerous B-frames per minigop to be used as references.
See also: --bframes, --refs, --no-mixed-refs

open-gop

Default: none
Open-GOP is an encoding technique which increases efficiency. Some decoders don't fully support open-GOP streams, which is why it hasn't been enabled by default. You should test with all decoders your streams will be played on, or (if that's impossible) wait until support is generally available.
There's an explanation of Open-GOP here.

no-cabac

Default: Not set
Disables CABAC (Context Adaptive Binary Arithmetic Coder) stream compression and falls back to the less efficient CAVLC (Context Adaptive Variable Length Coder) system. Significantly reduces both the compression efficiency (10-20% typically) and the decoding requirements.

ref

Default: 3
Controls the size of the DPB (Decoded Picture Buffer). The range is from 0-16. In short, this value is the number of previous frames each P-frame can use as references. (B-frames can use one or two fewer, depending on if they are used as references or not.) The minimum number of refs that can be referenced is 1.
Also note that the H.264 spec limits DPB size for each level. If adhering to Level 4.1 specs, the maximum refs for 720p and 1080p video are 9 and 4 respectively. You can read more about levels and 4.1 in particular under --level.
See also: --b-pyramid, --no-mixed-refs, --level

no-deblock

Default: Not Set
Completely disables the loop filter. Not Recommended.
See Also: --deblock

deblock

Default: 0:0
Controls the loop filter (aka inloop deblocker), which is part of the H.264 standard. It is very efficient in terms of encoding time vs. quality gained.
You can find a good description of how the loop filter parameters work in this doom9 thread (see the initial post and akupenguin's replies).
See Also: --no-deblock

slices

Default: 0
Sets the number of slices per frame, and forces rectangular slices. (Overridden by either --slice-max-size or --slice-max-mbs if they are set.)
If you are encoding for Blu-ray, set this to four. Otherwise, don't use this unless you know you need to.
See Also: --slice-max-size, --slice-max-mbs.

slice-max-size

Default: 0
Sets the maximum slice size in bytes, including estimated NAL overhead. (Currently is not compatible with --interlaced.)
See Also: --slices

slice-max-mbs

Default: 0
Sets the maximum slice size in macroblocks. (Currently is not compatible with --interlaced.)
See Also: --slices

tff

Enable interlaced encoding and specify the top field is first. x264's interlaced encoding uses MBAFF, and is inherently less efficient than progressive encoding. For that reason, you should only encode interlaced if you intend to display the video on an interlaced display (or can't deinterlace the video before sending it to x264). Implies --pic-struct.

bff

Enable interlaced encoding and specify the bottom field is first. See --tff for more info.

no-interlaced

Forces x264 to output in progressive mode.

constrained-intra

Default: Not Set
Enable constrained intra prediction, which is required for the base layer of SVC encodes. Since EveryoneTM ignores SVC you can likewise ignore this switch.

pulldown

Default: none
Signal soft telecine for your (progressive, constant framerate) input stream using one of a few preset modes. Soft telecine is explained in more detail on the HandBrake wiki. The available presets are: none, 22, 32, 64, double, triple and euro.
Specifying any mode but none implies --pic-struct.

fake-interlaced

Default: Not Set
Mark a stream as interlaced even when not encoding as interlaced. Allows encoding of 25p and 30p Blu-ray compliant videos.

frame-packing

Default: Not Set
If you're encoding 3d video, this parameter sets a bitstream flag that tells your decoder how the 3d video was packed. The values and what they mean can be found in x264 --fullhelp.

Ratecontrol

qp

Default: Not Set
The first of three possible ratecontrol methods. Set x264 to encode the movie in Constant Quantizer mode. The number you give here specifies the P-frame quantizer. The quantizer used for I- and B-frames is derived from --ipratio and --pbratio. CQ mode targets a certain quantizer, which means final filesize is not known (although it can be reasonably accurately estimated with some methods). A setting of 0 will produce lossless output. qp produces larger files than --crf for the same visual quality. qp mode also disables adaptive quantization, since by definition 'constant quantizer' implies no adaptive quantization.
This option is mutually exclusive with --bitrate and --crf. See this writeup for more information on the various ratecontrol systems.
You should generally use --crf instead, although qp doesn't require lookahead to run and thus can be faster.
See also: --bitrate, --crf, --ipratio, --pbratio

bitrate

Default: Not Set
The second of three ratecontrol methods. Encode the video in target bitrate mode. Target bitrate mode means the final filesize is known, but the final quality is not. x264 will attempt to encode the video to target the given bitrate as the overall average. The parameter given is the bitrate in kilobits/sec. (8bits = 1byte and so on). Note that 1 kilobit is 1000, not 1024 bits.
This setting is often used in conjunction with --pass for two-pass encoding.
This option is mutually exclusive with --qp and --crf. See this writeup for more information on the various ratecontrol systems.
See also: --qp, --crf, --ratetol, --pass, --stats

crf

Default: 23.0
The final ratecontrol method: Constant Ratefactor. While qp targets a certain quantizer, and bitrate targets a certain filesize, crf targets a certain 'quality'. The idea is for crf n to give the same perceptual quality as qp n, just in a smaller space. The arbitrary unit of measure for crf values is the "ratefactor".
CRF achieves this by reducing the quality of 'less important' frames. In this context, 'less important' means frames in complex or high-motion scenes, where quality is either more expensive (in terms of bits) or less visible, will have their quantizer increased. The bits saved in frames like these are redistributed to frames where they will be more effective.
CRF will take less time than a 2pass bitrate encode, because the 'first pass' from a 2pass encode was skipped. On the other hand, it's impossible to predict the bitrate a CRF encode will come out to. It's up to you to decide which rate-control mode is better for your circumstances.
This option is mutually exclusive with qp and bitrate. See this writeup for more information on the various ratecontrol systems.
See also: --qp, --bitrate

rc-lookahead

Default: 40
Sets the number of frames to use for mb-tree ratecontrol and vbv-lookahead. The maximum allowed value is 250.
For the mb-tree portion of this, increasing the frame count generates better results but is also slower. The maximum buffer value used by mb-tree is the MIN( rc-lookahead, --keyint )
For the vbv-lookahead portion of this, increasing the frame count generates better stability and accuracy when using vbv. The maximum value used by vbv-lookahead is:
MIN(rc-lookahead, MAX(--keyint, MAX(--vbv-maxrate, --bitrate) / --vbv-bufsize * --fps))
See Also: --no-mbtree, --vbv-bufsize, --vbv-maxrate, --sync-lookahead

vbv-maxrate

Default: 0
Sets the maximum rate the VBV buffer should be assumed to refill at.
VBV reduces quality, so you should only use this if you're encoding for a playback scenario that requires it.
See also: --vbv-bufsize, --vbv-init, VBV Encoding Suggestions

vbv-bufsize

Default: 0
Sets the size of the VBV buffer in kilobits.
VBV reduces quality, so you should only use this if you're encoding for a playback scenario that requires it.
See also: --vbv-maxrate, --vbv-init, VBV Encoding Suggestions

vbv-init

Default: 0.9
Sets how full the VBV Buffer must be before playback starts.
If it is less than 1, the the initial fill is: vbv-init * vbv-bufsize. Otherwise it is interpreted as the initial fill in kbits.
See also: --vbv-maxrate, --vbv-bufsize, VBV Encoding Suggestions

crf-max

Default: Not set
A similar setting to --qpmax except instead of specifying a maximum quantizer you're specifying a maximum ratefactor. This option only works when you are using CRF and have VBV enabled. It prevents x264 from reducing the ratefactor (aka "quality") below the given value even when doing so would violate VBV constraints. This setting is mostly applicable to custom streaming servers. More information can be found in the initial commit message.
See Also: --crf, --vbv-maxrate, --vbv-bufsize

qpmin

Default: 0
Defines the minimum quantizer that x264 will ever use. The lower the quantizer, the closer the output is to the input. At some point, the output of x264 will look the same as the input, even though it is not exactly the same. Usually there is no reason to allow x264 to spend more bits than this on any particular macroblock.
With adaptive quantization enabled (the default), raising qpmin is discouraged because this could reduce the quality of flat background areas of the frame.
See also: --qpmax, --ipratio

qpmax

Default: 51
The opposite of qpmin, above. Defines the maximum quantizer that x264 can use. The default of 51 is the highest quantizer available for use in the H.264 spec, and is extremely low quality. This default effectively disables qpmax. You may want to set this lower (values in the 30-40 range are generally as low as you'd go) if you want to cap the minimum quality x264 can output, but adjusting it is generally not recommended.
See also: --qpmin, --pbratio, --crf-max

qpstep

Default: 4
Sets the maximum change in quantizer between two frames.

ratetol

Default: 1.0
This is a dual purpose parameter:
  • In 1-pass bitrate encodes, this settings controls the percentage that x264 can miss the target average bitrate by. You can set this to 'inf' to disable this overflow detection completely. The lowest you can set this is to 0.01. The higher you set this to the better x264 can react to complex scenes near the end of the movie. The unit of measure for this purpose is percent (eg, 1.0 = 1% bitrate deviation allowed).
Many movies (any action movie, for instance) are most complex at the climatic finale. As a 1pass encode doesn't know this, the number of bits required for the end is usually underestimated. A ratetol of inf can mitigate this by allowing the encode to function more like a --crf encode, but the filesize will blow out.
  • When VBV is activated (ie, you're specified --vbv-* options), this setting also affects VBV aggressiveness. Setting this higher allows VBV to fluctuate more at the risk of possibly violating the VBV settings. For this purpose, the unit of measure is arbitrary.

ipratio

Default: 1.40
Modifies the target average increase in quantizer for I-frames as compared to P-frames. Higher values increase the quality of I-frames generated.
See also: --pbratio

pbratio

Default: 1.30
Modifies the target average decrease in quantizer for B-frames as compared to P-frames. Higher values decrease the quality of B-frames generated. Not used with mbtree (enabled by default), which calculates the optimum value automatically.
See also: --ipratio

chroma-qp-offset

Default: 0
Add an offset to the quantizer of chroma planes when encoding. The offset can be negative.
When using psy options are enabled (psy-rd, psy-trellis), x264 automatically subtracts 2 from this value to compensate for these optimisations overly favouring luma detail by default.
Note: x264 only encodes the luma and chroma planes at the same quantizer up to quantizer 29. After this, chroma is progressively quantized by a lower amount than luma until you end with luma at q51 and chroma at q39. This behavior is required by the H.264 standard.

aq-mode

Adaptive Quantization Mode
Default: 1
Without AQ, x264 tends to underallocate bits to less-detailed sections. AQ is used to better distribute the available bits between all macroblocks in the video. This setting changes what scope AQ re-arranges bits in:
  • 0: Do not use AQ at all.
  • 1: Allow AQ to redistribute bits across the whole video and within frames.
  • 2: Auto-variance AQ (experimental) which attempts to adapt strength per-frame.
See also: --aq-strength

aq-strength

Adaptive Quantization Strength
Default: 1.0
Sets the strength of AQ bias towards low detail ('flat') macroblocks. Negative values are not allowed. Values outside the range 0.0 - 2.0 are probably a bad idea.
See also: --aq-mode

pass

Default: Not Set
This is an important setting for 2pass encoding. It controls what x264 will do with the --stats file. It has three settings:
  • 1: Create a new stats file. Use this on the first pass.
  • 2: Read the stats file. Use this on the final pass.
  • 3: Read the stats file, and update it as well.
The stats file contains information about every input frame, which can be input to x264 in order to improve the output. The idea is you run a first pass to generate the stats file, and the second pass will create an optimized encode of the video. The improvement is mostly gained from better ratecontrol.
See also: --stats, --bitrate, --slow-firstpass X264_statsfile

stats

Default: 'x264_2pass.log'
Set the location that x264 will read/write the --pass X264_statsfile to/from.
See also: --pass

no-mbtree

Default: Not Set
Disable macroblock tree ratecontrol. Using macroblock tree ratecontrol overall improves the compression by keeping track of temporal propagation across frames and weighting accordingly. Requires a new large statsfile in addition to the already existing for multipass encodes.
Recommendation: Default
See Also: --rc-lookahead

qcomp

Default: 0.60
Quantizer curve compression factor. 0.0 => Constant Bitrate, 1.0 => Constant Quantizer.
When used with mbtree, it affects the strength of mbtree. (Higher qcomp = weaker mbtree).
Recommendation: Default
See Also: --cplxblur, --qblur

cplxblur

Default: 20
Apply a gaussian blur with the given radius to the quantizer curve. This means that the quantizer assigned to each frame is blurred temporally with its neighbours to limit quantizer fluctuations.
See also: --qcomp, --qblur

qblur

Default: 0.5
Apply a gaussian blur with the given radius to the quantizer curve, after curve compression. Not a very important setting.
See also: --qcomp, --cplxblur

zones

Default: Not Set
Tweak settings for specific sections of the video. You can modify most x264 options per-zone.
  • A single zone takes the form of ,,
  • Multiple zones are separated from each other with a '/'

Options:
These two options are special. You can only set one per zone, and if you set one, it must be the first option listed for the zone:
  • b= applies a bitrate multiplier on the zone. Useful for extra tweaking of high- and low-action scenes.
  • q= applies a constant quantizer on the zone. Useful for applying to a range of frames.
The other available options are as follows:
  • ref=
  • b-bias=
  • scenecut=
  • no-deblock
  • deblock=:
  • deadzone-intra=
  • deadzone-inter=
  • direct=
  • merange=
  • nr=
  • subme=
  • trellis=
  • (no-)chroma-me
  • (no-)dct-decimate
  • (no-)fast-pskip
  • (no-)mixed-refs
  • psy-rd=:
  • me=
  • no-8x8dct
  • b-pyramid=
  • crf=
Limitations:
  • The number of reference frames for a zone can never exceed what was specified with --ref
  • Scenecut can not be turned on and off; only varied if originally active (>0)
  • Merange can not exceed what was originally specified if --me esa/tesa
  • Subme can't be changed if the original commandline specified it as 0.
  • You can't set me to esa or tesa if --me was originally specified as dia, hex, or umh
Example: 0,1000,b=2/1001,2000,q=20,me=3,b-bias=-1000
Recommendation: Default

qpfile

Manual override to standard ratecontrol. Specify a file that gives the quantizer and frametype for specified frames. The format is 'framenum frametype quantizer'. For example:
0 I 18 < IDR (key) I-frame
1 P 18 < P-frame
2 B 18 < Referenced B-frame
3 i 18 < Non-IDR (non-key) I-frame
4 b 18 < Non-referenced B-frame
5 K 18 < Keyframe*
  • You don't need to specify every frame
  • Using -1 as the desired quantizer allows x264 to choose the optimal quantizer value, useful when only needing to set the frametype
  • Having a large number of specified frame types and quantizers while still letting x264 choose intermittently decreases x264's performance
  • 'Keyframe' is a generic keyframe/seekpoint type that equates to a IDR I-Frame if --open-gop is none, otherwise it equates to a Non-IDR I-Frame flagged with the Recovery Point SEI

Analysis

partitions

Default: 'p8x8,b8x8,i8x8,i4x4'
H.264 video is split up into 16x16 macroblocks during compression. These blocks can be further split up into smaller partitions, which is what this option controls.
With this option, you enable individual partitions. Partitions are enabled per-frametype (i.e., I, P, B). The available partitions are p8x8, p4x4, b8x8, i8x8, and i4x4.
  • I: i8x8, i4x4
  • P: p8x8 (also enables p16x8/p8x16), p4x4 (also enables p8x4/p4x8)
  • B: b8x8 (also enables b16x8/b8x16)
You can also set 'none' or 'all'.
p4x4 is generally not very useful and has an extremely high ratio of speed cost to resulting quality gain.
See also: --no-8x8dct

direct

Default: 'spatial'
Set prediction mode for 'direct' motion vectors. There are two modes available: spatial and temporal. You can also select none to disable direct MVs, and auto to allow x264 to swap between them as it sees fit. If you set auto, x264 outputs information on the usage at the end of the encode. 'auto' works best in a 2pass encode, but will work in single-pass encodes too. In first-pass auto mode, x264 keeps a running average of how well each method has so far performed, and picks the next prediction mode from that. Note that you should only enable auto on the second pass if it was enabled on the first pass; if it wasn't, the second pass will default to temporal. Direct none wastes bits and is strongly discouraged.
Recommendation: 'auto'

no-weightb

Default: Not Set
H.264 allows you to 'weight' references in B-frames, which allows you to change how much each reference affects the predicted picture. This disables that feature.
Recommendation: Default

weightp

Default: 2
Enables use of explicit weighted prediction to improve compression in P-frames. Also improves quality in fades. Higher modes are slower.
NOTE: When encoding for Adobe Flash set this to 1 - its decoder generates artifacts otherwise. Flash 10.1 fixes this bug.
Modes:
  • 0. Disabled.
  • 1. Simple: fade analysis, but no reference duplication.
  • 2. Smart: fade analysis and reference duplication.

me

Default: 'hex'
Set the full-pixel motion estimation method. There are five choices:
  • dia (diamond) is the simplest search, consisting of starting at the best predictor, checking the motion vectors at one pixel upwards, left, down, and to the right, picking the best, and repeating the process until it no longer finds any better motion vector.
  • hex (hexagon) consists of a similar strategy, except it uses a range-2 search of 6 surrounding points, thus the name. It is considerably more efficient than dia and hardly any slower, and therefore makes a good choice for general-use encoding.
  • umh (uneven multi-hex) is considerably slower than hex, but searches a complex multi-hexagon pattern in order to avoid missing harder-to-find motion vectors. Unlike hex and dia, the merange parameter directly controls umh's search radius, allowing one to increase or decrease the size of the wide search.
  • esa (exhaustive) is a highly optimized intelligent search of the entire motion search space within merange of the best predictor. It is mathematically equivalent to the bruteforce method of searching every single motion vector in that area, though faster. However, it is still considerably slower than UMH, with not too much benefit, so is not particularly useful for everyday encoding.
  • tesa (transformed exhaustive) is an algorithm which attempts to approximate the effect of running a Hadamard transform comparison at each motion vector; like exhaustive, but a little bit better and a little bit slower.
See also: --merange

merange

Default: 16
merange controls the max range of the motion search in pixels. For hex and dia, the range is clamped to 4-16, with a default of 16. For umh and esa, it can be increased beyond the default 16 to allow for a wider-range motion search, which is useful on HD footage and for high-motion footage. Note that for umh, esa, and tesa, increasing merange will significantly slow down encoding.
Extremely high merange (e.g. >64) is unlikely to find any new motion vectors that are useful, so it may very slightly decrease compression in some cases by picking motion vector deltas so large that they even worsen prediction of future motion vectors in the rare cases they're locally useful, making them worse than useless.
The effect is so small as to be near-negligible, though, and you shouldn't be using such insane settings.this post
See also: --me

mvrange

Default: -1 (auto)
Set the maximum (vertical) range of any one motion vector in pixels. The default value is level-dependent:
  • Level 1/1b: 64
  • Level 1.1-2.0: 128
  • Level 2.1-3.0: 256
  • Level 3.1+: 512
Note: if you want to manually override the mvrange, subtract 0.25 from the above values when setting (eg --mvrange 127.75).
Recommendation: Default

mvrange-thread

Default: -1 (auto)
Set the minimum motion vector buffer between threads. Don't touch it.
Recommendation: Default

subme

Default: 7
Set the subpixel estimation complexity. Higher numbers are better. Levels 1-5 simply control the subpixel refinement strength. Level 6 enables RDO for mode decision, and level 8 enables RDO for motion vectors and intra prediction modes. RDO levels are significantly slower than the previous levels.
Using a value less than 2 will enable a faster, and lower quality lookahead mode, as well as cause poorer --scenecut decisions to be made, and thus it is not recommended.
Possible Values:
0. fullpel only
1. QPel SAD 1 iteration
2. QPel SATD 2 iterations
3. HPel on MB then QPel
4. Always QPel
5. Multi QPel + bi-directional motion estimation
6. RD on I/P frames
7. RD on all frames
8. RD refinement on I/P frames
9. RD refinement on all frames
10. QP-RD (requires --trellis=2, --aq-mode > 0)
11. Full RD [1][2]
Recommendation: Default, or higher, unless speed is very important.

subq

Alias of --subme

psy-rd

Default: 1.0:0.0
The first number is the strength of Psy-RDO to use (requires subme>=6 to activate). The second number is the strength of Psy-Trellis (requires trellis>=1 to activate). Note that Trellis is still considered 'experimental', and almost certainly is a Bad Thing for at least cartoons.
See this thread on doom9 for an explanation of psy-rd.
Life is short, and this article saved valubale time on this Earth.

no-mixed-refs

Default: Not Set
Mixed refs will select refs on a per-8x8 partition, rather than per-macroblock basis. This improves quality when using multiple reference frames, albeit at some speed cost. Setting this option will disable it.
Recommendation: Default
See also: --ref

no-chroma-me

Default: Not Set
Normally, motion estimation works off both the luma and chroma planes. This disables chroma motion estimation for a small speed boost.
Recommendation: Default

no-8x8dct

Default: Not Set
Adaptive 8x8 DCT enables the intelligent adaptive use of 8x8 transforms in I-frames. This disables the feature.
Recommendation: Default

trellis

Default: 1
Performs Trellis quantization to increase efficiency.
0. Disabled
1. Enabled only on the final encode of a macroblock
2. Enabled on all mode decisions
On Macroblock provides a good compromise between speed and efficiency. On all decisions reduces speed further.
See: Trellis Quantization
Recommendation: Default
Note: Requires --cabac

no-fast-pskip

Default: Not Set
Disables early skip detection on P-frames. At low bitrates, provides a moderate quality increase for a large speed cost. At high bitrates, has negligible effect on both speed and quality.
Recommendation: Default

no-dct-decimate

Default: Not Set
DCT Decimation will drop DCT blocks it deems "unnecessary". This will improve coding efficiency, with a usually negligible loss in quality. Setting this option will disable it.
Recommendation: Default

nr

Default: Not Set
Performs fast noise reduction. Estimates film noise based on this value and attempts to remove it by dropping small details before quantization. This may not match the quality of a good external noise reduction filter, but it performs very fast.
Recommendation: Default or (100 to 1000 for denoising)

deadzone-inter/intra

Default: Not Set
Set the size of the inter/intra luma quantization deadzone. Deadzones should be in the range of 0 to 32. The deadzone value sets the level of fine detail that x264 will arbitrarily drop without attempting to preserve. Very fine detail is both hard to see and expensive to encode, dropping this detail without attempting to preserve it stops wasting bits on such a low-return section of the video. Deadzone is incompatible with Trellis.
Recommendation: Default

cqm

Default: Flat (Not Set)
Sets all custom quantization matrices to those of a built-in preset. The built-in presets are flat or JVT.
Recommendation: Default
See also: --cqmfile

cqmfile

Default: Not Set
Sets custom quantization matrices from a specified JM-compatible file. Overrides any other --cqm* options.
Recommendation: Default
See also: --cqm

cqm4* / cqm8*

Default: Not Set
  • --cqm4: Set all 4x4 quant matrices. Takes a comma-separated list of 16 integers.
  • --cqm8: Set all 8x8 quant matrices. Takes a comma-separated list of 64 integers.
  • --cqm4i, --cqm4p, --cqm8i, --cqm8p: Set both luma and chroma quant matrices
  • --cqm4iy, --cqm4ic, --cqm4py, --cqm4pc: Set individual quant matrices. Same switches exist for cqm8.
Recommendation: Default

Video Usability Info

These options set a flag in the output stream that can be read by the decoding application and possibly acted on. It's worth noting that most of these options in most scenarios are pointless, and are usually ignored by software decoders.

overscan

Default: undef
How to handle overscan. Overscan is used here in the sense of a device only displaying part of an image.
Possible Values:
  • undef - Undefined.
  • show - Indicate to show the entire image. Theoretically must be respected if set.
  • crop - Indicate that the image is suitable for playback on devices with overscan. Not necessarily respected.
Recommendation: Crop before encoding and use show if your device supports it, otherwise ignore.

videoformat

Default: undef
Indicates what the video was before encoding/digitizing.
Possible Values:
  • component
  • pal
  • ntsc
  • secam
  • mac
  • undef
Recommendation: Whatever your source video was, or undefined.

range

Default: auto
Indicates whether the output range of luma and chroma levels should be limited or full. If set to TV, the limited ranges will be used. If set to auto, use the same range as input.
NOTE: If range and --input-range differ, then a range conversion will occur!
See this page for a simple description.
Recommendation: Default.
See also: --input-range

colorprim

Default: undef
Set what color primaries for converting to RGB.
Possible Values:
  • undef
  • bt709
  • bt470m
  • bt470bg
  • smpte170m
  • smpte240m
  • film
See: RGB and YCrCb
Recommendation: Default, unless you know what your source uses.

transfer

Default: undef
Set the opto-electronic transfer characteristics to use. (Sets the gamma curve to use for correction.)
Possible Values
  • undef
  • bt709
  • bt470m
  • bt470bg
  • linear
  • log100
  • log316
  • smpte170m
  • smpte240m
See: Gamma Correction
Recommendation: Default, unless you know what your source uses.

colormatrix

Default: undef
Set the matrix coefficients used in deriving the luma and chroma from the RGB primaries.
Possible Values
  • undef
  • bt709
  • fcc
  • bt470bg
  • smpte170m
  • smpte240m
  • GBR
  • YCgCo
See: YCbCr
Recommendation: Whatever your sources uses, or default.

chromaloc

Default: 0
Sets the chroma sample location. (as defined in Annex E of the ITU-T Specification).
Values range from 0 to 5.
See x264's vui.txt
Recommendation:
  • If you transcode from MPEG1 with proper subsampled 4:2:0, and don't do any color space conversion, you should set this option to 1.
  • If you transcode from MPEG2 with proper subsampled 4:2:0, and don't do any color space conversion, you should set this option to 0.
  • If you transcode from MPEG4 with proper subsampled 4:2:0, and don't do any color space conversion, you should set this option to 0.
  • Otherwise, default.

nal-hrd

Default: None
Signal HRD information. Required for Blu-ray streams, television broadcast and a few other specialist areas. Acceptable values are:
  • none Specify no HRD information
  • vbr Specify HRD information
  • cbr Specify HRD information and pack the bitstream to the bitrate specified by bitrate. Requires bitrate mode ratecontrol.
Recommendation: none, unless you need to signal this information.
See also: --vbv-bufsize, --vbv-maxrate, --aud

pic-struct

Default: Not Set
Force sending pic_struct in Picture Timing SEI.
Implied when you use --pulldown or --tff/--bff.
Recommendation: Default

crop-rect

Default: Not Set
Specify a bitstream-level cropping rectangle. You can use this if you want the decoder to crop on playback, but don't want to crop the video x264 encodes for some reason. Specify the value in pixels that should be cropped on playback.

Input/Output

output

Default: Not Set.
Specifies output filename. The extension you specify determines the output format of your video. If the extension is not recognised the default output format is the raw video stream (generally stored with the .264 extension).
The special location NUL (Windows) or /dev/null (Unix) specifies the output should be discarded. This is particularly useful when using --pass 1, as the only output you care about is that from --stats.

muxer

Default: auto
Specifies what format to write to.
Possible Values
  • auto
  • raw
  • mkv
  • flv
  • mp4
The 'auto' option will pick a muxer based on the supplied output filename.
See also: --output
Recommendation: Default

demuxer

Default: Automatically detected.
Sets what demuxer and decoder x264 uses for parsing the input video.
Possible Values
  • auto
  • raw
  • y4m
  • avs
  • lavf
  • ffms
If the input file has an extension of raw, y4m or avs, x264 will use the relevant demuxer to read the file. Standard input uses the raw demuxer. Otherwise, x264 will attempt to open the file with ffms, then lavf, and then fail.
The 'lavf' and 'ffms' options require x264 to be compiled with the respective libraries. If either is used, x264 will carry over the timecodes from the input file, provided you don't output to raw. This effectively makes x264 VFR-aware. The other options can have a constant framerate specified with --fps or a variable framerate with --tcfile-in.
See also: --input, --muxer
Recommendation: Default.

input-csp

Default: i420
Tell x264 what colourspace your raw video input is with this switch. Supported colourspaces are listed in x264 --fullhelp.
See Also: --input-res, --fps

output-csp

Default: i420
Tell x264 what colourspace you want out. Supported colourspaces are listed in x264 --fullhelp.
Possible Values
  • i420
  • i422
  • i444
  • rgb
See Also: --input-csp

input-range

Default: auto
Indicates the source's range of luma and chroma levels. Can be set to TV for limited ranges or PC for full ranges.
NOTE: If --range and input-range differ, then a range conversion will occur!
Recommendation: Default, unless you know if your source is TV or PC levels.
See also: --range

input-res

Specify the input resolution of raw video input. Use the syntax --input-res 720x576.
See Also: --input-csp, --fps

index

Default: Not Set
An optional setting that only takes effect when using the ffms --demuxer. Specifies a file for ffms to write out indexing data for the input file to, which can be referred to in a future encode to remove the need to reindex the video. Generally not needed -- indexing is not a slow process relative to video encoding.
See also: --demuxer, FFMS2 API Documentation
Recommendation: Default, unless you want to save a minute amount of time indexing.

sar

Default: Not Set
Specifies the input video's Sample Aspect Ratio (SAR) to be used by the encoder in width:height.
This in conjunction with frame dimensions can be used to encode an anamorphic output by determining the Display Aspect Ratio (DAR) via the formula: DAR = SAR x width/height
See Main Article here
Recommendation: You might need to set this if you're using the resize filter and encoding with anamorphic input.

fps

Default: autodetected
Specifies video framerate as either a float (29.970) a rational (30000/1001), or an integer (2997/100) value. x264 detects and uses the framerate from the input stream header when available (y4m, avs, ffms and lavf demuxer), otherwise uses 25. Setting this implies --force-cfr.
If you are using raw YUV input and --bitrate-based ratecontrol, you need to specify the correct framerate using this parameter or --tcfile-in. x264 won't hit your target bitrate otherwise.

seek

Default: Not Set
Specifies the first frame to encode, allowing the encode to begin at any point in the source.
Recommendation: Default

frames

Default: Not Set
Specifies the maximum number of frames to encode, allowing the encode to finish at any point before the end of the source.
Recommendation: Default

level

Default: -1 (auto)
Sets the level flag in the output bitstream (as defined by Annex A of the H.264 standard). Permissible levels are:
1 1b 1.1 1.2 1.3 2 2.1 2.2 3 3.1 3.2 4 4.1 4.2 5 5.1
If you do not specify --level on the commandline, x264 will attempt to autodetect the level. This detection is not perfect and may underestimate the level if you are not using VBV. x264 will also automatically limit the DPB size (see --ref) to remain in compliance with the level you select (unless you also manually specify --ref). Note: specifying the level does not automatically set the --vbv-maxrate or --vbv-bufsize, however it will warn if the level specific properties are exceeded.
What Level Do I Pick?
Level 4.1 is often considered the highest level you can rely on desktop consumer hardware to support. Blu-ray Discs only support level 4.1, and many non-mobile devices like the Xbox 360 specify level 4.1 as the highest they officially support. Mobile devices like the iPhone/Android are a totally different story.
Wikipedia has a nice chart detailing the restrictions for each level, if you want to read it.
Recommendation: Default, unless you are aiming for a specific device.

bluray-compat

Default: Not set
Modify x264's options to ensure better compatibility with all Blu-Ray players. Only neccessary if your video will be played by Blu-Ray hardware players.
This setting makes some option changes:
It also enables some internal x264 hacks to produce more hardware-player-friendly streams. For example:
  • GOP/mini-GOP tweaks to size and reference lists.
  • More verbose slice headers
Recommendation: Set if you're encoding for hardware Blu-Ray players.

verbose

Default: Not Set
Displays statistics for each encoded frame.
Recommendation: Default

no-progress

Default: Not Set
Disables the progress indicator while encoding.
Recommendation: Default

quiet

Default: Not Set
Enables Quiet Mode, silencing status messages from x264.
Recommendation: Default

log-level

Default: info
Manually specify the logging level of both x264cli and libx264.
Possible Values
  • none
  • error
  • warning
  • info
  • debug
Recommendation: Default

psnr

Default: Not Set
Enables PSNR calculations that are reported on completion at the cost of a small decrease in speed.
Recommendation: Default

ssim

Default: Not Set
Enables SSIM calculations that are reported on completion at the cost of a small decrease in speed.
Recommendation: Default

threads

Default: auto (frame based threads: 1.5 * logical processors, rounded down; slice based threads: 1 * logical processors)
Enables parallel encoding by using more than 1 thread to increase speed on multi-core systems. The quality loss from multiple threads is mostly negligible unless using very high numbers of threads (say, above 16). The speed gain should be slightly less than linear until you start using more than 1 thread per 40px of vertical video, at which point the gain from additional threads sharply decreases.
x264 currently has an internal limit on the number of threads set at 128, realistically you should never set it this high.
Recommendation: Default
See also: --sliced-threads, --thread-input

sliced-threads

Default: off
Enables slice-based threading. This threading method produces lower quality results than the default method both compression and efficiency-wise, but adds no encoding latency.
The maximum number of sliced threads is MIN( (height+15)/16 / 4, 128 )
Recommendation: Default (off), unless you are doing some sort of realtime streaming or low latency is important.

thread-input

Default: Set if threads > 1.
Decodes the input video in a separate thread to the encoding process.
Recommendation: Default.

sync-lookahead

Default: auto (bframes+1)
Sets the number of frames to be used as a buffer for threaded lookahead. Maximum Value is 250. Automatically disabled during the 2nd or greater pass or when using sliced threads.
Setting this to 0 disables threaded lookahead, which allows lower latency at the cost of reduced performance.
Recommendation: Default

non-deterministic

Default: Not Set
Slightly improve quality when encoding with --threads > 1, at the cost of non-deterministic output encodes. This enables multi-threaded mv and uses the entire lookahead buffer in slicetype decisions when slicetype is threaded -- rather than just the minimum amount known to be available.
Not for general use.
Recommendation: Default
See also: threads

asm

Default: auto
Override automatic CPU detection. Useful for debugging or troubleshooting.
Recommendation: Default

no-asm

Default: Not Set
Disables all CPU optimisations. Useful for debugging or troubleshooting.
Recommendation: Default

visualize

Default: Not Set
Enables Macroblock Type visualizations over the encoded video. Useful for frame by frame debugging or analysis.
Requires compile time support, and an X11 windowing system.
Recommendation: Default

dump-yuv

Default: Not Set
Dumps the reconstructed YUV frames to the specified file. Useful mostly for debugging. Not for general use.
Recommendation: Default

sps-id

Default: Not Set
Set SPS (sequence parameter set) and PPS (picture parameter set) id numbers. Not for general use.
Recommendation: Default

aud

Default: Not Set
Use access unit delimiters.
Recommendation: Default, unless encoding for Blu-ray, in which case set this option.

force-cfr

Default: Not Set
If using ffms2 or lavf demuxers, timecodes are copied from the input file, provided the output file is not raw. This option disables this, and forces x264 to generate its own. When using this you probably also want to set --fps.
Recommendation: Default

tcfile-in

Specify a timecodes file which should be used to interpret the framerate of the input video. The timecode file can be in either v1 or v2 format which are described in the mkvmerge documentation.
See Also: tcfile-out, force-cfr, fps

tcfile-out

Output a timecode file (v2 format) based on the input timestamps. For use when you're encoding a VFR input video and want to dump the timecodes. For details on the file format, see tcfile-in.

timebase

Default: Not Set
Allows you to set a custom timebase.
The numerator is 'seconds', and the denominator is 'ticks'. Means how many seconds one tick takes.
  • If passed a rational, it will set the numerator and denominator accordingly.
  • If passed an integer, and an input timecodes file is set via tcfile-in, it will use the value passed as the numerator, and generate the denominator accordingly.
  • If passed an integer, and no input timecodes file is set, it will use the value passed as the denominator and generate the 'ticks per frame' from the input video.
Not compatible with --force-cfr mode.
Recommendation: Default

dts-compress

Default: Not Set
A hack, implemented for FLV and MP4 containers only, that can work around buggy decoders that expect all DTSs to be positive. As per the commit message for this change, use at your own risk.
Note: DTS refers to Decode TimeStamp. Each frame is allocated a DTS that reflects its position in the 'coded order' of the stream, as opposed to the 'display order' of the stream, which is specified by the Presentation TimeStamp. The order frames are stored in the stream is different to the order they are displayed due to compression techniques such as B-frames, which result in frames requiring data from frames that will be displayed after.

Filtering

video-filter

The x264 filtering system is used to process the input video before encoding. Multiple filters can also be applied sequentially to the input video.
The basic syntax to apply a filter is this:
--video-filter 
You can apply multiple filters sequentially by delimiting them with a /:
--video-filter /
You can 'chain' as many filter operations as you like together.
The available filters are:

crop

Syntax: crop:left,top,right,bottom
Remove pixels from the edges of the frame.
  • You must crop height in multiples of 4 when using yv12i, i420i, or nv12i format video input
  • You must crop height in multiples of 2 when using yv12p, i420p, nv12p, or any other interlaced format video input not specified above.
  • You must crop width in multiples of 2 when using i420, i422, yv12, yv16, nv12, or nv16 format video input.

resize

Syntax: resize:[width,height][,sar][,fittobox][,csp][,method]
Resizes frames and/or converts frames between different colorspaces. Requires x264 to be compiled with libswscale.
There are a few possible modes on how to resize frames:
  • Resolution only: Resizes frames to the specified resolution and changes the SAR to avoid stretching.
  • SAR only: Sets the SAR and resizes frames to a new resolution to avoid stretching.
  • Resolution + SAR: Resizes frames to the specified resolution and sets SAR to the specified value, potentially allowing stretching.
  • Fittobox: Resizes frames based on the specified constraint mode, adapting the resolution to have a resultant SAR of 1:1
  • width: Resize frames to fit within the specified width constraint
  • height: Resize frames to fit within the specified height constraint
  • both: Resize frames to fit within the specified box constraint
  • Fittobox + SAR: Same as regular Fittobox mode except the resultant frames have the specified SAR, shrinking the video to where the anamorphic video fits within the specified constraint.
Options that are independent of the resizing mode are
  • csp: simultaneously converting frames to the specified colorspace. The valid list of colorspaces are displayed in x264 --fullhelp
  • method (Default bicubic): when resizing frames, use the specified resizer method
fastbilinear, bilinear, bicubic, experimental, point, area, bicublin, gauss, sinc, lanczos, spline
Example:
resize:width=1280,height=720,method=spline

select_every

Syntax: select_every:step,offset1[,offset2,...]
"Select" only a subset of input frames to encode, dropping the rest. Every step frames, take only the frames specified with an offset. For example: To encode every second frame:
select_every:2,1
To drop every third frame:
select_every:3,0,1
You can see more examples at the Avisynth wiki (which has an identical filter).

See Also

http://mewiki.project357.com/wiki/X264_Settings

[Encoding] FFmpeg and x264 Encoding Guide

FFmpeg and x264 Encoding Guide

x264 is a H.264/MPEG-4 AVC encoder. The goal of this guide is to inform new users how to create a high-quality H.264 video.
There are two rate control modes that are usually suggested for general use: Constant Rate Factor (CRF) or Two-Pass ABR. The rate control is a method that will decide how many bits will be used for each frame. This will determine the file size and also how quality is distributed.
If you need help compiling and installing libx264 see one of our FFmpeg and x264 compiling guides.

Constant Rate Factor (CRF)

This method allows the encoder to attempt to achieve a certain output quality for the whole file when output file size is of less importance. This provides maximum compression efficiency with a single pass. Each frame gets the bitrate it needs to keep the requested quality level. The downside is that you can't tell it to get a specific filesize or not go over a specific size or bitrate.

1. Choose a CRF value

The range of the quantizer scale is 0-51: where 0 is lossless, 23 is default, and 51 is worst possible. A lower value is a higher quality and a subjectively sane range is 18-28. Consider 18 to be visually lossless or nearly so: it should look the same or nearly the same as the input but it isn't technically lossless.
The range is exponential, so increasing the CRF value +6 is roughly half the bitrate while -6 is roughly twice the bitrate. General usage is to choose the highest CRF value that still provides an acceptable quality. If the output looks good, then try a higher value and if it looks bad then choose a lower value.
Note: The CRF quantizer scale mentioned on this page only applies to 8-bit x264 (10-bit x264 quantizer scale is 0-63). You can see what you are using with x264 --help listed under Output bit depth. 8-bit is more common among distributors.

2. Choose a preset

A preset is a collection of options that will provide a certain encoding speed to compression ratio. A slower preset will provide better compression (compression is quality per filesize). This means that, for example, if you target a certain file size or constant bit rate, you will achieve better quality with a slower preset. Similarly, for constant quality encoding, you will simply save bitrate by choosing a slower preset.
The general guideline is to use the slowest preset that you have patience for. Current presets in descending order of speed are: ultrafast,superfast, veryfast, faster, fast, medium, slow, slower, veryslow, placebo. The default preset is medium. Ignore placebo as it is not useful (see FAQ). You can see a list of current presets with -preset help, and what settings they apply with x264 --fullhelp.
You can optionally use -tune to change settings based upon the specifics of your input. Current tunings include: film, animation, grain, stillimage, psnr, ssim, fastdecode, zerolatency. For example, if your input is animation then use the animation tuning, or if you want to preserve grain then use the grain tuning. If you are unsure of what to use or your input does not match any of tunings then omit the -tune option. You can see a list of current tunings with -tune help, and what settings they apply with x264 --fullhelp.
Another optional setting is -profile:v which will limit the output to a specific H.264 profile. This can generally be omitted unless the target device only supports a certain profile (see Compatibility). Current profiles include: baseline, main, high, high10, high422, high444. Note that usage of -profile:v is incompatible with lossless encoding.
As a shortcut, you can also list all possible internal presets/tunes for FFmpeg by specifying no preset or tune option at all:
ffmpeg -y -i input -c:v libx264 -preset -tune -f mp4 /dev/null
Note: Windows users should use NUL instead of /dev/null.

3. Use your settings

Once you've chosen your settings apply them for the rest of your videos if you are encoding more. This will ensure that they will all have similar quality.

CRF Example

ffmpeg -i input -c:v libx264 -preset slow -crf 22 -c:a copy output.mkv
Note that in this example the audio stream of the input file is simply stream copied over to the output and not re-encoded.

Two-Pass

This method is generally used if you are targeting a specific output file size and output quality from frame to frame is of less importance. This is best explained with an example. Your video is 10 minutes (600 seconds) long and an output of 50 MB is desired. Since bitrate = file size / duration:
(50 MB * 8192 [converts MB to kilobits]) / 600 seconds = ~683 kilobits/s total bitrate
683k - 128k (desired audio bitrate) = 555k video bitrate

Two-Pass Example

ffmpeg -y -i input -c:v libx264 -preset medium -b:v 555k -pass 1 -an -f mp4 /dev/null && \
ffmpeg -i input -c:v libx264 -preset medium -b:v 555k -pass 2 -c:a libfdk_aac -b:a 128k output.mp4
Note: Windows users should use NUL instead of /dev/null.
As with CRF, choose the slowest preset you can tolerate.
Also see  Making a high quality MPEG-4 ("DivX") rip of a DVD movie. It is an MEncoder guide, but it will give you an insight about how important it is to use two-pass when you want to efficiently use every bit when you're constrained with storage space.

Lossless H.264

You can use -qp 0 or -crf 0 to encode a lossless output. Use of -qp is recommended over -crf for lossless because 8-bit and 10-bit x264 use different -crf values for lossless. Two useful presets for this are ultrafast or veryslow since either a fast encoding speed or best compression are usually the most important factors. Most non-FFmpeg based players will not be able to decode lossless (but YouTube can), so if compatibility is an issue you should not use lossless.

Lossless Example (fastest encoding)

ffmpeg -i input -c:v libx264 -preset ultrafast -qp 0 output.mkv

Lossless Example (best compression)

ffmpeg -i input -c:v libx264 -preset veryslow -qp 0 output.mkv

Overwriting default preset settings

You can overwrite default preset settings with the x264opts option, the x264-params option, or by using the libx264 private options (see ffmpeg -h encoder=libx264). This is not recommended unless you know what you are doing. The presets were created by the x264 developers and tweaking values to get a better output is usually a waste of time.
Example:
ffmpeg -i input -c:v libx264 -preset slow -crf 22 -x264opts keyint=123:min-keyint=20 -c:a copy output.mkv

Additional Information & Tips

ABR (Average Bit Rate)

ffmpeg -i input -c:v libx264 -b:v 1000k output.mp4
This provides something of a "running average" target, with the end goal that the final file match this number "overall on average" (so basically, if it gets a lot of black frames, which cost very little, it will encode them with less than the requested bitrate, but then the next few seconds of (non-black) frames it will encode at very high quality, to bring the average back in line). Using 2-pass can help this method to be more effective. You can also use this in combination with a "max bit rate" setting in order to prevent some of the swings.

CBR (Constant Bit Rate)

There is no native CBR mode, but you can "simulate" a constant bit rate setting by tuning the parameters of ABR:
ffmpeg -i input -c:v libx264 -b:v 4000k -minrate 4000k -maxrate 4000k -bufsize 1835k out.m2v
In the above example, -bufsize is the "rate control buffer" so it will enforce your requested "average" (4000k in this case) across each 1835k worth of video. So basically it is assumed that the receiver/end player will buffer that much data so it's ok to fluctuate within that much.
Of course, if it's all just empty/black frames then it will still serve less than that many bits/s but it will raise the quality level as much as it can, up to the crf level.

CRF with maximum bit rate

You can also also use a crf with a maximum bit rate by specifying both crf *and* maxrate settings, like
ffmpeg -i input -c:v libx264 -crf 20 -maxrate 400k -bufsize 1835k output.mp4
This will effectively "target" crf 20, but if the output exceeds 400kb/s, it will degrade to something less than crf 20 in that case.

Low Latency

libx264 offers a -tune zerolatency option. See the StreamingGuide.

Compatibility

All devices

If you want your videos to have highest compatibility with target devices (older iOS versions or all Android devices):
-profile:v baseline -level 3.0
This disables some advanced features but provides for better compatibility. Typically you may not need this setting (and therefore avoid using -profile:v and -level), but if you do use this setting it may increase the bit rate quite a bit compared to what is needed to achieve the same quality in higher profiles.

iOS

iOS Compatability ( source)
Profile Level Devices Options
Baseline 3.0 All devices -profile:v baseline -level 3.0
Baseline 3.1 iPhone 3G and later, iPod touch 2nd generation and later -profile:v baseline -level 3.1
Main 3.1 iPad (all versions), Apple TV 2 and later, iPhone 4 and later -profile:v main -level 3.1
Main 4.0 Apple TV 3 and later, iPad 2 and later, iPhone 4S and later -profile:v main -level 4.0
High 4.0 Apple TV 3 and later, iPad 2 and later, iPhone 4S and later -profile:v high -level 4.0
High 4.1 iPad 2 and later and iPhone 4S and later -profile:v high -level 4.1
This table does not include any additional restrictions which may be present.

Apple Quicktime

Apple QuickTime only supports YUV planar color space with 4:2:0 chroma subsampling (use -pix_fmt yuv420p) for H.264 video. For information on additional restrictions see  QuickTime-compatible Encoding.

Blu-ray

See  Authoring a professional Blu-ray Disc with x264.

Pre-testing your settings

Encode a random section instead of the whole video with the -ss and -t options to quickly get a general idea of what the output will look like.
  • -ss: Offset time from beginning. Value can be in seconds or HH:MM:SS format.
  • -t: Output duration. Value can be in seconds or HH:MM:SS format.

faststart for web video

You can add -movflags +faststart as an output option if your videos are going to be viewed in a browser. This will move some information to the beginning of your file and allow the video to begin playing before it is completely downloaded by the viewer. It is not required if you are going to use a video service such as YouTube.

FAQ

Will two-pass provide a better quality than CRF?

 No, though it does allow you to target a file size more accurately.

Why is placebo a waste of time?

It helps at most ~1% compared to the veryslow preset at the cost of a much higher encoding time. It's diminishing returns: veryslow helps about 3% compared to the slower preset, slower helps about 5% compared to the slow preset, and slow helps about 5-10% compared to the medium preset.

Why doesn't my lossless output look lossless?

Blame the RGB to YUV color space conversion. If you convert to yuv444 it should still be lossless (which is the default now).

Will a graphics card make x264 encode faster?

Not necessarily.  x264 supports OpenCL for some lookahead operations. There are also some proprietary encoders that utilize the GPU, but that does not mean they are well optimized, though encoding time may be faster; and they might be  worse than vanilla x264, and possibly slower. Regardless, FFmpeg today doesn't support any means of GPU encoding, outside of libx264.

Encoding for dumb players

You may need to use -pix_fmt yuv420p for your output to work in QuickTime and most other players. These players only supports the YUV planar color space with 4:2:0 chroma subsampling for H.264 video. Otherwise, depending on your source, ffmpeg may output to a pixel format that may be incompatible with these players.

http://trac.ffmpeg.org/wiki/x264EncodingGuide

[Encoding] Blu-ray Encoding Tutorials


Lesson 1 - Prepare Source Video

In the first lesson you will learn how to analyze your source video, ensuring AviSynth will be able to decode it properly, and also formulate a plan for making any changes which may be required. In most cases this will also involve creating an index, which is a sort of map to the contents of a video.

Lesson 2 - Create AviSynth Script

In the second lesson you will learn to use MeGUI's AVS Script Creator tool to provide instructions for loading your source video and performing any required processing. This may include resizing video to the desired resolution and either deinterlacing or bobbing interlaced video to make it progressive.

Lesson 3 - Create Chapter File and Calculate Bitrate

In lesson three you wil learn how to create a file specifying chapter points and calculate the correct bitrate for your encoded video.

Lesson 4 - Encode Video

In lesson four you will learn about the proper settings for encoding your video.

Lesson 5 - Encode AC-3 Audio

In lesson five you will learn how to encode your audio to AC-3 format using MeGUI and either the Aften encoder or FFmpeg. When you complete this step you will have Blu-ray compliant audio files.

Lesson 6 - Advanced Bitrate Calculation

In lesson six you will learn more advanced techniques for calculating bitrate when you are authoring a Blu-ray disc from multiple video files.

Lesson 7 - Advanced Audio Processing

In this lesson you will learn how to use Audacity to combine individual audio files to produce either an uncompressed (LPCM) or Dolby Digital (AC-3) audio stream

Lesson 8 - Convert Text Subtitles To Images

In Lesson 9 you will become familiar with the process of converting subitles from the text-based SRT, SSA, and ASS formats to Blu-ray compliant SUP or BDN XML format.

Lesson 9 - Prepare A Still Menu Background

After completing Lesson 10 you should be able to create a single frame video file for use as the background for a Blu-ray still menu. You will also be able to extract a video frame as a regular still image file (such as a PNG or JPEG) and how to convert those common files into single frame, Blu-ray compliant video streams.

Lesson 10 - Make Menu Buttons With GIMP

This lesson will teach you the basics of making your own buttons for Blu-ray menus using the free image editor GIMP. It also includes tips on how to add elements necessary for a functional Blu-ray menu to a still image and assemble a mockup so you know what your menu will look like before you start the authoring process.
http://www.afterdawn.com/guides/

[Encoding], [Programming] Tutorial: Encoding an MP4 File

This tutorial shows how to use the Transcode API to encode an MP4 file, using H.264 for the video stream and AAC for the audio stream.

Headers and Library Files

Include the following header files.
#include <new>
#include
#include
#include
#include
#include


Link the following library files.
#pragma comment(lib, "mfplat")
#pragma comment(lib, "mf")
#pragma comment(lib, "mfuuid")
#pragma comment(lib, "shlwapi")


Define the Encoding Profiles

One approach to encoding is to define a list of target encoding profiles that are known in advance. For this tutorial, we take a relatively simple approach, and store a list of encoding formats for H.264 video and AAC audio.
For H.264, the most important format attributes are the H.264 profile, the frame rate, the frame size, and the encoded bit rate. The following array contains a list of H.264 encoding formats.
struct H264ProfileInfo
{
UINT32 profile;
MFRatio fps;
MFRatio frame_size;
UINT32 bitrate;
};

H264ProfileInfo h264_profiles[] =
{
{ eAVEncH264VProfile_Base, { 15, 1 }, { 176, 144 }, 128000 },
{ eAVEncH264VProfile_Base, { 15, 1 }, { 352, 288 }, 384000 },
{ eAVEncH264VProfile_Base, { 30, 1 }, { 352, 288 }, 384000 },
{ eAVEncH264VProfile_Base, { 29970, 1000 }, { 320, 240 }, 528560 },
{ eAVEncH264VProfile_Base, { 15, 1 }, { 720, 576 }, 4000000 },
{ eAVEncH264VProfile_Main, { 25, 1 }, { 720, 576 }, 10000000 },
{ eAVEncH264VProfile_Main, { 30, 1 }, { 352, 288 }, 10000000 },
};


H.264 profiles are specified using the eAVEncH264VProfile enumeration. You could also specify the H.264 level, but the Microsoft Media Foundation H.264 Video Encoder can derive the proper level for a given video stream, so it is recommended not to override the encoder's selected level. For interlaced content, you would also specify the interlace mode (see Video Interlacing).
For AAC audio, the most important format attributes are the audio sample rate, the number of channels, the number of bits per sample, and the encoded bit rate. Optionally, you can set the AAC audio profile level indication. For more information, see AAC Encoder. The following array contains a list of AAC encoding formats.
struct AACProfileInfo
{
UINT32 samplesPerSec;
UINT32 numChannels;
UINT32 bitsPerSample;
UINT32 bytesPerSec;
UINT32 aacProfile;
};

AACProfileInfo aac_profiles[] =
{
{ 96000, 2, 16, 24000, 0x29},
{ 48000, 2, 16, 24000, 0x29},
{ 44100, 2, 16, 16000, 0x29},
{ 44100, 2, 16, 12000, 0x29},
};


Note  The H264ProfileInfo and AACProfileInfo structures defined here are not part of the Media Foundation API.

Write the wmain Function

The following code shows the entry point for the console application.
int video_profile = 0;
int audio_profile = 0;

int wmain(int argc, wchar_t* argv[])
{
HeapSetInformation(NULL, HeapEnableTerminationOnCorruption, NULL, 0);

if (argc < 3 || argc > 5)
{
std::cout << "Usage:" << std::endl;
std::cout << "input output [ audio_profile video_profile ]" << std::endl;
return 1;
}

if (argc > 3)
{
audio_profile = _wtoi(argv[3]);
}
if (argc > 4)
{
video_profile = _wtoi(argv[4]);
}

HRESULT hr = CoInitializeEx(NULL, COINIT_APARTMENTTHREADED);
if (SUCCEEDED(hr))
{
hr = MFStartup(MF_VERSION);
if (SUCCEEDED(hr))
{
hr = EncodeFile(argv[1], argv[2]);
MFShutdown();
}
CoUninitialize();
}

if (SUCCEEDED(hr))
{
std::cout << "Done." << std::endl;
}
else
{
std::cout << "Error: " << std::hex << hr << std::endl;
}

return 0;
}


The wmain function does the following:
  1. Calls the CoInitializeEx function to initialize the COM library.
  2. Calls the MFStartup function to initialize Media Foundation.
  3. Calls the application-defined EncodeFile function. This function transcodes the input file to the output file, and is shown in the next section.
  4. Calls the MFShutdown function to shut down Media Foundation.
  5. Call the CoUninitialize function to uninitialize the COM library.

Encode the File

The following code shows EncodeFile function, which performs the transcoding. This function consists mostly of calls to other application-defined functions, which are shown later in this topic.
HRESULT EncodeFile(PCWSTR pszInput, PCWSTR pszOutput)
{
IMFTranscodeProfile *pProfile = NULL;
IMFMediaSource *pSource = NULL;
IMFTopology *pTopology = NULL;
CSession *pSession = NULL;

MFTIME duration = 0;

HRESULT hr = CreateMediaSource(pszInput, &pSource);
if (FAILED(hr))
{
goto done;
}

hr = GetSourceDuration(pSource, &duration);
if (FAILED(hr))
{
goto done;
}

hr = CreateTranscodeProfile(&pProfile);
if (FAILED(hr))
{
goto done;
}

hr = MFCreateTranscodeTopology(pSource, pszOutput, pProfile, &pTopology);
if (FAILED(hr))
{
goto done;
}

hr = CSession::Create(&pSession);
if (FAILED(hr))
{
goto done;
}

hr = pSession->StartEncodingSession(pTopology);
if (FAILED(hr))
{
goto done;
}

hr = RunEncodingSession(pSession, duration);

done:
if (pSource)
{
pSource->Shutdown();
}

SafeRelease(&pSession);
SafeRelease(&pProfile);
SafeRelease(&pSource);
SafeRelease(&pTopology);
return hr;
}


The EncodeFile function performs the following steps.
  1. Creates a media source for the input file, using the URL or file path of the input file. (See Create the Media Source.)
  2. Gets the duration of the input file. (See Get the Source Duration.)
  3. Create the transcode profile. (See Create the Transcode Profile.)
  4. Call MFCreateTranscodeTopology to create the partial transcode topology.
  5. Create a helper object that manages the Media Session. (See Media Session Helper).
  6. Run the encoding session and wait for it to complete. (See Run the Encoding Session.)
  7. Call IMFMediaSource::Shutdown to shut down the media source.
  8. Release interface pointers. This code uses the SafeRelease function to release interface pointers. Another option is to use a COM smart pointer class, such as CComPtr.

Create the Media Source

The media source is the object that reads and parses the input file. To create the media source, pass the URL of the input file to the Source Resolver. The following code shows how to do this.
HRESULT CreateMediaSource(PCWSTR pszURL, IMFMediaSource **ppSource)
{
MF_OBJECT_TYPE ObjectType = MF_OBJECT_INVALID;

IMFSourceResolver* pResolver = NULL;
IUnknown* pSource = NULL;

// Create the source resolver.
HRESULT hr = MFCreateSourceResolver(&pResolver);
if (FAILED(hr))
{
goto done;
}

// Use the source resolver to create the media source
hr = pResolver->CreateObjectFromURL(pszURL, MF_RESOLUTION_MEDIASOURCE,
NULL, &ObjectType, &pSource);
if (FAILED(hr))
{
goto done;
}

// Get the IMFMediaSource interface from the media source.
hr = pSource->QueryInterface(IID_PPV_ARGS(ppSource));

done:
SafeRelease(&pResolver);
SafeRelease(&pSource);
return hr;
}


For more information, see Using the Source Resolver.

Get the Source Duration

Although not required, it is useful to query the media source for the duration of the input file. This value can be used to track the encoding progress. The duration is stored in the MF_PD_DURATION attribute of the presentation descriptor. Get the presentation descriptor by calling IMFMediaSource::CreatePresentationDescriptor.
HRESULT GetSourceDuration(IMFMediaSource *pSource, MFTIME *pDuration)
{
*pDuration = 0;

IMFPresentationDescriptor *pPD = NULL;

HRESULT hr = pSource->CreatePresentationDescriptor(&pPD);
if (SUCCEEDED(hr))
{
hr = pPD->GetUINT64(MF_PD_DURATION, (UINT64*)pDuration);
pPD->Release();
}
return hr;
}


Create the Transcode Profile

The transcode profile describes the encoding parameters. For more information about creating a transcode profile, see Using the Transcode API. To create the profile, perform the following steps.
  1. Call MFCreateTranscodeProfile to create the empty profile.
  2. Create a media type for the AAC audio stream. Add it to the profile by calling IMFTranscodeProfile::SetAudioAttributes.
  3. Create a media type for the H.264 video stream. Add it to the profile by calling IMFTranscodeProfile::SetVideoAttributes.
  4. Call MFCreateAttributes to create an attribute store for the container-level attributes.
  5. Set the MF_TRANSCODE_CONTAINERTYPE attribute. This is the only required container-level attribute. For MP4 file output, set this attribute to MFTranscodeContainerType_MPEG4.
  6. Call IMFTranscodeProfile::SetContainerAttributes to set the container-level attributes.
The following code shows these steps.
HRESULT CreateTranscodeProfile(IMFTranscodeProfile **ppProfile)
{
IMFTranscodeProfile *pProfile = NULL;
IMFAttributes *pAudio = NULL;
IMFAttributes *pVideo = NULL;
IMFAttributes *pContainer = NULL;

HRESULT hr = MFCreateTranscodeProfile(&pProfile);
if (FAILED(hr))
{
goto done;
}

// Audio attributes.
hr = CreateAACProfile(audio_profile, &pAudio);
if (FAILED(hr))
{
goto done;
}

hr = pProfile->SetAudioAttributes(pAudio);
if (FAILED(hr))
{
goto done;
}

// Video attributes.
hr = CreateH264Profile(video_profile, &pVideo);
if (FAILED(hr))
{
goto done;
}

hr = pProfile->SetVideoAttributes(pVideo);
if (FAILED(hr))
{
goto done;
}

// Container attributes.
hr = MFCreateAttributes(&pContainer, 1);
if (FAILED(hr))
{
goto done;
}

hr = pContainer->SetGUID(MF_TRANSCODE_CONTAINERTYPE, MFTranscodeContainerType_MPEG4);
if (FAILED(hr))
{
goto done;
}

hr = pProfile->SetContainerAttributes(pContainer);
if (FAILED(hr))
{
goto done;
}

*ppProfile = pProfile;
(*ppProfile)->AddRef();

done:
SafeRelease(&pProfile);
SafeRelease(&pAudio);
SafeRelease(&pVideo);
SafeRelease(&pContainer);
return hr;
}


To specify the attributes for the H.264 video stream, create an attribute store and set the following attributes:
AttributeDesription
MF_MT_SUBTYPESet to MFVideoFormat_H264.
MF_MT_MPEG2_PROFILEH.264 profile.
MF_MT_FRAME_SIZEFrame size.
MF_MT_FRAME_RATEFrame rate.
MF_MT_AVG_BITRATEEncoded bit rate.

To specify the attributes for the AAC audio stream, create an attribute store and set the following attributes:
AttributeDesription
MF_MT_SUBTYPESet to MFAudioFormat_AAC
MF_MT_AUDIO_SAMPLES_PER_SECONDAudio sample rate.
MF_MT_AUDIO_BITS_PER_SAMPLEBits per audio sample.
MF_MT_AUDIO_NUM_CHANNELSNumber of audio channels.
MF_MT_AUDIO_AVG_BYTES_PER_SECONDEncoded bit rate.
MF_MT_AUDIO_BLOCK_ALIGNMENTSet to 1.
MF_MT_AAC_AUDIO_PROFILE_LEVEL_INDICATIONAAC profile level indication (optional).

The following code creates the video stream attributes.
HRESULT CreateH264Profile(DWORD index, IMFAttributes **ppAttributes)
{
if (index >= ARRAYSIZE(h264_profiles))
{
return E_INVALIDARG;
}

IMFAttributes *pAttributes = NULL;

const H264ProfileInfo& profile = h264_profiles[index];

HRESULT hr = MFCreateAttributes(&pAttributes, 5);
if (SUCCEEDED(hr))
{
hr = pAttributes->SetGUID(MF_MT_SUBTYPE, MFVideoFormat_H264);
}
if (SUCCEEDED(hr))
{
hr = pAttributes->SetUINT32(MF_MT_MPEG2_PROFILE, profile.profile);
}
if (SUCCEEDED(hr))
{
hr = MFSetAttributeSize(
pAttributes, MF_MT_FRAME_SIZE,
profile.frame_size.Numerator, profile.frame_size.Numerator);
}
if (SUCCEEDED(hr))
{
hr = MFSetAttributeRatio(
pAttributes, MF_MT_FRAME_RATE,
profile.fps.Numerator, profile.fps.Denominator);
}
if (SUCCEEDED(hr))
{
hr = pAttributes->SetUINT32(MF_MT_AVG_BITRATE, profile.bitrate);
}
if (SUCCEEDED(hr))
{
*ppAttributes = pAttributes;
(*ppAttributes)->AddRef();
}
SafeRelease(&pAttributes);
return hr;
}


The following code creates the audio stream attributes.
HRESULT CreateAACProfile(DWORD index, IMFAttributes **ppAttributes)
{
if (index >= ARRAYSIZE(h264_profiles))
{
return E_INVALIDARG;
}

const AACProfileInfo& profile = aac_profiles[index];

IMFAttributes *pAttributes = NULL;

HRESULT hr = MFCreateAttributes(&pAttributes, 7);
if (SUCCEEDED(hr))
{
hr = pAttributes->SetGUID(MF_MT_SUBTYPE, MFAudioFormat_AAC);
}
if (SUCCEEDED(hr))
{
hr = pAttributes->SetUINT32(
MF_MT_AUDIO_BITS_PER_SAMPLE, profile.bitsPerSample);
}
if (SUCCEEDED(hr))
{
hr = pAttributes->SetUINT32(
MF_MT_AUDIO_SAMPLES_PER_SECOND, profile.samplesPerSec);
}
if (SUCCEEDED(hr))
{
hr = pAttributes->SetUINT32(
MF_MT_AUDIO_NUM_CHANNELS, profile.numChannels);
}
if (SUCCEEDED(hr))
{
hr = pAttributes->SetUINT32(
MF_MT_AUDIO_AVG_BYTES_PER_SECOND, profile.bytesPerSec);
}
if (SUCCEEDED(hr))
{
hr = pAttributes->SetUINT32(MF_MT_AUDIO_BLOCK_ALIGNMENT, 1);
}
if (SUCCEEDED(hr))
{
hr = pAttributes->SetUINT32(
MF_MT_AAC_AUDIO_PROFILE_LEVEL_INDICATION, profile.aacProfile);
}
if (SUCCEEDED(hr))
{
*ppAttributes = pAttributes;
(*ppAttributes)->AddRef();
}
SafeRelease(&pAttributes);
return hr;
}


Note that the transcode API does not require a true media type, although it uses media-type attributes. In particular, the MF_MT_MAJOR_TYPE attribute it not required, because the SetVideoAttributes and SetAudioAttributes methods imply the major type. However, it also valid to pass an actual media type to these methods. (The IMFMediaType interface inherits IMFAttributes.)

Run the Encoding Session

The following code runs the encoding session. It uses the Media Session helper class, which is shown in the next section.
HRESULT RunEncodingSession(CSession *pSession, MFTIME duration)
{
const DWORD WAIT_PERIOD = 500;
const int UPDATE_INCR = 5;

HRESULT hr = S_OK;
MFTIME pos;
LONGLONG prev = 0;
while (1)
{
hr = pSession->Wait(WAIT_PERIOD);
if (hr == E_PENDING)
{
hr = pSession->GetEncodingPosition(&pos);

LONGLONG percent = (100 * pos) / duration ;
if (percent >= prev + UPDATE_INCR)
{
std::cout << percent << "% .. ";
prev = percent;
}
}
else
{
std::cout << std::endl;
break;
}
}
return hr;
}


Media Session Helper

The Media Session is described more fully in the Media Foundation Architecture section of this documentation. The Media Session uses an asynchronous event model. In a GUI application, you should respond to session events without blocking the UI thread to wait for the next event. The tutorial How to Play Unprotected Media Files shows how to do this in a playback application. For encoding, the principle is the same, but fewer events are relevant:
EventDesription
MESessionEndedRaised when the encoding is complete.
MESessionClosedRaised when the IMFMediaSession::Close method completes. After this event is raised, it is safe to shut down the Media Session.

For a console application, it is reasonable to block and wait for events. Depending on the source file and the encoding settings, it might take awhile to complete the encoding. You can get progress updates as follows:
  1. Call IMFMediaSession::GetClock to get the presentation clock.
  2. Query the clock for the IMFPresentationClock interface.
  3. Call IMFPresentationClock::GetTime to get the current position.
  4. The position is given in units of time. To get the percentage completed, use the value (100 * position) / duration.
Here is the declaration of the CSession class.
class CSession  : public IMFAsyncCallback 
{
public:
static HRESULT Create(CSession **ppSession);

// IUnknown methods
STDMETHODIMP QueryInterface(REFIID riid, void** ppv);
STDMETHODIMP_(ULONG) AddRef();
STDMETHODIMP_(ULONG) Release();

// IMFAsyncCallback methods
STDMETHODIMP GetParameters(DWORD* pdwFlags, DWORD* pdwQueue)
{
// Implementation of this method is optional.
return E_NOTIMPL;
}
STDMETHODIMP Invoke(IMFAsyncResult *pResult);

// Other methods
HRESULT StartEncodingSession(IMFTopology *pTopology);
HRESULT GetEncodingPosition(MFTIME *pTime);
HRESULT Wait(DWORD dwMsec);

private:
CSession() : m_cRef(1), m_pSession(NULL), m_pClock(NULL), m_hrStatus(S_OK), m_hWaitEvent(NULL)
{
}
virtual ~CSession()
{
if (m_pSession)
{
m_pSession->Shutdown();
}

SafeRelease(&m_pClock);
SafeRelease(&m_pSession);
CloseHandle(m_hWaitEvent);
}

HRESULT Initialize();

private:
IMFMediaSession *m_pSession;
IMFPresentationClock *m_pClock;
HRESULT m_hrStatus;
HANDLE m_hWaitEvent;
long m_cRef;
};


The following code shows the complete implementation of the CSession class.
HRESULT CSession::Create(CSession **ppSession)
{
*ppSession = NULL;

CSession *pSession = new (std::nothrow) CSession();
if (pSession == NULL)
{
return E_OUTOFMEMORY;
}

HRESULT hr = pSession->Initialize();
if (FAILED(hr))
{
pSession->Release();
return hr;
}
*ppSession = pSession;
return S_OK;
}

STDMETHODIMP CSession::QueryInterface(REFIID riid, void** ppv)
{
static const QITAB qit[] =
{
QITABENT(CSession, IMFAsyncCallback),
{ 0 }
};
return QISearch(this, qit, riid, ppv);
}

STDMETHODIMP_(ULONG) CSession::AddRef()
{
return InterlockedIncrement(&m_cRef);
}

STDMETHODIMP_(ULONG) CSession::Release()
{
long cRef = InterlockedDecrement(&m_cRef);
if (cRef == 0)
{
delete this;
}
return cRef;
}

HRESULT CSession::Initialize()
{
IMFClock *pClock = NULL;

HRESULT hr = MFCreateMediaSession(NULL, &m_pSession);
if (FAILED(hr))
{
goto done;
}

hr = m_pSession->GetClock(&pClock);
if (FAILED(hr))
{
goto done;
}

hr = pClock->QueryInterface(IID_PPV_ARGS(&m_pClock));
if (FAILED(hr))
{
goto done;
}

hr = m_pSession->BeginGetEvent(this, NULL);
if (FAILED(hr))
{
goto done;
}

m_hWaitEvent = CreateEvent(NULL, FALSE, FALSE, NULL);
if (m_hWaitEvent == NULL)
{
hr = HRESULT_FROM_WIN32(GetLastError());
}
done:
SafeRelease(&pClock);
return hr;
}

// Implements IMFAsyncCallback::Invoke
STDMETHODIMP CSession::Invoke(IMFAsyncResult *pResult)
{
IMFMediaEvent* pEvent = NULL;
MediaEventType meType = MEUnknown;
HRESULT hrStatus = S_OK;

HRESULT hr = m_pSession->EndGetEvent(pResult, &pEvent);
if (FAILED(hr))
{
goto done;
}

hr = pEvent->GetType(&meType);
if (FAILED(hr))
{
goto done;
}

hr = pEvent->GetStatus(&hrStatus);
if (FAILED(hr))
{
goto done;
}

if (FAILED(hrStatus))
{
hr = hrStatus;
goto done;
}

switch (meType)
{
case MESessionEnded:
hr = m_pSession->Close();
if (FAILED(hr))
{
goto done;
}
break;

case MESessionClosed:
SetEvent(m_hWaitEvent);
break;
}

if (meType != MESessionClosed)
{
hr = m_pSession->BeginGetEvent(this, NULL);
}

done:
if (FAILED(hr))
{
m_hrStatus = hr;
m_pSession->Close();
}

SafeRelease(&pEvent);
return hr;
}

HRESULT CSession::StartEncodingSession(IMFTopology *pTopology)
{
HRESULT hr = m_pSession->SetTopology(0, pTopology);
if (SUCCEEDED(hr))
{
PROPVARIANT varStart;
PropVariantClear(&varStart);
hr = m_pSession->Start(&GUID_NULL, &varStart);
}
return hr;
}

HRESULT CSession::GetEncodingPosition(MFTIME *pTime)
{
return m_pClock->GetTime(pTime);
}

HRESULT CSession::Wait(DWORD dwMsec)
{
HRESULT hr = S_OK;

DWORD dwTimeoutStatus = WaitForSingleObject(m_hWaitEvent, dwMsec);
if (dwTimeoutStatus != WAIT_OBJECT_0)
{
hr = E_PENDING;
}
else
{
hr = m_hrStatus;
}
return hr;
}


Related topics

AAC Encoder
H.264 Video Encoder
Media Session
Media Types
Transcode API


Send comments about this topic to Microsoft
Build date: 10/12/2013

Community Additions

ADD

Minor correction in Tutorial example - Frame size incorrectly set

In CreateH264Profile function, the Frame size is incorrectly set, resulting in square video frames. Instead of :-


hr = MFSetAttributeSize( pAttributes, MF_MT_FRAME_SIZE, profile.frame_size.Numerator, profile.frame_size.Numerator);



It should be:-




hr = MFSetAttributeSize( pAttributes, MF_MT_FRAME_SIZE,


profile.frame_size.Numerator, profile.frame_size.Denominator);



http://msdn.microsoft.com/en-us/library/windows/desktop/ff819476%28v=vs.85%29.aspx

Labels

[Android] [Anti Virus] [Audio] [Design] [Encoding] [Excel] [Guitar Pro] [HD phim] [Hooking] [iOS] [mySQL] [PHP] [Pic] [Programming] [Repair Disk] [Security] [Subtitle] [Sync Sub] [System Info] [Using soft] [Using Tools] [Video] [Word] ẢNH ẢNH BẠN BÈ ẢNH CHỤP Ảnh Của Tôi ảnh đẹp Ảnh động Ảnh động đẹp ẢNH GH.ĐỘNG SONCA ẢNH GH.NG ẢNH GH.NG VÀ CẢNH ẢNH GIA ĐÌNH Ảnh hoa đẹp Ảnh trang trí 3 Ảnh trang trí 4 Bài hát yêu thích BẠN ĐỒNG MÔN Cách cắm hoa Chăm sóc hoa CODE ĐÀN NGỰA CHẠY DƯỚI CHÂN TRANG-CHUỘT CHẠY BLOGSPOT ĐỊA CHỈ TRANG GHÉP ẢNH GH.NG GHÉP ẢNH SC -BẠN BÈ-GIA ĐÌNH 13 (TRANG http://www.loonapix.com) Happy New Year Hạt giống hoa Hoa anh đào Hoa anh thảo Hoa Baby Hoa Bằng lăng Hoa bất tử Hoa Bleeding heart Hoa Bồ Công Anh Hoa cải Hoa Cát Tường Hoa Cẩm Chướng Hoa cẩm tú Hoa cây roi Hoa cúc Hoa cưới Hoa dạ yến thảo Hoa dâm bụt Hoa đào Hoa đỗ quyên Hoa đồng tiền Hoa gạo Hoa giấy Hoa hải đường Hoa hồng Hoa hướng dương Hoa kim châm Hoa kim cương Hoa Lan Hoa lê Hoa lily hoa loa kèn Hoa lưu ly Hoa mai Hoa mẫu đơn Hoa mười giờ Hoa ngọc lan Hoa ngũ sắc Hoa oải hương Hoa phượng Hoa Sen Hoa sen trắng Hoa sim Hoa sứ Hoa sử dương tử Hoa sữa Hoa Thạch Thảo Hoa thiết mộc lan Hoa thủy tiên Hoa thược dược Hoa tulip Hoa Violet Hoa xương rồng LINK TRANG GHÉP ẢNH TRỰC TUYẾN VÀ CODE CHỈNH HÌNH MÙA HẠ Nhạc Không Lời nhật kí Quốc hoa Thông tin riêng blog Thơ của tôi. Thơ hay thơ hay 2 THƠ LỤC BÁT THƠ THẤT NGÔN BÁT CÚ THỦ THUÂT BLOG THỦ THUẬT BLOG Tổng Hợp TRÁNG TẠO VIDEO TRỰC TUYẾN MIỄN PHÍ XE ĐẠP ĐIỆN Ý nghĩa các loài hoa