OSDN Git Service

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