OSDN Git Service

Remove depreciated cpu count from the api
[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, uint64_t min_duration );
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, uint64_t min_duration )
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     /* Get duration */
419     title->duration = longest;
420     title->hours    = title->duration / 90000 / 3600;
421     title->minutes  = ( ( title->duration / 90000 ) % 3600 ) / 60;
422     title->seconds  = ( title->duration / 90000 ) % 60;
423     hb_log( "scan: duration is %02d:%02d:%02d (%"PRId64" ms)",
424             title->hours, title->minutes, title->seconds,
425             title->duration / 90 );
426
427     /* ignore titles under 10 seconds because they're often stills or
428      * clips with no audio & our preview code doesn't currently handle
429      * either of these. */
430     if( longest < min_duration )
431     {
432         hb_log( "scan: ignoring title (too short)" );
433         goto fail;
434     }
435
436     pgcn       = longest_pgcn;
437     pgcn_end   = longest_pgcn_end;
438     pgn        = longest_pgn;;
439     title_pgcn = pgcn;
440
441
442     /* Get pgc */
443     if ( pgcn < 1 || pgcn > ifo->vts_pgcit->nr_of_pgci_srp || pgcn >= MAX_PGCN)
444     {
445         hb_error( "invalid PGC ID %d for title %d, skipping", pgcn, t );
446         goto fail;
447     }
448
449     pgc = ifo->vts_pgcit->pgci_srp[pgcn-1].pgc;
450
451     hb_log("pgc_id: %d, pgn: %d: pgc: %p", pgcn, pgn, pgc);
452     if (pgn > pgc->nr_of_programs)
453     {
454         hb_error( "invalid PGN %d for title %d, skipping", pgn, t );
455         goto fail;
456     }
457
458     /* Title start */
459     title->cell_start = pgc->program_map[pgn-1] - 1;
460     title->block_start = pgc->cell_playback[title->cell_start].first_sector;
461
462     pgc = ifo->vts_pgcit->pgci_srp[pgcn_end-1].pgc;
463
464     /* Title end */
465     title->cell_end = pgc->nr_of_cells - 1;
466     title->block_end = pgc->cell_playback[title->cell_end].last_sector;
467
468     hb_log( "scan: vts=%d, ttn=%d, cells=%d->%d, blocks=%"PRIu64"->%"PRIu64", "
469             "%"PRIu64" blocks", title->vts, title->ttn, title->cell_start,
470             title->cell_end, title->block_start, title->block_end,
471             title->block_count );
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     /* Check for subtitles */
595     for( i = 0; i < ifo->vtsi_mat->nr_of_vts_subp_streams; i++ )
596     {
597         hb_subtitle_t * subtitle;
598         int spu_control;
599         int position;
600         iso639_lang_t * lang;
601         int lang_extension = 0;
602
603         hb_log( "scan: checking subtitle %d", i + 1 );
604
605         spu_control =
606             ifo->vts_pgcit->pgci_srp[title_pgcn-1].pgc->subp_control[i];
607
608         if( !( spu_control & 0x80000000 ) )
609         {
610             hb_log( "scan: subtitle channel is not active" );
611             continue;
612         }
613
614         if( ifo->vtsi_mat->vts_video_attr.display_aspect_ratio )
615         {
616             switch( ifo->vtsi_mat->vts_video_attr.permitted_df )
617             {
618                 case 1:
619                     position = spu_control & 0xFF;
620                     break;
621                 case 2:
622                     position = ( spu_control >> 8 ) & 0xFF;
623                     break;
624                 default:
625                     position = ( spu_control >> 16 ) & 0xFF;
626             }
627         }
628         else
629         {
630             position = ( spu_control >> 24 ) & 0x7F;
631         }
632
633         lang_extension = ifo->vtsi_mat->vts_subp_attr[i].code_extension;
634
635         lang = lang_for_code( ifo->vtsi_mat->vts_subp_attr[i].lang_code );
636
637         subtitle = calloc( sizeof( hb_subtitle_t ), 1 );
638         subtitle->track = i+1;
639         subtitle->id = ( ( 0x20 + position ) << 8 ) | 0xbd;
640         snprintf( subtitle->lang, sizeof( subtitle->lang ), "%s",
641              strlen(lang->native_name) ? lang->native_name : lang->eng_name);
642         snprintf( subtitle->iso639_2, sizeof( subtitle->iso639_2 ), "%s",
643                   lang->iso639_2);
644         subtitle->format = PICTURESUB;
645         subtitle->source = VOBSUB;
646         subtitle->config.dest   = RENDERSUB;  // By default render (burn-in) the VOBSUB.
647
648         subtitle->type = lang_extension;
649         
650         memcpy( subtitle->palette,
651             ifo->vts_pgcit->pgci_srp[title_pgcn-1].pgc->palette,
652             16 * sizeof( uint32_t ) );
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=%"PRIu64"->%"PRIu64" (%"PRIu64"), %"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 void skip_some( dvdnav_t * dvdnav, int blocks )
839 {
840     int ii;
841     int result, event, len;
842     uint8_t buf[HB_DVD_READ_BUFFER_SIZE];
843
844     for ( ii = 0; ii < blocks; ii++ )
845     {
846         result = dvdnav_get_next_block( dvdnav, buf, &event, &len );
847         if ( result == DVDNAV_STATUS_ERR )
848         {
849             hb_error("dvdnav: Read Error, %s", dvdnav_err_to_string(dvdnav));
850             return;
851         }
852         switch ( event )
853         {
854         case DVDNAV_BLOCK_OK:
855             break;
856
857         case DVDNAV_CELL_CHANGE:
858         {
859         } break;
860
861         case DVDNAV_STILL_FRAME:
862             dvdnav_still_skip( dvdnav );
863             break;
864
865         case DVDNAV_WAIT:
866             dvdnav_wait_skip( dvdnav );
867             break;
868
869         case DVDNAV_STOP:
870             return;
871
872         case DVDNAV_HOP_CHANNEL:
873             break;
874
875         case DVDNAV_NAV_PACKET:
876             break;
877
878         case DVDNAV_VTS_CHANGE:
879         {
880             dvdnav_vts_change_event_t *event;
881             event = (dvdnav_vts_change_event_t*)buf;
882             // Some discs initialize the vts with the "first play" item
883             // and some don't seem to.  So if we see it is uninitialized,
884             // set it.
885             if ( event->new_vtsN <= 0 )
886                 result = dvdnav_title_play( dvdnav, 1 );
887         } break;
888
889         case DVDNAV_HIGHLIGHT:
890             break;
891
892         case DVDNAV_AUDIO_STREAM_CHANGE:
893             break;
894
895         case DVDNAV_SPU_STREAM_CHANGE:
896             break;
897
898         case DVDNAV_SPU_CLUT_CHANGE:
899             break;
900
901         case DVDNAV_NOP:
902             break;
903
904         default:
905             break;
906         }
907     }
908 }
909
910 static int try_button( dvdnav_t * dvdnav, int menu_id, int button, hb_list_t * list_title )
911 {
912     int result, event, len;
913     uint8_t buf[HB_DVD_READ_BUFFER_SIZE];
914     int ii, jj;
915     int32_t cur_title, title, pgcn, pgn;
916     uint64_t longest_duration = 0;
917     int longest = -1;
918
919     pci_t *pci = dvdnav_get_current_nav_pci( dvdnav );
920     result = dvdnav_button_select_and_activate( dvdnav, pci, button + 1 );
921     if (result != DVDNAV_STATUS_OK)
922     {
923         hb_log("dvdnav_button_select_and_activate: %s", dvdnav_err_to_string(dvdnav));
924     }
925
926     result = dvdnav_current_title_program( dvdnav, &title, &pgcn, &pgn );
927     if (result != DVDNAV_STATUS_OK)
928         hb_log("dvdnav cur pgcn err: %s", dvdnav_err_to_string(dvdnav));
929
930     if ( title > 0 )
931     {
932         hb_title_t * hbtitle;
933         int index;
934         index = find_title( list_title, title );
935         hbtitle = hb_list_item( list_title, index );
936         if ( hbtitle != NULL )
937         {
938             if ( hbtitle->duration > longest_duration )
939             {
940                 longest_duration = hbtitle->duration;
941                 longest = title;
942             }
943         }
944         // If the duration is longer than 10min, assume
945         // this isn't garbage leading to something bigger.
946         if ( longest_duration / 90000 > 10 * 60 )
947         {
948             return longest;
949         }
950     }
951     cur_title = title;
952
953     for (jj = 0; jj < 5; jj++)
954     {
955         for (ii = 0; ii < 2000; ii++)
956         {
957             result = dvdnav_get_next_block( dvdnav, buf, &event, &len );
958             if ( result == DVDNAV_STATUS_ERR )
959             {
960                 hb_error("dvdnav: Read Error, %s", dvdnav_err_to_string(dvdnav));
961                 return 0;
962             }
963             switch ( event )
964             {
965             case DVDNAV_BLOCK_OK:
966                 break;
967
968             case DVDNAV_CELL_CHANGE:
969             {
970                 result = dvdnav_current_title_program( dvdnav, &title, &pgcn, &pgn );
971                 if (result != DVDNAV_STATUS_OK)
972                     hb_log("dvdnav cur pgcn err: %s", dvdnav_err_to_string(dvdnav));
973
974                 if ( title != cur_title && title > 0 )
975                 {
976                     hb_title_t * hbtitle;
977                     int index;
978                     index = find_title( list_title, title );
979                     hbtitle = hb_list_item( list_title, index );
980                     if ( hbtitle != NULL )
981                     {
982                         if ( hbtitle->duration > longest_duration )
983                         {
984                             longest_duration = hbtitle->duration;
985                             longest = title;
986                         }
987                     }
988                     // If the duration is longer than 10min, assume
989                     // this isn't garbage leading to something bigger.
990                     if ( longest_duration / 90000 > 10 * 60 )
991                     {
992                         return longest;
993                     }
994                 }
995                 cur_title = title;
996                 if (title > 0)
997                 {
998                     result = dvdnav_next_pg_search( dvdnav );
999                     if ( result != DVDNAV_STATUS_OK )
1000                     {
1001                         return longest;
1002                     }
1003                 }
1004             } break;
1005
1006             case DVDNAV_STILL_FRAME:
1007                 dvdnav_still_skip( dvdnav );
1008                 break;
1009
1010             case DVDNAV_WAIT:
1011                 dvdnav_wait_skip( dvdnav );
1012                 break;
1013
1014             case DVDNAV_STOP:
1015                 return 0;
1016
1017             case DVDNAV_HOP_CHANNEL:
1018                 break;
1019
1020             case DVDNAV_NAV_PACKET:
1021             {
1022             } break;
1023
1024             case DVDNAV_VTS_CHANGE:
1025             {
1026                 result = dvdnav_current_title_program( dvdnav, &title, &pgcn, &pgn );
1027                 if (result != DVDNAV_STATUS_OK)
1028                     hb_log("dvdnav cur pgcn err: %s", dvdnav_err_to_string(dvdnav));
1029
1030                 if ( title != cur_title && title > 0 )
1031                 {
1032                     hb_title_t * hbtitle;
1033                     int index;
1034                     index = find_title( list_title, title );
1035                     hbtitle = hb_list_item( list_title, index );
1036                     if ( hbtitle != NULL )
1037                     {
1038                         if ( hbtitle->duration > longest_duration )
1039                         {
1040                             longest_duration = hbtitle->duration;
1041                             longest = title;
1042                         }
1043                     }
1044                     if ( longest_duration / 90000 > 10 * 60 )
1045                     {
1046                         return longest;
1047                     }
1048                 }
1049                 cur_title = title;
1050             } break;
1051
1052             case DVDNAV_HIGHLIGHT:
1053                 break;
1054
1055             case DVDNAV_AUDIO_STREAM_CHANGE:
1056                 break;
1057
1058             case DVDNAV_SPU_STREAM_CHANGE:
1059                 break;
1060
1061             case DVDNAV_SPU_CLUT_CHANGE:
1062                 break;
1063
1064             case DVDNAV_NOP:
1065                 break;
1066
1067             default:
1068                 break;
1069             }
1070         }
1071         if (cur_title > 0)
1072         {
1073             // Some titles have long lead-ins. Try skipping it.
1074             dvdnav_next_pg_search( dvdnav );
1075         }
1076     }
1077     return longest;
1078 }
1079
1080 static int try_menu( 
1081     hb_dvdnav_t * d, 
1082     hb_list_t * list_title, 
1083     DVDMenuID_t menu, 
1084     uint64_t fallback_duration )
1085 {
1086     int result, event, len;
1087     uint8_t buf[HB_DVD_READ_BUFFER_SIZE];
1088     int ii, jj;
1089     int32_t cur_title, title, pgcn, pgn;
1090     uint64_t longest_duration = 0;
1091     int longest = -1;
1092
1093
1094     result = dvdnav_menu_call( d->dvdnav, menu );
1095     if ( result != DVDNAV_STATUS_OK )
1096     {
1097         // Sometimes the "first play" item doesn't initialize the
1098         // initial VTS. So do it here.
1099         result = dvdnav_title_play( d->dvdnav, 1 );
1100         result = dvdnav_menu_call( d->dvdnav, menu );
1101         if ( result != DVDNAV_STATUS_OK )
1102         {
1103             hb_error("dvdnav: Can not set dvd menu, %s", dvdnav_err_to_string(d->dvdnav));
1104             goto done;
1105         }
1106     }
1107
1108     result = dvdnav_current_title_program( d->dvdnav, &title, &pgcn, &pgn );
1109     if (result != DVDNAV_STATUS_OK)
1110         hb_log("dvdnav cur pgcn err: %s", dvdnav_err_to_string(d->dvdnav));
1111
1112     cur_title = title;
1113
1114     for (jj = 0; jj < 4; jj++)
1115     {
1116         for (ii = 0; ii < 4000; ii++)
1117         {
1118             result = dvdnav_get_next_block( d->dvdnav, buf, &event, &len );
1119             if ( result == DVDNAV_STATUS_ERR )
1120             {
1121                 hb_error("dvdnav: Read Error, %s", dvdnav_err_to_string(d->dvdnav));
1122                 goto done;
1123             }
1124             switch ( event )
1125             {
1126             case DVDNAV_BLOCK_OK:
1127                 break;
1128
1129             case DVDNAV_CELL_CHANGE:
1130             {
1131                 result = dvdnav_current_title_program( d->dvdnav, &title, &pgcn, &pgn );
1132                 if (result != DVDNAV_STATUS_OK)
1133                     hb_log("dvdnav cur pgcn err: %s", dvdnav_err_to_string(d->dvdnav));
1134                 cur_title = title;
1135             } break;
1136
1137             case DVDNAV_STILL_FRAME:
1138                 dvdnav_still_skip( d->dvdnav );
1139                 break;
1140
1141             case DVDNAV_WAIT:
1142                 dvdnav_wait_skip( d->dvdnav );
1143                 break;
1144
1145             case DVDNAV_STOP:
1146                 goto done;
1147
1148             case DVDNAV_HOP_CHANNEL:
1149                 break;
1150
1151             case DVDNAV_NAV_PACKET:
1152             {
1153                 pci_t *pci = dvdnav_get_current_nav_pci( d->dvdnav );
1154                 int kk;
1155                 int buttons;
1156                 if ( pci == NULL ) break;
1157
1158                 buttons = pci->hli.hl_gi.btn_ns;
1159                 if ( cur_title == 0 && buttons > 1 )
1160                 {
1161                     int menu_title, menu_id;
1162                     result = dvdnav_current_title_info( d->dvdnav, &menu_title, &menu_id );
1163                     if (result != DVDNAV_STATUS_OK)
1164                         hb_log("dvdnav cur pgcn err: %s", dvdnav_err_to_string(d->dvdnav));
1165                     for (kk = 0; kk < buttons; kk++)
1166                     {
1167                         dvdnav_t *dvdnav_copy;
1168
1169                         result = dvdnav_dup( &dvdnav_copy, d->dvdnav );
1170                         if (result != DVDNAV_STATUS_OK)
1171                         {
1172                             hb_log("dvdnav dup failed: %s", dvdnav_err_to_string(d->dvdnav));
1173                             goto done;
1174                         }
1175                         title = try_button( dvdnav_copy, menu_id, kk, list_title );
1176                         dvdnav_free_dup( dvdnav_copy );
1177
1178                         if ( title >= 0 )
1179                         {
1180                             hb_title_t * hbtitle;
1181                             int index;
1182                             index = find_title( list_title, title );
1183                             hbtitle = hb_list_item( list_title, index );
1184                             if ( hbtitle != NULL )
1185                             {
1186                                 if ( hbtitle->duration > longest_duration )
1187                                 {
1188                                     longest_duration = hbtitle->duration;
1189                                     longest = title;
1190                                     if ((float)fallback_duration * 0.75 < longest_duration)
1191                                         goto done;
1192                                 }
1193                             }
1194                         }
1195                     }
1196                     goto done;
1197                 }
1198                 if ( cur_title == 0 && buttons == 1 )
1199                 {
1200                     dvdnav_button_select_and_activate( d->dvdnav, pci, 1 );
1201                 }
1202             } break;
1203
1204             case DVDNAV_VTS_CHANGE:
1205             {
1206                 result = dvdnav_current_title_program( d->dvdnav, &title, &pgcn, &pgn );
1207                 if (result != DVDNAV_STATUS_OK)
1208                     hb_log("dvdnav cur pgcn err: %s", dvdnav_err_to_string(d->dvdnav));
1209                 cur_title = title;
1210             } break;
1211
1212             case DVDNAV_HIGHLIGHT:
1213                 break;
1214
1215             case DVDNAV_AUDIO_STREAM_CHANGE:
1216                 break;
1217
1218             case DVDNAV_SPU_STREAM_CHANGE:
1219                 break;
1220
1221             case DVDNAV_SPU_CLUT_CHANGE:
1222                 break;
1223
1224             case DVDNAV_NOP:
1225                 break;
1226
1227             default:
1228                 break;
1229             }
1230         }
1231         // Sometimes the menu is preceeded by a intro that just
1232         // gets restarted when hitting the menu button. So
1233         // try skipping with the skip forward button.  Then
1234         // try hitting the menu again.
1235         if ( !(jj & 1) )
1236             dvdnav_next_pg_search( d->dvdnav );
1237         else
1238             result = dvdnav_menu_call( d->dvdnav, menu );
1239     }
1240
1241 done:
1242     return longest;
1243 }
1244
1245 static int hb_dvdnav_main_feature( hb_dvd_t * e, hb_list_t * list_title )
1246 {
1247     hb_dvdnav_t * d = &(e->dvdnav);
1248     int longest_root;
1249     int longest_title = 0;
1250     int longest_fallback = 0;
1251     int ii;
1252     uint64_t longest_duration_root = 0;
1253     uint64_t longest_duration_title = 0;
1254     uint64_t longest_duration_fallback = 0;
1255
1256     for ( ii = 0; ii < hb_list_count( list_title ); ii++ )
1257     {
1258         hb_title_t * title = hb_list_item( list_title, ii );
1259         if ( title->duration > longest_duration_fallback )
1260         {
1261             longest_duration_fallback = title->duration;
1262             longest_fallback = title->index;
1263         }
1264     }
1265
1266     dvdnav_reset( d->dvdnav );
1267     skip_some( d->dvdnav, 500 );
1268
1269     longest_root = try_menu( d, list_title, DVD_MENU_Root, longest_duration_fallback );
1270     if ( longest_root >= 0 )
1271     {
1272         hb_title_t * hbtitle;
1273         int index;
1274         index = find_title( list_title, longest_root );
1275         hbtitle = hb_list_item( list_title, index );
1276         if ( hbtitle )
1277             longest_duration_root = hbtitle->duration;
1278     }
1279     if ( longest_root < 0 || 
1280          (float)longest_duration_fallback * 0.7 > longest_duration_root)
1281     {
1282         longest_title = try_menu( d, list_title, DVD_MENU_Title, longest_duration_fallback );
1283         if ( longest_title >= 0 )
1284         {
1285             hb_title_t * hbtitle;
1286             int index;
1287             index = find_title( list_title, longest_title );
1288             hbtitle = hb_list_item( list_title, index );
1289             if ( hbtitle )
1290                 longest_duration_title = hbtitle->duration;
1291         }
1292     }
1293
1294     uint64_t longest_duration;
1295     int longest;
1296
1297     if ( longest_duration_root > longest_duration_title )
1298     {
1299         longest_duration = longest_duration_root;
1300         longest = longest_root;
1301     }
1302     else
1303     {
1304         longest_duration = longest_duration_title;
1305         longest = longest_title;
1306     }
1307     if ((float)longest_duration_fallback * 0.7 > longest_duration)
1308     {
1309         longest = longest_fallback;
1310     }
1311     return longest;
1312 }
1313
1314 /***********************************************************************
1315  * hb_dvdnav_start
1316  ***********************************************************************
1317  * Title and chapter start at 1
1318  **********************************************************************/
1319 static int hb_dvdnav_start( hb_dvd_t * e, hb_title_t *title, int c )
1320 {
1321     hb_dvdnav_t * d = &(e->dvdnav);
1322     int t = title->index;
1323     hb_chapter_t *chapter;
1324     dvdnav_status_t result;
1325
1326     d->title_block_count = title->block_count;
1327     d->list_chapter = title->list_chapter;
1328
1329     if ( d->stopped && !hb_dvdnav_reset(d) )
1330     {
1331         return 0;
1332     }
1333     dvdnav_reset( d->dvdnav );
1334     chapter = hb_list_item( title->list_chapter, c - 1);
1335     if (chapter != NULL)
1336         result = dvdnav_program_play(d->dvdnav, t, chapter->pgcn, chapter->pgn);
1337     else
1338         result = dvdnav_part_play(d->dvdnav, t, 1);
1339     if (result != DVDNAV_STATUS_OK)
1340     {
1341         hb_error( "dvd: dvdnav_*_play failed - %s", 
1342                   dvdnav_err_to_string(d->dvdnav) );
1343         return 0;
1344     }
1345     d->title = t;
1346     d->stopped = 0;
1347     d->chapter = 0;
1348     d->cell = 0;
1349     return 1;
1350 }
1351
1352 /***********************************************************************
1353  * hb_dvdnav_stop
1354  ***********************************************************************
1355  *
1356  **********************************************************************/
1357 static void hb_dvdnav_stop( hb_dvd_t * e )
1358 {
1359 }
1360
1361 /***********************************************************************
1362  * hb_dvdnav_seek
1363  ***********************************************************************
1364  *
1365  **********************************************************************/
1366 static int hb_dvdnav_seek( hb_dvd_t * e, float f )
1367 {
1368     hb_dvdnav_t * d = &(e->dvdnav);
1369     uint64_t sector = f * d->title_block_count;
1370     int result, event, len;
1371     uint8_t buf[HB_DVD_READ_BUFFER_SIZE];
1372     int done = 0, ii;
1373
1374     if (d->stopped)
1375     {
1376         return 0;
1377     }
1378
1379     // XXX the current version of libdvdnav can't seek outside the current
1380     // PGC. Check if the place we're seeking to is in a different
1381     // PGC. Position there & adjust the offset if so.
1382     uint64_t pgc_offset = 0;
1383     uint64_t chap_offset = 0;
1384     hb_chapter_t *pgc_change = hb_list_item(d->list_chapter, 0 );
1385     for ( ii = 0; ii < hb_list_count( d->list_chapter ); ++ii )
1386     {
1387         hb_chapter_t *chapter = hb_list_item( d->list_chapter, ii );
1388         uint64_t chap_len = chapter->block_end - chapter->block_start + 1;
1389
1390         if ( chapter->pgcn != pgc_change->pgcn )
1391         {
1392             // this chapter's in a different pgc from the previous - note the
1393             // change so we can make sector offset's be pgc relative.
1394             pgc_offset = chap_offset;
1395             pgc_change = chapter;
1396         }
1397         if ( chap_offset <= sector && sector < chap_offset + chap_len )
1398         {
1399             // this chapter contains the sector we want - see if it's in a
1400             // different pgc than the one we're currently in.
1401             int32_t title, pgcn, pgn;
1402             if (dvdnav_current_title_program( d->dvdnav, &title, &pgcn, &pgn ) != DVDNAV_STATUS_OK)
1403                 hb_log("dvdnav cur pgcn err: %s", dvdnav_err_to_string(d->dvdnav));
1404             // If we find ourselves in a new title, it means a title
1405             // transition was made while reading data.  Jumping between
1406             // titles can cause the vm to get into a bad state.  So
1407             // reset the vm in this case.
1408             if ( d->title != title )
1409                 dvdnav_reset( d->dvdnav );
1410
1411             if ( d->title != title || chapter->pgcn != pgcn )
1412             {
1413                 // this chapter is in a different pgc - switch to it.
1414                 if (dvdnav_program_play(d->dvdnav, d->title, chapter->pgcn, chapter->pgn) != DVDNAV_STATUS_OK)
1415                     hb_log("dvdnav prog play err: %s", dvdnav_err_to_string(d->dvdnav));
1416             }
1417             // seek sectors are pgc-relative so remove the pgc start sector.
1418             sector -= pgc_offset;
1419             break;
1420         }
1421         chap_offset += chap_len;
1422     }
1423
1424     // dvdnav will not let you seek or poll current position
1425     // till it reaches a certain point in parsing.  so we
1426     // have to get blocks until we reach a cell
1427     // Put an arbitrary limit of 100 blocks on how long we search
1428     for (ii = 0; ii < 100 && !done; ii++)
1429     {
1430         result = dvdnav_get_next_block( d->dvdnav, buf, &event, &len );
1431         if ( result == DVDNAV_STATUS_ERR )
1432         {
1433             hb_error("dvdnav: Read Error, %s", dvdnav_err_to_string(d->dvdnav));
1434             return 0;
1435         }
1436         switch ( event )
1437         {
1438         case DVDNAV_BLOCK_OK:
1439         case DVDNAV_CELL_CHANGE:
1440             done = 1;
1441             break;
1442
1443         case DVDNAV_STILL_FRAME:
1444             dvdnav_still_skip( d->dvdnav );
1445             break;
1446
1447         case DVDNAV_WAIT:
1448             dvdnav_wait_skip( d->dvdnav );
1449             break;
1450
1451         case DVDNAV_STOP:
1452             hb_log("dvdnav: stop encountered during seek");
1453             d->stopped = 1;
1454             return 0;
1455
1456         case DVDNAV_HOP_CHANNEL:
1457         case DVDNAV_NAV_PACKET:
1458         case DVDNAV_VTS_CHANGE:
1459         case DVDNAV_HIGHLIGHT:
1460         case DVDNAV_AUDIO_STREAM_CHANGE:
1461         case DVDNAV_SPU_STREAM_CHANGE:
1462         case DVDNAV_SPU_CLUT_CHANGE:
1463         case DVDNAV_NOP:
1464         default:
1465             break;
1466         }
1467     }
1468
1469     if (dvdnav_sector_search(d->dvdnav, sector, SEEK_SET) != DVDNAV_STATUS_OK)
1470     {
1471         hb_error( "dvd: dvdnav_sector_search failed - %s", 
1472                   dvdnav_err_to_string(d->dvdnav) );
1473         return 0;
1474     }
1475     d->chapter = 0;
1476     d->cell = 0;
1477     return 1;
1478 }
1479
1480 /***********************************************************************
1481  * hb_dvdnav_read
1482  ***********************************************************************
1483  *
1484  **********************************************************************/
1485 static int hb_dvdnav_read( hb_dvd_t * e, hb_buffer_t * b )
1486 {
1487     hb_dvdnav_t * d = &(e->dvdnav);
1488     int result, event, len;
1489     int chapter = 0;
1490     int error_count = 0;
1491
1492     while ( 1 )
1493     {
1494         if (d->stopped)
1495         {
1496             return 0;
1497         }
1498         result = dvdnav_get_next_block( d->dvdnav, b->data, &event, &len );
1499         if ( result == DVDNAV_STATUS_ERR )
1500         {
1501             hb_error("dvdnav: Read Error, %s", dvdnav_err_to_string(d->dvdnav));
1502             if (dvdnav_sector_search(d->dvdnav, 1, SEEK_CUR) != DVDNAV_STATUS_OK)
1503             {
1504                 hb_error( "dvd: dvdnav_sector_search failed - %s",
1505                         dvdnav_err_to_string(d->dvdnav) );
1506                 return 0;
1507             }
1508             error_count++;
1509             if (error_count > 500)
1510             {
1511                 hb_error("dvdnav: Error, too many consecutive read errors");
1512                 return 0;
1513             }
1514             continue;
1515         }
1516         switch ( event )
1517         {
1518         case DVDNAV_BLOCK_OK:
1519             // We have received a regular block of the currently playing
1520             // MPEG stream.
1521
1522             // The muxers expect to only get chapter 2 and above
1523             // They write chapter 1 when chapter 2 is detected.
1524             if (chapter > 1)
1525                 b->new_chap = chapter;
1526             chapter = 0;
1527             error_count = 0;
1528             return 1;
1529
1530         case DVDNAV_NOP:
1531             /*
1532             * Nothing to do here. 
1533             */
1534             break;
1535
1536         case DVDNAV_STILL_FRAME:
1537             /*
1538             * We have reached a still frame. A real player application
1539             * would wait the amount of time specified by the still's
1540             * length while still handling user input to make menus and
1541             * other interactive stills work. A length of 0xff means an
1542             * indefinite still which has to be skipped indirectly by some 
1543             * user interaction. 
1544             */
1545             dvdnav_still_skip( d->dvdnav );
1546             break;
1547
1548         case DVDNAV_WAIT:
1549             /*
1550             * We have reached a point in DVD playback, where timing is
1551             * critical. Player application with internal fifos can
1552             * introduce state inconsistencies, because libdvdnav is
1553             * always the fifo's length ahead in the stream compared to
1554             * what the application sees. Such applications should wait
1555             * until their fifos are empty when they receive this type of
1556             * event. 
1557             */
1558             dvdnav_wait_skip( d->dvdnav );
1559             break;
1560
1561         case DVDNAV_SPU_CLUT_CHANGE:
1562             /*
1563             * Player applications should pass the new colour lookup table 
1564             * to their SPU decoder 
1565             */
1566             break;
1567
1568         case DVDNAV_SPU_STREAM_CHANGE:
1569             /*
1570             * Player applications should inform their SPU decoder to
1571             * switch channels 
1572             */
1573             break;
1574
1575         case DVDNAV_AUDIO_STREAM_CHANGE:
1576             /*
1577             * Player applications should inform their audio decoder to
1578             * switch channels 
1579             */
1580             break;
1581
1582         case DVDNAV_HIGHLIGHT:
1583             /*
1584             * Player applications should inform their overlay engine to
1585             * highlight the given button 
1586             */
1587             break;
1588
1589         case DVDNAV_VTS_CHANGE:
1590             /*
1591             * Some status information like video aspect and video scale
1592             * permissions do not change inside a VTS. Therefore this
1593             * event can be used to query such information only when
1594             * necessary and update the decoding/displaying accordingly. 
1595             */
1596             {
1597                 int tt = 0, pgcn = 0, pgn = 0;
1598
1599                 dvdnav_current_title_program(d->dvdnav, &tt, &pgcn, &pgn);
1600                 if (tt != d->title)
1601                 {
1602                     // Transition to another title signals that we are done.
1603                     return 0;
1604                 }
1605             }
1606             break;
1607
1608         case DVDNAV_CELL_CHANGE:
1609             /*
1610             * Some status information like the current Title and Part
1611             * numbers do not change inside a cell. Therefore this event
1612             * can be used to query such information only when necessary
1613             * and update the decoding/displaying accordingly. 
1614             */
1615             {
1616                 dvdnav_cell_change_event_t * cell_event;
1617                 int tt = 0, pgcn = 0, pgn = 0, c;
1618
1619                 cell_event = (dvdnav_cell_change_event_t*)b->data;
1620
1621                 dvdnav_current_title_program(d->dvdnav, &tt, &pgcn, &pgn);
1622                 if (tt != d->title)
1623                 {
1624                     // Transition to another title signals that we are done.
1625                     return 0;
1626                 }
1627                 c = FindChapterIndex(d->list_chapter, pgcn, pgn);
1628                 if (c != d->chapter)
1629                 {
1630                     if (c < d->chapter)
1631                     {
1632                         // Some titles end with a 'link' back to the beginning so
1633                         // a transition to an earlier chapter means we're done.
1634                         return 0;
1635                     }
1636                     chapter = d->chapter = c;
1637                 }
1638                 else if ( cell_event->cellN <= d->cell )
1639                 {
1640                     return 0;
1641                 }
1642                 d->cell = cell_event->cellN;
1643             }
1644             break;
1645
1646         case DVDNAV_NAV_PACKET:
1647             /*
1648             * A NAV packet provides PTS discontinuity information, angle
1649             * linking information and button definitions for DVD menus.
1650             * Angles are handled completely inside libdvdnav. For the
1651             * menus to work, the NAV packet information has to be passed
1652             * to the overlay engine of the player so that it knows the
1653             * dimensions of the button areas. 
1654             */
1655
1656             // mpegdemux expects to get these.  I don't think it does
1657             // anything useful with them however.
1658
1659             // The muxers expect to only get chapter 2 and above
1660             // They write chapter 1 when chapter 2 is detected.
1661             if (chapter > 1)
1662                 b->new_chap = chapter;
1663             chapter = 0;
1664             return 1;
1665
1666             break;
1667
1668         case DVDNAV_HOP_CHANNEL:
1669             /*
1670             * This event is issued whenever a non-seamless operation has
1671             * been executed. Applications with fifos should drop the
1672             * fifos content to speed up responsiveness. 
1673             */
1674             break;
1675
1676         case DVDNAV_STOP:
1677             /*
1678             * Playback should end here. 
1679             */
1680             d->stopped = 1;
1681             return 0;
1682
1683         default:
1684             break;
1685         }
1686     }
1687     return 0;
1688 }
1689
1690 /***********************************************************************
1691  * hb_dvdnav_chapter
1692  ***********************************************************************
1693  * Returns in which chapter the next block to be read is.
1694  * Chapter numbers start at 1.
1695  **********************************************************************/
1696 static int hb_dvdnav_chapter( hb_dvd_t * e )
1697 {
1698     hb_dvdnav_t * d = &(e->dvdnav);
1699     int32_t t, pgcn, pgn;
1700     int32_t c;
1701
1702     if (dvdnav_current_title_program(d->dvdnav, &t, &pgcn, &pgn) != DVDNAV_STATUS_OK)
1703     {
1704         return -1;
1705     }
1706     c = FindChapterIndex( d->list_chapter, pgcn, pgn );
1707     return c;
1708 }
1709
1710 /***********************************************************************
1711  * hb_dvdnav_close
1712  ***********************************************************************
1713  * Closes and frees everything
1714  **********************************************************************/
1715 static void hb_dvdnav_close( hb_dvd_t ** _d )
1716 {
1717     hb_dvdnav_t * d = &((*_d)->dvdnav);
1718
1719     if( d->dvdnav ) dvdnav_close( d->dvdnav );
1720     if( d->vmg ) ifoClose( d->vmg );
1721     if( d->reader ) DVDClose( d->reader );
1722
1723     free( d );
1724     *_d = NULL;
1725 }
1726
1727 /***********************************************************************
1728  * hb_dvdnav_angle_count
1729  ***********************************************************************
1730  * Returns the number of angles supported.
1731  **********************************************************************/
1732 static int hb_dvdnav_angle_count( hb_dvd_t * e )
1733 {
1734     hb_dvdnav_t * d = &(e->dvdnav);
1735     int current, angle_count;
1736
1737     if (dvdnav_get_angle_info( d->dvdnav, &current, &angle_count) != DVDNAV_STATUS_OK)
1738     {
1739         hb_log("dvdnav_get_angle_info %s", dvdnav_err_to_string(d->dvdnav));
1740         angle_count = 1;
1741     }
1742     return angle_count;
1743 }
1744
1745 /***********************************************************************
1746  * hb_dvdnav_set_angle
1747  ***********************************************************************
1748  * Sets the angle to read
1749  **********************************************************************/
1750 static void hb_dvdnav_set_angle( hb_dvd_t * e, int angle )
1751 {
1752     hb_dvdnav_t * d = &(e->dvdnav);
1753
1754     if (dvdnav_angle_change( d->dvdnav, angle) != DVDNAV_STATUS_OK)
1755     {
1756         hb_log("dvdnav_angle_change %s", dvdnav_err_to_string(d->dvdnav));
1757     }
1758 }
1759
1760 /***********************************************************************
1761  * FindChapterIndex
1762  ***********************************************************************
1763  * Assumes pgc and cell_cur are correctly set, and sets cell_next to the
1764  * cell to be read when we will be done with cell_cur.
1765  **********************************************************************/
1766 static int FindChapterIndex( hb_list_t * list, int pgcn, int pgn )
1767 {
1768     int count, ii;
1769     hb_chapter_t *chapter;
1770
1771     count = hb_list_count( list );
1772     for (ii = 0; ii < count; ii++)
1773     {
1774         chapter = hb_list_item( list, ii );
1775         if (chapter->pgcn == pgcn && chapter->pgn == pgn)
1776             return chapter->index;
1777     }
1778     return 0;
1779 }
1780
1781 /***********************************************************************
1782  * FindNextCell
1783  ***********************************************************************
1784  * Assumes pgc and cell_cur are correctly set, and sets cell_next to the
1785  * cell to be read when we will be done with cell_cur.
1786  **********************************************************************/
1787 static int FindNextCell( pgc_t *pgc, int cell_cur )
1788 {
1789     int i = 0;
1790     int cell_next;
1791
1792     if( pgc->cell_playback[cell_cur].block_type ==
1793             BLOCK_TYPE_ANGLE_BLOCK )
1794     {
1795
1796         while( pgc->cell_playback[cell_cur+i].block_mode !=
1797                    BLOCK_MODE_LAST_CELL )
1798         {
1799              i++;
1800         }
1801         cell_next = cell_cur + i + 1;
1802         hb_log( "dvd: Skipping multi-angle cells %d-%d",
1803                 cell_cur,
1804                 cell_next - 1 );
1805     }
1806     else
1807     {
1808         cell_next = cell_cur + 1;
1809     }
1810     return cell_next;
1811 }
1812
1813 /***********************************************************************
1814  * NextPgcn
1815  ***********************************************************************
1816  * Assumes pgc and cell_cur are correctly set, and sets cell_next to the
1817  * cell to be read when we will be done with cell_cur.
1818  * Since pg chains can be circularly linked (either from a read error or
1819  * deliberately) pgcn_map tracks program chains we've already seen.
1820  **********************************************************************/
1821 static int NextPgcn( ifo_handle_t *ifo, int pgcn, uint32_t pgcn_map[MAX_PGCN/32] )
1822 {
1823     int next_pgcn;
1824     pgc_t *pgc;
1825
1826     pgcn_map[pgcn >> 5] |= (1 << (pgcn & 31));
1827
1828     pgc = ifo->vts_pgcit->pgci_srp[pgcn-1].pgc;
1829     next_pgcn = pgc->next_pgc_nr;
1830     if ( next_pgcn < 1 || next_pgcn >= MAX_PGCN || next_pgcn > ifo->vts_pgcit->nr_of_pgci_srp )
1831         return 0;
1832
1833     return pgcn_map[next_pgcn >> 5] & (1 << (next_pgcn & 31))? 0 : next_pgcn;
1834 }
1835
1836 /***********************************************************************
1837  * PgcWalkInit
1838  ***********************************************************************
1839  * Pgc links can loop. I track which have been visited in a bit vector
1840  * Initialize the bit vector to empty.
1841  **********************************************************************/
1842 static void PgcWalkInit( uint32_t pgcn_map[MAX_PGCN/32] )
1843 {
1844     memset(pgcn_map, 0, sizeof(pgcn_map) );
1845 }
1846
1847 /***********************************************************************
1848  * dvdtime2msec
1849  ***********************************************************************
1850  * From lsdvd
1851  **********************************************************************/
1852 static int dvdtime2msec(dvd_time_t * dt)
1853 {
1854     double frames_per_s[4] = {-1.0, 25.00, -1.0, 29.97};
1855     double fps = frames_per_s[(dt->frame_u & 0xc0) >> 6];
1856     long   ms;
1857     ms  = (((dt->hour &   0xf0) >> 3) * 5 + (dt->hour   & 0x0f)) * 3600000;
1858     ms += (((dt->minute & 0xf0) >> 3) * 5 + (dt->minute & 0x0f)) * 60000;
1859     ms += (((dt->second & 0xf0) >> 3) * 5 + (dt->second & 0x0f)) * 1000;
1860
1861     if( fps > 0 )
1862     {
1863         ms += ((dt->frame_u & 0x30) >> 3) * 5 +
1864               (dt->frame_u & 0x0f) * 1000.0 / fps;
1865     }
1866
1867     return ms;
1868 }