OSDN Git Service

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