dcp.cpp 34.4 KB
Newer Older
1 2 3 4 5 6 7
/*****************************************************************************
 * Copyright (C) 2012-2013 VLC authors and VideoLAN
 *
 * Authors:
 *          Nicolas Bertrand <nico@isf.cc>
 *          Simona-Marinela Prodea <simona dot marinela dot prodea at gmail dot com>
 *          Jean-Baptiste Kempf <jb@videolan.org>
Valentin Vetter's avatar
Valentin Vetter committed
8 9 10 11 12
 *          Guillaume Gonnaud
 *          Valentin Vetter <vvetter@outlook.com>
 *          Anthony Giniers
 *          Ludovic Hoareau
 *          Loukmane Dessai
13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42
 *          Pierre Villard <pierre dot villard dot fr at gmail dot com>
 *          Claire Etienne
 *          Aurélie Sbinné
 *          Samuel Kerjose
 *          Julien Puyobro
 *
 * 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
 * (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
 * GNU Lesser General Public License for more details.
 *
 * 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.
 *****************************************************************************/

/**
 * @file dcp.cpp
 * @brief DCP access-demux module for Digital Cinema Packages using asdcp library
 */

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

43 44
#define KDM_HELP_TEXT          N_("KDM file")
#define KDM_HELP_LONG_TEXT     N_("Path to Key Delivery Message XML file")
45 46 47 48 49 50 51 52 53

/* VLC core API headers */
#include <vlc_common.h>
#include <vlc_demux.h>
#include <vlc_plugin.h>
#include <vlc_xml.h>
#include <vlc_url.h>
#include <vlc_aout.h>

54 55 56 57
#ifdef _WIN32
# define KM_WIN32
#endif

58 59 60
/* ASDCP headers */
#include <AS_DCP.h>

61 62
#include <vector>

63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78
#include "dcpparser.h"

using namespace ASDCP;

#define FRAME_BUFFER_SIZE 1302083 /* maximum frame length, in bytes, after
                                     "Digital Cinema System Specification Version 1.2
                                     with Errata as of 30 August 2012" */

/* Forward declarations */
static int Open( vlc_object_t * );
static void Close( vlc_object_t * );

/* Module descriptor */
vlc_module_begin()
    set_shortname( N_( "DCP" ) )
    add_shortcut( "dcp" )
79
    add_loadfile( "kdm", "", KDM_HELP_TEXT, KDM_HELP_LONG_TEXT, false )
80 81 82 83 84 85 86 87 88 89 90 91 92 93
    set_description( N_( "Digital Cinema Package module" ) )
    set_capability( "access_demux", 0 )
    set_category( CAT_INPUT )
    set_subcategory( SUBCAT_INPUT_ACCESS )
    set_callbacks( Open, Close )
vlc_module_end()

//! Kind of MXF MEDIA TYPE
typedef enum MxfMedia_t {
    MXF_UNKNOWN = 0,
    MXF_PICTURE,
    MXF_AUDIO,
} MxfMedia_t;

94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110
union videoReader_t
{
   /* JPEG2000 essence type */
   ASDCP::JP2K::MXFReader *p_PicMXFReader;

   /* JPEG2000 stereoscopic essence type */
   ASDCP::JP2K::MXFSReader *p_PicMXFSReader;

   /* MPEG2 essence type */
   ASDCP::MPEG2::MXFReader *p_VideoMXFReader;
};

struct audioReader_t
{
    PCM::MXFReader *p_AudioMXFReader;
};

111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129
/* ASDCP library (version 1.10.48) can handle files having one of the following Essence Types, as defined in AS_DCP.h:
    ESS_UNKNOWN,     // the file is not a supported AS-DCP essence container
    ESS_MPEG2_VES,   // the file contains an MPEG video elementary stream
    ESS_JPEG_2000,   // the file contains one or more JPEG 2000 codestreams
    ESS_PCM_24b_48k, // the file contains one or more PCM audio pairs
    ESS_PCM_24b_96k, // the file contains one or more PCM audio pairs
    ESS_TIMED_TEXT,  // the file contains an XML timed text document and one or more resources
    ESS_JPEG_2000_S, // the file contains one or more JPEG 2000 codestream pairs (stereoscopic).

    The classes for handling these essence types are defined in AS_DCP.h and are different for each essence type, respectively. The demux_sys_t structure contains members for handling each of these essence types.
*/

class demux_sys_t
{
 public:
    /* ASDCP Picture Essence Type */
    EssenceType_t PictureEssType;

    /* ASDCP Video MXF Reader */
130
    std::vector<videoReader_t> v_videoReader;
131 132

    /* ASDCP Audio MXF Reader */
133
    std::vector<audioReader_t> v_audioReader;
134 135 136 137 138 139 140 141 142 143 144

    /* audio buffer size */
    uint32_t i_audio_buffer;

    /* elementary streams */
    es_out_id_t *p_video_es;
    es_out_id_t *p_audio_es;

    /* DCP object */
    dcp_t *p_dcp;

145
    /* current absolute frame number */
146 147 148
    uint32_t frame_no;

    /* frame rate */
Jean-Baptiste Kempf's avatar
Jean-Baptiste Kempf committed
149 150
    int frame_rate_num;
    int frame_rate_denom;
151 152 153 154

    /* total number of frames */
    uint32_t frames_total;

155
    /* current video reel */
Jean-Baptiste Kempf's avatar
Jean-Baptiste Kempf committed
156
    unsigned int i_video_reel;
157 158

    /* current audio reel */
Jean-Baptiste Kempf's avatar
Jean-Baptiste Kempf committed
159
    unsigned int i_audio_reel;
160

161 162 163 164 165 166 167 168
    uint8_t i_chans_to_reorder;            /* do we need channel reordering */
    uint8_t pi_chan_table[AOUT_CHAN_MAX];
    uint8_t i_channels;

    mtime_t i_pts;

    demux_sys_t():
        PictureEssType ( ESS_UNKNOWN ),
Jean-Baptiste Kempf's avatar
Jean-Baptiste Kempf committed
169 170
        v_videoReader(),
        v_audioReader(),
171 172 173
        p_video_es( NULL ),
        p_audio_es( NULL ),
        p_dcp( NULL ),
174 175 176
        frame_no( 0 ),
        frames_total( 0 ),
        i_video_reel( 0 ),
177 178 179
        i_audio_reel( 0 ),
        i_pts( 0 )
    {}
180 181 182 183 184 185 186 187

    ~demux_sys_t()
    {
        switch ( PictureEssType )
        {
            case ESS_UNKNOWN:
                break;
            case ESS_JPEG_2000:
188 189 190 191
                for ( unsigned int i = 0; i < v_videoReader.size(); i++ )
                {
                    delete v_videoReader[i].p_PicMXFReader;
                }
192 193
                break;
            case ESS_JPEG_2000_S:
194 195 196 197
                for ( unsigned int i = 0; i < v_videoReader.size(); i++ )
                {
                    delete v_videoReader[i].p_PicMXFSReader;
                }
198 199
                break;
            case ESS_MPEG2_VES:
200 201 202 203
                for ( unsigned int i = 0; i < v_videoReader.size(); i++ )
                {
                    delete v_videoReader[i].p_VideoMXFReader;
                }
204 205 206 207
                break;
            default:
                break;
        }
208 209 210 211 212 213

        for ( unsigned int i = 0; i < v_audioReader.size(); i++ )
        {
            delete v_audioReader[i].p_AudioMXFReader;
        }

214 215 216 217 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 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308
        delete p_dcp;
    }
};

/*TODO: basic correlation between SMPTE S428-3/S429-2
 * Real sound is more complex with case of left/right surround, ...
 * and hearing impaired/Narration channels */

/* 1 channel: mono */
static const uint32_t i_channels_1[] =
{ AOUT_CHAN_LEFT, 0 };

/* 2 channels: stereo */
static const uint32_t i_channels_2[]=
{ AOUT_CHAN_LEFT, AOUT_CHAN_RIGHT, 0 };

/* 4 channels */
static const uint32_t i_channels_4[] =
{   AOUT_CHAN_LEFT, AOUT_CHAN_RIGHT, AOUT_CHAN_CENTER,
    AOUT_CHAN_LFE, 0  };

/* 6 channels: 5.1 */
static const uint32_t i_channels_6[] =
{   AOUT_CHAN_LEFT, AOUT_CHAN_RIGHT,      AOUT_CHAN_CENTER,
    AOUT_CHAN_LFE,  AOUT_CHAN_REARLEFT,   AOUT_CHAN_REARRIGHT,
    0 };

/* 7 channels: 6.1 */
static const uint32_t i_channels_7[] =
{   AOUT_CHAN_LEFT,       AOUT_CHAN_RIGHT,    AOUT_CHAN_CENTER,
    AOUT_CHAN_LFE,        AOUT_CHAN_REARLEFT, AOUT_CHAN_REARRIGHT,
    AOUT_CHAN_REARCENTER, 0  };

/* 8 channels:  7.1 */
static const uint32_t i_channels_8[] =
{   AOUT_CHAN_LEFT,        AOUT_CHAN_RIGHT,      AOUT_CHAN_CENTER,
    AOUT_CHAN_LFE,         AOUT_CHAN_REARLEFT,   AOUT_CHAN_REARRIGHT,
    AOUT_CHAN_MIDDLELEFT,  AOUT_CHAN_MIDDLERIGHT, 0 };

/* 9 channels; 8.1 */
static const uint32_t i_channels_9[] =
{   AOUT_CHAN_LEFT,        AOUT_CHAN_RIGHT,      AOUT_CHAN_CENTER,
    AOUT_CHAN_LFE,         AOUT_CHAN_REARLEFT,   AOUT_CHAN_REARRIGHT,
    AOUT_CHAN_MIDDLELEFT,  AOUT_CHAN_MIDDLERIGHT, AOUT_CHAN_REARCENTER, 0 };

static const uint32_t *pi_channels_aout [] =
{   NULL,
    i_channels_1,
    i_channels_2,
    NULL,
    i_channels_4,
    NULL,
    i_channels_6,
    i_channels_7,
    i_channels_8,
    i_channels_9 };

static const unsigned i_channel_mask[] =
{    0,
    AOUT_CHAN_LEFT,
    AOUT_CHANS_STEREO,
    0,
    AOUT_CHANS_3_1,
    0,
    AOUT_CHANS_5_1,
    AOUT_CHANS_6_1_MIDDLE,
    AOUT_CHANS_7_1,
    AOUT_CHANS_8_1 };

/*****************************************************************************
 * Local prototypes
 *****************************************************************************/

static int Demux( demux_t * );
static int Control( demux_t *, int, va_list );

int dcpInit ( demux_t *p_demux );
int parseXML ( demux_t * p_demux );
static inline void fillVideoFmt(
        video_format_t * fmt, unsigned int width, unsigned int height,
        unsigned int frame_rate_num, unsigned int frame_rate_denom );
void CloseDcpAndMxf( demux_t *p_demux );



/*****************************************************************************
 * Open: module init function
 *****************************************************************************/
static int Open( vlc_object_t *obj )
{
    demux_t *p_demux = ( demux_t* ) obj;
    demux_sys_t *p_sys;
    es_format_t video_format, audio_format;
    int retval;

309
    if( !p_demux->psz_filepath )
310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331
        return VLC_EGENERIC;

    p_sys = new ( nothrow ) demux_sys_t();
    if( unlikely( p_sys == NULL ) ) {
        return VLC_ENOMEM;
    }
    p_demux->p_sys = p_sys;

    /* Allocate DCP object */
    dcp_t *p_dcp = new ( nothrow ) dcp_t;
    if( unlikely( p_dcp == NULL ) ) {
        delete  p_sys;
        return VLC_ENOMEM;
    }
    p_sys->p_dcp = p_dcp;


    /* handle the DCP directory, saving the paths for audio and video file, returning error if unsuccessful */
    if( ( retval = dcpInit( p_demux ) ) )
        goto error;

    /* Open video file */
332
    EssenceType_t essInter;
Jean-Baptiste Kempf's avatar
Jean-Baptiste Kempf committed
333
    for ( size_t i = 0; i < ( p_sys->p_dcp->video_reels.size() ); i++ )
334
    {
335 336 337 338 339 340 341 342 343 344 345 346 347 348
        EssenceType( p_sys->p_dcp->video_reels[i].filename.c_str(), essInter );
        if ( i == 0 )
        {
            p_sys->PictureEssType = essInter;
        }
        else
        {
            if ( essInter != p_sys->PictureEssType )
            {
                msg_Err( p_demux, "Integrity check failed : different essence containers" );
                retval = VLC_EGENERIC;
                goto error;
            }
        }
349

350 351 352 353 354 355
        switch( essInter )
        {
            case ESS_UNKNOWN:
                msg_Err( p_demux, "The file %s is not a supported AS_DCP essence container", p_sys->p_dcp->video_reels[i].filename.c_str() );
                retval = VLC_EGENERIC;
                goto error;
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
            case ESS_JPEG_2000:
            case ESS_JPEG_2000_S: {
                JP2K::PictureDescriptor PicDesc;
                if (p_sys->PictureEssType == ESS_JPEG_2000_S) {     /* 3D JPEG2000 */
                    JP2K::MXFSReader * p_PicMXFSReader = new ( nothrow ) JP2K::MXFSReader();

                    if( !p_PicMXFSReader) {
                        retval = VLC_ENOMEM;
                        goto error;
                    }
                    if( !ASDCP_SUCCESS( p_PicMXFSReader->OpenRead( p_sys->p_dcp->video_reels[i].filename.c_str() ) ) ) {
                        msg_Err( p_demux, "File %s could not be opened with ASDCP", p_sys->p_dcp->video_reels[i].filename.c_str() );
                        retval = VLC_EGENERIC;
                        delete p_PicMXFSReader;
                        goto error;
                    }

                    p_PicMXFSReader->FillPictureDescriptor( PicDesc );
                    videoReader_t videoReader;
                    videoReader.p_PicMXFSReader = p_PicMXFSReader;
                    p_sys->v_videoReader.push_back(videoReader);
                } else {                                            /* 2D JPEG2000 */
                    JP2K::MXFReader *p_PicMXFReader = new ( nothrow ) JP2K::MXFReader();
                    if( !p_PicMXFReader ) {
                        retval = VLC_ENOMEM;
                        goto error;
                    }
                    if( !ASDCP_SUCCESS( p_PicMXFReader->OpenRead( p_sys->p_dcp->video_reels[i].filename.c_str() ) ) ) {
                        msg_Err( p_demux, "File %s could not be opened with ASDCP",
                                        p_sys->p_dcp->video_reels[i].filename.c_str() );
                        retval = VLC_EGENERIC;
                        delete p_PicMXFReader;
                        goto error;
                    }

                    p_PicMXFReader->FillPictureDescriptor( PicDesc );
                    videoReader_t videoReader;
                    videoReader.p_PicMXFReader = p_PicMXFReader;
                    p_sys->v_videoReader.push_back(videoReader);
396
                }
397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414
                es_format_Init( &video_format, VIDEO_ES, VLC_CODEC_JPEG2000 );
                fillVideoFmt( &video_format.video, PicDesc.StoredWidth, PicDesc.StoredHeight,
                                PicDesc.EditRate.Numerator, PicDesc.EditRate.Denominator );


                if ( i > 0 ) {
                    if ( p_sys->frame_rate_num != PicDesc.EditRate.Numerator ||
                            p_sys->frame_rate_denom != PicDesc.EditRate.Denominator )
                    {
                        msg_Err( p_demux, "Integrity check failed : different frame rates" );
                        retval = VLC_EGENERIC;
                        goto error;
                    }
                }
                else
                {
                    p_sys->frame_rate_num   = PicDesc.EditRate.Numerator;
                    p_sys->frame_rate_denom = PicDesc.EditRate.Denominator;
415 416
                }

417 418 419 420 421 422 423 424 425 426 427 428 429 430
                p_sys->frames_total += p_sys->p_dcp->video_reels[i].i_duration;
                break;
            }
            case ESS_MPEG2_VES: {

                MPEG2::MXFReader *p_VideoMXFReader = new ( nothrow ) MPEG2::MXFReader();

                videoReader_t videoReader;
                videoReader.p_VideoMXFReader = p_VideoMXFReader;
                p_sys->v_videoReader.push_back(videoReader);

                MPEG2::VideoDescriptor  VideoDesc;

                if( !p_VideoMXFReader ) {
431 432 433
                    retval = VLC_ENOMEM;
                    goto error;
                }
434 435 436

                if( !ASDCP_SUCCESS( p_VideoMXFReader->OpenRead( p_sys->p_dcp->video_reels[i].filename.c_str() ) ) ) {
                    msg_Err( p_demux, "File %s could not be opened with ASDCP", p_sys->p_dcp->video_reels[i].filename.c_str() );
437 438 439 440
                    retval = VLC_EGENERIC;
                    goto error;
                }

441
                p_VideoMXFReader->FillVideoDescriptor( VideoDesc );
442

443 444 445
                es_format_Init( &video_format, VIDEO_ES, VLC_CODEC_MPGV );
                fillVideoFmt( &video_format.video, VideoDesc.StoredWidth, VideoDesc.StoredHeight,
                              VideoDesc.EditRate.Numerator, VideoDesc.EditRate.Denominator );
446 447


448 449 450 451 452 453 454 455 456 457 458 459 460 461
                if ( i > 0 ) {
                    if ( p_sys->frame_rate_num != VideoDesc.EditRate.Numerator ||
                            p_sys->frame_rate_denom != VideoDesc.EditRate.Denominator)
                    {
                        msg_Err( p_demux, "Integrity check failed : different frame rates" );
                        retval = VLC_EGENERIC;
                        goto error;
                    }
                }
                else
                {
                    p_sys->frame_rate_num   = VideoDesc.EditRate.Numerator;
                    p_sys->frame_rate_denom = VideoDesc.EditRate.Denominator;
                }
462

463 464 465 466 467
                p_sys->frames_total += p_sys->p_dcp->video_reels[i].i_duration;
                break;
            }
            default:
                msg_Err( p_demux, "Unrecognized video format" );
468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487
                retval = VLC_EGENERIC;
                goto error;
        }
    }

    if ( (p_sys->frame_rate_num == 0) || (p_sys->frame_rate_denom == 0) ) {
        msg_Err(p_demux, "Invalid frame rate (%i/%i)",
                p_sys->frame_rate_num, p_sys->frame_rate_denom);
        retval = VLC_EGENERIC;
        goto error;
    }

    if( ( p_sys->p_video_es = es_out_Add( p_demux->out, &video_format ) ) == NULL ) {
        msg_Err( p_demux, "Failed to add video es" );
        retval = VLC_EGENERIC;
        goto error;
    }

    /* Open audio file */
    EssenceType_t AudioEssType;
488
    EssenceType_t AudioEssTypeCompare;
489

490
    if( !p_sys->p_dcp->audio_reels.empty() )
491
    {
492
        EssenceType( p_sys->p_dcp->audio_reels[0].filename.c_str(), AudioEssType );
493

494 495
        if ( (AudioEssType == ESS_PCM_24b_48k) || (AudioEssType == ESS_PCM_24b_96k) ) {
            PCM::AudioDescriptor AudioDesc;
496

497
            for ( size_t i = 0; i < ( p_sys->p_dcp->audio_reels.size() ); i++)
498
            {
499
                if ( i != 0 )
500
                {
501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519
                    EssenceType( p_sys->p_dcp->audio_reels[i].filename.c_str(), AudioEssTypeCompare );
                    if ( AudioEssTypeCompare != AudioEssType )
                    {
                        msg_Err( p_demux, "Integrity check failed : different audio essence types in %s",
                        p_sys->p_dcp->audio_reels[i].filename.c_str() );
                        retval = VLC_EGENERIC;
                        goto error;
                    }
                }
                PCM::MXFReader *p_AudioMXFReader = new ( nothrow ) PCM::MXFReader();

                if( !p_AudioMXFReader ) {
                    retval = VLC_ENOMEM;
                    goto error;
                }

                if( !ASDCP_SUCCESS( p_AudioMXFReader->OpenRead( p_sys->p_dcp->audio_reels[i].filename.c_str() ) ) ) {
                    msg_Err( p_demux, "File %s could not be opened with ASDCP",
                                    p_sys->p_dcp->audio_reels[i].filename.c_str() );
520
                    retval = VLC_EGENERIC;
521
                    delete p_AudioMXFReader;
522 523 524
                    goto error;
                }

525 526 527 528 529 530 531 532 533 534 535 536 537
                p_AudioMXFReader->FillAudioDescriptor( AudioDesc );

                if (  (AudioDesc.ChannelCount >= sizeof(pi_channels_aout)/sizeof(uint32_t *))
                        || (pi_channels_aout[AudioDesc.ChannelCount] == NULL) )
                {
                    msg_Err(p_demux, " DCP module does not support %i channels", AudioDesc.ChannelCount);
                    retval = VLC_EGENERIC;
                    delete p_AudioMXFReader;
                    goto error;
                }
                audioReader_t audioReader;
                audioReader.p_AudioMXFReader = p_AudioMXFReader;
                p_sys->v_audioReader.push_back( audioReader );
538

539 540 541 542 543 544 545 546 547 548 549 550 551 552
            }
            es_format_Init( &audio_format, AUDIO_ES, VLC_CODEC_S24L );
            if( AudioDesc.AudioSamplingRate.Denominator != 0 )
                audio_format.audio.i_rate =
                    AudioDesc.AudioSamplingRate.Numerator
                    / AudioDesc.AudioSamplingRate.Denominator;
            else if ( AudioEssType == ESS_PCM_24b_96k )
                audio_format.audio.i_rate = 96000;
            else
                audio_format.audio.i_rate = 48000;

            p_sys->i_audio_buffer = PCM::CalcFrameBufferSize( AudioDesc );
            if (p_sys->i_audio_buffer == 0) {
                msg_Err( p_demux, "Failed to get audio buffer size" );
553 554 555 556
                retval = VLC_EGENERIC;
                goto error;
            }

557 558 559 560
            audio_format.audio.i_bitspersample = AudioDesc.QuantizationBits;
            audio_format.audio.i_blockalign    = AudioDesc.BlockAlign;
            audio_format.audio.i_channels      =
            p_sys->i_channels                  = AudioDesc.ChannelCount;
561

562 563 564 565 566 567 568
            /* Manage channel orders */
            p_sys->i_chans_to_reorder =  aout_CheckChannelReorder(
                    pi_channels_aout[AudioDesc.ChannelCount], NULL,
                    i_channel_mask[AudioDesc.ChannelCount],   p_sys->pi_chan_table );

            if( ( p_sys->p_audio_es = es_out_Add( p_demux->out, &audio_format ) ) == NULL ) {
                msg_Err( p_demux, "Failed to add audio es" );
569 570 571
                retval = VLC_EGENERIC;
                goto error;
            }
572 573 574
        } else {
            msg_Err( p_demux, "The file %s is not a supported AS_DCP essence container",
                    p_sys->p_dcp->audio_reels[0].filename.c_str() );
575 576
            retval = VLC_EGENERIC;
            goto error;
577 578 579 580
        }
    }
    p_demux->pf_demux = Demux;
    p_demux->pf_control = Control;
581
    p_sys->frame_no = p_sys->p_dcp->video_reels[0].i_entrypoint;
582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605

    return VLC_SUCCESS;
error:
    CloseDcpAndMxf( p_demux );
    return retval;
}


/*****************************************************************************
 * Close: module destroy function
 *****************************************************************************/
static inline void Close( vlc_object_t *obj )
{
    demux_t *p_demux = ( demux_t* ) obj;
    CloseDcpAndMxf( p_demux );
}



/*****************************************************************************
 * Demux: DCP Demuxing function
 *****************************************************************************/
static int Demux( demux_t *p_demux )
{
606
    demux_sys_t *p_sys = (demux_sys_t *)p_demux->p_sys;
607
    block_t *p_video_frame = NULL, *p_audio_frame = NULL;
608

609
    PCM::FrameBuffer   AudioFrameBuff( p_sys->i_audio_buffer);
610
    AESDecContext video_aes_ctx, audio_aes_ctx;
611

612 613 614 615 616 617 618 619 620 621 622 623 624 625
    /* swaping video reels */
    if  ( p_sys->frame_no == p_sys->p_dcp->video_reels[p_sys->i_video_reel].i_absolute_end )
    {
        if ( p_sys->i_video_reel + 1 == p_sys->v_videoReader.size() )
        {
            return 0;
        }
        else
        {
            p_sys->i_video_reel++;
        }
    }

    /* swaping audio reels */
626
    if  ( !p_sys->p_dcp->audio_reels.empty() && p_sys->frame_no == p_sys->p_dcp->audio_reels[p_sys->i_audio_reel].i_absolute_end )
627 628 629 630 631 632 633 634 635 636
     {
         if ( p_sys->i_audio_reel + 1 == p_sys->v_audioReader.size() )
         {
             return 0;//should never go there
         }
         else
         {
             p_sys->i_audio_reel++;
         }
     }
637 638

    /* video frame */
639 640

    /* initialize AES context, if reel is encrypted */
641 642
    if( p_sys->p_dcp->video_reels.size() > p_sys->i_video_reel &&
        p_sys->p_dcp->video_reels[p_sys->i_video_reel].p_key )
643 644 645 646 647 648 649 650
    {
        if( ! ASDCP_SUCCESS( video_aes_ctx.InitKey( p_sys->p_dcp->video_reels[p_sys->i_video_reel].p_key->getKey() ) ) )
        {
            msg_Err( p_demux, "ASDCP failed to initialize AES key" );
            goto error;
        }
    }

651 652 653 654 655
    switch( p_sys->PictureEssType )
    {
        case ESS_JPEG_2000:
        case ESS_JPEG_2000_S:{
            JP2K::FrameBuffer  PicFrameBuff(FRAME_BUFFER_SIZE);
656
            int nextFrame = p_sys->frame_no + p_sys->p_dcp->video_reels[p_sys->i_video_reel].i_correction;
657 658 659 660 661 662 663 664
            if ( ( p_video_frame = block_Alloc( FRAME_BUFFER_SIZE )) == NULL )
                goto error;

            if ( ! ASDCP_SUCCESS(
                    PicFrameBuff.SetData(p_video_frame->p_buffer, FRAME_BUFFER_SIZE)) )
                goto error_asdcp;
            if ( p_sys->PictureEssType == ESS_JPEG_2000_S ) {
                if ( ! ASDCP_SUCCESS(
665
                        p_sys->v_videoReader[p_sys->i_video_reel].p_PicMXFSReader->ReadFrame(nextFrame, JP2K::SP_LEFT, PicFrameBuff, &video_aes_ctx, 0)) ) {
666 667 668 669 670
                    PicFrameBuff.SetData(0,0);
                    goto error_asdcp;
                }
             } else {
                if ( ! ASDCP_SUCCESS(
671
                        p_sys->v_videoReader[p_sys->i_video_reel].p_PicMXFReader->ReadFrame(nextFrame, PicFrameBuff, &video_aes_ctx, 0)) ) {
672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688
                    PicFrameBuff.SetData(0,0);
                    goto error_asdcp;
                }
            }
            p_video_frame->i_buffer = PicFrameBuff.Size();
            break;
        }
        case ESS_MPEG2_VES: {
            MPEG2::FrameBuffer VideoFrameBuff(FRAME_BUFFER_SIZE);
            if ( ( p_video_frame = block_Alloc( FRAME_BUFFER_SIZE )) == NULL )
                goto error;

            if ( ! ASDCP_SUCCESS(
                    VideoFrameBuff.SetData(p_video_frame->p_buffer, FRAME_BUFFER_SIZE)) )
                goto error_asdcp;

            if ( ! ASDCP_SUCCESS(
689
                    p_sys->v_videoReader[p_sys->i_video_reel].p_VideoMXFReader->ReadFrame(p_sys->frame_no + p_sys->p_dcp->video_reels[p_sys->i_video_reel].i_correction, VideoFrameBuff, &video_aes_ctx, 0)) ) {
690 691 692 693 694 695 696 697 698 699 700 701 702 703 704
                VideoFrameBuff.SetData(0,0);
                goto error_asdcp;
            }

            p_video_frame->i_buffer = VideoFrameBuff.Size();
            break;
        }
        default:
            msg_Err( p_demux, "Unrecognized video format" );
            goto error;
    }

    p_video_frame->i_length = CLOCK_FREQ * p_sys->frame_rate_denom / p_sys->frame_rate_num;
    p_video_frame->i_pts = CLOCK_FREQ * p_sys->frame_no * p_sys->frame_rate_denom / p_sys->frame_rate_num;

705
    if( !p_sys->p_dcp->audio_reels.empty() )
706
    {
707 708
        /* audio frame */
        if ( ( p_audio_frame = block_Alloc( p_sys->i_audio_buffer )) == NULL ) {
709 710 711
            goto error;
        }

712
        /* initialize AES context, if reel is encrypted */
713 714
        if( p_sys->p_dcp->audio_reels.size() > p_sys->i_audio_reel &&
            p_sys->p_dcp->audio_reels[p_sys->i_audio_reel].p_key )
715 716 717 718 719 720 721
        {
            if( ! ASDCP_SUCCESS( audio_aes_ctx.InitKey( p_sys->p_dcp->audio_reels[p_sys->i_audio_reel].p_key->getKey() ) ) )
            {
                msg_Err( p_demux, "ASDCP failed to initialize AES key" );
                goto error;
            }
        }
722

723 724 725 726
        if ( ! ASDCP_SUCCESS(
                AudioFrameBuff.SetData(p_audio_frame->p_buffer, p_sys->i_audio_buffer)) ) {
            goto error_asdcp;
        }
727

728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745
        if ( ! ASDCP_SUCCESS(
                p_sys->v_audioReader[p_sys->i_audio_reel].p_AudioMXFReader->ReadFrame(p_sys->frame_no + p_sys->p_dcp->audio_reels[p_sys->i_audio_reel].i_correction, AudioFrameBuff, &audio_aes_ctx, 0)) ) {
            AudioFrameBuff.SetData(0,0);
            goto error_asdcp;
        }

        if( p_sys->i_chans_to_reorder )
            aout_ChannelReorder( p_audio_frame->p_buffer, p_audio_frame->i_buffer,
                    p_sys->i_channels,
                    p_sys->pi_chan_table, VLC_CODEC_S24L );

        p_audio_frame->i_buffer = AudioFrameBuff.Size();
        p_audio_frame->i_length = CLOCK_FREQ * p_sys->frame_rate_denom / p_sys->frame_rate_num;
        p_audio_frame->i_pts = CLOCK_FREQ * p_sys->frame_no * p_sys->frame_rate_denom / p_sys->frame_rate_num;
        /* Video is the main pts */
        if ( p_audio_frame->i_pts != p_video_frame->i_pts ) {
            msg_Err( p_demux, "Audio and video frame pts are not in sync" );
        }
746 747 748
    }

    p_sys->i_pts = p_video_frame->i_pts;
749
    es_out_SetPCR( p_demux->out, p_sys->i_pts );
750 751 752 753
    if(p_video_frame)
        es_out_Send( p_demux->out, p_sys->p_video_es, p_video_frame );
    if(p_audio_frame)
        es_out_Send( p_demux->out, p_sys->p_audio_es, p_audio_frame );
754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776

    p_sys->frame_no++;

    return 1;

error_asdcp:
    msg_Err( p_demux, "Couldn't read frame with ASDCP");
error:
    if (p_video_frame)
        block_Release(p_video_frame);
    if (p_audio_frame)
        block_Release(p_audio_frame);
    return -1;
}

/*****************************************************************************
 * Control: handle the controls
 *****************************************************************************/
static int Control( demux_t *p_demux, int query, va_list args )
{
    double f,*pf;
    bool *pb;
    int64_t *pi64, i64;
777
    demux_sys_t *p_sys = (demux_sys_t *)p_demux->p_sys;
778 779 780 781 782

    switch ( query )
    {
        case DEMUX_CAN_PAUSE:
        case DEMUX_CAN_CONTROL_PACE:
783
            pb = va_arg ( args, bool* );
784 785 786 787
            *pb = true;
            break;

        case DEMUX_CAN_SEEK:
788
            pb = va_arg( args, bool * );
789 790 791 792 793 794
            if( p_sys->PictureEssType != ESS_MPEG2_VES )
                *pb = true;
            else
                *pb = false;
            break;

Valentin Vetter's avatar
Valentin Vetter committed
795 796 797
        case DEMUX_SET_PAUSE_STATE:
            return VLC_SUCCESS;

798
        case DEMUX_GET_POSITION:
799
            pf = va_arg( args, double * );
800 801 802 803 804 805 806 807 808
            if( p_sys->frames_total != 0 )
                *pf = (double) p_sys->frame_no / (double) p_sys->frames_total;
            else {
                msg_Warn( p_demux, "Total number of frames is 0" );
                *pf = 0.0;
            }
            break;

        case DEMUX_SET_POSITION:
809
            f = va_arg( args, double );
810 811 812 813
            p_sys->frame_no = (int) ( f * p_sys->frames_total );
            break;

        case DEMUX_GET_LENGTH:
814
            pi64 = va_arg ( args, int64_t * );
815 816 817 818
            *pi64 =  ( p_sys->frames_total * p_sys->frame_rate_denom / p_sys->frame_rate_num ) * CLOCK_FREQ;
            break;

        case DEMUX_GET_TIME:
819
            pi64 = va_arg( args, int64_t * );
820 821 822 823
            *pi64 = p_sys->i_pts >= 0 ? p_sys->i_pts : 0;
            break;

        case DEMUX_SET_TIME:
824
            i64 = va_arg( args, int64_t );
825 826 827
            msg_Warn( p_demux, "DEMUX_SET_TIME"  );
            p_sys->frame_no = i64 * p_sys->frame_rate_num / ( CLOCK_FREQ * p_sys->frame_rate_denom );
            p_sys->i_pts= i64;
828
            es_out_SetPCR(p_demux->out, p_sys->i_pts);
829 830
            es_out_Control( p_demux->out, ES_OUT_SET_NEXT_DISPLAY_TIME, ( mtime_t ) i64 );
            break;
831
        case DEMUX_GET_PTS_DELAY:
832
            pi64 = va_arg( args, int64_t * );
833 834 835 836 837
            *pi64 =
                INT64_C(1000) * var_InheritInteger( p_demux, "file-caching" );
            return VLC_SUCCESS;


838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871
        default:
            msg_Warn( p_demux, "Unknown query %d in DCP Control", query );
            return VLC_EGENERIC;
    }

    return VLC_SUCCESS;
}


/*****************************************************************************
 * Low-level functions : string manipulation, free function, etc
 *****************************************************************************/
/**
 * Function to fill video_format_t fields for an elementary stream
 * @param fmt video format structure
 * @param width picture width
 * @param height picture height
 * @param frame_rate_num video frame rate numerator
 * @param frame_rate_denom video frame rate denominator
 */
static inline void fillVideoFmt( video_format_t * fmt, unsigned int width, unsigned int height, unsigned int frame_rate_num, unsigned int frame_rate_denom )
{
    fmt->i_width = width;
    fmt->i_height = height;
    /* As input are square pixels let VLC  or decoder fix SAR, origin,
     * and visible area */
    fmt->i_frame_rate = frame_rate_num;
    fmt->i_frame_rate_base = frame_rate_denom;
}

/**
 * Function to free memory in case of error or when closing the module
 * @param p_demux DCP access-demux
 */
872 873


874 875
void CloseDcpAndMxf( demux_t *p_demux )
{
876
    demux_sys_t *p_sys = (demux_sys_t *)p_demux->p_sys;
877 878 879 880 881 882
    /* close the files */
    switch( p_sys->PictureEssType )
    {
        case ESS_UNKNOWN:
            break;
        case ESS_JPEG_2000:
Jean-Baptiste Kempf's avatar
Jean-Baptiste Kempf committed
883
            for ( size_t i = 0; i < p_sys->v_videoReader.size(); i++ )
884 885 886 887
            {
                if( p_sys->v_videoReader[i].p_PicMXFReader )
                    p_sys->v_videoReader[i].p_PicMXFReader->Close();
            }
888 889
            break;
        case ESS_JPEG_2000_S:
Jean-Baptiste Kempf's avatar
Jean-Baptiste Kempf committed
890
            for ( size_t i = 0; i < p_sys->v_videoReader.size(); i++ )
891 892 893 894
            {
                if( p_sys->v_videoReader[i].p_PicMXFSReader )
                    p_sys->v_videoReader[i].p_PicMXFSReader->Close();
            }
895 896
            break;
        case ESS_MPEG2_VES:
Jean-Baptiste Kempf's avatar
Jean-Baptiste Kempf committed
897
            for ( size_t i = 0; i < p_sys->v_videoReader.size(); i++ )
898 899 900 901
            {
                if( p_sys->v_videoReader[i].p_VideoMXFReader )
                    p_sys->v_videoReader[i].p_VideoMXFReader->Close();
            }
902 903 904 905
            break;
        default:
            break;
    }
906

Jean-Baptiste Kempf's avatar
Jean-Baptiste Kempf committed
907
    for ( size_t i = 0; i < p_sys->v_audioReader.size(); i++ )
908 909 910 911
    {
        if( p_sys->v_audioReader[i].p_AudioMXFReader )
            p_sys->v_audioReader[i].p_AudioMXFReader->Close();
    }
912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929

    delete( p_demux->p_sys );
}


/*****************************************************************************
 * DCP init
 *****************************************************************************/

/**
 * Function to handle the operations with the DCP directory.
 * @param p_demux Demux pointer.
 * @return Integer according to the success or not of the process.
 */
int dcpInit ( demux_t *p_demux )
{
    int retval;

930
    demux_sys_t *p_sys = (demux_sys_t *)p_demux->p_sys;
931 932
    dcp_t *p_dcp = p_sys->p_dcp;

933
    p_dcp->path = p_demux->psz_filepath;
934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956
    /* Add a '/' in end of path if needed */
    if ( *(p_dcp->path).rbegin() != '/')
        p_dcp->path.append( "/" );

    /* Parsing XML files to get audio and video files */
    msg_Dbg( p_demux, "parsing XML files..." );
    if( ( retval = parseXML( p_demux ) ) )
        return retval;

    msg_Dbg(p_demux, "parsing XML files done");

    return VLC_SUCCESS;
}


/*****************************************************************************
 * functions for XML parsing
 *****************************************************************************/

/**
 * Function to retrieve the path to the ASSETMAP file.
 * @param p_demux DCP access_demux.
 */
957
static std::string assetmapPath( demux_t * p_demux )
958 959 960
{
    DIR *dir = NULL;
    struct dirent *ent = NULL;
961 962
    demux_sys_t *p_sys = (demux_sys_t *)p_demux->p_sys;
    dcp_t *p_dcp = p_sys->p_dcp;
963
    std::string result;
964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997

    if( ( dir = opendir (p_dcp->path.c_str() ) ) != NULL )
    {
        /* print all the files and directories within directory */
        while( ( ent = readdir ( dir ) ) != NULL )
        {
            if( strcasecmp( "assetmap", ent->d_name ) == 0 || strcasecmp( "assetmap.xml", ent->d_name ) == 0 )
            {
                /* copy of "path" in "res" */
                result = p_dcp->path;
                result.append( ent->d_name );
                break;
            }
        }
        closedir( dir );
    }
    else
        msg_Err( p_demux, "Could not open the directory: %s", p_dcp->path.c_str() );

    /* if no assetmap file */
    if( result.empty() )
        msg_Err( p_demux, "No ASSETMAP found in the directory: %s", p_dcp->path.c_str() );

    return result;
}


/**
 * Function which parses XML files in DCP directory in order to get video and audio files
 * @param p_demux Demux pointer.
 * @return Integer according to the success or not of the operation
 */
int parseXML ( demux_t * p_demux )
{
998
    demux_sys_t *p_sys = (demux_sys_t *)p_demux->p_sys;
999 1000
    int retval;

1001
    std::string assetmap_path = assetmapPath( p_demux );
1002 1003 1004 1005 1006 1007
    /* We get the ASSETMAP file path */
    if( assetmap_path.empty() )
        return VLC_EGENERIC;

    /* We parse the ASSETMAP File in order to get CPL File path, PKL File path
     and to store UID/Path of all files in DCP directory (except ASSETMAP file) */
1008
    AssetMap *assetmap = new (nothrow) AssetMap( p_demux, assetmap_path, p_sys->p_dcp );
1009 1010 1011 1012 1013 1014
    if( ( retval = assetmap->Parse() ) )
        return retval;

    delete assetmap;
    return VLC_SUCCESS; /* TODO : perform checking on XML parsing */
}