Diary Of An x264 Developer

05/25/2010 (11:01 pm)

Anatomy of an optimization: H.264 deblocking

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

As mentioned in the previous post, H.264 has an adaptive deblocking filter.  But what exactly does that mean — and more importantly, what does it mean for performance?  And how can we make it as fast as possible?  In this post I’ll try to answer these questions, particularly in relation to my recent deblocking optimizations in x264.

H.264′s deblocking filter has two steps: strength calculation and the actual filter.  The first step calculates the parameters for the second step.  The filter runs on all the edges in each macroblock.  That’s 4 vertical edges of length 16 pixels and 4 horizontal edges of length 16 pixels.  The vertical edges are filtered first, from left to right, then the horizontal edges, from top to bottom (order matters!).  The leftmost edge is the one between the current macroblock and the left macroblock, while the topmost edge is the one between the current macroblock and the top macroblock.

Here’s the formula for the strength calculation in progressive mode. The highest strength that applies is always selected.

If we’re on the edge between an intra macroblock and any other macroblock: Strength 4
If we’re on an internal edge of an intra macroblock: Strength 3
If either side of a 4-pixel-long edge has residual data: Strength 2
If the motion vectors on opposite sides of a 4-pixel-long edge are at least a pixel apart (in either x or y direction) or the reference frames aren’t the same: Strength 1
Otherwise: Strength 0 (no deblocking)

These values are then thrown into a lookup table depending on the quantizer: higher quantizers have stronger deblocking.  Then the actual filter is run with the appropriate parameters.  Note that Strength 4 is actually a special deblocking mode that performs a much stronger filter and affects more pixels.

One can see somewhat intuitively why these strengths are chosen.  The deblocker exists to get rid of sharp edges caused by the block-based nature of H.264, and so the strength depends on what exists that might cause such sharp edges.  The strength calculation is a way to use existing data from the video stream to make better decisions during the deblocking process, improving compression and quality.

Both the strength calculation and the actual filter (not described here) are very complex if naively implemented.  The latter can be SIMD’d with not too much difficulty; no H.264 decoder can get away with reasonable performance without such a thing.  But what about optimizing the strength calculation?  A quick analysis shows that this can be beneficial as well.

Since we have to check both horizontal and vertical edges, we have to check up to 32 pairs of coefficient counts (for residual), 16 pairs of reference frame indices, and 128 motion vector values (counting x and y as separate values).  This is a lot of calculation; a naive implementation can take 500-1000 clock cycles on a modern CPU.  Of course, there’s a lot of shortcuts we can take.  Here’s some examples:

  • If the macroblock uses the 8×8 transform, we only need to check 2 edges in each direction instead of 4, because we don’t deblock inside of the 8×8 blocks.
  • If the macroblock is a P-skip, we only have to check the first edge in each direction, since there’s guaranteed to be no motion vector differences, reference frame differences, or residual inside of the macroblock.
  • If the macroblock has no residual at all, we can skip that check.
  • If we know the partition type of the macroblock, we can do motion vector checks only along the edges of the partitions.
  • If the effective quantizer is so low that no deblocking would be performed no matter what, don’t bother calculating the strength.

But even all of this doesn’t save us from ourselves.  We still have to iterate over a ton of edges, checking each one.  Stuff like the partition-checking logic greatly complicates the code and adds overhead even as it reduces the number of checks.  And in many cases decoupling the checks to add such logic will make it slower: if the checks are coupled, we can avoid doing a motion vector check if there’s residual, since Strength 2 overrides Strength 1.

But wait.  What if we could do this in SIMD, just like the actual loopfilter itself?  Sure, it seems more of a problem for C code than assembly, but there aren’t any obvious things in the way.  Many years ago, Loren Merritt (pengvado) wrote the first SIMD implementation that I know of (for ffmpeg’s decoder); it is quite fast, so I decided to work on porting the idea to x264 to see if we could eke out a bit more speed here as well.

Before I go over what I had to do to make this change, let me first describe how deblocking is implemented in x264.  Since the filter is a loopfilter, it acts “in loop” and must be done in both the encoder and decoder — hence why x264 has it too, not just decoders.  At the end of encoding one row of macroblocks, x264 goes back and deblocks the row, then performs half-pixel interpolation for use in encoding the next frame.

We do it per-row for reasons of cache coherency: deblocking accesses a lot of pixels and a lot of code that wouldn’t otherwise be used, so it’s more efficient to do it in a single pass as opposed to deblocking each macroblock immediately after encoding.  Then half-pixel interpolation can immediately re-use the resulting data.

Now to the change.  First, I modified deblocking to implement a subset of the macroblock_cache_load function: spend an extra bit of effort loading the necessary data into a data structure which is much simpler to address — as an assembly implementation would need (x264_macroblock_cache_load_deblock).  Then I massively cleaned up deblocking to move all of the core strength-calculation logic into a single, small function that could be converted to assembly (deblock_strength_c).  Finally, I wrote the assembly functions and worked with Loren to optimize them.  Here’s the result.

And the timings for the resulting assembly function on my Core i7, in cycles:

deblock_strength_c: 309
deblock_strength_mmx: 79
deblock_strength_sse2: 37
deblock_strength_ssse3: 33

Now that is a seriously nice improvement. 33 cycles on average to perform that many comparisons–that’s absurdly low, especially considering the SIMD takes no branchy shortcuts: it always checks every single edge!  I walked over to my performance chart and happily crossed off a box.

But I had a hunch that I could do better.  Remember, as mentioned earlier, we’re reloading all that data back into our data structures in order to address it.  This isn’t that slow, but takes enough time to significantly cut down on the gain of the assembly code.  And worse, less than a row ago, all this data was in the correct place to be used (when we just finished encoding the macroblock)!  But if we did the deblocking right after encoding each macroblock, the cache issues would make it too slow to be worth it (yes, I tested this).  So I went back to other things, a bit annoyed that I couldn’t get the full benefit of the changes.

Then, yesterday, I was talking with Pascal, a former Xvid dev and current video hacker over at Google, about various possible x264 optimizations.  He had seen my deblocking changes and we discussed that a bit as well.  Then two lines hit me like a pile of bricks:

<_skal_> tried computing the strength at least?
<_skal_> while it’s fresh

Why hadn’t I thought of that?  Do the strength calculation immediately after encoding each macroblock, save the result, and then go pick it up later for the main deblocking filter.  Then we can use the data right there and then for strength calculation, but we don’t have to do the whole deblock process until later.

I went and implemented it and, after working my way through a horde of bugs, eventually got a working implementation.  A big catch was that of slices: deblocking normally acts between slices even though normal encoding does not, so I had to perform extra munging to get that to work.  By midday today I was able to go cross yet another box off on the performance chart.  And now it’s committed.

Sometimes chatting for 10 minutes with another developer is enough to spot the idea that your brain somehow managed to miss for nearly a straight week.

NB: the performance chart is on a specific test clip at a specific set of settings (super fast settings) relevant to the company I work at, so it isn’t accurate nor complete for, say, default settings.

Update: Here’s a higher resolution version of the current chart, as requested in the comments.

18 Responses to “Anatomy of an optimization: H.264 deblocking”

  1. Michael Says:

    I’m sure you hear this a lot but: holy crap, excellent work!

    Do you have a slightly higher resolution picture of the performance chart?

  2. Dark Shikari Says:


    I’ll go take a better one at work tomorrow :)

  3. saintdev Says:

    Sometimes all it takes is another perspective on the issue.

  4. Fruit Says:

    Thanks for your work :)
    BTW, do you think that doing the strength calculation outside the deblocking pass (during macroblock decode*, I guess?) could be also applied to lavc decoder?

    *not sure I got the right idea of how it is structured in decoder…

  5. shon3i Says:

    What you think about adaptive deblocker, as in Ateme?

  6. Dark Shikari Says:


    Yes, it can be applied to lavc. I’ve already poked Michael Niedermayer about it ;)

  7. Anonymous Says:

    This reminds me of something – performing deblocking after the fact means that the ‘D’ in RDO works over something else than the final picture.

    Now I remember somebody (pengvado?) saying deblocking doesn’t change metrics such as PSNR much (except it helps providing better prediction for future frames). However, I was wondering how this affects psy-rd optimizations.

  8. Dark Shikari Says:


    This is definitely something to try; I’ve tried it before but haven’t gotten it to work, but there’s no reason that it shouldn’t, so I probably screwed up.

    It will probably favor 8x8dct, as that will mean less deblocking.

  9. Denis Says:

    please comment next ‘rollback’ commit:
    Stats need to be calculated before deblock strength, not after.

  10. Scaevolus Says:

    What percentage speed increase does this provide on your test clip?

  11. Anon Says:

    so just a noob here wondering what will be the effect of this optimization on deblocking? will it remove more blocking artifacts on videos? will this optimization affect all x264 video encodes even older video encodes?

    and thumbs up to your great work Dark Shikari

  12. John Says:

    Thanks for taking the time to discuss these technical topics (H.264 deblocking, VP8, wavelets, etc.) in a way that average people like me can understand.

    I would like to suggest that you include more diagrams and other visual illustrations in your posts for visual people like me to quickly and easily grasp and understand the meat of your posts (instead of having to read every line of text at least 5 times and hoping that I have the right visualization in mind).

    If you have the time, it would be nice of you to include diagrams and other illustrations in this post and in some of your previous technical posts for future reference.
    P.S. Don’t hold back on those visual illustrations; we always want more than what you’ve included already. ;)

    Thanks for reading!

  13. Esurnir Says:

    stupid question : What’s 10l?

  14. D3C0D3R Says:

    Meanwhile, x264 clearly wons MSU comparsion with a crushing score.
    Moreover it has incredible speed – beating concurents with ratio and speed both.
    In last year Mainconcept was faster and has better PNSR, but x264 beats it on SSIM.
    Now it simply best.
    Theora – big looose.

    @Dark Shikari
    Huge Respect 4 further improving best 264 encoder in world.

  15. D3C0D3R Says:

    As I undestand Dark cutted redudant work
    and wisely use SSE and cache for serious speed-up.
    After that he used some loopy trick to save even more clocks.
    it just giving us little bit faster encoding process

  16. Anon Says:


    oh i see now i fully understand that when Dark says Optimizations its speeding up the encoding process

    thanks for that explanation

  17. lycium Says:

    very interesting blog you have here :)

    i was esp interested to hear about skal, the oh-so-legendary french demoscene coder!

  18. george stanton Says:

    hey dark shikari, great stuff!

    but have you considered further defining filter strength based on whether or not neighboring blocks have been INTRA BL (base layer) predicted?

    in multilayer, since a frame of an upper layer can be predicted from a frame of a lower layer (intra BL), the prediction results in very similar data.

    thus, if you have already deblocked the lower layer, and when you get to the upper layer, you may not need to deblock again. or if you still decide to deblock, your deblocking strength can be much less (i.e. fewer calculations).

    what do you think?


Leave a Reply