]> git.sesse.net Git - x264/blob - encoder/slicetype.c
checkasm: Check the right output range for integral_initXh
[x264] / encoder / slicetype.c
1 /*****************************************************************************
2  * slicetype.c: lookahead analysis
3  *****************************************************************************
4  * Copyright (C) 2005-2015 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                                       int b_intra_penalty );
38
39 void x264_weights_analyse( x264_t *h, x264_frame_t *fenc, x264_frame_t *ref, int b_lookahead );
40
41 #if HAVE_OPENCL
42 int x264_opencl_lowres_init( x264_t *h, x264_frame_t *fenc, int lambda );
43 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 );
44 int x264_opencl_finalize_cost( x264_t *h, int lambda, x264_frame_t **frames, int p0, int p1, int b, int dist_scale_factor );
45 int x264_opencl_precalculate_frame_cost( x264_t *h, x264_frame_t **frames, int lambda, int p0, int p1, int b );
46 void x264_opencl_flush( x264_t *h );
47 void x264_opencl_slicetype_prep( x264_t *h, x264_frame_t **frames, int num_frames, int lambda );
48 void x264_opencl_slicetype_end( x264_t *h );
49 #endif
50
51 static void x264_lowres_context_init( x264_t *h, x264_mb_analysis_t *a )
52 {
53     a->i_qp = X264_LOOKAHEAD_QP;
54     a->i_lambda = x264_lambda_tab[ a->i_qp ];
55     x264_mb_analyse_load_costs( h, a );
56     if( h->param.analyse.i_subpel_refine > 1 )
57     {
58         h->mb.i_me_method = X264_MIN( X264_ME_HEX, h->param.analyse.i_me_method );
59         h->mb.i_subpel_refine = 4;
60     }
61     else
62     {
63         h->mb.i_me_method = X264_ME_DIA;
64         h->mb.i_subpel_refine = 2;
65     }
66     h->mb.b_chroma_me = 0;
67 }
68
69 /* makes a non-h264 weight (i.e. fix7), into an h264 weight */
70 static void x264_weight_get_h264( int weight_nonh264, int offset, x264_weight_t *w )
71 {
72     w->i_offset = offset;
73     w->i_denom = 7;
74     w->i_scale = weight_nonh264;
75     while( w->i_denom > 0 && (w->i_scale > 127) )
76     {
77         w->i_denom--;
78         w->i_scale >>= 1;
79     }
80     w->i_scale = X264_MIN( w->i_scale, 127 );
81 }
82
83 static NOINLINE pixel *x264_weight_cost_init_luma( x264_t *h, x264_frame_t *fenc, x264_frame_t *ref, pixel *dest )
84 {
85     int ref0_distance = fenc->i_frame - ref->i_frame - 1;
86     /* Note: this will never run during lookahead as weights_analyse is only called if no
87      * motion search has been done. */
88     if( fenc->lowres_mvs[0][ref0_distance][0][0] != 0x7FFF )
89     {
90         int i_stride = fenc->i_stride_lowres;
91         int i_lines = fenc->i_lines_lowres;
92         int i_width = fenc->i_width_lowres;
93         int i_mb_xy = 0;
94         pixel *p = dest;
95
96         for( int y = 0; y < i_lines; y += 8, p += i_stride*8 )
97             for( int x = 0; x < i_width; x += 8, i_mb_xy++ )
98             {
99                 int mvx = fenc->lowres_mvs[0][ref0_distance][i_mb_xy][0];
100                 int mvy = fenc->lowres_mvs[0][ref0_distance][i_mb_xy][1];
101                 h->mc.mc_luma( p+x, i_stride, ref->lowres, i_stride,
102                                mvx+(x<<2), mvy+(y<<2), 8, 8, x264_weight_none );
103             }
104         x264_emms();
105         return dest;
106     }
107     x264_emms();
108     return ref->lowres[0];
109 }
110
111 /* How data is organized for 4:2:0/4:2:2 chroma weightp:
112  * [U: ref] [U: fenc]
113  * [V: ref] [V: fenc]
114  * fenc = ref + offset
115  * v = u + stride * chroma height */
116
117 static NOINLINE void x264_weight_cost_init_chroma( x264_t *h, x264_frame_t *fenc, x264_frame_t *ref, pixel *dstu, pixel *dstv )
118 {
119     int ref0_distance = fenc->i_frame - ref->i_frame - 1;
120     int i_stride = fenc->i_stride[1];
121     int i_offset = i_stride / 2;
122     int i_lines = fenc->i_lines[1];
123     int i_width = fenc->i_width[1];
124     int v_shift = CHROMA_V_SHIFT;
125     int cw = 8*h->mb.i_mb_width;
126     int ch = 16*h->mb.i_mb_height >> v_shift;
127     int height = 16 >> v_shift;
128
129     if( fenc->lowres_mvs[0][ref0_distance][0][0] != 0x7FFF )
130     {
131         x264_frame_expand_border_chroma( h, ref, 1 );
132         for( int y = 0, mb_xy = 0, pel_offset_y = 0; y < i_lines; y += height, pel_offset_y = y*i_stride )
133             for( int x = 0, pel_offset_x = 0; x < i_width; x += 8, mb_xy++, pel_offset_x += 8 )
134             {
135                 pixel *pixu = dstu + pel_offset_y + pel_offset_x;
136                 pixel *pixv = dstv + pel_offset_y + pel_offset_x;
137                 pixel *src1 =  ref->plane[1] + pel_offset_y + pel_offset_x*2; /* NV12/NV16 */
138                 int mvx = fenc->lowres_mvs[0][ref0_distance][mb_xy][0];
139                 int mvy = fenc->lowres_mvs[0][ref0_distance][mb_xy][1];
140                 h->mc.mc_chroma( pixu, pixv, i_stride, src1, i_stride, mvx, 2*mvy>>v_shift, 8, height );
141             }
142     }
143     else
144         h->mc.plane_copy_deinterleave( dstu, i_stride, dstv, i_stride, ref->plane[1], i_stride, cw, ch );
145     h->mc.plane_copy_deinterleave( dstu+i_offset, i_stride, dstv+i_offset, i_stride, fenc->plane[1], i_stride, cw, ch );
146     x264_emms();
147 }
148
149 static NOINLINE pixel *x264_weight_cost_init_chroma444( x264_t *h, x264_frame_t *fenc, x264_frame_t *ref, pixel *dst, int p )
150 {
151     int ref0_distance = fenc->i_frame - ref->i_frame - 1;
152     int i_stride = fenc->i_stride[p];
153     int i_lines = fenc->i_lines[p];
154     int i_width = fenc->i_width[p];
155
156     if( fenc->lowres_mvs[0][ref0_distance][0][0] != 0x7FFF )
157     {
158         x264_frame_expand_border_chroma( h, ref, p );
159         for( int y = 0, mb_xy = 0, pel_offset_y = 0; y < i_lines; y += 16, pel_offset_y = y*i_stride )
160             for( int x = 0, pel_offset_x = 0; x < i_width; x += 16, mb_xy++, pel_offset_x += 16 )
161             {
162                 pixel *pix = dst + pel_offset_y + pel_offset_x;
163                 pixel *src = ref->plane[p] + pel_offset_y + pel_offset_x;
164                 int mvx = fenc->lowres_mvs[0][ref0_distance][mb_xy][0] / 2;
165                 int mvy = fenc->lowres_mvs[0][ref0_distance][mb_xy][1] / 2;
166                 /* We don't want to calculate hpels for fenc frames, so we round the motion
167                  * vectors to fullpel here.  It's not too bad, I guess? */
168                 h->mc.copy_16x16_unaligned( pix, i_stride, src+mvx+mvy*i_stride, i_stride, 16 );
169             }
170         x264_emms();
171         return dst;
172     }
173     x264_emms();
174     return ref->plane[p];
175 }
176
177 static int x264_weight_slice_header_cost( x264_t *h, x264_weight_t *w, int b_chroma )
178 {
179     /* Add cost of weights in the slice header. */
180     int lambda = x264_lambda_tab[X264_LOOKAHEAD_QP];
181     /* 4 times higher, because chroma is analyzed at full resolution. */
182     if( b_chroma )
183         lambda *= 4;
184     int numslices;
185     if( h->param.i_slice_count )
186         numslices = h->param.i_slice_count;
187     else if( h->param.i_slice_max_mbs )
188         numslices = (h->mb.i_mb_width * h->mb.i_mb_height + h->param.i_slice_max_mbs-1) / h->param.i_slice_max_mbs;
189     else
190         numslices = 1;
191     /* FIXME: find a way to account for --slice-max-size?
192      * 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.
193      * Cut denom cost in half if chroma, since it's shared between the two chroma planes. */
194     int denom_cost = bs_size_ue( w[0].i_denom ) * (2 - b_chroma);
195     return lambda * numslices * ( 10 + denom_cost + 2 * (bs_size_se( w[0].i_scale ) + bs_size_se( w[0].i_offset )) );
196 }
197
198 static NOINLINE unsigned int x264_weight_cost_luma( x264_t *h, x264_frame_t *fenc, pixel *src, x264_weight_t *w )
199 {
200     unsigned int cost = 0;
201     int i_stride = fenc->i_stride_lowres;
202     int i_lines = fenc->i_lines_lowres;
203     int i_width = fenc->i_width_lowres;
204     pixel *fenc_plane = fenc->lowres[0];
205     ALIGNED_ARRAY_16( pixel, buf,[8*8] );
206     int pixoff = 0;
207     int i_mb = 0;
208
209     if( w )
210     {
211         for( int y = 0; y < i_lines; y += 8, pixoff = y*i_stride )
212             for( int x = 0; x < i_width; x += 8, i_mb++, pixoff += 8)
213             {
214                 w->weightfn[8>>2]( buf, 8, &src[pixoff], i_stride, w, 8 );
215                 int cmp = h->pixf.mbcmp[PIXEL_8x8]( buf, 8, &fenc_plane[pixoff], i_stride );
216                 cost += X264_MIN( cmp, fenc->i_intra_cost[i_mb] );
217             }
218         cost += x264_weight_slice_header_cost( h, w, 0 );
219     }
220     else
221         for( int y = 0; y < i_lines; y += 8, pixoff = y*i_stride )
222             for( int x = 0; x < i_width; x += 8, i_mb++, pixoff += 8 )
223             {
224                 int cmp = h->pixf.mbcmp[PIXEL_8x8]( &src[pixoff], i_stride, &fenc_plane[pixoff], i_stride );
225                 cost += X264_MIN( cmp, fenc->i_intra_cost[i_mb] );
226             }
227     x264_emms();
228     return cost;
229 }
230
231 static NOINLINE unsigned int x264_weight_cost_chroma( x264_t *h, x264_frame_t *fenc, pixel *ref, x264_weight_t *w )
232 {
233     unsigned int cost = 0;
234     int i_stride = fenc->i_stride[1];
235     int i_lines = fenc->i_lines[1];
236     int i_width = fenc->i_width[1];
237     pixel *src = ref + (i_stride >> 1);
238     ALIGNED_ARRAY_16( pixel, buf, [8*16] );
239     int pixoff = 0;
240     int height = 16 >> CHROMA_V_SHIFT;
241     if( w )
242     {
243         for( int y = 0; y < i_lines; y += height, pixoff = y*i_stride )
244             for( int x = 0; x < i_width; x += 8, pixoff += 8 )
245             {
246                 w->weightfn[8>>2]( buf, 8, &ref[pixoff], i_stride, w, height );
247                 /* The naive and seemingly sensible algorithm is to use mbcmp as in luma.
248                  * But testing shows that for chroma the DC coefficient is by far the most
249                  * important part of the coding cost.  Thus a more useful chroma weight is
250                  * obtained by comparing each block's DC coefficient instead of the actual
251                  * pixels. */
252                 cost += h->pixf.asd8( buf, 8, &src[pixoff], i_stride, height );
253             }
254         cost += x264_weight_slice_header_cost( h, w, 1 );
255     }
256     else
257         for( int y = 0; y < i_lines; y += height, pixoff = y*i_stride )
258             for( int x = 0; x < i_width; x += 8, pixoff += 8 )
259                 cost += h->pixf.asd8( &ref[pixoff], i_stride, &src[pixoff], i_stride, height );
260     x264_emms();
261     return cost;
262 }
263
264 static NOINLINE unsigned int x264_weight_cost_chroma444( x264_t *h, x264_frame_t *fenc, pixel *ref, x264_weight_t *w, int p )
265 {
266     unsigned int cost = 0;
267     int i_stride = fenc->i_stride[p];
268     int i_lines = fenc->i_lines[p];
269     int i_width = fenc->i_width[p];
270     pixel *src = fenc->plane[p];
271     ALIGNED_ARRAY_16( pixel, buf, [16*16] );
272     int pixoff = 0;
273     if( w )
274     {
275         for( int y = 0; y < i_lines; y += 16, pixoff = y*i_stride )
276             for( int x = 0; x < i_width; x += 16, pixoff += 16 )
277             {
278                 w->weightfn[16>>2]( buf, 16, &ref[pixoff], i_stride, w, 16 );
279                 cost += h->pixf.mbcmp[PIXEL_16x16]( buf, 16, &src[pixoff], i_stride );
280             }
281         cost += x264_weight_slice_header_cost( h, w, 1 );
282     }
283     else
284         for( int y = 0; y < i_lines; y += 16, pixoff = y*i_stride )
285             for( int x = 0; x < i_width; x += 16, pixoff += 16 )
286                 cost += h->pixf.mbcmp[PIXEL_16x16]( &ref[pixoff], i_stride, &src[pixoff], i_stride );
287     x264_emms();
288     return cost;
289 }
290
291 void x264_weights_analyse( x264_t *h, x264_frame_t *fenc, x264_frame_t *ref, int b_lookahead )
292 {
293     int i_delta_index = fenc->i_frame - ref->i_frame - 1;
294     /* epsilon is chosen to require at least a numerator of 127 (with denominator = 128) */
295     const float epsilon = 1.f/128.f;
296     x264_weight_t *weights = fenc->weight[0];
297     SET_WEIGHT( weights[0], 0, 1, 0, 0 );
298     SET_WEIGHT( weights[1], 0, 1, 0, 0 );
299     SET_WEIGHT( weights[2], 0, 1, 0, 0 );
300     int chroma_initted = 0;
301     float guess_scale[3];
302     float fenc_mean[3];
303     float ref_mean[3];
304     for( int plane = 0; plane <= 2*!b_lookahead; plane++ )
305     {
306         float fenc_var = fenc->i_pixel_ssd[plane] + !ref->i_pixel_ssd[plane];
307         float ref_var  =  ref->i_pixel_ssd[plane] + !ref->i_pixel_ssd[plane];
308         guess_scale[plane] = sqrtf( fenc_var / ref_var );
309         fenc_mean[plane] = (float)fenc->i_pixel_sum[plane] / (fenc->i_lines[!!plane] * fenc->i_width[!!plane]) / (1 << (BIT_DEPTH - 8));
310         ref_mean[plane]  = (float) ref->i_pixel_sum[plane] / (fenc->i_lines[!!plane] * fenc->i_width[!!plane]) / (1 << (BIT_DEPTH - 8));
311     }
312
313     int chroma_denom = 7;
314     if( !b_lookahead )
315     {
316         /* make sure both our scale factors fit */
317         while( chroma_denom > 0 )
318         {
319             float thresh = 127.f / (1<<chroma_denom);
320             if( guess_scale[1] < thresh && guess_scale[2] < thresh )
321                 break;
322             chroma_denom--;
323         }
324     }
325
326     /* Don't check chroma in lookahead, or if there wasn't a luma weight. */
327     for( int plane = 0; plane <= 2 && !( plane && ( !weights[0].weightfn || b_lookahead ) ); plane++ )
328     {
329         int minoff, minscale, mindenom;
330         unsigned int minscore, origscore;
331         int found;
332
333         //early termination
334         if( fabsf( ref_mean[plane] - fenc_mean[plane] ) < 0.5f && fabsf( 1.f - guess_scale[plane] ) < epsilon )
335         {
336             SET_WEIGHT( weights[plane], 0, 1, 0, 0 );
337             continue;
338         }
339
340         if( plane )
341         {
342             weights[plane].i_denom = chroma_denom;
343             weights[plane].i_scale = x264_clip3( round( guess_scale[plane] * (1<<chroma_denom) ), 0, 255 );
344             if( weights[plane].i_scale > 127 )
345             {
346                 weights[1].weightfn = weights[2].weightfn = NULL;
347                 break;
348             }
349         }
350         else
351             x264_weight_get_h264( round( guess_scale[plane] * 128 ), 0, &weights[plane] );
352
353         found = 0;
354         mindenom = weights[plane].i_denom;
355         minscale = weights[plane].i_scale;
356         minoff = 0;
357
358         pixel *mcbuf;
359         if( !plane )
360         {
361             if( !fenc->b_intra_calculated )
362             {
363                 x264_mb_analysis_t a;
364                 x264_lowres_context_init( h, &a );
365                 x264_slicetype_frame_cost( h, &a, &fenc, 0, 0, 0, 0 );
366             }
367             mcbuf = x264_weight_cost_init_luma( h, fenc, ref, h->mb.p_weight_buf[0] );
368             origscore = minscore = x264_weight_cost_luma( h, fenc, mcbuf, NULL );
369         }
370         else
371         {
372             if( CHROMA444 )
373             {
374                 mcbuf = x264_weight_cost_init_chroma444( h, fenc, ref, h->mb.p_weight_buf[0], plane );
375                 origscore = minscore = x264_weight_cost_chroma444( h, fenc, mcbuf, NULL, plane );
376             }
377             else
378             {
379                 pixel *dstu = h->mb.p_weight_buf[0];
380                 pixel *dstv = h->mb.p_weight_buf[0]+fenc->i_stride[1]*fenc->i_lines[1];
381                 if( !chroma_initted++ )
382                     x264_weight_cost_init_chroma( h, fenc, ref, dstu, dstv );
383                 mcbuf = plane == 1 ? dstu : dstv;
384                 origscore = minscore = x264_weight_cost_chroma( h, fenc, mcbuf, NULL );
385             }
386         }
387
388         if( !minscore )
389             continue;
390
391         /* Picked somewhat arbitrarily */
392         static const uint8_t weight_check_distance[][2] =
393         {
394             {0,0},{0,0},{0,1},{0,1},
395             {0,1},{0,1},{0,1},{1,1},
396             {1,1},{2,1},{2,1},{4,2}
397         };
398         int scale_dist =  b_lookahead ? 0 : weight_check_distance[h->param.analyse.i_subpel_refine][0];
399         int offset_dist = b_lookahead ? 0 : weight_check_distance[h->param.analyse.i_subpel_refine][1];
400
401         int start_scale  = x264_clip3( minscale - scale_dist, 0, 127 );
402         int end_scale    = x264_clip3( minscale + scale_dist, 0, 127 );
403         for( int i_scale = start_scale; i_scale <= end_scale; i_scale++ )
404         {
405             int cur_scale = i_scale;
406             int cur_offset = fenc_mean[plane] - ref_mean[plane] * cur_scale / (1 << mindenom) + 0.5f * b_lookahead;
407             if( cur_offset < - 128 || cur_offset > 127 )
408             {
409                 /* Rescale considering the constraints on cur_offset. We do it in this order
410                  * because scale has a much wider range than offset (because of denom), so
411                  * it should almost never need to be clamped. */
412                 cur_offset = x264_clip3( cur_offset, -128, 127 );
413                 cur_scale = (1 << mindenom) * (fenc_mean[plane] - cur_offset) / ref_mean[plane] + 0.5f;
414                 cur_scale = x264_clip3( cur_scale, 0, 127 );
415             }
416             int start_offset = x264_clip3( cur_offset - offset_dist, -128, 127 );
417             int end_offset   = x264_clip3( cur_offset + offset_dist, -128, 127 );
418             for( int i_off = start_offset; i_off <= end_offset; i_off++ )
419             {
420                 SET_WEIGHT( weights[plane], 1, cur_scale, mindenom, i_off );
421                 unsigned int s;
422                 if( plane )
423                 {
424                     if( CHROMA444 )
425                         s = x264_weight_cost_chroma444( h, fenc, mcbuf, &weights[plane], plane );
426                     else
427                         s = x264_weight_cost_chroma( h, fenc, mcbuf, &weights[plane] );
428                 }
429                 else
430                     s = x264_weight_cost_luma( h, fenc, mcbuf, &weights[plane] );
431                 COPY4_IF_LT( minscore, s, minscale, cur_scale, minoff, i_off, found, 1 );
432
433                 // Don't check any more offsets if the previous one had a lower cost than the current one
434                 if( minoff == start_offset && i_off != start_offset )
435                     break;
436             }
437         }
438         x264_emms();
439
440         /* Use a smaller denominator if possible */
441         if( !plane )
442         {
443             while( mindenom > 0 && !(minscale&1) )
444             {
445                 mindenom--;
446                 minscale >>= 1;
447             }
448         }
449
450         /* FIXME: More analysis can be done here on SAD vs. SATD termination. */
451         /* 0.2% termination derived experimentally to avoid weird weights in frames that are mostly intra. */
452         if( !found || (minscale == 1 << mindenom && minoff == 0) || (float)minscore / origscore > 0.998f )
453         {
454             SET_WEIGHT( weights[plane], 0, 1, 0, 0 );
455             continue;
456         }
457         else
458             SET_WEIGHT( weights[plane], 1, minscale, mindenom, minoff );
459
460         if( h->param.analyse.i_weighted_pred == X264_WEIGHTP_FAKE && weights[0].weightfn && !plane )
461             fenc->f_weighted_cost_delta[i_delta_index] = (float)minscore / origscore;
462     }
463
464     /* Optimize and unify denominator */
465     if( weights[1].weightfn || weights[2].weightfn )
466     {
467         int denom = weights[1].weightfn ? weights[1].i_denom : weights[2].i_denom;
468         int both_weighted = weights[1].weightfn && weights[2].weightfn;
469         /* If only one plane is weighted, the other has an implicit scale of 1<<denom.
470          * With denom==7, this comes out to 128, which is invalid, so don't allow that. */
471         while( (!both_weighted && denom==7) ||
472                (denom > 0 && !(weights[1].weightfn && (weights[1].i_scale&1))
473                          && !(weights[2].weightfn && (weights[2].i_scale&1))) )
474         {
475             denom--;
476             for( int i = 1; i <= 2; i++ )
477                 if( weights[i].weightfn )
478                 {
479                     weights[i].i_scale >>= 1;
480                     weights[i].i_denom = denom;
481                 }
482         }
483     }
484     for( int i = 1; i <= 2; i++ )
485         if( weights[i].weightfn )
486             h->mc.weight_cache( h, &weights[i] );
487
488     if( weights[0].weightfn && b_lookahead )
489     {
490         //scale lowres in lookahead for slicetype_frame_cost
491         pixel *src = ref->buffer_lowres[0];
492         pixel *dst = h->mb.p_weight_buf[0];
493         int width = ref->i_width_lowres + PADH*2;
494         int height = ref->i_lines_lowres + PADV*2;
495         x264_weight_scale_plane( h, dst, ref->i_stride_lowres, src, ref->i_stride_lowres,
496                                  width, height, &weights[0] );
497         fenc->weighted[0] = h->mb.p_weight_buf[0] + PADH + ref->i_stride_lowres * PADV;
498     }
499 }
500
501 /* Output buffers are separated by 128 bytes to avoid false sharing of cachelines
502  * in multithreaded lookahead. */
503 #define PAD_SIZE 32
504 /* cost_est, cost_est_aq, intra_mbs, num rows */
505 #define NUM_INTS 4
506 #define COST_EST 0
507 #define COST_EST_AQ 1
508 #define INTRA_MBS 2
509 #define NUM_ROWS 3
510 #define ROW_SATD (NUM_INTS + (h->mb.i_mb_y - h->i_threadslice_start))
511
512 static void x264_slicetype_mb_cost( x264_t *h, x264_mb_analysis_t *a,
513                                     x264_frame_t **frames, int p0, int p1, int b,
514                                     int dist_scale_factor, int do_search[2], const x264_weight_t *w,
515                                     int *output_inter, int *output_intra )
516 {
517     x264_frame_t *fref0 = frames[p0];
518     x264_frame_t *fref1 = frames[p1];
519     x264_frame_t *fenc  = frames[b];
520     const int b_bidir = (b < p1);
521     const int i_mb_x = h->mb.i_mb_x;
522     const int i_mb_y = h->mb.i_mb_y;
523     const int i_mb_stride = h->mb.i_mb_width;
524     const int i_mb_xy = i_mb_x + i_mb_y * i_mb_stride;
525     const int i_stride = fenc->i_stride_lowres;
526     const int i_pel_offset = 8 * (i_mb_x + i_mb_y * i_stride);
527     const int i_bipred_weight = h->param.analyse.b_weighted_bipred ? 64 - (dist_scale_factor>>2) : 32;
528     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] };
529     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] };
530     int b_frame_score_mb = (i_mb_x > 0 && i_mb_x < h->mb.i_mb_width - 1 &&
531                             i_mb_y > 0 && i_mb_y < h->mb.i_mb_height - 1) ||
532                             h->mb.i_mb_width <= 2 || h->mb.i_mb_height <= 2;
533
534     ALIGNED_ARRAY_16( pixel, pix1,[9*FDEC_STRIDE] );
535     pixel *pix2 = pix1+8;
536     x264_me_t m[2];
537     int i_bcost = COST_MAX;
538     int list_used = 0;
539     /* A small, arbitrary bias to avoid VBV problems caused by zero-residual lookahead blocks. */
540     int lowres_penalty = 4;
541
542     h->mb.pic.p_fenc[0] = h->mb.pic.fenc_buf;
543     h->mc.copy[PIXEL_8x8]( h->mb.pic.p_fenc[0], FENC_STRIDE, &fenc->lowres[0][i_pel_offset], i_stride, 8 );
544
545     if( p0 == p1 )
546         goto lowres_intra_mb;
547
548     // no need for h->mb.mv_min[]
549     h->mb.mv_limit_fpel[0][0] = -8*h->mb.i_mb_x - 4;
550     h->mb.mv_limit_fpel[1][0] = 8*( h->mb.i_mb_width - h->mb.i_mb_x - 1 ) + 4;
551     h->mb.mv_min_spel[0] = 4*( h->mb.mv_limit_fpel[0][0] - 8 );
552     h->mb.mv_max_spel[0] = 4*( h->mb.mv_limit_fpel[1][0] + 8 );
553     if( h->mb.i_mb_x >= h->mb.i_mb_width - 2 )
554     {
555         h->mb.mv_limit_fpel[0][1] = -8*h->mb.i_mb_y - 4;
556         h->mb.mv_limit_fpel[1][1] = 8*( h->mb.i_mb_height - h->mb.i_mb_y - 1 ) + 4;
557         h->mb.mv_min_spel[1] = 4*( h->mb.mv_limit_fpel[0][1] - 8 );
558         h->mb.mv_max_spel[1] = 4*( h->mb.mv_limit_fpel[1][1] + 8 );
559     }
560
561 #define LOAD_HPELS_LUMA(dst, src) \
562     { \
563         (dst)[0] = &(src)[0][i_pel_offset]; \
564         (dst)[1] = &(src)[1][i_pel_offset]; \
565         (dst)[2] = &(src)[2][i_pel_offset]; \
566         (dst)[3] = &(src)[3][i_pel_offset]; \
567     }
568 #define LOAD_WPELS_LUMA(dst,src) \
569     (dst) = &(src)[i_pel_offset];
570
571 #define CLIP_MV( mv ) \
572     { \
573         mv[0] = x264_clip3( mv[0], h->mb.mv_min_spel[0], h->mb.mv_max_spel[0] ); \
574         mv[1] = x264_clip3( mv[1], h->mb.mv_min_spel[1], h->mb.mv_max_spel[1] ); \
575     }
576 #define TRY_BIDIR( mv0, mv1, penalty ) \
577     { \
578         int i_cost; \
579         if( h->param.analyse.i_subpel_refine <= 1 ) \
580         { \
581             int hpel_idx1 = (((mv0)[0]&2)>>1) + ((mv0)[1]&2); \
582             int hpel_idx2 = (((mv1)[0]&2)>>1) + ((mv1)[1]&2); \
583             pixel *src1 = m[0].p_fref[hpel_idx1] + ((mv0)[0]>>2) + ((mv0)[1]>>2) * m[0].i_stride[0]; \
584             pixel *src2 = m[1].p_fref[hpel_idx2] + ((mv1)[0]>>2) + ((mv1)[1]>>2) * m[1].i_stride[0]; \
585             h->mc.avg[PIXEL_8x8]( pix1, 16, src1, m[0].i_stride[0], src2, m[1].i_stride[0], i_bipred_weight ); \
586         } \
587         else \
588         { \
589             intptr_t stride1 = 16, stride2 = 16; \
590             pixel *src1, *src2; \
591             src1 = h->mc.get_ref( pix1, &stride1, m[0].p_fref, m[0].i_stride[0], \
592                                   (mv0)[0], (mv0)[1], 8, 8, w ); \
593             src2 = h->mc.get_ref( pix2, &stride2, m[1].p_fref, m[1].i_stride[0], \
594                                   (mv1)[0], (mv1)[1], 8, 8, w ); \
595             h->mc.avg[PIXEL_8x8]( pix1, 16, src1, stride1, src2, stride2, i_bipred_weight ); \
596         } \
597         i_cost = penalty * a->i_lambda + h->pixf.mbcmp[PIXEL_8x8]( \
598                            m[0].p_fenc[0], FENC_STRIDE, pix1, 16 ); \
599         COPY2_IF_LT( i_bcost, i_cost, list_used, 3 ); \
600     }
601
602     m[0].i_pixel = PIXEL_8x8;
603     m[0].p_cost_mv = a->p_cost_mv;
604     m[0].i_stride[0] = i_stride;
605     m[0].p_fenc[0] = h->mb.pic.p_fenc[0];
606     m[0].weight = w;
607     m[0].i_ref = 0;
608     LOAD_HPELS_LUMA( m[0].p_fref, fref0->lowres );
609     m[0].p_fref_w = m[0].p_fref[0];
610     if( w[0].weightfn )
611         LOAD_WPELS_LUMA( m[0].p_fref_w, fenc->weighted[0] );
612
613     if( b_bidir )
614     {
615         ALIGNED_ARRAY_8( int16_t, dmv,[2],[2] );
616
617         m[1].i_pixel = PIXEL_8x8;
618         m[1].p_cost_mv = a->p_cost_mv;
619         m[1].i_stride[0] = i_stride;
620         m[1].p_fenc[0] = h->mb.pic.p_fenc[0];
621         m[1].i_ref = 0;
622         m[1].weight = x264_weight_none;
623         LOAD_HPELS_LUMA( m[1].p_fref, fref1->lowres );
624         m[1].p_fref_w = m[1].p_fref[0];
625
626         if( fref1->lowres_mvs[0][p1-p0-1][0][0] != 0x7FFF )
627         {
628             int16_t *mvr = fref1->lowres_mvs[0][p1-p0-1][i_mb_xy];
629             dmv[0][0] = ( mvr[0] * dist_scale_factor + 128 ) >> 8;
630             dmv[0][1] = ( mvr[1] * dist_scale_factor + 128 ) >> 8;
631             dmv[1][0] = dmv[0][0] - mvr[0];
632             dmv[1][1] = dmv[0][1] - mvr[1];
633             CLIP_MV( dmv[0] );
634             CLIP_MV( dmv[1] );
635             if( h->param.analyse.i_subpel_refine <= 1 )
636                 M64( dmv ) &= ~0x0001000100010001ULL; /* mv & ~1 */
637         }
638         else
639             M64( dmv ) = 0;
640
641         TRY_BIDIR( dmv[0], dmv[1], 0 );
642         if( M64( dmv ) )
643         {
644             int i_cost;
645             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 );
646             i_cost = h->pixf.mbcmp[PIXEL_8x8]( m[0].p_fenc[0], FENC_STRIDE, pix1, 16 );
647             COPY2_IF_LT( i_bcost, i_cost, list_used, 3 );
648         }
649     }
650
651     for( int l = 0; l < 1 + b_bidir; l++ )
652     {
653         if( do_search[l] )
654         {
655             int i_mvc = 0;
656             int16_t (*fenc_mv)[2] = fenc_mvs[l];
657             ALIGNED_4( int16_t mvc[4][2] );
658
659             /* Reverse-order MV prediction. */
660             M32( mvc[0] ) = 0;
661             M32( mvc[2] ) = 0;
662 #define MVC(mv) { CP32( mvc[i_mvc], mv ); i_mvc++; }
663             if( i_mb_x < h->mb.i_mb_width - 1 )
664                 MVC( fenc_mv[1] );
665             if( i_mb_y < h->i_threadslice_end - 1 )
666             {
667                 MVC( fenc_mv[i_mb_stride] );
668                 if( i_mb_x > 0 )
669                     MVC( fenc_mv[i_mb_stride-1] );
670                 if( i_mb_x < h->mb.i_mb_width - 1 )
671                     MVC( fenc_mv[i_mb_stride+1] );
672             }
673 #undef MVC
674             if( i_mvc <= 1 )
675                 CP32( m[l].mvp, mvc[0] );
676             else
677                 x264_median_mv( m[l].mvp, mvc[0], mvc[1], mvc[2] );
678
679             /* Fast skip for cases of near-zero residual.  Shortcut: don't bother except in the mv0 case,
680              * since anything else is likely to have enough residual to not trigger the skip. */
681             if( !M32( m[l].mvp ) )
682             {
683                 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] );
684                 if( m[l].cost < 64 )
685                 {
686                     M32( m[l].mv ) = 0;
687                     goto skip_motionest;
688                 }
689             }
690
691             x264_me_search( h, &m[l], mvc, i_mvc );
692             m[l].cost -= a->p_cost_mv[0]; // remove mvcost from skip mbs
693             if( M32( m[l].mv ) )
694                 m[l].cost += 5 * a->i_lambda;
695
696 skip_motionest:
697             CP32( fenc_mvs[l], m[l].mv );
698             *fenc_costs[l] = m[l].cost;
699         }
700         else
701         {
702             CP32( m[l].mv, fenc_mvs[l] );
703             m[l].cost = *fenc_costs[l];
704         }
705         COPY2_IF_LT( i_bcost, m[l].cost, list_used, l+1 );
706     }
707
708     if( b_bidir && ( M32( m[0].mv ) || M32( m[1].mv ) ) )
709         TRY_BIDIR( m[0].mv, m[1].mv, 5 );
710
711 lowres_intra_mb:
712     if( !fenc->b_intra_calculated )
713     {
714         ALIGNED_ARRAY_16( pixel, edge,[36] );
715         pixel *pix = &pix1[8+FDEC_STRIDE];
716         pixel *src = &fenc->lowres[0][i_pel_offset];
717         const int intra_penalty = 5 * a->i_lambda;
718         int satds[3];
719         int pixoff = 4 / sizeof(pixel);
720
721         /* Avoid store forwarding stalls by writing larger chunks */
722         memcpy( pix-FDEC_STRIDE, src-i_stride, 16 * sizeof(pixel) );
723         for( int i = -1; i < 8; i++ )
724             M32( &pix[i*FDEC_STRIDE-pixoff] ) = M32( &src[i*i_stride-pixoff] );
725
726         h->pixf.intra_mbcmp_x3_8x8c( h->mb.pic.p_fenc[0], pix, satds );
727         int i_icost = X264_MIN3( satds[0], satds[1], satds[2] );
728
729         if( h->param.analyse.i_subpel_refine > 1 )
730         {
731             h->predict_8x8c[I_PRED_CHROMA_P]( pix );
732             int satd = h->pixf.mbcmp[PIXEL_8x8]( pix, FDEC_STRIDE, h->mb.pic.p_fenc[0], FENC_STRIDE );
733             i_icost = X264_MIN( i_icost, satd );
734             h->predict_8x8_filter( pix, edge, ALL_NEIGHBORS, ALL_NEIGHBORS );
735             for( int i = 3; i < 9; i++ )
736             {
737                 h->predict_8x8[i]( pix, edge );
738                 satd = h->pixf.mbcmp[PIXEL_8x8]( pix, FDEC_STRIDE, h->mb.pic.p_fenc[0], FENC_STRIDE );
739                 i_icost = X264_MIN( i_icost, satd );
740             }
741         }
742
743         i_icost += intra_penalty + lowres_penalty;
744         fenc->i_intra_cost[i_mb_xy] = i_icost;
745         int i_icost_aq = i_icost;
746         if( h->param.rc.i_aq_mode )
747             i_icost_aq = (i_icost_aq * fenc->i_inv_qscale_factor[i_mb_xy] + 128) >> 8;
748         output_intra[ROW_SATD] += i_icost_aq;
749         if( b_frame_score_mb )
750         {
751             output_intra[COST_EST] += i_icost;
752             output_intra[COST_EST_AQ] += i_icost_aq;
753         }
754     }
755     i_bcost += lowres_penalty;
756
757     /* forbid intra-mbs in B-frames, because it's rare and not worth checking */
758     /* FIXME: Should we still forbid them now that we cache intra scores? */
759     if( !b_bidir )
760     {
761         int i_icost = fenc->i_intra_cost[i_mb_xy];
762         int b_intra = i_icost < i_bcost;
763         if( b_intra )
764         {
765             i_bcost = i_icost;
766             list_used = 0;
767         }
768         if( b_frame_score_mb )
769             output_inter[INTRA_MBS] += b_intra;
770     }
771
772     /* In an I-frame, we've already added the results above in the intra section. */
773     if( p0 != p1 )
774     {
775         int i_bcost_aq = i_bcost;
776         if( h->param.rc.i_aq_mode )
777             i_bcost_aq = (i_bcost_aq * fenc->i_inv_qscale_factor[i_mb_xy] + 128) >> 8;
778         output_inter[ROW_SATD] += i_bcost_aq;
779         if( b_frame_score_mb )
780         {
781             /* Don't use AQ-weighted costs for slicetype decision, only for ratecontrol. */
782             output_inter[COST_EST] += i_bcost;
783             output_inter[COST_EST_AQ] += i_bcost_aq;
784         }
785     }
786
787     fenc->lowres_costs[b-p0][p1-b][i_mb_xy] = X264_MIN( i_bcost, LOWRES_COST_MASK ) + (list_used << LOWRES_COST_SHIFT);
788 }
789 #undef TRY_BIDIR
790
791 #define NUM_MBS\
792    (h->mb.i_mb_width > 2 && h->mb.i_mb_height > 2 ?\
793    (h->mb.i_mb_width - 2) * (h->mb.i_mb_height - 2) :\
794     h->mb.i_mb_width * h->mb.i_mb_height)
795
796 typedef struct
797 {
798     x264_t *h;
799     x264_mb_analysis_t *a;
800     x264_frame_t **frames;
801     int p0;
802     int p1;
803     int b;
804     int dist_scale_factor;
805     int *do_search;
806     const x264_weight_t *w;
807     int *output_inter;
808     int *output_intra;
809 } x264_slicetype_slice_t;
810
811 static void x264_slicetype_slice_cost( x264_slicetype_slice_t *s )
812 {
813     x264_t *h = s->h;
814
815     /* Lowres lookahead goes backwards because the MVs are used as predictors in the main encode.
816      * This considerably improves MV prediction overall. */
817
818     /* The edge mbs seem to reduce the predictive quality of the
819      * whole frame's score, but are needed for a spatial distribution. */
820     int do_edges = h->param.rc.b_mb_tree || h->param.rc.i_vbv_buffer_size || h->mb.i_mb_width <= 2 || h->mb.i_mb_height <= 2;
821
822     int start_y = X264_MIN( h->i_threadslice_end - 1, h->mb.i_mb_height - 2 + do_edges );
823     int end_y = X264_MAX( h->i_threadslice_start, 1 - do_edges );
824     int start_x = h->mb.i_mb_width - 2 + do_edges;
825     int end_x = 1 - do_edges;
826
827     for( h->mb.i_mb_y = start_y; h->mb.i_mb_y >= end_y; h->mb.i_mb_y-- )
828         for( h->mb.i_mb_x = start_x; h->mb.i_mb_x >= end_x; h->mb.i_mb_x-- )
829             x264_slicetype_mb_cost( h, s->a, s->frames, s->p0, s->p1, s->b, s->dist_scale_factor,
830                                     s->do_search, s->w, s->output_inter, s->output_intra );
831 }
832
833 static int x264_slicetype_frame_cost( x264_t *h, x264_mb_analysis_t *a,
834                                       x264_frame_t **frames, int p0, int p1, int b,
835                                       int b_intra_penalty )
836 {
837     int i_score = 0;
838     int do_search[2];
839     const x264_weight_t *w = x264_weight_none;
840     x264_frame_t *fenc = frames[b];
841
842     /* Check whether we already evaluated this frame
843      * If we have tried this frame as P, then we have also tried
844      * the preceding frames as B. (is this still true?) */
845     /* Also check that we already calculated the row SATDs for the current frame. */
846     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) )
847         i_score = fenc->i_cost_est[b-p0][p1-b];
848     else
849     {
850         int dist_scale_factor = 128;
851
852         /* For each list, check to see whether we have lowres motion-searched this reference frame before. */
853         do_search[0] = b != p0 && fenc->lowres_mvs[0][b-p0-1][0][0] == 0x7FFF;
854         do_search[1] = b != p1 && fenc->lowres_mvs[1][p1-b-1][0][0] == 0x7FFF;
855         if( do_search[0] )
856         {
857             if( h->param.analyse.i_weighted_pred && b == p1 )
858             {
859                 x264_emms();
860                 x264_weights_analyse( h, fenc, frames[p0], 1 );
861                 w = fenc->weight[0];
862             }
863             fenc->lowres_mvs[0][b-p0-1][0][0] = 0;
864         }
865         if( do_search[1] ) fenc->lowres_mvs[1][p1-b-1][0][0] = 0;
866
867         if( p1 != p0 )
868             dist_scale_factor = ( ((b-p0) << 8) + ((p1-p0) >> 1) ) / (p1-p0);
869
870         int output_buf_size = h->mb.i_mb_height + (NUM_INTS + PAD_SIZE) * h->param.i_lookahead_threads;
871         int *output_inter[X264_LOOKAHEAD_THREAD_MAX+1];
872         int *output_intra[X264_LOOKAHEAD_THREAD_MAX+1];
873         output_inter[0] = h->scratch_buffer2;
874         output_intra[0] = output_inter[0] + output_buf_size;
875
876 #if HAVE_OPENCL
877         if( h->param.b_opencl )
878         {
879             x264_opencl_lowres_init(h, fenc, a->i_lambda );
880             if( do_search[0] )
881             {
882                 x264_opencl_lowres_init( h, frames[p0], a->i_lambda );
883                 x264_opencl_motionsearch( h, frames, b, p0, 0, a->i_lambda, w );
884             }
885             if( do_search[1] )
886             {
887                 x264_opencl_lowres_init( h, frames[p1], a->i_lambda );
888                 x264_opencl_motionsearch( h, frames, b, p1, 1, a->i_lambda, NULL );
889             }
890             if( b != p0 )
891                 x264_opencl_finalize_cost( h, a->i_lambda, frames, p0, p1, b, dist_scale_factor );
892             x264_opencl_flush( h );
893
894             i_score = fenc->i_cost_est[b-p0][p1-b];
895         }
896         else
897 #endif
898         {
899             if( h->param.i_lookahead_threads > 1 )
900             {
901                 x264_slicetype_slice_t s[X264_LOOKAHEAD_THREAD_MAX];
902
903                 for( int i = 0; i < h->param.i_lookahead_threads; i++ )
904                 {
905                     x264_t *t = h->lookahead_thread[i];
906
907                     /* FIXME move this somewhere else */
908                     t->mb.i_me_method = h->mb.i_me_method;
909                     t->mb.i_subpel_refine = h->mb.i_subpel_refine;
910                     t->mb.b_chroma_me = h->mb.b_chroma_me;
911
912                     s[i] = (x264_slicetype_slice_t){ t, a, frames, p0, p1, b, dist_scale_factor, do_search, w,
913                         output_inter[i], output_intra[i] };
914
915                     t->i_threadslice_start = ((h->mb.i_mb_height *  i    + h->param.i_lookahead_threads/2) / h->param.i_lookahead_threads);
916                     t->i_threadslice_end   = ((h->mb.i_mb_height * (i+1) + h->param.i_lookahead_threads/2) / h->param.i_lookahead_threads);
917
918                     int thread_height = t->i_threadslice_end - t->i_threadslice_start;
919                     int thread_output_size = thread_height + NUM_INTS;
920                     memset( output_inter[i], 0, thread_output_size * sizeof(int) );
921                     memset( output_intra[i], 0, thread_output_size * sizeof(int) );
922                     output_inter[i][NUM_ROWS] = output_intra[i][NUM_ROWS] = thread_height;
923
924                     output_inter[i+1] = output_inter[i] + thread_output_size + PAD_SIZE;
925                     output_intra[i+1] = output_intra[i] + thread_output_size + PAD_SIZE;
926
927                     x264_threadpool_run( h->lookaheadpool, (void*)x264_slicetype_slice_cost, &s[i] );
928                 }
929                 for( int i = 0; i < h->param.i_lookahead_threads; i++ )
930                     x264_threadpool_wait( h->lookaheadpool, &s[i] );
931             }
932             else
933             {
934                 h->i_threadslice_start = 0;
935                 h->i_threadslice_end = h->mb.i_mb_height;
936                 memset( output_inter[0], 0, (output_buf_size - PAD_SIZE) * sizeof(int) );
937                 memset( output_intra[0], 0, (output_buf_size - PAD_SIZE) * sizeof(int) );
938                 output_inter[0][NUM_ROWS] = output_intra[0][NUM_ROWS] = h->mb.i_mb_height;
939                 x264_slicetype_slice_t s = (x264_slicetype_slice_t){ h, a, frames, p0, p1, b, dist_scale_factor, do_search, w,
940                     output_inter[0], output_intra[0] };
941                 x264_slicetype_slice_cost( &s );
942             }
943
944             /* Sum up accumulators */
945             if( b == p1 )
946                 fenc->i_intra_mbs[b-p0] = 0;
947             if( !fenc->b_intra_calculated )
948             {
949                 fenc->i_cost_est[0][0] = 0;
950                 fenc->i_cost_est_aq[0][0] = 0;
951             }
952             fenc->i_cost_est[b-p0][p1-b] = 0;
953             fenc->i_cost_est_aq[b-p0][p1-b] = 0;
954
955             int *row_satd_inter = fenc->i_row_satds[b-p0][p1-b];
956             int *row_satd_intra = fenc->i_row_satds[0][0];
957             for( int i = 0; i < h->param.i_lookahead_threads; i++ )
958             {
959                 if( b == p1 )
960                     fenc->i_intra_mbs[b-p0] += output_inter[i][INTRA_MBS];
961                 if( !fenc->b_intra_calculated )
962                 {
963                     fenc->i_cost_est[0][0] += output_intra[i][COST_EST];
964                     fenc->i_cost_est_aq[0][0] += output_intra[i][COST_EST_AQ];
965                 }
966
967                 fenc->i_cost_est[b-p0][p1-b] += output_inter[i][COST_EST];
968                 fenc->i_cost_est_aq[b-p0][p1-b] += output_inter[i][COST_EST_AQ];
969
970                 if( h->param.rc.i_vbv_buffer_size )
971                 {
972                     int row_count = output_inter[i][NUM_ROWS];
973                     memcpy( row_satd_inter, output_inter[i] + NUM_INTS, row_count * sizeof(int) );
974                     if( !fenc->b_intra_calculated )
975                         memcpy( row_satd_intra, output_intra[i] + NUM_INTS, row_count * sizeof(int) );
976                     row_satd_inter += row_count;
977                     row_satd_intra += row_count;
978                 }
979             }
980
981             i_score = fenc->i_cost_est[b-p0][p1-b];
982             if( b != p1 )
983                 i_score = (uint64_t)i_score * 100 / (120 + h->param.i_bframe_bias);
984             else
985                 fenc->b_intra_calculated = 1;
986
987             fenc->i_cost_est[b-p0][p1-b] = i_score;
988             x264_emms();
989         }
990     }
991
992     if( b_intra_penalty )
993     {
994         // arbitrary penalty for I-blocks after B-frames
995         int nmb = NUM_MBS;
996         i_score += (uint64_t)i_score * fenc->i_intra_mbs[b-p0] / (nmb * 8);
997     }
998     return i_score;
999 }
1000
1001 /* If MB-tree changes the quantizers, we need to recalculate the frame cost without
1002  * re-running lookahead. */
1003 static int x264_slicetype_frame_cost_recalculate( x264_t *h, x264_frame_t **frames, int p0, int p1, int b )
1004 {
1005     int i_score = 0;
1006     int *row_satd = frames[b]->i_row_satds[b-p0][p1-b];
1007     float *qp_offset = IS_X264_TYPE_B(frames[b]->i_type) ? frames[b]->f_qp_offset_aq : frames[b]->f_qp_offset;
1008     x264_emms();
1009     for( h->mb.i_mb_y = h->mb.i_mb_height - 1; h->mb.i_mb_y >= 0; h->mb.i_mb_y-- )
1010     {
1011         row_satd[ h->mb.i_mb_y ] = 0;
1012         for( h->mb.i_mb_x = h->mb.i_mb_width - 1; h->mb.i_mb_x >= 0; h->mb.i_mb_x-- )
1013         {
1014             int i_mb_xy = h->mb.i_mb_x + h->mb.i_mb_y*h->mb.i_mb_stride;
1015             int i_mb_cost = frames[b]->lowres_costs[b-p0][p1-b][i_mb_xy] & LOWRES_COST_MASK;
1016             float qp_adj = qp_offset[i_mb_xy];
1017             i_mb_cost = (i_mb_cost * x264_exp2fix8(qp_adj) + 128) >> 8;
1018             row_satd[ h->mb.i_mb_y ] += i_mb_cost;
1019             if( (h->mb.i_mb_y > 0 && h->mb.i_mb_y < h->mb.i_mb_height - 1 &&
1020                  h->mb.i_mb_x > 0 && h->mb.i_mb_x < h->mb.i_mb_width - 1) ||
1021                  h->mb.i_mb_width <= 2 || h->mb.i_mb_height <= 2 )
1022             {
1023                 i_score += i_mb_cost;
1024             }
1025         }
1026     }
1027     return i_score;
1028 }
1029
1030 /* Trade off precision in mbtree for increased range */
1031 #define MBTREE_PRECISION 0.5f
1032
1033 static void x264_macroblock_tree_finish( x264_t *h, x264_frame_t *frame, float average_duration, int ref0_distance )
1034 {
1035     int fps_factor = round( CLIP_DURATION(average_duration) / CLIP_DURATION(frame->f_duration) * 256 / MBTREE_PRECISION );
1036     float weightdelta = 0.0;
1037     if( ref0_distance && frame->f_weighted_cost_delta[ref0_distance-1] > 0 )
1038         weightdelta = (1.0 - frame->f_weighted_cost_delta[ref0_distance-1]);
1039
1040     /* Allow the strength to be adjusted via qcompress, since the two
1041      * concepts are very similar. */
1042     float strength = 5.0f * (1.0f - h->param.rc.f_qcompress);
1043     for( int mb_index = 0; mb_index < h->mb.i_mb_count; mb_index++ )
1044     {
1045         int intra_cost = (frame->i_intra_cost[mb_index] * frame->i_inv_qscale_factor[mb_index] + 128) >> 8;
1046         if( intra_cost )
1047         {
1048             int propagate_cost = (frame->i_propagate_cost[mb_index] * fps_factor + 128) >> 8;
1049             float log2_ratio = x264_log2(intra_cost + propagate_cost) - x264_log2(intra_cost) + weightdelta;
1050             frame->f_qp_offset[mb_index] = frame->f_qp_offset_aq[mb_index] - strength * log2_ratio;
1051         }
1052     }
1053 }
1054
1055 static void x264_macroblock_tree_propagate( x264_t *h, x264_frame_t **frames, float average_duration, int p0, int p1, int b, int referenced )
1056 {
1057     uint16_t *ref_costs[2] = {frames[p0]->i_propagate_cost,frames[p1]->i_propagate_cost};
1058     int dist_scale_factor = ( ((b-p0) << 8) + ((p1-p0) >> 1) ) / (p1-p0);
1059     int i_bipred_weight = h->param.analyse.b_weighted_bipred ? 64 - (dist_scale_factor>>2) : 32;
1060     int16_t (*mvs[2])[2] = { frames[b]->lowres_mvs[0][b-p0-1], frames[b]->lowres_mvs[1][p1-b-1] };
1061     int bipred_weights[2] = {i_bipred_weight, 64 - i_bipred_weight};
1062     int16_t *buf = h->scratch_buffer;
1063     uint16_t *propagate_cost = frames[b]->i_propagate_cost;
1064     uint16_t *lowres_costs = frames[b]->lowres_costs[b-p0][p1-b];
1065
1066     x264_emms();
1067     float fps_factor = CLIP_DURATION(frames[b]->f_duration) / (CLIP_DURATION(average_duration) * 256.0f) * MBTREE_PRECISION;
1068
1069     /* For non-reffed frames the source costs are always zero, so just memset one row and re-use it. */
1070     if( !referenced )
1071         memset( frames[b]->i_propagate_cost, 0, h->mb.i_mb_width * sizeof(uint16_t) );
1072
1073     for( h->mb.i_mb_y = 0; h->mb.i_mb_y < h->mb.i_mb_height; h->mb.i_mb_y++ )
1074     {
1075         int mb_index = h->mb.i_mb_y*h->mb.i_mb_stride;
1076         h->mc.mbtree_propagate_cost( buf, propagate_cost,
1077             frames[b]->i_intra_cost+mb_index, lowres_costs+mb_index,
1078             frames[b]->i_inv_qscale_factor+mb_index, &fps_factor, h->mb.i_mb_width );
1079         if( referenced )
1080             propagate_cost += h->mb.i_mb_width;
1081
1082         h->mc.mbtree_propagate_list( h, ref_costs[0], &mvs[0][mb_index], buf, &lowres_costs[mb_index],
1083                                      bipred_weights[0], h->mb.i_mb_y, h->mb.i_mb_width, 0 );
1084         if( b != p1 )
1085         {
1086             h->mc.mbtree_propagate_list( h, ref_costs[1], &mvs[1][mb_index], buf, &lowres_costs[mb_index],
1087                                          bipred_weights[1], h->mb.i_mb_y, h->mb.i_mb_width, 1 );
1088         }
1089     }
1090
1091     if( h->param.rc.i_vbv_buffer_size && h->param.rc.i_lookahead && referenced )
1092         x264_macroblock_tree_finish( h, frames[b], average_duration, b == p1 ? b - p0 : 0 );
1093 }
1094
1095 static void x264_macroblock_tree( x264_t *h, x264_mb_analysis_t *a, x264_frame_t **frames, int num_frames, int b_intra )
1096 {
1097     int idx = !b_intra;
1098     int last_nonb, cur_nonb = 1;
1099     int bframes = 0;
1100
1101     x264_emms();
1102     float total_duration = 0.0;
1103     for( int j = 0; j <= num_frames; j++ )
1104         total_duration += frames[j]->f_duration;
1105     float average_duration = total_duration / (num_frames + 1);
1106
1107     int i = num_frames;
1108
1109     if( b_intra )
1110         x264_slicetype_frame_cost( h, a, frames, 0, 0, 0, 0 );
1111
1112     while( i > 0 && IS_X264_TYPE_B( frames[i]->i_type ) )
1113         i--;
1114     last_nonb = i;
1115
1116     /* Lookaheadless MB-tree is not a theoretically distinct case; the same extrapolation could
1117      * be applied to the end of a lookahead buffer of any size.  However, it's most needed when
1118      * lookahead=0, so that's what's currently implemented. */
1119     if( !h->param.rc.i_lookahead )
1120     {
1121         if( b_intra )
1122         {
1123             memset( frames[0]->i_propagate_cost, 0, h->mb.i_mb_count * sizeof(uint16_t) );
1124             memcpy( frames[0]->f_qp_offset, frames[0]->f_qp_offset_aq, h->mb.i_mb_count * sizeof(float) );
1125             return;
1126         }
1127         XCHG( uint16_t*, frames[last_nonb]->i_propagate_cost, frames[0]->i_propagate_cost );
1128         memset( frames[0]->i_propagate_cost, 0, h->mb.i_mb_count * sizeof(uint16_t) );
1129     }
1130     else
1131     {
1132         if( last_nonb < idx )
1133             return;
1134         memset( frames[last_nonb]->i_propagate_cost, 0, h->mb.i_mb_count * sizeof(uint16_t) );
1135     }
1136
1137     while( i-- > idx )
1138     {
1139         cur_nonb = i;
1140         while( IS_X264_TYPE_B( frames[cur_nonb]->i_type ) && cur_nonb > 0 )
1141             cur_nonb--;
1142         if( cur_nonb < idx )
1143             break;
1144         x264_slicetype_frame_cost( h, a, frames, cur_nonb, last_nonb, last_nonb, 0 );
1145         memset( frames[cur_nonb]->i_propagate_cost, 0, h->mb.i_mb_count * sizeof(uint16_t) );
1146         bframes = last_nonb - cur_nonb - 1;
1147         if( h->param.i_bframe_pyramid && bframes > 1 )
1148         {
1149             int middle = (bframes + 1)/2 + cur_nonb;
1150             x264_slicetype_frame_cost( h, a, frames, cur_nonb, last_nonb, middle, 0 );
1151             memset( frames[middle]->i_propagate_cost, 0, h->mb.i_mb_count * sizeof(uint16_t) );
1152             while( i > cur_nonb )
1153             {
1154                 int p0 = i > middle ? middle : cur_nonb;
1155                 int p1 = i < middle ? middle : last_nonb;
1156                 if( i != middle )
1157                 {
1158                     x264_slicetype_frame_cost( h, a, frames, p0, p1, i, 0 );
1159                     x264_macroblock_tree_propagate( h, frames, average_duration, p0, p1, i, 0 );
1160                 }
1161                 i--;
1162             }
1163             x264_macroblock_tree_propagate( h, frames, average_duration, cur_nonb, last_nonb, middle, 1 );
1164         }
1165         else
1166         {
1167             while( i > cur_nonb )
1168             {
1169                 x264_slicetype_frame_cost( h, a, frames, cur_nonb, last_nonb, i, 0 );
1170                 x264_macroblock_tree_propagate( h, frames, average_duration, cur_nonb, last_nonb, i, 0 );
1171                 i--;
1172             }
1173         }
1174         x264_macroblock_tree_propagate( h, frames, average_duration, cur_nonb, last_nonb, last_nonb, 1 );
1175         last_nonb = cur_nonb;
1176     }
1177
1178     if( !h->param.rc.i_lookahead )
1179     {
1180         x264_slicetype_frame_cost( h, a, frames, 0, last_nonb, last_nonb, 0 );
1181         x264_macroblock_tree_propagate( h, frames, average_duration, 0, last_nonb, last_nonb, 1 );
1182         XCHG( uint16_t*, frames[last_nonb]->i_propagate_cost, frames[0]->i_propagate_cost );
1183     }
1184
1185     x264_macroblock_tree_finish( h, frames[last_nonb], average_duration, last_nonb );
1186     if( h->param.i_bframe_pyramid && bframes > 1 && !h->param.rc.i_vbv_buffer_size )
1187         x264_macroblock_tree_finish( h, frames[last_nonb+(bframes+1)/2], average_duration, 0 );
1188 }
1189
1190 static int x264_vbv_frame_cost( x264_t *h, x264_mb_analysis_t *a, x264_frame_t **frames, int p0, int p1, int b )
1191 {
1192     int cost = x264_slicetype_frame_cost( h, a, frames, p0, p1, b, 0 );
1193     if( h->param.rc.i_aq_mode )
1194     {
1195         if( h->param.rc.b_mb_tree )
1196             return x264_slicetype_frame_cost_recalculate( h, frames, p0, p1, b );
1197         else
1198             return frames[b]->i_cost_est_aq[b-p0][p1-b];
1199     }
1200     return cost;
1201 }
1202
1203 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 )
1204 {
1205     cur_frame->i_cpb_delay = *i_cpb_delay;
1206     cur_frame->i_dpb_output_delay = cur_frame->i_field_cnt - *i_coded_fields;
1207
1208     // add a correction term for frame reordering
1209     cur_frame->i_dpb_output_delay += h->sps->vui.i_num_reorder_frames*2;
1210
1211     // fix possible negative dpb_output_delay because of pulldown changes and reordering
1212     if( cur_frame->i_dpb_output_delay < 0 )
1213     {
1214         cur_frame->i_cpb_delay += cur_frame->i_dpb_output_delay;
1215         cur_frame->i_dpb_output_delay = 0;
1216         if( prev_frame )
1217             prev_frame->i_cpb_duration += cur_frame->i_dpb_output_delay;
1218     }
1219
1220     // don't reset cpb delay for IDR frames when using intra-refresh
1221     if( cur_frame->b_keyframe && !h->param.b_intra_refresh )
1222         *i_cpb_delay = 0;
1223
1224     *i_cpb_delay += cur_frame->i_duration;
1225     *i_coded_fields += cur_frame->i_duration;
1226     cur_frame->i_cpb_duration = cur_frame->i_duration;
1227 }
1228
1229 static void x264_vbv_lookahead( x264_t *h, x264_mb_analysis_t *a, x264_frame_t **frames, int num_frames, int keyframe )
1230 {
1231     int last_nonb = 0, cur_nonb = 1, idx = 0;
1232     x264_frame_t *prev_frame = NULL;
1233     int prev_frame_idx = 0;
1234     while( cur_nonb < num_frames && IS_X264_TYPE_B( frames[cur_nonb]->i_type ) )
1235         cur_nonb++;
1236     int next_nonb = keyframe ? last_nonb : cur_nonb;
1237
1238     if( frames[cur_nonb]->i_coded_fields_lookahead >= 0 )
1239     {
1240         h->i_coded_fields_lookahead = frames[cur_nonb]->i_coded_fields_lookahead;
1241         h->i_cpb_delay_lookahead = frames[cur_nonb]->i_cpb_delay_lookahead;
1242     }
1243
1244     while( cur_nonb < num_frames )
1245     {
1246         /* P/I cost: This shouldn't include the cost of next_nonb */
1247         if( next_nonb != cur_nonb )
1248         {
1249             int p0 = IS_X264_TYPE_I( frames[cur_nonb]->i_type ) ? cur_nonb : last_nonb;
1250             frames[next_nonb]->i_planned_satd[idx] = x264_vbv_frame_cost( h, a, frames, p0, cur_nonb, cur_nonb );
1251             frames[next_nonb]->i_planned_type[idx] = frames[cur_nonb]->i_type;
1252             frames[cur_nonb]->i_coded_fields_lookahead = h->i_coded_fields_lookahead;
1253             frames[cur_nonb]->i_cpb_delay_lookahead = h->i_cpb_delay_lookahead;
1254             x264_calculate_durations( h, frames[cur_nonb], prev_frame, &h->i_cpb_delay_lookahead, &h->i_coded_fields_lookahead );
1255             if( prev_frame )
1256             {
1257                 frames[next_nonb]->f_planned_cpb_duration[prev_frame_idx] = (double)prev_frame->i_cpb_duration *
1258                                                                             h->sps->vui.i_num_units_in_tick / h->sps->vui.i_time_scale;
1259             }
1260             frames[next_nonb]->f_planned_cpb_duration[idx] = (double)frames[cur_nonb]->i_cpb_duration *
1261                                                              h->sps->vui.i_num_units_in_tick / h->sps->vui.i_time_scale;
1262             prev_frame = frames[cur_nonb];
1263             prev_frame_idx = idx;
1264             idx++;
1265         }
1266         /* Handle the B-frames: coded order */
1267         for( int i = last_nonb+1; i < cur_nonb; i++, idx++ )
1268         {
1269             frames[next_nonb]->i_planned_satd[idx] = x264_vbv_frame_cost( h, a, frames, last_nonb, cur_nonb, i );
1270             frames[next_nonb]->i_planned_type[idx] = X264_TYPE_B;
1271             frames[i]->i_coded_fields_lookahead = h->i_coded_fields_lookahead;
1272             frames[i]->i_cpb_delay_lookahead = h->i_cpb_delay_lookahead;
1273             x264_calculate_durations( h, frames[i], prev_frame, &h->i_cpb_delay_lookahead, &h->i_coded_fields_lookahead );
1274             if( prev_frame )
1275             {
1276                 frames[next_nonb]->f_planned_cpb_duration[prev_frame_idx] = (double)prev_frame->i_cpb_duration *
1277                                                                             h->sps->vui.i_num_units_in_tick / h->sps->vui.i_time_scale;
1278             }
1279             frames[next_nonb]->f_planned_cpb_duration[idx] = (double)frames[i]->i_cpb_duration *
1280                                                              h->sps->vui.i_num_units_in_tick / h->sps->vui.i_time_scale;
1281             prev_frame = frames[i];
1282             prev_frame_idx = idx;
1283         }
1284         last_nonb = cur_nonb;
1285         cur_nonb++;
1286         while( cur_nonb <= num_frames && IS_X264_TYPE_B( frames[cur_nonb]->i_type ) )
1287             cur_nonb++;
1288     }
1289     frames[next_nonb]->i_planned_type[idx] = X264_TYPE_AUTO;
1290 }
1291
1292 static int x264_slicetype_path_cost( x264_t *h, x264_mb_analysis_t *a, x264_frame_t **frames, char *path, int threshold )
1293 {
1294     int loc = 1;
1295     int cost = 0;
1296     int cur_nonb = 0;
1297     path--; /* Since the 1st path element is really the second frame */
1298     while( path[loc] )
1299     {
1300         int next_nonb = loc;
1301         /* Find the location of the next non-B-frame. */
1302         while( path[next_nonb] == 'B' )
1303             next_nonb++;
1304
1305         /* Add the cost of the non-B-frame found above */
1306         if( path[next_nonb] == 'P' )
1307             cost += x264_slicetype_frame_cost( h, a, frames, cur_nonb, next_nonb, next_nonb, 0 );
1308         else /* I-frame */
1309             cost += x264_slicetype_frame_cost( h, a, frames, next_nonb, next_nonb, next_nonb, 0 );
1310         /* Early terminate if the cost we have found is larger than the best path cost so far */
1311         if( cost > threshold )
1312             break;
1313
1314         if( h->param.i_bframe_pyramid && next_nonb - cur_nonb > 2 )
1315         {
1316             int middle = cur_nonb + (next_nonb - cur_nonb)/2;
1317             cost += x264_slicetype_frame_cost( h, a, frames, cur_nonb, next_nonb, middle, 0 );
1318             for( int next_b = loc; next_b < middle && cost < threshold; next_b++ )
1319                 cost += x264_slicetype_frame_cost( h, a, frames, cur_nonb, middle, next_b, 0 );
1320             for( int next_b = middle+1; next_b < next_nonb && cost < threshold; next_b++ )
1321                 cost += x264_slicetype_frame_cost( h, a, frames, middle, next_nonb, next_b, 0 );
1322         }
1323         else
1324             for( int next_b = loc; next_b < next_nonb && cost < threshold; next_b++ )
1325                 cost += x264_slicetype_frame_cost( h, a, frames, cur_nonb, next_nonb, next_b, 0 );
1326
1327         loc = next_nonb + 1;
1328         cur_nonb = next_nonb;
1329     }
1330     return cost;
1331 }
1332
1333 /* Viterbi/trellis slicetype decision algorithm. */
1334 /* Uses strings due to the fact that the speed of the control functions is
1335    negligible compared to the cost of running slicetype_frame_cost, and because
1336    it makes debugging easier. */
1337 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] )
1338 {
1339     char paths[2][X264_LOOKAHEAD_MAX+1];
1340     int num_paths = X264_MIN( h->param.i_bframe+1, length );
1341     int best_cost = COST_MAX;
1342     int best_possible = 0;
1343     int idx = 0;
1344
1345     /* Iterate over all currently possible paths */
1346     for( int path = 0; path < num_paths; path++ )
1347     {
1348         /* Add suffixes to the current path */
1349         int len = length - (path + 1);
1350         memcpy( paths[idx], best_paths[len % (X264_BFRAME_MAX+1)], len );
1351         memset( paths[idx]+len, 'B', path );
1352         strcpy( paths[idx]+len+path, "P" );
1353
1354         int possible = 1;
1355         for( int i = 1; i <= length; i++ )
1356         {
1357             int i_type = frames[i]->i_type;
1358             if( i_type == X264_TYPE_AUTO )
1359                 continue;
1360             if( IS_X264_TYPE_B( i_type ) )
1361                 possible = possible && (i < len || i == length || paths[idx][i-1] == 'B');
1362             else
1363             {
1364                 possible = possible && (i < len || paths[idx][i-1] != 'B');
1365                 paths[idx][i-1] = IS_X264_TYPE_I( i_type ) ? 'I' : 'P';
1366             }
1367         }
1368
1369         if( possible || !best_possible )
1370         {
1371             if( possible && !best_possible )
1372                 best_cost = COST_MAX;
1373             /* Calculate the actual cost of the current path */
1374             int cost = x264_slicetype_path_cost( h, a, frames, paths[idx], best_cost );
1375             if( cost < best_cost )
1376             {
1377                 best_cost = cost;
1378                 best_possible = possible;
1379                 idx ^= 1;
1380             }
1381         }
1382     }
1383
1384     /* Store the best path. */
1385     memcpy( best_paths[length % (X264_BFRAME_MAX+1)], paths[idx^1], length );
1386 }
1387
1388 static int scenecut_internal( x264_t *h, x264_mb_analysis_t *a, x264_frame_t **frames, int p0, int p1, int real_scenecut )
1389 {
1390     x264_frame_t *frame = frames[p1];
1391
1392     /* Don't do scenecuts on the right view of a frame-packed video. */
1393     if( real_scenecut && h->param.i_frame_packing == 5 && (frame->i_frame&1) )
1394         return 0;
1395
1396     x264_slicetype_frame_cost( h, a, frames, p0, p1, p1, 0 );
1397
1398     int icost = frame->i_cost_est[0][0];
1399     int pcost = frame->i_cost_est[p1-p0][0];
1400     float f_bias;
1401     int i_gop_size = frame->i_frame - h->lookahead->i_last_keyframe;
1402     float f_thresh_max = h->param.i_scenecut_threshold / 100.0;
1403     /* magic numbers pulled out of thin air */
1404     float f_thresh_min = f_thresh_max * 0.25;
1405     int res;
1406
1407     if( h->param.i_keyint_min == h->param.i_keyint_max )
1408         f_thresh_min = f_thresh_max;
1409     if( i_gop_size <= h->param.i_keyint_min / 4 || h->param.b_intra_refresh )
1410         f_bias = f_thresh_min / 4;
1411     else if( i_gop_size <= h->param.i_keyint_min )
1412         f_bias = f_thresh_min * i_gop_size / h->param.i_keyint_min;
1413     else
1414     {
1415         f_bias = f_thresh_min
1416                  + ( f_thresh_max - f_thresh_min )
1417                  * ( i_gop_size - h->param.i_keyint_min )
1418                  / ( h->param.i_keyint_max - h->param.i_keyint_min );
1419     }
1420
1421     res = pcost >= (1.0 - f_bias) * icost;
1422     if( res && real_scenecut )
1423     {
1424         int imb = frame->i_intra_mbs[p1-p0];
1425         int pmb = NUM_MBS - imb;
1426         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",
1427                   frame->i_frame,
1428                   icost, pcost, 1. - (double)pcost / icost,
1429                   f_bias, i_gop_size, imb, pmb );
1430     }
1431     return res;
1432 }
1433
1434 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 )
1435 {
1436     /* Only do analysis during a normal scenecut check. */
1437     if( real_scenecut && h->param.i_bframe )
1438     {
1439         int origmaxp1 = p0 + 1;
1440         /* Look ahead to avoid coding short flashes as scenecuts. */
1441         if( h->param.i_bframe_adaptive == X264_B_ADAPT_TRELLIS )
1442             /* Don't analyse any more frames than the trellis would have covered. */
1443             origmaxp1 += h->param.i_bframe;
1444         else
1445             origmaxp1++;
1446         int maxp1 = X264_MIN( origmaxp1, num_frames );
1447
1448         /* Where A and B are scenes: AAAAAABBBAAAAAA
1449          * If BBB is shorter than (maxp1-p0), it is detected as a flash
1450          * and not considered a scenecut. */
1451         for( int curp1 = p1; curp1 <= maxp1; curp1++ )
1452             if( !scenecut_internal( h, a, frames, p0, curp1, 0 ) )
1453                 /* Any frame in between p0 and cur_p1 cannot be a real scenecut. */
1454                 for( int i = curp1; i > p0; i-- )
1455                     frames[i]->b_scenecut = 0;
1456
1457         /* Where A-F are scenes: AAAAABBCCDDEEFFFFFF
1458          * If each of BB ... EE are shorter than (maxp1-p0), they are
1459          * detected as flashes and not considered scenecuts.
1460          * Instead, the first F frame becomes a scenecut.
1461          * If the video ends before F, no frame becomes a scenecut. */
1462         for( int curp0 = p0; curp0 <= maxp1; curp0++ )
1463             if( origmaxp1 > i_max_search || (curp0 < maxp1 && scenecut_internal( h, a, frames, curp0, maxp1, 0 )) )
1464                 /* If cur_p0 is the p0 of a scenecut, it cannot be the p1 of a scenecut. */
1465                     frames[curp0]->b_scenecut = 0;
1466     }
1467
1468     /* Ignore frames that are part of a flash, i.e. cannot be real scenecuts. */
1469     if( !frames[p1]->b_scenecut )
1470         return 0;
1471     return scenecut_internal( h, a, frames, p0, p1, real_scenecut );
1472 }
1473
1474 #define IS_X264_TYPE_AUTO_OR_I(x) ((x)==X264_TYPE_AUTO || IS_X264_TYPE_I(x))
1475 #define IS_X264_TYPE_AUTO_OR_B(x) ((x)==X264_TYPE_AUTO || IS_X264_TYPE_B(x))
1476
1477 void x264_slicetype_analyse( x264_t *h, int intra_minigop )
1478 {
1479     x264_mb_analysis_t a;
1480     x264_frame_t *frames[X264_LOOKAHEAD_MAX+3] = { NULL, };
1481     int num_frames, orig_num_frames, keyint_limit, framecnt;
1482     int i_mb_count = NUM_MBS;
1483     int i_max_search = X264_MIN( h->lookahead->next.i_size, X264_LOOKAHEAD_MAX );
1484     int vbv_lookahead = h->param.rc.i_vbv_buffer_size && h->param.rc.i_lookahead;
1485     /* For determinism we should limit the search to the number of frames lookahead has for sure
1486      * in h->lookahead->next.list buffer, except at the end of stream.
1487      * For normal calls with (intra_minigop == 0) that is h->lookahead->i_slicetype_length + 1 frames.
1488      * And for I-frame calls (intra_minigop != 0) we already removed intra_minigop frames from there. */
1489     if( h->param.b_deterministic )
1490         i_max_search = X264_MIN( i_max_search, h->lookahead->i_slicetype_length + 1 - intra_minigop );
1491     int keyframe = !!intra_minigop;
1492
1493     assert( h->frames.b_have_lowres );
1494
1495     if( !h->lookahead->last_nonb )
1496         return;
1497     frames[0] = h->lookahead->last_nonb;
1498     for( framecnt = 0; framecnt < i_max_search; framecnt++ )
1499         frames[framecnt+1] = h->lookahead->next.list[framecnt];
1500
1501     x264_lowres_context_init( h, &a );
1502
1503     if( !framecnt )
1504     {
1505         if( h->param.rc.b_mb_tree )
1506             x264_macroblock_tree( h, &a, frames, 0, keyframe );
1507         return;
1508     }
1509
1510     keyint_limit = h->param.i_keyint_max - frames[0]->i_frame + h->lookahead->i_last_keyframe - 1;
1511     orig_num_frames = num_frames = h->param.b_intra_refresh ? framecnt : X264_MIN( framecnt, keyint_limit );
1512
1513     /* This is important psy-wise: if we have a non-scenecut keyframe,
1514      * there will be significant visual artifacts if the frames just before
1515      * go down in quality due to being referenced less, despite it being
1516      * more RD-optimal. */
1517     if( (h->param.analyse.b_psy && h->param.rc.b_mb_tree) || vbv_lookahead )
1518         num_frames = framecnt;
1519     else if( h->param.b_open_gop && num_frames < framecnt )
1520         num_frames++;
1521     else if( num_frames == 0 )
1522     {
1523         frames[1]->i_type = X264_TYPE_I;
1524         return;
1525     }
1526
1527     if( IS_X264_TYPE_AUTO_OR_I( frames[1]->i_type ) &&
1528         h->param.i_scenecut_threshold && scenecut( h, &a, frames, 0, 1, 1, orig_num_frames, i_max_search ) )
1529     {
1530         if( frames[1]->i_type == X264_TYPE_AUTO )
1531             frames[1]->i_type = X264_TYPE_I;
1532         return;
1533     }
1534
1535 #if HAVE_OPENCL
1536     x264_opencl_slicetype_prep( h, frames, num_frames, a.i_lambda );
1537 #endif
1538
1539     /* Replace forced keyframes with I/IDR-frames */
1540     for( int j = 1; j <= num_frames; j++ )
1541     {
1542         if( frames[j]->i_type == X264_TYPE_KEYFRAME )
1543             frames[j]->i_type = h->param.b_open_gop ? X264_TYPE_I : X264_TYPE_IDR;
1544     }
1545
1546     /* Close GOP at IDR-frames */
1547     for( int j = 2; j <= num_frames; j++ )
1548     {
1549         if( frames[j]->i_type == X264_TYPE_IDR && IS_X264_TYPE_AUTO_OR_B( frames[j-1]->i_type ) )
1550             frames[j-1]->i_type = X264_TYPE_P;
1551     }
1552
1553     int num_analysed_frames = num_frames;
1554     int reset_start;
1555
1556     if( h->param.i_bframe )
1557     {
1558         if( h->param.i_bframe_adaptive == X264_B_ADAPT_TRELLIS )
1559         {
1560             if( num_frames > 1 )
1561             {
1562                 char best_paths[X264_BFRAME_MAX+1][X264_LOOKAHEAD_MAX+1] = {"","P"};
1563                 int best_path_index = num_frames % (X264_BFRAME_MAX+1);
1564
1565                 /* Perform the frametype analysis. */
1566                 for( int j = 2; j <= num_frames; j++ )
1567                     x264_slicetype_path( h, &a, frames, j, best_paths );
1568
1569                 /* Load the results of the analysis into the frame types. */
1570                 for( int j = 1; j < num_frames; j++ )
1571                 {
1572                     if( best_paths[best_path_index][j-1] != 'B' )
1573                     {
1574                         if( IS_X264_TYPE_AUTO_OR_B( frames[j]->i_type ) )
1575                             frames[j]->i_type = X264_TYPE_P;
1576                     }
1577                     else
1578                     {
1579                         if( frames[j]->i_type == X264_TYPE_AUTO )
1580                             frames[j]->i_type = X264_TYPE_B;
1581                     }
1582                 }
1583             }
1584         }
1585         else if( h->param.i_bframe_adaptive == X264_B_ADAPT_FAST )
1586         {
1587             int last_nonb = 0;
1588             int num_bframes = h->param.i_bframe;
1589             for( int j = 1; j < num_frames; j++ )
1590             {
1591                 if( j-1 > 0 && IS_X264_TYPE_B( frames[j-1]->i_type ) )
1592                     num_bframes--;
1593                 else
1594                 {
1595                     last_nonb = j-1;
1596                     num_bframes = h->param.i_bframe;
1597                 }
1598                 if( !num_bframes )
1599                 {
1600                     if( IS_X264_TYPE_AUTO_OR_B( frames[j]->i_type ) )
1601                         frames[j]->i_type = X264_TYPE_P;
1602                     continue;
1603                 }
1604
1605                 if( frames[j]->i_type != X264_TYPE_AUTO )
1606                     continue;
1607
1608                 if( IS_X264_TYPE_B( frames[j+1]->i_type ) )
1609                 {
1610                     frames[j]->i_type = X264_TYPE_P;
1611                     continue;
1612                 }
1613
1614                 if( j - last_nonb <= 1 )
1615                 {
1616                     int cost2p1 = x264_slicetype_frame_cost( h, &a, frames, last_nonb+0, j+1, j+1, 1 );
1617                     if( frames[j+1]->i_intra_mbs[2] > i_mb_count / 2 )
1618                     {
1619                         frames[j]->i_type = X264_TYPE_P;
1620                         continue;
1621                     }
1622
1623 #if HAVE_OPENCL
1624                     if( h->param.b_opencl )
1625                     {
1626                         int b_work_done = 0;
1627                         b_work_done |= x264_opencl_precalculate_frame_cost(h, frames, a.i_lambda, last_nonb+0, j+1, j+0 );
1628                         b_work_done |= x264_opencl_precalculate_frame_cost(h, frames, a.i_lambda, last_nonb+0, j+0, j+0 );
1629                         b_work_done |= x264_opencl_precalculate_frame_cost(h, frames, a.i_lambda, last_nonb+1, j+1, j+1 );
1630                         if( b_work_done )
1631                             x264_opencl_flush( h );
1632                     }
1633 #endif
1634
1635                     int cost1b1 = x264_slicetype_frame_cost( h, &a, frames, last_nonb+0, j+1, j+0, 0 );
1636                     int cost1p0 = x264_slicetype_frame_cost( h, &a, frames, last_nonb+0, j+0, j+0, 0 );
1637                     int cost2p0 = x264_slicetype_frame_cost( h, &a, frames, last_nonb+1, j+1, j+1, 0 );
1638
1639                     if( cost1p0 + cost2p0 < cost1b1 + cost2p1 )
1640                     {
1641                         frames[j]->i_type = X264_TYPE_P;
1642                         continue;
1643                     }
1644                     frames[j]->i_type = X264_TYPE_B;
1645                     continue;
1646                 }
1647
1648                 // arbitrary and untuned
1649                 #define INTER_THRESH 300
1650                 #define P_SENS_BIAS (50 - h->param.i_bframe_bias)
1651
1652                 int pthresh = X264_MAX(INTER_THRESH - P_SENS_BIAS * (j-last_nonb-1), INTER_THRESH/10);
1653                 int pcost = x264_slicetype_frame_cost( h, &a, frames, last_nonb, j+1, j+1, 1 );
1654                 if( pcost > pthresh*i_mb_count || frames[j+1]->i_intra_mbs[j-last_nonb+1] > i_mb_count/3 )
1655                     frames[j]->i_type = X264_TYPE_P;
1656                 else
1657                     frames[j]->i_type = X264_TYPE_B;
1658             }
1659         }
1660         else
1661         {
1662             int num_bframes = h->param.i_bframe;
1663             for( int j = 1; j < num_frames; j++ )
1664             {
1665                 if( !num_bframes )
1666                 {
1667                     if( IS_X264_TYPE_AUTO_OR_B( frames[j]->i_type ) )
1668                         frames[j]->i_type = X264_TYPE_P;
1669                 }
1670                 else if( frames[j]->i_type == X264_TYPE_AUTO )
1671                 {
1672                     if( IS_X264_TYPE_B( frames[j+1]->i_type ) )
1673                         frames[j]->i_type = X264_TYPE_P;
1674                     else
1675                         frames[j]->i_type = X264_TYPE_B;
1676                 }
1677                 if( IS_X264_TYPE_B( frames[j]->i_type ) )
1678                     num_bframes--;
1679                 else
1680                     num_bframes = h->param.i_bframe;
1681             }
1682         }
1683         if( IS_X264_TYPE_AUTO_OR_B( frames[num_frames]->i_type ) )
1684             frames[num_frames]->i_type = X264_TYPE_P;
1685
1686         int num_bframes = 0;
1687         while( num_bframes < num_frames && IS_X264_TYPE_B( frames[num_bframes+1]->i_type ) )
1688             num_bframes++;
1689
1690         /* Check scenecut on the first minigop. */
1691         for( int j = 1; j < num_bframes+1; j++ )
1692         {
1693             if( frames[j]->i_forced_type == X264_TYPE_AUTO && IS_X264_TYPE_AUTO_OR_I( frames[j+1]->i_forced_type ) &&
1694                 h->param.i_scenecut_threshold && scenecut( h, &a, frames, j, j+1, 0, orig_num_frames, i_max_search ) )
1695             {
1696                 frames[j]->i_type = X264_TYPE_P;
1697                 num_analysed_frames = j;
1698                 break;
1699             }
1700         }
1701
1702         reset_start = keyframe ? 1 : X264_MIN( num_bframes+2, num_analysed_frames+1 );
1703     }
1704     else
1705     {
1706         for( int j = 1; j <= num_frames; j++ )
1707             if( IS_X264_TYPE_AUTO_OR_B( frames[j]->i_type ) )
1708                 frames[j]->i_type = X264_TYPE_P;
1709         reset_start = !keyframe + 1;
1710     }
1711
1712     /* Perform the actual macroblock tree analysis.
1713      * Don't go farther than the maximum keyframe interval; this helps in short GOPs. */
1714     if( h->param.rc.b_mb_tree )
1715         x264_macroblock_tree( h, &a, frames, X264_MIN(num_frames, h->param.i_keyint_max), keyframe );
1716
1717     /* Enforce keyframe limit. */
1718     if( !h->param.b_intra_refresh )
1719     {
1720         int last_keyframe = h->lookahead->i_last_keyframe;
1721         int last_possible = 0;
1722         for( int j = 1; j <= num_frames; j++ )
1723         {
1724             x264_frame_t *frm = frames[j];
1725             int keyframe_dist = frm->i_frame - last_keyframe;
1726
1727             if( IS_X264_TYPE_AUTO_OR_I( frm->i_forced_type ) )
1728             {
1729                 if( h->param.b_open_gop || !IS_X264_TYPE_B( frames[j-1]->i_forced_type ) )
1730                     last_possible = j;
1731             }
1732             if( keyframe_dist >= h->param.i_keyint_max )
1733             {
1734                 if( last_possible != 0 && last_possible != j )
1735                 {
1736                     j = last_possible;
1737                     frm = frames[j];
1738                     keyframe_dist = frm->i_frame - last_keyframe;
1739                 }
1740                 last_possible = 0;
1741                 if( frm->i_type != X264_TYPE_IDR )
1742                     frm->i_type = h->param.b_open_gop ? X264_TYPE_I : X264_TYPE_IDR;
1743             }
1744             if( frm->i_type == X264_TYPE_I && keyframe_dist >= h->param.i_keyint_min )
1745             {
1746                 if( h->param.b_open_gop )
1747                 {
1748                     last_keyframe = frm->i_frame;
1749                     if( h->param.b_bluray_compat )
1750                     {
1751                         // Use bluray order
1752                         int bframes = 0;
1753                         while( bframes < j-1 && IS_X264_TYPE_B( frames[j-1-bframes]->i_type ) )
1754                             bframes++;
1755                         last_keyframe -= bframes;
1756                     }
1757                 }
1758                 else if( frm->i_forced_type != X264_TYPE_I )
1759                     frm->i_type = X264_TYPE_IDR;
1760             }
1761             if( frm->i_type == X264_TYPE_IDR )
1762             {
1763                 last_keyframe = frm->i_frame;
1764                 if( j > 1 && IS_X264_TYPE_B( frames[j-1]->i_type ) )
1765                     frames[j-1]->i_type = X264_TYPE_P;
1766             }
1767         }
1768     }
1769
1770     if( vbv_lookahead )
1771         x264_vbv_lookahead( h, &a, frames, num_frames, keyframe );
1772
1773     /* Restore frametypes for all frames that haven't actually been decided yet. */
1774     for( int j = reset_start; j <= num_frames; j++ )
1775         frames[j]->i_type = frames[j]->i_forced_type;
1776
1777 #if HAVE_OPENCL
1778     x264_opencl_slicetype_end( h );
1779 #endif
1780 }
1781
1782 void x264_slicetype_decide( x264_t *h )
1783 {
1784     x264_frame_t *frames[X264_BFRAME_MAX+2];
1785     x264_frame_t *frm;
1786     int bframes;
1787     int brefs;
1788
1789     if( !h->lookahead->next.i_size )
1790         return;
1791
1792     int lookahead_size = h->lookahead->next.i_size;
1793
1794     for( int i = 0; i < h->lookahead->next.i_size; i++ )
1795     {
1796         if( h->param.b_vfr_input )
1797         {
1798             if( lookahead_size-- > 1 )
1799                 h->lookahead->next.list[i]->i_duration = 2 * (h->lookahead->next.list[i+1]->i_pts - h->lookahead->next.list[i]->i_pts);
1800             else
1801                 h->lookahead->next.list[i]->i_duration = h->i_prev_duration;
1802         }
1803         else
1804             h->lookahead->next.list[i]->i_duration = delta_tfi_divisor[h->lookahead->next.list[i]->i_pic_struct];
1805         h->i_prev_duration = h->lookahead->next.list[i]->i_duration;
1806         h->lookahead->next.list[i]->f_duration = (double)h->lookahead->next.list[i]->i_duration
1807                                                * h->sps->vui.i_num_units_in_tick
1808                                                / h->sps->vui.i_time_scale;
1809
1810         if( h->lookahead->next.list[i]->i_frame > h->i_disp_fields_last_frame && lookahead_size > 0 )
1811         {
1812             h->lookahead->next.list[i]->i_field_cnt = h->i_disp_fields;
1813             h->i_disp_fields += h->lookahead->next.list[i]->i_duration;
1814             h->i_disp_fields_last_frame = h->lookahead->next.list[i]->i_frame;
1815         }
1816         else if( lookahead_size == 0 )
1817         {
1818             h->lookahead->next.list[i]->i_field_cnt = h->i_disp_fields;
1819             h->lookahead->next.list[i]->i_duration = h->i_prev_duration;
1820         }
1821     }
1822
1823     if( h->param.rc.b_stat_read )
1824     {
1825         /* Use the frame types from the first pass */
1826         for( int i = 0; i < h->lookahead->next.i_size; i++ )
1827             h->lookahead->next.list[i]->i_type =
1828                 x264_ratecontrol_slice_type( h, h->lookahead->next.list[i]->i_frame );
1829     }
1830     else if( (h->param.i_bframe && h->param.i_bframe_adaptive)
1831              || h->param.i_scenecut_threshold
1832              || h->param.rc.b_mb_tree
1833              || (h->param.rc.i_vbv_buffer_size && h->param.rc.i_lookahead) )
1834         x264_slicetype_analyse( h, 0 );
1835
1836     for( bframes = 0, brefs = 0;; bframes++ )
1837     {
1838         frm = h->lookahead->next.list[bframes];
1839
1840         if( frm->i_forced_type != X264_TYPE_AUTO && frm->i_type != frm->i_forced_type &&
1841             !(frm->i_forced_type == X264_TYPE_KEYFRAME && IS_X264_TYPE_I( frm->i_type )) )
1842         {
1843             x264_log( h, X264_LOG_WARNING, "forced frame type (%d) at %d was changed to frame type (%d)\n",
1844                       frm->i_forced_type, frm->i_frame, frm->i_type );
1845         }
1846
1847         if( frm->i_type == X264_TYPE_BREF && h->param.i_bframe_pyramid < X264_B_PYRAMID_NORMAL &&
1848             brefs == h->param.i_bframe_pyramid )
1849         {
1850             frm->i_type = X264_TYPE_B;
1851             x264_log( h, X264_LOG_WARNING, "B-ref at frame %d incompatible with B-pyramid %s \n",
1852                       frm->i_frame, x264_b_pyramid_names[h->param.i_bframe_pyramid] );
1853         }
1854         /* pyramid with multiple B-refs needs a big enough dpb that the preceding P-frame stays available.
1855            smaller dpb could be supported by smart enough use of mmco, but it's easier just to forbid it. */
1856         else if( frm->i_type == X264_TYPE_BREF && h->param.i_bframe_pyramid == X264_B_PYRAMID_NORMAL &&
1857             brefs && h->param.i_frame_reference <= (brefs+3) )
1858         {
1859             frm->i_type = X264_TYPE_B;
1860             x264_log( h, X264_LOG_WARNING, "B-ref at frame %d incompatible with B-pyramid %s and %d reference frames\n",
1861                       frm->i_frame, x264_b_pyramid_names[h->param.i_bframe_pyramid], h->param.i_frame_reference );
1862         }
1863
1864         if( frm->i_type == X264_TYPE_KEYFRAME )
1865             frm->i_type = h->param.b_open_gop ? X264_TYPE_I : X264_TYPE_IDR;
1866
1867         /* Limit GOP size */
1868         if( (!h->param.b_intra_refresh || frm->i_frame == 0) && frm->i_frame - h->lookahead->i_last_keyframe >= h->param.i_keyint_max )
1869         {
1870             if( frm->i_type == X264_TYPE_AUTO || frm->i_type == X264_TYPE_I )
1871                 frm->i_type = h->param.b_open_gop && h->lookahead->i_last_keyframe >= 0 ? X264_TYPE_I : X264_TYPE_IDR;
1872             int warn = frm->i_type != X264_TYPE_IDR;
1873             if( warn && h->param.b_open_gop )
1874                 warn &= frm->i_type != X264_TYPE_I;
1875             if( warn )
1876             {
1877                 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 );
1878                 frm->i_type = h->param.b_open_gop && h->lookahead->i_last_keyframe >= 0 ? X264_TYPE_I : X264_TYPE_IDR;
1879             }
1880         }
1881         if( frm->i_type == X264_TYPE_I && frm->i_frame - h->lookahead->i_last_keyframe >= h->param.i_keyint_min )
1882         {
1883             if( h->param.b_open_gop )
1884             {
1885                 h->lookahead->i_last_keyframe = frm->i_frame; // Use display order
1886                 if( h->param.b_bluray_compat )
1887                     h->lookahead->i_last_keyframe -= bframes; // Use bluray order
1888                 frm->b_keyframe = 1;
1889             }
1890             else
1891                 frm->i_type = X264_TYPE_IDR;
1892         }
1893         if( frm->i_type == X264_TYPE_IDR )
1894         {
1895             /* Close GOP */
1896             h->lookahead->i_last_keyframe = frm->i_frame;
1897             frm->b_keyframe = 1;
1898             if( bframes > 0 )
1899             {
1900                 bframes--;
1901                 h->lookahead->next.list[bframes]->i_type = X264_TYPE_P;
1902             }
1903         }
1904
1905         if( bframes == h->param.i_bframe ||
1906             !h->lookahead->next.list[bframes+1] )
1907         {
1908             if( IS_X264_TYPE_B( frm->i_type ) )
1909                 x264_log( h, X264_LOG_WARNING, "specified frame type is not compatible with max B-frames\n" );
1910             if( frm->i_type == X264_TYPE_AUTO
1911                 || IS_X264_TYPE_B( frm->i_type ) )
1912                 frm->i_type = X264_TYPE_P;
1913         }
1914
1915         if( frm->i_type == X264_TYPE_BREF )
1916             brefs++;
1917
1918         if( frm->i_type == X264_TYPE_AUTO )
1919             frm->i_type = X264_TYPE_B;
1920
1921         else if( !IS_X264_TYPE_B( frm->i_type ) ) break;
1922     }
1923
1924     if( bframes )
1925         h->lookahead->next.list[bframes-1]->b_last_minigop_bframe = 1;
1926     h->lookahead->next.list[bframes]->i_bframes = bframes;
1927
1928     /* insert a bref into the sequence */
1929     if( h->param.i_bframe_pyramid && bframes > 1 && !brefs )
1930     {
1931         h->lookahead->next.list[bframes/2]->i_type = X264_TYPE_BREF;
1932         brefs++;
1933     }
1934
1935     /* calculate the frame costs ahead of time for x264_rc_analyse_slice while we still have lowres */
1936     if( h->param.rc.i_rc_method != X264_RC_CQP )
1937     {
1938         x264_mb_analysis_t a;
1939         int p0, p1, b;
1940         p1 = b = bframes + 1;
1941
1942         x264_lowres_context_init( h, &a );
1943
1944         frames[0] = h->lookahead->last_nonb;
1945         memcpy( &frames[1], h->lookahead->next.list, (bframes+1) * sizeof(x264_frame_t*) );
1946         if( IS_X264_TYPE_I( h->lookahead->next.list[bframes]->i_type ) )
1947             p0 = bframes + 1;
1948         else // P
1949             p0 = 0;
1950
1951         x264_slicetype_frame_cost( h, &a, frames, p0, p1, b, 0 );
1952
1953         if( (p0 != p1 || bframes) && h->param.rc.i_vbv_buffer_size )
1954         {
1955             /* We need the intra costs for row SATDs. */
1956             x264_slicetype_frame_cost( h, &a, frames, b, b, b, 0 );
1957
1958             /* We need B-frame costs for row SATDs. */
1959             p0 = 0;
1960             for( b = 1; b <= bframes; b++ )
1961             {
1962                 if( frames[b]->i_type == X264_TYPE_B )
1963                     for( p1 = b; frames[p1]->i_type == X264_TYPE_B; )
1964                         p1++;
1965                 else
1966                     p1 = bframes + 1;
1967                 x264_slicetype_frame_cost( h, &a, frames, p0, p1, b, 0 );
1968                 if( frames[b]->i_type == X264_TYPE_BREF )
1969                     p0 = b;
1970             }
1971         }
1972     }
1973
1974     /* Analyse for weighted P frames */
1975     if( !h->param.rc.b_stat_read && h->lookahead->next.list[bframes]->i_type == X264_TYPE_P
1976         && h->param.analyse.i_weighted_pred >= X264_WEIGHTP_SIMPLE )
1977     {
1978         x264_emms();
1979         x264_weights_analyse( h, h->lookahead->next.list[bframes], h->lookahead->last_nonb, 0 );
1980     }
1981
1982     /* shift sequence to coded order.
1983        use a small temporary list to avoid shifting the entire next buffer around */
1984     int i_coded = h->lookahead->next.list[0]->i_frame;
1985     if( bframes )
1986     {
1987         int idx_list[] = { brefs+1, 1 };
1988         for( int i = 0; i < bframes; i++ )
1989         {
1990             int idx = idx_list[h->lookahead->next.list[i]->i_type == X264_TYPE_BREF]++;
1991             frames[idx] = h->lookahead->next.list[i];
1992             frames[idx]->i_reordered_pts = h->lookahead->next.list[idx]->i_pts;
1993         }
1994         frames[0] = h->lookahead->next.list[bframes];
1995         frames[0]->i_reordered_pts = h->lookahead->next.list[0]->i_pts;
1996         memcpy( h->lookahead->next.list, frames, (bframes+1) * sizeof(x264_frame_t*) );
1997     }
1998
1999     for( int i = 0; i <= bframes; i++ )
2000     {
2001         h->lookahead->next.list[i]->i_coded = i_coded++;
2002         if( i )
2003         {
2004             x264_calculate_durations( h, h->lookahead->next.list[i], h->lookahead->next.list[i-1], &h->i_cpb_delay, &h->i_coded_fields );
2005             h->lookahead->next.list[0]->f_planned_cpb_duration[i-1] = (double)h->lookahead->next.list[i]->i_cpb_duration *
2006                                                                       h->sps->vui.i_num_units_in_tick / h->sps->vui.i_time_scale;
2007         }
2008         else
2009             x264_calculate_durations( h, h->lookahead->next.list[i], NULL, &h->i_cpb_delay, &h->i_coded_fields );
2010     }
2011 }
2012
2013 int x264_rc_analyse_slice( x264_t *h )
2014 {
2015     int p0 = 0, p1, b;
2016     int cost;
2017     x264_emms();
2018
2019     if( IS_X264_TYPE_I(h->fenc->i_type) )
2020         p1 = b = 0;
2021     else if( h->fenc->i_type == X264_TYPE_P )
2022         p1 = b = h->fenc->i_bframes + 1;
2023     else //B
2024     {
2025         p1 = (h->fref_nearest[1]->i_poc - h->fref_nearest[0]->i_poc)/2;
2026         b  = (h->fenc->i_poc - h->fref_nearest[0]->i_poc)/2;
2027     }
2028     /* We don't need to assign p0/p1 since we are not performing any real analysis here. */
2029     x264_frame_t **frames = &h->fenc - b;
2030
2031     /* cost should have been already calculated by x264_slicetype_decide */
2032     cost = frames[b]->i_cost_est[b-p0][p1-b];
2033     assert( cost >= 0 );
2034
2035     if( h->param.rc.b_mb_tree && !h->param.rc.b_stat_read )
2036     {
2037         cost = x264_slicetype_frame_cost_recalculate( h, frames, p0, p1, b );
2038         if( b && h->param.rc.i_vbv_buffer_size )
2039             x264_slicetype_frame_cost_recalculate( h, frames, b, b, b );
2040     }
2041     /* In AQ, use the weighted score instead. */
2042     else if( h->param.rc.i_aq_mode )
2043         cost = frames[b]->i_cost_est_aq[b-p0][p1-b];
2044
2045     h->fenc->i_row_satd = h->fenc->i_row_satds[b-p0][p1-b];
2046     h->fdec->i_row_satd = h->fdec->i_row_satds[b-p0][p1-b];
2047     h->fdec->i_satd = cost;
2048     memcpy( h->fdec->i_row_satd, h->fenc->i_row_satd, h->mb.i_mb_height * sizeof(int) );
2049     if( !IS_X264_TYPE_I(h->fenc->i_type) )
2050         memcpy( h->fdec->i_row_satds[0][0], h->fenc->i_row_satds[0][0], h->mb.i_mb_height * sizeof(int) );
2051
2052     if( h->param.b_intra_refresh && h->param.rc.i_vbv_buffer_size && h->fenc->i_type == X264_TYPE_P )
2053     {
2054         int ip_factor = 256 * h->param.rc.f_ip_factor; /* fix8 */
2055         for( int y = 0; y < h->mb.i_mb_height; y++ )
2056         {
2057             int mb_xy = y * h->mb.i_mb_stride + h->fdec->i_pir_start_col;
2058             for( int x = h->fdec->i_pir_start_col; x <= h->fdec->i_pir_end_col; x++, mb_xy++ )
2059             {
2060                 int intra_cost = (h->fenc->i_intra_cost[mb_xy] * ip_factor + 128) >> 8;
2061                 int inter_cost = h->fenc->lowres_costs[b-p0][p1-b][mb_xy] & LOWRES_COST_MASK;
2062                 int diff = intra_cost - inter_cost;
2063                 if( h->param.rc.i_aq_mode )
2064                     h->fdec->i_row_satd[y] += (diff * frames[b]->i_inv_qscale_factor[mb_xy] + 128) >> 8;
2065                 else
2066                     h->fdec->i_row_satd[y] += diff;
2067                 cost += diff;
2068             }
2069         }
2070     }
2071
2072     if( BIT_DEPTH > 8 )
2073         for( int y = 0; y < h->mb.i_mb_height; y++ )
2074             h->fdec->i_row_satd[y] >>= (BIT_DEPTH - 8);
2075
2076     return cost >> (BIT_DEPTH - 8);
2077 }