Using HandBrakeCLI

HandBrake's CLI is really easy to use. If you get comfortable with it, it can be a lot more efficient than the GUIs.

The Basics

First, simple input and output.

HandBrakeCLI -i source -o destination

That will encode with default values: 1000kbps ffmpeg video and 160kbps AAC audio in an .mp4 container.

Easy, right? So now you can start customizing those settings. You can pile on all sorts of things, and end up with a monster like:

HandBrakeCLI -i /Volumes/MyBook/VIDEO_TS -o /Volumes/MyBook/movie.m4v -v -P -m -E aac,ac3 -e x264
-q 0.65 -x ref=3:mixed-refs:bframes=6:b-pyramid=1:weightb=1:analyse=all:8x8dct=1:subme=7:me=umh
:merange=24:filter=-2,-2:trellis=1:no-fast-pskip=1:no-dct-decimate=1:direct=auto

For now, think about less complex stuff:

HandBrakeCLI -i VIDEO_TS -o movie.mp4 -e x264 -b 2000 -B 192

That will encode a source video located at the path VIDEO_TS to an output file called movie.mp4. It will use x264 with a bitrate of 2000 to encode the video, and encode the audio as 128kb/s AAC.

So can you start to see how this works? The most important info for HandBrakeCLI is the location of the DVD, and the location and name where you want to store the encoded video it will output. If you don't specify anything else, it uses fast, low-quality, default values. Each bit of information is preceded by a flag: -i for input, -o for output. To select an encoder, you use -e followed by the encoder name. So -e x264 uses x264 to encode the video. Video bitrate is controlled by -b, and audio bitrate is controlled by -B (yes, the option names are case-sensitive. -b is not -B and -e is not -E).

A few rudimentary hints for using the command line

  • Filepaths are important. I'm on a Mac, and my username is jon. My home directory is:
    /Users/jon/
    
    So the path to my Desktop is:
    /Users/jon/Desktop
    
    And so my Movies folder is at
    /Users/jon/Movies
    
    A common shortcut is to use a tilde (~) to represent your home directory. That means:
    ~/Movies
    
    is the same as:
    /Users/jon/Movies
    

Make sure you remember the right capitalization for everything. At the command line, HandBrakeCLI is not the same as handbrakecli. If you have to type a space in filepath, precede it with a \ backslash so the system knows what's going on.

  • You usually store GUI programs in the /Applications folder. CLI programs are usually stored in places like /usr/bin or /opt/local/bin. You can do that with HandBrake, but the easiest thing to do is just navigate to the directory that stores HandBrakeCLI. To navigate through your file system at the command line, you change directories (folders) by using the "cd" (Change Directories) command. For example, to move to my Movies folder, I would type:
    cd ~/Movies
    
    Then, tell the shell to look for the program in the current working directory. To run a command in the Terminal, you just type its name. But the shell will only look in the places where applications are usually stored (like /usr/bin/). You need to tell it to look in the current directory. To do that, precede the program name with ./ like this:
    ./HandBrakeCLI
    
    Of course, running that won't do much anything useful. If you run HandBrake without telling it what to do, it will just tell you to read the help...

Presets

HandBrake offers hard coded, factory-fresh presets that are exactly the same as the built-in presets in the MacGui. Descriptions of presets and rankings for speed, as well as a web-copy of all the presets' CLI strings are available.

To use a preset, type, for example:

./HandBrakeCLI -i /Volumes/DVD -o movie.mp4 --preset="iPhone & iPod Touch" 

So it's:

--preset="Preset Name"

Be careful -- spelling and spacing and capitalization count. Don't forget the quotation marks, either. You can override most preset settings by specifying other options on the command line. To see a list of all the preset names and settings, type:

./HandBrakeCLI --preset-list

The following presets are available:

Option by Option

To see everything HandBrakeCLI has to offer, run this:

HandBrakeCLI -h

That should produce this output:

Syntax: HandBrakeCLI [options] -i <device> -o <file>

### General Handbrake Options------------------------------------------------

    -h, --help              Print help
    -u, --update            Check for updates and exit
    -v, --verbose <#>       Be verbose (optional argument: logging level)
    -C, --cpu               Set CPU count (default: autodetected)
    -Z. --preset <string>   Use a built-in preset. Capitalization matters, and
                            if the preset name has spaces, surround it with
                            double quotation marks
    -z, --preset-list       See a list of available built-in presets

### Source Options-----------------------------------------------------------

    -i, --input <string>    Set input device
    -t, --title <number>    Select a title to encode (0 to scan only,
                            default: 1)
    -L, --longest           Select the longest title
    -c, --chapters <string> Select chapters (e.g. "1-3" for chapters
                            1 to 3, or "3" for chapter 3 only,
                            default: all chapters)

### Destination Options------------------------------------------------------

    -o, --output <string>   Set output file name
    -f, --format <string>   Set output format (avi/mp4/ogm/mkv, default:
                            autodetected from file name)
    -m, --markers           Add chapter markers (mp4 and mkv output formats only)
    -4, --large-file        Use 64-bit mp4 files that can hold more than
                            4 GB. Note: Breaks iPod, PS3 compatibility.
    -O, --optimize          Optimize mp4 files for HTTP streaming
    -I, --ipod-atom         Mark mp4 files so 5.5G iPods will accept them

### Video Options------------------------------------------------------------

    -e, --encoder <string>  Set video library encoder (ffmpeg,xvid,
                            x264,theora default: ffmpeg)
    -x, --x264opts <string> Specify advanced x264 options in the
                            same style as mencoder:
                            option1=value1:option2=value2
    -q, --quality <float>   Set video quality (0.0..1.0)
    -Q, --cqp               Use with -q for CQP instead of CRF
    -S, --size <MB>         Set target size
    -b, --vb <kb/s>         Set video bitrate (default: 1000)
    -2, --two-pass          Use two-pass mode
    -T, --turbo             When using 2-pass use the turbo options
                            on the first pass to improve speed
                            (only works with x264, affects PSNR by about 0.05dB,
                            and increases first pass speed two to four times)
    -r, --rate              Set video framerate (5/10/12/15/23.976/24/25/29.97)
                            Be aware that not specifying a framerate lets
                            HandBrake preserve a source's time stamps,
                            potentially creating variable framerate video

### Audio Options-----------------------------------------------------------

    -a, --audio <string>    Select audio track(s), separated by commas
                            More than one output track can be used for one
                            input.
                            ("none" for no audio, "1,2,3" for multiple
                             tracks, default: first one)
    -E, --aencoder <string> Audio encoder(s) (faac/lame/vorbis/ac3) 
                            ac3 meaning passthrough
                            Separated by commas for more than one audio track.
                            (default: guessed)
    -B, --ab <kb/s>         Set audio bitrate(s)  (default: 160)
                            Separated by commas for more than one audio track.
    -6, --mixdown <string>  Format(s) for surround sound downmixing
                            Separated by commas for more than one audio track.
                            (mono/stereo/dpl1/dpl2/6ch, default: dpl2)
    -R, --arate             Set audio samplerate(s) (22.05/24/32/44.1/48 kHz)
                            Separated by commas for more than one audio track.
    -D, --drc <float>       Apply extra dynamic range compression to the audio,
                            making soft sounds louder. Range is 1.0 to 4.0
                            (too loud), with 1.5 - 2.5 being a useful range.
                            Separated by commas for more than one audio track.
    -A, --aname <string>    Audio track name(s),
                            Separated by commas for more than one audio track.

### Picture Settings---------------------------------------------------------

    -w, --width <number>    Set picture width
    -l, --height <number>   Set picture height
        --crop <T:B:L:R>    Set cropping values (default: autocrop)
    -Y, --maxHeight <#>     Set maximum height
    -X, --maxWidth <#>      Set maximum width
    -p, --pixelratio        Store pixel aspect ratio in video stream
    -P, --loosePixelratio   Store pixel aspect ratio with specified width
          <MOD:PARX:PARY>   Takes as optional arguments what number you want
                            the dimensions to divide cleanly by (default 16)
                            and the pixel ratio to use (default autodetected)
    -M  --color-matrix      Set the color space signaled by the output
          <601 or 709>      (Bt.601 is mostly for SD content, Bt.709 for HD,
                             default: set by resolution)

### Filters---------------------------------------------------------

    -d, --deinterlace       Deinterlace video with yadif/mcdeint filter
          <YM:FD:MM:QP>     (default 0:-1:-1:1)
           or
          <fast/slow/slower>
    -5, --decomb            Selectively deinterlaces when it detects combing
          <MO:ME:MT:ST:BT:BX:BY>     (default: 1:2:6:9:80:16:16)
    -9, --detelecine        Detelecine (ivtc) video with pullup filter
                            Note: this filter drops duplicate frames to
                            restore the pre-telecine framerate, unless you
                            specify a constant framerate (--rate 29.97)
          <L:R:T:B:SB:MP>   (default 1:1:4:4:0:0)
    -8, --denoise           Denoise video with hqdn3d filter
          <SL:SC:TL:TC>     (default 4:3:6:4.5)
           or
          <weak/medium/strong>
    -7, --deblock           Deblock video with pp7 filter
          <QP:M>            (default 5:2)
    -g, --grayscale         Grayscale encoding

### Subtitle Options------------------------------------------------------------

    -s, --subtitle <number> Select subtitle (default: none)
    -U, --subtitle-scan     Scan for subtitles in an extra 1st pass, and choose
                            the one that's only used 10 percent of the time
                            or less. This should locate subtitles for short
                            foreign language segments. Best used in conjunction
                            with --subtitle-forced.
    -F, --subtitle-forced   Only display subtitles from the selected stream if
                            the subtitle has the forced flag set. May be used in
                            conjunction with --subtitle-scan to auto-select
                            a stream if it contains forced subtitles.
    -N, --native-language   Select subtitles with this language if it does not
          <string>          match the Audio language. Provide the language's
                            iso639-2 code (fre, eng, spa, dut, et cetera)

Now we'll go through one-by-one...

General Options

  • -u or --update: asks the HandBrake website if there's a new version available
  • -v or --verbose: in verbose mode, extra messages from the core library will appear on screen during the encode. This is useful if you're a developer debugging, or if you can't figure out why an encode isn't working right. There are different levels of verbosity. By default enabling -v turns on level 1 logging. This contains anything useful for tech support, and is the "Activity Log" talked about so much on the HandBrake forums. Level 2 adds some memory-related logging, and level 3 is for granular, packet-by-packet analysis for debugging. If you follow -v with a number, like "-v2", it will use that as the verbosity level instead of 1.

  • -C or --cpu: while the program can discern how many CPUs your computer has on its own, there are some cases when you might want to force a specific number. This flag has to be followed by a number.
  • -Z or --preset: enter a preset name to use.
  • -z or --preset-list: displays all the presets' names and what CLI options they use.

Source Options

  • -i or --input: input is all important. You must include it, followed by a filepath (like /Volumes/MOVIE or ~/Movies/VIDEO_TS).
  • -t or --title: selects the title from a DVD to encode. If you don't specify it, this will default to 1. To just scan a DVD, letting you see the titles and their durations (to help pick which is the feature you want) as well as the chapter durations, autodetected cropping, subtitle and audio tracks, etc., give this a value of 0.
  • -L or --longest: automagically selects the longest title on the DVD, which is probably the main feature you want to encode. Mirrors default behavior in the MacGui.
  • -c or --chapters: tells it to only encode a specified chapter or range of chapters from the title. If you don't specify, it will default to all chapters. Ranges are given with hyphens, like 1-3.

Destination Options

  • -o or --output: output is all important. You must include it, followed by an output filename with a filepath (like ~/Movies/movie.mp4). If you suffix the file .mp4, .mkv, .avi, or .ogm, it will be encoded with that file format container.
  • -f or --format: forces a particular container file format. Your choices are avi, mp4, mkv, and ogm. If this is omitted, it will try to figure out the format from the output filename.
  • -m or --markers: only available with the .mp4 and .mkv file formats, this setting includes a chapter index in the video, based on the chapter times used on the DVD. In .mp4 files, these chapter markers are in QuickTime's format. They can be read by VLC, QuickTime, iTunes, the AppleTV, the iPod, and the iPhone. In order for QuickTime to see the chapters, you must rename the output file to end with .m4v instead of .mp4.

If you wish to import chapter names from a csv file, you can do so using the following: --markers="/full/path/to/chapters_file.csv" The CSV file should be formatted as follows:

1,Chapter One
2,Chapter Two
3,Chapter Three

Note: Should you use a comma in your chapter name: e.g 1,Chapter, Name you must place a backslash before it like so: 1,Chapter\, Name (This slash will not actually appear in the chapter name)

  • -4 or --large-file: when used with the MP4 file format, this permits creation of files larger than 4GB. But to do so, it uses 64-bit numbers. These make it incompatible with some devices (like the iPod and the PS3) -- and that incompatibility happens whenever the feature is enabled, whether or not the output reaches 4 GB. On the other hand, if you do not enable it, and your MP4 is larger than 4 GB, HandBrake will crash.
  • -O or --optimize: Rearranges MP4 files so they play better over the web as progressive downloads.
  • -I or --ipod-atom: Applies a marker to MP4 files that older iPods require before they'll allow H.264 video to sync.

Video Options

  • -r or --rate: controls the video framerate, or FPS. Your options are 5, 10, 12, 15, 23.976, 24, 25, or 29.97. If you do not specify, HandBrake will default to using the same frame rate as the DVD. It will literally pass through the durations of each frame in the source video. This can mean a variable frame rate, because many sources--such as DVDs and other MPEG-2 streams--are inherently variable framerate. A frame remains on screen until the next frame's time stamp is reached. Those time stamps are not always separated by the same amount of time. Note that the .avi format isn't smart enough to understand this. If you do not specify a rate, HandBrake will, for it, instead set the framerate to a constant 23.976, 25, or 29.97 FPS based on some guesswork about the source video.

Audio Options

  • -a or --audio: selects the audio track or tracks to encode. You can include an unlimited number of audio tracks, separated by commas. The first track is 1, the second is 2, etc. Each track can use different output settings, and the same input track can be encoded multiple times with different settings.
  • -E or --aencoder: selects the audio encoder. Choices are faac, lame, vorbis, and ac3. Faac encodes AAC, and lame encodes MP3. The defaults are AAC for .mp4, MP3 for .avi, Vorbis for .ogm, and AC3 for .mkv. You can pass-through AC3 (the original Dolby Digital audio from the DVD) when using the .avi, .mkv, and .mp4 file formats. If you pass through AC3 to an .mp4, it will only be recognized by the AppleTV, Perian, and the VLC, and then only when you end the file with the suffix .m4v.
  • -B or --ab: allows you to set an average audio bitrate in kilobits per second. The default is 160.
  • -6 or --mixdown: This controls downmixing of the audio. The options are none, mono, stereo, dpl1, dpl2, or 6ch. For example, you could downmix a stereo source to mono, or a 5.1 source to 2-channel Dolby ProLogic 2. Assuming you have not set AC3 pass-through as the audio encoder, the default behavior is for HandBrake to downmix Dolby Digital 5.1 to Dolby ProLogic 2. When encoding audio to AAC, you may use --mixdown 6ch to preserve all of the surround channels in the source audio, creating a 6-channel AAC from a 6-channel (5.1) AC3.
  • -R or --arate: sets the sample rate for the audio in kilohertz. The default, auto, uses the same sample rate as the source audio track, unless it's not compatible with the audio encoder.
  • -D or --drc: if your audio isn't loud enough, you can try applying extra dynamic range compression when encoding from AC3 sources. This will boost up the volume of soft audio samples while leaving loud samples as is. This reduces the dynamic range, but should help for catching quiet audio in noisy listening environments. It takes a floating point number as its value, from 1.0 (off) to 4.0 (blow out your speakers from the background sound of elevator doors closing). 1.5 to 2.5 is a useful range.
  • -A or --aname: sets an audio track's name. Only available in .mp4 files. This is useful for the AppleTV, which otherwise gets confused when more than one track is in the same language and codec.

Multiple Audio Tracks

HandBrake can encode more than one audio track at a time, or the same track multiple times, and use different settings for each encode. It is common for AppleTV users to make one file that includes the main audio track from the source encoded once to AAC for playback on iPods, and also pass it through as a secondary track.

This is achieved by using the command:

-E aac,ac3

If you do not specify which audio tracks to encode with the -a option, then HandBrake uses the first track in the source. When you include more than setting for an audio option, separated by a comma, it implicitly tells HandBrake: "The output should have two audio tracks." And without a source audio track specified, it will just use the first track for both.

You can also do complete settings for multiple tracks:

-a 1,1,2 -A "Main Audio","Downmixed Audio","Director's Commentary"-E ac3,aac,aac -B auto,160,128 -R auto,auto,44100 -6 auto,dpl2,stereo 

There will be 3 audio tracks in the output, named "Main Audio", "Downmixed Audio", and "Director's Commentary" in turn. The first 2 will be the first audio track from the source: once as AC3 passed-through untouched, once as AAC with a bitrate of 160 and a Dolby Pro Logic II mixdown. The third track will use the second audio track from the source, encoded to AAC at a bitrate of 128, with a samplerate of 44.1kHz, and a stereo mixdown.

When you don't want to specify any particular setting for one of the tracks, use "auto" as a placeholder.

Picture Settings

  • -w or --width: Enter your desired output width here in pixels. The default is 720 for widescreen, 640 for fullscreen. If you do not specify a height as well, it will calculate one that will preserve the film's aspect ratio.
  • -l or --height: Enter your desired output height here in pixels. If you do not specify a width as well, it will calculate one that will preserve the film's aspect ratio. The default behavior is to use a height that preserves the film's aspect ratio, given the width. If you specify neither -w nor -l, by default your output will be approximately 720*400 for 1.78:1, 720*386 for 1.85:1, 720*304 for 2.35:1, and 640*480 for 1.33:1.
  • --crop: controls the cropping values. The cropping has to be in the form Top:Bottom:Left:Right, so to crop 60pixels from the top, 58 from the bottom, 2 from the left, and 6 from the right, use --crop 60:58:2:6 ... do note that this is different from cropping in some other programs, like MEncoder. If you don't enter this setting, HandBrake will automatically detect how many pixels to crop to remove black borders.
  • -Y or --maxHeight: sets an upper boundary on the height. Smaller values will be permitted, but anything larger will be scaled down and the width adjusted to match the film's aspect ratio. For example, the iPhone display is 480*320. While it can accept resolutions up to 640*480, some people prefer to go "dot-by-dot" and encode exactly the number of pixels the device can display, to save space or increase bits per pixel. If you just use -w 480, then with 4:3 content, HandBrake will encode to dimensions of 480*360 (too tall!). If you just use -l 320, then with 16:9 content, HandBrake will encode to dimensions of 570*320 (too wide!). But if you use -w 480 -Y 320, HandBrake will encode to dimensions of 416*320 for 4:3 content and 480*272 for 16:9 content (just right!).
  • -X or --maxWidth: sets an upper boundary on the width. Smaller values will be permitted, but anything larger will be scaled down and the height adjusted to match the film's aspect ratio.
  • -p or --pixelratio: this enables anamorphic encoding (the "p" is for PAR, pixel aspect ratio). It takes no options.
  • -P or --loosePixelratio: this enables loose anamorphic encoding. Unlike regular old --pixelratio, it will use dimensions that divide cleanly by 16, and allow you to scale down the stored frame by giving HandBrake a --width. It takes an optional argument, that makes it so dimensions divide cleanly by some number other than 16 (8 is popular). That is done like so: --loosePixelratio=8. It also handles ITU pixel aspects, which are applied automatically when the source width after cropping is less than 708.
  • -M or --color-matrix: tells video players to use either Bt.601 or Bt.709 color to display the encoded output, with the required option of 601 or 709. Only effective with .mp4 files and/or x264 video. Bt.601 is what standard definition video like DVDs is supposed to use, and Bt.709 is supposed to be for high definition, so that's what HandBrake signals by default if you do not include this setting.

Filters

  • -d or --deinterlace: turns on deinterlacing filtering. It accepts parameters in the form --deinterlace="1:-1:1". The first parameter controls yadif and ffmpeg. "-1" means ffmpeg, HandBrake's fast, quick'n'dirty, traditional deinterlacer. "0" means yadif with 1-pass and spatial deinterlacing. "2" means yadif with 1-pass without spatial deinterlacing. "1" means yadif with 2-pass and spatial deinterlacing. The second parameter is the field dominance. "-1" means "assume top field first" and it should generally be left that way. The third parameter controls mcdeint, which is currently broken, so leave it set to "-1". There are also short names for commonly used parameters: "fast" is --deinterlacer="-1", "slow" is --deinterlace="2", and "slower" is --deinterlace="0". So you can also just do: --deinterlace="slow".
  • -5 or --decomb: selective deinterlacer -- it only deinterlaces frames that show visible interlacing artifacts. Much more information on decomb is available, but using it with its default options should work out well most of the time.
  • -9 or --detelecine: stateless inverse telecine (the pullup filter from MPlayer). When 24fps content is hard-telecined to 30fps by interpolating extra, interlaced fields, detelecine will restore the video to progressive. Bewarned that when used with a constant frame rate, HandBrake will drop or dupe frames as necessary to reach that constant rate. You can avoid this by not specifying a video framerate. By default, HandBrake will use the "Same as source" FPS, which permits a variable frame rate.
  • -8 or --denoise: high quality temporal and spatial denoising. Denoising softens the image (removing detail) but can significantly reduce bitrate. The parameters, in order, control filter strength for spatial luma, spatial chroma, temporal luma, and temporal chroma. Take guidance from the MacGui. You can also use some short names to commonly used parameters. A good "weak" setting for general use is --denoise="2:1:2:3", a good "medium" strength setting that will leave minor visual artifacts is --denoise="3:2:2:3", and for simple animation, consider "strong" settings of --denoise="7:7:5:5". You can just type them in like that: --denoise="weak".
  • -7 or --deblock: pp7, a post processing filter from MPlayer, removes blocks from video. You're probably best off using its defaults and not specifying parameters. If you do, know that the default is 5, 1 is very little deblocking, and by 10 things get quite blurry.
  • -g or -grayscale: lets HandBrake know the movie is black and white, so it doesn't bother keeping track of color information. This can reduce green tinge or rainbow shimmering in black and white encodes. It takes no options.

Subtitle Options

  • -s or --subtitle: selects a subtitle track to use. Subtitles are selected by number: the first track is 1, the second is 2, etc. HandBrake "hard burns" subtitles onto the video. If you enable them, they will always be visible. You cannot turn them on or off like with a DVD.
  • -U or --subtitle-scan: This option lets HandBrake scan and detect subtitles that should be enabled. Sometimes, movies will be primarily in one language, but with short sections in foreign tongues, during which subtitles appear in the primary language. Different DVDs do that in different ways. Some only have one main-language subtitle track, that covers the whole film, and the DVD only forces them on in foreign language segments (see --subtitle-forced). Other DVDs will have a separate subtitle track in the primary language, that only has content for the short foreign-language segments. This feature handles those with aplomb.
  • -F or --subtitle-forced: This option may be used in two ways. When used with --subtitle-scan it will modify the subtitle scan to automatically select subtitle tracks that contain forced subtitles, and then display just the forced subtitles in that track. When used on its own in conjunction with --subtitle only subtitles that have the forced flag set will be displayed for the selected subtitle track.
  • -N or --native-language: follow this flag with a language code (eng, fre, spa, dut, et cetera) and it will use that language's subtitles if the selected or default audio language differs from your native language. This way, you don't have to run a -t 0 scan first to see what subtitles are in what languages. Just tell HandBrake what language you want, and it will find the correct track if available. For example, if you select "fre" and you encode a title with French audio, you will not get any subtitles, however if you encode the same title with English audio you will get the French subtitles enabled.

Where's the queue?

In the CLI, there is no queue. You can use a semi-colon:

HandBrakeCLI -i VIDEO_TS -o movie1.mp4 -t 1 ; HandBrakeCLI -i VIDEO_TS -o movie2.mp4 -t 2

Or, you can write a simple shell script.