OSDN Git Service

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