OSDN Git Service

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