OSDN Git Service

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