OSDN Git Service

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