OSDN Git Service

Gives the CLI a separate option for adding the iPod UUID atom to mp4 files, instead...
[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.m0k.org/>.
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 /* Options */
17 static int    debug       = HB_DEBUG_NONE;
18 static int    update      = 0;
19 static char * input       = NULL;
20 static char * output      = NULL;
21 static char * format      = NULL;
22 static int    titleindex  = 1;
23 static int    longest_title = 0;
24 static int    subtitle_scan = 0;
25 static int    subtitle_force = 0;
26 static char * native_language = NULL;
27 static int    twoPass     = 0;
28 static int    deinterlace           = 0;
29 static char * deinterlace_opt       = 0;
30 static int    deblock               = 0;
31 static char * deblock_opt           = 0;
32 static int    denoise               = 0;
33 static char * denoise_opt           = 0;
34 static int    detelecine            = 0;
35 static char * detelecine_opt        = 0;
36 static int    grayscale   = 0;
37 static int    vcodec      = HB_VCODEC_FFMPEG;
38 static int    h264_13     = 0;
39 static int    h264_30     = 0;
40 static char * audios      = NULL;
41 static int    audio_mixdown = HB_AMIXDOWN_DOLBYPLII;
42 static int    sub         = 0;
43 static int    width       = 0;
44 static int    height      = 0;
45 static int    crop[4]     = { -1,-1,-1,-1 };
46 static int    cpu         = 0;
47 static int    vrate       = 0;
48 static int    arate       = 0;
49 static float  vquality    = -1.0;
50 static int    vbitrate    = 0;
51 static int    size        = 0;
52 static int    abitrate    = 0;
53 static int    mux         = 0;
54 static int    acodec      = 0;
55 static int    pixelratio  = 0;
56 static int    loosePixelratio = 0;
57 static int    modulus       = 0;
58 static int    chapter_start = 0;
59 static int    chapter_end   = 0;
60 static int    chapter_markers = 0;
61 static char * marker_file   = NULL;
62 static int        crf                   = 0;
63 static char       *x264opts             = NULL;
64 static char       *x264opts2    = NULL;
65 static int        maxHeight             = 0;
66 static int        maxWidth              = 0;
67 static int    turbo_opts_enabled = 0;
68 static char * turbo_opts = "ref=1:subme=1:me=dia:analyse=none:trellis=0:no-fast-pskip=0:8x8dct=0";
69 static int    largeFileSize = 0;
70 static int    preset        = 0;
71 static char * preset_name   = 0;
72 static int    vfr           = 0;
73 static int    mp4_optimize  = 0;
74 static int    ipod_atom     = 0;
75
76 /* Exit cleanly on Ctrl-C */
77 static volatile int die = 0;
78 static void SigHandler( int );
79
80 /* Utils */
81 static void ShowCommands();
82 static void ShowHelp();
83 static void ShowPresets();
84
85 static int  ParseOptions( int argc, char ** argv );
86 static int  CheckOptions( int argc, char ** argv );
87 static int  HandleEvents( hb_handle_t * h );
88
89 /****************************************************************************
90  * hb_error_handler
91  * 
92  * When using the CLI just display using hb_log as we always did in the past
93  * make sure that we prefix with a nice ERROR message to catch peoples eyes.
94  ****************************************************************************/
95 static void hb_cli_error_handler ( const char *errmsg )
96 {
97     fprintf( stderr, "ERROR: %s", errmsg );
98 }
99
100 int main( int argc, char ** argv )
101 {
102     hb_handle_t * h;
103     int           build;
104     char        * version;
105
106     /* Parse command line */
107     if( ParseOptions( argc, argv ) ||
108         CheckOptions( argc, argv ) )
109     {
110         return 1;
111     }
112
113     /* Register our error handler */
114     hb_register_error_handler(&hb_cli_error_handler);
115
116     /* Init libhb */
117     h = hb_init( debug, update );
118
119     /* Show version */
120     fprintf( stderr, "HandBrake %s (%d) - http://handbrake.m0k.org/\n",
121              hb_get_version( h ), hb_get_build( h ) );
122
123     /* Check for update */
124     if( update )
125     {
126         if( ( build = hb_check_update( h, &version ) ) > -1 )
127         {
128             fprintf( stderr, "You are using an old version of "
129                      "HandBrake.\nLatest is %s (build %d).\n", version,
130                      build );
131         }
132         else
133         {
134             fprintf( stderr, "Your version of HandBrake is up to "
135                      "date.\n" );
136         }
137         hb_close( &h );
138         return 0;
139     }
140
141     /* Geeky */
142     fprintf( stderr, "%d CPU%s detected\n", hb_get_cpu_count(),
143              hb_get_cpu_count( h ) > 1 ? "s" : "" );
144     if( cpu )
145     {
146         fprintf( stderr, "Forcing %d CPU%s\n", cpu,
147                  cpu > 1 ? "s" : "" );
148         hb_set_cpu_count( h, cpu );
149     }
150
151     /* Exit ASAP on Ctrl-C */
152     signal( SIGINT, SigHandler );
153
154     /* Feed libhb with a DVD to scan */
155     fprintf( stderr, "Opening %s...\n", input );
156
157     if (longest_title) {
158         /*
159          * We need to scan for all the titles in order to find the longest
160          */
161         titleindex = 0;
162     }
163     hb_scan( h, input, titleindex );
164
165     /* Wait... */
166     while( !die )
167     {
168 #if !defined(SYS_BEOS)
169         fd_set         fds;
170         struct timeval tv;
171         int            ret;
172         char           buf[257];
173
174         tv.tv_sec  = 0;
175         tv.tv_usec = 100000;
176
177         FD_ZERO( &fds );
178         FD_SET( STDIN_FILENO, &fds );
179         ret = select( STDIN_FILENO + 1, &fds, NULL, NULL, &tv );
180
181         if( ret > 0 )
182         {
183             int size = 0;
184
185             while( size < 256 &&
186                    read( STDIN_FILENO, &buf[size], 1 ) > 0 )
187             {
188                 if( buf[size] == '\n' )
189                 {
190                     break;
191                 }
192                 size++;
193             }
194
195             if( size >= 256 || buf[size] == '\n' )
196             {
197                 switch( buf[0] )
198                 {
199                     case 'q':
200                         fprintf( stdout, "\nEncoding Quit by user command\n" );
201                         die = 1;
202                         break;
203                     case 'p':
204                         fprintf( stdout, "\nEncoding Paused by user command, 'r' to resume\n" );
205                         hb_pause( h );
206                         break;
207                     case 'r':
208                         hb_resume( h );
209                         break;
210                     case 'h':
211                         ShowCommands();
212                         break;
213                 }
214             }
215         }
216         hb_snooze( 200 );
217 #else
218         hb_snooze( 200 );
219 #endif
220
221         HandleEvents( h );
222     }
223
224     /* Clean up */
225     hb_close( &h );
226     if( input )  free( input );
227     if( output ) free( output );
228     if( format ) free( format );
229     if( audios ) free( audios );
230     if (native_language ) free (native_language );
231         if( x264opts ) free (x264opts );
232         if( x264opts2 ) free (x264opts2 );
233     if (preset_name) free (preset_name);
234         
235     fprintf( stderr, "HandBrake has exited.\n" );
236
237     return 0;
238 }
239
240 static void ShowCommands()
241 {
242     fprintf( stdout, "\nCommands:\n" );
243     fprintf( stdout, " [h]elp    Show this message\n" );
244     fprintf( stdout, " [q]uit    Exit HandBrakeCLI\n" );
245     fprintf( stdout, " [p]ause   Pause encoding\n" );
246     fprintf( stdout, " [r]esume  Resume encoding\n" );
247 }
248
249 static void PrintTitleInfo( hb_title_t * title )
250 {
251     hb_chapter_t  * chapter;
252     hb_audio_t    * audio;
253     hb_subtitle_t * subtitle;
254     int i;
255
256     fprintf( stderr, "+ title %d:\n", title->index );
257     fprintf( stderr, "  + vts %d, ttn %d, cells %d->%d (%d blocks)\n",
258              title->vts, title->ttn, title->cell_start, title->cell_end,
259              title->block_count );
260     fprintf( stderr, "  + duration: %02d:%02d:%02d\n",
261              title->hours, title->minutes, title->seconds );
262     fprintf( stderr, "  + size: %dx%d, aspect: %.2f, %.3f fps\n",
263              title->width, title->height,
264              (float) title->aspect / HB_ASPECT_BASE,
265              (float) title->rate / title->rate_base );
266     fprintf( stderr, "  + autocrop: %d/%d/%d/%d\n", title->crop[0],
267              title->crop[1], title->crop[2], title->crop[3] );
268     fprintf( stderr, "  + chapters:\n" );
269     for( i = 0; i < hb_list_count( title->list_chapter ); i++ )
270     {
271         chapter = hb_list_item( title->list_chapter, i );
272         fprintf( stderr, "    + %d: cells %d->%d, %d blocks, duration "
273                  "%02d:%02d:%02d\n", chapter->index,
274                  chapter->cell_start, chapter->cell_end,
275                  chapter->block_count, chapter->hours, chapter->minutes,
276                  chapter->seconds );
277     }
278     fprintf( stderr, "  + audio tracks:\n" );
279     for( i = 0; i < hb_list_count( title->list_audio ); i++ )
280     {
281         audio = hb_list_item( title->list_audio, i );
282         if( ( audio->codec & HB_ACODEC_AC3 ) || ( audio->codec & HB_ACODEC_DCA) )
283         {
284             fprintf( stderr, "    + %d, %s, %dHz, %dbps\n", i + 1,
285                      audio->lang, audio->rate, audio->bitrate );
286         }
287         else
288         {
289             fprintf( stderr, "    + %d, %s\n", i + 1, audio->lang );
290         }
291     }
292     fprintf( stderr, "  + subtitle tracks:\n" );
293     for( i = 0; i < hb_list_count( title->list_subtitle ); i++ )
294     {
295         subtitle = hb_list_item( title->list_subtitle, i );
296         fprintf( stderr, "    + %d, %s (iso639-2: %s)\n", i + 1, subtitle->lang,
297             subtitle->iso639_2);
298     }
299 }
300
301 static int HandleEvents( hb_handle_t * h )
302 {
303     hb_state_t s;
304     hb_get_state( h, &s );
305     switch( s.state )
306     {
307         case HB_STATE_IDLE:
308             /* Nothing to do */
309             break;
310
311 #define p s.param.scanning
312         case HB_STATE_SCANNING:
313             /* Show what title is currently being scanned */
314             fprintf( stderr, "Scanning title %d", p.title_cur );
315             if( !titleindex )
316                 fprintf( stderr, " of %d", p.title_count );
317             fprintf( stderr, "...\n" );
318             break;
319 #undef p
320
321         case HB_STATE_SCANDONE:
322         {
323             hb_list_t  * list;
324             hb_title_t * title;
325             hb_job_t   * job;
326
327             list = hb_get_titles( h );
328
329             if( !hb_list_count( list ) )
330             {
331                 /* No valid title, stop right there */
332                 fprintf( stderr, "No title found.\n" );
333                 die = 1;
334                 break;
335             }
336             if( longest_title )
337             {
338                 int i;
339                 int longest_title_idx=0;
340                 int longest_title_pos=-1;
341                 int longest_title_time=0;
342                 int title_time;
343                 
344                 fprintf( stderr, "Searching for longest title...\n" );
345
346                 for( i = 0; i < hb_list_count( list ); i++ )
347                 {
348                     title = hb_list_item( list, i );
349                     title_time = (title->hours*60*60 ) + (title->minutes *60) + (title->seconds);
350                     fprintf( stderr, " + Title (%d) index %d has length %dsec\n", 
351                              i, title->index, title_time );
352                     if( longest_title_time < title_time )
353                     {
354                         longest_title_time = title_time;
355                         longest_title_pos = i;
356                         longest_title_idx = title->index;
357                     }               
358                 }
359                 if( longest_title_pos == -1 ) 
360                 {
361                     fprintf( stderr, "No longest title found.\n" );
362                     die = 1;
363                     break;
364                 }
365                 titleindex = longest_title_idx;
366                 fprintf( stderr, "Found longest title, setting title to %d\n", 
367                          longest_title_idx);
368
369                 title = hb_list_item( list, longest_title_pos);
370             } else {
371                 title = hb_list_item( list, 0 );
372             }
373
374             if( !titleindex )
375             {
376                 /* Scan-only mode, print infos and exit */
377                 int i;
378                 for( i = 0; i < hb_list_count( list ); i++ )
379                 {
380                     title = hb_list_item( list, i );
381                     PrintTitleInfo( title );
382                 }
383                 die = 1;
384                 break;
385             }
386
387             /* Set job settings */
388             job   = title->job;
389
390             PrintTitleInfo( title );
391
392             if( chapter_start && chapter_end )
393             {
394                 job->chapter_start = MAX( job->chapter_start,
395                                           chapter_start );
396                 job->chapter_end   = MIN( job->chapter_end,
397                                           chapter_end );
398                 job->chapter_end   = MAX( job->chapter_start,
399                                           job->chapter_end );
400             }
401
402             if (preset)
403             {
404                 hb_log("+ Using preset: %s", preset_name);
405                 
406                 if (!strcmp(preset_name, "Animation"))
407                 {
408                     mux = HB_MUX_MKV;
409                     vcodec = HB_VCODEC_X264;
410                     job->vbitrate = 1000;
411                     job->abitrate = 160;
412                     job->arate = 48000;
413                     acodec = HB_ACODEC_FAAC;
414                     x264opts = strdup("ref=5:mixed-refs:bframes=16: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");
415                     job->chapter_markers = 1;
416                     job->deinterlace = 1;
417                     pixelratio = 1;
418                     twoPass = 1;
419                     turbo_opts_enabled = 1;
420                 }
421
422                 if (!strcmp(preset_name, "AppleTV"))
423                 {
424                     mux = HB_MUX_MP4;
425                     vcodec = HB_VCODEC_X264;
426                     job->vbitrate = 2500;
427                     job->abitrate = 160;
428                     job->arate = 48000;
429                     acodec = HB_ACODEC_FAAC;
430                     x264opts = strdup("bframes=3:ref=1:subme=5:me=umh:no-fast-pskip=1:trellis=2:cabac=0");
431                     job->chapter_markers = 1;
432                     pixelratio = 1;
433                 }
434
435                 if (!strcmp(preset_name, "Bedlam"))
436                 {
437                     mux = HB_MUX_MKV;
438                     vcodec = HB_VCODEC_X264;
439                     job->vbitrate = 1800;
440                     acodec = HB_ACODEC_AC3;
441                     x264opts = strdup("ref=16:mixed-refs:bframes=16:bime:weightb:b-rdo:direct=auto:b-pyramid:me=umh:subme=7:me-range=64:analyse=all:8x8dct:trellis=2:no-fast-pskip:no-dct-decimate:filter=-2,-1");
442                     job->chapter_markers = 1;
443                     pixelratio = 1;
444                     twoPass = 1;
445                     turbo_opts_enabled = 1;
446                 }
447
448                 if (!strcmp(preset_name, "Blind"))
449                 {
450                     mux = HB_MUX_MP4;
451                     job->vbitrate = 512;
452                     job->abitrate = 128;
453                     job->arate = 48000;
454                     acodec = HB_ACODEC_FAAC;
455                     job->width = 512;
456                     job->chapter_markers = 1;
457                 }
458
459                 if (!strcmp(preset_name, "Broke"))
460                 {
461                     mux = HB_MUX_MP4;
462                     vcodec = HB_VCODEC_X264;
463                     size = 695;
464                     job->abitrate = 128;
465                     job->arate = 48000;
466                     acodec = HB_ACODEC_FAAC;
467                     job->width = 640;
468                     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");
469                     job->chapter_markers = 1;
470                     twoPass = 1;
471                     turbo_opts_enabled = 1;
472                 }
473
474                 if (!strcmp(preset_name, "Classic"))
475                 {
476                     mux = HB_MUX_MP4;
477                     job->vbitrate = 1000;
478                     job->abitrate = 160;
479                     job->arate = 48000;
480                     acodec = HB_ACODEC_FAAC;
481                  }
482
483                 if (!strcmp(preset_name, "Constant Quality Rate"))
484                 {
485                     mux = HB_MUX_MKV;
486                     vcodec = HB_VCODEC_X264;
487                     job->vquality = 0.64709997177124023;
488                     job->crf = 1;
489                     acodec = HB_ACODEC_AC3;
490                     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");
491                     job->chapter_markers = 1;
492                     pixelratio = 1;
493                 }
494
495                 if (!strcmp(preset_name, "Deux Six Quatre"))
496                 {
497                     mux = HB_MUX_MKV;
498                     vcodec = HB_VCODEC_X264;
499                     job->vbitrate = 1600;
500                     acodec = HB_ACODEC_AC3;
501                     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");
502                     job->chapter_markers = 1;
503                     pixelratio = 1;
504                     twoPass = 1;
505                     turbo_opts_enabled = 1;
506                 }
507
508                 if (!strcmp(preset_name, "Film"))
509                 {
510                     mux = HB_MUX_MKV;
511                     vcodec = HB_VCODEC_X264;
512                     job->vbitrate = 1800;
513                     acodec = HB_ACODEC_AC3;
514                     x264opts = strdup("ref=3:mixed-refs:bframes=16:bime:weightb:b-rdo:direct=auto:b-pyramid:me=umh:subme=6:analyse=all:8x8dct:trellis=1:no-fast-pskip");
515                     job->chapter_markers = 1;
516                     pixelratio = 1;
517                     twoPass = 1;
518                     turbo_opts_enabled = 1;
519                 }
520
521                 if (!strcmp(preset_name, "iPhone / iPod Touch"))
522                 {
523                     mux = HB_MUX_MP4;
524                     vcodec = HB_VCODEC_X264;
525                     job->h264_level = 30;
526                     job->vbitrate = 960;
527                     job->abitrate = 128;
528                     job->arate = 48000;
529                     acodec = HB_ACODEC_FAAC;
530                     job->width = 480;
531                     x264opts = strdup("cabac=0:ref=1:analyse=all:me=umh:subme=6:no-fast-pskip=1:trellis=1");
532                     job->chapter_markers = 1;
533                 }
534
535                 if (!strcmp(preset_name, "iPod High-Rez"))
536                 {
537                     mux = HB_MUX_MP4;
538                     vcodec = HB_VCODEC_X264;
539                     job->h264_level = 30;
540                     job->vbitrate = 1500;
541                     job->abitrate = 160;
542                     job->arate = 48000;
543                     acodec = HB_ACODEC_FAAC;
544                     job->width = 640;
545                     x264opts = strdup("keyint=300:keyint-min=30:bframes=0:cabac=0:ref=1:vbv-maxrate=1500:vbv-bufsize=2000:analyse=all:me=umh:subme=6:no-fast-pskip=1");
546                     job->chapter_markers = 1;
547                 }
548
549                 if (!strcmp(preset_name, "iPod Low-Rez"))
550                 {
551                     mux = HB_MUX_MP4;
552                     vcodec = HB_VCODEC_X264;
553                     job->h264_level = 30;
554                     job->vbitrate = 700;
555                     job->abitrate = 160;
556                     job->arate = 48000;
557                     acodec = HB_ACODEC_FAAC;
558                     job->width = 320;
559                     x264opts = strdup("keyint=300:keyint-min=30:bframes=0:cabac=0:ref=1:vbv-maxrate=768:vbv-bufsize=2000:analyse=all:me=umh:subme=6:no-fast-pskip=1");
560                     job->chapter_markers = 1;
561                 }
562
563                 if (!strcmp(preset_name, "Normal"))
564                 {
565                     mux = HB_MUX_MP4;
566                     vcodec = HB_VCODEC_X264;
567                     job->vbitrate = 1500;
568                     job->abitrate = 160;
569                     job->arate = 48000;
570                     acodec = HB_ACODEC_FAAC;
571                     x264opts = strdup("ref=2:bframes=2:subme=5:me=umh");
572                     job->chapter_markers = 1;
573                     pixelratio = 1;
574                     twoPass = 1;
575                     turbo_opts_enabled = 1;
576                 }
577
578                 if (!strcmp(preset_name, "PS3"))
579                 {
580                     mux = HB_MUX_MP4;
581                     vcodec = HB_VCODEC_X264;
582                     job->vbitrate = 2500;
583                     job->abitrate = 160;
584                     job->arate = 48000;
585                     acodec = HB_ACODEC_FAAC;
586                     x264opts = strdup("level=41:subme=5:me=umh");
587                     pixelratio = 1;
588                 }
589
590                 if (!strcmp(preset_name, "PSP"))
591                 {
592                     mux = HB_MUX_MP4;
593                     job->vbitrate = 1024;
594                     job->abitrate = 128;
595                     job->arate = 48000;
596                     acodec = HB_ACODEC_FAAC;
597                     job->width = 368;
598                     job->height = 208;
599                     job->chapter_markers = 1;
600                 }
601
602                 if (!strcmp(preset_name, "QuickTime"))
603                 {
604                     mux = HB_MUX_MP4;
605                     vcodec = HB_VCODEC_X264;
606                     job->vbitrate = 2000;
607                     job->abitrate = 160;
608                     job->arate = 48000;
609                     acodec = HB_ACODEC_FAAC;
610                     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");
611                     job->chapter_markers = 1;
612                     pixelratio = 1;
613                     twoPass = 1;
614                     turbo_opts_enabled = 1;
615                 }
616
617                 if (!strcmp(preset_name, "Television"))
618                 {
619                     mux = HB_MUX_MKV;
620                     vcodec = HB_VCODEC_X264;
621                     job->vbitrate = 1300;
622                     job->abitrate = 160;
623                     job->arate = 48000;
624                     acodec = HB_ACODEC_FAAC;
625                     x264opts = strdup("ref=3:mixed-refs:bframes=16:bime:weightb:direct=auto:b-pyramid:me=umh:subme=6:analyse=all:8x8dct:trellis=1:nr=150:no-fast-pskip");
626                     job->chapter_markers = 1;
627                     job->deinterlace = 1;
628                     twoPass = 1;
629                     turbo_opts_enabled = 1;
630                 }
631             }
632             
633                         if ( chapter_markers )
634                         {
635                                 job->chapter_markers = chapter_markers;
636
637                 if( marker_file != NULL )
638                 {
639                     hb_csv_file_t * file = hb_open_csv_file( marker_file );
640                     hb_csv_cell_t * cell;
641                     int row = 0;
642                     int chapter = 0;
643                     
644                     fprintf( stderr, "Reading chapter markers from file %s\n", marker_file );
645                     
646                     if( file == NULL )
647                     {
648                          fprintf( stderr, "Cannot open chapter marker file, using defaults\n" );
649                     }
650                     else
651                     {
652                         /* Parse the cells */
653                         while( NULL != ( cell = hb_read_next_cell( file ) ) )
654                         {                            
655                             /* We have a chapter number */
656                             if( cell->cell_col == 0 )
657                             {
658                                 row = cell->cell_row;
659                                 chapter = atoi( cell->cell_text );
660                             }
661                              
662                             /* We have a chapter name */
663                             if( cell->cell_col == 1 && row == cell->cell_row )
664                             {
665                                 /* If we have a valid chapter, copy the string an terminate it */
666                                 if( chapter >= job->chapter_start && chapter <= job->chapter_end )
667                                 {
668                                     hb_chapter_t * chapter_s;
669                                     
670                                     chapter_s = hb_list_item( job->title->list_chapter, chapter - 1);
671                                     strncpy(chapter_s->title, cell->cell_text, 1023);
672                                     chapter_s->title[1023] = '\0';
673                                 }
674                             }                               
675                         
676                                                            
677                             hb_dispose_cell( cell );
678                         }
679                         
680                         hb_close_csv_file( file );
681                     }
682                 }
683                         }
684
685             if( crop[0] >= 0 && crop[1] >= 0 &&
686                 crop[2] >= 0 && crop[3] >= 0 )
687             {
688                 memcpy( job->crop, crop, 4 * sizeof( int ) );
689             }
690
691             job->deinterlace = deinterlace;
692             job->grayscale   = grayscale;
693             if (loosePixelratio)
694             {
695                 job->pixel_ratio = 2;
696                 if (modulus)
697                 {
698                     job->modulus = modulus;
699                 }
700             }
701             else
702             {
703                 job->pixel_ratio = pixelratio;
704             }
705             /* Add selected filters */
706             job->filters = hb_list_init();
707             if( detelecine )
708             {
709                 hb_filter_detelecine.settings = detelecine_opt;
710                 hb_list_add( job->filters, &hb_filter_detelecine );
711             }
712             if( deinterlace )
713             {
714                 hb_filter_deinterlace.settings = deinterlace_opt;
715                 hb_list_add( job->filters, &hb_filter_deinterlace );
716             }
717             if( deblock )
718             {
719                 hb_filter_deblock.settings = deblock_opt;
720                 hb_list_add( job->filters, &hb_filter_deblock );
721             }
722             if( denoise )
723             {
724                 hb_filter_denoise.settings = denoise_opt;
725                 hb_list_add( job->filters, &hb_filter_denoise );
726             }
727             
728             if( width && height )
729             {
730                 job->width  = width;
731                 job->height = height;
732             }
733             else if( width )
734             {
735                 job->width = width;
736                 hb_fix_aspect( job, HB_KEEP_WIDTH );
737             }
738             else if( height && !loosePixelratio)
739             {
740                 job->height = height;
741                 hb_fix_aspect( job, HB_KEEP_HEIGHT );
742             }
743             else if( !width && !height && !pixelratio && !loosePixelratio )
744             {
745                 hb_fix_aspect( job, HB_KEEP_WIDTH );
746             }
747             else if (!width && loosePixelratio)
748             {
749                 /* Default to full width when one isn't specified for loose anamorphic */
750                 job->width = title->width - job->crop[2] - job->crop[3];
751                 /* The height will be thrown away in hb.c but calculate it anyway */
752                 hb_fix_aspect( job, HB_KEEP_WIDTH );
753             }
754             
755             if( vquality >= 0.0 && vquality <= 1.0 )
756             {
757                 job->vquality = vquality;
758                 job->vbitrate = 0;
759             }
760             else if( vbitrate )
761             {
762                 job->vquality = -1.0;
763                 job->vbitrate = vbitrate;
764             }
765             if( vcodec )
766             {
767                 job->vcodec = vcodec;
768             }
769             if( h264_13 ) 
770             { 
771                 job->h264_level = 13; 
772             }
773                 if( h264_30 )
774                 {
775                     job->h264_level = 30;
776             }
777             if( vrate )
778             {
779                 job->vrate = 27000000;
780                 job->vrate_base = vrate;
781             }
782             if( arate )
783             {
784                 job->arate = arate;
785             }
786
787             if( audios )
788             {
789                 if( strcasecmp( audios, "none" ) )
790                 {
791                     int    audio_count = 0;
792                     char * tmp         = audios;
793                     while( *tmp )
794                     {
795                         if( *tmp < '0' || *tmp > '9' )
796                         {
797                             /* Skip non numeric char */
798                             tmp++;
799                             continue;
800                         }
801                                                 job->audio_mixdowns[audio_count] = audio_mixdown;
802                         job->audios[audio_count++] =
803                             strtol( tmp, &tmp, 0 ) - 1;
804                     }
805                     job->audios[audio_count] = -1;
806                 }
807                 else
808                 {
809                     job->audios[0] = -1;
810                 }
811             }
812                         else
813                         {
814                             /* default to the first audio track if none has been specified */
815                             job->audios[0] = 0;
816                             job->audio_mixdowns[0] = audio_mixdown;
817                         }
818             if( abitrate )
819             {
820                 job->abitrate = abitrate;
821             }
822             if( acodec )
823             {
824                 job->acodec = acodec;
825             }
826
827             if( size )
828             {
829                 job->vbitrate = hb_calc_bitrate( job, size );
830                 fprintf( stderr, "Calculated bitrate: %d kbps\n",
831                          job->vbitrate );
832             }
833
834             if( sub )
835             {
836                 job->subtitle = sub - 1;
837             }
838
839             if( native_language )
840             {
841                 job->native_language = strdup( native_language );
842             }
843
844             if( job->mux )
845             {
846                 job->mux = mux;
847             }
848             
849             if ( largeFileSize )
850             {
851                 job->largeFileSize = 1;
852             }
853             if ( mp4_optimize )
854             {
855                 job->mp4_optimize = 1;
856             }
857             if ( ipod_atom )
858             {
859                 job->ipod_atom = 1;
860             }
861             
862             job->file = strdup( output );
863
864             if( crf )
865             {
866                 job->crf = 1;
867             }
868
869             if( x264opts != NULL && *x264opts != '\0' )
870             {
871                 job->x264opts = x264opts;
872             }
873             else /*avoids a bus error crash when options aren't specified*/
874             {
875                 job->x264opts =  NULL;
876             }
877             if (maxWidth)
878                 job->maxWidth = maxWidth;
879             if (maxHeight)
880                 job->maxHeight = maxHeight;
881             
882             if (vfr)
883                 job->vfr = 1;
884         
885             if( subtitle_force )
886             {
887                 job->subtitle_force = subtitle_force;
888             }
889
890             if( subtitle_scan )
891             {
892                 char *x264opts_tmp;
893
894                 /*
895                  * When subtitle scan is enabled do a fast pre-scan job
896                  * which will determine which subtitles to enable, if any.
897                  */
898                 job->pass = -1;
899                 
900                 x264opts_tmp = job->x264opts;
901
902                 job->x264opts = NULL;
903
904                 job->indepth_scan = subtitle_scan;  
905                 fprintf( stderr, "Subtitle Scan Enabled - enabling "
906                          "subtitles if found for foreign language segments\n");
907                 job->select_subtitle = malloc(sizeof(hb_subtitle_t*));
908                 *(job->select_subtitle) = NULL;
909                 
910                 /*
911                  * Add the pre-scan job
912                  */
913                 hb_add( h, job );
914
915                 job->x264opts = x264opts_tmp;
916             }
917
918             if( twoPass )
919             {
920                 /*
921                  * If subtitle_scan is enabled then only turn it on
922                  * for the first pass and then off again for the
923                  * second. 
924                  */
925                 hb_subtitle_t **subtitle_tmp = job->select_subtitle;
926
927                 job->select_subtitle = NULL;
928
929                 job->pass = 1;
930
931                 job->indepth_scan = 0;
932                 
933                 if (x264opts)
934                 {
935                     x264opts2 = strdup(x264opts);
936                 }
937
938                 /*
939                  * If turbo options have been selected then append them
940                  * to the x264opts now (size includes one ':' and the '\0')
941                  */
942                 if( turbo_opts_enabled ) 
943                 {
944                     int size = (x264opts ? strlen(x264opts) : 0) + strlen(turbo_opts) + 2;
945                     char *tmp_x264opts;
946                         
947                     tmp_x264opts = malloc(size * sizeof(char));
948                     if( x264opts ) 
949                     {
950                         snprintf( tmp_x264opts, size, "%s:%s", 
951                                   x264opts, turbo_opts );  
952                         free( x264opts );
953                     } else {
954                         /*
955                          * No x264opts to modify, but apply the turbo options
956                          * anyway as they may be modifying defaults
957                          */
958                         snprintf( tmp_x264opts, size, "%s", 
959                                   turbo_opts );
960                     }
961                     x264opts = tmp_x264opts;
962
963                     fprintf( stderr, "Modified x264 options for pass 1 to append turbo options: %s\n",
964                              x264opts );
965
966                     job->x264opts = x264opts;
967                 }     
968                 hb_add( h, job );
969
970                 job->select_subtitle = subtitle_tmp;
971
972                 job->pass = 2;
973                 /*
974                  * On the second pass we turn off subtitle scan so that we
975                  * can actually encode using any subtitles that were auto
976                  * selected in the first pass (using the whacky select-subtitle
977                  * attribute of the job).
978                  */
979                 job->indepth_scan = 0;
980
981                 job->x264opts = x264opts2;
982                 
983                 hb_add( h, job );
984             }
985             else
986             {
987                 /*
988                  * Turn on subtitle scan if requested, note that this option
989                  * precludes encoding of any actual subtitles.
990                  */ 
991
992                 job->indepth_scan = 0;
993                 job->pass = 0;
994                 hb_add( h, job );
995             }
996             hb_start( h );
997             break;
998         }
999
1000 #define p s.param.working
1001         case HB_STATE_WORKING:
1002             fprintf( stdout, "\rEncoding: task %d of %d, %.2f %%",
1003                      p.job_cur, p.job_count, 100.0 * p.progress );
1004             if( p.seconds > -1 )
1005             {
1006                 fprintf( stdout, " (%.2f fps, avg %.2f fps, ETA "
1007                          "%02dh%02dm%02ds)", p.rate_cur, p.rate_avg,
1008                          p.hours, p.minutes, p.seconds );
1009             }
1010             fflush(stdout);
1011             break;
1012 #undef p
1013
1014 #define p s.param.muxing
1015         case HB_STATE_MUXING:
1016         {
1017             fprintf( stdout, "\rMuxing: %.2f %%", 100.0 * p.progress );
1018             fflush(stdout);
1019             break;
1020         }
1021 #undef p
1022
1023 #define p s.param.workdone
1024         case HB_STATE_WORKDONE:
1025             /* Print error if any, then exit */
1026             switch( p.error )
1027             {
1028                 case HB_ERROR_NONE:
1029                     fprintf( stderr, "\nRip done!\n" );
1030                     break;
1031                 case HB_ERROR_CANCELED:
1032                     fprintf( stderr, "\nRip canceled.\n" );
1033                     break;
1034                 default:
1035                     fprintf( stderr, "\nRip failed (error %x).\n",
1036                              p.error );
1037             }
1038             die = 1;
1039             break;
1040 #undef p
1041     }
1042     return 0;
1043 }
1044
1045 /****************************************************************************
1046  * SigHandler:
1047  ****************************************************************************/
1048 static volatile int64_t i_die_date = 0;
1049 void SigHandler( int i_signal )
1050 {
1051     if( die == 0 )
1052     {
1053         die = 1;
1054         i_die_date = hb_get_date();
1055         fprintf( stderr, "Signal %d received, terminating - do it "
1056                  "again in case it gets stuck\n", i_signal );
1057     }
1058     else if( i_die_date + 500 < hb_get_date() )
1059     {
1060         fprintf( stderr, "Dying badly, files might remain in your /tmp\n" );
1061         exit( 1 );
1062     }
1063 }
1064
1065 /****************************************************************************
1066  * ShowHelp:
1067  ****************************************************************************/
1068 static void ShowHelp()
1069 {
1070     int i;
1071     
1072     fprintf( stderr,
1073     "Syntax: HandBrakeCLI [options] -i <device> -o <file>\n"
1074     "\n"
1075         "### General Handbrake Options------------------------------------------------\n\n"
1076     "    -h, --help              Print help\n"
1077     "    -u, --update            Check for updates and exit\n"
1078     "    -v, --verbose           Be verbose\n"
1079     "    -C, --cpu               Set CPU count (default: autodetected)\n"
1080     "    -Z. --preset <string>   Use a built-in preset. Capitalization matters, and\n"
1081     "                            if the preset name has spaces, surround it with\n"
1082     "                            double quotation marks\n"
1083     "    -z, --preset-list       See a list of available built-in presets\n"
1084     "\n"
1085         
1086         "### Source Options-----------------------------------------------------------\n\n"
1087         "    -i, --input <string>    Set input device\n"
1088         "    -t, --title <number>    Select a title to encode (0 to scan only,\n"
1089     "                            default: 1)\n"
1090     "    -L, --longest           Select the longest title\n"
1091     "    -c, --chapters <string> Select chapters (e.g. \"1-3\" for chapters\n"
1092     "                            1 to 3, or \"3\" for chapter 3 only,\n"
1093     "                            default: all chapters)\n"
1094         "\n"
1095         
1096         "### Destination Options------------------------------------------------------\n\n"
1097     "    -o, --output <string>   Set output file name\n"
1098         "    -f, --format <string>   Set output format (avi/mp4/ogm/mkv, default:\n"
1099     "                            autodetected from file name)\n"
1100     "    -4, --large-file        Use 64-bit mp4 files that can hold more than\n"
1101     "                            4 GB. Note: Breaks iPod, @TV, PS3 compatibility.\n"""
1102     "    -O, --optimize          Optimize mp4 files for HTTP streaming\n"
1103     "    -I, --ipod-atom         Mark mp4 files so iPods will accept them\n"
1104     "\n"
1105         
1106         "### Picture Settings---------------------------------------------------------\n\n"
1107     "    -w, --width <number>    Set picture width\n"
1108     "    -l, --height <number>   Set picture height\n"
1109     "        --crop <T:B:L:R>    Set cropping values (default: autocrop)\n"
1110         "    -Y, --maxHeight <#>     Set maximum height\n"
1111         "    -X, --maxWidth <#>      Set maximum width\n"
1112         "    -s, --subtitle <number> Select subtitle (default: none)\n"
1113     "    -U, --subtitle-scan     Scan for subtitles in an extra 1st pass, and choose\n"
1114     "                            the one that's only used 10 percent of the time\n"
1115     "                            or less. This should locate subtitles for short\n"
1116     "                            foreign language segments. Best used in conjunction\n"
1117     "                            with --subtitle-forced.\n"
1118     "    -F, --subtitle-forced   Only display subtitles from the selected stream if\n"
1119     "                            the subtitle has the forced flag set. May be used in\n"
1120     "                            conjunction with --subtitle-scan to auto-select\n"
1121     "                            a stream if it contains forced subtitles.\n"
1122     "    -N, --native-language   Select subtitles with this language if it does not\n"
1123     "          <string>          match the Audio language. Provide the language's\n"
1124     "                            iso639-2 code (fre, eng, spa, dut, et cetera)\n"
1125         "    -m, --markers           Add chapter markers (mp4 output format only)\n"
1126         "\n"
1127         
1128         "### Video Options------------------------------------------------------------\n\n"
1129         "    -e, --encoder <string>  Set video library encoder (ffmpeg,xvid,\n"
1130     "                            x264,x264b13,x264b30 default: ffmpeg)\n"
1131         "    -q, --quality <float>   Set video quality (0.0..1.0)\n"
1132         "    -Q, --crf               Use with -q for CRF instead of CQP\n"
1133     "    -S, --size <MB>         Set target size\n"
1134         "    -b, --vb <kb/s>         Set video bitrate (default: 1000)\n"
1135         "    -r, --rate              Set video framerate (" );
1136     for( i = 0; i < hb_video_rates_count; i++ )
1137     {
1138         fprintf( stderr, hb_video_rates[i].string );
1139         if( i != hb_video_rates_count - 1 )
1140             fprintf( stderr, "/" );
1141     }
1142     fprintf( stderr, ")\n"
1143         "\n"
1144         "    -2, --two-pass          Use two-pass mode\n"
1145      "    -d, --deinterlace       Deinterlace video with yadif/mcdeint filter\n"
1146      "          <YM:FD:MM:QP>     (default 0:-1:-1:1)\n"
1147      "           or\n"
1148      "          <fast/slow/slower/slowest>\n"            
1149      "    -7, --deblock           Deblock video with pp7 filter\n"
1150      "          <QP:M>            (default 0:2)\n"
1151      "    -8, --denoise           Denoise video with hqdn3d filter\n"
1152      "          <SL:SC:TL:TC>     (default 4:3:6:4.5)\n"
1153      "           or\n"
1154      "          <weak/medium/strong>\n"
1155      "    -9, --detelecine        Detelecine video with pullup filter\n"
1156      "          <L:R:T:B:SB:MP>   (default 1:1:4:4:0:0)\n"
1157     "    -g, --grayscale         Grayscale encoding\n"
1158     "    -p, --pixelratio        Store pixel aspect ratio in video stream\n"
1159     "    -P, --loosePixelratio   Store pixel aspect ratio with specified width\n"
1160     "           <modulus>        Takes as optional argument what number you want\n"
1161     "                            the dimensions to divide cleanly by (default 16)\n"
1162     
1163         
1164         "\n"
1165         
1166         
1167         "### Audio Options-----------------------------------------------------------\n\n"
1168         "    -E, --aencoder <string> Set audio encoder (faac/lame/vorbis/ac3, ac3\n"
1169     "                            meaning passthrough, default: guessed)\n"
1170         "    -B, --ab <kb/s>         Set audio bitrate (default: 128)\n"
1171         "    -a, --audio <string>    Select audio channel(s), separated by commas\n"
1172         "                            (\"none\" for no audio, \"1,2,3\" for multiple\n"
1173         "                             tracks, default: first one, max: eight)\n"
1174     "    -6, --mixdown <string>  Format for surround sound downmixing\n"
1175     "                            (mono/stereo/dpl1/dpl2/6ch, default: dpl2)\n"
1176     "    -R, --arate             Set audio samplerate (" );
1177     for( i = 0; i < hb_audio_rates_count; i++ )
1178     {
1179         fprintf( stderr, hb_audio_rates[i].string );
1180         if( i != hb_audio_rates_count - 1 )
1181             fprintf( stderr, "/" );
1182     }
1183     fprintf( stderr, " kHz)\n"
1184    
1185     
1186         
1187         "\n"
1188         
1189         
1190     "### Advanced Options---------------------------------------------------------\n\n"
1191     "    -x, --x264opts <string> Specify advanced x264 options in the\n"
1192     "                            same style as mencoder:\n"
1193     "                            option1=value1:option2=value2\n"
1194     "    -T, --turbo             When using 2-pass use the turbo options\n"
1195     "                            on the first pass to improve speed\n"
1196     "                            (only works with x264, affects PSNR by about 0.05dB,\n"
1197     "                            and increases first pass speed two to four times)\n"
1198     "    -V, --vfr               Perform variable framerate detelecine on NTSC video\n"
1199     );
1200 }
1201
1202 /****************************************************************************
1203  * ShowPresets:
1204  ****************************************************************************/
1205 static void ShowPresets()
1206 {
1207     printf("\n+ Animation:  -e x264 -b 1000 -B 160 -R 48 -E faac -f mkv -m -d -p -2 -T -x ref=5:mixed-refs:bframes=16: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");
1208
1209     printf("\n+ AppleTV:  -e x264 -b 2500 -B 160 -R 48 -E faac -f mp4 -m -p -x bframes=3:ref=1:subme=5:me=umh:no-fast-pskip=1:trellis=2:cabac=0\n");
1210
1211     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=umh:subme=7:me-range=64:analyse=all:8x8dct:trellis=2:no-fast-pskip:no-dct-decimate:filter=-2,-1\n");
1212
1213     printf("\n+ Blind:  -b 512 -B 128 -R 48 -E faac -f mp4 -w 512 -m\n");
1214
1215     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");
1216
1217     printf("\n+ Classic:  -b 1000 -B 160 -R 48 -E faac -f mp4\n");
1218
1219     printf("\n+ Constant Quality Rate:  -e x264 -q 0.64709997177124023 -Q  -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");
1220
1221     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");
1222
1223     printf("\n+ Film:  -e x264 -b 1800 -E ac3 -f mkv -m -p -2 -T -x ref=3:mixed-refs:bframes=16:bime:weightb:b-rdo:direct=auto:b-pyramid:me=umh:subme=6:analyse=all:8x8dct:trellis=1:no-fast-pskip\n");
1224
1225     printf("\n+ iPhone / iPod Touch:  -e x264b30 -b 960 -B 128 -R 48 -E faac -f mp4 -w 480 -m -x cabac=0:ref=1:analyse=all:me=umh:subme=6:no-fast-pskip=1:trellis=1\n");
1226
1227     printf("\n+ iPod High-Rez:  -e x264b30 -b 1500 -B 160 -R 48 -E faac -f mp4 -w 640 -m -x keyint=300:keyint-min=30:bframes=0:cabac=0:ref=1:vbv-maxrate=1500:vbv-bufsize=2000:analyse=all:me=umh:subme=6:no-fast-pskip=1\n");
1228
1229     printf("\n+ iPod Low-Rez:  -e x264b30 -b 700 -B 160 -R 48 -E faac -f mp4 -w 320 -m -x keyint=300:keyint-min=30:bframes=0:cabac=0:ref=1:vbv-maxrate=768:vbv-bufsize=2000:analyse=all:me=umh:subme=6:no-fast-pskip=1\n");
1230
1231     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");
1232
1233     printf("\n+ PS3:  -e x264 -b 2500 -B 160 -R 48 -E faac -f mp4 -p -x level=41:subme=5:me=umh\n");
1234
1235     printf("\n+ PSP:  -b 1024 -B 128 -R 48 -E faac -f mp4 -w 368 -l 208 -m\n");
1236
1237     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");
1238
1239     printf("\n+ Television:  -e x264 -b 1300 -B 160 -R 48 -E faac -f mkv -m -d -2 -T -x ref=3:mixed-refs:bframes=16:bime:weightb:direct=auto:b-pyramid:me=umh:subme=6:analyse=all:8x8dct:trellis=1:nr=150:no-fast-pskip\n");
1240     
1241 }
1242
1243 /****************************************************************************
1244  * ParseOptions:
1245  ****************************************************************************/
1246 static int ParseOptions( int argc, char ** argv )
1247 {
1248     for( ;; )
1249     {
1250         static struct option long_options[] =
1251           {
1252             { "help",        no_argument,       NULL,    'h' },
1253             { "update",      no_argument,       NULL,    'u' },
1254             { "verbose",     no_argument,       NULL,    'v' },
1255             { "cpu",         required_argument, NULL,    'C' },
1256
1257             { "format",      required_argument, NULL,    'f' },
1258             { "input",       required_argument, NULL,    'i' },
1259             { "output",      required_argument, NULL,    'o' },
1260             { "large-file",  no_argument,       NULL,    '4' },
1261             { "optimize",    no_argument,       NULL,    'O' },
1262             { "ipod-atom",   no_argument,       NULL,    'I' },
1263             
1264             { "title",       required_argument, NULL,    't' },
1265             { "longest",     no_argument,       NULL,    'L' },
1266             { "chapters",    required_argument, NULL,    'c' },
1267             { "markers",     optional_argument, NULL,    'm' },
1268             { "audio",       required_argument, NULL,    'a' },
1269             { "mixdown",     required_argument, NULL,    '6' },
1270             { "subtitle",    required_argument, NULL,    's' },
1271             { "subtitle-scan", no_argument,     NULL,    'U' },
1272             { "subtitle-forced", no_argument,   NULL,    'F' },
1273             { "native-language", required_argument, NULL,'N' },
1274
1275             { "encoder",     required_argument, NULL,    'e' },
1276             { "aencoder",    required_argument, NULL,    'E' },
1277             { "two-pass",    no_argument,       NULL,    '2' },
1278             { "deinterlace", optional_argument, NULL,    'd' },
1279             { "deblock",     optional_argument, NULL,    '7' },
1280             { "denoise",     optional_argument, NULL,    '8' },
1281             { "detelecine",  optional_argument, NULL,    '9' },
1282             { "grayscale",   no_argument,       NULL,    'g' },
1283             { "pixelratio",  no_argument,       NULL,    'p' },
1284             { "loosePixelratio", optional_argument,   NULL,    'P' },
1285             { "width",       required_argument, NULL,    'w' },
1286             { "height",      required_argument, NULL,    'l' },
1287             { "crop",        required_argument, NULL,    'n' },
1288
1289             { "vb",          required_argument, NULL,    'b' },
1290             { "quality",     required_argument, NULL,    'q' },
1291             { "size",        required_argument, NULL,    'S' },
1292             { "ab",          required_argument, NULL,    'B' },
1293             { "rate",        required_argument, NULL,    'r' },
1294             { "arate",       required_argument, NULL,    'R' },
1295             { "crf",         no_argument,       NULL,    'Q' },
1296             { "x264opts",    required_argument, NULL,    'x' },
1297             { "turbo",       no_argument,       NULL,    'T' },
1298             { "maxHeight",   required_argument, NULL,    'Y' },
1299             { "maxWidth",    required_argument, NULL,    'X' },
1300             { "preset",      required_argument, NULL,    'Z' },
1301             { "preset-list", no_argument,       NULL,    'z' },
1302             { "vfr",         no_argument,       NULL,    'V' },
1303                         
1304             { 0, 0, 0, 0 }
1305           };
1306
1307         int option_index = 0;
1308         int c;
1309
1310         c = getopt_long( argc, argv,
1311                          "hvuC:f:4i:Io:t:Lc:ma:6:s:UFN:e:E:2d789gpOP::w:l:n:b:q:S:B:r:R:Qx:TY:X:VZ:z",
1312                          long_options, &option_index );
1313         if( c < 0 )
1314         {
1315             break;
1316         }
1317
1318         switch( c )
1319         {
1320             case 'h':
1321                 ShowHelp();
1322                 exit( 0 );
1323             case 'u':
1324                 update = 1;
1325                 break;
1326             case 'v':
1327                 debug = HB_DEBUG_ALL;
1328                 break;
1329             case 'C':
1330                 cpu = atoi( optarg );
1331                 break;
1332             
1333             case 'Z':
1334                 preset = 1;
1335                 preset_name = strdup(optarg);
1336                 break;
1337             case 'z':
1338                 ShowPresets();
1339                 exit ( 0 );
1340                 
1341             case 'f':
1342                 format = strdup( optarg );
1343                 break;
1344             case 'i':
1345                 input = strdup( optarg );
1346                 break;
1347             case 'o':
1348                 output = strdup( optarg );
1349                 break;
1350             case '4':
1351                 largeFileSize = 1;
1352                 break;
1353             case 'O':
1354                 mp4_optimize = 1;
1355                 break;
1356             case 'I':
1357                 ipod_atom = 1;
1358                 break;
1359             
1360             case 't':
1361                 titleindex = atoi( optarg );
1362                 break;
1363             case 'L':
1364                 longest_title = 1;
1365                 break;
1366             case 'c':
1367             {
1368                 int start, end;
1369                 if( sscanf( optarg, "%d-%d", &start, &end ) == 2 )
1370                 {
1371                     chapter_start = start;
1372                     chapter_end   = end;
1373                 }
1374                 else if( sscanf( optarg, "%d", &start ) == 1 )
1375                 {
1376                     chapter_start = start;
1377                     chapter_end   = chapter_start;
1378                 }
1379                 else
1380                 {
1381                     fprintf( stderr, "chapters: invalid syntax (%s)\n",
1382                              optarg );
1383                     return -1;
1384                 }
1385                 break;
1386             }
1387             case 'm':
1388                 if( optarg != NULL )
1389                 {
1390                     marker_file = strdup( optarg );
1391                 }
1392                 chapter_markers = 1;
1393                 break;
1394             case 'a':
1395                 audios = strdup( optarg );
1396                 break;
1397             case '6':
1398                 if( !strcasecmp( optarg, "mono" ) )
1399                 {
1400                     audio_mixdown = HB_AMIXDOWN_MONO;
1401                 }
1402                 else if( !strcasecmp( optarg, "stereo" ) )
1403                 {
1404                     audio_mixdown = HB_AMIXDOWN_STEREO;
1405                 }
1406                 else if( !strcasecmp( optarg, "dpl1" ) )
1407                 {
1408                     audio_mixdown = HB_AMIXDOWN_DOLBY;
1409                 }
1410                 else if( !strcasecmp( optarg, "dpl2" ) )
1411                 {
1412                     audio_mixdown = HB_AMIXDOWN_DOLBYPLII;
1413                 }
1414                 else if( !strcasecmp( optarg, "6ch" ) )
1415                 {
1416                     audio_mixdown = HB_AMIXDOWN_6CH;
1417                 }
1418                 break;
1419             case 's':
1420                 sub = atoi( optarg );
1421                 break;
1422             case 'U':
1423                 subtitle_scan = 1;
1424                 break;
1425             case 'F':
1426                 subtitle_force = 1;
1427                 break;
1428             case 'N':
1429                 native_language = strdup( optarg );
1430                 break;
1431             case '2':
1432                 twoPass = 1;
1433                 break;
1434             case 'd':
1435                 if( optarg != NULL )
1436                 {
1437                     if (!( strcmp( optarg, "fast" ) ))
1438                     {
1439                         deinterlace_opt = "-1";
1440                     }
1441                     else if (!( strcmp( optarg, "slow" ) ))
1442                     {
1443                         deinterlace_opt = "0";
1444                     }
1445                     else if (!( strcmp( optarg, "slower" ) ))
1446                     {
1447                         deinterlace_opt = "2:-1:1";
1448                     }
1449                     else if (!( strcmp( optarg, "slowest" ) ))
1450                     {
1451                         deinterlace_opt = "1:-1:1";
1452                     }
1453                     else
1454                     {
1455                         deinterlace_opt = strdup( optarg );
1456                     }
1457                 }
1458                 deinterlace = 1;
1459                 break;
1460             case '7':
1461                 if( optarg != NULL )
1462                 {
1463                     deblock_opt = strdup( optarg );
1464                 }
1465                 deblock = 1;
1466                 break;
1467             case '8':
1468                 if( optarg != NULL )
1469                 {
1470                     if (!( strcmp( optarg, "weak" ) ))
1471                     {
1472                         denoise_opt = "2:1:2:3";
1473                     }
1474                     else if (!( strcmp( optarg, "medium" ) ))
1475                     {
1476                         denoise_opt = "3:2:2:3";
1477                     }
1478                     else if (!( strcmp( optarg, "strong" ) ))
1479                     {
1480                         denoise_opt = "7:7:5:5";
1481                     }
1482                     else
1483                     {
1484                         denoise_opt = strdup( optarg );
1485                     }
1486                 }
1487                 denoise = 1;
1488                 break;                
1489             case '9':
1490                 if( optarg != NULL )
1491                 {
1492                     detelecine_opt = strdup( optarg );
1493                 }
1494                 detelecine = 1;
1495                 break;                
1496             case 'g':
1497                 grayscale = 1;
1498                 break;
1499             case 'p':
1500                 pixelratio = 1;
1501                 break;
1502             case 'P':
1503                 loosePixelratio = 1;
1504                 if( optarg != NULL )
1505                 {
1506                     modulus = atoi( optarg );
1507                 }
1508                 break;
1509             case 'e':
1510                 if( !strcasecmp( optarg, "ffmpeg" ) )
1511                 {
1512                     vcodec = HB_VCODEC_FFMPEG;
1513                 }
1514                 else if( !strcasecmp( optarg, "xvid" ) )
1515                 {
1516                     vcodec = HB_VCODEC_XVID;
1517                 }
1518                 else if( !strcasecmp( optarg, "x264" ) )
1519                 {
1520                     vcodec = HB_VCODEC_X264;
1521                 }
1522                 else if( !strcasecmp( optarg, "x264b13" ) )
1523                 {
1524                     vcodec = HB_VCODEC_X264;
1525                     h264_13 = 1;
1526                 }
1527                 else if( !strcasecmp( optarg, "x264b30" ) )
1528                 {
1529                     vcodec = HB_VCODEC_X264;
1530                     h264_30 = 1;
1531                 }
1532                 else
1533                 {
1534                     fprintf( stderr, "invalid codec (%s)\n", optarg );
1535                     return -1;
1536                 }
1537                 break;
1538             case 'E':
1539                 if( !strcasecmp( optarg, "ac3" ) )
1540                 {
1541                     acodec = HB_ACODEC_AC3;
1542                 }
1543                 else if( !strcasecmp( optarg, "lame" ) )
1544                 {
1545                     acodec = HB_ACODEC_LAME;
1546                 }
1547                 else if( !strcasecmp( optarg, "faac" ) )
1548                 {
1549                     acodec = HB_ACODEC_FAAC;
1550                 }
1551                 else if( !strcasecmp( optarg, "vorbis") )
1552                 {
1553                     acodec = HB_ACODEC_VORBIS;
1554                 }
1555                 break;
1556             case 'w':
1557                 width = atoi( optarg );
1558                 break;
1559             case 'l':
1560                 height = atoi( optarg );
1561                 break;
1562             case 'n':
1563             {
1564                 int    i;
1565                 char * tmp = optarg;
1566                 for( i = 0; i < 4; i++ )
1567                 {
1568                     if( !*tmp )
1569                         break;
1570                     crop[i] = strtol( tmp, &tmp, 0 );
1571                     tmp++;
1572                 }
1573                 break;
1574             }
1575             case 'r':
1576             {
1577                 int i;
1578                 vrate = 0;
1579                 for( i = 0; i < hb_video_rates_count; i++ )
1580                 {
1581                     if( !strcmp( optarg, hb_video_rates[i].string ) )
1582                     {
1583                         vrate = hb_video_rates[i].rate;
1584                         break;
1585                     }
1586                 }
1587                 if( !vrate )
1588                 {
1589                     fprintf( stderr, "invalid framerate %s\n", optarg );
1590                 }
1591                 break;
1592             }
1593             case 'R':
1594             {
1595                 int i;
1596                 arate = 0;
1597                 for( i = 0; i < hb_audio_rates_count; i++ )
1598                 {
1599                     if( !strcmp( optarg, hb_audio_rates[i].string ) )
1600                     {
1601                         arate = hb_audio_rates[i].rate;
1602                         break;
1603                     }
1604                 }
1605                 if( !arate )
1606                 {
1607                     fprintf( stderr, "invalid framerate %s\n", optarg );
1608                 }
1609                 break;
1610             }
1611             case 'b':
1612                 vbitrate = atoi( optarg );
1613                 break;
1614             case 'q':
1615                 vquality = atof( optarg );
1616                 break;
1617             case 'S':
1618                 size = atoi( optarg );
1619                 break;
1620             case 'B':
1621                 abitrate = atoi( optarg );
1622                 break;
1623             case 'Q':
1624                 crf = 1;
1625                 break;
1626             case 'x':
1627                 x264opts = strdup( optarg );
1628                 break;
1629             case 'T':
1630                 turbo_opts_enabled = 1;
1631                 break;
1632             case 'Y':
1633                 maxHeight = atoi( optarg );
1634                 break;
1635             case 'X':
1636                 maxWidth = atoi (optarg );
1637                 break;
1638             case 'V':
1639                 vfr = 1;
1640                 break;
1641                                 
1642             default:
1643                 fprintf( stderr, "unknown option (%s)\n", argv[optind] );
1644                 return -1;
1645         }
1646     }
1647
1648     return 0;
1649 }
1650
1651 static int CheckOptions( int argc, char ** argv )
1652 {
1653     if( update )
1654     {
1655         return 0;
1656     }
1657
1658     if( input == NULL || *input == '\0' )
1659     {
1660         fprintf( stderr, "Missing input device. Run %s --help for "
1661                  "syntax.\n", argv[0] );
1662         return 1;
1663     }
1664
1665     /* Parse format */
1666     if( titleindex > 0 )
1667     {
1668         if( output == NULL || *output == '\0' )
1669         {
1670             fprintf( stderr, "Missing output file name. Run %s --help "
1671                      "for syntax.\n", argv[0] );
1672             return 1;
1673         }
1674
1675         if( !format )
1676         {
1677             char * p = strrchr( output, '.' );
1678
1679             /* autodetect */
1680             if( p && !strcasecmp( p, ".avi" ) )
1681             {
1682                 mux = HB_MUX_AVI;
1683             }
1684             else if( p && ( !strcasecmp( p, ".mp4" )  ||
1685                             !strcasecmp( p, ".m4v" ) ) )
1686             {
1687                 if ( h264_30 == 1 )
1688                     mux = HB_MUX_IPOD;
1689                 else
1690                     mux = HB_MUX_MP4;
1691             }
1692             else if( p && ( !strcasecmp( p, ".ogm" ) ||
1693                             !strcasecmp( p, ".ogg" ) ) )
1694             {
1695                 mux = HB_MUX_OGM;
1696             }
1697             else if( p && !strcasecmp(p, ".mkv" ) )
1698             {
1699                 mux = HB_MUX_MKV;
1700             }
1701             else
1702             {
1703                 fprintf( stderr, "Output format couldn't be guessed "
1704                          "from file name, using default.\n" );
1705                 return 0;
1706             }
1707         }
1708         else if( !strcasecmp( format, "avi" ) )
1709         {
1710             mux = HB_MUX_AVI;
1711         }
1712         else if( !strcasecmp( format, "mp4" ) )
1713         {
1714             if ( h264_30 == 1)
1715                 mux = HB_MUX_IPOD;
1716             else
1717                 mux = HB_MUX_MP4;
1718         }
1719         else if( !strcasecmp( format, "ogm" ) ||
1720                  !strcasecmp( format, "ogg" ) )
1721         {
1722             mux = HB_MUX_OGM;
1723         }
1724         else if( !strcasecmp( format, "mkv" ) )
1725         {
1726             mux = HB_MUX_MKV;
1727         }
1728         else
1729         {
1730             fprintf( stderr, "Invalid output format (%s). Possible "
1731                      "choices are avi, mp4, m4v, ogm, ogg and mkv\n.", format );
1732             return 1;
1733         }
1734
1735         if( !acodec )
1736         {
1737             if( mux == HB_MUX_MP4 || mux == HB_MUX_IPOD )
1738             {
1739                 acodec = HB_ACODEC_FAAC;
1740             }
1741             else if( mux == HB_MUX_AVI )
1742             {
1743                 acodec = HB_ACODEC_LAME;
1744             }
1745             else if( mux == HB_MUX_OGM )
1746             {
1747                 acodec = HB_ACODEC_VORBIS;
1748             }
1749             else if( mux == HB_MUX_MKV )
1750             {
1751                 acodec = HB_ACODEC_AC3;
1752             }
1753         }
1754
1755     }
1756
1757     return 0;
1758 }