]> git.sesse.net Git - x264/blob - encoder/slicetype.c
Fix all aliasing violations
[x264] / encoder / slicetype.c
1 /*****************************************************************************
2  * slicetype.c: h264 encoder library
3  *****************************************************************************
4  * Copyright (C) 2005-2008 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
25 #include <math.h>
26
27 #include "common/common.h"
28 #include "common/cpu.h"
29 #include "macroblock.h"
30 #include "me.h"
31
32 static int x264_slicetype_frame_cost( x264_t *h, x264_mb_analysis_t *a,
33                                       x264_frame_t **frames, int p0, int p1, int b,
34                                       int b_intra_penalty );
35
36 static void x264_lowres_context_init( x264_t *h, x264_mb_analysis_t *a )
37 {
38     a->i_qp = X264_LOOKAHEAD_QP;
39     a->i_lambda = x264_lambda_tab[ a->i_qp ];
40     x264_mb_analyse_load_costs( h, a );
41     h->mb.i_me_method = X264_MIN( X264_ME_HEX, h->param.analyse.i_me_method ); // maybe dia?
42     h->mb.i_subpel_refine = 4; // 3 should be enough, but not tweaking for speed now
43     h->mb.b_chroma_me = 0;
44 }
45
46 /* makes a non-h264 weight (i.e. fix7), into an h264 weight */
47 static void get_h264_weight( unsigned int weight_nonh264, int offset, x264_weight_t *w )
48 {
49     w->i_offset = offset;
50     w->i_denom = 7;
51     w->i_scale = weight_nonh264;
52     while( w->i_denom > 0 && (w->i_scale > 127 || !(w->i_scale & 1)) )
53     {
54         w->i_denom--;
55         w->i_scale >>= 1;
56     }
57     w->i_scale = X264_MIN( w->i_scale, 127 );
58 }
59 /* due to a GCC bug on some platforms (win32), flat[16] may not actually be aligned. */
60 ALIGNED_16( static uint8_t flat[17] ) = {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1};
61
62 static NOINLINE void weights_plane_analyse( x264_t *h, uint8_t *plane, int width, int height, int stride, unsigned int *sum, uint64_t *var )
63 {
64     int x,y;
65     unsigned int sad = 0;
66     uint64_t ssd = 0;
67     uint8_t *p = plane;
68     for( y = 0; y < height>>4; y++, p += stride*16 )
69         for( x = 0; x < width; x+=16 )
70         {
71             sad += h->pixf.sad_aligned[PIXEL_16x16]( p + x, stride, flat, 0 );
72             ssd += h->pixf.ssd[PIXEL_16x16]( p + x, stride, flat, 0 );
73         }
74
75     *sum = sad;
76     *var = ssd - (uint64_t) sad * sad / (width * height);
77     x264_emms();
78 }
79
80 #define LOAD_HPELS_LUMA(dst, src) \
81 { \
82    (dst)[0] = &(src)[0][i_pel_offset]; \
83    (dst)[1] = &(src)[1][i_pel_offset]; \
84    (dst)[2] = &(src)[2][i_pel_offset]; \
85    (dst)[3] = &(src)[3][i_pel_offset]; \
86 }
87
88 static NOINLINE uint8_t *x264_weight_cost_init_luma( x264_t *h, x264_frame_t *fenc, x264_frame_t *ref, uint8_t *dest, int b_lowres )
89 {
90     uint8_t **ref_planes = b_lowres ? ref->lowres : ref->filtered;
91     int ref0_distance = fenc->i_frame - ref->i_frame - 1;
92     /* Note: this will never run during lookahead as weights_analyse is only called if no
93      * motion search has been done. */
94     if( h->frames.b_have_lowres && fenc->lowres_mvs[0][ref0_distance][0][0] != 0x7FFF
95         && ( h->param.analyse.i_subpel_refine || h->param.i_threads > 1 ))
96     {
97         uint8_t *src[4];
98         int i_stride = b_lowres ? fenc->i_stride_lowres : fenc->i_stride[0];
99         int i_lines = b_lowres ? fenc->i_lines_lowres : fenc->i_lines[0];
100         int i_width = b_lowres ? fenc->i_width_lowres : fenc->i_width[0];
101         int i_mb_xy = 0;
102         int mbsizeshift = b_lowres ? 3 : 4;
103         int mbsize = 1 << mbsizeshift;
104         int x,y;
105         int i_pel_offset = 0;
106
107         for( y = 0; y < i_lines; y += mbsize, i_pel_offset = y*i_stride )
108             for( x = 0; x < i_width; x += mbsize, i_mb_xy++, i_pel_offset += mbsize )
109             {
110                 uint8_t *pix = &dest[ i_pel_offset ];
111                 int mvx = fenc->lowres_mvs[0][ref0_distance][i_mb_xy][0] << !b_lowres;
112                 int mvy = fenc->lowres_mvs[0][ref0_distance][i_mb_xy][1] << !b_lowres;
113                 LOAD_HPELS_LUMA( src, ref_planes );
114                 h->mc.mc_luma( pix, i_stride, src, i_stride,
115                                mvx, mvy, mbsize, mbsize, weight_none );
116             }
117         x264_emms();
118         return dest;
119     }
120     x264_emms();
121     return ref_planes[0];
122 }
123 #undef LOAD_HPELS_LUMA
124
125 static NOINLINE unsigned int x264_weight_cost( x264_t *h, x264_frame_t *fenc, uint8_t *src, x264_weight_t *w, int b_lowres )
126 {
127     int x, y;
128     unsigned int cost = 0;
129     int mbsize = b_lowres ? 8 : 16;
130     int pixelsize = mbsize == 8 ? PIXEL_8x8 : PIXEL_16x16;
131     int i_stride = b_lowres ? fenc->i_stride_lowres : fenc->i_stride[0];
132     int i_lines = b_lowres ? fenc->i_lines_lowres : fenc->i_lines[0];
133     int i_width = b_lowres ? fenc->i_width_lowres : fenc->i_width[0];
134     uint8_t *fenc_plane = b_lowres ? fenc->lowres[0] : fenc->plane[0];
135     ALIGNED_ARRAY_16( uint8_t, buf,[16*16] );
136     int pixoff = 0;
137     int i_mb = 0;
138
139     if( w )
140         for( y = 0; y < i_lines; y += mbsize, pixoff = y*i_stride )
141             for( x = 0; x < i_width; x += mbsize, i_mb++, pixoff += mbsize)
142             {
143                 w->weightfn[mbsize>>2]( buf, 16, &src[pixoff], i_stride, w, mbsize );
144                 cost += X264_MIN( h->pixf.mbcmp[pixelsize]( buf, 16, &fenc_plane[pixoff], i_stride ), fenc->i_intra_cost[i_mb] );
145             }
146     else
147         for( y = 0; y < i_lines; y += mbsize, pixoff = y*i_stride )
148             for( x = 0; x < i_width; x+=mbsize, i_mb++, pixoff += mbsize )
149                 cost += X264_MIN( h->pixf.mbcmp[pixelsize]( &src[pixoff], i_stride, &fenc_plane[pixoff], i_stride ), fenc->i_intra_cost[i_mb] );
150
151     int lambda = b_lowres ? 1 : 4;
152     if( w )
153     {
154         int numslices;
155         if( h->param.i_slice_count )
156             numslices = h->param.i_slice_count;
157         else if( h->param.i_slice_max_mbs )
158             numslices = (h->sps->i_mb_width * h->sps->i_mb_height + h->param.i_slice_max_mbs-1) / h->param.i_slice_max_mbs;
159         else
160             numslices = 1;
161         // FIXME still need to calculate for --slice-max-size
162         // 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.
163         cost += lambda * numslices * ( 10 + 2 * ( bs_size_ue( w[0].i_denom ) + bs_size_se( w[0].i_scale ) + bs_size_se( w[0].i_offset ) ) );
164     }
165     x264_emms();
166     return cost;
167 }
168
169 void x264_weights_analyse( x264_t *h, x264_frame_t *fenc, x264_frame_t *ref, int b_lowres, int b_lookahead )
170 {
171     unsigned int fenc_sum, ref_sum;
172     float fenc_mean, ref_mean;
173     uint64_t fenc_var, ref_var;
174     int i_off, offset_search;
175     int minoff, minscale, mindenom;
176     unsigned int minscore, origscore;
177     int i_delta_index = fenc->i_frame - ref->i_frame - 1;
178     /* epsilon is chosen to require at least a numerator of 127 (with denominator = 128) */
179     const float epsilon = 1.0/128.0;
180
181     float guess_scale;
182     int found;
183     x264_weight_t *weights = fenc->weight[0];
184
185     weights_plane_analyse( h, fenc->plane[0], fenc->i_width[0], fenc->i_lines[0], fenc->i_stride[0], &fenc_sum, &fenc_var );
186     weights_plane_analyse( h, ref->plane[0], ref->i_width[0], ref->i_lines[0], ref->i_stride[0], &ref_sum, &ref_var );
187     fenc_var = round( sqrt( fenc_var ) );
188     ref_var = round( sqrt( ref_var ) );
189     fenc_mean = (float)fenc_sum / (fenc->i_lines[0] * fenc->i_width[0]);
190     ref_mean = (float)ref_sum / (fenc->i_lines[0] * fenc->i_width[0]);
191
192     //early termination
193
194     if( fabs( ref_mean - fenc_mean ) < 0.5 && fabsf( 1 - (float)fenc_var / ref_var ) < epsilon )
195         return;
196
197     guess_scale = ref_var ? (float)fenc_var/ref_var : 0;
198     get_h264_weight( round( guess_scale * 128 ), 0, &weights[0] );
199
200     found = 0;
201     mindenom = weights[0].i_denom;
202     minscale = weights[0].i_scale;
203     minoff = 0;
204     offset_search = x264_clip3( floor( fenc_mean - ref_mean * minscale / (1 << mindenom) + 0.5f*b_lookahead ), -128, 126 );
205
206     if( !fenc->b_intra_calculated )
207     {
208         x264_mb_analysis_t a;
209         x264_lowres_context_init( h, &a );
210         x264_slicetype_frame_cost( h, &a, &fenc, 0, 0, 0, 0 );
211     }
212     uint8_t *mcbuf = x264_weight_cost_init_luma( h, fenc, ref, h->mb.p_weight_buf[0], b_lowres );
213     origscore = minscore = x264_weight_cost( h, fenc, mcbuf, 0, b_lowres );
214
215     if( !minscore )
216         return;
217
218     // This gives a slight improvement due to rounding errors but only tests
219     // one offset on lookahead.
220     // TODO: currently searches only offset +1. try other offsets/multipliers/combinations thereof?
221     for( i_off = offset_search; i_off <= offset_search+!b_lookahead; i_off++ )
222     {
223         SET_WEIGHT( weights[0], 1, minscale, mindenom, i_off );
224         unsigned int s = x264_weight_cost( h, fenc, mcbuf, &weights[0], b_lowres );
225         COPY3_IF_LT( minscore, s, minoff, i_off, found, 1 );
226     }
227     x264_emms();
228
229     /* FIXME: More analysis can be done here on SAD vs. SATD termination. */
230     if( !found || (minscale == 1<<mindenom && minoff == 0) || minscore >= fenc->i_width[0] * fenc->i_lines[0] * (b_lowres ? 2 : 8) )
231     {
232         SET_WEIGHT( weights[0], 0, 1, 0, 0 );
233         return;
234     }
235     else
236         SET_WEIGHT( weights[0], 1, minscale, mindenom, minoff );
237
238     if( h->param.analyse.i_weighted_pred == X264_WEIGHTP_FAKE && weights[0].weightfn )
239         fenc->f_weighted_cost_delta[i_delta_index] = (float)minscore / origscore;
240
241     if( weights[0].weightfn && b_lookahead )
242     {
243         //scale lowres in lookahead for slicetype_frame_cost
244         int i_padv = PADV<<h->param.b_interlaced;
245         uint8_t *src = ref->buffer_lowres[0];
246         uint8_t *dst = h->mb.p_weight_buf[0];
247         int width = ref->i_width_lowres + PADH*2;
248         int height = ref->i_lines_lowres + i_padv*2;
249         x264_weight_scale_plane( h, dst, ref->i_stride_lowres, src, ref->i_stride_lowres,
250                                  width, height, &weights[0] );
251         fenc->weighted[0] = h->mb.p_weight_buf[0] + PADH + ref->i_stride_lowres * i_padv;
252     }
253 }
254
255 static int x264_slicetype_mb_cost( x264_t *h, x264_mb_analysis_t *a,
256                                    x264_frame_t **frames, int p0, int p1, int b,
257                                    int dist_scale_factor, int do_search[2], const x264_weight_t *w )
258 {
259     x264_frame_t *fref0 = frames[p0];
260     x264_frame_t *fref1 = frames[p1];
261     x264_frame_t *fenc  = frames[b];
262     const int b_bidir = (b < p1);
263     const int i_mb_x = h->mb.i_mb_x;
264     const int i_mb_y = h->mb.i_mb_y;
265     const int i_mb_stride = h->sps->i_mb_width;
266     const int i_mb_xy = i_mb_x + i_mb_y * i_mb_stride;
267     const int i_stride = fenc->i_stride_lowres;
268     const int i_pel_offset = 8 * (i_mb_x + i_mb_y * i_stride);
269     const int i_bipred_weight = h->param.analyse.b_weighted_bipred ? 64 - (dist_scale_factor>>2) : 32;
270     int16_t (*fenc_mvs[2])[2] = { &frames[b]->lowres_mvs[0][b-p0-1][i_mb_xy], &frames[b]->lowres_mvs[1][p1-b-1][i_mb_xy] };
271     int (*fenc_costs[2]) = { &frames[b]->lowres_mv_costs[0][b-p0-1][i_mb_xy], &frames[b]->lowres_mv_costs[1][p1-b-1][i_mb_xy] };
272
273     ALIGNED_8( uint8_t pix1[9*FDEC_STRIDE] );
274     uint8_t *pix2 = pix1+8;
275     x264_me_t m[2];
276     int i_bcost = COST_MAX;
277     int l, i;
278     int list_used = 0;
279
280     h->mb.pic.p_fenc[0] = h->mb.pic.fenc_buf;
281     h->mc.copy[PIXEL_8x8]( h->mb.pic.p_fenc[0], FENC_STRIDE, &fenc->lowres[0][i_pel_offset], i_stride, 8 );
282
283     if( p0 == p1 )
284         goto lowres_intra_mb;
285
286     // no need for h->mb.mv_min[]
287     h->mb.mv_min_fpel[0] = -8*h->mb.i_mb_x - 4;
288     h->mb.mv_max_fpel[0] = 8*( h->sps->i_mb_width - h->mb.i_mb_x - 1 ) + 4;
289     h->mb.mv_min_spel[0] = 4*( h->mb.mv_min_fpel[0] - 8 );
290     h->mb.mv_max_spel[0] = 4*( h->mb.mv_max_fpel[0] + 8 );
291     if( h->mb.i_mb_x >= h->sps->i_mb_width - 2 )
292     {
293         h->mb.mv_min_fpel[1] = -8*h->mb.i_mb_y - 4;
294         h->mb.mv_max_fpel[1] = 8*( h->sps->i_mb_height - h->mb.i_mb_y - 1 ) + 4;
295         h->mb.mv_min_spel[1] = 4*( h->mb.mv_min_fpel[1] - 8 );
296         h->mb.mv_max_spel[1] = 4*( h->mb.mv_max_fpel[1] + 8 );
297     }
298
299 #define LOAD_HPELS_LUMA(dst, src) \
300     { \
301         (dst)[0] = &(src)[0][i_pel_offset]; \
302         (dst)[1] = &(src)[1][i_pel_offset]; \
303         (dst)[2] = &(src)[2][i_pel_offset]; \
304         (dst)[3] = &(src)[3][i_pel_offset]; \
305     }
306 #define LOAD_WPELS_LUMA(dst,src) \
307     (dst) = &(src)[i_pel_offset];
308
309 #define CLIP_MV( mv ) \
310     { \
311         mv[0] = x264_clip3( mv[0], h->mb.mv_min_spel[0], h->mb.mv_max_spel[0] ); \
312         mv[1] = x264_clip3( mv[1], h->mb.mv_min_spel[1], h->mb.mv_max_spel[1] ); \
313     }
314 #define TRY_BIDIR( mv0, mv1, penalty ) \
315     { \
316         int stride1 = 16, stride2 = 16; \
317         uint8_t *src1, *src2; \
318         int i_cost; \
319         src1 = h->mc.get_ref( pix1, &stride1, m[0].p_fref, m[0].i_stride[0], \
320                               (mv0)[0], (mv0)[1], 8, 8, w ); \
321         src2 = h->mc.get_ref( pix2, &stride2, m[1].p_fref, m[1].i_stride[0], \
322                               (mv1)[0], (mv1)[1], 8, 8, w ); \
323         h->mc.avg[PIXEL_8x8]( pix1, 16, src1, stride1, src2, stride2, i_bipred_weight ); \
324         i_cost = penalty + h->pixf.mbcmp[PIXEL_8x8]( \
325                            m[0].p_fenc[0], FENC_STRIDE, pix1, 16 ); \
326         COPY2_IF_LT( i_bcost, i_cost, list_used, 3 ); \
327     }
328
329     m[0].i_pixel = PIXEL_8x8;
330     m[0].p_cost_mv = a->p_cost_mv;
331     m[0].i_stride[0] = i_stride;
332     m[0].p_fenc[0] = h->mb.pic.p_fenc[0];
333     m[0].weight = w;
334     LOAD_HPELS_LUMA( m[0].p_fref, fref0->lowres );
335     m[0].p_fref_w = m[0].p_fref[0];
336     if( w[0].weightfn )
337         LOAD_WPELS_LUMA( m[0].p_fref_w, fenc->weighted[0] );
338
339     if( b_bidir )
340     {
341         int16_t *mvr = fref1->lowres_mvs[0][p1-p0-1][i_mb_xy];
342         int dmv[2][2];
343
344         h->mc.memcpy_aligned( &m[1], &m[0], sizeof(x264_me_t) );
345         m[1].i_ref = p1;
346         m[1].weight = weight_none;
347         LOAD_HPELS_LUMA( m[1].p_fref, fref1->lowres );
348         m[1].p_fref_w = m[1].p_fref[0];
349
350         dmv[0][0] = ( mvr[0] * dist_scale_factor + 128 ) >> 8;
351         dmv[0][1] = ( mvr[1] * dist_scale_factor + 128 ) >> 8;
352         dmv[1][0] = dmv[0][0] - mvr[0];
353         dmv[1][1] = dmv[0][1] - mvr[1];
354         CLIP_MV( dmv[0] );
355         CLIP_MV( dmv[1] );
356
357         TRY_BIDIR( dmv[0], dmv[1], 0 );
358         if( dmv[0][0] | dmv[0][1] | dmv[1][0] | dmv[1][1] )
359         {
360             int i_cost;
361             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 );
362             i_cost = h->pixf.mbcmp[PIXEL_8x8]( m[0].p_fenc[0], FENC_STRIDE, pix1, 16 );
363             COPY2_IF_LT( i_bcost, i_cost, list_used, 3 );
364         }
365     }
366
367     for( l = 0; l < 1 + b_bidir; l++ )
368     {
369         if( do_search[l] )
370         {
371             int i_mvc = 0;
372             int16_t (*fenc_mv)[2] = fenc_mvs[l];
373             ALIGNED_4( int16_t mvc[4][2] );
374
375             /* Reverse-order MV prediction. */
376             M32( mvc[0] ) = 0;
377             M32( mvc[1] ) = 0;
378             M32( mvc[2] ) = 0;
379 #define MVC(mv) { CP32( mvc[i_mvc], mv ); i_mvc++; }
380             if( i_mb_x < h->sps->i_mb_width - 1 )
381                 MVC(fenc_mv[1]);
382             if( i_mb_y < h->sps->i_mb_height - 1 )
383             {
384                 MVC(fenc_mv[i_mb_stride]);
385                 if( i_mb_x > 0 )
386                     MVC(fenc_mv[i_mb_stride-1]);
387                 if( i_mb_x < h->sps->i_mb_width - 1 )
388                     MVC(fenc_mv[i_mb_stride+1]);
389             }
390 #undef MVC
391             x264_median_mv( m[l].mvp, mvc[0], mvc[1], mvc[2] );
392             x264_me_search( h, &m[l], mvc, i_mvc );
393
394             m[l].cost -= 2; // remove mvcost from skip mbs
395             if( M32( m[l].mv ) )
396                 m[l].cost += 5;
397             CP32( fenc_mvs[l], m[l].mv );
398             *fenc_costs[l] = m[l].cost;
399         }
400         else
401         {
402             CP32( m[l].mv, fenc_mvs[l] );
403             m[l].cost = *fenc_costs[l];
404         }
405         COPY2_IF_LT( i_bcost, m[l].cost, list_used, l+1 );
406     }
407
408     if( b_bidir && ( M32( m[0].mv ) || M32( m[1].mv ) ) )
409         TRY_BIDIR( m[0].mv, m[1].mv, 5 );
410
411     /* Store to width-2 bitfield. */
412     frames[b]->lowres_inter_types[b-p0][p1-b][i_mb_xy>>2] &= ~(3<<((i_mb_xy&3)*2));
413     frames[b]->lowres_inter_types[b-p0][p1-b][i_mb_xy>>2] |= list_used<<((i_mb_xy&3)*2);
414
415 lowres_intra_mb:
416     /* forbid intra-mbs in B-frames, because it's rare and not worth checking */
417     /* FIXME: Should we still forbid them now that we cache intra scores? */
418     if( !b_bidir || h->param.rc.b_mb_tree )
419     {
420         int i_icost, b_intra;
421         if( !fenc->b_intra_calculated )
422         {
423             ALIGNED_ARRAY_16( uint8_t, edge,[33] );
424             uint8_t *pix = &pix1[8+FDEC_STRIDE - 1];
425             uint8_t *src = &fenc->lowres[0][i_pel_offset - 1];
426             const int intra_penalty = 5;
427             int satds[4];
428
429             memcpy( pix-FDEC_STRIDE, src-i_stride, 17 );
430             for( i=0; i<8; i++ )
431                 pix[i*FDEC_STRIDE] = src[i*i_stride];
432             pix++;
433
434             if( h->pixf.intra_mbcmp_x3_8x8c )
435             {
436                 h->pixf.intra_mbcmp_x3_8x8c( h->mb.pic.p_fenc[0], pix, satds );
437                 h->predict_8x8c[I_PRED_CHROMA_P]( pix );
438                 satds[I_PRED_CHROMA_P] =
439                     h->pixf.mbcmp[PIXEL_8x8]( pix, FDEC_STRIDE, h->mb.pic.p_fenc[0], FENC_STRIDE );
440             }
441             else
442             {
443                 for( i=0; i<4; i++ )
444                 {
445                     h->predict_8x8c[i]( pix );
446                     satds[i] = h->pixf.mbcmp[PIXEL_8x8]( pix, FDEC_STRIDE, h->mb.pic.p_fenc[0], FENC_STRIDE );
447                 }
448             }
449             i_icost = X264_MIN4( satds[0], satds[1], satds[2], satds[3] );
450
451             h->predict_8x8_filter( pix, edge, ALL_NEIGHBORS, ALL_NEIGHBORS );
452             for( i=3; i<9; i++ )
453             {
454                 int satd;
455                 h->predict_8x8[i]( pix, edge );
456                 satd = h->pixf.mbcmp[PIXEL_8x8]( pix, FDEC_STRIDE, h->mb.pic.p_fenc[0], FENC_STRIDE );
457                 i_icost = X264_MIN( i_icost, satd );
458             }
459
460             i_icost += intra_penalty;
461             fenc->i_intra_cost[i_mb_xy] = i_icost;
462         }
463         else
464             i_icost = fenc->i_intra_cost[i_mb_xy];
465         if( !b_bidir )
466         {
467             b_intra = i_icost < i_bcost;
468             if( b_intra )
469                 i_bcost = i_icost;
470             if(   (i_mb_x > 0 && i_mb_x < h->sps->i_mb_width - 1
471                 && i_mb_y > 0 && i_mb_y < h->sps->i_mb_height - 1)
472                 || h->sps->i_mb_width <= 2 || h->sps->i_mb_height <= 2 )
473             {
474                 fenc->i_intra_mbs[b-p0] += b_intra;
475                 fenc->i_cost_est[0][0] += i_icost;
476                 if( h->param.rc.i_aq_mode )
477                     fenc->i_cost_est_aq[0][0] += (i_icost * fenc->i_inv_qscale_factor[i_mb_xy] + 128) >> 8;
478             }
479         }
480     }
481
482     fenc->lowres_costs[b-p0][p1-b][i_mb_xy] = i_bcost;
483
484     return i_bcost;
485 }
486 #undef TRY_BIDIR
487
488 #define NUM_MBS\
489    (h->sps->i_mb_width > 2 && h->sps->i_mb_height > 2 ?\
490    (h->sps->i_mb_width - 2) * (h->sps->i_mb_height - 2) :\
491     h->sps->i_mb_width * h->sps->i_mb_height)
492
493 static int x264_slicetype_frame_cost( x264_t *h, x264_mb_analysis_t *a,
494                                       x264_frame_t **frames, int p0, int p1, int b,
495                                       int b_intra_penalty )
496 {
497
498     int i_score = 0;
499     /* Don't use the AQ'd scores for slicetype decision. */
500     int i_score_aq = 0;
501     int do_search[2];
502     const x264_weight_t *w = weight_none;
503     /* Check whether we already evaluated this frame
504      * If we have tried this frame as P, then we have also tried
505      * the preceding frames as B. (is this still true?) */
506     /* Also check that we already calculated the row SATDs for the current frame. */
507     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) )
508     {
509         i_score = frames[b]->i_cost_est[b-p0][p1-b];
510     }
511     else
512     {
513         int dist_scale_factor = 128;
514         int *row_satd = frames[b]->i_row_satds[b-p0][p1-b];
515
516         /* For each list, check to see whether we have lowres motion-searched this reference frame before. */
517         do_search[0] = b != p0 && frames[b]->lowres_mvs[0][b-p0-1][0][0] == 0x7FFF;
518         do_search[1] = b != p1 && frames[b]->lowres_mvs[1][p1-b-1][0][0] == 0x7FFF;
519         if( do_search[0] )
520         {
521             if( ( h->param.analyse.i_weighted_pred == X264_WEIGHTP_SMART
522                   || h->param.analyse.i_weighted_pred == X264_WEIGHTP_FAKE ) && b == p1 )
523             {
524                 x264_weights_analyse( h, frames[b], frames[p0], 1, 1 );
525                 w = frames[b]->weight[0];
526             }
527             frames[b]->lowres_mvs[0][b-p0-1][0][0] = 0;
528         }
529         if( do_search[1] ) frames[b]->lowres_mvs[1][p1-b-1][0][0] = 0;
530
531         if( b == p1 )
532         {
533             frames[b]->i_intra_mbs[b-p0] = 0;
534             frames[b]->i_cost_est[0][0] = 0;
535             frames[b]->i_cost_est_aq[0][0] = 0;
536         }
537         if( p1 != p0 )
538             dist_scale_factor = ( ((b-p0) << 8) + ((p1-p0) >> 1) ) / (p1-p0);
539
540         /* Lowres lookahead goes backwards because the MVs are used as predictors in the main encode.
541          * This considerably improves MV prediction overall. */
542
543         /* the edge mbs seem to reduce the predictive quality of the
544          * whole frame's score, but are needed for a spatial distribution. */
545         if( h->param.rc.b_mb_tree || h->param.rc.i_vbv_buffer_size ||
546             h->sps->i_mb_width <= 2 || h->sps->i_mb_height <= 2 )
547         {
548             for( h->mb.i_mb_y = h->sps->i_mb_height - 1; h->mb.i_mb_y >= 0; h->mb.i_mb_y-- )
549             {
550                 row_satd[ h->mb.i_mb_y ] = 0;
551                 for( h->mb.i_mb_x = h->sps->i_mb_width - 1; h->mb.i_mb_x >= 0; h->mb.i_mb_x-- )
552                 {
553                     int i_mb_cost = x264_slicetype_mb_cost( h, a, frames, p0, p1, b, dist_scale_factor, do_search, w );
554                     int i_mb_cost_aq = i_mb_cost;
555                     if( h->param.rc.i_aq_mode )
556                         i_mb_cost_aq = (i_mb_cost_aq * frames[b]->i_inv_qscale_factor[h->mb.i_mb_x + h->mb.i_mb_y*h->mb.i_mb_stride] + 128) >> 8;
557                     row_satd[ h->mb.i_mb_y ] += i_mb_cost_aq;
558                     if( (h->mb.i_mb_y > 0 && h->mb.i_mb_y < h->sps->i_mb_height - 1 &&
559                          h->mb.i_mb_x > 0 && h->mb.i_mb_x < h->sps->i_mb_width - 1) ||
560                          h->sps->i_mb_width <= 2 || h->sps->i_mb_height <= 2 )
561                     {
562                         /* Don't use AQ-weighted costs for slicetype decision, only for ratecontrol. */
563                         i_score += i_mb_cost;
564                         i_score_aq += i_mb_cost_aq;
565                     }
566                 }
567             }
568         }
569         else
570         {
571             for( h->mb.i_mb_y = h->sps->i_mb_height - 2; h->mb.i_mb_y > 0; h->mb.i_mb_y-- )
572                 for( h->mb.i_mb_x = h->sps->i_mb_width - 2; h->mb.i_mb_x > 0; h->mb.i_mb_x-- )
573                 {
574                     int i_mb_cost = x264_slicetype_mb_cost( h, a, frames, p0, p1, b, dist_scale_factor, do_search, w );
575                     int i_mb_cost_aq = i_mb_cost;
576                     if( h->param.rc.i_aq_mode )
577                         i_mb_cost_aq = (i_mb_cost_aq * frames[b]->i_inv_qscale_factor[h->mb.i_mb_x + h->mb.i_mb_y*h->mb.i_mb_stride] + 128) >> 8;
578                     i_score += i_mb_cost;
579                     i_score_aq += i_mb_cost_aq;
580                 }
581         }
582
583         if( b != p1 )
584             i_score = (uint64_t)i_score * 100 / (120 + h->param.i_bframe_bias);
585         else
586             frames[b]->b_intra_calculated = 1;
587
588         frames[b]->i_cost_est[b-p0][p1-b] = i_score;
589         frames[b]->i_cost_est_aq[b-p0][p1-b] = i_score_aq;
590         x264_emms();
591     }
592
593     if( b_intra_penalty )
594     {
595         // arbitrary penalty for I-blocks after B-frames
596         int nmb = NUM_MBS;
597         i_score += i_score * frames[b]->i_intra_mbs[b-p0] / (nmb * 8);
598     }
599     return i_score;
600 }
601
602 /* If MB-tree changes the quantizers, we need to recalculate the frame cost without
603  * re-running lookahead. */
604 static int x264_slicetype_frame_cost_recalculate( x264_t *h, x264_frame_t **frames, int p0, int p1, int b )
605 {
606     int i_score = 0;
607     int *row_satd = frames[b]->i_row_satds[b-p0][p1-b];
608     float *qp_offset = IS_X264_TYPE_B(frames[b]->i_type) ? frames[b]->f_qp_offset_aq : frames[b]->f_qp_offset;
609     x264_emms();
610     for( h->mb.i_mb_y = h->sps->i_mb_height - 1; h->mb.i_mb_y >= 0; h->mb.i_mb_y-- )
611     {
612         row_satd[ h->mb.i_mb_y ] = 0;
613         for( h->mb.i_mb_x = h->sps->i_mb_width - 1; h->mb.i_mb_x >= 0; h->mb.i_mb_x-- )
614         {
615             int i_mb_xy = h->mb.i_mb_x + h->mb.i_mb_y*h->mb.i_mb_stride;
616             int i_mb_cost = frames[b]->lowres_costs[b-p0][p1-b][i_mb_xy];
617             float qp_adj = qp_offset[i_mb_xy];
618             i_mb_cost = (i_mb_cost * x264_exp2fix8(qp_adj) + 128) >> 8;
619             row_satd[ h->mb.i_mb_y ] += i_mb_cost;
620             if( (h->mb.i_mb_y > 0 && h->mb.i_mb_y < h->sps->i_mb_height - 1 &&
621                  h->mb.i_mb_x > 0 && h->mb.i_mb_x < h->sps->i_mb_width - 1) ||
622                  h->sps->i_mb_width <= 2 || h->sps->i_mb_height <= 2 )
623             {
624                 i_score += i_mb_cost;
625             }
626         }
627     }
628     return i_score;
629 }
630
631 static void x264_macroblock_tree_finish( x264_t *h, x264_frame_t *frame, int ref0_distance )
632 {
633     int mb_index;
634     x264_emms();
635     float weightdelta = 0.0;
636     if( ref0_distance && frame->f_weighted_cost_delta[ref0_distance-1] > 0 )
637         weightdelta = (1.0 - frame->f_weighted_cost_delta[ref0_distance-1]);
638
639     /* Allow the strength to be adjusted via qcompress, since the two
640      * concepts are very similar. */
641     float strength = 5.0f * (1.0f - h->param.rc.f_qcompress);
642     for( mb_index = 0; mb_index < h->mb.i_mb_count; mb_index++ )
643     {
644         int intra_cost = (frame->i_intra_cost[mb_index] * frame->i_inv_qscale_factor[mb_index]+128)>>8;
645         if( intra_cost )
646         {
647             int propagate_cost = frame->i_propagate_cost[mb_index];
648             float log2_ratio = x264_log2(intra_cost + propagate_cost) - x264_log2(intra_cost) + weightdelta;
649             frame->f_qp_offset[mb_index] = frame->f_qp_offset_aq[mb_index] - strength * log2_ratio;
650         }
651     }
652 }
653
654 static void x264_macroblock_tree_propagate( x264_t *h, x264_frame_t **frames, int p0, int p1, int b )
655 {
656     uint16_t *ref_costs[2] = {frames[p0]->i_propagate_cost,frames[p1]->i_propagate_cost};
657     int dist_scale_factor = ( ((b-p0) << 8) + ((p1-p0) >> 1) ) / (p1-p0);
658     int i_bipred_weight = h->param.analyse.b_weighted_bipred ? 64 - (dist_scale_factor>>2) : 32;
659     int16_t (*mvs[2])[2] = { frames[b]->lowres_mvs[0][b-p0-1], frames[b]->lowres_mvs[1][p1-b-1] };
660     int bipred_weights[2] = {i_bipred_weight, 64 - i_bipred_weight};
661     int *buf = h->scratch_buffer;
662
663     for( h->mb.i_mb_y = 0; h->mb.i_mb_y < h->sps->i_mb_height; h->mb.i_mb_y++ )
664     {
665         int mb_index = h->mb.i_mb_y*h->mb.i_mb_stride;
666         h->mc.mbtree_propagate_cost( buf, frames[b]->i_propagate_cost+mb_index,
667             frames[b]->i_intra_cost+mb_index, frames[b]->lowres_costs[b-p0][p1-b]+mb_index,
668             frames[b]->i_inv_qscale_factor+mb_index, h->sps->i_mb_width );
669         for( h->mb.i_mb_x = 0; h->mb.i_mb_x < h->sps->i_mb_width; h->mb.i_mb_x++, mb_index++ )
670         {
671             int propagate_amount = buf[h->mb.i_mb_x];
672             /* Don't propagate for an intra block. */
673             if( propagate_amount > 0 )
674             {
675                 /* Access width-2 bitfield. */
676                 int lists_used = (frames[b]->lowres_inter_types[b-p0][p1-b][mb_index>>2] >> ((mb_index&3)*2))&3;
677                 int list;
678                 /* Follow the MVs to the previous frame(s). */
679                 for( list = 0; list < 2; list++ )
680                     if( (lists_used >> list)&1 )
681                     {
682                         int x = mvs[list][mb_index][0];
683                         int y = mvs[list][mb_index][1];
684                         int listamount = propagate_amount;
685                         int mbx = (x>>5)+h->mb.i_mb_x;
686                         int mby = (y>>5)+h->mb.i_mb_y;
687                         int idx0 = mbx + mby*h->mb.i_mb_stride;
688                         int idx1 = idx0 + 1;
689                         int idx2 = idx0 + h->mb.i_mb_stride;
690                         int idx3 = idx0 + h->mb.i_mb_stride + 1;
691                         x &= 31;
692                         y &= 31;
693                         int idx0weight = (32-y)*(32-x);
694                         int idx1weight = (32-y)*x;
695                         int idx2weight = y*(32-x);
696                         int idx3weight = y*x;
697
698                         /* Apply bipred weighting. */
699                         if( lists_used == 3 )
700                             listamount = (listamount * bipred_weights[list] + 32) >> 6;
701
702 #define CLIP_ADD(s,x) (s) = X264_MIN((s)+(x),(1<<16)-1)
703
704                         /* We could just clip the MVs, but pixels that lie outside the frame probably shouldn't
705                          * be counted. */
706                         if( mbx < h->sps->i_mb_width-1 && mby < h->sps->i_mb_height-1 && mbx >= 0 && mby >= 0 )
707                         {
708                             CLIP_ADD( ref_costs[list][idx0], (listamount*idx0weight+512)>>10 );
709                             CLIP_ADD( ref_costs[list][idx1], (listamount*idx1weight+512)>>10 );
710                             CLIP_ADD( ref_costs[list][idx2], (listamount*idx2weight+512)>>10 );
711                             CLIP_ADD( ref_costs[list][idx3], (listamount*idx3weight+512)>>10 );
712                         }
713                         else /* Check offsets individually */
714                         {
715                             if( mbx < h->sps->i_mb_width && mby < h->sps->i_mb_height && mbx >= 0 && mby >= 0 )
716                                 CLIP_ADD( ref_costs[list][idx0], (listamount*idx0weight+512)>>10 );
717                             if( mbx+1 < h->sps->i_mb_width && mby < h->sps->i_mb_height && mbx+1 >= 0 && mby >= 0 )
718                                 CLIP_ADD( ref_costs[list][idx1], (listamount*idx1weight+512)>>10 );
719                             if( mbx < h->sps->i_mb_width && mby+1 < h->sps->i_mb_height && mbx >= 0 && mby+1 >= 0 )
720                                 CLIP_ADD( ref_costs[list][idx2], (listamount*idx2weight+512)>>10 );
721                             if( mbx+1 < h->sps->i_mb_width && mby+1 < h->sps->i_mb_height && mbx+1 >= 0 && mby+1 >= 0 )
722                                 CLIP_ADD( ref_costs[list][idx3], (listamount*idx3weight+512)>>10 );
723                         }
724                     }
725             }
726         }
727     }
728
729     if( h->param.rc.i_vbv_buffer_size && b == p1 )
730         x264_macroblock_tree_finish( h, frames[b], b-p0 );
731 }
732
733 static void x264_macroblock_tree( x264_t *h, x264_mb_analysis_t *a, x264_frame_t **frames, int num_frames, int b_intra )
734 {
735     int i, idx = !b_intra;
736     int last_nonb, cur_nonb = 1;
737     if( b_intra )
738         x264_slicetype_frame_cost( h, a, frames, 0, 0, 0, 0 );
739
740     i = num_frames-1;
741     while( i > 0 && frames[i]->i_type == X264_TYPE_B )
742         i--;
743     last_nonb = i;
744
745     if( last_nonb < idx )
746         return;
747
748     memset( frames[last_nonb]->i_propagate_cost, 0, h->mb.i_mb_count * sizeof(uint16_t) );
749     while( i-- > idx )
750     {
751         cur_nonb = i;
752         while( frames[cur_nonb]->i_type == X264_TYPE_B && cur_nonb > 0 )
753             cur_nonb--;
754         if( cur_nonb < idx )
755             break;
756         x264_slicetype_frame_cost( h, a, frames, cur_nonb, last_nonb, last_nonb, 0 );
757         memset( frames[cur_nonb]->i_propagate_cost, 0, h->mb.i_mb_count * sizeof(uint16_t) );
758         while( i > cur_nonb )
759         {
760             x264_slicetype_frame_cost( h, a, frames, cur_nonb, last_nonb, i, 0 );
761             memset( frames[i]->i_propagate_cost, 0, h->mb.i_mb_count * sizeof(uint16_t) );
762             x264_macroblock_tree_propagate( h, frames, cur_nonb, last_nonb, i );
763             i--;
764         }
765         x264_macroblock_tree_propagate( h, frames, cur_nonb, last_nonb, last_nonb );
766         last_nonb = cur_nonb;
767     }
768
769     x264_macroblock_tree_finish( h, frames[last_nonb], last_nonb );
770 }
771
772 static int x264_vbv_frame_cost( x264_t *h, x264_mb_analysis_t *a, x264_frame_t **frames, int p0, int p1, int b )
773 {
774     int cost = x264_slicetype_frame_cost( h, a, frames, p0, p1, b, 0 );
775     if( h->param.rc.i_aq_mode )
776     {
777         if( h->param.rc.b_mb_tree )
778             return x264_slicetype_frame_cost_recalculate( h, frames, p0, p1, b );
779         else
780             return frames[b]->i_cost_est_aq[b-p0][p1-b];
781     }
782     return cost;
783 }
784
785 static void x264_vbv_lookahead( x264_t *h, x264_mb_analysis_t *a, x264_frame_t **frames, int num_frames, int keyframe )
786 {
787     int last_nonb = 0, cur_nonb = 1, next_nonb, i, idx = 0;
788     while( cur_nonb < num_frames && frames[cur_nonb]->i_type == X264_TYPE_B )
789         cur_nonb++;
790     next_nonb = keyframe ? last_nonb : cur_nonb;
791
792     while( cur_nonb <= num_frames )
793     {
794         /* P/I cost: This shouldn't include the cost of next_nonb */
795         if( next_nonb != cur_nonb )
796         {
797             int p0 = IS_X264_TYPE_I( frames[cur_nonb]->i_type ) ? cur_nonb : last_nonb;
798             frames[next_nonb]->i_planned_satd[idx] = x264_vbv_frame_cost( h, a, frames, p0, cur_nonb, cur_nonb );
799             frames[next_nonb]->i_planned_type[idx] = frames[cur_nonb]->i_type;
800             idx++;
801         }
802         /* Handle the B-frames: coded order */
803         for( i = last_nonb+1; i < cur_nonb; i++, idx++ )
804         {
805             frames[next_nonb]->i_planned_satd[idx] = x264_vbv_frame_cost( h, a, frames, last_nonb, cur_nonb, i );
806             frames[next_nonb]->i_planned_type[idx] = X264_TYPE_B;
807         }
808         last_nonb = cur_nonb;
809         cur_nonb++;
810         while( cur_nonb <= num_frames && frames[cur_nonb]->i_type == X264_TYPE_B )
811             cur_nonb++;
812     }
813     frames[next_nonb]->i_planned_type[idx] = X264_TYPE_AUTO;
814 }
815
816 static int x264_slicetype_path_cost( x264_t *h, x264_mb_analysis_t *a, x264_frame_t **frames, char *path, int threshold )
817 {
818     int loc = 1;
819     int cost = 0;
820     int cur_p = 0;
821     path--; /* Since the 1st path element is really the second frame */
822     while( path[loc] )
823     {
824         int next_p = loc;
825         int next_b;
826         /* Find the location of the next P-frame. */
827         while( path[next_p] && path[next_p] != 'P' )
828             next_p++;
829         /* Return if the path doesn't end on a P-frame. */
830         if( path[next_p] != 'P' )
831             return cost;
832
833         /* Add the cost of the P-frame found above */
834         cost += x264_slicetype_frame_cost( h, a, frames, cur_p, next_p, next_p, 0 );
835         /* Early terminate if the cost we have found is larger than the best path cost so far */
836         if( cost > threshold )
837             break;
838
839         for( next_b = loc; next_b < next_p && cost < threshold; next_b++ )
840             cost += x264_slicetype_frame_cost( h, a, frames, cur_p, next_p, next_b, 0 );
841
842         loc = next_p + 1;
843         cur_p = next_p;
844     }
845     return cost;
846 }
847
848 /* Viterbi/trellis slicetype decision algorithm. */
849 /* Uses strings due to the fact that the speed of the control functions is
850    negligable compared to the cost of running slicetype_frame_cost, and because
851    it makes debugging easier. */
852 static void x264_slicetype_path( x264_t *h, x264_mb_analysis_t *a, x264_frame_t **frames, int length, int max_bframes, char (*best_paths)[X264_LOOKAHEAD_MAX] )
853 {
854     char paths[X264_BFRAME_MAX+1][X264_LOOKAHEAD_MAX] = {{0}};
855     int num_paths = X264_MIN( max_bframes+1, length );
856     int path;
857     int best_cost = COST_MAX;
858     int best_path_index = 0;
859
860     /* Iterate over all currently possible paths */
861     for( path = 0; path < num_paths; path++ )
862     {
863         /* Add suffixes to the current path */
864         int len = length - (path + 1);
865         memcpy( paths[path], best_paths[len % (X264_BFRAME_MAX+1)], len );
866         memset( paths[path]+len, 'B', path );
867         strcat( paths[path], "P" );
868
869         /* Calculate the actual cost of the current path */
870         int cost = x264_slicetype_path_cost( h, a, frames, paths[path], best_cost );
871         if( cost < best_cost )
872         {
873             best_cost = cost;
874             best_path_index = path;
875         }
876     }
877
878     /* Store the best path. */
879     memcpy( best_paths[length % (X264_BFRAME_MAX+1)], paths[best_path_index], length );
880 }
881
882 static int scenecut_internal( x264_t *h, x264_mb_analysis_t *a, x264_frame_t **frames, int p0, int p1, int print )
883 {
884     x264_frame_t *frame = frames[p1];
885     x264_slicetype_frame_cost( h, a, frames, p0, p1, p1, 0 );
886
887     int icost = frame->i_cost_est[0][0];
888     int pcost = frame->i_cost_est[p1-p0][0];
889     float f_bias;
890     int i_gop_size = frame->i_frame - h->lookahead->i_last_idr;
891     float f_thresh_max = h->param.i_scenecut_threshold / 100.0;
892     /* magic numbers pulled out of thin air */
893     float f_thresh_min = f_thresh_max * h->param.i_keyint_min
894                          / ( h->param.i_keyint_max * 4 );
895     int res;
896
897     if( h->param.i_keyint_min == h->param.i_keyint_max )
898         f_thresh_min= f_thresh_max;
899     if( i_gop_size < h->param.i_keyint_min / 4 )
900         f_bias = f_thresh_min / 4;
901     else if( i_gop_size <= h->param.i_keyint_min )
902         f_bias = f_thresh_min * i_gop_size / h->param.i_keyint_min;
903     else
904     {
905         f_bias = f_thresh_min
906                  + ( f_thresh_max - f_thresh_min )
907                     * ( i_gop_size - h->param.i_keyint_min )
908                    / ( h->param.i_keyint_max - h->param.i_keyint_min ) ;
909     }
910
911     res = pcost >= (1.0 - f_bias) * icost;
912     if( res && print )
913     {
914         int imb = frame->i_intra_mbs[p1-p0];
915         int pmb = NUM_MBS - imb;
916         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",
917                   frame->i_frame,
918                   icost, pcost, 1. - (double)pcost / icost,
919                   f_bias, i_gop_size, imb, pmb );
920     }
921     return res;
922 }
923
924 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 )
925 {
926     int curp0, curp1, i, maxp1 = p0 + 1;
927
928     /* Only do analysis during a normal scenecut check. */
929     if( real_scenecut && h->param.i_bframe )
930     {
931         /* Look ahead to avoid coding short flashes as scenecuts. */
932         if( h->param.i_bframe_adaptive == X264_B_ADAPT_TRELLIS )
933             /* Don't analyse any more frames than the trellis would have covered. */
934             maxp1 += h->param.i_bframe;
935         else
936             maxp1++;
937         maxp1 = X264_MIN( maxp1, num_frames );
938
939         /* Where A and B are scenes: AAAAAABBBAAAAAA
940          * If BBB is shorter than (maxp1-p0), it is detected as a flash
941          * and not considered a scenecut. */
942         for( curp1 = p1; curp1 <= maxp1; curp1++ )
943             if( !scenecut_internal( h, a, frames, p0, curp1, 0 ) )
944                 /* Any frame in between p0 and cur_p1 cannot be a real scenecut. */
945                 for( i = curp1; i > p0; i-- )
946                     frames[i]->b_scenecut = 0;
947
948         /* Where A-F are scenes: AAAAABBCCDDEEFFFFFF
949          * If each of BB ... EE are shorter than (maxp1-p0), they are
950          * detected as flashes and not considered scenecuts.
951          * Instead, the first F frame becomes a scenecut. */
952         for( curp0 = p0; curp0 < maxp1; curp0++ )
953             if( scenecut_internal( h, a, frames, curp0, maxp1, 0 ) )
954                 /* If cur_p0 is the p0 of a scenecut, it cannot be the p1 of a scenecut. */
955                     frames[curp0]->b_scenecut = 0;
956     }
957
958     /* Ignore frames that are part of a flash, i.e. cannot be real scenecuts. */
959     if( !frames[p1]->b_scenecut )
960         return 0;
961     return scenecut_internal( h, a, frames, p0, p1, real_scenecut );
962 }
963
964 void x264_slicetype_analyse( x264_t *h, int keyframe )
965 {
966     x264_mb_analysis_t a;
967     x264_frame_t *frames[X264_LOOKAHEAD_MAX+3] = { NULL, };
968     int num_frames, orig_num_frames, keyint_limit, idr_frame_type, i, j;
969     int i_mb_count = NUM_MBS;
970     int cost1p0, cost2p0, cost1b1, cost2p1;
971     int i_max_search = X264_MIN( h->lookahead->next.i_size, X264_LOOKAHEAD_MAX );
972     if( h->param.b_deterministic )
973         i_max_search = X264_MIN( i_max_search, h->lookahead->i_slicetype_length + !keyframe );
974
975     assert( h->frames.b_have_lowres );
976
977     if( !h->lookahead->last_nonb )
978         return;
979     frames[0] = h->lookahead->last_nonb;
980     for( j = 0; j < i_max_search && h->lookahead->next.list[j]->i_type == X264_TYPE_AUTO; j++ )
981         frames[j+1] = h->lookahead->next.list[j];
982
983     if( !j )
984         return;
985
986     keyint_limit = h->param.i_keyint_max - frames[0]->i_frame + h->lookahead->i_last_idr - 1;
987     orig_num_frames = num_frames = X264_MIN( j, keyint_limit );
988
989     x264_lowres_context_init( h, &a );
990     idr_frame_type = frames[1]->i_frame - h->lookahead->i_last_idr >= h->param.i_keyint_min ? X264_TYPE_IDR : X264_TYPE_I;
991
992     /* This is important psy-wise: if we have a non-scenecut keyframe,
993      * there will be significant visual artifacts if the frames just before
994      * go down in quality due to being referenced less, despite it being
995      * more RD-optimal. */
996     if( (h->param.analyse.b_psy && h->param.rc.b_mb_tree) || h->param.rc.i_vbv_buffer_size )
997         num_frames = j;
998     else if( num_frames == 1 )
999     {
1000         frames[1]->i_type = X264_TYPE_P;
1001         if( h->param.i_scenecut_threshold && scenecut( h, &a, frames, 0, 1, 1, orig_num_frames ) )
1002             frames[1]->i_type = idr_frame_type;
1003         return;
1004     }
1005     else if( num_frames == 0 )
1006     {
1007         frames[1]->i_type = idr_frame_type;
1008         return;
1009     }
1010
1011     int num_bframes = 0;
1012     int max_bframes = X264_MIN(num_frames-1, h->param.i_bframe);
1013     int num_analysed_frames = num_frames;
1014     int reset_start;
1015     if( h->param.i_scenecut_threshold && scenecut( h, &a, frames, 0, 1, 1, orig_num_frames ) )
1016     {
1017         frames[1]->i_type = idr_frame_type;
1018         return;
1019     }
1020
1021     if( h->param.i_bframe )
1022     {
1023         if( h->param.i_bframe_adaptive == X264_B_ADAPT_TRELLIS )
1024         {
1025             char best_paths[X264_BFRAME_MAX+1][X264_LOOKAHEAD_MAX] = {"","P"};
1026             int n;
1027
1028             /* Perform the frametype analysis. */
1029             for( n = 2; n < num_frames; n++ )
1030                 x264_slicetype_path( h, &a, frames, n, max_bframes, best_paths );
1031             if( num_frames > 1 )
1032             {
1033                 int best_path_index = (num_frames-1) % (X264_BFRAME_MAX+1);
1034                 num_bframes = strspn( best_paths[best_path_index], "B" );
1035                 /* Load the results of the analysis into the frame types. */
1036                 for( j = 1; j < num_frames; j++ )
1037                     frames[j]->i_type = best_paths[best_path_index][j-1] == 'B' ? X264_TYPE_B : X264_TYPE_P;
1038             }
1039             frames[num_frames]->i_type = X264_TYPE_P;
1040         }
1041         else if( h->param.i_bframe_adaptive == X264_B_ADAPT_FAST )
1042         {
1043             for( i = 0; i <= num_frames-2; )
1044             {
1045                 cost2p1 = x264_slicetype_frame_cost( h, &a, frames, i+0, i+2, i+2, 1 );
1046                 if( frames[i+2]->i_intra_mbs[2] > i_mb_count / 2 )
1047                 {
1048                     frames[i+1]->i_type = X264_TYPE_P;
1049                     frames[i+2]->i_type = X264_TYPE_P;
1050                     i += 2;
1051                     continue;
1052                 }
1053
1054                 cost1b1 = x264_slicetype_frame_cost( h, &a, frames, i+0, i+2, i+1, 0 );
1055                 cost1p0 = x264_slicetype_frame_cost( h, &a, frames, i+0, i+1, i+1, 0 );
1056                 cost2p0 = x264_slicetype_frame_cost( h, &a, frames, i+1, i+2, i+2, 0 );
1057
1058                 if( cost1p0 + cost2p0 < cost1b1 + cost2p1 )
1059                 {
1060                     frames[i+1]->i_type = X264_TYPE_P;
1061                     i += 1;
1062                     continue;
1063                 }
1064
1065                 // arbitrary and untuned
1066                 #define INTER_THRESH 300
1067                 #define P_SENS_BIAS (50 - h->param.i_bframe_bias)
1068                 frames[i+1]->i_type = X264_TYPE_B;
1069
1070                 for( j = i+2; j <= X264_MIN( i+h->param.i_bframe, num_frames-1 ); j++ )
1071                 {
1072                     int pthresh = X264_MAX(INTER_THRESH - P_SENS_BIAS * (j-i-1), INTER_THRESH/10);
1073                     int pcost = x264_slicetype_frame_cost( h, &a, frames, i+0, j+1, j+1, 1 );
1074                     if( pcost > pthresh*i_mb_count || frames[j+1]->i_intra_mbs[j-i+1] > i_mb_count/3 )
1075                         break;
1076                     frames[j]->i_type = X264_TYPE_B;
1077                 }
1078                 frames[j]->i_type = X264_TYPE_P;
1079                 i = j;
1080             }
1081             frames[num_frames]->i_type = X264_TYPE_P;
1082             num_bframes = 0;
1083             while( num_bframes < num_frames && frames[num_bframes+1]->i_type == X264_TYPE_B )
1084                 num_bframes++;
1085         }
1086         else
1087         {
1088             num_bframes = X264_MIN(num_frames-1, h->param.i_bframe);
1089             for( j = 1; j < num_frames; j++ )
1090                 frames[j]->i_type = (j%(num_bframes+1)) ? X264_TYPE_B : X264_TYPE_P;
1091             frames[num_frames]->i_type = X264_TYPE_P;
1092         }
1093
1094         /* Check scenecut on the first minigop. */
1095         for( j = 1; j < num_bframes+1; j++ )
1096             if( h->param.i_scenecut_threshold && scenecut( h, &a, frames, j, j+1, 0, orig_num_frames ) )
1097             {
1098                 frames[j]->i_type = X264_TYPE_P;
1099                 num_analysed_frames = j;
1100                 break;
1101             }
1102
1103         reset_start = keyframe ? 1 : X264_MIN( num_bframes+2, num_analysed_frames+1 );
1104     }
1105     else
1106     {
1107         for( j = 1; j <= num_frames; j++ )
1108             frames[j]->i_type = X264_TYPE_P;
1109         reset_start = !keyframe + 1;
1110         num_bframes = 0;
1111     }
1112
1113     /* Perform the actual macroblock tree analysis.
1114      * Don't go farther than the maximum keyframe interval; this helps in short GOPs. */
1115     if( h->param.rc.b_mb_tree )
1116         x264_macroblock_tree( h, &a, frames, X264_MIN(num_frames, h->param.i_keyint_max), keyframe );
1117
1118     /* Enforce keyframe limit. */
1119     for( j = 0; j < num_frames; j++ )
1120     {
1121         if( ((j-keyint_limit) % h->param.i_keyint_max) == 0 )
1122         {
1123             if( j && h->param.i_keyint_max > 1 )
1124                 frames[j]->i_type = X264_TYPE_P;
1125             frames[j+1]->i_type = X264_TYPE_IDR;
1126             reset_start = X264_MIN( reset_start, j+2 );
1127         }
1128     }
1129
1130     if( h->param.rc.i_vbv_buffer_size )
1131         x264_vbv_lookahead( h, &a, frames, num_frames, keyframe );
1132
1133     /* Restore frametypes for all frames that haven't actually been decided yet. */
1134     for( j = reset_start; j <= num_frames; j++ )
1135         frames[j]->i_type = X264_TYPE_AUTO;
1136 }
1137
1138 void x264_slicetype_decide( x264_t *h )
1139 {
1140     x264_frame_t *frames[X264_BFRAME_MAX+2];
1141     x264_frame_t *frm;
1142     int bframes;
1143     int brefs;
1144     int i;
1145
1146     if( !h->lookahead->next.i_size )
1147         return;
1148
1149     if( h->param.rc.b_stat_read )
1150     {
1151         /* Use the frame types from the first pass */
1152         for( i = 0; i < h->lookahead->next.i_size; i++ )
1153             h->lookahead->next.list[i]->i_type =
1154                 x264_ratecontrol_slice_type( h, h->lookahead->next.list[i]->i_frame );
1155     }
1156     else if( (h->param.i_bframe && h->param.i_bframe_adaptive)
1157              || h->param.i_scenecut_threshold
1158              || h->param.rc.b_mb_tree
1159              || (h->param.rc.i_vbv_buffer_size && h->param.rc.i_lookahead) )
1160         x264_slicetype_analyse( h, 0 );
1161
1162     for( bframes = 0, brefs = 0;; bframes++ )
1163     {
1164         frm = h->lookahead->next.list[bframes];
1165         if( frm->i_type == X264_TYPE_BREF && h->param.i_bframe_pyramid < X264_B_PYRAMID_NORMAL &&
1166             brefs == h->param.i_bframe_pyramid )
1167         {
1168             frm->i_type = X264_TYPE_B;
1169             x264_log( h, X264_LOG_WARNING, "B-ref at frame %d incompatible with B-pyramid %s \n",
1170                       frm->i_frame, x264_b_pyramid_names[h->param.i_bframe_pyramid] );
1171         }
1172         /* pyramid with multiple B-refs needs a big enough dpb that the preceding P-frame stays available.
1173            smaller dpb could be supported by smart enough use of mmco, but it's easier just to forbid it. */
1174         else if( frm->i_type == X264_TYPE_BREF && h->param.i_bframe_pyramid == X264_B_PYRAMID_NORMAL &&
1175             brefs && h->param.i_frame_reference <= (brefs+3) )
1176         {
1177             frm->i_type = X264_TYPE_B;
1178             x264_log( h, X264_LOG_WARNING, "B-ref at frame %d incompatible with B-pyramid %s and %d reference frames\n",
1179                       frm->i_frame, x264_b_pyramid_names[h->param.i_bframe_pyramid], h->param.i_frame_reference );
1180         }
1181
1182         /* Limit GOP size */
1183         if( frm->i_frame - h->lookahead->i_last_idr >= h->param.i_keyint_max )
1184         {
1185             if( frm->i_type == X264_TYPE_AUTO )
1186                 frm->i_type = X264_TYPE_IDR;
1187             if( frm->i_type != X264_TYPE_IDR )
1188                 x264_log( h, X264_LOG_WARNING, "specified frame type (%d) is not compatible with keyframe interval\n", frm->i_type );
1189         }
1190         if( frm->i_type == X264_TYPE_IDR )
1191         {
1192             /* Close GOP */
1193             h->lookahead->i_last_idr = frm->i_frame;
1194             if( bframes > 0 )
1195             {
1196                 bframes--;
1197                 h->lookahead->next.list[bframes]->i_type = X264_TYPE_P;
1198             }
1199         }
1200
1201         if( bframes == h->param.i_bframe ||
1202             !h->lookahead->next.list[bframes+1] )
1203         {
1204             if( IS_X264_TYPE_B( frm->i_type ) )
1205                 x264_log( h, X264_LOG_WARNING, "specified frame type is not compatible with max B-frames\n" );
1206             if( frm->i_type == X264_TYPE_AUTO
1207                 || IS_X264_TYPE_B( frm->i_type ) )
1208                 frm->i_type = X264_TYPE_P;
1209         }
1210
1211         if( frm->i_type == X264_TYPE_BREF )
1212             brefs++;
1213
1214         if( frm->i_type == X264_TYPE_AUTO )
1215             frm->i_type = X264_TYPE_B;
1216
1217         else if( !IS_X264_TYPE_B( frm->i_type ) ) break;
1218     }
1219
1220     if( bframes )
1221         h->lookahead->next.list[bframes-1]->b_last_minigop_bframe = 1;
1222     h->lookahead->next.list[bframes]->i_bframes = bframes;
1223
1224     /* insert a bref into the sequence */
1225     if( h->param.i_bframe_pyramid && bframes > 1 && !brefs )
1226     {
1227         h->lookahead->next.list[bframes/2]->i_type = X264_TYPE_BREF;
1228         brefs++;
1229     }
1230
1231     /* calculate the frame costs ahead of time for x264_rc_analyse_slice while we still have lowres */
1232     if( h->param.rc.i_rc_method != X264_RC_CQP )
1233     {
1234         x264_mb_analysis_t a;
1235         int p0, p1, b;
1236         p1 = b = bframes + 1;
1237
1238         x264_lowres_context_init( h, &a );
1239
1240         frames[0] = h->lookahead->last_nonb;
1241         memcpy( &frames[1], h->lookahead->next.list, (bframes+1) * sizeof(x264_frame_t*) );
1242         if( IS_X264_TYPE_I( h->lookahead->next.list[bframes]->i_type ) )
1243             p0 = bframes + 1;
1244         else // P
1245             p0 = 0;
1246
1247         x264_slicetype_frame_cost( h, &a, frames, p0, p1, b, 0 );
1248
1249         if( (p0 != p1 || bframes) && h->param.rc.i_vbv_buffer_size )
1250         {
1251             /* We need the intra costs for row SATDs. */
1252             x264_slicetype_frame_cost( h, &a, frames, b, b, b, 0 );
1253
1254             /* We need B-frame costs for row SATDs. */
1255             p0 = 0;
1256             for( b = 1; b <= bframes; b++ )
1257             {
1258                 if( frames[b]->i_type == X264_TYPE_B )
1259                     for( p1 = b; frames[p1]->i_type == X264_TYPE_B; )
1260                         p1++;
1261                 else
1262                     p1 = bframes + 1;
1263                 x264_slicetype_frame_cost( h, &a, frames, p0, p1, b, 0 );
1264                 if( frames[b]->i_type == X264_TYPE_BREF )
1265                     p0 = b;
1266             }
1267         }
1268     }
1269
1270     /* Analyse for weighted P frames */
1271     if( h->lookahead->next.list[bframes]->i_type == X264_TYPE_P )
1272     {
1273         memset( h->lookahead->next.list[bframes]->weight, 0, sizeof(h->lookahead->next.list[bframes]->weight) );
1274         if( h->param.analyse.i_weighted_pred == X264_WEIGHTP_SMART && h->param.i_threads > 1 )
1275             x264_weights_analyse( h, h->lookahead->next.list[bframes], h->lookahead->last_nonb, 1, 0 );
1276     }
1277
1278     /* shift sequence to coded order.
1279        use a small temporary list to avoid shifting the entire next buffer around */
1280     int i_dts = h->lookahead->next.list[0]->i_frame;
1281     if( bframes )
1282     {
1283         int index[] = { brefs+1, 1 };
1284         for( i = 0; i < bframes; i++ )
1285             frames[ index[h->lookahead->next.list[i]->i_type == X264_TYPE_BREF]++ ] = h->lookahead->next.list[i];
1286         frames[0] = h->lookahead->next.list[bframes];
1287         memcpy( h->lookahead->next.list, frames, (bframes+1) * sizeof(x264_frame_t*) );
1288     }
1289     for( i = 0; i <= bframes; i++ )
1290          h->lookahead->next.list[i]->i_dts = i_dts++;
1291 }
1292
1293 int x264_rc_analyse_slice( x264_t *h )
1294 {
1295     int p0=0, p1, b;
1296     int cost;
1297
1298     if( IS_X264_TYPE_I(h->fenc->i_type) )
1299         p1 = b = 0;
1300     else if( h->fenc->i_type == X264_TYPE_P )
1301         p1 = b = h->fenc->i_bframes + 1;
1302     else //B
1303     {
1304         p1 = (h->fref1[0]->i_poc - h->fref0[0]->i_poc)/2;
1305         b  = (h->fenc->i_poc - h->fref0[0]->i_poc)/2;
1306     }
1307     /* We don't need to assign p0/p1 since we are not performing any real analysis here. */
1308     x264_frame_t **frames = &h->fenc - b;
1309
1310     /* cost should have been already calculated by x264_slicetype_decide */
1311     cost = frames[b]->i_cost_est[b-p0][p1-b];
1312     assert( cost >= 0 );
1313
1314     if( h->param.rc.b_mb_tree && !h->param.rc.b_stat_read )
1315     {
1316         cost = x264_slicetype_frame_cost_recalculate( h, frames, p0, p1, b );
1317         if( b && h->param.rc.i_vbv_buffer_size )
1318             x264_slicetype_frame_cost_recalculate( h, frames, b, b, b );
1319     }
1320     /* In AQ, use the weighted score instead. */
1321     else if( h->param.rc.i_aq_mode )
1322         cost = frames[b]->i_cost_est_aq[b-p0][p1-b];
1323
1324     h->fenc->i_row_satd = h->fenc->i_row_satds[b-p0][p1-b];
1325     h->fdec->i_row_satd = h->fdec->i_row_satds[b-p0][p1-b];
1326     h->fdec->i_satd = cost;
1327     memcpy( h->fdec->i_row_satd, h->fenc->i_row_satd, h->sps->i_mb_height * sizeof(int) );
1328     if( !IS_X264_TYPE_I(h->fenc->i_type) )
1329         memcpy( h->fdec->i_row_satds[0][0], h->fenc->i_row_satds[0][0], h->sps->i_mb_height * sizeof(int) );
1330     return cost;
1331 }