OSDN Git Service

add dvd main feature title detection
[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 * d, int angle );
30 static int           hb_dvdnav_main_feature( hb_dvd_t * d, hb_list_t * list_title );
31
32 hb_dvd_func_t hb_dvdnav_func =
33 {
34     hb_dvdnav_init,
35     hb_dvdnav_close,
36     hb_dvdnav_name,
37     hb_dvdnav_title_count,
38     hb_dvdnav_title_scan,
39     hb_dvdnav_start,
40     hb_dvdnav_stop,
41     hb_dvdnav_seek,
42     hb_dvdnav_read,
43     hb_dvdnav_chapter,
44     hb_dvdnav_angle_count,
45     hb_dvdnav_set_angle,
46     hb_dvdnav_main_feature
47 };
48
49 // there can be at most 999 PGCs per title. round that up to the nearest
50 // power of two.
51 #define MAX_PGCN 1024
52
53 /***********************************************************************
54  * Local prototypes
55  **********************************************************************/
56 static void PgcWalkInit( uint32_t pgcn_map[MAX_PGCN/32] );
57 static int FindChapterIndex( hb_list_t * list, int pgcn, int pgn );
58 static int NextPgcn( ifo_handle_t *ifo, int pgcn, uint32_t pgcn_map[MAX_PGCN/32] );
59 static int FindNextCell( pgc_t *pgc, int cell_cur );
60 static int dvdtime2msec( dvd_time_t * );
61
62 hb_dvd_func_t * hb_dvdnav_methods( void )
63 {
64     return &hb_dvdnav_func;
65 }
66
67 static char * hb_dvdnav_name( char * path )
68 {
69     static char name[1024];
70     unsigned char unused[1024];
71     dvd_reader_t * reader;
72
73     reader = DVDOpen( path );
74     if( !reader )
75     {
76         return NULL;
77     }
78
79     if( DVDUDFVolumeInfo( reader, name, sizeof( name ),
80                           unused, sizeof( unused ) ) )
81     {
82         DVDClose( reader );
83         return NULL;
84     }
85
86     DVDClose( reader );
87     return name;
88 }
89
90 /***********************************************************************
91  * hb_dvdnav_reset
92  ***********************************************************************
93  * Once dvdnav has entered the 'stopped' state, it can not be revived
94  * dvdnav_reset doesn't work because it doesn't remember the path
95  * So this function re-opens dvdnav
96  **********************************************************************/
97 static int hb_dvdnav_reset( hb_dvdnav_t * d )
98 {
99     if ( d->dvdnav ) 
100         dvdnav_close( d->dvdnav );
101
102     /* Open device */
103     if( dvdnav_open(&d->dvdnav, d->path) != DVDNAV_STATUS_OK )
104     {
105         /*
106          * Not an error, may be a stream - which we'll try in a moment.
107          */
108         hb_log( "dvd: not a dvd - trying as a stream/file instead" );
109         goto fail;
110     }
111
112     if (dvdnav_set_readahead_flag(d->dvdnav, DVD_READ_CACHE) !=
113         DVDNAV_STATUS_OK)
114     {
115         hb_error("Error: dvdnav_set_readahead_flag: %s\n",
116                  dvdnav_err_to_string(d->dvdnav));
117         goto fail;
118     }
119
120     /*
121      ** set the PGC positioning flag to have position information
122      ** relatively to the whole feature instead of just relatively to the
123      ** current chapter 
124      **/
125     if (dvdnav_set_PGC_positioning_flag(d->dvdnav, 1) != DVDNAV_STATUS_OK)
126     {
127         hb_error("Error: dvdnav_set_PGC_positioning_flag: %s\n",
128                  dvdnav_err_to_string(d->dvdnav));
129         goto fail;
130     }
131     return 1;
132
133 fail:
134     if( d->dvdnav ) dvdnav_close( d->dvdnav );
135     return 0;
136 }
137
138 /***********************************************************************
139  * hb_dvdnav_init
140  ***********************************************************************
141  *
142  **********************************************************************/
143 static hb_dvd_t * hb_dvdnav_init( char * path )
144 {
145     hb_dvd_t * e;
146     hb_dvdnav_t * d;
147     int region_mask;
148
149     e = calloc( sizeof( hb_dvd_t ), 1 );
150     d = &(e->dvdnav);
151
152         /* Log DVD drive region code */
153     if ( hb_dvd_region( path, &region_mask ) == 0 )
154     {
155         hb_log( "dvd: Region mask 0x%02x", region_mask );
156         if ( region_mask == 0xFF )
157         {
158             hb_log( "dvd: Warning, DVD device has no region set" );
159         }
160     }
161
162     /* Open device */
163     if( dvdnav_open(&d->dvdnav, path) != DVDNAV_STATUS_OK )
164     {
165         /*
166          * Not an error, may be a stream - which we'll try in a moment.
167          */
168         hb_log( "dvd: not a dvd - trying as a stream/file instead" );
169         goto fail;
170     }
171
172     if (dvdnav_set_readahead_flag(d->dvdnav, DVD_READ_CACHE) !=
173         DVDNAV_STATUS_OK)
174     {
175         hb_error("Error: dvdnav_set_readahead_flag: %s\n",
176                  dvdnav_err_to_string(d->dvdnav));
177         goto fail;
178     }
179
180     /*
181      ** set the PGC positioning flag to have position information
182      ** relatively to the whole feature instead of just relatively to the
183      ** current chapter 
184      **/
185     if (dvdnav_set_PGC_positioning_flag(d->dvdnav, 1) != DVDNAV_STATUS_OK)
186     {
187         hb_error("Error: dvdnav_set_PGC_positioning_flag: %s\n",
188                  dvdnav_err_to_string(d->dvdnav));
189         goto fail;
190     }
191
192     /* Open device */
193     if( !( d->reader = DVDOpen( path ) ) )
194     {
195         /*
196          * Not an error, may be a stream - which we'll try in a moment.
197          */
198         hb_log( "dvd: not a dvd - trying as a stream/file instead" );
199         goto fail;
200     }
201
202     /* Open main IFO */
203     if( !( d->vmg = ifoOpen( d->reader, 0 ) ) )
204     {
205         hb_error( "dvd: ifoOpen failed" );
206         goto fail;
207     }
208
209     d->path = strdup( path );
210
211     return e;
212
213 fail:
214     if( d->dvdnav ) dvdnav_close( d->dvdnav );
215     if( d->vmg )    ifoClose( d->vmg );
216     if( d->reader ) DVDClose( d->reader );
217     free( e );
218     return NULL;
219 }
220
221 /***********************************************************************
222  * hb_dvdnav_title_count
223  **********************************************************************/
224 static int hb_dvdnav_title_count( hb_dvd_t * e )
225 {
226     int titles = 0;
227     hb_dvdnav_t * d = &(e->dvdnav);
228
229     dvdnav_get_number_of_titles(d->dvdnav, &titles);
230     return titles;
231 }
232
233 static uint64_t
234 PttDuration(ifo_handle_t *ifo, int ttn, int pttn, int *blocks, int *last_pgcn)
235 {
236     int            pgcn, pgn;
237     pgc_t        * pgc;
238     uint64_t       duration = 0;
239     int            cell_start, cell_end;
240     int            i;
241
242     // Initialize map of visited pgc's to prevent loops
243     uint32_t pgcn_map[MAX_PGCN/32];
244     PgcWalkInit( pgcn_map );
245     pgcn   = ifo->vts_ptt_srpt->title[ttn-1].ptt[pttn-1].pgcn;
246     pgn   = ifo->vts_ptt_srpt->title[ttn-1].ptt[pttn-1].pgn;
247     if ( pgcn < 1 || pgcn > ifo->vts_pgcit->nr_of_pgci_srp || pgcn >= MAX_PGCN)
248     {
249         hb_error( "invalid PGC ID %d, skipping", pgcn );
250         return 0;
251     }
252
253     if( pgn <= 0 || pgn > 99 )
254     {
255         hb_error( "scan: pgn %d not valid, skipping", pgn );
256         return 0;
257     }
258
259     *blocks = 0;
260     do
261     {
262         pgc = ifo->vts_pgcit->pgci_srp[pgcn-1].pgc;
263         if (!pgc)
264         {
265             hb_error( "scan: pgc not valid, skipping" );
266             break;
267         }
268         if (pgn > pgc->nr_of_programs)
269         {
270             pgn = 1;
271             continue;
272         }
273
274         duration += 90LL * dvdtime2msec( &pgc->playback_time );
275
276         cell_start = pgc->program_map[pgn-1] - 1;
277         cell_end = pgc->nr_of_cells - 1;
278         for(i = cell_start; i <= cell_end; i = FindNextCell(pgc, i))
279         {
280             *blocks += pgc->cell_playback[i].last_sector + 1 -
281                 pgc->cell_playback[i].first_sector;
282         }
283         *last_pgcn = pgcn;
284         pgn = 1;
285     } while((pgcn = NextPgcn(ifo, pgcn, pgcn_map)) != 0);
286     return duration;
287 }
288
289 /***********************************************************************
290  * hb_dvdnav_title_scan
291  **********************************************************************/
292 static hb_title_t * hb_dvdnav_title_scan( hb_dvd_t * e, int t )
293 {
294
295     hb_dvdnav_t * d = &(e->dvdnav);
296     hb_title_t   * title;
297     ifo_handle_t * ifo = NULL;
298     int            pgcn, pgn, pgcn_end, i, c;
299     int            title_pgcn;
300     pgc_t        * pgc;
301     int            cell_cur;
302     hb_chapter_t * chapter;
303     int            count;
304     uint64_t       duration, longest;
305     int            longest_pgcn, longest_pgn, longest_pgcn_end;
306     float          duration_correction;
307     const char   * name;
308
309     hb_log( "scan: scanning title %d", t );
310
311     title = hb_title_init( d->path, t );
312     title->type = HB_DVD_TYPE;
313     if (dvdnav_get_title_string(d->dvdnav, &name) == DVDNAV_STATUS_OK)
314     {
315         strncpy( title->name, name, sizeof( title->name ) );
316     }
317     else
318     {
319         char * p_cur, * p_last = d->path;
320         for( p_cur = d->path; *p_cur; p_cur++ )
321         {
322             if( p_cur[0] == '/' && p_cur[1] )
323             {
324                 p_last = &p_cur[1];
325             }
326         }
327         snprintf( title->name, sizeof( title->name ), "%s", p_last );
328     }
329
330     /* VTS which our title is in */
331     title->vts = d->vmg->tt_srpt->title[t-1].title_set_nr;
332
333     if ( !title->vts )
334     {
335         /* A VTS of 0 means the title wasn't found in the title set */
336         hb_error("Invalid VTS (title set) number: %i", title->vts);
337         goto fail;
338     }
339
340     hb_log( "scan: opening IFO for VTS %d", title->vts );
341     if( !( ifo = ifoOpen( d->reader, title->vts ) ) )
342     {
343         hb_error( "scan: ifoOpen failed" );
344         goto fail;
345     }
346
347     /* ignore titles with bogus cell addresses so we don't abort later
348      ** in libdvdread. */
349     for ( i = 0; i < ifo->vts_c_adt->nr_of_vobs; ++i)
350     {
351         if( (ifo->vts_c_adt->cell_adr_table[i].start_sector & 0xffffff ) ==
352             0xffffff )
353         {
354             hb_error( "scan: cell_adr_table[%d].start_sector invalid (0x%x) "
355                       "- skipping title", i,
356                       ifo->vts_c_adt->cell_adr_table[i].start_sector );
357             goto fail;
358         }
359         if( (ifo->vts_c_adt->cell_adr_table[i].last_sector & 0xffffff ) ==
360             0xffffff )
361         {
362             hb_error( "scan: cell_adr_table[%d].last_sector invalid (0x%x) "
363                       "- skipping title", i,
364                       ifo->vts_c_adt->cell_adr_table[i].last_sector );
365             goto fail;
366         }
367         if( ifo->vts_c_adt->cell_adr_table[i].start_sector >=
368             ifo->vts_c_adt->cell_adr_table[i].last_sector )
369         {
370             hb_error( "scan: cell_adr_table[%d].start_sector (0x%x) "
371                       "is not before last_sector (0x%x) - skipping title", i,
372                       ifo->vts_c_adt->cell_adr_table[i].start_sector,
373                       ifo->vts_c_adt->cell_adr_table[i].last_sector );
374             goto fail;
375         }
376     }
377
378     if( global_verbosity_level == 3 )
379     {
380         ifo_print( d->reader, title->vts );
381     }
382
383     /* Position of the title in the VTS */
384     title->ttn = d->vmg->tt_srpt->title[t-1].vts_ttn;
385     if ( title->ttn < 1 || title->ttn > ifo->vts_ptt_srpt->nr_of_srpts )
386     {
387         hb_error( "invalid VTS PTT offset %d for title %d, skipping", title->ttn, t );
388         goto fail;
389     }
390
391     longest = 0LL;
392     longest_pgcn = -1;
393     longest_pgn = 1;
394     longest_pgcn_end = -1;
395     pgcn_end = -1;
396     for( i = 0; i < ifo->vts_ptt_srpt->title[title->ttn-1].nr_of_ptts; i++ )
397     {
398         int blocks = 0;
399
400         duration = PttDuration(ifo, title->ttn, i+1, &blocks, &pgcn_end);
401         pgcn  = ifo->vts_ptt_srpt->title[title->ttn-1].ptt[i].pgcn;
402         pgn   = ifo->vts_ptt_srpt->title[title->ttn-1].ptt[i].pgn;
403         if( duration > longest )
404         {
405             longest_pgcn  = pgcn;
406             longest_pgn   = pgn;
407             longest_pgcn_end   = pgcn_end;
408             longest = duration;
409             title->block_count = blocks;
410         }
411         else if (pgcn == longest_pgcn && pgn < longest_pgn)
412         {
413             longest_pgn   = pgn;
414             title->block_count = blocks;
415         }
416     }
417
418     /* ignore titles under 10 seconds because they're often stills or
419      * clips with no audio & our preview code doesn't currently handle
420      * either of these. */
421     if( longest < 900000LL )
422     {
423         hb_log( "scan: ignoring title (too short)" );
424         goto fail;
425     }
426
427     pgcn       = longest_pgcn;
428     pgcn_end   = longest_pgcn_end;
429     pgn        = longest_pgn;;
430     title_pgcn = pgcn;
431
432
433     /* Get pgc */
434     if ( pgcn < 1 || pgcn > ifo->vts_pgcit->nr_of_pgci_srp || pgcn >= MAX_PGCN)
435     {
436         hb_error( "invalid PGC ID %d for title %d, skipping", pgcn, t );
437         goto fail;
438     }
439
440     pgc = ifo->vts_pgcit->pgci_srp[pgcn-1].pgc;
441
442     hb_log("pgc_id: %d, pgn: %d: pgc: %p", pgcn, pgn, pgc);
443     if (pgn > pgc->nr_of_programs)
444     {
445         hb_error( "invalid PGN %d for title %d, skipping", pgn, t );
446         goto fail;
447     }
448
449     /* Title start */
450     title->cell_start = pgc->program_map[pgn-1] - 1;
451     title->block_start = pgc->cell_playback[title->cell_start].first_sector;
452
453     pgc = ifo->vts_pgcit->pgci_srp[pgcn_end-1].pgc;
454
455     /* Title end */
456     title->cell_end = pgc->nr_of_cells - 1;
457     title->block_end = pgc->cell_playback[title->cell_end].last_sector;
458
459     hb_log( "scan: vts=%d, ttn=%d, cells=%d->%d, blocks=%d->%d, "
460             "%d blocks", title->vts, title->ttn, title->cell_start,
461             title->cell_end, title->block_start, title->block_end,
462             title->block_count );
463
464     /* Get duration */
465     title->duration = longest;
466     title->hours    = title->duration / 90000 / 3600;
467     title->minutes  = ( ( title->duration / 90000 ) % 3600 ) / 60;
468     title->seconds  = ( title->duration / 90000 ) % 60;
469     hb_log( "scan: duration is %02d:%02d:%02d (%"PRId64" ms)",
470             title->hours, title->minutes, title->seconds,
471             title->duration / 90 );
472
473     /* Detect languages */
474     for( i = 0; i < ifo->vtsi_mat->nr_of_vts_audio_streams; i++ )
475     {
476         hb_audio_t * audio, * audio_tmp;
477         int          audio_format, lang_code, audio_control,
478                      position, j;
479         iso639_lang_t * lang;
480         int lang_extension = 0;
481
482         hb_log( "scan: checking audio %d", i + 1 );
483
484         audio = calloc( sizeof( hb_audio_t ), 1 );
485
486         audio_format  = ifo->vtsi_mat->vts_audio_attr[i].audio_format;
487         lang_code     = ifo->vtsi_mat->vts_audio_attr[i].lang_code;
488         lang_extension = ifo->vtsi_mat->vts_audio_attr[i].code_extension;
489         audio_control =
490             ifo->vts_pgcit->pgci_srp[title_pgcn-1].pgc->audio_control[i];
491
492         if( !( audio_control & 0x8000 ) )
493         {
494             hb_log( "scan: audio channel is not active" );
495             free( audio );
496             continue;
497         }
498
499         position = ( audio_control & 0x7F00 ) >> 8;
500
501         switch( audio_format )
502         {
503             case 0x00:
504                 audio->id    = ( ( 0x80 + position ) << 8 ) | 0xbd;
505                 audio->config.in.codec = HB_ACODEC_AC3;
506                 break;
507
508             case 0x02:
509             case 0x03:
510                 audio->id    = 0xc0 + position;
511                 audio->config.in.codec = HB_ACODEC_MPGA;
512                 break;
513
514             case 0x04:
515                 audio->id    = ( ( 0xa0 + position ) << 8 ) | 0xbd;
516                 audio->config.in.codec = HB_ACODEC_LPCM;
517                 break;
518
519             case 0x06:
520                 audio->id    = ( ( 0x88 + position ) << 8 ) | 0xbd;
521                 audio->config.in.codec = HB_ACODEC_DCA;
522                 break;
523
524             default:
525                 audio->id    = 0;
526                 audio->config.in.codec = 0;
527                 hb_log( "scan: unknown audio codec (%x)",
528                         audio_format );
529                 break;
530         }
531         if( !audio->id )
532         {
533             continue;
534         }
535
536         /* Check for duplicate tracks */
537         audio_tmp = NULL;
538         for( j = 0; j < hb_list_count( title->list_audio ); j++ )
539         {
540             audio_tmp = hb_list_item( title->list_audio, j );
541             if( audio->id == audio_tmp->id )
542             {
543                 break;
544             }
545             audio_tmp = NULL;
546         }
547         if( audio_tmp )
548         {
549             hb_log( "scan: duplicate audio track" );
550             free( audio );
551             continue;
552         }
553
554         audio->config.lang.type = lang_extension;
555
556         lang = lang_for_code( ifo->vtsi_mat->vts_audio_attr[i].lang_code );
557
558         snprintf( audio->config.lang.description, sizeof( audio->config.lang.description ), "%s (%s)",
559             strlen(lang->native_name) ? lang->native_name : lang->eng_name,
560             audio->config.in.codec == HB_ACODEC_AC3 ? "AC3" : ( audio->config.in.codec ==
561                 HB_ACODEC_DCA ? "DTS" : ( audio->config.in.codec ==
562                 HB_ACODEC_MPGA ? "MPEG" : "LPCM" ) ) );
563         snprintf( audio->config.lang.simple, sizeof( audio->config.lang.simple ), "%s",
564                   strlen(lang->native_name) ? lang->native_name : lang->eng_name );
565         snprintf( audio->config.lang.iso639_2, sizeof( audio->config.lang.iso639_2 ), "%s",
566                   lang->iso639_2);
567
568         switch( lang_extension )
569         {
570         case 0:
571         case 1:
572             break;
573         case 2:
574             strcat( audio->config.lang.description, " (Visually Impaired)" );
575             break;
576         case 3:
577             strcat( audio->config.lang.description, " (Director's Commentary 1)" );
578             break;
579         case 4:
580             strcat( audio->config.lang.description, " (Director's Commentary 2)" );
581             break;
582         default:
583             break;
584         }
585
586         hb_log( "scan: id=%x, lang=%s, 3cc=%s ext=%i", audio->id,
587                 audio->config.lang.description, audio->config.lang.iso639_2,
588                 lang_extension );
589
590         audio->config.in.track = i;
591         hb_list_add( title->list_audio, audio );
592     }
593
594     memcpy( title->palette,
595             ifo->vts_pgcit->pgci_srp[title_pgcn-1].pgc->palette,
596             16 * sizeof( uint32_t ) );
597
598     /* Check for subtitles */
599     for( i = 0; i < ifo->vtsi_mat->nr_of_vts_subp_streams; i++ )
600     {
601         hb_subtitle_t * subtitle;
602         int spu_control;
603         int position;
604         iso639_lang_t * lang;
605         int lang_extension = 0;
606
607         hb_log( "scan: checking subtitle %d", i + 1 );
608
609         spu_control =
610             ifo->vts_pgcit->pgci_srp[title_pgcn-1].pgc->subp_control[i];
611
612         if( !( spu_control & 0x80000000 ) )
613         {
614             hb_log( "scan: subtitle channel is not active" );
615             continue;
616         }
617
618         if( ifo->vtsi_mat->vts_video_attr.display_aspect_ratio )
619         {
620             switch( ifo->vtsi_mat->vts_video_attr.permitted_df )
621             {
622                 case 1:
623                     position = spu_control & 0xFF;
624                     break;
625                 case 2:
626                     position = ( spu_control >> 8 ) & 0xFF;
627                     break;
628                 default:
629                     position = ( spu_control >> 16 ) & 0xFF;
630             }
631         }
632         else
633         {
634             position = ( spu_control >> 24 ) & 0x7F;
635         }
636
637         lang_extension = ifo->vtsi_mat->vts_subp_attr[i].code_extension;
638
639         lang = lang_for_code( ifo->vtsi_mat->vts_subp_attr[i].lang_code );
640
641         subtitle = calloc( sizeof( hb_subtitle_t ), 1 );
642         subtitle->track = i+1;
643         subtitle->id = ( ( 0x20 + position ) << 8 ) | 0xbd;
644         snprintf( subtitle->lang, sizeof( subtitle->lang ), "%s",
645              strlen(lang->native_name) ? lang->native_name : lang->eng_name);
646         snprintf( subtitle->iso639_2, sizeof( subtitle->iso639_2 ), "%s",
647                   lang->iso639_2);
648         subtitle->format = PICTURESUB;
649         subtitle->source = VOBSUB;
650         subtitle->config.dest   = RENDERSUB;  // By default render (burn-in) the VOBSUB.
651
652         subtitle->type = lang_extension;
653
654         switch( lang_extension )
655         {  
656         case 0:
657             break;
658         case 1:
659             break;
660         case 2:
661             strcat( subtitle->lang, " (Caption with bigger size character)");
662             break;
663         case 3: 
664             strcat( subtitle->lang, " (Caption for Children)");
665             break;
666         case 4:
667             break;
668         case 5:
669             strcat( subtitle->lang, " (Closed Caption)");
670             break;
671         case 6:
672             strcat( subtitle->lang, " (Closed Caption with bigger size character)");
673             break;
674         case 7:
675             strcat( subtitle->lang, " (Closed Caption for Children)");
676             break;
677         case 8:
678             break;
679         case 9:
680             strcat( subtitle->lang, " (Forced Caption)");
681             break;
682         case 10:
683             break;
684         case 11:
685             break;
686         case 12:
687             break;
688         case 13:
689             strcat( subtitle->lang, " (Director's Commentary)");
690             break;
691         case 14:
692             strcat( subtitle->lang, " (Director's Commentary with bigger size character)");
693             break;
694         case 15:
695             strcat( subtitle->lang, " (Director's Commentary for Children)");
696         default:
697             break;
698         }
699
700         hb_log( "scan: id=%x, lang=%s, 3cc=%s", subtitle->id,
701                 subtitle->lang, subtitle->iso639_2 );
702
703         hb_list_add( title->list_subtitle, subtitle );
704     }
705
706     /* Chapters */
707     uint32_t pgcn_map[MAX_PGCN/32];
708     PgcWalkInit( pgcn_map );
709     c = 0;
710     do
711     {
712         pgc = ifo->vts_pgcit->pgci_srp[pgcn-1].pgc;
713
714         for (i = pgn; i <= pgc->nr_of_programs; i++)
715         {
716             chapter = calloc( sizeof( hb_chapter_t ), 1 );
717
718             chapter->index = c + 1;
719             chapter->pgcn = pgcn;
720             chapter->pgn = i;
721             hb_list_add( title->list_chapter, chapter );
722             c++;
723         }
724
725         pgn = 1;
726     } while ((pgcn = NextPgcn(ifo, pgcn, pgcn_map)) != 0);
727
728     hb_log( "scan: title %d has %d chapters", t, c );
729
730     duration = 0;
731     count = hb_list_count( title->list_chapter );
732     for (i = 0; i < count; i++)
733     {
734         chapter = hb_list_item( title->list_chapter, i );
735
736         pgcn = chapter->pgcn;
737         pgn = chapter->pgn;
738         pgc = ifo->vts_pgcit->pgci_srp[pgcn-1].pgc;
739
740         /* Start cell */
741         chapter->cell_start  = pgc->program_map[pgn-1] - 1;
742         chapter->block_start = pgc->cell_playback[chapter->cell_start].first_sector;
743         // if there are no more programs in this pgc, the end cell is the
744         // last cell. Otherwise it's the cell before the start cell of the
745         // next program.
746         if ( pgn == pgc->nr_of_programs )
747         {
748             chapter->cell_end = pgc->nr_of_cells - 1;
749         }
750         else
751         {
752             chapter->cell_end = pgc->program_map[pgn] - 2;;
753         }
754         chapter->block_end = pgc->cell_playback[chapter->cell_end].last_sector;
755
756         /* Block count, duration */
757         chapter->block_count = 0;
758         chapter->duration = 0;
759
760         cell_cur = chapter->cell_start;
761         while( cell_cur <= chapter->cell_end )
762         {
763 #define cp pgc->cell_playback[cell_cur]
764             chapter->block_count += cp.last_sector + 1 - cp.first_sector;
765             chapter->duration += 90LL * dvdtime2msec( &cp.playback_time );
766 #undef cp
767             cell_cur = FindNextCell( pgc, cell_cur );
768         }
769         duration += chapter->duration;
770     }
771
772     /* The durations we get for chapters aren't precise. Scale them so
773        the total matches the title duration */
774     duration_correction = (float) title->duration / (float) duration;
775     for( i = 0; i < hb_list_count( title->list_chapter ); i++ )
776     {
777         int seconds;
778         chapter            = hb_list_item( title->list_chapter, i );
779         chapter->duration  = duration_correction * chapter->duration;
780         seconds            = ( chapter->duration + 45000 ) / 90000;
781         chapter->hours     = seconds / 3600;
782         chapter->minutes   = ( seconds % 3600 ) / 60;
783         chapter->seconds   = seconds % 60;
784
785         hb_log( "scan: chap %d c=%d->%d, b=%d->%d (%d), %"PRId64" ms",
786                 chapter->index, chapter->cell_start, chapter->cell_end,
787                 chapter->block_start, chapter->block_end,
788                 chapter->block_count, chapter->duration / 90 );
789     }
790
791     /* Get aspect. We don't get width/height/rate infos here as
792        they tend to be wrong */
793     switch( ifo->vtsi_mat->vts_video_attr.display_aspect_ratio )
794     {
795         case 0:
796             title->container_aspect = 4. / 3.;
797             break;
798         case 3:
799             title->container_aspect = 16. / 9.;
800             break;
801         default:
802             hb_log( "scan: unknown aspect" );
803             goto fail;
804     }
805
806     hb_log( "scan: aspect = %g", title->aspect );
807
808     /* This title is ok so far */
809     goto cleanup;
810
811 fail:
812     hb_list_close( &title->list_audio );
813     free( title );
814     title = NULL;
815
816 cleanup:
817     if( ifo ) ifoClose( ifo );
818
819     return title;
820 }
821
822 /***********************************************************************
823  * hb_dvdnav_title_scan
824  **********************************************************************/
825 static int find_title( hb_list_t * list_title, int title )
826 {
827     int ii;
828
829     for ( ii = 0; ii < hb_list_count( list_title ); ii++ )
830     {
831         hb_title_t * hbtitle = hb_list_item( list_title, ii );
832         if ( hbtitle->index == title )
833             return ii;
834     }
835     return -1;
836 }
837
838 static int try_button( dvdnav_t * dvdnav, int menu_id, int button, hb_list_t * list_title )
839 {
840     int result, event, len;
841     uint8_t buf[HB_DVD_READ_BUFFER_SIZE];
842     int ii;
843     int32_t cur_title, title, pgcn, pgn;
844     uint64_t longest_duration = 0;
845     int longest = -1;
846
847     pci_t *pci = dvdnav_get_current_nav_pci( dvdnav );
848     result = dvdnav_button_select_and_activate( dvdnav, pci, button + 1 );
849     if (result != DVDNAV_STATUS_OK)
850     {
851         hb_log("dvdnav_button_select_and_activate: %s", dvdnav_err_to_string(dvdnav));
852     }
853
854     result = dvdnav_current_title_program( dvdnav, &title, &pgcn, &pgn );
855     if (result != DVDNAV_STATUS_OK)
856         hb_log("dvdnav cur pgcn err: %s", dvdnav_err_to_string(dvdnav));
857
858     if ( title > 0 )
859     {
860         hb_title_t * hbtitle;
861         int index;
862         index = find_title( list_title, title );
863         hbtitle = hb_list_item( list_title, index );
864         if ( hbtitle != NULL )
865         {
866             if ( hbtitle->duration > longest_duration )
867             {
868                 longest_duration = hbtitle->duration;
869                 longest = title;
870             }
871         }
872         // If the duration is longer than 10min, assume
873         // this isn't garbage leading to something bigger.
874         if ( longest_duration / 90000 > 10 * 60 )
875         {
876             return longest;
877         }
878     }
879     cur_title = title;
880
881     for (ii = 0; ii < 8000; ii++)
882     {
883         result = dvdnav_get_next_block( dvdnav, buf, &event, &len );
884         if ( result == DVDNAV_STATUS_ERR )
885         {
886             hb_error("dvdnav: Read Error, %s", dvdnav_err_to_string(dvdnav));
887             return 0;
888         }
889         switch ( event )
890         {
891         case DVDNAV_BLOCK_OK:
892             break;
893
894         case DVDNAV_CELL_CHANGE:
895         {
896             result = dvdnav_current_title_program( dvdnav, &title, &pgcn, &pgn );
897             if (result != DVDNAV_STATUS_OK)
898                 hb_log("dvdnav cur pgcn err: %s", dvdnav_err_to_string(dvdnav));
899             if ( title != cur_title && title > 0 )
900             {
901                 hb_title_t * hbtitle;
902                 int index;
903                 index = find_title( list_title, title );
904                 hbtitle = hb_list_item( list_title, index );
905                 if ( hbtitle != NULL )
906                 {
907                     if ( hbtitle->duration > longest_duration )
908                     {
909                         longest_duration = hbtitle->duration;
910                         longest = title;
911                     }
912                 }
913                 // If the duration is longer than 10min, assume
914                 // this isn't garbage leading to something bigger.
915                 if ( longest_duration / 90000 > 10 * 60 )
916                 {
917                     return longest;
918                 }
919                 cur_title = title;
920             }
921             if (title > 0)
922             {
923                 result = dvdnav_next_pg_search( dvdnav );
924                 if ( result != DVDNAV_STATUS_OK )
925                 {
926                     return longest;
927                 }
928                 int next_title, next_pgcn, next_pgn;
929                 dvdnav_current_title_program( dvdnav, &next_title, &next_pgcn, &next_pgn );
930                 if (title == next_title && pgcn == next_pgcn && pgn == next_pgn)
931                 {
932                     return longest;
933                 }
934             }
935         } break;
936
937         case DVDNAV_STILL_FRAME:
938             dvdnav_still_skip( dvdnav );
939             break;
940
941         case DVDNAV_WAIT:
942             dvdnav_wait_skip( dvdnav );
943             break;
944
945         case DVDNAV_STOP:
946             hb_log("dvdnav: stop encountered during seek");
947             return 0;
948
949         case DVDNAV_HOP_CHANNEL:
950             break;
951
952         case DVDNAV_NAV_PACKET:
953         {
954         } break;
955
956         case DVDNAV_VTS_CHANGE:
957         {
958             result = dvdnav_current_title_program( dvdnav, &title, &pgcn, &pgn );
959             if (result != DVDNAV_STATUS_OK)
960                 hb_log("dvdnav cur pgcn err: %s", dvdnav_err_to_string(dvdnav));
961             if ( title != cur_title && title > 0 )
962             {
963                 hb_title_t * hbtitle;
964                 int index;
965                 index = find_title( list_title, title );
966                 hbtitle = hb_list_item( list_title, index );
967                 if ( hbtitle != NULL )
968                 {
969                     if ( hbtitle->duration > longest_duration )
970                     {
971                         longest_duration = hbtitle->duration;
972                         longest = title;
973                     }
974                 }
975                 cur_title = title;
976                 if ( longest_duration / 90000 > 10 * 60 )
977                 {
978                     return longest;
979                 }
980             }
981             if ( title > 0 )
982             {
983                 dvdnav_next_pg_search( dvdnav );
984             }
985         } break;
986
987         case DVDNAV_HIGHLIGHT:
988             break;
989
990         case DVDNAV_AUDIO_STREAM_CHANGE:
991             break;
992
993         case DVDNAV_SPU_STREAM_CHANGE:
994             break;
995
996         case DVDNAV_SPU_CLUT_CHANGE:
997             break;
998
999         case DVDNAV_NOP:
1000             break;
1001
1002         default:
1003             break;
1004         }
1005     }
1006     return longest;
1007 }
1008
1009 static int try_menu( hb_dvdnav_t * d, hb_list_t * list_title, DVDMenuID_t menu )
1010 {
1011     int result, event, len;
1012     uint8_t buf[HB_DVD_READ_BUFFER_SIZE];
1013     int ii;
1014     int32_t cur_title, title, pgcn, pgn;
1015     uint64_t longest_duration = 0;
1016     int longest = -1;
1017
1018     dvdnav_reset( d->dvdnav );
1019     result = dvdnav_title_play( d->dvdnav, 1 );
1020     if ( result == DVDNAV_STATUS_ERR )
1021     {
1022         hb_error("dvdnav: Can not set title, %s", dvdnav_err_to_string(d->dvdnav));
1023         goto done;
1024     }
1025     result = dvdnav_menu_call( d->dvdnav, menu );
1026     if ( result != DVDNAV_STATUS_OK )
1027     {
1028         hb_error("dvdnav: Can not set dvd menu, %s", dvdnav_err_to_string(d->dvdnav));
1029         goto done;
1030     }
1031
1032     result = dvdnav_current_title_program( d->dvdnav, &cur_title, &pgcn, &pgn );
1033     if (result != DVDNAV_STATUS_OK)
1034         hb_log("dvdnav cur pgcn err: %s", dvdnav_err_to_string(d->dvdnav));
1035
1036     // Hit the root menu again to see if we can force
1037     // our way to the main menu.
1038     dvdnav_next_pg_search( d->dvdnav );
1039     result = dvdnav_menu_call( d->dvdnav, menu );
1040
1041     dvdnav_next_pg_search( d->dvdnav );
1042     result = dvdnav_menu_call( d->dvdnav, menu );
1043
1044     if ( cur_title > 0 )
1045     {
1046         dvdnav_next_pg_search( d->dvdnav );
1047     }
1048
1049     for (ii = 0; ii < 5000; ii++)
1050     {
1051         result = dvdnav_get_next_block( d->dvdnav, buf, &event, &len );
1052         if ( result == DVDNAV_STATUS_ERR )
1053         {
1054             hb_error("dvdnav: Read Error, %s", dvdnav_err_to_string(d->dvdnav));
1055             goto done;
1056         }
1057         switch ( event )
1058         {
1059         case DVDNAV_BLOCK_OK:
1060             break;
1061
1062         case DVDNAV_CELL_CHANGE:
1063         {
1064             result = dvdnav_current_title_program( d->dvdnav, &title, &pgcn, &pgn );
1065             if (result != DVDNAV_STATUS_OK)
1066                 hb_log("dvdnav cur pgcn err: %s", dvdnav_err_to_string(d->dvdnav));
1067             cur_title = title;
1068             if ( title > 0 )
1069             {
1070                 dvdnav_next_pg_search( d->dvdnav );
1071             }
1072         } break;
1073
1074         case DVDNAV_STILL_FRAME:
1075             dvdnav_still_skip( d->dvdnav );
1076             break;
1077
1078         case DVDNAV_WAIT:
1079             dvdnav_wait_skip( d->dvdnav );
1080             break;
1081
1082         case DVDNAV_STOP:
1083             hb_log("dvdnav: stop encountered during seek");
1084             d->stopped = 1;
1085             goto done;
1086
1087         case DVDNAV_HOP_CHANNEL:
1088             break;
1089
1090         case DVDNAV_NAV_PACKET:
1091         {
1092             pci_t *pci = dvdnav_get_current_nav_pci( d->dvdnav );
1093             int kk;
1094             int buttons;
1095             if ( pci == NULL ) break;
1096
1097             buttons = pci->hli.hl_gi.btn_ns;
1098             if ( cur_title == 0 && buttons > 0 )
1099             {
1100                 int menu_title, menu_id;
1101                 result = dvdnav_current_title_info( d->dvdnav, &menu_title, &menu_id );
1102                 if (result != DVDNAV_STATUS_OK)
1103                     hb_log("dvdnav cur pgcn err: %s", dvdnav_err_to_string(d->dvdnav));
1104                 for (kk = 0; kk < buttons; kk++)
1105                 {
1106                     dvdnav_t *dvdnav_copy;
1107
1108                     result = dvdnav_dup( &dvdnav_copy, d->dvdnav );
1109                     if (result != DVDNAV_STATUS_OK)
1110                     {
1111                         hb_log("dvdnav dup failed: %s", dvdnav_err_to_string(d->dvdnav));
1112                         goto done;
1113                     }
1114                     title = try_button( dvdnav_copy, menu_id, kk, list_title );
1115                     dvdnav_free_dup( dvdnav_copy );
1116
1117                     if ( title >= 0 )
1118                     {
1119                         hb_title_t * hbtitle;
1120                         int index;
1121                         index = find_title( list_title, title );
1122                         hbtitle = hb_list_item( list_title, index );
1123                         if ( hbtitle != NULL )
1124                         {
1125                             if ( hbtitle->duration > longest_duration )
1126                             {
1127                                 longest_duration = hbtitle->duration;
1128                                 longest = title;
1129                             }
1130                         }
1131                     }
1132                 }
1133                 goto done;
1134             }
1135         } break;
1136
1137         case DVDNAV_VTS_CHANGE:
1138         {
1139             result = dvdnav_current_title_program( d->dvdnav, &title, &pgcn, &pgn );
1140             if (result != DVDNAV_STATUS_OK)
1141                 hb_log("dvdnav cur pgcn err: %s", dvdnav_err_to_string(d->dvdnav));
1142             cur_title = title;
1143             if ( title > 0 )
1144             {
1145                 dvdnav_next_pg_search( d->dvdnav );
1146             }
1147         } break;
1148
1149         case DVDNAV_HIGHLIGHT:
1150             break;
1151
1152         case DVDNAV_AUDIO_STREAM_CHANGE:
1153             break;
1154
1155         case DVDNAV_SPU_STREAM_CHANGE:
1156             break;
1157
1158         case DVDNAV_SPU_CLUT_CHANGE:
1159             break;
1160
1161         case DVDNAV_NOP:
1162             break;
1163
1164         default:
1165             break;
1166         }
1167     }
1168
1169 done:
1170     return longest;
1171 }
1172
1173 static int hb_dvdnav_main_feature( hb_dvd_t * e, hb_list_t * list_title )
1174 {
1175     hb_dvdnav_t * d = &(e->dvdnav);
1176     int longest_root;
1177     int longest_title;
1178     int longest_fallback;
1179     int ii;
1180     uint64_t longest_duration_root = 0;
1181     uint64_t longest_duration_title = 0;
1182     uint64_t longest_duration_fallback = 0;
1183
1184     for ( ii = 0; ii < hb_list_count( list_title ); ii++ )
1185     {
1186         hb_title_t * title = hb_list_item( list_title, ii );
1187         if ( title->duration > longest_duration_fallback )
1188         {
1189             longest_duration_fallback = title->duration;
1190             longest_fallback = title->index;
1191         }
1192     }
1193
1194     longest_root = try_menu( d, list_title, DVD_MENU_Root );
1195     if ( longest_root >= 0 )
1196     {
1197         hb_title_t * hbtitle;
1198         int index;
1199         index = find_title( list_title, longest_root );
1200         hbtitle = hb_list_item( list_title, index );
1201         if ( hbtitle )
1202             longest_duration_root = hbtitle->duration;
1203     }
1204     if ( longest_root < 0 || 
1205          (float)longest_duration_fallback * 0.7 > longest_duration_root)
1206     {
1207         longest_title = try_menu( d, list_title, DVD_MENU_Title );
1208         if ( longest_title >= 0 )
1209         {
1210             hb_title_t * hbtitle;
1211             int index;
1212             index = find_title( list_title, longest_title );
1213             hbtitle = hb_list_item( list_title, index );
1214             if ( hbtitle )
1215                 longest_duration_title = hbtitle->duration;
1216         }
1217     }
1218
1219     uint64_t longest_duration;
1220     int longest;
1221
1222     if ( longest_duration_root > longest_duration_title )
1223     {
1224         longest_duration = longest_duration_root;
1225         longest = longest_root;
1226     }
1227     else
1228     {
1229         longest_duration = longest_duration_title;
1230         longest = longest_title;
1231     }
1232     if ((float)longest_duration_fallback * 0.7 > longest_duration)
1233     {
1234         longest = longest_fallback;
1235     }
1236     return longest;
1237 }
1238
1239 /***********************************************************************
1240  * hb_dvdnav_start
1241  ***********************************************************************
1242  * Title and chapter start at 1
1243  **********************************************************************/
1244 static int hb_dvdnav_start( hb_dvd_t * e, hb_title_t *title, int c )
1245 {
1246     hb_dvdnav_t * d = &(e->dvdnav);
1247     int t = title->index;
1248     hb_chapter_t *chapter;
1249     dvdnav_status_t result;
1250
1251     d->title_block_count = title->block_count;
1252     d->list_chapter = title->list_chapter;
1253
1254     if ( d->stopped && !hb_dvdnav_reset(d) )
1255     {
1256         return 0;
1257     }
1258     dvdnav_reset( d->dvdnav );
1259     chapter = hb_list_item( title->list_chapter, c - 1);
1260     if (chapter != NULL)
1261         result = dvdnav_program_play(d->dvdnav, t, chapter->pgcn, chapter->pgn);
1262     else
1263         result = dvdnav_part_play(d->dvdnav, t, 1);
1264     if (result != DVDNAV_STATUS_OK)
1265     {
1266         hb_error( "dvd: dvdnav_*_play failed - %s", 
1267                   dvdnav_err_to_string(d->dvdnav) );
1268         return 0;
1269     }
1270     d->title = t;
1271     d->stopped = 0;
1272     d->chapter = 0;
1273     return 1;
1274 }
1275
1276 /***********************************************************************
1277  * hb_dvdnav_stop
1278  ***********************************************************************
1279  *
1280  **********************************************************************/
1281 static void hb_dvdnav_stop( hb_dvd_t * e )
1282 {
1283 }
1284
1285 /***********************************************************************
1286  * hb_dvdnav_seek
1287  ***********************************************************************
1288  *
1289  **********************************************************************/
1290 static int hb_dvdnav_seek( hb_dvd_t * e, float f )
1291 {
1292     hb_dvdnav_t * d = &(e->dvdnav);
1293     uint64_t sector = f * d->title_block_count;
1294     int result, event, len;
1295     uint8_t buf[HB_DVD_READ_BUFFER_SIZE];
1296     int done = 0, ii;
1297
1298     if (d->stopped)
1299     {
1300         return 0;
1301     }
1302
1303     // XXX the current version of libdvdnav can't seek outside the current
1304     // PGC. Check if the place we're seeking to is in a different
1305     // PGC. Position there & adjust the offset if so.
1306     uint64_t pgc_offset = 0;
1307     uint64_t chap_offset = 0;
1308     hb_chapter_t *pgc_change = hb_list_item(d->list_chapter, 0 );
1309     for ( ii = 0; ii < hb_list_count( d->list_chapter ); ++ii )
1310     {
1311         hb_chapter_t *chapter = hb_list_item( d->list_chapter, ii );
1312         uint64_t chap_len = chapter->block_end - chapter->block_start + 1;
1313
1314         if ( chapter->pgcn != pgc_change->pgcn )
1315         {
1316             // this chapter's in a different pgc from the previous - note the
1317             // change so we can make sector offset's be pgc relative.
1318             pgc_offset = chap_offset;
1319             pgc_change = chapter;
1320         }
1321         if ( chap_offset <= sector && sector < chap_offset + chap_len )
1322         {
1323             // this chapter contains the sector we want - see if it's in a
1324             // different pgc than the one we're currently in.
1325             int32_t title, pgcn, pgn;
1326             if (dvdnav_current_title_program( d->dvdnav, &title, &pgcn, &pgn ) != DVDNAV_STATUS_OK)
1327                 hb_log("dvdnav cur pgcn err: %s", dvdnav_err_to_string(d->dvdnav));
1328             // If we find ourselves in a new title, it means a title
1329             // transition was made while reading data.  Jumping between
1330             // titles can cause the vm to get into a bad state.  So
1331             // reset the vm in this case.
1332             if ( d->title != title )
1333                 dvdnav_reset( d->dvdnav );
1334
1335             if ( d->title != title || chapter->pgcn != pgcn )
1336             {
1337                 // this chapter is in a different pgc - switch to it.
1338                 if (dvdnav_program_play(d->dvdnav, d->title, chapter->pgcn, chapter->pgn) != DVDNAV_STATUS_OK)
1339                     hb_log("dvdnav prog play err: %s", dvdnav_err_to_string(d->dvdnav));
1340             }
1341             // seek sectors are pgc-relative so remove the pgc start sector.
1342             sector -= pgc_offset;
1343             break;
1344         }
1345         chap_offset += chap_len;
1346     }
1347
1348     // dvdnav will not let you seek or poll current position
1349     // till it reaches a certain point in parsing.  so we
1350     // have to get blocks until we reach a cell
1351     // Put an arbitrary limit of 100 blocks on how long we search
1352     for (ii = 0; ii < 100 && !done; ii++)
1353     {
1354         result = dvdnav_get_next_block( d->dvdnav, buf, &event, &len );
1355         if ( result == DVDNAV_STATUS_ERR )
1356         {
1357             hb_error("dvdnav: Read Error, %s", dvdnav_err_to_string(d->dvdnav));
1358             return 0;
1359         }
1360         switch ( event )
1361         {
1362         case DVDNAV_BLOCK_OK:
1363         case DVDNAV_CELL_CHANGE:
1364             done = 1;
1365             break;
1366
1367         case DVDNAV_STILL_FRAME:
1368             dvdnav_still_skip( d->dvdnav );
1369             break;
1370
1371         case DVDNAV_WAIT:
1372             dvdnav_wait_skip( d->dvdnav );
1373             break;
1374
1375         case DVDNAV_STOP:
1376             hb_log("dvdnav: stop encountered during seek");
1377             d->stopped = 1;
1378             return 0;
1379
1380         case DVDNAV_HOP_CHANNEL:
1381         case DVDNAV_NAV_PACKET:
1382         case DVDNAV_VTS_CHANGE:
1383         case DVDNAV_HIGHLIGHT:
1384         case DVDNAV_AUDIO_STREAM_CHANGE:
1385         case DVDNAV_SPU_STREAM_CHANGE:
1386         case DVDNAV_SPU_CLUT_CHANGE:
1387         case DVDNAV_NOP:
1388         default:
1389             break;
1390         }
1391     }
1392
1393     if (dvdnav_sector_search(d->dvdnav, sector, SEEK_SET) != DVDNAV_STATUS_OK)
1394     {
1395         hb_error( "dvd: dvdnav_sector_search failed - %s", 
1396                   dvdnav_err_to_string(d->dvdnav) );
1397         return 0;
1398     }
1399     return 1;
1400 }
1401
1402 /***********************************************************************
1403  * hb_dvdnav_read
1404  ***********************************************************************
1405  *
1406  **********************************************************************/
1407 static int hb_dvdnav_read( hb_dvd_t * e, hb_buffer_t * b )
1408 {
1409     hb_dvdnav_t * d = &(e->dvdnav);
1410     int result, event, len;
1411     int chapter = 0;
1412     int error_count = 0;
1413
1414     while ( 1 )
1415     {
1416         if (d->stopped)
1417         {
1418             return 0;
1419         }
1420         result = dvdnav_get_next_block( d->dvdnav, b->data, &event, &len );
1421         if ( result == DVDNAV_STATUS_ERR )
1422         {
1423             hb_error("dvdnav: Read Error, %s", dvdnav_err_to_string(d->dvdnav));
1424             if (dvdnav_sector_search(d->dvdnav, 1, SEEK_CUR) != DVDNAV_STATUS_OK)
1425             {
1426                 hb_error( "dvd: dvdnav_sector_search failed - %s",
1427                         dvdnav_err_to_string(d->dvdnav) );
1428                 return 0;
1429             }
1430             error_count++;
1431             if (error_count > 10)
1432             {
1433                 hb_error("dvdnav: Error, too many consecutive read errors");
1434                 return 0;
1435             }
1436             continue;
1437         }
1438         switch ( event )
1439         {
1440         case DVDNAV_BLOCK_OK:
1441             // We have received a regular block of the currently playing
1442             // MPEG stream.
1443
1444             // The muxers expect to only get chapter 2 and above
1445             // They write chapter 1 when chapter 2 is detected.
1446             if (chapter > 1)
1447                 b->new_chap = chapter;
1448             chapter = 0;
1449             error_count = 0;
1450             return 1;
1451
1452         case DVDNAV_NOP:
1453             /*
1454             * Nothing to do here. 
1455             */
1456             break;
1457
1458         case DVDNAV_STILL_FRAME:
1459             /*
1460             * We have reached a still frame. A real player application
1461             * would wait the amount of time specified by the still's
1462             * length while still handling user input to make menus and
1463             * other interactive stills work. A length of 0xff means an
1464             * indefinite still which has to be skipped indirectly by some 
1465             * user interaction. 
1466             */
1467             dvdnav_still_skip( d->dvdnav );
1468             break;
1469
1470         case DVDNAV_WAIT:
1471             /*
1472             * We have reached a point in DVD playback, where timing is
1473             * critical. Player application with internal fifos can
1474             * introduce state inconsistencies, because libdvdnav is
1475             * always the fifo's length ahead in the stream compared to
1476             * what the application sees. Such applications should wait
1477             * until their fifos are empty when they receive this type of
1478             * event. 
1479             */
1480             dvdnav_wait_skip( d->dvdnav );
1481             break;
1482
1483         case DVDNAV_SPU_CLUT_CHANGE:
1484             /*
1485             * Player applications should pass the new colour lookup table 
1486             * to their SPU decoder 
1487             */
1488             break;
1489
1490         case DVDNAV_SPU_STREAM_CHANGE:
1491             /*
1492             * Player applications should inform their SPU decoder to
1493             * switch channels 
1494             */
1495             break;
1496
1497         case DVDNAV_AUDIO_STREAM_CHANGE:
1498             /*
1499             * Player applications should inform their audio decoder to
1500             * switch channels 
1501             */
1502             break;
1503
1504         case DVDNAV_HIGHLIGHT:
1505             /*
1506             * Player applications should inform their overlay engine to
1507             * highlight the given button 
1508             */
1509             break;
1510
1511         case DVDNAV_VTS_CHANGE:
1512             /*
1513             * Some status information like video aspect and video scale
1514             * permissions do not change inside a VTS. Therefore this
1515             * event can be used to query such information only when
1516             * necessary and update the decoding/displaying accordingly. 
1517             */
1518             {
1519                 int tt = 0, pgcn = 0, pgn = 0;
1520
1521                 dvdnav_current_title_program(d->dvdnav, &tt, &pgcn, &pgn);
1522                 if (tt != d->title)
1523                 {
1524                     // Transition to another title signals that we are done.
1525                     return 0;
1526                 }
1527             }
1528             break;
1529
1530         case DVDNAV_CELL_CHANGE:
1531             /*
1532             * Some status information like the current Title and Part
1533             * numbers do not change inside a cell. Therefore this event
1534             * can be used to query such information only when necessary
1535             * and update the decoding/displaying accordingly. 
1536             */
1537             {
1538                 int tt = 0, pgcn = 0, pgn = 0, c;
1539
1540                 dvdnav_current_title_program(d->dvdnav, &tt, &pgcn, &pgn);
1541                 if (tt != d->title)
1542                 {
1543                     // Transition to another title signals that we are done.
1544                     return 0;
1545                 }
1546                 c = FindChapterIndex(d->list_chapter, pgcn, pgn);
1547                 if (c != d->chapter)
1548                 {
1549                     if (c < d->chapter)
1550                     {
1551                         // Some titles end with a 'link' back to the beginning so
1552                         // a transition to an earlier chapter means we're done.
1553                         return 0;
1554                     }
1555                     chapter = d->chapter = c;
1556                 }
1557             }
1558             break;
1559
1560         case DVDNAV_NAV_PACKET:
1561             /*
1562             * A NAV packet provides PTS discontinuity information, angle
1563             * linking information and button definitions for DVD menus.
1564             * Angles are handled completely inside libdvdnav. For the
1565             * menus to work, the NAV packet information has to be passed
1566             * to the overlay engine of the player so that it knows the
1567             * dimensions of the button areas. 
1568             */
1569
1570             // mpegdemux expects to get these.  I don't think it does
1571             // anything useful with them however.
1572
1573             // The muxers expect to only get chapter 2 and above
1574             // They write chapter 1 when chapter 2 is detected.
1575             if (chapter > 1)
1576                 b->new_chap = chapter;
1577             chapter = 0;
1578             return 1;
1579
1580             break;
1581
1582         case DVDNAV_HOP_CHANNEL:
1583             /*
1584             * This event is issued whenever a non-seamless operation has
1585             * been executed. Applications with fifos should drop the
1586             * fifos content to speed up responsiveness. 
1587             */
1588             break;
1589
1590         case DVDNAV_STOP:
1591             /*
1592             * Playback should end here. 
1593             */
1594             d->stopped = 1;
1595             return 0;
1596
1597         default:
1598             break;
1599         }
1600     }
1601     return 0;
1602 }
1603
1604 /***********************************************************************
1605  * hb_dvdnav_chapter
1606  ***********************************************************************
1607  * Returns in which chapter the next block to be read is.
1608  * Chapter numbers start at 1.
1609  **********************************************************************/
1610 static int hb_dvdnav_chapter( hb_dvd_t * e )
1611 {
1612     hb_dvdnav_t * d = &(e->dvdnav);
1613     int32_t t, pgcn, pgn;
1614     int32_t c;
1615
1616     if (dvdnav_current_title_program(d->dvdnav, &t, &pgcn, &pgn) != DVDNAV_STATUS_OK)
1617     {
1618         return -1;
1619     }
1620     c = FindChapterIndex( d->list_chapter, pgcn, pgn );
1621     return c;
1622 }
1623
1624 /***********************************************************************
1625  * hb_dvdnav_close
1626  ***********************************************************************
1627  * Closes and frees everything
1628  **********************************************************************/
1629 static void hb_dvdnav_close( hb_dvd_t ** _d )
1630 {
1631     hb_dvdnav_t * d = &((*_d)->dvdnav);
1632
1633     if( d->dvdnav ) dvdnav_close( d->dvdnav );
1634     if( d->vmg ) ifoClose( d->vmg );
1635     if( d->reader ) DVDClose( d->reader );
1636
1637     free( d );
1638     *_d = NULL;
1639 }
1640
1641 /***********************************************************************
1642  * hb_dvdnav_angle_count
1643  ***********************************************************************
1644  * Returns the number of angles supported.
1645  **********************************************************************/
1646 static int hb_dvdnav_angle_count( hb_dvd_t * e )
1647 {
1648     hb_dvdnav_t * d = &(e->dvdnav);
1649     int current, angle_count;
1650
1651     if (dvdnav_get_angle_info( d->dvdnav, &current, &angle_count) != DVDNAV_STATUS_OK)
1652     {
1653         hb_log("dvdnav_get_angle_info %s", dvdnav_err_to_string(d->dvdnav));
1654         angle_count = 1;
1655     }
1656     return angle_count;
1657 }
1658
1659 /***********************************************************************
1660  * hb_dvdnav_set_angle
1661  ***********************************************************************
1662  * Sets the angle to read
1663  **********************************************************************/
1664 static void hb_dvdnav_set_angle( hb_dvd_t * e, int angle )
1665 {
1666     hb_dvdnav_t * d = &(e->dvdnav);
1667
1668     if (dvdnav_angle_change( d->dvdnav, angle) != DVDNAV_STATUS_OK)
1669     {
1670         hb_log("dvdnav_angle_change %s", dvdnav_err_to_string(d->dvdnav));
1671     }
1672 }
1673
1674 /***********************************************************************
1675  * FindChapterIndex
1676  ***********************************************************************
1677  * Assumes pgc and cell_cur are correctly set, and sets cell_next to the
1678  * cell to be read when we will be done with cell_cur.
1679  **********************************************************************/
1680 static int FindChapterIndex( hb_list_t * list, int pgcn, int pgn )
1681 {
1682     int count, ii;
1683     hb_chapter_t *chapter;
1684
1685     count = hb_list_count( list );
1686     for (ii = 0; ii < count; ii++)
1687     {
1688         chapter = hb_list_item( list, ii );
1689         if (chapter->pgcn == pgcn && chapter->pgn == pgn)
1690             return chapter->index;
1691     }
1692     return 0;
1693 }
1694
1695 /***********************************************************************
1696  * FindNextCell
1697  ***********************************************************************
1698  * Assumes pgc and cell_cur are correctly set, and sets cell_next to the
1699  * cell to be read when we will be done with cell_cur.
1700  **********************************************************************/
1701 static int FindNextCell( pgc_t *pgc, int cell_cur )
1702 {
1703     int i = 0;
1704     int cell_next;
1705
1706     if( pgc->cell_playback[cell_cur].block_type ==
1707             BLOCK_TYPE_ANGLE_BLOCK )
1708     {
1709
1710         while( pgc->cell_playback[cell_cur+i].block_mode !=
1711                    BLOCK_MODE_LAST_CELL )
1712         {
1713              i++;
1714         }
1715         cell_next = cell_cur + i + 1;
1716         hb_log( "dvd: Skipping multi-angle cells %d-%d",
1717                 cell_cur,
1718                 cell_next - 1 );
1719     }
1720     else
1721     {
1722         cell_next = cell_cur + 1;
1723     }
1724     return cell_next;
1725 }
1726
1727 /***********************************************************************
1728  * NextPgcn
1729  ***********************************************************************
1730  * Assumes pgc and cell_cur are correctly set, and sets cell_next to the
1731  * cell to be read when we will be done with cell_cur.
1732  * Since pg chains can be circularly linked (either from a read error or
1733  * deliberately) pgcn_map tracks program chains we've already seen.
1734  **********************************************************************/
1735 static int NextPgcn( ifo_handle_t *ifo, int pgcn, uint32_t pgcn_map[MAX_PGCN/32] )
1736 {
1737     int next_pgcn;
1738     pgc_t *pgc;
1739
1740     pgcn_map[pgcn >> 5] |= (1 << (pgcn & 31));
1741
1742     pgc = ifo->vts_pgcit->pgci_srp[pgcn-1].pgc;
1743     next_pgcn = pgc->next_pgc_nr;
1744     if ( next_pgcn < 1 || next_pgcn >= MAX_PGCN || next_pgcn > ifo->vts_pgcit->nr_of_pgci_srp )
1745         return 0;
1746
1747     return pgcn_map[next_pgcn >> 5] & (1 << (next_pgcn & 31))? 0 : next_pgcn;
1748 }
1749
1750 /***********************************************************************
1751  * PgcWalkInit
1752  ***********************************************************************
1753  * Pgc links can loop. I track which have been visited in a bit vector
1754  * Initialize the bit vector to empty.
1755  **********************************************************************/
1756 static void PgcWalkInit( uint32_t pgcn_map[MAX_PGCN/32] )
1757 {
1758     memset(pgcn_map, 0, sizeof(pgcn_map) );
1759 }
1760
1761 /***********************************************************************
1762  * dvdtime2msec
1763  ***********************************************************************
1764  * From lsdvd
1765  **********************************************************************/
1766 static int dvdtime2msec(dvd_time_t * dt)
1767 {
1768     double frames_per_s[4] = {-1.0, 25.00, -1.0, 29.97};
1769     double fps = frames_per_s[(dt->frame_u & 0xc0) >> 6];
1770     long   ms;
1771     ms  = (((dt->hour &   0xf0) >> 3) * 5 + (dt->hour   & 0x0f)) * 3600000;
1772     ms += (((dt->minute & 0xf0) >> 3) * 5 + (dt->minute & 0x0f)) * 60000;
1773     ms += (((dt->second & 0xf0) >> 3) * 5 + (dt->second & 0x0f)) * 1000;
1774
1775     if( fps > 0 )
1776     {
1777         ms += ((dt->frame_u & 0x30) >> 3) * 5 +
1778               (dt->frame_u & 0x0f) * 1000.0 / fps;
1779     }
1780
1781     return ms;
1782 }