bluray.c 74.6 KB
Newer Older
1 2 3
/*****************************************************************************
 * bluray.c: Blu-ray disc support plugin
 *****************************************************************************
Jean-Baptiste Kempf's avatar
Jean-Baptiste Kempf committed
4
 * Copyright © 2010-2012 VideoLAN, VLC authors and libbluray AUTHORS
5 6
 *
 * Authors: Jean-Baptiste Kempf <jb@videolan.org>
Jean-Baptiste Kempf's avatar
Jean-Baptiste Kempf committed
7
 *          Hugo Beauzée-Luyssen <hugo@videolan.org>
8
 *
9 10 11
 * 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
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
Jean-Baptiste Kempf's avatar
LGPL  
Jean-Baptiste Kempf committed
16
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
17
 * GNU Lesser General Public License for more details.
18
 *
19 20 21
 * 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.
22 23 24 25 26 27 28
 *****************************************************************************/

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

#include <assert.h>
Jean-Baptiste Kempf's avatar
Jean-Baptiste Kempf committed
29

30
#if defined (HAVE_MNTENT_H) && defined(HAVE_SYS_STAT_H)
Jean-Baptiste Kempf's avatar
Jean-Baptiste Kempf committed
31 32
# include <mntent.h>
# include <sys/stat.h>
33
#endif
34 35
#include <fcntl.h>      /* O_* */
#include <unistd.h>     /* close() */
36

37
#ifdef __APPLE__
Jean-Baptiste Kempf's avatar
Jean-Baptiste Kempf committed
38 39 40 41
# include <sys/stat.h>
# include <sys/param.h>
# include <sys/ucred.h>
# include <sys/mount.h>
42 43
#endif

44 45
#include <vlc_common.h>
#include <vlc_plugin.h>
46 47
#include <vlc_demux.h>                      /* demux_t */
#include <vlc_input.h>                      /* Seekpoints, chapters */
48
#include <vlc_atomic.h>
49
#include <vlc_dialog.h>                     /* BD+/AACS warnings */
50
#include <vlc_vout.h>                       /* vout_PutSubpicture / subpicture_t */
51
#include <vlc_url.h>                        /* vlc_path2uri */
52
#include <vlc_iso_lang.h>
53
#include <vlc_fs.h>
54 55 56 57

/* FIXME we should find a better way than including that */
#include "../../src/text/iso-639_def.h"

58 59

#include <libbluray/bluray.h>
60
#include <libbluray/bluray-version.h>
61
#include <libbluray/keys.h>
62
#include <libbluray/meta_data.h>
63
#include <libbluray/overlay.h>
64 65 66 67 68

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

Rafaël Carré's avatar
Rafaël Carré committed
69 70 71 72 73
#define BD_MENU_TEXT        N_("Blu-ray menus")
#define BD_MENU_LONGTEXT    N_("Use Blu-ray menus. If disabled, "\
                                "the movie will start directly")
#define BD_REGION_TEXT      N_("Region code")
#define BD_REGION_LONGTEXT  N_("Blu-Ray player region code. "\
74 75 76 77 78 79 80 81
                                "Some discs can be played only with a correct region code.")

static const char *const ppsz_region_code[] = {
    "A", "B", "C" };
static const char *const ppsz_region_code_text[] = {
    "Region A", "Region B", "Region C" };

#define REGION_DEFAULT   1   /* Index to region list. Actual region code is (1<<REGION_DEFAULT) */
82
#define LANGUAGE_DEFAULT ("eng")
83

84
/* Callbacks */
Rafaël Carré's avatar
Rafaël Carré committed
85 86
static int  blurayOpen (vlc_object_t *);
static void blurayClose(vlc_object_t *);
87 88

vlc_module_begin ()
Rafaël Carré's avatar
Rafaël Carré committed
89 90
    set_shortname(N_("Blu-ray"))
    set_description(N_("Blu-ray Disc support (libbluray)"))
91

Rafaël Carré's avatar
Rafaël Carré committed
92 93 94
    set_category(CAT_INPUT)
    set_subcategory(SUBCAT_INPUT_ACCESS)
    set_capability("access_demux", 200)
95
    add_bool("bluray-menu", true, BD_MENU_TEXT, BD_MENU_LONGTEXT, false)
Rafaël Carré's avatar
Rafaël Carré committed
96 97
    add_string("bluray-region", ppsz_region_code[REGION_DEFAULT], BD_REGION_TEXT, BD_REGION_LONGTEXT, false)
        change_string_list(ppsz_region_code, ppsz_region_code_text)
98

Rafaël Carré's avatar
Rafaël Carré committed
99
    add_shortcut("bluray", "file")
100

Rafaël Carré's avatar
Rafaël Carré committed
101
    set_callbacks(blurayOpen, blurayClose)
102 103 104 105 106 107 108 109 110

    /* demux module */
    add_submodule()
        set_description( "BluRay demuxer" )
        set_category( CAT_INPUT )
        set_subcategory( SUBCAT_INPUT_DEMUX )
        set_capability( "demux", 5 )
        set_callbacks( blurayOpen, blurayClose )

111 112
vlc_module_end ()

113 114
/* libbluray's overlay.h defines 2 types of overlay (bd_overlay_plane_e). */
#define MAX_OVERLAY 2
115

116 117 118 119 120 121 122 123
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
124
{
125
    vlc_mutex_t         lock;
126
    int                 i_channel;
127 128
    OverlayStatus       status;
    subpicture_region_t *p_regions;
129
    int                 width, height;
130 131 132 133 134 135 136

    /* pointer to last subpicture updater.
     * used to disconnect this overlay from vout when:
     * - the overlay is closed
     * - vout is changed and this overlay is sent to the new vout
     */
    struct subpicture_updater_sys_t *p_updater;
137 138 139 140 141
} bluray_overlay_t;

struct  demux_sys_t
{
    BLURAY              *bluray;
142 143

    /* Titles */
144 145 146
    unsigned int        i_title;
    unsigned int        i_longest_title;
    input_title_t       **pp_title;
147

148 149 150 151
    vlc_mutex_t             pl_info_lock;
    BLURAY_TITLE_INFO      *p_pl_info;
    const BLURAY_CLIP_INFO *p_clip_info;

152 153 154 155 156
    /* Attachments */
    int                 i_attachments;
    input_attachment_t  **attachments;
    int                 i_cover_idx;

157
    /* Meta information */
158 159
    const META_DL       *p_meta;

160
    /* Menus */
161
    bluray_overlay_t    *p_overlays[MAX_OVERLAY];
162
    bool                b_fatal_error;
163
    bool                b_menu;
Petri Hintukainen's avatar
Petri Hintukainen committed
164 165
    bool                b_menu_open;
    bool                b_popup_available;
166
    mtime_t             i_still_end_time;
167

168 169
    vlc_mutex_t         bdj_overlay_lock; /* used to lock BD-J overlay open/close while overlays are being sent to vout */

170 171
    /* */
    vout_thread_t       *p_vout;
172

173 174
    es_out_id_t         *p_dummy_video;

175
    /* TS stream */
176
    es_out_t            *p_out;
177
    vlc_array_t         es;
178 179
    int                 i_audio_stream_idx; /* Selected audio stream. -1 if default */
    int                 i_spu_stream_idx;   /* Selected subtitle stream. -1 if default */
180
    bool                b_spu_enable;       /* enabled / disabled */
181
    int                 i_video_stream;
182
    stream_t            *p_parser;
183
    bool                b_flushed;
184
    bool                b_pl_playing;       /* true when playing playlist */
185

186 187 188
    /* stream input */
    vlc_mutex_t         read_block_lock;

189 190
    /* Used to store bluray disc path */
    char                *psz_bd_path;
191 192 193 194
};

struct subpicture_updater_sys_t
{
195 196 197
    vlc_mutex_t          lock;      // protect p_overlay pointer and ref_cnt
    bluray_overlay_t    *p_overlay; // NULL if overlay has been closed
    int                  ref_cnt;   // one reference in vout (subpicture_t), one in input (bluray_overlay_t)
198 199
};

200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217
/*
 * cut the connection between vout and overlay.
 * - called when vout is closed or overlay is closed.
 * - frees subpicture_updater_sys_t when both sides have been closed.
 */
static void unref_subpicture_updater(subpicture_updater_sys_t *p_sys)
{
    vlc_mutex_lock(&p_sys->lock);
    int refs = p_sys->ref_cnt--;
    p_sys->p_overlay = NULL;
    vlc_mutex_unlock(&p_sys->lock);

    if (refs < 1) {
        vlc_mutex_destroy(&p_sys->lock);
        free(p_sys);
    }
}

218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254
/* Get a 3 char code
 * FIXME: partiallyy duplicated from src/input/es_out.c
 */
static const char *DemuxGetLanguageCode( demux_t *p_demux, const char *psz_var )
{
    const iso639_lang_t *pl;
    char *psz_lang;
    char *p;

    psz_lang = var_CreateGetString( p_demux, psz_var );
    if( !psz_lang )
        return LANGUAGE_DEFAULT;

    /* XXX: we will use only the first value
     * (and ignore other ones in case of a list) */
    if( ( p = strchr( psz_lang, ',' ) ) )
        *p = '\0';

    for( pl = p_languages; pl->psz_eng_name != NULL; pl++ )
    {
        if( *psz_lang == '\0' )
            continue;
        if( !strcasecmp( pl->psz_eng_name, psz_lang ) ||
            !strcasecmp( pl->psz_iso639_1, psz_lang ) ||
            !strcasecmp( pl->psz_iso639_2T, psz_lang ) ||
            !strcasecmp( pl->psz_iso639_2B, psz_lang ) )
            break;
    }

    free( psz_lang );

    if( pl->psz_eng_name != NULL )
        return pl->psz_iso639_2T;

    return LANGUAGE_DEFAULT;
}

255 256 257
/*****************************************************************************
 * Local prototypes
 *****************************************************************************/
Rafaël Carré's avatar
Rafaël Carré committed
258
static es_out_t *esOutNew(demux_t *p_demux);
259

Jean-Baptiste Kempf's avatar
Jean-Baptiste Kempf committed
260 261
static int   blurayControl(demux_t *, int, va_list);
static int   blurayDemux(demux_t *);
262

263
static void  blurayInitTitles(demux_t *p_demux, int menu_titles);
Jean-Baptiste Kempf's avatar
Jean-Baptiste Kempf committed
264
static int   bluraySetTitle(demux_t *p_demux, int i_title);
265

Jean-Baptiste Kempf's avatar
Jean-Baptiste Kempf committed
266
static void  blurayOverlayProc(void *ptr, const BD_OVERLAY * const overlay);
267
static void  blurayArgbOverlayProc(void *ptr, const BD_ARGB_OVERLAY * const overlay);
268

Jean-Baptiste Kempf's avatar
Jean-Baptiste Kempf committed
269 270
static int   onMouseEvent(vlc_object_t *p_vout, const char *psz_var,
                          vlc_value_t old, vlc_value_t val, void *p_data);
271 272
static int   onIntfEvent(vlc_object_t *, char const *,
                         vlc_value_t, vlc_value_t, void *);
273

274 275
static void  blurayResetParser(demux_t *p_demux);

Petri Hintukainen's avatar
Petri Hintukainen committed
276 277
#define FROM_TICKS(a) ((a)*CLOCK_FREQ / INT64_C(90000))
#define TO_TICKS(a)   ((a)*INT64_C(90000)/CLOCK_FREQ)
278
#define CUR_LENGTH    p_sys->pp_title[p_demux->info.i_title]->i_length
279

280 281 282 283 284
/* */
static void FindMountPoint(char **file)
{
    char *device = *file;
#if defined (HAVE_MNTENT_H) && defined (HAVE_SYS_STAT_H)
285 286 287 288 289 290
    /* bd path may be a symlink (e.g. /dev/dvd -> /dev/sr0), so make sure
     * we look up the real device */
    char *bd_device = realpath(device, NULL);
    if (bd_device == NULL)
        return;

291
    struct stat st;
292
    if (lstat (bd_device, &st) == 0 && S_ISBLK (st.st_mode)) {
293 294 295 296 297 298 299 300 301 302 303 304 305
        FILE *mtab = setmntent ("/proc/self/mounts", "r");
        struct mntent *m, mbuf;
        char buf [8192];

        while ((m = getmntent_r (mtab, &mbuf, buf, sizeof(buf))) != NULL) {
            if (!strcmp (m->mnt_fsname, bd_device)) {
                free(device);
                *file = strdup(m->mnt_dir);
                break;
            }
        }
        endmntent (mtab);
    }
306 307
    free(bd_device);

308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324
#elif defined(__APPLE__)
    struct stat st;
    if (!stat (device, &st) && S_ISBLK (st.st_mode)) {
        int fs_count = getfsstat (NULL, 0, MNT_NOWAIT);
        if (fs_count > 0) {
            struct statfs mbuf[128];
            getfsstat (mbuf, fs_count * sizeof(mbuf[0]), MNT_NOWAIT);
            for (int i = 0; i < fs_count; ++i)
                if (!strcmp (mbuf[i].f_mntfromname, device)) {
                    free(device);
                    *file = strdup(mbuf[i].f_mntonname);
                    return;
                }
        }
    }
#else
# warning Disc device to mount point not implemented
325
    VLC_UNUSED( device );
326 327 328
#endif
}

329 330 331 332 333 334 335
static void blurayReleaseVout(demux_t *p_demux)
{
    demux_sys_t *p_sys = p_demux->p_sys;

    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);
336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355

        for (int i = 0; i < MAX_OVERLAY; i++) {
            bluray_overlay_t *p_ov = p_sys->p_overlays[i];
            if (p_ov) {
                vlc_mutex_lock(&p_ov->lock);
                if (p_ov->i_channel != -1) {
                    msg_Err(p_demux, "blurayReleaseVout: subpicture channel exists\n");
                    vout_FlushSubpictureChannel(p_sys->p_vout, p_ov->i_channel);
                }
                p_ov->i_channel = -1;
                p_ov->status = ToDisplay;
                vlc_mutex_unlock(&p_ov->lock);

                if (p_ov->p_updater) {
                    unref_subpicture_updater(p_ov->p_updater);
                    p_ov->p_updater = NULL;
                }
            }
        }

356 357 358 359 360
        vlc_object_release(p_sys->p_vout);
        p_sys->p_vout = NULL;
    }
}

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
/*****************************************************************************
 * BD-J background video
 *****************************************************************************/

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

    if (p_sys->p_dummy_video) {
        return;
    }

    msg_Info(p_demux, "Start background");

    /* */
    es_format_t fmt;
    es_format_Init( &fmt, VIDEO_ES, VLC_CODEC_I420 );
    video_format_Setup( &fmt.video, VLC_CODEC_I420,
                        1920, 1080, 1920, 1080, 1, 1);
    fmt.i_priority = ES_PRIORITY_SELECTABLE_MIN;
    fmt.i_id = 4115; /* 4113 = main video. 4114 = MVC. 4115 = unused. */
    fmt.i_group = 1;

    p_sys->p_dummy_video = es_out_Add(p_demux->out, &fmt);
    es_format_Clean(&fmt);

    if (!p_sys->p_dummy_video) {
      msg_Err(p_demux, "Error adding background ES");
      return;
    }

392 393
    block_t *p_block = block_Alloc(fmt.video.i_width * fmt.video.i_height *
                                   fmt.video.i_bits_per_pixel / 8);
394 395 396 397 398 399 400 401 402
    if (!p_block) {
        msg_Err(p_demux, "Error allocating block for background video");
        return;
    }

    // XXX TODO: what would be correct timestamp ???
    p_block->i_dts = p_block->i_pts = mdate() + CLOCK_FREQ/25;

    uint8_t *p = p_block->p_buffer;
403 404 405
    memset(p, 0, fmt.video.i_width * fmt.video.i_height);
    p += fmt.video.i_width * fmt.video.i_height;
    memset(p, 0x80, fmt.video.i_width * fmt.video.i_height / 2);
406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423

    es_out_Send(p_demux->out, p_sys->p_dummy_video, p_block);
}

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

    if (!p_sys->p_dummy_video) {
        return;
    }

    msg_Info(p_demux, "Stop background");

    es_out_Del(p_demux->out, p_sys->p_dummy_video);
    p_sys->p_dummy_video = NULL;
}

424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444
/*****************************************************************************
 * cache current playlist (title) information
 *****************************************************************************/

static void setTitleInfo(demux_sys_t *p_sys, BLURAY_TITLE_INFO *info)
{
    vlc_mutex_lock(&p_sys->pl_info_lock);

    if (p_sys->p_pl_info) {
        bd_free_title_info(p_sys->p_pl_info);
    }
    p_sys->p_pl_info   = info;
    p_sys->p_clip_info = NULL;

    if (p_sys->p_pl_info && p_sys->p_pl_info->clip_count) {
        p_sys->p_clip_info = &p_sys->p_pl_info->clips[0];
    }

    vlc_mutex_unlock(&p_sys->pl_info_lock);
}

445 446 447 448 449 450 451 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
/*****************************************************************************
 * create input attachment for thumbnail
 *****************************************************************************/

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

    if (!p_sys->p_meta)
        return;

#if BLURAY_VERSION >= BLURAY_VERSION_CODE(0,9,0)
    if (p_sys->p_meta->thumb_count > 0 && p_sys->p_meta->thumbnails) {
        int64_t size;
        void *data;
        if (bd_get_meta_file(p_sys->bluray, p_sys->p_meta->thumbnails[0].path, &data, &size) > 0) {
            char psz_name[64];
            input_attachment_t *p_attachment;

            snprintf(psz_name, sizeof(psz_name), "picture%d_%s", p_sys->i_attachments, p_sys->p_meta->thumbnails[0].path);

            p_attachment = vlc_input_attachment_New(psz_name, NULL, "Album art", data, size);
            if (p_attachment) {
                p_sys->i_cover_idx = p_sys->i_attachments;
                TAB_APPEND(p_sys->i_attachments, p_sys->attachments, p_attachment);
            }
        }
        free(data);
    }
#endif
}

477 478 479 480 481 482 483 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
/*****************************************************************************
 * stream input
 *****************************************************************************/

static int probeStream(demux_t *p_demux)
{
    /* input must be seekable */
    bool b_canseek = false;
    stream_Control( p_demux->s, STREAM_CAN_SEEK, &b_canseek );
    if (!b_canseek) {
        return VLC_EGENERIC;
    }

    /* first sector(s) should be filled with zeros */
    size_t i_peek;
    const uint8_t *p_peek;
    i_peek = stream_Peek( p_demux->s, &p_peek, 2048 );
    if( i_peek != 2048 ) {
        return VLC_EGENERIC;
    }
    while (i_peek > 0) {
        if (p_peek[ --i_peek ]) {
            return VLC_EGENERIC;
        }
    }

    return VLC_SUCCESS;
}

static int blurayReadBlock(void *object, void *buf, int lba, int num_blocks)
{
    demux_t *p_demux = (demux_t*)object;
    demux_sys_t *p_sys = p_demux->p_sys;
    int result = -1;

    assert(p_demux->s != NULL);

    vlc_mutex_lock(&p_sys->read_block_lock);

    if (stream_Seek( p_demux->s, lba * INT64_C(2048) ) == VLC_SUCCESS) {
        size_t  req = (size_t)2048 * num_blocks;
        ssize_t got;

        got = stream_Read( p_demux->s, buf, req);
        if (got < 0) {
            msg_Err(p_demux, "read from lba %d failed", lba);
        } else {
            result = got / 2048;
        }
    } else {
       msg_Err(p_demux, "seek to lba %d failed", lba);
    }

    vlc_mutex_unlock(&p_sys->read_block_lock);

    return result;
}

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
/*****************************************************************************
 * probing of local files
 *****************************************************************************/

/* Descriptor Tag (ECMA 167, 3/7.2) */
static int decode_descriptor_tag(const uint8_t *buf)
{
    uint16_t id;
    uint8_t  checksum = 0;
    int      i;

    id = buf[0] | (buf[1] << 8);

    /* calculate tag checksum */
    for (i = 0; i < 4; i++) {
        checksum = (uint8_t)(checksum + buf[i]);
    }
    for (i = 5; i < 16; i++) {
        checksum = (uint8_t)(checksum + buf[i]);
    }

    if (checksum != buf[4]) {
        return -1;
    }

    return id;
}

static int probeFile(const char *psz_name)
{
    struct stat stat_info;
    uint8_t peek[2048];
    unsigned i;
    int ret = VLC_EGENERIC;
    int fd;

    fd = vlc_open(psz_name, O_RDONLY | O_NONBLOCK);
    if (fd == -1) {
        return VLC_EGENERIC;
    }

    if (fstat(fd, &stat_info) == -1) {
        goto bailout;
    }
    if (!S_ISREG(stat_info.st_mode) && !S_ISBLK(stat_info.st_mode)) {
        goto bailout;
    }

    /* first sector should be filled with zeros */
    if (read(fd, peek, sizeof(peek)) != sizeof(peek)) {
        goto bailout;
    }
    for (i = 0; i < sizeof(peek); i++) {
        if (peek[ i ]) {
            goto bailout;
        }
    }

    /* Check AVDP tag checksum */
    if (lseek(fd, 256 * 2048, SEEK_SET) == -1 ||
        read(fd, peek, 16) != 16 ||
        decode_descriptor_tag(peek) != 2) {
        goto bailout;
    }

    ret = VLC_SUCCESS;

bailout:
    close(fd);
    return ret;
}

607 608 609
/*****************************************************************************
 * blurayOpen: module init function
 *****************************************************************************/
Rafaël Carré's avatar
Rafaël Carré committed
610
static int blurayOpen(vlc_object_t *object)
611
{
612 613
    demux_t *p_demux = (demux_t*)object;
    demux_sys_t *p_sys;
614 615
    bool forced;
    uint64_t i_init_pos = 0;
616

617
    const char *error_msg = NULL;
618
#define BLURAY_ERROR(s) do { error_msg = s; goto error; } while(0)
619

620 621 622 623 624 625 626 627 628 629 630
    forced = !strcasecmp(p_demux->psz_access, "bluray");

    if (p_demux->s) {
        if (p_demux->psz_access == NULL || !strcasecmp(p_demux->psz_access, "file")) {
            /* use access_demux for local files */
            return VLC_EGENERIC;
        }

        if (probeStream(p_demux) != VLC_SUCCESS) {
            return VLC_EGENERIC;
        }
631

Petri Hintukainen's avatar
Petri Hintukainen committed
632
    } else if (!forced) {
633 634 635 636 637 638 639
        if (!p_demux->psz_file) {
            return VLC_EGENERIC;
        }

        if (probeFile(p_demux->psz_file) != VLC_SUCCESS) {
            return VLC_EGENERIC;
        }
640 641
    }

642
    /* */
643
    p_demux->p_sys = p_sys = calloc(1, sizeof(*p_sys));
Rafaël Carré's avatar
Rafaël Carré committed
644
    if (unlikely(!p_sys))
645
        return VLC_ENOMEM;
Rafaël Carré's avatar
Rafaël Carré committed
646

647 648
    p_sys->i_audio_stream_idx = -1;
    p_sys->i_spu_stream_idx = -1;
649
    p_sys->i_video_stream = -1;
650
    p_sys->i_still_end_time = 0;
651 652 653 654 655

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

Rafaël Carré's avatar
Rafaël Carré committed
657
    TAB_INIT(p_sys->i_title, p_sys->pp_title);
658
    TAB_INIT(p_sys->i_attachments, p_sys->attachments);
659

660 661
    vlc_mutex_init(&p_sys->pl_info_lock);
    vlc_mutex_init(&p_sys->bdj_overlay_lock);
662 663
    vlc_mutex_init(&p_sys->read_block_lock); /* used during bd_open_stream() */

664 665
    var_AddCallback( p_demux->p_input, "intf-event", onIntfEvent, p_demux );

666 667 668 669 670 671 672 673 674 675
    /* Open BluRay */
    if (p_demux->s) {
        i_init_pos = stream_Tell(p_demux->s);

        p_sys->bluray = bd_init();
        if (!bd_open_stream(p_sys->bluray, p_demux, blurayReadBlock)) {
            bd_close(p_sys->bluray);
            p_sys->bluray = NULL;
        }
    } else {
Petri Hintukainen's avatar
Petri Hintukainen committed
676 677 678 679 680 681 682 683

        if (!p_demux->psz_file) {
            /* no path provided (bluray://). use default DVD device. */
            p_sys->psz_bd_path = var_InheritString(object, "dvd");
        } else {
            /* store current bd path */
            p_sys->psz_bd_path = strdup(p_demux->psz_file);
        }
684 685 686 687 688 689

        /* If we're passed a block device, try to convert it to the mount point. */
        FindMountPoint(&p_sys->psz_bd_path);

        p_sys->bluray = bd_open(p_sys->psz_bd_path, NULL);
    }
690
    if (!p_sys->bluray) {
691
        goto error;
692 693
    }

694 695
    /* Warning the user about AACS/BD+ */
    const BLURAY_DISC_INFO *disc_info = bd_get_disc_info(p_sys->bluray);
696 697

    /* Is it a bluray? */
698 699 700 701 702 703
    if (!disc_info->bluray_detected) {
        if (forced) {
            BLURAY_ERROR(_("Path doesn't appear to be a Blu-ray"));
        }
        goto error;
    }
704

705 706
    msg_Info(p_demux, "First play: %i, Top menu: %i\n"
                      "HDMV Titles: %i, BD-J Titles: %i, Other: %i",
707 708 709 710 711 712
             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) {
713
        msg_Dbg(p_demux, "Disc is using AACS");
714 715 716
        if (!disc_info->libaacs_detected)
            BLURAY_ERROR(_("This Blu-ray Disc needs a library for AACS decoding"
                      ", and your system does not have it."));
717
        if (!disc_info->aacs_handled) {
718 719
            if (disc_info->aacs_error_code) {
                switch (disc_info->aacs_error_code) {
720 721 722 723 724 725 726 727 728 729 730 731
                case BD_AACS_CORRUPTED_DISC:
                    BLURAY_ERROR(_("Blu-ray Disc is corrupted."));
                case BD_AACS_NO_CONFIG:
                    BLURAY_ERROR(_("Missing AACS configuration file!"));
                case BD_AACS_NO_PK:
                    BLURAY_ERROR(_("No valid processing key found in AACS config file."));
                case BD_AACS_NO_CERT:
                    BLURAY_ERROR(_("No valid host certificate found in AACS config file."));
                case BD_AACS_CERT_REVOKED:
                    BLURAY_ERROR(_("AACS Host certificate revoked."));
                case BD_AACS_MMC_FAILED:
                    BLURAY_ERROR(_("AACS MMC failed."));
732 733
                }
            }
734 735 736 737 738
        }
    }

    /* BD+ */
    if (disc_info->bdplus_detected) {
739
        msg_Dbg(p_demux, "Disc is using BD+");
740 741 742 743 744 745
        if (!disc_info->libbdplus_detected)
            BLURAY_ERROR(_("This Blu-ray Disc needs a library for BD+ decoding"
                      ", and your system does not have it."));
        if (!disc_info->bdplus_handled)
            BLURAY_ERROR(_("Your system BD+ decoding library does not work. "
                      "Missing configuration?"));
746 747
    }

748 749 750 751 752 753
    /* set player region code */
    char *psz_region = var_InheritString(p_demux, "bluray-region");
    unsigned int region = psz_region ? (psz_region[0] - 'A') : REGION_DEFAULT;
    free(psz_region);
    bd_set_player_setting(p_sys->bluray, BLURAY_PLAYER_SETTING_REGION_CODE, 1<<region);

754 755 756 757 758 759 760 761
    /* set preferred languages */
    const char *psz_code = DemuxGetLanguageCode( p_demux, "audio-language" );
    bd_set_player_setting_str(p_sys->bluray, BLURAY_PLAYER_SETTING_AUDIO_LANG, psz_code);
    psz_code = DemuxGetLanguageCode( p_demux, "sub-language" );
    bd_set_player_setting_str(p_sys->bluray, BLURAY_PLAYER_SETTING_PG_LANG,    psz_code);
    psz_code = DemuxGetLanguageCode( p_demux, "menu-language" );
    bd_set_player_setting_str(p_sys->bluray, BLURAY_PLAYER_SETTING_MENU_LANG,  psz_code);

Petri Hintukainen's avatar
Petri Hintukainen committed
762
    /* Get disc metadata */
763 764
    p_sys->p_meta = bd_get_meta(p_sys->bluray);
    if (!p_sys->p_meta)
Rafaël Carré's avatar
Rafaël Carré committed
765
        msg_Warn(p_demux, "Failed to get meta info.");
766

767 768 769
    p_sys->i_cover_idx = -1;
    attachThumbnail(p_demux);

770 771
    p_sys->b_menu = var_InheritBool(p_demux, "bluray-menu");

772 773 774 775 776 777 778 779 780 781 782 783
    /* Check BD-J capability */
    if (p_sys->b_menu && disc_info->bdj_detected && !disc_info->bdj_handled) {
        msg_Err(p_demux, "BD-J menus not supported. Playing without menus. "
                "BD-J support: %d, JVM found: %d, JVM usable: %d",
                disc_info->bdj_supported, disc_info->libjvm_detected, disc_info->bdj_handled);
        dialog_Fatal(p_demux, _("Java required"),
                     _("This Blu-ray disc needs Java for menus.%s\nDisc is played without menus."),
                     !disc_info->libjvm_detected ? _(" Java was not found from your system.") : "");
        p_sys->b_menu = false;
    }

    /* Get titles and chapters */
784
    blurayInitTitles(p_demux, disc_info->num_hdmv_titles + disc_info->num_bdj_titles + 1/*Top Menu*/ + 1/*First Play*/);
785

786 787 788 789 790
    /*
     * Initialize the event queue, so we can receive events in blurayDemux(Menu).
     */
    bd_get_event(p_sys->bluray, NULL);

791 792
    /* Registering overlay event handler */
    bd_register_overlay_proc(p_sys->bluray, p_demux, blurayOverlayProc);
793
    if (unlikely(!p_demux->p_input)) {
794 795 796
        msg_Err(p_demux, "Could not get parent input");
        goto error;
    }
797

Jean-Baptiste Kempf's avatar
Jean-Baptiste Kempf committed
798
    if (p_sys->b_menu) {
799

800
        /* Register ARGB overlay handler for BD-J */
801
        if (disc_info->num_bdj_titles)
802 803
            bd_register_argb_overlay_proc(p_sys->bluray, p_demux, blurayArgbOverlayProc, NULL);

804
        /* libbluray will start playback from "First-Title" title */
805 806 807
        if (bd_play(p_sys->bluray) == 0)
            BLURAY_ERROR(_("Failed to start bluray playback. Please try without menu support."));

Jean-Baptiste Kempf's avatar
Jean-Baptiste Kempf committed
808
    } else {
809
        /* set start title number */
810
        if (bluraySetTitle(p_demux, p_sys->i_longest_title) != VLC_SUCCESS) {
Rafaël Carré's avatar
Rafaël Carré committed
811
            msg_Err(p_demux, "Could not set the title %d", p_sys->i_longest_title);
812 813
            goto error;
        }
814 815
    }

816
    vlc_array_init(&p_sys->es);
Rafaël Carré's avatar
Rafaël Carré committed
817
    p_sys->p_out = esOutNew(p_demux);
Rafaël Carré's avatar
Rafaël Carré committed
818
    if (unlikely(p_sys->p_out == NULL))
819 820
        goto error;

Rafaël Carré's avatar
Rafaël Carré committed
821
    blurayResetParser(p_demux);
822 823
    if (!p_sys->p_parser) {
        msg_Err(p_demux, "Failed to create TS demuxer");
824
        goto error;
825 826 827 828
    }

    p_demux->pf_control = blurayControl;
    p_demux->pf_demux   = blurayDemux;
829 830

    return VLC_SUCCESS;
831 832 833

error:
    if (error_msg)
Christoph Miebach's avatar
Christoph Miebach committed
834
        dialog_Fatal(p_demux, _("Blu-ray error"), "%s", error_msg);
835
    blurayClose(object);
836 837 838 839 840 841 842 843 844

    if (p_demux->s != NULL) {
        /* restore stream position */
        if (stream_Seek(p_demux->s, i_init_pos) != VLC_SUCCESS) {
            msg_Err(p_demux, "Failed to seek back to stream start");
            return VLC_ETIMEOUT;
        }
    }

845
    return VLC_EGENERIC;
846
#undef BLURAY_ERROR
847 848 849 850 851 852
}


/*****************************************************************************
 * blurayClose: module destroy function
 *****************************************************************************/
Rafaël Carré's avatar
Rafaël Carré committed
853
static void blurayClose(vlc_object_t *object)
854
{
855 856 857
    demux_t *p_demux = (demux_t*)object;
    demux_sys_t *p_sys = p_demux->p_sys;

858 859
    var_DelCallback( p_demux->p_input, "intf-event", onIntfEvent, p_demux );

860 861
    setTitleInfo(p_sys, NULL);

862 863 864
    /*
     * Close libbluray first.
     * This will close all the overlays before we release p_vout
Rafaël Carré's avatar
Rafaël Carré committed
865
     * bd_close(NULL) can crash
866
     */
867 868 869
    if (p_sys->bluray) {
        bd_close(p_sys->bluray);
    }
870

871 872
    blurayReleaseVout(p_demux);

873 874
    if (p_sys->p_parser)
        stream_Delete(p_sys->p_parser);
875 876
    if (p_sys->p_out != NULL)
        es_out_Delete(p_sys->p_out);
Rafaël Carré's avatar
Rafaël Carré committed
877 878
    assert(vlc_array_count(&p_sys->es) == 0);
    vlc_array_clear(&p_sys->es);
879

880 881 882
    /* Titles */
    for (unsigned int i = 0; i < p_sys->i_title; i++)
        vlc_input_title_Delete(p_sys->pp_title[i]);
Rafaël Carré's avatar
Rafaël Carré committed
883
    TAB_CLEAN(p_sys->i_title, p_sys->pp_title);
884

885 886 887 888
    for (int i = 0; i < p_sys->i_attachments; i++)
      vlc_input_attachment_Delete(p_sys->attachments[i]);
    TAB_CLEAN(p_sys->i_attachments, p_sys->attachments);

889
    vlc_mutex_destroy(&p_sys->pl_info_lock);
890
    vlc_mutex_destroy(&p_sys->bdj_overlay_lock);
891
    vlc_mutex_destroy(&p_sys->read_block_lock);
892

893
    free(p_sys->psz_bd_path);
894 895 896
    free(p_sys);
}

897 898 899 900 901 902 903 904
/*****************************************************************************
 * Elementary streams handling
 *****************************************************************************/

struct es_out_sys_t {
    demux_t *p_demux;
};

905 906 907 908 909
typedef struct  fmt_es_pair {
    int         i_id;
    es_out_id_t *p_es;
}               fmt_es_pair_t;

Rafaël Carré's avatar
Rafaël Carré committed
910
static int  findEsPairIndex(demux_sys_t *p_sys, int i_id)
911
{
Rafaël Carré's avatar
Rafaël Carré committed
912 913
    for (int i = 0; i < vlc_array_count(&p_sys->es); ++i)
        if (((fmt_es_pair_t*)vlc_array_item_at_index(&p_sys->es, i))->i_id == i_id)
914
            return i;
Rafaël Carré's avatar
Rafaël Carré committed
915

916 917 918
    return -1;
}

Rafaël Carré's avatar
Rafaël Carré committed
919
static int  findEsPairIndexByEs(demux_sys_t *p_sys, es_out_id_t *p_es)
920
{
Rafaël Carré's avatar
Rafaël Carré committed
921 922
    for (int i = 0; i < vlc_array_count(&p_sys->es); ++i)
        if (((fmt_es_pair_t*)vlc_array_item_at_index(&p_sys->es, i))->p_es == p_es)
923
            return i;
Rafaël Carré's avatar
Rafaël Carré committed
924

925 926 927
    return -1;
}

928
static void setStreamLang(demux_sys_t *p_sys, es_format_t *p_fmt)
929
{
930 931 932 933 934 935 936 937 938 939 940 941 942 943 944
    const BLURAY_STREAM_INFO *p_streams;
    int i_stream_count = 0;

    vlc_mutex_lock(&p_sys->pl_info_lock);

    if (p_sys->p_clip_info) {
        if (p_fmt->i_cat == AUDIO_ES) {
            p_streams      = p_sys->p_clip_info->audio_streams;
            i_stream_count = p_sys->p_clip_info->audio_stream_count;
        } else if (p_fmt->i_cat == SPU_ES) {
            p_streams      = p_sys->p_clip_info->pg_streams;
            i_stream_count = p_sys->p_clip_info->pg_stream_count;
        }
    }

945 946 947
    for (int i = 0; i < i_stream_count; i++) {
        if (p_fmt->i_id == p_streams[i].pid) {
            free(p_fmt->psz_language);
948
            p_fmt->psz_language = strndup((const char *)p_streams[i].lang, 3);
949
            break;
950 951
        }
    }
952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976

    vlc_mutex_unlock(&p_sys->pl_info_lock);
}

static int blurayEsPid(demux_sys_t *p_sys, int es_type, int i_es_idx)
{
    int i_pid = -1;

    vlc_mutex_lock(&p_sys->pl_info_lock);

    if (p_sys->p_clip_info) {
        if (es_type == AUDIO_ES) {
            if (i_es_idx >= 0 && i_es_idx < p_sys->p_clip_info->pg_stream_count) {
                i_pid = p_sys->p_clip_info->audio_streams[i_es_idx].pid;
            }
        } else if (es_type == SPU_ES) {
            if (i_es_idx >= 0 && i_es_idx < p_sys->p_clip_info->pg_stream_count) {
                i_pid = p_sys->p_clip_info->pg_streams[i_es_idx].pid;
            }
        }
    }

    vlc_mutex_unlock(&p_sys->pl_info_lock);

    return i_pid;
977 978
}

Rafaël Carré's avatar
Rafaël Carré committed
979
static es_out_id_t *esOutAdd(es_out_t *p_out, const es_format_t *p_fmt)
980
{
981 982
    demux_t *p_demux = p_out->p_sys->p_demux;
    demux_sys_t *p_sys = p_demux->p_sys;
983
    es_format_t fmt;
984
    bool b_select = false;
985 986

    es_format_Copy(&fmt, p_fmt);
987

Rafaël Carré's avatar
Rafaël Carré committed
988
    switch (fmt.i_cat) {
989
    case VIDEO_ES:
Rafaël Carré's avatar
Rafaël Carré committed
990
        if (p_sys->i_video_stream != -1 && p_sys->i_video_stream != p_fmt->i_id)
991
            fmt.i_priority = ES_PRIORITY_NOT_SELECTABLE;
992 993
        break ;
    case AUDIO_ES:
994 995 996
        if (p_sys->i_audio_stream_idx != -1) {
            if (blurayEsPid(p_sys, AUDIO_ES, p_sys->i_audio_stream_idx) == p_fmt->i_id)
                b_select = true;
997
            fmt.i_priority = ES_PRIORITY_NOT_SELECTABLE;
998
        }
999
        setStreamLang(p_sys, &fmt);
1000 1001
        break ;
    case SPU_ES:
1002 1003 1004
        if (p_sys->i_spu_stream_idx != -1) {
            if (blurayEsPid(p_sys, SPU_ES, p_sys->i_spu_stream_idx) == p_fmt->i_id)
                b_select = true;
1005
            fmt.i_priority = ES_PRIORITY_NOT_SELECTABLE;
1006
        }
1007
        setStreamLang(p_sys, &fmt);
1008 1009 1010
        break ;
    }

1011
    es_out_id_t *p_es = es_out_Add(p_demux->out, &fmt);
Rafaël Carré's avatar
Rafaël Carré committed
1012
    if (p_fmt->i_id >= 0) {
1013
        /* Ensure we are not overriding anything */
1014
        int idx = findEsPairIndex(p_sys, p_fmt->i_id);
Rafaël Carré's avatar
Rafaël Carré committed
1015 1016 1017
        if (idx == -1) {
            fmt_es_pair_t *p_pair = malloc(sizeof(*p_pair));
            if (likely(p_pair != NULL)) {
1018 1019
                p_pair->i_id = p_fmt->i_id;
                p_pair->p_es = p_es;
1020
                msg_Info(p_demux, "Adding ES %d", p_fmt->i_id);
1021
                vlc_array_append(&p_sys->es, p_pair);
1022 1023 1024 1025 1026 1027 1028 1029

                if (b_select) {
                    if (fmt.i_cat == AUDIO_ES) {
                        var_SetInteger( p_demux->p_input, "audio-es", p_fmt->i_id );
                    } else if (fmt.i_cat == SPU_ES) {
                        var_SetInteger( p_demux->p_input, "spu-es", p_sys->b_spu_enable ? p_fmt->i_id : -1 );
                    }
                }
1030 1031 1032
            }
        }
    }
1033
    es_format_Clean(&fmt);
1034
    return p_es;
1035 1036
}

Rafaël Carré's avatar
Rafaël Carré committed
1037
static int esOutSend(es_out_t *p_out, es_out_id_t *p_es, block_t *p_block)
1038
{
Rafaël Carré's avatar
Rafaël Carré committed
1039
    return es_out_Send(p_out->p_sys->p_demux->out, p_es, p_block);
1040 1041
}

Rafaël Carré's avatar
Rafaël Carré committed
1042
static void esOutDel(es_out_t *p_out, es_out_id_t *p_es)
1043
{
Rafaël Carré's avatar
Rafaël Carré committed
1044 1045 1046
    int idx = findEsPairIndexByEs(p_out->p_sys->p_demux->p_sys, p_es);
    if (idx >= 0) {
        free(vlc_array_item_at_index(&p_out->p_sys->p_demux->p_sys->es, idx));
1047 1048
        vlc_array_remove(&p_out->p_sys->p_demux->p_sys->es, idx);
    }
Rafaël Carré's avatar
Rafaël Carré committed
1049
    es_out_Del(p_out->p_sys->p_demux->out, p_es);