OSDN Git Service

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