avoid \r\n problems
authorSteve Lhomme <robux@videolan.org>
Wed, 16 Feb 2005 22:01:41 +0000 (22:01 +0000)
committerSteve Lhomme <robux@videolan.org>
Wed, 16 Feb 2005 22:01:41 +0000 (22:01 +0000)
modules/demux/mkv.cpp

index 870f68a..9cab57f 100644 (file)
-/*****************************************************************************\r
- * mkv.cpp : matroska demuxer\r
- *****************************************************************************\r
- * Copyright (C) 2003-2004 VideoLAN\r
- * $Id$\r
- *\r
- * Authors: Laurent Aimar <fenrir@via.ecp.fr>\r
- *          Steve Lhomme <steve.lhomme@free.fr>\r
- *\r
- * This program is free software; you can redistribute it and/or modify\r
- * it under the terms of the GNU General Public License as published by\r
- * the Free Software Foundation; either version 2 of the License, or\r
- * (at your option) any later version.\r
- *\r
- * This program is distributed in the hope that it will be useful,\r
- * but WITHOUT ANY WARRANTY; without even the implied warranty of\r
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\r
- * GNU General Public License for more details.\r
- *\r
- * You should have received a copy of the GNU General Public License\r
- * along with this program; if not, write to the Free Software\r
- * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111, USA.\r
- *****************************************************************************/\r
-\r
-/*****************************************************************************\r
- * Preamble\r
- *****************************************************************************/\r
-#include <stdlib.h>                                      /* malloc(), free() */\r
-\r
-#include <vlc/vlc.h>\r
-\r
-#ifdef HAVE_TIME_H\r
-#   include <time.h>                                               /* time() */\r
-#endif\r
-\r
-#include <vlc/input.h>\r
-\r
-#include <codecs.h>                        /* BITMAPINFOHEADER, WAVEFORMATEX */\r
-#include "iso_lang.h"\r
-#include "vlc_meta.h"\r
-\r
-#include <iostream>\r
-#include <cassert>\r
-#include <typeinfo>\r
-#include <string>\r
-#include <vector>\r
-\r
-#ifdef HAVE_DIRENT_H\r
-#   include <dirent.h>\r
-#else\r
-#   include "../../src/extras/dirent.h"\r
-#endif\r
-\r
-/* libebml and matroska */\r
-#include "ebml/EbmlHead.h"\r
-#include "ebml/EbmlSubHead.h"\r
-#include "ebml/EbmlStream.h"\r
-#include "ebml/EbmlContexts.h"\r
-#include "ebml/EbmlVoid.h"\r
-#include "ebml/StdIOCallback.h"\r
-\r
-#include "matroska/KaxAttachments.h"\r
-#include "matroska/KaxBlock.h"\r
-#include "matroska/KaxBlockData.h"\r
-#include "matroska/KaxChapters.h"\r
-#include "matroska/KaxCluster.h"\r
-#include "matroska/KaxClusterData.h"\r
-#include "matroska/KaxContexts.h"\r
-#include "matroska/KaxCues.h"\r
-#include "matroska/KaxCuesData.h"\r
-#include "matroska/KaxInfo.h"\r
-#include "matroska/KaxInfoData.h"\r
-#include "matroska/KaxSeekHead.h"\r
-#include "matroska/KaxSegment.h"\r
-#include "matroska/KaxTag.h"\r
-#include "matroska/KaxTags.h"\r
-#include "matroska/KaxTagMulti.h"\r
-#include "matroska/KaxTracks.h"\r
-#include "matroska/KaxTrackAudio.h"\r
-#include "matroska/KaxTrackVideo.h"\r
-#include "matroska/KaxTrackEntryData.h"\r
-#include "matroska/KaxContentEncoding.h"\r
-\r
-#include "ebml/StdIOCallback.h"\r
-\r
-extern "C" {\r
-   #include "mp4/libmp4.h"\r
-}\r
-#ifdef HAVE_ZLIB_H\r
-#   include <zlib.h>\r
-#endif\r
-\r
-#define MATROSKA_COMPRESSION_NONE 0\r
-#define MATROSKA_COMPRESSION_ZLIB 1\r
-\r
-/**\r
- * What's between a directory and a filename?\r
- */\r
-#if defined( WIN32 )\r
-    #define DIRECTORY_SEPARATOR '\\'\r
-#else\r
-    #define DIRECTORY_SEPARATOR '/'\r
-#endif\r
-\r
-using namespace LIBMATROSKA_NAMESPACE;\r
-using namespace std;\r
-\r
-/*****************************************************************************\r
- * Module descriptor\r
- *****************************************************************************/\r
-static int  Open ( vlc_object_t * );\r
-static void Close( vlc_object_t * );\r
-\r
-vlc_module_begin();\r
-    set_shortname( _("Matroska") );\r
-    set_description( _("Matroska stream demuxer" ) );\r
-    set_capability( "demux2", 50 );\r
-    set_callbacks( Open, Close );\r
-    set_category( CAT_INPUT );\r
-    set_subcategory( SUBCAT_INPUT_DEMUX );\r
-\r
-    add_bool( "mkv-seek-percent", 1, NULL,\r
-            N_("Seek based on percent not time"),\r
-            N_("Seek based on percent not time"), VLC_TRUE );\r
-\r
-    add_shortcut( "mka" );\r
-    add_shortcut( "mkv" );\r
-vlc_module_end();\r
-\r
-/*****************************************************************************\r
- * Local prototypes\r
- *****************************************************************************/\r
-static int  Demux  ( demux_t * );\r
-static int  Control( demux_t *, int, va_list );\r
-static void Seek   ( demux_t *, mtime_t i_date, int i_percent );\r
-\r
-#ifdef HAVE_ZLIB_H\r
-block_t *block_zlib_decompress( vlc_object_t *p_this, block_t *p_in_block ) {\r
-    int result, dstsize, n;\r
-    unsigned char *dst;\r
-    block_t *p_block;\r
-    z_stream d_stream;\r
-\r
-    d_stream.zalloc = (alloc_func)0;\r
-    d_stream.zfree = (free_func)0;\r
-    d_stream.opaque = (voidpf)0;\r
-    result = inflateInit(&d_stream);\r
-    if( result != Z_OK )\r
-    {\r
-        msg_Dbg( p_this, "inflateInit() failed. Result: %d", result );\r
-        return NULL;\r
-    }\r
-\r
-    d_stream.next_in = (Bytef *)p_in_block->p_buffer;\r
-    d_stream.avail_in = p_in_block->i_buffer;\r
-    n = 0;\r
-    p_block = block_New( p_this, 0 );\r
-    dst = NULL;\r
-    do\r
-    {\r
-        n++;\r
-        p_block = block_Realloc( p_block, 0, n * 1000 );\r
-        dst = (unsigned char *)p_block->p_buffer;\r
-        d_stream.next_out = (Bytef *)&dst[(n - 1) * 1000];\r
-        d_stream.avail_out = 1000;\r
-        result = inflate(&d_stream, Z_NO_FLUSH);\r
-        if( ( result != Z_OK ) && ( result != Z_STREAM_END ) )\r
-        {\r
-            msg_Dbg( p_this, "Zlib decompression failed. Result: %d", result );\r
-            return NULL;\r
-        }\r
-    }\r
-    while( ( d_stream.avail_out == 0 ) && ( d_stream.avail_in != 0 ) &&\r
-           ( result != Z_STREAM_END ) );\r
-\r
-    dstsize = d_stream.total_out;\r
-    inflateEnd( &d_stream );\r
-\r
-    p_block = block_Realloc( p_block, 0, dstsize );\r
-    p_block->i_buffer = dstsize;\r
-    block_Release( p_in_block );\r
-\r
-    return p_block;\r
-}\r
-#endif\r
-\r
-/**\r
- * Helper function to print the mkv parse tree\r
- */\r
-static void MkvTree( demux_t *p_this, int i_level, char *psz_format, ... )\r
-{\r
-    va_list args;\r
-    if( i_level > 9 )\r
-    {\r
-        msg_Err( p_this, "too deep tree" );\r
-        return;\r
-    }\r
-    va_start( args, psz_format );\r
-    static char *psz_foo = "|   |   |   |   |   |   |   |   |   |";\r
-    char *psz_foo2 = (char*)malloc( ( i_level * 4 + 3 + strlen( psz_format ) ) * sizeof(char) );\r
-    strncpy( psz_foo2, psz_foo, 4 * i_level );\r
-    psz_foo2[ 4 * i_level ] = '+';\r
-    psz_foo2[ 4 * i_level + 1 ] = ' ';\r
-    strcpy( &psz_foo2[ 4 * i_level + 2 ], psz_format );\r
-    __msg_GenericVa( VLC_OBJECT(p_this), VLC_MSG_DBG, "mkv", psz_foo2, args );\r
-    free( psz_foo2 );\r
-    va_end( args );\r
-}\r
-    \r
-/*****************************************************************************\r
- * Stream managment\r
- *****************************************************************************/\r
-class vlc_stream_io_callback: public IOCallback\r
-{\r
-  private:\r
-    stream_t       *s;\r
-    vlc_bool_t     mb_eof;\r
-\r
-  public:\r
-    vlc_stream_io_callback( stream_t * );\r
-\r
-    virtual uint32   read            ( void *p_buffer, size_t i_size);\r
-    virtual void     setFilePointer  ( int64_t i_offset, seek_mode mode = seek_beginning );\r
-    virtual size_t   write           ( const void *p_buffer, size_t i_size);\r
-    virtual uint64   getFilePointer  ( void );\r
-    virtual void     close           ( void );\r
-};\r
-\r
-/*****************************************************************************\r
- * Ebml Stream parser\r
- *****************************************************************************/\r
-class EbmlParser\r
-{\r
-  public:\r
-    EbmlParser( EbmlStream *es, EbmlElement *el_start );\r
-    ~EbmlParser( void );\r
-\r
-    void Up( void );\r
-    void Down( void );\r
-    EbmlElement *Get( void );\r
-    void        Keep( void );\r
-\r
-    int GetLevel( void );\r
-\r
-  private:\r
-    EbmlStream  *m_es;\r
-    int         mi_level;\r
-    EbmlElement *m_el[10];\r
-\r
-    EbmlElement *m_got;\r
-\r
-    int         mi_user_level;\r
-    vlc_bool_t  mb_keep;\r
-};\r
-\r
-\r
-/*****************************************************************************\r
- * Some functions to manipulate memory\r
- *****************************************************************************/\r
-#define GetFOURCC( p )  __GetFOURCC( (uint8_t*)p )\r
-static vlc_fourcc_t __GetFOURCC( uint8_t *p )\r
-{\r
-    return VLC_FOURCC( p[0], p[1], p[2], p[3] );\r
-}\r
-\r
-/*****************************************************************************\r
- * definitions of structures and functions used by this plugins\r
- *****************************************************************************/\r
-typedef struct\r
-{\r
-    vlc_bool_t  b_default;\r
-    vlc_bool_t  b_enabled;\r
-    int         i_number;\r
-\r
-    int         i_extra_data;\r
-    uint8_t     *p_extra_data;\r
-\r
-    char         *psz_codec;\r
-\r
-    uint64_t     i_default_duration;\r
-    float        f_timecodescale;\r
-\r
-    /* video */\r
-    es_format_t fmt;\r
-    float       f_fps;\r
-    es_out_id_t *p_es;\r
-\r
-    vlc_bool_t      b_inited;\r
-    /* data to be send first */\r
-    int             i_data_init;\r
-    uint8_t         *p_data_init;\r
-\r
-    /* hack : it's for seek */\r
-    vlc_bool_t      b_search_keyframe;\r
-\r
-    /* informative */\r
-    char         *psz_codec_name;\r
-    char         *psz_codec_settings;\r
-    char         *psz_codec_info_url;\r
-    char         *psz_codec_download_url;\r
-    \r
-    /* encryption/compression */\r
-    int           i_compression_type;\r
-\r
-} mkv_track_t;\r
-\r
-typedef struct\r
-{\r
-    int     i_track;\r
-    int     i_block_number;\r
-\r
-    int64_t i_position;\r
-    int64_t i_time;\r
-\r
-    vlc_bool_t b_key;\r
-} mkv_index_t;\r
-\r
-class demux_sys_t\r
-{\r
-public:\r
-    demux_sys_t()\r
-        :in(NULL)\r
-        ,es(NULL)\r
-        ,ep(NULL)\r
-        ,i_timescale(0)\r
-        ,f_duration(0.0)\r
-        ,i_track(0)\r
-        ,track(NULL)\r
-        ,i_cues_position(0)\r
-        ,i_chapters_position(0)\r
-        ,i_tags_position(0)\r
-        ,segment(NULL)\r
-        ,cluster(NULL)\r
-        ,i_pts(0)\r
-        ,i_start_pts(0)\r
-        ,b_cues(false)\r
-        ,i_index(0)\r
-        ,i_index_max(0)\r
-        ,index(NULL)\r
-        ,psz_muxing_application(NULL)\r
-        ,psz_writing_application(NULL)\r
-        ,psz_segment_filename(NULL)\r
-        ,psz_title(NULL)\r
-        ,psz_date_utc(NULL)\r
-        ,meta(NULL)\r
-        ,title(NULL)\r
-    {}\r
-\r
-    vlc_stream_io_callback  *in;\r
-    EbmlStream              *es;\r
-    EbmlParser              *ep;\r
-\r
-    /* time scale */\r
-    uint64_t                i_timescale;\r
-\r
-    /* duration of the segment */\r
-    float                   f_duration;\r
-\r
-    /* all tracks */\r
-    int                     i_track;\r
-    mkv_track_t             *track;\r
-\r
-    /* from seekhead */\r
-    int64_t                 i_cues_position;\r
-    int64_t                 i_chapters_position;\r
-    int64_t                 i_tags_position;\r
-\r
-    /* current data */\r
-    KaxSegment              *segment;\r
-    KaxCluster              *cluster;\r
-    KaxSegmentUID           segment_uid;\r
-\r
-    mtime_t                 i_pts;\r
-    mtime_t                 i_start_pts;\r
-\r
-    vlc_bool_t              b_cues;\r
-    int                     i_index;\r
-    int                     i_index_max;\r
-    mkv_index_t             *index;\r
-\r
-    /* info */\r
-    char                    *psz_muxing_application;\r
-    char                    *psz_writing_application;\r
-    char                    *psz_segment_filename;\r
-    char                    *psz_title;\r
-    char                    *psz_date_utc;\r
-\r
-    vlc_meta_t              *meta;\r
-\r
-    input_title_t           *title;\r
-\r
-    std::vector<KaxSegmentFamily> families;\r
-    std::vector<KaxSegment*> family_members;\r
-\r
-    int64_t                  edition_uid;\r
-    bool                     edition_ordered;\r
-};\r
-\r
-#define MKVD_TIMECODESCALE 1000000\r
-\r
-#define MKV_IS_ID( el, C ) ( EbmlId( (*el) ) == C::ClassInfos.GlobalId )\r
-\r
-static void IndexAppendCluster  ( demux_t *p_demux, KaxCluster *cluster );\r
-static char *UTF8ToStr          ( const UTFstring &u );\r
-static void LoadCues            ( demux_t * );\r
-static void InformationCreate  ( demux_t * );\r
-\r
-static void ParseInfo( demux_t *, EbmlElement *info );\r
-static void ParseTracks( demux_t *, EbmlElement *tracks );\r
-static void ParseSeekHead( demux_t *, EbmlElement *seekhead );\r
-static void ParseChapters( demux_t *, EbmlElement *chapters );\r
-\r
-/*****************************************************************************\r
- * Open: initializes matroska demux structures\r
- *****************************************************************************/\r
-static int Open( vlc_object_t * p_this )\r
-{\r
-    demux_t     *p_demux = (demux_t*)p_this;\r
-    demux_sys_t *p_sys;\r
-    uint8_t     *p_peek;\r
-    std::string  s_path, s_filename;\r
-    int          i_upper_lvl;\r
-    size_t       i, j;\r
-\r
-    int          i_track;\r
-\r
-    EbmlElement *el = NULL, *el1 = NULL;\r
-\r
-    /* peek the begining */\r
-    if( stream_Peek( p_demux->s, &p_peek, 4 ) < 4 )\r
-    {\r
-        msg_Warn( p_demux, "cannot peek" );\r
-        return VLC_EGENERIC;\r
-    }\r
-\r
-    /* is a valid file */\r
-    if( p_peek[0] != 0x1a || p_peek[1] != 0x45 ||\r
-        p_peek[2] != 0xdf || p_peek[3] != 0xa3 )\r
-    {\r
-        msg_Warn( p_demux, "matroska module discarded "\r
-                           "(invalid header 0x%.2x%.2x%.2x%.2x)",\r
-                           p_peek[0], p_peek[1], p_peek[2], p_peek[3] );\r
-        return VLC_EGENERIC;\r
-    }\r
-\r
-    /* Set the demux function */\r
-    p_demux->pf_demux   = Demux;\r
-    p_demux->pf_control = Control;\r
-    p_demux->p_sys      = p_sys = new demux_sys_t;\r
-\r
-    p_sys->in = new vlc_stream_io_callback( p_demux->s );\r
-    p_sys->es = new EbmlStream( *p_sys->in );\r
-    p_sys->f_duration   = -1;\r
-    p_sys->i_timescale     = MKVD_TIMECODESCALE;\r
-    p_sys->i_track      = 0;\r
-    p_sys->track        = (mkv_track_t*)malloc( sizeof( mkv_track_t ) );\r
-    p_sys->i_pts   = 0;\r
-    p_sys->i_cues_position = -1;\r
-    p_sys->i_chapters_position = -1;\r
-    p_sys->i_tags_position = -1;\r
-\r
-    p_sys->b_cues       = VLC_FALSE;\r
-    p_sys->i_index      = 0;\r
-    p_sys->i_index_max  = 1024;\r
-    p_sys->index        = (mkv_index_t*)malloc( sizeof( mkv_index_t ) *\r
-                                                p_sys->i_index_max );\r
-\r
-    p_sys->psz_muxing_application = NULL;\r
-    p_sys->psz_writing_application = NULL;\r
-    p_sys->psz_segment_filename = NULL;\r
-    p_sys->psz_title = NULL;\r
-    p_sys->psz_date_utc = NULL;;\r
-    p_sys->meta = NULL;\r
-    p_sys->title = NULL;\r
-\r
-    if( p_sys->es == NULL )\r
-    {\r
-        msg_Err( p_demux, "failed to create EbmlStream" );\r
-        delete p_sys->in;\r
-        delete p_sys;\r
-        return VLC_EGENERIC;\r
-    }\r
-    /* Find the EbmlHead element */\r
-    el = p_sys->es->FindNextID(EbmlHead::ClassInfos, 0xFFFFFFFFL);\r
-    if( el == NULL )\r
-    {\r
-        msg_Err( p_demux, "cannot find EbmlHead" );\r
-        goto error;\r
-    }\r
-    msg_Dbg( p_demux, "EbmlHead" );\r
-    /* skip it */\r
-    el->SkipData( *p_sys->es, el->Generic().Context );\r
-    delete el;\r
-\r
-    /* Find a segment */\r
-    el = p_sys->es->FindNextID( KaxSegment::ClassInfos, 0xFFFFFFFFL);\r
-    if( el == NULL )\r
-    {\r
-        msg_Err( p_demux, "cannot find KaxSegment" );\r
-        goto error;\r
-    }\r
-    MkvTree( p_demux, 0, "Segment" );\r
-    p_sys->segment = (KaxSegment*)el;\r
-    p_sys->cluster = NULL;\r
-\r
-    p_sys->ep = new EbmlParser( p_sys->es, el );\r
-\r
-    while( ( el1 = p_sys->ep->Get() ) != NULL )\r
-    {\r
-        if( MKV_IS_ID( el1, KaxInfo ) )\r
-        {\r
-            ParseInfo( p_demux, el1 );\r
-        }\r
-        else if( MKV_IS_ID( el1, KaxTracks ) )\r
-        {\r
-            ParseTracks( p_demux, el1 );\r
-        }\r
-        else if( MKV_IS_ID( el1, KaxSeekHead ) )\r
-        {\r
-            ParseSeekHead( p_demux, el1 );\r
-        }\r
-        else if( MKV_IS_ID( el1, KaxCues ) )\r
-        {\r
-            msg_Dbg( p_demux, "|   + Cues" );\r
-        }\r
-        else if( MKV_IS_ID( el1, KaxCluster ) )\r
-        {\r
-            msg_Dbg( p_demux, "|   + Cluster" );\r
-\r
-            p_sys->cluster = (KaxCluster*)el1;\r
-\r
-            p_sys->ep->Down();\r
-            /* stop parsing the stream */\r
-            break;\r
-        }\r
-        else if( MKV_IS_ID( el1, KaxAttachments ) )\r
-        {\r
-            msg_Dbg( p_demux, "|   + Attachments FIXME TODO (but probably never supported)" );\r
-        }\r
-        else if( MKV_IS_ID( el1, KaxChapters ) )\r
-        {\r
-            msg_Dbg( p_demux, "|   + Chapters" );\r
-            ParseChapters( p_demux, el1 );\r
-        }\r
-        else if( MKV_IS_ID( el1, KaxTag ) )\r
-        {\r
-            msg_Dbg( p_demux, "|   + Tags FIXME TODO" );\r
-        }\r
-        else\r
-        {\r
-            msg_Dbg( p_demux, "|   + Unknown (%s)", typeid(*el1).name() );\r
-        }\r
-    }\r
-\r
-    /* get the files from the same dir from the same family (based on p_demux->psz_path) */\r
-    /* _todo_ handle multi-segment files */\r
-    if (p_demux->psz_path[0] != '\0' && (!strcmp(p_demux->psz_access, "") || !strcmp(p_demux->psz_access, "")))\r
-    {\r
-        // assume it's a regular file\r
-        // get the directory path\r
-        s_path = p_demux->psz_path;\r
-        if (s_path.at(s_path.length() - 1) == DIRECTORY_SEPARATOR)\r
-        {\r
-            s_path = s_path.substr(0,s_path.length()-1);\r
-        }\r
-        else\r
-        {\r
-            if (s_path.find_last_of(DIRECTORY_SEPARATOR) > 0) \r
-            {\r
-                s_path = s_path.substr(0,s_path.find_last_of(DIRECTORY_SEPARATOR));\r
-            }\r
-        }\r
-\r
-        struct dirent *p_file_item;\r
-        DIR *p_src_dir = opendir(s_path.c_str());\r
-\r
-        if (p_src_dir != NULL)\r
-        {\r
-            while ((p_file_item = readdir(p_src_dir)))\r
-            {\r
-                if (strlen(p_file_item->d_name) > 4)\r
-                {\r
-                    s_filename = s_path + DIRECTORY_SEPARATOR + p_file_item->d_name;\r
-\r
-                    if (!s_filename.compare(p_demux->psz_path))\r
-                        continue;\r
-\r
-                    if (!s_filename.compare(s_filename.length() - 3, 3, "mkv") || \r
-                        !s_filename.compare(s_filename.length() - 3, 3, "mka"))\r
-                    {\r
-                        // test wether this file belongs to the our family\r
-                        bool b_keep_file_opened = false;\r
-                        StdIOCallback *p_file_io = new StdIOCallback(s_filename.c_str(), MODE_READ);\r
-                        EbmlStream *p_stream = new EbmlStream(*p_file_io);\r
-                        EbmlElement *p_l0, *p_l1, *p_l2;\r
-\r
-                        // verify the EBML Header\r
-                        p_l0 = p_stream->FindNextID(EbmlHead::ClassInfos, 0xFFFFFFFFL);\r
-                        if (p_l0 == NULL)\r
-                        {\r
-                            delete p_stream;\r
-                            delete p_file_io;\r
-                            continue;\r
-                        }\r
-\r
-                        p_l0->SkipData(*p_stream, EbmlHead_Context);\r
-                        delete p_l0;\r
-\r
-                        // find all segments in this file\r
-                        p_l0 = p_stream->FindNextID(KaxSegment::ClassInfos, 0xFFFFFFFFL);\r
-                        if (p_l0 == NULL)\r
-                        {\r
-                            delete p_stream;\r
-                            delete p_file_io;\r
-                            continue;\r
-                        }\r
-\r
-                        i_upper_lvl = 0;\r
-\r
-                        while (p_l0 != 0)\r
-                        {\r
-                            if (EbmlId(*p_l0) == KaxSegment::ClassInfos.GlobalId)\r
-                            {\r
-                                EbmlParser  *ep;\r
-                                KaxSegmentUID *p_uid = NULL;\r
-\r
-                                ep = new EbmlParser(p_stream, p_l0);\r
-                                bool b_this_segment_matches = false;\r
-                                while ((p_l1 = ep->Get()))\r
-                                {\r
-                                    if (MKV_IS_ID(p_l1, KaxInfo))\r
-                                    {\r
-                                        // find the families of this segment\r
-                                        KaxInfo *p_info = static_cast<KaxInfo*>(p_l1);\r
-\r
-                                        p_info->Read(*p_stream, KaxInfo::ClassInfos.Context, i_upper_lvl, p_l2, true);\r
-                                        for( i = 0; i < p_info->ListSize() && !b_this_segment_matches; i++ )\r
-                                        {\r
-                                            EbmlElement *l = (*p_info)[i];\r
-\r
-                                            if( MKV_IS_ID( l, KaxSegmentUID ) )\r
-                                            {\r
-                                                p_uid = static_cast<KaxSegmentUID*>(l);\r
-                                                if (p_sys->segment_uid == *p_uid)\r
-                                                    break;\r
-                                            }\r
-                                            else if( MKV_IS_ID( l, KaxSegmentFamily ) )\r
-                                            {\r
-                                                KaxSegmentFamily *p_fam = static_cast<KaxSegmentFamily*>(l);\r
-                                                for (j=0; j<p_sys->families.size(); j++)\r
-                                                {\r
-                                                    if (p_sys->families.at(j) == *p_fam)\r
-                                                    {\r
-                                                        b_this_segment_matches = true;\r
-                                                        break;\r
-                                                    }\r
-                                                }\r
-                                            }\r
-                                        }\r
-                                        break;\r
-                                    }\r
-                                }\r
-\r
-                                if (b_this_segment_matches)\r
-                                {\r
-                                    b_keep_file_opened = true;\r
-                                }\r
-                            }\r
-\r
-                            p_l0->SkipData(*p_stream, EbmlHead_Context);\r
-                            delete p_l0;\r
-                            p_l0 = p_stream->FindNextID(KaxSegment::ClassInfos, 0xFFFFFFFFL);\r
-                        }\r
-\r
-                        if (!b_keep_file_opened)\r
-                        {\r
-                            delete p_stream;\r
-                            delete p_file_io;\r
-                        }\r
-                    }\r
-                }\r
-            }\r
-            closedir( p_src_dir );\r
-        }\r
-    }\r
-\r
-\r
-    if( p_sys->cluster == NULL )\r
-    {\r
-        msg_Err( p_demux, "cannot find any cluster, damaged file ?" );\r
-        goto error;\r
-    }\r
-\r
-    /* *** Load the cue if found *** */\r
-    if( p_sys->i_cues_position >= 0 )\r
-    {\r
-        vlc_bool_t b_seekable;\r
-\r
-        stream_Control( p_demux->s, STREAM_CAN_FASTSEEK, &b_seekable );\r
-        if( b_seekable )\r
-        {\r
-            LoadCues( p_demux );\r
-        }\r
-    }\r
-\r
-    if( !p_sys->b_cues || p_sys->i_index <= 0 )\r
-    {\r
-        msg_Warn( p_demux, "no cues/empty cues found->seek won't be precise" );\r
-\r
-        IndexAppendCluster( p_demux, p_sys->cluster );\r
-\r
-        p_sys->b_cues = VLC_FALSE;\r
-    }\r
-\r
-    /* add all es */\r
-    msg_Dbg( p_demux, "found %d es", p_sys->i_track );\r
-    for( i_track = 0; i_track < p_sys->i_track; i_track++ )\r
-    {\r
-#define tk  p_sys->track[i_track]\r
-        if( tk.fmt.i_cat == UNKNOWN_ES )\r
-        {\r
-            msg_Warn( p_demux, "invalid track[%d, n=%d]", i_track, tk.i_number );\r
-            tk.p_es = NULL;\r
-            continue;\r
-        }\r
-\r
-        if( !strcmp( tk.psz_codec, "V_MS/VFW/FOURCC" ) )\r
-        {\r
-            if( tk.i_extra_data < (int)sizeof( BITMAPINFOHEADER ) )\r
-            {\r
-                msg_Err( p_demux, "missing/invalid BITMAPINFOHEADER" );\r
-                tk.fmt.i_codec = VLC_FOURCC( 'u', 'n', 'd', 'f' );\r
-            }\r
-            else\r
-            {\r
-                BITMAPINFOHEADER *p_bih = (BITMAPINFOHEADER*)tk.p_extra_data;\r
-\r
-                tk.fmt.video.i_width = GetDWLE( &p_bih->biWidth );\r
-                tk.fmt.video.i_height= GetDWLE( &p_bih->biHeight );\r
-                tk.fmt.i_codec       = GetFOURCC( &p_bih->biCompression );\r
-\r
-                tk.fmt.i_extra       = GetDWLE( &p_bih->biSize ) - sizeof( BITMAPINFOHEADER );\r
-                if( tk.fmt.i_extra > 0 )\r
-                {\r
-                    tk.fmt.p_extra = malloc( tk.fmt.i_extra );\r
-                    memcpy( tk.fmt.p_extra, &p_bih[1], tk.fmt.i_extra );\r
-                }\r
-            }\r
-        }\r
-        else if( !strcmp( tk.psz_codec, "V_MPEG1" ) ||\r
-                 !strcmp( tk.psz_codec, "V_MPEG2" ) )\r
-        {\r
-            tk.fmt.i_codec = VLC_FOURCC( 'm', 'p', 'g', 'v' );\r
-        }\r
-        else if( !strncmp( tk.psz_codec, "V_MPEG4", 7 ) )\r
-        {\r
-            if( !strcmp( tk.psz_codec, "V_MPEG4/MS/V3" ) )\r
-            {\r
-                tk.fmt.i_codec = VLC_FOURCC( 'D', 'I', 'V', '3' );\r
-            }\r
-            else if( !strcmp( tk.psz_codec, "V_MPEG4/ISO/AVC" ) )\r
-            {\r
-                tk.fmt.i_codec = VLC_FOURCC( 'a', 'v', 'c', '1' );\r
-                tk.fmt.b_packetized = VLC_FALSE;\r
-                tk.fmt.i_extra = tk.i_extra_data;\r
-                tk.fmt.p_extra = malloc( tk.i_extra_data );\r
-                memcpy( tk.fmt.p_extra,tk.p_extra_data, tk.i_extra_data );\r
-            }\r
-            else\r
-            {\r
-                tk.fmt.i_codec = VLC_FOURCC( 'm', 'p', '4', 'v' );\r
-            }\r
-        }\r
-        else if( !strcmp( tk.psz_codec, "V_QUICKTIME" ) )\r
-        {\r
-            MP4_Box_t *p_box = (MP4_Box_t*)malloc( sizeof( MP4_Box_t ) );\r
-            stream_t *p_mp4_stream = stream_MemoryNew( VLC_OBJECT(p_demux),\r
-                                                       tk.p_extra_data,\r
-                                                       tk.i_extra_data );\r
-            MP4_ReadBoxCommon( p_mp4_stream, p_box );\r
-            MP4_ReadBox_sample_vide( p_mp4_stream, p_box );\r
-            tk.fmt.i_codec = p_box->i_type;\r
-            tk.fmt.video.i_width = p_box->data.p_sample_vide->i_width;\r
-            tk.fmt.video.i_height = p_box->data.p_sample_vide->i_height;\r
-            tk.fmt.i_extra = p_box->data.p_sample_vide->i_qt_image_description;\r
-            tk.fmt.p_extra = malloc( tk.fmt.i_extra );\r
-            memcpy( tk.fmt.p_extra, p_box->data.p_sample_vide->p_qt_image_description, tk.fmt.i_extra );\r
-            MP4_FreeBox_sample_vide( p_box );\r
-            stream_MemoryDelete( p_mp4_stream, VLC_TRUE );\r
-        }\r
-        else if( !strcmp( tk.psz_codec, "A_MS/ACM" ) )\r
-        {\r
-            if( tk.i_extra_data < (int)sizeof( WAVEFORMATEX ) )\r
-            {\r
-                msg_Err( p_demux, "missing/invalid WAVEFORMATEX" );\r
-                tk.fmt.i_codec = VLC_FOURCC( 'u', 'n', 'd', 'f' );\r
-            }\r
-            else\r
-            {\r
-                WAVEFORMATEX *p_wf = (WAVEFORMATEX*)tk.p_extra_data;\r
-\r
-                wf_tag_to_fourcc( GetWLE( &p_wf->wFormatTag ), &tk.fmt.i_codec, NULL );\r
-\r
-                tk.fmt.audio.i_channels   = GetWLE( &p_wf->nChannels );\r
-                tk.fmt.audio.i_rate = GetDWLE( &p_wf->nSamplesPerSec );\r
-                tk.fmt.i_bitrate    = GetDWLE( &p_wf->nAvgBytesPerSec ) * 8;\r
-                tk.fmt.audio.i_blockalign = GetWLE( &p_wf->nBlockAlign );;\r
-                tk.fmt.audio.i_bitspersample = GetWLE( &p_wf->wBitsPerSample );\r
-\r
-                tk.fmt.i_extra            = GetWLE( &p_wf->cbSize );\r
-                if( tk.fmt.i_extra > 0 )\r
-                {\r
-                    tk.fmt.p_extra = malloc( tk.fmt.i_extra );\r
-                    memcpy( tk.fmt.p_extra, &p_wf[1], tk.fmt.i_extra );\r
-                }\r
-            }\r
-        }\r
-        else if( !strcmp( tk.psz_codec, "A_MPEG/L3" ) ||\r
-                 !strcmp( tk.psz_codec, "A_MPEG/L2" ) ||\r
-                 !strcmp( tk.psz_codec, "A_MPEG/L1" ) )\r
-        {\r
-            tk.fmt.i_codec = VLC_FOURCC( 'm', 'p', 'g', 'a' );\r
-        }\r
-        else if( !strcmp( tk.psz_codec, "A_AC3" ) )\r
-        {\r
-            tk.fmt.i_codec = VLC_FOURCC( 'a', '5', '2', ' ' );\r
-        }\r
-        else if( !strcmp( tk.psz_codec, "A_DTS" ) )\r
-        {\r
-            tk.fmt.i_codec = VLC_FOURCC( 'd', 't', 's', ' ' );\r
-        }\r
-        else if( !strcmp( tk.psz_codec, "A_FLAC" ) )\r
-        {\r
-            tk.fmt.i_codec = VLC_FOURCC( 'f', 'l', 'a', 'c' );\r
-            tk.fmt.i_extra = tk.i_extra_data;\r
-            tk.fmt.p_extra = malloc( tk.i_extra_data );\r
-            memcpy( tk.fmt.p_extra,tk.p_extra_data, tk.i_extra_data );\r
-        }\r
-        else if( !strcmp( tk.psz_codec, "A_VORBIS" ) )\r
-        {\r
-            int i, i_offset = 1, i_size[3], i_extra;\r
-            uint8_t *p_extra;\r
-\r
-            tk.fmt.i_codec = VLC_FOURCC( 'v', 'o', 'r', 'b' );\r
-\r
-            /* Split the 3 headers */\r
-            if( tk.p_extra_data[0] != 0x02 )\r
-                msg_Err( p_demux, "invalid vorbis header" );\r
-\r
-            for( i = 0; i < 2; i++ )\r
-            {\r
-                i_size[i] = 0;\r
-                while( i_offset < tk.i_extra_data )\r
-                {\r
-                    i_size[i] += tk.p_extra_data[i_offset];\r
-                    if( tk.p_extra_data[i_offset++] != 0xff ) break;\r
-                }\r
-            }\r
-\r
-            i_size[0] = __MIN(i_size[0], tk.i_extra_data - i_offset);\r
-            i_size[1] = __MIN(i_size[1], tk.i_extra_data -i_offset -i_size[0]);\r
-            i_size[2] = tk.i_extra_data - i_offset - i_size[0] - i_size[1];\r
-\r
-            tk.fmt.i_extra = 3 * 2 + i_size[0] + i_size[1] + i_size[2];\r
-            tk.fmt.p_extra = malloc( tk.fmt.i_extra );\r
-            p_extra = (uint8_t *)tk.fmt.p_extra; i_extra = 0;\r
-            for( i = 0; i < 3; i++ )\r
-            {\r
-                *(p_extra++) = i_size[i] >> 8;\r
-                *(p_extra++) = i_size[i] & 0xFF;\r
-                memcpy( p_extra, tk.p_extra_data + i_offset + i_extra,\r
-                        i_size[i] );\r
-                p_extra += i_size[i];\r
-                i_extra += i_size[i];\r
-            }\r
-        }\r
-        else if( !strncmp( tk.psz_codec, "A_AAC/MPEG2/", strlen( "A_AAC/MPEG2/" ) ) ||\r
-                 !strncmp( tk.psz_codec, "A_AAC/MPEG4/", strlen( "A_AAC/MPEG4/" ) ) )\r
-        {\r
-            int i_profile, i_srate;\r
-            static unsigned int i_sample_rates[] =\r
-            {\r
-                    96000, 88200, 64000, 48000, 44100, 32000, 24000, 22050,\r
-                        16000, 12000, 11025, 8000,  7350,  0,     0,     0\r
-            };\r
-\r
-            tk.fmt.i_codec = VLC_FOURCC( 'm', 'p', '4', 'a' );\r
-            /* create data for faad (MP4DecSpecificDescrTag)*/\r
-\r
-            if( !strcmp( &tk.psz_codec[12], "MAIN" ) )\r
-            {\r
-                i_profile = 0;\r
-            }\r
-            else if( !strcmp( &tk.psz_codec[12], "LC" ) )\r
-            {\r
-                i_profile = 1;\r
-            }\r
-            else if( !strcmp( &tk.psz_codec[12], "SSR" ) )\r
-            {\r
-                i_profile = 2;\r
-            }\r
-            else\r
-            {\r
-                i_profile = 3;\r
-            }\r
-\r
-            for( i_srate = 0; i_srate < 13; i_srate++ )\r
-            {\r
-                if( i_sample_rates[i_srate] == tk.fmt.audio.i_rate )\r
-                {\r
-                    break;\r
-                }\r
-            }\r
-            msg_Dbg( p_demux, "profile=%d srate=%d", i_profile, i_srate );\r
-\r
-            tk.fmt.i_extra = 2;\r
-            tk.fmt.p_extra = malloc( tk.fmt.i_extra );\r
-            ((uint8_t*)tk.fmt.p_extra)[0] = ((i_profile + 1) << 3) | ((i_srate&0xe) >> 1);\r
-            ((uint8_t*)tk.fmt.p_extra)[1] = ((i_srate & 0x1) << 7) | (tk.fmt.audio.i_channels << 3);\r
-        }\r
-        else if( !strcmp( tk.psz_codec, "A_PCM/INT/BIG" ) ||\r
-                 !strcmp( tk.psz_codec, "A_PCM/INT/LIT" ) ||\r
-                 !strcmp( tk.psz_codec, "A_PCM/FLOAT/IEEE" ) )\r
-        {\r
-            if( !strcmp( tk.psz_codec, "A_PCM/INT/BIG" ) )\r
-            {\r
-                tk.fmt.i_codec = VLC_FOURCC( 't', 'w', 'o', 's' );\r
-            }\r
-            else\r
-            {\r
-                tk.fmt.i_codec = VLC_FOURCC( 'a', 'r', 'a', 'w' );\r
-            }\r
-            tk.fmt.audio.i_blockalign = ( tk.fmt.audio.i_bitspersample + 7 ) / 8 * tk.fmt.audio.i_channels;\r
-        }\r
-        else if( !strcmp( tk.psz_codec, "A_TTA1" ) )\r
-        {\r
-            /* FIXME: support this codec */\r
-            msg_Err( p_demux, "TTA not supported yet[%d, n=%d]", i_track, tk.i_number );\r
-            tk.fmt.i_codec = VLC_FOURCC( 'u', 'n', 'd', 'f' );\r
-        }\r
-        else if( !strcmp( tk.psz_codec, "A_WAVPACK4" ) )\r
-        {\r
-            /* FIXME: support this codec */\r
-            msg_Err( p_demux, "Wavpack not supported yet[%d, n=%d]", i_track, tk.i_number );\r
-            tk.fmt.i_codec = VLC_FOURCC( 'u', 'n', 'd', 'f' );\r
-        }\r
-        else if( !strcmp( tk.psz_codec, "S_TEXT/UTF8" ) )\r
-        {\r
-            tk.fmt.i_codec = VLC_FOURCC( 's', 'u', 'b', 't' );\r
-            tk.fmt.subs.psz_encoding = strdup( "UTF-8" );\r
-        }\r
-        else if( !strcmp( tk.psz_codec, "S_TEXT/SSA" ) ||\r
-                 !strcmp( tk.psz_codec, "S_TEXT/ASS" ) ||\r
-                 !strcmp( tk.psz_codec, "S_SSA" ) ||\r
-                 !strcmp( tk.psz_codec, "S_ASS" ))\r
-        {\r
-            tk.fmt.i_codec = VLC_FOURCC( 's', 's', 'a', ' ' );\r
-            tk.fmt.subs.psz_encoding = strdup( "UTF-8" );\r
-        }\r
-        else if( !strcmp( tk.psz_codec, "S_VOBSUB" ) )\r
-        {\r
-            tk.fmt.i_codec = VLC_FOURCC( 's','p','u',' ' );\r
-            if( tk.i_extra_data )\r
-            {\r
-                char *p_start;\r
-                char *p_buf = (char *)malloc( tk.i_extra_data + 1);\r
-                memcpy( p_buf, tk.p_extra_data , tk.i_extra_data );\r
-                p_buf[tk.i_extra_data] = '\0';\r
-                \r
-                p_start = strstr( p_buf, "size:" );\r
-                if( sscanf( p_start, "size: %dx%d",\r
-                        &tk.fmt.subs.spu.i_original_frame_width, &tk.fmt.subs.spu.i_original_frame_height ) == 2 )\r
-                {\r
-                    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 );\r
-                }\r
-                else\r
-                {\r
-                    msg_Warn( p_demux, "reading original frame size for vobsub failed" );\r
-                }\r
-                free( p_buf );\r
-            }\r
-        }\r
-        else if( !strcmp( tk.psz_codec, "B_VOBBTN" ) )\r
-        {\r
-            /* FIXME: support this codec */\r
-            msg_Err( p_demux, "Vob Buttons not supported yet[%d, n=%d]", i_track, tk.i_number );\r
-            tk.fmt.i_codec = VLC_FOURCC( 'u', 'n', 'd', 'f' );\r
-        }\r
-        else\r
-        {\r
-            msg_Err( p_demux, "unknow codec id=`%s'", tk.psz_codec );\r
-            tk.fmt.i_codec = VLC_FOURCC( 'u', 'n', 'd', 'f' );\r
-        }\r
-        if( tk.b_default )\r
-        {\r
-            tk.fmt.i_priority = 1000;\r
-        }\r
-\r
-        tk.p_es = es_out_Add( p_demux->out, &tk.fmt );\r
-#undef tk\r
-    }\r
-\r
-    /* add information */\r
-    InformationCreate( p_demux );\r
-\r
-    return VLC_SUCCESS;\r
-\r
-error:\r
-    delete p_sys->es;\r
-    delete p_sys->in;\r
-    delete p_sys;\r
-    return VLC_EGENERIC;\r
-}\r
-\r
-/*****************************************************************************\r
- * Close: frees unused data\r
- *****************************************************************************/\r
-static void Close( vlc_object_t *p_this )\r
-{\r
-    demux_t     *p_demux = (demux_t*)p_this;\r
-    demux_sys_t *p_sys   = p_demux->p_sys;\r
-    int         i_track;\r
-\r
-    for( i_track = 0; i_track < p_sys->i_track; i_track++ )\r
-    {\r
-#define tk  p_sys->track[i_track]\r
-        if( tk.fmt.psz_description )\r
-        {\r
-            free( tk.fmt.psz_description );\r
-        }\r
-        if( tk.psz_codec )\r
-        {\r
-            free( tk.psz_codec );\r
-        }\r
-        if( tk.fmt.psz_language )\r
-        {\r
-            free( tk.fmt.psz_language );\r
-        }\r
-#undef tk\r
-    }\r
-    free( p_sys->track );\r
-\r
-    if( p_sys->psz_writing_application  )\r
-    {\r
-        free( p_sys->psz_writing_application );\r
-    }\r
-    if( p_sys->psz_muxing_application  )\r
-    {\r
-        free( p_sys->psz_muxing_application );\r
-    }\r
-\r
-    delete p_sys->segment;\r
-\r
-    delete p_sys->ep;\r
-    delete p_sys->es;\r
-    delete p_sys->in;\r
-    delete p_sys;\r
-}\r
-\r
-/*****************************************************************************\r
- * Control:\r
- *****************************************************************************/\r
-static int Control( demux_t *p_demux, int i_query, va_list args )\r
-{\r
-    demux_sys_t *p_sys = p_demux->p_sys;\r
-    int64_t     *pi64;\r
-    double      *pf, f;\r
-    int         i_skp;\r
-\r
-    vlc_meta_t **pp_meta;\r
-\r
-    switch( i_query )\r
-    {\r
-        case DEMUX_GET_META:\r
-            pp_meta = (vlc_meta_t**)va_arg( args, vlc_meta_t** );\r
-            *pp_meta = vlc_meta_Duplicate( p_sys->meta );\r
-            return VLC_SUCCESS;\r
-\r
-        case DEMUX_GET_LENGTH:\r
-            pi64 = (int64_t*)va_arg( args, int64_t * );\r
-            if( p_sys->f_duration > 0.0 )\r
-            {\r
-                *pi64 = (int64_t)(p_sys->f_duration * 1000);\r
-                return VLC_SUCCESS;\r
-            }\r
-            return VLC_EGENERIC;\r
-\r
-        case DEMUX_GET_POSITION:\r
-            pf = (double*)va_arg( args, double * );\r
-            *pf = (double)p_sys->in->getFilePointer() / (double)stream_Size( p_demux->s );\r
-            return VLC_SUCCESS;\r
-\r
-        case DEMUX_SET_POSITION:\r
-            f = (double)va_arg( args, double );\r
-            Seek( p_demux, -1, (int)(100.0 * f) );\r
-            return VLC_SUCCESS;\r
-\r
-        case DEMUX_GET_TIME:\r
-            pi64 = (int64_t*)va_arg( args, int64_t * );\r
-            if( p_sys->f_duration > 0.0 )\r
-            {\r
-                mtime_t i_duration = (mtime_t)( p_sys->f_duration / 1000 );\r
-\r
-                /* FIXME */\r
-                *pi64 = (mtime_t)1000000 *\r
-                        (mtime_t)i_duration*\r
-                        (mtime_t)p_sys->in->getFilePointer() /\r
-                        (mtime_t)stream_Size( p_demux->s );\r
-                return VLC_SUCCESS;\r
-            }\r
-            return VLC_EGENERIC;\r
-\r
-        case DEMUX_GET_TITLE_INFO:\r
-            if( p_sys->title && p_sys->title->i_seekpoint > 0 )\r
-            {\r
-                input_title_t ***ppp_title = (input_title_t***)va_arg( args, input_title_t*** );\r
-                int *pi_int    = (int*)va_arg( args, int* );\r
-\r
-                *pi_int = 1;\r
-                *ppp_title = (input_title_t**)malloc( sizeof( input_title_t**) );\r
-\r
-                (*ppp_title)[0] = vlc_input_title_Duplicate( p_sys->title );\r
-\r
-                return VLC_SUCCESS;\r
-            }\r
-            return VLC_EGENERIC;\r
-\r
-        case DEMUX_SET_TITLE:\r
-            if( p_sys->title && p_sys->title->i_seekpoint > 0 )\r
-            {\r
-                return VLC_SUCCESS;\r
-            }\r
-            return VLC_EGENERIC;\r
-\r
-        case DEMUX_SET_SEEKPOINT:\r
-            /* FIXME do a better implementation */\r
-            i_skp = (int)va_arg( args, int );\r
-\r
-            if( p_sys->title && i_skp < p_sys->title->i_seekpoint)\r
-            {\r
-                Seek( p_demux, (int64_t)p_sys->title->seekpoint[i_skp]->i_time_offset, -1);\r
-                p_demux->info.i_seekpoint |= INPUT_UPDATE_SEEKPOINT;\r
-                p_demux->info.i_seekpoint = i_skp;\r
-                return VLC_SUCCESS;\r
-            }\r
-            return VLC_EGENERIC;\r
-\r
-\r
-        case DEMUX_SET_TIME:\r
-        case DEMUX_GET_FPS:\r
-        default:\r
-            return VLC_EGENERIC;\r
-    }\r
-}\r
-\r
-static int BlockGet( demux_t *p_demux, KaxBlock **pp_block, int64_t *pi_ref1, int64_t *pi_ref2, int64_t *pi_duration )\r
-{\r
-    demux_sys_t *p_sys = p_demux->p_sys;\r
-\r
-    *pp_block = NULL;\r
-    *pi_ref1  = -1;\r
-    *pi_ref2  = -1;\r
-\r
-    for( ;; )\r
-    {\r
-        EbmlElement *el;\r
-        int         i_level;\r
-\r
-        if( p_demux->b_die )\r
-        {\r
-            return VLC_EGENERIC;\r
-        }\r
-\r
-        el = p_sys->ep->Get();\r
-        i_level = p_sys->ep->GetLevel();\r
-\r
-        if( el == NULL && *pp_block != NULL )\r
-        {\r
-            /* update the index */\r
-#define idx p_sys->index[p_sys->i_index - 1]\r
-            if( p_sys->i_index > 0 && idx.i_time == -1 )\r
-            {\r
-                idx.i_time        = (*pp_block)->GlobalTimecode() / (mtime_t)1000;\r
-                idx.b_key         = *pi_ref1 == -1 ? VLC_TRUE : VLC_FALSE;\r
-            }\r
-#undef idx\r
-            return VLC_SUCCESS;\r
-        }\r
-\r
-        if( el == NULL )\r
-        {\r
-            if( p_sys->ep->GetLevel() > 1 )\r
-            {\r
-                p_sys->ep->Up();\r
-                continue;\r
-            }\r
-            msg_Warn( p_demux, "EOF" );\r
-            return VLC_EGENERIC;\r
-        }\r
-\r
-        /* do parsing */\r
-        if( i_level == 1 )\r
-        {\r
-            if( MKV_IS_ID( el, KaxCluster ) )\r
-            {\r
-                p_sys->cluster = (KaxCluster*)el;\r
-\r
-                /* add it to the index */\r
-                if( p_sys->i_index == 0 ||\r
-                    ( p_sys->i_index > 0 && p_sys->index[p_sys->i_index - 1].i_position < (int64_t)p_sys->cluster->GetElementPosition() ) )\r
-                {\r
-                    IndexAppendCluster( p_demux, p_sys->cluster );\r
-                }\r
-\r
-                p_sys->ep->Down();\r
-            }\r
-            else if( MKV_IS_ID( el, KaxCues ) )\r
-            {\r
-                msg_Warn( p_demux, "find KaxCues FIXME" );\r
-                return VLC_EGENERIC;\r
-            }\r
-            else\r
-            {\r
-                msg_Dbg( p_demux, "unknown (%s)", typeid( el ).name() );\r
-            }\r
-        }\r
-        else if( i_level == 2 )\r
-        {\r
-            if( MKV_IS_ID( el, KaxClusterTimecode ) )\r
-            {\r
-                KaxClusterTimecode &ctc = *(KaxClusterTimecode*)el;\r
-\r
-                ctc.ReadData( p_sys->es->I_O(), SCOPE_ALL_DATA );\r
-                p_sys->cluster->InitTimecode( uint64( ctc ), p_sys->i_timescale );\r
-            }\r
-            else if( MKV_IS_ID( el, KaxBlockGroup ) )\r
-            {\r
-                p_sys->ep->Down();\r
-            }\r
-        }\r
-        else if( i_level == 3 )\r
-        {\r
-            if( MKV_IS_ID( el, KaxBlock ) )\r
-            {\r
-                *pp_block = (KaxBlock*)el;\r
-\r
-                (*pp_block)->ReadData( p_sys->es->I_O() );\r
-                (*pp_block)->SetParent( *p_sys->cluster );\r
-\r
-                p_sys->ep->Keep();\r
-            }\r
-            else if( MKV_IS_ID( el, KaxBlockDuration ) )\r
-            {\r
-                KaxBlockDuration &dur = *(KaxBlockDuration*)el;\r
-\r
-                dur.ReadData( p_sys->es->I_O() );\r
-                *pi_duration = uint64( dur );\r
-            }\r
-            else if( MKV_IS_ID( el, KaxReferenceBlock ) )\r
-            {\r
-                KaxReferenceBlock &ref = *(KaxReferenceBlock*)el;\r
-\r
-                ref.ReadData( p_sys->es->I_O() );\r
-                if( *pi_ref1 == -1 )\r
-                {\r
-                    *pi_ref1 = int64( ref );\r
-                }\r
-                else\r
-                {\r
-                    *pi_ref2 = int64( ref );\r
-                }\r
-            }\r
-        }\r
-        else\r
-        {\r
-            msg_Err( p_demux, "invalid level = %d", i_level );\r
-            return VLC_EGENERIC;\r
-        }\r
-    }\r
-}\r
-\r
-static block_t *MemToBlock( demux_t *p_demux, uint8_t *p_mem, int i_mem)\r
-{\r
-    block_t *p_block;\r
-    if( !(p_block = block_New( p_demux, i_mem ) ) ) return NULL;\r
-    memcpy( p_block->p_buffer, p_mem, i_mem );\r
-    //p_block->i_rate = p_input->stream.control.i_rate;\r
-    return p_block;\r
-}\r
-\r
-static void BlockDecode( demux_t *p_demux, KaxBlock *block, mtime_t i_pts,\r
-                         mtime_t i_duration )\r
-{\r
-    demux_sys_t *p_sys = p_demux->p_sys;\r
-\r
-    int             i_track;\r
-    unsigned int    i;\r
-    vlc_bool_t      b;\r
-\r
-#define tk  p_sys->track[i_track]\r
-    for( i_track = 0; i_track < p_sys->i_track; i_track++ )\r
-    {\r
-        if( tk.i_number == block->TrackNum() )\r
-        {\r
-            break;\r
-        }\r
-    }\r
-\r
-    if( i_track >= p_sys->i_track )\r
-    {\r
-        msg_Err( p_demux, "invalid track number=%d", block->TrackNum() );\r
-        return;\r
-    }\r
-    if( tk.p_es == NULL )\r
-    {\r
-        msg_Err( p_demux, "unknown track number=%d", block->TrackNum() );\r
-        return;\r
-    }\r
-\r
-    es_out_Control( p_demux->out, ES_OUT_GET_ES_STATE, tk.p_es, &b );\r
-    if( !b )\r
-    {\r
-        tk.b_inited = VLC_FALSE;\r
-        return;\r
-    }\r
-\r
-    /* First send init data */\r
-    if( !tk.b_inited && tk.i_data_init > 0 )\r
-    {\r
-        block_t *p_init;\r
-\r
-        msg_Dbg( p_demux, "sending header (%d bytes)", tk.i_data_init );\r
-        p_init = MemToBlock( p_demux, tk.p_data_init, tk.i_data_init );\r
-        if( p_init ) es_out_Send( p_demux->out, tk.p_es, p_init );\r
-    }\r
-    tk.b_inited = VLC_TRUE;\r
-\r
-\r
-    for( i = 0; i < block->NumberFrames(); i++ )\r
-    {\r
-        block_t *p_block;\r
-        DataBuffer &data = block->GetBuffer(i);\r
-\r
-        p_block = MemToBlock( p_demux, data.Buffer(), data.Size() );\r
-\r
-        if( p_block == NULL )\r
-        {\r
-            break;\r
-        }\r
-\r
-#if defined(HAVE_ZLIB_H)\r
-        if( tk.i_compression_type )\r
-        {\r
-            p_block = block_zlib_decompress( VLC_OBJECT(p_demux), p_block );\r
-        }\r
-#endif\r
-\r
-        if( tk.fmt.i_cat != VIDEO_ES )\r
-        {\r
-            p_block->i_dts = p_block->i_pts = i_pts;\r
-        }\r
-        else\r
-        {\r
-            p_block->i_dts = i_pts;\r
-            p_block->i_pts = 0;\r
-        }\r
-\r
-        if( tk.fmt.i_cat == SPU_ES && strcmp( tk.psz_codec, "S_VOBSUB" ) )\r
-        {\r
-            p_block->i_length = i_duration * 1000;\r
-        }\r
-        es_out_Send( p_demux->out, tk.p_es, p_block );\r
-\r
-        /* use time stamp only for first block */\r
-        i_pts = 0;\r
-    }\r
-\r
-#undef tk\r
-}\r
-\r
-static void Seek( demux_t *p_demux, mtime_t i_date, int i_percent)\r
-{\r
-    demux_sys_t *p_sys = p_demux->p_sys;\r
-\r
-    KaxBlock    *block;\r
-    int64_t     i_block_duration;\r
-    int64_t     i_block_ref1;\r
-    int64_t     i_block_ref2;\r
-\r
-    int         i_index = 0;\r
-    int         i_track_skipping;\r
-    int         i_track;\r
-\r
-    msg_Dbg( p_demux, "seek request to "I64Fd" (%d%%)", i_date, i_percent );\r
-    if( i_date < 0 && i_percent < 0 )\r
-    {\r
-        return;\r
-    }\r
-    if( i_percent > 100 ) i_percent = 100;\r
-\r
-    delete p_sys->ep;\r
-    p_sys->ep = new EbmlParser( p_sys->es, p_sys->segment );\r
-    p_sys->cluster = NULL;\r
-\r
-    /* seek without index or without date */\r
-    if( i_percent >= 0 && (config_GetInt( p_demux, "mkv-seek-percent" ) || !p_sys->b_cues || i_date < 0 ))\r
-    {\r
-        if (p_sys->f_duration >= 0)\r
-        {\r
-            i_date = i_percent * p_sys->f_duration * 10;\r
-        }\r
-        else\r
-        {\r
-            int64_t i_pos = i_percent * stream_Size( p_demux->s ) / 100;\r
-\r
-            msg_Dbg( p_demux, "inacurate way of seeking" );\r
-            for( i_index = 0; i_index < p_sys->i_index; i_index++ )\r
-            {\r
-                if( p_sys->index[i_index].i_position >= i_pos)\r
-                {\r
-                    break;\r
-                }\r
-            }\r
-            if( i_index == p_sys->i_index )\r
-            {\r
-                i_index--;\r
-            }\r
-\r
-            i_date = p_sys->index[i_index].i_time;\r
-\r
-#if 0\r
-            if( p_sys->index[i_index].i_position < i_pos )\r
-            {\r
-                EbmlElement *el;\r
-\r
-                msg_Warn( p_demux, "searching for cluster, could take some time" );\r
-\r
-                /* search a cluster */\r
-                while( ( el = p_sys->ep->Get() ) != NULL )\r
-                {\r
-                    if( MKV_IS_ID( el, KaxCluster ) )\r
-                    {\r
-                        KaxCluster *cluster = (KaxCluster*)el;\r
-\r
-                        /* add it to the index */\r
-                        IndexAppendCluster( p_demux, cluster );\r
-\r
-                        if( (int64_t)cluster->GetElementPosition() >= i_pos )\r
-                        {\r
-                            p_sys->cluster = cluster;\r
-                            p_sys->ep->Down();\r
-                            break;\r
-                        }\r
-                    }\r
-                }\r
-            }\r
-#endif\r
-        }\r
-    }\r
-\r
-    for( ; i_index < p_sys->i_index; i_index++ )\r
-    {\r
-        if( p_sys->index[i_index].i_time > i_date )\r
-        {\r
-            break;\r
-        }\r
-    }\r
-\r
-    if( i_index > 0 )\r
-    {\r
-        i_index--;\r
-    }\r
-\r
-    msg_Dbg( p_demux, "seek got "I64Fd" (%d%%)",\r
-                p_sys->index[i_index].i_time,\r
-                (int)( 100 * p_sys->index[i_index].i_position /\r
-                    stream_Size( p_demux->s ) ) );\r
-\r
-    p_sys->in->setFilePointer( p_sys->index[i_index].i_position,\r
-                                seek_beginning );\r
-\r
-\r
-    /* now parse until key frame */\r
-#define tk  p_sys->track[i_track]\r
-    i_track_skipping = 0;\r
-    for( i_track = 0; i_track < p_sys->i_track; i_track++ )\r
-    {\r
-        if( tk.fmt.i_cat == VIDEO_ES )\r
-        {\r
-            tk.b_search_keyframe = VLC_TRUE;\r
-            i_track_skipping++;\r
-        }\r
-    }\r
-\r
-    p_sys->i_start_pts = i_date;\r
-\r
-    while( i_track_skipping > 0 )\r
-    {\r
-        if( BlockGet( p_demux, &block, &i_block_ref1, &i_block_ref2, &i_block_duration ) )\r
-        {\r
-            msg_Warn( p_demux, "cannot get block EOF?" );\r
-\r
-            return;\r
-        }\r
-\r
-        p_sys->i_pts = block->GlobalTimecode() / (mtime_t) 1000;\r
-\r
-        for( i_track = 0; i_track < p_sys->i_track; i_track++ )\r
-        {\r
-            if( tk.i_number == block->TrackNum() )\r
-            {\r
-                break;\r
-            }\r
-        }\r
-\r
-        if( i_track < p_sys->i_track )\r
-        {\r
-            if( tk.fmt.i_cat == VIDEO_ES )\r
-            {\r
-                if( i_block_ref1 == -1 && tk.b_search_keyframe )\r
-                {\r
-                    tk.b_search_keyframe = VLC_FALSE;\r
-                    i_track_skipping--;\r
-                }\r
-                if( !tk.b_search_keyframe )\r
-                {\r
-                    BlockDecode( p_demux, block, 0, 0 );\r
-/*                    es_out_Control( p_demux->out, ES_OUT_SET_PCR, block->GlobalTimecode() / (mtime_t) 1000 );*/\r
-                }\r
-            }\r
-        }\r
-\r
-        delete block;\r
-    }\r
-#undef tk\r
-}\r
-\r
-/*****************************************************************************\r
- * Demux: reads and demuxes data packets\r
- *****************************************************************************\r
- * Returns -1 in case of error, 0 in case of EOF, 1 otherwise\r
- *****************************************************************************/\r
-static int Demux( demux_t *p_demux)\r
-{\r
-    demux_sys_t *p_sys = p_demux->p_sys;\r
-    mtime_t        i_start_pts;\r
-    int            i_block_count = 0;\r
-\r
-    KaxBlock *block;\r
-    int64_t i_block_duration;\r
-    int64_t i_block_ref1;\r
-    int64_t i_block_ref2;\r
-\r
-    i_start_pts = -1;\r
-\r
-    for( ;; )\r
-    {\r
-        if( BlockGet( p_demux, &block, &i_block_ref1, &i_block_ref2, &i_block_duration ) )\r
-        {\r
-            msg_Warn( p_demux, "cannot get block EOF?" );\r
-\r
-            return 0;\r
-        }\r
-\r
-        p_sys->i_pts = block->GlobalTimecode() / (mtime_t) 1000;\r
-\r
-        if( p_sys->i_pts >= p_sys->i_start_pts  )\r
-        {\r
-            es_out_Control( p_demux->out, ES_OUT_SET_PCR, p_sys->i_pts );\r
-        }\r
-\r
-        BlockDecode( p_demux, block, p_sys->i_pts, i_block_duration );\r
-\r
-        delete block;\r
-        i_block_count++;\r
-\r
-        if( p_sys->i_pts > i_start_pts + (mtime_t)100000 || i_block_count > 5 )\r
-        {\r
-            return 1;\r
-        }\r
-    }\r
-}\r
-\r
-\r
-\r
-/*****************************************************************************\r
- * Stream managment\r
- *****************************************************************************/\r
-vlc_stream_io_callback::vlc_stream_io_callback( stream_t *s_ )\r
-{\r
-    s = s_;\r
-    mb_eof = VLC_FALSE;\r
-}\r
-\r
-uint32 vlc_stream_io_callback::read( void *p_buffer, size_t i_size )\r
-{\r
-    if( i_size <= 0 || mb_eof )\r
-    {\r
-        return 0;\r
-    }\r
-\r
-    return stream_Read( s, p_buffer, i_size );\r
-}\r
-void vlc_stream_io_callback::setFilePointer(int64_t i_offset, seek_mode mode )\r
-{\r
-    int64_t i_pos;\r
-\r
-    switch( mode )\r
-    {\r
-        case seek_beginning:\r
-            i_pos = i_offset;\r
-            break;\r
-        case seek_end:\r
-            i_pos = stream_Size( s ) - i_offset;\r
-            break;\r
-        default:\r
-            i_pos= stream_Tell( s ) + i_offset;\r
-            break;\r
-    }\r
-\r
-    if( i_pos < 0 || i_pos >= stream_Size( s ) )\r
-    {\r
-        mb_eof = VLC_TRUE;\r
-        return;\r
-    }\r
-\r
-    mb_eof = VLC_FALSE;\r
-    if( stream_Seek( s, i_pos ) )\r
-    {\r
-        mb_eof = VLC_TRUE;\r
-    }\r
-    return;\r
-}\r
-size_t vlc_stream_io_callback::write( const void *p_buffer, size_t i_size )\r
-{\r
-    return 0;\r
-}\r
-uint64 vlc_stream_io_callback::getFilePointer( void )\r
-{\r
-    return stream_Tell( s );\r
-}\r
-void vlc_stream_io_callback::close( void )\r
-{\r
-    return;\r
-}\r
-\r
-\r
-/*****************************************************************************\r
- * Ebml Stream parser\r
- *****************************************************************************/\r
-EbmlParser::EbmlParser( EbmlStream *es, EbmlElement *el_start )\r
-{\r
-    int i;\r
-\r
-    m_es = es;\r
-    m_got = NULL;\r
-    m_el[0] = el_start;\r
-\r
-    for( i = 1; i < 6; i++ )\r
-    {\r
-        m_el[i] = NULL;\r
-    }\r
-    mi_level = 1;\r
-    mi_user_level = 1;\r
-    mb_keep = VLC_FALSE;\r
-}\r
-\r
-EbmlParser::~EbmlParser( void )\r
-{\r
-    int i;\r
-\r
-    for( i = 1; i < mi_level; i++ )\r
-    {\r
-        if( !mb_keep )\r
-        {\r
-            delete m_el[i];\r
-        }\r
-        mb_keep = VLC_FALSE;\r
-    }\r
-}\r
-\r
-void EbmlParser::Up( void )\r
-{\r
-    if( mi_user_level == mi_level )\r
-    {\r
-        fprintf( stderr," arrrrrrrrrrrrrg Up cannot escape itself\n" );\r
-    }\r
-\r
-    mi_user_level--;\r
-}\r
-\r
-void EbmlParser::Down( void )\r
-{\r
-    mi_user_level++;\r
-    mi_level++;\r
-}\r
-\r
-void EbmlParser::Keep( void )\r
-{\r
-    mb_keep = VLC_TRUE;\r
-}\r
-\r
-int EbmlParser::GetLevel( void )\r
-{\r
-    return mi_user_level;\r
-}\r
-\r
-EbmlElement *EbmlParser::Get( void )\r
-{\r
-    int i_ulev = 0;\r
-\r
-    if( mi_user_level != mi_level )\r
-    {\r
-        return NULL;\r
-    }\r
-    if( m_got )\r
-    {\r
-        EbmlElement *ret = m_got;\r
-        m_got = NULL;\r
-\r
-        return ret;\r
-    }\r
-\r
-    if( m_el[mi_level] )\r
-    {\r
-        m_el[mi_level]->SkipData( *m_es, m_el[mi_level]->Generic().Context );\r
-        if( !mb_keep )\r
-        {\r
-            delete m_el[mi_level];\r
-        }\r
-        mb_keep = VLC_FALSE;\r
-    }\r
-\r
-    m_el[mi_level] = m_es->FindNextElement( m_el[mi_level - 1]->Generic().Context, i_ulev, 0xFFFFFFFFL, true, 1 );\r
-    if( i_ulev > 0 )\r
-    {\r
-        while( i_ulev > 0 )\r
-        {\r
-            if( mi_level == 1 )\r
-            {\r
-                mi_level = 0;\r
-                return NULL;\r
-            }\r
-\r
-            delete m_el[mi_level - 1];\r
-            m_got = m_el[mi_level -1] = m_el[mi_level];\r
-            m_el[mi_level] = NULL;\r
-\r
-            mi_level--;\r
-            i_ulev--;\r
-        }\r
-        return NULL;\r
-    }\r
-    else if( m_el[mi_level] == NULL )\r
-    {\r
-        fprintf( stderr," m_el[mi_level] == NULL\n" );\r
-    }\r
-\r
-    return m_el[mi_level];\r
-}\r
-\r
-\r
-/*****************************************************************************\r
- * Tools\r
- *  * LoadCues : load the cues element and update index\r
- *\r
- *  * LoadTags : load ... the tags element\r
- *\r
- *  * InformationCreate : create all information, load tags if present\r
- *\r
- *****************************************************************************/\r
-static void LoadCues( demux_t *p_demux )\r
-{\r
-    demux_sys_t *p_sys = p_demux->p_sys;\r
-    int64_t     i_sav_position = p_sys->in->getFilePointer();\r
-    EbmlParser  *ep;\r
-    EbmlElement *el, *cues;\r
-\r
-    msg_Dbg( p_demux, "loading cues" );\r
-    p_sys->in->setFilePointer( p_sys->i_cues_position, seek_beginning );\r
-    cues = p_sys->es->FindNextID( KaxCues::ClassInfos, 0xFFFFFFFFL);\r
-\r
-    if( cues == NULL )\r
-    {\r
-        msg_Err( p_demux, "cannot load cues (broken seekhead or file)" );\r
-        p_sys->in->setFilePointer( i_sav_position, seek_beginning );\r
-        return;\r
-    }\r
-\r
-    ep = new EbmlParser( p_sys->es, cues );\r
-    while( ( el = ep->Get() ) != NULL )\r
-    {\r
-        if( MKV_IS_ID( el, KaxCuePoint ) )\r
-        {\r
-#define idx p_sys->index[p_sys->i_index]\r
-\r
-            idx.i_track       = -1;\r
-            idx.i_block_number= -1;\r
-            idx.i_position    = -1;\r
-            idx.i_time        = 0;\r
-            idx.b_key         = VLC_TRUE;\r
-\r
-            ep->Down();\r
-            while( ( el = ep->Get() ) != NULL )\r
-            {\r
-                if( MKV_IS_ID( el, KaxCueTime ) )\r
-                {\r
-                    KaxCueTime &ctime = *(KaxCueTime*)el;\r
-\r
-                    ctime.ReadData( p_sys->es->I_O() );\r
-\r
-                    idx.i_time = uint64( ctime ) * p_sys->i_timescale / (mtime_t)1000;\r
-                }\r
-                else if( MKV_IS_ID( el, KaxCueTrackPositions ) )\r
-                {\r
-                    ep->Down();\r
-                    while( ( el = ep->Get() ) != NULL )\r
-                    {\r
-                        if( MKV_IS_ID( el, KaxCueTrack ) )\r
-                        {\r
-                            KaxCueTrack &ctrack = *(KaxCueTrack*)el;\r
-\r
-                            ctrack.ReadData( p_sys->es->I_O() );\r
-                            idx.i_track = uint16( ctrack );\r
-                        }\r
-                        else if( MKV_IS_ID( el, KaxCueClusterPosition ) )\r
-                        {\r
-                            KaxCueClusterPosition &ccpos = *(KaxCueClusterPosition*)el;\r
-\r
-                            ccpos.ReadData( p_sys->es->I_O() );\r
-                            idx.i_position = p_sys->segment->GetGlobalPosition( uint64( ccpos ) );\r
-                        }\r
-                        else if( MKV_IS_ID( el, KaxCueBlockNumber ) )\r
-                        {\r
-                            KaxCueBlockNumber &cbnum = *(KaxCueBlockNumber*)el;\r
-\r
-                            cbnum.ReadData( p_sys->es->I_O() );\r
-                            idx.i_block_number = uint32( cbnum );\r
-                        }\r
-                        else\r
-                        {\r
-                            msg_Dbg( p_demux, "         * Unknown (%s)", typeid(*el).name() );\r
-                        }\r
-                    }\r
-                    ep->Up();\r
-                }\r
-                else\r
-                {\r
-                    msg_Dbg( p_demux, "     * Unknown (%s)", typeid(*el).name() );\r
-                }\r
-            }\r
-            ep->Up();\r
-\r
-#if 0\r
-            msg_Dbg( p_demux, " * added time="I64Fd" pos="I64Fd\r
-                     " track=%d bnum=%d", idx.i_time, idx.i_position,\r
-                     idx.i_track, idx.i_block_number );\r
-#endif\r
-\r
-            p_sys->i_index++;\r
-            if( p_sys->i_index >= p_sys->i_index_max )\r
-            {\r
-                p_sys->i_index_max += 1024;\r
-                p_sys->index = (mkv_index_t*)realloc( p_sys->index, sizeof( mkv_index_t ) * p_sys->i_index_max );\r
-            }\r
-#undef idx\r
-        }\r
-        else\r
-        {\r
-            msg_Dbg( p_demux, " * Unknown (%s)", typeid(*el).name() );\r
-        }\r
-    }\r
-    delete ep;\r
-    delete cues;\r
-\r
-    p_sys->b_cues = VLC_TRUE;\r
-\r
-    msg_Dbg( p_demux, "loading cues done." );\r
-    p_sys->in->setFilePointer( i_sav_position, seek_beginning );\r
-}\r
-\r
-static void LoadTags( demux_t *p_demux )\r
-{\r
-    demux_sys_t *p_sys = p_demux->p_sys;\r
-    int64_t     i_sav_position = p_sys->in->getFilePointer();\r
-    EbmlParser  *ep;\r
-    EbmlElement *el, *tags;\r
-\r
-    msg_Dbg( p_demux, "loading tags" );\r
-    p_sys->in->setFilePointer( p_sys->i_tags_position, seek_beginning );\r
-    tags = p_sys->es->FindNextID( KaxTags::ClassInfos, 0xFFFFFFFFL);\r
-\r
-    if( tags == NULL )\r
-    {\r
-        msg_Err( p_demux, "cannot load tags (broken seekhead or file)" );\r
-        p_sys->in->setFilePointer( i_sav_position, seek_beginning );\r
-        return;\r
-    }\r
-\r
-    msg_Dbg( p_demux, "Tags" );\r
-    ep = new EbmlParser( p_sys->es, tags );\r
-    while( ( el = ep->Get() ) != NULL )\r
-    {\r
-        if( MKV_IS_ID( el, KaxTag ) )\r
-        {\r
-            msg_Dbg( p_demux, "+ Tag" );\r
-            ep->Down();\r
-            while( ( el = ep->Get() ) != NULL )\r
-            {\r
-                if( MKV_IS_ID( el, KaxTagTargets ) )\r
-                {\r
-                    msg_Dbg( p_demux, "|   + Targets" );\r
-                    ep->Down();\r
-                    while( ( el = ep->Get() ) != NULL )\r
-                    {\r
-                        msg_Dbg( p_demux, "|   |   + Unknown (%s)", typeid( *el ).name() );\r
-                    }\r
-                    ep->Up();\r
-                }\r
-                else if( MKV_IS_ID( el, KaxTagGeneral ) )\r
-                {\r
-                    msg_Dbg( p_demux, "|   + General" );\r
-                    ep->Down();\r
-                    while( ( el = ep->Get() ) != NULL )\r
-                    {\r
-                        msg_Dbg( p_demux, "|   |   + Unknown (%s)", typeid( *el ).name() );\r
-                    }\r
-                    ep->Up();\r
-                }\r
-                else if( MKV_IS_ID( el, KaxTagGenres ) )\r
-                {\r
-                    msg_Dbg( p_demux, "|   + Genres" );\r
-                    ep->Down();\r
-                    while( ( el = ep->Get() ) != NULL )\r
-                    {\r
-                        msg_Dbg( p_demux, "|   |   + Unknown (%s)", typeid( *el ).name() );\r
-                    }\r
-                    ep->Up();\r
-                }\r
-                else if( MKV_IS_ID( el, KaxTagAudioSpecific ) )\r
-                {\r
-                    msg_Dbg( p_demux, "|   + Audio Specific" );\r
-                    ep->Down();\r
-                    while( ( el = ep->Get() ) != NULL )\r
-                    {\r
-                        msg_Dbg( p_demux, "|   |   + Unknown (%s)", typeid( *el ).name() );\r
-                    }\r
-                    ep->Up();\r
-                }\r
-                else if( MKV_IS_ID( el, KaxTagImageSpecific ) )\r
-                {\r
-                    msg_Dbg( p_demux, "|   + Images Specific" );\r
-                    ep->Down();\r
-                    while( ( el = ep->Get() ) != NULL )\r
-                    {\r
-                        msg_Dbg( p_demux, "|   |   + Unknown (%s)", typeid( *el ).name() );\r
-                    }\r
-                    ep->Up();\r
-                }\r
-                else if( MKV_IS_ID( el, KaxTagMultiComment ) )\r
-                {\r
-                    msg_Dbg( p_demux, "|   + Multi Comment" );\r
-                }\r
-                else if( MKV_IS_ID( el, KaxTagMultiCommercial ) )\r
-                {\r
-                    msg_Dbg( p_demux, "|   + Multi Commercial" );\r
-                }\r
-                else if( MKV_IS_ID( el, KaxTagMultiDate ) )\r
-                {\r
-                    msg_Dbg( p_demux, "|   + Multi Date" );\r
-                }\r
-                else if( MKV_IS_ID( el, KaxTagMultiEntity ) )\r
-                {\r
-                    msg_Dbg( p_demux, "|   + Multi Entity" );\r
-                }\r
-                else if( MKV_IS_ID( el, KaxTagMultiIdentifier ) )\r
-                {\r
-                    msg_Dbg( p_demux, "|   + Multi Identifier" );\r
-                }\r
-                else if( MKV_IS_ID( el, KaxTagMultiLegal ) )\r
-                {\r
-                    msg_Dbg( p_demux, "|   + Multi Legal" );\r
-                }\r
-                else if( MKV_IS_ID( el, KaxTagMultiTitle ) )\r
-                {\r
-                    msg_Dbg( p_demux, "|   + Multi Title" );\r
-                }\r
-                else\r
-                {\r
-                    msg_Dbg( p_demux, "|   + Unknown (%s)", typeid( *el ).name() );\r
-                }\r
-            }\r
-            ep->Up();\r
-        }\r
-        else\r
-        {\r
-            msg_Dbg( p_demux, "+ Unknown (%s)", typeid( *el ).name() );\r
-        }\r
-    }\r
-    delete ep;\r
-    delete tags;\r
-\r
-    msg_Dbg( p_demux, "loading tags done." );\r
-    p_sys->in->setFilePointer( i_sav_position, seek_beginning );\r
-}\r
-\r
-/*****************************************************************************\r
- * ParseInfo:\r
- *****************************************************************************/\r
-static void ParseSeekHead( demux_t *p_demux, EbmlElement *seekhead )\r
-{\r
-    demux_sys_t *p_sys = p_demux->p_sys;\r
-    EbmlElement *el;\r
-    EbmlMaster  *m;\r
-    unsigned int i;\r
-    int i_upper_level = 0;\r
-\r
-    msg_Dbg( p_demux, "|   + Seek head" );\r
-\r
-    /* Master elements */\r
-    m = static_cast<EbmlMaster *>(seekhead);\r
-    m->Read( *p_sys->es, seekhead->Generic().Context, i_upper_level, el, true );\r
-\r
-    for( i = 0; i < m->ListSize(); i++ )\r
-    {\r
-        EbmlElement *l = (*m)[i];\r
-\r
-        if( MKV_IS_ID( l, KaxSeek ) )\r
-        {\r
-            EbmlMaster *sk = static_cast<EbmlMaster *>(l);\r
-            EbmlId id = EbmlVoid::ClassInfos.GlobalId;\r
-            int64_t i_pos = -1;\r
-\r
-            unsigned int j;\r
-\r
-            for( j = 0; j < sk->ListSize(); j++ )\r
-            {\r
-                EbmlElement *l = (*sk)[j];\r
-\r
-                if( MKV_IS_ID( l, KaxSeekID ) )\r
-                {\r
-                    KaxSeekID &sid = *(KaxSeekID*)l;\r
-                    id = EbmlId( sid.GetBuffer(), sid.GetSize() );\r
-                }\r
-                else if( MKV_IS_ID( l, KaxSeekPosition ) )\r
-                {\r
-                    KaxSeekPosition &spos = *(KaxSeekPosition*)l;\r
-                    i_pos = uint64( spos );\r
-                }\r
-                else\r
-                {\r
-                    msg_Dbg( p_demux, "|   |   |   + Unknown (%s)", typeid(*l).name() );\r
-                }\r
-            }\r
-\r
-            if( i_pos >= 0 )\r
-            {\r
-                if( id == KaxCues::ClassInfos.GlobalId )\r
-                {\r
-                    msg_Dbg( p_demux, "|   |   |   = cues at "I64Fd, i_pos );\r
-                    p_sys->i_cues_position = p_sys->segment->GetGlobalPosition( i_pos );\r
-                }\r
-                else if( id == KaxChapters::ClassInfos.GlobalId )\r
-                {\r
-                    msg_Dbg( p_demux, "|   |   |   = chapters at "I64Fd, i_pos );\r
-                    p_sys->i_chapters_position = p_sys->segment->GetGlobalPosition( i_pos );\r
-                }\r
-                else if( id == KaxTags::ClassInfos.GlobalId )\r
-                {\r
-                    msg_Dbg( p_demux, "|   |   |   = tags at "I64Fd, i_pos );\r
-                    p_sys->i_tags_position = p_sys->segment->GetGlobalPosition( i_pos );\r
-                }\r
-            }\r
-        }\r
-        else\r
-        {\r
-            msg_Dbg( p_demux, "|   |   + Unknown (%s)", typeid(*l).name() );\r
-        }\r
-    }\r
-}\r
-\r
-/*****************************************************************************\r
- * ParseTracks:\r
- *****************************************************************************/\r
-static void ParseTrackEntry( demux_t *p_demux, EbmlMaster *m )\r
-{\r
-    demux_sys_t *p_sys = p_demux->p_sys;\r
-    unsigned int i;\r
-\r
-    mkv_track_t *tk;\r
-\r
-    msg_Dbg( p_demux, "|   |   + Track Entry" );\r
-\r
-    p_sys->i_track++;\r
-    p_sys->track = (mkv_track_t*)realloc( p_sys->track, sizeof( mkv_track_t ) * (p_sys->i_track + 1 ) );\r
-\r
-    /* Init the track */\r
-    tk = &p_sys->track[p_sys->i_track - 1];\r
-\r
-    memset( tk, 0, sizeof( mkv_track_t ) );\r
-\r
-    es_format_Init( &tk->fmt, UNKNOWN_ES, 0 );\r
-    tk->fmt.psz_language = strdup("English");\r
-    tk->fmt.psz_description = NULL;\r
-\r
-    tk->b_default = VLC_TRUE;\r
-    tk->b_enabled = VLC_TRUE;\r
-    tk->i_number = p_sys->i_track - 1;\r
-    tk->i_extra_data = 0;\r
-    tk->p_extra_data = NULL;\r
-    tk->psz_codec = NULL;\r
-    tk->i_default_duration = 0;\r
-    tk->f_timecodescale = 1.0;\r
-\r
-    tk->b_inited = VLC_FALSE;\r
-    tk->i_data_init = 0;\r
-    tk->p_data_init = NULL;\r
-\r
-    tk->psz_codec_name = NULL;\r
-    tk->psz_codec_settings = NULL;\r
-    tk->psz_codec_info_url = NULL;\r
-    tk->psz_codec_download_url = NULL;\r
-    \r
-    tk->i_compression_type = MATROSKA_COMPRESSION_NONE;\r
-\r
-    for( i = 0; i < m->ListSize(); i++ )\r
-    {\r
-        EbmlElement *l = (*m)[i];\r
-\r
-        if( MKV_IS_ID( l, KaxTrackNumber ) )\r
-        {\r
-            KaxTrackNumber &tnum = *(KaxTrackNumber*)l;\r
-\r
-            tk->i_number = uint32( tnum );\r
-            msg_Dbg( p_demux, "|   |   |   + Track Number=%u", uint32( tnum ) );\r
-        }\r
-        else  if( MKV_IS_ID( l, KaxTrackUID ) )\r
-        {\r
-            KaxTrackUID &tuid = *(KaxTrackUID*)l;\r
-\r
-            msg_Dbg( p_demux, "|   |   |   + Track UID=%u",  uint32( tuid ) );\r
-        }\r
-        else  if( MKV_IS_ID( l, KaxTrackType ) )\r
-        {\r
-            char *psz_type;\r
-            KaxTrackType &ttype = *(KaxTrackType*)l;\r
-\r
-            switch( uint8(ttype) )\r
-            {\r
-                case track_audio:\r
-                    psz_type = "audio";\r
-                    tk->fmt.i_cat = AUDIO_ES;\r
-                    break;\r
-                case track_video:\r
-                    psz_type = "video";\r
-                    tk->fmt.i_cat = VIDEO_ES;\r
-                    break;\r
-                case track_subtitle:\r
-                    psz_type = "subtitle";\r
-                    tk->fmt.i_cat = SPU_ES;\r
-                    break;\r
-                default:\r
-                    psz_type = "unknown";\r
-                    tk->fmt.i_cat = UNKNOWN_ES;\r
-                    break;\r
-            }\r
-\r
-            msg_Dbg( p_demux, "|   |   |   + Track Type=%s", psz_type );\r
-        }\r
-//        else  if( EbmlId( *l ) == KaxTrackFlagEnabled::ClassInfos.GlobalId )\r
-//        {\r
-//            KaxTrackFlagEnabled &fenb = *(KaxTrackFlagEnabled*)l;\r
-\r
-//            tk->b_enabled = uint32( fenb );\r
-//            msg_Dbg( p_demux, "|   |   |   + Track Enabled=%u",\r
-//                     uint32( fenb )  );\r
-//        }\r
-        else  if( MKV_IS_ID( l, KaxTrackFlagDefault ) )\r
-        {\r
-            KaxTrackFlagDefault &fdef = *(KaxTrackFlagDefault*)l;\r
-\r
-            tk->b_default = uint32( fdef );\r
-            msg_Dbg( p_demux, "|   |   |   + Track Default=%u", uint32( fdef )  );\r
-        }\r
-        else  if( MKV_IS_ID( l, KaxTrackFlagLacing ) )\r
-        {\r
-            KaxTrackFlagLacing &lac = *(KaxTrackFlagLacing*)l;\r
-\r
-            msg_Dbg( p_demux, "|   |   |   + Track Lacing=%d", uint32( lac ) );\r
-        }\r
-        else  if( MKV_IS_ID( l, KaxTrackMinCache ) )\r
-        {\r
-            KaxTrackMinCache &cmin = *(KaxTrackMinCache*)l;\r
-\r
-            msg_Dbg( p_demux, "|   |   |   + Track MinCache=%d", uint32( cmin ) );\r
-        }\r
-        else  if( MKV_IS_ID( l, KaxTrackMaxCache ) )\r
-        {\r
-            KaxTrackMaxCache &cmax = *(KaxTrackMaxCache*)l;\r
-\r
-            msg_Dbg( p_demux, "|   |   |   + Track MaxCache=%d", uint32( cmax ) );\r
-        }\r
-        else  if( MKV_IS_ID( l, KaxTrackDefaultDuration ) )\r
-        {\r
-            KaxTrackDefaultDuration &defd = *(KaxTrackDefaultDuration*)l;\r
-\r
-            tk->i_default_duration = uint64(defd);\r
-            msg_Dbg( p_demux, "|   |   |   + Track Default Duration="I64Fd, uint64(defd) );\r
-        }\r
-        else  if( MKV_IS_ID( l, KaxTrackTimecodeScale ) )\r
-        {\r
-            KaxTrackTimecodeScale &ttcs = *(KaxTrackTimecodeScale*)l;\r
-\r
-            tk->f_timecodescale = float( ttcs );\r
-            msg_Dbg( p_demux, "|   |   |   + Track TimeCodeScale=%f", tk->f_timecodescale );\r
-        }\r
-        else if( MKV_IS_ID( l, KaxTrackName ) )\r
-        {\r
-            KaxTrackName &tname = *(KaxTrackName*)l;\r
-\r
-            tk->fmt.psz_description = UTF8ToStr( UTFstring( tname ) );\r
-            msg_Dbg( p_demux, "|   |   |   + Track Name=%s", tk->fmt.psz_description );\r
-        }\r
-        else  if( MKV_IS_ID( l, KaxTrackLanguage ) )\r
-        {\r
-            KaxTrackLanguage &lang = *(KaxTrackLanguage*)l;\r
-\r
-            tk->fmt.psz_language = strdup( string( lang ).c_str() );\r
-            msg_Dbg( p_demux,\r
-                     "|   |   |   + Track Language=`%s'", tk->fmt.psz_language );\r
-        }\r
-        else  if( MKV_IS_ID( l, KaxCodecID ) )\r
-        {\r
-            KaxCodecID &codecid = *(KaxCodecID*)l;\r
-\r
-            tk->psz_codec = strdup( string( codecid ).c_str() );\r
-            msg_Dbg( p_demux, "|   |   |   + Track CodecId=%s", string( codecid ).c_str() );\r
-        }\r
-        else  if( MKV_IS_ID( l, KaxCodecPrivate ) )\r
-        {\r
-            KaxCodecPrivate &cpriv = *(KaxCodecPrivate*)l;\r
-\r
-            tk->i_extra_data = cpriv.GetSize();\r
-            if( tk->i_extra_data > 0 )\r
-            {\r
-                tk->p_extra_data = (uint8_t*)malloc( tk->i_extra_data );\r
-                memcpy( tk->p_extra_data, cpriv.GetBuffer(), tk->i_extra_data );\r
-            }\r
-            msg_Dbg( p_demux, "|   |   |   + Track CodecPrivate size="I64Fd, cpriv.GetSize() );\r
-        }\r
-        else if( MKV_IS_ID( l, KaxCodecName ) )\r
-        {\r
-            KaxCodecName &cname = *(KaxCodecName*)l;\r
-\r
-            tk->psz_codec_name = UTF8ToStr( UTFstring( cname ) );\r
-            msg_Dbg( p_demux, "|   |   |   + Track Codec Name=%s", tk->psz_codec_name );\r
-        }\r
-        else if( MKV_IS_ID( l, KaxContentEncodings ) )\r
-        {\r
-            EbmlMaster *cencs = static_cast<EbmlMaster*>(l);\r
-            MkvTree( p_demux, 3, "Content Encodings" );\r
-            for( unsigned int i = 0; i < cencs->ListSize(); i++ )\r
-            {\r
-                EbmlElement *l2 = (*cencs)[i];\r
-                if( MKV_IS_ID( l2, KaxContentEncoding ) )\r
-                {\r
-                    MkvTree( p_demux, 4, "Content Encoding" );\r
-                    EbmlMaster *cenc = static_cast<EbmlMaster*>(l2);\r
-                    for( unsigned int i = 0; i < cenc->ListSize(); i++ )\r
-                    {\r
-                        EbmlElement *l3 = (*cenc)[i];\r
-                        if( MKV_IS_ID( l3, KaxContentEncodingOrder ) )\r
-                        {\r
-                            KaxContentEncodingOrder &encord = *(KaxContentEncodingOrder*)l3;\r
-                            MkvTree( p_demux, 5, "Order: %i", uint32( encord ) );\r
-                        }\r
-                        else if( MKV_IS_ID( l3, KaxContentEncodingScope ) )\r
-                        {\r
-                            KaxContentEncodingScope &encscope = *(KaxContentEncodingScope*)l3;\r
-                            MkvTree( p_demux, 5, "Scope: %i", uint32( encscope ) );\r
-                        }\r
-                        else if( MKV_IS_ID( l3, KaxContentEncodingType ) )\r
-                        {\r
-                            KaxContentEncodingType &enctype = *(KaxContentEncodingType*)l3;\r
-                            MkvTree( p_demux, 5, "Type: %i", uint32( enctype ) );\r
-                        }\r
-                        else if( MKV_IS_ID( l3, KaxContentCompression ) )\r
-                        {\r
-                            EbmlMaster *compr = static_cast<EbmlMaster*>(l3);\r
-                            MkvTree( p_demux, 5, "Content Compression" );\r
-                            for( unsigned int i = 0; i < compr->ListSize(); i++ )\r
-                            {\r
-                                EbmlElement *l4 = (*compr)[i];\r
-                                if( MKV_IS_ID( l4, KaxContentCompAlgo ) )\r
-                                {\r
-                                    KaxContentCompAlgo &compalg = *(KaxContentCompAlgo*)l4;\r
-                                    MkvTree( p_demux, 6, "Compression Algorithm: %i", uint32(compalg) );\r
-                                    if( uint32( compalg ) == 0 )\r
-                                    {\r
-                                        tk->i_compression_type = MATROSKA_COMPRESSION_ZLIB;\r
-                                    }\r
-                                }\r
-                                else\r
-                                {\r
-                                    MkvTree( p_demux, 6, "Unknown (%s)", typeid(*l4).name() );\r
-                                }\r
-                            }\r
-                        }\r
-\r
-                        else\r
-                        {\r
-                            MkvTree( p_demux, 5, "Unknown (%s)", typeid(*l3).name() );\r
-                        }\r
-                    }\r
-                    \r
-                }\r
-                else\r
-                {\r
-                    MkvTree( p_demux, 4, "Unknown (%s)", typeid(*l2).name() );\r
-                }\r
-            }\r
-                \r
-        }\r
-//        else if( EbmlId( *l ) == KaxCodecSettings::ClassInfos.GlobalId )\r
-//        {\r
-//            KaxCodecSettings &cset = *(KaxCodecSettings*)l;\r
-\r
-//            tk->psz_codec_settings = UTF8ToStr( UTFstring( cset ) );\r
-//            msg_Dbg( p_demux, "|   |   |   + Track Codec Settings=%s", tk->psz_codec_settings );\r
-//        }\r
-//        else if( EbmlId( *l ) == KaxCodecInfoURL::ClassInfos.GlobalId )\r
-//        {\r
-//            KaxCodecInfoURL &ciurl = *(KaxCodecInfoURL*)l;\r
-\r
-//            tk->psz_codec_info_url = strdup( string( ciurl ).c_str() );\r
-//            msg_Dbg( p_demux, "|   |   |   + Track Codec Info URL=%s", tk->psz_codec_info_url );\r
-//        }\r
-//        else if( EbmlId( *l ) == KaxCodecDownloadURL::ClassInfos.GlobalId )\r
-//        {\r
-//            KaxCodecDownloadURL &cdurl = *(KaxCodecDownloadURL*)l;\r
-\r
-//            tk->psz_codec_download_url = strdup( string( cdurl ).c_str() );\r
-//            msg_Dbg( p_demux, "|   |   |   + Track Codec Info URL=%s", tk->psz_codec_download_url );\r
-//        }\r
-//        else if( EbmlId( *l ) == KaxCodecDecodeAll::ClassInfos.GlobalId )\r
-//        {\r
-//            KaxCodecDecodeAll &cdall = *(KaxCodecDecodeAll*)l;\r
-\r
-//            msg_Dbg( p_demux, "|   |   |   + Track Codec Decode All=%u <== UNUSED", uint8( cdall ) );\r
-//        }\r
-//        else if( EbmlId( *l ) == KaxTrackOverlay::ClassInfos.GlobalId )\r
-//        {\r
-//            KaxTrackOverlay &tovr = *(KaxTrackOverlay*)l;\r
-\r
-//            msg_Dbg( p_demux, "|   |   |   + Track Overlay=%u <== UNUSED", uint32( tovr ) );\r
-//        }\r
-        else  if( MKV_IS_ID( l, KaxTrackVideo ) )\r
-        {\r
-            EbmlMaster *tkv = static_cast<EbmlMaster*>(l);\r
-            unsigned int j;\r
-\r
-            msg_Dbg( p_demux, "|   |   |   + Track Video" );\r
-            tk->f_fps = 0.0;\r
-\r
-            for( j = 0; j < tkv->ListSize(); j++ )\r
-            {\r
-                EbmlElement *l = (*tkv)[j];\r
-//                if( EbmlId( *el4 ) == KaxVideoFlagInterlaced::ClassInfos.GlobalId )\r
-//                {\r
-//                    KaxVideoFlagInterlaced &fint = *(KaxVideoFlagInterlaced*)el4;\r
-\r
-//                    msg_Dbg( p_demux, "|   |   |   |   + Track Video Interlaced=%u", uint8( fint ) );\r
-//                }\r
-//                else if( EbmlId( *el4 ) == KaxVideoStereoMode::ClassInfos.GlobalId )\r
-//                {\r
-//                    KaxVideoStereoMode &stereo = *(KaxVideoStereoMode*)el4;\r
-\r
-//                    msg_Dbg( p_demux, "|   |   |   |   + Track Video Stereo Mode=%u", uint8( stereo ) );\r
-//                }\r
-//                else\r
-                if( MKV_IS_ID( l, KaxVideoPixelWidth ) )\r
-                {\r
-                    KaxVideoPixelWidth &vwidth = *(KaxVideoPixelWidth*)l;\r
-\r
-                    tk->fmt.video.i_width = uint16( vwidth );\r
-                    msg_Dbg( p_demux, "|   |   |   |   + width=%d", uint16( vwidth ) );\r
-                }\r
-                else if( MKV_IS_ID( l, KaxVideoPixelHeight ) )\r
-                {\r
-                    KaxVideoPixelWidth &vheight = *(KaxVideoPixelWidth*)l;\r
-\r
-                    tk->fmt.video.i_height = uint16( vheight );\r
-                    msg_Dbg( p_demux, "|   |   |   |   + height=%d", uint16( vheight ) );\r
-                }\r
-                else if( MKV_IS_ID( l, KaxVideoDisplayWidth ) )\r
-                {\r
-                    KaxVideoDisplayWidth &vwidth = *(KaxVideoDisplayWidth*)l;\r
-\r
-                    tk->fmt.video.i_visible_width = uint16( vwidth );\r
-                    msg_Dbg( p_demux, "|   |   |   |   + display width=%d", uint16( vwidth ) );\r
-                }\r
-                else if( MKV_IS_ID( l, KaxVideoDisplayHeight ) )\r
-                {\r
-                    KaxVideoDisplayWidth &vheight = *(KaxVideoDisplayWidth*)l;\r
-\r
-                    tk->fmt.video.i_visible_height = uint16( vheight );\r
-                    msg_Dbg( p_demux, "|   |   |   |   + display height=%d", uint16( vheight ) );\r
-                }\r
-                else if( MKV_IS_ID( l, KaxVideoFrameRate ) )\r
-                {\r
-                    KaxVideoFrameRate &vfps = *(KaxVideoFrameRate*)l;\r
-\r
-                    tk->f_fps = float( vfps );\r
-                    msg_Dbg( p_demux, "   |   |   |   + fps=%f", float( vfps ) );\r
-                }\r
-//                else if( EbmlId( *l ) == KaxVideoDisplayUnit::ClassInfos.GlobalId )\r
-//                {\r
-//                     KaxVideoDisplayUnit &vdmode = *(KaxVideoDisplayUnit*)l;\r
-\r
-//                    msg_Dbg( p_demux, "|   |   |   |   + Track Video Display Unit=%s",\r
-//                             uint8( vdmode ) == 0 ? "pixels" : ( uint8( vdmode ) == 1 ? "centimeters": "inches" ) );\r
-//                }\r
-//                else if( EbmlId( *l ) == KaxVideoAspectRatio::ClassInfos.GlobalId )\r
-//                {\r
-//                    KaxVideoAspectRatio &ratio = *(KaxVideoAspectRatio*)l;\r
-\r
-//                    msg_Dbg( p_demux, "   |   |   |   + Track Video Aspect Ratio Type=%u", uint8( ratio ) );\r
-//                }\r
-//                else if( EbmlId( *l ) == KaxVideoGamma::ClassInfos.GlobalId )\r
-//                {\r
-//                    KaxVideoGamma &gamma = *(KaxVideoGamma*)l;\r
-\r
-//                    msg_Dbg( p_demux, "   |   |   |   + fps=%f", float( gamma ) );\r
-//                }\r
-                else\r
-                {\r
-                    msg_Dbg( p_demux, "|   |   |   |   + Unknown (%s)", typeid(*l).name() );\r
-                }\r
-            }\r
-        }\r
-        else  if( MKV_IS_ID( l, KaxTrackAudio ) )\r
-        {\r
-            EbmlMaster *tka = static_cast<EbmlMaster*>(l);\r
-            unsigned int j;\r
-\r
-            msg_Dbg( p_demux, "|   |   |   + Track Audio" );\r
-\r
-            for( j = 0; j < tka->ListSize(); j++ )\r
-            {\r
-                EbmlElement *l = (*tka)[j];\r
-\r
-                if( MKV_IS_ID( l, KaxAudioSamplingFreq ) )\r
-                {\r
-                    KaxAudioSamplingFreq &afreq = *(KaxAudioSamplingFreq*)l;\r
-\r
-                    tk->fmt.audio.i_rate = (int)float( afreq );\r
-                    msg_Dbg( p_demux, "|   |   |   |   + afreq=%d", tk->fmt.audio.i_rate );\r
-                }\r
-                else if( MKV_IS_ID( l, KaxAudioChannels ) )\r
-                {\r
-                    KaxAudioChannels &achan = *(KaxAudioChannels*)l;\r
-\r
-                    tk->fmt.audio.i_channels = uint8( achan );\r
-                    msg_Dbg( p_demux, "|   |   |   |   + achan=%u", uint8( achan ) );\r
-                }\r
-                else if( MKV_IS_ID( l, KaxAudioBitDepth ) )\r
-                {\r
-                    KaxAudioBitDepth &abits = *(KaxAudioBitDepth*)l;\r
-\r
-                    tk->fmt.audio.i_bitspersample = uint8( abits );\r
-                    msg_Dbg( p_demux, "|   |   |   |   + abits=%u", uint8( abits ) );\r
-                }\r
-                else\r
-                {\r
-                    msg_Dbg( p_demux, "|   |   |   |   + Unknown (%s)", typeid(*l).name() );\r
-                }\r
-            }\r
-        }\r
-        else\r
-        {\r
-            msg_Dbg( p_demux, "|   |   |   + Unknown (%s)",\r
-                     typeid(*l).name() );\r
-        }\r
-    }\r
-}\r
-\r
-static void ParseTracks( demux_t *p_demux, EbmlElement *tracks )\r
-{\r
-    demux_sys_t *p_sys = p_demux->p_sys;\r
-    EbmlElement *el;\r
-    EbmlMaster  *m;\r
-    unsigned int i;\r
-    int i_upper_level = 0;\r
-\r
-    msg_Dbg( p_demux, "|   + Tracks" );\r
-\r
-    /* Master elements */\r
-    m = static_cast<EbmlMaster *>(tracks);\r
-    m->Read( *p_sys->es, tracks->Generic().Context, i_upper_level, el, true );\r
-\r
-    for( i = 0; i < m->ListSize(); i++ )\r
-    {\r
-        EbmlElement *l = (*m)[i];\r
-\r
-        if( MKV_IS_ID( l, KaxTrackEntry ) )\r
-        {\r
-            ParseTrackEntry( p_demux, static_cast<EbmlMaster *>(l) );\r
-        }\r
-        else\r
-        {\r
-            msg_Dbg( p_demux, "|   |   + Unknown (%s)", typeid(*l).name() );\r
-        }\r
-    }\r
-}\r
-\r
-/*****************************************************************************\r
- * ParseInfo:\r
- *****************************************************************************/\r
-static void ParseInfo( demux_t *p_demux, EbmlElement *info )\r
-{\r
-    demux_sys_t *p_sys = p_demux->p_sys;\r
-    EbmlElement *el;\r
-    EbmlMaster  *m;\r
-    unsigned int i;\r
-    int i_upper_level = 0;\r
-\r
-    msg_Dbg( p_demux, "|   + Information" );\r
-\r
-    /* Master elements */\r
-    m = static_cast<EbmlMaster *>(info);\r
-    m->Read( *p_sys->es, info->Generic().Context, i_upper_level, el, true );\r
-\r
-    for( i = 0; i < m->ListSize(); i++ )\r
-    {\r
-        EbmlElement *l = (*m)[i];\r
-\r
-        if( MKV_IS_ID( l, KaxSegmentUID ) )\r
-        {\r
-            p_sys->segment_uid = *(new KaxSegmentUID(*static_cast<KaxSegmentUID*>(l)));\r
-\r
-            msg_Dbg( p_demux, "|   |   + UID=%d", *(uint32*)p_sys->segment_uid.GetBuffer() );\r
-        }\r
-        else if( MKV_IS_ID( l, KaxTimecodeScale ) )\r
-        {\r
-            KaxTimecodeScale &tcs = *(KaxTimecodeScale*)l;\r
-\r
-            p_sys->i_timescale = uint64(tcs);\r
-\r
-            msg_Dbg( p_demux, "|   |   + TimecodeScale="I64Fd,\r
-                     p_sys->i_timescale );\r
-        }\r
-        else if( MKV_IS_ID( l, KaxDuration ) )\r
-        {\r
-            KaxDuration &dur = *(KaxDuration*)l;\r
-\r
-            p_sys->f_duration = float(dur);\r
-\r
-            msg_Dbg( p_demux, "|   |   + Duration=%f",\r
-                     p_sys->f_duration );\r
-        }\r
-        else if( MKV_IS_ID( l, KaxMuxingApp ) )\r
-        {\r
-            KaxMuxingApp &mapp = *(KaxMuxingApp*)l;\r
-\r
-            p_sys->psz_muxing_application = UTF8ToStr( UTFstring( mapp ) );\r
-\r
-            msg_Dbg( p_demux, "|   |   + Muxing Application=%s",\r
-                     p_sys->psz_muxing_application );\r
-        }\r
-        else if( MKV_IS_ID( l, KaxWritingApp ) )\r
-        {\r
-            KaxWritingApp &wapp = *(KaxWritingApp*)l;\r
-\r
-            p_sys->psz_writing_application = UTF8ToStr( UTFstring( wapp ) );\r
-\r
-            msg_Dbg( p_demux, "|   |   + Writing Application=%s",\r
-                     p_sys->psz_writing_application );\r
-        }\r
-        else if( MKV_IS_ID( l, KaxSegmentFilename ) )\r
-        {\r
-            KaxSegmentFilename &sfn = *(KaxSegmentFilename*)l;\r
-\r
-            p_sys->psz_segment_filename = UTF8ToStr( UTFstring( sfn ) );\r
-\r
-            msg_Dbg( p_demux, "|   |   + Segment Filename=%s",\r
-                     p_sys->psz_segment_filename );\r
-        }\r
-        else if( MKV_IS_ID( l, KaxTitle ) )\r
-        {\r
-            KaxTitle &title = *(KaxTitle*)l;\r
-\r
-            p_sys->psz_title = UTF8ToStr( UTFstring( title ) );\r
-\r
-            msg_Dbg( p_demux, "|   |   + Title=%s", p_sys->psz_title );\r
-        }\r
-        if( MKV_IS_ID( l, KaxSegmentFamily ) )\r
-        {\r
-            KaxSegmentFamily *uid = static_cast<KaxSegmentFamily*>(l);\r
-\r
-            p_sys->families.push_back(*uid);\r
-\r
-            msg_Dbg( p_demux, "|   |   + family=%d", *(uint32*)uid->GetBuffer() );\r
-        }\r
-#if defined( HAVE_GMTIME_R ) && !defined( SYS_DARWIN )\r
-        else if( MKV_IS_ID( l, KaxDateUTC ) )\r
-        {\r
-            KaxDateUTC &date = *(KaxDateUTC*)l;\r
-            time_t i_date;\r
-            struct tm tmres;\r
-            char   buffer[256];\r
-\r
-            i_date = date.GetEpochDate();\r
-            memset( buffer, 0, 256 );\r
-            if( gmtime_r( &i_date, &tmres ) &&\r
-                asctime_r( &tmres, buffer ) )\r
-            {\r
-                buffer[strlen( buffer)-1]= '\0';\r
-                p_sys->psz_date_utc = strdup( buffer );\r
-                msg_Dbg( p_demux, "|   |   + Date=%s", p_sys->psz_date_utc );\r
-            }\r
-        }\r
-#endif\r
-        else\r
-        {\r
-            msg_Dbg( p_demux, "|   |   + Unknown (%s)", typeid(*l).name() );\r
-        }\r
-    }\r
-\r
-    p_sys->f_duration *= p_sys->i_timescale / 1000000.0;\r
-}\r
-\r
-\r
-/*****************************************************************************\r
- * ParseChapterAtom\r
- *****************************************************************************/\r
-static void ParseChapterAtom( demux_t *p_demux, int i_level, EbmlMaster *ca )\r
-{\r
-    demux_sys_t *p_sys = p_demux->p_sys;\r
-    unsigned int i;\r
-    seekpoint_t *sk;\r
-    bool b_display_seekpoint = true;\r
-\r
-    if( p_sys->title == NULL )\r
-    {\r
-        p_sys->title = vlc_input_title_New();\r
-    }\r
-    sk = vlc_seekpoint_New();\r
-\r
-    sk->i_level = i_level;\r
-\r
-    msg_Dbg( p_demux, "|   |   |   + ChapterAtom (level=%d)", i_level );\r
-    for( i = 0; i < ca->ListSize(); i++ )\r
-    {\r
-        EbmlElement *l = (*ca)[i];\r
-\r
-        if( MKV_IS_ID( l, KaxChapterUID ) )\r
-        {\r
-            KaxChapterUID &uid = *(KaxChapterUID*)l;\r
-            uint32_t i_uid = uint32( uid );\r
-            msg_Dbg( p_demux, "|   |   |   |   + ChapterUID: 0x%x", i_uid );\r
-        }\r
-        else if( MKV_IS_ID( l, KaxChapterFlagHidden ) )\r
-        {\r
-            KaxChapterFlagHidden &flag =*(KaxChapterFlagHidden*)l;\r
-            b_display_seekpoint = uint8( flag ) == 0;\r
-\r
-            msg_Dbg( p_demux, "|   |   |   |   + ChapterFlagHidden: %s", b_display_seekpoint ? "no":"yes" );\r
-        }\r
-        else if( MKV_IS_ID( l, KaxChapterTimeStart ) )\r
-        {\r
-            KaxChapterTimeStart &start =*(KaxChapterTimeStart*)l;\r
-            sk->i_time_offset = uint64( start ) / I64C(1000);\r
-\r
-            msg_Dbg( p_demux, "|   |   |   |   + ChapterTimeStart: %lld", sk->i_time_offset );\r
-        }\r
-        else if( MKV_IS_ID( l, KaxChapterTimeEnd ) )\r
-        {\r
-            KaxChapterTimeEnd &end =*(KaxChapterTimeEnd*)l;\r
-            int64_t i_end = uint64( end );\r
-\r
-            msg_Dbg( p_demux, "|   |   |   |   + ChapterTimeEnd: %lld", i_end );\r
-        }\r
-        else if( MKV_IS_ID( l, KaxChapterDisplay ) )\r
-        {\r
-            EbmlMaster *cd = static_cast<EbmlMaster *>(l);\r
-            unsigned int j;\r
-\r
-            msg_Dbg( p_demux, "|   |   |   |   + ChapterDisplay" );\r
-            for( j = 0; j < cd->ListSize(); j++ )\r
-            {\r
-                EbmlElement *l= (*cd)[j];\r
-\r
-                if( MKV_IS_ID( l, KaxChapterString ) )\r
-                {\r
-                    std::string psz;\r
-                    int k;\r
-\r
-                    KaxChapterString &name =*(KaxChapterString*)l;\r
-                    for (k = 0; k < i_level; k++)\r
-                        psz += '+';\r
-                    psz += ' ';\r
-                    psz += UTF8ToStr( UTFstring( name ) );\r
-                    sk->psz_name = strdup( psz.c_str() );\r
-                    msg_Dbg( p_demux, "|   |   |   |   |    + ChapterString '%s'", UTF8ToStr(UTFstring(name)) );\r
-                }\r
-                else if( MKV_IS_ID( l, KaxChapterLanguage ) )\r
-                {\r
-                    KaxChapterLanguage &lang =*(KaxChapterLanguage*)l;\r
-                    const char *psz = string( lang ).c_str();\r
-\r
-                    msg_Dbg( p_demux, "|   |   |   |   |    + ChapterLanguage '%s'", psz );\r
-                }\r
-                else if( MKV_IS_ID( l, KaxChapterCountry ) )\r
-                {\r
-                    KaxChapterCountry &ct =*(KaxChapterCountry*)l;\r
-                    const char *psz = string( ct ).c_str();\r
-\r
-                    msg_Dbg( p_demux, "|   |   |   |   |    + ChapterCountry '%s'", psz );\r
-                }\r
-            }\r
-        }\r
-        else if( MKV_IS_ID( l, KaxChapterAtom ) )\r
-        {\r
-            ParseChapterAtom( p_demux, i_level+1, static_cast<EbmlMaster *>(l) );\r
-        }\r
-    }\r
-\r
-    if (b_display_seekpoint)\r
-    {\r
-        // A start time of '0' is ok. A missing ChapterTime element is ok, too, because '0' is its default value.\r
-        p_sys->title->i_seekpoint++;\r
-        p_sys->title->seekpoint = (seekpoint_t**)realloc( p_sys->title->seekpoint, p_sys->title->i_seekpoint * sizeof( seekpoint_t* ) );\r
-        p_sys->title->seekpoint[p_sys->title->i_seekpoint-1] = sk;\r
-    }\r
-    else\r
-    {\r
-        vlc_seekpoint_Delete(sk);\r
-    }\r
-}\r
-\r
-/*****************************************************************************\r
- * ParseChapters:\r
- *****************************************************************************/\r
-static void ParseChapters( demux_t *p_demux, EbmlElement *chapters )\r
-{\r
-    demux_sys_t *p_sys = p_demux->p_sys;\r
-    EbmlElement *el;\r
-    EbmlMaster  *m;\r
-    unsigned int i;\r
-    int i_upper_level = 0;\r
-\r
-\r
-    /* Master elements */\r
-    m = static_cast<EbmlMaster *>(chapters);\r
-    m->Read( *p_sys->es, chapters->Generic().Context, i_upper_level, el, true );\r
-\r
-    for( i = 0; i < m->ListSize(); i++ )\r
-    {\r
-        EbmlElement *l = (*m)[i];\r
-\r
-        if( MKV_IS_ID( l, KaxEditionEntry ) )\r
-        {\r
-            EbmlMaster *E = static_cast<EbmlMaster *>(l );\r
-            unsigned int j;\r
-            msg_Dbg( p_demux, "|   |   + EditionEntry" );\r
-            p_sys->edition_ordered = false;\r
-            for( j = 0; j < E->ListSize(); j++ )\r
-            {\r
-                EbmlElement *l = (*E)[j];\r
-\r
-                if( MKV_IS_ID( l, KaxChapterAtom ) )\r
-                {\r
-                    ParseChapterAtom( p_demux, 0, static_cast<EbmlMaster *>(l) );\r
-                }\r
-                else if( MKV_IS_ID( l, KaxEditionUID ) )\r
-                {\r
-                    p_sys->edition_uid = uint64(*static_cast<KaxEditionUID *>(l));\r
-                }\r
-                else if( MKV_IS_ID( l, KaxEditionFlagOrdered ) )\r
-                {\r
-                    p_sys->edition_ordered = uint8(*static_cast<KaxEditionFlagOrdered *>(l)) != 0;\r
-                }\r
-                else\r
-                {\r
-                    msg_Dbg( p_demux, "|   |   |   + Unknown (%s)", typeid(*l).name() );\r
-                }\r
-            }\r
-        }\r
-        else\r
-        {\r
-            msg_Dbg( p_demux, "|   |   + Unknown (%s)", typeid(*l).name() );\r
-        }\r
-    }\r
-}\r
-\r
-/*****************************************************************************\r
- * InformationCreate:\r
- *****************************************************************************/\r
-static void InformationCreate( demux_t *p_demux )\r
-{\r
-    demux_sys_t *p_sys = p_demux->p_sys;\r
-    int         i_track;\r
-\r
-    p_sys->meta = vlc_meta_New();\r
-\r
-    if( p_sys->psz_title )\r
-    {\r
-        vlc_meta_Add( p_sys->meta, VLC_META_TITLE, p_sys->psz_title );\r
-    }\r
-    if( p_sys->psz_date_utc )\r
-    {\r
-        vlc_meta_Add( p_sys->meta, VLC_META_DATE, p_sys->psz_date_utc );\r
-    }\r
-    if( p_sys->psz_segment_filename )\r
-    {\r
-        vlc_meta_Add( p_sys->meta, _("Segment filename"), p_sys->psz_segment_filename );\r
-    }\r
-    if( p_sys->psz_muxing_application )\r
-    {\r
-        vlc_meta_Add( p_sys->meta, _("Muxing application"), p_sys->psz_muxing_application );\r
-    }\r
-    if( p_sys->psz_writing_application )\r
-    {\r
-        vlc_meta_Add( p_sys->meta, _("Writing application"), p_sys->psz_writing_application );\r
-    }\r
-\r
-    for( i_track = 0; i_track < p_sys->i_track; i_track++ )\r
-    {\r
-        mkv_track_t *tk = &p_sys->track[i_track];\r
-        vlc_meta_t *mtk = vlc_meta_New();\r
-\r
-        p_sys->meta->track = (vlc_meta_t**)realloc( p_sys->meta->track,\r
-                                                    sizeof( vlc_meta_t * ) * ( p_sys->meta->i_track + 1 ) );\r
-        p_sys->meta->track[p_sys->meta->i_track++] = mtk;\r
-\r
-        if( tk->fmt.psz_description )\r
-        {\r
-            vlc_meta_Add( p_sys->meta, VLC_META_DESCRIPTION, tk->fmt.psz_description );\r
-        }\r
-        if( tk->psz_codec_name )\r
-        {\r
-            vlc_meta_Add( p_sys->meta, VLC_META_CODEC_NAME, tk->psz_codec_name );\r
-        }\r
-        if( tk->psz_codec_settings )\r
-        {\r
-            vlc_meta_Add( p_sys->meta, VLC_META_SETTING, tk->psz_codec_settings );\r
-        }\r
-        if( tk->psz_codec_info_url )\r
-        {\r
-            vlc_meta_Add( p_sys->meta, VLC_META_CODEC_DESCRIPTION, tk->psz_codec_info_url );\r
-        }\r
-        if( tk->psz_codec_download_url )\r
-        {\r
-            vlc_meta_Add( p_sys->meta, VLC_META_URL, tk->psz_codec_download_url );\r
-        }\r
-    }\r
-\r
-    if( p_sys->i_tags_position >= 0 )\r
-    {\r
-        vlc_bool_t b_seekable;\r
-\r
-        stream_Control( p_demux->s, STREAM_CAN_FASTSEEK, &b_seekable );\r
-        if( b_seekable )\r
-        {\r
-            LoadTags( p_demux );\r
-        }\r
-    }\r
-}\r
-\r
-\r
-/*****************************************************************************\r
- * Divers\r
- *****************************************************************************/\r
-\r
-static void IndexAppendCluster( demux_t *p_demux, KaxCluster *cluster )\r
-{\r
-    demux_sys_t *p_sys = p_demux->p_sys;\r
-\r
-#define idx p_sys->index[p_sys->i_index]\r
-    idx.i_track       = -1;\r
-    idx.i_block_number= -1;\r
-    idx.i_position    = cluster->GetElementPosition();\r
-    idx.i_time        = -1;\r
-    idx.b_key         = VLC_TRUE;\r
-\r
-    p_sys->i_index++;\r
-    if( p_sys->i_index >= p_sys->i_index_max )\r
-    {\r
-        p_sys->i_index_max += 1024;\r
-        p_sys->index = (mkv_index_t*)realloc( p_sys->index, sizeof( mkv_index_t ) * p_sys->i_index_max );\r
-    }\r
-#undef idx\r
-}\r
-\r
-static char * UTF8ToStr( const UTFstring &u )\r
-{\r
-    int     i_src;\r
-    const wchar_t *src;\r
-    char *dst, *p;\r
-\r
-    i_src = u.length();\r
-    src   = u.c_str();\r
-\r
-    p = dst = (char*)malloc( i_src + 1);\r
-    while( i_src > 0 )\r
-    {\r
-        if( *src < 255 )\r
-        {\r
-            *p++ = (char)*src;\r
-        }\r
-        else\r
-        {\r
-            *p++ = '?';\r
-        }\r
-        src++;\r
-        i_src--;\r
-    }\r
-    *p++= '\0';\r
-\r
-    return dst;\r
-}\r
-\r
+/*****************************************************************************
+ * mkv.cpp : matroska demuxer
+ *****************************************************************************
+ * Copyright (C) 2003-2004 VideoLAN
+ * $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
+ * the Free Software Foundation; either version 2 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software
+ * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111, USA.
+ *****************************************************************************/
+
+/*****************************************************************************
+ * Preamble
+ *****************************************************************************/
+#include <stdlib.h>                                      /* malloc(), free() */
+
+#include <vlc/vlc.h>
+
+#ifdef HAVE_TIME_H
+#   include <time.h>                                               /* time() */
+#endif
+
+#include <vlc/input.h>
+
+#include <codecs.h>                        /* BITMAPINFOHEADER, WAVEFORMATEX */
+#include "iso_lang.h"
+#include "vlc_meta.h"
+
+#include <iostream>
+#include <cassert>
+#include <typeinfo>
+#include <string>
+#include <vector>
+
+#ifdef HAVE_DIRENT_H
+#   include <dirent.h>
+#else
+#   include "../../src/extras/dirent.h"
+#endif
+
+/* libebml and matroska */
+#include "ebml/EbmlHead.h"
+#include "ebml/EbmlSubHead.h"
+#include "ebml/EbmlStream.h"
+#include "ebml/EbmlContexts.h"
+#include "ebml/EbmlVoid.h"
+#include "ebml/StdIOCallback.h"
+
+#include "matroska/KaxAttachments.h"
+#include "matroska/KaxBlock.h"
+#include "matroska/KaxBlockData.h"
+#include "matroska/KaxChapters.h"
+#include "matroska/KaxCluster.h"
+#include "matroska/KaxClusterData.h"
+#include "matroska/KaxContexts.h"
+#include "matroska/KaxCues.h"
+#include "matroska/KaxCuesData.h"
+#include "matroska/KaxInfo.h"
+#include "matroska/KaxInfoData.h"
+#include "matroska/KaxSeekHead.h"
+#include "matroska/KaxSegment.h"
+#include "matroska/KaxTag.h"
+#include "matroska/KaxTags.h"
+#include "matroska/KaxTagMulti.h"
+#include "matroska/KaxTracks.h"
+#include "matroska/KaxTrackAudio.h"
+#include "matroska/KaxTrackVideo.h"
+#include "matroska/KaxTrackEntryData.h"
+#include "matroska/KaxContentEncoding.h"
+
+#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;
+
+/*****************************************************************************
+ * Module descriptor
+ *****************************************************************************/
+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"),
+            N_("Seek based on percent not time"), VLC_TRUE );
+
+    add_shortcut( "mka" );
+    add_shortcut( "mkv" );
+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;
+    unsigned char *dst;
+    block_t *p_block;
+    z_stream d_stream;
+
+    d_stream.zalloc = (alloc_func)0;
+    d_stream.zfree = (free_func)0;
+    d_stream.opaque = (voidpf)0;
+    result = inflateInit(&d_stream);
+    if( result != Z_OK )
+    {
+        msg_Dbg( p_this, "inflateInit() failed. Result: %d", result );
+        return NULL;
+    }
+
+    d_stream.next_in = (Bytef *)p_in_block->p_buffer;
+    d_stream.avail_in = p_in_block->i_buffer;
+    n = 0;
+    p_block = block_New( p_this, 0 );
+    dst = NULL;
+    do
+    {
+        n++;
+        p_block = block_Realloc( p_block, 0, n * 1000 );
+        dst = (unsigned char *)p_block->p_buffer;
+        d_stream.next_out = (Bytef *)&dst[(n - 1) * 1000];
+        d_stream.avail_out = 1000;
+        result = inflate(&d_stream, Z_NO_FLUSH);
+        if( ( result != Z_OK ) && ( result != Z_STREAM_END ) )
+        {
+            msg_Dbg( p_this, "Zlib decompression failed. Result: %d", result );
+            return NULL;
+        }
+    }
+    while( ( d_stream.avail_out == 0 ) && ( d_stream.avail_in != 0 ) &&
+           ( result != Z_STREAM_END ) );
+
+    dstsize = d_stream.total_out;
+    inflateEnd( &d_stream );
+
+    p_block = block_Realloc( p_block, 0, dstsize );
+    p_block->i_buffer = dstsize;
+    block_Release( p_in_block );
+
+    return p_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
+ *****************************************************************************/
+class vlc_stream_io_callback: public IOCallback
+{
+  private:
+    stream_t       *s;
+    vlc_bool_t     mb_eof;
+
+  public:
+    vlc_stream_io_callback( stream_t * );
+
+    virtual uint32   read            ( void *p_buffer, size_t i_size);
+    virtual void     setFilePointer  ( int64_t i_offset, seek_mode mode = seek_beginning );
+    virtual size_t   write           ( const void *p_buffer, size_t i_size);
+    virtual uint64   getFilePointer  ( void );
+    virtual void     close           ( void );
+};
+
+/*****************************************************************************
+ * Ebml Stream parser
+ *****************************************************************************/
+class EbmlParser
+{
+  public:
+    EbmlParser( EbmlStream *es, EbmlElement *el_start );
+    ~EbmlParser( void );
+
+    void Up( void );
+    void Down( void );
+    EbmlElement *Get( void );
+    void        Keep( void );
+
+    int GetLevel( void );
+
+  private:
+    EbmlStream  *m_es;
+    int         mi_level;
+    EbmlElement *m_el[10];
+
+    EbmlElement *m_got;
+
+    int         mi_user_level;
+    vlc_bool_t  mb_keep;
+};
+
+
+/*****************************************************************************
+ * Some functions to manipulate memory
+ *****************************************************************************/
+#define GetFOURCC( p )  __GetFOURCC( (uint8_t*)p )
+static vlc_fourcc_t __GetFOURCC( uint8_t *p )
+{
+    return VLC_FOURCC( p[0], p[1], p[2], p[3] );
+}
+
+/*****************************************************************************
+ * definitions of structures and functions used by this plugins
+ *****************************************************************************/
+typedef struct
+{
+    vlc_bool_t  b_default;
+    vlc_bool_t  b_enabled;
+    int         i_number;
+
+    int         i_extra_data;
+    uint8_t     *p_extra_data;
+
+    char         *psz_codec;
+
+    uint64_t     i_default_duration;
+    float        f_timecodescale;
+
+    /* video */
+    es_format_t fmt;
+    float       f_fps;
+    es_out_id_t *p_es;
+
+    vlc_bool_t      b_inited;
+    /* data to be send first */
+    int             i_data_init;
+    uint8_t         *p_data_init;
+
+    /* hack : it's for seek */
+    vlc_bool_t      b_search_keyframe;
+
+    /* informative */
+    char         *psz_codec_name;
+    char         *psz_codec_settings;
+    char         *psz_codec_info_url;
+    char         *psz_codec_download_url;
+    
+    /* encryption/compression */
+    int           i_compression_type;
+
+} mkv_track_t;
+
+typedef struct
+{
+    int     i_track;
+    int     i_block_number;
+
+    int64_t i_position;
+    int64_t i_time;
+
+    vlc_bool_t b_key;
+} mkv_index_t;
+
+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)
+        ,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)
+    {}
+
+    vlc_stream_io_callback  *in;
+    EbmlStream              *es;
+    EbmlParser              *ep;
+
+    /* time scale */
+    uint64_t                i_timescale;
+
+    /* duration of the segment */
+    float                   f_duration;
+
+    /* all tracks */
+    int                     i_track;
+    mkv_track_t             *track;
+
+    /* from seekhead */
+    int64_t                 i_cues_position;
+    int64_t                 i_chapters_position;
+    int64_t                 i_tags_position;
+
+    /* current data */
+    KaxSegment              *segment;
+    KaxCluster              *cluster;
+    KaxSegmentUID           segment_uid;
+
+    mtime_t                 i_pts;
+    mtime_t                 i_start_pts;
+
+    vlc_bool_t              b_cues;
+    int                     i_index;
+    int                     i_index_max;
+    mkv_index_t             *index;
+
+    /* info */
+    char                    *psz_muxing_application;
+    char                    *psz_writing_application;
+    char                    *psz_segment_filename;
+    char                    *psz_title;
+    char                    *psz_date_utc;
+
+    vlc_meta_t              *meta;
+
+    input_title_t           *title;
+
+    std::vector<KaxSegmentFamily> families;
+    std::vector<KaxSegment*> family_members;
+
+    int64_t                  edition_uid;
+    bool                     edition_ordered;
+};
+
+#define MKVD_TIMECODESCALE 1000000
+
+#define MKV_IS_ID( el, C ) ( EbmlId( (*el) ) == C::ClassInfos.GlobalId )
+
+static void IndexAppendCluster  ( demux_t *p_demux, KaxCluster *cluster );
+static char *UTF8ToStr          ( const UTFstring &u );
+static void LoadCues            ( demux_t * );
+static void InformationCreate  ( demux_t * );
+
+static void ParseInfo( demux_t *, EbmlElement *info );
+static void ParseTracks( demux_t *, EbmlElement *tracks );
+static void ParseSeekHead( demux_t *, EbmlElement *seekhead );
+static void ParseChapters( demux_t *, EbmlElement *chapters );
+
+/*****************************************************************************
+ * Open: initializes matroska demux structures
+ *****************************************************************************/
+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, j;
+
+    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;
+    }
+
+    /* 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;
+    }
+
+    /* Set the demux function */
+    p_demux->pf_demux   = Demux;
+    p_demux->pf_control = Control;
+    p_demux->p_sys      = p_sys = new 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;
+    p_sys->i_timescale     = MKVD_TIMECODESCALE;
+    p_sys->i_track      = 0;
+    p_sys->track        = (mkv_track_t*)malloc( sizeof( mkv_track_t ) );
+    p_sys->i_pts   = 0;
+    p_sys->i_cues_position = -1;
+    p_sys->i_chapters_position = -1;
+    p_sys->i_tags_position = -1;
+
+    p_sys->b_cues       = VLC_FALSE;
+    p_sys->i_index      = 0;
+    p_sys->i_index_max  = 1024;
+    p_sys->index        = (mkv_index_t*)malloc( sizeof( mkv_index_t ) *
+                                                p_sys->i_index_max );
+
+    p_sys->psz_muxing_application = NULL;
+    p_sys->psz_writing_application = NULL;
+    p_sys->psz_segment_filename = NULL;
+    p_sys->psz_title = NULL;
+    p_sys->psz_date_utc = NULL;;
+    p_sys->meta = NULL;
+    p_sys->title = NULL;
+
+    if( p_sys->es == NULL )
+    {
+        msg_Err( p_demux, "failed to create EbmlStream" );
+        delete p_sys->in;
+        delete p_sys;
+        return VLC_EGENERIC;
+    }
+    /* Find the EbmlHead element */
+    el = p_sys->es->FindNextID(EbmlHead::ClassInfos, 0xFFFFFFFFL);
+    if( el == NULL )
+    {
+        msg_Err( p_demux, "cannot find EbmlHead" );
+        goto error;
+    }
+    msg_Dbg( p_demux, "EbmlHead" );
+    /* skip it */
+    el->SkipData( *p_sys->es, el->Generic().Context );
+    delete el;
+
+    /* Find a segment */
+    el = p_sys->es->FindNextID( KaxSegment::ClassInfos, 0xFFFFFFFFL);
+    if( el == NULL )
+    {
+        msg_Err( p_demux, "cannot find KaxSegment" );
+        goto error;
+    }
+    MkvTree( p_demux, 0, "Segment" );
+    p_sys->segment = (KaxSegment*)el;
+    p_sys->cluster = NULL;
+
+    p_sys->ep = new EbmlParser( p_sys->es, el );
+
+    while( ( el1 = p_sys->ep->Get() ) != NULL )
+    {
+        if( MKV_IS_ID( el1, KaxInfo ) )
+        {
+            ParseInfo( p_demux, el1 );
+        }
+        else if( MKV_IS_ID( el1, KaxTracks ) )
+        {
+            ParseTracks( p_demux, el1 );
+        }
+        else if( MKV_IS_ID( el1, KaxSeekHead ) )
+        {
+            ParseSeekHead( p_demux, el1 );
+        }
+        else if( MKV_IS_ID( el1, KaxCues ) )
+        {
+            msg_Dbg( p_demux, "|   + Cues" );
+        }
+        else if( MKV_IS_ID( el1, KaxCluster ) )
+        {
+            msg_Dbg( p_demux, "|   + Cluster" );
+
+            p_sys->cluster = (KaxCluster*)el1;
+
+            p_sys->ep->Down();
+            /* stop parsing the stream */
+            break;
+        }
+        else if( MKV_IS_ID( el1, KaxAttachments ) )
+        {
+            msg_Dbg( p_demux, "|   + Attachments FIXME TODO (but probably never supported)" );
+        }
+        else if( MKV_IS_ID( el1, KaxChapters ) )
+        {
+            msg_Dbg( p_demux, "|   + Chapters" );
+            ParseChapters( p_demux, el1 );
+        }
+        else if( MKV_IS_ID( el1, KaxTag ) )
+        {
+            msg_Dbg( p_demux, "|   + Tags FIXME TODO" );
+        }
+        else
+        {
+            msg_Dbg( p_demux, "|   + Unknown (%s)", typeid(*el1).name() );
+        }
+    }
+
+    /* 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 = 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 (!s_filename.compare(s_filename.length() - 3, 3, "mkv") || 
+                        !s_filename.compare(s_filename.length() - 3, 3, "mka"))
+                    {
+                        // 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);
+                                                for (j=0; j<p_sys->families.size(); j++)
+                                                {
+                                                    if (p_sys->families.at(j) == *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 ?" );
+        goto error;
+    }
+
+    /* *** Load the cue if found *** */
+    if( p_sys->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 );
+        }
+    }
+
+    if( !p_sys->b_cues || p_sys->i_index <= 0 )
+    {
+        msg_Warn( p_demux, "no cues/empty cues found->seek won't be precise" );
+
+        IndexAppendCluster( p_demux, p_sys->cluster );
+
+        p_sys->b_cues = VLC_FALSE;
+    }
+
+    /* add all es */
+    msg_Dbg( p_demux, "found %d es", p_sys->i_track );
+    for( i_track = 0; i_track < p_sys->i_track; i_track++ )
+    {
+#define tk  p_sys->track[i_track]
+        if( tk.fmt.i_cat == UNKNOWN_ES )
+        {
+            msg_Warn( p_demux, "invalid track[%d, n=%d]", i_track, tk.i_number );
+            tk.p_es = NULL;
+            continue;
+        }
+
+        if( !strcmp( tk.psz_codec, "V_MS/VFW/FOURCC" ) )
+        {
+            if( tk.i_extra_data < (int)sizeof( BITMAPINFOHEADER ) )
+            {
+                msg_Err( p_demux, "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(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" ) )
+        {
+            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++ )
+            {
+                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;
+                }
+            }
+
+            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++ )
+            {
+                *(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( !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[] =
+            {
+                    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)*/
+
+            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;
+            }
+            else
+            {
+                i_profile = 3;
+            }
+
+            for( i_srate = 0; i_srate < 13; i_srate++ )
+            {
+                if( i_sample_rates[i_srate] == tk.fmt.audio.i_rate )
+                {
+                    break;
+                }
+            }
+            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 )
+                {
+                    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 );
+                }
+                else
+                {
+                    msg_Warn( p_demux, "reading original frame size for vobsub failed" );
+                }
+                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;
+        }
+
+        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->es;
+    delete p_sys->in;
+    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;
+    int         i_track;
+
+    for( i_track = 0; i_track < p_sys->i_track; i_track++ )
+    {
+#define tk  p_sys->track[i_track]
+        if( tk.fmt.psz_description )
+        {
+            free( tk.fmt.psz_description );
+        }
+        if( tk.psz_codec )
+        {
+            free( tk.psz_codec );
+        }
+        if( tk.fmt.psz_language )
+        {
+            free( tk.fmt.psz_language );
+        }
+#undef tk
+    }
+    free( p_sys->track );
+
+    if( p_sys->psz_writing_application  )
+    {
+        free( p_sys->psz_writing_application );
+    }
+    if( p_sys->psz_muxing_application  )
+    {
+        free( p_sys->psz_muxing_application );
+    }
+
+    delete p_sys->segment;
+
+    delete p_sys->ep;
+    delete p_sys->es;
+    delete p_sys->in;
+    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;
+    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 * );
+            *pf = (double)p_sys->in->getFilePointer() / (double)stream_Size( p_demux->s );
+            return VLC_SUCCESS;
+
+        case DEMUX_SET_POSITION:
+            f = (double)va_arg( args, double );
+            Seek( p_demux, -1, (int)(100.0 * f) );
+            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;
+
+        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:
+            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);
+                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;
+    }
+}
+
+static int BlockGet( demux_t *p_demux, KaxBlock **pp_block, int64_t *pi_ref1, int64_t *pi_ref2, int64_t *pi_duration )
+{
+    demux_sys_t *p_sys = p_demux->p_sys;
+
+    *pp_block = NULL;
+    *pi_ref1  = -1;
+    *pi_ref2  = -1;
+
+    for( ;; )
+    {
+        EbmlElement *el;
+        int         i_level;
+
+        if( p_demux->b_die )
+        {
+            return VLC_EGENERIC;
+        }
+
+        el = p_sys->ep->Get();
+        i_level = p_sys->ep->GetLevel();
+
+        if( el == NULL && *pp_block != NULL )
+        {
+            /* update the index */
+#define idx p_sys->index[p_sys->i_index - 1]
+            if( p_sys->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;
+        }
+
+        if( el == NULL )
+        {
+            if( p_sys->ep->GetLevel() > 1 )
+            {
+                p_sys->ep->Up();
+                continue;
+            }
+            msg_Warn( p_demux, "EOF" );
+            return VLC_EGENERIC;
+        }
+
+        /* do parsing */
+        if( i_level == 1 )
+        {
+            if( MKV_IS_ID( el, KaxCluster ) )
+            {
+                p_sys->cluster = (KaxCluster*)el;
+
+                /* add it to the index */
+                if( p_sys->i_index == 0 ||
+                    ( p_sys->i_index > 0 && p_sys->index[p_sys->i_index - 1].i_position < (int64_t)p_sys->cluster->GetElementPosition() ) )
+                {
+                    IndexAppendCluster( p_demux, p_sys->cluster );
+                }
+
+                p_sys->ep->Down();
+            }
+            else if( MKV_IS_ID( el, KaxCues ) )
+            {
+                msg_Warn( p_demux, "find KaxCues FIXME" );
+                return VLC_EGENERIC;
+            }
+            else
+            {
+                msg_Dbg( p_demux, "unknown (%s)", typeid( el ).name() );
+            }
+        }
+        else if( i_level == 2 )
+        {
+            if( MKV_IS_ID( el, KaxClusterTimecode ) )
+            {
+                KaxClusterTimecode &ctc = *(KaxClusterTimecode*)el;
+
+                ctc.ReadData( p_sys->es->I_O(), SCOPE_ALL_DATA );
+                p_sys->cluster->InitTimecode( uint64( ctc ), p_sys->i_timescale );
+            }
+            else if( MKV_IS_ID( el, KaxBlockGroup ) )
+            {
+                p_sys->ep->Down();
+            }
+        }
+        else if( i_level == 3 )
+        {
+            if( MKV_IS_ID( el, KaxBlock ) )
+            {
+                *pp_block = (KaxBlock*)el;
+
+                (*pp_block)->ReadData( p_sys->es->I_O() );
+                (*pp_block)->SetParent( *p_sys->cluster );
+
+                p_sys->ep->Keep();
+            }
+            else if( MKV_IS_ID( el, KaxBlockDuration ) )
+            {
+                KaxBlockDuration &dur = *(KaxBlockDuration*)el;
+
+                dur.ReadData( p_sys->es->I_O() );
+                *pi_duration = uint64( dur );
+            }
+            else if( MKV_IS_ID( el, KaxReferenceBlock ) )
+            {
+                KaxReferenceBlock &ref = *(KaxReferenceBlock*)el;
+
+                ref.ReadData( p_sys->es->I_O() );
+                if( *pi_ref1 == -1 )
+                {
+                    *pi_ref1 = int64( ref );
+                }
+                else
+                {
+                    *pi_ref2 = int64( ref );
+                }
+            }
+        }
+        else
+        {
+            msg_Err( p_demux, "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;
+
+    int             i_track;
+    unsigned int    i;
+    vlc_bool_t      b;
+
+#define tk  p_sys->track[i_track]
+    for( i_track = 0; i_track < p_sys->i_track; i_track++ )
+    {
+        if( tk.i_number == block->TrackNum() )
+        {
+            break;
+        }
+    }
+
+    if( i_track >= p_sys->i_track )
+    {
+        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;
+    }
+
+    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 )
+        {
+            break;
+        }
+
+#if defined(HAVE_ZLIB_H)
+        if( tk.i_compression_type )
+        {
+            p_block = block_zlib_decompress( VLC_OBJECT(p_demux), p_block );
+        }
+#endif
+
+        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;
+        }
+        es_out_Send( p_demux->out, tk.p_es, p_block );
+
+        /* use time stamp only for first block */
+        i_pts = 0;
+    }
+
+#undef tk
+}
+
+static void Seek( demux_t *p_demux, mtime_t i_date, int i_percent)
+{
+    demux_sys_t *p_sys = p_demux->p_sys;
+
+    KaxBlock    *block;
+    int64_t     i_block_duration;
+    int64_t     i_block_ref1;
+    int64_t     i_block_ref2;
+
+    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 )
+    {
+        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( i_percent >= 0 && (config_GetInt( p_demux, "mkv-seek-percent" ) || !p_sys->b_cues || i_date < 0 ))
+    {
+        if (p_sys->f_duration >= 0)
+        {
+            i_date = i_percent * p_sys->f_duration * 10;
+        }
+        else
+        {
+            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->index[i_index].i_position >= i_pos)
+                {
+                    break;
+                }
+            }
+            if( i_index == p_sys->i_index )
+            {
+                i_index--;
+            }
+
+            i_date = p_sys->index[i_index].i_time;
+
+#if 0
+            if( p_sys->index[i_index].i_position < i_pos )
+            {
+                EbmlElement *el;
+
+                msg_Warn( p_demux, "searching for cluster, could take some time" );
+
+                /* search a cluster */
+                while( ( el = p_sys->ep->Get() ) != NULL )
+                {
+                    if( MKV_IS_ID( el, KaxCluster ) )
+                    {
+                        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
+        }
+    }
+
+    for( ; i_index < p_sys->i_index; i_index++ )
+    {
+        if( p_sys->index[i_index].i_time > i_date )
+        {
+            break;
+        }
+    }
+
+    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 );
+
+
+    /* now parse until key frame */
+#define tk  p_sys->track[i_track]
+    i_track_skipping = 0;
+    for( i_track = 0; i_track < p_sys->i_track; i_track++ )
+    {
+        if( tk.fmt.i_cat == VIDEO_ES )
+        {
+            tk.b_search_keyframe = VLC_TRUE;
+            i_track_skipping++;
+        }
+    }
+
+    p_sys->i_start_pts = i_date;
+
+    while( i_track_skipping > 0 )
+    {
+        if( BlockGet( p_demux, &block, &i_block_ref1, &i_block_ref2, &i_block_duration ) )
+        {
+            msg_Warn( p_demux, "cannot get block EOF?" );
+
+            return;
+        }
+
+        p_sys->i_pts = block->GlobalTimecode() / (mtime_t) 1000;
+
+        for( i_track = 0; i_track < p_sys->i_track; i_track++ )
+        {
+            if( tk.i_number == block->TrackNum() )
+            {
+                break;
+            }
+        }
+
+        if( i_track < p_sys->i_track )
+        {
+            if( tk.fmt.i_cat == VIDEO_ES )
+            {
+                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, 0, 0 );
+/*                    es_out_Control( p_demux->out, ES_OUT_SET_PCR, block->GlobalTimecode() / (mtime_t) 1000 );*/
+                }
+            }
+        }
+
+        delete block;
+    }
+#undef tk
+}
+
+/*****************************************************************************
+ * Demux: reads and demuxes data packets
+ *****************************************************************************
+ * Returns -1 in case of error, 0 in case of EOF, 1 otherwise
+ *****************************************************************************/
+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;
+    int64_t i_block_duration;
+    int64_t i_block_ref1;
+    int64_t i_block_ref2;
+
+    i_start_pts = -1;
+
+    for( ;; )
+    {
+        if( BlockGet( p_demux, &block, &i_block_ref1, &i_block_ref2, &i_block_duration ) )
+        {
+            msg_Warn( p_demux, "cannot get block EOF?" );
+
+            return 0;
+        }
+
+        p_sys->i_pts = block->GlobalTimecode() / (mtime_t) 1000;
+
+        if( p_sys->i_pts >= p_sys->i_start_pts  )
+        {
+            es_out_Control( p_demux->out, ES_OUT_SET_PCR, p_sys->i_pts );
+        }
+
+        BlockDecode( p_demux, block, p_sys->i_pts, i_block_duration );
+
+        delete block;
+        i_block_count++;
+
+        if( p_sys->i_pts > i_start_pts + (mtime_t)100000 || i_block_count > 5 )
+        {
+            return 1;
+        }
+    }
+}
+
+
+
+/*****************************************************************************
+ * Stream managment
+ *****************************************************************************/
+vlc_stream_io_callback::vlc_stream_io_callback( stream_t *s_ )
+{
+    s = s_;
+    mb_eof = VLC_FALSE;
+}
+
+uint32 vlc_stream_io_callback::read( void *p_buffer, size_t i_size )
+{
+    if( i_size <= 0 || mb_eof )
+    {
+        return 0;
+    }
+
+    return stream_Read( s, p_buffer, i_size );
+}
+void vlc_stream_io_callback::setFilePointer(int64_t i_offset, seek_mode mode )
+{
+    int64_t i_pos;
+
+    switch( mode )
+    {
+        case seek_beginning:
+            i_pos = i_offset;
+            break;
+        case seek_end:
+            i_pos = stream_Size( s ) - i_offset;
+            break;
+        default:
+            i_pos= stream_Tell( s ) + i_offset;
+            break;
+    }
+
+    if( i_pos < 0 || i_pos >= stream_Size( s ) )
+    {
+        mb_eof = VLC_TRUE;
+        return;
+    }
+
+    mb_eof = VLC_FALSE;
+    if( stream_Seek( s, i_pos ) )
+    {
+        mb_eof = VLC_TRUE;
+    }
+    return;
+}
+size_t vlc_stream_io_callback::write( const void *p_buffer, size_t i_size )
+{
+    return 0;
+}
+uint64 vlc_stream_io_callback::getFilePointer( void )
+{
+    return stream_Tell( s );
+}
+void vlc_stream_io_callback::close( void )
+{
+    return;
+}
+
+
+/*****************************************************************************
+ * Ebml Stream parser
+ *****************************************************************************/
+EbmlParser::EbmlParser( EbmlStream *es, EbmlElement *el_start )
+{
+    int i;
+
+    m_es = es;
+    m_got = NULL;
+    m_el[0] = el_start;
+
+    for( i = 1; i < 6; i++ )
+    {
+        m_el[i] = NULL;
+    }
+    mi_level = 1;
+    mi_user_level = 1;
+    mb_keep = VLC_FALSE;
+}
+
+EbmlParser::~EbmlParser( void )
+{
+    int i;
+
+    for( i = 1; i < mi_level; i++ )
+    {
+        if( !mb_keep )
+        {
+            delete m_el[i];
+        }
+        mb_keep = VLC_FALSE;
+    }
+}
+
+void EbmlParser::Up( void )
+{
+    if( mi_user_level == mi_level )
+    {
+        fprintf( stderr," arrrrrrrrrrrrrg Up cannot escape itself\n" );
+    }
+
+    mi_user_level--;
+}
+
+void EbmlParser::Down( void )
+{
+    mi_user_level++;
+    mi_level++;
+}
+
+void EbmlParser::Keep( void )
+{
+    mb_keep = VLC_TRUE;
+}
+
+int EbmlParser::GetLevel( void )
+{
+    return mi_user_level;
+}
+
+EbmlElement *EbmlParser::Get( void )
+{
+    int i_ulev = 0;
+
+    if( mi_user_level != mi_level )
+    {
+        return NULL;
+    }
+    if( m_got )
+    {
+        EbmlElement *ret = m_got;
+        m_got = NULL;
+
+        return ret;
+    }
+
+    if( m_el[mi_level] )
+    {
+        m_el[mi_level]->SkipData( *m_es, m_el[mi_level]->Generic().Context );
+        if( !mb_keep )
+        {
+            delete m_el[mi_level];
+        }
+        mb_keep = VLC_FALSE;
+    }
+
+    m_el[mi_level] = m_es->FindNextElement( m_el[mi_level - 1]->Generic().Context, i_ulev, 0xFFFFFFFFL, true, 1 );
+    if( i_ulev > 0 )
+    {
+        while( i_ulev > 0 )
+        {
+            if( mi_level == 1 )
+            {
+                mi_level = 0;
+                return NULL;
+            }
+
+            delete m_el[mi_level - 1];
+            m_got = m_el[mi_level -1] = m_el[mi_level];
+            m_el[mi_level] = NULL;
+
+            mi_level--;
+            i_ulev--;
+        }
+        return NULL;
+    }
+    else if( m_el[mi_level] == NULL )
+    {
+        fprintf( stderr," m_el[mi_level] == NULL\n" );
+    }
+
+    return m_el[mi_level];
+}
+
+
+/*****************************************************************************
+ * Tools
+ *  * LoadCues : load the cues element and update index
+ *
+ *  * LoadTags : load ... the tags element
+ *
+ *  * InformationCreate : create all information, load tags if present
+ *
+ *****************************************************************************/
+static void LoadCues( demux_t *p_demux )
+{
+    demux_sys_t *p_sys = p_demux->p_sys;
+    int64_t     i_sav_position = p_sys->in->getFilePointer();
+    EbmlParser  *ep;
+    EbmlElement *el, *cues;
+
+    msg_Dbg( p_demux, "loading cues" );
+    p_sys->in->setFilePointer( p_sys->i_cues_position, seek_beginning );
+    cues = p_sys->es->FindNextID( KaxCues::ClassInfos, 0xFFFFFFFFL);
+
+    if( cues == NULL )
+    {
+        msg_Err( p_demux, "cannot load cues (broken seekhead or file)" );
+        p_sys->in->setFilePointer( i_sav_position, seek_beginning );
+        return;
+    }
+
+    ep = new EbmlParser( p_sys->es, cues );
+    while( ( el = ep->Get() ) != NULL )
+    {
+        if( MKV_IS_ID( el, KaxCuePoint ) )
+        {
+#define idx p_sys->index[p_sys->i_index]
+
+            idx.i_track       = -1;
+            idx.i_block_number= -1;
+            idx.i_position    = -1;
+            idx.i_time        = 0;
+            idx.b_key         = VLC_TRUE;
+
+            ep->Down();
+            while( ( el = ep->Get() ) != NULL )
+            {
+                if( MKV_IS_ID( el, KaxCueTime ) )
+                {
+                    KaxCueTime &ctime = *(KaxCueTime*)el;
+
+                    ctime.ReadData( p_sys->es->I_O() );
+
+                    idx.i_time = uint64( ctime ) * p_sys->i_timescale / (mtime_t)1000;
+                }
+                else if( MKV_IS_ID( el, KaxCueTrackPositions ) )
+                {
+                    ep->Down();
+                    while( ( el = ep->Get() ) != NULL )
+                    {
+                        if( MKV_IS_ID( el, KaxCueTrack ) )
+                        {
+                            KaxCueTrack &ctrack = *(KaxCueTrack*)el;
+
+                            ctrack.ReadData( p_sys->es->I_O() );
+                            idx.i_track = uint16( ctrack );
+                        }
+                        else if( MKV_IS_ID( el, KaxCueClusterPosition ) )
+                        {
+                            KaxCueClusterPosition &ccpos = *(KaxCueClusterPosition*)el;
+
+                            ccpos.ReadData( p_sys->es->I_O() );
+                            idx.i_position = p_sys->segment->GetGlobalPosition( uint64( ccpos ) );
+                        }
+                        else if( MKV_IS_ID( el, KaxCueBlockNumber ) )
+                        {
+                            KaxCueBlockNumber &cbnum = *(KaxCueBlockNumber*)el;
+
+                            cbnum.ReadData( p_sys->es->I_O() );
+                            idx.i_block_number = uint32( cbnum );
+                        }
+                        else
+                        {
+                            msg_Dbg( p_demux, "         * Unknown (%s)", typeid(*el).name() );
+                        }
+                    }
+                    ep->Up();
+                }
+                else
+                {
+                    msg_Dbg( p_demux, "     * Unknown (%s)", typeid(*el).name() );
+                }
+            }
+            ep->Up();
+
+#if 0
+            msg_Dbg( p_demux, " * added time="I64Fd" pos="I64Fd
+                     " track=%d bnum=%d", idx.i_time, idx.i_position,
+                     idx.i_track, idx.i_block_number );
+#endif
+
+            p_sys->i_index++;
+            if( p_sys->i_index >= p_sys->i_index_max )
+            {
+                p_sys->i_index_max += 1024;
+                p_sys->index = (mkv_index_t*)realloc( p_sys->index, sizeof( mkv_index_t ) * p_sys->i_index_max );
+            }
+#undef idx
+        }
+        else
+        {
+            msg_Dbg( p_demux, " * Unknown (%s)", typeid(*el).name() );
+        }
+    }
+    delete ep;
+    delete cues;
+
+    p_sys->b_cues = VLC_TRUE;
+
+    msg_Dbg( p_demux, "loading cues done." );
+    p_sys->in->setFilePointer( i_sav_position, seek_beginning );
+}
+
+static void LoadTags( demux_t *p_demux )
+{
+    demux_sys_t *p_sys = p_demux->p_sys;
+    int64_t     i_sav_position = p_sys->in->getFilePointer();
+    EbmlParser  *ep;
+    EbmlElement *el, *tags;
+
+    msg_Dbg( p_demux, "loading tags" );
+    p_sys->in->setFilePointer( p_sys->i_tags_position, seek_beginning );
+    tags = p_sys->es->FindNextID( KaxTags::ClassInfos, 0xFFFFFFFFL);
+
+    if( tags == NULL )
+    {
+        msg_Err( p_demux, "cannot load tags (broken seekhead or file)" );
+        p_sys->in->setFilePointer( i_sav_position, seek_beginning );
+        return;
+    }
+
+    msg_Dbg( p_demux, "Tags" );
+    ep = new EbmlParser( p_sys->es, tags );
+    while( ( el = ep->Get() ) != NULL )
+    {
+        if( MKV_IS_ID( el, KaxTag ) )
+        {
+            msg_Dbg( p_demux, "+ Tag" );
+            ep->Down();
+            while( ( el = ep->Get() ) != NULL )
+            {
+                if( MKV_IS_ID( el, KaxTagTargets ) )
+                {
+                    msg_Dbg( p_demux, "|   + Targets" );
+                    ep->Down();
+                    while( ( el = ep->Get() ) != NULL )
+                    {
+                        msg_Dbg( p_demux, "|   |   + Unknown (%s)", typeid( *el ).name() );
+                    }
+                    ep->Up();
+                }
+                else if( MKV_IS_ID( el, KaxTagGeneral ) )
+                {
+                    msg_Dbg( p_demux, "|   + General" );
+                    ep->Down();
+                    while( ( el = ep->Get() ) != NULL )
+                    {
+                        msg_Dbg( p_demux, "|   |   + Unknown (%s)", typeid( *el ).name() );
+                    }
+                    ep->Up();
+                }
+                else if( MKV_IS_ID( el, KaxTagGenres ) )
+                {
+                    msg_Dbg( p_demux, "|   + Genres" );
+                    ep->Down();
+                    while( ( el = ep->Get() ) != NULL )
+                    {
+                        msg_Dbg( p_demux, "|   |   + Unknown (%s)", typeid( *el ).name() );
+                    }
+                    ep->Up();
+                }
+                else if( MKV_IS_ID( el, KaxTagAudioSpecific ) )
+                {
+                    msg_Dbg( p_demux, "|   + Audio Specific" );
+                    ep->Down();
+                    while( ( el = ep->Get() ) != NULL )
+                    {
+                        msg_Dbg( p_demux, "|   |   + Unknown (%s)", typeid( *el ).name() );
+                    }
+                    ep->Up();
+                }
+                else if( MKV_IS_ID( el, KaxTagImageSpecific ) )
+                {
+                    msg_Dbg( p_demux, "|   + Images Specific" );
+                    ep->Down();
+                    while( ( el = ep->Get() ) != NULL )
+                    {
+                        msg_Dbg( p_demux, "|   |   + Unknown (%s)", typeid( *el ).name() );
+                    }
+                    ep->Up();
+                }
+                else if( MKV_IS_ID( el, KaxTagMultiComment ) )
+                {
+                    msg_Dbg( p_demux, "|   + Multi Comment" );
+                }
+                else if( MKV_IS_ID( el, KaxTagMultiCommercial ) )
+                {
+                    msg_Dbg( p_demux, "|   + Multi Commercial" );
+                }
+                else if( MKV_IS_ID( el, KaxTagMultiDate ) )
+                {
+                    msg_Dbg( p_demux, "|   + Multi Date" );
+                }
+                else if( MKV_IS_ID( el, KaxTagMultiEntity ) )
+                {
+                    msg_Dbg( p_demux, "|   + Multi Entity" );
+                }
+                else if( MKV_IS_ID( el, KaxTagMultiIdentifier ) )
+                {
+                    msg_Dbg( p_demux, "|   + Multi Identifier" );
+                }
+                else if( MKV_IS_ID( el, KaxTagMultiLegal ) )
+                {
+                    msg_Dbg( p_demux, "|   + Multi Legal" );
+                }
+                else if( MKV_IS_ID( el, KaxTagMultiTitle ) )
+                {
+                    msg_Dbg( p_demux, "|   + Multi Title" );
+                }
+                else
+                {
+                    msg_Dbg( p_demux, "|   + Unknown (%s)", typeid( *el ).name() );
+                }
+            }
+            ep->Up();
+        }
+        else
+        {
+            msg_Dbg( p_demux, "+ Unknown (%s)", typeid( *el ).name() );
+        }
+    }
+    delete ep;
+    delete tags;
+
+    msg_Dbg( p_demux, "loading tags done." );
+    p_sys->in->setFilePointer( i_sav_position, seek_beginning );
+}
+
+/*****************************************************************************
+ * ParseInfo:
+ *****************************************************************************/
+static void ParseSeekHead( demux_t *p_demux, EbmlElement *seekhead )
+{
+    demux_sys_t *p_sys = p_demux->p_sys;
+    EbmlElement *el;
+    EbmlMaster  *m;
+    unsigned int i;
+    int i_upper_level = 0;
+
+    msg_Dbg( p_demux, "|   + Seek head" );
+
+    /* Master elements */
+    m = static_cast<EbmlMaster *>(seekhead);
+    m->Read( *p_sys->es, seekhead->Generic().Context, i_upper_level, el, true );
+
+    for( i = 0; i < m->ListSize(); i++ )
+    {
+        EbmlElement *l = (*m)[i];
+
+        if( MKV_IS_ID( l, KaxSeek ) )
+        {
+            EbmlMaster *sk = static_cast<EbmlMaster *>(l);
+            EbmlId id = EbmlVoid::ClassInfos.GlobalId;
+            int64_t i_pos = -1;
+
+            unsigned int j;
+
+            for( j = 0; j < sk->ListSize(); j++ )
+            {
+                EbmlElement *l = (*sk)[j];
+
+                if( MKV_IS_ID( l, KaxSeekID ) )
+                {
+                    KaxSeekID &sid = *(KaxSeekID*)l;
+                    id = EbmlId( sid.GetBuffer(), sid.GetSize() );
+                }
+                else if( MKV_IS_ID( l, KaxSeekPosition ) )
+                {
+                    KaxSeekPosition &spos = *(KaxSeekPosition*)l;
+                    i_pos = uint64( spos );
+                }
+                else
+                {
+                    msg_Dbg( p_demux, "|   |   |   + Unknown (%s)", typeid(*l).name() );
+                }
+            }
+
+            if( i_pos >= 0 )
+            {
+                if( id == KaxCues::ClassInfos.GlobalId )
+                {
+                    msg_Dbg( p_demux, "|   |   |   = cues at "I64Fd, i_pos );
+                    p_sys->i_cues_position = p_sys->segment->GetGlobalPosition( i_pos );
+                }
+                else if( id == KaxChapters::ClassInfos.GlobalId )
+                {
+                    msg_Dbg( p_demux, "|   |   |   = chapters at "I64Fd, i_pos );
+                    p_sys->i_chapters_position = p_sys->segment->GetGlobalPosition( i_pos );
+                }
+                else if( id == KaxTags::ClassInfos.GlobalId )
+                {
+                    msg_Dbg( p_demux, "|   |   |   = tags at "I64Fd, i_pos );
+                    p_sys->i_tags_position = p_sys->segment->GetGlobalPosition( i_pos );
+                }
+            }
+        }
+        else
+        {
+            msg_Dbg( p_demux, "|   |   + Unknown (%s)", typeid(*l).name() );
+        }
+    }
+}
+
+/*****************************************************************************
+ * ParseTracks:
+ *****************************************************************************/
+static void ParseTrackEntry( demux_t *p_demux, EbmlMaster *m )
+{
+    demux_sys_t *p_sys = p_demux->p_sys;
+    unsigned int i;
+
+    mkv_track_t *tk;
+
+    msg_Dbg( p_demux, "|   |   + Track Entry" );
+
+    p_sys->i_track++;
+    p_sys->track = (mkv_track_t*)realloc( p_sys->track, sizeof( mkv_track_t ) * (p_sys->i_track + 1 ) );
+
+    /* Init the track */
+    tk = &p_sys->track[p_sys->i_track - 1];
+
+    memset( tk, 0, sizeof( mkv_track_t ) );
+
+    es_format_Init( &tk->fmt, UNKNOWN_ES, 0 );
+    tk->fmt.psz_language = strdup("English");
+    tk->fmt.psz_description = NULL;
+
+    tk->b_default = VLC_TRUE;
+    tk->b_enabled = VLC_TRUE;
+    tk->i_number = p_sys->i_track - 1;
+    tk->i_extra_data = 0;
+    tk->p_extra_data = NULL;
+    tk->psz_codec = NULL;
+    tk->i_default_duration = 0;
+    tk->f_timecodescale = 1.0;
+
+    tk->b_inited = VLC_FALSE;
+    tk->i_data_init = 0;
+    tk->p_data_init = NULL;
+
+    tk->psz_codec_name = NULL;
+    tk->psz_codec_settings = NULL;
+    tk->psz_codec_info_url = NULL;
+    tk->psz_codec_download_url = NULL;
+    
+    tk->i_compression_type = MATROSKA_COMPRESSION_NONE;
+
+    for( i = 0; i < m->ListSize(); i++ )
+    {
+        EbmlElement *l = (*m)[i];
+
+        if( MKV_IS_ID( l, KaxTrackNumber ) )
+        {
+            KaxTrackNumber &tnum = *(KaxTrackNumber*)l;
+
+            tk->i_number = uint32( tnum );
+            msg_Dbg( p_demux, "|   |   |   + Track Number=%u", uint32( tnum ) );
+        }
+        else  if( MKV_IS_ID( l, KaxTrackUID ) )
+        {
+            KaxTrackUID &tuid = *(KaxTrackUID*)l;
+
+            msg_Dbg( p_demux, "|   |   |   + Track UID=%u",  uint32( tuid ) );
+        }
+        else  if( MKV_IS_ID( l, KaxTrackType ) )
+        {
+            char *psz_type;
+            KaxTrackType &ttype = *(KaxTrackType*)l;
+
+            switch( uint8(ttype) )
+            {
+                case track_audio:
+                    psz_type = "audio";
+                    tk->fmt.i_cat = AUDIO_ES;
+                    break;
+                case track_video:
+                    psz_type = "video";
+                    tk->fmt.i_cat = VIDEO_ES;
+                    break;
+                case track_subtitle:
+                    psz_type = "subtitle";
+                    tk->fmt.i_cat = SPU_ES;
+                    break;
+                default:
+                    psz_type = "unknown";
+                    tk->fmt.i_cat = UNKNOWN_ES;
+                    break;
+            }
+
+            msg_Dbg( p_demux, "|   |   |   + Track Type=%s", psz_type );
+        }
+//        else  if( EbmlId( *l ) == KaxTrackFlagEnabled::ClassInfos.GlobalId )
+//        {
+//            KaxTrackFlagEnabled &fenb = *(KaxTrackFlagEnabled*)l;
+
+//            tk->b_enabled = uint32( fenb );
+//            msg_Dbg( p_demux, "|   |   |   + Track Enabled=%u",
+//                     uint32( fenb )  );
+//        }
+        else  if( MKV_IS_ID( l, KaxTrackFlagDefault ) )
+        {
+            KaxTrackFlagDefault &fdef = *(KaxTrackFlagDefault*)l;
+
+            tk->b_default = uint32( fdef );
+            msg_Dbg( p_demux, "|   |   |   + Track Default=%u", uint32( fdef )  );
+        }
+        else  if( MKV_IS_ID( l, KaxTrackFlagLacing ) )
+        {
+            KaxTrackFlagLacing &lac = *(KaxTrackFlagLacing*)l;
+
+            msg_Dbg( p_demux, "|   |   |   + Track Lacing=%d", uint32( lac ) );
+        }
+        else  if( MKV_IS_ID( l, KaxTrackMinCache ) )
+        {
+            KaxTrackMinCache &cmin = *(KaxTrackMinCache*)l;
+
+            msg_Dbg( p_demux, "|   |   |   + Track MinCache=%d", uint32( cmin ) );
+        }
+        else  if( MKV_IS_ID( l, KaxTrackMaxCache ) )
+        {
+            KaxTrackMaxCache &cmax = *(KaxTrackMaxCache*)l;
+
+            msg_Dbg( p_demux, "|   |   |   + Track MaxCache=%d", uint32( cmax ) );
+        }
+        else  if( MKV_IS_ID( l, KaxTrackDefaultDuration ) )
+        {
+            KaxTrackDefaultDuration &defd = *(KaxTrackDefaultDuration*)l;
+
+            tk->i_default_duration = uint64(defd);
+            msg_Dbg( p_demux, "|   |   |   + Track Default Duration="I64Fd, uint64(defd) );
+        }
+        else  if( MKV_IS_ID( l, KaxTrackTimecodeScale ) )
+        {
+            KaxTrackTimecodeScale &ttcs = *(KaxTrackTimecodeScale*)l;
+
+            tk->f_timecodescale = float( ttcs );
+            msg_Dbg( p_demux, "|   |   |   + Track TimeCodeScale=%f", tk->f_timecodescale );
+        }
+        else if( MKV_IS_ID( l, KaxTrackName ) )
+        {
+            KaxTrackName &tname = *(KaxTrackName*)l;
+
+            tk->fmt.psz_description = UTF8ToStr( UTFstring( tname ) );
+            msg_Dbg( p_demux, "|   |   |   + Track Name=%s", tk->fmt.psz_description );
+        }
+        else  if( MKV_IS_ID( l, KaxTrackLanguage ) )
+        {
+            KaxTrackLanguage &lang = *(KaxTrackLanguage*)l;
+
+            tk->fmt.psz_language = strdup( string( lang ).c_str() );
+            msg_Dbg( p_demux,
+                     "|   |   |   + Track Language=`%s'", tk->fmt.psz_language );
+        }
+        else  if( MKV_IS_ID( l, KaxCodecID ) )
+        {
+            KaxCodecID &codecid = *(KaxCodecID*)l;
+
+            tk->psz_codec = strdup( string( codecid ).c_str() );
+            msg_Dbg( p_demux, "|   |   |   + Track CodecId=%s", string( codecid ).c_str() );
+        }
+        else  if( MKV_IS_ID( l, KaxCodecPrivate ) )
+        {
+            KaxCodecPrivate &cpriv = *(KaxCodecPrivate*)l;
+
+            tk->i_extra_data = cpriv.GetSize();
+            if( tk->i_extra_data > 0 )
+            {
+                tk->p_extra_data = (uint8_t*)malloc( tk->i_extra_data );
+                memcpy( tk->p_extra_data, cpriv.GetBuffer(), tk->i_extra_data );
+            }
+            msg_Dbg( p_demux, "|   |   |   + Track CodecPrivate size="I64Fd, cpriv.GetSize() );
+        }
+        else if( MKV_IS_ID( l, KaxCodecName ) )
+        {
+            KaxCodecName &cname = *(KaxCodecName*)l;
+
+            tk->psz_codec_name = UTF8ToStr( UTFstring( cname ) );
+            msg_Dbg( p_demux, "|   |   |   + Track Codec Name=%s", tk->psz_codec_name );
+        }
+        else if( MKV_IS_ID( l, KaxContentEncodings ) )
+        {
+            EbmlMaster *cencs = static_cast<EbmlMaster*>(l);
+            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 ) )
+                {
+                    MkvTree( p_demux, 4, "Content Encoding" );
+                    EbmlMaster *cenc = static_cast<EbmlMaster*>(l2);
+                    for( unsigned int i = 0; i < cenc->ListSize(); i++ )
+                    {
+                        EbmlElement *l3 = (*cenc)[i];
+                        if( MKV_IS_ID( l3, KaxContentEncodingOrder ) )
+                        {
+                            KaxContentEncodingOrder &encord = *(KaxContentEncodingOrder*)l3;
+                            MkvTree( p_demux, 5, "Order: %i", uint32( encord ) );
+                        }
+                        else if( MKV_IS_ID( l3, KaxContentEncodingScope ) )
+                        {
+                            KaxContentEncodingScope &encscope = *(KaxContentEncodingScope*)l3;
+                            MkvTree( p_demux, 5, "Scope: %i", uint32( encscope ) );
+                        }
+                        else if( MKV_IS_ID( l3, KaxContentEncodingType ) )
+                        {
+                            KaxContentEncodingType &enctype = *(KaxContentEncodingType*)l3;
+                            MkvTree( p_demux, 5, "Type: %i", uint32( enctype ) );
+                        }
+                        else if( MKV_IS_ID( l3, KaxContentCompression ) )
+                        {
+                            EbmlMaster *compr = static_cast<EbmlMaster*>(l3);
+                            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;
+                                    MkvTree( p_demux, 6, "Compression Algorithm: %i", uint32(compalg) );
+                                    if( uint32( compalg ) == 0 )
+                                    {
+                                        tk->i_compression_type = MATROSKA_COMPRESSION_ZLIB;
+                                    }
+                                }
+                                else
+                                {
+                                    MkvTree( p_demux, 6, "Unknown (%s)", typeid(*l4).name() );
+                                }
+                            }
+                        }
+
+                        else
+                        {
+                            MkvTree( p_demux, 5, "Unknown (%s)", typeid(*l3).name() );
+                        }
+                    }
+                    
+                }
+                else
+                {
+                    MkvTree( p_demux, 4, "Unknown (%s)", typeid(*l2).name() );
+                }
+            }
+                
+        }
+//        else if( EbmlId( *l ) == KaxCodecSettings::ClassInfos.GlobalId )
+//        {
+//            KaxCodecSettings &cset = *(KaxCodecSettings*)l;
+
+//            tk->psz_codec_settings = UTF8ToStr( UTFstring( cset ) );
+//            msg_Dbg( p_demux, "|   |   |   + Track Codec Settings=%s", tk->psz_codec_settings );
+//        }
+//        else if( EbmlId( *l ) == KaxCodecInfoURL::ClassInfos.GlobalId )
+//        {
+//            KaxCodecInfoURL &ciurl = *(KaxCodecInfoURL*)l;
+
+//            tk->psz_codec_info_url = strdup( string( ciurl ).c_str() );
+//            msg_Dbg( p_demux, "|   |   |   + Track Codec Info URL=%s", tk->psz_codec_info_url );
+//        }
+//        else if( EbmlId( *l ) == KaxCodecDownloadURL::ClassInfos.GlobalId )
+//        {
+//            KaxCodecDownloadURL &cdurl = *(KaxCodecDownloadURL*)l;
+
+//            tk->psz_codec_download_url = strdup( string( cdurl ).c_str() );
+//            msg_Dbg( p_demux, "|   |   |   + Track Codec Info URL=%s", tk->psz_codec_download_url );
+//        }
+//        else if( EbmlId( *l ) == KaxCodecDecodeAll::ClassInfos.GlobalId )
+//        {
+//            KaxCodecDecodeAll &cdall = *(KaxCodecDecodeAll*)l;
+
+//            msg_Dbg( p_demux, "|   |   |   + Track Codec Decode All=%u <== UNUSED", uint8( cdall ) );
+//        }
+//        else if( EbmlId( *l ) == KaxTrackOverlay::ClassInfos.GlobalId )
+//        {
+//            KaxTrackOverlay &tovr = *(KaxTrackOverlay*)l;
+
+//            msg_Dbg( p_demux, "|   |   |   + Track Overlay=%u <== UNUSED", uint32( tovr ) );
+//        }
+        else  if( MKV_IS_ID( l, KaxTrackVideo ) )
+        {
+            EbmlMaster *tkv = static_cast<EbmlMaster*>(l);
+            unsigned int j;
+
+            msg_Dbg( p_demux, "|   |   |   + Track Video" );
+            tk->f_fps = 0.0;
+
+            for( j = 0; j < tkv->ListSize(); j++ )
+            {
+                EbmlElement *l = (*tkv)[j];
+//                if( EbmlId( *el4 ) == KaxVideoFlagInterlaced::ClassInfos.GlobalId )
+//                {
+//                    KaxVideoFlagInterlaced &fint = *(KaxVideoFlagInterlaced*)el4;
+
+//                    msg_Dbg( p_demux, "|   |   |   |   + Track Video Interlaced=%u", uint8( fint ) );
+//                }
+//                else if( EbmlId( *el4 ) == KaxVideoStereoMode::ClassInfos.GlobalId )
+//                {
+//                    KaxVideoStereoMode &stereo = *(KaxVideoStereoMode*)el4;
+
+//                    msg_Dbg( p_demux, "|   |   |   |   + Track Video Stereo Mode=%u", uint8( stereo ) );
+//                }
+//                else
+                if( MKV_IS_ID( l, KaxVideoPixelWidth ) )
+                {
+                    KaxVideoPixelWidth &vwidth = *(KaxVideoPixelWidth*)l;
+
+                    tk->fmt.video.i_width = uint16( vwidth );
+                    msg_Dbg( p_demux, "|   |   |   |   + width=%d", uint16( vwidth ) );
+                }
+                else if( MKV_IS_ID( l, KaxVideoPixelHeight ) )
+                {
+                    KaxVideoPixelWidth &vheight = *(KaxVideoPixelWidth*)l;
+
+                    tk->fmt.video.i_height = uint16( vheight );
+                    msg_Dbg( p_demux, "|   |   |   |   + height=%d", uint16( vheight ) );
+                }
+                else if( MKV_IS_ID( l, KaxVideoDisplayWidth ) )
+                {
+                    KaxVideoDisplayWidth &vwidth = *(KaxVideoDisplayWidth*)l;
+
+                    tk->fmt.video.i_visible_width = uint16( vwidth );
+                    msg_Dbg( p_demux, "|   |   |   |   + display width=%d", uint16( vwidth ) );
+                }
+                else if( MKV_IS_ID( l, KaxVideoDisplayHeight ) )
+                {
+                    KaxVideoDisplayWidth &vheight = *(KaxVideoDisplayWidth*)l;
+
+                    tk->fmt.video.i_visible_height = uint16( vheight );
+                    msg_Dbg( p_demux, "|   |   |   |   + display height=%d", uint16( vheight ) );
+                }
+                else if( MKV_IS_ID( l, KaxVideoFrameRate ) )
+                {
+                    KaxVideoFrameRate &vfps = *(KaxVideoFrameRate*)l;
+
+                    tk->f_fps = float( vfps );
+                    msg_Dbg( p_demux, "   |   |   |   + fps=%f", float( vfps ) );
+                }
+//                else if( EbmlId( *l ) == KaxVideoDisplayUnit::ClassInfos.GlobalId )
+//                {
+//                     KaxVideoDisplayUnit &vdmode = *(KaxVideoDisplayUnit*)l;
+
+//                    msg_Dbg( p_demux, "|   |   |   |   + Track Video Display Unit=%s",
+//                             uint8( vdmode ) == 0 ? "pixels" : ( uint8( vdmode ) == 1 ? "centimeters": "inches" ) );
+//                }
+//                else if( EbmlId( *l ) == KaxVideoAspectRatio::ClassInfos.GlobalId )
+//                {
+//                    KaxVideoAspectRatio &ratio = *(KaxVideoAspectRatio*)l;
+
+//                    msg_Dbg( p_demux, "   |   |   |   + Track Video Aspect Ratio Type=%u", uint8( ratio ) );
+//                }
+//                else if( EbmlId( *l ) == KaxVideoGamma::ClassInfos.GlobalId )
+//                {
+//                    KaxVideoGamma &gamma = *(KaxVideoGamma*)l;
+
+//                    msg_Dbg( p_demux, "   |   |   |   + fps=%f", float( gamma ) );
+//                }
+                else
+                {
+                    msg_Dbg( p_demux, "|   |   |   |   + Unknown (%s)", typeid(*l).name() );
+                }
+            }
+        }
+        else  if( MKV_IS_ID( l, KaxTrackAudio ) )
+        {
+            EbmlMaster *tka = static_cast<EbmlMaster*>(l);
+            unsigned int j;
+
+            msg_Dbg( p_demux, "|   |   |   + Track Audio" );
+
+            for( j = 0; j < tka->ListSize(); j++ )
+            {
+                EbmlElement *l = (*tka)[j];
+
+                if( MKV_IS_ID( l, KaxAudioSamplingFreq ) )
+                {
+                    KaxAudioSamplingFreq &afreq = *(KaxAudioSamplingFreq*)l;
+
+                    tk->fmt.audio.i_rate = (int)float( afreq );
+                    msg_Dbg( p_demux, "|   |   |   |   + afreq=%d", tk->fmt.audio.i_rate );
+                }
+                else if( MKV_IS_ID( l, KaxAudioChannels ) )
+                {
+                    KaxAudioChannels &achan = *(KaxAudioChannels*)l;
+
+                    tk->fmt.audio.i_channels = uint8( achan );
+                    msg_Dbg( p_demux, "|   |   |   |   + achan=%u", uint8( achan ) );
+                }
+                else if( MKV_IS_ID( l, KaxAudioBitDepth ) )
+                {
+                    KaxAudioBitDepth &abits = *(KaxAudioBitDepth*)l;
+
+                    tk->fmt.audio.i_bitspersample = uint8( abits );
+                    msg_Dbg( p_demux, "|   |   |   |   + abits=%u", uint8( abits ) );
+                }
+                else
+                {
+                    msg_Dbg( p_demux, "|   |   |   |   + Unknown (%s)", typeid(*l).name() );
+                }
+            }
+        }
+        else
+        {
+            msg_Dbg( p_demux, "|   |   |   + Unknown (%s)",
+                     typeid(*l).name() );
+        }
+    }
+}
+
+static void ParseTracks( demux_t *p_demux, EbmlElement *tracks )
+{
+    demux_sys_t *p_sys = p_demux->p_sys;
+    EbmlElement *el;
+    EbmlMaster  *m;
+    unsigned int i;
+    int i_upper_level = 0;
+
+    msg_Dbg( p_demux, "|   + Tracks" );
+
+    /* Master elements */
+    m = static_cast<EbmlMaster *>(tracks);
+    m->Read( *p_sys->es, tracks->Generic().Context, i_upper_level, el, true );
+
+    for( i = 0; i < m->ListSize(); i++ )
+    {
+        EbmlElement *l = (*m)[i];
+
+        if( MKV_IS_ID( l, KaxTrackEntry ) )
+        {
+            ParseTrackEntry( p_demux, static_cast<EbmlMaster *>(l) );
+        }
+        else
+        {
+            msg_Dbg( p_demux, "|   |   + Unknown (%s)", typeid(*l).name() );
+        }
+    }
+}
+
+/*****************************************************************************
+ * ParseInfo:
+ *****************************************************************************/
+static void ParseInfo( demux_t *p_demux, EbmlElement *info )
+{
+    demux_sys_t *p_sys = p_demux->p_sys;
+    EbmlElement *el;
+    EbmlMaster  *m;
+    unsigned int i;
+    int i_upper_level = 0;
+
+    msg_Dbg( p_demux, "|   + Information" );
+
+    /* Master elements */
+    m = static_cast<EbmlMaster *>(info);
+    m->Read( *p_sys->es, info->Generic().Context, i_upper_level, el, true );
+
+    for( i = 0; i < m->ListSize(); i++ )
+    {
+        EbmlElement *l = (*m)[i];
+
+        if( MKV_IS_ID( l, KaxSegmentUID ) )
+        {
+            p_sys->segment_uid = *(new KaxSegmentUID(*static_cast<KaxSegmentUID*>(l)));
+
+            msg_Dbg( p_demux, "|   |   + UID=%d", *(uint32*)p_sys->segment_uid.GetBuffer() );
+        }
+        else if( MKV_IS_ID( l, KaxTimecodeScale ) )
+        {
+            KaxTimecodeScale &tcs = *(KaxTimecodeScale*)l;
+
+            p_sys->i_timescale = uint64(tcs);
+
+            msg_Dbg( p_demux, "|   |   + TimecodeScale="I64Fd,
+                     p_sys->i_timescale );
+        }
+        else if( MKV_IS_ID( l, KaxDuration ) )
+        {
+            KaxDuration &dur = *(KaxDuration*)l;
+
+            p_sys->f_duration = float(dur);
+
+            msg_Dbg( p_demux, "|   |   + Duration=%f",
+                     p_sys->f_duration );
+        }
+        else if( MKV_IS_ID( l, KaxMuxingApp ) )
+        {
+            KaxMuxingApp &mapp = *(KaxMuxingApp*)l;
+
+            p_sys->psz_muxing_application = UTF8ToStr( UTFstring( mapp ) );
+
+            msg_Dbg( p_demux, "|   |   + Muxing Application=%s",
+                     p_sys->psz_muxing_application );
+        }
+        else if( MKV_IS_ID( l, KaxWritingApp ) )
+        {
+            KaxWritingApp &wapp = *(KaxWritingApp*)l;
+
+            p_sys->psz_writing_application = UTF8ToStr( UTFstring( wapp ) );
+
+            msg_Dbg( p_demux, "|   |   + Writing Application=%s",
+                     p_sys->psz_writing_application );
+        }
+        else if( MKV_IS_ID( l, KaxSegmentFilename ) )
+        {
+            KaxSegmentFilename &sfn = *(KaxSegmentFilename*)l;
+
+            p_sys->psz_segment_filename = UTF8ToStr( UTFstring( sfn ) );
+
+            msg_Dbg( p_demux, "|   |   + Segment Filename=%s",
+                     p_sys->psz_segment_filename );
+        }
+        else if( MKV_IS_ID( l, KaxTitle ) )
+        {
+            KaxTitle &title = *(KaxTitle*)l;
+
+            p_sys->psz_title = UTF8ToStr( UTFstring( title ) );
+
+            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 ) )
+        {
+            KaxDateUTC &date = *(KaxDateUTC*)l;
+            time_t i_date;
+            struct tm tmres;
+            char   buffer[256];
+
+            i_date = date.GetEpochDate();
+            memset( buffer, 0, 256 );
+            if( gmtime_r( &i_date, &tmres ) &&
+                asctime_r( &tmres, buffer ) )
+            {
+                buffer[strlen( buffer)-1]= '\0';
+                p_sys->psz_date_utc = strdup( buffer );
+                msg_Dbg( p_demux, "|   |   + Date=%s", p_sys->psz_date_utc );
+            }
+        }
+#endif
+        else
+        {
+            msg_Dbg( p_demux, "|   |   + Unknown (%s)", typeid(*l).name() );
+        }
+    }
+
+    p_sys->f_duration *= p_sys->i_timescale / 1000000.0;
+}
+
+
+/*****************************************************************************
+ * ParseChapterAtom
+ *****************************************************************************/
+static void ParseChapterAtom( demux_t *p_demux, int i_level, EbmlMaster *ca )
+{
+    demux_sys_t *p_sys = p_demux->p_sys;
+    unsigned int i;
+    seekpoint_t *sk;
+    bool b_display_seekpoint = true;
+
+    if( p_sys->title == NULL )
+    {
+        p_sys->title = vlc_input_title_New();
+    }
+    sk = vlc_seekpoint_New();
+
+    sk->i_level = i_level;
+
+    msg_Dbg( p_demux, "|   |   |   + ChapterAtom (level=%d)", i_level );
+    for( i = 0; i < ca->ListSize(); i++ )
+    {
+        EbmlElement *l = (*ca)[i];
+
+        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 );
+        }
+        else if( MKV_IS_ID( l, KaxChapterFlagHidden ) )
+        {
+            KaxChapterFlagHidden &flag =*(KaxChapterFlagHidden*)l;
+            b_display_seekpoint = uint8( flag ) == 0;
+
+            msg_Dbg( p_demux, "|   |   |   |   + ChapterFlagHidden: %s", b_display_seekpoint ? "no":"yes" );
+        }
+        else if( MKV_IS_ID( l, KaxChapterTimeStart ) )
+        {
+            KaxChapterTimeStart &start =*(KaxChapterTimeStart*)l;
+            sk->i_time_offset = uint64( start ) / I64C(1000);
+
+            msg_Dbg( p_demux, "|   |   |   |   + ChapterTimeStart: %lld", sk->i_time_offset );
+        }
+        else if( MKV_IS_ID( l, KaxChapterTimeEnd ) )
+        {
+            KaxChapterTimeEnd &end =*(KaxChapterTimeEnd*)l;
+            int64_t i_end = uint64( end );
+
+            msg_Dbg( p_demux, "|   |   |   |   + ChapterTimeEnd: %lld", i_end );
+        }
+        else if( MKV_IS_ID( l, KaxChapterDisplay ) )
+        {
+            EbmlMaster *cd = static_cast<EbmlMaster *>(l);
+            unsigned int j;
+
+            msg_Dbg( p_demux, "|   |   |   |   + ChapterDisplay" );
+            for( j = 0; j < cd->ListSize(); j++ )
+            {
+                EbmlElement *l= (*cd)[j];
+
+                if( MKV_IS_ID( l, KaxChapterString ) )
+                {
+                    std::string psz;
+                    int k;
+
+                    KaxChapterString &name =*(KaxChapterString*)l;
+                    for (k = 0; k < i_level; k++)
+                        psz += '+';
+                    psz += ' ';
+                    psz += UTF8ToStr( UTFstring( name ) );
+                    sk->psz_name = strdup( psz.c_str() );
+                    msg_Dbg( p_demux, "|   |   |   |   |    + ChapterString '%s'", UTF8ToStr(UTFstring(name)) );
+                }
+                else if( MKV_IS_ID( l, KaxChapterLanguage ) )
+                {
+                    KaxChapterLanguage &lang =*(KaxChapterLanguage*)l;
+                    const char *psz = string( lang ).c_str();
+
+                    msg_Dbg( p_demux, "|   |   |   |   |    + ChapterLanguage '%s'", psz );
+                }
+                else if( MKV_IS_ID( l, KaxChapterCountry ) )
+                {
+                    KaxChapterCountry &ct =*(KaxChapterCountry*)l;
+                    const char *psz = string( ct ).c_str();
+
+                    msg_Dbg( p_demux, "|   |   |   |   |    + ChapterCountry '%s'", psz );
+                }
+            }
+        }
+        else if( MKV_IS_ID( l, KaxChapterAtom ) )
+        {
+            ParseChapterAtom( p_demux, i_level+1, static_cast<EbmlMaster *>(l) );
+        }
+    }
+
+    if (b_display_seekpoint)
+    {
+        // 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;
+    }
+    else
+    {
+        vlc_seekpoint_Delete(sk);
+    }
+}
+
+/*****************************************************************************
+ * ParseChapters:
+ *****************************************************************************/
+static void ParseChapters( demux_t *p_demux, EbmlElement *chapters )
+{
+    demux_sys_t *p_sys = p_demux->p_sys;
+    EbmlElement *el;
+    EbmlMaster  *m;
+    unsigned int i;
+    int i_upper_level = 0;
+
+
+    /* Master elements */
+    m = static_cast<EbmlMaster *>(chapters);
+    m->Read( *p_sys->es, chapters->Generic().Context, i_upper_level, el, true );
+
+    for( i = 0; i < m->ListSize(); i++ )
+    {
+        EbmlElement *l = (*m)[i];
+
+        if( MKV_IS_ID( l, KaxEditionEntry ) )
+        {
+            EbmlMaster *E = static_cast<EbmlMaster *>(l );
+            unsigned int j;
+            msg_Dbg( p_demux, "|   |   + EditionEntry" );
+            p_sys->edition_ordered = false;
+            for( j = 0; j < E->ListSize(); j++ )
+            {
+                EbmlElement *l = (*E)[j];
+
+                if( MKV_IS_ID( l, KaxChapterAtom ) )
+                {
+                    ParseChapterAtom( p_demux, 0, static_cast<EbmlMaster *>(l) );
+                }
+                else if( MKV_IS_ID( l, KaxEditionUID ) )
+                {
+                    p_sys->edition_uid = uint64(*static_cast<KaxEditionUID *>(l));
+                }
+                else if( MKV_IS_ID( l, KaxEditionFlagOrdered ) )
+                {
+                    p_sys->edition_ordered = uint8(*static_cast<KaxEditionFlagOrdered *>(l)) != 0;
+                }
+                else
+                {
+                    msg_Dbg( p_demux, "|   |   |   + Unknown (%s)", typeid(*l).name() );
+                }
+            }
+        }
+        else
+        {
+            msg_Dbg( p_demux, "|   |   + Unknown (%s)", typeid(*l).name() );
+        }
+    }
+}
+
+/*****************************************************************************
+ * InformationCreate:
+ *****************************************************************************/
+static void InformationCreate( demux_t *p_demux )
+{
+    demux_sys_t *p_sys = p_demux->p_sys;
+    int         i_track;
+
+    p_sys->meta = vlc_meta_New();
+
+    if( p_sys->psz_title )
+    {
+        vlc_meta_Add( p_sys->meta, VLC_META_TITLE, p_sys->psz_title );
+    }
+    if( p_sys->psz_date_utc )
+    {
+        vlc_meta_Add( p_sys->meta, VLC_META_DATE, p_sys->psz_date_utc );
+    }
+    if( p_sys->psz_segment_filename )
+    {
+        vlc_meta_Add( p_sys->meta, _("Segment filename"), p_sys->psz_segment_filename );
+    }
+    if( p_sys->psz_muxing_application )
+    {
+        vlc_meta_Add( p_sys->meta, _("Muxing application"), p_sys->psz_muxing_application );
+    }
+    if( p_sys->psz_writing_application )
+    {
+        vlc_meta_Add( p_sys->meta, _("Writing application"), p_sys->psz_writing_application );
+    }
+
+    for( i_track = 0; i_track < p_sys->i_track; i_track++ )
+    {
+        mkv_track_t *tk = &p_sys->track[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;
+
+        if( tk->fmt.psz_description )
+        {
+            vlc_meta_Add( p_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 );
+        }
+        if( tk->psz_codec_settings )
+        {
+            vlc_meta_Add( p_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 );
+        }
+        if( tk->psz_codec_download_url )
+        {
+            vlc_meta_Add( p_sys->meta, VLC_META_URL, tk->psz_codec_download_url );
+        }
+    }
+
+    if( p_sys->i_tags_position >= 0 )
+    {
+        vlc_bool_t b_seekable;
+
+        stream_Control( p_demux->s, STREAM_CAN_FASTSEEK, &b_seekable );
+        if( b_seekable )
+        {
+            LoadTags( p_demux );
+        }
+    }
+}
+
+
+/*****************************************************************************
+ * Divers
+ *****************************************************************************/
+
+static void IndexAppendCluster( demux_t *p_demux, KaxCluster *cluster )
+{
+    demux_sys_t *p_sys = p_demux->p_sys;
+
+#define idx p_sys->index[p_sys->i_index]
+    idx.i_track       = -1;
+    idx.i_block_number= -1;
+    idx.i_position    = cluster->GetElementPosition();
+    idx.i_time        = -1;
+    idx.b_key         = VLC_TRUE;
+
+    p_sys->i_index++;
+    if( p_sys->i_index >= p_sys->i_index_max )
+    {
+        p_sys->i_index_max += 1024;
+        p_sys->index = (mkv_index_t*)realloc( p_sys->index, sizeof( mkv_index_t ) * p_sys->i_index_max );
+    }
+#undef idx
+}
+
+static char * UTF8ToStr( const UTFstring &u )
+{
+    int     i_src;
+    const wchar_t *src;
+    char *dst, *p;
+
+    i_src = u.length();
+    src   = u.c_str();
+
+    p = dst = (char*)malloc( i_src + 1);
+    while( i_src > 0 )
+    {
+        if( *src < 255 )
+        {
+            *p++ = (char)*src;
+        }
+        else
+        {
+            *p++ = '?';
+        }
+        src++;
+        i_src--;
+    }
+    *p++= '\0';
+
+    return dst;
+}
+