]> git.sesse.net Git - vlc/blobdiff - modules/demux/mkv.cpp
mkv.cpp: handle missing linked segments (seg->missing->seg)
[vlc] / modules / demux / mkv.cpp
index 41dff67ac5722ece5918366a3d6bdeeb37c6b12c..6513c8e3b33c8392be898a7566fa86fc2630a7b9 100644 (file)
@@ -121,7 +121,15 @@ vlc_module_begin();
     set_category( CAT_INPUT );
     set_subcategory( SUBCAT_INPUT_DEMUX );
 
-    add_bool( "mkv-seek-percent", 1, NULL,
+    add_bool( "mkv-use-ordered-chapters", 1, NULL,
+            N_("Ordered chapters"),
+            N_("Play chapters in the specified order as specified in the file"), VLC_TRUE );
+
+    add_bool( "mkv-use-chapter-codec", 1, NULL,
+            N_("Chapter codecs"),
+            N_("Use chapter codecs found in the file"), VLC_TRUE );
+
+    add_bool( "mkv-seek-percent", 0, NULL,
             N_("Seek based on percent not time"),
             N_("Seek based on percent not time"), VLC_TRUE );
 
@@ -267,12 +275,12 @@ static vlc_fourcc_t __GetFOURCC( uint8_t *p )
  *****************************************************************************/
 typedef struct
 {
-    vlc_bool_t  b_default;
-    vlc_bool_t  b_enabled;
-    int         i_number;
+    vlc_bool_t   b_default;
+    vlc_bool_t   b_enabled;
+    unsigned int i_number;
 
-    int         i_extra_data;
-    uint8_t     *p_extra_data;
+    int          i_extra_data;
+    uint8_t      *p_extra_data;
 
     char         *psz_codec;
 
@@ -381,6 +389,7 @@ public:
         ,i_chapters_position(-1)
         ,i_tags_position(-1)
         ,cluster(NULL)
+        ,i_start_pos(0)
         ,b_cues(VLC_FALSE)
         ,i_index(0)
         ,i_index_max(1024)
@@ -463,6 +472,7 @@ public:
     int64_t                 i_tags_position;
 
     KaxCluster              *cluster;
+    int64_t                 i_start_pos;
     KaxSegmentUID           segment_uid;
     KaxPrevUID              prev_segment_uid;
     KaxNextUID              next_segment_uid;
@@ -498,7 +508,6 @@ public:
 
     bool Preload( );
     bool PreloadFamily( const matroska_segment_t & segment );
-    size_t PreloadLinked( const demux_sys_t & of_sys );
     void ParseInfo( EbmlElement *info );
     void ParseChapters( EbmlElement *chapters );
     void ParseSeekHead( EbmlElement *seekhead );
@@ -506,7 +515,58 @@ public:
     void ParseChapterAtom( int i_level, EbmlMaster *ca, chapter_item_t & chapters );
     void ParseTrackEntry( EbmlMaster *m );
     void IndexAppendCluster( KaxCluster *cluster );
+    void LoadCues( );
+    void LoadTags( );
+    void InformationCreate( );
     int BlockGet( KaxBlock **pp_block, int64_t *pi_ref1, int64_t *pi_ref2, int64_t *pi_duration );
+    bool Select( mtime_t i_start_time );
+    void UnSelect( );
+    static bool CompareSegmentUIDs( const matroska_segment_t * item_a, const matroska_segment_t * item_b );
+};
+
+// class holding hard-linked segment together in the playback order
+class virtual_segment_t
+{
+public:
+    virtual_segment_t( matroska_segment_t *p_segment )
+        :i_current_segment(0)
+    {
+        linked_segments.push_back( p_segment );
+
+        AppendUID( p_segment->segment_uid );
+        AppendUID( p_segment->prev_segment_uid );
+        AppendUID( p_segment->next_segment_uid );
+    }
+
+    void Sort();
+    size_t AddSegment( matroska_segment_t *p_segment );
+    void PreloadLinked( );
+    float Duration( ) const;
+    void LoadCues( );
+
+    matroska_segment_t * Segment() const
+    {
+        if ( linked_segments.size() == 0 || i_current_segment >= linked_segments.size() )
+            return NULL;
+        return linked_segments[i_current_segment];
+    }
+
+    bool SelectNext()
+    {
+        if ( i_current_segment < linked_segments.size()-1 )
+        {
+            i_current_segment++;
+            return true;
+        }
+        return false;
+    }
+
+protected:
+    std::vector<matroska_segment_t*> linked_segments;
+    std::vector<const KaxSegmentUID> linked_uids;
+    size_t                           i_current_segment;
+
+    void                             AppendUID( const EbmlBinary & UID );
 };
 
 class matroska_stream_t
@@ -515,14 +575,11 @@ public:
     matroska_stream_t( demux_sys_t & demuxer )
         :p_in(NULL)
         ,p_es(NULL)
-        ,i_current_segment(-1)
         ,sys(demuxer)
     {}
 
     ~matroska_stream_t()
     {
-        for ( size_t i=0; i<segments.size(); i++ )
-            delete segments[i];
         delete p_in;
         delete p_es;
     }
@@ -531,21 +588,10 @@ public:
     EbmlStream         *p_es;
 
     std::vector<matroska_segment_t*> segments;
-    int                              i_current_segment;
 
     demux_sys_t                      & sys;
-    
-    inline matroska_segment_t *Segment()
-    {
-        if ( i_current_segment >= 0 && size_t(i_current_segment) < segments.size() )
-            return segments[i_current_segment];
-        return NULL;
-    }
-    
-    matroska_segment_t *FindSegment( EbmlBinary & uid ) const;
 
     void PreloadFamily( const matroska_segment_t & segment );
-    size_t PreloadLinked( const demux_sys_t & of_sys );
 };
 
 class demux_sys_t
@@ -558,13 +604,16 @@ public:
         ,i_chapter_time(0)
         ,meta(NULL)
         ,title(NULL)
-        ,i_current_stream(-1)
+        ,p_current_segment(NULL)
+        ,f_duration(-1.0)
     {}
 
     ~demux_sys_t()
     {
         for (size_t i=0; i<streams.size(); i++)
             delete streams[i];
+        for ( size_t i=0; i<opened_segments.size(); i++ )
+            delete opened_segments[i];
     }
 
     /* current data */
@@ -578,19 +627,17 @@ public:
 
     input_title_t           *title;
 
-    std::vector<matroska_stream_t*> streams;
-    int                             i_current_stream;
+    std::vector<matroska_stream_t*>  streams;
+    std::vector<matroska_segment_t*> opened_segments;
+    virtual_segment_t                *p_current_segment;
 
-    inline matroska_stream_t *Stream()
-    {
-        if ( i_current_stream >= 0 && size_t(i_current_stream) < streams.size() )
-            return streams[i_current_stream];
-        return NULL;
-    }
+    /* duration of the stream */
+    float                   f_duration;
 
-    matroska_segment_t *FindSegment( EbmlBinary & uid ) const;
+    matroska_segment_t *FindSegment( const EbmlBinary & uid ) const;
     void PreloadFamily( );
-    void PreloadLinked( );
+    void PreloadLinked( matroska_segment_t *p_segment );
+    void PreparePlayback( );
     matroska_stream_t *AnalyseAllSegmentsFound( EbmlStream *p_estream );
 };
 
@@ -601,8 +648,6 @@ static void Seek   ( demux_t *, mtime_t i_date, double f_percent, const chapter_
 #define MKV_IS_ID( el, C ) ( EbmlId( (*el) ) == C::ClassInfos.GlobalId )
 
 static char *UTF8ToStr          ( const UTFstring &u );
-static void LoadCues            ( demux_t * );
-static void InformationCreate   ( demux_t * );
 
 /*****************************************************************************
  * Open: initializes matroska demux structures
@@ -615,7 +660,6 @@ static int Open( vlc_object_t * p_this )
     matroska_segment_t *p_segment;
     uint8_t            *p_peek;
     std::string        s_path, s_filename;
-    size_t             i_track;
     vlc_stream_io_callback *p_io_callback;
     EbmlStream         *p_io_stream;
 
@@ -649,7 +693,6 @@ static int Open( vlc_object_t * p_this )
         goto error;
     }
     p_sys->streams.push_back( p_stream );
-    p_sys->i_current_stream = 0;
 
     p_stream->p_in = p_io_callback;
     p_stream->p_es = p_io_stream;
@@ -658,9 +701,8 @@ static int Open( vlc_object_t * p_this )
     {
         p_stream->segments[i]->Preload();
     }
-    p_stream->i_current_segment = 0;
 
-    p_segment = p_stream->Segment();
+    p_segment = p_stream->segments[0];
     if( p_segment->cluster == NULL )
     {
         msg_Err( p_demux, "cannot find any cluster, damaged file ?" );
@@ -735,19 +777,8 @@ static int Open( vlc_object_t * p_this )
     }
 
     p_sys->PreloadFamily( );
-    p_sys->PreloadLinked( );
-
-    /* *** Load the cue if found *** */
-    if( p_segment->i_cues_position >= 0 )
-    {
-        vlc_bool_t b_seekable;
-
-        stream_Control( p_demux->s, STREAM_CAN_FASTSEEK, &b_seekable );
-        if( b_seekable )
-        {
-            LoadCues( p_demux );
-        }
-    }
+    p_sys->PreloadLinked( p_segment );
+    p_sys->PreparePlayback( );
 
     if( !p_segment->b_cues || p_segment->i_index <= 0 )
     {
@@ -758,765 +789,796 @@ static int Open( vlc_object_t * p_this )
         p_segment->b_cues = VLC_FALSE;
     }
 
-    /* add all es */
-    msg_Dbg( p_demux, "found %d es", p_segment->tracks.size() );
-    for( i_track = 0; i_track < p_segment->tracks.size(); i_track++ )
+    /* add information */
+    p_segment->InformationCreate( );
+
+    if ( !p_segment->Select( 0 ) )
     {
-#define tk  p_segment->tracks[i_track]
-        if( tk->fmt.i_cat == UNKNOWN_ES )
+        msg_Err( p_demux, "cannot use the segment" );
+        goto error;
+    }
+    
+    return VLC_SUCCESS;
+
+error:
+    delete p_sys;
+    return VLC_EGENERIC;
+}
+
+/*****************************************************************************
+ * Close: frees unused data
+ *****************************************************************************/
+static void Close( vlc_object_t *p_this )
+{
+    demux_t     *p_demux = (demux_t*)p_this;
+    demux_sys_t *p_sys   = p_demux->p_sys;
+
+    delete p_sys;
+}
+
+/*****************************************************************************
+ * Control:
+ *****************************************************************************/
+static int Control( demux_t *p_demux, int i_query, va_list args )
+{
+    demux_sys_t        *p_sys = p_demux->p_sys;
+    matroska_segment_t *p_segment = p_sys->p_current_segment->Segment();
+    int64_t     *pi64;
+    double      *pf, f;
+    int         i_skp;
+
+    vlc_meta_t **pp_meta;
+
+    switch( i_query )
+    {
+        case DEMUX_GET_META:
+            pp_meta = (vlc_meta_t**)va_arg( args, vlc_meta_t** );
+            *pp_meta = vlc_meta_Duplicate( p_sys->meta );
+            return VLC_SUCCESS;
+
+        case DEMUX_GET_LENGTH:
+            pi64 = (int64_t*)va_arg( args, int64_t * );
+            if( p_sys->f_duration > 0.0 )
+            {
+                *pi64 = (int64_t)(p_sys->f_duration * 1000);
+                return VLC_SUCCESS;
+            }
+            return VLC_EGENERIC;
+
+        case DEMUX_GET_POSITION:
+            pf = (double*)va_arg( args, double * );
+            if ( p_sys->f_duration > 0.0 )
+                *pf = (double)p_sys->i_pts / (1000.0 * p_sys->f_duration);
+            return VLC_SUCCESS;
+
+        case DEMUX_SET_POSITION:
+            f = (double)va_arg( args, double );
+            Seek( p_demux, -1, f, NULL );
+            return VLC_SUCCESS;
+
+        case DEMUX_GET_TIME:
+            pi64 = (int64_t*)va_arg( args, int64_t * );
+            *pi64 = p_sys->i_pts;
+            return VLC_SUCCESS;
+
+        case DEMUX_GET_TITLE_INFO:
+            if( p_sys->title && p_sys->title->i_seekpoint > 0 )
+            {
+                input_title_t ***ppp_title = (input_title_t***)va_arg( args, input_title_t*** );
+                int *pi_int    = (int*)va_arg( args, int* );
+
+                *pi_int = 1;
+                *ppp_title = (input_title_t**)malloc( sizeof( input_title_t**) );
+
+                (*ppp_title)[0] = vlc_input_title_Duplicate( p_sys->title );
+
+                return VLC_SUCCESS;
+            }
+            return VLC_EGENERIC;
+
+        case DEMUX_SET_TITLE:
+            /* TODO handle editions as titles & DVD titles as well */
+            if( p_sys->title && p_sys->title->i_seekpoint > 0 )
+            {
+                return VLC_SUCCESS;
+            }
+            return VLC_EGENERIC;
+
+        case DEMUX_SET_SEEKPOINT:
+            /* FIXME do a better implementation */
+            i_skp = (int)va_arg( args, int );
+
+            if( p_sys->title && i_skp < p_sys->title->i_seekpoint)
+            {
+                Seek( p_demux, (int64_t)p_sys->title->seekpoint[i_skp]->i_time_offset, -1, NULL);
+                p_demux->info.i_seekpoint |= INPUT_UPDATE_SEEKPOINT;
+                p_demux->info.i_seekpoint = i_skp;
+                return VLC_SUCCESS;
+            }
+            return VLC_EGENERIC;
+
+        case DEMUX_SET_TIME:
+        case DEMUX_GET_FPS:
+        default:
+            return VLC_EGENERIC;
+    }
+}
+
+int matroska_segment_t::BlockGet( KaxBlock **pp_block, int64_t *pi_ref1, int64_t *pi_ref2, int64_t *pi_duration )
+{
+    *pp_block = NULL;
+    *pi_ref1  = -1;
+    *pi_ref2  = -1;
+
+    for( ;; )
+    {
+        EbmlElement *el;
+        int         i_level;
+
+        if( sys.demuxer.b_die )
         {
-            msg_Warn( p_demux, "invalid track[%d, n=%d]", i_track, tk->i_number );
-            tk->p_es = NULL;
-            continue;
+            return VLC_EGENERIC;
         }
 
-        if( !strcmp( tk->psz_codec, "V_MS/VFW/FOURCC" ) )
+        el = ep->Get();
+        i_level = ep->GetLevel();
+
+        if( el == NULL && *pp_block != NULL )
         {
-            if( tk->i_extra_data < (int)sizeof( BITMAPINFOHEADER ) )
+            /* update the index */
+#define idx index[i_index - 1]
+            if( i_index > 0 && idx.i_time == -1 )
             {
-                msg_Err( p_demux, "missing/invalid BITMAPINFOHEADER" );
-                tk->fmt.i_codec = VLC_FOURCC( 'u', 'n', 'd', 'f' );
+                idx.i_time        = (*pp_block)->GlobalTimecode() / (mtime_t)1000;
+                idx.b_key         = *pi_ref1 == -1 ? VLC_TRUE : VLC_FALSE;
             }
-            else
+#undef idx
+            return VLC_SUCCESS;
+        }
+
+        if( el == NULL )
+        {
+            if( ep->GetLevel() > 1 )
             {
-                BITMAPINFOHEADER *p_bih = (BITMAPINFOHEADER*)tk->p_extra_data;
+                ep->Up();
+                continue;
+            }
+            msg_Warn( &sys.demuxer, "EOF" );
+            return VLC_EGENERIC;
+        }
 
-                tk->fmt.video.i_width = GetDWLE( &p_bih->biWidth );
-                tk->fmt.video.i_height= GetDWLE( &p_bih->biHeight );
-                tk->fmt.i_codec       = GetFOURCC( &p_bih->biCompression );
+        /* do parsing */
+        if( i_level == 1 )
+        {
+            if( MKV_IS_ID( el, KaxCluster ) )
+            {
+                cluster = (KaxCluster*)el;
 
-                tk->fmt.i_extra       = GetDWLE( &p_bih->biSize ) - sizeof( BITMAPINFOHEADER );
-                if( tk->fmt.i_extra > 0 )
+                /* add it to the index */
+                if( i_index == 0 ||
+                    ( i_index > 0 && index[i_index - 1].i_position < (int64_t)cluster->GetElementPosition() ) )
                 {
-                    tk->fmt.p_extra = malloc( tk->fmt.i_extra );
-                    memcpy( tk->fmt.p_extra, &p_bih[1], tk->fmt.i_extra );
+                    IndexAppendCluster( cluster );
+                }
+
+                // reset silent tracks
+                for (size_t i=0; i<tracks.size(); i++)
+                {
+                    tracks[i]->b_silent = VLC_FALSE;
                 }
+
+                ep->Down();
+            }
+            else if( MKV_IS_ID( el, KaxCues ) )
+            {
+                msg_Warn( &sys.demuxer, "find KaxCues FIXME" );
+                return VLC_EGENERIC;
+            }
+            else
+            {
+                msg_Dbg( &sys.demuxer, "unknown (%s)", typeid( el ).name() );
             }
         }
-        else if( !strcmp( tk->psz_codec, "V_MPEG1" ) ||
-                 !strcmp( tk->psz_codec, "V_MPEG2" ) )
-        {
-            tk->fmt.i_codec = VLC_FOURCC( 'm', 'p', 'g', 'v' );
-        }
-        else if( !strncmp( tk->psz_codec, "V_MPEG4", 7 ) )
+        else if( i_level == 2 )
         {
-            if( !strcmp( tk->psz_codec, "V_MPEG4/MS/V3" ) )
+            if( MKV_IS_ID( el, KaxClusterTimecode ) )
             {
-                tk->fmt.i_codec = VLC_FOURCC( 'D', 'I', 'V', '3' );
+                KaxClusterTimecode &ctc = *(KaxClusterTimecode*)el;
+
+                ctc.ReadData( es.I_O(), SCOPE_ALL_DATA );
+                cluster->InitTimecode( uint64( ctc ), i_timescale );
             }
-            else if( !strcmp( tk->psz_codec, "V_MPEG4/ISO/AVC" ) )
+            else if( MKV_IS_ID( el, KaxClusterSilentTracks ) )
             {
-                tk->fmt.i_codec = VLC_FOURCC( 'a', 'v', 'c', '1' );
-                tk->fmt.b_packetized = VLC_FALSE;
-                tk->fmt.i_extra = tk->i_extra_data;
-                tk->fmt.p_extra = malloc( tk->i_extra_data );
-                memcpy( tk->fmt.p_extra,tk->p_extra_data, tk->i_extra_data );
+                ep->Down();
             }
-            else
+            else if( MKV_IS_ID( el, KaxBlockGroup ) )
             {
-                tk->fmt.i_codec = VLC_FOURCC( 'm', 'p', '4', 'v' );
+                ep->Down();
             }
         }
-        else if( !strcmp( tk->psz_codec, "V_QUICKTIME" ) )
-        {
-            MP4_Box_t *p_box = (MP4_Box_t*)malloc( sizeof( MP4_Box_t ) );
-            stream_t *p_mp4_stream = stream_MemoryNew( VLC_OBJECT(p_demux),
-                                                       tk->p_extra_data,
-                                                       tk->i_extra_data );
-            MP4_ReadBoxCommon( p_mp4_stream, p_box );
-            MP4_ReadBox_sample_vide( p_mp4_stream, p_box );
-            tk->fmt.i_codec = p_box->i_type;
-            tk->fmt.video.i_width = p_box->data.p_sample_vide->i_width;
-            tk->fmt.video.i_height = p_box->data.p_sample_vide->i_height;
-            tk->fmt.i_extra = p_box->data.p_sample_vide->i_qt_image_description;
-            tk->fmt.p_extra = malloc( tk->fmt.i_extra );
-            memcpy( tk->fmt.p_extra, p_box->data.p_sample_vide->p_qt_image_description, tk->fmt.i_extra );
-            MP4_FreeBox_sample_vide( p_box );
-            stream_MemoryDelete( p_mp4_stream, VLC_TRUE );
-        }
-        else if( !strcmp( tk->psz_codec, "A_MS/ACM" ) )
-        {
-            if( tk->i_extra_data < (int)sizeof( WAVEFORMATEX ) )
-            {
-                msg_Err( p_demux, "missing/invalid WAVEFORMATEX" );
-                tk->fmt.i_codec = VLC_FOURCC( 'u', 'n', 'd', 'f' );
-            }
-            else
-            {
-                WAVEFORMATEX *p_wf = (WAVEFORMATEX*)tk->p_extra_data;
-
-                wf_tag_to_fourcc( GetWLE( &p_wf->wFormatTag ), &tk->fmt.i_codec, NULL );
-
-                tk->fmt.audio.i_channels   = GetWLE( &p_wf->nChannels );
-                tk->fmt.audio.i_rate = GetDWLE( &p_wf->nSamplesPerSec );
-                tk->fmt.i_bitrate    = GetDWLE( &p_wf->nAvgBytesPerSec ) * 8;
-                tk->fmt.audio.i_blockalign = GetWLE( &p_wf->nBlockAlign );;
-                tk->fmt.audio.i_bitspersample = GetWLE( &p_wf->wBitsPerSample );
-
-                tk->fmt.i_extra            = GetWLE( &p_wf->cbSize );
-                if( tk->fmt.i_extra > 0 )
-                {
-                    tk->fmt.p_extra = malloc( tk->fmt.i_extra );
-                    memcpy( tk->fmt.p_extra, &p_wf[1], tk->fmt.i_extra );
-                }
-            }
-        }
-        else if( !strcmp( tk->psz_codec, "A_MPEG/L3" ) ||
-                 !strcmp( tk->psz_codec, "A_MPEG/L2" ) ||
-                 !strcmp( tk->psz_codec, "A_MPEG/L1" ) )
-        {
-            tk->fmt.i_codec = VLC_FOURCC( 'm', 'p', 'g', 'a' );
-        }
-        else if( !strcmp( tk->psz_codec, "A_AC3" ) )
-        {
-            tk->fmt.i_codec = VLC_FOURCC( 'a', '5', '2', ' ' );
-        }
-        else if( !strcmp( tk->psz_codec, "A_DTS" ) )
-        {
-            tk->fmt.i_codec = VLC_FOURCC( 'd', 't', 's', ' ' );
-        }
-        else if( !strcmp( tk->psz_codec, "A_FLAC" ) )
-        {
-            tk->fmt.i_codec = VLC_FOURCC( 'f', 'l', 'a', 'c' );
-            tk->fmt.i_extra = tk->i_extra_data;
-            tk->fmt.p_extra = malloc( tk->i_extra_data );
-            memcpy( tk->fmt.p_extra,tk->p_extra_data, tk->i_extra_data );
-        }
-        else if( !strcmp( tk->psz_codec, "A_VORBIS" ) )
+        else if( i_level == 3 )
         {
-            int i, i_offset = 1, i_size[3], i_extra;
-            uint8_t *p_extra;
-
-            tk->fmt.i_codec = VLC_FOURCC( 'v', 'o', 'r', 'b' );
-
-            /* Split the 3 headers */
-            if( tk->p_extra_data[0] != 0x02 )
-                msg_Err( p_demux, "invalid vorbis header" );
-
-            for( i = 0; i < 2; i++ )
+            if( MKV_IS_ID( el, KaxBlock ) )
             {
-                i_size[i] = 0;
-                while( i_offset < tk->i_extra_data )
-                {
-                    i_size[i] += tk->p_extra_data[i_offset];
-                    if( tk->p_extra_data[i_offset++] != 0xff ) break;
-                }
-            }
+                *pp_block = (KaxBlock*)el;
 
-            i_size[0] = __MIN(i_size[0], tk->i_extra_data - i_offset);
-            i_size[1] = __MIN(i_size[1], tk->i_extra_data -i_offset -i_size[0]);
-            i_size[2] = tk->i_extra_data - i_offset - i_size[0] - i_size[1];
+                (*pp_block)->ReadData( es.I_O() );
+                (*pp_block)->SetParent( *cluster );
 
-            tk->fmt.i_extra = 3 * 2 + i_size[0] + i_size[1] + i_size[2];
-            tk->fmt.p_extra = malloc( tk->fmt.i_extra );
-            p_extra = (uint8_t *)tk->fmt.p_extra; i_extra = 0;
-            for( i = 0; i < 3; i++ )
-            {
-                *(p_extra++) = i_size[i] >> 8;
-                *(p_extra++) = i_size[i] & 0xFF;
-                memcpy( p_extra, tk->p_extra_data + i_offset + i_extra,
-                        i_size[i] );
-                p_extra += i_size[i];
-                i_extra += i_size[i];
+                ep->Keep();
             }
-        }
-        else if( !strncmp( tk->psz_codec, "A_AAC/MPEG2/", strlen( "A_AAC/MPEG2/" ) ) ||
-                 !strncmp( tk->psz_codec, "A_AAC/MPEG4/", strlen( "A_AAC/MPEG4/" ) ) )
-        {
-            int i_profile, i_srate;
-            static unsigned int i_sample_rates[] =
+            else if( MKV_IS_ID( el, KaxBlockDuration ) )
             {
-                    96000, 88200, 64000, 48000, 44100, 32000, 24000, 22050,
-                        16000, 12000, 11025, 8000,  7350,  0,     0,     0
-            };
-
-            tk->fmt.i_codec = VLC_FOURCC( 'm', 'p', '4', 'a' );
-            /* create data for faad (MP4DecSpecificDescrTag)*/
+                KaxBlockDuration &dur = *(KaxBlockDuration*)el;
 
-            if( !strcmp( &tk->psz_codec[12], "MAIN" ) )
-            {
-                i_profile = 0;
-            }
-            else if( !strcmp( &tk->psz_codec[12], "LC" ) )
-            {
-                i_profile = 1;
-            }
-            else if( !strcmp( &tk->psz_codec[12], "SSR" ) )
-            {
-                i_profile = 2;
+                dur.ReadData( es.I_O() );
+                *pi_duration = uint64( dur );
             }
-            else
+            else if( MKV_IS_ID( el, KaxReferenceBlock ) )
             {
-                i_profile = 3;
-            }
+                KaxReferenceBlock &ref = *(KaxReferenceBlock*)el;
 
-            for( i_srate = 0; i_srate < 13; i_srate++ )
-            {
-                if( i_sample_rates[i_srate] == tk->fmt.audio.i_rate )
+                ref.ReadData( es.I_O() );
+                if( *pi_ref1 == -1 )
                 {
-                    break;
+                    *pi_ref1 = int64( ref );
                 }
-            }
-            msg_Dbg( p_demux, "profile=%d srate=%d", i_profile, i_srate );
-
-            tk->fmt.i_extra = 2;
-            tk->fmt.p_extra = malloc( tk->fmt.i_extra );
-            ((uint8_t*)tk->fmt.p_extra)[0] = ((i_profile + 1) << 3) | ((i_srate&0xe) >> 1);
-            ((uint8_t*)tk->fmt.p_extra)[1] = ((i_srate & 0x1) << 7) | (tk->fmt.audio.i_channels << 3);
-        }
-        else if( !strcmp( tk->psz_codec, "A_PCM/INT/BIG" ) ||
-                 !strcmp( tk->psz_codec, "A_PCM/INT/LIT" ) ||
-                 !strcmp( tk->psz_codec, "A_PCM/FLOAT/IEEE" ) )
-        {
-            if( !strcmp( tk->psz_codec, "A_PCM/INT/BIG" ) )
-            {
-                tk->fmt.i_codec = VLC_FOURCC( 't', 'w', 'o', 's' );
-            }
-            else
-            {
-                tk->fmt.i_codec = VLC_FOURCC( 'a', 'r', 'a', 'w' );
-            }
-            tk->fmt.audio.i_blockalign = ( tk->fmt.audio.i_bitspersample + 7 ) / 8 * tk->fmt.audio.i_channels;
-        }
-        else if( !strcmp( tk->psz_codec, "A_TTA1" ) )
-        {
-            /* FIXME: support this codec */
-            msg_Err( p_demux, "TTA not supported yet[%d, n=%d]", i_track, tk->i_number );
-            tk->fmt.i_codec = VLC_FOURCC( 'u', 'n', 'd', 'f' );
-        }
-        else if( !strcmp( tk->psz_codec, "A_WAVPACK4" ) )
-        {
-            /* FIXME: support this codec */
-            msg_Err( p_demux, "Wavpack not supported yet[%d, n=%d]", i_track, tk->i_number );
-            tk->fmt.i_codec = VLC_FOURCC( 'u', 'n', 'd', 'f' );
-        }
-        else if( !strcmp( tk->psz_codec, "S_TEXT/UTF8" ) )
-        {
-            tk->fmt.i_codec = VLC_FOURCC( 's', 'u', 'b', 't' );
-            tk->fmt.subs.psz_encoding = strdup( "UTF-8" );
-        }
-        else if( !strcmp( tk->psz_codec, "S_TEXT/SSA" ) ||
-                 !strcmp( tk->psz_codec, "S_TEXT/ASS" ) ||
-                 !strcmp( tk->psz_codec, "S_SSA" ) ||
-                 !strcmp( tk->psz_codec, "S_ASS" ))
-        {
-            tk->fmt.i_codec = VLC_FOURCC( 's', 's', 'a', ' ' );
-            tk->fmt.subs.psz_encoding = strdup( "UTF-8" );
-        }
-        else if( !strcmp( tk->psz_codec, "S_VOBSUB" ) )
-        {
-            tk->fmt.i_codec = VLC_FOURCC( 's','p','u',' ' );
-            if( tk->i_extra_data )
-            {
-                char *p_start;
-                char *p_buf = (char *)malloc( tk->i_extra_data + 1);
-                memcpy( p_buf, tk->p_extra_data , tk->i_extra_data );
-                p_buf[tk->i_extra_data] = '\0';
-                
-                p_start = strstr( p_buf, "size:" );
-                if( sscanf( p_start, "size: %dx%d",
-                        &tk->fmt.subs.spu.i_original_frame_width, &tk->fmt.subs.spu.i_original_frame_height ) == 2 )
+                else
                 {
-                    msg_Dbg( p_demux, "original frame size vobsubs: %dx%d", tk->fmt.subs.spu.i_original_frame_width, tk->fmt.subs.spu.i_original_frame_height );
+                    *pi_ref2 = int64( ref );
                 }
-                else
+            }
+            else if( MKV_IS_ID( el, KaxClusterSilentTrackNumber ) )
+            {
+                KaxClusterSilentTrackNumber &track_num = *(KaxClusterSilentTrackNumber*)el;
+                track_num.ReadData( es.I_O() );
+                // find the track
+                for (size_t i=0; i<tracks.size(); i++)
                 {
-                    msg_Warn( p_demux, "reading original frame size for vobsub failed" );
+                    if ( tracks[i]->i_number == uint32(track_num))
+                    {
+                        tracks[i]->b_silent = VLC_TRUE;
+                        break;
+                    }
                 }
-                free( p_buf );
             }
         }
-        else if( !strcmp( tk->psz_codec, "B_VOBBTN" ) )
-        {
-            /* FIXME: support this codec */
-            msg_Err( p_demux, "Vob Buttons not supported yet[%d, n=%d]", i_track, tk->i_number );
-            tk->fmt.i_codec = VLC_FOURCC( 'u', 'n', 'd', 'f' );
-        }
         else
         {
-            msg_Err( p_demux, "unknow codec id=`%s'", tk->psz_codec );
-            tk->fmt.i_codec = VLC_FOURCC( 'u', 'n', 'd', 'f' );
-        }
-        if( tk->b_default )
-        {
-            tk->fmt.i_priority = 1000;
+            msg_Err( &sys.demuxer, "invalid level = %d", i_level );
+            return VLC_EGENERIC;
         }
-
-        tk->p_es = es_out_Add( p_demux->out, &tk->fmt );
-#undef tk
     }
-
-    /* add information */
-    InformationCreate( p_demux );
-
-    return VLC_SUCCESS;
-
-error:
-    delete p_sys;
-    return VLC_EGENERIC;
 }
 
-/*****************************************************************************
- * Close: frees unused data
- *****************************************************************************/
-static void Close( vlc_object_t *p_this )
+static block_t *MemToBlock( demux_t *p_demux, uint8_t *p_mem, int i_mem)
 {
-    demux_t     *p_demux = (demux_t*)p_this;
-    demux_sys_t *p_sys   = p_demux->p_sys;
-    matroska_stream_t  *p_stream = p_sys->Stream();
-    matroska_segment_t *p_segment = p_stream->Segment();
-
-    /* TODO close everything ? */
-    
-    delete p_segment->segment;
-
-    delete p_sys;
+    block_t *p_block;
+    if( !(p_block = block_New( p_demux, i_mem ) ) ) return NULL;
+    memcpy( p_block->p_buffer, p_mem, i_mem );
+    //p_block->i_rate = p_input->stream.control.i_rate;
+    return p_block;
 }
 
-/*****************************************************************************
- * Control:
- *****************************************************************************/
-static int Control( demux_t *p_demux, int i_query, va_list args )
+static void BlockDecode( demux_t *p_demux, KaxBlock *block, mtime_t i_pts,
+                         mtime_t i_duration )
 {
     demux_sys_t        *p_sys = p_demux->p_sys;
-    matroska_stream_t  *p_stream = p_sys->Stream();
-    matroska_segment_t *p_segment = p_stream->Segment();
-    int64_t     *pi64;
-    double      *pf, f;
-    int         i_skp;
+    matroska_segment_t *p_segment = p_sys->p_current_segment->Segment();
 
-    vlc_meta_t **pp_meta;
+    size_t          i_track;
+    unsigned int    i;
+    vlc_bool_t      b;
 
-    switch( i_query )
+#define tk  p_segment->tracks[i_track]
+    for( i_track = 0; i_track < p_segment->tracks.size(); i_track++ )
     {
-        case DEMUX_GET_META:
-            pp_meta = (vlc_meta_t**)va_arg( args, vlc_meta_t** );
-            *pp_meta = vlc_meta_Duplicate( p_sys->meta );
-            return VLC_SUCCESS;
+        if( tk->i_number == block->TrackNum() )
+        {
+            break;
+        }
+    }
 
-        case DEMUX_GET_LENGTH:
-            pi64 = (int64_t*)va_arg( args, int64_t * );
-            if( p_segment->f_duration > 0.0 )
-            {
-                *pi64 = (int64_t)(p_segment->f_duration * 1000);
-                return VLC_SUCCESS;
-            }
-            return VLC_EGENERIC;
+    if( i_track >= p_segment->tracks.size() )
+    {
+        msg_Err( p_demux, "invalid track number=%d", block->TrackNum() );
+        return;
+    }
+    if( tk->p_es == NULL )
+    {
+        msg_Err( p_demux, "unknown track number=%d", block->TrackNum() );
+        return;
+    }
+    if( i_pts < p_sys->i_start_pts && tk->fmt.i_cat == AUDIO_ES )
+    {
+        return; /* discard audio packets that shouldn't be rendered */
+    }
 
-        case DEMUX_GET_POSITION:
-            pf = (double*)va_arg( args, double * );
-            *pf = (double)p_sys->i_pts / (1000.0 * p_segment->f_duration);
-            return VLC_SUCCESS;
+    es_out_Control( p_demux->out, ES_OUT_GET_ES_STATE, tk->p_es, &b );
+    if( !b )
+    {
+        tk->b_inited = VLC_FALSE;
+        return;
+    }
 
-        case DEMUX_SET_POSITION:
-            f = (double)va_arg( args, double );
-            Seek( p_demux, -1, f, NULL );
-            return VLC_SUCCESS;
+    /* First send init data */
+    if( !tk->b_inited && tk->i_data_init > 0 )
+    {
+        block_t *p_init;
 
-        case DEMUX_GET_TIME:
-            pi64 = (int64_t*)va_arg( args, int64_t * );
-            *pi64 = p_sys->i_pts;
-            return VLC_SUCCESS;
+        msg_Dbg( p_demux, "sending header (%d bytes)", tk->i_data_init );
+        p_init = MemToBlock( p_demux, tk->p_data_init, tk->i_data_init );
+        if( p_init ) es_out_Send( p_demux->out, tk->p_es, p_init );
+    }
+    tk->b_inited = VLC_TRUE;
 
-        case DEMUX_GET_TITLE_INFO:
-            if( p_sys->title && p_sys->title->i_seekpoint > 0 )
-            {
-                input_title_t ***ppp_title = (input_title_t***)va_arg( args, input_title_t*** );
-                int *pi_int    = (int*)va_arg( args, int* );
 
-                *pi_int = 1;
-                *ppp_title = (input_title_t**)malloc( sizeof( input_title_t**) );
+    for( i = 0; i < block->NumberFrames(); i++ )
+    {
+        block_t *p_block;
+        DataBuffer &data = block->GetBuffer(i);
 
-                (*ppp_title)[0] = vlc_input_title_Duplicate( p_sys->title );
+        p_block = MemToBlock( p_demux, data.Buffer(), data.Size() );
 
-                return VLC_SUCCESS;
-            }
-            return VLC_EGENERIC;
+        if( p_block == NULL )
+        {
+            break;
+        }
 
-        case DEMUX_SET_TITLE:
-            /* TODO handle editions as titles & DVD titles as well */
-            if( p_sys->title && p_sys->title->i_seekpoint > 0 )
+#if defined(HAVE_ZLIB_H)
+        if( tk->i_compression_type )
+        {
+            p_block = block_zlib_decompress( VLC_OBJECT(p_demux), p_block );
+        }
+#endif
+
+        // TODO implement correct timestamping when B frames are used
+        if( tk->fmt.i_cat != VIDEO_ES )
+        {
+            p_block->i_dts = p_block->i_pts = i_pts;
+        }
+        else
+        {
+            p_block->i_dts = i_pts;
+            p_block->i_pts = 0;
+        }
+
+        if( tk->fmt.i_cat == SPU_ES && strcmp( tk->psz_codec, "S_VOBSUB" ) )
+        {
+            p_block->i_length = i_duration * 1000;
+        }
+msg_Warn( p_demux, "Sending block %d", p_block );
+        es_out_Send( p_demux->out, tk->p_es, p_block );
+
+        /* use time stamp only for first block */
+        i_pts = 0;
+    }
+
+#undef tk
+}
+
+matroska_stream_t *demux_sys_t::AnalyseAllSegmentsFound( EbmlStream *p_estream )
+{
+    int i_upper_lvl = 0;
+    size_t i;
+    EbmlElement *p_l0, *p_l1, *p_l2;
+    bool b_keep_stream = false, b_keep_segment;
+
+    // verify the EBML Header
+    p_l0 = p_estream->FindNextID(EbmlHead::ClassInfos, 0xFFFFFFFFL);
+    if (p_l0 == NULL)
+    {
+        return NULL;
+    }
+    p_l0->SkipData(*p_estream, EbmlHead_Context);
+    delete p_l0;
+
+    // find all segments in this file
+    p_l0 = p_estream->FindNextID(KaxSegment::ClassInfos, 0xFFFFFFFFL);
+    if (p_l0 == NULL)
+    {
+        return NULL;
+    }
+
+    matroska_stream_t *p_stream1 = new matroska_stream_t( *this );
+
+    while (p_l0 != 0)
+    {
+        if (EbmlId(*p_l0) == KaxSegment::ClassInfos.GlobalId)
+        {
+            EbmlParser  *ep;
+            matroska_segment_t *p_segment1 = new matroska_segment_t( *this, *p_estream );
+            b_keep_segment = false;
+
+            ep = new EbmlParser(p_estream, p_l0);
+            p_segment1->ep = ep;
+            p_segment1->segment = (KaxSegment*)p_l0;
+
+            while ((p_l1 = ep->Get()))
             {
-                return VLC_SUCCESS;
-            }
-            return VLC_EGENERIC;
+                if (MKV_IS_ID(p_l1, KaxInfo))
+                {
+                    // find the families of this segment
+                    KaxInfo *p_info = static_cast<KaxInfo*>(p_l1);
 
-        case DEMUX_SET_SEEKPOINT:
-            /* FIXME do a better implementation */
-            i_skp = (int)va_arg( args, int );
+                    p_info->Read(*p_estream, KaxInfo::ClassInfos.Context, i_upper_lvl, p_l2, true);
+                    for( i = 0; i < p_info->ListSize(); i++ )
+                    {
+                        EbmlElement *l = (*p_info)[i];
 
-            if( p_sys->title && i_skp < p_sys->title->i_seekpoint)
+                        if( MKV_IS_ID( l, KaxSegmentUID ) )
+                        {
+                            KaxSegmentUID *p_uid = static_cast<KaxSegmentUID*>(l);
+                            b_keep_segment = (FindSegment( *p_uid ) == NULL);
+                            if ( !b_keep_segment )
+                                break; // this segment is already known
+                            opened_segments.push_back( p_segment1 );
+                            p_segment1->segment_uid = *( new KaxSegmentUID(*p_uid) );
+                        }
+                        else if( MKV_IS_ID( l, KaxPrevUID ) )
+                        {
+                            p_segment1->prev_segment_uid = *( new KaxPrevUID( *static_cast<KaxPrevUID*>(l) ) );
+                        }
+                        else if( MKV_IS_ID( l, KaxNextUID ) )
+                        {
+                            p_segment1->next_segment_uid = *( new KaxNextUID( *static_cast<KaxNextUID*>(l) ) );
+                        }
+                        else if( MKV_IS_ID( l, KaxSegmentFamily ) )
+                        {
+                            KaxSegmentFamily *p_fam = new KaxSegmentFamily( *static_cast<KaxSegmentFamily*>(l) );
+                            std::vector<KaxSegmentFamily>::iterator iter;
+                            p_segment1->families.push_back( *p_fam );
+                        }
+                    }
+                    break;
+                }
+            }
+            if ( b_keep_segment )
             {
-                Seek( p_demux, (int64_t)p_sys->title->seekpoint[i_skp]->i_time_offset, -1, NULL);
-                p_demux->info.i_seekpoint |= INPUT_UPDATE_SEEKPOINT;
-                p_demux->info.i_seekpoint = i_skp;
-                return VLC_SUCCESS;
+                b_keep_stream = true;
+                p_stream1->segments.push_back( p_segment1 );
             }
-            return VLC_EGENERIC;
+            else
+                delete p_segment1;
+        }
 
-        case DEMUX_SET_TIME:
-        case DEMUX_GET_FPS:
-        default:
-            return VLC_EGENERIC;
+        p_l0->SkipData(*p_estream, EbmlHead_Context);
+        p_l0 = p_estream->FindNextID(KaxSegment::ClassInfos, 0xFFFFFFFFL);
+    }
+
+    if ( !b_keep_stream )
+    {
+        delete p_stream1;
+        p_stream1 = NULL;
     }
+
+    return p_stream1;
 }
 
-int matroska_segment_t::BlockGet( KaxBlock **pp_block, int64_t *pi_ref1, int64_t *pi_ref2, int64_t *pi_duration )
+bool matroska_segment_t::Select( mtime_t i_start_time )
 {
-    *pp_block = NULL;
-    *pi_ref1  = -1;
-    *pi_ref2  = -1;
+    size_t i_track;
 
-    for( ;; )
+    /* add all es */
+    msg_Dbg( &sys.demuxer, "found %d es", tracks.size() );
+    for( i_track = 0; i_track < tracks.size(); i_track++ )
     {
-        EbmlElement *el;
-        int         i_level;
+#define tk  tracks[i_track]
+        if( tk->fmt.i_cat == UNKNOWN_ES )
+        {
+            msg_Warn( &sys.demuxer, "invalid track[%d, n=%d]", i_track, tk->i_number );
+            tk->p_es = NULL;
+            continue;
+        }
 
-        if( sys.demuxer.b_die )
+        if( !strcmp( tk->psz_codec, "V_MS/VFW/FOURCC" ) )
+        {
+            if( tk->i_extra_data < (int)sizeof( BITMAPINFOHEADER ) )
+            {
+                msg_Err( &sys.demuxer, "missing/invalid BITMAPINFOHEADER" );
+                tk->fmt.i_codec = VLC_FOURCC( 'u', 'n', 'd', 'f' );
+            }
+            else
+            {
+                BITMAPINFOHEADER *p_bih = (BITMAPINFOHEADER*)tk->p_extra_data;
+
+                tk->fmt.video.i_width = GetDWLE( &p_bih->biWidth );
+                tk->fmt.video.i_height= GetDWLE( &p_bih->biHeight );
+                tk->fmt.i_codec       = GetFOURCC( &p_bih->biCompression );
+
+                tk->fmt.i_extra       = GetDWLE( &p_bih->biSize ) - sizeof( BITMAPINFOHEADER );
+                if( tk->fmt.i_extra > 0 )
+                {
+                    tk->fmt.p_extra = malloc( tk->fmt.i_extra );
+                    memcpy( tk->fmt.p_extra, &p_bih[1], tk->fmt.i_extra );
+                }
+            }
+        }
+        else if( !strcmp( tk->psz_codec, "V_MPEG1" ) ||
+                 !strcmp( tk->psz_codec, "V_MPEG2" ) )
+        {
+            tk->fmt.i_codec = VLC_FOURCC( 'm', 'p', 'g', 'v' );
+        }
+        else if( !strncmp( tk->psz_codec, "V_MPEG4", 7 ) )
+        {
+            if( !strcmp( tk->psz_codec, "V_MPEG4/MS/V3" ) )
+            {
+                tk->fmt.i_codec = VLC_FOURCC( 'D', 'I', 'V', '3' );
+            }
+            else if( !strcmp( tk->psz_codec, "V_MPEG4/ISO/AVC" ) )
+            {
+                tk->fmt.i_codec = VLC_FOURCC( 'a', 'v', 'c', '1' );
+                tk->fmt.b_packetized = VLC_FALSE;
+                tk->fmt.i_extra = tk->i_extra_data;
+                tk->fmt.p_extra = malloc( tk->i_extra_data );
+                memcpy( tk->fmt.p_extra,tk->p_extra_data, tk->i_extra_data );
+            }
+            else
+            {
+                tk->fmt.i_codec = VLC_FOURCC( 'm', 'p', '4', 'v' );
+            }
+        }
+        else if( !strcmp( tk->psz_codec, "V_QUICKTIME" ) )
+        {
+            MP4_Box_t *p_box = (MP4_Box_t*)malloc( sizeof( MP4_Box_t ) );
+            stream_t *p_mp4_stream = stream_MemoryNew( VLC_OBJECT(&sys.demuxer),
+                                                       tk->p_extra_data,
+                                                       tk->i_extra_data );
+            MP4_ReadBoxCommon( p_mp4_stream, p_box );
+            MP4_ReadBox_sample_vide( p_mp4_stream, p_box );
+            tk->fmt.i_codec = p_box->i_type;
+            tk->fmt.video.i_width = p_box->data.p_sample_vide->i_width;
+            tk->fmt.video.i_height = p_box->data.p_sample_vide->i_height;
+            tk->fmt.i_extra = p_box->data.p_sample_vide->i_qt_image_description;
+            tk->fmt.p_extra = malloc( tk->fmt.i_extra );
+            memcpy( tk->fmt.p_extra, p_box->data.p_sample_vide->p_qt_image_description, tk->fmt.i_extra );
+            MP4_FreeBox_sample_vide( p_box );
+            stream_MemoryDelete( p_mp4_stream, VLC_TRUE );
+        }
+        else if( !strcmp( tk->psz_codec, "A_MS/ACM" ) )
+        {
+            if( tk->i_extra_data < (int)sizeof( WAVEFORMATEX ) )
+            {
+                msg_Err( &sys.demuxer, "missing/invalid WAVEFORMATEX" );
+                tk->fmt.i_codec = VLC_FOURCC( 'u', 'n', 'd', 'f' );
+            }
+            else
+            {
+                WAVEFORMATEX *p_wf = (WAVEFORMATEX*)tk->p_extra_data;
+
+                wf_tag_to_fourcc( GetWLE( &p_wf->wFormatTag ), &tk->fmt.i_codec, NULL );
+
+                tk->fmt.audio.i_channels   = GetWLE( &p_wf->nChannels );
+                tk->fmt.audio.i_rate = GetDWLE( &p_wf->nSamplesPerSec );
+                tk->fmt.i_bitrate    = GetDWLE( &p_wf->nAvgBytesPerSec ) * 8;
+                tk->fmt.audio.i_blockalign = GetWLE( &p_wf->nBlockAlign );;
+                tk->fmt.audio.i_bitspersample = GetWLE( &p_wf->wBitsPerSample );
+
+                tk->fmt.i_extra            = GetWLE( &p_wf->cbSize );
+                if( tk->fmt.i_extra > 0 )
+                {
+                    tk->fmt.p_extra = malloc( tk->fmt.i_extra );
+                    memcpy( tk->fmt.p_extra, &p_wf[1], tk->fmt.i_extra );
+                }
+            }
+        }
+        else if( !strcmp( tk->psz_codec, "A_MPEG/L3" ) ||
+                 !strcmp( tk->psz_codec, "A_MPEG/L2" ) ||
+                 !strcmp( tk->psz_codec, "A_MPEG/L1" ) )
         {
-            return VLC_EGENERIC;
+            tk->fmt.i_codec = VLC_FOURCC( 'm', 'p', 'g', 'a' );
         }
-
-        el = ep->Get();
-        i_level = ep->GetLevel();
-
-        if( el == NULL && *pp_block != NULL )
+        else if( !strcmp( tk->psz_codec, "A_AC3" ) )
         {
-            /* update the index */
-#define idx index[i_index - 1]
-            if( i_index > 0 && idx.i_time == -1 )
-            {
-                idx.i_time        = (*pp_block)->GlobalTimecode() / (mtime_t)1000;
-                idx.b_key         = *pi_ref1 == -1 ? VLC_TRUE : VLC_FALSE;
-            }
-#undef idx
-            return VLC_SUCCESS;
+            tk->fmt.i_codec = VLC_FOURCC( 'a', '5', '2', ' ' );
         }
-
-        if( el == NULL )
+        else if( !strcmp( tk->psz_codec, "A_DTS" ) )
         {
-            if( ep->GetLevel() > 1 )
-            {
-                ep->Up();
-                continue;
-            }
-            msg_Warn( &sys.demuxer, "EOF" );
-            return VLC_EGENERIC;
+            tk->fmt.i_codec = VLC_FOURCC( 'd', 't', 's', ' ' );
         }
-
-        /* do parsing */
-        if( i_level == 1 )
+        else if( !strcmp( tk->psz_codec, "A_FLAC" ) )
         {
-            if( MKV_IS_ID( el, KaxCluster ) )
-            {
-                cluster = (KaxCluster*)el;
+            tk->fmt.i_codec = VLC_FOURCC( 'f', 'l', 'a', 'c' );
+            tk->fmt.i_extra = tk->i_extra_data;
+            tk->fmt.p_extra = malloc( tk->i_extra_data );
+            memcpy( tk->fmt.p_extra,tk->p_extra_data, tk->i_extra_data );
+        }
+        else if( !strcmp( tk->psz_codec, "A_VORBIS" ) )
+        {
+            int i, i_offset = 1, i_size[3], i_extra;
+            uint8_t *p_extra;
 
-                /* add it to the index */
-                if( i_index == 0 ||
-                    ( i_index > 0 && index[i_index - 1].i_position < (int64_t)cluster->GetElementPosition() ) )
-                {
-                    IndexAppendCluster( cluster );
-                }
+            tk->fmt.i_codec = VLC_FOURCC( 'v', 'o', 'r', 'b' );
 
-                // reset silent tracks
-                for (size_t i=0; i<tracks.size(); i++)
-                {
-                    tracks[i]->b_silent = VLC_FALSE;
-                }
+            /* Split the 3 headers */
+            if( tk->p_extra_data[0] != 0x02 )
+                msg_Err( &sys.demuxer, "invalid vorbis header" );
 
-                ep->Down();
-            }
-            else if( MKV_IS_ID( el, KaxCues ) )
+            for( i = 0; i < 2; i++ )
             {
-                msg_Warn( &sys.demuxer, "find KaxCues FIXME" );
-                return VLC_EGENERIC;
+                i_size[i] = 0;
+                while( i_offset < tk->i_extra_data )
+                {
+                    i_size[i] += tk->p_extra_data[i_offset];
+                    if( tk->p_extra_data[i_offset++] != 0xff ) break;
+                }
             }
-            else
+
+            i_size[0] = __MIN(i_size[0], tk->i_extra_data - i_offset);
+            i_size[1] = __MIN(i_size[1], tk->i_extra_data -i_offset -i_size[0]);
+            i_size[2] = tk->i_extra_data - i_offset - i_size[0] - i_size[1];
+
+            tk->fmt.i_extra = 3 * 2 + i_size[0] + i_size[1] + i_size[2];
+            tk->fmt.p_extra = malloc( tk->fmt.i_extra );
+            p_extra = (uint8_t *)tk->fmt.p_extra; i_extra = 0;
+            for( i = 0; i < 3; i++ )
             {
-                msg_Dbg( &sys.demuxer, "unknown (%s)", typeid( el ).name() );
+                *(p_extra++) = i_size[i] >> 8;
+                *(p_extra++) = i_size[i] & 0xFF;
+                memcpy( p_extra, tk->p_extra_data + i_offset + i_extra,
+                        i_size[i] );
+                p_extra += i_size[i];
+                i_extra += i_size[i];
             }
         }
-        else if( i_level == 2 )
+        else if( !strncmp( tk->psz_codec, "A_AAC/MPEG2/", strlen( "A_AAC/MPEG2/" ) ) ||
+                 !strncmp( tk->psz_codec, "A_AAC/MPEG4/", strlen( "A_AAC/MPEG4/" ) ) )
         {
-            if( MKV_IS_ID( el, KaxClusterTimecode ) )
+            int i_profile, i_srate;
+            static unsigned int i_sample_rates[] =
             {
-                KaxClusterTimecode &ctc = *(KaxClusterTimecode*)el;
+                    96000, 88200, 64000, 48000, 44100, 32000, 24000, 22050,
+                        16000, 12000, 11025, 8000,  7350,  0,     0,     0
+            };
 
-                ctc.ReadData( es.I_O(), SCOPE_ALL_DATA );
-                cluster->InitTimecode( uint64( ctc ), i_timescale );
-            }
-            else if( MKV_IS_ID( el, KaxClusterSilentTracks ) )
+            tk->fmt.i_codec = VLC_FOURCC( 'm', 'p', '4', 'a' );
+            /* create data for faad (MP4DecSpecificDescrTag)*/
+
+            if( !strcmp( &tk->psz_codec[12], "MAIN" ) )
             {
-                ep->Down();
+                i_profile = 0;
             }
-            else if( MKV_IS_ID( el, KaxBlockGroup ) )
+            else if( !strcmp( &tk->psz_codec[12], "LC" ) )
             {
-                ep->Down();
+                i_profile = 1;
             }
-        }
-        else if( i_level == 3 )
-        {
-            if( MKV_IS_ID( el, KaxBlock ) )
+            else if( !strcmp( &tk->psz_codec[12], "SSR" ) )
             {
-                *pp_block = (KaxBlock*)el;
-
-                (*pp_block)->ReadData( es.I_O() );
-                (*pp_block)->SetParent( *cluster );
-
-                ep->Keep();
+                i_profile = 2;
             }
-            else if( MKV_IS_ID( el, KaxBlockDuration ) )
+            else
             {
-                KaxBlockDuration &dur = *(KaxBlockDuration*)el;
-
-                dur.ReadData( es.I_O() );
-                *pi_duration = uint64( dur );
+                i_profile = 3;
             }
-            else if( MKV_IS_ID( el, KaxReferenceBlock ) )
-            {
-                KaxReferenceBlock &ref = *(KaxReferenceBlock*)el;
 
-                ref.ReadData( es.I_O() );
-                if( *pi_ref1 == -1 )
-                {
-                    *pi_ref1 = int64( ref );
-                }
-                else
-                {
-                    *pi_ref2 = int64( ref );
-                }
-            }
-            else if( MKV_IS_ID( el, KaxClusterSilentTrackNumber ) )
+            for( i_srate = 0; i_srate < 13; i_srate++ )
             {
-                KaxClusterSilentTrackNumber &track_num = *(KaxClusterSilentTrackNumber*)el;
-                track_num.ReadData( es.I_O() );
-                // find the track
-                for (size_t i=0; i<tracks.size(); i++)
+                if( i_sample_rates[i_srate] == tk->fmt.audio.i_rate )
                 {
-                    if ( tracks[i]->i_number == uint32(track_num))
-                    {
-                        tracks[i]->b_silent = VLC_TRUE;
-                        break;
-                    }
+                    break;
                 }
             }
-        }
-        else
-        {
-            msg_Err( &sys.demuxer, "invalid level = %d", i_level );
-            return VLC_EGENERIC;
-        }
-    }
-}
-
-static block_t *MemToBlock( demux_t *p_demux, uint8_t *p_mem, int i_mem)
-{
-    block_t *p_block;
-    if( !(p_block = block_New( p_demux, i_mem ) ) ) return NULL;
-    memcpy( p_block->p_buffer, p_mem, i_mem );
-    //p_block->i_rate = p_input->stream.control.i_rate;
-    return p_block;
-}
-
-static void BlockDecode( demux_t *p_demux, KaxBlock *block, mtime_t i_pts,
-                         mtime_t i_duration )
-{
-    demux_sys_t        *p_sys = p_demux->p_sys;
-    matroska_stream_t  *p_stream = p_sys->Stream();
-    matroska_segment_t *p_segment = p_stream->Segment();
-
-    size_t          i_track;
-    unsigned int    i;
-    vlc_bool_t      b;
+            msg_Dbg( &sys.demuxer, "profile=%d srate=%d", i_profile, i_srate );
 
-#define tk  p_segment->tracks[i_track]
-    for( i_track = 0; i_track < p_segment->tracks.size(); i_track++ )
-    {
-        if( tk->i_number == block->TrackNum() )
-        {
-            break;
+            tk->fmt.i_extra = 2;
+            tk->fmt.p_extra = malloc( tk->fmt.i_extra );
+            ((uint8_t*)tk->fmt.p_extra)[0] = ((i_profile + 1) << 3) | ((i_srate&0xe) >> 1);
+            ((uint8_t*)tk->fmt.p_extra)[1] = ((i_srate & 0x1) << 7) | (tk->fmt.audio.i_channels << 3);
         }
-    }
-
-    if( i_track >= p_segment->tracks.size() )
-    {
-        msg_Err( p_demux, "invalid track number=%d", block->TrackNum() );
-        return;
-    }
-    if( tk->p_es == NULL )
-    {
-        msg_Err( p_demux, "unknown track number=%d", block->TrackNum() );
-        return;
-    }
-    if( i_pts < p_sys->i_start_pts && tk->fmt.i_cat == AUDIO_ES )
-    {
-        return; /* discard audio packets that shouldn't be rendered */
-    }
-
-    es_out_Control( p_demux->out, ES_OUT_GET_ES_STATE, tk->p_es, &b );
-    if( !b )
-    {
-        tk->b_inited = VLC_FALSE;
-        return;
-    }
-
-    /* First send init data */
-    if( !tk->b_inited && tk->i_data_init > 0 )
-    {
-        block_t *p_init;
-
-        msg_Dbg( p_demux, "sending header (%d bytes)", tk->i_data_init );
-        p_init = MemToBlock( p_demux, tk->p_data_init, tk->i_data_init );
-        if( p_init ) es_out_Send( p_demux->out, tk->p_es, p_init );
-    }
-    tk->b_inited = VLC_TRUE;
-
-
-    for( i = 0; i < block->NumberFrames(); i++ )
-    {
-        block_t *p_block;
-        DataBuffer &data = block->GetBuffer(i);
-
-        p_block = MemToBlock( p_demux, data.Buffer(), data.Size() );
-
-        if( p_block == NULL )
+        else if( !strcmp( tk->psz_codec, "A_PCM/INT/BIG" ) ||
+                 !strcmp( tk->psz_codec, "A_PCM/INT/LIT" ) ||
+                 !strcmp( tk->psz_codec, "A_PCM/FLOAT/IEEE" ) )
+        {
+            if( !strcmp( tk->psz_codec, "A_PCM/INT/BIG" ) )
+            {
+                tk->fmt.i_codec = VLC_FOURCC( 't', 'w', 'o', 's' );
+            }
+            else
+            {
+                tk->fmt.i_codec = VLC_FOURCC( 'a', 'r', 'a', 'w' );
+            }
+            tk->fmt.audio.i_blockalign = ( tk->fmt.audio.i_bitspersample + 7 ) / 8 * tk->fmt.audio.i_channels;
+        }
+        else if( !strcmp( tk->psz_codec, "A_TTA1" ) )
         {
-            break;
+            /* FIXME: support this codec */
+            msg_Err( &sys.demuxer, "TTA not supported yet[%d, n=%d]", i_track, tk->i_number );
+            tk->fmt.i_codec = VLC_FOURCC( 'u', 'n', 'd', 'f' );
         }
-
-#if defined(HAVE_ZLIB_H)
-        if( tk->i_compression_type )
+        else if( !strcmp( tk->psz_codec, "A_WAVPACK4" ) )
         {
-            p_block = block_zlib_decompress( VLC_OBJECT(p_demux), p_block );
+            /* FIXME: support this codec */
+            msg_Err( &sys.demuxer, "Wavpack not supported yet[%d, n=%d]", i_track, tk->i_number );
+            tk->fmt.i_codec = VLC_FOURCC( 'u', 'n', 'd', 'f' );
         }
-#endif
-
-        // TODO implement correct timestamping when B frames are used
-        if( tk->fmt.i_cat != VIDEO_ES )
+        else if( !strcmp( tk->psz_codec, "S_TEXT/UTF8" ) )
         {
-            p_block->i_dts = p_block->i_pts = i_pts;
+            tk->fmt.i_codec = VLC_FOURCC( 's', 'u', 'b', 't' );
+            tk->fmt.subs.psz_encoding = strdup( "UTF-8" );
+        }
+        else if( !strcmp( tk->psz_codec, "S_TEXT/SSA" ) ||
+                 !strcmp( tk->psz_codec, "S_TEXT/ASS" ) ||
+                 !strcmp( tk->psz_codec, "S_SSA" ) ||
+                 !strcmp( tk->psz_codec, "S_ASS" ))
+        {
+            tk->fmt.i_codec = VLC_FOURCC( 's', 's', 'a', ' ' );
+            tk->fmt.subs.psz_encoding = strdup( "UTF-8" );
+        }
+        else if( !strcmp( tk->psz_codec, "S_VOBSUB" ) )
+        {
+            tk->fmt.i_codec = VLC_FOURCC( 's','p','u',' ' );
+            if( tk->i_extra_data )
+            {
+                char *p_start;
+                char *p_buf = (char *)malloc( tk->i_extra_data + 1);
+                memcpy( p_buf, tk->p_extra_data , tk->i_extra_data );
+                p_buf[tk->i_extra_data] = '\0';
+                
+                p_start = strstr( p_buf, "size:" );
+                if( sscanf( p_start, "size: %dx%d",
+                        &tk->fmt.subs.spu.i_original_frame_width, &tk->fmt.subs.spu.i_original_frame_height ) == 2 )
+                {
+                    msg_Dbg( &sys.demuxer, "original frame size vobsubs: %dx%d", tk->fmt.subs.spu.i_original_frame_width, tk->fmt.subs.spu.i_original_frame_height );
+                }
+                else
+                {
+                    msg_Warn( &sys.demuxer, "reading original frame size for vobsub failed" );
+                }
+                free( p_buf );
+            }
+        }
+        else if( !strcmp( tk->psz_codec, "B_VOBBTN" ) )
+        {
+            /* FIXME: support this codec */
+            msg_Err( &sys.demuxer, "Vob Buttons not supported yet[%d, n=%d]", i_track, tk->i_number );
+            tk->fmt.i_codec = VLC_FOURCC( 'u', 'n', 'd', 'f' );
         }
         else
         {
-            p_block->i_dts = i_pts;
-            p_block->i_pts = 0;
+            msg_Err( &sys.demuxer, "unknow codec id=`%s'", tk->psz_codec );
+            tk->fmt.i_codec = VLC_FOURCC( 'u', 'n', 'd', 'f' );
         }
-
-        if( tk->fmt.i_cat == SPU_ES && strcmp( tk->psz_codec, "S_VOBSUB" ) )
+        if( tk->b_default )
         {
-            p_block->i_length = i_duration * 1000;
+            tk->fmt.i_priority = 1000;
         }
-        es_out_Send( p_demux->out, tk->p_es, p_block );
 
-        /* use time stamp only for first block */
-        i_pts = 0;
-    }
+        tk->p_es = es_out_Add( sys.demuxer.out, &tk->fmt );
 
+        es_out_Control( sys.demuxer.out, ES_OUT_SET_NEXT_DISPLAY_TIME, tk->p_es, i_start_time );
 #undef tk
-}
-
-matroska_stream_t *demux_sys_t::AnalyseAllSegmentsFound( EbmlStream *p_estream )
-{
-    int i_upper_lvl = 0;
-    size_t i;
-    EbmlElement *p_l0, *p_l1, *p_l2;
-    bool b_keep_stream = false, b_keep_segment;
-
-    // verify the EBML Header
-    p_l0 = p_estream->FindNextID(EbmlHead::ClassInfos, 0xFFFFFFFFL);
-    if (p_l0 == NULL)
-    {
-        return NULL;
     }
-    p_l0->SkipData(*p_estream, EbmlHead_Context);
-    delete p_l0;
+    
+    sys.i_start_pts = i_start_time;
+    ep->Reset();
 
-    // find all segments in this file
-    p_l0 = p_estream->FindNextID(KaxSegment::ClassInfos, 0xFFFFFFFFL);
-    if (p_l0 == NULL)
-    {
-        return NULL;
-    }
+    // reset the stream reading to the first cluster of the segment used
+    es.I_O().setFilePointer( i_start_pos );
 
-    matroska_stream_t *p_stream1 = new matroska_stream_t( *this );
+    return true;
+}
 
-    while (p_l0 != 0)
+void matroska_segment_t::UnSelect( )
+{
+    size_t i_track;
+
+    for( i_track = 0; i_track < tracks.size(); i_track++ )
     {
-        if (EbmlId(*p_l0) == KaxSegment::ClassInfos.GlobalId)
+#define tk  tracks[i_track]
+        if ( tk->p_es != NULL )
         {
-            EbmlParser  *ep;
-            matroska_segment_t *p_segment1 = new matroska_segment_t( *this, *p_estream );
-            b_keep_segment = false;
-
-            ep = new EbmlParser(p_estream, p_l0);
-            p_segment1->ep = ep;
-            p_segment1->segment = (KaxSegment*)p_l0;
-
-            while ((p_l1 = ep->Get()))
-            {
-                if (MKV_IS_ID(p_l1, KaxInfo))
-                {
-                    // find the families of this segment
-                    KaxInfo *p_info = static_cast<KaxInfo*>(p_l1);
-
-                    p_info->Read(*p_estream, KaxInfo::ClassInfos.Context, i_upper_lvl, p_l2, true);
-                    for( i = 0; i < p_info->ListSize(); i++ )
-                    {
-                        EbmlElement *l = (*p_info)[i];
-
-                        if( MKV_IS_ID( l, KaxSegmentUID ) )
-                        {
-                            KaxSegmentUID *p_uid = static_cast<KaxSegmentUID*>(l);
-                            b_keep_segment = (FindSegment( *p_uid ) == NULL);
-                            if ( !b_keep_segment )
-                                break; // this segment is already known
-                            p_segment1->segment_uid = *( new KaxSegmentUID(*p_uid) );
-                        }
-                        else if( MKV_IS_ID( l, KaxPrevUID ) )
-                        {
-                            p_segment1->prev_segment_uid = *( new KaxPrevUID( *static_cast<KaxPrevUID*>(l) ) );
-                        }
-                        else if( MKV_IS_ID( l, KaxNextUID ) )
-                        {
-                            p_segment1->next_segment_uid = *( new KaxNextUID( *static_cast<KaxNextUID*>(l) ) );
-                        }
-                        else if( MKV_IS_ID( l, KaxSegmentFamily ) )
-                        {
-                            KaxSegmentFamily *p_fam = new KaxSegmentFamily( *static_cast<KaxSegmentFamily*>(l) );
-                            std::vector<KaxSegmentFamily>::iterator iter;
-                            p_segment1->families.push_back( *p_fam );
-                        }
-                    }
-                    break;
-                }
-            }
-            if ( b_keep_segment )
-            {
-                b_keep_stream = true;
-                p_stream1->segments.push_back( p_segment1 );
-            }
-            else
-                delete p_segment1;
+            es_out_Del( sys.demuxer.out, tk->p_es );
+            tk->p_es = NULL;
         }
-
-        p_l0->SkipData(*p_estream, EbmlHead_Context);
-        p_l0 = p_estream->FindNextID(KaxSegment::ClassInfos, 0xFFFFFFFFL);
-    }
-
-    if ( !b_keep_stream )
-    {
-        delete p_stream1;
-        p_stream1 = NULL;
+#undef tk
     }
-
-    return p_stream1;
 }
 
 static void UpdateCurrentToChapter( demux_t & demux )
 {
     demux_sys_t & sys = *demux.p_sys;
-    matroska_stream_t  *p_stream = sys.Stream();
-    matroska_segment_t *p_segment = p_stream->Segment();
+    matroska_segment_t *p_segment = sys.p_current_segment->Segment();
     const chapter_item_t *psz_curr_chapter;
 
     /* update current chapter/seekpoint */
@@ -1553,8 +1615,7 @@ static void UpdateCurrentToChapter( demux_t & demux )
 static void Seek( demux_t *p_demux, mtime_t i_date, double f_percent, const chapter_item_t *psz_chapter)
 {
     demux_sys_t        *p_sys = p_demux->p_sys;
-    matroska_stream_t  *p_stream = p_sys->Stream();
-    matroska_segment_t *p_segment = p_stream->Segment();
+    matroska_segment_t *p_segment = p_sys->p_current_segment->Segment();
     mtime_t            i_time_offset = 0;
 
     KaxBlock    *block;
@@ -1579,15 +1640,15 @@ static void Seek( demux_t *p_demux, mtime_t i_date, double f_percent, const chap
     }
 
     delete p_segment->ep;
-    p_segment->ep = new EbmlParser( p_stream->p_es, p_segment->segment );
+    p_segment->ep = new EbmlParser( &p_segment->es, p_segment->segment );
     p_segment->cluster = NULL;
 
     /* seek without index or without date */
     if( f_percent >= 0 && (config_GetInt( p_demux, "mkv-seek-percent" ) || !p_segment->b_cues || i_date < 0 ))
     {
-        if (p_segment->f_duration >= 0)
+        if (p_sys->f_duration >= 0)
         {
-            i_date = int64_t( f_percent * p_segment->f_duration * 1000.0 );
+            i_date = int64_t( f_percent * p_sys->f_duration * 1000.0 );
         }
         else
         {
@@ -1674,7 +1735,7 @@ static void Seek( demux_t *p_demux, mtime_t i_date, double f_percent, const chap
                 (int)( 100 * p_segment->index[i_index].i_position /
                     stream_Size( p_demux->s ) ) );
 
-    p_stream->p_in->setFilePointer( p_segment->index[i_index].i_position,
+    p_segment->es.I_O().setFilePointer( p_segment->index[i_index].i_position,
                                 seek_beginning );
 
     p_sys->i_start_pts = i_date;
@@ -1748,8 +1809,8 @@ static void Seek( demux_t *p_demux, mtime_t i_date, double f_percent, const chap
 static int Demux( demux_t *p_demux)
 {
     demux_sys_t        *p_sys = p_demux->p_sys;
-    matroska_stream_t  *p_stream = p_sys->Stream();
-    matroska_segment_t *p_segment = p_stream->Segment();
+    matroska_segment_t *p_segment = p_sys->p_current_segment->Segment();
+    if ( p_segment == NULL ) return 0;
     int                i_block_count = 0;
 
     KaxBlock *block;
@@ -1765,10 +1826,19 @@ static int Demux( demux_t *p_demux)
         if ( p_segment->editions.size() && p_segment->editions[p_segment->i_current_edition].b_ordered && p_segment->psz_current_chapter == NULL )
         {
             /* nothing left to read in this ordered edition */
-            if ( p_stream->i_current_segment == p_stream->segments.size() - 1)
+            if ( !p_sys->p_current_segment->SelectNext() )
+                return 0;
+            p_segment->UnSelect( );
+            
+            es_out_Control( p_demux->out, ES_OUT_RESET_PCR );
+
+            /* switch to the next segment */
+            p_segment = p_sys->p_current_segment->Segment();
+            if ( !p_segment->Select( 0 ) )
+            {
+                msg_Err( p_demux, "Failed to select new segment" );
                 return 0;
-            /* switch to the next segment (TODO update the duration) */
-            p_stream->i_current_segment++;
+            }
             continue;
         }
 
@@ -1786,8 +1856,22 @@ static int Demux( demux_t *p_demux)
                 return 0;
             }
             msg_Warn( p_demux, "cannot get block EOF?" );
+            p_segment->UnSelect( );
+            
+            es_out_Control( p_demux->out, ES_OUT_RESET_PCR );
 
-            return 0;
+            /* switch to the next segment */
+            if ( !p_sys->p_current_segment->SelectNext() )
+                // no more segments in this stream
+                return 0;
+            p_segment = p_sys->p_current_segment->Segment();
+            if ( !p_segment->Select( 0 ) )
+            {
+                msg_Err( p_demux, "Failed to select new segment" );
+                return 0;
+            }
+
+            continue;
         }
 
         p_sys->i_pts = p_sys->i_chapter_time + block->GlobalTimecode() / (mtime_t) 1000;
@@ -1936,11 +2020,16 @@ int EbmlParser::GetLevel( void )
 
 void EbmlParser::Reset( void )
 {
-    delete m_el[mi_level];
-    m_el[mi_level] = NULL;
+    while ( mi_level > 0)
+    {
+        delete m_el[mi_level];
+        m_el[mi_level] = NULL;
+        mi_level--;
+    }
+    mi_user_level = mi_level = 1;
 #if LIBEBML_VERSION >= 0x000704
     // a little faster and cleaner
-    m_es->I_O().setFilePointer( static_cast<EbmlMaster*>(m_el[0])->GetDataStart() );
+    m_es->I_O().setFilePointer( static_cast<KaxSegment*>(m_el[0])->GetGlobalPosition(0) );
 #else
     m_es->I_O().setFilePointer( m_el[0]->GetElementPosition() + m_el[0]->ElementSize(true) - m_el[0]->GetSize() );
 #endif
@@ -2010,32 +2099,39 @@ EbmlElement *EbmlParser::Get( void )
  *  * InformationCreate : create all information, load tags if present
  *
  *****************************************************************************/
-static void LoadCues( demux_t *p_demux )
+void matroska_segment_t::LoadCues( )
 {
-    demux_sys_t *p_sys = p_demux->p_sys;
-    matroska_stream_t  *p_stream = p_sys->Stream();
-    matroska_segment_t *p_segment = p_stream->Segment();
-    int64_t     i_sav_position = p_stream->p_in->getFilePointer();
+    int64_t     i_sav_position = es.I_O().getFilePointer();
     EbmlParser  *ep;
     EbmlElement *el, *cues;
 
-    msg_Dbg( p_demux, "loading cues" );
-    p_stream->p_in->setFilePointer( p_segment->i_cues_position, seek_beginning );
-    cues = p_stream->p_es->FindNextID( KaxCues::ClassInfos, 0xFFFFFFFFL);
+    /* *** Load the cue if found *** */
+    if( i_cues_position < 0 )
+        return;
+
+    vlc_bool_t b_seekable;
+
+    stream_Control( sys.demuxer.s, STREAM_CAN_FASTSEEK, &b_seekable );
+    if( !b_seekable )
+        return;
+
+    msg_Dbg( &sys.demuxer, "loading cues" );
+    es.I_O().setFilePointer( i_cues_position, seek_beginning );
+    cues = es.FindNextID( KaxCues::ClassInfos, 0xFFFFFFFFL);
 
     if( cues == NULL )
     {
-        msg_Err( p_demux, "cannot load cues (broken seekhead or file)" );
-        p_stream->p_in->setFilePointer( i_sav_position, seek_beginning );
+        msg_Err( &sys.demuxer, "cannot load cues (broken seekhead or file)" );
+        es.I_O().setFilePointer( i_sav_position, seek_beginning );
         return;
     }
 
-    ep = new EbmlParser( p_stream->p_es, cues );
+    ep = new EbmlParser( &es, cues );
     while( ( el = ep->Get() ) != NULL )
     {
         if( MKV_IS_ID( el, KaxCuePoint ) )
         {
-#define idx p_segment->index[p_segment->i_index]
+#define idx index[i_index]
 
             idx.i_track       = -1;
             idx.i_block_number= -1;
@@ -2050,9 +2146,9 @@ static void LoadCues( demux_t *p_demux )
                 {
                     KaxCueTime &ctime = *(KaxCueTime*)el;
 
-                    ctime.ReadData( p_stream->p_es->I_O() );
+                    ctime.ReadData( es.I_O() );
 
-                    idx.i_time = uint64( ctime ) * p_segment->i_timescale / (mtime_t)1000;
+                    idx.i_time = uint64( ctime ) * i_timescale / (mtime_t)1000;
                 }
                 else if( MKV_IS_ID( el, KaxCueTrackPositions ) )
                 {
@@ -2063,190 +2159,187 @@ static void LoadCues( demux_t *p_demux )
                         {
                             KaxCueTrack &ctrack = *(KaxCueTrack*)el;
 
-                            ctrack.ReadData( p_stream->p_es->I_O() );
+                            ctrack.ReadData( es.I_O() );
                             idx.i_track = uint16( ctrack );
                         }
                         else if( MKV_IS_ID( el, KaxCueClusterPosition ) )
                         {
                             KaxCueClusterPosition &ccpos = *(KaxCueClusterPosition*)el;
 
-                            ccpos.ReadData( p_stream->p_es->I_O() );
-                            idx.i_position = p_segment->segment->GetGlobalPosition( uint64( ccpos ) );
+                            ccpos.ReadData( es.I_O() );
+                            idx.i_position = segment->GetGlobalPosition( uint64( ccpos ) );
                         }
                         else if( MKV_IS_ID( el, KaxCueBlockNumber ) )
                         {
                             KaxCueBlockNumber &cbnum = *(KaxCueBlockNumber*)el;
 
-                            cbnum.ReadData( p_stream->p_es->I_O() );
+                            cbnum.ReadData( es.I_O() );
                             idx.i_block_number = uint32( cbnum );
                         }
                         else
                         {
-                            msg_Dbg( p_demux, "         * Unknown (%s)", typeid(*el).name() );
+                            msg_Dbg( &sys.demuxer, "         * Unknown (%s)", typeid(*el).name() );
                         }
                     }
                     ep->Up();
                 }
                 else
                 {
-                    msg_Dbg( p_demux, "     * Unknown (%s)", typeid(*el).name() );
+                    msg_Dbg( &sys.demuxer, "     * Unknown (%s)", typeid(*el).name() );
                 }
             }
             ep->Up();
 
 #if 0
-            msg_Dbg( p_demux, " * added time="I64Fd" pos="I64Fd
+            msg_Dbg( &sys.demuxer, " * added time="I64Fd" pos="I64Fd
                      " track=%d bnum=%d", idx.i_time, idx.i_position,
                      idx.i_track, idx.i_block_number );
 #endif
 
-            p_segment->i_index++;
-            if( p_segment->i_index >= p_segment->i_index_max )
+            i_index++;
+            if( i_index >= i_index_max )
             {
-                p_segment->i_index_max += 1024;
-                p_segment->index = (mkv_index_t*)realloc( p_segment->index, sizeof( mkv_index_t ) * p_segment->i_index_max );
+                i_index_max += 1024;
+                index = (mkv_index_t*)realloc( index, sizeof( mkv_index_t ) * i_index_max );
             }
 #undef idx
         }
         else
         {
-            msg_Dbg( p_demux, " * Unknown (%s)", typeid(*el).name() );
+            msg_Dbg( &sys.demuxer, " * Unknown (%s)", typeid(*el).name() );
         }
     }
     delete ep;
     delete cues;
 
-    p_segment->b_cues = VLC_TRUE;
+    b_cues = VLC_TRUE;
 
-    msg_Dbg( p_demux, "loading cues done." );
-    p_stream->p_in->setFilePointer( i_sav_position, seek_beginning );
+    msg_Dbg( &sys.demuxer, "loading cues done." );
+    es.I_O().setFilePointer( i_sav_position, seek_beginning );
 }
 
-static void LoadTags( demux_t *p_demux )
+void matroska_segment_t::LoadTags( )
 {
-    demux_sys_t *p_sys = p_demux->p_sys;
-    matroska_stream_t  *p_stream = p_sys->Stream();
-    matroska_segment_t *p_segment = p_stream->Segment();
-    int64_t     i_sav_position = p_stream->p_in->getFilePointer();
+    int64_t     i_sav_position = es.I_O().getFilePointer();
     EbmlParser  *ep;
     EbmlElement *el, *tags;
 
-    msg_Dbg( p_demux, "loading tags" );
-    p_stream->p_in->setFilePointer( p_segment->i_tags_position, seek_beginning );
-    tags = p_stream->p_es->FindNextID( KaxTags::ClassInfos, 0xFFFFFFFFL);
+    msg_Dbg( &sys.demuxer, "loading tags" );
+    es.I_O().setFilePointer( i_tags_position, seek_beginning );
+    tags = es.FindNextID( KaxTags::ClassInfos, 0xFFFFFFFFL);
 
     if( tags == NULL )
     {
-        msg_Err( p_demux, "cannot load tags (broken seekhead or file)" );
-        p_stream->p_in->setFilePointer( i_sav_position, seek_beginning );
+        msg_Err( &sys.demuxer, "cannot load tags (broken seekhead or file)" );
+        es.I_O().setFilePointer( i_sav_position, seek_beginning );
         return;
     }
 
-    msg_Dbg( p_demux, "Tags" );
-    ep = new EbmlParser( p_stream->p_es, tags );
+    msg_Dbg( &sys.demuxer, "Tags" );
+    ep = new EbmlParser( &es, tags );
     while( ( el = ep->Get() ) != NULL )
     {
         if( MKV_IS_ID( el, KaxTag ) )
         {
-            msg_Dbg( p_demux, "+ Tag" );
+            msg_Dbg( &sys.demuxer, "+ Tag" );
             ep->Down();
             while( ( el = ep->Get() ) != NULL )
             {
                 if( MKV_IS_ID( el, KaxTagTargets ) )
                 {
-                    msg_Dbg( p_demux, "|   + Targets" );
+                    msg_Dbg( &sys.demuxer, "|   + Targets" );
                     ep->Down();
                     while( ( el = ep->Get() ) != NULL )
                     {
-                        msg_Dbg( p_demux, "|   |   + Unknown (%s)", typeid( *el ).name() );
+                        msg_Dbg( &sys.demuxer, "|   |   + Unknown (%s)", typeid( *el ).name() );
                     }
                     ep->Up();
                 }
                 else if( MKV_IS_ID( el, KaxTagGeneral ) )
                 {
-                    msg_Dbg( p_demux, "|   + General" );
+                    msg_Dbg( &sys.demuxer, "|   + General" );
                     ep->Down();
                     while( ( el = ep->Get() ) != NULL )
                     {
-                        msg_Dbg( p_demux, "|   |   + Unknown (%s)", typeid( *el ).name() );
+                        msg_Dbg( &sys.demuxer, "|   |   + Unknown (%s)", typeid( *el ).name() );
                     }
                     ep->Up();
                 }
                 else if( MKV_IS_ID( el, KaxTagGenres ) )
                 {
-                    msg_Dbg( p_demux, "|   + Genres" );
+                    msg_Dbg( &sys.demuxer, "|   + Genres" );
                     ep->Down();
                     while( ( el = ep->Get() ) != NULL )
                     {
-                        msg_Dbg( p_demux, "|   |   + Unknown (%s)", typeid( *el ).name() );
+                        msg_Dbg( &sys.demuxer, "|   |   + Unknown (%s)", typeid( *el ).name() );
                     }
                     ep->Up();
                 }
                 else if( MKV_IS_ID( el, KaxTagAudioSpecific ) )
                 {
-                    msg_Dbg( p_demux, "|   + Audio Specific" );
+                    msg_Dbg( &sys.demuxer, "|   + Audio Specific" );
                     ep->Down();
                     while( ( el = ep->Get() ) != NULL )
                     {
-                        msg_Dbg( p_demux, "|   |   + Unknown (%s)", typeid( *el ).name() );
+                        msg_Dbg( &sys.demuxer, "|   |   + Unknown (%s)", typeid( *el ).name() );
                     }
                     ep->Up();
                 }
                 else if( MKV_IS_ID( el, KaxTagImageSpecific ) )
                 {
-                    msg_Dbg( p_demux, "|   + Images Specific" );
+                    msg_Dbg( &sys.demuxer, "|   + Images Specific" );
                     ep->Down();
                     while( ( el = ep->Get() ) != NULL )
                     {
-                        msg_Dbg( p_demux, "|   |   + Unknown (%s)", typeid( *el ).name() );
+                        msg_Dbg( &sys.demuxer, "|   |   + Unknown (%s)", typeid( *el ).name() );
                     }
                     ep->Up();
                 }
                 else if( MKV_IS_ID( el, KaxTagMultiComment ) )
                 {
-                    msg_Dbg( p_demux, "|   + Multi Comment" );
+                    msg_Dbg( &sys.demuxer, "|   + Multi Comment" );
                 }
                 else if( MKV_IS_ID( el, KaxTagMultiCommercial ) )
                 {
-                    msg_Dbg( p_demux, "|   + Multi Commercial" );
+                    msg_Dbg( &sys.demuxer, "|   + Multi Commercial" );
                 }
                 else if( MKV_IS_ID( el, KaxTagMultiDate ) )
                 {
-                    msg_Dbg( p_demux, "|   + Multi Date" );
+                    msg_Dbg( &sys.demuxer, "|   + Multi Date" );
                 }
                 else if( MKV_IS_ID( el, KaxTagMultiEntity ) )
                 {
-                    msg_Dbg( p_demux, "|   + Multi Entity" );
+                    msg_Dbg( &sys.demuxer, "|   + Multi Entity" );
                 }
                 else if( MKV_IS_ID( el, KaxTagMultiIdentifier ) )
                 {
-                    msg_Dbg( p_demux, "|   + Multi Identifier" );
+                    msg_Dbg( &sys.demuxer, "|   + Multi Identifier" );
                 }
                 else if( MKV_IS_ID( el, KaxTagMultiLegal ) )
                 {
-                    msg_Dbg( p_demux, "|   + Multi Legal" );
+                    msg_Dbg( &sys.demuxer, "|   + Multi Legal" );
                 }
                 else if( MKV_IS_ID( el, KaxTagMultiTitle ) )
                 {
-                    msg_Dbg( p_demux, "|   + Multi Title" );
+                    msg_Dbg( &sys.demuxer, "|   + Multi Title" );
                 }
                 else
                 {
-                    msg_Dbg( p_demux, "|   + Unknown (%s)", typeid( *el ).name() );
+                    msg_Dbg( &sys.demuxer, "|   + Unknown (%s)", typeid( *el ).name() );
                 }
             }
             ep->Up();
         }
         else
         {
-            msg_Dbg( p_demux, "+ Unknown (%s)", typeid( *el ).name() );
+            msg_Dbg( &sys.demuxer, "+ Unknown (%s)", typeid( *el ).name() );
         }
     }
     delete ep;
     delete tags;
 
-    msg_Dbg( p_demux, "loading tags done." );
-    p_stream->p_in->setFilePointer( i_sav_position, seek_beginning );
+    msg_Dbg( &sys.demuxer, "loading tags done." );
+    es.I_O().setFilePointer( i_sav_position, seek_beginning );
 }
 
 /*****************************************************************************
@@ -3021,7 +3114,7 @@ void matroska_segment_t::ParseChapters( EbmlElement *chapters )
                 }
                 else if( MKV_IS_ID( l, KaxEditionFlagOrdered ) )
                 {
-                    edition.b_ordered = uint8(*static_cast<KaxEditionFlagOrdered *>( l )) != 0;
+                    edition.b_ordered = config_GetInt( &sys.demuxer, "mkv-use-ordered-chapters" ) ? (uint8(*static_cast<KaxEditionFlagOrdered *>( l )) != 0) : 0;
                 }
                 else if( MKV_IS_ID( l, KaxEditionFlagDefault ) )
                 {
@@ -3060,75 +3153,72 @@ void matroska_segment_t::ParseChapters( EbmlElement *chapters )
 /*****************************************************************************
  * InformationCreate:
  *****************************************************************************/
-static void InformationCreate( demux_t *p_demux )
+void matroska_segment_t::InformationCreate( )
 {
-    demux_sys_t *p_sys = p_demux->p_sys;
-    matroska_stream_t  *p_stream = p_sys->Stream();
-    matroska_segment_t *p_segment = p_stream->Segment();
     size_t      i_track;
 
-    p_sys->meta = vlc_meta_New();
+    sys.meta = vlc_meta_New();
 
-    if( p_segment->psz_title )
+    if( psz_title )
     {
-        vlc_meta_Add( p_sys->meta, VLC_META_TITLE, p_segment->psz_title );
+        vlc_meta_Add( sys.meta, VLC_META_TITLE, psz_title );
     }
-    if( p_segment->psz_date_utc )
+    if( psz_date_utc )
     {
-        vlc_meta_Add( p_sys->meta, VLC_META_DATE, p_segment->psz_date_utc );
+        vlc_meta_Add( sys.meta, VLC_META_DATE, psz_date_utc );
     }
-    if( p_segment->psz_segment_filename )
+    if( psz_segment_filename )
     {
-        vlc_meta_Add( p_sys->meta, _("Segment filename"), p_segment->psz_segment_filename );
+        vlc_meta_Add( sys.meta, _("Segment filename"), psz_segment_filename );
     }
-    if( p_segment->psz_muxing_application )
+    if( psz_muxing_application )
     {
-        vlc_meta_Add( p_sys->meta, _("Muxing application"), p_segment->psz_muxing_application );
+        vlc_meta_Add( sys.meta, _("Muxing application"), psz_muxing_application );
     }
-    if( p_segment->psz_writing_application )
+    if( psz_writing_application )
     {
-        vlc_meta_Add( p_sys->meta, _("Writing application"), p_segment->psz_writing_application );
+        vlc_meta_Add( sys.meta, _("Writing application"), psz_writing_application );
     }
 
-    for( i_track = 0; i_track < p_segment->tracks.size(); i_track++ )
+    for( i_track = 0; i_track < tracks.size(); i_track++ )
     {
-        mkv_track_t *tk = p_segment->tracks[i_track];
+        mkv_track_t *tk = tracks[i_track];
         vlc_meta_t *mtk = vlc_meta_New();
 
-        p_sys->meta->track = (vlc_meta_t**)realloc( p_sys->meta->track,
-                                                    sizeof( vlc_meta_t * ) * ( p_sys->meta->i_track + 1 ) );
-        p_sys->meta->track[p_sys->meta->i_track++] = mtk;
+        sys.meta->track = (vlc_meta_t**)realloc( sys.meta->track,
+                                                    sizeof( vlc_meta_t * ) * ( sys.meta->i_track + 1 ) );
+        sys.meta->track[sys.meta->i_track++] = mtk;
 
         if( tk->fmt.psz_description )
         {
-            vlc_meta_Add( p_sys->meta, VLC_META_DESCRIPTION, tk->fmt.psz_description );
+            vlc_meta_Add( sys.meta, VLC_META_DESCRIPTION, tk->fmt.psz_description );
         }
         if( tk->psz_codec_name )
         {
-            vlc_meta_Add( p_sys->meta, VLC_META_CODEC_NAME, tk->psz_codec_name );
+            vlc_meta_Add( sys.meta, VLC_META_CODEC_NAME, tk->psz_codec_name );
         }
         if( tk->psz_codec_settings )
         {
-            vlc_meta_Add( p_sys->meta, VLC_META_SETTING, tk->psz_codec_settings );
+            vlc_meta_Add( sys.meta, VLC_META_SETTING, tk->psz_codec_settings );
         }
         if( tk->psz_codec_info_url )
         {
-            vlc_meta_Add( p_sys->meta, VLC_META_CODEC_DESCRIPTION, tk->psz_codec_info_url );
+            vlc_meta_Add( sys.meta, VLC_META_CODEC_DESCRIPTION, tk->psz_codec_info_url );
         }
         if( tk->psz_codec_download_url )
         {
-            vlc_meta_Add( p_sys->meta, VLC_META_URL, tk->psz_codec_download_url );
+            vlc_meta_Add( sys.meta, VLC_META_URL, tk->psz_codec_download_url );
         }
     }
 
-    if( p_segment->i_tags_position >= 0 )
+    if( i_tags_position >= 0 )
     {
         vlc_bool_t b_seekable;
 
-        stream_Control( p_demux->s, STREAM_CAN_FASTSEEK, &b_seekable );
+        stream_Control( sys.demuxer.s, STREAM_CAN_FASTSEEK, &b_seekable );
         if( b_seekable )
         {
-            LoadTags( p_demux );
+            LoadTags( );
         }
     }
 }
@@ -3296,6 +3386,7 @@ const chapter_item_t *chapter_edition_t::FindTimecode( mtime_t i_user_timecode )
 
 void demux_sys_t::PreloadFamily( )
 {
+/* family handling disabled  for the moment
     matroska_stream_t *p_stream = Stream();
     if ( p_stream )
     {
@@ -3308,6 +3399,7 @@ void demux_sys_t::PreloadFamily( )
             }
         }
     }
+*/
 }
 
 void matroska_stream_t::PreloadFamily( const matroska_segment_t & of_segment )
@@ -3336,48 +3428,47 @@ bool matroska_segment_t::PreloadFamily( const matroska_segment_t & of_segment )
 }
 
 // preload all the linked segments for all preloaded segments
-void demux_sys_t::PreloadLinked( )
+void demux_sys_t::PreloadLinked( matroska_segment_t *p_segment )
 {
-    size_t i_prealoaded;
+    size_t i_preloaded, i;
+
+    delete p_current_segment;
+    p_current_segment = new virtual_segment_t( p_segment );
+
+    // fill our current virtual segment with all hard linked segments
     do {
-        i_prealoaded = 0;
-        for (size_t i=0; i<streams.size(); i++)
+        i_preloaded = 0;
+        for ( i=0; i< opened_segments.size(); i++ )
         {
-            i_prealoaded += streams[i]->PreloadLinked( *this );
+            i_preloaded += p_current_segment->AddSegment( opened_segments[i] );
         }
-    } while ( i_prealoaded ); // worst case: will stop when all segments are preloaded
+    } while ( i_preloaded ); // worst case: will stop when all segments are found as linked
+
+    p_current_segment->Sort( );
+
+    p_current_segment->PreloadLinked( );
 }
 
-size_t matroska_stream_t::PreloadLinked( const demux_sys_t & of_sys )
+void demux_sys_t::PreparePlayback( )
 {
-    size_t i_result = 0;
-    for (size_t i=0; i<segments.size(); i++)
-    {
-        i_result += segments[i]->PreloadLinked( of_sys );
-    }
-    return i_result;
+    f_duration = p_current_segment->Duration();
+    p_current_segment->LoadCues();
 }
 
-size_t matroska_segment_t::PreloadLinked( const demux_sys_t & of_sys )
+bool matroska_segment_t::CompareSegmentUIDs( const matroska_segment_t * p_item_a, const matroska_segment_t * p_item_b )
 {
-    size_t i_result = 0;
-    if ( prev_segment_uid.GetBuffer() )
-    {
-        matroska_segment_t *p_segment = of_sys.FindSegment( prev_segment_uid );
-        if ( p_segment )
-        {
-            i_result += p_segment->Preload( ) ? 1 : 0;
-        }
-    }
-    if ( next_segment_uid.GetBuffer() )
-    {
-        matroska_segment_t *p_segment = of_sys.FindSegment( next_segment_uid );
-        if ( p_segment )
-        {
-            i_result += p_segment->Preload( ) ? 1 : 0;
-        }
-    }
-    return i_result;
+    EbmlBinary * p_itema = (EbmlBinary *)(&p_item_a->segment_uid);
+    if ( *p_itema == p_item_b->prev_segment_uid )
+        return true;
+
+    p_itema = (EbmlBinary *)(&p_item_a->next_segment_uid);
+    if ( *p_itema == p_item_b->segment_uid )
+        return true;
+
+    if ( *p_itema == p_item_b->prev_segment_uid )
+        return true;
+
+    return false;
 }
 
 bool matroska_segment_t::Preload( )
@@ -3413,6 +3504,8 @@ bool matroska_segment_t::Preload( )
 
             cluster = (KaxCluster*)el;
 
+            i_start_pos = cluster->GetElementPosition();
+
             ep->Down();
             /* stop parsing the stream */
             break;
@@ -3441,22 +3534,91 @@ bool matroska_segment_t::Preload( )
     return true;
 }
 
-matroska_segment_t *demux_sys_t::FindSegment( EbmlBinary & uid ) const
+matroska_segment_t *demux_sys_t::FindSegment( const EbmlBinary & uid ) const
 {
-    matroska_segment_t *p_segment = NULL;
-    for (size_t i=0; i<streams.size() && p_segment == NULL; i++)
+    for (size_t i=0; i<opened_segments.size(); i++)
     {
-        p_segment = streams[i]->FindSegment( uid );
+        if ( opened_segments[i]->segment_uid == uid )
+            return opened_segments[i];
     }
-    return p_segment;
+    return NULL;
 }
 
-matroska_segment_t *matroska_stream_t::FindSegment( EbmlBinary & uid ) const
+void virtual_segment_t::Sort()
 {
-    for (size_t i=0; i<segments.size(); i++)
+    // keep the current segment index
+    matroska_segment_t *p_segment = linked_segments[i_current_segment];
+
+    std::sort( linked_segments.begin(), linked_segments.end(), matroska_segment_t::CompareSegmentUIDs );
+
+    for ( i_current_segment=0; i_current_segment<linked_segments.size(); i_current_segment++)
+        if ( linked_segments[i_current_segment] == p_segment )
+            break;
+}
+
+size_t virtual_segment_t::AddSegment( matroska_segment_t *p_segment )
+{
+    size_t i;
+    // check if it's not already in here
+    for ( i=0; i<linked_segments.size(); i++ )
     {
-        if ( segments[i]->segment_uid == uid )
-            return segments[i];
+        if ( p_segment->segment_uid == linked_segments[i]->segment_uid )
+            return 0;
     }
-    return NULL;
+
+    // find possible mates
+    for ( i=0; i<linked_uids.size(); i++ )
+    {
+        if (   p_segment->segment_uid == linked_uids[i] 
+            || p_segment->prev_segment_uid == linked_uids[i] 
+            || p_segment->next_segment_uid == linked_uids[i] )
+        {
+            linked_segments.push_back( p_segment );
+
+            AppendUID( p_segment->prev_segment_uid );
+            AppendUID( p_segment->next_segment_uid );
+
+            return 1;
+        }
+    }
+    return 0;
+}
+
+void virtual_segment_t::PreloadLinked( )
+{
+    for ( size_t i=0; i<linked_segments.size(); i++ )
+    {
+        linked_segments[i]->Preload( );
+    }
+}
+
+float virtual_segment_t::Duration() const
+{
+    float f_duration = 0.0;
+    for ( size_t i=0; i<linked_segments.size(); i++ )
+    {
+        f_duration += linked_segments[i]->f_duration;
+    }
+    return f_duration;
+}
+
+void virtual_segment_t::LoadCues( )
+{
+    for ( size_t i=0; i<linked_segments.size(); i++ )
+    {
+        linked_segments[i]->LoadCues();
+    }
+}
+
+void virtual_segment_t::AppendUID( const EbmlBinary & UID )
+{
+    if ( UID.GetBuffer() == NULL )
+        return;
+
+    for (size_t i=0; i<linked_uids.size(); i++)
+    {
+        if ( UID == linked_uids[i] )
+            return;
+    }
+    linked_uids.push_back( *(KaxSegmentUID*)(&UID) );
 }