]> git.sesse.net Git - vlc/blobdiff - modules/demux/mp4/mp4.c
Tools: Fix SF URLs
[vlc] / modules / demux / mp4 / mp4.c
index 7e107d47f0dd1d568af22d0f4e5768305688da8a..42c718d9f346c126ab73fc9c3d786ec173c65b73 100644 (file)
 # include "config.h"
 #endif
 
-#include <vlc_common.h>
+#include "mp4.h"
+
 #include <vlc_plugin.h>
 
 #include <vlc_demux.h>
 #include <vlc_charset.h>                           /* EnsureUTF8 */
 #include <vlc_meta.h>                              /* vlc_meta_t, vlc_meta_ */
 #include <vlc_input.h>
+#include <vlc_aout.h>
 #include <assert.h>
 
-#include "libmp4.h"
 #include "id3genres.h"                             /* for ATOM_gnre */
 
 /*****************************************************************************
@@ -61,19 +62,10 @@ vlc_module_end ()
 static int   Demux   ( demux_t * );
 static int   DemuxRef( demux_t *p_demux ){ (void)p_demux; return 0;}
 static int   DemuxFrg( demux_t * );
+static int   DemuxAsLeaf( 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 */
@@ -92,12 +84,21 @@ struct demux_sys_t
     bool         b_fragmented;   /* fMP4 */
     bool         b_seekable;
     bool         b_fastseekable;
+    bool         b_seekmode;
     bool         b_smooth;       /* Is it Smooth Streaming? */
 
+    bool            b_index_probed;
     bool            b_fragments_probed;
     mp4_fragment_t  moovfragment; /* moov */
     mp4_fragment_t *p_fragments;  /* known fragments (moof following moov) */
 
+    struct
+    {
+        mp4_fragment_t *p_fragment;
+        uint32_t        i_current_box_type;
+        uint32_t        i_mdatbytesleft;
+    } context;
+
     /* */
     MP4_Box_t    *p_tref_chap;
 
@@ -114,23 +115,35 @@ static void MP4_TrackCreate ( demux_t *, mp4_track_t *, MP4_Box_t  *, bool b_for
 static int MP4_frg_TrackCreate( demux_t *, mp4_track_t *, MP4_Box_t *);
 static void MP4_TrackDestroy(  mp4_track_t * );
 
+static block_t * MP4_Block_Read( demux_t *, const mp4_track_t *, int );
+static void MP4_Block_Send( demux_t *, mp4_track_t *, block_t * );
+
 static int  MP4_TrackSelect ( demux_t *, mp4_track_t *, mtime_t );
 static void MP4_TrackUnselect(demux_t *, mp4_track_t * );
 
 static int  MP4_TrackSeek   ( demux_t *, mp4_track_t *, mtime_t );
 
 static uint64_t MP4_TrackGetPos    ( mp4_track_t * );
-static uint32_t MP4_TrackSampleSize( mp4_track_t *, uint32_t * );
+static uint32_t MP4_TrackGetReadSize( mp4_track_t *, uint32_t * );
 static int      MP4_TrackNextSample( demux_t *, mp4_track_t *, uint32_t );
 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 );
+static int  ProbeFragments( demux_t *p_demux, bool b_force );
+static int  ProbeIndex( demux_t *p_demux );
+static mp4_fragment_t *GetFragmentByPos( demux_t *p_demux, uint64_t i_pos, bool b_exact );
+static mp4_fragment_t *GetFragmentByTime( demux_t *p_demux, const mtime_t i_time );
+
+static int LeafIndexGetMoofPosByTime( demux_t *p_demux, const mtime_t i_target_time,
+                                      uint64_t *pi_pos, mtime_t *pi_mooftime );
+static mtime_t LeafGetFragmentTimeOffset( demux_t *p_demux, mp4_fragment_t * );
+static int LeafGetTrackAndChunkByMOOVPos( demux_t *p_demux, uint64_t *pi_pos,
+                                      mp4_track_t **pp_tk, unsigned int *pi_chunk );
+static int LeafMapTrafTrunContextes( demux_t *p_demux, MP4_Box_t *p_moof );
 
 /* Helpers */
 
@@ -166,7 +179,8 @@ 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 )
+        if ( p_trex->i_type == ATOM_trex &&
+             BOXDATA(p_trex) && BOXDATA(p_trex)->i_track_ID == i_id )
                 break;
         else
             p_trex = p_trex->p_next;
@@ -181,7 +195,7 @@ static MP4_Box_t * MP4_GetTrakByTrackID( MP4_Box_t *p_moov, const uint32_t i_id
     while( p_trak )
     {
         if( p_trak->i_type == ATOM_trak &&
-            (p_tkhd = MP4_BoxGet( p_trak, "tkhd" )) &&
+            (p_tkhd = MP4_BoxGet( p_trak, "tkhd" )) && BOXDATA(p_tkhd) &&
             BOXDATA(p_tkhd)->i_track_ID == i_id )
                 break;
         else
@@ -296,13 +310,17 @@ static int LoadInitFrag( 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 && BOXDATA(p_stra)->i_track_ID )
+                if( p_stra && BOXDATA(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 = BOXDATA(p_stra)->i_timescale;
-                    p_sys->i_duration = BOXDATA(p_stra)->i_duration;
+                    if ( p_stra && BOXDATA(p_stra) )
+                    {
+                        p_sys->i_timescale = BOXDATA(p_stra)->i_timescale;
+                        p_sys->i_duration = BOXDATA(p_stra)->i_duration;
+                        p_sys->i_overall_duration = BOXDATA(p_stra)->i_duration;
+                    }
                     if( p_sys->i_timescale == 0 )
                     {
                         msg_Err( p_demux, "bad timescale" );
@@ -362,7 +380,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 || BOXDATA(p_stra)->i_track_ID == 0 )
+        if( !p_stra || !BOXDATA(p_stra) || BOXDATA(p_stra)->i_track_ID == 0 )
             continue;
         else
         {
@@ -373,6 +391,101 @@ static void CreateTracksFromSmooBox( demux_t *p_demux )
     }
 }
 
+static block_t * MP4_EIA608_Convert( block_t * p_block )
+{
+    /* Rebuild codec data from encap */
+    size_t i_copied = 0;
+    size_t i_remaining = p_block->i_buffer;
+    uint32_t i_bytes = 0;
+    block_t *p_newblock;
+
+    if ( i_remaining < 10 ||
+         !(i_bytes = GetDWBE(p_block->p_buffer)) ||
+         (i_bytes + 8 > i_remaining) ||
+         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
+    {
+        p_write[i_copied++] = 0; /* cc1 == field 0 */
+        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 );
+
+    if ( i_remaining >= 10 &&
+         (i_bytes = GetDWBE(p_read)) &&
+         (i_bytes + 8 <= i_remaining) &&
+         !memcmp("cdt2", &p_read[4], 4) )
+    {
+        p_read += 8;
+        i_bytes -= 8;
+        i_remaining -= 8;
+        do
+        {
+            p_write[i_copied++] = 0; /* cc1 == field 0 */
+            p_write[i_copied++] = p_read[0];
+            p_write[i_copied++] = p_read[1];
+            p_read += 2;
+            i_bytes -= 2;
+        } while( i_bytes >= 2 );
+    }
+
+    block_Release( p_block );
+    p_newblock->i_buffer = i_copied;
+    return p_newblock;
+}
+
+static block_t * MP4_Block_Read( demux_t *p_demux, const mp4_track_t *p_track, int i_size )
+{
+    block_t *p_block = stream_Block( p_demux->s, i_size );
+    if ( !p_block )
+        return NULL;
+
+    /* might have some encap */
+    if( p_track->fmt.i_cat == SPU_ES )
+    {
+        switch( p_track->fmt.i_codec )
+        {
+            case VLC_CODEC_TX3G:
+            case VLC_CODEC_SPU:
+            /* accept as-is */
+            break;
+            case VLC_CODEC_EIA608_1:
+                p_block = MP4_EIA608_Convert( p_block );
+            break;
+        default:
+            p_block->i_buffer = 0;
+            break;
+        }
+    }
+
+    return p_block;
+}
+
+static void MP4_Block_Send( demux_t *p_demux, mp4_track_t *p_track, block_t *p_block )
+{
+    if ( p_track->b_chans_reorder && aout_BitsPerSample( p_track->fmt.i_codec ) )
+    {
+        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 );
+    }
+    es_out_Send( p_demux->out, p_track->p_es, p_block );
+}
+
 /*****************************************************************************
  * Open: check file and initializes MP4 structures
  *****************************************************************************/
@@ -430,6 +543,7 @@ static int Open( vlc_object_t * p_this )
         return VLC_EGENERIC;
     }
     stream_Control( p_demux->s, STREAM_CAN_FASTSEEK, &p_sys->b_fastseekable );
+    p_sys->b_seekmode = p_sys->b_fastseekable;
 
     /*Set exported functions */
     p_demux->pf_demux = Demux;
@@ -453,11 +567,14 @@ static int Open( vlc_object_t * p_this )
         {
             /* Probe remaining to check if there's really fragments
                or if that file is just ready to append fragments */
-            ProbeFragments( p_demux );
+            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 && !p_sys->i_overall_duration )
+            ProbeFragments( p_demux, true );
     }
 
     if ( !p_sys->moovfragment.p_moox )
@@ -465,14 +582,16 @@ static int Open( vlc_object_t * p_this )
 
     /* 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 )
+    if ( p_sys->b_smooth )
     {
         p_demux->pf_demux = DemuxFrg;
     }
+    else if( p_sys->b_fragmented )
+    {
+        p_demux->pf_demux = DemuxAsLeaf;
+    }
 
     if( p_sys->b_smooth )
     {
@@ -481,15 +600,6 @@ static int Open( vlc_object_t * p_this )
         CreateTracksFromSmooBox( p_demux );
         return VLC_SUCCESS;
     }
-    else if( p_sys->b_fragmented )
-    {
-        /* We are not yet able to demux a fragmented MP4 file, using the 'mfra'
-         * a file, and we let avformat do the job. */
-        msg_Warn( p_demux, "MP4 plugin discarded "\
-                "(fragmented, let avformat demux it)" );
-        stream_Seek( p_demux->s, 0 ); /* rewind, for other demux */
-        goto error;
-    }
 
     MP4_BoxDumpStructure( p_demux->s, p_sys->p_root );
 
@@ -566,7 +676,7 @@ static int Open( vlc_object_t * p_this )
             char      *psz_ref;
             uint32_t  i_ref_type;
 
-            if( !p_rdrf || !( psz_ref = strdup( BOXDATA(p_rdrf)->psz_ref ) ) )
+            if( !p_rdrf || !BOXDATA(p_rdrf) || !( psz_ref = strdup( BOXDATA(p_rdrf)->psz_ref ) ) )
             {
                 continue;
             }
@@ -654,7 +764,7 @@ static int Open( vlc_object_t * p_this )
     {
         /* Try in mehd if fragmented */
         MP4_Box_t *p_mehd = MP4_BoxGet( p_demux->p_sys->p_root, "moov/mvex/mehd");
-        if ( p_mehd )
+        if ( p_mehd && p_mehd->data.p_mehd )
             p_sys->i_overall_duration = p_mehd->data.p_mehd->i_fragment_duration;
         else
             p_sys->i_overall_duration = p_sys->moovfragment.i_duration;
@@ -682,11 +792,12 @@ static int Open( vlc_object_t * p_this )
 
 
         MP4_Box_t *p_tkhd = MP4_BoxGet( p_trak, "tkhd" );
-        if( p_tkhd && (BOXDATA(p_tkhd)->i_flags&MP4_TRACK_ENABLED) )
+        if( p_tkhd && BOXDATA(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 );
-        if( p_chap && p_chap->data.p_tref_generic->i_entry_count > 0 && !p_sys->p_tref_chap )
+        if( p_chap && p_chap->data.p_tref_generic &&
+            p_chap->data.p_tref_generic->i_entry_count > 0 && !p_sys->p_tref_chap )
             p_sys->p_tref_chap = p_chap;
     }
 
@@ -739,9 +850,9 @@ 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,
+        msg_Dbg( p_demux, "fragment offset %"PRId64", data %"PRIu64"<->%"PRIu64", duration %"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->i_chunk_range_max_offset, CLOCK_FREQ * p_fragment->i_duration / p_sys->i_timescale );
         p_fragment = p_fragment->p_next;
     }
 
@@ -830,17 +941,32 @@ static int Demux( demux_t *p_demux )
     /* Find next track matching contiguous data */
     mp4_track_t *tk = NULL;
     uint64_t i_candidate_pos = UINT64_MAX;
+    mtime_t i_candidate_dts = INT64_MAX;
     for( i_track = 0; i_track < p_sys->i_tracks; i_track++ )
     {
         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;
 
-        uint64_t i_pos = MP4_TrackGetPos( tk_tmp );
-        if ( i_pos <= i_candidate_pos )
+        if ( p_sys->b_seekmode )
+        {
+            mtime_t i_dts = MP4_TrackGetDTS( p_demux, tk_tmp );
+            if ( i_dts <= i_candidate_dts )
+            {
+                tk = tk_tmp;
+                i_candidate_dts = i_dts;
+                i_candidate_pos = MP4_TrackGetPos( tk_tmp );
+            }
+        }
+        else
         {
-            i_candidate_pos = i_pos;
-            tk = tk_tmp;
+            /* Try to avoid seeking on non fastseekable. Will fail with non interleaved content */
+            uint64_t i_pos = MP4_TrackGetPos( tk_tmp );
+            if ( i_pos <= i_candidate_pos )
+            {
+                i_candidate_pos = i_pos;
+                tk = tk_tmp;
+            }
         }
     }
 
@@ -849,6 +975,16 @@ static int Demux( demux_t *p_demux )
         msg_Dbg( p_demux, "Could not select track by data position" );
         goto end;
     }
+    else if ( p_sys->b_seekmode )
+    {
+        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;
+        }
+    }
 
 #if 0
     msg_Dbg( p_demux, "tk(%i)=%"PRId64" mv=%"PRId64" pos=%"PRIu64, i_track,
@@ -857,7 +993,7 @@ static int Demux( demux_t *p_demux )
 #endif
 
     uint32_t i_nb_samples = 0;
-    uint32_t i_samplessize = MP4_TrackSampleSize( tk, &i_nb_samples );
+    uint32_t i_samplessize = MP4_TrackGetReadSize( tk, &i_nb_samples );
     if( i_samplessize > 0 )
     {
         block_t *p_block;
@@ -872,27 +1008,24 @@ static int Demux( demux_t *p_demux )
         {
             if( stream_Seek( p_demux->s, i_candidate_pos ) )
             {
-                msg_Warn( p_demux, "track[0x%x] will be disabled (eof?)",
-                          tk->i_track_ID );
+                msg_Warn( p_demux, "track[0x%x] will be disabled (eof?)"
+                          ": Failed to seek to %"PRIu64,
+                          tk->i_track_ID, i_candidate_pos );
                 MP4_TrackUnselect( p_demux, tk );
                 goto end;
             }
+            i_current_pos = i_candidate_pos;
         }
 
         /* now read pes */
-        if( !(p_block = stream_Block( p_demux->s, i_samplessize )) )
+        if( !(p_block = MP4_Block_Read( p_demux, tk, i_samplessize )) )
         {
-            msg_Warn( p_demux, "track[0x%x] will be disabled (eof?)",
-                      tk->i_track_ID );
+            msg_Warn( p_demux, "track[0x%x] will be disabled (eof?)"
+                      ": Failed to read %d bytes sample at %"PRIu64,
+                      tk->i_track_ID, i_samplessize, i_current_pos );
             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 );
@@ -910,11 +1043,12 @@ static int Demux( demux_t *p_demux )
             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 );
+        MP4_Block_Send( p_demux, tk, p_block );
+    }
 
-        /* Next sample */
+    /* Next sample */
+    if ( i_nb_samples ) /* sample size could be 0, need to go fwd. see return */
         MP4_TrackNextSample( p_demux, tk, i_nb_samples );
-    }
 
 end:
     if ( b_data_sent )
@@ -923,13 +1057,24 @@ end:
         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_selected ) continue;
-            p_sys->i_pcr = __MIN( MP4_TrackGetDTS( p_demux, tk ), p_sys->i_pcr );
+            if ( !tk->b_ok || !tk->b_selected  ||
+                 (tk->fmt.i_cat != AUDIO_ES && tk->fmt.i_cat != VIDEO_ES) )
+                continue;
+
+            mtime_t i_dts = MP4_TrackGetDTS( p_demux, tk );
+            p_sys->i_pcr = __MIN( i_dts, p_sys->i_pcr );
+
+            if ( !p_sys->b_seekmode && i_dts > p_sys->i_pcr + 2*CLOCK_FREQ )
+            {
+                msg_Dbg( p_demux, "that media doesn't look interleaved, will need to seek");
+                p_sys->b_seekmode = true;
+            }
+
             p_sys->i_time = p_sys->i_pcr * p_sys->i_timescale / CLOCK_FREQ;
         }
     }
 
-    return b_data_sent;
+    return b_data_sent || ( i_samplessize == 0 && i_nb_samples );
 }
 
 static void MP4_UpdateSeekpoint( demux_t *p_demux )
@@ -978,6 +1123,143 @@ static int Seek( demux_t *p_demux, mtime_t i_date )
     return VLC_SUCCESS;
 }
 
+static int LeafSeekIntoFragment( demux_t *p_demux, mp4_fragment_t *p_fragment )
+{
+    demux_sys_t *p_sys = p_demux->p_sys;
+    uint64_t i64 = p_fragment->i_chunk_range_min_offset;
+
+    if ( p_fragment->p_moox->i_type == ATOM_moov )
+    {
+        mp4_track_t *p_track;
+        unsigned int i_chunk;
+        int i_ret = LeafGetTrackAndChunkByMOOVPos( p_demux, &i64, &p_track, &i_chunk );
+        if ( i_ret == VLC_EGENERIC )
+        {
+            msg_Dbg( p_demux, "moov seek failed to identify %"PRIu64, i64 );
+            return i_ret;
+        }
+        msg_Dbg( p_demux, "moov seeking to %"PRIu64, i64 );
+    }
+    else
+    {
+        i64 = p_fragment->i_chunk_range_min_offset;
+        msg_Dbg( p_demux, "moof seeking to %"PRIu64, i64 );
+    }
+
+    if( stream_Seek( p_demux->s, i64 ) )
+    {
+        msg_Err( p_demux, "seek failed to %"PRIu64, i64 );
+        return VLC_EGENERIC;
+    }
+
+    /* map context */
+    p_sys->context.p_fragment = p_fragment;
+    p_sys->context.i_current_box_type = ATOM_mdat;
+    LeafMapTrafTrunContextes( p_demux, p_fragment->p_moox );
+    p_sys->context.i_mdatbytesleft = p_fragment->i_chunk_range_max_offset - i64;
+
+    mtime_t i_time_base = LeafGetFragmentTimeOffset( p_demux, p_fragment );
+    for( unsigned int i_track = 0; i_track < p_sys->i_tracks; i_track++ )
+    {
+        p_sys->track[i_track].i_time = i_time_base * p_sys->track[i_track].i_timescale / p_sys->i_timescale;
+    }
+    p_sys->i_time = i_time_base;
+    p_sys->i_pcr  = VLC_TS_INVALID;
+
+    return VLC_SUCCESS;
+}
+
+static int LeafSeekToTime( demux_t *p_demux, mtime_t i_nztime )
+{
+    demux_sys_t *p_sys = p_demux->p_sys;
+    mp4_fragment_t *p_fragment;
+    uint64_t i64 = 0;
+    if ( !p_sys->i_timescale || !p_sys->i_overall_duration || !p_sys->b_seekable )
+         return VLC_EGENERIC;
+
+    if ( !p_sys->b_fragments_probed && !p_sys->b_index_probed && p_sys->b_seekable )
+    {
+        ProbeIndex( p_demux );
+        p_sys->b_index_probed = true;
+    }
+
+    p_fragment = GetFragmentByTime( p_demux, i_nztime );
+    if ( !p_fragment )
+    {
+        mtime_t i_mooftime;
+        msg_Dbg( p_demux, "seek can't find matching fragment for %"PRId64", trying index", i_nztime );
+        if ( LeafIndexGetMoofPosByTime( p_demux, i_nztime, &i64, &i_mooftime ) == VLC_SUCCESS )
+        {
+            msg_Dbg( p_demux, "seek trying to go to unknown but indexed fragment at %"PRId64, i64 );
+            if( stream_Seek( p_demux->s, i64 ) )
+            {
+                msg_Err( p_demux, "seek to moof failed %"PRId64, i64 );
+                return VLC_EGENERIC;
+            }
+            p_sys->context.i_current_box_type = 0;
+            p_sys->context.i_mdatbytesleft = 0;
+            p_sys->context.p_fragment = NULL;
+            for( unsigned int i_track = 0; i_track < p_sys->i_tracks; i_track++ )
+            {
+                p_sys->track[i_track].i_time = i_mooftime / CLOCK_FREQ * p_sys->track[i_track].i_timescale;
+            }
+            p_sys->i_time = i_mooftime / CLOCK_FREQ * p_sys->i_timescale;
+            p_sys->i_pcr  = VLC_TS_INVALID;
+        }
+        else
+        {
+            msg_Warn( p_demux, "seek by index failed" );
+            return VLC_EGENERIC;
+        }
+    }
+    else
+    {
+        msg_Dbg( p_demux, "seeking to fragment data starting at %"PRIu64" for time %"PRId64,
+                           p_fragment->i_chunk_range_min_offset, i_nztime );
+        if ( LeafSeekIntoFragment( p_demux, p_fragment ) != VLC_SUCCESS )
+            return VLC_EGENERIC;
+    }
+
+    /* And set next display time in that trun/fragment */
+    es_out_Control( p_demux->out, ES_OUT_SET_NEXT_DISPLAY_TIME, VLC_TS_0 + i_nztime );
+    return VLC_SUCCESS;
+}
+
+static int LeafSeekToPos( demux_t *p_demux, double f )
+{
+    demux_sys_t *p_sys = p_demux->p_sys;
+    if ( !p_sys->b_seekable )
+        return VLC_EGENERIC;
+
+    if ( p_sys->i_timescale && p_sys->i_overall_duration )
+    {
+        return LeafSeekToTime( p_demux,
+                    (mtime_t)( f * CLOCK_FREQ * p_sys->i_overall_duration /
+                               p_sys->i_timescale ) );
+    }
+
+    if ( !p_sys->b_fragments_probed && !p_sys->b_index_probed && p_sys->b_seekable )
+    {
+        ProbeIndex( p_demux );
+        p_sys->b_index_probed = true;
+    }
+
+    /* Blind seek to pos only */
+    uint64_t i64 = (uint64_t) stream_Size( p_demux->s ) * f;
+    mp4_fragment_t *p_fragment = GetFragmentByPos( p_demux, i64, false );
+    if ( p_fragment )
+    {
+        msg_Dbg( p_demux, "Seeking to fragment data starting at %"PRIu64" for pos %"PRIu64,
+                 p_fragment->i_chunk_range_min_offset, i64 );
+        return LeafSeekIntoFragment( p_demux, p_fragment );
+    }
+    else
+    {
+        msg_Dbg( p_demux, "Cant get fragment for data starting at %"PRIu64, i64 );
+        return VLC_EGENERIC;
+    }
+}
+
 static int MP4_frg_Seek( demux_t *p_demux, double f )
 {
     demux_sys_t *p_sys = p_demux->p_sys;
@@ -1038,10 +1320,10 @@ static int Control( demux_t *p_demux, int i_query, va_list args )
 
         case DEMUX_SET_POSITION:
             f = (double)va_arg( args, double );
-            if( p_sys->b_fragmented )
-            {
+            if ( p_demux->pf_demux == DemuxAsLeaf )
+                return LeafSeekToPos( p_demux, f );
+            else if ( p_demux->pf_demux == DemuxFrg )
                 return MP4_frg_Seek( p_demux, f );
-            }
             else if( p_sys->i_timescale > 0 )
             {
                 i64 = (int64_t)( f * CLOCK_FREQ *
@@ -1049,7 +1331,7 @@ static int Control( demux_t *p_demux, int i_query, va_list args )
                                  (double)p_sys->i_timescale );
                 return Seek( p_demux, i64 );
             }
-            else return VLC_SUCCESS;
+            else return VLC_EGENERIC;
 
         case DEMUX_GET_TIME:
             pi64 = (int64_t*)va_arg( args, int64_t * );
@@ -1064,7 +1346,10 @@ static int Control( demux_t *p_demux, int i_query, va_list args )
 
         case DEMUX_SET_TIME:
             i64 = (int64_t)va_arg( args, int64_t );
-            return Seek( p_demux, i64 );
+            if ( p_demux->pf_demux == DemuxAsLeaf )
+                return LeafSeekToTime( p_demux, i64 );
+            else
+                return Seek( p_demux, i64 );
 
         case DEMUX_GET_LENGTH:
             pi64 = (int64_t*)va_arg( args, int64_t * );
@@ -1418,7 +1703,7 @@ static void LoadChapterApple( demux_t  *p_demux, mp4_track_t *tk )
         const int64_t i_dts = MP4_TrackGetDTS( p_demux, tk );
         const int64_t i_pts_delta = MP4_TrackGetPTSDelta( p_demux, tk );
         uint32_t i_nb_samples = 0;
-        const uint32_t i_size = MP4_TrackSampleSize( tk, &i_nb_samples );
+        const uint32_t i_size = MP4_TrackGetReadSize( tk, &i_nb_samples );
 
         if( i_size > 0 && !stream_Seek( p_demux->s, MP4_TrackGetPos( tk ) ) )
         {
@@ -1451,7 +1736,8 @@ 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" ) ) && BOXDATA(p_chpl)->i_chapter > 0 )
+    if( ( p_chpl = MP4_BoxGet( p_sys->p_root, "/moov/udta/chpl" ) ) &&
+          BOXDATA(p_chpl) && BOXDATA(p_chpl)->i_chapter > 0 )
     {
         LoadChapterGpac( p_demux, p_chpl );
     }
@@ -1556,12 +1842,15 @@ static int TrackCreateChunksIndex( demux_t *p_demux,
         i_last = BOXDATA(p_stsc)->i_first_chunk[i_index] - 1;
     }
 
-    p_demux_track->chunk[0].i_sample_first = 0;
-    for( i_chunk = 1; i_chunk < p_demux_track->i_chunk_count; i_chunk++ )
+    if ( p_demux_track->i_chunk_count )
     {
-        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;
+        p_demux_track->chunk[0].i_sample_first = 0;
+        for( i_chunk = 1; i_chunk < p_demux_track->i_chunk_count; i_chunk++ )
+        {
+            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;
+        }
     }
 
     msg_Dbg( p_demux, "track[Id 0x%x] read %d chunk",
@@ -1807,7 +2096,7 @@ static int TrackCreateSamplesIndex( demux_t *p_demux,
      *  Gives the delta between decoding time (dts) and composition table (pts)
      */
     p_box = MP4_BoxGet( p_demux_track->p_stbl, "ctts" );
-    if( p_box )
+    if( p_box && p_box->data.p_ctts )
     {
         MP4_Box_data_ctts_t *ctts = p_box->data.p_ctts;
 
@@ -1916,7 +2205,7 @@ static void TrackGetESSampleRate( demux_t *p_demux,
     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 )
+    if ( p_mdhd && BOXDATA(p_mdhd) )
     {
         vlc_ureduce( pi_num, pi_den,
                      (uint64_t) BOXDATA(p_mdhd)->i_timescale * p_track->i_sample_count,
@@ -2000,7 +2289,7 @@ static int TrackCreateES( demux_t *p_demux, mp4_track_t *p_track,
 
     p_track->p_sample = p_sample;
 
-    if( ( p_frma = MP4_BoxGet( p_track->p_sample, "sinf/frma" ) ) )
+    if( ( p_frma = MP4_BoxGet( p_track->p_sample, "sinf/frma" ) ) && p_frma->data.p_frma )
     {
         msg_Warn( p_demux, "Original Format Box: %4.4s", (char *)&p_frma->data.p_frma->i_type );
 
@@ -2017,6 +2306,8 @@ static int TrackCreateES( demux_t *p_demux, mp4_track_t *p_track,
     switch( p_track->fmt.i_cat )
     {
     case VIDEO_ES:
+        if ( !p_sample->data.p_sample_vide || p_sample->i_handler != ATOM_vide )
+            break;
         p_track->fmt.video.i_width = p_sample->data.p_sample_vide->i_width;
         p_track->fmt.video.i_height = p_sample->data.p_sample_vide->i_height;
         p_track->fmt.video.i_bits_per_pixel =
@@ -2072,6 +2363,8 @@ static int TrackCreateES( demux_t *p_demux, mp4_track_t *p_track,
         break;
 
     case AUDIO_ES:
+        if ( !p_sample->data.p_sample_soun || p_sample->i_handler != ATOM_soun )
+            break;
         p_track->fmt.audio.i_channels =
             p_sample->data.p_sample_soun->i_channelcount;
         p_track->fmt.audio.i_rate =
@@ -2082,11 +2375,12 @@ static int TrackCreateES( demux_t *p_demux, mp4_track_t *p_track,
         p_track->fmt.audio.i_bitspersample =
             p_sample->data.p_sample_soun->i_samplesize;
 
+        MP4_Box_data_sample_soun_t *p_soun = p_sample->data.p_sample_soun;
+
+        p_track->fmt.i_original_fourcc = p_sample->i_type;
+
         if( ( p_track->i_sample_size == 1 || p_track->i_sample_size == 2 ) )
         {
-            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 )
@@ -2136,8 +2430,6 @@ static int TrackCreateES( demux_t *p_demux, mp4_track_t *p_track,
         }
         else if( p_sample->data.p_sample_soun->i_qt_version == 1 )
         {
-            MP4_Box_data_sample_soun_t *p_soun = p_sample->data.p_sample_soun;
-
             switch( p_sample->i_type )
             {
                 case( VLC_FOURCC( '.', 'm', 'p', '3' ) ):
@@ -2147,8 +2439,8 @@ static int TrackCreateES( demux_t *p_demux, mp4_track_t *p_track,
                             p_soun->i_qt_version = 0;
                         break;
                     }
-                case( VLC_FOURCC( 'a', 'c', '-', '3' ) ):
-                case( VLC_FOURCC( 'e', 'c', '-', '3' ) ):
+                case( ATOM_ac3 ):
+                case( ATOM_eac3 ):
                 case( VLC_FOURCC( 'm', 's', 0x20, 0x00 ) ):
                     p_soun->i_qt_version = 0;
                     break;
@@ -2164,13 +2456,48 @@ static int TrackCreateES( demux_t *p_demux, mp4_track_t *p_track,
             msg_Err( p_demux, "Invalid sample per packet value for qt_version 1. Broken muxer!" );
             p_sample->data.p_sample_soun->i_qt_version = 0;
         }
+
+        /* Lookup for then channels extension */
+        const MP4_Box_t *p_chan = MP4_BoxGet( p_sample, "chan" );
+        if ( p_chan )
+        {
+            if ( BOXDATA(p_chan)->layout.i_channels_layout_tag == MP4_CHAN_USE_CHANNELS_BITMAP )
+            {
+                uint32_t rgi_chans_sequence[AOUT_CHAN_MAX + 1];
+                uint16_t i_vlc_mapping = 0;
+                uint8_t i_channels = 0;
+                const uint32_t i_bitmap = BOXDATA(p_chan)->layout.i_channels_bitmap;
+                for (uint8_t i=0;i<MP4_CHAN_BITMAP_MAPPING_COUNT;i++)
+                {
+                    if ( chan_bitmap_mapping[i].i_bitmap & i_bitmap )
+                    {
+                        i_channels++;
+                        if ( (chan_bitmap_mapping[i].i_vlc & i_vlc_mapping) ||
+                             i_channels > AOUT_CHAN_MAX )
+                        {
+                            /* double mapping or unsupported number of channels */
+                            i_vlc_mapping = 0;
+                            msg_Warn( p_demux, "discarding chan mapping" );
+                            break;
+                        }
+                        i_vlc_mapping |= chan_bitmap_mapping[i].i_vlc;
+                        rgi_chans_sequence[i_channels - 1] = chan_bitmap_mapping[i].i_vlc;
+                    }
+                }
+                rgi_chans_sequence[i_channels] = 0;
+                p_track->b_chans_reorder = !!
+                        aout_CheckChannelReorder( rgi_chans_sequence, NULL, i_vlc_mapping,
+                                                  p_track->rgi_chans_reordering );
+            }
+
+        }
+
         break;
 
     default:
         break;
     }
 
-
     /* It's a little ugly but .. there are special cases */
     switch( p_sample->i_type )
     {
@@ -2180,12 +2507,25 @@ static int TrackCreateES( demux_t *p_demux, mp4_track_t *p_track,
             p_track->fmt.i_codec = VLC_CODEC_MPGA;
             break;
         }
-        case( VLC_FOURCC( 'a', 'c', '-', '3' ) ):
+        case( ATOM_eac3 ):
+        {
+            const MP4_Box_t *p_dec3 = MP4_BoxGet(  p_sample, "dec3", 0 );
+
+            p_track->fmt.i_codec = VLC_CODEC_EAC3;
+            if( p_dec3 && BOXDATA(p_dec3) )
+            {
+                p_track->fmt.audio.i_channels = 0;
+                p_track->fmt.i_bitrate = BOXDATA(p_dec3)->i_data_rate * 1000;
+                p_track->fmt.audio.i_bitspersample = 0;
+            }
+            break;
+        }
+        case( ATOM_ac3 ):
         {
-            MP4_Box_t *p_dac3_box = MP4_BoxGet(  p_sample, "dac3", 0 );
+            const MP4_Box_t *p_dac3 = MP4_BoxGet(  p_sample, "dac3", 0 );
 
             p_track->fmt.i_codec = VLC_CODEC_A52;
-            if( p_dac3_box )
+            if( p_dac3 && BOXDATA(p_dac3) )
             {
                 static const int pi_bitrate[] = {
                      32,  40,  48,  56,
@@ -2194,24 +2534,20 @@ static int TrackCreateES( demux_t *p_demux, mp4_track_t *p_track,
                     256, 320, 384, 448,
                     512, 576, 640,
                 };
-                MP4_Box_data_dac3_t *p_dac3 = p_dac3_box->data.p_dac3;
                 p_track->fmt.audio.i_channels = 0;
                 p_track->fmt.i_bitrate = 0;
-                if( p_dac3->i_bitrate_code < sizeof(pi_bitrate)/sizeof(*pi_bitrate) )
-                    p_track->fmt.i_bitrate = pi_bitrate[p_dac3->i_bitrate_code] * 1000;
+                if( BOXDATA(p_dac3)->i_bitrate_code < sizeof(pi_bitrate)/sizeof(*pi_bitrate) )
+                    p_track->fmt.i_bitrate = pi_bitrate[BOXDATA(p_dac3)->i_bitrate_code] * 1000;
                 p_track->fmt.audio.i_bitspersample = 0;
             }
             break;
         }
-        case( VLC_FOURCC( 'e', 'c', '-', '3' ) ):
-        {
-            p_track->fmt.i_codec = VLC_CODEC_EAC3;
-            break;
-        }
 
         case( VLC_FOURCC( 'r', 'a', 'w', ' ' ) ):
         case( VLC_FOURCC( 'N', 'O', 'N', 'E' ) ):
         {
+            if ( p_sample->i_handler != ATOM_soun )
+                break;
             MP4_Box_data_sample_soun_t *p_soun = p_sample->data.p_sample_soun;
 
             if(p_soun && (p_soun->i_samplesize+7)/8 == 1 )
@@ -2223,9 +2559,6 @@ static int TrackCreateES( demux_t *p_demux, mp4_track_t *p_track,
             if( p_sample->data.p_sample_soun && (p_track->i_timescale !=
                 p_sample->data.p_sample_soun->i_sampleratehi) )
             {
-                MP4_Box_data_sample_soun_t *p_soun =
-                    p_sample->data.p_sample_soun;
-
                 msg_Warn( p_demux, "i_timescale (%"PRId32") != i_sampleratehi "
                           "(%u), making both equal (report any problem).",
                           p_track->i_timescale, p_soun->i_sampleratehi );
@@ -2242,9 +2575,17 @@ static int TrackCreateES( demux_t *p_demux, mp4_track_t *p_track,
             p_track->fmt.i_codec = VLC_CODEC_H263;
             break;
 
+        case( ATOM_c608 ): /* EIA608 closed captions */
+        //case( ATOM_c708 ): /* EIA708 closed captions */
+            p_track->fmt.i_codec = VLC_CODEC_EIA608_1;
+            p_track->fmt.i_cat = SPU_ES;
+            break;
+
         case( VLC_FOURCC( 't', 'e', 'x', 't' ) ):
         case( VLC_FOURCC( 't', 'x', '3', 'g' ) ):
         {
+            if ( p_sample->i_handler != ATOM_text )
+                break;
             p_track->fmt.i_codec = VLC_CODEC_TX3G;
             MP4_Box_data_sample_text_t *p_text = p_sample->data.p_sample_text;
             if ( p_text )
@@ -2301,9 +2642,10 @@ static int TrackCreateES( demux_t *p_demux, mp4_track_t *p_track,
             break;
         case VLC_CODEC_DVD_LPCM:
         {
+            if ( p_sample->i_handler != ATOM_soun )
+                break;
             MP4_Box_data_sample_soun_t *p_soun = p_sample->data.p_sample_soun;
-            if( p_soun->i_qt_version == 2 &&
-                p_soun->i_qt_description > 20 + 28 )
+            if( p_soun->i_qt_version == 2 )
             {
                 /* Flags:
                  *  0x01: IsFloat
@@ -2341,17 +2683,16 @@ static int TrackCreateES( demux_t *p_demux, mp4_track_t *p_track,
 
                     {0, 0, 0, 0}
                 };
-                uint32_t i_bits  = GetDWBE(&p_soun->p_qt_description[20 + 20]);
-                uint32_t i_flags = GetDWBE(&p_soun->p_qt_description[20 + 24]);
 
                 for( int i = 0; p_formats[i].i_codec; i++ )
                 {
-                    if( p_formats[i].i_bits == i_bits &&
-                        (i_flags & p_formats[i].i_mask) == p_formats[i].i_flags )
+                    if( p_formats[i].i_bits == p_soun->i_constbitsperchannel &&
+                        (p_soun->i_formatflags & p_formats[i].i_mask) == p_formats[i].i_flags )
                     {
                         p_track->fmt.i_codec = p_formats[i].i_codec;
-                        p_track->fmt.audio.i_bitspersample = i_bits;
-                        p_track->fmt.audio.i_blockalign = p_soun->i_channelcount * i_bits / 8;
+                        p_track->fmt.audio.i_bitspersample = p_soun->i_constbitsperchannel;
+                        p_track->fmt.audio.i_blockalign =
+                                p_soun->i_channelcount * p_soun->i_constbitsperchannel / 8;
                         p_track->i_sample_size = p_track->fmt.audio.i_blockalign;
 
                         p_soun->i_qt_version = 0;
@@ -2368,6 +2709,8 @@ static int TrackCreateES( demux_t *p_demux, mp4_track_t *p_track,
 
     /* now see if esds is present and if so create a data packet
         with decoder_specific_info  */
+
+    /* Only if MP4V */
 #define p_decconfig p_esds->data.p_esds->es_descriptor.p_decConfigDescr
     if( ( ( p_esds = MP4_BoxGet( p_sample, "esds" ) ) ||
           ( p_esds = MP4_BoxGet( p_sample, "wave/esds" ) ) )&&
@@ -2375,7 +2718,7 @@ static int TrackCreateES( demux_t *p_demux, mp4_track_t *p_track,
         ( p_decconfig ) )
     {
         /* First update information based on i_objectTypeIndication */
-        switch( p_decconfig->i_objectTypeIndication )
+        switch( p_decconfig->i_objectProfileIndication )
         {
             case( 0x20 ): /* MPEG4 VIDEO */
                 p_track->fmt.i_codec = VLC_CODEC_MP4V;
@@ -2468,8 +2811,8 @@ static int TrackCreateES( demux_t *p_demux, mp4_track_t *p_track,
             default:
                 /* Unknown entry, but don't touch i_fourcc */
                 msg_Warn( p_demux,
-                          "unknown objectTypeIndication(0x%x) (Track[ID 0x%x])",
-                          p_decconfig->i_objectTypeIndication,
+                          "unknown objectProfileIndication(0x%x) (Track[ID 0x%x])",
+                          p_decconfig->i_objectProfileIndication,
                           p_track->i_track_ID );
                 break;
         }
@@ -2516,6 +2859,9 @@ static int TrackCreateES( demux_t *p_demux, mp4_track_t *p_track,
             case VLC_FOURCC( 'V', 'P', '3', '1' ):
             case VLC_FOURCC( '3', 'I', 'V', '1' ):
             case VLC_FOURCC( 'Z', 'y', 'G', 'o' ):
+            {
+                if ( p_sample->i_handler != ATOM_vide )
+                    break;
                 p_track->fmt.i_extra =
                     p_sample->data.p_sample_vide->i_qt_image_description;
                 if( p_track->fmt.i_extra > 0 )
@@ -2526,6 +2872,7 @@ static int TrackCreateES( demux_t *p_demux, mp4_track_t *p_track,
                             p_track->fmt.i_extra);
                 }
                 break;
+            }
 
             case VLC_CODEC_AMR_NB:
                 p_track->fmt.audio.i_rate = 8000;
@@ -2536,6 +2883,9 @@ static int TrackCreateES( demux_t *p_demux, mp4_track_t *p_track,
             case VLC_FOURCC( 'Q', 'D', 'M', 'C' ):
             case VLC_CODEC_QDM2:
             case VLC_CODEC_ALAC:
+            {
+                if ( p_sample->i_handler != ATOM_soun )
+                    break;
                 p_track->fmt.i_extra =
                     p_sample->data.p_sample_soun->i_qt_description;
                 if( p_track->fmt.i_extra > 0 )
@@ -2551,11 +2901,11 @@ static int TrackCreateES( demux_t *p_demux, mp4_track_t *p_track,
                     p_track->fmt.audio.i_rate = GetDWBE((uint8_t*)p_track->fmt.p_extra + 52);
                 }
                 break;
-
+            }
             case VLC_FOURCC( 'v', 'c', '-', '1' ):
             {
                 MP4_Box_t *p_dvc1 = MP4_BoxGet( p_sample, "dvc1" );
-                if( p_dvc1 )
+                if( p_dvc1 && BOXDATA(p_dvc1) )
                 {
                     p_track->fmt.i_extra = BOXDATA(p_dvc1)->i_vc1;
                     if( p_track->fmt.i_extra > 0 )
@@ -2577,7 +2927,7 @@ static int TrackCreateES( demux_t *p_demux, mp4_track_t *p_track,
             {
                 MP4_Box_t *p_avcC = MP4_BoxGet( p_sample, "avcC" );
 
-                if( p_avcC )
+                if( p_avcC && BOXDATA(p_avcC) )
                 {
                     p_track->fmt.i_extra = BOXDATA(p_avcC)->i_avcC;
                     if( p_track->fmt.i_extra > 0 )
@@ -2598,13 +2948,13 @@ static int TrackCreateES( demux_t *p_demux, mp4_track_t *p_track,
             {
                 MP4_Box_t *p_hvcC = MP4_BoxGet( p_sample, "hvcC" );
 
-                if( p_hvcC )
+                if( p_hvcC && BOXDATA(p_hvcC) )
                 {
-                    p_track->fmt.i_extra = p_hvcC->data.p_hvcC->i_hvcC;
+                    p_track->fmt.i_extra = BOXDATA(p_hvcC)->i_hvcC;
                     if( p_track->fmt.i_extra > 0 )
                     {
-                        p_track->fmt.p_extra = malloc( p_hvcC->data.p_hvcC->i_hvcC );
-                        memcpy( p_track->fmt.p_extra, p_hvcC->data.p_hvcC->p_hvcC,
+                        p_track->fmt.p_extra = malloc( BOXDATA(p_hvcC)->i_hvcC );
+                        memcpy( p_track->fmt.p_extra, BOXDATA(p_hvcC)->p_hvcC,
                                 p_track->fmt.i_extra );
                     }
                     p_track->fmt.i_codec = VLC_CODEC_HEVC;
@@ -2620,8 +2970,11 @@ static int TrackCreateES( demux_t *p_demux, mp4_track_t *p_track,
             case VLC_CODEC_ADPCM_MS:
             case VLC_CODEC_ADPCM_IMA_WAV:
             case VLC_CODEC_QCELP:
-                p_track->fmt.audio.i_blockalign = p_sample->data.p_sample_soun->i_bytes_per_frame;
+            {
+                if ( p_sample->i_handler == ATOM_soun )
+                    p_track->fmt.audio.i_blockalign = p_sample->data.p_sample_soun->i_bytes_per_frame;
                 break;
+            }
 
             default:
                 msg_Dbg( p_demux, "Unrecognized FourCC %4.4s", (char *)&p_sample->i_type );
@@ -2907,19 +3260,8 @@ static void MP4_TrackCreate( demux_t *p_demux, mp4_track_t *p_track,
     if( p_track->i_timescale == 0 )
         return;
 
-    if( BOXDATA(p_mdhd)->i_language_code < 0x400 )
-    {
-        strcpy( language, MP4_ConvertMacCode( BOXDATA(p_mdhd)->i_language_code ) );
-        p_track->b_mac_encoding = true;
-    }
-    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] = BOXDATA(p_mdhd)->i_language[i];
-        language[3] = '\0';
-    }
+    memcpy( &language, BOXDATA(p_mdhd)->rgs_language, 3 );
+    p_track->b_mac_encoding = BOXDATA(p_mdhd)->b_mac_encoding;
 
     switch( p_hdlr->data.p_hdlr->i_handler_type )
     {
@@ -2947,6 +3289,11 @@ static void MP4_TrackCreate( demux_t *p_demux, mp4_track_t *p_track,
             p_track->fmt.i_cat = SPU_ES;
             break;
 
+        /* closed captions */
+        case( ATOM_clcp ):
+            p_track->fmt.i_cat = SPU_ES;
+            break;
+
         default:
             return;
     }
@@ -3184,7 +3531,6 @@ static int MP4_TrackSeek( demux_t *p_demux, mp4_track_t *p_track,
     }
 
     p_track->b_selected = true;
-
     if( !TrackGotoChunkSample( p_demux, p_track, i_chunk, i_sample ) )
         p_track->b_selected = true;
 
@@ -3197,63 +3543,93 @@ static int MP4_TrackSeek( demux_t *p_demux, mp4_track_t *p_track,
  *
  */
 #define QT_V0_MAX_SAMPLES 1024
-static uint32_t MP4_TrackSampleSize( mp4_track_t *p_track, uint32_t *pi_nb_samples )
+static uint32_t MP4_TrackGetReadSize( mp4_track_t *p_track, uint32_t *pi_nb_samples )
 {
-    uint32_t i_size;
-    MP4_Box_data_sample_soun_t *p_soun;
+    uint32_t i_size = 0;
+    *pi_nb_samples = 0;
 
-    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->i_sample == p_track->i_sample_count )
+        return 0;
 
-    if( p_track->fmt.i_cat != AUDIO_ES )
+    if ( p_track->fmt.i_cat != AUDIO_ES )
     {
         *pi_nb_samples = 1;
-        return p_track->i_sample_size;
-    }
 
-    p_soun = p_track->p_sample->data.p_sample_soun;
-
-    if( p_soun->i_qt_version == 1 )
-    {
-        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 )
-            i_size *= p_soun->i_bytes_per_frame;
+        if( p_track->i_sample_size == 0 ) /* all sizes are different */
+            return p_track->p_sample_size[p_track->i_sample];
         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;
+            return p_track->i_sample_size;
     }
     else
     {
-        mp4_chunk_t *p_chunk = &p_track->chunk[p_track->i_chunk];
-        int64_t i_length = CLOCK_FREQ / 10;
-        uint32_t i_samples = 0;
-        uint32_t i_maxsamples = 0;
-        for( uint32_t i=p_track->i_sample; i<p_chunk->i_sample_count; i++ )
+        const MP4_Box_data_sample_soun_t *p_soun = p_track->p_sample->data.p_sample_soun;
+        const mp4_chunk_t *p_chunk = &p_track->chunk[p_track->i_chunk];
+        uint32_t i_max_samples = p_chunk->i_sample_count - p_chunk->i_sample + 1;
+
+        /* Group audio packets so we don't call demux for single sample unit */
+        if( p_track->fmt.i_original_fourcc == VLC_CODEC_DVD_LPCM &&
+            p_soun->i_constLPCMframesperaudiopacket &&
+            p_soun->i_constbytesperaudiopacket )
         {
-            i_length -= CLOCK_FREQ * p_chunk->p_sample_delta_dts[i] / p_track->i_timescale;
-            if ( i_length < 0 ) break;
-            i_maxsamples++;
+            /* uncompressed case */
+            uint32_t i_packets = i_max_samples / p_soun->i_constLPCMframesperaudiopacket;
+            if ( UINT32_MAX / p_soun->i_constbytesperaudiopacket < i_packets )
+                i_packets = UINT32_MAX / p_soun->i_constbytesperaudiopacket;
+            *pi_nb_samples = i_packets * p_soun->i_constLPCMframesperaudiopacket;
+            return i_packets * p_soun->i_constbytesperaudiopacket;
         }
 
-        i_samples = __MIN( QT_V0_MAX_SAMPLES, i_samples );
-        i_samples = __MIN( i_maxsamples, i_samples );
-        if ( i_samples == 0 ) i_samples = 1;
-        i_size = i_samples * p_track->i_sample_size;
-        *pi_nb_samples = i_samples;
+        /* all samples have a different size */
+        if( p_track->i_sample_size == 0 )
+        {
+            *pi_nb_samples = 1;
+            return p_track->p_sample_size[p_track->i_sample];
+        }
+
+        if( p_soun->i_qt_version == 1 )
+        {
+            if ( p_soun->i_compressionid != 0 || p_soun->i_bytes_per_sample > 1 ) /* compressed */
+            {
+                /* in this case we are dealing with compressed data
+                   -2 in V1: additional fields are meaningless (VBR and such) */
+                *pi_nb_samples = i_max_samples;//p_track->chunk[p_track->i_chunk].i_sample_count;
+                if( p_track->fmt.audio.i_blockalign > 1 )
+                    *pi_nb_samples = p_soun->i_sample_per_packet;
+                i_size = *pi_nb_samples / p_soun->i_sample_per_packet * p_soun->i_bytes_per_frame;
+                return i_size;
+            }
+            else /* uncompressed case */
+            {
+                uint32_t i_packets;
+                if( p_track->fmt.audio.i_blockalign > 1 )
+                    i_packets = 1;
+                else
+                    i_packets = i_max_samples / p_soun->i_sample_per_packet;
+
+                if ( UINT32_MAX / p_soun->i_bytes_per_frame < i_packets )
+                    i_packets = UINT32_MAX / p_soun->i_bytes_per_frame;
+
+                *pi_nb_samples = i_packets * p_soun->i_sample_per_packet;
+                i_size = i_packets * p_soun->i_bytes_per_frame;
+                return i_size;
+            }
+        }
+
+        /* uncompressed v0 */
+        *pi_nb_samples = 0;
+        for( uint32_t i=p_track->i_sample;
+             i<p_chunk->i_sample_first+p_chunk->i_sample_count &&
+             i<p_track->i_sample_count;
+             i++ )
+        {
+            (*pi_nb_samples)++;
+            if ( p_track->i_sample_size == 0 )
+                i_size += p_track->p_sample_size[i];
+            else
+                i_size += p_track->i_sample_size;
+            if ( *pi_nb_samples == QT_V0_MAX_SAMPLES )
+                break;
+        }
     }
 
     //fprintf( stderr, "size=%d\n", i_size );
@@ -3300,55 +3676,24 @@ static uint64_t MP4_TrackGetPos( mp4_track_t *p_track )
 
 static int MP4_TrackNextSample( demux_t *p_demux, mp4_track_t *p_track, uint32_t i_samples )
 {
-    if( p_track->fmt.i_cat == AUDIO_ES && p_track->i_sample_size != 0 )
+    if ( UINT32_MAX - p_track->i_sample < i_samples )
     {
-        MP4_Box_data_sample_soun_t *p_soun;
+        p_track->i_sample = UINT32_MAX;
+        return VLC_EGENERIC;
+    }
 
-        p_soun = p_track->p_sample->data.p_sample_soun;
+    p_track->i_sample += i_samples;
 
-        if( p_soun->i_qt_version == 1 )
-        {
-            /* we read chunk by chunk unless a blockalign is requested */
-            if( p_track->fmt.audio.i_blockalign > 1 )
-                p_track->i_sample += p_soun->i_sample_per_packet;
-            else
-                p_track->i_sample += p_track->chunk[p_track->i_chunk].i_sample_count;
-        }
-        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) */
-            p_track->i_sample += 1;
-        }
-        else
-        {
-            /* FIXME */
-            p_track->i_sample += i_samples;
-            if( p_track->i_sample >
-                p_track->chunk[p_track->i_chunk].i_sample_first +
-                p_track->chunk[p_track->i_chunk].i_sample_count )
-            {
-                p_track->i_sample =
-                    p_track->chunk[p_track->i_chunk].i_sample_first +
-                    p_track->chunk[p_track->i_chunk].i_sample_count;
-            }
-        }
-    }
-    else
-    {
-        p_track->i_sample++;
-    }
-
-    if( p_track->i_sample >= p_track->i_sample_count )
-        return VLC_EGENERIC;
-
-    /* Have we changed chunk ? */
-    if( p_track->i_sample >=
-            p_track->chunk[p_track->i_chunk].i_sample_first +
-            p_track->chunk[p_track->i_chunk].i_sample_count )
-    {
-        if( TrackGotoChunkSample( p_demux, p_track, p_track->i_chunk + 1,
-                                  p_track->i_sample ) )
+    if( p_track->i_sample >= p_track->i_sample_count )
+        return VLC_EGENERIC;
+
+    /* Have we changed chunk ? */
+    if( p_track->i_sample >=
+            p_track->chunk[p_track->i_chunk].i_sample_first +
+            p_track->chunk[p_track->i_chunk].i_sample_count )
+    {
+        if( TrackGotoChunkSample( p_demux, p_track, p_track->i_chunk + 1,
+                                  p_track->i_sample ) )
         {
             msg_Warn( p_demux, "track[0x%x] will be disabled "
                       "(cannot restart decoder)", p_track->i_track_ID );
@@ -3421,47 +3766,6 @@ static void MP4_TrackSetELST( demux_t *p_demux, mp4_track_t *tk,
     }
 }
 
-/* */
-static const char *MP4_ConvertMacCode( uint16_t i_code )
-{
-    static const struct { const char psz_iso639_1[3]; uint16_t i_code; } p_cvt[] = {
-        { "en",   0 }, { "fr",   1 }, { "de",   2 }, { "it",   3 }, { "nl",   4 },
-        { "sv",   5 }, { "es",   6 }, { "da",   7 }, { "pt",   8 }, { "no",   9 },
-        { "he",  10 }, { "ja",  11 }, { "ar",  12 }, { "fi",  13 }, { "el",  14 },
-        { "is",  15 }, { "mt",  16 }, { "tr",  17 }, { "hr",  18 }, { "zh",  19 },
-        { "ur",  20 }, { "hi",  21 }, { "th",  22 }, { "ko",  23 }, { "lt",  24 },
-        { "pl",  25 }, { "hu",  26 }, { "et",  27 }, { "lv",  28 }, //{ "??",  29 },
-        { "fo",  30 }, { "fa",  31 }, { "ru",  32 }, { "zh",  33 }, { "nl",  34 },
-        { "ga",  35 }, { "sq",  36 }, { "ro",  37 }, { "cs",  38 }, { "sk",  39 },
-        { "sl",  40 }, { "yi",  41 }, { "sr",  42 }, { "mk",  43 }, { "bg",  44 },
-        { "uk",  45 }, { "be",  46 }, { "uz",  47 }, { "az",  48 }, { "kk",  48 },
-        { "az",  50 }, { "hy",  51 }, { "ka",  52 }, { "mo",  53 }, { "ky",  54 },
-        { "tg",  55 }, { "tk",  56 }, { "mn",  57 }, { "mn",  58 }, { "ps",  59 },
-        { "ku",  60 }, { "ks",  61 }, { "sd",  62 }, { "bo",  63 }, { "ne",  64 },
-        { "sa",  65 }, { "mr",  66 }, { "bn",  67 }, { "as",  68 }, { "gu",  69 },
-        { "pa",  70 }, { "or",  71 }, { "ml",  72 }, { "kn",  73 }, { "ta",  74 },
-        { "te",  75 }, { "si",  76 }, { "my",  77 }, { "km",  78 }, { "lo",  79 },
-        { "vi",  80 }, { "id",  81 }, { "tl",  82 }, { "ms",  83 }, { "ms",  84 },
-        { "am",  85 }, { "ti",  86 }, { "om",  87 }, { "so",  88 }, { "sw",  89 },
-        { "rw",  90 }, { "rn",  91 }, { "ny",  92 }, { "mg",  93 }, { "eo",  94 },
-
-                                                     { "cy", 128 }, { "eu", 129 },
-        { "ca", 130 }, { "la", 131 }, { "qu", 132 }, { "gn", 133 }, { "ay", 134 },
-        { "tt", 135 }, { "ug", 136 }, { "dz", 137 }, { "jv", 138 }, { "su", 139 },
-        { "gl", 140 }, { "af", 141 }, { "br", 142 }, { "iu", 143 }, { "gd", 144 },
-        { "gv", 145 }, { "ga", 146 }, { "to", 147 }, { "el", 148 },
-        /* */
-        { "", 0 }
-    };
-    int i;
-    for( i = 0; *p_cvt[i].psz_iso639_1; i++ )
-    {
-        if( p_cvt[i].i_code == i_code )
-            return p_cvt[i].psz_iso639_1;
-    }
-    return "";
-}
-
 /******************************************************************************
  *     Here are the functions used for fragmented MP4
  *****************************************************************************/
@@ -3714,7 +4018,7 @@ static void FlushChunk( demux_t *p_demux, mp4_track_t *tk )
         else
             p_block->i_pts = VLC_TS_INVALID;
 
-        es_out_Send( p_demux->out, tk->p_es, p_block );
+        MP4_Block_Send( p_demux, tk, p_block );
 
         tk->i_sample++;
     }
@@ -3970,12 +4274,13 @@ static int MP4_frg_GetChunk( demux_t *p_demux, MP4_Box_t *p_chunk, unsigned *i_t
     return VLC_SUCCESS;
 }
 
+
 /**
  * Get the next chunk of the track identified by i_tk_id.
  * \Note We don't want to seek all the time, so if the first chunk given by the
  * input method doesn't belong to the right track, we don't throw it away,
  * and so, in general, this function fetch more than one chunk.
- * Not to mention that a new init segment might be put everywhere
+ * Not to mention that a new init fragment might be put everywhere
  * between two chunks by the input method.
  */
 static int MP4_frg_GetChunks( demux_t *p_demux, const unsigned i_tk_id )
@@ -4006,7 +4311,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 = BOXDATA(p_tkhd)->i_track_ID;
+                tid = p_tkhd->data.p_tkhd->i_track_ID;
             }
             else                      /* Smooth Streaming */
             {
@@ -4017,7 +4322,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 = BOXDATA(p_stra)->i_track_ID;
+                tid = p_stra->data.p_stra->i_track_ID;
             }
 
             p_track = MP4_frg_GetTrackByID( p_demux, tid );
@@ -4064,6 +4369,162 @@ static int MP4_frg_TrackSelect( demux_t *p_demux, mp4_track_t *p_track )
     return VLC_SUCCESS;
 }
 
+/**
+ * DemuxFrg: read packet and send them to decoders
+ * \return 1 on success, 0 on error.
+ * TODO check for newly selected track
+ */
+int DemuxFrg( demux_t *p_demux )
+{
+    demux_sys_t *p_sys = p_demux->p_sys;
+    unsigned i_track;
+    unsigned i_track_selected;
+
+    /* check for newly selected/unselected track */
+    for( i_track = 0, i_track_selected = 0; i_track < p_sys->i_tracks; i_track++ )
+    {
+        mp4_track_t *tk = &p_sys->track[i_track];
+        bool b;
+
+        if( !tk->b_ok || tk->b_chapter )
+            continue;
+
+        es_out_Control( p_demux->out, ES_OUT_GET_ES_STATE, tk->p_es, &b );
+        msg_Dbg( p_demux, "track %u %s!", tk->i_track_ID, b ? "enabled" : "disabled" );
+
+        if( tk->b_selected && !b )
+        {
+            MP4_TrackUnselect( p_demux, tk );
+        }
+        else if( !tk->b_selected && b)
+        {
+            MP4_frg_TrackSelect( p_demux, tk );
+        }
+
+        if( tk->b_selected )
+            i_track_selected++;
+    }
+
+    if( i_track_selected <= 0 )
+    {
+        p_sys->i_time += __MAX( p_sys->i_timescale / 10 , 1 );
+        if( p_sys->i_timescale > 0 )
+        {
+            int64_t i_length = CLOCK_FREQ *
+                               (mtime_t)p_sys->moovfragment.i_duration /
+                               (mtime_t)p_sys->i_timescale;
+            if( MP4_GetMoviePTS( p_sys ) >= i_length )
+                return 0;
+            return 1;
+        }
+
+        msg_Warn( p_demux, "no track selected, exiting..." );
+        return 0;
+    }
+
+    /* first wait for the good time to read a packet */
+    es_out_Control( p_demux->out, ES_OUT_SET_PCR, VLC_TS_0 + p_sys->i_pcr );
+
+    p_sys->i_pcr = MP4_GetMoviePTS( p_sys );
+
+    /* we will read 100ms for each stream so ...*/
+    p_sys->i_time += __MAX( p_sys->i_timescale / 10, 1 );
+
+    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 )
+        {
+            msg_Warn( p_demux, "Skipping track id %u", tk->i_track_ID );
+            continue;
+        }
+
+        if( !tk->b_has_non_empty_cchunk )
+        {
+            if( MP4_frg_GetChunks( p_demux, tk->i_track_ID ) != VLC_SUCCESS )
+            {
+                msg_Info( p_demux, "MP4_frg_GetChunks returned error. End of stream?" );
+                return 0;
+            }
+        }
+
+        while( MP4_TrackGetDTS( p_demux, tk ) < MP4_GetMoviePTS( p_sys ) )
+        {
+            block_t *p_block;
+            int64_t i_delta;
+
+            mp4_chunk_t *ck = tk->cchunk;
+            if( ck->i_sample >= ck->i_sample_count )
+            {
+                msg_Err( p_demux, "sample %"PRIu32" of %"PRIu32"",
+                                    ck->i_sample, ck->i_sample_count );
+                return 0;
+            }
+
+            uint32_t sample_size = ck->p_sample_size[ck->i_sample];
+            p_block = block_Alloc( sample_size );
+            uint8_t *src = ck->p_sample_data[ck->i_sample];
+            memcpy( p_block->p_buffer, src, sample_size );
+
+            ck->i_sample++;
+            if( ck->i_sample == ck->i_sample_count )
+                tk->b_has_non_empty_cchunk = false;
+
+            /* 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;
+
+            MP4_Block_Send( p_demux, tk, p_block );
+
+            tk->i_sample++;
+
+            if( !tk->b_has_non_empty_cchunk )
+                break;
+        }
+    }
+    return 1;
+}
+
+static MP4_Box_t * LoadNextChunk( demux_t *p_demux )
+{
+    /* Read Next Chunk */
+    MP4_Box_t *p_chunk = MP4_BoxGetNextChunk( p_demux->s );
+    if( !p_chunk )
+    {
+        msg_Warn( p_demux, "no next chunk" );
+        return NULL;
+    }
+
+    if( !p_chunk->p_first )
+    {
+        msg_Warn( p_demux, "no next chunk child" );
+        return NULL;
+    }
+
+    return p_chunk;
+}
+
+static bool BoxExistsInRootTree( MP4_Box_t *p_root, uint32_t i_type, off_t i_pos )
+{
+    while ( p_root )
+    {
+        if ( p_root->i_pos == i_pos )
+        {
+            assert( i_type == p_root->i_type );
+            break;
+        }
+        p_root = p_root->p_next;
+    }
+    return (p_root != NULL);
+}
 
 /* Keeps an ordered chain of all fragments */
 static bool AddFragment( demux_t *p_demux, MP4_Box_t *p_moox )
@@ -4078,13 +4539,29 @@ static bool AddFragment( demux_t *p_demux, MP4_Box_t *p_moox )
         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;
+                p_sys->i_overall_duration = BOXDATA(p_mvhd)->i_duration;
+            }
+
+            if ( MP4_BoxCount( p_moox, "mvex" ) || !p_mvhd )
+            { /* duration might be wrong an be set to whole duration :/ */
+               p_sys->moovfragment.i_duration = 0;
+               MP4_Box_t *p_tkhd;
+               MP4_Box_t *p_trak = MP4_BoxGet( p_moox, "trak" );
+               while( p_trak )
+               {
+                   if ( p_trak->i_type == ATOM_trak && (p_tkhd = MP4_BoxGet( p_trak, "tkhd" )) )
+                   {
+                       if ( BOXDATA(p_tkhd)->i_duration > p_sys->moovfragment.i_duration )
+                           p_sys->moovfragment.i_duration = BOXDATA(p_tkhd)->i_duration;
+                   }
+                   p_trak = p_trak->p_next;
+               }
             }
+
             msg_Dbg( p_demux, "added fragment %4.4s", (char*) &p_moox->i_type );
             return true;
         }
@@ -4160,6 +4637,7 @@ static bool AddFragment( demux_t *p_demux, MP4_Box_t *p_moox )
                 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 )
              {
@@ -4180,7 +4658,7 @@ static bool AddFragment( demux_t *p_demux, MP4_Box_t *p_moox )
         }
         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;
+            i_traf_base_data_offset = p_new->p_moox->i_pos /* + 8*/;
         }
         else
         {
@@ -4273,11 +4751,14 @@ static bool AddFragment( demux_t *p_demux, MP4_Box_t *p_moox )
     if ( !p_mehd )
     {
         p_sys->i_overall_duration = 0;
-        p_new = &p_sys->moovfragment;
-        while ( p_new )
+        if ( p_sys->b_fragments_probed )
         {
-            p_sys->i_overall_duration += p_new->i_duration;
-            p_new = p_new->p_next;
+            p_new = &p_sys->moovfragment;
+            while ( p_new )
+            {
+                p_sys->i_overall_duration += p_new->i_duration;
+                p_new = p_new->p_next;
+            }
         }
     }
     else
@@ -4287,7 +4768,45 @@ static bool AddFragment( demux_t *p_demux, MP4_Box_t *p_moox )
     return true;
 }
 
-static int ProbeFragments( demux_t *p_demux )
+static int ProbeIndex( demux_t *p_demux )
+{
+    demux_sys_t *p_sys = p_demux->p_sys;
+    uint64_t i_backup_pos, i_stream_size;
+    uint8_t mfro[MP4_MFRO_BOXSIZE];
+    assert( p_sys->b_seekable );
+
+    if ( MP4_BoxCount( p_sys->p_root, "/mfra" ) )
+        return VLC_SUCCESS;
+
+    i_stream_size = stream_Size( p_demux->s );
+    if ( ( i_stream_size >> 62 ) ||
+         ( i_stream_size < MP4_MFRO_BOXSIZE ) ||
+         ( !MP4_stream_Tell( p_demux->s, &i_backup_pos ) ) ||
+         ( stream_Seek( p_demux->s, i_stream_size - MP4_MFRO_BOXSIZE ) != VLC_SUCCESS )
+       )
+    {
+        msg_Dbg( p_demux, "Probing tail for mfro has failed" );
+        return VLC_EGENERIC;
+    }
+
+    if ( stream_Read( p_demux->s, &mfro, MP4_MFRO_BOXSIZE ) == MP4_MFRO_BOXSIZE &&
+         VLC_FOURCC(mfro[4],mfro[5],mfro[6],mfro[7]) == ATOM_mfro &&
+         GetDWBE( &mfro ) == MP4_MFRO_BOXSIZE )
+    {
+        uint32_t i_offset = GetDWBE( &mfro[12] );
+        msg_Dbg( p_demux, "will read mfra index at %"PRIu64, i_stream_size - i_offset );
+        if ( i_stream_size > i_offset &&
+             stream_Seek( p_demux->s, i_stream_size - i_offset ) == VLC_SUCCESS )
+        {
+            msg_Dbg( p_demux, "reading mfra index at %"PRIu64, i_stream_size - i_offset );
+            MP4_ReadBoxContainerChildren( p_demux->s, p_sys->p_root, ATOM_mfra );
+        }
+    }
+
+    return stream_Seek( p_demux->s, i_backup_pos );
+}
+
+static int ProbeFragments( demux_t *p_demux, bool b_force )
 {
     demux_sys_t *p_sys = p_demux->p_sys;
     uint64_t i_current_pos;
@@ -4297,15 +4816,29 @@ static int ProbeFragments( demux_t *p_demux )
 
     assert( p_sys->p_root );
 
-    MP4_ReadBoxContainerChildren( p_demux->s, p_sys->p_root, 0 ); /* Get the rest of the file */
+    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 )
+    if ( !p_sys->moovfragment.p_moox )
     {
-        MP4_BoxDumpStructure( p_demux->s, p_sys->p_root );
-        return VLC_EGENERIC;
+        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 );
     }
-    AddFragment( p_demux, p_moov );
 
     MP4_Box_t *p_moof = MP4_BoxGet( p_sys->p_root, "moof" );
     while ( p_moof )
@@ -4315,137 +4848,767 @@ static int ProbeFragments( demux_t *p_demux )
         p_moof = p_moof->p_next;
     }
 
-    p_sys->b_fragments_probed = true;
-
     MP4_Box_t *p_mdat = MP4_BoxGet( p_sys->p_root, "mdat" );
-    assert( p_mdat );
-    stream_Seek( p_demux->s, p_mdat->i_pos );
-    msg_Dbg( p_demux, "rewinding to mdat %"PRId64, p_mdat->i_pos );
+    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.
- * TODO check for newly selected track
- */
-int DemuxFrg( demux_t *p_demux )
+static mp4_fragment_t * GetFragmentByPos( demux_t *p_demux, uint64_t i_pos, bool b_exact )
 {
-    demux_sys_t *p_sys = p_demux->p_sys;
-    unsigned i_track;
-    unsigned i_track_selected;
-
-    /* check for newly selected/unselected track */
-    for( i_track = 0, i_track_selected = 0; i_track < p_sys->i_tracks; i_track++ )
+    mp4_fragment_t *p_fragment = &p_demux->p_sys->moovfragment;
+    while ( p_fragment )
     {
-        mp4_track_t *tk = &p_sys->track[i_track];
-        bool b;
-
-        if( !tk->b_ok || tk->b_chapter )
-            continue;
-
-        es_out_Control( p_demux->out, ES_OUT_GET_ES_STATE, tk->p_es, &b );
-        msg_Dbg( p_demux, "track %u %s!", tk->i_track_ID, b ? "enabled" : "disabled" );
-
-        if( tk->b_selected && !b )
+        if ( i_pos <= p_fragment->i_chunk_range_max_offset &&
+             ( !b_exact || i_pos >= p_fragment->i_chunk_range_min_offset ) )
         {
-            MP4_TrackUnselect( p_demux, tk );
+            msg_Dbg( p_demux, "fragment matched %"PRIu64" << %"PRIu64" << %"PRIu64,
+                     p_fragment->i_chunk_range_min_offset, i_pos,
+                     p_fragment->i_chunk_range_max_offset );
+            return p_fragment;
         }
-        else if( !tk->b_selected && b)
+        else
         {
-            MP4_frg_TrackSelect( p_demux, tk );
+            p_fragment = p_fragment->p_next;
         }
-
-        if( tk->b_selected )
-            i_track_selected++;
     }
+    return NULL;
+}
 
-    if( i_track_selected <= 0 )
+/* Get a matching fragment data start by clock time */
+static mp4_fragment_t * GetFragmentByTime( demux_t *p_demux, const mtime_t i_time )
+{
+    mp4_fragment_t *p_fragment = &p_demux->p_sys->moovfragment;
+    mtime_t i_base_time = 0;
+    while ( p_fragment )
     {
-        p_sys->i_time += __MAX( p_sys->i_timescale / 10 , 1 );
-        if( p_sys->i_timescale > 0 )
+        mtime_t i_length = CLOCK_FREQ * p_fragment->i_duration / p_demux->p_sys->i_timescale;
+        if ( i_time >= i_base_time &&
+             i_time <= i_base_time + i_length )
         {
-            int64_t i_length = CLOCK_FREQ *
-                               (mtime_t)p_sys->moovfragment.i_duration /
-                               (mtime_t)p_sys->i_timescale;
-            if( MP4_GetMoviePTS( p_sys ) >= i_length )
-                return 0;
-            return 1;
+            return p_fragment;
+        }
+        else
+        {
+            i_base_time += i_length;
+            p_fragment = p_fragment->p_next;
         }
 
-        msg_Warn( p_demux, "no track selected, exiting..." );
-        return 0;
+        if ( !p_demux->p_sys->b_fragments_probed )
+            return NULL; /* We have no way to guess missing fragments time */
     }
+    return NULL;
+}
 
-    /* first wait for the good time to read a packet */
-    es_out_Control( p_demux->out, ES_OUT_SET_PCR, VLC_TS_0 + p_sys->i_pcr );
+/* Returns fragment scaled time offset */
+static mtime_t LeafGetFragmentTimeOffset( demux_t *p_demux, mp4_fragment_t *p_fragment )
+{
+    mtime_t i_base_scaledtime = 0;
+    mp4_fragment_t *p_current = &p_demux->p_sys->moovfragment;
+    while ( p_current != p_fragment )
+    {
+        i_base_scaledtime += p_current->i_duration;
+        p_current = p_current->p_next;
+    }
+    return i_base_scaledtime;
+}
 
-    p_sys->i_pcr = MP4_GetMoviePTS( p_sys );
+static int LeafParseTRUN( demux_t *p_demux, mp4_track_t *p_track,
+                      const uint32_t i_defaultduration, const uint32_t i_defaultsize,
+                      const MP4_Box_data_trun_t *p_trun, uint32_t * const pi_mdatlen )
+{
+    assert( p_trun->i_sample_count );
+    msg_Dbg( p_demux, "Default sample duration %"PRIu32" size %"PRIu32" firstdts %"PRIu64,
+             i_defaultduration, i_defaultsize, p_track->i_first_dts );
 
-    /* we will read 100ms for each stream so ...*/
-    p_sys->i_time += __MAX( p_sys->i_timescale / 10, 1 );
+    uint32_t dur = 0, len;
+    uint32_t chunk_size = 0;
+    mtime_t i_nzdts = CLOCK_FREQ * p_track->i_time / p_track->i_timescale;
 
-    for( i_track = 0; i_track < p_sys->i_tracks; i_track++ )
+    mtime_t i_nzpts;
+
+    for( uint32_t i = 0; i < p_trun->i_sample_count; i++)
     {
-        mp4_track_t *tk = &p_sys->track[i_track];
+        i_nzdts += CLOCK_FREQ * dur / p_track->i_timescale;
+        i_nzpts = i_nzdts;
 
-        if( !tk->b_ok || tk->b_chapter || !tk->b_selected )
+        if( p_trun->i_flags & MP4_TRUN_SAMPLE_DURATION )
+            dur = p_trun->p_samples[i].i_duration;
+        else
+            dur = i_defaultduration;
+
+        p_track->i_time += dur;
+
+        if( p_trun->i_flags & MP4_TRUN_SAMPLE_TIME_OFFSET )
         {
-            msg_Warn( p_demux, "Skipping track id %u", tk->i_track_ID );
+            if ( p_trun->i_version == 0 )
+                i_nzpts += CLOCK_FREQ * (int32_t) p_trun->p_samples[i].i_composition_time_offset / p_track->i_timescale;
+            else
+                i_nzpts += CLOCK_FREQ * p_trun->p_samples[i].i_composition_time_offset / p_track->i_timescale;
+        }
+
+        if( p_trun->i_flags & MP4_TRUN_SAMPLE_SIZE )
+            len = p_trun->p_samples[i].i_size;
+        else
+            len = i_defaultsize;
+
+        assert( dur ); /* dur, dur ! */
+        assert( len );
+
+        if ( chunk_size + len > *pi_mdatlen )
+        {
+            /* update data left in mdat */
+            *pi_mdatlen -= chunk_size;
+            return VLC_EGENERIC;
+        }
+
+        block_t *p_block = MP4_Block_Read( p_demux, p_track, __MIN( len, INT32_MAX ) );
+        uint32_t i_read = ( p_block ) ? p_block->i_buffer : 0;
+        if( i_read < len )
+        {
+            /* update data left in mdat */
+            *pi_mdatlen -= chunk_size;
+            *pi_mdatlen -= i_read;
+            free( p_block );
+            return VLC_EGENERIC;
+        }
+
+        if ( p_demux->p_sys->i_pcr < VLC_TS_0 )
+        {
+            p_demux->p_sys->i_pcr = i_nzdts;
+            es_out_Control( p_demux->out, ES_OUT_SET_PCR, VLC_TS_0 + i_nzdts );
+        }
+
+        if ( p_track->p_es )
+        {
+            p_block->i_dts = VLC_TS_0 + i_nzdts;
+            p_block->i_pts = VLC_TS_0 + i_nzpts;
+            p_block->i_length = CLOCK_FREQ * dur / p_track->i_timescale;
+            MP4_Block_Send( p_demux, p_track, p_block );
+        }
+        else free( p_block );
+
+        chunk_size += len;
+    }
+
+    /* update data left in mdat */
+    *pi_mdatlen -= chunk_size;
+    return VLC_SUCCESS;
+}
+
+static int LeafGetTrackAndChunkByMOOVPos( demux_t *p_demux, uint64_t *pi_pos,
+                                      mp4_track_t **pp_tk, unsigned int *pi_chunk )
+{
+    const demux_sys_t *p_sys = p_demux->p_sys;
+
+    mp4_track_t *p_tk_closest = NULL;
+    uint64_t i_closest = UINT64_MAX;
+    unsigned int i_chunk_closest;
+
+    *pp_tk = NULL;
+
+    for ( unsigned int i_track = 0; i_track < p_sys->i_tracks; i_track++ )
+    {
+        for( unsigned int i_chunk = 0; i_chunk < p_sys->track[i_track].i_chunk_count; i_chunk++ )
+        {
+            if ( p_sys->track[i_track].chunk[i_chunk].i_offset > *pi_pos )
+            {
+                i_closest = __MIN( i_closest, p_sys->track[i_track].chunk[i_chunk].i_offset );
+                p_tk_closest = &p_sys->track[i_track];
+                i_chunk_closest = i_chunk;
+            }
+
+            if ( *pi_pos == p_sys->track[i_track].chunk[i_chunk].i_offset )
+            {
+                *pp_tk = &p_sys->track[i_track];
+                *pi_chunk = i_chunk;
+                return VLC_SUCCESS;
+            }
+        }
+    }
+
+    if ( i_closest != UINT64_MAX )
+    {
+        *pi_pos = i_closest;
+        *pp_tk = p_tk_closest;
+        *pi_chunk = i_chunk_closest;
+        return VLC_ENOOBJ;
+    }
+    else return VLC_EGENERIC;
+}
+
+static int LeafMOOVGetSamplesSize( const mp4_track_t *p_track, const uint32_t i_sample,
+                           uint32_t *pi_samplestoread, uint32_t *pi_samplessize,
+                           const uint32_t i_maxbytes, const uint32_t i_maxsamples )
+{
+    MP4_Box_t *p_stsz = MP4_BoxGet( p_track->p_stbl, "stsz" );
+    if ( !p_stsz )
+        return VLC_EGENERIC;
+
+    if ( BOXDATA(p_stsz)->i_sample_size == 0 )
+    {
+        uint32_t i_entry = i_sample;
+        uint32_t i_totalbytes = 0;
+        *pi_samplestoread = 1;
+
+        if ( i_sample >= BOXDATA(p_stsz)->i_sample_count )
+            return VLC_EGENERIC;
+
+        *pi_samplessize = BOXDATA(p_stsz)->i_entry_size[i_sample];
+        i_totalbytes += *pi_samplessize;
+
+        if ( *pi_samplessize > i_maxbytes )
+            return VLC_EGENERIC;
+
+        i_entry++;
+        while( i_entry < BOXDATA(p_stsz)->i_sample_count &&
+               *pi_samplessize == BOXDATA(p_stsz)->i_entry_size[i_entry] &&
+               i_totalbytes + *pi_samplessize < i_maxbytes &&
+               *pi_samplestoread < i_maxsamples
+              )
+        {
+            i_totalbytes += *pi_samplessize;
+            (*pi_samplestoread)++;
+        }
+
+        *pi_samplessize = i_totalbytes;
+    }
+    else
+    {
+        /* all samples have same size */
+        *pi_samplessize = BOXDATA(p_stsz)->i_sample_size;
+        *pi_samplestoread = __MIN( i_maxsamples, BOXDATA(p_stsz)->i_sample_count );
+        *pi_samplestoread = __MIN( i_maxbytes / *pi_samplessize, *pi_samplestoread );
+        *pi_samplessize = *pi_samplessize * *pi_samplestoread;
+    }
+
+    return VLC_SUCCESS;
+}
+
+static inline mtime_t LeafGetMOOVTimeInChunk( const mp4_chunk_t *p_chunk, uint32_t i_sample )
+{
+    mtime_t i_time = 0;
+    uint32_t i_index = 0;
+
+    while( i_sample > 0 )
+    {
+        if( i_sample > p_chunk->p_sample_count_dts[i_index] )
+        {
+            i_time += 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];
+            i_index++;
+        }
+        else
+        {
+            i_time += i_sample * p_chunk->p_sample_delta_dts[i_index];
+            break;
+        }
+    }
+
+    return i_time;
+}
+
+static int LeafParseMDATwithMOOV( demux_t *p_demux )
+{
+    demux_sys_t *p_sys = p_demux->p_sys;
+
+    assert( p_sys->context.i_current_box_type == ATOM_mdat );
+    assert( p_sys->context.p_fragment->p_moox->i_type == ATOM_moov );
+
+    uint64_t i_current_pos;
+    if ( !MP4_stream_Tell( p_demux->s, &i_current_pos ) )
+        return VLC_EGENERIC;
+
+    if ( p_sys->context.i_mdatbytesleft == 0 ) /* Start parsing new mdat */
+    {
+        /* Ready mdat section */
+        uint8_t mdat[8];
+        int i_read = stream_Read( p_demux->s, &mdat, 8 );
+        p_sys->context.i_mdatbytesleft = GetDWBE( mdat );
+        if ( i_read < 8 || p_sys->context.i_mdatbytesleft < 8 ||
+             VLC_FOURCC( mdat[4], mdat[5], mdat[6], mdat[7] ) != ATOM_mdat )
+        {
+            uint64_t i_pos;
+            if ( !MP4_stream_Tell( p_demux->s, &i_pos ) )
+                msg_Err( p_demux, "No mdat atom at %"PRIu64, i_pos - __MAX( 0, i_read ) );
+            return VLC_EGENERIC;
+        }
+        i_current_pos += 8;
+        p_sys->context.i_mdatbytesleft -= 8;
+    }
+
+    while( p_sys->context.i_mdatbytesleft > 0 )
+    {
+        mp4_track_t *p_track;
+        unsigned int i_chunk;
+
+        /**/
+        uint64_t i_pos = i_current_pos;
+        int i_ret = LeafGetTrackAndChunkByMOOVPos( p_demux, &i_pos, &p_track, &i_chunk );
+        if ( i_ret == VLC_EGENERIC )
+        {
+            msg_Err(p_demux, "can't find referenced chunk for start at %"PRIu64, i_current_pos );
+            goto error;
+        }
+        else if( i_ret == VLC_ENOOBJ )
+        {
+            assert( i_pos - i_current_pos > p_sys->context.i_mdatbytesleft );
+            int i_read = stream_Read( p_demux->s, NULL, i_pos - i_current_pos );
+            i_current_pos += i_read;
+            p_sys->context.i_mdatbytesleft -= i_read;
+            if ( i_read == 0 ) goto error;
             continue;
         }
+        /**/
 
-        if( !tk->b_has_non_empty_cchunk )
+        mp4_chunk_t *p_chunk = &p_track->chunk[i_chunk];
+
+        uint32_t i_nb_samples_at_chunk_start = p_chunk->i_sample_first;
+        uint32_t i_nb_samples_in_chunk = p_chunk->i_sample_count;
+
+        assert(i_nb_samples_in_chunk);
+
+        uint32_t i_nb_samples = 0;
+        while ( i_nb_samples < i_nb_samples_in_chunk )
         {
-            if( MP4_frg_GetChunks( p_demux, tk->i_track_ID ) != VLC_SUCCESS )
+            uint32_t i_samplessize = 0;
+            uint32_t i_samplescounttoread = 0;
+            i_ret = LeafMOOVGetSamplesSize( p_track,
+                            i_nb_samples_at_chunk_start + i_nb_samples,
+                            &i_samplescounttoread, &i_samplessize,
+                            p_sys->context.i_mdatbytesleft,
+                            /*i_nb_samples_in_chunk - i_nb_samples*/ 1 );
+            if ( i_ret != VLC_SUCCESS )
+                goto error;
+
+            if( p_sys->context.i_mdatbytesleft &&
+                p_sys->context.i_mdatbytesleft  >= i_samplessize )
             {
-                msg_Info( p_demux, "MP4_frg_GetChunks returned error. End of stream?" );
-                return 0;
+                block_t *p_block;
+
+                /* now read pes */
+
+                if( !(p_block = MP4_Block_Read( p_demux, p_track, i_samplessize )) )
+                {
+                    uint64_t i_pos;
+                    if ( MP4_stream_Tell( p_demux->s, &i_pos ) )
+                    {
+                        p_sys->context.i_mdatbytesleft -= ( i_pos - i_current_pos );
+                        msg_Err( p_demux, "stream block error %"PRId64" %"PRId64, i_pos, i_pos - i_current_pos );
+                    }
+                    goto error;
+                }
+
+                i_nb_samples += i_samplescounttoread;
+                i_current_pos += i_samplessize;
+                p_sys->context.i_mdatbytesleft -= i_samplessize;
+
+                /* dts */
+                mtime_t i_time = LeafGetMOOVTimeInChunk( p_chunk, i_nb_samples );
+                i_time += p_chunk->i_first_dts;
+                p_track->i_time = i_time;
+                p_block->i_dts = VLC_TS_0 + CLOCK_FREQ * i_time / p_track->i_timescale;
+
+                /* pts */
+                int64_t i_delta = MP4_TrackGetPTSDelta( p_demux, p_track );
+                if( i_delta != -1 )
+                    p_block->i_pts = p_block->i_dts + i_delta;
+                else if( p_track->fmt.i_cat != VIDEO_ES )
+                    p_block->i_pts = p_block->i_dts;
+                else
+                    p_block->i_pts = VLC_TS_INVALID;
+
+                MP4_Block_Send( p_demux, p_track, p_block );
+
+                if ( p_demux->p_sys->i_pcr < VLC_TS_0 )
+                {
+                    p_sys->i_time = p_track->i_time * p_sys->i_timescale / p_track->i_timescale;
+                    p_demux->p_sys->i_pcr = MP4_GetMoviePTS( p_demux->p_sys );
+                    es_out_Control( p_demux->out, ES_OUT_SET_PCR, VLC_TS_0 + p_demux->p_sys->i_pcr );
+                }
+
+            }
+            else
+            {
+                // sample size > left bytes
+                break;
             }
+
+            p_track->i_sample += i_samplescounttoread;
         }
 
-        while( MP4_TrackGetDTS( p_demux, tk ) < MP4_GetMoviePTS( p_sys ) )
+        /* flag end of mdat section if needed */
+        if ( p_sys->context.i_mdatbytesleft == 0 )
+            p_sys->context.i_current_box_type = 0;
+
+        // next chunk
+        return VLC_SUCCESS;
+    }
+
+error:
+    /* Skip if we didn't reach the end of mdat box */
+    if ( p_sys->context.i_mdatbytesleft  > 0 )
+    {
+        msg_Err( p_demux, "mdat had still %"PRIu32" bytes unparsed as samples",
+                 p_sys->context.i_mdatbytesleft );
+        stream_ReadU32( p_demux->s, NULL, p_sys->context.i_mdatbytesleft );
+    }
+    p_sys->context.i_current_box_type = 0;
+
+    return VLC_SUCCESS;
+}
+
+static mp4_track_t * LeafGetTrackByTrunPos( demux_t *p_demux, const uint64_t i_pos, const uint64_t i_moofpos )
+{
+    demux_sys_t *p_sys = p_demux->p_sys;
+
+    for ( uint32_t i=0; i<p_sys->i_tracks; i++ )
+    {
+        mp4_track_t *p_track = &p_sys->track[i];
+        if ( !p_track->context.p_trun || !p_track->context.p_tfhd )
+            continue;
+        const MP4_Box_data_trun_t *p_trun_data = p_track->context.BOXDATA(p_trun);
+        uint64_t i_offset = 0;
+
+        if ( p_track->context.BOXDATA(p_tfhd)->i_flags & MP4_TFHD_BASE_DATA_OFFSET )
+            i_offset = p_track->context.BOXDATA(p_tfhd)->i_base_data_offset;
+        else
+            i_offset = i_moofpos;
+
+        //if ( p_track->context.BOXDATA(p_tfhd)->i_flags & MP4_TFHD_DEFAULT_BASE_IS_MOOF )
+          //  i_offset += i_moofpos;
+
+        if (p_trun_data->i_flags & MP4_TRUN_DATA_OFFSET)
+            i_offset += p_trun_data->i_data_offset;
+        else
+            return p_track;
+
+        if ( i_offset == i_pos )
+            return p_track;
+    }
+
+    return NULL;
+}
+
+static int LeafMapTrafTrunContextes( demux_t *p_demux, MP4_Box_t *p_moof )
+{
+    demux_sys_t *p_sys = p_demux->p_sys;
+
+    /* reset */
+    for ( uint32_t i=0; i<p_sys->i_tracks; i++ )
+    {
+        mp4_track_t *p_track = &p_sys->track[i];
+        p_track->context.p_tfhd = NULL;
+        p_track->context.p_traf = NULL;
+        p_track->context.p_trun = NULL;
+    }
+
+    if ( p_moof->i_type == ATOM_moov )
+        return VLC_SUCCESS;
+
+    MP4_Box_t *p_traf = MP4_BoxGet( p_moof, "traf" );
+    if( !p_traf )
+    {
+        msg_Warn( p_demux, "no traf box found!" );
+        return VLC_EGENERIC;
+    }
+
+    /* map contexts */
+    while ( p_traf )
+    {
+        if ( p_traf->i_type == ATOM_traf )
         {
-            block_t *p_block;
-            int64_t i_delta;
+            MP4_Box_t *p_tfhd = MP4_BoxGet( p_traf, "tfhd" );
+            for ( uint32_t i=0; p_tfhd && i<p_sys->i_tracks; i++ )
+            {
+                mp4_track_t *p_track = &p_sys->track[i];
+                if ( BOXDATA(p_tfhd)->i_track_ID == p_track->i_track_ID )
+                {
+                    MP4_Box_t *p_trun = MP4_BoxGet( p_traf, "trun" );
+                    if ( p_trun )
+                    {
+                        p_track->context.p_tfhd = p_tfhd;
+                        p_track->context.p_traf = p_traf;
+                        p_track->context.p_trun = p_trun;
+                    }
+                    p_tfhd = NULL; /* break loop */
+                }
+            }
+        }
+        p_traf = p_traf->p_next;
+    }
 
-            mp4_chunk_t *ck = tk->cchunk;
-            if( ck->i_sample >= ck->i_sample_count )
+    return VLC_SUCCESS;
+}
+
+static int LeafIndexGetMoofPosByTime( demux_t *p_demux, const mtime_t i_target_time,
+                                      uint64_t *pi_pos, mtime_t *pi_mooftime )
+{
+    MP4_Box_t *p_tfra = MP4_BoxGet( p_demux->p_sys->p_root, "mfra/tfra" );
+    while ( p_tfra )
+    {
+        if ( p_tfra->i_type == ATOM_tfra )
+        {
+            int64_t i_pos = -1;
+            const MP4_Box_data_tfra_t *p_data = BOXDATA(p_tfra);
+            mp4_track_t *p_track = MP4_frg_GetTrackByID( p_demux, p_data->i_track_ID );
+            if ( p_track && (p_track->fmt.i_cat == AUDIO_ES || p_track->fmt.i_cat == VIDEO_ES) )
             {
-                msg_Err( p_demux, "sample %"PRIu32" of %"PRIu32"",
-                                    ck->i_sample, ck->i_sample_count );
-                return 0;
+                for ( uint32_t i = 0; i<p_data->i_number_of_entries; i += ( p_data->i_version == 1 ) ? 2 : 1 )
+                {
+                    mtime_t i_time;
+                    uint64_t i_offset;
+                    if ( p_data->i_version == 1 )
+                    {
+                        i_time = *((uint64_t *)(p_data->p_time + i));
+                        i_offset = *((uint64_t *)(p_data->p_moof_offset + i));
+                    }
+                    else
+                    {
+                        i_time = p_data->p_time[i];
+                        i_offset = p_data->p_moof_offset[i];
+                    }
+
+                    if ( CLOCK_FREQ * i_time / p_track->i_timescale >= i_target_time )
+                    {
+                        if ( i_pos == -1 ) /* Not in this traf */
+                            break;
+
+                        *pi_pos = (uint64_t) i_pos;
+                        *pi_mooftime = CLOCK_FREQ * i_time / p_track->i_timescale;
+                        if ( p_track->fmt.i_cat == AUDIO_ES )
+                            *pi_mooftime -= CLOCK_FREQ / p_track->fmt.audio.i_rate * p_data->p_sample_number[i];
+                        else
+                            *pi_mooftime -= CLOCK_FREQ / p_demux->p_sys->f_fps * p_data->p_sample_number[i];
+                        return VLC_SUCCESS;
+                    }
+                    else
+                        i_pos = i_offset;
+                }
             }
+        }
+        p_tfra = p_tfra->p_next;
+    }
+    return VLC_EGENERIC;
+}
 
-            uint32_t sample_size = ck->p_sample_size[ck->i_sample];
-            p_block = block_Alloc( sample_size );
-            uint8_t *src = ck->p_sample_data[ck->i_sample];
-            memcpy( p_block->p_buffer, src, sample_size );
+static int LeafParseMDATwithMOOF( demux_t *p_demux, MP4_Box_t *p_moof )
+{
+    demux_sys_t *p_sys = p_demux->p_sys;
+    uint64_t i_pos;
+    assert( p_moof->i_type == ATOM_moof );
+    assert( p_sys->context.i_current_box_type == ATOM_mdat );
 
-            ck->i_sample++;
-            if( ck->i_sample == ck->i_sample_count )
-                tk->b_has_non_empty_cchunk = false;
+    if ( p_sys->context.i_mdatbytesleft == 0 )
+    {
+        int i_ret = LeafMapTrafTrunContextes( p_demux, p_moof );
+        if ( i_ret != VLC_SUCCESS )
+            return i_ret;
 
-            /* 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;
+        /* Ready mdat section */
+        uint8_t mdat[8];
+        int i_read = stream_Read( p_demux->s, &mdat, 8 );
+        p_sys->context.i_mdatbytesleft = GetDWBE( mdat );
+        if ( i_read < 8 || p_sys->context.i_mdatbytesleft < 8 ||
+             VLC_FOURCC( mdat[4], mdat[5], mdat[6], mdat[7] ) != ATOM_mdat )
+        {
+            if ( MP4_stream_Tell( p_demux->s, &i_pos ) )
+                msg_Err(p_demux, "No mdat atom at %"PRIu64, i_pos - i_read );
+            return VLC_EGENERIC;
+        }
+        p_sys->context.i_mdatbytesleft -= 8;
+    }
 
-            es_out_Send( p_demux->out, tk->p_es, p_block );
+    if ( !MP4_stream_Tell( p_demux->s, &i_pos ) )
+        return VLC_EGENERIC;
+    if ( p_sys->b_smooth )
+        i_pos -= p_moof->i_pos;
+    mp4_track_t *p_track = LeafGetTrackByTrunPos( p_demux, i_pos, p_moof->i_pos );
+    if( p_track )
+    {
+        MP4_Box_data_tfhd_t *p_tfhd_data = p_track->context.BOXDATA(p_tfhd);
+        uint32_t i_trun_sample_default_duration = 0;
+        uint32_t i_trun_sample_default_size = 0;
 
-            tk->i_sample++;
+        if ( p_track->context.p_trun )
+        {
+            /* Get defaults for this/these RUN */
+            if( p_tfhd_data->i_flags & MP4_TFHD_DFLT_SAMPLE_DURATION )
+                i_trun_sample_default_duration = p_tfhd_data->i_default_sample_duration;
 
-            if( !tk->b_has_non_empty_cchunk )
-                break;
+            if( p_tfhd_data->i_flags & MP4_TFHD_DFLT_SAMPLE_SIZE )
+                i_trun_sample_default_size = p_tfhd_data->i_default_sample_size;
+
+            if( !i_trun_sample_default_duration || !i_trun_sample_default_size )
+            {
+                MP4_Box_t *p_trex = MP4_BoxGet( p_demux->p_sys->p_root, "moov/mvex/trex");
+                if ( p_trex )
+                {
+                    while( p_trex && BOXDATA(p_trex)->i_track_ID != p_tfhd_data->i_track_ID )
+                        p_trex = p_trex->p_next;
+                    if ( p_trex && !i_trun_sample_default_duration )
+                        i_trun_sample_default_duration = BOXDATA(p_trex)->i_default_sample_duration;
+                    if ( p_trex && !i_trun_sample_default_size )
+                        i_trun_sample_default_size = BOXDATA(p_trex)->i_default_sample_size;
+                }
+            }
+
+            const MP4_Box_data_trun_t *p_trun_data = p_track->context.BOXDATA(p_trun);
+
+           /* NOW PARSE TRUN WITH MDAT */
+            int i_ret = LeafParseTRUN( p_demux, p_track,
+                                   i_trun_sample_default_duration, i_trun_sample_default_size,
+                                   p_trun_data, & p_sys->context.i_mdatbytesleft );
+            if ( i_ret != VLC_SUCCESS )
+                goto end;
+
+            p_track->context.p_trun = p_track->context.p_trun->p_next;
         }
+
+        if ( p_sys->context.i_mdatbytesleft == 0 )
+            p_sys->context.i_current_box_type = 0;
+        return VLC_SUCCESS;
+    }
+
+end:
+    /* Skip if we didn't reach the end of mdat box */
+    if ( p_sys->context.i_mdatbytesleft > 0 )
+    {
+        msg_Warn( p_demux, "mdat had still %"PRIu32" bytes unparsed as samples", p_sys->context.i_mdatbytesleft - 8 );
+        stream_ReadU32( p_demux->s, NULL, p_sys->context.i_mdatbytesleft );
+    }
+
+    p_sys->context.i_current_box_type = 0;
+
+    return VLC_SUCCESS;
+}
+
+static int DemuxAsLeaf( demux_t *p_demux )
+{
+    demux_sys_t *p_sys = p_demux->p_sys;
+    unsigned i_track_selected = 0;
+
+    /* check for newly selected/unselected track */
+    for( unsigned i_track = 0; i_track < p_sys->i_tracks; i_track++ )
+    {
+        mp4_track_t *tk = &p_sys->track[i_track];
+        bool b;
+
+        if( !tk->b_ok || tk->b_chapter )
+            continue;
+
+        es_out_Control( p_demux->out, ES_OUT_GET_ES_STATE, tk->p_es, &b );
+        msg_Dbg( p_demux, "track %u %s!", tk->i_track_ID, b ? "enabled" : "disabled" );
+
+        if( tk->b_selected && !b )
+            MP4_TrackUnselect( p_demux, tk );
+        else if( !tk->b_selected && b)
+            MP4_frg_TrackSelect( p_demux, tk );
+
+        if( tk->b_selected )
+            i_track_selected++;
     }
+
+    if( i_track_selected <= 0 )
+    {
+        msg_Warn( p_demux, "no track selected, exiting..." );
+        return 0;
+    }
+
+    if ( p_sys->context.i_current_box_type != ATOM_mdat )
+    {
+        /* Othewise mdat is skipped. FIXME: mdat reading ! */
+        const uint8_t *p_peek;
+        int i_read  = stream_Peek( p_demux->s, &p_peek, 8 );
+        if ( i_read < 8 )
+            return 0;
+
+        p_sys->context.i_current_box_type = VLC_FOURCC( p_peek[4], p_peek[5], p_peek[6], p_peek[7] );
+
+        if ( p_sys->context.i_current_box_type != ATOM_mdat )
+        {
+            if ( ! BoxExistsInRootTree( p_sys->p_root, p_sys->context.i_current_box_type, stream_Tell( p_demux->s ) ) )
+            {// only if !b_probed ??
+                MP4_Box_t *p_vroot = LoadNextChunk( p_demux );
+                switch( p_sys->context.i_current_box_type )
+                {
+                case ATOM_moov:
+                case ATOM_moof:
+                    /* create fragment */
+                    AddFragment( p_demux, p_vroot->p_first );
+                    //ft
+                default:
+                    break;
+                }
+
+                /* Append to root */
+                p_sys->p_root->p_last->p_next = p_vroot->p_first;
+                p_sys->p_root->p_last = p_vroot->p_first;
+                p_vroot->p_last = NULL;
+                p_vroot->p_next = NULL;
+                p_vroot->p_first = NULL;
+                MP4_BoxFree( p_demux->s, p_vroot );
+            }
+            else
+            {
+                /* Skip */
+                msg_Err( p_demux, "skipping known chunk type %4.4s size %"PRIu32, (char*)& p_sys->context.i_current_box_type, GetDWBE( p_peek ) );
+                stream_Read( p_demux->s, NULL, GetDWBE( p_peek ) );
+            }
+        }
+        else
+        {
+            /* skip mdat header */
+            p_sys->context.p_fragment = GetFragmentByPos( p_demux,
+                                       stream_Tell( p_demux->s ) + 8, true );
+        }
+
+    }
+
+    if ( p_sys->context.i_current_box_type == ATOM_mdat )
+    {
+        assert(p_sys->context.p_fragment);
+        if ( p_sys->context.p_fragment )
+        switch( p_sys->context.p_fragment->p_moox->i_type )
+        {
+            case ATOM_moov://[ftyp/moov, mdat]+ -> [moof, mdat]+
+                LeafParseMDATwithMOOV( p_demux );
+            break;
+            case ATOM_moof:
+                LeafParseMDATwithMOOF( p_demux, p_sys->context.p_fragment->p_moox ); // BACKUP CHUNK!
+            break;
+        default:
+             msg_Err( p_demux, "fragment type %4.4s", (char*) &p_sys->context.p_fragment->p_moox->i_type );
+             break;
+        }
+    }
+
+    /* Get current time */
+    mtime_t i_lowest_dts = VLC_TS_INVALID;
+    mtime_t i_lowest_time = INT64_MAX;
+    for( unsigned int i_track = 0; i_track < p_sys->i_tracks; i_track++ )
+    {
+        const mp4_track_t *p_track = &p_sys->track[i_track];
+        if( !p_track->b_selected || ( p_track->fmt.i_cat != VIDEO_ES && p_track->fmt.i_cat != AUDIO_ES ) )
+            continue;
+
+        i_lowest_time = __MIN( i_lowest_time, p_track->i_time * p_sys->i_timescale / p_track->i_timescale );
+
+        if ( i_lowest_dts == VLC_TS_INVALID )
+            i_lowest_dts = CLOCK_FREQ * p_track->i_time / p_track->i_timescale;
+        else
+            i_lowest_dts = __MIN( i_lowest_dts, CLOCK_FREQ * p_track->i_time / p_track->i_timescale );
+    }
+
+    p_sys->i_time = i_lowest_time;
+    p_sys->i_pcr = i_lowest_dts;
+    es_out_Control( p_demux->out, ES_OUT_SET_PCR, VLC_TS_0 + p_sys->i_pcr );
+
     return 1;
 }