1 /*****************************************************************************
2 * slicetype.c: h264 encoder library
3 *****************************************************************************
4 * Copyright (C) 2005-2008 x264 project
6 * Authors: Loren Merritt <lorenm@u.washington.edu>
7 * Fiona Glaser <fiona@x264.com>
9 * This program is free software; you can redistribute it and/or modify
10 * it under the terms of the GNU General Public License as published by
11 * the Free Software Foundation; either version 2 of the License, or
12 * (at your option) any later version.
14 * This program is distributed in the hope that it will be useful,
15 * but WITHOUT ANY WARRANTY; without even the implied warranty of
16 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
17 * GNU General Public License for more details.
19 * You should have received a copy of the GNU General Public License
20 * along with this program; if not, write to the Free Software
21 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02111, USA.
22 *****************************************************************************/
26 #include "common/common.h"
27 #include "common/cpu.h"
28 #include "macroblock.h"
32 static void x264_lowres_context_init( x264_t *h, x264_mb_analysis_t *a )
34 a->i_qp = X264_LOOKAHEAD_QP;
35 a->i_lambda = x264_lambda_tab[ a->i_qp ];
36 x264_mb_analyse_load_costs( h, a );
37 h->mb.i_me_method = X264_MIN( X264_ME_HEX, h->param.analyse.i_me_method ); // maybe dia?
38 h->mb.i_subpel_refine = 4; // 3 should be enough, but not tweaking for speed now
39 h->mb.b_chroma_me = 0;
42 static int x264_slicetype_mb_cost( x264_t *h, x264_mb_analysis_t *a,
43 x264_frame_t **frames, int p0, int p1, int b,
44 int dist_scale_factor, int do_search[2] )
46 x264_frame_t *fref0 = frames[p0];
47 x264_frame_t *fref1 = frames[p1];
48 x264_frame_t *fenc = frames[b];
49 const int b_bidir = (b < p1);
50 const int i_mb_x = h->mb.i_mb_x;
51 const int i_mb_y = h->mb.i_mb_y;
52 const int i_mb_stride = h->sps->i_mb_width;
53 const int i_mb_xy = i_mb_x + i_mb_y * i_mb_stride;
54 const int i_stride = fenc->i_stride_lowres;
55 const int i_pel_offset = 8 * ( i_mb_x + i_mb_y * i_stride );
56 const int i_bipred_weight = h->param.analyse.b_weighted_bipred ? 64 - (dist_scale_factor>>2) : 32;
57 int16_t (*fenc_mvs[2])[2] = { &frames[b]->lowres_mvs[0][b-p0-1][i_mb_xy], &frames[b]->lowres_mvs[1][p1-b-1][i_mb_xy] };
58 int (*fenc_costs[2]) = { &frames[b]->lowres_mv_costs[0][b-p0-1][i_mb_xy], &frames[b]->lowres_mv_costs[1][p1-b-1][i_mb_xy] };
60 ALIGNED_8( uint8_t pix1[9*FDEC_STRIDE] );
61 uint8_t *pix2 = pix1+8;
63 int i_bcost = COST_MAX;
67 h->mb.pic.p_fenc[0] = h->mb.pic.fenc_buf;
68 h->mc.copy[PIXEL_8x8]( h->mb.pic.p_fenc[0], FENC_STRIDE, &fenc->lowres[0][i_pel_offset], i_stride, 8 );
73 // no need for h->mb.mv_min[]
74 h->mb.mv_min_fpel[0] = -8*h->mb.i_mb_x - 4;
75 h->mb.mv_max_fpel[0] = 8*( h->sps->i_mb_width - h->mb.i_mb_x - 1 ) + 4;
76 h->mb.mv_min_spel[0] = 4*( h->mb.mv_min_fpel[0] - 8 );
77 h->mb.mv_max_spel[0] = 4*( h->mb.mv_max_fpel[0] + 8 );
78 if( h->mb.i_mb_x >= h->sps->i_mb_width - 2 )
80 h->mb.mv_min_fpel[1] = -8*h->mb.i_mb_y - 4;
81 h->mb.mv_max_fpel[1] = 8*( h->sps->i_mb_height - h->mb.i_mb_y - 1 ) + 4;
82 h->mb.mv_min_spel[1] = 4*( h->mb.mv_min_fpel[1] - 8 );
83 h->mb.mv_max_spel[1] = 4*( h->mb.mv_max_fpel[1] + 8 );
86 #define LOAD_HPELS_LUMA(dst, src) \
88 (dst)[0] = &(src)[0][i_pel_offset]; \
89 (dst)[1] = &(src)[1][i_pel_offset]; \
90 (dst)[2] = &(src)[2][i_pel_offset]; \
91 (dst)[3] = &(src)[3][i_pel_offset]; \
93 #define CLIP_MV( mv ) \
95 mv[0] = x264_clip3( mv[0], h->mb.mv_min_spel[0], h->mb.mv_max_spel[0] ); \
96 mv[1] = x264_clip3( mv[1], h->mb.mv_min_spel[1], h->mb.mv_max_spel[1] ); \
98 #define TRY_BIDIR( mv0, mv1, penalty ) \
100 int stride1 = 16, stride2 = 16; \
101 uint8_t *src1, *src2; \
103 src1 = h->mc.get_ref( pix1, &stride1, m[0].p_fref, m[0].i_stride[0], \
104 (mv0)[0], (mv0)[1], 8, 8 ); \
105 src2 = h->mc.get_ref( pix2, &stride2, m[1].p_fref, m[1].i_stride[0], \
106 (mv1)[0], (mv1)[1], 8, 8 ); \
107 h->mc.avg[PIXEL_8x8]( pix1, 16, src1, stride1, src2, stride2, i_bipred_weight ); \
108 i_cost = penalty + h->pixf.mbcmp[PIXEL_8x8]( \
109 m[0].p_fenc[0], FENC_STRIDE, pix1, 16 ); \
110 COPY2_IF_LT( i_bcost, i_cost, list_used, 3 ); \
113 m[0].i_pixel = PIXEL_8x8;
114 m[0].p_cost_mv = a->p_cost_mv;
115 m[0].i_stride[0] = i_stride;
116 m[0].p_fenc[0] = h->mb.pic.p_fenc[0];
117 LOAD_HPELS_LUMA( m[0].p_fref, fref0->lowres );
121 int16_t *mvr = fref1->lowres_mvs[0][p1-p0-1][i_mb_xy];
124 h->mc.memcpy_aligned( &m[1], &m[0], sizeof(x264_me_t) );
125 LOAD_HPELS_LUMA( m[1].p_fref, fref1->lowres );
127 dmv[0][0] = ( mvr[0] * dist_scale_factor + 128 ) >> 8;
128 dmv[0][1] = ( mvr[1] * dist_scale_factor + 128 ) >> 8;
129 dmv[1][0] = dmv[0][0] - mvr[0];
130 dmv[1][1] = dmv[0][1] - mvr[1];
134 TRY_BIDIR( dmv[0], dmv[1], 0 );
135 if( dmv[0][0] | dmv[0][1] | dmv[1][0] | dmv[1][1] )
138 h->mc.avg[PIXEL_8x8]( pix1, 16, m[0].p_fref[0], m[0].i_stride[0], m[1].p_fref[0], m[1].i_stride[0], i_bipred_weight );
139 i_cost = h->pixf.mbcmp[PIXEL_8x8]( m[0].p_fenc[0], FENC_STRIDE, pix1, 16 );
140 COPY2_IF_LT( i_bcost, i_cost, list_used, 3 );
144 for( l = 0; l < 1 + b_bidir; l++ )
149 int16_t (*fenc_mv)[2] = fenc_mvs[l];
150 ALIGNED_4( int16_t mvc[4][2] );
152 /* Reverse-order MV prediction. */
153 *(uint32_t*)mvc[0] = 0;
154 *(uint32_t*)mvc[1] = 0;
155 *(uint32_t*)mvc[2] = 0;
156 #define MVC(mv) { *(uint32_t*)mvc[i_mvc] = *(uint32_t*)mv; i_mvc++; }
157 if( i_mb_x < h->sps->i_mb_width - 1 )
159 if( i_mb_y < h->sps->i_mb_height - 1 )
161 MVC(fenc_mv[i_mb_stride]);
163 MVC(fenc_mv[i_mb_stride-1]);
164 if( i_mb_x < h->sps->i_mb_width - 1 )
165 MVC(fenc_mv[i_mb_stride+1]);
168 x264_median_mv( m[l].mvp, mvc[0], mvc[1], mvc[2] );
169 x264_me_search( h, &m[l], mvc, i_mvc );
171 m[l].cost -= 2; // remove mvcost from skip mbs
172 if( *(uint32_t*)m[l].mv )
174 *(uint32_t*)fenc_mvs[l] = *(uint32_t*)m[l].mv;
175 *fenc_costs[l] = m[l].cost;
179 *(uint32_t*)m[l].mv = *(uint32_t*)fenc_mvs[l];
180 m[l].cost = *fenc_costs[l];
182 COPY2_IF_LT( i_bcost, m[l].cost, list_used, l+1 );
185 if( b_bidir && ( *(uint32_t*)m[0].mv || *(uint32_t*)m[1].mv ) )
186 TRY_BIDIR( m[0].mv, m[1].mv, 5 );
188 /* Store to width-2 bitfield. */
189 frames[b]->lowres_inter_types[b-p0][p1-b][i_mb_xy>>2] &= ~(3<<((i_mb_xy&3)*2));
190 frames[b]->lowres_inter_types[b-p0][p1-b][i_mb_xy>>2] |= list_used<<((i_mb_xy&3)*2);
193 /* forbid intra-mbs in B-frames, because it's rare and not worth checking */
194 /* FIXME: Should we still forbid them now that we cache intra scores? */
195 if( !b_bidir || h->param.rc.b_mb_tree )
197 int i_icost, b_intra;
198 if( !fenc->b_intra_calculated )
200 ALIGNED_ARRAY_16( uint8_t, edge,[33] );
201 uint8_t *pix = &pix1[8+FDEC_STRIDE - 1];
202 uint8_t *src = &fenc->lowres[0][i_pel_offset - 1];
203 const int intra_penalty = 5;
206 memcpy( pix-FDEC_STRIDE, src-i_stride, 17 );
208 pix[i*FDEC_STRIDE] = src[i*i_stride];
211 if( h->pixf.intra_mbcmp_x3_8x8c )
213 h->pixf.intra_mbcmp_x3_8x8c( h->mb.pic.p_fenc[0], pix, satds );
214 h->predict_8x8c[I_PRED_CHROMA_P]( pix );
215 satds[I_PRED_CHROMA_P] =
216 h->pixf.mbcmp[PIXEL_8x8]( pix, FDEC_STRIDE, h->mb.pic.p_fenc[0], FENC_STRIDE );
222 h->predict_8x8c[i]( pix );
223 satds[i] = h->pixf.mbcmp[PIXEL_8x8]( pix, FDEC_STRIDE, h->mb.pic.p_fenc[0], FENC_STRIDE );
226 i_icost = X264_MIN4( satds[0], satds[1], satds[2], satds[3] );
228 h->predict_8x8_filter( pix, edge, ALL_NEIGHBORS, ALL_NEIGHBORS );
232 h->predict_8x8[i]( pix, edge );
233 satd = h->pixf.mbcmp[PIXEL_8x8]( pix, FDEC_STRIDE, h->mb.pic.p_fenc[0], FENC_STRIDE );
234 i_icost = X264_MIN( i_icost, satd );
237 i_icost += intra_penalty;
238 fenc->i_intra_cost[i_mb_xy] = i_icost;
241 i_icost = fenc->i_intra_cost[i_mb_xy];
244 b_intra = i_icost < i_bcost;
247 if( (i_mb_x > 0 && i_mb_x < h->sps->i_mb_width - 1
248 && i_mb_y > 0 && i_mb_y < h->sps->i_mb_height - 1)
249 || h->sps->i_mb_width <= 2 || h->sps->i_mb_height <= 2 )
251 fenc->i_intra_mbs[b-p0] += b_intra;
252 fenc->i_cost_est[0][0] += i_icost;
253 if( h->param.rc.i_aq_mode )
254 fenc->i_cost_est_aq[0][0] += (i_icost * fenc->i_inv_qscale_factor[i_mb_xy] + 128) >> 8;
259 fenc->lowres_costs[b-p0][p1-b][i_mb_xy] = i_bcost;
266 (h->sps->i_mb_width > 2 && h->sps->i_mb_height > 2 ?\
267 (h->sps->i_mb_width - 2) * (h->sps->i_mb_height - 2) :\
268 h->sps->i_mb_width * h->sps->i_mb_height)
270 static int x264_slicetype_frame_cost( x264_t *h, x264_mb_analysis_t *a,
271 x264_frame_t **frames, int p0, int p1, int b,
272 int b_intra_penalty )
276 /* Don't use the AQ'd scores for slicetype decision. */
280 /* Check whether we already evaluated this frame
281 * If we have tried this frame as P, then we have also tried
282 * the preceding frames as B. (is this still true?) */
283 /* Also check that we already calculated the row SATDs for the current frame. */
284 if( frames[b]->i_cost_est[b-p0][p1-b] >= 0 && (!h->param.rc.i_vbv_buffer_size || frames[b]->i_row_satds[b-p0][p1-b][0] != -1) )
286 i_score = frames[b]->i_cost_est[b-p0][p1-b];
290 int dist_scale_factor = 128;
291 int *row_satd = frames[b]->i_row_satds[b-p0][p1-b];
293 /* For each list, check to see whether we have lowres motion-searched this reference frame before. */
294 do_search[0] = b != p0 && frames[b]->lowres_mvs[0][b-p0-1][0][0] == 0x7FFF;
295 do_search[1] = b != p1 && frames[b]->lowres_mvs[1][p1-b-1][0][0] == 0x7FFF;
296 if( do_search[0] ) frames[b]->lowres_mvs[0][b-p0-1][0][0] = 0;
297 if( do_search[1] ) frames[b]->lowres_mvs[1][p1-b-1][0][0] = 0;
301 frames[b]->i_intra_mbs[b-p0] = 0;
302 frames[b]->i_cost_est[0][0] = 0;
303 frames[b]->i_cost_est_aq[0][0] = 0;
306 dist_scale_factor = ( ((b-p0) << 8) + ((p1-p0) >> 1) ) / (p1-p0);
308 /* Lowres lookahead goes backwards because the MVs are used as predictors in the main encode.
309 * This considerably improves MV prediction overall. */
311 /* the edge mbs seem to reduce the predictive quality of the
312 * whole frame's score, but are needed for a spatial distribution. */
313 if( h->param.rc.b_mb_tree || h->param.rc.i_vbv_buffer_size ||
314 h->sps->i_mb_width <= 2 || h->sps->i_mb_height <= 2 )
316 for( h->mb.i_mb_y = h->sps->i_mb_height - 1; h->mb.i_mb_y >= 0; h->mb.i_mb_y-- )
318 row_satd[ h->mb.i_mb_y ] = 0;
319 for( h->mb.i_mb_x = h->sps->i_mb_width - 1; h->mb.i_mb_x >= 0; h->mb.i_mb_x-- )
321 int i_mb_cost = x264_slicetype_mb_cost( h, a, frames, p0, p1, b, dist_scale_factor, do_search );
322 int i_mb_cost_aq = i_mb_cost;
323 if( h->param.rc.i_aq_mode )
324 i_mb_cost_aq = (i_mb_cost_aq * frames[b]->i_inv_qscale_factor[h->mb.i_mb_x + h->mb.i_mb_y*h->mb.i_mb_stride] + 128) >> 8;
325 row_satd[ h->mb.i_mb_y ] += i_mb_cost_aq;
326 if( (h->mb.i_mb_y > 0 && h->mb.i_mb_y < h->sps->i_mb_height - 1 &&
327 h->mb.i_mb_x > 0 && h->mb.i_mb_x < h->sps->i_mb_width - 1) ||
328 h->sps->i_mb_width <= 2 || h->sps->i_mb_height <= 2 )
330 /* Don't use AQ-weighted costs for slicetype decision, only for ratecontrol. */
331 i_score += i_mb_cost;
332 i_score_aq += i_mb_cost_aq;
339 for( h->mb.i_mb_y = h->sps->i_mb_height - 2; h->mb.i_mb_y > 0; h->mb.i_mb_y-- )
340 for( h->mb.i_mb_x = h->sps->i_mb_width - 2; h->mb.i_mb_x > 0; h->mb.i_mb_x-- )
342 int i_mb_cost = x264_slicetype_mb_cost( h, a, frames, p0, p1, b, dist_scale_factor, do_search );
343 int i_mb_cost_aq = i_mb_cost;
344 if( h->param.rc.i_aq_mode )
345 i_mb_cost_aq = (i_mb_cost_aq * frames[b]->i_inv_qscale_factor[h->mb.i_mb_x + h->mb.i_mb_y*h->mb.i_mb_stride] + 128) >> 8;
346 i_score += i_mb_cost;
347 i_score_aq += i_mb_cost_aq;
352 i_score = (uint64_t)i_score * 100 / (120 + h->param.i_bframe_bias);
354 frames[b]->b_intra_calculated = 1;
356 frames[b]->i_cost_est[b-p0][p1-b] = i_score;
357 frames[b]->i_cost_est_aq[b-p0][p1-b] = i_score_aq;
361 if( b_intra_penalty )
363 // arbitrary penalty for I-blocks after B-frames
365 i_score += i_score * frames[b]->i_intra_mbs[b-p0] / (nmb * 8);
370 /* If MB-tree changes the quantizers, we need to recalculate the frame cost without
371 * re-running lookahead. */
372 static int x264_slicetype_frame_cost_recalculate( x264_t *h, x264_frame_t **frames, int p0, int p1, int b )
375 int *row_satd = frames[b]->i_row_satds[b-p0][p1-b];
376 float *qp_offset = IS_X264_TYPE_B(frames[b]->i_type) ? frames[b]->f_qp_offset_aq : frames[b]->f_qp_offset;
378 for( h->mb.i_mb_y = h->sps->i_mb_height - 1; h->mb.i_mb_y >= 0; h->mb.i_mb_y-- )
380 row_satd[ h->mb.i_mb_y ] = 0;
381 for( h->mb.i_mb_x = h->sps->i_mb_width - 1; h->mb.i_mb_x >= 0; h->mb.i_mb_x-- )
383 int i_mb_xy = h->mb.i_mb_x + h->mb.i_mb_y*h->mb.i_mb_stride;
384 int i_mb_cost = frames[b]->lowres_costs[b-p0][p1-b][i_mb_xy];
385 float qp_adj = qp_offset[i_mb_xy];
386 i_mb_cost = (i_mb_cost * x264_exp2fix8(qp_adj) + 128) >> 8;
387 row_satd[ h->mb.i_mb_y ] += i_mb_cost;
388 if( (h->mb.i_mb_y > 0 && h->mb.i_mb_y < h->sps->i_mb_height - 1 &&
389 h->mb.i_mb_x > 0 && h->mb.i_mb_x < h->sps->i_mb_width - 1) ||
390 h->sps->i_mb_width <= 2 || h->sps->i_mb_height <= 2 )
392 i_score += i_mb_cost;
399 static void x264_macroblock_tree_finish( x264_t *h, x264_frame_t *frame )
403 /* Allow the strength to be adjusted via qcompress, since the two
404 * concepts are very similar. */
405 float strength = 5.0f * (1.0f - h->param.rc.f_qcompress);
406 for( mb_index = 0; mb_index < h->mb.i_mb_count; mb_index++ )
408 int intra_cost = (frame->i_intra_cost[mb_index] * frame->i_inv_qscale_factor[mb_index]+128)>>8;
411 int propagate_cost = frame->i_propagate_cost[mb_index];
412 float log2_ratio = x264_log2(intra_cost + propagate_cost) - x264_log2(intra_cost);
413 frame->f_qp_offset[mb_index] = frame->f_qp_offset_aq[mb_index] - strength * log2_ratio;
418 static void x264_macroblock_tree_propagate( x264_t *h, x264_frame_t **frames, int p0, int p1, int b )
420 uint16_t *ref_costs[2] = {frames[p0]->i_propagate_cost,frames[p1]->i_propagate_cost};
421 int dist_scale_factor = ( ((b-p0) << 8) + ((p1-p0) >> 1) ) / (p1-p0);
422 int i_bipred_weight = h->param.analyse.b_weighted_bipred ? 64 - (dist_scale_factor>>2) : 32;
423 int16_t (*mvs[2])[2] = { frames[b]->lowres_mvs[0][b-p0-1], frames[b]->lowres_mvs[1][p1-b-1] };
424 int bipred_weights[2] = {i_bipred_weight, 64 - i_bipred_weight};
425 int *buf = h->scratch_buffer;
427 for( h->mb.i_mb_y = 0; h->mb.i_mb_y < h->sps->i_mb_height; h->mb.i_mb_y++ )
429 int mb_index = h->mb.i_mb_y*h->mb.i_mb_stride;
430 h->mc.mbtree_propagate_cost( buf, frames[b]->i_propagate_cost+mb_index,
431 frames[b]->i_intra_cost+mb_index, frames[b]->lowres_costs[b-p0][p1-b]+mb_index,
432 frames[b]->i_inv_qscale_factor+mb_index, h->sps->i_mb_width );
433 for( h->mb.i_mb_x = 0; h->mb.i_mb_x < h->sps->i_mb_width; h->mb.i_mb_x++, mb_index++ )
435 int propagate_amount = buf[h->mb.i_mb_x];
436 /* Don't propagate for an intra block. */
437 if( propagate_amount > 0 )
439 /* Access width-2 bitfield. */
440 int lists_used = (frames[b]->lowres_inter_types[b-p0][p1-b][mb_index>>2] >> ((mb_index&3)*2))&3;
442 /* Follow the MVs to the previous frame(s). */
443 for( list = 0; list < 2; list++ )
444 if( (lists_used >> list)&1 )
446 int x = mvs[list][mb_index][0];
447 int y = mvs[list][mb_index][1];
448 int listamount = propagate_amount;
449 int mbx = (x>>5)+h->mb.i_mb_x;
450 int mby = (y>>5)+h->mb.i_mb_y;
451 int idx0 = mbx + mby*h->mb.i_mb_stride;
453 int idx2 = idx0 + h->mb.i_mb_stride;
454 int idx3 = idx0 + h->mb.i_mb_stride + 1;
457 int idx0weight = (32-y)*(32-x);
458 int idx1weight = (32-y)*x;
459 int idx2weight = y*(32-x);
460 int idx3weight = y*x;
462 /* Apply bipred weighting. */
463 if( lists_used == 3 )
464 listamount = (listamount * bipred_weights[list] + 32) >> 6;
466 #define CLIP_ADD(s,x) (s) = X264_MIN((s)+(x),(1<<16)-1)
468 /* We could just clip the MVs, but pixels that lie outside the frame probably shouldn't
470 if( mbx < h->sps->i_mb_width-1 && mby < h->sps->i_mb_height-1 && mbx >= 0 && mby >= 0 )
472 CLIP_ADD( ref_costs[list][idx0], (listamount*idx0weight+512)>>10 );
473 CLIP_ADD( ref_costs[list][idx1], (listamount*idx1weight+512)>>10 );
474 CLIP_ADD( ref_costs[list][idx2], (listamount*idx2weight+512)>>10 );
475 CLIP_ADD( ref_costs[list][idx3], (listamount*idx3weight+512)>>10 );
477 else /* Check offsets individually */
479 if( mbx < h->sps->i_mb_width && mby < h->sps->i_mb_height && mbx >= 0 && mby >= 0 )
480 CLIP_ADD( ref_costs[list][idx0], (listamount*idx0weight+512)>>10 );
481 if( mbx+1 < h->sps->i_mb_width && mby < h->sps->i_mb_height && mbx+1 >= 0 && mby >= 0 )
482 CLIP_ADD( ref_costs[list][idx1], (listamount*idx1weight+512)>>10 );
483 if( mbx < h->sps->i_mb_width && mby+1 < h->sps->i_mb_height && mbx >= 0 && mby+1 >= 0 )
484 CLIP_ADD( ref_costs[list][idx2], (listamount*idx2weight+512)>>10 );
485 if( mbx+1 < h->sps->i_mb_width && mby+1 < h->sps->i_mb_height && mbx+1 >= 0 && mby+1 >= 0 )
486 CLIP_ADD( ref_costs[list][idx3], (listamount*idx3weight+512)>>10 );
493 if( h->param.rc.i_vbv_buffer_size && b == p1 )
494 x264_macroblock_tree_finish( h, frames[b] );
497 static void x264_macroblock_tree( x264_t *h, x264_mb_analysis_t *a, x264_frame_t **frames, int num_frames, int b_intra )
499 int i, idx = !b_intra;
500 int last_nonb, cur_nonb = 1;
502 x264_slicetype_frame_cost( h, a, frames, 0, 0, 0, 0 );
505 while( i > 0 && frames[i]->i_type == X264_TYPE_B )
509 if( last_nonb < idx )
512 memset( frames[last_nonb]->i_propagate_cost, 0, h->mb.i_mb_count * sizeof(uint16_t) );
516 while( frames[cur_nonb]->i_type == X264_TYPE_B && cur_nonb > 0 )
520 x264_slicetype_frame_cost( h, a, frames, cur_nonb, last_nonb, last_nonb, 0 );
521 memset( frames[cur_nonb]->i_propagate_cost, 0, h->mb.i_mb_count * sizeof(uint16_t) );
522 while( i > cur_nonb )
524 x264_slicetype_frame_cost( h, a, frames, cur_nonb, last_nonb, i, 0 );
525 memset( frames[i]->i_propagate_cost, 0, h->mb.i_mb_count * sizeof(uint16_t) );
526 x264_macroblock_tree_propagate( h, frames, cur_nonb, last_nonb, i );
529 x264_macroblock_tree_propagate( h, frames, cur_nonb, last_nonb, last_nonb );
530 last_nonb = cur_nonb;
533 x264_macroblock_tree_finish( h, frames[last_nonb] );
536 static int x264_vbv_frame_cost( x264_t *h, x264_mb_analysis_t *a, x264_frame_t **frames, int p0, int p1, int b )
538 int cost = x264_slicetype_frame_cost( h, a, frames, p0, p1, b, 0 );
539 if( h->param.rc.i_aq_mode )
541 if( h->param.rc.b_mb_tree )
542 return x264_slicetype_frame_cost_recalculate( h, frames, p0, p1, b );
544 return frames[b]->i_cost_est_aq[b-p0][p1-b];
549 static void x264_vbv_lookahead( x264_t *h, x264_mb_analysis_t *a, x264_frame_t **frames, int num_frames, int keyframe )
551 int last_nonb = 0, cur_nonb = 1, next_nonb, i, idx = 0;
552 while( cur_nonb < num_frames && frames[cur_nonb]->i_type == X264_TYPE_B )
554 next_nonb = keyframe ? last_nonb : cur_nonb;
556 while( cur_nonb <= num_frames )
558 /* P/I cost: This shouldn't include the cost of next_nonb */
559 if( next_nonb != cur_nonb )
561 int p0 = IS_X264_TYPE_I( frames[cur_nonb]->i_type ) ? cur_nonb : last_nonb;
562 frames[next_nonb]->i_planned_satd[idx] = x264_vbv_frame_cost( h, a, frames, p0, cur_nonb, cur_nonb );
563 frames[next_nonb]->i_planned_type[idx] = frames[cur_nonb]->i_type;
566 /* Handle the B-frames: coded order */
567 for( i = last_nonb+1; i < cur_nonb; i++, idx++ )
569 frames[next_nonb]->i_planned_satd[idx] = x264_vbv_frame_cost( h, a, frames, last_nonb, cur_nonb, i );
570 frames[next_nonb]->i_planned_type[idx] = X264_TYPE_B;
572 last_nonb = cur_nonb;
574 while( cur_nonb <= num_frames && frames[cur_nonb]->i_type == X264_TYPE_B )
577 frames[next_nonb]->i_planned_type[idx] = X264_TYPE_AUTO;
580 static int x264_slicetype_path_cost( x264_t *h, x264_mb_analysis_t *a, x264_frame_t **frames, char *path, int threshold )
585 path--; /* Since the 1st path element is really the second frame */
590 /* Find the location of the next P-frame. */
591 while( path[next_p] && path[next_p] != 'P' )
593 /* Return if the path doesn't end on a P-frame. */
594 if( path[next_p] != 'P' )
597 /* Add the cost of the P-frame found above */
598 cost += x264_slicetype_frame_cost( h, a, frames, cur_p, next_p, next_p, 0 );
599 /* Early terminate if the cost we have found is larger than the best path cost so far */
600 if( cost > threshold )
603 for( next_b = loc; next_b < next_p && cost < threshold; next_b++ )
604 cost += x264_slicetype_frame_cost( h, a, frames, cur_p, next_p, next_b, 0 );
612 /* Viterbi/trellis slicetype decision algorithm. */
613 /* Uses strings due to the fact that the speed of the control functions is
614 negligable compared to the cost of running slicetype_frame_cost, and because
615 it makes debugging easier. */
616 static void x264_slicetype_path( x264_t *h, x264_mb_analysis_t *a, x264_frame_t **frames, int length, int max_bframes, char (*best_paths)[X264_LOOKAHEAD_MAX] )
618 char paths[X264_BFRAME_MAX+1][X264_LOOKAHEAD_MAX] = {{0}};
619 int num_paths = X264_MIN( max_bframes+1, length );
621 int best_cost = COST_MAX;
622 int best_path_index = 0;
624 /* Iterate over all currently possible paths */
625 for( path = 0; path < num_paths; path++ )
627 /* Add suffixes to the current path */
628 int len = length - (path + 1);
629 memcpy( paths[path], best_paths[len % (X264_BFRAME_MAX+1)], len );
630 memset( paths[path]+len, 'B', path );
631 strcat( paths[path], "P" );
633 /* Calculate the actual cost of the current path */
634 int cost = x264_slicetype_path_cost( h, a, frames, paths[path], best_cost );
635 if( cost < best_cost )
638 best_path_index = path;
642 /* Store the best path. */
643 memcpy( best_paths[length % (X264_BFRAME_MAX+1)], paths[best_path_index], length );
646 static int scenecut_internal( x264_t *h, x264_mb_analysis_t *a, x264_frame_t **frames, int p0, int p1, int print )
648 x264_frame_t *frame = frames[p1];
649 x264_slicetype_frame_cost( h, a, frames, p0, p1, p1, 0 );
651 int icost = frame->i_cost_est[0][0];
652 int pcost = frame->i_cost_est[p1-p0][0];
654 int i_gop_size = frame->i_frame - h->lookahead->i_last_idr;
655 float f_thresh_max = h->param.i_scenecut_threshold / 100.0;
656 /* magic numbers pulled out of thin air */
657 float f_thresh_min = f_thresh_max * h->param.i_keyint_min
658 / ( h->param.i_keyint_max * 4 );
661 if( h->param.i_keyint_min == h->param.i_keyint_max )
662 f_thresh_min= f_thresh_max;
663 if( i_gop_size < h->param.i_keyint_min / 4 )
664 f_bias = f_thresh_min / 4;
665 else if( i_gop_size <= h->param.i_keyint_min )
666 f_bias = f_thresh_min * i_gop_size / h->param.i_keyint_min;
669 f_bias = f_thresh_min
670 + ( f_thresh_max - f_thresh_min )
671 * ( i_gop_size - h->param.i_keyint_min )
672 / ( h->param.i_keyint_max - h->param.i_keyint_min ) ;
675 res = pcost >= (1.0 - f_bias) * icost;
678 int imb = frame->i_intra_mbs[p1-p0];
679 int pmb = NUM_MBS - imb;
680 x264_log( h, X264_LOG_DEBUG, "scene cut at %d Icost:%d Pcost:%d ratio:%.4f bias:%.4f gop:%d (imb:%d pmb:%d)\n",
682 icost, pcost, 1. - (double)pcost / icost,
683 f_bias, i_gop_size, imb, pmb );
688 static int scenecut( x264_t *h, x264_mb_analysis_t *a, x264_frame_t **frames, int p0, int p1, int real_scenecut, int num_frames )
690 int curp0, curp1, i, maxp1 = p0 + 1;
692 /* Only do analysis during a normal scenecut check. */
693 if( real_scenecut && h->param.i_bframe )
695 /* Look ahead to avoid coding short flashes as scenecuts. */
696 if( h->param.i_bframe_adaptive == X264_B_ADAPT_TRELLIS )
697 /* Don't analyse any more frames than the trellis would have covered. */
698 maxp1 += h->param.i_bframe;
701 maxp1 = X264_MIN( maxp1, num_frames );
703 /* Where A and B are scenes: AAAAAABBBAAAAAA
704 * If BBB is shorter than (maxp1-p0), it is detected as a flash
705 * and not considered a scenecut. */
706 for( curp1 = p1; curp1 <= maxp1; curp1++ )
707 if( !scenecut_internal( h, a, frames, p0, curp1, 0 ) )
708 /* Any frame in between p0 and cur_p1 cannot be a real scenecut. */
709 for( i = curp1; i > p0; i-- )
710 frames[i]->b_scenecut = 0;
712 /* Where A-F are scenes: AAAAABBCCDDEEFFFFFF
713 * If each of BB ... EE are shorter than (maxp1-p0), they are
714 * detected as flashes and not considered scenecuts.
715 * Instead, the first F frame becomes a scenecut. */
716 for( curp0 = p0; curp0 < maxp1; curp0++ )
717 if( scenecut_internal( h, a, frames, curp0, maxp1, 0 ) )
718 /* If cur_p0 is the p0 of a scenecut, it cannot be the p1 of a scenecut. */
719 frames[curp0]->b_scenecut = 0;
722 /* Ignore frames that are part of a flash, i.e. cannot be real scenecuts. */
723 if( !frames[p1]->b_scenecut )
725 return scenecut_internal( h, a, frames, p0, p1, real_scenecut );
728 void x264_slicetype_analyse( x264_t *h, int keyframe )
730 x264_mb_analysis_t a;
731 x264_frame_t *frames[X264_LOOKAHEAD_MAX+3] = { NULL, };
732 int num_frames, orig_num_frames, keyint_limit, idr_frame_type, i, j;
733 int i_mb_count = NUM_MBS;
734 int cost1p0, cost2p0, cost1b1, cost2p1;
735 int i_max_search = X264_MIN( h->lookahead->next.i_size, X264_LOOKAHEAD_MAX );
736 if( h->param.b_deterministic )
737 i_max_search = X264_MIN( i_max_search, h->lookahead->i_slicetype_length + !keyframe );
739 assert( h->frames.b_have_lowres );
741 if( !h->lookahead->last_nonb )
743 frames[0] = h->lookahead->last_nonb;
744 for( j = 0; j < i_max_search && h->lookahead->next.list[j]->i_type == X264_TYPE_AUTO; j++ )
745 frames[j+1] = h->lookahead->next.list[j];
750 keyint_limit = h->param.i_keyint_max - frames[0]->i_frame + h->lookahead->i_last_idr - 1;
751 orig_num_frames = num_frames = X264_MIN( j, keyint_limit );
753 x264_lowres_context_init( h, &a );
754 idr_frame_type = frames[1]->i_frame - h->lookahead->i_last_idr >= h->param.i_keyint_min ? X264_TYPE_IDR : X264_TYPE_I;
756 /* This is important psy-wise: if we have a non-scenecut keyframe,
757 * there will be significant visual artifacts if the frames just before
758 * go down in quality due to being referenced less, despite it being
759 * more RD-optimal. */
760 if( (h->param.analyse.b_psy && h->param.rc.b_mb_tree) || h->param.rc.i_vbv_buffer_size )
762 else if( num_frames == 1 )
764 frames[1]->i_type = X264_TYPE_P;
765 if( h->param.i_scenecut_threshold && scenecut( h, &a, frames, 0, 1, 1, orig_num_frames ) )
766 frames[1]->i_type = idr_frame_type;
769 else if( num_frames == 0 )
771 frames[1]->i_type = idr_frame_type;
776 int max_bframes = X264_MIN(num_frames-1, h->param.i_bframe);
777 int num_analysed_frames = num_frames;
779 if( h->param.i_scenecut_threshold && scenecut( h, &a, frames, 0, 1, 1, orig_num_frames ) )
781 frames[1]->i_type = idr_frame_type;
785 if( h->param.i_bframe )
787 if( h->param.i_bframe_adaptive == X264_B_ADAPT_TRELLIS )
789 char best_paths[X264_BFRAME_MAX+1][X264_LOOKAHEAD_MAX] = {"","P"};
792 /* Perform the frametype analysis. */
793 for( n = 2; n < num_frames; n++ )
794 x264_slicetype_path( h, &a, frames, n, max_bframes, best_paths );
797 int best_path_index = (num_frames-1) % (X264_BFRAME_MAX+1);
798 num_bframes = strspn( best_paths[best_path_index], "B" );
799 /* Load the results of the analysis into the frame types. */
800 for( j = 1; j < num_frames; j++ )
801 frames[j]->i_type = best_paths[best_path_index][j-1] == 'B' ? X264_TYPE_B : X264_TYPE_P;
803 frames[num_frames]->i_type = X264_TYPE_P;
805 else if( h->param.i_bframe_adaptive == X264_B_ADAPT_FAST )
807 for( i = 0; i <= num_frames-2; )
809 cost2p1 = x264_slicetype_frame_cost( h, &a, frames, i+0, i+2, i+2, 1 );
810 if( frames[i+2]->i_intra_mbs[2] > i_mb_count / 2 )
812 frames[i+1]->i_type = X264_TYPE_P;
813 frames[i+2]->i_type = X264_TYPE_P;
818 cost1b1 = x264_slicetype_frame_cost( h, &a, frames, i+0, i+2, i+1, 0 );
819 cost1p0 = x264_slicetype_frame_cost( h, &a, frames, i+0, i+1, i+1, 0 );
820 cost2p0 = x264_slicetype_frame_cost( h, &a, frames, i+1, i+2, i+2, 0 );
822 if( cost1p0 + cost2p0 < cost1b1 + cost2p1 )
824 frames[i+1]->i_type = X264_TYPE_P;
829 // arbitrary and untuned
830 #define INTER_THRESH 300
831 #define P_SENS_BIAS (50 - h->param.i_bframe_bias)
832 frames[i+1]->i_type = X264_TYPE_B;
834 for( j = i+2; j <= X264_MIN( i+h->param.i_bframe, num_frames-1 ); j++ )
836 int pthresh = X264_MAX(INTER_THRESH - P_SENS_BIAS * (j-i-1), INTER_THRESH/10);
837 int pcost = x264_slicetype_frame_cost( h, &a, frames, i+0, j+1, j+1, 1 );
838 if( pcost > pthresh*i_mb_count || frames[j+1]->i_intra_mbs[j-i+1] > i_mb_count/3 )
840 frames[j]->i_type = X264_TYPE_B;
842 frames[j]->i_type = X264_TYPE_P;
845 frames[num_frames]->i_type = X264_TYPE_P;
847 while( num_bframes < num_frames && frames[num_bframes+1]->i_type == X264_TYPE_B )
852 num_bframes = X264_MIN(num_frames-1, h->param.i_bframe);
853 for( j = 1; j < num_frames; j++ )
854 frames[j]->i_type = (j%(num_bframes+1)) ? X264_TYPE_B : X264_TYPE_P;
855 frames[num_frames]->i_type = X264_TYPE_P;
858 /* Check scenecut on the first minigop. */
859 for( j = 1; j < num_bframes+1; j++ )
860 if( h->param.i_scenecut_threshold && scenecut( h, &a, frames, j, j+1, 0, orig_num_frames ) )
862 frames[j]->i_type = X264_TYPE_P;
863 num_analysed_frames = j;
867 reset_start = keyframe ? 1 : X264_MIN( num_bframes+2, num_analysed_frames+1 );
871 for( j = 1; j <= num_frames; j++ )
872 frames[j]->i_type = X264_TYPE_P;
873 reset_start = !keyframe + 1;
877 /* Perform the actual macroblock tree analysis.
878 * Don't go farther than the maximum keyframe interval; this helps in short GOPs. */
879 if( h->param.rc.b_mb_tree )
880 x264_macroblock_tree( h, &a, frames, X264_MIN(num_frames, h->param.i_keyint_max), keyframe );
882 /* Enforce keyframe limit. */
883 for( j = 0; j < num_frames; j++ )
885 if( ((j-keyint_limit) % h->param.i_keyint_max) == 0 )
887 if( j && h->param.i_keyint_max > 1 )
888 frames[j]->i_type = X264_TYPE_P;
889 frames[j+1]->i_type = X264_TYPE_IDR;
890 reset_start = X264_MIN( reset_start, j+2 );
894 if( h->param.rc.i_vbv_buffer_size )
895 x264_vbv_lookahead( h, &a, frames, num_frames, keyframe );
897 /* Restore frametypes for all frames that haven't actually been decided yet. */
898 for( j = reset_start; j <= num_frames; j++ )
899 frames[j]->i_type = X264_TYPE_AUTO;
902 void x264_slicetype_decide( x264_t *h )
904 x264_frame_t *frames[X264_BFRAME_MAX+2];
910 if( !h->lookahead->next.i_size )
913 if( h->param.rc.b_stat_read )
915 /* Use the frame types from the first pass */
916 for( i = 0; i < h->lookahead->next.i_size; i++ )
917 h->lookahead->next.list[i]->i_type =
918 x264_ratecontrol_slice_type( h, h->lookahead->next.list[i]->i_frame );
920 else if( (h->param.i_bframe && h->param.i_bframe_adaptive)
921 || h->param.i_scenecut_threshold
922 || h->param.rc.b_mb_tree
923 || (h->param.rc.i_vbv_buffer_size && h->param.rc.i_lookahead) )
924 x264_slicetype_analyse( h, 0 );
926 for( bframes = 0, brefs = 0;; bframes++ )
928 frm = h->lookahead->next.list[bframes];
929 if( frm->i_type == X264_TYPE_BREF && h->param.i_bframe_pyramid < X264_B_PYRAMID_NORMAL &&
930 brefs == h->param.i_bframe_pyramid )
932 frm->i_type = X264_TYPE_B;
933 x264_log( h, X264_LOG_WARNING, "B-ref at frame %d incompatible with B-pyramid %s \n",
934 frm->i_frame, x264_b_pyramid_names[h->param.i_bframe_pyramid] );
936 /* pyramid with multiple B-refs needs a big enough dpb that the preceding P-frame stays available.
937 smaller dpb could be supported by smart enough use of mmco, but it's easier just to forbid it. */
938 else if( frm->i_type == X264_TYPE_BREF && h->param.i_bframe_pyramid == X264_B_PYRAMID_NORMAL &&
939 brefs && h->param.i_frame_reference <= (brefs+3) )
941 frm->i_type = X264_TYPE_B;
942 x264_log( h, X264_LOG_WARNING, "B-ref at frame %d incompatible with B-pyramid %s and %d reference frames\n",
943 frm->i_frame, x264_b_pyramid_names[h->param.i_bframe_pyramid], h->param.i_frame_reference );
947 if( frm->i_frame - h->lookahead->i_last_idr >= h->param.i_keyint_max )
949 if( frm->i_type == X264_TYPE_AUTO )
950 frm->i_type = X264_TYPE_IDR;
951 if( frm->i_type != X264_TYPE_IDR )
952 x264_log( h, X264_LOG_WARNING, "specified frame type (%d) is not compatible with keyframe interval\n", frm->i_type );
954 if( frm->i_type == X264_TYPE_IDR )
957 h->lookahead->i_last_idr = frm->i_frame;
961 h->lookahead->next.list[bframes]->i_type = X264_TYPE_P;
965 if( bframes == h->param.i_bframe ||
966 !h->lookahead->next.list[bframes+1] )
968 if( IS_X264_TYPE_B( frm->i_type ) )
969 x264_log( h, X264_LOG_WARNING, "specified frame type is not compatible with max B-frames\n" );
970 if( frm->i_type == X264_TYPE_AUTO
971 || IS_X264_TYPE_B( frm->i_type ) )
972 frm->i_type = X264_TYPE_P;
975 if( frm->i_type == X264_TYPE_BREF )
978 if( frm->i_type == X264_TYPE_AUTO )
979 frm->i_type = X264_TYPE_B;
981 else if( !IS_X264_TYPE_B( frm->i_type ) ) break;
985 h->lookahead->next.list[bframes-1]->b_last_minigop_bframe = 1;
986 h->lookahead->next.list[bframes]->i_bframes = bframes;
988 /* insert a bref into the sequence */
989 if( h->param.i_bframe_pyramid && bframes > 1 && !brefs )
991 h->lookahead->next.list[bframes/2]->i_type = X264_TYPE_BREF;
995 /* calculate the frame costs ahead of time for x264_rc_analyse_slice while we still have lowres */
996 if( h->param.rc.i_rc_method != X264_RC_CQP )
998 x264_mb_analysis_t a;
1000 p1 = b = bframes + 1;
1002 x264_lowres_context_init( h, &a );
1004 frames[0] = h->lookahead->last_nonb;
1005 memcpy( &frames[1], h->lookahead->next.list, (bframes+1) * sizeof(x264_frame_t*) );
1006 if( IS_X264_TYPE_I( h->lookahead->next.list[bframes]->i_type ) )
1011 x264_slicetype_frame_cost( h, &a, frames, p0, p1, b, 0 );
1013 if( (p0 != p1 || bframes) && h->param.rc.i_vbv_buffer_size )
1015 /* We need the intra costs for row SATDs. */
1016 x264_slicetype_frame_cost( h, &a, frames, b, b, b, 0 );
1018 /* We need B-frame costs for row SATDs. */
1020 for( b = 1; b <= bframes; b++ )
1022 if( frames[b]->i_type == X264_TYPE_B )
1023 for( p1 = b; frames[p1]->i_type == X264_TYPE_B; )
1027 x264_slicetype_frame_cost( h, &a, frames, p0, p1, b, 0 );
1028 if( frames[b]->i_type == X264_TYPE_BREF )
1034 /* shift sequence to coded order.
1035 use a small temporary list to avoid shifting the entire next buffer around */
1036 int i_dts = h->lookahead->next.list[0]->i_frame;
1039 int index[] = { brefs+1, 1 };
1040 for( i = 0; i < bframes; i++ )
1041 frames[ index[h->lookahead->next.list[i]->i_type == X264_TYPE_BREF]++ ] = h->lookahead->next.list[i];
1042 frames[0] = h->lookahead->next.list[bframes];
1043 memcpy( h->lookahead->next.list, frames, (bframes+1) * sizeof(x264_frame_t*) );
1045 for( i = 0; i <= bframes; i++ )
1046 h->lookahead->next.list[i]->i_dts = i_dts++;
1049 int x264_rc_analyse_slice( x264_t *h )
1054 if( IS_X264_TYPE_I(h->fenc->i_type) )
1056 else if( h->fenc->i_type == X264_TYPE_P )
1057 p1 = b = h->fenc->i_bframes + 1;
1060 p1 = (h->fref1[0]->i_poc - h->fref0[0]->i_poc)/2;
1061 b = (h->fenc->i_poc - h->fref0[0]->i_poc)/2;
1063 /* We don't need to assign p0/p1 since we are not performing any real analysis here. */
1064 x264_frame_t **frames = &h->fenc - b;
1066 /* cost should have been already calculated by x264_slicetype_decide */
1067 cost = frames[b]->i_cost_est[b-p0][p1-b];
1068 assert( cost >= 0 );
1070 if( h->param.rc.b_mb_tree && !h->param.rc.b_stat_read )
1072 cost = x264_slicetype_frame_cost_recalculate( h, frames, p0, p1, b );
1073 if( b && h->param.rc.i_vbv_buffer_size )
1074 x264_slicetype_frame_cost_recalculate( h, frames, b, b, b );
1076 /* In AQ, use the weighted score instead. */
1077 else if( h->param.rc.i_aq_mode )
1078 cost = frames[b]->i_cost_est_aq[b-p0][p1-b];
1080 h->fenc->i_row_satd = h->fenc->i_row_satds[b-p0][p1-b];
1081 h->fdec->i_row_satd = h->fdec->i_row_satds[b-p0][p1-b];
1082 h->fdec->i_satd = cost;
1083 memcpy( h->fdec->i_row_satd, h->fenc->i_row_satd, h->sps->i_mb_height * sizeof(int) );
1084 if( !IS_X264_TYPE_I(h->fenc->i_type) )
1085 memcpy( h->fdec->i_row_satds[0][0], h->fenc->i_row_satds[0][0], h->sps->i_mb_height * sizeof(int) );