Chroma encoding revisited
Chroma has always been a ripe target for optimization. We have to perform transform+quantization on every block, but the vast majority of blocks end up having not a single nonzero coefficient to code, so it seems as if we wasted our time doing all that arithmetic only to find out that there was no information there anyways. But we can’t just skip it, because the few times that there are coefficients, they are very important. Part of this problem is unique to H.264, which has a quite curious method of encoding its chroma, which I will describe here for those not familiar with it.
For each chroma channel in the current macroblock, 4 4×4 transforms are performed on the residual, making up an 8×8 block. Then, the DC coefficients of each transform are collected and put into a separate 2×2 block, which is transformed again with a Hadamard transform. In the bitstream, the encoder can signal three modes, which apply to both chroma channels. The first mode, 0, simply says there is no chroma data. The second mode, 1, says there is DC data, but not AC data (the rest of the coefficients that weren’t put into that special 2×2 block). The third mode, 2, says that there is both DC and AC data. Since having AC but not DC data is extremely rare, there is no special mode for this.
Here’s some sample stats from a 720p video encoded at 4.5 megabits per second:
coded y,uvDC,uvAC inter:26.5% 9.4% 0.3%
Over one quarter of 8×8 blocks have nonzero luma coefficients. But only 9.4% of chroma blocks even have DC coefficients, and a pathetic 0.3% have AC coefficients. The reason for the bizarre coding scheme outlined above is exactly that: it’s very rare to have significant chroma information, so the extra DC transformation is designed to localize the most common data as best as possible so that the rest can be coded as rarely as possible.
Clearly, the vast majority of chroma blocks have no information at all, and even in those that do, all our time spent calculating AC coefficients is wasted 97% of the time. We need a fast way of accurately terminating in the case of a DC-only or empty block. We can’t make any mistakes, because doing so could impact quality. So, what should we do?
First, we’ll go back to mid-2008 and look at this commit. Hidden in this somewhat complex commit was the following change:
“Add an SSD threshold for chroma in probe_skip to improve speed and minimize time spent on chroma skip analysis.”
In probe_skip, luma and chroma are checked sequentially in order to determine whether a block can be skipped. This involves doing a transform, quantizing the results, and running decimate_score to see if the block can be cleared. As per the above “coded blocks” numbers, since luma is coded vastly more often than chroma, if analysis of luma suggests the block can be skipped, the analysis of chroma will almost always agree. But we can’t skip the check entirely, since that could result in artifacts if a block had significant chroma residual but no luma residual. But we can take a shortcut.
Parseval’s Theorem states that the sum of the squares of a set of data is equivalent to the sum of squares of the transform of that data. This means that if we take the sum of squares of the residual data, we know the amount of energy in the frequency domain, too. So, if we take the sum of squares of the residual data and find it to be sufficiently low, we can skip the full check.
Now, let’s move forward half a year to this commit. Again, hidden in the commit message is this gem:
“adding special-case idct_dc function, since most coded chroma blocks are DC-only.”
Since after transforming and quantizing the block, we know whether it’s DC-only or not, we can branch based on this and do a special DC-only inverse-transform in such a case, saving a lot of time. This is quite similar to what many decoders do.
Let’s go forward another 3 months to this commit. This goes back to the probe_skip function, where it adds a threshold equal to 4 times the original SSD threshold in the case that the first threshold failed, but after encoding the DC data, it was found that there were no DC coefficients. In such a case, since small numbers of AC coefficients get decimated, we can check against a much higher threshold without losing any accuracy.
Now, combine the ideas from these commits and turn them up to 11. Let’s go back to the idea of taking sum of squares of the residual data as a method of predicting whether or not there will be nonzero coefficients after quantization. If we take the variance instead of the sum of squares–in other words, we subtract out the average–we eliminate the DC coefficient, since the DC coefficient is simply equal to the average of the input data. With relatively little calculation, we now have the energy of the AC data.
If we sum this over both chroma channels and compare to the lambda value, which represents the “value” of residual in terms of bits, we can estimate the maximum number of bits’ worth of AC coefficients that exist in the block. If that value is small, we know for sure that the block will not have AC coefficients, as x264 already decimates chroma blocks that contain very few AC coefficients. Thus, I made the decision to early terminate if that number was less than 16 bits’ worth of AC data.
Now that we’ve early terminated, what do we do? Well, we still have the data from earlier–the sum of squares of the block. We can threshold this individually for each of the chroma channels. If the number of bits’ worth of sum of squares is less than 4, we don’t even encode the block at all–we just skip it entirely, figuring that there will not be any DC coefficients with such a small residual. Now we get to the final step: we’ve early-terminated, but there’s still a large enough residual that we have to encode the DC coefficients. Now, we can take yet another shortcut.
A frequency transform is rather complicated; usually it involves a 1-dimensional transform, then a transpose, and then the same transform again. One common shortcut taken during video decoding is to detect blocks which only contain a DC coefficient and use a faster “idct_dc” for them, which only needs to add the single DC value to all of the elements of the output block. But normally you can’t take this shortcut in encoding, because you don’t know yet that the block will only have DC coefficients. But, due to what we know from above… we do know that. So we can do a forward transform that ignores all non-DC data. This literally just means summing up the residual data in each of the 4×4 blocks, which is a cinch in SIMD. We’ve reduced a complicated transform to a simple sum, saving an enormous amount of time.
A very attentive reader might have noticed a problem with the above. Chroma consists of 4 4×4 transforms, but we did a sum of squares and variance over the whole 8×8 block. This means that differences in DC value between the 4 4×4 blocks will be incorrectly counted as AC energy. Fortunately, testing showed that doing this “correctly” helped minimally in terms of termination accuracy on real content and merely forced the variance function to be significantly more complicated in order to sum the variances of 4 separate blocks instead of one big block.
Another potential problem with this scheme is that at very low quantizers (high bitrates), the relationship described at the beginning is no longer true; nearly all blocks contain coefficients at such high bitrates, so it is no longer worthwhile to spend extra time checking for an early termination that will almost never happen. The threshold for this depends on how long it takes to do the chroma encode; with trellis off, tests showed the threshold to be about QP=18, and with trellis on the threshold was around QP=12 due to the vastly slower encoding with trellis on. So I just added a check to not run the early termination at such low QPs.
So how much does this help overall? Benchmarks show that it gives about a 1-2% performance boost with trellis off and as high as 6% with trellis on. Lower bitrates unsurprisingly gain more due to having more near-empty chroma blocks.
Finally, let’s analyze the actual code for the core of this change.
if( b_decimate && i_qp >= (h->mb.b_trellis ? 12 : 18) && !h->mb.b_lossless )
Only run this code if decimation is on, lossless is off, and our QP is above the threshold determined earlier.
int thresh = (x264_lambda2_tab[i_qp] + 32) >> 6;
“thresh” is 4 bits. Lambda is stored as a fixed-point with 8 bits of fractional precision (“FIX8″), so shift right by 6 with correct rounding to get 4 bits.
int ssd[2];
int score0 = h->pixf.var2_8x8( h->mb.pic.p_fenc[1], FENC_STRIDE, h->mb.pic.p_fdec[1], FDEC_STRIDE, &ssd[0] );
int score1 = h->pixf.var2_8x8( h->mb.pic.p_fenc[2], FENC_STRIDE, h->mb.pic.p_fdec[2], FDEC_STRIDE, &ssd[1] );
int score = score0 + score1;
ssd[0] and ssd[1] are the sum of squares for the two channels, and score is the sum of the variances, where variance is defined as SumOfSquares – (Sum)^2 / N, where N is the number of elements in the input data.
if( score < thresh*4 )
If the total AC energy is less than 16 bits, perform the early termination.
h->mb.cache.non_zero_count[x264_scan8[16]] = 0;
h->mb.cache.non_zero_count[x264_scan8[17]] = 0;
h->mb.cache.non_zero_count[x264_scan8[18]] = 0;
h->mb.cache.non_zero_count[x264_scan8[19]] = 0;
h->mb.cache.non_zero_count[x264_scan8[20]] = 0;
h->mb.cache.non_zero_count[x264_scan8[21]] = 0;
h->mb.cache.non_zero_count[x264_scan8[22]] = 0;
h->mb.cache.non_zero_count[x264_scan8[23]] = 0;
Zero all the nonzero counts for the AC coefficient blocks, since we’ve declared these to be zero.
h->mb.cache.non_zero_count[x264_scan8[25]] = 0;
h->mb.cache.non_zero_count[x264_scan8[26]] = 0;
Zero the DC coefficient blocks too; we’ll assume them to be zero unless the code later sets them to be nonzero.
for( ch = 0; ch < 2; ch++ )
Loop over the two chroma channels.
if( ssd[ch] > thresh )
If the sum of squares of the channel’s residual is greater than the threshold (4 bits), continue, otherwise completely skip the block.
h->dctf.sub8x8_dct_dc( dct2x2, h->mb.pic.p_fenc[1+ch], h->mb.pic.p_fdec[1+ch] );
dct2x2dc_dconly( dct2x2 );
Perform a DC-only forward transform, then do the Hadamard transform on the output of that.
if( h->mb.b_trellis )
nz_dc = x264_quant_dc_trellis( h, (int16_t*)dct2x2, CQM_4IC+b_inter, i_qp, DCT_CHROMA_DC, !b_inter );
else
nz_dc = h->quantf.quant_2x2_dc( dct2x2, h->quant4_mf[CQM_4IC+b_inter][i_qp][0]>>1, h->quant4_bias[CQM_4IC+b_inter][i_qp][0]<<
1 );
Quantize the DC block.
h->mb.cache.non_zero_count[x264_scan8[25]+ch] = nz_dc;
Store the results of the quantization, whether the block was nonzero or not.
if( nz_dc )
{
zigzag_scan_2x2_dc( h->dct.chroma_dc[ch], dct2x2 );
idct_dequant_2x2_dconly( dct2x2, h->dequant4_mf[CQM_4IC + b_inter], i_qp );
h->dctf.add8x8_idct_dc( h->mb.pic.p_fdec[1+ch], dct2x2 );
h->mb.i_cbp_chroma = 1;
}
If the block is nonzero, store the coefficients, dequant and inverse-Hadamard-transform them, and then perform a DC-only inverse transform to store the resulting pixel data. Set the chroma coded block pattern to 1, to indicate that there were DC coefficients.
The full patch as of the time of writing this can be found here. It will probably be changed somewhat before the final commit.
As can be seen from the commits originally discussed, this change was over a year in coming; it evolved from a simple curiosity in mid-2008 to a full-fledged termination smack in the middle of the main encoding loop. Good ideas have to gestate before they truly come to fruition.
July 12th, 2009 at 9:36 am
Nice work — it’s great to see how much thought and testing goes into “small” diffs. Blog more
October 22nd, 2009 at 8:21 am
The topic you research in technical literature is called “early detection of all-zero blocks” or shortly “early detection of AZB”.
I think the following articles are interesting for you:
1) “An Improved Early Detection Algorithm for
All-Zero Blocks in H.264 Video Encoding”,Yong Ho Moon, Gyu Yeong Kim, and Jae Ho Kim,IEEE TRANSACTIONS ON CIRCUITS AND SYSTEMS FOR VIDEO TECHNOLOGY, VOL. 15, NO. 8, AUGUST 2005
2) “An adaptive and fast fractional pixel search algorithm in H.264″, Liquan Shena, Zhaoyang Zhanga, Zhi Liua, Wenjun Zhang, Signal Processing 87 (2007) 2629–2639
3) “An Enhanced Detection Algorithm for All-Zero Blocks in H.264 Video Coding”, Chung-Yen Su, IEEE Transactions on Consumer Electronics, Vol. 52, No. 2, MAY 2006
4)”Efficient Prediction Algorithm of Integer DCT Coefficients for H.264/AVC Optimization”, Hanli Wang, Student Member, Sam Kwong, Senior Member, IEEE, and Chi-Wah Kok, Senior Member, IEEE, IEEE TRANSACTIONS ON CIRCUITS AND SYSTEMS FOR VIDEO TECHNOLOGY, VOL. 16, NO. 4, APRIL 2006
If you have a difficulty to obtain the above papers let me know I can send you a digital copy.