Diary Of An x264 Developer

10/31/2008 (6:17 pm)

x264 revision 1000 party!

Filed under: development,x264 ::

I promised cake in the previous post.

And cake there was.

Read the full story here.

10/22/2008 (12:41 pm)

In the pipeline, part 2

From the local commit git log:

Read More…

10/13/2008 (8:37 pm)

In the pipeline

Filed under: Uncategorized ::

Trellis improvements:
1) Trellis on DC coefficients (i16x16 DC, chroma DC)
2) Chroma trellis

Full MBAFF support, for 10-15% improved interlaced coding efficiency. Thanks to Avail Media for funding this project; expect the final commit within a few months.

Speed improvements:
1) Nehalem optimizations (no further information: I am under NDA about specifics until the release of the processor publicly).
2) More deblock speed improvements (as if there weren’t enough already!)
3) Some possible motion search speed improvements for small partitions.

VBV improvements:
1) Emergency mode: avoid VBV violations in cases where QP51 is not enough.
2) More compliancy improvements from Gabriel Bouvigne.

Oh, and cake. Yes, I’m serious about the cake. Cake is in the pipeline.

10/13/2008 (8:32 pm)

More updates on x264 development

Filed under: development,GSOC,H.264,speed,x264 ::

Its been quite some time, hasn’t it? I’ve managed to go a few months without updates here, mostly because of my work at Avail and school also, but also because I’ve been intentionally putting it off. So, I’m going to actually put in some updates.

x264 now supports Predictive Lossless, the new lossless format introduced in the 2007 revision of the H.264 standard. The compression improvement is considerable; about 4-25% depending on source, with numbers generally higher in intra-only compression. There is no significant speed difference; if anything, it is faster, since lower bitrate means less time spent in bitstream coding. The downside is that only a single decoder in the entire world currently supports it correctly: CoreAVC. Not even JM supports it correctly (its i16×16 prediction support is bugged). A patch is available on the ffmpeg mailing list (simply search for Predictive Lossless or similar) to add support in libavcodec for the format. The strategy here is that since the main reason any decoder anywhere supported lossless to begin with is likely because of x264, this change should force the adoption of the much-superior Predictive Lossless profile.

I’ve begun merging much of the Google Summer of Code work; next on the menu will be the rest of Holger’s assembly and Joey Degges’ much improved multi-ref p8×8 partition search algorithm.

I also have acquired access to a pre-release Nehalem machine through Avail Media; this will allow for a series of Nehalem-specific speed optimizations to be committed on the day of Nehalem’s official release, giving a significant speed boost to users of the new processor in addition to the already-enormous benefit it gives.

x264 is now used by Facebook for their internet video; at this point in time, 25% of all new Facebook videos are encoded using x264. This will likely soon increase to 100% as VP6 is phased out in favor of H.264.

x264 is now at revision 999: only one left to 1000, and indeed we have special plans… more on that when it happens!

07/17/2008 (12:58 pm)

Psy RDO

Many of you may have seen this thread on the Doom9 forums. But what exactly is Psy RDO, other than a magical patch that increases detail retention and sharpness with seemingly few to no downsides? Well here’s how it works.

Psy RDO measures, in addition to normal PSNR-wise distortion, the difference in complexity between the reconstructed frame (what the video will look like on decoding) and the source frame. It values complexity values as close to that of the original frame as possible. Thus, it strongly biases against blurring, and for that matter, any significant loss of detail. Even on non-grainy sources, this generally results in a reduction of banding, increased sharpness, and better retention of fine details. The speed cost is relatively low, though Psy RDO requires regular RD to be enabled.

In all tests so far, this new metric appears to beat out FGO.

And in the spirit of the improved quality, I’ve made a new codec comparison with the latest psy-RDO x264 against basically every other encoder on my (and various other people’s) hard disks.

07/10/2008 (2:34 pm)

A summary of recent revisions

I haven’t written a post here for quite some time, so I figured I’d get back into the swing of things with an update on some recent revisions.  Further information can be found on the official git repository page.

r891: Instead of checking for the end of the bitstream on every single write, check before encoding each macroblock–and instead of silently truncating the frame upon reaching the end of the malloced memory, reallocate with more room. (patch by me)

r892: A patch by Gabriel for compilation on MSVC and other crappy compiles that don’t maintain mod16 stack alignment–disable all functions that require these on such platforms.  This results in a visible CPU flag (“slow_mod4_stack”) to warn the user that their build is crippled.

r893: Various micro-optimizations by me, along with a very cool little idea that saves quite a bit of time in probe_skip.  The idea here is that the probe_skip function *almost never* terminates during the chroma check, but you can’t skip it completely, since if you choose to skip a block before looking at the chroma, and it turned out there was significant detail there that you ignored, there might be noticeable artifacting as a result.  The solution was to do a quick Sum of Squared Differences (SSD) check before doing the actual probe_skip on each chroma plane; if low enough, skip the check.  Even an incredibly low threshold was sufficient for skipping the check nearly half the time yet never changing the results.

r894: Assembly for the lowres interpolation filter used for frametype decision–drastically increases its speed.  The C was modified in order to match the assembly version, which had slightly different rounding.  I originally wrote an MMX, SSE2, SSE3, and SSSE3 version of this patch, but Loren found an even faster method of doing it and rewrote most of it from scratch before committing it.

r895: Fix a bug in adaptive quantization stemming from the original implementation.  One subtle issue with this patch is that on win32, GCC incorrectly puts arrays of all zeroes into .bss even when told to align them–despite the fact that .bss is only labeled as 4-byte aligned.  This causes a crash, of course.  We resolved this with an ugly hack–tack a “1″ onto the end of the array to stop GCC from putting it in .bss.

r896: Improve the permutation macros for easier use throughout x264′s assembly. (patch by Loren)

r897: Port the noise reduction assembly from libavcodec and improve it.  Speed up the C version too.  The SSSE3 assembly is roughly 25 times faster than the original C code.  (patch by me with help from Loren and Holger)

r898-r899: Update the copyright headers across x264. (patch by me)

r900: Fix a subtle bug in Loren’s frame_init_lowres patch; in some cases the FPU might not be re-initialized with “emms” after running frame_init_lowres, so an emms was added just in case.

r901: Lots of mini-optimizations, one by holger, the rest by me.

r902: Considerable cleanup of the SSD assembly functions to simplify the code. (patch by Loren)

r903: A complete rewrite of the bitstream functions from the ground up.  This vastly faster bitstream writer uses 32-bit and 64-bit instead of 8-bit chunks.  This eliminates the need for any loop in bitstream writing.  The 32-bit writer is quite similar to ffmpeg’s 32-bit writer.  The 64-bit writer uses a particularly ingenious system whereby the writer only writes 32 bits at a time, but keeps up to 64 bits in a storage chunk–this means that any variable-length code can be written unconditionally to the chunk, since there’s always at least 32 bits of space left: the write to the bitstream is done afterwards.  Because of this, the 64-bit bitstream writer only needs a single if statement in its write function; not even an else. (patch by me with help from Loren)

r904: The golomb functions were far more complicated than necessary–with the new bitstream writer changes many of the special cases were no longer useful speed-wise.  Additionally, many of the branches were not necessary in most calls to those functions.  (patch by Loren with some changes by me)

r905: When a large static table is stuck in a .h file, its duplicated in every single C file that includes and uses it.  This is a waste of memory–its better to declare it once in a C file and use “extern” to address it from other locations.  This diff de-duplicates VLC tables and additionally reduces them from using 16-bit to using 8-bit codes, since none of the VLC codes have more than 8 significant bits.  (patch by Loren, change to 8-bit by me)

r906:  Add support for PCM macroblocks.   This type of macroblock is *completely* uncompressed and bypasses the CABAC entropy coder.   As such, each PCM block is always 384 bytes.  The advantage of this is that sometimes, given the current state of the CABAC encoder, at very low QPs (0-5) and in lossless mode, its possible that a block will exceed 384 bytes in size–so PCM would have been a better option.  When rate-distortion optimization is enabled, PCM is considered as a possible option by x264.  (patch by me)

06/03/2008 (11:03 am)

The power of CABAC

Today we’ll take a post directly from the stream analyzer.

position : 24×25 (384×400)
mb_addr : 1024
size (in bits) : 1
mb_type : 1
pmode : 0
mb_type : Intra(I_16x16_0_0_0)
slice_number : 0
transform_8x8 : 0
field\frame : frame
cbp bits
: 0000 00 00
: 0000 00 00
: 0000
: 0000
quant_param : 0
pmode : Intra_16x16
ipred : 16x16_Vertical

position : 23×27 (368×432)
mb_addr : 1103
size (in bits) : 15
mb_type : 6
pmode : 0
mb_type : Intra(I_16x16_0_0_0)
slice_number : 0
transform_8x8 : 0
field\frame : frame
cbp bits
: 0000 00 00
: 0000 00 00
: 0000
: 0000
quant_param : 0
pmode : Intra_16x16
ipred : 16x16_Vertical

Same macroblock type. Same (zero) coded block pattern. Same prediction mode. Except that one is 1 bit, and the other is 15.  Both are CABAC; the only different is the state of the context table.

05/29/2008 (9:32 am)

Working at Avail Media

Filed under: avail,development,x264 ::

As some of you know, this summer I am living in Kalispell, Montana and working at Avail Media, a relatively small broadcast/IPTV company that caters primarily to smaller telecomms looking to set up IPTV and VOD services for reasonable prices. What’s unique about Avail, however, is that they don’t use hardware encoders; they use x264! They’re definitely not the only company using x264–other notable users include Google and Facebook–but I know of nobody else using x264 for live HD television. As the company which Loren Merritt (pengvado) worked for, they are responsible for quite a number of x264′s broadcast-related features, such as its interlaced encoding support.

Of course, broadcast has its own difficulties that make it much more of a challenge than ordinary offline encoding. For one, encoding has to run in realtime, quite a challenge when dealing with 1080i input. This is assisted by a patch written by Loren and improved by me, “speed control,” which automatically reconfigures x264′s settings on the fly to run at exactly the specified speed. It even communicates with the encoding/muxing frontend to know exactly how much time it really has left.

Another major issue is that of the VBV; the stream must strictly obey the buffer size or else packets might end up being dropped, corrupting the video stream. This is a hard problem, considering that x264′s VBV, especially in 1pass mode, is not very compliant. This has been a repeated subject of research by me even before I came here. Gabriel from Joost has also spent quite a bit of time on it in the form of his 2pass VBV patch, which in its latest form also improves 1pass VBV ratecontrol.

The biggest issue is the quality of the sources one comes across in broadcast–or better stated, the lack thereof. Much input is in the form of 18 megabit CBR MPEG-2 streams which are of such low quality that motion search above DIA/HEX is nearly useless. This is because in any scene with sufficient motion to require a complex motion search, the stream has already gone completely blocky. Re-encoding to 6-7 megabit H.264 doesn’t make it much better, either! This mess of input also results in a very large percentage of intra blocks in the output, which makes ratecontrol that much more difficult. Add this to the relative inefficiency of x264′s interlaced encoding and things get even worse.

Yet despite the difficulties of broadcast, Avail has managed to get it to work; quite an amazing accomplishment, proving once again that x264 isn’t just for ordinary offline 2pass encoding.

05/21/2008 (11:57 am)

Eliminating Pentium I support

Filed under: assembly,speed,x264 ::

With this change, we have finally eliminated support for all x86 CPUs that don’t support MMXEXT. More correctly, x264 compiled on an MMXEXT-supporting system will not run a non-MMXEXT system, so people who still use Pentium Is for their encoding will have to compile their own versions.

What exactly did we do? Its quite nice to be able to use MMX, CMOV, and other such extended x86 instructions in ordinary C code. Normal assembly code in x264 uses function pointers so that the best function is selected on runtime. But in a case where a performance gain can only be achieved through inlining, function pointers are useless. This is especially the case with small, simple functions that are called often, such as the x264_median in the above diff, used for motion vector prediction. A more extreme example was the CABAC asm, which got a >20% performance boost for CABAC encoding merely by changing a branch to a cmov (but which required the whole function to be rewritten in assembly).

Now, having officially eliminated support for all x86 CPU architectures prior to MMXEXT, we can feel free to throw MMX/CMOV code basically wherever we want in the code, allowing all kinds of small speedups in cases that groups of simple operations can be easily SIMD’d. Another note: the median assembly referenced at the start of this post is the first use of GCC inline assembly in x264′s history.

Edit: Since it appears that some people aren’t exactly clear on the point of this post, the program will still compile on a non-MMX machine; its just that code compiled on an MMX machine will not work on a non-MMX machine, whereas before it did.

05/16/2008 (11:43 pm)

Write combining

Filed under: gcc,speed,ugly code,x264 ::

Let’s say we need to copy a few variables from one array to another. The obvious way is something like this:

byte array1[4] = {1,2,3,4};
byte array2[4];
int i;
for(i = 0; i < 4; i++) array2[i] = array1[i];

But this is suboptimal for many reasons. For one, we’re doing 8-bit reads and writes, which on 32-bit systems may actually be slower than 32-bit reads and writes; i.e. a single 32-bit read/write may be faster than a single 8-bit read/write. But the main issue is that we could be doing this:

DECLARE_ALIGNED_4(byte array1[4] = {1,2,3,4});
DECLARE_ALIGNED_4(byte array2[4]);
*(uint32_t*)array2 = *(uint32_t*)array1;

In a single operation instead of 4, we just copied the whole array. Faster speed-wise and shorter code-wise, too. The alignment is to ensure that we don’t copy between unaligned arrays, which could crash on non-x86 architectures (e.g. PowerPC) and would also go slightly slower on x86 (but still faster than the uncombined write). But, one might ask, can’t the compiler do this? Well, there are many reasons it doesn’t happen. We’ll start from the easiest case and go to the hardest case.

The easiest case is a simple zeroing of a struct (say s={a,b} where a and b are 16-bit integers). The struct is likely to be aligned by the compiler to begin with and writing zero to {a,b} is the same as writing a 32-bit zero to the whole struct. But GCC doesn’t even optimize this; it still assigns the zeroes separately! How stupid.

The second-easiest case is the generalization of this; if you’re dealing with arrays in which the function is directly accessing them (rather than pointers to arrays, which it might not know whether they’re aligned or not) and assigning zero or constant value, write-combining is trivial. But again, GCC doesn’t do it.

Now, we get to the harder stuff. What if we’re copying between two arrays, both of which are directly accessed? Now, we have to be able to detect this sequential copying and merge it. This basically is a simple form of autovectorization; its no surprise at all that GCC doesn’t do this.

The hardest, and in fact nearly impossible case is the one in which we’re dealing with pointers to arrays as arguments; the compiler really has no reliable way of knowing that the pointers are aligned (though we as programmers might know that they always are). There are cases where it could make accurate derivations (by annotating pointers passed between functions) as to whether they are aligned or not, in which case it might be able to do write combining; this would of course be very difficult.  Of course, on x86, its still worthwhile to combine even if there’s a misalignment risk, since it will only go slightly slower rather than crash.

The end result of this kind of operation is a massive speed boost in such functions; for example, in the section where motion vectors are cached (in macroblock_cache_save) I got over double the speed by converting 16-bit copies to write-combined copies. This of course is only on a 32-bit system; on a 64-bit system we could do even better. The code of course uses 64-bit so that a 64-bit compiled binary will do it as best it can. The compiler is smart enough to split the copies on 32-bit systems, of course.

We could actually do even better if we were willing to use MMX or SSE, since MMX could be used for 64-bit copies on 32-bit systems and SSE could be used for 128-bit copies. Unfortunately, this would completely sacrifice portability and at this point the speed boost would be pretty small from the current merged copies.

One of the big tricks currently is the ability to treat two motion vectors as one, and since all motion vectors come in pairs (X and Y, 16-bit signed integers each), its quite easy to manipulate them as pairs. This allowed me to drastically speed up a lot of manipulation involved in motion vector prediction and general copying and storing. The result of all the issues described in the article is this massive diff.

« Previous Page — Next Page »