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