encoder.c 143 KB
Newer Older
Laurent Aimar's avatar
Laurent Aimar committed
1
/*****************************************************************************
Fiona Glaser's avatar
Fiona Glaser committed
2
 * encoder.c: top-level encoder functions
Laurent Aimar's avatar
Laurent Aimar committed
3
 *****************************************************************************
Sean McGovern's avatar
Sean McGovern committed
4
 * Copyright (C) 2003-2011 x264 project
Laurent Aimar's avatar
Laurent Aimar committed
5
6
 *
 * Authors: Laurent Aimar <fenrir@via.ecp.fr>
7
 *          Loren Merritt <lorenm@u.washington.edu>
8
 *          Fiona Glaser <fiona@x264.com>
Laurent Aimar's avatar
Laurent Aimar committed
9
10
11
12
13
14
15
16
17
18
19
20
21
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
22
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02111, USA.
Fiona Glaser's avatar
Fiona Glaser committed
23
24
25
 *
 * This program is also available under a commercial proprietary license.
 * For more information, contact us at licensing@x264.com.
Laurent Aimar's avatar
Laurent Aimar committed
26
27
 *****************************************************************************/

28
#include "common/common.h"
Laurent Aimar's avatar
Laurent Aimar committed
29
30
31
32
33

#include "set.h"
#include "analyse.h"
#include "ratecontrol.h"
#include "macroblock.h"
34
#include "me.h"
Laurent Aimar's avatar
Laurent Aimar committed
35

Steven Walters's avatar
Steven Walters committed
36
#if HAVE_VISUALIZE
Loren Merritt's avatar
Loren Merritt committed
37
38
39
#include "common/visualize.h"
#endif

Laurent Aimar's avatar
Laurent Aimar committed
40
41
//#define DEBUG_MB_TYPE

Fiona Glaser's avatar
Fiona Glaser committed
42
43
#define bs_write_ue bs_write_ue_big

Fiona Glaser's avatar
Fiona Glaser committed
44
static int x264_encoder_frame_end( x264_t *h, x264_t *thread_current,
45
46
                                   x264_nal_t **pp_nal, int *pi_nal,
                                   x264_picture_t *pic_out );
Loren Merritt's avatar
Loren Merritt committed
47

Laurent Aimar's avatar
Laurent Aimar committed
48
49
50
51
52
/****************************************************************************
 *
 ******************************* x264 libs **********************************
 *
 ****************************************************************************/
Fiona Glaser's avatar
Fiona Glaser committed
53
static double x264_psnr( double sqe, double size )
54
{
Fiona Glaser's avatar
Fiona Glaser committed
55
56
    double mse = sqe / (PIXEL_MAX*PIXEL_MAX * size);
    if( mse <= 0.0000000001 ) /* Max 100dB */
57
58
        return 100;

Fiona Glaser's avatar
Fiona Glaser committed
59
    return -10.0 * log10( mse );
60
61
}

Fiona Glaser's avatar
Fiona Glaser committed
62
static double x264_ssim( double ssim )
63
64
65
66
{
    return -10.0 * log10( 1 - ssim );
}

67
static void x264_frame_dump( x264_t *h )
Laurent Aimar's avatar
Laurent Aimar committed
68
{
69
    FILE *f = fopen( h->param.psz_dump_yuv, "r+b" );
70
71
    if( !f )
        return;
Fiona Glaser's avatar
Fiona Glaser committed
72

73
    /* Write the frame in display order */
Henrik Gramner's avatar
Henrik Gramner committed
74
    int frame_size = FRAME_SIZE( h->param.i_height * h->param.i_width * sizeof(pixel) );
Fiona Glaser's avatar
Fiona Glaser committed
75
76
77
78
79
80
81
    fseek( f, (uint64_t)h->fdec->i_frame * frame_size, SEEK_SET );
    for( int p = 0; p < (CHROMA444 ? 3 : 1); p++ )
        for( int y = 0; y < h->param.i_height; y++ )
            fwrite( &h->fdec->plane[p][y*h->fdec->i_stride[p]], sizeof(pixel), h->param.i_width, f );
    if( !CHROMA444 )
    {
        int cw = h->param.i_width>>1;
82
        int ch = h->param.i_height>>CHROMA_V_SHIFT;
Fiona Glaser's avatar
Fiona Glaser committed
83
84
85
86
87
88
89
        pixel *planeu = x264_malloc( (cw*ch*2+32)*sizeof(pixel) );
        pixel *planev = planeu + cw*ch + 16;
        h->mc.plane_copy_deinterleave( planeu, cw, planev, cw, h->fdec->plane[1], h->fdec->i_stride[1], cw, ch );
        fwrite( planeu, 1, cw*ch*sizeof(pixel), f );
        fwrite( planev, 1, cw*ch*sizeof(pixel), f );
        x264_free( planeu );
    }
Laurent Aimar's avatar
Laurent Aimar committed
90
91
92
93
    fclose( f );
}

/* Fill "default" values */
94
static void x264_slice_header_init( x264_t *h, x264_slice_header_t *sh,
Laurent Aimar's avatar
Laurent Aimar committed
95
                                    x264_sps_t *sps, x264_pps_t *pps,
Loren Merritt's avatar
Loren Merritt committed
96
                                    int i_idr_pic_id, int i_frame, int i_qp )
Laurent Aimar's avatar
Laurent Aimar committed
97
{
98
99
    x264_param_t *param = &h->param;

100
    /* First we fill all fields */
Laurent Aimar's avatar
Laurent Aimar committed
101
102
103
104
    sh->sps = sps;
    sh->pps = pps;

    sh->i_first_mb  = 0;
Fiona Glaser's avatar
Fiona Glaser committed
105
    sh->i_last_mb   = h->mb.i_mb_count - 1;
Laurent Aimar's avatar
Laurent Aimar committed
106
107
108
109
    sh->i_pps_id    = pps->i_id;

    sh->i_frame_num = i_frame;

110
    sh->b_mbaff = PARAM_INTERLACED;
111
112
    sh->b_field_pic = 0;    /* no field support for now */
    sh->b_bottom_field = 0; /* not yet used */
Laurent Aimar's avatar
Laurent Aimar committed
113
114
115
116

    sh->i_idr_pic_id = i_idr_pic_id;

    /* poc stuff, fixed later */
117
    sh->i_poc = 0;
Laurent Aimar's avatar
Laurent Aimar committed
118
119
120
121
122
123
    sh->i_delta_poc_bottom = 0;
    sh->i_delta_poc[0] = 0;
    sh->i_delta_poc[1] = 0;

    sh->i_redundant_pic_cnt = 0;

124
125
126
127
128
    h->mb.b_direct_auto_write = h->param.analyse.i_direct_mv_pred == X264_DIRECT_PRED_AUTO
                                && h->param.i_bframe
                                && ( h->param.rc.b_stat_write || !h->param.rc.b_stat_read );

    if( !h->mb.b_direct_auto_read && sh->i_type == SLICE_TYPE_B )
Loren Merritt's avatar
Loren Merritt committed
129
    {
130
        if( h->fref[1][0]->i_poc_l0ref0 == h->fref[0][0]->i_poc )
131
132
133
134
135
136
        {
            if( h->mb.b_direct_auto_write )
                sh->b_direct_spatial_mv_pred = ( h->stat.i_direct_score[1] > h->stat.i_direct_score[0] );
            else
                sh->b_direct_spatial_mv_pred = ( param->analyse.i_direct_mv_pred == X264_DIRECT_PRED_SPATIAL );
        }
Loren Merritt's avatar
Loren Merritt committed
137
        else
138
139
140
141
        {
            h->mb.b_direct_auto_write = 0;
            sh->b_direct_spatial_mv_pred = 1;
        }
Loren Merritt's avatar
Loren Merritt committed
142
143
    }
    /* else b_direct_spatial_mv_pred was read from the 2pass statsfile */
Laurent Aimar's avatar
Laurent Aimar committed
144
145
146
147
148

    sh->b_num_ref_idx_override = 0;
    sh->i_num_ref_idx_l0_active = 1;
    sh->i_num_ref_idx_l1_active = 1;

149
150
    sh->b_ref_pic_list_reordering[0] = h->b_ref_reorder[0];
    sh->b_ref_pic_list_reordering[1] = h->b_ref_reorder[1];
151
152

    /* If the ref list isn't in the default order, construct reordering header */
153
    for( int list = 0; list < 2; list++ )
154
    {
155
        if( sh->b_ref_pic_list_reordering[list] )
156
        {
157
158
159
160
161
162
163
164
            int pred_frame_num = i_frame;
            for( int i = 0; i < h->i_ref[list]; i++ )
            {
                int diff = h->fref[list][i]->i_frame_num - pred_frame_num;
                sh->ref_pic_list_order[list][i].idc = ( diff > 0 );
                sh->ref_pic_list_order[list][i].arg = (abs(diff) - 1) & ((1 << sps->i_log2_max_frame_num) - 1);
                pred_frame_num = h->fref[list][i]->i_frame_num;
            }
165
166
167
        }
    }

Laurent Aimar's avatar
Laurent Aimar committed
168
169
    sh->i_cabac_init_idc = param->i_cabac_init_idc;

Fiona Glaser's avatar
Fiona Glaser committed
170
171
    sh->i_qp = SPEC_QP(i_qp);
    sh->i_qp_delta = sh->i_qp - pps->i_pic_init_qp;
Laurent Aimar's avatar
Laurent Aimar committed
172
173
174
    sh->b_sp_for_swidth = 0;
    sh->i_qs_delta = 0;

175
    int deblock_thresh = i_qp + 2 * X264_MIN(param->i_deblocking_filter_alphac0, param->i_deblocking_filter_beta);
176
    /* If effective qp <= 15, deblocking would have no effect anyway */
177
    if( param->b_deblocking_filter && (h->mb.b_variable_qp || 15 < deblock_thresh ) )
178
        sh->i_disable_deblocking_filter_idc = param->b_sliced_threads ? 2 : 0;
Laurent Aimar's avatar
Laurent Aimar committed
179
180
181
182
183
184
185
186
    else
        sh->i_disable_deblocking_filter_idc = 1;
    sh->i_alpha_c0_offset = param->i_deblocking_filter_alphac0 << 1;
    sh->i_beta_offset = param->i_deblocking_filter_beta << 1;
}

static void x264_slice_header_write( bs_t *s, x264_slice_header_t *sh, int i_nal_ref_idc )
{
187
188
    if( sh->b_mbaff )
    {
189
190
191
192
        int first_x = sh->i_first_mb % sh->sps->i_mb_width;
        int first_y = sh->i_first_mb / sh->sps->i_mb_width;
        assert( (first_y&1) == 0 );
        bs_write_ue( s, (2*first_x + sh->sps->i_mb_width*(first_y&~1) + (first_y&1)) >> 1 );
193
194
195
196
    }
    else
        bs_write_ue( s, sh->i_first_mb );

Laurent Aimar's avatar
Laurent Aimar committed
197
198
    bs_write_ue( s, sh->i_type + 5 );   /* same type things */
    bs_write_ue( s, sh->i_pps_id );
Fiona Glaser's avatar
Fiona Glaser committed
199
    bs_write( s, sh->sps->i_log2_max_frame_num, sh->i_frame_num & ((1<<sh->sps->i_log2_max_frame_num)-1) );
Laurent Aimar's avatar
Laurent Aimar committed
200

201
202
203
    if( !sh->sps->b_frame_mbs_only )
    {
        bs_write1( s, sh->b_field_pic );
Fiona Glaser's avatar
Fiona Glaser committed
204
        if( sh->b_field_pic )
205
206
207
            bs_write1( s, sh->b_bottom_field );
    }

Laurent Aimar's avatar
Laurent Aimar committed
208
209
210
211
212
    if( sh->i_idr_pic_id >= 0 ) /* NAL IDR */
        bs_write_ue( s, sh->i_idr_pic_id );

    if( sh->sps->i_poc_type == 0 )
    {
213
        bs_write( s, sh->sps->i_log2_max_poc_lsb, sh->i_poc & ((1<<sh->sps->i_log2_max_poc_lsb)-1) );
Laurent Aimar's avatar
Laurent Aimar committed
214
215
216
217
218
219
220
221
222
        if( sh->pps->b_pic_order && !sh->b_field_pic )
            bs_write_se( s, sh->i_delta_poc_bottom );
    }

    if( sh->pps->b_redundant_pic_cnt )
        bs_write_ue( s, sh->i_redundant_pic_cnt );

    if( sh->i_type == SLICE_TYPE_B )
        bs_write1( s, sh->b_direct_spatial_mv_pred );
223

224
    if( sh->i_type == SLICE_TYPE_P || sh->i_type == SLICE_TYPE_B )
Laurent Aimar's avatar
Laurent Aimar committed
225
226
227
228
229
230
231
232
233
234
235
236
237
    {
        bs_write1( s, sh->b_num_ref_idx_override );
        if( sh->b_num_ref_idx_override )
        {
            bs_write_ue( s, sh->i_num_ref_idx_l0_active - 1 );
            if( sh->i_type == SLICE_TYPE_B )
                bs_write_ue( s, sh->i_num_ref_idx_l1_active - 1 );
        }
    }

    /* ref pic list reordering */
    if( sh->i_type != SLICE_TYPE_I )
    {
238
239
        bs_write1( s, sh->b_ref_pic_list_reordering[0] );
        if( sh->b_ref_pic_list_reordering[0] )
Laurent Aimar's avatar
Laurent Aimar committed
240
        {
241
            for( int i = 0; i < sh->i_num_ref_idx_l0_active; i++ )
242
243
244
245
246
            {
                bs_write_ue( s, sh->ref_pic_list_order[0][i].idc );
                bs_write_ue( s, sh->ref_pic_list_order[0][i].arg );
            }
            bs_write_ue( s, 3 );
Laurent Aimar's avatar
Laurent Aimar committed
247
248
249
250
        }
    }
    if( sh->i_type == SLICE_TYPE_B )
    {
251
252
        bs_write1( s, sh->b_ref_pic_list_reordering[1] );
        if( sh->b_ref_pic_list_reordering[1] )
Laurent Aimar's avatar
Laurent Aimar committed
253
        {
254
            for( int i = 0; i < sh->i_num_ref_idx_l1_active; i++ )
255
256
257
258
259
            {
                bs_write_ue( s, sh->ref_pic_list_order[1][i].idc );
                bs_write_ue( s, sh->ref_pic_list_order[1][i].arg );
            }
            bs_write_ue( s, 3 );
Laurent Aimar's avatar
Laurent Aimar committed
260
261
262
        }
    }

263
    if( sh->pps->b_weighted_pred && sh->i_type == SLICE_TYPE_P )
Laurent Aimar's avatar
Laurent Aimar committed
264
    {
Dylan Yudaken's avatar
Dylan Yudaken committed
265
266
267
        /* pred_weight_table() */
        bs_write_ue( s, sh->weight[0][0].i_denom );
        bs_write_ue( s, sh->weight[0][1].i_denom );
268
        for( int i = 0; i < sh->i_num_ref_idx_l0_active; i++ )
Dylan Yudaken's avatar
Dylan Yudaken committed
269
270
271
272
273
274
275
276
277
278
279
280
        {
            int luma_weight_l0_flag = !!sh->weight[i][0].weightfn;
            int chroma_weight_l0_flag = !!sh->weight[i][1].weightfn || !!sh->weight[i][2].weightfn;
            bs_write1( s, luma_weight_l0_flag );
            if( luma_weight_l0_flag )
            {
                bs_write_se( s, sh->weight[i][0].i_scale );
                bs_write_se( s, sh->weight[i][0].i_offset );
            }
            bs_write1( s, chroma_weight_l0_flag );
            if( chroma_weight_l0_flag )
            {
281
                for( int j = 1; j < 3; j++ )
Dylan Yudaken's avatar
Dylan Yudaken committed
282
283
284
285
286
287
288
289
290
291
                {
                    bs_write_se( s, sh->weight[i][j].i_scale );
                    bs_write_se( s, sh->weight[i][j].i_offset );
                }
            }
        }
    }
    else if( sh->pps->b_weighted_bipred == 1 && sh->i_type == SLICE_TYPE_B )
    {
      /* TODO */
Laurent Aimar's avatar
Laurent Aimar committed
292
293
294
295
296
297
298
299
300
301
302
    }

    if( i_nal_ref_idc != 0 )
    {
        if( sh->i_idr_pic_id >= 0 )
        {
            bs_write1( s, 0 );  /* no output of prior pics flag */
            bs_write1( s, 0 );  /* long term reference flag */
        }
        else
        {
Lamont Alston's avatar
Lamont Alston committed
303
304
305
            bs_write1( s, sh->i_mmco_command_count > 0 ); /* adaptive_ref_pic_marking_mode_flag */
            if( sh->i_mmco_command_count > 0 )
            {
306
                for( int i = 0; i < sh->i_mmco_command_count; i++ )
Lamont Alston's avatar
Lamont Alston committed
307
308
309
310
311
312
                {
                    bs_write_ue( s, 1 ); /* mark short term ref as unused */
                    bs_write_ue( s, sh->mmco[i].i_difference_of_pic_nums - 1 );
                }
                bs_write_ue( s, 0 ); /* end command list */
            }
Laurent Aimar's avatar
Laurent Aimar committed
313
314
315
316
317
        }
    }

    if( sh->pps->b_cabac && sh->i_type != SLICE_TYPE_I )
        bs_write_ue( s, sh->i_cabac_init_idc );
318

Laurent Aimar's avatar
Laurent Aimar committed
319
320
321
322
323
324
325
326
327
328
329
330
331
    bs_write_se( s, sh->i_qp_delta );      /* slice qp delta */

    if( sh->pps->b_deblocking_filter_control )
    {
        bs_write_ue( s, sh->i_disable_deblocking_filter_idc );
        if( sh->i_disable_deblocking_filter_idc != 1 )
        {
            bs_write_se( s, sh->i_alpha_c0_offset >> 1 );
            bs_write_se( s, sh->i_beta_offset >> 1 );
        }
    }
}

332
333
/* If we are within a reasonable distance of the end of the memory allocated for the bitstream, */
/* reallocate, adding an arbitrary amount of space (100 kilobytes). */
334
static int x264_bitstream_check_buffer( x264_t *h )
335
{
336
    uint8_t *bs_bak = h->out.p_bitstream;
337
338
339
    int max_mb_size = 2500 << SLICE_MBAFF;
    if( (h->param.b_cabac && (h->cabac.p_end - h->cabac.p < max_mb_size)) ||
        (h->out.bs.p_end - h->out.bs.p < max_mb_size) )
340
341
    {
        h->out.i_bitstream += 100000;
342
343
        CHECKED_MALLOC( h->out.p_bitstream, h->out.i_bitstream );
        h->mc.memcpy_aligned( h->out.p_bitstream, bs_bak, (h->out.i_bitstream - 100000) & ~15 );
344
        intptr_t delta = h->out.p_bitstream - bs_bak;
345
346
347
348
349
350
351
352
353

        h->out.bs.p_start += delta;
        h->out.bs.p += delta;
        h->out.bs.p_end = h->out.p_bitstream + h->out.i_bitstream;

        h->cabac.p_start += delta;
        h->cabac.p += delta;
        h->cabac.p_end = h->out.p_bitstream + h->out.i_bitstream;

354
        for( int i = 0; i <= h->out.i_nal; i++ )
355
            h->out.nal[i].p_payload += delta;
356
        x264_free( bs_bak );
357
    }
358
359
360
361
    return 0;
fail:
    x264_free( bs_bak );
    return -1;
362
363
}

364
#if HAVE_THREAD
365
366
367
368
369
370
371
372
373
374
375
376
377
static void x264_encoder_thread_init( x264_t *h )
{
    if( h->param.i_sync_lookahead )
        x264_lower_thread_priority( 10 );

#if HAVE_MMX
    /* Misalign mask has to be set separately for each thread. */
    if( h->param.cpu&X264_CPU_SSE_MISALIGN )
        x264_cpu_mask_misalign_sse();
#endif
}
#endif

Laurent Aimar's avatar
Laurent Aimar committed
378
379
380
381
382
383
384
385
/****************************************************************************
 *
 ****************************************************************************
 ****************************** External API*********************************
 ****************************************************************************
 *
 ****************************************************************************/

386
static int x264_validate_parameters( x264_t *h, int b_open )
Laurent Aimar's avatar
Laurent Aimar committed
387
{
Steven Walters's avatar
Steven Walters committed
388
#if HAVE_MMX
389
#ifdef __SSE__
390
    if( b_open && !(x264_cpu_detect() & X264_CPU_SSE) )
391
    {
392
        x264_log( h, X264_LOG_ERROR, "your cpu does not support SSE1, but x264 was compiled with asm support\n");
393
#else
Loren Merritt's avatar
Loren Merritt committed
394
    if( b_open && !(x264_cpu_detect() & X264_CPU_MMX2) )
395
396
397
    {
        x264_log( h, X264_LOG_ERROR, "your cpu does not support MMXEXT, but x264 was compiled with asm support\n");
#endif
398
399
400
401
        x264_log( h, X264_LOG_ERROR, "to run x264, recompile without asm support (configure --disable-asm)\n");
        return -1;
    }
#endif
Henrik Gramner's avatar
Henrik Gramner committed
402
403
404
405
406
407
408
409
410
411
412

#if HAVE_INTERLACED
    h->param.b_interlaced = !!PARAM_INTERLACED;
#else
    if( h->param.b_interlaced )
    {
        x264_log( h, X264_LOG_ERROR, "not compiled with interlaced support\n" );
        return -1;
    }
#endif

413
    if( h->param.i_width <= 0 || h->param.i_height <= 0 )
Laurent Aimar's avatar
Laurent Aimar committed
414
    {
415
        x264_log( h, X264_LOG_ERROR, "invalid width x height (%dx%d)\n",
416
417
                  h->param.i_width, h->param.i_height );
        return -1;
Laurent Aimar's avatar
Laurent Aimar committed
418
419
    }

Fiona Glaser's avatar
Fiona Glaser committed
420
    int i_csp = h->param.i_csp & X264_CSP_MASK;
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
#if X264_CHROMA_FORMAT
    if( CHROMA_FORMAT != CHROMA_420 && i_csp >= X264_CSP_I420 && i_csp <= X264_CSP_NV12 )
    {
        x264_log( h, X264_LOG_ERROR, "not compiled with 4:2:0 support\n" );
        return -1;
    }
    else if( CHROMA_FORMAT != CHROMA_422 && i_csp >= X264_CSP_I422 && i_csp <= X264_CSP_NV16 )
    {
        x264_log( h, X264_LOG_ERROR, "not compiled with 4:2:2 support\n" );
        return -1;
    }
    else if( CHROMA_FORMAT != CHROMA_444 && i_csp >= X264_CSP_I444 && i_csp <= X264_CSP_RGB )
    {
        x264_log( h, X264_LOG_ERROR, "not compiled with 4:4:4 support\n" );
        return -1;
    }
#endif
Fiona Glaser's avatar
Fiona Glaser committed
438
    if( i_csp <= X264_CSP_NONE || i_csp >= X264_CSP_MAX )
Laurent Aimar's avatar
Laurent Aimar committed
439
    {
Henrik Gramner's avatar
Henrik Gramner committed
440
        x264_log( h, X264_LOG_ERROR, "invalid CSP (only I420/YV12/NV12/I422/YV16/NV16/I444/YV24/BGR/BGRA/RGB supported)\n" );
441
        return -1;
Laurent Aimar's avatar
Laurent Aimar committed
442
    }
Fiona Glaser's avatar
Fiona Glaser committed
443

Henrik Gramner's avatar
Henrik Gramner committed
444
    if( i_csp < X264_CSP_I444 && h->param.i_width % 2 )
Laurent Aimar's avatar
Laurent Aimar committed
445
    {
Henrik Gramner's avatar
Henrik Gramner committed
446
        x264_log( h, X264_LOG_ERROR, "width not divisible by 2 (%dx%d)\n",
Fiona Glaser's avatar
Fiona Glaser committed
447
                  h->param.i_width, h->param.i_height );
448
        return -1;
Laurent Aimar's avatar
Laurent Aimar committed
449
450
    }

Henrik Gramner's avatar
Henrik Gramner committed
451
    if( i_csp < X264_CSP_I422 && PARAM_INTERLACED && h->param.i_height % 4 )
452
    {
Henrik Gramner's avatar
Henrik Gramner committed
453
454
455
456
457
458
459
460
461
        x264_log( h, X264_LOG_ERROR, "height not divisible by 4 (%dx%d)\n",
                  h->param.i_width, h->param.i_height );
        return -1;
    }

    if( (i_csp < X264_CSP_I422 || PARAM_INTERLACED) && h->param.i_height % 2 )
    {
        x264_log( h, X264_LOG_ERROR, "height not divisible by 2 (%dx%d)\n",
                  h->param.i_width, h->param.i_height );
462
463
464
        return -1;
    }

465
466
467
468
469
470
471
472
    if( (h->param.crop_rect.i_left + h->param.crop_rect.i_right ) >= h->param.i_width ||
        (h->param.crop_rect.i_top  + h->param.crop_rect.i_bottom) >= h->param.i_height )
    {
        x264_log( h, X264_LOG_ERROR, "invalid crop-rect %u,%u,%u,%u\n", h->param.crop_rect.i_left,
                  h->param.crop_rect.i_top, h->param.crop_rect.i_right,  h->param.crop_rect.i_bottom );
        return -1;
    }

Steven Walters's avatar
Steven Walters committed
473
    if( h->param.i_threads == X264_THREADS_AUTO )
Fiona Glaser's avatar
Fiona Glaser committed
474
        h->param.i_threads = x264_cpu_num_processors() * (h->param.b_sliced_threads?2:3)/2;
Loren Merritt's avatar
Loren Merritt committed
475
    h->param.i_threads = x264_clip3( h->param.i_threads, 1, X264_THREAD_MAX );
Loren Merritt's avatar
Loren Merritt committed
476
477
    if( h->param.i_threads > 1 )
    {
478
479
#if !HAVE_THREAD
        x264_log( h, X264_LOG_WARNING, "not compiled with thread support!\n");
Loren Merritt's avatar
Loren Merritt committed
480
        h->param.i_threads = 1;
Loren Merritt's avatar
Loren Merritt committed
481
#endif
482
483
484
485
486
487
488
        /* Avoid absurdly small thread slices as they can reduce performance
         * and VBV compliance.  Capped at an arbitrary 4 rows per thread. */
        if( h->param.b_sliced_threads )
        {
            int max_threads = (h->param.i_height+15)/16 / 4;
            h->param.i_threads = X264_MIN( h->param.i_threads, max_threads );
        }
Loren Merritt's avatar
Loren Merritt committed
489
    }
490
491
    else
        h->param.b_sliced_threads = 0;
492
    h->i_thread_frames = h->param.b_sliced_threads ? 1 : h->param.i_threads;
493
494
    if( h->i_thread_frames > 1 )
        h->param.nalu_process = NULL;
Loren Merritt's avatar
Loren Merritt committed
495

496
497
498
499
500
501
502
    h->param.i_keyint_max = x264_clip3( h->param.i_keyint_max, 1, X264_KEYINT_MAX_INFINITE );
    if( h->param.i_keyint_max == 1 )
    {
        h->param.b_intra_refresh = 0;
        h->param.analyse.i_weighted_pred = 0;
    }

503
504
    h->param.i_frame_packing = x264_clip3( h->param.i_frame_packing, -1, 5 );

505
    /* Detect default ffmpeg settings and terminate with an error. */
506
    if( b_open )
507
508
509
510
511
512
513
514
515
516
517
518
519
520
    {
        int score = 0;
        score += h->param.analyse.i_me_range == 0;
        score += h->param.rc.i_qp_step == 3;
        score += h->param.i_keyint_max == 12;
        score += h->param.rc.i_qp_min == 2;
        score += h->param.rc.i_qp_max == 31;
        score += h->param.rc.f_qcompress == 0.5;
        score += fabs(h->param.rc.f_ip_factor - 1.25) < 0.01;
        score += fabs(h->param.rc.f_pb_factor - 1.25) < 0.01;
        score += h->param.analyse.inter == 0 && h->param.analyse.i_subpel_refine == 8;
        if( score >= 5 )
        {
            x264_log( h, X264_LOG_ERROR, "broken ffmpeg default settings detected\n" );
521
522
523
524
            x264_log( h, X264_LOG_ERROR, "use an encoding preset (e.g. -vpre medium)\n" );
            x264_log( h, X264_LOG_ERROR, "preset usage: -vpre <speed> -vpre <profile>\n" );
            x264_log( h, X264_LOG_ERROR, "speed presets are listed in x264 --help\n" );
            x264_log( h, X264_LOG_ERROR, "profile is optional; x264 defaults to high\n" );
525
526
527
528
            return -1;
        }
    }

529
530
    if( h->param.rc.i_rc_method < 0 || h->param.rc.i_rc_method > 2 )
    {
531
        x264_log( h, X264_LOG_ERROR, "no ratecontrol method specified\n" );
532
533
        return -1;
    }
Fiona Glaser's avatar
Fiona Glaser committed
534
    h->param.rc.f_rf_constant = x264_clip3f( h->param.rc.f_rf_constant, -QP_BD_OFFSET, 51 );
535
    h->param.rc.f_rf_constant_max = x264_clip3f( h->param.rc.f_rf_constant_max, -QP_BD_OFFSET, 51 );
536
    h->param.rc.i_qp_constant = x264_clip3( h->param.rc.i_qp_constant, 0, QP_MAX );
537
    h->param.analyse.i_subpel_refine = x264_clip3( h->param.analyse.i_subpel_refine, 0, 11 );
538
539
    h->param.rc.f_ip_factor = X264_MAX( h->param.rc.f_ip_factor, 0.01f );
    h->param.rc.f_pb_factor = X264_MAX( h->param.rc.f_pb_factor, 0.01f );
540
    if( h->param.rc.i_rc_method == X264_RC_CRF )
Fiona Glaser's avatar
Fiona Glaser committed
541
    {
Fiona Glaser's avatar
Fiona Glaser committed
542
        h->param.rc.i_qp_constant = h->param.rc.f_rf_constant + QP_BD_OFFSET;
Fiona Glaser's avatar
Fiona Glaser committed
543
544
        h->param.rc.i_bitrate = 0;
    }
545
546
    if( (h->param.rc.i_rc_method == X264_RC_CQP || h->param.rc.i_rc_method == X264_RC_CRF)
        && h->param.rc.i_qp_constant == 0 )
Loren Merritt's avatar
Loren Merritt committed
547
548
    {
        h->mb.b_lossless = 1;
Loren Merritt's avatar
Loren Merritt committed
549
        h->param.i_cqm_preset = X264_CQM_FLAT;
Loren Merritt's avatar
Loren Merritt committed
550
        h->param.psz_cqm_file = NULL;
551
        h->param.rc.i_rc_method = X264_RC_CQP;
Loren Merritt's avatar
Loren Merritt committed
552
553
554
        h->param.rc.f_ip_factor = 1;
        h->param.rc.f_pb_factor = 1;
        h->param.analyse.b_psnr = 0;
555
        h->param.analyse.b_ssim = 0;
556
        h->param.analyse.i_chroma_qp_offset = 0;
557
        h->param.analyse.i_trellis = 0;
Loren Merritt's avatar
Loren Merritt committed
558
        h->param.analyse.b_fast_pskip = 0;
559
        h->param.analyse.i_noise_reduction = 0;
Anton Mitrofanov's avatar
Anton Mitrofanov committed
560
        h->param.analyse.b_psy = 0;
561
        h->param.i_bframe = 0;
562
563
        /* 8x8dct is not useful without RD in CAVLC lossless */
        if( !h->param.b_cabac && h->param.analyse.i_subpel_refine < 6 )
564
            h->param.analyse.b_transform_8x8 = 0;
Loren Merritt's avatar
Loren Merritt committed
565
    }
Loren Merritt's avatar
Loren Merritt committed
566
567
568
    if( h->param.rc.i_rc_method == X264_RC_CQP )
    {
        float qp_p = h->param.rc.i_qp_constant;
569
570
        float qp_i = qp_p - 6*log2f( h->param.rc.f_ip_factor );
        float qp_b = qp_p + 6*log2f( h->param.rc.f_pb_factor );
571
572
        h->param.rc.i_qp_min = x264_clip3( (int)(X264_MIN3( qp_p, qp_i, qp_b )), 0, QP_MAX );
        h->param.rc.i_qp_max = x264_clip3( (int)(X264_MAX3( qp_p, qp_i, qp_b ) + .999), 0, QP_MAX );
Loren Merritt's avatar
Loren Merritt committed
573
        h->param.rc.i_aq_mode = 0;
Fiona Glaser's avatar
Fiona Glaser committed
574
        h->param.rc.b_mb_tree = 0;
575
        h->param.rc.i_bitrate = 0;
Loren Merritt's avatar
Loren Merritt committed
576
    }
577
    h->param.rc.i_qp_max = x264_clip3( h->param.rc.i_qp_max, 0, QP_MAX );
578
    h->param.rc.i_qp_min = x264_clip3( h->param.rc.i_qp_min, 0, h->param.rc.i_qp_max );
579
    h->param.rc.i_qp_step = x264_clip3( h->param.rc.i_qp_step, 0, QP_MAX );
580
581
582
583
    h->param.rc.i_bitrate = x264_clip3( h->param.rc.i_bitrate, 0, 2000000 );
    h->param.rc.i_vbv_buffer_size = x264_clip3( h->param.rc.i_vbv_buffer_size, 0, 2000000 );
    h->param.rc.i_vbv_max_bitrate = x264_clip3( h->param.rc.i_vbv_max_bitrate, 0, 2000000 );
    h->param.rc.f_vbv_buffer_init = x264_clip3f( h->param.rc.f_vbv_buffer_init, 0, 2000000 );
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
    if( h->param.rc.i_vbv_buffer_size )
    {
        if( h->param.rc.i_rc_method == X264_RC_CQP )
        {
            x264_log( h, X264_LOG_WARNING, "VBV is incompatible with constant QP, ignored.\n" );
            h->param.rc.i_vbv_max_bitrate = 0;
            h->param.rc.i_vbv_buffer_size = 0;
        }
        else if( h->param.rc.i_vbv_max_bitrate == 0 )
        {
            if( h->param.rc.i_rc_method == X264_RC_ABR )
            {
                x264_log( h, X264_LOG_WARNING, "VBV maxrate unspecified, assuming CBR\n" );
                h->param.rc.i_vbv_max_bitrate = h->param.rc.i_bitrate;
            }
            else
            {
                x264_log( h, X264_LOG_WARNING, "VBV bufsize set but maxrate unspecified, ignored\n" );
                h->param.rc.i_vbv_buffer_size = 0;
            }
        }
        else if( h->param.rc.i_vbv_max_bitrate < h->param.rc.i_bitrate &&
                 h->param.rc.i_rc_method == X264_RC_ABR )
        {
            x264_log( h, X264_LOG_WARNING, "max bitrate less than average bitrate, assuming CBR\n" );
            h->param.rc.i_vbv_max_bitrate = h->param.rc.i_bitrate;
        }
    }
    else if( h->param.rc.i_vbv_max_bitrate )
    {
        x264_log( h, X264_LOG_WARNING, "VBV maxrate specified, but no bufsize, ignored\n" );
        h->param.rc.i_vbv_max_bitrate = 0;
    }
Loren Merritt's avatar
Loren Merritt committed
617

Fiona Glaser's avatar
Fiona Glaser committed
618
619
620
    h->param.i_slice_max_size = X264_MAX( h->param.i_slice_max_size, 0 );
    h->param.i_slice_max_mbs = X264_MAX( h->param.i_slice_max_mbs, 0 );

621
    int max_slices = (h->param.i_height+((16<<PARAM_INTERLACED)-1))/(16<<PARAM_INTERLACED);
Fiona Glaser's avatar
Fiona Glaser committed
622
623
624
625
626
627
628
629
    if( h->param.b_sliced_threads )
        h->param.i_slice_count = x264_clip3( h->param.i_threads, 0, max_slices );
    else
    {
        h->param.i_slice_count = x264_clip3( h->param.i_slice_count, 0, max_slices );
        if( h->param.i_slice_max_mbs || h->param.i_slice_max_size )
            h->param.i_slice_count = 0;
    }
Fiona Glaser's avatar
Fiona Glaser committed
630

631
632
633
634
635
636
637
638
639
640
641
642
643
    if( h->param.b_bluray_compat )
    {
        h->param.i_bframe_pyramid = X264_MIN( X264_B_PYRAMID_STRICT, h->param.i_bframe_pyramid );
        h->param.i_bframe = X264_MIN( h->param.i_bframe, 3 );
        h->param.b_aud = 1;
        h->param.i_nal_hrd = X264_MAX( h->param.i_nal_hrd, X264_NAL_HRD_VBR );
        h->param.i_slice_max_size = 0;
        h->param.i_slice_max_mbs = 0;
        h->param.b_intra_refresh = 0;
        h->param.i_frame_reference = X264_MIN( h->param.i_frame_reference, 6 );
        h->param.i_dpb_size = X264_MIN( h->param.i_dpb_size, 6 );
        /* Due to the proliferation of broken players that don't handle dupes properly. */
        h->param.analyse.i_weighted_pred = X264_MIN( h->param.analyse.i_weighted_pred, X264_WEIGHTP_SIMPLE );
644
645
        if( h->param.b_fake_interlaced )
            h->param.b_pic_struct = 1;
646
647
    }

648
649
    h->param.i_frame_reference = x264_clip3( h->param.i_frame_reference, 1, X264_REF_MAX );
    h->param.i_dpb_size = x264_clip3( h->param.i_dpb_size, 1, X264_REF_MAX );
Fiona Glaser's avatar
Fiona Glaser committed
650
651
    if( h->param.i_scenecut_threshold < 0 )
        h->param.i_scenecut_threshold = 0;
652
    h->param.analyse.i_direct_mv_pred = x264_clip3( h->param.analyse.i_direct_mv_pred, X264_DIRECT_PRED_NONE, X264_DIRECT_PRED_AUTO );
653
654
655
656
657
    if( !h->param.analyse.i_subpel_refine && h->param.analyse.i_direct_mv_pred > X264_DIRECT_PRED_SPATIAL )
    {
        x264_log( h, X264_LOG_WARNING, "subme=0 + direct=temporal is not supported\n" );
        h->param.analyse.i_direct_mv_pred = X264_DIRECT_PRED_SPATIAL;
    }
Lamont Alston's avatar
Lamont Alston committed
658
    h->param.i_bframe = x264_clip3( h->param.i_bframe, 0, X264_MIN( X264_BFRAME_MAX, h->param.i_keyint_max-1 ) );
659
    h->param.i_bframe_bias = x264_clip3( h->param.i_bframe_bias, -90, 100 );
Lamont Alston's avatar
Lamont Alston committed
660
661
662
    if( h->param.i_bframe <= 1 )
        h->param.i_bframe_pyramid = X264_B_PYRAMID_NONE;
    h->param.i_bframe_pyramid = x264_clip3( h->param.i_bframe_pyramid, X264_B_PYRAMID_NONE, X264_B_PYRAMID_NORMAL );
663
    h->param.i_bframe_adaptive = x264_clip3( h->param.i_bframe_adaptive, X264_B_ADAPT_NONE, X264_B_ADAPT_TRELLIS );
664
    if( !h->param.i_bframe )
665
    {
666
        h->param.i_bframe_adaptive = X264_B_ADAPT_NONE;
667
668
        h->param.analyse.i_direct_mv_pred = 0;
        h->param.analyse.b_weighted_bipred = 0;
669
        h->param.b_open_gop = 0;
670
    }
Fiona Glaser's avatar
Fiona Glaser committed
671
672
673
674
675
    if( h->param.b_intra_refresh && h->param.i_bframe_pyramid == X264_B_PYRAMID_NORMAL )
    {
        x264_log( h, X264_LOG_WARNING, "b-pyramid normal + intra-refresh is not supported\n" );
        h->param.i_bframe_pyramid = X264_B_PYRAMID_STRICT;
    }
676
    if( h->param.b_intra_refresh && (h->param.i_frame_reference > 1 || h->param.i_dpb_size > 1) )
Fiona Glaser's avatar
Fiona Glaser committed
677
678
679
    {
        x264_log( h, X264_LOG_WARNING, "ref > 1 + intra-refresh is not supported\n" );
        h->param.i_frame_reference = 1;
680
        h->param.i_dpb_size = 1;
Fiona Glaser's avatar
Fiona Glaser committed
681
    }
682
    if( h->param.b_intra_refresh && h->param.b_open_gop )
Lamont Alston's avatar
Lamont Alston committed
683
684
    {
        x264_log( h, X264_LOG_WARNING, "intra-refresh is not compatible with open-gop\n" );
685
        h->param.b_open_gop = 0;
Lamont Alston's avatar
Lamont Alston committed
686
    }
687
    float fps = h->param.i_fps_num > 0 && h->param.i_fps_den > 0 ? (float) h->param.i_fps_num / h->param.i_fps_den : 25.0;
Fiona Glaser's avatar
Fiona Glaser committed
688
    if( h->param.i_keyint_min == X264_KEYINT_MIN_AUTO )
689
        h->param.i_keyint_min = X264_MIN( h->param.i_keyint_max / 10, fps );
Fiona Glaser's avatar
Fiona Glaser committed
690
    h->param.i_keyint_min = x264_clip3( h->param.i_keyint_min, 1, h->param.i_keyint_max/2+1 );
Fiona Glaser's avatar
Fiona Glaser committed
691
    h->param.rc.i_lookahead = x264_clip3( h->param.rc.i_lookahead, 0, X264_LOOKAHEAD_MAX );
Fiona Glaser's avatar
Fiona Glaser committed
692
693
694
695
696
697
    {
        int maxrate = X264_MAX( h->param.rc.i_vbv_max_bitrate, h->param.rc.i_bitrate );
        float bufsize = maxrate ? (float)h->param.rc.i_vbv_buffer_size / maxrate : 0;
        h->param.rc.i_lookahead = X264_MIN( h->param.rc.i_lookahead, X264_MAX( h->param.i_keyint_max, bufsize*fps ) );
    }

698
    if( !h->param.i_timebase_num || !h->param.i_timebase_den || !(h->param.b_vfr_input || h->param.b_pulldown) )
699
700
701
702
703
    {
        h->param.i_timebase_num = h->param.i_fps_den;
        h->param.i_timebase_den = h->param.i_fps_num;
    }

704
    h->param.rc.f_qcompress = x264_clip3f( h->param.rc.f_qcompress, 0.0, 1.0 );
Fiona Glaser's avatar
Fiona Glaser committed
705
    if( h->param.i_keyint_max == 1 || h->param.rc.f_qcompress == 1 )
706
        h->param.rc.b_mb_tree = 0;
707
708
    if( (!h->param.b_intra_refresh && h->param.i_keyint_max != X264_KEYINT_MAX_INFINITE) &&
        !h->param.rc.i_lookahead && h->param.rc.b_mb_tree )
Fiona Glaser's avatar
Fiona Glaser committed
709
    {
710
        x264_log( h, X264_LOG_WARNING, "lookaheadless mb-tree requires intra refresh or infinite keyint\n" );
Fiona Glaser's avatar
Fiona Glaser committed
711
712
        h->param.rc.b_mb_tree = 0;
    }
Fiona Glaser's avatar
Fiona Glaser committed
713
714
    if( h->param.rc.b_stat_read )
        h->param.rc.i_lookahead = 0;
715
#if HAVE_THREAD
716
717
718
    if( h->param.i_sync_lookahead < 0 )
        h->param.i_sync_lookahead = h->param.i_bframe + 1;
    h->param.i_sync_lookahead = X264_MIN( h->param.i_sync_lookahead, X264_LOOKAHEAD_MAX );
719
    if( h->param.rc.b_stat_read || h->i_thread_frames == 1 )
Steven Walters's avatar
Steven Walters committed
720
721
722
723
        h->param.i_sync_lookahead = 0;
#else
    h->param.i_sync_lookahead = 0;
#endif
Fiona Glaser's avatar
Fiona Glaser committed
724

Laurent Aimar's avatar
Laurent Aimar committed
725
726
    h->param.i_deblocking_filter_alphac0 = x264_clip3( h->param.i_deblocking_filter_alphac0, -6, 6 );
    h->param.i_deblocking_filter_beta    = x264_clip3( h->param.i_deblocking_filter_beta, -6, 6 );
727
728
    h->param.analyse.i_luma_deadzone[0] = x264_clip3( h->param.analyse.i_luma_deadzone[0], 0, 32 );
    h->param.analyse.i_luma_deadzone[1] = x264_clip3( h->param.analyse.i_luma_deadzone[1], 0, 32 );
Laurent Aimar's avatar
Laurent Aimar committed
729

730
    h->param.i_cabac_init_idc = x264_clip3( h->param.i_cabac_init_idc, 0, 2 );
Laurent Aimar's avatar
Laurent Aimar committed
731

Loren Merritt's avatar
Loren Merritt committed
732
733
734
    if( h->param.i_cqm_preset < X264_CQM_FLAT || h->param.i_cqm_preset > X264_CQM_CUSTOM )
        h->param.i_cqm_preset = X264_CQM_FLAT;

735
    if( h->param.analyse.i_me_method < X264_ME_DIA ||
736
        h->param.analyse.i_me_method > X264_ME_TESA )
737
        h->param.analyse.i_me_method = X264_ME_HEX;
738
    h->param.analyse.i_me_range = x264_clip3( h->param.analyse.i_me_range, 4, 1024 );
739
    if( h->param.analyse.i_me_range > 16 && h->param.analyse.i_me_method <= X264_ME_HEX )
740
        h->param.analyse.i_me_range = 16;
741
742
743
    if( h->param.analyse.i_me_method == X264_ME_TESA &&
        (h->mb.b_lossless || h->param.analyse.i_subpel_refine <= 1) )
        h->param.analyse.i_me_method = X264_ME_ESA;
744
745
746
747
    h->param.analyse.b_mixed_references = h->param.analyse.b_mixed_references && h->param.i_frame_reference > 1;
    h->param.analyse.inter &= X264_ANALYSE_PSUB16x16|X264_ANALYSE_PSUB8x8|X264_ANALYSE_BSUB16x16|
                              X264_ANALYSE_I4x4|X264_ANALYSE_I8x8;
    h->param.analyse.intra &= X264_ANALYSE_I4x4|X264_ANALYSE_I8x8;
748
749
    if( !(h->param.analyse.inter & X264_ANALYSE_PSUB16x16) )
        h->param.analyse.inter &= ~X264_ANALYSE_PSUB8x8;
750
751
752
753
754
    if( !h->param.analyse.b_transform_8x8 )
    {
        h->param.analyse.inter &= ~X264_ANALYSE_I8x8;
        h->param.analyse.intra &= ~X264_ANALYSE_I8x8;
    }
755
    h->param.analyse.i_trellis = x264_clip3( h->param.analyse.i_trellis, 0, 2 );
756
757
758
759
    h->param.rc.i_aq_mode = x264_clip3( h->param.rc.i_aq_mode, 0, 2 );
    h->param.rc.f_aq_strength = x264_clip3f( h->param.rc.f_aq_strength, 0, 3 );
    if( h->param.rc.f_aq_strength == 0 )
        h->param.rc.i_aq_mode = 0;
760
761
762
763
764
765
766

    if( h->param.i_log_level < X264_LOG_INFO )
    {
        h->param.analyse.b_psnr = 0;
        h->param.analyse.b_ssim = 0;
    }
    /* Warn users trying to measure PSNR/SSIM with psy opts on. */
767
    if( b_open && (h->param.analyse.b_psnr || h->param.analyse.b_ssim) )
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
    {
        char *s = NULL;

        if( h->param.analyse.b_psy )
        {
            s = h->param.analyse.b_psnr ? "psnr" : "ssim";
            x264_log( h, X264_LOG_WARNING, "--%s used with psy on: results will be invalid!\n", s );
        }
        else if( !h->param.rc.i_aq_mode && h->param.analyse.b_ssim )
        {
            x264_log( h, X264_LOG_WARNING, "--ssim used with AQ off: results will be invalid!\n" );
            s = "ssim";
        }
        else if(  h->param.rc.i_aq_mode && h->param.analyse.b_psnr )
        {
            x264_log( h, X264_LOG_WARNING, "--psnr used with AQ on: results will be invalid!\n" );
            s = "psnr";
        }
        if( s )
            x264_log( h, X264_LOG_WARNING, "--tune %s should be used if attempting to benchmark %s!\n", s, s );
    }

Fiona Glaser's avatar
Fiona Glaser committed
790
791
792
793
794
    if( !h->param.analyse.b_psy )
    {
        h->param.analyse.f_psy_rd = 0;
        h->param.analyse.f_psy_trellis = 0;
    }
795
796
    h->param.analyse.f_psy_rd = x264_clip3f( h->param.analyse.f_psy_rd, 0, 10 );
    h->param.analyse.f_psy_trellis = x264_clip3f( h->param.analyse.f_psy_trellis, 0, 10 );
797
798
    h->mb.i_psy_rd = h->param.analyse.i_subpel_refine >= 6 ? FIX8( h->param.analyse.f_psy_rd ) : 0;
    h->mb.i_psy_trellis = h->param.analyse.i_trellis ? FIX8( h->param.analyse.f_psy_trellis / 4 ) : 0;
799
    h->param.analyse.i_chroma_qp_offset = x264_clip3(h->param.analyse.i_chroma_qp_offset, -32, 32);
Fiona Glaser's avatar
Fiona Glaser committed
800
    /* In 4:4:4 mode, chroma gets twice as much resolution, so we can halve its quality. */
xvidfan's avatar
xvidfan committed
801
    if( b_open && i_csp >= X264_CSP_I444 && i_csp < X264_CSP_BGR && h->param.analyse.b_psy )
Fiona Glaser's avatar
Fiona Glaser committed
802
        h->param.analyse.i_chroma_qp_offset += 6;
803
804
    /* Psy RDO increases overall quantizers to improve the quality of luma--this indirectly hurts chroma quality */
    /* so we lower the chroma QP offset to compensate */
805
    if( b_open && h->mb.i_psy_rd )
806
807
        h->param.analyse.i_chroma_qp_offset -= h->param.analyse.f_psy_rd < 0.25 ? 1 : 2;
    /* Psy trellis has a similar effect. */
808
    if( b_open && h->mb.i_psy_trellis )
809
810
        h->param.analyse.i_chroma_qp_offset -= h->param.analyse.f_psy_trellis < 0.25 ? 1 : 2;
    h->param.analyse.i_chroma_qp_offset = x264_clip3(h->param.analyse.i_chroma_qp_offset, -12, 12);
Fiona Glaser's avatar
Fiona Glaser committed
811
812
813
814
815
816
    /* MB-tree requires AQ to be on, even if the strength is zero. */
    if( !h->param.rc.i_aq_mode && h->param.rc.b_mb_tree )
    {
        h->param.rc.i_aq_mode = 1;
        h->param.rc.f_aq_strength = 0;
    }
817
    h->param.analyse.i_noise_reduction = x264_clip3( h->param.analyse.i_noise_reduction, 0, 1<<16 );
818
    if( h->param.analyse.i_subpel_refine >= 10 && (h->param.analyse.i_trellis != 2 || !h->param.rc.i_aq_mode) )
Fiona Glaser's avatar
Fiona Glaser committed
819
        h->param.analyse.i_subpel_refine = 9;
820

821
822
    {
        const x264_level_t *l = x264_levels;
823
        if( h->param.i_level_idc < 0 )
824
        {
Loren Merritt's avatar
Loren Merritt committed
825
            int maxrate_bak = h->param.rc.i_vbv_max_bitrate;
826
827
828
829
830
            if( h->param.rc.i_rc_method == X264_RC_ABR && h->param.rc.i_vbv_buffer_size <= 0 )
                h->param.rc.i_vbv_max_bitrate = h->param.rc.i_bitrate * 2;
            x264_sps_init( h->sps, h->param.i_sps_id, &h->param );
            do h->param.i_level_idc = l->level_idc;
                while( l[1].level_idc && x264_validate_levels( h, 0 ) && l++ );
Loren Merritt's avatar
Loren Merritt committed
831
            h->param.rc.i_vbv_max_bitrate = maxrate_bak;
832
833
834
835
836
837
838
839
840
841
        }
        else
        {
            while( l->level_idc && l->level_idc != h->param.i_level_idc )
                l++;
            if( l->level_idc == 0 )
            {
                x264_log( h, X264_LOG_ERROR, "invalid level_idc: %d\n", h->param.i_level_idc );
                return -1;
            }
842
843
        }
        if( h->param.analyse.i_mv_range <= 0 )
844
            h->param.analyse.i_mv_range = l->mv_range >> PARAM_INTERLACED;
845
        else
846
            h->param.analyse.i_mv_range = x264_clip3(h->param.analyse.i_mv_range, 32, 512 >> PARAM_INTERLACED);
847
848
    }

849
    h->param.analyse.i_weighted_pred = x264_clip3( h->param.analyse.i_weighted_pred, X264_WEIGHTP_NONE, X264_WEIGHTP_SMART );
850

851
    if( PARAM_INTERLACED )
852
853
854
855
856
857
858
859
860
861
862
863
864
    {
        if( h->param.analyse.i_me_method >= X264_ME_ESA )
        {
            x264_log( h, X264_LOG_WARNING, "interlace + me=esa is not implemented\n" );
            h->param.analyse.i_me_method = X264_ME_UMH;
        }
        if( h->param.analyse.i_weighted_pred > 0 )
        {
            x264_log( h, X264_LOG_WARNING, "interlace + weightp is not implemented\n" );
            h->param.analyse.i_weighted_pred = X264_WEIGHTP_NONE;
        }
    }

865
    if( !h->param.analyse.i_weighted_pred && h->param.rc.b_mb_tree && h->param.analyse.b_psy )
Dylan Yudaken's avatar
Dylan Yudaken committed
866
867
        h->param.analyse.i_weighted_pred = X264_WEIGHTP_FAKE;

868
    if( h->i_thread_frames > 1 )
Loren Merritt's avatar
Loren Merritt committed
869
870
871
872
873
874
875
876
877
    {
        int r = h->param.analyse.i_mv_range_thread;
        int r2;
        if( r <= 0 )
        {
            // half of the available space is reserved and divided evenly among the threads,
            // the rest is allocated to whichever thread is far enough ahead to use it.
            // reserving more space increases quality for some videos, but costs more time
            // in thread synchronization.
878
            int max_range = (h->param.i_height + X264_THREAD_HEIGHT) / h->i_thread_frames - X264_THREAD_HEIGHT;
Loren Merritt's avatar
Loren Merritt committed
879
880
881
882
883
884
885
886
887
888
889
890
            r = max_range / 2;
        }
        r = X264_MAX( r, h->param.analyse.i_me_range );
        r = X264_MIN( r, h->param.analyse.i_mv_range );
        // round up to use the whole mb row
        r2 = (r & ~15) + ((-X264_THREAD_HEIGHT) & 15);
        if( r2 < r )
            r2 += 16;
        x264_log( h, X264_LOG_DEBUG, "using mv_range_thread = %d\n", r2 );
        h->param.analyse.i_mv_range_thread = r2;
    }

891
892
    if( h->param.rc.f_rate_tolerance < 0 )
        h->param.rc.f_rate_tolerance = 0;
Loren Merritt's avatar
Loren Merritt committed
893
894
895
896
897
    if( h->param.rc.f_qblur < 0 )
        h->param.rc.f_qblur = 0;
    if( h->param.rc.f_complexity_blur < 0 )
        h->param.rc.f_complexity_blur = 0;

898
899
    h->param.i_sps_id &= 31;

900
    if( PARAM_INTERLACED )
901
902
        h->param.b_pic_struct = 1;

903
904
    h->param.i_nal_hrd = x264_clip3( h->param.i_nal_hrd, X264_NAL_HRD_NONE, X264_NAL_HRD_CBR );

905
906
907
908
909
910
911
912
913
914
915
916
917
    if( h->param.i_nal_hrd && !h->param.rc.i_vbv_buffer_size )
    {
        x264_log( h, X264_LOG_WARNING, "NAL HRD parameters require VBV parameters\n" );
        h->param.i_nal_hrd = X264_NAL_HRD_NONE;
    }

    if( h->param.i_nal_hrd == X264_NAL_HRD_CBR &&
       (h->param.rc.i_bitrate != h->param.rc.i_vbv_max_bitrate || !h->param.rc.i_vbv_max_bitrate) )
    {
        x264_log( h, X264_LOG_WARNING, "CBR HRD requires constant bitrate\n" );
        h->param.i_nal_hrd = X264_NAL_HRD_VBR;
    }

918
919
920
    /* ensure the booleans are 0 or 1 so they can be used in math */
#define BOOLIFY(x) h->param.x = !!h->param.x
    BOOLIFY( b_cabac );
921
    BOOLIFY( b_constrained_intra );
922
    BOOLIFY( b_deblocking_filter );
923
    BOOLIFY( b_deterministic );
924
    BOOLIFY( b_sliced_threads );
925
    BOOLIFY( b_interlaced );
Fiona Glaser's avatar
Fiona Glaser committed
926
    BOOLIFY( b_intra_refresh );
927
928
929
930
    BOOLIFY( b_visualize );
    BOOLIFY( b_aud );
    BOOLIFY( b_repeat_headers );
    BOOLIFY( b_annexb );
931
    BOOLIFY( b_vfr_input );
932
933
    BOOLIFY( b_pulldown );
    BOOLIFY( b_tff );
934
    BOOLIFY( b_pic_struct );
Kieran Kunhya's avatar
Kieran Kunhya committed
935
    BOOLIFY( b_fake_interlaced );
936
    BOOLIFY( b_open_gop );
937
    BOOLIFY( b_bluray_compat );
938
    BOOLIFY( analyse.b_transform_8x8 );
939
    BOOLIFY( analyse.b_weighted_bipred );
940
    BOOLIFY( analyse.b_chroma_me );
941
    BOOLIFY( analyse.b_mixed_references );
942
    BOOLIFY( analyse.b_fast_pskip );
943
944
945
946
    BOOLIFY( analyse.b_dct_decimate );
    BOOLIFY( analyse.b_psy );
    BOOLIFY( analyse.b_psnr );
    BOOLIFY( analyse.b_ssim );
947
948
    BOOLIFY( rc.b_stat_write );
    BOOLIFY( rc.b_stat_read );
949
    BOOLIFY( rc.b_mb_tree );
950
951
#undef BOOLIFY

952
953
954
    return 0;
}

955
956
static void mbcmp_init( x264_t *h )
{
957
    int satd = !h->mb.b_lossless && h->param.analyse.i_subpel_refine > 1;
958
959
    memcpy( h->pixf.mbcmp, satd ? h->pixf.satd : h->pixf.sad_aligned, sizeof(h->pixf.mbcmp) );
    memcpy( h->pixf.mbcmp_unaligned, satd ? h->pixf.satd : h->pixf.sad, sizeof(h->pixf.mbcmp_unaligned) );
960
    h->pixf.intra_mbcmp_x3_16x16 = satd ? h->pixf.intra_satd_x3_16x16 : h->pixf.intra_sad_x3_16x16;
Henrik Gramner's avatar
Henrik Gramner committed
961
962
    h->pixf.intra_mbcmp_x3_8x16c = satd ? h->pixf.intra_satd_x3_8x16c : h->pixf.intra_sad_x3_8x16c;
    h->pixf.intra_mbcmp_x3_8x8c  = satd ? h->pixf.intra_satd_x3_8x8c  : h->pixf.intra_sad_x3_8x8c;
Fiona Glaser's avatar
Fiona Glaser committed
963
    h->pixf.intra_mbcmp_x3_8x8 = satd ? h->pixf.intra_sa8d_x3_8x8 : h->pixf.intra_sad_x3_8x8;
Fiona Glaser's avatar
Fiona Glaser committed
964
    h->pixf.intra_mbcmp_x3_4x4 = satd ? h->pixf.intra_satd_x3_4x4 : h->pixf.intra_sad_x3_4x4;
965
966
    h->pixf.intra_mbcmp_x9_4x4 = h->param.b_cpu_independent || h->mb.b_lossless ? NULL
                               : satd ? h->pixf.intra_satd_x9_4x4 : h->pixf.intra_sad_x9_4x4;
967
968
969
970
    satd &= h->param.analyse.i_me_method == X264_ME_TESA;
    memcpy( h->pixf.fpelcmp, satd ? h->pixf.satd : h->pixf.sad, sizeof(h->pixf.fpelcmp) );
    memcpy( h->pixf.fpelcmp_x3, satd ? h->pixf.satd_x3 : h->pixf.sad_x3, sizeof(h->pixf.fpelcmp_x3) );
    memcpy( h->pixf.fpelcmp_x4, satd ? h->pixf.satd_x4 : h->pixf.sad_x4, sizeof(h->pixf.fpelcmp_x4) );
971
972
}

Henrik Gramner's avatar
Henrik Gramner committed
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
static void chroma_dsp_init( x264_t *h )
{
    memcpy( h->luma2chroma_pixel, x264_luma2chroma_pixel[CHROMA_FORMAT], sizeof(h->luma2chroma_pixel) );

    switch( CHROMA_FORMAT )
    {
        case CHROMA_420:
            memcpy( h->predict_chroma, h->predict_8x8c, sizeo