OSDN Git Service

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