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