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