OSDN Git Service

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