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