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 void 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 x264_mb_analyse_load_costs( h, a );
38 h->mb.i_me_method = X264_MIN( X264_ME_HEX, h->param.analyse.i_me_method ); // maybe dia?
39 h->mb.i_subpel_refine = 4; // 3 should be enough, but not tweaking for speed now
40 h->mb.b_chroma_me = 0;
43 static int x264_slicetype_mb_cost( x264_t *h, x264_mb_analysis_t *a,
44 x264_frame_t **frames, int p0, int p1, int b,
45 int dist_scale_factor, int do_search[2] )
47 x264_frame_t *fref0 = frames[p0];
48 x264_frame_t *fref1 = frames[p1];
49 x264_frame_t *fenc = frames[b];
50 const int b_bidir = (b < p1);
51 const int i_mb_x = h->mb.i_mb_x;
52 const int i_mb_y = h->mb.i_mb_y;
53 const int i_mb_stride = h->sps->i_mb_width;
54 const int i_mb_xy = i_mb_x + i_mb_y * i_mb_stride;
55 const int i_stride = fenc->i_stride_lowres;
56 const int i_pel_offset = 8 * ( i_mb_x + i_mb_y * i_stride );
57 const int i_bipred_weight = h->param.analyse.b_weighted_bipred ? 64 - (dist_scale_factor>>2) : 32;
58 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] };
59 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] };
61 DECLARE_ALIGNED_8( uint8_t pix1[9*FDEC_STRIDE] );
62 uint8_t *pix2 = pix1+8;
64 int i_bcost = COST_MAX;
68 h->mb.pic.p_fenc[0] = h->mb.pic.fenc_buf;
69 h->mc.copy[PIXEL_8x8]( h->mb.pic.p_fenc[0], FENC_STRIDE, &fenc->lowres[0][i_pel_offset], i_stride, 8 );
71 if( !p0 && !p1 && !b )
74 // no need for h->mb.mv_min[]
75 h->mb.mv_min_fpel[0] = -8*h->mb.i_mb_x - 4;
76 h->mb.mv_max_fpel[0] = 8*( h->sps->i_mb_width - h->mb.i_mb_x - 1 ) + 4;
77 h->mb.mv_min_spel[0] = 4*( h->mb.mv_min_fpel[0] - 8 );
78 h->mb.mv_max_spel[0] = 4*( h->mb.mv_max_fpel[0] + 8 );
79 if( h->mb.i_mb_x >= h->sps->i_mb_width - 2 )
81 h->mb.mv_min_fpel[1] = -8*h->mb.i_mb_y - 4;
82 h->mb.mv_max_fpel[1] = 8*( h->sps->i_mb_height - h->mb.i_mb_y - 1 ) + 4;
83 h->mb.mv_min_spel[1] = 4*( h->mb.mv_min_fpel[1] - 8 );
84 h->mb.mv_max_spel[1] = 4*( h->mb.mv_max_fpel[1] + 8 );
87 #define LOAD_HPELS_LUMA(dst, src) \
89 (dst)[0] = &(src)[0][i_pel_offset]; \
90 (dst)[1] = &(src)[1][i_pel_offset]; \
91 (dst)[2] = &(src)[2][i_pel_offset]; \
92 (dst)[3] = &(src)[3][i_pel_offset]; \
94 #define CLIP_MV( mv ) \
96 mv[0] = x264_clip3( mv[0], h->mb.mv_min_spel[0], h->mb.mv_max_spel[0] ); \
97 mv[1] = x264_clip3( mv[1], h->mb.mv_min_spel[1], h->mb.mv_max_spel[1] ); \
99 #define TRY_BIDIR( mv0, mv1, penalty ) \
101 int stride1 = 16, stride2 = 16; \
102 uint8_t *src1, *src2; \
104 src1 = h->mc.get_ref( pix1, &stride1, m[0].p_fref, m[0].i_stride[0], \
105 (mv0)[0], (mv0)[1], 8, 8 ); \
106 src2 = h->mc.get_ref( pix2, &stride2, m[1].p_fref, m[1].i_stride[0], \
107 (mv1)[0], (mv1)[1], 8, 8 ); \
108 h->mc.avg[PIXEL_8x8]( pix1, 16, src1, stride1, src2, stride2, i_bipred_weight ); \
109 i_cost = penalty + h->pixf.mbcmp[PIXEL_8x8]( \
110 m[0].p_fenc[0], FENC_STRIDE, pix1, 16 ); \
111 COPY2_IF_LT( i_bcost, i_cost, list_used, 3 ); \
114 m[0].i_pixel = PIXEL_8x8;
115 m[0].p_cost_mv = a->p_cost_mv;
116 m[0].i_stride[0] = i_stride;
117 m[0].p_fenc[0] = h->mb.pic.p_fenc[0];
118 LOAD_HPELS_LUMA( m[0].p_fref, fref0->lowres );
122 int16_t *mvr = fref1->lowres_mvs[0][p1-p0-1][i_mb_xy];
125 h->mc.memcpy_aligned( &m[1], &m[0], sizeof(x264_me_t) );
126 LOAD_HPELS_LUMA( m[1].p_fref, fref1->lowres );
128 dmv[0][0] = ( mvr[0] * dist_scale_factor + 128 ) >> 8;
129 dmv[0][1] = ( mvr[1] * dist_scale_factor + 128 ) >> 8;
130 dmv[1][0] = dmv[0][0] - mvr[0];
131 dmv[1][1] = dmv[0][1] - mvr[1];
135 TRY_BIDIR( dmv[0], dmv[1], 0 );
136 if( dmv[0][0] | dmv[0][1] | dmv[1][0] | dmv[1][1] )
139 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 );
140 i_cost = h->pixf.mbcmp[PIXEL_8x8]( m[0].p_fenc[0], FENC_STRIDE, pix1, 16 );
141 COPY2_IF_LT( i_bcost, i_cost, list_used, 3 );
145 for( l = 0; l < 1 + b_bidir; l++ )
150 int16_t (*fenc_mv)[2] = fenc_mvs[l];
151 DECLARE_ALIGNED_4( int16_t mvc[4][2] );
153 /* Reverse-order MV prediction. */
154 *(uint32_t*)mvc[0] = 0;
155 *(uint32_t*)mvc[1] = 0;
156 *(uint32_t*)mvc[2] = 0;
157 #define MVC(mv) { *(uint32_t*)mvc[i_mvc] = *(uint32_t*)mv; i_mvc++; }
158 if( i_mb_x < h->sps->i_mb_width - 1 )
160 if( i_mb_y < h->sps->i_mb_height - 1 )
162 MVC(fenc_mv[i_mb_stride]);
164 MVC(fenc_mv[i_mb_stride-1]);
165 if( i_mb_x < h->sps->i_mb_width - 1 )
166 MVC(fenc_mv[i_mb_stride+1]);
169 x264_median_mv( m[l].mvp, mvc[0], mvc[1], mvc[2] );
170 x264_me_search( h, &m[l], mvc, i_mvc );
172 m[l].cost -= 2; // remove mvcost from skip mbs
173 if( *(uint32_t*)m[l].mv )
175 *(uint32_t*)fenc_mvs[l] = *(uint32_t*)m[l].mv;
176 *fenc_costs[l] = m[l].cost;
180 *(uint32_t*)m[l].mv = *(uint32_t*)fenc_mvs[l];
181 m[l].cost = *fenc_costs[l];
183 COPY2_IF_LT( i_bcost, m[l].cost, list_used, l+1 );
186 if( b_bidir && ( *(uint32_t*)m[0].mv || *(uint32_t*)m[1].mv ) )
187 TRY_BIDIR( m[0].mv, m[1].mv, 5 );
189 frames[b]->lowres_inter_types[b-p0][p1-b][i_mb_xy] = list_used;
192 /* forbid intra-mbs in B-frames, because it's rare and not worth checking */
193 /* FIXME: Should we still forbid them now that we cache intra scores? */
194 if( !b_bidir || h->param.rc.b_mb_tree )
196 int i_icost, b_intra;
197 if( !fenc->b_intra_calculated )
199 DECLARE_ALIGNED_16( uint8_t edge[33] );
200 uint8_t *pix = &pix1[8+FDEC_STRIDE - 1];
201 uint8_t *src = &fenc->lowres[0][i_pel_offset - 1];
202 const int intra_penalty = 5;
205 memcpy( pix-FDEC_STRIDE, src-i_stride, 17 );
207 pix[i*FDEC_STRIDE] = src[i*i_stride];
210 if( h->pixf.intra_mbcmp_x3_8x8c )
212 h->pixf.intra_mbcmp_x3_8x8c( h->mb.pic.p_fenc[0], pix, satds );
213 h->predict_8x8c[I_PRED_CHROMA_P]( pix );
214 satds[I_PRED_CHROMA_P] =
215 h->pixf.mbcmp[PIXEL_8x8]( pix, FDEC_STRIDE, h->mb.pic.p_fenc[0], FENC_STRIDE );
221 h->predict_8x8c[i]( pix );
222 satds[i] = h->pixf.mbcmp[PIXEL_8x8]( pix, FDEC_STRIDE, h->mb.pic.p_fenc[0], FENC_STRIDE );
225 i_icost = X264_MIN4( satds[0], satds[1], satds[2], satds[3] );
227 h->predict_8x8_filter( pix, edge, ALL_NEIGHBORS, ALL_NEIGHBORS );
231 h->predict_8x8[i]( pix, edge );
232 satd = h->pixf.mbcmp[PIXEL_8x8]( pix, FDEC_STRIDE, h->mb.pic.p_fenc[0], FENC_STRIDE );
233 i_icost = X264_MIN( i_icost, satd );
236 i_icost += intra_penalty;
237 fenc->i_intra_cost[i_mb_xy] = i_icost;
240 i_icost = fenc->i_intra_cost[i_mb_xy];
243 b_intra = i_icost < i_bcost;
246 if( (i_mb_x > 0 && i_mb_x < h->sps->i_mb_width - 1
247 && i_mb_y > 0 && i_mb_y < h->sps->i_mb_height - 1)
248 || h->sps->i_mb_width <= 2 || h->sps->i_mb_height <= 2 )
250 fenc->i_intra_mbs[b-p0] += b_intra;
251 fenc->i_cost_est[0][0] += i_icost;
256 frames[b]->lowres_costs[b-p0][p1-b][i_mb_xy] = i_bcost;
263 (h->sps->i_mb_width > 2 && h->sps->i_mb_height > 2 ?\
264 (h->sps->i_mb_width - 2) * (h->sps->i_mb_height - 2) :\
265 h->sps->i_mb_width * h->sps->i_mb_height)
267 static int x264_slicetype_frame_cost( x264_t *h, x264_mb_analysis_t *a,
268 x264_frame_t **frames, int p0, int p1, int b,
269 int b_intra_penalty )
273 /* Don't use the AQ'd scores for slicetype decision. */
277 /* Check whether we already evaluated this frame
278 * If we have tried this frame as P, then we have also tried
279 * the preceding frames as B. (is this still true?) */
280 /* Also check that we already calculated the row SATDs for the current frame. */
281 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) )
283 i_score = frames[b]->i_cost_est[b-p0][p1-b];
287 int dist_scale_factor = 128;
288 int *row_satd = frames[b]->i_row_satds[b-p0][p1-b];
290 /* For each list, check to see whether we have lowres motion-searched this reference frame before. */
291 do_search[0] = b != p0 && frames[b]->lowres_mvs[0][b-p0-1][0][0] == 0x7FFF;
292 do_search[1] = b != p1 && frames[b]->lowres_mvs[1][p1-b-1][0][0] == 0x7FFF;
293 if( do_search[0] ) frames[b]->lowres_mvs[0][b-p0-1][0][0] = 0;
294 if( do_search[1] ) frames[b]->lowres_mvs[1][p1-b-1][0][0] = 0;
298 frames[b]->i_intra_mbs[b-p0] = 0;
299 frames[b]->i_cost_est[0][0] = 0;
302 dist_scale_factor = ( ((b-p0) << 8) + ((p1-p0) >> 1) ) / (p1-p0);
304 /* Lowres lookahead goes backwards because the MVs are used as predictors in the main encode.
305 * This considerably improves MV prediction overall. */
307 /* the edge mbs seem to reduce the predictive quality of the
308 * whole frame's score, but are needed for a spatial distribution. */
309 if( h->param.rc.b_mb_tree || h->param.rc.i_vbv_buffer_size ||
310 h->sps->i_mb_width <= 2 || h->sps->i_mb_height <= 2 )
312 for( h->mb.i_mb_y = h->sps->i_mb_height - 1; h->mb.i_mb_y >= 0; h->mb.i_mb_y-- )
314 row_satd[ h->mb.i_mb_y ] = 0;
315 for( h->mb.i_mb_x = h->sps->i_mb_width - 1; h->mb.i_mb_x >= 0; h->mb.i_mb_x-- )
317 int i_mb_cost = x264_slicetype_mb_cost( h, a, frames, p0, p1, b, dist_scale_factor, do_search );
318 int i_mb_cost_aq = i_mb_cost;
319 if( h->param.rc.i_aq_mode )
320 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;
321 row_satd[ h->mb.i_mb_y ] += i_mb_cost_aq;
322 if( (h->mb.i_mb_y > 0 && h->mb.i_mb_y < h->sps->i_mb_height - 1 &&
323 h->mb.i_mb_x > 0 && h->mb.i_mb_x < h->sps->i_mb_width - 1) ||
324 h->sps->i_mb_width <= 2 || h->sps->i_mb_height <= 2 )
326 /* Don't use AQ-weighted costs for slicetype decision, only for ratecontrol. */
327 i_score += i_mb_cost;
328 i_score_aq += i_mb_cost_aq;
335 for( h->mb.i_mb_y = h->sps->i_mb_height - 2; h->mb.i_mb_y > 0; h->mb.i_mb_y-- )
336 for( h->mb.i_mb_x = h->sps->i_mb_width - 2; h->mb.i_mb_x > 0; h->mb.i_mb_x-- )
338 int i_mb_cost = x264_slicetype_mb_cost( h, a, frames, p0, p1, b, dist_scale_factor, do_search );
339 int i_mb_cost_aq = i_mb_cost;
340 if( h->param.rc.i_aq_mode )
341 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;
342 i_score += i_mb_cost;
343 i_score_aq += i_mb_cost_aq;
348 i_score = i_score * 100 / (120 + h->param.i_bframe_bias);
350 frames[b]->b_intra_calculated = 1;
352 frames[b]->i_cost_est[b-p0][p1-b] = i_score;
353 frames[b]->i_cost_est_aq[b-p0][p1-b] = i_score_aq;
357 if( b_intra_penalty )
359 // arbitrary penalty for I-blocks after B-frames
361 i_score += i_score * frames[b]->i_intra_mbs[b-p0] / (nmb * 8);
366 /* If MB-tree changes the quantizers, we need to recalculate the frame cost without
367 * re-running lookahead. */
368 static int x264_slicetype_frame_cost_recalculate( x264_t *h, x264_mb_analysis_t *a, x264_frame_t **frames,
369 int p0, int p1, int b )
372 int *row_satd = frames[b]->i_row_satds[b-p0][p1-b];
374 for( h->mb.i_mb_y = h->sps->i_mb_height - 1; h->mb.i_mb_y >= 0; h->mb.i_mb_y-- )
376 row_satd[ h->mb.i_mb_y ] = 0;
377 for( h->mb.i_mb_x = h->sps->i_mb_width - 1; h->mb.i_mb_x >= 0; h->mb.i_mb_x-- )
379 int i_mb_xy = h->mb.i_mb_x + h->mb.i_mb_y*h->mb.i_mb_stride;
380 int i_mb_cost = frames[b]->lowres_costs[b-p0][p1-b][i_mb_xy];
381 float qp_adj = frames[b]->f_qp_offset[i_mb_xy];
382 i_mb_cost = (i_mb_cost * x264_exp2fix8(qp_adj*(-1.f/6.f)) + 128) >> 8;
383 row_satd[ h->mb.i_mb_y ] += i_mb_cost;
384 if( (h->mb.i_mb_y > 0 && h->mb.i_mb_y < h->sps->i_mb_height - 1 &&
385 h->mb.i_mb_x > 0 && h->mb.i_mb_x < h->sps->i_mb_width - 1) ||
386 h->sps->i_mb_width <= 2 || h->sps->i_mb_height <= 2 )
388 i_score += i_mb_cost;
395 static void x264_macroblock_tree_propagate( x264_t *h, x264_frame_t **frames, int p0, int p1, int b )
397 x264_frame_t *refs[2] = {frames[p0],frames[p1]};
398 int dist_scale_factor = p1 != p0 ? 128 : ( ((b-p0) << 8) + ((p1-p0) >> 1) ) / (p1-p0);
399 int i_bipred_weight = h->param.analyse.b_weighted_bipred ? 64 - (dist_scale_factor>>2) : 32;
401 for( h->mb.i_mb_y = 0; h->mb.i_mb_y < h->sps->i_mb_height; h->mb.i_mb_y++ )
403 for( h->mb.i_mb_x = 0; h->mb.i_mb_x < h->sps->i_mb_width; h->mb.i_mb_x++ )
405 int mb_index = h->mb.i_mb_x + h->mb.i_mb_y*h->mb.i_mb_stride;
406 int inter_cost = frames[b]->lowres_costs[b-p0][p1-b][mb_index];
407 int intra_cost = (frames[b]->i_intra_cost[mb_index] * frames[b]->i_inv_qscale_factor[mb_index]+128)>>8;
408 int lists_used = frames[b]->lowres_inter_types[b-p0][p1-b][mb_index];
409 /* The approximate amount of data that this block contains. */
410 int propagate_amount = intra_cost + frames[b]->i_propagate_cost[mb_index];
412 /* Divide by 64 for per-pixel summing. */
413 propagate_amount = (((uint64_t)propagate_amount*(intra_cost-inter_cost)) / intra_cost + 32) >> 6;
415 /* Don't propagate for an intra block. */
416 if( inter_cost < intra_cost )
419 mv[0][0] = frames[b]->lowres_mvs[0][b-p0-1][mb_index][0];
420 mv[0][1] = frames[b]->lowres_mvs[0][b-p0-1][mb_index][1];
423 mv[1][0] = frames[b]->lowres_mvs[1][p1-b-1][mb_index][0];
424 mv[1][1] = frames[b]->lowres_mvs[1][p1-b-1][mb_index][1];
427 /* Follow the MVs to the previous frame(s). */
428 for( list = 0; list < 2; list++ )
429 if( (lists_used >> list)&1 )
433 int listamount = propagate_amount;
434 int mbx = (x>>5)+h->mb.i_mb_x;
435 int mby = ((y>>5)+h->mb.i_mb_y);
436 int idx0 = mbx + mby*h->mb.i_mb_stride;
438 int idx2 = idx0 + h->mb.i_mb_stride;
439 int idx3 = idx0 + h->mb.i_mb_stride + 1;
440 int idx0weight = (32-(y&31))*(32-(x&31));
441 int idx1weight = (32-(y&31))*(x&31);
442 int idx2weight = (y&31)*(32-(x&31));
443 int idx3weight = (y&31)*(x&31);
445 /* Apply bipred weighting. */
446 if( lists_used == 3 )
447 listamount = (listamount * (list?(64-i_bipred_weight):i_bipred_weight) + 32) >> 6;
449 #define CLIP_ADD(s,x) (s) = X264_MIN((s)+(x),(1<<16)-1)
451 /* We could just clip the MVs, but pixels that lie outside the frame probably shouldn't
453 if( mbx < h->sps->i_mb_width-1 && mby < h->sps->i_mb_height-1 && mbx >= 0 && mby >= 0 )
455 CLIP_ADD( refs[list]->i_propagate_cost[idx0], (listamount*idx0weight+8)>>4 );
456 CLIP_ADD( refs[list]->i_propagate_cost[idx1], (listamount*idx1weight+8)>>4 );
457 CLIP_ADD( refs[list]->i_propagate_cost[idx2], (listamount*idx2weight+8)>>4 );
458 CLIP_ADD( refs[list]->i_propagate_cost[idx3], (listamount*idx3weight+8)>>4 );
460 else /* Check offsets individually */
462 if( mbx < h->sps->i_mb_width && mby < h->sps->i_mb_height && mbx >= 0 && mby >= 0 )
463 CLIP_ADD( refs[list]->i_propagate_cost[idx0], (listamount*idx0weight+8)>>4 );
464 if( mbx+1 < h->sps->i_mb_width && mby < h->sps->i_mb_height && mbx+1 >= 0 && mby >= 0 )
465 CLIP_ADD( refs[list]->i_propagate_cost[idx1], (listamount*idx1weight+8)>>4 );
466 if( mbx < h->sps->i_mb_width && mby+1 < h->sps->i_mb_height && mbx >= 0 && mby+1 >= 0 )
467 CLIP_ADD( refs[list]->i_propagate_cost[idx2], (listamount*idx2weight+8)>>4 );
468 if( mbx+1 < h->sps->i_mb_width && mby+1 < h->sps->i_mb_height && mbx+1 >= 0 && mby+1 >= 0 )
469 CLIP_ADD( refs[list]->i_propagate_cost[idx3], (listamount*idx3weight+8)>>4 );
477 static void x264_macroblock_tree( x264_t *h, x264_mb_analysis_t *a, x264_frame_t **frames, int num_frames, int b_intra )
479 int i, idx = !b_intra;
480 int last_nonb, cur_nonb = 1;
482 x264_slicetype_frame_cost( h, a, frames, 0, 0, 0, 0 );
485 while( i > 0 && frames[i]->i_type == X264_TYPE_B )
492 memset( frames[last_nonb]->i_propagate_cost, 0, h->mb.i_mb_count * sizeof(uint32_t) );
496 while( frames[cur_nonb]->i_type == X264_TYPE_B && cur_nonb > 0 )
500 x264_slicetype_frame_cost( h, a, frames, cur_nonb, last_nonb, last_nonb, 0 );
501 memset( frames[cur_nonb]->i_propagate_cost, 0, h->mb.i_mb_count * sizeof(uint32_t) );
502 x264_macroblock_tree_propagate( h, frames, cur_nonb, last_nonb, last_nonb );
503 while( frames[i]->i_type == X264_TYPE_B && i > 0 )
505 x264_slicetype_frame_cost( h, a, frames, cur_nonb, last_nonb, i, 0 );
506 memset( frames[i]->i_propagate_cost, 0, h->mb.i_mb_count * sizeof(uint32_t) );
507 x264_macroblock_tree_propagate( h, frames, cur_nonb, last_nonb, i );
510 last_nonb = cur_nonb;
514 for( h->mb.i_mb_y = 0; h->mb.i_mb_y < h->sps->i_mb_height; h->mb.i_mb_y++ )
516 for( h->mb.i_mb_x = 0; h->mb.i_mb_x < h->sps->i_mb_width; h->mb.i_mb_x++ )
518 int mb_index = h->mb.i_mb_x + h->mb.i_mb_y*h->mb.i_mb_stride;
519 int intra_cost = (frames[last_nonb]->i_intra_cost[mb_index] * frames[last_nonb]->i_inv_qscale_factor[mb_index]+128)>>8;
523 int propagate_cost = frames[last_nonb]->i_propagate_cost[mb_index];
524 float log2_ratio = x264_log2(intra_cost + propagate_cost) - x264_log2(intra_cost);
525 /* Allow the constant to be adjusted via qcompress, since the two
526 * concepts are very similar. */
527 frames[last_nonb]->f_qp_offset[mb_index] -= 5.0 * (1.0 - h->param.rc.f_qcompress) * log2_ratio;
533 static int x264_slicetype_path_cost( x264_t *h, x264_mb_analysis_t *a, x264_frame_t **frames, char *path, int threshold )
538 path--; /* Since the 1st path element is really the second frame */
543 /* Find the location of the next P-frame. */
544 while( path[next_p] && path[next_p] != 'P' )
546 /* Return if the path doesn't end on a P-frame. */
547 if( path[next_p] != 'P' )
550 /* Add the cost of the P-frame found above */
551 cost += x264_slicetype_frame_cost( h, a, frames, cur_p, next_p, next_p, 0 );
552 /* Early terminate if the cost we have found is larger than the best path cost so far */
553 if( cost > threshold )
556 for( next_b = loc; next_b < next_p && cost < threshold; next_b++ )
557 cost += x264_slicetype_frame_cost( h, a, frames, cur_p, next_p, next_b, 0 );
565 /* Viterbi/trellis slicetype decision algorithm. */
566 /* Uses strings due to the fact that the speed of the control functions is
567 negligable compared to the cost of running slicetype_frame_cost, and because
568 it makes debugging easier. */
569 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] )
571 char paths[X264_BFRAME_MAX+2][X264_LOOKAHEAD_MAX] = {{0}};
572 int num_paths = X264_MIN(max_bframes+1, length);
573 int suffix_size, loc, path;
574 int best_cost = COST_MAX;
575 int best_path_index = 0;
576 length = X264_MIN(length,X264_LOOKAHEAD_MAX);
578 /* Iterate over all currently possible paths and add suffixes to each one */
579 for( suffix_size = 0; suffix_size < num_paths; suffix_size++ )
581 memcpy( paths[suffix_size], best_paths[length - (suffix_size + 1)], length - (suffix_size + 1) );
582 for( loc = 0; loc < suffix_size; loc++ )
583 strcat( paths[suffix_size], "B" );
584 strcat( paths[suffix_size], "P" );
587 /* Calculate the actual cost of each of the current paths */
588 for( path = 0; path < num_paths; path++ )
590 int cost = x264_slicetype_path_cost( h, a, frames, paths[path], best_cost );
591 if( cost < best_cost )
594 best_path_index = path;
598 /* Store the best path. */
599 memcpy( best_paths[length], paths[best_path_index], length );
602 static int scenecut( x264_t *h, x264_mb_analysis_t *a, x264_frame_t **frames, int p0, int p1 )
604 x264_frame_t *frame = frames[p1];
605 x264_slicetype_frame_cost( h, a, frames, p0, p1, p1, 0 );
607 int icost = frame->i_cost_est[0][0];
608 int pcost = frame->i_cost_est[p1-p0][0];
610 int i_gop_size = frame->i_frame - h->frames.i_last_idr;
611 float f_thresh_max = h->param.i_scenecut_threshold / 100.0;
612 /* magic numbers pulled out of thin air */
613 float f_thresh_min = f_thresh_max * h->param.i_keyint_min
614 / ( h->param.i_keyint_max * 4 );
617 if( h->param.i_keyint_min == h->param.i_keyint_max )
618 f_thresh_min= f_thresh_max;
619 if( i_gop_size < h->param.i_keyint_min / 4 )
620 f_bias = f_thresh_min / 4;
621 else if( i_gop_size <= h->param.i_keyint_min )
622 f_bias = f_thresh_min * i_gop_size / h->param.i_keyint_min;
625 f_bias = f_thresh_min
626 + ( f_thresh_max - f_thresh_min )
627 * ( i_gop_size - h->param.i_keyint_min )
628 / ( h->param.i_keyint_max - h->param.i_keyint_min ) ;
631 res = pcost >= (1.0 - f_bias) * icost;
634 int imb = frame->i_intra_mbs[p1-p0];
635 int pmb = NUM_MBS - imb;
636 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",
638 icost, pcost, 1. - (double)pcost / icost,
639 f_bias, i_gop_size, imb, pmb );
644 static void x264_slicetype_analyse( x264_t *h, int keyframe )
646 x264_mb_analysis_t a;
647 x264_frame_t *frames[X264_LOOKAHEAD_MAX+3] = { NULL, };
651 int i_mb_count = NUM_MBS;
652 int cost1p0, cost2p0, cost1b1, cost2p1;
655 assert( h->frames.b_have_lowres );
657 if( !h->frames.last_nonb )
659 frames[0] = h->frames.last_nonb;
660 for( j = 0; h->frames.next[j] && h->frames.next[j]->i_type == X264_TYPE_AUTO; j++ )
661 frames[j+1] = h->frames.next[j];
662 keyint_limit = h->param.i_keyint_max - frames[0]->i_frame + h->frames.i_last_idr - 1;
663 num_frames = X264_MIN( j, keyint_limit );
665 if( num_frames == 0 && (!j || !h->param.rc.b_mb_tree) )
668 x264_lowres_context_init( h, &a );
669 idr_frame_type = frames[1]->i_frame - h->frames.i_last_idr >= h->param.i_keyint_min ? X264_TYPE_IDR : X264_TYPE_I;
671 if( num_frames == 1 && !h->param.rc.b_mb_tree )
673 frames[1]->i_type = X264_TYPE_P;
674 if( h->param.i_scenecut_threshold && scenecut( h, &a, frames, 0, 1 ) )
675 frames[1]->i_type = idr_frame_type;
679 /* This is important psy-wise: if we have a non-scenecut keyframe,
680 * there will be significant visual artifacts if the frames just before
681 * go down in quality due to being referenced less, despite it being
682 * more RD-optimal. */
683 if( h->param.analyse.b_psy && h->param.rc.b_mb_tree )
686 char best_paths[X264_LOOKAHEAD_MAX][X264_LOOKAHEAD_MAX] = {"","P"};
689 int max_bframes = X264_MIN(num_frames-1, h->param.i_bframe);
690 int num_analysed_frames = num_frames;
692 if( h->param.i_scenecut_threshold && scenecut( h, &a, frames, 0, 1 ) )
694 frames[1]->i_type = idr_frame_type;
698 if( h->param.i_bframe )
700 if( h->param.i_bframe_adaptive == X264_B_ADAPT_TRELLIS )
702 /* Perform the frametype analysis. */
703 for( n = 2; n < num_frames-1; n++ )
704 x264_slicetype_path( h, &a, frames, n, max_bframes, num_frames-max_bframes, best_paths );
705 num_bframes = strspn( best_paths[num_frames-2], "B" );
706 /* Load the results of the analysis into the frame types. */
707 for( j = 1; j < num_frames; j++ )
708 frames[j]->i_type = best_paths[num_frames-2][j-1] == 'B' ? X264_TYPE_B : X264_TYPE_P;
709 frames[num_frames]->i_type = X264_TYPE_P;
711 else if( h->param.i_bframe_adaptive == X264_B_ADAPT_FAST )
713 for( i = 0; i < num_frames-(2-!i); )
715 cost2p1 = x264_slicetype_frame_cost( h, &a, frames, i+0, i+2, i+2, 1 );
716 if( frames[i+2]->i_intra_mbs[2] > i_mb_count / 2 )
718 frames[i+1]->i_type = X264_TYPE_P;
719 frames[i+2]->i_type = X264_TYPE_P;
724 cost1b1 = x264_slicetype_frame_cost( h, &a, frames, i+0, i+2, i+1, 0 );
725 cost1p0 = x264_slicetype_frame_cost( h, &a, frames, i+0, i+1, i+1, 0 );
726 cost2p0 = x264_slicetype_frame_cost( h, &a, frames, i+1, i+2, i+2, 0 );
728 if( cost1p0 + cost2p0 < cost1b1 + cost2p1 )
730 frames[i+1]->i_type = X264_TYPE_P;
731 frames[i+2]->i_type = X264_TYPE_P;
736 // arbitrary and untuned
737 #define INTER_THRESH 300
738 #define P_SENS_BIAS (50 - h->param.i_bframe_bias)
739 frames[i+1]->i_type = X264_TYPE_B;
740 frames[i+2]->i_type = X264_TYPE_P;
742 for( j = i+2; j <= X264_MIN( h->param.i_bframe, num_frames-2 ); j++ )
744 int pthresh = X264_MAX(INTER_THRESH - P_SENS_BIAS * (j-i-1), INTER_THRESH/10);
745 int pcost = x264_slicetype_frame_cost( h, &a, frames, i+0, j+1, j+1, 1 );
747 if( pcost > pthresh*i_mb_count || frames[j+1]->i_intra_mbs[j-i+1] > i_mb_count/3 )
749 frames[j]->i_type = X264_TYPE_P;
753 frames[j]->i_type = X264_TYPE_B;
757 frames[i+!i]->i_type = X264_TYPE_P;
759 while( num_bframes < num_frames && frames[num_bframes+1]->i_type == X264_TYPE_B )
764 num_bframes = X264_MIN(num_frames-1, h->param.i_bframe);
765 for( j = 1; j < num_frames; j++ )
766 frames[j]->i_type = (j%(num_bframes+1)) ? X264_TYPE_B : X264_TYPE_P;
767 frames[num_frames]->i_type = X264_TYPE_P;
770 /* Check scenecut on the first minigop. */
771 for( j = 1; j < num_bframes+1; j++ )
772 if( h->param.i_scenecut_threshold && scenecut( h, &a, frames, j, j+1 ) )
774 frames[j]->i_type = X264_TYPE_P;
775 num_analysed_frames = j;
779 reset_start = keyframe ? 1 : X264_MIN( num_bframes+2, num_analysed_frames+1 );
783 for( j = 1; j < num_frames; j++ )
784 frames[j]->i_type = X264_TYPE_P;
785 reset_start = !keyframe + 1;
788 /* Perform the actual macroblock tree analysis.
789 * Don't go farther than the lookahead parameter; this helps in short GOPs. */
790 if( h->param.rc.b_mb_tree )
791 x264_macroblock_tree( h, &a, frames, X264_MIN(num_analysed_frames, h->param.rc.i_lookahead), keyframe );
793 /* Enforce keyframe limit. */
794 if( h->param.i_bframe )
795 for( j = 0; j <= num_bframes; j++ )
796 if( j+1 > keyint_limit )
799 frames[j]->i_type = X264_TYPE_P;
800 frames[j+1]->i_type = idr_frame_type;
805 /* Restore frametypes for all frames that haven't actually been decided yet. */
806 for( j = reset_start; j <= num_frames; j++ )
807 frames[j]->i_type = X264_TYPE_AUTO;
810 void x264_slicetype_decide( x264_t *h )
816 if( h->frames.next[0] == NULL )
819 if( h->param.rc.b_stat_read )
821 /* Use the frame types from the first pass */
822 for( i = 0; h->frames.next[i] != NULL; i++ )
823 h->frames.next[i]->i_type =
824 x264_ratecontrol_slice_type( h, h->frames.next[i]->i_frame );
826 else if( (h->param.i_bframe && h->param.i_bframe_adaptive)
827 || h->param.i_scenecut_threshold
828 || h->param.rc.b_mb_tree )
829 x264_slicetype_analyse( h, 0 );
831 for( bframes = 0;; bframes++ )
833 frm = h->frames.next[bframes];
836 if( frm->i_frame - h->frames.i_last_idr >= h->param.i_keyint_max )
838 if( frm->i_type == X264_TYPE_AUTO )
839 frm->i_type = X264_TYPE_IDR;
840 if( frm->i_type != X264_TYPE_IDR )
841 x264_log( h, X264_LOG_WARNING, "specified frame type (%d) is not compatible with keyframe interval\n", frm->i_type );
843 if( frm->i_type == X264_TYPE_IDR )
849 h->frames.next[bframes]->i_type = X264_TYPE_P;
857 if( bframes == h->param.i_bframe
858 || h->frames.next[bframes+1] == NULL )
860 if( IS_X264_TYPE_B( frm->i_type ) )
861 x264_log( h, X264_LOG_WARNING, "specified frame type is not compatible with max B-frames\n" );
862 if( frm->i_type == X264_TYPE_AUTO
863 || IS_X264_TYPE_B( frm->i_type ) )
864 frm->i_type = X264_TYPE_P;
867 if( frm->i_type == X264_TYPE_AUTO )
868 frm->i_type = X264_TYPE_B;
870 else if( !IS_X264_TYPE_B( frm->i_type ) ) break;
874 int x264_rc_analyse_slice( x264_t *h )
876 x264_mb_analysis_t a;
877 x264_frame_t *frames[X264_LOOKAHEAD_MAX+2] = { NULL, };
881 x264_lowres_context_init( h, &a );
883 if( IS_X264_TYPE_I(h->fenc->i_type) )
886 /* For MB-tree, we have to perform propagation analysis on I-frames too. */
887 if( h->param.rc.b_mb_tree )
889 h->frames.last_nonb = h->fenc;
890 x264_slicetype_analyse( h, 1 );
893 else if( X264_TYPE_P == h->fenc->i_type )
896 while( h->frames.current[p1] && IS_X264_TYPE_B( h->frames.current[p1]->i_type ) )
903 p1 = (h->fref1[0]->i_poc - h->fref0[0]->i_poc)/2;
904 b = (h->fref1[0]->i_poc - h->fenc->i_poc)/2;
905 frames[p1] = h->fref1[0];
907 frames[p0] = h->fref0[0];
910 if( h->param.rc.b_mb_tree )
911 cost = x264_slicetype_frame_cost_recalculate( h, &a, frames, p0, p1, b );
914 cost = x264_slicetype_frame_cost( h, &a, frames, p0, p1, b, 0 );
916 /* In AQ, use the weighted score instead. */
917 if( h->param.rc.i_aq_mode )
918 cost = frames[b]->i_cost_est[b-p0][p1-b];
921 h->fenc->i_row_satd = h->fenc->i_row_satds[b-p0][p1-b];
922 h->fdec->i_row_satd = h->fdec->i_row_satds[b-p0][p1-b];
923 h->fdec->i_satd = cost;
924 memcpy( h->fdec->i_row_satd, h->fenc->i_row_satd, h->sps->i_mb_height * sizeof(int) );