]> git.sesse.net Git - x264/blob - encoder/slicetype.c
c1040a6dcd58ee4fb11eddb5baf789eb1eab6d09
[x264] / encoder / slicetype.c
1 /*****************************************************************************
2  * slicetype.c: h264 encoder library
3  *****************************************************************************
4  * Copyright (C) 2005-2008 x264 project
5  *
6  * Authors: Loren Merritt <lorenm@u.washington.edu>
7  *          Fiona Glaser <fiona@x264.com>
8  *
9  * This program is free software; you can redistribute it and/or modify
10  * it under the terms of the GNU General Public License as published by
11  * the Free Software Foundation; either version 2 of the License, or
12  * (at your option) any later version.
13  *
14  * This program is distributed in the hope that it will be useful,
15  * but WITHOUT ANY WARRANTY; without even the implied warranty of
16  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
17  * GNU General Public License for more details.
18  *
19  * You should have received a copy of the GNU General Public License
20  * along with this program; if not, write to the Free Software
21  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02111, USA.
22  *****************************************************************************/
23
24 #include <math.h>
25
26 #include "common/common.h"
27 #include "common/cpu.h"
28 #include "macroblock.h"
29 #include "me.h"
30
31
32 static void x264_lowres_context_init( x264_t *h, x264_mb_analysis_t *a )
33 {
34     a->i_qp = X264_LOOKAHEAD_QP;
35     a->i_lambda = x264_lambda_tab[ a->i_qp ];
36     x264_mb_analyse_load_costs( h, a );
37     h->mb.i_me_method = X264_MIN( X264_ME_HEX, h->param.analyse.i_me_method ); // maybe dia?
38     h->mb.i_subpel_refine = 4; // 3 should be enough, but not tweaking for speed now
39     h->mb.b_chroma_me = 0;
40 }
41
42 static int x264_slicetype_mb_cost( x264_t *h, x264_mb_analysis_t *a,
43                             x264_frame_t **frames, int p0, int p1, int b,
44                             int dist_scale_factor, int do_search[2] )
45 {
46     x264_frame_t *fref0 = frames[p0];
47     x264_frame_t *fref1 = frames[p1];
48     x264_frame_t *fenc  = frames[b];
49     const int b_bidir = (b < p1);
50     const int i_mb_x = h->mb.i_mb_x;
51     const int i_mb_y = h->mb.i_mb_y;
52     const int i_mb_stride = h->sps->i_mb_width;
53     const int i_mb_xy = i_mb_x + i_mb_y * i_mb_stride;
54     const int i_stride = fenc->i_stride_lowres;
55     const int i_pel_offset = 8 * ( i_mb_x + i_mb_y * i_stride );
56     const int i_bipred_weight = h->param.analyse.b_weighted_bipred ? 64 - (dist_scale_factor>>2) : 32;
57     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] };
58     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] };
59
60     ALIGNED_8( uint8_t pix1[9*FDEC_STRIDE] );
61     uint8_t *pix2 = pix1+8;
62     x264_me_t m[2];
63     int i_bcost = COST_MAX;
64     int l, i;
65     int list_used = 0;
66
67     h->mb.pic.p_fenc[0] = h->mb.pic.fenc_buf;
68     h->mc.copy[PIXEL_8x8]( h->mb.pic.p_fenc[0], FENC_STRIDE, &fenc->lowres[0][i_pel_offset], i_stride, 8 );
69
70     if( p0 == p1 )
71         goto lowres_intra_mb;
72
73     // no need for h->mb.mv_min[]
74     h->mb.mv_min_fpel[0] = -8*h->mb.i_mb_x - 4;
75     h->mb.mv_max_fpel[0] = 8*( h->sps->i_mb_width - h->mb.i_mb_x - 1 ) + 4;
76     h->mb.mv_min_spel[0] = 4*( h->mb.mv_min_fpel[0] - 8 );
77     h->mb.mv_max_spel[0] = 4*( h->mb.mv_max_fpel[0] + 8 );
78     if( h->mb.i_mb_x >= h->sps->i_mb_width - 2 )
79     {
80         h->mb.mv_min_fpel[1] = -8*h->mb.i_mb_y - 4;
81         h->mb.mv_max_fpel[1] = 8*( h->sps->i_mb_height - h->mb.i_mb_y - 1 ) + 4;
82         h->mb.mv_min_spel[1] = 4*( h->mb.mv_min_fpel[1] - 8 );
83         h->mb.mv_max_spel[1] = 4*( h->mb.mv_max_fpel[1] + 8 );
84     }
85
86 #define LOAD_HPELS_LUMA(dst, src) \
87     { \
88         (dst)[0] = &(src)[0][i_pel_offset]; \
89         (dst)[1] = &(src)[1][i_pel_offset]; \
90         (dst)[2] = &(src)[2][i_pel_offset]; \
91         (dst)[3] = &(src)[3][i_pel_offset]; \
92     }
93 #define CLIP_MV( mv ) \
94     { \
95         mv[0] = x264_clip3( mv[0], h->mb.mv_min_spel[0], h->mb.mv_max_spel[0] ); \
96         mv[1] = x264_clip3( mv[1], h->mb.mv_min_spel[1], h->mb.mv_max_spel[1] ); \
97     }
98 #define TRY_BIDIR( mv0, mv1, penalty ) \
99     { \
100         int stride1 = 16, stride2 = 16; \
101         uint8_t *src1, *src2; \
102         int i_cost; \
103         src1 = h->mc.get_ref( pix1, &stride1, m[0].p_fref, m[0].i_stride[0], \
104                               (mv0)[0], (mv0)[1], 8, 8 ); \
105         src2 = h->mc.get_ref( pix2, &stride2, m[1].p_fref, m[1].i_stride[0], \
106                               (mv1)[0], (mv1)[1], 8, 8 ); \
107         h->mc.avg[PIXEL_8x8]( pix1, 16, src1, stride1, src2, stride2, i_bipred_weight ); \
108         i_cost = penalty + h->pixf.mbcmp[PIXEL_8x8]( \
109                            m[0].p_fenc[0], FENC_STRIDE, pix1, 16 ); \
110         COPY2_IF_LT( i_bcost, i_cost, list_used, 3 ); \
111     }
112
113     m[0].i_pixel = PIXEL_8x8;
114     m[0].p_cost_mv = a->p_cost_mv;
115     m[0].i_stride[0] = i_stride;
116     m[0].p_fenc[0] = h->mb.pic.p_fenc[0];
117     LOAD_HPELS_LUMA( m[0].p_fref, fref0->lowres );
118
119     if( b_bidir )
120     {
121         int16_t *mvr = fref1->lowres_mvs[0][p1-p0-1][i_mb_xy];
122         int dmv[2][2];
123
124         h->mc.memcpy_aligned( &m[1], &m[0], sizeof(x264_me_t) );
125         LOAD_HPELS_LUMA( m[1].p_fref, fref1->lowres );
126
127         dmv[0][0] = ( mvr[0] * dist_scale_factor + 128 ) >> 8;
128         dmv[0][1] = ( mvr[1] * dist_scale_factor + 128 ) >> 8;
129         dmv[1][0] = dmv[0][0] - mvr[0];
130         dmv[1][1] = dmv[0][1] - mvr[1];
131         CLIP_MV( dmv[0] );
132         CLIP_MV( dmv[1] );
133
134         TRY_BIDIR( dmv[0], dmv[1], 0 );
135         if( dmv[0][0] | dmv[0][1] | dmv[1][0] | dmv[1][1] )
136         {
137             int i_cost;
138             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 );
139             i_cost = h->pixf.mbcmp[PIXEL_8x8]( m[0].p_fenc[0], FENC_STRIDE, pix1, 16 );
140             COPY2_IF_LT( i_bcost, i_cost, list_used, 3 );
141         }
142     }
143
144     for( l = 0; l < 1 + b_bidir; l++ )
145     {
146         if( do_search[l] )
147         {
148             int i_mvc = 0;
149             int16_t (*fenc_mv)[2] = fenc_mvs[l];
150             ALIGNED_4( int16_t mvc[4][2] );
151
152             /* Reverse-order MV prediction. */
153             *(uint32_t*)mvc[0] = 0;
154             *(uint32_t*)mvc[1] = 0;
155             *(uint32_t*)mvc[2] = 0;
156 #define MVC(mv) { *(uint32_t*)mvc[i_mvc] = *(uint32_t*)mv; i_mvc++; }
157             if( i_mb_x < h->sps->i_mb_width - 1 )
158                 MVC(fenc_mv[1]);
159             if( i_mb_y < h->sps->i_mb_height - 1 )
160             {
161                 MVC(fenc_mv[i_mb_stride]);
162                 if( i_mb_x > 0 )
163                     MVC(fenc_mv[i_mb_stride-1]);
164                 if( i_mb_x < h->sps->i_mb_width - 1 )
165                     MVC(fenc_mv[i_mb_stride+1]);
166             }
167 #undef MVC
168             x264_median_mv( m[l].mvp, mvc[0], mvc[1], mvc[2] );
169             x264_me_search( h, &m[l], mvc, i_mvc );
170
171             m[l].cost -= 2; // remove mvcost from skip mbs
172             if( *(uint32_t*)m[l].mv )
173                 m[l].cost += 5;
174             *(uint32_t*)fenc_mvs[l] = *(uint32_t*)m[l].mv;
175             *fenc_costs[l] = m[l].cost;
176         }
177         else
178         {
179             *(uint32_t*)m[l].mv = *(uint32_t*)fenc_mvs[l];
180             m[l].cost = *fenc_costs[l];
181         }
182         COPY2_IF_LT( i_bcost, m[l].cost, list_used, l+1 );
183     }
184
185     if( b_bidir && ( *(uint32_t*)m[0].mv || *(uint32_t*)m[1].mv ) )
186         TRY_BIDIR( m[0].mv, m[1].mv, 5 );
187
188     /* Store to width-2 bitfield. */
189     frames[b]->lowres_inter_types[b-p0][p1-b][i_mb_xy>>2] &= ~(3<<((i_mb_xy&3)*2));
190     frames[b]->lowres_inter_types[b-p0][p1-b][i_mb_xy>>2] |= list_used<<((i_mb_xy&3)*2);
191
192 lowres_intra_mb:
193     /* forbid intra-mbs in B-frames, because it's rare and not worth checking */
194     /* FIXME: Should we still forbid them now that we cache intra scores? */
195     if( !b_bidir || h->param.rc.b_mb_tree )
196     {
197         int i_icost, b_intra;
198         if( !fenc->b_intra_calculated )
199         {
200             ALIGNED_ARRAY_16( uint8_t, edge,[33] );
201             uint8_t *pix = &pix1[8+FDEC_STRIDE - 1];
202             uint8_t *src = &fenc->lowres[0][i_pel_offset - 1];
203             const int intra_penalty = 5;
204             int satds[4];
205
206             memcpy( pix-FDEC_STRIDE, src-i_stride, 17 );
207             for( i=0; i<8; i++ )
208                 pix[i*FDEC_STRIDE] = src[i*i_stride];
209             pix++;
210
211             if( h->pixf.intra_mbcmp_x3_8x8c )
212             {
213                 h->pixf.intra_mbcmp_x3_8x8c( h->mb.pic.p_fenc[0], pix, satds );
214                 h->predict_8x8c[I_PRED_CHROMA_P]( pix );
215                 satds[I_PRED_CHROMA_P] =
216                     h->pixf.mbcmp[PIXEL_8x8]( pix, FDEC_STRIDE, h->mb.pic.p_fenc[0], FENC_STRIDE );
217             }
218             else
219             {
220                 for( i=0; i<4; i++ )
221                 {
222                     h->predict_8x8c[i]( pix );
223                     satds[i] = h->pixf.mbcmp[PIXEL_8x8]( pix, FDEC_STRIDE, h->mb.pic.p_fenc[0], FENC_STRIDE );
224                 }
225             }
226             i_icost = X264_MIN4( satds[0], satds[1], satds[2], satds[3] );
227
228             h->predict_8x8_filter( pix, edge, ALL_NEIGHBORS, ALL_NEIGHBORS );
229             for( i=3; i<9; i++ )
230             {
231                 int satd;
232                 h->predict_8x8[i]( pix, edge );
233                 satd = h->pixf.mbcmp[PIXEL_8x8]( pix, FDEC_STRIDE, h->mb.pic.p_fenc[0], FENC_STRIDE );
234                 i_icost = X264_MIN( i_icost, satd );
235             }
236
237             i_icost += intra_penalty;
238             fenc->i_intra_cost[i_mb_xy] = i_icost;
239         }
240         else
241             i_icost = fenc->i_intra_cost[i_mb_xy];
242         if( !b_bidir )
243         {
244             b_intra = i_icost < i_bcost;
245             if( b_intra )
246                 i_bcost = i_icost;
247             if(   (i_mb_x > 0 && i_mb_x < h->sps->i_mb_width - 1
248                 && i_mb_y > 0 && i_mb_y < h->sps->i_mb_height - 1)
249                 || h->sps->i_mb_width <= 2 || h->sps->i_mb_height <= 2 )
250             {
251                 fenc->i_intra_mbs[b-p0] += b_intra;
252                 fenc->i_cost_est[0][0] += i_icost;
253                 if( h->param.rc.i_aq_mode )
254                     fenc->i_cost_est_aq[0][0] += (i_icost * fenc->i_inv_qscale_factor[i_mb_xy] + 128) >> 8;
255             }
256         }
257     }
258
259     fenc->lowres_costs[b-p0][p1-b][i_mb_xy] = i_bcost;
260
261     return i_bcost;
262 }
263 #undef TRY_BIDIR
264
265 #define NUM_MBS\
266    (h->sps->i_mb_width > 2 && h->sps->i_mb_height > 2 ?\
267    (h->sps->i_mb_width - 2) * (h->sps->i_mb_height - 2) :\
268     h->sps->i_mb_width * h->sps->i_mb_height)
269
270 static int x264_slicetype_frame_cost( x264_t *h, x264_mb_analysis_t *a,
271                                x264_frame_t **frames, int p0, int p1, int b,
272                                int b_intra_penalty )
273 {
274
275     int i_score = 0;
276     /* Don't use the AQ'd scores for slicetype decision. */
277     int i_score_aq = 0;
278     int do_search[2];
279
280     /* Check whether we already evaluated this frame
281      * If we have tried this frame as P, then we have also tried
282      * the preceding frames as B. (is this still true?) */
283     /* Also check that we already calculated the row SATDs for the current frame. */
284     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) )
285     {
286         i_score = frames[b]->i_cost_est[b-p0][p1-b];
287     }
288     else
289     {
290         int dist_scale_factor = 128;
291         int *row_satd = frames[b]->i_row_satds[b-p0][p1-b];
292
293         /* For each list, check to see whether we have lowres motion-searched this reference frame before. */
294         do_search[0] = b != p0 && frames[b]->lowres_mvs[0][b-p0-1][0][0] == 0x7FFF;
295         do_search[1] = b != p1 && frames[b]->lowres_mvs[1][p1-b-1][0][0] == 0x7FFF;
296         if( do_search[0] ) frames[b]->lowres_mvs[0][b-p0-1][0][0] = 0;
297         if( do_search[1] ) frames[b]->lowres_mvs[1][p1-b-1][0][0] = 0;
298
299         if( b == p1 )
300         {
301             frames[b]->i_intra_mbs[b-p0] = 0;
302             frames[b]->i_cost_est[0][0] = 0;
303             frames[b]->i_cost_est_aq[0][0] = 0;
304         }
305         if( p1 != p0 )
306             dist_scale_factor = ( ((b-p0) << 8) + ((p1-p0) >> 1) ) / (p1-p0);
307
308         /* Lowres lookahead goes backwards because the MVs are used as predictors in the main encode.
309          * This considerably improves MV prediction overall. */
310
311         /* the edge mbs seem to reduce the predictive quality of the
312          * whole frame's score, but are needed for a spatial distribution. */
313         if( h->param.rc.b_mb_tree || h->param.rc.i_vbv_buffer_size ||
314             h->sps->i_mb_width <= 2 || h->sps->i_mb_height <= 2 )
315         {
316             for( h->mb.i_mb_y = h->sps->i_mb_height - 1; h->mb.i_mb_y >= 0; h->mb.i_mb_y-- )
317             {
318                 row_satd[ h->mb.i_mb_y ] = 0;
319                 for( h->mb.i_mb_x = h->sps->i_mb_width - 1; h->mb.i_mb_x >= 0; h->mb.i_mb_x-- )
320                 {
321                     int i_mb_cost = x264_slicetype_mb_cost( h, a, frames, p0, p1, b, dist_scale_factor, do_search );
322                     int i_mb_cost_aq = i_mb_cost;
323                     if( h->param.rc.i_aq_mode )
324                         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;
325                     row_satd[ h->mb.i_mb_y ] += i_mb_cost_aq;
326                     if( (h->mb.i_mb_y > 0 && h->mb.i_mb_y < h->sps->i_mb_height - 1 &&
327                          h->mb.i_mb_x > 0 && h->mb.i_mb_x < h->sps->i_mb_width - 1) ||
328                          h->sps->i_mb_width <= 2 || h->sps->i_mb_height <= 2 )
329                     {
330                         /* Don't use AQ-weighted costs for slicetype decision, only for ratecontrol. */
331                         i_score += i_mb_cost;
332                         i_score_aq += i_mb_cost_aq;
333                     }
334                 }
335             }
336         }
337         else
338         {
339             for( h->mb.i_mb_y = h->sps->i_mb_height - 2; h->mb.i_mb_y > 0; h->mb.i_mb_y-- )
340                 for( h->mb.i_mb_x = h->sps->i_mb_width - 2; h->mb.i_mb_x > 0; h->mb.i_mb_x-- )
341                 {
342                     int i_mb_cost = x264_slicetype_mb_cost( h, a, frames, p0, p1, b, dist_scale_factor, do_search );
343                     int i_mb_cost_aq = i_mb_cost;
344                     if( h->param.rc.i_aq_mode )
345                         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;
346                     i_score += i_mb_cost;
347                     i_score_aq += i_mb_cost_aq;
348                 }
349         }
350
351         if( b != p1 )
352             i_score = (uint64_t)i_score * 100 / (120 + h->param.i_bframe_bias);
353         else
354             frames[b]->b_intra_calculated = 1;
355
356         frames[b]->i_cost_est[b-p0][p1-b] = i_score;
357         frames[b]->i_cost_est_aq[b-p0][p1-b] = i_score_aq;
358         x264_emms();
359     }
360
361     if( b_intra_penalty )
362     {
363         // arbitrary penalty for I-blocks after B-frames
364         int nmb = NUM_MBS;
365         i_score += i_score * frames[b]->i_intra_mbs[b-p0] / (nmb * 8);
366     }
367     return i_score;
368 }
369
370 /* If MB-tree changes the quantizers, we need to recalculate the frame cost without
371  * re-running lookahead. */
372 static int x264_slicetype_frame_cost_recalculate( x264_t *h, x264_frame_t **frames, int p0, int p1, int b )
373 {
374     int i_score = 0;
375     int *row_satd = frames[b]->i_row_satds[b-p0][p1-b];
376     float *qp_offset = IS_X264_TYPE_B(frames[b]->i_type) ? frames[b]->f_qp_offset_aq : frames[b]->f_qp_offset;
377     x264_emms();
378     for( h->mb.i_mb_y = h->sps->i_mb_height - 1; h->mb.i_mb_y >= 0; h->mb.i_mb_y-- )
379     {
380         row_satd[ h->mb.i_mb_y ] = 0;
381         for( h->mb.i_mb_x = h->sps->i_mb_width - 1; h->mb.i_mb_x >= 0; h->mb.i_mb_x-- )
382         {
383             int i_mb_xy = h->mb.i_mb_x + h->mb.i_mb_y*h->mb.i_mb_stride;
384             int i_mb_cost = frames[b]->lowres_costs[b-p0][p1-b][i_mb_xy];
385             float qp_adj = qp_offset[i_mb_xy];
386             i_mb_cost = (i_mb_cost * x264_exp2fix8(qp_adj) + 128) >> 8;
387             row_satd[ h->mb.i_mb_y ] += i_mb_cost;
388             if( (h->mb.i_mb_y > 0 && h->mb.i_mb_y < h->sps->i_mb_height - 1 &&
389                  h->mb.i_mb_x > 0 && h->mb.i_mb_x < h->sps->i_mb_width - 1) ||
390                  h->sps->i_mb_width <= 2 || h->sps->i_mb_height <= 2 )
391             {
392                 i_score += i_mb_cost;
393             }
394         }
395     }
396     return i_score;
397 }
398
399 static void x264_macroblock_tree_finish( x264_t *h, x264_frame_t *frame )
400 {
401     int mb_index;
402     x264_emms();
403     /* Allow the strength to be adjusted via qcompress, since the two
404      * concepts are very similar. */
405     float strength = 5.0f * (1.0f - h->param.rc.f_qcompress);
406     for( mb_index = 0; mb_index < h->mb.i_mb_count; mb_index++ )
407     {
408         int intra_cost = (frame->i_intra_cost[mb_index] * frame->i_inv_qscale_factor[mb_index]+128)>>8;
409         if( intra_cost )
410         {
411             int propagate_cost = frame->i_propagate_cost[mb_index];
412             float log2_ratio = x264_log2(intra_cost + propagate_cost) - x264_log2(intra_cost);
413             frame->f_qp_offset[mb_index] = frame->f_qp_offset_aq[mb_index] - strength * log2_ratio;
414         }
415     }
416 }
417
418 static void x264_macroblock_tree_propagate( x264_t *h, x264_frame_t **frames, int p0, int p1, int b )
419 {
420     uint16_t *ref_costs[2] = {frames[p0]->i_propagate_cost,frames[p1]->i_propagate_cost};
421     int dist_scale_factor = ( ((b-p0) << 8) + ((p1-p0) >> 1) ) / (p1-p0);
422     int i_bipred_weight = h->param.analyse.b_weighted_bipred ? 64 - (dist_scale_factor>>2) : 32;
423     int16_t (*mvs[2])[2] = { frames[b]->lowres_mvs[0][b-p0-1], frames[b]->lowres_mvs[1][p1-b-1] };
424     int bipred_weights[2] = {i_bipred_weight, 64 - i_bipred_weight};
425     int *buf = h->scratch_buffer;
426
427     for( h->mb.i_mb_y = 0; h->mb.i_mb_y < h->sps->i_mb_height; h->mb.i_mb_y++ )
428     {
429         int mb_index = h->mb.i_mb_y*h->mb.i_mb_stride;
430         h->mc.mbtree_propagate_cost( buf, frames[b]->i_propagate_cost+mb_index,
431             frames[b]->i_intra_cost+mb_index, frames[b]->lowres_costs[b-p0][p1-b]+mb_index,
432             frames[b]->i_inv_qscale_factor+mb_index, h->sps->i_mb_width );
433         for( h->mb.i_mb_x = 0; h->mb.i_mb_x < h->sps->i_mb_width; h->mb.i_mb_x++, mb_index++ )
434         {
435             int propagate_amount = buf[h->mb.i_mb_x];
436             /* Don't propagate for an intra block. */
437             if( propagate_amount > 0 )
438             {
439                 /* Access width-2 bitfield. */
440                 int lists_used = (frames[b]->lowres_inter_types[b-p0][p1-b][mb_index>>2] >> ((mb_index&3)*2))&3;
441                 int list;
442                 /* Follow the MVs to the previous frame(s). */
443                 for( list = 0; list < 2; list++ )
444                     if( (lists_used >> list)&1 )
445                     {
446                         int x = mvs[list][mb_index][0];
447                         int y = mvs[list][mb_index][1];
448                         int listamount = propagate_amount;
449                         int mbx = (x>>5)+h->mb.i_mb_x;
450                         int mby = (y>>5)+h->mb.i_mb_y;
451                         int idx0 = mbx + mby*h->mb.i_mb_stride;
452                         int idx1 = idx0 + 1;
453                         int idx2 = idx0 + h->mb.i_mb_stride;
454                         int idx3 = idx0 + h->mb.i_mb_stride + 1;
455                         x &= 31;
456                         y &= 31;
457                         int idx0weight = (32-y)*(32-x);
458                         int idx1weight = (32-y)*x;
459                         int idx2weight = y*(32-x);
460                         int idx3weight = y*x;
461
462                         /* Apply bipred weighting. */
463                         if( lists_used == 3 )
464                             listamount = (listamount * bipred_weights[list] + 32) >> 6;
465
466 #define CLIP_ADD(s,x) (s) = X264_MIN((s)+(x),(1<<16)-1)
467
468                         /* We could just clip the MVs, but pixels that lie outside the frame probably shouldn't
469                          * be counted. */
470                         if( mbx < h->sps->i_mb_width-1 && mby < h->sps->i_mb_height-1 && mbx >= 0 && mby >= 0 )
471                         {
472                             CLIP_ADD( ref_costs[list][idx0], (listamount*idx0weight+512)>>10 );
473                             CLIP_ADD( ref_costs[list][idx1], (listamount*idx1weight+512)>>10 );
474                             CLIP_ADD( ref_costs[list][idx2], (listamount*idx2weight+512)>>10 );
475                             CLIP_ADD( ref_costs[list][idx3], (listamount*idx3weight+512)>>10 );
476                         }
477                         else /* Check offsets individually */
478                         {
479                             if( mbx < h->sps->i_mb_width && mby < h->sps->i_mb_height && mbx >= 0 && mby >= 0 )
480                                 CLIP_ADD( ref_costs[list][idx0], (listamount*idx0weight+512)>>10 );
481                             if( mbx+1 < h->sps->i_mb_width && mby < h->sps->i_mb_height && mbx+1 >= 0 && mby >= 0 )
482                                 CLIP_ADD( ref_costs[list][idx1], (listamount*idx1weight+512)>>10 );
483                             if( mbx < h->sps->i_mb_width && mby+1 < h->sps->i_mb_height && mbx >= 0 && mby+1 >= 0 )
484                                 CLIP_ADD( ref_costs[list][idx2], (listamount*idx2weight+512)>>10 );
485                             if( mbx+1 < h->sps->i_mb_width && mby+1 < h->sps->i_mb_height && mbx+1 >= 0 && mby+1 >= 0 )
486                                 CLIP_ADD( ref_costs[list][idx3], (listamount*idx3weight+512)>>10 );
487                         }
488                     }
489             }
490         }
491     }
492
493     if( h->param.rc.i_vbv_buffer_size && b == p1 )
494         x264_macroblock_tree_finish( h, frames[b] );
495 }
496
497 static void x264_macroblock_tree( x264_t *h, x264_mb_analysis_t *a, x264_frame_t **frames, int num_frames, int b_intra )
498 {
499     int i, idx = !b_intra;
500     int last_nonb, cur_nonb = 1;
501     if( b_intra )
502         x264_slicetype_frame_cost( h, a, frames, 0, 0, 0, 0 );
503
504     i = num_frames-1;
505     while( i > 0 && frames[i]->i_type == X264_TYPE_B )
506         i--;
507     last_nonb = i;
508
509     if( last_nonb < idx )
510         return;
511
512     memset( frames[last_nonb]->i_propagate_cost, 0, h->mb.i_mb_count * sizeof(uint16_t) );
513     while( i-- > idx )
514     {
515         cur_nonb = i;
516         while( frames[cur_nonb]->i_type == X264_TYPE_B && cur_nonb > 0 )
517             cur_nonb--;
518         if( cur_nonb < idx )
519             break;
520         x264_slicetype_frame_cost( h, a, frames, cur_nonb, last_nonb, last_nonb, 0 );
521         memset( frames[cur_nonb]->i_propagate_cost, 0, h->mb.i_mb_count * sizeof(uint16_t) );
522         while( i > cur_nonb )
523         {
524             x264_slicetype_frame_cost( h, a, frames, cur_nonb, last_nonb, i, 0 );
525             memset( frames[i]->i_propagate_cost, 0, h->mb.i_mb_count * sizeof(uint16_t) );
526             x264_macroblock_tree_propagate( h, frames, cur_nonb, last_nonb, i );
527             i--;
528         }
529         x264_macroblock_tree_propagate( h, frames, cur_nonb, last_nonb, last_nonb );
530         last_nonb = cur_nonb;
531     }
532
533     x264_macroblock_tree_finish( h, frames[last_nonb] );
534 }
535
536 static int x264_vbv_frame_cost( x264_t *h, x264_mb_analysis_t *a, x264_frame_t **frames, int p0, int p1, int b )
537 {
538     int cost = x264_slicetype_frame_cost( h, a, frames, p0, p1, b, 0 );
539     if( h->param.rc.i_aq_mode )
540     {
541         if( h->param.rc.b_mb_tree )
542             return x264_slicetype_frame_cost_recalculate( h, frames, p0, p1, b );
543         else
544             return frames[b]->i_cost_est_aq[b-p0][p1-b];
545     }
546     return cost;
547 }
548
549 static void x264_vbv_lookahead( x264_t *h, x264_mb_analysis_t *a, x264_frame_t **frames, int num_frames, int keyframe )
550 {
551     int last_nonb = 0, cur_nonb = 1, next_nonb, i, idx = 0;
552     while( cur_nonb < num_frames && frames[cur_nonb]->i_type == X264_TYPE_B )
553         cur_nonb++;
554     next_nonb = keyframe ? last_nonb : cur_nonb;
555
556     while( cur_nonb <= num_frames )
557     {
558         /* P/I cost: This shouldn't include the cost of next_nonb */
559         if( next_nonb != cur_nonb )
560         {
561             int p0 = IS_X264_TYPE_I( frames[cur_nonb]->i_type ) ? cur_nonb : last_nonb;
562             frames[next_nonb]->i_planned_satd[idx] = x264_vbv_frame_cost( h, a, frames, p0, cur_nonb, cur_nonb );
563             frames[next_nonb]->i_planned_type[idx] = frames[cur_nonb]->i_type;
564             idx++;
565         }
566         /* Handle the B-frames: coded order */
567         for( i = last_nonb+1; i < cur_nonb; i++, idx++ )
568         {
569             frames[next_nonb]->i_planned_satd[idx] = x264_vbv_frame_cost( h, a, frames, last_nonb, cur_nonb, i );
570             frames[next_nonb]->i_planned_type[idx] = X264_TYPE_B;
571         }
572         last_nonb = cur_nonb;
573         cur_nonb++;
574         while( cur_nonb <= num_frames && frames[cur_nonb]->i_type == X264_TYPE_B )
575             cur_nonb++;
576     }
577     frames[next_nonb]->i_planned_type[idx] = X264_TYPE_AUTO;
578 }
579
580 static int x264_slicetype_path_cost( x264_t *h, x264_mb_analysis_t *a, x264_frame_t **frames, char *path, int threshold )
581 {
582     int loc = 1;
583     int cost = 0;
584     int cur_p = 0;
585     path--; /* Since the 1st path element is really the second frame */
586     while( path[loc] )
587     {
588         int next_p = loc;
589         int next_b;
590         /* Find the location of the next P-frame. */
591         while( path[next_p] && path[next_p] != 'P' )
592             next_p++;
593         /* Return if the path doesn't end on a P-frame. */
594         if( path[next_p] != 'P' )
595             return cost;
596
597         /* Add the cost of the P-frame found above */
598         cost += x264_slicetype_frame_cost( h, a, frames, cur_p, next_p, next_p, 0 );
599         /* Early terminate if the cost we have found is larger than the best path cost so far */
600         if( cost > threshold )
601             break;
602
603         for( next_b = loc; next_b < next_p && cost < threshold; next_b++ )
604             cost += x264_slicetype_frame_cost( h, a, frames, cur_p, next_p, next_b, 0 );
605
606         loc = next_p + 1;
607         cur_p = next_p;
608     }
609     return cost;
610 }
611
612 /* Viterbi/trellis slicetype decision algorithm. */
613 /* Uses strings due to the fact that the speed of the control functions is
614    negligable compared to the cost of running slicetype_frame_cost, and because
615    it makes debugging easier. */
616 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] )
617 {
618     char paths[X264_BFRAME_MAX+1][X264_LOOKAHEAD_MAX] = {{0}};
619     int num_paths = X264_MIN( max_bframes+1, length );
620     int path;
621     int best_cost = COST_MAX;
622     int best_path_index = 0;
623
624     /* Iterate over all currently possible paths */
625     for( path = 0; path < num_paths; path++ )
626     {
627         /* Add suffixes to the current path */
628         int len = length - (path + 1);
629         memcpy( paths[path], best_paths[len % (X264_BFRAME_MAX+1)], len );
630         memset( paths[path]+len, 'B', path );
631         strcat( paths[path], "P" );
632
633         /* Calculate the actual cost of the current path */
634         int cost = x264_slicetype_path_cost( h, a, frames, paths[path], best_cost );
635         if( cost < best_cost )
636         {
637             best_cost = cost;
638             best_path_index = path;
639         }
640     }
641
642     /* Store the best path. */
643     memcpy( best_paths[length % (X264_BFRAME_MAX+1)], paths[best_path_index], length );
644 }
645
646 static int scenecut_internal( x264_t *h, x264_mb_analysis_t *a, x264_frame_t **frames, int p0, int p1, int print )
647 {
648     x264_frame_t *frame = frames[p1];
649     x264_slicetype_frame_cost( h, a, frames, p0, p1, p1, 0 );
650
651     int icost = frame->i_cost_est[0][0];
652     int pcost = frame->i_cost_est[p1-p0][0];
653     float f_bias;
654     int i_gop_size = frame->i_frame - h->lookahead->i_last_idr;
655     float f_thresh_max = h->param.i_scenecut_threshold / 100.0;
656     /* magic numbers pulled out of thin air */
657     float f_thresh_min = f_thresh_max * h->param.i_keyint_min
658                          / ( h->param.i_keyint_max * 4 );
659     int res;
660
661     if( h->param.i_keyint_min == h->param.i_keyint_max )
662         f_thresh_min= f_thresh_max;
663     if( i_gop_size < h->param.i_keyint_min / 4 )
664         f_bias = f_thresh_min / 4;
665     else if( i_gop_size <= h->param.i_keyint_min )
666         f_bias = f_thresh_min * i_gop_size / h->param.i_keyint_min;
667     else
668     {
669         f_bias = f_thresh_min
670                  + ( f_thresh_max - f_thresh_min )
671                     * ( i_gop_size - h->param.i_keyint_min )
672                    / ( h->param.i_keyint_max - h->param.i_keyint_min ) ;
673     }
674
675     res = pcost >= (1.0 - f_bias) * icost;
676     if( res && print )
677     {
678         int imb = frame->i_intra_mbs[p1-p0];
679         int pmb = NUM_MBS - imb;
680         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",
681                   frame->i_frame,
682                   icost, pcost, 1. - (double)pcost / icost,
683                   f_bias, i_gop_size, imb, pmb );
684     }
685     return res;
686 }
687
688 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 )
689 {
690     int curp0, curp1, i, maxp1 = p0 + 1;
691
692     /* Only do analysis during a normal scenecut check. */
693     if( real_scenecut && h->param.i_bframe )
694     {
695         /* Look ahead to avoid coding short flashes as scenecuts. */
696         if( h->param.i_bframe_adaptive == X264_B_ADAPT_TRELLIS )
697             /* Don't analyse any more frames than the trellis would have covered. */
698             maxp1 += h->param.i_bframe;
699         else
700             maxp1++;
701         maxp1 = X264_MIN( maxp1, num_frames );
702
703         /* Where A and B are scenes: AAAAAABBBAAAAAA
704          * If BBB is shorter than (maxp1-p0), it is detected as a flash
705          * and not considered a scenecut. */
706         for( curp1 = p1; curp1 <= maxp1; curp1++ )
707             if( !scenecut_internal( h, a, frames, p0, curp1, 0 ) )
708                 /* Any frame in between p0 and cur_p1 cannot be a real scenecut. */
709                 for( i = curp1; i > p0; i-- )
710                     frames[i]->b_scenecut = 0;
711
712         /* Where A-F are scenes: AAAAABBCCDDEEFFFFFF
713          * If each of BB ... EE are shorter than (maxp1-p0), they are
714          * detected as flashes and not considered scenecuts.
715          * Instead, the first F frame becomes a scenecut. */
716         for( curp0 = p0; curp0 < maxp1; curp0++ )
717             if( scenecut_internal( h, a, frames, curp0, maxp1, 0 ) )
718                 /* If cur_p0 is the p0 of a scenecut, it cannot be the p1 of a scenecut. */
719                     frames[curp0]->b_scenecut = 0;
720     }
721
722     /* Ignore frames that are part of a flash, i.e. cannot be real scenecuts. */
723     if( !frames[p1]->b_scenecut )
724         return 0;
725     return scenecut_internal( h, a, frames, p0, p1, real_scenecut );
726 }
727
728 void x264_slicetype_analyse( x264_t *h, int keyframe )
729 {
730     x264_mb_analysis_t a;
731     x264_frame_t *frames[X264_LOOKAHEAD_MAX+3] = { NULL, };
732     int num_frames, orig_num_frames, keyint_limit, idr_frame_type, i, j;
733     int i_mb_count = NUM_MBS;
734     int cost1p0, cost2p0, cost1b1, cost2p1;
735     int i_max_search = X264_MIN( h->lookahead->next.i_size, X264_LOOKAHEAD_MAX );
736     if( h->param.b_deterministic )
737         i_max_search = X264_MIN( i_max_search, h->lookahead->i_slicetype_length + !keyframe );
738
739     assert( h->frames.b_have_lowres );
740
741     if( !h->lookahead->last_nonb )
742         return;
743     frames[0] = h->lookahead->last_nonb;
744     for( j = 0; j < i_max_search && h->lookahead->next.list[j]->i_type == X264_TYPE_AUTO; j++ )
745         frames[j+1] = h->lookahead->next.list[j];
746
747     if( !j )
748         return;
749
750     keyint_limit = h->param.i_keyint_max - frames[0]->i_frame + h->lookahead->i_last_idr - 1;
751     orig_num_frames = num_frames = X264_MIN( j, keyint_limit );
752
753     x264_lowres_context_init( h, &a );
754     idr_frame_type = frames[1]->i_frame - h->lookahead->i_last_idr >= h->param.i_keyint_min ? X264_TYPE_IDR : X264_TYPE_I;
755
756     /* This is important psy-wise: if we have a non-scenecut keyframe,
757      * there will be significant visual artifacts if the frames just before
758      * go down in quality due to being referenced less, despite it being
759      * more RD-optimal. */
760     if( (h->param.analyse.b_psy && h->param.rc.b_mb_tree) || h->param.rc.i_vbv_buffer_size )
761         num_frames = j;
762     else if( num_frames == 1 )
763     {
764         frames[1]->i_type = X264_TYPE_P;
765         if( h->param.i_scenecut_threshold && scenecut( h, &a, frames, 0, 1, 1, orig_num_frames ) )
766             frames[1]->i_type = idr_frame_type;
767         return;
768     }
769     else if( num_frames == 0 )
770     {
771         frames[1]->i_type = idr_frame_type;
772         return;
773     }
774
775     int num_bframes = 0;
776     int max_bframes = X264_MIN(num_frames-1, h->param.i_bframe);
777     int num_analysed_frames = num_frames;
778     int reset_start;
779     if( h->param.i_scenecut_threshold && scenecut( h, &a, frames, 0, 1, 1, orig_num_frames ) )
780     {
781         frames[1]->i_type = idr_frame_type;
782         return;
783     }
784
785     if( h->param.i_bframe )
786     {
787         if( h->param.i_bframe_adaptive == X264_B_ADAPT_TRELLIS )
788         {
789             char best_paths[X264_BFRAME_MAX+1][X264_LOOKAHEAD_MAX] = {"","P"};
790             int n;
791
792             /* Perform the frametype analysis. */
793             for( n = 2; n < num_frames; n++ )
794                 x264_slicetype_path( h, &a, frames, n, max_bframes, best_paths );
795             if( num_frames > 1 )
796             {
797                 int best_path_index = (num_frames-1) % (X264_BFRAME_MAX+1);
798                 num_bframes = strspn( best_paths[best_path_index], "B" );
799                 /* Load the results of the analysis into the frame types. */
800                 for( j = 1; j < num_frames; j++ )
801                     frames[j]->i_type = best_paths[best_path_index][j-1] == 'B' ? X264_TYPE_B : X264_TYPE_P;
802             }
803             frames[num_frames]->i_type = X264_TYPE_P;
804         }
805         else if( h->param.i_bframe_adaptive == X264_B_ADAPT_FAST )
806         {
807             for( i = 0; i <= num_frames-2; )
808             {
809                 cost2p1 = x264_slicetype_frame_cost( h, &a, frames, i+0, i+2, i+2, 1 );
810                 if( frames[i+2]->i_intra_mbs[2] > i_mb_count / 2 )
811                 {
812                     frames[i+1]->i_type = X264_TYPE_P;
813                     frames[i+2]->i_type = X264_TYPE_P;
814                     i += 2;
815                     continue;
816                 }
817
818                 cost1b1 = x264_slicetype_frame_cost( h, &a, frames, i+0, i+2, i+1, 0 );
819                 cost1p0 = x264_slicetype_frame_cost( h, &a, frames, i+0, i+1, i+1, 0 );
820                 cost2p0 = x264_slicetype_frame_cost( h, &a, frames, i+1, i+2, i+2, 0 );
821
822                 if( cost1p0 + cost2p0 < cost1b1 + cost2p1 )
823                 {
824                     frames[i+1]->i_type = X264_TYPE_P;
825                     i += 1;
826                     continue;
827                 }
828
829                 // arbitrary and untuned
830                 #define INTER_THRESH 300
831                 #define P_SENS_BIAS (50 - h->param.i_bframe_bias)
832                 frames[i+1]->i_type = X264_TYPE_B;
833
834                 for( j = i+2; j <= X264_MIN( i+h->param.i_bframe, num_frames-1 ); j++ )
835                 {
836                     int pthresh = X264_MAX(INTER_THRESH - P_SENS_BIAS * (j-i-1), INTER_THRESH/10);
837                     int pcost = x264_slicetype_frame_cost( h, &a, frames, i+0, j+1, j+1, 1 );
838                     if( pcost > pthresh*i_mb_count || frames[j+1]->i_intra_mbs[j-i+1] > i_mb_count/3 )
839                         break;
840                     frames[j]->i_type = X264_TYPE_B;
841                 }
842                 frames[j]->i_type = X264_TYPE_P;
843                 i = j;
844             }
845             frames[num_frames]->i_type = X264_TYPE_P;
846             num_bframes = 0;
847             while( num_bframes < num_frames && frames[num_bframes+1]->i_type == X264_TYPE_B )
848                 num_bframes++;
849         }
850         else
851         {
852             num_bframes = X264_MIN(num_frames-1, h->param.i_bframe);
853             for( j = 1; j < num_frames; j++ )
854                 frames[j]->i_type = (j%(num_bframes+1)) ? X264_TYPE_B : X264_TYPE_P;
855             frames[num_frames]->i_type = X264_TYPE_P;
856         }
857
858         /* Check scenecut on the first minigop. */
859         for( j = 1; j < num_bframes+1; j++ )
860             if( h->param.i_scenecut_threshold && scenecut( h, &a, frames, j, j+1, 0, orig_num_frames ) )
861             {
862                 frames[j]->i_type = X264_TYPE_P;
863                 num_analysed_frames = j;
864                 break;
865             }
866
867         reset_start = keyframe ? 1 : X264_MIN( num_bframes+2, num_analysed_frames+1 );
868     }
869     else
870     {
871         for( j = 1; j <= num_frames; j++ )
872             frames[j]->i_type = X264_TYPE_P;
873         reset_start = !keyframe + 1;
874         num_bframes = 0;
875     }
876
877     /* Perform the actual macroblock tree analysis.
878      * Don't go farther than the maximum keyframe interval; this helps in short GOPs. */
879     if( h->param.rc.b_mb_tree )
880         x264_macroblock_tree( h, &a, frames, X264_MIN(num_frames, h->param.i_keyint_max), keyframe );
881
882     /* Enforce keyframe limit. */
883     for( j = 0; j < num_frames; j++ )
884     {
885         if( ((j-keyint_limit) % h->param.i_keyint_max) == 0 )
886         {
887             if( j && h->param.i_keyint_max > 1 )
888                 frames[j]->i_type = X264_TYPE_P;
889             frames[j+1]->i_type = X264_TYPE_IDR;
890             reset_start = X264_MIN( reset_start, j+2 );
891         }
892     }
893
894     if( h->param.rc.i_vbv_buffer_size )
895         x264_vbv_lookahead( h, &a, frames, num_frames, keyframe );
896
897     /* Restore frametypes for all frames that haven't actually been decided yet. */
898     for( j = reset_start; j <= num_frames; j++ )
899         frames[j]->i_type = X264_TYPE_AUTO;
900 }
901
902 void x264_slicetype_decide( x264_t *h )
903 {
904     x264_frame_t *frames[X264_BFRAME_MAX+2];
905     x264_frame_t *frm;
906     int bframes;
907     int brefs;
908     int i;
909
910     if( !h->lookahead->next.i_size )
911         return;
912
913     if( h->param.rc.b_stat_read )
914     {
915         /* Use the frame types from the first pass */
916         for( i = 0; i < h->lookahead->next.i_size; i++ )
917             h->lookahead->next.list[i]->i_type =
918                 x264_ratecontrol_slice_type( h, h->lookahead->next.list[i]->i_frame );
919     }
920     else if( (h->param.i_bframe && h->param.i_bframe_adaptive)
921              || h->param.i_scenecut_threshold
922              || h->param.rc.b_mb_tree
923              || (h->param.rc.i_vbv_buffer_size && h->param.rc.i_lookahead) )
924         x264_slicetype_analyse( h, 0 );
925
926     for( bframes = 0, brefs = 0;; bframes++ )
927     {
928         frm = h->lookahead->next.list[bframes];
929         if( frm->i_type == X264_TYPE_BREF && h->param.i_bframe_pyramid < X264_B_PYRAMID_NORMAL &&
930             brefs == h->param.i_bframe_pyramid )
931         {
932             frm->i_type = X264_TYPE_B;
933             x264_log( h, X264_LOG_WARNING, "B-ref at frame %d incompatible with B-pyramid %s \n",
934                       frm->i_frame, x264_b_pyramid_names[h->param.i_bframe_pyramid] );
935         }
936         /* pyramid with multiple B-refs needs a big enough dpb that the preceding P-frame stays available.
937            smaller dpb could be supported by smart enough use of mmco, but it's easier just to forbid it. */
938         else if( frm->i_type == X264_TYPE_BREF && h->param.i_bframe_pyramid == X264_B_PYRAMID_NORMAL &&
939             brefs && h->param.i_frame_reference <= (brefs+3) )
940         {
941             frm->i_type = X264_TYPE_B;
942             x264_log( h, X264_LOG_WARNING, "B-ref at frame %d incompatible with B-pyramid %s and %d reference frames\n",
943                       frm->i_frame, x264_b_pyramid_names[h->param.i_bframe_pyramid], h->param.i_frame_reference );
944         }
945
946         /* Limit GOP size */
947         if( frm->i_frame - h->lookahead->i_last_idr >= h->param.i_keyint_max )
948         {
949             if( frm->i_type == X264_TYPE_AUTO )
950                 frm->i_type = X264_TYPE_IDR;
951             if( frm->i_type != X264_TYPE_IDR )
952                 x264_log( h, X264_LOG_WARNING, "specified frame type (%d) is not compatible with keyframe interval\n", frm->i_type );
953         }
954         if( frm->i_type == X264_TYPE_IDR )
955         {
956             /* Close GOP */
957             h->lookahead->i_last_idr = frm->i_frame;
958             if( bframes > 0 )
959             {
960                 bframes--;
961                 h->lookahead->next.list[bframes]->i_type = X264_TYPE_P;
962             }
963         }
964
965         if( bframes == h->param.i_bframe ||
966             !h->lookahead->next.list[bframes+1] )
967         {
968             if( IS_X264_TYPE_B( frm->i_type ) )
969                 x264_log( h, X264_LOG_WARNING, "specified frame type is not compatible with max B-frames\n" );
970             if( frm->i_type == X264_TYPE_AUTO
971                 || IS_X264_TYPE_B( frm->i_type ) )
972                 frm->i_type = X264_TYPE_P;
973         }
974
975         if( frm->i_type == X264_TYPE_BREF )
976             brefs++;
977
978         if( frm->i_type == X264_TYPE_AUTO )
979             frm->i_type = X264_TYPE_B;
980
981         else if( !IS_X264_TYPE_B( frm->i_type ) ) break;
982     }
983
984     if( bframes )
985         h->lookahead->next.list[bframes-1]->b_last_minigop_bframe = 1;
986     h->lookahead->next.list[bframes]->i_bframes = bframes;
987
988     /* insert a bref into the sequence */
989     if( h->param.i_bframe_pyramid && bframes > 1 && !brefs )
990     {
991         h->lookahead->next.list[bframes/2]->i_type = X264_TYPE_BREF;
992         brefs++;
993     }
994
995     /* calculate the frame costs ahead of time for x264_rc_analyse_slice while we still have lowres */
996     if( h->param.rc.i_rc_method != X264_RC_CQP )
997     {
998         x264_mb_analysis_t a;
999         int p0, p1, b;
1000         p1 = b = bframes + 1;
1001
1002         x264_lowres_context_init( h, &a );
1003
1004         frames[0] = h->lookahead->last_nonb;
1005         memcpy( &frames[1], h->lookahead->next.list, (bframes+1) * sizeof(x264_frame_t*) );
1006         if( IS_X264_TYPE_I( h->lookahead->next.list[bframes]->i_type ) )
1007             p0 = bframes + 1;
1008         else // P
1009             p0 = 0;
1010
1011         x264_slicetype_frame_cost( h, &a, frames, p0, p1, b, 0 );
1012
1013         if( (p0 != p1 || bframes) && h->param.rc.i_vbv_buffer_size )
1014         {
1015             /* We need the intra costs for row SATDs. */
1016             x264_slicetype_frame_cost( h, &a, frames, b, b, b, 0 );
1017
1018             /* We need B-frame costs for row SATDs. */
1019             p0 = 0;
1020             for( b = 1; b <= bframes; b++ )
1021             {
1022                 if( frames[b]->i_type == X264_TYPE_B )
1023                     for( p1 = b; frames[p1]->i_type == X264_TYPE_B; )
1024                         p1++;
1025                 else
1026                     p1 = bframes + 1;
1027                 x264_slicetype_frame_cost( h, &a, frames, p0, p1, b, 0 );
1028                 if( frames[b]->i_type == X264_TYPE_BREF )
1029                     p0 = b;
1030             }
1031         }
1032     }
1033
1034     /* shift sequence to coded order.
1035        use a small temporary list to avoid shifting the entire next buffer around */
1036     int i_dts = h->lookahead->next.list[0]->i_frame;
1037     if( bframes )
1038     {
1039         int index[] = { brefs+1, 1 };
1040         for( i = 0; i < bframes; i++ )
1041             frames[ index[h->lookahead->next.list[i]->i_type == X264_TYPE_BREF]++ ] = h->lookahead->next.list[i];
1042         frames[0] = h->lookahead->next.list[bframes];
1043         memcpy( h->lookahead->next.list, frames, (bframes+1) * sizeof(x264_frame_t*) );
1044     }
1045     for( i = 0; i <= bframes; i++ )
1046          h->lookahead->next.list[i]->i_dts = i_dts++;
1047 }
1048
1049 int x264_rc_analyse_slice( x264_t *h )
1050 {
1051     int p0=0, p1, b;
1052     int cost;
1053
1054     if( IS_X264_TYPE_I(h->fenc->i_type) )
1055         p1 = b = 0;
1056     else if( h->fenc->i_type == X264_TYPE_P )
1057         p1 = b = h->fenc->i_bframes + 1;
1058     else //B
1059     {
1060         p1 = (h->fref1[0]->i_poc - h->fref0[0]->i_poc)/2;
1061         b  = (h->fenc->i_poc - h->fref0[0]->i_poc)/2;
1062     }
1063     /* We don't need to assign p0/p1 since we are not performing any real analysis here. */
1064     x264_frame_t **frames = &h->fenc - b;
1065
1066     /* cost should have been already calculated by x264_slicetype_decide */
1067     cost = frames[b]->i_cost_est[b-p0][p1-b];
1068     assert( cost >= 0 );
1069
1070     if( h->param.rc.b_mb_tree && !h->param.rc.b_stat_read )
1071     {
1072         cost = x264_slicetype_frame_cost_recalculate( h, frames, p0, p1, b );
1073         if( b && h->param.rc.i_vbv_buffer_size )
1074             x264_slicetype_frame_cost_recalculate( h, frames, b, b, b );
1075     }
1076     /* In AQ, use the weighted score instead. */
1077     else if( h->param.rc.i_aq_mode )
1078         cost = frames[b]->i_cost_est_aq[b-p0][p1-b];
1079
1080     h->fenc->i_row_satd = h->fenc->i_row_satds[b-p0][p1-b];
1081     h->fdec->i_row_satd = h->fdec->i_row_satds[b-p0][p1-b];
1082     h->fdec->i_satd = cost;
1083     memcpy( h->fdec->i_row_satd, h->fenc->i_row_satd, h->sps->i_mb_height * sizeof(int) );
1084     if( !IS_X264_TYPE_I(h->fenc->i_type) )
1085         memcpy( h->fdec->i_row_satds[0][0], h->fenc->i_row_satds[0][0], h->sps->i_mb_height * sizeof(int) );
1086     return cost;
1087 }