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