OSDN Git Service

Allow short option name -P for loose anamorphic to take its optional argument without...
[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
71 /* Exit cleanly on Ctrl-C */
72 static volatile int die = 0;
73 static void SigHandler( int );
74
75 /* Utils */
76 static void ShowCommands();
77 static void ShowHelp();
78 static int  ParseOptions( int argc, char ** argv );
79 static int  CheckOptions( int argc, char ** argv );
80 static int  HandleEvents( hb_handle_t * h );
81
82 /****************************************************************************
83  * hb_error_handler
84  * 
85  * When using the CLI just display using hb_log as we always did in the past
86  * make sure that we prefix with a nice ERROR message to catch peoples eyes.
87  ****************************************************************************/
88 static void hb_cli_error_handler ( const char *errmsg )
89 {
90     fprintf( stderr, "ERROR: %s", errmsg );
91 }
92
93 int main( int argc, char ** argv )
94 {
95     hb_handle_t * h;
96     int           build;
97     char        * version;
98
99     /* Parse command line */
100     if( ParseOptions( argc, argv ) ||
101         CheckOptions( argc, argv ) )
102     {
103         return 1;
104     }
105
106     /* Register our error handler */
107     hb_register_error_handler(&hb_cli_error_handler);
108
109     /* Init libhb */
110     h = hb_init( debug, update );
111
112     /* Show version */
113     fprintf( stderr, "HandBrake %s (%d) - http://handbrake.m0k.org/\n",
114              hb_get_version( h ), hb_get_build( h ) );
115
116     /* Check for update */
117     if( update )
118     {
119         if( ( build = hb_check_update( h, &version ) ) > -1 )
120         {
121             fprintf( stderr, "You are using an old version of "
122                      "HandBrake.\nLatest is %s (build %d).\n", version,
123                      build );
124         }
125         else
126         {
127             fprintf( stderr, "Your version of HandBrake is up to "
128                      "date.\n" );
129         }
130         hb_close( &h );
131         return 0;
132     }
133
134     /* Geeky */
135     fprintf( stderr, "%d CPU%s detected\n", hb_get_cpu_count(),
136              hb_get_cpu_count( h ) > 1 ? "s" : "" );
137     if( cpu )
138     {
139         fprintf( stderr, "Forcing %d CPU%s\n", cpu,
140                  cpu > 1 ? "s" : "" );
141         hb_set_cpu_count( h, cpu );
142     }
143
144     /* Exit ASAP on Ctrl-C */
145     signal( SIGINT, SigHandler );
146
147     /* Feed libhb with a DVD to scan */
148     fprintf( stderr, "Opening %s...\n", input );
149
150     if (longest_title) {
151         /*
152          * We need to scan for all the titles in order to find the longest
153          */
154         titleindex = 0;
155     }
156     hb_scan( h, input, titleindex );
157
158     /* Wait... */
159     while( !die )
160     {
161 #if !defined(SYS_BEOS)
162         fd_set         fds;
163         struct timeval tv;
164         int            ret;
165         char           buf[257];
166
167         tv.tv_sec  = 0;
168         tv.tv_usec = 100000;
169
170         FD_ZERO( &fds );
171         FD_SET( STDIN_FILENO, &fds );
172         ret = select( STDIN_FILENO + 1, &fds, NULL, NULL, &tv );
173
174         if( ret > 0 )
175         {
176             int size = 0;
177
178             while( size < 256 &&
179                    read( STDIN_FILENO, &buf[size], 1 ) > 0 )
180             {
181                 if( buf[size] == '\n' )
182                 {
183                     break;
184                 }
185                 size++;
186             }
187
188             if( size >= 256 || buf[size] == '\n' )
189             {
190                 switch( buf[0] )
191                 {
192                     case 'q':
193                         fprintf( stdout, "\nEncoding Quit by user command\n" );
194                         die = 1;
195                         break;
196                     case 'p':
197                         fprintf( stdout, "\nEncoding Paused by user command, 'r' to resume\n" );
198                         hb_pause( h );
199                         break;
200                     case 'r':
201                         hb_resume( h );
202                         break;
203                     case 'h':
204                         ShowCommands();
205                         break;
206                 }
207             }
208         }
209         hb_snooze( 200 );
210 #else
211         hb_snooze( 200 );
212 #endif
213
214         HandleEvents( h );
215     }
216
217     /* Clean up */
218     hb_close( &h );
219     if( input )  free( input );
220     if( output ) free( output );
221     if( format ) free( format );
222     if( audios ) free( audios );
223     if (native_language ) free (native_language );
224         if( x264opts ) free (x264opts );
225         if( x264opts2 ) free (x264opts2 );
226         
227     fprintf( stderr, "HandBrake has exited.\n" );
228
229     return 0;
230 }
231
232 static void ShowCommands()
233 {
234     fprintf( stdout, "\nCommands:\n" );
235     fprintf( stdout, " [h]elp    Show this message\n" );
236     fprintf( stdout, " [q]uit    Exit HandBrakeCLI\n" );
237     fprintf( stdout, " [p]ause   Pause encoding\n" );
238     fprintf( stdout, " [r]esume  Resume encoding\n" );
239 }
240
241 static void PrintTitleInfo( hb_title_t * title )
242 {
243     hb_chapter_t  * chapter;
244     hb_audio_t    * audio;
245     hb_subtitle_t * subtitle;
246     int i;
247
248     fprintf( stderr, "+ title %d:\n", title->index );
249     fprintf( stderr, "  + vts %d, ttn %d, cells %d->%d (%d blocks)\n",
250              title->vts, title->ttn, title->cell_start, title->cell_end,
251              title->block_count );
252     fprintf( stderr, "  + duration: %02d:%02d:%02d\n",
253              title->hours, title->minutes, title->seconds );
254     fprintf( stderr, "  + size: %dx%d, aspect: %.2f, %.3f fps\n",
255              title->width, title->height,
256              (float) title->aspect / HB_ASPECT_BASE,
257              (float) title->rate / title->rate_base );
258     fprintf( stderr, "  + autocrop: %d/%d/%d/%d\n", title->crop[0],
259              title->crop[1], title->crop[2], title->crop[3] );
260     fprintf( stderr, "  + chapters:\n" );
261     for( i = 0; i < hb_list_count( title->list_chapter ); i++ )
262     {
263         chapter = hb_list_item( title->list_chapter, i );
264         fprintf( stderr, "    + %d: cells %d->%d, %d blocks, duration "
265                  "%02d:%02d:%02d\n", chapter->index,
266                  chapter->cell_start, chapter->cell_end,
267                  chapter->block_count, chapter->hours, chapter->minutes,
268                  chapter->seconds );
269     }
270     fprintf( stderr, "  + audio tracks:\n" );
271     for( i = 0; i < hb_list_count( title->list_audio ); i++ )
272     {
273         audio = hb_list_item( title->list_audio, i );
274         if( ( audio->codec & HB_ACODEC_AC3 ) || ( audio->codec & HB_ACODEC_DCA) )
275         {
276             fprintf( stderr, "    + %d, %s, %dHz, %dbps\n", i + 1,
277                      audio->lang, audio->rate, audio->bitrate );
278         }
279         else
280         {
281             fprintf( stderr, "    + %d, %s\n", i + 1, audio->lang );
282         }
283     }
284     fprintf( stderr, "  + subtitle tracks:\n" );
285     for( i = 0; i < hb_list_count( title->list_subtitle ); i++ )
286     {
287         subtitle = hb_list_item( title->list_subtitle, i );
288         fprintf( stderr, "    + %d, %s (iso639-2: %s)\n", i + 1, subtitle->lang,
289             subtitle->iso639_2);
290     }
291 }
292
293 static int HandleEvents( hb_handle_t * h )
294 {
295     hb_state_t s;
296     hb_get_state( h, &s );
297     switch( s.state )
298     {
299         case HB_STATE_IDLE:
300             /* Nothing to do */
301             break;
302
303 #define p s.param.scanning
304         case HB_STATE_SCANNING:
305             /* Show what title is currently being scanned */
306             fprintf( stderr, "Scanning title %d", p.title_cur );
307             if( !titleindex )
308                 fprintf( stderr, " of %d", p.title_count );
309             fprintf( stderr, "...\n" );
310             break;
311 #undef p
312
313         case HB_STATE_SCANDONE:
314         {
315             hb_list_t  * list;
316             hb_title_t * title;
317             hb_job_t   * job;
318
319             list = hb_get_titles( h );
320
321             if( !hb_list_count( list ) )
322             {
323                 /* No valid title, stop right there */
324                 fprintf( stderr, "No title found.\n" );
325                 die = 1;
326                 break;
327             }
328             if( longest_title )
329             {
330                 int i;
331                 int longest_title_idx=0;
332                 int longest_title_pos=-1;
333                 int longest_title_time=0;
334                 int title_time;
335                 
336                 fprintf( stderr, "Searching for longest title...\n" );
337
338                 for( i = 0; i < hb_list_count( list ); i++ )
339                 {
340                     title = hb_list_item( list, i );
341                     title_time = (title->hours*60*60 ) + (title->minutes *60) + (title->seconds);
342                     fprintf( stderr, " + Title (%d) index %d has length %dsec\n", 
343                              i, title->index, title_time );
344                     if( longest_title_time < title_time )
345                     {
346                         longest_title_time = title_time;
347                         longest_title_pos = i;
348                         longest_title_idx = title->index;
349                     }               
350                 }
351                 if( longest_title_pos == -1 ) 
352                 {
353                     fprintf( stderr, "No longest title found.\n" );
354                     die = 1;
355                     break;
356                 }
357                 titleindex = longest_title_idx;
358                 fprintf( stderr, "Found longest title, setting title to %d\n", 
359                          longest_title_idx);
360
361                 title = hb_list_item( list, longest_title_pos);
362             } else {
363                 title = hb_list_item( list, 0 );
364             }
365
366             if( !titleindex )
367             {
368                 /* Scan-only mode, print infos and exit */
369                 int i;
370                 for( i = 0; i < hb_list_count( list ); i++ )
371                 {
372                     title = hb_list_item( list, i );
373                     PrintTitleInfo( title );
374                 }
375                 die = 1;
376                 break;
377             }
378
379             /* Set job settings */
380             job   = title->job;
381
382             PrintTitleInfo( title );
383
384             if( chapter_start && chapter_end )
385             {
386                 job->chapter_start = MAX( job->chapter_start,
387                                           chapter_start );
388                 job->chapter_end   = MIN( job->chapter_end,
389                                           chapter_end );
390                 job->chapter_end   = MAX( job->chapter_start,
391                                           job->chapter_end );
392             }
393
394                         if ( chapter_markers )
395                         {
396                                 job->chapter_markers = chapter_markers;
397
398                 if( marker_file != NULL )
399                 {
400                     hb_csv_file_t * file = hb_open_csv_file( marker_file );
401                     hb_csv_cell_t * cell;
402                     int row = 0;
403                     int chapter = 0;
404                     
405                     fprintf( stderr, "Reading chapter markers from file %s\n", marker_file );
406                     
407                     if( file == NULL )
408                     {
409                          fprintf( stderr, "Cannot open chapter marker file, using defaults\n" );
410                     }
411                     else
412                     {
413                         /* Parse the cells */
414                         while( NULL != ( cell = hb_read_next_cell( file ) ) )
415                         {                            
416                             /* We have a chapter number */
417                             if( cell->cell_col == 0 )
418                             {
419                                 row = cell->cell_row;
420                                 chapter = atoi( cell->cell_text );
421                             }
422                              
423                             /* We have a chapter name */
424                             if( cell->cell_col == 1 && row == cell->cell_row )
425                             {
426                                 /* If we have a valid chapter, copy the string an terminate it */
427                                 if( chapter >= job->chapter_start && chapter <= job->chapter_end )
428                                 {
429                                     hb_chapter_t * chapter_s;
430                                     
431                                     chapter_s = hb_list_item( job->title->list_chapter, chapter - 1);
432                                     strncpy(chapter_s->title, cell->cell_text, 1023);
433                                     chapter_s->title[1023] = '\0';
434                                 }
435                             }                               
436                         
437                                                            
438                             hb_dispose_cell( cell );
439                         }
440                         
441                         hb_close_csv_file( file );
442                     }
443                 }
444                         }
445
446             if( crop[0] >= 0 && crop[1] >= 0 &&
447                 crop[2] >= 0 && crop[3] >= 0 )
448             {
449                 memcpy( job->crop, crop, 4 * sizeof( int ) );
450             }
451
452             job->deinterlace = deinterlace;
453             job->grayscale   = grayscale;
454             if (loosePixelratio)
455             {
456                 job->pixel_ratio = 2;
457                 if (modulus)
458                 {
459                     job->modulus = modulus;
460                 }
461             }
462             else
463             {
464                 job->pixel_ratio = pixelratio;
465             }
466             /* Add selected filters */
467             job->filters = hb_list_init();
468             if( detelecine )
469             {
470                 hb_filter_detelecine.settings = detelecine_opt;
471                 hb_list_add( job->filters, &hb_filter_detelecine );
472             }
473             if( deinterlace )
474             {
475                 hb_filter_deinterlace.settings = deinterlace_opt;
476                 hb_list_add( job->filters, &hb_filter_deinterlace );
477             }
478             if( deblock )
479             {
480                 hb_filter_deblock.settings = deblock_opt;
481                 hb_list_add( job->filters, &hb_filter_deblock );
482             }
483             if( denoise )
484             {
485                 hb_filter_denoise.settings = denoise_opt;
486                 hb_list_add( job->filters, &hb_filter_denoise );
487             }
488             
489             if( width && height )
490             {
491                 job->width  = width;
492                 job->height = height;
493             }
494             else if( width )
495             {
496                 job->width = width;
497                 hb_fix_aspect( job, HB_KEEP_WIDTH );
498             }
499             else if( height && !loosePixelratio)
500             {
501                 job->height = height;
502                 hb_fix_aspect( job, HB_KEEP_HEIGHT );
503             }
504             else if( !width && !height && !pixelratio && !loosePixelratio )
505             {
506                 hb_fix_aspect( job, HB_KEEP_WIDTH );
507             }
508             else if (!width && loosePixelratio)
509             {
510                 /* Default to full width when one isn't specified for loose anamorphic */
511                 job->width = title->width - job->crop[2] - job->crop[3];
512                 /* The height will be thrown away in hb.c but calculate it anyway */
513                 hb_fix_aspect( job, HB_KEEP_WIDTH );
514             }
515             
516             if( vquality >= 0.0 && vquality <= 1.0 )
517             {
518                 job->vquality = vquality;
519                 job->vbitrate = 0;
520             }
521             else if( vbitrate )
522             {
523                 job->vquality = -1.0;
524                 job->vbitrate = vbitrate;
525             }
526             if( vcodec )
527             {
528                 job->vcodec = vcodec;
529             }
530             if( h264_13 ) 
531             { 
532                 job->h264_level = 13; 
533             }
534                 if( h264_30 )
535                 {
536                     job->h264_level = 30;
537             }
538             if( vrate )
539             {
540                 job->vrate = 27000000;
541                 job->vrate_base = vrate;
542             }
543             if( arate )
544             {
545                 job->arate = arate;
546             }
547
548             if( audios )
549             {
550                 if( strcasecmp( audios, "none" ) )
551                 {
552                     int    audio_count = 0;
553                     char * tmp         = audios;
554                     while( *tmp )
555                     {
556                         if( *tmp < '0' || *tmp > '9' )
557                         {
558                             /* Skip non numeric char */
559                             tmp++;
560                             continue;
561                         }
562                                                 job->audio_mixdowns[audio_count] = audio_mixdown;
563                         job->audios[audio_count++] =
564                             strtol( tmp, &tmp, 0 ) - 1;
565                     }
566                     job->audios[audio_count] = -1;
567                 }
568                 else
569                 {
570                     job->audios[0] = -1;
571                 }
572             }
573                         else
574                         {
575                             /* default to the first audio track if none has been specified */
576                             job->audios[0] = 0;
577                             job->audio_mixdowns[0] = audio_mixdown;
578                         }
579             if( abitrate )
580             {
581                 job->abitrate = abitrate;
582             }
583             if( acodec )
584             {
585                 job->acodec = acodec;
586             }
587
588             if( size )
589             {
590                 job->vbitrate = hb_calc_bitrate( job, size );
591                 fprintf( stderr, "Calculated bitrate: %d kbps\n",
592                          job->vbitrate );
593             }
594
595             if( sub )
596             {
597                 job->subtitle = sub - 1;
598             }
599
600             if( native_language )
601             {
602                 job->native_language = strdup( native_language );
603             }
604
605             if( job->mux )
606             {
607                 job->mux = mux;
608             }
609             
610             if ( largeFileSize )
611             {
612                 job->largeFileSize = 1;
613             }
614             
615             job->file = strdup( output );
616
617             if( crf )
618             {
619                 job->crf = 1;
620             }
621
622             if( x264opts != NULL && *x264opts != '\0' )
623             {
624                 fprintf( stderr, "Applying the following x264 options: %s\n", 
625                          x264opts);
626                 job->x264opts = x264opts;
627             }
628             else /*avoids a bus error crash when options aren't specified*/
629             {
630                 job->x264opts =  NULL;
631             }
632             if (maxWidth)
633                 job->maxWidth = maxWidth;
634             if (maxHeight)
635                 job->maxHeight = maxHeight;
636         
637             if( subtitle_force )
638             {
639                 job->subtitle_force = subtitle_force;
640             }
641
642             if( subtitle_scan )
643             {
644                 char *x264opts_tmp;
645
646                 /*
647                  * When subtitle scan is enabled do a fast pre-scan job
648                  * which will determine which subtitles to enable, if any.
649                  */
650                 job->pass = -1;
651                 
652                 x264opts_tmp = job->x264opts;
653
654                 job->x264opts = NULL;
655
656                 job->indepth_scan = subtitle_scan;  
657                 fprintf( stderr, "Subtitle Scan Enabled - enabling "
658                          "subtitles if found for foreign language segments\n");
659                 job->select_subtitle = malloc(sizeof(hb_subtitle_t*));
660                 *(job->select_subtitle) = NULL;
661                 
662                 /*
663                  * Add the pre-scan job
664                  */
665                 hb_add( h, job );
666
667                 job->x264opts = x264opts_tmp;
668             }
669
670             if( twoPass )
671             {
672                 /*
673                  * If subtitle_scan is enabled then only turn it on
674                  * for the first pass and then off again for the
675                  * second. 
676                  */
677                 hb_subtitle_t **subtitle_tmp = job->select_subtitle;
678
679                 job->select_subtitle = NULL;
680
681                 job->pass = 1;
682
683                 job->indepth_scan = 0;
684
685                 /*
686                  * If turbo options have been selected then append them
687                  * to the x264opts now (size includes one ':' and the '\0')
688                  */
689                 if( turbo_opts_enabled ) 
690                 {
691                     int size = (x264opts ? strlen(x264opts) : 0) + strlen(turbo_opts) + 2;
692                     char *tmp_x264opts;
693                         
694                     tmp_x264opts = malloc(size * sizeof(char));
695                     if( x264opts ) 
696                     {
697                         snprintf( tmp_x264opts, size, "%s:%s", 
698                                   x264opts, turbo_opts );  
699                         free( x264opts );
700                     } else {
701                         /*
702                          * No x264opts to modify, but apply the turbo options
703                          * anyway as they may be modifying defaults
704                          */
705                         snprintf( tmp_x264opts, size, "%s", 
706                                   turbo_opts );
707                     }
708                     x264opts = tmp_x264opts;
709
710                     fprintf( stderr, "Modified x264 options for pass 1 to append turbo options: %s\n",
711                              x264opts );
712
713                     job->x264opts = x264opts;
714                 }     
715                 hb_add( h, job );
716
717                 job->select_subtitle = subtitle_tmp;
718
719                 job->pass = 2;
720                 /*
721                  * On the second pass we turn off subtitle scan so that we
722                  * can actually encode using any subtitles that were auto
723                  * selected in the first pass (using the whacky select-subtitle
724                  * attribute of the job).
725                  */
726                 job->indepth_scan = 0;
727
728                 job->x264opts = x264opts2;
729                 
730                 hb_add( h, job );
731             }
732             else
733             {
734                 /*
735                  * Turn on subtitle scan if requested, note that this option
736                  * precludes encoding of any actual subtitles.
737                  */ 
738
739                 job->indepth_scan = 0;
740                 job->pass = 0;
741                 hb_add( h, job );
742             }
743             hb_start( h );
744             break;
745         }
746
747 #define p s.param.working
748         case HB_STATE_WORKING:
749             fprintf( stdout, "\rEncoding: task %d of %d, %.2f %%",
750                      p.job_cur, p.job_count, 100.0 * p.progress );
751             if( p.seconds > -1 )
752             {
753                 fprintf( stdout, " (%.2f fps, avg %.2f fps, ETA "
754                          "%02dh%02dm%02ds)", p.rate_cur, p.rate_avg,
755                          p.hours, p.minutes, p.seconds );
756             }
757             fflush(stdout);
758             break;
759 #undef p
760
761 #define p s.param.muxing
762         case HB_STATE_MUXING:
763         {
764             fprintf( stdout, "\rMuxing: %.2f %%", 100.0 * p.progress );
765             fflush(stdout);
766             break;
767         }
768 #undef p
769
770 #define p s.param.workdone
771         case HB_STATE_WORKDONE:
772             /* Print error if any, then exit */
773             switch( p.error )
774             {
775                 case HB_ERROR_NONE:
776                     fprintf( stderr, "\nRip done!\n" );
777                     break;
778                 case HB_ERROR_CANCELED:
779                     fprintf( stderr, "\nRip canceled.\n" );
780                     break;
781                 default:
782                     fprintf( stderr, "\nRip failed (error %x).\n",
783                              p.error );
784             }
785             die = 1;
786             break;
787 #undef p
788     }
789     return 0;
790 }
791
792 /****************************************************************************
793  * SigHandler:
794  ****************************************************************************/
795 static volatile int64_t i_die_date = 0;
796 void SigHandler( int i_signal )
797 {
798     if( die == 0 )
799     {
800         die = 1;
801         i_die_date = hb_get_date();
802         fprintf( stderr, "Signal %d received, terminating - do it "
803                  "again in case it gets stuck\n", i_signal );
804     }
805     else if( i_die_date + 500 < hb_get_date() )
806     {
807         fprintf( stderr, "Dying badly, files might remain in your /tmp\n" );
808         exit( 1 );
809     }
810 }
811
812 /****************************************************************************
813  * ShowHelp:
814  ****************************************************************************/
815 static void ShowHelp()
816 {
817     int i;
818     
819     fprintf( stderr,
820     "Syntax: HandBrakeCLI [options] -i <device> -o <file>\n"
821     "\n"
822         "### General Handbrake Options------------------------------------------------\n\n"
823     "    -h, --help              Print help\n"
824     "    -u, --update            Check for updates and exit\n"
825     "    -v, --verbose           Be verbose\n"
826     "    -C, --cpu               Set CPU count (default: autodetected)\n"
827     "\n"
828         
829         "### Source Options-----------------------------------------------------------\n\n"
830         "    -i, --input <string>    Set input device\n"
831         "    -t, --title <number>    Select a title to encode (0 to scan only,\n"
832     "                            default: 1)\n"
833     "    -L, --longest           Select the longest title\n"
834     "    -c, --chapters <string> Select chapters (e.g. \"1-3\" for chapters\n"
835     "                            1 to 3, or \"3\" for chapter 3 only,\n"
836     "                            default: all chapters)\n"
837         "\n"
838         
839         "### Destination Options------------------------------------------------------\n\n"
840     "    -o, --output <string>   Set output file name\n"
841         "    -f, --format <string>   Set output format (avi/mp4/ogm/mkv, default:\n"
842     "                            autodetected from file name)\n"
843     "    -4, --large-file        Use 64-bit mp4 files that can hold more than\n"
844     "                            4 GB. Note: Breaks iPod, @TV, PS3 compatibility.\n"""
845     "\n"
846         
847         "### Picture Settings---------------------------------------------------------\n\n"
848     "    -w, --width <number>    Set picture width\n"
849     "    -l, --height <number>   Set picture height\n"
850     "        --crop <T:B:L:R>    Set cropping values (default: autocrop)\n"
851         "    -Y, --maxHeight <#>     Set maximum height\n"
852         "    -X, --maxWidth <#>      Set maximum width\n"
853         "    -s, --subtitle <number> Select subtitle (default: none)\n"
854     "    -U, --subtitle-scan     Scan for subtitles in an extra first pass, and choose\n"
855     "                            the one that's only used 10 percent of the time\n"
856     "                            or less. This should locate subtitles for short\n"
857     "                            foreign language segments. Best used in conjunction\n"
858     "                            with --subtitle-forced.\n"
859     "    -F, --subtitle-forced   Only display subtitles from the selected stream if\n"
860     "                            the subtitle has the forced flag set. May be used in\n"
861     "                            conjunction with --subtitle-scan to auto-select\n"
862     "                            a stream if it contains forced subtitles.\n"
863     "    -N, --native-language   Select subtitles with this language if it does not\n"
864     "          <string>          match the Audio language. Provide the language's\n"
865     "                            iso639-2 code (fre, eng, spa, dut, et cetera)\n"
866         "    -m, --markers           Add chapter markers (mp4 output format only)\n"
867         "\n"
868         
869         "### Video Options------------------------------------------------------------\n\n"
870         "    -e, --encoder <string>  Set video library encoder (ffmpeg,xvid,\n"
871     "                            x264,x264b13,x264b30 default: ffmpeg)\n"
872         "    -q, --quality <float>   Set video quality (0.0..1.0)\n"
873         "    -Q, --crf               Use with -q for CRF instead of CQP\n"
874     "    -S, --size <MB>         Set target size\n"
875         "    -b, --vb <kb/s>         Set video bitrate (default: 1000)\n"
876         "    -r, --rate              Set video framerate (" );
877     for( i = 0; i < hb_video_rates_count; i++ )
878     {
879         fprintf( stderr, hb_video_rates[i].string );
880         if( i != hb_video_rates_count - 1 )
881             fprintf( stderr, "/" );
882     }
883     fprintf( stderr, ")\n"
884         "\n"
885         "    -2, --two-pass          Use two-pass mode\n"
886      "    -d, --deinterlace       Deinterlace video with yadif/mcdeint filter\n"
887      "          <YM:FD:MM:QP>     (default 0:-1:-1:1)\n"            
888      "    -7, --deblock           Deblock video with pp7 filter\n"
889      "          <QP:M>            (default 0:2)\n"
890      "    -8, --denoise           Denoise video with hqdn3d filter\n"
891      "          <SL:SC:TL:TC>     (default 4:3:6:4.5)\n"
892      "    -9, --detelecine        Detelecine video with pullup filter\n"
893      "          <L:R:T:B:SB:MP>   (default 1:1:4:4:0:0)\n"
894     "    -g, --grayscale         Grayscale encoding\n"
895     "    -p, --pixelratio        Store pixel aspect ratio in video stream\n"
896     "    -P, --loosePixelratio   Store pixel aspect ratio with specified width\n"
897     "           <modulus>        Takes as optional argument what number you want\n"
898     "                            the dimensions to divide cleanly by (default 16)\n"
899     
900         
901         "\n"
902         
903         
904         "### Audio Options-----------------------------------------------------------\n\n"
905         "    -E, --aencoder <string> Set audio encoder (faac/lame/vorbis/ac3, ac3\n"
906     "                            meaning passthrough, default: guessed)\n"
907         "    -B, --ab <kb/s>         Set audio bitrate (default: 128)\n"
908         "    -a, --audio <string>    Select audio channel(s) (\"none\" for no \n"
909     "                            audio, default: first one)\n"
910     "    -6, --mixdown <string>  Format for surround sound downmixing\n"
911     "                            (mono/stereo/dpl1/dpl2/6ch, default: dpl2)\n"
912     "    -R, --arate             Set audio samplerate (" );
913     for( i = 0; i < hb_audio_rates_count; i++ )
914     {
915         fprintf( stderr, hb_audio_rates[i].string );
916         if( i != hb_audio_rates_count - 1 )
917             fprintf( stderr, "/" );
918     }
919     fprintf( stderr, " kHz)\n"
920    
921     
922         
923         "\n"
924         
925         
926     "### Advanced H264 Options----------------------------------------------------\n\n"
927     "    -x, --x264opts <string> Specify advanced x264 options in the\n"
928     "                            same style as mencoder:\n"
929     "                            option1=value1:option2=value2\n"
930     "    -T, --turbo             When using 2-pass use the turbo options\n"
931     "                            on the first pass to improve speed\n"
932     "                            (only works with x264, affects PSNR by about 0.05dB,\n"
933     "                            and increases first pass speed two to four times)\n");
934 }
935
936 /****************************************************************************
937  * ParseOptions:
938  ****************************************************************************/
939 static int ParseOptions( int argc, char ** argv )
940 {
941     for( ;; )
942     {
943         static struct option long_options[] =
944           {
945             { "help",        no_argument,       NULL,    'h' },
946             { "update",      no_argument,       NULL,    'u' },
947             { "verbose",     no_argument,       NULL,    'v' },
948             { "cpu",         required_argument, NULL,    'C' },
949
950             { "format",      required_argument, NULL,    'f' },
951             { "input",       required_argument, NULL,    'i' },
952             { "output",      required_argument, NULL,    'o' },
953             { "large-file",  no_argument,       NULL,    '4' },
954             
955             { "title",       required_argument, NULL,    't' },
956             { "longest",     no_argument,       NULL,    'L' },
957             { "chapters",    required_argument, NULL,    'c' },
958             { "markers",     optional_argument, NULL,    'm' },
959             { "audio",       required_argument, NULL,    'a' },
960             { "mixdown",     required_argument, NULL,    '6' },
961             { "subtitle",    required_argument, NULL,    's' },
962             { "subtitle-scan", no_argument,     NULL,    'U' },
963             { "subtitle-forced", no_argument,   NULL,    'F' },
964             { "native-language", required_argument, NULL,'N' },
965
966             { "encoder",     required_argument, NULL,    'e' },
967             { "aencoder",    required_argument, NULL,    'E' },
968             { "two-pass",    no_argument,       NULL,    '2' },
969             { "deinterlace", optional_argument, NULL,    'd' },
970             { "deblock",     optional_argument, NULL,    '7' },
971             { "denoise",     optional_argument, NULL,    '8' },
972             { "detelecine",  optional_argument, NULL,    '9' },
973             { "grayscale",   no_argument,       NULL,    'g' },
974             { "pixelratio",  no_argument,       NULL,    'p' },
975             { "loosePixelratio", optional_argument,   NULL,    'P' },
976             { "width",       required_argument, NULL,    'w' },
977             { "height",      required_argument, NULL,    'l' },
978             { "crop",        required_argument, NULL,    'n' },
979
980             { "vb",          required_argument, NULL,    'b' },
981             { "quality",     required_argument, NULL,    'q' },
982             { "size",        required_argument, NULL,    'S' },
983             { "ab",          required_argument, NULL,    'B' },
984             { "rate",        required_argument, NULL,    'r' },
985             { "arate",       required_argument, NULL,    'R' },
986             { "crf",         no_argument,       NULL,    'Q' },
987             { "x264opts",    required_argument, NULL,    'x' },
988             { "turbo",       no_argument,       NULL,    'T' },
989             
990             { "maxHeight",   required_argument, NULL,    'Y' },
991             { "maxWidth",    required_argument, NULL,    'X' },
992                         
993             { 0, 0, 0, 0 }
994           };
995
996         int option_index = 0;
997         int c;
998
999         c = getopt_long( argc, argv,
1000                          "hvuC:f:4i:o:t:Lc:ma:6:s:UFN:e:E:2d789gpP:w:l:n:b:q:S:B:r:R:Qx:TY:X:",
1001                          long_options, &option_index );
1002         if( c < 0 )
1003         {
1004             break;
1005         }
1006
1007         switch( c )
1008         {
1009             case 'h':
1010                 ShowHelp();
1011                 exit( 0 );
1012             case 'u':
1013                 update = 1;
1014                 break;
1015             case 'v':
1016                 debug = HB_DEBUG_ALL;
1017                 break;
1018             case 'C':
1019                 cpu = atoi( optarg );
1020                 break;
1021
1022             case 'f':
1023                 format = strdup( optarg );
1024                 break;
1025             case 'i':
1026                 input = strdup( optarg );
1027                 break;
1028             case 'o':
1029                 output = strdup( optarg );
1030                 break;
1031             case '4':
1032                 largeFileSize = 1;
1033                 break;
1034             case 't':
1035                 titleindex = atoi( optarg );
1036                 break;
1037             case 'L':
1038                 longest_title = 1;
1039                 break;
1040             case 'c':
1041             {
1042                 int start, end;
1043                 if( sscanf( optarg, "%d-%d", &start, &end ) == 2 )
1044                 {
1045                     chapter_start = start;
1046                     chapter_end   = end;
1047                 }
1048                 else if( sscanf( optarg, "%d", &start ) == 1 )
1049                 {
1050                     chapter_start = start;
1051                     chapter_end   = chapter_start;
1052                 }
1053                 else
1054                 {
1055                     fprintf( stderr, "chapters: invalid syntax (%s)\n",
1056                              optarg );
1057                     return -1;
1058                 }
1059                 break;
1060             }
1061             case 'm':
1062                 if( optarg != NULL )
1063                 {
1064                     marker_file = strdup( optarg );
1065                 }
1066                 chapter_markers = 1;
1067                 break;
1068             case 'a':
1069                 audios = strdup( optarg );
1070                 break;
1071             case '6':
1072                 if( !strcasecmp( optarg, "mono" ) )
1073                 {
1074                     audio_mixdown = HB_AMIXDOWN_MONO;
1075                 }
1076                 else if( !strcasecmp( optarg, "stereo" ) )
1077                 {
1078                     audio_mixdown = HB_AMIXDOWN_STEREO;
1079                 }
1080                 else if( !strcasecmp( optarg, "dpl1" ) )
1081                 {
1082                     audio_mixdown = HB_AMIXDOWN_DOLBY;
1083                 }
1084                 else if( !strcasecmp( optarg, "dpl2" ) )
1085                 {
1086                     audio_mixdown = HB_AMIXDOWN_DOLBYPLII;
1087                 }
1088                 else if( !strcasecmp( optarg, "6ch" ) )
1089                 {
1090                     audio_mixdown = HB_AMIXDOWN_6CH;
1091                 }
1092                 break;
1093             case 's':
1094                 sub = atoi( optarg );
1095                 break;
1096             case 'U':
1097                 subtitle_scan = 1;
1098                 break;
1099             case 'F':
1100                 subtitle_force = 1;
1101                 break;
1102             case 'N':
1103                 native_language = strdup( optarg );
1104                 break;
1105             case '2':
1106                 twoPass = 1;
1107                 break;
1108             case 'd':
1109                 if( optarg != NULL )
1110                 {
1111                     deinterlace_opt = strdup( optarg );
1112                 }
1113                 deinterlace = 1;
1114                 break;
1115             case '7':
1116                 if( optarg != NULL )
1117                 {
1118                     deblock_opt = strdup( optarg );
1119                 }
1120                 deblock = 1;
1121                 break;
1122             case '8':
1123                 if( optarg != NULL )
1124                 {
1125                     denoise_opt = strdup( optarg );
1126                 }
1127                 denoise = 1;
1128                 break;                
1129             case '9':
1130                 if( optarg != NULL )
1131                 {
1132                     detelecine_opt = strdup( optarg );
1133                 }
1134                 detelecine = 1;
1135                 break;                
1136             case 'g':
1137                 grayscale = 1;
1138                 break;
1139             case 'p':
1140                 pixelratio = 1;
1141                 break;
1142             case 'P':
1143                 loosePixelratio = 1;
1144                 if( optarg != NULL )
1145                 {
1146                     modulus = atoi( optarg );
1147                 }
1148                 break;
1149             case 'e':
1150                 if( !strcasecmp( optarg, "ffmpeg" ) )
1151                 {
1152                     vcodec = HB_VCODEC_FFMPEG;
1153                 }
1154                 else if( !strcasecmp( optarg, "xvid" ) )
1155                 {
1156                     vcodec = HB_VCODEC_XVID;
1157                 }
1158                 else if( !strcasecmp( optarg, "x264" ) )
1159                 {
1160                     vcodec = HB_VCODEC_X264;
1161                 }
1162                 else if( !strcasecmp( optarg, "x264b13" ) )
1163                 {
1164                     vcodec = HB_VCODEC_X264;
1165                     h264_13 = 1;
1166                 }
1167                 else if( !strcasecmp( optarg, "x264b30" ) )
1168                 {
1169                     vcodec = HB_VCODEC_X264;
1170                     h264_30 = 1;
1171                 }
1172                 else
1173                 {
1174                     fprintf( stderr, "invalid codec (%s)\n", optarg );
1175                     return -1;
1176                 }
1177                 break;
1178             case 'E':
1179                 if( !strcasecmp( optarg, "ac3" ) )
1180                 {
1181                     acodec = HB_ACODEC_AC3;
1182                 }
1183                 else if( !strcasecmp( optarg, "lame" ) )
1184                 {
1185                     acodec = HB_ACODEC_LAME;
1186                 }
1187                 else if( !strcasecmp( optarg, "faac" ) )
1188                 {
1189                     acodec = HB_ACODEC_FAAC;
1190                 }
1191                 else if( !strcasecmp( optarg, "vorbis") )
1192                 {
1193                     acodec = HB_ACODEC_VORBIS;
1194                 }
1195                 break;
1196             case 'w':
1197                 width = atoi( optarg );
1198                 break;
1199             case 'l':
1200                 height = atoi( optarg );
1201                 break;
1202             case 'n':
1203             {
1204                 int    i;
1205                 char * tmp = optarg;
1206                 for( i = 0; i < 4; i++ )
1207                 {
1208                     if( !*tmp )
1209                         break;
1210                     crop[i] = strtol( tmp, &tmp, 0 );
1211                     tmp++;
1212                 }
1213                 break;
1214             }
1215             case 'r':
1216             {
1217                 int i;
1218                 vrate = 0;
1219                 for( i = 0; i < hb_video_rates_count; i++ )
1220                 {
1221                     if( !strcmp( optarg, hb_video_rates[i].string ) )
1222                     {
1223                         vrate = hb_video_rates[i].rate;
1224                         break;
1225                     }
1226                 }
1227                 if( !vrate )
1228                 {
1229                     fprintf( stderr, "invalid framerate %s\n", optarg );
1230                 }
1231                 break;
1232             }
1233             case 'R':
1234             {
1235                 int i;
1236                 arate = 0;
1237                 for( i = 0; i < hb_audio_rates_count; i++ )
1238                 {
1239                     if( !strcmp( optarg, hb_audio_rates[i].string ) )
1240                     {
1241                         arate = hb_audio_rates[i].rate;
1242                         break;
1243                     }
1244                 }
1245                 if( !arate )
1246                 {
1247                     fprintf( stderr, "invalid framerate %s\n", optarg );
1248                 }
1249                 break;
1250             }
1251             case 'b':
1252                 vbitrate = atoi( optarg );
1253                 break;
1254             case 'q':
1255                 vquality = atof( optarg );
1256                 break;
1257             case 'S':
1258                 size = atoi( optarg );
1259                 break;
1260             case 'B':
1261                 abitrate = atoi( optarg );
1262                 break;
1263             case 'Q':
1264                 crf = 1;
1265                 break;
1266             case 'x':
1267                 x264opts = strdup( optarg );
1268                 x264opts2 = strdup( optarg );
1269                 break;
1270             case 'T':
1271                 turbo_opts_enabled = 1;
1272                 break;
1273             case 'Y':
1274                 maxHeight = atoi( optarg );
1275                 break;
1276             case 'X':
1277                 maxWidth = atoi (optarg );
1278                 break;
1279                                 
1280             default:
1281                 fprintf( stderr, "unknown option (%s)\n", argv[optind] );
1282                 return -1;
1283         }
1284     }
1285
1286     return 0;
1287 }
1288
1289 static int CheckOptions( int argc, char ** argv )
1290 {
1291     if( update )
1292     {
1293         return 0;
1294     }
1295
1296     if( input == NULL || *input == '\0' )
1297     {
1298         fprintf( stderr, "Missing input device. Run %s --help for "
1299                  "syntax.\n", argv[0] );
1300         return 1;
1301     }
1302
1303     /* Parse format */
1304     if( titleindex > 0 )
1305     {
1306         if( output == NULL || *output == '\0' )
1307         {
1308             fprintf( stderr, "Missing output file name. Run %s --help "
1309                      "for syntax.\n", argv[0] );
1310             return 1;
1311         }
1312
1313         if( !format )
1314         {
1315             char * p = strrchr( output, '.' );
1316
1317             /* autodetect */
1318             if( p && !strcasecmp( p, ".avi" ) )
1319             {
1320                 mux = HB_MUX_AVI;
1321             }
1322             else if( p && ( !strcasecmp( p, ".mp4" )  ||
1323                             !strcasecmp( p, ".m4v" ) ) )
1324             {
1325                 if ( h264_30 == 1 )
1326                     mux = HB_MUX_IPOD;
1327                 else
1328                     mux = HB_MUX_MP4;
1329             }
1330             else if( p && ( !strcasecmp( p, ".ogm" ) ||
1331                             !strcasecmp( p, ".ogg" ) ) )
1332             {
1333                 mux = HB_MUX_OGM;
1334             }
1335             else if( p && !strcasecmp(p, ".mkv" ) )
1336             {
1337                 mux = HB_MUX_MKV;
1338             }
1339             else
1340             {
1341                 fprintf( stderr, "Output format couldn't be guessed "
1342                          "from file name, using default.\n" );
1343                 return 0;
1344             }
1345         }
1346         else if( !strcasecmp( format, "avi" ) )
1347         {
1348             mux = HB_MUX_AVI;
1349         }
1350         else if( !strcasecmp( format, "mp4" ) )
1351         {
1352             if ( h264_30 == 1)
1353                 mux = HB_MUX_IPOD;
1354             else
1355                 mux = HB_MUX_MP4;
1356         }
1357         else if( !strcasecmp( format, "ogm" ) ||
1358                  !strcasecmp( format, "ogg" ) )
1359         {
1360             mux = HB_MUX_OGM;
1361         }
1362         else if( !strcasecmp( format, "mkv" ) )
1363         {
1364             mux = HB_MUX_MKV;
1365         }
1366         else
1367         {
1368             fprintf( stderr, "Invalid output format (%s). Possible "
1369                      "choices are avi, mp4, m4v, ogm, ogg and mkv\n.", format );
1370             return 1;
1371         }
1372
1373         if( !acodec )
1374         {
1375             if( mux == HB_MUX_MP4 || mux == HB_MUX_IPOD )
1376             {
1377                 acodec = HB_ACODEC_FAAC;
1378             }
1379             else if( mux == HB_MUX_AVI )
1380             {
1381                 acodec = HB_ACODEC_LAME;
1382             }
1383             else if( mux == HB_MUX_OGM )
1384             {
1385                 acodec = HB_ACODEC_VORBIS;
1386             }
1387             else if( mux == HB_MUX_MKV )
1388             {
1389                 acodec = HB_ACODEC_AC3;
1390             }
1391         }
1392
1393     }
1394
1395     return 0;
1396 }