Some Bits: Nelson's log

11 posts about ffmpeg

Intel QuickSync GPU transcoding in Proxmox

Notes on video hacking, efficiently transcoding H.264 to H.265 video. I’m updating my old to65 function to work in my new Proxmox environment. The key idea here is to use jellyfin’s build of ffmpeg with Intel QuickSync codecs to transcode video faster. The challenge is making getting a Proxmox guest OS that can use that. Both to set up the container and also to make sure it has the permissions necessary.

The expedient solution I set up was to use a tteck script to install jellyfin. That’s a whole server environment and is overkill but it installs the /usr/lib/jellyfin-ffmpeg/ffmpeg I need. It also sets up the container to access the Intel GPU. The main thing it does is make the container privileged: not ideal (nor necessary) but sure smooths things over. There’s also some entries in /etc/pve/lxc/104.conf for mapping the necessary devices, particularly /dev/dri/renderD128.

Anyway installing with that script is really all I needed. With that my i5-12600K server is transcoding a 1080p video at about 4x speed. Using 40% of one CPU core and intel_gpu_top shows me the Render engine is pegged at 100% (encoding?) with the Video engine also at 20% (decoding?). That’s more or less what I remember doing on the old native hardware, no surprise.

tteck also has a tdarr package. I should try that again; last time I did I couldn’t figure out tdarr’s UI. It’s perfect for what I need but I was scared it’d aggressively transcode all my video files, I really want to only transcode a few things.

ffmpeg and hevc_qsv Intel Quick Sync settings

I’m revisiting my experiments using Intel Quick Sync to transcode video into H.265 using the hevc_qsv transcoder. I’m using jellyfin’s build of ffmpeg. Here’s where I ended up:

function to65 {
  /usr/lib/jellyfin-ffmpeg/ffmpeg \
    -c:v h264_qsv \
    -i "$1" \
    -map 0 -c copy \
    -c:v hevc_qsv -preset slow -global_quality 22 -look_ahead 1 \
    $2 \
    "${1%.*} x265.mkv";
}

Doing this results in an H.265 video file about 1/4th the size of the H.264 file and takes about 1/8th the show length to transcode. (ie: 5-6 minutes for a typical 42 minute tv show). Quality looks about the same to me but I’m using fairly unexciting video sources to test.

ffmpeg options

The challenge is this is all very poorly documented, particularly quality settings. Keep in mind that hardware H.265 encoding is generally considered lower quality than the CPU based x265 encoder. NVenc is said to be better than QSV. Also be aware Google search is treating hevc_qsv as a synonym for h264_qsv, so searches will often find irrelevant information if you’re not careful.

ffmpeg -h encoder=hevc_qsv is supposed to give you a list of all the codec specific options. You can see that list here. But there’s no real basic quality or bitrate setting, just a lot of mysterious technical-seeming options. Some of this might be documented in the Intel Media SDK docs or this white paper on how it all works.

Instead you want these ffmpeg docs and the QSV encoder help page. The key option here is global_quality. I think this works like crf (which is not an option and seems to be silently ignored if provided). The number is not documented but can be 1 (highest) to 51 (lowest), folks online recommending about 21. With global_quality set you still have 3 algorithm options: -look_ahead 1 seems to be the fanciest. I’m not sure but that might be the default. -preset is another option to consider; slow seems the right tradeoff to me. I did not consider the -profile option.

I still feel like I’m missing one clear set of docs for how this encoder works. I cobbled some of it together also using this cookbook page.

Testing

I did a very casual test of these settings using a 720p web rip (AMZN) of a TV cooking show. The original file is about 6000kbps; the video stream itself is 5800kbps H.264. I have a tin eye; I’m OK with fairly mediocre video encoding for most things like this. I’m just trying to keep some old TV shows around without taking up too much space.

For visual quality, -global_quality had an enormous impact; it’s the most important setting. Using the default settings instead or was unacceptably bad, particularly on scene transitions. Honestly anything from -global_quality 18 to 26 looked about the same to me. The preset option didn’t have nearly as clear an impact on visual quality.

Preset does have an impact on encoding speed. medium: 9.5x. slow: 7.5x. slower: 3.7x. Quality settings didn’t have much impact on encoding speed.

Here’s bitrates at different settings of -slow -global-quality N

-global_qualityFile bitrate (kbps)
182911
202309
221777
241395
261114
original6075
default hevc_qsv1222

Running ffmpeg this way uses 1 CPU core and the GPU at 100%.

Screenshots

Sorry for the lack of labels on the images. The first is the original, the second two are without global_quality (and unacceptable). The rest are progessively lower global_quality although honestly they all look about the same to me. This was a frame with a lot of detail right after a scene transition. It’s not crystal sharp in the original so it’s not a big surprise many of the transcoded versions are roughly the blurry same.

Ubuntu, ffmpeg, and Intel GPU acceleration

My fancy new Linux box has an Intel 12th gen CPU (Alder Lake) with a GPU in it. I wanted to try using ffmpeg to transcode video from H.264 to H.265. Here’s how I got it working, it was not easy.

Transcoding commands

First, my old way of transcoding without GPU acceleration

ffmpeg -i "$1" -map 0 -c copy -c:v libx265 -crf 25 $2 "${1%.*} x265.mkv"

I get about 4x encoding speed on an i5-12600K (compare about 1.1x on a ten year old i7-2600). However all 16 cores are pegged at 80% ish and the machine is drawing 165 watts. Note we’re using the libx265 encoder, all CPU. It’s not bad.

The new hardware accelerated way (some of these arguments need tweaking)

sudo /usr/lib/jellyfin-ffmpeg/ffmpeg \
  -c:v h264_qsv \
  -i input.mkv
  -c:v hevc_qsv
  -c:a copy out.mkv

This runs much nicer! I get 7.5x encoding speed. But now I’m only using 1-2 cores and the machine is drawing only 55 watts. I haven’t looked closely at encoding options or video quality but a quick preview looks plausible.

The primary change here is different codecs; h264_qsv and hevc_qsv. These are Intel Quick Sync codecs that are hardware accelerated using the GPU. The h264_qsv decoder uses about 10 watts less than the default CPU decoder (and 1-2 cores). The hevc_qsv is where the big savings are, some 90 watts.

The other change is I’m using jellyfin’s build of ffmpeg. Installing all this was a bit of a trick. Note also I had to be root to run this; I think there’s a way to change permissions so you can open the video device without root. Update: the devices are in /dev/dri which are usable by group “render”.

Installing prerequisites

I’m starting with an Ubuntu 22.04 server install running the 3.19 mainline kernel. Probably any kernel is fine.

I installed these packages from the default Ubuntu repository:

$ apt install onevpl-tools vainfo intel-media-va-driver-non-free
$ sudo vainfo
vainfo: Driver version: Intel iHD driver for Intel(R) Gen Graphics - 22.3.1 ()

OneVPL is Intel’s userspace for Quick Sync, the GPU accelerator. The non-free driver is recommended. vainfo is probably not necessary but is a handy tool for verifying the graphics driver.

With this I thought the stock ffmpeg would work. But it did not. I finally gave up and installed the jellyfin-ffmpeg package with the Ubuntu Repository instructions. Jellyfin is an open source media server, sort of like Plex. Its hardware acceleration docs are a lot clearer than ffmpeg’s wiki docs and apparently their build of ffmpeg has something important that Ubuntu’s does not.

Updates

intel_gpu_top (from intel-gpu-tools) is handy for seeing what’s running on the GPU

x265 transcoding

I continue to re-encode video I get into x265. It’s much smaller, which helps both with storage and bandwidth. And it looks fine to my tin eye.

My script has evolved over time. This is what I do now:

ffmpeg -i “$1” -map 0 -c copy -c:v libx265 “${1%.*} x265.mkv”

In theory this leaves all the audio and subtitles alone, just copies them, but re-encodes the video in x265 with default settings.

I was in a hurry today and so got fancy with resizing the video to 360p and using a faster / less accurate encoding setting.

ffmpeg -i “$1” -map 0 -c copy -vf scale=-1:360 -c:v libx265 -preset faster “${1%.*} x265.mkv”

Quality definitely suffers for this, but I can encode at 3-4x playback speed on my CPU this way.

x264 / x265 sizes compared

Doing a little ugly fast and loose codec comparison. I took a pirate scene MKV file in 720p with 5.1 audio, an hour long video file that was (no doubt) lovingly encoded in H.264 with one audio track and several subtitle tracks. I then transcoded it to H.265 and H.264 using ffmpeg with default settings. This also transcoded the audio from 640kbps AAC to 276kbps Vorbis. Anyway here’s what I got for file sizes:

Original file

  • 1800MB, 720p, 51 minutes
  • 1580MB video, 240MB audio
  • h264 (High)

x265

  • 170MB, or roughly 10% the size
  • 80MB video, 90 MB audio
  • hevc (Main), encoded with “ffmpeg -c:v libx265”, default settings.
  • Encoded at about 1.3x playback speed (software)

x264

  • 400MB, or roughly 22% the size
  • 290 MB video, 90 MB audio
  • h264 (High), encoded with “ffmpeg -c:v libx264”, default settings.
  • Encoded at about 3x playback speed (software)

The x265 encoding is remarkable. The video is literally smaller than the audio! And the resulting file is 10% of the source. The video segment is 5% of the size of the source and the audio is 38%.

The x264 re-encoding is also notable, in that I’ve squished it to 22% of the source with nominally the same codec. That’s a pretty good savings and indicative that the source of the file was probably encoded with very high quality / high bitrate to make paying customers happy.

The resulting x265 file looks fine on my TV. You can see some posterization on subtle dark areas and maybe the sound isn’t as clear. But I’m blessed with a tin ear so those degradations don’t bug me much. No doubt there’s a sliding bar here between bandwidth and quality that a proper codec testing setup can do. Me, I’m just a dumb bear using ffmpeg default settings and pretty happy with the result

This post was all motivated by this post and discussion about comparing AV1 to x264 and VP9. AV1 is the new hotness in codecs, although as with all these things there’s years of controversy and patents and hardware support to settle before adoption.

Blu-Ray to x265

I am super excited about the Vinegar Syndrome re-release of Liquid Sky. One of my favorite movies from the 80s, most of us watched it on crappy 3rd generation VHS tapes or if we were lucky, a low quality DVD. Vinegar Syndrome remastered it and put out a beautiful Blu-Ray with gorgeous color and lots of extra features. Only problem: it’s a disc. Who can play discs these days? So I ripped it. (For myself only, I respect Vinegar Syndrome far too much to give out copies.)

Pasted image at 2017_12_12 02_36 PM.png

Blu-Ray discs are encrypted so most computer tools can’t read them. But MakeMKV can. It’s a straight up rip; it copies all the tracks off of the Blu-Ray and puts them in MKV containers on your hard drive. No re-encoding so the 2 hour movie is like 29 GB.

Re-encoding it to a smaller file is easy. Handbrake will do the job fine but for some reason was running slowly for me, so I used ffmpeg instead. Here’s the command:

ffmpeg -hwaccel auto -i title00.mkv
-map 0:v -c:v libx265 -crf 26 -preset slow -tune grain
-map 0:a:0 -c:a:0 aac
-map 0:a:1 -c:a:1 copy
-map 0:s:0 -c:s copy
ls.mkv

I’m doing this the complicated way with -map options so I can pick and choose audio tracks. Track 0 is the main audio, track 1 is director’s commentary. There’s also a track 2 which is the sound without dialog, but I decided not to include it. Just the one video track of course, and one subtitle track.

I transcoded the main audio. The source is in 768kbps DTS, overkill particularly since the audio is mono (as the original film was). So I’m re-encoding it to AAC. I have no idea what bitrate that was going to give me. The result is about 150kbps which seems reasonable, if generous.

I also transcoded the video to H.265, the result is about 3300kbps for 1920x1080. crf 26 is higher quality than the default crf 28. Preset slow trades off CPU time for higher quality / smaller video. And “tune grain” tweaks the encoder to try to preserve film grain, something abundantly visible in the source disc.

I wanted to transcode the subtitles to SRT but that didn’t work for me, ffmpeg threw an error.

The metadata mostly came through but then some of it is wrong; bitrates and stuff were copied from the Blu-Ray. Chapter marks did come through from the original source.

All told it took about 18 hours or about 0.1x real time speed. That slow preset really makes it slower, something like 4x slower.

Hardware accelerated ffmpeg transcoding

Since I have a Linux VM with a big GPU lying around I thought I’d take a quick stab at hardware accelerated video transcoding using ffmpeg. Quick results:

  • software decode, h264 software encode: 0.355x real time
  • software decode, h264_nvenc hardware encode: 2.7x real time
  • cuvid hardware decode, h264_nvenc hardware encode: 2.8x real time

So the hardware h264 encoder is about 7x faster than software. Hardware decoding is nice but not a huge improvement.

This is all on a 1 vCPU, K80 Google Compute server. Crappy little CPU and big beefy GPU. Normal desktop machines probably have less of a spread in results.

I really wanted to test this with H265 encoding, but the hevc_nvenc encoder does not work with the Kepler-class K80 hardware. I’m regularly doing H264 -> H265 transcoding at home now and on my i7-2600 it transcodes 720p video at just about real time.

Between the video transcoding and the machine learning I’m itching to own my own Linux box with a GPU in it. I could add a GPU to the existing server but it seems to be $200 minimum. The old server is 6 years old, maybe it’s time for a full hardware upgrade. Go for SSDs. Ubuntu 17.10 while I’m at it; these LTS releases are reliable but limiting.

I wonder if there’s a way to use the on-chip Intel GPU more? Probably not worth the hassle.

 

Converting video to x265 with avconv

A simple command line for converting video to small x265. These options are chosen to produce acceptably low quality, low bitrate output.

avconv -i in.mkv -c:v libx265 -c:a copy -crf 29 -s 854x480 -preset fast out.mkv

  • c:v libx265 means “encode using x265”.
  • c:a copy means “copy audio, don’t re-encode”
  • crf 29 means “slightly worse than default 28 quality”
  • s 854x480 means “resize to 480p”
  • preset fast means “I don’t have a hardware encoder so please don’t take forever”

Obviously better quality is possible, this is producing about 500-600kbit/second video or about 4x the same of the audio track.

Speaking of audio track it’d be nice to convert whatever the source is to 128kbps AAC stereo. I’m not clear if a simple “-ac 2” is sufficient or if more complex downmixing is necessary.

some ffmpeg bash functions

I’m doing a lot of trashy video editing on the command line. I’m taking FLV files from a screen recorder, trimming them to a time frame and converting them to MP4. And then I’m concatenating multiple MP4 files. This is all very confusing to remember how to do in ffmpeg so here are two shell functions I use to do the work for me. There’s nothing particularly clever here except the <() process substitution for the catmp4 program, which creates a temporary file (or named pipe or something) with the output of a command.

function tomp4 {
    ffmpeg \
      -i "$1" \
      -c:v libx264 \
      -preset slower \
      -crf 19 \
      -ss "$2" \
      -to "$3" \
      "${1%.flv}".mp4
}

function catmp4 {
    ffmpeg \
      -f concat \
      -safe 0 \
      -i <(for f in "$@"; do echo "file '$PWD/$f'"; done) \
      -c copy \
      out.mp4
    ls -l out.mp4
}

Mac screen capture: creating League of Legends highlights

I felt like a huge nerd today and wanted to record a video highlight from a League of Legends. Lots of steps here to capture the game itself, capture video and audio on the Mac to a file, convert it to something usable, then upload it. Here’s all the steps.

Generate content: record game replay

The service replay.gg will record all your League of Legends games for you. It’s terrific! Using it you can watch one of your games later in the observer client. I use this to get the exact game scene I want to capture.

Capture content: video and audio capture

The Mac does not make it easy to capture full screen video and audio. I used to use the commercial product Screenflick to do this but it’s pretty buggy. So this time I did the capture with Open Broadcaster Software, which is a free. The UI is a bit more hackerware but for my purposes it’s perfect.

OBS records video pretty much right out of the box. I tinkered with the Advanced Output settings to record at the bitrate of 10,000 (overkill) using the faster preset. Note that OBS is doing h.264 encoding live while you go, so it’s taking CPU power. The “slow” preset definitely interfered with my game framerate. (Screenflick records with a very fast, disk intensive codec and then re-encodes later, which is kind of nice.)

Audio is a problem. Update: see this second post about sound. OBS recommends WavTap but I couldn’t make it work. Instead I installed SoundFlower, which also works well with OBS. Basically SoundFlower installs a kernel module that’s a new loopback audio device. You use the Sound control panel to tell the Mac to make SoundFlower 2ch the default audio device. SoundFlower then passes that through to your actual headphones or whatever, while also making the sound stream available to apps. Note that starting with Yosemite it’s getting very hard to run custom kernel drivers in MacOS. Thanks a lot, Apple.

Now I have OBS recording movie files to my hard drive of whatever is on my screen. Yay!

Edit content

The next challenge is editing the capture down to what you want to share. I’m allergic to iMovie, and AFAIK there is still no good free simple “let me cut 15 seconds out of my video” GUI tool for Macs. I ended up using ffmpeg to do this with these instructions. ffmpeg lets you pick to the nearest millisecond, but irritatingly VLC won’t show you milliseconds in playback, so precise cuts suck.

Here’s the command I used to cut from 00:02 to 00:19 of my recording and re-encode it at decent quality. Unfortunately you can’t just use “-copy” in ffmpeg because that doesn’t properly trim the audio for some reason; you have to reencode.

ffmpeg -i obs.flv -c:v libx264 -preset slow -crf 20 -ss 00:00:02 -to 00:00:19 out.mp4

Man I’d like a simple GUI program that lets me watch the movie and set a start time, an end time, and press a button to do this cut for me.

Share content

Now you have an ordinary MP4 movie file you can share anywhere. I uploaded it to Streamable, a lightweight hosting / sharing service for video that plays nicely with Reddit and friends. They re-encoded it to a 2260 kbps vp8+vorbis file which still looks pretty good. In particular I think they kept my 60 frame per second source, much appreciated.

Ubuntu 14.04: converting m4a audio to mp3

I want to convert a bunch of .m4a files that youtube-dl created to MP3 files. The files are audio only, 128kbps, AAC encoding. They play in VLC but a lot of AAC-supporting software like Sonos can’t read the .m4a files and I don’t care why, just want to convert it to the shitty 18 year old format that works everywhere.

First challenge is that ffmpeg has completely disappeared from Ubuntu 14.04. It’s been replaced with avconv. There was some nerd fight and a fork, no idea what or why or which fork is better. Sigh. Ubuntu went with the fork avtools, so I will too. (There is an ffmpeg PPA). “ffmpeg” is now “avconv”, and “ffprobe” is now “avprobe”.

sudo apt-get install libav-tools

for f in *; do
  avconv -i "$f" -metadata album="Album Title" "${f%.m4a}".mp3;
done

I realize this is all very basic, but every time I try to do any AV codec stuff I get very confused. I wasted a lot of time playing with quality options before deciding avconv was choosing a reasonable setting that I couldn’t really override, probably based on the source material. (Although apparently there’s at least two MP3 codecs buried in there being autoselected.) Also I tried using “-threads auto” to speed things up but no luck, maybe the MP3 encoder is single threaded or maybe it’s all IO bound anyway. It’s re-encoding about a megabyte a second, fast enough for my small job. GNU parallel is another solution here.

Sadly the source tracks have no useful metadata in them like song title or artist. I did throw in an album name at least.