]> git.sesse.net Git - vlc/blobdiff - modules/demux/mp4/mp4.c
demux: mp4: validate fragmentation after first moof
[vlc] / modules / demux / mp4 / mp4.c
index 58df1acab5c5649e22e8ba7c2990becea85704bd..25ff40a87d37924265b914a19214362d781ba431 100644 (file)
@@ -64,21 +64,39 @@ static int   DemuxFrg( demux_t * );
 static int   Seek    ( demux_t *, mtime_t );
 static int   Control ( demux_t *, int, va_list );
 
+typedef struct mp4_fragment_t mp4_fragment_t;
+struct mp4_fragment_t
+{
+    uint64_t i_chunk_range_min_offset;
+    uint64_t i_chunk_range_max_offset;
+    uint64_t i_duration;
+    MP4_Box_t *p_moox;
+    mp4_fragment_t *p_next;
+};
+
 struct demux_sys_t
 {
     MP4_Box_t    *p_root;      /* container for the whole file */
 
     mtime_t      i_pcr;
 
+    uint64_t     i_overall_duration; /* Full duration, including all fragments */
     uint64_t     i_time;         /* time position of the presentation
                                   * in movie timescale */
-    uint64_t     i_timescale;    /* movie time scale */
+    uint32_t     i_timescale;    /* movie time scale */
     uint64_t     i_duration;     /* movie duration */
     unsigned int i_tracks;       /* number of tracks */
     mp4_track_t  *track;         /* array of track */
     float        f_fps;          /* number of frame per seconds */
 
     bool         b_fragmented;   /* fMP4 */
+    bool         b_seekable;
+    bool         b_fastseekable;
+    bool         b_smooth;       /* Is it Smooth Streaming? */
+
+    bool            b_fragments_probed;
+    mp4_fragment_t  moovfragment; /* moov */
+    mp4_fragment_t *p_fragments;  /* known fragments (moof following moov) */
 
     /* */
     MP4_Box_t    *p_tref_chap;
@@ -87,6 +105,8 @@ struct demux_sys_t
     input_title_t *p_title;
 };
 
+#define BOXDATA(type) type->data.type
+
 /*****************************************************************************
  * Declaration of local function
  *****************************************************************************/
@@ -107,6 +127,13 @@ static void     MP4_TrackSetELST( demux_t *, mp4_track_t *, int64_t );
 static void     MP4_UpdateSeekpoint( demux_t * );
 static const char *MP4_ConvertMacCode( uint16_t );
 
+static MP4_Box_t * MP4_GetTrexByTrackID( MP4_Box_t *p_moov, const uint32_t i_id );
+
+static bool AddFragment( demux_t *p_demux, MP4_Box_t *p_moox );
+static int  ProbeFragments( demux_t *p_demux, bool b_force );
+
+/* Helpers */
+
 static uint32_t stream_ReadU32( stream_t *s, void *p_read, uint32_t i_toread )
 {
     uint32_t i_return = 0;
@@ -122,6 +149,47 @@ static uint32_t stream_ReadU32( stream_t *s, void *p_read, uint32_t i_toread )
     return i_return;
 }
 
+static bool MP4_stream_Tell( stream_t *s, uint64_t *pi_pos )
+{
+    int64_t i_pos = stream_Tell( s );
+    if ( i_pos < 0 )
+        return false;
+    else
+    {
+        *pi_pos = (uint64_t) i_pos;
+        return true;
+    }
+}
+
+static MP4_Box_t * MP4_GetTrexByTrackID( MP4_Box_t *p_moov, const uint32_t i_id )
+{
+    MP4_Box_t *p_trex = MP4_BoxGet( p_moov, "mvex/trex" );
+    while( p_trex )
+    {
+        if ( p_trex->i_type == ATOM_trex && BOXDATA(p_trex)->i_track_ID == i_id )
+                break;
+        else
+            p_trex = p_trex->p_next;
+    }
+    return p_trex;
+}
+
+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 &&
+            (p_tkhd = MP4_BoxGet( p_trak, "tkhd" )) &&
+            BOXDATA(p_tkhd)->i_track_ID == i_id )
+                break;
+        else
+            p_trak = p_trak->p_next;
+    }
+    return p_trak;
+}
+
 /* Return time in microsecond of a track */
 static inline int64_t MP4_TrackGetDTS( demux_t *p_demux, mp4_track_t *p_track )
 {
@@ -156,7 +224,7 @@ static inline int64_t MP4_TrackGetDTS( demux_t *p_demux, mp4_track_t *p_track )
     if( p_track->p_elst )
     {
         demux_sys_t         *p_sys = p_demux->p_sys;
-        MP4_Box_data_elst_t *elst = p_track->p_elst->data.p_elst;
+        MP4_Box_data_elst_t *elst = p_track->BOXDATA(p_elst);
 
         /* convert to offset */
         if( ( elst->i_media_rate_integer[p_track->i_elst] > 0 ||
@@ -208,11 +276,11 @@ static inline int64_t MP4_GetMoviePTS(demux_sys_t *p_sys )
 
 static void LoadChapter( demux_t  *p_demux );
 
-static int LoadInitFrag( demux_t *p_demux, const bool b_smooth )
+static int LoadInitFrag( demux_t *p_demux )
 {
     demux_sys_t *p_sys = p_demux->p_sys;
 
-    if( b_smooth ) /* Smooth Streaming */
+    if( p_sys->b_smooth ) /* Smooth Streaming */
     {
         if( ( p_sys->p_root = MP4_BoxGetSmooBox( p_demux->s ) ) == NULL )
         {
@@ -228,13 +296,13 @@ static int LoadInitFrag( demux_t *p_demux, const bool b_smooth )
             for( int i = 0; i < 3; i++ )
             {
                 MP4_Box_t *p_stra = MP4_BoxGet( p_smoo, "uuid[%d]", i );
-                if( p_stra && p_stra->data.p_stra->i_track_ID )
+                if( p_stra && BOXDATA(p_stra)->i_track_ID )
                     p_sys->i_tracks++;
                 /* Get timescale and duration of the video track; */
                 if( p_sys->i_timescale == 0 )
                 {
-                    p_sys->i_timescale = p_stra->data.p_stra->i_timescale;
-                    p_sys->i_duration = p_stra->data.p_stra->i_duration;
+                    p_sys->i_timescale = BOXDATA(p_stra)->i_timescale;
+                    p_sys->i_duration = BOXDATA(p_stra)->i_duration;
                     if( p_sys->i_timescale == 0 )
                     {
                         msg_Err( p_demux, "bad timescale" );
@@ -294,7 +362,7 @@ static void CreateTracksFromSmooBox( demux_t *p_demux )
     for( int i = 0; i < 3; i++ )
     {
         MP4_Box_t *p_stra = MP4_BoxGet( p_smoo, "uuid[%d]", i );
-        if( !p_stra || p_stra->data.p_stra->i_track_ID == 0 )
+        if( !p_stra || BOXDATA(p_stra)->i_track_ID == 0 )
             continue;
         else
         {
@@ -321,7 +389,6 @@ static int Open( vlc_object_t * p_this )
     MP4_Box_t       *p_trak;
 
     unsigned int    i;
-    bool      b_seekable;
     bool      b_enabled_es;
 
     /* A little test to see if it could be a mp4 */
@@ -349,63 +416,77 @@ static int Open( vlc_object_t * p_this )
             return VLC_EGENERIC;
     }
 
+    /* create our structure that will contains all data */
+    p_sys = calloc( 1, sizeof( demux_sys_t ) );
+    if ( !p_sys )
+        return VLC_EGENERIC;
+
     /* I need to seek */
-    stream_Control( p_demux->s, STREAM_CAN_SEEK, &b_seekable );
-    if( !b_seekable )
+    stream_Control( p_demux->s, STREAM_CAN_SEEK, &p_sys->b_seekable );
+    if( !p_sys->b_seekable )
     {
         msg_Warn( p_demux, "MP4 plugin discarded (not seekable)" );
+        free( p_sys );
         return VLC_EGENERIC;
     }
+    stream_Control( p_demux->s, STREAM_CAN_FASTSEEK, &p_sys->b_fastseekable );
 
     /*Set exported functions */
     p_demux->pf_demux = Demux;
     p_demux->pf_control = Control;
 
-    /* create our structure that will contains all data */
-    p_demux->p_sys = p_sys = calloc( 1, sizeof( demux_sys_t ) );
+    p_demux->p_sys = p_sys;
 
-    /* Is it Smooth Streaming? */
-    bool b_smooth = false;
     if( stream_Peek( p_demux->s, &p_peek, 24 ) < 24 ) return VLC_EGENERIC;
     if( !CmpUUID( (UUID_t *)(p_peek + 8), &SmooBoxUUID ) )
     {
-        b_smooth = true;
+        p_sys->b_smooth = true;
         p_sys->b_fragmented = true;
     }
 
-    if( LoadInitFrag( p_demux, b_smooth ) != VLC_SUCCESS )
+    if( LoadInitFrag( p_demux ) != VLC_SUCCESS )
         goto error;
 
     if( MP4_BoxCount( p_sys->p_root, "/moov/mvex" ) > 0 )
     {
-        p_sys->b_fragmented = true;
+        if ( p_sys->b_seekable )
+        {
+            /* Probe remaining to check if there's really fragments
+               or if that file is just ready to append fragments */
+            ProbeFragments( p_demux, false );
+            p_sys->b_fragmented = !!MP4_BoxCount( p_sys->p_root, "/moof" );
+        }
+        else
+            p_sys->b_fragmented = true;
     }
-    if( p_sys->b_fragmented )
+
+    if ( !p_sys->moovfragment.p_moox )
+        AddFragment( p_demux, MP4_BoxGet( p_sys->p_root, "/moov" ) );
+
+    /* we always need a moov entry, but smooth has a workaround */
+    if ( !p_sys->moovfragment.p_moox && !p_sys->b_smooth )
+    {
+        goto error;
+    }
+
+    if( p_sys->b_fragmented || p_sys->b_smooth )
     {
         p_demux->pf_demux = DemuxFrg;
     }
 
-    stream_Control( p_demux->s, STREAM_CAN_FASTSEEK, &b_seekable );
-    if( b_smooth )
+    if( p_sys->b_smooth )
     {
         if( InitTracks( p_demux ) != VLC_SUCCESS )
             goto error;
         CreateTracksFromSmooBox( p_demux );
         return VLC_SUCCESS;
     }
-    else if( p_sys->b_fragmented && b_seekable )
+    else if( p_sys->b_fragmented )
     {
         /* We are not yet able to demux a fragmented MP4 file, using the 'mfra'
-         * box. So if STREAM_CAN_FASTSEEK is true, we're assuming we've got such
          * a file, and we let avformat do the job. */
         msg_Warn( p_demux, "MP4 plugin discarded "\
-                "(fast-seekable and fragmented, let avformat demux it)" );
-        stream_Seek( p_demux->s, 0 ); /* rewind, for other demux */
-        goto error;
-    }
-    else if( !p_sys->b_fragmented && !b_seekable )
-    {
-        msg_Warn( p_demux, "MP4 plugin discarded (not fast-seekable)" );
+                "(fragmented, let avformat demux it)" );
         stream_Seek( p_demux->s, 0 ); /* rewind, for other demux */
         goto error;
     }
@@ -414,12 +495,12 @@ static int Open( vlc_object_t * p_this )
 
     if( ( p_ftyp = MP4_BoxGet( p_sys->p_root, "/ftyp" ) ) )
     {
-        switch( p_ftyp->data.p_ftyp->i_major_brand )
+        switch( BOXDATA(p_ftyp)->i_major_brand )
         {
             case( ATOM_isom ):
                 msg_Dbg( p_demux,
                          "ISO Media file (isom) version %d.",
-                         p_ftyp->data.p_ftyp->i_minor_version );
+                         BOXDATA(p_ftyp)->i_minor_version );
                 break;
             case( ATOM_3gp4 ):
             case( VLC_FOURCC( '3', 'g', 'p', '5' ) ):
@@ -427,9 +508,9 @@ static int Open( vlc_object_t * p_this )
             case( VLC_FOURCC( '3', 'g', 'p', '7' ) ):
                 msg_Dbg( p_demux, "3GPP Media file Release: %c",
 #ifdef WORDS_BIGENDIAN
-                        p_ftyp->data.p_ftyp->i_major_brand
+                        BOXDATA(p_ftyp)->i_major_brand
 #else
-                        p_ftyp->data.p_ftyp->i_major_brand >> 24
+                        BOXDATA(p_ftyp)->i_major_brand >> 24
 #endif
                         );
                 break;
@@ -442,7 +523,7 @@ static int Open( vlc_object_t * p_this )
             default:
                 msg_Dbg( p_demux,
                          "unrecognized major file specification (%4.4s).",
-                          (char*)&p_ftyp->data.p_ftyp->i_major_brand );
+                          (char*)&BOXDATA(p_ftyp)->i_major_brand );
                 break;
         }
     }
@@ -452,7 +533,8 @@ static int Open( vlc_object_t * p_this )
     }
 
     /* the file need to have one moov box */
-    if( MP4_BoxCount( p_sys->p_root, "/moov" ) <= 0 )
+    p_sys->moovfragment.p_moox = MP4_BoxGet( p_sys->p_root, "/moov", 0 );
+    if( !p_sys->moovfragment.p_moox )
     {
         MP4_Box_t *p_foov = MP4_BoxGet( p_sys->p_root, "/foov" );
 
@@ -463,6 +545,7 @@ static int Open( vlc_object_t * p_this )
         }
         /* we have a free box as a moov, rename it */
         p_foov->i_type = ATOM_moov;
+        p_sys->moovfragment.p_moox = p_foov;
     }
 
     if( ( p_rmra = MP4_BoxGet( p_sys->p_root,  "/moov/rmra" ) ) )
@@ -483,11 +566,11 @@ static int Open( vlc_object_t * p_this )
             char      *psz_ref;
             uint32_t  i_ref_type;
 
-            if( !p_rdrf || !( psz_ref = strdup( p_rdrf->data.p_rdrf->psz_ref ) ) )
+            if( !p_rdrf || !( psz_ref = strdup( BOXDATA(p_rdrf)->psz_ref ) ) )
             {
                 continue;
             }
-            i_ref_type = p_rdrf->data.p_rdrf->i_ref_type;
+            i_ref_type = BOXDATA(p_rdrf)->i_ref_type;
 
             msg_Dbg( p_demux, "new ref=`%s' type=%4.4s",
                      psz_ref, (char*)&i_ref_type );
@@ -535,7 +618,7 @@ static int Open( vlc_object_t * p_this )
             else
             {
                 msg_Err( p_demux, "unknown ref type=%4.4s FIXME (send a bug report)",
-                         (char*)&p_rdrf->data.p_rdrf->i_ref_type );
+                         (char*)&BOXDATA(p_rdrf)->i_ref_type );
             }
             free( psz_ref );
         }
@@ -559,21 +642,22 @@ static int Open( vlc_object_t * p_this )
     }
     else
     {
-        p_sys->i_timescale = p_mvhd->data.p_mvhd->i_timescale;
+        p_sys->i_timescale = BOXDATA(p_mvhd)->i_timescale;
         if( p_sys->i_timescale == 0 )
         {
             msg_Err( p_this, "bad timescale" );
             goto error;
         }
-        p_sys->i_duration = p_mvhd->data.p_mvhd->i_duration;
     }
 
-    /* Try in mehd if fragmented */
-    if ( p_sys->i_duration == 0 )
+    if ( p_sys->i_overall_duration == 0 )
     {
+        /* Try in mehd if fragmented */
         MP4_Box_t *p_mehd = MP4_BoxGet( p_demux->p_sys->p_root, "moov/mvex/mehd");
         if ( p_mehd )
-            p_sys->i_duration = p_mehd->data.p_mehd->i_fragment_duration;
+            p_sys->i_overall_duration = p_mehd->data.p_mehd->i_fragment_duration;
+        else
+            p_sys->i_overall_duration = p_sys->moovfragment.i_duration;
     }
 
     if( !( p_sys->i_tracks = MP4_BoxCount( p_sys->p_root, "/moov/trak" ) ) )
@@ -598,7 +682,7 @@ static int Open( vlc_object_t * p_this )
 
 
         MP4_Box_t *p_tkhd = MP4_BoxGet( p_trak, "tkhd" );
-        if( p_tkhd && (p_tkhd->data.p_tkhd->i_flags&MP4_TRACK_ENABLED) )
+        if( p_tkhd && (BOXDATA(p_tkhd)->i_flags&MP4_TRACK_ENABLED) )
             b_enabled_es = true;
 
         MP4_Box_t *p_chap = MP4_BoxGet( p_trak, "tref/chap", i );
@@ -652,6 +736,15 @@ static int Open( vlc_object_t * p_this )
         }
     }
 
+    mp4_fragment_t *p_fragment = &p_sys->moovfragment;
+    while ( p_fragment )
+    {
+        msg_Dbg( p_demux, "fragment offset %"PRId64", data %"PRId64"<->%"PRId64", time %"PRId64,
+                 p_fragment->p_moox->i_pos, p_fragment->i_chunk_range_min_offset,
+                 p_fragment->i_chunk_range_max_offset, p_fragment->i_duration );
+        p_fragment = p_fragment->p_next;
+    }
+
     /* */
     LoadChapter( p_demux );
 
@@ -715,7 +808,7 @@ static int Demux( demux_t *p_demux )
         if( p_sys->i_timescale > 0 )
         {
             int64_t i_length = CLOCK_FREQ *
-                               (mtime_t)p_sys->i_duration /
+                               (mtime_t)p_sys->moovfragment.i_duration /
                                (mtime_t)p_sys->i_timescale;
             if( MP4_GetMoviePTS( p_sys ) >= i_length )
                 return 0;
@@ -732,85 +825,98 @@ static int Demux( demux_t *p_demux )
     /* first wait for the good time to read a packet */
     p_sys->i_pcr = MP4_GetMoviePTS( p_sys );
 
-    /* we will read 100ms for each stream so ...*/
-    mtime_t i_targettime = p_sys->i_pcr + CLOCK_FREQ/10;
     bool b_data_sent = false;
 
+    /* Find next track matching contiguous data */
+    mp4_track_t *tk = NULL;
+    uint64_t i_candidate_pos = UINT64_MAX;
     for( i_track = 0; i_track < p_sys->i_tracks; i_track++ )
     {
-        mp4_track_t *tk = &p_sys->track[i_track];
-
-        if( !tk->b_ok || tk->b_chapter || !tk->b_selected || tk->i_sample >= tk->i_sample_count )
+        mp4_track_t *tk_tmp = &p_sys->track[i_track];
+        if( !tk_tmp->b_ok || tk_tmp->b_chapter || !tk_tmp->b_selected || tk_tmp->i_sample >= tk_tmp->i_sample_count )
             continue;
 
-        while( MP4_TrackGetDTS( p_demux, tk ) < i_targettime
-               || ( p_sys->i_pcr == VLC_TS_INVALID && !b_data_sent ) )
+        uint64_t i_pos = MP4_TrackGetPos( tk_tmp );
+        if ( i_pos <= i_candidate_pos )
         {
+            i_candidate_pos = i_pos;
+            tk = tk_tmp;
+        }
+    }
+
+    if ( !tk )
+    {
+        msg_Dbg( p_demux, "Could not select track by data position" );
+        goto end;
+    }
+
 #if 0
-            msg_Dbg( p_demux, "tk(%i)=%lld mv=%lld", i_track,
-                     MP4_TrackGetDTS( p_demux, tk ),
-                     MP4_GetMoviePTS( p_sys ) );
+    msg_Dbg( p_demux, "tk(%i)=%"PRId64" mv=%"PRId64" pos=%"PRIu64, i_track,
+             MP4_TrackGetDTS( p_demux, tk ),
+             MP4_GetMoviePTS( p_sys ), i_candidate_pos );
 #endif
-            uint32_t i_nb_samples = 0;
-            uint32_t i_samplessize = MP4_TrackSampleSize( tk, &i_nb_samples );
-            if( i_samplessize > 0 )
-            {
-                block_t *p_block;
-                int64_t i_delta, i_newpos;
-
-                /* go,go go ! */
-                i_newpos = MP4_TrackGetPos( tk );
-                if( stream_Tell( p_demux->s ) != i_newpos )
-                {
-                    if( stream_Seek( p_demux->s, i_newpos ) )
-                    {
-                        msg_Warn( p_demux, "track[0x%x] will be disabled (eof?)",
-                                  tk->i_track_ID );
-                        MP4_TrackUnselect( p_demux, tk );
-                        break;
-                    }
-                }
 
-                /* now read pes */
-                if( !(p_block = stream_Block( p_demux->s, i_samplessize )) )
-                {
-                    msg_Warn( p_demux, "track[0x%x] will be disabled (eof?)",
-                              tk->i_track_ID );
-                    MP4_TrackUnselect( p_demux, tk );
-                    break;
-                }
-                else if( tk->fmt.i_cat == SPU_ES )
-                {
-                    if ( tk->fmt.i_codec != VLC_CODEC_TX3G &&
-                         tk->fmt.i_codec != VLC_CODEC_SPU )
-                        p_block->i_buffer = 0;
-                }
+    uint32_t i_nb_samples = 0;
+    uint32_t i_samplessize = MP4_TrackSampleSize( tk, &i_nb_samples );
+    if( i_samplessize > 0 )
+    {
+        block_t *p_block;
+        int64_t i_delta;
+        uint64_t i_current_pos;
 
-                /* dts */
-                p_block->i_dts = VLC_TS_0 + MP4_TrackGetDTS( p_demux, tk );
-                /* pts */
-                i_delta = MP4_TrackGetPTSDelta( p_demux, tk );
-                if( i_delta != -1 )
-                    p_block->i_pts = p_block->i_dts + i_delta;
-                else if( tk->fmt.i_cat != VIDEO_ES )
-                    p_block->i_pts = p_block->i_dts;
-                else
-                    p_block->i_pts = VLC_TS_INVALID;
+        /* go,go go ! */
+        if ( !MP4_stream_Tell( p_demux->s, &i_current_pos ) )
+            goto end;
 
-                if ( !b_data_sent )
-                {
-                    es_out_Control( p_demux->out, ES_OUT_SET_PCR, VLC_TS_0 + p_sys->i_pcr );
-                    b_data_sent = true;
-                }
-                es_out_Send( p_demux->out, tk->p_es, p_block );
+        if( i_current_pos != i_candidate_pos )
+        {
+            if( stream_Seek( p_demux->s, i_candidate_pos ) )
+            {
+                msg_Warn( p_demux, "track[0x%x] will be disabled (eof?)",
+                          tk->i_track_ID );
+                MP4_TrackUnselect( p_demux, tk );
+                goto end;
             }
+        }
 
-            /* Next sample */
-            if( MP4_TrackNextSample( p_demux, tk, i_nb_samples ) )
-                break;
+        /* now read pes */
+        if( !(p_block = stream_Block( p_demux->s, i_samplessize )) )
+        {
+            msg_Warn( p_demux, "track[0x%x] will be disabled (eof?)",
+                      tk->i_track_ID );
+            MP4_TrackUnselect( p_demux, tk );
+            goto end;
+        }
+        else if( tk->fmt.i_cat == SPU_ES )
+        {
+            if ( tk->fmt.i_codec != VLC_CODEC_TX3G &&
+                 tk->fmt.i_codec != VLC_CODEC_SPU )
+                p_block->i_buffer = 0;
+        }
+
+        /* dts */
+        p_block->i_dts = VLC_TS_0 + MP4_TrackGetDTS( p_demux, tk );
+        /* pts */
+        i_delta = MP4_TrackGetPTSDelta( p_demux, tk );
+        if( i_delta != -1 )
+            p_block->i_pts = p_block->i_dts + i_delta;
+        else if( tk->fmt.i_cat != VIDEO_ES )
+            p_block->i_pts = p_block->i_dts;
+        else
+            p_block->i_pts = VLC_TS_INVALID;
+
+        if ( !b_data_sent )
+        {
+            es_out_Control( p_demux->out, ES_OUT_SET_PCR, VLC_TS_0 + p_sys->i_pcr );
+            b_data_sent = true;
         }
+        es_out_Send( p_demux->out, tk->p_es, p_block );
+
+        /* Next sample */
+        MP4_TrackNextSample( p_demux, tk, i_nb_samples );
     }
 
+end:
     if ( b_data_sent )
     {
         p_sys->i_pcr = INT64_MAX;
@@ -884,7 +990,7 @@ static int MP4_frg_Seek( demux_t *p_demux, double f )
     else
     {
         /* update global time */
-        p_sys->i_time = (uint64_t)(f * (double)p_sys->i_duration);
+        p_sys->i_time = (uint64_t)(f * (double)p_sys->moovfragment.i_duration);
         p_sys->i_pcr  = MP4_GetMoviePTS( p_sys );
 
         for( unsigned i_track = 0; i_track < p_sys->i_tracks; i_track++ )
@@ -920,9 +1026,9 @@ static int Control( demux_t *p_demux, int i_query, va_list args )
     {
         case DEMUX_GET_POSITION:
             pf = (double*)va_arg( args, double * );
-            if( p_sys->i_duration > 0 )
+            if( p_sys->i_overall_duration > 0 )
             {
-                *pf = (double)p_sys->i_time / (double)p_sys->i_duration;
+                *pf = (double)p_sys->i_time / (double)p_sys->i_overall_duration;
             }
             else
             {
@@ -939,7 +1045,7 @@ static int Control( demux_t *p_demux, int i_query, va_list args )
             else if( p_sys->i_timescale > 0 )
             {
                 i64 = (int64_t)( f * CLOCK_FREQ *
-                                 (double)p_sys->i_duration /
+                                 (double)p_sys->i_overall_duration /
                                  (double)p_sys->i_timescale );
                 return Seek( p_demux, i64 );
             }
@@ -965,7 +1071,7 @@ static int Control( demux_t *p_demux, int i_query, va_list args )
             if( p_sys->i_timescale > 0 )
             {
                 *pi64 = CLOCK_FREQ *
-                        (mtime_t)p_sys->i_duration /
+                        (mtime_t)p_sys->i_overall_duration /
                         (mtime_t)p_sys->i_timescale;
             }
             else *pi64 = 0;
@@ -1065,12 +1171,12 @@ static int Control( demux_t *p_demux, int i_query, va_list args )
                  p_0xa9xxx = p_0xa9xxx->p_next )
             {
 
-                if( !p_0xa9xxx || !p_0xa9xxx->data.p_0xa9xxx )
+                if( !p_0xa9xxx || !BOXDATA(p_0xa9xxx) )
                     continue;
 
                 /* FIXME FIXME: should convert from whatever the character
                  * encoding of MP4 meta data is to UTF-8. */
-#define SET(fct) do { char *psz_utf = strdup( p_0xa9xxx->data.p_0xa9xxx->psz_text ? p_0xa9xxx->data.p_0xa9xxx->psz_text : "" ); \
+#define SET(fct) do { char *psz_utf = strdup( BOXDATA(p_0xa9xxx)->psz_text ? BOXDATA(p_0xa9xxx)->psz_text : "" ); \
     if( psz_utf ) { EnsureUTF8( psz_utf );  \
                     fct( p_meta, psz_utf ); free( psz_utf ); } } while(0)
 
@@ -1191,7 +1297,7 @@ static int Control( demux_t *p_demux, int i_query, va_list args )
                 {
                     if( p_0xa9xxx->i_type == xa9typetoextrameta[i].xa9_type )
                     {
-                        char *psz_utf = strdup( p_0xa9xxx->data.p_0xa9xxx->psz_text ? p_0xa9xxx->data.p_0xa9xxx->psz_text : "" );
+                        char *psz_utf = strdup( BOXDATA(p_0xa9xxx)->psz_text ? BOXDATA(p_0xa9xxx)->psz_text : "" );
                         if( psz_utf )
                         {
                              EnsureUTF8( psz_utf );
@@ -1271,6 +1377,13 @@ static void Close ( vlc_object_t * p_this )
     if( p_sys->p_title )
         vlc_input_title_Delete( p_sys->p_title );
 
+    while( p_sys->moovfragment.p_next )
+    {
+        mp4_fragment_t *p_fragment = p_sys->moovfragment.p_next->p_next;
+        free( p_sys->moovfragment.p_next );
+        p_sys->moovfragment.p_next = p_fragment;
+    }
+
     free( p_sys );
 }
 
@@ -1286,13 +1399,13 @@ static void LoadChapterGpac( demux_t  *p_demux, MP4_Box_t *p_chpl )
     int i;
 
     p_sys->p_title = vlc_input_title_New();
-    for( i = 0; i < p_chpl->data.p_chpl->i_chapter; i++ )
+    for( i = 0; i < BOXDATA(p_chpl)->i_chapter; i++ )
     {
         seekpoint_t *s = vlc_seekpoint_New();
 
-        s->psz_name = strdup( p_chpl->data.p_chpl->chapter[i].psz_name );
+        s->psz_name = strdup( BOXDATA(p_chpl)->chapter[i].psz_name );
         EnsureUTF8( s->psz_name );
-        s->i_time_offset = p_chpl->data.p_chpl->chapter[i].i_start / 10;
+        s->i_time_offset = BOXDATA(p_chpl)->chapter[i].i_start / 10;
         TAB_APPEND( p_sys->p_title->i_seekpoint, p_sys->p_title->seekpoint, s );
     }
 }
@@ -1338,7 +1451,7 @@ static void LoadChapter( demux_t  *p_demux )
     demux_sys_t *p_sys = p_demux->p_sys;
     MP4_Box_t *p_chpl;
 
-    if( ( p_chpl = MP4_BoxGet( p_sys->p_root, "/moov/udta/chpl" ) ) && p_chpl->data.p_chpl->i_chapter > 0 )
+    if( ( p_chpl = MP4_BoxGet( p_sys->p_root, "/moov/udta/chpl" ) ) && BOXDATA(p_chpl)->i_chapter > 0 )
     {
         LoadChapterGpac( p_demux, p_chpl );
     }
@@ -1369,7 +1482,7 @@ static void LoadChapter( demux_t  *p_demux )
     if( p_sys->p_title )
     {
         p_sys->p_title->i_length = CLOCK_FREQ *
-                       (uint64_t)p_sys->i_duration / (uint64_t)p_sys->i_timescale;
+                       (uint64_t)p_sys->i_overall_duration / (uint64_t)p_sys->i_timescale;
     }
 }
 
@@ -1378,8 +1491,6 @@ static int TrackCreateChunksIndex( demux_t *p_demux,
                                    mp4_track_t *p_demux_track )
 {
     demux_sys_t *p_sys = p_demux->p_sys;
-    if( p_sys->b_fragmented )
-        return VLC_SUCCESS;
 
     MP4_Box_t *p_co64; /* give offset for each chunk, same for stco and co64 */
     MP4_Box_t *p_stsc;
@@ -1394,11 +1505,10 @@ static int TrackCreateChunksIndex( demux_t *p_demux,
         return( VLC_EGENERIC );
     }
 
-    p_demux_track->i_chunk_count = p_co64->data.p_co64->i_entry_count;
+    p_demux_track->i_chunk_count = BOXDATA(p_co64)->i_entry_count;
     if( !p_demux_track->i_chunk_count )
     {
         msg_Warn( p_demux, "no chunk defined" );
-        return( VLC_EGENERIC );
     }
     p_demux_track->chunk = calloc( p_demux_track->i_chunk_count,
                                    sizeof( mp4_chunk_t ) );
@@ -1412,7 +1522,7 @@ static int TrackCreateChunksIndex( demux_t *p_demux,
     {
         mp4_chunk_t *ck = &p_demux_track->chunk[i_chunk];
 
-        ck->i_offset = p_co64->data.p_co64->i_chunk_offset[i_chunk];
+        ck->i_offset = BOXDATA(p_co64)->i_chunk_offset[i_chunk];
 
         ck->i_first_dts = 0;
         ck->p_sample_count_dts = NULL;
@@ -1425,16 +1535,11 @@ static int TrackCreateChunksIndex( demux_t *p_demux,
         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 )
-    {
-        msg_Warn( p_demux, "cannot read chunk table or table empty" );
-        return( VLC_EGENERIC );
-    }
+    i_index = BOXDATA(p_stsc)->i_entry_count;
 
-    while( i_index-- )
+    while( i_index-- > 0 )
     {
-        for( i_chunk = p_stsc->data.p_stsc->i_first_chunk[i_index] - 1;
+        for( i_chunk = BOXDATA(p_stsc)->i_first_chunk[i_index] - 1;
              i_chunk < i_last; i_chunk++ )
         {
             if( i_chunk >= p_demux_track->i_chunk_count )
@@ -1444,11 +1549,11 @@ static int TrackCreateChunksIndex( demux_t *p_demux,
             }
 
             p_demux_track->chunk[i_chunk].i_sample_description_index =
-                    p_stsc->data.p_stsc->i_sample_description_index[i_index];
+                    BOXDATA(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];
+                    BOXDATA(p_stsc)->i_samples_per_chunk[i_index];
         }
-        i_last = p_stsc->data.p_stsc->i_first_chunk[i_index] - 1;
+        i_last = BOXDATA(p_stsc)->i_first_chunk[i_index] - 1;
     }
 
     p_demux_track->chunk[0].i_sample_first = 0;
@@ -1462,6 +1567,12 @@ static int TrackCreateChunksIndex( demux_t *p_demux,
     msg_Dbg( p_demux, "track[Id 0x%x] read %d chunk",
              p_demux_track->i_track_ID, p_demux_track->i_chunk_count );
 
+    if ( p_demux_track->i_chunk_count && (
+             p_sys->moovfragment.i_chunk_range_min_offset == 0 ||
+             p_sys->moovfragment.i_chunk_range_min_offset > p_demux_track->chunk[0].i_offset
+             ) )
+        p_sys->moovfragment.i_chunk_range_min_offset = p_demux_track->chunk[0].i_offset;
+
     return VLC_SUCCESS;
 }
 
@@ -1517,8 +1628,6 @@ static int TrackCreateSamplesIndex( demux_t *p_demux,
                                     mp4_track_t *p_demux_track )
 {
     demux_sys_t *p_sys = p_demux->p_sys;
-    if( p_sys->b_fragmented )
-        return VLC_SUCCESS;
 
     MP4_Box_t *p_box;
     MP4_Box_data_stsz_t *stsz;
@@ -1561,6 +1670,22 @@ static int TrackCreateSamplesIndex( demux_t *p_demux,
         }
     }
 
+    if ( p_demux_track->i_chunk_count )
+    {
+        mp4_chunk_t *lastchunk = &p_demux_track->chunk[p_demux_track->i_chunk_count - 1];
+        uint64_t i_total_size = lastchunk->i_offset;
+        for( uint32_t i=0; i<lastchunk->i_sample_count; i++)
+        {
+            if( p_demux_track->i_sample_size == 0 )
+                i_total_size += stsz->i_entry_size[i];
+            else
+                i_total_size += p_demux_track->i_sample_size;
+        }
+
+        if ( i_total_size > p_sys->moovfragment.i_chunk_range_max_offset )
+            p_sys->moovfragment.i_chunk_range_max_offset = i_total_size;
+    }
+
     /* Use stts table to create a sample number -> dts table.
      * XXX: if we don't want to waste too much memory, we can't expand
      *  the box! so each chunk will contain an "extract" of this table
@@ -1779,7 +1904,8 @@ static int TrackCreateSamplesIndex( demux_t *p_demux,
  * It computes the sample rate for a video track using the given sample
  * description index
  */
-static void TrackGetESSampleRate( unsigned *pi_num, unsigned *pi_den,
+static void TrackGetESSampleRate( demux_t *p_demux,
+                                  unsigned *pi_num, unsigned *pi_den,
                                   const mp4_track_t *p_track,
                                   unsigned i_sd_index,
                                   unsigned i_chunk )
@@ -1787,6 +1913,18 @@ static void TrackGetESSampleRate( unsigned *pi_num, unsigned *pi_den,
     *pi_num = 0;
     *pi_den = 0;
 
+    MP4_Box_t *p_trak = MP4_GetTrakByTrackID( MP4_BoxGet( p_demux->p_sys->p_root, "/moov" ),
+                                              p_track->i_track_ID );
+    MP4_Box_t *p_mdhd = MP4_BoxGet( p_trak, "mdia/mdhd" );
+    if ( p_mdhd )
+    {
+        vlc_ureduce( pi_num, pi_den,
+                     (uint64_t) BOXDATA(p_mdhd)->i_timescale * p_track->i_sample_count,
+                     (uint64_t) BOXDATA(p_mdhd)->i_duration,
+                     UINT16_MAX );
+        return;
+    }
+
     if( p_track->i_chunk_count <= 0 )
         return;
 
@@ -1910,9 +2048,11 @@ static int TrackCreateES( demux_t *p_demux, mp4_track_t *p_track,
         p_track->fmt.video.i_visible_height = p_track->fmt.video.i_height;
 
         /* Frame rate */
-        TrackGetESSampleRate( &p_track->fmt.video.i_frame_rate,
+        TrackGetESSampleRate( p_demux,
+                              &p_track->fmt.video.i_frame_rate,
                               &p_track->fmt.video.i_frame_rate_base,
                               p_track, i_sample_description_index, i_chunk );
+
         p_demux->p_sys->f_fps = (float)p_track->fmt.video.i_frame_rate /
                                 (float)p_track->fmt.video.i_frame_rate_base;
 
@@ -2086,7 +2226,7 @@ static int TrackCreateES( demux_t *p_demux, mp4_track_t *p_track,
                 MP4_Box_data_sample_soun_t *p_soun =
                     p_sample->data.p_sample_soun;
 
-                msg_Warn( p_demux, "i_timescale (%"PRIu64") != i_sampleratehi "
+                msg_Warn( p_demux, "i_timescale (%"PRId32") != i_sampleratehi "
                           "(%u), making both equal (report any problem).",
                           p_track->i_timescale, p_soun->i_sampleratehi );
 
@@ -2144,19 +2284,19 @@ static int TrackCreateES( demux_t *p_demux, mp4_track_t *p_track,
             break;
 
         case VLC_FOURCC('i','n','2','4'):
-            p_track->fmt.i_codec = p_enda && p_enda->data.p_enda->i_little_endian == 1 ?
+            p_track->fmt.i_codec = p_enda && BOXDATA(p_enda)->i_little_endian == 1 ?
                                     VLC_FOURCC('4','2','n','i') : VLC_FOURCC('i','n','2','4');
             break;
         case VLC_FOURCC('i','n','3','2'):
-            p_track->fmt.i_codec = p_enda && p_enda->data.p_enda->i_little_endian == 1 ?
+            p_track->fmt.i_codec = p_enda && BOXDATA(p_enda)->i_little_endian == 1 ?
                                     VLC_CODEC_S32L : VLC_CODEC_S32B;
             break;
         case VLC_FOURCC('f','l','3','2'):
-            p_track->fmt.i_codec = p_enda && p_enda->data.p_enda->i_little_endian == 1 ?
+            p_track->fmt.i_codec = p_enda && BOXDATA(p_enda)->i_little_endian == 1 ?
                                     VLC_CODEC_F32L : VLC_CODEC_F32B;
             break;
         case VLC_FOURCC('f','l','6','4'):
-            p_track->fmt.i_codec = p_enda && p_enda->data.p_enda->i_little_endian == 1 ?
+            p_track->fmt.i_codec = p_enda && BOXDATA(p_enda)->i_little_endian == 1 ?
                                     VLC_CODEC_F64L : VLC_CODEC_F64B;
             break;
         case VLC_CODEC_DVD_LPCM:
@@ -2417,11 +2557,11 @@ static int TrackCreateES( demux_t *p_demux, mp4_track_t *p_track,
                 MP4_Box_t *p_dvc1 = MP4_BoxGet( p_sample, "dvc1" );
                 if( p_dvc1 )
                 {
-                    p_track->fmt.i_extra = p_dvc1->data.p_dvc1->i_vc1;
+                    p_track->fmt.i_extra = BOXDATA(p_dvc1)->i_vc1;
                     if( p_track->fmt.i_extra > 0 )
                     {
-                        p_track->fmt.p_extra = malloc( p_dvc1->data.p_dvc1->i_vc1 );
-                        memcpy( p_track->fmt.p_extra, p_dvc1->data.p_dvc1->p_vc1,
+                        p_track->fmt.p_extra = malloc( BOXDATA(p_dvc1)->i_vc1 );
+                        memcpy( p_track->fmt.p_extra, BOXDATA(p_dvc1)->p_vc1,
                                 p_track->fmt.i_extra );
                     }
                 }
@@ -2439,11 +2579,11 @@ static int TrackCreateES( demux_t *p_demux, mp4_track_t *p_track,
 
                 if( p_avcC )
                 {
-                    p_track->fmt.i_extra = p_avcC->data.p_avcC->i_avcC;
+                    p_track->fmt.i_extra = BOXDATA(p_avcC)->i_avcC;
                     if( p_track->fmt.i_extra > 0 )
                     {
-                        p_track->fmt.p_extra = malloc( p_avcC->data.p_avcC->i_avcC );
-                        memcpy( p_track->fmt.p_extra, p_avcC->data.p_avcC->p_avcC,
+                        p_track->fmt.p_extra = malloc( BOXDATA(p_avcC)->i_avcC );
+                        memcpy( p_track->fmt.p_extra, BOXDATA(p_avcC)->p_avcC,
                                 p_track->fmt.i_extra );
                     }
                 }
@@ -2517,9 +2657,9 @@ static int TrackTimeToSampleChunk( demux_t *p_demux, mp4_track_t *p_track,
 
     /* handle elst (find the correct one) */
     MP4_TrackSetELST( p_demux, p_track, i_start );
-    if( p_track->p_elst && p_track->p_elst->data.p_elst->i_entry_count > 0 )
+    if( p_track->p_elst && p_track->BOXDATA(p_elst)->i_entry_count > 0 )
     {
-        MP4_Box_data_elst_t *elst = p_track->p_elst->data.p_elst;
+        MP4_Box_data_elst_t *elst = p_track->BOXDATA(p_elst);
         int64_t i_mvt= i_start * p_sys->i_timescale / CLOCK_FREQ;
 
         /* now calculate i_start for this elst */
@@ -2621,7 +2761,7 @@ static int TrackTimeToSampleChunk( demux_t *p_demux, mp4_track_t *p_track,
                 i_sample < p_stss->i_sample_number[i_index+1] )
             {
                 unsigned i_sync_sample = p_stss->i_sample_number[i_index];
-                msg_Dbg( p_demux, "stts gives %d --> %d (sample number)",
+                msg_Dbg( p_demux, "stss gives %d --> %d (sample number)",
                          i_sample, i_sync_sample );
 
                 if( i_sync_sample <= i_sample )
@@ -2740,15 +2880,15 @@ static void MP4_TrackCreate( demux_t *p_demux, mp4_track_t *p_track,
 
     /* do we launch this track by default ? */
     p_track->b_enable =
-        ( ( p_tkhd->data.p_tkhd->i_flags&MP4_TRACK_ENABLED ) != 0 );
+        ( ( BOXDATA(p_tkhd)->i_flags&MP4_TRACK_ENABLED ) != 0 );
     if( !p_track->b_enable )
         p_track->fmt.i_priority = ES_PRIORITY_NOT_DEFAULTABLE;
 
-    p_track->i_track_ID = p_tkhd->data.p_tkhd->i_track_ID;
+    p_track->i_track_ID = BOXDATA(p_tkhd)->i_track_ID;
 
-    p_track->i_width = p_tkhd->data.p_tkhd->i_width / BLOCK16x16;
-    p_track->i_height = p_tkhd->data.p_tkhd->i_height / BLOCK16x16;
-    p_track->f_rotation = p_tkhd->data.p_tkhd->f_rotation;
+    p_track->i_width = BOXDATA(p_tkhd)->i_width / BLOCK16x16;
+    p_track->i_height = BOXDATA(p_tkhd)->i_height / BLOCK16x16;
+    p_track->f_rotation = BOXDATA(p_tkhd)->f_rotation;
 
     if( p_tref )
     {
@@ -2763,21 +2903,21 @@ static void MP4_TrackCreate( demux_t *p_demux, mp4_track_t *p_track,
         return;
     }
 
-    p_track->i_timescale = p_mdhd->data.p_mdhd->i_timescale;
+    p_track->i_timescale = BOXDATA(p_mdhd)->i_timescale;
     if( p_track->i_timescale == 0 )
         return;
 
-    if( p_mdhd->data.p_mdhd->i_language_code < 0x400 )
+    if( BOXDATA(p_mdhd)->i_language_code < 0x400 )
     {
-        strcpy( language, MP4_ConvertMacCode( p_mdhd->data.p_mdhd->i_language_code ) );
+        strcpy( language, MP4_ConvertMacCode( BOXDATA(p_mdhd)->i_language_code ) );
         p_track->b_mac_encoding = true;
     }
-    else if( p_mdhd->data.p_mdhd->i_language_code == 0x7fff )
+    else if( BOXDATA(p_mdhd)->i_language_code == 0x7fff )
         p_track->b_mac_encoding = true;
     else
     {
         for( unsigned i = 0; i < 3; i++ )
-            language[i] = p_mdhd->data.p_mdhd->i_language[i];
+            language[i] = BOXDATA(p_mdhd)->i_language[i];
         language[3] = '\0';
     }
 
@@ -2815,7 +2955,7 @@ static void MP4_TrackCreate( demux_t *p_demux, mp4_track_t *p_track,
     p_track->i_elst_time = 0;
     if( ( p_track->p_elst = p_elst = MP4_BoxGet( p_box_trak, "edts/elst" ) ) )
     {
-        MP4_Box_data_elst_t *elst = p_elst->data.p_elst;
+        MP4_Box_data_elst_t *elst = BOXDATA(p_elst);
         unsigned int i;
 
         msg_Warn( p_demux, "elst box found" );
@@ -2874,6 +3014,7 @@ static void MP4_TrackCreate( demux_t *p_demux, mp4_track_t *p_track,
     if( TrackCreateChunksIndex( p_demux,p_track  ) ||
         TrackCreateSamplesIndex( p_demux, p_track ) )
     {
+        msg_Err( p_demux, "cannot create chunks index" );
         return; /* cannot create chunks index */
     }
 
@@ -3064,10 +3205,13 @@ static uint32_t MP4_TrackSampleSize( mp4_track_t *p_track, uint32_t *pi_nb_sampl
     if( p_track->i_sample_size == 0 )
     {
         /* most simple case */
+        *pi_nb_samples = 1;
         return p_track->p_sample_size[p_track->i_sample];
     }
+
     if( p_track->fmt.i_cat != AUDIO_ES )
     {
+        *pi_nb_samples = 1;
         return p_track->i_sample_size;
     }
 
@@ -3078,18 +3222,19 @@ static uint32_t MP4_TrackSampleSize( mp4_track_t *p_track, uint32_t *pi_nb_sampl
         uint32_t i_samples = p_track->chunk[p_track->i_chunk].i_sample_count;
         if( p_track->fmt.audio.i_blockalign > 1 )
             i_samples = p_soun->i_sample_per_packet;
-
         i_size = i_samples / p_soun->i_sample_per_packet;
-        if ( UINT32_MAX / i_size < p_soun->i_bytes_per_frame )
+        if ( UINT32_MAX / i_size >= p_soun->i_bytes_per_frame )
             i_size *= p_soun->i_bytes_per_frame;
         else
             i_size = UINT32_MAX;
+        *pi_nb_samples = i_samples;
     }
     else if( p_track->i_sample_size > 256 )
     {
         /* We do that so we don't read too much data
          * (in this case we are likely dealing with compressed data) */
         i_size = p_track->i_sample_size;
+        *pi_nb_samples = 1;
     }
     else
     {
@@ -3213,10 +3358,10 @@ static int MP4_TrackNextSample( demux_t *p_demux, mp4_track_t *p_track, uint32_t
     }
 
     /* Have we changed elst */
-    if( p_track->p_elst && p_track->p_elst->data.p_elst->i_entry_count > 0 )
+    if( p_track->p_elst && p_track->BOXDATA(p_elst)->i_entry_count > 0 )
     {
         demux_sys_t *p_sys = p_demux->p_sys;
-        MP4_Box_data_elst_t *elst = p_track->p_elst->data.p_elst;
+        MP4_Box_data_elst_t *elst = p_track->BOXDATA(p_elst);
         uint64_t i_mvt = MP4_TrackGetDTS( p_demux, p_track ) *
                         p_sys->i_timescale / CLOCK_FREQ;
 
@@ -3241,9 +3386,9 @@ static void MP4_TrackSetELST( demux_t *p_demux, mp4_track_t *tk,
     /* handle elst (find the correct one) */
     tk->i_elst      = 0;
     tk->i_elst_time = 0;
-    if( tk->p_elst && tk->p_elst->data.p_elst->i_entry_count > 0 )
+    if( tk->p_elst && tk->BOXDATA(p_elst)->i_entry_count > 0 )
     {
-        MP4_Box_data_elst_t *elst = tk->p_elst->data.p_elst;
+        MP4_Box_data_elst_t *elst = tk->BOXDATA(p_elst);
         int64_t i_mvt= i_time * p_sys->i_timescale / CLOCK_FREQ;
 
         for( tk->i_elst = 0; (unsigned int)tk->i_elst < elst->i_entry_count; tk->i_elst++ )
@@ -3432,7 +3577,7 @@ static int MP4_frg_TrackCreate( demux_t *p_demux, mp4_track_t *p_track, MP4_Box_
 {
     demux_sys_t *p_sys = p_demux->p_sys;
     int ret;
-    MP4_Box_data_stra_t *p_data = p_stra->data.p_stra;
+    MP4_Box_data_stra_t *p_data = BOXDATA(p_stra);
     if( !p_data )
         return VLC_EGENERIC;
 
@@ -3529,8 +3674,6 @@ static mp4_track_t *MP4_frg_GetTrackByID( demux_t *p_demux, const uint32_t tid )
     for( unsigned i = 0; i < p_sys->i_tracks; i++ )
     {
         ret = &p_sys->track[i];
-        if( !ret )
-            return NULL;
         if( ret->i_track_ID == tid )
             return ret;
     }
@@ -3659,7 +3802,7 @@ static int MP4_frg_GetChunk( demux_t *p_demux, MP4_Box_t *p_chunk, unsigned *i_t
         return VLC_EGENERIC;
     }
 
-    uint32_t i_track_ID = p_tfhd->data.p_tfhd->i_track_ID;
+    uint32_t i_track_ID = BOXDATA(p_tfhd)->i_track_ID;
     *i_tk_id = i_track_ID;
     assert( i_track_ID > 0 );
     msg_Dbg( p_demux, "GetChunk: track ID is %"PRIu32"", i_track_ID );
@@ -3670,7 +3813,7 @@ static int MP4_frg_GetChunk( demux_t *p_demux, MP4_Box_t *p_chunk, unsigned *i_t
 
     mp4_chunk_t *ret = p_track->cchunk;
 
-    if( p_tfhd->data.p_tfhd->b_empty )
+    if( BOXDATA(p_tfhd)->b_empty )
         msg_Warn( p_demux, "No samples in this chunk!" );
 
     /* Usually we read 100 ms of each track. However, suppose we have two tracks,
@@ -3692,12 +3835,12 @@ static int MP4_frg_GetChunk( demux_t *p_demux, MP4_Box_t *p_chunk, unsigned *i_t
         FreeAndResetChunk( ret );
 
     uint32_t default_duration = 0;
-    if( p_tfhd->data.p_tfhd->i_flags & MP4_TFHD_DFLT_SAMPLE_DURATION )
-        default_duration = p_tfhd->data.p_tfhd->i_default_sample_duration;
+    if( BOXDATA(p_tfhd)->i_flags & MP4_TFHD_DFLT_SAMPLE_DURATION )
+        default_duration = BOXDATA(p_tfhd)->i_default_sample_duration;
 
     uint32_t default_size = 0;
-    if( p_tfhd->data.p_tfhd->i_flags & MP4_TFHD_DFLT_SAMPLE_SIZE )
-        default_size = p_tfhd->data.p_tfhd->i_default_sample_size;
+    if( BOXDATA(p_tfhd)->i_flags & MP4_TFHD_DFLT_SAMPLE_SIZE )
+        default_size = BOXDATA(p_tfhd)->i_default_sample_size;
 
     MP4_Box_t *p_trun = MP4_BoxGet( p_traf, "trun");
     if( p_trun == NULL)
@@ -3721,17 +3864,12 @@ static int MP4_frg_GetChunk( demux_t *p_demux, MP4_Box_t *p_chunk, unsigned *i_t
      * more than one subsegment. */
     if( !default_duration )
     {
-        MP4_Box_t *p_trex = MP4_BoxGet( p_demux->p_sys->p_root, "moov/mvex/trex");
+        MP4_Box_t *p_trex = MP4_GetTrexByTrackID( p_moof, i_track_ID );
         if ( p_trex )
-        {
-            while( p_trex && p_trex->data.p_trex->i_track_ID != i_track_ID )
-                p_trex = p_trex->p_next;
-            if ( p_trex )
-                default_duration = p_trex->data.p_trex->i_default_sample_duration;
-        }
+            default_duration = BOXDATA(p_trex)->i_default_sample_duration;
         else if( p_sidx )
         {
-            MP4_Box_data_sidx_t *p_sidx_data = p_sidx->data.p_sidx;
+            MP4_Box_data_sidx_t *p_sidx_data = BOXDATA(p_sidx);
             assert( p_sidx_data->i_reference_count == 1 );
 
             if( p_sidx_data->i_timescale == 0 )
@@ -3795,8 +3933,10 @@ static int MP4_frg_GetChunk( demux_t *p_demux, MP4_Box_t *p_chunk, unsigned *i_t
 
         if( ret->p_sample_offset_pts )
         {
-            ret->p_sample_offset_pts[i] =
-                        p_trun_data->p_samples[i].i_composition_time_offset;
+            if ( p_trun_data->i_version == 0 )
+                ret->p_sample_offset_pts[i] = (int32_t) p_trun_data->p_samples[i].i_composition_time_offset;
+            else
+                ret->p_sample_offset_pts[i] = __MIN( INT32_MAX, p_trun_data->p_samples[i].i_composition_time_offset );
         }
 
         if( p_trun_data->i_flags & MP4_TRUN_SAMPLE_SIZE )
@@ -3866,7 +4006,7 @@ static int MP4_frg_GetChunks( demux_t *p_demux, const unsigned i_tk_id )
                     msg_Warn( p_demux, "No tkhd found!" );
                     goto MP4_frg_GetChunks_Error;
                 }
-                tid = p_tkhd->data.p_tkhd->i_track_ID;
+                tid = BOXDATA(p_tkhd)->i_track_ID;
             }
             else                      /* Smooth Streaming */
             {
@@ -3877,7 +4017,7 @@ static int MP4_frg_GetChunks( demux_t *p_demux, const unsigned i_tk_id )
                     msg_Warn( p_demux, "No StraBox found!" );
                     goto MP4_frg_GetChunks_Error;
                 }
-                tid = p_stra->data.p_stra->i_track_ID;
+                tid = BOXDATA(p_stra)->i_track_ID;
             }
 
             p_track = MP4_frg_GetTrackByID( p_demux, tid );
@@ -3924,6 +4064,278 @@ static int MP4_frg_TrackSelect( demux_t *p_demux, mp4_track_t *p_track )
     return VLC_SUCCESS;
 }
 
+
+/* Keeps an ordered chain of all fragments */
+static bool AddFragment( demux_t *p_demux, MP4_Box_t *p_moox )
+{
+    demux_sys_t *p_sys = p_demux->p_sys;
+    mp4_fragment_t *p_base_fragment = & p_sys->moovfragment;
+    if ( !p_moox )
+        return false;
+
+    if( p_moox->i_type == ATOM_moov )
+    {
+        if ( !p_sys->moovfragment.p_moox )
+        {
+            p_sys->moovfragment.p_moox = p_moox;
+
+            MP4_Box_t *p_mvhd;
+            if( (p_mvhd = MP4_BoxGet( p_moox, "mvhd" )) )
+            {
+                p_sys->i_timescale = BOXDATA(p_mvhd)->i_timescale;
+                p_sys->moovfragment.i_duration = BOXDATA(p_mvhd)->i_duration;
+            }
+            msg_Dbg( p_demux, "added fragment %4.4s", (char*) &p_moox->i_type );
+            return true;
+        }
+        return false;
+    }
+    else // p_moox->i_type == ATOM_moof
+    {
+        assert(p_moox->i_type == ATOM_moof);
+        mp4_fragment_t *p_fragment = p_sys->moovfragment.p_next;
+        while ( p_fragment )
+        {
+            if ( !p_base_fragment->p_moox || p_moox->i_pos > p_base_fragment->p_moox->i_pos )
+            {
+                p_base_fragment = p_fragment;
+                p_fragment = p_fragment->p_next;
+            }
+            else if ( p_moox->i_pos == p_base_fragment->p_moox->i_pos )
+            {
+                /* already exists */
+                return false;
+            }
+        }
+    }
+
+    /* Add the moof fragment */
+    mp4_fragment_t *p_new = malloc(sizeof(mp4_fragment_t));
+    if ( !p_new ) return false;
+    p_new->p_moox = p_moox;
+    p_new->i_duration = 0;
+    p_new->p_next = p_base_fragment->p_next;
+    p_base_fragment->p_next = p_new;
+    msg_Dbg( p_demux, "added fragment %4.4s", (char*) &p_moox->i_type );
+
+    /* we have to probe all fragments :/ */
+    uint64_t i_traf_base_data_offset = 0;
+    uint64_t i_traf_min_offset = 0;
+    uint32_t i_traf = 0;
+    uint32_t i_traf_total_size = 0;
+    uint32_t i_trafs_total_size = 0;
+
+    MP4_Box_t *p_traf = MP4_BoxGet( p_new->p_moox, "traf" );
+    while ( p_traf )
+    {
+        if ( p_traf->i_type != ATOM_traf )
+        {
+           p_traf = p_traf->p_next;
+           continue;
+        }
+        const MP4_Box_t *p_tfhd = MP4_BoxGet( p_traf, "tfhd" );
+        const MP4_Box_t *p_trun = MP4_BoxGet( p_traf, "trun" );
+        if ( !p_tfhd || !p_trun )
+        {
+           p_traf = p_traf->p_next;
+           continue;
+        }
+
+        uint32_t i_track_timescale = 0;
+        uint32_t i_track_defaultsamplesize = 0;
+        uint32_t i_track_defaultsampleduration = 0;
+        if ( p_sys->b_smooth )
+        {
+            /* stra sets identical timescales */
+            i_track_timescale = p_sys->i_timescale;
+            i_track_defaultsamplesize = 1;
+            i_track_defaultsampleduration = 1;
+        }
+        else
+        {
+            /* set trex for defaults */
+             MP4_Box_t *p_trex = MP4_GetTrexByTrackID( p_sys->moovfragment.p_moox, BOXDATA(p_tfhd)->i_track_ID );
+             if ( p_trex )
+             {
+                i_track_defaultsamplesize = BOXDATA(p_trex)->i_default_sample_size;
+                i_track_defaultsampleduration = BOXDATA(p_trex)->i_default_sample_duration;
+             }
+             MP4_Box_t *p_trak = MP4_GetTrakByTrackID( p_sys->moovfragment.p_moox, BOXDATA(p_tfhd)->i_track_ID );
+             if ( p_trak )
+             {
+                MP4_Box_t *p_mdhd = MP4_BoxGet( p_trak, "mdia/mdhd" );
+                if ( p_mdhd ) i_track_timescale = BOXDATA(p_mdhd)->i_timescale;
+             }
+        }
+
+        if ( !i_track_timescale )
+        {
+           p_traf = p_traf->p_next;
+           continue;
+        }
+
+        if ( BOXDATA(p_tfhd)->i_flags & MP4_TFHD_BASE_DATA_OFFSET )
+        {
+            i_traf_base_data_offset = BOXDATA(p_tfhd)->i_base_data_offset;
+        }
+        else if ( BOXDATA(p_tfhd)->i_flags & MP4_TFHD_DEFAULT_BASE_IS_MOOF )
+        {
+            i_traf_base_data_offset = p_new->p_moox->i_pos + 8;
+        }
+        else
+        {
+            if ( i_traf == 0 )
+                i_traf_base_data_offset = p_new->p_moox->i_pos /*+ 8*/;
+            else
+                i_traf_base_data_offset += i_traf_total_size;
+        }
+
+        i_traf_total_size = 0;
+
+        uint64_t i_trun_data_offset = i_traf_base_data_offset;
+        uint64_t i_traf_duration = 0;
+        uint32_t i_trun_size = 0;
+        while ( p_trun && p_tfhd )
+        {
+            if ( p_trun->i_type != ATOM_trun )
+            {
+               p_trun = p_trun->p_next;
+               continue;
+            }
+            const MP4_Box_data_trun_t *p_trundata = p_trun->data.p_trun;
+
+            /* Get data offset */
+            if ( p_trundata->i_flags & MP4_TRUN_DATA_OFFSET )
+                i_trun_data_offset += __MAX( p_trundata->i_data_offset, 0 );
+            else
+                i_trun_data_offset += i_trun_size;
+
+            i_trun_size = 0;
+
+            /* Sum total time */
+            if ( p_trundata->i_flags & MP4_TRUN_SAMPLE_DURATION )
+            {
+                for( uint32_t i=0; i< p_trundata->i_sample_count; i++ )
+                    i_traf_duration += p_trundata->p_samples[i].i_duration;
+            }
+            else if ( BOXDATA(p_tfhd)->i_flags & MP4_TFHD_DFLT_SAMPLE_DURATION )
+            {
+                i_traf_duration += p_trundata->i_sample_count *
+                        BOXDATA(p_tfhd)->i_default_sample_duration;
+            }
+            else
+            {
+                i_traf_duration += p_trundata->i_sample_count *
+                        i_track_defaultsampleduration;
+            }
+
+            /* Get total traf size */
+            if ( p_trundata->i_flags & MP4_TRUN_SAMPLE_SIZE )
+            {
+                for( uint32_t i=0; i< p_trundata->i_sample_count; i++ )
+                    i_trun_size += p_trundata->p_samples[i].i_size;
+            }
+            else if ( BOXDATA(p_tfhd)->i_flags & MP4_TFHD_DFLT_SAMPLE_SIZE )
+            {
+                i_trun_size += p_trundata->i_sample_count *
+                        BOXDATA(p_tfhd)->i_default_sample_size;
+            }
+            else
+            {
+                i_trun_size += p_trundata->i_sample_count *
+                        i_track_defaultsamplesize;
+            }
+
+            i_traf_total_size += i_trun_size;
+
+            if ( i_traf_min_offset )
+                i_traf_min_offset = __MIN( i_trun_data_offset, i_traf_min_offset );
+            else
+                i_traf_min_offset = i_trun_data_offset;
+
+            p_trun = p_trun->p_next;
+        }
+
+        i_trafs_total_size += i_traf_total_size;
+        p_new->i_duration = __MAX( p_new->i_duration, i_traf_duration * p_sys->i_timescale / i_track_timescale );
+
+        p_traf = p_traf->p_next;
+        i_traf++;
+    }
+
+    p_new->i_chunk_range_min_offset = i_traf_min_offset;
+    p_new->i_chunk_range_max_offset = i_traf_min_offset + i_trafs_total_size;
+
+    msg_Dbg( p_demux, "new fragment is %"PRId64" %"PRId64, p_new->i_chunk_range_min_offset, p_new->i_chunk_range_max_offset );
+
+    /* compute total duration with that new fragment if no overall provided */
+    MP4_Box_t *p_mehd = MP4_BoxGet( p_sys->moovfragment.p_moox, "mvex/mehd");
+    if ( !p_mehd )
+    {
+        p_sys->i_overall_duration = 0;
+        p_new = &p_sys->moovfragment;
+        while ( p_new )
+        {
+            p_sys->i_overall_duration += p_new->i_duration;
+            p_new = p_new->p_next;
+        }
+    }
+    else
+        p_sys->i_overall_duration = BOXDATA(p_mehd)->i_fragment_duration;
+
+    msg_Dbg( p_demux, "total fragments duration %"PRId64, CLOCK_FREQ * p_sys->i_overall_duration / p_sys->i_timescale);
+    return true;
+}
+
+static int ProbeFragments( demux_t *p_demux, bool b_force )
+{
+    demux_sys_t *p_sys = p_demux->p_sys;
+    uint64_t i_current_pos;
+
+    if ( MP4_stream_Tell( p_demux->s, &i_current_pos ) )
+        msg_Dbg( p_demux, "probing fragments from %"PRId64, i_current_pos );
+
+    assert( p_sys->p_root );
+
+    if ( p_sys->b_fastseekable || b_force )
+    {
+        MP4_ReadBoxContainerChildren( p_demux->s, p_sys->p_root, 0 ); /* Get the rest of the file */
+        p_sys->b_fragments_probed = true;
+    }
+    else
+    {
+        /* We stop at first moof, which validates our fragmentation condition
+         * and we'll find others while reading. */
+        MP4_ReadBoxContainerChildren( p_demux->s, p_sys->p_root, ATOM_moof );
+    }
+
+    MP4_Box_t *p_moov = MP4_BoxGet( p_sys->p_root, "/moov" );
+    if ( !p_moov )
+    {
+        /* moov/mvex before probing should be present anyway */
+        MP4_BoxDumpStructure( p_demux->s, p_sys->p_root );
+        return VLC_EGENERIC;
+    }
+    AddFragment( p_demux, p_moov );
+
+    MP4_Box_t *p_moof = MP4_BoxGet( p_sys->p_root, "moof" );
+    while ( p_moof )
+    {
+        if ( p_moof->i_type == ATOM_moof )
+            AddFragment( p_demux, p_moof );
+        p_moof = p_moof->p_next;
+    }
+
+    MP4_Box_t *p_mdat = MP4_BoxGet( p_sys->p_root, "mdat" );
+    if ( p_mdat )
+    {
+        stream_Seek( p_demux->s, p_mdat->i_pos );
+        msg_Dbg( p_demux, "rewinding to mdat %"PRId64, p_mdat->i_pos );
+    }
+
+    return VLC_SUCCESS;
+}
+
 /**
  * DemuxFrg: read packet and send them to decoders
  * \return 1 on success, 0 on error.
@@ -3966,7 +4378,7 @@ int DemuxFrg( demux_t *p_demux )
         if( p_sys->i_timescale > 0 )
         {
             int64_t i_length = CLOCK_FREQ *
-                               (mtime_t)p_sys->i_duration /
+                               (mtime_t)p_sys->moovfragment.i_duration /
                                (mtime_t)p_sys->i_timescale;
             if( MP4_GetMoviePTS( p_sys ) >= i_length )
                 return 0;
@@ -4047,3 +4459,5 @@ int DemuxFrg( demux_t *p_demux )
     }
     return 1;
 }
+
+#undef BOXDATA