Log in

View Full Version : h264levl - automatically ensuring level-conformance for H.264 encodes


fvisagie
31st October 2014, 15:45
Here is something I started, partly to fulfil a need and partly to explore Windows shell scripting. As it may be useful to others too, I'm taking the liberty of sharing it here.

The main aim of the attached utilities is to automatically ensure the H.264 level-conformance of arbitrary encodes. In other words, the utilities make it unnecessary to guess and/or discover the required settings through trial-and-error test encodes.

Automatically ensuring level-conformance is useful for various reasons:

It ensures maximum compatibility with the widest range of players (even in cases where strict settings for a specific target are not required)
Encoding time can be reduced by as much as 50% by using only as many reference frames as a particular encode's level allows (relevant to (lib)x264 presets slower than medium, and esp. true for veryslow)
It takes the guesswork and test encodes out of changing between sources with different frame sizes, frame rates, bitrates, etc.

h264levl calculates, for the given output video parameters, the expected H.264 level and corresponding maximum reference frames. It supports both manual and unattended operation, providing appropriate exit codes and diagnostic output to STDERR for the latter.

Here is an example of how h264level can be called from another script:

...
setlocal enableextensions
setlocal enabledelayedexpansion
...
rem Calculate H.264 level and maxref
rem --------------------------------
for /f "usebackq tokens=1* delims==" %%i in (`"call h264levl %WIDTH% %HEIGHT% %FPS% %BITRATE% %PROFILE% 1 1 "`) do (
if /i [%%i] == [level] (
set LEVEL=%%j
) else if /i [%%i] == [maxref] (
set MAXREF=%%j
) else if /i [%%i] == [x264maxref] (
set XMAXREF=%%j
)
)

rem Check successful parsing
set PARLIST=
for %%i in (LEVEL MAXREF XMAXREF) do (
if [!%%i!] == [] (
if not [!PARLIST!] == [] set PARLIST=!PARLIST!,
set PARLIST=!PARLIST!'%%i'
)
)
if not "%PARLIST%" == "" (
set ERRMSG=Unable to calculate legal value/s for %PARLIST%^^!
goto ERRPAUSE
)
...


FFx264 is an example of such an encoder wrapper script. In addition to h264levl, it also uses ffprobe to establish video characteristics such as frame rate and width and height (the latter two when not over-ridden by the user).

Although FFx264 uses ffmpeg for encoding, its syntax is readily adapted for e.g. x264.

Extract the files and double-click for instructions.

Known restrictions
* These utilities have only been properly tested on 8-bit video