ffmpeg

This page holds my notes on using ffmpeg for typical (and atypical) conversions, largely thanks to the mess that the consumer electronics industry has made of standards (see also , which is the format I favored for ripping my kids’ DVDs to avoid them chewing the discs to pieces until I switched to an and decided to just go with multi-track MP4).

Converting AAC 5.1 surround sound to AC3

This can be done on an ARM machine with remarkably little CPU power, since you’ll simply be copying video across without touching it:

ffmpeg -i file_with_aac_surround_.mp4 -vcodec copy -acodec ac3 -ac 6 -ar 48000 -ab 448k file_with_ac3.mp4 

Converting FLAC to MP3

# fixed bitrate
find . -name "*.flac" -exec ffmpeg -i {} -ab 320k -map_metadata 0 -id3v2_version 3 {}.mp3 \;
# high quality VBR
find . -name "*.flac" -exec ffmpeg -i {} -codec:a libmp3lame -q:a 0 -map_metadata 0 -id3v2_version 3 {}.mp3 \;

Extracting thumbnails from videos

The typical use case is to generate a poster image:

ffmpeg -i input.mp4 -vf "scale=iw*sar:ih,setsar=1" -vframes 1 poster.png

I was once asked to make it easier to navigate a set of videos on a WDTV media player and, after looking around for alternatives, eventually came up with the following snippet, which is designed to be dropped into an workflow.

It takes a list of files on standard input and then invokes ffmpeg to extract a thumbnail 30s into the video. sips is then used to resample that image to a smaller size, preserving the aspect ratio:

import sys, os, re

# Handle only these file extensions
pattern = re.compile("^(.+)\.(divx|mov|avi|3gp|wmv|mp4|mkv)$", re.IGNORECASE)

for f in sys.stdin:
  f = f.strip()
  matches = pattern.match(f)
  if matches:
    base = matches.group(1)
    thumb = "%s.jpg" % base
    if os.path.exists(thumb) and os.path.getsize(thumb):
      continue # skip existing non-null files
    os.system("/usr/local/bin/ffmpeg -i '%s' -deinterlace -an -ss 30 -t 00:00:01 -r 1 -y -vcodec mjpeg -f mjpeg '%s' 2>&1" % (f, thumb))
    if os.path.exists(thumb):
      # tweaked rendering to attempt a vertical thumbnail with a center crop
      os.system("/usr/bin/sips '%s' --resampleHeight 160 --cropToHeightWidth 160 120 --out '%s'" % (thumb, thumb))

There’s also a one-liner I was sent that may help:

for %i in (*.avi) do ffmpeg -i "%i" -f mjpeg -t 0.001 -ss 30 -y "%~ni.jpg"

Stacking videos

See this blog post.

Transcoding for mobile devices:

João Neves sent over this one-liner for transcoding to or iOS devices. The bitrate (-b) can vary from 600k to 1000k for the latter, and 600k reportedly works well for the HTC Magic:

ffmpeg -i input.avi -acodec libfaac -ab 128k -vcodec mpeg4 -b 600k -mbd 2 -cmp 2 -subcmp 2 -s 320x180 output.mp4

Other Tools:

  • remux is able to change envelope without re-encoding, do track re-ordering and audio transcoding.
  • libav tutorial (includes a sample H.264/H.265 transcoder)

This page is referenced in: