OSDN Git Service

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