OSDN Git Service

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