]> git.sesse.net Git - x264/blob - encoder/slicetype.c
Fix glitches with slow-firstpass + weightb + multiref + 2pass
[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     x264_emms();
377     for( h->mb.i_mb_y = h->sps->i_mb_height - 1; h->mb.i_mb_y >= 0; h->mb.i_mb_y-- )
378     {
379         row_satd[ h->mb.i_mb_y ] = 0;
380         for( h->mb.i_mb_x = h->sps->i_mb_width - 1; h->mb.i_mb_x >= 0; h->mb.i_mb_x-- )
381         {
382             int i_mb_xy = h->mb.i_mb_x + h->mb.i_mb_y*h->mb.i_mb_stride;
383             int i_mb_cost = frames[b]->lowres_costs[b-p0][p1-b][i_mb_xy];
384             float qp_adj = frames[b]->f_qp_offset[i_mb_xy];
385             i_mb_cost = (i_mb_cost * x264_exp2fix8(qp_adj) + 128) >> 8;
386             row_satd[ h->mb.i_mb_y ] += i_mb_cost;
387             if( (h->mb.i_mb_y > 0 && h->mb.i_mb_y < h->sps->i_mb_height - 1 &&
388                  h->mb.i_mb_x > 0 && h->mb.i_mb_x < h->sps->i_mb_width - 1) ||
389                  h->sps->i_mb_width <= 2 || h->sps->i_mb_height <= 2 )
390             {
391                 i_score += i_mb_cost;
392             }
393         }
394     }
395     return i_score;
396 }
397
398 static void x264_macroblock_tree_finish( x264_t *h, x264_frame_t *frame, int b_bidir )
399 {
400     int mb_index;
401     x264_emms();
402     if( b_bidir )
403         memcpy( frame->f_qp_offset, frame->f_qp_offset_aq, sizeof( frame->f_qp_offset ) );
404     else
405     {
406         /* Allow the strength to be adjusted via qcompress, since the two
407          * concepts are very similar. */
408         float strength = 5.0f * (1.0f - h->param.rc.f_qcompress);
409         for( mb_index = 0; mb_index < h->mb.i_mb_count; mb_index++ )
410         {
411             int intra_cost = (frame->i_intra_cost[mb_index] * frame->i_inv_qscale_factor[mb_index]+128)>>8;
412             if( intra_cost )
413             {
414                 int propagate_cost = frame->i_propagate_cost[mb_index];
415                 float log2_ratio = x264_log2(intra_cost + propagate_cost) - x264_log2(intra_cost);
416                 frame->f_qp_offset[mb_index] = frame->f_qp_offset_aq[mb_index] - strength * log2_ratio;
417             }
418         }
419     }
420 }
421
422 static void x264_macroblock_tree_propagate( x264_t *h, x264_frame_t **frames, int p0, int p1, int b )
423 {
424     uint16_t *ref_costs[2] = {frames[p0]->i_propagate_cost,frames[p1]->i_propagate_cost};
425     int dist_scale_factor = ( ((b-p0) << 8) + ((p1-p0) >> 1) ) / (p1-p0);
426     int i_bipred_weight = h->param.analyse.b_weighted_bipred ? 64 - (dist_scale_factor>>2) : 32;
427     int16_t (*mvs[2])[2] = { frames[b]->lowres_mvs[0][b-p0-1], frames[b]->lowres_mvs[1][p1-b-1] };
428     int bipred_weights[2] = {i_bipred_weight, 64 - i_bipred_weight};
429     int *buf = h->scratch_buffer;
430
431     for( h->mb.i_mb_y = 0; h->mb.i_mb_y < h->sps->i_mb_height; h->mb.i_mb_y++ )
432     {
433         int mb_index = h->mb.i_mb_y*h->mb.i_mb_stride;
434         h->mc.mbtree_propagate_cost( buf, frames[b]->i_propagate_cost+mb_index,
435             frames[b]->i_intra_cost+mb_index, frames[b]->lowres_costs[b-p0][p1-b]+mb_index,
436             frames[b]->i_inv_qscale_factor+mb_index, h->sps->i_mb_width );
437         for( h->mb.i_mb_x = 0; h->mb.i_mb_x < h->sps->i_mb_width; h->mb.i_mb_x++, mb_index++ )
438         {
439             int propagate_amount = buf[h->mb.i_mb_x];
440             /* Don't propagate for an intra block. */
441             if( propagate_amount > 0 )
442             {
443                 /* Access width-2 bitfield. */
444                 int lists_used = (frames[b]->lowres_inter_types[b-p0][p1-b][mb_index>>2] >> ((mb_index&3)*2))&3;
445                 int list;
446                 /* Follow the MVs to the previous frame(s). */
447                 for( list = 0; list < 2; list++ )
448                     if( (lists_used >> list)&1 )
449                     {
450                         int x = mvs[list][mb_index][0];
451                         int y = mvs[list][mb_index][1];
452                         int listamount = propagate_amount;
453                         int mbx = (x>>5)+h->mb.i_mb_x;
454                         int mby = (y>>5)+h->mb.i_mb_y;
455                         int idx0 = mbx + mby*h->mb.i_mb_stride;
456                         int idx1 = idx0 + 1;
457                         int idx2 = idx0 + h->mb.i_mb_stride;
458                         int idx3 = idx0 + h->mb.i_mb_stride + 1;
459                         x &= 31;
460                         y &= 31;
461                         int idx0weight = (32-y)*(32-x);
462                         int idx1weight = (32-y)*x;
463                         int idx2weight = y*(32-x);
464                         int idx3weight = y*x;
465
466                         /* Apply bipred weighting. */
467                         if( lists_used == 3 )
468                             listamount = (listamount * bipred_weights[list] + 32) >> 6;
469
470 #define CLIP_ADD(s,x) (s) = X264_MIN((s)+(x),(1<<16)-1)
471
472                         /* We could just clip the MVs, but pixels that lie outside the frame probably shouldn't
473                          * be counted. */
474                         if( mbx < h->sps->i_mb_width-1 && mby < h->sps->i_mb_height-1 && mbx >= 0 && mby >= 0 )
475                         {
476                             CLIP_ADD( ref_costs[list][idx0], (listamount*idx0weight+512)>>10 );
477                             CLIP_ADD( ref_costs[list][idx1], (listamount*idx1weight+512)>>10 );
478                             CLIP_ADD( ref_costs[list][idx2], (listamount*idx2weight+512)>>10 );
479                             CLIP_ADD( ref_costs[list][idx3], (listamount*idx3weight+512)>>10 );
480                         }
481                         else /* Check offsets individually */
482                         {
483                             if( mbx < h->sps->i_mb_width && mby < h->sps->i_mb_height && mbx >= 0 && mby >= 0 )
484                                 CLIP_ADD( ref_costs[list][idx0], (listamount*idx0weight+512)>>10 );
485                             if( mbx+1 < h->sps->i_mb_width && mby < h->sps->i_mb_height && mbx+1 >= 0 && mby >= 0 )
486                                 CLIP_ADD( ref_costs[list][idx1], (listamount*idx1weight+512)>>10 );
487                             if( mbx < h->sps->i_mb_width && mby+1 < h->sps->i_mb_height && mbx >= 0 && mby+1 >= 0 )
488                                 CLIP_ADD( ref_costs[list][idx2], (listamount*idx2weight+512)>>10 );
489                             if( mbx+1 < h->sps->i_mb_width && mby+1 < h->sps->i_mb_height && mbx+1 >= 0 && mby+1 >= 0 )
490                                 CLIP_ADD( ref_costs[list][idx3], (listamount*idx3weight+512)>>10 );
491                         }
492                     }
493             }
494         }
495     }
496
497     if( h->param.rc.i_vbv_buffer_size )
498         x264_macroblock_tree_finish( h, frames[b], b != p1 );
499 }
500
501 static void x264_macroblock_tree( x264_t *h, x264_mb_analysis_t *a, x264_frame_t **frames, int num_frames, int b_intra )
502 {
503     int i, idx = !b_intra;
504     int last_nonb, cur_nonb = 1;
505     if( b_intra )
506         x264_slicetype_frame_cost( h, a, frames, 0, 0, 0, 0 );
507
508     i = num_frames-1;
509     while( i > 0 && frames[i]->i_type == X264_TYPE_B )
510         i--;
511     last_nonb = i;
512
513     if( last_nonb < 0 )
514         return;
515
516     memset( frames[last_nonb]->i_propagate_cost, 0, h->mb.i_mb_count * sizeof(uint16_t) );
517     while( i-- > idx )
518     {
519         cur_nonb = i;
520         while( frames[cur_nonb]->i_type == X264_TYPE_B && cur_nonb > 0 )
521             cur_nonb--;
522         if( cur_nonb < idx )
523             break;
524         x264_slicetype_frame_cost( h, a, frames, cur_nonb, last_nonb, last_nonb, 0 );
525         memset( frames[cur_nonb]->i_propagate_cost, 0, h->mb.i_mb_count * sizeof(uint16_t) );
526         x264_macroblock_tree_propagate( h, frames, cur_nonb, last_nonb, last_nonb );
527         while( frames[i]->i_type == X264_TYPE_B && i > 0 )
528         {
529             x264_slicetype_frame_cost( h, a, frames, cur_nonb, last_nonb, i, 0 );
530             memset( frames[i]->i_propagate_cost, 0, h->mb.i_mb_count * sizeof(uint16_t) );
531             x264_macroblock_tree_propagate( h, frames, cur_nonb, last_nonb, i );
532             i--;
533         }
534         last_nonb = cur_nonb;
535     }
536
537     x264_macroblock_tree_finish( h, frames[last_nonb], 0 );
538 }
539
540 static int x264_vbv_frame_cost( x264_t *h, x264_mb_analysis_t *a, x264_frame_t **frames, int p0, int p1, int b )
541 {
542     int cost = x264_slicetype_frame_cost( h, a, frames, p0, p1, b, 0 );
543     if( h->param.rc.i_aq_mode )
544     {
545         if( h->param.rc.b_mb_tree )
546             return x264_slicetype_frame_cost_recalculate( h, frames, p0, p1, b );
547         else
548             return frames[b]->i_cost_est_aq[b-p0][p1-b];
549     }
550     return cost;
551 }
552
553 static void x264_vbv_lookahead( x264_t *h, x264_mb_analysis_t *a, x264_frame_t **frames, int num_frames, int keyframe )
554 {
555     int last_nonb = 0, cur_nonb = 1, next_nonb, i, idx = 0;
556     while( cur_nonb < num_frames && frames[cur_nonb]->i_type == X264_TYPE_B )
557         cur_nonb++;
558     next_nonb = keyframe ? last_nonb : cur_nonb;
559
560     while( cur_nonb <= num_frames )
561     {
562         /* P/I cost: This shouldn't include the cost of next_nonb */
563         if( next_nonb != cur_nonb )
564         {
565             int p0 = IS_X264_TYPE_I( frames[cur_nonb]->i_type ) ? cur_nonb : last_nonb;
566             frames[next_nonb]->i_planned_satd[idx] = x264_vbv_frame_cost( h, a, frames, p0, cur_nonb, cur_nonb );
567             frames[next_nonb]->i_planned_type[idx] = frames[cur_nonb]->i_type;
568             idx++;
569         }
570         /* Handle the B-frames: coded order */
571         for( i = last_nonb+1; i < cur_nonb; i++, idx++ )
572         {
573             frames[next_nonb]->i_planned_satd[idx] = x264_vbv_frame_cost( h, a, frames, last_nonb, cur_nonb, i );
574             frames[next_nonb]->i_planned_type[idx] = X264_TYPE_B;
575         }
576         last_nonb = cur_nonb;
577         cur_nonb++;
578         while( cur_nonb <= num_frames && frames[cur_nonb]->i_type == X264_TYPE_B )
579             cur_nonb++;
580     }
581     frames[next_nonb]->i_planned_type[idx] = X264_TYPE_AUTO;
582 }
583
584 static int x264_slicetype_path_cost( x264_t *h, x264_mb_analysis_t *a, x264_frame_t **frames, char *path, int threshold )
585 {
586     int loc = 1;
587     int cost = 0;
588     int cur_p = 0;
589     path--; /* Since the 1st path element is really the second frame */
590     while( path[loc] )
591     {
592         int next_p = loc;
593         int next_b;
594         /* Find the location of the next P-frame. */
595         while( path[next_p] && path[next_p] != 'P' )
596             next_p++;
597         /* Return if the path doesn't end on a P-frame. */
598         if( path[next_p] != 'P' )
599             return cost;
600
601         /* Add the cost of the P-frame found above */
602         cost += x264_slicetype_frame_cost( h, a, frames, cur_p, next_p, next_p, 0 );
603         /* Early terminate if the cost we have found is larger than the best path cost so far */
604         if( cost > threshold )
605             break;
606
607         for( next_b = loc; next_b < next_p && cost < threshold; next_b++ )
608             cost += x264_slicetype_frame_cost( h, a, frames, cur_p, next_p, next_b, 0 );
609
610         loc = next_p + 1;
611         cur_p = next_p;
612     }
613     return cost;
614 }
615
616 /* Viterbi/trellis slicetype decision algorithm. */
617 /* Uses strings due to the fact that the speed of the control functions is
618    negligable compared to the cost of running slicetype_frame_cost, and because
619    it makes debugging easier. */
620 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] )
621 {
622     char paths[X264_BFRAME_MAX+2][X264_LOOKAHEAD_MAX] = {{0}};
623     int num_paths = X264_MIN(max_bframes+1, length);
624     int path;
625     int best_cost = COST_MAX;
626     int best_path_index = 0;
627     length = X264_MIN( length, X264_LOOKAHEAD_MAX );
628
629     /* Iterate over all currently possible paths */
630     for( path = 0; path < num_paths; path++ )
631     {
632         /* Add suffixes to the current path */
633         int len = length - (path + 1);
634         memcpy( paths[path], best_paths[len], len );
635         memset( paths[path]+len, 'B', path );
636         strcat( paths[path], "P" );
637
638         /* Calculate the actual cost of the current path */
639         int cost = x264_slicetype_path_cost( h, a, frames, paths[path], best_cost );
640         if( cost < best_cost )
641         {
642             best_cost = cost;
643             best_path_index = path;
644         }
645     }
646
647     /* Store the best path. */
648     memcpy( best_paths[length], paths[best_path_index], length );
649 }
650
651 static int scenecut_internal( x264_t *h, x264_mb_analysis_t *a, x264_frame_t **frames, int p0, int p1, int print )
652 {
653     x264_frame_t *frame = frames[p1];
654     x264_slicetype_frame_cost( h, a, frames, p0, p1, p1, 0 );
655
656     int icost = frame->i_cost_est[0][0];
657     int pcost = frame->i_cost_est[p1-p0][0];
658     float f_bias;
659     int i_gop_size = frame->i_frame - h->lookahead->i_last_idr;
660     float f_thresh_max = h->param.i_scenecut_threshold / 100.0;
661     /* magic numbers pulled out of thin air */
662     float f_thresh_min = f_thresh_max * h->param.i_keyint_min
663                          / ( h->param.i_keyint_max * 4 );
664     int res;
665
666     if( h->param.i_keyint_min == h->param.i_keyint_max )
667         f_thresh_min= f_thresh_max;
668     if( i_gop_size < h->param.i_keyint_min / 4 )
669         f_bias = f_thresh_min / 4;
670     else if( i_gop_size <= h->param.i_keyint_min )
671         f_bias = f_thresh_min * i_gop_size / h->param.i_keyint_min;
672     else
673     {
674         f_bias = f_thresh_min
675                  + ( f_thresh_max - f_thresh_min )
676                     * ( i_gop_size - h->param.i_keyint_min )
677                    / ( h->param.i_keyint_max - h->param.i_keyint_min ) ;
678     }
679
680     res = pcost >= (1.0 - f_bias) * icost;
681     if( res && print )
682     {
683         int imb = frame->i_intra_mbs[p1-p0];
684         int pmb = NUM_MBS - imb;
685         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",
686                   frame->i_frame,
687                   icost, pcost, 1. - (double)pcost / icost,
688                   f_bias, i_gop_size, imb, pmb );
689     }
690     return res;
691 }
692
693 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 )
694 {
695     int curp0, curp1, i, maxp1 = p0 + 1;
696
697     /* Only do analysis during a normal scenecut check. */
698     if( real_scenecut && h->param.i_bframe )
699     {
700         /* Look ahead to avoid coding short flashes as scenecuts. */
701         if( h->param.i_bframe_adaptive == X264_B_ADAPT_TRELLIS )
702             /* Don't analyse any more frames than the trellis would have covered. */
703             maxp1 += h->param.i_bframe;
704         else
705             maxp1++;
706         maxp1 = X264_MIN( maxp1, num_frames );
707
708         /* Where A and B are scenes: AAAAAABBBAAAAAA
709          * If BBB is shorter than (maxp1-p0), it is detected as a flash
710          * and not considered a scenecut. */
711         for( curp1 = p1; curp1 <= maxp1; curp1++ )
712             if( !scenecut_internal( h, a, frames, p0, curp1, 0 ) )
713                 /* Any frame in between p0 and cur_p1 cannot be a real scenecut. */
714                 for( i = curp1; i > p0; i-- )
715                     frames[i]->b_scenecut = 0;
716
717         /* Where A-F are scenes: AAAAABBCCDDEEFFFFFF
718          * If each of BB ... EE are shorter than (maxp1-p0), they are
719          * detected as flashes and not considered scenecuts.
720          * Instead, the first F frame becomes a scenecut. */
721         for( curp0 = p0; curp0 < maxp1; curp0++ )
722             if( scenecut_internal( h, a, frames, curp0, maxp1, 0 ) )
723                 /* If cur_p0 is the p0 of a scenecut, it cannot be the p1 of a scenecut. */
724                     frames[curp0]->b_scenecut = 0;
725     }
726
727     /* Ignore frames that are part of a flash, i.e. cannot be real scenecuts. */
728     if( !frames[p1]->b_scenecut )
729         return 0;
730     return scenecut_internal( h, a, frames, p0, p1, real_scenecut );
731 }
732
733 void x264_slicetype_analyse( x264_t *h, int keyframe )
734 {
735     x264_mb_analysis_t a;
736     x264_frame_t *frames[X264_LOOKAHEAD_MAX+3] = { NULL, };
737     int num_frames, orig_num_frames, keyint_limit, idr_frame_type, i, j;
738     int i_mb_count = NUM_MBS;
739     int cost1p0, cost2p0, cost1b1, cost2p1;
740     int i_max_search = X264_MIN( h->lookahead->next.i_size, X264_LOOKAHEAD_MAX );
741     if( h->param.b_deterministic )
742         i_max_search = X264_MIN( i_max_search, h->lookahead->i_slicetype_length + !keyframe );
743
744     assert( h->frames.b_have_lowres );
745
746     if( !h->lookahead->last_nonb )
747         return;
748     frames[0] = h->lookahead->last_nonb;
749     for( j = 0; j < i_max_search && h->lookahead->next.list[j]->i_type == X264_TYPE_AUTO; j++ )
750         frames[j+1] = h->lookahead->next.list[j];
751
752     if( !j )
753         return;
754
755     keyint_limit = h->param.i_keyint_max - frames[0]->i_frame + h->lookahead->i_last_idr - 1;
756     orig_num_frames = num_frames = X264_MIN( j, keyint_limit );
757
758     x264_lowres_context_init( h, &a );
759     idr_frame_type = frames[1]->i_frame - h->lookahead->i_last_idr >= h->param.i_keyint_min ? X264_TYPE_IDR : X264_TYPE_I;
760
761     /* This is important psy-wise: if we have a non-scenecut keyframe,
762      * there will be significant visual artifacts if the frames just before
763      * go down in quality due to being referenced less, despite it being
764      * more RD-optimal. */
765     if( (h->param.analyse.b_psy && h->param.rc.b_mb_tree) || h->param.rc.i_vbv_buffer_size )
766         num_frames = j;
767     else if( num_frames == 1 )
768     {
769         frames[1]->i_type = X264_TYPE_P;
770         if( h->param.i_scenecut_threshold && scenecut( h, &a, frames, 0, 1, 1, orig_num_frames ) )
771             frames[1]->i_type = idr_frame_type;
772         return;
773     }
774     else if( num_frames == 0 )
775     {
776         frames[1]->i_type = idr_frame_type;
777         return;
778     }
779
780     char best_paths[X264_LOOKAHEAD_MAX][X264_LOOKAHEAD_MAX] = {"","P"};
781     int n;
782     int num_bframes = 0;
783     int max_bframes = X264_MIN(num_frames-1, h->param.i_bframe);
784     int num_analysed_frames = num_frames;
785     int reset_start;
786     if( h->param.i_scenecut_threshold && scenecut( h, &a, frames, 0, 1, 1, orig_num_frames ) )
787     {
788         frames[1]->i_type = idr_frame_type;
789         return;
790     }
791
792     if( h->param.i_bframe )
793     {
794         if( h->param.i_bframe_adaptive == X264_B_ADAPT_TRELLIS )
795         {
796             /* Perform the frametype analysis. */
797             for( n = 2; n < num_frames-1; n++ )
798                 x264_slicetype_path( h, &a, frames, n, max_bframes, best_paths );
799             if( num_frames > 1 )
800             {
801                 num_bframes = strspn( best_paths[num_frames-2], "B" );
802                 /* Load the results of the analysis into the frame types. */
803                 for( j = 1; j < num_frames; j++ )
804                     frames[j]->i_type = best_paths[num_frames-2][j-1] == 'B' ? X264_TYPE_B : X264_TYPE_P;
805             }
806             frames[num_frames]->i_type = X264_TYPE_P;
807         }
808         else if( h->param.i_bframe_adaptive == X264_B_ADAPT_FAST )
809         {
810             for( i = 0; i < num_frames-(2-!i); )
811             {
812                 cost2p1 = x264_slicetype_frame_cost( h, &a, frames, i+0, i+2, i+2, 1 );
813                 if( frames[i+2]->i_intra_mbs[2] > i_mb_count / 2 )
814                 {
815                     frames[i+1]->i_type = X264_TYPE_P;
816                     frames[i+2]->i_type = X264_TYPE_P;
817                     i += 2;
818                     continue;
819                 }
820
821                 cost1b1 = x264_slicetype_frame_cost( h, &a, frames, i+0, i+2, i+1, 0 );
822                 cost1p0 = x264_slicetype_frame_cost( h, &a, frames, i+0, i+1, i+1, 0 );
823                 cost2p0 = x264_slicetype_frame_cost( h, &a, frames, i+1, i+2, i+2, 0 );
824
825                 if( cost1p0 + cost2p0 < cost1b1 + cost2p1 )
826                 {
827                     frames[i+1]->i_type = X264_TYPE_P;
828                     frames[i+2]->i_type = X264_TYPE_P;
829                     i += 2;
830                     continue;
831                 }
832
833                 // arbitrary and untuned
834                 #define INTER_THRESH 300
835                 #define P_SENS_BIAS (50 - h->param.i_bframe_bias)
836                 frames[i+1]->i_type = X264_TYPE_B;
837                 frames[i+2]->i_type = X264_TYPE_P;
838
839                 for( j = i+2; j <= X264_MIN( h->param.i_bframe, num_frames-1 ); j++ )
840                 {
841                     int pthresh = X264_MAX(INTER_THRESH - P_SENS_BIAS * (j-i-1), INTER_THRESH/10);
842                     int pcost = x264_slicetype_frame_cost( h, &a, frames, i+0, j+1, j+1, 1 );
843
844                     if( pcost > pthresh*i_mb_count || frames[j+1]->i_intra_mbs[j-i+1] > i_mb_count/3 )
845                     {
846                         frames[j]->i_type = X264_TYPE_P;
847                         break;
848                     }
849                     else
850                         frames[j]->i_type = X264_TYPE_B;
851                 }
852                 i = j;
853             }
854             frames[i+!i]->i_type = X264_TYPE_P;
855             num_bframes = 0;
856             while( num_bframes < num_frames && frames[num_bframes+1]->i_type == X264_TYPE_B )
857                 num_bframes++;
858         }
859         else
860         {
861             num_bframes = X264_MIN(num_frames-1, h->param.i_bframe);
862             for( j = 1; j < num_frames; j++ )
863                 frames[j]->i_type = (j%(num_bframes+1)) ? X264_TYPE_B : X264_TYPE_P;
864             frames[num_frames]->i_type = X264_TYPE_P;
865         }
866
867         /* Check scenecut on the first minigop. */
868         for( j = 1; j < num_bframes+1; j++ )
869             if( h->param.i_scenecut_threshold && scenecut( h, &a, frames, j, j+1, 0, orig_num_frames ) )
870             {
871                 frames[j]->i_type = X264_TYPE_P;
872                 num_analysed_frames = j;
873                 break;
874             }
875
876         reset_start = keyframe ? 1 : X264_MIN( num_bframes+2, num_analysed_frames+1 );
877     }
878     else
879     {
880         for( j = 1; j < num_frames; j++ )
881             frames[j]->i_type = X264_TYPE_P;
882         reset_start = !keyframe + 1;
883         num_bframes = 0;
884     }
885
886     for( j = 1; j <= num_frames; j++ )
887         if( frames[j]->i_type == X264_TYPE_AUTO )
888             frames[j]->i_type = X264_TYPE_P;
889
890     /* Perform the actual macroblock tree analysis.
891      * Don't go farther than the maximum keyframe interval; this helps in short GOPs. */
892     if( h->param.rc.b_mb_tree )
893         x264_macroblock_tree( h, &a, frames, X264_MIN(num_frames, h->param.i_keyint_max), keyframe );
894
895     /* Enforce keyframe limit. */
896     for( j = 0; j < num_frames; j++ )
897     {
898         if( ((j-keyint_limit) % h->param.i_keyint_max) == 0 )
899         {
900             if( j && h->param.i_keyint_max > 1 )
901                 frames[j]->i_type = X264_TYPE_P;
902             frames[j+1]->i_type = X264_TYPE_IDR;
903             reset_start = X264_MIN( reset_start, j+2 );
904         }
905     }
906
907     if( h->param.rc.i_vbv_buffer_size )
908         x264_vbv_lookahead( h, &a, frames, num_frames, keyframe );
909
910     /* Restore frametypes for all frames that haven't actually been decided yet. */
911     for( j = reset_start; j <= num_frames; j++ )
912         frames[j]->i_type = X264_TYPE_AUTO;
913 }
914
915 void x264_slicetype_decide( x264_t *h )
916 {
917     x264_frame_t *frm;
918     int bframes;
919     int i;
920
921     if( !h->lookahead->next.i_size )
922         return;
923
924     if( h->param.rc.b_stat_read )
925     {
926         /* Use the frame types from the first pass */
927         for( i = 0; i < h->lookahead->next.i_size; i++ )
928             h->lookahead->next.list[i]->i_type =
929                 x264_ratecontrol_slice_type( h, h->lookahead->next.list[i]->i_frame );
930     }
931     else if( (h->param.i_bframe && h->param.i_bframe_adaptive)
932              || h->param.i_scenecut_threshold
933              || h->param.rc.b_mb_tree
934              || (h->param.rc.i_vbv_buffer_size && h->param.rc.i_lookahead) )
935         x264_slicetype_analyse( h, 0 );
936
937     for( bframes = 0;; bframes++ )
938     {
939         frm = h->lookahead->next.list[bframes];
940
941         /* Limit GOP size */
942         if( frm->i_frame - h->lookahead->i_last_idr >= h->param.i_keyint_max )
943         {
944             if( frm->i_type == X264_TYPE_AUTO )
945                 frm->i_type = X264_TYPE_IDR;
946             if( frm->i_type != X264_TYPE_IDR )
947                 x264_log( h, X264_LOG_WARNING, "specified frame type (%d) is not compatible with keyframe interval\n", frm->i_type );
948         }
949         if( frm->i_type == X264_TYPE_IDR )
950         {
951             /* Close GOP */
952             h->lookahead->i_last_idr = frm->i_frame;
953             if( bframes > 0 )
954             {
955                 bframes--;
956                 h->lookahead->next.list[bframes]->i_type = X264_TYPE_P;
957             }
958         }
959
960         if( bframes == h->param.i_bframe ||
961             !h->lookahead->next.list[bframes+1] )
962         {
963             if( IS_X264_TYPE_B( frm->i_type ) )
964                 x264_log( h, X264_LOG_WARNING, "specified frame type is not compatible with max B-frames\n" );
965             if( frm->i_type == X264_TYPE_AUTO
966                 || IS_X264_TYPE_B( frm->i_type ) )
967                 frm->i_type = X264_TYPE_P;
968         }
969
970         if( frm->i_type == X264_TYPE_AUTO )
971             frm->i_type = X264_TYPE_B;
972
973         else if( !IS_X264_TYPE_B( frm->i_type ) ) break;
974     }
975
976     if( bframes )
977         h->lookahead->next.list[bframes-1]->b_last_minigop_bframe = 1;
978     h->lookahead->next.list[bframes]->i_bframes = bframes;
979
980     /* calculate the frame costs ahead of time for x264_rc_analyse_slice while we still have lowres */
981     if( h->param.rc.i_rc_method != X264_RC_CQP )
982     {
983         x264_mb_analysis_t a;
984         x264_frame_t *frames[X264_BFRAME_MAX+2] = { NULL, };
985         int p0=0, p1, b;
986
987         x264_lowres_context_init( h, &a );
988
989         if( IS_X264_TYPE_I( h->lookahead->next.list[bframes]->i_type ) )
990             p1 = b = 0;
991         else // P
992             p1 = b = bframes + 1;
993         frames[p0] = h->lookahead->last_nonb;
994         frames[b] = h->lookahead->next.list[bframes];
995
996         x264_slicetype_frame_cost( h, &a, frames, p0, p1, b, 0 );
997
998         if( b && h->param.rc.i_vbv_buffer_size )
999         {
1000             /* We need the intra costs for row SATDs. */
1001             x264_slicetype_frame_cost( h, &a, frames, b, b, b, 0 );
1002
1003             /* We need B-frame costs for row SATDs. */
1004             for( i = 0; i < bframes; i++ )
1005             {
1006                 b = bframes - i;
1007                 frames[b] = h->lookahead->next.list[i];
1008                 x264_slicetype_frame_cost( h, &a, frames, p0, p1, b, 0 );
1009             }
1010         }
1011     }
1012 }
1013
1014 int x264_rc_analyse_slice( x264_t *h )
1015 {
1016     x264_frame_t *frames[X264_BFRAME_MAX+2] = { NULL, };
1017     int p0=0, p1, b;
1018     int cost;
1019
1020     if( IS_X264_TYPE_I(h->fenc->i_type) )
1021         p1 = b = 0;
1022     else if( h->fenc->i_type == X264_TYPE_P )
1023         p1 = b = h->fenc->i_bframes + 1;
1024     else //B
1025     {
1026         p1 = (h->fref1[0]->i_poc - h->fref0[0]->i_poc)/2;
1027         b  = (h->fref1[0]->i_poc - h->fenc->i_poc)/2;
1028         frames[p1] = h->fref1[0];
1029     }
1030     frames[p0] = h->fref0[0];
1031     frames[b] = h->fenc;
1032
1033     /* cost should have been already calculated by x264_slicetype_decide */
1034     cost = frames[b]->i_cost_est[b-p0][p1-b];
1035     assert( cost >= 0 );
1036
1037     if( h->param.rc.b_mb_tree && !h->param.rc.b_stat_read )
1038     {
1039         cost = x264_slicetype_frame_cost_recalculate( h, frames, p0, p1, b );
1040         if( b && h->param.rc.i_vbv_buffer_size )
1041             x264_slicetype_frame_cost_recalculate( h, frames, b, b, b );
1042     }
1043     /* In AQ, use the weighted score instead. */
1044     else if( h->param.rc.i_aq_mode )
1045         cost = frames[b]->i_cost_est_aq[b-p0][p1-b];
1046
1047     h->fenc->i_row_satd = h->fenc->i_row_satds[b-p0][p1-b];
1048     h->fdec->i_row_satd = h->fdec->i_row_satds[b-p0][p1-b];
1049     h->fdec->i_satd = cost;
1050     memcpy( h->fdec->i_row_satd, h->fenc->i_row_satd, h->sps->i_mb_height * sizeof(int) );
1051     if( !IS_X264_TYPE_I(h->fenc->i_type) )
1052         memcpy( h->fdec->i_row_satds[0][0], h->fenc->i_row_satds[0][0], h->sps->i_mb_height * sizeof(int) );
1053     return cost;
1054 }