bluray.c 33.8 KB
Newer Older
1 2 3
/*****************************************************************************
 * bluray.c: Blu-ray disc support plugin
 *****************************************************************************
4 5 6
 * Copyright © 2010-2011 VideoLAN, VLC authors and libbluray AUTHORS
 *
 * Authors: Jean-Baptiste Kempf <jb@videolan.org>
7
 *
8 9 10
 * This program is free software; you can redistribute it and/or modify it
 * under the terms of the GNU Lesser General Public License as published by
 * the Free Software Foundation; either version 2.1 of the License, or
11 12 13 14 15
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16
 * GNU Lesser General Public License for more details.
17
 *
18 19 20
 * You should have received a copy of the GNU Lesser General Public License
 * along with this program; if not, write to the Free Software Foundation,
 * Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA.
21 22 23 24 25 26 27
 *****************************************************************************/

#ifdef HAVE_CONFIG_H
# include "config.h"
#endif

#include <assert.h>
28
#include <limits.h>                         /* PATH_MAX */
29 30 31 32
#if defined (HAVE_MNTENT_H) && defined(HAVE_SYS_STAT_H)
#include <mntent.h>
#include <sys/stat.h>
#endif
33 34 35

#include <vlc_common.h>
#include <vlc_plugin.h>
36 37 38
#include <vlc_demux.h>                      /* demux_t */
#include <vlc_input.h>                      /* Seekpoints, chapters */
#include <vlc_dialog.h>                     /* BD+/AACS warnings */
39
#include <vlc_vout.h>                       /* vout_PutSubpicture / subpicture_t */
40 41

#include <libbluray/bluray.h>
42
#include <libbluray/keys.h>
43
#include <libbluray/meta_data.h>
44
#include <libbluray/overlay.h>
45 46 47 48 49

/*****************************************************************************
 * Module descriptor
 *****************************************************************************/

50 51 52 53
#define BD_MENU_TEXT        N_( "Bluray menus" )
#define BD_MENU_LONGTEXT    N_( "Use bluray menus. If disabled, "\
                                "the movie will start directly" )

54 55 56 57 58 59 60 61 62 63
/* Callbacks */
static int  blurayOpen ( vlc_object_t * );
static void blurayClose( vlc_object_t * );

vlc_module_begin ()
    set_shortname( N_("BluRay") )
    set_description( N_("Blu-Ray Disc support (libbluray)") )

    set_category( CAT_INPUT )
    set_subcategory( SUBCAT_INPUT_ACCESS )
64
    set_capability( "access_demux", 200)
65
    add_bool( "bluray-menu", false, BD_MENU_TEXT, BD_MENU_LONGTEXT, false )
66

67
    add_shortcut( "bluray", "file" )
68 69 70 71

    set_callbacks( blurayOpen, blurayClose )
vlc_module_end ()

72 73
/* libbluray's overlay.h defines 2 types of overlay (bd_overlay_plane_e). */
#define MAX_OVERLAY 2
74

75 76 77 78 79 80 81 82
typedef enum OverlayStatus {
    Closed = 0,
    ToDisplay,  //Used to mark the overlay to be displayed the first time.
    Displayed,
    Outdated    //used to update the overlay after it has been sent to the vout
} OverlayStatus;

typedef struct bluray_overlay_t
83
{
84 85 86 87 88 89 90 91 92 93 94
    VLC_GC_MEMBERS

    vlc_mutex_t         lock;
    subpicture_t        *p_pic;
    OverlayStatus       status;
    subpicture_region_t *p_regions;
} bluray_overlay_t;

struct  demux_sys_t
{
    BLURAY              *bluray;
95 96

    /* Titles */
97 98 99
    unsigned int        i_title;
    unsigned int        i_longest_title;
    input_title_t       **pp_title;
100

101
    /* Menus */
102 103 104 105 106 107 108
    bluray_overlay_t    *p_overlays[MAX_OVERLAY];
    int                 current_overlay; // -1 if no current overlay;
    bool                b_menu;

    /* */
    input_thread_t      *p_input;
    vout_thread_t       *p_vout;
109

110
    /* TS stream */
111 112 113 114 115 116
    stream_t            *p_parser;
};

struct subpicture_updater_sys_t
{
    bluray_overlay_t    *p_overlay;
117 118
};

119 120 121 122
/*****************************************************************************
 * Local prototypes
 *****************************************************************************/
static int     blurayControl(demux_t *, int, va_list);
123
static int     blurayDemux(demux_t *);
124 125 126 127

static int     blurayInitTitles(demux_t *p_demux );
static int     bluraySetTitle(demux_t *p_demux, int i_title);

128 129
static void    blurayOverlayProc(void *ptr, const BD_OVERLAY * const overlay);

130 131 132
static int     onMouseEvent( vlc_object_t *p_vout, const char *psz_var,
                             vlc_value_t old, vlc_value_t val, void *p_data );

133 134 135
#define FROM_TICKS(a) (a*CLOCK_FREQ / INT64_C(90000))
#define TO_TICKS(a)   (a*INT64_C(90000)/CLOCK_FREQ)
#define CUR_LENGTH    p_sys->pp_title[p_demux->info.i_title]->i_length
136 137 138 139 140 141

/*****************************************************************************
 * blurayOpen: module init function
 *****************************************************************************/
static int blurayOpen( vlc_object_t *object )
{
142 143
    demux_t *p_demux = (demux_t*)object;
    demux_sys_t *p_sys;
144 145

    char *pos_title;
146
    int i_title = -1;
147
    char bd_path[PATH_MAX] = { '\0' };
148
    const char *error_msg = NULL;
149

150
    if (strcmp(p_demux->psz_access, "bluray")) {
151
        // TODO BDMV support, once we figure out what to do in libbluray
152 153 154
        return VLC_EGENERIC;
    }

155
    /* */
156
    p_demux->p_sys = p_sys = calloc(1, sizeof(*p_sys));
157 158 159
    if (unlikely(!p_sys)) {
        return VLC_ENOMEM;
    }
160
    p_sys->current_overlay = -1;
161 162 163 164 165

    /* init demux info fields */
    p_demux->info.i_update    = 0;
    p_demux->info.i_title     = 0;
    p_demux->info.i_seekpoint = 0;
166

167 168
    TAB_INIT( p_sys->i_title, p_sys->pp_title );

169
    /* store current bd_path */
170 171 172 173
    if (p_demux->psz_file) {
        strncpy(bd_path, p_demux->psz_file, sizeof(bd_path));
        bd_path[PATH_MAX - 1] = '\0';
    }
174

175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194
#if defined (HAVE_MNTENT_H) && defined (HAVE_SYS_STAT_H)
    /* If we're passed a block device, try to convert it to the mount point. */
    struct stat st;
    if ( !stat (bd_path, &st)) {
        if (S_ISBLK (st.st_mode)) {
            FILE* mtab = setmntent ("/proc/self/mounts", "r");
            struct mntent* m;
            struct mntent mbuf;
            char buf [8192];
            while ((m = getmntent_r (mtab, &mbuf, buf, sizeof(buf))) != NULL) {
                if (!strcmp (m->mnt_fsname, bd_path)) {
                    strncpy (bd_path, m->mnt_dir, sizeof(bd_path));
                    bd_path[sizeof(bd_path) - 1] = '\0';
                    break;
                }
            }
            endmntent (mtab);
        }
    }
#endif /* HAVE_MNTENT_H && HAVE_SYS_STAT_H */
195
    p_sys->bluray = bd_open(bd_path, NULL);
196
    if (!p_sys->bluray) {
197 198 199 200
        free(p_sys);
        return VLC_EGENERIC;
    }

201 202
    /* Warning the user about AACS/BD+ */
    const BLURAY_DISC_INFO *disc_info = bd_get_disc_info(p_sys->bluray);
203 204 205 206 207 208 209

    /* Is it a bluray? */
    if (!disc_info->bluray_detected) {
        error_msg = "Path doesn't appear to be a bluray";
        goto error;
    }

210 211
    msg_Info(p_demux, "First play: %i, Top menu: %i\n"
                      "HDMV Titles: %i, BD-J Titles: %i, Other: %i",
212 213 214 215 216 217 218
             disc_info->first_play_supported, disc_info->top_menu_supported,
             disc_info->num_hdmv_titles, disc_info->num_bdj_titles,
             disc_info->num_unsupported_titles);

    /* AACS */
    if (disc_info->aacs_detected) {
        if (!disc_info->libaacs_detected) {
219 220 221
            error_msg = _("This Blu-Ray Disc needs a library for AACS decoding, "
                      "and your system does not have it.");
            goto error;
222 223
        }
        if (!disc_info->aacs_handled) {
224 225 226
            error_msg = _("Your system AACS decoding library does not work. "
                      "Missing keys?");
            goto error;
227 228 229 230 231 232
        }
    }

    /* BD+ */
    if (disc_info->bdplus_detected) {
        if (!disc_info->libbdplus_detected) {
233 234 235
            error_msg = _("This Blu-Ray Disc needs a library for BD+ decoding, "
                      "and your system does not have it.");
            goto error;
236 237
        }
        if (!disc_info->bdplus_handled) {
238 239 240
            error_msg = _("Your system BD+ decoding library does not work. "
                      "Missing configuration?");
            goto error;
241 242 243 244
        }
    }

    /* Get titles and chapters */
245
    if (blurayInitTitles(p_demux) != VLC_SUCCESS) {
246
        goto error;
247 248
    }

249 250 251 252 253
    /*
     * Initialize the event queue, so we can receive events in blurayDemux(Menu).
     */
    bd_get_event(p_sys->bluray, NULL);

254 255 256
    p_sys->b_menu = var_InheritBool( p_demux, "bluray-menu" );
    if ( p_sys->b_menu )
    {
257 258 259 260 261 262 263 264 265
        p_sys->p_input = demux_GetParentInput(p_demux);
        if (unlikely(!p_sys->p_input))
            goto error;

        /* libbluray will start playback from "First-Title" title */
        bd_play(p_sys->bluray);

        /* Registering overlay event handler */
        bd_register_overlay_proc(p_sys->bluray, p_demux, blurayOverlayProc);
266
    }
267 268 269 270 271 272 273 274
    else
    {
        /* get title request */
        if ((pos_title = strrchr(bd_path, ':'))) {
            /* found character ':' for title information */
            *(pos_title++) = '\0';
            i_title = atoi(pos_title);
        }
275

276 277 278 279 280
        /* set start title number */
        if (bluraySetTitle(p_demux, i_title) != VLC_SUCCESS) {
            msg_Err( p_demux, "Could not set the title %d", i_title );
            goto error;
        }
281 282
    }

283 284 285
    p_sys->p_parser   = stream_DemuxNew(p_demux, "ts", p_demux->out);
    if (!p_sys->p_parser) {
        msg_Err(p_demux, "Failed to create TS demuxer");
286
        goto error;
287 288 289 290
    }

    p_demux->pf_control = blurayControl;
    p_demux->pf_demux   = blurayDemux;
291 292

    return VLC_SUCCESS;
293 294 295 296 297 298

error:
    if (error_msg)
        dialog_Fatal(p_demux, _("Blu-Ray error"), "%s", error_msg);
    blurayClose(object);
    return VLC_EGENERIC;
299 300 301 302 303 304 305 306
}


/*****************************************************************************
 * blurayClose: module destroy function
 *****************************************************************************/
static void blurayClose( vlc_object_t *object )
{
307 308 309
    demux_t *p_demux = (demux_t*)object;
    demux_sys_t *p_sys = p_demux->p_sys;

310 311 312 313 314 315 316 317
    /*
     * Close libbluray first.
     * This will close all the overlays before we release p_vout
     * bd_close( NULL ) can crash
     */
    assert(p_sys->bluray);
    bd_close(p_sys->bluray);

318 319 320
    if (p_sys->p_vout != NULL) {
        var_DelCallback(p_sys->p_vout, "mouse-moved", &onMouseEvent, p_demux);
        var_DelCallback(p_sys->p_vout, "mouse-clicked", &onMouseEvent, p_demux);
321
        vlc_object_release(p_sys->p_vout);
322
    }
323 324
    if (p_sys->p_input != NULL)
        vlc_object_release(p_sys->p_input);
325 326
    if (p_sys->p_parser)
        stream_Delete(p_sys->p_parser);
327

328 329 330 331 332
    /* Titles */
    for (unsigned int i = 0; i < p_sys->i_title; i++)
        vlc_input_title_Delete(p_sys->pp_title[i]);
    TAB_CLEAN( p_sys->i_title, p_sys->pp_title );

333 334 335
    free(p_sys);
}

336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428
/*****************************************************************************
 * subpicture_updater_t functions:
 *****************************************************************************/
static int subpictureUpdaterValidate( subpicture_t *p_subpic,
                                      bool b_fmt_src, const video_format_t *p_fmt_src,
                                      bool b_fmt_dst, const video_format_t *p_fmt_dst,
                                      mtime_t i_ts )
{
    VLC_UNUSED( b_fmt_src );
    VLC_UNUSED( b_fmt_dst );
    VLC_UNUSED( p_fmt_src );
    VLC_UNUSED( p_fmt_dst );
    VLC_UNUSED( i_ts );

    subpicture_updater_sys_t *p_upd_sys = p_subpic->updater.p_sys;
    bluray_overlay_t         *p_overlay = p_upd_sys->p_overlay;

    vlc_mutex_lock(&p_overlay->lock);
    int res = p_overlay->status == Outdated;
    vlc_mutex_unlock(&p_overlay->lock);
    return res;
}

/* This should probably be moved to subpictures.c afterward */
static subpicture_region_t* subpicture_region_Clone(subpicture_region_t *p_region_src)
{
    if (!p_region_src)
        return NULL;
    subpicture_region_t *p_region_dst = subpicture_region_New(&p_region_src->fmt);
    if (unlikely(!p_region_dst))
        return NULL;

    p_region_dst->i_x      = p_region_src->i_x;
    p_region_dst->i_y      = p_region_src->i_y;
    p_region_dst->i_align  = p_region_src->i_align;
    p_region_dst->i_alpha  = p_region_src->i_alpha;

    p_region_dst->psz_text = p_region_src->psz_text ? strdup(p_region_src->psz_text) : NULL;
    p_region_dst->psz_html = p_region_src->psz_html ? strdup(p_region_src->psz_html) : NULL;
    if (p_region_src->p_style != NULL) {
        p_region_dst->p_style = malloc(sizeof(*p_region_dst->p_style));
        p_region_dst->p_style = text_style_Copy(p_region_dst->p_style,
                                                p_region_src->p_style);
    }

    //Palette is already copied by subpicture_region_New, we just have to duplicate p_pixels
    for (int i = 0; i < p_region_src->p_picture->i_planes; i++)
        memcpy(p_region_dst->p_picture->p[i].p_pixels,
               p_region_src->p_picture->p[i].p_pixels,
               p_region_src->p_picture->p[i].i_lines * p_region_src->p_picture->p[i].i_pitch);
    return p_region_dst;
}

static void subpictureUpdaterUpdate(subpicture_t *p_subpic,
                                    const video_format_t *p_fmt_src,
                                    const video_format_t *p_fmt_dst,
                                    mtime_t i_ts)
{
    VLC_UNUSED(p_fmt_src);
    VLC_UNUSED(p_fmt_dst);
    VLC_UNUSED(i_ts);
    subpicture_updater_sys_t *p_upd_sys = p_subpic->updater.p_sys;
    bluray_overlay_t         *p_overlay = p_upd_sys->p_overlay;

    /*
     * When this function is called, all p_subpic regions are gone.
     * We need to duplicate our regions (stored internaly) to this subpic.
     */
    vlc_mutex_lock(&p_overlay->lock);

    subpicture_region_t *p_src = p_overlay->p_regions;
    if (!p_src)
        return;

    subpicture_region_t **p_dst = &(p_subpic->p_region);
    while (p_src != NULL) {
        *p_dst = subpicture_region_Clone(p_src);
        if (*p_dst == NULL)
            break ;
        p_dst = &((*p_dst)->p_next);
        p_src = p_src->p_next;
    }
    if (*p_dst != NULL)
        (*p_dst)->p_next = NULL;
    p_overlay->status = Displayed;
    vlc_mutex_unlock(&p_overlay->lock);
}

static void subpictureUpdaterDestroy(subpicture_t *p_subpic)
{
    vlc_gc_decref(p_subpic->updater.p_sys->p_overlay);
}

429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451
/*****************************************************************************
 * User input events:
 *****************************************************************************/
static int onMouseEvent(vlc_object_t *p_vout, const char *psz_var, vlc_value_t old,
                        vlc_value_t val, void *p_data)
{
    demux_t     *p_demux = (demux_t*)p_data;
    demux_sys_t *p_sys   = p_demux->p_sys;
    mtime_t     now      = mdate();
    VLC_UNUSED(old);
    VLC_UNUSED(p_vout);

    if (psz_var[6] == 'm')   //Mouse moved
        bd_mouse_select(p_sys->bluray, now, val.coords.x, val.coords.y);
    else if (psz_var[6] == 'c') {
        bd_mouse_select(p_sys->bluray, now, val.coords.x, val.coords.y);
        bd_user_input(p_sys->bluray, now, BD_VK_MOUSE_ACTIVATE);
    } else {
        assert(0);
    }
    return VLC_SUCCESS;
}

452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481
/*****************************************************************************
 * libbluray overlay handling:
 *****************************************************************************/
static void blurayCleanOverayStruct(gc_object_t *p_gc)
{
    bluray_overlay_t *p_overlay = vlc_priv(p_gc, bluray_overlay_t);

    /*
     * This will be called when destroying the picture.
     * Don't delete it again from here!
     */
    vlc_mutex_destroy(&p_overlay->lock);
    subpicture_region_Delete(p_overlay->p_regions);
    free(p_overlay);
}

static void blurayCloseAllOverlays(demux_t *p_demux)
{
    demux_sys_t *p_sys = p_demux->p_sys;

    p_demux->p_sys->current_overlay = -1;
    if (p_sys->p_vout != NULL) {
        for (int i = 0; i < 0; i++) {
            if (p_sys->p_overlays[i] != NULL) {
                vout_FlushSubpictureChannel(p_sys->p_vout,
                                            p_sys->p_overlays[i]->p_pic->i_channel);
                vlc_gc_decref(p_sys->p_overlays[i]);
                p_sys->p_overlays[i] = NULL;
            }
        }
482 483
        var_DelCallback(p_sys->p_vout, "mouse-moved", &onMouseEvent, p_demux);
        var_DelCallback(p_sys->p_vout, "mouse-clicked", &onMouseEvent, p_demux);
484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699
        vlc_object_release(p_sys->p_vout);
        p_sys->p_vout = NULL;
    }
}

/*
 * Mark the overlay as "ToDisplay" status.
 * This will not send the overlay to the vout instantly, as the vout
 * may not be acquired (not acquirable) yet.
 * If is has already been acquired, the overlay has already been sent to it,
 * therefore, we only flag the overlay as "Outdated"
 */
static void blurayActivateOverlay(demux_t *p_demux, const BD_OVERLAY* const ov)
{
    demux_sys_t *p_sys = p_demux->p_sys;

    /*
     * If the overlay is already displayed, mark the picture as outdated.
     * We must NOT use vout_PutSubpicture if a picture is already displayed.
     */
    vlc_mutex_lock(&p_sys->p_overlays[ov->plane]->lock);
    if ((p_sys->p_overlays[ov->plane]->status == Displayed ||
            p_sys->p_overlays[ov->plane]->status == Outdated)
            && p_sys->p_vout) {
        p_sys->p_overlays[ov->plane]->status = Outdated;
        vlc_mutex_unlock(&p_sys->p_overlays[ov->plane]->lock);
        return ;
    }
    /*
     * Mark the overlay as available, but don't display it right now.
     * the blurayDemuxMenu will send it to vout, as it may be unavailable when
     * the overlay is computed
     */
    p_sys->current_overlay = ov->plane;
    p_sys->p_overlays[ov->plane]->status = ToDisplay;
    vlc_mutex_unlock(&p_sys->p_overlays[ov->plane]->lock);
}

static void blurayInitOverlay(demux_t *p_demux, const BD_OVERLAY* const ov)
{
    demux_sys_t *p_sys = p_demux->p_sys;

    assert(p_sys->p_overlays[ov->plane] == NULL);

    p_sys->p_overlays[ov->plane] = calloc(1, sizeof(**p_sys->p_overlays));
    if (unlikely(!p_sys->p_overlays[ov->plane]))
        return;

    subpicture_updater_sys_t *p_upd_sys = malloc(sizeof(*p_upd_sys));
    if (unlikely(!p_upd_sys)) {
        free(p_sys->p_overlays[ov->plane]);
        p_sys->p_overlays[ov->plane] = NULL;
        return;
    }
    vlc_gc_init(p_sys->p_overlays[ov->plane], blurayCleanOverayStruct);
    /* Incrementing refcounter: vout + demux */
    vlc_gc_incref(p_sys->p_overlays[ov->plane]);

    p_upd_sys->p_overlay = p_sys->p_overlays[ov->plane];
    subpicture_updater_t updater = {
        .pf_validate = subpictureUpdaterValidate,
        .pf_update   = subpictureUpdaterUpdate,
        .pf_destroy  = subpictureUpdaterDestroy,
        .p_sys       = p_upd_sys,
    };
    p_sys->p_overlays[ov->plane]->p_pic = subpicture_New(&updater);
    p_sys->p_overlays[ov->plane]->p_pic->i_original_picture_width = ov->w;
    p_sys->p_overlays[ov->plane]->p_pic->i_original_picture_height = ov->h;
    p_sys->p_overlays[ov->plane]->p_pic->b_ephemer = true;
    p_sys->p_overlays[ov->plane]->p_pic->b_absolute = true;
}

/**
 * Destroy every regions in the subpicture.
 * This is done in two steps:
 * - Wiping our private regions list
 * - Flagging the overlay as outdated, so the changes are replicated from
 *   the subpicture_updater_t::pf_update
 * This doesn't destroy the subpicture, as the overlay may be used again by libbluray.
 */
static void blurayClearOverlay(demux_t *p_demux, const BD_OVERLAY* const ov)
{
    demux_sys_t *p_sys = p_demux->p_sys;

    vlc_mutex_lock(&p_sys->p_overlays[ov->plane]->lock);

    subpicture_region_ChainDelete(p_sys->p_overlays[ov->plane]->p_regions);
    p_sys->p_overlays[ov->plane]->p_regions = NULL;
    p_sys->p_overlays[ov->plane]->status = Outdated;
    vlc_mutex_unlock(&p_sys->p_overlays[ov->plane]->lock);
}

/*
 * This will draw to the overlay by adding a region to our region list
 * This will have to be copied to the subpicture used to render the overlay.
 */
static void blurayDrawOverlay(demux_t *p_demux, const BD_OVERLAY* const ov)
{
    demux_sys_t *p_sys = p_demux->p_sys;

    /*
     * Compute a subpicture_region_t.
     * It will be copied and sent to the vout later.
     */
    if (!ov->img)
        return;

    vlc_mutex_lock(&p_sys->p_overlays[ov->plane]->lock);

    /* Find a region to update */
    subpicture_region_t *p_reg = p_sys->p_overlays[ov->plane]->p_regions;
    subpicture_region_t *p_last = NULL;
    while (p_reg != NULL) {
        p_last = p_reg;
        if (p_reg->i_x == ov->x && p_reg->i_y == ov->y &&
                p_reg->fmt.i_width == ov->w && p_reg->fmt.i_height == ov->h)
            break;
        p_reg = p_reg->p_next;
    }

    /* If there is no region to update, create a new one. */
    if (!p_reg) {
        video_format_t fmt;
        video_format_Init(&fmt, 0);
        video_format_Setup(&fmt, VLC_CODEC_YUVP, ov->w, ov->h, 1, 1);

        p_reg = subpicture_region_New(&fmt);
        p_reg->i_x = ov->x;
        p_reg->i_y = ov->y;
        /* Append it to our list. */
        if (p_last != NULL)
            p_last->p_next = p_reg;
        else /* If we don't have a last region, then our list empty */
            p_sys->p_overlays[ov->plane]->p_regions = p_reg;
    }

    /* Now we can update the region, regardless it's an update or an insert */
    const BD_PG_RLE_ELEM *img = ov->img;
    for (int y = 0; y < ov->h; y++) {
        for (int x = 0; x < ov->w;) {
            memset(p_reg->p_picture->p[0].p_pixels +
                   y * p_reg->p_picture->p[0].i_pitch + x,
                   img->color, img->len);
            x += img->len;
            img++;
        }
    }
    if (ov->palette) {
        p_reg->fmt.p_palette->i_entries = 256;
        for (int i = 0; i < 256; ++i) {
            p_reg->fmt.p_palette->palette[i][0] = ov->palette[i].Y;
            p_reg->fmt.p_palette->palette[i][1] = ov->palette[i].Cb;
            p_reg->fmt.p_palette->palette[i][2] = ov->palette[i].Cr;
            p_reg->fmt.p_palette->palette[i][3] = ov->palette[i].T;
        }
    }
    vlc_mutex_unlock(&p_sys->p_overlays[ov->plane]->lock);
    /*
     * /!\ The region is now stored in our internal list, but not in the subpicture /!\
     */
}

static void blurayOverlayProc(void *ptr, const BD_OVERLAY *const overlay)
{
    demux_t *p_demux = (demux_t*)ptr;

    if (!overlay) {
        msg_Info(p_demux, "Closing overlay.");
        blurayCloseAllOverlays(p_demux);
        return;
    }
    switch (overlay->cmd) {
        case BD_OVERLAY_INIT:
            msg_Info(p_demux, "Initializing overlay");
            blurayInitOverlay(p_demux, overlay);
            break;
        case BD_OVERLAY_CLEAR:
            blurayClearOverlay(p_demux, overlay);
            break;
        case BD_OVERLAY_FLUSH:
            blurayActivateOverlay(p_demux, overlay);
            break;
        case BD_OVERLAY_DRAW:
            blurayDrawOverlay(p_demux, overlay);
            break;
        default:
            msg_Warn(p_demux, "Unknown BD overlay command: %u", overlay->cmd);
            break;
    }
}

static void bluraySendOverlayToVout(demux_t *p_demux)
{
    demux_sys_t *p_sys = p_demux->p_sys;

    assert(p_sys->current_overlay >= 0 &&
           p_sys->p_overlays[p_sys->current_overlay] != NULL &&
           p_sys->p_overlays[p_sys->current_overlay]->p_pic != NULL);

    p_sys->p_overlays[p_sys->current_overlay]->p_pic->i_start =
        p_sys->p_overlays[p_sys->current_overlay]->p_pic->i_stop = mdate();
    p_sys->p_overlays[p_sys->current_overlay]->p_pic->i_channel =
        vout_RegisterSubpictureChannel(p_sys->p_vout);
    /*
     * After this point, the picture should not be accessed from the demux thread,
     * as it's hold by the vout thread.
     * This must be done only once per subpicture, ie. only once between each
     * blurayInitOverlay & blurayCloseOverlay call.
     */
    vout_PutSubpicture(p_sys->p_vout, p_sys->p_overlays[p_sys->current_overlay]->p_pic);
    /*
     * Mark the picture as Outdated, as it contains no region for now.
     * This will make the subpicture_updater_t call pf_update
     */
    p_sys->p_overlays[p_sys->current_overlay]->status = Outdated;
}
700 701

static int blurayInitTitles(demux_t *p_demux )
702
{
703
    demux_sys_t *p_sys = p_demux->p_sys;
704 705

    /* get and set the titles */
706
    unsigned i_title = bd_get_titles(p_sys->bluray, TITLES_RELEVANT, 60);
707 708 709 710 711 712 713
    int64_t duration = 0;

    for (unsigned int i = 0; i < i_title; i++) {
        input_title_t *t = vlc_input_title_New();
        if (!t)
            break;

714
        BLURAY_TITLE_INFO *title_info = bd_get_title_info(p_sys->bluray, i, 0);
715 716
        if (!title_info)
            break;
717
        t->i_length = FROM_TICKS(title_info->duration);
718 719 720 721 722 723 724 725

        if (t->i_length > duration) {
            duration = t->i_length;
            p_sys->i_longest_title = i;
        }

        for ( unsigned int j = 0; j < title_info->chapter_count; j++) {
            seekpoint_t *s = vlc_seekpoint_New();
726
            if (!s)
727 728 729 730 731 732 733 734 735 736
                break;
            s->i_time_offset = title_info->chapters[j].offset;

            TAB_APPEND( t->i_seekpoint, t->seekpoint, s );
        }
        TAB_APPEND( p_sys->i_title, p_sys->pp_title, t );
        bd_free_title_info(title_info);
    }
    return VLC_SUCCESS;
}
737

738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754
static void blurayResetParser( demux_t *p_demux )
{
    /*
     * This is a hack and will have to be removed.
     * The parser should be flushed, and not destroy/created each time
     * we are changing title.
     */
    demux_sys_t *p_sys = p_demux->p_sys;
    if (!p_sys->p_parser)
        return;
    stream_Delete(p_sys->p_parser);
    p_sys->p_parser = stream_DemuxNew(p_demux, "ts", p_demux->out);
    if (!p_sys->p_parser) {
        msg_Err(p_demux, "Failed to create TS demuxer");
    }
}

755 756
static void blurayUpdateTitle( demux_t *p_demux, int i_title )
{
757 758 759 760
    blurayResetParser(p_demux);
    if (i_title >= p_demux->p_sys->i_title)
        return;

761 762 763 764 765
    /* read title info and init some values */
    p_demux->info.i_title = i_title;
    p_demux->info.i_seekpoint = 0;
    p_demux->info.i_update |= INPUT_UPDATE_TITLE | INPUT_UPDATE_SEEKPOINT;
}
766

767 768 769
/*****************************************************************************
 * bluraySetTitle: select new BD title
 *****************************************************************************/
770
static int bluraySetTitle(demux_t *p_demux, int i_title)
771
{
772
    demux_sys_t *p_sys = p_demux->p_sys;
773

774
    /* Looking for the main title, ie the longest duration */
775
    if (i_title < 0)
776
        i_title = p_sys->i_longest_title;
777 778
    else if ((unsigned)i_title > p_sys->i_title)
        return VLC_EGENERIC;
779

780
    msg_Dbg( p_demux, "Selecting Title %i", i_title);
781

782
    /* Select Blu-Ray title */
783 784
    if (bd_select_title(p_demux->p_sys->bluray, i_title) == 0 ) {
        msg_Err(p_demux, "cannot select bd title '%d'", p_demux->info.i_title);
785 786
        return VLC_EGENERIC;
    }
787
    blurayUpdateTitle( p_demux, i_title );
788 789 790 791 792 793 794 795

    return VLC_SUCCESS;
}


/*****************************************************************************
 * blurayControl: handle the controls
 *****************************************************************************/
796
static int blurayControl(demux_t *p_demux, int query, va_list args)
797
{
798
    demux_sys_t *p_sys = p_demux->p_sys;
799 800 801 802
    bool     *pb_bool;
    int64_t  *pi_64;

    switch (query) {
803 804 805
        case DEMUX_CAN_SEEK:
        case DEMUX_CAN_PAUSE:
        case DEMUX_CAN_CONTROL_PACE:
806 807 808 809
             pb_bool = (bool*)va_arg( args, bool * );
             *pb_bool = true;
             break;

810
        case DEMUX_GET_PTS_DELAY:
811
            pi_64 = (int64_t*)va_arg( args, int64_t * );
812 813
            *pi_64 =
                INT64_C(1000) * var_InheritInteger( p_demux, "disc-caching" );
814 815
            break;

816
        case DEMUX_SET_PAUSE_STATE:
817 818 819
            /* Nothing to do */
            break;

820
        case DEMUX_SET_TITLE:
821 822
        {
            int i_title = (int)va_arg( args, int );
823
            if (bluraySetTitle(p_demux, i_title) != VLC_SUCCESS)
824 825 826
                return VLC_EGENERIC;
            break;
        }
827
        case DEMUX_SET_SEEKPOINT:
828 829 830
        {
            int i_chapter = (int)va_arg( args, int );
            bd_seek_chapter( p_sys->bluray, i_chapter );
831
            p_demux->info.i_update = INPUT_UPDATE_SEEKPOINT;
832 833
            break;
        }
834

835
        case DEMUX_GET_TITLE_INFO:
836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853
        {
            input_title_t ***ppp_title = (input_title_t***)va_arg( args, input_title_t*** );
            int *pi_int             = (int*)va_arg( args, int* );
            int *pi_title_offset    = (int*)va_arg( args, int* );
            int *pi_chapter_offset  = (int*)va_arg( args, int* );

            /* */
            *pi_title_offset   = 0;
            *pi_chapter_offset = 0;

            /* Duplicate local title infos */
            *pi_int = p_sys->i_title;
            *ppp_title = calloc( p_sys->i_title, sizeof(input_title_t **) );
            for( unsigned int i = 0; i < p_sys->i_title; i++ )
                (*ppp_title)[i] = vlc_input_title_Duplicate( p_sys->pp_title[i]);

            return VLC_SUCCESS;
        }
854

855 856 857
        case DEMUX_GET_LENGTH:
        {
            int64_t *pi_length = (int64_t*)va_arg(args, int64_t *);
858
            *pi_length = p_demux->info.i_title < p_sys->i_title ? CUR_LENGTH : 0;
859 860 861 862 863 864 865 866 867 868 869 870 871 872
            return VLC_SUCCESS;
        }
        case DEMUX_SET_TIME:
        {
            int64_t i_time = (int64_t)va_arg(args, int64_t);
            bd_seek_time(p_sys->bluray, TO_TICKS(i_time));
            return VLC_SUCCESS;
        }
        case DEMUX_GET_TIME:
        {
            int64_t *pi_time = (int64_t*)va_arg(args, int64_t *);
            *pi_time = (int64_t)FROM_TICKS(bd_tell_time(p_sys->bluray));
            return VLC_SUCCESS;
        }
873

874 875 876
        case DEMUX_GET_POSITION:
        {
            double *pf_position = (double*)va_arg( args, double * );
877 878
            *pf_position = p_demux->info.i_title < p_sys->i_title ?
                        (double)FROM_TICKS(bd_tell_time(p_sys->bluray))/CUR_LENGTH : 0.0;
879 880 881 882 883 884 885 886 887 888 889
            return VLC_SUCCESS;
        }
        case DEMUX_SET_POSITION:
        {
            double f_position = (double)va_arg(args, double);
            bd_seek_time(p_sys->bluray, TO_TICKS(f_position*CUR_LENGTH));
            return VLC_SUCCESS;
        }

        case DEMUX_GET_META:
        {
890
            const struct meta_dl *meta = bd_get_meta(p_sys->bluray);
891 892 893
            if(!meta)
                return VLC_EGENERIC;

894
            vlc_meta_t *p_meta = (vlc_meta_t *) va_arg (args, vlc_meta_t*);
895

896
            if (!EMPTY_STR(meta->di_name)) vlc_meta_SetTitle(p_meta, meta->di_name);
897

898 899 900
            if (!EMPTY_STR(meta->language_code)) vlc_meta_AddExtra(p_meta, "Language", meta->language_code);
            if (!EMPTY_STR(meta->filename)) vlc_meta_AddExtra(p_meta, "Filename", meta->filename);
            if (!EMPTY_STR(meta->di_alternative)) vlc_meta_AddExtra(p_meta, "Alternative", meta->di_alternative);
901

902 903
            // if (meta->di_set_number > 0) vlc_meta_SetTrackNum(p_meta, meta->di_set_number);
            // if (meta->di_num_sets > 0) vlc_meta_AddExtra(p_meta, "Discs numbers in Set", meta->di_num_sets);
904

905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921
            if (meta->thumb_count > 0 && meta->thumbnails) {
                vlc_meta_SetArtURL(p_meta, meta->thumbnails[0].path);
            }

            return VLC_SUCCESS;
        }

        case DEMUX_CAN_RECORD:
        case DEMUX_GET_FPS:
        case DEMUX_SET_GROUP:
        case DEMUX_HAS_UNSUPPORTED_META:
        case DEMUX_GET_ATTACHMENTS:
            return VLC_EGENERIC;
        default:
            msg_Warn( p_demux, "unimplemented query (%d) in control", query );
            return VLC_EGENERIC;
    }
922 923 924
    return VLC_SUCCESS;
}

925 926 927 928 929 930 931
static void blurayHandleEvent( demux_t *p_demux, const BD_EVENT *e )
{
    demux_sys_t *p_sys = p_demux->p_sys;

    switch (e->event)
    {
        case BD_EVENT_TITLE:
932
            blurayUpdateTitle( p_demux, e->param );
933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958
            break;
        case BD_EVENT_PLAYITEM:
            break;
        case BD_EVENT_AUDIO_STREAM:
            break;
        case BD_EVENT_CHAPTER:
            p_demux->info.i_update |= INPUT_UPDATE_SEEKPOINT;
            p_demux->info.i_seekpoint = 0;
            break;
        case BD_EVENT_ANGLE:
        case BD_EVENT_IG_STREAM:
        default:
            msg_Warn( p_demux, "event: %d param: %d", e->event, e->param );
            break;
    }
}

static void blurayHandleEvents( demux_t *p_demux )
{
    BD_EVENT e;

    while (bd_get_event(p_demux->p_sys->bluray, &e))
    {
        blurayHandleEvent(p_demux, &e);
    }
}
959

960 961 962 963
#define BD_TS_PACKET_SIZE (192)
#define NB_TS_PACKETS (200)

static int blurayDemux(demux_t *p_demux)
964
{
965
    demux_sys_t *p_sys = p_demux->p_sys;
966

967 968 969
    block_t *p_block = block_New(p_demux, NB_TS_PACKETS * (int64_t)BD_TS_PACKET_SIZE);
    if (!p_block) {
        return -1;
970 971
    }

972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993
    int nread = -1;
    if (p_sys->b_menu == false) {
        blurayHandleEvents(p_demux);
        nread = bd_read(p_sys->bluray, p_block->p_buffer,
                NB_TS_PACKETS * BD_TS_PACKET_SIZE);
        if (nread < 0) {
            block_Release(p_block);
            return nread;
        }
    }
    else {
        BD_EVENT e;
        nread = bd_read_ext( p_sys->bluray, p_block->p_buffer,
                NB_TS_PACKETS * BD_TS_PACKET_SIZE, &e );
        if ( nread == 0 ) {
            if ( e.event == BD_EVENT_NONE )
                msg_Info( p_demux, "We reached the end of a title" );
            else
                blurayHandleEvent( p_demux, &e );
            block_Release(p_block);
            return 1;
        }
994 995 996 997 998 999 1000 1001
        if (p_sys->current_overlay != -1)
        {
            vlc_mutex_lock(&p_sys->p_overlays[p_sys->current_overlay]->lock);
            if (p_sys->p_overlays[p_sys->current_overlay]->status == ToDisplay) {
                vlc_mutex_unlock(&p_sys->p_overlays[p_sys->current_overlay]->lock);
                if (p_sys->p_vout == NULL)
                    p_sys->p_vout = input_GetVout(p_sys->p_input);
                if (p_sys->p_vout != NULL) {
1002 1003
                    var_AddCallback(p_sys->p_vout, "mouse-moved", &onMouseEvent, p_demux);
                    var_AddCallback(p_sys->p_vout, "mouse-clicked", &onMouseEvent, p_demux);
1004 1005 1006 1007 1008
                    bluraySendOverlayToVout(p_demux);
                }
            } else
                vlc_mutex_unlock(&p_sys->p_overlays[p_sys->current_overlay]->lock);
        }
1009 1010
    }

1011
    p_block->i_buffer = nread;
1012

1013 1014 1015 1016
    stream_DemuxSend( p_sys->p_parser, p_block );

    return 1;
}