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