OSDN Git Service

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