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