mp4.c 171 KB
Newer Older
1 2 3
/*****************************************************************************
 * mp4.c : MP4 file input module for vlc
 *****************************************************************************
Jean-Baptiste Kempf's avatar
LGPL  
Jean-Baptiste Kempf committed
4
 * Copyright (C) 2001-2004, 2010 VLC authors and VideoLAN
5
 *
6
 * Authors: Laurent Aimar <fenrir@via.ecp.fr>
7
 *
Jean-Baptiste Kempf's avatar
LGPL  
Jean-Baptiste Kempf committed
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
 * (at your option) any later version.
12
 *
13 14
 * 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
15 16
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
 * GNU Lesser General Public License for more details.
17
 *
Jean-Baptiste Kempf's avatar
LGPL  
Jean-Baptiste Kempf committed
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
#ifdef HAVE_CONFIG_H
# include "config.h"
#endif
25 26 27 28

/*****************************************************************************
 * Preamble
 *****************************************************************************/
29 30
#include "mp4.h"

Clément Stenac's avatar
Clément Stenac committed
31
#include <vlc_demux.h>
32
#include <vlc_charset.h>                           /* EnsureUTF8 */
33
#include <vlc_input.h>
34
#include <vlc_aout.h>
35
#include <vlc_plugin.h>
36
#include <vlc_dialog.h>
37
#include <assert.h>
38
#include <limits.h>
39
#include "../codec/cc.h"
40

41 42 43
/*****************************************************************************
 * Module descriptor
 *****************************************************************************/
44 45
static int  Open ( vlc_object_t * );
static void Close( vlc_object_t * );
46

47 48 49 50 51
#define CFG_PREFIX "mp4-"

#define MP4_M4A_TEXT     "M4A audio only"
#define MP4_M4A_LONGTEXT "Ignore non audio tracks from iTunes audio files"

52 53 54 55
vlc_module_begin ()
    set_category( CAT_INPUT )
    set_subcategory( SUBCAT_INPUT_DEMUX )
    set_description( N_("MP4 stream demuxer") )
56
    set_shortname( N_("MP4") )
57
    set_capability( "demux", 240 )
58
    set_callbacks( Open, Close )
59 60 61

    add_category_hint("Hacks", NULL, true)
    add_bool( CFG_PREFIX"m4a-audioonly", false, MP4_M4A_TEXT, MP4_M4A_LONGTEXT, true )
62
vlc_module_end ()
63

64 65 66
/*****************************************************************************
 * Local prototypes
 *****************************************************************************/
67
static int   Demux   ( demux_t * );
68
static int   DemuxRef( demux_t *p_demux ){ (void)p_demux; return 0;}
69
static int   DemuxFrag( demux_t * );
70
static int   Control ( demux_t *, int, va_list );
71

72 73 74 75 76 77
struct demux_sys_t
{
    MP4_Box_t    *p_root;      /* container for the whole file */

    mtime_t      i_pcr;

78 79 80
    uint64_t     i_moov_duration;
    uint64_t     i_duration;           /* Declared fragmented duration */
    uint64_t     i_cumulated_duration; /* Same as above, but not from probing */
81 82
    uint64_t     i_time;         /* time position of the presentation
                                  * in movie timescale */
83
    uint32_t     i_timescale;    /* movie time scale */
84 85
    unsigned int i_tracks;       /* number of tracks */
    mp4_track_t  *track;         /* array of track */
86
    float        f_fps;          /* number of frame per seconds */
87

88
    bool         b_fragmented;   /* fMP4 */
89 90
    bool         b_seekable;
    bool         b_fastseekable;
91
    bool         b_error;        /* unrecoverable */
92

93 94
    bool            b_index_probed;     /* mFra sync points index */
    bool            b_fragments_probed; /* moof segments index created */
95

96
    MP4_Box_t *p_moov;
97

98 99 100
    struct
    {
        uint32_t        i_current_box_type;
101
        MP4_Box_t      *p_fragment_atom;
102
        uint64_t        i_post_mdat_offset;
103
        uint32_t        i_lastseqnumber;
104 105
    } context;

106 107
    /* */
    MP4_Box_t    *p_tref_chap;
108 109 110

    /* */
    input_title_t *p_title;
111
    vlc_meta_t    *p_meta;
112 113 114 115 116

    /* ASF in MP4 */
    asf_packet_sys_t asfpacketsys;
    uint64_t i_preroll;         /* foobar */
    int64_t  i_preroll_start;
117 118 119 120 121

    struct
    {
        int es_cat_filters;
    } hacks;
122 123

    mp4_fragments_index_t *p_fragsindex;
124 125
};

126
#define DEMUX_INCREMENT (CLOCK_FREQ / 4) /* How far the pcr will go, each round */
127 128
#define DEMUX_TRACK_MAX_PRELOAD (CLOCK_FREQ * 15) /* maximum preloading, to deal with interleaving */

129 130
#define VLC_DEMUXER_EOS (VLC_DEMUXER_EGENERIC - 1)

131 132 133 134 135 136 137 138 139
const uint32_t rgi_pict_atoms[2] = { ATOM_PICT, ATOM_pict };
const char *psz_meta_roots[] = { "/moov/udta/meta/ilst",
                                 "/moov/meta/ilst",
                                 "/moov/udta/meta",
                                 "/moov/udta",
                                 "/meta/ilst",
                                 "/udta",
                                 NULL };

140
/*****************************************************************************
141
 * Declaration of local function
142
 *****************************************************************************/
143 144 145
static void MP4_TrackSetup( demux_t *, mp4_track_t *, MP4_Box_t  *, bool, bool );
static void MP4_TrackInit( mp4_track_t * );
static void MP4_TrackClean( es_out_t *, mp4_track_t * );
146

147 148
static void MP4_Block_Send( demux_t *, mp4_track_t *, block_t * );

149
static void MP4_TrackSelect  ( demux_t *, mp4_track_t *, bool );
Laurent Aimar's avatar
Laurent Aimar committed
150
static int  MP4_TrackSeek   ( demux_t *, mp4_track_t *, mtime_t );
151

Laurent Aimar's avatar
Laurent Aimar committed
152
static uint64_t MP4_TrackGetPos    ( mp4_track_t * );
153
static uint32_t MP4_TrackGetReadSize( mp4_track_t *, uint32_t * );
154
static int      MP4_TrackNextSample( demux_t *, mp4_track_t *, uint32_t );
Laurent Aimar's avatar
Laurent Aimar committed
155
static void     MP4_TrackSetELST( demux_t *, mp4_track_t *, int64_t );
Laurent Aimar's avatar
Laurent Aimar committed
156

157
static void     MP4_UpdateSeekpoint( demux_t *, int64_t );
158

159
static MP4_Box_t * MP4_GetTrexByTrackID( MP4_Box_t *p_moov, const uint32_t i_id );
160
static void MP4_GetDefaultSizeAndDuration( MP4_Box_t *p_moov,
161 162 163
                                           const MP4_Box_data_tfhd_t *p_tfhd_data,
                                           uint32_t *pi_default_size,
                                           uint32_t *pi_default_duration );
164

165 166
static stime_t GetMoovTrackDuration( demux_sys_t *p_sys, unsigned i_track_ID );

167
static int  ProbeFragments( demux_t *p_demux, bool b_force, bool *pb_fragmented );
168 169
static int  ProbeIndex( demux_t *p_demux );

170 171 172
static int FragCreateTrunIndex( demux_t *, MP4_Box_t *, MP4_Box_t *, stime_t, bool );

static int FragGetMoofBySidxIndex( demux_t *p_demux, mtime_t i_target_time,
173
                                   uint64_t *pi_moof_pos, mtime_t *pi_sampletime );
174
static int FragGetMoofByTfraIndex( demux_t *p_demux, const mtime_t i_target_time, unsigned i_track_ID,
175
                                   uint64_t *pi_moof_pos, mtime_t *pi_sampletime );
176
static void FragResetContext( demux_sys_t * );
177

178 179 180 181 182
/* ASF Handlers */
static asf_track_info_t * MP4ASF_GetTrackInfo( asf_packet_sys_t *p_packetsys, uint8_t i_stream_number );
static void MP4ASF_Send(asf_packet_sys_t *p_packetsys, uint8_t i_stream_number, block_t **pp_frame);
static void MP4ASF_ResetFrames( demux_sys_t *p_sys );

183 184 185 186
/* RTP Hint track */
static block_t * MP4_RTPHint_Convert( demux_t *p_demux, block_t *p_block, vlc_fourcc_t i_codec );
static block_t * MP4_RTPHintToFrame( demux_t *p_demux, block_t *p_block, uint32_t packetcount );

187 188
static int MP4_LoadMeta( demux_sys_t *p_sys, vlc_meta_t *p_meta );

189 190
/* Helpers */

191 192 193 194 195 196 197 198 199 200 201 202 203 204
static int64_t MP4_rescale( int64_t i_value, uint32_t i_timescale, uint32_t i_newscale )
{
    if( i_timescale == i_newscale )
        return i_value;

    if( i_value <= INT64_MAX / i_newscale )
        return i_value * i_newscale / i_timescale;

    /* overflow */
    int64_t q = i_value / i_timescale;
    int64_t r = i_value % i_timescale;
    return q * i_newscale + r * i_newscale / i_timescale;
}

205 206
static uint32_t stream_ReadU32( stream_t *s, void *p_read, uint32_t i_toread )
{
207
    ssize_t i_return = 0;
208 209
    if ( i_toread > INT32_MAX )
    {
210
        i_return = vlc_stream_Read( s, p_read, (size_t) INT32_MAX );
211 212 213 214 215
        if ( i_return < INT32_MAX )
            return i_return;
        else
            i_toread -= INT32_MAX;
    }
216
    i_return += vlc_stream_Read( s, (uint8_t *)p_read + i_return, (size_t) i_toread );
217 218 219
    return i_return;
}

220 221
static MP4_Box_t * MP4_GetTrexByTrackID( MP4_Box_t *p_moov, const uint32_t i_id )
{
222 223
    if(!p_moov)
        return NULL;
224 225 226
    MP4_Box_t *p_trex = MP4_BoxGet( p_moov, "mvex/trex" );
    while( p_trex )
    {
227 228
        if ( p_trex->i_type == ATOM_trex &&
             BOXDATA(p_trex) && BOXDATA(p_trex)->i_track_ID == i_id )
229 230 231 232 233 234 235
                break;
        else
            p_trex = p_trex->p_next;
    }
    return p_trex;
}

236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252
/**
 * Return the track identified by tid
 */
static mp4_track_t *MP4_GetTrackByTrackID( demux_t *p_demux, const uint32_t tid )
{
    demux_sys_t *p_sys = p_demux->p_sys;

    mp4_track_t *ret = NULL;
    for( unsigned i = 0; i < p_sys->i_tracks; i++ )
    {
        ret = &p_sys->track[i];
        if( ret->i_track_ID == tid )
            return ret;
    }
    return NULL;
}

253 254 255 256 257 258 259
static MP4_Box_t * MP4_GetTrakByTrackID( MP4_Box_t *p_moov, const uint32_t i_id )
{
    MP4_Box_t *p_trak = MP4_BoxGet( p_moov, "trak" );
    MP4_Box_t *p_tkhd;
    while( p_trak )
    {
        if( p_trak->i_type == ATOM_trak &&
260
            (p_tkhd = MP4_BoxGet( p_trak, "tkhd" )) && BOXDATA(p_tkhd) &&
261 262 263 264 265 266 267 268
            BOXDATA(p_tkhd)->i_track_ID == i_id )
                break;
        else
            p_trak = p_trak->p_next;
    }
    return p_trak;
}

269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284
static MP4_Box_t * MP4_GetTrafByTrackID( MP4_Box_t *p_moof, const uint32_t i_id )
{
    MP4_Box_t *p_traf = MP4_BoxGet( p_moof, "traf" );
    MP4_Box_t *p_tfhd;
    while( p_traf )
    {
        if( p_traf->i_type == ATOM_traf &&
            (p_tfhd = MP4_BoxGet( p_traf, "tfhd" )) && BOXDATA(p_tfhd) &&
            BOXDATA(p_tfhd)->i_track_ID == i_id )
                break;
        else
            p_traf = p_traf->p_next;
    }
    return p_traf;
}

285 286 287 288 289 290 291 292 293 294
static es_out_id_t * MP4_AddTrackES( es_out_t *out, mp4_track_t *p_track )
{
    es_out_id_t *p_es = es_out_Add( out, &p_track->fmt );
    /* Force SPU which isn't selected/defaulted */
    if( p_track->fmt.i_cat == SPU_ES && p_es && p_track->b_forced_spu )
        es_out_Control( out, ES_OUT_SET_ES_DEFAULT, p_es );

    return p_es;
}

295
/* Return time in microsecond of a track */
Laurent Aimar's avatar
Laurent Aimar committed
296
static inline int64_t MP4_TrackGetDTS( demux_t *p_demux, mp4_track_t *p_track )
Laurent Aimar's avatar
Laurent Aimar committed
297
{
298
    demux_sys_t *p_sys = p_demux->p_sys;
299
    const mp4_chunk_t *p_chunk = &p_track->chunk[p_track->i_chunk];
300 301

    unsigned int i_index = 0;
302 303
    unsigned int i_sample = p_track->i_sample - p_chunk->i_sample_first;
    int64_t i_dts = p_chunk->i_first_dts;
Laurent Aimar's avatar
Laurent Aimar committed
304

305
    while( i_sample > 0 && i_index < p_chunk->i_entries_dts )
Laurent Aimar's avatar
Laurent Aimar committed
306
    {
307
        if( i_sample > p_chunk->p_sample_count_dts[i_index] )
Laurent Aimar's avatar
Laurent Aimar committed
308
        {
309 310 311
            i_dts += p_chunk->p_sample_count_dts[i_index] *
                p_chunk->p_sample_delta_dts[i_index];
            i_sample -= p_chunk->p_sample_count_dts[i_index];
Laurent Aimar's avatar
Laurent Aimar committed
312 313 314 315
            i_index++;
        }
        else
        {
316
            i_dts += i_sample * p_chunk->p_sample_delta_dts[i_index];
Laurent Aimar's avatar
Laurent Aimar committed
317 318 319 320
            break;
        }
    }

321 322 323
    /* now handle elst */
    if( p_track->p_elst )
    {
324
        MP4_Box_data_elst_t *elst = p_track->BOXDATA(p_elst);
325 326 327 328 329 330 331 332 333 334

        /* convert to offset */
        if( ( elst->i_media_rate_integer[p_track->i_elst] > 0 ||
              elst->i_media_rate_fraction[p_track->i_elst] > 0 ) &&
            elst->i_media_time[p_track->i_elst] > 0 )
        {
            i_dts -= elst->i_media_time[p_track->i_elst];
        }

        /* add i_elst_time */
335
        i_dts += MP4_rescale( p_track->i_elst_time, p_sys->i_timescale, p_track->i_timescale );
336 337 338 339

        if( i_dts < 0 ) i_dts = 0;
    }

340
    return MP4_rescale( i_dts, p_track->i_timescale, CLOCK_FREQ );
Laurent Aimar's avatar
Laurent Aimar committed
341
}
342

343 344
static inline bool MP4_TrackGetPTSDelta( demux_t *p_demux, mp4_track_t *p_track,
                                         int64_t *pi_delta )
Laurent Aimar's avatar
Laurent Aimar committed
345
{
346
    VLC_UNUSED( p_demux );
347
    mp4_chunk_t *ck = &p_track->chunk[p_track->i_chunk];
348

Laurent Aimar's avatar
Laurent Aimar committed
349 350 351 352
    unsigned int i_index = 0;
    unsigned int i_sample = p_track->i_sample - ck->i_sample_first;

    if( ck->p_sample_count_pts == NULL || ck->p_sample_offset_pts == NULL )
353
        return false;
Laurent Aimar's avatar
Laurent Aimar committed
354

355
    for( i_index = 0; i_index < ck->i_entries_pts ; i_index++ )
Laurent Aimar's avatar
Laurent Aimar committed
356 357
    {
        if( i_sample < ck->p_sample_count_pts[i_index] )
358
        {
359 360
            *pi_delta = MP4_rescale( ck->p_sample_offset_pts[i_index],
                                     p_track->i_timescale, CLOCK_FREQ );
361 362
            return true;
        }
Laurent Aimar's avatar
Laurent Aimar committed
363 364 365

        i_sample -= ck->p_sample_count_pts[i_index];
    }
366
    return false;
Laurent Aimar's avatar
Laurent Aimar committed
367 368
}

Laurent Aimar's avatar
Laurent Aimar committed
369 370
static inline int64_t MP4_GetMoviePTS(demux_sys_t *p_sys )
{
371
    return MP4_rescale( p_sys->i_time, p_sys->i_timescale, CLOCK_FREQ );
Laurent Aimar's avatar
Laurent Aimar committed
372
}
373

374 375
static void LoadChapter( demux_t  *p_demux );

376
static int LoadInitFrag( demux_t *p_demux )
377 378 379
{
    demux_sys_t *p_sys = p_demux->p_sys;

380 381
    /* Load all boxes ( except raw data ) */
    if( ( p_sys->p_root = MP4_BoxGetRoot( p_demux->s ) ) == NULL )
382
    {
383
        goto LoadInitFragError;
384
    }
385

386 387 388 389 390 391 392
    return VLC_SUCCESS;

LoadInitFragError:
    msg_Warn( p_demux, "MP4 plugin discarded (not a valid initialization chunk)" );
    return VLC_EGENERIC;
}

393
static int CreateTracks( demux_t *p_demux, unsigned i_tracks )
394 395 396
{
    demux_sys_t *p_sys = p_demux->p_sys;

397 398 399 400
    if( SIZE_MAX / i_tracks < sizeof(mp4_track_t) )
        return VLC_EGENERIC;

    p_sys->track = malloc( i_tracks * sizeof(mp4_track_t)  );
401
    if( p_sys->track == NULL )
402 403
        return VLC_ENOMEM;
    p_sys->i_tracks = i_tracks;
404

405 406 407
    for( unsigned i=0; i<i_tracks; i++ )
        MP4_TrackInit( &p_sys->track[i] );

408 409 410
    return VLC_SUCCESS;
}

411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442
static block_t * MP4_WebVTT_Convert( demux_t *p_demux, block_t * p_block )
{
    stream_t *p_stream =
            vlc_stream_MemoryNew( p_demux, p_block->p_buffer,
                                  p_block->i_buffer, true );
    if( p_stream )
    {
        MP4_Box_t *p_vroot = MP4_BoxNew(ATOM_wvtt);
        if( p_vroot )
        {
            p_vroot->i_size = p_block->i_buffer;
            if ( MP4_ReadBoxContainerChildren( p_stream, p_vroot, NULL ) == 1 )
            {
                MP4_Box_t *p_payl = MP4_BoxGet( p_vroot, "vttc/payl" );
                if( p_payl && p_payl->i_size >= 9 )
                {
                    p_block->p_buffer += p_payl->i_pos + 8;
                    p_block->i_buffer = p_payl->i_size - 8;
                    p_block->p_buffer[p_block->i_buffer - 1] = '\0';
                }
                else p_block->i_buffer = 0;
#ifndef NDEBUG
                MP4_BoxDumpStructure(p_stream, p_vroot);
#endif
            }
            MP4_BoxFree(p_vroot);
        }
        vlc_stream_Delete( p_stream );
     }
    return p_block;
}

443 444 445 446
static block_t * MP4_EIA608_Convert( block_t * p_block )
{
    /* Rebuild codec data from encap */
    size_t i_copied = 0;
447
    size_t i_remaining = __MIN(p_block->i_buffer, INT64_MAX / 3);
448 449 450
    uint32_t i_bytes = 0;
    block_t *p_newblock;

451
    /* always need at least 10 bytes (atom size+header+1pair)*/
452 453
    if ( i_remaining < 10 ||
         !(i_bytes = GetDWBE(p_block->p_buffer)) ||
454
         (i_bytes > i_remaining) ||
455 456 457 458 459 460 461 462 463 464 465 466 467 468
         memcmp("cdat", &p_block->p_buffer[4], 4) ||
         !(p_newblock = block_Alloc( i_remaining * 3 - 8 )) )
    {
        p_block->i_buffer = 0;
        return p_block;
    }

    uint8_t *p_write = p_newblock->p_buffer;
    uint8_t *p_read = &p_block->p_buffer[8];
    i_bytes -= 8;
    i_remaining -= 8;

    do
    {
469
        p_write[i_copied++] = CC_PKT_BYTE0(0); /* cc1 == field 0 */
470 471 472 473 474 475 476
        p_write[i_copied++] = p_read[0];
        p_write[i_copied++] = p_read[1];
        p_read += 2;
        i_bytes -= 2;
        i_remaining -= 2;
    } while( i_bytes >= 2 );

477
    /* cdt2 is optional */
478 479
    if ( i_remaining >= 10 &&
         (i_bytes = GetDWBE(p_read)) &&
480
         (i_bytes <= i_remaining) &&
481 482 483 484 485 486 487
         !memcmp("cdt2", &p_read[4], 4) )
    {
        p_read += 8;
        i_bytes -= 8;
        i_remaining -= 8;
        do
        {
488
            p_write[i_copied++] = CC_PKT_BYTE0(0); /* cc1 == field 0 */
489 490 491 492 493 494 495
            p_write[i_copied++] = p_read[0];
            p_write[i_copied++] = p_read[1];
            p_read += 2;
            i_bytes -= 2;
        } while( i_bytes >= 2 );
    }

496
    p_newblock->i_pts = p_block->i_dts;
497
    p_newblock->i_buffer = i_copied;
498 499 500
    p_newblock->i_flags = BLOCK_FLAG_TYPE_P;
    block_Release( p_block );

501 502 503
    return p_newblock;
}

504 505 506 507 508 509 510
static uint32_t MP4_TrackGetRunSeq( mp4_track_t *p_track )
{
    if( p_track->i_chunk_count > 0 )
        return p_track->chunk[p_track->i_chunk].i_virtual_run_number;
    return 0;
}

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
/* Analyzes chunks to find max interleave length
 * sets flat flag if no interleaving is in use */
static void MP4_GetInterleaving( demux_t *p_demux, uint64_t *pi_max_contiguous, bool *pb_flat )
{
    demux_sys_t *p_sys = p_demux->p_sys;
    *pi_max_contiguous = 0;
    *pb_flat = true;

    /* Find first recorded chunk */
    mp4_track_t *tk = NULL;
    uint64_t i_duration = 0;
    for( unsigned i=0; i < p_sys->i_tracks; i++ )
    {
        mp4_track_t *cur = &p_sys->track[i];
        if( !cur->i_chunk_count )
            continue;

        if( tk == NULL || cur->chunk[0].i_offset < tk->chunk[0].i_offset )
            tk = cur;
    }

    for( ; tk != NULL; )
    {
        i_duration += tk->chunk[tk->i_chunk].i_duration;
        tk->i_chunk++;

        /* Find next chunk in data order */
        mp4_track_t *nexttk = NULL;
        for( unsigned i=0; i < p_sys->i_tracks; i++ )
        {
            mp4_track_t *cur = &p_sys->track[i];
            if( cur->i_chunk == cur->i_chunk_count )
                continue;

            if( nexttk == NULL ||
                cur->chunk[cur->i_chunk].i_offset < nexttk->chunk[nexttk->i_chunk].i_offset )
                nexttk = cur;
        }

550 551 552 553 554
        /* copy previous run */
        if( nexttk && nexttk->i_chunk > 0 )
            nexttk->chunk[nexttk->i_chunk].i_virtual_run_number =
                    nexttk->chunk[nexttk->i_chunk - 1].i_virtual_run_number;

555 556
        if( tk != nexttk )
        {
557
            i_duration = MP4_rescale( i_duration, tk->i_timescale, CLOCK_FREQ );
558 559 560 561 562 563
            if( i_duration > *pi_max_contiguous )
                *pi_max_contiguous = i_duration;
            i_duration = 0;

            if( tk->i_chunk != tk->i_chunk_count )
                *pb_flat = false;
564 565 566

            if( nexttk && nexttk->i_chunk > 0 ) /* new run number */
                nexttk->chunk[nexttk->i_chunk].i_virtual_run_number++;
567 568 569 570 571 572 573 574 575 576
        }

        tk = nexttk;
    }

    /* reset */
    for( unsigned i=0; i < p_sys->i_tracks; i++ )
        p_sys->track[i].i_chunk = 0;
}

577
static block_t * MP4_Block_Convert( demux_t *p_demux, const mp4_track_t *p_track, block_t *p_block )
578 579 580 581 582 583
{
    /* might have some encap */
    if( p_track->fmt.i_cat == SPU_ES )
    {
        switch( p_track->fmt.i_codec )
        {
François Cartegnie's avatar
François Cartegnie committed
584
            case VLC_CODEC_TTML:
585 586 587 588
            case VLC_CODEC_TX3G:
            case VLC_CODEC_SPU:
            /* accept as-is */
            break;
589 590 591
            case VLC_CODEC_EIA608_1:
                p_block = MP4_EIA608_Convert( p_block );
            break;
592 593 594 595
            case VLC_CODEC_SUBT:
                if( p_track->fmt.i_original_fourcc == ATOM_wvtt )
                    p_block = MP4_WebVTT_Convert( p_demux, p_block );
            break;
596 597 598 599 600
        default:
            p_block->i_buffer = 0;
            break;
        }
    }
601 602 603 604
    else if( p_track->fmt.i_original_fourcc == ATOM_rrtp )
    {
        p_block = MP4_RTPHint_Convert( p_demux, p_block, p_track->fmt.i_codec );
    }
605 606 607 608

    return p_block;
}

609 610
static void MP4_Block_Send( demux_t *p_demux, mp4_track_t *p_track, block_t *p_block )
{
611 612 613 614
    p_block = MP4_Block_Convert( p_demux, p_track, p_block );
    if( p_block == NULL )
        return;

615
    if ( p_track->b_chans_reorder )
616 617 618 619 620 621
    {
        aout_ChannelReorder( p_block->p_buffer, p_block->i_buffer,
                             p_track->fmt.audio.i_channels,
                             p_track->rgi_chans_reordering,
                             p_track->fmt.i_codec );
    }
622

623
    p_block->i_flags |= p_track->i_block_flags;
624 625 626 627 628
    if( p_track->i_next_block_flags )
    {
        p_block->i_flags |= p_track->i_next_block_flags;
        p_track->i_next_block_flags = 0;
    }
629

630 631 632 633 634
    /* ASF packets in mov */
    if( p_track->p_asf )
    {
        /* Fake a new stream from MP4 block */
        stream_t *p_stream = p_demux->s;
635
        p_demux->s = vlc_stream_MemoryNew( p_demux, p_block->p_buffer, p_block->i_buffer, true );
636 637 638 639 640 641
        if ( p_demux->s )
        {
            p_track->i_dts_backup = p_block->i_dts;
            p_track->i_pts_backup = p_block->i_pts;
            /* And demux it as ASF packet */
            DemuxASFPacket( &p_demux->p_sys->asfpacketsys, p_block->i_buffer, p_block->i_buffer );
642
            vlc_stream_Delete(p_demux->s);
643 644 645 646 647 648
        }
        block_Release(p_block);
        p_demux->s = p_stream;
    }
    else
        es_out_Send( p_demux->out, p_track->p_es, p_block );
649 650
}

651
/*****************************************************************************
652
 * Open: check file and initializes MP4 structures
653
 *****************************************************************************/
654
static int Open( vlc_object_t * p_this )
655
{
Laurent Aimar's avatar
Laurent Aimar committed
656
    demux_t  *p_demux = (demux_t *)p_this;
657
    demux_sys_t     *p_sys;
658

Christophe Mutricy's avatar
Christophe Mutricy committed
659
    const uint8_t   *p_peek;
660

661
    MP4_Box_t       *p_ftyp;
662
    MP4_Box_t       *p_rmra;
663 664
    const MP4_Box_t *p_mvhd = NULL;
    const MP4_Box_t *p_mvex = NULL;
665

666
    bool      b_enabled_es;
667

668
    /* A little test to see if it could be a mp4 */
669
    if( vlc_stream_Peek( p_demux->s, &p_peek, 11 ) < 11 ) return VLC_EGENERIC;
670

671
    switch( VLC_FOURCC( p_peek[4], p_peek[5], p_peek[6], p_peek[7] ) )
672
    {
Jean-Baptiste Kempf's avatar
Jean-Baptiste Kempf committed
673 674 675 676 677 678 679 680
        case ATOM_moov:
        case ATOM_foov:
        case ATOM_moof:
        case ATOM_mdat:
        case ATOM_udta:
        case ATOM_free:
        case ATOM_skip:
        case ATOM_wide:
681
        case ATOM_uuid:
682
        case VLC_FOURCC( 'p', 'n', 'o', 't' ):
683
            break;
684 685 686 687 688
        case ATOM_ftyp:
            /* We don't yet support f4v, but avformat does. */
            if( p_peek[8] == 'f' && p_peek[9] == '4' && p_peek[10] == 'v' )
                return VLC_EGENERIC;
            break;
689
         default:
690
            return VLC_EGENERIC;
691
    }
692

693 694 695 696 697
    /* create our structure that will contains all data */
    p_sys = calloc( 1, sizeof( demux_sys_t ) );
    if ( !p_sys )
        return VLC_EGENERIC;

698
    /* I need to seek */
699
    vlc_stream_Control( p_demux->s, STREAM_CAN_SEEK, &p_sys->b_seekable );
700 701
    if( p_sys->b_seekable )
        vlc_stream_Control( p_demux->s, STREAM_CAN_FASTSEEK, &p_sys->b_fastseekable );
702

703
    /*Set exported functions */
Laurent Aimar's avatar
Laurent Aimar committed
704 705
    p_demux->pf_demux = Demux;
    p_demux->pf_control = Control;
706

707
    p_sys->context.i_lastseqnumber = UINT32_MAX;
708

709
    p_demux->p_sys = p_sys;
710

711
    if( LoadInitFrag( p_demux ) != VLC_SUCCESS )
712 713
        goto error;

714
    MP4_BoxDumpStructure( p_demux->s, p_sys->p_root );
715

716
    if( ( p_ftyp = MP4_BoxGet( p_sys->p_root, "/ftyp" ) ) )
717
    {
718
        switch( BOXDATA(p_ftyp)->i_major_brand )
719
        {
720
            case MAJOR_isom:
Laurent Aimar's avatar
Laurent Aimar committed
721
                msg_Dbg( p_demux,
François Cartegnie's avatar
François Cartegnie committed
722
                         "ISO Media (isom) version %d.",
723
                         BOXDATA(p_ftyp)->i_minor_version );
724
                break;
725 726 727 728
            case MAJOR_3gp4:
            case MAJOR_3gp5:
            case MAJOR_3gp6:
            case MAJOR_3gp7:
729 730
                msg_Dbg( p_demux, "3GPP Media Release: %4.4s",
                         (char *)&BOXDATA(p_ftyp)->i_major_brand );
731
                break;
732
            case MAJOR_qt__:
François Cartegnie's avatar
François Cartegnie committed
733
                msg_Dbg( p_demux, "Apple QuickTime media" );
734
                break;
735
            case MAJOR_isml:
François Cartegnie's avatar
François Cartegnie committed
736
                msg_Dbg( p_demux, "PIFF (= isml = fMP4) media" );
737
                break;
738
            case MAJOR_dash:
François Cartegnie's avatar
François Cartegnie committed
739
                msg_Dbg( p_demux, "DASH Stream" );
740
                break;
741 742 743 744 745
            case MAJOR_M4A:
                msg_Dbg( p_demux, "iTunes audio" );
                if( var_InheritBool( p_demux, CFG_PREFIX"m4a-audioonly" ) )
                    p_sys->hacks.es_cat_filters = AUDIO_ES;
                break;
746
            default:
Laurent Aimar's avatar
Laurent Aimar committed
747
                msg_Dbg( p_demux,
François Cartegnie's avatar
François Cartegnie committed
748
                         "unrecognized major media specification (%4.4s).",
749
                          (char*)&BOXDATA(p_ftyp)->i_major_brand );
750 751
                break;
        }
752 753 754 755 756
        /* also lookup in compatibility list */
        for(uint32_t i=0; i<BOXDATA(p_ftyp)->i_compatible_brands_count; i++)
        {
            if (BOXDATA(p_ftyp)->i_compatible_brands[i] == MAJOR_dash)
            {
François Cartegnie's avatar
François Cartegnie committed
757
                msg_Dbg( p_demux, "DASH Stream" );
758
            }
759 760 761 762
            else if (BOXDATA(p_ftyp)->i_compatible_brands[i] == VLC_FOURCC('s', 'm', 'o', 'o') )
            {
                msg_Dbg( p_demux, "Handling VLC Smooth Stream" );
            }
763
        }
764 765 766
    }
    else
    {
François Cartegnie's avatar
François Cartegnie committed
767
        msg_Dbg( p_demux, "file type box missing (assuming ISO Media)" );
768 769
    }

770 771 772
    /* the file need to have one moov box */
    p_sys->p_moov = MP4_BoxGet( p_sys->p_root, "/moov" );
    if( unlikely(!p_sys->p_moov) )
773
    {
774 775 776 777 778 779 780 781
        p_sys->p_moov = MP4_BoxGet( p_sys->p_root, "/foov" );
        if( !p_sys->p_moov )
        {
            msg_Err( p_demux, "MP4 plugin discarded (no moov,foov,moof box)" );
            goto error;
        }
        /* we have a free box as a moov, rename it */
        p_sys->p_moov->i_type = ATOM_moov;
782 783
    }

784
    p_mvhd = MP4_BoxGet( p_sys->p_moov, "mvhd" );
785
    if( p_mvhd && BOXDATA(p_mvhd) && BOXDATA(p_mvhd)->i_timescale )
786 787 788 789 790 791 792 793
    {
        p_sys->i_timescale = BOXDATA(p_mvhd)->i_timescale;
        p_sys->i_moov_duration = p_sys->i_duration = BOXDATA(p_mvhd)->i_duration;
        p_sys->i_cumulated_duration = BOXDATA(p_mvhd)->i_duration;
    }
    else
    {
        msg_Warn( p_demux, "No valid mvhd found" );
794
        goto error;
795 796
    }

797
    if( ( p_rmra = MP4_BoxGet( p_sys->p_root,  "/moov/rmra" ) ) )
798 799 800 801
    {
        int        i_count = MP4_BoxCount( p_rmra, "rmda" );
        int        i;

Laurent Aimar's avatar
Laurent Aimar committed
802
        msg_Dbg( p_demux, "detected playlist mov file (%d ref)", i_count );
803

804
        input_thread_t *p_input = p_demux->p_input;
805
        input_item_t *p_current = input_GetItem( p_input );
806

807 808
        input_item_node_t *p_subitems = input_item_node_Create( p_current );

809
        for( i = 0; i < i_count; i++ )
810
        {
811 812 813
            MP4_Box_t *p_rdrf = MP4_BoxGet( p_rmra, "rmda[%d]/rdrf", i );
            char      *psz_ref;
            uint32_t  i_ref_type;
814

815
            if( !p_rdrf || !BOXDATA(p_rdrf) || !( psz_ref = strdup( BOXDATA(p_rdrf)->psz_ref ) ) )
816
            {
817 818
                continue;
            }
819
            i_ref_type = BOXDATA(p_rdrf)->i_ref_type;
820

821 822 823 824 825 826
            msg_Dbg( p_demux, "new ref=`%s' type=%4.4s",
                     psz_ref, (char*)&i_ref_type );

            if( i_ref_type == VLC_FOURCC( 'u', 'r', 'l', ' ' ) )
            {
                if( strstr( psz_ref, "qt5gateQT" ) )
827
                {
828
                    msg_Dbg( p_demux, "ignoring pseudo ref =`%s'", psz_ref );
829
                    free( psz_ref );
830 831
                    continue;
                }
832 833
                if( !strncmp( psz_ref, "http://", 7 ) ||
                    !strncmp( psz_ref, "rtsp://", 7 ) )
834
                {
835
                    ;
836 837 838
                }
                else
                {
839
                    char *psz_absolute;
840
                    char *psz_path = strdup( p_demux->psz_location );
841 842 843 844
                    char *end = strrchr( psz_path, '/' );
                    if( end ) end[1] = '\0';
                    else *psz_path = '\0';

Christophe Mutricy's avatar
Christophe Mutricy committed
845 846
                    if( asprintf( &psz_absolute, "%s://%s%s",
                                  p_demux->psz_access, psz_path, psz_ref ) < 0 )
Rémi Duraffort's avatar
Rémi Duraffort committed
847 848 849
                    {
                        free( psz_ref );
                        free( psz_path );
François Cartegnie's avatar
François Cartegnie committed
850
                        input_item_node_Delete( p_subitems );
Christophe Mutricy's avatar
Christophe Mutricy committed
851
                        return VLC_ENOMEM;
Rémi Duraffort's avatar
Rémi Duraffort committed
852
                    }
853 854 855 856

                    free( psz_ref );
                    psz_ref = psz_absolute;
                    free( psz_path );
857
                }
858
                msg_Dbg( p_demux, "adding ref = `%s'", psz_ref );
859
                input_item_t *p_item = input_item_New( psz_ref, NULL );
860
                input_item_CopyOptions( p_item, p_current );
861
                input_item_node_AppendItem( p_subitems, p_item );
862
                input_item_Release( p_item );
863
            }
864
            else
865
            {
866
                msg_Err( p_demux, "unknown ref type=%4.4s FIXME (send a bug report)",
867
                         (char*)&BOXDATA(p_rdrf)->i_ref_type );
868
            }
869
            free( psz_ref );
870
        }
871 872 873 874

        /* FIXME: create a stream_filter sub-module for this */
        if (es_out_Control(p_demux->out, ES_OUT_POST_SUBNODE, p_subitems))
            input_item_node_Delete(p_subitems);
875 876
    }

877
    if( !(p_mvhd = MP4_BoxGet( p_sys->p_root, "/moov/mvhd" ) ) )
878
    {
879 880
        if( !p_rmra )
        {
Laurent Aimar's avatar
Laurent Aimar committed
881
            msg_Err( p_demux, "cannot find /moov/mvhd" );
882
            goto error;
883 884 885
        }
        else
        {
Laurent Aimar's avatar
Laurent Aimar committed
886 887
            msg_Warn( p_demux, "cannot find /moov/mvhd (pure ref file)" );
            p_demux->pf_demux = DemuxRef;
888
            return VLC_SUCCESS;
889
        }
890 891 892
    }
    else
    {
893
        p_sys->i_timescale = BOXDATA(p_mvhd)->i_timescale;
894 895 896 897 898
        if( p_sys->i_timescale == 0 )
        {
            msg_Err( p_this, "bad timescale" );
            goto error;
        }
899
    }
900

901 902
    const unsigned i_tracks = MP4_BoxCount( p_sys->p_root, "/moov/trak" );
    if( i_tracks < 1 )
903
    {
Laurent Aimar's avatar
Laurent Aimar committed
904
        msg_Err( p_demux, "cannot find any /moov/trak" );
905
        goto error;
906
    }
907
    msg_Dbg( p_demux, "found %u track%c", i_tracks, i_tracks ? 's':' ' );
908

909
    if( CreateTracks( p_demux, i_tracks ) != VLC_SUCCESS )
910
        goto error;
911

912 913
    /* Search the first chap reference (like quicktime) and
     * check that at least 1 stream is enabled */
914
    p_sys->p_tref_chap = NULL;
915
    b_enabled_es = false;
916
    for( unsigned i = 0; i < p_sys->i_tracks; i++ )
917 918 919
    {
        MP4_Box_t *p_trak = MP4_BoxGet( p_sys->p_root, "/moov/trak[%d]", i );

920 921

        MP4_Box_t *p_tkhd = MP4_BoxGet( p_trak, "tkhd" );
922
        if( p_tkhd && BOXDATA(p_tkhd) && (BOXDATA(p_tkhd)->i_flags&MP4_TRACK_ENABLED) )
923 924 925
            b_enabled_es = true;

        MP4_Box_t *p_chap = MP4_BoxGet( p_trak, "tref/chap", i );
926 927
        if( p_chap && p_chap->data.p_tref_generic &&
            p_chap->data.p_tref_generic->i_entry_count > 0 && !p_sys->p_tref_chap )
928
            p_sys->p_tref_chap = p_chap;
Laurent Aimar's avatar<