OSDN Git Service

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