1 /*****************************************************************************
2 * slicetype.c: h264 encoder library
3 *****************************************************************************
4 * Copyright (C) 2005-2008 x264 project
6 * Authors: Fiona Glaser <fiona@x264.com>
7 * Loren Merritt <lorenm@u.washington.edu>
8 * Dylan Yudaken <dyudaken@gmail.com>
10 * This program is free software; you can redistribute it and/or modify
11 * it under the terms of the GNU General Public License as published by
12 * the Free Software Foundation; either version 2 of the License, or
13 * (at your option) any later version.
15 * This program is distributed in the hope that it will be useful,
16 * but WITHOUT ANY WARRANTY; without even the implied warranty of
17 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
18 * GNU General Public License for more details.
20 * You should have received a copy of the GNU General Public License
21 * along with this program; if not, write to the Free Software
22 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02111, USA.
23 *****************************************************************************/
27 #include "common/common.h"
28 #include "common/cpu.h"
29 #include "macroblock.h"
32 static int x264_slicetype_frame_cost( x264_t *h, x264_mb_analysis_t *a,
33 x264_frame_t **frames, int p0, int p1, int b,
34 int b_intra_penalty );
36 static void x264_lowres_context_init( x264_t *h, x264_mb_analysis_t *a )
38 a->i_qp = X264_LOOKAHEAD_QP;
39 a->i_lambda = x264_lambda_tab[ a->i_qp ];
40 x264_mb_analyse_load_costs( h, a );
41 if( h->param.analyse.i_subpel_refine > 1 )
43 h->mb.i_me_method = X264_MIN( X264_ME_HEX, h->param.analyse.i_me_method );
44 h->mb.i_subpel_refine = 4;
48 h->mb.i_me_method = X264_ME_DIA;
49 h->mb.i_subpel_refine = 3;
51 h->mb.b_chroma_me = 0;
54 /* makes a non-h264 weight (i.e. fix7), into an h264 weight */
55 static void get_h264_weight( unsigned int weight_nonh264, int offset, x264_weight_t *w )
59 w->i_scale = weight_nonh264;
60 while( w->i_denom > 0 && (w->i_scale > 127 || !(w->i_scale & 1)) )
65 w->i_scale = X264_MIN( w->i_scale, 127 );
68 static NOINLINE void weights_plane_analyse( x264_t *h, uint8_t *plane, int width, int height, int stride, unsigned int *sum, uint64_t *var )
74 for( y = 0; y < height>>4; y++, p += stride*16 )
75 for( x = 0; x < width; x+=16 )
77 uint64_t res = h->pixf.var[PIXEL_16x16]( p + x, stride );
83 *var = ssd - ((uint64_t)sad * sad + width * height / 2) / (width * height);
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]; \
95 static NOINLINE uint8_t *x264_weight_cost_init_luma( x264_t *h, x264_frame_t *fenc, x264_frame_t *ref, uint8_t *dest )
97 int ref0_distance = fenc->i_frame - ref->i_frame - 1;
98 /* Note: this will never run during lookahead as weights_analyse is only called if no
99 * motion search has been done. */
100 if( fenc->lowres_mvs[0][ref0_distance][0][0] != 0x7FFF )
103 int i_stride = fenc->i_stride_lowres;
104 int i_lines = fenc->i_lines_lowres;
105 int i_width = fenc->i_width_lowres;
108 int i_pel_offset = 0;
110 for( y = 0; y < i_lines; y += 8, i_pel_offset = y*i_stride )
111 for( x = 0; x < i_width; x += 8, i_mb_xy++, i_pel_offset += 8 )
113 uint8_t *pix = &dest[ i_pel_offset ];
114 int mvx = fenc->lowres_mvs[0][ref0_distance][i_mb_xy][0];
115 int mvy = fenc->lowres_mvs[0][ref0_distance][i_mb_xy][1];
116 LOAD_HPELS_LUMA( src, ref->lowres );
117 h->mc.mc_luma( pix, i_stride, src, i_stride,
118 mvx, mvy, 8, 8, weight_none );
124 return ref->lowres[0];
126 #undef LOAD_HPELS_LUMA
128 static NOINLINE unsigned int x264_weight_cost( x264_t *h, x264_frame_t *fenc, uint8_t *src, x264_weight_t *w )
131 unsigned int cost = 0;
132 int i_stride = fenc->i_stride_lowres;
133 int i_lines = fenc->i_lines_lowres;
134 int i_width = fenc->i_width_lowres;
135 uint8_t *fenc_plane = fenc->lowres[0];
136 ALIGNED_8( uint8_t buf[8*8] );
142 for( y = 0; y < i_lines; y += 8, pixoff = y*i_stride )
143 for( x = 0; x < i_width; x += 8, i_mb++, pixoff += 8)
145 w->weightfn[8>>2]( buf, 8, &src[pixoff], i_stride, w, 8 );
146 cost += X264_MIN( h->pixf.mbcmp[PIXEL_8x8]( buf, 8, &fenc_plane[pixoff], i_stride ), fenc->i_intra_cost[i_mb] );
148 /* Add cost of weights in the slice header. */
150 if( h->param.i_slice_count )
151 numslices = h->param.i_slice_count;
152 else if( h->param.i_slice_max_mbs )
153 numslices = (h->sps->i_mb_width * h->sps->i_mb_height + h->param.i_slice_max_mbs-1) / h->param.i_slice_max_mbs;
156 /* FIXME: find a way to account for --slice-max-size?
157 * Multiply by 2 as there will be a duplicate. 10 bits added as if there is a weighted frame, then an additional duplicate is used.
158 * Since using lowres frames, assume lambda = 1. */
159 cost += numslices * ( 10 + 2 * ( bs_size_ue( w[0].i_denom ) + bs_size_se( w[0].i_scale ) + bs_size_se( w[0].i_offset ) ) );
162 for( y = 0; y < i_lines; y += 8, pixoff = y*i_stride )
163 for( x = 0; x < i_width; x += 8, i_mb++, pixoff += 8 )
164 cost += X264_MIN( h->pixf.mbcmp[PIXEL_8x8]( &src[pixoff], i_stride, &fenc_plane[pixoff], i_stride ), fenc->i_intra_cost[i_mb] );
169 void x264_weights_analyse( x264_t *h, x264_frame_t *fenc, x264_frame_t *ref, int b_lookahead )
171 unsigned int fenc_sum, ref_sum;
172 float fenc_mean, ref_mean;
173 uint64_t fenc_var, ref_var;
174 int i_off, offset_search;
175 int minoff, minscale, mindenom;
176 unsigned int minscore, origscore;
177 int i_delta_index = fenc->i_frame - ref->i_frame - 1;
178 /* epsilon is chosen to require at least a numerator of 127 (with denominator = 128) */
179 const float epsilon = 1.0/128.0;
182 x264_weight_t *weights = fenc->weight[0];
184 weights_plane_analyse( h, fenc->plane[0], fenc->i_width[0], fenc->i_lines[0], fenc->i_stride[0], &fenc_sum, &fenc_var );
185 weights_plane_analyse( h, ref->plane[0], ref->i_width[0], ref->i_lines[0], ref->i_stride[0], &ref_sum, &ref_var );
186 fenc_var = round( sqrt( fenc_var ) );
187 ref_var = round( sqrt( ref_var ) );
188 fenc_mean = (float)fenc_sum / (fenc->i_lines[0] * fenc->i_width[0]);
189 ref_mean = (float) ref_sum / (fenc->i_lines[0] * fenc->i_width[0]);
192 if( fabs( ref_mean - fenc_mean ) < 0.5 && fabsf( 1 - (float)fenc_var / ref_var ) < epsilon )
195 guess_scale = ref_var ? (float)fenc_var/ref_var : 0;
196 get_h264_weight( round( guess_scale * 128 ), 0, &weights[0] );
199 mindenom = weights[0].i_denom;
200 minscale = weights[0].i_scale;
202 offset_search = x264_clip3( floor( fenc_mean - ref_mean * minscale / (1 << mindenom) + 0.5f*b_lookahead ), -128, 126 );
204 if( !fenc->b_intra_calculated )
206 x264_mb_analysis_t a;
207 x264_lowres_context_init( h, &a );
208 x264_slicetype_frame_cost( h, &a, &fenc, 0, 0, 0, 0 );
210 uint8_t *mcbuf = x264_weight_cost_init_luma( h, fenc, ref, h->mb.p_weight_buf[0] );
211 origscore = minscore = x264_weight_cost( h, fenc, mcbuf, 0 );
216 // This gives a slight improvement due to rounding errors but only tests
217 // one offset on lookahead.
218 // TODO: currently searches only offset +1. try other offsets/multipliers/combinations thereof?
219 for( i_off = offset_search; i_off <= offset_search+!b_lookahead; i_off++ )
221 SET_WEIGHT( weights[0], 1, minscale, mindenom, i_off );
222 unsigned int s = x264_weight_cost( h, fenc, mcbuf, &weights[0] );
223 COPY3_IF_LT( minscore, s, minoff, i_off, found, 1 );
227 /* FIXME: More analysis can be done here on SAD vs. SATD termination. */
228 /* 0.2% termination derived experimentally to avoid weird weights in frames that are mostly intra. */
229 if( !found || (minscale == 1<<mindenom && minoff == 0) || (float)minscore / origscore > 0.998 )
231 SET_WEIGHT( weights[0], 0, 1, 0, 0 );
235 SET_WEIGHT( weights[0], 1, minscale, mindenom, minoff );
237 if( h->param.analyse.i_weighted_pred == X264_WEIGHTP_FAKE && weights[0].weightfn )
238 fenc->f_weighted_cost_delta[i_delta_index] = (float)minscore / origscore;
240 if( weights[0].weightfn && b_lookahead )
242 //scale lowres in lookahead for slicetype_frame_cost
243 int i_padv = PADV<<h->param.b_interlaced;
244 uint8_t *src = ref->buffer_lowres[0];
245 uint8_t *dst = h->mb.p_weight_buf[0];
246 int width = ref->i_width_lowres + PADH*2;
247 int height = ref->i_lines_lowres + i_padv*2;
248 x264_weight_scale_plane( h, dst, ref->i_stride_lowres, src, ref->i_stride_lowres,
249 width, height, &weights[0] );
250 fenc->weighted[0] = h->mb.p_weight_buf[0] + PADH + ref->i_stride_lowres * i_padv;
254 static int x264_slicetype_mb_cost( x264_t *h, x264_mb_analysis_t *a,
255 x264_frame_t **frames, int p0, int p1, int b,
256 int dist_scale_factor, int do_search[2], const x264_weight_t *w )
258 x264_frame_t *fref0 = frames[p0];
259 x264_frame_t *fref1 = frames[p1];
260 x264_frame_t *fenc = frames[b];
261 const int b_bidir = (b < p1);
262 const int i_mb_x = h->mb.i_mb_x;
263 const int i_mb_y = h->mb.i_mb_y;
264 const int i_mb_stride = h->sps->i_mb_width;
265 const int i_mb_xy = i_mb_x + i_mb_y * i_mb_stride;
266 const int i_stride = fenc->i_stride_lowres;
267 const int i_pel_offset = 8 * (i_mb_x + i_mb_y * i_stride);
268 const int i_bipred_weight = h->param.analyse.b_weighted_bipred ? 64 - (dist_scale_factor>>2) : 32;
269 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] };
270 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] };
272 ALIGNED_8( uint8_t pix1[9*FDEC_STRIDE] );
273 uint8_t *pix2 = pix1+8;
275 int i_bcost = COST_MAX;
279 h->mb.pic.p_fenc[0] = h->mb.pic.fenc_buf;
280 h->mc.copy[PIXEL_8x8]( h->mb.pic.p_fenc[0], FENC_STRIDE, &fenc->lowres[0][i_pel_offset], i_stride, 8 );
283 goto lowres_intra_mb;
285 // no need for h->mb.mv_min[]
286 h->mb.mv_min_fpel[0] = -8*h->mb.i_mb_x - 4;
287 h->mb.mv_max_fpel[0] = 8*( h->sps->i_mb_width - h->mb.i_mb_x - 1 ) + 4;
288 h->mb.mv_min_spel[0] = 4*( h->mb.mv_min_fpel[0] - 8 );
289 h->mb.mv_max_spel[0] = 4*( h->mb.mv_max_fpel[0] + 8 );
290 if( h->mb.i_mb_x >= h->sps->i_mb_width - 2 )
292 h->mb.mv_min_fpel[1] = -8*h->mb.i_mb_y - 4;
293 h->mb.mv_max_fpel[1] = 8*( h->sps->i_mb_height - h->mb.i_mb_y - 1 ) + 4;
294 h->mb.mv_min_spel[1] = 4*( h->mb.mv_min_fpel[1] - 8 );
295 h->mb.mv_max_spel[1] = 4*( h->mb.mv_max_fpel[1] + 8 );
298 #define LOAD_HPELS_LUMA(dst, src) \
300 (dst)[0] = &(src)[0][i_pel_offset]; \
301 (dst)[1] = &(src)[1][i_pel_offset]; \
302 (dst)[2] = &(src)[2][i_pel_offset]; \
303 (dst)[3] = &(src)[3][i_pel_offset]; \
305 #define LOAD_WPELS_LUMA(dst,src) \
306 (dst) = &(src)[i_pel_offset];
308 #define CLIP_MV( mv ) \
310 mv[0] = x264_clip3( mv[0], h->mb.mv_min_spel[0], h->mb.mv_max_spel[0] ); \
311 mv[1] = x264_clip3( mv[1], h->mb.mv_min_spel[1], h->mb.mv_max_spel[1] ); \
313 #define TRY_BIDIR( mv0, mv1, penalty ) \
315 int stride1 = 16, stride2 = 16; \
316 uint8_t *src1, *src2; \
318 src1 = h->mc.get_ref( pix1, &stride1, m[0].p_fref, m[0].i_stride[0], \
319 (mv0)[0], (mv0)[1], 8, 8, w ); \
320 src2 = h->mc.get_ref( pix2, &stride2, m[1].p_fref, m[1].i_stride[0], \
321 (mv1)[0], (mv1)[1], 8, 8, w ); \
322 h->mc.avg[PIXEL_8x8]( pix1, 16, src1, stride1, src2, stride2, i_bipred_weight ); \
323 i_cost = penalty + h->pixf.mbcmp[PIXEL_8x8]( \
324 m[0].p_fenc[0], FENC_STRIDE, pix1, 16 ); \
325 COPY2_IF_LT( i_bcost, i_cost, list_used, 3 ); \
328 m[0].i_pixel = PIXEL_8x8;
329 m[0].p_cost_mv = a->p_cost_mv;
330 m[0].i_stride[0] = i_stride;
331 m[0].p_fenc[0] = h->mb.pic.p_fenc[0];
333 LOAD_HPELS_LUMA( m[0].p_fref, fref0->lowres );
334 m[0].p_fref_w = m[0].p_fref[0];
336 LOAD_WPELS_LUMA( m[0].p_fref_w, fenc->weighted[0] );
340 int16_t *mvr = fref1->lowres_mvs[0][p1-p0-1][i_mb_xy];
343 h->mc.memcpy_aligned( &m[1], &m[0], sizeof(x264_me_t) );
345 m[1].weight = weight_none;
346 LOAD_HPELS_LUMA( m[1].p_fref, fref1->lowres );
347 m[1].p_fref_w = m[1].p_fref[0];
349 dmv[0][0] = ( mvr[0] * dist_scale_factor + 128 ) >> 8;
350 dmv[0][1] = ( mvr[1] * dist_scale_factor + 128 ) >> 8;
351 dmv[1][0] = dmv[0][0] - mvr[0];
352 dmv[1][1] = dmv[0][1] - mvr[1];
356 TRY_BIDIR( dmv[0], dmv[1], 0 );
357 if( dmv[0][0] | dmv[0][1] | dmv[1][0] | dmv[1][1] )
360 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 );
361 i_cost = h->pixf.mbcmp[PIXEL_8x8]( m[0].p_fenc[0], FENC_STRIDE, pix1, 16 );
362 COPY2_IF_LT( i_bcost, i_cost, list_used, 3 );
366 for( l = 0; l < 1 + b_bidir; l++ )
371 int16_t (*fenc_mv)[2] = fenc_mvs[l];
372 ALIGNED_4( int16_t mvc[4][2] );
374 /* Reverse-order MV prediction. */
378 #define MVC(mv) { CP32( mvc[i_mvc], mv ); i_mvc++; }
379 if( i_mb_x < h->sps->i_mb_width - 1 )
381 if( i_mb_y < h->sps->i_mb_height - 1 )
383 MVC(fenc_mv[i_mb_stride]);
385 MVC(fenc_mv[i_mb_stride-1]);
386 if( i_mb_x < h->sps->i_mb_width - 1 )
387 MVC(fenc_mv[i_mb_stride+1]);
390 x264_median_mv( m[l].mvp, mvc[0], mvc[1], mvc[2] );
391 x264_me_search( h, &m[l], mvc, i_mvc );
393 m[l].cost -= 2; // remove mvcost from skip mbs
396 CP32( fenc_mvs[l], m[l].mv );
397 *fenc_costs[l] = m[l].cost;
401 CP32( m[l].mv, fenc_mvs[l] );
402 m[l].cost = *fenc_costs[l];
404 COPY2_IF_LT( i_bcost, m[l].cost, list_used, l+1 );
407 if( b_bidir && ( M32( m[0].mv ) || M32( m[1].mv ) ) )
408 TRY_BIDIR( m[0].mv, m[1].mv, 5 );
410 /* Store to width-2 bitfield. */
411 frames[b]->lowres_inter_types[b-p0][p1-b][i_mb_xy>>2] &= ~(3<<((i_mb_xy&3)*2));
412 frames[b]->lowres_inter_types[b-p0][p1-b][i_mb_xy>>2] |= list_used<<((i_mb_xy&3)*2);
415 /* forbid intra-mbs in B-frames, because it's rare and not worth checking */
416 /* FIXME: Should we still forbid them now that we cache intra scores? */
417 if( !b_bidir || h->param.rc.b_mb_tree )
419 int i_icost, b_intra;
420 if( !fenc->b_intra_calculated )
422 ALIGNED_ARRAY_16( uint8_t, edge,[33] );
423 uint8_t *pix = &pix1[8+FDEC_STRIDE - 1];
424 uint8_t *src = &fenc->lowres[0][i_pel_offset - 1];
425 const int intra_penalty = 5;
428 memcpy( pix-FDEC_STRIDE, src-i_stride, 17 );
430 pix[i*FDEC_STRIDE] = src[i*i_stride];
433 if( h->pixf.intra_mbcmp_x3_8x8c )
434 h->pixf.intra_mbcmp_x3_8x8c( h->mb.pic.p_fenc[0], pix, satds );
439 h->predict_8x8c[i]( pix );
440 satds[i] = h->pixf.mbcmp[PIXEL_8x8]( pix, FDEC_STRIDE, h->mb.pic.p_fenc[0], FENC_STRIDE );
443 i_icost = X264_MIN3( satds[0], satds[1], satds[2] );
445 if( h->param.analyse.i_subpel_refine > 1 )
447 h->predict_8x8c[I_PRED_CHROMA_P]( pix );
448 int satd = h->pixf.mbcmp[PIXEL_8x8]( pix, FDEC_STRIDE, h->mb.pic.p_fenc[0], FENC_STRIDE );
449 i_icost = X264_MIN( i_icost, satd );
450 h->predict_8x8_filter( pix, edge, ALL_NEIGHBORS, ALL_NEIGHBORS );
454 h->predict_8x8[i]( pix, edge );
455 satd = h->pixf.mbcmp[PIXEL_8x8]( pix, FDEC_STRIDE, h->mb.pic.p_fenc[0], FENC_STRIDE );
456 i_icost = X264_MIN( i_icost, satd );
460 i_icost += intra_penalty;
461 fenc->i_intra_cost[i_mb_xy] = i_icost;
464 i_icost = fenc->i_intra_cost[i_mb_xy];
467 b_intra = i_icost < i_bcost;
470 if( (i_mb_x > 0 && i_mb_x < h->sps->i_mb_width - 1
471 && i_mb_y > 0 && i_mb_y < h->sps->i_mb_height - 1)
472 || h->sps->i_mb_width <= 2 || h->sps->i_mb_height <= 2 )
474 fenc->i_intra_mbs[b-p0] += b_intra;
475 fenc->i_cost_est[0][0] += i_icost;
476 if( h->param.rc.i_aq_mode )
477 fenc->i_cost_est_aq[0][0] += (i_icost * fenc->i_inv_qscale_factor[i_mb_xy] + 128) >> 8;
482 fenc->lowres_costs[b-p0][p1-b][i_mb_xy] = i_bcost;
489 (h->sps->i_mb_width > 2 && h->sps->i_mb_height > 2 ?\
490 (h->sps->i_mb_width - 2) * (h->sps->i_mb_height - 2) :\
491 h->sps->i_mb_width * h->sps->i_mb_height)
493 static int x264_slicetype_frame_cost( x264_t *h, x264_mb_analysis_t *a,
494 x264_frame_t **frames, int p0, int p1, int b,
495 int b_intra_penalty )
499 /* Don't use the AQ'd scores for slicetype decision. */
502 const x264_weight_t *w = weight_none;
503 /* Check whether we already evaluated this frame
504 * If we have tried this frame as P, then we have also tried
505 * the preceding frames as B. (is this still true?) */
506 /* Also check that we already calculated the row SATDs for the current frame. */
507 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) )
509 i_score = frames[b]->i_cost_est[b-p0][p1-b];
513 int dist_scale_factor = 128;
514 int *row_satd = frames[b]->i_row_satds[b-p0][p1-b];
516 /* For each list, check to see whether we have lowres motion-searched this reference frame before. */
517 do_search[0] = b != p0 && frames[b]->lowres_mvs[0][b-p0-1][0][0] == 0x7FFF;
518 do_search[1] = b != p1 && frames[b]->lowres_mvs[1][p1-b-1][0][0] == 0x7FFF;
521 if( ( h->param.analyse.i_weighted_pred == X264_WEIGHTP_SMART
522 || h->param.analyse.i_weighted_pred == X264_WEIGHTP_FAKE ) && b == p1 )
524 x264_weights_analyse( h, frames[b], frames[p0], 1 );
525 w = frames[b]->weight[0];
527 frames[b]->lowres_mvs[0][b-p0-1][0][0] = 0;
529 if( do_search[1] ) frames[b]->lowres_mvs[1][p1-b-1][0][0] = 0;
533 frames[b]->i_intra_mbs[b-p0] = 0;
534 frames[b]->i_cost_est[0][0] = 0;
535 frames[b]->i_cost_est_aq[0][0] = 0;
538 dist_scale_factor = ( ((b-p0) << 8) + ((p1-p0) >> 1) ) / (p1-p0);
540 /* Lowres lookahead goes backwards because the MVs are used as predictors in the main encode.
541 * This considerably improves MV prediction overall. */
543 /* the edge mbs seem to reduce the predictive quality of the
544 * whole frame's score, but are needed for a spatial distribution. */
545 if( h->param.rc.b_mb_tree || h->param.rc.i_vbv_buffer_size ||
546 h->sps->i_mb_width <= 2 || h->sps->i_mb_height <= 2 )
548 for( h->mb.i_mb_y = h->sps->i_mb_height - 1; h->mb.i_mb_y >= 0; h->mb.i_mb_y-- )
550 row_satd[ h->mb.i_mb_y ] = 0;
551 for( h->mb.i_mb_x = h->sps->i_mb_width - 1; h->mb.i_mb_x >= 0; h->mb.i_mb_x-- )
553 int i_mb_cost = x264_slicetype_mb_cost( h, a, frames, p0, p1, b, dist_scale_factor, do_search, w );
554 int i_mb_cost_aq = i_mb_cost;
555 if( h->param.rc.i_aq_mode )
556 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;
557 row_satd[ h->mb.i_mb_y ] += i_mb_cost_aq;
558 if( (h->mb.i_mb_y > 0 && h->mb.i_mb_y < h->sps->i_mb_height - 1 &&
559 h->mb.i_mb_x > 0 && h->mb.i_mb_x < h->sps->i_mb_width - 1) ||
560 h->sps->i_mb_width <= 2 || h->sps->i_mb_height <= 2 )
562 /* Don't use AQ-weighted costs for slicetype decision, only for ratecontrol. */
563 i_score += i_mb_cost;
564 i_score_aq += i_mb_cost_aq;
571 for( h->mb.i_mb_y = h->sps->i_mb_height - 2; h->mb.i_mb_y > 0; h->mb.i_mb_y-- )
572 for( h->mb.i_mb_x = h->sps->i_mb_width - 2; h->mb.i_mb_x > 0; h->mb.i_mb_x-- )
574 int i_mb_cost = x264_slicetype_mb_cost( h, a, frames, p0, p1, b, dist_scale_factor, do_search, w );
575 int i_mb_cost_aq = i_mb_cost;
576 if( h->param.rc.i_aq_mode )
577 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;
578 i_score += i_mb_cost;
579 i_score_aq += i_mb_cost_aq;
584 i_score = (uint64_t)i_score * 100 / (120 + h->param.i_bframe_bias);
586 frames[b]->b_intra_calculated = 1;
588 frames[b]->i_cost_est[b-p0][p1-b] = i_score;
589 frames[b]->i_cost_est_aq[b-p0][p1-b] = i_score_aq;
593 if( b_intra_penalty )
595 // arbitrary penalty for I-blocks after B-frames
597 i_score += i_score * frames[b]->i_intra_mbs[b-p0] / (nmb * 8);
602 /* If MB-tree changes the quantizers, we need to recalculate the frame cost without
603 * re-running lookahead. */
604 static int x264_slicetype_frame_cost_recalculate( x264_t *h, x264_frame_t **frames, int p0, int p1, int b )
607 int *row_satd = frames[b]->i_row_satds[b-p0][p1-b];
608 float *qp_offset = IS_X264_TYPE_B(frames[b]->i_type) ? frames[b]->f_qp_offset_aq : frames[b]->f_qp_offset;
610 for( h->mb.i_mb_y = h->sps->i_mb_height - 1; h->mb.i_mb_y >= 0; h->mb.i_mb_y-- )
612 row_satd[ h->mb.i_mb_y ] = 0;
613 for( h->mb.i_mb_x = h->sps->i_mb_width - 1; h->mb.i_mb_x >= 0; h->mb.i_mb_x-- )
615 int i_mb_xy = h->mb.i_mb_x + h->mb.i_mb_y*h->mb.i_mb_stride;
616 int i_mb_cost = frames[b]->lowres_costs[b-p0][p1-b][i_mb_xy];
617 float qp_adj = qp_offset[i_mb_xy];
618 i_mb_cost = (i_mb_cost * x264_exp2fix8(qp_adj) + 128) >> 8;
619 row_satd[ h->mb.i_mb_y ] += i_mb_cost;
620 if( (h->mb.i_mb_y > 0 && h->mb.i_mb_y < h->sps->i_mb_height - 1 &&
621 h->mb.i_mb_x > 0 && h->mb.i_mb_x < h->sps->i_mb_width - 1) ||
622 h->sps->i_mb_width <= 2 || h->sps->i_mb_height <= 2 )
624 i_score += i_mb_cost;
631 static void x264_macroblock_tree_finish( x264_t *h, x264_frame_t *frame, int ref0_distance )
635 float weightdelta = 0.0;
636 if( ref0_distance && frame->f_weighted_cost_delta[ref0_distance-1] > 0 )
637 weightdelta = (1.0 - frame->f_weighted_cost_delta[ref0_distance-1]);
639 /* Allow the strength to be adjusted via qcompress, since the two
640 * concepts are very similar. */
641 float strength = 5.0f * (1.0f - h->param.rc.f_qcompress);
642 for( mb_index = 0; mb_index < h->mb.i_mb_count; mb_index++ )
644 int intra_cost = (frame->i_intra_cost[mb_index] * frame->i_inv_qscale_factor[mb_index]+128)>>8;
647 int propagate_cost = frame->i_propagate_cost[mb_index];
648 float log2_ratio = x264_log2(intra_cost + propagate_cost) - x264_log2(intra_cost) + weightdelta;
649 frame->f_qp_offset[mb_index] = frame->f_qp_offset_aq[mb_index] - strength * log2_ratio;
654 static void x264_macroblock_tree_propagate( x264_t *h, x264_frame_t **frames, int p0, int p1, int b )
656 uint16_t *ref_costs[2] = {frames[p0]->i_propagate_cost,frames[p1]->i_propagate_cost};
657 int dist_scale_factor = ( ((b-p0) << 8) + ((p1-p0) >> 1) ) / (p1-p0);
658 int i_bipred_weight = h->param.analyse.b_weighted_bipred ? 64 - (dist_scale_factor>>2) : 32;
659 int16_t (*mvs[2])[2] = { frames[b]->lowres_mvs[0][b-p0-1], frames[b]->lowres_mvs[1][p1-b-1] };
660 int bipred_weights[2] = {i_bipred_weight, 64 - i_bipred_weight};
661 int *buf = h->scratch_buffer;
663 for( h->mb.i_mb_y = 0; h->mb.i_mb_y < h->sps->i_mb_height; h->mb.i_mb_y++ )
665 int mb_index = h->mb.i_mb_y*h->mb.i_mb_stride;
666 h->mc.mbtree_propagate_cost( buf, frames[b]->i_propagate_cost+mb_index,
667 frames[b]->i_intra_cost+mb_index, frames[b]->lowres_costs[b-p0][p1-b]+mb_index,
668 frames[b]->i_inv_qscale_factor+mb_index, h->sps->i_mb_width );
669 for( h->mb.i_mb_x = 0; h->mb.i_mb_x < h->sps->i_mb_width; h->mb.i_mb_x++, mb_index++ )
671 int propagate_amount = buf[h->mb.i_mb_x];
672 /* Don't propagate for an intra block. */
673 if( propagate_amount > 0 )
675 /* Access width-2 bitfield. */
676 int lists_used = (frames[b]->lowres_inter_types[b-p0][p1-b][mb_index>>2] >> ((mb_index&3)*2))&3;
678 /* Follow the MVs to the previous frame(s). */
679 for( list = 0; list < 2; list++ )
680 if( (lists_used >> list)&1 )
682 int x = mvs[list][mb_index][0];
683 int y = mvs[list][mb_index][1];
684 int listamount = propagate_amount;
685 int mbx = (x>>5)+h->mb.i_mb_x;
686 int mby = (y>>5)+h->mb.i_mb_y;
687 int idx0 = mbx + mby*h->mb.i_mb_stride;
689 int idx2 = idx0 + h->mb.i_mb_stride;
690 int idx3 = idx0 + h->mb.i_mb_stride + 1;
693 int idx0weight = (32-y)*(32-x);
694 int idx1weight = (32-y)*x;
695 int idx2weight = y*(32-x);
696 int idx3weight = y*x;
698 /* Apply bipred weighting. */
699 if( lists_used == 3 )
700 listamount = (listamount * bipred_weights[list] + 32) >> 6;
702 #define CLIP_ADD(s,x) (s) = X264_MIN((s)+(x),(1<<16)-1)
704 /* We could just clip the MVs, but pixels that lie outside the frame probably shouldn't
706 if( mbx < h->sps->i_mb_width-1 && mby < h->sps->i_mb_height-1 && mbx >= 0 && mby >= 0 )
708 CLIP_ADD( ref_costs[list][idx0], (listamount*idx0weight+512)>>10 );
709 CLIP_ADD( ref_costs[list][idx1], (listamount*idx1weight+512)>>10 );
710 CLIP_ADD( ref_costs[list][idx2], (listamount*idx2weight+512)>>10 );
711 CLIP_ADD( ref_costs[list][idx3], (listamount*idx3weight+512)>>10 );
713 else /* Check offsets individually */
715 if( mbx < h->sps->i_mb_width && mby < h->sps->i_mb_height && mbx >= 0 && mby >= 0 )
716 CLIP_ADD( ref_costs[list][idx0], (listamount*idx0weight+512)>>10 );
717 if( mbx+1 < h->sps->i_mb_width && mby < h->sps->i_mb_height && mbx+1 >= 0 && mby >= 0 )
718 CLIP_ADD( ref_costs[list][idx1], (listamount*idx1weight+512)>>10 );
719 if( mbx < h->sps->i_mb_width && mby+1 < h->sps->i_mb_height && mbx >= 0 && mby+1 >= 0 )
720 CLIP_ADD( ref_costs[list][idx2], (listamount*idx2weight+512)>>10 );
721 if( mbx+1 < h->sps->i_mb_width && mby+1 < h->sps->i_mb_height && mbx+1 >= 0 && mby+1 >= 0 )
722 CLIP_ADD( ref_costs[list][idx3], (listamount*idx3weight+512)>>10 );
729 if( h->param.rc.i_vbv_buffer_size && b == p1 )
730 x264_macroblock_tree_finish( h, frames[b], b-p0 );
733 static void x264_macroblock_tree( x264_t *h, x264_mb_analysis_t *a, x264_frame_t **frames, int num_frames, int b_intra )
735 int i, idx = !b_intra;
736 int last_nonb, cur_nonb = 1;
738 x264_slicetype_frame_cost( h, a, frames, 0, 0, 0, 0 );
741 while( i > 0 && frames[i]->i_type == X264_TYPE_B )
745 if( last_nonb < idx )
748 memset( frames[last_nonb]->i_propagate_cost, 0, h->mb.i_mb_count * sizeof(uint16_t) );
752 while( frames[cur_nonb]->i_type == X264_TYPE_B && cur_nonb > 0 )
756 x264_slicetype_frame_cost( h, a, frames, cur_nonb, last_nonb, last_nonb, 0 );
757 memset( frames[cur_nonb]->i_propagate_cost, 0, h->mb.i_mb_count * sizeof(uint16_t) );
758 while( i > cur_nonb )
760 x264_slicetype_frame_cost( h, a, frames, cur_nonb, last_nonb, i, 0 );
761 memset( frames[i]->i_propagate_cost, 0, h->mb.i_mb_count * sizeof(uint16_t) );
762 x264_macroblock_tree_propagate( h, frames, cur_nonb, last_nonb, i );
765 x264_macroblock_tree_propagate( h, frames, cur_nonb, last_nonb, last_nonb );
766 last_nonb = cur_nonb;
769 x264_macroblock_tree_finish( h, frames[last_nonb], last_nonb );
772 static int x264_vbv_frame_cost( x264_t *h, x264_mb_analysis_t *a, x264_frame_t **frames, int p0, int p1, int b )
774 int cost = x264_slicetype_frame_cost( h, a, frames, p0, p1, b, 0 );
775 if( h->param.rc.i_aq_mode )
777 if( h->param.rc.b_mb_tree )
778 return x264_slicetype_frame_cost_recalculate( h, frames, p0, p1, b );
780 return frames[b]->i_cost_est_aq[b-p0][p1-b];
785 static void x264_vbv_lookahead( x264_t *h, x264_mb_analysis_t *a, x264_frame_t **frames, int num_frames, int keyframe )
787 int last_nonb = 0, cur_nonb = 1, next_nonb, i, idx = 0;
788 while( cur_nonb < num_frames && frames[cur_nonb]->i_type == X264_TYPE_B )
790 next_nonb = keyframe ? last_nonb : cur_nonb;
792 while( cur_nonb <= num_frames )
794 /* P/I cost: This shouldn't include the cost of next_nonb */
795 if( next_nonb != cur_nonb )
797 int p0 = IS_X264_TYPE_I( frames[cur_nonb]->i_type ) ? cur_nonb : last_nonb;
798 frames[next_nonb]->i_planned_satd[idx] = x264_vbv_frame_cost( h, a, frames, p0, cur_nonb, cur_nonb );
799 frames[next_nonb]->i_planned_type[idx] = frames[cur_nonb]->i_type;
802 /* Handle the B-frames: coded order */
803 for( i = last_nonb+1; i < cur_nonb; i++, idx++ )
805 frames[next_nonb]->i_planned_satd[idx] = x264_vbv_frame_cost( h, a, frames, last_nonb, cur_nonb, i );
806 frames[next_nonb]->i_planned_type[idx] = X264_TYPE_B;
808 last_nonb = cur_nonb;
810 while( cur_nonb <= num_frames && frames[cur_nonb]->i_type == X264_TYPE_B )
813 frames[next_nonb]->i_planned_type[idx] = X264_TYPE_AUTO;
816 static int x264_slicetype_path_cost( x264_t *h, x264_mb_analysis_t *a, x264_frame_t **frames, char *path, int threshold )
821 path--; /* Since the 1st path element is really the second frame */
826 /* Find the location of the next P-frame. */
827 while( path[next_p] && path[next_p] != 'P' )
829 /* Return if the path doesn't end on a P-frame. */
830 if( path[next_p] != 'P' )
833 /* Add the cost of the P-frame found above */
834 cost += x264_slicetype_frame_cost( h, a, frames, cur_p, next_p, next_p, 0 );
835 /* Early terminate if the cost we have found is larger than the best path cost so far */
836 if( cost > threshold )
839 for( next_b = loc; next_b < next_p && cost < threshold; next_b++ )
840 cost += x264_slicetype_frame_cost( h, a, frames, cur_p, next_p, next_b, 0 );
848 /* Viterbi/trellis slicetype decision algorithm. */
849 /* Uses strings due to the fact that the speed of the control functions is
850 negligable compared to the cost of running slicetype_frame_cost, and because
851 it makes debugging easier. */
852 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] )
854 char paths[X264_BFRAME_MAX+1][X264_LOOKAHEAD_MAX] = {{0}};
855 int num_paths = X264_MIN( max_bframes+1, length );
857 int best_cost = COST_MAX;
858 int best_path_index = 0;
860 /* Iterate over all currently possible paths */
861 for( path = 0; path < num_paths; path++ )
863 /* Add suffixes to the current path */
864 int len = length - (path + 1);
865 memcpy( paths[path], best_paths[len % (X264_BFRAME_MAX+1)], len );
866 memset( paths[path]+len, 'B', path );
867 strcat( paths[path], "P" );
869 /* Calculate the actual cost of the current path */
870 int cost = x264_slicetype_path_cost( h, a, frames, paths[path], best_cost );
871 if( cost < best_cost )
874 best_path_index = path;
878 /* Store the best path. */
879 memcpy( best_paths[length % (X264_BFRAME_MAX+1)], paths[best_path_index], length );
882 static int scenecut_internal( x264_t *h, x264_mb_analysis_t *a, x264_frame_t **frames, int p0, int p1, int print )
884 x264_frame_t *frame = frames[p1];
885 x264_slicetype_frame_cost( h, a, frames, p0, p1, p1, 0 );
887 int icost = frame->i_cost_est[0][0];
888 int pcost = frame->i_cost_est[p1-p0][0];
890 int i_gop_size = frame->i_frame - h->lookahead->i_last_idr;
891 float f_thresh_max = h->param.i_scenecut_threshold / 100.0;
892 /* magic numbers pulled out of thin air */
893 float f_thresh_min = f_thresh_max * h->param.i_keyint_min
894 / ( h->param.i_keyint_max * 4 );
897 if( h->param.i_keyint_min == h->param.i_keyint_max )
898 f_thresh_min= f_thresh_max;
899 if( i_gop_size < h->param.i_keyint_min / 4 )
900 f_bias = f_thresh_min / 4;
901 else if( i_gop_size <= h->param.i_keyint_min )
902 f_bias = f_thresh_min * i_gop_size / h->param.i_keyint_min;
905 f_bias = f_thresh_min
906 + ( f_thresh_max - f_thresh_min )
907 * ( i_gop_size - h->param.i_keyint_min )
908 / ( h->param.i_keyint_max - h->param.i_keyint_min ) ;
911 res = pcost >= (1.0 - f_bias) * icost;
914 int imb = frame->i_intra_mbs[p1-p0];
915 int pmb = NUM_MBS - imb;
916 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",
918 icost, pcost, 1. - (double)pcost / icost,
919 f_bias, i_gop_size, imb, pmb );
924 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 )
926 int curp0, curp1, i, maxp1 = p0 + 1;
928 /* Only do analysis during a normal scenecut check. */
929 if( real_scenecut && h->param.i_bframe )
931 /* Look ahead to avoid coding short flashes as scenecuts. */
932 if( h->param.i_bframe_adaptive == X264_B_ADAPT_TRELLIS )
933 /* Don't analyse any more frames than the trellis would have covered. */
934 maxp1 += h->param.i_bframe;
937 maxp1 = X264_MIN( maxp1, num_frames );
939 /* Where A and B are scenes: AAAAAABBBAAAAAA
940 * If BBB is shorter than (maxp1-p0), it is detected as a flash
941 * and not considered a scenecut. */
942 for( curp1 = p1; curp1 <= maxp1; curp1++ )
943 if( !scenecut_internal( h, a, frames, p0, curp1, 0 ) )
944 /* Any frame in between p0 and cur_p1 cannot be a real scenecut. */
945 for( i = curp1; i > p0; i-- )
946 frames[i]->b_scenecut = 0;
948 /* Where A-F are scenes: AAAAABBCCDDEEFFFFFF
949 * If each of BB ... EE are shorter than (maxp1-p0), they are
950 * detected as flashes and not considered scenecuts.
951 * Instead, the first F frame becomes a scenecut. */
952 for( curp0 = p0; curp0 < maxp1; curp0++ )
953 if( scenecut_internal( h, a, frames, curp0, maxp1, 0 ) )
954 /* If cur_p0 is the p0 of a scenecut, it cannot be the p1 of a scenecut. */
955 frames[curp0]->b_scenecut = 0;
958 /* Ignore frames that are part of a flash, i.e. cannot be real scenecuts. */
959 if( !frames[p1]->b_scenecut )
961 return scenecut_internal( h, a, frames, p0, p1, real_scenecut );
964 void x264_slicetype_analyse( x264_t *h, int keyframe )
966 x264_mb_analysis_t a;
967 x264_frame_t *frames[X264_LOOKAHEAD_MAX+3] = { NULL, };
968 int num_frames, orig_num_frames, keyint_limit, idr_frame_type, i, j;
969 int i_mb_count = NUM_MBS;
970 int cost1p0, cost2p0, cost1b1, cost2p1;
971 int i_max_search = X264_MIN( h->lookahead->next.i_size, X264_LOOKAHEAD_MAX );
972 if( h->param.b_deterministic )
973 i_max_search = X264_MIN( i_max_search, h->lookahead->i_slicetype_length + !keyframe );
975 assert( h->frames.b_have_lowres );
977 if( !h->lookahead->last_nonb )
979 frames[0] = h->lookahead->last_nonb;
980 for( j = 0; j < i_max_search && h->lookahead->next.list[j]->i_type == X264_TYPE_AUTO; j++ )
981 frames[j+1] = h->lookahead->next.list[j];
986 keyint_limit = h->param.i_keyint_max - frames[0]->i_frame + h->lookahead->i_last_idr - 1;
987 orig_num_frames = num_frames = X264_MIN( j, keyint_limit );
989 x264_lowres_context_init( h, &a );
990 idr_frame_type = frames[1]->i_frame - h->lookahead->i_last_idr >= h->param.i_keyint_min ? X264_TYPE_IDR : X264_TYPE_I;
992 /* This is important psy-wise: if we have a non-scenecut keyframe,
993 * there will be significant visual artifacts if the frames just before
994 * go down in quality due to being referenced less, despite it being
995 * more RD-optimal. */
996 if( (h->param.analyse.b_psy && h->param.rc.b_mb_tree) || h->param.rc.i_vbv_buffer_size )
998 else if( num_frames == 1 )
1000 frames[1]->i_type = X264_TYPE_P;
1001 if( h->param.i_scenecut_threshold && scenecut( h, &a, frames, 0, 1, 1, orig_num_frames ) )
1002 frames[1]->i_type = idr_frame_type;
1005 else if( num_frames == 0 )
1007 frames[1]->i_type = idr_frame_type;
1011 int num_bframes = 0;
1012 int max_bframes = X264_MIN(num_frames-1, h->param.i_bframe);
1013 int num_analysed_frames = num_frames;
1015 if( h->param.i_scenecut_threshold && scenecut( h, &a, frames, 0, 1, 1, orig_num_frames ) )
1017 frames[1]->i_type = idr_frame_type;
1021 if( h->param.i_bframe )
1023 if( h->param.i_bframe_adaptive == X264_B_ADAPT_TRELLIS )
1025 char best_paths[X264_BFRAME_MAX+1][X264_LOOKAHEAD_MAX] = {"","P"};
1028 /* Perform the frametype analysis. */
1029 for( n = 2; n < num_frames; n++ )
1030 x264_slicetype_path( h, &a, frames, n, max_bframes, best_paths );
1031 if( num_frames > 1 )
1033 int best_path_index = (num_frames-1) % (X264_BFRAME_MAX+1);
1034 num_bframes = strspn( best_paths[best_path_index], "B" );
1035 /* Load the results of the analysis into the frame types. */
1036 for( j = 1; j < num_frames; j++ )
1037 frames[j]->i_type = best_paths[best_path_index][j-1] == 'B' ? X264_TYPE_B : X264_TYPE_P;
1039 frames[num_frames]->i_type = X264_TYPE_P;
1041 else if( h->param.i_bframe_adaptive == X264_B_ADAPT_FAST )
1043 for( i = 0; i <= num_frames-2; )
1045 cost2p1 = x264_slicetype_frame_cost( h, &a, frames, i+0, i+2, i+2, 1 );
1046 if( frames[i+2]->i_intra_mbs[2] > i_mb_count / 2 )
1048 frames[i+1]->i_type = X264_TYPE_P;
1049 frames[i+2]->i_type = X264_TYPE_P;
1054 cost1b1 = x264_slicetype_frame_cost( h, &a, frames, i+0, i+2, i+1, 0 );
1055 cost1p0 = x264_slicetype_frame_cost( h, &a, frames, i+0, i+1, i+1, 0 );
1056 cost2p0 = x264_slicetype_frame_cost( h, &a, frames, i+1, i+2, i+2, 0 );
1058 if( cost1p0 + cost2p0 < cost1b1 + cost2p1 )
1060 frames[i+1]->i_type = X264_TYPE_P;
1065 // arbitrary and untuned
1066 #define INTER_THRESH 300
1067 #define P_SENS_BIAS (50 - h->param.i_bframe_bias)
1068 frames[i+1]->i_type = X264_TYPE_B;
1070 for( j = i+2; j <= X264_MIN( i+h->param.i_bframe, num_frames-1 ); j++ )
1072 int pthresh = X264_MAX(INTER_THRESH - P_SENS_BIAS * (j-i-1), INTER_THRESH/10);
1073 int pcost = x264_slicetype_frame_cost( h, &a, frames, i+0, j+1, j+1, 1 );
1074 if( pcost > pthresh*i_mb_count || frames[j+1]->i_intra_mbs[j-i+1] > i_mb_count/3 )
1076 frames[j]->i_type = X264_TYPE_B;
1078 frames[j]->i_type = X264_TYPE_P;
1081 frames[num_frames]->i_type = X264_TYPE_P;
1083 while( num_bframes < num_frames && frames[num_bframes+1]->i_type == X264_TYPE_B )
1088 num_bframes = X264_MIN(num_frames-1, h->param.i_bframe);
1089 for( j = 1; j < num_frames; j++ )
1090 frames[j]->i_type = (j%(num_bframes+1)) ? X264_TYPE_B : X264_TYPE_P;
1091 frames[num_frames]->i_type = X264_TYPE_P;
1094 /* Check scenecut on the first minigop. */
1095 for( j = 1; j < num_bframes+1; j++ )
1096 if( h->param.i_scenecut_threshold && scenecut( h, &a, frames, j, j+1, 0, orig_num_frames ) )
1098 frames[j]->i_type = X264_TYPE_P;
1099 num_analysed_frames = j;
1103 reset_start = keyframe ? 1 : X264_MIN( num_bframes+2, num_analysed_frames+1 );
1107 for( j = 1; j <= num_frames; j++ )
1108 frames[j]->i_type = X264_TYPE_P;
1109 reset_start = !keyframe + 1;
1113 /* Perform the actual macroblock tree analysis.
1114 * Don't go farther than the maximum keyframe interval; this helps in short GOPs. */
1115 if( h->param.rc.b_mb_tree )
1116 x264_macroblock_tree( h, &a, frames, X264_MIN(num_frames, h->param.i_keyint_max), keyframe );
1118 /* Enforce keyframe limit. */
1119 for( j = 0; j < num_frames; j++ )
1121 if( ((j-keyint_limit) % h->param.i_keyint_max) == 0 )
1123 if( j && h->param.i_keyint_max > 1 )
1124 frames[j]->i_type = X264_TYPE_P;
1125 frames[j+1]->i_type = X264_TYPE_IDR;
1126 reset_start = X264_MIN( reset_start, j+2 );
1130 if( h->param.rc.i_vbv_buffer_size )
1131 x264_vbv_lookahead( h, &a, frames, num_frames, keyframe );
1133 /* Restore frametypes for all frames that haven't actually been decided yet. */
1134 for( j = reset_start; j <= num_frames; j++ )
1135 frames[j]->i_type = X264_TYPE_AUTO;
1138 void x264_slicetype_decide( x264_t *h )
1140 x264_frame_t *frames[X264_BFRAME_MAX+2];
1146 if( !h->lookahead->next.i_size )
1149 if( h->param.rc.b_stat_read )
1151 /* Use the frame types from the first pass */
1152 for( i = 0; i < h->lookahead->next.i_size; i++ )
1153 h->lookahead->next.list[i]->i_type =
1154 x264_ratecontrol_slice_type( h, h->lookahead->next.list[i]->i_frame );
1156 else if( (h->param.i_bframe && h->param.i_bframe_adaptive)
1157 || h->param.i_scenecut_threshold
1158 || h->param.rc.b_mb_tree
1159 || (h->param.rc.i_vbv_buffer_size && h->param.rc.i_lookahead) )
1160 x264_slicetype_analyse( h, 0 );
1162 for( bframes = 0, brefs = 0;; bframes++ )
1164 frm = h->lookahead->next.list[bframes];
1165 if( frm->i_type == X264_TYPE_BREF && h->param.i_bframe_pyramid < X264_B_PYRAMID_NORMAL &&
1166 brefs == h->param.i_bframe_pyramid )
1168 frm->i_type = X264_TYPE_B;
1169 x264_log( h, X264_LOG_WARNING, "B-ref at frame %d incompatible with B-pyramid %s \n",
1170 frm->i_frame, x264_b_pyramid_names[h->param.i_bframe_pyramid] );
1172 /* pyramid with multiple B-refs needs a big enough dpb that the preceding P-frame stays available.
1173 smaller dpb could be supported by smart enough use of mmco, but it's easier just to forbid it. */
1174 else if( frm->i_type == X264_TYPE_BREF && h->param.i_bframe_pyramid == X264_B_PYRAMID_NORMAL &&
1175 brefs && h->param.i_frame_reference <= (brefs+3) )
1177 frm->i_type = X264_TYPE_B;
1178 x264_log( h, X264_LOG_WARNING, "B-ref at frame %d incompatible with B-pyramid %s and %d reference frames\n",
1179 frm->i_frame, x264_b_pyramid_names[h->param.i_bframe_pyramid], h->param.i_frame_reference );
1182 /* Limit GOP size */
1183 if( frm->i_frame - h->lookahead->i_last_idr >= h->param.i_keyint_max )
1185 if( frm->i_type == X264_TYPE_AUTO )
1186 frm->i_type = X264_TYPE_IDR;
1187 if( frm->i_type != X264_TYPE_IDR )
1188 x264_log( h, X264_LOG_WARNING, "specified frame type (%d) is not compatible with keyframe interval\n", frm->i_type );
1190 if( frm->i_type == X264_TYPE_IDR )
1193 h->lookahead->i_last_idr = frm->i_frame;
1197 h->lookahead->next.list[bframes]->i_type = X264_TYPE_P;
1201 if( bframes == h->param.i_bframe ||
1202 !h->lookahead->next.list[bframes+1] )
1204 if( IS_X264_TYPE_B( frm->i_type ) )
1205 x264_log( h, X264_LOG_WARNING, "specified frame type is not compatible with max B-frames\n" );
1206 if( frm->i_type == X264_TYPE_AUTO
1207 || IS_X264_TYPE_B( frm->i_type ) )
1208 frm->i_type = X264_TYPE_P;
1211 if( frm->i_type == X264_TYPE_BREF )
1214 if( frm->i_type == X264_TYPE_AUTO )
1215 frm->i_type = X264_TYPE_B;
1217 else if( !IS_X264_TYPE_B( frm->i_type ) ) break;
1221 h->lookahead->next.list[bframes-1]->b_last_minigop_bframe = 1;
1222 h->lookahead->next.list[bframes]->i_bframes = bframes;
1224 /* insert a bref into the sequence */
1225 if( h->param.i_bframe_pyramid && bframes > 1 && !brefs )
1227 h->lookahead->next.list[bframes/2]->i_type = X264_TYPE_BREF;
1231 /* calculate the frame costs ahead of time for x264_rc_analyse_slice while we still have lowres */
1232 if( h->param.rc.i_rc_method != X264_RC_CQP )
1234 x264_mb_analysis_t a;
1236 p1 = b = bframes + 1;
1238 x264_lowres_context_init( h, &a );
1240 frames[0] = h->lookahead->last_nonb;
1241 memcpy( &frames[1], h->lookahead->next.list, (bframes+1) * sizeof(x264_frame_t*) );
1242 if( IS_X264_TYPE_I( h->lookahead->next.list[bframes]->i_type ) )
1247 x264_slicetype_frame_cost( h, &a, frames, p0, p1, b, 0 );
1249 if( (p0 != p1 || bframes) && h->param.rc.i_vbv_buffer_size )
1251 /* We need the intra costs for row SATDs. */
1252 x264_slicetype_frame_cost( h, &a, frames, b, b, b, 0 );
1254 /* We need B-frame costs for row SATDs. */
1256 for( b = 1; b <= bframes; b++ )
1258 if( frames[b]->i_type == X264_TYPE_B )
1259 for( p1 = b; frames[p1]->i_type == X264_TYPE_B; )
1263 x264_slicetype_frame_cost( h, &a, frames, p0, p1, b, 0 );
1264 if( frames[b]->i_type == X264_TYPE_BREF )
1270 /* Analyse for weighted P frames */
1271 if( !h->param.rc.b_stat_read && h->lookahead->next.list[bframes]->i_type == X264_TYPE_P
1272 && h->param.analyse.i_weighted_pred == X264_WEIGHTP_SMART )
1273 x264_weights_analyse( h, h->lookahead->next.list[bframes], h->lookahead->last_nonb, 0 );
1275 /* shift sequence to coded order.
1276 use a small temporary list to avoid shifting the entire next buffer around */
1277 int i_dts = h->lookahead->next.list[0]->i_frame;
1280 int index[] = { brefs+1, 1 };
1281 for( i = 0; i < bframes; i++ )
1282 frames[ index[h->lookahead->next.list[i]->i_type == X264_TYPE_BREF]++ ] = h->lookahead->next.list[i];
1283 frames[0] = h->lookahead->next.list[bframes];
1284 memcpy( h->lookahead->next.list, frames, (bframes+1) * sizeof(x264_frame_t*) );
1286 for( i = 0; i <= bframes; i++ )
1287 h->lookahead->next.list[i]->i_dts = i_dts++;
1290 int x264_rc_analyse_slice( x264_t *h )
1295 if( IS_X264_TYPE_I(h->fenc->i_type) )
1297 else if( h->fenc->i_type == X264_TYPE_P )
1298 p1 = b = h->fenc->i_bframes + 1;
1301 p1 = (h->fref1[0]->i_poc - h->fref0[0]->i_poc)/2;
1302 b = (h->fenc->i_poc - h->fref0[0]->i_poc)/2;
1304 /* We don't need to assign p0/p1 since we are not performing any real analysis here. */
1305 x264_frame_t **frames = &h->fenc - b;
1307 /* cost should have been already calculated by x264_slicetype_decide */
1308 cost = frames[b]->i_cost_est[b-p0][p1-b];
1309 assert( cost >= 0 );
1311 if( h->param.rc.b_mb_tree && !h->param.rc.b_stat_read )
1313 cost = x264_slicetype_frame_cost_recalculate( h, frames, p0, p1, b );
1314 if( b && h->param.rc.i_vbv_buffer_size )
1315 x264_slicetype_frame_cost_recalculate( h, frames, b, b, b );
1317 /* In AQ, use the weighted score instead. */
1318 else if( h->param.rc.i_aq_mode )
1319 cost = frames[b]->i_cost_est_aq[b-p0][p1-b];
1321 h->fenc->i_row_satd = h->fenc->i_row_satds[b-p0][p1-b];
1322 h->fdec->i_row_satd = h->fdec->i_row_satds[b-p0][p1-b];
1323 h->fdec->i_satd = cost;
1324 memcpy( h->fdec->i_row_satd, h->fenc->i_row_satd, h->sps->i_mb_height * sizeof(int) );
1325 if( !IS_X264_TYPE_I(h->fenc->i_type) )
1326 memcpy( h->fdec->i_row_satds[0][0], h->fenc->i_row_satds[0][0], h->sps->i_mb_height * sizeof(int) );