OSDN Git Service

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