OSDN Git Service

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