mp4.c 54.3 KB
Newer Older
1 2 3 4
/*****************************************************************************
 * mp4.c : MP4 file input module for vlc
 *****************************************************************************
 * Copyright (C) 2001 VideoLAN
5
 * $Id: mp4.c,v 1.51 2004/01/13 01:44:49 fenrir Exp $
6
 * Authors: Laurent Aimar <fenrir@via.ecp.fr>
7
 *
8 9 10 11
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
12
 *
13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29
 * 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 General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111, USA.
 *****************************************************************************/

/*****************************************************************************
 * Preamble
 *****************************************************************************/
#include <stdlib.h>                                      /* malloc(), free() */

#include <vlc/vlc.h>
#include <vlc/input.h>
30
#include <vlc_playlist.h>
31

32 33
#include "libmp4.h"
#include "mp4.h"
34
#include "drms.h"
35 36 37 38

/*****************************************************************************
 * Module descriptor
 *****************************************************************************/
39 40
static int  Open ( vlc_object_t * );
static void Close( vlc_object_t * );
41

42
vlc_module_begin();
Gildas Bazin's avatar
 
Gildas Bazin committed
43
    set_description( _("MP4 demuxer") );
44
    set_capability( "demux", 242 );
45
    set_callbacks( Open, Close );
46 47
vlc_module_end();

48 49 50 51 52 53 54 55 56 57 58
/*****************************************************************************
 * Local prototypes
 *****************************************************************************/
static int    Demux   ( input_thread_t * );
static int    DemuxRef( input_thread_t *p_input )
{
    return 0;
}
static int   Seek     ( input_thread_t *, mtime_t );
static int   Control  ( input_thread_t *, int, va_list );

59
/*****************************************************************************
60
 * Declaration of local function
61
 *****************************************************************************/
62 63
static void MP4_TrackCreate ( input_thread_t *, track_data_mp4_t *, MP4_Box_t  *);
static void MP4_TrackDestroy( input_thread_t *, track_data_mp4_t * );
64

65 66
static int  MP4_TrackSelect ( input_thread_t *, track_data_mp4_t *, mtime_t );
static void MP4_TrackUnselect(input_thread_t *, track_data_mp4_t * );
67

68
static int  MP4_TrackSeek   ( input_thread_t *, track_data_mp4_t *, mtime_t );
69

70 71 72
static uint64_t MP4_GetTrackPos    ( track_data_mp4_t * );
static int      MP4_TrackSampleSize( track_data_mp4_t * );
static int      MP4_TrackNextSample( input_thread_t *, track_data_mp4_t * );
73

74 75
#define FREE( p ) \
    if( p ) { free( p ); (p) = NULL;}
76

77
/*****************************************************************************
78
 * Open: check file and initializes MP4 structures
79
 *****************************************************************************/
80
static int Open( vlc_object_t * p_this )
81
{
82
    input_thread_t  *p_input = (input_thread_t *)p_this;
83
    demux_sys_t     *p_sys;
84

85
    uint8_t         *p_peek;
86

87
    MP4_Box_t       *p_ftyp;
88
    MP4_Box_t       *p_rmra;
89 90
    MP4_Box_t       *p_mvhd;
    MP4_Box_t       *p_trak;
91

92
    unsigned int    i;
93
    vlc_bool_t      b_seekable;
94

95
    /* a little test to see if it could be a mp4 */
96
    if( stream_Peek( p_input->s, &p_peek, 8 ) < 8 )
97 98
    {
        msg_Warn( p_input, "MP4 plugin discarded (cannot peek)" );
99
        return VLC_EGENERIC;
100
    }
101
    switch( VLC_FOURCC( p_peek[4], p_peek[5], p_peek[6], p_peek[7] ) )
102
    {
103 104 105 106 107 108 109 110 111
        case FOURCC_ftyp:
        case FOURCC_moov:
        case FOURCC_foov:
        case FOURCC_moof:
        case FOURCC_mdat:
        case FOURCC_udta:
        case FOURCC_free:
        case FOURCC_skip:
        case FOURCC_wide:
112 113 114
            break;
         default:
            msg_Warn( p_input, "MP4 plugin discarded (not a valid file)" );
115
            return VLC_EGENERIC;
116
    }
117

118
    /* I need to seek */
119 120
    stream_Control( p_input->s, STREAM_CAN_SEEK, &b_seekable );
    if( !b_seekable )
121
    {
122 123
        msg_Warn( p_input, "MP4 plugin discarded (unseekable)" );
        return VLC_EGENERIC;
124
    }
125

126 127 128 129 130
    /*Set exported functions */
    p_input->pf_demux = Demux;
    p_input->pf_demux_control = Control;

    /* create our structure that will contains all data */
131 132
    p_input->p_demux_data = p_sys = malloc( sizeof( demux_sys_t ) );
    memset( p_sys, 0, sizeof( demux_sys_t ) );
133 134

    /* Now load all boxes ( except raw data ) */
135
    if( ( p_sys->p_root = MP4_BoxGetRoot( p_input ) ) == NULL )
136 137
    {
        msg_Warn( p_input, "MP4 plugin discarded (not a valid file)" );
Laurent Aimar's avatar
Laurent Aimar committed
138
        goto error;
139 140
    }

141
    MP4_BoxDumpStructure( p_input, p_sys->p_root );
142

143
    if( ( p_ftyp = MP4_BoxGet( p_sys->p_root, "/ftyp" ) ) )
144 145 146 147
    {
        switch( p_ftyp->data.p_ftyp->i_major_brand )
        {
            case( FOURCC_isom ):
148
                msg_Dbg( p_input,
149 150
                         "ISO Media file (isom) version %d.",
                         p_ftyp->data.p_ftyp->i_minor_version );
151 152
                break;
            default:
153
                msg_Dbg( p_input,
154 155
                         "unrecognized major file specification (%4.4s).",
                          (char*)&p_ftyp->data.p_ftyp->i_major_brand );
156 157 158 159 160
                break;
        }
    }
    else
    {
161
        msg_Dbg( p_input, "file type box missing (assuming ISO Media file)" );
162 163 164
    }

    /* the file need to have one moov box */
165
    if( MP4_BoxCount( p_sys->p_root, "/moov" ) <= 0 )
166
    {
167
        MP4_Box_t *p_foov = MP4_BoxGet( p_sys->p_root, "/foov" );
168 169 170 171

        if( !p_foov )
        {
            msg_Err( p_input, "MP4 plugin discarded (no moov box)" );
172
            goto error;
173 174 175
        }
        /* we have a free box as a moov, rename it */
        p_foov->i_type = FOURCC_moov;
176 177
    }

178
    if( ( p_rmra = MP4_BoxGet( p_sys->p_root,  "/moov/rmra" ) ) )
179 180 181 182 183 184 185 186 187 188 189 190 191
    {
        playlist_t *p_playlist;
        int        i_count = MP4_BoxCount( p_rmra, "rmda" );
        int        i;

        msg_Dbg( p_input, "detected playlist mov file (%d ref)", i_count );

        p_playlist =
            (playlist_t *)vlc_object_find( p_input,
                                           VLC_OBJECT_PLAYLIST,
                                           FIND_ANYWHERE );
        if( p_playlist )
        {
192
            //p_playlist->pp_items[p_playlist->i_index]->b_autodeletion = VLC_TRUE;
193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214
            for( i = 0; i < i_count; i++ )
            {
                MP4_Box_t *p_rdrf = MP4_BoxGet( p_rmra, "rmda[%d]/rdrf", i );
                char      *psz_ref;
                uint32_t  i_ref_type;

                if( !p_rdrf || !( psz_ref = p_rdrf->data.p_rdrf->psz_ref ) )
                {
                    continue;
                }
                i_ref_type = p_rdrf->data.p_rdrf->i_ref_type;

                msg_Dbg( p_input, "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" ) )
                    {
                        msg_Dbg( p_input, "ignoring pseudo ref =`%s'", psz_ref );
                        continue;
                    }
215 216
                    if( !strncmp( psz_ref, "http://", 7 ) ||
                        !strncmp( psz_ref, "rtsp://", 7 ) )
217 218
                    {
                        msg_Dbg( p_input, "adding ref = `%s'", psz_ref );
Clément Stenac's avatar
Clément Stenac committed
219
                        playlist_Add( p_playlist, psz_ref, psz_ref,
Gildas Bazin's avatar
 
Gildas Bazin committed
220
                                      PLAYLIST_APPEND, PLAYLIST_END );
221 222 223 224
                    }
                    else
                    {
                        /* msg dbg relative ? */
225 226
                        char *psz_absolute = alloca( strlen( p_input->psz_source ) + strlen( psz_ref ) + 1);
                        char *end = strrchr( p_input->psz_source, '/' );
227 228 229

                        if( end )
                        {
230
                            int i_len = end + 1 - p_input->psz_source;
231

232
                            strncpy( psz_absolute, p_input->psz_source, i_len);
233
                            psz_absolute[i_len] = '\0';
234 235 236 237 238 239 240
                        }
                        else
                        {
                            strcpy( psz_absolute, "" );
                        }
                        strcat( psz_absolute, psz_ref );
                        msg_Dbg( p_input, "adding ref = `%s'", psz_absolute );
Clément Stenac's avatar
Clément Stenac committed
241
                        playlist_Add( p_playlist, psz_absolute, psz_absolute,
Gildas Bazin's avatar
 
Gildas Bazin committed
242
                                      PLAYLIST_APPEND, PLAYLIST_END );
243 244 245 246 247 248 249 250 251 252 253 254 255 256 257
                    }
                }
                else
                {
                    msg_Err( p_input, "unknown ref type=%4.4s FIXME (send a bug report)", (char*)&p_rdrf->data.p_rdrf->i_ref_type );
                }
            }
            vlc_object_release( p_playlist );
        }
        else
        {
            msg_Err( p_input, "can't find playlist" );
        }
    }

258
    if( !(p_mvhd = MP4_BoxGet( p_sys->p_root, "/moov/mvhd" ) ) )
259
    {
260 261 262
        if( !p_rmra )
        {
            msg_Err( p_input, "cannot find /moov/mvhd" );
263
            goto error;
264 265 266 267
        }
        else
        {
            msg_Warn( p_input, "cannot find /moov/mvhd (pure ref file)" );
268
            p_input->pf_demux = DemuxRef;
269
            return VLC_SUCCESS;
270
        }
271 272 273
    }
    else
    {
274 275
        p_sys->i_timescale = p_mvhd->data.p_mvhd->i_timescale;
        p_sys->i_duration = p_mvhd->data.p_mvhd->i_duration;
276
    }
277

278
    if( !( p_sys->i_tracks = MP4_BoxCount( p_sys->p_root, "/moov/trak" ) ) )
279
    {
280
        msg_Err( p_input, "cannot find any /moov/trak" );
281
        goto error;
282
    }
283
    msg_Dbg( p_input, "find %d track%c",
284 285
                        p_sys->i_tracks,
                        p_sys->i_tracks ? 's':' ' );
286

287 288 289 290 291 292
    /*  create one program */
    vlc_mutex_lock( &p_input->stream.stream_lock );
    if( input_InitStream( p_input, 0 ) == -1)
    {
        vlc_mutex_unlock( &p_input->stream.stream_lock );
        msg_Err( p_input, "cannot init stream" );
293
        goto error;
294
    }
295
    if( p_sys->i_duration/p_sys->i_timescale > 0 )
296 297 298
    {
        p_input->stream.i_mux_rate =
            p_input->stream.p_selected_area->i_size / 50 /
299
            ( p_sys->i_duration / p_sys->i_timescale );
300 301 302 303 304 305 306 307
    }
    else
    {
        p_input->stream.i_mux_rate = 0;
    }
    vlc_mutex_unlock( &p_input->stream.stream_lock );


308
    /* allocate memory */
309 310
    p_sys->track = calloc( p_sys->i_tracks, sizeof( track_data_mp4_t ) );
    memset( p_sys->track, 0, p_sys->i_tracks * sizeof( track_data_mp4_t ) );
311 312

    /* now process each track and extract all usefull informations */
313
    for( i = 0; i < p_sys->i_tracks; i++ )
314
    {
315 316
        p_trak = MP4_BoxGet( p_sys->p_root, "/moov/trak[%d]", i );
        MP4_TrackCreate( p_input, &p_sys->track[i], p_trak );
317

318
        if( p_sys->track[i].b_ok )
319 320
        {
            char *psz_cat;
321
            switch( p_sys->track[i].fmt.i_cat )
322 323 324 325 326 327 328 329
            {
                case( VIDEO_ES ):
                    psz_cat = "video";
                    break;
                case( AUDIO_ES ):
                    psz_cat = "audio";
                    break;
                default:
330
                    psz_cat = "unknown";
331 332
                    break;
            }
333

334 335
            msg_Dbg( p_input, "adding track[Id 0x%x] %s (%s) language %s",
                            p_sys->track[i].i_track_ID,
336
                            psz_cat,
337 338
                            p_sys->track[i].b_enable ? "enable":"disable",
                            p_sys->track[i].fmt.psz_language ? p_sys->track[i].fmt.psz_language : "undef" );
339 340 341
        }
        else
        {
342
            msg_Dbg( p_input, "ignoring track[Id 0x%x]", p_sys->track[i].i_track_ID );
343 344 345
        }

    }
346 347 348
    return VLC_SUCCESS;

error:
349
    if( p_sys->p_root )
Laurent Aimar's avatar
Laurent Aimar committed
350
    {
351
        MP4_BoxFree( p_input, p_sys->p_root );
Laurent Aimar's avatar
Laurent Aimar committed
352
    }
353
    free( p_sys );
354
    return VLC_EGENERIC;
355 356 357
}

/*****************************************************************************
358
 * Demux: read packet and send them to decoders
359 360
 *****************************************************************************
 * TODO check for newly selected track (ie audio upt to now )
361
 *****************************************************************************/
362
static int Demux( input_thread_t *p_input )
363
{
364
    demux_sys_t *p_sys = p_input->p_demux_data;
365
    unsigned int i_track;
366

367 368 369 370 371

    unsigned int i_track_selected;
    vlc_bool_t   b_play_audio;

    /* check for newly selected/unselected track */
372
    for( i_track = 0, i_track_selected = 0; i_track <  p_sys->i_tracks; i_track++ )
373
    {
374
#define track   p_sys->track[i_track]
375 376 377 378 379 380 381
        if( track.b_selected && track.i_sample >= track.i_sample_count )
        {
            msg_Warn( p_input, "track[0x%x] will be disabled", track.i_track_ID );
            MP4_TrackUnselect( p_input, &track );
        }
        else if( track.b_ok )
        {
382 383 384 385
            vlc_bool_t b;
            es_out_Control( p_input->p_es_out, ES_OUT_GET_ES_STATE, track.p_es, &b );

            if( track.b_selected && !b )
386 387 388
            {
                MP4_TrackUnselect( p_input, &track );
            }
389
            else if( !track.b_selected && b)
390
            {
391
                MP4_TrackSelect( p_input, &track, MP4_GetMoviePTS( p_sys ) );
392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407
            }

            if( track.b_selected )
            {
                i_track_selected++;
            }
        }
#undef  track
    }

    if( i_track_selected <= 0 )
    {
        msg_Warn( p_input, "no track selected, exiting..." );
        return( 0 );
    }

408 409 410
    /* first wait for the good time to read a packet */
    input_ClockManageRef( p_input,
                          p_input->stream.p_selected_program,
411
                          p_sys->i_pcr );
412 413

    /* update pcr XXX in mpeg scale so in 90000 unit/s */
414
    p_sys->i_pcr = MP4_GetMoviePTS( p_sys ) * 9 / 100;
415 416

    /* we will read 100ms for each stream so ...*/
417
    p_sys->i_time += __MAX( p_sys->i_timescale / 10 , 1 );
418

Gildas Bazin's avatar
 
Gildas Bazin committed
419 420
    /* Check if we need to send the audio data to decoder */
    b_play_audio = !p_input->stream.control.b_mute;
421

422
    for( i_track = 0; i_track < p_sys->i_tracks; i_track++ )
423
    {
424
#define track p_sys->track[i_track]
425 426
        if( !track.b_ok ||
            !track.b_selected ||
427
            MP4_GetTrackPTS( &track ) >= MP4_GetMoviePTS( p_sys ) )
428
        {
429
            continue;
430
        }
431 432

        while( MP4_GetTrackPTS( &track ) < MP4_GetMoviePTS( p_sys ) )
433 434
        {

435 436
            if( ( !b_play_audio && track.fmt.i_cat == AUDIO_ES ) ||
                MP4_TrackSampleSize( &track ) <= 0 )
437
            {
438 439 440 441
                if( MP4_TrackNextSample( p_input, &track ) )
                {
                    break;
                }
442
            }
443 444
            else
            {
445
                block_t *p_block;
446

447
                /* go,go go ! */
448
                if( stream_Seek( p_input->s, MP4_GetTrackPos( &track ) ) )
449 450 451 452 453 454
                {
                    msg_Warn( p_input, "track[0x%x] will be disabled (eof?)", track.i_track_ID );
                    MP4_TrackUnselect( p_input, &track );
                    break;
                }

Laurent Aimar's avatar
Laurent Aimar committed
455
                /* now read pes */
456 457
                if( ( p_block = stream_Block( p_input->s,
                                              MP4_TrackSampleSize( &track ) ) ) == NULL )
458
                {
Laurent Aimar's avatar
Laurent Aimar committed
459 460
                    msg_Warn( p_input, "track[0x%x] will be disabled (eof?)", track.i_track_ID );
                    MP4_TrackUnselect( p_input, &track );
461 462
                    break;
                }
Gildas Bazin's avatar
 
Gildas Bazin committed
463

464
                if( track.b_drms && track.p_drms )
465 466 467 468 469 470
                {
                    drms_decrypt( track.p_drms,
                                  (uint32_t *)p_block->p_buffer,
                                  p_block->i_buffer );
                }

471
                if( track.fmt.i_cat == VIDEO_ES )
472
                {
473 474 475 476 477 478
                    /* FIXME sometime we can calculate PTS */
                    p_block->i_pts = 0;
                    p_block->i_dts =
                        input_ClockGetTS( p_input,
                                          p_input->stream.p_selected_program,
                                          MP4_GetTrackPTS( &track ) * 9/100 );
479 480 481
                }
                else
                {
482 483 484 485 486
                    p_block->i_pts =
                    p_block->i_dts =
                        input_ClockGetTS( p_input,
                                          p_input->stream.p_selected_program,
                                          MP4_GetTrackPTS( &track ) * 9/100 );
487 488
                }

489 490 491 492
                if( !track.b_drms || ( track.b_drms && track.p_drms ) )
                {
                    es_out_Send( p_input->p_es_out, track.p_es, p_block );
                }
493

494 495 496 497 498
                if( MP4_TrackNextSample( p_input, &track ) )
                {
                    break;
                }
            }
499
        }
500
#undef track
501 502
    }

503
    return( 1 );
504
}
505
/*****************************************************************************
506
 * Seek: Got to i_date
507
 ******************************************************************************/
508
static int   Seek     ( input_thread_t *p_input, mtime_t i_date )
509
{
510
    demux_sys_t *p_sys = p_input->p_demux_data;
511
    unsigned int i_track;
512
    /* First update update global time */
513 514
    p_sys->i_time = i_date * p_sys->i_timescale / 1000000;
    p_sys->i_pcr  = i_date* 9 / 100;
515

516
    /* Now for each stream try to go to this time */
517
    for( i_track = 0; i_track < p_sys->i_tracks; i_track++ )
518
    {
519
#define track p_sys->track[i_track]
520 521 522 523 524
        if( track.b_ok && track.b_selected )
        {
            MP4_TrackSeek( p_input, &track, i_date );
        }
#undef  track
525 526 527
    }
    return( 1 );
}
528 529

/*****************************************************************************
530
 * Control:
531
 *****************************************************************************/
532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577
static int   Control  ( input_thread_t *p_input, int i_query, va_list args )
{
    demux_sys_t *p_sys = p_input->p_demux_data;

    double   f, *pf;
    int64_t i64, *pi64;

    switch( i_query )
    {
        case DEMUX_GET_POSITION:
            pf = (double*)va_arg( args, double * );
            if( p_sys->i_duration > 0 )
            {
                *pf = (double)p_sys->i_time / (double)p_sys->i_duration;
            }
            else
            {
                *pf = 0.0;
            }
            return VLC_SUCCESS;

        case DEMUX_SET_POSITION:
            f = (double)va_arg( args, double );
            i64 = (int64_t)( f *
                             (double)1000000 *
                             (double)p_sys->i_duration /
                             (double)p_sys->i_timescale );
            return Seek( p_input, i64 );

        case DEMUX_GET_TIME:
            pi64 = (int64_t*)va_arg( args, int64_t * );
            *pi64 = (mtime_t)1000000 *
                    (mtime_t)p_sys->i_time /
                    (mtime_t)p_sys->i_timescale;
            return VLC_SUCCESS;

        case DEMUX_SET_TIME:
            i64 = (int64_t)va_arg( args, int64_t );
            return Seek( p_input, i64 );

        case DEMUX_GET_LENGTH:
            pi64 = (int64_t*)va_arg( args, int64_t * );
            *pi64 = (mtime_t)1000000 *
                    (mtime_t)p_sys->i_duration /
                    (mtime_t)p_sys->i_timescale;
            return VLC_SUCCESS;
578 579 580
        case DEMUX_GET_FPS:
            msg_Warn( p_input, "DEMUX_GET_FPS unimplemented !!" );
            return VLC_EGENERIC;
581 582 583 584 585 586 587 588 589 590
        default:
            msg_Err( p_input, "control query unimplemented !!!" );
            return demux_vaControlDefault( p_input, i_query, args );
    }
}

/*****************************************************************************
 * Close: frees unused data
 *****************************************************************************/
static void Close ( vlc_object_t * p_this )
591 592
{
    unsigned int i_track;
593
    input_thread_t *  p_input = (input_thread_t *)p_this;
594
    demux_sys_t *p_sys = p_input->p_demux_data;
595

596
    msg_Dbg( p_input, "freeing all memory" );
Laurent Aimar's avatar
Laurent Aimar committed
597

598 599
    MP4_BoxFree( p_input, p_sys->p_root );
    for( i_track = 0; i_track < p_sys->i_tracks; i_track++ )
600
    {
601
        MP4_TrackDestroy( p_input, &p_sys->track[i_track] );
602
    }
603
    FREE( p_sys->track );
604

605
    free( p_sys );
606 607 608
}


609

610 611 612 613
/****************************************************************************
 * Local functions, specific to vlc
 ****************************************************************************/

614 615 616
/* now create basic chunk data, the rest will be filled by MP4_CreateSamplesIndex */
static int TrackCreateChunksIndex( input_thread_t *p_input,
                                   track_data_mp4_t *p_demux_track )
617
{
618 619
    MP4_Box_t *p_co64; /* give offset for each chunk, same for stco and co64 */
    MP4_Box_t *p_stsc;
620

621 622 623 624 625 626
    unsigned int i_chunk;
    unsigned int i_index, i_last;

    if( ( !(p_co64 = MP4_BoxGet( p_demux_track->p_stbl, "stco" ) )&&
          !(p_co64 = MP4_BoxGet( p_demux_track->p_stbl, "co64" ) ) )||
        ( !(p_stsc = MP4_BoxGet( p_demux_track->p_stbl, "stsc" ) ) ))
627
    {
628
        return( VLC_EGENERIC );
629
    }
630 631 632

    p_demux_track->i_chunk_count = p_co64->data.p_co64->i_entry_count;
    if( !p_demux_track->i_chunk_count )
633
    {
634 635
        msg_Warn( p_input, "no chunk defined" );
        return( VLC_EGENERIC );
636
    }
637 638 639 640 641
    p_demux_track->chunk = calloc( p_demux_track->i_chunk_count,
                                   sizeof( chunk_data_mp4_t ) );

    /* first we read chunk offset */
    for( i_chunk = 0; i_chunk < p_demux_track->i_chunk_count; i_chunk++ )
642
    {
643 644
        p_demux_track->chunk[i_chunk].i_offset =
                p_co64->data.p_co64->i_chunk_offset[i_chunk];
645 646
    }

647 648 649 650 651 652
    /* now we read index for SampleEntry( soun vide mp4a mp4v ...)
        to be used for the sample XXX begin to 1
        We construct it begining at the end */
    i_last = p_demux_track->i_chunk_count; /* last chunk proceded */
    i_index = p_stsc->data.p_stsc->i_entry_count;
    if( !i_index )
653
    {
654 655
        msg_Warn( p_input, "cannot read chunk table or table empty" );
        return( VLC_EGENERIC );
656
    }
657 658

    while( i_index )
659
    {
660 661 662 663 664 665 666 667 668 669
        i_index--;
        for( i_chunk = p_stsc->data.p_stsc->i_first_chunk[i_index] - 1;
                i_chunk < i_last; i_chunk++ )
        {
            p_demux_track->chunk[i_chunk].i_sample_description_index =
                    p_stsc->data.p_stsc->i_sample_description_index[i_index];
            p_demux_track->chunk[i_chunk].i_sample_count =
                    p_stsc->data.p_stsc->i_samples_per_chunk[i_index];
        }
        i_last = p_stsc->data.p_stsc->i_first_chunk[i_index] - 1;
670 671
    }

672 673
    p_demux_track->chunk[0].i_sample_first = 0;
    for( i_chunk = 1; i_chunk < p_demux_track->i_chunk_count; i_chunk++ )
674
    {
675 676 677
        p_demux_track->chunk[i_chunk].i_sample_first =
            p_demux_track->chunk[i_chunk-1].i_sample_first +
                p_demux_track->chunk[i_chunk-1].i_sample_count;
678
    }
679

680 681 682 683
    msg_Dbg( p_input,
             "track[Id 0x%x] read %d chunk",
             p_demux_track->i_track_ID,
            p_demux_track->i_chunk_count );
684

685
    return( VLC_SUCCESS );
686
}
687 688
static int TrackCreateSamplesIndex( input_thread_t *p_input,
                                    track_data_mp4_t *p_demux_track )
689 690
{
    MP4_Box_t *p_stts; /* makes mapping between sample and decoding time,
691
                          ctts make same mapping but for composition time,
692
                          not yet used and probably not usefull */
693 694
    MP4_Box_t *p_stsz; /* gives sample size of each samples, there is also stz2
                          that uses a compressed form FIXME make them in libmp4
695 696 697
                          as a unique type */
    /* TODO use also stss and stsh table for seeking */
    /* FIXME use edit table */
698 699
    int64_t i_sample;
    int64_t i_chunk;
700

701 702
    int64_t i_index;
    int64_t i_index_sample_used;
703

704 705
    int64_t i_last_dts;

706 707
    p_stts = MP4_BoxGet( p_demux_track->p_stbl, "stts" );
    p_stsz = MP4_BoxGet( p_demux_track->p_stbl, "stsz" ); /* FIXME and stz2 */
708 709 710 711

    if( ( !p_stts )||( !p_stsz ) )
    {
        msg_Warn( p_input, "cannot read sample table" );
712
        return( VLC_EGENERIC );
713
    }
714

715 716 717 718 719 720 721 722 723 724 725 726 727 728
    p_demux_track->i_sample_count = p_stsz->data.p_stsz->i_sample_count;


    /* for sample size, there are 2 case */
    if( p_stsz->data.p_stsz->i_sample_size )
    {
        /* 1: all sample have the same size, so no need to construct a table */
        p_demux_track->i_sample_size = p_stsz->data.p_stsz->i_sample_size;
        p_demux_track->p_sample_size = NULL;
    }
    else
    {
        /* 2: each sample can have a different size */
        p_demux_track->i_sample_size = 0;
729
        p_demux_track->p_sample_size =
730
            calloc( p_demux_track->i_sample_count, sizeof( uint32_t ) );
731

732 733
        for( i_sample = 0; i_sample < p_demux_track->i_sample_count; i_sample++ )
        {
734
            p_demux_track->p_sample_size[i_sample] =
735 736 737 738 739 740 741
                    p_stsz->data.p_stsz->i_entry_size[i_sample];
        }
    }
    /* we have extract all information from stsz,
        now use stts */

    /* if we don't want to waste too much memory, we can't expand
742
       the box !, so each chunk will contain an "extract" of this table
743
       for fast research */
744

745 746
    i_last_dts = 0;
    i_index = 0; i_index_sample_used =0;
747

748 749 750 751
    /* create and init last data for each chunk */
    for(i_chunk = 0 ; i_chunk < p_demux_track->i_chunk_count; i_chunk++ )
    {

752
        int64_t i_entry, i_sample_count, i;
753 754
        /* save last dts */
        p_demux_track->chunk[i_chunk].i_first_dts = i_last_dts;
755
    /* count how many entries needed for this chunk
756 757 758
       for p_sample_delta_dts and p_sample_count_dts */

        i_sample_count = p_demux_track->chunk[i_chunk].i_sample_count;
759 760

        i_entry = 0;
761 762 763 764 765
        while( i_sample_count > 0 )
        {
            i_sample_count -= p_stts->data.p_stts->i_sample_count[i_index+i_entry];
            if( i_entry == 0 )
            {
766
                i_sample_count += i_index_sample_used; /* don't count already used sample
767 768 769 770
                                                   int this entry */
            }
            i_entry++;
        }
771

772
        /* allocate them */
773
        p_demux_track->chunk[i_chunk].p_sample_count_dts =
774
            calloc( i_entry, sizeof( uint32_t ) );
775
        p_demux_track->chunk[i_chunk].p_sample_delta_dts =
776
            calloc( i_entry, sizeof( uint32_t ) );
777 778 779 780 781

        /* now copy */
        i_sample_count = p_demux_track->chunk[i_chunk].i_sample_count;
        for( i = 0; i < i_entry; i++ )
        {
782 783
            int64_t i_used;
            int64_t i_rest;
784

785 786 787 788 789
            i_rest = p_stts->data.p_stts->i_sample_count[i_index] - i_index_sample_used;

            i_used = __MIN( i_rest, i_sample_count );

            i_index_sample_used += i_used;
790
            i_sample_count -= i_used;
791 792 793 794 795

            p_demux_track->chunk[i_chunk].p_sample_count_dts[i] = i_used;

            p_demux_track->chunk[i_chunk].p_sample_delta_dts[i] =
                        p_stts->data.p_stts->i_sample_delta[i_index];
796 797

            i_last_dts += i_used *
798 799 800 801 802
                    p_demux_track->chunk[i_chunk].p_sample_delta_dts[i];

            if( i_index_sample_used >=
                             p_stts->data.p_stts->i_sample_count[i_index] )
            {
803

804 805 806 807
                i_index++;
                i_index_sample_used = 0;
            }
        }
808

809 810
    }

811 812
    msg_Dbg( p_input,
             "track[Id 0x%x] read %d samples length:"I64Fd"s",
813
             p_demux_track->i_track_ID,
814 815
             p_demux_track->i_sample_count,
             i_last_dts / p_demux_track->i_timescale );
816

817
    return( VLC_SUCCESS );
818 819
}

820 821 822 823 824 825 826
/*
 * TrackCreateES:
 *  Create ES and PES to init decoder if needed, for a track starting at i_chunk
 */
static int  TrackCreateES   ( input_thread_t   *p_input,
                              track_data_mp4_t *p_track,
                              unsigned int     i_chunk,
827
                              es_out_id_t      **pp_es )
828
{
829
    MP4_Box_t   *p_sample;
830
    MP4_Box_t   *p_esds;
831

832 833
    *pp_es = NULL;

834
    if( !p_track->chunk[i_chunk].i_sample_description_index )
835
    {
836
        msg_Warn( p_input,
837
                  "invalid SampleEntry index (track[Id 0x%x])",
838
                  p_track->i_track_ID );
839
        return VLC_EGENERIC;
840
    }
841

842
    p_sample = MP4_BoxGet(  p_track->p_stsd, "[%d]",
843
                p_track->chunk[i_chunk].i_sample_description_index - 1 );
844

845
    if( !p_sample || !p_sample->data.p_data )
846
    {
847
        msg_Warn( p_input,
848
                  "cannot find SampleEntry (track[Id 0x%x])",
849 850
                  p_track->i_track_ID );
        return( VLC_EGENERIC );
851 852
    }

853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871
    p_track->p_sample = p_sample;

    if( p_track->i_sample_size == 1 )
    {
        MP4_Box_data_sample_soun_t *p_soun;

        p_soun = p_sample->data.p_sample_soun;

        if( p_soun->i_qt_version == 0 )
        {
            switch( p_sample->i_type )
            {
                case VLC_FOURCC( 'i', 'm', 'a', '4' ):
                    p_soun->i_qt_version = 1;
                    p_soun->i_sample_per_packet = 64;
                    p_soun->i_bytes_per_packet  = 34;
                    p_soun->i_bytes_per_frame   = 34 * p_soun->i_channelcount;
                    p_soun->i_bytes_per_sample  = 2;
                    break;
872 873 874 875 876 877 878 879 880 881 882 883 884 885
                case VLC_FOURCC( 'M', 'A', 'C', '3' ):
                    p_soun->i_qt_version = 1;
                    p_soun->i_sample_per_packet = 6;
                    p_soun->i_bytes_per_packet  = 2;
                    p_soun->i_bytes_per_frame   = 2 * p_soun->i_channelcount;
                    p_soun->i_bytes_per_sample  = 2;
                    break;
                case VLC_FOURCC( 'M', 'A', 'C', '6' ):
                    p_soun->i_qt_version = 1;
                    p_soun->i_sample_per_packet = 12;
                    p_soun->i_bytes_per_packet  = 2;
                    p_soun->i_bytes_per_frame   = 2 * p_soun->i_channelcount;
                    p_soun->i_bytes_per_sample  = 2;
                    break;
886 887 888
                default:
                    break;
            }
889 890 891 892 893

        }
        else if( p_soun->i_qt_version == 1 && p_soun->i_sample_per_packet <= 0 )
        {
            p_soun->i_qt_version = 0;