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 h->mb.i_me_method = X264_MIN( X264_ME_HEX, h->param.analyse.i_me_method ); // maybe dia?
42 h->mb.i_subpel_refine = 4; // 3 should be enough, but not tweaking for speed now
43 h->mb.b_chroma_me = 0;
46 /* makes a non-h264 weight (i.e. fix7), into an h264 weight */
47 static void get_h264_weight( unsigned int weight_nonh264, int offset, x264_weight_t *w )
51 w->i_scale = weight_nonh264;
52 while( w->i_denom > 0 && (w->i_scale > 127 || !(w->i_scale & 1)) )
57 w->i_scale = X264_MIN( w->i_scale, 127 );
59 /* due to a GCC bug on some platforms (win32), flat[16] may not actually be aligned. */
60 ALIGNED_16( static uint8_t flat[17] ) = {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1};
62 static NOINLINE void weights_plane_analyse( x264_t *h, uint8_t *plane, int width, int height, int stride, unsigned int *sum, uint64_t *var )
68 for( y = 0; y < height>>4; y++, p += stride*16 )
69 for( x = 0; x < width; x+=16 )
71 sad += h->pixf.sad_aligned[PIXEL_16x16]( p + x, stride, flat, 0 );
72 ssd += h->pixf.ssd[PIXEL_16x16]( p + x, stride, flat, 0 );
76 *var = ssd - (uint64_t) sad * sad / (width * height);
80 #define LOAD_HPELS_LUMA(dst, src) \
82 (dst)[0] = &(src)[0][i_pel_offset]; \
83 (dst)[1] = &(src)[1][i_pel_offset]; \
84 (dst)[2] = &(src)[2][i_pel_offset]; \
85 (dst)[3] = &(src)[3][i_pel_offset]; \
88 static NOINLINE uint8_t *x264_weight_cost_init_luma( x264_t *h, x264_frame_t *fenc, x264_frame_t *ref, uint8_t *dest )
90 int ref0_distance = fenc->i_frame - ref->i_frame - 1;
91 /* Note: this will never run during lookahead as weights_analyse is only called if no
92 * motion search has been done. */
93 if( fenc->lowres_mvs[0][ref0_distance][0][0] != 0x7FFF )
96 int i_stride = fenc->i_stride_lowres;
97 int i_lines = fenc->i_lines_lowres;
98 int i_width = fenc->i_width_lowres;
101 int i_pel_offset = 0;
103 for( y = 0; y < i_lines; y += 8, i_pel_offset = y*i_stride )
104 for( x = 0; x < i_width; x += 8, i_mb_xy++, i_pel_offset += 8 )
106 uint8_t *pix = &dest[ i_pel_offset ];
107 int mvx = fenc->lowres_mvs[0][ref0_distance][i_mb_xy][0];
108 int mvy = fenc->lowres_mvs[0][ref0_distance][i_mb_xy][1];
109 LOAD_HPELS_LUMA( src, ref->lowres );
110 h->mc.mc_luma( pix, i_stride, src, i_stride,
111 mvx, mvy, 8, 8, weight_none );
117 return ref->lowres[0];
119 #undef LOAD_HPELS_LUMA
121 static NOINLINE unsigned int x264_weight_cost( x264_t *h, x264_frame_t *fenc, uint8_t *src, x264_weight_t *w )
124 unsigned int cost = 0;
125 int i_stride = fenc->i_stride_lowres;
126 int i_lines = fenc->i_lines_lowres;
127 int i_width = fenc->i_width_lowres;
128 uint8_t *fenc_plane = fenc->lowres[0];
129 ALIGNED_ARRAY_16( uint8_t, buf, [8*8] );
134 for( y = 0; y < i_lines; y += 8, pixoff = y*i_stride )
135 for( x = 0; x < i_width; x += 8, i_mb++, pixoff += 8)
137 w->weightfn[8>>2]( buf, 8, &src[pixoff], i_stride, w, 8 );
138 cost += X264_MIN( h->pixf.mbcmp[PIXEL_8x8]( buf, 8, &fenc_plane[pixoff], i_stride ), fenc->i_intra_cost[i_mb] );
141 for( y = 0; y < i_lines; y += 8, pixoff = y*i_stride )
142 for( x = 0; x < i_width; x += 8, i_mb++, pixoff += 8 )
143 cost += X264_MIN( h->pixf.mbcmp[PIXEL_8x8]( &src[pixoff], i_stride, &fenc_plane[pixoff], i_stride ), fenc->i_intra_cost[i_mb] );
148 if( h->param.i_slice_count )
149 numslices = h->param.i_slice_count;
150 else if( h->param.i_slice_max_mbs )
151 numslices = (h->sps->i_mb_width * h->sps->i_mb_height + h->param.i_slice_max_mbs-1) / h->param.i_slice_max_mbs;
154 // FIXME still need to calculate for --slice-max-size
155 // 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.
156 // Since using lowres frames, assume lambda = 1.
157 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 ) ) );
163 void x264_weights_analyse( x264_t *h, x264_frame_t *fenc, x264_frame_t *ref, int b_lookahead )
165 unsigned int fenc_sum, ref_sum;
166 float fenc_mean, ref_mean;
167 uint64_t fenc_var, ref_var;
168 int i_off, offset_search;
169 int minoff, minscale, mindenom;
170 unsigned int minscore, origscore;
171 int i_delta_index = fenc->i_frame - ref->i_frame - 1;
172 /* epsilon is chosen to require at least a numerator of 127 (with denominator = 128) */
173 const float epsilon = 1.0/128.0;
177 x264_weight_t *weights = fenc->weight[0];
179 weights_plane_analyse( h, fenc->plane[0], fenc->i_width[0], fenc->i_lines[0], fenc->i_stride[0], &fenc_sum, &fenc_var );
180 weights_plane_analyse( h, ref->plane[0], ref->i_width[0], ref->i_lines[0], ref->i_stride[0], &ref_sum, &ref_var );
181 fenc_var = round( sqrt( fenc_var ) );
182 ref_var = round( sqrt( ref_var ) );
183 fenc_mean = (float)fenc_sum / (fenc->i_lines[0] * fenc->i_width[0]);
184 ref_mean = (float)ref_sum / (fenc->i_lines[0] * fenc->i_width[0]);
187 if( fabs( ref_mean - fenc_mean ) < 0.5 && fabsf( 1 - (float)fenc_var / ref_var ) < epsilon )
190 guess_scale = ref_var ? (float)fenc_var/ref_var : 0;
191 get_h264_weight( round( guess_scale * 128 ), 0, &weights[0] );
194 mindenom = weights[0].i_denom;
195 minscale = weights[0].i_scale;
197 offset_search = x264_clip3( floor( fenc_mean - ref_mean * minscale / (1 << mindenom) + 0.5f*b_lookahead ), -128, 126 );
199 if( !fenc->b_intra_calculated )
201 x264_mb_analysis_t a;
202 x264_lowres_context_init( h, &a );
203 x264_slicetype_frame_cost( h, &a, &fenc, 0, 0, 0, 0 );
205 uint8_t *mcbuf = x264_weight_cost_init_luma( h, fenc, ref, h->mb.p_weight_buf[0] );
206 origscore = minscore = x264_weight_cost( h, fenc, mcbuf, 0 );
211 // This gives a slight improvement due to rounding errors but only tests
212 // one offset on lookahead.
213 // TODO: currently searches only offset +1. try other offsets/multipliers/combinations thereof?
214 for( i_off = offset_search; i_off <= offset_search+!b_lookahead; i_off++ )
216 SET_WEIGHT( weights[0], 1, minscale, mindenom, i_off );
217 unsigned int s = x264_weight_cost( h, fenc, mcbuf, &weights[0] );
218 COPY3_IF_LT( minscore, s, minoff, i_off, found, 1 );
222 /* FIXME: More analysis can be done here on SAD vs. SATD termination. */
223 /* 0.2% termination derived experimentally to avoid weird weights in frames that are mostly intra. */
224 if( !found || (minscale == 1<<mindenom && minoff == 0) || (float)minscore / origscore > 0.998 )
226 SET_WEIGHT( weights[0], 0, 1, 0, 0 );
230 SET_WEIGHT( weights[0], 1, minscale, mindenom, minoff );
232 if( h->param.analyse.i_weighted_pred == X264_WEIGHTP_FAKE && weights[0].weightfn )
233 fenc->f_weighted_cost_delta[i_delta_index] = (float)minscore / origscore;
235 if( weights[0].weightfn && b_lookahead )
237 //scale lowres in lookahead for slicetype_frame_cost
238 int i_padv = PADV<<h->param.b_interlaced;
239 uint8_t *src = ref->buffer_lowres[0];
240 uint8_t *dst = h->mb.p_weight_buf[0];
241 int width = ref->i_width_lowres + PADH*2;
242 int height = ref->i_lines_lowres + i_padv*2;
243 x264_weight_scale_plane( h, dst, ref->i_stride_lowres, src, ref->i_stride_lowres,
244 width, height, &weights[0] );
245 fenc->weighted[0] = h->mb.p_weight_buf[0] + PADH + ref->i_stride_lowres * i_padv;
249 static int x264_slicetype_mb_cost( x264_t *h, x264_mb_analysis_t *a,
250 x264_frame_t **frames, int p0, int p1, int b,
251 int dist_scale_factor, int do_search[2], const x264_weight_t *w )
253 x264_frame_t *fref0 = frames[p0];
254 x264_frame_t *fref1 = frames[p1];
255 x264_frame_t *fenc = frames[b];
256 const int b_bidir = (b < p1);
257 const int i_mb_x = h->mb.i_mb_x;
258 const int i_mb_y = h->mb.i_mb_y;
259 const int i_mb_stride = h->sps->i_mb_width;
260 const int i_mb_xy = i_mb_x + i_mb_y * i_mb_stride;
261 const int i_stride = fenc->i_stride_lowres;
262 const int i_pel_offset = 8 * (i_mb_x + i_mb_y * i_stride);
263 const int i_bipred_weight = h->param.analyse.b_weighted_bipred ? 64 - (dist_scale_factor>>2) : 32;
264 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] };
265 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] };
267 ALIGNED_8( uint8_t pix1[9*FDEC_STRIDE] );
268 uint8_t *pix2 = pix1+8;
270 int i_bcost = COST_MAX;
274 h->mb.pic.p_fenc[0] = h->mb.pic.fenc_buf;
275 h->mc.copy[PIXEL_8x8]( h->mb.pic.p_fenc[0], FENC_STRIDE, &fenc->lowres[0][i_pel_offset], i_stride, 8 );
278 goto lowres_intra_mb;
280 // no need for h->mb.mv_min[]
281 h->mb.mv_min_fpel[0] = -8*h->mb.i_mb_x - 4;
282 h->mb.mv_max_fpel[0] = 8*( h->sps->i_mb_width - h->mb.i_mb_x - 1 ) + 4;
283 h->mb.mv_min_spel[0] = 4*( h->mb.mv_min_fpel[0] - 8 );
284 h->mb.mv_max_spel[0] = 4*( h->mb.mv_max_fpel[0] + 8 );
285 if( h->mb.i_mb_x >= h->sps->i_mb_width - 2 )
287 h->mb.mv_min_fpel[1] = -8*h->mb.i_mb_y - 4;
288 h->mb.mv_max_fpel[1] = 8*( h->sps->i_mb_height - h->mb.i_mb_y - 1 ) + 4;
289 h->mb.mv_min_spel[1] = 4*( h->mb.mv_min_fpel[1] - 8 );
290 h->mb.mv_max_spel[1] = 4*( h->mb.mv_max_fpel[1] + 8 );
293 #define LOAD_HPELS_LUMA(dst, src) \
295 (dst)[0] = &(src)[0][i_pel_offset]; \
296 (dst)[1] = &(src)[1][i_pel_offset]; \
297 (dst)[2] = &(src)[2][i_pel_offset]; \
298 (dst)[3] = &(src)[3][i_pel_offset]; \
300 #define LOAD_WPELS_LUMA(dst,src) \
301 (dst) = &(src)[i_pel_offset];
303 #define CLIP_MV( mv ) \
305 mv[0] = x264_clip3( mv[0], h->mb.mv_min_spel[0], h->mb.mv_max_spel[0] ); \
306 mv[1] = x264_clip3( mv[1], h->mb.mv_min_spel[1], h->mb.mv_max_spel[1] ); \
308 #define TRY_BIDIR( mv0, mv1, penalty ) \
310 int stride1 = 16, stride2 = 16; \
311 uint8_t *src1, *src2; \
313 src1 = h->mc.get_ref( pix1, &stride1, m[0].p_fref, m[0].i_stride[0], \
314 (mv0)[0], (mv0)[1], 8, 8, w ); \
315 src2 = h->mc.get_ref( pix2, &stride2, m[1].p_fref, m[1].i_stride[0], \
316 (mv1)[0], (mv1)[1], 8, 8, w ); \
317 h->mc.avg[PIXEL_8x8]( pix1, 16, src1, stride1, src2, stride2, i_bipred_weight ); \
318 i_cost = penalty + h->pixf.mbcmp[PIXEL_8x8]( \
319 m[0].p_fenc[0], FENC_STRIDE, pix1, 16 ); \
320 COPY2_IF_LT( i_bcost, i_cost, list_used, 3 ); \
323 m[0].i_pixel = PIXEL_8x8;
324 m[0].p_cost_mv = a->p_cost_mv;
325 m[0].i_stride[0] = i_stride;
326 m[0].p_fenc[0] = h->mb.pic.p_fenc[0];
328 LOAD_HPELS_LUMA( m[0].p_fref, fref0->lowres );
329 m[0].p_fref_w = m[0].p_fref[0];
331 LOAD_WPELS_LUMA( m[0].p_fref_w, fenc->weighted[0] );
335 int16_t *mvr = fref1->lowres_mvs[0][p1-p0-1][i_mb_xy];
338 h->mc.memcpy_aligned( &m[1], &m[0], sizeof(x264_me_t) );
340 m[1].weight = weight_none;
341 LOAD_HPELS_LUMA( m[1].p_fref, fref1->lowres );
342 m[1].p_fref_w = m[1].p_fref[0];
344 dmv[0][0] = ( mvr[0] * dist_scale_factor + 128 ) >> 8;
345 dmv[0][1] = ( mvr[1] * dist_scale_factor + 128 ) >> 8;
346 dmv[1][0] = dmv[0][0] - mvr[0];
347 dmv[1][1] = dmv[0][1] - mvr[1];
351 TRY_BIDIR( dmv[0], dmv[1], 0 );
352 if( dmv[0][0] | dmv[0][1] | dmv[1][0] | dmv[1][1] )
355 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 );
356 i_cost = h->pixf.mbcmp[PIXEL_8x8]( m[0].p_fenc[0], FENC_STRIDE, pix1, 16 );
357 COPY2_IF_LT( i_bcost, i_cost, list_used, 3 );
361 for( l = 0; l < 1 + b_bidir; l++ )
366 int16_t (*fenc_mv)[2] = fenc_mvs[l];
367 ALIGNED_4( int16_t mvc[4][2] );
369 /* Reverse-order MV prediction. */
373 #define MVC(mv) { CP32( mvc[i_mvc], mv ); i_mvc++; }
374 if( i_mb_x < h->sps->i_mb_width - 1 )
376 if( i_mb_y < h->sps->i_mb_height - 1 )
378 MVC(fenc_mv[i_mb_stride]);
380 MVC(fenc_mv[i_mb_stride-1]);
381 if( i_mb_x < h->sps->i_mb_width - 1 )
382 MVC(fenc_mv[i_mb_stride+1]);
385 x264_median_mv( m[l].mvp, mvc[0], mvc[1], mvc[2] );
386 x264_me_search( h, &m[l], mvc, i_mvc );
388 m[l].cost -= 2; // remove mvcost from skip mbs
391 CP32( fenc_mvs[l], m[l].mv );
392 *fenc_costs[l] = m[l].cost;
396 CP32( m[l].mv, fenc_mvs[l] );
397 m[l].cost = *fenc_costs[l];
399 COPY2_IF_LT( i_bcost, m[l].cost, list_used, l+1 );
402 if( b_bidir && ( M32( m[0].mv ) || M32( m[1].mv ) ) )
403 TRY_BIDIR( m[0].mv, m[1].mv, 5 );
405 /* Store to width-2 bitfield. */
406 frames[b]->lowres_inter_types[b-p0][p1-b][i_mb_xy>>2] &= ~(3<<((i_mb_xy&3)*2));
407 frames[b]->lowres_inter_types[b-p0][p1-b][i_mb_xy>>2] |= list_used<<((i_mb_xy&3)*2);
410 /* forbid intra-mbs in B-frames, because it's rare and not worth checking */
411 /* FIXME: Should we still forbid them now that we cache intra scores? */
412 if( !b_bidir || h->param.rc.b_mb_tree )
414 int i_icost, b_intra;
415 if( !fenc->b_intra_calculated )
417 ALIGNED_ARRAY_16( uint8_t, edge,[33] );
418 uint8_t *pix = &pix1[8+FDEC_STRIDE - 1];
419 uint8_t *src = &fenc->lowres[0][i_pel_offset - 1];
420 const int intra_penalty = 5;
423 memcpy( pix-FDEC_STRIDE, src-i_stride, 17 );
425 pix[i*FDEC_STRIDE] = src[i*i_stride];
428 if( h->pixf.intra_mbcmp_x3_8x8c )
430 h->pixf.intra_mbcmp_x3_8x8c( h->mb.pic.p_fenc[0], pix, satds );
431 h->predict_8x8c[I_PRED_CHROMA_P]( pix );
432 satds[I_PRED_CHROMA_P] =
433 h->pixf.mbcmp[PIXEL_8x8]( pix, FDEC_STRIDE, h->mb.pic.p_fenc[0], FENC_STRIDE );
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_MIN4( satds[0], satds[1], satds[2], satds[3] );
445 h->predict_8x8_filter( pix, edge, ALL_NEIGHBORS, ALL_NEIGHBORS );
449 h->predict_8x8[i]( pix, edge );
450 satd = h->pixf.mbcmp[PIXEL_8x8]( pix, FDEC_STRIDE, h->mb.pic.p_fenc[0], FENC_STRIDE );
451 i_icost = X264_MIN( i_icost, satd );
454 i_icost += intra_penalty;
455 fenc->i_intra_cost[i_mb_xy] = i_icost;
458 i_icost = fenc->i_intra_cost[i_mb_xy];
461 b_intra = i_icost < i_bcost;
464 if( (i_mb_x > 0 && i_mb_x < h->sps->i_mb_width - 1
465 && i_mb_y > 0 && i_mb_y < h->sps->i_mb_height - 1)
466 || h->sps->i_mb_width <= 2 || h->sps->i_mb_height <= 2 )
468 fenc->i_intra_mbs[b-p0] += b_intra;
469 fenc->i_cost_est[0][0] += i_icost;
470 if( h->param.rc.i_aq_mode )
471 fenc->i_cost_est_aq[0][0] += (i_icost * fenc->i_inv_qscale_factor[i_mb_xy] + 128) >> 8;
476 fenc->lowres_costs[b-p0][p1-b][i_mb_xy] = i_bcost;
483 (h->sps->i_mb_width > 2 && h->sps->i_mb_height > 2 ?\
484 (h->sps->i_mb_width - 2) * (h->sps->i_mb_height - 2) :\
485 h->sps->i_mb_width * h->sps->i_mb_height)
487 static int x264_slicetype_frame_cost( x264_t *h, x264_mb_analysis_t *a,
488 x264_frame_t **frames, int p0, int p1, int b,
489 int b_intra_penalty )
493 /* Don't use the AQ'd scores for slicetype decision. */
496 const x264_weight_t *w = weight_none;
497 /* Check whether we already evaluated this frame
498 * If we have tried this frame as P, then we have also tried
499 * the preceding frames as B. (is this still true?) */
500 /* Also check that we already calculated the row SATDs for the current frame. */
501 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) )
503 i_score = frames[b]->i_cost_est[b-p0][p1-b];
507 int dist_scale_factor = 128;
508 int *row_satd = frames[b]->i_row_satds[b-p0][p1-b];
510 /* For each list, check to see whether we have lowres motion-searched this reference frame before. */
511 do_search[0] = b != p0 && frames[b]->lowres_mvs[0][b-p0-1][0][0] == 0x7FFF;
512 do_search[1] = b != p1 && frames[b]->lowres_mvs[1][p1-b-1][0][0] == 0x7FFF;
515 if( ( h->param.analyse.i_weighted_pred == X264_WEIGHTP_SMART
516 || h->param.analyse.i_weighted_pred == X264_WEIGHTP_FAKE ) && b == p1 )
518 x264_weights_analyse( h, frames[b], frames[p0], 1 );
519 w = frames[b]->weight[0];
521 frames[b]->lowres_mvs[0][b-p0-1][0][0] = 0;
523 if( do_search[1] ) frames[b]->lowres_mvs[1][p1-b-1][0][0] = 0;
527 frames[b]->i_intra_mbs[b-p0] = 0;
528 frames[b]->i_cost_est[0][0] = 0;
529 frames[b]->i_cost_est_aq[0][0] = 0;
532 dist_scale_factor = ( ((b-p0) << 8) + ((p1-p0) >> 1) ) / (p1-p0);
534 /* Lowres lookahead goes backwards because the MVs are used as predictors in the main encode.
535 * This considerably improves MV prediction overall. */
537 /* the edge mbs seem to reduce the predictive quality of the
538 * whole frame's score, but are needed for a spatial distribution. */
539 if( h->param.rc.b_mb_tree || h->param.rc.i_vbv_buffer_size ||
540 h->sps->i_mb_width <= 2 || h->sps->i_mb_height <= 2 )
542 for( h->mb.i_mb_y = h->sps->i_mb_height - 1; h->mb.i_mb_y >= 0; h->mb.i_mb_y-- )
544 row_satd[ h->mb.i_mb_y ] = 0;
545 for( h->mb.i_mb_x = h->sps->i_mb_width - 1; h->mb.i_mb_x >= 0; h->mb.i_mb_x-- )
547 int i_mb_cost = x264_slicetype_mb_cost( h, a, frames, p0, p1, b, dist_scale_factor, do_search, w );
548 int i_mb_cost_aq = i_mb_cost;
549 if( h->param.rc.i_aq_mode )
550 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;
551 row_satd[ h->mb.i_mb_y ] += i_mb_cost_aq;
552 if( (h->mb.i_mb_y > 0 && h->mb.i_mb_y < h->sps->i_mb_height - 1 &&
553 h->mb.i_mb_x > 0 && h->mb.i_mb_x < h->sps->i_mb_width - 1) ||
554 h->sps->i_mb_width <= 2 || h->sps->i_mb_height <= 2 )
556 /* Don't use AQ-weighted costs for slicetype decision, only for ratecontrol. */
557 i_score += i_mb_cost;
558 i_score_aq += i_mb_cost_aq;
565 for( h->mb.i_mb_y = h->sps->i_mb_height - 2; h->mb.i_mb_y > 0; h->mb.i_mb_y-- )
566 for( h->mb.i_mb_x = h->sps->i_mb_width - 2; h->mb.i_mb_x > 0; h->mb.i_mb_x-- )
568 int i_mb_cost = x264_slicetype_mb_cost( h, a, frames, p0, p1, b, dist_scale_factor, do_search, w );
569 int i_mb_cost_aq = i_mb_cost;
570 if( h->param.rc.i_aq_mode )
571 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;
572 i_score += i_mb_cost;
573 i_score_aq += i_mb_cost_aq;
578 i_score = (uint64_t)i_score * 100 / (120 + h->param.i_bframe_bias);
580 frames[b]->b_intra_calculated = 1;
582 frames[b]->i_cost_est[b-p0][p1-b] = i_score;
583 frames[b]->i_cost_est_aq[b-p0][p1-b] = i_score_aq;
587 if( b_intra_penalty )
589 // arbitrary penalty for I-blocks after B-frames
591 i_score += i_score * frames[b]->i_intra_mbs[b-p0] / (nmb * 8);
596 /* If MB-tree changes the quantizers, we need to recalculate the frame cost without
597 * re-running lookahead. */
598 static int x264_slicetype_frame_cost_recalculate( x264_t *h, x264_frame_t **frames, int p0, int p1, int b )
601 int *row_satd = frames[b]->i_row_satds[b-p0][p1-b];
602 float *qp_offset = IS_X264_TYPE_B(frames[b]->i_type) ? frames[b]->f_qp_offset_aq : frames[b]->f_qp_offset;
604 for( h->mb.i_mb_y = h->sps->i_mb_height - 1; h->mb.i_mb_y >= 0; h->mb.i_mb_y-- )
606 row_satd[ h->mb.i_mb_y ] = 0;
607 for( h->mb.i_mb_x = h->sps->i_mb_width - 1; h->mb.i_mb_x >= 0; h->mb.i_mb_x-- )
609 int i_mb_xy = h->mb.i_mb_x + h->mb.i_mb_y*h->mb.i_mb_stride;
610 int i_mb_cost = frames[b]->lowres_costs[b-p0][p1-b][i_mb_xy];
611 float qp_adj = qp_offset[i_mb_xy];
612 i_mb_cost = (i_mb_cost * x264_exp2fix8(qp_adj) + 128) >> 8;
613 row_satd[ h->mb.i_mb_y ] += i_mb_cost;
614 if( (h->mb.i_mb_y > 0 && h->mb.i_mb_y < h->sps->i_mb_height - 1 &&
615 h->mb.i_mb_x > 0 && h->mb.i_mb_x < h->sps->i_mb_width - 1) ||
616 h->sps->i_mb_width <= 2 || h->sps->i_mb_height <= 2 )
618 i_score += i_mb_cost;
625 static void x264_macroblock_tree_finish( x264_t *h, x264_frame_t *frame, int ref0_distance )
629 float weightdelta = 0.0;
630 if( ref0_distance && frame->f_weighted_cost_delta[ref0_distance-1] > 0 )
631 weightdelta = (1.0 - frame->f_weighted_cost_delta[ref0_distance-1]);
633 /* Allow the strength to be adjusted via qcompress, since the two
634 * concepts are very similar. */
635 float strength = 5.0f * (1.0f - h->param.rc.f_qcompress);
636 for( mb_index = 0; mb_index < h->mb.i_mb_count; mb_index++ )
638 int intra_cost = (frame->i_intra_cost[mb_index] * frame->i_inv_qscale_factor[mb_index]+128)>>8;
641 int propagate_cost = frame->i_propagate_cost[mb_index];
642 float log2_ratio = x264_log2(intra_cost + propagate_cost) - x264_log2(intra_cost) + weightdelta;
643 frame->f_qp_offset[mb_index] = frame->f_qp_offset_aq[mb_index] - strength * log2_ratio;
648 static void x264_macroblock_tree_propagate( x264_t *h, x264_frame_t **frames, int p0, int p1, int b )
650 uint16_t *ref_costs[2] = {frames[p0]->i_propagate_cost,frames[p1]->i_propagate_cost};
651 int dist_scale_factor = ( ((b-p0) << 8) + ((p1-p0) >> 1) ) / (p1-p0);
652 int i_bipred_weight = h->param.analyse.b_weighted_bipred ? 64 - (dist_scale_factor>>2) : 32;
653 int16_t (*mvs[2])[2] = { frames[b]->lowres_mvs[0][b-p0-1], frames[b]->lowres_mvs[1][p1-b-1] };
654 int bipred_weights[2] = {i_bipred_weight, 64 - i_bipred_weight};
655 int *buf = h->scratch_buffer;
657 for( h->mb.i_mb_y = 0; h->mb.i_mb_y < h->sps->i_mb_height; h->mb.i_mb_y++ )
659 int mb_index = h->mb.i_mb_y*h->mb.i_mb_stride;
660 h->mc.mbtree_propagate_cost( buf, frames[b]->i_propagate_cost+mb_index,
661 frames[b]->i_intra_cost+mb_index, frames[b]->lowres_costs[b-p0][p1-b]+mb_index,
662 frames[b]->i_inv_qscale_factor+mb_index, h->sps->i_mb_width );
663 for( h->mb.i_mb_x = 0; h->mb.i_mb_x < h->sps->i_mb_width; h->mb.i_mb_x++, mb_index++ )
665 int propagate_amount = buf[h->mb.i_mb_x];
666 /* Don't propagate for an intra block. */
667 if( propagate_amount > 0 )
669 /* Access width-2 bitfield. */
670 int lists_used = (frames[b]->lowres_inter_types[b-p0][p1-b][mb_index>>2] >> ((mb_index&3)*2))&3;
672 /* Follow the MVs to the previous frame(s). */
673 for( list = 0; list < 2; list++ )
674 if( (lists_used >> list)&1 )
676 int x = mvs[list][mb_index][0];
677 int y = mvs[list][mb_index][1];
678 int listamount = propagate_amount;
679 int mbx = (x>>5)+h->mb.i_mb_x;
680 int mby = (y>>5)+h->mb.i_mb_y;
681 int idx0 = mbx + mby*h->mb.i_mb_stride;
683 int idx2 = idx0 + h->mb.i_mb_stride;
684 int idx3 = idx0 + h->mb.i_mb_stride + 1;
687 int idx0weight = (32-y)*(32-x);
688 int idx1weight = (32-y)*x;
689 int idx2weight = y*(32-x);
690 int idx3weight = y*x;
692 /* Apply bipred weighting. */
693 if( lists_used == 3 )
694 listamount = (listamount * bipred_weights[list] + 32) >> 6;
696 #define CLIP_ADD(s,x) (s) = X264_MIN((s)+(x),(1<<16)-1)
698 /* We could just clip the MVs, but pixels that lie outside the frame probably shouldn't
700 if( mbx < h->sps->i_mb_width-1 && mby < h->sps->i_mb_height-1 && mbx >= 0 && mby >= 0 )
702 CLIP_ADD( ref_costs[list][idx0], (listamount*idx0weight+512)>>10 );
703 CLIP_ADD( ref_costs[list][idx1], (listamount*idx1weight+512)>>10 );
704 CLIP_ADD( ref_costs[list][idx2], (listamount*idx2weight+512)>>10 );
705 CLIP_ADD( ref_costs[list][idx3], (listamount*idx3weight+512)>>10 );
707 else /* Check offsets individually */
709 if( mbx < h->sps->i_mb_width && mby < h->sps->i_mb_height && mbx >= 0 && mby >= 0 )
710 CLIP_ADD( ref_costs[list][idx0], (listamount*idx0weight+512)>>10 );
711 if( mbx+1 < h->sps->i_mb_width && mby < h->sps->i_mb_height && mbx+1 >= 0 && mby >= 0 )
712 CLIP_ADD( ref_costs[list][idx1], (listamount*idx1weight+512)>>10 );
713 if( mbx < h->sps->i_mb_width && mby+1 < h->sps->i_mb_height && mbx >= 0 && mby+1 >= 0 )
714 CLIP_ADD( ref_costs[list][idx2], (listamount*idx2weight+512)>>10 );
715 if( mbx+1 < h->sps->i_mb_width && mby+1 < h->sps->i_mb_height && mbx+1 >= 0 && mby+1 >= 0 )
716 CLIP_ADD( ref_costs[list][idx3], (listamount*idx3weight+512)>>10 );
723 if( h->param.rc.i_vbv_buffer_size && b == p1 )
724 x264_macroblock_tree_finish( h, frames[b], b-p0 );
727 static void x264_macroblock_tree( x264_t *h, x264_mb_analysis_t *a, x264_frame_t **frames, int num_frames, int b_intra )
729 int i, idx = !b_intra;
730 int last_nonb, cur_nonb = 1;
732 x264_slicetype_frame_cost( h, a, frames, 0, 0, 0, 0 );
735 while( i > 0 && frames[i]->i_type == X264_TYPE_B )
739 if( last_nonb < idx )
742 memset( frames[last_nonb]->i_propagate_cost, 0, h->mb.i_mb_count * sizeof(uint16_t) );
746 while( frames[cur_nonb]->i_type == X264_TYPE_B && cur_nonb > 0 )
750 x264_slicetype_frame_cost( h, a, frames, cur_nonb, last_nonb, last_nonb, 0 );
751 memset( frames[cur_nonb]->i_propagate_cost, 0, h->mb.i_mb_count * sizeof(uint16_t) );
752 while( i > cur_nonb )
754 x264_slicetype_frame_cost( h, a, frames, cur_nonb, last_nonb, i, 0 );
755 memset( frames[i]->i_propagate_cost, 0, h->mb.i_mb_count * sizeof(uint16_t) );
756 x264_macroblock_tree_propagate( h, frames, cur_nonb, last_nonb, i );
759 x264_macroblock_tree_propagate( h, frames, cur_nonb, last_nonb, last_nonb );
760 last_nonb = cur_nonb;
763 x264_macroblock_tree_finish( h, frames[last_nonb], last_nonb );
766 static int x264_vbv_frame_cost( x264_t *h, x264_mb_analysis_t *a, x264_frame_t **frames, int p0, int p1, int b )
768 int cost = x264_slicetype_frame_cost( h, a, frames, p0, p1, b, 0 );
769 if( h->param.rc.i_aq_mode )
771 if( h->param.rc.b_mb_tree )
772 return x264_slicetype_frame_cost_recalculate( h, frames, p0, p1, b );
774 return frames[b]->i_cost_est_aq[b-p0][p1-b];
779 static void x264_vbv_lookahead( x264_t *h, x264_mb_analysis_t *a, x264_frame_t **frames, int num_frames, int keyframe )
781 int last_nonb = 0, cur_nonb = 1, next_nonb, i, idx = 0;
782 while( cur_nonb < num_frames && frames[cur_nonb]->i_type == X264_TYPE_B )
784 next_nonb = keyframe ? last_nonb : cur_nonb;
786 while( cur_nonb <= num_frames )
788 /* P/I cost: This shouldn't include the cost of next_nonb */
789 if( next_nonb != cur_nonb )
791 int p0 = IS_X264_TYPE_I( frames[cur_nonb]->i_type ) ? cur_nonb : last_nonb;
792 frames[next_nonb]->i_planned_satd[idx] = x264_vbv_frame_cost( h, a, frames, p0, cur_nonb, cur_nonb );
793 frames[next_nonb]->i_planned_type[idx] = frames[cur_nonb]->i_type;
796 /* Handle the B-frames: coded order */
797 for( i = last_nonb+1; i < cur_nonb; i++, idx++ )
799 frames[next_nonb]->i_planned_satd[idx] = x264_vbv_frame_cost( h, a, frames, last_nonb, cur_nonb, i );
800 frames[next_nonb]->i_planned_type[idx] = X264_TYPE_B;
802 last_nonb = cur_nonb;
804 while( cur_nonb <= num_frames && frames[cur_nonb]->i_type == X264_TYPE_B )
807 frames[next_nonb]->i_planned_type[idx] = X264_TYPE_AUTO;
810 static int x264_slicetype_path_cost( x264_t *h, x264_mb_analysis_t *a, x264_frame_t **frames, char *path, int threshold )
815 path--; /* Since the 1st path element is really the second frame */
820 /* Find the location of the next P-frame. */
821 while( path[next_p] && path[next_p] != 'P' )
823 /* Return if the path doesn't end on a P-frame. */
824 if( path[next_p] != 'P' )
827 /* Add the cost of the P-frame found above */
828 cost += x264_slicetype_frame_cost( h, a, frames, cur_p, next_p, next_p, 0 );
829 /* Early terminate if the cost we have found is larger than the best path cost so far */
830 if( cost > threshold )
833 for( next_b = loc; next_b < next_p && cost < threshold; next_b++ )
834 cost += x264_slicetype_frame_cost( h, a, frames, cur_p, next_p, next_b, 0 );
842 /* Viterbi/trellis slicetype decision algorithm. */
843 /* Uses strings due to the fact that the speed of the control functions is
844 negligable compared to the cost of running slicetype_frame_cost, and because
845 it makes debugging easier. */
846 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] )
848 char paths[X264_BFRAME_MAX+1][X264_LOOKAHEAD_MAX] = {{0}};
849 int num_paths = X264_MIN( max_bframes+1, length );
851 int best_cost = COST_MAX;
852 int best_path_index = 0;
854 /* Iterate over all currently possible paths */
855 for( path = 0; path < num_paths; path++ )
857 /* Add suffixes to the current path */
858 int len = length - (path + 1);
859 memcpy( paths[path], best_paths[len % (X264_BFRAME_MAX+1)], len );
860 memset( paths[path]+len, 'B', path );
861 strcat( paths[path], "P" );
863 /* Calculate the actual cost of the current path */
864 int cost = x264_slicetype_path_cost( h, a, frames, paths[path], best_cost );
865 if( cost < best_cost )
868 best_path_index = path;
872 /* Store the best path. */
873 memcpy( best_paths[length % (X264_BFRAME_MAX+1)], paths[best_path_index], length );
876 static int scenecut_internal( x264_t *h, x264_mb_analysis_t *a, x264_frame_t **frames, int p0, int p1, int print )
878 x264_frame_t *frame = frames[p1];
879 x264_slicetype_frame_cost( h, a, frames, p0, p1, p1, 0 );
881 int icost = frame->i_cost_est[0][0];
882 int pcost = frame->i_cost_est[p1-p0][0];
884 int i_gop_size = frame->i_frame - h->lookahead->i_last_idr;
885 float f_thresh_max = h->param.i_scenecut_threshold / 100.0;
886 /* magic numbers pulled out of thin air */
887 float f_thresh_min = f_thresh_max * h->param.i_keyint_min
888 / ( h->param.i_keyint_max * 4 );
891 if( h->param.i_keyint_min == h->param.i_keyint_max )
892 f_thresh_min= f_thresh_max;
893 if( i_gop_size < h->param.i_keyint_min / 4 )
894 f_bias = f_thresh_min / 4;
895 else if( i_gop_size <= h->param.i_keyint_min )
896 f_bias = f_thresh_min * i_gop_size / h->param.i_keyint_min;
899 f_bias = f_thresh_min
900 + ( f_thresh_max - f_thresh_min )
901 * ( i_gop_size - h->param.i_keyint_min )
902 / ( h->param.i_keyint_max - h->param.i_keyint_min ) ;
905 res = pcost >= (1.0 - f_bias) * icost;
908 int imb = frame->i_intra_mbs[p1-p0];
909 int pmb = NUM_MBS - imb;
910 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",
912 icost, pcost, 1. - (double)pcost / icost,
913 f_bias, i_gop_size, imb, pmb );
918 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 )
920 int curp0, curp1, i, maxp1 = p0 + 1;
922 /* Only do analysis during a normal scenecut check. */
923 if( real_scenecut && h->param.i_bframe )
925 /* Look ahead to avoid coding short flashes as scenecuts. */
926 if( h->param.i_bframe_adaptive == X264_B_ADAPT_TRELLIS )
927 /* Don't analyse any more frames than the trellis would have covered. */
928 maxp1 += h->param.i_bframe;
931 maxp1 = X264_MIN( maxp1, num_frames );
933 /* Where A and B are scenes: AAAAAABBBAAAAAA
934 * If BBB is shorter than (maxp1-p0), it is detected as a flash
935 * and not considered a scenecut. */
936 for( curp1 = p1; curp1 <= maxp1; curp1++ )
937 if( !scenecut_internal( h, a, frames, p0, curp1, 0 ) )
938 /* Any frame in between p0 and cur_p1 cannot be a real scenecut. */
939 for( i = curp1; i > p0; i-- )
940 frames[i]->b_scenecut = 0;
942 /* Where A-F are scenes: AAAAABBCCDDEEFFFFFF
943 * If each of BB ... EE are shorter than (maxp1-p0), they are
944 * detected as flashes and not considered scenecuts.
945 * Instead, the first F frame becomes a scenecut. */
946 for( curp0 = p0; curp0 < maxp1; curp0++ )
947 if( scenecut_internal( h, a, frames, curp0, maxp1, 0 ) )
948 /* If cur_p0 is the p0 of a scenecut, it cannot be the p1 of a scenecut. */
949 frames[curp0]->b_scenecut = 0;
952 /* Ignore frames that are part of a flash, i.e. cannot be real scenecuts. */
953 if( !frames[p1]->b_scenecut )
955 return scenecut_internal( h, a, frames, p0, p1, real_scenecut );
958 void x264_slicetype_analyse( x264_t *h, int keyframe )
960 x264_mb_analysis_t a;
961 x264_frame_t *frames[X264_LOOKAHEAD_MAX+3] = { NULL, };
962 int num_frames, orig_num_frames, keyint_limit, idr_frame_type, i, j;
963 int i_mb_count = NUM_MBS;
964 int cost1p0, cost2p0, cost1b1, cost2p1;
965 int i_max_search = X264_MIN( h->lookahead->next.i_size, X264_LOOKAHEAD_MAX );
966 if( h->param.b_deterministic )
967 i_max_search = X264_MIN( i_max_search, h->lookahead->i_slicetype_length + !keyframe );
969 assert( h->frames.b_have_lowres );
971 if( !h->lookahead->last_nonb )
973 frames[0] = h->lookahead->last_nonb;
974 for( j = 0; j < i_max_search && h->lookahead->next.list[j]->i_type == X264_TYPE_AUTO; j++ )
975 frames[j+1] = h->lookahead->next.list[j];
980 keyint_limit = h->param.i_keyint_max - frames[0]->i_frame + h->lookahead->i_last_idr - 1;
981 orig_num_frames = num_frames = X264_MIN( j, keyint_limit );
983 x264_lowres_context_init( h, &a );
984 idr_frame_type = frames[1]->i_frame - h->lookahead->i_last_idr >= h->param.i_keyint_min ? X264_TYPE_IDR : X264_TYPE_I;
986 /* This is important psy-wise: if we have a non-scenecut keyframe,
987 * there will be significant visual artifacts if the frames just before
988 * go down in quality due to being referenced less, despite it being
989 * more RD-optimal. */
990 if( (h->param.analyse.b_psy && h->param.rc.b_mb_tree) || h->param.rc.i_vbv_buffer_size )
992 else if( num_frames == 1 )
994 frames[1]->i_type = X264_TYPE_P;
995 if( h->param.i_scenecut_threshold && scenecut( h, &a, frames, 0, 1, 1, orig_num_frames ) )
996 frames[1]->i_type = idr_frame_type;
999 else if( num_frames == 0 )
1001 frames[1]->i_type = idr_frame_type;
1005 int num_bframes = 0;
1006 int max_bframes = X264_MIN(num_frames-1, h->param.i_bframe);
1007 int num_analysed_frames = num_frames;
1009 if( h->param.i_scenecut_threshold && scenecut( h, &a, frames, 0, 1, 1, orig_num_frames ) )
1011 frames[1]->i_type = idr_frame_type;
1015 if( h->param.i_bframe )
1017 if( h->param.i_bframe_adaptive == X264_B_ADAPT_TRELLIS )
1019 char best_paths[X264_BFRAME_MAX+1][X264_LOOKAHEAD_MAX] = {"","P"};
1022 /* Perform the frametype analysis. */
1023 for( n = 2; n < num_frames; n++ )
1024 x264_slicetype_path( h, &a, frames, n, max_bframes, best_paths );
1025 if( num_frames > 1 )
1027 int best_path_index = (num_frames-1) % (X264_BFRAME_MAX+1);
1028 num_bframes = strspn( best_paths[best_path_index], "B" );
1029 /* Load the results of the analysis into the frame types. */
1030 for( j = 1; j < num_frames; j++ )
1031 frames[j]->i_type = best_paths[best_path_index][j-1] == 'B' ? X264_TYPE_B : X264_TYPE_P;
1033 frames[num_frames]->i_type = X264_TYPE_P;
1035 else if( h->param.i_bframe_adaptive == X264_B_ADAPT_FAST )
1037 for( i = 0; i <= num_frames-2; )
1039 cost2p1 = x264_slicetype_frame_cost( h, &a, frames, i+0, i+2, i+2, 1 );
1040 if( frames[i+2]->i_intra_mbs[2] > i_mb_count / 2 )
1042 frames[i+1]->i_type = X264_TYPE_P;
1043 frames[i+2]->i_type = X264_TYPE_P;
1048 cost1b1 = x264_slicetype_frame_cost( h, &a, frames, i+0, i+2, i+1, 0 );
1049 cost1p0 = x264_slicetype_frame_cost( h, &a, frames, i+0, i+1, i+1, 0 );
1050 cost2p0 = x264_slicetype_frame_cost( h, &a, frames, i+1, i+2, i+2, 0 );
1052 if( cost1p0 + cost2p0 < cost1b1 + cost2p1 )
1054 frames[i+1]->i_type = X264_TYPE_P;
1059 // arbitrary and untuned
1060 #define INTER_THRESH 300
1061 #define P_SENS_BIAS (50 - h->param.i_bframe_bias)
1062 frames[i+1]->i_type = X264_TYPE_B;
1064 for( j = i+2; j <= X264_MIN( i+h->param.i_bframe, num_frames-1 ); j++ )
1066 int pthresh = X264_MAX(INTER_THRESH - P_SENS_BIAS * (j-i-1), INTER_THRESH/10);
1067 int pcost = x264_slicetype_frame_cost( h, &a, frames, i+0, j+1, j+1, 1 );
1068 if( pcost > pthresh*i_mb_count || frames[j+1]->i_intra_mbs[j-i+1] > i_mb_count/3 )
1070 frames[j]->i_type = X264_TYPE_B;
1072 frames[j]->i_type = X264_TYPE_P;
1075 frames[num_frames]->i_type = X264_TYPE_P;
1077 while( num_bframes < num_frames && frames[num_bframes+1]->i_type == X264_TYPE_B )
1082 num_bframes = X264_MIN(num_frames-1, h->param.i_bframe);
1083 for( j = 1; j < num_frames; j++ )
1084 frames[j]->i_type = (j%(num_bframes+1)) ? X264_TYPE_B : X264_TYPE_P;
1085 frames[num_frames]->i_type = X264_TYPE_P;
1088 /* Check scenecut on the first minigop. */
1089 for( j = 1; j < num_bframes+1; j++ )
1090 if( h->param.i_scenecut_threshold && scenecut( h, &a, frames, j, j+1, 0, orig_num_frames ) )
1092 frames[j]->i_type = X264_TYPE_P;
1093 num_analysed_frames = j;
1097 reset_start = keyframe ? 1 : X264_MIN( num_bframes+2, num_analysed_frames+1 );
1101 for( j = 1; j <= num_frames; j++ )
1102 frames[j]->i_type = X264_TYPE_P;
1103 reset_start = !keyframe + 1;
1107 /* Perform the actual macroblock tree analysis.
1108 * Don't go farther than the maximum keyframe interval; this helps in short GOPs. */
1109 if( h->param.rc.b_mb_tree )
1110 x264_macroblock_tree( h, &a, frames, X264_MIN(num_frames, h->param.i_keyint_max), keyframe );
1112 /* Enforce keyframe limit. */
1113 for( j = 0; j < num_frames; j++ )
1115 if( ((j-keyint_limit) % h->param.i_keyint_max) == 0 )
1117 if( j && h->param.i_keyint_max > 1 )
1118 frames[j]->i_type = X264_TYPE_P;
1119 frames[j+1]->i_type = X264_TYPE_IDR;
1120 reset_start = X264_MIN( reset_start, j+2 );
1124 if( h->param.rc.i_vbv_buffer_size )
1125 x264_vbv_lookahead( h, &a, frames, num_frames, keyframe );
1127 /* Restore frametypes for all frames that haven't actually been decided yet. */
1128 for( j = reset_start; j <= num_frames; j++ )
1129 frames[j]->i_type = X264_TYPE_AUTO;
1132 void x264_slicetype_decide( x264_t *h )
1134 x264_frame_t *frames[X264_BFRAME_MAX+2];
1140 if( !h->lookahead->next.i_size )
1143 if( h->param.rc.b_stat_read )
1145 /* Use the frame types from the first pass */
1146 for( i = 0; i < h->lookahead->next.i_size; i++ )
1147 h->lookahead->next.list[i]->i_type =
1148 x264_ratecontrol_slice_type( h, h->lookahead->next.list[i]->i_frame );
1150 else if( (h->param.i_bframe && h->param.i_bframe_adaptive)
1151 || h->param.i_scenecut_threshold
1152 || h->param.rc.b_mb_tree
1153 || (h->param.rc.i_vbv_buffer_size && h->param.rc.i_lookahead) )
1154 x264_slicetype_analyse( h, 0 );
1156 for( bframes = 0, brefs = 0;; bframes++ )
1158 frm = h->lookahead->next.list[bframes];
1159 if( frm->i_type == X264_TYPE_BREF && h->param.i_bframe_pyramid < X264_B_PYRAMID_NORMAL &&
1160 brefs == h->param.i_bframe_pyramid )
1162 frm->i_type = X264_TYPE_B;
1163 x264_log( h, X264_LOG_WARNING, "B-ref at frame %d incompatible with B-pyramid %s \n",
1164 frm->i_frame, x264_b_pyramid_names[h->param.i_bframe_pyramid] );
1166 /* pyramid with multiple B-refs needs a big enough dpb that the preceding P-frame stays available.
1167 smaller dpb could be supported by smart enough use of mmco, but it's easier just to forbid it. */
1168 else if( frm->i_type == X264_TYPE_BREF && h->param.i_bframe_pyramid == X264_B_PYRAMID_NORMAL &&
1169 brefs && h->param.i_frame_reference <= (brefs+3) )
1171 frm->i_type = X264_TYPE_B;
1172 x264_log( h, X264_LOG_WARNING, "B-ref at frame %d incompatible with B-pyramid %s and %d reference frames\n",
1173 frm->i_frame, x264_b_pyramid_names[h->param.i_bframe_pyramid], h->param.i_frame_reference );
1176 /* Limit GOP size */
1177 if( frm->i_frame - h->lookahead->i_last_idr >= h->param.i_keyint_max )
1179 if( frm->i_type == X264_TYPE_AUTO )
1180 frm->i_type = X264_TYPE_IDR;
1181 if( frm->i_type != X264_TYPE_IDR )
1182 x264_log( h, X264_LOG_WARNING, "specified frame type (%d) is not compatible with keyframe interval\n", frm->i_type );
1184 if( frm->i_type == X264_TYPE_IDR )
1187 h->lookahead->i_last_idr = frm->i_frame;
1191 h->lookahead->next.list[bframes]->i_type = X264_TYPE_P;
1195 if( bframes == h->param.i_bframe ||
1196 !h->lookahead->next.list[bframes+1] )
1198 if( IS_X264_TYPE_B( frm->i_type ) )
1199 x264_log( h, X264_LOG_WARNING, "specified frame type is not compatible with max B-frames\n" );
1200 if( frm->i_type == X264_TYPE_AUTO
1201 || IS_X264_TYPE_B( frm->i_type ) )
1202 frm->i_type = X264_TYPE_P;
1205 if( frm->i_type == X264_TYPE_BREF )
1208 if( frm->i_type == X264_TYPE_AUTO )
1209 frm->i_type = X264_TYPE_B;
1211 else if( !IS_X264_TYPE_B( frm->i_type ) ) break;
1215 h->lookahead->next.list[bframes-1]->b_last_minigop_bframe = 1;
1216 h->lookahead->next.list[bframes]->i_bframes = bframes;
1218 /* insert a bref into the sequence */
1219 if( h->param.i_bframe_pyramid && bframes > 1 && !brefs )
1221 h->lookahead->next.list[bframes/2]->i_type = X264_TYPE_BREF;
1225 /* calculate the frame costs ahead of time for x264_rc_analyse_slice while we still have lowres */
1226 if( h->param.rc.i_rc_method != X264_RC_CQP )
1228 x264_mb_analysis_t a;
1230 p1 = b = bframes + 1;
1232 x264_lowres_context_init( h, &a );
1234 frames[0] = h->lookahead->last_nonb;
1235 memcpy( &frames[1], h->lookahead->next.list, (bframes+1) * sizeof(x264_frame_t*) );
1236 if( IS_X264_TYPE_I( h->lookahead->next.list[bframes]->i_type ) )
1241 x264_slicetype_frame_cost( h, &a, frames, p0, p1, b, 0 );
1243 if( (p0 != p1 || bframes) && h->param.rc.i_vbv_buffer_size )
1245 /* We need the intra costs for row SATDs. */
1246 x264_slicetype_frame_cost( h, &a, frames, b, b, b, 0 );
1248 /* We need B-frame costs for row SATDs. */
1250 for( b = 1; b <= bframes; b++ )
1252 if( frames[b]->i_type == X264_TYPE_B )
1253 for( p1 = b; frames[p1]->i_type == X264_TYPE_B; )
1257 x264_slicetype_frame_cost( h, &a, frames, p0, p1, b, 0 );
1258 if( frames[b]->i_type == X264_TYPE_BREF )
1264 /* Analyse for weighted P frames */
1265 if( !h->param.rc.b_stat_read && h->lookahead->next.list[bframes]->i_type == X264_TYPE_P
1266 && h->param.analyse.i_weighted_pred == X264_WEIGHTP_SMART )
1267 x264_weights_analyse( h, h->lookahead->next.list[bframes], h->lookahead->last_nonb, 0 );
1269 /* shift sequence to coded order.
1270 use a small temporary list to avoid shifting the entire next buffer around */
1271 int i_dts = h->lookahead->next.list[0]->i_frame;
1274 int index[] = { brefs+1, 1 };
1275 for( i = 0; i < bframes; i++ )
1276 frames[ index[h->lookahead->next.list[i]->i_type == X264_TYPE_BREF]++ ] = h->lookahead->next.list[i];
1277 frames[0] = h->lookahead->next.list[bframes];
1278 memcpy( h->lookahead->next.list, frames, (bframes+1) * sizeof(x264_frame_t*) );
1280 for( i = 0; i <= bframes; i++ )
1281 h->lookahead->next.list[i]->i_dts = i_dts++;
1284 int x264_rc_analyse_slice( x264_t *h )
1289 if( IS_X264_TYPE_I(h->fenc->i_type) )
1291 else if( h->fenc->i_type == X264_TYPE_P )
1292 p1 = b = h->fenc->i_bframes + 1;
1295 p1 = (h->fref1[0]->i_poc - h->fref0[0]->i_poc)/2;
1296 b = (h->fenc->i_poc - h->fref0[0]->i_poc)/2;
1298 /* We don't need to assign p0/p1 since we are not performing any real analysis here. */
1299 x264_frame_t **frames = &h->fenc - b;
1301 /* cost should have been already calculated by x264_slicetype_decide */
1302 cost = frames[b]->i_cost_est[b-p0][p1-b];
1303 assert( cost >= 0 );
1305 if( h->param.rc.b_mb_tree && !h->param.rc.b_stat_read )
1307 cost = x264_slicetype_frame_cost_recalculate( h, frames, p0, p1, b );
1308 if( b && h->param.rc.i_vbv_buffer_size )
1309 x264_slicetype_frame_cost_recalculate( h, frames, b, b, b );
1311 /* In AQ, use the weighted score instead. */
1312 else if( h->param.rc.i_aq_mode )
1313 cost = frames[b]->i_cost_est_aq[b-p0][p1-b];
1315 h->fenc->i_row_satd = h->fenc->i_row_satds[b-p0][p1-b];
1316 h->fdec->i_row_satd = h->fdec->i_row_satds[b-p0][p1-b];
1317 h->fdec->i_satd = cost;
1318 memcpy( h->fdec->i_row_satd, h->fenc->i_row_satd, h->sps->i_mb_height * sizeof(int) );
1319 if( !IS_X264_TYPE_I(h->fenc->i_type) )
1320 memcpy( h->fdec->i_row_satds[0][0], h->fenc->i_row_satds[0][0], h->sps->i_mb_height * sizeof(int) );