OSDN Git Service

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