OSDN Git Service

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