OSDN Git Service

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