OSDN Git Service

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