OSDN Git Service

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