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];
377 for( h->mb.i_mb_y = h->sps->i_mb_height - 1; h->mb.i_mb_y >= 0; h->mb.i_mb_y-- )
379 row_satd[ h->mb.i_mb_y ] = 0;
380 for( h->mb.i_mb_x = h->sps->i_mb_width - 1; h->mb.i_mb_x >= 0; h->mb.i_mb_x-- )
382 int i_mb_xy = h->mb.i_mb_x + h->mb.i_mb_y*h->mb.i_mb_stride;
383 int i_mb_cost = frames[b]->lowres_costs[b-p0][p1-b][i_mb_xy];
384 float qp_adj = frames[b]->f_qp_offset[i_mb_xy];
385 i_mb_cost = (i_mb_cost * x264_exp2fix8(qp_adj) + 128) >> 8;
386 row_satd[ h->mb.i_mb_y ] += i_mb_cost;
387 if( (h->mb.i_mb_y > 0 && h->mb.i_mb_y < h->sps->i_mb_height - 1 &&
388 h->mb.i_mb_x > 0 && h->mb.i_mb_x < h->sps->i_mb_width - 1) ||
389 h->sps->i_mb_width <= 2 || h->sps->i_mb_height <= 2 )
391 i_score += i_mb_cost;
398 static void x264_macroblock_tree_finish( x264_t *h, x264_frame_t *frame, int b_bidir )
403 memcpy( frame->f_qp_offset, frame->f_qp_offset_aq, sizeof( frame->f_qp_offset ) );
406 /* Allow the strength to be adjusted via qcompress, since the two
407 * concepts are very similar. */
408 float strength = 5.0f * (1.0f - h->param.rc.f_qcompress);
409 for( mb_index = 0; mb_index < h->mb.i_mb_count; mb_index++ )
411 int intra_cost = (frame->i_intra_cost[mb_index] * frame->i_inv_qscale_factor[mb_index]+128)>>8;
414 int propagate_cost = frame->i_propagate_cost[mb_index];
415 float log2_ratio = x264_log2(intra_cost + propagate_cost) - x264_log2(intra_cost);
416 frame->f_qp_offset[mb_index] = frame->f_qp_offset_aq[mb_index] - strength * log2_ratio;
422 static void x264_macroblock_tree_propagate( x264_t *h, x264_frame_t **frames, int p0, int p1, int b )
424 uint16_t *ref_costs[2] = {frames[p0]->i_propagate_cost,frames[p1]->i_propagate_cost};
425 int dist_scale_factor = ( ((b-p0) << 8) + ((p1-p0) >> 1) ) / (p1-p0);
426 int i_bipred_weight = h->param.analyse.b_weighted_bipred ? 64 - (dist_scale_factor>>2) : 32;
427 int16_t (*mvs[2])[2] = { frames[b]->lowres_mvs[0][b-p0-1], frames[b]->lowres_mvs[1][p1-b-1] };
428 int bipred_weights[2] = {i_bipred_weight, 64 - i_bipred_weight};
429 int *buf = h->scratch_buffer;
431 for( h->mb.i_mb_y = 0; h->mb.i_mb_y < h->sps->i_mb_height; h->mb.i_mb_y++ )
433 int mb_index = h->mb.i_mb_y*h->mb.i_mb_stride;
434 h->mc.mbtree_propagate_cost( buf, frames[b]->i_propagate_cost+mb_index,
435 frames[b]->i_intra_cost+mb_index, frames[b]->lowres_costs[b-p0][p1-b]+mb_index,
436 frames[b]->i_inv_qscale_factor+mb_index, h->sps->i_mb_width );
437 for( h->mb.i_mb_x = 0; h->mb.i_mb_x < h->sps->i_mb_width; h->mb.i_mb_x++, mb_index++ )
439 int propagate_amount = buf[h->mb.i_mb_x];
440 /* Don't propagate for an intra block. */
441 if( propagate_amount > 0 )
443 /* Access width-2 bitfield. */
444 int lists_used = (frames[b]->lowres_inter_types[b-p0][p1-b][mb_index>>2] >> ((mb_index&3)*2))&3;
446 /* Follow the MVs to the previous frame(s). */
447 for( list = 0; list < 2; list++ )
448 if( (lists_used >> list)&1 )
450 int x = mvs[list][mb_index][0];
451 int y = mvs[list][mb_index][1];
452 int listamount = propagate_amount;
453 int mbx = (x>>5)+h->mb.i_mb_x;
454 int mby = (y>>5)+h->mb.i_mb_y;
455 int idx0 = mbx + mby*h->mb.i_mb_stride;
457 int idx2 = idx0 + h->mb.i_mb_stride;
458 int idx3 = idx0 + h->mb.i_mb_stride + 1;
461 int idx0weight = (32-y)*(32-x);
462 int idx1weight = (32-y)*x;
463 int idx2weight = y*(32-x);
464 int idx3weight = y*x;
466 /* Apply bipred weighting. */
467 if( lists_used == 3 )
468 listamount = (listamount * bipred_weights[list] + 32) >> 6;
470 #define CLIP_ADD(s,x) (s) = X264_MIN((s)+(x),(1<<16)-1)
472 /* We could just clip the MVs, but pixels that lie outside the frame probably shouldn't
474 if( mbx < h->sps->i_mb_width-1 && mby < h->sps->i_mb_height-1 && mbx >= 0 && mby >= 0 )
476 CLIP_ADD( ref_costs[list][idx0], (listamount*idx0weight+512)>>10 );
477 CLIP_ADD( ref_costs[list][idx1], (listamount*idx1weight+512)>>10 );
478 CLIP_ADD( ref_costs[list][idx2], (listamount*idx2weight+512)>>10 );
479 CLIP_ADD( ref_costs[list][idx3], (listamount*idx3weight+512)>>10 );
481 else /* Check offsets individually */
483 if( mbx < h->sps->i_mb_width && mby < h->sps->i_mb_height && mbx >= 0 && mby >= 0 )
484 CLIP_ADD( ref_costs[list][idx0], (listamount*idx0weight+512)>>10 );
485 if( mbx+1 < h->sps->i_mb_width && mby < h->sps->i_mb_height && mbx+1 >= 0 && mby >= 0 )
486 CLIP_ADD( ref_costs[list][idx1], (listamount*idx1weight+512)>>10 );
487 if( mbx < h->sps->i_mb_width && mby+1 < h->sps->i_mb_height && mbx >= 0 && mby+1 >= 0 )
488 CLIP_ADD( ref_costs[list][idx2], (listamount*idx2weight+512)>>10 );
489 if( mbx+1 < h->sps->i_mb_width && mby+1 < h->sps->i_mb_height && mbx+1 >= 0 && mby+1 >= 0 )
490 CLIP_ADD( ref_costs[list][idx3], (listamount*idx3weight+512)>>10 );
497 if( h->param.rc.i_vbv_buffer_size )
498 x264_macroblock_tree_finish( h, frames[b], b != p1 );
501 static void x264_macroblock_tree( x264_t *h, x264_mb_analysis_t *a, x264_frame_t **frames, int num_frames, int b_intra )
503 int i, idx = !b_intra;
504 int last_nonb, cur_nonb = 1;
506 x264_slicetype_frame_cost( h, a, frames, 0, 0, 0, 0 );
509 while( i > 0 && frames[i]->i_type == X264_TYPE_B )
516 memset( frames[last_nonb]->i_propagate_cost, 0, h->mb.i_mb_count * sizeof(uint16_t) );
520 while( frames[cur_nonb]->i_type == X264_TYPE_B && cur_nonb > 0 )
524 x264_slicetype_frame_cost( h, a, frames, cur_nonb, last_nonb, last_nonb, 0 );
525 memset( frames[cur_nonb]->i_propagate_cost, 0, h->mb.i_mb_count * sizeof(uint16_t) );
526 x264_macroblock_tree_propagate( h, frames, cur_nonb, last_nonb, last_nonb );
527 while( frames[i]->i_type == X264_TYPE_B && i > 0 )
529 x264_slicetype_frame_cost( h, a, frames, cur_nonb, last_nonb, i, 0 );
530 memset( frames[i]->i_propagate_cost, 0, h->mb.i_mb_count * sizeof(uint16_t) );
531 x264_macroblock_tree_propagate( h, frames, cur_nonb, last_nonb, i );
534 last_nonb = cur_nonb;
537 x264_macroblock_tree_finish( h, frames[last_nonb], 0 );
540 static int x264_vbv_frame_cost( x264_t *h, x264_mb_analysis_t *a, x264_frame_t **frames, int p0, int p1, int b )
542 int cost = x264_slicetype_frame_cost( h, a, frames, p0, p1, b, 0 );
543 if( h->param.rc.i_aq_mode )
545 if( h->param.rc.b_mb_tree )
546 return x264_slicetype_frame_cost_recalculate( h, frames, p0, p1, b );
548 return frames[b]->i_cost_est_aq[b-p0][p1-b];
553 static void x264_vbv_lookahead( x264_t *h, x264_mb_analysis_t *a, x264_frame_t **frames, int num_frames, int keyframe )
555 int last_nonb = 0, cur_nonb = 1, next_nonb, i, idx = 0;
556 while( cur_nonb < num_frames && frames[cur_nonb]->i_type == X264_TYPE_B )
558 next_nonb = keyframe ? last_nonb : cur_nonb;
560 while( cur_nonb <= num_frames )
562 /* P/I cost: This shouldn't include the cost of next_nonb */
563 if( next_nonb != cur_nonb )
565 int p0 = IS_X264_TYPE_I( frames[cur_nonb]->i_type ) ? cur_nonb : last_nonb;
566 frames[next_nonb]->i_planned_satd[idx] = x264_vbv_frame_cost( h, a, frames, p0, cur_nonb, cur_nonb );
567 frames[next_nonb]->i_planned_type[idx] = frames[cur_nonb]->i_type;
570 /* Handle the B-frames: coded order */
571 for( i = last_nonb+1; i < cur_nonb; i++, idx++ )
573 frames[next_nonb]->i_planned_satd[idx] = x264_vbv_frame_cost( h, a, frames, last_nonb, cur_nonb, i );
574 frames[next_nonb]->i_planned_type[idx] = X264_TYPE_B;
576 last_nonb = cur_nonb;
578 while( cur_nonb <= num_frames && frames[cur_nonb]->i_type == X264_TYPE_B )
581 frames[next_nonb]->i_planned_type[idx] = X264_TYPE_AUTO;
584 static int x264_slicetype_path_cost( x264_t *h, x264_mb_analysis_t *a, x264_frame_t **frames, char *path, int threshold )
589 path--; /* Since the 1st path element is really the second frame */
594 /* Find the location of the next P-frame. */
595 while( path[next_p] && path[next_p] != 'P' )
597 /* Return if the path doesn't end on a P-frame. */
598 if( path[next_p] != 'P' )
601 /* Add the cost of the P-frame found above */
602 cost += x264_slicetype_frame_cost( h, a, frames, cur_p, next_p, next_p, 0 );
603 /* Early terminate if the cost we have found is larger than the best path cost so far */
604 if( cost > threshold )
607 for( next_b = loc; next_b < next_p && cost < threshold; next_b++ )
608 cost += x264_slicetype_frame_cost( h, a, frames, cur_p, next_p, next_b, 0 );
616 /* Viterbi/trellis slicetype decision algorithm. */
617 /* Uses strings due to the fact that the speed of the control functions is
618 negligable compared to the cost of running slicetype_frame_cost, and because
619 it makes debugging easier. */
620 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] )
622 char paths[X264_BFRAME_MAX+2][X264_LOOKAHEAD_MAX] = {{0}};
623 int num_paths = X264_MIN(max_bframes+1, length);
625 int best_cost = COST_MAX;
626 int best_path_index = 0;
627 length = X264_MIN( length, X264_LOOKAHEAD_MAX );
629 /* Iterate over all currently possible paths */
630 for( path = 0; path < num_paths; path++ )
632 /* Add suffixes to the current path */
633 int len = length - (path + 1);
634 memcpy( paths[path], best_paths[len], len );
635 memset( paths[path]+len, 'B', path );
636 strcat( paths[path], "P" );
638 /* Calculate the actual cost of the current path */
639 int cost = x264_slicetype_path_cost( h, a, frames, paths[path], best_cost );
640 if( cost < best_cost )
643 best_path_index = path;
647 /* Store the best path. */
648 memcpy( best_paths[length], paths[best_path_index], length );
651 static int scenecut_internal( x264_t *h, x264_mb_analysis_t *a, x264_frame_t **frames, int p0, int p1, int print )
653 x264_frame_t *frame = frames[p1];
654 x264_slicetype_frame_cost( h, a, frames, p0, p1, p1, 0 );
656 int icost = frame->i_cost_est[0][0];
657 int pcost = frame->i_cost_est[p1-p0][0];
659 int i_gop_size = frame->i_frame - h->lookahead->i_last_idr;
660 float f_thresh_max = h->param.i_scenecut_threshold / 100.0;
661 /* magic numbers pulled out of thin air */
662 float f_thresh_min = f_thresh_max * h->param.i_keyint_min
663 / ( h->param.i_keyint_max * 4 );
666 if( h->param.i_keyint_min == h->param.i_keyint_max )
667 f_thresh_min= f_thresh_max;
668 if( i_gop_size < h->param.i_keyint_min / 4 )
669 f_bias = f_thresh_min / 4;
670 else if( i_gop_size <= h->param.i_keyint_min )
671 f_bias = f_thresh_min * i_gop_size / h->param.i_keyint_min;
674 f_bias = f_thresh_min
675 + ( f_thresh_max - f_thresh_min )
676 * ( i_gop_size - h->param.i_keyint_min )
677 / ( h->param.i_keyint_max - h->param.i_keyint_min ) ;
680 res = pcost >= (1.0 - f_bias) * icost;
683 int imb = frame->i_intra_mbs[p1-p0];
684 int pmb = NUM_MBS - imb;
685 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",
687 icost, pcost, 1. - (double)pcost / icost,
688 f_bias, i_gop_size, imb, pmb );
693 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 )
695 int curp0, curp1, i, maxp1 = p0 + 1;
697 /* Only do analysis during a normal scenecut check. */
698 if( real_scenecut && h->param.i_bframe )
700 /* Look ahead to avoid coding short flashes as scenecuts. */
701 if( h->param.i_bframe_adaptive == X264_B_ADAPT_TRELLIS )
702 /* Don't analyse any more frames than the trellis would have covered. */
703 maxp1 += h->param.i_bframe;
706 maxp1 = X264_MIN( maxp1, num_frames );
708 /* Where A and B are scenes: AAAAAABBBAAAAAA
709 * If BBB is shorter than (maxp1-p0), it is detected as a flash
710 * and not considered a scenecut. */
711 for( curp1 = p1; curp1 <= maxp1; curp1++ )
712 if( !scenecut_internal( h, a, frames, p0, curp1, 0 ) )
713 /* Any frame in between p0 and cur_p1 cannot be a real scenecut. */
714 for( i = curp1; i > p0; i-- )
715 frames[i]->b_scenecut = 0;
717 /* Where A-F are scenes: AAAAABBCCDDEEFFFFFF
718 * If each of BB ... EE are shorter than (maxp1-p0), they are
719 * detected as flashes and not considered scenecuts.
720 * Instead, the first F frame becomes a scenecut. */
721 for( curp0 = p0; curp0 < maxp1; curp0++ )
722 if( scenecut_internal( h, a, frames, curp0, maxp1, 0 ) )
723 /* If cur_p0 is the p0 of a scenecut, it cannot be the p1 of a scenecut. */
724 frames[curp0]->b_scenecut = 0;
727 /* Ignore frames that are part of a flash, i.e. cannot be real scenecuts. */
728 if( !frames[p1]->b_scenecut )
730 return scenecut_internal( h, a, frames, p0, p1, real_scenecut );
733 void x264_slicetype_analyse( x264_t *h, int keyframe )
735 x264_mb_analysis_t a;
736 x264_frame_t *frames[X264_LOOKAHEAD_MAX+3] = { NULL, };
737 int num_frames, orig_num_frames, keyint_limit, idr_frame_type, i, j;
738 int i_mb_count = NUM_MBS;
739 int cost1p0, cost2p0, cost1b1, cost2p1;
740 int i_max_search = X264_MIN( h->lookahead->next.i_size, X264_LOOKAHEAD_MAX );
741 if( h->param.b_deterministic )
742 i_max_search = X264_MIN( i_max_search, h->lookahead->i_slicetype_length + !keyframe );
744 assert( h->frames.b_have_lowres );
746 if( !h->lookahead->last_nonb )
748 frames[0] = h->lookahead->last_nonb;
749 for( j = 0; j < i_max_search && h->lookahead->next.list[j]->i_type == X264_TYPE_AUTO; j++ )
750 frames[j+1] = h->lookahead->next.list[j];
755 keyint_limit = h->param.i_keyint_max - frames[0]->i_frame + h->lookahead->i_last_idr - 1;
756 orig_num_frames = num_frames = X264_MIN( j, keyint_limit );
758 x264_lowres_context_init( h, &a );
759 idr_frame_type = frames[1]->i_frame - h->lookahead->i_last_idr >= h->param.i_keyint_min ? X264_TYPE_IDR : X264_TYPE_I;
761 /* This is important psy-wise: if we have a non-scenecut keyframe,
762 * there will be significant visual artifacts if the frames just before
763 * go down in quality due to being referenced less, despite it being
764 * more RD-optimal. */
765 if( (h->param.analyse.b_psy && h->param.rc.b_mb_tree) || h->param.rc.i_vbv_buffer_size )
767 else if( num_frames == 1 )
769 frames[1]->i_type = X264_TYPE_P;
770 if( h->param.i_scenecut_threshold && scenecut( h, &a, frames, 0, 1, 1, orig_num_frames ) )
771 frames[1]->i_type = idr_frame_type;
774 else if( num_frames == 0 )
776 frames[1]->i_type = idr_frame_type;
780 char best_paths[X264_LOOKAHEAD_MAX][X264_LOOKAHEAD_MAX] = {"","P"};
783 int max_bframes = X264_MIN(num_frames-1, h->param.i_bframe);
784 int num_analysed_frames = num_frames;
786 if( h->param.i_scenecut_threshold && scenecut( h, &a, frames, 0, 1, 1, orig_num_frames ) )
788 frames[1]->i_type = idr_frame_type;
792 if( h->param.i_bframe )
794 if( h->param.i_bframe_adaptive == X264_B_ADAPT_TRELLIS )
796 /* Perform the frametype analysis. */
797 for( n = 2; n < num_frames-1; n++ )
798 x264_slicetype_path( h, &a, frames, n, max_bframes, best_paths );
801 num_bframes = strspn( best_paths[num_frames-2], "B" );
802 /* Load the results of the analysis into the frame types. */
803 for( j = 1; j < num_frames; j++ )
804 frames[j]->i_type = best_paths[num_frames-2][j-1] == 'B' ? X264_TYPE_B : X264_TYPE_P;
806 frames[num_frames]->i_type = X264_TYPE_P;
808 else if( h->param.i_bframe_adaptive == X264_B_ADAPT_FAST )
810 for( i = 0; i < num_frames-(2-!i); )
812 cost2p1 = x264_slicetype_frame_cost( h, &a, frames, i+0, i+2, i+2, 1 );
813 if( frames[i+2]->i_intra_mbs[2] > i_mb_count / 2 )
815 frames[i+1]->i_type = X264_TYPE_P;
816 frames[i+2]->i_type = X264_TYPE_P;
821 cost1b1 = x264_slicetype_frame_cost( h, &a, frames, i+0, i+2, i+1, 0 );
822 cost1p0 = x264_slicetype_frame_cost( h, &a, frames, i+0, i+1, i+1, 0 );
823 cost2p0 = x264_slicetype_frame_cost( h, &a, frames, i+1, i+2, i+2, 0 );
825 if( cost1p0 + cost2p0 < cost1b1 + cost2p1 )
827 frames[i+1]->i_type = X264_TYPE_P;
828 frames[i+2]->i_type = X264_TYPE_P;
833 // arbitrary and untuned
834 #define INTER_THRESH 300
835 #define P_SENS_BIAS (50 - h->param.i_bframe_bias)
836 frames[i+1]->i_type = X264_TYPE_B;
837 frames[i+2]->i_type = X264_TYPE_P;
839 for( j = i+2; j <= X264_MIN( h->param.i_bframe, num_frames-1 ); j++ )
841 int pthresh = X264_MAX(INTER_THRESH - P_SENS_BIAS * (j-i-1), INTER_THRESH/10);
842 int pcost = x264_slicetype_frame_cost( h, &a, frames, i+0, j+1, j+1, 1 );
844 if( pcost > pthresh*i_mb_count || frames[j+1]->i_intra_mbs[j-i+1] > i_mb_count/3 )
846 frames[j]->i_type = X264_TYPE_P;
850 frames[j]->i_type = X264_TYPE_B;
854 frames[i+!i]->i_type = X264_TYPE_P;
856 while( num_bframes < num_frames && frames[num_bframes+1]->i_type == X264_TYPE_B )
861 num_bframes = X264_MIN(num_frames-1, h->param.i_bframe);
862 for( j = 1; j < num_frames; j++ )
863 frames[j]->i_type = (j%(num_bframes+1)) ? X264_TYPE_B : X264_TYPE_P;
864 frames[num_frames]->i_type = X264_TYPE_P;
867 /* Check scenecut on the first minigop. */
868 for( j = 1; j < num_bframes+1; j++ )
869 if( h->param.i_scenecut_threshold && scenecut( h, &a, frames, j, j+1, 0, orig_num_frames ) )
871 frames[j]->i_type = X264_TYPE_P;
872 num_analysed_frames = j;
876 reset_start = keyframe ? 1 : X264_MIN( num_bframes+2, num_analysed_frames+1 );
880 for( j = 1; j < num_frames; j++ )
881 frames[j]->i_type = X264_TYPE_P;
882 reset_start = !keyframe + 1;
886 for( j = 1; j <= num_frames; j++ )
887 if( frames[j]->i_type == X264_TYPE_AUTO )
888 frames[j]->i_type = X264_TYPE_P;
890 /* Perform the actual macroblock tree analysis.
891 * Don't go farther than the maximum keyframe interval; this helps in short GOPs. */
892 if( h->param.rc.b_mb_tree )
893 x264_macroblock_tree( h, &a, frames, X264_MIN(num_frames, h->param.i_keyint_max), keyframe );
895 /* Enforce keyframe limit. */
896 for( j = 0; j < num_frames; j++ )
898 if( ((j-keyint_limit) % h->param.i_keyint_max) == 0 )
900 if( j && h->param.i_keyint_max > 1 )
901 frames[j]->i_type = X264_TYPE_P;
902 frames[j+1]->i_type = X264_TYPE_IDR;
903 reset_start = X264_MIN( reset_start, j+2 );
907 if( h->param.rc.i_vbv_buffer_size )
908 x264_vbv_lookahead( h, &a, frames, num_frames, keyframe );
910 /* Restore frametypes for all frames that haven't actually been decided yet. */
911 for( j = reset_start; j <= num_frames; j++ )
912 frames[j]->i_type = X264_TYPE_AUTO;
915 void x264_slicetype_decide( x264_t *h )
921 if( !h->lookahead->next.i_size )
924 if( h->param.rc.b_stat_read )
926 /* Use the frame types from the first pass */
927 for( i = 0; i < h->lookahead->next.i_size; i++ )
928 h->lookahead->next.list[i]->i_type =
929 x264_ratecontrol_slice_type( h, h->lookahead->next.list[i]->i_frame );
931 else if( (h->param.i_bframe && h->param.i_bframe_adaptive)
932 || h->param.i_scenecut_threshold
933 || h->param.rc.b_mb_tree
934 || (h->param.rc.i_vbv_buffer_size && h->param.rc.i_lookahead) )
935 x264_slicetype_analyse( h, 0 );
937 for( bframes = 0;; bframes++ )
939 frm = h->lookahead->next.list[bframes];
942 if( frm->i_frame - h->lookahead->i_last_idr >= h->param.i_keyint_max )
944 if( frm->i_type == X264_TYPE_AUTO )
945 frm->i_type = X264_TYPE_IDR;
946 if( frm->i_type != X264_TYPE_IDR )
947 x264_log( h, X264_LOG_WARNING, "specified frame type (%d) is not compatible with keyframe interval\n", frm->i_type );
949 if( frm->i_type == X264_TYPE_IDR )
952 h->lookahead->i_last_idr = frm->i_frame;
956 h->lookahead->next.list[bframes]->i_type = X264_TYPE_P;
960 if( bframes == h->param.i_bframe ||
961 !h->lookahead->next.list[bframes+1] )
963 if( IS_X264_TYPE_B( frm->i_type ) )
964 x264_log( h, X264_LOG_WARNING, "specified frame type is not compatible with max B-frames\n" );
965 if( frm->i_type == X264_TYPE_AUTO
966 || IS_X264_TYPE_B( frm->i_type ) )
967 frm->i_type = X264_TYPE_P;
970 if( frm->i_type == X264_TYPE_AUTO )
971 frm->i_type = X264_TYPE_B;
973 else if( !IS_X264_TYPE_B( frm->i_type ) ) break;
977 h->lookahead->next.list[bframes-1]->b_last_minigop_bframe = 1;
978 h->lookahead->next.list[bframes]->i_bframes = bframes;
980 /* calculate the frame costs ahead of time for x264_rc_analyse_slice while we still have lowres */
981 if( h->param.rc.i_rc_method != X264_RC_CQP )
983 x264_mb_analysis_t a;
984 x264_frame_t *frames[X264_BFRAME_MAX+2] = { NULL, };
987 x264_lowres_context_init( h, &a );
989 if( IS_X264_TYPE_I( h->lookahead->next.list[bframes]->i_type ) )
992 p1 = b = bframes + 1;
993 frames[p0] = h->lookahead->last_nonb;
994 frames[b] = h->lookahead->next.list[bframes];
996 x264_slicetype_frame_cost( h, &a, frames, p0, p1, b, 0 );
998 if( b && h->param.rc.i_vbv_buffer_size )
1000 /* We need the intra costs for row SATDs. */
1001 x264_slicetype_frame_cost( h, &a, frames, b, b, b, 0 );
1003 /* We need B-frame costs for row SATDs. */
1004 for( i = 0; i < bframes; i++ )
1007 frames[b] = h->lookahead->next.list[i];
1008 x264_slicetype_frame_cost( h, &a, frames, p0, p1, b, 0 );
1014 int x264_rc_analyse_slice( x264_t *h )
1016 x264_frame_t *frames[X264_BFRAME_MAX+2] = { NULL, };
1020 if( IS_X264_TYPE_I(h->fenc->i_type) )
1022 else if( h->fenc->i_type == X264_TYPE_P )
1023 p1 = b = h->fenc->i_bframes + 1;
1026 p1 = (h->fref1[0]->i_poc - h->fref0[0]->i_poc)/2;
1027 b = (h->fref1[0]->i_poc - h->fenc->i_poc)/2;
1028 frames[p1] = h->fref1[0];
1030 frames[p0] = h->fref0[0];
1031 frames[b] = h->fenc;
1033 /* cost should have been already calculated by x264_slicetype_decide */
1034 cost = frames[b]->i_cost_est[b-p0][p1-b];
1035 assert( cost >= 0 );
1037 if( h->param.rc.b_mb_tree && !h->param.rc.b_stat_read )
1039 cost = x264_slicetype_frame_cost_recalculate( h, frames, p0, p1, b );
1040 if( b && h->param.rc.i_vbv_buffer_size )
1041 x264_slicetype_frame_cost_recalculate( h, frames, b, b, b );
1043 /* In AQ, use the weighted score instead. */
1044 else if( h->param.rc.i_aq_mode )
1045 cost = frames[b]->i_cost_est_aq[b-p0][p1-b];
1047 h->fenc->i_row_satd = h->fenc->i_row_satds[b-p0][p1-b];
1048 h->fdec->i_row_satd = h->fdec->i_row_satds[b-p0][p1-b];
1049 h->fdec->i_satd = cost;
1050 memcpy( h->fdec->i_row_satd, h->fenc->i_row_satd, h->sps->i_mb_height * sizeof(int) );
1051 if( !IS_X264_TYPE_I(h->fenc->i_type) )
1052 memcpy( h->fdec->i_row_satds[0][0], h->fenc->i_row_satds[0][0], h->sps->i_mb_height * sizeof(int) );