OSDN Git Service

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