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