OSDN Git Service

Optimize MP4 files for HTTP streaming (on the CLI it's -O or --optimize).
[handbrake-jp/handbrake-jp-git.git] / test / test.c
1 /* $Id: test.c,v 1.82 2005/11/19 08:25:54 titer Exp $
2
3    This file is part of the HandBrake source code.
4    Homepage: <http://handbrake.m0k.org/>.
5    It may be used under the terms of the GNU General Public License. */
6
7 #include <signal.h>
8 #include <getopt.h>
9 #include <sys/time.h>
10 #include <time.h>
11 #include <unistd.h>
12
13 #include "hb.h"
14 #include "parsecsv.h"
15
16 /* Options */
17 static int    debug       = HB_DEBUG_NONE;
18 static int    update      = 0;
19 static char * input       = NULL;
20 static char * output      = NULL;
21 static char * format      = NULL;
22 static int    titleindex  = 1;
23 static int    longest_title = 0;
24 static int    subtitle_scan = 0;
25 static int    subtitle_force = 0;
26 static char * native_language = NULL;
27 static int    twoPass     = 0;
28 static int    deinterlace           = 0;
29 static char * deinterlace_opt       = 0;
30 static int    deblock               = 0;
31 static char * deblock_opt           = 0;
32 static int    denoise               = 0;
33 static char * denoise_opt           = 0;
34 static int    detelecine            = 0;
35 static char * detelecine_opt        = 0;
36 static int    grayscale   = 0;
37 static int    vcodec      = HB_VCODEC_FFMPEG;
38 static int    h264_13     = 0;
39 static int    h264_30     = 0;
40 static char * audios      = NULL;
41 static int    audio_mixdown = HB_AMIXDOWN_DOLBYPLII;
42 static int    sub         = 0;
43 static int    width       = 0;
44 static int    height      = 0;
45 static int    crop[4]     = { -1,-1,-1,-1 };
46 static int    cpu         = 0;
47 static int    vrate       = 0;
48 static int    arate       = 0;
49 static float  vquality    = -1.0;
50 static int    vbitrate    = 0;
51 static int    size        = 0;
52 static int    abitrate    = 0;
53 static int    mux         = 0;
54 static int    acodec      = 0;
55 static int    pixelratio  = 0;
56 static int    loosePixelratio = 0;
57 static int    modulus       = 0;
58 static int    chapter_start = 0;
59 static int    chapter_end   = 0;
60 static int    chapter_markers = 0;
61 static char * marker_file   = NULL;
62 static int        crf                   = 0;
63 static char       *x264opts             = NULL;
64 static char       *x264opts2    = NULL;
65 static int        maxHeight             = 0;
66 static int        maxWidth              = 0;
67 static int    turbo_opts_enabled = 0;
68 static char * turbo_opts = "ref=1:subme=1:me=dia:analyse=none:trellis=0:no-fast-pskip=0:8x8dct=0";
69 static int    largeFileSize = 0;
70 static int    preset        = 0;
71 static char * preset_name   = 0;
72 static int    vfr           = 0;
73 static int    mp4_optimize  = 0;
74
75 /* Exit cleanly on Ctrl-C */
76 static volatile int die = 0;
77 static void SigHandler( int );
78
79 /* Utils */
80 static void ShowCommands();
81 static void ShowHelp();
82 static void ShowPresets();
83
84 static int  ParseOptions( int argc, char ** argv );
85 static int  CheckOptions( int argc, char ** argv );
86 static int  HandleEvents( hb_handle_t * h );
87
88 /****************************************************************************
89  * hb_error_handler
90  * 
91  * When using the CLI just display using hb_log as we always did in the past
92  * make sure that we prefix with a nice ERROR message to catch peoples eyes.
93  ****************************************************************************/
94 static void hb_cli_error_handler ( const char *errmsg )
95 {
96     fprintf( stderr, "ERROR: %s", errmsg );
97 }
98
99 int main( int argc, char ** argv )
100 {
101     hb_handle_t * h;
102     int           build;
103     char        * version;
104
105     /* Parse command line */
106     if( ParseOptions( argc, argv ) ||
107         CheckOptions( argc, argv ) )
108     {
109         return 1;
110     }
111
112     /* Register our error handler */
113     hb_register_error_handler(&hb_cli_error_handler);
114
115     /* Init libhb */
116     h = hb_init( debug, update );
117
118     /* Show version */
119     fprintf( stderr, "HandBrake %s (%d) - http://handbrake.m0k.org/\n",
120              hb_get_version( h ), hb_get_build( h ) );
121
122     /* Check for update */
123     if( update )
124     {
125         if( ( build = hb_check_update( h, &version ) ) > -1 )
126         {
127             fprintf( stderr, "You are using an old version of "
128                      "HandBrake.\nLatest is %s (build %d).\n", version,
129                      build );
130         }
131         else
132         {
133             fprintf( stderr, "Your version of HandBrake is up to "
134                      "date.\n" );
135         }
136         hb_close( &h );
137         return 0;
138     }
139
140     /* Geeky */
141     fprintf( stderr, "%d CPU%s detected\n", hb_get_cpu_count(),
142              hb_get_cpu_count( h ) > 1 ? "s" : "" );
143     if( cpu )
144     {
145         fprintf( stderr, "Forcing %d CPU%s\n", cpu,
146                  cpu > 1 ? "s" : "" );
147         hb_set_cpu_count( h, cpu );
148     }
149
150     /* Exit ASAP on Ctrl-C */
151     signal( SIGINT, SigHandler );
152
153     /* Feed libhb with a DVD to scan */
154     fprintf( stderr, "Opening %s...\n", input );
155
156     if (longest_title) {
157         /*
158          * We need to scan for all the titles in order to find the longest
159          */
160         titleindex = 0;
161     }
162     hb_scan( h, input, titleindex );
163
164     /* Wait... */
165     while( !die )
166     {
167 #if !defined(SYS_BEOS)
168         fd_set         fds;
169         struct timeval tv;
170         int            ret;
171         char           buf[257];
172
173         tv.tv_sec  = 0;
174         tv.tv_usec = 100000;
175
176         FD_ZERO( &fds );
177         FD_SET( STDIN_FILENO, &fds );
178         ret = select( STDIN_FILENO + 1, &fds, NULL, NULL, &tv );
179
180         if( ret > 0 )
181         {
182             int size = 0;
183
184             while( size < 256 &&
185                    read( STDIN_FILENO, &buf[size], 1 ) > 0 )
186             {
187                 if( buf[size] == '\n' )
188                 {
189                     break;
190                 }
191                 size++;
192             }
193
194             if( size >= 256 || buf[size] == '\n' )
195             {
196                 switch( buf[0] )
197                 {
198                     case 'q':
199                         fprintf( stdout, "\nEncoding Quit by user command\n" );
200                         die = 1;
201                         break;
202                     case 'p':
203                         fprintf( stdout, "\nEncoding Paused by user command, 'r' to resume\n" );
204                         hb_pause( h );
205                         break;
206                     case 'r':
207                         hb_resume( h );
208                         break;
209                     case 'h':
210                         ShowCommands();
211                         break;
212                 }
213             }
214         }
215         hb_snooze( 200 );
216 #else
217         hb_snooze( 200 );
218 #endif
219
220         HandleEvents( h );
221     }
222
223     /* Clean up */
224     hb_close( &h );
225     if( input )  free( input );
226     if( output ) free( output );
227     if( format ) free( format );
228     if( audios ) free( audios );
229     if (native_language ) free (native_language );
230         if( x264opts ) free (x264opts );
231         if( x264opts2 ) free (x264opts2 );
232     if (preset_name) free (preset_name);
233         
234     fprintf( stderr, "HandBrake has exited.\n" );
235
236     return 0;
237 }
238
239 static void ShowCommands()
240 {
241     fprintf( stdout, "\nCommands:\n" );
242     fprintf( stdout, " [h]elp    Show this message\n" );
243     fprintf( stdout, " [q]uit    Exit HandBrakeCLI\n" );
244     fprintf( stdout, " [p]ause   Pause encoding\n" );
245     fprintf( stdout, " [r]esume  Resume encoding\n" );
246 }
247
248 static void PrintTitleInfo( hb_title_t * title )
249 {
250     hb_chapter_t  * chapter;
251     hb_audio_t    * audio;
252     hb_subtitle_t * subtitle;
253     int i;
254
255     fprintf( stderr, "+ title %d:\n", title->index );
256     fprintf( stderr, "  + vts %d, ttn %d, cells %d->%d (%d blocks)\n",
257              title->vts, title->ttn, title->cell_start, title->cell_end,
258              title->block_count );
259     fprintf( stderr, "  + duration: %02d:%02d:%02d\n",
260              title->hours, title->minutes, title->seconds );
261     fprintf( stderr, "  + size: %dx%d, aspect: %.2f, %.3f fps\n",
262              title->width, title->height,
263              (float) title->aspect / HB_ASPECT_BASE,
264              (float) title->rate / title->rate_base );
265     fprintf( stderr, "  + autocrop: %d/%d/%d/%d\n", title->crop[0],
266              title->crop[1], title->crop[2], title->crop[3] );
267     fprintf( stderr, "  + chapters:\n" );
268     for( i = 0; i < hb_list_count( title->list_chapter ); i++ )
269     {
270         chapter = hb_list_item( title->list_chapter, i );
271         fprintf( stderr, "    + %d: cells %d->%d, %d blocks, duration "
272                  "%02d:%02d:%02d\n", chapter->index,
273                  chapter->cell_start, chapter->cell_end,
274                  chapter->block_count, chapter->hours, chapter->minutes,
275                  chapter->seconds );
276     }
277     fprintf( stderr, "  + audio tracks:\n" );
278     for( i = 0; i < hb_list_count( title->list_audio ); i++ )
279     {
280         audio = hb_list_item( title->list_audio, i );
281         if( ( audio->codec & HB_ACODEC_AC3 ) || ( audio->codec & HB_ACODEC_DCA) )
282         {
283             fprintf( stderr, "    + %d, %s, %dHz, %dbps\n", i + 1,
284                      audio->lang, audio->rate, audio->bitrate );
285         }
286         else
287         {
288             fprintf( stderr, "    + %d, %s\n", i + 1, audio->lang );
289         }
290     }
291     fprintf( stderr, "  + subtitle tracks:\n" );
292     for( i = 0; i < hb_list_count( title->list_subtitle ); i++ )
293     {
294         subtitle = hb_list_item( title->list_subtitle, i );
295         fprintf( stderr, "    + %d, %s (iso639-2: %s)\n", i + 1, subtitle->lang,
296             subtitle->iso639_2);
297     }
298 }
299
300 static int HandleEvents( hb_handle_t * h )
301 {
302     hb_state_t s;
303     hb_get_state( h, &s );
304     switch( s.state )
305     {
306         case HB_STATE_IDLE:
307             /* Nothing to do */
308             break;
309
310 #define p s.param.scanning
311         case HB_STATE_SCANNING:
312             /* Show what title is currently being scanned */
313             fprintf( stderr, "Scanning title %d", p.title_cur );
314             if( !titleindex )
315                 fprintf( stderr, " of %d", p.title_count );
316             fprintf( stderr, "...\n" );
317             break;
318 #undef p
319
320         case HB_STATE_SCANDONE:
321         {
322             hb_list_t  * list;
323             hb_title_t * title;
324             hb_job_t   * job;
325
326             list = hb_get_titles( h );
327
328             if( !hb_list_count( list ) )
329             {
330                 /* No valid title, stop right there */
331                 fprintf( stderr, "No title found.\n" );
332                 die = 1;
333                 break;
334             }
335             if( longest_title )
336             {
337                 int i;
338                 int longest_title_idx=0;
339                 int longest_title_pos=-1;
340                 int longest_title_time=0;
341                 int title_time;
342                 
343                 fprintf( stderr, "Searching for longest title...\n" );
344
345                 for( i = 0; i < hb_list_count( list ); i++ )
346                 {
347                     title = hb_list_item( list, i );
348                     title_time = (title->hours*60*60 ) + (title->minutes *60) + (title->seconds);
349                     fprintf( stderr, " + Title (%d) index %d has length %dsec\n", 
350                              i, title->index, title_time );
351                     if( longest_title_time < title_time )
352                     {
353                         longest_title_time = title_time;
354                         longest_title_pos = i;
355                         longest_title_idx = title->index;
356                     }               
357                 }
358                 if( longest_title_pos == -1 ) 
359                 {
360                     fprintf( stderr, "No longest title found.\n" );
361                     die = 1;
362                     break;
363                 }
364                 titleindex = longest_title_idx;
365                 fprintf( stderr, "Found longest title, setting title to %d\n", 
366                          longest_title_idx);
367
368                 title = hb_list_item( list, longest_title_pos);
369             } else {
370                 title = hb_list_item( list, 0 );
371             }
372
373             if( !titleindex )
374             {
375                 /* Scan-only mode, print infos and exit */
376                 int i;
377                 for( i = 0; i < hb_list_count( list ); i++ )
378                 {
379                     title = hb_list_item( list, i );
380                     PrintTitleInfo( title );
381                 }
382                 die = 1;
383                 break;
384             }
385
386             /* Set job settings */
387             job   = title->job;
388
389             PrintTitleInfo( title );
390
391             if( chapter_start && chapter_end )
392             {
393                 job->chapter_start = MAX( job->chapter_start,
394                                           chapter_start );
395                 job->chapter_end   = MIN( job->chapter_end,
396                                           chapter_end );
397                 job->chapter_end   = MAX( job->chapter_start,
398                                           job->chapter_end );
399             }
400
401             if (preset)
402             {
403                 hb_log("+ Using preset: %s", preset_name);
404                 
405                 if (!strcmp(preset_name, "Animation"))
406                 {
407                     mux = HB_MUX_MKV;
408                     vcodec = HB_VCODEC_X264;
409                     job->vbitrate = 1000;
410                     job->abitrate = 160;
411                     job->arate = 48000;
412                     acodec = HB_ACODEC_FAAC;
413                     x264opts = strdup("ref=5:mixed-refs:bframes=16:bime:weightb:b-rdo:direct=auto:b-pyramid:me=umh:subme=5:analyse=all:8x8dct:trellis=1:nr=150:no-fast-pskip:filter=2,2");
414                     job->chapter_markers = 1;
415                     job->deinterlace = 1;
416                     pixelratio = 1;
417                     twoPass = 1;
418                     turbo_opts_enabled = 1;
419                 }
420
421                 if (!strcmp(preset_name, "AppleTV"))
422                 {
423                     mux = HB_MUX_MP4;
424                     vcodec = HB_VCODEC_X264;
425                     job->vbitrate = 2500;
426                     job->abitrate = 160;
427                     job->arate = 48000;
428                     acodec = HB_ACODEC_FAAC;
429                     x264opts = strdup("bframes=3:ref=1:subme=5:me=umh:no-fast-pskip=1:trellis=2:cabac=0");
430                     job->chapter_markers = 1;
431                     pixelratio = 1;
432                 }
433
434                 if (!strcmp(preset_name, "Bedlam"))
435                 {
436                     mux = HB_MUX_MKV;
437                     vcodec = HB_VCODEC_X264;
438                     job->vbitrate = 1800;
439                     acodec = HB_ACODEC_AC3;
440                     x264opts = strdup("ref=16:mixed-refs:bframes=16:bime:weightb:b-rdo:direct=auto:b-pyramid:me=umh:subme=7:me-range=64:analyse=all:8x8dct:trellis=2:no-fast-pskip:no-dct-decimate:filter=-2,-1");
441                     job->chapter_markers = 1;
442                     pixelratio = 1;
443                     twoPass = 1;
444                     turbo_opts_enabled = 1;
445                 }
446
447                 if (!strcmp(preset_name, "Blind"))
448                 {
449                     mux = HB_MUX_MP4;
450                     job->vbitrate = 512;
451                     job->abitrate = 128;
452                     job->arate = 48000;
453                     acodec = HB_ACODEC_FAAC;
454                     job->width = 512;
455                     job->chapter_markers = 1;
456                 }
457
458                 if (!strcmp(preset_name, "Broke"))
459                 {
460                     mux = HB_MUX_MP4;
461                     vcodec = HB_VCODEC_X264;
462                     size = 695;
463                     job->abitrate = 128;
464                     job->arate = 48000;
465                     acodec = HB_ACODEC_FAAC;
466                     job->width = 640;
467                     x264opts = strdup("ref=3:mixed-refs:bframes=16:bime:weightb:b-rdo:b-pyramid:direct=auto:me=umh:subme=6:trellis=1:analyse=all:8x8dct:no-fast-pskip");
468                     job->chapter_markers = 1;
469                     twoPass = 1;
470                     turbo_opts_enabled = 1;
471                 }
472
473                 if (!strcmp(preset_name, "Classic"))
474                 {
475                     mux = HB_MUX_MP4;
476                     job->vbitrate = 1000;
477                     job->abitrate = 160;
478                     job->arate = 48000;
479                     acodec = HB_ACODEC_FAAC;
480                  }
481
482                 if (!strcmp(preset_name, "Constant Quality Rate"))
483                 {
484                     mux = HB_MUX_MKV;
485                     vcodec = HB_VCODEC_X264;
486                     job->vquality = 0.64709997177124023;
487                     job->crf = 1;
488                     acodec = HB_ACODEC_AC3;
489                     x264opts = strdup("ref=3:mixed-refs:bframes=3:b-pyramid:b-rdo:bime:weightb:filter=-2,-1:subme=6:trellis=1:analyse=all:8x8dct:me=umh");
490                     job->chapter_markers = 1;
491                     pixelratio = 1;
492                 }
493
494                 if (!strcmp(preset_name, "Deux Six Quatre"))
495                 {
496                     mux = HB_MUX_MKV;
497                     vcodec = HB_VCODEC_X264;
498                     job->vbitrate = 1600;
499                     acodec = HB_ACODEC_AC3;
500                     x264opts = strdup("ref=5:mixed-refs:bframes=3:bime:weightb:b-rdo:b-pyramid:me=umh:subme=7:trellis=1:analyse=all:8x8dct:no-fast-pskip");
501                     job->chapter_markers = 1;
502                     pixelratio = 1;
503                     twoPass = 1;
504                     turbo_opts_enabled = 1;
505                 }
506
507                 if (!strcmp(preset_name, "Film"))
508                 {
509                     mux = HB_MUX_MKV;
510                     vcodec = HB_VCODEC_X264;
511                     job->vbitrate = 1800;
512                     acodec = HB_ACODEC_AC3;
513                     x264opts = strdup("ref=3:mixed-refs:bframes=16:bime:weightb:b-rdo:direct=auto:b-pyramid:me=umh:subme=6:analyse=all:8x8dct:trellis=1:no-fast-pskip");
514                     job->chapter_markers = 1;
515                     pixelratio = 1;
516                     twoPass = 1;
517                     turbo_opts_enabled = 1;
518                 }
519
520                 if (!strcmp(preset_name, "iPhone / iPod Touch"))
521                 {
522                     mux = HB_MUX_MP4;
523                     vcodec = HB_VCODEC_X264;
524                     job->h264_level = 30;
525                     job->vbitrate = 960;
526                     job->abitrate = 128;
527                     job->arate = 48000;
528                     acodec = HB_ACODEC_FAAC;
529                     job->width = 480;
530                     x264opts = strdup("cabac=0:ref=1:analyse=all:me=umh:subme=6:no-fast-pskip=1:trellis=1");
531                     job->chapter_markers = 1;
532                 }
533
534                 if (!strcmp(preset_name, "iPod High-Rez"))
535                 {
536                     mux = HB_MUX_MP4;
537                     vcodec = HB_VCODEC_X264;
538                     job->h264_level = 30;
539                     job->vbitrate = 1500;
540                     job->abitrate = 160;
541                     job->arate = 48000;
542                     acodec = HB_ACODEC_FAAC;
543                     job->width = 640;
544                     x264opts = strdup("keyint=300:keyint-min=30:bframes=0:cabac=0:ref=1:vbv-maxrate=1500:vbv-bufsize=2000:analyse=all:me=umh:subme=6:no-fast-pskip=1");
545                     job->chapter_markers = 1;
546                 }
547
548                 if (!strcmp(preset_name, "iPod Low-Rez"))
549                 {
550                     mux = HB_MUX_MP4;
551                     vcodec = HB_VCODEC_X264;
552                     job->h264_level = 30;
553                     job->vbitrate = 700;
554                     job->abitrate = 160;
555                     job->arate = 48000;
556                     acodec = HB_ACODEC_FAAC;
557                     job->width = 320;
558                     x264opts = strdup("keyint=300:keyint-min=30:bframes=0:cabac=0:ref=1:vbv-maxrate=768:vbv-bufsize=2000:analyse=all:me=umh:subme=6:no-fast-pskip=1");
559                     job->chapter_markers = 1;
560                 }
561
562                 if (!strcmp(preset_name, "Normal"))
563                 {
564                     mux = HB_MUX_MP4;
565                     vcodec = HB_VCODEC_X264;
566                     job->vbitrate = 1500;
567                     job->abitrate = 160;
568                     job->arate = 48000;
569                     acodec = HB_ACODEC_FAAC;
570                     x264opts = strdup("ref=2:bframes=2:subme=5:me=umh");
571                     job->chapter_markers = 1;
572                     pixelratio = 1;
573                     twoPass = 1;
574                     turbo_opts_enabled = 1;
575                 }
576
577                 if (!strcmp(preset_name, "PS3"))
578                 {
579                     mux = HB_MUX_MP4;
580                     vcodec = HB_VCODEC_X264;
581                     job->vbitrate = 2500;
582                     job->abitrate = 160;
583                     job->arate = 48000;
584                     acodec = HB_ACODEC_FAAC;
585                     x264opts = strdup("level=41:subme=5:me=umh");
586                     pixelratio = 1;
587                 }
588
589                 if (!strcmp(preset_name, "PSP"))
590                 {
591                     mux = HB_MUX_MP4;
592                     job->vbitrate = 1024;
593                     job->abitrate = 128;
594                     job->arate = 48000;
595                     acodec = HB_ACODEC_FAAC;
596                     job->width = 368;
597                     job->height = 208;
598                     job->chapter_markers = 1;
599                 }
600
601                 if (!strcmp(preset_name, "QuickTime"))
602                 {
603                     mux = HB_MUX_MP4;
604                     vcodec = HB_VCODEC_X264;
605                     job->vbitrate = 2000;
606                     job->abitrate = 160;
607                     job->arate = 48000;
608                     acodec = HB_ACODEC_FAAC;
609                     x264opts = strdup("ref=3:mixed-refs:bframes=3:bime:weightb:b-rdo:direct=auto:me=umh:subme=5:analyse=all:trellis=1:no-fast-pskip");
610                     job->chapter_markers = 1;
611                     pixelratio = 1;
612                     twoPass = 1;
613                     turbo_opts_enabled = 1;
614                 }
615
616                 if (!strcmp(preset_name, "Television"))
617                 {
618                     mux = HB_MUX_MKV;
619                     vcodec = HB_VCODEC_X264;
620                     job->vbitrate = 1300;
621                     job->abitrate = 160;
622                     job->arate = 48000;
623                     acodec = HB_ACODEC_FAAC;
624                     x264opts = strdup("ref=3:mixed-refs:bframes=16:bime:weightb:direct=auto:b-pyramid:me=umh:subme=6:analyse=all:8x8dct:trellis=1:nr=150:no-fast-pskip");
625                     job->chapter_markers = 1;
626                     job->deinterlace = 1;
627                     twoPass = 1;
628                     turbo_opts_enabled = 1;
629                 }
630             }
631             
632                         if ( chapter_markers )
633                         {
634                                 job->chapter_markers = chapter_markers;
635
636                 if( marker_file != NULL )
637                 {
638                     hb_csv_file_t * file = hb_open_csv_file( marker_file );
639                     hb_csv_cell_t * cell;
640                     int row = 0;
641                     int chapter = 0;
642                     
643                     fprintf( stderr, "Reading chapter markers from file %s\n", marker_file );
644                     
645                     if( file == NULL )
646                     {
647                          fprintf( stderr, "Cannot open chapter marker file, using defaults\n" );
648                     }
649                     else
650                     {
651                         /* Parse the cells */
652                         while( NULL != ( cell = hb_read_next_cell( file ) ) )
653                         {                            
654                             /* We have a chapter number */
655                             if( cell->cell_col == 0 )
656                             {
657                                 row = cell->cell_row;
658                                 chapter = atoi( cell->cell_text );
659                             }
660                              
661                             /* We have a chapter name */
662                             if( cell->cell_col == 1 && row == cell->cell_row )
663                             {
664                                 /* If we have a valid chapter, copy the string an terminate it */
665                                 if( chapter >= job->chapter_start && chapter <= job->chapter_end )
666                                 {
667                                     hb_chapter_t * chapter_s;
668                                     
669                                     chapter_s = hb_list_item( job->title->list_chapter, chapter - 1);
670                                     strncpy(chapter_s->title, cell->cell_text, 1023);
671                                     chapter_s->title[1023] = '\0';
672                                 }
673                             }                               
674                         
675                                                            
676                             hb_dispose_cell( cell );
677                         }
678                         
679                         hb_close_csv_file( file );
680                     }
681                 }
682                         }
683
684             if( crop[0] >= 0 && crop[1] >= 0 &&
685                 crop[2] >= 0 && crop[3] >= 0 )
686             {
687                 memcpy( job->crop, crop, 4 * sizeof( int ) );
688             }
689
690             job->deinterlace = deinterlace;
691             job->grayscale   = grayscale;
692             if (loosePixelratio)
693             {
694                 job->pixel_ratio = 2;
695                 if (modulus)
696                 {
697                     job->modulus = modulus;
698                 }
699             }
700             else
701             {
702                 job->pixel_ratio = pixelratio;
703             }
704             /* Add selected filters */
705             job->filters = hb_list_init();
706             if( detelecine )
707             {
708                 hb_filter_detelecine.settings = detelecine_opt;
709                 hb_list_add( job->filters, &hb_filter_detelecine );
710             }
711             if( deinterlace )
712             {
713                 hb_filter_deinterlace.settings = deinterlace_opt;
714                 hb_list_add( job->filters, &hb_filter_deinterlace );
715             }
716             if( deblock )
717             {
718                 hb_filter_deblock.settings = deblock_opt;
719                 hb_list_add( job->filters, &hb_filter_deblock );
720             }
721             if( denoise )
722             {
723                 hb_filter_denoise.settings = denoise_opt;
724                 hb_list_add( job->filters, &hb_filter_denoise );
725             }
726             
727             if( width && height )
728             {
729                 job->width  = width;
730                 job->height = height;
731             }
732             else if( width )
733             {
734                 job->width = width;
735                 hb_fix_aspect( job, HB_KEEP_WIDTH );
736             }
737             else if( height && !loosePixelratio)
738             {
739                 job->height = height;
740                 hb_fix_aspect( job, HB_KEEP_HEIGHT );
741             }
742             else if( !width && !height && !pixelratio && !loosePixelratio )
743             {
744                 hb_fix_aspect( job, HB_KEEP_WIDTH );
745             }
746             else if (!width && loosePixelratio)
747             {
748                 /* Default to full width when one isn't specified for loose anamorphic */
749                 job->width = title->width - job->crop[2] - job->crop[3];
750                 /* The height will be thrown away in hb.c but calculate it anyway */
751                 hb_fix_aspect( job, HB_KEEP_WIDTH );
752             }
753             
754             if( vquality >= 0.0 && vquality <= 1.0 )
755             {
756                 job->vquality = vquality;
757                 job->vbitrate = 0;
758             }
759             else if( vbitrate )
760             {
761                 job->vquality = -1.0;
762                 job->vbitrate = vbitrate;
763             }
764             if( vcodec )
765             {
766                 job->vcodec = vcodec;
767             }
768             if( h264_13 ) 
769             { 
770                 job->h264_level = 13; 
771             }
772                 if( h264_30 )
773                 {
774                     job->h264_level = 30;
775             }
776             if( vrate )
777             {
778                 job->vrate = 27000000;
779                 job->vrate_base = vrate;
780             }
781             if( arate )
782             {
783                 job->arate = arate;
784             }
785
786             if( audios )
787             {
788                 if( strcasecmp( audios, "none" ) )
789                 {
790                     int    audio_count = 0;
791                     char * tmp         = audios;
792                     while( *tmp )
793                     {
794                         if( *tmp < '0' || *tmp > '9' )
795                         {
796                             /* Skip non numeric char */
797                             tmp++;
798                             continue;
799                         }
800                                                 job->audio_mixdowns[audio_count] = audio_mixdown;
801                         job->audios[audio_count++] =
802                             strtol( tmp, &tmp, 0 ) - 1;
803                     }
804                     job->audios[audio_count] = -1;
805                 }
806                 else
807                 {
808                     job->audios[0] = -1;
809                 }
810             }
811                         else
812                         {
813                             /* default to the first audio track if none has been specified */
814                             job->audios[0] = 0;
815                             job->audio_mixdowns[0] = audio_mixdown;
816                         }
817             if( abitrate )
818             {
819                 job->abitrate = abitrate;
820             }
821             if( acodec )
822             {
823                 job->acodec = acodec;
824             }
825
826             if( size )
827             {
828                 job->vbitrate = hb_calc_bitrate( job, size );
829                 fprintf( stderr, "Calculated bitrate: %d kbps\n",
830                          job->vbitrate );
831             }
832
833             if( sub )
834             {
835                 job->subtitle = sub - 1;
836             }
837
838             if( native_language )
839             {
840                 job->native_language = strdup( native_language );
841             }
842
843             if( job->mux )
844             {
845                 job->mux = mux;
846             }
847             
848             if ( largeFileSize )
849             {
850                 job->largeFileSize = 1;
851             }
852             if ( mp4_optimize )
853             {
854                 job->mp4_optimize = 1;
855             }
856             
857             job->file = strdup( output );
858
859             if( crf )
860             {
861                 job->crf = 1;
862             }
863
864             if( x264opts != NULL && *x264opts != '\0' )
865             {
866                 job->x264opts = x264opts;
867             }
868             else /*avoids a bus error crash when options aren't specified*/
869             {
870                 job->x264opts =  NULL;
871             }
872             if (maxWidth)
873                 job->maxWidth = maxWidth;
874             if (maxHeight)
875                 job->maxHeight = maxHeight;
876             
877             if (vfr)
878                 job->vfr = 1;
879         
880             if( subtitle_force )
881             {
882                 job->subtitle_force = subtitle_force;
883             }
884
885             if( subtitle_scan )
886             {
887                 char *x264opts_tmp;
888
889                 /*
890                  * When subtitle scan is enabled do a fast pre-scan job
891                  * which will determine which subtitles to enable, if any.
892                  */
893                 job->pass = -1;
894                 
895                 x264opts_tmp = job->x264opts;
896
897                 job->x264opts = NULL;
898
899                 job->indepth_scan = subtitle_scan;  
900                 fprintf( stderr, "Subtitle Scan Enabled - enabling "
901                          "subtitles if found for foreign language segments\n");
902                 job->select_subtitle = malloc(sizeof(hb_subtitle_t*));
903                 *(job->select_subtitle) = NULL;
904                 
905                 /*
906                  * Add the pre-scan job
907                  */
908                 hb_add( h, job );
909
910                 job->x264opts = x264opts_tmp;
911             }
912
913             if( twoPass )
914             {
915                 /*
916                  * If subtitle_scan is enabled then only turn it on
917                  * for the first pass and then off again for the
918                  * second. 
919                  */
920                 hb_subtitle_t **subtitle_tmp = job->select_subtitle;
921
922                 job->select_subtitle = NULL;
923
924                 job->pass = 1;
925
926                 job->indepth_scan = 0;
927                 
928                 if (x264opts)
929                 {
930                     x264opts2 = strdup(x264opts);
931                 }
932
933                 /*
934                  * If turbo options have been selected then append them
935                  * to the x264opts now (size includes one ':' and the '\0')
936                  */
937                 if( turbo_opts_enabled ) 
938                 {
939                     int size = (x264opts ? strlen(x264opts) : 0) + strlen(turbo_opts) + 2;
940                     char *tmp_x264opts;
941                         
942                     tmp_x264opts = malloc(size * sizeof(char));
943                     if( x264opts ) 
944                     {
945                         snprintf( tmp_x264opts, size, "%s:%s", 
946                                   x264opts, turbo_opts );  
947                         free( x264opts );
948                     } else {
949                         /*
950                          * No x264opts to modify, but apply the turbo options
951                          * anyway as they may be modifying defaults
952                          */
953                         snprintf( tmp_x264opts, size, "%s", 
954                                   turbo_opts );
955                     }
956                     x264opts = tmp_x264opts;
957
958                     fprintf( stderr, "Modified x264 options for pass 1 to append turbo options: %s\n",
959                              x264opts );
960
961                     job->x264opts = x264opts;
962                 }     
963                 hb_add( h, job );
964
965                 job->select_subtitle = subtitle_tmp;
966
967                 job->pass = 2;
968                 /*
969                  * On the second pass we turn off subtitle scan so that we
970                  * can actually encode using any subtitles that were auto
971                  * selected in the first pass (using the whacky select-subtitle
972                  * attribute of the job).
973                  */
974                 job->indepth_scan = 0;
975
976                 job->x264opts = x264opts2;
977                 
978                 hb_add( h, job );
979             }
980             else
981             {
982                 /*
983                  * Turn on subtitle scan if requested, note that this option
984                  * precludes encoding of any actual subtitles.
985                  */ 
986
987                 job->indepth_scan = 0;
988                 job->pass = 0;
989                 hb_add( h, job );
990             }
991             hb_start( h );
992             break;
993         }
994
995 #define p s.param.working
996         case HB_STATE_WORKING:
997             fprintf( stdout, "\rEncoding: task %d of %d, %.2f %%",
998                      p.job_cur, p.job_count, 100.0 * p.progress );
999             if( p.seconds > -1 )
1000             {
1001                 fprintf( stdout, " (%.2f fps, avg %.2f fps, ETA "
1002                          "%02dh%02dm%02ds)", p.rate_cur, p.rate_avg,
1003                          p.hours, p.minutes, p.seconds );
1004             }
1005             fflush(stdout);
1006             break;
1007 #undef p
1008
1009 #define p s.param.muxing
1010         case HB_STATE_MUXING:
1011         {
1012             fprintf( stdout, "\rMuxing: %.2f %%", 100.0 * p.progress );
1013             fflush(stdout);
1014             break;
1015         }
1016 #undef p
1017
1018 #define p s.param.workdone
1019         case HB_STATE_WORKDONE:
1020             /* Print error if any, then exit */
1021             switch( p.error )
1022             {
1023                 case HB_ERROR_NONE:
1024                     fprintf( stderr, "\nRip done!\n" );
1025                     break;
1026                 case HB_ERROR_CANCELED:
1027                     fprintf( stderr, "\nRip canceled.\n" );
1028                     break;
1029                 default:
1030                     fprintf( stderr, "\nRip failed (error %x).\n",
1031                              p.error );
1032             }
1033             die = 1;
1034             break;
1035 #undef p
1036     }
1037     return 0;
1038 }
1039
1040 /****************************************************************************
1041  * SigHandler:
1042  ****************************************************************************/
1043 static volatile int64_t i_die_date = 0;
1044 void SigHandler( int i_signal )
1045 {
1046     if( die == 0 )
1047     {
1048         die = 1;
1049         i_die_date = hb_get_date();
1050         fprintf( stderr, "Signal %d received, terminating - do it "
1051                  "again in case it gets stuck\n", i_signal );
1052     }
1053     else if( i_die_date + 500 < hb_get_date() )
1054     {
1055         fprintf( stderr, "Dying badly, files might remain in your /tmp\n" );
1056         exit( 1 );
1057     }
1058 }
1059
1060 /****************************************************************************
1061  * ShowHelp:
1062  ****************************************************************************/
1063 static void ShowHelp()
1064 {
1065     int i;
1066     
1067     fprintf( stderr,
1068     "Syntax: HandBrakeCLI [options] -i <device> -o <file>\n"
1069     "\n"
1070         "### General Handbrake Options------------------------------------------------\n\n"
1071     "    -h, --help              Print help\n"
1072     "    -u, --update            Check for updates and exit\n"
1073     "    -v, --verbose           Be verbose\n"
1074     "    -C, --cpu               Set CPU count (default: autodetected)\n"
1075     "    -Z. --preset <string>   Use a built-in preset. Capitalization matters, and\n"
1076     "                            if the preset name has spaces, surround it with\n"
1077     "                            double quotation marks\n"
1078     "    -z, --preset-list       See a list of available built-in presets\n"
1079     "\n"
1080         
1081         "### Source Options-----------------------------------------------------------\n\n"
1082         "    -i, --input <string>    Set input device\n"
1083         "    -t, --title <number>    Select a title to encode (0 to scan only,\n"
1084     "                            default: 1)\n"
1085     "    -L, --longest           Select the longest title\n"
1086     "    -c, --chapters <string> Select chapters (e.g. \"1-3\" for chapters\n"
1087     "                            1 to 3, or \"3\" for chapter 3 only,\n"
1088     "                            default: all chapters)\n"
1089         "\n"
1090         
1091         "### Destination Options------------------------------------------------------\n\n"
1092     "    -o, --output <string>   Set output file name\n"
1093         "    -f, --format <string>   Set output format (avi/mp4/ogm/mkv, default:\n"
1094     "                            autodetected from file name)\n"
1095     "    -4, --large-file        Use 64-bit mp4 files that can hold more than\n"
1096     "                            4 GB. Note: Breaks iPod, @TV, PS3 compatibility.\n"""
1097     "    -O, --optimize          Optimize mp4 files for HTTP streaming\n"
1098     "\n"
1099         
1100         "### Picture Settings---------------------------------------------------------\n\n"
1101     "    -w, --width <number>    Set picture width\n"
1102     "    -l, --height <number>   Set picture height\n"
1103     "        --crop <T:B:L:R>    Set cropping values (default: autocrop)\n"
1104         "    -Y, --maxHeight <#>     Set maximum height\n"
1105         "    -X, --maxWidth <#>      Set maximum width\n"
1106         "    -s, --subtitle <number> Select subtitle (default: none)\n"
1107     "    -U, --subtitle-scan     Scan for subtitles in an extra 1st pass, and choose\n"
1108     "                            the one that's only used 10 percent of the time\n"
1109     "                            or less. This should locate subtitles for short\n"
1110     "                            foreign language segments. Best used in conjunction\n"
1111     "                            with --subtitle-forced.\n"
1112     "    -F, --subtitle-forced   Only display subtitles from the selected stream if\n"
1113     "                            the subtitle has the forced flag set. May be used in\n"
1114     "                            conjunction with --subtitle-scan to auto-select\n"
1115     "                            a stream if it contains forced subtitles.\n"
1116     "    -N, --native-language   Select subtitles with this language if it does not\n"
1117     "          <string>          match the Audio language. Provide the language's\n"
1118     "                            iso639-2 code (fre, eng, spa, dut, et cetera)\n"
1119         "    -m, --markers           Add chapter markers (mp4 output format only)\n"
1120         "\n"
1121         
1122         "### Video Options------------------------------------------------------------\n\n"
1123         "    -e, --encoder <string>  Set video library encoder (ffmpeg,xvid,\n"
1124     "                            x264,x264b13,x264b30 default: ffmpeg)\n"
1125         "    -q, --quality <float>   Set video quality (0.0..1.0)\n"
1126         "    -Q, --crf               Use with -q for CRF instead of CQP\n"
1127     "    -S, --size <MB>         Set target size\n"
1128         "    -b, --vb <kb/s>         Set video bitrate (default: 1000)\n"
1129         "    -r, --rate              Set video framerate (" );
1130     for( i = 0; i < hb_video_rates_count; i++ )
1131     {
1132         fprintf( stderr, hb_video_rates[i].string );
1133         if( i != hb_video_rates_count - 1 )
1134             fprintf( stderr, "/" );
1135     }
1136     fprintf( stderr, ")\n"
1137         "\n"
1138         "    -2, --two-pass          Use two-pass mode\n"
1139      "    -d, --deinterlace       Deinterlace video with yadif/mcdeint filter\n"
1140      "          <YM:FD:MM:QP>     (default 0:-1:-1:1)\n"
1141      "           or\n"
1142      "          <fast/slow/slower/slowest>\n"            
1143      "    -7, --deblock           Deblock video with pp7 filter\n"
1144      "          <QP:M>            (default 0:2)\n"
1145      "    -8, --denoise           Denoise video with hqdn3d filter\n"
1146      "          <SL:SC:TL:TC>     (default 4:3:6:4.5)\n"
1147      "           or\n"
1148      "          <weak/medium/strong>\n"
1149      "    -9, --detelecine        Detelecine video with pullup filter\n"
1150      "          <L:R:T:B:SB:MP>   (default 1:1:4:4:0:0)\n"
1151     "    -g, --grayscale         Grayscale encoding\n"
1152     "    -p, --pixelratio        Store pixel aspect ratio in video stream\n"
1153     "    -P, --loosePixelratio   Store pixel aspect ratio with specified width\n"
1154     "           <modulus>        Takes as optional argument what number you want\n"
1155     "                            the dimensions to divide cleanly by (default 16)\n"
1156     
1157         
1158         "\n"
1159         
1160         
1161         "### Audio Options-----------------------------------------------------------\n\n"
1162         "    -E, --aencoder <string> Set audio encoder (faac/lame/vorbis/ac3, ac3\n"
1163     "                            meaning passthrough, default: guessed)\n"
1164         "    -B, --ab <kb/s>         Set audio bitrate (default: 128)\n"
1165         "    -a, --audio <string>    Select audio channel(s), separated by commas\n"
1166         "                            (\"none\" for no audio, \"1,2,3\" for multiple\n"
1167         "                             tracks, default: first one, max: eight)\n"
1168     "    -6, --mixdown <string>  Format for surround sound downmixing\n"
1169     "                            (mono/stereo/dpl1/dpl2/6ch, default: dpl2)\n"
1170     "    -R, --arate             Set audio samplerate (" );
1171     for( i = 0; i < hb_audio_rates_count; i++ )
1172     {
1173         fprintf( stderr, hb_audio_rates[i].string );
1174         if( i != hb_audio_rates_count - 1 )
1175             fprintf( stderr, "/" );
1176     }
1177     fprintf( stderr, " kHz)\n"
1178    
1179     
1180         
1181         "\n"
1182         
1183         
1184     "### Advanced Options---------------------------------------------------------\n\n"
1185     "    -x, --x264opts <string> Specify advanced x264 options in the\n"
1186     "                            same style as mencoder:\n"
1187     "                            option1=value1:option2=value2\n"
1188     "    -T, --turbo             When using 2-pass use the turbo options\n"
1189     "                            on the first pass to improve speed\n"
1190     "                            (only works with x264, affects PSNR by about 0.05dB,\n"
1191     "                            and increases first pass speed two to four times)\n"
1192     "    -V, --vfr               Perform variable framerate detelecine on NTSC video\n"
1193     );
1194 }
1195
1196 /****************************************************************************
1197  * ShowPresets:
1198  ****************************************************************************/
1199 static void ShowPresets()
1200 {
1201     printf("\n+ Animation:  -e x264 -b 1000 -B 160 -R 48 -E faac -f mkv -m -d -p -2 -T -x ref=5:mixed-refs:bframes=16:bime:weightb:b-rdo:direct=auto:b-pyramid:me=umh:subme=5:analyse=all:8x8dct:trellis=1:nr=150:no-fast-pskip:filter=2,2\n");
1202
1203     printf("\n+ AppleTV:  -e x264 -b 2500 -B 160 -R 48 -E faac -f mp4 -m -p -x bframes=3:ref=1:subme=5:me=umh:no-fast-pskip=1:trellis=2:cabac=0\n");
1204
1205     printf("\n+ Bedlam:  -e x264 -b 1800 -E ac3 -f mkv -m -p -2 -T -x ref=16:mixed-refs:bframes=16:bime:weightb:b-rdo:direct=auto:b-pyramid:me=umh:subme=7:me-range=64:analyse=all:8x8dct:trellis=2:no-fast-pskip:no-dct-decimate:filter=-2,-1\n");
1206
1207     printf("\n+ Blind:  -b 512 -B 128 -R 48 -E faac -f mp4 -w 512 -m\n");
1208
1209     printf("\n+ Broke:  -e x264 -S 695 -B 128 -R 48 -E faac -f mp4 -w 640 -m -2 -T -x ref=3:mixed-refs:bframes=16:bime:weightb:b-rdo:b-pyramid:direct=auto:me=umh:subme=6:trellis=1:analyse=all:8x8dct:no-fast-pskip\n");
1210
1211     printf("\n+ Classic:  -b 1000 -B 160 -R 48 -E faac -f mp4\n");
1212
1213     printf("\n+ Constant Quality Rate:  -e x264 -q 0.64709997177124023 -Q  -E ac3 -f mkv -m -p -x ref=3:mixed-refs:bframes=3:b-pyramid:b-rdo:bime:weightb:filter=-2,-1:subme=6:trellis=1:analyse=all:8x8dct:me=umh\n");
1214
1215     printf("\n+ Deux Six Quatre:  -e x264 -b 1600 -E ac3 -f mkv -m -p -2 -T -x ref=5:mixed-refs:bframes=3:bime:weightb:b-rdo:b-pyramid:me=umh:subme=7:trellis=1:analyse=all:8x8dct:no-fast-pskip\n");
1216
1217     printf("\n+ Film:  -e x264 -b 1800 -E ac3 -f mkv -m -p -2 -T -x ref=3:mixed-refs:bframes=16:bime:weightb:b-rdo:direct=auto:b-pyramid:me=umh:subme=6:analyse=all:8x8dct:trellis=1:no-fast-pskip\n");
1218
1219     printf("\n+ iPhone / iPod Touch:  -e x264b30 -b 960 -B 128 -R 48 -E faac -f mp4 -w 480 -m -x cabac=0:ref=1:analyse=all:me=umh:subme=6:no-fast-pskip=1:trellis=1\n");
1220
1221     printf("\n+ iPod High-Rez:  -e x264b30 -b 1500 -B 160 -R 48 -E faac -f mp4 -w 640 -m -x keyint=300:keyint-min=30:bframes=0:cabac=0:ref=1:vbv-maxrate=1500:vbv-bufsize=2000:analyse=all:me=umh:subme=6:no-fast-pskip=1\n");
1222
1223     printf("\n+ iPod Low-Rez:  -e x264b30 -b 700 -B 160 -R 48 -E faac -f mp4 -w 320 -m -x keyint=300:keyint-min=30:bframes=0:cabac=0:ref=1:vbv-maxrate=768:vbv-bufsize=2000:analyse=all:me=umh:subme=6:no-fast-pskip=1\n");
1224
1225     printf("\n+ Normal:  -e x264 -b 1500 -B 160 -R 48 -E faac -f mp4 -m -p -2 -T -x ref=2:bframes=2:subme=5:me=umh\n");
1226
1227     printf("\n+ PS3:  -e x264 -b 2500 -B 160 -R 48 -E faac -f mp4 -p -x level=41:subme=5:me=umh\n");
1228
1229     printf("\n+ PSP:  -b 1024 -B 128 -R 48 -E faac -f mp4 -w 368 -l 208 -m\n");
1230
1231     printf("\n+ QuickTime:  -e x264 -b 2000 -B 160 -R 48 -E faac -f mp4 -m -p -2 -T -x ref=3:mixed-refs:bframes=3:bime:weightb:b-rdo:direct=auto:me=umh:subme=5:analyse=all:trellis=1:no-fast-pskip\n");
1232
1233     printf("\n+ Television:  -e x264 -b 1300 -B 160 -R 48 -E faac -f mkv -m -d -2 -T -x ref=3:mixed-refs:bframes=16:bime:weightb:direct=auto:b-pyramid:me=umh:subme=6:analyse=all:8x8dct:trellis=1:nr=150:no-fast-pskip\n");
1234     
1235 }
1236
1237 /****************************************************************************
1238  * ParseOptions:
1239  ****************************************************************************/
1240 static int ParseOptions( int argc, char ** argv )
1241 {
1242     for( ;; )
1243     {
1244         static struct option long_options[] =
1245           {
1246             { "help",        no_argument,       NULL,    'h' },
1247             { "update",      no_argument,       NULL,    'u' },
1248             { "verbose",     no_argument,       NULL,    'v' },
1249             { "cpu",         required_argument, NULL,    'C' },
1250
1251             { "format",      required_argument, NULL,    'f' },
1252             { "input",       required_argument, NULL,    'i' },
1253             { "output",      required_argument, NULL,    'o' },
1254             { "large-file",  no_argument,       NULL,    '4' },
1255             { "optimize",    no_argument,       NULL,    'O' },
1256             
1257             { "title",       required_argument, NULL,    't' },
1258             { "longest",     no_argument,       NULL,    'L' },
1259             { "chapters",    required_argument, NULL,    'c' },
1260             { "markers",     optional_argument, NULL,    'm' },
1261             { "audio",       required_argument, NULL,    'a' },
1262             { "mixdown",     required_argument, NULL,    '6' },
1263             { "subtitle",    required_argument, NULL,    's' },
1264             { "subtitle-scan", no_argument,     NULL,    'U' },
1265             { "subtitle-forced", no_argument,   NULL,    'F' },
1266             { "native-language", required_argument, NULL,'N' },
1267
1268             { "encoder",     required_argument, NULL,    'e' },
1269             { "aencoder",    required_argument, NULL,    'E' },
1270             { "two-pass",    no_argument,       NULL,    '2' },
1271             { "deinterlace", optional_argument, NULL,    'd' },
1272             { "deblock",     optional_argument, NULL,    '7' },
1273             { "denoise",     optional_argument, NULL,    '8' },
1274             { "detelecine",  optional_argument, NULL,    '9' },
1275             { "grayscale",   no_argument,       NULL,    'g' },
1276             { "pixelratio",  no_argument,       NULL,    'p' },
1277             { "loosePixelratio", optional_argument,   NULL,    'P' },
1278             { "width",       required_argument, NULL,    'w' },
1279             { "height",      required_argument, NULL,    'l' },
1280             { "crop",        required_argument, NULL,    'n' },
1281
1282             { "vb",          required_argument, NULL,    'b' },
1283             { "quality",     required_argument, NULL,    'q' },
1284             { "size",        required_argument, NULL,    'S' },
1285             { "ab",          required_argument, NULL,    'B' },
1286             { "rate",        required_argument, NULL,    'r' },
1287             { "arate",       required_argument, NULL,    'R' },
1288             { "crf",         no_argument,       NULL,    'Q' },
1289             { "x264opts",    required_argument, NULL,    'x' },
1290             { "turbo",       no_argument,       NULL,    'T' },
1291             { "maxHeight",   required_argument, NULL,    'Y' },
1292             { "maxWidth",    required_argument, NULL,    'X' },
1293             { "preset",      required_argument, NULL,    'Z' },
1294             { "preset-list", no_argument,       NULL,    'z' },
1295             { "vfr",         no_argument,       NULL,    'V' },
1296                         
1297             { 0, 0, 0, 0 }
1298           };
1299
1300         int option_index = 0;
1301         int c;
1302
1303         c = getopt_long( argc, argv,
1304                          "hvuC:f:4i:o:t:Lc:ma:6:s:UFN:e:E:2d789gpOP::w:l:n:b:q:S:B:r:R:Qx:TY:X:VZ:z",
1305                          long_options, &option_index );
1306         if( c < 0 )
1307         {
1308             break;
1309         }
1310
1311         switch( c )
1312         {
1313             case 'h':
1314                 ShowHelp();
1315                 exit( 0 );
1316             case 'u':
1317                 update = 1;
1318                 break;
1319             case 'v':
1320                 debug = HB_DEBUG_ALL;
1321                 break;
1322             case 'C':
1323                 cpu = atoi( optarg );
1324                 break;
1325             
1326             case 'Z':
1327                 preset = 1;
1328                 preset_name = strdup(optarg);
1329                 break;
1330             case 'z':
1331                 ShowPresets();
1332                 exit ( 0 );
1333                 
1334             case 'f':
1335                 format = strdup( optarg );
1336                 break;
1337             case 'i':
1338                 input = strdup( optarg );
1339                 break;
1340             case 'o':
1341                 output = strdup( optarg );
1342                 break;
1343             case '4':
1344                 largeFileSize = 1;
1345                 break;
1346             case 'O':
1347                 mp4_optimize = 1;
1348                 break;
1349
1350             case 't':
1351                 titleindex = atoi( optarg );
1352                 break;
1353             case 'L':
1354                 longest_title = 1;
1355                 break;
1356             case 'c':
1357             {
1358                 int start, end;
1359                 if( sscanf( optarg, "%d-%d", &start, &end ) == 2 )
1360                 {
1361                     chapter_start = start;
1362                     chapter_end   = end;
1363                 }
1364                 else if( sscanf( optarg, "%d", &start ) == 1 )
1365                 {
1366                     chapter_start = start;
1367                     chapter_end   = chapter_start;
1368                 }
1369                 else
1370                 {
1371                     fprintf( stderr, "chapters: invalid syntax (%s)\n",
1372                              optarg );
1373                     return -1;
1374                 }
1375                 break;
1376             }
1377             case 'm':
1378                 if( optarg != NULL )
1379                 {
1380                     marker_file = strdup( optarg );
1381                 }
1382                 chapter_markers = 1;
1383                 break;
1384             case 'a':
1385                 audios = strdup( optarg );
1386                 break;
1387             case '6':
1388                 if( !strcasecmp( optarg, "mono" ) )
1389                 {
1390                     audio_mixdown = HB_AMIXDOWN_MONO;
1391                 }
1392                 else if( !strcasecmp( optarg, "stereo" ) )
1393                 {
1394                     audio_mixdown = HB_AMIXDOWN_STEREO;
1395                 }
1396                 else if( !strcasecmp( optarg, "dpl1" ) )
1397                 {
1398                     audio_mixdown = HB_AMIXDOWN_DOLBY;
1399                 }
1400                 else if( !strcasecmp( optarg, "dpl2" ) )
1401                 {
1402                     audio_mixdown = HB_AMIXDOWN_DOLBYPLII;
1403                 }
1404                 else if( !strcasecmp( optarg, "6ch" ) )
1405                 {
1406                     audio_mixdown = HB_AMIXDOWN_6CH;
1407                 }
1408                 break;
1409             case 's':
1410                 sub = atoi( optarg );
1411                 break;
1412             case 'U':
1413                 subtitle_scan = 1;
1414                 break;
1415             case 'F':
1416                 subtitle_force = 1;
1417                 break;
1418             case 'N':
1419                 native_language = strdup( optarg );
1420                 break;
1421             case '2':
1422                 twoPass = 1;
1423                 break;
1424             case 'd':
1425                 if( optarg != NULL )
1426                 {
1427                     if (!( strcmp( optarg, "fast" ) ))
1428                     {
1429                         deinterlace_opt = "-1";
1430                     }
1431                     else if (!( strcmp( optarg, "slow" ) ))
1432                     {
1433                         deinterlace_opt = "0";
1434                     }
1435                     else if (!( strcmp( optarg, "slower" ) ))
1436                     {
1437                         deinterlace_opt = "2:-1:1";
1438                     }
1439                     else if (!( strcmp( optarg, "slowest" ) ))
1440                     {
1441                         deinterlace_opt = "1:-1:1";
1442                     }
1443                     else
1444                     {
1445                         deinterlace_opt = strdup( optarg );
1446                     }
1447                 }
1448                 deinterlace = 1;
1449                 break;
1450             case '7':
1451                 if( optarg != NULL )
1452                 {
1453                     deblock_opt = strdup( optarg );
1454                 }
1455                 deblock = 1;
1456                 break;
1457             case '8':
1458                 if( optarg != NULL )
1459                 {
1460                     if (!( strcmp( optarg, "weak" ) ))
1461                     {
1462                         denoise_opt = "2:1:2:3";
1463                     }
1464                     else if (!( strcmp( optarg, "medium" ) ))
1465                     {
1466                         denoise_opt = "3:2:2:3";
1467                     }
1468                     else if (!( strcmp( optarg, "strong" ) ))
1469                     {
1470                         denoise_opt = "7:7:5:5";
1471                     }
1472                     else
1473                     {
1474                         denoise_opt = strdup( optarg );
1475                     }
1476                 }
1477                 denoise = 1;
1478                 break;                
1479             case '9':
1480                 if( optarg != NULL )
1481                 {
1482                     detelecine_opt = strdup( optarg );
1483                 }
1484                 detelecine = 1;
1485                 break;                
1486             case 'g':
1487                 grayscale = 1;
1488                 break;
1489             case 'p':
1490                 pixelratio = 1;
1491                 break;
1492             case 'P':
1493                 loosePixelratio = 1;
1494                 if( optarg != NULL )
1495                 {
1496                     modulus = atoi( optarg );
1497                 }
1498                 break;
1499             case 'e':
1500                 if( !strcasecmp( optarg, "ffmpeg" ) )
1501                 {
1502                     vcodec = HB_VCODEC_FFMPEG;
1503                 }
1504                 else if( !strcasecmp( optarg, "xvid" ) )
1505                 {
1506                     vcodec = HB_VCODEC_XVID;
1507                 }
1508                 else if( !strcasecmp( optarg, "x264" ) )
1509                 {
1510                     vcodec = HB_VCODEC_X264;
1511                 }
1512                 else if( !strcasecmp( optarg, "x264b13" ) )
1513                 {
1514                     vcodec = HB_VCODEC_X264;
1515                     h264_13 = 1;
1516                 }
1517                 else if( !strcasecmp( optarg, "x264b30" ) )
1518                 {
1519                     vcodec = HB_VCODEC_X264;
1520                     h264_30 = 1;
1521                 }
1522                 else
1523                 {
1524                     fprintf( stderr, "invalid codec (%s)\n", optarg );
1525                     return -1;
1526                 }
1527                 break;
1528             case 'E':
1529                 if( !strcasecmp( optarg, "ac3" ) )
1530                 {
1531                     acodec = HB_ACODEC_AC3;
1532                 }
1533                 else if( !strcasecmp( optarg, "lame" ) )
1534                 {
1535                     acodec = HB_ACODEC_LAME;
1536                 }
1537                 else if( !strcasecmp( optarg, "faac" ) )
1538                 {
1539                     acodec = HB_ACODEC_FAAC;
1540                 }
1541                 else if( !strcasecmp( optarg, "vorbis") )
1542                 {
1543                     acodec = HB_ACODEC_VORBIS;
1544                 }
1545                 break;
1546             case 'w':
1547                 width = atoi( optarg );
1548                 break;
1549             case 'l':
1550                 height = atoi( optarg );
1551                 break;
1552             case 'n':
1553             {
1554                 int    i;
1555                 char * tmp = optarg;
1556                 for( i = 0; i < 4; i++ )
1557                 {
1558                     if( !*tmp )
1559                         break;
1560                     crop[i] = strtol( tmp, &tmp, 0 );
1561                     tmp++;
1562                 }
1563                 break;
1564             }
1565             case 'r':
1566             {
1567                 int i;
1568                 vrate = 0;
1569                 for( i = 0; i < hb_video_rates_count; i++ )
1570                 {
1571                     if( !strcmp( optarg, hb_video_rates[i].string ) )
1572                     {
1573                         vrate = hb_video_rates[i].rate;
1574                         break;
1575                     }
1576                 }
1577                 if( !vrate )
1578                 {
1579                     fprintf( stderr, "invalid framerate %s\n", optarg );
1580                 }
1581                 break;
1582             }
1583             case 'R':
1584             {
1585                 int i;
1586                 arate = 0;
1587                 for( i = 0; i < hb_audio_rates_count; i++ )
1588                 {
1589                     if( !strcmp( optarg, hb_audio_rates[i].string ) )
1590                     {
1591                         arate = hb_audio_rates[i].rate;
1592                         break;
1593                     }
1594                 }
1595                 if( !arate )
1596                 {
1597                     fprintf( stderr, "invalid framerate %s\n", optarg );
1598                 }
1599                 break;
1600             }
1601             case 'b':
1602                 vbitrate = atoi( optarg );
1603                 break;
1604             case 'q':
1605                 vquality = atof( optarg );
1606                 break;
1607             case 'S':
1608                 size = atoi( optarg );
1609                 break;
1610             case 'B':
1611                 abitrate = atoi( optarg );
1612                 break;
1613             case 'Q':
1614                 crf = 1;
1615                 break;
1616             case 'x':
1617                 x264opts = strdup( optarg );
1618                 break;
1619             case 'T':
1620                 turbo_opts_enabled = 1;
1621                 break;
1622             case 'Y':
1623                 maxHeight = atoi( optarg );
1624                 break;
1625             case 'X':
1626                 maxWidth = atoi (optarg );
1627                 break;
1628             case 'V':
1629                 vfr = 1;
1630                 break;
1631                                 
1632             default:
1633                 fprintf( stderr, "unknown option (%s)\n", argv[optind] );
1634                 return -1;
1635         }
1636     }
1637
1638     return 0;
1639 }
1640
1641 static int CheckOptions( int argc, char ** argv )
1642 {
1643     if( update )
1644     {
1645         return 0;
1646     }
1647
1648     if( input == NULL || *input == '\0' )
1649     {
1650         fprintf( stderr, "Missing input device. Run %s --help for "
1651                  "syntax.\n", argv[0] );
1652         return 1;
1653     }
1654
1655     /* Parse format */
1656     if( titleindex > 0 )
1657     {
1658         if( output == NULL || *output == '\0' )
1659         {
1660             fprintf( stderr, "Missing output file name. Run %s --help "
1661                      "for syntax.\n", argv[0] );
1662             return 1;
1663         }
1664
1665         if( !format )
1666         {
1667             char * p = strrchr( output, '.' );
1668
1669             /* autodetect */
1670             if( p && !strcasecmp( p, ".avi" ) )
1671             {
1672                 mux = HB_MUX_AVI;
1673             }
1674             else if( p && ( !strcasecmp( p, ".mp4" )  ||
1675                             !strcasecmp( p, ".m4v" ) ) )
1676             {
1677                 if ( h264_30 == 1 )
1678                     mux = HB_MUX_IPOD;
1679                 else
1680                     mux = HB_MUX_MP4;
1681             }
1682             else if( p && ( !strcasecmp( p, ".ogm" ) ||
1683                             !strcasecmp( p, ".ogg" ) ) )
1684             {
1685                 mux = HB_MUX_OGM;
1686             }
1687             else if( p && !strcasecmp(p, ".mkv" ) )
1688             {
1689                 mux = HB_MUX_MKV;
1690             }
1691             else
1692             {
1693                 fprintf( stderr, "Output format couldn't be guessed "
1694                          "from file name, using default.\n" );
1695                 return 0;
1696             }
1697         }
1698         else if( !strcasecmp( format, "avi" ) )
1699         {
1700             mux = HB_MUX_AVI;
1701         }
1702         else if( !strcasecmp( format, "mp4" ) )
1703         {
1704             if ( h264_30 == 1)
1705                 mux = HB_MUX_IPOD;
1706             else
1707                 mux = HB_MUX_MP4;
1708         }
1709         else if( !strcasecmp( format, "ogm" ) ||
1710                  !strcasecmp( format, "ogg" ) )
1711         {
1712             mux = HB_MUX_OGM;
1713         }
1714         else if( !strcasecmp( format, "mkv" ) )
1715         {
1716             mux = HB_MUX_MKV;
1717         }
1718         else
1719         {
1720             fprintf( stderr, "Invalid output format (%s). Possible "
1721                      "choices are avi, mp4, m4v, ogm, ogg and mkv\n.", format );
1722             return 1;
1723         }
1724
1725         if( !acodec )
1726         {
1727             if( mux == HB_MUX_MP4 || mux == HB_MUX_IPOD )
1728             {
1729                 acodec = HB_ACODEC_FAAC;
1730             }
1731             else if( mux == HB_MUX_AVI )
1732             {
1733                 acodec = HB_ACODEC_LAME;
1734             }
1735             else if( mux == HB_MUX_OGM )
1736             {
1737                 acodec = HB_ACODEC_VORBIS;
1738             }
1739             else if( mux == HB_MUX_MKV )
1740             {
1741                 acodec = HB_ACODEC_AC3;
1742             }
1743         }
1744
1745     }
1746
1747     return 0;
1748 }