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