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