OSDN Git Service

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