1 /*****************************************************************************
2 * rdo.c: h264 encoder library (rate-distortion optimization)
3 *****************************************************************************
4 * Copyright (C) 2005 x264 project
6 * Authors: Loren Merritt <lorenm@u.washington.edu>
8 * This program is free software; you can redistribute it and/or modify
9 * it under the terms of the GNU General Public License as published by
10 * the Free Software Foundation; either version 2 of the License, or
11 * (at your option) any later version.
13 * This program is distributed in the hope that it will be useful,
14 * but WITHOUT ANY WARRANTY; without even the implied warranty of
15 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 * GNU General Public License for more details.
18 * You should have received a copy of the GNU General Public License
19 * along with this program; if not, write to the Free Software
20 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111, USA.
21 *****************************************************************************/
23 /* duplicate all the writer functions, just calculating bit cost
24 * instead of writing the bitstream.
25 * TODO: use these for fast 1st pass too. */
29 /* CAVLC: produces exactly the same bit count as a normal encode */
30 /* this probably still leaves some unnecessary computations */
31 #define bs_write1(s,v) ((s)->i_bits_encoded += 1)
32 #define bs_write(s,n,v) ((s)->i_bits_encoded += (n))
33 #define bs_write_ue(s,v) ((s)->i_bits_encoded += bs_size_ue(v))
34 #define bs_write_se(s,v) ((s)->i_bits_encoded += bs_size_se(v))
35 #define bs_write_te(s,v,l) ((s)->i_bits_encoded += bs_size_te(v,l))
36 #define x264_macroblock_write_cavlc x264_macroblock_size_cavlc
39 /* CABAC: not exactly the same. x264_cabac_size_decision() keeps track of
40 * fractional bits, but only finite precision. */
41 #define x264_cabac_encode_decision(c,x,v) x264_cabac_size_decision(c,x,v)
42 #define x264_cabac_encode_terminal(c,v) x264_cabac_size_decision(c,276,v)
43 #define x264_cabac_encode_bypass(c,v) ((c)->f8_bits_encoded += 256)
44 #define x264_cabac_encode_flush(c)
45 #define x264_macroblock_write_cabac x264_macroblock_size_cabac
46 #define x264_cabac_mb_skip x264_cabac_mb_size_skip_unused
50 static int x264_rd_cost_mb( x264_t *h, int i_lambda2 )
52 int b_transform_bak = h->mb.b_transform_8x8;
56 x264_macroblock_encode( h );
58 i_ssd = h->pixf.ssd[PIXEL_16x16]( h->mb.pic.p_fenc[0], h->mb.pic.i_stride[0],
59 h->mb.pic.p_fdec[0], h->mb.pic.i_stride[0] )
60 + h->pixf.ssd[PIXEL_8x8]( h->mb.pic.p_fenc[1], h->mb.pic.i_stride[1],
61 h->mb.pic.p_fdec[1], h->mb.pic.i_stride[1] )
62 + h->pixf.ssd[PIXEL_8x8]( h->mb.pic.p_fenc[2], h->mb.pic.i_stride[2],
63 h->mb.pic.p_fdec[2], h->mb.pic.i_stride[2] );
65 if( IS_SKIP( h->mb.i_type ) )
67 i_bits = 1 * i_lambda2;
69 else if( h->param.b_cabac )
71 x264_cabac_t cabac_tmp = h->cabac;
72 cabac_tmp.f8_bits_encoded = 0;
73 x264_macroblock_size_cabac( h, &cabac_tmp );
74 i_bits = ( cabac_tmp.f8_bits_encoded * i_lambda2 + 128 ) >> 8;
78 bs_t bs_tmp = h->out.bs;
79 bs_tmp.i_bits_encoded = 0;
80 x264_macroblock_size_cavlc( h, &bs_tmp );
81 i_bits = bs_tmp.i_bits_encoded * i_lambda2;
84 h->mb.b_transform_8x8 = b_transform_bak;
86 return i_ssd + i_bits;
90 /****************************************************************************
91 * Trellis RD quantization
92 ****************************************************************************/
94 #define TRELLIS_SCORE_MAX (1ULL<<50)
95 #define CABAC_SIZE_BITS 8
96 #define SSD_WEIGHT_BITS 5
99 /* precalculate the cost of coding abs_level_m1 */
100 static int cabac_prefix_transition[15][128];
101 static int cabac_prefix_size[15][128];
102 void x264_rdo_init( )
106 for( i_prefix = 0; i_prefix < 15; i_prefix++ )
108 for( i_ctx = 0; i_ctx < 128; i_ctx++ )
114 for( i = 1; i < i_prefix; i++ )
115 f8_bits += x264_cabac_size_decision2( &ctx, 1 );
116 if( i_prefix > 0 && i_prefix < 14 )
117 f8_bits += x264_cabac_size_decision2( &ctx, 0 );
118 f8_bits += 1 << CABAC_SIZE_BITS; //sign
120 cabac_prefix_size[i_prefix][i_ctx] = f8_bits;
121 cabac_prefix_transition[i_prefix][i_ctx] = ctx;
126 // node ctx: 0..3: abslevel1 (with abslevelgt1 == 0).
127 // 4..7: abslevelgt1 + 3 (and abslevel1 doesn't matter).
128 /* map node ctx => cabac ctx for level=1 */
129 static const int coeff_abs_level1_ctx[8] = { 1, 2, 3, 4, 0, 0, 0, 0 };
130 /* map node ctx => cabac ctx for level>1 */
131 static const int coeff_abs_levelgt1_ctx[8] = { 5, 5, 5, 5, 6, 7, 8, 9 };
132 static const int coeff_abs_level_transition[2][8] = {
133 /* update node.ctx after coding a level=1 */
134 { 1, 2, 3, 3, 4, 5, 6, 7 },
135 /* update node.ctx after coding a level>1 */
136 { 4, 4, 4, 4, 5, 6, 7, 7 }
139 static const int lambda2_tab[6] = { 1024, 1290, 1625, 2048, 2580, 3251 };
143 int level_idx; // index into level_tree[]
144 uint8_t cabac_state[10]; //just the contexts relevant to coding abs_level_m1
148 // support chroma and i16x16 DC
149 // save cabac state between blocks?
150 // use trellis' RD score instead of x264_mb_decimate_score?
151 // code 8x8 sig/last flags forwards with deadzone and save the contexts at
153 // change weights when using CQMs?
155 // possible optimizations:
156 // make scores fit in 32bit
157 // save quantized coefs during rd, to avoid a duplicate trellis in the final encode
158 // if trellissing all MBRD modes, finish SSD calculation so we can skip all of
159 // the normal dequant/idct/ssd/cabac
161 // the unquant_mf here is not the same as dequant_mf:
162 // in normal operation (dct->quant->dequant->idct) the dct and idct are not
163 // normalized. quant/dequant absorb those scaling factors.
164 // in this function, we just do (quant->unquant) and want the output to be
165 // comparable to the input. so unquant is the direct inverse of quant,
166 // and uses the dct scaling factors, not the idct ones.
168 static void quant_trellis_cabac( x264_t *h, int16_t *dct,
169 const int *quant_mf, const int *unquant_mf,
170 const int *coef_weight, const int *zigzag,
171 int i_ctxBlockCat, int i_qbits, int i_lambda2, int b_ac, int i_coefs )
173 int abs_coefs[64], signs[64];
174 trellis_node_t nodes[2][8];
175 trellis_node_t *nodes_cur = nodes[0];
176 trellis_node_t *nodes_prev = nodes[1];
177 trellis_node_t *bnode;
178 uint8_t cabac_state_sig[64];
179 uint8_t cabac_state_last[64];
180 const int f = 1 << (i_qbits-1); // no deadzone
184 // (# of coefs) * (# of ctx) * (# of levels tried) = 1024
185 // we don't need to keep all of those: (# of coefs) * (# of ctx) would be enough,
186 // but it takes more time to remove dead states than you gain in reduced memory.
190 } level_tree[64*8*2];
191 int i_levels_used = 1;
194 for( i = b_ac; i < i_coefs; i++ )
196 int coef = dct[zigzag[i]];
197 abs_coefs[i] = abs(coef);
198 signs[i] = coef < 0 ? -1 : 1;
199 if( f <= abs_coefs[i] * quant_mf[zigzag[i]] )
203 if( i_last_nnz == -1 )
205 memset( dct, 0, i_coefs * sizeof(*dct) );
210 for( i = 1; i < 8; i++ )
211 nodes_cur[i].score = TRELLIS_SCORE_MAX;
212 nodes_cur[0].score = 0;
213 nodes_cur[0].level_idx = 0;
214 level_tree[0].abs_level = 0;
215 level_tree[0].next = 0;
217 // coefs are processed in reverse order, because that's how the abs value is coded.
218 // last_coef and significant_coef flags are normally coded in forward order, but
219 // we have to reverse them to match the levels.
220 // in 4x4 blocks, last_coef and significant_coef use a separate context for each
221 // position, so the order doesn't matter, and we don't even have to update their contexts.
222 // in 8x8 blocks, some positions share contexts, so we'll just have to hope that
223 // cabac isn't too sensitive.
227 const uint8_t *ctx_sig = &h->cabac.state[ significant_coeff_flag_offset[i_ctxBlockCat] ];
228 const uint8_t *ctx_last = &h->cabac.state[ last_coeff_flag_offset[i_ctxBlockCat] ];
229 for( i = 0; i < 63; i++ )
231 cabac_state_sig[i] = ctx_sig[ significant_coeff_flag_offset_8x8[i] ];
232 cabac_state_last[i] = ctx_last[ last_coeff_flag_offset_8x8[i] ];
237 memcpy( cabac_state_sig, &h->cabac.state[ significant_coeff_flag_offset[i_ctxBlockCat] ], 15 );
238 memcpy( cabac_state_last, &h->cabac.state[ last_coeff_flag_offset[i_ctxBlockCat] ], 15 );
240 memcpy( nodes_cur[0].cabac_state, &h->cabac.state[ coeff_abs_level_m1_offset[i_ctxBlockCat] ], 10 );
242 for( i = i_last_nnz; i >= b_ac; i-- )
244 int i_coef = abs_coefs[i];
245 int q = ( f + i_coef * quant_mf[zigzag[i]] ) >> i_qbits;
247 int cost_sig[2], cost_last[2];
250 // skip 0s: this doesn't affect the output, but saves some unnecessary computation.
253 // no need to calculate ssd of 0s: it's the same in all nodes.
254 // no need to modify level_tree for ctx=0: it starts with an infinite loop of 0s.
255 const int cost_sig0 = x264_cabac_size_decision_noup( &cabac_state_sig[i], 0 )
256 * i_lambda2 >> ( CABAC_SIZE_BITS - LAMBDA_BITS );
257 for( j = 1; j < 8; j++ )
259 if( nodes_cur[j].score != TRELLIS_SCORE_MAX )
261 #define SET_LEVEL(n,l) \
262 level_tree[i_levels_used].abs_level = l; \
263 level_tree[i_levels_used].next = n.level_idx; \
264 n.level_idx = i_levels_used; \
267 SET_LEVEL( nodes_cur[j], 0 );
268 nodes_cur[j].score += cost_sig0;
274 XCHG( trellis_node_t*, nodes_cur, nodes_prev );
276 for( j = 0; j < 8; j++ )
277 nodes_cur[j].score = TRELLIS_SCORE_MAX;
281 cost_sig[0] = x264_cabac_size_decision_noup( &cabac_state_sig[i], 0 );
282 cost_sig[1] = x264_cabac_size_decision_noup( &cabac_state_sig[i], 1 );
283 cost_last[0] = x264_cabac_size_decision_noup( &cabac_state_last[i], 0 );
284 cost_last[1] = x264_cabac_size_decision_noup( &cabac_state_last[i], 1 );
288 cost_sig[0] = cost_sig[1] = 0;
289 cost_last[0] = cost_last[1] = 0;
292 // there are a few cases where increasing the coeff magnitude helps,
293 // but it's only around .003 dB, and skipping them ~doubles the speed of trellis.
294 // could also try q-2: that sometimes helps, but also sometimes decimates blocks
295 // that are better left coded, especially at QP > 40.
296 for( abs_level = q; abs_level >= q-1; abs_level-- )
298 int d = i_coef - ((unquant_mf[zigzag[i]] * abs_level + 128) >> 8);
299 uint64_t ssd = (int64_t)d*d * coef_weight[i];
301 for( j = 0; j < 8; j++ )
304 if( nodes_prev[j].score == TRELLIS_SCORE_MAX )
308 /* code the proposed level, and count how much entropy it would take */
309 if( abs_level || node_ctx )
311 unsigned f8_bits = cost_sig[ abs_level != 0 ];
314 const int i_prefix = X264_MIN( abs_level - 1, 14 );
315 f8_bits += cost_last[ node_ctx == 0 ];
316 f8_bits += x264_cabac_size_decision2( &n.cabac_state[coeff_abs_level1_ctx[node_ctx]], i_prefix > 0 );
319 uint8_t *ctx = &n.cabac_state[coeff_abs_levelgt1_ctx[node_ctx]];
320 f8_bits += cabac_prefix_size[i_prefix][*ctx];
321 *ctx = cabac_prefix_transition[i_prefix][*ctx];
322 if( abs_level >= 15 )
323 f8_bits += bs_size_ue( abs_level - 15 ) << CABAC_SIZE_BITS;
324 node_ctx = coeff_abs_level_transition[1][node_ctx];
328 f8_bits += 1 << CABAC_SIZE_BITS;
329 node_ctx = coeff_abs_level_transition[0][node_ctx];
332 n.score += (uint64_t)f8_bits * i_lambda2 >> ( CABAC_SIZE_BITS - LAMBDA_BITS );
337 /* save the node if it's better than any existing node with the same cabac ctx */
338 if( n.score < nodes_cur[node_ctx].score )
340 SET_LEVEL( n, abs_level );
341 nodes_cur[node_ctx] = n;
347 /* output levels from the best path through the trellis */
348 bnode = &nodes_cur[0];
349 for( j = 1; j < 8; j++ )
350 if( nodes_cur[j].score < bnode->score )
351 bnode = &nodes_cur[j];
353 j = bnode->level_idx;
354 for( i = b_ac; i < i_coefs; i++ )
356 dct[zigzag[i]] = level_tree[j].abs_level * signs[i];
357 j = level_tree[j].next;
362 void x264_quant_4x4_trellis( x264_t *h, int16_t dct[4][4], int i_quant_cat,
363 int i_qp, int i_ctxBlockCat, int b_intra )
365 const int i_qbits = i_qp / 6;
366 const int i_mf = i_qp % 6;
367 const int b_ac = (i_ctxBlockCat == DCT_LUMA_AC);
368 /* should the lambdas be different? I'm just matching the behaviour of deadzone quant. */
369 const int i_lambda_mult = b_intra ? 65 : 85;
370 const int i_lambda2 = ((lambda2_tab[i_mf] * i_lambda_mult*i_lambda_mult / 10000)
371 << (2*i_qbits)) >> LAMBDA_BITS;
373 quant_trellis_cabac( h, (int16_t*)dct,
374 (int*)h->quant4_mf[i_quant_cat][i_mf], h->unquant4_mf[i_quant_cat][i_qp],
375 x264_dct4_weight2_zigzag, x264_zigzag_scan4,
376 i_ctxBlockCat, 15+i_qbits, i_lambda2, b_ac, 16 );
380 void x264_quant_8x8_trellis( x264_t *h, int16_t dct[8][8], int i_quant_cat,
381 int i_qp, int b_intra )
383 const int i_qbits = i_qp / 6;
384 const int i_mf = i_qp % 6;
385 const int i_lambda_mult = b_intra ? 65 : 85;
386 const int i_lambda2 = ((lambda2_tab[i_mf] * i_lambda_mult*i_lambda_mult / 10000)
387 << (2*i_qbits)) >> LAMBDA_BITS;
389 quant_trellis_cabac( h, (int16_t*)dct,
390 (int*)h->quant8_mf[i_quant_cat][i_mf], h->unquant8_mf[i_quant_cat][i_qp],
391 x264_dct8_weight2_zigzag, x264_zigzag_scan8,
392 DCT_LUMA_8x8, 16+i_qbits, i_lambda2, 0, 64 );