OSDN Git Service

WinGui:
[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     hb_chapter_t *pgc_change = hb_list_item(d->list_chapter, 0 );
887     for ( ii = 0; ii < hb_list_count( d->list_chapter ); ++ii )
888     {
889         hb_chapter_t *chapter = hb_list_item( d->list_chapter, ii );
890
891         if ( chapter->pgcn != pgc_change->pgcn )
892         {
893             // this chapter's in a different pgc from the previous - note the
894             // change so we can make sector offset's be pgc relative.
895             pgc_change = chapter;
896         }
897         if ( chapter->block_start <= sector && sector <= chapter->block_end )
898         {
899             // this chapter contains the sector we want - see if it's in a
900             // different pgc than the one we're currently in.
901             int32_t title, pgcn, pgn;
902             if (dvdnav_current_title_program( d->dvdnav, &title, &pgcn, &pgn ) != DVDNAV_STATUS_OK)
903                 hb_log("dvdnav cur pgcn err: %s", dvdnav_err_to_string(d->dvdnav));
904             if ( d->title != title || chapter->pgcn != pgcn )
905             {
906                 // this chapter is in a different pgc - switch to it.
907                 if (dvdnav_program_play(d->dvdnav, d->title, chapter->pgcn, chapter->pgn) != DVDNAV_STATUS_OK)
908                     hb_log("dvdnav prog play err: %s", dvdnav_err_to_string(d->dvdnav));
909             }
910             // seek sectors are pgc-relative so remove the pgc start sector.
911             sector -= pgc_change->block_start;
912             break;
913         }
914     }
915
916     // dvdnav will not let you seek or poll current position
917     // till it reaches a certain point in parsing.  so we
918     // have to get blocks until we reach a cell
919     // Put an arbitrary limit of 100 blocks on how long we search
920     for (ii = 0; ii < 100 && !done; ii++)
921     {
922         result = dvdnav_get_next_block( d->dvdnav, buf, &event, &len );
923         if ( result == DVDNAV_STATUS_ERR )
924         {
925             hb_error("dvdnav: Read Error, %s", dvdnav_err_to_string(d->dvdnav));
926             return 0;
927         }
928         switch ( event )
929         {
930         case DVDNAV_BLOCK_OK:
931         case DVDNAV_CELL_CHANGE:
932             done = 1;
933             break;
934
935         case DVDNAV_STILL_FRAME:
936             dvdnav_still_skip( d->dvdnav );
937             break;
938
939         case DVDNAV_WAIT:
940             dvdnav_wait_skip( d->dvdnav );
941             break;
942
943         case DVDNAV_STOP:
944             hb_log("dvdnav: stop encountered during seek");
945             d->stopped = 1;
946             return 0;
947
948         case DVDNAV_HOP_CHANNEL:
949         case DVDNAV_NAV_PACKET:
950         case DVDNAV_VTS_CHANGE:
951         case DVDNAV_HIGHLIGHT:
952         case DVDNAV_AUDIO_STREAM_CHANGE:
953         case DVDNAV_SPU_STREAM_CHANGE:
954         case DVDNAV_SPU_CLUT_CHANGE:
955         case DVDNAV_NOP:
956         default:
957             break;
958         }
959     }
960
961     if (dvdnav_sector_search(d->dvdnav, sector, SEEK_SET) != DVDNAV_STATUS_OK)
962     {
963         hb_error( "dvd: dvdnav_sector_search failed - %s", 
964                   dvdnav_err_to_string(d->dvdnav) );
965         return 0;
966     }
967     return 1;
968 }
969
970 /***********************************************************************
971  * hb_dvdnav_read
972  ***********************************************************************
973  *
974  **********************************************************************/
975 static int hb_dvdnav_read( hb_dvd_t * e, hb_buffer_t * b )
976 {
977     hb_dvdnav_t * d = &(e->dvdnav);
978     int result, event, len;
979     int chapter = 0;
980     int error_count = 0;
981
982     while ( 1 )
983     {
984         if (d->stopped)
985         {
986             return 0;
987         }
988         result = dvdnav_get_next_block( d->dvdnav, b->data, &event, &len );
989         if ( result == DVDNAV_STATUS_ERR )
990         {
991             hb_error("dvdnav: Read Error, %s", dvdnav_err_to_string(d->dvdnav));
992             if (dvdnav_sector_search(d->dvdnav, 1, SEEK_CUR) != DVDNAV_STATUS_OK)
993             {
994                 hb_error( "dvd: dvdnav_sector_search failed - %s",
995                         dvdnav_err_to_string(d->dvdnav) );
996                 return 0;
997             }
998             error_count++;
999             if (error_count > 10)
1000             {
1001                 hb_error("dvdnav: Error, too many consecutive read errors");
1002                 return 0;
1003             }
1004             continue;
1005         }
1006         error_count = 0;
1007         switch ( event )
1008         {
1009         case DVDNAV_BLOCK_OK:
1010             // We have received a regular block of the currently playing
1011             // MPEG stream.
1012
1013             // The muxers expect to only get chapter 2 and above
1014             // They write chapter 1 when chapter 2 is detected.
1015             if (chapter > 1)
1016                 b->new_chap = chapter;
1017             chapter = 0;
1018             return 1;
1019
1020         case DVDNAV_NOP:
1021             /*
1022             * Nothing to do here. 
1023             */
1024             break;
1025
1026         case DVDNAV_STILL_FRAME:
1027             /*
1028             * We have reached a still frame. A real player application
1029             * would wait the amount of time specified by the still's
1030             * length while still handling user input to make menus and
1031             * other interactive stills work. A length of 0xff means an
1032             * indefinite still which has to be skipped indirectly by some 
1033             * user interaction. 
1034             */
1035             dvdnav_still_skip( d->dvdnav );
1036             break;
1037
1038         case DVDNAV_WAIT:
1039             /*
1040             * We have reached a point in DVD playback, where timing is
1041             * critical. Player application with internal fifos can
1042             * introduce state inconsistencies, because libdvdnav is
1043             * always the fifo's length ahead in the stream compared to
1044             * what the application sees. Such applications should wait
1045             * until their fifos are empty when they receive this type of
1046             * event. 
1047             */
1048             dvdnav_wait_skip( d->dvdnav );
1049             break;
1050
1051         case DVDNAV_SPU_CLUT_CHANGE:
1052             /*
1053             * Player applications should pass the new colour lookup table 
1054             * to their SPU decoder 
1055             */
1056             break;
1057
1058         case DVDNAV_SPU_STREAM_CHANGE:
1059             /*
1060             * Player applications should inform their SPU decoder to
1061             * switch channels 
1062             */
1063             break;
1064
1065         case DVDNAV_AUDIO_STREAM_CHANGE:
1066             /*
1067             * Player applications should inform their audio decoder to
1068             * switch channels 
1069             */
1070             break;
1071
1072         case DVDNAV_HIGHLIGHT:
1073             /*
1074             * Player applications should inform their overlay engine to
1075             * highlight the given button 
1076             */
1077             break;
1078
1079         case DVDNAV_VTS_CHANGE:
1080             /*
1081             * Some status information like video aspect and video scale
1082             * permissions do not change inside a VTS. Therefore this
1083             * event can be used to query such information only when
1084             * necessary and update the decoding/displaying accordingly. 
1085             */
1086             break;
1087
1088         case DVDNAV_CELL_CHANGE:
1089             /*
1090             * Some status information like the current Title and Part
1091             * numbers do not change inside a cell. Therefore this event
1092             * can be used to query such information only when necessary
1093             * and update the decoding/displaying accordingly. 
1094             */
1095             {
1096                 int tt = 0, pgcn = 0, pgn = 0, c;
1097
1098                 dvdnav_current_title_program(d->dvdnav, &tt, &pgcn, &pgn);
1099                 if (tt != d->title)
1100                 {
1101                     // Transition to another title signals that we are done.
1102                     return 0;
1103                 }
1104                 c = FindChapterIndex(d->list_chapter, pgcn, pgn);
1105                 if (c != d->chapter)
1106                 {
1107                     if (c < d->chapter)
1108                     {
1109                         // Some titles end with a 'link' back to the beginning so
1110                         // a transition to an earlier chapter means we're done.
1111                         return 0;
1112                     }
1113                     chapter = d->chapter = c;
1114                 }
1115             }
1116             break;
1117
1118         case DVDNAV_NAV_PACKET:
1119             /*
1120             * A NAV packet provides PTS discontinuity information, angle
1121             * linking information and button definitions for DVD menus.
1122             * Angles are handled completely inside libdvdnav. For the
1123             * menus to work, the NAV packet information has to be passed
1124             * to the overlay engine of the player so that it knows the
1125             * dimensions of the button areas. 
1126             */
1127
1128             // mpegdemux expects to get these.  I don't think it does
1129             // anything useful with them however.
1130
1131             // The muxers expect to only get chapter 2 and above
1132             // They write chapter 1 when chapter 2 is detected.
1133             if (chapter > 1)
1134                 b->new_chap = chapter;
1135             chapter = 0;
1136             return 1;
1137
1138             break;
1139
1140         case DVDNAV_HOP_CHANNEL:
1141             /*
1142             * This event is issued whenever a non-seamless operation has
1143             * been executed. Applications with fifos should drop the
1144             * fifos content to speed up responsiveness. 
1145             */
1146             break;
1147
1148         case DVDNAV_STOP:
1149             /*
1150             * Playback should end here. 
1151             */
1152             d->stopped = 1;
1153             return 0;
1154
1155         default:
1156             break;
1157         }
1158     }
1159     return 0;
1160 }
1161
1162 /***********************************************************************
1163  * hb_dvdnav_chapter
1164  ***********************************************************************
1165  * Returns in which chapter the next block to be read is.
1166  * Chapter numbers start at 1.
1167  **********************************************************************/
1168 static int hb_dvdnav_chapter( hb_dvd_t * e )
1169 {
1170     hb_dvdnav_t * d = &(e->dvdnav);
1171     int32_t t, pgcn, pgn;
1172     int32_t c;
1173
1174     if (dvdnav_current_title_program(d->dvdnav, &t, &pgcn, &pgn) != DVDNAV_STATUS_OK)
1175     {
1176         return -1;
1177     }
1178     c = FindChapterIndex( d->list_chapter, pgcn, pgn );
1179     return c;
1180 }
1181
1182 /***********************************************************************
1183  * hb_dvdnav_close
1184  ***********************************************************************
1185  * Closes and frees everything
1186  **********************************************************************/
1187 static void hb_dvdnav_close( hb_dvd_t ** _d )
1188 {
1189     hb_dvdnav_t * d = &((*_d)->dvdnav);
1190
1191     if( d->dvdnav ) dvdnav_close( d->dvdnav );
1192     if( d->vmg ) ifoClose( d->vmg );
1193     if( d->reader ) DVDClose( d->reader );
1194
1195     free( d );
1196     *_d = NULL;
1197 }
1198
1199 /***********************************************************************
1200  * hb_dvdnav_angle_count
1201  ***********************************************************************
1202  * Returns the number of angles supported.
1203  **********************************************************************/
1204 static int hb_dvdnav_angle_count( hb_dvd_t * e )
1205 {
1206     hb_dvdnav_t * d = &(e->dvdnav);
1207     int current, angle_count;
1208
1209     if (dvdnav_get_angle_info( d->dvdnav, &current, &angle_count) != DVDNAV_STATUS_OK)
1210     {
1211         hb_log("dvdnav_get_angle_info %s", dvdnav_err_to_string(d->dvdnav));
1212         angle_count = 1;
1213     }
1214     return angle_count;
1215 }
1216
1217 /***********************************************************************
1218  * hb_dvdnav_set_angle
1219  ***********************************************************************
1220  * Sets the angle to read
1221  **********************************************************************/
1222 static void hb_dvdnav_set_angle( hb_dvd_t * e, int angle )
1223 {
1224     hb_dvdnav_t * d = &(e->dvdnav);
1225
1226     if (dvdnav_angle_change( d->dvdnav, angle) != DVDNAV_STATUS_OK)
1227     {
1228         hb_log("dvdnav_angle_change %s", dvdnav_err_to_string(d->dvdnav));
1229     }
1230 }
1231
1232 /***********************************************************************
1233  * FindChapterIndex
1234  ***********************************************************************
1235  * Assumes pgc and cell_cur are correctly set, and sets cell_next to the
1236  * cell to be read when we will be done with cell_cur.
1237  **********************************************************************/
1238 static int FindChapterIndex( hb_list_t * list, int pgcn, int pgn )
1239 {
1240     int count, ii;
1241     hb_chapter_t *chapter;
1242
1243     count = hb_list_count( list );
1244     for (ii = 0; ii < count; ii++)
1245     {
1246         chapter = hb_list_item( list, ii );
1247         if (chapter->pgcn == pgcn && chapter->pgn == pgn)
1248             return chapter->index;
1249     }
1250     return 0;
1251 }
1252
1253 /***********************************************************************
1254  * FindNextCell
1255  ***********************************************************************
1256  * Assumes pgc and cell_cur are correctly set, and sets cell_next to the
1257  * cell to be read when we will be done with cell_cur.
1258  **********************************************************************/
1259 static int FindNextCell( pgc_t *pgc, int cell_cur )
1260 {
1261     int i = 0;
1262     int cell_next;
1263
1264     if( pgc->cell_playback[cell_cur].block_type ==
1265             BLOCK_TYPE_ANGLE_BLOCK )
1266     {
1267
1268         while( pgc->cell_playback[cell_cur+i].block_mode !=
1269                    BLOCK_MODE_LAST_CELL )
1270         {
1271              i++;
1272         }
1273         cell_next = cell_cur + i + 1;
1274         hb_log( "dvd: Skipping multi-angle cells %d-%d",
1275                 cell_cur,
1276                 cell_next - 1 );
1277     }
1278     else
1279     {
1280         cell_next = cell_cur + 1;
1281     }
1282     return cell_next;
1283 }
1284
1285 /***********************************************************************
1286  * NextPgcn
1287  ***********************************************************************
1288  * Assumes pgc and cell_cur are correctly set, and sets cell_next to the
1289  * cell to be read when we will be done with cell_cur.
1290  * Since pg chains can be circularly linked (either from a read error or
1291  * deliberately) pgcn_map tracks program chains we've already seen.
1292  **********************************************************************/
1293 static int NextPgcn( ifo_handle_t *ifo, int pgcn, uint32_t pgcn_map[MAX_PGCN/32] )
1294 {
1295     int next_pgcn;
1296     pgc_t *pgc;
1297
1298     pgcn_map[pgcn >> 5] |= (1 << (pgcn & 31));
1299
1300     pgc = ifo->vts_pgcit->pgci_srp[pgcn-1].pgc;
1301     next_pgcn = pgc->next_pgc_nr;
1302     if ( next_pgcn < 1 || next_pgcn >= MAX_PGCN || next_pgcn > ifo->vts_pgcit->nr_of_pgci_srp )
1303         return 0;
1304
1305     return pgcn_map[next_pgcn >> 5] & (1 << (next_pgcn & 31))? 0 : next_pgcn;
1306 }
1307
1308 /***********************************************************************
1309  * PgcWalkInit
1310  ***********************************************************************
1311  * Pgc links can loop. I track which have been visited in a bit vector
1312  * Initialize the bit vector to empty.
1313  **********************************************************************/
1314 static void PgcWalkInit( uint32_t pgcn_map[MAX_PGCN/32] )
1315 {
1316     memset(pgcn_map, 0, sizeof(pgcn_map) );
1317 }
1318
1319 /***********************************************************************
1320  * dvdtime2msec
1321  ***********************************************************************
1322  * From lsdvd
1323  **********************************************************************/
1324 static int dvdtime2msec(dvd_time_t * dt)
1325 {
1326     double frames_per_s[4] = {-1.0, 25.00, -1.0, 29.97};
1327     double fps = frames_per_s[(dt->frame_u & 0xc0) >> 6];
1328     long   ms;
1329     ms  = (((dt->hour &   0xf0) >> 3) * 5 + (dt->hour   & 0x0f)) * 3600000;
1330     ms += (((dt->minute & 0xf0) >> 3) * 5 + (dt->minute & 0x0f)) * 60000;
1331     ms += (((dt->second & 0xf0) >> 3) * 5 + (dt->second & 0x0f)) * 1000;
1332
1333     if( fps > 0 )
1334     {
1335         ms += ((dt->frame_u & 0x30) >> 3) * 5 +
1336               (dt->frame_u & 0x0f) * 1000.0 / fps;
1337     }
1338
1339     return ms;
1340 }