]> git.sesse.net Git - vlc/blobdiff - modules/demux/mkv.cpp
* modules/demux/*: removed useless probing messages.
[vlc] / modules / demux / mkv.cpp
index 9dcd168cc7806dc435feeb80bfb6133c3e525746..0665a325928f2bf56afe2b3d7f0436a082dcaf75 100644 (file)
@@ -5,6 +5,7 @@
  * $Id$
  *
  * Authors: Laurent Aimar <fenrir@via.ecp.fr>
+ *          Steve Lhomme <steve.lhomme@free.fr>
  *
  * This program is free software; you can redistribute it and/or modify
  * it under the terms of the GNU General Public License as published by
 #include <iostream>
 #include <cassert>
 #include <typeinfo>
+#include <string>
+#include <vector>
+#include <algorithm>
+
+#ifdef HAVE_DIRENT_H
+#   include <dirent.h>
+#endif
 
 /* libebml and matroska */
 #include "ebml/EbmlHead.h"
 #include "ebml/EbmlSubHead.h"
 #include "ebml/EbmlStream.h"
 #include "ebml/EbmlContexts.h"
-#include "ebml/EbmlVersion.h"
 #include "ebml/EbmlVoid.h"
+#include "ebml/StdIOCallback.h"
 
-#include "matroska/FileKax.h"
 #include "matroska/KaxAttachments.h"
 #include "matroska/KaxBlock.h"
 #include "matroska/KaxBlockData.h"
@@ -75,6 +82,9 @@
 
 #include "ebml/StdIOCallback.h"
 
+extern "C" {
+   #include "mp4/libmp4.h"
+}
 #ifdef HAVE_ZLIB_H
 #   include <zlib.h>
 #endif
 #define MATROSKA_COMPRESSION_NONE 0
 #define MATROSKA_COMPRESSION_ZLIB 1
 
+/**
+ * What's between a directory and a filename?
+ */
+#if defined( WIN32 )
+    #define DIRECTORY_SEPARATOR '\\'
+#else
+    #define DIRECTORY_SEPARATOR '/'
+#endif
+
 using namespace LIBMATROSKA_NAMESPACE;
 using namespace std;
 
@@ -92,9 +111,12 @@ static int  Open ( vlc_object_t * );
 static void Close( vlc_object_t * );
 
 vlc_module_begin();
+    set_shortname( _("Matroska") );
     set_description( _("Matroska stream demuxer" ) );
     set_capability( "demux2", 50 );
     set_callbacks( Open, Close );
+    set_category( CAT_INPUT );
+    set_subcategory( SUBCAT_INPUT_DEMUX );
 
     add_bool( "mkv-seek-percent", 1, NULL,
             N_("Seek based on percent not time"),
@@ -107,10 +129,6 @@ vlc_module_end();
 /*****************************************************************************
  * Local prototypes
  *****************************************************************************/
-static int  Demux  ( demux_t * );
-static int  Control( demux_t *, int, va_list );
-static void Seek   ( demux_t *, mtime_t i_date, int i_percent );
-
 #ifdef HAVE_ZLIB_H
 block_t *block_zlib_decompress( vlc_object_t *p_this, block_t *p_in_block ) {
     int result, dstsize, n;
@@ -161,6 +179,29 @@ block_t *block_zlib_decompress( vlc_object_t *p_this, block_t *p_in_block ) {
 }
 #endif
 
+/**
+ * Helper function to print the mkv parse tree
+ */
+static void MkvTree( demux_t *p_this, int i_level, char *psz_format, ... )
+{
+    va_list args;
+    if( i_level > 9 )
+    {
+        msg_Err( p_this, "too deep tree" );
+        return;
+    }
+    va_start( args, psz_format );
+    static char *psz_foo = "|   |   |   |   |   |   |   |   |   |";
+    char *psz_foo2 = (char*)malloc( ( i_level * 4 + 3 + strlen( psz_format ) ) * sizeof(char) );
+    strncpy( psz_foo2, psz_foo, 4 * i_level );
+    psz_foo2[ 4 * i_level ] = '+';
+    psz_foo2[ 4 * i_level + 1 ] = ' ';
+    strcpy( &psz_foo2[ 4 * i_level + 2 ], psz_format );
+    __msg_GenericVa( VLC_OBJECT(p_this), VLC_MSG_DBG, "mkv", psz_foo2, args );
+    free( psz_foo2 );
+    va_end( args );
+}
+    
 /*****************************************************************************
  * Stream managment
  *****************************************************************************/
@@ -254,7 +295,7 @@ typedef struct
     char         *psz_codec_download_url;
     
     /* encryption/compression */
-    vlc_bool_t   b_compression_zlib;
+    int           i_compression_type;
 
 } mkv_track_t;
 
@@ -269,8 +310,92 @@ typedef struct
     vlc_bool_t b_key;
 } mkv_index_t;
 
-struct demux_sys_t
+class chapter_item_t
 {
+public:
+    chapter_item_t()
+    :i_start_time(0)
+    ,i_end_time(-1)
+    ,i_user_start_time(-1)
+    ,i_user_end_time(-1)
+    ,i_seekpoint_num(-1)
+    ,b_display_seekpoint(true)
+    ,psz_parent(NULL)
+    {}
+    
+    int64_t RefreshChapters( bool b_ordered, int64_t i_prev_user_time, input_title_t & title );
+    const chapter_item_t * FindTimecode( mtime_t i_timecode ) const;
+    
+    int64_t                     i_start_time, i_end_time;
+    int64_t                     i_user_start_time, i_user_end_time; /* the time in the stream when an edition is ordered */
+    std::vector<chapter_item_t> sub_chapters;
+    int                         i_seekpoint_num;
+    int64_t                     i_uid;
+    bool                        b_display_seekpoint;
+    std::string                 psz_name;
+    chapter_item_t              *psz_parent;
+    
+    bool operator<( const chapter_item_t & item ) const
+    {
+        return ( i_user_start_time < item.i_user_start_time || (i_user_start_time == item.i_user_start_time && i_user_end_time < item.i_user_end_time) );
+    }
+
+protected:
+    bool Enter();
+    bool Leave();
+};
+
+class chapter_edition_t 
+{
+public:
+    chapter_edition_t()
+    :i_uid(-1)
+    ,b_ordered(false)
+    {}
+    
+    void RefreshChapters( input_title_t & title );
+    double Duration() const;
+    const chapter_item_t * FindTimecode( mtime_t i_timecode ) const;
+    
+    std::vector<chapter_item_t> chapters;
+    int64_t                     i_uid;
+    bool                        b_ordered;
+};
+
+class demux_sys_t
+{
+public:
+    demux_sys_t()
+        :in(NULL)
+        ,es(NULL)
+        ,ep(NULL)
+        ,i_timescale(0)
+        ,f_duration(0.0)
+        ,i_track(0)
+        ,track(NULL)
+        ,i_cues_position(0)
+        ,i_chapters_position(0)
+        ,i_tags_position(0)
+        ,segment(NULL)
+        ,cluster(NULL)
+        ,i_pts(0)
+        ,i_start_pts(0)
+        ,i_chapter_time(0)
+        ,b_cues(false)
+        ,i_index(0)
+        ,i_index_max(0)
+        ,index(NULL)
+        ,psz_muxing_application(NULL)
+        ,psz_writing_application(NULL)
+        ,psz_segment_filename(NULL)
+        ,psz_title(NULL)
+        ,psz_date_utc(NULL)
+        ,meta(NULL)
+        ,title(NULL)
+        ,i_current_edition(0)
+        ,psz_current_chapter(NULL)
+    {}
+
     vlc_stream_io_callback  *in;
     EbmlStream              *es;
     EbmlParser              *ep;
@@ -293,8 +418,11 @@ struct demux_sys_t
     /* current data */
     KaxSegment              *segment;
     KaxCluster              *cluster;
+    KaxSegmentUID           segment_uid;
 
     mtime_t                 i_pts;
+    mtime_t                 i_start_pts;
+    mtime_t                 i_chapter_time;
 
     vlc_bool_t              b_cues;
     int                     i_index;
@@ -311,8 +439,19 @@ struct demux_sys_t
     vlc_meta_t              *meta;
 
     input_title_t           *title;
+
+    std::vector<KaxSegmentFamily> families;
+    std::vector<KaxSegment*>      family_members;
+    
+    std::vector<chapter_edition_t> editions;
+    int                            i_current_edition;
+    const chapter_item_t           *psz_current_chapter;
 };
 
+static int  Demux  ( demux_t * );
+static int  Control( demux_t *, int, va_list );
+static void Seek   ( demux_t *, mtime_t i_date, double f_percent, const chapter_item_t *psz_chapter );
+
 #define MKVD_TIMECODESCALE 1000000
 
 #define MKV_IS_ID( el, C ) ( EbmlId( (*el) ) == C::ClassInfos.GlobalId )
@@ -335,34 +474,26 @@ static int Open( vlc_object_t * p_this )
     demux_t     *p_demux = (demux_t*)p_this;
     demux_sys_t *p_sys;
     uint8_t     *p_peek;
+    std::string  s_path, s_filename;
+    int          i_upper_lvl;
+    size_t       i;
 
     int          i_track;
 
     EbmlElement *el = NULL, *el1 = NULL;
 
     /* peek the begining */
-    if( stream_Peek( p_demux->s, &p_peek, 4 ) < 4 )
-    {
-        msg_Warn( p_demux, "cannot peek" );
-        return VLC_EGENERIC;
-    }
+    if( stream_Peek( p_demux->s, &p_peek, 4 ) < 4 ) return VLC_EGENERIC;
 
     /* is a valid file */
     if( p_peek[0] != 0x1a || p_peek[1] != 0x45 ||
-        p_peek[2] != 0xdf || p_peek[3] != 0xa3 )
-    {
-        msg_Warn( p_demux, "matroska module discarded "
-                           "(invalid header 0x%.2x%.2x%.2x%.2x)",
-                           p_peek[0], p_peek[1], p_peek[2], p_peek[3] );
-        return VLC_EGENERIC;
-    }
+        p_peek[2] != 0xdf || p_peek[3] != 0xa3 ) return VLC_EGENERIC;
 
     /* Set the demux function */
     p_demux->pf_demux   = Demux;
     p_demux->pf_control = Control;
-    p_demux->p_sys      = p_sys = (demux_sys_t*)malloc(sizeof( demux_sys_t ));
+    p_demux->p_sys      = p_sys = new demux_sys_t;
 
-    memset( p_sys, 0, sizeof( demux_sys_t ) );
     p_sys->in = new vlc_stream_io_callback( p_demux->s );
     p_sys->es = new EbmlStream( *p_sys->in );
     p_sys->f_duration   = -1;
@@ -392,7 +523,7 @@ static int Open( vlc_object_t * p_this )
     {
         msg_Err( p_demux, "failed to create EbmlStream" );
         delete p_sys->in;
-        free( p_sys );
+        delete p_sys;
         return VLC_EGENERIC;
     }
     /* Find the EbmlHead element */
@@ -414,7 +545,7 @@ static int Open( vlc_object_t * p_this )
         msg_Err( p_demux, "cannot find KaxSegment" );
         goto error;
     }
-    msg_Dbg( p_demux, "+ Segment" );
+    MkvTree( p_demux, 0, "Segment" );
     p_sys->segment = (KaxSegment*)el;
     p_sys->cluster = NULL;
 
@@ -467,6 +598,147 @@ static int Open( vlc_object_t * p_this )
         }
     }
 
+    /* get the files from the same dir from the same family (based on p_demux->psz_path) */
+    /* _todo_ handle multi-segment files */
+    if (p_demux->psz_path[0] != '\0' && (!strcmp(p_demux->psz_access, "") || !strcmp(p_demux->psz_access, "")))
+    {
+        // assume it's a regular file
+        // get the directory path
+        s_path = p_demux->psz_path;
+        if (s_path.at(s_path.length() - 1) == DIRECTORY_SEPARATOR)
+        {
+            s_path = s_path.substr(0,s_path.length()-1);
+        }
+        else
+        {
+            if (s_path.find_last_of(DIRECTORY_SEPARATOR) > 0) 
+            {
+                s_path = s_path.substr(0,s_path.find_last_of(DIRECTORY_SEPARATOR));
+            }
+        }
+
+        struct dirent *p_file_item;
+        DIR *p_src_dir = opendir(s_path.c_str());
+
+        if (p_src_dir != NULL)
+        {
+            while ((p_file_item = (dirent *) readdir(p_src_dir)))
+            {
+                if (strlen(p_file_item->d_name) > 4)
+                {
+                    s_filename = s_path + DIRECTORY_SEPARATOR + p_file_item->d_name;
+
+                    if (!s_filename.compare(p_demux->psz_path))
+                        continue;
+
+#if defined(__GNUC__) && (__GNUC__ < 3)
+                    if (!s_filename.compare("mkv", s_filename.length() - 3, 3) || 
+                        !s_filename.compare("mka", s_filename.length() - 3, 3))
+#else
+                    if (!s_filename.compare(s_filename.length() - 3, 3, "mkv") || 
+                        !s_filename.compare(s_filename.length() - 3, 3, "mka"))
+#endif
+                    {
+                        // test wether this file belongs to the our family
+                        bool b_keep_file_opened = false;
+                        StdIOCallback *p_file_io = new StdIOCallback(s_filename.c_str(), MODE_READ);
+                        EbmlStream *p_stream = new EbmlStream(*p_file_io);
+                        EbmlElement *p_l0, *p_l1, *p_l2;
+
+                        // verify the EBML Header
+                        p_l0 = p_stream->FindNextID(EbmlHead::ClassInfos, 0xFFFFFFFFL);
+                        if (p_l0 == NULL)
+                        {
+                            delete p_stream;
+                            delete p_file_io;
+                            continue;
+                        }
+
+                        p_l0->SkipData(*p_stream, EbmlHead_Context);
+                        delete p_l0;
+
+                        // find all segments in this file
+                        p_l0 = p_stream->FindNextID(KaxSegment::ClassInfos, 0xFFFFFFFFL);
+                        if (p_l0 == NULL)
+                        {
+                            delete p_stream;
+                            delete p_file_io;
+                            continue;
+                        }
+
+                        i_upper_lvl = 0;
+
+                        while (p_l0 != 0)
+                        {
+                            if (EbmlId(*p_l0) == KaxSegment::ClassInfos.GlobalId)
+                            {
+                                EbmlParser  *ep;
+                                KaxSegmentUID *p_uid = NULL;
+
+                                ep = new EbmlParser(p_stream, p_l0);
+                                bool b_this_segment_matches = false;
+                                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_stream, KaxInfo::ClassInfos.Context, i_upper_lvl, p_l2, true);
+                                        for( i = 0; i < p_info->ListSize() && !b_this_segment_matches; i++ )
+                                        {
+                                            EbmlElement *l = (*p_info)[i];
+
+                                            if( MKV_IS_ID( l, KaxSegmentUID ) )
+                                            {
+                                                p_uid = static_cast<KaxSegmentUID*>(l);
+                                                if (p_sys->segment_uid == *p_uid)
+                                                    break;
+                                            }
+                                            else if( MKV_IS_ID( l, KaxSegmentFamily ) )
+                                            {
+                                                KaxSegmentFamily *p_fam = static_cast<KaxSegmentFamily*>(l);
+                                                std::vector<KaxSegmentFamily>::iterator iter;
+                                                for( iter = p_sys->families.begin();
+                                                     iter != p_sys->families.end();
+                                                     iter++ )
+                                                {
+                                                    if( *iter == *p_fam )
+                                                    {
+                                                        b_this_segment_matches = true;
+                                                        break;
+                                                    }
+                                                }
+                                            }
+                                        }
+                                        break;
+                                    }
+                                }
+
+                                if (b_this_segment_matches)
+                                {
+                                    b_keep_file_opened = true;
+                                }
+                            }
+
+                            p_l0->SkipData(*p_stream, EbmlHead_Context);
+                            delete p_l0;
+                            p_l0 = p_stream->FindNextID(KaxSegment::ClassInfos, 0xFFFFFFFFL);
+                        }
+
+                        if (!b_keep_file_opened)
+                        {
+                            delete p_stream;
+                            delete p_file_io;
+                        }
+                    }
+                }
+            }
+            closedir( p_src_dir );
+        }
+    }
+
+
     if( p_sys->cluster == NULL )
     {
         msg_Err( p_demux, "cannot find any cluster, damaged file ?" );
@@ -540,11 +812,36 @@ static int Open( vlc_object_t * p_this )
             {
                 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(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 ) )
@@ -689,6 +986,18 @@ static int Open( vlc_object_t * p_this )
             }
             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' );
@@ -725,6 +1034,12 @@ static int Open( vlc_object_t * p_this )
                 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 );
@@ -747,7 +1062,7 @@ static int Open( vlc_object_t * p_this )
 error:
     delete p_sys->es;
     delete p_sys->in;
-    free( p_sys );
+    delete p_sys;
     return VLC_EGENERIC;
 }
 
@@ -793,8 +1108,7 @@ static void Close( vlc_object_t *p_this )
     delete p_sys->ep;
     delete p_sys->es;
     delete p_sys->in;
-
-    free( p_sys );
+    delete p_sys;
 }
 
 /*****************************************************************************
@@ -805,6 +1119,8 @@ static int Control( demux_t *p_demux, int i_query, va_list args )
     demux_sys_t *p_sys = p_demux->p_sys;
     int64_t     *pi64;
     double      *pf, f;
+    int         i_skp;
+    mtime_t     *i_sk_time;
 
     vlc_meta_t **pp_meta;
 
@@ -826,28 +1142,24 @@ static int Control( demux_t *p_demux, int i_query, va_list args )
 
         case DEMUX_GET_POSITION:
             pf = (double*)va_arg( args, double * );
-            *pf = (double)p_sys->in->getFilePointer() / (double)stream_Size( p_demux->s );
+/*            if (p_sys->i_pts < p_sys->i_start_pts)
+                *pf = (double)p_sys->i_start_pts / (1000.0 * p_sys->f_duration);
+            else*/
+                *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, (int)(100.0 * f) );
+            Seek( p_demux, -1, f, NULL );
             return VLC_SUCCESS;
 
         case DEMUX_GET_TIME:
             pi64 = (int64_t*)va_arg( args, int64_t * );
-            if( p_sys->f_duration > 0.0 )
-            {
-                mtime_t i_duration = (mtime_t)( p_sys->f_duration / 1000 );
-
-                /* FIXME */
-                *pi64 = (mtime_t)1000000 *
-                        (mtime_t)i_duration*
-                        (mtime_t)p_sys->in->getFilePointer() /
-                        (mtime_t)stream_Size( p_demux->s );
-                return VLC_SUCCESS;
-            }
-            return VLC_EGENERIC;
+/*            if (p_sys->i_pts < p_sys->i_start_pts)
+                *pi64 = p_sys->i_start_pts;
+            else*/
+                *pi64 = p_sys->i_pts;
+            return VLC_SUCCESS;
 
         case DEMUX_GET_TITLE_INFO:
             if( p_sys->title && p_sys->title->i_seekpoint > 0 )
@@ -865,6 +1177,7 @@ static int Control( demux_t *p_demux, int i_query, va_list args )
             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;
@@ -873,15 +1186,26 @@ static int Control( demux_t *p_demux, int i_query, va_list args )
 
         case DEMUX_SET_SEEKPOINT:
             /* FIXME do a better implementation */
-            if( p_sys->title && p_sys->title->i_seekpoint > 0 )
-            {
-                int i_skp = (int)va_arg( args, int );
+            i_skp = (int)va_arg( args, int );
 
-                Seek( p_demux, (int64_t)p_sys->title->seekpoint[i_skp]->i_time_offset, -1);
+            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_GET_SEEKPOINT_TIME:
+            i_skp = (int)va_arg( args, int );
+            i_sk_time = (mtime_t *)va_arg( args, mtime_t * );
+            if( p_sys->title && i_skp < p_sys->title->i_seekpoint)
+            {
+                *i_sk_time = p_sys->title->seekpoint[i_skp]->i_time_offset;
+                return VLC_SUCCESS;
+            }
+            return VLC_EGENERIC;
 
         case DEMUX_SET_TIME:
         case DEMUX_GET_FPS:
@@ -1048,6 +1372,15 @@ static void BlockDecode( demux_t *p_demux, KaxBlock *block, mtime_t i_pts,
         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 )
@@ -1074,19 +1407,24 @@ static void BlockDecode( demux_t *p_demux, KaxBlock *block, mtime_t i_pts,
         DataBuffer &data = block->GetBuffer(i);
 
         p_block = MemToBlock( p_demux, data.Buffer(), data.Size() );
+
+        if( p_block == NULL )
+        {
+            break;
+        }
+
 #if defined(HAVE_ZLIB_H)
-        if( p_block != NULL && tk.b_compression_zlib )
+        if( tk.i_compression_type )
         {
             p_block = block_zlib_decompress( VLC_OBJECT(p_demux), p_block );
         }
 #endif
-        if( p_block == NULL )
-        {
-            break;
-        }
 
+        // 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;
@@ -1106,101 +1444,171 @@ static void BlockDecode( demux_t *p_demux, KaxBlock *block, mtime_t i_pts,
 #undef tk
 }
 
-static void Seek( demux_t *p_demux, mtime_t i_date, int i_percent)
+static void UpdateCurrentToChapter( demux_t & demux )
+{
+    demux_sys_t & sys = *demux.p_sys;
+    const chapter_item_t *psz_curr_chapter;
+
+    /* update current chapter/seekpoint */
+    if ( sys.editions.size())
+    {
+        /* 1st, we need to know in which chapter we are */
+        psz_curr_chapter = sys.editions[sys.i_current_edition].FindTimecode( sys.i_pts );
+
+        /* we have moved to a new chapter */
+        if (sys.psz_current_chapter != NULL && psz_curr_chapter != NULL && sys.psz_current_chapter != psz_curr_chapter)
+        {
+            if (sys.psz_current_chapter->i_seekpoint_num != psz_curr_chapter->i_seekpoint_num && psz_curr_chapter->i_seekpoint_num > 0)
+            {
+                demux.info.i_update |= INPUT_UPDATE_SEEKPOINT;
+                demux.info.i_seekpoint = psz_curr_chapter->i_seekpoint_num - 1;
+            }
+
+            if (sys.editions[sys.i_current_edition].b_ordered )
+            {
+                /* TODO check if we need to silently seek to a new location in the stream (switch to another chapter) */
+                if (sys.psz_current_chapter->i_end_time != psz_curr_chapter->i_start_time)
+                    Seek(&demux, sys.i_pts, -1, psz_curr_chapter);
+                /* count the last duration time found for each track in a table (-1 not found, -2 silent) */
+                /* only seek after each duration >= end timecode of the current chapter */
+            }
+
+//            sys.i_user_time = psz_curr_chapter->i_user_start_time - psz_curr_chapter->i_start_time;
+//            sys.i_start_pts = psz_curr_chapter->i_user_start_time;
+        }
+        sys.psz_current_chapter = psz_curr_chapter;
+    }
+}
+
+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;
+    mtime_t i_time_offset = 0;
 
     KaxBlock    *block;
     int64_t     i_block_duration;
     int64_t     i_block_ref1;
     int64_t     i_block_ref2;
 
-    int         i_index;
+    int         i_index = 0;
     int         i_track_skipping;
     int         i_track;
 
-    msg_Dbg( p_demux, "seek request to "I64Fd" (%d%%)", i_date, i_percent );
-    if( i_date < 0 && i_percent < 0 )
+    msg_Dbg( p_demux, "seek request to "I64Fd" (%f%%)", i_date, f_percent );
+    if( i_date < 0 && f_percent < 0 )
     {
+        msg_Warn( p_demux, "cannot seek nowhere !" );
+        return;
+    }
+    if( f_percent > 1.0 )
+    {
+        msg_Warn( p_demux, "cannot seek so far !" );
         return;
     }
-    if( i_percent > 100 ) i_percent = 100;
 
     delete p_sys->ep;
     p_sys->ep = new EbmlParser( p_sys->es, p_sys->segment );
     p_sys->cluster = NULL;
 
     /* seek without index or without date */
-    if( config_GetInt( p_demux, "mkv-seek-percent" ) || !p_sys->b_cues || i_date < 0 )
+    if( f_percent >= 0 && (config_GetInt( p_demux, "mkv-seek-percent" ) || !p_sys->b_cues || i_date < 0 ))
     {
-        int64_t i_pos = i_percent * stream_Size( p_demux->s ) / 100;
-
-        msg_Dbg( p_demux, "inacurate way of seeking" );
-        for( i_index = 0; i_index < p_sys->i_index; i_index++ )
+        if (p_sys->f_duration >= 0)
         {
-            if( p_sys->index[i_index].i_position >= i_pos)
-            {
-                break;
-            }
+            i_date = int64_t( f_percent * p_sys->f_duration * 1000.0 );
         }
-        if( i_index == p_sys->i_index )
+        else
         {
-            i_index--;
-        }
-
-        p_sys->in->setFilePointer( p_sys->index[i_index].i_position,
-                                   seek_beginning );
+            int64_t i_pos = int64_t( f_percent * stream_Size( p_demux->s ) );
 
-        if( p_sys->index[i_index].i_position < i_pos )
-        {
-            EbmlElement *el;
+            msg_Dbg( p_demux, "inacurate way of seeking" );
+            for( i_index = 0; i_index < p_sys->i_index; i_index++ )
+            {
+                if( p_sys->index[i_index].i_position >= i_pos)
+                {
+                    break;
+                }
+            }
+            if( i_index == p_sys->i_index )
+            {
+                i_index--;
+            }
 
-            msg_Warn( p_demux, "searching for cluster, could take some time" );
+            i_date = p_sys->index[i_index].i_time;
 
-            /* search a cluster */
-            while( ( el = p_sys->ep->Get() ) != NULL )
+#if 0
+            if( p_sys->index[i_index].i_position < i_pos )
             {
-                if( MKV_IS_ID( el, KaxCluster ) )
-                {
-                    KaxCluster *cluster = (KaxCluster*)el;
+                EbmlElement *el;
 
-                    /* add it to the index */
-                    IndexAppendCluster( p_demux, cluster );
+                msg_Warn( p_demux, "searching for cluster, could take some time" );
 
-                    if( (int64_t)cluster->GetElementPosition() >= i_pos )
+                /* search a cluster */
+                while( ( el = p_sys->ep->Get() ) != NULL )
+                {
+                    if( MKV_IS_ID( el, KaxCluster ) )
                     {
-                        p_sys->cluster = cluster;
-                        p_sys->ep->Down();
-                        break;
+                        KaxCluster *cluster = (KaxCluster*)el;
+
+                        /* add it to the index */
+                        IndexAppendCluster( p_demux, cluster );
+
+                        if( (int64_t)cluster->GetElementPosition() >= i_pos )
+                        {
+                            p_sys->cluster = cluster;
+                            p_sys->ep->Down();
+                            break;
+                        }
                     }
                 }
             }
+#endif
         }
     }
-    else
+
+    // find the actual time for an ordered edition
+    if ( psz_chapter == NULL )
     {
-        for( i_index = 0; i_index < p_sys->i_index; i_index++ )
+        if ( p_sys->editions.size() && p_sys->editions[p_sys->i_current_edition].b_ordered )
         {
-            if( p_sys->index[i_index].i_time >= i_date )
-            {
-                break;
-            }
+            /* 1st, we need to know in which chapter we are */
+            psz_chapter = p_sys->editions[p_sys->i_current_edition].FindTimecode( i_date );
         }
+    }
 
-        if( i_index > 0 )
+    if ( psz_chapter != NULL )
+    {
+        p_sys->psz_current_chapter = psz_chapter;
+        p_sys->i_chapter_time = i_time_offset = psz_chapter->i_user_start_time - psz_chapter->i_start_time;
+        p_demux->info.i_update |= INPUT_UPDATE_SEEKPOINT;
+        p_demux->info.i_seekpoint = psz_chapter->i_seekpoint_num - 1;
+    }
+
+    for( ; i_index < p_sys->i_index; i_index++ )
+    {
+        if( p_sys->index[i_index].i_time + i_time_offset > i_date )
         {
-            i_index--;
+            break;
         }
+    }
 
-        msg_Dbg( p_demux, "seek got "I64Fd" (%d%%)",
-                 p_sys->index[i_index].i_time,
-                 (int)( 100 * p_sys->index[i_index].i_position /
-                        stream_Size( p_demux->s ) ) );
-
-        p_sys->in->setFilePointer( p_sys->index[i_index].i_position,
-                                   seek_beginning );
+    if( i_index > 0 )
+    {
+        i_index--;
     }
 
+    msg_Dbg( p_demux, "seek got "I64Fd" (%d%%)",
+                p_sys->index[i_index].i_time,
+                (int)( 100 * p_sys->index[i_index].i_position /
+                    stream_Size( p_demux->s ) ) );
+
+    p_sys->in->setFilePointer( p_sys->index[i_index].i_position,
+                                seek_beginning );
+
+    p_sys->i_start_pts = i_date;
+
+    es_out_Control( p_demux->out, ES_OUT_RESET_PCR );
+
     /* now parse until key frame */
 #define tk  p_sys->track[i_track]
     i_track_skipping = 0;
@@ -1211,8 +1619,10 @@ static void Seek( demux_t *p_demux, mtime_t i_date, int i_percent)
             tk.b_search_keyframe = VLC_TRUE;
             i_track_skipping++;
         }
+        es_out_Control( p_demux->out, ES_OUT_SET_NEXT_DISPLAY_TIME, tk.p_es, i_date );
     }
 
+
     while( i_track_skipping > 0 )
     {
         if( BlockGet( p_demux, &block, &i_block_ref1, &i_block_ref2, &i_block_duration ) )
@@ -1222,8 +1632,6 @@ static void Seek( demux_t *p_demux, mtime_t i_date, int i_percent)
             return;
         }
 
-        p_sys->i_pts = block->GlobalTimecode() / (mtime_t) 1000 + 1;
-
         for( i_track = 0; i_track < p_sys->i_track; i_track++ )
         {
             if( tk.i_number == block->TrackNum() )
@@ -1232,16 +1640,21 @@ static void Seek( demux_t *p_demux, mtime_t i_date, int i_percent)
             }
         }
 
+        p_sys->i_pts = p_sys->i_chapter_time + block->GlobalTimecode() / (mtime_t) 1000;
+
         if( i_track < p_sys->i_track )
         {
-            if( tk.fmt.i_cat == VIDEO_ES && i_block_ref1 == -1 && tk.b_search_keyframe )
-            {
-                tk.b_search_keyframe = VLC_FALSE;
-                i_track_skipping--;
-            }
-            if( tk.fmt.i_cat == VIDEO_ES && !tk.b_search_keyframe )
+            if( tk.fmt.i_cat == VIDEO_ES )
             {
-                BlockDecode( p_demux, block, 0, 0 );
+                if( i_block_ref1 == -1 && tk.b_search_keyframe )
+                {
+                    tk.b_search_keyframe = VLC_FALSE;
+                    i_track_skipping--;
+                }
+                if( !tk.b_search_keyframe )
+                {
+                    BlockDecode( p_demux, block, p_sys->i_pts, 0 );
+                }
             }
         }
 
@@ -1258,7 +1671,6 @@ static void Seek( demux_t *p_demux, mtime_t i_date, int i_percent)
 static int Demux( demux_t *p_demux)
 {
     demux_sys_t *p_sys = p_demux->p_sys;
-    mtime_t        i_start_pts;
     int            i_block_count = 0;
 
     KaxBlock *block;
@@ -1266,20 +1678,38 @@ static int Demux( demux_t *p_demux)
     int64_t i_block_ref1;
     int64_t i_block_ref2;
 
-    i_start_pts = -1;
-
     for( ;; )
     {
+        if( p_sys->i_pts >= p_sys->i_start_pts  )
+            UpdateCurrentToChapter( *p_demux );
+        
+        if ( p_sys->editions.size() && p_sys->editions[p_sys->i_current_edition].b_ordered && p_sys->psz_current_chapter == NULL )
+        {
+            /* nothing left to read in this ordered edition */
+            return 0;
+        }
+
         if( BlockGet( p_demux, &block, &i_block_ref1, &i_block_ref2, &i_block_duration ) )
         {
+            if ( p_sys->editions.size() && p_sys->editions[p_sys->i_current_edition].b_ordered )
+            {
+                // check if there are more chapters to read
+                if ( p_sys->psz_current_chapter != NULL )
+                {
+                    p_sys->i_pts = p_sys->psz_current_chapter->i_user_end_time;
+                    return 1;
+                }
+
+                return 0;
+            }
             msg_Warn( p_demux, "cannot get block EOF?" );
 
             return 0;
         }
 
-        p_sys->i_pts = block->GlobalTimecode() / (mtime_t) 1000 + 1;
+        p_sys->i_pts = p_sys->i_chapter_time + block->GlobalTimecode() / (mtime_t) 1000;
 
-        if( p_sys->i_pts > 0 )
+        if( p_sys->i_pts >= p_sys->i_start_pts  )
         {
             es_out_Control( p_demux->out, ES_OUT_SET_PCR, p_sys->i_pts );
         }
@@ -1289,11 +1719,8 @@ static int Demux( demux_t *p_demux)
         delete block;
         i_block_count++;
 
-        if( i_start_pts == -1 )
-        {
-            i_start_pts = p_sys->i_pts;
-        }
-        else if( p_sys->i_pts > i_start_pts + (mtime_t)100000 || i_block_count > 5 )
+        // TODO optimize when there is need to leave or when seeking has been called
+        if( i_block_count > 5 )
         {
             return 1;
         }
@@ -1840,7 +2267,7 @@ static void ParseTrackEntry( demux_t *p_demux, EbmlMaster *m )
     tk->psz_codec_info_url = NULL;
     tk->psz_codec_download_url = NULL;
     
-    tk->b_compression_zlib = VLC_FALSE;
+    tk->i_compression_type = MATROSKA_COMPRESSION_NONE;
 
     for( i = 0; i < m->ListSize(); i++ )
     {
@@ -1977,13 +2404,13 @@ static void ParseTrackEntry( demux_t *p_demux, EbmlMaster *m )
         else if( MKV_IS_ID( l, KaxContentEncodings ) )
         {
             EbmlMaster *cencs = static_cast<EbmlMaster*>(l);
-            msg_Dbg( p_demux, "|   |   |   + Content Encodings" );
+            MkvTree( p_demux, 3, "Content Encodings" );
             for( unsigned int i = 0; i < cencs->ListSize(); i++ )
             {
                 EbmlElement *l2 = (*cencs)[i];
                 if( MKV_IS_ID( l2, KaxContentEncoding ) )
                 {
-                    msg_Dbg( p_demux, "|   |   |   |   + Content Encoding" );
+                    MkvTree( p_demux, 4, "Content Encoding" );
                     EbmlMaster *cenc = static_cast<EbmlMaster*>(l2);
                     for( unsigned int i = 0; i < cenc->ListSize(); i++ )
                     {
@@ -1991,51 +2418,51 @@ static void ParseTrackEntry( demux_t *p_demux, EbmlMaster *m )
                         if( MKV_IS_ID( l3, KaxContentEncodingOrder ) )
                         {
                             KaxContentEncodingOrder &encord = *(KaxContentEncodingOrder*)l3;
-                            msg_Dbg( p_demux, "|   |   |   |   |   + Order: %i", uint32( encord ) );
+                            MkvTree( p_demux, 5, "Order: %i", uint32( encord ) );
                         }
                         else if( MKV_IS_ID( l3, KaxContentEncodingScope ) )
                         {
                             KaxContentEncodingScope &encscope = *(KaxContentEncodingScope*)l3;
-                            msg_Dbg( p_demux, "|   |   |   |   |   + Scope: %i", uint32( encscope ) );
+                            MkvTree( p_demux, 5, "Scope: %i", uint32( encscope ) );
                         }
                         else if( MKV_IS_ID( l3, KaxContentEncodingType ) )
                         {
                             KaxContentEncodingType &enctype = *(KaxContentEncodingType*)l3;
-                            msg_Dbg( p_demux, "|   |   |   |   |   + Type: %i", uint32( enctype ) );
+                            MkvTree( p_demux, 5, "Type: %i", uint32( enctype ) );
                         }
                         else if( MKV_IS_ID( l3, KaxContentCompression ) )
                         {
                             EbmlMaster *compr = static_cast<EbmlMaster*>(l3);
-                            msg_Dbg( p_demux, "|   |   |   |   |   + Content Compression" );
+                            MkvTree( p_demux, 5, "Content Compression" );
                             for( unsigned int i = 0; i < compr->ListSize(); i++ )
                             {
                                 EbmlElement *l4 = (*compr)[i];
                                 if( MKV_IS_ID( l4, KaxContentCompAlgo ) )
                                 {
                                     KaxContentCompAlgo &compalg = *(KaxContentCompAlgo*)l4;
-                                    msg_Dbg( p_demux, "|   |   |   |   |   |   + Compression Algorithm: %i", uint32(compalg) );
+                                    MkvTree( p_demux, 6, "Compression Algorithm: %i", uint32(compalg) );
                                     if( uint32( compalg ) == 0 )
                                     {
-                                        tk->b_compression_zlib = VLC_TRUE;
+                                        tk->i_compression_type = MATROSKA_COMPRESSION_ZLIB;
                                     }
                                 }
                                 else
                                 {
-                                    msg_Dbg( p_demux, "|   |   |   |   |   |   + Unknown (%s)", typeid(*l4).name() );
+                                    MkvTree( p_demux, 6, "Unknown (%s)", typeid(*l4).name() );
                                 }
                             }
                         }
 
                         else
                         {
-                            msg_Dbg( p_demux, "|   |   |   |   |   + Unknown (%s)", typeid(*l3).name() );
+                            MkvTree( p_demux, 5, "Unknown (%s)", typeid(*l3).name() );
                         }
                     }
                     
                 }
                 else
                 {
-                    msg_Dbg( p_demux, "|   |   |   |   + Unknown (%s)", typeid(*l2).name() );
+                    MkvTree( p_demux, 4, "Unknown (%s)", typeid(*l2).name() );
                 }
             }
                 
@@ -2255,9 +2682,9 @@ static void ParseInfo( demux_t *p_demux, EbmlElement *info )
 
         if( MKV_IS_ID( l, KaxSegmentUID ) )
         {
-            KaxSegmentUID &uid = *(KaxSegmentUID*)l;
+            p_sys->segment_uid = *(new KaxSegmentUID(*static_cast<KaxSegmentUID*>(l)));
 
-            msg_Dbg( p_demux, "|   |   + UID=%d", uint32(uid) );
+            msg_Dbg( p_demux, "|   |   + UID=%d", *(uint32*)p_sys->segment_uid.GetBuffer() );
         }
         else if( MKV_IS_ID( l, KaxTimecodeScale ) )
         {
@@ -2312,6 +2739,14 @@ static void ParseInfo( demux_t *p_demux, EbmlElement *info )
 
             msg_Dbg( p_demux, "|   |   + Title=%s", p_sys->psz_title );
         }
+        if( MKV_IS_ID( l, KaxSegmentFamily ) )
+        {
+            KaxSegmentFamily *uid = static_cast<KaxSegmentFamily*>(l);
+
+            p_sys->families.push_back(*uid);
+
+            msg_Dbg( p_demux, "|   |   + family=%d", *(uint32*)uid->GetBuffer() );
+        }
 #if defined( HAVE_GMTIME_R ) && !defined( SYS_DARWIN )
         else if( MKV_IS_ID( l, KaxDateUTC ) )
         {
@@ -2337,24 +2772,22 @@ static void ParseInfo( demux_t *p_demux, EbmlElement *info )
         }
     }
 
-    p_sys->f_duration = p_sys->f_duration * p_sys->i_timescale / 1000000.0;
+    p_sys->f_duration *= p_sys->i_timescale / 1000000.0;
 }
 
 
 /*****************************************************************************
  * ParseChapterAtom
  *****************************************************************************/
-static void ParseChapterAtom( demux_t *p_demux, int i_level, EbmlMaster *ca )
+static void ParseChapterAtom( demux_t *p_demux, int i_level, EbmlMaster *ca, chapter_item_t & chapters )
 {
     demux_sys_t *p_sys = p_demux->p_sys;
     unsigned int i;
-    seekpoint_t *sk;
 
     if( p_sys->title == NULL )
     {
         p_sys->title = vlc_input_title_New();
     }
-    sk = vlc_seekpoint_New();
 
     msg_Dbg( p_demux, "|   |   |   + ChapterAtom (level=%d)", i_level );
     for( i = 0; i < ca->ListSize(); i++ )
@@ -2363,23 +2796,29 @@ static void ParseChapterAtom( demux_t *p_demux, int i_level, EbmlMaster *ca )
 
         if( MKV_IS_ID( l, KaxChapterUID ) )
         {
-            KaxChapterUID &uid = *(KaxChapterUID*)l;
-            uint32_t i_uid = uint32( uid );
-            msg_Dbg( p_demux, "|   |   |   |   + ChapterUID: 0x%x", i_uid );
+            chapters.i_uid = uint64_t(*(KaxChapterUID*)l);
+            msg_Dbg( p_demux, "|   |   |   |   + ChapterUID: %lld", chapters.i_uid );
+        }
+        else if( MKV_IS_ID( l, KaxChapterFlagHidden ) )
+        {
+            KaxChapterFlagHidden &flag =*(KaxChapterFlagHidden*)l;
+            chapters.b_display_seekpoint = uint8( flag ) == 0;
+
+            msg_Dbg( p_demux, "|   |   |   |   + ChapterFlagHidden: %s", chapters.b_display_seekpoint ? "no":"yes" );
         }
         else if( MKV_IS_ID( l, KaxChapterTimeStart ) )
         {
             KaxChapterTimeStart &start =*(KaxChapterTimeStart*)l;
-            sk->i_time_offset = uint64( start ) / I64C(1000);
+            chapters.i_start_time = uint64( start ) / I64C(1000);
 
-            msg_Dbg( p_demux, "|   |   |   |   + ChapterTimeStart: %lld", sk->i_time_offset );
+            msg_Dbg( p_demux, "|   |   |   |   + ChapterTimeStart: %lld", chapters.i_start_time );
         }
         else if( MKV_IS_ID( l, KaxChapterTimeEnd ) )
         {
             KaxChapterTimeEnd &end =*(KaxChapterTimeEnd*)l;
-            int64_t i_end = uint64( end );
+            chapters.i_end_time = uint64( end ) / I64C(1000);
 
-            msg_Dbg( p_demux, "|   |   |   |   + ChapterTimeEnd: %lld", i_end );
+            msg_Dbg( p_demux, "|   |   |   |   + ChapterTimeEnd: %lld", chapters.i_end_time );
         }
         else if( MKV_IS_ID( l, KaxChapterDisplay ) )
         {
@@ -2393,10 +2832,15 @@ static void ParseChapterAtom( demux_t *p_demux, int i_level, EbmlMaster *ca )
 
                 if( MKV_IS_ID( l, KaxChapterString ) )
                 {
+                    int k;
+
                     KaxChapterString &name =*(KaxChapterString*)l;
-                    char *psz = UTF8ToStr( UTFstring( name ) );
-                    sk->psz_name = strdup( psz );
-                    msg_Dbg( p_demux, "|   |   |   |   |    + ChapterString '%s'", psz );
+                    for (k = 0; k < i_level; k++)
+                        chapters.psz_name += '+';
+                    chapters.psz_name += ' ';
+                    chapters.psz_name += UTF8ToStr( UTFstring( name ) );
+
+                    msg_Dbg( p_demux, "|   |   |   |   |    + ChapterString '%s'", UTF8ToStr(UTFstring(name)) );
                 }
                 else if( MKV_IS_ID( l, KaxChapterLanguage ) )
                 {
@@ -2416,13 +2860,12 @@ static void ParseChapterAtom( demux_t *p_demux, int i_level, EbmlMaster *ca )
         }
         else if( MKV_IS_ID( l, KaxChapterAtom ) )
         {
-            ParseChapterAtom( p_demux, i_level+1, static_cast<EbmlMaster *>(l) );
+            chapter_item_t new_sub_chapter;
+            ParseChapterAtom( p_demux, i_level+1, static_cast<EbmlMaster *>(l), new_sub_chapter );
+            new_sub_chapter.psz_parent = &chapters;
+            chapters.sub_chapters.push_back( new_sub_chapter );
         }
     }
-    // A start time of '0' is ok. A missing ChapterTime element is ok, too, because '0' is its default value.
-    p_sys->title->i_seekpoint++;
-    p_sys->title->seekpoint = (seekpoint_t**)realloc( p_sys->title->seekpoint, p_sys->title->i_seekpoint * sizeof( seekpoint_t* ) );
-    p_sys->title->seekpoint[p_sys->title->i_seekpoint-1] = sk;
 }
 
 /*****************************************************************************
@@ -2435,7 +2878,8 @@ static void ParseChapters( demux_t *p_demux, EbmlElement *chapters )
     EbmlMaster  *m;
     unsigned int i;
     int i_upper_level = 0;
-
+    int i_default_edition = 0;
+    float f_duration;
 
     /* Master elements */
     m = static_cast<EbmlMaster *>(chapters);
@@ -2447,6 +2891,8 @@ static void ParseChapters( demux_t *p_demux, EbmlElement *chapters )
 
         if( MKV_IS_ID( l, KaxEditionEntry ) )
         {
+            chapter_edition_t edition;
+            
             EbmlMaster *E = static_cast<EbmlMaster *>(l );
             unsigned int j;
             msg_Dbg( p_demux, "|   |   + EditionEntry" );
@@ -2456,19 +2902,50 @@ static void ParseChapters( demux_t *p_demux, EbmlElement *chapters )
 
                 if( MKV_IS_ID( l, KaxChapterAtom ) )
                 {
-                    ParseChapterAtom( p_demux, 0, static_cast<EbmlMaster *>(l) );
+                    chapter_item_t new_sub_chapter;
+                    ParseChapterAtom( p_demux, 0, static_cast<EbmlMaster *>(l), new_sub_chapter );
+                    edition.chapters.push_back( new_sub_chapter );
+                }
+                else if( MKV_IS_ID( l, KaxEditionUID ) )
+                {
+                    edition.i_uid = uint64(*static_cast<KaxEditionUID *>( l ));
+                }
+                else if( MKV_IS_ID( l, KaxEditionFlagOrdered ) )
+                {
+                    edition.b_ordered = uint8(*static_cast<KaxEditionFlagOrdered *>( l )) != 0;
+                }
+                else if( MKV_IS_ID( l, KaxEditionFlagDefault ) )
+                {
+                    if (uint8(*static_cast<KaxEditionFlagDefault *>( l )) != 0)
+                        i_default_edition = p_sys->editions.size();
                 }
                 else
                 {
                     msg_Dbg( p_demux, "|   |   |   + Unknown (%s)", typeid(*l).name() );
                 }
             }
+            p_sys->editions.push_back( edition );
         }
         else
         {
             msg_Dbg( p_demux, "|   |   + Unknown (%s)", typeid(*l).name() );
         }
     }
+
+    for( i = 0; i < p_sys->editions.size(); i++ )
+    {
+        p_sys->editions[i].RefreshChapters( *p_sys->title );
+    }
+    
+    p_sys->i_current_edition = i_default_edition;
+    
+    if ( p_sys->editions[i_default_edition].b_ordered )
+    {
+        /* update the duration of the segment according to the sum of all sub chapters */
+        f_duration = p_sys->editions[i_default_edition].Duration() / I64C(1000);
+        if (f_duration > 0.0)
+            p_sys->f_duration = f_duration;
+    }
 }
 
 /*****************************************************************************
@@ -2598,3 +3075,112 @@ static char * UTF8ToStr( const UTFstring &u )
     return dst;
 }
 
+void chapter_edition_t::RefreshChapters( input_title_t & title )
+{
+    int64_t i_prev_user_time = 0;
+    std::vector<chapter_item_t>::iterator index = chapters.begin();
+
+    while ( index != chapters.end() )
+    {
+        i_prev_user_time = (*index).RefreshChapters( b_ordered, i_prev_user_time, title );
+        index++;
+    }
+}
+
+int64_t chapter_item_t::RefreshChapters( bool b_ordered, int64_t i_prev_user_time, input_title_t & title )
+{
+    int64_t i_user_time = i_prev_user_time;
+    
+    // first the sub-chapters, and then ourself
+    std::vector<chapter_item_t>::iterator index = sub_chapters.begin();
+    while ( index != sub_chapters.end() )
+    {
+        i_user_time = (*index).RefreshChapters( b_ordered, i_user_time, title );
+        index++;
+    }
+
+    if ( b_ordered )
+    {
+        i_user_start_time = i_prev_user_time;
+        if ( i_end_time != -1 && i_user_time == i_prev_user_time )
+        {
+            i_user_end_time = i_user_start_time - i_start_time + i_end_time;
+        }
+        else
+        {
+            i_user_end_time = i_user_time;
+        }
+    }
+    else
+    {
+        std::sort( sub_chapters.begin(), sub_chapters.end() );
+        i_user_start_time = i_start_time;
+        i_user_end_time = i_end_time;
+    }
+
+    if (b_display_seekpoint)
+    {
+        seekpoint_t *sk = vlc_seekpoint_New();
+
+//        sk->i_level = i_level;
+        sk->i_time_offset = i_start_time;
+        sk->psz_name = strdup( psz_name.c_str() );
+
+        // A start time of '0' is ok. A missing ChapterTime element is ok, too, because '0' is its default value.
+        title.i_seekpoint++;
+        title.seekpoint = (seekpoint_t**)realloc( title.seekpoint, title.i_seekpoint * sizeof( seekpoint_t* ) );
+        title.seekpoint[title.i_seekpoint-1] = sk;
+    }
+
+    i_seekpoint_num = title.i_seekpoint;
+
+    return i_user_end_time;
+}
+
+double chapter_edition_t::Duration() const
+{
+    double f_result = 0.0;
+    
+    if ( chapters.size() )
+    {
+        std::vector<chapter_item_t>::const_iterator index = chapters.end();
+        index--;
+        f_result = (*index).i_user_end_time;
+    }
+    
+    return f_result;
+}
+
+const chapter_item_t *chapter_item_t::FindTimecode( mtime_t i_user_timecode ) const
+{
+    const chapter_item_t *psz_result = NULL;
+
+    if (i_user_timecode >= i_user_start_time && i_user_timecode < i_user_end_time)
+    {
+        std::vector<chapter_item_t>::const_iterator index = sub_chapters.begin();
+        while ( index != sub_chapters.end() && psz_result == NULL )
+        {
+            psz_result = (*index).FindTimecode( i_user_timecode );
+            index++;
+        }
+        
+        if ( psz_result == NULL )
+            psz_result = this;
+    }
+
+    return psz_result;
+}
+
+const chapter_item_t *chapter_edition_t::FindTimecode( mtime_t i_user_timecode ) const
+{
+    const chapter_item_t *psz_result = NULL;
+
+    std::vector<chapter_item_t>::const_iterator index = chapters.begin();
+    while ( index != chapters.end() && psz_result == NULL )
+    {
+        psz_result = (*index).FindTimecode( i_user_timecode );
+        index++;
+    }
+
+    return psz_result;
+}