OSDN Git Service

MacGui: Allow up to 320 kbps bitrate for stereo and 768 kbps for 6 channel discrete...
[handbrake-jp/handbrake-jp-git.git] / libhb / dvdnav.c
1 /* $Id: dvd.c,v 1.12 2005/11/25 15:05:25 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 "hb.h"
8 #include "lang.h"
9 #include "dvd.h"
10
11 #include "dvdnav/dvdnav.h"
12 #include "dvdread/ifo_read.h"
13 #include "dvdread/ifo_print.h"
14 #include "dvdread/nav_read.h"
15
16 #define DVD_READ_CACHE 1
17
18 static char        * hb_dvdnav_name( char * path );
19 static hb_dvd_t    * hb_dvdnav_init( char * path );
20 static int           hb_dvdnav_title_count( hb_dvd_t * d );
21 static hb_title_t  * hb_dvdnav_title_scan( hb_dvd_t * d, int t );
22 static int           hb_dvdnav_start( hb_dvd_t * d, hb_title_t *title, int chapter );
23 static void          hb_dvdnav_stop( hb_dvd_t * d );
24 static int           hb_dvdnav_seek( hb_dvd_t * d, float f );
25 static int           hb_dvdnav_read( hb_dvd_t * d, hb_buffer_t * b );
26 static int           hb_dvdnav_chapter( hb_dvd_t * d );
27 static void          hb_dvdnav_close( hb_dvd_t ** _d );
28 static int           hb_dvdnav_angle_count( hb_dvd_t * d );
29 static void          hb_dvdnav_set_angle( hb_dvd_t * e, int angle );
30
31 hb_dvd_func_t hb_dvdnav_func =
32 {
33     hb_dvdnav_init,
34     hb_dvdnav_close,
35     hb_dvdnav_name,
36     hb_dvdnav_title_count,
37     hb_dvdnav_title_scan,
38     hb_dvdnav_start,
39     hb_dvdnav_stop,
40     hb_dvdnav_seek,
41     hb_dvdnav_read,
42     hb_dvdnav_chapter,
43     hb_dvdnav_angle_count,
44     hb_dvdnav_set_angle
45 };
46
47 // there can be at most 999 PGCs per title. round that up to the nearest
48 // power of two.
49 #define MAX_PGCN 1024
50
51 /***********************************************************************
52  * Local prototypes
53  **********************************************************************/
54 static void PgcWalkInit( uint32_t pgcn_map[MAX_PGCN/32] );
55 static int FindChapterIndex( hb_list_t * list, int pgcn, int pgn );
56 static int NextPgcn( ifo_handle_t *ifo, int pgcn, uint32_t pgcn_map[MAX_PGCN/32] );
57 static int FindNextCell( pgc_t *pgc, int cell_cur );
58 static int dvdtime2msec( dvd_time_t * );
59
60 hb_dvd_func_t * hb_dvdnav_methods( void )
61 {
62     return &hb_dvdnav_func;
63 }
64
65 static char * hb_dvdnav_name( char * path )
66 {
67     static char name[1024];
68     unsigned char unused[1024];
69     dvd_reader_t * reader;
70
71     reader = DVDOpen( path );
72     if( !reader )
73     {
74         return NULL;
75     }
76
77     if( DVDUDFVolumeInfo( reader, name, sizeof( name ),
78                           unused, sizeof( unused ) ) )
79     {
80         DVDClose( reader );
81         return NULL;
82     }
83
84     DVDClose( reader );
85     return name;
86 }
87
88 /***********************************************************************
89  * hb_dvdnav_reset
90  ***********************************************************************
91  * Once dvdnav has entered the 'stopped' state, it can not be revived
92  * dvdnav_reset doesn't work because it doesn't remember the path
93  * So this function re-opens dvdnav
94  **********************************************************************/
95 static int hb_dvdnav_reset( hb_dvdnav_t * d )
96 {
97     if ( d->dvdnav ) 
98         dvdnav_close( d->dvdnav );
99
100     /* Open device */
101     if( dvdnav_open(&d->dvdnav, d->path) != DVDNAV_STATUS_OK )
102     {
103         /*
104          * Not an error, may be a stream - which we'll try in a moment.
105          */
106         hb_log( "dvd: not a dvd - trying as a stream/file instead" );
107         goto fail;
108     }
109
110     if (dvdnav_set_readahead_flag(d->dvdnav, DVD_READ_CACHE) !=
111         DVDNAV_STATUS_OK)
112     {
113         hb_error("Error: dvdnav_set_readahead_flag: %s\n",
114                  dvdnav_err_to_string(d->dvdnav));
115         goto fail;
116     }
117
118     /*
119      ** set the PGC positioning flag to have position information
120      ** relatively to the whole feature instead of just relatively to the
121      ** current chapter 
122      **/
123     if (dvdnav_set_PGC_positioning_flag(d->dvdnav, 1) != DVDNAV_STATUS_OK)
124     {
125         hb_error("Error: dvdnav_set_PGC_positioning_flag: %s\n",
126                  dvdnav_err_to_string(d->dvdnav));
127         goto fail;
128     }
129     return 1;
130
131 fail:
132     if( d->dvdnav ) dvdnav_close( d->dvdnav );
133     return 0;
134 }
135
136 /***********************************************************************
137  * hb_dvdnav_init
138  ***********************************************************************
139  *
140  **********************************************************************/
141 static hb_dvd_t * hb_dvdnav_init( char * path )
142 {
143     hb_dvd_t * e;
144     hb_dvdnav_t * d;
145     int region_mask;
146
147     e = calloc( sizeof( hb_dvd_t ), 1 );
148     d = &(e->dvdnav);
149
150         /* Log DVD drive region code */
151     if ( hb_dvd_region( path, &region_mask ) == 0 )
152     {
153         hb_log( "dvd: Region mask 0x%02x", region_mask );
154         if ( region_mask == 0xFF )
155         {
156             hb_log( "dvd: Warning, DVD device has no region set" );
157         }
158     }
159
160     /* Open device */
161     if( dvdnav_open(&d->dvdnav, path) != DVDNAV_STATUS_OK )
162     {
163         /*
164          * Not an error, may be a stream - which we'll try in a moment.
165          */
166         hb_log( "dvd: not a dvd - trying as a stream/file instead" );
167         goto fail;
168     }
169
170     if (dvdnav_set_readahead_flag(d->dvdnav, DVD_READ_CACHE) !=
171         DVDNAV_STATUS_OK)
172     {
173         hb_error("Error: dvdnav_set_readahead_flag: %s\n",
174                  dvdnav_err_to_string(d->dvdnav));
175         goto fail;
176     }
177
178     /*
179      ** set the PGC positioning flag to have position information
180      ** relatively to the whole feature instead of just relatively to the
181      ** current chapter 
182      **/
183     if (dvdnav_set_PGC_positioning_flag(d->dvdnav, 1) != DVDNAV_STATUS_OK)
184     {
185         hb_error("Error: dvdnav_set_PGC_positioning_flag: %s\n",
186                  dvdnav_err_to_string(d->dvdnav));
187         goto fail;
188     }
189
190     /* Open device */
191     if( !( d->reader = DVDOpen( path ) ) )
192     {
193         /*
194          * Not an error, may be a stream - which we'll try in a moment.
195          */
196         hb_log( "dvd: not a dvd - trying as a stream/file instead" );
197         goto fail;
198     }
199
200     /* Open main IFO */
201     if( !( d->vmg = ifoOpen( d->reader, 0 ) ) )
202     {
203         hb_error( "dvd: ifoOpen failed" );
204         goto fail;
205     }
206
207     d->path = strdup( path );
208
209     return e;
210
211 fail:
212     if( d->dvdnav ) dvdnav_close( d->dvdnav );
213     if( d->vmg )    ifoClose( d->vmg );
214     if( d->reader ) DVDClose( d->reader );
215     free( e );
216     return NULL;
217 }
218
219 /***********************************************************************
220  * hb_dvdnav_title_count
221  **********************************************************************/
222 static int hb_dvdnav_title_count( hb_dvd_t * e )
223 {
224     int titles = 0;
225     hb_dvdnav_t * d = &(e->dvdnav);
226
227     dvdnav_get_number_of_titles(d->dvdnav, &titles);
228     return titles;
229 }
230
231 static uint64_t
232 PttDuration(ifo_handle_t *ifo, int ttn, int pttn, int *blocks, int *last_pgcn)
233 {
234     int            pgcn, pgn;
235     pgc_t        * pgc;
236     uint64_t       duration = 0;
237     int            cell_start, cell_end;
238     int            i;
239
240     // Initialize map of visited pgc's to prevent loops
241     uint32_t pgcn_map[MAX_PGCN/32];
242     PgcWalkInit( pgcn_map );
243     pgcn   = ifo->vts_ptt_srpt->title[ttn-1].ptt[pttn-1].pgcn;
244     pgn   = ifo->vts_ptt_srpt->title[ttn-1].ptt[pttn-1].pgn;
245     if ( pgcn < 1 || pgcn > ifo->vts_pgcit->nr_of_pgci_srp || pgcn >= MAX_PGCN)
246     {
247         hb_error( "invalid PGC ID %d, skipping", pgcn );
248         return 0;
249     }
250
251     if( pgn <= 0 || pgn > 99 )
252     {
253         hb_error( "scan: pgn %d not valid, skipping", pgn );
254         return 0;
255     }
256
257     *blocks = 0;
258     do
259     {
260         pgc = ifo->vts_pgcit->pgci_srp[pgcn-1].pgc;
261         if (!pgc)
262         {
263             hb_error( "scan: pgc not valid, skipping" );
264             break;
265         }
266         if (pgn > pgc->nr_of_programs)
267         {
268             pgn = 1;
269             continue;
270         }
271
272         duration += 90LL * dvdtime2msec( &pgc->playback_time );
273
274         cell_start = pgc->program_map[pgn-1] - 1;
275         cell_end = pgc->nr_of_cells - 1;
276         for(i = cell_start; i <= cell_end; i = FindNextCell(pgc, i))
277         {
278             *blocks += pgc->cell_playback[i].last_sector + 1 -
279                 pgc->cell_playback[i].first_sector;
280         }
281         *last_pgcn = pgcn;
282         pgn = 1;
283     } while((pgcn = NextPgcn(ifo, pgcn, pgcn_map)) != 0);
284     return duration;
285 }
286
287 /***********************************************************************
288  * hb_dvdnav_title_scan
289  **********************************************************************/
290 static hb_title_t * hb_dvdnav_title_scan( hb_dvd_t * e, int t )
291 {
292
293     hb_dvdnav_t * d = &(e->dvdnav);
294     hb_title_t   * title;
295     ifo_handle_t * ifo = NULL;
296     int            pgcn, pgn, pgcn_end, i, c;
297     int            title_pgcn;
298     pgc_t        * pgc;
299     int            cell_cur;
300     hb_chapter_t * chapter;
301     int            count;
302     uint64_t       duration, longest;
303     int            longest_pgcn, longest_pgn, longest_pgcn_end;
304     float          duration_correction;
305     const char   * name;
306
307     hb_log( "scan: scanning title %d", t );
308
309     title = hb_title_init( d->path, t );
310     title->type = HB_DVD_TYPE;
311     if (dvdnav_get_title_string(d->dvdnav, &name) == DVDNAV_STATUS_OK)
312     {
313         strncpy( title->name, name, sizeof( title->name ) );
314     }
315     else
316     {
317         char * p_cur, * p_last = d->path;
318         for( p_cur = d->path; *p_cur; p_cur++ )
319         {
320             if( p_cur[0] == '/' && p_cur[1] )
321             {
322                 p_last = &p_cur[1];
323             }
324         }
325         snprintf( title->name, sizeof( title->name ), "%s", p_last );
326     }
327
328     /* VTS which our title is in */
329     title->vts = d->vmg->tt_srpt->title[t-1].title_set_nr;
330
331     if ( !title->vts )
332     {
333         /* A VTS of 0 means the title wasn't found in the title set */
334         hb_error("Invalid VTS (title set) number: %i", title->vts);
335         goto fail;
336     }
337
338     hb_log( "scan: opening IFO for VTS %d", title->vts );
339     if( !( ifo = ifoOpen( d->reader, title->vts ) ) )
340     {
341         hb_error( "scan: ifoOpen failed" );
342         goto fail;
343     }
344
345     /* ignore titles with bogus cell addresses so we don't abort later
346      ** in libdvdread. */
347     for ( i = 0; i < ifo->vts_c_adt->nr_of_vobs; ++i)
348     {
349         if( (ifo->vts_c_adt->cell_adr_table[i].start_sector & 0xffffff ) ==
350             0xffffff )
351         {
352             hb_error( "scan: cell_adr_table[%d].start_sector invalid (0x%x) "
353                       "- skipping title", i,
354                       ifo->vts_c_adt->cell_adr_table[i].start_sector );
355             goto fail;
356         }
357         if( (ifo->vts_c_adt->cell_adr_table[i].last_sector & 0xffffff ) ==
358             0xffffff )
359         {
360             hb_error( "scan: cell_adr_table[%d].last_sector invalid (0x%x) "
361                       "- skipping title", i,
362                       ifo->vts_c_adt->cell_adr_table[i].last_sector );
363             goto fail;
364         }
365         if( ifo->vts_c_adt->cell_adr_table[i].start_sector >=
366             ifo->vts_c_adt->cell_adr_table[i].last_sector )
367         {
368             hb_error( "scan: cell_adr_table[%d].start_sector (0x%x) "
369                       "is not before last_sector (0x%x) - skipping title", i,
370                       ifo->vts_c_adt->cell_adr_table[i].start_sector,
371                       ifo->vts_c_adt->cell_adr_table[i].last_sector );
372             goto fail;
373         }
374     }
375
376     if( global_verbosity_level == 3 )
377     {
378         ifo_print( d->reader, title->vts );
379     }
380
381     /* Position of the title in the VTS */
382     title->ttn = d->vmg->tt_srpt->title[t-1].vts_ttn;
383     if ( title->ttn < 1 || title->ttn > ifo->vts_ptt_srpt->nr_of_srpts )
384     {
385         hb_error( "invalid VTS PTT offset %d for title %d, skipping", title->ttn, t );
386         goto fail;
387     }
388
389     longest = 0LL;
390     longest_pgcn = -1;
391     longest_pgn = 1;
392     longest_pgcn_end = -1;
393     pgcn_end = -1;
394     for( i = 0; i < ifo->vts_ptt_srpt->title[title->ttn-1].nr_of_ptts; i++ )
395     {
396         int blocks = 0;
397
398         duration = PttDuration(ifo, title->ttn, i+1, &blocks, &pgcn_end);
399         pgcn  = ifo->vts_ptt_srpt->title[title->ttn-1].ptt[i].pgcn;
400         pgn   = ifo->vts_ptt_srpt->title[title->ttn-1].ptt[i].pgn;
401         if( duration > longest )
402         {
403             longest_pgcn  = pgcn;
404             longest_pgn   = pgn;
405             longest_pgcn_end   = pgcn_end;
406             longest = duration;
407             title->block_count = blocks;
408         }
409         else if (pgcn == longest_pgcn && pgn < longest_pgn)
410         {
411             longest_pgn   = pgn;
412             title->block_count = blocks;
413         }
414     }
415
416     /* ignore titles under 10 seconds because they're often stills or
417      * clips with no audio & our preview code doesn't currently handle
418      * either of these. */
419     if( longest < 900000LL )
420     {
421         hb_log( "scan: ignoring title (too short)" );
422         goto fail;
423     }
424
425     pgcn       = longest_pgcn;
426     pgcn_end   = longest_pgcn_end;
427     pgn        = longest_pgn;;
428     title_pgcn = pgcn;
429
430
431     /* Get pgc */
432     if ( pgcn < 1 || pgcn > ifo->vts_pgcit->nr_of_pgci_srp || pgcn >= MAX_PGCN)
433     {
434         hb_error( "invalid PGC ID %d for title %d, skipping", pgcn, t );
435         goto fail;
436     }
437
438     pgc = ifo->vts_pgcit->pgci_srp[pgcn-1].pgc;
439
440     hb_log("pgc_id: %d, pgn: %d: pgc: %p", pgcn, pgn, pgc);
441     if (pgn > pgc->nr_of_programs)
442     {
443         hb_error( "invalid PGN %d for title %d, skipping", pgn, t );
444         goto fail;
445     }
446
447     /* Title start */
448     title->cell_start = pgc->program_map[pgn-1] - 1;
449     title->block_start = pgc->cell_playback[title->cell_start].first_sector;
450
451     pgc = ifo->vts_pgcit->pgci_srp[pgcn_end-1].pgc;
452
453     /* Title end */
454     title->cell_end = pgc->nr_of_cells - 1;
455     title->block_end = pgc->cell_playback[title->cell_end].last_sector;
456
457     hb_log( "scan: vts=%d, ttn=%d, cells=%d->%d, blocks=%d->%d, "
458             "%d blocks", title->vts, title->ttn, title->cell_start,
459             title->cell_end, title->block_start, title->block_end,
460             title->block_count );
461
462     /* Get duration */
463     title->duration = longest;
464     title->hours    = title->duration / 90000 / 3600;
465     title->minutes  = ( ( title->duration / 90000 ) % 3600 ) / 60;
466     title->seconds  = ( title->duration / 90000 ) % 60;
467     hb_log( "scan: duration is %02d:%02d:%02d (%"PRId64" ms)",
468             title->hours, title->minutes, title->seconds,
469             title->duration / 90 );
470
471     /* Detect languages */
472     for( i = 0; i < ifo->vtsi_mat->nr_of_vts_audio_streams; i++ )
473     {
474         hb_audio_t * audio, * audio_tmp;
475         int          audio_format, lang_code, audio_control,
476                      position, j;
477         iso639_lang_t * lang;
478         int lang_extension = 0;
479
480         hb_log( "scan: checking audio %d", i + 1 );
481
482         audio = calloc( sizeof( hb_audio_t ), 1 );
483
484         audio_format  = ifo->vtsi_mat->vts_audio_attr[i].audio_format;
485         lang_code     = ifo->vtsi_mat->vts_audio_attr[i].lang_code;
486         lang_extension = ifo->vtsi_mat->vts_audio_attr[i].code_extension;
487         audio_control =
488             ifo->vts_pgcit->pgci_srp[title_pgcn-1].pgc->audio_control[i];
489
490         if( !( audio_control & 0x8000 ) )
491         {
492             hb_log( "scan: audio channel is not active" );
493             free( audio );
494             continue;
495         }
496
497         position = ( audio_control & 0x7F00 ) >> 8;
498
499         switch( audio_format )
500         {
501             case 0x00:
502                 audio->id    = ( ( 0x80 + position ) << 8 ) | 0xbd;
503                 audio->config.in.codec = HB_ACODEC_AC3;
504                 break;
505
506             case 0x02:
507             case 0x03:
508                 audio->id    = 0xc0 + position;
509                 audio->config.in.codec = HB_ACODEC_MPGA;
510                 break;
511
512             case 0x04:
513                 audio->id    = ( ( 0xa0 + position ) << 8 ) | 0xbd;
514                 audio->config.in.codec = HB_ACODEC_LPCM;
515                 break;
516
517             case 0x06:
518                 audio->id    = ( ( 0x88 + position ) << 8 ) | 0xbd;
519                 audio->config.in.codec = HB_ACODEC_DCA;
520                 break;
521
522             default:
523                 audio->id    = 0;
524                 audio->config.in.codec = 0;
525                 hb_log( "scan: unknown audio codec (%x)",
526                         audio_format );
527                 break;
528         }
529         if( !audio->id )
530         {
531             continue;
532         }
533
534         /* Check for duplicate tracks */
535         audio_tmp = NULL;
536         for( j = 0; j < hb_list_count( title->list_audio ); j++ )
537         {
538             audio_tmp = hb_list_item( title->list_audio, j );
539             if( audio->id == audio_tmp->id )
540             {
541                 break;
542             }
543             audio_tmp = NULL;
544         }
545         if( audio_tmp )
546         {
547             hb_log( "scan: duplicate audio track" );
548             free( audio );
549             continue;
550         }
551
552         audio->config.lang.type = lang_extension;
553
554         lang = lang_for_code( ifo->vtsi_mat->vts_audio_attr[i].lang_code );
555
556         snprintf( audio->config.lang.description, sizeof( audio->config.lang.description ), "%s (%s)",
557             strlen(lang->native_name) ? lang->native_name : lang->eng_name,
558             audio->config.in.codec == HB_ACODEC_AC3 ? "AC3" : ( audio->config.in.codec ==
559                 HB_ACODEC_DCA ? "DTS" : ( audio->config.in.codec ==
560                 HB_ACODEC_MPGA ? "MPEG" : "LPCM" ) ) );
561         snprintf( audio->config.lang.simple, sizeof( audio->config.lang.simple ), "%s",
562                   strlen(lang->native_name) ? lang->native_name : lang->eng_name );
563         snprintf( audio->config.lang.iso639_2, sizeof( audio->config.lang.iso639_2 ), "%s",
564                   lang->iso639_2);
565
566         switch( lang_extension )
567         {
568         case 0:
569         case 1:
570             break;
571         case 2:
572             strcat( audio->config.lang.description, " (Visually Impaired)" );
573             break;
574         case 3:
575             strcat( audio->config.lang.description, " (Director's Commentary 1)" );
576             break;
577         case 4:
578             strcat( audio->config.lang.description, " (Director's Commentary 2)" );
579             break;
580         default:
581             break;
582         }
583
584         hb_log( "scan: id=%x, lang=%s, 3cc=%s ext=%i", audio->id,
585                 audio->config.lang.description, audio->config.lang.iso639_2,
586                 lang_extension );
587
588         audio->config.in.track = i;
589         hb_list_add( title->list_audio, audio );
590     }
591
592     memcpy( title->palette,
593             ifo->vts_pgcit->pgci_srp[title_pgcn-1].pgc->palette,
594             16 * sizeof( uint32_t ) );
595
596     /* Check for subtitles */
597     for( i = 0; i < ifo->vtsi_mat->nr_of_vts_subp_streams; i++ )
598     {
599         hb_subtitle_t * subtitle;
600         int spu_control;
601         int position;
602         iso639_lang_t * lang;
603         int lang_extension = 0;
604
605         hb_log( "scan: checking subtitle %d", i + 1 );
606
607         spu_control =
608             ifo->vts_pgcit->pgci_srp[title_pgcn-1].pgc->subp_control[i];
609
610         if( !( spu_control & 0x80000000 ) )
611         {
612             hb_log( "scan: subtitle channel is not active" );
613             continue;
614         }
615
616         if( ifo->vtsi_mat->vts_video_attr.display_aspect_ratio )
617         {
618             switch( ifo->vtsi_mat->vts_video_attr.permitted_df )
619             {
620                 case 1:
621                     position = spu_control & 0xFF;
622                     break;
623                 case 2:
624                     position = ( spu_control >> 8 ) & 0xFF;
625                     break;
626                 default:
627                     position = ( spu_control >> 16 ) & 0xFF;
628             }
629         }
630         else
631         {
632             position = ( spu_control >> 24 ) & 0x7F;
633         }
634
635         lang_extension = ifo->vtsi_mat->vts_subp_attr[i].code_extension;
636
637         lang = lang_for_code( ifo->vtsi_mat->vts_subp_attr[i].lang_code );
638
639         subtitle = calloc( sizeof( hb_subtitle_t ), 1 );
640         subtitle->track = i+1;
641         subtitle->id = ( ( 0x20 + position ) << 8 ) | 0xbd;
642         snprintf( subtitle->lang, sizeof( subtitle->lang ), "%s",
643              strlen(lang->native_name) ? lang->native_name : lang->eng_name);
644         snprintf( subtitle->iso639_2, sizeof( subtitle->iso639_2 ), "%s",
645                   lang->iso639_2);
646         subtitle->format = PICTURESUB;
647         subtitle->source = VOBSUB;
648         subtitle->config.dest   = RENDERSUB;  // By default render (burn-in) the VOBSUB.
649
650         subtitle->type = lang_extension;
651
652         switch( lang_extension )
653         {  
654         case 0:
655             break;
656         case 1:
657             break;
658         case 2:
659             strcat( subtitle->lang, " (Caption with bigger size character)");
660             break;
661         case 3: 
662             strcat( subtitle->lang, " (Caption for Children)");
663             break;
664         case 4:
665             break;
666         case 5:
667             strcat( subtitle->lang, " (Closed Caption)");
668             break;
669         case 6:
670             strcat( subtitle->lang, " (Closed Caption with bigger size character)");
671             break;
672         case 7:
673             strcat( subtitle->lang, " (Closed Caption for Children)");
674             break;
675         case 8:
676             break;
677         case 9:
678             strcat( subtitle->lang, " (Forced Caption)");
679             break;
680         case 10:
681             break;
682         case 11:
683             break;
684         case 12:
685             break;
686         case 13:
687             strcat( subtitle->lang, " (Director's Commentary)");
688             break;
689         case 14:
690             strcat( subtitle->lang, " (Director's Commentary with bigger size character)");
691             break;
692         case 15:
693             strcat( subtitle->lang, " (Director's Commentary for Children)");
694         default:
695             break;
696         }
697
698         hb_log( "scan: id=%x, lang=%s, 3cc=%s", subtitle->id,
699                 subtitle->lang, subtitle->iso639_2 );
700
701         hb_list_add( title->list_subtitle, subtitle );
702     }
703
704     /* Chapters */
705     uint32_t pgcn_map[MAX_PGCN/32];
706     PgcWalkInit( pgcn_map );
707     c = 0;
708     do
709     {
710         pgc = ifo->vts_pgcit->pgci_srp[pgcn-1].pgc;
711
712         for (i = pgn; i <= pgc->nr_of_programs; i++)
713         {
714             chapter = calloc( sizeof( hb_chapter_t ), 1 );
715
716             chapter->index = c + 1;
717             chapter->pgcn = pgcn;
718             chapter->pgn = i;
719             hb_list_add( title->list_chapter, chapter );
720             c++;
721         }
722
723         pgn = 1;
724     } while ((pgcn = NextPgcn(ifo, pgcn, pgcn_map)) != 0);
725
726     hb_log( "scan: title %d has %d chapters", t, c );
727
728     duration = 0;
729     count = hb_list_count( title->list_chapter );
730     for (i = 0; i < count; i++)
731     {
732         chapter = hb_list_item( title->list_chapter, i );
733
734         pgcn = chapter->pgcn;
735         pgn = chapter->pgn;
736         pgc = ifo->vts_pgcit->pgci_srp[pgcn-1].pgc;
737
738         /* Start cell */
739         chapter->cell_start  = pgc->program_map[pgn-1] - 1;
740         chapter->block_start = pgc->cell_playback[chapter->cell_start].first_sector;
741         // if there are no more programs in this pgc, the end cell is the
742         // last cell. Otherwise it's the cell before the start cell of the
743         // next program.
744         if ( pgn == pgc->nr_of_programs )
745         {
746             chapter->cell_end = pgc->nr_of_cells - 1;
747         }
748         else
749         {
750             chapter->cell_end = pgc->program_map[pgn] - 2;;
751         }
752         chapter->block_end = pgc->cell_playback[chapter->cell_end].last_sector;
753
754         /* Block count, duration */
755         chapter->block_count = 0;
756         chapter->duration = 0;
757
758         cell_cur = chapter->cell_start;
759         while( cell_cur <= chapter->cell_end )
760         {
761 #define cp pgc->cell_playback[cell_cur]
762             chapter->block_count += cp.last_sector + 1 - cp.first_sector;
763             chapter->duration += 90LL * dvdtime2msec( &cp.playback_time );
764 #undef cp
765             cell_cur = FindNextCell( pgc, cell_cur );
766         }
767         duration += chapter->duration;
768     }
769
770     /* The durations we get for chapters aren't precise. Scale them so
771        the total matches the title duration */
772     duration_correction = (float) title->duration / (float) duration;
773     for( i = 0; i < hb_list_count( title->list_chapter ); i++ )
774     {
775         int seconds;
776         chapter            = hb_list_item( title->list_chapter, i );
777         chapter->duration  = duration_correction * chapter->duration;
778         seconds            = ( chapter->duration + 45000 ) / 90000;
779         chapter->hours     = seconds / 3600;
780         chapter->minutes   = ( seconds % 3600 ) / 60;
781         chapter->seconds   = seconds % 60;
782
783         hb_log( "scan: chap %d c=%d->%d, b=%d->%d (%d), %"PRId64" ms",
784                 chapter->index, chapter->cell_start, chapter->cell_end,
785                 chapter->block_start, chapter->block_end,
786                 chapter->block_count, chapter->duration / 90 );
787     }
788
789     /* Get aspect. We don't get width/height/rate infos here as
790        they tend to be wrong */
791     switch( ifo->vtsi_mat->vts_video_attr.display_aspect_ratio )
792     {
793         case 0:
794             title->container_aspect = 4. / 3.;
795             break;
796         case 3:
797             title->container_aspect = 16. / 9.;
798             break;
799         default:
800             hb_log( "scan: unknown aspect" );
801             goto fail;
802     }
803
804     hb_log( "scan: aspect = %g", title->aspect );
805
806     /* This title is ok so far */
807     goto cleanup;
808
809 fail:
810     hb_list_close( &title->list_audio );
811     free( title );
812     title = NULL;
813
814 cleanup:
815     if( ifo ) ifoClose( ifo );
816
817     return title;
818 }
819
820 /***********************************************************************
821  * hb_dvdnav_start
822  ***********************************************************************
823  * Title and chapter start at 1
824  **********************************************************************/
825 static int hb_dvdnav_start( hb_dvd_t * e, hb_title_t *title, int c )
826 {
827     hb_dvdnav_t * d = &(e->dvdnav);
828     int t = title->index;
829     hb_chapter_t *chapter;
830     dvdnav_status_t result;
831
832     d->title_block_count = title->block_count;
833     d->list_chapter = title->list_chapter;
834
835     if ( d->stopped && !hb_dvdnav_reset(d) )
836     {
837         return 0;
838     }
839     chapter = hb_list_item( title->list_chapter, c - 1);
840     if (chapter != NULL)
841         result = dvdnav_program_play(d->dvdnav, t, chapter->pgcn, chapter->pgn);
842     else
843         result = dvdnav_part_play(d->dvdnav, t, 1);
844     if (result != DVDNAV_STATUS_OK)
845     {
846         hb_error( "dvd: dvdnav_*_play failed - %s", 
847                   dvdnav_err_to_string(d->dvdnav) );
848         return 0;
849     }
850     d->title = t;
851     d->stopped = 0;
852     d->chapter = 0;
853     return 1;
854 }
855
856 /***********************************************************************
857  * hb_dvdnav_stop
858  ***********************************************************************
859  *
860  **********************************************************************/
861 static void hb_dvdnav_stop( hb_dvd_t * e )
862 {
863 }
864
865 /***********************************************************************
866  * hb_dvdnav_seek
867  ***********************************************************************
868  *
869  **********************************************************************/
870 static int hb_dvdnav_seek( hb_dvd_t * e, float f )
871 {
872     hb_dvdnav_t * d = &(e->dvdnav);
873     uint64_t sector = f * d->title_block_count;
874     int result, event, len;
875     uint8_t buf[HB_DVD_READ_BUFFER_SIZE];
876     int done = 0, ii;
877
878     if (d->stopped)
879     {
880         return 0;
881     }
882
883     // XXX the current version of libdvdnav can't seek outside the current
884     // PGC. Check if the place we're seeking to is in a different
885     // PGC. Position there & adjust the offset if so.
886     uint64_t pgc_offset = 0;
887     uint64_t chap_offset = 0;
888     hb_chapter_t *pgc_change = hb_list_item(d->list_chapter, 0 );
889     for ( ii = 0; ii < hb_list_count( d->list_chapter ); ++ii )
890     {
891         hb_chapter_t *chapter = hb_list_item( d->list_chapter, ii );
892         uint64_t chap_len = chapter->block_end - chapter->block_start + 1;
893
894         if ( chapter->pgcn != pgc_change->pgcn )
895         {
896             // this chapter's in a different pgc from the previous - note the
897             // change so we can make sector offset's be pgc relative.
898             pgc_offset = chap_offset;
899             pgc_change = chapter;
900         }
901         if ( chap_offset <= sector && sector < chap_offset + chap_len )
902         {
903             // this chapter contains the sector we want - see if it's in a
904             // different pgc than the one we're currently in.
905             int32_t title, pgcn, pgn;
906             if (dvdnav_current_title_program( d->dvdnav, &title, &pgcn, &pgn ) != DVDNAV_STATUS_OK)
907                 hb_log("dvdnav cur pgcn err: %s", dvdnav_err_to_string(d->dvdnav));
908             if ( d->title != title || chapter->pgcn != pgcn )
909             {
910                 // this chapter is in a different pgc - switch to it.
911                 if (dvdnav_program_play(d->dvdnav, d->title, chapter->pgcn, chapter->pgn) != DVDNAV_STATUS_OK)
912                     hb_log("dvdnav prog play err: %s", dvdnav_err_to_string(d->dvdnav));
913             }
914             // seek sectors are pgc-relative so remove the pgc start sector.
915             sector -= pgc_offset;
916             break;
917         }
918         chap_offset += chap_len;
919     }
920
921     // dvdnav will not let you seek or poll current position
922     // till it reaches a certain point in parsing.  so we
923     // have to get blocks until we reach a cell
924     // Put an arbitrary limit of 100 blocks on how long we search
925     for (ii = 0; ii < 100 && !done; ii++)
926     {
927         result = dvdnav_get_next_block( d->dvdnav, buf, &event, &len );
928         if ( result == DVDNAV_STATUS_ERR )
929         {
930             hb_error("dvdnav: Read Error, %s", dvdnav_err_to_string(d->dvdnav));
931             return 0;
932         }
933         switch ( event )
934         {
935         case DVDNAV_BLOCK_OK:
936         case DVDNAV_CELL_CHANGE:
937             done = 1;
938             break;
939
940         case DVDNAV_STILL_FRAME:
941             dvdnav_still_skip( d->dvdnav );
942             break;
943
944         case DVDNAV_WAIT:
945             dvdnav_wait_skip( d->dvdnav );
946             break;
947
948         case DVDNAV_STOP:
949             hb_log("dvdnav: stop encountered during seek");
950             d->stopped = 1;
951             return 0;
952
953         case DVDNAV_HOP_CHANNEL:
954         case DVDNAV_NAV_PACKET:
955         case DVDNAV_VTS_CHANGE:
956         case DVDNAV_HIGHLIGHT:
957         case DVDNAV_AUDIO_STREAM_CHANGE:
958         case DVDNAV_SPU_STREAM_CHANGE:
959         case DVDNAV_SPU_CLUT_CHANGE:
960         case DVDNAV_NOP:
961         default:
962             break;
963         }
964     }
965
966     if (dvdnav_sector_search(d->dvdnav, sector, SEEK_SET) != DVDNAV_STATUS_OK)
967     {
968         hb_error( "dvd: dvdnav_sector_search failed - %s", 
969                   dvdnav_err_to_string(d->dvdnav) );
970         return 0;
971     }
972     return 1;
973 }
974
975 /***********************************************************************
976  * hb_dvdnav_read
977  ***********************************************************************
978  *
979  **********************************************************************/
980 static int hb_dvdnav_read( hb_dvd_t * e, hb_buffer_t * b )
981 {
982     hb_dvdnav_t * d = &(e->dvdnav);
983     int result, event, len;
984     int chapter = 0;
985     int error_count = 0;
986
987     while ( 1 )
988     {
989         if (d->stopped)
990         {
991             return 0;
992         }
993         result = dvdnav_get_next_block( d->dvdnav, b->data, &event, &len );
994         if ( result == DVDNAV_STATUS_ERR )
995         {
996             hb_error("dvdnav: Read Error, %s", dvdnav_err_to_string(d->dvdnav));
997             if (dvdnav_sector_search(d->dvdnav, 1, SEEK_CUR) != DVDNAV_STATUS_OK)
998             {
999                 hb_error( "dvd: dvdnav_sector_search failed - %s",
1000                         dvdnav_err_to_string(d->dvdnav) );
1001                 return 0;
1002             }
1003             error_count++;
1004             if (error_count > 10)
1005             {
1006                 hb_error("dvdnav: Error, too many consecutive read errors");
1007                 return 0;
1008             }
1009             continue;
1010         }
1011         switch ( event )
1012         {
1013         case DVDNAV_BLOCK_OK:
1014             // We have received a regular block of the currently playing
1015             // MPEG stream.
1016
1017             // The muxers expect to only get chapter 2 and above
1018             // They write chapter 1 when chapter 2 is detected.
1019             if (chapter > 1)
1020                 b->new_chap = chapter;
1021             chapter = 0;
1022             error_count = 0;
1023             return 1;
1024
1025         case DVDNAV_NOP:
1026             /*
1027             * Nothing to do here. 
1028             */
1029             break;
1030
1031         case DVDNAV_STILL_FRAME:
1032             /*
1033             * We have reached a still frame. A real player application
1034             * would wait the amount of time specified by the still's
1035             * length while still handling user input to make menus and
1036             * other interactive stills work. A length of 0xff means an
1037             * indefinite still which has to be skipped indirectly by some 
1038             * user interaction. 
1039             */
1040             dvdnav_still_skip( d->dvdnav );
1041             break;
1042
1043         case DVDNAV_WAIT:
1044             /*
1045             * We have reached a point in DVD playback, where timing is
1046             * critical. Player application with internal fifos can
1047             * introduce state inconsistencies, because libdvdnav is
1048             * always the fifo's length ahead in the stream compared to
1049             * what the application sees. Such applications should wait
1050             * until their fifos are empty when they receive this type of
1051             * event. 
1052             */
1053             dvdnav_wait_skip( d->dvdnav );
1054             break;
1055
1056         case DVDNAV_SPU_CLUT_CHANGE:
1057             /*
1058             * Player applications should pass the new colour lookup table 
1059             * to their SPU decoder 
1060             */
1061             break;
1062
1063         case DVDNAV_SPU_STREAM_CHANGE:
1064             /*
1065             * Player applications should inform their SPU decoder to
1066             * switch channels 
1067             */
1068             break;
1069
1070         case DVDNAV_AUDIO_STREAM_CHANGE:
1071             /*
1072             * Player applications should inform their audio decoder to
1073             * switch channels 
1074             */
1075             break;
1076
1077         case DVDNAV_HIGHLIGHT:
1078             /*
1079             * Player applications should inform their overlay engine to
1080             * highlight the given button 
1081             */
1082             break;
1083
1084         case DVDNAV_VTS_CHANGE:
1085             /*
1086             * Some status information like video aspect and video scale
1087             * permissions do not change inside a VTS. Therefore this
1088             * event can be used to query such information only when
1089             * necessary and update the decoding/displaying accordingly. 
1090             */
1091             break;
1092
1093         case DVDNAV_CELL_CHANGE:
1094             /*
1095             * Some status information like the current Title and Part
1096             * numbers do not change inside a cell. Therefore this event
1097             * can be used to query such information only when necessary
1098             * and update the decoding/displaying accordingly. 
1099             */
1100             {
1101                 int tt = 0, pgcn = 0, pgn = 0, c;
1102
1103                 dvdnav_current_title_program(d->dvdnav, &tt, &pgcn, &pgn);
1104                 if (tt != d->title)
1105                 {
1106                     // Transition to another title signals that we are done.
1107                     return 0;
1108                 }
1109                 c = FindChapterIndex(d->list_chapter, pgcn, pgn);
1110                 if (c != d->chapter)
1111                 {
1112                     if (c < d->chapter)
1113                     {
1114                         // Some titles end with a 'link' back to the beginning so
1115                         // a transition to an earlier chapter means we're done.
1116                         return 0;
1117                     }
1118                     chapter = d->chapter = c;
1119                 }
1120             }
1121             break;
1122
1123         case DVDNAV_NAV_PACKET:
1124             /*
1125             * A NAV packet provides PTS discontinuity information, angle
1126             * linking information and button definitions for DVD menus.
1127             * Angles are handled completely inside libdvdnav. For the
1128             * menus to work, the NAV packet information has to be passed
1129             * to the overlay engine of the player so that it knows the
1130             * dimensions of the button areas. 
1131             */
1132
1133             // mpegdemux expects to get these.  I don't think it does
1134             // anything useful with them however.
1135
1136             // The muxers expect to only get chapter 2 and above
1137             // They write chapter 1 when chapter 2 is detected.
1138             if (chapter > 1)
1139                 b->new_chap = chapter;
1140             chapter = 0;
1141             return 1;
1142
1143             break;
1144
1145         case DVDNAV_HOP_CHANNEL:
1146             /*
1147             * This event is issued whenever a non-seamless operation has
1148             * been executed. Applications with fifos should drop the
1149             * fifos content to speed up responsiveness. 
1150             */
1151             break;
1152
1153         case DVDNAV_STOP:
1154             /*
1155             * Playback should end here. 
1156             */
1157             d->stopped = 1;
1158             return 0;
1159
1160         default:
1161             break;
1162         }
1163     }
1164     return 0;
1165 }
1166
1167 /***********************************************************************
1168  * hb_dvdnav_chapter
1169  ***********************************************************************
1170  * Returns in which chapter the next block to be read is.
1171  * Chapter numbers start at 1.
1172  **********************************************************************/
1173 static int hb_dvdnav_chapter( hb_dvd_t * e )
1174 {
1175     hb_dvdnav_t * d = &(e->dvdnav);
1176     int32_t t, pgcn, pgn;
1177     int32_t c;
1178
1179     if (dvdnav_current_title_program(d->dvdnav, &t, &pgcn, &pgn) != DVDNAV_STATUS_OK)
1180     {
1181         return -1;
1182     }
1183     c = FindChapterIndex( d->list_chapter, pgcn, pgn );
1184     return c;
1185 }
1186
1187 /***********************************************************************
1188  * hb_dvdnav_close
1189  ***********************************************************************
1190  * Closes and frees everything
1191  **********************************************************************/
1192 static void hb_dvdnav_close( hb_dvd_t ** _d )
1193 {
1194     hb_dvdnav_t * d = &((*_d)->dvdnav);
1195
1196     if( d->dvdnav ) dvdnav_close( d->dvdnav );
1197     if( d->vmg ) ifoClose( d->vmg );
1198     if( d->reader ) DVDClose( d->reader );
1199
1200     free( d );
1201     *_d = NULL;
1202 }
1203
1204 /***********************************************************************
1205  * hb_dvdnav_angle_count
1206  ***********************************************************************
1207  * Returns the number of angles supported.
1208  **********************************************************************/
1209 static int hb_dvdnav_angle_count( hb_dvd_t * e )
1210 {
1211     hb_dvdnav_t * d = &(e->dvdnav);
1212     int current, angle_count;
1213
1214     if (dvdnav_get_angle_info( d->dvdnav, &current, &angle_count) != DVDNAV_STATUS_OK)
1215     {
1216         hb_log("dvdnav_get_angle_info %s", dvdnav_err_to_string(d->dvdnav));
1217         angle_count = 1;
1218     }
1219     return angle_count;
1220 }
1221
1222 /***********************************************************************
1223  * hb_dvdnav_set_angle
1224  ***********************************************************************
1225  * Sets the angle to read
1226  **********************************************************************/
1227 static void hb_dvdnav_set_angle( hb_dvd_t * e, int angle )
1228 {
1229     hb_dvdnav_t * d = &(e->dvdnav);
1230
1231     if (dvdnav_angle_change( d->dvdnav, angle) != DVDNAV_STATUS_OK)
1232     {
1233         hb_log("dvdnav_angle_change %s", dvdnav_err_to_string(d->dvdnav));
1234     }
1235 }
1236
1237 /***********************************************************************
1238  * FindChapterIndex
1239  ***********************************************************************
1240  * Assumes pgc and cell_cur are correctly set, and sets cell_next to the
1241  * cell to be read when we will be done with cell_cur.
1242  **********************************************************************/
1243 static int FindChapterIndex( hb_list_t * list, int pgcn, int pgn )
1244 {
1245     int count, ii;
1246     hb_chapter_t *chapter;
1247
1248     count = hb_list_count( list );
1249     for (ii = 0; ii < count; ii++)
1250     {
1251         chapter = hb_list_item( list, ii );
1252         if (chapter->pgcn == pgcn && chapter->pgn == pgn)
1253             return chapter->index;
1254     }
1255     return 0;
1256 }
1257
1258 /***********************************************************************
1259  * FindNextCell
1260  ***********************************************************************
1261  * Assumes pgc and cell_cur are correctly set, and sets cell_next to the
1262  * cell to be read when we will be done with cell_cur.
1263  **********************************************************************/
1264 static int FindNextCell( pgc_t *pgc, int cell_cur )
1265 {
1266     int i = 0;
1267     int cell_next;
1268
1269     if( pgc->cell_playback[cell_cur].block_type ==
1270             BLOCK_TYPE_ANGLE_BLOCK )
1271     {
1272
1273         while( pgc->cell_playback[cell_cur+i].block_mode !=
1274                    BLOCK_MODE_LAST_CELL )
1275         {
1276              i++;
1277         }
1278         cell_next = cell_cur + i + 1;
1279         hb_log( "dvd: Skipping multi-angle cells %d-%d",
1280                 cell_cur,
1281                 cell_next - 1 );
1282     }
1283     else
1284     {
1285         cell_next = cell_cur + 1;
1286     }
1287     return cell_next;
1288 }
1289
1290 /***********************************************************************
1291  * NextPgcn
1292  ***********************************************************************
1293  * Assumes pgc and cell_cur are correctly set, and sets cell_next to the
1294  * cell to be read when we will be done with cell_cur.
1295  * Since pg chains can be circularly linked (either from a read error or
1296  * deliberately) pgcn_map tracks program chains we've already seen.
1297  **********************************************************************/
1298 static int NextPgcn( ifo_handle_t *ifo, int pgcn, uint32_t pgcn_map[MAX_PGCN/32] )
1299 {
1300     int next_pgcn;
1301     pgc_t *pgc;
1302
1303     pgcn_map[pgcn >> 5] |= (1 << (pgcn & 31));
1304
1305     pgc = ifo->vts_pgcit->pgci_srp[pgcn-1].pgc;
1306     next_pgcn = pgc->next_pgc_nr;
1307     if ( next_pgcn < 1 || next_pgcn >= MAX_PGCN || next_pgcn > ifo->vts_pgcit->nr_of_pgci_srp )
1308         return 0;
1309
1310     return pgcn_map[next_pgcn >> 5] & (1 << (next_pgcn & 31))? 0 : next_pgcn;
1311 }
1312
1313 /***********************************************************************
1314  * PgcWalkInit
1315  ***********************************************************************
1316  * Pgc links can loop. I track which have been visited in a bit vector
1317  * Initialize the bit vector to empty.
1318  **********************************************************************/
1319 static void PgcWalkInit( uint32_t pgcn_map[MAX_PGCN/32] )
1320 {
1321     memset(pgcn_map, 0, sizeof(pgcn_map) );
1322 }
1323
1324 /***********************************************************************
1325  * dvdtime2msec
1326  ***********************************************************************
1327  * From lsdvd
1328  **********************************************************************/
1329 static int dvdtime2msec(dvd_time_t * dt)
1330 {
1331     double frames_per_s[4] = {-1.0, 25.00, -1.0, 29.97};
1332     double fps = frames_per_s[(dt->frame_u & 0xc0) >> 6];
1333     long   ms;
1334     ms  = (((dt->hour &   0xf0) >> 3) * 5 + (dt->hour   & 0x0f)) * 3600000;
1335     ms += (((dt->minute & 0xf0) >> 3) * 5 + (dt->minute & 0x0f)) * 60000;
1336     ms += (((dt->second & 0xf0) >> 3) * 5 + (dt->second & 0x0f)) * 1000;
1337
1338     if( fps > 0 )
1339     {
1340         ms += ((dt->frame_u & 0x30) >> 3) * 5 +
1341               (dt->frame_u & 0x0f) * 1000.0 / fps;
1342     }
1343
1344     return ms;
1345 }