1 /*****************************************************************************
2  * slicetype.c: lookahead analysis
3  *****************************************************************************
4  * Copyright (C) 2005-2021 x264 project
5  *
6  * Authors: Fiona Glaser <fiona@x264.com>
7  *          Loren Merritt <lorenm@u.washington.edu>
8  *          Dylan Yudaken <dyudaken@gmail.com>
9  *
10  * This program is free software; you can redistribute it and/or modify
11  * it under the terms of the GNU General Public License as published by
12  * the Free Software Foundation; either version 2 of the License, or
13  * (at your option) any later version.
14  *
15  * This program is distributed in the hope that it will be useful,
16  * but WITHOUT ANY WARRANTY; without even the implied warranty of
17  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
18  * GNU General Public License for more details.
19  *
20  * You should have received a copy of the GNU General Public License
21  * along with this program; if not, write to the Free Software
22  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02111, USA.
23  *
24  * This program is also available under a commercial proprietary license.
25  * For more information, contact us at licensing@x264.com.
26  *****************************************************************************/
27 
28 #include "common/common.h"
29 #include "macroblock.h"
30 #include "me.h"
31 
32 // Indexed by pic_struct values
33 static const uint8_t delta_tfi_divisor[10] = { 0, 2, 1, 1, 2, 2, 3, 3, 4, 6 };
34 
35 static int slicetype_frame_cost( x264_t *h, x264_mb_analysis_t *a,
36                                  x264_frame_t **frames, int p0, int p1, int b );
37 
38 #define x264_weights_analyse x264_template(weights_analyse)
39 void x264_weights_analyse( x264_t *h, x264_frame_t *fenc, x264_frame_t *ref, int b_lookahead );
40 
41 #if HAVE_OPENCL
42 #include "slicetype-cl.h"
43 #endif
44 
lowres_context_init(x264_t * h,x264_mb_analysis_t * a)45 static void lowres_context_init( x264_t *h, x264_mb_analysis_t *a )
46 {
47     a->i_qp = X264_LOOKAHEAD_QP;
48     a->i_lambda = x264_lambda_tab[ a->i_qp ];
49     mb_analyse_load_costs( h, a );
50     if( h->param.analyse.i_subpel_refine > 1 )
51     {
52         h->mb.i_me_method = X264_MIN( X264_ME_HEX, h->param.analyse.i_me_method );
53         h->mb.i_subpel_refine = 4;
54     }
55     else
56     {
57         h->mb.i_me_method = X264_ME_DIA;
58         h->mb.i_subpel_refine = 2;
59     }
60     h->mb.b_chroma_me = 0;
61 }
62 
63 /* makes a non-h264 weight (i.e. fix7), into an h264 weight */
weight_get_h264(int weight_nonh264,int offset,x264_weight_t * w)64 static void weight_get_h264( int weight_nonh264, int offset, x264_weight_t *w )
65 {
66     w->i_offset = offset;
67     w->i_denom = 7;
68     w->i_scale = weight_nonh264;
69     while( w->i_denom > 0 && (w->i_scale > 127) )
70     {
71         w->i_denom--;
72         w->i_scale >>= 1;
73     }
74     w->i_scale = X264_MIN( w->i_scale, 127 );
75 }
76 
weight_cost_init_luma(x264_t * h,x264_frame_t * fenc,x264_frame_t * ref,pixel * dest)77 static NOINLINE pixel *weight_cost_init_luma( x264_t *h, x264_frame_t *fenc, x264_frame_t *ref, pixel *dest )
78 {
79     int ref0_distance = fenc->i_frame - ref->i_frame - 1;
80     /* Note: this will never run during lookahead as weights_analyse is only called if no
81      * motion search has been done. */
82     if( fenc->lowres_mvs[0][ref0_distance][0][0] != 0x7FFF )
83     {
84         int i_stride = fenc->i_stride_lowres;
85         int i_lines = fenc->i_lines_lowres;
86         int i_width = fenc->i_width_lowres;
87         int i_mb_xy = 0;
88         pixel *p = dest;
89 
90         for( int y = 0; y < i_lines; y += 8, p += i_stride*8 )
91             for( int x = 0; x < i_width; x += 8, i_mb_xy++ )
92             {
93                 int mvx = fenc->lowres_mvs[0][ref0_distance][i_mb_xy][0];
94                 int mvy = fenc->lowres_mvs[0][ref0_distance][i_mb_xy][1];
95                 h->mc.mc_luma( p+x, i_stride, ref->lowres, i_stride,
96                                mvx+(x<<2), mvy+(y<<2), 8, 8, x264_weight_none );
97             }
98         x264_emms();
99         return dest;
100     }
101     x264_emms();
102     return ref->lowres[0];
103 }
104 
105 /* How data is organized for 4:2:0/4:2:2 chroma weightp:
106  * [U: ref] [U: fenc]
107  * [V: ref] [V: fenc]
108  * fenc = ref + offset
109  * v = u + stride * chroma height */
110 
weight_cost_init_chroma(x264_t * h,x264_frame_t * fenc,x264_frame_t * ref,pixel * dstu,pixel * dstv)111 static NOINLINE void weight_cost_init_chroma( x264_t *h, x264_frame_t *fenc, x264_frame_t *ref, pixel *dstu, pixel *dstv )
112 {
113     int ref0_distance = fenc->i_frame - ref->i_frame - 1;
114     int i_stride = fenc->i_stride[1];
115     int i_lines = fenc->i_lines[1];
116     int i_width = fenc->i_width[1];
117     int v_shift = CHROMA_V_SHIFT;
118     int cw = 8*h->mb.i_mb_width;
119     int ch = 16*h->mb.i_mb_height >> v_shift;
120     int height = 16 >> v_shift;
121 
122     if( fenc->lowres_mvs[0][ref0_distance][0][0] != 0x7FFF )
123     {
124         x264_frame_expand_border_chroma( h, ref, 1 );
125         for( int y = 0, mb_xy = 0, pel_offset_y = 0; y < i_lines; y += height, pel_offset_y = y*i_stride )
126             for( int x = 0, pel_offset_x = 0; x < i_width; x += 8, mb_xy++, pel_offset_x += 8 )
127             {
128                 pixel *pixu = dstu + pel_offset_y + pel_offset_x;
129                 pixel *pixv = dstv + pel_offset_y + pel_offset_x;
130                 pixel *src1 =  ref->plane[1] + pel_offset_y + pel_offset_x*2; /* NV12/NV16 */
131                 int mvx = fenc->lowres_mvs[0][ref0_distance][mb_xy][0];
132                 int mvy = fenc->lowres_mvs[0][ref0_distance][mb_xy][1];
133                 h->mc.mc_chroma( pixu, pixv, i_stride, src1, i_stride, mvx, 2*mvy>>v_shift, 8, height );
134             }
135     }
136     else
137         h->mc.plane_copy_deinterleave( dstu, i_stride, dstv, i_stride, ref->plane[1], i_stride, cw, ch );
138     h->mc.plane_copy_deinterleave( dstu+i_width, i_stride, dstv+i_width, i_stride, fenc->plane[1], i_stride, cw, ch );
139     x264_emms();
140 }
141 
weight_cost_init_chroma444(x264_t * h,x264_frame_t * fenc,x264_frame_t * ref,pixel * dst,int p)142 static NOINLINE pixel *weight_cost_init_chroma444( x264_t *h, x264_frame_t *fenc, x264_frame_t *ref, pixel *dst, int p )
143 {
144     int ref0_distance = fenc->i_frame - ref->i_frame - 1;
145     int i_stride = fenc->i_stride[p];
146     int i_lines = fenc->i_lines[p];
147     int i_width = fenc->i_width[p];
148 
149     if( fenc->lowres_mvs[0][ref0_distance][0][0] != 0x7FFF )
150     {
151         x264_frame_expand_border_chroma( h, ref, p );
152         for( int y = 0, mb_xy = 0, pel_offset_y = 0; y < i_lines; y += 16, pel_offset_y = y*i_stride )
153             for( int x = 0, pel_offset_x = 0; x < i_width; x += 16, mb_xy++, pel_offset_x += 16 )
154             {
155                 pixel *pix = dst + pel_offset_y + pel_offset_x;
156                 pixel *src = ref->plane[p] + pel_offset_y + pel_offset_x;
157                 int mvx = fenc->lowres_mvs[0][ref0_distance][mb_xy][0] / 2;
158                 int mvy = fenc->lowres_mvs[0][ref0_distance][mb_xy][1] / 2;
159                 /* We don't want to calculate hpels for fenc frames, so we round the motion
160                  * vectors to fullpel here.  It's not too bad, I guess? */
161                 h->mc.copy_16x16_unaligned( pix, i_stride, src+mvx+mvy*i_stride, i_stride, 16 );
162             }
163         x264_emms();
164         return dst;
165     }
166     x264_emms();
167     return ref->plane[p];
168 }
169 
weight_slice_header_cost(x264_t * h,x264_weight_t * w,int b_chroma)170 static int weight_slice_header_cost( x264_t *h, x264_weight_t *w, int b_chroma )
171 {
172     /* Add cost of weights in the slice header. */
173     int lambda = x264_lambda_tab[X264_LOOKAHEAD_QP];
174     /* 4 times higher, because chroma is analyzed at full resolution. */
175     if( b_chroma )
176         lambda *= 4;
177     int numslices;
178     if( h->param.i_slice_count )
179         numslices = h->param.i_slice_count;
180     else if( h->param.i_slice_max_mbs )
181         numslices = (h->mb.i_mb_width * h->mb.i_mb_height + h->param.i_slice_max_mbs-1) / h->param.i_slice_max_mbs;
182     else
183         numslices = 1;
184     /* FIXME: find a way to account for --slice-max-size?
185      * Multiply by 2 as there will be a duplicate. 10 bits added as if there is a weighted frame, then an additional duplicate is used.
186      * Cut denom cost in half if chroma, since it's shared between the two chroma planes. */
187     int denom_cost = bs_size_ue( w[0].i_denom ) * (2 - b_chroma);
188     return lambda * numslices * ( 10 + denom_cost + 2 * (bs_size_se( w[0].i_scale ) + bs_size_se( w[0].i_offset )) );
189 }
190 
weight_cost_luma(x264_t * h,x264_frame_t * fenc,pixel * src,x264_weight_t * w)191 static NOINLINE unsigned int weight_cost_luma( x264_t *h, x264_frame_t *fenc, pixel *src, x264_weight_t *w )
192 {
193     unsigned int cost = 0;
194     int i_stride = fenc->i_stride_lowres;
195     int i_lines = fenc->i_lines_lowres;
196     int i_width = fenc->i_width_lowres;
197     pixel *fenc_plane = fenc->lowres[0];
198     ALIGNED_ARRAY_16( pixel, buf,[8*8] );
199     int pixoff = 0;
200     int i_mb = 0;
201 
202     if( w )
203     {
204         for( int y = 0; y < i_lines; y += 8, pixoff = y*i_stride )
205             for( int x = 0; x < i_width; x += 8, i_mb++, pixoff += 8)
206             {
207                 w->weightfn[8>>2]( buf, 8, &src[pixoff], i_stride, w, 8 );
208                 int cmp = h->pixf.mbcmp[PIXEL_8x8]( buf, 8, &fenc_plane[pixoff], i_stride );
209                 cost += X264_MIN( cmp, fenc->i_intra_cost[i_mb] );
210             }
211         cost += weight_slice_header_cost( h, w, 0 );
212     }
213     else
214         for( int y = 0; y < i_lines; y += 8, pixoff = y*i_stride )
215             for( int x = 0; x < i_width; x += 8, i_mb++, pixoff += 8 )
216             {
217                 int cmp = h->pixf.mbcmp[PIXEL_8x8]( &src[pixoff], i_stride, &fenc_plane[pixoff], i_stride );
218                 cost += X264_MIN( cmp, fenc->i_intra_cost[i_mb] );
219             }
220     x264_emms();
221     return cost;
222 }
223 
weight_cost_chroma(x264_t * h,x264_frame_t * fenc,pixel * ref,x264_weight_t * w)224 static NOINLINE unsigned int weight_cost_chroma( x264_t *h, x264_frame_t *fenc, pixel *ref, x264_weight_t *w )
225 {
226     unsigned int cost = 0;
227     int i_stride = fenc->i_stride[1];
228     int i_lines = fenc->i_lines[1];
229     int i_width = fenc->i_width[1];
230     pixel *src = ref + i_width;
231     ALIGNED_ARRAY_16( pixel, buf, [8*16] );
232     int pixoff = 0;
233     int height = 16 >> CHROMA_V_SHIFT;
234     if( w )
235     {
236         for( int y = 0; y < i_lines; y += height, pixoff = y*i_stride )
237             for( int x = 0; x < i_width; x += 8, pixoff += 8 )
238             {
239                 w->weightfn[8>>2]( buf, 8, &ref[pixoff], i_stride, w, height );
240                 /* The naive and seemingly sensible algorithm is to use mbcmp as in luma.
241                  * But testing shows that for chroma the DC coefficient is by far the most
242                  * important part of the coding cost.  Thus a more useful chroma weight is
243                  * obtained by comparing each block's DC coefficient instead of the actual
244                  * pixels. */
245                 cost += h->pixf.asd8( buf, 8, &src[pixoff], i_stride, height );
246             }
247         cost += weight_slice_header_cost( h, w, 1 );
248     }
249     else
250         for( int y = 0; y < i_lines; y += height, pixoff = y*i_stride )
251             for( int x = 0; x < i_width; x += 8, pixoff += 8 )
252                 cost += h->pixf.asd8( &ref[pixoff], i_stride, &src[pixoff], i_stride, height );
253     x264_emms();
254     return cost;
255 }
256 
weight_cost_chroma444(x264_t * h,x264_frame_t * fenc,pixel * ref,x264_weight_t * w,int p)257 static NOINLINE unsigned int weight_cost_chroma444( x264_t *h, x264_frame_t *fenc, pixel *ref, x264_weight_t *w, int p )
258 {
259     unsigned int cost = 0;
260     int i_stride = fenc->i_stride[p];
261     int i_lines = fenc->i_lines[p];
262     int i_width = fenc->i_width[p];
263     pixel *src = fenc->plane[p];
264     ALIGNED_ARRAY_64( pixel, buf, [16*16] );
265     int pixoff = 0;
266     if( w )
267     {
268         for( int y = 0; y < i_lines; y += 16, pixoff = y*i_stride )
269             for( int x = 0; x < i_width; x += 16, pixoff += 16 )
270             {
271                 w->weightfn[16>>2]( buf, 16, &ref[pixoff], i_stride, w, 16 );
272                 cost += h->pixf.mbcmp[PIXEL_16x16]( buf, 16, &src[pixoff], i_stride );
273             }
274         cost += weight_slice_header_cost( h, w, 1 );
275     }
276     else
277         for( int y = 0; y < i_lines; y += 16, pixoff = y*i_stride )
278             for( int x = 0; x < i_width; x += 16, pixoff += 16 )
279                 cost += h->pixf.mbcmp[PIXEL_16x16]( &ref[pixoff], i_stride, &src[pixoff], i_stride );
280     x264_emms();
281     return cost;
282 }
283 
x264_weights_analyse(x264_t * h,x264_frame_t * fenc,x264_frame_t * ref,int b_lookahead)284 void x264_weights_analyse( x264_t *h, x264_frame_t *fenc, x264_frame_t *ref, int b_lookahead )
285 {
286     int i_delta_index = fenc->i_frame - ref->i_frame - 1;
287     /* epsilon is chosen to require at least a numerator of 127 (with denominator = 128) */
288     const float epsilon = 1.f/128.f;
289     x264_weight_t *weights = fenc->weight[0];
290     SET_WEIGHT( weights[0], 0, 1, 0, 0 );
291     SET_WEIGHT( weights[1], 0, 1, 0, 0 );
292     SET_WEIGHT( weights[2], 0, 1, 0, 0 );
293     int chroma_initted = 0;
294     float guess_scale[3];
295     float fenc_mean[3];
296     float ref_mean[3];
297     for( int plane = 0; plane <= 2*!b_lookahead; plane++ )
298     {
299         if( !plane || CHROMA_FORMAT )
300         {
301             int zero_bias = !ref->i_pixel_ssd[plane];
302             float fenc_var = fenc->i_pixel_ssd[plane] + zero_bias;
303             float ref_var  =  ref->i_pixel_ssd[plane] + zero_bias;
304             guess_scale[plane] = sqrtf( fenc_var / ref_var );
305             fenc_mean[plane] = (float)(fenc->i_pixel_sum[plane] + zero_bias) / (fenc->i_lines[!!plane] * fenc->i_width[!!plane]) / (1 << (BIT_DEPTH - 8));
306             ref_mean[plane]  = (float)( ref->i_pixel_sum[plane] + zero_bias) / (fenc->i_lines[!!plane] * fenc->i_width[!!plane]) / (1 << (BIT_DEPTH - 8));
307         }
308         else
309         {
310             guess_scale[plane] = 1;
311             fenc_mean[plane] = 0;
312             ref_mean[plane]  = 0;
313         }
314     }
315 
316     int chroma_denom = 7;
317     if( !b_lookahead )
318     {
319         /* make sure both our scale factors fit */
320         while( chroma_denom > 0 )
321         {
322             float thresh = 127.f / (1<<chroma_denom);
323             if( guess_scale[1] < thresh && guess_scale[2] < thresh )
324                 break;
325             chroma_denom--;
326         }
327     }
328 
329     /* Don't check chroma in lookahead, or if there wasn't a luma weight. */
330     for( int plane = 0; plane < (CHROMA_FORMAT ? 3 : 1) && !( plane && ( !weights[0].weightfn || b_lookahead ) ); plane++ )
331     {
332         int minoff, minscale, mindenom;
333         unsigned int minscore, origscore;
334         int found;
335 
336         //early termination
337         if( fabsf( ref_mean[plane] - fenc_mean[plane] ) < 0.5f && fabsf( 1.f - guess_scale[plane] ) < epsilon )
338         {
339             SET_WEIGHT( weights[plane], 0, 1, 0, 0 );
340             continue;
341         }
342 
343         if( plane )
344         {
345             weights[plane].i_denom = chroma_denom;
346             weights[plane].i_scale = x264_clip3( round( guess_scale[plane] * (1<<chroma_denom) ), 0, 255 );
347             if( weights[plane].i_scale > 127 )
348             {
349                 weights[1].weightfn = weights[2].weightfn = NULL;
350                 break;
351             }
352         }
353         else
354             weight_get_h264( round( guess_scale[plane] * 128 ), 0, &weights[plane] );
355 
356         found = 0;
357         mindenom = weights[plane].i_denom;
358         minscale = weights[plane].i_scale;
359         minoff = 0;
360 
361         pixel *mcbuf;
362         if( !plane )
363         {
364             if( !fenc->b_intra_calculated )
365             {
366                 x264_mb_analysis_t a;
367                 lowres_context_init( h, &a );
368                 slicetype_frame_cost( h, &a, &fenc, 0, 0, 0 );
369             }
370             mcbuf = weight_cost_init_luma( h, fenc, ref, h->mb.p_weight_buf[0] );
371             origscore = minscore = weight_cost_luma( h, fenc, mcbuf, NULL );
372         }
373         else
374         {
375             if( CHROMA444 )
376             {
377                 mcbuf = weight_cost_init_chroma444( h, fenc, ref, h->mb.p_weight_buf[0], plane );
378                 origscore = minscore = weight_cost_chroma444( h, fenc, mcbuf, NULL, plane );
379             }
380             else
381             {
382                 pixel *dstu = h->mb.p_weight_buf[0];
383                 pixel *dstv = h->mb.p_weight_buf[0]+fenc->i_stride[1]*fenc->i_lines[1];
384                 if( !chroma_initted++ )
385                     weight_cost_init_chroma( h, fenc, ref, dstu, dstv );
386                 mcbuf = plane == 1 ? dstu : dstv;
387                 origscore = minscore = weight_cost_chroma( h, fenc, mcbuf, NULL );
388             }
389         }
390 
391         if( !minscore )
392             continue;
393 
394         /* Picked somewhat arbitrarily */
395         static const uint8_t weight_check_distance[][2] =
396         {
397             {0,0},{0,0},{0,1},{0,1},
398             {0,1},{0,1},{0,1},{1,1},
399             {1,1},{2,1},{2,1},{4,2}
400         };
401         int scale_dist =  b_lookahead ? 0 : weight_check_distance[h->param.analyse.i_subpel_refine][0];
402         int offset_dist = b_lookahead ? 0 : weight_check_distance[h->param.analyse.i_subpel_refine][1];
403 
404         int start_scale  = x264_clip3( minscale - scale_dist, 0, 127 );
405         int end_scale    = x264_clip3( minscale + scale_dist, 0, 127 );
406         for( int i_scale = start_scale; i_scale <= end_scale; i_scale++ )
407         {
408             int cur_scale = i_scale;
409             int cur_offset = fenc_mean[plane] - ref_mean[plane] * cur_scale / (1 << mindenom) + 0.5f * b_lookahead;
410             if( cur_offset < - 128 || cur_offset > 127 )
411             {
412                 /* Rescale considering the constraints on cur_offset. We do it in this order
413                  * because scale has a much wider range than offset (because of denom), so
414                  * it should almost never need to be clamped. */
415                 cur_offset = x264_clip3( cur_offset, -128, 127 );
416                 cur_scale = x264_clip3f( (1 << mindenom) * (fenc_mean[plane] - cur_offset) / ref_mean[plane] + 0.5f, 0, 127 );
417             }
418             int start_offset = x264_clip3( cur_offset - offset_dist, -128, 127 );
419             int end_offset   = x264_clip3( cur_offset + offset_dist, -128, 127 );
420             for( int i_off = start_offset; i_off <= end_offset; i_off++ )
421             {
422                 SET_WEIGHT( weights[plane], 1, cur_scale, mindenom, i_off );
423                 unsigned int s;
424                 if( plane )
425                 {
426                     if( CHROMA444 )
427                         s = weight_cost_chroma444( h, fenc, mcbuf, &weights[plane], plane );
428                     else
429                         s = weight_cost_chroma( h, fenc, mcbuf, &weights[plane] );
430                 }
431                 else
432                     s = weight_cost_luma( h, fenc, mcbuf, &weights[plane] );
433                 COPY4_IF_LT( minscore, s, minscale, cur_scale, minoff, i_off, found, 1 );
434 
435                 // Don't check any more offsets if the previous one had a lower cost than the current one
436                 if( minoff == start_offset && i_off != start_offset )
437                     break;
438             }
439         }
440         x264_emms();
441 
442         /* Use a smaller denominator if possible */
443         if( !plane )
444         {
445             while( mindenom > 0 && !(minscale&1) )
446             {
447                 mindenom--;
448                 minscale >>= 1;
449             }
450         }
451 
452         /* FIXME: More analysis can be done here on SAD vs. SATD termination. */
453         /* 0.2% termination derived experimentally to avoid weird weights in frames that are mostly intra. */
454         if( !found || (minscale == 1 << mindenom && minoff == 0) || (float)minscore / origscore > 0.998f )
455         {
456             SET_WEIGHT( weights[plane], 0, 1, 0, 0 );
457             continue;
458         }
459         else
460             SET_WEIGHT( weights[plane], 1, minscale, mindenom, minoff );
461 
462         if( h->param.analyse.i_weighted_pred == X264_WEIGHTP_FAKE && weights[0].weightfn && !plane )
463             fenc->f_weighted_cost_delta[i_delta_index] = (float)minscore / origscore;
464     }
465 
466     /* Optimize and unify denominator */
467     if( weights[1].weightfn || weights[2].weightfn )
468     {
469         int denom = weights[1].weightfn ? weights[1].i_denom : weights[2].i_denom;
470         int both_weighted = weights[1].weightfn && weights[2].weightfn;
471         /* If only one plane is weighted, the other has an implicit scale of 1<<denom.
472          * With denom==7, this comes out to 128, which is invalid, so don't allow that. */
473         while( (!both_weighted && denom==7) ||
474                (denom > 0 && !(weights[1].weightfn && (weights[1].i_scale&1))
475                          && !(weights[2].weightfn && (weights[2].i_scale&1))) )
476         {
477             denom--;
478             for( int i = 1; i <= 2; i++ )
479                 if( weights[i].weightfn )
480                 {
481                     weights[i].i_scale >>= 1;
482                     weights[i].i_denom = denom;
483                 }
484         }
485     }
486     for( int i = 1; i <= 2; i++ )
487         if( weights[i].weightfn )
488             h->mc.weight_cache( h, &weights[i] );
489 
490     if( weights[0].weightfn && b_lookahead )
491     {
492         //scale lowres in lookahead for slicetype_frame_cost
493         pixel *src = ref->buffer_lowres;
494         pixel *dst = h->mb.p_weight_buf[0];
495         int width = ref->i_width_lowres + PADH2;
496         int height = ref->i_lines_lowres + PADV*2;
497         x264_weight_scale_plane( h, dst, ref->i_stride_lowres, src, ref->i_stride_lowres,
498                                  width, height, &weights[0] );
499         fenc->weighted[0] = h->mb.p_weight_buf[0] + PADH_ALIGN + ref->i_stride_lowres * PADV;
500     }
501 }
502 
503 /* Output buffers are separated by 128 bytes to avoid false sharing of cachelines
504  * in multithreaded lookahead. */
505 #define PAD_SIZE 32
506 /* cost_est, cost_est_aq, intra_mbs, num rows */
507 #define NUM_INTS 4
508 #define COST_EST 0
509 #define COST_EST_AQ 1
510 #define INTRA_MBS 2
511 #define NUM_ROWS 3
512 #define ROW_SATD (NUM_INTS + (h->mb.i_mb_y - h->i_threadslice_start))
513 
slicetype_mb_cost(x264_t * h,x264_mb_analysis_t * a,x264_frame_t ** frames,int p0,int p1,int b,int dist_scale_factor,int do_search[2],const x264_weight_t * w,int * output_inter,int * output_intra)514 static void slicetype_mb_cost( x264_t *h, x264_mb_analysis_t *a,
515                                x264_frame_t **frames, int p0, int p1, int b,
516                                int dist_scale_factor, int do_search[2], const x264_weight_t *w,
517                                int *output_inter, int *output_intra )
518 {
519     x264_frame_t *fref0 = frames[p0];
520     x264_frame_t *fref1 = frames[p1];
521     x264_frame_t *fenc  = frames[b];
522     const int b_bidir = (b < p1);
523     const int i_mb_x = h->mb.i_mb_x;
524     const int i_mb_y = h->mb.i_mb_y;
525     const int i_mb_stride = h->mb.i_mb_width;
526     const int i_mb_xy = i_mb_x + i_mb_y * i_mb_stride;
527     const int i_stride = fenc->i_stride_lowres;
528     const int i_pel_offset = 8 * (i_mb_x + i_mb_y * i_stride);
529     const int i_bipred_weight = h->param.analyse.b_weighted_bipred ? 64 - (dist_scale_factor>>2) : 32;
530     int16_t (*fenc_mvs[2])[2] = { b != p0 ? &fenc->lowres_mvs[0][b-p0-1][i_mb_xy] : NULL, b != p1 ? &fenc->lowres_mvs[1][p1-b-1][i_mb_xy] : NULL };
531     int (*fenc_costs[2]) = { b != p0 ? &fenc->lowres_mv_costs[0][b-p0-1][i_mb_xy] : NULL, b != p1 ? &fenc->lowres_mv_costs[1][p1-b-1][i_mb_xy] : NULL };
532     int b_frame_score_mb = (i_mb_x > 0 && i_mb_x < h->mb.i_mb_width - 1 &&
533                             i_mb_y > 0 && i_mb_y < h->mb.i_mb_height - 1) ||
534                             h->mb.i_mb_width <= 2 || h->mb.i_mb_height <= 2;
535 
536     ALIGNED_ARRAY_16( pixel, pix1,[9*FDEC_STRIDE] );
537     pixel *pix2 = pix1+8;
538     x264_me_t m[2];
539     int i_bcost = COST_MAX;
540     int list_used = 0;
541     /* A small, arbitrary bias to avoid VBV problems caused by zero-residual lookahead blocks. */
542     int lowres_penalty = 4;
543 
544     h->mb.pic.p_fenc[0] = h->mb.pic.fenc_buf;
545     h->mc.copy[PIXEL_8x8]( h->mb.pic.p_fenc[0], FENC_STRIDE, &fenc->lowres[0][i_pel_offset], i_stride, 8 );
546 
547     if( p0 == p1 )
548         goto lowres_intra_mb;
549 
550     int mv_range = 2 * h->param.analyse.i_mv_range;
551     // no need for h->mb.mv_min[]
552     h->mb.mv_min_spel[0] = X264_MAX( 4*(-8*h->mb.i_mb_x - 12), -mv_range );
553     h->mb.mv_max_spel[0] = X264_MIN( 4*(8*(h->mb.i_mb_width - h->mb.i_mb_x - 1) + 12), mv_range-1 );
554     h->mb.mv_limit_fpel[0][0] = h->mb.mv_min_spel[0] >> 2;
555     h->mb.mv_limit_fpel[1][0] = h->mb.mv_max_spel[0] >> 2;
556     if( h->mb.i_mb_x >= h->mb.i_mb_width - 2 )
557     {
558         h->mb.mv_min_spel[1] = X264_MAX( 4*(-8*h->mb.i_mb_y - 12), -mv_range );
559         h->mb.mv_max_spel[1] = X264_MIN( 4*(8*( h->mb.i_mb_height - h->mb.i_mb_y - 1) + 12), mv_range-1 );
560         h->mb.mv_limit_fpel[0][1] = h->mb.mv_min_spel[1] >> 2;
561         h->mb.mv_limit_fpel[1][1] = h->mb.mv_max_spel[1] >> 2;
562     }
563 
564 #define LOAD_HPELS_LUMA(dst, src) \
565     { \
566         (dst)[0] = &(src)[0][i_pel_offset]; \
567         (dst)[1] = &(src)[1][i_pel_offset]; \
568         (dst)[2] = &(src)[2][i_pel_offset]; \
569         (dst)[3] = &(src)[3][i_pel_offset]; \
570     }
571 #define LOAD_WPELS_LUMA(dst,src) \
572     (dst) = &(src)[i_pel_offset];
573 
574 #define CLIP_MV( mv ) \
575     { \
576         mv[0] = x264_clip3( mv[0], h->mb.mv_min_spel[0], h->mb.mv_max_spel[0] ); \
577         mv[1] = x264_clip3( mv[1], h->mb.mv_min_spel[1], h->mb.mv_max_spel[1] ); \
578     }
579 #define TRY_BIDIR( mv0, mv1, penalty ) \
580     { \
581         int i_cost; \
582         if( h->param.analyse.i_subpel_refine <= 1 ) \
583         { \
584             int hpel_idx1 = (((mv0)[0]&2)>>1) + ((mv0)[1]&2); \
585             int hpel_idx2 = (((mv1)[0]&2)>>1) + ((mv1)[1]&2); \
586             pixel *src1 = m[0].p_fref[hpel_idx1] + ((mv0)[0]>>2) + ((mv0)[1]>>2) * m[0].i_stride[0]; \
587             pixel *src2 = m[1].p_fref[hpel_idx2] + ((mv1)[0]>>2) + ((mv1)[1]>>2) * m[1].i_stride[0]; \
588             h->mc.avg[PIXEL_8x8]( pix1, 16, src1, m[0].i_stride[0], src2, m[1].i_stride[0], i_bipred_weight ); \
589         } \
590         else \
591         { \
592             intptr_t stride1 = 16, stride2 = 16; \
593             pixel *src1, *src2; \
594             src1 = h->mc.get_ref( pix1, &stride1, m[0].p_fref, m[0].i_stride[0], \
595                                   (mv0)[0], (mv0)[1], 8, 8, w ); \
596             src2 = h->mc.get_ref( pix2, &stride2, m[1].p_fref, m[1].i_stride[0], \
597                                   (mv1)[0], (mv1)[1], 8, 8, w ); \
598             h->mc.avg[PIXEL_8x8]( pix1, 16, src1, stride1, src2, stride2, i_bipred_weight ); \
599         } \
600         i_cost = penalty * a->i_lambda + h->pixf.mbcmp[PIXEL_8x8]( \
601                            m[0].p_fenc[0], FENC_STRIDE, pix1, 16 ); \
602         COPY2_IF_LT( i_bcost, i_cost, list_used, 3 ); \
603     }
604 
605     m[0].i_pixel = PIXEL_8x8;
606     m[0].p_cost_mv = a->p_cost_mv;
607     m[0].i_stride[0] = i_stride;
608     m[0].p_fenc[0] = h->mb.pic.p_fenc[0];
609     m[0].weight = w;
610     m[0].i_ref = 0;
611     LOAD_HPELS_LUMA( m[0].p_fref, fref0->lowres );
612     m[0].p_fref_w = m[0].p_fref[0];
613     if( w[0].weightfn )
614         LOAD_WPELS_LUMA( m[0].p_fref_w, fenc->weighted[0] );
615 
616     if( b_bidir )
617     {
618         ALIGNED_ARRAY_8( int16_t, dmv,[2],[2] );
619 
620         m[1].i_pixel = PIXEL_8x8;
621         m[1].p_cost_mv = a->p_cost_mv;
622         m[1].i_stride[0] = i_stride;
623         m[1].p_fenc[0] = h->mb.pic.p_fenc[0];
624         m[1].i_ref = 0;
625         m[1].weight = x264_weight_none;
626         LOAD_HPELS_LUMA( m[1].p_fref, fref1->lowres );
627         m[1].p_fref_w = m[1].p_fref[0];
628 
629         if( fref1->lowres_mvs[0][p1-p0-1][0][0] != 0x7FFF )
630         {
631             int16_t *mvr = fref1->lowres_mvs[0][p1-p0-1][i_mb_xy];
632             dmv[0][0] = ( mvr[0] * dist_scale_factor + 128 ) >> 8;
633             dmv[0][1] = ( mvr[1] * dist_scale_factor + 128 ) >> 8;
634             dmv[1][0] = dmv[0][0] - mvr[0];
635             dmv[1][1] = dmv[0][1] - mvr[1];
636             CLIP_MV( dmv[0] );
637             CLIP_MV( dmv[1] );
638             if( h->param.analyse.i_subpel_refine <= 1 )
639                 M64( dmv ) &= ~0x0001000100010001ULL; /* mv & ~1 */
640         }
641         else
642             M64( dmv ) = 0;
643 
644         TRY_BIDIR( dmv[0], dmv[1], 0 );
645         if( M64( dmv ) )
646         {
647             int i_cost;
648             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 );
649             i_cost = h->pixf.mbcmp[PIXEL_8x8]( m[0].p_fenc[0], FENC_STRIDE, pix1, 16 );
650             COPY2_IF_LT( i_bcost, i_cost, list_used, 3 );
651         }
652     }
653 
654     for( int l = 0; l < 1 + b_bidir; l++ )
655     {
656         if( do_search[l] )
657         {
658             int i_mvc = 0;
659             int16_t (*fenc_mv)[2] = fenc_mvs[l];
660             ALIGNED_ARRAY_8( int16_t, mvc,[4],[2] );
661 
662             /* Reverse-order MV prediction. */
663             M32( mvc[0] ) = 0;
664             M32( mvc[2] ) = 0;
665 #define MVC(mv) { CP32( mvc[i_mvc], mv ); i_mvc++; }
666             if( i_mb_x < h->mb.i_mb_width - 1 )
667                 MVC( fenc_mv[1] );
668             if( i_mb_y < h->i_threadslice_end - 1 )
669             {
670                 MVC( fenc_mv[i_mb_stride] );
671                 if( i_mb_x > 0 )
672                     MVC( fenc_mv[i_mb_stride-1] );
673                 if( i_mb_x < h->mb.i_mb_width - 1 )
674                     MVC( fenc_mv[i_mb_stride+1] );
675             }
676 #undef MVC
677             if( i_mvc <= 1 )
678                 CP32( m[l].mvp, mvc[0] );
679             else
680                 x264_median_mv( m[l].mvp, mvc[0], mvc[1], mvc[2] );
681 
682             /* Fast skip for cases of near-zero residual.  Shortcut: don't bother except in the mv0 case,
683              * since anything else is likely to have enough residual to not trigger the skip. */
684             if( !M32( m[l].mvp ) )
685             {
686                 m[l].cost = h->pixf.mbcmp[PIXEL_8x8]( m[l].p_fenc[0], FENC_STRIDE, m[l].p_fref[0], m[l].i_stride[0] );
687                 if( m[l].cost < 64 )
688                 {
689                     M32( m[l].mv ) = 0;
690                     goto skip_motionest;
691                 }
692             }
693 
694             x264_me_search( h, &m[l], mvc, i_mvc );
695             m[l].cost -= a->p_cost_mv[0]; // remove mvcost from skip mbs
696             if( M32( m[l].mv ) )
697                 m[l].cost += 5 * a->i_lambda;
698 
699 skip_motionest:
700             CP32( fenc_mvs[l], m[l].mv );
701             *fenc_costs[l] = m[l].cost;
702         }
703         else
704         {
705             CP32( m[l].mv, fenc_mvs[l] );
706             m[l].cost = *fenc_costs[l];
707         }
708         COPY2_IF_LT( i_bcost, m[l].cost, list_used, l+1 );
709     }
710 
711     if( b_bidir && ( M32( m[0].mv ) || M32( m[1].mv ) ) )
712         TRY_BIDIR( m[0].mv, m[1].mv, 5 );
713 
714 lowres_intra_mb:
715     if( !fenc->b_intra_calculated )
716     {
717         ALIGNED_ARRAY_16( pixel, edge,[36] );
718         pixel *pix = &pix1[8+FDEC_STRIDE];
719         pixel *src = &fenc->lowres[0][i_pel_offset];
720         const int intra_penalty = 5 * a->i_lambda;
721         int satds[3];
722         int pixoff = 4 / SIZEOF_PIXEL;
723 
724         /* Avoid store forwarding stalls by writing larger chunks */
725         memcpy( pix-FDEC_STRIDE, src-i_stride, 16 * SIZEOF_PIXEL );
726         for( int i = -1; i < 8; i++ )
727             M32( &pix[i*FDEC_STRIDE-pixoff] ) = M32( &src[i*i_stride-pixoff] );
728 
729         h->pixf.intra_mbcmp_x3_8x8c( h->mb.pic.p_fenc[0], pix, satds );
730         int i_icost = X264_MIN3( satds[0], satds[1], satds[2] );
731 
732         if( h->param.analyse.i_subpel_refine > 1 )
733         {
734             h->predict_8x8c[I_PRED_CHROMA_P]( pix );
735             int satd = h->pixf.mbcmp[PIXEL_8x8]( h->mb.pic.p_fenc[0], FENC_STRIDE, pix, FDEC_STRIDE );
736             i_icost = X264_MIN( i_icost, satd );
737             h->predict_8x8_filter( pix, edge, ALL_NEIGHBORS, ALL_NEIGHBORS );
738             for( int i = 3; i < 9; i++ )
739             {
740                 h->predict_8x8[i]( pix, edge );
741                 satd = h->pixf.mbcmp[PIXEL_8x8]( h->mb.pic.p_fenc[0], FENC_STRIDE, pix, FDEC_STRIDE );
742                 i_icost = X264_MIN( i_icost, satd );
743             }
744         }
745 
746         i_icost = ((i_icost + intra_penalty) >> (BIT_DEPTH - 8)) + lowres_penalty;
747         fenc->i_intra_cost[i_mb_xy] = i_icost;
748         int i_icost_aq = i_icost;
749         if( h->param.rc.i_aq_mode )
750             i_icost_aq = (i_icost_aq * fenc->i_inv_qscale_factor[i_mb_xy] + 128) >> 8;
751         output_intra[ROW_SATD] += i_icost_aq;
752         if( b_frame_score_mb )
753         {
754             output_intra[COST_EST] += i_icost;
755             output_intra[COST_EST_AQ] += i_icost_aq;
756         }
757     }
758     i_bcost = (i_bcost >> (BIT_DEPTH - 8)) + lowres_penalty;
759 
760     /* forbid intra-mbs in B-frames, because it's rare and not worth checking */
761     /* FIXME: Should we still forbid them now that we cache intra scores? */
762     if( !b_bidir )
763     {
764         int i_icost = fenc->i_intra_cost[i_mb_xy];
765         int b_intra = i_icost < i_bcost;
766         if( b_intra )
767         {
768             i_bcost = i_icost;
769             list_used = 0;
770         }
771         if( b_frame_score_mb )
772             output_inter[INTRA_MBS] += b_intra;
773     }
774 
775     /* In an I-frame, we've already added the results above in the intra section. */
776     if( p0 != p1 )
777     {
778         int i_bcost_aq = i_bcost;
779         if( h->param.rc.i_aq_mode )
780             i_bcost_aq = (i_bcost_aq * fenc->i_inv_qscale_factor[i_mb_xy] + 128) >> 8;
781         output_inter[ROW_SATD] += i_bcost_aq;
782         if( b_frame_score_mb )
783         {
784             /* Don't use AQ-weighted costs for slicetype decision, only for ratecontrol. */
785             output_inter[COST_EST] += i_bcost;
786             output_inter[COST_EST_AQ] += i_bcost_aq;
787         }
788     }
789 
790     fenc->lowres_costs[b-p0][p1-b][i_mb_xy] = X264_MIN( i_bcost, LOWRES_COST_MASK ) + (list_used << LOWRES_COST_SHIFT);
791 }
792 #undef TRY_BIDIR
793 
794 #define NUM_MBS\
795    (h->mb.i_mb_width > 2 && h->mb.i_mb_height > 2 ?\
796    (h->mb.i_mb_width - 2) * (h->mb.i_mb_height - 2) :\
797     h->mb.i_mb_width * h->mb.i_mb_height)
798 
799 typedef struct
800 {
801     x264_t *h;
802     x264_mb_analysis_t *a;
803     x264_frame_t **frames;
804     int p0;
805     int p1;
806     int b;
807     int dist_scale_factor;
808     int *do_search;
809     const x264_weight_t *w;
810     int *output_inter;
811     int *output_intra;
812 } x264_slicetype_slice_t;
813 
slicetype_slice_cost(x264_slicetype_slice_t * s)814 static void slicetype_slice_cost( x264_slicetype_slice_t *s )
815 {
816     x264_t *h = s->h;
817 
818     /* Lowres lookahead goes backwards because the MVs are used as predictors in the main encode.
819      * This considerably improves MV prediction overall. */
820 
821     /* The edge mbs seem to reduce the predictive quality of the
822      * whole frame's score, but are needed for a spatial distribution. */
823     int do_edges = h->param.rc.b_mb_tree || h->param.rc.i_vbv_buffer_size || h->mb.i_mb_width <= 2 || h->mb.i_mb_height <= 2;
824 
825     int start_y = X264_MIN( h->i_threadslice_end - 1, h->mb.i_mb_height - 2 + do_edges );
826     int end_y = X264_MAX( h->i_threadslice_start, 1 - do_edges );
827     int start_x = h->mb.i_mb_width - 2 + do_edges;
828     int end_x = 1 - do_edges;
829 
830     for( h->mb.i_mb_y = start_y; h->mb.i_mb_y >= end_y; h->mb.i_mb_y-- )
831         for( h->mb.i_mb_x = start_x; h->mb.i_mb_x >= end_x; h->mb.i_mb_x-- )
832             slicetype_mb_cost( h, s->a, s->frames, s->p0, s->p1, s->b, s->dist_scale_factor,
833                                s->do_search, s->w, s->output_inter, s->output_intra );
834 }
835 
slicetype_frame_cost(x264_t * h,x264_mb_analysis_t * a,x264_frame_t ** frames,int p0,int p1,int b)836 static int slicetype_frame_cost( x264_t *h, x264_mb_analysis_t *a,
837                                  x264_frame_t **frames, int p0, int p1, int b )
838 {
839     int i_score = 0;
840     int do_search[2];
841     const x264_weight_t *w = x264_weight_none;
842     x264_frame_t *fenc = frames[b];
843 
844     /* Check whether we already evaluated this frame
845      * If we have tried this frame as P, then we have also tried
846      * the preceding frames as B. (is this still true?) */
847     /* Also check that we already calculated the row SATDs for the current frame. */
848     if( fenc->i_cost_est[b-p0][p1-b] >= 0 && (!h->param.rc.i_vbv_buffer_size || fenc->i_row_satds[b-p0][p1-b][0] != -1) )
849         i_score = fenc->i_cost_est[b-p0][p1-b];
850     else
851     {
852         int dist_scale_factor = 128;
853 
854         /* For each list, check to see whether we have lowres motion-searched this reference frame before. */
855         do_search[0] = b != p0 && fenc->lowres_mvs[0][b-p0-1][0][0] == 0x7FFF;
856         do_search[1] = b != p1 && fenc->lowres_mvs[1][p1-b-1][0][0] == 0x7FFF;
857         if( do_search[0] )
858         {
859             if( h->param.analyse.i_weighted_pred && b == p1 )
860             {
861                 x264_emms();
862                 x264_weights_analyse( h, fenc, frames[p0], 1 );
863                 w = fenc->weight[0];
864             }
865             fenc->lowres_mvs[0][b-p0-1][0][0] = 0;
866         }
867         if( do_search[1] ) fenc->lowres_mvs[1][p1-b-1][0][0] = 0;
868 
869         if( p1 != p0 )
870             dist_scale_factor = ( ((b-p0) << 8) + ((p1-p0) >> 1) ) / (p1-p0);
871 
872         int output_buf_size = h->mb.i_mb_height + (NUM_INTS + PAD_SIZE) * h->param.i_lookahead_threads;
873         int *output_inter[X264_LOOKAHEAD_THREAD_MAX+1];
874         int *output_intra[X264_LOOKAHEAD_THREAD_MAX+1];
875         output_inter[0] = h->scratch_buffer2;
876         output_intra[0] = output_inter[0] + output_buf_size;
877 
878 #if HAVE_OPENCL
879         if( h->param.b_opencl )
880         {
881             x264_opencl_lowres_init(h, fenc, a->i_lambda );
882             if( do_search[0] )
883             {
884                 x264_opencl_lowres_init( h, frames[p0], a->i_lambda );
885                 x264_opencl_motionsearch( h, frames, b, p0, 0, a->i_lambda, w );
886             }
887             if( do_search[1] )
888             {
889                 x264_opencl_lowres_init( h, frames[p1], a->i_lambda );
890                 x264_opencl_motionsearch( h, frames, b, p1, 1, a->i_lambda, NULL );
891             }
892             if( b != p0 )
893                 x264_opencl_finalize_cost( h, a->i_lambda, frames, p0, p1, b, dist_scale_factor );
894             x264_opencl_flush( h );
895 
896             i_score = fenc->i_cost_est[b-p0][p1-b];
897         }
898         else
899 #endif
900         {
901             if( h->param.i_lookahead_threads > 1 )
902             {
903                 x264_slicetype_slice_t s[X264_LOOKAHEAD_THREAD_MAX];
904 
905                 for( int i = 0; i < h->param.i_lookahead_threads; i++ )
906                 {
907                     x264_t *t = h->lookahead_thread[i];
908 
909                     /* FIXME move this somewhere else */
910                     t->mb.i_me_method = h->mb.i_me_method;
911                     t->mb.i_subpel_refine = h->mb.i_subpel_refine;
912                     t->mb.b_chroma_me = h->mb.b_chroma_me;
913 
914                     s[i] = (x264_slicetype_slice_t){ t, a, frames, p0, p1, b, dist_scale_factor, do_search, w,
915                         output_inter[i], output_intra[i] };
916 
917                     t->i_threadslice_start = ((h->mb.i_mb_height *  i    + h->param.i_lookahead_threads/2) / h->param.i_lookahead_threads);
918                     t->i_threadslice_end   = ((h->mb.i_mb_height * (i+1) + h->param.i_lookahead_threads/2) / h->param.i_lookahead_threads);
919 
920                     int thread_height = t->i_threadslice_end - t->i_threadslice_start;
921                     int thread_output_size = thread_height + NUM_INTS;
922                     memset( output_inter[i], 0, thread_output_size * sizeof(int) );
923                     memset( output_intra[i], 0, thread_output_size * sizeof(int) );
924                     output_inter[i][NUM_ROWS] = output_intra[i][NUM_ROWS] = thread_height;
925 
926                     output_inter[i+1] = output_inter[i] + thread_output_size + PAD_SIZE;
927                     output_intra[i+1] = output_intra[i] + thread_output_size + PAD_SIZE;
928 
929                     x264_threadpool_run( h->lookaheadpool, (void*)slicetype_slice_cost, &s[i] );
930                 }
931                 for( int i = 0; i < h->param.i_lookahead_threads; i++ )
932                     x264_threadpool_wait( h->lookaheadpool, &s[i] );
933             }
934             else
935             {
936                 h->i_threadslice_start = 0;
937                 h->i_threadslice_end = h->mb.i_mb_height;
938                 memset( output_inter[0], 0, (output_buf_size - PAD_SIZE) * sizeof(int) );
939                 memset( output_intra[0], 0, (output_buf_size - PAD_SIZE) * sizeof(int) );
940                 output_inter[0][NUM_ROWS] = output_intra[0][NUM_ROWS] = h->mb.i_mb_height;
941                 x264_slicetype_slice_t s = (x264_slicetype_slice_t){ h, a, frames, p0, p1, b, dist_scale_factor, do_search, w,
942                     output_inter[0], output_intra[0] };
943                 slicetype_slice_cost( &s );
944             }
945 
946             /* Sum up accumulators */
947             if( b == p1 )
948                 fenc->i_intra_mbs[b-p0] = 0;
949             if( !fenc->b_intra_calculated )
950             {
951                 fenc->i_cost_est[0][0] = 0;
952                 fenc->i_cost_est_aq[0][0] = 0;
953             }
954             fenc->i_cost_est[b-p0][p1-b] = 0;
955             fenc->i_cost_est_aq[b-p0][p1-b] = 0;
956 
957             int *row_satd_inter = fenc->i_row_satds[b-p0][p1-b];
958             int *row_satd_intra = fenc->i_row_satds[0][0];
959             for( int i = 0; i < h->param.i_lookahead_threads; i++ )
960             {
961                 if( b == p1 )
962                     fenc->i_intra_mbs[b-p0] += output_inter[i][INTRA_MBS];
963                 if( !fenc->b_intra_calculated )
964                 {
965                     fenc->i_cost_est[0][0] += output_intra[i][COST_EST];
966                     fenc->i_cost_est_aq[0][0] += output_intra[i][COST_EST_AQ];
967                 }
968 
969                 fenc->i_cost_est[b-p0][p1-b] += output_inter[i][COST_EST];
970                 fenc->i_cost_est_aq[b-p0][p1-b] += output_inter[i][COST_EST_AQ];
971 
972                 if( h->param.rc.i_vbv_buffer_size )
973                 {
974                     int row_count = output_inter[i][NUM_ROWS];
975                     memcpy( row_satd_inter, output_inter[i] + NUM_INTS, row_count * sizeof(int) );
976                     if( !fenc->b_intra_calculated )
977                         memcpy( row_satd_intra, output_intra[i] + NUM_INTS, row_count * sizeof(int) );
978                     row_satd_inter += row_count;
979                     row_satd_intra += row_count;
980                 }
981             }
982 
983             i_score = fenc->i_cost_est[b-p0][p1-b];
984             if( b != p1 )
985                 i_score = (uint64_t)i_score * 100 / (120 + h->param.i_bframe_bias);
986             else
987                 fenc->b_intra_calculated = 1;
988 
989             fenc->i_cost_est[b-p0][p1-b] = i_score;
990             x264_emms();
991         }
992     }
993 
994     return i_score;
995 }
996 
997 /* If MB-tree changes the quantizers, we need to recalculate the frame cost without
998  * re-running lookahead. */
slicetype_frame_cost_recalculate(x264_t * h,x264_frame_t ** frames,int p0,int p1,int b)999 static int slicetype_frame_cost_recalculate( x264_t *h, x264_frame_t **frames, int p0, int p1, int b )
1000 {
1001     int i_score = 0;
1002     int *row_satd = frames[b]->i_row_satds[b-p0][p1-b];
1003     float *qp_offset = IS_X264_TYPE_B(frames[b]->i_type) ? frames[b]->f_qp_offset_aq : frames[b]->f_qp_offset;
1004     x264_emms();
1005     for( h->mb.i_mb_y = h->mb.i_mb_height - 1; h->mb.i_mb_y >= 0; h->mb.i_mb_y-- )
1006     {
1007         row_satd[ h->mb.i_mb_y ] = 0;
1008         for( h->mb.i_mb_x = h->mb.i_mb_width - 1; h->mb.i_mb_x >= 0; h->mb.i_mb_x-- )
1009         {
1010             int i_mb_xy = h->mb.i_mb_x + h->mb.i_mb_y*h->mb.i_mb_stride;
1011             int i_mb_cost = frames[b]->lowres_costs[b-p0][p1-b][i_mb_xy] & LOWRES_COST_MASK;
1012             float qp_adj = qp_offset[i_mb_xy];
1013             i_mb_cost = (i_mb_cost * x264_exp2fix8(qp_adj) + 128) >> 8;
1014             row_satd[ h->mb.i_mb_y ] += i_mb_cost;
1015             if( (h->mb.i_mb_y > 0 && h->mb.i_mb_y < h->mb.i_mb_height - 1 &&
1016                  h->mb.i_mb_x > 0 && h->mb.i_mb_x < h->mb.i_mb_width - 1) ||
1017                  h->mb.i_mb_width <= 2 || h->mb.i_mb_height <= 2 )
1018             {
1019                 i_score += i_mb_cost;
1020             }
1021         }
1022     }
1023     return i_score;
1024 }
1025 
1026 /* Trade off precision in mbtree for increased range */
1027 #define MBTREE_PRECISION 0.5f
1028 
macroblock_tree_finish(x264_t * h,x264_frame_t * frame,float average_duration,int ref0_distance)1029 static void macroblock_tree_finish( x264_t *h, x264_frame_t *frame, float average_duration, int ref0_distance )
1030 {
1031     int fps_factor = round( CLIP_DURATION(average_duration) / CLIP_DURATION(frame->f_duration) * 256 / MBTREE_PRECISION );
1032     float weightdelta = 0.0;
1033     if( ref0_distance && frame->f_weighted_cost_delta[ref0_distance-1] > 0 )
1034         weightdelta = (1.0 - frame->f_weighted_cost_delta[ref0_distance-1]);
1035 
1036     /* Allow the strength to be adjusted via qcompress, since the two
1037      * concepts are very similar. */
1038     float strength = 5.0f * (1.0f - h->param.rc.f_qcompress);
1039     for( int mb_index = 0; mb_index < h->mb.i_mb_count; mb_index++ )
1040     {
1041         int intra_cost = (frame->i_intra_cost[mb_index] * frame->i_inv_qscale_factor[mb_index] + 128) >> 8;
1042         if( intra_cost )
1043         {
1044             int propagate_cost = (frame->i_propagate_cost[mb_index] * fps_factor + 128) >> 8;
1045             float log2_ratio = x264_log2(intra_cost + propagate_cost) - x264_log2(intra_cost) + weightdelta;
1046             frame->f_qp_offset[mb_index] = frame->f_qp_offset_aq[mb_index] - strength * log2_ratio;
1047         }
1048     }
1049 }
1050 
macroblock_tree_propagate(x264_t * h,x264_frame_t ** frames,float average_duration,int p0,int p1,int b,int referenced)1051 static void macroblock_tree_propagate( x264_t *h, x264_frame_t **frames, float average_duration, int p0, int p1, int b, int referenced )
1052 {
1053     uint16_t *ref_costs[2] = {frames[p0]->i_propagate_cost,frames[p1]->i_propagate_cost};
1054     int dist_scale_factor = ( ((b-p0) << 8) + ((p1-p0) >> 1) ) / (p1-p0);
1055     int i_bipred_weight = h->param.analyse.b_weighted_bipred ? 64 - (dist_scale_factor>>2) : 32;
1056     int16_t (*mvs[2])[2] = { b != p0 ? frames[b]->lowres_mvs[0][b-p0-1] : NULL, b != p1 ? frames[b]->lowres_mvs[1][p1-b-1] : NULL };
1057     int bipred_weights[2] = {i_bipred_weight, 64 - i_bipred_weight};
1058     int16_t *buf = h->scratch_buffer;
1059     uint16_t *propagate_cost = frames[b]->i_propagate_cost;
1060     uint16_t *lowres_costs = frames[b]->lowres_costs[b-p0][p1-b];
1061 
1062     x264_emms();
1063     float fps_factor = CLIP_DURATION(frames[b]->f_duration) / (CLIP_DURATION(average_duration) * 256.0f) * MBTREE_PRECISION;
1064 
1065     /* For non-reffed frames the source costs are always zero, so just memset one row and re-use it. */
1066     if( !referenced )
1067         memset( frames[b]->i_propagate_cost, 0, h->mb.i_mb_width * sizeof(uint16_t) );
1068 
1069     for( h->mb.i_mb_y = 0; h->mb.i_mb_y < h->mb.i_mb_height; h->mb.i_mb_y++ )
1070     {
1071         int mb_index = h->mb.i_mb_y*h->mb.i_mb_stride;
1072         h->mc.mbtree_propagate_cost( buf, propagate_cost,
1073             frames[b]->i_intra_cost+mb_index, lowres_costs+mb_index,
1074             frames[b]->i_inv_qscale_factor+mb_index, &fps_factor, h->mb.i_mb_width );
1075         if( referenced )
1076             propagate_cost += h->mb.i_mb_width;
1077 
1078         h->mc.mbtree_propagate_list( h, ref_costs[0], &mvs[0][mb_index], buf, &lowres_costs[mb_index],
1079                                      bipred_weights[0], h->mb.i_mb_y, h->mb.i_mb_width, 0 );
1080         if( b != p1 )
1081         {
1082             h->mc.mbtree_propagate_list( h, ref_costs[1], &mvs[1][mb_index], buf, &lowres_costs[mb_index],
1083                                          bipred_weights[1], h->mb.i_mb_y, h->mb.i_mb_width, 1 );
1084         }
1085     }
1086 
1087     if( h->param.rc.i_vbv_buffer_size && h->param.rc.i_lookahead && referenced )
1088         macroblock_tree_finish( h, frames[b], average_duration, b == p1 ? b - p0 : 0 );
1089 }
1090 
macroblock_tree(x264_t * h,x264_mb_analysis_t * a,x264_frame_t ** frames,int num_frames,int b_intra)1091 static void macroblock_tree( x264_t *h, x264_mb_analysis_t *a, x264_frame_t **frames, int num_frames, int b_intra )
1092 {
1093     int idx = !b_intra;
1094     int last_nonb, cur_nonb = 1;
1095     int bframes = 0;
1096 
1097     x264_emms();
1098     float total_duration = 0.0;
1099     for( int j = 0; j <= num_frames; j++ )
1100         total_duration += frames[j]->f_duration;
1101     float average_duration = total_duration / (num_frames + 1);
1102 
1103     int i = num_frames;
1104 
1105     if( b_intra )
1106         slicetype_frame_cost( h, a, frames, 0, 0, 0 );
1107 
1108     while( i > 0 && IS_X264_TYPE_B( frames[i]->i_type ) )
1109         i--;
1110     last_nonb = i;
1111 
1112     /* Lookaheadless MB-tree is not a theoretically distinct case; the same extrapolation could
1113      * be applied to the end of a lookahead buffer of any size.  However, it's most needed when
1114      * lookahead=0, so that's what's currently implemented. */
1115     if( !h->param.rc.i_lookahead )
1116     {
1117         if( b_intra )
1118         {
1119             memset( frames[0]->i_propagate_cost, 0, h->mb.i_mb_count * sizeof(uint16_t) );
1120             memcpy( frames[0]->f_qp_offset, frames[0]->f_qp_offset_aq, h->mb.i_mb_count * sizeof(float) );
1121             return;
1122         }
1123         XCHG( uint16_t*, frames[last_nonb]->i_propagate_cost, frames[0]->i_propagate_cost );
1124         memset( frames[0]->i_propagate_cost, 0, h->mb.i_mb_count * sizeof(uint16_t) );
1125     }
1126     else
1127     {
1128         if( last_nonb < idx )
1129             return;
1130         memset( frames[last_nonb]->i_propagate_cost, 0, h->mb.i_mb_count * sizeof(uint16_t) );
1131     }
1132 
1133     while( i-- > idx )
1134     {
1135         cur_nonb = i;
1136         while( IS_X264_TYPE_B( frames[cur_nonb]->i_type ) && cur_nonb > 0 )
1137             cur_nonb--;
1138         if( cur_nonb < idx )
1139             break;
1140         slicetype_frame_cost( h, a, frames, cur_nonb, last_nonb, last_nonb );
1141         memset( frames[cur_nonb]->i_propagate_cost, 0, h->mb.i_mb_count * sizeof(uint16_t) );
1142         bframes = last_nonb - cur_nonb - 1;
1143         if( h->param.i_bframe_pyramid && bframes > 1 )
1144         {
1145             int middle = (bframes + 1)/2 + cur_nonb;
1146             slicetype_frame_cost( h, a, frames, cur_nonb, last_nonb, middle );
1147             memset( frames[middle]->i_propagate_cost, 0, h->mb.i_mb_count * sizeof(uint16_t) );
1148             while( i > cur_nonb )
1149             {
1150                 int p0 = i > middle ? middle : cur_nonb;
1151                 int p1 = i < middle ? middle : last_nonb;
1152                 if( i != middle )
1153                 {
1154                     slicetype_frame_cost( h, a, frames, p0, p1, i );
1155                     macroblock_tree_propagate( h, frames, average_duration, p0, p1, i, 0 );
1156                 }
1157                 i--;
1158             }
1159             macroblock_tree_propagate( h, frames, average_duration, cur_nonb, last_nonb, middle, 1 );
1160         }
1161         else
1162         {
1163             while( i > cur_nonb )
1164             {
1165                 slicetype_frame_cost( h, a, frames, cur_nonb, last_nonb, i );
1166                 macroblock_tree_propagate( h, frames, average_duration, cur_nonb, last_nonb, i, 0 );
1167                 i--;
1168             }
1169         }
1170         macroblock_tree_propagate( h, frames, average_duration, cur_nonb, last_nonb, last_nonb, 1 );
1171         last_nonb = cur_nonb;
1172     }
1173 
1174     if( !h->param.rc.i_lookahead )
1175     {
1176         slicetype_frame_cost( h, a, frames, 0, last_nonb, last_nonb );
1177         macroblock_tree_propagate( h, frames, average_duration, 0, last_nonb, last_nonb, 1 );
1178         XCHG( uint16_t*, frames[last_nonb]->i_propagate_cost, frames[0]->i_propagate_cost );
1179     }
1180 
1181     macroblock_tree_finish( h, frames[last_nonb], average_duration, last_nonb );
1182     if( h->param.i_bframe_pyramid && bframes > 1 && !h->param.rc.i_vbv_buffer_size )
1183         macroblock_tree_finish( h, frames[last_nonb+(bframes+1)/2], average_duration, 0 );
1184 }
1185 
vbv_frame_cost(x264_t * h,x264_mb_analysis_t * a,x264_frame_t ** frames,int p0,int p1,int b)1186 static int vbv_frame_cost( x264_t *h, x264_mb_analysis_t *a, x264_frame_t **frames, int p0, int p1, int b )
1187 {
1188     int cost = slicetype_frame_cost( h, a, frames, p0, p1, b );
1189     if( h->param.rc.i_aq_mode )
1190     {
1191         if( h->param.rc.b_mb_tree )
1192             return slicetype_frame_cost_recalculate( h, frames, p0, p1, b );
1193         else
1194             return frames[b]->i_cost_est_aq[b-p0][p1-b];
1195     }
1196     return cost;
1197 }
1198 
calculate_durations(x264_t * h,x264_frame_t * cur_frame,x264_frame_t * prev_frame,int64_t * i_cpb_delay,int64_t * i_coded_fields)1199 static void calculate_durations( x264_t *h, x264_frame_t *cur_frame, x264_frame_t *prev_frame, int64_t *i_cpb_delay, int64_t *i_coded_fields )
1200 {
1201     cur_frame->i_cpb_delay = *i_cpb_delay;
1202     cur_frame->i_dpb_output_delay = cur_frame->i_field_cnt - *i_coded_fields;
1203 
1204     // add a correction term for frame reordering
1205     cur_frame->i_dpb_output_delay += h->sps->vui.i_num_reorder_frames*2;
1206 
1207     // fix possible negative dpb_output_delay because of pulldown changes and reordering
1208     if( cur_frame->i_dpb_output_delay < 0 )
1209     {
1210         cur_frame->i_cpb_delay += cur_frame->i_dpb_output_delay;
1211         cur_frame->i_dpb_output_delay = 0;
1212         if( prev_frame )
1213             prev_frame->i_cpb_duration += cur_frame->i_dpb_output_delay;
1214     }
1215 
1216     // don't reset cpb delay for IDR frames when using intra-refresh
1217     if( cur_frame->b_keyframe && !h->param.b_intra_refresh )
1218         *i_cpb_delay = 0;
1219 
1220     *i_cpb_delay += cur_frame->i_duration;
1221     *i_coded_fields += cur_frame->i_duration;
1222     cur_frame->i_cpb_duration = cur_frame->i_duration;
1223 }
1224 
vbv_lookahead(x264_t * h,x264_mb_analysis_t * a,x264_frame_t ** frames,int num_frames,int keyframe)1225 static void vbv_lookahead( x264_t *h, x264_mb_analysis_t *a, x264_frame_t **frames, int num_frames, int keyframe )
1226 {
1227     int last_nonb = 0, cur_nonb = 1, idx = 0;
1228     x264_frame_t *prev_frame = NULL;
1229     int prev_frame_idx = 0;
1230     while( cur_nonb < num_frames && IS_X264_TYPE_B( frames[cur_nonb]->i_type ) )
1231         cur_nonb++;
1232     int next_nonb = keyframe ? last_nonb : cur_nonb;
1233 
1234     if( frames[cur_nonb]->i_coded_fields_lookahead >= 0 )
1235     {
1236         h->i_coded_fields_lookahead = frames[cur_nonb]->i_coded_fields_lookahead;
1237         h->i_cpb_delay_lookahead = frames[cur_nonb]->i_cpb_delay_lookahead;
1238     }
1239 
1240     while( cur_nonb < num_frames )
1241     {
1242         /* P/I cost: This shouldn't include the cost of next_nonb */
1243         if( next_nonb != cur_nonb )
1244         {
1245             int p0 = IS_X264_TYPE_I( frames[cur_nonb]->i_type ) ? cur_nonb : last_nonb;
1246             frames[next_nonb]->i_planned_satd[idx] = vbv_frame_cost( h, a, frames, p0, cur_nonb, cur_nonb );
1247             frames[next_nonb]->i_planned_type[idx] = frames[cur_nonb]->i_type;
1248             frames[cur_nonb]->i_coded_fields_lookahead = h->i_coded_fields_lookahead;
1249             frames[cur_nonb]->i_cpb_delay_lookahead = h->i_cpb_delay_lookahead;
1250             calculate_durations( h, frames[cur_nonb], prev_frame, &h->i_cpb_delay_lookahead, &h->i_coded_fields_lookahead );
1251             if( prev_frame )
1252             {
1253                 frames[next_nonb]->f_planned_cpb_duration[prev_frame_idx] = (double)prev_frame->i_cpb_duration *
1254                                                                             h->sps->vui.i_num_units_in_tick / h->sps->vui.i_time_scale;
1255             }
1256             frames[next_nonb]->f_planned_cpb_duration[idx] = (double)frames[cur_nonb]->i_cpb_duration *
1257                                                              h->sps->vui.i_num_units_in_tick / h->sps->vui.i_time_scale;
1258             prev_frame = frames[cur_nonb];
1259             prev_frame_idx = idx;
1260             idx++;
1261         }
1262         /* Handle the B-frames: coded order */
1263         for( int i = last_nonb+1; i < cur_nonb; i++, idx++ )
1264         {
1265             frames[next_nonb]->i_planned_satd[idx] = vbv_frame_cost( h, a, frames, last_nonb, cur_nonb, i );
1266             frames[next_nonb]->i_planned_type[idx] = X264_TYPE_B;
1267             frames[i]->i_coded_fields_lookahead = h->i_coded_fields_lookahead;
1268             frames[i]->i_cpb_delay_lookahead = h->i_cpb_delay_lookahead;
1269             calculate_durations( h, frames[i], prev_frame, &h->i_cpb_delay_lookahead, &h->i_coded_fields_lookahead );
1270             if( prev_frame )
1271             {
1272                 frames[next_nonb]->f_planned_cpb_duration[prev_frame_idx] = (double)prev_frame->i_cpb_duration *
1273                                                                             h->sps->vui.i_num_units_in_tick / h->sps->vui.i_time_scale;
1274             }
1275             frames[next_nonb]->f_planned_cpb_duration[idx] = (double)frames[i]->i_cpb_duration *
1276                                                              h->sps->vui.i_num_units_in_tick / h->sps->vui.i_time_scale;
1277             prev_frame = frames[i];
1278             prev_frame_idx = idx;
1279         }
1280         last_nonb = cur_nonb;
1281         cur_nonb++;
1282         while( cur_nonb <= num_frames && IS_X264_TYPE_B( frames[cur_nonb]->i_type ) )
1283             cur_nonb++;
1284     }
1285     frames[next_nonb]->i_planned_type[idx] = X264_TYPE_AUTO;
1286 }
1287 
slicetype_path_cost(x264_t * h,x264_mb_analysis_t * a,x264_frame_t ** frames,char * path,uint64_t threshold)1288 static uint64_t slicetype_path_cost( x264_t *h, x264_mb_analysis_t *a, x264_frame_t **frames, char *path, uint64_t threshold )
1289 {
1290     uint64_t cost = 0;
1291     int loc = 1;
1292     int cur_nonb = 0;
1293     path--; /* Since the 1st path element is really the second frame */
1294     while( path[loc] )
1295     {
1296         int next_nonb = loc;
1297         /* Find the location of the next non-B-frame. */
1298         while( path[next_nonb] == 'B' )
1299             next_nonb++;
1300 
1301         /* Add the cost of the non-B-frame found above */
1302         if( path[next_nonb] == 'P' )
1303             cost += slicetype_frame_cost( h, a, frames, cur_nonb, next_nonb, next_nonb );
1304         else /* I-frame */
1305             cost += slicetype_frame_cost( h, a, frames, next_nonb, next_nonb, next_nonb );
1306         /* Early terminate if the cost we have found is larger than the best path cost so far */
1307         if( cost > threshold )
1308             break;
1309 
1310         if( h->param.i_bframe_pyramid && next_nonb - cur_nonb > 2 )
1311         {
1312             int middle = cur_nonb + (next_nonb - cur_nonb)/2;
1313             cost += slicetype_frame_cost( h, a, frames, cur_nonb, next_nonb, middle );
1314             for( int next_b = loc; next_b < middle && cost < threshold; next_b++ )
1315                 cost += slicetype_frame_cost( h, a, frames, cur_nonb, middle, next_b );
1316             for( int next_b = middle+1; next_b < next_nonb && cost < threshold; next_b++ )
1317                 cost += slicetype_frame_cost( h, a, frames, middle, next_nonb, next_b );
1318         }
1319         else
1320             for( int next_b = loc; next_b < next_nonb && cost < threshold; next_b++ )
1321                 cost += slicetype_frame_cost( h, a, frames, cur_nonb, next_nonb, next_b );
1322 
1323         loc = next_nonb + 1;
1324         cur_nonb = next_nonb;
1325     }
1326     return cost;
1327 }
1328 
1329 /* Viterbi/trellis slicetype decision algorithm. */
1330 /* Uses strings due to the fact that the speed of the control functions is
1331    negligible compared to the cost of running slicetype_frame_cost, and because
1332    it makes debugging easier. */
slicetype_path(x264_t * h,x264_mb_analysis_t * a,x264_frame_t ** frames,int length,char (* best_paths)[X264_LOOKAHEAD_MAX+1])1333 static void slicetype_path( x264_t *h, x264_mb_analysis_t *a, x264_frame_t **frames, int length, char (*best_paths)[X264_LOOKAHEAD_MAX+1] )
1334 {
1335     char paths[2][X264_LOOKAHEAD_MAX+1];
1336     int num_paths = X264_MIN( h->param.i_bframe+1, length );
1337     uint64_t best_cost = COST_MAX64;
1338     int best_possible = 0;
1339     int idx = 0;
1340 
1341     /* Iterate over all currently possible paths */
1342     for( int path = 0; path < num_paths; path++ )
1343     {
1344         /* Add suffixes to the current path */
1345         int len = length - (path + 1);
1346         memcpy( paths[idx], best_paths[len % (X264_BFRAME_MAX+1)], len );
1347         memset( paths[idx]+len, 'B', path );
1348         strcpy( paths[idx]+len+path, "P" );
1349 
1350         int possible = 1;
1351         for( int i = 1; i <= length; i++ )
1352         {
1353             int i_type = frames[i]->i_type;
1354             if( i_type == X264_TYPE_AUTO )
1355                 continue;
1356             if( IS_X264_TYPE_B( i_type ) )
1357                 possible = possible && (i < len || i == length || paths[idx][i-1] == 'B');
1358             else
1359             {
1360                 possible = possible && (i < len || paths[idx][i-1] != 'B');
1361                 paths[idx][i-1] = IS_X264_TYPE_I( i_type ) ? 'I' : 'P';
1362             }
1363         }
1364 
1365         if( possible || !best_possible )
1366         {
1367             if( possible && !best_possible )
1368                 best_cost = COST_MAX64;
1369             /* Calculate the actual cost of the current path */
1370             uint64_t cost = slicetype_path_cost( h, a, frames, paths[idx], best_cost );
1371             if( cost < best_cost )
1372             {
1373                 best_cost = cost;
1374                 best_possible = possible;
1375                 idx ^= 1;
1376             }
1377         }
1378     }
1379 
1380     /* Store the best path. */
1381     memcpy( best_paths[length % (X264_BFRAME_MAX+1)], paths[idx^1], length );
1382 }
1383 
scenecut_internal(x264_t * h,x264_mb_analysis_t * a,x264_frame_t ** frames,int p0,int p1,int real_scenecut)1384 static int scenecut_internal( x264_t *h, x264_mb_analysis_t *a, x264_frame_t **frames, int p0, int p1, int real_scenecut )
1385 {
1386     x264_frame_t *frame = frames[p1];
1387 
1388     /* Don't do scenecuts on the right view of a frame-packed video. */
1389     if( real_scenecut && h->param.i_frame_packing == 5 && (frame->i_frame&1) )
1390         return 0;
1391 
1392     slicetype_frame_cost( h, a, frames, p0, p1, p1 );
1393 
1394     int icost = frame->i_cost_est[0][0];
1395     int pcost = frame->i_cost_est[p1-p0][0];
1396     float f_bias;
1397     int i_gop_size = frame->i_frame - h->lookahead->i_last_keyframe;
1398     float f_thresh_max = h->param.i_scenecut_threshold / 100.0;
1399     /* magic numbers pulled out of thin air */
1400     float f_thresh_min = f_thresh_max * 0.25;
1401     int res;
1402 
1403     if( h->param.i_keyint_min == h->param.i_keyint_max )
1404         f_thresh_min = f_thresh_max;
1405     if( i_gop_size <= h->param.i_keyint_min / 4 || h->param.b_intra_refresh )
1406         f_bias = f_thresh_min / 4;
1407     else if( i_gop_size <= h->param.i_keyint_min )
1408         f_bias = f_thresh_min * i_gop_size / h->param.i_keyint_min;
1409     else
1410     {
1411         f_bias = f_thresh_min
1412                  + ( f_thresh_max - f_thresh_min )
1413                  * ( i_gop_size - h->param.i_keyint_min )
1414                  / ( h->param.i_keyint_max - h->param.i_keyint_min );
1415     }
1416 
1417     res = pcost >= (1.0 - f_bias) * icost;
1418     if( res && real_scenecut )
1419     {
1420         int imb = frame->i_intra_mbs[p1-p0];
1421         int pmb = NUM_MBS - imb;
1422         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",
1423                   frame->i_frame,
1424                   icost, pcost, 1. - (double)pcost / icost,
1425                   f_bias, i_gop_size, imb, pmb );
1426     }
1427     return res;
1428 }
1429 
scenecut(x264_t * h,x264_mb_analysis_t * a,x264_frame_t ** frames,int p0,int p1,int real_scenecut,int num_frames,int i_max_search)1430 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, int i_max_search )
1431 {
1432     /* Only do analysis during a normal scenecut check. */
1433     if( real_scenecut && h->param.i_bframe )
1434     {
1435         int origmaxp1 = p0 + 1;
1436         /* Look ahead to avoid coding short flashes as scenecuts. */
1437         if( h->param.i_bframe_adaptive == X264_B_ADAPT_TRELLIS )
1438             /* Don't analyse any more frames than the trellis would have covered. */
1439             origmaxp1 += h->param.i_bframe;
1440         else
1441             origmaxp1++;
1442         int maxp1 = X264_MIN( origmaxp1, num_frames );
1443 
1444         /* Where A and B are scenes: AAAAAABBBAAAAAA
1445          * If BBB is shorter than (maxp1-p0), it is detected as a flash
1446          * and not considered a scenecut. */
1447         for( int curp1 = p1; curp1 <= maxp1; curp1++ )
1448             if( !scenecut_internal( h, a, frames, p0, curp1, 0 ) )
1449                 /* Any frame in between p0 and cur_p1 cannot be a real scenecut. */
1450                 for( int i = curp1; i > p0; i-- )
1451                     frames[i]->b_scenecut = 0;
1452 
1453         /* Where A-F are scenes: AAAAABBCCDDEEFFFFFF
1454          * If each of BB ... EE are shorter than (maxp1-p0), they are
1455          * detected as flashes and not considered scenecuts.
1456          * Instead, the first F frame becomes a scenecut.
1457          * If the video ends before F, no frame becomes a scenecut. */
1458         for( int curp0 = p0; curp0 <= maxp1; curp0++ )
1459             if( origmaxp1 > i_max_search || (curp0 < maxp1 && scenecut_internal( h, a, frames, curp0, maxp1, 0 )) )
1460                 /* If cur_p0 is the p0 of a scenecut, it cannot be the p1 of a scenecut. */
1461                     frames[curp0]->b_scenecut = 0;
1462     }
1463 
1464     /* Ignore frames that are part of a flash, i.e. cannot be real scenecuts. */
1465     if( !frames[p1]->b_scenecut )
1466         return 0;
1467     return scenecut_internal( h, a, frames, p0, p1, real_scenecut );
1468 }
1469 
1470 #define IS_X264_TYPE_AUTO_OR_I(x) ((x)==X264_TYPE_AUTO || IS_X264_TYPE_I(x))
1471 #define IS_X264_TYPE_AUTO_OR_B(x) ((x)==X264_TYPE_AUTO || IS_X264_TYPE_B(x))
1472 
x264_slicetype_analyse(x264_t * h,int intra_minigop)1473 void x264_slicetype_analyse( x264_t *h, int intra_minigop )
1474 {
1475     x264_mb_analysis_t a;
1476     x264_frame_t *frames[X264_LOOKAHEAD_MAX+3] = { NULL, };
1477     int num_frames, orig_num_frames, keyint_limit, framecnt;
1478     int i_max_search = X264_MIN( h->lookahead->next.i_size, X264_LOOKAHEAD_MAX );
1479     int b_vbv_lookahead = h->param.rc.i_vbv_buffer_size && h->param.rc.i_lookahead;
1480     /* For determinism we should limit the search to the number of frames lookahead has for sure
1481      * in h->lookahead->next.list buffer, except at the end of stream.
1482      * For normal calls with (intra_minigop == 0) that is h->lookahead->i_slicetype_length + 1 frames.
1483      * And for I-frame calls (intra_minigop != 0) we already removed intra_minigop frames from there. */
1484     if( h->param.b_deterministic )
1485         i_max_search = X264_MIN( i_max_search, h->lookahead->i_slicetype_length + 1 - intra_minigop );
1486     int keyframe = !!intra_minigop;
1487 
1488     assert( h->frames.b_have_lowres );
1489 
1490     if( !h->lookahead->last_nonb )
1491         return;
1492     frames[0] = h->lookahead->last_nonb;
1493     for( framecnt = 0; framecnt < i_max_search; framecnt++ )
1494         frames[framecnt+1] = h->lookahead->next.list[framecnt];
1495 
1496     lowres_context_init( h, &a );
1497 
1498     if( !framecnt )
1499     {
1500         if( h->param.rc.b_mb_tree )
1501             macroblock_tree( h, &a, frames, 0, keyframe );
1502         return;
1503     }
1504 
1505     keyint_limit = h->param.i_keyint_max - frames[0]->i_frame + h->lookahead->i_last_keyframe - 1;
1506     orig_num_frames = num_frames = h->param.b_intra_refresh ? framecnt : X264_MIN( framecnt, keyint_limit );
1507 
1508     /* This is important psy-wise: if we have a non-scenecut keyframe,
1509      * there will be significant visual artifacts if the frames just before
1510      * go down in quality due to being referenced less, despite it being
1511      * more RD-optimal. */
1512     if( (h->param.analyse.b_psy && h->param.rc.b_mb_tree) || b_vbv_lookahead )
1513         num_frames = framecnt;
1514     else if( h->param.b_open_gop && num_frames < framecnt )
1515         num_frames++;
1516     else if( num_frames == 0 )
1517     {
1518         frames[1]->i_type = X264_TYPE_I;
1519         return;
1520     }
1521 
1522     if( IS_X264_TYPE_AUTO_OR_I( frames[1]->i_type ) &&
1523         h->param.i_scenecut_threshold && scenecut( h, &a, frames, 0, 1, 1, orig_num_frames, i_max_search ) )
1524     {
1525         if( frames[1]->i_type == X264_TYPE_AUTO )
1526             frames[1]->i_type = X264_TYPE_I;
1527         return;
1528     }
1529 
1530 #if HAVE_OPENCL
1531     x264_opencl_slicetype_prep( h, frames, num_frames, a.i_lambda );
1532 #endif
1533 
1534     /* Replace forced keyframes with I/IDR-frames */
1535     for( int j = 1; j <= num_frames; j++ )
1536     {
1537         if( frames[j]->i_type == X264_TYPE_KEYFRAME )
1538             frames[j]->i_type = h->param.b_open_gop ? X264_TYPE_I : X264_TYPE_IDR;
1539     }
1540 
1541     /* Close GOP at IDR-frames */
1542     for( int j = 2; j <= num_frames; j++ )
1543     {
1544         if( frames[j]->i_type == X264_TYPE_IDR && IS_X264_TYPE_AUTO_OR_B( frames[j-1]->i_type ) )
1545             frames[j-1]->i_type = X264_TYPE_P;
1546     }
1547 
1548     int num_analysed_frames = num_frames;
1549     int reset_start;
1550 
1551     if( h->param.i_bframe )
1552     {
1553         if( h->param.i_bframe_adaptive == X264_B_ADAPT_TRELLIS )
1554         {
1555             if( num_frames > 1 )
1556             {
1557                 char best_paths[X264_BFRAME_MAX+1][X264_LOOKAHEAD_MAX+1] = {"","P"};
1558                 int best_path_index = num_frames % (X264_BFRAME_MAX+1);
1559 
1560                 /* Perform the frametype analysis. */
1561                 for( int j = 2; j <= num_frames; j++ )
1562                     slicetype_path( h, &a, frames, j, best_paths );
1563 
1564                 /* Load the results of the analysis into the frame types. */
1565                 for( int j = 1; j < num_frames; j++ )
1566                 {
1567                     if( best_paths[best_path_index][j-1] != 'B' )
1568                     {
1569                         if( IS_X264_TYPE_AUTO_OR_B( frames[j]->i_type ) )
1570                             frames[j]->i_type = X264_TYPE_P;
1571                     }
1572                     else
1573                     {
1574                         if( frames[j]->i_type == X264_TYPE_AUTO )
1575                             frames[j]->i_type = X264_TYPE_B;
1576                     }
1577                 }
1578             }
1579         }
1580         else if( h->param.i_bframe_adaptive == X264_B_ADAPT_FAST )
1581         {
1582             int last_nonb = 0;
1583             int num_bframes = h->param.i_bframe;
1584             char path[X264_LOOKAHEAD_MAX+1];
1585             for( int j = 1; j < num_frames; j++ )
1586             {
1587                 if( j-1 > 0 && IS_X264_TYPE_B( frames[j-1]->i_type ) )
1588                     num_bframes--;
1589                 else
1590                 {
1591                     last_nonb = j-1;
1592                     num_bframes = h->param.i_bframe;
1593                 }
1594                 if( !num_bframes )
1595                 {
1596                     if( IS_X264_TYPE_AUTO_OR_B( frames[j]->i_type ) )
1597                         frames[j]->i_type = X264_TYPE_P;
1598                     continue;
1599                 }
1600 
1601                 if( frames[j]->i_type != X264_TYPE_AUTO )
1602                     continue;
1603 
1604                 if( IS_X264_TYPE_B( frames[j+1]->i_type ) )
1605                 {
1606                     frames[j]->i_type = X264_TYPE_P;
1607                     continue;
1608                 }
1609 
1610                 int bframes = j - last_nonb - 1;
1611                 memset( path, 'B', bframes );
1612                 strcpy( path+bframes, "PP" );
1613                 uint64_t cost_p = slicetype_path_cost( h, &a, frames+last_nonb, path, COST_MAX64 );
1614                 strcpy( path+bframes, "BP" );
1615                 uint64_t cost_b = slicetype_path_cost( h, &a, frames+last_nonb, path, cost_p );
1616 
1617                 if( cost_b < cost_p )
1618                     frames[j]->i_type = X264_TYPE_B;
1619                 else
1620                     frames[j]->i_type = X264_TYPE_P;
1621             }
1622         }
1623         else
1624         {
1625             int num_bframes = h->param.i_bframe;
1626             for( int j = 1; j < num_frames; j++ )
1627             {
1628                 if( !num_bframes )
1629                 {
1630                     if( IS_X264_TYPE_AUTO_OR_B( frames[j]->i_type ) )
1631                         frames[j]->i_type = X264_TYPE_P;
1632                 }
1633                 else if( frames[j]->i_type == X264_TYPE_AUTO )
1634                 {
1635                     if( IS_X264_TYPE_B( frames[j+1]->i_type ) )
1636                         frames[j]->i_type = X264_TYPE_P;
1637                     else
1638                         frames[j]->i_type = X264_TYPE_B;
1639                 }
1640                 if( IS_X264_TYPE_B( frames[j]->i_type ) )
1641                     num_bframes--;
1642                 else
1643                     num_bframes = h->param.i_bframe;
1644             }
1645         }
1646         if( IS_X264_TYPE_AUTO_OR_B( frames[num_frames]->i_type ) )
1647             frames[num_frames]->i_type = X264_TYPE_P;
1648 
1649         int num_bframes = 0;
1650         while( num_bframes < num_frames && IS_X264_TYPE_B( frames[num_bframes+1]->i_type ) )
1651             num_bframes++;
1652 
1653         /* Check scenecut on the first minigop. */
1654         for( int j = 1; j < num_bframes+1; j++ )
1655         {
1656             if( frames[j]->i_forced_type == X264_TYPE_AUTO && IS_X264_TYPE_AUTO_OR_I( frames[j+1]->i_forced_type ) &&
1657                 h->param.i_scenecut_threshold && scenecut( h, &a, frames, j, j+1, 0, orig_num_frames, i_max_search ) )
1658             {
1659                 frames[j]->i_type = X264_TYPE_P;
1660                 num_analysed_frames = j;
1661                 break;
1662             }
1663         }
1664 
1665         reset_start = keyframe ? 1 : X264_MIN( num_bframes+2, num_analysed_frames+1 );
1666     }
1667     else
1668     {
1669         for( int j = 1; j <= num_frames; j++ )
1670             if( IS_X264_TYPE_AUTO_OR_B( frames[j]->i_type ) )
1671                 frames[j]->i_type = X264_TYPE_P;
1672         reset_start = !keyframe + 1;
1673     }
1674 
1675     /* Perform the actual macroblock tree analysis.
1676      * Don't go farther than the maximum keyframe interval; this helps in short GOPs. */
1677     if( h->param.rc.b_mb_tree )
1678         macroblock_tree( h, &a, frames, X264_MIN(num_frames, h->param.i_keyint_max), keyframe );
1679 
1680     /* Enforce keyframe limit. */
1681     if( !h->param.b_intra_refresh )
1682     {
1683         int last_keyframe = h->lookahead->i_last_keyframe;
1684         int last_possible = 0;
1685         for( int j = 1; j <= num_frames; j++ )
1686         {
1687             x264_frame_t *frm = frames[j];
1688             int keyframe_dist = frm->i_frame - last_keyframe;
1689 
1690             if( IS_X264_TYPE_AUTO_OR_I( frm->i_forced_type ) )
1691             {
1692                 if( h->param.b_open_gop || !IS_X264_TYPE_B( frames[j-1]->i_forced_type ) )
1693                     last_possible = j;
1694             }
1695             if( keyframe_dist >= h->param.i_keyint_max )
1696             {
1697                 if( last_possible != 0 && last_possible != j )
1698                 {
1699                     j = last_possible;
1700                     frm = frames[j];
1701                     keyframe_dist = frm->i_frame - last_keyframe;
1702                 }
1703                 last_possible = 0;
1704                 if( frm->i_type != X264_TYPE_IDR )
1705                     frm->i_type = h->param.b_open_gop ? X264_TYPE_I : X264_TYPE_IDR;
1706             }
1707             if( frm->i_type == X264_TYPE_I && keyframe_dist >= h->param.i_keyint_min )
1708             {
1709                 if( h->param.b_open_gop )
1710                 {
1711                     last_keyframe = frm->i_frame;
1712                     if( h->param.b_bluray_compat )
1713                     {
1714                         // Use bluray order
1715                         int bframes = 0;
1716                         while( bframes < j-1 && IS_X264_TYPE_B( frames[j-1-bframes]->i_type ) )
1717                             bframes++;
1718                         last_keyframe -= bframes;
1719                     }
1720                 }
1721                 else if( frm->i_forced_type != X264_TYPE_I )
1722                     frm->i_type = X264_TYPE_IDR;
1723             }
1724             if( frm->i_type == X264_TYPE_IDR )
1725             {
1726                 last_keyframe = frm->i_frame;
1727                 if( j > 1 && IS_X264_TYPE_B( frames[j-1]->i_type ) )
1728                     frames[j-1]->i_type = X264_TYPE_P;
1729             }
1730         }
1731     }
1732 
1733     if( b_vbv_lookahead )
1734         vbv_lookahead( h, &a, frames, num_frames, keyframe );
1735 
1736     /* Restore frametypes for all frames that haven't actually been decided yet. */
1737     for( int j = reset_start; j <= num_frames; j++ )
1738         frames[j]->i_type = frames[j]->i_forced_type;
1739 
1740 #if HAVE_OPENCL
1741     x264_opencl_slicetype_end( h );
1742 #endif
1743 }
1744 
x264_slicetype_decide(x264_t * h)1745 void x264_slicetype_decide( x264_t *h )
1746 {
1747     x264_frame_t *frames[X264_BFRAME_MAX+2];
1748     x264_frame_t *frm;
1749     int bframes;
1750     int brefs;
1751 
1752     if( !h->lookahead->next.i_size )
1753         return;
1754 
1755     int lookahead_size = h->lookahead->next.i_size;
1756 
1757     for( int i = 0; i < h->lookahead->next.i_size; i++ )
1758     {
1759         if( h->param.b_vfr_input )
1760         {
1761             if( lookahead_size-- > 1 )
1762                 h->lookahead->next.list[i]->i_duration = 2 * (h->lookahead->next.list[i+1]->i_pts - h->lookahead->next.list[i]->i_pts);
1763             else
1764                 h->lookahead->next.list[i]->i_duration = h->i_prev_duration;
1765         }
1766         else
1767             h->lookahead->next.list[i]->i_duration = delta_tfi_divisor[h->lookahead->next.list[i]->i_pic_struct];
1768         h->i_prev_duration = h->lookahead->next.list[i]->i_duration;
1769         h->lookahead->next.list[i]->f_duration = (double)h->lookahead->next.list[i]->i_duration
1770                                                * h->sps->vui.i_num_units_in_tick
1771                                                / h->sps->vui.i_time_scale;
1772 
1773         if( h->lookahead->next.list[i]->i_frame > h->i_disp_fields_last_frame && lookahead_size > 0 )
1774         {
1775             h->lookahead->next.list[i]->i_field_cnt = h->i_disp_fields;
1776             h->i_disp_fields += h->lookahead->next.list[i]->i_duration;
1777             h->i_disp_fields_last_frame = h->lookahead->next.list[i]->i_frame;
1778         }
1779         else if( lookahead_size == 0 )
1780         {
1781             h->lookahead->next.list[i]->i_field_cnt = h->i_disp_fields;
1782             h->lookahead->next.list[i]->i_duration = h->i_prev_duration;
1783         }
1784     }
1785 
1786     if( h->param.rc.b_stat_read )
1787     {
1788         /* Use the frame types from the first pass */
1789         for( int i = 0; i < h->lookahead->next.i_size; i++ )
1790             h->lookahead->next.list[i]->i_type =
1791                 x264_ratecontrol_slice_type( h, h->lookahead->next.list[i]->i_frame );
1792     }
1793     else if( (h->param.i_bframe && h->param.i_bframe_adaptive)
1794              || h->param.i_scenecut_threshold
1795              || h->param.rc.b_mb_tree
1796              || (h->param.rc.i_vbv_buffer_size && h->param.rc.i_lookahead) )
1797         x264_slicetype_analyse( h, 0 );
1798 
1799     for( bframes = 0, brefs = 0;; bframes++ )
1800     {
1801         frm = h->lookahead->next.list[bframes];
1802 
1803         if( frm->i_forced_type != X264_TYPE_AUTO && frm->i_type != frm->i_forced_type &&
1804             !(frm->i_forced_type == X264_TYPE_KEYFRAME && IS_X264_TYPE_I( frm->i_type )) )
1805         {
1806             x264_log( h, X264_LOG_WARNING, "forced frame type (%d) at %d was changed to frame type (%d)\n",
1807                       frm->i_forced_type, frm->i_frame, frm->i_type );
1808         }
1809 
1810         if( frm->i_type == X264_TYPE_BREF && h->param.i_bframe_pyramid < X264_B_PYRAMID_NORMAL &&
1811             brefs == h->param.i_bframe_pyramid )
1812         {
1813             frm->i_type = X264_TYPE_B;
1814             x264_log( h, X264_LOG_WARNING, "B-ref at frame %d incompatible with B-pyramid %s \n",
1815                       frm->i_frame, x264_b_pyramid_names[h->param.i_bframe_pyramid] );
1816         }
1817         /* pyramid with multiple B-refs needs a big enough dpb that the preceding P-frame stays available.
1818            smaller dpb could be supported by smart enough use of mmco, but it's easier just to forbid it. */
1819         else if( frm->i_type == X264_TYPE_BREF && h->param.i_bframe_pyramid == X264_B_PYRAMID_NORMAL &&
1820             brefs && h->param.i_frame_reference <= (brefs+3) )
1821         {
1822             frm->i_type = X264_TYPE_B;
1823             x264_log( h, X264_LOG_WARNING, "B-ref at frame %d incompatible with B-pyramid %s and %d reference frames\n",
1824                       frm->i_frame, x264_b_pyramid_names[h->param.i_bframe_pyramid], h->param.i_frame_reference );
1825         }
1826 
1827         if( frm->i_type == X264_TYPE_KEYFRAME )
1828             frm->i_type = h->param.b_open_gop ? X264_TYPE_I : X264_TYPE_IDR;
1829 
1830         /* Limit GOP size */
1831         if( (!h->param.b_intra_refresh || frm->i_frame == 0) && frm->i_frame - h->lookahead->i_last_keyframe >= h->param.i_keyint_max )
1832         {
1833             if( frm->i_type == X264_TYPE_AUTO || frm->i_type == X264_TYPE_I )
1834                 frm->i_type = h->param.b_open_gop && h->lookahead->i_last_keyframe >= 0 ? X264_TYPE_I : X264_TYPE_IDR;
1835             int warn = frm->i_type != X264_TYPE_IDR;
1836             if( warn && h->param.b_open_gop )
1837                 warn &= frm->i_type != X264_TYPE_I;
1838             if( warn )
1839             {
1840                 x264_log( h, X264_LOG_WARNING, "specified frame type (%d) at %d is not compatible with keyframe interval\n", frm->i_type, frm->i_frame );
1841                 frm->i_type = h->param.b_open_gop && h->lookahead->i_last_keyframe >= 0 ? X264_TYPE_I : X264_TYPE_IDR;
1842             }
1843         }
1844         if( frm->i_type == X264_TYPE_I && frm->i_frame - h->lookahead->i_last_keyframe >= h->param.i_keyint_min )
1845         {
1846             if( h->param.b_open_gop )
1847             {
1848                 h->lookahead->i_last_keyframe = frm->i_frame; // Use display order
1849                 if( h->param.b_bluray_compat )
1850                     h->lookahead->i_last_keyframe -= bframes; // Use bluray order
1851                 frm->b_keyframe = 1;
1852             }
1853             else
1854                 frm->i_type = X264_TYPE_IDR;
1855         }
1856         if( frm->i_type == X264_TYPE_IDR )
1857         {
1858             /* Close GOP */
1859             h->lookahead->i_last_keyframe = frm->i_frame;
1860             frm->b_keyframe = 1;
1861             if( bframes > 0 )
1862             {
1863                 bframes--;
1864                 h->lookahead->next.list[bframes]->i_type = X264_TYPE_P;
1865             }
1866         }
1867 
1868         if( bframes == h->param.i_bframe ||
1869             !h->lookahead->next.list[bframes+1] )
1870         {
1871             if( IS_X264_TYPE_B( frm->i_type ) )
1872                 x264_log( h, X264_LOG_WARNING, "specified frame type is not compatible with max B-frames\n" );
1873             if( frm->i_type == X264_TYPE_AUTO
1874                 || IS_X264_TYPE_B( frm->i_type ) )
1875                 frm->i_type = X264_TYPE_P;
1876         }
1877 
1878         if( frm->i_type == X264_TYPE_BREF )
1879             brefs++;
1880 
1881         if( frm->i_type == X264_TYPE_AUTO )
1882             frm->i_type = X264_TYPE_B;
1883 
1884         else if( !IS_X264_TYPE_B( frm->i_type ) ) break;
1885     }
1886 
1887     if( bframes )
1888         h->lookahead->next.list[bframes-1]->b_last_minigop_bframe = 1;
1889     h->lookahead->next.list[bframes]->i_bframes = bframes;
1890 
1891     /* insert a bref into the sequence */
1892     if( h->param.i_bframe_pyramid && bframes > 1 && !brefs )
1893     {
1894         h->lookahead->next.list[(bframes-1)/2]->i_type = X264_TYPE_BREF;
1895         brefs++;
1896     }
1897 
1898     /* calculate the frame costs ahead of time for x264_rc_analyse_slice while we still have lowres */
1899     if( h->param.rc.i_rc_method != X264_RC_CQP )
1900     {
1901         x264_mb_analysis_t a;
1902         int p0, p1, b;
1903         p1 = b = bframes + 1;
1904 
1905         lowres_context_init( h, &a );
1906 
1907         frames[0] = h->lookahead->last_nonb;
1908         memcpy( &frames[1], h->lookahead->next.list, (bframes+1) * sizeof(x264_frame_t*) );
1909         if( IS_X264_TYPE_I( h->lookahead->next.list[bframes]->i_type ) )
1910             p0 = bframes + 1;
1911         else // P
1912             p0 = 0;
1913 
1914         slicetype_frame_cost( h, &a, frames, p0, p1, b );
1915 
1916         if( (p0 != p1 || bframes) && h->param.rc.i_vbv_buffer_size )
1917         {
1918             /* We need the intra costs for row SATDs. */
1919             slicetype_frame_cost( h, &a, frames, b, b, b );
1920 
1921             /* We need B-frame costs for row SATDs. */
1922             p0 = 0;
1923             for( b = 1; b <= bframes; b++ )
1924             {
1925                 if( frames[b]->i_type == X264_TYPE_B )
1926                     for( p1 = b; frames[p1]->i_type == X264_TYPE_B; )
1927                         p1++;
1928                 else
1929                     p1 = bframes + 1;
1930                 slicetype_frame_cost( h, &a, frames, p0, p1, b );
1931                 if( frames[b]->i_type == X264_TYPE_BREF )
1932                     p0 = b;
1933             }
1934         }
1935     }
1936 
1937     /* Analyse for weighted P frames */
1938     if( !h->param.rc.b_stat_read && h->lookahead->next.list[bframes]->i_type == X264_TYPE_P
1939         && h->param.analyse.i_weighted_pred >= X264_WEIGHTP_SIMPLE )
1940     {
1941         x264_emms();
1942         x264_weights_analyse( h, h->lookahead->next.list[bframes], h->lookahead->last_nonb, 0 );
1943     }
1944 
1945     /* shift sequence to coded order.
1946        use a small temporary list to avoid shifting the entire next buffer around */
1947     int i_coded = h->lookahead->next.list[0]->i_frame;
1948     if( bframes )
1949     {
1950         int idx_list[] = { brefs+1, 1 };
1951         for( int i = 0; i < bframes; i++ )
1952         {
1953             int idx = idx_list[h->lookahead->next.list[i]->i_type == X264_TYPE_BREF]++;
1954             frames[idx] = h->lookahead->next.list[i];
1955             frames[idx]->i_reordered_pts = h->lookahead->next.list[idx]->i_pts;
1956         }
1957         frames[0] = h->lookahead->next.list[bframes];
1958         frames[0]->i_reordered_pts = h->lookahead->next.list[0]->i_pts;
1959         memcpy( h->lookahead->next.list, frames, (bframes+1) * sizeof(x264_frame_t*) );
1960     }
1961 
1962     for( int i = 0; i <= bframes; i++ )
1963     {
1964         h->lookahead->next.list[i]->i_coded = i_coded++;
1965         if( i )
1966         {
1967             calculate_durations( h, h->lookahead->next.list[i], h->lookahead->next.list[i-1], &h->i_cpb_delay, &h->i_coded_fields );
1968             h->lookahead->next.list[0]->f_planned_cpb_duration[i-1] = (double)h->lookahead->next.list[i]->i_cpb_duration *
1969                                                                       h->sps->vui.i_num_units_in_tick / h->sps->vui.i_time_scale;
1970         }
1971         else
1972             calculate_durations( h, h->lookahead->next.list[i], NULL, &h->i_cpb_delay, &h->i_coded_fields );
1973     }
1974 }
1975 
x264_rc_analyse_slice(x264_t * h)1976 int x264_rc_analyse_slice( x264_t *h )
1977 {
1978     int p0 = 0, p1, b;
1979     int cost;
1980     x264_emms();
1981 
1982     if( IS_X264_TYPE_I(h->fenc->i_type) )
1983         p1 = b = 0;
1984     else if( h->fenc->i_type == X264_TYPE_P )
1985         p1 = b = h->fenc->i_bframes + 1;
1986     else //B
1987     {
1988         p1 = (h->fref_nearest[1]->i_poc - h->fref_nearest[0]->i_poc)/2;
1989         b  = (h->fenc->i_poc - h->fref_nearest[0]->i_poc)/2;
1990     }
1991     /* We don't need to assign p0/p1 since we are not performing any real analysis here. */
1992     x264_frame_t **frames = &h->fenc - b;
1993 
1994     /* cost should have been already calculated by x264_slicetype_decide */
1995     cost = frames[b]->i_cost_est[b-p0][p1-b];
1996     assert( cost >= 0 );
1997 
1998     if( h->param.rc.b_mb_tree && !h->param.rc.b_stat_read )
1999     {
2000         cost = slicetype_frame_cost_recalculate( h, frames, p0, p1, b );
2001         if( b && h->param.rc.i_vbv_buffer_size )
2002             slicetype_frame_cost_recalculate( h, frames, b, b, b );
2003     }
2004     /* In AQ, use the weighted score instead. */
2005     else if( h->param.rc.i_aq_mode )
2006         cost = frames[b]->i_cost_est_aq[b-p0][p1-b];
2007 
2008     h->fenc->i_row_satd = h->fenc->i_row_satds[b-p0][p1-b];
2009     h->fdec->i_row_satd = h->fdec->i_row_satds[b-p0][p1-b];
2010     h->fdec->i_satd = cost;
2011     memcpy( h->fdec->i_row_satd, h->fenc->i_row_satd, h->mb.i_mb_height * sizeof(int) );
2012     if( !IS_X264_TYPE_I(h->fenc->i_type) )
2013         memcpy( h->fdec->i_row_satds[0][0], h->fenc->i_row_satds[0][0], h->mb.i_mb_height * sizeof(int) );
2014 
2015     if( h->param.b_intra_refresh && h->param.rc.i_vbv_buffer_size && h->fenc->i_type == X264_TYPE_P )
2016     {
2017         int ip_factor = 256 * h->param.rc.f_ip_factor; /* fix8 */
2018         for( int y = 0; y < h->mb.i_mb_height; y++ )
2019         {
2020             int mb_xy = y * h->mb.i_mb_stride + h->fdec->i_pir_start_col;
2021             for( int x = h->fdec->i_pir_start_col; x <= h->fdec->i_pir_end_col; x++, mb_xy++ )
2022             {
2023                 int intra_cost = (h->fenc->i_intra_cost[mb_xy] * ip_factor + 128) >> 8;
2024                 int inter_cost = h->fenc->lowres_costs[b-p0][p1-b][mb_xy] & LOWRES_COST_MASK;
2025                 int diff = intra_cost - inter_cost;
2026                 if( h->param.rc.i_aq_mode )
2027                     h->fdec->i_row_satd[y] += (diff * frames[b]->i_inv_qscale_factor[mb_xy] + 128) >> 8;
2028                 else
2029                     h->fdec->i_row_satd[y] += diff;
2030                 cost += diff;
2031             }
2032         }
2033     }
2034 
2035     return cost;
2036 }
2037