OSDN Git Service

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