OSDN Git Service

bump ffmpeg from git-185a155 to git-0b32da9
[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, uint64_t min_duration );
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, uint64_t min_duration )
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=%"PRIu64"->%"PRIu64", "
303             "%"PRIu64" 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 < min_duration )
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=%"PRIu64"->%"PRIu64" (%"PRIu64"), %"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 = 1; read_retry < 1024; read_retry++ )
865             {
866                 if( DVDReadBlocks( d->file, d->next_vobu, 1, b->data ) == 1 )
867                 {
868                     /*
869                      * Successful read.
870                      */
871                     if( read_retry > 1 && !is_nav_pack( b->data) )
872                     {
873                         // But wasn't a nav pack, so carry on looking
874                         read_retry = 1;
875                         d->next_vobu++;
876                         continue;
877                     }
878                     break;
879                 } else {  
880                     // First retry the same block, then try the next one, 
881                     // adjust the skip increment upwards so that we can skip
882                     // large sections of bad blocks more efficiently (at the
883                     // cost of some missed good blocks at the end).
884                     hb_log( "dvd: vobu read error blk %d - skipping to next blk incr %d",
885                             d->next_vobu, (read_retry * 10));
886                     d->next_vobu += (read_retry * 10);
887                 }
888                 
889             }
890
891             if( read_retry == 1024 )
892             {
893                 // That's too many bad blocks, jump to the start of the
894                 // next cell.
895                 hb_log( "dvd: vobu read error blk %d - skipping to cell %d",
896                         d->next_vobu, d->cell_next );
897                 d->cell_cur  = d->cell_next;
898                 if ( d->cell_cur > d->cell_end )
899                     return 0;
900                 d->in_cell = 0;
901                 d->next_vobu = d->pgc->cell_playback[d->cell_cur].first_sector;
902                 FindNextCell( d );
903                 d->cell_overlap = 1;
904                 continue;
905             }
906
907             if ( !is_nav_pack( b->data ) ) {
908                 (d->next_vobu)++;
909                 if( d->in_sync == 1 ) {
910                     hb_log("dvd: Lost sync, searching for NAV pack at blk %d",
911                            d->next_vobu);
912                     d->in_sync = 0;
913                 } 
914                 continue;
915             }
916
917             navRead_DSI( &dsi_pack, &b->data[DSI_START_BYTE] );
918
919             if ( d->in_sync == 0 && d->cur_cell_id &&
920                  (d->cur_vob_id != dsi_pack.dsi_gi.vobu_vob_idn ||
921                   d->cur_cell_id != dsi_pack.dsi_gi.vobu_c_idn ) )
922             {
923                 // We walked out of the cell we're supposed to be in.
924                 // If we're not at the start of our next cell go there.
925                 hb_log("dvd: left cell %d (%u,%u) for (%u,%u) at block %u",
926                        d->cell_cur, d->cur_vob_id, d->cur_cell_id,
927                        dsi_pack.dsi_gi.vobu_vob_idn, dsi_pack.dsi_gi.vobu_c_idn,
928                        d->next_vobu );
929                 if ( d->next_vobu != d->pgc->cell_playback[d->cell_next].first_sector )
930                 {
931                     d->next_vobu = d->pgc->cell_playback[d->cell_next].first_sector;
932                     d->cur_cell_id = 0;
933                     continue;
934                 }
935             }
936
937             block     = dsi_pack.dsi_gi.nv_pck_lbn;
938             pack_len  = dsi_pack.dsi_gi.vobu_ea;
939
940             // There are a total of 21 next vobu offsets (and 21 prev_vobu
941             // offsets) in the navpack SRI structure. The primary one is
942             // 'next_vobu' which is the offset (in dvd blocks) from the current
943             // block to the start of the next vobu. If the block at 'next_vobu'
944             // can't be read, 'next_video' is the offset to the vobu closest to it.
945             // The other 19 offsets are vobus at successively longer distances from
946             // the current block (this is so that a hardware player can do
947             // adaptive error recovery to skip over a bad spot on the disk). In all
948             // these offsets the high bit is set to indicate when it contains a
949             // valid offset. The next bit (2^30) is set to indicate that there's
950             // another valid offset in the SRI that's closer to the current block.
951             // A hardware player uses these bits to chose the closest valid offset
952             // and uses that as its next vobu. (Some mastering schemes appear to
953             // put a bogus offset in next_vobu with the 2^30 bit set & the
954             // correct offset in next_video. This works fine in hardware players
955             // but will mess up software that doesn't implement the full next
956             // vobu decision logic.) In addition to the flag bits there's a
957             // reserved value of the offset that indicates 'no next vobu' (which
958             // indicates the end of a cell). But having no next vobu pointer with a
959             // 'valid' bit set also indicates end of cell. Different mastering
960             // schemes seem to use all possible combinations of the flag bits
961             // and reserved values to indicate end of cell so we have to check
962             // them all or we'll get a disk read error from following an
963             // invalid offset.
964             uint32_t next_ptr = dsi_pack.vobu_sri.next_vobu;
965             if ( ( next_ptr & ( 1 << 31 ) ) == 0  ||
966                  ( next_ptr & ( 1 << 30 ) ) != 0 ||
967                  ( next_ptr & 0x3fffffff ) == 0x3fffffff )
968             {
969                 next_ptr = dsi_pack.vobu_sri.next_video;
970                 if ( ( next_ptr & ( 1 << 31 ) ) == 0 ||
971                      ( next_ptr & 0x3fffffff ) == 0x3fffffff )
972                 {
973                     // don't have a valid forward pointer - assume end-of-cell
974                     d->block     = block;
975                     d->pack_len  = pack_len;
976                     break;
977                 }
978             }
979             next_vobu = block + ( next_ptr & 0x3fffffff );
980
981             if( pack_len >  0    &&
982                 pack_len <  1024 &&
983                 block    >= d->next_vobu &&
984                 ( block <= d->title_start + d->title_block_count ||
985                   block <= d->title_end ) )
986             {
987                 d->block     = block;
988                 d->pack_len  = pack_len;
989                 d->next_vobu = next_vobu;
990                 break;
991             }
992
993             /* Wasn't a valid VOBU, try next block */
994             if( ++error > 1024 )
995             {
996                 hb_log( "dvd: couldn't find a VOBU after 1024 blocks" );
997                 return 0;
998             }
999
1000             (d->next_vobu)++;
1001         }
1002
1003         if( d->in_sync == 0 || d->in_sync == 2 )
1004         {
1005             if( d->in_sync == 0 )
1006             {
1007                 hb_log( "dvd: In sync with DVD at block %d", d->block );
1008             }
1009             d->in_sync = 1;
1010         }
1011
1012         // Revert the cell overlap, and check for a chapter break
1013         // If this cell is zero length (prev_vobu & next_vobu both
1014         // set to END_OF_CELL) we need to check for beginning of
1015         // cell before checking for end or we'll advance to the next
1016         // cell too early and fail to generate a chapter mark when this
1017         // cell starts a chapter.
1018         if( ( dsi_pack.vobu_sri.prev_vobu & (1 << 31 ) ) == 0 ||
1019             ( dsi_pack.vobu_sri.prev_vobu & 0x3fffffff ) == 0x3fffffff )
1020         {
1021             // A vobu that's not at the start of a cell can have an
1022             // EOC prev pointer (this seems to be associated with some
1023             // sort of drm). The rest of the content in the cell may be
1024             // booby-trapped so treat this like an end-of-cell rather
1025             // than a beginning of cell.
1026             if ( d->pgc->cell_playback[d->cell_cur].first_sector < dsi_pack.dsi_gi.nv_pck_lbn &&
1027                  d->pgc->cell_playback[d->cell_cur].last_sector >= dsi_pack.dsi_gi.nv_pck_lbn )
1028             {
1029                 hb_log( "dvd: null prev_vobu in cell %d at block %d", d->cell_cur,
1030                         d->block );
1031                 // treat like end-of-cell then go directly to start of next cell.
1032                 d->cell_cur  = d->cell_next;
1033                 d->in_cell = 0;
1034                 d->next_vobu = d->pgc->cell_playback[d->cell_cur].first_sector;
1035                 FindNextCell( d );
1036                 d->cell_overlap = 1;
1037                 goto top;
1038             }
1039             else
1040             {
1041                 if ( d->block != d->pgc->cell_playback[d->cell_cur].first_sector )
1042                 {
1043                     hb_log( "dvd: beginning of cell %d at block %d", d->cell_cur,
1044                            d->block );
1045                 }
1046                 if( d->in_cell )
1047                 {
1048                     hb_error( "dvd: assuming missed end of cell %d at block %d", d->cell_cur, d->block );
1049                     d->cell_cur  = d->cell_next;
1050                     d->next_vobu = d->pgc->cell_playback[d->cell_cur].first_sector;
1051                     FindNextCell( d );
1052                     d->cell_overlap = 1;
1053                     d->in_cell = 0;
1054                 } else {
1055                     d->in_cell = 1;
1056                 }
1057                 d->cur_vob_id = dsi_pack.dsi_gi.vobu_vob_idn;
1058                 d->cur_cell_id = dsi_pack.dsi_gi.vobu_c_idn;
1059
1060                 if( d->cell_overlap )
1061                 {
1062                     b->new_chap = hb_dvdread_is_break( d );
1063                     d->cell_overlap = 0;
1064                 }
1065             }
1066         }
1067
1068         if( ( dsi_pack.vobu_sri.next_vobu & (1 << 31 ) ) == 0 ||
1069             ( dsi_pack.vobu_sri.next_vobu & 0x3fffffff ) == 0x3fffffff )
1070         {
1071             if ( d->block <= d->pgc->cell_playback[d->cell_cur].first_sector ||
1072                  d->block > d->pgc->cell_playback[d->cell_cur].last_sector )
1073             {
1074                 hb_log( "dvd: end of cell %d at block %d", d->cell_cur,
1075                         d->block );
1076             }
1077             d->cell_cur  = d->cell_next;
1078             d->in_cell = 0;
1079             d->next_vobu = d->pgc->cell_playback[d->cell_cur].first_sector;
1080             FindNextCell( d );
1081             d->cell_overlap = 1;
1082
1083         }
1084     }
1085     else
1086     {
1087         if( DVDReadBlocks( d->file, d->block, 1, b->data ) != 1 )
1088         {
1089             // this may be a real DVD error or may be DRM. Either way
1090             // we don't want to quit because of one bad block so set
1091             // things up so we'll advance to the next vobu and recurse.
1092             hb_error( "dvd: DVDReadBlocks failed (%d), skipping to vobu %u",
1093                       d->block, d->next_vobu );
1094             d->pack_len = 0;
1095             goto top;  /* XXX need to restructure this routine & avoid goto */
1096         }
1097         d->pack_len--;
1098     }
1099
1100     d->block++;
1101
1102     return 1;
1103 }
1104
1105 /***********************************************************************
1106  * hb_dvdread_chapter
1107  ***********************************************************************
1108  * Returns in which chapter the next block to be read is.
1109  * Chapter numbers start at 1.
1110  **********************************************************************/
1111 static int hb_dvdread_chapter( hb_dvd_t * e )
1112 {
1113     hb_dvdread_t *d = &(e->dvdread);
1114     int     i;
1115     int     pgc_id, pgn;
1116     int     nr_of_ptts = d->ifo->vts_ptt_srpt->title[d->ttn-1].nr_of_ptts;
1117     pgc_t * pgc;
1118
1119     for( i = nr_of_ptts - 1;
1120          i >= 0;
1121          i-- )
1122     {
1123         /* Get pgc for chapter (i+1) */
1124         pgc_id = d->ifo->vts_ptt_srpt->title[d->ttn-1].ptt[i].pgcn;
1125         pgn    = d->ifo->vts_ptt_srpt->title[d->ttn-1].ptt[i].pgn;
1126         pgc    = d->ifo->vts_pgcit->pgci_srp[pgc_id-1].pgc;
1127
1128         if( d->cell_cur - d->cell_overlap >= pgc->program_map[pgn-1] - 1 &&
1129             d->cell_cur - d->cell_overlap <= pgc->nr_of_cells - 1 )
1130         {
1131             /* We are in this chapter */
1132             return i + 1;
1133         }
1134     }
1135
1136     /* End of title */
1137     return -1;
1138 }
1139
1140 /***********************************************************************
1141  * hb_dvdread_is_break
1142  ***********************************************************************
1143  * Returns chapter number if the current block is a new chapter start
1144  **********************************************************************/
1145 static int hb_dvdread_is_break( hb_dvdread_t * d )
1146 {
1147     int     i;
1148     int     pgc_id, pgn;
1149     int     nr_of_ptts = d->ifo->vts_ptt_srpt->title[d->ttn-1].nr_of_ptts;
1150     pgc_t * pgc;
1151     int     cell;
1152
1153     for( i = nr_of_ptts - 1;
1154          i > 0;
1155          i-- )
1156     {
1157         /* Get pgc for chapter (i+1) */
1158         pgc_id = d->ifo->vts_ptt_srpt->title[d->ttn-1].ptt[i].pgcn;
1159         pgn    = d->ifo->vts_ptt_srpt->title[d->ttn-1].ptt[i].pgn;
1160         pgc    = d->ifo->vts_pgcit->pgci_srp[pgc_id-1].pgc;
1161         cell   = pgc->program_map[pgn-1] - 1;
1162
1163         if( cell <= d->cell_start )
1164             break;
1165
1166         // This must not match against the start cell.
1167         if( pgc->cell_playback[cell].first_sector == d->block && cell != d->cell_start )
1168         {
1169             return i + 1;
1170         }
1171     }
1172
1173     return 0;
1174 }
1175
1176 /***********************************************************************
1177  * hb_dvdread_close
1178  ***********************************************************************
1179  * Closes and frees everything
1180  **********************************************************************/
1181 static void hb_dvdread_close( hb_dvd_t ** _d )
1182 {
1183     hb_dvdread_t * d = &((*_d)->dvdread);
1184
1185     if( d->vmg )
1186     {
1187         ifoClose( d->vmg );
1188     }
1189     if( d->reader )
1190     {
1191         DVDClose( d->reader );
1192     }
1193
1194     free( d );
1195     *_d = NULL;
1196 }
1197
1198 /***********************************************************************
1199  * hb_dvdread_angle_count
1200  ***********************************************************************
1201  * Returns the number of angles supported.  We do not support angles
1202  * with dvdread
1203  **********************************************************************/
1204 static int hb_dvdread_angle_count( hb_dvd_t * d )
1205 {
1206     return 1;
1207 }
1208
1209 /***********************************************************************
1210  * hb_dvdread_set_angle
1211  ***********************************************************************
1212  * Sets the angle to read.  Not supported with dvdread
1213  **********************************************************************/
1214 static void hb_dvdread_set_angle( hb_dvd_t * d, int angle )
1215 {
1216 }
1217
1218 /***********************************************************************
1219  * FindNextCell
1220  ***********************************************************************
1221  * Assumes pgc and cell_cur are correctly set, and sets cell_next to the
1222  * cell to be read when we will be done with cell_cur.
1223  **********************************************************************/
1224 static void FindNextCell( hb_dvdread_t * d )
1225 {
1226     int i = 0;
1227
1228     if( d->pgc->cell_playback[d->cell_cur].block_type ==
1229             BLOCK_TYPE_ANGLE_BLOCK )
1230     {
1231
1232         while( d->pgc->cell_playback[d->cell_cur+i].block_mode !=
1233                    BLOCK_MODE_LAST_CELL )
1234         {
1235              i++;
1236         }
1237         d->cell_next = d->cell_cur + i + 1;
1238         hb_log( "dvd: Skipping multi-angle cells %d-%d",
1239                 d->cell_cur,
1240                 d->cell_next - 1 );
1241     }
1242     else
1243     {
1244         d->cell_next = d->cell_cur + 1;
1245     }
1246 }
1247
1248 /***********************************************************************
1249  * dvdtime2msec
1250  ***********************************************************************
1251  * From lsdvd
1252  **********************************************************************/
1253 static int dvdtime2msec(dvd_time_t * dt)
1254 {
1255     double frames_per_s[4] = {-1.0, 25.00, -1.0, 29.97};
1256     double fps = frames_per_s[(dt->frame_u & 0xc0) >> 6];
1257     long   ms;
1258     ms  = (((dt->hour &   0xf0) >> 3) * 5 + (dt->hour   & 0x0f)) * 3600000;
1259     ms += (((dt->minute & 0xf0) >> 3) * 5 + (dt->minute & 0x0f)) * 60000;
1260     ms += (((dt->second & 0xf0) >> 3) * 5 + (dt->second & 0x0f)) * 1000;
1261
1262     if( fps > 0 )
1263     {
1264         ms += ((dt->frame_u & 0x30) >> 3) * 5 +
1265               (dt->frame_u & 0x0f) * 1000.0 / fps;
1266     }
1267
1268     return ms;
1269 }
1270
1271 char * hb_dvd_name( char * path )
1272 {
1273     return dvd_methods->name(path);
1274 }
1275
1276 hb_dvd_t * hb_dvd_init( char * path )
1277 {
1278     return dvd_methods->init(path);
1279 }
1280
1281 int hb_dvd_title_count( hb_dvd_t * d )
1282 {
1283     return dvd_methods->title_count(d);
1284 }
1285
1286 hb_title_t * hb_dvd_title_scan( hb_dvd_t * d, int t, uint64_t min_duration )
1287 {
1288     return dvd_methods->title_scan(d, t, min_duration);
1289 }
1290
1291 int hb_dvd_start( hb_dvd_t * d, hb_title_t *title, int chapter )
1292 {
1293     return dvd_methods->start(d, title, chapter);
1294 }
1295
1296 void hb_dvd_stop( hb_dvd_t * d )
1297 {
1298     dvd_methods->stop(d);
1299 }
1300
1301 int hb_dvd_seek( hb_dvd_t * d, float f )
1302 {
1303     return dvd_methods->seek(d, f);
1304 }
1305
1306 int hb_dvd_read( hb_dvd_t * d, hb_buffer_t * b )
1307 {
1308     return dvd_methods->read(d, b);
1309 }
1310
1311 int hb_dvd_chapter( hb_dvd_t * d )
1312 {
1313     return dvd_methods->chapter(d);
1314 }
1315
1316 void hb_dvd_close( hb_dvd_t ** _d )
1317 {
1318     dvd_methods->close(_d);
1319 }
1320
1321 int hb_dvd_angle_count( hb_dvd_t * d )
1322 {
1323     return dvd_methods->angle_count(d);
1324 }
1325
1326 void hb_dvd_set_angle( hb_dvd_t * d, int angle )
1327 {
1328     dvd_methods->set_angle(d, angle);
1329 }
1330
1331 int hb_dvd_main_feature( hb_dvd_t * d, hb_list_t * list_title )
1332 {
1333     return dvd_methods->main_feature(d, list_title);
1334 }
1335
1336 // hb_dvd_set_dvdnav must only be called when no dvd source is open
1337 // it rips the rug out from under things so be careful
1338 void hb_dvd_set_dvdnav( int enable )
1339 {
1340     if (enable)
1341         dvd_methods = hb_dvdnav_methods();
1342     else
1343         dvd_methods = hb_dvdread_methods();
1344 }
1345