OSDN Git Service

Don't crash when the user specifies audio tracks that don't exist from the HandBrakeCLI
[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.fr/>.
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 #ifdef __APPLE_CC__
17 #import <CoreServices/CoreServices.h>
18 #include <IOKit/IOKitLib.h>
19 #include <IOKit/storage/IOMedia.h>
20 #include <IOKit/storage/IODVDMedia.h>
21 #endif
22
23 /* Options */
24 static int    debug       = HB_DEBUG_NONE;
25 static int    update      = 0;
26 static char * input       = NULL;
27 static char * output      = NULL;
28 static char * format      = NULL;
29 static int    titleindex  = 1;
30 static int    longest_title = 0;
31 static int    subtitle_scan = 0;
32 static int    subtitle_force = 0;
33 static char * native_language = NULL;
34 static int    twoPass     = 0;
35 static int    deinterlace           = 0;
36 static char * deinterlace_opt       = 0;
37 static int    deblock               = 0;
38 static char * deblock_opt           = 0;
39 static int    denoise               = 0;
40 static char * denoise_opt           = 0;
41 static int    detelecine            = 0;
42 static char * detelecine_opt        = 0;
43 static int    decomb                = 0;
44 static char * decomb_opt            = 0;
45 static int    grayscale   = 0;
46 static int    vcodec      = HB_VCODEC_FFMPEG;
47 static int    h264_13     = 0;
48 static int    h264_30     = 0;
49 static hb_list_t * audios = NULL;
50 static hb_audio_config_t * audio = NULL;
51 static int    num_audio_tracks = 0;
52 static char * mixdowns    = NULL;
53 static char * dynamic_range_compression = NULL;
54 static char * atracks     = NULL;
55 static char * arates      = NULL;
56 static char * abitrates   = NULL;
57 static char * acodecs     = NULL;
58 static int    default_acodec = HB_ACODEC_FAAC;
59 static int    default_arate = 48000;
60 static int    default_abitrate = 160;
61 static int    sub         = 0;
62 static int    width       = 0;
63 static int    height      = 0;
64 static int    crop[4]     = { -1,-1,-1,-1 };
65 static int    cpu         = 0;
66 static int    vrate       = 0;
67 static float  vquality    = -1.0;
68 static int    vbitrate    = 0;
69 static int    size        = 0;
70 static int    mux         = 0;
71 static int    pixelratio  = 0;
72 static int    loosePixelratio = 0;
73 static int    modulus       = 0;
74 static int    par_height    = 0;
75 static int    par_width     = 0;
76 static int    chapter_start = 0;
77 static int    chapter_end   = 0;
78 static int    chapter_markers = 0;
79 static char * marker_file   = NULL;
80 static int        crf                   = 1;
81 static char       *x264opts             = NULL;
82 static char       *x264opts2    = NULL;
83 static int        maxHeight             = 0;
84 static int        maxWidth              = 0;
85 static int    turbo_opts_enabled = 0;
86 static char * turbo_opts = "ref=1:subme=1:me=dia:analyse=none:trellis=0:no-fast-pskip=0:8x8dct=0:weightb=0";
87 static int    largeFileSize = 0;
88 static int    preset        = 0;
89 static char * preset_name   = 0;
90 static int    vfr           = 0;
91 static int    cfr           = 0;
92 static int    mp4_optimize  = 0;
93 static int    ipod_atom     = 0;
94
95 /* Exit cleanly on Ctrl-C */
96 static volatile int die = 0;
97 static void SigHandler( int );
98
99 /* Utils */
100 static void ShowCommands();
101 static void ShowHelp();
102 static void ShowPresets();
103
104 static int  ParseOptions( int argc, char ** argv );
105 static int  CheckOptions( int argc, char ** argv );
106 static int  HandleEvents( hb_handle_t * h );
107
108 static int get_acodec_for_string( char *codec );
109 static int is_sample_rate_valid(int rate);
110
111 #ifdef __APPLE_CC__
112 static char* bsd_name_for_path(char *path);
113 static int device_is_dvd(char *device);
114 static io_service_t get_iokit_service( char *device );
115 static int is_dvd_service( io_service_t service );
116 static is_whole_media_service( io_service_t service );
117 #endif
118
119 /* Only print the "Muxing..." message once */
120 static int show_mux_warning = 1;
121
122 /****************************************************************************
123  * hb_error_handler
124  *
125  * When using the CLI just display using hb_log as we always did in the past
126  * make sure that we prefix with a nice ERROR message to catch peoples eyes.
127  ****************************************************************************/
128 static void hb_cli_error_handler ( const char *errmsg )
129 {
130     fprintf( stderr, "ERROR: %s\n", errmsg );
131 }
132
133 int main( int argc, char ** argv )
134 {
135     hb_handle_t * h;
136     int           build;
137     char        * version;
138
139     audios = hb_list_init();
140
141     /* Parse command line */
142     if( ParseOptions( argc, argv ) ||
143         CheckOptions( argc, argv ) )
144     {
145         return 1;
146     }
147
148     /* Register our error handler */
149     hb_register_error_handler(&hb_cli_error_handler);
150
151     /* Init libhb */
152     h = hb_init( debug, update );
153
154     /* Show version */
155     fprintf( stderr, "HandBrake %s (%d) - http://handbrake.fr/\n",
156              hb_get_version( h ), hb_get_build( h ) );
157
158     /* Check for update */
159     if( update )
160     {
161         if( ( build = hb_check_update( h, &version ) ) > -1 )
162         {
163             fprintf( stderr, "You are using an old version of "
164                      "HandBrake.\nLatest is %s (build %d).\n", version,
165                      build );
166         }
167         else
168         {
169             fprintf( stderr, "Your version of HandBrake is up to "
170                      "date.\n" );
171         }
172         hb_close( &h );
173         return 0;
174     }
175
176     /* Geeky */
177     fprintf( stderr, "%d CPU%s detected\n", hb_get_cpu_count(),
178              hb_get_cpu_count( h ) > 1 ? "s" : "" );
179     if( cpu )
180     {
181         fprintf( stderr, "Forcing %d CPU%s\n", cpu,
182                  cpu > 1 ? "s" : "" );
183         hb_set_cpu_count( h, cpu );
184     }
185
186     /* Exit ASAP on Ctrl-C */
187     signal( SIGINT, SigHandler );
188
189     /* Feed libhb with a DVD to scan */
190     fprintf( stderr, "Opening %s...\n", input );
191
192     if (longest_title) {
193         /*
194          * We need to scan for all the titles in order to find the longest
195          */
196         titleindex = 0;
197     }
198     hb_scan( h, input, titleindex );
199
200     /* Wait... */
201     while( !die )
202     {
203 #if !defined(SYS_BEOS)
204         fd_set         fds;
205         struct timeval tv;
206         int            ret;
207         char           buf[257];
208
209         tv.tv_sec  = 0;
210         tv.tv_usec = 100000;
211
212         FD_ZERO( &fds );
213         FD_SET( STDIN_FILENO, &fds );
214         ret = select( STDIN_FILENO + 1, &fds, NULL, NULL, &tv );
215
216         if( ret > 0 )
217         {
218             int size = 0;
219
220             while( size < 256 &&
221                    read( STDIN_FILENO, &buf[size], 1 ) > 0 )
222             {
223                 if( buf[size] == '\n' )
224                 {
225                     break;
226                 }
227                 size++;
228             }
229
230             if( size >= 256 || buf[size] == '\n' )
231             {
232                 switch( buf[0] )
233                 {
234                     case 'q':
235                         fprintf( stdout, "\nEncoding Quit by user command\n" );
236                         die = 1;
237                         break;
238                     case 'p':
239                         fprintf( stdout, "\nEncoding Paused by user command, 'r' to resume\n" );
240                         hb_pause( h );
241                         break;
242                     case 'r':
243                         hb_resume( h );
244                         break;
245                     case 'h':
246                         ShowCommands();
247                         break;
248                 }
249             }
250         }
251         hb_snooze( 200 );
252 #else
253         hb_snooze( 200 );
254 #endif
255
256         HandleEvents( h );
257     }
258
259     /* Clean up */
260     hb_close( &h );
261     if( input )  free( input );
262     if( output ) free( output );
263     if( format ) free( format );
264     if( audios )
265     {
266         while( ( audio = hb_list_item( audios, 0 ) ) )
267         {
268             hb_list_rem( audios, audio );
269             free( audio );
270         }
271         hb_list_close( &audios );
272     }
273     if( mixdowns ) free( mixdowns );
274     if( dynamic_range_compression ) free( dynamic_range_compression );
275     if( atracks ) free( atracks );
276     if( arates ) free( arates );
277     if( abitrates ) free( abitrates );
278     if( acodecs ) free( acodecs );
279     if (native_language ) free (native_language );
280         if( x264opts ) free (x264opts );
281         if( x264opts2 ) free (x264opts2 );
282     if (preset_name) free (preset_name);
283
284     fprintf( stderr, "HandBrake has exited.\n" );
285
286     return 0;
287 }
288
289 static void ShowCommands()
290 {
291     fprintf( stdout, "\nCommands:\n" );
292     fprintf( stdout, " [h]elp    Show this message\n" );
293     fprintf( stdout, " [q]uit    Exit HandBrakeCLI\n" );
294     fprintf( stdout, " [p]ause   Pause encoding\n" );
295     fprintf( stdout, " [r]esume  Resume encoding\n" );
296 }
297
298 static void PrintTitleInfo( hb_title_t * title )
299 {
300     hb_chapter_t  * chapter;
301     hb_audio_config_t    * audio;
302     hb_subtitle_t * subtitle;
303     int i;
304
305     fprintf( stderr, "+ title %d:\n", title->index );
306     fprintf( stderr, "  + vts %d, ttn %d, cells %d->%d (%d blocks)\n",
307              title->vts, title->ttn, title->cell_start, title->cell_end,
308              title->block_count );
309     fprintf( stderr, "  + duration: %02d:%02d:%02d\n",
310              title->hours, title->minutes, title->seconds );
311     fprintf( stderr, "  + size: %dx%d, aspect: %.2f, %.3f fps\n",
312              title->width, title->height,
313              (float) title->aspect,
314              (float) title->rate / title->rate_base );
315     fprintf( stderr, "  + autocrop: %d/%d/%d/%d\n", title->crop[0],
316              title->crop[1], title->crop[2], title->crop[3] );
317     fprintf( stderr, "  + chapters:\n" );
318     for( i = 0; i < hb_list_count( title->list_chapter ); i++ )
319     {
320         chapter = hb_list_item( title->list_chapter, i );
321         fprintf( stderr, "    + %d: cells %d->%d, %d blocks, duration "
322                  "%02d:%02d:%02d\n", chapter->index,
323                  chapter->cell_start, chapter->cell_end,
324                  chapter->block_count, chapter->hours, chapter->minutes,
325                  chapter->seconds );
326     }
327     fprintf( stderr, "  + audio tracks:\n" );
328     for( i = 0; i < hb_list_count( title->list_audio ); i++ )
329     {
330         audio = hb_list_audio_config_item( title->list_audio, i );
331         if( ( audio->in.codec == HB_ACODEC_AC3 ) || ( audio->in.codec == HB_ACODEC_DCA) )
332         {
333             fprintf( stderr, "    + %d, %s, %dHz, %dbps\n", i + 1,
334                      audio->lang.description, audio->in.samplerate, audio->in.bitrate );
335         }
336         else
337         {
338             fprintf( stderr, "    + %d, %s\n", i + 1, audio->lang.description );
339         }
340     }
341     fprintf( stderr, "  + subtitle tracks:\n" );
342     for( i = 0; i < hb_list_count( title->list_subtitle ); i++ )
343     {
344         subtitle = hb_list_item( title->list_subtitle, i );
345         fprintf( stderr, "    + %d, %s (iso639-2: %s)\n", i + 1, subtitle->lang,
346             subtitle->iso639_2);
347     }
348
349     if(title->detected_interlacing)
350     {
351         /* Interlacing was found in half or more of the preview frames */
352         fprintf( stderr, "  + combing detected, may be interlaced or telecined\n");
353     }
354
355 }
356
357 static int HandleEvents( hb_handle_t * h )
358 {
359     hb_state_t s;
360     hb_get_state( h, &s );
361     switch( s.state )
362     {
363         case HB_STATE_IDLE:
364             /* Nothing to do */
365             break;
366
367 #define p s.param.scanning
368         case HB_STATE_SCANNING:
369             /* Show what title is currently being scanned */
370             fprintf( stderr, "Scanning title %d", p.title_cur );
371             if( !titleindex )
372                 fprintf( stderr, " of %d", p.title_count );
373             fprintf( stderr, "...\n" );
374             break;
375 #undef p
376
377         case HB_STATE_SCANDONE:
378         {
379             hb_list_t  * list;
380             hb_title_t * title;
381             hb_job_t   * job;
382             int i;
383
384             /* Audio argument string parsing variables */
385             int acodec = 0;
386             int abitrate = 0;
387             int arate = 0;
388             int mixdown = HB_AMIXDOWN_DOLBYPLII;
389             double d_r_c = 0;
390             /* Audio argument string parsing variables */
391
392             list = hb_get_titles( h );
393
394             if( !hb_list_count( list ) )
395             {
396                 /* No valid title, stop right there */
397                 fprintf( stderr, "No title found.\n" );
398                 die = 1;
399                 break;
400             }
401             if( longest_title )
402             {
403                 int i;
404                 int longest_title_idx=0;
405                 int longest_title_pos=-1;
406                 int longest_title_time=0;
407                 int title_time;
408
409                 fprintf( stderr, "Searching for longest title...\n" );
410
411                 for( i = 0; i < hb_list_count( list ); i++ )
412                 {
413                     title = hb_list_item( list, i );
414                     title_time = (title->hours*60*60 ) + (title->minutes *60) + (title->seconds);
415                     fprintf( stderr, " + Title (%d) index %d has length %dsec\n",
416                              i, title->index, title_time );
417                     if( longest_title_time < title_time )
418                     {
419                         longest_title_time = title_time;
420                         longest_title_pos = i;
421                         longest_title_idx = title->index;
422                     }
423                 }
424                 if( longest_title_pos == -1 )
425                 {
426                     fprintf( stderr, "No longest title found.\n" );
427                     die = 1;
428                     break;
429                 }
430                 titleindex = longest_title_idx;
431                 fprintf( stderr, "Found longest title, setting title to %d\n",
432                          longest_title_idx);
433
434                 title = hb_list_item( list, longest_title_pos);
435             } else {
436                 title = hb_list_item( list, 0 );
437             }
438
439             if( !titleindex )
440             {
441                 /* Scan-only mode, print infos and exit */
442                 int i;
443                 for( i = 0; i < hb_list_count( list ); i++ )
444                 {
445                     title = hb_list_item( list, i );
446                     PrintTitleInfo( title );
447                 }
448                 die = 1;
449                 break;
450             }
451
452             /* Set job settings */
453             job   = title->job;
454
455             PrintTitleInfo( title );
456
457             if( chapter_start && chapter_end )
458             {
459                 job->chapter_start = MAX( job->chapter_start,
460                                           chapter_start );
461                 job->chapter_end   = MIN( job->chapter_end,
462                                           chapter_end );
463                 job->chapter_end   = MAX( job->chapter_start,
464                                           job->chapter_end );
465             }
466
467             if (preset)
468             {
469                 fprintf( stderr, "+ Using preset: %s", preset_name);
470
471                 if (!strcmp(preset_name, "Animation"))
472                 {
473                     mux = HB_MUX_MKV;
474                     vcodec = HB_VCODEC_X264;
475                     job->vbitrate = 1000;
476                     default_abitrate = 160;
477                     default_acodec = HB_ACODEC_FAAC;
478                     x264opts = strdup("ref=5:mixed-refs:bframes=6: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");
479                     deinterlace = 1;
480                     deinterlace_opt = "0";
481                     job->chapter_markers = 1;
482                     pixelratio = 1;
483                     twoPass = 1;
484                     turbo_opts_enabled = 1;
485                 }
486
487                 if (!strcmp(preset_name, "AppleTV"))
488                 {
489                     if (!acodecs)
490                     {
491                         acodecs = strdup("faac,ac3");
492                     }
493
494                     mux = HB_MUX_MP4;
495                     job->largeFileSize = 1;
496                     vcodec = HB_VCODEC_X264;
497                     job->vbitrate = 2500;
498                     default_abitrate = 160;
499                     default_arate = 48000;
500                     default_acodec = HB_ACODEC_FAAC;
501                     x264opts = strdup("bframes=3:ref=1:subme=5:me=umh:no-fast-pskip=1:trellis=1:cabac=0");
502                     job->chapter_markers = 1;
503                     pixelratio = 1;
504                 }
505
506                 if (!strcmp(preset_name, "Bedlam"))
507                 {
508                     mux = HB_MUX_MKV;
509                     vcodec = HB_VCODEC_X264;
510                     job->vbitrate = 1800;
511                     default_acodec = HB_ACODEC_AC3;
512                     x264opts = strdup("ref=16:mixed-refs:bframes=16:bime:weightb:b-rdo:direct=auto:b-pyramid:me=esa:subme=7:me-range=64:analyse=all:8x8dct:trellis=1:no-fast-pskip:no-dct-decimate:filter=-2,-1");
513                     job->chapter_markers = 1;
514                     pixelratio = 1;
515                     twoPass = 1;
516                     turbo_opts_enabled = 1;
517                 }
518
519                 if (!strcmp(preset_name, "Blind"))
520                 {
521                     mux = HB_MUX_MP4;
522                     job->vbitrate = 512;
523                     default_abitrate = 128;
524                     default_acodec = HB_ACODEC_FAAC;
525                     job->width = 512;
526                     job->chapter_markers = 1;
527                 }
528
529                 if (!strcmp(preset_name, "Broke"))
530                 {
531                     mux = HB_MUX_MP4;
532                     vcodec = HB_VCODEC_X264;
533                     size = 695;
534                     default_abitrate = 128;
535                     default_acodec = HB_ACODEC_FAAC;
536                     job->width = 640;
537                     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");
538                     job->chapter_markers = 1;
539                     twoPass = 1;
540                     turbo_opts_enabled = 1;
541                 }
542
543                 if (!strcmp(preset_name, "Classic"))
544                 {
545                     mux = HB_MUX_MP4;
546                     job->vbitrate = 1000;
547                     default_abitrate = 160;
548                     default_acodec = HB_ACODEC_FAAC;
549                 }
550
551                 if (!strcmp(preset_name, "Constant Quality Rate"))
552                 {
553                     mux = HB_MUX_MKV;
554                     vcodec = HB_VCODEC_X264;
555                     job->vquality = 0.64709997177124023;
556                     job->crf = 1;
557                     default_acodec = HB_ACODEC_AC3;
558                     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");
559                     job->chapter_markers = 1;
560                     pixelratio = 1;
561                 }
562
563                 if (!strcmp(preset_name, "Deux Six Quatre"))
564                 {
565                     mux = HB_MUX_MKV;
566                     vcodec = HB_VCODEC_X264;
567                     job->vbitrate = 1600;
568                     default_acodec = HB_ACODEC_AC3;
569                     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");
570                     job->chapter_markers = 1;
571                     pixelratio = 1;
572                     twoPass = 1;
573                     turbo_opts_enabled = 1;
574                 }
575
576                 if (!strcmp(preset_name, "Film"))
577                 {
578                     mux = HB_MUX_MKV;
579                     vcodec = HB_VCODEC_X264;
580                     job->vbitrate = 1800;
581                     default_acodec = HB_ACODEC_AC3;
582                     x264opts = strdup("ref=3:mixed-refs:bframes=6:bime:weightb:b-rdo:direct=auto:b-pyramid:me=umh:subme=7:analyse=all:8x8dct:trellis=1:no-fast-pskip");
583                     job->chapter_markers = 1;
584                     pixelratio = 1;
585                     twoPass = 1;
586                     turbo_opts_enabled = 1;
587                 }
588
589                 if (!strcmp(preset_name, "iPhone / iPod Touch"))
590                 {
591                     mux = HB_MUX_MP4;
592                     job->ipod_atom = 1;
593                     vcodec = HB_VCODEC_X264;
594                     job->vbitrate = 960;
595                     default_abitrate = 128;
596                     default_arate = 48000;
597                     default_acodec = HB_ACODEC_FAAC;
598                     job->width = 480;
599                     x264opts = strdup("level=30:cabac=0:ref=1:analyse=all:me=umh:subme=6:no-fast-pskip=1:trellis=1");
600                     job->chapter_markers = 1;
601                 }
602
603                 if (!strcmp(preset_name, "iPod High-Rez"))
604                 {
605                     mux = HB_MUX_MP4;
606                     job->ipod_atom = 1;
607                     vcodec = HB_VCODEC_X264;
608                     job->vbitrate = 1500;
609                     default_abitrate = 160;
610                     default_arate = 48000;
611                     default_acodec = HB_ACODEC_FAAC;
612                     job->width = 640;
613                     x264opts = strdup("level=30:bframes=0:cabac=0:ref=1:vbv-maxrate=1500:vbv-bufsize=2000:analyse=all:me=umh:subme=6:no-fast-pskip=1");
614                     job->chapter_markers = 1;
615                 }
616
617                 if (!strcmp(preset_name, "iPod Low-Rez"))
618                 {
619                     mux = HB_MUX_MP4;
620                     job->ipod_atom = 1;
621                     vcodec = HB_VCODEC_X264;
622                     job->vbitrate = 700;
623                     default_abitrate = 160;
624                     default_arate = 48000;
625                     default_acodec = HB_ACODEC_FAAC;
626                     job->width = 320;
627                     x264opts = strdup("level=30:bframes=0:cabac=0:ref=1:vbv-maxrate=768:vbv-bufsize=2000:analyse=all:me=umh:subme=6:no-fast-pskip=1");
628                     job->chapter_markers = 1;
629                 }
630
631                 if (!strcmp(preset_name, "Normal"))
632                 {
633                     mux = HB_MUX_MP4;
634                     vcodec = HB_VCODEC_X264;
635                     job->vbitrate = 1500;
636                     default_abitrate = 160;
637                     default_acodec = HB_ACODEC_FAAC;
638                     x264opts = strdup("ref=2:bframes=2:subme=5:me=umh");
639                     job->chapter_markers = 1;
640                     pixelratio = 1;
641                     twoPass = 1;
642                     turbo_opts_enabled = 1;
643                 }
644
645                 if (!strcmp(preset_name, "PS3"))
646                 {
647                     mux = HB_MUX_MP4;
648                     vcodec = HB_VCODEC_X264;
649                     job->vbitrate = 2500;
650                     default_abitrate = 160;
651                     default_acodec = HB_ACODEC_FAAC;
652                     x264opts = strdup("level=41:subme=5:me=umh");
653                     pixelratio = 1;
654                 }
655
656                 if (!strcmp(preset_name, "PSP"))
657                 {
658                     mux = HB_MUX_MP4;
659                     job->vbitrate = 1024;
660                     default_abitrate = 128;
661                     default_arate = 48000;
662                     default_acodec = HB_ACODEC_FAAC;
663                     job->width = 368;
664                     job->height = 208;
665                     job->chapter_markers = 1;
666                 }
667
668                 if (!strcmp(preset_name, "QuickTime"))
669                 {
670                     mux = HB_MUX_MP4;
671                     vcodec = HB_VCODEC_X264;
672                     job->vbitrate = 2000;
673                     default_abitrate = 160;
674                     default_acodec = HB_ACODEC_FAAC;
675                     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");
676                     job->chapter_markers = 1;
677                     pixelratio = 1;
678                     twoPass = 1;
679                     turbo_opts_enabled = 1;
680                 }
681
682                 if (!strcmp(preset_name, "Television"))
683                 {
684                     mux = HB_MUX_MKV;
685                     vcodec = HB_VCODEC_X264;
686                     job->vbitrate = 1300;
687                     default_abitrate = 160;
688                     default_acodec = HB_ACODEC_FAAC;
689                     x264opts = strdup("ref=3:mixed-refs:bframes=6:bime:weightb:direct=auto:b-pyramid:me=umh:subme=6:analyse=all:8x8dct:trellis=1:nr=150:no-fast-pskip");
690                     deinterlace = 1;
691                     deinterlace_opt = "0";
692                     denoise = 1;
693                     denoise_opt = "2:1:2:3";
694                     job->chapter_markers = 1;
695                     twoPass = 1;
696                     turbo_opts_enabled = 1;
697                 }
698
699                 if (!strcmp(preset_name, "Xbox 360"))
700                 {
701                     mux = HB_MUX_MP4;
702                     vcodec = HB_VCODEC_X264;
703                     job->vbitrate = 2000;
704                     default_abitrate = 160;
705                     default_acodec = HB_ACODEC_FAAC;
706                     x264opts = strdup("level=40:ref=2:mixed-refs:bframes=3:bime:weightb:b-rdo:direct=auto:b-pyramid:me=umh:subme=5:analyse=all:no-fast-pskip:filter=-2,-1");
707                     pixelratio = 1;
708                 }
709             }
710
711                         if ( chapter_markers )
712                         {
713                                 job->chapter_markers = chapter_markers;
714
715                 if( marker_file != NULL )
716                 {
717                     hb_csv_file_t * file = hb_open_csv_file( marker_file );
718                     hb_csv_cell_t * cell;
719                     int row = 0;
720                     int chapter = 0;
721
722                     fprintf( stderr, "Reading chapter markers from file %s\n", marker_file );
723
724                     if( file == NULL )
725                     {
726                          fprintf( stderr, "Cannot open chapter marker file, using defaults\n" );
727                     }
728                     else
729                     {
730                         /* Parse the cells */
731                         while( NULL != ( cell = hb_read_next_cell( file ) ) )
732                         {
733                             /* We have a chapter number */
734                             if( cell->cell_col == 0 )
735                             {
736                                 row = cell->cell_row;
737                                 chapter = atoi( cell->cell_text );
738                             }
739
740                             /* We have a chapter name */
741                             if( cell->cell_col == 1 && row == cell->cell_row )
742                             {
743                                 /* If we have a valid chapter, copy the string an terminate it */
744                                 if( chapter >= job->chapter_start && chapter <= job->chapter_end )
745                                 {
746                                     hb_chapter_t * chapter_s;
747
748                                     chapter_s = hb_list_item( job->title->list_chapter, chapter - 1);
749                                     strncpy(chapter_s->title, cell->cell_text, 1023);
750                                     chapter_s->title[1023] = '\0';
751                                 }
752                             }
753
754
755                             hb_dispose_cell( cell );
756                         }
757
758                         hb_close_csv_file( file );
759                     }
760                 }
761                 else
762                 {
763                     /* No marker file */
764
765                     int number_of_chapters = hb_list_count(job->title->list_chapter);
766                     int chapter;
767
768                     for(chapter = 0; chapter <= number_of_chapters - 1 ; chapter++)
769                     {
770                         hb_chapter_t * chapter_s;
771                         chapter_s = hb_list_item( job->title->list_chapter, chapter);
772                         snprintf( chapter_s->title, 1023, "Chapter %i", chapter + 1 );
773                         chapter_s->title[1023] = '\0';
774                     }
775                 }
776                         }
777
778             if( crop[0] >= 0 && crop[1] >= 0 &&
779                 crop[2] >= 0 && crop[3] >= 0 )
780             {
781                 memcpy( job->crop, crop, 4 * sizeof( int ) );
782             }
783
784             job->deinterlace = deinterlace;
785             job->grayscale   = grayscale;
786             if (loosePixelratio)
787             {
788                 job->pixel_ratio = 2;
789                 if (modulus)
790                 {
791                     job->modulus = modulus;
792                 }
793                 if( par_width && par_height )
794                 {
795                     job->pixel_ratio = 3;
796                     job->pixel_aspect_width = par_width;
797                     job->pixel_aspect_height = par_height;
798                 }
799             }
800             else
801             {
802                 job->pixel_ratio = pixelratio;
803             }
804
805             if (vfr)
806             {
807                 detelecine = 1;
808                 job->vfr = 1;
809             }
810
811             /* Add selected filters */
812             job->filters = hb_list_init();
813             if( detelecine )
814             {
815                 hb_filter_detelecine.settings = detelecine_opt;
816                 hb_list_add( job->filters, &hb_filter_detelecine );
817             }
818             if( decomb )
819             {
820                 hb_filter_decomb.settings = decomb_opt;
821                 hb_list_add( job->filters, &hb_filter_decomb );
822             }
823             if( deinterlace )
824             {
825                 hb_filter_deinterlace.settings = deinterlace_opt;
826                 hb_list_add( job->filters, &hb_filter_deinterlace );
827             }
828             if( deblock )
829             {
830                 hb_filter_deblock.settings = deblock_opt;
831                 hb_list_add( job->filters, &hb_filter_deblock );
832             }
833             if( denoise )
834             {
835                 hb_filter_denoise.settings = denoise_opt;
836                 hb_list_add( job->filters, &hb_filter_denoise );
837             }
838
839             if( width && height )
840             {
841                 job->width  = width;
842                 job->height = height;
843             }
844             else if( width )
845             {
846                 job->width = width;
847                 hb_fix_aspect( job, HB_KEEP_WIDTH );
848             }
849             else if( height && !loosePixelratio)
850             {
851                 job->height = height;
852                 hb_fix_aspect( job, HB_KEEP_HEIGHT );
853             }
854             else if( !width && !height && !pixelratio && !loosePixelratio )
855             {
856                 hb_fix_aspect( job, HB_KEEP_WIDTH );
857             }
858             else if (!width && loosePixelratio)
859             {
860                 /* Default to full width when one isn't specified for loose anamorphic */
861                 job->width = title->width - job->crop[2] - job->crop[3];
862                 /* The height will be thrown away in hb.c but calculate it anyway */
863                 hb_fix_aspect( job, HB_KEEP_WIDTH );
864             }
865
866             if( vquality >= 0.0 && ( ( vquality <= 1.0 ) || ( vcodec == HB_VCODEC_X264 ) || (vcodec == HB_VCODEC_FFMPEG) ) )
867             {
868                 job->vquality = vquality;
869                 job->vbitrate = 0;
870             }
871             else if( vbitrate )
872             {
873                 job->vquality = -1.0;
874                 job->vbitrate = vbitrate;
875             }
876             if( vcodec )
877             {
878                 job->vcodec = vcodec;
879             }
880             if( h264_13 )
881             {
882                 job->h264_level = 13;
883             }
884                 if( h264_30 )
885                 {
886                     job->h264_level = 30;
887             }
888             if( vrate )
889             {
890                 job->cfr = 1;
891                 job->vrate = 27000000;
892                 job->vrate_base = vrate;
893             }
894
895             /* Grab audio tracks */
896             if( atracks )
897             {
898                 char * token = strtok(atracks, ",");
899                 if (token == NULL)
900                     token = optarg;
901                 int track_start, track_end;
902                 while( token != NULL )
903                 {
904                     audio = calloc(1, sizeof(*audio));
905                     hb_audio_config_init(audio);
906                     if (strlen(token) >= 3)
907                     {
908                         if (sscanf(token, "%d-%d", &track_start, &track_end) == 2)
909                         {
910                             int i;
911                             for (i = track_start - 1; i < track_end; i++)
912                             {
913                                 if (i != track_start - 1)
914                                 {
915                                     audio = calloc(1, sizeof(*audio));
916                                     hb_audio_config_init(audio);
917                                 }
918                                 audio->in.track = i;
919                                 audio->out.track = num_audio_tracks++;
920                                 hb_list_add(audios, audio);
921                             }
922                         }
923                         else if( !strcasecmp(token, "none" ) )
924                         {
925                             audio->in.track = audio->out.track = -1;
926                             audio->out.codec = 0;
927                             hb_list_add(audios, audio);
928                             break;
929                         }
930                         else
931                         {
932                             fprintf(stderr, "ERROR: Unable to parse audio input \"%s\", skipping.",
933                                     token);
934                             free(audio);
935                         }
936                     }
937                     else
938                     {
939                         audio->in.track = atoi(token) - 1;
940                         audio->out.track = num_audio_tracks++;
941                         hb_list_add(audios, audio);
942                     }
943                     token = strtok(NULL, ",");
944                 }
945             }
946
947             /* Parse audio tracks */
948             if( hb_list_count(audios) == 0 )
949             {
950                 /* Create a new audio track with default settings */
951                 audio = calloc(1, sizeof(*audio));
952                 hb_audio_config_init(audio);
953                 /* Add it to our audios */
954                 hb_list_add(audios, audio);
955             }
956
957             num_audio_tracks = hb_list_count(audios);
958             for (i = 0; i < num_audio_tracks; i++)
959             {
960                 audio = hb_list_item(audios, 0);
961                 if( (audio == NULL) || (audio->in.track == -1) ||
962                     (audio->out.track == -1) || (audio->out.codec == 0) )
963                 {
964                     num_audio_tracks--;
965                 }
966                 else
967                 {
968                     if( hb_audio_add( job, audio ) == 0 )
969                     {
970                         fprintf(stderr, "ERROR: Invalid audio input track '%u', skipping.\n", 
971                                 audio->in.track + 1 );
972                         num_audio_tracks--;
973                     }
974                 }
975                 hb_list_rem(audios, audio);
976                 if( audio != NULL)
977                     free( audio );
978             }
979             /* Audio Tracks */
980
981             /* Audio Codecs */
982             i = 0;
983             if( acodecs )
984             {
985                 char * token = strtok(acodecs, ",");
986                 if( token == NULL )
987                     token = acodecs;
988                 while ( token != NULL )
989                 {
990                     if ((acodec = get_acodec_for_string(token)) == -1)
991                     {
992                         fprintf(stderr, "Invalid codec %s, using default for container.\n", token);
993                         acodec = default_acodec;
994                     }
995                     if( i < num_audio_tracks )
996                     {
997                         audio = hb_list_audio_config_item(job->list_audio, i);
998                         audio->out.codec = acodec;
999                     }
1000                     else
1001                     {
1002                         hb_audio_config_t * last_audio = hb_list_audio_config_item( job->list_audio, i - 1 );
1003                         hb_audio_config_t audio;
1004
1005                         fprintf(stderr, "More audio codecs than audio tracks, copying track %i and using encoder %s\n",
1006                             i, token);
1007                         hb_audio_config_init(&audio);
1008                         audio.in.track = last_audio->in.track;
1009                         audio.out.track = num_audio_tracks++;
1010                         audio.out.codec = acodec;
1011                         hb_audio_add(job, &audio);
1012                     }
1013                     token = strtok(NULL, ",");
1014                     i++;
1015                 }
1016             }
1017             if( i < num_audio_tracks )
1018             {
1019                 /* We have fewer inputs than audio tracks, use the default codec for
1020                  * this container for the remaining tracks. Unless we only have one input
1021                  * then use that codec instead.
1022                  */
1023                 if (i != 1)
1024                     acodec = default_acodec;
1025                 for ( ; i < num_audio_tracks; i++)
1026                 {
1027                     audio = hb_list_audio_config_item(job->list_audio, i);
1028                     audio->out.codec = acodec;
1029                 }
1030             }
1031             /* Audio Codecs */
1032
1033             /* Sample Rate */
1034             i = 0;
1035             if( arates )
1036             {
1037                 char * token = strtok(arates, ",");
1038                 if (token == NULL)
1039                     token = arates;
1040                 while ( token != NULL )
1041                 {
1042                     arate = atoi(token);
1043                     audio = hb_list_audio_config_item(job->list_audio, i);
1044                     int j;
1045
1046                     for( j = 0; j < hb_audio_rates_count; j++ )
1047                     {
1048                         if( !strcmp( token, hb_audio_rates[j].string ) )
1049                         {
1050                             arate = hb_audio_rates[j].rate;
1051                             break;
1052                         }
1053                     }
1054
1055                     if (!is_sample_rate_valid(arate))
1056                     {
1057                         fprintf(stderr, "Invalid sample rate %d, using input rate %d\n", arate, audio->in.samplerate);
1058                         arate = audio->in.samplerate;
1059                     }
1060
1061                     audio->out.samplerate = arate;
1062                     if( (++i) >= num_audio_tracks )
1063                         break;  /* We have more inputs than audio tracks, oops */
1064                     token = strtok(NULL, ",");
1065                 }
1066             }
1067             if (i < num_audio_tracks)
1068             {
1069                 /* We have fewer inputs than audio tracks, use default sample rate.
1070                  * Unless we only have one input, then use that for all tracks.
1071                  */
1072                 if (i != 1)
1073                     arate = audio->in.samplerate;
1074                 for ( ; i < num_audio_tracks; i++)
1075                 {
1076                     audio = hb_list_audio_config_item(job->list_audio, i);
1077                     audio->out.samplerate = arate;
1078                 }
1079             }
1080             /* Sample Rate */
1081
1082             /* Audio Bitrate */
1083             i = 0;
1084             if( abitrates )
1085             {
1086                 char * token = strtok(abitrates, ",");
1087                 if (token == NULL)
1088                     token = abitrates;
1089                 while ( token != NULL )
1090                 {
1091                     abitrate = atoi(token);
1092                     audio = hb_list_audio_config_item(job->list_audio, i);
1093                     audio->out.bitrate = abitrate;
1094                     if( (++i) >= num_audio_tracks )
1095                         break;  /* We have more inputs than audio tracks, oops */
1096                     token = strtok(NULL, ",");
1097                 }
1098             }
1099             if (i < num_audio_tracks)
1100             {
1101                 /* We have fewer inputs than audio tracks, use the default bitrate
1102                  * for the remaining tracks. Unless we only have one input, then use
1103                  * that for all tracks.
1104                  */
1105                 if (i != 1)
1106                     abitrate = default_abitrate;
1107                 for (; i < num_audio_tracks; i++)
1108                 {
1109                     audio = hb_list_audio_config_item(job->list_audio, i);
1110                     audio->out.bitrate = abitrate;
1111                 }
1112             }
1113             /* Audio Bitrate */
1114
1115             /* Audio DRC */
1116             i = 0;
1117             if ( dynamic_range_compression )
1118             {
1119                 char * token = strtok(dynamic_range_compression, ",");
1120                 if (token == NULL)
1121                     token = dynamic_range_compression;
1122                 while ( token != NULL )
1123                 {
1124                     d_r_c = atof(token);
1125                     audio = hb_list_audio_config_item(job->list_audio, i);
1126                     audio->out.dynamic_range_compression = d_r_c;
1127                     if( (++i) >= num_audio_tracks )
1128                         break;  /* We have more inputs than audio tracks, oops */
1129                     token = strtok(NULL, ",");
1130                 }
1131             }
1132             if (i < num_audio_tracks)
1133             {
1134                 /* We have fewer inputs than audio tracks, use no DRC for the remaining
1135                  * tracks. Unless we only have one input, then use the same DRC for all
1136                  * tracks.
1137                  */
1138                 if (i != 1)
1139                     d_r_c = 0;
1140                 for (; i < num_audio_tracks; i++)
1141                 {
1142                     audio = hb_list_audio_config_item(job->list_audio, i);
1143                     audio->out.dynamic_range_compression = d_r_c;
1144                 }
1145             }
1146             /* Audio DRC */
1147
1148             /* Audio Mixdown */
1149             i = 0;
1150             if ( mixdowns )
1151             {
1152                 char * token = strtok(mixdowns, ",");
1153                 if (token == NULL)
1154                     token = mixdowns;
1155                 while ( token != NULL )
1156                 {
1157                     mixdown = hb_mixdown_get_mixdown_from_short_name(token);
1158                     audio = hb_list_audio_config_item(job->list_audio, i);
1159                     audio->out.mixdown = mixdown;
1160                     if( (++i) >= num_audio_tracks )
1161                         break;  /* We have more inputs than audio tracks, oops */
1162                     token = strtok(NULL, ",");
1163                 }
1164             }
1165             if (i < num_audio_tracks)
1166             {
1167                 /* We have fewer inputs than audio tracks, use DPLII for the rest. Unless
1168                  * we only have one input, then use that.
1169                  */
1170                 if (i != 1)
1171                     mixdown = HB_AMIXDOWN_DOLBYPLII;
1172                 for (; i < num_audio_tracks; i++)
1173                 {
1174                    audio = hb_list_audio_config_item(job->list_audio, i);
1175                    audio->out.mixdown = mixdown;
1176                 }
1177             }
1178             /* Audio Mixdown */
1179
1180             if( size )
1181             {
1182                 job->vbitrate = hb_calc_bitrate( job, size );
1183                 fprintf( stderr, "Calculated bitrate: %d kbps\n",
1184                          job->vbitrate );
1185             }
1186
1187             if( sub )
1188             {
1189                 job->subtitle = sub - 1;
1190             }
1191
1192             if( native_language )
1193             {
1194                 job->native_language = strdup( native_language );
1195             }
1196
1197             if( job->mux )
1198             {
1199                 job->mux = mux;
1200             }
1201
1202             if ( largeFileSize )
1203             {
1204                 job->largeFileSize = 1;
1205             }
1206             if ( mp4_optimize )
1207             {
1208                 job->mp4_optimize = 1;
1209             }
1210             if ( ipod_atom )
1211             {
1212                 job->ipod_atom = 1;
1213             }
1214
1215             job->file = strdup( output );
1216
1217             if( crf )
1218             {
1219                 job->crf = 1;
1220             }
1221
1222             if( x264opts != NULL && *x264opts != '\0' )
1223             {
1224                 job->x264opts = x264opts;
1225             }
1226             else /*avoids a bus error crash when options aren't specified*/
1227             {
1228                 job->x264opts =  NULL;
1229             }
1230             if (maxWidth)
1231                 job->maxWidth = maxWidth;
1232             if (maxHeight)
1233                 job->maxHeight = maxHeight;
1234
1235             if( subtitle_force )
1236             {
1237                 job->subtitle_force = subtitle_force;
1238             }
1239
1240             if( subtitle_scan )
1241             {
1242                 char *x264opts_tmp;
1243
1244                 /*
1245                  * When subtitle scan is enabled do a fast pre-scan job
1246                  * which will determine which subtitles to enable, if any.
1247                  */
1248                 job->pass = -1;
1249
1250                 x264opts_tmp = job->x264opts;
1251
1252                 job->x264opts = NULL;
1253
1254                 job->indepth_scan = subtitle_scan;
1255                 fprintf( stderr, "Subtitle Scan Enabled - enabling "
1256                          "subtitles if found for foreign language segments\n");
1257                 job->select_subtitle = malloc(sizeof(hb_subtitle_t*));
1258                 *(job->select_subtitle) = NULL;
1259
1260                 /*
1261                  * Add the pre-scan job
1262                  */
1263                 hb_add( h, job );
1264
1265                 job->x264opts = x264opts_tmp;
1266             }
1267
1268             if( twoPass )
1269             {
1270                 /*
1271                  * If subtitle_scan is enabled then only turn it on
1272                  * for the first pass and then off again for the
1273                  * second.
1274                  */
1275                 hb_subtitle_t **subtitle_tmp = job->select_subtitle;
1276
1277                 job->select_subtitle = NULL;
1278
1279                 job->pass = 1;
1280
1281                 job->indepth_scan = 0;
1282
1283                 if (x264opts)
1284                 {
1285                     x264opts2 = strdup(x264opts);
1286                 }
1287
1288                 /*
1289                  * If turbo options have been selected then append them
1290                  * to the x264opts now (size includes one ':' and the '\0')
1291                  */
1292                 if( turbo_opts_enabled )
1293                 {
1294                     int size = (x264opts ? strlen(x264opts) : 0) + strlen(turbo_opts) + 2;
1295                     char *tmp_x264opts;
1296
1297                     tmp_x264opts = malloc(size * sizeof(char));
1298                     if( x264opts )
1299                     {
1300                         snprintf( tmp_x264opts, size, "%s:%s",
1301                                   x264opts, turbo_opts );
1302                         free( x264opts );
1303                     } else {
1304                         /*
1305                          * No x264opts to modify, but apply the turbo options
1306                          * anyway as they may be modifying defaults
1307                          */
1308                         snprintf( tmp_x264opts, size, "%s",
1309                                   turbo_opts );
1310                     }
1311                     x264opts = tmp_x264opts;
1312
1313                     fprintf( stderr, "Modified x264 options for pass 1 to append turbo options: %s\n",
1314                              x264opts );
1315
1316                     job->x264opts = x264opts;
1317                 }
1318                 hb_add( h, job );
1319
1320                 job->select_subtitle = subtitle_tmp;
1321
1322                 job->pass = 2;
1323                 /*
1324                  * On the second pass we turn off subtitle scan so that we
1325                  * can actually encode using any subtitles that were auto
1326                  * selected in the first pass (using the whacky select-subtitle
1327                  * attribute of the job).
1328                  */
1329                 job->indepth_scan = 0;
1330
1331                 job->x264opts = x264opts2;
1332
1333                 hb_add( h, job );
1334             }
1335             else
1336             {
1337                 /*
1338                  * Turn on subtitle scan if requested, note that this option
1339                  * precludes encoding of any actual subtitles.
1340                  */
1341
1342                 job->indepth_scan = 0;
1343                 job->pass = 0;
1344                 hb_add( h, job );
1345             }
1346             hb_start( h );
1347             break;
1348         }
1349
1350 #define p s.param.working
1351         case HB_STATE_WORKING:
1352             fprintf( stdout, "\rEncoding: task %d of %d, %.2f %%",
1353                      p.job_cur, p.job_count, 100.0 * p.progress );
1354             if( p.seconds > -1 )
1355             {
1356                 fprintf( stdout, " (%.2f fps, avg %.2f fps, ETA "
1357                          "%02dh%02dm%02ds)", p.rate_cur, p.rate_avg,
1358                          p.hours, p.minutes, p.seconds );
1359             }
1360             fflush(stdout);
1361             break;
1362 #undef p
1363
1364 #define p s.param.muxing
1365         case HB_STATE_MUXING:
1366         {
1367             if (show_mux_warning)
1368             {
1369                 fprintf( stdout, "\rMuxing: this may take awhile..." );
1370                 fflush(stdout);
1371                 show_mux_warning = 0;
1372             }
1373             break;
1374         }
1375 #undef p
1376
1377 #define p s.param.workdone
1378         case HB_STATE_WORKDONE:
1379             /* Print error if any, then exit */
1380             switch( p.error )
1381             {
1382                 case HB_ERROR_NONE:
1383                     fprintf( stderr, "\nRip done!\n" );
1384                     break;
1385                 case HB_ERROR_CANCELED:
1386                     fprintf( stderr, "\nRip canceled.\n" );
1387                     break;
1388                 default:
1389                     fprintf( stderr, "\nRip failed (error %x).\n",
1390                              p.error );
1391             }
1392             die = 1;
1393             break;
1394 #undef p
1395     }
1396     return 0;
1397 }
1398
1399 /****************************************************************************
1400  * SigHandler:
1401  ****************************************************************************/
1402 static volatile int64_t i_die_date = 0;
1403 void SigHandler( int i_signal )
1404 {
1405     if( die == 0 )
1406     {
1407         die = 1;
1408         i_die_date = hb_get_date();
1409         fprintf( stderr, "Signal %d received, terminating - do it "
1410                  "again in case it gets stuck\n", i_signal );
1411     }
1412     else if( i_die_date + 500 < hb_get_date() )
1413     {
1414         fprintf( stderr, "Dying badly, files might remain in your /tmp\n" );
1415         exit( 1 );
1416     }
1417 }
1418
1419 /****************************************************************************
1420  * ShowHelp:
1421  ****************************************************************************/
1422 static void ShowHelp()
1423 {
1424     int i;
1425
1426     fprintf( stderr,
1427     "Syntax: HandBrakeCLI [options] -i <device> -o <file>\n"
1428     "\n"
1429         "### General Handbrake Options------------------------------------------------\n\n"
1430     "    -h, --help              Print help\n"
1431     "    -u, --update            Check for updates and exit\n"
1432     "    -v, --verbose           Be verbose\n"
1433     "    -C, --cpu               Set CPU count (default: autodetected)\n"
1434     "    -Z. --preset <string>   Use a built-in preset. Capitalization matters, and\n"
1435     "                            if the preset name has spaces, surround it with\n"
1436     "                            double quotation marks\n"
1437     "    -z, --preset-list       See a list of available built-in presets\n"
1438     "\n"
1439
1440         "### Source Options-----------------------------------------------------------\n\n"
1441         "    -i, --input <string>    Set input device\n"
1442         "    -t, --title <number>    Select a title to encode (0 to scan only,\n"
1443     "                            default: 1)\n"
1444     "    -L, --longest           Select the longest title\n"
1445     "    -c, --chapters <string> Select chapters (e.g. \"1-3\" for chapters\n"
1446     "                            1 to 3, or \"3\" for chapter 3 only,\n"
1447     "                            default: all chapters)\n"
1448         "\n"
1449
1450         "### Destination Options------------------------------------------------------\n\n"
1451     "    -o, --output <string>   Set output file name\n"
1452         "    -f, --format <string>   Set output format (avi/mp4/ogm/mkv, default:\n"
1453     "                            autodetected from file name)\n"
1454     "    -4, --large-file        Use 64-bit mp4 files that can hold more than\n"
1455     "                            4 GB. Note: Breaks iPod, @TV, PS3 compatibility.\n"""
1456     "    -O, --optimize          Optimize mp4 files for HTTP streaming\n"
1457     "    -I, --ipod-atom         Mark mp4 files so iPods will accept them\n"
1458     "\n"
1459
1460         "### Picture Settings---------------------------------------------------------\n\n"
1461     "    -w, --width <number>    Set picture width\n"
1462     "    -l, --height <number>   Set picture height\n"
1463     "        --crop <T:B:L:R>    Set cropping values (default: autocrop)\n"
1464         "    -Y, --maxHeight <#>     Set maximum height\n"
1465         "    -X, --maxWidth <#>      Set maximum width\n"
1466         "    -s, --subtitle <number> Select subtitle (default: none)\n"
1467     "    -U, --subtitle-scan     Scan for subtitles in an extra 1st pass, and choose\n"
1468     "                            the one that's only used 10 percent of the time\n"
1469     "                            or less. This should locate subtitles for short\n"
1470     "                            foreign language segments. Best used in conjunction\n"
1471     "                            with --subtitle-forced.\n"
1472     "    -F, --subtitle-forced   Only display subtitles from the selected stream if\n"
1473     "                            the subtitle has the forced flag set. May be used in\n"
1474     "                            conjunction with --subtitle-scan to auto-select\n"
1475     "                            a stream if it contains forced subtitles.\n"
1476     "    -N, --native-language   Select subtitles with this language if it does not\n"
1477     "          <string>          match the Audio language. Provide the language's\n"
1478     "                            iso639-2 code (fre, eng, spa, dut, et cetera)\n"
1479         "    -m, --markers           Add chapter markers (mp4 output format only)\n"
1480         "\n"
1481
1482         "### Video Options------------------------------------------------------------\n\n"
1483         "    -e, --encoder <string>  Set video library encoder (ffmpeg,xvid,\n"
1484     "                            x264,theora default: ffmpeg)\n"
1485         "    -q, --quality <float>   Set video quality (0.0..1.0)\n"
1486         "    -Q, --cqp               Use with -q for CQP instead of CRF\n"
1487     "    -S, --size <MB>         Set target size\n"
1488         "    -b, --vb <kb/s>         Set video bitrate (default: 1000)\n"
1489         "    -r, --rate              Set video framerate (" );
1490     for( i = 0; i < hb_video_rates_count; i++ )
1491     {
1492         fprintf( stderr, hb_video_rates[i].string );
1493         if( i != hb_video_rates_count - 1 )
1494             fprintf( stderr, "/" );
1495     }
1496     fprintf( stderr, ")\n"
1497         "\n"
1498         "    -2, --two-pass          Use two-pass mode\n"
1499      "    -d, --deinterlace       Deinterlace video with yadif/mcdeint filter\n"
1500      "          <YM:FD:MM:QP>     (default 0:-1:-1:1)\n"
1501      "           or\n"
1502      "          <fast/slow/slower>\n"
1503      "    -7, --deblock           Deblock video with pp7 filter\n"
1504      "          <QP:M>            (default 0:2)\n"
1505      "    -8, --denoise           Denoise video with hqdn3d filter\n"
1506      "          <SL:SC:TL:TC>     (default 4:3:6:4.5)\n"
1507      "           or\n"
1508      "          <weak/medium/strong>\n"
1509      "    -9, --detelecine        Detelecine video with pullup filter\n"
1510      "          <L:R:T:B:SB:MP>   (default 1:1:4:4:0:0)\n"
1511      "    -5, --decomb           Selectively deinterlaces when it detects combing\n"
1512      "          <MO:ME:MT:ST:BT:BX:BY>     (default: 1:2:6:9:80:16:16)\n"
1513     "    -g, --grayscale         Grayscale encoding\n"
1514     "    -p, --pixelratio        Store pixel aspect ratio in video stream\n"
1515     "    -P, --loosePixelratio   Store pixel aspect ratio with specified width\n"
1516     "          <MOD:PARX:PARY>   Takes as optional arguments what number you want\n"
1517     "                            the dimensions to divide cleanly by (default 16)\n"
1518     "                            and the pixel ratio to use (default autodetected)\n)"
1519
1520
1521         "\n"
1522
1523
1524         "### Audio Options-----------------------------------------------------------\n\n"
1525         "    -a, --audio <string>    Select audio channel(s), separated by commas\n"
1526     "                            More than one output track can be used for one\n"
1527     "                            input.\n"
1528     "                            (\"none\" for no audio, \"1,2,3\" for multiple\n"
1529     "                             tracks, default: first one)\n"
1530     "    -E, --aencoder <string> Audio encoder(s) (faac/lame/vorbis/ac3) \n"
1531         "                            ac3 meaning passthrough\n"
1532         "                            Seperated by commas for more than one audio track.\n"
1533         "                            (default: guessed)\n"
1534         "    -B, --ab <kb/s>         Set audio bitrate(s)  (default: 128)\n"
1535     "                            Seperated by commas for more than one audio track.\n"
1536         "    -6, --mixdown <string>  Format(s) for surround sound downmixing\n"
1537     "                            Seperated by commas for more than one audio track.\n"
1538     "                            (mono/stereo/dpl1/dpl2/6ch, default: dpl2)\n"
1539     "    -R, --arate             Set audio samplerate(s) (" );
1540     for( i = 0; i < hb_audio_rates_count; i++ )
1541     {
1542         fprintf( stderr, hb_audio_rates[i].string );
1543         if( i != hb_audio_rates_count - 1 )
1544             fprintf( stderr, "/" );
1545     }
1546     fprintf( stderr, " kHz)\n"
1547     "                            Seperated by commas for more than one audio track.\n"
1548     "    -D, --drc <float>       Apply extra dynamic range compression to the audio,\n"
1549     "                            making soft sounds louder. Range is 1.0 to 4.0\n"
1550     "                            (too loud), with 1.5 - 2.5 being a useful range.\n"
1551     "                            Seperated by commas for more than one audio track.\n"
1552
1553
1554         "\n"
1555
1556
1557     "### Advanced Options---------------------------------------------------------\n\n"
1558     "    -x, --x264opts <string> Specify advanced x264 options in the\n"
1559     "                            same style as mencoder:\n"
1560     "                            option1=value1:option2=value2\n"
1561     "    -T, --turbo             When using 2-pass use the turbo options\n"
1562     "                            on the first pass to improve speed\n"
1563     "                            (only works with x264, affects PSNR by about 0.05dB,\n"
1564     "                            and increases first pass speed two to four times)\n"
1565     "    -V, --vfr               Perform variable framerate detelecine on NTSC video\n"
1566     );
1567 }
1568
1569 /****************************************************************************
1570  * ShowPresets:
1571  ****************************************************************************/
1572 static void ShowPresets()
1573 {
1574     printf("\n+ Animation:  -e x264 -b 1000 -B 160 -R 48 -E faac -f mkv --deinterlace=\"slower\" -m -p -2 -T -x ref=5:mixed-refs:bframes=6: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");
1575
1576     printf("\n+ AppleTV:  -e x264 -b 2500 -B 160 -R 48 -E faac,ac3 -f mp4 -4 -m -p -x bframes=3:ref=1:subme=5:me=umh:no-fast-pskip=1:trellis=1:cabac=0\n");
1577
1578     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=esa:subme=7:me-range=64:analyse=all:8x8dct:trellis=1:no-fast-pskip:no-dct-decimate:filter=-2,-1\n");
1579
1580     printf("\n+ Blind:  -b 512 -B 128 -R 48 -E faac -f mp4 -w 512 -m\n");
1581
1582     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");
1583
1584     printf("\n+ Classic:  -b 1000 -B 160 -R 48 -E faac -f mp4\n");
1585
1586     printf("\n+ Constant Quality Rate:  -e x264 -q 0.64709997177124023 -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");
1587
1588     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");
1589
1590     printf("\n+ Film:  -e x264 -b 1800 -E ac3 -f mkv -m -p -2 -T -x ref=3:mixed-refs:bframes=6:bime:weightb:b-rdo:direct=auto:b-pyramid:me=umh:subme=7:analyse=all:8x8dct:trellis=1:no-fast-pskip\n");
1591
1592     printf("\n+ iPhone / iPod Touch:  -e x264 -b 960 -B 128 -R 48 -E faac -f mp4 -I -w 480 -m -x level=30:cabac=0:ref=1:analyse=all:me=umh:subme=6:no-fast-pskip=1:trellis=1\n");
1593
1594     printf("\n+ iPod High-Rez:  -e x264 -b 1500 -B 160 -R 48 -E faac -f mp4 -I -w 640 -m -x level=30:bframes=0:cabac=0:ref=1:vbv-maxrate=1500:vbv-bufsize=2000:analyse=all:me=umh:subme=6:no-fast-pskip=1\n");
1595
1596     printf("\n+ iPod Low-Rez:  -e x264 -b 700 -B 160 -R 48 -E faac -f mp4 -I -w 320 -m -x level=30:bframes=0:cabac=0:ref=1:vbv-maxrate=768:vbv-bufsize=2000:analyse=all:me=umh:subme=6:no-fast-pskip=1\n");
1597
1598     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");
1599
1600     printf("\n+ PS3:  -e x264 -b 2500 -B 160 -R 48 -E faac -f mp4 -p -x level=41:subme=5:me=umh\n");
1601
1602     printf("\n+ PSP:  -b 1024 -B 128 -R 48 -E faac -f mp4 -w 368 -l 208 -m\n");
1603
1604     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");
1605
1606     printf("\n+ Television:  -e x264 -b 1300 -B 160 -R 48 -E faac -f mkv --deinterlace=\"slower\" --denoise=\"weak\" -m -2 -T -x ref=3:mixed-refs:bframes=6:bime:weightb:direct=auto:b-pyramid:me=umh:subme=6:analyse=all:8x8dct:trellis=1:nr=150:no-fast-pskip\n");
1607
1608     printf("\n+ Xbox 360:  -e x264 -b 2000 -B 160 -R 48 -E faac -f mp4 -p -x level=40:ref=2:mixed-refs:bframes=3:bime:weightb:b-rdo:direct=auto:b-pyramid:me=umh:subme=5:analyse=all:no-fast-pskip:filter=-2,-1\n");
1609 }
1610
1611 /****************************************************************************
1612  * ParseOptions:
1613  ****************************************************************************/
1614 static int ParseOptions( int argc, char ** argv )
1615 {
1616     for( ;; )
1617     {
1618         static struct option long_options[] =
1619           {
1620             { "help",        no_argument,       NULL,    'h' },
1621             { "update",      no_argument,       NULL,    'u' },
1622             { "verbose",     no_argument,       NULL,    'v' },
1623             { "cpu",         required_argument, NULL,    'C' },
1624
1625             { "format",      required_argument, NULL,    'f' },
1626             { "input",       required_argument, NULL,    'i' },
1627             { "output",      required_argument, NULL,    'o' },
1628             { "large-file",  no_argument,       NULL,    '4' },
1629             { "optimize",    no_argument,       NULL,    'O' },
1630             { "ipod-atom",   no_argument,       NULL,    'I' },
1631
1632             { "title",       required_argument, NULL,    't' },
1633             { "longest",     no_argument,       NULL,    'L' },
1634             { "chapters",    required_argument, NULL,    'c' },
1635             { "markers",     optional_argument, NULL,    'm' },
1636             { "audio",       required_argument, NULL,    'a' },
1637             { "mixdown",     required_argument, NULL,    '6' },
1638             { "drc",         required_argument, NULL,    'D' },
1639             { "subtitle",    required_argument, NULL,    's' },
1640             { "subtitle-scan", no_argument,     NULL,    'U' },
1641             { "subtitle-forced", no_argument,   NULL,    'F' },
1642             { "native-language", required_argument, NULL,'N' },
1643
1644             { "encoder",     required_argument, NULL,    'e' },
1645             { "aencoder",    required_argument, NULL,    'E' },
1646             { "two-pass",    no_argument,       NULL,    '2' },
1647             { "deinterlace", optional_argument, NULL,    'd' },
1648             { "deblock",     optional_argument, NULL,    '7' },
1649             { "denoise",     optional_argument, NULL,    '8' },
1650             { "detelecine",  optional_argument, NULL,    '9' },
1651             { "decomb",      optional_argument, NULL,    '5' },
1652             { "grayscale",   no_argument,       NULL,    'g' },
1653             { "pixelratio",  no_argument,       NULL,    'p' },
1654             { "loosePixelratio", optional_argument,   NULL,    'P' },
1655             { "width",       required_argument, NULL,    'w' },
1656             { "height",      required_argument, NULL,    'l' },
1657             { "crop",        required_argument, NULL,    'n' },
1658
1659             { "vb",          required_argument, NULL,    'b' },
1660             { "quality",     required_argument, NULL,    'q' },
1661             { "size",        required_argument, NULL,    'S' },
1662             { "ab",          required_argument, NULL,    'B' },
1663             { "rate",        required_argument, NULL,    'r' },
1664             { "arate",       required_argument, NULL,    'R' },
1665             { "cqp",         no_argument,       NULL,    'Q' },
1666             { "x264opts",    required_argument, NULL,    'x' },
1667             { "turbo",       no_argument,       NULL,    'T' },
1668             { "maxHeight",   required_argument, NULL,    'Y' },
1669             { "maxWidth",    required_argument, NULL,    'X' },
1670             { "preset",      required_argument, NULL,    'Z' },
1671             { "preset-list", no_argument,       NULL,    'z' },
1672             { "vfr",         no_argument,       NULL,    'V' },
1673
1674             { 0, 0, 0, 0 }
1675           };
1676
1677         int option_index = 0;
1678         int c;
1679
1680                 c = getopt_long( argc, argv,
1681                                                  "hvuC:f:4i:Io:t:Lc:m::a:6:s:UFN:e:E:2dD:7895gpOP::w:l:n:b:q:S:B:r:R:Qx:TY:X:VZ:z",
1682                          long_options, &option_index );
1683         if( c < 0 )
1684         {
1685             break;
1686         }
1687
1688         switch( c )
1689         {
1690             case 'h':
1691                 ShowHelp();
1692                 exit( 0 );
1693             case 'u':
1694                 update = 1;
1695                 break;
1696             case 'v':
1697                 debug = HB_DEBUG_ALL;
1698                 break;
1699             case 'C':
1700                 cpu = atoi( optarg );
1701                 break;
1702
1703             case 'Z':
1704                 preset = 1;
1705                 preset_name = strdup(optarg);
1706                 break;
1707             case 'z':
1708                 ShowPresets();
1709                 exit ( 0 );
1710
1711             case 'f':
1712                 format = strdup( optarg );
1713                 break;
1714             case 'i':
1715                 input = strdup( optarg );
1716                 #ifdef __APPLE_CC__
1717                 char *devName = bsd_name_for_path( input );
1718                 if( devName == NULL )
1719                 {
1720                     return 0;
1721                 }
1722                 if( device_is_dvd( devName ) )
1723                 {
1724                     char *newInput = malloc( strlen("/dev/") + strlen( devName ) + 1);
1725                     sprintf( newInput, "/dev/%s", devName );
1726                     free(input);
1727                     input = newInput;
1728                 }
1729                 #endif
1730                 break;
1731             case 'o':
1732                 output = strdup( optarg );
1733                 break;
1734             case '4':
1735                 largeFileSize = 1;
1736                 break;
1737             case 'O':
1738                 mp4_optimize = 1;
1739                 break;
1740             case 'I':
1741                 ipod_atom = 1;
1742                 break;
1743
1744             case 't':
1745                 titleindex = atoi( optarg );
1746                 break;
1747             case 'L':
1748                 longest_title = 1;
1749                 break;
1750             case 'c':
1751             {
1752                 int start, end;
1753                 if( sscanf( optarg, "%d-%d", &start, &end ) == 2 )
1754                 {
1755                     chapter_start = start;
1756                     chapter_end   = end;
1757                 }
1758                 else if( sscanf( optarg, "%d", &start ) == 1 )
1759                 {
1760                     chapter_start = start;
1761                     chapter_end   = chapter_start;
1762                 }
1763                 else
1764                 {
1765                     fprintf( stderr, "chapters: invalid syntax (%s)\n",
1766                              optarg );
1767                     return -1;
1768                 }
1769                 break;
1770             }
1771             case 'm':
1772                 if( optarg != NULL )
1773                 {
1774                     marker_file = strdup( optarg );
1775                 }
1776                 chapter_markers = 1;
1777                 break;
1778             case 'a':
1779                 if( optarg != NULL )
1780                 {
1781                     atracks = strdup( optarg );
1782                 }
1783                 else
1784                 {
1785                     atracks = "1" ;
1786                 }
1787                 break;
1788             case '6':
1789                 if( optarg != NULL )
1790                 {
1791                     mixdowns = strdup( optarg );
1792                 }
1793                 break;
1794             case 'D':
1795                 if( optarg != NULL )
1796                 {
1797                     dynamic_range_compression = strdup( optarg );
1798                 }
1799                 break;
1800             case 's':
1801                 sub = atoi( optarg );
1802                 break;
1803             case 'U':
1804                 subtitle_scan = 1;
1805                 break;
1806             case 'F':
1807                 subtitle_force = 1;
1808                 break;
1809             case 'N':
1810                 native_language = strdup( optarg );
1811                 break;
1812             case '2':
1813                 twoPass = 1;
1814                 break;
1815             case 'd':
1816                 if( optarg != NULL )
1817                 {
1818                     if (!( strcmp( optarg, "fast" ) ))
1819                     {
1820                         deinterlace_opt = "-1";
1821                     }
1822                     else if (!( strcmp( optarg, "slow" ) ))
1823                     {
1824                         deinterlace_opt = "2";
1825                     }
1826                     else if (!( strcmp( optarg, "slower" ) ))
1827                     {
1828                         deinterlace_opt = "0";
1829                     }
1830                     else
1831                     {
1832                         deinterlace_opt = strdup( optarg );
1833                     }
1834                 }
1835                 deinterlace = 1;
1836                 break;
1837             case '7':
1838                 if( optarg != NULL )
1839                 {
1840                     deblock_opt = strdup( optarg );
1841                 }
1842                 deblock = 1;
1843                 break;
1844             case '8':
1845                 if( optarg != NULL )
1846                 {
1847                     if (!( strcmp( optarg, "weak" ) ))
1848                     {
1849                         denoise_opt = "2:1:2:3";
1850                     }
1851                     else if (!( strcmp( optarg, "medium" ) ))
1852                     {
1853                         denoise_opt = "3:2:2:3";
1854                     }
1855                     else if (!( strcmp( optarg, "strong" ) ))
1856                     {
1857                         denoise_opt = "7:7:5:5";
1858                     }
1859                     else
1860                     {
1861                         denoise_opt = strdup( optarg );
1862                     }
1863                 }
1864                 denoise = 1;
1865                 break;
1866             case '9':
1867                 if( optarg != NULL )
1868                 {
1869                     detelecine_opt = strdup( optarg );
1870                 }
1871                 detelecine = 1;
1872                 break;
1873             case '5':
1874                 if( optarg != NULL )
1875                 {
1876                     decomb_opt = strdup( optarg );
1877                 }
1878                 decomb = 1;
1879                 break;
1880             case 'g':
1881                 grayscale = 1;
1882                 break;
1883             case 'p':
1884                 pixelratio = 1;
1885                 break;
1886             case 'P':
1887                 loosePixelratio = 1;
1888                 if( optarg != NULL )
1889                 {
1890                     sscanf( optarg, "%i:%i:%i", &modulus, &par_width, &par_height );
1891                 }
1892                 break;
1893             case 'e':
1894                 if( !strcasecmp( optarg, "ffmpeg" ) )
1895                 {
1896                     vcodec = HB_VCODEC_FFMPEG;
1897                 }
1898                 else if( !strcasecmp( optarg, "xvid" ) )
1899                 {
1900                     vcodec = HB_VCODEC_XVID;
1901                 }
1902                 else if( !strcasecmp( optarg, "x264" ) )
1903                 {
1904                     vcodec = HB_VCODEC_X264;
1905                 }
1906                 else if( !strcasecmp( optarg, "x264b13" ) )
1907                 {
1908                     vcodec = HB_VCODEC_X264;
1909                     h264_13 = 1;
1910                 }
1911                 else if( !strcasecmp( optarg, "x264b30" ) )
1912                 {
1913                     vcodec = HB_VCODEC_X264;
1914                     h264_30 = 1;
1915                 }
1916                 else if( !strcasecmp( optarg, "theora" ) )
1917                 {
1918                     vcodec = HB_VCODEC_THEORA;
1919                 }
1920                 else
1921                 {
1922                     fprintf( stderr, "invalid codec (%s)\n", optarg );
1923                     return -1;
1924                 }
1925                 break;
1926             case 'E':
1927                 if( optarg != NULL )
1928                 {
1929                     acodecs = strdup( optarg );
1930                 }
1931                 break;
1932             case 'w':
1933                 width = atoi( optarg );
1934                 break;
1935             case 'l':
1936                 height = atoi( optarg );
1937                 break;
1938             case 'n':
1939             {
1940                 int    i;
1941                 char * tmp = optarg;
1942                 for( i = 0; i < 4; i++ )
1943                 {
1944                     if( !*tmp )
1945                         break;
1946                     crop[i] = strtol( tmp, &tmp, 0 );
1947                     tmp++;
1948                 }
1949                 break;
1950             }
1951             case 'r':
1952             {
1953                 int i;
1954                 vrate = 0;
1955                 for( i = 0; i < hb_video_rates_count; i++ )
1956                 {
1957                     if( !strcmp( optarg, hb_video_rates[i].string ) )
1958                     {
1959                         vrate = hb_video_rates[i].rate;
1960                         break;
1961                     }
1962                 }
1963                 if( !vrate )
1964                 {
1965                     fprintf( stderr, "invalid framerate %s\n", optarg );
1966                 }
1967                 break;
1968             }
1969             case 'R':
1970                 if( optarg != NULL )
1971                 {
1972                     arates = strdup( optarg );
1973                 }
1974                 break;
1975             case 'b':
1976                 vbitrate = atoi( optarg );
1977                 break;
1978             case 'q':
1979                 vquality = atof( optarg );
1980                 break;
1981             case 'S':
1982                 size = atoi( optarg );
1983                 break;
1984             case 'B':
1985                 if( optarg != NULL )
1986                 {
1987                     abitrates = strdup( optarg );
1988                 }
1989                 break;
1990             case 'Q':
1991                 crf = 0;
1992                 break;
1993             case 'x':
1994                 x264opts = strdup( optarg );
1995                 break;
1996             case 'T':
1997                 turbo_opts_enabled = 1;
1998                 break;
1999             case 'Y':
2000                 maxHeight = atoi( optarg );
2001                 break;
2002             case 'X':
2003                 maxWidth = atoi (optarg );
2004                 break;
2005             case 'V':
2006                 vfr = 1;
2007                 break;
2008
2009             default:
2010                 fprintf( stderr, "unknown option (%s)\n", argv[optind] );
2011                 return -1;
2012         }
2013     }
2014
2015     return 0;
2016 }
2017
2018 static int CheckOptions( int argc, char ** argv )
2019 {
2020     if( update )
2021     {
2022         return 0;
2023     }
2024
2025     if( input == NULL || *input == '\0' )
2026     {
2027         fprintf( stderr, "Missing input device. Run %s --help for "
2028                  "syntax.\n", argv[0] );
2029         return 1;
2030     }
2031
2032     /* Parse format */
2033     if( titleindex > 0 )
2034     {
2035         if( output == NULL || *output == '\0' )
2036         {
2037             fprintf( stderr, "Missing output file name. Run %s --help "
2038                      "for syntax.\n", argv[0] );
2039             return 1;
2040         }
2041
2042         if( !format )
2043         {
2044             char * p = strrchr( output, '.' );
2045
2046             /* autodetect */
2047             if( p && !strcasecmp( p, ".avi" ) )
2048             {
2049                 mux = HB_MUX_AVI;
2050                 default_acodec = HB_ACODEC_LAME;
2051             }
2052             else if( p && ( !strcasecmp( p, ".mp4" )  ||
2053                             !strcasecmp( p, ".m4v" ) ) )
2054             {
2055                 if ( h264_30 == 1 )
2056                     mux = HB_MUX_IPOD;
2057                 else
2058                     mux = HB_MUX_MP4;
2059                 default_acodec = HB_ACODEC_FAAC;
2060             }
2061             else if( p && ( !strcasecmp( p, ".ogm" ) ||
2062                             !strcasecmp( p, ".ogg" ) ) )
2063             {
2064                 mux = HB_MUX_OGM;
2065                 default_acodec = HB_ACODEC_VORBIS;
2066             }
2067             else if( p && !strcasecmp(p, ".mkv" ) )
2068             {
2069                 mux = HB_MUX_MKV;
2070                 default_acodec = HB_ACODEC_AC3;
2071             }
2072             else
2073             {
2074                 fprintf( stderr, "Output format couldn't be guessed "
2075                          "from file name, using default.\n" );
2076                 return 0;
2077             }
2078         }
2079         else if( !strcasecmp( format, "avi" ) )
2080         {
2081             mux = HB_MUX_AVI;
2082             default_acodec = HB_ACODEC_LAME;
2083         }
2084         else if( !strcasecmp( format, "mp4" ) ||
2085                  !strcasecmp( format, "m4v" ) )
2086         {
2087             if ( h264_30 == 1)
2088                 mux = HB_MUX_IPOD;
2089             else
2090                 mux = HB_MUX_MP4;
2091             default_acodec = HB_ACODEC_FAAC;
2092         }
2093         else if( !strcasecmp( format, "ogm" ) ||
2094                  !strcasecmp( format, "ogg" ) )
2095         {
2096             mux = HB_MUX_OGM;
2097             default_acodec = HB_ACODEC_VORBIS;
2098         }
2099         else if( !strcasecmp( format, "mkv" ) )
2100         {
2101             mux = HB_MUX_MKV;
2102             default_acodec = HB_ACODEC_AC3;
2103         }
2104         else
2105         {
2106             fprintf( stderr, "Invalid output format (%s). Possible "
2107                      "choices are avi, mp4, m4v, ogm, ogg and mkv\n.", format );
2108             return 1;
2109         }
2110     }
2111
2112     return 0;
2113 }
2114
2115 static int get_acodec_for_string( char *codec )
2116 {
2117     if( !strcasecmp( codec, "ac3" ) )
2118     {
2119         return HB_ACODEC_AC3;
2120     }
2121     else if( !strcasecmp( codec, "dts" ) || !strcasecmp( codec, "dca" ) )
2122     {
2123         return HB_ACODEC_DCA;
2124     }
2125     else if( !strcasecmp( codec, "lame" ) )
2126     {
2127         return HB_ACODEC_LAME;
2128     }
2129     else if( !strcasecmp( codec, "faac" ) )
2130     {
2131         return HB_ACODEC_FAAC;
2132     }
2133     else if( !strcasecmp( codec, "vorbis") )
2134     {
2135         return HB_ACODEC_VORBIS;
2136     }
2137     else
2138     {
2139         return -1;
2140     }
2141 }
2142
2143 static int is_sample_rate_valid(int rate)
2144 {
2145     int i;
2146     for( i = 0; i < hb_audio_rates_count; i++ )
2147     {
2148             if (rate == hb_audio_rates[i].rate)
2149                 return 1;
2150     }
2151     return 0;
2152 }
2153
2154 #ifdef __APPLE_CC__
2155 /****************************************************************************
2156  * bsd_name_for_path
2157  *
2158  * Returns the BSD device name for the block device that contains the
2159  * passed-in path. Returns NULL on failure.
2160  ****************************************************************************/
2161 static char* bsd_name_for_path(char *path)
2162 {
2163     OSStatus err;
2164     FSRef ref;
2165     err = FSPathMakeRef( (const UInt8 *) input, &ref, NULL );
2166     if( err != noErr )
2167     {
2168         return NULL;
2169     }
2170
2171     // Get the volume reference number.
2172     FSCatalogInfo catalogInfo;
2173     err = FSGetCatalogInfo( &ref, kFSCatInfoVolume, &catalogInfo, NULL, NULL,
2174                             NULL);
2175     if( err != noErr )
2176     {
2177         return NULL;
2178     }
2179     FSVolumeRefNum volRefNum = catalogInfo.volume;
2180
2181     // Now let's get the device name
2182     GetVolParmsInfoBuffer volumeParms;
2183     err = FSGetVolumeParms( volRefNum, &volumeParms, sizeof( volumeParms ) );
2184     if( err != noErr )
2185     {
2186         return NULL;
2187     }
2188
2189     // A version 4 GetVolParmsInfoBuffer contains the BSD node name in the
2190     // vMDeviceID field. It is actually a char * value. This is mentioned in the
2191     // header CoreServices/CarbonCore/Files.h.
2192     return volumeParms.vMDeviceID;
2193 }
2194
2195 /****************************************************************************
2196  * device_is_dvd
2197  *
2198  * Returns whether or not the passed in BSD device represents a DVD, or other
2199  * optical media.
2200  ****************************************************************************/
2201 static int device_is_dvd(char *device)
2202 {
2203     io_service_t service = get_iokit_service(device);
2204     if( service == IO_OBJECT_NULL )
2205     {
2206         return 0;
2207     }
2208     int result = is_dvd_service(service);
2209     IOObjectRelease(service);
2210     return result;
2211 }
2212
2213 /****************************************************************************
2214  * get_iokit_service
2215  *
2216  * Returns the IOKit service object for the passed in BSD device name.
2217  ****************************************************************************/
2218 static io_service_t get_iokit_service( char *device )
2219 {
2220     CFMutableDictionaryRef matchingDict;
2221     matchingDict = IOBSDNameMatching( kIOMasterPortDefault, 0, device );
2222     if( matchingDict == NULL )
2223     {
2224         return IO_OBJECT_NULL;
2225     }
2226     // Fetch the object with the matching BSD node name. There should only be
2227     // one match, so IOServiceGetMatchingService is used instead of
2228     // IOServiceGetMatchingServices to simplify the code.
2229     return IOServiceGetMatchingService( kIOMasterPortDefault, matchingDict );
2230 }
2231
2232 /****************************************************************************
2233  * is_dvd_service
2234  *
2235  * Returns whether or not the service passed in is a DVD.
2236  *
2237  * Searches for an IOMedia object that represents the entire (whole) media that
2238  * the volume is on. If the volume is on partitioned media, the whole media
2239  * object will be a parent of the volume's media object. If the media is not
2240  * partitioned, the volume's media object will be the whole media object.
2241  ****************************************************************************/
2242 static int is_dvd_service( io_service_t service )
2243 {
2244     kern_return_t  kernResult;
2245     io_iterator_t  iter;
2246
2247     // Create an iterator across all parents of the service object passed in.
2248     kernResult = IORegistryEntryCreateIterator( service,
2249                                                 kIOServicePlane,
2250                                                 kIORegistryIterateRecursively | kIORegistryIterateParents,
2251                                                 &iter );
2252     if( kernResult != KERN_SUCCESS )
2253     {
2254         return 0;
2255     }
2256     if( iter == IO_OBJECT_NULL )
2257     {
2258         return 0;
2259     }
2260
2261     // A reference on the initial service object is released in the do-while
2262     // loop below, so add a reference to balance.
2263     IOObjectRetain( service );
2264
2265     int result = 0;
2266     do
2267     {
2268         if( is_whole_media_service( service ) &&
2269             IOObjectConformsTo( service, kIODVDMediaClass) )
2270         {
2271             result = 1;
2272         }
2273         IOObjectRelease( service );
2274     } while( !result && (service = IOIteratorNext( iter )) );
2275     IOObjectRelease( iter );
2276
2277     return result;
2278 }
2279
2280 /****************************************************************************
2281  * is_whole_media_service
2282  *
2283  * Returns whether or not the service passed in is an IOMedia service and
2284  * represents the "whole" media instead of just a partition.
2285  *
2286  * The whole media object is indicated in the IORegistry by the presence of a
2287  * property with the key "Whole" and value "Yes".
2288  ****************************************************************************/
2289 static is_whole_media_service( io_service_t service )
2290 {
2291     int result = 0;
2292
2293     if( IOObjectConformsTo( service, kIOMediaClass ) )
2294     {
2295         CFTypeRef wholeMedia = IORegistryEntryCreateCFProperty( service,
2296                                                                 CFSTR( kIOMediaWholeKey ),
2297                                                                 kCFAllocatorDefault,
2298                                                                 0 );
2299         if ( !wholeMedia )
2300         {
2301             return 0;
2302         }
2303         result = CFBooleanGetValue( (CFBooleanRef)wholeMedia );
2304         CFRelease( wholeMedia );
2305     }
2306
2307     return result;
2308 }
2309 #endif // __APPLE_CC__