OSDN Git Service

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