OSDN Git Service

6c08ecd9bc15006e1dd0040ae196eeb497d5aee7
[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                         
999                         int j;
1000                         for( j = 0; j < hb_audio_rates_count; j++ )
1001                         {
1002                             if( !strcmp( token, hb_audio_rates[j].string ) )
1003                             {
1004                                 arate = hb_audio_rates[j].rate;
1005                                 break;
1006                             }
1007                         }
1008                         
1009                         audio->out.samplerate = arate;
1010                     }
1011                     if( (++i) >= num_audio_tracks )
1012                         break;  /* We have more inputs than audio tracks, oops */
1013                     token = strtok(NULL, ",");
1014                 }
1015             }
1016             if (i < num_audio_tracks)
1017             {
1018                 /* We have fewer inputs than audio tracks, use default sample rate.
1019                  * Unless we only have one input, then use that for all tracks.
1020                  */
1021                 if (i != 1)
1022                     arate = default_arate;
1023                 for ( ; i < num_audio_tracks; i++)
1024                 {
1025                     audio = hb_list_audio_config_item(job->list_audio, i);
1026                     if (audio->out.codec == HB_ACODEC_AC3 || audio->out.codec == HB_ACODEC_DCA)
1027                     {
1028                         audio->out.samplerate = audio->in.samplerate;
1029                         continue;
1030                     }
1031                     audio->out.samplerate = arate;
1032                 }
1033             }
1034             /* Sample Rate */
1035
1036             /* Audio Bitrate */
1037             i = 0;
1038             if( abitrates )
1039             {
1040                 char * token = strtok(abitrates, ",");
1041                 if (token == NULL)
1042                     token = abitrates;
1043                 while ( token != NULL )
1044                 {
1045                     abitrate = atoi(token);
1046                     audio = hb_list_audio_config_item(job->list_audio, i);
1047                     if (audio->out.codec == HB_ACODEC_AC3 || audio->out.codec == HB_ACODEC_DCA)
1048                     {
1049                         audio->out.bitrate = audio->in.bitrate;   /* See note above about arate. */
1050                     }
1051                     else
1052                     {
1053                         audio->out.bitrate = abitrate;
1054                     }
1055                     if( (++i) >= num_audio_tracks )
1056                         break;  /* We have more inputs than audio tracks, oops */
1057                     token = strtok(NULL, ",");
1058                 }
1059             }
1060             if (i < num_audio_tracks)
1061             {
1062                 /* We have fewer inputs than audio tracks, use the default bitrate
1063                  * for the remaining tracks. Unless we only have one input, then use
1064                  * that for all tracks.
1065                  */
1066                 if (i != 1)
1067                     abitrate = default_abitrate;
1068                 for (; i < num_audio_tracks; i++)
1069                 {
1070                     audio = hb_list_audio_config_item(job->list_audio, i);
1071                     if (audio->out.codec == HB_ACODEC_AC3 || audio->out.codec == HB_ACODEC_DCA)
1072                     {
1073                         audio->out.bitrate = audio->in.bitrate;
1074                         continue;
1075                     }
1076                     audio->out.bitrate = abitrate;
1077                 }
1078             }
1079             /* Audio Bitrate */
1080
1081             /* Audio DRC */
1082             i = 0;
1083             if ( dynamic_range_compression )
1084             {
1085                 char * token = strtok(dynamic_range_compression, ",");
1086                 if (token == NULL)
1087                     token = dynamic_range_compression;
1088                 while ( token != NULL )
1089                 {
1090                     d_r_c = atof(token);
1091                     audio = hb_list_audio_config_item(job->list_audio, i);
1092                     audio->out.dynamic_range_compression = d_r_c;
1093                     if( (++i) >= num_audio_tracks )
1094                         break;  /* We have more inputs than audio tracks, oops */
1095                     token = strtok(NULL, ",");
1096                 }
1097             }
1098             if (i < num_audio_tracks)
1099             {
1100                 /* We have fewer inputs than audio tracks, use no DRC for the remaining
1101                  * tracks. Unless we only have one input, then use the same DRC for all
1102                  * tracks.
1103                  */
1104                 if (i != 1)
1105                     d_r_c = 0;
1106                 for (; i < num_audio_tracks; i++)
1107                 {
1108                     audio = hb_list_audio_config_item(job->list_audio, i);
1109                     audio->out.dynamic_range_compression = d_r_c;
1110                 }
1111             }
1112             /* Audio DRC */
1113
1114             /* Audio Mixdown */
1115             i = 0;
1116             if ( mixdowns )
1117             {
1118                 char * token = strtok(mixdowns, ",");
1119                 if (token == NULL)
1120                     token = mixdowns;
1121                 while ( token != NULL )
1122                 {
1123                     mixdown = hb_mixdown_get_mixdown_from_short_name(token);
1124                     audio = hb_list_audio_config_item(job->list_audio, i);
1125                     audio->out.mixdown = mixdown;
1126                     if( (++i) >= num_audio_tracks )
1127                         break;  /* We have more inputs than audio tracks, oops */
1128                     token = strtok(NULL, ",");
1129                 }
1130             }
1131             if (i < num_audio_tracks)
1132             {
1133                 /* We have fewer inputs than audio tracks, use DPLII for the rest. Unless
1134                  * we only have one input, then use that.
1135                  */
1136                 if (i != 1)
1137                     mixdown = HB_AMIXDOWN_DOLBYPLII;
1138                 for (; i < num_audio_tracks; i++)
1139                 {
1140                    audio = hb_list_audio_config_item(job->list_audio, i);
1141                    audio->out.mixdown = mixdown;
1142                 }
1143             }
1144             /* Audio Mixdown */
1145
1146             if( size )
1147             {
1148                 job->vbitrate = hb_calc_bitrate( job, size );
1149                 fprintf( stderr, "Calculated bitrate: %d kbps\n",
1150                          job->vbitrate );
1151             }
1152
1153             if( sub )
1154             {
1155                 job->subtitle = sub - 1;
1156             }
1157
1158             if( native_language )
1159             {
1160                 job->native_language = strdup( native_language );
1161             }
1162
1163             if( job->mux )
1164             {
1165                 job->mux = mux;
1166             }
1167
1168             if ( largeFileSize )
1169             {
1170                 job->largeFileSize = 1;
1171             }
1172             if ( mp4_optimize )
1173             {
1174                 job->mp4_optimize = 1;
1175             }
1176             if ( ipod_atom )
1177             {
1178                 job->ipod_atom = 1;
1179             }
1180
1181             job->file = strdup( output );
1182
1183             if( crf )
1184             {
1185                 job->crf = 1;
1186             }
1187
1188             if( x264opts != NULL && *x264opts != '\0' )
1189             {
1190                 job->x264opts = x264opts;
1191             }
1192             else /*avoids a bus error crash when options aren't specified*/
1193             {
1194                 job->x264opts =  NULL;
1195             }
1196             if (maxWidth)
1197                 job->maxWidth = maxWidth;
1198             if (maxHeight)
1199                 job->maxHeight = maxHeight;
1200
1201             if( subtitle_force )
1202             {
1203                 job->subtitle_force = subtitle_force;
1204             }
1205
1206             if( subtitle_scan )
1207             {
1208                 char *x264opts_tmp;
1209
1210                 /*
1211                  * When subtitle scan is enabled do a fast pre-scan job
1212                  * which will determine which subtitles to enable, if any.
1213                  */
1214                 job->pass = -1;
1215
1216                 x264opts_tmp = job->x264opts;
1217
1218                 job->x264opts = NULL;
1219
1220                 job->indepth_scan = subtitle_scan;
1221                 fprintf( stderr, "Subtitle Scan Enabled - enabling "
1222                          "subtitles if found for foreign language segments\n");
1223                 job->select_subtitle = malloc(sizeof(hb_subtitle_t*));
1224                 *(job->select_subtitle) = NULL;
1225
1226                 /*
1227                  * Add the pre-scan job
1228                  */
1229                 hb_add( h, job );
1230
1231                 job->x264opts = x264opts_tmp;
1232             }
1233
1234             if( twoPass )
1235             {
1236                 /*
1237                  * If subtitle_scan is enabled then only turn it on
1238                  * for the first pass and then off again for the
1239                  * second.
1240                  */
1241                 hb_subtitle_t **subtitle_tmp = job->select_subtitle;
1242
1243                 job->select_subtitle = NULL;
1244
1245                 job->pass = 1;
1246
1247                 job->indepth_scan = 0;
1248
1249                 if (x264opts)
1250                 {
1251                     x264opts2 = strdup(x264opts);
1252                 }
1253
1254                 /*
1255                  * If turbo options have been selected then append them
1256                  * to the x264opts now (size includes one ':' and the '\0')
1257                  */
1258                 if( turbo_opts_enabled )
1259                 {
1260                     int size = (x264opts ? strlen(x264opts) : 0) + strlen(turbo_opts) + 2;
1261                     char *tmp_x264opts;
1262
1263                     tmp_x264opts = malloc(size * sizeof(char));
1264                     if( x264opts )
1265                     {
1266                         snprintf( tmp_x264opts, size, "%s:%s",
1267                                   x264opts, turbo_opts );
1268                         free( x264opts );
1269                     } else {
1270                         /*
1271                          * No x264opts to modify, but apply the turbo options
1272                          * anyway as they may be modifying defaults
1273                          */
1274                         snprintf( tmp_x264opts, size, "%s",
1275                                   turbo_opts );
1276                     }
1277                     x264opts = tmp_x264opts;
1278
1279                     fprintf( stderr, "Modified x264 options for pass 1 to append turbo options: %s\n",
1280                              x264opts );
1281
1282                     job->x264opts = x264opts;
1283                 }
1284                 hb_add( h, job );
1285
1286                 job->select_subtitle = subtitle_tmp;
1287
1288                 job->pass = 2;
1289                 /*
1290                  * On the second pass we turn off subtitle scan so that we
1291                  * can actually encode using any subtitles that were auto
1292                  * selected in the first pass (using the whacky select-subtitle
1293                  * attribute of the job).
1294                  */
1295                 job->indepth_scan = 0;
1296
1297                 job->x264opts = x264opts2;
1298
1299                 hb_add( h, job );
1300             }
1301             else
1302             {
1303                 /*
1304                  * Turn on subtitle scan if requested, note that this option
1305                  * precludes encoding of any actual subtitles.
1306                  */
1307
1308                 job->indepth_scan = 0;
1309                 job->pass = 0;
1310                 hb_add( h, job );
1311             }
1312             hb_start( h );
1313             break;
1314         }
1315
1316 #define p s.param.working
1317         case HB_STATE_WORKING:
1318             fprintf( stdout, "\rEncoding: task %d of %d, %.2f %%",
1319                      p.job_cur, p.job_count, 100.0 * p.progress );
1320             if( p.seconds > -1 )
1321             {
1322                 fprintf( stdout, " (%.2f fps, avg %.2f fps, ETA "
1323                          "%02dh%02dm%02ds)", p.rate_cur, p.rate_avg,
1324                          p.hours, p.minutes, p.seconds );
1325             }
1326             fflush(stdout);
1327             break;
1328 #undef p
1329
1330 #define p s.param.muxing
1331         case HB_STATE_MUXING:
1332         {
1333             if (show_mux_warning)
1334             {
1335                 fprintf( stdout, "\rMuxing: this may take awhile..." );
1336                 fflush(stdout);
1337                 show_mux_warning = 0;
1338             }
1339             break;
1340         }
1341 #undef p
1342
1343 #define p s.param.workdone
1344         case HB_STATE_WORKDONE:
1345             /* Print error if any, then exit */
1346             switch( p.error )
1347             {
1348                 case HB_ERROR_NONE:
1349                     fprintf( stderr, "\nRip done!\n" );
1350                     break;
1351                 case HB_ERROR_CANCELED:
1352                     fprintf( stderr, "\nRip canceled.\n" );
1353                     break;
1354                 default:
1355                     fprintf( stderr, "\nRip failed (error %x).\n",
1356                              p.error );
1357             }
1358             die = 1;
1359             break;
1360 #undef p
1361     }
1362     return 0;
1363 }
1364
1365 /****************************************************************************
1366  * SigHandler:
1367  ****************************************************************************/
1368 static volatile int64_t i_die_date = 0;
1369 void SigHandler( int i_signal )
1370 {
1371     if( die == 0 )
1372     {
1373         die = 1;
1374         i_die_date = hb_get_date();
1375         fprintf( stderr, "Signal %d received, terminating - do it "
1376                  "again in case it gets stuck\n", i_signal );
1377     }
1378     else if( i_die_date + 500 < hb_get_date() )
1379     {
1380         fprintf( stderr, "Dying badly, files might remain in your /tmp\n" );
1381         exit( 1 );
1382     }
1383 }
1384
1385 /****************************************************************************
1386  * ShowHelp:
1387  ****************************************************************************/
1388 static void ShowHelp()
1389 {
1390     int i;
1391
1392     fprintf( stderr,
1393     "Syntax: HandBrakeCLI [options] -i <device> -o <file>\n"
1394     "\n"
1395         "### General Handbrake Options------------------------------------------------\n\n"
1396     "    -h, --help              Print help\n"
1397     "    -u, --update            Check for updates and exit\n"
1398     "    -v, --verbose           Be verbose\n"
1399     "    -C, --cpu               Set CPU count (default: autodetected)\n"
1400     "    -Z. --preset <string>   Use a built-in preset. Capitalization matters, and\n"
1401     "                            if the preset name has spaces, surround it with\n"
1402     "                            double quotation marks\n"
1403     "    -z, --preset-list       See a list of available built-in presets\n"
1404     "\n"
1405
1406         "### Source Options-----------------------------------------------------------\n\n"
1407         "    -i, --input <string>    Set input device\n"
1408         "    -t, --title <number>    Select a title to encode (0 to scan only,\n"
1409     "                            default: 1)\n"
1410     "    -L, --longest           Select the longest title\n"
1411     "    -c, --chapters <string> Select chapters (e.g. \"1-3\" for chapters\n"
1412     "                            1 to 3, or \"3\" for chapter 3 only,\n"
1413     "                            default: all chapters)\n"
1414         "\n"
1415
1416         "### Destination Options------------------------------------------------------\n\n"
1417     "    -o, --output <string>   Set output file name\n"
1418         "    -f, --format <string>   Set output format (avi/mp4/ogm/mkv, default:\n"
1419     "                            autodetected from file name)\n"
1420     "    -4, --large-file        Use 64-bit mp4 files that can hold more than\n"
1421     "                            4 GB. Note: Breaks iPod, @TV, PS3 compatibility.\n"""
1422     "    -O, --optimize          Optimize mp4 files for HTTP streaming\n"
1423     "    -I, --ipod-atom         Mark mp4 files so iPods will accept them\n"
1424     "\n"
1425
1426         "### Picture Settings---------------------------------------------------------\n\n"
1427     "    -w, --width <number>    Set picture width\n"
1428     "    -l, --height <number>   Set picture height\n"
1429     "        --crop <T:B:L:R>    Set cropping values (default: autocrop)\n"
1430         "    -Y, --maxHeight <#>     Set maximum height\n"
1431         "    -X, --maxWidth <#>      Set maximum width\n"
1432         "    -s, --subtitle <number> Select subtitle (default: none)\n"
1433     "    -U, --subtitle-scan     Scan for subtitles in an extra 1st pass, and choose\n"
1434     "                            the one that's only used 10 percent of the time\n"
1435     "                            or less. This should locate subtitles for short\n"
1436     "                            foreign language segments. Best used in conjunction\n"
1437     "                            with --subtitle-forced.\n"
1438     "    -F, --subtitle-forced   Only display subtitles from the selected stream if\n"
1439     "                            the subtitle has the forced flag set. May be used in\n"
1440     "                            conjunction with --subtitle-scan to auto-select\n"
1441     "                            a stream if it contains forced subtitles.\n"
1442     "    -N, --native-language   Select subtitles with this language if it does not\n"
1443     "          <string>          match the Audio language. Provide the language's\n"
1444     "                            iso639-2 code (fre, eng, spa, dut, et cetera)\n"
1445         "    -m, --markers           Add chapter markers (mp4 output format only)\n"
1446         "\n"
1447
1448         "### Video Options------------------------------------------------------------\n\n"
1449         "    -e, --encoder <string>  Set video library encoder (ffmpeg,xvid,\n"
1450     "                            x264,theora default: ffmpeg)\n"
1451         "    -q, --quality <float>   Set video quality (0.0..1.0)\n"
1452         "    -Q, --cqp               Use with -q for CQP instead of CRF\n"
1453     "    -S, --size <MB>         Set target size\n"
1454         "    -b, --vb <kb/s>         Set video bitrate (default: 1000)\n"
1455         "    -r, --rate              Set video framerate (" );
1456     for( i = 0; i < hb_video_rates_count; i++ )
1457     {
1458         fprintf( stderr, hb_video_rates[i].string );
1459         if( i != hb_video_rates_count - 1 )
1460             fprintf( stderr, "/" );
1461     }
1462     fprintf( stderr, ")\n"
1463         "\n"
1464         "    -2, --two-pass          Use two-pass mode\n"
1465      "    -d, --deinterlace       Deinterlace video with yadif/mcdeint filter\n"
1466      "          <YM:FD:MM:QP>     (default 0:-1:-1:1)\n"
1467      "           or\n"
1468      "          <fast/slow/slower>\n"
1469      "    -7, --deblock           Deblock video with pp7 filter\n"
1470      "          <QP:M>            (default 0:2)\n"
1471      "    -8, --denoise           Denoise video with hqdn3d filter\n"
1472      "          <SL:SC:TL:TC>     (default 4:3:6:4.5)\n"
1473      "           or\n"
1474      "          <weak/medium/strong>\n"
1475      "    -9, --detelecine        Detelecine video with pullup filter\n"
1476      "          <L:R:T:B:SB:MP>   (default 1:1:4:4:0:0)\n"
1477     "    -g, --grayscale         Grayscale encoding\n"
1478     "    -p, --pixelratio        Store pixel aspect ratio in video stream\n"
1479     "    -P, --loosePixelratio   Store pixel aspect ratio with specified width\n"
1480     "          <MOD:PARX:PARY>   Takes as optional arguments what number you want\n"
1481     "                            the dimensions to divide cleanly by (default 16)\n"
1482     "                            and the pixel ratio to use (default autodetected)\n)"
1483
1484
1485         "\n"
1486
1487
1488         "### Audio Options-----------------------------------------------------------\n\n"
1489         "    -a, --audio <string>    Select audio channel(s), separated by commas\n"
1490     "                            More than one output track can be used for one\n"
1491     "                            input.\n"
1492     "                            (\"none\" for no audio, \"1,2,3\" for multiple\n"
1493     "                             tracks, default: first one)\n"
1494     "    -E, --aencoder <string> Audio encoder(s) (faac/lame/vorbis/ac3) \n"
1495         "                            ac3 meaning passthrough\n"
1496         "                            Seperated by commas for more than one audio track.\n"
1497         "                            (default: guessed)\n"
1498         "    -B, --ab <kb/s>         Set audio bitrate(s)  (default: 128)\n"
1499     "                            Seperated by commas for more than one audio track.\n"
1500         "    -6, --mixdown <string>  Format(s) for surround sound downmixing\n"
1501     "                            Seperated by commas for more than one audio track.\n"
1502     "                            (mono/stereo/dpl1/dpl2/6ch, default: dpl2)\n"
1503     "    -R, --arate             Set audio samplerate(s) (" );
1504     for( i = 0; i < hb_audio_rates_count; i++ )
1505     {
1506         fprintf( stderr, hb_audio_rates[i].string );
1507         if( i != hb_audio_rates_count - 1 )
1508             fprintf( stderr, "/" );
1509     }
1510     fprintf( stderr, " kHz)\n"
1511     "                            Seperated by commas for more than one audio track.\n"
1512     "    -D, --drc <float>       Apply extra dynamic range compression to the audio,\n"
1513     "                            making soft sounds louder. Range is 1.0 to 4.0\n"
1514     "                            (too loud), with 1.5 - 2.5 being a useful range.\n"
1515     "                            Seperated by commas for more than one audio track.\n"
1516
1517
1518         "\n"
1519
1520
1521     "### Advanced Options---------------------------------------------------------\n\n"
1522     "    -x, --x264opts <string> Specify advanced x264 options in the\n"
1523     "                            same style as mencoder:\n"
1524     "                            option1=value1:option2=value2\n"
1525     "    -T, --turbo             When using 2-pass use the turbo options\n"
1526     "                            on the first pass to improve speed\n"
1527     "                            (only works with x264, affects PSNR by about 0.05dB,\n"
1528     "                            and increases first pass speed two to four times)\n"
1529     "    -V, --vfr               Perform variable framerate detelecine on NTSC video\n"
1530     );
1531 }
1532
1533 /****************************************************************************
1534  * ShowPresets:
1535  ****************************************************************************/
1536 static void ShowPresets()
1537 {
1538     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");
1539
1540     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");
1541
1542     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");
1543
1544     printf("\n+ Blind:  -b 512 -B 128 -R 48 -E faac -f mp4 -w 512 -m\n");
1545
1546     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");
1547
1548     printf("\n+ Classic:  -b 1000 -B 160 -R 48 -E faac -f mp4\n");
1549
1550     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");
1551
1552     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");
1553
1554     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");
1555
1556     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");
1557
1558     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");
1559
1560     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");
1561
1562     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");
1563
1564     printf("\n+ PS3:  -e x264 -b 2500 -B 160 -R 48 -E faac -f mp4 -p -x level=41:subme=5:me=umh\n");
1565
1566     printf("\n+ PSP:  -b 1024 -B 128 -R 48 -E faac -f mp4 -w 368 -l 208 -m\n");
1567
1568     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");
1569
1570     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");
1571
1572     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");
1573 }
1574
1575 /****************************************************************************
1576  * ParseOptions:
1577  ****************************************************************************/
1578 static int ParseOptions( int argc, char ** argv )
1579 {
1580     for( ;; )
1581     {
1582         static struct option long_options[] =
1583           {
1584             { "help",        no_argument,       NULL,    'h' },
1585             { "update",      no_argument,       NULL,    'u' },
1586             { "verbose",     no_argument,       NULL,    'v' },
1587             { "cpu",         required_argument, NULL,    'C' },
1588
1589             { "format",      required_argument, NULL,    'f' },
1590             { "input",       required_argument, NULL,    'i' },
1591             { "output",      required_argument, NULL,    'o' },
1592             { "large-file",  no_argument,       NULL,    '4' },
1593             { "optimize",    no_argument,       NULL,    'O' },
1594             { "ipod-atom",   no_argument,       NULL,    'I' },
1595
1596             { "title",       required_argument, NULL,    't' },
1597             { "longest",     no_argument,       NULL,    'L' },
1598             { "chapters",    required_argument, NULL,    'c' },
1599             { "markers",     optional_argument, NULL,    'm' },
1600             { "audio",       required_argument, NULL,    'a' },
1601             { "mixdown",     required_argument, NULL,    '6' },
1602             { "drc",         required_argument, NULL,    'D' },
1603             { "subtitle",    required_argument, NULL,    's' },
1604             { "subtitle-scan", no_argument,     NULL,    'U' },
1605             { "subtitle-forced", no_argument,   NULL,    'F' },
1606             { "native-language", required_argument, NULL,'N' },
1607
1608             { "encoder",     required_argument, NULL,    'e' },
1609             { "aencoder",    required_argument, NULL,    'E' },
1610             { "two-pass",    no_argument,       NULL,    '2' },
1611             { "deinterlace", optional_argument, NULL,    'd' },
1612             { "deblock",     optional_argument, NULL,    '7' },
1613             { "denoise",     optional_argument, NULL,    '8' },
1614             { "detelecine",  optional_argument, NULL,    '9' },
1615             { "grayscale",   no_argument,       NULL,    'g' },
1616             { "pixelratio",  no_argument,       NULL,    'p' },
1617             { "loosePixelratio", optional_argument,   NULL,    'P' },
1618             { "width",       required_argument, NULL,    'w' },
1619             { "height",      required_argument, NULL,    'l' },
1620             { "crop",        required_argument, NULL,    'n' },
1621
1622             { "vb",          required_argument, NULL,    'b' },
1623             { "quality",     required_argument, NULL,    'q' },
1624             { "size",        required_argument, NULL,    'S' },
1625             { "ab",          required_argument, NULL,    'B' },
1626             { "rate",        required_argument, NULL,    'r' },
1627             { "arate",       required_argument, NULL,    'R' },
1628             { "cqp",         no_argument,       NULL,    'Q' },
1629             { "x264opts",    required_argument, NULL,    'x' },
1630             { "turbo",       no_argument,       NULL,    'T' },
1631             { "maxHeight",   required_argument, NULL,    'Y' },
1632             { "maxWidth",    required_argument, NULL,    'X' },
1633             { "preset",      required_argument, NULL,    'Z' },
1634             { "preset-list", no_argument,       NULL,    'z' },
1635             { "vfr",         no_argument,       NULL,    'V' },
1636
1637             { 0, 0, 0, 0 }
1638           };
1639
1640         int option_index = 0;
1641         int c;
1642
1643                 c = getopt_long( argc, argv,
1644                                                  "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",
1645                          long_options, &option_index );
1646         if( c < 0 )
1647         {
1648             break;
1649         }
1650
1651         switch( c )
1652         {
1653             case 'h':
1654                 ShowHelp();
1655                 exit( 0 );
1656             case 'u':
1657                 update = 1;
1658                 break;
1659             case 'v':
1660                 debug = HB_DEBUG_ALL;
1661                 break;
1662             case 'C':
1663                 cpu = atoi( optarg );
1664                 break;
1665
1666             case 'Z':
1667                 preset = 1;
1668                 preset_name = strdup(optarg);
1669                 break;
1670             case 'z':
1671                 ShowPresets();
1672                 exit ( 0 );
1673
1674             case 'f':
1675                 format = strdup( optarg );
1676                 break;
1677             case 'i':
1678                 input = strdup( optarg );
1679                 #ifdef __APPLE_CC__
1680                 char *devName = bsd_name_for_path( input );
1681                 if( devName == NULL )
1682                 {
1683                     return 0;
1684                 }
1685                 if( device_is_dvd( devName ) )
1686                 {
1687                     char *newInput = malloc( strlen("/dev/") + strlen( devName ) + 1);
1688                     sprintf( newInput, "/dev/%s", devName );
1689                     free(input);
1690                     input = newInput;
1691                 }
1692                 #endif
1693                 break;
1694             case 'o':
1695                 output = strdup( optarg );
1696                 break;
1697             case '4':
1698                 largeFileSize = 1;
1699                 break;
1700             case 'O':
1701                 mp4_optimize = 1;
1702                 break;
1703             case 'I':
1704                 ipod_atom = 1;
1705                 break;
1706
1707             case 't':
1708                 titleindex = atoi( optarg );
1709                 break;
1710             case 'L':
1711                 longest_title = 1;
1712                 break;
1713             case 'c':
1714             {
1715                 int start, end;
1716                 if( sscanf( optarg, "%d-%d", &start, &end ) == 2 )
1717                 {
1718                     chapter_start = start;
1719                     chapter_end   = end;
1720                 }
1721                 else if( sscanf( optarg, "%d", &start ) == 1 )
1722                 {
1723                     chapter_start = start;
1724                     chapter_end   = chapter_start;
1725                 }
1726                 else
1727                 {
1728                     fprintf( stderr, "chapters: invalid syntax (%s)\n",
1729                              optarg );
1730                     return -1;
1731                 }
1732                 break;
1733             }
1734             case 'm':
1735                 if( optarg != NULL )
1736                 {
1737                     marker_file = strdup( optarg );
1738                 }
1739                 chapter_markers = 1;
1740                 break;
1741             case 'a':
1742             {
1743                 char * token = strtok(optarg, ",");
1744                 if (token == NULL)
1745                     token = optarg;
1746                 int track_start, track_end;
1747                 while( token != NULL )
1748                 {
1749                     audio = calloc(1, sizeof(*audio));
1750                     hb_audio_config_init(audio);
1751                     if (strlen(token) >= 3)
1752                     {
1753                         if (sscanf(token, "%d-%d", &track_start, &track_end) == 2)
1754                         {
1755                             int i;
1756                             for (i = track_start - 1; i < track_end; i++)
1757                             {
1758                                 if (i != track_start - 1)
1759                                 {
1760                                     audio = calloc(1, sizeof(*audio));
1761                                     hb_audio_config_init(audio);
1762                                 }
1763                                 audio->in.track = i;
1764                                 audio->out.track = num_audio_tracks++;
1765                                 hb_list_add(audios, audio);
1766                             }
1767                         }
1768                         else if( !strcasecmp(token, "none" ) )
1769                         {
1770                             audio->in.track = audio->out.track = -1;
1771                             audio->out.codec = 0;
1772                             hb_list_add(audios, audio);
1773                             break;
1774                         }
1775                         else
1776                         {
1777                             fprintf(stderr, "ERROR: Unable to parse audio input \"%s\", skipping.",
1778                                     token);
1779                             free(audio);
1780                         }
1781                     }
1782                     else
1783                     {
1784                         audio->in.track = atoi(token) - 1;
1785                         audio->out.track = num_audio_tracks++;
1786                         hb_list_add(audios, audio);
1787                     }
1788                     token = strtok(NULL, ",");
1789                 }
1790                 break;
1791             }
1792             case '6':
1793                 if( optarg != NULL )
1794                 {
1795                     mixdowns = strdup( optarg );
1796                 }
1797                 break;
1798             case 'D':
1799                 if( optarg != NULL )
1800                 {
1801                     dynamic_range_compression = strdup( optarg );
1802                 }
1803                 break;
1804             case 's':
1805                 sub = atoi( optarg );
1806                 break;
1807             case 'U':
1808                 subtitle_scan = 1;
1809                 break;
1810             case 'F':
1811                 subtitle_force = 1;
1812                 break;
1813             case 'N':
1814                 native_language = strdup( optarg );
1815                 break;
1816             case '2':
1817                 twoPass = 1;
1818                 break;
1819             case 'd':
1820                 if( optarg != NULL )
1821                 {
1822                     if (!( strcmp( optarg, "fast" ) ))
1823                     {
1824                         deinterlace_opt = "-1";
1825                     }
1826                     else if (!( strcmp( optarg, "slow" ) ))
1827                     {
1828                         deinterlace_opt = "2";
1829                     }
1830                     else if (!( strcmp( optarg, "slower" ) ))
1831                     {
1832                         deinterlace_opt = "0";
1833                     }
1834                     else
1835                     {
1836                         deinterlace_opt = strdup( optarg );
1837                     }
1838                 }
1839                 deinterlace = 1;
1840                 break;
1841             case '7':
1842                 if( optarg != NULL )
1843                 {
1844                     deblock_opt = strdup( optarg );
1845                 }
1846                 deblock = 1;
1847                 break;
1848             case '8':
1849                 if( optarg != NULL )
1850                 {
1851                     if (!( strcmp( optarg, "weak" ) ))
1852                     {
1853                         denoise_opt = "2:1:2:3";
1854                     }
1855                     else if (!( strcmp( optarg, "medium" ) ))
1856                     {
1857                         denoise_opt = "3:2:2:3";
1858                     }
1859                     else if (!( strcmp( optarg, "strong" ) ))
1860                     {
1861                         denoise_opt = "7:7:5:5";
1862                     }
1863                     else
1864                     {
1865                         denoise_opt = strdup( optarg );
1866                     }
1867                 }
1868                 denoise = 1;
1869                 break;
1870             case '9':
1871                 if( optarg != NULL )
1872                 {
1873                     detelecine_opt = strdup( optarg );
1874                 }
1875                 detelecine = 1;
1876                 break;
1877             case 'g':
1878                 grayscale = 1;
1879                 break;
1880             case 'p':
1881                 pixelratio = 1;
1882                 break;
1883             case 'P':
1884                 loosePixelratio = 1;
1885                 if( optarg != NULL )
1886                 {
1887                     sscanf( optarg, "%i:%i:%i", &modulus, &par_width, &par_height );
1888                 }
1889                 break;
1890             case 'e':
1891                 if( !strcasecmp( optarg, "ffmpeg" ) )
1892                 {
1893                     vcodec = HB_VCODEC_FFMPEG;
1894                 }
1895                 else if( !strcasecmp( optarg, "xvid" ) )
1896                 {
1897                     vcodec = HB_VCODEC_XVID;
1898                 }
1899                 else if( !strcasecmp( optarg, "x264" ) )
1900                 {
1901                     vcodec = HB_VCODEC_X264;
1902                 }
1903                 else if( !strcasecmp( optarg, "x264b13" ) )
1904                 {
1905                     vcodec = HB_VCODEC_X264;
1906                     h264_13 = 1;
1907                 }
1908                 else if( !strcasecmp( optarg, "x264b30" ) )
1909                 {
1910                     vcodec = HB_VCODEC_X264;
1911                     h264_30 = 1;
1912                 }
1913                 else if( !strcasecmp( optarg, "theora" ) )
1914                 {
1915                     vcodec = HB_VCODEC_THEORA;
1916                 }
1917                 else
1918                 {
1919                     fprintf( stderr, "invalid codec (%s)\n", optarg );
1920                     return -1;
1921                 }
1922                 break;
1923             case 'E':
1924                 if( optarg != NULL )
1925                 {
1926                     acodecs = strdup( optarg );
1927                 }
1928                 break;
1929             case 'w':
1930                 width = atoi( optarg );
1931                 break;
1932             case 'l':
1933                 height = atoi( optarg );
1934                 break;
1935             case 'n':
1936             {
1937                 int    i;
1938                 char * tmp = optarg;
1939                 for( i = 0; i < 4; i++ )
1940                 {
1941                     if( !*tmp )
1942                         break;
1943                     crop[i] = strtol( tmp, &tmp, 0 );
1944                     tmp++;
1945                 }
1946                 break;
1947             }
1948             case 'r':
1949             {
1950                 int i;
1951                 vrate = 0;
1952                 for( i = 0; i < hb_video_rates_count; i++ )
1953                 {
1954                     if( !strcmp( optarg, hb_video_rates[i].string ) )
1955                     {
1956                         vrate = hb_video_rates[i].rate;
1957                         break;
1958                     }
1959                 }
1960                 if( !vrate )
1961                 {
1962                     fprintf( stderr, "invalid framerate %s\n", optarg );
1963                 }
1964                 break;
1965             }
1966             case 'R':
1967                 if( optarg != NULL )
1968                 {
1969                     arates = strdup( optarg );
1970                 }
1971                 break;
1972             case 'b':
1973                 vbitrate = atoi( optarg );
1974                 break;
1975             case 'q':
1976                 vquality = atof( optarg );
1977                 break;
1978             case 'S':
1979                 size = atoi( optarg );
1980                 break;
1981             case 'B':
1982                 if( optarg != NULL )
1983                 {
1984                     abitrates = strdup( optarg );
1985                 }
1986                 break;
1987             case 'Q':
1988                 crf = 0;
1989                 break;
1990             case 'x':
1991                 x264opts = strdup( optarg );
1992                 break;
1993             case 'T':
1994                 turbo_opts_enabled = 1;
1995                 break;
1996             case 'Y':
1997                 maxHeight = atoi( optarg );
1998                 break;
1999             case 'X':
2000                 maxWidth = atoi (optarg );
2001                 break;
2002             case 'V':
2003                 vfr = 1;
2004                 break;
2005
2006             default:
2007                 fprintf( stderr, "unknown option (%s)\n", argv[optind] );
2008                 return -1;
2009         }
2010     }
2011
2012     return 0;
2013 }
2014
2015 static int CheckOptions( int argc, char ** argv )
2016 {
2017     if( update )
2018     {
2019         return 0;
2020     }
2021
2022     if( input == NULL || *input == '\0' )
2023     {
2024         fprintf( stderr, "Missing input device. Run %s --help for "
2025                  "syntax.\n", argv[0] );
2026         return 1;
2027     }
2028
2029     /* Parse format */
2030     if( titleindex > 0 )
2031     {
2032         if( output == NULL || *output == '\0' )
2033         {
2034             fprintf( stderr, "Missing output file name. Run %s --help "
2035                      "for syntax.\n", argv[0] );
2036             return 1;
2037         }
2038
2039         if( !format )
2040         {
2041             char * p = strrchr( output, '.' );
2042
2043             /* autodetect */
2044             if( p && !strcasecmp( p, ".avi" ) )
2045             {
2046                 mux = HB_MUX_AVI;
2047                 default_acodec = HB_ACODEC_LAME;
2048             }
2049             else if( p && ( !strcasecmp( p, ".mp4" )  ||
2050                             !strcasecmp( p, ".m4v" ) ) )
2051             {
2052                 if ( h264_30 == 1 )
2053                     mux = HB_MUX_IPOD;
2054                 else
2055                     mux = HB_MUX_MP4;
2056                 default_acodec = HB_ACODEC_FAAC;
2057             }
2058             else if( p && ( !strcasecmp( p, ".ogm" ) ||
2059                             !strcasecmp( p, ".ogg" ) ) )
2060             {
2061                 mux = HB_MUX_OGM;
2062                 default_acodec = HB_ACODEC_VORBIS;
2063             }
2064             else if( p && !strcasecmp(p, ".mkv" ) )
2065             {
2066                 mux = HB_MUX_MKV;
2067                 default_acodec = HB_ACODEC_AC3;
2068             }
2069             else
2070             {
2071                 fprintf( stderr, "Output format couldn't be guessed "
2072                          "from file name, using default.\n" );
2073                 return 0;
2074             }
2075         }
2076         else if( !strcasecmp( format, "avi" ) )
2077         {
2078             mux = HB_MUX_AVI;
2079             default_acodec = HB_ACODEC_LAME;
2080         }
2081         else if( !strcasecmp( format, "mp4" ) ||
2082                  !strcasecmp( format, "m4v" ) )
2083         {
2084             if ( h264_30 == 1)
2085                 mux = HB_MUX_IPOD;
2086             else
2087                 mux = HB_MUX_MP4;
2088             default_acodec = HB_ACODEC_FAAC;
2089         }
2090         else if( !strcasecmp( format, "ogm" ) ||
2091                  !strcasecmp( format, "ogg" ) )
2092         {
2093             mux = HB_MUX_OGM;
2094             default_acodec = HB_ACODEC_VORBIS;
2095         }
2096         else if( !strcasecmp( format, "mkv" ) )
2097         {
2098             mux = HB_MUX_MKV;
2099             default_acodec = HB_ACODEC_AC3;
2100         }
2101         else
2102         {
2103             fprintf( stderr, "Invalid output format (%s). Possible "
2104                      "choices are avi, mp4, m4v, ogm, ogg and mkv\n.", format );
2105             return 1;
2106         }
2107     }
2108
2109     return 0;
2110 }
2111
2112 static int get_acodec_for_string( char *codec )
2113 {
2114     if( !strcasecmp( codec, "ac3" ) )
2115     {
2116         return HB_ACODEC_AC3;
2117     }
2118     else if( !strcasecmp( codec, "dts" ) || !strcasecmp( codec, "dca" ) )
2119     {
2120         return HB_ACODEC_DCA;
2121     }
2122     else if( !strcasecmp( codec, "lame" ) )
2123     {
2124         return HB_ACODEC_LAME;
2125     }
2126     else if( !strcasecmp( codec, "faac" ) )
2127     {
2128         return HB_ACODEC_FAAC;
2129     }
2130     else if( !strcasecmp( codec, "vorbis") )
2131     {
2132         return HB_ACODEC_VORBIS;
2133     }
2134     else
2135     {
2136         return -1;
2137     }
2138 }
2139
2140 static int is_sample_rate_valid(int rate)
2141 {
2142     int i;
2143     for( i = 0; i < hb_audio_rates_count; i++ )
2144     {
2145             if (rate == hb_audio_rates[i].rate)
2146                 return 1;
2147     }
2148     return 0;
2149 }
2150
2151 #ifdef __APPLE_CC__
2152 /****************************************************************************
2153  * bsd_name_for_path
2154  *
2155  * Returns the BSD device name for the block device that contains the
2156  * passed-in path. Returns NULL on failure.
2157  ****************************************************************************/
2158 static char* bsd_name_for_path(char *path)
2159 {
2160     OSStatus err;
2161     FSRef ref;
2162     err = FSPathMakeRef( (const UInt8 *) input, &ref, NULL );
2163     if( err != noErr )
2164     {
2165         return NULL;
2166     }
2167
2168     // Get the volume reference number.
2169     FSCatalogInfo catalogInfo;
2170     err = FSGetCatalogInfo( &ref, kFSCatInfoVolume, &catalogInfo, NULL, NULL,
2171                             NULL);
2172     if( err != noErr )
2173     {
2174         return NULL;
2175     }
2176     FSVolumeRefNum volRefNum = catalogInfo.volume;
2177
2178     // Now let's get the device name
2179     GetVolParmsInfoBuffer volumeParms;
2180     err = FSGetVolumeParms( volRefNum, &volumeParms, sizeof( volumeParms ) );
2181     if( err != noErr )
2182     {
2183         return NULL;
2184     }
2185
2186     // A version 4 GetVolParmsInfoBuffer contains the BSD node name in the
2187     // vMDeviceID field. It is actually a char * value. This is mentioned in the
2188     // header CoreServices/CarbonCore/Files.h.
2189     return volumeParms.vMDeviceID;
2190 }
2191
2192 /****************************************************************************
2193  * device_is_dvd
2194  *
2195  * Returns whether or not the passed in BSD device represents a DVD, or other
2196  * optical media.
2197  ****************************************************************************/
2198 static int device_is_dvd(char *device)
2199 {
2200     io_service_t service = get_iokit_service(device);
2201     if( service == IO_OBJECT_NULL )
2202     {
2203         return 0;
2204     }
2205     int result = is_dvd_service(service);
2206     IOObjectRelease(service);
2207     return result;
2208 }
2209
2210 /****************************************************************************
2211  * get_iokit_service
2212  *
2213  * Returns the IOKit service object for the passed in BSD device name.
2214  ****************************************************************************/
2215 static io_service_t get_iokit_service( char *device )
2216 {
2217     CFMutableDictionaryRef matchingDict;
2218     matchingDict = IOBSDNameMatching( kIOMasterPortDefault, 0, device );
2219     if( matchingDict == NULL )
2220     {
2221         return IO_OBJECT_NULL;
2222     }
2223     // Fetch the object with the matching BSD node name. There should only be
2224     // one match, so IOServiceGetMatchingService is used instead of
2225     // IOServiceGetMatchingServices to simplify the code.
2226     return IOServiceGetMatchingService( kIOMasterPortDefault, matchingDict );
2227 }
2228
2229 /****************************************************************************
2230  * is_dvd_service
2231  *
2232  * Returns whether or not the service passed in is a DVD.
2233  *
2234  * Searches for an IOMedia object that represents the entire (whole) media that
2235  * the volume is on. If the volume is on partitioned media, the whole media
2236  * object will be a parent of the volume's media object. If the media is not
2237  * partitioned, the volume's media object will be the whole media object.
2238  ****************************************************************************/
2239 static int is_dvd_service( io_service_t service )
2240 {
2241     kern_return_t  kernResult;
2242     io_iterator_t  iter;
2243
2244     // Create an iterator across all parents of the service object passed in.
2245     kernResult = IORegistryEntryCreateIterator( service,
2246                                                 kIOServicePlane,
2247                                                 kIORegistryIterateRecursively | kIORegistryIterateParents,
2248                                                 &iter );
2249     if( kernResult != KERN_SUCCESS )
2250     {
2251         return 0;
2252     }
2253     if( iter == IO_OBJECT_NULL )
2254     {
2255         return 0;
2256     }
2257
2258     // A reference on the initial service object is released in the do-while
2259     // loop below, so add a reference to balance.
2260     IOObjectRetain( service );
2261
2262     int result = 0;
2263     do
2264     {
2265         if( is_whole_media_service( service ) &&
2266             IOObjectConformsTo( service, kIODVDMediaClass) )
2267         {
2268             result = 1;
2269         }
2270         IOObjectRelease( service );
2271     } while( !result && (service = IOIteratorNext( iter )) );
2272     IOObjectRelease( iter );
2273
2274     return result;
2275 }
2276
2277 /****************************************************************************
2278  * is_whole_media_service
2279  *
2280  * Returns whether or not the service passed in is an IOMedia service and
2281  * represents the "whole" media instead of just a partition.
2282  *
2283  * The whole media object is indicated in the IORegistry by the presence of a
2284  * property with the key "Whole" and value "Yes".
2285  ****************************************************************************/
2286 static is_whole_media_service( io_service_t service )
2287 {
2288     int result = 0;
2289
2290     if( IOObjectConformsTo( service, kIOMediaClass ) )
2291     {
2292         CFTypeRef wholeMedia = IORegistryEntryCreateCFProperty( service,
2293                                                                 CFSTR( kIOMediaWholeKey ),
2294                                                                 kCFAllocatorDefault,
2295                                                                 0 );
2296         if ( !wholeMedia )
2297         {
2298             return 0;
2299         }
2300         result = CFBooleanGetValue( (CFBooleanRef)wholeMedia );
2301         CFRelease( wholeMedia );
2302     }
2303
2304     return result;
2305 }
2306 #endif // __APPLE_CC__