]> git.sesse.net Git - x264/blob - x264.c
Remove unused function
[x264] / x264.c
1 /*****************************************************************************
2  * x264: h264 encoder testing program.
3  *****************************************************************************
4  * Copyright (C) 2003-2008 x264 project
5  *
6  * Authors: Loren Merritt <lorenm@u.washington.edu>
7  *          Laurent Aimar <fenrir@via.ecp.fr>
8  *          Steven Walters <kemuri9@gmail.com>
9  *          Kieran Kunhya <kieran@kunhya.com>
10  *
11  * This program is free software; you can redistribute it and/or modify
12  * it under the terms of the GNU General Public License as published by
13  * the Free Software Foundation; either version 2 of the License, or
14  * (at your option) any later version.
15  *
16  * This program is distributed in the hope that it will be useful,
17  * but WITHOUT ANY WARRANTY; without even the implied warranty of
18  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
19  * GNU General Public License for more details.
20  *
21  * You should have received a copy of the GNU General Public License
22  * along with this program; if not, write to the Free Software
23  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02111, USA.
24  *****************************************************************************/
25
26 #include <stdlib.h>
27 #include <math.h>
28
29 #include <signal.h>
30 #define _GNU_SOURCE
31 #include <getopt.h>
32
33 #include "common/common.h"
34 #include "common/cpu.h"
35 #include "x264.h"
36 #include "muxers.h"
37
38 #ifdef _WIN32
39 #include <windows.h>
40 #else
41 #define SetConsoleTitle(t)
42 #endif
43
44 /* Ctrl-C handler */
45 static int     b_ctrl_c = 0;
46 static int     b_exit_on_ctrl_c = 0;
47 static void    SigIntHandler( int a )
48 {
49     if( b_exit_on_ctrl_c )
50         exit(0);
51     b_ctrl_c = 1;
52 }
53
54 typedef struct {
55     int b_progress;
56     int i_seek;
57     hnd_t hin;
58     hnd_t hout;
59     FILE *qpfile;
60 } cli_opt_t;
61
62 /* i/o file operation function pointer structs */
63 cli_input_t input;
64 static cli_output_t output;
65
66 static const char * const demuxer_names[] =
67 {
68     "auto",
69     "yuv",
70     "y4m",
71 #ifdef AVS_INPUT
72     "avs",
73 #endif
74 #ifdef LAVF_INPUT
75     "lavf",
76 #endif
77 #ifdef FFMS_INPUT
78     "ffms",
79 #endif
80     0
81 };
82
83 static const char * const muxer_names[] =
84 {
85     "auto",
86     "raw",
87     "mkv",
88     "flv",
89 #ifdef MP4_OUTPUT
90     "mp4",
91 #endif
92     0
93 };
94
95 static void Help( x264_param_t *defaults, int longhelp );
96 static int  Parse( int argc, char **argv, x264_param_t *param, cli_opt_t *opt );
97 static int  Encode( x264_param_t *param, cli_opt_t *opt );
98
99 /****************************************************************************
100  * main:
101  ****************************************************************************/
102 int main( int argc, char **argv )
103 {
104     x264_param_t param;
105     cli_opt_t opt;
106     int ret;
107
108 #ifdef PTW32_STATIC_LIB
109     pthread_win32_process_attach_np();
110     pthread_win32_thread_attach_np();
111 #endif
112
113 #ifdef _WIN32
114     _setmode(_fileno(stdin), _O_BINARY);
115     _setmode(_fileno(stdout), _O_BINARY);
116 #endif
117
118     /* Parse command line */
119     if( Parse( argc, argv, &param, &opt ) < 0 )
120         return -1;
121
122     /* Control-C handler */
123     signal( SIGINT, SigIntHandler );
124
125     ret = Encode( &param, &opt );
126
127 #ifdef PTW32_STATIC_LIB
128     pthread_win32_thread_detach_np();
129     pthread_win32_process_detach_np();
130 #endif
131
132     return ret;
133 }
134
135 static char const *strtable_lookup( const char * const table[], int index )
136 {
137     int i = 0; while( table[i] ) i++;
138     return ( ( index >= 0 && index < i ) ? table[ index ] : "???" );
139 }
140
141 static char *stringify_names( char *buf, const char * const names[] )
142 {
143     int i = 0;
144     char *p = buf;
145     for( p[0] = 0; names[i]; i++ )
146     {
147         p += sprintf( p, "%s", names[i] );
148         if( names[i+1] )
149             p += sprintf( p, ", " );
150     }
151     return buf;
152 }
153
154 /*****************************************************************************
155  * Help:
156  *****************************************************************************/
157 static void Help( x264_param_t *defaults, int longhelp )
158 {
159     char buf[50];
160 #define H0 printf
161 #define H1 if(longhelp>=1) printf
162 #define H2 if(longhelp==2) printf
163     H0( "x264 core:%d%s\n"
164         "Syntax: x264 [options] -o outfile infile [widthxheight]\n"
165         "\n"
166         "Infile can be raw YUV 4:2:0 (in which case resolution is required),\n"
167         "  or YUV4MPEG 4:2:0 (*.y4m),\n"
168         "  or Avisynth if compiled with support (%s).\n"
169         "  or libav* formats if compiled with lavf support (%s) or ffms support (%s).\n"
170         "Outfile type is selected by filename:\n"
171         " .264 -> Raw bytestream\n"
172         " .mkv -> Matroska\n"
173         " .flv -> Flash Video\n"
174         " .mp4 -> MP4 if compiled with GPAC support (%s)\n"
175         "\n"
176         "Options:\n"
177         "\n"
178         "  -h, --help                  List basic options\n"
179         "      --longhelp              List more options\n"
180         "      --fullhelp              List all options\n"
181         "\n",
182         X264_BUILD, X264_VERSION,
183 #ifdef AVS_INPUT
184         "yes",
185 #else
186         "no",
187 #endif
188 #ifdef LAVF_INPUT
189         "yes",
190 #else
191         "no",
192 #endif
193 #ifdef FFMS_INPUT
194         "yes",
195 #else
196         "no",
197 #endif
198 #ifdef MP4_OUTPUT
199         "yes"
200 #else
201         "no"
202 #endif
203       );
204     H0( "Example usage:\n" );
205     H0( "\n" );
206     H0( "      Constant quality mode:\n" );
207     H0( "            x264 --crf 24 -o <output> <input>\n" );
208     H0( "\n" );
209     H0( "      Two-pass with a bitrate of 1000kbps:\n" );
210     H0( "            x264 --pass 1 --bitrate 1000 -o <output> <input>\n" );
211     H0( "            x264 --pass 2 --bitrate 1000 -o <output> <input>\n" );
212     H0( "\n" );
213     H0( "      Lossless:\n" );
214     H0( "            x264 --crf 0 -o <output> <input>\n" );
215     H0( "\n" );
216     H0( "      Maximum PSNR at the cost of speed and visual quality:\n" );
217     H0( "            x264 --preset placebo --tune psnr -o <output> <input>\n" );
218     H0( "\n" );
219     H0( "      Constant bitrate at 1000kbps with a 2 second-buffer:\n");
220     H0( "            x264 --vbv-bufsize 2000 --bitrate 1000 -o <output> <input>\n" );
221     H0( "\n" );
222     H0( "Presets:\n" );
223     H0( "\n" );
224     H0( "      --profile               Force the limits of an H.264 profile [high]\n"
225         "                                  Overrides all settings.\n" );
226     H2( "                                  - baseline:\n"
227         "                                    --no-8x8dct --bframes 0 --no-cabac\n"
228         "                                    --cqm flat --weightp 0 No interlaced\n"
229         "                                    No lossless\n"
230         "                                  - main:\n"
231         "                                    --no-8x8dct --cqm flat No lossless\n"
232         "                                  - high:\n"
233         "                                    No lossless\n" );
234         else H0( "                                  - baseline,main,high\n" );
235     H0( "      --preset                Use a preset to select encoding settings [medium]\n"
236         "                                  Overridden by user settings.\n" );
237     H2( "                                  - ultrafast:\n"
238         "                                    --no-8x8dct --aq-mode 0 --b-adapt 0\n"
239         "                                    --bframes 0 --no-cabac --no-deblock\n"
240         "                                    --no-mbtree --me dia --no-mixed-refs\n"
241         "                                    --partitions none --ref 1 --scenecut 0\n"
242         "                                    --subme 0 --trellis 0 --no-weightb\n"
243         "                                    --weightp 0\n"
244         "                                  - veryfast:\n"
245         "                                    --no-mbtree --me dia --no-mixed-refs\n"
246         "                                    --partitions i8x8,i4x4 --ref 1\n"
247         "                                    --subme 1 --trellis 0 --weightp 0\n"
248         "                                  - faster:\n"
249         "                                    --no-mbtree --no-mixed-refs --ref 2\n"
250         "                                    --subme 4 --weightp 1\n"
251         "                                  - fast:\n"
252         "                                    --rc-lookahead 30 --ref 2 --subme 6\n"
253         "                                  - medium:\n"
254         "                                    Default settings apply.\n"
255         "                                  - slow:\n"
256         "                                    --b-adapt 2 --direct auto --me umh\n"
257         "                                    --rc-lookahead 50 --ref 5 --subme 8\n"
258         "                                  - slower:\n"
259         "                                    --b-adapt 2 --direct auto --me umh\n"
260         "                                    --partitions all --rc-lookahead 60\n"
261         "                                    --ref 8 --subme 9 --trellis 2\n"
262         "                                  - veryslow:\n"
263         "                                    --b-adapt 2 --bframes 8 --direct auto\n"
264         "                                    --me umh --merange 24 --partitions all\n"
265         "                                    --ref 16 --subme 10 --trellis 2\n"
266         "                                    --rc-lookahead 60\n"
267         "                                  - placebo:\n"
268         "                                    --bframes 16 --b-adapt 2 --direct auto\n"
269         "                                    --slow-firstpass --no-fast-pskip\n"
270         "                                    --me tesa --merange 24 --partitions all\n"
271         "                                    --rc-lookahead 60 --ref 16 --subme 10\n"
272         "                                    --trellis 2\n" );
273     else H0( "                                  - ultrafast,veryfast,faster,fast,medium\n"
274              "                                  - slow,slower,veryslow,placebo\n" );
275     H0( "      --tune                  Tune the settings for a particular type of source\n"
276         "                              or situation\n"
277         "                                  Overridden by user settings.\n"
278         "                                  Multiple tunings are separated by commas.\n"
279         "                                  Only one psy tuning can be used at a time.\n" );
280     H2( "                                  - film (psy tuning):\n"
281         "                                    --deblock -1:-1 --psy-rd <unset>:0.15\n"
282         "                                  - animation (psy tuning):\n"
283         "                                    --bframes {+2} --deblock 1:1\n"
284         "                                    --psy-rd 0.4:<unset> --aq-strength 0.6\n"
285         "                                    --ref {Double if >1 else 1}\n"
286         "                                  - grain (psy tuning):\n"
287         "                                    --aq-strength 0.5 --no-dct-decimate\n"
288         "                                    --deadzone-inter 6 --deadzone-intra 6\n"
289         "                                    --deblock -2:-2 --ipratio 1.1 \n"
290         "                                    --pbratio 1.1 --psy-rd <unset>:0.25\n"
291         "                                    --qcomp 0.8\n"
292         "                                  - psnr (psy tuning):\n"
293         "                                    --aq-mode 0 --no-psy\n"
294         "                                  - ssim (psy tuning):\n"
295         "                                    --aq-mode 2 --no-psy\n"
296         "                                  - fastdecode:\n"
297         "                                    --no-cabac --no-deblock --no-weightb\n"
298         "                                    --weightp 0\n"
299         "                                  - zerolatency:\n"
300         "                                    --bframes 0 --rc-lookahead 0\n"
301         "                                    --sync-lookahead 0 --sliced-threads\n" );
302     else H0( "                                  - psy tunings: film,animation,grain,psnr,ssim\n"
303              "                                  - other tunings: fastdecode,zerolatency\n" );
304     H1( "      --slow-firstpass        Don't use faster settings with --pass 1\n" );
305     H0( "\n" );
306     H0( "Frame-type options:\n" );
307     H0( "\n" );
308     H0( "  -I, --keyint <integer>      Maximum GOP size [%d]\n", defaults->i_keyint_max );
309     H2( "  -i, --min-keyint <integer>  Minimum GOP size [%d]\n", defaults->i_keyint_min );
310     H2( "      --no-scenecut           Disable adaptive I-frame decision\n" );
311     H2( "      --scenecut <integer>    How aggressively to insert extra I-frames [%d]\n", defaults->i_scenecut_threshold );
312     H2( "      --intra-refresh         Use Periodic Intra Refresh instead of IDR frames\n" );
313     H1( "  -b, --bframes <integer>     Number of B-frames between I and P [%d]\n", defaults->i_bframe );
314     H1( "      --b-adapt <integer>     Adaptive B-frame decision method [%d]\n"
315         "                                  Higher values may lower threading efficiency.\n"
316         "                                  - 0: Disabled\n"
317         "                                  - 1: Fast\n"
318         "                                  - 2: Optimal (slow with high --bframes)\n", defaults->i_bframe_adaptive );
319     H2( "      --b-bias <integer>      Influences how often B-frames are used [%d]\n", defaults->i_bframe_bias );
320     H1( "      --b-pyramid <string>    Keep some B-frames as references [%s]\n"
321         "                                  - none: Disabled\n"
322         "                                  - strict: Strictly hierarchical pyramid\n"
323         "                                  - normal: Non-strict (not Blu-ray compatible)\n",
324         strtable_lookup( x264_b_pyramid_names, defaults->i_bframe_pyramid ) );
325     H1( "      --no-cabac              Disable CABAC\n" );
326     H1( "  -r, --ref <integer>         Number of reference frames [%d]\n", defaults->i_frame_reference );
327     H1( "      --no-deblock            Disable loop filter\n" );
328     H1( "  -f, --deblock <alpha:beta>  Loop filter parameters [%d:%d]\n",
329                                        defaults->i_deblocking_filter_alphac0, defaults->i_deblocking_filter_beta );
330     H2( "      --slices <integer>      Number of slices per frame; forces rectangular\n"
331         "                              slices and is overridden by other slicing options\n" );
332     else H1( "      --slices <integer>      Number of slices per frame\n" );
333     H2( "      --slice-max-size <integer> Limit the size of each slice in bytes\n");
334     H2( "      --slice-max-mbs <integer> Limit the size of each slice in macroblocks\n");
335     H0( "      --interlaced            Enable pure-interlaced mode\n" );
336     H2( "      --constrained-intra     Enable constrained intra prediction.\n" );
337     H0( "\n" );
338     H0( "Ratecontrol:\n" );
339     H0( "\n" );
340     H1( "  -q, --qp <integer>          Force constant QP (0-51, 0=lossless)\n" );
341     H0( "  -B, --bitrate <integer>     Set bitrate (kbit/s)\n" );
342     H0( "      --crf <float>           Quality-based VBR (0-51, 0=lossless) [%.1f]\n", defaults->rc.f_rf_constant );
343     H1( "      --rc-lookahead <integer> Number of frames for frametype lookahead [%d]\n", defaults->rc.i_lookahead );
344     H0( "      --vbv-maxrate <integer> Max local bitrate (kbit/s) [%d]\n", defaults->rc.i_vbv_max_bitrate );
345     H0( "      --vbv-bufsize <integer> Set size of the VBV buffer (kbit) [%d]\n", defaults->rc.i_vbv_buffer_size );
346     H2( "      --vbv-init <float>      Initial VBV buffer occupancy [%.1f]\n", defaults->rc.f_vbv_buffer_init );
347     H2( "      --qpmin <integer>       Set min QP [%d]\n", defaults->rc.i_qp_min );
348     H2( "      --qpmax <integer>       Set max QP [%d]\n", defaults->rc.i_qp_max );
349     H2( "      --qpstep <integer>      Set max QP step [%d]\n", defaults->rc.i_qp_step );
350     H2( "      --ratetol <float>       Tolerance of ABR ratecontrol and VBV [%.1f]\n", defaults->rc.f_rate_tolerance );
351     H2( "      --ipratio <float>       QP factor between I and P [%.2f]\n", defaults->rc.f_ip_factor );
352     H2( "      --pbratio <float>       QP factor between P and B [%.2f]\n", defaults->rc.f_pb_factor );
353     H2( "      --chroma-qp-offset <integer>  QP difference between chroma and luma [%d]\n", defaults->analyse.i_chroma_qp_offset );
354     H2( "      --aq-mode <integer>     AQ method [%d]\n"
355         "                                  - 0: Disabled\n"
356         "                                  - 1: Variance AQ (complexity mask)\n"
357         "                                  - 2: Auto-variance AQ (experimental)\n", defaults->rc.i_aq_mode );
358     H1( "      --aq-strength <float>   Reduces blocking and blurring in flat and\n"
359         "                              textured areas. [%.1f]\n", defaults->rc.f_aq_strength );
360     H1( "\n" );
361     H0( "  -p, --pass <integer>        Enable multipass ratecontrol\n"
362         "                                  - 1: First pass, creates stats file\n"
363         "                                  - 2: Last pass, does not overwrite stats file\n" );
364     H2( "                                  - 3: Nth pass, overwrites stats file\n" );
365     H1( "      --stats <string>        Filename for 2 pass stats [\"%s\"]\n", defaults->rc.psz_stat_out );
366     H2( "      --no-mbtree             Disable mb-tree ratecontrol.\n");
367     H2( "      --qcomp <float>         QP curve compression [%.2f]\n", defaults->rc.f_qcompress );
368     H2( "      --cplxblur <float>      Reduce fluctuations in QP (before curve compression) [%.1f]\n", defaults->rc.f_complexity_blur );
369     H2( "      --qblur <float>         Reduce fluctuations in QP (after curve compression) [%.1f]\n", defaults->rc.f_qblur );
370     H2( "      --zones <zone0>/<zone1>/...  Tweak the bitrate of regions of the video\n" );
371     H2( "                              Each zone is of the form\n"
372         "                                  <start frame>,<end frame>,<option>\n"
373         "                                  where <option> is either\n"
374         "                                      q=<integer> (force QP)\n"
375         "                                  or  b=<float> (bitrate multiplier)\n" );
376     H2( "      --qpfile <string>       Force frametypes and QPs for some or all frames\n"
377         "                              Format of each line: framenumber frametype QP\n"
378         "                              QP of -1 lets x264 choose. Frametypes: I,i,P,B,b.\n"
379         "                              QPs are restricted by qpmin/qpmax.\n" );
380     H1( "\n" );
381     H1( "Analysis:\n" );
382     H1( "\n" );
383     H1( "  -A, --partitions <string>   Partitions to consider [\"p8x8,b8x8,i8x8,i4x4\"]\n"
384         "                                  - p8x8, p4x4, b8x8, i8x8, i4x4\n"
385         "                                  - none, all\n"
386         "                                  (p4x4 requires p8x8. i8x8 requires --8x8dct.)\n" );
387     H1( "      --direct <string>       Direct MV prediction mode [\"%s\"]\n"
388         "                                  - none, spatial, temporal, auto\n",
389                                        strtable_lookup( x264_direct_pred_names, defaults->analyse.i_direct_mv_pred ) );
390     H2( "      --no-weightb            Disable weighted prediction for B-frames\n" );
391     H1( "      --weightp <integer>     Weighted prediction for P-frames [%d]\n"
392         "                                  - 0: Disabled\n"
393         "                                  - 1: Blind offset\n"
394         "                                  - 2: Smart analysis\n", defaults->analyse.i_weighted_pred );
395     H1( "      --me <string>           Integer pixel motion estimation method [\"%s\"]\n",
396                                        strtable_lookup( x264_motion_est_names, defaults->analyse.i_me_method ) );
397     H2( "                                  - dia: diamond search, radius 1 (fast)\n"
398         "                                  - hex: hexagonal search, radius 2\n"
399         "                                  - umh: uneven multi-hexagon search\n"
400         "                                  - esa: exhaustive search\n"
401         "                                  - tesa: hadamard exhaustive search (slow)\n" );
402     else H1( "                                  - dia, hex, umh\n" );
403     H2( "      --merange <integer>     Maximum motion vector search range [%d]\n", defaults->analyse.i_me_range );
404     H2( "      --mvrange <integer>     Maximum motion vector length [-1 (auto)]\n" );
405     H2( "      --mvrange-thread <int>  Minimum buffer between threads [-1 (auto)]\n" );
406     H1( "  -m, --subme <integer>       Subpixel motion estimation and mode decision [%d]\n", defaults->analyse.i_subpel_refine );
407     H2( "                                  - 0: fullpel only (not recommended)\n"
408         "                                  - 1: SAD mode decision, one qpel iteration\n"
409         "                                  - 2: SATD mode decision\n"
410         "                                  - 3-5: Progressively more qpel\n"
411         "                                  - 6: RD mode decision for I/P-frames\n"
412         "                                  - 7: RD mode decision for all frames\n"
413         "                                  - 8: RD refinement for I/P-frames\n"
414         "                                  - 9: RD refinement for all frames\n"
415         "                                  - 10: QP-RD - requires trellis=2, aq-mode>0\n" );
416     else H1( "                                  decision quality: 1=fast, 10=best.\n"  );
417     H1( "      --psy-rd                Strength of psychovisual optimization [\"%.1f:%.1f\"]\n"
418         "                                  #1: RD (requires subme>=6)\n"
419         "                                  #2: Trellis (requires trellis, experimental)\n",
420                                        defaults->analyse.f_psy_rd, defaults->analyse.f_psy_trellis );
421     H2( "      --no-psy                Disable all visual optimizations that worsen\n"
422         "                              both PSNR and SSIM.\n" );
423     H2( "      --no-mixed-refs         Don't decide references on a per partition basis\n" );
424     H2( "      --no-chroma-me          Ignore chroma in motion estimation\n" );
425     H1( "      --no-8x8dct             Disable adaptive spatial transform size\n" );
426     H1( "  -t, --trellis <integer>     Trellis RD quantization. Requires CABAC. [%d]\n"
427         "                                  - 0: disabled\n"
428         "                                  - 1: enabled only on the final encode of a MB\n"
429         "                                  - 2: enabled on all mode decisions\n", defaults->analyse.i_trellis );
430     H2( "      --no-fast-pskip         Disables early SKIP detection on P-frames\n" );
431     H2( "      --no-dct-decimate       Disables coefficient thresholding on P-frames\n" );
432     H1( "      --nr <integer>          Noise reduction [%d]\n", defaults->analyse.i_noise_reduction );
433     H2( "\n" );
434     H2( "      --deadzone-inter <int>  Set the size of the inter luma quantization deadzone [%d]\n", defaults->analyse.i_luma_deadzone[0] );
435     H2( "      --deadzone-intra <int>  Set the size of the intra luma quantization deadzone [%d]\n", defaults->analyse.i_luma_deadzone[1] );
436     H2( "                                  Deadzones should be in the range 0 - 32.\n" );
437     H2( "      --cqm <string>          Preset quant matrices [\"flat\"]\n"
438         "                                  - jvt, flat\n" );
439     H1( "      --cqmfile <string>      Read custom quant matrices from a JM-compatible file\n" );
440     H2( "                                  Overrides any other --cqm* options.\n" );
441     H2( "      --cqm4 <list>           Set all 4x4 quant matrices\n"
442         "                                  Takes a comma-separated list of 16 integers.\n" );
443     H2( "      --cqm8 <list>           Set all 8x8 quant matrices\n"
444         "                                  Takes a comma-separated list of 64 integers.\n" );
445     H2( "      --cqm4i, --cqm4p, --cqm8i, --cqm8p\n"
446         "                              Set both luma and chroma quant matrices\n" );
447     H2( "      --cqm4iy, --cqm4ic, --cqm4py, --cqm4pc\n"
448         "                              Set individual quant matrices\n" );
449     H2( "\n" );
450     H2( "Video Usability Info (Annex E):\n" );
451     H2( "The VUI settings are not used by the encoder but are merely suggestions to\n" );
452     H2( "the playback equipment. See doc/vui.txt for details. Use at your own risk.\n" );
453     H2( "\n" );
454     H2( "      --overscan <string>     Specify crop overscan setting [\"%s\"]\n"
455         "                                  - undef, show, crop\n",
456                                        strtable_lookup( x264_overscan_names, defaults->vui.i_overscan ) );
457     H2( "      --videoformat <string>  Specify video format [\"%s\"]\n"
458         "                                  - component, pal, ntsc, secam, mac, undef\n",
459                                        strtable_lookup( x264_vidformat_names, defaults->vui.i_vidformat ) );
460     H2( "      --fullrange <string>    Specify full range samples setting [\"%s\"]\n"
461         "                                  - off, on\n",
462                                        strtable_lookup( x264_fullrange_names, defaults->vui.b_fullrange ) );
463     H2( "      --colorprim <string>    Specify color primaries [\"%s\"]\n"
464         "                                  - undef, bt709, bt470m, bt470bg\n"
465         "                                    smpte170m, smpte240m, film\n",
466                                        strtable_lookup( x264_colorprim_names, defaults->vui.i_colorprim ) );
467     H2( "      --transfer <string>     Specify transfer characteristics [\"%s\"]\n"
468         "                                  - undef, bt709, bt470m, bt470bg, linear,\n"
469         "                                    log100, log316, smpte170m, smpte240m\n",
470                                        strtable_lookup( x264_transfer_names, defaults->vui.i_transfer ) );
471     H2( "      --colormatrix <string>  Specify color matrix setting [\"%s\"]\n"
472         "                                  - undef, bt709, fcc, bt470bg\n"
473         "                                    smpte170m, smpte240m, GBR, YCgCo\n",
474                                        strtable_lookup( x264_colmatrix_names, defaults->vui.i_colmatrix ) );
475     H2( "      --chromaloc <integer>   Specify chroma sample location (0 to 5) [%d]\n",
476                                        defaults->vui.i_chroma_loc );
477     H0( "\n" );
478     H0( "Input/Output:\n" );
479     H0( "\n" );
480     H0( "  -o, --output                Specify output file\n" );
481     H1( "      --muxer <string>        Specify output container format [\"%s\"]\n"
482         "                                  - %s\n", muxer_names[0], stringify_names( buf, muxer_names ) );
483     H1( "      --demuxer <string>      Specify input container format [\"%s\"]\n"
484         "                                  - %s\n", demuxer_names[0], stringify_names( buf, demuxer_names ) );
485     H1( "      --index <string>        Filename for input index file\n" );
486     H0( "      --sar width:height      Specify Sample Aspect Ratio\n" );
487     H0( "      --fps <float|rational>  Specify framerate\n" );
488     H0( "      --seek <integer>        First frame to encode\n" );
489     H0( "      --frames <integer>      Maximum number of frames to encode\n" );
490     H0( "      --level <string>        Specify level (as defined by Annex A)\n" );
491     H1( "\n" );
492     H1( "  -v, --verbose               Print stats for each frame\n" );
493     H1( "      --no-progress           Don't show the progress indicator while encoding\n" );
494     H0( "      --quiet                 Quiet Mode\n" );
495     H1( "      --psnr                  Enable PSNR computation\n" );
496     H1( "      --ssim                  Enable SSIM computation\n" );
497     H1( "      --threads <integer>     Force a specific number of threads\n" );
498     H2( "      --sliced-threads        Low-latency but lower-efficiency threading\n" );
499     H2( "      --thread-input          Run Avisynth in its own thread\n" );
500     H2( "      --sync-lookahead <integer> Number of buffer frames for threaded lookahead\n" );
501     H2( "      --non-deterministic     Slightly improve quality of SMP, at the cost of repeatability\n" );
502     H2( "      --asm <integer>         Override CPU detection\n" );
503     H2( "      --no-asm                Disable all CPU optimizations\n" );
504     H2( "      --visualize             Show MB types overlayed on the encoded video\n" );
505     H2( "      --dump-yuv <string>     Save reconstructed frames\n" );
506     H2( "      --sps-id <integer>      Set SPS and PPS id numbers [%d]\n", defaults->i_sps_id );
507     H2( "      --aud                   Use access unit delimiters\n" );
508     H2( "      --force-cfr             Force constant framerate timestamp generation\n" );
509     H0( "\n" );
510 }
511
512 #define OPT_FRAMES 256
513 #define OPT_SEEK 257
514 #define OPT_QPFILE 258
515 #define OPT_THREAD_INPUT 259
516 #define OPT_QUIET 260
517 #define OPT_NOPROGRESS 261
518 #define OPT_VISUALIZE 262
519 #define OPT_LONGHELP 263
520 #define OPT_PROFILE 264
521 #define OPT_PRESET 265
522 #define OPT_TUNE 266
523 #define OPT_SLOWFIRSTPASS 267
524 #define OPT_FULLHELP 268
525 #define OPT_FPS 269
526 #define OPT_MUXER 270
527 #define OPT_DEMUXER 271
528 #define OPT_INDEX 272
529 #define OPT_INTERLACED 273
530
531 static char short_options[] = "8A:B:b:f:hI:i:m:o:p:q:r:t:Vvw";
532 static struct option long_options[] =
533 {
534     { "help",              no_argument, NULL, 'h' },
535     { "longhelp",          no_argument, NULL, OPT_LONGHELP },
536     { "fullhelp",          no_argument, NULL, OPT_FULLHELP },
537     { "version",           no_argument, NULL, 'V' },
538     { "profile",     required_argument, NULL, OPT_PROFILE },
539     { "preset",      required_argument, NULL, OPT_PRESET },
540     { "tune",        required_argument, NULL, OPT_TUNE },
541     { "slow-firstpass",    no_argument, NULL, OPT_SLOWFIRSTPASS },
542     { "bitrate",     required_argument, NULL, 'B' },
543     { "bframes",     required_argument, NULL, 'b' },
544     { "b-adapt",     required_argument, NULL, 0 },
545     { "no-b-adapt",        no_argument, NULL, 0 },
546     { "b-bias",      required_argument, NULL, 0 },
547     { "b-pyramid",   required_argument, NULL, 0 },
548     { "min-keyint",  required_argument, NULL, 'i' },
549     { "keyint",      required_argument, NULL, 'I' },
550     { "intra-refresh",     no_argument, NULL, 0 },
551     { "scenecut",    required_argument, NULL, 0 },
552     { "no-scenecut",       no_argument, NULL, 0 },
553     { "nf",                no_argument, NULL, 0 },
554     { "no-deblock",        no_argument, NULL, 0 },
555     { "filter",      required_argument, NULL, 0 },
556     { "deblock",     required_argument, NULL, 'f' },
557     { "interlaced",        no_argument, NULL, OPT_INTERLACED },
558     { "no-interlaced",     no_argument, NULL, OPT_INTERLACED },
559     { "constrained-intra", no_argument, NULL, 0 },
560     { "cabac",             no_argument, NULL, 0 },
561     { "no-cabac",          no_argument, NULL, 0 },
562     { "qp",          required_argument, NULL, 'q' },
563     { "qpmin",       required_argument, NULL, 0 },
564     { "qpmax",       required_argument, NULL, 0 },
565     { "qpstep",      required_argument, NULL, 0 },
566     { "crf",         required_argument, NULL, 0 },
567     { "rc-lookahead",required_argument, NULL, 0 },
568     { "ref",         required_argument, NULL, 'r' },
569     { "asm",         required_argument, NULL, 0 },
570     { "no-asm",            no_argument, NULL, 0 },
571     { "sar",         required_argument, NULL, 0 },
572     { "fps",         required_argument, NULL, OPT_FPS },
573     { "frames",      required_argument, NULL, OPT_FRAMES },
574     { "seek",        required_argument, NULL, OPT_SEEK },
575     { "output",      required_argument, NULL, 'o' },
576     { "muxer",       required_argument, NULL, OPT_MUXER },
577     { "demuxer",     required_argument, NULL, OPT_DEMUXER },
578     { "stdout",      required_argument, NULL, OPT_MUXER },
579     { "stdin",       required_argument, NULL, OPT_DEMUXER },
580     { "index",       required_argument, NULL, OPT_INDEX },
581     { "analyse",     required_argument, NULL, 0 },
582     { "partitions",  required_argument, NULL, 'A' },
583     { "direct",      required_argument, NULL, 0 },
584     { "weightb",           no_argument, NULL, 'w' },
585     { "no-weightb",        no_argument, NULL, 0 },
586     { "weightp",     required_argument, NULL, 0 },
587     { "me",          required_argument, NULL, 0 },
588     { "merange",     required_argument, NULL, 0 },
589     { "mvrange",     required_argument, NULL, 0 },
590     { "mvrange-thread", required_argument, NULL, 0 },
591     { "subme",       required_argument, NULL, 'm' },
592     { "psy-rd",      required_argument, NULL, 0 },
593     { "no-psy",            no_argument, NULL, 0 },
594     { "psy",               no_argument, NULL, 0 },
595     { "mixed-refs",        no_argument, NULL, 0 },
596     { "no-mixed-refs",     no_argument, NULL, 0 },
597     { "no-chroma-me",      no_argument, NULL, 0 },
598     { "8x8dct",            no_argument, NULL, 0 },
599     { "no-8x8dct",         no_argument, NULL, 0 },
600     { "trellis",     required_argument, NULL, 't' },
601     { "fast-pskip",        no_argument, NULL, 0 },
602     { "no-fast-pskip",     no_argument, NULL, 0 },
603     { "no-dct-decimate",   no_argument, NULL, 0 },
604     { "aq-strength", required_argument, NULL, 0 },
605     { "aq-mode",     required_argument, NULL, 0 },
606     { "deadzone-inter", required_argument, NULL, '0' },
607     { "deadzone-intra", required_argument, NULL, '0' },
608     { "level",       required_argument, NULL, 0 },
609     { "ratetol",     required_argument, NULL, 0 },
610     { "vbv-maxrate", required_argument, NULL, 0 },
611     { "vbv-bufsize", required_argument, NULL, 0 },
612     { "vbv-init",    required_argument, NULL,  0 },
613     { "ipratio",     required_argument, NULL, 0 },
614     { "pbratio",     required_argument, NULL, 0 },
615     { "chroma-qp-offset", required_argument, NULL, 0 },
616     { "pass",        required_argument, NULL, 'p' },
617     { "stats",       required_argument, NULL, 0 },
618     { "qcomp",       required_argument, NULL, 0 },
619     { "mbtree",            no_argument, NULL, 0 },
620     { "no-mbtree",         no_argument, NULL, 0 },
621     { "qblur",       required_argument, NULL, 0 },
622     { "cplxblur",    required_argument, NULL, 0 },
623     { "zones",       required_argument, NULL, 0 },
624     { "qpfile",      required_argument, NULL, OPT_QPFILE },
625     { "threads",     required_argument, NULL, 0 },
626     { "sliced-threads",    no_argument, NULL, 0 },
627     { "no-sliced-threads", no_argument, NULL, 0 },
628     { "slice-max-size",    required_argument, NULL, 0 },
629     { "slice-max-mbs",     required_argument, NULL, 0 },
630     { "slices",            required_argument, NULL, 0 },
631     { "thread-input",      no_argument, NULL, OPT_THREAD_INPUT },
632     { "sync-lookahead",    required_argument, NULL, 0 },
633     { "non-deterministic", no_argument, NULL, 0 },
634     { "psnr",              no_argument, NULL, 0 },
635     { "ssim",              no_argument, NULL, 0 },
636     { "quiet",             no_argument, NULL, OPT_QUIET },
637     { "verbose",           no_argument, NULL, 'v' },
638     { "no-progress",       no_argument, NULL, OPT_NOPROGRESS },
639     { "visualize",         no_argument, NULL, OPT_VISUALIZE },
640     { "dump-yuv",    required_argument, NULL, 0 },
641     { "sps-id",      required_argument, NULL, 0 },
642     { "aud",               no_argument, NULL, 0 },
643     { "nr",          required_argument, NULL, 0 },
644     { "cqm",         required_argument, NULL, 0 },
645     { "cqmfile",     required_argument, NULL, 0 },
646     { "cqm4",        required_argument, NULL, 0 },
647     { "cqm4i",       required_argument, NULL, 0 },
648     { "cqm4iy",      required_argument, NULL, 0 },
649     { "cqm4ic",      required_argument, NULL, 0 },
650     { "cqm4p",       required_argument, NULL, 0 },
651     { "cqm4py",      required_argument, NULL, 0 },
652     { "cqm4pc",      required_argument, NULL, 0 },
653     { "cqm8",        required_argument, NULL, 0 },
654     { "cqm8i",       required_argument, NULL, 0 },
655     { "cqm8p",       required_argument, NULL, 0 },
656     { "overscan",    required_argument, NULL, 0 },
657     { "videoformat", required_argument, NULL, 0 },
658     { "fullrange",   required_argument, NULL, 0 },
659     { "colorprim",   required_argument, NULL, 0 },
660     { "transfer",    required_argument, NULL, 0 },
661     { "colormatrix", required_argument, NULL, 0 },
662     { "chromaloc",   required_argument, NULL, 0 },
663     { "force-cfr",         no_argument, NULL, 0 },
664     {0, 0, 0, 0}
665 };
666
667 static int select_output( const char *muxer, char *filename, x264_param_t *param )
668 {
669     const char *ext = get_filename_extension( filename );
670     if( !strcmp( filename, "-" ) || strcasecmp( muxer, "auto" ) )
671         ext = muxer;
672
673     if( !strcasecmp( ext, "mp4" ) )
674     {
675 #ifdef MP4_OUTPUT
676         output = mp4_output;
677         param->b_annexb = 0;
678         param->b_aud = 0;
679         param->b_dts_compress = 0;
680         param->b_repeat_headers = 0;
681 #else
682         fprintf( stderr, "x264 [error]: not compiled with MP4 output support\n" );
683         return -1;
684 #endif
685     }
686     else if( !strcasecmp( ext, "mkv" ) )
687     {
688         output = mkv_output;
689         param->b_annexb = 0;
690         param->b_aud = 0;
691         param->b_dts_compress = 0;
692         param->b_repeat_headers = 0;
693     }
694     else if( !strcasecmp( ext, "flv" ) )
695     {
696         output = flv_output;
697         param->b_annexb = 0;
698         param->b_aud = 0;
699         param->b_dts_compress = 1;
700         param->b_repeat_headers = 0;
701     }
702     else
703         output = raw_output;
704     return 0;
705 }
706
707 static int select_input( const char *demuxer, char *used_demuxer, char *filename,
708                          hnd_t *p_handle, video_info_t *info, cli_input_opt_t *opt )
709 {
710     const char *ext = get_filename_extension( filename );
711     int b_regular = strcmp( filename, "-" );
712     int b_auto = !strcasecmp( demuxer, "auto" );
713     if( !b_regular && b_auto )
714         ext = "yuv";
715     if( b_regular )
716     {
717         FILE *f = fopen( filename, "r" );
718         if( f )
719         {
720             b_regular = x264_is_regular_file( f );
721             fclose( f );
722         }
723     }
724     const char *module = b_auto ? ext : demuxer;
725
726     if( !strcasecmp( module, "avs" ) || !strcasecmp( ext, "d2v" ) || !strcasecmp( ext, "dga" ) )
727     {
728 #ifdef AVS_INPUT
729         input = avs_input;
730         module = "avs";
731 #else
732         fprintf( stderr, "x264 [error]: not compiled with AVS input support\n" );
733         return -1;
734 #endif
735     }
736     else if( !strcasecmp( module, "y4m" ) )
737         input = y4m_input;
738     else if( !strcasecmp( module, "yuv" ) )
739         input = yuv_input;
740     else
741     {
742 #ifdef FFMS_INPUT
743         if( b_regular && (b_auto || !strcasecmp( demuxer, "ffms" )) &&
744             !ffms_input.open_file( filename, p_handle, info, opt ) )
745         {
746             module = "ffms";
747             b_auto = 0;
748             input = ffms_input;
749         }
750 #endif
751 #ifdef LAVF_INPUT
752         if( (b_auto || !strcasecmp( demuxer, "lavf" )) &&
753             !lavf_input.open_file( filename, p_handle, info, opt ) )
754         {
755             module = "lavf";
756             b_auto = 0;
757             input = lavf_input;
758         }
759 #endif
760 #ifdef AVS_INPUT
761         if( b_regular && (b_auto || !strcasecmp( demuxer, "avs" )) &&
762             !avs_input.open_file( filename, p_handle, info, opt ) )
763         {
764             module = "avs";
765             b_auto = 0;
766             input = avs_input;
767         }
768 #endif
769         if( b_auto && !yuv_input.open_file( filename, p_handle, info, opt ) )
770         {
771             module = "yuv";
772             b_auto = 0;
773             input = yuv_input;
774         }
775
776         if( !(*p_handle) )
777         {
778             fprintf( stderr, "x264 [error]: could not open input file `%s' via any method!\n", filename );
779             return -1;
780         }
781     }
782     strcpy( used_demuxer, module );
783
784     return 0;
785 }
786
787 /*****************************************************************************
788  * Parse:
789  *****************************************************************************/
790 static int Parse( int argc, char **argv, x264_param_t *param, cli_opt_t *opt )
791 {
792     char *input_filename = NULL;
793     const char *demuxer = demuxer_names[0];
794     char *output_filename = NULL;
795     const char *muxer = muxer_names[0];
796     x264_param_t defaults;
797     char *profile = NULL;
798     int b_thread_input = 0;
799     int b_turbo = 1;
800     int b_user_ref = 0;
801     int b_user_fps = 0;
802     int b_user_interlaced = 0;
803     int i;
804     cli_input_opt_t input_opt;
805     char *preset = NULL;
806     char *tune = NULL;
807
808     x264_param_default( &defaults );
809
810     memset( opt, 0, sizeof(cli_opt_t) );
811     memset( &input_opt, 0, sizeof(cli_input_opt_t) );
812     opt->b_progress = 1;
813
814     /* Presets are applied before all other options. */
815     for( optind = 0;; )
816     {
817         int c = getopt_long( argc, argv, short_options, long_options, NULL );
818         if( c == -1 )
819             break;
820         if( c == OPT_PRESET )
821             preset = optarg;
822         if( c == OPT_TUNE )
823             tune = optarg;
824         else if( c == '?' )
825             return -1;
826     }
827
828     if( preset && !strcasecmp( preset, "placebo" ) )
829         b_turbo = 0;
830
831     if( x264_param_default_preset( param, preset, tune ) < 0 )
832         return -1;
833
834     /* Parse command line options */
835     for( optind = 0;; )
836     {
837         int b_error = 0;
838         int long_options_index = -1;
839
840         int c = getopt_long( argc, argv, short_options, long_options, &long_options_index );
841
842         if( c == -1 )
843         {
844             break;
845         }
846
847         switch( c )
848         {
849             case 'h':
850                 Help( &defaults, 0 );
851                 exit(0);
852             case OPT_LONGHELP:
853                 Help( &defaults, 1 );
854                 exit(0);
855             case OPT_FULLHELP:
856                 Help( &defaults, 2 );
857                 exit(0);
858             case 'V':
859 #ifdef X264_POINTVER
860                 printf( "x264 "X264_POINTVER"\n" );
861 #else
862                 printf( "x264 0.%d.X\n", X264_BUILD );
863 #endif
864                 printf( "built on " __DATE__ ", " );
865 #ifdef __GNUC__
866                 printf( "gcc: " __VERSION__ "\n" );
867 #else
868                 printf( "using a non-gcc compiler\n" );
869 #endif
870                 exit(0);
871             case OPT_FRAMES:
872                 param->i_frame_total = X264_MAX( atoi( optarg ), 0 );
873                 break;
874             case OPT_SEEK:
875                 opt->i_seek = input_opt.seek = X264_MAX( atoi( optarg ), 0 );
876                 break;
877             case 'o':
878                 output_filename = optarg;
879                 break;
880             case OPT_MUXER:
881                 for( i = 0; muxer_names[i] && strcasecmp( muxer_names[i], optarg ); )
882                     i++;
883                 if( !muxer_names[i] )
884                 {
885                     fprintf( stderr, "x264 [error]: invalid muxer '%s'\n", optarg );
886                     return -1;
887                 }
888                 muxer = optarg;
889                 break;
890             case OPT_DEMUXER:
891                 for( i = 0; demuxer_names[i] && strcasecmp( demuxer_names[i], optarg ); )
892                     i++;
893                 if( !demuxer_names[i] )
894                 {
895                     fprintf( stderr, "x264 [error]: invalid demuxer '%s'\n", optarg );
896                     return -1;
897                 }
898                 demuxer = optarg;
899                 break;
900             case OPT_INDEX:
901                 input_opt.index = optarg;
902                 break;
903             case OPT_QPFILE:
904                 opt->qpfile = fopen( optarg, "rb" );
905                 if( !opt->qpfile )
906                 {
907                     fprintf( stderr, "x264 [error]: can't open qpfile `%s'\n", optarg );
908                     return -1;
909                 }
910                 else if( !x264_is_regular_file( opt->qpfile ) )
911                 {
912                     fprintf( stderr, "x264 [error]: qpfile incompatible with non-regular file `%s'\n", optarg );
913                     fclose( opt->qpfile );
914                     return -1;
915                 }
916                 break;
917             case OPT_THREAD_INPUT:
918                 b_thread_input = 1;
919                 break;
920             case OPT_QUIET:
921                 param->i_log_level = X264_LOG_NONE;
922                 break;
923             case 'v':
924                 param->i_log_level = X264_LOG_DEBUG;
925                 break;
926             case OPT_NOPROGRESS:
927                 opt->b_progress = 0;
928                 break;
929             case OPT_VISUALIZE:
930 #ifdef VISUALIZE
931                 param->b_visualize = 1;
932                 b_exit_on_ctrl_c = 1;
933 #else
934                 fprintf( stderr, "x264 [warning]: not compiled with visualization support\n" );
935 #endif
936                 break;
937             case OPT_TUNE:
938             case OPT_PRESET:
939                 break;
940             case OPT_PROFILE:
941                 profile = optarg;
942                 break;
943             case OPT_SLOWFIRSTPASS:
944                 b_turbo = 0;
945                 break;
946             case 'r':
947                 b_user_ref = 1;
948                 goto generic_option;
949             case OPT_FPS:
950                 b_user_fps = 1;
951                 param->b_vfr_input = 0;
952                 goto generic_option;
953             case OPT_INTERLACED:
954                 b_user_interlaced = 1;
955                 goto generic_option;
956             default:
957 generic_option:
958             {
959                 int i;
960                 if( long_options_index < 0 )
961                 {
962                     for( i = 0; long_options[i].name; i++ )
963                         if( long_options[i].val == c )
964                         {
965                             long_options_index = i;
966                             break;
967                         }
968                     if( long_options_index < 0 )
969                     {
970                         /* getopt_long already printed an error message */
971                         return -1;
972                     }
973                 }
974
975                 b_error |= x264_param_parse( param, long_options[long_options_index].name, optarg );
976             }
977         }
978
979         if( b_error )
980         {
981             const char *name = long_options_index > 0 ? long_options[long_options_index].name : argv[optind-2];
982             fprintf( stderr, "x264 [error]: invalid argument: %s = %s\n", name, optarg );
983             return -1;
984         }
985     }
986
987     /* If first pass mode is used, apply faster settings. */
988     if( b_turbo )
989         x264_param_apply_fastfirstpass( param );
990
991     /* Apply profile restrictions. */
992     if( x264_param_apply_profile( param, profile ) < 0 )
993         return -1;
994
995     /* Get the file name */
996     if( optind > argc - 1 || !output_filename )
997     {
998         fprintf( stderr, "x264 [error]: No %s file. Run x264 --help for a list of options.\n",
999                  optind > argc - 1 ? "input" : "output" );
1000         return -1;
1001     }
1002
1003     if( select_output( muxer, output_filename, param ) )
1004         return -1;
1005     if( output.open_file( output_filename, &opt->hout ) )
1006     {
1007         fprintf( stderr, "x264 [error]: could not open output file `%s'\n", output_filename );
1008         return -1;
1009     }
1010
1011     input_filename = argv[optind++];
1012     input_opt.resolution = optind < argc ? argv[optind++] : NULL;
1013     video_info_t info = {0};
1014     char demuxername[5];
1015
1016     /* set info flags to param flags to be overwritten by demuxer as necessary. */
1017     info.csp        = param->i_csp;
1018     info.fps_num    = param->i_fps_num;
1019     info.fps_den    = param->i_fps_den;
1020     info.interlaced = param->b_interlaced;
1021     info.sar_width  = param->vui.i_sar_width;
1022     info.sar_height = param->vui.i_sar_height;
1023     info.vfr        = param->b_vfr_input;
1024
1025     if( select_input( demuxer, demuxername, input_filename, &opt->hin, &info, &input_opt ) )
1026         return -1;
1027
1028     if( !opt->hin && input.open_file( input_filename, &opt->hin, &info, &input_opt ) )
1029     {
1030         fprintf( stderr, "x264 [error]: could not open input file `%s'\n", input_filename );
1031         return -1;
1032     }
1033
1034     x264_reduce_fraction( &info.sar_width, &info.sar_height );
1035     x264_reduce_fraction( &info.fps_num, &info.fps_den );
1036     if( param->i_log_level >= X264_LOG_INFO )
1037         fprintf( stderr, "%s [info]: %dx%d%c %d:%d @ %d/%d fps (%cfr)\n", demuxername, info.width,
1038                  info.height, info.interlaced ? 'i' : 'p', info.sar_width, info.sar_height,
1039                  info.fps_num, info.fps_den, info.vfr ? 'v' : 'c' );
1040
1041     /* set param flags from the info flags as necessary */
1042     param->i_csp       = info.csp;
1043     param->i_height    = info.height;
1044     param->b_vfr_input = info.vfr;
1045     param->i_width     = info.width;
1046     if( !b_user_interlaced && info.interlaced )
1047     {
1048         fprintf( stderr, "x264 [warning]: input appears to be interlaced, enabling interlaced mode.\n"
1049                          "                If you want otherwise, use --no-interlaced\n" );
1050         param->b_interlaced = 1;
1051     }
1052     if( !b_user_fps )
1053     {
1054         param->i_fps_num = info.fps_num;
1055         param->i_fps_den = info.fps_den;
1056     }
1057     if( param->b_vfr_input )
1058     {
1059         param->i_timebase_num = info.timebase_num;
1060         param->i_timebase_den = info.timebase_den;
1061     }
1062     else
1063     {
1064         param->i_timebase_den = param->i_fps_num;
1065         param->i_timebase_num = param->i_fps_den;
1066     }
1067     if( !param->vui.i_sar_width || !param->vui.i_sar_height )
1068     {
1069         param->vui.i_sar_width  = info.sar_width;
1070         param->vui.i_sar_height = info.sar_height;
1071     }
1072
1073 #ifdef HAVE_PTHREAD
1074     if( b_thread_input || param->i_threads > 1
1075         || (param->i_threads == X264_THREADS_AUTO && x264_cpu_num_processors() > 1) )
1076     {
1077         if( thread_input.open_file( NULL, &opt->hin, &info, NULL ) )
1078         {
1079             fprintf( stderr, "x264 [error]: threaded input failed\n" );
1080             return -1;
1081         }
1082         else
1083             input = thread_input;
1084     }
1085 #endif
1086
1087
1088     /* Automatically reduce reference frame count to match the user's target level
1089      * if the user didn't explicitly set a reference frame count. */
1090     if( !b_user_ref )
1091     {
1092         int mbs = (((param->i_width)+15)>>4) * (((param->i_height)+15)>>4);
1093         int i;
1094         for( i = 0; x264_levels[i].level_idc != 0; i++ )
1095             if( param->i_level_idc == x264_levels[i].level_idc )
1096             {
1097                 while( mbs * 384 * param->i_frame_reference > x264_levels[i].dpb
1098                        && param->i_frame_reference > 1 )
1099                 {
1100                     param->i_frame_reference--;
1101                 }
1102                 break;
1103             }
1104     }
1105
1106
1107     return 0;
1108 }
1109
1110 static void parse_qpfile( cli_opt_t *opt, x264_picture_t *pic, int i_frame )
1111 {
1112     int num = -1, qp, ret;
1113     char type;
1114     uint64_t file_pos;
1115     while( num < i_frame )
1116     {
1117         file_pos = ftell( opt->qpfile );
1118         ret = fscanf( opt->qpfile, "%d %c %d\n", &num, &type, &qp );
1119         if( num > i_frame || ret == EOF )
1120         {
1121             pic->i_type = X264_TYPE_AUTO;
1122             pic->i_qpplus1 = 0;
1123             fseek( opt->qpfile, file_pos, SEEK_SET );
1124             break;
1125         }
1126         if( num < i_frame && ret == 3 )
1127             continue;
1128         pic->i_qpplus1 = qp+1;
1129         if     ( type == 'I' ) pic->i_type = X264_TYPE_IDR;
1130         else if( type == 'i' ) pic->i_type = X264_TYPE_I;
1131         else if( type == 'P' ) pic->i_type = X264_TYPE_P;
1132         else if( type == 'B' ) pic->i_type = X264_TYPE_BREF;
1133         else if( type == 'b' ) pic->i_type = X264_TYPE_B;
1134         else ret = 0;
1135         if( ret != 3 || qp < -1 || qp > 51 )
1136         {
1137             fprintf( stderr, "x264 [error]: can't parse qpfile for frame %d\n", i_frame );
1138             fclose( opt->qpfile );
1139             opt->qpfile = NULL;
1140             pic->i_type = X264_TYPE_AUTO;
1141             pic->i_qpplus1 = 0;
1142             break;
1143         }
1144     }
1145 }
1146
1147 /*****************************************************************************
1148  * Encode:
1149  *****************************************************************************/
1150
1151 static int  Encode_frame( x264_t *h, hnd_t hout, x264_picture_t *pic, int64_t *last_pts )
1152 {
1153     x264_picture_t pic_out;
1154     x264_nal_t *nal;
1155     int i_nal;
1156     int i_frame_size = 0;
1157
1158     i_frame_size = x264_encoder_encode( h, &nal, &i_nal, pic, &pic_out );
1159
1160     if( i_frame_size < 0 )
1161     {
1162         fprintf( stderr, "x264 [error]: x264_encoder_encode failed\n" );
1163         return -1;
1164     }
1165
1166     if( i_frame_size )
1167     {
1168         i_frame_size = output.write_frame( hout, nal[0].p_payload, i_frame_size, &pic_out );
1169         *last_pts = pic_out.i_pts;
1170     }
1171
1172     return i_frame_size;
1173 }
1174
1175 static void Print_status( int64_t i_start, int i_frame, int i_frame_total, int64_t i_file, x264_param_t *param, int64_t last_pts )
1176 {
1177     char    buf[200];
1178     int64_t i_elapsed = x264_mdate() - i_start;
1179     double fps = i_elapsed > 0 ? i_frame * 1000000. / i_elapsed : 0;
1180     double bitrate = (double) i_file * 8 / ( (double) last_pts * 1000 * param->i_timebase_num / param->i_timebase_den );
1181     if( i_frame_total )
1182     {
1183         int eta = i_elapsed * (i_frame_total - i_frame) / ((int64_t)i_frame * 1000000);
1184         sprintf( buf, "x264 [%.1f%%] %d/%d frames, %.2f fps, %.2f kb/s, eta %d:%02d:%02d",
1185                  100. * i_frame / i_frame_total, i_frame, i_frame_total, fps, bitrate,
1186                  eta/3600, (eta/60)%60, eta%60 );
1187     }
1188     else
1189     {
1190         sprintf( buf, "x264 %d frames: %.2f fps, %.2f kb/s", i_frame, fps, bitrate );
1191     }
1192     fprintf( stderr, "%s  \r", buf+5 );
1193     SetConsoleTitle( buf );
1194     fflush( stderr ); // needed in windows
1195 }
1196
1197 static int  Encode( x264_param_t *param, cli_opt_t *opt )
1198 {
1199     x264_t *h;
1200     x264_picture_t pic;
1201
1202     int     i_frame, i_frame_total, i_frame_output;
1203     int64_t i_start, i_end;
1204     int64_t i_file = 0;
1205     int     i_frame_size;
1206     int     i_update_interval;
1207     int64_t last_pts = 0;
1208 #   define  MAX_PTS_WARNING 3 /* arbitrary */
1209     int     pts_warning_cnt = 0;
1210     int64_t largest_pts = -1;
1211     int64_t second_largest_pts = -1;
1212     int64_t ticks_per_frame;
1213     double  duration;
1214     int     prev_timebase_den = param->i_timebase_den / gcd( param->i_timebase_num, param->i_timebase_den );
1215     int     dts_compress_multiplier;
1216
1217     opt->b_progress &= param->i_log_level < X264_LOG_DEBUG;
1218     i_frame_total = input.get_frame_total( opt->hin );
1219     i_frame_total = X264_MAX( i_frame_total - opt->i_seek, 0 );
1220     if( ( i_frame_total == 0 || param->i_frame_total < i_frame_total )
1221         && param->i_frame_total > 0 )
1222         i_frame_total = param->i_frame_total;
1223     param->i_frame_total = i_frame_total;
1224     i_update_interval = i_frame_total ? x264_clip3( i_frame_total / 1000, 1, 10 ) : 10;
1225
1226     if( ( h = x264_encoder_open( param ) ) == NULL )
1227     {
1228         fprintf( stderr, "x264 [error]: x264_encoder_open failed\n" );
1229         input.close_file( opt->hin );
1230         return -1;
1231     }
1232
1233     x264_encoder_parameters( h, param );
1234
1235     dts_compress_multiplier = param->i_timebase_den / prev_timebase_den;
1236
1237     if( output.set_param( opt->hout, param ) )
1238     {
1239         fprintf( stderr, "x264 [error]: can't set outfile param\n" );
1240         input.close_file( opt->hin );
1241         output.close_file( opt->hout, largest_pts, second_largest_pts );
1242         return -1;
1243     }
1244
1245     /* Create a new pic */
1246     if( input.picture_alloc( &pic, param->i_csp, param->i_width, param->i_height ) )
1247     {
1248         fprintf( stderr, "x264 [error]: malloc failed\n" );
1249         return -1;
1250     }
1251
1252     i_start = x264_mdate();
1253     /* ticks/frame = ticks/second / frames/second */
1254     ticks_per_frame = (int64_t)param->i_timebase_den * param->i_fps_den / param->i_timebase_num / param->i_fps_num;
1255     if( ticks_per_frame < 1 )
1256     {
1257         fprintf( stderr, "x264 [error]: ticks_per_frame invalid: %"PRId64"\n", ticks_per_frame );
1258         return -1;
1259     }
1260
1261     if( !param->b_repeat_headers )
1262     {
1263         // Write SPS/PPS/SEI
1264         x264_nal_t *headers;
1265         int i_nal;
1266
1267         if( x264_encoder_headers( h, &headers, &i_nal ) < 0 )
1268         {
1269             fprintf( stderr, "x264 [error]: x264_encoder_headers failed\n" );
1270             return -1;
1271         }
1272
1273         if( (i_file = output.write_headers( opt->hout, headers )) < 0 )
1274             return -1;
1275     }
1276
1277     /* Encode frames */
1278     for( i_frame = 0, i_frame_output = 0; b_ctrl_c == 0 && (i_frame < i_frame_total || i_frame_total == 0); )
1279     {
1280         if( input.read_frame( &pic, opt->hin, i_frame + opt->i_seek ) )
1281             break;
1282
1283         if( !param->b_vfr_input )
1284             pic.i_pts = i_frame;
1285         if( pic.i_pts <= largest_pts )
1286         {
1287             if( param->i_log_level >= X264_LOG_WARNING )
1288             {
1289                 if( param->i_log_level >= X264_LOG_DEBUG || pts_warning_cnt < MAX_PTS_WARNING )
1290                     fprintf( stderr, "x264 [warning]: non-strictly-monotonic pts at frame %d (%"PRId64" <= %"PRId64")\n",
1291                              i_frame, pic.i_pts * dts_compress_multiplier, largest_pts * dts_compress_multiplier );
1292                 else if( pts_warning_cnt == MAX_PTS_WARNING )
1293                     fprintf( stderr, "x264 [warning]: too many nonmonotonic pts warnings, suppressing further ones\n" );
1294                 pts_warning_cnt++;
1295             }
1296             pic.i_pts = largest_pts + ticks_per_frame;
1297         }
1298         second_largest_pts = largest_pts;
1299         largest_pts = pic.i_pts;
1300
1301         if( opt->qpfile )
1302             parse_qpfile( opt, &pic, i_frame + opt->i_seek );
1303         else
1304         {
1305             /* Do not force any parameters */
1306             pic.i_type = X264_TYPE_AUTO;
1307             pic.i_qpplus1 = 0;
1308         }
1309
1310         i_frame_size = Encode_frame( h, opt->hout, &pic, &last_pts );
1311         if( i_frame_size < 0 )
1312             return -1;
1313         i_file += i_frame_size;
1314         if( i_frame_size )
1315             i_frame_output++;
1316
1317         i_frame++;
1318
1319         if( input.release_frame && input.release_frame( &pic, opt->hin ) )
1320             break;
1321
1322         /* update status line (up to 1000 times per input file) */
1323         if( opt->b_progress && i_frame_output % i_update_interval == 0 && i_frame_output )
1324             Print_status( i_start, i_frame_output, i_frame_total, i_file, param, last_pts );
1325     }
1326     /* Flush delayed frames */
1327     while( !b_ctrl_c && x264_encoder_delayed_frames( h ) )
1328     {
1329         i_frame_size = Encode_frame( h, opt->hout, NULL, &last_pts );
1330         if( i_frame_size < 0 )
1331             return -1;
1332         i_file += i_frame_size;
1333         if( i_frame_size )
1334             i_frame_output++;
1335         if( opt->b_progress && i_frame_output % i_update_interval == 0 && i_frame_output )
1336             Print_status( i_start, i_frame_output, i_frame_total, i_file, param, last_pts );
1337     }
1338     if( pts_warning_cnt >= MAX_PTS_WARNING && param->i_log_level < X264_LOG_DEBUG )
1339         fprintf( stderr, "x264 [warning]: %d suppressed nonmonotonic pts warnings\n", pts_warning_cnt-MAX_PTS_WARNING );
1340
1341     /* duration algorithm fails when only 1 frame is output */
1342     if( i_frame_output == 1 )
1343         duration = (double)param->i_fps_den / param->i_fps_num;
1344     else
1345         duration = (double)(2 * largest_pts - second_largest_pts) * param->i_timebase_num / param->i_timebase_den;
1346     duration *= dts_compress_multiplier;
1347
1348     i_end = x264_mdate();
1349     input.picture_clean( &pic );
1350     /* Erase progress indicator before printing encoding stats. */
1351     if( opt->b_progress )
1352         fprintf( stderr, "                                                                               \r" );
1353     x264_encoder_close( h );
1354     fprintf( stderr, "\n" );
1355
1356     if( b_ctrl_c )
1357         fprintf( stderr, "aborted at input frame %d, output frame %d\n", opt->i_seek + i_frame, i_frame_output );
1358
1359     input.close_file( opt->hin );
1360     output.close_file( opt->hout, largest_pts, second_largest_pts );
1361
1362     if( i_frame_output > 0 )
1363     {
1364         double fps = (double)i_frame_output * (double)1000000 /
1365                      (double)( i_end - i_start );
1366
1367         fprintf( stderr, "encoded %d frames, %.2f fps, %.2f kb/s\n", i_frame_output, fps,
1368                  (double) i_file * 8 / ( 1000 * duration ) );
1369     }
1370
1371     return 0;
1372 }