OSDN Git Service

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