vlc_list: prevent name conflict
[vlc.git] / modules / access / dvdnav.c
1 /*****************************************************************************
2  * dvdnav.c: DVD module using the dvdnav library.
3  *****************************************************************************
4  * Copyright (C) 2004-2009 VLC authors and VideoLAN
5  * $Id$
6  *
7  * Authors: Laurent Aimar <fenrir@via.ecp.fr>
8  *
9  * This program is free software; you can redistribute it and/or modify it
10  * under the terms of the GNU Lesser General Public License as published by
11  * the Free Software Foundation; either version 2.1 of the License, or
12  * (at your option) any later version.
13  *
14  * This program is distributed in the hope that it will be useful,
15  * but WITHOUT ANY WARRANTY; without even the implied warranty of
16  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
17  * GNU Lesser General Public License for more details.
18  *
19  * You should have received a copy of the GNU Lesser General Public License
20  * along with this program; if not, write to the Free Software Foundation,
21  * Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA.
22  *****************************************************************************/
23
24 /*****************************************************************************
25  * NOTA BENE: this module requires the linking against a library which is
26  * known to require licensing under the GNU General Public License version 2
27  * (or later). Therefore, the result of compiling this module will normally
28  * be subject to the terms of that later license.
29  *****************************************************************************/
30
31
32 /*****************************************************************************
33  * Preamble
34  *****************************************************************************/
35
36 #ifdef HAVE_CONFIG_H
37 # include "config.h"
38 #endif
39
40 #include <assert.h>
41 #include <sys/stat.h>
42 #include <fcntl.h>
43 #include <errno.h>
44 #include <unistd.h>     /* close() */
45
46 #include <vlc_common.h>
47 #include <vlc_plugin.h>
48 #include <vlc_input.h>
49 #include <vlc_access.h>
50 #include <vlc_demux.h>
51 #include <vlc_charset.h>
52 #include <vlc_fs.h>
53 #include <vlc_vout.h>
54 #include <vlc_dialog.h>
55 #include <vlc_iso_lang.h>
56
57 /* FIXME we should find a better way than including that */
58 #include "../../src/text/iso-639_def.h"
59
60
61 #include <dvdnav/dvdnav.h>
62
63 #include "../demux/mpeg/pes.h"
64 #include "../demux/mpeg/ps.h"
65
66 /*****************************************************************************
67  * Module descriptor
68  *****************************************************************************/
69 #define ANGLE_TEXT N_("DVD angle")
70 #define ANGLE_LONGTEXT N_( \
71      "Default DVD angle." )
72
73 #define MENU_TEXT N_("Start directly in menu")
74 #define MENU_LONGTEXT N_( \
75     "Start the DVD directly in the main menu. This "\
76     "will try to skip all the useless warning introductions." )
77
78 #define LANGUAGE_DEFAULT ("en")
79
80 static int  AccessDemuxOpen ( vlc_object_t * );
81 static void Close( vlc_object_t * );
82
83 #if DVDREAD_VERSION >= 50300 && defined( HAVE_STREAM_CB_IN_DVDNAV_H )
84 #define HAVE_DVDNAV_DEMUX
85 static int  DemuxOpen ( vlc_object_t * );
86 #endif
87
88 vlc_module_begin ()
89     set_shortname( N_("DVD with menus") )
90     set_description( N_("DVDnav Input") )
91     set_category( CAT_INPUT )
92     set_subcategory( SUBCAT_INPUT_ACCESS )
93     add_integer( "dvdnav-angle", 1, ANGLE_TEXT,
94         ANGLE_LONGTEXT, false )
95     add_bool( "dvdnav-menu", true,
96         MENU_TEXT, MENU_LONGTEXT, false )
97     set_capability( "access", 305 )
98     add_shortcut( "dvd", "dvdnav", "file" )
99     set_callbacks( AccessDemuxOpen, Close )
100 #ifdef HAVE_DVDNAV_DEMUX
101     add_submodule()
102         set_description( N_("DVDnav demuxer") )
103         set_category( CAT_INPUT )
104         set_subcategory( SUBCAT_INPUT_DEMUX )
105         set_capability( "demux", 5 )
106         set_callbacks( DemuxOpen, Close )
107         add_shortcut( "dvd", "iso" )
108 #endif
109 vlc_module_end ()
110
111 /* Shall we use libdvdnav's read ahead cache? */
112 #ifdef __OS2__
113 #define DVD_READ_CACHE 0
114 #else
115 #define DVD_READ_CACHE 1
116 #endif
117
118 #define BLOCK_FLAG_CELL_DISCONTINUITY (BLOCK_FLAG_PRIVATE_SHIFT << 1)
119
120 /*****************************************************************************
121  * Local prototypes
122  *****************************************************************************/
123 typedef struct
124 {
125     dvdnav_t    *dvdnav;
126
127     /* */
128     bool        b_reset_pcr;
129     bool        b_readahead;
130
131     struct
132     {
133         bool         b_created;
134         bool         b_enabled;
135         vlc_mutex_t  lock;
136         vlc_timer_t  timer;
137     } still;
138
139     /* track */
140     ps_track_t  tk[PS_TK_COUNT];
141     int         i_mux_rate;
142
143     /* event */
144     vout_thread_t *p_vout;
145
146     /* palette for menus */
147     uint32_t clut[16];
148     uint8_t  palette[4][4];
149     bool b_spu_change;
150
151     /* Aspect ration */
152     struct {
153         unsigned i_num;
154         unsigned i_den;
155     } sar;
156
157     /* */
158     int           i_title;
159     input_title_t **title;
160     int           cur_title;
161     int           cur_seekpoint;
162     unsigned      updates;
163
164     /* length of program group chain */
165     vlc_tick_t  i_pgc_length;
166     int         i_vobu_index;
167     int         i_vobu_flush;
168 } demux_sys_t;
169
170 static int Control( demux_t *, int, va_list );
171 static int Demux( demux_t * );
172 static int DemuxBlock( demux_t *, const uint8_t *, int );
173 static void DemuxForceStill( demux_t * );
174
175 static void DemuxTitles( demux_t * );
176 static void ESSubtitleUpdate( demux_t * );
177 static void ButtonUpdate( demux_t *, bool );
178
179 static void ESNew( demux_t *, int );
180 static int ProbeDVD( const char * );
181
182 static char *DemuxGetLanguageCode( demux_t *p_demux, const char *psz_var );
183
184 static int ControlInternal( demux_t *, int, ... );
185
186 static void StillTimer( void * );
187
188 static int EventMouse( vlc_object_t *, char const *,
189                        vlc_value_t, vlc_value_t, void * );
190 static int EventIntf( vlc_object_t *, char const *,
191                       vlc_value_t, vlc_value_t, void * );
192
193 /*****************************************************************************
194  * CommonOpen:
195  *****************************************************************************/
196 static int CommonOpen( vlc_object_t *p_this,
197                        dvdnav_t *p_dvdnav, bool b_readahead )
198 {
199     demux_t     *p_demux = (demux_t*)p_this;
200     demux_sys_t *p_sys;
201     int         i_angle;
202     char        *psz_code;
203
204     assert( p_dvdnav );
205
206     /* Fill p_demux field */
207     DEMUX_INIT_COMMON(); p_sys = p_demux->p_sys;
208     p_sys->dvdnav = p_dvdnav;
209     p_sys->b_reset_pcr = false;
210
211     ps_track_init( p_sys->tk );
212     p_sys->sar.i_num = 0;
213     p_sys->sar.i_den = 0;
214     p_sys->i_mux_rate = 0;
215     p_sys->i_pgc_length = 0;
216     p_sys->b_spu_change = false;
217     p_sys->i_vobu_index = 0;
218     p_sys->i_vobu_flush = 0;
219     p_sys->b_readahead = b_readahead;
220
221     if( 1 )
222     {
223         // Hack for libdvdnav CVS.
224         // Without it dvdnav_get_number_of_titles() fails.
225         // Remove when fixed in libdvdnav CVS.
226         uint8_t buffer[DVD_VIDEO_LB_LEN];
227         int i_event, i_len;
228
229         if( dvdnav_get_next_block( p_sys->dvdnav, buffer, &i_event, &i_len )
230               == DVDNAV_STATUS_ERR )
231         {
232             msg_Warn( p_demux, "dvdnav_get_next_block failed" );
233         }
234
235         dvdnav_sector_search( p_sys->dvdnav, 0, SEEK_SET );
236     }
237
238     /* Configure dvdnav */
239     if( dvdnav_set_readahead_flag( p_sys->dvdnav, p_sys->b_readahead ) !=
240           DVDNAV_STATUS_OK )
241     {
242         msg_Warn( p_demux, "cannot set read-a-head flag" );
243     }
244
245     if( dvdnav_set_PGC_positioning_flag( p_sys->dvdnav, 1 ) !=
246           DVDNAV_STATUS_OK )
247     {
248         msg_Warn( p_demux, "cannot set PGC positioning flag" );
249     }
250
251     /* Set menu language */
252     psz_code = DemuxGetLanguageCode( p_demux, "menu-language" );
253     if( dvdnav_menu_language_select( p_sys->dvdnav, psz_code ) !=
254         DVDNAV_STATUS_OK )
255     {
256         msg_Warn( p_demux, "can't set menu language to '%s' (%s)",
257                   psz_code, dvdnav_err_to_string( p_sys->dvdnav ) );
258         /* We try to fall back to 'en' */
259         if( strcmp( psz_code, LANGUAGE_DEFAULT ) )
260             dvdnav_menu_language_select( p_sys->dvdnav, (char*)LANGUAGE_DEFAULT );
261     }
262     free( psz_code );
263
264     /* Set audio language */
265     psz_code = DemuxGetLanguageCode( p_demux, "audio-language" );
266     if( dvdnav_audio_language_select( p_sys->dvdnav, psz_code ) !=
267         DVDNAV_STATUS_OK )
268     {
269         msg_Warn( p_demux, "can't set audio language to '%s' (%s)",
270                   psz_code, dvdnav_err_to_string( p_sys->dvdnav ) );
271         /* We try to fall back to 'en' */
272         if( strcmp( psz_code, LANGUAGE_DEFAULT ) )
273             dvdnav_audio_language_select( p_sys->dvdnav, (char*)LANGUAGE_DEFAULT );
274     }
275     free( psz_code );
276
277     /* Set spu language */
278     psz_code = DemuxGetLanguageCode( p_demux, "sub-language" );
279     if( dvdnav_spu_language_select( p_sys->dvdnav, psz_code ) !=
280         DVDNAV_STATUS_OK )
281     {
282         msg_Warn( p_demux, "can't set spu language to '%s' (%s)",
283                   psz_code, dvdnav_err_to_string( p_sys->dvdnav ) );
284         /* We try to fall back to 'en' */
285         if( strcmp( psz_code, LANGUAGE_DEFAULT ) )
286             dvdnav_spu_language_select(p_sys->dvdnav, (char*)LANGUAGE_DEFAULT );
287     }
288     free( psz_code );
289
290     DemuxTitles( p_demux );
291
292     if( var_CreateGetBool( p_demux, "dvdnav-menu" ) )
293     {
294         msg_Dbg( p_demux, "trying to go to dvd menu" );
295
296         if( dvdnav_title_play( p_sys->dvdnav, 1 ) != DVDNAV_STATUS_OK )
297         {
298             msg_Err( p_demux, "cannot set title (can't decrypt DVD?)" );
299             vlc_dialog_display_error( p_demux, _("Playback failure"), "%s",
300                 _("VLC cannot set the DVD's title. It possibly "
301                   "cannot decrypt the entire disc.") );
302             free( p_sys );
303             return VLC_EGENERIC;
304         }
305
306         if( dvdnav_menu_call( p_sys->dvdnav, DVD_MENU_Title ) !=
307             DVDNAV_STATUS_OK )
308         {
309             /* Try going to menu root */
310             if( dvdnav_menu_call( p_sys->dvdnav, DVD_MENU_Root ) !=
311                 DVDNAV_STATUS_OK )
312                     msg_Warn( p_demux, "cannot go to dvd menu" );
313         }
314     }
315
316     i_angle = var_CreateGetInteger( p_demux, "dvdnav-angle" );
317     if( i_angle <= 0 ) i_angle = 1;
318
319     /* FIXME hack hack hack hack FIXME */
320     /* Get p_input and create variable */
321     var_Create( p_demux->p_input, "x-start", VLC_VAR_INTEGER );
322     var_Create( p_demux->p_input, "y-start", VLC_VAR_INTEGER );
323     var_Create( p_demux->p_input, "x-end", VLC_VAR_INTEGER );
324     var_Create( p_demux->p_input, "y-end", VLC_VAR_INTEGER );
325     var_Create( p_demux->p_input, "color", VLC_VAR_ADDRESS );
326     var_Create( p_demux->p_input, "menu-palette", VLC_VAR_ADDRESS );
327     var_Create( p_demux->p_input, "highlight", VLC_VAR_BOOL );
328
329     /* catch vout creation event */
330     var_AddCallback( p_demux->p_input, "intf-event", EventIntf, p_demux );
331
332     p_sys->still.b_enabled = false;
333     vlc_mutex_init( &p_sys->still.lock );
334     if( !vlc_timer_create( &p_sys->still.timer, StillTimer, p_sys ) )
335         p_sys->still.b_created = true;
336
337     return VLC_SUCCESS;
338 }
339
340 /*****************************************************************************
341  * AccessDemuxOpen:
342  *****************************************************************************/
343 static int AccessDemuxOpen ( vlc_object_t *p_this )
344 {
345     demux_t *p_demux = (demux_t*)p_this;
346     dvdnav_t *p_dvdnav = NULL;
347     char *psz_file = NULL;
348     const char *psz_path = NULL;
349     int i_ret = VLC_EGENERIC;
350     bool forced = false;
351
352     if (p_demux->out == NULL)
353         return VLC_EGENERIC;
354
355     if( !strncasecmp(p_demux->psz_url, "dvd", 3) )
356         forced = true;
357
358     if( !p_demux->psz_filepath || !*p_demux->psz_filepath )
359     {
360         /* Only when selected */
361         if( !forced )
362             return VLC_EGENERIC;
363
364         psz_file = var_InheritString( p_this, "dvd" );
365     }
366     else
367         psz_file = strdup( p_demux->psz_filepath );
368
369 #if defined( _WIN32 ) || defined( __OS2__ )
370     if( psz_file != NULL )
371     {
372         /* Remove trailing backslash, otherwise dvdnav_open will fail */
373         size_t flen = strlen( psz_file );
374         if( flen > 0 && psz_file[flen - 1] == '\\' )
375             psz_file[flen - 1] = '\0';
376     }
377     else
378         psz_file = strdup("");
379 #endif
380
381     if( unlikely(psz_file == NULL) )
382         return VLC_EGENERIC;
383
384     /* Try some simple probing to avoid going through dvdnav_open too often */
385     if( !forced && ProbeDVD( psz_file ) != VLC_SUCCESS )
386         goto bailout;
387
388     /* Open dvdnav */
389     psz_path = ToLocale( psz_file );
390     if( dvdnav_open( &p_dvdnav, psz_path ) != DVDNAV_STATUS_OK )
391     {
392         msg_Warn( p_demux, "cannot open DVD (%s)", psz_file);
393         goto bailout;
394     }
395
396     i_ret = CommonOpen( p_this, p_dvdnav, !!DVD_READ_CACHE );
397     if( i_ret != VLC_SUCCESS )
398         dvdnav_close( p_dvdnav );
399
400 bailout:
401     free( psz_file );
402     if( psz_path )
403         LocaleFree( psz_path );
404     return i_ret;
405 }
406
407 #ifdef HAVE_DVDNAV_DEMUX
408 /*****************************************************************************
409  * StreamProbeDVD: very weak probing that avoids going too often into a dvdnav_open()
410  *****************************************************************************/
411 static int StreamProbeDVD( stream_t *s )
412 {
413     /* first sector should be filled with zeros */
414     ssize_t i_peek;
415     const uint8_t *p_peek;
416     i_peek = vlc_stream_Peek( s, &p_peek, 2048 );
417     if( i_peek < 512 ) {
418         return VLC_EGENERIC;
419     }
420     while (i_peek > 0) {
421         if (p_peek[ --i_peek ]) {
422             return VLC_EGENERIC;
423         }
424     }
425
426     /* ISO 9660 volume descriptor */
427     char iso_dsc[6];
428     if( vlc_stream_Seek( s, 0x8000 + 1 ) != VLC_SUCCESS
429      || vlc_stream_Read( s, iso_dsc, sizeof (iso_dsc) ) < (int)sizeof (iso_dsc)
430      || memcmp( iso_dsc, "CD001\x01", 6 ) )
431         return VLC_EGENERIC;
432
433     /* Try to find the anchor (2 bytes at LBA 256) */
434     uint16_t anchor;
435
436     if( vlc_stream_Seek( s, 256 * DVD_VIDEO_LB_LEN ) == VLC_SUCCESS
437      && vlc_stream_Read( s, &anchor, 2 ) == 2
438      && GetWLE( &anchor ) == 2 )
439         return VLC_SUCCESS;
440     else
441         return VLC_EGENERIC;
442 }
443
444 /*****************************************************************************
445  * dvdnav stream callbacks
446  *****************************************************************************/
447 static int stream_cb_seek( void *s, uint64_t pos )
448 {
449     return vlc_stream_Seek( (stream_t *)s, pos );
450 }
451
452 static int stream_cb_read( void *s, void* buffer, int size )
453 {
454     return vlc_stream_Read( (stream_t *)s, buffer, size );
455 }
456
457 /*****************************************************************************
458  * DemuxOpen:
459  *****************************************************************************/
460 static int DemuxOpen ( vlc_object_t *p_this )
461 {
462     demux_t *p_demux = (demux_t*)p_this;
463     dvdnav_t *p_dvdnav = NULL;
464     bool forced = false, b_seekable = false;
465
466     if( p_demux->psz_name != NULL && !strncmp(p_demux->psz_name, "dvd", 3) )
467         forced = true;
468
469     /* StreamProbeDVD need FASTSEEK, but if dvd is forced, we don't probe thus
470      * don't need fastseek */
471     vlc_stream_Control( p_demux->s, forced ? STREAM_CAN_SEEK : STREAM_CAN_FASTSEEK,
472                     &b_seekable );
473     if( !b_seekable )
474         return VLC_EGENERIC;
475
476     /* Try some simple probing to avoid going through dvdnav_open too often */
477     if( !forced && StreamProbeDVD( p_demux->s ) != VLC_SUCCESS )
478         return VLC_EGENERIC;
479
480     static dvdnav_stream_cb stream_cb =
481     {
482         .pf_seek = stream_cb_seek,
483         .pf_read = stream_cb_read,
484         .pf_readv = NULL,
485     };
486
487     /* Open dvdnav with stream callbacks */
488     if( dvdnav_open_stream( &p_dvdnav, p_demux->s,
489                             &stream_cb ) != DVDNAV_STATUS_OK )
490     {
491         msg_Warn( p_demux, "cannot open DVD with open_stream" );
492         return VLC_EGENERIC;
493     }
494
495     int i_ret = CommonOpen( p_this, p_dvdnav, false );
496     if( i_ret != VLC_SUCCESS )
497         dvdnav_close( p_dvdnav );
498     return i_ret;
499 }
500 #endif
501
502 /*****************************************************************************
503  * Close:
504  *****************************************************************************/
505 static void Close( vlc_object_t *p_this )
506 {
507     demux_t     *p_demux = (demux_t*)p_this;
508     demux_sys_t *p_sys = p_demux->p_sys;
509
510     /* Stop vout event handler */
511     var_DelCallback( p_demux->p_input, "intf-event", EventIntf, p_demux );
512     if( p_sys->p_vout != NULL )
513     {   /* Should not happen, but better be safe than sorry. */
514         msg_Warn( p_sys->p_vout, "removing dangling mouse DVD callbacks" );
515         var_DelCallback( p_sys->p_vout, "mouse-moved", EventMouse, p_demux );
516         var_DelCallback( p_sys->p_vout, "mouse-clicked", EventMouse, p_demux );
517     }
518
519     /* Stop still image handler */
520     if( p_sys->still.b_created )
521         vlc_timer_destroy( p_sys->still.timer );
522     vlc_mutex_destroy( &p_sys->still.lock );
523
524     var_Destroy( p_demux->p_input, "highlight" );
525     var_Destroy( p_demux->p_input, "x-start" );
526     var_Destroy( p_demux->p_input, "x-end" );
527     var_Destroy( p_demux->p_input, "y-start" );
528     var_Destroy( p_demux->p_input, "y-end" );
529     var_Destroy( p_demux->p_input, "color" );
530     var_Destroy( p_demux->p_input, "menu-palette" );
531
532     for( int i = 0; i < PS_TK_COUNT; i++ )
533     {
534         ps_track_t *tk = &p_sys->tk[i];
535         if( tk->b_configured )
536         {
537             es_format_Clean( &tk->fmt );
538             if( tk->es ) es_out_Del( p_demux->out, tk->es );
539         }
540     }
541
542     /* Free the array of titles */
543     for( int i = 0; i < p_sys->i_title; i++ )
544         vlc_input_title_Delete( p_sys->title[i] );
545     TAB_CLEAN( p_sys->i_title, p_sys->title );
546
547     dvdnav_close( p_sys->dvdnav );
548     free( p_sys );
549 }
550
551 /*****************************************************************************
552  * Control:
553  *****************************************************************************/
554 static int Control( demux_t *p_demux, int i_query, va_list args )
555 {
556     demux_sys_t *p_sys = p_demux->p_sys;
557     input_title_t ***ppp_title;
558     int i;
559
560     switch( i_query )
561     {
562         case DEMUX_SET_POSITION:
563         case DEMUX_GET_POSITION:
564         case DEMUX_GET_TIME:
565         case DEMUX_GET_LENGTH:
566         {
567             uint32_t pos, len;
568             if( dvdnav_get_position( p_sys->dvdnav, &pos, &len ) !=
569                   DVDNAV_STATUS_OK || len == 0 )
570             {
571                 return VLC_EGENERIC;
572             }
573
574             switch( i_query )
575             {
576             case DEMUX_GET_POSITION:
577                 *va_arg( args, double* ) = (double)pos / (double)len;
578                 return VLC_SUCCESS;
579
580             case DEMUX_SET_POSITION:
581                 pos = va_arg( args, double ) * len;
582                 if( dvdnav_sector_search( p_sys->dvdnav, pos, SEEK_SET ) ==
583                       DVDNAV_STATUS_OK )
584                 {
585                     return VLC_SUCCESS;
586                 }
587                 break;
588
589             case DEMUX_GET_TIME:
590                 if( p_sys->i_pgc_length > 0 )
591                 {
592                     *va_arg( args, int64_t * ) = p_sys->i_pgc_length*pos/len;
593                     return VLC_SUCCESS;
594                 }
595                 break;
596
597             case DEMUX_GET_LENGTH:
598                 if( p_sys->i_pgc_length > 0 )
599                 {
600                     *va_arg( args, int64_t * ) = (int64_t)p_sys->i_pgc_length;
601                     return VLC_SUCCESS;
602                 }
603                 break;
604             }
605             return VLC_EGENERIC;
606         }
607
608         /* Special for access_demux */
609         case DEMUX_CAN_PAUSE:
610         case DEMUX_CAN_SEEK:
611         case DEMUX_CAN_CONTROL_PACE:
612             /* TODO */
613             *va_arg( args, bool * ) = true;
614             return VLC_SUCCESS;
615
616         case DEMUX_SET_PAUSE_STATE:
617             return VLC_SUCCESS;
618
619         case DEMUX_GET_TITLE_INFO:
620             ppp_title = va_arg( args, input_title_t*** );
621             *va_arg( args, int* ) = p_sys->i_title;
622             *va_arg( args, int* ) = 0; /* Title offset */
623             *va_arg( args, int* ) = 1; /* Chapter offset */
624
625             /* Duplicate title infos */
626             *ppp_title = vlc_alloc( p_sys->i_title, sizeof( input_title_t * ) );
627             for( i = 0; i < p_sys->i_title; i++ )
628             {
629                 (*ppp_title)[i] = vlc_input_title_Duplicate( p_sys->title[i] );
630             }
631             return VLC_SUCCESS;
632
633         case DEMUX_SET_TITLE:
634             i = va_arg( args, int );
635             if( i == 0 && dvdnav_menu_call( p_sys->dvdnav, DVD_MENU_Root )
636                   != DVDNAV_STATUS_OK )
637             {
638                 msg_Warn( p_demux, "cannot set title/chapter" );
639                 return VLC_EGENERIC;
640             }
641
642             if( i != 0 )
643             {
644                 dvdnav_still_skip( p_sys->dvdnav );
645                 if( dvdnav_title_play( p_sys->dvdnav, i ) != DVDNAV_STATUS_OK )
646                 {
647                     msg_Warn( p_demux, "cannot set title/chapter" );
648                     return VLC_EGENERIC;
649                 }
650             }
651
652             p_sys->updates |= INPUT_UPDATE_TITLE | INPUT_UPDATE_SEEKPOINT;
653             p_sys->cur_title = i;
654             p_sys->cur_seekpoint = 0;
655             return VLC_SUCCESS;
656
657         case DEMUX_SET_SEEKPOINT:
658             i = va_arg( args, int );
659             if( p_sys->cur_title == 0 )
660             {
661                 static const int argtab[] = {
662                     DVD_MENU_Escape,
663                     DVD_MENU_Root,
664                     DVD_MENU_Title,
665                     DVD_MENU_Part,
666                     DVD_MENU_Subpicture,
667                     DVD_MENU_Audio,
668                     DVD_MENU_Angle
669                 };
670                 enum { numargs = sizeof(argtab)/sizeof(int) };
671                 if( (unsigned)i >= numargs || DVDNAV_STATUS_OK !=
672                            dvdnav_menu_call(p_sys->dvdnav,argtab[i]) )
673                     return VLC_EGENERIC;
674             }
675             else if( dvdnav_part_play( p_sys->dvdnav, p_sys->cur_title,
676                                        i + 1 ) != DVDNAV_STATUS_OK )
677             {
678                 msg_Warn( p_demux, "cannot set title/chapter" );
679                 return VLC_EGENERIC;
680             }
681             p_sys->updates |= INPUT_UPDATE_SEEKPOINT;
682             p_sys->cur_seekpoint = i;
683             return VLC_SUCCESS;
684
685         case DEMUX_TEST_AND_CLEAR_FLAGS:
686         {
687             unsigned *restrict flags = va_arg(args, unsigned *);
688             *flags &= p_sys->updates;
689             p_sys->updates &= ~*flags;
690             break;
691         }
692
693         case DEMUX_GET_TITLE:
694             *va_arg( args, int * ) = p_sys->cur_title;
695             break;
696
697         case DEMUX_GET_SEEKPOINT:
698             *va_arg( args, int * ) = p_sys->cur_seekpoint;
699             break;
700
701         case DEMUX_GET_PTS_DELAY:
702             *va_arg( args, int64_t * ) =
703                 INT64_C(1000) * var_InheritInteger( p_demux, "disc-caching" );
704             return VLC_SUCCESS;
705
706         case DEMUX_GET_META:
707         {
708             const char *title_name = NULL;
709
710             dvdnav_get_title_string(p_sys->dvdnav, &title_name);
711             if( (NULL != title_name) && ('\0' != title_name[0]) )
712             {
713                 vlc_meta_t *p_meta = va_arg( args, vlc_meta_t* );
714                 vlc_meta_Set( p_meta, vlc_meta_Title, title_name );
715                 return VLC_SUCCESS;
716             }
717             return VLC_EGENERIC;
718         }
719
720         case DEMUX_NAV_ACTIVATE:
721         {
722             pci_t *pci = dvdnav_get_current_nav_pci( p_sys->dvdnav );
723
724             if( dvdnav_button_activate( p_sys->dvdnav, pci ) != DVDNAV_STATUS_OK )
725                 return VLC_EGENERIC;
726             ButtonUpdate( p_demux, true );
727             break;
728         }
729
730         case DEMUX_NAV_UP:
731         {
732             pci_t *pci = dvdnav_get_current_nav_pci( p_sys->dvdnav );
733
734             if( dvdnav_upper_button_select( p_sys->dvdnav, pci ) != DVDNAV_STATUS_OK )
735                 return VLC_EGENERIC;
736             break;
737         }
738
739         case DEMUX_NAV_DOWN:
740         {
741             pci_t *pci = dvdnav_get_current_nav_pci( p_sys->dvdnav );
742
743             if( dvdnav_lower_button_select( p_sys->dvdnav, pci ) != DVDNAV_STATUS_OK )
744                 return VLC_EGENERIC;
745             break;
746         }
747
748         case DEMUX_NAV_LEFT:
749         {
750             pci_t *pci = dvdnav_get_current_nav_pci( p_sys->dvdnav );
751
752             if( dvdnav_left_button_select( p_sys->dvdnav, pci ) != DVDNAV_STATUS_OK )
753                 return VLC_EGENERIC;
754             break;
755         }
756
757         case DEMUX_NAV_RIGHT:
758         {
759             pci_t *pci = dvdnav_get_current_nav_pci( p_sys->dvdnav );
760
761             if( dvdnav_right_button_select( p_sys->dvdnav, pci ) != DVDNAV_STATUS_OK )
762                 return VLC_EGENERIC;
763             break;
764         }
765
766         case DEMUX_NAV_MENU:
767         {
768             if( dvdnav_menu_call( p_sys->dvdnav, DVD_MENU_Title )
769                 != DVDNAV_STATUS_OK )
770             {
771                 msg_Warn( p_demux, "cannot select Title menu" );
772                 if( dvdnav_menu_call( p_sys->dvdnav, DVD_MENU_Root )
773                     != DVDNAV_STATUS_OK )
774                 {
775                     msg_Warn( p_demux, "cannot select Root menu" );
776                     return VLC_EGENERIC;
777                 }
778             }
779             p_sys->updates |= INPUT_UPDATE_TITLE | INPUT_UPDATE_SEEKPOINT;
780             p_sys->cur_title = 0;
781             p_sys->cur_seekpoint = 2;
782             break;
783         }
784
785         /* TODO implement others */
786         default:
787             return VLC_EGENERIC;
788     }
789
790     return VLC_SUCCESS;
791 }
792
793 static int ControlInternal( demux_t *p_demux, int i_query, ... )
794 {
795     va_list args;
796     int     i_result;
797
798     va_start( args, i_query );
799     i_result = Control( p_demux, i_query, args );
800     va_end( args );
801
802     return i_result;
803 }
804 /*****************************************************************************
805  * Demux:
806  *****************************************************************************/
807 static int Demux( demux_t *p_demux )
808 {
809     demux_sys_t *p_sys = p_demux->p_sys;
810
811     uint8_t buffer[DVD_VIDEO_LB_LEN];
812     uint8_t *packet = buffer;
813     int i_event;
814     int i_len;
815     dvdnav_status_t status;
816
817     if( p_sys->b_readahead )
818         status = dvdnav_get_next_cache_block( p_sys->dvdnav, &packet, &i_event,
819                                               &i_len );
820     else
821         status = dvdnav_get_next_block( p_sys->dvdnav, packet, &i_event,
822                                         &i_len );
823     if( status == DVDNAV_STATUS_ERR )
824     {
825         msg_Warn( p_demux, "cannot get next block (%s)",
826                   dvdnav_err_to_string( p_sys->dvdnav ) );
827         if( p_sys->cur_title == 0 )
828         {
829             msg_Dbg( p_demux, "jumping to first title" );
830             return ControlInternal( p_demux, DEMUX_SET_TITLE, 1 ) == VLC_SUCCESS ? 1 : -1;
831         }
832         return -1;
833     }
834
835     switch( i_event )
836     {
837     case DVDNAV_BLOCK_OK:   /* mpeg block */
838         vlc_mutex_lock( &p_sys->still.lock );
839         vlc_timer_schedule( p_sys->still.timer, false, 0, 0 );
840         p_sys->still.b_enabled = false;
841         vlc_mutex_unlock( &p_sys->still.lock );
842         if( p_sys->b_reset_pcr )
843         {
844             es_out_Control( p_demux->out, ES_OUT_RESET_PCR );
845             p_sys->b_reset_pcr = false;
846         }
847         DemuxBlock( p_demux, packet, i_len );
848         if( p_sys->i_vobu_index > 0 )
849         {
850             if( p_sys->i_vobu_flush == p_sys->i_vobu_index )
851                 DemuxForceStill( p_demux );
852             p_sys->i_vobu_index++;
853         }
854         break;
855
856     case DVDNAV_NOP:    /* Nothing */
857         msg_Dbg( p_demux, "DVDNAV_NOP" );
858         break;
859
860     case DVDNAV_STILL_FRAME:
861     {
862         dvdnav_still_event_t *event = (dvdnav_still_event_t*)packet;
863         bool b_still_init = false;
864
865         vlc_mutex_lock( &p_sys->still.lock );
866         if( !p_sys->still.b_enabled )
867         {
868             msg_Dbg( p_demux, "DVDNAV_STILL_FRAME" );
869             msg_Dbg( p_demux, "     - length=0x%x", event->length );
870             p_sys->still.b_enabled = true;
871
872             if( event->length != 0xff && p_sys->still.b_created )
873             {
874                 vlc_tick_t delay = event->length * CLOCK_FREQ;
875                 vlc_timer_schedule( p_sys->still.timer, false, delay, 0 );
876             }
877
878             b_still_init = true;
879         }
880         vlc_mutex_unlock( &p_sys->still.lock );
881
882         if( b_still_init )
883         {
884             DemuxForceStill( p_demux );
885             p_sys->b_reset_pcr = true;
886         }
887         vlc_tick_sleep( 40000 );
888         break;
889     }
890
891     case DVDNAV_SPU_CLUT_CHANGE:
892     {
893         int i;
894
895         msg_Dbg( p_demux, "DVDNAV_SPU_CLUT_CHANGE" );
896         /* Update color lookup table (16 *uint32_t in packet) */
897         memcpy( p_sys->clut, packet, 16 * sizeof( uint32_t ) );
898
899         /* HACK to get the SPU tracks registered in the right order */
900         for( i = 0; i < 0x1f; i++ )
901         {
902             if( dvdnav_spu_stream_to_lang( p_sys->dvdnav, i ) != 0xffff )
903                 ESNew( p_demux, 0xbd20 + i );
904         }
905         /* END HACK */
906         break;
907     }
908
909     case DVDNAV_SPU_STREAM_CHANGE:
910     {
911         dvdnav_spu_stream_change_event_t *event =
912             (dvdnav_spu_stream_change_event_t*)packet;
913         int i;
914
915         msg_Dbg( p_demux, "DVDNAV_SPU_STREAM_CHANGE" );
916         msg_Dbg( p_demux, "     - physical_wide=%d",
917                  event->physical_wide );
918         msg_Dbg( p_demux, "     - physical_letterbox=%d",
919                  event->physical_letterbox);
920         msg_Dbg( p_demux, "     - physical_pan_scan=%d",
921                  event->physical_pan_scan );
922
923         ESSubtitleUpdate( p_demux );
924         p_sys->b_spu_change = true;
925
926         /* HACK to get the SPU tracks registered in the right order */
927         for( i = 0; i < 0x1f; i++ )
928         {
929             if( dvdnav_spu_stream_to_lang( p_sys->dvdnav, i ) != 0xffff )
930                 ESNew( p_demux, 0xbd20 + i );
931         }
932         /* END HACK */
933         break;
934     }
935
936     case DVDNAV_AUDIO_STREAM_CHANGE:
937     {
938         dvdnav_audio_stream_change_event_t *event =
939             (dvdnav_audio_stream_change_event_t*)packet;
940         msg_Dbg( p_demux, "DVDNAV_AUDIO_STREAM_CHANGE" );
941         msg_Dbg( p_demux, "     - physical=%d", event->physical );
942         /* TODO */
943         break;
944     }
945
946     case DVDNAV_VTS_CHANGE:
947     {
948         int32_t i_title = 0;
949         int32_t i_part  = 0;
950
951         dvdnav_vts_change_event_t *event = (dvdnav_vts_change_event_t*)packet;
952         msg_Dbg( p_demux, "DVDNAV_VTS_CHANGE" );
953         msg_Dbg( p_demux, "     - vtsN=%d", event->new_vtsN );
954         msg_Dbg( p_demux, "     - domain=%d", event->new_domain );
955
956         /* reset PCR */
957         es_out_Control( p_demux->out, ES_OUT_RESET_PCR );
958
959         for( int i = 0; i < PS_TK_COUNT; i++ )
960         {
961             ps_track_t *tk = &p_sys->tk[i];
962             if( tk->b_configured )
963             {
964                 es_format_Clean( &tk->fmt );
965                 if( tk->es ) es_out_Del( p_demux->out, tk->es );
966             }
967             tk->b_configured = false;
968         }
969
970         uint32_t i_width, i_height;
971         if( dvdnav_get_video_resolution( p_sys->dvdnav,
972                                          &i_width, &i_height ) )
973             i_width = i_height = 0;
974         switch( dvdnav_get_video_aspect( p_sys->dvdnav ) )
975         {
976         case 0:
977             p_sys->sar.i_num = 4 * i_height;
978             p_sys->sar.i_den = 3 * i_width;
979             break;
980         case 3:
981             p_sys->sar.i_num = 16 * i_height;
982             p_sys->sar.i_den =  9 * i_width;
983             break;
984         default:
985             p_sys->sar.i_num = 0;
986             p_sys->sar.i_den = 0;
987             break;
988         }
989
990         if( dvdnav_current_title_info( p_sys->dvdnav, &i_title,
991                                        &i_part ) == DVDNAV_STATUS_OK )
992         {
993             if( i_title >= 0 && i_title < p_sys->i_title &&
994                 p_sys->cur_title != i_title )
995             {
996                 p_sys->updates |= INPUT_UPDATE_TITLE;
997                 p_sys->cur_title = i_title;
998             }
999         }
1000         break;
1001     }
1002
1003     case DVDNAV_CELL_CHANGE:
1004     {
1005         int32_t i_title = 0;
1006         int32_t i_part  = 0;
1007
1008         dvdnav_cell_change_event_t *event =
1009             (dvdnav_cell_change_event_t*)packet;
1010         msg_Dbg( p_demux, "DVDNAV_CELL_CHANGE" );
1011         msg_Dbg( p_demux, "     - cellN=%d", event->cellN );
1012         msg_Dbg( p_demux, "     - pgN=%d", event->pgN );
1013         msg_Dbg( p_demux, "     - cell_length=%"PRId64, event->cell_length );
1014         msg_Dbg( p_demux, "     - pg_length=%"PRId64, event->pg_length );
1015         msg_Dbg( p_demux, "     - pgc_length=%"PRId64, event->pgc_length );
1016         msg_Dbg( p_demux, "     - cell_start=%"PRId64, event->cell_start );
1017         msg_Dbg( p_demux, "     - pg_start=%"PRId64, event->pg_start );
1018
1019         /* Store the length in time of the current PGC */
1020         p_sys->i_pgc_length = event->pgc_length / 90 * 1000;
1021         p_sys->i_vobu_index = 0;
1022         p_sys->i_vobu_flush = 0;
1023
1024         for( int i=0; i<PS_TK_COUNT; i++ )
1025             p_sys->tk[i].i_next_block_flags |= BLOCK_FLAG_CELL_DISCONTINUITY;
1026
1027         /* FIXME is it correct or there is better way to know chapter change */
1028         if( dvdnav_current_title_info( p_sys->dvdnav, &i_title,
1029                                        &i_part ) == DVDNAV_STATUS_OK )
1030         {
1031             if( i_title >= 0 && i_title < p_sys->i_title )
1032             {
1033                 p_sys->updates |= INPUT_UPDATE_TITLE;
1034                 p_sys->cur_title = i_title;
1035
1036                 if( i_part >= 1 && i_part <= p_sys->title[i_title]->i_seekpoint )
1037                 {
1038                     p_sys->updates |= INPUT_UPDATE_SEEKPOINT;
1039                     p_sys->cur_seekpoint = i_part - 1;
1040                 }
1041             }
1042         }
1043         break;
1044     }
1045
1046     case DVDNAV_NAV_PACKET:
1047     {
1048         p_sys->i_vobu_index = 1;
1049         p_sys->i_vobu_flush = 0;
1050
1051         /* Look if we have need to force a flush (and when) */
1052         const pci_gi_t *p_pci_gi = &dvdnav_get_current_nav_pci( p_sys->dvdnav )->pci_gi;
1053         if( p_pci_gi->vobu_se_e_ptm != 0 && p_pci_gi->vobu_se_e_ptm < p_pci_gi->vobu_e_ptm )
1054         {
1055             const dsi_gi_t *p_dsi_gi = &dvdnav_get_current_nav_dsi( p_sys->dvdnav )->dsi_gi;
1056             if( p_dsi_gi->vobu_3rdref_ea != 0 )
1057                 p_sys->i_vobu_flush = p_dsi_gi->vobu_3rdref_ea;
1058             else if( p_dsi_gi->vobu_2ndref_ea != 0 )
1059                 p_sys->i_vobu_flush = p_dsi_gi->vobu_2ndref_ea;
1060             else if( p_dsi_gi->vobu_1stref_ea != 0 )
1061                 p_sys->i_vobu_flush = p_dsi_gi->vobu_1stref_ea;
1062         }
1063
1064 #ifdef DVDNAV_DEBUG
1065         msg_Dbg( p_demux, "DVDNAV_NAV_PACKET" );
1066 #endif
1067         /* A lot of thing to do here :
1068          *  - handle packet
1069          *  - fetch pts (for time display)
1070          *  - ...
1071          */
1072         DemuxBlock( p_demux, packet, i_len );
1073         if( p_sys->b_spu_change )
1074         {
1075             ButtonUpdate( p_demux, false );
1076             p_sys->b_spu_change = false;
1077         }
1078         break;
1079     }
1080
1081     case DVDNAV_STOP:   /* EOF */
1082         msg_Dbg( p_demux, "DVDNAV_STOP" );
1083
1084         if( p_sys->b_readahead )
1085             dvdnav_free_cache_block( p_sys->dvdnav, packet );
1086         return 0;
1087
1088     case DVDNAV_HIGHLIGHT:
1089     {
1090         dvdnav_highlight_event_t *event = (dvdnav_highlight_event_t*)packet;
1091         msg_Dbg( p_demux, "DVDNAV_HIGHLIGHT" );
1092         msg_Dbg( p_demux, "     - display=%d", event->display );
1093         msg_Dbg( p_demux, "     - buttonN=%d", event->buttonN );
1094         ButtonUpdate( p_demux, false );
1095         break;
1096     }
1097
1098     case DVDNAV_HOP_CHANNEL:
1099         msg_Dbg( p_demux, "DVDNAV_HOP_CHANNEL" );
1100         p_sys->i_vobu_index = 0;
1101         p_sys->i_vobu_flush = 0;
1102         es_out_Control( p_demux->out, ES_OUT_RESET_PCR );
1103         break;
1104
1105     case DVDNAV_WAIT:
1106         msg_Dbg( p_demux, "DVDNAV_WAIT" );
1107
1108         bool b_empty;
1109         es_out_Control( p_demux->out, ES_OUT_GET_EMPTY, &b_empty );
1110         if( !b_empty )
1111         {
1112             vlc_tick_sleep( 40*1000 );
1113         }
1114         else
1115         {
1116             dvdnav_wait_skip( p_sys->dvdnav );
1117             p_sys->b_reset_pcr = true;
1118         }
1119         break;
1120
1121     default:
1122         msg_Warn( p_demux, "Unknown event (0x%x)", i_event );
1123         break;
1124     }
1125
1126     if( p_sys->b_readahead )
1127         dvdnav_free_cache_block( p_sys->dvdnav, packet );
1128
1129     return 1;
1130 }
1131
1132 /* Get a 2 char code
1133  * FIXME: partiallyy duplicated from src/input/es_out.c
1134  */
1135 static char *DemuxGetLanguageCode( demux_t *p_demux, const char *psz_var )
1136 {
1137     const iso639_lang_t *pl;
1138     char *psz_lang;
1139     char *p;
1140
1141     psz_lang = var_CreateGetString( p_demux, psz_var );
1142     if( !psz_lang )
1143         return strdup(LANGUAGE_DEFAULT);
1144
1145     /* XXX: we will use only the first value
1146      * (and ignore other ones in case of a list) */
1147     if( ( p = strchr( psz_lang, ',' ) ) )
1148         *p = '\0';
1149
1150     for( pl = p_languages; pl->psz_eng_name != NULL; pl++ )
1151     {
1152         if( *psz_lang == '\0' )
1153             continue;
1154         if( !strcasecmp( pl->psz_eng_name, psz_lang ) ||
1155             !strcasecmp( pl->psz_iso639_1, psz_lang ) ||
1156             !strcasecmp( pl->psz_iso639_2T, psz_lang ) ||
1157             !strcasecmp( pl->psz_iso639_2B, psz_lang ) )
1158             break;
1159     }
1160
1161     free( psz_lang );
1162
1163     if( pl->psz_eng_name != NULL )
1164         return strdup( pl->psz_iso639_1 );
1165
1166     return strdup(LANGUAGE_DEFAULT);
1167 }
1168
1169 static void DemuxTitles( demux_t *p_demux )
1170 {
1171     demux_sys_t *p_sys = p_demux->p_sys;
1172     input_title_t *t;
1173     seekpoint_t *s;
1174     int32_t i_titles;
1175
1176     /* Menu */
1177     t = vlc_input_title_New();
1178     t->i_flags = INPUT_TITLE_MENU | INPUT_TITLE_INTERACTIVE;
1179     t->psz_name = strdup( "DVD Menu" );
1180
1181     s = vlc_seekpoint_New();
1182     s->psz_name = strdup( "Resume" );
1183     TAB_APPEND( t->i_seekpoint, t->seekpoint, s );
1184
1185     s = vlc_seekpoint_New();
1186     s->psz_name = strdup( "Root" );
1187     TAB_APPEND( t->i_seekpoint, t->seekpoint, s );
1188
1189     s = vlc_seekpoint_New();
1190     s->psz_name = strdup( "Title" );
1191     TAB_APPEND( t->i_seekpoint, t->seekpoint, s );
1192
1193     s = vlc_seekpoint_New();
1194     s->psz_name = strdup( "Chapter" );
1195     TAB_APPEND( t->i_seekpoint, t->seekpoint, s );
1196
1197     s = vlc_seekpoint_New();
1198     s->psz_name = strdup( "Subtitle" );
1199     TAB_APPEND( t->i_seekpoint, t->seekpoint, s );
1200
1201     s = vlc_seekpoint_New();
1202     s->psz_name = strdup( "Audio" );
1203     TAB_APPEND( t->i_seekpoint, t->seekpoint, s );
1204
1205     s = vlc_seekpoint_New();
1206     s->psz_name = strdup( "Angle" );
1207     TAB_APPEND( t->i_seekpoint, t->seekpoint, s );
1208
1209     TAB_APPEND( p_sys->i_title, p_sys->title, t );
1210
1211     /* Find out number of titles/chapters */
1212     dvdnav_get_number_of_titles( p_sys->dvdnav, &i_titles );
1213
1214     if( i_titles > 90 )
1215         msg_Err( p_demux, "This is probably an Arccos Protected DVD. This could take time..." );
1216
1217     for( int i = 1; i <= i_titles; i++ )
1218     {
1219         uint64_t i_title_length;
1220         uint64_t *p_chapters_time;
1221
1222         int32_t i_chapters = dvdnav_describe_title_chapters( p_sys->dvdnav, i,
1223                                                             &p_chapters_time,
1224                                                             &i_title_length );
1225         if( i_chapters < 1 )
1226         {
1227             i_title_length = 0;
1228             p_chapters_time = NULL;
1229         }
1230         t = vlc_input_title_New();
1231         t->i_length = i_title_length * 1000 / 90;
1232         for( int j = 0; j < __MAX( i_chapters, 1 ); j++ )
1233         {
1234             s = vlc_seekpoint_New();
1235             if( p_chapters_time )
1236             {
1237                 if ( j > 0 )
1238                     s->i_time_offset = p_chapters_time[j - 1] * 1000 / 90;
1239                 else
1240                     s->i_time_offset = 0;
1241             }
1242             TAB_APPEND( t->i_seekpoint, t->seekpoint, s );
1243         }
1244         free( p_chapters_time );
1245         TAB_APPEND( p_sys->i_title, p_sys->title, t );
1246     }
1247 }
1248
1249 /*****************************************************************************
1250  * Update functions:
1251  *****************************************************************************/
1252 static void ButtonUpdate( demux_t *p_demux, bool b_mode )
1253 {
1254     demux_sys_t *p_sys = p_demux->p_sys;
1255     int32_t i_title, i_part;
1256
1257     dvdnav_current_title_info( p_sys->dvdnav, &i_title, &i_part );
1258
1259     dvdnav_highlight_area_t hl;
1260     int32_t i_button;
1261     bool    b_button_ok;
1262
1263     if( dvdnav_get_current_highlight( p_sys->dvdnav, &i_button )
1264         != DVDNAV_STATUS_OK )
1265     {
1266         msg_Err( p_demux, "dvdnav_get_current_highlight failed" );
1267         return;
1268     }
1269
1270     b_button_ok = false;
1271     if( i_button > 0 && i_title ==  0 )
1272     {
1273         pci_t *pci = dvdnav_get_current_nav_pci( p_sys->dvdnav );
1274
1275         b_button_ok = DVDNAV_STATUS_OK ==
1276                   dvdnav_get_highlight_area( pci, i_button, b_mode, &hl );
1277     }
1278
1279     if( b_button_ok )
1280     {
1281         for( unsigned i = 0; i < 4; i++ )
1282         {
1283             uint32_t i_yuv = p_sys->clut[(hl.palette>>(16+i*4))&0x0f];
1284             uint8_t i_alpha = ( (hl.palette>>(i*4))&0x0f ) * 0xff / 0xf;
1285
1286             p_sys->palette[i][0] = (i_yuv >> 16) & 0xff;
1287             p_sys->palette[i][1] = (i_yuv >> 0) & 0xff;
1288             p_sys->palette[i][2] = (i_yuv >> 8) & 0xff;
1289             p_sys->palette[i][3] = i_alpha;
1290         }
1291
1292         vlc_global_lock( VLC_HIGHLIGHT_MUTEX );
1293         var_SetInteger( p_demux->p_input, "x-start", hl.sx );
1294         var_SetInteger( p_demux->p_input, "x-end",  hl.ex );
1295         var_SetInteger( p_demux->p_input, "y-start", hl.sy );
1296         var_SetInteger( p_demux->p_input, "y-end", hl.ey );
1297
1298         var_SetAddress( p_demux->p_input, "menu-palette", p_sys->palette );
1299         var_SetBool( p_demux->p_input, "highlight", true );
1300
1301         msg_Dbg( p_demux, "buttonUpdate %d", i_button );
1302     }
1303     else
1304     {
1305         msg_Dbg( p_demux, "buttonUpdate not done b=%d t=%d",
1306                  i_button, i_title );
1307
1308         /* Show all */
1309         vlc_global_lock( VLC_HIGHLIGHT_MUTEX );
1310         var_SetBool( p_demux->p_input, "highlight", false );
1311     }
1312     vlc_global_unlock( VLC_HIGHLIGHT_MUTEX );
1313 }
1314
1315 static void ESSubtitleUpdate( demux_t *p_demux )
1316 {
1317     demux_sys_t *p_sys = p_demux->p_sys;
1318     int         i_spu = dvdnav_get_active_spu_stream( p_sys->dvdnav );
1319     int32_t i_title, i_part;
1320
1321     ButtonUpdate( p_demux, false );
1322
1323     dvdnav_current_title_info( p_sys->dvdnav, &i_title, &i_part );
1324     if( i_title > 0 ) return;
1325
1326     /* dvdnav_get_active_spu_stream sets (in)visibility flag as 0xF0 */
1327     if( i_spu >= 0 && i_spu <= 0x1f )
1328     {
1329         ps_track_t *tk = &p_sys->tk[ps_id_to_tk(0xbd20 + i_spu)];
1330
1331         ESNew( p_demux, 0xbd20 + i_spu );
1332
1333         /* be sure to unselect it (reset) */
1334         if( tk->es )
1335         {
1336             es_out_Control( p_demux->out, ES_OUT_SET_ES_STATE, tk->es,
1337                             (bool)false );
1338
1339             /* now select it */
1340             es_out_Control( p_demux->out, ES_OUT_SET_ES, tk->es );
1341         }
1342     }
1343     else
1344     {
1345         for( i_spu = 0; i_spu <= 0x1F; i_spu++ )
1346         {
1347             ps_track_t *tk = &p_sys->tk[ps_id_to_tk(0xbd20 + i_spu)];
1348             if( tk->es )
1349             {
1350                 es_out_Control( p_demux->out, ES_OUT_SET_ES_STATE, tk->es,
1351                                 (bool)false );
1352             }
1353         }
1354     }
1355 }
1356
1357 /*****************************************************************************
1358  * DemuxBlock: demux a given block
1359  *****************************************************************************/
1360 static int DemuxBlock( demux_t *p_demux, const uint8_t *p, int len )
1361 {
1362     demux_sys_t *p_sys = p_demux->p_sys;
1363
1364     while( len > 0 )
1365     {
1366         int i_size = ps_pkt_size( p, len );
1367         if( i_size <= 0 || i_size > len )
1368         {
1369             break;
1370         }
1371
1372         /* Create a block */
1373         block_t *p_pkt = block_Alloc( i_size );
1374         memcpy( p_pkt->p_buffer, p, i_size);
1375
1376         /* Parse it and send it */
1377         switch( 0x100 | p[3] )
1378         {
1379         case 0x1b9:
1380         case 0x1bb:
1381         case 0x1bc:
1382 #ifdef DVDNAV_DEBUG
1383             if( p[3] == 0xbc )
1384             {
1385                 msg_Warn( p_demux, "received a PSM packet" );
1386             }
1387             else if( p[3] == 0xbb )
1388             {
1389                 msg_Warn( p_demux, "received a SYSTEM packet" );
1390             }
1391 #endif
1392             block_Release( p_pkt );
1393             break;
1394
1395         case 0x1ba:
1396         {
1397             int64_t i_scr;
1398             int i_mux_rate;
1399             if( !ps_pkt_parse_pack( p_pkt, &i_scr, &i_mux_rate ) )
1400             {
1401                 es_out_SetPCR( p_demux->out, i_scr + 1 );
1402                 if( i_mux_rate > 0 ) p_sys->i_mux_rate = i_mux_rate;
1403             }
1404             block_Release( p_pkt );
1405             break;
1406         }
1407         default:
1408         {
1409             int i_id = ps_pkt_id( p_pkt );
1410             if( i_id >= 0xc0 )
1411             {
1412                 ps_track_t *tk = &p_sys->tk[ps_id_to_tk(i_id)];
1413
1414                 if( !tk->b_configured )
1415                 {
1416                     ESNew( p_demux, i_id );
1417                 }
1418
1419                 if( tk->es &&
1420                     !ps_pkt_parse_pes( VLC_OBJECT(p_demux), p_pkt, tk->i_skip ) )
1421                 {
1422                     int i_next_block_flags = tk->i_next_block_flags;
1423                     tk->i_next_block_flags = 0;
1424                     if( i_next_block_flags & BLOCK_FLAG_CELL_DISCONTINUITY )
1425                     {
1426                         if( p_pkt->i_dts != VLC_TS_INVALID )
1427                         {
1428                             i_next_block_flags &= ~BLOCK_FLAG_CELL_DISCONTINUITY;
1429                             i_next_block_flags |= BLOCK_FLAG_DISCONTINUITY;
1430                         }
1431                         else tk->i_next_block_flags = BLOCK_FLAG_CELL_DISCONTINUITY;
1432                     }
1433                     p_pkt->i_flags |= i_next_block_flags;
1434                     es_out_Send( p_demux->out, tk->es, p_pkt );
1435                 }
1436                 else
1437                 {
1438                     tk->i_next_block_flags = 0;
1439                     block_Release( p_pkt );
1440                 }
1441             }
1442             else
1443             {
1444                 block_Release( p_pkt );
1445             }
1446             break;
1447         }
1448         }
1449
1450         p += i_size;
1451         len -= i_size;
1452     }
1453
1454     return VLC_SUCCESS;
1455 }
1456
1457 /*****************************************************************************
1458  * Force still images to be displayed by sending EOS and stopping buffering.
1459  *****************************************************************************/
1460 static void DemuxForceStill( demux_t *p_demux )
1461 {
1462     static const uint8_t buffer[] = {
1463         0x00, 0x00, 0x01, 0xe0, 0x00, 0x07,
1464         0x80, 0x00, 0x00,
1465         0x00, 0x00, 0x01, 0xB7,
1466     };
1467     DemuxBlock( p_demux, buffer, sizeof(buffer) );
1468
1469     bool b_empty;
1470     es_out_Control( p_demux->out, ES_OUT_GET_EMPTY, &b_empty );
1471 }
1472
1473 /*****************************************************************************
1474  * ESNew: register a new elementary stream
1475  *****************************************************************************/
1476 static void ESNew( demux_t *p_demux, int i_id )
1477 {
1478     demux_sys_t *p_sys = p_demux->p_sys;
1479     ps_track_t  *tk = &p_sys->tk[ps_id_to_tk(i_id)];
1480     bool  b_select = false;
1481
1482     if( tk->b_configured ) return;
1483
1484     if( ps_track_fill( tk, 0, i_id, NULL, true ) )
1485     {
1486         msg_Warn( p_demux, "unknown codec for id=0x%x", i_id );
1487         return;
1488     }
1489
1490     /* Add a new ES */
1491     if( tk->fmt.i_cat == VIDEO_ES )
1492     {
1493         tk->fmt.video.i_sar_num = p_sys->sar.i_num;
1494         tk->fmt.video.i_sar_den = p_sys->sar.i_den;
1495         b_select = true;
1496     }
1497     else if( tk->fmt.i_cat == AUDIO_ES )
1498     {
1499         int i_audio = -1;
1500         /* find the audio number PLEASE find another way */
1501         if( (i_id&0xbdf8) == 0xbd88 )       /* dts */
1502         {
1503             i_audio = i_id&0x07;
1504         }
1505         else if( (i_id&0xbdf0) == 0xbd80 )  /* a52 */
1506         {
1507             i_audio = i_id&0xf;
1508         }
1509         else if( (i_id&0xbdf0) == 0xbda0 )  /* lpcm */
1510         {
1511             i_audio = i_id&0x1f;
1512         }
1513         else if( ( i_id&0xe0 ) == 0xc0 )    /* mpga */
1514         {
1515             i_audio = i_id&0x1f;
1516         }
1517         if( i_audio >= 0 )
1518         {
1519             int i_lang = dvdnav_audio_stream_to_lang( p_sys->dvdnav, i_audio );
1520             if( i_lang != 0xffff )
1521             {
1522                 tk->fmt.psz_language = malloc( 3 );
1523                 tk->fmt.psz_language[0] = (i_lang >> 8)&0xff;
1524                 tk->fmt.psz_language[1] = (i_lang     )&0xff;
1525                 tk->fmt.psz_language[2] = 0;
1526             }
1527             if( dvdnav_get_active_audio_stream( p_sys->dvdnav ) == i_audio )
1528             {
1529                 b_select = true;
1530             }
1531         }
1532     }
1533     else if( tk->fmt.i_cat == SPU_ES )
1534     {
1535         int32_t i_title, i_part;
1536         int i_lang = dvdnav_spu_stream_to_lang( p_sys->dvdnav, i_id&0x1f );
1537         if( i_lang != 0xffff )
1538         {
1539             tk->fmt.psz_language = malloc( 3 );
1540             tk->fmt.psz_language[0] = (i_lang >> 8)&0xff;
1541             tk->fmt.psz_language[1] = (i_lang     )&0xff;
1542             tk->fmt.psz_language[2] = 0;
1543         }
1544
1545         /* Palette */
1546         tk->fmt.subs.spu.palette[0] = SPU_PALETTE_DEFINED;
1547         memcpy( &tk->fmt.subs.spu.palette[1], p_sys->clut,
1548                 16 * sizeof( uint32_t ) );
1549
1550         /* We select only when we are not in the menu */
1551         dvdnav_current_title_info( p_sys->dvdnav, &i_title, &i_part );
1552         if( i_title > 0 &&
1553             dvdnav_get_active_spu_stream( p_sys->dvdnav ) == (i_id&0x1f) )
1554         {
1555             b_select = true;
1556         }
1557     }
1558
1559     tk->fmt.i_id = i_id;
1560     tk->es = es_out_Add( p_demux->out, &tk->fmt );
1561     if( b_select && tk->es )
1562     {
1563         es_out_Control( p_demux->out, ES_OUT_SET_ES, tk->es );
1564     }
1565     tk->b_configured = true;
1566
1567     if( tk->fmt.i_cat == VIDEO_ES ) ButtonUpdate( p_demux, false );
1568 }
1569
1570 /*****************************************************************************
1571  * Still image end
1572  *****************************************************************************/
1573 static void StillTimer( void *p_data )
1574 {
1575     demux_sys_t    *p_sys = p_data;
1576
1577     vlc_mutex_lock( &p_sys->still.lock );
1578     if( likely(p_sys->still.b_enabled) )
1579     {
1580         p_sys->still.b_enabled = false;
1581         dvdnav_still_skip( p_sys->dvdnav );
1582     }
1583     vlc_mutex_unlock( &p_sys->still.lock );
1584 }
1585
1586 static int EventMouse( vlc_object_t *p_vout, char const *psz_var,
1587                        vlc_value_t oldval, vlc_value_t val, void *p_data )
1588 {
1589     demux_t *p_demux = p_data;
1590     demux_sys_t *p_sys = p_demux->p_sys;
1591
1592     /* FIXME? PCI usage thread safe? */
1593     pci_t *pci = dvdnav_get_current_nav_pci( p_sys->dvdnav );
1594     int x = val.coords.x;
1595     int y = val.coords.y;
1596
1597     if( psz_var[6] == 'm' ) /* mouse-moved */
1598         dvdnav_mouse_select( p_sys->dvdnav, pci, x, y );
1599     else
1600     {
1601         assert( psz_var[6] == 'c' ); /* mouse-clicked */
1602
1603         ButtonUpdate( p_demux, true );
1604         dvdnav_mouse_activate( p_sys->dvdnav, pci, x, y );
1605     }
1606     (void)p_vout;
1607     (void)oldval;
1608     return VLC_SUCCESS;
1609 }
1610
1611 static int EventIntf( vlc_object_t *p_input, char const *psz_var,
1612                       vlc_value_t oldval, vlc_value_t val, void *p_data )
1613 {
1614     demux_t *p_demux = p_data;
1615     demux_sys_t *p_sys = p_demux->p_sys;
1616
1617     if (val.i_int == INPUT_EVENT_VOUT)
1618     {
1619         if( p_sys->p_vout != NULL )
1620         {
1621             var_DelCallback( p_sys->p_vout, "mouse-moved", EventMouse, p_demux );
1622             var_DelCallback( p_sys->p_vout, "mouse-clicked", EventMouse, p_demux );
1623             vlc_object_release( p_sys->p_vout );
1624         }
1625
1626         p_sys->p_vout = input_GetVout( (input_thread_t *)p_input );
1627         if( p_sys->p_vout != NULL )
1628         {
1629             var_AddCallback( p_sys->p_vout, "mouse-moved", EventMouse, p_demux );
1630             var_AddCallback( p_sys->p_vout, "mouse-clicked", EventMouse, p_demux );
1631         }
1632     }
1633     (void) psz_var; (void) oldval;
1634     return VLC_SUCCESS;
1635 }
1636
1637 /*****************************************************************************
1638  * ProbeDVD: very weak probing that avoids going too often into a dvdnav_open()
1639  *****************************************************************************/
1640 static int ProbeDVD( const char *psz_name )
1641 {
1642     if( !*psz_name )
1643         /* Triggers libdvdcss autodetection */
1644         return VLC_SUCCESS;
1645
1646     int fd = vlc_open( psz_name, O_RDONLY | O_NONBLOCK );
1647     if( fd == -1 )
1648 #ifdef HAVE_FDOPENDIR
1649         return VLC_EGENERIC;
1650 #else
1651         return (errno == ENOENT) ? VLC_EGENERIC : VLC_SUCCESS;
1652 #endif
1653
1654     int ret = VLC_EGENERIC;
1655     struct stat stat_info;
1656
1657     if( fstat( fd, &stat_info ) == -1 )
1658          goto bailout;
1659     if( !S_ISREG( stat_info.st_mode ) )
1660     {
1661         if( S_ISDIR( stat_info.st_mode ) || S_ISBLK( stat_info.st_mode ) )
1662             ret = VLC_SUCCESS; /* Let dvdnav_open() do the probing */
1663         goto bailout;
1664     }
1665
1666     /* ISO 9660 volume descriptor */
1667     char iso_dsc[6];
1668     if( lseek( fd, 0x8000 + 1, SEEK_SET ) == -1
1669      || read( fd, iso_dsc, sizeof (iso_dsc) ) < (int)sizeof (iso_dsc)
1670      || memcmp( iso_dsc, "CD001\x01", 6 ) )
1671         goto bailout;
1672
1673     /* Try to find the anchor (2 bytes at LBA 256) */
1674     uint16_t anchor;
1675
1676     if( lseek( fd, 256 * DVD_VIDEO_LB_LEN, SEEK_SET ) != -1
1677      && read( fd, &anchor, 2 ) == 2
1678      && GetWLE( &anchor ) == 2 )
1679         ret = VLC_SUCCESS; /* Found a potential anchor */
1680 bailout:
1681     vlc_close( fd );
1682     return ret;
1683 }