]> git.sesse.net Git - x264/blob - encoder/slicetype.c
Fix delay calculation with multiple threads
[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 #include <limits.h>
26
27 #include "common/common.h"
28 #include "common/cpu.h"
29 #include "macroblock.h"
30 #include "me.h"
31
32
33 static void x264_lowres_context_init( x264_t *h, x264_mb_analysis_t *a )
34 {
35     a->i_qp = 12; // arbitrary, but low because SATD scores are 1/4 normal
36     a->i_lambda = x264_lambda_tab[ a->i_qp ];
37     x264_mb_analyse_load_costs( h, a );
38     h->mb.i_me_method = X264_MIN( X264_ME_HEX, h->param.analyse.i_me_method ); // maybe dia?
39     h->mb.i_subpel_refine = 4; // 3 should be enough, but not tweaking for speed now
40     h->mb.b_chroma_me = 0;
41 }
42
43 static int x264_slicetype_mb_cost( x264_t *h, x264_mb_analysis_t *a,
44                             x264_frame_t **frames, int p0, int p1, int b,
45                             int dist_scale_factor, int do_search[2] )
46 {
47     x264_frame_t *fref0 = frames[p0];
48     x264_frame_t *fref1 = frames[p1];
49     x264_frame_t *fenc  = frames[b];
50     const int b_bidir = (b < p1);
51     const int i_mb_x = h->mb.i_mb_x;
52     const int i_mb_y = h->mb.i_mb_y;
53     const int i_mb_stride = h->sps->i_mb_width;
54     const int i_mb_xy = i_mb_x + i_mb_y * i_mb_stride;
55     const int i_stride = fenc->i_stride_lowres;
56     const int i_pel_offset = 8 * ( i_mb_x + i_mb_y * i_stride );
57     const int i_bipred_weight = h->param.analyse.b_weighted_bipred ? 64 - (dist_scale_factor>>2) : 32;
58     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] };
59     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] };
60
61     DECLARE_ALIGNED_8( uint8_t pix1[9*FDEC_STRIDE] );
62     uint8_t *pix2 = pix1+8;
63     x264_me_t m[2];
64     int i_bcost = COST_MAX;
65     int l, i;
66     int list_used = 0;
67
68     h->mb.pic.p_fenc[0] = h->mb.pic.fenc_buf;
69     h->mc.copy[PIXEL_8x8]( h->mb.pic.p_fenc[0], FENC_STRIDE, &fenc->lowres[0][i_pel_offset], i_stride, 8 );
70
71     if( !p0 && !p1 && !b )
72         goto lowres_intra_mb;
73
74     // no need for h->mb.mv_min[]
75     h->mb.mv_min_fpel[0] = -8*h->mb.i_mb_x - 4;
76     h->mb.mv_max_fpel[0] = 8*( h->sps->i_mb_width - h->mb.i_mb_x - 1 ) + 4;
77     h->mb.mv_min_spel[0] = 4*( h->mb.mv_min_fpel[0] - 8 );
78     h->mb.mv_max_spel[0] = 4*( h->mb.mv_max_fpel[0] + 8 );
79     if( h->mb.i_mb_x >= h->sps->i_mb_width - 2 )
80     {
81         h->mb.mv_min_fpel[1] = -8*h->mb.i_mb_y - 4;
82         h->mb.mv_max_fpel[1] = 8*( h->sps->i_mb_height - h->mb.i_mb_y - 1 ) + 4;
83         h->mb.mv_min_spel[1] = 4*( h->mb.mv_min_fpel[1] - 8 );
84         h->mb.mv_max_spel[1] = 4*( h->mb.mv_max_fpel[1] + 8 );
85     }
86
87 #define LOAD_HPELS_LUMA(dst, src) \
88     { \
89         (dst)[0] = &(src)[0][i_pel_offset]; \
90         (dst)[1] = &(src)[1][i_pel_offset]; \
91         (dst)[2] = &(src)[2][i_pel_offset]; \
92         (dst)[3] = &(src)[3][i_pel_offset]; \
93     }
94 #define CLIP_MV( mv ) \
95     { \
96         mv[0] = x264_clip3( mv[0], h->mb.mv_min_spel[0], h->mb.mv_max_spel[0] ); \
97         mv[1] = x264_clip3( mv[1], h->mb.mv_min_spel[1], h->mb.mv_max_spel[1] ); \
98     }
99 #define TRY_BIDIR( mv0, mv1, penalty ) \
100     { \
101         int stride1 = 16, stride2 = 16; \
102         uint8_t *src1, *src2; \
103         int i_cost; \
104         src1 = h->mc.get_ref( pix1, &stride1, m[0].p_fref, m[0].i_stride[0], \
105                               (mv0)[0], (mv0)[1], 8, 8 ); \
106         src2 = h->mc.get_ref( pix2, &stride2, m[1].p_fref, m[1].i_stride[0], \
107                               (mv1)[0], (mv1)[1], 8, 8 ); \
108         h->mc.avg[PIXEL_8x8]( pix1, 16, src1, stride1, src2, stride2, i_bipred_weight ); \
109         i_cost = penalty + h->pixf.mbcmp[PIXEL_8x8]( \
110                            m[0].p_fenc[0], FENC_STRIDE, pix1, 16 ); \
111         COPY2_IF_LT( i_bcost, i_cost, list_used, 3 ); \
112     }
113
114     m[0].i_pixel = PIXEL_8x8;
115     m[0].p_cost_mv = a->p_cost_mv;
116     m[0].i_stride[0] = i_stride;
117     m[0].p_fenc[0] = h->mb.pic.p_fenc[0];
118     LOAD_HPELS_LUMA( m[0].p_fref, fref0->lowres );
119
120     if( b_bidir )
121     {
122         int16_t *mvr = fref1->lowres_mvs[0][p1-p0-1][i_mb_xy];
123         int dmv[2][2];
124
125         h->mc.memcpy_aligned( &m[1], &m[0], sizeof(x264_me_t) );
126         LOAD_HPELS_LUMA( m[1].p_fref, fref1->lowres );
127
128         dmv[0][0] = ( mvr[0] * dist_scale_factor + 128 ) >> 8;
129         dmv[0][1] = ( mvr[1] * dist_scale_factor + 128 ) >> 8;
130         dmv[1][0] = dmv[0][0] - mvr[0];
131         dmv[1][1] = dmv[0][1] - mvr[1];
132         CLIP_MV( dmv[0] );
133         CLIP_MV( dmv[1] );
134
135         TRY_BIDIR( dmv[0], dmv[1], 0 );
136         if( dmv[0][0] | dmv[0][1] | dmv[1][0] | dmv[1][1] )
137         {
138             int i_cost;
139             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 );
140             i_cost = h->pixf.mbcmp[PIXEL_8x8]( m[0].p_fenc[0], FENC_STRIDE, pix1, 16 );
141             COPY2_IF_LT( i_bcost, i_cost, list_used, 3 );
142         }
143     }
144
145     for( l = 0; l < 1 + b_bidir; l++ )
146     {
147         if( do_search[l] )
148         {
149             int i_mvc = 0;
150             int16_t (*fenc_mv)[2] = fenc_mvs[l];
151             DECLARE_ALIGNED_4( int16_t mvc[4][2] );
152
153             /* Reverse-order MV prediction. */
154             *(uint32_t*)mvc[0] = 0;
155             *(uint32_t*)mvc[1] = 0;
156             *(uint32_t*)mvc[2] = 0;
157 #define MVC(mv) { *(uint32_t*)mvc[i_mvc] = *(uint32_t*)mv; i_mvc++; }
158             if( i_mb_x < h->sps->i_mb_width - 1 )
159                 MVC(fenc_mv[1]);
160             if( i_mb_y < h->sps->i_mb_height - 1 )
161             {
162                 MVC(fenc_mv[i_mb_stride]);
163                 if( i_mb_x > 0 )
164                     MVC(fenc_mv[i_mb_stride-1]);
165                 if( i_mb_x < h->sps->i_mb_width - 1 )
166                     MVC(fenc_mv[i_mb_stride+1]);
167             }
168 #undef MVC
169             x264_median_mv( m[l].mvp, mvc[0], mvc[1], mvc[2] );
170             x264_me_search( h, &m[l], mvc, i_mvc );
171
172             m[l].cost -= 2; // remove mvcost from skip mbs
173             if( *(uint32_t*)m[l].mv )
174                 m[l].cost += 5;
175             *(uint32_t*)fenc_mvs[l] = *(uint32_t*)m[l].mv;
176             *fenc_costs[l] = m[l].cost;
177         }
178         else
179         {
180             *(uint32_t*)m[l].mv = *(uint32_t*)fenc_mvs[l];
181             m[l].cost = *fenc_costs[l];
182         }
183         COPY2_IF_LT( i_bcost, m[l].cost, list_used, l+1 );
184     }
185
186     if( b_bidir && ( *(uint32_t*)m[0].mv || *(uint32_t*)m[1].mv ) )
187         TRY_BIDIR( m[0].mv, m[1].mv, 5 );
188
189     frames[b]->lowres_inter_types[b-p0][p1-b][i_mb_xy] = list_used;
190
191 lowres_intra_mb:
192     /* forbid intra-mbs in B-frames, because it's rare and not worth checking */
193     /* FIXME: Should we still forbid them now that we cache intra scores? */
194     if( !b_bidir || h->param.rc.b_mb_tree )
195     {
196         int i_icost, b_intra;
197         if( !fenc->b_intra_calculated )
198         {
199             DECLARE_ALIGNED_16( uint8_t edge[33] );
200             uint8_t *pix = &pix1[8+FDEC_STRIDE - 1];
201             uint8_t *src = &fenc->lowres[0][i_pel_offset - 1];
202             const int intra_penalty = 5;
203             int satds[4];
204
205             memcpy( pix-FDEC_STRIDE, src-i_stride, 17 );
206             for( i=0; i<8; i++ )
207                 pix[i*FDEC_STRIDE] = src[i*i_stride];
208             pix++;
209
210             if( h->pixf.intra_mbcmp_x3_8x8c )
211             {
212                 h->pixf.intra_mbcmp_x3_8x8c( h->mb.pic.p_fenc[0], pix, satds );
213                 h->predict_8x8c[I_PRED_CHROMA_P]( pix );
214                 satds[I_PRED_CHROMA_P] =
215                     h->pixf.mbcmp[PIXEL_8x8]( pix, FDEC_STRIDE, h->mb.pic.p_fenc[0], FENC_STRIDE );
216             }
217             else
218             {
219                 for( i=0; i<4; i++ )
220                 {
221                     h->predict_8x8c[i]( pix );
222                     satds[i] = h->pixf.mbcmp[PIXEL_8x8]( pix, FDEC_STRIDE, h->mb.pic.p_fenc[0], FENC_STRIDE );
223                 }
224             }
225             i_icost = X264_MIN4( satds[0], satds[1], satds[2], satds[3] );
226
227             h->predict_8x8_filter( pix, edge, ALL_NEIGHBORS, ALL_NEIGHBORS );
228             for( i=3; i<9; i++ )
229             {
230                 int satd;
231                 h->predict_8x8[i]( pix, edge );
232                 satd = h->pixf.mbcmp[PIXEL_8x8]( pix, FDEC_STRIDE, h->mb.pic.p_fenc[0], FENC_STRIDE );
233                 i_icost = X264_MIN( i_icost, satd );
234             }
235
236             i_icost += intra_penalty;
237             fenc->i_intra_cost[i_mb_xy] = i_icost;
238         }
239         else
240             i_icost = fenc->i_intra_cost[i_mb_xy];
241         if( !b_bidir )
242         {
243             b_intra = i_icost < i_bcost;
244             if( b_intra )
245                 i_bcost = i_icost;
246             if(   (i_mb_x > 0 && i_mb_x < h->sps->i_mb_width - 1
247                 && i_mb_y > 0 && i_mb_y < h->sps->i_mb_height - 1)
248                 || h->sps->i_mb_width <= 2 || h->sps->i_mb_height <= 2 )
249             {
250                 fenc->i_intra_mbs[b-p0] += b_intra;
251                 fenc->i_cost_est[0][0] += i_icost;
252             }
253         }
254     }
255
256     frames[b]->lowres_costs[b-p0][p1-b][i_mb_xy] = i_bcost;
257
258     return i_bcost;
259 }
260 #undef TRY_BIDIR
261
262 #define NUM_MBS\
263    (h->sps->i_mb_width > 2 && h->sps->i_mb_height > 2 ?\
264    (h->sps->i_mb_width - 2) * (h->sps->i_mb_height - 2) :\
265     h->sps->i_mb_width * h->sps->i_mb_height)
266
267 static int x264_slicetype_frame_cost( x264_t *h, x264_mb_analysis_t *a,
268                                x264_frame_t **frames, int p0, int p1, int b,
269                                int b_intra_penalty )
270 {
271
272     int i_score = 0;
273     /* Don't use the AQ'd scores for slicetype decision. */
274     int i_score_aq = 0;
275     int do_search[2];
276
277     /* Check whether we already evaluated this frame
278      * If we have tried this frame as P, then we have also tried
279      * the preceding frames as B. (is this still true?) */
280     /* Also check that we already calculated the row SATDs for the current frame. */
281     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) )
282     {
283         i_score = frames[b]->i_cost_est[b-p0][p1-b];
284     }
285     else
286     {
287         int dist_scale_factor = 128;
288         int *row_satd = frames[b]->i_row_satds[b-p0][p1-b];
289
290         /* For each list, check to see whether we have lowres motion-searched this reference frame before. */
291         do_search[0] = b != p0 && frames[b]->lowres_mvs[0][b-p0-1][0][0] == 0x7FFF;
292         do_search[1] = b != p1 && frames[b]->lowres_mvs[1][p1-b-1][0][0] == 0x7FFF;
293         if( do_search[0] ) frames[b]->lowres_mvs[0][b-p0-1][0][0] = 0;
294         if( do_search[1] ) frames[b]->lowres_mvs[1][p1-b-1][0][0] = 0;
295
296         if( b == p1 )
297         {
298             frames[b]->i_intra_mbs[b-p0] = 0;
299             frames[b]->i_cost_est[0][0] = 0;
300         }
301         if( p1 != p0 )
302             dist_scale_factor = ( ((b-p0) << 8) + ((p1-p0) >> 1) ) / (p1-p0);
303
304         /* Lowres lookahead goes backwards because the MVs are used as predictors in the main encode.
305          * This considerably improves MV prediction overall. */
306
307         /* the edge mbs seem to reduce the predictive quality of the
308          * whole frame's score, but are needed for a spatial distribution. */
309         if( h->param.rc.b_mb_tree || h->param.rc.i_vbv_buffer_size ||
310             h->sps->i_mb_width <= 2 || h->sps->i_mb_height <= 2 )
311         {
312             for( h->mb.i_mb_y = h->sps->i_mb_height - 1; h->mb.i_mb_y >= 0; h->mb.i_mb_y-- )
313             {
314                 row_satd[ h->mb.i_mb_y ] = 0;
315                 for( h->mb.i_mb_x = h->sps->i_mb_width - 1; h->mb.i_mb_x >= 0; h->mb.i_mb_x-- )
316                 {
317                     int i_mb_cost = x264_slicetype_mb_cost( h, a, frames, p0, p1, b, dist_scale_factor, do_search );
318                     int i_mb_cost_aq = i_mb_cost;
319                     if( h->param.rc.i_aq_mode )
320                         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;
321                     row_satd[ h->mb.i_mb_y ] += i_mb_cost_aq;
322                     if( (h->mb.i_mb_y > 0 && h->mb.i_mb_y < h->sps->i_mb_height - 1 &&
323                          h->mb.i_mb_x > 0 && h->mb.i_mb_x < h->sps->i_mb_width - 1) ||
324                          h->sps->i_mb_width <= 2 || h->sps->i_mb_height <= 2 )
325                     {
326                         /* Don't use AQ-weighted costs for slicetype decision, only for ratecontrol. */
327                         i_score += i_mb_cost;
328                         i_score_aq += i_mb_cost_aq;
329                     }
330                 }
331             }
332         }
333         else
334         {
335             for( h->mb.i_mb_y = h->sps->i_mb_height - 2; h->mb.i_mb_y > 0; h->mb.i_mb_y-- )
336                 for( h->mb.i_mb_x = h->sps->i_mb_width - 2; h->mb.i_mb_x > 0; h->mb.i_mb_x-- )
337                 {
338                     int i_mb_cost = x264_slicetype_mb_cost( h, a, frames, p0, p1, b, dist_scale_factor, do_search );
339                     int i_mb_cost_aq = i_mb_cost;
340                     if( h->param.rc.i_aq_mode )
341                         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;
342                     i_score += i_mb_cost;
343                     i_score_aq += i_mb_cost_aq;
344                 }
345         }
346
347         if( b != p1 )
348             i_score = i_score * 100 / (120 + h->param.i_bframe_bias);
349         else
350             frames[b]->b_intra_calculated = 1;
351
352         frames[b]->i_cost_est[b-p0][p1-b] = i_score;
353         frames[b]->i_cost_est_aq[b-p0][p1-b] = i_score_aq;
354         x264_emms();
355     }
356
357     if( b_intra_penalty )
358     {
359         // arbitrary penalty for I-blocks after B-frames
360         int nmb = NUM_MBS;
361         i_score += i_score * frames[b]->i_intra_mbs[b-p0] / (nmb * 8);
362     }
363     return i_score;
364 }
365
366 /* If MB-tree changes the quantizers, we need to recalculate the frame cost without
367  * re-running lookahead. */
368 static int x264_slicetype_frame_cost_recalculate( x264_t *h, x264_mb_analysis_t *a, x264_frame_t **frames,
369                                                   int p0, int p1, int b )
370 {
371     int i_score = 0;
372     int *row_satd = frames[b]->i_row_satds[b-p0][p1-b];
373     x264_emms();
374     for( h->mb.i_mb_y = h->sps->i_mb_height - 1; h->mb.i_mb_y >= 0; h->mb.i_mb_y-- )
375     {
376         row_satd[ h->mb.i_mb_y ] = 0;
377         for( h->mb.i_mb_x = h->sps->i_mb_width - 1; h->mb.i_mb_x >= 0; h->mb.i_mb_x-- )
378         {
379             int i_mb_xy = h->mb.i_mb_x + h->mb.i_mb_y*h->mb.i_mb_stride;
380             int i_mb_cost = frames[b]->lowres_costs[b-p0][p1-b][i_mb_xy];
381             float qp_adj = frames[b]->f_qp_offset[i_mb_xy];
382             i_mb_cost = (i_mb_cost * x264_exp2fix8(qp_adj*(-1.f/6.f)) + 128) >> 8;
383             row_satd[ h->mb.i_mb_y ] += i_mb_cost;
384             if( (h->mb.i_mb_y > 0 && h->mb.i_mb_y < h->sps->i_mb_height - 1 &&
385                  h->mb.i_mb_x > 0 && h->mb.i_mb_x < h->sps->i_mb_width - 1) ||
386                  h->sps->i_mb_width <= 2 || h->sps->i_mb_height <= 2 )
387             {
388                 i_score += i_mb_cost;
389             }
390         }
391     }
392     return i_score;
393 }
394
395 static void x264_macroblock_tree_propagate( x264_t *h, x264_frame_t **frames, int p0, int p1, int b )
396 {
397     x264_frame_t *refs[2] = {frames[p0],frames[p1]};
398     int dist_scale_factor = p1 != p0 ? 128 : ( ((b-p0) << 8) + ((p1-p0) >> 1) ) / (p1-p0);
399     int i_bipred_weight = h->param.analyse.b_weighted_bipred ? 64 - (dist_scale_factor>>2) : 32;
400
401     for( h->mb.i_mb_y = 0; h->mb.i_mb_y < h->sps->i_mb_height; h->mb.i_mb_y++ )
402     {
403         for( h->mb.i_mb_x = 0; h->mb.i_mb_x < h->sps->i_mb_width; h->mb.i_mb_x++ )
404         {
405             int mb_index = h->mb.i_mb_x + h->mb.i_mb_y*h->mb.i_mb_stride;
406             int inter_cost = frames[b]->lowres_costs[b-p0][p1-b][mb_index];
407             int intra_cost = (frames[b]->i_intra_cost[mb_index] * frames[b]->i_inv_qscale_factor[mb_index]+128)>>8;
408             int lists_used = frames[b]->lowres_inter_types[b-p0][p1-b][mb_index];
409             /* The approximate amount of data that this block contains. */
410             int propagate_amount = intra_cost + frames[b]->i_propagate_cost[mb_index];
411
412             /* Divide by 64 for per-pixel summing. */
413             propagate_amount = (((uint64_t)propagate_amount*(intra_cost-inter_cost)) / intra_cost + 32) >> 6;
414
415             /* Don't propagate for an intra block. */
416             if( inter_cost < intra_cost )
417             {
418                 int mv[2][2], list;
419                 mv[0][0] = frames[b]->lowres_mvs[0][b-p0-1][mb_index][0];
420                 mv[0][1] = frames[b]->lowres_mvs[0][b-p0-1][mb_index][1];
421                 if( b != p1 )
422                 {
423                     mv[1][0] = frames[b]->lowres_mvs[1][p1-b-1][mb_index][0];
424                     mv[1][1] = frames[b]->lowres_mvs[1][p1-b-1][mb_index][1];
425                 }
426
427                 /* Follow the MVs to the previous frame(s). */
428                 for( list = 0; list < 2; list++ )
429                     if( (lists_used >> list)&1 )
430                     {
431                         int x = mv[list][0];
432                         int y = mv[list][1];
433                         int listamount = propagate_amount;
434                         int mbx = (x>>5)+h->mb.i_mb_x;
435                         int mby = ((y>>5)+h->mb.i_mb_y);
436                         int idx0 = mbx + mby*h->mb.i_mb_stride;
437                         int idx1 = idx0 + 1;
438                         int idx2 = idx0 + h->mb.i_mb_stride;
439                         int idx3 = idx0 + h->mb.i_mb_stride + 1;
440                         int idx0weight = (32-(y&31))*(32-(x&31));
441                         int idx1weight = (32-(y&31))*(x&31);
442                         int idx2weight = (y&31)*(32-(x&31));
443                         int idx3weight = (y&31)*(x&31);
444
445                         /* Apply bipred weighting. */
446                         if( lists_used == 3 )
447                             listamount = (listamount * (list?(64-i_bipred_weight):i_bipred_weight) + 32) >> 6;
448
449 #define CLIP_ADD(s,x) (s) = X264_MIN((s)+(x),(1<<16)-1)
450
451                         /* We could just clip the MVs, but pixels that lie outside the frame probably shouldn't
452                          * be counted. */
453                         if( mbx < h->sps->i_mb_width-1 && mby < h->sps->i_mb_height-1 && mbx >= 0 && mby >= 0 )
454                         {
455                             CLIP_ADD( refs[list]->i_propagate_cost[idx0], (listamount*idx0weight+8)>>4 );
456                             CLIP_ADD( refs[list]->i_propagate_cost[idx1], (listamount*idx1weight+8)>>4 );
457                             CLIP_ADD( refs[list]->i_propagate_cost[idx2], (listamount*idx2weight+8)>>4 );
458                             CLIP_ADD( refs[list]->i_propagate_cost[idx3], (listamount*idx3weight+8)>>4 );
459                         }
460                         else /* Check offsets individually */
461                         {
462                             if( mbx < h->sps->i_mb_width && mby < h->sps->i_mb_height && mbx >= 0 && mby >= 0 )
463                                 CLIP_ADD( refs[list]->i_propagate_cost[idx0], (listamount*idx0weight+8)>>4 );
464                             if( mbx+1 < h->sps->i_mb_width && mby < h->sps->i_mb_height && mbx+1 >= 0 && mby >= 0 )
465                                 CLIP_ADD( refs[list]->i_propagate_cost[idx1], (listamount*idx1weight+8)>>4 );
466                             if( mbx < h->sps->i_mb_width && mby+1 < h->sps->i_mb_height && mbx >= 0 && mby+1 >= 0 )
467                                 CLIP_ADD( refs[list]->i_propagate_cost[idx2], (listamount*idx2weight+8)>>4 );
468                             if( mbx+1 < h->sps->i_mb_width && mby+1 < h->sps->i_mb_height && mbx+1 >= 0 && mby+1 >= 0 )
469                                 CLIP_ADD( refs[list]->i_propagate_cost[idx3], (listamount*idx3weight+8)>>4 );
470                         }
471                     }
472             }
473         }
474     }
475 }
476
477 static void x264_macroblock_tree( x264_t *h, x264_mb_analysis_t *a, x264_frame_t **frames, int num_frames, int b_intra )
478 {
479     int i, idx = !b_intra;
480     int last_nonb, cur_nonb = 1;
481     if( b_intra )
482        x264_slicetype_frame_cost( h, a, frames, 0, 0, 0, 0 );
483
484     i = num_frames-1;
485     while( i > 0 && frames[i]->i_type == X264_TYPE_B )
486         i--;
487     last_nonb = i;
488
489     if( last_nonb < 0 )
490         return;
491
492     memset( frames[last_nonb]->i_propagate_cost, 0, h->mb.i_mb_count * sizeof(uint32_t) );
493     while( i-- > idx )
494     {
495         cur_nonb = i;
496         while( frames[cur_nonb]->i_type == X264_TYPE_B && cur_nonb > 0 )
497             cur_nonb--;
498         if( cur_nonb < idx )
499             break;
500         x264_slicetype_frame_cost( h, a, frames, cur_nonb, last_nonb, last_nonb, 0 );
501         memset( frames[cur_nonb]->i_propagate_cost, 0, h->mb.i_mb_count * sizeof(uint32_t) );
502         x264_macroblock_tree_propagate( h, frames, cur_nonb, last_nonb, last_nonb );
503         while( frames[i]->i_type == X264_TYPE_B && i > 0 )
504         {
505             x264_slicetype_frame_cost( h, a, frames, cur_nonb, last_nonb, i, 0 );
506             memset( frames[i]->i_propagate_cost, 0, h->mb.i_mb_count * sizeof(uint32_t) );
507             x264_macroblock_tree_propagate( h, frames, cur_nonb, last_nonb, i );
508             i--;
509         }
510         last_nonb = cur_nonb;
511     }
512     x264_emms();
513
514     for( h->mb.i_mb_y = 0; h->mb.i_mb_y < h->sps->i_mb_height; h->mb.i_mb_y++ )
515     {
516         for( h->mb.i_mb_x = 0; h->mb.i_mb_x < h->sps->i_mb_width; h->mb.i_mb_x++ )
517         {
518             int mb_index = h->mb.i_mb_x + h->mb.i_mb_y*h->mb.i_mb_stride;
519             int intra_cost = (frames[last_nonb]->i_intra_cost[mb_index] * frames[last_nonb]->i_inv_qscale_factor[mb_index]+128)>>8;
520
521             if( intra_cost )
522             {
523                 int propagate_cost = frames[last_nonb]->i_propagate_cost[mb_index];
524                 float log2_ratio = x264_log2(intra_cost + propagate_cost) - x264_log2(intra_cost);
525                 /* Allow the constant to be adjusted via qcompress, since the two
526                  * concepts are very similar. */
527                 frames[last_nonb]->f_qp_offset[mb_index] -= 5.0 * (1.0 - h->param.rc.f_qcompress) * log2_ratio;
528             }
529         }
530     }
531 }
532
533 static int x264_slicetype_path_cost( x264_t *h, x264_mb_analysis_t *a, x264_frame_t **frames, char *path, int threshold )
534 {
535     int loc = 1;
536     int cost = 0;
537     int cur_p = 0;
538     path--; /* Since the 1st path element is really the second frame */
539     while( path[loc] )
540     {
541         int next_p = loc;
542         int next_b;
543         /* Find the location of the next P-frame. */
544         while( path[next_p] && path[next_p] != 'P' )
545             next_p++;
546         /* Return if the path doesn't end on a P-frame. */
547         if( path[next_p] != 'P' )
548             return cost;
549
550         /* Add the cost of the P-frame found above */
551         cost += x264_slicetype_frame_cost( h, a, frames, cur_p, next_p, next_p, 0 );
552         /* Early terminate if the cost we have found is larger than the best path cost so far */
553         if( cost > threshold )
554             break;
555
556         for( next_b = loc; next_b < next_p && cost < threshold; next_b++ )
557             cost += x264_slicetype_frame_cost( h, a, frames, cur_p, next_p, next_b, 0 );
558
559         loc = next_p + 1;
560         cur_p = next_p;
561     }
562     return cost;
563 }
564
565 /* Viterbi/trellis slicetype decision algorithm. */
566 /* Uses strings due to the fact that the speed of the control functions is
567    negligable compared to the cost of running slicetype_frame_cost, and because
568    it makes debugging easier. */
569 static void x264_slicetype_path( x264_t *h, x264_mb_analysis_t *a, x264_frame_t **frames, int length, int max_bframes, int buffer_size, char (*best_paths)[X264_LOOKAHEAD_MAX] )
570 {
571     char paths[X264_BFRAME_MAX+2][X264_LOOKAHEAD_MAX] = {{0}};
572     int num_paths = X264_MIN(max_bframes+1, length);
573     int suffix_size, loc, path;
574     int best_cost = COST_MAX;
575     int best_path_index = 0;
576     length = X264_MIN(length,X264_LOOKAHEAD_MAX);
577
578     /* Iterate over all currently possible paths and add suffixes to each one */
579     for( suffix_size = 0; suffix_size < num_paths; suffix_size++ )
580     {
581         memcpy( paths[suffix_size], best_paths[length - (suffix_size + 1)], length - (suffix_size + 1) );
582         for( loc = 0; loc < suffix_size; loc++ )
583             strcat( paths[suffix_size], "B" );
584         strcat( paths[suffix_size], "P" );
585     }
586
587     /* Calculate the actual cost of each of the current paths */
588     for( path = 0; path < num_paths; path++ )
589     {
590         int cost = x264_slicetype_path_cost( h, a, frames, paths[path], best_cost );
591         if( cost < best_cost )
592         {
593             best_cost = cost;
594             best_path_index = path;
595         }
596     }
597
598     /* Store the best path. */
599     memcpy( best_paths[length], paths[best_path_index], length );
600 }
601
602 static int scenecut( x264_t *h, x264_mb_analysis_t *a, x264_frame_t **frames, int p0, int p1 )
603 {
604     x264_frame_t *frame = frames[p1];
605     x264_slicetype_frame_cost( h, a, frames, p0, p1, p1, 0 );
606
607     int icost = frame->i_cost_est[0][0];
608     int pcost = frame->i_cost_est[p1-p0][0];
609     float f_bias;
610     int i_gop_size = frame->i_frame - h->frames.i_last_idr;
611     float f_thresh_max = h->param.i_scenecut_threshold / 100.0;
612     /* magic numbers pulled out of thin air */
613     float f_thresh_min = f_thresh_max * h->param.i_keyint_min
614                          / ( h->param.i_keyint_max * 4 );
615     int res;
616
617     if( h->param.i_keyint_min == h->param.i_keyint_max )
618         f_thresh_min= f_thresh_max;
619     if( i_gop_size < h->param.i_keyint_min / 4 )
620         f_bias = f_thresh_min / 4;
621     else if( i_gop_size <= h->param.i_keyint_min )
622         f_bias = f_thresh_min * i_gop_size / h->param.i_keyint_min;
623     else
624     {
625         f_bias = f_thresh_min
626                  + ( f_thresh_max - f_thresh_min )
627                     * ( i_gop_size - h->param.i_keyint_min )
628                    / ( h->param.i_keyint_max - h->param.i_keyint_min ) ;
629     }
630
631     res = pcost >= (1.0 - f_bias) * icost;
632     if( res )
633     {
634         int imb = frame->i_intra_mbs[p1-p0];
635         int pmb = NUM_MBS - imb;
636         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",
637                   frame->i_frame,
638                   icost, pcost, 1. - (double)pcost / icost,
639                   f_bias, i_gop_size, imb, pmb );
640     }
641     return res;
642 }
643
644 static void x264_slicetype_analyse( x264_t *h, int keyframe )
645 {
646     x264_mb_analysis_t a;
647     x264_frame_t *frames[X264_LOOKAHEAD_MAX+3] = { NULL, };
648     int num_frames;
649     int keyint_limit;
650     int i,j;
651     int i_mb_count = NUM_MBS;
652     int cost1p0, cost2p0, cost1b1, cost2p1;
653     int idr_frame_type;
654
655     assert( h->frames.b_have_lowres );
656
657     if( !h->frames.last_nonb )
658         return;
659     frames[0] = h->frames.last_nonb;
660     for( j = 0; h->frames.next[j] && h->frames.next[j]->i_type == X264_TYPE_AUTO; j++ )
661         frames[j+1] = h->frames.next[j];
662     keyint_limit = h->param.i_keyint_max - frames[0]->i_frame + h->frames.i_last_idr - 1;
663     num_frames = X264_MIN( j, keyint_limit );
664
665     if( num_frames == 0 && (!j || !h->param.rc.b_mb_tree) )
666         return;
667
668     x264_lowres_context_init( h, &a );
669     idr_frame_type = frames[1]->i_frame - h->frames.i_last_idr >= h->param.i_keyint_min ? X264_TYPE_IDR : X264_TYPE_I;
670
671     if( num_frames == 1 && !h->param.rc.b_mb_tree )
672     {
673         frames[1]->i_type = X264_TYPE_P;
674         if( h->param.i_scenecut_threshold && scenecut( h, &a, frames, 0, 1 ) )
675             frames[1]->i_type = idr_frame_type;
676         return;
677     }
678
679     /* This is important psy-wise: if we have a non-scenecut keyframe,
680      * there will be significant visual artifacts if the frames just before
681      * go down in quality due to being referenced less, despite it being
682      * more RD-optimal. */
683     if( h->param.analyse.b_psy && h->param.rc.b_mb_tree )
684         num_frames = j;
685
686     char best_paths[X264_LOOKAHEAD_MAX][X264_LOOKAHEAD_MAX] = {"","P"};
687     int n;
688     int num_bframes = 0;
689     int max_bframes = X264_MIN(num_frames-1, h->param.i_bframe);
690     int num_analysed_frames = num_frames;
691     int reset_start;
692     if( h->param.i_scenecut_threshold && scenecut( h, &a, frames, 0, 1 ) )
693     {
694         frames[1]->i_type = idr_frame_type;
695         return;
696     }
697
698     if( h->param.i_bframe )
699     {
700         if( h->param.i_bframe_adaptive == X264_B_ADAPT_TRELLIS )
701         {
702             /* Perform the frametype analysis. */
703             for( n = 2; n < num_frames-1; n++ )
704                 x264_slicetype_path( h, &a, frames, n, max_bframes, num_frames-max_bframes, best_paths );
705             num_bframes = strspn( best_paths[num_frames-2], "B" );
706             /* Load the results of the analysis into the frame types. */
707             for( j = 1; j < num_frames; j++ )
708                 frames[j]->i_type = best_paths[num_frames-2][j-1] == 'B' ? X264_TYPE_B : X264_TYPE_P;
709             frames[num_frames]->i_type = X264_TYPE_P;
710         }
711         else if( h->param.i_bframe_adaptive == X264_B_ADAPT_FAST )
712         {
713             for( i = 0; i < num_frames-(2-!i); )
714             {
715                 cost2p1 = x264_slicetype_frame_cost( h, &a, frames, i+0, i+2, i+2, 1 );
716                 if( frames[i+2]->i_intra_mbs[2] > i_mb_count / 2 )
717                 {
718                     frames[i+1]->i_type = X264_TYPE_P;
719                     frames[i+2]->i_type = X264_TYPE_P;
720                     i += 2;
721                     continue;
722                 }
723
724                 cost1b1 = x264_slicetype_frame_cost( h, &a, frames, i+0, i+2, i+1, 0 );
725                 cost1p0 = x264_slicetype_frame_cost( h, &a, frames, i+0, i+1, i+1, 0 );
726                 cost2p0 = x264_slicetype_frame_cost( h, &a, frames, i+1, i+2, i+2, 0 );
727
728                 if( cost1p0 + cost2p0 < cost1b1 + cost2p1 )
729                 {
730                     frames[i+1]->i_type = X264_TYPE_P;
731                     frames[i+2]->i_type = X264_TYPE_P;
732                     i += 2;
733                     continue;
734                 }
735
736                 // arbitrary and untuned
737                 #define INTER_THRESH 300
738                 #define P_SENS_BIAS (50 - h->param.i_bframe_bias)
739                 frames[i+1]->i_type = X264_TYPE_B;
740                 frames[i+2]->i_type = X264_TYPE_P;
741
742                 for( j = i+2; j <= X264_MIN( h->param.i_bframe, num_frames-2 ); j++ )
743                 {
744                     int pthresh = X264_MAX(INTER_THRESH - P_SENS_BIAS * (j-i-1), INTER_THRESH/10);
745                     int pcost = x264_slicetype_frame_cost( h, &a, frames, i+0, j+1, j+1, 1 );
746
747                     if( pcost > pthresh*i_mb_count || frames[j+1]->i_intra_mbs[j-i+1] > i_mb_count/3 )
748                     {
749                         frames[j]->i_type = X264_TYPE_P;
750                         break;
751                     }
752                     else
753                         frames[j]->i_type = X264_TYPE_B;
754                 }
755                 i = j;
756             }
757             frames[i+!i]->i_type = X264_TYPE_P;
758             num_bframes = 0;
759             while( num_bframes < num_frames && frames[num_bframes+1]->i_type == X264_TYPE_B )
760                 num_bframes++;
761         }
762         else
763         {
764             num_bframes = X264_MIN(num_frames-1, h->param.i_bframe);
765             for( j = 1; j < num_frames; j++ )
766                 frames[j]->i_type = (j%(num_bframes+1)) ? X264_TYPE_B : X264_TYPE_P;
767             frames[num_frames]->i_type = X264_TYPE_P;
768         }
769
770         /* Check scenecut on the first minigop. */
771         for( j = 1; j < num_bframes+1; j++ )
772             if( h->param.i_scenecut_threshold && scenecut( h, &a, frames, j, j+1 ) )
773             {
774                 frames[j]->i_type = X264_TYPE_P;
775                 num_analysed_frames = j;
776                 break;
777             }
778
779         reset_start = keyframe ? 1 : X264_MIN( num_bframes+2, num_analysed_frames+1 );
780     }
781     else
782     {
783         for( j = 1; j < num_frames; j++ )
784             frames[j]->i_type = X264_TYPE_P;
785         reset_start = !keyframe + 1;
786     }
787
788     /* Perform the actual macroblock tree analysis.
789      * Don't go farther than the lookahead parameter; this helps in short GOPs. */
790     if( h->param.rc.b_mb_tree )
791         x264_macroblock_tree( h, &a, frames, X264_MIN(num_analysed_frames, h->param.rc.i_lookahead), keyframe );
792
793     /* Enforce keyframe limit. */
794     if( h->param.i_bframe )
795         for( j = 0; j <= num_bframes; j++ )
796             if( j+1 > keyint_limit )
797             {
798                 if( j )
799                     frames[j]->i_type = X264_TYPE_P;
800                 frames[j+1]->i_type = idr_frame_type;
801                 reset_start = j+2;
802                 break;
803             }
804
805     /* Restore frametypes for all frames that haven't actually been decided yet. */
806     for( j = reset_start; j <= num_frames; j++ )
807         frames[j]->i_type = X264_TYPE_AUTO;
808 }
809
810 void x264_slicetype_decide( x264_t *h )
811 {
812     x264_frame_t *frm;
813     int bframes;
814     int i;
815
816     if( h->frames.next[0] == NULL )
817         return;
818
819     if( h->param.rc.b_stat_read )
820     {
821         /* Use the frame types from the first pass */
822         for( i = 0; h->frames.next[i] != NULL; i++ )
823             h->frames.next[i]->i_type =
824                 x264_ratecontrol_slice_type( h, h->frames.next[i]->i_frame );
825     }
826     else if( (h->param.i_bframe && h->param.i_bframe_adaptive)
827              || h->param.i_scenecut_threshold
828              || h->param.rc.b_mb_tree )
829         x264_slicetype_analyse( h, 0 );
830
831     for( bframes = 0;; bframes++ )
832     {
833         frm = h->frames.next[bframes];
834
835         /* Limit GOP size */
836         if( frm->i_frame - h->frames.i_last_idr >= h->param.i_keyint_max )
837         {
838             if( frm->i_type == X264_TYPE_AUTO )
839                 frm->i_type = X264_TYPE_IDR;
840             if( frm->i_type != X264_TYPE_IDR )
841                 x264_log( h, X264_LOG_WARNING, "specified frame type (%d) is not compatible with keyframe interval\n", frm->i_type );
842         }
843         if( frm->i_type == X264_TYPE_IDR )
844         {
845             /* Close GOP */
846             if( bframes > 0 )
847             {
848                 bframes--;
849                 h->frames.next[bframes]->i_type = X264_TYPE_P;
850             }
851             else
852             {
853                 h->i_frame_num = 0;
854             }
855         }
856
857         if( bframes == h->param.i_bframe
858             || h->frames.next[bframes+1] == NULL )
859         {
860             if( IS_X264_TYPE_B( frm->i_type ) )
861                 x264_log( h, X264_LOG_WARNING, "specified frame type is not compatible with max B-frames\n" );
862             if( frm->i_type == X264_TYPE_AUTO
863                 || IS_X264_TYPE_B( frm->i_type ) )
864                 frm->i_type = X264_TYPE_P;
865         }
866
867         if( frm->i_type == X264_TYPE_AUTO )
868             frm->i_type = X264_TYPE_B;
869
870         else if( !IS_X264_TYPE_B( frm->i_type ) ) break;
871     }
872 }
873
874 int x264_rc_analyse_slice( x264_t *h )
875 {
876     x264_mb_analysis_t a;
877     x264_frame_t *frames[X264_LOOKAHEAD_MAX+2] = { NULL, };
878     int p0=0, p1, b;
879     int cost;
880
881     x264_lowres_context_init( h, &a );
882
883     if( IS_X264_TYPE_I(h->fenc->i_type) )
884     {
885         p1 = b = 0;
886         /* For MB-tree, we have to perform propagation analysis on I-frames too. */
887         if( h->param.rc.b_mb_tree )
888         {
889             h->frames.last_nonb = h->fenc;
890             x264_slicetype_analyse( h, 1 );
891         }
892     }
893     else if( X264_TYPE_P == h->fenc->i_type )
894     {
895         p1 = 0;
896         while( h->frames.current[p1] && IS_X264_TYPE_B( h->frames.current[p1]->i_type ) )
897             p1++;
898         p1++;
899         b = p1;
900     }
901     else //B
902     {
903         p1 = (h->fref1[0]->i_poc - h->fref0[0]->i_poc)/2;
904         b  = (h->fref1[0]->i_poc - h->fenc->i_poc)/2;
905         frames[p1] = h->fref1[0];
906     }
907     frames[p0] = h->fref0[0];
908     frames[b] = h->fenc;
909
910     if( h->param.rc.b_mb_tree )
911         cost = x264_slicetype_frame_cost_recalculate( h, &a, frames, p0, p1, b );
912     else
913     {
914         cost = x264_slicetype_frame_cost( h, &a, frames, p0, p1, b, 0 );
915
916         /* In AQ, use the weighted score instead. */
917         if( h->param.rc.i_aq_mode )
918             cost = frames[b]->i_cost_est[b-p0][p1-b];
919     }
920
921     h->fenc->i_row_satd = h->fenc->i_row_satds[b-p0][p1-b];
922     h->fdec->i_row_satd = h->fdec->i_row_satds[b-p0][p1-b];
923     h->fdec->i_satd = cost;
924     memcpy( h->fdec->i_row_satd, h->fenc->i_row_satd, h->sps->i_mb_height * sizeof(int) );
925     return cost;
926 }