Improvements to preferences
[vlc.git] / modules / access / dvdread.c
1 /*****************************************************************************
2  * dvdread.c : DvdRead input module for vlc
3  *****************************************************************************
4  * Copyright (C) 2001-2004 VideoLAN
5  * $Id$
6  *
7  * Authors: St├ęphane Borel <stef@via.ecp.fr>
8  *          Gildas Bazin <gbazin@videolan.org>
9  *
10  * This program is free software; you can redistribute it and/or modify
11  * it under the terms of the GNU General Public License as published by
12  * the Free Software Foundation; either version 2 of the License, or
13  * (at your option) any later version.
14  *
15  * This program is distributed in the hope that it will be useful,
16  * but WITHOUT ANY WARRANTY; without even the implied warranty of
17  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
18  * GNU General Public License for more details.
19  *
20  * You should have received a copy of the GNU General Public License
21  * along with this program; if not, write to the Free Software
22  * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111, USA.
23  *****************************************************************************/
24
25 /*****************************************************************************
26  * Preamble
27  *****************************************************************************/
28 #include <stdio.h>
29 #include <stdlib.h>                                      /* malloc(), free() */
30 #include <string.h>                                              /* strdup() */
31
32 #include <vlc/vlc.h>
33 #include <vlc/input.h>
34
35 #include "iso_lang.h"
36
37 #include "../demux/ps.h"
38
39 #ifdef HAVE_UNISTD_H
40 #   include <unistd.h>
41 #endif
42
43 #include <fcntl.h>
44 #include <sys/types.h>
45 #include <sys/stat.h>
46 #include <string.h>
47
48 #include <dvdread/dvd_reader.h>
49 #include <dvdread/ifo_types.h>
50 #include <dvdread/ifo_read.h>
51 #include <dvdread/nav_read.h>
52 #include <dvdread/nav_print.h>
53
54 /*****************************************************************************
55  * Module descriptor
56  *****************************************************************************/
57 #define ANGLE_TEXT N_("DVD angle")
58 #define ANGLE_LONGTEXT N_( \
59     "Allows you to select the default DVD angle." )
60
61 #define CACHING_TEXT N_("Caching value in ms")
62 #define CACHING_LONGTEXT N_( \
63     "Allows you to modify the default caching value for DVDread streams. " \
64     "This value should be set in millisecond units." )
65
66 #define CSSMETHOD_TEXT N_("Method used by libdvdcss for decryption")
67 #define CSSMETHOD_LONGTEXT N_( \
68     "Set the method used by libdvdcss for key decryption.\n" \
69     "title: decrypted title key is guessed from the encrypted sectors of " \
70            "the stream. Thus it should work with a file as well as the " \
71            "DVD device. But it sometimes takes much time to decrypt a title " \
72            "key and may even fail. With this method, the key is only checked "\
73            "at the beginning of each title, so it won't work if the key " \
74            "changes in the middle of a title.\n" \
75     "disc: the disc key is first cracked, then all title keys can be " \
76            "decrypted instantly, which allows us to check them often.\n" \
77     "key: the same as \"disc\" if you don't have a file with player keys " \
78            "at compilation time. If you do, the decryption of the disc key " \
79            "will be faster with this method. It is the one that was used by " \
80            "libcss.\n" \
81     "The default method is: key.")
82
83 static char *psz_css_list[] = { "title", "disc", "key" };
84 static char *psz_css_list_text[] = { N_("title"), N_("Disc"), N_("Key") };
85
86 static int  Open ( vlc_object_t * );
87 static void Close( vlc_object_t * );
88
89 vlc_module_begin();
90     set_name( _("DVD without menus") );
91     set_description( _("DVDRead Input (DVD without menu support)") );
92     set_category( CAT_INPUT );
93     set_subcategory( SUBCAT_INPUT_ACCESS );
94     add_integer( "dvdread-angle", 1, NULL, ANGLE_TEXT,
95         ANGLE_LONGTEXT, VLC_FALSE );
96     add_integer( "dvdread-caching", DEFAULT_PTS_DELAY / 1000, NULL,
97         CACHING_TEXT, CACHING_LONGTEXT, VLC_TRUE );
98     add_string( "dvdread-css-method", NULL, NULL, CSSMETHOD_TEXT,
99                 CSSMETHOD_LONGTEXT, VLC_TRUE );
100         change_string_list( psz_css_list, psz_css_list_text, 0 );
101     set_capability( "access_demux", 0 );
102     add_shortcut( "dvd" );
103     add_shortcut( "dvdread" );
104     add_shortcut( "dvdsimple" );
105     set_callbacks( Open, Close );
106 vlc_module_end();
107
108 /* how many blocks DVDRead will read in each loop */
109 #define DVD_BLOCK_READ_ONCE 4
110
111 /*****************************************************************************
112  * Local prototypes
113  *****************************************************************************/
114
115 struct demux_sys_t
116 {
117     /* DVDRead state */
118     dvd_reader_t *p_dvdread;
119     dvd_file_t   *p_title;
120
121     ifo_handle_t *p_vmg_file;
122     ifo_handle_t *p_vts_file;
123
124     int i_title;
125     int i_chapter, i_chapters;
126     int i_angle, i_angles;
127
128     tt_srpt_t    *p_tt_srpt;
129     pgc_t        *p_cur_pgc;
130     dsi_t        dsi_pack;
131     int          i_ttn;
132
133     int i_pack_len;
134     int i_cur_block;
135     int i_next_vobu;
136
137     /* Current title start/end blocks */
138     int i_title_start_block;
139     int i_title_end_block;
140     int i_title_blocks;
141     int i_title_offset;
142
143     int i_title_start_cell;
144     int i_title_end_cell;
145     int i_cur_cell;
146     int i_next_cell;
147
148     /* Track */
149     ps_track_t    tk[PS_TK_COUNT];
150     int           i_mux_rate;
151
152     int           i_titles;
153     input_title_t **titles;
154
155     /* Video */
156     int i_aspect;
157
158     /* SPU */
159     uint32_t clut[16];
160 };
161
162 static int Control   ( demux_t *, int, va_list );
163 static int Demux     ( demux_t * );
164 static int DemuxBlock( demux_t *, uint8_t *, int );
165
166 static void DemuxTitles( demux_t *, int * );
167 static void ESNew( demux_t *, int, int );
168
169 static int  DvdReadSetArea  ( demux_t *, int, int, int );
170 static void DvdReadSeek     ( demux_t *, int );
171 static void DvdReadHandleDSI( demux_t *, uint8_t * );
172 static void DvdReadFindCell ( demux_t * );
173
174 /*****************************************************************************
175  * Open:
176  *****************************************************************************/
177 static int Open( vlc_object_t *p_this )
178 {
179     demux_t      *p_demux = (demux_t*)p_this;
180     demux_sys_t  *p_sys;
181     char         *psz_name;
182     char         *psz_dvdcss_env;
183     dvd_reader_t *p_dvdread;
184     ifo_handle_t *p_vmg_file;
185     vlc_value_t  val;
186
187     if( !p_demux->psz_path || !*p_demux->psz_path )
188     {
189         /* Only when selected */
190         if( !p_this->b_force ) return VLC_EGENERIC;
191
192         psz_name = var_CreateGetString( p_this, "dvd" );
193         if( !psz_name || !*psz_name )
194         {
195             if( psz_name ) free( psz_name );
196             return VLC_EGENERIC;
197         }
198     }
199     else psz_name = strdup( p_demux->psz_path );
200
201 #ifdef WIN32
202     if( psz_name[0] && psz_name[1] == ':' &&
203         psz_name[2] == '\\' && psz_name[3] == '\0' ) psz_name[2] = '\0';
204 #endif
205
206     /* Override environment variable DVDCSS_METHOD with config option
207      * (FIXME: this creates a small memory leak) */
208     psz_dvdcss_env = config_GetPsz( p_demux, "dvdread-css-method" );
209     if( psz_dvdcss_env && *psz_dvdcss_env )
210     {
211         char *psz_env;
212
213         psz_env = malloc( strlen("DVDCSS_METHOD=") +
214                           strlen( psz_dvdcss_env ) + 1 );
215         if( !psz_env )
216         {
217             free( psz_dvdcss_env );
218             return VLC_ENOMEM;
219         }
220
221         sprintf( psz_env, "%s%s", "DVDCSS_METHOD=", psz_dvdcss_env );
222
223         putenv( psz_env );
224     }
225     if( psz_dvdcss_env ) free( psz_dvdcss_env );
226
227     /* Open dvdread */
228     if( !(p_dvdread = DVDOpen( psz_name )) )
229     {
230         msg_Err( p_demux, "DVDRead cannot open source: %s", psz_name );
231         free( psz_name );
232         return VLC_EGENERIC;
233     }
234     free( psz_name );
235
236     /* Ifo allocation & initialisation */
237     if( !( p_vmg_file = ifoOpen( p_dvdread, 0 ) ) )
238     {
239         msg_Warn( p_demux, "cannot open VMG info" );
240         return VLC_EGENERIC;
241     }
242     msg_Dbg( p_demux, "VMG opened" );
243
244     /* Fill p_demux field */
245     p_demux->pf_demux = Demux;
246     p_demux->pf_control = Control;
247     p_demux->p_sys = p_sys = malloc( sizeof( demux_sys_t ) );
248     memset( p_sys, 0, sizeof( demux_sys_t ) );
249
250     ps_track_init( p_sys->tk );
251     p_sys->i_aspect = -1;
252     p_sys->i_mux_rate = 0;
253
254     p_sys->p_dvdread = p_dvdread;
255     p_sys->p_vmg_file = p_vmg_file;
256     p_sys->p_title = NULL;
257     p_sys->p_vts_file = NULL;
258
259     p_sys->i_title = p_sys->i_chapter = -1;
260
261     var_Create( p_demux, "dvdread-angle", VLC_VAR_INTEGER|VLC_VAR_DOINHERIT );
262     var_Get( p_demux, "dvdread-angle", &val );
263     p_sys->i_angle = val.i_int > 0 ? val.i_int : 1;
264
265     DemuxTitles( p_demux, &p_sys->i_angle );
266     DvdReadSetArea( p_demux, 0, 0, p_sys->i_angle );
267
268     /* Update default_pts to a suitable value for dvdread access */
269     var_Create( p_demux, "dvdread-caching",
270                 VLC_VAR_INTEGER|VLC_VAR_DOINHERIT );
271
272     return VLC_SUCCESS;
273 }
274
275 /*****************************************************************************
276  * Close:
277  *****************************************************************************/
278 static void Close( vlc_object_t *p_this )
279 {
280     demux_t     *p_demux = (demux_t*)p_this;
281     demux_sys_t *p_sys = p_demux->p_sys;
282     int i;
283
284     for( i = 0; i < PS_TK_COUNT; i++ )
285     {
286         ps_track_t *tk = &p_sys->tk[i];
287         if( tk->b_seen )
288         {
289             es_format_Clean( &tk->fmt );
290             if( tk->es ) es_out_Del( p_demux->out, tk->es );
291         }
292     }
293
294     /* Close libdvdread */
295     if( p_sys->p_title ) DVDCloseFile( p_sys->p_title );
296     if( p_sys->p_vts_file ) ifoClose( p_sys->p_vts_file );
297     if( p_sys->p_vmg_file ) ifoClose( p_sys->p_vmg_file );
298     DVDClose( p_sys->p_dvdread );
299
300     free( p_sys );
301 }
302
303 /*****************************************************************************
304  * Control:
305  *****************************************************************************/
306 static int Control( demux_t *p_demux, int i_query, va_list args )
307 {
308     demux_sys_t *p_sys = p_demux->p_sys;
309     double f, *pf;
310     vlc_bool_t *pb;
311     int64_t *pi64;
312     input_title_t ***ppp_title;
313     int *pi_int;
314     int i;
315
316     switch( i_query )
317     {
318         case DEMUX_GET_POSITION:
319         {
320             pf = (double*) va_arg( args, double* );
321
322             if( p_sys->i_title_blocks > 0 )
323                 *pf = (double)p_sys->i_title_offset / p_sys->i_title_blocks;
324             else
325                 *pf = 0.0;
326
327             return VLC_SUCCESS;
328         }
329         case DEMUX_SET_POSITION:
330         {
331             f = (double)va_arg( args, double );
332
333             DvdReadSeek( p_demux, f * p_sys->i_title_blocks );
334
335             return VLC_SUCCESS;
336         }
337         case DEMUX_GET_TIME:
338             pi64 = (int64_t*)va_arg( args, int64_t * );
339             if( p_sys->i_mux_rate > 0 )
340             {
341                 *pi64 = (int64_t)1000000 * DVD_VIDEO_LB_LEN *
342                         p_sys->i_title_offset / 50 / p_sys->i_mux_rate;
343                 return VLC_SUCCESS;
344             }
345             *pi64 = 0;
346             return VLC_EGENERIC;
347
348         case DEMUX_GET_LENGTH:
349             pi64 = (int64_t*)va_arg( args, int64_t * );
350             if( p_sys->i_mux_rate > 0 )
351             {
352                 *pi64 = (int64_t)1000000 * DVD_VIDEO_LB_LEN *
353                         p_sys->i_title_blocks / 50 / p_sys->i_mux_rate;
354                 return VLC_SUCCESS;
355             }
356             *pi64 = 0;
357             return VLC_EGENERIC;
358
359         /* Special for access_demux */
360         case DEMUX_CAN_PAUSE:
361         case DEMUX_CAN_CONTROL_PACE:
362             /* TODO */
363             pb = (vlc_bool_t*)va_arg( args, vlc_bool_t * );
364             *pb = VLC_TRUE;
365             return VLC_SUCCESS;
366
367         case DEMUX_SET_PAUSE_STATE:
368             return VLC_SUCCESS;
369
370         case DEMUX_GET_TITLE_INFO:
371             ppp_title = (input_title_t***)va_arg( args, input_title_t*** );
372             pi_int    = (int*)va_arg( args, int* );
373             *((int*)va_arg( args, int* )) = 1; /* Title offset */
374             *((int*)va_arg( args, int* )) = 1; /* Chapter offset */
375
376             /* Duplicate title infos */
377             *pi_int = p_sys->i_titles;
378             *ppp_title = malloc( sizeof(input_title_t **) * p_sys->i_titles );
379             for( i = 0; i < p_sys->i_titles; i++ )
380             {
381                 (*ppp_title)[i] = vlc_input_title_Duplicate(p_sys->titles[i]);
382             }
383             return VLC_SUCCESS;
384
385         case DEMUX_SET_TITLE:
386             i = (int)va_arg( args, int );
387             if( DvdReadSetArea( p_demux, i, 0, -1 ) != VLC_SUCCESS )
388             {
389                 msg_Warn( p_demux, "cannot set title/chapter" );
390                 return VLC_EGENERIC;
391             }
392             p_demux->info.i_update |=
393                 INPUT_UPDATE_TITLE | INPUT_UPDATE_SEEKPOINT;
394             p_demux->info.i_title = i;
395             p_demux->info.i_seekpoint = 0;
396             return VLC_SUCCESS;
397
398         case DEMUX_SET_SEEKPOINT:
399             i = (int)va_arg( args, int );
400             if( DvdReadSetArea( p_demux, -1, i, -1 ) != VLC_SUCCESS )
401             {
402                 msg_Warn( p_demux, "cannot set title/chapter" );
403                 return VLC_EGENERIC;
404             }
405             p_demux->info.i_update |= INPUT_UPDATE_SEEKPOINT;
406             p_demux->info.i_seekpoint = i;
407             return VLC_SUCCESS;
408
409         case DEMUX_GET_PTS_DELAY:
410             pi64 = (int64_t*)va_arg( args, int64_t * );
411             *pi64 = (int64_t)var_GetInteger( p_demux, "dvdread-caching" )*1000;
412             return VLC_SUCCESS;
413
414         /* TODO implement others */
415         default:
416             return VLC_EGENERIC;
417     }
418 }
419
420 /*****************************************************************************
421  * Demux:
422  *****************************************************************************/
423 static int Demux( demux_t *p_demux )
424 {
425     demux_sys_t *p_sys = p_demux->p_sys;
426
427     uint8_t p_buffer[DVD_VIDEO_LB_LEN * DVD_BLOCK_READ_ONCE];
428     int i_blocks_once, i_read;
429     int i;
430
431     /*
432      * Playback by cell in this pgc, starting at the cell for our chapter.
433      */
434
435     /*
436      * Check end of pack, and select the following one
437      */
438     if( !p_sys->i_pack_len )
439     {
440         /* Read NAV packet */
441         if( DVDReadBlocks( p_sys->p_title, p_sys->i_next_vobu,
442                            1, p_buffer ) != 1 )
443         {
444             msg_Err( p_demux, "read failed for block %d", p_sys->i_next_vobu );
445             return -1;
446         }
447
448         /* Basic check to be sure we don't have a empty title
449          * go to next title if so */
450         //assert( p_buffer[41] == 0xbf && p_buffer[1027] == 0xbf );
451
452         /* Parse the contained dsi packet */
453         DvdReadHandleDSI( p_demux, p_buffer );
454
455         /* End of title */
456         if( p_sys->i_next_vobu > p_sys->i_title_end_block )
457         {
458             if( p_sys->i_title + 1 >= p_sys->i_titles )
459             {
460                 return 0; /* EOF */
461             }
462
463             DvdReadSetArea( p_demux, p_sys->i_title + 1, 0, -1 );
464         }
465
466         if( p_sys->i_pack_len >= 1024 )
467         {
468             msg_Err( p_demux, "i_pack_len >= 1024 (%i). "
469                      "This shouldn't happen!", p_sys->i_pack_len );
470             return 0; /* EOF */
471         }
472
473         /* FIXME: Ugly kludge: we send the pack block to the input for it
474          * sometimes has a zero scr and restart the sync */
475         p_sys->i_cur_block++;
476         p_sys->i_title_offset++;
477
478         DemuxBlock( p_demux, p_buffer, DVD_VIDEO_LB_LEN );
479     }
480
481     if( p_sys->i_cur_block > p_sys->i_title_end_block )
482     {
483         if( p_sys->i_title + 1 >= p_sys->i_titles )
484         {
485             return 0; /* EOF */
486         }
487
488         DvdReadSetArea( p_demux, p_sys->i_title + 1, 0, -1 );
489     }
490
491     /*
492      * Read actual data
493      */
494     i_blocks_once = __MIN( p_sys->i_pack_len, DVD_BLOCK_READ_ONCE );
495     p_sys->i_pack_len -= i_blocks_once;
496
497     /* Reads from DVD */
498     i_read = DVDReadBlocks( p_sys->p_title, p_sys->i_cur_block,
499                             i_blocks_once, p_buffer );
500     if( i_read != i_blocks_once )
501     {
502         msg_Err( p_demux, "read failed for %d/%d blocks at 0x%02x",
503                  i_read, i_blocks_once, p_sys->i_cur_block );
504         return -1;
505     }
506
507     p_sys->i_cur_block += i_read;
508     p_sys->i_title_offset += i_read;
509
510 #if 0
511     msg_Dbg( p_demux, "i_blocks: %d len: %d current: 0x%02x",
512              i_read, p_sys->i_pack_len, p_sys->i_cur_block );
513 #endif
514
515     for( i = 0; i < i_read; i++ )
516     {
517         DemuxBlock( p_demux, p_buffer + i * DVD_VIDEO_LB_LEN,
518                     DVD_VIDEO_LB_LEN );
519     }
520
521 #undef p_pgc
522
523     return 1;
524 }
525
526 /*****************************************************************************
527  * DemuxBlock: demux a given block
528  *****************************************************************************/
529 static int DemuxBlock( demux_t *p_demux, uint8_t *pkt, int i_pkt )
530 {
531     demux_sys_t *p_sys = p_demux->p_sys;
532     uint8_t     *p = pkt;
533
534     while( p < &pkt[i_pkt] )
535     {
536         int i_size = ps_pkt_size( p, &pkt[i_pkt] - p );
537         block_t *p_pkt;
538         if( i_size <= 0 )
539         {
540             break;
541         }
542
543         /* Create a block */
544         p_pkt = block_New( p_demux, i_size );
545         memcpy( p_pkt->p_buffer, p, i_size);
546
547         /* Parse it and send it */
548         switch( 0x100 | p[3] )
549         {
550         case 0x1b9:
551         case 0x1bb:
552         case 0x1bc:
553
554 #ifdef DVDREAD_DEBUG
555             if( p[3] == 0xbc )
556             {
557                 msg_Warn( p_demux, "received a PSM packet" );
558             }
559             else if( p[3] == 0xbb )
560             {
561                 msg_Warn( p_demux, "received a SYSTEM packet" );
562             }
563 #endif
564             block_Release( p_pkt );
565             break;
566
567         case 0x1ba:
568         {
569             int64_t i_scr;
570             int i_mux_rate;
571             if( !ps_pkt_parse_pack( p_pkt, &i_scr, &i_mux_rate ) )
572             {
573                 es_out_Control( p_demux->out, ES_OUT_SET_PCR, i_scr );
574                 if( i_mux_rate > 0 ) p_sys->i_mux_rate = i_mux_rate;
575             }
576             block_Release( p_pkt );
577             break;
578         }
579         default:
580         {
581             int i_id = ps_pkt_id( p_pkt );
582             if( i_id >= 0xc0 )
583             {
584                 ps_track_t *tk = &p_sys->tk[PS_ID_TO_TK(i_id)];
585
586                 if( !tk->b_seen )
587                 {
588                     ESNew( p_demux, i_id, 0 );
589                 }
590                 if( tk->b_seen && tk->es &&
591                     !ps_pkt_parse_pes( p_pkt, tk->i_skip ) )
592                 {
593                     es_out_Send( p_demux->out, tk->es, p_pkt );
594                 }
595                 else
596                 {
597                     block_Release( p_pkt );
598                 }
599             }
600             else
601             {
602                 block_Release( p_pkt );
603             }
604             break;
605         }
606         }
607
608         p += i_size;
609     }
610
611     return VLC_SUCCESS;
612 }
613
614 /*****************************************************************************
615  * ESNew: register a new elementary stream
616  *****************************************************************************/
617 static void ESNew( demux_t *p_demux, int i_id, int i_lang )
618 {
619     demux_sys_t *p_sys = p_demux->p_sys;
620     ps_track_t  *tk = &p_sys->tk[PS_ID_TO_TK(i_id)];
621     char psz_language[3];
622
623     if( tk->b_seen ) return;
624
625     if( ps_track_fill( tk, 0, i_id ) )
626     {
627         msg_Warn( p_demux, "unknown codec for id=0x%x", i_id );
628         return;
629     }
630
631     psz_language[0] = psz_language[1] = psz_language[2] = 0;
632     if( i_lang && i_lang != 0xffff )
633     {
634         psz_language[0] = (i_lang >> 8)&0xff;
635         psz_language[1] = (i_lang     )&0xff;
636     }
637
638     /* Add a new ES */
639     if( tk->fmt.i_cat == VIDEO_ES )
640     {
641         if( p_sys->i_aspect >= 0 )
642         {
643             tk->fmt.video.i_aspect = p_sys->i_aspect;
644         }
645     }
646     else if( tk->fmt.i_cat == AUDIO_ES )
647     {
648         int i_audio = -1;
649         /* find the audio number PLEASE find another way */
650         if( (i_id&0xbdf8) == 0xbd88 )       /* dts */
651         {
652             i_audio = i_id&0x07;
653         }
654         else if( (i_id&0xbdf0) == 0xbd80 )  /* a52 */
655         {
656             i_audio = i_id&0xf;
657         }
658         else if( (i_id&0xbdf0) == 0xbda0 )  /* lpcm */
659         {
660             i_audio = i_id&0x1f;
661         }
662         else if( ( i_id&0xe0 ) == 0xc0 )    /* mpga */
663         {
664             i_audio = i_id&0x1f;
665         }
666
667         if( psz_language[0] ) tk->fmt.psz_language = strdup( psz_language );
668     }
669     else if( tk->fmt.i_cat == SPU_ES )
670     {
671         /* Palette */
672         tk->fmt.subs.spu.palette[0] = 0xBeef;
673         memcpy( &tk->fmt.subs.spu.palette[1], p_sys->clut,
674                 16 * sizeof( uint32_t ) );
675
676         if( psz_language[0] ) tk->fmt.psz_language = strdup( psz_language );
677     }
678
679     tk->es = es_out_Add( p_demux->out, &tk->fmt );
680     tk->b_seen = VLC_TRUE;
681 }
682
683 /*****************************************************************************
684  * DvdReadSetArea: initialize input data for title x, chapter y.
685  * It should be called for each user navigation request.
686  *****************************************************************************
687  * Take care that i_title and i_chapter start from 0.
688  *****************************************************************************/
689 static int DvdReadSetArea( demux_t *p_demux, int i_title, int i_chapter,
690                            int i_angle )
691 {
692     demux_sys_t *p_sys = p_demux->p_sys;
693     int pgc_id = 0, pgn = 0;
694     int i;
695
696 #define p_pgc p_sys->p_cur_pgc
697 #define p_vmg p_sys->p_vmg_file
698 #define p_vts p_sys->p_vts_file
699
700     if( i_title >= 0 && i_title < p_sys->i_titles &&
701         i_title != p_sys->i_title )
702     {
703         int i_start_cell, i_end_cell;
704
705         if( p_sys->p_title != NULL ) DVDCloseFile( p_sys->p_title );
706         if( p_vts != NULL ) ifoClose( p_vts );
707         p_sys->i_title = i_title;
708
709         /*
710          *  We have to load all title information
711          */
712         msg_Dbg( p_demux, "open VTS %d, for title %d",
713                  p_vmg->tt_srpt->title[i_title].title_set_nr, i_title + 1 );
714
715         /* Ifo vts */
716         if( !( p_vts = ifoOpen( p_sys->p_dvdread,
717                p_vmg->tt_srpt->title[i_title].title_set_nr ) ) )
718         {
719             msg_Err( p_demux, "fatal error in vts ifo" );
720             return VLC_EGENERIC;
721         }
722
723         /* Title position inside the selected vts */
724         p_sys->i_ttn = p_vmg->tt_srpt->title[i_title].vts_ttn;
725
726         /* Find title start/end */
727         pgc_id = p_vts->vts_ptt_srpt->title[p_sys->i_ttn - 1].ptt[0].pgcn;
728         pgn = p_vts->vts_ptt_srpt->title[p_sys->i_ttn - 1].ptt[0].pgn;
729         p_pgc = p_vts->vts_pgcit->pgci_srp[pgc_id - 1].pgc;
730
731         p_sys->i_title_start_cell =
732             i_start_cell = p_pgc->program_map[pgn - 1] - 1;
733         p_sys->i_title_start_block =
734             p_pgc->cell_playback[i_start_cell].first_sector;
735
736         p_sys->i_title_end_cell =
737             i_end_cell = p_pgc->nr_of_cells - 1;
738         p_sys->i_title_end_block =
739             p_pgc->cell_playback[i_end_cell].last_sector;
740
741         p_sys->i_title_offset = 0;
742
743         p_sys->i_title_blocks = 0;
744         for( i = i_start_cell; i <= i_end_cell; i++ )
745         {
746             p_sys->i_title_blocks += p_pgc->cell_playback[i].last_sector -
747                 p_pgc->cell_playback[i].first_sector + 1;
748         }
749
750         msg_Dbg( p_demux, "title %d vts_title %d pgc %d pgn %d "
751                  "start %d end %d blocks: %d",
752                  i_title + 1, p_sys->i_ttn, pgc_id, pgn,
753                  p_sys->i_title_start_block, p_sys->i_title_end_block,
754                  p_sys->i_title_blocks );
755
756         /*
757          * Set properties for current chapter
758          */
759         p_sys->i_chapter = 0;
760         p_sys->i_chapters =
761             p_vts->vts_ptt_srpt->title[p_sys->i_ttn - 1].nr_of_ptts;
762
763         pgc_id = p_vts->vts_ptt_srpt->title[
764                     p_sys->i_ttn - 1].ptt[p_sys->i_chapter].pgcn;
765         pgn = p_vts->vts_ptt_srpt->title[
766                     p_sys->i_ttn - 1].ptt[p_sys->i_chapter].pgn;
767
768         p_pgc = p_vts->vts_pgcit->pgci_srp[pgc_id - 1].pgc;
769         p_sys->i_pack_len = 0;
770         p_sys->i_next_cell =
771             p_sys->i_cur_cell = p_pgc->program_map[pgn - 1] - 1;
772         DvdReadFindCell( p_demux );
773
774         p_sys->i_next_vobu = p_sys->i_cur_block =
775             p_pgc->cell_playback[p_sys->i_cur_cell].first_sector;
776
777         /*
778          * Angle management
779          */
780         p_sys->i_angles = p_vmg->tt_srpt->title[i_title].nr_of_angles;
781         if( p_sys->i_angle > p_sys->i_angles ) p_sys->i_angle = 1;
782
783         /*
784          * We've got enough info, time to open the title set data.
785          */
786         if( !( p_sys->p_title = DVDOpenFile( p_sys->p_dvdread,
787             p_vmg->tt_srpt->title[i_title].title_set_nr,
788             DVD_READ_TITLE_VOBS ) ) )
789         {
790             msg_Err( p_demux, "cannot open title (VTS_%02d_1.VOB)",
791                      p_vmg->tt_srpt->title[i_title].title_set_nr );
792             return VLC_EGENERIC;
793         }
794
795         //IfoPrintTitle( p_demux );
796
797         /*
798          * Destroy obsolete ES by reinitializing program 0
799          * and find all ES in title with ifo data
800          */
801         es_out_Control( p_demux->out, ES_OUT_RESET_PCR );
802
803         for( i = 0; i < PS_TK_COUNT; i++ )
804         {
805             ps_track_t *tk = &p_sys->tk[i];
806             if( tk->b_seen )
807             {
808                 es_format_Clean( &tk->fmt );
809                 if( tk->es ) es_out_Del( p_demux->out, tk->es );
810             }
811             tk->b_seen = VLC_FALSE;
812         }
813
814         if( p_demux->info.i_title != i_title )
815         {
816             p_demux->info.i_update |=
817                 INPUT_UPDATE_TITLE | INPUT_UPDATE_SEEKPOINT;
818             p_demux->info.i_title = i_title;
819             p_demux->info.i_seekpoint = 0;
820         }
821
822         /* TODO: re-add angles */
823
824
825         ESNew( p_demux, 0xe0, 0 ); /* Video, FIXME ? */
826         p_sys->i_aspect = p_vts->vtsi_mat->vts_video_attr.display_aspect_ratio;
827
828 #define audio_control \
829     p_sys->p_vts_file->vts_pgcit->pgci_srp[pgc_id-1].pgc->audio_control[i-1]
830
831         /* Audio ES, in the order they appear in the .ifo */
832         for( i = 1; i <= p_vts->vtsi_mat->nr_of_vts_audio_streams; i++ )
833         {
834             int i_position = 0;
835             uint16_t i_id;
836
837             //IfoPrintAudio( p_demux, i );
838
839             /* Audio channel is active if first byte is 0x80 */
840             if( audio_control & 0x8000 )
841             {
842                 i_position = ( audio_control & 0x7F00 ) >> 8;
843
844                 msg_Dbg( p_demux, "audio position  %d", i_position );
845                 switch( p_vts->vtsi_mat->vts_audio_attr[i - 1].audio_format )
846                 {
847                 case 0x00: /* A52 */
848                     i_id = (0x80 + i_position) | 0xbd00;
849                     break;
850                 case 0x02:
851                 case 0x03: /* MPEG audio */
852                     i_id = 0xc000 + i_position;
853                     break;
854                 case 0x04: /* LPCM */
855                     i_id = (0xa0 + i_position) | 0xbd00;
856                     break;
857                 case 0x06: /* DTS */
858                     i_id = (0x88 + i_position) | 0xbd00;
859                     break;
860                 default:
861                     i_id = 0;
862                     msg_Err( p_demux, "unknown audio type %.2x",
863                         p_vts->vtsi_mat->vts_audio_attr[i - 1].audio_format );
864                 }
865
866                 ESNew( p_demux, i_id, p_sys->p_vts_file->vtsi_mat->
867                        vts_audio_attr[i - 1].lang_code );
868             }
869         }
870 #undef audio_control
871
872 #define spu_palette \
873     p_sys->p_vts_file->vts_pgcit->pgci_srp[pgc_id-1].pgc->palette
874
875         memcpy( p_sys->clut, spu_palette, 16 * sizeof( uint32_t ) );
876
877 #define spu_control \
878     p_sys->p_vts_file->vts_pgcit->pgci_srp[pgc_id-1].pgc->subp_control[i-1]
879
880         /* Sub Picture ES */
881         for( i = 1; i <= p_vts->vtsi_mat->nr_of_vts_subp_streams; i++ )
882         {
883             int i_position = 0;
884             uint16_t i_id;
885
886             //IfoPrintSpu( p_sys, i );
887             msg_Dbg( p_demux, "spu %d 0x%02x", i, spu_control );
888
889             if( spu_control & 0x80000000 )
890             {
891                 /*  there are several streams for one spu */
892                 if( p_vts->vtsi_mat->vts_video_attr.display_aspect_ratio )
893                 {
894                     /* 16:9 */
895                     switch( p_vts->vtsi_mat->vts_video_attr.permitted_df )
896                     {
897                     case 1: /* letterbox */
898                         i_position = spu_control & 0xff;
899                         break;
900                     case 2: /* pan&scan */
901                         i_position = ( spu_control >> 8 ) & 0xff;
902                         break;
903                     default: /* widescreen */
904                         i_position = ( spu_control >> 16 ) & 0xff;
905                         break;
906                     }
907                 }
908                 else
909                 {
910                     /* 4:3 */
911                     i_position = ( spu_control >> 24 ) & 0x7F;
912                 }
913
914                 i_id = (0x20 + i_position) | 0xbd00;
915
916                 ESNew( p_demux, i_id, p_sys->p_vts_file->vtsi_mat->
917                        vts_subp_attr[i - 1].lang_code );
918             }
919         }
920 #undef spu_control
921
922     }
923     else if( i_title != -1 && i_title != p_sys->i_title )
924
925     {
926         return VLC_EGENERIC; /* Couldn't set title */
927     }
928
929     /*
930      * Chapter selection
931      */
932
933     if( i_chapter >= 0 && i_chapter < p_sys->i_chapters )
934     {
935         pgc_id = p_vts->vts_ptt_srpt->title[
936                      p_sys->i_ttn - 1].ptt[i_chapter].pgcn;
937         pgn = p_vts->vts_ptt_srpt->title[
938                   p_sys->i_ttn - 1].ptt[i_chapter].pgn;
939
940         p_pgc = p_vts->vts_pgcit->pgci_srp[pgc_id - 1].pgc;
941
942         p_sys->i_cur_cell = p_pgc->program_map[pgn - 1] - 1;
943         p_sys->i_chapter = i_chapter;
944         DvdReadFindCell( p_demux );
945
946         p_sys->i_title_offset = 0;
947         for( i = p_sys->i_title_start_cell; i < p_sys->i_cur_cell; i++ )
948         {
949             p_sys->i_title_offset += p_pgc->cell_playback[i].last_sector -
950                 p_pgc->cell_playback[i].first_sector + 1;
951         }
952
953         p_sys->i_pack_len = 0;
954         p_sys->i_next_vobu = p_sys->i_cur_block =
955             p_pgc->cell_playback[p_sys->i_cur_cell].first_sector;
956
957         if( p_demux->info.i_seekpoint != i_chapter )
958         {
959             p_demux->info.i_update |= INPUT_UPDATE_SEEKPOINT;
960             p_demux->info.i_seekpoint = i_chapter;
961         }
962     }
963     else if( i_chapter != -1 )
964
965     {
966         return VLC_EGENERIC; /* Couldn't set chapter */
967     }
968
969 #undef p_pgc
970 #undef p_vts
971 #undef p_vmg
972
973     return VLC_SUCCESS;
974 }
975
976 /*****************************************************************************
977  * DvdReadSeek : Goes to a given position on the stream.
978  *****************************************************************************
979  * This one is used by the input and translate chronological position from
980  * input to logical position on the device.
981  *****************************************************************************/
982 static void DvdReadSeek( demux_t *p_demux, int i_block_offset )
983 {
984     demux_sys_t *p_sys = p_demux->p_sys;
985     int i_chapter = 0;
986     int i_cell = 0;
987     int i_vobu = 0;
988     int i_sub_cell = 0;
989     int i_block;
990
991 #define p_pgc p_sys->p_cur_pgc
992 #define p_vts p_sys->p_vts_file
993
994     /* Find cell */
995     i_block = i_block_offset;
996     for( i_cell = p_sys->i_title_start_cell;
997          i_cell <= p_sys->i_title_end_cell; i_cell++ )
998     {
999         if( i_block < (int)p_pgc->cell_playback[i_cell].last_sector -
1000             (int)p_pgc->cell_playback[i_cell].first_sector + 1 ) break;
1001
1002         i_block -= (p_pgc->cell_playback[i_cell].last_sector -
1003             p_pgc->cell_playback[i_cell].first_sector + 1);
1004     }
1005     if( i_cell > p_sys->i_title_end_cell )
1006     {
1007         msg_Err( p_demux, "couldn't find cell for block %i", i_block_offset );
1008         return;
1009     }
1010     i_block += p_pgc->cell_playback[i_cell].first_sector;
1011     p_sys->i_title_offset = i_block_offset;
1012
1013     /* Find chapter */
1014     for( i_chapter = 0; i_chapter < p_sys->i_chapters; i_chapter++ )
1015     {
1016         int pgc_id, pgn, i_tmp;
1017
1018         pgc_id = p_vts->vts_ptt_srpt->title[
1019                     p_sys->i_ttn - 1].ptt[i_chapter].pgcn;
1020         pgn = p_vts->vts_ptt_srpt->title[
1021                     p_sys->i_ttn - 1].ptt[i_chapter].pgn;
1022
1023         i_tmp = p_vts->vts_pgcit->pgci_srp[pgc_id - 1].pgc->program_map[pgn-1];
1024
1025         if( i_tmp > i_cell ) break;
1026     }
1027
1028     if( i_chapter < p_sys->i_chapters &&
1029         p_demux->info.i_seekpoint != i_chapter )
1030     {
1031         p_demux->info.i_update |= INPUT_UPDATE_SEEKPOINT;
1032         p_demux->info.i_seekpoint = i_chapter;
1033     }
1034
1035     /* Find vobu */
1036     while( (int)p_vts->vts_vobu_admap->vobu_start_sectors[i_vobu] <= i_block )
1037     {
1038         i_vobu++;
1039     }
1040
1041     /* Find sub_cell */
1042     while( p_vts->vts_c_adt->cell_adr_table[i_sub_cell].start_sector <
1043            p_vts->vts_vobu_admap->vobu_start_sectors[i_vobu-1] )
1044     {
1045         i_sub_cell++;
1046     }
1047
1048 #if 1
1049     msg_Dbg( p_demux, "cell %d i_sub_cell %d chapter %d vobu %d "
1050              "cell_sector %d vobu_sector %d sub_cell_sector %d",
1051              i_cell, i_sub_cell, i_chapter, i_vobu,
1052              p_sys->p_cur_pgc->cell_playback[i_cell].first_sector,
1053              p_vts->vts_vobu_admap->vobu_start_sectors[i_vobu],
1054              p_vts->vts_c_adt->cell_adr_table[i_sub_cell - 1].start_sector);
1055 #endif
1056
1057     p_sys->i_cur_block = i_block;
1058     p_sys->i_next_vobu = p_vts->vts_vobu_admap->vobu_start_sectors[i_vobu];
1059     p_sys->i_pack_len = p_sys->i_next_vobu - i_block;
1060     p_sys->i_cur_cell = i_cell;
1061     p_sys->i_chapter = i_chapter;
1062     DvdReadFindCell( p_demux );
1063
1064 #undef p_vts
1065 #undef p_pgc
1066
1067     return;
1068 }
1069
1070 /*****************************************************************************
1071  * DvdReadHandleDSI
1072  *****************************************************************************/
1073 static void DvdReadHandleDSI( demux_t *p_demux, uint8_t *p_data )
1074 {
1075     demux_sys_t *p_sys = p_demux->p_sys;
1076
1077     navRead_DSI( &p_sys->dsi_pack, &p_data[DSI_START_BYTE] );
1078
1079     /*
1080      * Determine where we go next.  These values are the ones we mostly
1081      * care about.
1082      */
1083     p_sys->i_cur_block = p_sys->dsi_pack.dsi_gi.nv_pck_lbn;
1084     p_sys->i_pack_len = p_sys->dsi_pack.dsi_gi.vobu_ea;
1085
1086     /*
1087      * If we're not at the end of this cell, we can determine the next
1088      * VOBU to display using the VOBU_SRI information section of the
1089      * DSI.  Using this value correctly follows the current angle,
1090      * avoiding the doubled scenes in The Matrix, and makes our life
1091      * really happy.
1092      */
1093
1094     p_sys->i_next_vobu = p_sys->i_cur_block +
1095         ( p_sys->dsi_pack.vobu_sri.next_vobu & 0x7fffffff );
1096
1097     if( p_sys->dsi_pack.vobu_sri.next_vobu != SRI_END_OF_CELL
1098         && p_sys->i_angle > 1 )
1099     {
1100         switch( ( p_sys->dsi_pack.sml_pbi.category & 0xf000 ) >> 12 )
1101         {
1102         case 0x4:
1103             /* Interleaved unit with no angle */
1104             if( p_sys->dsi_pack.sml_pbi.ilvu_sa != 0 )
1105             {
1106                 p_sys->i_next_vobu = p_sys->i_cur_block +
1107                     p_sys->dsi_pack.sml_pbi.ilvu_sa;
1108                 p_sys->i_pack_len = p_sys->dsi_pack.sml_pbi.ilvu_ea;
1109             }
1110             else
1111             {
1112                 p_sys->i_next_vobu = p_sys->i_cur_block +
1113                     p_sys->dsi_pack.dsi_gi.vobu_ea + 1;
1114             }
1115             break;
1116         case 0x5:
1117             /* vobu is end of ilvu */
1118             if( p_sys->dsi_pack.sml_agli.data[p_sys->i_angle-1].address )
1119             {
1120                 p_sys->i_next_vobu = p_sys->i_cur_block +
1121                     p_sys->dsi_pack.sml_agli.data[p_sys->i_angle-1].address;
1122                 p_sys->i_pack_len = p_sys->dsi_pack.sml_pbi.ilvu_ea;
1123
1124                 break;
1125             }
1126         case 0x6:
1127             /* vobu is beginning of ilvu */
1128         case 0x9:
1129             /* next scr is 0 */
1130         case 0xa:
1131             /* entering interleaved section */
1132         case 0x8:
1133             /* non interleaved cells in interleaved section */
1134         default:
1135             p_sys->i_next_vobu = p_sys->i_cur_block +
1136                 ( p_sys->dsi_pack.vobu_sri.next_vobu & 0x7fffffff );
1137             break;
1138         }
1139     }
1140     else if( p_sys->dsi_pack.vobu_sri.next_vobu == SRI_END_OF_CELL )
1141     {
1142         p_sys->i_cur_cell = p_sys->i_next_cell;
1143         DvdReadFindCell( p_demux );
1144
1145         p_sys->i_next_vobu =
1146             p_sys->p_cur_pgc->cell_playback[p_sys->i_cur_cell].first_sector;
1147     }
1148
1149 #if 0
1150     msg_Dbg( p_demux, 12, "scr %d lbn 0x%02x vobu_ea %d vob_id %d c_id %d",
1151              p_sys->dsi_pack.dsi_gi.nv_pck_scr,
1152              p_sys->dsi_pack.dsi_gi.nv_pck_lbn,
1153              p_sys->dsi_pack.dsi_gi.vobu_ea,
1154              p_sys->dsi_pack.dsi_gi.vobu_vob_idn,
1155              p_sys->dsi_pack.dsi_gi.vobu_c_idn );
1156
1157     msg_Dbg( p_demux, 12, "cat 0x%02x ilvu_ea %d ilvu_sa %d size %d",
1158              p_sys->dsi_pack.sml_pbi.category,
1159              p_sys->dsi_pack.sml_pbi.ilvu_ea,
1160              p_sys->dsi_pack.sml_pbi.ilvu_sa,
1161              p_sys->dsi_pack.sml_pbi.size );
1162
1163     msg_Dbg( p_demux, 12, "next_vobu %d next_ilvu1 %d next_ilvu2 %d",
1164              p_sys->dsi_pack.vobu_sri.next_vobu & 0x7fffffff,
1165              p_sys->dsi_pack.sml_agli.data[ p_sys->i_angle - 1 ].address,
1166              p_sys->dsi_pack.sml_agli.data[ p_sys->i_angle ].address);
1167 #endif
1168 }
1169
1170 /*****************************************************************************
1171  * DvdReadFindCell
1172  *****************************************************************************/
1173 static void DvdReadFindCell( demux_t *p_demux )
1174 {
1175     demux_sys_t *p_sys = p_demux->p_sys;
1176
1177     pgc_t *p_pgc;
1178     int   pgc_id, pgn;
1179     int   i = 0;
1180
1181 #define cell p_sys->p_cur_pgc->cell_playback
1182
1183     if( cell[p_sys->i_cur_cell].block_type == BLOCK_TYPE_ANGLE_BLOCK )
1184     {
1185         p_sys->i_cur_cell += p_sys->i_angle - 1;
1186
1187         while( cell[p_sys->i_cur_cell+i].block_mode != BLOCK_MODE_LAST_CELL )
1188         {
1189             i++;
1190         }
1191         p_sys->i_next_cell = p_sys->i_cur_cell + i + 1;
1192     }
1193     else
1194     {
1195         p_sys->i_next_cell = p_sys->i_cur_cell + 1;
1196     }
1197
1198 #undef cell
1199
1200     if( p_sys->i_chapter + 1 >= p_sys->i_chapters ) return;
1201
1202     pgc_id = p_sys->p_vts_file->vts_ptt_srpt->title[
1203                 p_sys->i_ttn - 1].ptt[p_sys->i_chapter + 1].pgcn;
1204     pgn = p_sys->p_vts_file->vts_ptt_srpt->title[
1205               p_sys->i_ttn - 1].ptt[p_sys->i_chapter + 1].pgn;
1206     p_pgc = p_sys->p_vts_file->vts_pgcit->pgci_srp[pgc_id - 1].pgc;
1207
1208     if( p_sys->i_cur_cell >= p_pgc->program_map[pgn - 1] - 1 )
1209     {
1210         p_sys->i_chapter++;
1211
1212         if( p_sys->i_chapter < p_sys->i_chapters &&
1213             p_demux->info.i_seekpoint != p_sys->i_chapter )
1214         {
1215             p_demux->info.i_update |= INPUT_UPDATE_SEEKPOINT;
1216             p_demux->info.i_seekpoint = p_sys->i_chapter;
1217         }
1218     }
1219 }
1220
1221 /*****************************************************************************
1222  * DemuxTitles: get the titles/chapters structure
1223  *****************************************************************************/
1224 static void DemuxTitles( demux_t *p_demux, int *pi_angle )
1225 {
1226     demux_sys_t *p_sys = p_demux->p_sys;
1227     input_title_t *t;
1228     seekpoint_t *s;
1229     int32_t i_titles;
1230     int i;
1231
1232     /* Find out number of titles/chapters */
1233 #define tt_srpt p_sys->p_vmg_file->tt_srpt
1234
1235     i_titles = tt_srpt->nr_of_srpts;
1236     msg_Dbg( p_demux, "number of titles: %d", i_titles );
1237
1238     for( i = 0; i < i_titles; i++ )
1239     {
1240         int32_t i_chapters = 0;
1241         int j;
1242
1243         i_chapters = tt_srpt->title[i].nr_of_ptts;
1244         msg_Dbg( p_demux, "title %d has %d chapters", i, i_chapters );
1245
1246         t = vlc_input_title_New();
1247
1248         for( j = 0; j < __MAX( i_chapters, 1 ); j++ )
1249         {
1250             s = vlc_seekpoint_New();
1251             TAB_APPEND( t->i_seekpoint, t->seekpoint, s );
1252         }
1253
1254         TAB_APPEND( p_sys->i_titles, p_sys->titles, t );
1255     }
1256
1257 #undef tt_srpt
1258 }