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