]> git.sesse.net Git - x264/blob - encoder/slicetype.c
Switch to exponential interpolation between presets.
[x264] / encoder / slicetype.c
1 /*****************************************************************************
2  * slicetype.c: lookahead analysis
3  *****************************************************************************
4  * Copyright (C) 2005-2016 x264 project
5  *
6  * Authors: Fiona Glaser <fiona@x264.com>
7  *          Loren Merritt <lorenm@u.washington.edu>
8  *          Dylan Yudaken <dyudaken@gmail.com>
9  *
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.
14  *
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.
19  *
20  * You should have received a copy of the GNU General Public License
21  * along with this program; if not, write to the Free Software
22  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02111, USA.
23  *
24  * This program is also available under a commercial proprietary license.
25  * For more information, contact us at licensing@x264.com.
26  *****************************************************************************/
27
28 #include "common/common.h"
29 #include "macroblock.h"
30 #include "me.h"
31
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 };
34
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
38 void x264_weights_analyse( x264_t *h, x264_frame_t *fenc, x264_frame_t *ref, int b_lookahead );
39
40 #if HAVE_OPENCL
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 );
48 #endif
49
50 static void x264_lowres_context_init( x264_t *h, x264_mb_analysis_t *a )
51 {
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 )
56     {
57         h->mb.i_me_method = X264_MIN( X264_ME_HEX, h->param.analyse.i_me_method );
58         h->mb.i_subpel_refine = 4;
59     }
60     else
61     {
62         h->mb.i_me_method = X264_ME_DIA;
63         h->mb.i_subpel_refine = 2;
64     }
65     h->mb.b_chroma_me = 0;
66 }
67
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 )
70 {
71     w->i_offset = offset;
72     w->i_denom = 7;
73     w->i_scale = weight_nonh264;
74     while( w->i_denom > 0 && (w->i_scale > 127) )
75     {
76         w->i_denom--;
77         w->i_scale >>= 1;
78     }
79     w->i_scale = X264_MIN( w->i_scale, 127 );
80 }
81
82 static NOINLINE pixel *x264_weight_cost_init_luma( x264_t *h, x264_frame_t *fenc, x264_frame_t *ref, pixel *dest )
83 {
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 )
88     {
89         int i_stride = fenc->i_stride_lowres;
90         int i_lines = fenc->i_lines_lowres;
91         int i_width = fenc->i_width_lowres;
92         int i_mb_xy = 0;
93         pixel *p = dest;
94
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++ )
97             {
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 );
102             }
103         x264_emms();
104         return dest;
105     }
106     x264_emms();
107     return ref->lowres[0];
108 }
109
110 /* How data is organized for 4:2:0/4:2:2 chroma weightp:
111  * [U: ref] [U: fenc]
112  * [V: ref] [V: fenc]
113  * fenc = ref + offset
114  * v = u + stride * chroma height */
115
116 static NOINLINE void x264_weight_cost_init_chroma( x264_t *h, x264_frame_t *fenc, x264_frame_t *ref, pixel *dstu, pixel *dstv )
117 {
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;
127
128     if( fenc->lowres_mvs[0][ref0_distance][0][0] != 0x7FFF )
129     {
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 )
133             {
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 );
140             }
141     }
142     else
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 );
145     x264_emms();
146 }
147
148 static NOINLINE pixel *x264_weight_cost_init_chroma444( x264_t *h, x264_frame_t *fenc, x264_frame_t *ref, pixel *dst, int p )
149 {
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];
154
155     if( fenc->lowres_mvs[0][ref0_distance][0][0] != 0x7FFF )
156     {
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 )
160             {
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 );
168             }
169         x264_emms();
170         return dst;
171     }
172     x264_emms();
173     return ref->plane[p];
174 }
175
176 static int x264_weight_slice_header_cost( x264_t *h, x264_weight_t *w, int b_chroma )
177 {
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. */
181     if( b_chroma )
182         lambda *= 4;
183     int numslices;
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;
188     else
189         numslices = 1;
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 )) );
195 }
196
197 static NOINLINE unsigned int x264_weight_cost_luma( x264_t *h, x264_frame_t *fenc, pixel *src, x264_weight_t *w )
198 {
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] );
205     int pixoff = 0;
206     int i_mb = 0;
207
208     if( w )
209     {
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)
212             {
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] );
216             }
217         cost += x264_weight_slice_header_cost( h, w, 0 );
218     }
219     else
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 )
222             {
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] );
225             }
226     x264_emms();
227     return cost;
228 }
229
230 static NOINLINE unsigned int x264_weight_cost_chroma( x264_t *h, x264_frame_t *fenc, pixel *ref, x264_weight_t *w )
231 {
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] );
238     int pixoff = 0;
239     int height = 16 >> CHROMA_V_SHIFT;
240     if( w )
241     {
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 )
244             {
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
250                  * pixels. */
251                 cost += h->pixf.asd8( buf, 8, &src[pixoff], i_stride, height );
252             }
253         cost += x264_weight_slice_header_cost( h, w, 1 );
254     }
255     else
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 );
259     x264_emms();
260     return cost;
261 }
262
263 static NOINLINE unsigned int x264_weight_cost_chroma444( x264_t *h, x264_frame_t *fenc, pixel *ref, x264_weight_t *w, int p )
264 {
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] );
271     int pixoff = 0;
272     if( w )
273     {
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 )
276             {
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 );
279             }
280         cost += x264_weight_slice_header_cost( h, w, 1 );
281     }
282     else
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 );
286     x264_emms();
287     return cost;
288 }
289
290 void x264_weights_analyse( x264_t *h, x264_frame_t *fenc, x264_frame_t *ref, int b_lookahead )
291 {
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];
301     float fenc_mean[3];
302     float ref_mean[3];
303     for( int plane = 0; plane <= 2*!b_lookahead; plane++ )
304     {
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));
310     }
311
312     int chroma_denom = 7;
313     if( !b_lookahead )
314     {
315         /* make sure both our scale factors fit */
316         while( chroma_denom > 0 )
317         {
318             float thresh = 127.f / (1<<chroma_denom);
319             if( guess_scale[1] < thresh && guess_scale[2] < thresh )
320                 break;
321             chroma_denom--;
322         }
323     }
324
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++ )
327     {
328         int minoff, minscale, mindenom;
329         unsigned int minscore, origscore;
330         int found;
331
332         //early termination
333         if( fabsf( ref_mean[plane] - fenc_mean[plane] ) < 0.5f && fabsf( 1.f - guess_scale[plane] ) < epsilon )
334         {
335             SET_WEIGHT( weights[plane], 0, 1, 0, 0 );
336             continue;
337         }
338
339         if( plane )
340         {
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 )
344             {
345                 weights[1].weightfn = weights[2].weightfn = NULL;
346                 break;
347             }
348         }
349         else
350             x264_weight_get_h264( round( guess_scale[plane] * 128 ), 0, &weights[plane] );
351
352         found = 0;
353         mindenom = weights[plane].i_denom;
354         minscale = weights[plane].i_scale;
355         minoff = 0;
356
357         pixel *mcbuf;
358         if( !plane )
359         {
360             if( !fenc->b_intra_calculated )
361             {
362                 x264_mb_analysis_t a;
363                 x264_lowres_context_init( h, &a );
364                 x264_slicetype_frame_cost( h, &a, &fenc, 0, 0, 0 );
365             }
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 );
368         }
369         else
370         {
371             if( CHROMA444 )
372             {
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 );
375             }
376             else
377             {
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 );
384             }
385         }
386
387         if( !minscore )
388             continue;
389
390         /* Picked somewhat arbitrarily */
391         static const uint8_t weight_check_distance[][2] =
392         {
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}
396         };
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];
399
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++ )
403         {
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 )
407             {
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 );
414             }
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++ )
418             {
419                 SET_WEIGHT( weights[plane], 1, cur_scale, mindenom, i_off );
420                 unsigned int s;
421                 if( plane )
422                 {
423                     if( CHROMA444 )
424                         s = x264_weight_cost_chroma444( h, fenc, mcbuf, &weights[plane], plane );
425                     else
426                         s = x264_weight_cost_chroma( h, fenc, mcbuf, &weights[plane] );
427                 }
428                 else
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 );
431
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 )
434                     break;
435             }
436         }
437         x264_emms();
438
439         /* Use a smaller denominator if possible */
440         if( !plane )
441         {
442             while( mindenom > 0 && !(minscale&1) )
443             {
444                 mindenom--;
445                 minscale >>= 1;
446             }
447         }
448
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 )
452         {
453             SET_WEIGHT( weights[plane], 0, 1, 0, 0 );
454             continue;
455         }
456         else
457             SET_WEIGHT( weights[plane], 1, minscale, mindenom, minoff );
458
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;
461     }
462
463     /* Optimize and unify denominator */
464     if( weights[1].weightfn || weights[2].weightfn )
465     {
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))) )
473         {
474             denom--;
475             for( int i = 1; i <= 2; i++ )
476                 if( weights[i].weightfn )
477                 {
478                     weights[i].i_scale >>= 1;
479                     weights[i].i_denom = denom;
480                 }
481         }
482     }
483     for( int i = 1; i <= 2; i++ )
484         if( weights[i].weightfn )
485             h->mc.weight_cache( h, &weights[i] );
486
487     if( weights[0].weightfn && b_lookahead )
488     {
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;
497     }
498 }
499
500 /* Output buffers are separated by 128 bytes to avoid false sharing of cachelines
501  * in multithreaded lookahead. */
502 #define PAD_SIZE 32
503 /* cost_est, cost_est_aq, intra_mbs, num rows */
504 #define NUM_INTS 4
505 #define COST_EST 0
506 #define COST_EST_AQ 1
507 #define INTRA_MBS 2
508 #define NUM_ROWS 3
509 #define ROW_SATD (NUM_INTS + (h->mb.i_mb_y - h->i_threadslice_start))
510
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 )
515 {
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;
532
533     ALIGNED_ARRAY_16( pixel, pix1,[9*FDEC_STRIDE] );
534     pixel *pix2 = pix1+8;
535     x264_me_t m[2];
536     int i_bcost = COST_MAX;
537     int list_used = 0;
538     /* A small, arbitrary bias to avoid VBV problems caused by zero-residual lookahead blocks. */
539     int lowres_penalty = 4;
540
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 );
543
544     if( p0 == p1 )
545         goto lowres_intra_mb;
546
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 )
553     {
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 );
558     }
559
560 #define LOAD_HPELS_LUMA(dst, src) \
561     { \
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]; \
566     }
567 #define LOAD_WPELS_LUMA(dst,src) \
568     (dst) = &(src)[i_pel_offset];
569
570 #define CLIP_MV( mv ) \
571     { \
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] ); \
574     }
575 #define TRY_BIDIR( mv0, mv1, penalty ) \
576     { \
577         int i_cost; \
578         if( h->param.analyse.i_subpel_refine <= 1 ) \
579         { \
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 ); \
585         } \
586         else \
587         { \
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 ); \
595         } \
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 ); \
599     }
600
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];
605     m[0].weight = w;
606     m[0].i_ref = 0;
607     LOAD_HPELS_LUMA( m[0].p_fref, fref0->lowres );
608     m[0].p_fref_w = m[0].p_fref[0];
609     if( w[0].weightfn )
610         LOAD_WPELS_LUMA( m[0].p_fref_w, fenc->weighted[0] );
611
612     if( b_bidir )
613     {
614         ALIGNED_ARRAY_8( int16_t, dmv,[2],[2] );
615
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];
620         m[1].i_ref = 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];
624
625         if( fref1->lowres_mvs[0][p1-p0-1][0][0] != 0x7FFF )
626         {
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];
632             CLIP_MV( dmv[0] );
633             CLIP_MV( dmv[1] );
634             if( h->param.analyse.i_subpel_refine <= 1 )
635                 M64( dmv ) &= ~0x0001000100010001ULL; /* mv & ~1 */
636         }
637         else
638             M64( dmv ) = 0;
639
640         TRY_BIDIR( dmv[0], dmv[1], 0 );
641         if( M64( dmv ) )
642         {
643             int i_cost;
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 );
647         }
648     }
649
650     for( int l = 0; l < 1 + b_bidir; l++ )
651     {
652         if( do_search[l] )
653         {
654             int i_mvc = 0;
655             int16_t (*fenc_mv)[2] = fenc_mvs[l];
656             ALIGNED_4( int16_t mvc[4][2] );
657
658             /* Reverse-order MV prediction. */
659             M32( mvc[0] ) = 0;
660             M32( mvc[2] ) = 0;
661 #define MVC(mv) { CP32( mvc[i_mvc], mv ); i_mvc++; }
662             if( i_mb_x < h->mb.i_mb_width - 1 )
663                 MVC( fenc_mv[1] );
664             if( i_mb_y < h->i_threadslice_end - 1 )
665             {
666                 MVC( fenc_mv[i_mb_stride] );
667                 if( i_mb_x > 0 )
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] );
671             }
672 #undef MVC
673             if( i_mvc <= 1 )
674                 CP32( m[l].mvp, mvc[0] );
675             else
676                 x264_median_mv( m[l].mvp, mvc[0], mvc[1], mvc[2] );
677
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 ) )
681             {
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] );
683                 if( m[l].cost < 64 )
684                 {
685                     M32( m[l].mv ) = 0;
686                     goto skip_motionest;
687                 }
688             }
689
690             x264_me_search( h, &m[l], mvc, i_mvc );
691             m[l].cost -= a->p_cost_mv[0]; // remove mvcost from skip mbs
692             if( M32( m[l].mv ) )
693                 m[l].cost += 5 * a->i_lambda;
694
695 skip_motionest:
696             CP32( fenc_mvs[l], m[l].mv );
697             *fenc_costs[l] = m[l].cost;
698         }
699         else
700         {
701             CP32( m[l].mv, fenc_mvs[l] );
702             m[l].cost = *fenc_costs[l];
703         }
704         COPY2_IF_LT( i_bcost, m[l].cost, list_used, l+1 );
705     }
706
707     if( b_bidir && ( M32( m[0].mv ) || M32( m[1].mv ) ) )
708         TRY_BIDIR( m[0].mv, m[1].mv, 5 );
709
710 lowres_intra_mb:
711     if( !fenc->b_intra_calculated )
712     {
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;
717         int satds[3];
718         int pixoff = 4 / sizeof(pixel);
719
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] );
724
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] );
727
728         if( h->param.analyse.i_subpel_refine > 1 )
729         {
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++ )
735             {
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 );
739             }
740         }
741
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 )
749         {
750             output_intra[COST_EST] += i_icost;
751             output_intra[COST_EST_AQ] += i_icost_aq;
752         }
753     }
754     i_bcost = (i_bcost >> (BIT_DEPTH - 8)) + lowres_penalty;
755
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? */
758     if( !b_bidir )
759     {
760         int i_icost = fenc->i_intra_cost[i_mb_xy];
761         int b_intra = i_icost < i_bcost;
762         if( b_intra )
763         {
764             i_bcost = i_icost;
765             list_used = 0;
766         }
767         if( b_frame_score_mb )
768             output_inter[INTRA_MBS] += b_intra;
769     }
770
771     /* In an I-frame, we've already added the results above in the intra section. */
772     if( p0 != p1 )
773     {
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 )
779         {
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;
783         }
784     }
785
786     fenc->lowres_costs[b-p0][p1-b][i_mb_xy] = X264_MIN( i_bcost, LOWRES_COST_MASK ) + (list_used << LOWRES_COST_SHIFT);
787 }
788 #undef TRY_BIDIR
789
790 #define NUM_MBS\
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)
794
795 typedef struct
796 {
797     x264_t *h;
798     x264_mb_analysis_t *a;
799     x264_frame_t **frames;
800     int p0;
801     int p1;
802     int b;
803     int dist_scale_factor;
804     int *do_search;
805     const x264_weight_t *w;
806     int *output_inter;
807     int *output_intra;
808 } x264_slicetype_slice_t;
809
810 static void x264_slicetype_slice_cost( x264_slicetype_slice_t *s )
811 {
812     x264_t *h = s->h;
813
814     /* Lowres lookahead goes backwards because the MVs are used as predictors in the main encode.
815      * This considerably improves MV prediction overall. */
816
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;
820
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;
825
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 );
830 }
831
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 )
834 {
835     int i_score = 0;
836     int do_search[2];
837     const x264_weight_t *w = x264_weight_none;
838     x264_frame_t *fenc = frames[b];
839
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];
846     else
847     {
848         int dist_scale_factor = 128;
849
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;
853         if( do_search[0] )
854         {
855             if( h->param.analyse.i_weighted_pred && b == p1 )
856             {
857                 x264_emms();
858                 x264_weights_analyse( h, fenc, frames[p0], 1 );
859                 w = fenc->weight[0];
860             }
861             fenc->lowres_mvs[0][b-p0-1][0][0] = 0;
862         }
863         if( do_search[1] ) fenc->lowres_mvs[1][p1-b-1][0][0] = 0;
864
865         if( p1 != p0 )
866             dist_scale_factor = ( ((b-p0) << 8) + ((p1-p0) >> 1) ) / (p1-p0);
867
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;
873
874 #if HAVE_OPENCL
875         if( h->param.b_opencl )
876         {
877             x264_opencl_lowres_init(h, fenc, a->i_lambda );
878             if( do_search[0] )
879             {
880                 x264_opencl_lowres_init( h, frames[p0], a->i_lambda );
881                 x264_opencl_motionsearch( h, frames, b, p0, 0, a->i_lambda, w );
882             }
883             if( do_search[1] )
884             {
885                 x264_opencl_lowres_init( h, frames[p1], a->i_lambda );
886                 x264_opencl_motionsearch( h, frames, b, p1, 1, a->i_lambda, NULL );
887             }
888             if( b != p0 )
889                 x264_opencl_finalize_cost( h, a->i_lambda, frames, p0, p1, b, dist_scale_factor );
890             x264_opencl_flush( h );
891
892             i_score = fenc->i_cost_est[b-p0][p1-b];
893         }
894         else
895 #endif
896         {
897             if( h->param.i_lookahead_threads > 1 )
898             {
899                 x264_slicetype_slice_t s[X264_LOOKAHEAD_THREAD_MAX];
900
901                 for( int i = 0; i < h->param.i_lookahead_threads; i++ )
902                 {
903                     x264_t *t = h->lookahead_thread[i];
904
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;
909
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] };
912
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);
915
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;
921
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;
924
925                     x264_threadpool_run( h->lookaheadpool, (void*)x264_slicetype_slice_cost, &s[i] );
926                 }
927                 for( int i = 0; i < h->param.i_lookahead_threads; i++ )
928                     x264_threadpool_wait( h->lookaheadpool, &s[i] );
929             }
930             else
931             {
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 );
940             }
941
942             /* Sum up accumulators */
943             if( b == p1 )
944                 fenc->i_intra_mbs[b-p0] = 0;
945             if( !fenc->b_intra_calculated )
946             {
947                 fenc->i_cost_est[0][0] = 0;
948                 fenc->i_cost_est_aq[0][0] = 0;
949             }
950             fenc->i_cost_est[b-p0][p1-b] = 0;
951             fenc->i_cost_est_aq[b-p0][p1-b] = 0;
952
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++ )
956             {
957                 if( b == p1 )
958                     fenc->i_intra_mbs[b-p0] += output_inter[i][INTRA_MBS];
959                 if( !fenc->b_intra_calculated )
960                 {
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];
963                 }
964
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];
967
968                 if( h->param.rc.i_vbv_buffer_size )
969                 {
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;
976                 }
977             }
978
979             i_score = fenc->i_cost_est[b-p0][p1-b];
980             if( b != p1 )
981                 i_score = (uint64_t)i_score * 100 / (120 + h->param.i_bframe_bias);
982             else
983                 fenc->b_intra_calculated = 1;
984
985             fenc->i_cost_est[b-p0][p1-b] = i_score;
986             x264_emms();
987         }
988     }
989
990     return i_score;
991 }
992
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 )
996 {
997     int i_score = 0;
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;
1000     x264_emms();
1001     for( h->mb.i_mb_y = h->mb.i_mb_height - 1; h->mb.i_mb_y >= 0; h->mb.i_mb_y-- )
1002     {
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-- )
1005         {
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 )
1014             {
1015                 i_score += i_mb_cost;
1016             }
1017         }
1018     }
1019     return i_score;
1020 }
1021
1022 /* Trade off precision in mbtree for increased range */
1023 #define MBTREE_PRECISION 0.5f
1024
1025 static void x264_macroblock_tree_finish( x264_t *h, x264_frame_t *frame, float average_duration, int ref0_distance )
1026 {
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]);
1031
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++ )
1036     {
1037         int intra_cost = (frame->i_intra_cost[mb_index] * frame->i_inv_qscale_factor[mb_index] + 128) >> 8;
1038         if( intra_cost )
1039         {
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;
1043         }
1044     }
1045 }
1046
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 )
1048 {
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];
1057
1058     x264_emms();
1059     float fps_factor = CLIP_DURATION(frames[b]->f_duration) / (CLIP_DURATION(average_duration) * 256.0f) * MBTREE_PRECISION;
1060
1061     /* For non-reffed frames the source costs are always zero, so just memset one row and re-use it. */
1062     if( !referenced )
1063         memset( frames[b]->i_propagate_cost, 0, h->mb.i_mb_width * sizeof(uint16_t) );
1064
1065     for( h->mb.i_mb_y = 0; h->mb.i_mb_y < h->mb.i_mb_height; h->mb.i_mb_y++ )
1066     {
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 );
1071         if( referenced )
1072             propagate_cost += h->mb.i_mb_width;
1073
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 );
1076         if( b != p1 )
1077         {
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 );
1080         }
1081     }
1082
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 );
1085 }
1086
1087 static void x264_macroblock_tree( x264_t *h, x264_mb_analysis_t *a, x264_frame_t **frames, int num_frames, int b_intra )
1088 {
1089     int idx = !b_intra;
1090     int last_nonb, cur_nonb = 1;
1091     int bframes = 0;
1092
1093     x264_emms();
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);
1098
1099     int i = num_frames;
1100
1101     if( b_intra )
1102         x264_slicetype_frame_cost( h, a, frames, 0, 0, 0 );
1103
1104     while( i > 0 && IS_X264_TYPE_B( frames[i]->i_type ) )
1105         i--;
1106     last_nonb = i;
1107
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 )
1112     {
1113         if( b_intra )
1114         {
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) );
1117             return;
1118         }
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) );
1121     }
1122     else
1123     {
1124         if( last_nonb < idx )
1125             return;
1126         memset( frames[last_nonb]->i_propagate_cost, 0, h->mb.i_mb_count * sizeof(uint16_t) );
1127     }
1128
1129     while( i-- > idx )
1130     {
1131         cur_nonb = i;
1132         while( IS_X264_TYPE_B( frames[cur_nonb]->i_type ) && cur_nonb > 0 )
1133             cur_nonb--;
1134         if( cur_nonb < idx )
1135             break;
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 )
1140         {
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 )
1145             {
1146                 int p0 = i > middle ? middle : cur_nonb;
1147                 int p1 = i < middle ? middle : last_nonb;
1148                 if( i != middle )
1149                 {
1150                     x264_slicetype_frame_cost( h, a, frames, p0, p1, i );
1151                     x264_macroblock_tree_propagate( h, frames, average_duration, p0, p1, i, 0 );
1152                 }
1153                 i--;
1154             }
1155             x264_macroblock_tree_propagate( h, frames, average_duration, cur_nonb, last_nonb, middle, 1 );
1156         }
1157         else
1158         {
1159             while( i > cur_nonb )
1160             {
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 );
1163                 i--;
1164             }
1165         }
1166         x264_macroblock_tree_propagate( h, frames, average_duration, cur_nonb, last_nonb, last_nonb, 1 );
1167         last_nonb = cur_nonb;
1168     }
1169
1170     if( !h->param.rc.i_lookahead )
1171     {
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 );
1175     }
1176
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 );
1180 }
1181
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 )
1183 {
1184     int cost = x264_slicetype_frame_cost( h, a, frames, p0, p1, b );
1185     if( h->param.rc.i_aq_mode )
1186     {
1187         if( h->param.rc.b_mb_tree )
1188             return x264_slicetype_frame_cost_recalculate( h, frames, p0, p1, b );
1189         else
1190             return frames[b]->i_cost_est_aq[b-p0][p1-b];
1191     }
1192     return cost;
1193 }
1194
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 )
1196 {
1197     cur_frame->i_cpb_delay = *i_cpb_delay;
1198     cur_frame->i_dpb_output_delay = cur_frame->i_field_cnt - *i_coded_fields;
1199
1200     // add a correction term for frame reordering
1201     cur_frame->i_dpb_output_delay += h->sps->vui.i_num_reorder_frames*2;
1202
1203     // fix possible negative dpb_output_delay because of pulldown changes and reordering
1204     if( cur_frame->i_dpb_output_delay < 0 )
1205     {
1206         cur_frame->i_cpb_delay += cur_frame->i_dpb_output_delay;
1207         cur_frame->i_dpb_output_delay = 0;
1208         if( prev_frame )
1209             prev_frame->i_cpb_duration += cur_frame->i_dpb_output_delay;
1210     }
1211
1212     // don't reset cpb delay for IDR frames when using intra-refresh
1213     if( cur_frame->b_keyframe && !h->param.b_intra_refresh )
1214         *i_cpb_delay = 0;
1215
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;
1219 }
1220
1221 static void x264_vbv_lookahead( x264_t *h, x264_mb_analysis_t *a, x264_frame_t **frames, int num_frames, int keyframe )
1222 {
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 ) )
1227         cur_nonb++;
1228     int next_nonb = keyframe ? last_nonb : cur_nonb;
1229
1230     if( frames[cur_nonb]->i_coded_fields_lookahead >= 0 )
1231     {
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;
1234     }
1235
1236     while( cur_nonb < num_frames )
1237     {
1238         /* P/I cost: This shouldn't include the cost of next_nonb */
1239         if( next_nonb != cur_nonb )
1240         {
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 );
1247             if( prev_frame )
1248             {
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;
1251             }
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;
1256             idx++;
1257         }
1258         /* Handle the B-frames: coded order */
1259         for( int i = last_nonb+1; i < cur_nonb; i++, idx++ )
1260         {
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 );
1266             if( prev_frame )
1267             {
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;
1270             }
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;
1275         }
1276         last_nonb = cur_nonb;
1277         cur_nonb++;
1278         while( cur_nonb <= num_frames && IS_X264_TYPE_B( frames[cur_nonb]->i_type ) )
1279             cur_nonb++;
1280     }
1281     frames[next_nonb]->i_planned_type[idx] = X264_TYPE_AUTO;
1282 }
1283
1284 static int x264_slicetype_path_cost( x264_t *h, x264_mb_analysis_t *a, x264_frame_t **frames, char *path, int threshold )
1285 {
1286     int loc = 1;
1287     int cost = 0;
1288     int cur_nonb = 0;
1289     path--; /* Since the 1st path element is really the second frame */
1290     while( path[loc] )
1291     {
1292         int next_nonb = loc;
1293         /* Find the location of the next non-B-frame. */
1294         while( path[next_nonb] == 'B' )
1295             next_nonb++;
1296
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 );
1300         else /* I-frame */
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 )
1304             break;
1305
1306         if( h->param.i_bframe_pyramid && next_nonb - cur_nonb > 2 )
1307         {
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 );
1314         }
1315         else
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 );
1318
1319         loc = next_nonb + 1;
1320         cur_nonb = next_nonb;
1321     }
1322     return cost;
1323 }
1324
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] )
1330 {
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;
1335     int idx = 0;
1336
1337     /* Iterate over all currently possible paths */
1338     for( int path = 0; path < num_paths; path++ )
1339     {
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" );
1345
1346         int possible = 1;
1347         for( int i = 1; i <= length; i++ )
1348         {
1349             int i_type = frames[i]->i_type;
1350             if( i_type == X264_TYPE_AUTO )
1351                 continue;
1352             if( IS_X264_TYPE_B( i_type ) )
1353                 possible = possible && (i < len || i == length || paths[idx][i-1] == 'B');
1354             else
1355             {
1356                 possible = possible && (i < len || paths[idx][i-1] != 'B');
1357                 paths[idx][i-1] = IS_X264_TYPE_I( i_type ) ? 'I' : 'P';
1358             }
1359         }
1360
1361         if( possible || !best_possible )
1362         {
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 )
1368             {
1369                 best_cost = cost;
1370                 best_possible = possible;
1371                 idx ^= 1;
1372             }
1373         }
1374     }
1375
1376     /* Store the best path. */
1377     memcpy( best_paths[length % (X264_BFRAME_MAX+1)], paths[idx^1], length );
1378 }
1379
1380 static int scenecut_internal( x264_t *h, x264_mb_analysis_t *a, x264_frame_t **frames, int p0, int p1, int real_scenecut )
1381 {
1382     x264_frame_t *frame = frames[p1];
1383
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) )
1386         return 0;
1387
1388     x264_slicetype_frame_cost( h, a, frames, p0, p1, p1 );
1389
1390     int icost = frame->i_cost_est[0][0];
1391     int pcost = frame->i_cost_est[p1-p0][0];
1392     float f_bias;
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;
1397     int res;
1398
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;
1405     else
1406     {
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 );
1411     }
1412
1413     res = pcost >= (1.0 - f_bias) * icost;
1414     if( res && real_scenecut )
1415     {
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",
1419                   frame->i_frame,
1420                   icost, pcost, 1. - (double)pcost / icost,
1421                   f_bias, i_gop_size, imb, pmb );
1422     }
1423     return res;
1424 }
1425
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 )
1427 {
1428     /* Only do analysis during a normal scenecut check. */
1429     if( real_scenecut && h->param.i_bframe )
1430     {
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;
1436         else
1437             origmaxp1++;
1438         int maxp1 = X264_MIN( origmaxp1, num_frames );
1439
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;
1448
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;
1458     }
1459
1460     /* Ignore frames that are part of a flash, i.e. cannot be real scenecuts. */
1461     if( !frames[p1]->b_scenecut )
1462         return 0;
1463     return scenecut_internal( h, a, frames, p0, p1, real_scenecut );
1464 }
1465
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))
1468
1469 void x264_slicetype_analyse( x264_t *h, int intra_minigop )
1470 {
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;
1483
1484     assert( h->frames.b_have_lowres );
1485
1486     if( !h->lookahead->last_nonb )
1487         return;
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];
1491
1492     x264_lowres_context_init( h, &a );
1493
1494     if( !framecnt )
1495     {
1496         if( h->param.rc.b_mb_tree )
1497             x264_macroblock_tree( h, &a, frames, 0, keyframe );
1498         return;
1499     }
1500
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 );
1503
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 )
1511         num_frames++;
1512     else if( num_frames == 0 )
1513     {
1514         frames[1]->i_type = X264_TYPE_I;
1515         return;
1516     }
1517
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 ) )
1520     {
1521         if( frames[1]->i_type == X264_TYPE_AUTO )
1522             frames[1]->i_type = X264_TYPE_I;
1523         return;
1524     }
1525
1526 #if HAVE_OPENCL
1527     x264_opencl_slicetype_prep( h, frames, num_frames, a.i_lambda );
1528 #endif
1529
1530     /* Replace forced keyframes with I/IDR-frames */
1531     for( int j = 1; j <= num_frames; j++ )
1532     {
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;
1535     }
1536
1537     /* Close GOP at IDR-frames */
1538     for( int j = 2; j <= num_frames; j++ )
1539     {
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;
1542     }
1543
1544     int num_analysed_frames = num_frames;
1545     int reset_start;
1546
1547     if( h->param.i_bframe )
1548     {
1549         if( h->param.i_bframe_adaptive == X264_B_ADAPT_TRELLIS )
1550         {
1551             if( num_frames > 1 )
1552             {
1553                 char best_paths[X264_BFRAME_MAX+1][X264_LOOKAHEAD_MAX+1] = {"","P"};
1554                 int best_path_index = num_frames % (X264_BFRAME_MAX+1);
1555
1556                 /* Perform the frametype analysis. */
1557                 for( int j = 2; j <= num_frames; j++ )
1558                     x264_slicetype_path( h, &a, frames, j, best_paths );
1559
1560                 /* Load the results of the analysis into the frame types. */
1561                 for( int j = 1; j < num_frames; j++ )
1562                 {
1563                     if( best_paths[best_path_index][j-1] != 'B' )
1564                     {
1565                         if( IS_X264_TYPE_AUTO_OR_B( frames[j]->i_type ) )
1566                             frames[j]->i_type = X264_TYPE_P;
1567                     }
1568                     else
1569                     {
1570                         if( frames[j]->i_type == X264_TYPE_AUTO )
1571                             frames[j]->i_type = X264_TYPE_B;
1572                     }
1573                 }
1574             }
1575         }
1576         else if( h->param.i_bframe_adaptive == X264_B_ADAPT_FAST )
1577         {
1578             int last_nonb = 0;
1579             int num_bframes = h->param.i_bframe;
1580             char path[X264_LOOKAHEAD_MAX+1];
1581             for( int j = 1; j < num_frames; j++ )
1582             {
1583                 if( j-1 > 0 && IS_X264_TYPE_B( frames[j-1]->i_type ) )
1584                     num_bframes--;
1585                 else
1586                 {
1587                     last_nonb = j-1;
1588                     num_bframes = h->param.i_bframe;
1589                 }
1590                 if( !num_bframes )
1591                 {
1592                     if( IS_X264_TYPE_AUTO_OR_B( frames[j]->i_type ) )
1593                         frames[j]->i_type = X264_TYPE_P;
1594                     continue;
1595                 }
1596
1597                 if( frames[j]->i_type != X264_TYPE_AUTO )
1598                     continue;
1599
1600                 if( IS_X264_TYPE_B( frames[j+1]->i_type ) )
1601                 {
1602                     frames[j]->i_type = X264_TYPE_P;
1603                     continue;
1604                 }
1605
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 );
1612
1613                 if( cost_b < cost_p )
1614                     frames[j]->i_type = X264_TYPE_B;
1615                 else
1616                     frames[j]->i_type = X264_TYPE_P;
1617             }
1618         }
1619         else
1620         {
1621             int num_bframes = h->param.i_bframe;
1622             for( int j = 1; j < num_frames; j++ )
1623             {
1624                 if( !num_bframes )
1625                 {
1626                     if( IS_X264_TYPE_AUTO_OR_B( frames[j]->i_type ) )
1627                         frames[j]->i_type = X264_TYPE_P;
1628                 }
1629                 else if( frames[j]->i_type == X264_TYPE_AUTO )
1630                 {
1631                     if( IS_X264_TYPE_B( frames[j+1]->i_type ) )
1632                         frames[j]->i_type = X264_TYPE_P;
1633                     else
1634                         frames[j]->i_type = X264_TYPE_B;
1635                 }
1636                 if( IS_X264_TYPE_B( frames[j]->i_type ) )
1637                     num_bframes--;
1638                 else
1639                     num_bframes = h->param.i_bframe;
1640             }
1641         }
1642         if( IS_X264_TYPE_AUTO_OR_B( frames[num_frames]->i_type ) )
1643             frames[num_frames]->i_type = X264_TYPE_P;
1644
1645         int num_bframes = 0;
1646         while( num_bframes < num_frames && IS_X264_TYPE_B( frames[num_bframes+1]->i_type ) )
1647             num_bframes++;
1648
1649         /* Check scenecut on the first minigop. */
1650         for( int j = 1; j < num_bframes+1; j++ )
1651         {
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 ) )
1654             {
1655                 frames[j]->i_type = X264_TYPE_P;
1656                 num_analysed_frames = j;
1657                 break;
1658             }
1659         }
1660
1661         reset_start = keyframe ? 1 : X264_MIN( num_bframes+2, num_analysed_frames+1 );
1662     }
1663     else
1664     {
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;
1669     }
1670
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 );
1675
1676     /* Enforce keyframe limit. */
1677     if( !h->param.b_intra_refresh )
1678     {
1679         int last_keyframe = h->lookahead->i_last_keyframe;
1680         int last_possible = 0;
1681         for( int j = 1; j <= num_frames; j++ )
1682         {
1683             x264_frame_t *frm = frames[j];
1684             int keyframe_dist = frm->i_frame - last_keyframe;
1685
1686             if( IS_X264_TYPE_AUTO_OR_I( frm->i_forced_type ) )
1687             {
1688                 if( h->param.b_open_gop || !IS_X264_TYPE_B( frames[j-1]->i_forced_type ) )
1689                     last_possible = j;
1690             }
1691             if( keyframe_dist >= h->param.i_keyint_max )
1692             {
1693                 if( last_possible != 0 && last_possible != j )
1694                 {
1695                     j = last_possible;
1696                     frm = frames[j];
1697                     keyframe_dist = frm->i_frame - last_keyframe;
1698                 }
1699                 last_possible = 0;
1700                 if( frm->i_type != X264_TYPE_IDR )
1701                     frm->i_type = h->param.b_open_gop ? X264_TYPE_I : X264_TYPE_IDR;
1702             }
1703             if( frm->i_type == X264_TYPE_I && keyframe_dist >= h->param.i_keyint_min )
1704             {
1705                 if( h->param.b_open_gop )
1706                 {
1707                     last_keyframe = frm->i_frame;
1708                     if( h->param.b_bluray_compat )
1709                     {
1710                         // Use bluray order
1711                         int bframes = 0;
1712                         while( bframes < j-1 && IS_X264_TYPE_B( frames[j-1-bframes]->i_type ) )
1713                             bframes++;
1714                         last_keyframe -= bframes;
1715                     }
1716                 }
1717                 else if( frm->i_forced_type != X264_TYPE_I )
1718                     frm->i_type = X264_TYPE_IDR;
1719             }
1720             if( frm->i_type == X264_TYPE_IDR )
1721             {
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;
1725             }
1726         }
1727     }
1728
1729     if( vbv_lookahead )
1730         x264_vbv_lookahead( h, &a, frames, num_frames, keyframe );
1731
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;
1735
1736 #if HAVE_OPENCL
1737     x264_opencl_slicetype_end( h );
1738 #endif
1739 }
1740
1741 void x264_slicetype_decide( x264_t *h )
1742 {
1743     x264_frame_t *frames[X264_BFRAME_MAX+2];
1744     x264_frame_t *frm;
1745     int bframes;
1746     int brefs;
1747
1748     if( !h->lookahead->next.i_size )
1749         return;
1750
1751     int lookahead_size = h->lookahead->next.i_size;
1752
1753     for( int i = 0; i < h->lookahead->next.i_size; i++ )
1754     {
1755         if( h->param.b_vfr_input )
1756         {
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);
1759             else
1760                 h->lookahead->next.list[i]->i_duration = h->i_prev_duration;
1761         }
1762         else
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;
1768
1769         if( h->lookahead->next.list[i]->i_frame > h->i_disp_fields_last_frame && lookahead_size > 0 )
1770         {
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;
1774         }
1775         else if( lookahead_size == 0 )
1776         {
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;
1779         }
1780     }
1781
1782     if( h->param.rc.b_stat_read )
1783     {
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 );
1788     }
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 );
1794
1795     for( bframes = 0, brefs = 0;; bframes++ )
1796     {
1797         frm = h->lookahead->next.list[bframes];
1798
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 )) )
1801         {
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 );
1804         }
1805
1806         if( frm->i_type == X264_TYPE_BREF && h->param.i_bframe_pyramid < X264_B_PYRAMID_NORMAL &&
1807             brefs == h->param.i_bframe_pyramid )
1808         {
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] );
1812         }
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) )
1817         {
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 );
1821         }
1822
1823         if( frm->i_type == X264_TYPE_KEYFRAME )
1824             frm->i_type = h->param.b_open_gop ? X264_TYPE_I : X264_TYPE_IDR;
1825
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 )
1828         {
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;
1834             if( warn )
1835             {
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;
1838             }
1839         }
1840         if( frm->i_type == X264_TYPE_I && frm->i_frame - h->lookahead->i_last_keyframe >= h->param.i_keyint_min )
1841         {
1842             if( h->param.b_open_gop )
1843             {
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;
1848             }
1849             else
1850                 frm->i_type = X264_TYPE_IDR;
1851         }
1852         if( frm->i_type == X264_TYPE_IDR )
1853         {
1854             /* Close GOP */
1855             h->lookahead->i_last_keyframe = frm->i_frame;
1856             frm->b_keyframe = 1;
1857             if( bframes > 0 )
1858             {
1859                 bframes--;
1860                 h->lookahead->next.list[bframes]->i_type = X264_TYPE_P;
1861             }
1862         }
1863
1864         if( bframes == h->param.i_bframe ||
1865             !h->lookahead->next.list[bframes+1] )
1866         {
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;
1872         }
1873
1874         if( frm->i_type == X264_TYPE_BREF )
1875             brefs++;
1876
1877         if( frm->i_type == X264_TYPE_AUTO )
1878             frm->i_type = X264_TYPE_B;
1879
1880         else if( !IS_X264_TYPE_B( frm->i_type ) ) break;
1881     }
1882
1883     if( bframes )
1884         h->lookahead->next.list[bframes-1]->b_last_minigop_bframe = 1;
1885     h->lookahead->next.list[bframes]->i_bframes = bframes;
1886
1887     /* insert a bref into the sequence */
1888     if( h->param.i_bframe_pyramid && bframes > 1 && !brefs )
1889     {
1890         h->lookahead->next.list[(bframes-1)/2]->i_type = X264_TYPE_BREF;
1891         brefs++;
1892     }
1893
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 )
1896     {
1897         x264_mb_analysis_t a;
1898         int p0, p1, b;
1899         p1 = b = bframes + 1;
1900
1901         x264_lowres_context_init( h, &a );
1902
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 ) )
1906             p0 = bframes + 1;
1907         else // P
1908             p0 = 0;
1909
1910         x264_slicetype_frame_cost( h, &a, frames, p0, p1, b );
1911
1912         if( (p0 != p1 || bframes) && h->param.rc.i_vbv_buffer_size )
1913         {
1914             /* We need the intra costs for row SATDs. */
1915             x264_slicetype_frame_cost( h, &a, frames, b, b, b );
1916
1917             /* We need B-frame costs for row SATDs. */
1918             p0 = 0;
1919             for( b = 1; b <= bframes; b++ )
1920             {
1921                 if( frames[b]->i_type == X264_TYPE_B )
1922                     for( p1 = b; frames[p1]->i_type == X264_TYPE_B; )
1923                         p1++;
1924                 else
1925                     p1 = bframes + 1;
1926                 x264_slicetype_frame_cost( h, &a, frames, p0, p1, b );
1927                 if( frames[b]->i_type == X264_TYPE_BREF )
1928                     p0 = b;
1929             }
1930         }
1931     }
1932
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 )
1936     {
1937         x264_emms();
1938         x264_weights_analyse( h, h->lookahead->next.list[bframes], h->lookahead->last_nonb, 0 );
1939     }
1940
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;
1944     if( bframes )
1945     {
1946         int idx_list[] = { brefs+1, 1 };
1947         for( int i = 0; i < bframes; i++ )
1948         {
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;
1952         }
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*) );
1956     }
1957
1958     for( int i = 0; i <= bframes; i++ )
1959     {
1960         h->lookahead->next.list[i]->i_coded = i_coded++;
1961         if( i )
1962         {
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;
1966         }
1967         else
1968             x264_calculate_durations( h, h->lookahead->next.list[i], NULL, &h->i_cpb_delay, &h->i_coded_fields );
1969     }
1970 }
1971
1972 int x264_rc_analyse_slice( x264_t *h )
1973 {
1974     int p0 = 0, p1, b;
1975     int cost;
1976     x264_emms();
1977
1978     if( IS_X264_TYPE_I(h->fenc->i_type) )
1979         p1 = b = 0;
1980     else if( h->fenc->i_type == X264_TYPE_P )
1981         p1 = b = h->fenc->i_bframes + 1;
1982     else //B
1983     {
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;
1986     }
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;
1989
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 );
1993
1994     if( h->param.rc.b_mb_tree && !h->param.rc.b_stat_read )
1995     {
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 );
1999     }
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];
2003
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) );
2010
2011     if( h->param.b_intra_refresh && h->param.rc.i_vbv_buffer_size && h->fenc->i_type == X264_TYPE_P )
2012     {
2013         int ip_factor = 256 * h->param.rc.f_ip_factor; /* fix8 */
2014         for( int y = 0; y < h->mb.i_mb_height; y++ )
2015         {
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++ )
2018             {
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;
2024                 else
2025                     h->fdec->i_row_satd[y] += diff;
2026                 cost += diff;
2027             }
2028         }
2029     }
2030
2031     return cost;
2032 }