OSDN Git Service

8bc61944f45a8702b83440a4552eb64a033f8d0d
[handbrake-jp/handbrake-jp-git.git] / libhb / dvd.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 "dvdread/ifo_read.h"
12 #include "dvdread/nav_read.h"
13
14 static hb_dvd_t    * hb_dvdread_init( char * path );
15 static void          hb_dvdread_close( hb_dvd_t ** _d );
16 static char        * hb_dvdread_name( char * path );
17 static int           hb_dvdread_title_count( hb_dvd_t * d );
18 static hb_title_t  * hb_dvdread_title_scan( hb_dvd_t * d, int t );
19 static int           hb_dvdread_start( hb_dvd_t * d, int title, int chapter );
20 static void          hb_dvdread_stop( hb_dvd_t * d );
21 static int           hb_dvdread_seek( hb_dvd_t * d, float f );
22 static int           hb_dvdread_read( hb_dvd_t * d, hb_buffer_t * b );
23 static int           hb_dvdread_chapter( hb_dvd_t * d );
24 static int           hb_dvdread_angle_count( hb_dvd_t * d );
25 static void          hb_dvdread_set_angle( hb_dvd_t * d, int angle );
26
27 hb_dvd_func_t hb_dvdread_func =
28 {
29     hb_dvdread_init,
30     hb_dvdread_close,
31     hb_dvdread_name,
32     hb_dvdread_title_count,
33     hb_dvdread_title_scan,
34     hb_dvdread_start,
35     hb_dvdread_stop,
36     hb_dvdread_seek,
37     hb_dvdread_read,
38     hb_dvdread_chapter,
39     hb_dvdread_angle_count,
40     hb_dvdread_set_angle
41 };
42
43 static hb_dvd_func_t *dvd_methods = &hb_dvdread_func;
44
45 /***********************************************************************
46  * Local prototypes
47  **********************************************************************/
48 static void FindNextCell( hb_dvdread_t * );
49 static int  dvdtime2msec( dvd_time_t * );
50 static int hb_dvdread_is_break( hb_dvdread_t * d );
51
52 hb_dvd_func_t * hb_dvdread_methods( void )
53 {
54     return &hb_dvdread_func;
55 }
56
57 static char * hb_dvdread_name( char * path )
58 {
59     static char name[1024];
60     unsigned char unused[1024];
61     dvd_reader_t * reader;
62
63     reader = DVDOpen( path );
64     if( !reader )
65     {
66         return NULL;
67     }
68
69     if( DVDUDFVolumeInfo( reader, name, sizeof( name ),
70                           unused, sizeof( unused ) ) )
71     {
72         DVDClose( reader );
73         return NULL;
74     }
75
76     DVDClose( reader );
77     return name;
78 }
79
80 /***********************************************************************
81  * hb_dvdread_init
82  ***********************************************************************
83  *
84  **********************************************************************/
85 hb_dvd_t * hb_dvdread_init( char * path )
86 {
87     hb_dvd_t * e;
88     hb_dvdread_t * d;
89
90     e = calloc( sizeof( hb_dvd_t ), 1 );
91     d = &(e->dvdread);
92
93     /* Open device */
94     if( !( d->reader = DVDOpen( path ) ) )
95     {
96         /*
97          * Not an error, may be a stream - which we'll try in a moment.
98          */
99         hb_log( "dvd: not a dvd - trying as a stream/file instead" );
100         goto fail;
101     }
102
103     /* Open main IFO */
104     if( !( d->vmg = ifoOpen( d->reader, 0 ) ) )
105     {
106         hb_error( "dvd: ifoOpen failed" );
107         goto fail;
108     }
109
110     d->path = strdup( path );
111
112     return e;
113
114 fail:
115     if( d->vmg )    ifoClose( d->vmg );
116     if( d->reader ) DVDClose( d->reader );
117     free( d );
118     return NULL;
119 }
120
121 /***********************************************************************
122  * hb_dvdread_title_count
123  **********************************************************************/
124 static int hb_dvdread_title_count( hb_dvd_t * e )
125 {
126     hb_dvdread_t *d = &(e->dvdread);
127     return d->vmg->tt_srpt->nr_of_srpts;
128 }
129
130 /***********************************************************************
131  * hb_dvdread_title_scan
132  **********************************************************************/
133 static hb_title_t * hb_dvdread_title_scan( hb_dvd_t * e, int t )
134 {
135
136     hb_dvdread_t *d = &(e->dvdread);
137     hb_title_t   * title;
138     ifo_handle_t * vts = NULL;
139     int            pgc_id, pgn, i;
140     hb_chapter_t * chapter;
141     int            c;
142     uint64_t       duration;
143     float          duration_correction;
144     unsigned char  unused[1024];
145
146     hb_log( "scan: scanning title %d", t );
147
148     title = hb_title_init( d->path, t );
149     if( DVDUDFVolumeInfo( d->reader, title->name, sizeof( title->name ),
150                           unused, sizeof( unused ) ) )
151     {
152         char * p_cur, * p_last = d->path;
153         for( p_cur = d->path; *p_cur; p_cur++ )
154         {
155             if( p_cur[0] == '/' && p_cur[1] )
156             {
157                 p_last = &p_cur[1];
158             }
159         }
160         snprintf( title->name, sizeof( title->name ), "%s", p_last );
161     }
162
163     /* VTS which our title is in */
164     title->vts = d->vmg->tt_srpt->title[t-1].title_set_nr;
165
166     if ( !title->vts )
167     {
168         /* A VTS of 0 means the title wasn't found in the title set */
169         hb_error("Invalid VTS (title set) number: %i", title->vts);
170         goto fail;
171     }
172
173     hb_log( "scan: opening IFO for VTS %d", title->vts );
174     if( !( vts = ifoOpen( d->reader, title->vts ) ) )
175     {
176         hb_error( "scan: ifoOpen failed" );
177         goto fail;
178     }
179
180     /* ignore titles with bogus cell addresses so we don't abort later
181      * in libdvdread. */
182     for ( i = 0; i < vts->vts_c_adt->nr_of_vobs; ++i)
183     {
184         if( (vts->vts_c_adt->cell_adr_table[i].start_sector & 0xffffff ) ==
185             0xffffff )
186         {
187             hb_error( "scan: cell_adr_table[%d].start_sector invalid (0x%x) "
188                       "- skipping title", i,
189                       vts->vts_c_adt->cell_adr_table[i].start_sector );
190             goto fail;
191         }
192         if( (vts->vts_c_adt->cell_adr_table[i].last_sector & 0xffffff ) ==
193             0xffffff )
194         {
195             hb_error( "scan: cell_adr_table[%d].last_sector invalid (0x%x) "
196                       "- skipping title", i,
197                       vts->vts_c_adt->cell_adr_table[i].last_sector );
198             goto fail;
199         }
200         if( vts->vts_c_adt->cell_adr_table[i].start_sector >=
201             vts->vts_c_adt->cell_adr_table[i].last_sector )
202         {
203             hb_error( "scan: cell_adr_table[%d].start_sector (0x%x) "
204                       "is not before last_sector (0x%x) - skipping title", i,
205                       vts->vts_c_adt->cell_adr_table[i].start_sector,
206                       vts->vts_c_adt->cell_adr_table[i].last_sector );
207             goto fail;
208         }
209     }
210
211     if( global_verbosity_level == 3 )
212     {
213         ifo_print( d->reader, title->vts );
214     }
215
216     /* Position of the title in the VTS */
217     title->ttn = d->vmg->tt_srpt->title[t-1].vts_ttn;
218     if ( title->ttn < 1 || title->ttn > vts->vts_ptt_srpt->nr_of_srpts )
219     {
220         hb_error( "invalid VTS PTT offset %d for title %d, skipping", title->ttn, t );
221         goto fail;
222     }
223
224     /* Get pgc */
225     pgc_id = vts->vts_ptt_srpt->title[title->ttn-1].ptt[0].pgcn;
226     if ( pgc_id < 1 || pgc_id > vts->vts_pgcit->nr_of_pgci_srp )
227     {
228         hb_error( "invalid PGC ID %d for title %d, skipping", pgc_id, t );
229         goto fail;
230     }
231     pgn    = vts->vts_ptt_srpt->title[title->ttn-1].ptt[0].pgn;
232     d->pgc = vts->vts_pgcit->pgci_srp[pgc_id-1].pgc;
233
234     hb_log("pgc_id: %d, pgn: %d: pgc: 0x%x", pgc_id, pgn, d->pgc);
235
236     if( !d->pgc )
237     {
238         hb_error( "scan: pgc not valid, skipping" );
239         goto fail;
240     }
241
242     if( pgn <= 0 || pgn > 99 )
243     {
244         hb_error( "scan: pgn %d not valid, skipping", pgn );
245         goto fail;
246     }
247
248     /* Start cell */
249     title->cell_start  = d->pgc->program_map[pgn-1] - 1;
250     title->block_start = d->pgc->cell_playback[title->cell_start].first_sector;
251
252     /* End cell */
253     title->cell_end  = d->pgc->nr_of_cells - 1;
254     title->block_end = d->pgc->cell_playback[title->cell_end].last_sector;
255
256     /* Block count */
257     title->block_count = 0;
258     d->cell_cur = title->cell_start;
259     while( d->cell_cur <= title->cell_end )
260     {
261 #define cp d->pgc->cell_playback[d->cell_cur]
262         title->block_count += cp.last_sector + 1 - cp.first_sector;
263 #undef cp
264         FindNextCell( d );
265         d->cell_cur = d->cell_next;
266     }
267
268     hb_log( "scan: vts=%d, ttn=%d, cells=%d->%d, blocks=%d->%d, "
269             "%d blocks", title->vts, title->ttn, title->cell_start,
270             title->cell_end, title->block_start, title->block_end,
271             title->block_count );
272
273     /* Get duration */
274     title->duration = 90LL * dvdtime2msec( &d->pgc->playback_time );
275     title->hours    = title->duration / 90000 / 3600;
276     title->minutes  = ( ( title->duration / 90000 ) % 3600 ) / 60;
277     title->seconds  = ( title->duration / 90000 ) % 60;
278     hb_log( "scan: duration is %02d:%02d:%02d (%lld ms)",
279             title->hours, title->minutes, title->seconds,
280             title->duration / 90 );
281
282     /* ignore titles under 10 seconds because they're often stills or
283      * clips with no audio & our preview code doesn't currently handle
284      * either of these. */
285     if( title->duration < 900000LL )
286     {
287         hb_log( "scan: ignoring title (too short)" );
288         goto fail;
289     }
290
291     /* Detect languages */
292     for( i = 0; i < vts->vtsi_mat->nr_of_vts_audio_streams; i++ )
293     {
294         hb_audio_t * audio, * audio_tmp;
295         int          audio_format, lang_code, audio_control,
296                      position, j;
297         iso639_lang_t * lang;
298         int lang_extension = 0;
299
300         hb_log( "scan: checking audio %d", i + 1 );
301
302         audio = calloc( sizeof( hb_audio_t ), 1 );
303
304         audio_format  = vts->vtsi_mat->vts_audio_attr[i].audio_format;
305         lang_code     = vts->vtsi_mat->vts_audio_attr[i].lang_code;
306         lang_extension = vts->vtsi_mat->vts_audio_attr[i].code_extension;
307         audio_control =
308             vts->vts_pgcit->pgci_srp[pgc_id-1].pgc->audio_control[i];
309
310         if( !( audio_control & 0x8000 ) )
311         {
312             hb_log( "scan: audio channel is not active" );
313             free( audio );
314             continue;
315         }
316
317         position = ( audio_control & 0x7F00 ) >> 8;
318
319         switch( audio_format )
320         {
321             case 0x00:
322                 audio->id    = ( ( 0x80 + position ) << 8 ) | 0xbd;
323                 audio->config.in.codec = HB_ACODEC_AC3;
324                 break;
325
326             case 0x02:
327             case 0x03:
328                 audio->id    = 0xc0 + position;
329                 audio->config.in.codec = HB_ACODEC_MPGA;
330                 break;
331
332             case 0x04:
333                 audio->id    = ( ( 0xa0 + position ) << 8 ) | 0xbd;
334                 audio->config.in.codec = HB_ACODEC_LPCM;
335                 break;
336
337             case 0x06:
338                 audio->id    = ( ( 0x88 + position ) << 8 ) | 0xbd;
339                 audio->config.in.codec = HB_ACODEC_DCA;
340                 break;
341
342             default:
343                 audio->id    = 0;
344                 audio->config.in.codec = 0;
345                 hb_log( "scan: unknown audio codec (%x)",
346                         audio_format );
347                 break;
348         }
349         if( !audio->id )
350         {
351             continue;
352         }
353
354         /* Check for duplicate tracks */
355         audio_tmp = NULL;
356         for( j = 0; j < hb_list_count( title->list_audio ); j++ )
357         {
358             audio_tmp = hb_list_item( title->list_audio, j );
359             if( audio->id == audio_tmp->id )
360             {
361                 break;
362             }
363             audio_tmp = NULL;
364         }
365         if( audio_tmp )
366         {
367             hb_log( "scan: duplicate audio track" );
368             free( audio );
369             continue;
370         }
371
372         audio->config.lang.type = lang_extension;
373
374         lang = lang_for_code( vts->vtsi_mat->vts_audio_attr[i].lang_code );
375
376         snprintf( audio->config.lang.description, sizeof( audio->config.lang.description ), "%s (%s)",
377             strlen(lang->native_name) ? lang->native_name : lang->eng_name,
378             audio->config.in.codec == HB_ACODEC_AC3 ? "AC3" : ( audio->config.in.codec ==
379                 HB_ACODEC_DCA ? "DTS" : ( audio->config.in.codec ==
380                 HB_ACODEC_MPGA ? "MPEG" : "LPCM" ) ) );
381         snprintf( audio->config.lang.simple, sizeof( audio->config.lang.simple ), "%s",
382                   strlen(lang->native_name) ? lang->native_name : lang->eng_name );
383         snprintf( audio->config.lang.iso639_2, sizeof( audio->config.lang.iso639_2 ), "%s",
384                   lang->iso639_2);
385
386         switch( lang_extension )
387         {
388         case 0:
389         case 1:
390             break;
391         case 2:
392             strcat( audio->config.lang.description, " (Visually Impaired)" );
393             break;
394         case 3:
395             strcat( audio->config.lang.description, " (Director's Commentary 1)" );
396             break;
397         case 4:
398             strcat( audio->config.lang.description, " (Director's Commentary 2)" );
399             break;
400         default:
401             break;
402         }
403
404         hb_log( "scan: id=%x, lang=%s, 3cc=%s ext=%i", audio->id,
405                 audio->config.lang.description, audio->config.lang.iso639_2,
406                 lang_extension );
407
408         audio->config.in.track = i;
409         hb_list_add( title->list_audio, audio );
410     }
411
412     if( !hb_list_count( title->list_audio ) )
413     {
414         hb_log( "scan: ignoring title (no audio track)" );
415         goto fail;
416     }
417
418     memcpy( title->palette,
419             vts->vts_pgcit->pgci_srp[pgc_id-1].pgc->palette,
420             16 * sizeof( uint32_t ) );
421
422     /* Check for subtitles */
423     for( i = 0; i < vts->vtsi_mat->nr_of_vts_subp_streams; i++ )
424     {
425         hb_subtitle_t * subtitle;
426         int spu_control;
427         int position;
428         iso639_lang_t * lang;
429         int lang_extension = 0;
430
431         hb_log( "scan: checking subtitle %d", i + 1 );
432
433         spu_control =
434             vts->vts_pgcit->pgci_srp[pgc_id-1].pgc->subp_control[i];
435
436         if( !( spu_control & 0x80000000 ) )
437         {
438             hb_log( "scan: subtitle channel is not active" );
439             continue;
440         }
441
442         if( vts->vtsi_mat->vts_video_attr.display_aspect_ratio )
443         {
444             switch( vts->vtsi_mat->vts_video_attr.permitted_df )
445             {
446                 case 1:
447                     position = spu_control & 0xFF;
448                     break;
449                 case 2:
450                     position = ( spu_control >> 8 ) & 0xFF;
451                     break;
452                 default:
453                     position = ( spu_control >> 16 ) & 0xFF;
454             }
455         }
456         else
457         {
458             position = ( spu_control >> 24 ) & 0x7F;
459         }
460
461         lang_extension = vts->vtsi_mat->vts_subp_attr[i].code_extension;
462
463         lang = lang_for_code( vts->vtsi_mat->vts_subp_attr[i].lang_code );
464
465         subtitle = calloc( sizeof( hb_subtitle_t ), 1 );
466         subtitle->id = ( ( 0x20 + position ) << 8 ) | 0xbd;
467         snprintf( subtitle->lang, sizeof( subtitle->lang ), "%s",
468              strlen(lang->native_name) ? lang->native_name : lang->eng_name);
469         snprintf( subtitle->iso639_2, sizeof( subtitle->iso639_2 ), "%s",
470                   lang->iso639_2);
471
472         subtitle->type = lang_extension;
473
474         switch( lang_extension )
475         {  
476         case 0:
477             break;
478         case 1:
479             break;
480         case 2:
481             strcat( subtitle->lang, " (Caption with bigger size character)");
482             break;
483         case 3: 
484             strcat( subtitle->lang, " (Caption for Children)");
485             break;
486         case 4:
487             break;
488         case 5:
489             strcat( subtitle->lang, " (Closed Caption)");
490             break;
491         case 6:
492             strcat( subtitle->lang, " (Closed Caption with bigger size character)");
493             break;
494         case 7:
495             strcat( subtitle->lang, " (Closed Caption for Children)");
496             break;
497         case 8:
498             break;
499         case 9:
500             strcat( subtitle->lang, " (Forced Caption)");
501             break;
502         case 10:
503             break;
504         case 11:
505             break;
506         case 12:
507             break;
508         case 13:
509             strcat( subtitle->lang, " (Director's Commentary)");
510             break;
511         case 14:
512             strcat( subtitle->lang, " (Director's Commentary with bigger size character)");
513             break;
514         case 15:
515             strcat( subtitle->lang, " (Director's Commentary for Children)");
516         default:
517             break;
518         }
519
520         hb_log( "scan: id=%x, lang=%s, 3cc=%s", subtitle->id,
521                 subtitle->lang, subtitle->iso639_2 );
522
523         hb_list_add( title->list_subtitle, subtitle );
524     }
525
526     /* Chapters */
527     hb_log( "scan: title %d has %d chapters", t,
528             vts->vts_ptt_srpt->title[title->ttn-1].nr_of_ptts );
529     for( i = 0, c = 1;
530          i < vts->vts_ptt_srpt->title[title->ttn-1].nr_of_ptts; i++ )
531     {
532         int pgc_id_next, pgn_next;
533         pgc_t * pgc_next;
534
535         chapter = calloc( sizeof( hb_chapter_t ), 1 );
536         /* remember the on-disc chapter number */
537         chapter->index = i + 1;
538
539         pgc_id = vts->vts_ptt_srpt->title[title->ttn-1].ptt[i].pgcn;
540         pgn    = vts->vts_ptt_srpt->title[title->ttn-1].ptt[i].pgn;
541         d->pgc = vts->vts_pgcit->pgci_srp[pgc_id-1].pgc;
542
543         /* Start cell */
544         chapter->cell_start  = d->pgc->program_map[pgn-1] - 1;
545         chapter->block_start =
546             d->pgc->cell_playback[chapter->cell_start].first_sector;
547
548         /* End cell */
549         if( i != vts->vts_ptt_srpt->title[title->ttn-1].nr_of_ptts - 1 )
550         {
551             /* The cell before the starting cell of the next chapter,
552                or... */
553             pgc_id_next = vts->vts_ptt_srpt->title[title->ttn-1].ptt[i+1].pgcn;
554             pgn_next    = vts->vts_ptt_srpt->title[title->ttn-1].ptt[i+1].pgn;
555             pgc_next    = vts->vts_pgcit->pgci_srp[pgc_id_next-1].pgc;
556             chapter->cell_end = pgc_next->program_map[pgn_next-1] - 2;
557             if( chapter->cell_end < 0 )
558             {
559                 /* Huh? */
560                 free( chapter );
561                 continue;
562             }
563         }
564         else
565         {
566             /* ... the last cell of the title */
567             chapter->cell_end = title->cell_end;
568         }
569         chapter->block_end =
570             d->pgc->cell_playback[chapter->cell_end].last_sector;
571
572         /* Block count, duration */
573         pgc_id = vts->vts_ptt_srpt->title[title->ttn-1].ptt[0].pgcn;
574         pgn    = vts->vts_ptt_srpt->title[title->ttn-1].ptt[0].pgn;
575         d->pgc = vts->vts_pgcit->pgci_srp[pgc_id-1].pgc;
576         chapter->block_count = 0;
577         chapter->duration = 0;
578
579         d->cell_cur = chapter->cell_start;
580         while( d->cell_cur <= chapter->cell_end )
581         {
582 #define cp d->pgc->cell_playback[d->cell_cur]
583             chapter->block_count += cp.last_sector + 1 - cp.first_sector;
584             chapter->duration += 90LL * dvdtime2msec( &cp.playback_time );
585 #undef cp
586             FindNextCell( d );
587             d->cell_cur = d->cell_next;
588         }
589         hb_list_add( title->list_chapter, chapter );
590         c++;
591     }
592
593     /* The durations we get for chapters aren't precise. Scale them so
594        the total matches the title duration */
595     duration = 0;
596     for( i = 0; i < hb_list_count( title->list_chapter ); i++ )
597     {
598         chapter = hb_list_item( title->list_chapter, i );
599         duration += chapter->duration;
600     }
601     duration_correction = (float) title->duration / (float) duration;
602     for( i = 0; i < hb_list_count( title->list_chapter ); i++ )
603     {
604         int seconds;
605         chapter            = hb_list_item( title->list_chapter, i );
606         chapter->duration  = duration_correction * chapter->duration;
607         seconds            = ( chapter->duration + 45000 ) / 90000;
608         chapter->hours     = seconds / 3600;
609         chapter->minutes   = ( seconds % 3600 ) / 60;
610         chapter->seconds   = seconds % 60;
611
612         hb_log( "scan: chap %d c=%d->%d, b=%d->%d (%d), %lld ms",
613                 chapter->index, chapter->cell_start, chapter->cell_end,
614                 chapter->block_start, chapter->block_end,
615                 chapter->block_count, chapter->duration / 90 );
616     }
617
618     /* Get aspect. We don't get width/height/rate infos here as
619        they tend to be wrong */
620     switch( vts->vtsi_mat->vts_video_attr.display_aspect_ratio )
621     {
622         case 0:
623             title->container_aspect = 4. / 3.;
624             break;
625         case 3:
626             title->container_aspect = 16. / 9.;
627             break;
628         default:
629             hb_log( "scan: unknown aspect" );
630             goto fail;
631     }
632
633     hb_log( "scan: aspect = %g", title->aspect );
634
635     /* This title is ok so far */
636     goto cleanup;
637
638 fail:
639     hb_list_close( &title->list_audio );
640     free( title );
641     title = NULL;
642
643 cleanup:
644     if( vts ) ifoClose( vts );
645
646     return title;
647 }
648
649 /***********************************************************************
650  * hb_dvdread_start
651  ***********************************************************************
652  * Title and chapter start at 1
653  **********************************************************************/
654 static int hb_dvdread_start( hb_dvd_t * e, int title, int chapter )
655 {
656     hb_dvdread_t *d = &(e->dvdread);
657     int pgc_id, pgn;
658     int i;
659
660     /* Open the IFO and the VOBs for this title */
661     d->vts = d->vmg->tt_srpt->title[title-1].title_set_nr;
662     d->ttn = d->vmg->tt_srpt->title[title-1].vts_ttn;
663     if( !( d->ifo = ifoOpen( d->reader, d->vts ) ) )
664     {
665         hb_error( "dvd: ifoOpen failed for VTS %d", d->vts );
666         return 0;
667     }
668     if( !( d->file = DVDOpenFile( d->reader, d->vts,
669                                   DVD_READ_TITLE_VOBS ) ) )
670     {
671         hb_error( "dvd: DVDOpenFile failed for VTS %d", d->vts );
672         return 0;
673     }
674
675     /* Get title first and last blocks */
676     pgc_id         = d->ifo->vts_ptt_srpt->title[d->ttn-1].ptt[0].pgcn;
677     pgn            = d->ifo->vts_ptt_srpt->title[d->ttn-1].ptt[0].pgn;
678     d->pgc         = d->ifo->vts_pgcit->pgci_srp[pgc_id-1].pgc;
679     d->cell_start  = d->pgc->program_map[pgn - 1] - 1;
680     d->cell_end    = d->pgc->nr_of_cells - 1;
681     d->title_start = d->pgc->cell_playback[d->cell_start].first_sector;
682     d->title_end   = d->pgc->cell_playback[d->cell_end].last_sector;
683
684     /* Block count */
685     d->title_block_count = 0;
686     for( i = d->cell_start; i <= d->cell_end; i++ )
687     {
688         d->title_block_count += d->pgc->cell_playback[i].last_sector + 1 -
689             d->pgc->cell_playback[i].first_sector;
690     }
691
692     /* Get pgc for the current chapter */
693     pgc_id = d->ifo->vts_ptt_srpt->title[d->ttn-1].ptt[chapter-1].pgcn;
694     pgn    = d->ifo->vts_ptt_srpt->title[d->ttn-1].ptt[chapter-1].pgn;
695     d->pgc = d->ifo->vts_pgcit->pgci_srp[pgc_id-1].pgc;
696
697     /* Get the two first cells */
698     d->cell_cur = d->pgc->program_map[pgn-1] - 1;
699     FindNextCell( d );
700
701     d->block     = d->pgc->cell_playback[d->cell_cur].first_sector;
702     d->next_vobu = d->block;
703     d->pack_len  = 0;
704     d->cell_overlap = 0;
705     d->in_cell = 0;
706     d->in_sync = 2;
707
708     return 1;
709 }
710
711 /***********************************************************************
712  * hb_dvdread_stop
713  ***********************************************************************
714  *
715  **********************************************************************/
716 static void hb_dvdread_stop( hb_dvd_t * e )
717 {
718     hb_dvdread_t *d = &(e->dvdread);
719     if( d->ifo )
720     {
721         ifoClose( d->ifo );
722         d->ifo = NULL;
723     }
724     if( d->file )
725     {
726         DVDCloseFile( d->file );
727         d->file = NULL;
728     }
729 }
730
731 /***********************************************************************
732  * hb_dvdread_seek
733  ***********************************************************************
734  *
735  **********************************************************************/
736 static int hb_dvdread_seek( hb_dvd_t * e, float f )
737 {
738     hb_dvdread_t *d = &(e->dvdread);
739     int count, sizeCell;
740     int i;
741
742     count = f * d->title_block_count;
743
744     for( i = d->cell_start; i <= d->cell_end; i++ )
745     {
746         sizeCell = d->pgc->cell_playback[i].last_sector + 1 -
747             d->pgc->cell_playback[i].first_sector;
748
749         if( count < sizeCell )
750         {
751             d->cell_cur = i;
752             d->cur_cell_id = 0;
753             FindNextCell( d );
754
755             /* Now let hb_dvdread_read find the next VOBU */
756             d->next_vobu = d->pgc->cell_playback[i].first_sector + count;
757             d->pack_len  = 0;
758             break;
759         }
760
761         count -= sizeCell;
762     }
763
764     if( i > d->cell_end )
765     {
766         return 0;
767     }
768
769     /*
770      * Assume that we are in sync, even if we are not given that it is obvious
771      * that we are out of sync if we have just done a seek.
772      */
773     d->in_sync = 2;
774
775     return 1;
776 }
777
778
779 /***********************************************************************
780  * is_nav_pack
781  ***********************************************************************/
782 int is_nav_pack( unsigned char *buf )
783 {
784     /*
785      * The NAV Pack is comprised of the PCI Packet and DSI Packet, both
786      * of these start at known offsets and start with a special identifier.
787      *
788      * NAV = {
789      *  PCI = { 00 00 01 bf  # private stream header
790      *          ?? ??        # length
791      *          00           # substream
792      *          ...
793      *        }
794      *  DSI = { 00 00 01 bf  # private stream header
795      *          ?? ??        # length
796      *          01           # substream
797      *          ...
798      *        }
799      *
800      * The PCI starts at offset 0x26 into the sector, and the DSI starts at 0x400
801      *
802      * This information from: http://dvd.sourceforge.net/dvdinfo/
803      */
804     if( ( buf[0x26] == 0x00 &&      // PCI
805           buf[0x27] == 0x00 &&
806           buf[0x28] == 0x01 &&
807           buf[0x29] == 0xbf &&
808           buf[0x2c] == 0x00 ) &&
809         ( buf[0x400] == 0x00 &&     // DSI
810           buf[0x401] == 0x00 &&
811           buf[0x402] == 0x01 &&
812           buf[0x403] == 0xbf &&
813           buf[0x406] == 0x01 ) )
814     {
815         return ( 1 );
816     } else {
817         return ( 0 );
818     }
819 }
820
821
822 /***********************************************************************
823  * hb_dvdread_read
824  ***********************************************************************
825  *
826  **********************************************************************/
827 static int hb_dvdread_read( hb_dvd_t * e, hb_buffer_t * b )
828 {
829     hb_dvdread_t *d = &(e->dvdread);
830  top:
831     if( !d->pack_len )
832     {
833         /* New pack */
834         dsi_t dsi_pack;
835         int   error = 0;
836
837         // if we've just finished the last cell of the title we don't
838         // want to read another block because our next_vobu pointer
839         // is probably invalid. Just return 'no data' & our caller
840         // should check and discover we're at eof.
841         if ( d->cell_cur > d->cell_end )
842             return 0;
843
844         for( ;; )
845         {
846             int block, pack_len, next_vobu, read_retry;
847
848             for( read_retry = 0; read_retry < 3; read_retry++ )
849             {
850                 if( DVDReadBlocks( d->file, d->next_vobu, 1, b->data ) == 1 )
851                 {
852                     /*
853                      * Successful read.
854                      */
855                     break;
856                 } else {
857                     hb_log( "dvd: Read Error on blk %d, attempt %d",
858                             d->next_vobu, read_retry );
859                 }
860             }
861
862             if( read_retry == 3 )
863             {
864                 hb_log( "dvd: vobu read error blk %d - skipping to cell %d",
865                         d->next_vobu, d->cell_next );
866                 d->cell_cur  = d->cell_next;
867                 if ( d->cell_cur > d->cell_end )
868                     return 0;
869                 d->in_cell = 0;
870                 d->next_vobu = d->pgc->cell_playback[d->cell_cur].first_sector;
871                 FindNextCell( d );
872                 d->cell_overlap = 1;
873                 continue;
874             }
875
876             if ( !is_nav_pack( b->data ) ) {
877                 (d->next_vobu)++;
878                 if( d->in_sync == 1 ) {
879                     hb_log("dvd: Lost sync, searching for NAV pack at blk %d",
880                            d->next_vobu);
881                     d->in_sync = 0;
882                 }
883                 continue;
884             }
885
886             navRead_DSI( &dsi_pack, &b->data[DSI_START_BYTE] );
887
888             if ( d->in_sync == 0 && d->cur_cell_id &&
889                  (d->cur_vob_id != dsi_pack.dsi_gi.vobu_vob_idn ||
890                   d->cur_cell_id != dsi_pack.dsi_gi.vobu_c_idn ) )
891             {
892                 // We walked out of the cell we're supposed to be in.
893                 // If we're not at the start of our next cell go there.
894                 hb_log("dvd: left cell %d (%u,%u) for (%u,%u) at block %u",
895                        d->cell_cur, d->cur_vob_id, d->cur_cell_id,
896                        dsi_pack.dsi_gi.vobu_vob_idn, dsi_pack.dsi_gi.vobu_c_idn,
897                        d->next_vobu );
898                 if ( d->next_vobu != d->pgc->cell_playback[d->cell_next].first_sector )
899                 {
900                     d->next_vobu = d->pgc->cell_playback[d->cell_next].first_sector;
901                     d->cur_cell_id = 0;
902                     continue;
903                 }
904             }
905
906             block     = dsi_pack.dsi_gi.nv_pck_lbn;
907             pack_len  = dsi_pack.dsi_gi.vobu_ea;
908
909             // There are a total of 21 next vobu offsets (and 21 prev_vobu
910             // offsets) in the navpack SRI structure. The primary one is
911             // 'next_vobu' which is the offset (in dvd blocks) from the current
912             // block to the start of the next vobu. If the block at 'next_vobu'
913             // can't be read, 'next_video' is the offset to the vobu closest to it.
914             // The other 19 offsets are vobus at successively longer distances from
915             // the current block (this is so that a hardware player can do
916             // adaptive error recovery to skip over a bad spot on the disk). In all
917             // these offsets the high bit is set to indicate when it contains a
918             // valid offset. The next bit (2^30) is set to indicate that there's
919             // another valid offset in the SRI that's closer to the current block.
920             // A hardware player uses these bits to chose the closest valid offset
921             // and uses that as its next vobu. (Some mastering schemes appear to
922             // put a bogus offset in next_vobu with the 2^30 bit set & the
923             // correct offset in next_video. This works fine in hardware players
924             // but will mess up software that doesn't implement the full next
925             // vobu decision logic.) In addition to the flag bits there's a
926             // reserved value of the offset that indicates 'no next vobu' (which
927             // indicates the end of a cell). But having no next vobu pointer with a
928             // 'valid' bit set also indicates end of cell. Different mastering
929             // schemes seem to use all possible combinations of the flag bits
930             // and reserved values to indicate end of cell so we have to check
931             // them all or we'll get a disk read error from following an
932             // invalid offset.
933             uint32_t next_ptr = dsi_pack.vobu_sri.next_vobu;
934             if ( ( next_ptr & ( 1 << 31 ) ) == 0  ||
935                  ( next_ptr & ( 1 << 30 ) ) != 0 ||
936                  ( next_ptr & 0x3fffffff ) == 0x3fffffff )
937             {
938                 next_ptr = dsi_pack.vobu_sri.next_video;
939                 if ( ( next_ptr & ( 1 << 31 ) ) == 0 ||
940                      ( next_ptr & 0x3fffffff ) == 0x3fffffff )
941                 {
942                     // don't have a valid forward pointer - assume end-of-cell
943                     d->block     = block;
944                     d->pack_len  = pack_len;
945                     break;
946                 }
947             }
948             next_vobu = block + ( next_ptr & 0x3fffffff );
949
950             if( pack_len >  0    &&
951                 pack_len <  1024 &&
952                 block    >= d->next_vobu &&
953                 ( block <= d->title_start + d->title_block_count ||
954                   block <= d->title_end ) )
955             {
956                 d->block     = block;
957                 d->pack_len  = pack_len;
958                 d->next_vobu = next_vobu;
959                 break;
960             }
961
962             /* Wasn't a valid VOBU, try next block */
963             if( ++error > 1024 )
964             {
965                 hb_log( "dvd: couldn't find a VOBU after 1024 blocks" );
966                 return 0;
967             }
968
969             (d->next_vobu)++;
970         }
971
972         if( d->in_sync == 0 || d->in_sync == 2 )
973         {
974             if( d->in_sync == 0 )
975             {
976                 hb_log( "dvd: In sync with DVD at block %d", d->block );
977             }
978             d->in_sync = 1;
979         }
980
981         // Revert the cell overlap, and check for a chapter break
982         // If this cell is zero length (prev_vobu & next_vobu both
983         // set to END_OF_CELL) we need to check for beginning of
984         // cell before checking for end or we'll advance to the next
985         // cell too early and fail to generate a chapter mark when this
986         // cell starts a chapter.
987         if( ( dsi_pack.vobu_sri.prev_vobu & (1 << 31 ) ) == 0 ||
988             ( dsi_pack.vobu_sri.prev_vobu & 0x3fffffff ) == 0x3fffffff )
989         {
990             // A vobu that's not at the start of a cell can have an
991             // EOC prev pointer (this seems to be associated with some
992             // sort of drm). The rest of the content in the cell may be
993             // booby-trapped so treat this like an end-of-cell rather
994             // than a beginning of cell.
995             if ( d->pgc->cell_playback[d->cell_cur].first_sector < dsi_pack.dsi_gi.nv_pck_lbn &&
996                  d->pgc->cell_playback[d->cell_cur].last_sector >= dsi_pack.dsi_gi.nv_pck_lbn )
997             {
998                 hb_log( "dvd: null prev_vobu in cell %d at block %d", d->cell_cur,
999                         d->block );
1000                 // treat like end-of-cell then go directly to start of next cell.
1001                 d->cell_cur  = d->cell_next;
1002                 d->in_cell = 0;
1003                 d->next_vobu = d->pgc->cell_playback[d->cell_cur].first_sector;
1004                 FindNextCell( d );
1005                 d->cell_overlap = 1;
1006                 goto top;
1007             }
1008             else
1009             {
1010                 if ( d->block != d->pgc->cell_playback[d->cell_cur].first_sector )
1011                 {
1012                     hb_log( "dvd: beginning of cell %d at block %d", d->cell_cur,
1013                            d->block );
1014                 }
1015                 if( d->in_cell )
1016                 {
1017                     hb_error( "dvd: assuming missed end of cell %d", d->cell_cur );
1018                     d->cell_cur  = d->cell_next;
1019                     d->next_vobu = d->pgc->cell_playback[d->cell_cur].first_sector;
1020                     FindNextCell( d );
1021                     d->cell_overlap = 1;
1022                     d->in_cell = 0;
1023                 } else {
1024                     d->in_cell = 1;
1025                 }
1026                 d->cur_vob_id = dsi_pack.dsi_gi.vobu_vob_idn;
1027                 d->cur_cell_id = dsi_pack.dsi_gi.vobu_c_idn;
1028
1029                 if( d->cell_overlap )
1030                 {
1031                     b->new_chap = hb_dvdread_is_break( d );
1032                     d->cell_overlap = 0;
1033                 }
1034             }
1035         }
1036
1037         if( ( dsi_pack.vobu_sri.next_vobu & (1 << 31 ) ) == 0 ||
1038             ( dsi_pack.vobu_sri.next_vobu & 0x3fffffff ) == 0x3fffffff )
1039         {
1040             if ( d->block <= d->pgc->cell_playback[d->cell_cur].first_sector ||
1041                  d->block > d->pgc->cell_playback[d->cell_cur].last_sector )
1042             {
1043                 hb_log( "dvd: end of cell %d at block %d", d->cell_cur,
1044                         d->block );
1045             }
1046             d->cell_cur  = d->cell_next;
1047             d->in_cell = 0;
1048             d->next_vobu = d->pgc->cell_playback[d->cell_cur].first_sector;
1049             FindNextCell( d );
1050             d->cell_overlap = 1;
1051
1052         }
1053     }
1054     else
1055     {
1056         if( DVDReadBlocks( d->file, d->block, 1, b->data ) != 1 )
1057         {
1058             // this may be a real DVD error or may be DRM. Either way
1059             // we don't want to quit because of one bad block so set
1060             // things up so we'll advance to the next vobu and recurse.
1061             hb_error( "dvd: DVDReadBlocks failed (%d), skipping to vobu %u",
1062                       d->block, d->next_vobu );
1063             d->pack_len = 0;
1064             goto top;  /* XXX need to restructure this routine & avoid goto */
1065         }
1066         d->pack_len--;
1067     }
1068
1069     d->block++;
1070
1071     return 1;
1072 }
1073
1074 /***********************************************************************
1075  * hb_dvdread_chapter
1076  ***********************************************************************
1077  * Returns in which chapter the next block to be read is.
1078  * Chapter numbers start at 1.
1079  **********************************************************************/
1080 static int hb_dvdread_chapter( hb_dvd_t * e )
1081 {
1082     hb_dvdread_t *d = &(e->dvdread);
1083     int     i;
1084     int     pgc_id, pgn;
1085     int     nr_of_ptts = d->ifo->vts_ptt_srpt->title[d->ttn-1].nr_of_ptts;
1086     pgc_t * pgc;
1087
1088     for( i = nr_of_ptts - 1;
1089          i >= 0;
1090          i-- )
1091     {
1092         /* Get pgc for chapter (i+1) */
1093         pgc_id = d->ifo->vts_ptt_srpt->title[d->ttn-1].ptt[i].pgcn;
1094         pgn    = d->ifo->vts_ptt_srpt->title[d->ttn-1].ptt[i].pgn;
1095         pgc    = d->ifo->vts_pgcit->pgci_srp[pgc_id-1].pgc;
1096
1097         if( d->cell_cur - d->cell_overlap >= pgc->program_map[pgn-1] - 1 &&
1098             d->cell_cur - d->cell_overlap <= pgc->nr_of_cells - 1 )
1099         {
1100             /* We are in this chapter */
1101             return i + 1;
1102         }
1103     }
1104
1105     /* End of title */
1106     return -1;
1107 }
1108
1109 /***********************************************************************
1110  * hb_dvdread_is_break
1111  ***********************************************************************
1112  * Returns chapter number if the current block is a new chapter start
1113  **********************************************************************/
1114 static int hb_dvdread_is_break( hb_dvdread_t * d )
1115 {
1116     int     i;
1117     int     pgc_id, pgn;
1118     int     nr_of_ptts = d->ifo->vts_ptt_srpt->title[d->ttn-1].nr_of_ptts;
1119     pgc_t * pgc;
1120     int     cell;
1121
1122     for( i = nr_of_ptts - 1;
1123          i > 0;
1124          i-- )
1125     {
1126         /* Get pgc for chapter (i+1) */
1127         pgc_id = d->ifo->vts_ptt_srpt->title[d->ttn-1].ptt[i].pgcn;
1128         pgn    = d->ifo->vts_ptt_srpt->title[d->ttn-1].ptt[i].pgn;
1129         pgc    = d->ifo->vts_pgcit->pgci_srp[pgc_id-1].pgc;
1130         cell   = pgc->program_map[pgn-1] - 1;
1131
1132         if( cell <= d->cell_start )
1133             break;
1134
1135         // This must not match against the start cell.
1136         if( pgc->cell_playback[cell].first_sector == d->block && cell != d->cell_start )
1137         {
1138             return i + 1;
1139         }
1140     }
1141
1142     return 0;
1143 }
1144
1145 /***********************************************************************
1146  * hb_dvdread_close
1147  ***********************************************************************
1148  * Closes and frees everything
1149  **********************************************************************/
1150 static void hb_dvdread_close( hb_dvd_t ** _d )
1151 {
1152     hb_dvdread_t * d = &((*_d)->dvdread);
1153
1154     if( d->vmg )
1155     {
1156         ifoClose( d->vmg );
1157     }
1158     if( d->reader )
1159     {
1160         DVDClose( d->reader );
1161     }
1162
1163     free( d );
1164     *_d = NULL;
1165 }
1166
1167 /***********************************************************************
1168  * hb_dvdread_angle_count
1169  ***********************************************************************
1170  * Returns the number of angles supported.  We do not support angles
1171  * with dvdread
1172  **********************************************************************/
1173 static int hb_dvdread_angle_count( hb_dvd_t * d )
1174 {
1175     return 1;
1176 }
1177
1178 /***********************************************************************
1179  * hb_dvdread_set_angle
1180  ***********************************************************************
1181  * Sets the angle to read.  Not supported with dvdread
1182  **********************************************************************/
1183 static void hb_dvdread_set_angle( hb_dvd_t * d, int angle )
1184 {
1185 }
1186
1187 /***********************************************************************
1188  * FindNextCell
1189  ***********************************************************************
1190  * Assumes pgc and cell_cur are correctly set, and sets cell_next to the
1191  * cell to be read when we will be done with cell_cur.
1192  **********************************************************************/
1193 static void FindNextCell( hb_dvdread_t * d )
1194 {
1195     int i = 0;
1196
1197     if( d->pgc->cell_playback[d->cell_cur].block_type ==
1198             BLOCK_TYPE_ANGLE_BLOCK )
1199     {
1200
1201         while( d->pgc->cell_playback[d->cell_cur+i].block_mode !=
1202                    BLOCK_MODE_LAST_CELL )
1203         {
1204              i++;
1205         }
1206         d->cell_next = d->cell_cur + i + 1;
1207         hb_log( "dvd: Skipping multi-angle cells %d-%d",
1208                 d->cell_cur,
1209                 d->cell_next - 1 );
1210     }
1211     else
1212     {
1213         d->cell_next = d->cell_cur + 1;
1214     }
1215 }
1216
1217 /***********************************************************************
1218  * dvdtime2msec
1219  ***********************************************************************
1220  * From lsdvd
1221  **********************************************************************/
1222 static int dvdtime2msec(dvd_time_t * dt)
1223 {
1224     double frames_per_s[4] = {-1.0, 25.00, -1.0, 29.97};
1225     double fps = frames_per_s[(dt->frame_u & 0xc0) >> 6];
1226     long   ms;
1227     ms  = (((dt->hour &   0xf0) >> 3) * 5 + (dt->hour   & 0x0f)) * 3600000;
1228     ms += (((dt->minute & 0xf0) >> 3) * 5 + (dt->minute & 0x0f)) * 60000;
1229     ms += (((dt->second & 0xf0) >> 3) * 5 + (dt->second & 0x0f)) * 1000;
1230
1231     if( fps > 0 )
1232     {
1233         ms += ((dt->frame_u & 0x30) >> 3) * 5 +
1234               (dt->frame_u & 0x0f) * 1000.0 / fps;
1235     }
1236
1237     return ms;
1238 }
1239
1240 char * hb_dvd_name( char * path )
1241 {
1242     return dvd_methods->name(path);
1243 }
1244
1245 hb_dvd_t * hb_dvd_init( char * path )
1246 {
1247     return dvd_methods->init(path);
1248 }
1249
1250 int hb_dvd_title_count( hb_dvd_t * d )
1251 {
1252     return dvd_methods->title_count(d);
1253 }
1254
1255 hb_title_t * hb_dvd_title_scan( hb_dvd_t * d, int t )
1256 {
1257     return dvd_methods->title_scan(d, t);
1258 }
1259
1260 int hb_dvd_start( hb_dvd_t * d, int title, int chapter )
1261 {
1262     return dvd_methods->start(d, title, chapter);
1263 }
1264
1265 void hb_dvd_stop( hb_dvd_t * d )
1266 {
1267     dvd_methods->stop(d);
1268 }
1269
1270 int hb_dvd_seek( hb_dvd_t * d, float f )
1271 {
1272     return dvd_methods->seek(d, f);
1273 }
1274
1275 int hb_dvd_read( hb_dvd_t * d, hb_buffer_t * b )
1276 {
1277     return dvd_methods->read(d, b);
1278 }
1279
1280 int hb_dvd_chapter( hb_dvd_t * d )
1281 {
1282     return dvd_methods->chapter(d);
1283 }
1284
1285 void hb_dvd_close( hb_dvd_t ** _d )
1286 {
1287     dvd_methods->close(_d);
1288 }
1289
1290 int hb_dvd_angle_count( hb_dvd_t * d )
1291 {
1292     return dvd_methods->angle_count(d);
1293 }
1294
1295 void hb_dvd_set_angle( hb_dvd_t * d, int angle )
1296 {
1297     dvd_methods->set_angle(d, angle);
1298 }
1299
1300 // hb_dvd_set_dvdnav must only be called when no dvd source is open
1301 // it rips the rug out from under things so be careful
1302 void hb_dvd_set_dvdnav( int enable )
1303 {
1304     if (enable)
1305         dvd_methods = hb_dvdnav_methods();
1306     else
1307         dvd_methods = hb_dvdread_methods();
1308 }
1309