1 /*****************************************************************************
2 * slicetype.c: lookahead analysis
3 *****************************************************************************
4 * Copyright (C) 2005-2016 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 );
38 void x264_weights_analyse( x264_t *h, x264_frame_t *fenc, x264_frame_t *ref, int b_lookahead );
41 int x264_opencl_lowres_init( x264_t *h, x264_frame_t *fenc, int lambda );
42 int x264_opencl_motionsearch( x264_t *h, x264_frame_t **frames, int b, int ref, int b_islist1, int lambda, const x264_weight_t *w );
43 int x264_opencl_finalize_cost( x264_t *h, int lambda, x264_frame_t **frames, int p0, int p1, int b, int dist_scale_factor );
44 int x264_opencl_precalculate_frame_cost( x264_t *h, x264_frame_t **frames, int lambda, int p0, int p1, int b );
45 void x264_opencl_flush( x264_t *h );
46 void x264_opencl_slicetype_prep( x264_t *h, x264_frame_t **frames, int num_frames, int lambda );
47 void x264_opencl_slicetype_end( x264_t *h );
50 static void x264_lowres_context_init( x264_t *h, x264_mb_analysis_t *a )
52 a->i_qp = X264_LOOKAHEAD_QP;
53 a->i_lambda = x264_lambda_tab[ a->i_qp ];
54 x264_mb_analyse_load_costs( h, a );
55 if( h->param.analyse.i_subpel_refine > 1 )
57 h->mb.i_me_method = X264_MIN( X264_ME_HEX, h->param.analyse.i_me_method );
58 h->mb.i_subpel_refine = 4;
62 h->mb.i_me_method = X264_ME_DIA;
63 h->mb.i_subpel_refine = 2;
65 h->mb.b_chroma_me = 0;
68 /* makes a non-h264 weight (i.e. fix7), into an h264 weight */
69 static void x264_weight_get_h264( int weight_nonh264, int offset, x264_weight_t *w )
73 w->i_scale = weight_nonh264;
74 while( w->i_denom > 0 && (w->i_scale > 127) )
79 w->i_scale = X264_MIN( w->i_scale, 127 );
82 static NOINLINE pixel *x264_weight_cost_init_luma( x264_t *h, x264_frame_t *fenc, x264_frame_t *ref, pixel *dest )
84 int ref0_distance = fenc->i_frame - ref->i_frame - 1;
85 /* Note: this will never run during lookahead as weights_analyse is only called if no
86 * motion search has been done. */
87 if( fenc->lowres_mvs[0][ref0_distance][0][0] != 0x7FFF )
89 int i_stride = fenc->i_stride_lowres;
90 int i_lines = fenc->i_lines_lowres;
91 int i_width = fenc->i_width_lowres;
95 for( int y = 0; y < i_lines; y += 8, p += i_stride*8 )
96 for( int x = 0; x < i_width; x += 8, i_mb_xy++ )
98 int mvx = fenc->lowres_mvs[0][ref0_distance][i_mb_xy][0];
99 int mvy = fenc->lowres_mvs[0][ref0_distance][i_mb_xy][1];
100 h->mc.mc_luma( p+x, i_stride, ref->lowres, i_stride,
101 mvx+(x<<2), mvy+(y<<2), 8, 8, x264_weight_none );
107 return ref->lowres[0];
110 /* How data is organized for 4:2:0/4:2:2 chroma weightp:
113 * fenc = ref + offset
114 * v = u + stride * chroma height */
116 static NOINLINE void x264_weight_cost_init_chroma( x264_t *h, x264_frame_t *fenc, x264_frame_t *ref, pixel *dstu, pixel *dstv )
118 int ref0_distance = fenc->i_frame - ref->i_frame - 1;
119 int i_stride = fenc->i_stride[1];
120 int i_offset = i_stride / 2;
121 int i_lines = fenc->i_lines[1];
122 int i_width = fenc->i_width[1];
123 int v_shift = CHROMA_V_SHIFT;
124 int cw = 8*h->mb.i_mb_width;
125 int ch = 16*h->mb.i_mb_height >> v_shift;
126 int height = 16 >> v_shift;
128 if( fenc->lowres_mvs[0][ref0_distance][0][0] != 0x7FFF )
130 x264_frame_expand_border_chroma( h, ref, 1 );
131 for( int y = 0, mb_xy = 0, pel_offset_y = 0; y < i_lines; y += height, pel_offset_y = y*i_stride )
132 for( int x = 0, pel_offset_x = 0; x < i_width; x += 8, mb_xy++, pel_offset_x += 8 )
134 pixel *pixu = dstu + pel_offset_y + pel_offset_x;
135 pixel *pixv = dstv + pel_offset_y + pel_offset_x;
136 pixel *src1 = ref->plane[1] + pel_offset_y + pel_offset_x*2; /* NV12/NV16 */
137 int mvx = fenc->lowres_mvs[0][ref0_distance][mb_xy][0];
138 int mvy = fenc->lowres_mvs[0][ref0_distance][mb_xy][1];
139 h->mc.mc_chroma( pixu, pixv, i_stride, src1, i_stride, mvx, 2*mvy>>v_shift, 8, height );
143 h->mc.plane_copy_deinterleave( dstu, i_stride, dstv, i_stride, ref->plane[1], i_stride, cw, ch );
144 h->mc.plane_copy_deinterleave( dstu+i_offset, i_stride, dstv+i_offset, i_stride, fenc->plane[1], i_stride, cw, ch );
148 static NOINLINE pixel *x264_weight_cost_init_chroma444( x264_t *h, x264_frame_t *fenc, x264_frame_t *ref, pixel *dst, int p )
150 int ref0_distance = fenc->i_frame - ref->i_frame - 1;
151 int i_stride = fenc->i_stride[p];
152 int i_lines = fenc->i_lines[p];
153 int i_width = fenc->i_width[p];
155 if( fenc->lowres_mvs[0][ref0_distance][0][0] != 0x7FFF )
157 x264_frame_expand_border_chroma( h, ref, p );
158 for( int y = 0, mb_xy = 0, pel_offset_y = 0; y < i_lines; y += 16, pel_offset_y = y*i_stride )
159 for( int x = 0, pel_offset_x = 0; x < i_width; x += 16, mb_xy++, pel_offset_x += 16 )
161 pixel *pix = dst + pel_offset_y + pel_offset_x;
162 pixel *src = ref->plane[p] + pel_offset_y + pel_offset_x;
163 int mvx = fenc->lowres_mvs[0][ref0_distance][mb_xy][0] / 2;
164 int mvy = fenc->lowres_mvs[0][ref0_distance][mb_xy][1] / 2;
165 /* We don't want to calculate hpels for fenc frames, so we round the motion
166 * vectors to fullpel here. It's not too bad, I guess? */
167 h->mc.copy_16x16_unaligned( pix, i_stride, src+mvx+mvy*i_stride, i_stride, 16 );
173 return ref->plane[p];
176 static int x264_weight_slice_header_cost( x264_t *h, x264_weight_t *w, int b_chroma )
178 /* Add cost of weights in the slice header. */
179 int lambda = x264_lambda_tab[X264_LOOKAHEAD_QP];
180 /* 4 times higher, because chroma is analyzed at full resolution. */
184 if( h->param.i_slice_count )
185 numslices = h->param.i_slice_count;
186 else if( h->param.i_slice_max_mbs )
187 numslices = (h->mb.i_mb_width * h->mb.i_mb_height + h->param.i_slice_max_mbs-1) / h->param.i_slice_max_mbs;
190 /* FIXME: find a way to account for --slice-max-size?
191 * 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.
192 * Cut denom cost in half if chroma, since it's shared between the two chroma planes. */
193 int denom_cost = bs_size_ue( w[0].i_denom ) * (2 - b_chroma);
194 return lambda * numslices * ( 10 + denom_cost + 2 * (bs_size_se( w[0].i_scale ) + bs_size_se( w[0].i_offset )) );
197 static NOINLINE unsigned int x264_weight_cost_luma( x264_t *h, x264_frame_t *fenc, pixel *src, x264_weight_t *w )
199 unsigned int cost = 0;
200 int i_stride = fenc->i_stride_lowres;
201 int i_lines = fenc->i_lines_lowres;
202 int i_width = fenc->i_width_lowres;
203 pixel *fenc_plane = fenc->lowres[0];
204 ALIGNED_ARRAY_16( pixel, buf,[8*8] );
210 for( int y = 0; y < i_lines; y += 8, pixoff = y*i_stride )
211 for( int x = 0; x < i_width; x += 8, i_mb++, pixoff += 8)
213 w->weightfn[8>>2]( buf, 8, &src[pixoff], i_stride, w, 8 );
214 int cmp = h->pixf.mbcmp[PIXEL_8x8]( buf, 8, &fenc_plane[pixoff], i_stride );
215 cost += X264_MIN( cmp, fenc->i_intra_cost[i_mb] );
217 cost += x264_weight_slice_header_cost( h, w, 0 );
220 for( int y = 0; y < i_lines; y += 8, pixoff = y*i_stride )
221 for( int x = 0; x < i_width; x += 8, i_mb++, pixoff += 8 )
223 int cmp = h->pixf.mbcmp[PIXEL_8x8]( &src[pixoff], i_stride, &fenc_plane[pixoff], i_stride );
224 cost += X264_MIN( cmp, fenc->i_intra_cost[i_mb] );
230 static NOINLINE unsigned int x264_weight_cost_chroma( x264_t *h, x264_frame_t *fenc, pixel *ref, x264_weight_t *w )
232 unsigned int cost = 0;
233 int i_stride = fenc->i_stride[1];
234 int i_lines = fenc->i_lines[1];
235 int i_width = fenc->i_width[1];
236 pixel *src = ref + (i_stride >> 1);
237 ALIGNED_ARRAY_16( pixel, buf, [8*16] );
239 int height = 16 >> CHROMA_V_SHIFT;
242 for( int y = 0; y < i_lines; y += height, pixoff = y*i_stride )
243 for( int x = 0; x < i_width; x += 8, pixoff += 8 )
245 w->weightfn[8>>2]( buf, 8, &ref[pixoff], i_stride, w, height );
246 /* The naive and seemingly sensible algorithm is to use mbcmp as in luma.
247 * But testing shows that for chroma the DC coefficient is by far the most
248 * important part of the coding cost. Thus a more useful chroma weight is
249 * obtained by comparing each block's DC coefficient instead of the actual
251 cost += h->pixf.asd8( buf, 8, &src[pixoff], i_stride, height );
253 cost += x264_weight_slice_header_cost( h, w, 1 );
256 for( int y = 0; y < i_lines; y += height, pixoff = y*i_stride )
257 for( int x = 0; x < i_width; x += 8, pixoff += 8 )
258 cost += h->pixf.asd8( &ref[pixoff], i_stride, &src[pixoff], i_stride, height );
263 static NOINLINE unsigned int x264_weight_cost_chroma444( x264_t *h, x264_frame_t *fenc, pixel *ref, x264_weight_t *w, int p )
265 unsigned int cost = 0;
266 int i_stride = fenc->i_stride[p];
267 int i_lines = fenc->i_lines[p];
268 int i_width = fenc->i_width[p];
269 pixel *src = fenc->plane[p];
270 ALIGNED_ARRAY_16( pixel, buf, [16*16] );
274 for( int y = 0; y < i_lines; y += 16, pixoff = y*i_stride )
275 for( int x = 0; x < i_width; x += 16, pixoff += 16 )
277 w->weightfn[16>>2]( buf, 16, &ref[pixoff], i_stride, w, 16 );
278 cost += h->pixf.mbcmp[PIXEL_16x16]( buf, 16, &src[pixoff], i_stride );
280 cost += x264_weight_slice_header_cost( h, w, 1 );
283 for( int y = 0; y < i_lines; y += 16, pixoff = y*i_stride )
284 for( int x = 0; x < i_width; x += 16, pixoff += 16 )
285 cost += h->pixf.mbcmp[PIXEL_16x16]( &ref[pixoff], i_stride, &src[pixoff], i_stride );
290 void x264_weights_analyse( x264_t *h, x264_frame_t *fenc, x264_frame_t *ref, int b_lookahead )
292 int i_delta_index = fenc->i_frame - ref->i_frame - 1;
293 /* epsilon is chosen to require at least a numerator of 127 (with denominator = 128) */
294 const float epsilon = 1.f/128.f;
295 x264_weight_t *weights = fenc->weight[0];
296 SET_WEIGHT( weights[0], 0, 1, 0, 0 );
297 SET_WEIGHT( weights[1], 0, 1, 0, 0 );
298 SET_WEIGHT( weights[2], 0, 1, 0, 0 );
299 int chroma_initted = 0;
300 float guess_scale[3];
303 for( int plane = 0; plane <= 2*!b_lookahead; plane++ )
305 float fenc_var = fenc->i_pixel_ssd[plane] + !ref->i_pixel_ssd[plane];
306 float ref_var = ref->i_pixel_ssd[plane] + !ref->i_pixel_ssd[plane];
307 guess_scale[plane] = sqrtf( fenc_var / ref_var );
308 fenc_mean[plane] = (float)fenc->i_pixel_sum[plane] / (fenc->i_lines[!!plane] * fenc->i_width[!!plane]) / (1 << (BIT_DEPTH - 8));
309 ref_mean[plane] = (float) ref->i_pixel_sum[plane] / (fenc->i_lines[!!plane] * fenc->i_width[!!plane]) / (1 << (BIT_DEPTH - 8));
312 int chroma_denom = 7;
315 /* make sure both our scale factors fit */
316 while( chroma_denom > 0 )
318 float thresh = 127.f / (1<<chroma_denom);
319 if( guess_scale[1] < thresh && guess_scale[2] < thresh )
325 /* Don't check chroma in lookahead, or if there wasn't a luma weight. */
326 for( int plane = 0; plane <= 2 && !( plane && ( !weights[0].weightfn || b_lookahead ) ); plane++ )
328 int minoff, minscale, mindenom;
329 unsigned int minscore, origscore;
333 if( fabsf( ref_mean[plane] - fenc_mean[plane] ) < 0.5f && fabsf( 1.f - guess_scale[plane] ) < epsilon )
335 SET_WEIGHT( weights[plane], 0, 1, 0, 0 );
341 weights[plane].i_denom = chroma_denom;
342 weights[plane].i_scale = x264_clip3( round( guess_scale[plane] * (1<<chroma_denom) ), 0, 255 );
343 if( weights[plane].i_scale > 127 )
345 weights[1].weightfn = weights[2].weightfn = NULL;
350 x264_weight_get_h264( round( guess_scale[plane] * 128 ), 0, &weights[plane] );
353 mindenom = weights[plane].i_denom;
354 minscale = weights[plane].i_scale;
360 if( !fenc->b_intra_calculated )
362 x264_mb_analysis_t a;
363 x264_lowres_context_init( h, &a );
364 x264_slicetype_frame_cost( h, &a, &fenc, 0, 0, 0 );
366 mcbuf = x264_weight_cost_init_luma( h, fenc, ref, h->mb.p_weight_buf[0] );
367 origscore = minscore = x264_weight_cost_luma( h, fenc, mcbuf, NULL );
373 mcbuf = x264_weight_cost_init_chroma444( h, fenc, ref, h->mb.p_weight_buf[0], plane );
374 origscore = minscore = x264_weight_cost_chroma444( h, fenc, mcbuf, NULL, plane );
378 pixel *dstu = h->mb.p_weight_buf[0];
379 pixel *dstv = h->mb.p_weight_buf[0]+fenc->i_stride[1]*fenc->i_lines[1];
380 if( !chroma_initted++ )
381 x264_weight_cost_init_chroma( h, fenc, ref, dstu, dstv );
382 mcbuf = plane == 1 ? dstu : dstv;
383 origscore = minscore = x264_weight_cost_chroma( h, fenc, mcbuf, NULL );
390 /* Picked somewhat arbitrarily */
391 static const uint8_t weight_check_distance[][2] =
393 {0,0},{0,0},{0,1},{0,1},
394 {0,1},{0,1},{0,1},{1,1},
395 {1,1},{2,1},{2,1},{4,2}
397 int scale_dist = b_lookahead ? 0 : weight_check_distance[h->param.analyse.i_subpel_refine][0];
398 int offset_dist = b_lookahead ? 0 : weight_check_distance[h->param.analyse.i_subpel_refine][1];
400 int start_scale = x264_clip3( minscale - scale_dist, 0, 127 );
401 int end_scale = x264_clip3( minscale + scale_dist, 0, 127 );
402 for( int i_scale = start_scale; i_scale <= end_scale; i_scale++ )
404 int cur_scale = i_scale;
405 int cur_offset = fenc_mean[plane] - ref_mean[plane] * cur_scale / (1 << mindenom) + 0.5f * b_lookahead;
406 if( cur_offset < - 128 || cur_offset > 127 )
408 /* Rescale considering the constraints on cur_offset. We do it in this order
409 * because scale has a much wider range than offset (because of denom), so
410 * it should almost never need to be clamped. */
411 cur_offset = x264_clip3( cur_offset, -128, 127 );
412 cur_scale = (1 << mindenom) * (fenc_mean[plane] - cur_offset) / ref_mean[plane] + 0.5f;
413 cur_scale = x264_clip3( cur_scale, 0, 127 );
415 int start_offset = x264_clip3( cur_offset - offset_dist, -128, 127 );
416 int end_offset = x264_clip3( cur_offset + offset_dist, -128, 127 );
417 for( int i_off = start_offset; i_off <= end_offset; i_off++ )
419 SET_WEIGHT( weights[plane], 1, cur_scale, mindenom, i_off );
424 s = x264_weight_cost_chroma444( h, fenc, mcbuf, &weights[plane], plane );
426 s = x264_weight_cost_chroma( h, fenc, mcbuf, &weights[plane] );
429 s = x264_weight_cost_luma( h, fenc, mcbuf, &weights[plane] );
430 COPY4_IF_LT( minscore, s, minscale, cur_scale, minoff, i_off, found, 1 );
432 // Don't check any more offsets if the previous one had a lower cost than the current one
433 if( minoff == start_offset && i_off != start_offset )
439 /* Use a smaller denominator if possible */
442 while( mindenom > 0 && !(minscale&1) )
449 /* FIXME: More analysis can be done here on SAD vs. SATD termination. */
450 /* 0.2% termination derived experimentally to avoid weird weights in frames that are mostly intra. */
451 if( !found || (minscale == 1 << mindenom && minoff == 0) || (float)minscore / origscore > 0.998f )
453 SET_WEIGHT( weights[plane], 0, 1, 0, 0 );
457 SET_WEIGHT( weights[plane], 1, minscale, mindenom, minoff );
459 if( h->param.analyse.i_weighted_pred == X264_WEIGHTP_FAKE && weights[0].weightfn && !plane )
460 fenc->f_weighted_cost_delta[i_delta_index] = (float)minscore / origscore;
463 /* Optimize and unify denominator */
464 if( weights[1].weightfn || weights[2].weightfn )
466 int denom = weights[1].weightfn ? weights[1].i_denom : weights[2].i_denom;
467 int both_weighted = weights[1].weightfn && weights[2].weightfn;
468 /* If only one plane is weighted, the other has an implicit scale of 1<<denom.
469 * With denom==7, this comes out to 128, which is invalid, so don't allow that. */
470 while( (!both_weighted && denom==7) ||
471 (denom > 0 && !(weights[1].weightfn && (weights[1].i_scale&1))
472 && !(weights[2].weightfn && (weights[2].i_scale&1))) )
475 for( int i = 1; i <= 2; i++ )
476 if( weights[i].weightfn )
478 weights[i].i_scale >>= 1;
479 weights[i].i_denom = denom;
483 for( int i = 1; i <= 2; i++ )
484 if( weights[i].weightfn )
485 h->mc.weight_cache( h, &weights[i] );
487 if( weights[0].weightfn && b_lookahead )
489 //scale lowres in lookahead for slicetype_frame_cost
490 pixel *src = ref->buffer_lowres[0];
491 pixel *dst = h->mb.p_weight_buf[0];
492 int width = ref->i_width_lowres + PADH*2;
493 int height = ref->i_lines_lowres + PADV*2;
494 x264_weight_scale_plane( h, dst, ref->i_stride_lowres, src, ref->i_stride_lowres,
495 width, height, &weights[0] );
496 fenc->weighted[0] = h->mb.p_weight_buf[0] + PADH + ref->i_stride_lowres * PADV;
500 /* Output buffers are separated by 128 bytes to avoid false sharing of cachelines
501 * in multithreaded lookahead. */
503 /* cost_est, cost_est_aq, intra_mbs, num rows */
506 #define COST_EST_AQ 1
509 #define ROW_SATD (NUM_INTS + (h->mb.i_mb_y - h->i_threadslice_start))
511 static void x264_slicetype_mb_cost( x264_t *h, x264_mb_analysis_t *a,
512 x264_frame_t **frames, int p0, int p1, int b,
513 int dist_scale_factor, int do_search[2], const x264_weight_t *w,
514 int *output_inter, int *output_intra )
516 x264_frame_t *fref0 = frames[p0];
517 x264_frame_t *fref1 = frames[p1];
518 x264_frame_t *fenc = frames[b];
519 const int b_bidir = (b < p1);
520 const int i_mb_x = h->mb.i_mb_x;
521 const int i_mb_y = h->mb.i_mb_y;
522 const int i_mb_stride = h->mb.i_mb_width;
523 const int i_mb_xy = i_mb_x + i_mb_y * i_mb_stride;
524 const int i_stride = fenc->i_stride_lowres;
525 const int i_pel_offset = 8 * (i_mb_x + i_mb_y * i_stride);
526 const int i_bipred_weight = h->param.analyse.b_weighted_bipred ? 64 - (dist_scale_factor>>2) : 32;
527 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] };
528 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] };
529 int b_frame_score_mb = (i_mb_x > 0 && i_mb_x < h->mb.i_mb_width - 1 &&
530 i_mb_y > 0 && i_mb_y < h->mb.i_mb_height - 1) ||
531 h->mb.i_mb_width <= 2 || h->mb.i_mb_height <= 2;
533 ALIGNED_ARRAY_16( pixel, pix1,[9*FDEC_STRIDE] );
534 pixel *pix2 = pix1+8;
536 int i_bcost = COST_MAX;
538 /* A small, arbitrary bias to avoid VBV problems caused by zero-residual lookahead blocks. */
539 int lowres_penalty = 4;
541 h->mb.pic.p_fenc[0] = h->mb.pic.fenc_buf;
542 h->mc.copy[PIXEL_8x8]( h->mb.pic.p_fenc[0], FENC_STRIDE, &fenc->lowres[0][i_pel_offset], i_stride, 8 );
545 goto lowres_intra_mb;
547 // no need for h->mb.mv_min[]
548 h->mb.mv_limit_fpel[0][0] = -8*h->mb.i_mb_x - 4;
549 h->mb.mv_limit_fpel[1][0] = 8*( h->mb.i_mb_width - h->mb.i_mb_x - 1 ) + 4;
550 h->mb.mv_min_spel[0] = 4*( h->mb.mv_limit_fpel[0][0] - 8 );
551 h->mb.mv_max_spel[0] = 4*( h->mb.mv_limit_fpel[1][0] + 8 );
552 if( h->mb.i_mb_x >= h->mb.i_mb_width - 2 )
554 h->mb.mv_limit_fpel[0][1] = -8*h->mb.i_mb_y - 4;
555 h->mb.mv_limit_fpel[1][1] = 8*( h->mb.i_mb_height - h->mb.i_mb_y - 1 ) + 4;
556 h->mb.mv_min_spel[1] = 4*( h->mb.mv_limit_fpel[0][1] - 8 );
557 h->mb.mv_max_spel[1] = 4*( h->mb.mv_limit_fpel[1][1] + 8 );
560 #define LOAD_HPELS_LUMA(dst, src) \
562 (dst)[0] = &(src)[0][i_pel_offset]; \
563 (dst)[1] = &(src)[1][i_pel_offset]; \
564 (dst)[2] = &(src)[2][i_pel_offset]; \
565 (dst)[3] = &(src)[3][i_pel_offset]; \
567 #define LOAD_WPELS_LUMA(dst,src) \
568 (dst) = &(src)[i_pel_offset];
570 #define CLIP_MV( mv ) \
572 mv[0] = x264_clip3( mv[0], h->mb.mv_min_spel[0], h->mb.mv_max_spel[0] ); \
573 mv[1] = x264_clip3( mv[1], h->mb.mv_min_spel[1], h->mb.mv_max_spel[1] ); \
575 #define TRY_BIDIR( mv0, mv1, penalty ) \
578 if( h->param.analyse.i_subpel_refine <= 1 ) \
580 int hpel_idx1 = (((mv0)[0]&2)>>1) + ((mv0)[1]&2); \
581 int hpel_idx2 = (((mv1)[0]&2)>>1) + ((mv1)[1]&2); \
582 pixel *src1 = m[0].p_fref[hpel_idx1] + ((mv0)[0]>>2) + ((mv0)[1]>>2) * m[0].i_stride[0]; \
583 pixel *src2 = m[1].p_fref[hpel_idx2] + ((mv1)[0]>>2) + ((mv1)[1]>>2) * m[1].i_stride[0]; \
584 h->mc.avg[PIXEL_8x8]( pix1, 16, src1, m[0].i_stride[0], src2, m[1].i_stride[0], i_bipred_weight ); \
588 intptr_t stride1 = 16, stride2 = 16; \
589 pixel *src1, *src2; \
590 src1 = h->mc.get_ref( pix1, &stride1, m[0].p_fref, m[0].i_stride[0], \
591 (mv0)[0], (mv0)[1], 8, 8, w ); \
592 src2 = h->mc.get_ref( pix2, &stride2, m[1].p_fref, m[1].i_stride[0], \
593 (mv1)[0], (mv1)[1], 8, 8, w ); \
594 h->mc.avg[PIXEL_8x8]( pix1, 16, src1, stride1, src2, stride2, i_bipred_weight ); \
596 i_cost = penalty * a->i_lambda + h->pixf.mbcmp[PIXEL_8x8]( \
597 m[0].p_fenc[0], FENC_STRIDE, pix1, 16 ); \
598 COPY2_IF_LT( i_bcost, i_cost, list_used, 3 ); \
601 m[0].i_pixel = PIXEL_8x8;
602 m[0].p_cost_mv = a->p_cost_mv;
603 m[0].i_stride[0] = i_stride;
604 m[0].p_fenc[0] = h->mb.pic.p_fenc[0];
607 LOAD_HPELS_LUMA( m[0].p_fref, fref0->lowres );
608 m[0].p_fref_w = m[0].p_fref[0];
610 LOAD_WPELS_LUMA( m[0].p_fref_w, fenc->weighted[0] );
614 ALIGNED_ARRAY_8( int16_t, dmv,[2],[2] );
616 m[1].i_pixel = PIXEL_8x8;
617 m[1].p_cost_mv = a->p_cost_mv;
618 m[1].i_stride[0] = i_stride;
619 m[1].p_fenc[0] = h->mb.pic.p_fenc[0];
621 m[1].weight = x264_weight_none;
622 LOAD_HPELS_LUMA( m[1].p_fref, fref1->lowres );
623 m[1].p_fref_w = m[1].p_fref[0];
625 if( fref1->lowres_mvs[0][p1-p0-1][0][0] != 0x7FFF )
627 int16_t *mvr = fref1->lowres_mvs[0][p1-p0-1][i_mb_xy];
628 dmv[0][0] = ( mvr[0] * dist_scale_factor + 128 ) >> 8;
629 dmv[0][1] = ( mvr[1] * dist_scale_factor + 128 ) >> 8;
630 dmv[1][0] = dmv[0][0] - mvr[0];
631 dmv[1][1] = dmv[0][1] - mvr[1];
634 if( h->param.analyse.i_subpel_refine <= 1 )
635 M64( dmv ) &= ~0x0001000100010001ULL; /* mv & ~1 */
640 TRY_BIDIR( dmv[0], dmv[1], 0 );
644 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 );
645 i_cost = h->pixf.mbcmp[PIXEL_8x8]( m[0].p_fenc[0], FENC_STRIDE, pix1, 16 );
646 COPY2_IF_LT( i_bcost, i_cost, list_used, 3 );
650 for( int l = 0; l < 1 + b_bidir; l++ )
655 int16_t (*fenc_mv)[2] = fenc_mvs[l];
656 ALIGNED_4( int16_t mvc[4][2] );
658 /* Reverse-order MV prediction. */
661 #define MVC(mv) { CP32( mvc[i_mvc], mv ); i_mvc++; }
662 if( i_mb_x < h->mb.i_mb_width - 1 )
664 if( i_mb_y < h->i_threadslice_end - 1 )
666 MVC( fenc_mv[i_mb_stride] );
668 MVC( fenc_mv[i_mb_stride-1] );
669 if( i_mb_x < h->mb.i_mb_width - 1 )
670 MVC( fenc_mv[i_mb_stride+1] );
674 CP32( m[l].mvp, mvc[0] );
676 x264_median_mv( m[l].mvp, mvc[0], mvc[1], mvc[2] );
678 /* Fast skip for cases of near-zero residual. Shortcut: don't bother except in the mv0 case,
679 * since anything else is likely to have enough residual to not trigger the skip. */
680 if( !M32( m[l].mvp ) )
682 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] );
690 x264_me_search( h, &m[l], mvc, i_mvc );
691 m[l].cost -= a->p_cost_mv[0]; // remove mvcost from skip mbs
693 m[l].cost += 5 * a->i_lambda;
696 CP32( fenc_mvs[l], m[l].mv );
697 *fenc_costs[l] = m[l].cost;
701 CP32( m[l].mv, fenc_mvs[l] );
702 m[l].cost = *fenc_costs[l];
704 COPY2_IF_LT( i_bcost, m[l].cost, list_used, l+1 );
707 if( b_bidir && ( M32( m[0].mv ) || M32( m[1].mv ) ) )
708 TRY_BIDIR( m[0].mv, m[1].mv, 5 );
711 if( !fenc->b_intra_calculated )
713 ALIGNED_ARRAY_16( pixel, edge,[36] );
714 pixel *pix = &pix1[8+FDEC_STRIDE];
715 pixel *src = &fenc->lowres[0][i_pel_offset];
716 const int intra_penalty = 5 * a->i_lambda;
718 int pixoff = 4 / sizeof(pixel);
720 /* Avoid store forwarding stalls by writing larger chunks */
721 memcpy( pix-FDEC_STRIDE, src-i_stride, 16 * sizeof(pixel) );
722 for( int i = -1; i < 8; i++ )
723 M32( &pix[i*FDEC_STRIDE-pixoff] ) = M32( &src[i*i_stride-pixoff] );
725 h->pixf.intra_mbcmp_x3_8x8c( h->mb.pic.p_fenc[0], pix, satds );
726 int i_icost = X264_MIN3( satds[0], satds[1], satds[2] );
728 if( h->param.analyse.i_subpel_refine > 1 )
730 h->predict_8x8c[I_PRED_CHROMA_P]( pix );
731 int satd = h->pixf.mbcmp[PIXEL_8x8]( pix, FDEC_STRIDE, h->mb.pic.p_fenc[0], FENC_STRIDE );
732 i_icost = X264_MIN( i_icost, satd );
733 h->predict_8x8_filter( pix, edge, ALL_NEIGHBORS, ALL_NEIGHBORS );
734 for( int i = 3; i < 9; i++ )
736 h->predict_8x8[i]( pix, edge );
737 satd = h->pixf.mbcmp[PIXEL_8x8]( pix, FDEC_STRIDE, h->mb.pic.p_fenc[0], FENC_STRIDE );
738 i_icost = X264_MIN( i_icost, satd );
742 i_icost = ((i_icost + intra_penalty) >> (BIT_DEPTH - 8)) + lowres_penalty;
743 fenc->i_intra_cost[i_mb_xy] = i_icost;
744 int i_icost_aq = i_icost;
745 if( h->param.rc.i_aq_mode )
746 i_icost_aq = (i_icost_aq * fenc->i_inv_qscale_factor[i_mb_xy] + 128) >> 8;
747 output_intra[ROW_SATD] += i_icost_aq;
748 if( b_frame_score_mb )
750 output_intra[COST_EST] += i_icost;
751 output_intra[COST_EST_AQ] += i_icost_aq;
754 i_bcost = (i_bcost >> (BIT_DEPTH - 8)) + lowres_penalty;
756 /* forbid intra-mbs in B-frames, because it's rare and not worth checking */
757 /* FIXME: Should we still forbid them now that we cache intra scores? */
760 int i_icost = fenc->i_intra_cost[i_mb_xy];
761 int b_intra = i_icost < i_bcost;
767 if( b_frame_score_mb )
768 output_inter[INTRA_MBS] += b_intra;
771 /* In an I-frame, we've already added the results above in the intra section. */
774 int i_bcost_aq = i_bcost;
775 if( h->param.rc.i_aq_mode )
776 i_bcost_aq = (i_bcost_aq * fenc->i_inv_qscale_factor[i_mb_xy] + 128) >> 8;
777 output_inter[ROW_SATD] += i_bcost_aq;
778 if( b_frame_score_mb )
780 /* Don't use AQ-weighted costs for slicetype decision, only for ratecontrol. */
781 output_inter[COST_EST] += i_bcost;
782 output_inter[COST_EST_AQ] += i_bcost_aq;
786 fenc->lowres_costs[b-p0][p1-b][i_mb_xy] = X264_MIN( i_bcost, LOWRES_COST_MASK ) + (list_used << LOWRES_COST_SHIFT);
791 (h->mb.i_mb_width > 2 && h->mb.i_mb_height > 2 ?\
792 (h->mb.i_mb_width - 2) * (h->mb.i_mb_height - 2) :\
793 h->mb.i_mb_width * h->mb.i_mb_height)
798 x264_mb_analysis_t *a;
799 x264_frame_t **frames;
803 int dist_scale_factor;
805 const x264_weight_t *w;
808 } x264_slicetype_slice_t;
810 static void x264_slicetype_slice_cost( x264_slicetype_slice_t *s )
814 /* Lowres lookahead goes backwards because the MVs are used as predictors in the main encode.
815 * This considerably improves MV prediction overall. */
817 /* The edge mbs seem to reduce the predictive quality of the
818 * whole frame's score, but are needed for a spatial distribution. */
819 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;
821 int start_y = X264_MIN( h->i_threadslice_end - 1, h->mb.i_mb_height - 2 + do_edges );
822 int end_y = X264_MAX( h->i_threadslice_start, 1 - do_edges );
823 int start_x = h->mb.i_mb_width - 2 + do_edges;
824 int end_x = 1 - do_edges;
826 for( h->mb.i_mb_y = start_y; h->mb.i_mb_y >= end_y; h->mb.i_mb_y-- )
827 for( h->mb.i_mb_x = start_x; h->mb.i_mb_x >= end_x; h->mb.i_mb_x-- )
828 x264_slicetype_mb_cost( h, s->a, s->frames, s->p0, s->p1, s->b, s->dist_scale_factor,
829 s->do_search, s->w, s->output_inter, s->output_intra );
832 static int x264_slicetype_frame_cost( x264_t *h, x264_mb_analysis_t *a,
833 x264_frame_t **frames, int p0, int p1, int b )
837 const x264_weight_t *w = x264_weight_none;
838 x264_frame_t *fenc = frames[b];
840 /* Check whether we already evaluated this frame
841 * If we have tried this frame as P, then we have also tried
842 * the preceding frames as B. (is this still true?) */
843 /* Also check that we already calculated the row SATDs for the current frame. */
844 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) )
845 i_score = fenc->i_cost_est[b-p0][p1-b];
848 int dist_scale_factor = 128;
850 /* For each list, check to see whether we have lowres motion-searched this reference frame before. */
851 do_search[0] = b != p0 && fenc->lowres_mvs[0][b-p0-1][0][0] == 0x7FFF;
852 do_search[1] = b != p1 && fenc->lowres_mvs[1][p1-b-1][0][0] == 0x7FFF;
855 if( h->param.analyse.i_weighted_pred && b == p1 )
858 x264_weights_analyse( h, fenc, frames[p0], 1 );
861 fenc->lowres_mvs[0][b-p0-1][0][0] = 0;
863 if( do_search[1] ) fenc->lowres_mvs[1][p1-b-1][0][0] = 0;
866 dist_scale_factor = ( ((b-p0) << 8) + ((p1-p0) >> 1) ) / (p1-p0);
868 int output_buf_size = h->mb.i_mb_height + (NUM_INTS + PAD_SIZE) * h->param.i_lookahead_threads;
869 int *output_inter[X264_LOOKAHEAD_THREAD_MAX+1];
870 int *output_intra[X264_LOOKAHEAD_THREAD_MAX+1];
871 output_inter[0] = h->scratch_buffer2;
872 output_intra[0] = output_inter[0] + output_buf_size;
875 if( h->param.b_opencl )
877 x264_opencl_lowres_init(h, fenc, a->i_lambda );
880 x264_opencl_lowres_init( h, frames[p0], a->i_lambda );
881 x264_opencl_motionsearch( h, frames, b, p0, 0, a->i_lambda, w );
885 x264_opencl_lowres_init( h, frames[p1], a->i_lambda );
886 x264_opencl_motionsearch( h, frames, b, p1, 1, a->i_lambda, NULL );
889 x264_opencl_finalize_cost( h, a->i_lambda, frames, p0, p1, b, dist_scale_factor );
890 x264_opencl_flush( h );
892 i_score = fenc->i_cost_est[b-p0][p1-b];
897 if( h->param.i_lookahead_threads > 1 )
899 x264_slicetype_slice_t s[X264_LOOKAHEAD_THREAD_MAX];
901 for( int i = 0; i < h->param.i_lookahead_threads; i++ )
903 x264_t *t = h->lookahead_thread[i];
905 /* FIXME move this somewhere else */
906 t->mb.i_me_method = h->mb.i_me_method;
907 t->mb.i_subpel_refine = h->mb.i_subpel_refine;
908 t->mb.b_chroma_me = h->mb.b_chroma_me;
910 s[i] = (x264_slicetype_slice_t){ t, a, frames, p0, p1, b, dist_scale_factor, do_search, w,
911 output_inter[i], output_intra[i] };
913 t->i_threadslice_start = ((h->mb.i_mb_height * i + h->param.i_lookahead_threads/2) / h->param.i_lookahead_threads);
914 t->i_threadslice_end = ((h->mb.i_mb_height * (i+1) + h->param.i_lookahead_threads/2) / h->param.i_lookahead_threads);
916 int thread_height = t->i_threadslice_end - t->i_threadslice_start;
917 int thread_output_size = thread_height + NUM_INTS;
918 memset( output_inter[i], 0, thread_output_size * sizeof(int) );
919 memset( output_intra[i], 0, thread_output_size * sizeof(int) );
920 output_inter[i][NUM_ROWS] = output_intra[i][NUM_ROWS] = thread_height;
922 output_inter[i+1] = output_inter[i] + thread_output_size + PAD_SIZE;
923 output_intra[i+1] = output_intra[i] + thread_output_size + PAD_SIZE;
925 x264_threadpool_run( h->lookaheadpool, (void*)x264_slicetype_slice_cost, &s[i] );
927 for( int i = 0; i < h->param.i_lookahead_threads; i++ )
928 x264_threadpool_wait( h->lookaheadpool, &s[i] );
932 h->i_threadslice_start = 0;
933 h->i_threadslice_end = h->mb.i_mb_height;
934 memset( output_inter[0], 0, (output_buf_size - PAD_SIZE) * sizeof(int) );
935 memset( output_intra[0], 0, (output_buf_size - PAD_SIZE) * sizeof(int) );
936 output_inter[0][NUM_ROWS] = output_intra[0][NUM_ROWS] = h->mb.i_mb_height;
937 x264_slicetype_slice_t s = (x264_slicetype_slice_t){ h, a, frames, p0, p1, b, dist_scale_factor, do_search, w,
938 output_inter[0], output_intra[0] };
939 x264_slicetype_slice_cost( &s );
942 /* Sum up accumulators */
944 fenc->i_intra_mbs[b-p0] = 0;
945 if( !fenc->b_intra_calculated )
947 fenc->i_cost_est[0][0] = 0;
948 fenc->i_cost_est_aq[0][0] = 0;
950 fenc->i_cost_est[b-p0][p1-b] = 0;
951 fenc->i_cost_est_aq[b-p0][p1-b] = 0;
953 int *row_satd_inter = fenc->i_row_satds[b-p0][p1-b];
954 int *row_satd_intra = fenc->i_row_satds[0][0];
955 for( int i = 0; i < h->param.i_lookahead_threads; i++ )
958 fenc->i_intra_mbs[b-p0] += output_inter[i][INTRA_MBS];
959 if( !fenc->b_intra_calculated )
961 fenc->i_cost_est[0][0] += output_intra[i][COST_EST];
962 fenc->i_cost_est_aq[0][0] += output_intra[i][COST_EST_AQ];
965 fenc->i_cost_est[b-p0][p1-b] += output_inter[i][COST_EST];
966 fenc->i_cost_est_aq[b-p0][p1-b] += output_inter[i][COST_EST_AQ];
968 if( h->param.rc.i_vbv_buffer_size )
970 int row_count = output_inter[i][NUM_ROWS];
971 memcpy( row_satd_inter, output_inter[i] + NUM_INTS, row_count * sizeof(int) );
972 if( !fenc->b_intra_calculated )
973 memcpy( row_satd_intra, output_intra[i] + NUM_INTS, row_count * sizeof(int) );
974 row_satd_inter += row_count;
975 row_satd_intra += row_count;
979 i_score = fenc->i_cost_est[b-p0][p1-b];
981 i_score = (uint64_t)i_score * 100 / (120 + h->param.i_bframe_bias);
983 fenc->b_intra_calculated = 1;
985 fenc->i_cost_est[b-p0][p1-b] = i_score;
993 /* If MB-tree changes the quantizers, we need to recalculate the frame cost without
994 * re-running lookahead. */
995 static int x264_slicetype_frame_cost_recalculate( x264_t *h, x264_frame_t **frames, int p0, int p1, int b )
998 int *row_satd = frames[b]->i_row_satds[b-p0][p1-b];
999 float *qp_offset = IS_X264_TYPE_B(frames[b]->i_type) ? frames[b]->f_qp_offset_aq : frames[b]->f_qp_offset;
1001 for( h->mb.i_mb_y = h->mb.i_mb_height - 1; h->mb.i_mb_y >= 0; h->mb.i_mb_y-- )
1003 row_satd[ h->mb.i_mb_y ] = 0;
1004 for( h->mb.i_mb_x = h->mb.i_mb_width - 1; h->mb.i_mb_x >= 0; h->mb.i_mb_x-- )
1006 int i_mb_xy = h->mb.i_mb_x + h->mb.i_mb_y*h->mb.i_mb_stride;
1007 int i_mb_cost = frames[b]->lowres_costs[b-p0][p1-b][i_mb_xy] & LOWRES_COST_MASK;
1008 float qp_adj = qp_offset[i_mb_xy];
1009 i_mb_cost = (i_mb_cost * x264_exp2fix8(qp_adj) + 128) >> 8;
1010 row_satd[ h->mb.i_mb_y ] += i_mb_cost;
1011 if( (h->mb.i_mb_y > 0 && h->mb.i_mb_y < h->mb.i_mb_height - 1 &&
1012 h->mb.i_mb_x > 0 && h->mb.i_mb_x < h->mb.i_mb_width - 1) ||
1013 h->mb.i_mb_width <= 2 || h->mb.i_mb_height <= 2 )
1015 i_score += i_mb_cost;
1022 /* Trade off precision in mbtree for increased range */
1023 #define MBTREE_PRECISION 0.5f
1025 static void x264_macroblock_tree_finish( x264_t *h, x264_frame_t *frame, float average_duration, int ref0_distance )
1027 int fps_factor = round( CLIP_DURATION(average_duration) / CLIP_DURATION(frame->f_duration) * 256 / MBTREE_PRECISION );
1028 float weightdelta = 0.0;
1029 if( ref0_distance && frame->f_weighted_cost_delta[ref0_distance-1] > 0 )
1030 weightdelta = (1.0 - frame->f_weighted_cost_delta[ref0_distance-1]);
1032 /* Allow the strength to be adjusted via qcompress, since the two
1033 * concepts are very similar. */
1034 float strength = 5.0f * (1.0f - h->param.rc.f_qcompress);
1035 for( int mb_index = 0; mb_index < h->mb.i_mb_count; mb_index++ )
1037 int intra_cost = (frame->i_intra_cost[mb_index] * frame->i_inv_qscale_factor[mb_index] + 128) >> 8;
1040 int propagate_cost = (frame->i_propagate_cost[mb_index] * fps_factor + 128) >> 8;
1041 float log2_ratio = x264_log2(intra_cost + propagate_cost) - x264_log2(intra_cost) + weightdelta;
1042 frame->f_qp_offset[mb_index] = frame->f_qp_offset_aq[mb_index] - strength * log2_ratio;
1047 static void x264_macroblock_tree_propagate( x264_t *h, x264_frame_t **frames, float average_duration, int p0, int p1, int b, int referenced )
1049 uint16_t *ref_costs[2] = {frames[p0]->i_propagate_cost,frames[p1]->i_propagate_cost};
1050 int dist_scale_factor = ( ((b-p0) << 8) + ((p1-p0) >> 1) ) / (p1-p0);
1051 int i_bipred_weight = h->param.analyse.b_weighted_bipred ? 64 - (dist_scale_factor>>2) : 32;
1052 int16_t (*mvs[2])[2] = { frames[b]->lowres_mvs[0][b-p0-1], frames[b]->lowres_mvs[1][p1-b-1] };
1053 int bipred_weights[2] = {i_bipred_weight, 64 - i_bipred_weight};
1054 int16_t *buf = h->scratch_buffer;
1055 uint16_t *propagate_cost = frames[b]->i_propagate_cost;
1056 uint16_t *lowres_costs = frames[b]->lowres_costs[b-p0][p1-b];
1059 float fps_factor = CLIP_DURATION(frames[b]->f_duration) / (CLIP_DURATION(average_duration) * 256.0f) * MBTREE_PRECISION;
1061 /* For non-reffed frames the source costs are always zero, so just memset one row and re-use it. */
1063 memset( frames[b]->i_propagate_cost, 0, h->mb.i_mb_width * sizeof(uint16_t) );
1065 for( h->mb.i_mb_y = 0; h->mb.i_mb_y < h->mb.i_mb_height; h->mb.i_mb_y++ )
1067 int mb_index = h->mb.i_mb_y*h->mb.i_mb_stride;
1068 h->mc.mbtree_propagate_cost( buf, propagate_cost,
1069 frames[b]->i_intra_cost+mb_index, lowres_costs+mb_index,
1070 frames[b]->i_inv_qscale_factor+mb_index, &fps_factor, h->mb.i_mb_width );
1072 propagate_cost += h->mb.i_mb_width;
1074 h->mc.mbtree_propagate_list( h, ref_costs[0], &mvs[0][mb_index], buf, &lowres_costs[mb_index],
1075 bipred_weights[0], h->mb.i_mb_y, h->mb.i_mb_width, 0 );
1078 h->mc.mbtree_propagate_list( h, ref_costs[1], &mvs[1][mb_index], buf, &lowres_costs[mb_index],
1079 bipred_weights[1], h->mb.i_mb_y, h->mb.i_mb_width, 1 );
1083 if( h->param.rc.i_vbv_buffer_size && h->param.rc.i_lookahead && referenced )
1084 x264_macroblock_tree_finish( h, frames[b], average_duration, b == p1 ? b - p0 : 0 );
1087 static void x264_macroblock_tree( x264_t *h, x264_mb_analysis_t *a, x264_frame_t **frames, int num_frames, int b_intra )
1090 int last_nonb, cur_nonb = 1;
1094 float total_duration = 0.0;
1095 for( int j = 0; j <= num_frames; j++ )
1096 total_duration += frames[j]->f_duration;
1097 float average_duration = total_duration / (num_frames + 1);
1102 x264_slicetype_frame_cost( h, a, frames, 0, 0, 0 );
1104 while( i > 0 && IS_X264_TYPE_B( frames[i]->i_type ) )
1108 /* Lookaheadless MB-tree is not a theoretically distinct case; the same extrapolation could
1109 * be applied to the end of a lookahead buffer of any size. However, it's most needed when
1110 * lookahead=0, so that's what's currently implemented. */
1111 if( !h->param.rc.i_lookahead )
1115 memset( frames[0]->i_propagate_cost, 0, h->mb.i_mb_count * sizeof(uint16_t) );
1116 memcpy( frames[0]->f_qp_offset, frames[0]->f_qp_offset_aq, h->mb.i_mb_count * sizeof(float) );
1119 XCHG( uint16_t*, frames[last_nonb]->i_propagate_cost, frames[0]->i_propagate_cost );
1120 memset( frames[0]->i_propagate_cost, 0, h->mb.i_mb_count * sizeof(uint16_t) );
1124 if( last_nonb < idx )
1126 memset( frames[last_nonb]->i_propagate_cost, 0, h->mb.i_mb_count * sizeof(uint16_t) );
1132 while( IS_X264_TYPE_B( frames[cur_nonb]->i_type ) && cur_nonb > 0 )
1134 if( cur_nonb < idx )
1136 x264_slicetype_frame_cost( h, a, frames, cur_nonb, last_nonb, last_nonb );
1137 memset( frames[cur_nonb]->i_propagate_cost, 0, h->mb.i_mb_count * sizeof(uint16_t) );
1138 bframes = last_nonb - cur_nonb - 1;
1139 if( h->param.i_bframe_pyramid && bframes > 1 )
1141 int middle = (bframes + 1)/2 + cur_nonb;
1142 x264_slicetype_frame_cost( h, a, frames, cur_nonb, last_nonb, middle );
1143 memset( frames[middle]->i_propagate_cost, 0, h->mb.i_mb_count * sizeof(uint16_t) );
1144 while( i > cur_nonb )
1146 int p0 = i > middle ? middle : cur_nonb;
1147 int p1 = i < middle ? middle : last_nonb;
1150 x264_slicetype_frame_cost( h, a, frames, p0, p1, i );
1151 x264_macroblock_tree_propagate( h, frames, average_duration, p0, p1, i, 0 );
1155 x264_macroblock_tree_propagate( h, frames, average_duration, cur_nonb, last_nonb, middle, 1 );
1159 while( i > cur_nonb )
1161 x264_slicetype_frame_cost( h, a, frames, cur_nonb, last_nonb, i );
1162 x264_macroblock_tree_propagate( h, frames, average_duration, cur_nonb, last_nonb, i, 0 );
1166 x264_macroblock_tree_propagate( h, frames, average_duration, cur_nonb, last_nonb, last_nonb, 1 );
1167 last_nonb = cur_nonb;
1170 if( !h->param.rc.i_lookahead )
1172 x264_slicetype_frame_cost( h, a, frames, 0, last_nonb, last_nonb );
1173 x264_macroblock_tree_propagate( h, frames, average_duration, 0, last_nonb, last_nonb, 1 );
1174 XCHG( uint16_t*, frames[last_nonb]->i_propagate_cost, frames[0]->i_propagate_cost );
1177 x264_macroblock_tree_finish( h, frames[last_nonb], average_duration, last_nonb );
1178 if( h->param.i_bframe_pyramid && bframes > 1 && !h->param.rc.i_vbv_buffer_size )
1179 x264_macroblock_tree_finish( h, frames[last_nonb+(bframes+1)/2], average_duration, 0 );
1182 static int x264_vbv_frame_cost( x264_t *h, x264_mb_analysis_t *a, x264_frame_t **frames, int p0, int p1, int b )
1184 int cost = x264_slicetype_frame_cost( h, a, frames, p0, p1, b );
1185 if( h->param.rc.i_aq_mode )
1187 if( h->param.rc.b_mb_tree )
1188 return x264_slicetype_frame_cost_recalculate( h, frames, p0, p1, b );
1190 return frames[b]->i_cost_est_aq[b-p0][p1-b];
1195 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 )
1197 cur_frame->i_cpb_delay = *i_cpb_delay;
1198 cur_frame->i_dpb_output_delay = cur_frame->i_field_cnt - *i_coded_fields;
1200 // add a correction term for frame reordering
1201 cur_frame->i_dpb_output_delay += h->sps->vui.i_num_reorder_frames*2;
1203 // fix possible negative dpb_output_delay because of pulldown changes and reordering
1204 if( cur_frame->i_dpb_output_delay < 0 )
1206 cur_frame->i_cpb_delay += cur_frame->i_dpb_output_delay;
1207 cur_frame->i_dpb_output_delay = 0;
1209 prev_frame->i_cpb_duration += cur_frame->i_dpb_output_delay;
1212 // don't reset cpb delay for IDR frames when using intra-refresh
1213 if( cur_frame->b_keyframe && !h->param.b_intra_refresh )
1216 *i_cpb_delay += cur_frame->i_duration;
1217 *i_coded_fields += cur_frame->i_duration;
1218 cur_frame->i_cpb_duration = cur_frame->i_duration;
1221 static void x264_vbv_lookahead( x264_t *h, x264_mb_analysis_t *a, x264_frame_t **frames, int num_frames, int keyframe )
1223 int last_nonb = 0, cur_nonb = 1, idx = 0;
1224 x264_frame_t *prev_frame = NULL;
1225 int prev_frame_idx = 0;
1226 while( cur_nonb < num_frames && IS_X264_TYPE_B( frames[cur_nonb]->i_type ) )
1228 int next_nonb = keyframe ? last_nonb : cur_nonb;
1230 if( frames[cur_nonb]->i_coded_fields_lookahead >= 0 )
1232 h->i_coded_fields_lookahead = frames[cur_nonb]->i_coded_fields_lookahead;
1233 h->i_cpb_delay_lookahead = frames[cur_nonb]->i_cpb_delay_lookahead;
1236 while( cur_nonb < num_frames )
1238 /* P/I cost: This shouldn't include the cost of next_nonb */
1239 if( next_nonb != cur_nonb )
1241 int p0 = IS_X264_TYPE_I( frames[cur_nonb]->i_type ) ? cur_nonb : last_nonb;
1242 frames[next_nonb]->i_planned_satd[idx] = x264_vbv_frame_cost( h, a, frames, p0, cur_nonb, cur_nonb );
1243 frames[next_nonb]->i_planned_type[idx] = frames[cur_nonb]->i_type;
1244 frames[cur_nonb]->i_coded_fields_lookahead = h->i_coded_fields_lookahead;
1245 frames[cur_nonb]->i_cpb_delay_lookahead = h->i_cpb_delay_lookahead;
1246 x264_calculate_durations( h, frames[cur_nonb], prev_frame, &h->i_cpb_delay_lookahead, &h->i_coded_fields_lookahead );
1249 frames[next_nonb]->f_planned_cpb_duration[prev_frame_idx] = (double)prev_frame->i_cpb_duration *
1250 h->sps->vui.i_num_units_in_tick / h->sps->vui.i_time_scale;
1252 frames[next_nonb]->f_planned_cpb_duration[idx] = (double)frames[cur_nonb]->i_cpb_duration *
1253 h->sps->vui.i_num_units_in_tick / h->sps->vui.i_time_scale;
1254 prev_frame = frames[cur_nonb];
1255 prev_frame_idx = idx;
1258 /* Handle the B-frames: coded order */
1259 for( int i = last_nonb+1; i < cur_nonb; i++, idx++ )
1261 frames[next_nonb]->i_planned_satd[idx] = x264_vbv_frame_cost( h, a, frames, last_nonb, cur_nonb, i );
1262 frames[next_nonb]->i_planned_type[idx] = X264_TYPE_B;
1263 frames[i]->i_coded_fields_lookahead = h->i_coded_fields_lookahead;
1264 frames[i]->i_cpb_delay_lookahead = h->i_cpb_delay_lookahead;
1265 x264_calculate_durations( h, frames[i], prev_frame, &h->i_cpb_delay_lookahead, &h->i_coded_fields_lookahead );
1268 frames[next_nonb]->f_planned_cpb_duration[prev_frame_idx] = (double)prev_frame->i_cpb_duration *
1269 h->sps->vui.i_num_units_in_tick / h->sps->vui.i_time_scale;
1271 frames[next_nonb]->f_planned_cpb_duration[idx] = (double)frames[i]->i_cpb_duration *
1272 h->sps->vui.i_num_units_in_tick / h->sps->vui.i_time_scale;
1273 prev_frame = frames[i];
1274 prev_frame_idx = idx;
1276 last_nonb = cur_nonb;
1278 while( cur_nonb <= num_frames && IS_X264_TYPE_B( frames[cur_nonb]->i_type ) )
1281 frames[next_nonb]->i_planned_type[idx] = X264_TYPE_AUTO;
1284 static int x264_slicetype_path_cost( x264_t *h, x264_mb_analysis_t *a, x264_frame_t **frames, char *path, int threshold )
1289 path--; /* Since the 1st path element is really the second frame */
1292 int next_nonb = loc;
1293 /* Find the location of the next non-B-frame. */
1294 while( path[next_nonb] == 'B' )
1297 /* Add the cost of the non-B-frame found above */
1298 if( path[next_nonb] == 'P' )
1299 cost += x264_slicetype_frame_cost( h, a, frames, cur_nonb, next_nonb, next_nonb );
1301 cost += x264_slicetype_frame_cost( h, a, frames, next_nonb, next_nonb, next_nonb );
1302 /* Early terminate if the cost we have found is larger than the best path cost so far */
1303 if( cost > threshold )
1306 if( h->param.i_bframe_pyramid && next_nonb - cur_nonb > 2 )
1308 int middle = cur_nonb + (next_nonb - cur_nonb)/2;
1309 cost += x264_slicetype_frame_cost( h, a, frames, cur_nonb, next_nonb, middle );
1310 for( int next_b = loc; next_b < middle && cost < threshold; next_b++ )
1311 cost += x264_slicetype_frame_cost( h, a, frames, cur_nonb, middle, next_b );
1312 for( int next_b = middle+1; next_b < next_nonb && cost < threshold; next_b++ )
1313 cost += x264_slicetype_frame_cost( h, a, frames, middle, next_nonb, next_b );
1316 for( int next_b = loc; next_b < next_nonb && cost < threshold; next_b++ )
1317 cost += x264_slicetype_frame_cost( h, a, frames, cur_nonb, next_nonb, next_b );
1319 loc = next_nonb + 1;
1320 cur_nonb = next_nonb;
1325 /* Viterbi/trellis slicetype decision algorithm. */
1326 /* Uses strings due to the fact that the speed of the control functions is
1327 negligible compared to the cost of running slicetype_frame_cost, and because
1328 it makes debugging easier. */
1329 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] )
1331 char paths[2][X264_LOOKAHEAD_MAX+1];
1332 int num_paths = X264_MIN( h->param.i_bframe+1, length );
1333 int best_cost = COST_MAX;
1334 int best_possible = 0;
1337 /* Iterate over all currently possible paths */
1338 for( int path = 0; path < num_paths; path++ )
1340 /* Add suffixes to the current path */
1341 int len = length - (path + 1);
1342 memcpy( paths[idx], best_paths[len % (X264_BFRAME_MAX+1)], len );
1343 memset( paths[idx]+len, 'B', path );
1344 strcpy( paths[idx]+len+path, "P" );
1347 for( int i = 1; i <= length; i++ )
1349 int i_type = frames[i]->i_type;
1350 if( i_type == X264_TYPE_AUTO )
1352 if( IS_X264_TYPE_B( i_type ) )
1353 possible = possible && (i < len || i == length || paths[idx][i-1] == 'B');
1356 possible = possible && (i < len || paths[idx][i-1] != 'B');
1357 paths[idx][i-1] = IS_X264_TYPE_I( i_type ) ? 'I' : 'P';
1361 if( possible || !best_possible )
1363 if( possible && !best_possible )
1364 best_cost = COST_MAX;
1365 /* Calculate the actual cost of the current path */
1366 int cost = x264_slicetype_path_cost( h, a, frames, paths[idx], best_cost );
1367 if( cost < best_cost )
1370 best_possible = possible;
1376 /* Store the best path. */
1377 memcpy( best_paths[length % (X264_BFRAME_MAX+1)], paths[idx^1], length );
1380 static int scenecut_internal( x264_t *h, x264_mb_analysis_t *a, x264_frame_t **frames, int p0, int p1, int real_scenecut )
1382 x264_frame_t *frame = frames[p1];
1384 /* Don't do scenecuts on the right view of a frame-packed video. */
1385 if( real_scenecut && h->param.i_frame_packing == 5 && (frame->i_frame&1) )
1388 x264_slicetype_frame_cost( h, a, frames, p0, p1, p1 );
1390 int icost = frame->i_cost_est[0][0];
1391 int pcost = frame->i_cost_est[p1-p0][0];
1393 int i_gop_size = frame->i_frame - h->lookahead->i_last_keyframe;
1394 float f_thresh_max = h->param.i_scenecut_threshold / 100.0;
1395 /* magic numbers pulled out of thin air */
1396 float f_thresh_min = f_thresh_max * 0.25;
1399 if( h->param.i_keyint_min == h->param.i_keyint_max )
1400 f_thresh_min = f_thresh_max;
1401 if( i_gop_size <= h->param.i_keyint_min / 4 || h->param.b_intra_refresh )
1402 f_bias = f_thresh_min / 4;
1403 else if( i_gop_size <= h->param.i_keyint_min )
1404 f_bias = f_thresh_min * i_gop_size / h->param.i_keyint_min;
1407 f_bias = f_thresh_min
1408 + ( f_thresh_max - f_thresh_min )
1409 * ( i_gop_size - h->param.i_keyint_min )
1410 / ( h->param.i_keyint_max - h->param.i_keyint_min );
1413 res = pcost >= (1.0 - f_bias) * icost;
1414 if( res && real_scenecut )
1416 int imb = frame->i_intra_mbs[p1-p0];
1417 int pmb = NUM_MBS - imb;
1418 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",
1420 icost, pcost, 1. - (double)pcost / icost,
1421 f_bias, i_gop_size, imb, pmb );
1426 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 )
1428 /* Only do analysis during a normal scenecut check. */
1429 if( real_scenecut && h->param.i_bframe )
1431 int origmaxp1 = p0 + 1;
1432 /* Look ahead to avoid coding short flashes as scenecuts. */
1433 if( h->param.i_bframe_adaptive == X264_B_ADAPT_TRELLIS )
1434 /* Don't analyse any more frames than the trellis would have covered. */
1435 origmaxp1 += h->param.i_bframe;
1438 int maxp1 = X264_MIN( origmaxp1, num_frames );
1440 /* Where A and B are scenes: AAAAAABBBAAAAAA
1441 * If BBB is shorter than (maxp1-p0), it is detected as a flash
1442 * and not considered a scenecut. */
1443 for( int curp1 = p1; curp1 <= maxp1; curp1++ )
1444 if( !scenecut_internal( h, a, frames, p0, curp1, 0 ) )
1445 /* Any frame in between p0 and cur_p1 cannot be a real scenecut. */
1446 for( int i = curp1; i > p0; i-- )
1447 frames[i]->b_scenecut = 0;
1449 /* Where A-F are scenes: AAAAABBCCDDEEFFFFFF
1450 * If each of BB ... EE are shorter than (maxp1-p0), they are
1451 * detected as flashes and not considered scenecuts.
1452 * Instead, the first F frame becomes a scenecut.
1453 * If the video ends before F, no frame becomes a scenecut. */
1454 for( int curp0 = p0; curp0 <= maxp1; curp0++ )
1455 if( origmaxp1 > i_max_search || (curp0 < maxp1 && scenecut_internal( h, a, frames, curp0, maxp1, 0 )) )
1456 /* If cur_p0 is the p0 of a scenecut, it cannot be the p1 of a scenecut. */
1457 frames[curp0]->b_scenecut = 0;
1460 /* Ignore frames that are part of a flash, i.e. cannot be real scenecuts. */
1461 if( !frames[p1]->b_scenecut )
1463 return scenecut_internal( h, a, frames, p0, p1, real_scenecut );
1466 #define IS_X264_TYPE_AUTO_OR_I(x) ((x)==X264_TYPE_AUTO || IS_X264_TYPE_I(x))
1467 #define IS_X264_TYPE_AUTO_OR_B(x) ((x)==X264_TYPE_AUTO || IS_X264_TYPE_B(x))
1469 void x264_slicetype_analyse( x264_t *h, int intra_minigop )
1471 x264_mb_analysis_t a;
1472 x264_frame_t *frames[X264_LOOKAHEAD_MAX+3] = { NULL, };
1473 int num_frames, orig_num_frames, keyint_limit, framecnt;
1474 int i_max_search = X264_MIN( h->lookahead->next.i_size, X264_LOOKAHEAD_MAX );
1475 int vbv_lookahead = h->param.rc.i_vbv_buffer_size && h->param.rc.i_lookahead;
1476 /* For determinism we should limit the search to the number of frames lookahead has for sure
1477 * in h->lookahead->next.list buffer, except at the end of stream.
1478 * For normal calls with (intra_minigop == 0) that is h->lookahead->i_slicetype_length + 1 frames.
1479 * And for I-frame calls (intra_minigop != 0) we already removed intra_minigop frames from there. */
1480 if( h->param.b_deterministic )
1481 i_max_search = X264_MIN( i_max_search, h->lookahead->i_slicetype_length + 1 - intra_minigop );
1482 int keyframe = !!intra_minigop;
1484 assert( h->frames.b_have_lowres );
1486 if( !h->lookahead->last_nonb )
1488 frames[0] = h->lookahead->last_nonb;
1489 for( framecnt = 0; framecnt < i_max_search; framecnt++ )
1490 frames[framecnt+1] = h->lookahead->next.list[framecnt];
1492 x264_lowres_context_init( h, &a );
1496 if( h->param.rc.b_mb_tree )
1497 x264_macroblock_tree( h, &a, frames, 0, keyframe );
1501 keyint_limit = h->param.i_keyint_max - frames[0]->i_frame + h->lookahead->i_last_keyframe - 1;
1502 orig_num_frames = num_frames = h->param.b_intra_refresh ? framecnt : X264_MIN( framecnt, keyint_limit );
1504 /* This is important psy-wise: if we have a non-scenecut keyframe,
1505 * there will be significant visual artifacts if the frames just before
1506 * go down in quality due to being referenced less, despite it being
1507 * more RD-optimal. */
1508 if( (h->param.analyse.b_psy && h->param.rc.b_mb_tree) || vbv_lookahead )
1509 num_frames = framecnt;
1510 else if( h->param.b_open_gop && num_frames < framecnt )
1512 else if( num_frames == 0 )
1514 frames[1]->i_type = X264_TYPE_I;
1518 if( IS_X264_TYPE_AUTO_OR_I( frames[1]->i_type ) &&
1519 h->param.i_scenecut_threshold && scenecut( h, &a, frames, 0, 1, 1, orig_num_frames, i_max_search ) )
1521 if( frames[1]->i_type == X264_TYPE_AUTO )
1522 frames[1]->i_type = X264_TYPE_I;
1527 x264_opencl_slicetype_prep( h, frames, num_frames, a.i_lambda );
1530 /* Replace forced keyframes with I/IDR-frames */
1531 for( int j = 1; j <= num_frames; j++ )
1533 if( frames[j]->i_type == X264_TYPE_KEYFRAME )
1534 frames[j]->i_type = h->param.b_open_gop ? X264_TYPE_I : X264_TYPE_IDR;
1537 /* Close GOP at IDR-frames */
1538 for( int j = 2; j <= num_frames; j++ )
1540 if( frames[j]->i_type == X264_TYPE_IDR && IS_X264_TYPE_AUTO_OR_B( frames[j-1]->i_type ) )
1541 frames[j-1]->i_type = X264_TYPE_P;
1544 int num_analysed_frames = num_frames;
1547 if( h->param.i_bframe )
1549 if( h->param.i_bframe_adaptive == X264_B_ADAPT_TRELLIS )
1551 if( num_frames > 1 )
1553 char best_paths[X264_BFRAME_MAX+1][X264_LOOKAHEAD_MAX+1] = {"","P"};
1554 int best_path_index = num_frames % (X264_BFRAME_MAX+1);
1556 /* Perform the frametype analysis. */
1557 for( int j = 2; j <= num_frames; j++ )
1558 x264_slicetype_path( h, &a, frames, j, best_paths );
1560 /* Load the results of the analysis into the frame types. */
1561 for( int j = 1; j < num_frames; j++ )
1563 if( best_paths[best_path_index][j-1] != 'B' )
1565 if( IS_X264_TYPE_AUTO_OR_B( frames[j]->i_type ) )
1566 frames[j]->i_type = X264_TYPE_P;
1570 if( frames[j]->i_type == X264_TYPE_AUTO )
1571 frames[j]->i_type = X264_TYPE_B;
1576 else if( h->param.i_bframe_adaptive == X264_B_ADAPT_FAST )
1579 int num_bframes = h->param.i_bframe;
1580 char path[X264_LOOKAHEAD_MAX+1];
1581 for( int j = 1; j < num_frames; j++ )
1583 if( j-1 > 0 && IS_X264_TYPE_B( frames[j-1]->i_type ) )
1588 num_bframes = h->param.i_bframe;
1592 if( IS_X264_TYPE_AUTO_OR_B( frames[j]->i_type ) )
1593 frames[j]->i_type = X264_TYPE_P;
1597 if( frames[j]->i_type != X264_TYPE_AUTO )
1600 if( IS_X264_TYPE_B( frames[j+1]->i_type ) )
1602 frames[j]->i_type = X264_TYPE_P;
1606 int bframes = j - last_nonb - 1;
1607 memset( path, 'B', bframes );
1608 strcpy( path+bframes, "PP" );
1609 int cost_p = x264_slicetype_path_cost( h, &a, frames+last_nonb, path, COST_MAX );
1610 strcpy( path+bframes, "BP" );
1611 int cost_b = x264_slicetype_path_cost( h, &a, frames+last_nonb, path, cost_p );
1613 if( cost_b < cost_p )
1614 frames[j]->i_type = X264_TYPE_B;
1616 frames[j]->i_type = X264_TYPE_P;
1621 int num_bframes = h->param.i_bframe;
1622 for( int j = 1; j < num_frames; j++ )
1626 if( IS_X264_TYPE_AUTO_OR_B( frames[j]->i_type ) )
1627 frames[j]->i_type = X264_TYPE_P;
1629 else if( frames[j]->i_type == X264_TYPE_AUTO )
1631 if( IS_X264_TYPE_B( frames[j+1]->i_type ) )
1632 frames[j]->i_type = X264_TYPE_P;
1634 frames[j]->i_type = X264_TYPE_B;
1636 if( IS_X264_TYPE_B( frames[j]->i_type ) )
1639 num_bframes = h->param.i_bframe;
1642 if( IS_X264_TYPE_AUTO_OR_B( frames[num_frames]->i_type ) )
1643 frames[num_frames]->i_type = X264_TYPE_P;
1645 int num_bframes = 0;
1646 while( num_bframes < num_frames && IS_X264_TYPE_B( frames[num_bframes+1]->i_type ) )
1649 /* Check scenecut on the first minigop. */
1650 for( int j = 1; j < num_bframes+1; j++ )
1652 if( frames[j]->i_forced_type == X264_TYPE_AUTO && IS_X264_TYPE_AUTO_OR_I( frames[j+1]->i_forced_type ) &&
1653 h->param.i_scenecut_threshold && scenecut( h, &a, frames, j, j+1, 0, orig_num_frames, i_max_search ) )
1655 frames[j]->i_type = X264_TYPE_P;
1656 num_analysed_frames = j;
1661 reset_start = keyframe ? 1 : X264_MIN( num_bframes+2, num_analysed_frames+1 );
1665 for( int j = 1; j <= num_frames; j++ )
1666 if( IS_X264_TYPE_AUTO_OR_B( frames[j]->i_type ) )
1667 frames[j]->i_type = X264_TYPE_P;
1668 reset_start = !keyframe + 1;
1671 /* Perform the actual macroblock tree analysis.
1672 * Don't go farther than the maximum keyframe interval; this helps in short GOPs. */
1673 if( h->param.rc.b_mb_tree )
1674 x264_macroblock_tree( h, &a, frames, X264_MIN(num_frames, h->param.i_keyint_max), keyframe );
1676 /* Enforce keyframe limit. */
1677 if( !h->param.b_intra_refresh )
1679 int last_keyframe = h->lookahead->i_last_keyframe;
1680 int last_possible = 0;
1681 for( int j = 1; j <= num_frames; j++ )
1683 x264_frame_t *frm = frames[j];
1684 int keyframe_dist = frm->i_frame - last_keyframe;
1686 if( IS_X264_TYPE_AUTO_OR_I( frm->i_forced_type ) )
1688 if( h->param.b_open_gop || !IS_X264_TYPE_B( frames[j-1]->i_forced_type ) )
1691 if( keyframe_dist >= h->param.i_keyint_max )
1693 if( last_possible != 0 && last_possible != j )
1697 keyframe_dist = frm->i_frame - last_keyframe;
1700 if( frm->i_type != X264_TYPE_IDR )
1701 frm->i_type = h->param.b_open_gop ? X264_TYPE_I : X264_TYPE_IDR;
1703 if( frm->i_type == X264_TYPE_I && keyframe_dist >= h->param.i_keyint_min )
1705 if( h->param.b_open_gop )
1707 last_keyframe = frm->i_frame;
1708 if( h->param.b_bluray_compat )
1712 while( bframes < j-1 && IS_X264_TYPE_B( frames[j-1-bframes]->i_type ) )
1714 last_keyframe -= bframes;
1717 else if( frm->i_forced_type != X264_TYPE_I )
1718 frm->i_type = X264_TYPE_IDR;
1720 if( frm->i_type == X264_TYPE_IDR )
1722 last_keyframe = frm->i_frame;
1723 if( j > 1 && IS_X264_TYPE_B( frames[j-1]->i_type ) )
1724 frames[j-1]->i_type = X264_TYPE_P;
1730 x264_vbv_lookahead( h, &a, frames, num_frames, keyframe );
1732 /* Restore frametypes for all frames that haven't actually been decided yet. */
1733 for( int j = reset_start; j <= num_frames; j++ )
1734 frames[j]->i_type = frames[j]->i_forced_type;
1737 x264_opencl_slicetype_end( h );
1741 void x264_slicetype_decide( x264_t *h )
1743 x264_frame_t *frames[X264_BFRAME_MAX+2];
1748 if( !h->lookahead->next.i_size )
1751 int lookahead_size = h->lookahead->next.i_size;
1753 for( int i = 0; i < h->lookahead->next.i_size; i++ )
1755 if( h->param.b_vfr_input )
1757 if( lookahead_size-- > 1 )
1758 h->lookahead->next.list[i]->i_duration = 2 * (h->lookahead->next.list[i+1]->i_pts - h->lookahead->next.list[i]->i_pts);
1760 h->lookahead->next.list[i]->i_duration = h->i_prev_duration;
1763 h->lookahead->next.list[i]->i_duration = delta_tfi_divisor[h->lookahead->next.list[i]->i_pic_struct];
1764 h->i_prev_duration = h->lookahead->next.list[i]->i_duration;
1765 h->lookahead->next.list[i]->f_duration = (double)h->lookahead->next.list[i]->i_duration
1766 * h->sps->vui.i_num_units_in_tick
1767 / h->sps->vui.i_time_scale;
1769 if( h->lookahead->next.list[i]->i_frame > h->i_disp_fields_last_frame && lookahead_size > 0 )
1771 h->lookahead->next.list[i]->i_field_cnt = h->i_disp_fields;
1772 h->i_disp_fields += h->lookahead->next.list[i]->i_duration;
1773 h->i_disp_fields_last_frame = h->lookahead->next.list[i]->i_frame;
1775 else if( lookahead_size == 0 )
1777 h->lookahead->next.list[i]->i_field_cnt = h->i_disp_fields;
1778 h->lookahead->next.list[i]->i_duration = h->i_prev_duration;
1782 if( h->param.rc.b_stat_read )
1784 /* Use the frame types from the first pass */
1785 for( int i = 0; i < h->lookahead->next.i_size; i++ )
1786 h->lookahead->next.list[i]->i_type =
1787 x264_ratecontrol_slice_type( h, h->lookahead->next.list[i]->i_frame );
1789 else if( (h->param.i_bframe && h->param.i_bframe_adaptive)
1790 || h->param.i_scenecut_threshold
1791 || h->param.rc.b_mb_tree
1792 || (h->param.rc.i_vbv_buffer_size && h->param.rc.i_lookahead) )
1793 x264_slicetype_analyse( h, 0 );
1795 for( bframes = 0, brefs = 0;; bframes++ )
1797 frm = h->lookahead->next.list[bframes];
1799 if( frm->i_forced_type != X264_TYPE_AUTO && frm->i_type != frm->i_forced_type &&
1800 !(frm->i_forced_type == X264_TYPE_KEYFRAME && IS_X264_TYPE_I( frm->i_type )) )
1802 x264_log( h, X264_LOG_WARNING, "forced frame type (%d) at %d was changed to frame type (%d)\n",
1803 frm->i_forced_type, frm->i_frame, frm->i_type );
1806 if( frm->i_type == X264_TYPE_BREF && h->param.i_bframe_pyramid < X264_B_PYRAMID_NORMAL &&
1807 brefs == h->param.i_bframe_pyramid )
1809 frm->i_type = X264_TYPE_B;
1810 x264_log( h, X264_LOG_WARNING, "B-ref at frame %d incompatible with B-pyramid %s \n",
1811 frm->i_frame, x264_b_pyramid_names[h->param.i_bframe_pyramid] );
1813 /* pyramid with multiple B-refs needs a big enough dpb that the preceding P-frame stays available.
1814 smaller dpb could be supported by smart enough use of mmco, but it's easier just to forbid it. */
1815 else if( frm->i_type == X264_TYPE_BREF && h->param.i_bframe_pyramid == X264_B_PYRAMID_NORMAL &&
1816 brefs && h->param.i_frame_reference <= (brefs+3) )
1818 frm->i_type = X264_TYPE_B;
1819 x264_log( h, X264_LOG_WARNING, "B-ref at frame %d incompatible with B-pyramid %s and %d reference frames\n",
1820 frm->i_frame, x264_b_pyramid_names[h->param.i_bframe_pyramid], h->param.i_frame_reference );
1823 if( frm->i_type == X264_TYPE_KEYFRAME )
1824 frm->i_type = h->param.b_open_gop ? X264_TYPE_I : X264_TYPE_IDR;
1826 /* Limit GOP size */
1827 if( (!h->param.b_intra_refresh || frm->i_frame == 0) && frm->i_frame - h->lookahead->i_last_keyframe >= h->param.i_keyint_max )
1829 if( frm->i_type == X264_TYPE_AUTO || frm->i_type == X264_TYPE_I )
1830 frm->i_type = h->param.b_open_gop && h->lookahead->i_last_keyframe >= 0 ? X264_TYPE_I : X264_TYPE_IDR;
1831 int warn = frm->i_type != X264_TYPE_IDR;
1832 if( warn && h->param.b_open_gop )
1833 warn &= frm->i_type != X264_TYPE_I;
1836 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 );
1837 frm->i_type = h->param.b_open_gop && h->lookahead->i_last_keyframe >= 0 ? X264_TYPE_I : X264_TYPE_IDR;
1840 if( frm->i_type == X264_TYPE_I && frm->i_frame - h->lookahead->i_last_keyframe >= h->param.i_keyint_min )
1842 if( h->param.b_open_gop )
1844 h->lookahead->i_last_keyframe = frm->i_frame; // Use display order
1845 if( h->param.b_bluray_compat )
1846 h->lookahead->i_last_keyframe -= bframes; // Use bluray order
1847 frm->b_keyframe = 1;
1850 frm->i_type = X264_TYPE_IDR;
1852 if( frm->i_type == X264_TYPE_IDR )
1855 h->lookahead->i_last_keyframe = frm->i_frame;
1856 frm->b_keyframe = 1;
1860 h->lookahead->next.list[bframes]->i_type = X264_TYPE_P;
1864 if( bframes == h->param.i_bframe ||
1865 !h->lookahead->next.list[bframes+1] )
1867 if( IS_X264_TYPE_B( frm->i_type ) )
1868 x264_log( h, X264_LOG_WARNING, "specified frame type is not compatible with max B-frames\n" );
1869 if( frm->i_type == X264_TYPE_AUTO
1870 || IS_X264_TYPE_B( frm->i_type ) )
1871 frm->i_type = X264_TYPE_P;
1874 if( frm->i_type == X264_TYPE_BREF )
1877 if( frm->i_type == X264_TYPE_AUTO )
1878 frm->i_type = X264_TYPE_B;
1880 else if( !IS_X264_TYPE_B( frm->i_type ) ) break;
1884 h->lookahead->next.list[bframes-1]->b_last_minigop_bframe = 1;
1885 h->lookahead->next.list[bframes]->i_bframes = bframes;
1887 /* insert a bref into the sequence */
1888 if( h->param.i_bframe_pyramid && bframes > 1 && !brefs )
1890 h->lookahead->next.list[(bframes-1)/2]->i_type = X264_TYPE_BREF;
1894 /* calculate the frame costs ahead of time for x264_rc_analyse_slice while we still have lowres */
1895 if( h->param.rc.i_rc_method != X264_RC_CQP )
1897 x264_mb_analysis_t a;
1899 p1 = b = bframes + 1;
1901 x264_lowres_context_init( h, &a );
1903 frames[0] = h->lookahead->last_nonb;
1904 memcpy( &frames[1], h->lookahead->next.list, (bframes+1) * sizeof(x264_frame_t*) );
1905 if( IS_X264_TYPE_I( h->lookahead->next.list[bframes]->i_type ) )
1910 x264_slicetype_frame_cost( h, &a, frames, p0, p1, b );
1912 if( (p0 != p1 || bframes) && h->param.rc.i_vbv_buffer_size )
1914 /* We need the intra costs for row SATDs. */
1915 x264_slicetype_frame_cost( h, &a, frames, b, b, b );
1917 /* We need B-frame costs for row SATDs. */
1919 for( b = 1; b <= bframes; b++ )
1921 if( frames[b]->i_type == X264_TYPE_B )
1922 for( p1 = b; frames[p1]->i_type == X264_TYPE_B; )
1926 x264_slicetype_frame_cost( h, &a, frames, p0, p1, b );
1927 if( frames[b]->i_type == X264_TYPE_BREF )
1933 /* Analyse for weighted P frames */
1934 if( !h->param.rc.b_stat_read && h->lookahead->next.list[bframes]->i_type == X264_TYPE_P
1935 && h->param.analyse.i_weighted_pred >= X264_WEIGHTP_SIMPLE )
1938 x264_weights_analyse( h, h->lookahead->next.list[bframes], h->lookahead->last_nonb, 0 );
1941 /* shift sequence to coded order.
1942 use a small temporary list to avoid shifting the entire next buffer around */
1943 int i_coded = h->lookahead->next.list[0]->i_frame;
1946 int idx_list[] = { brefs+1, 1 };
1947 for( int i = 0; i < bframes; i++ )
1949 int idx = idx_list[h->lookahead->next.list[i]->i_type == X264_TYPE_BREF]++;
1950 frames[idx] = h->lookahead->next.list[i];
1951 frames[idx]->i_reordered_pts = h->lookahead->next.list[idx]->i_pts;
1953 frames[0] = h->lookahead->next.list[bframes];
1954 frames[0]->i_reordered_pts = h->lookahead->next.list[0]->i_pts;
1955 memcpy( h->lookahead->next.list, frames, (bframes+1) * sizeof(x264_frame_t*) );
1958 for( int i = 0; i <= bframes; i++ )
1960 h->lookahead->next.list[i]->i_coded = i_coded++;
1963 x264_calculate_durations( h, h->lookahead->next.list[i], h->lookahead->next.list[i-1], &h->i_cpb_delay, &h->i_coded_fields );
1964 h->lookahead->next.list[0]->f_planned_cpb_duration[i-1] = (double)h->lookahead->next.list[i]->i_cpb_duration *
1965 h->sps->vui.i_num_units_in_tick / h->sps->vui.i_time_scale;
1968 x264_calculate_durations( h, h->lookahead->next.list[i], NULL, &h->i_cpb_delay, &h->i_coded_fields );
1972 int x264_rc_analyse_slice( x264_t *h )
1978 if( IS_X264_TYPE_I(h->fenc->i_type) )
1980 else if( h->fenc->i_type == X264_TYPE_P )
1981 p1 = b = h->fenc->i_bframes + 1;
1984 p1 = (h->fref_nearest[1]->i_poc - h->fref_nearest[0]->i_poc)/2;
1985 b = (h->fenc->i_poc - h->fref_nearest[0]->i_poc)/2;
1987 /* We don't need to assign p0/p1 since we are not performing any real analysis here. */
1988 x264_frame_t **frames = &h->fenc - b;
1990 /* cost should have been already calculated by x264_slicetype_decide */
1991 cost = frames[b]->i_cost_est[b-p0][p1-b];
1992 assert( cost >= 0 );
1994 if( h->param.rc.b_mb_tree && !h->param.rc.b_stat_read )
1996 cost = x264_slicetype_frame_cost_recalculate( h, frames, p0, p1, b );
1997 if( b && h->param.rc.i_vbv_buffer_size )
1998 x264_slicetype_frame_cost_recalculate( h, frames, b, b, b );
2000 /* In AQ, use the weighted score instead. */
2001 else if( h->param.rc.i_aq_mode )
2002 cost = frames[b]->i_cost_est_aq[b-p0][p1-b];
2004 h->fenc->i_row_satd = h->fenc->i_row_satds[b-p0][p1-b];
2005 h->fdec->i_row_satd = h->fdec->i_row_satds[b-p0][p1-b];
2006 h->fdec->i_satd = cost;
2007 memcpy( h->fdec->i_row_satd, h->fenc->i_row_satd, h->mb.i_mb_height * sizeof(int) );
2008 if( !IS_X264_TYPE_I(h->fenc->i_type) )
2009 memcpy( h->fdec->i_row_satds[0][0], h->fenc->i_row_satds[0][0], h->mb.i_mb_height * sizeof(int) );
2011 if( h->param.b_intra_refresh && h->param.rc.i_vbv_buffer_size && h->fenc->i_type == X264_TYPE_P )
2013 int ip_factor = 256 * h->param.rc.f_ip_factor; /* fix8 */
2014 for( int y = 0; y < h->mb.i_mb_height; y++ )
2016 int mb_xy = y * h->mb.i_mb_stride + h->fdec->i_pir_start_col;
2017 for( int x = h->fdec->i_pir_start_col; x <= h->fdec->i_pir_end_col; x++, mb_xy++ )
2019 int intra_cost = (h->fenc->i_intra_cost[mb_xy] * ip_factor + 128) >> 8;
2020 int inter_cost = h->fenc->lowres_costs[b-p0][p1-b][mb_xy] & LOWRES_COST_MASK;
2021 int diff = intra_cost - inter_cost;
2022 if( h->param.rc.i_aq_mode )
2023 h->fdec->i_row_satd[y] += (diff * frames[b]->i_inv_qscale_factor[mb_xy] + 128) >> 8;
2025 h->fdec->i_row_satd[y] += diff;