OSDN Git Service

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