OSDN Git Service

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