1 /*****************************************************************************
2 * slicetype.c: lookahead analysis
3 *****************************************************************************
4 * Copyright (C) 2005-2012 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.
24 * This program is also available under a commercial proprietary license.
25 * For more information, contact us at licensing@x264.com.
26 *****************************************************************************/
28 #include "common/common.h"
29 #include "macroblock.h"
32 // Indexed by pic_struct values
33 static const uint8_t delta_tfi_divisor[10] = { 0, 2, 1, 1, 2, 2, 3, 3, 4, 6 };
35 static int x264_slicetype_frame_cost( x264_t *h, x264_mb_analysis_t *a,
36 x264_frame_t **frames, int p0, int p1, int b,
37 int b_intra_penalty );
39 static void x264_lowres_context_init( x264_t *h, x264_mb_analysis_t *a )
41 a->i_qp = X264_LOOKAHEAD_QP;
42 a->i_lambda = x264_lambda_tab[ a->i_qp ];
43 x264_mb_analyse_load_costs( h, a );
44 if( h->param.analyse.i_subpel_refine > 1 )
46 h->mb.i_me_method = X264_MIN( X264_ME_HEX, h->param.analyse.i_me_method );
47 h->mb.i_subpel_refine = 4;
51 h->mb.i_me_method = X264_ME_DIA;
52 h->mb.i_subpel_refine = 2;
54 h->mb.b_chroma_me = 0;
57 /* makes a non-h264 weight (i.e. fix7), into an h264 weight */
58 static void x264_weight_get_h264( int weight_nonh264, int offset, x264_weight_t *w )
62 w->i_scale = weight_nonh264;
63 while( w->i_denom > 0 && (w->i_scale > 127 || !(w->i_scale & 1)) )
68 w->i_scale = X264_MIN( w->i_scale, 127 );
71 static NOINLINE pixel *x264_weight_cost_init_luma( x264_t *h, x264_frame_t *fenc, x264_frame_t *ref, pixel *dest )
73 int ref0_distance = fenc->i_frame - ref->i_frame - 1;
74 /* Note: this will never run during lookahead as weights_analyse is only called if no
75 * motion search has been done. */
76 if( fenc->lowres_mvs[0][ref0_distance][0][0] != 0x7FFF )
78 int i_stride = fenc->i_stride_lowres;
79 int i_lines = fenc->i_lines_lowres;
80 int i_width = fenc->i_width_lowres;
84 for( int y = 0; y < i_lines; y += 8, p += i_stride*8 )
85 for( int x = 0; x < i_width; x += 8, i_mb_xy++ )
87 int mvx = fenc->lowres_mvs[0][ref0_distance][i_mb_xy][0];
88 int mvy = fenc->lowres_mvs[0][ref0_distance][i_mb_xy][1];
89 h->mc.mc_luma( p+x, i_stride, ref->lowres, i_stride,
90 mvx+(x<<2), mvy+(y<<2), 8, 8, x264_weight_none );
96 return ref->lowres[0];
99 /* How data is organized for 4:2:0/4:2:2 chroma weightp:
102 * fenc = ref + offset
103 * v = u + stride * chroma height */
105 static NOINLINE void x264_weight_cost_init_chroma( x264_t *h, x264_frame_t *fenc, x264_frame_t *ref, pixel *dstu, pixel *dstv )
107 int ref0_distance = fenc->i_frame - ref->i_frame - 1;
108 int i_stride = fenc->i_stride[1];
109 int i_offset = i_stride / 2;
110 int i_lines = fenc->i_lines[1];
111 int i_width = fenc->i_width[1];
112 int v_shift = CHROMA_V_SHIFT;
113 int cw = 8*h->mb.i_mb_width;
114 int ch = 16*h->mb.i_mb_height >> v_shift;
115 int height = 16 >> v_shift;
117 if( fenc->lowres_mvs[0][ref0_distance][0][0] != 0x7FFF )
119 x264_frame_expand_border_chroma( h, ref, 1 );
120 for( int y = 0, mb_xy = 0, pel_offset_y = 0; y < i_lines; y += height, pel_offset_y = y*i_stride )
121 for( int x = 0, pel_offset_x = 0; x < i_width; x += 8, mb_xy++, pel_offset_x += 8 )
123 pixel *pixu = dstu + pel_offset_y + pel_offset_x;
124 pixel *pixv = dstv + pel_offset_y + pel_offset_x;
125 pixel *src1 = ref->plane[1] + pel_offset_y + pel_offset_x*2; /* NV12/NV16 */
126 int mvx = fenc->lowres_mvs[0][ref0_distance][mb_xy][0];
127 int mvy = fenc->lowres_mvs[0][ref0_distance][mb_xy][1];
128 h->mc.mc_chroma( pixu, pixv, i_stride, src1, i_stride, mvx, 2*mvy>>v_shift, 8, height );
132 h->mc.plane_copy_deinterleave( dstu, i_stride, dstv, i_stride, ref->plane[1], i_stride, cw, ch );
133 h->mc.plane_copy_deinterleave( dstu+i_offset, i_stride, dstv+i_offset, i_stride, fenc->plane[1], i_stride, cw, ch );
137 static NOINLINE pixel *x264_weight_cost_init_chroma444( x264_t *h, x264_frame_t *fenc, x264_frame_t *ref, pixel *dst, int p )
139 int ref0_distance = fenc->i_frame - ref->i_frame - 1;
140 int i_stride = fenc->i_stride[p];
141 int i_lines = fenc->i_lines[p];
142 int i_width = fenc->i_width[p];
144 if( fenc->lowres_mvs[0][ref0_distance][0][0] != 0x7FFF )
146 x264_frame_expand_border_chroma( h, ref, p );
147 for( int y = 0, mb_xy = 0, pel_offset_y = 0; y < i_lines; y += 16, pel_offset_y = y*i_stride )
148 for( int x = 0, pel_offset_x = 0; x < i_width; x += 16, mb_xy++, pel_offset_x += 16 )
150 pixel *pix = dst + pel_offset_y + pel_offset_x;
151 pixel *src = ref->plane[p] + pel_offset_y + pel_offset_x;
152 int mvx = fenc->lowres_mvs[0][ref0_distance][mb_xy][0] / 2;
153 int mvy = fenc->lowres_mvs[0][ref0_distance][mb_xy][1] / 2;
154 /* We don't want to calculate hpels for fenc frames, so we round the motion
155 * vectors to fullpel here. It's not too bad, I guess? */
156 h->mc.copy_16x16_unaligned( pix, i_stride, src+mvx+mvy*i_stride, i_stride, 16 );
162 return ref->plane[p];
165 static int x264_weight_slice_header_cost( x264_t *h, x264_weight_t *w, int b_chroma )
167 /* Add cost of weights in the slice header. */
168 int lambda = x264_lambda_tab[X264_LOOKAHEAD_QP];
169 /* 4 times higher, because chroma is analyzed at full resolution. */
173 if( h->param.i_slice_count )
174 numslices = h->param.i_slice_count;
175 else if( h->param.i_slice_max_mbs )
176 numslices = (h->mb.i_mb_width * h->mb.i_mb_height + h->param.i_slice_max_mbs-1) / h->param.i_slice_max_mbs;
179 /* FIXME: find a way to account for --slice-max-size?
180 * 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.
181 * Cut denom cost in half if chroma, since it's shared between the two chroma planes. */
182 int denom_cost = bs_size_ue( w[0].i_denom ) * (2 - b_chroma);
183 return lambda * numslices * ( 10 + denom_cost + 2 * (bs_size_se( w[0].i_scale ) + bs_size_se( w[0].i_offset )) );
186 static NOINLINE unsigned int x264_weight_cost_luma( x264_t *h, x264_frame_t *fenc, pixel *src, x264_weight_t *w )
188 unsigned int cost = 0;
189 int i_stride = fenc->i_stride_lowres;
190 int i_lines = fenc->i_lines_lowres;
191 int i_width = fenc->i_width_lowres;
192 pixel *fenc_plane = fenc->lowres[0];
193 ALIGNED_ARRAY_16( pixel, buf,[8*8] );
199 for( int y = 0; y < i_lines; y += 8, pixoff = y*i_stride )
200 for( int x = 0; x < i_width; x += 8, i_mb++, pixoff += 8)
202 w->weightfn[8>>2]( buf, 8, &src[pixoff], i_stride, w, 8 );
203 int cmp = h->pixf.mbcmp[PIXEL_8x8]( buf, 8, &fenc_plane[pixoff], i_stride );
204 cost += X264_MIN( cmp, fenc->i_intra_cost[i_mb] );
206 cost += x264_weight_slice_header_cost( h, w, 0 );
209 for( int y = 0; y < i_lines; y += 8, pixoff = y*i_stride )
210 for( int x = 0; x < i_width; x += 8, i_mb++, pixoff += 8 )
212 int cmp = h->pixf.mbcmp[PIXEL_8x8]( &src[pixoff], i_stride, &fenc_plane[pixoff], i_stride );
213 cost += X264_MIN( cmp, fenc->i_intra_cost[i_mb] );
219 static NOINLINE unsigned int x264_weight_cost_chroma( x264_t *h, x264_frame_t *fenc, pixel *ref, x264_weight_t *w )
221 unsigned int cost = 0;
222 int i_stride = fenc->i_stride[1];
223 int i_lines = fenc->i_lines[1];
224 int i_width = fenc->i_width[1];
225 pixel *src = ref + (i_stride >> 1);
226 ALIGNED_ARRAY_16( pixel, buf, [8*16] );
228 int height = 16 >> CHROMA_V_SHIFT;
231 for( int y = 0; y < i_lines; y += height, pixoff = y*i_stride )
232 for( int x = 0; x < i_width; x += 8, pixoff += 8 )
234 w->weightfn[8>>2]( buf, 8, &ref[pixoff], i_stride, w, height );
235 /* The naive and seemingly sensible algorithm is to use mbcmp as in luma.
236 * But testing shows that for chroma the DC coefficient is by far the most
237 * important part of the coding cost. Thus a more useful chroma weight is
238 * obtained by comparing each block's DC coefficient instead of the actual
240 cost += h->pixf.asd8( buf, 8, &src[pixoff], i_stride, height );
242 cost += x264_weight_slice_header_cost( h, w, 1 );
245 for( int y = 0; y < i_lines; y += height, pixoff = y*i_stride )
246 for( int x = 0; x < i_width; x += 8, pixoff += 8 )
247 cost += h->pixf.asd8( &ref[pixoff], i_stride, &src[pixoff], i_stride, height );
252 static NOINLINE unsigned int x264_weight_cost_chroma444( x264_t *h, x264_frame_t *fenc, pixel *ref, x264_weight_t *w, int p )
254 unsigned int cost = 0;
255 int i_stride = fenc->i_stride[p];
256 int i_lines = fenc->i_lines[p];
257 int i_width = fenc->i_width[p];
258 pixel *src = fenc->plane[p];
259 ALIGNED_ARRAY_16( pixel, buf, [16*16] );
263 for( int y = 0; y < i_lines; y += 16, pixoff = y*i_stride )
264 for( int x = 0; x < i_width; x += 16, pixoff += 16 )
266 w->weightfn[16>>2]( buf, 16, &ref[pixoff], i_stride, w, 16 );
267 cost += h->pixf.mbcmp[PIXEL_16x16]( buf, 16, &src[pixoff], i_stride );
269 cost += x264_weight_slice_header_cost( h, w, 1 );
272 for( int y = 0; y < i_lines; y += 16, pixoff = y*i_stride )
273 for( int x = 0; x < i_width; x += 16, pixoff += 16 )
274 cost += h->pixf.mbcmp[PIXEL_16x16]( &ref[pixoff], i_stride, &src[pixoff], i_stride );
279 static void x264_weights_analyse( x264_t *h, x264_frame_t *fenc, x264_frame_t *ref, int b_lookahead )
281 int i_delta_index = fenc->i_frame - ref->i_frame - 1;
282 /* epsilon is chosen to require at least a numerator of 127 (with denominator = 128) */
283 const float epsilon = 1.f/128.f;
284 x264_weight_t *weights = fenc->weight[0];
285 SET_WEIGHT( weights[0], 0, 1, 0, 0 );
286 SET_WEIGHT( weights[1], 0, 1, 0, 0 );
287 SET_WEIGHT( weights[2], 0, 1, 0, 0 );
288 int chroma_initted = 0;
289 /* Don't check chroma in lookahead, or if there wasn't a luma weight. */
290 for( int plane = 0; plane <= 2 && !( plane && ( !weights[0].weightfn || b_lookahead ) ); plane++ )
292 int cur_offset, start_offset, end_offset;
293 int minoff, minscale, mindenom;
294 unsigned int minscore, origscore;
296 float fenc_var = fenc->i_pixel_ssd[plane] + !ref->i_pixel_ssd[plane];
297 float ref_var = ref->i_pixel_ssd[plane] + !ref->i_pixel_ssd[plane];
298 float guess_scale = sqrtf( fenc_var / ref_var );
299 float fenc_mean = (float)fenc->i_pixel_sum[plane] / (fenc->i_lines[!!plane] * fenc->i_width[!!plane]) / (1 << (BIT_DEPTH - 8));
300 float ref_mean = (float) ref->i_pixel_sum[plane] / (fenc->i_lines[!!plane] * fenc->i_width[!!plane]) / (1 << (BIT_DEPTH - 8));
303 if( fabsf( ref_mean - fenc_mean ) < 0.5f && fabsf( 1.f - guess_scale ) < epsilon )
305 SET_WEIGHT( weights[plane], 0, 1, 0, 0 );
311 weights[plane].i_denom = 6;
312 weights[plane].i_scale = x264_clip3( round( guess_scale * 64 ), 0, 255 );
313 if( weights[plane].i_scale > 127 )
315 weights[1].weightfn = weights[2].weightfn = NULL;
320 x264_weight_get_h264( round( guess_scale * 128 ), 0, &weights[plane] );
323 mindenom = weights[plane].i_denom;
324 minscale = weights[plane].i_scale;
330 if( !fenc->b_intra_calculated )
332 x264_mb_analysis_t a;
333 x264_lowres_context_init( h, &a );
334 x264_slicetype_frame_cost( h, &a, &fenc, 0, 0, 0, 0 );
336 mcbuf = x264_weight_cost_init_luma( h, fenc, ref, h->mb.p_weight_buf[0] );
337 origscore = minscore = x264_weight_cost_luma( h, fenc, mcbuf, NULL );
343 mcbuf = x264_weight_cost_init_chroma444( h, fenc, ref, h->mb.p_weight_buf[0], plane );
344 origscore = minscore = x264_weight_cost_chroma444( h, fenc, mcbuf, NULL, plane );
348 pixel *dstu = h->mb.p_weight_buf[0];
349 pixel *dstv = h->mb.p_weight_buf[0]+fenc->i_stride[1]*fenc->i_lines[1];
350 if( !chroma_initted++ )
351 x264_weight_cost_init_chroma( h, fenc, ref, dstu, dstv );
352 mcbuf = plane == 1 ? dstu : dstv;
353 origscore = minscore = x264_weight_cost_chroma( h, fenc, mcbuf, NULL );
360 // This gives a slight improvement due to rounding errors but only tests one offset in lookahead.
361 // Currently only searches within +/- 1 of the best offset found so far.
362 // TODO: Try other offsets/multipliers/combinations thereof?
363 cur_offset = fenc_mean - ref_mean * minscale / (1 << mindenom) + 0.5f * b_lookahead;
364 start_offset = x264_clip3( cur_offset - !b_lookahead, -128, 127 );
365 end_offset = x264_clip3( cur_offset + !b_lookahead, -128, 127 );
366 for( int i_off = start_offset; i_off <= end_offset; i_off++ )
368 SET_WEIGHT( weights[plane], 1, minscale, mindenom, i_off );
373 s = x264_weight_cost_chroma444( h, fenc, mcbuf, &weights[plane], plane );
375 s = x264_weight_cost_chroma( h, fenc, mcbuf, &weights[plane] );
378 s = x264_weight_cost_luma( h, fenc, mcbuf, &weights[plane] );
379 COPY3_IF_LT( minscore, s, minoff, i_off, found, 1 );
381 // Don't check any more offsets if the previous one had a lower cost than the current one
382 if( minoff == start_offset && i_off != start_offset )
387 /* FIXME: More analysis can be done here on SAD vs. SATD termination. */
388 /* 0.2% termination derived experimentally to avoid weird weights in frames that are mostly intra. */
389 if( !found || (minscale == 1 << mindenom && minoff == 0) || (float)minscore / origscore > 0.998f )
391 SET_WEIGHT( weights[plane], 0, 1, 0, 0 );
395 SET_WEIGHT( weights[plane], 1, minscale, mindenom, minoff );
397 if( h->param.analyse.i_weighted_pred == X264_WEIGHTP_FAKE && weights[0].weightfn && !plane )
398 fenc->f_weighted_cost_delta[i_delta_index] = (float)minscore / origscore;
401 //FIXME, what is the correct way to deal with this?
402 if( weights[1].weightfn && weights[2].weightfn && weights[1].i_denom != weights[2].i_denom )
404 int denom = X264_MIN( weights[1].i_denom, weights[2].i_denom );
406 for( i = 1; i <= 2; i++ )
408 weights[i].i_scale = x264_clip3( weights[i].i_scale >> ( weights[i].i_denom - denom ), 0, 255 );
409 weights[i].i_denom = denom;
410 h->mc.weight_cache( h, &weights[i] );
414 if( weights[0].weightfn && b_lookahead )
416 //scale lowres in lookahead for slicetype_frame_cost
417 pixel *src = ref->buffer_lowres[0];
418 pixel *dst = h->mb.p_weight_buf[0];
419 int width = ref->i_width_lowres + PADH*2;
420 int height = ref->i_lines_lowres + PADV*2;
421 x264_weight_scale_plane( h, dst, ref->i_stride_lowres, src, ref->i_stride_lowres,
422 width, height, &weights[0] );
423 fenc->weighted[0] = h->mb.p_weight_buf[0] + PADH + ref->i_stride_lowres * PADV;
427 /* Output buffers are separated by 128 bytes to avoid false sharing of cachelines
428 * in multithreaded lookahead. */
430 /* cost_est, cost_est_aq, intra_mbs, num rows */
433 #define COST_EST_AQ 1
436 #define ROW_SATD (NUM_INTS + (h->mb.i_mb_y - h->i_threadslice_start))
438 static void x264_slicetype_mb_cost( x264_t *h, x264_mb_analysis_t *a,
439 x264_frame_t **frames, int p0, int p1, int b,
440 int dist_scale_factor, int do_search[2], const x264_weight_t *w,
441 int *output_inter, int *output_intra )
443 x264_frame_t *fref0 = frames[p0];
444 x264_frame_t *fref1 = frames[p1];
445 x264_frame_t *fenc = frames[b];
446 const int b_bidir = (b < p1);
447 const int i_mb_x = h->mb.i_mb_x;
448 const int i_mb_y = h->mb.i_mb_y;
449 const int i_mb_stride = h->mb.i_mb_width;
450 const int i_mb_xy = i_mb_x + i_mb_y * i_mb_stride;
451 const int i_stride = fenc->i_stride_lowres;
452 const int i_pel_offset = 8 * (i_mb_x + i_mb_y * i_stride);
453 const int i_bipred_weight = h->param.analyse.b_weighted_bipred ? 64 - (dist_scale_factor>>2) : 32;
454 int16_t (*fenc_mvs[2])[2] = { &fenc->lowres_mvs[0][b-p0-1][i_mb_xy], &fenc->lowres_mvs[1][p1-b-1][i_mb_xy] };
455 int (*fenc_costs[2]) = { &fenc->lowres_mv_costs[0][b-p0-1][i_mb_xy], &fenc->lowres_mv_costs[1][p1-b-1][i_mb_xy] };
456 int b_frame_score_mb = (i_mb_x > 0 && i_mb_x < h->mb.i_mb_width - 1 &&
457 i_mb_y > 0 && i_mb_y < h->mb.i_mb_height - 1) ||
458 h->mb.i_mb_width <= 2 || h->mb.i_mb_height <= 2;
460 ALIGNED_ARRAY_16( pixel, pix1,[9*FDEC_STRIDE] );
461 pixel *pix2 = pix1+8;
463 int i_bcost = COST_MAX;
465 /* A small, arbitrary bias to avoid VBV problems caused by zero-residual lookahead blocks. */
466 int lowres_penalty = 4;
468 h->mb.pic.p_fenc[0] = h->mb.pic.fenc_buf;
469 h->mc.copy[PIXEL_8x8]( h->mb.pic.p_fenc[0], FENC_STRIDE, &fenc->lowres[0][i_pel_offset], i_stride, 8 );
472 goto lowres_intra_mb;
474 // no need for h->mb.mv_min[]
475 h->mb.mv_min_fpel[0] = -8*h->mb.i_mb_x - 4;
476 h->mb.mv_max_fpel[0] = 8*( h->mb.i_mb_width - h->mb.i_mb_x - 1 ) + 4;
477 h->mb.mv_min_spel[0] = 4*( h->mb.mv_min_fpel[0] - 8 );
478 h->mb.mv_max_spel[0] = 4*( h->mb.mv_max_fpel[0] + 8 );
479 if( h->mb.i_mb_x >= h->mb.i_mb_width - 2 )
481 h->mb.mv_min_fpel[1] = -8*h->mb.i_mb_y - 4;
482 h->mb.mv_max_fpel[1] = 8*( h->mb.i_mb_height - h->mb.i_mb_y - 1 ) + 4;
483 h->mb.mv_min_spel[1] = 4*( h->mb.mv_min_fpel[1] - 8 );
484 h->mb.mv_max_spel[1] = 4*( h->mb.mv_max_fpel[1] + 8 );
487 #define LOAD_HPELS_LUMA(dst, src) \
489 (dst)[0] = &(src)[0][i_pel_offset]; \
490 (dst)[1] = &(src)[1][i_pel_offset]; \
491 (dst)[2] = &(src)[2][i_pel_offset]; \
492 (dst)[3] = &(src)[3][i_pel_offset]; \
494 #define LOAD_WPELS_LUMA(dst,src) \
495 (dst) = &(src)[i_pel_offset];
497 #define CLIP_MV( mv ) \
499 mv[0] = x264_clip3( mv[0], h->mb.mv_min_spel[0], h->mb.mv_max_spel[0] ); \
500 mv[1] = x264_clip3( mv[1], h->mb.mv_min_spel[1], h->mb.mv_max_spel[1] ); \
502 #define TRY_BIDIR( mv0, mv1, penalty ) \
505 if( h->param.analyse.i_subpel_refine <= 1 ) \
507 int hpel_idx1 = (((mv0)[0]&2)>>1) + ((mv0)[1]&2); \
508 int hpel_idx2 = (((mv1)[0]&2)>>1) + ((mv1)[1]&2); \
509 pixel *src1 = m[0].p_fref[hpel_idx1] + ((mv0)[0]>>2) + ((mv0)[1]>>2) * m[0].i_stride[0]; \
510 pixel *src2 = m[1].p_fref[hpel_idx2] + ((mv1)[0]>>2) + ((mv1)[1]>>2) * m[1].i_stride[0]; \
511 h->mc.avg[PIXEL_8x8]( pix1, 16, src1, m[0].i_stride[0], src2, m[1].i_stride[0], i_bipred_weight ); \
515 intptr_t stride1 = 16, stride2 = 16; \
516 pixel *src1, *src2; \
517 src1 = h->mc.get_ref( pix1, &stride1, m[0].p_fref, m[0].i_stride[0], \
518 (mv0)[0], (mv0)[1], 8, 8, w ); \
519 src2 = h->mc.get_ref( pix2, &stride2, m[1].p_fref, m[1].i_stride[0], \
520 (mv1)[0], (mv1)[1], 8, 8, w ); \
521 h->mc.avg[PIXEL_8x8]( pix1, 16, src1, stride1, src2, stride2, i_bipred_weight ); \
523 i_cost = penalty * a->i_lambda + h->pixf.mbcmp[PIXEL_8x8]( \
524 m[0].p_fenc[0], FENC_STRIDE, pix1, 16 ); \
525 COPY2_IF_LT( i_bcost, i_cost, list_used, 3 ); \
528 m[0].i_pixel = PIXEL_8x8;
529 m[0].p_cost_mv = a->p_cost_mv;
530 m[0].i_stride[0] = i_stride;
531 m[0].p_fenc[0] = h->mb.pic.p_fenc[0];
534 LOAD_HPELS_LUMA( m[0].p_fref, fref0->lowres );
535 m[0].p_fref_w = m[0].p_fref[0];
537 LOAD_WPELS_LUMA( m[0].p_fref_w, fenc->weighted[0] );
541 int16_t *mvr = fref1->lowres_mvs[0][p1-p0-1][i_mb_xy];
542 ALIGNED_ARRAY_8( int16_t, dmv,[2],[2] );
544 m[1].i_pixel = PIXEL_8x8;
545 m[1].p_cost_mv = a->p_cost_mv;
546 m[1].i_stride[0] = i_stride;
547 m[1].p_fenc[0] = h->mb.pic.p_fenc[0];
549 m[1].weight = x264_weight_none;
550 LOAD_HPELS_LUMA( m[1].p_fref, fref1->lowres );
551 m[1].p_fref_w = m[1].p_fref[0];
553 dmv[0][0] = ( mvr[0] * dist_scale_factor + 128 ) >> 8;
554 dmv[0][1] = ( mvr[1] * dist_scale_factor + 128 ) >> 8;
555 dmv[1][0] = dmv[0][0] - mvr[0];
556 dmv[1][1] = dmv[0][1] - mvr[1];
559 if( h->param.analyse.i_subpel_refine <= 1 )
560 M64( dmv ) &= ~0x0001000100010001ULL; /* mv & ~1 */
562 TRY_BIDIR( dmv[0], dmv[1], 0 );
566 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 );
567 i_cost = h->pixf.mbcmp[PIXEL_8x8]( m[0].p_fenc[0], FENC_STRIDE, pix1, 16 );
568 COPY2_IF_LT( i_bcost, i_cost, list_used, 3 );
572 for( int l = 0; l < 1 + b_bidir; l++ )
577 int16_t (*fenc_mv)[2] = fenc_mvs[l];
578 ALIGNED_4( int16_t mvc[4][2] );
580 /* Reverse-order MV prediction. */
583 #define MVC(mv) { CP32( mvc[i_mvc], mv ); i_mvc++; }
584 if( i_mb_x < h->mb.i_mb_width - 1 )
586 if( i_mb_y < h->i_threadslice_end - 1 )
588 MVC( fenc_mv[i_mb_stride] );
590 MVC( fenc_mv[i_mb_stride-1] );
591 if( i_mb_x < h->mb.i_mb_width - 1 )
592 MVC( fenc_mv[i_mb_stride+1] );
596 CP32( m[l].mvp, mvc[0] );
598 x264_median_mv( m[l].mvp, mvc[0], mvc[1], mvc[2] );
600 /* Fast skip for cases of near-zero residual. Shortcut: don't bother except in the mv0 case,
601 * since anything else is likely to have enough residual to not trigger the skip. */
602 if( !M32( m[l].mvp ) )
604 m[l].cost = h->pixf.mbcmp[PIXEL_8x8]( m[l].p_fenc[0], FENC_STRIDE, m[l].p_fref[0], m[l].i_stride[0] );
612 x264_me_search( h, &m[l], mvc, i_mvc );
613 m[l].cost -= a->p_cost_mv[0]; // remove mvcost from skip mbs
615 m[l].cost += 5 * a->i_lambda;
618 CP32( fenc_mvs[l], m[l].mv );
619 *fenc_costs[l] = m[l].cost;
623 CP32( m[l].mv, fenc_mvs[l] );
624 m[l].cost = *fenc_costs[l];
626 COPY2_IF_LT( i_bcost, m[l].cost, list_used, l+1 );
629 if( b_bidir && ( M32( m[0].mv ) || M32( m[1].mv ) ) )
630 TRY_BIDIR( m[0].mv, m[1].mv, 5 );
633 if( !fenc->b_intra_calculated )
635 ALIGNED_ARRAY_16( pixel, edge,[36] );
636 pixel *pix = &pix1[8+FDEC_STRIDE - 1];
637 pixel *src = &fenc->lowres[0][i_pel_offset - 1];
638 const int intra_penalty = 5 * a->i_lambda;
641 memcpy( pix-FDEC_STRIDE, src-i_stride, 17 * sizeof(pixel) );
642 for( int i = 0; i < 8; i++ )
643 pix[i*FDEC_STRIDE] = src[i*i_stride];
646 h->pixf.intra_mbcmp_x3_8x8c( h->mb.pic.p_fenc[0], pix, satds );
647 int i_icost = X264_MIN3( satds[0], satds[1], satds[2] );
649 if( h->param.analyse.i_subpel_refine > 1 )
651 h->predict_8x8c[I_PRED_CHROMA_P]( pix );
652 int satd = h->pixf.mbcmp[PIXEL_8x8]( pix, FDEC_STRIDE, h->mb.pic.p_fenc[0], FENC_STRIDE );
653 i_icost = X264_MIN( i_icost, satd );
654 h->predict_8x8_filter( pix, edge, ALL_NEIGHBORS, ALL_NEIGHBORS );
655 for( int i = 3; i < 9; i++ )
657 h->predict_8x8[i]( pix, edge );
658 satd = h->pixf.mbcmp[PIXEL_8x8]( pix, FDEC_STRIDE, h->mb.pic.p_fenc[0], FENC_STRIDE );
659 i_icost = X264_MIN( i_icost, satd );
663 i_icost += intra_penalty + lowres_penalty;
664 fenc->i_intra_cost[i_mb_xy] = i_icost;
665 int i_icost_aq = i_icost;
666 if( h->param.rc.i_aq_mode )
667 i_icost_aq = (i_icost_aq * fenc->i_inv_qscale_factor[i_mb_xy] + 128) >> 8;
668 output_intra[ROW_SATD] += i_icost_aq;
669 if( b_frame_score_mb )
671 output_intra[COST_EST] += i_icost;
672 output_intra[COST_EST_AQ] += i_icost_aq;
675 i_bcost += lowres_penalty;
677 /* forbid intra-mbs in B-frames, because it's rare and not worth checking */
678 /* FIXME: Should we still forbid them now that we cache intra scores? */
681 int i_icost = fenc->i_intra_cost[i_mb_xy];
682 int b_intra = i_icost < i_bcost;
688 if( b_frame_score_mb )
689 output_inter[INTRA_MBS] += b_intra;
692 /* In an I-frame, we've already added the results above in the intra section. */
695 int i_bcost_aq = i_bcost;
696 if( h->param.rc.i_aq_mode )
697 i_bcost_aq = (i_bcost_aq * fenc->i_inv_qscale_factor[i_mb_xy] + 128) >> 8;
698 output_inter[ROW_SATD] += i_bcost_aq;
699 if( b_frame_score_mb )
701 /* Don't use AQ-weighted costs for slicetype decision, only for ratecontrol. */
702 output_inter[COST_EST] += i_bcost;
703 output_inter[COST_EST_AQ] += i_bcost_aq;
707 fenc->lowres_costs[b-p0][p1-b][i_mb_xy] = X264_MIN( i_bcost, LOWRES_COST_MASK ) + (list_used << LOWRES_COST_SHIFT);
712 (h->mb.i_mb_width > 2 && h->mb.i_mb_height > 2 ?\
713 (h->mb.i_mb_width - 2) * (h->mb.i_mb_height - 2) :\
714 h->mb.i_mb_width * h->mb.i_mb_height)
719 x264_mb_analysis_t *a;
720 x264_frame_t **frames;
724 int dist_scale_factor;
726 const x264_weight_t *w;
729 } x264_slicetype_slice_t;
731 static void x264_slicetype_slice_cost( x264_slicetype_slice_t *s )
735 /* Lowres lookahead goes backwards because the MVs are used as predictors in the main encode.
736 * This considerably improves MV prediction overall. */
738 /* The edge mbs seem to reduce the predictive quality of the
739 * whole frame's score, but are needed for a spatial distribution. */
740 int do_edges = h->param.rc.b_mb_tree || h->param.rc.i_vbv_buffer_size || h->mb.i_mb_width <= 2 || h->mb.i_mb_height <= 2;
742 int start_y = X264_MIN( h->i_threadslice_end - 1, h->mb.i_mb_height - 2 + do_edges );
743 int end_y = X264_MAX( h->i_threadslice_start, 1 - do_edges );
744 int start_x = h->mb.i_mb_width - 2 + do_edges;
745 int end_x = 1 - do_edges;
747 for( h->mb.i_mb_y = start_y; h->mb.i_mb_y >= end_y; h->mb.i_mb_y-- )
748 for( h->mb.i_mb_x = start_x; h->mb.i_mb_x >= end_x; h->mb.i_mb_x-- )
749 x264_slicetype_mb_cost( h, s->a, s->frames, s->p0, s->p1, s->b, s->dist_scale_factor,
750 s->do_search, s->w, s->output_inter, s->output_intra );
753 static int x264_slicetype_frame_cost( x264_t *h, x264_mb_analysis_t *a,
754 x264_frame_t **frames, int p0, int p1, int b,
755 int b_intra_penalty )
759 const x264_weight_t *w = x264_weight_none;
760 x264_frame_t *fenc = frames[b];
762 /* Check whether we already evaluated this frame
763 * If we have tried this frame as P, then we have also tried
764 * the preceding frames as B. (is this still true?) */
765 /* Also check that we already calculated the row SATDs for the current frame. */
766 if( fenc->i_cost_est[b-p0][p1-b] >= 0 && (!h->param.rc.i_vbv_buffer_size || fenc->i_row_satds[b-p0][p1-b][0] != -1) )
767 i_score = fenc->i_cost_est[b-p0][p1-b];
770 int dist_scale_factor = 128;
772 /* For each list, check to see whether we have lowres motion-searched this reference frame before. */
773 do_search[0] = b != p0 && fenc->lowres_mvs[0][b-p0-1][0][0] == 0x7FFF;
774 do_search[1] = b != p1 && fenc->lowres_mvs[1][p1-b-1][0][0] == 0x7FFF;
777 if( h->param.analyse.i_weighted_pred && b == p1 )
780 x264_weights_analyse( h, fenc, frames[p0], 1 );
783 fenc->lowres_mvs[0][b-p0-1][0][0] = 0;
785 if( do_search[1] ) fenc->lowres_mvs[1][p1-b-1][0][0] = 0;
788 dist_scale_factor = ( ((b-p0) << 8) + ((p1-p0) >> 1) ) / (p1-p0);
790 int output_buf_size = h->mb.i_mb_height + (NUM_INTS + PAD_SIZE) * h->param.i_lookahead_threads;
791 int *output_inter[X264_LOOKAHEAD_THREAD_MAX+1];
792 int *output_intra[X264_LOOKAHEAD_THREAD_MAX+1];
793 output_inter[0] = h->scratch_buffer2;
794 output_intra[0] = output_inter[0] + output_buf_size;
796 if( h->param.i_lookahead_threads > 1 )
798 x264_slicetype_slice_t s[X264_LOOKAHEAD_THREAD_MAX];
800 for( int i = 0; i < h->param.i_lookahead_threads; i++ )
802 x264_t *t = h->lookahead_thread[i];
804 /* FIXME move this somewhere else */
805 t->mb.i_me_method = h->mb.i_me_method;
806 t->mb.i_subpel_refine = h->mb.i_subpel_refine;
807 t->mb.b_chroma_me = h->mb.b_chroma_me;
809 s[i] = (x264_slicetype_slice_t){ t, a, frames, p0, p1, b, dist_scale_factor, do_search, w,
810 output_inter[i], output_intra[i] };
812 t->i_threadslice_start = ((h->mb.i_mb_height * i + h->param.i_lookahead_threads/2) / h->param.i_lookahead_threads);
813 t->i_threadslice_end = ((h->mb.i_mb_height * (i+1) + h->param.i_lookahead_threads/2) / h->param.i_lookahead_threads);
815 int thread_height = t->i_threadslice_end - t->i_threadslice_start;
816 int thread_output_size = thread_height + NUM_INTS;
817 memset( output_inter[i], 0, thread_output_size * sizeof(int) );
818 memset( output_intra[i], 0, thread_output_size * sizeof(int) );
819 output_inter[i][NUM_ROWS] = output_intra[i][NUM_ROWS] = thread_height;
821 output_inter[i+1] = output_inter[i] + thread_output_size + PAD_SIZE;
822 output_intra[i+1] = output_intra[i] + thread_output_size + PAD_SIZE;
824 x264_threadpool_run( h->lookaheadpool, (void*)x264_slicetype_slice_cost, &s[i] );
826 for( int i = 0; i < h->param.i_lookahead_threads; i++ )
827 x264_threadpool_wait( h->lookaheadpool, &s[i] );
831 h->i_threadslice_start = 0;
832 h->i_threadslice_end = h->mb.i_mb_height;
833 memset( output_inter[0], 0, (output_buf_size - PAD_SIZE) * sizeof(int) );
834 memset( output_intra[0], 0, (output_buf_size - PAD_SIZE) * sizeof(int) );
835 output_inter[0][NUM_ROWS] = output_intra[0][NUM_ROWS] = h->mb.i_mb_height;
836 x264_slicetype_slice_t s = (x264_slicetype_slice_t){ h, a, frames, p0, p1, b, dist_scale_factor, do_search, w,
837 output_inter[0], output_intra[0] };
838 x264_slicetype_slice_cost( &s );
841 /* Sum up accumulators */
843 fenc->i_intra_mbs[b-p0] = 0;
844 if( !fenc->b_intra_calculated )
846 fenc->i_cost_est[0][0] = 0;
847 fenc->i_cost_est_aq[0][0] = 0;
849 fenc->i_cost_est[b-p0][p1-b] = 0;
850 fenc->i_cost_est_aq[b-p0][p1-b] = 0;
852 int *row_satd_inter = fenc->i_row_satds[b-p0][p1-b];
853 int *row_satd_intra = fenc->i_row_satds[0][0];
854 for( int i = 0; i < h->param.i_lookahead_threads; i++ )
857 fenc->i_intra_mbs[b-p0] += output_inter[i][INTRA_MBS];
858 if( !fenc->b_intra_calculated )
860 fenc->i_cost_est[0][0] += output_intra[i][COST_EST];
861 fenc->i_cost_est_aq[0][0] += output_intra[i][COST_EST_AQ];
864 fenc->i_cost_est[b-p0][p1-b] += output_inter[i][COST_EST];
865 fenc->i_cost_est_aq[b-p0][p1-b] += output_inter[i][COST_EST_AQ];
867 if( h->param.rc.i_vbv_buffer_size )
869 int row_count = output_inter[i][NUM_ROWS];
870 memcpy( row_satd_inter, output_inter[i] + NUM_INTS, row_count * sizeof(int) );
871 if( !fenc->b_intra_calculated )
872 memcpy( row_satd_intra, output_intra[i] + NUM_INTS, row_count * sizeof(int) );
873 row_satd_inter += row_count;
874 row_satd_intra += row_count;
878 i_score = fenc->i_cost_est[b-p0][p1-b];
880 i_score = (uint64_t)i_score * 100 / (120 + h->param.i_bframe_bias);
882 fenc->b_intra_calculated = 1;
884 fenc->i_cost_est[b-p0][p1-b] = i_score;
888 if( b_intra_penalty )
890 // arbitrary penalty for I-blocks after B-frames
892 i_score += (uint64_t)i_score * fenc->i_intra_mbs[b-p0] / (nmb * 8);
897 /* If MB-tree changes the quantizers, we need to recalculate the frame cost without
898 * re-running lookahead. */
899 static int x264_slicetype_frame_cost_recalculate( x264_t *h, x264_frame_t **frames, int p0, int p1, int b )
902 int *row_satd = frames[b]->i_row_satds[b-p0][p1-b];
903 float *qp_offset = IS_X264_TYPE_B(frames[b]->i_type) ? frames[b]->f_qp_offset_aq : frames[b]->f_qp_offset;
905 for( h->mb.i_mb_y = h->mb.i_mb_height - 1; h->mb.i_mb_y >= 0; h->mb.i_mb_y-- )
907 row_satd[ h->mb.i_mb_y ] = 0;
908 for( h->mb.i_mb_x = h->mb.i_mb_width - 1; h->mb.i_mb_x >= 0; h->mb.i_mb_x-- )
910 int i_mb_xy = h->mb.i_mb_x + h->mb.i_mb_y*h->mb.i_mb_stride;
911 int i_mb_cost = frames[b]->lowres_costs[b-p0][p1-b][i_mb_xy] & LOWRES_COST_MASK;
912 float qp_adj = qp_offset[i_mb_xy];
913 i_mb_cost = (i_mb_cost * x264_exp2fix8(qp_adj) + 128) >> 8;
914 row_satd[ h->mb.i_mb_y ] += i_mb_cost;
915 if( (h->mb.i_mb_y > 0 && h->mb.i_mb_y < h->mb.i_mb_height - 1 &&
916 h->mb.i_mb_x > 0 && h->mb.i_mb_x < h->mb.i_mb_width - 1) ||
917 h->mb.i_mb_width <= 2 || h->mb.i_mb_height <= 2 )
919 i_score += i_mb_cost;
926 static void x264_macroblock_tree_finish( x264_t *h, x264_frame_t *frame, float average_duration, int ref0_distance )
928 int fps_factor = round( CLIP_DURATION(average_duration) / CLIP_DURATION(frame->f_duration) * 256 );
929 float weightdelta = 0.0;
930 if( ref0_distance && frame->f_weighted_cost_delta[ref0_distance-1] > 0 )
931 weightdelta = (1.0 - frame->f_weighted_cost_delta[ref0_distance-1]);
933 /* Allow the strength to be adjusted via qcompress, since the two
934 * concepts are very similar. */
935 float strength = 5.0f * (1.0f - h->param.rc.f_qcompress);
936 for( int mb_index = 0; mb_index < h->mb.i_mb_count; mb_index++ )
938 int intra_cost = (frame->i_intra_cost[mb_index] * frame->i_inv_qscale_factor[mb_index] + 128) >> 8;
941 int propagate_cost = (frame->i_propagate_cost[mb_index] * fps_factor + 128) >> 8;
942 float log2_ratio = x264_log2(intra_cost + propagate_cost) - x264_log2(intra_cost) + weightdelta;
943 frame->f_qp_offset[mb_index] = frame->f_qp_offset_aq[mb_index] - strength * log2_ratio;
948 static void x264_macroblock_tree_propagate( x264_t *h, x264_frame_t **frames, float average_duration, int p0, int p1, int b, int referenced )
950 uint16_t *ref_costs[2] = {frames[p0]->i_propagate_cost,frames[p1]->i_propagate_cost};
951 int dist_scale_factor = ( ((b-p0) << 8) + ((p1-p0) >> 1) ) / (p1-p0);
952 int i_bipred_weight = h->param.analyse.b_weighted_bipred ? 64 - (dist_scale_factor>>2) : 32;
953 int16_t (*mvs[2])[2] = { frames[b]->lowres_mvs[0][b-p0-1], frames[b]->lowres_mvs[1][p1-b-1] };
954 int bipred_weights[2] = {i_bipred_weight, 64 - i_bipred_weight};
955 int *buf = h->scratch_buffer;
956 uint16_t *propagate_cost = frames[b]->i_propagate_cost;
959 float fps_factor = CLIP_DURATION(frames[b]->f_duration) / CLIP_DURATION(average_duration);
961 /* For non-reffed frames the source costs are always zero, so just memset one row and re-use it. */
963 memset( frames[b]->i_propagate_cost, 0, h->mb.i_mb_width * sizeof(uint16_t) );
965 for( h->mb.i_mb_y = 0; h->mb.i_mb_y < h->mb.i_mb_height; h->mb.i_mb_y++ )
967 int mb_index = h->mb.i_mb_y*h->mb.i_mb_stride;
968 h->mc.mbtree_propagate_cost( buf, propagate_cost,
969 frames[b]->i_intra_cost+mb_index, frames[b]->lowres_costs[b-p0][p1-b]+mb_index,
970 frames[b]->i_inv_qscale_factor+mb_index, &fps_factor, h->mb.i_mb_width );
972 propagate_cost += h->mb.i_mb_width;
973 for( h->mb.i_mb_x = 0; h->mb.i_mb_x < h->mb.i_mb_width; h->mb.i_mb_x++, mb_index++ )
975 int propagate_amount = buf[h->mb.i_mb_x];
976 /* Don't propagate for an intra block. */
977 if( propagate_amount > 0 )
979 /* Access width-2 bitfield. */
980 int lists_used = frames[b]->lowres_costs[b-p0][p1-b][mb_index] >> LOWRES_COST_SHIFT;
981 /* Follow the MVs to the previous frame(s). */
982 for( int list = 0; list < 2; list++ )
983 if( (lists_used >> list)&1 )
985 #define CLIP_ADD(s,x) (s) = X264_MIN((s)+(x),(1<<16)-1)
986 int listamount = propagate_amount;
987 /* Apply bipred weighting. */
988 if( lists_used == 3 )
989 listamount = (listamount * bipred_weights[list] + 32) >> 6;
991 /* Early termination for simple case of mv0. */
992 if( !M32( mvs[list][mb_index] ) )
994 CLIP_ADD( ref_costs[list][mb_index], listamount );
998 int x = mvs[list][mb_index][0];
999 int y = mvs[list][mb_index][1];
1000 int mbx = (x>>5)+h->mb.i_mb_x;
1001 int mby = (y>>5)+h->mb.i_mb_y;
1002 int idx0 = mbx + mby * h->mb.i_mb_stride;
1003 int idx1 = idx0 + 1;
1004 int idx2 = idx0 + h->mb.i_mb_stride;
1005 int idx3 = idx0 + h->mb.i_mb_stride + 1;
1008 int idx0weight = (32-y)*(32-x);
1009 int idx1weight = (32-y)*x;
1010 int idx2weight = y*(32-x);
1011 int idx3weight = y*x;
1013 /* We could just clip the MVs, but pixels that lie outside the frame probably shouldn't
1015 if( mbx < h->mb.i_mb_width-1 && mby < h->mb.i_mb_height-1 && mbx >= 0 && mby >= 0 )
1017 CLIP_ADD( ref_costs[list][idx0], (listamount*idx0weight+512)>>10 );
1018 CLIP_ADD( ref_costs[list][idx1], (listamount*idx1weight+512)>>10 );
1019 CLIP_ADD( ref_costs[list][idx2], (listamount*idx2weight+512)>>10 );
1020 CLIP_ADD( ref_costs[list][idx3], (listamount*idx3weight+512)>>10 );
1022 else /* Check offsets individually */
1024 if( mbx < h->mb.i_mb_width && mby < h->mb.i_mb_height && mbx >= 0 && mby >= 0 )
1025 CLIP_ADD( ref_costs[list][idx0], (listamount*idx0weight+512)>>10 );
1026 if( mbx+1 < h->mb.i_mb_width && mby < h->mb.i_mb_height && mbx+1 >= 0 && mby >= 0 )
1027 CLIP_ADD( ref_costs[list][idx1], (listamount*idx1weight+512)>>10 );
1028 if( mbx < h->mb.i_mb_width && mby+1 < h->mb.i_mb_height && mbx >= 0 && mby+1 >= 0 )
1029 CLIP_ADD( ref_costs[list][idx2], (listamount*idx2weight+512)>>10 );
1030 if( mbx+1 < h->mb.i_mb_width && mby+1 < h->mb.i_mb_height && mbx+1 >= 0 && mby+1 >= 0 )
1031 CLIP_ADD( ref_costs[list][idx3], (listamount*idx3weight+512)>>10 );
1038 if( h->param.rc.i_vbv_buffer_size && h->param.rc.i_lookahead && referenced )
1039 x264_macroblock_tree_finish( h, frames[b], average_duration, b == p1 ? b - p0 : 0 );
1042 static void x264_macroblock_tree( x264_t *h, x264_mb_analysis_t *a, x264_frame_t **frames, int num_frames, int b_intra )
1045 int last_nonb, cur_nonb = 1;
1049 float total_duration = 0.0;
1050 for( int j = 0; j <= num_frames; j++ )
1051 total_duration += frames[j]->f_duration;
1052 float average_duration = total_duration / (num_frames + 1);
1057 x264_slicetype_frame_cost( h, a, frames, 0, 0, 0, 0 );
1059 while( i > 0 && frames[i]->i_type == X264_TYPE_B )
1063 /* Lookaheadless MB-tree is not a theoretically distinct case; the same extrapolation could
1064 * be applied to the end of a lookahead buffer of any size. However, it's most needed when
1065 * lookahead=0, so that's what's currently implemented. */
1066 if( !h->param.rc.i_lookahead )
1070 memset( frames[0]->i_propagate_cost, 0, h->mb.i_mb_count * sizeof(uint16_t) );
1071 memcpy( frames[0]->f_qp_offset, frames[0]->f_qp_offset_aq, h->mb.i_mb_count * sizeof(float) );
1074 XCHG( uint16_t*, frames[last_nonb]->i_propagate_cost, frames[0]->i_propagate_cost );
1075 memset( frames[0]->i_propagate_cost, 0, h->mb.i_mb_count * sizeof(uint16_t) );
1079 if( last_nonb < idx )
1081 memset( frames[last_nonb]->i_propagate_cost, 0, h->mb.i_mb_count * sizeof(uint16_t) );
1087 while( frames[cur_nonb]->i_type == X264_TYPE_B && cur_nonb > 0 )
1089 if( cur_nonb < idx )
1091 x264_slicetype_frame_cost( h, a, frames, cur_nonb, last_nonb, last_nonb, 0 );
1092 memset( frames[cur_nonb]->i_propagate_cost, 0, h->mb.i_mb_count * sizeof(uint16_t) );
1093 bframes = last_nonb - cur_nonb - 1;
1094 if( h->param.i_bframe_pyramid && bframes > 1 )
1096 int middle = (bframes + 1)/2 + cur_nonb;
1097 x264_slicetype_frame_cost( h, a, frames, cur_nonb, last_nonb, middle, 0 );
1098 memset( frames[middle]->i_propagate_cost, 0, h->mb.i_mb_count * sizeof(uint16_t) );
1099 while( i > cur_nonb )
1101 int p0 = i > middle ? middle : cur_nonb;
1102 int p1 = i < middle ? middle : last_nonb;
1105 x264_slicetype_frame_cost( h, a, frames, p0, p1, i, 0 );
1106 x264_macroblock_tree_propagate( h, frames, average_duration, p0, p1, i, 0 );
1110 x264_macroblock_tree_propagate( h, frames, average_duration, cur_nonb, last_nonb, middle, 1 );
1114 while( i > cur_nonb )
1116 x264_slicetype_frame_cost( h, a, frames, cur_nonb, last_nonb, i, 0 );
1117 x264_macroblock_tree_propagate( h, frames, average_duration, cur_nonb, last_nonb, i, 0 );
1121 x264_macroblock_tree_propagate( h, frames, average_duration, cur_nonb, last_nonb, last_nonb, 1 );
1122 last_nonb = cur_nonb;
1125 if( !h->param.rc.i_lookahead )
1127 x264_slicetype_frame_cost( h, a, frames, 0, last_nonb, last_nonb, 0 );
1128 x264_macroblock_tree_propagate( h, frames, average_duration, 0, last_nonb, last_nonb, 1 );
1129 XCHG( uint16_t*, frames[last_nonb]->i_propagate_cost, frames[0]->i_propagate_cost );
1132 x264_macroblock_tree_finish( h, frames[last_nonb], average_duration, last_nonb );
1133 if( h->param.i_bframe_pyramid && bframes > 1 && !h->param.rc.i_vbv_buffer_size )
1134 x264_macroblock_tree_finish( h, frames[last_nonb+(bframes+1)/2], average_duration, 0 );
1137 static int x264_vbv_frame_cost( x264_t *h, x264_mb_analysis_t *a, x264_frame_t **frames, int p0, int p1, int b )
1139 int cost = x264_slicetype_frame_cost( h, a, frames, p0, p1, b, 0 );
1140 if( h->param.rc.i_aq_mode )
1142 if( h->param.rc.b_mb_tree )
1143 return x264_slicetype_frame_cost_recalculate( h, frames, p0, p1, b );
1145 return frames[b]->i_cost_est_aq[b-p0][p1-b];
1150 static void x264_calculate_durations( x264_t *h, x264_frame_t *cur_frame, x264_frame_t *prev_frame, int64_t *i_cpb_delay, int64_t *i_coded_fields )
1152 cur_frame->i_cpb_delay = *i_cpb_delay;
1153 cur_frame->i_dpb_output_delay = cur_frame->i_field_cnt - *i_coded_fields;
1155 // add a correction term for frame reordering
1156 cur_frame->i_dpb_output_delay += h->sps->vui.i_num_reorder_frames*2;
1158 // fix possible negative dpb_output_delay because of pulldown changes and reordering
1159 if( cur_frame->i_dpb_output_delay < 0 )
1161 cur_frame->i_cpb_delay += cur_frame->i_dpb_output_delay;
1162 cur_frame->i_dpb_output_delay = 0;
1164 prev_frame->i_cpb_duration += cur_frame->i_dpb_output_delay;
1167 // don't reset cpb delay for IDR frames when using intra-refresh
1168 if( cur_frame->b_keyframe && !h->param.b_intra_refresh )
1171 *i_cpb_delay += cur_frame->i_duration;
1172 *i_coded_fields += cur_frame->i_duration;
1173 cur_frame->i_cpb_duration = cur_frame->i_duration;
1176 static void x264_vbv_lookahead( x264_t *h, x264_mb_analysis_t *a, x264_frame_t **frames, int num_frames, int keyframe )
1178 int last_nonb = 0, cur_nonb = 1, idx = 0;
1179 x264_frame_t *prev_frame = NULL;
1180 int prev_frame_idx = 0;
1181 while( cur_nonb < num_frames && frames[cur_nonb]->i_type == X264_TYPE_B )
1183 int next_nonb = keyframe ? last_nonb : cur_nonb;
1185 if( frames[cur_nonb]->i_coded_fields_lookahead >= 0 )
1187 h->i_coded_fields_lookahead = frames[cur_nonb]->i_coded_fields_lookahead;
1188 h->i_cpb_delay_lookahead = frames[cur_nonb]->i_cpb_delay_lookahead;
1191 while( cur_nonb < num_frames )
1193 /* P/I cost: This shouldn't include the cost of next_nonb */
1194 if( next_nonb != cur_nonb )
1196 int p0 = IS_X264_TYPE_I( frames[cur_nonb]->i_type ) ? cur_nonb : last_nonb;
1197 frames[next_nonb]->i_planned_satd[idx] = x264_vbv_frame_cost( h, a, frames, p0, cur_nonb, cur_nonb );
1198 frames[next_nonb]->i_planned_type[idx] = frames[cur_nonb]->i_type;
1199 frames[cur_nonb]->i_coded_fields_lookahead = h->i_coded_fields_lookahead;
1200 frames[cur_nonb]->i_cpb_delay_lookahead = h->i_cpb_delay_lookahead;
1201 x264_calculate_durations( h, frames[cur_nonb], prev_frame, &h->i_cpb_delay_lookahead, &h->i_coded_fields_lookahead );
1204 frames[next_nonb]->f_planned_cpb_duration[prev_frame_idx] = (double)prev_frame->i_cpb_duration *
1205 h->sps->vui.i_num_units_in_tick / h->sps->vui.i_time_scale;
1207 frames[next_nonb]->f_planned_cpb_duration[idx] = (double)frames[cur_nonb]->i_cpb_duration *
1208 h->sps->vui.i_num_units_in_tick / h->sps->vui.i_time_scale;
1209 prev_frame = frames[cur_nonb];
1210 prev_frame_idx = idx;
1213 /* Handle the B-frames: coded order */
1214 for( int i = last_nonb+1; i < cur_nonb; i++, idx++ )
1216 frames[next_nonb]->i_planned_satd[idx] = x264_vbv_frame_cost( h, a, frames, last_nonb, cur_nonb, i );
1217 frames[next_nonb]->i_planned_type[idx] = X264_TYPE_B;
1218 frames[i]->i_coded_fields_lookahead = h->i_coded_fields_lookahead;
1219 frames[i]->i_cpb_delay_lookahead = h->i_cpb_delay_lookahead;
1220 x264_calculate_durations( h, frames[i], prev_frame, &h->i_cpb_delay_lookahead, &h->i_coded_fields_lookahead );
1223 frames[next_nonb]->f_planned_cpb_duration[prev_frame_idx] = (double)prev_frame->i_cpb_duration *
1224 h->sps->vui.i_num_units_in_tick / h->sps->vui.i_time_scale;
1226 frames[next_nonb]->f_planned_cpb_duration[idx] = (double)frames[i]->i_cpb_duration *
1227 h->sps->vui.i_num_units_in_tick / h->sps->vui.i_time_scale;
1228 prev_frame = frames[i];
1229 prev_frame_idx = idx;
1231 last_nonb = cur_nonb;
1233 while( cur_nonb <= num_frames && frames[cur_nonb]->i_type == X264_TYPE_B )
1236 frames[next_nonb]->i_planned_type[idx] = X264_TYPE_AUTO;
1239 static int x264_slicetype_path_cost( x264_t *h, x264_mb_analysis_t *a, x264_frame_t **frames, char *path, int threshold )
1244 path--; /* Since the 1st path element is really the second frame */
1248 /* Find the location of the next P-frame. */
1249 while( path[next_p] != 'P' )
1252 /* Add the cost of the P-frame found above */
1253 cost += x264_slicetype_frame_cost( h, a, frames, cur_p, next_p, next_p, 0 );
1254 /* Early terminate if the cost we have found is larger than the best path cost so far */
1255 if( cost > threshold )
1258 if( h->param.i_bframe_pyramid && next_p - cur_p > 2 )
1260 int middle = cur_p + (next_p - cur_p)/2;
1261 cost += x264_slicetype_frame_cost( h, a, frames, cur_p, next_p, middle, 0 );
1262 for( int next_b = loc; next_b < middle && cost < threshold; next_b++ )
1263 cost += x264_slicetype_frame_cost( h, a, frames, cur_p, middle, next_b, 0 );
1264 for( int next_b = middle+1; next_b < next_p && cost < threshold; next_b++ )
1265 cost += x264_slicetype_frame_cost( h, a, frames, middle, next_p, next_b, 0 );
1268 for( int next_b = loc; next_b < next_p && cost < threshold; next_b++ )
1269 cost += x264_slicetype_frame_cost( h, a, frames, cur_p, next_p, next_b, 0 );
1277 /* Viterbi/trellis slicetype decision algorithm. */
1278 /* Uses strings due to the fact that the speed of the control functions is
1279 negligible compared to the cost of running slicetype_frame_cost, and because
1280 it makes debugging easier. */
1281 static void x264_slicetype_path( x264_t *h, x264_mb_analysis_t *a, x264_frame_t **frames, int length, char (*best_paths)[X264_LOOKAHEAD_MAX+1] )
1283 char paths[2][X264_LOOKAHEAD_MAX+1];
1284 int num_paths = X264_MIN( h->param.i_bframe+1, length );
1285 int best_cost = COST_MAX;
1288 /* Iterate over all currently possible paths */
1289 for( int path = 0; path < num_paths; path++ )
1291 /* Add suffixes to the current path */
1292 int len = length - (path + 1);
1293 memcpy( paths[idx], best_paths[len % (X264_BFRAME_MAX+1)], len );
1294 memset( paths[idx]+len, 'B', path );
1295 strcpy( paths[idx]+len+path, "P" );
1297 /* Calculate the actual cost of the current path */
1298 int cost = x264_slicetype_path_cost( h, a, frames, paths[idx], best_cost );
1299 if( cost < best_cost )
1306 /* Store the best path. */
1307 memcpy( best_paths[length % (X264_BFRAME_MAX+1)], paths[idx^1], length );
1310 static int scenecut_internal( x264_t *h, x264_mb_analysis_t *a, x264_frame_t **frames, int p0, int p1, int real_scenecut )
1312 x264_frame_t *frame = frames[p1];
1314 /* Don't do scenecuts on the right view of a frame-packed video. */
1315 if( real_scenecut && h->param.i_frame_packing == 5 && (frame->i_frame&1) )
1318 x264_slicetype_frame_cost( h, a, frames, p0, p1, p1, 0 );
1320 int icost = frame->i_cost_est[0][0];
1321 int pcost = frame->i_cost_est[p1-p0][0];
1323 int i_gop_size = frame->i_frame - h->lookahead->i_last_keyframe;
1324 float f_thresh_max = h->param.i_scenecut_threshold / 100.0;
1325 /* magic numbers pulled out of thin air */
1326 float f_thresh_min = f_thresh_max * 0.25;
1329 if( h->param.i_keyint_min == h->param.i_keyint_max )
1330 f_thresh_min = f_thresh_max;
1331 if( i_gop_size <= h->param.i_keyint_min / 4 || h->param.b_intra_refresh )
1332 f_bias = f_thresh_min / 4;
1333 else if( i_gop_size <= h->param.i_keyint_min )
1334 f_bias = f_thresh_min * i_gop_size / h->param.i_keyint_min;
1337 f_bias = f_thresh_min
1338 + ( f_thresh_max - f_thresh_min )
1339 * ( i_gop_size - h->param.i_keyint_min )
1340 / ( h->param.i_keyint_max - h->param.i_keyint_min );
1343 res = pcost >= (1.0 - f_bias) * icost;
1344 if( res && real_scenecut )
1346 int imb = frame->i_intra_mbs[p1-p0];
1347 int pmb = NUM_MBS - imb;
1348 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",
1350 icost, pcost, 1. - (double)pcost / icost,
1351 f_bias, i_gop_size, imb, pmb );
1356 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, int i_max_search )
1358 /* Only do analysis during a normal scenecut check. */
1359 if( real_scenecut && h->param.i_bframe )
1361 int origmaxp1 = p0 + 1;
1362 /* Look ahead to avoid coding short flashes as scenecuts. */
1363 if( h->param.i_bframe_adaptive == X264_B_ADAPT_TRELLIS )
1364 /* Don't analyse any more frames than the trellis would have covered. */
1365 origmaxp1 += h->param.i_bframe;
1368 int maxp1 = X264_MIN( origmaxp1, num_frames );
1370 /* Where A and B are scenes: AAAAAABBBAAAAAA
1371 * If BBB is shorter than (maxp1-p0), it is detected as a flash
1372 * and not considered a scenecut. */
1373 for( int curp1 = p1; curp1 <= maxp1; curp1++ )
1374 if( !scenecut_internal( h, a, frames, p0, curp1, 0 ) )
1375 /* Any frame in between p0 and cur_p1 cannot be a real scenecut. */
1376 for( int i = curp1; i > p0; i-- )
1377 frames[i]->b_scenecut = 0;
1379 /* Where A-F are scenes: AAAAABBCCDDEEFFFFFF
1380 * If each of BB ... EE are shorter than (maxp1-p0), they are
1381 * detected as flashes and not considered scenecuts.
1382 * Instead, the first F frame becomes a scenecut.
1383 * If the video ends before F, no frame becomes a scenecut. */
1384 for( int curp0 = p0; curp0 <= maxp1; curp0++ )
1385 if( origmaxp1 > i_max_search || (curp0 < maxp1 && scenecut_internal( h, a, frames, curp0, maxp1, 0 )) )
1386 /* If cur_p0 is the p0 of a scenecut, it cannot be the p1 of a scenecut. */
1387 frames[curp0]->b_scenecut = 0;
1390 /* Ignore frames that are part of a flash, i.e. cannot be real scenecuts. */
1391 if( !frames[p1]->b_scenecut )
1393 return scenecut_internal( h, a, frames, p0, p1, real_scenecut );
1396 void x264_slicetype_analyse( x264_t *h, int keyframe )
1398 x264_mb_analysis_t a;
1399 x264_frame_t *frames[X264_LOOKAHEAD_MAX+3] = { NULL, };
1400 int num_frames, orig_num_frames, keyint_limit, framecnt;
1401 int i_mb_count = NUM_MBS;
1402 int cost1p0, cost2p0, cost1b1, cost2p1;
1403 int i_max_search = X264_MIN( h->lookahead->next.i_size, X264_LOOKAHEAD_MAX );
1404 int vbv_lookahead = h->param.rc.i_vbv_buffer_size && h->param.rc.i_lookahead;
1405 if( h->param.b_deterministic )
1406 i_max_search = X264_MIN( i_max_search, h->lookahead->i_slicetype_length + !keyframe );
1408 assert( h->frames.b_have_lowres );
1410 if( !h->lookahead->last_nonb )
1412 frames[0] = h->lookahead->last_nonb;
1413 for( framecnt = 0; framecnt < i_max_search && h->lookahead->next.list[framecnt]->i_type == X264_TYPE_AUTO; framecnt++ )
1414 frames[framecnt+1] = h->lookahead->next.list[framecnt];
1416 x264_lowres_context_init( h, &a );
1420 if( h->param.rc.b_mb_tree )
1421 x264_macroblock_tree( h, &a, frames, 0, keyframe );
1425 keyint_limit = h->param.i_keyint_max - frames[0]->i_frame + h->lookahead->i_last_keyframe - 1;
1426 orig_num_frames = num_frames = h->param.b_intra_refresh ? framecnt : X264_MIN( framecnt, keyint_limit );
1428 /* This is important psy-wise: if we have a non-scenecut keyframe,
1429 * there will be significant visual artifacts if the frames just before
1430 * go down in quality due to being referenced less, despite it being
1431 * more RD-optimal. */
1432 if( (h->param.analyse.b_psy && h->param.rc.b_mb_tree) || vbv_lookahead )
1433 num_frames = framecnt;
1434 else if( h->param.b_open_gop && num_frames < framecnt )
1436 else if( num_frames == 0 )
1438 frames[1]->i_type = X264_TYPE_I;
1442 int num_bframes = 0;
1443 int num_analysed_frames = num_frames;
1445 if( h->param.i_scenecut_threshold && scenecut( h, &a, frames, 0, 1, 1, orig_num_frames, i_max_search ) )
1447 frames[1]->i_type = X264_TYPE_I;
1451 if( h->param.i_bframe )
1453 if( h->param.i_bframe_adaptive == X264_B_ADAPT_TRELLIS )
1455 if( num_frames > 1 )
1457 char best_paths[X264_BFRAME_MAX+1][X264_LOOKAHEAD_MAX+1] = {"","P"};
1458 int best_path_index = num_frames % (X264_BFRAME_MAX+1);
1460 /* Perform the frametype analysis. */
1461 for( int j = 2; j <= num_frames; j++ )
1462 x264_slicetype_path( h, &a, frames, j, best_paths );
1464 num_bframes = strspn( best_paths[best_path_index], "B" );
1465 /* Load the results of the analysis into the frame types. */
1466 for( int j = 1; j < num_frames; j++ )
1467 frames[j]->i_type = best_paths[best_path_index][j-1] == 'B' ? X264_TYPE_B : X264_TYPE_P;
1469 frames[num_frames]->i_type = X264_TYPE_P;
1471 else if( h->param.i_bframe_adaptive == X264_B_ADAPT_FAST )
1473 for( int i = 0; i <= num_frames-2; )
1475 cost2p1 = x264_slicetype_frame_cost( h, &a, frames, i+0, i+2, i+2, 1 );
1476 if( frames[i+2]->i_intra_mbs[2] > i_mb_count / 2 )
1478 frames[i+1]->i_type = X264_TYPE_P;
1479 frames[i+2]->i_type = X264_TYPE_P;
1484 cost1b1 = x264_slicetype_frame_cost( h, &a, frames, i+0, i+2, i+1, 0 );
1485 cost1p0 = x264_slicetype_frame_cost( h, &a, frames, i+0, i+1, i+1, 0 );
1486 cost2p0 = x264_slicetype_frame_cost( h, &a, frames, i+1, i+2, i+2, 0 );
1488 if( cost1p0 + cost2p0 < cost1b1 + cost2p1 )
1490 frames[i+1]->i_type = X264_TYPE_P;
1495 // arbitrary and untuned
1496 #define INTER_THRESH 300
1497 #define P_SENS_BIAS (50 - h->param.i_bframe_bias)
1498 frames[i+1]->i_type = X264_TYPE_B;
1501 for( j = i+2; j <= X264_MIN( i+h->param.i_bframe, num_frames-1 ); j++ )
1503 int pthresh = X264_MAX(INTER_THRESH - P_SENS_BIAS * (j-i-1), INTER_THRESH/10);
1504 int pcost = x264_slicetype_frame_cost( h, &a, frames, i+0, j+1, j+1, 1 );
1505 if( pcost > pthresh*i_mb_count || frames[j+1]->i_intra_mbs[j-i+1] > i_mb_count/3 )
1507 frames[j]->i_type = X264_TYPE_B;
1509 frames[j]->i_type = X264_TYPE_P;
1512 frames[num_frames]->i_type = X264_TYPE_P;
1514 while( num_bframes < num_frames && frames[num_bframes+1]->i_type == X264_TYPE_B )
1519 num_bframes = X264_MIN(num_frames-1, h->param.i_bframe);
1520 for( int j = 1; j < num_frames; j++ )
1521 frames[j]->i_type = (j%(num_bframes+1)) ? X264_TYPE_B : X264_TYPE_P;
1522 frames[num_frames]->i_type = X264_TYPE_P;
1525 /* Check scenecut on the first minigop. */
1526 for( int j = 1; j < num_bframes+1; j++ )
1527 if( h->param.i_scenecut_threshold && scenecut( h, &a, frames, j, j+1, 0, orig_num_frames, i_max_search ) )
1529 frames[j]->i_type = X264_TYPE_P;
1530 num_analysed_frames = j;
1534 reset_start = keyframe ? 1 : X264_MIN( num_bframes+2, num_analysed_frames+1 );
1538 for( int j = 1; j <= num_frames; j++ )
1539 frames[j]->i_type = X264_TYPE_P;
1540 reset_start = !keyframe + 1;
1544 /* Perform the actual macroblock tree analysis.
1545 * Don't go farther than the maximum keyframe interval; this helps in short GOPs. */
1546 if( h->param.rc.b_mb_tree )
1547 x264_macroblock_tree( h, &a, frames, X264_MIN(num_frames, h->param.i_keyint_max), keyframe );
1549 /* Enforce keyframe limit. */
1550 if( !h->param.b_intra_refresh )
1551 for( int i = keyint_limit+1; i <= num_frames; i += h->param.i_keyint_max )
1553 frames[i]->i_type = X264_TYPE_I;
1554 reset_start = X264_MIN( reset_start, i+1 );
1555 if( h->param.b_open_gop && h->param.b_bluray_compat )
1556 while( IS_X264_TYPE_B( frames[i-1]->i_type ) )
1561 x264_vbv_lookahead( h, &a, frames, num_frames, keyframe );
1563 /* Restore frametypes for all frames that haven't actually been decided yet. */
1564 for( int j = reset_start; j <= num_frames; j++ )
1565 frames[j]->i_type = X264_TYPE_AUTO;
1568 void x264_slicetype_decide( x264_t *h )
1570 x264_frame_t *frames[X264_BFRAME_MAX+2];
1575 if( !h->lookahead->next.i_size )
1578 int lookahead_size = h->lookahead->next.i_size;
1580 for( int i = 0; i < h->lookahead->next.i_size; i++ )
1582 if( h->param.b_vfr_input )
1584 if( lookahead_size-- > 1 )
1585 h->lookahead->next.list[i]->i_duration = 2 * (h->lookahead->next.list[i+1]->i_pts - h->lookahead->next.list[i]->i_pts);
1587 h->lookahead->next.list[i]->i_duration = h->i_prev_duration;
1590 h->lookahead->next.list[i]->i_duration = delta_tfi_divisor[h->lookahead->next.list[i]->i_pic_struct];
1591 h->i_prev_duration = h->lookahead->next.list[i]->i_duration;
1592 h->lookahead->next.list[i]->f_duration = (double)h->lookahead->next.list[i]->i_duration
1593 * h->sps->vui.i_num_units_in_tick
1594 / h->sps->vui.i_time_scale;
1596 if( h->lookahead->next.list[i]->i_frame > h->i_disp_fields_last_frame && lookahead_size > 0 )
1598 h->lookahead->next.list[i]->i_field_cnt = h->i_disp_fields;
1599 h->i_disp_fields += h->lookahead->next.list[i]->i_duration;
1600 h->i_disp_fields_last_frame = h->lookahead->next.list[i]->i_frame;
1602 else if( lookahead_size == 0 )
1604 h->lookahead->next.list[i]->i_field_cnt = h->i_disp_fields;
1605 h->lookahead->next.list[i]->i_duration = h->i_prev_duration;
1609 if( h->param.rc.b_stat_read )
1611 /* Use the frame types from the first pass */
1612 for( int i = 0; i < h->lookahead->next.i_size; i++ )
1613 h->lookahead->next.list[i]->i_type =
1614 x264_ratecontrol_slice_type( h, h->lookahead->next.list[i]->i_frame );
1616 else if( (h->param.i_bframe && h->param.i_bframe_adaptive)
1617 || h->param.i_scenecut_threshold
1618 || h->param.rc.b_mb_tree
1619 || (h->param.rc.i_vbv_buffer_size && h->param.rc.i_lookahead) )
1620 x264_slicetype_analyse( h, 0 );
1622 for( bframes = 0, brefs = 0;; bframes++ )
1624 frm = h->lookahead->next.list[bframes];
1625 if( frm->i_type == X264_TYPE_BREF && h->param.i_bframe_pyramid < X264_B_PYRAMID_NORMAL &&
1626 brefs == h->param.i_bframe_pyramid )
1628 frm->i_type = X264_TYPE_B;
1629 x264_log( h, X264_LOG_WARNING, "B-ref at frame %d incompatible with B-pyramid %s \n",
1630 frm->i_frame, x264_b_pyramid_names[h->param.i_bframe_pyramid] );
1632 /* pyramid with multiple B-refs needs a big enough dpb that the preceding P-frame stays available.
1633 smaller dpb could be supported by smart enough use of mmco, but it's easier just to forbid it. */
1634 else if( frm->i_type == X264_TYPE_BREF && h->param.i_bframe_pyramid == X264_B_PYRAMID_NORMAL &&
1635 brefs && h->param.i_frame_reference <= (brefs+3) )
1637 frm->i_type = X264_TYPE_B;
1638 x264_log( h, X264_LOG_WARNING, "B-ref at frame %d incompatible with B-pyramid %s and %d reference frames\n",
1639 frm->i_frame, x264_b_pyramid_names[h->param.i_bframe_pyramid], h->param.i_frame_reference );
1642 if( frm->i_type == X264_TYPE_KEYFRAME )
1643 frm->i_type = h->param.b_open_gop ? X264_TYPE_I : X264_TYPE_IDR;
1645 /* Limit GOP size */
1646 if( (!h->param.b_intra_refresh || frm->i_frame == 0) && frm->i_frame - h->lookahead->i_last_keyframe >= h->param.i_keyint_max )
1648 if( frm->i_type == X264_TYPE_AUTO || frm->i_type == X264_TYPE_I )
1649 frm->i_type = h->param.b_open_gop && h->lookahead->i_last_keyframe >= 0 ? X264_TYPE_I : X264_TYPE_IDR;
1650 int warn = frm->i_type != X264_TYPE_IDR;
1651 if( warn && h->param.b_open_gop )
1652 warn &= frm->i_type != X264_TYPE_I;
1654 x264_log( h, X264_LOG_WARNING, "specified frame type (%d) at %d is not compatible with keyframe interval\n", frm->i_type, frm->i_frame );
1656 if( frm->i_type == X264_TYPE_I && frm->i_frame - h->lookahead->i_last_keyframe >= h->param.i_keyint_min )
1658 if( h->param.b_open_gop )
1660 h->lookahead->i_last_keyframe = frm->i_frame; // Use display order
1661 if( h->param.b_bluray_compat )
1662 h->lookahead->i_last_keyframe -= bframes; // Use bluray order
1663 frm->b_keyframe = 1;
1666 frm->i_type = X264_TYPE_IDR;
1668 if( frm->i_type == X264_TYPE_IDR )
1671 h->lookahead->i_last_keyframe = frm->i_frame;
1672 frm->b_keyframe = 1;
1676 h->lookahead->next.list[bframes]->i_type = X264_TYPE_P;
1680 if( bframes == h->param.i_bframe ||
1681 !h->lookahead->next.list[bframes+1] )
1683 if( IS_X264_TYPE_B( frm->i_type ) )
1684 x264_log( h, X264_LOG_WARNING, "specified frame type is not compatible with max B-frames\n" );
1685 if( frm->i_type == X264_TYPE_AUTO
1686 || IS_X264_TYPE_B( frm->i_type ) )
1687 frm->i_type = X264_TYPE_P;
1690 if( frm->i_type == X264_TYPE_BREF )
1693 if( frm->i_type == X264_TYPE_AUTO )
1694 frm->i_type = X264_TYPE_B;
1696 else if( !IS_X264_TYPE_B( frm->i_type ) ) break;
1700 h->lookahead->next.list[bframes-1]->b_last_minigop_bframe = 1;
1701 h->lookahead->next.list[bframes]->i_bframes = bframes;
1703 /* insert a bref into the sequence */
1704 if( h->param.i_bframe_pyramid && bframes > 1 && !brefs )
1706 h->lookahead->next.list[bframes/2]->i_type = X264_TYPE_BREF;
1710 /* calculate the frame costs ahead of time for x264_rc_analyse_slice while we still have lowres */
1711 if( h->param.rc.i_rc_method != X264_RC_CQP )
1713 x264_mb_analysis_t a;
1715 p1 = b = bframes + 1;
1717 x264_lowres_context_init( h, &a );
1719 frames[0] = h->lookahead->last_nonb;
1720 memcpy( &frames[1], h->lookahead->next.list, (bframes+1) * sizeof(x264_frame_t*) );
1721 if( IS_X264_TYPE_I( h->lookahead->next.list[bframes]->i_type ) )
1726 x264_slicetype_frame_cost( h, &a, frames, p0, p1, b, 0 );
1728 if( (p0 != p1 || bframes) && h->param.rc.i_vbv_buffer_size )
1730 /* We need the intra costs for row SATDs. */
1731 x264_slicetype_frame_cost( h, &a, frames, b, b, b, 0 );
1733 /* We need B-frame costs for row SATDs. */
1735 for( b = 1; b <= bframes; b++ )
1737 if( frames[b]->i_type == X264_TYPE_B )
1738 for( p1 = b; frames[p1]->i_type == X264_TYPE_B; )
1742 x264_slicetype_frame_cost( h, &a, frames, p0, p1, b, 0 );
1743 if( frames[b]->i_type == X264_TYPE_BREF )
1749 /* Analyse for weighted P frames */
1750 if( !h->param.rc.b_stat_read && h->lookahead->next.list[bframes]->i_type == X264_TYPE_P
1751 && h->param.analyse.i_weighted_pred >= X264_WEIGHTP_SIMPLE )
1754 x264_weights_analyse( h, h->lookahead->next.list[bframes], h->lookahead->last_nonb, 0 );
1757 /* shift sequence to coded order.
1758 use a small temporary list to avoid shifting the entire next buffer around */
1759 int i_coded = h->lookahead->next.list[0]->i_frame;
1762 int idx_list[] = { brefs+1, 1 };
1763 for( int i = 0; i < bframes; i++ )
1765 int idx = idx_list[h->lookahead->next.list[i]->i_type == X264_TYPE_BREF]++;
1766 frames[idx] = h->lookahead->next.list[i];
1767 frames[idx]->i_reordered_pts = h->lookahead->next.list[idx]->i_pts;
1769 frames[0] = h->lookahead->next.list[bframes];
1770 frames[0]->i_reordered_pts = h->lookahead->next.list[0]->i_pts;
1771 memcpy( h->lookahead->next.list, frames, (bframes+1) * sizeof(x264_frame_t*) );
1774 for( int i = 0; i <= bframes; i++ )
1776 h->lookahead->next.list[i]->i_coded = i_coded++;
1779 x264_calculate_durations( h, h->lookahead->next.list[i], h->lookahead->next.list[i-1], &h->i_cpb_delay, &h->i_coded_fields );
1780 h->lookahead->next.list[0]->f_planned_cpb_duration[i-1] = (double)h->lookahead->next.list[i-1]->i_cpb_duration *
1781 h->sps->vui.i_num_units_in_tick / h->sps->vui.i_time_scale;
1784 x264_calculate_durations( h, h->lookahead->next.list[i], NULL, &h->i_cpb_delay, &h->i_coded_fields );
1786 h->lookahead->next.list[0]->f_planned_cpb_duration[i] = (double)h->lookahead->next.list[i]->i_cpb_duration *
1787 h->sps->vui.i_num_units_in_tick / h->sps->vui.i_time_scale;
1791 int x264_rc_analyse_slice( x264_t *h )
1797 if( IS_X264_TYPE_I(h->fenc->i_type) )
1799 else if( h->fenc->i_type == X264_TYPE_P )
1800 p1 = b = h->fenc->i_bframes + 1;
1803 p1 = (h->fref_nearest[1]->i_poc - h->fref_nearest[0]->i_poc)/2;
1804 b = (h->fenc->i_poc - h->fref_nearest[0]->i_poc)/2;
1806 /* We don't need to assign p0/p1 since we are not performing any real analysis here. */
1807 x264_frame_t **frames = &h->fenc - b;
1809 /* cost should have been already calculated by x264_slicetype_decide */
1810 cost = frames[b]->i_cost_est[b-p0][p1-b];
1811 assert( cost >= 0 );
1813 if( h->param.rc.b_mb_tree && !h->param.rc.b_stat_read )
1815 cost = x264_slicetype_frame_cost_recalculate( h, frames, p0, p1, b );
1816 if( b && h->param.rc.i_vbv_buffer_size )
1817 x264_slicetype_frame_cost_recalculate( h, frames, b, b, b );
1819 /* In AQ, use the weighted score instead. */
1820 else if( h->param.rc.i_aq_mode )
1821 cost = frames[b]->i_cost_est_aq[b-p0][p1-b];
1823 h->fenc->i_row_satd = h->fenc->i_row_satds[b-p0][p1-b];
1824 h->fdec->i_row_satd = h->fdec->i_row_satds[b-p0][p1-b];
1825 h->fdec->i_satd = cost;
1826 memcpy( h->fdec->i_row_satd, h->fenc->i_row_satd, h->mb.i_mb_height * sizeof(int) );
1827 if( !IS_X264_TYPE_I(h->fenc->i_type) )
1828 memcpy( h->fdec->i_row_satds[0][0], h->fenc->i_row_satds[0][0], h->mb.i_mb_height * sizeof(int) );
1830 if( h->param.b_intra_refresh && h->param.rc.i_vbv_buffer_size && h->fenc->i_type == X264_TYPE_P )
1832 int ip_factor = 256 * h->param.rc.f_ip_factor; /* fix8 */
1833 for( int y = 0; y < h->mb.i_mb_height; y++ )
1835 int mb_xy = y * h->mb.i_mb_stride + h->fdec->i_pir_start_col;
1836 for( int x = h->fdec->i_pir_start_col; x <= h->fdec->i_pir_end_col; x++, mb_xy++ )
1838 int intra_cost = (h->fenc->i_intra_cost[mb_xy] * ip_factor + 128) >> 8;
1839 int inter_cost = h->fenc->lowres_costs[b-p0][p1-b][mb_xy] & LOWRES_COST_MASK;
1840 int diff = intra_cost - inter_cost;
1841 if( h->param.rc.i_aq_mode )
1842 h->fdec->i_row_satd[y] += (diff * frames[b]->i_inv_qscale_factor[mb_xy] + 128) >> 8;
1844 h->fdec->i_row_satd[y] += diff;
1851 for( int y = 0; y < h->mb.i_mb_height; y++ )
1852 h->fdec->i_row_satd[y] >>= (BIT_DEPTH - 8);
1854 return cost >> (BIT_DEPTH - 8);