OSDN Git Service

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