]> git.sesse.net Git - vlc/blob - modules/access/bluray.c
avio: remove interrupt callback for output
[vlc] / modules / access / bluray.c
1 /*****************************************************************************
2  * bluray.c: Blu-ray disc support plugin
3  *****************************************************************************
4  * Copyright © 2010-2012 VideoLAN, VLC authors and libbluray AUTHORS
5  *
6  * Authors: Jean-Baptiste Kempf <jb@videolan.org>
7  *          Hugo Beauzée-Luyssen <hugo@videolan.org>
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 #ifdef HAVE_CONFIG_H
25 # include "config.h"
26 #endif
27
28 #include <assert.h>
29 #include <limits.h>                         /* PATH_MAX */
30
31 #if defined (HAVE_MNTENT_H) && defined(HAVE_SYS_STAT_H)
32 # include <mntent.h>
33 # include <sys/stat.h>
34 #endif
35
36 #ifdef __APPLE__
37 # include <sys/stat.h>
38 # include <sys/param.h>
39 # include <sys/ucred.h>
40 # include <sys/mount.h>
41 #endif
42
43 #include <vlc_common.h>
44 #include <vlc_plugin.h>
45 #include <vlc_demux.h>                      /* demux_t */
46 #include <vlc_input.h>                      /* Seekpoints, chapters */
47 #include <vlc_atomic.h>
48 #include <vlc_dialog.h>                     /* BD+/AACS warnings */
49 #include <vlc_vout.h>                       /* vout_PutSubpicture / subpicture_t */
50 #include <vlc_url.h>                        /* vlc_path2uri */
51 #include <vlc_iso_lang.h>
52
53 /* FIXME we should find a better way than including that */
54 #include "../../src/text/iso-639_def.h"
55
56
57 #include <libbluray/bluray.h>
58 #include <libbluray/bluray-version.h>
59 #include <libbluray/keys.h>
60 #include <libbluray/meta_data.h>
61 #include <libbluray/overlay.h>
62
63 /*****************************************************************************
64  * Module descriptor
65  *****************************************************************************/
66
67 #define BD_MENU_TEXT        N_("Blu-ray menus")
68 #define BD_MENU_LONGTEXT    N_("Use Blu-ray menus. If disabled, "\
69                                 "the movie will start directly")
70 #define BD_REGION_TEXT      N_("Region code")
71 #define BD_REGION_LONGTEXT  N_("Blu-Ray player region code. "\
72                                 "Some discs can be played only with a correct region code.")
73
74 static const char *const ppsz_region_code[] = {
75     "A", "B", "C" };
76 static const char *const ppsz_region_code_text[] = {
77     "Region A", "Region B", "Region C" };
78
79 #define REGION_DEFAULT   1   /* Index to region list. Actual region code is (1<<REGION_DEFAULT) */
80 #define LANGUAGE_DEFAULT ("eng")
81
82 /* Callbacks */
83 static int  blurayOpen (vlc_object_t *);
84 static void blurayClose(vlc_object_t *);
85
86 vlc_module_begin ()
87     set_shortname(N_("Blu-ray"))
88     set_description(N_("Blu-ray Disc support (libbluray)"))
89
90     set_category(CAT_INPUT)
91     set_subcategory(SUBCAT_INPUT_ACCESS)
92     set_capability("access_demux", 200)
93     add_bool("bluray-menu", false, BD_MENU_TEXT, BD_MENU_LONGTEXT, false)
94     add_string("bluray-region", ppsz_region_code[REGION_DEFAULT], BD_REGION_TEXT, BD_REGION_LONGTEXT, false)
95         change_string_list(ppsz_region_code, ppsz_region_code_text)
96
97     add_shortcut("bluray", "file")
98
99     set_callbacks(blurayOpen, blurayClose)
100 vlc_module_end ()
101
102 /* libbluray's overlay.h defines 2 types of overlay (bd_overlay_plane_e). */
103 #define MAX_OVERLAY 2
104
105 typedef enum OverlayStatus {
106     Closed = 0,
107     ToDisplay,  //Used to mark the overlay to be displayed the first time.
108     Displayed,
109     Outdated    //used to update the overlay after it has been sent to the vout
110 } OverlayStatus;
111
112 typedef struct bluray_overlay_t
113 {
114     atomic_flag         released_once;
115     vlc_mutex_t         lock;
116     subpicture_t        *p_pic;
117     OverlayStatus       status;
118     subpicture_region_t *p_regions;
119 } bluray_overlay_t;
120
121 struct  demux_sys_t
122 {
123     BLURAY              *bluray;
124
125     /* Titles */
126     unsigned int        i_title;
127     unsigned int        i_longest_title;
128     input_title_t       **pp_title;
129
130     vlc_mutex_t             pl_info_lock;
131     BLURAY_TITLE_INFO      *p_pl_info;
132     const BLURAY_CLIP_INFO *p_clip_info;
133
134     /* Meta information */
135     const META_DL       *p_meta;
136
137     /* Menus */
138     bluray_overlay_t    *p_overlays[MAX_OVERLAY];
139     int                 current_overlay; // -1 if no current overlay;
140     bool                b_menu;
141     bool                b_menu_open;
142     bool                b_popup_available;
143     mtime_t             i_still_end_time;
144
145     /* */
146     input_thread_t      *p_input;
147     vout_thread_t       *p_vout;
148
149     /* TS stream */
150     es_out_t            *p_out;
151     vlc_array_t         es;
152     int                 i_audio_stream; /* Selected audio stream. -1 if default */
153     int                 i_spu_stream;   /* Selected subtitle stream. -1 if default */
154     int                 i_video_stream;
155     stream_t            *p_parser;
156     bool                b_flushed;
157
158     /* Used to store bluray disc path */
159     char                *psz_bd_path;
160 };
161
162 struct subpicture_updater_sys_t
163 {
164     bluray_overlay_t    *p_overlay;
165 };
166
167 /* Get a 3 char code
168  * FIXME: partiallyy duplicated from src/input/es_out.c
169  */
170 static const char *DemuxGetLanguageCode( demux_t *p_demux, const char *psz_var )
171 {
172     const iso639_lang_t *pl;
173     char *psz_lang;
174     char *p;
175
176     psz_lang = var_CreateGetString( p_demux, psz_var );
177     if( !psz_lang )
178         return LANGUAGE_DEFAULT;
179
180     /* XXX: we will use only the first value
181      * (and ignore other ones in case of a list) */
182     if( ( p = strchr( psz_lang, ',' ) ) )
183         *p = '\0';
184
185     for( pl = p_languages; pl->psz_eng_name != NULL; pl++ )
186     {
187         if( *psz_lang == '\0' )
188             continue;
189         if( !strcasecmp( pl->psz_eng_name, psz_lang ) ||
190             !strcasecmp( pl->psz_iso639_1, psz_lang ) ||
191             !strcasecmp( pl->psz_iso639_2T, psz_lang ) ||
192             !strcasecmp( pl->psz_iso639_2B, psz_lang ) )
193             break;
194     }
195
196     free( psz_lang );
197
198     if( pl->psz_eng_name != NULL )
199         return pl->psz_iso639_2T;
200
201     return LANGUAGE_DEFAULT;
202 }
203
204 /*****************************************************************************
205  * Local prototypes
206  *****************************************************************************/
207 static es_out_t *esOutNew(demux_t *p_demux);
208
209 static int   blurayControl(demux_t *, int, va_list);
210 static int   blurayDemux(demux_t *);
211
212 static void  blurayInitTitles(demux_t *p_demux, int menu_titles);
213 static int   bluraySetTitle(demux_t *p_demux, int i_title);
214
215 static void  blurayOverlayProc(void *ptr, const BD_OVERLAY * const overlay);
216 static void  blurayArgbOverlayProc(void *ptr, const BD_ARGB_OVERLAY * const overlay);
217
218 static int   onMouseEvent(vlc_object_t *p_vout, const char *psz_var,
219                           vlc_value_t old, vlc_value_t val, void *p_data);
220
221 static void  blurayResetParser(demux_t *p_demux);
222
223 #define FROM_TICKS(a) (a*CLOCK_FREQ / INT64_C(90000))
224 #define TO_TICKS(a)   (a*INT64_C(90000)/CLOCK_FREQ)
225 #define CUR_LENGTH    p_sys->pp_title[p_demux->info.i_title]->i_length
226
227 /* */
228 static void FindMountPoint(char **file)
229 {
230     char *device = *file;
231 #if defined (HAVE_MNTENT_H) && defined (HAVE_SYS_STAT_H)
232     /* bd path may be a symlink (e.g. /dev/dvd -> /dev/sr0), so make sure
233      * we look up the real device */
234     char *bd_device = realpath(device, NULL);
235     if (bd_device == NULL)
236         return;
237
238     struct stat st;
239     if (lstat (bd_device, &st) == 0 && S_ISBLK (st.st_mode)) {
240         FILE *mtab = setmntent ("/proc/self/mounts", "r");
241         struct mntent *m, mbuf;
242         char buf [8192];
243
244         while ((m = getmntent_r (mtab, &mbuf, buf, sizeof(buf))) != NULL) {
245             if (!strcmp (m->mnt_fsname, bd_device)) {
246                 free(device);
247                 *file = strdup(m->mnt_dir);
248                 break;
249             }
250         }
251         endmntent (mtab);
252     }
253     free(bd_device);
254
255 #elif defined(__APPLE__)
256     struct stat st;
257     if (!stat (device, &st) && S_ISBLK (st.st_mode)) {
258         int fs_count = getfsstat (NULL, 0, MNT_NOWAIT);
259         if (fs_count > 0) {
260             struct statfs mbuf[128];
261             getfsstat (mbuf, fs_count * sizeof(mbuf[0]), MNT_NOWAIT);
262             for (int i = 0; i < fs_count; ++i)
263                 if (!strcmp (mbuf[i].f_mntfromname, device)) {
264                     free(device);
265                     *file = strdup(mbuf[i].f_mntonname);
266                     return;
267                 }
268         }
269     }
270 #else
271 # warning Disc device to mount point not implemented
272 #endif
273 }
274
275 /*****************************************************************************
276  * cache current playlist (title) information
277  *****************************************************************************/
278
279 static void setTitleInfo(demux_sys_t *p_sys, BLURAY_TITLE_INFO *info)
280 {
281     vlc_mutex_lock(&p_sys->pl_info_lock);
282
283     if (p_sys->p_pl_info) {
284         bd_free_title_info(p_sys->p_pl_info);
285     }
286     p_sys->p_pl_info   = info;
287     p_sys->p_clip_info = NULL;
288
289     if (p_sys->p_pl_info && p_sys->p_pl_info->clip_count) {
290         p_sys->p_clip_info = &p_sys->p_pl_info->clips[0];
291     }
292
293     vlc_mutex_unlock(&p_sys->pl_info_lock);
294 }
295
296 /*****************************************************************************
297  * blurayOpen: module init function
298  *****************************************************************************/
299 static int blurayOpen(vlc_object_t *object)
300 {
301     demux_t *p_demux = (demux_t*)object;
302     demux_sys_t *p_sys;
303
304     const char *error_msg = NULL;
305 #define BLURAY_ERROR(s) do { error_msg = s; goto error; } while(0)
306
307     if (strcmp(p_demux->psz_access, "bluray")) {
308         // TODO BDMV support, once we figure out what to do in libbluray
309         return VLC_EGENERIC;
310     }
311
312     /* */
313     p_demux->p_sys = p_sys = calloc(1, sizeof(*p_sys));
314     if (unlikely(!p_sys))
315         return VLC_ENOMEM;
316
317     p_sys->current_overlay = -1;
318     p_sys->i_audio_stream = -1;
319     p_sys->i_spu_stream = -1;
320     p_sys->i_video_stream = -1;
321     p_sys->i_still_end_time = 0;
322
323     /* init demux info fields */
324     p_demux->info.i_update    = 0;
325     p_demux->info.i_title     = 0;
326     p_demux->info.i_seekpoint = 0;
327
328     TAB_INIT(p_sys->i_title, p_sys->pp_title);
329
330     /* store current bd path */
331     if (p_demux->psz_file)
332         p_sys->psz_bd_path = strdup(p_demux->psz_file);
333
334     /* If we're passed a block device, try to convert it to the mount point. */
335     FindMountPoint(&p_sys->psz_bd_path);
336
337     p_sys->bluray = bd_open(p_sys->psz_bd_path, NULL);
338     if (!p_sys->bluray) {
339         free(p_sys->psz_bd_path);
340         free(p_sys);
341         return VLC_EGENERIC;
342     }
343
344     vlc_mutex_init(&p_sys->pl_info_lock);
345
346     /* Warning the user about AACS/BD+ */
347     const BLURAY_DISC_INFO *disc_info = bd_get_disc_info(p_sys->bluray);
348
349     /* Is it a bluray? */
350     if (!disc_info->bluray_detected)
351         BLURAY_ERROR(_("Path doesn't appear to be a Blu-ray"));
352
353     msg_Info(p_demux, "First play: %i, Top menu: %i\n"
354                       "HDMV Titles: %i, BD-J Titles: %i, Other: %i",
355              disc_info->first_play_supported, disc_info->top_menu_supported,
356              disc_info->num_hdmv_titles, disc_info->num_bdj_titles,
357              disc_info->num_unsupported_titles);
358
359     /* AACS */
360     if (disc_info->aacs_detected) {
361         msg_Dbg(p_demux, "Disc is using AACS");
362         if (!disc_info->libaacs_detected)
363             BLURAY_ERROR(_("This Blu-ray Disc needs a library for AACS decoding"
364                       ", and your system does not have it."));
365         if (!disc_info->aacs_handled) {
366             if (disc_info->aacs_error_code) {
367                 switch (disc_info->aacs_error_code) {
368                 case BD_AACS_CORRUPTED_DISC:
369                     BLURAY_ERROR(_("Blu-ray Disc is corrupted."));
370                 case BD_AACS_NO_CONFIG:
371                     BLURAY_ERROR(_("Missing AACS configuration file!"));
372                 case BD_AACS_NO_PK:
373                     BLURAY_ERROR(_("No valid processing key found in AACS config file."));
374                 case BD_AACS_NO_CERT:
375                     BLURAY_ERROR(_("No valid host certificate found in AACS config file."));
376                 case BD_AACS_CERT_REVOKED:
377                     BLURAY_ERROR(_("AACS Host certificate revoked."));
378                 case BD_AACS_MMC_FAILED:
379                     BLURAY_ERROR(_("AACS MMC failed."));
380                 }
381             }
382         }
383     }
384
385     /* BD+ */
386     if (disc_info->bdplus_detected) {
387         msg_Dbg(p_demux, "Disc is using BD+");
388         if (!disc_info->libbdplus_detected)
389             BLURAY_ERROR(_("This Blu-ray Disc needs a library for BD+ decoding"
390                       ", and your system does not have it."));
391         if (!disc_info->bdplus_handled)
392             BLURAY_ERROR(_("Your system BD+ decoding library does not work. "
393                       "Missing configuration?"));
394     }
395
396     /* set player region code */
397     char *psz_region = var_InheritString(p_demux, "bluray-region");
398     unsigned int region = psz_region ? (psz_region[0] - 'A') : REGION_DEFAULT;
399     free(psz_region);
400     bd_set_player_setting(p_sys->bluray, BLURAY_PLAYER_SETTING_REGION_CODE, 1<<region);
401
402     /* set preferred languages */
403     const char *psz_code = DemuxGetLanguageCode( p_demux, "audio-language" );
404     bd_set_player_setting_str(p_sys->bluray, BLURAY_PLAYER_SETTING_AUDIO_LANG, psz_code);
405     psz_code = DemuxGetLanguageCode( p_demux, "sub-language" );
406     bd_set_player_setting_str(p_sys->bluray, BLURAY_PLAYER_SETTING_PG_LANG,    psz_code);
407     psz_code = DemuxGetLanguageCode( p_demux, "menu-language" );
408     bd_set_player_setting_str(p_sys->bluray, BLURAY_PLAYER_SETTING_MENU_LANG,  psz_code);
409
410     /* Get titles and chapters */
411     p_sys->p_meta = bd_get_meta(p_sys->bluray);
412     if (!p_sys->p_meta)
413         msg_Warn(p_demux, "Failed to get meta info.");
414
415     p_sys->b_menu = var_InheritBool(p_demux, "bluray-menu");
416
417     blurayInitTitles(p_demux, disc_info->num_hdmv_titles + disc_info->num_bdj_titles + 1/*Top Menu*/ + 1/*First Play*/);
418
419     /*
420      * Initialize the event queue, so we can receive events in blurayDemux(Menu).
421      */
422     bd_get_event(p_sys->bluray, NULL);
423
424     /* Registering overlay event handler */
425     bd_register_overlay_proc(p_sys->bluray, p_demux, blurayOverlayProc);
426     p_sys->p_input = demux_GetParentInput(p_demux);
427     if (unlikely(!p_sys->p_input)) {
428         msg_Err(p_demux, "Could not get parent input");
429         goto error;
430     }
431
432     if (p_sys->b_menu) {
433
434         /* Register ARGB overlay handler for BD-J */
435         if (disc_info->num_bdj_titles)
436             bd_register_argb_overlay_proc(p_sys->bluray, p_demux, blurayArgbOverlayProc, NULL);
437
438         /* libbluray will start playback from "First-Title" title */
439         if (bd_play(p_sys->bluray) == 0)
440             BLURAY_ERROR(_("Failed to start bluray playback. Please try without menu support."));
441
442     } else {
443         /* set start title number */
444         if (bluraySetTitle(p_demux, p_sys->i_longest_title) != VLC_SUCCESS) {
445             msg_Err(p_demux, "Could not set the title %d", p_sys->i_longest_title);
446             goto error;
447         }
448     }
449
450     vlc_array_init(&p_sys->es);
451     p_sys->p_out = esOutNew(p_demux);
452     if (unlikely(p_sys->p_out == NULL))
453         goto error;
454
455     blurayResetParser(p_demux);
456     if (!p_sys->p_parser) {
457         msg_Err(p_demux, "Failed to create TS demuxer");
458         goto error;
459     }
460
461     p_demux->pf_control = blurayControl;
462     p_demux->pf_demux   = blurayDemux;
463
464     return VLC_SUCCESS;
465
466 error:
467     if (error_msg)
468         dialog_Fatal(p_demux, _("Blu-ray error"), "%s", error_msg);
469     blurayClose(object);
470     return VLC_EGENERIC;
471 #undef BLURAY_ERROR
472 }
473
474
475 /*****************************************************************************
476  * blurayClose: module destroy function
477  *****************************************************************************/
478 static void blurayClose(vlc_object_t *object)
479 {
480     demux_t *p_demux = (demux_t*)object;
481     demux_sys_t *p_sys = p_demux->p_sys;
482
483     setTitleInfo(p_sys, NULL);
484
485     /*
486      * Close libbluray first.
487      * This will close all the overlays before we release p_vout
488      * bd_close(NULL) can crash
489      */
490     assert(p_sys->bluray);
491     bd_close(p_sys->bluray);
492
493     if (p_sys->p_vout != NULL) {
494         var_DelCallback(p_sys->p_vout, "mouse-moved", onMouseEvent, p_demux);
495         var_DelCallback(p_sys->p_vout, "mouse-clicked", onMouseEvent, p_demux);
496         vlc_object_release(p_sys->p_vout);
497     }
498     if (p_sys->p_input != NULL)
499         vlc_object_release(p_sys->p_input);
500     if (p_sys->p_parser)
501         stream_Delete(p_sys->p_parser);
502     if (p_sys->p_out != NULL)
503         es_out_Delete(p_sys->p_out);
504     assert(vlc_array_count(&p_sys->es) == 0);
505     vlc_array_clear(&p_sys->es);
506
507     /* Titles */
508     for (unsigned int i = 0; i < p_sys->i_title; i++)
509         vlc_input_title_Delete(p_sys->pp_title[i]);
510     TAB_CLEAN(p_sys->i_title, p_sys->pp_title);
511
512     vlc_mutex_destroy(&p_sys->pl_info_lock);
513
514     free(p_sys->psz_bd_path);
515     free(p_sys);
516 }
517
518 /*****************************************************************************
519  * Elementary streams handling
520  *****************************************************************************/
521
522 struct es_out_sys_t {
523     demux_t *p_demux;
524 };
525
526 typedef struct  fmt_es_pair {
527     int         i_id;
528     es_out_id_t *p_es;
529 }               fmt_es_pair_t;
530
531 static int  findEsPairIndex(demux_sys_t *p_sys, int i_id)
532 {
533     for (int i = 0; i < vlc_array_count(&p_sys->es); ++i)
534         if (((fmt_es_pair_t*)vlc_array_item_at_index(&p_sys->es, i))->i_id == i_id)
535             return i;
536
537     return -1;
538 }
539
540 static int  findEsPairIndexByEs(demux_sys_t *p_sys, es_out_id_t *p_es)
541 {
542     for (int i = 0; i < vlc_array_count(&p_sys->es); ++i)
543         if (((fmt_es_pair_t*)vlc_array_item_at_index(&p_sys->es, i))->p_es == p_es)
544             return i;
545
546     return -1;
547 }
548
549 static void setStreamLang(es_format_t *p_fmt,
550                           const BLURAY_STREAM_INFO *p_streams, int i_stream_count)
551 {
552     for (int i = 0; i < i_stream_count; i++) {
553         if (p_fmt->i_id == p_streams[i].pid) {
554             free(p_fmt->psz_language);
555             p_fmt->psz_language = strndup((const char *)p_streams[i].lang, 3);
556             return;
557         }
558     }
559 }
560
561 static es_out_id_t *esOutAdd(es_out_t *p_out, const es_format_t *p_fmt)
562 {
563     demux_sys_t *p_sys = p_out->p_sys->p_demux->p_sys;
564     es_format_t fmt;
565
566     es_format_Copy(&fmt, p_fmt);
567
568     vlc_mutex_lock(&p_sys->pl_info_lock);
569
570     switch (fmt.i_cat) {
571     case VIDEO_ES:
572         if (p_sys->i_video_stream != -1 && p_sys->i_video_stream != p_fmt->i_id)
573             fmt.i_priority = ES_PRIORITY_NOT_SELECTABLE;
574         break ;
575     case AUDIO_ES:
576         if (p_sys->i_audio_stream != -1 && p_sys->i_audio_stream != p_fmt->i_id)
577             fmt.i_priority = ES_PRIORITY_NOT_SELECTABLE;
578         if (p_sys->p_clip_info)
579             setStreamLang(&fmt, p_sys->p_clip_info->audio_streams, p_sys->p_clip_info->audio_stream_count);
580         break ;
581     case SPU_ES:
582         if (p_sys->i_spu_stream != -1 && p_sys->i_spu_stream != p_fmt->i_id)
583             fmt.i_priority = ES_PRIORITY_NOT_SELECTABLE;
584         if (p_sys->p_clip_info)
585             setStreamLang(&fmt, p_sys->p_clip_info->pg_streams, p_sys->p_clip_info->pg_stream_count);
586         break ;
587     }
588
589     vlc_mutex_unlock(&p_sys->pl_info_lock);
590
591     es_out_id_t *p_es = es_out_Add(p_out->p_sys->p_demux->out, &fmt);
592     if (p_fmt->i_id >= 0) {
593         /* Ensure we are not overriding anything */
594         int idx = findEsPairIndex(p_sys, p_fmt->i_id);
595         if (idx == -1) {
596             fmt_es_pair_t *p_pair = malloc(sizeof(*p_pair));
597             if (likely(p_pair != NULL)) {
598                 p_pair->i_id = p_fmt->i_id;
599                 p_pair->p_es = p_es;
600                 msg_Info(p_out->p_sys->p_demux, "Adding ES %d", p_fmt->i_id);
601                 vlc_array_append(&p_sys->es, p_pair);
602             }
603         }
604     }
605     es_format_Clean(&fmt);
606     return p_es;
607 }
608
609 static int esOutSend(es_out_t *p_out, es_out_id_t *p_es, block_t *p_block)
610 {
611     return es_out_Send(p_out->p_sys->p_demux->out, p_es, p_block);
612 }
613
614 static void esOutDel(es_out_t *p_out, es_out_id_t *p_es)
615 {
616     int idx = findEsPairIndexByEs(p_out->p_sys->p_demux->p_sys, p_es);
617     if (idx >= 0) {
618         free(vlc_array_item_at_index(&p_out->p_sys->p_demux->p_sys->es, idx));
619         vlc_array_remove(&p_out->p_sys->p_demux->p_sys->es, idx);
620     }
621     es_out_Del(p_out->p_sys->p_demux->out, p_es);
622 }
623
624 static int esOutControl(es_out_t *p_out, int i_query, va_list args)
625 {
626     return es_out_vaControl(p_out->p_sys->p_demux->out, i_query, args);
627 }
628
629 static void esOutDestroy(es_out_t *p_out)
630 {
631     for (int i = 0; i < vlc_array_count(&p_out->p_sys->p_demux->p_sys->es); ++i)
632         free(vlc_array_item_at_index(&p_out->p_sys->p_demux->p_sys->es, i));
633     vlc_array_clear(&p_out->p_sys->p_demux->p_sys->es);
634     free(p_out->p_sys);
635     free(p_out);
636 }
637
638 static es_out_t *esOutNew(demux_t *p_demux)
639 {
640     assert(vlc_array_count(&p_demux->p_sys->es) == 0);
641     es_out_t    *p_out = malloc(sizeof(*p_out));
642     if (unlikely(p_out == NULL))
643         return NULL;
644
645     p_out->pf_add       = esOutAdd;
646     p_out->pf_control   = esOutControl;
647     p_out->pf_del       = esOutDel;
648     p_out->pf_destroy   = esOutDestroy;
649     p_out->pf_send      = esOutSend;
650
651     p_out->p_sys = malloc(sizeof(*p_out->p_sys));
652     if (unlikely(p_out->p_sys == NULL)) {
653         free(p_out);
654         return NULL;
655     }
656     p_out->p_sys->p_demux = p_demux;
657     return p_out;
658 }
659
660 /*****************************************************************************
661  * subpicture_updater_t functions:
662  *****************************************************************************/
663 static int subpictureUpdaterValidate(subpicture_t *p_subpic,
664                                       bool b_fmt_src, const video_format_t *p_fmt_src,
665                                       bool b_fmt_dst, const video_format_t *p_fmt_dst,
666                                       mtime_t i_ts)
667 {
668     VLC_UNUSED(b_fmt_src);
669     VLC_UNUSED(b_fmt_dst);
670     VLC_UNUSED(p_fmt_src);
671     VLC_UNUSED(p_fmt_dst);
672     VLC_UNUSED(i_ts);
673
674     subpicture_updater_sys_t *p_upd_sys = p_subpic->updater.p_sys;
675     bluray_overlay_t         *p_overlay = p_upd_sys->p_overlay;
676
677     vlc_mutex_lock(&p_overlay->lock);
678     int res = p_overlay->status == Outdated;
679     vlc_mutex_unlock(&p_overlay->lock);
680     return res;
681 }
682
683 /* This should probably be moved to subpictures.c afterward */
684 static subpicture_region_t* subpicture_region_Clone(subpicture_region_t *p_region_src)
685 {
686     if (!p_region_src)
687         return NULL;
688     subpicture_region_t *p_region_dst = subpicture_region_New(&p_region_src->fmt);
689     if (unlikely(!p_region_dst))
690         return NULL;
691
692     p_region_dst->i_x      = p_region_src->i_x;
693     p_region_dst->i_y      = p_region_src->i_y;
694     p_region_dst->i_align  = p_region_src->i_align;
695     p_region_dst->i_alpha  = p_region_src->i_alpha;
696
697     p_region_dst->psz_text = p_region_src->psz_text ? strdup(p_region_src->psz_text) : NULL;
698     p_region_dst->psz_html = p_region_src->psz_html ? strdup(p_region_src->psz_html) : NULL;
699     if (p_region_src->p_style != NULL) {
700         p_region_dst->p_style = malloc(sizeof(*p_region_dst->p_style));
701         p_region_dst->p_style = text_style_Copy(p_region_dst->p_style,
702                                                 p_region_src->p_style);
703     }
704
705     //Palette is already copied by subpicture_region_New, we just have to duplicate p_pixels
706     for (int i = 0; i < p_region_src->p_picture->i_planes; i++)
707         memcpy(p_region_dst->p_picture->p[i].p_pixels,
708                p_region_src->p_picture->p[i].p_pixels,
709                p_region_src->p_picture->p[i].i_lines * p_region_src->p_picture->p[i].i_pitch);
710     return p_region_dst;
711 }
712
713 static void subpictureUpdaterUpdate(subpicture_t *p_subpic,
714                                     const video_format_t *p_fmt_src,
715                                     const video_format_t *p_fmt_dst,
716                                     mtime_t i_ts)
717 {
718     VLC_UNUSED(p_fmt_src);
719     VLC_UNUSED(p_fmt_dst);
720     VLC_UNUSED(i_ts);
721     subpicture_updater_sys_t *p_upd_sys = p_subpic->updater.p_sys;
722     bluray_overlay_t         *p_overlay = p_upd_sys->p_overlay;
723
724     /*
725      * When this function is called, all p_subpic regions are gone.
726      * We need to duplicate our regions (stored internaly) to this subpic.
727      */
728     vlc_mutex_lock(&p_overlay->lock);
729
730     subpicture_region_t *p_src = p_overlay->p_regions;
731     if (!p_src) {
732         vlc_mutex_unlock(&p_overlay->lock);
733         return;
734     }
735
736     subpicture_region_t **p_dst = &p_subpic->p_region;
737     while (p_src != NULL) {
738         *p_dst = subpicture_region_Clone(p_src);
739         if (*p_dst == NULL)
740             break;
741         p_dst = &(*p_dst)->p_next;
742         p_src = p_src->p_next;
743     }
744     if (*p_dst != NULL)
745         (*p_dst)->p_next = NULL;
746     p_overlay->status = Displayed;
747     vlc_mutex_unlock(&p_overlay->lock);
748 }
749
750 static void blurayCleanOverlayStruct(bluray_overlay_t *);
751
752 static void subpictureUpdaterDestroy(subpicture_t *p_subpic)
753 {
754     blurayCleanOverlayStruct(p_subpic->updater.p_sys->p_overlay);
755     free(p_subpic->updater.p_sys);
756 }
757
758 /*****************************************************************************
759  * User input events:
760  *****************************************************************************/
761 static int onMouseEvent(vlc_object_t *p_vout, const char *psz_var, vlc_value_t old,
762                         vlc_value_t val, void *p_data)
763 {
764     demux_t     *p_demux = (demux_t*)p_data;
765     demux_sys_t *p_sys   = p_demux->p_sys;
766     mtime_t     now      = mdate();
767     VLC_UNUSED(old);
768     VLC_UNUSED(p_vout);
769
770     if (psz_var[6] == 'm')   //Mouse moved
771         bd_mouse_select(p_sys->bluray, now, val.coords.x, val.coords.y);
772     else if (psz_var[6] == 'c') {
773         bd_mouse_select(p_sys->bluray, now, val.coords.x, val.coords.y);
774         bd_user_input(p_sys->bluray, now, BD_VK_MOUSE_ACTIVATE);
775     } else {
776         assert(0);
777     }
778     return VLC_SUCCESS;
779 }
780
781 static int sendKeyEvent(demux_sys_t *p_sys, unsigned int key)
782 {
783     mtime_t now = mdate();
784     if (bd_user_input(p_sys->bluray, now, key) < 0)
785         return VLC_EGENERIC;
786
787     return VLC_SUCCESS;
788 }
789
790 /*****************************************************************************
791  * libbluray overlay handling:
792  *****************************************************************************/
793 static void blurayCleanOverlayStruct(bluray_overlay_t *p_overlay)
794 {
795     if (!atomic_flag_test_and_set(&p_overlay->released_once))
796         return;
797     /*
798      * This will be called when destroying the picture.
799      * Don't delete it again from here!
800      */
801     vlc_mutex_destroy(&p_overlay->lock);
802     subpicture_region_ChainDelete(p_overlay->p_regions);
803     free(p_overlay);
804 }
805
806 static void blurayCloseOverlay(demux_t *p_demux, int plane)
807 {
808     demux_sys_t *p_sys = p_demux->p_sys;
809     bluray_overlay_t *ov = p_sys->p_overlays[plane];
810
811     if (ov != NULL) {
812         if (p_sys->p_vout)
813             vout_FlushSubpictureChannel(p_sys->p_vout, ov->p_pic->i_channel);
814         blurayCleanOverlayStruct(ov);
815         if (p_sys->current_overlay == plane)
816             p_sys->current_overlay = -1;
817
818         p_sys->p_overlays[plane] = NULL;
819     }
820
821     for (int i = 0; i < MAX_OVERLAY; i++)
822         if (p_sys->p_overlays[i])
823             return;
824
825     /* All overlays have been closed */
826     if (p_sys->p_vout != NULL) {
827         var_DelCallback(p_sys->p_vout, "mouse-moved", onMouseEvent, p_demux);
828         var_DelCallback(p_sys->p_vout, "mouse-clicked", onMouseEvent, p_demux);
829         vlc_object_release(p_sys->p_vout);
830         p_sys->p_vout = NULL;
831     }
832 }
833
834 /*
835  * Mark the overlay as "ToDisplay" status.
836  * This will not send the overlay to the vout instantly, as the vout
837  * may not be acquired (not acquirable) yet.
838  * If is has already been acquired, the overlay has already been sent to it,
839  * therefore, we only flag the overlay as "Outdated"
840  */
841 static void blurayActivateOverlay(demux_t *p_demux, int plane)
842 {
843     demux_sys_t *p_sys = p_demux->p_sys;
844     bluray_overlay_t *ov = p_sys->p_overlays[plane];
845
846     /*
847      * If the overlay is already displayed, mark the picture as outdated.
848      * We must NOT use vout_PutSubpicture if a picture is already displayed.
849      */
850     vlc_mutex_lock(&ov->lock);
851     if (ov->status >= Displayed && p_sys->p_vout) {
852         ov->status = Outdated;
853         vlc_mutex_unlock(&ov->lock);
854         return;
855     }
856
857     /*
858      * Mark the overlay as available, but don't display it right now.
859      * the blurayDemuxMenu will send it to vout, as it may be unavailable when
860      * the overlay is computed
861      */
862     p_sys->current_overlay = plane;
863     ov->status = ToDisplay;
864     vlc_mutex_unlock(&ov->lock);
865 }
866
867 static void blurayInitOverlay(demux_t *p_demux, int plane, int width, int height)
868 {
869     demux_sys_t *p_sys = p_demux->p_sys;
870
871     assert(p_sys->p_overlays[plane] == NULL);
872
873     bluray_overlay_t *ov = calloc(1, sizeof(*ov));
874     if (unlikely(ov == NULL))
875         return;
876
877     subpicture_updater_sys_t *p_upd_sys = malloc(sizeof(*p_upd_sys));
878     if (unlikely(p_upd_sys == NULL)) {
879         free(ov);
880         return;
881     }
882     /* two references: vout + demux */
883     atomic_flag_clear(&ov->released_once);
884
885     p_upd_sys->p_overlay = ov;
886     subpicture_updater_t updater = {
887         .pf_validate = subpictureUpdaterValidate,
888         .pf_update   = subpictureUpdaterUpdate,
889         .pf_destroy  = subpictureUpdaterDestroy,
890         .p_sys       = p_upd_sys,
891     };
892
893     ov->p_pic = subpicture_New(&updater);
894     if (ov->p_pic == NULL) {
895         free(p_upd_sys);
896         free(ov);
897         return;
898     }
899
900     ov->p_pic->i_original_picture_width = width;
901     ov->p_pic->i_original_picture_height = height;
902     ov->p_pic->b_ephemer = true;
903     ov->p_pic->b_absolute = true;
904
905     vlc_mutex_init(&ov->lock);
906
907     p_sys->p_overlays[plane] = ov;
908 }
909
910 /**
911  * Destroy every regions in the subpicture.
912  * This is done in two steps:
913  * - Wiping our private regions list
914  * - Flagging the overlay as outdated, so the changes are replicated from
915  *   the subpicture_updater_t::pf_update
916  * This doesn't destroy the subpicture, as the overlay may be used again by libbluray.
917  */
918 static void blurayClearOverlay(demux_t *p_demux, int plane)
919 {
920     demux_sys_t *p_sys = p_demux->p_sys;
921     bluray_overlay_t *ov = p_sys->p_overlays[plane];
922
923     vlc_mutex_lock(&ov->lock);
924
925     subpicture_region_ChainDelete(ov->p_regions);
926     ov->p_regions = NULL;
927     ov->status = Outdated;
928
929     vlc_mutex_unlock(&ov->lock);
930 }
931
932 /*
933  * This will draw to the overlay by adding a region to our region list
934  * This will have to be copied to the subpicture used to render the overlay.
935  */
936 static void blurayDrawOverlay(demux_t *p_demux, const BD_OVERLAY* const ov)
937 {
938     demux_sys_t *p_sys = p_demux->p_sys;
939
940     /*
941      * Compute a subpicture_region_t.
942      * It will be copied and sent to the vout later.
943      */
944     if (!ov->img)
945         return;
946
947     vlc_mutex_lock(&p_sys->p_overlays[ov->plane]->lock);
948
949     /* Find a region to update */
950     subpicture_region_t *p_reg = p_sys->p_overlays[ov->plane]->p_regions;
951     subpicture_region_t *p_last = NULL;
952     while (p_reg != NULL) {
953         p_last = p_reg;
954         if (p_reg->i_x == ov->x && p_reg->i_y == ov->y &&
955                 p_reg->fmt.i_width == ov->w && p_reg->fmt.i_height == ov->h)
956             break;
957         p_reg = p_reg->p_next;
958     }
959
960     /* If there is no region to update, create a new one. */
961     if (!p_reg) {
962         video_format_t fmt;
963         video_format_Init(&fmt, 0);
964         video_format_Setup(&fmt, VLC_CODEC_YUVP, ov->w, ov->h, ov->w, ov->h, 1, 1);
965
966         p_reg = subpicture_region_New(&fmt);
967         p_reg->i_x = ov->x;
968         p_reg->i_y = ov->y;
969         /* Append it to our list. */
970         if (p_last != NULL)
971             p_last->p_next = p_reg;
972         else /* If we don't have a last region, then our list empty */
973             p_sys->p_overlays[ov->plane]->p_regions = p_reg;
974     }
975
976     /* Now we can update the region, regardless it's an update or an insert */
977     const BD_PG_RLE_ELEM *img = ov->img;
978     for (int y = 0; y < ov->h; y++)
979         for (int x = 0; x < ov->w;) {
980             plane_t *p = &p_reg->p_picture->p[0];
981             memset(&p->p_pixels[y * p->i_pitch + x], img->color, img->len);
982             x += img->len;
983             img++;
984         }
985
986     if (ov->palette) {
987         p_reg->fmt.p_palette->i_entries = 256;
988         for (int i = 0; i < 256; ++i) {
989             p_reg->fmt.p_palette->palette[i][0] = ov->palette[i].Y;
990             p_reg->fmt.p_palette->palette[i][1] = ov->palette[i].Cb;
991             p_reg->fmt.p_palette->palette[i][2] = ov->palette[i].Cr;
992             p_reg->fmt.p_palette->palette[i][3] = ov->palette[i].T;
993         }
994     }
995
996     vlc_mutex_unlock(&p_sys->p_overlays[ov->plane]->lock);
997     /*
998      * /!\ The region is now stored in our internal list, but not in the subpicture /!\
999      */
1000 }
1001
1002 static void blurayOverlayProc(void *ptr, const BD_OVERLAY *const overlay)
1003 {
1004     demux_t *p_demux = (demux_t*)ptr;
1005     demux_sys_t *p_sys = p_demux->p_sys;
1006
1007     if (!overlay) {
1008         msg_Info(p_demux, "Closing overlays.");
1009         p_sys->current_overlay = -1;
1010         if (p_sys->p_vout)
1011             for (int i = 0; i < MAX_OVERLAY; i++)
1012                 blurayCloseOverlay(p_demux, i);
1013         return;
1014     }
1015
1016     switch (overlay->cmd) {
1017     case BD_OVERLAY_INIT:
1018         msg_Info(p_demux, "Initializing overlay");
1019         blurayInitOverlay(p_demux, overlay->plane, overlay->w, overlay->h);
1020         break;
1021     case BD_OVERLAY_CLOSE:
1022         blurayClearOverlay(p_demux, overlay->plane);
1023         blurayCloseOverlay(p_demux, overlay->plane);
1024         break;
1025     case BD_OVERLAY_CLEAR:
1026         blurayClearOverlay(p_demux, overlay->plane);
1027         break;
1028     case BD_OVERLAY_FLUSH:
1029         blurayActivateOverlay(p_demux, overlay->plane);
1030         break;
1031     case BD_OVERLAY_DRAW:
1032         blurayDrawOverlay(p_demux, overlay);
1033         break;
1034     default:
1035         msg_Warn(p_demux, "Unknown BD overlay command: %u", overlay->cmd);
1036         break;
1037     }
1038 }
1039
1040 /*
1041  * ARGB overlay (BD-J)
1042  */
1043 static void blurayInitArgbOverlay(demux_t *p_demux, int plane, int width, int height)
1044 {
1045     demux_sys_t *p_sys = p_demux->p_sys;
1046
1047     blurayInitOverlay(p_demux, plane, width, height);
1048
1049     if (!p_sys->p_overlays[plane]->p_regions) {
1050         video_format_t fmt;
1051         video_format_Init(&fmt, 0);
1052         video_format_Setup(&fmt, VLC_CODEC_RGBA, width, height, width, height, 1, 1);
1053
1054         p_sys->p_overlays[plane]->p_regions = subpicture_region_New(&fmt);
1055     }
1056 }
1057
1058 static void blurayDrawArgbOverlay(demux_t *p_demux, const BD_ARGB_OVERLAY* const ov)
1059 {
1060     demux_sys_t *p_sys = p_demux->p_sys;
1061
1062     vlc_mutex_lock(&p_sys->p_overlays[ov->plane]->lock);
1063
1064     /* Find a region to update */
1065     subpicture_region_t *p_reg = p_sys->p_overlays[ov->plane]->p_regions;
1066     if (!p_reg) {
1067         vlc_mutex_unlock(&p_sys->p_overlays[ov->plane]->lock);
1068         return;
1069     }
1070
1071     /* Now we can update the region */
1072     const uint32_t *src0 = ov->argb;
1073     uint8_t        *dst0 = p_reg->p_picture->p[0].p_pixels +
1074                            p_reg->p_picture->p[0].i_pitch * ov->y +
1075                            ov->x * 4;
1076
1077     for (int y = 0; y < ov->h; y++) {
1078         // XXX: add support for this format ? Should be possible with OPENGL/VDPAU/...
1079         // - or add libbluray option to select the format ?
1080         for (int x = 0; x < ov->w; x++) {
1081             dst0[x*4  ] = src0[x]>>16; /* R */
1082             dst0[x*4+1] = src0[x]>>8;  /* G */
1083             dst0[x*4+2] = src0[x];     /* B */
1084             dst0[x*4+3] = src0[x]>>24; /* A */
1085         }
1086
1087         src0 += ov->stride;
1088         dst0 += p_reg->p_picture->p[0].i_pitch;
1089     }
1090
1091     vlc_mutex_unlock(&p_sys->p_overlays[ov->plane]->lock);
1092     /*
1093      * /!\ The region is now stored in our internal list, but not in the subpicture /!\
1094      */
1095 }
1096
1097 static void blurayArgbOverlayProc(void *ptr, const BD_ARGB_OVERLAY *const overlay)
1098 {
1099     demux_t *p_demux = (demux_t*)ptr;
1100
1101     switch (overlay->cmd) {
1102     case BD_ARGB_OVERLAY_INIT:
1103         blurayInitArgbOverlay(p_demux, overlay->plane, overlay->w, overlay->h);
1104         break;
1105     case BD_ARGB_OVERLAY_CLOSE:
1106         blurayClearOverlay(p_demux, overlay->plane);
1107         blurayCloseOverlay(p_demux, overlay->plane);
1108         break;
1109     case BD_ARGB_OVERLAY_FLUSH:
1110         blurayActivateOverlay(p_demux, overlay->plane);
1111         break;
1112     case BD_ARGB_OVERLAY_DRAW:
1113         blurayDrawArgbOverlay(p_demux, overlay);
1114         break;
1115     default:
1116         msg_Warn(p_demux, "Unknown BD ARGB overlay command: %u", overlay->cmd);
1117         break;
1118     }
1119 }
1120
1121 static void bluraySendOverlayToVout(demux_t *p_demux)
1122 {
1123     demux_sys_t *p_sys = p_demux->p_sys;
1124
1125     assert(p_sys->current_overlay >= 0 &&
1126            p_sys->p_overlays[p_sys->current_overlay] != NULL &&
1127            p_sys->p_overlays[p_sys->current_overlay]->p_pic != NULL);
1128
1129     p_sys->p_overlays[p_sys->current_overlay]->p_pic->i_start =
1130         p_sys->p_overlays[p_sys->current_overlay]->p_pic->i_stop = mdate();
1131     p_sys->p_overlays[p_sys->current_overlay]->p_pic->i_channel =
1132         vout_RegisterSubpictureChannel(p_sys->p_vout);
1133     /*
1134      * After this point, the picture should not be accessed from the demux thread,
1135      * as it is held by the vout thread.
1136      * This must be done only once per subpicture, ie. only once between each
1137      * blurayInitOverlay & blurayCloseOverlay call.
1138      */
1139     vout_PutSubpicture(p_sys->p_vout, p_sys->p_overlays[p_sys->current_overlay]->p_pic);
1140     /*
1141      * Mark the picture as Outdated, as it contains no region for now.
1142      * This will make the subpicture_updater_t call pf_update
1143      */
1144     p_sys->p_overlays[p_sys->current_overlay]->status = Outdated;
1145 }
1146
1147 static void blurayUpdateTitleInfo(input_title_t *t, BLURAY_TITLE_INFO *title_info)
1148 {
1149     t->i_length = FROM_TICKS(title_info->duration);
1150
1151     if (!t->i_seekpoint) {
1152         for (unsigned int j = 0; j < title_info->chapter_count; j++) {
1153             seekpoint_t *s = vlc_seekpoint_New();
1154             if (!s) {
1155                 break;
1156             }
1157             s->i_time_offset = title_info->chapters[j].offset;
1158
1159             TAB_APPEND(t->i_seekpoint, t->seekpoint, s);
1160         }
1161     }
1162 }
1163
1164 static void blurayInitTitles(demux_t *p_demux, int menu_titles)
1165 {
1166     demux_sys_t *p_sys = p_demux->p_sys;
1167
1168     /* get and set the titles */
1169     unsigned i_title = menu_titles;
1170
1171     if (!p_sys->b_menu) {
1172         i_title = bd_get_titles(p_sys->bluray, TITLES_RELEVANT, 60);
1173         p_sys->i_longest_title = bd_get_main_title(p_sys->bluray);
1174     }
1175
1176     for (unsigned int i = 0; i < i_title; i++) {
1177         input_title_t *t = vlc_input_title_New();
1178         if (!t)
1179             break;
1180
1181         if (!p_sys->b_menu) {
1182             BLURAY_TITLE_INFO *title_info = bd_get_title_info(p_sys->bluray, i, 0);
1183             blurayUpdateTitleInfo(t, title_info);
1184             bd_free_title_info(title_info);
1185
1186         } else if (i == 0) {
1187             t->psz_name = strdup(_("Top Menu"));
1188         } else if (i == i_title - 1) {
1189             t->psz_name = strdup(_("First Play"));
1190         }
1191
1192         TAB_APPEND(p_sys->i_title, p_sys->pp_title, t);
1193     }
1194 }
1195
1196 static void blurayResetParser(demux_t *p_demux)
1197 {
1198     /*
1199      * This is a hack and will have to be removed.
1200      * The parser should be flushed, and not destroy/created each time
1201      * we are changing title.
1202      */
1203     demux_sys_t *p_sys = p_demux->p_sys;
1204     if (p_sys->p_parser)
1205         stream_Delete(p_sys->p_parser);
1206
1207     p_sys->p_parser = stream_DemuxNew(p_demux, "ts", p_sys->p_out);
1208
1209     if (!p_sys->p_parser)
1210         msg_Err(p_demux, "Failed to create TS demuxer");
1211 }
1212
1213 /*****************************************************************************
1214  * bluraySetTitle: select new BD title
1215  *****************************************************************************/
1216 static int bluraySetTitle(demux_t *p_demux, int i_title)
1217 {
1218     demux_sys_t *p_sys = p_demux->p_sys;
1219
1220     if (p_sys->b_menu) {
1221         if (i_title <= 0) {
1222             msg_Dbg(p_demux, "Playing TopMenu Title");
1223         } else if (i_title >= (int)p_sys->i_title - 1) {
1224             msg_Dbg(p_demux, "Playing FirstPlay Title");
1225             i_title = BLURAY_TITLE_FIRST_PLAY;
1226         } else {
1227             msg_Dbg(p_demux, "Playing Title %i", i_title);
1228         }
1229
1230         if (bd_play_title(p_sys->bluray, i_title) == 0) {
1231             msg_Err(p_demux, "cannot play bd title '%d'", i_title);
1232             return VLC_EGENERIC;
1233         }
1234
1235         return VLC_SUCCESS;
1236     }
1237
1238     /* Looking for the main title, ie the longest duration */
1239     if (i_title < 0)
1240         i_title = p_sys->i_longest_title;
1241     else if ((unsigned)i_title > p_sys->i_title)
1242         return VLC_EGENERIC;
1243
1244     msg_Dbg(p_demux, "Selecting Title %i", i_title);
1245
1246     if (bd_select_title(p_sys->bluray, i_title) == 0) {
1247         msg_Err(p_demux, "cannot select bd title '%d'", i_title);
1248         return VLC_EGENERIC;
1249     }
1250
1251     blurayResetParser(p_demux);
1252
1253     return VLC_SUCCESS;
1254 }
1255
1256 /*****************************************************************************
1257  * blurayControl: handle the controls
1258  *****************************************************************************/
1259 static int blurayControl(demux_t *p_demux, int query, va_list args)
1260 {
1261     demux_sys_t *p_sys = p_demux->p_sys;
1262     bool     *pb_bool;
1263     int64_t  *pi_64;
1264
1265     switch (query) {
1266     case DEMUX_CAN_SEEK:
1267     case DEMUX_CAN_PAUSE:
1268     case DEMUX_CAN_CONTROL_PACE:
1269          pb_bool = (bool*)va_arg(args, bool *);
1270          *pb_bool = true;
1271          break;
1272
1273     case DEMUX_GET_PTS_DELAY:
1274         pi_64 = (int64_t*)va_arg(args, int64_t *);
1275         *pi_64 = INT64_C(1000) * var_InheritInteger(p_demux, "disc-caching");
1276         break;
1277
1278     case DEMUX_SET_PAUSE_STATE:
1279         /* Nothing to do */
1280         break;
1281
1282     case DEMUX_SET_TITLE:
1283     {
1284         int i_title = (int)va_arg(args, int);
1285         if (bluraySetTitle(p_demux, i_title) != VLC_SUCCESS)
1286             return VLC_EGENERIC;
1287         break;
1288     }
1289     case DEMUX_SET_SEEKPOINT:
1290     {
1291         int i_chapter = (int)va_arg(args, int);
1292         bd_seek_chapter(p_sys->bluray, i_chapter);
1293         p_demux->info.i_update = INPUT_UPDATE_SEEKPOINT;
1294         break;
1295     }
1296
1297     case DEMUX_GET_TITLE_INFO:
1298     {
1299         input_title_t ***ppp_title = (input_title_t***)va_arg(args, input_title_t***);
1300         int *pi_int             = (int*)va_arg(args, int*);
1301         int *pi_title_offset    = (int*)va_arg(args, int*);
1302         int *pi_chapter_offset  = (int*)va_arg(args, int*);
1303
1304         /* */
1305         *pi_title_offset   = 0;
1306         *pi_chapter_offset = 0;
1307
1308         /* Duplicate local title infos */
1309         *pi_int = p_sys->i_title;
1310         *ppp_title = malloc(p_sys->i_title * sizeof(input_title_t *));
1311         for (unsigned int i = 0; i < p_sys->i_title; i++)
1312             (*ppp_title)[i] = vlc_input_title_Duplicate(p_sys->pp_title[i]);
1313
1314         return VLC_SUCCESS;
1315     }
1316
1317     case DEMUX_GET_LENGTH:
1318     {
1319         int64_t *pi_length = (int64_t*)va_arg(args, int64_t *);
1320         *pi_length = p_demux->info.i_title < (int)p_sys->i_title ? CUR_LENGTH : 0;
1321         return VLC_SUCCESS;
1322     }
1323     case DEMUX_SET_TIME:
1324     {
1325         int64_t i_time = (int64_t)va_arg(args, int64_t);
1326         bd_seek_time(p_sys->bluray, TO_TICKS(i_time));
1327         return VLC_SUCCESS;
1328     }
1329     case DEMUX_GET_TIME:
1330     {
1331         int64_t *pi_time = (int64_t*)va_arg(args, int64_t *);
1332         *pi_time = (int64_t)FROM_TICKS(bd_tell_time(p_sys->bluray));
1333         return VLC_SUCCESS;
1334     }
1335
1336     case DEMUX_GET_POSITION:
1337     {
1338         double *pf_position = (double*)va_arg(args, double *);
1339         *pf_position = p_demux->info.i_title < (int)p_sys->i_title && CUR_LENGTH > 0 ?
1340                       (double)FROM_TICKS(bd_tell_time(p_sys->bluray))/CUR_LENGTH : 0.0;
1341         return VLC_SUCCESS;
1342     }
1343     case DEMUX_SET_POSITION:
1344     {
1345         double f_position = (double)va_arg(args, double);
1346         bd_seek_time(p_sys->bluray, TO_TICKS(f_position*CUR_LENGTH));
1347         return VLC_SUCCESS;
1348     }
1349
1350     case DEMUX_GET_META:
1351     {
1352         vlc_meta_t *p_meta = (vlc_meta_t *) va_arg (args, vlc_meta_t*);
1353         const META_DL *meta = p_sys->p_meta;
1354         if (meta == NULL)
1355             return VLC_EGENERIC;
1356
1357         if (!EMPTY_STR(meta->di_name)) vlc_meta_SetTitle(p_meta, meta->di_name);
1358
1359         if (!EMPTY_STR(meta->language_code)) vlc_meta_AddExtra(p_meta, "Language", meta->language_code);
1360         if (!EMPTY_STR(meta->filename)) vlc_meta_AddExtra(p_meta, "Filename", meta->filename);
1361         if (!EMPTY_STR(meta->di_alternative)) vlc_meta_AddExtra(p_meta, "Alternative", meta->di_alternative);
1362
1363         // if (meta->di_set_number > 0) vlc_meta_SetTrackNum(p_meta, meta->di_set_number);
1364         // if (meta->di_num_sets > 0) vlc_meta_AddExtra(p_meta, "Discs numbers in Set", meta->di_num_sets);
1365
1366         if (meta->thumb_count > 0 && meta->thumbnails) {
1367             char *psz_thumbpath;
1368             if (asprintf(&psz_thumbpath, "%s" DIR_SEP "BDMV" DIR_SEP "META" DIR_SEP "DL" DIR_SEP "%s",
1369                           p_sys->psz_bd_path, meta->thumbnails[0].path) > 0) {
1370                 char *psz_thumburl = vlc_path2uri(psz_thumbpath, "file");
1371                 if (unlikely(psz_thumburl == NULL)) {
1372                     free(psz_thumbpath);
1373                     return VLC_ENOMEM;
1374                 }
1375
1376                 vlc_meta_SetArtURL(p_meta, psz_thumburl);
1377                 free(psz_thumburl);
1378             }
1379             free(psz_thumbpath);
1380         }
1381
1382         return VLC_SUCCESS;
1383     }
1384
1385     case DEMUX_NAV_ACTIVATE:
1386         if (p_sys->b_popup_available && !p_sys->b_menu_open) {
1387             return sendKeyEvent(p_sys, BD_VK_POPUP);
1388         }
1389         return sendKeyEvent(p_sys, BD_VK_ENTER);
1390     case DEMUX_NAV_UP:
1391         return sendKeyEvent(p_sys, BD_VK_UP);
1392     case DEMUX_NAV_DOWN:
1393         return sendKeyEvent(p_sys, BD_VK_DOWN);
1394     case DEMUX_NAV_LEFT:
1395         return sendKeyEvent(p_sys, BD_VK_LEFT);
1396     case DEMUX_NAV_RIGHT:
1397         return sendKeyEvent(p_sys, BD_VK_RIGHT);
1398
1399     case DEMUX_CAN_RECORD:
1400     case DEMUX_GET_FPS:
1401     case DEMUX_SET_GROUP:
1402     case DEMUX_HAS_UNSUPPORTED_META:
1403     case DEMUX_GET_ATTACHMENTS:
1404         return VLC_EGENERIC;
1405     default:
1406         msg_Warn(p_demux, "unimplemented query (%d) in control", query);
1407         return VLC_EGENERIC;
1408     }
1409     return VLC_SUCCESS;
1410 }
1411
1412 /*****************************************************************************
1413  * libbluray event handling
1414  *****************************************************************************/
1415
1416 static void streamFlush( demux_sys_t *p_sys )
1417 {
1418     /*
1419      * MPEG-TS demuxer does not flush last video frame if size of PES packet is unknown.
1420      * Packet is flushed only when TS packet with PUSI flag set is received.
1421      *
1422      * Fix this by emitting (video) ts packet with PUSI flag set.
1423      * Add video sequence end code to payload so that also video decoder is flushed.
1424      * Set PES packet size in the payload so that it will be sent to decoder immediately.
1425      */
1426
1427     if (p_sys->b_flushed)
1428         return;
1429
1430     block_t *p_block = block_Alloc(192);
1431     if (!p_block)
1432         return;
1433
1434     static const uint8_t seq_end_pes[] = {
1435         0x00, 0x00, 0x01, 0xe0, 0x00, 0x07, 0x80, 0x00, 0x00,  /* PES header */
1436         0x00, 0x00, 0x01, 0xb7,                                /* PES payload: sequence end */
1437     };
1438     static const uint8_t vid_pusi_ts[] = {
1439         0x00, 0x00, 0x00, 0x00,                /* TP extra header (ATC) */
1440         0x47, 0x50, 0x11, 0x30,                /* TP header */
1441         (192 - (4 + 5) - sizeof(seq_end_pes)), /* adaptation field length */
1442         0x80,                                  /* adaptation field: discontinuity indicator */
1443     };
1444
1445     memset(p_block->p_buffer, 0, 192);
1446     memcpy(p_block->p_buffer, vid_pusi_ts, sizeof(vid_pusi_ts));
1447     memcpy(p_block->p_buffer + 192 - sizeof(seq_end_pes), seq_end_pes, sizeof(seq_end_pes));
1448     p_block->i_buffer = 192;
1449
1450     /* set correct sequence end code */
1451     vlc_mutex_lock(&p_sys->pl_info_lock);
1452     if (p_sys->p_clip_info != NULL) {
1453         if (p_sys->p_clip_info->video_streams[0].coding_type > 2) {
1454             /* VC1 / H.264 sequence end */
1455             p_block->p_buffer[191] = 0x0a;
1456         }
1457     }
1458     vlc_mutex_unlock(&p_sys->pl_info_lock);
1459
1460     stream_DemuxSend(p_sys->p_parser, p_block);
1461     p_sys->b_flushed = true;
1462 }
1463
1464 static void blurayResetStillImage( demux_t *p_demux )
1465 {
1466     demux_sys_t *p_sys = p_demux->p_sys;
1467
1468     if (p_sys->i_still_end_time) {
1469         p_sys->i_still_end_time = 0;
1470
1471         blurayResetParser(p_demux);
1472         es_out_Control( p_demux->out, ES_OUT_RESET_PCR );
1473     }
1474 }
1475
1476 static void blurayStillImage( demux_t *p_demux, unsigned i_timeout )
1477 {
1478     demux_sys_t *p_sys = p_demux->p_sys;
1479
1480     /* time period elapsed ? */
1481     if (p_sys->i_still_end_time > 0 && p_sys->i_still_end_time <= mdate()) {
1482         msg_Dbg(p_demux, "Still image end");
1483         bd_read_skip_still(p_sys->bluray);
1484
1485         blurayResetStillImage(p_demux);
1486         return;
1487     }
1488
1489     /* show last frame as still image */
1490     if (!p_sys->i_still_end_time) {
1491         if (i_timeout) {
1492             msg_Dbg(p_demux, "Still image (%d seconds)", i_timeout);
1493             p_sys->i_still_end_time = mdate() + i_timeout * CLOCK_FREQ;
1494         } else {
1495             msg_Dbg(p_demux, "Still image (infinite)");
1496             p_sys->i_still_end_time = -1;
1497         }
1498
1499         /* flush demuxer and decoder (there won't be next video packet starting with ts PUSI) */
1500         streamFlush(p_sys);
1501
1502         /* stop buffering */
1503         bool b_empty;
1504         es_out_Control( p_demux->out, ES_OUT_GET_EMPTY, &b_empty );
1505     }
1506
1507     /* avoid busy loops (read returns no data) */
1508     msleep( 40000 );
1509 }
1510
1511 static void blurayStreamSelect(demux_t *p_demux, uint32_t i_type, uint32_t i_id)
1512 {
1513     demux_sys_t *p_sys = p_demux->p_sys;
1514     int i_pid = -1;
1515
1516     vlc_mutex_lock(&p_sys->pl_info_lock);
1517
1518     if (p_sys->p_clip_info) {
1519
1520         /* The param we get is the real stream id, not an index, ie. it starts from 1 */
1521         i_id--;
1522         if (i_type == BD_EVENT_AUDIO_STREAM) {
1523             if (i_id < p_sys->p_clip_info->audio_stream_count) {
1524                 i_pid = p_sys->p_clip_info->audio_streams[i_id].pid;
1525                 p_sys->i_audio_stream = i_pid;
1526             }
1527         } else if (i_type == BD_EVENT_PG_TEXTST_STREAM) {
1528             if (i_id < p_sys->p_clip_info->pg_stream_count) {
1529                 i_pid = p_sys->p_clip_info->pg_streams[i_id].pid;
1530                 p_sys->i_spu_stream = i_pid;
1531             }
1532         }
1533     }
1534
1535     vlc_mutex_unlock(&p_sys->pl_info_lock);
1536
1537     if (i_pid > 0) {
1538         int i_idx = findEsPairIndex(p_sys, i_pid);
1539         if (i_idx >= 0) {
1540             es_out_id_t *p_es = vlc_array_item_at_index(&p_sys->es, i_idx);
1541             es_out_Control(p_demux->out, ES_OUT_SET_ES, p_es);
1542         }
1543     }
1544 }
1545
1546 static void blurayUpdatePlaylist(demux_t *p_demux, unsigned i_playlist)
1547 {
1548     demux_sys_t *p_sys = p_demux->p_sys;
1549
1550     blurayResetParser(p_demux);
1551
1552     /* read title info and init some values */
1553     if (!p_sys->b_menu)
1554         p_demux->info.i_title = bd_get_current_title(p_sys->bluray);
1555     p_demux->info.i_seekpoint = 0;
1556     p_demux->info.i_update |= INPUT_UPDATE_TITLE | INPUT_UPDATE_SEEKPOINT;
1557
1558     BLURAY_TITLE_INFO *p_title_info = bd_get_playlist_info(p_sys->bluray, i_playlist, 0);
1559     if (p_title_info) {
1560         blurayUpdateTitleInfo(p_sys->pp_title[p_demux->info.i_title], p_title_info);
1561     }
1562     setTitleInfo(p_sys, p_title_info);
1563
1564     blurayResetStillImage(p_demux);
1565 }
1566
1567 static void blurayUpdateCurrentClip(demux_t *p_demux, uint32_t clip)
1568 {
1569     demux_sys_t *p_sys = p_demux->p_sys;
1570
1571     vlc_mutex_lock(&p_sys->pl_info_lock);
1572
1573     p_sys->p_clip_info = NULL;
1574     p_sys->i_video_stream = -1;
1575
1576     if (p_sys->p_pl_info && clip < p_sys->p_pl_info->clip_count) {
1577
1578         p_sys->p_clip_info = &p_sys->p_pl_info->clips[clip];
1579
1580     /* Let's assume a single video track for now.
1581      * This may brake later, but it's enough for now.
1582      */
1583         assert(p_sys->p_clip_info->video_stream_count >= 1);
1584         p_sys->i_video_stream = p_sys->p_clip_info->video_streams[0].pid;
1585     }
1586
1587     vlc_mutex_unlock(&p_sys->pl_info_lock);
1588
1589     blurayResetStillImage(p_demux);
1590 }
1591
1592 static void blurayHandleEvent(demux_t *p_demux, const BD_EVENT *e)
1593 {
1594     demux_sys_t *p_sys = p_demux->p_sys;
1595
1596     switch (e->event) {
1597     case BD_EVENT_TITLE:
1598         if (e->param == BLURAY_TITLE_FIRST_PLAY)
1599             p_demux->info.i_title = p_sys->i_title - 1;
1600         else
1601             p_demux->info.i_title = e->param;
1602         /* this is feature title, we don't know yet which playlist it will play (if any) */
1603         setTitleInfo(p_sys, NULL);
1604         /* reset title infos here ? */
1605         p_demux->info.i_update |= INPUT_UPDATE_TITLE | INPUT_UPDATE_SEEKPOINT; /* might be BD-J title with no video */
1606         break;
1607     case BD_EVENT_PLAYLIST:
1608         /* Start of playlist playback (?????.mpls) */
1609         blurayUpdatePlaylist(p_demux, e->param);
1610         break;
1611     case BD_EVENT_PLAYITEM:
1612         blurayUpdateCurrentClip(p_demux, e->param);
1613         break;
1614     case BD_EVENT_CHAPTER:
1615         p_demux->info.i_update |= INPUT_UPDATE_SEEKPOINT;
1616         p_demux->info.i_seekpoint = e->param;
1617         break;
1618     case BD_EVENT_ANGLE:
1619         break;
1620     case BD_EVENT_MENU:
1621         p_sys->b_menu_open = e->param;
1622         break;
1623     case BD_EVENT_POPUP:
1624         p_sys->b_popup_available = e->param;
1625         /* TODO: show / hide pop-up menu button in gui ? */
1626         break;
1627
1628     /*
1629      * stream selection events
1630      */
1631     case BD_EVENT_AUDIO_STREAM:
1632     case BD_EVENT_PG_TEXTST_STREAM:
1633         blurayStreamSelect(p_demux, e->event, e->param);
1634         break;
1635     case BD_EVENT_IG_STREAM:
1636         break;
1637
1638     /*
1639      * playback control events
1640      */
1641     case BD_EVENT_STILL_TIME:
1642         blurayStillImage(p_demux, e->param);
1643         break;
1644     case BD_EVENT_DISCONTINUITY:
1645         /* reset demuxer (partially decoded PES packets must be dropped) */
1646         blurayResetParser(p_demux);
1647         break;
1648     case BD_EVENT_IDLE:
1649         /* nothing to do (ex. BD-J is preparing menus, waiting user input or running animation) */
1650         /* avoid busy loop (bd_read() returns no data) */
1651         msleep( 40000 );
1652         break;
1653
1654     default:
1655         msg_Warn(p_demux, "event: %d param: %d", e->event, e->param);
1656         break;
1657     }
1658 }
1659
1660 #define BD_TS_PACKET_SIZE (192)
1661 #define NB_TS_PACKETS (200)
1662
1663 static int blurayDemux(demux_t *p_demux)
1664 {
1665     demux_sys_t *p_sys = p_demux->p_sys;
1666     BD_EVENT e;
1667
1668     block_t *p_block = block_Alloc(NB_TS_PACKETS * (int64_t)BD_TS_PACKET_SIZE);
1669     if (!p_block)
1670         return -1;
1671
1672     int nread;
1673
1674     if (p_sys->b_menu == false) {
1675         while (bd_get_event(p_sys->bluray, &e))
1676             blurayHandleEvent(p_demux, &e);
1677
1678         nread = bd_read(p_sys->bluray, p_block->p_buffer,
1679                         NB_TS_PACKETS * BD_TS_PACKET_SIZE);
1680     } else {
1681         nread = bd_read_ext(p_sys->bluray, p_block->p_buffer,
1682                             NB_TS_PACKETS * BD_TS_PACKET_SIZE, &e);
1683         while (e.event != BD_EVENT_NONE) {
1684             blurayHandleEvent(p_demux, &e);
1685             bd_get_event(p_sys->bluray, &e);
1686         }
1687     }
1688
1689     if (p_sys->current_overlay != -1) {
1690         bluray_overlay_t *ov = p_sys->p_overlays[p_sys->current_overlay];
1691         vlc_mutex_lock(&ov->lock);
1692         bool display = ov->status == ToDisplay;
1693         vlc_mutex_unlock(&ov->lock);
1694         if (display) {
1695             if (p_sys->p_vout == NULL)
1696                 p_sys->p_vout = input_GetVout(p_sys->p_input);
1697             if (p_sys->p_vout != NULL) {
1698                 var_AddCallback(p_sys->p_vout, "mouse-moved", onMouseEvent, p_demux);
1699                 var_AddCallback(p_sys->p_vout, "mouse-clicked", onMouseEvent, p_demux);
1700                 bluraySendOverlayToVout(p_demux);
1701             }
1702         }
1703     }
1704
1705     if (nread <= 0) {
1706         block_Release(p_block);
1707         if (nread < 0)
1708             return -1;
1709         return 1;
1710     }
1711
1712     p_block->i_buffer = nread;
1713
1714     stream_DemuxSend(p_sys->p_parser, p_block);
1715
1716     p_sys->b_flushed = false;
1717
1718     return 1;
1719 }