OSDN Git Service

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