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