OSDN Git Service

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