OSDN Git Service

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