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