OSDN Git Service

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