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 *****************************************************************************/
27 #include "common/common.h"
28 #include "common/cpu.h"
29 #include "macroblock.h"
33 static int x264_lowres_context_init( x264_t *h, x264_mb_analysis_t *a )
35 a->i_qp = 12; // arbitrary, but low because SATD scores are 1/4 normal
36 a->i_lambda = x264_lambda_tab[ a->i_qp ];
37 if( x264_mb_analyse_load_costs( h, a ) )
39 h->mb.i_me_method = X264_MIN( X264_ME_HEX, h->param.analyse.i_me_method ); // maybe dia?
40 h->mb.i_subpel_refine = 4; // 3 should be enough, but not tweaking for speed now
41 h->mb.b_chroma_me = 0;
45 int x264_lowres_context_alloc( x264_t *h )
48 return x264_lowres_context_init( h, &a );
51 static int x264_slicetype_mb_cost( x264_t *h, x264_mb_analysis_t *a,
52 x264_frame_t **frames, int p0, int p1, int b,
53 int dist_scale_factor, int do_search[2] )
55 x264_frame_t *fref0 = frames[p0];
56 x264_frame_t *fref1 = frames[p1];
57 x264_frame_t *fenc = frames[b];
58 const int b_bidir = (b < p1);
59 const int i_mb_x = h->mb.i_mb_x;
60 const int i_mb_y = h->mb.i_mb_y;
61 const int i_mb_stride = h->sps->i_mb_width;
62 const int i_mb_xy = i_mb_x + i_mb_y * i_mb_stride;
63 const int i_stride = fenc->i_stride_lowres;
64 const int i_pel_offset = 8 * ( i_mb_x + i_mb_y * i_stride );
65 const int i_bipred_weight = h->param.analyse.b_weighted_bipred ? 64 - (dist_scale_factor>>2) : 32;
66 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] };
67 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] };
69 DECLARE_ALIGNED_8( uint8_t pix1[9*FDEC_STRIDE] );
70 uint8_t *pix2 = pix1+8;
72 int i_bcost = COST_MAX;
76 h->mb.pic.p_fenc[0] = h->mb.pic.fenc_buf;
77 h->mc.copy[PIXEL_8x8]( h->mb.pic.p_fenc[0], FENC_STRIDE, &fenc->lowres[0][i_pel_offset], i_stride, 8 );
82 // no need for h->mb.mv_min[]
83 h->mb.mv_min_fpel[0] = -8*h->mb.i_mb_x - 4;
84 h->mb.mv_max_fpel[0] = 8*( h->sps->i_mb_width - h->mb.i_mb_x - 1 ) + 4;
85 h->mb.mv_min_spel[0] = 4*( h->mb.mv_min_fpel[0] - 8 );
86 h->mb.mv_max_spel[0] = 4*( h->mb.mv_max_fpel[0] + 8 );
87 if( h->mb.i_mb_x >= h->sps->i_mb_width - 2 )
89 h->mb.mv_min_fpel[1] = -8*h->mb.i_mb_y - 4;
90 h->mb.mv_max_fpel[1] = 8*( h->sps->i_mb_height - h->mb.i_mb_y - 1 ) + 4;
91 h->mb.mv_min_spel[1] = 4*( h->mb.mv_min_fpel[1] - 8 );
92 h->mb.mv_max_spel[1] = 4*( h->mb.mv_max_fpel[1] + 8 );
95 #define LOAD_HPELS_LUMA(dst, src) \
97 (dst)[0] = &(src)[0][i_pel_offset]; \
98 (dst)[1] = &(src)[1][i_pel_offset]; \
99 (dst)[2] = &(src)[2][i_pel_offset]; \
100 (dst)[3] = &(src)[3][i_pel_offset]; \
102 #define CLIP_MV( mv ) \
104 mv[0] = x264_clip3( mv[0], h->mb.mv_min_spel[0], h->mb.mv_max_spel[0] ); \
105 mv[1] = x264_clip3( mv[1], h->mb.mv_min_spel[1], h->mb.mv_max_spel[1] ); \
107 #define TRY_BIDIR( mv0, mv1, penalty ) \
109 int stride1 = 16, stride2 = 16; \
110 uint8_t *src1, *src2; \
112 src1 = h->mc.get_ref( pix1, &stride1, m[0].p_fref, m[0].i_stride[0], \
113 (mv0)[0], (mv0)[1], 8, 8 ); \
114 src2 = h->mc.get_ref( pix2, &stride2, m[1].p_fref, m[1].i_stride[0], \
115 (mv1)[0], (mv1)[1], 8, 8 ); \
116 h->mc.avg[PIXEL_8x8]( pix1, 16, src1, stride1, src2, stride2, i_bipred_weight ); \
117 i_cost = penalty + h->pixf.mbcmp[PIXEL_8x8]( \
118 m[0].p_fenc[0], FENC_STRIDE, pix1, 16 ); \
119 COPY2_IF_LT( i_bcost, i_cost, list_used, 3 ); \
122 m[0].i_pixel = PIXEL_8x8;
123 m[0].p_cost_mv = a->p_cost_mv;
124 m[0].i_stride[0] = i_stride;
125 m[0].p_fenc[0] = h->mb.pic.p_fenc[0];
126 LOAD_HPELS_LUMA( m[0].p_fref, fref0->lowres );
130 int16_t *mvr = fref1->lowres_mvs[0][p1-p0-1][i_mb_xy];
133 h->mc.memcpy_aligned( &m[1], &m[0], sizeof(x264_me_t) );
134 LOAD_HPELS_LUMA( m[1].p_fref, fref1->lowres );
136 dmv[0][0] = ( mvr[0] * dist_scale_factor + 128 ) >> 8;
137 dmv[0][1] = ( mvr[1] * dist_scale_factor + 128 ) >> 8;
138 dmv[1][0] = dmv[0][0] - mvr[0];
139 dmv[1][1] = dmv[0][1] - mvr[1];
143 TRY_BIDIR( dmv[0], dmv[1], 0 );
144 if( dmv[0][0] | dmv[0][1] | dmv[1][0] | dmv[1][1] )
147 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 );
148 i_cost = h->pixf.mbcmp[PIXEL_8x8]( m[0].p_fenc[0], FENC_STRIDE, pix1, 16 );
149 COPY2_IF_LT( i_bcost, i_cost, list_used, 3 );
153 for( l = 0; l < 1 + b_bidir; l++ )
158 int16_t (*fenc_mv)[2] = fenc_mvs[l];
159 DECLARE_ALIGNED_4( int16_t mvc[4][2] );
161 /* Reverse-order MV prediction. */
162 *(uint32_t*)mvc[0] = 0;
163 *(uint32_t*)mvc[1] = 0;
164 *(uint32_t*)mvc[2] = 0;
165 #define MVC(mv) { *(uint32_t*)mvc[i_mvc] = *(uint32_t*)mv; i_mvc++; }
166 if( i_mb_x < h->sps->i_mb_width - 1 )
168 if( i_mb_y < h->sps->i_mb_height - 1 )
170 MVC(fenc_mv[i_mb_stride]);
172 MVC(fenc_mv[i_mb_stride-1]);
173 if( i_mb_x < h->sps->i_mb_width - 1 )
174 MVC(fenc_mv[i_mb_stride+1]);
177 x264_median_mv( m[l].mvp, mvc[0], mvc[1], mvc[2] );
178 x264_me_search( h, &m[l], mvc, i_mvc );
180 m[l].cost -= 2; // remove mvcost from skip mbs
181 if( *(uint32_t*)m[l].mv )
183 *(uint32_t*)fenc_mvs[l] = *(uint32_t*)m[l].mv;
184 *fenc_costs[l] = m[l].cost;
188 *(uint32_t*)m[l].mv = *(uint32_t*)fenc_mvs[l];
189 m[l].cost = *fenc_costs[l];
191 COPY2_IF_LT( i_bcost, m[l].cost, list_used, l+1 );
194 if( b_bidir && ( *(uint32_t*)m[0].mv || *(uint32_t*)m[1].mv ) )
195 TRY_BIDIR( m[0].mv, m[1].mv, 5 );
197 frames[b]->lowres_inter_types[b-p0][p1-b][i_mb_xy] = list_used;
200 /* forbid intra-mbs in B-frames, because it's rare and not worth checking */
201 /* FIXME: Should we still forbid them now that we cache intra scores? */
202 if( !b_bidir || h->param.rc.b_mb_tree )
204 int i_icost, b_intra;
205 if( !fenc->b_intra_calculated )
207 DECLARE_ALIGNED_16( uint8_t edge[33] );
208 uint8_t *pix = &pix1[8+FDEC_STRIDE - 1];
209 uint8_t *src = &fenc->lowres[0][i_pel_offset - 1];
210 const int intra_penalty = 5;
213 memcpy( pix-FDEC_STRIDE, src-i_stride, 17 );
215 pix[i*FDEC_STRIDE] = src[i*i_stride];
218 if( h->pixf.intra_mbcmp_x3_8x8c )
220 h->pixf.intra_mbcmp_x3_8x8c( h->mb.pic.p_fenc[0], pix, satds );
221 h->predict_8x8c[I_PRED_CHROMA_P]( pix );
222 satds[I_PRED_CHROMA_P] =
223 h->pixf.mbcmp[PIXEL_8x8]( pix, FDEC_STRIDE, h->mb.pic.p_fenc[0], FENC_STRIDE );
229 h->predict_8x8c[i]( pix );
230 satds[i] = h->pixf.mbcmp[PIXEL_8x8]( pix, FDEC_STRIDE, h->mb.pic.p_fenc[0], FENC_STRIDE );
233 i_icost = X264_MIN4( satds[0], satds[1], satds[2], satds[3] );
235 h->predict_8x8_filter( pix, edge, ALL_NEIGHBORS, ALL_NEIGHBORS );
239 h->predict_8x8[i]( pix, edge );
240 satd = h->pixf.mbcmp[PIXEL_8x8]( pix, FDEC_STRIDE, h->mb.pic.p_fenc[0], FENC_STRIDE );
241 i_icost = X264_MIN( i_icost, satd );
244 i_icost += intra_penalty;
245 fenc->i_intra_cost[i_mb_xy] = i_icost;
248 i_icost = fenc->i_intra_cost[i_mb_xy];
251 b_intra = i_icost < i_bcost;
254 if( (i_mb_x > 0 && i_mb_x < h->sps->i_mb_width - 1
255 && i_mb_y > 0 && i_mb_y < h->sps->i_mb_height - 1)
256 || h->sps->i_mb_width <= 2 || h->sps->i_mb_height <= 2 )
258 fenc->i_intra_mbs[b-p0] += b_intra;
259 fenc->i_cost_est[0][0] += i_icost;
260 if( h->param.rc.i_aq_mode )
261 fenc->i_cost_est_aq[0][0] += (i_icost * fenc->i_inv_qscale_factor[i_mb_xy] + 128) >> 8;
266 fenc->lowres_costs[b-p0][p1-b][i_mb_xy] = i_bcost;
273 (h->sps->i_mb_width > 2 && h->sps->i_mb_height > 2 ?\
274 (h->sps->i_mb_width - 2) * (h->sps->i_mb_height - 2) :\
275 h->sps->i_mb_width * h->sps->i_mb_height)
277 static int x264_slicetype_frame_cost( x264_t *h, x264_mb_analysis_t *a,
278 x264_frame_t **frames, int p0, int p1, int b,
279 int b_intra_penalty )
283 /* Don't use the AQ'd scores for slicetype decision. */
287 /* Check whether we already evaluated this frame
288 * If we have tried this frame as P, then we have also tried
289 * the preceding frames as B. (is this still true?) */
290 /* Also check that we already calculated the row SATDs for the current frame. */
291 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) )
293 i_score = frames[b]->i_cost_est[b-p0][p1-b];
297 int dist_scale_factor = 128;
298 int *row_satd = frames[b]->i_row_satds[b-p0][p1-b];
300 /* For each list, check to see whether we have lowres motion-searched this reference frame before. */
301 do_search[0] = b != p0 && frames[b]->lowres_mvs[0][b-p0-1][0][0] == 0x7FFF;
302 do_search[1] = b != p1 && frames[b]->lowres_mvs[1][p1-b-1][0][0] == 0x7FFF;
303 if( do_search[0] ) frames[b]->lowres_mvs[0][b-p0-1][0][0] = 0;
304 if( do_search[1] ) frames[b]->lowres_mvs[1][p1-b-1][0][0] = 0;
308 frames[b]->i_intra_mbs[b-p0] = 0;
309 frames[b]->i_cost_est[0][0] = 0;
310 frames[b]->i_cost_est_aq[0][0] = 0;
313 dist_scale_factor = ( ((b-p0) << 8) + ((p1-p0) >> 1) ) / (p1-p0);
315 /* Lowres lookahead goes backwards because the MVs are used as predictors in the main encode.
316 * This considerably improves MV prediction overall. */
318 /* the edge mbs seem to reduce the predictive quality of the
319 * whole frame's score, but are needed for a spatial distribution. */
320 if( h->param.rc.b_mb_tree || h->param.rc.i_vbv_buffer_size ||
321 h->sps->i_mb_width <= 2 || h->sps->i_mb_height <= 2 )
323 for( h->mb.i_mb_y = h->sps->i_mb_height - 1; h->mb.i_mb_y >= 0; h->mb.i_mb_y-- )
325 row_satd[ h->mb.i_mb_y ] = 0;
326 for( h->mb.i_mb_x = h->sps->i_mb_width - 1; h->mb.i_mb_x >= 0; h->mb.i_mb_x-- )
328 int i_mb_cost = x264_slicetype_mb_cost( h, a, frames, p0, p1, b, dist_scale_factor, do_search );
329 int i_mb_cost_aq = i_mb_cost;
330 if( h->param.rc.i_aq_mode )
331 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;
332 row_satd[ h->mb.i_mb_y ] += i_mb_cost_aq;
333 if( (h->mb.i_mb_y > 0 && h->mb.i_mb_y < h->sps->i_mb_height - 1 &&
334 h->mb.i_mb_x > 0 && h->mb.i_mb_x < h->sps->i_mb_width - 1) ||
335 h->sps->i_mb_width <= 2 || h->sps->i_mb_height <= 2 )
337 /* Don't use AQ-weighted costs for slicetype decision, only for ratecontrol. */
338 i_score += i_mb_cost;
339 i_score_aq += i_mb_cost_aq;
346 for( h->mb.i_mb_y = h->sps->i_mb_height - 2; h->mb.i_mb_y > 0; h->mb.i_mb_y-- )
347 for( h->mb.i_mb_x = h->sps->i_mb_width - 2; h->mb.i_mb_x > 0; h->mb.i_mb_x-- )
349 int i_mb_cost = x264_slicetype_mb_cost( h, a, frames, p0, p1, b, dist_scale_factor, do_search );
350 int i_mb_cost_aq = i_mb_cost;
351 if( h->param.rc.i_aq_mode )
352 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;
353 i_score += i_mb_cost;
354 i_score_aq += i_mb_cost_aq;
359 i_score = i_score * 100 / (120 + h->param.i_bframe_bias);
361 frames[b]->b_intra_calculated = 1;
363 frames[b]->i_cost_est[b-p0][p1-b] = i_score;
364 frames[b]->i_cost_est_aq[b-p0][p1-b] = i_score_aq;
368 if( b_intra_penalty )
370 // arbitrary penalty for I-blocks after B-frames
372 i_score += i_score * frames[b]->i_intra_mbs[b-p0] / (nmb * 8);
377 /* If MB-tree changes the quantizers, we need to recalculate the frame cost without
378 * re-running lookahead. */
379 static int x264_slicetype_frame_cost_recalculate( x264_t *h, x264_frame_t **frames, int p0, int p1, int b )
382 int *row_satd = frames[b]->i_row_satds[b-p0][p1-b];
384 for( h->mb.i_mb_y = h->sps->i_mb_height - 1; h->mb.i_mb_y >= 0; h->mb.i_mb_y-- )
386 row_satd[ h->mb.i_mb_y ] = 0;
387 for( h->mb.i_mb_x = h->sps->i_mb_width - 1; h->mb.i_mb_x >= 0; h->mb.i_mb_x-- )
389 int i_mb_xy = h->mb.i_mb_x + h->mb.i_mb_y*h->mb.i_mb_stride;
390 int i_mb_cost = frames[b]->lowres_costs[b-p0][p1-b][i_mb_xy];
391 float qp_adj = frames[b]->f_qp_offset[i_mb_xy];
392 i_mb_cost = (i_mb_cost * x264_exp2fix8(qp_adj*(-1.f/6.f)) + 128) >> 8;
393 row_satd[ h->mb.i_mb_y ] += i_mb_cost;
394 if( (h->mb.i_mb_y > 0 && h->mb.i_mb_y < h->sps->i_mb_height - 1 &&
395 h->mb.i_mb_x > 0 && h->mb.i_mb_x < h->sps->i_mb_width - 1) ||
396 h->sps->i_mb_width <= 2 || h->sps->i_mb_height <= 2 )
398 i_score += i_mb_cost;
405 static void x264_macroblock_tree_finish( x264_t *h, x264_frame_t *frame, int b_bidir )
410 memcpy( frame->f_qp_offset, frame->f_qp_offset_aq, sizeof( frame->f_qp_offset ) );
413 for( mb_index = 0; mb_index < h->mb.i_mb_count; mb_index++ )
415 int intra_cost = (frame->i_intra_cost[mb_index] * frame->i_inv_qscale_factor[mb_index]+128)>>8;
418 int propagate_cost = frame->i_propagate_cost[mb_index];
419 float log2_ratio = x264_log2(intra_cost + propagate_cost) - x264_log2(intra_cost);
420 /* Allow the constant to be adjusted via qcompress, since the two
421 * concepts are very similar. */
422 frame->f_qp_offset[mb_index] = frame->f_qp_offset_aq[mb_index] - 5.0 * (1.0 - h->param.rc.f_qcompress) * log2_ratio;
428 static void x264_macroblock_tree_propagate( x264_t *h, x264_frame_t **frames, int p0, int p1, int b )
430 x264_frame_t *refs[2] = {frames[p0],frames[p1]};
431 int dist_scale_factor = ( ((b-p0) << 8) + ((p1-p0) >> 1) ) / (p1-p0);
432 int i_bipred_weight = h->param.analyse.b_weighted_bipred ? 64 - (dist_scale_factor>>2) : 32;
433 int16_t (*mvs[2])[2] = { frames[b]->lowres_mvs[0][b-p0-1], frames[b]->lowres_mvs[1][p1-b-1] };
434 int *buf = h->scratch_buffer;
436 for( h->mb.i_mb_y = 0; h->mb.i_mb_y < h->sps->i_mb_height; h->mb.i_mb_y++ )
438 int mb_index = h->mb.i_mb_y*h->mb.i_mb_stride;
439 h->mc.mbtree_propagate_cost( buf, frames[b]->i_propagate_cost+mb_index,
440 frames[b]->i_intra_cost+mb_index, frames[b]->lowres_costs[b-p0][p1-b]+mb_index,
441 frames[b]->i_inv_qscale_factor+mb_index, h->sps->i_mb_width );
442 for( h->mb.i_mb_x = 0; h->mb.i_mb_x < h->sps->i_mb_width; h->mb.i_mb_x++, mb_index++ )
444 int propagate_amount = buf[h->mb.i_mb_x];
445 /* Don't propagate for an intra block. */
446 if( propagate_amount > 0 )
448 int lists_used = frames[b]->lowres_inter_types[b-p0][p1-b][mb_index];
450 /* Follow the MVs to the previous frame(s). */
451 for( list = 0; list < 2; list++ )
452 if( (lists_used >> list)&1 )
454 int x = mvs[list][mb_index][0];
455 int y = mvs[list][mb_index][1];
456 int listamount = propagate_amount;
457 int mbx = (x>>5)+h->mb.i_mb_x;
458 int mby = ((y>>5)+h->mb.i_mb_y);
459 int idx0 = mbx + mby*h->mb.i_mb_stride;
461 int idx2 = idx0 + h->mb.i_mb_stride;
462 int idx3 = idx0 + h->mb.i_mb_stride + 1;
465 int idx0weight = (32-y)*(32-x);
466 int idx1weight = (32-y)*x;
467 int idx2weight = y*(32-x);
468 int idx3weight = y*x;
470 /* Apply bipred weighting. */
471 if( lists_used == 3 )
472 listamount = (listamount * (list?(64-i_bipred_weight):i_bipred_weight) + 32) >> 6;
474 #define CLIP_ADD(s,x) (s) = X264_MIN((s)+(x),(1<<16)-1)
476 /* We could just clip the MVs, but pixels that lie outside the frame probably shouldn't
478 if( mbx < h->sps->i_mb_width-1 && mby < h->sps->i_mb_height-1 && mbx >= 0 && mby >= 0 )
480 CLIP_ADD( refs[list]->i_propagate_cost[idx0], (listamount*idx0weight+512)>>10 );
481 CLIP_ADD( refs[list]->i_propagate_cost[idx1], (listamount*idx1weight+512)>>10 );
482 CLIP_ADD( refs[list]->i_propagate_cost[idx2], (listamount*idx2weight+512)>>10 );
483 CLIP_ADD( refs[list]->i_propagate_cost[idx3], (listamount*idx3weight+512)>>10 );
485 else /* Check offsets individually */
487 if( mbx < h->sps->i_mb_width && mby < h->sps->i_mb_height && mbx >= 0 && mby >= 0 )
488 CLIP_ADD( refs[list]->i_propagate_cost[idx0], (listamount*idx0weight+512)>>10 );
489 if( mbx+1 < h->sps->i_mb_width && mby < h->sps->i_mb_height && mbx+1 >= 0 && mby >= 0 )
490 CLIP_ADD( refs[list]->i_propagate_cost[idx1], (listamount*idx1weight+512)>>10 );
491 if( mbx < h->sps->i_mb_width && mby+1 < h->sps->i_mb_height && mbx >= 0 && mby+1 >= 0 )
492 CLIP_ADD( refs[list]->i_propagate_cost[idx2], (listamount*idx2weight+512)>>10 );
493 if( mbx+1 < h->sps->i_mb_width && mby+1 < h->sps->i_mb_height && mbx+1 >= 0 && mby+1 >= 0 )
494 CLIP_ADD( refs[list]->i_propagate_cost[idx3], (listamount*idx3weight+512)>>10 );
501 if( h->param.rc.i_vbv_buffer_size )
502 x264_macroblock_tree_finish( h, frames[b], b != p1 );
505 static void x264_macroblock_tree( x264_t *h, x264_mb_analysis_t *a, x264_frame_t **frames, int num_frames, int b_intra )
507 int i, idx = !b_intra;
508 int last_nonb, cur_nonb = 1;
510 x264_slicetype_frame_cost( h, a, frames, 0, 0, 0, 0 );
513 while( i > 0 && frames[i]->i_type == X264_TYPE_B )
520 memset( frames[last_nonb]->i_propagate_cost, 0, h->mb.i_mb_count * sizeof(uint16_t) );
524 while( frames[cur_nonb]->i_type == X264_TYPE_B && cur_nonb > 0 )
528 x264_slicetype_frame_cost( h, a, frames, cur_nonb, last_nonb, last_nonb, 0 );
529 memset( frames[cur_nonb]->i_propagate_cost, 0, h->mb.i_mb_count * sizeof(uint16_t) );
530 x264_macroblock_tree_propagate( h, frames, cur_nonb, last_nonb, last_nonb );
531 while( frames[i]->i_type == X264_TYPE_B && i > 0 )
533 x264_slicetype_frame_cost( h, a, frames, cur_nonb, last_nonb, i, 0 );
534 memset( frames[i]->i_propagate_cost, 0, h->mb.i_mb_count * sizeof(uint16_t) );
535 x264_macroblock_tree_propagate( h, frames, cur_nonb, last_nonb, i );
538 last_nonb = cur_nonb;
541 x264_macroblock_tree_finish( h, frames[last_nonb], 0 );
544 static int x264_vbv_frame_cost( x264_t *h, x264_mb_analysis_t *a, x264_frame_t **frames, int p0, int p1, int b )
546 int cost = x264_slicetype_frame_cost( h, a, frames, p0, p1, b, 0 );
547 if( h->param.rc.i_aq_mode )
549 if( h->param.rc.b_mb_tree )
550 return x264_slicetype_frame_cost_recalculate( h, frames, p0, p1, b );
552 return frames[b]->i_cost_est_aq[b-p0][p1-b];
557 static void x264_vbv_lookahead( x264_t *h, x264_mb_analysis_t *a, x264_frame_t **frames, int num_frames, int keyframe )
559 int last_nonb = 0, cur_nonb = 1, next_nonb, i, idx = 0;
560 while( cur_nonb < num_frames && frames[cur_nonb]->i_type == X264_TYPE_B )
562 next_nonb = keyframe ? last_nonb : cur_nonb;
564 while( cur_nonb <= num_frames )
566 /* P/I cost: This shouldn't include the cost of next_nonb */
567 if( next_nonb != cur_nonb )
569 int p0 = IS_X264_TYPE_I( frames[cur_nonb]->i_type ) ? cur_nonb : last_nonb;
570 frames[next_nonb]->i_planned_satd[idx] = x264_vbv_frame_cost( h, a, frames, p0, cur_nonb, cur_nonb );
571 frames[next_nonb]->i_planned_type[idx] = frames[cur_nonb]->i_type;
574 /* Handle the B-frames: coded order */
575 for( i = last_nonb+1; i < cur_nonb; i++, idx++ )
577 frames[next_nonb]->i_planned_satd[idx] = x264_vbv_frame_cost( h, a, frames, last_nonb, cur_nonb, i );
578 frames[next_nonb]->i_planned_type[idx] = X264_TYPE_B;
580 last_nonb = cur_nonb;
582 while( cur_nonb <= num_frames && frames[cur_nonb]->i_type == X264_TYPE_B )
585 frames[next_nonb]->i_planned_type[idx] = X264_TYPE_AUTO;
588 static int x264_slicetype_path_cost( x264_t *h, x264_mb_analysis_t *a, x264_frame_t **frames, char *path, int threshold )
593 path--; /* Since the 1st path element is really the second frame */
598 /* Find the location of the next P-frame. */
599 while( path[next_p] && path[next_p] != 'P' )
601 /* Return if the path doesn't end on a P-frame. */
602 if( path[next_p] != 'P' )
605 /* Add the cost of the P-frame found above */
606 cost += x264_slicetype_frame_cost( h, a, frames, cur_p, next_p, next_p, 0 );
607 /* Early terminate if the cost we have found is larger than the best path cost so far */
608 if( cost > threshold )
611 for( next_b = loc; next_b < next_p && cost < threshold; next_b++ )
612 cost += x264_slicetype_frame_cost( h, a, frames, cur_p, next_p, next_b, 0 );
620 /* Viterbi/trellis slicetype decision algorithm. */
621 /* Uses strings due to the fact that the speed of the control functions is
622 negligable compared to the cost of running slicetype_frame_cost, and because
623 it makes debugging easier. */
624 static void x264_slicetype_path( x264_t *h, x264_mb_analysis_t *a, x264_frame_t **frames, int length, int max_bframes, int buffer_size, char (*best_paths)[X264_LOOKAHEAD_MAX] )
626 char paths[X264_BFRAME_MAX+2][X264_LOOKAHEAD_MAX] = {{0}};
627 int num_paths = X264_MIN(max_bframes+1, length);
628 int suffix_size, loc, path;
629 int best_cost = COST_MAX;
630 int best_path_index = 0;
631 length = X264_MIN(length,X264_LOOKAHEAD_MAX);
633 /* Iterate over all currently possible paths and add suffixes to each one */
634 for( suffix_size = 0; suffix_size < num_paths; suffix_size++ )
636 memcpy( paths[suffix_size], best_paths[length - (suffix_size + 1)], length - (suffix_size + 1) );
637 for( loc = 0; loc < suffix_size; loc++ )
638 strcat( paths[suffix_size], "B" );
639 strcat( paths[suffix_size], "P" );
642 /* Calculate the actual cost of each of the current paths */
643 for( path = 0; path < num_paths; path++ )
645 int cost = x264_slicetype_path_cost( h, a, frames, paths[path], best_cost );
646 if( cost < best_cost )
649 best_path_index = path;
653 /* Store the best path. */
654 memcpy( best_paths[length], paths[best_path_index], length );
657 static int scenecut( x264_t *h, x264_mb_analysis_t *a, x264_frame_t **frames, int p0, int p1 )
659 x264_frame_t *frame = frames[p1];
660 x264_slicetype_frame_cost( h, a, frames, p0, p1, p1, 0 );
662 int icost = frame->i_cost_est[0][0];
663 int pcost = frame->i_cost_est[p1-p0][0];
665 int i_gop_size = frame->i_frame - h->frames.i_last_idr;
666 float f_thresh_max = h->param.i_scenecut_threshold / 100.0;
667 /* magic numbers pulled out of thin air */
668 float f_thresh_min = f_thresh_max * h->param.i_keyint_min
669 / ( h->param.i_keyint_max * 4 );
672 if( h->param.i_keyint_min == h->param.i_keyint_max )
673 f_thresh_min= f_thresh_max;
674 if( i_gop_size < h->param.i_keyint_min / 4 )
675 f_bias = f_thresh_min / 4;
676 else if( i_gop_size <= h->param.i_keyint_min )
677 f_bias = f_thresh_min * i_gop_size / h->param.i_keyint_min;
680 f_bias = f_thresh_min
681 + ( f_thresh_max - f_thresh_min )
682 * ( i_gop_size - h->param.i_keyint_min )
683 / ( h->param.i_keyint_max - h->param.i_keyint_min ) ;
686 res = pcost >= (1.0 - f_bias) * icost;
689 int imb = frame->i_intra_mbs[p1-p0];
690 int pmb = NUM_MBS - imb;
691 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",
693 icost, pcost, 1. - (double)pcost / icost,
694 f_bias, i_gop_size, imb, pmb );
699 static void x264_slicetype_analyse( x264_t *h, int keyframe )
701 x264_mb_analysis_t a;
702 x264_frame_t *frames[X264_LOOKAHEAD_MAX+3] = { NULL, };
706 int i_mb_count = NUM_MBS;
707 int cost1p0, cost2p0, cost1b1, cost2p1;
710 assert( h->frames.b_have_lowres );
712 if( !h->frames.last_nonb )
714 frames[0] = h->frames.last_nonb;
715 for( j = 0; h->frames.next[j] && h->frames.next[j]->i_type == X264_TYPE_AUTO; j++ )
716 frames[j+1] = h->frames.next[j];
721 keyint_limit = h->param.i_keyint_max - frames[0]->i_frame + h->frames.i_last_idr - 1;
722 num_frames = X264_MIN( j, keyint_limit );
724 x264_lowres_context_init( h, &a );
725 idr_frame_type = frames[1]->i_frame - h->frames.i_last_idr >= h->param.i_keyint_min ? X264_TYPE_IDR : X264_TYPE_I;
727 /* This is important psy-wise: if we have a non-scenecut keyframe,
728 * there will be significant visual artifacts if the frames just before
729 * go down in quality due to being referenced less, despite it being
730 * more RD-optimal. */
731 if( (h->param.analyse.b_psy && h->param.rc.b_mb_tree) || h->param.rc.i_vbv_buffer_size )
733 else if( num_frames == 1 )
735 frames[1]->i_type = X264_TYPE_P;
736 if( h->param.i_scenecut_threshold && scenecut( h, &a, frames, 0, 1 ) )
737 frames[1]->i_type = idr_frame_type;
740 else if( num_frames == 0 )
742 frames[1]->i_type = idr_frame_type;
746 char best_paths[X264_LOOKAHEAD_MAX][X264_LOOKAHEAD_MAX] = {"","P"};
749 int max_bframes = X264_MIN(num_frames-1, h->param.i_bframe);
750 int num_analysed_frames = num_frames;
752 if( h->param.i_scenecut_threshold && scenecut( h, &a, frames, 0, 1 ) )
754 frames[1]->i_type = idr_frame_type;
758 if( h->param.i_bframe )
760 if( h->param.i_bframe_adaptive == X264_B_ADAPT_TRELLIS )
762 /* Perform the frametype analysis. */
763 for( n = 2; n < num_frames-1; n++ )
764 x264_slicetype_path( h, &a, frames, n, max_bframes, num_frames-max_bframes, best_paths );
765 num_bframes = strspn( best_paths[num_frames-2], "B" );
766 /* Load the results of the analysis into the frame types. */
767 for( j = 1; j < num_frames; j++ )
768 frames[j]->i_type = best_paths[num_frames-2][j-1] == 'B' ? X264_TYPE_B : X264_TYPE_P;
769 frames[num_frames]->i_type = X264_TYPE_P;
771 else if( h->param.i_bframe_adaptive == X264_B_ADAPT_FAST )
773 for( i = 0; i < num_frames-(2-!i); )
775 cost2p1 = x264_slicetype_frame_cost( h, &a, frames, i+0, i+2, i+2, 1 );
776 if( frames[i+2]->i_intra_mbs[2] > i_mb_count / 2 )
778 frames[i+1]->i_type = X264_TYPE_P;
779 frames[i+2]->i_type = X264_TYPE_P;
784 cost1b1 = x264_slicetype_frame_cost( h, &a, frames, i+0, i+2, i+1, 0 );
785 cost1p0 = x264_slicetype_frame_cost( h, &a, frames, i+0, i+1, i+1, 0 );
786 cost2p0 = x264_slicetype_frame_cost( h, &a, frames, i+1, i+2, i+2, 0 );
788 if( cost1p0 + cost2p0 < cost1b1 + cost2p1 )
790 frames[i+1]->i_type = X264_TYPE_P;
791 frames[i+2]->i_type = X264_TYPE_P;
796 // arbitrary and untuned
797 #define INTER_THRESH 300
798 #define P_SENS_BIAS (50 - h->param.i_bframe_bias)
799 frames[i+1]->i_type = X264_TYPE_B;
800 frames[i+2]->i_type = X264_TYPE_P;
802 for( j = i+2; j <= X264_MIN( h->param.i_bframe, num_frames-1 ); j++ )
804 int pthresh = X264_MAX(INTER_THRESH - P_SENS_BIAS * (j-i-1), INTER_THRESH/10);
805 int pcost = x264_slicetype_frame_cost( h, &a, frames, i+0, j+1, j+1, 1 );
807 if( pcost > pthresh*i_mb_count || frames[j+1]->i_intra_mbs[j-i+1] > i_mb_count/3 )
809 frames[j]->i_type = X264_TYPE_P;
813 frames[j]->i_type = X264_TYPE_B;
817 frames[i+!i]->i_type = X264_TYPE_P;
819 while( num_bframes < num_frames && frames[num_bframes+1]->i_type == X264_TYPE_B )
824 num_bframes = X264_MIN(num_frames-1, h->param.i_bframe);
825 for( j = 1; j < num_frames; j++ )
826 frames[j]->i_type = (j%(num_bframes+1)) ? X264_TYPE_B : X264_TYPE_P;
827 frames[num_frames]->i_type = X264_TYPE_P;
830 /* Check scenecut on the first minigop. */
831 for( j = 1; j < num_bframes+1; j++ )
832 if( h->param.i_scenecut_threshold && scenecut( h, &a, frames, j, j+1 ) )
834 frames[j]->i_type = X264_TYPE_P;
835 num_analysed_frames = j;
839 reset_start = keyframe ? 1 : X264_MIN( num_bframes+2, num_analysed_frames+1 );
843 for( j = 1; j < num_frames; j++ )
844 frames[j]->i_type = X264_TYPE_P;
845 reset_start = !keyframe + 1;
849 for( j = 1; j <= num_frames; j++ )
850 if( frames[j]->i_type == X264_TYPE_AUTO )
851 frames[j]->i_type = X264_TYPE_P;
853 /* Perform the actual macroblock tree analysis.
854 * Don't go farther than the maximum keyframe interval; this helps in short GOPs. */
855 if( h->param.rc.b_mb_tree )
856 x264_macroblock_tree( h, &a, frames, X264_MIN(num_frames, h->param.i_keyint_max), keyframe );
858 /* Enforce keyframe limit. */
859 for( j = 0; j < num_frames; j++ )
861 if( ((j-keyint_limit) % h->param.i_keyint_max) == 0 )
864 frames[j]->i_type = X264_TYPE_P;
865 frames[j+1]->i_type = X264_TYPE_IDR;
866 reset_start = X264_MIN( reset_start, j+2 );
870 if( h->param.rc.i_vbv_buffer_size )
871 x264_vbv_lookahead( h, &a, frames, num_frames, keyframe );
873 /* Restore frametypes for all frames that haven't actually been decided yet. */
874 for( j = reset_start; j <= num_frames; j++ )
875 frames[j]->i_type = X264_TYPE_AUTO;
878 void x264_slicetype_decide( x264_t *h )
884 if( h->frames.next[0] == NULL )
887 if( h->param.rc.b_stat_read )
889 /* Use the frame types from the first pass */
890 for( i = 0; h->frames.next[i] != NULL; i++ )
891 h->frames.next[i]->i_type =
892 x264_ratecontrol_slice_type( h, h->frames.next[i]->i_frame );
894 else if( (h->param.i_bframe && h->param.i_bframe_adaptive)
895 || h->param.i_scenecut_threshold
896 || h->param.rc.b_mb_tree
897 || (h->param.rc.i_vbv_buffer_size && h->param.rc.i_lookahead) )
898 x264_slicetype_analyse( h, 0 );
900 for( bframes = 0;; bframes++ )
902 frm = h->frames.next[bframes];
905 if( frm->i_frame - h->frames.i_last_idr >= h->param.i_keyint_max )
907 if( frm->i_type == X264_TYPE_AUTO )
908 frm->i_type = X264_TYPE_IDR;
909 if( frm->i_type != X264_TYPE_IDR )
910 x264_log( h, X264_LOG_WARNING, "specified frame type (%d) is not compatible with keyframe interval\n", frm->i_type );
912 if( frm->i_type == X264_TYPE_IDR )
918 h->frames.next[bframes]->i_type = X264_TYPE_P;
926 if( bframes == h->param.i_bframe
927 || h->frames.next[bframes+1] == NULL )
929 if( IS_X264_TYPE_B( frm->i_type ) )
930 x264_log( h, X264_LOG_WARNING, "specified frame type is not compatible with max B-frames\n" );
931 if( frm->i_type == X264_TYPE_AUTO
932 || IS_X264_TYPE_B( frm->i_type ) )
933 frm->i_type = X264_TYPE_P;
936 if( frm->i_type == X264_TYPE_AUTO )
937 frm->i_type = X264_TYPE_B;
939 else if( !IS_X264_TYPE_B( frm->i_type ) ) break;
943 int x264_rc_analyse_slice( x264_t *h )
945 x264_mb_analysis_t a;
946 x264_frame_t *frames[X264_LOOKAHEAD_MAX+2] = { NULL, };
950 x264_lowres_context_init( h, &a );
952 if( IS_X264_TYPE_I(h->fenc->i_type) )
955 /* For MB-tree and VBV lookahead, we have to perform propagation analysis on I-frames too. */
956 if( h->param.rc.b_mb_tree || (h->param.rc.i_vbv_buffer_size && h->param.rc.i_lookahead) )
958 h->frames.last_nonb = h->fenc;
959 x264_slicetype_analyse( h, 1 );
962 else if( X264_TYPE_P == h->fenc->i_type )
965 while( h->frames.current[p1] && IS_X264_TYPE_B( h->frames.current[p1]->i_type ) )
972 p1 = (h->fref1[0]->i_poc - h->fref0[0]->i_poc)/2;
973 b = (h->fref1[0]->i_poc - h->fenc->i_poc)/2;
974 frames[p1] = h->fref1[0];
976 frames[p0] = h->fref0[0];
979 if( h->param.rc.b_mb_tree )
980 cost = x264_slicetype_frame_cost_recalculate( h, frames, p0, p1, b );
983 cost = x264_slicetype_frame_cost( h, &a, frames, p0, p1, b, 0 );
985 /* In AQ, use the weighted score instead. */
986 if( h->param.rc.i_aq_mode )
987 cost = frames[b]->i_cost_est_aq[b-p0][p1-b];
990 h->fenc->i_row_satd = h->fenc->i_row_satds[b-p0][p1-b];
991 h->fdec->i_row_satd = h->fdec->i_row_satds[b-p0][p1-b];
992 h->fdec->i_satd = cost;
993 memcpy( h->fdec->i_row_satd, h->fenc->i_row_satd, h->sps->i_mb_height * sizeof(int) );