OSDN Git Service

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