]> git.sesse.net Git - vlc/blob - modules/demux/mkv.cpp
438a0f0853e956380d7e777c19329cfaf2a7ed0a
[vlc] / modules / demux / mkv.cpp
1 /*****************************************************************************
2  * mkv.cpp : matroska demuxer
3  *****************************************************************************
4  * Copyright (C) 2003-2004 VideoLAN
5  * $Id$
6  *
7  * Authors: Laurent Aimar <fenrir@via.ecp.fr>
8  *          Steve Lhomme <steve.lhomme@free.fr>
9  *
10  * This program is free software; you can redistribute it and/or modify
11  * it under the terms of the GNU General Public License as published by
12  * the Free Software Foundation; either version 2 of the License, or
13  * (at your option) any later version.
14  *
15  * This program is distributed in the hope that it will be useful,
16  * but WITHOUT ANY WARRANTY; without even the implied warranty of
17  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
18  * GNU General Public License for more details.
19  *
20  * You should have received a copy of the GNU General Public License
21  * along with this program; if not, write to the Free Software
22  * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111, USA.
23  *****************************************************************************/
24
25 /*****************************************************************************
26  * Preamble
27  *****************************************************************************/
28 #include <stdlib.h>                                      /* malloc(), free() */
29
30 #include <vlc/vlc.h>
31
32 #ifdef HAVE_TIME_H
33 #   include <time.h>                                               /* time() */
34 #endif
35
36 #include <vlc/input.h>
37
38 #include <codecs.h>                        /* BITMAPINFOHEADER, WAVEFORMATEX */
39 #include "iso_lang.h"
40 #include "vlc_meta.h"
41
42 #include <iostream>
43 #include <cassert>
44 #include <typeinfo>
45 #include <string>
46 #include <vector>
47 #include <algorithm>
48
49 #ifdef HAVE_DIRENT_H
50 #   include <dirent.h>
51 #endif
52
53 /* libebml and matroska */
54 #include "ebml/EbmlHead.h"
55 #include "ebml/EbmlSubHead.h"
56 #include "ebml/EbmlStream.h"
57 #include "ebml/EbmlContexts.h"
58 #include "ebml/EbmlVoid.h"
59 #include "ebml/StdIOCallback.h"
60
61 #include "matroska/KaxAttachments.h"
62 #include "matroska/KaxBlock.h"
63 #include "matroska/KaxBlockData.h"
64 #include "matroska/KaxChapters.h"
65 #include "matroska/KaxCluster.h"
66 #include "matroska/KaxClusterData.h"
67 #include "matroska/KaxContexts.h"
68 #include "matroska/KaxCues.h"
69 #include "matroska/KaxCuesData.h"
70 #include "matroska/KaxInfo.h"
71 #include "matroska/KaxInfoData.h"
72 #include "matroska/KaxSeekHead.h"
73 #include "matroska/KaxSegment.h"
74 #include "matroska/KaxTag.h"
75 #include "matroska/KaxTags.h"
76 #include "matroska/KaxTagMulti.h"
77 #include "matroska/KaxTracks.h"
78 #include "matroska/KaxTrackAudio.h"
79 #include "matroska/KaxTrackVideo.h"
80 #include "matroska/KaxTrackEntryData.h"
81 #include "matroska/KaxContentEncoding.h"
82
83 #include "ebml/StdIOCallback.h"
84
85 extern "C" {
86    #include "mp4/libmp4.h"
87 }
88 #ifdef HAVE_ZLIB_H
89 #   include <zlib.h>
90 #endif
91
92 #define MATROSKA_COMPRESSION_NONE 0
93 #define MATROSKA_COMPRESSION_ZLIB 1
94
95 /**
96  * What's between a directory and a filename?
97  */
98 #if defined( WIN32 )
99     #define DIRECTORY_SEPARATOR '\\'
100 #else
101     #define DIRECTORY_SEPARATOR '/'
102 #endif
103
104 using namespace LIBMATROSKA_NAMESPACE;
105 using namespace std;
106
107 /*****************************************************************************
108  * Module descriptor
109  *****************************************************************************/
110 static int  Open ( vlc_object_t * );
111 static void Close( vlc_object_t * );
112
113 vlc_module_begin();
114     set_shortname( _("Matroska") );
115     set_description( _("Matroska stream demuxer" ) );
116     set_capability( "demux2", 50 );
117     set_callbacks( Open, Close );
118     set_category( CAT_INPUT );
119     set_subcategory( SUBCAT_INPUT_DEMUX );
120
121     add_bool( "mkv-seek-percent", 1, NULL,
122             N_("Seek based on percent not time"),
123             N_("Seek based on percent not time"), VLC_TRUE );
124
125     add_shortcut( "mka" );
126     add_shortcut( "mkv" );
127 vlc_module_end();
128
129 /*****************************************************************************
130  * Local prototypes
131  *****************************************************************************/
132 #ifdef HAVE_ZLIB_H
133 block_t *block_zlib_decompress( vlc_object_t *p_this, block_t *p_in_block ) {
134     int result, dstsize, n;
135     unsigned char *dst;
136     block_t *p_block;
137     z_stream d_stream;
138
139     d_stream.zalloc = (alloc_func)0;
140     d_stream.zfree = (free_func)0;
141     d_stream.opaque = (voidpf)0;
142     result = inflateInit(&d_stream);
143     if( result != Z_OK )
144     {
145         msg_Dbg( p_this, "inflateInit() failed. Result: %d", result );
146         return NULL;
147     }
148
149     d_stream.next_in = (Bytef *)p_in_block->p_buffer;
150     d_stream.avail_in = p_in_block->i_buffer;
151     n = 0;
152     p_block = block_New( p_this, 0 );
153     dst = NULL;
154     do
155     {
156         n++;
157         p_block = block_Realloc( p_block, 0, n * 1000 );
158         dst = (unsigned char *)p_block->p_buffer;
159         d_stream.next_out = (Bytef *)&dst[(n - 1) * 1000];
160         d_stream.avail_out = 1000;
161         result = inflate(&d_stream, Z_NO_FLUSH);
162         if( ( result != Z_OK ) && ( result != Z_STREAM_END ) )
163         {
164             msg_Dbg( p_this, "Zlib decompression failed. Result: %d", result );
165             return NULL;
166         }
167     }
168     while( ( d_stream.avail_out == 0 ) && ( d_stream.avail_in != 0 ) &&
169            ( result != Z_STREAM_END ) );
170
171     dstsize = d_stream.total_out;
172     inflateEnd( &d_stream );
173
174     p_block = block_Realloc( p_block, 0, dstsize );
175     p_block->i_buffer = dstsize;
176     block_Release( p_in_block );
177
178     return p_block;
179 }
180 #endif
181
182 /**
183  * Helper function to print the mkv parse tree
184  */
185 static void MkvTree( demux_t *p_this, int i_level, char *psz_format, ... )
186 {
187     va_list args;
188     if( i_level > 9 )
189     {
190         msg_Err( p_this, "too deep tree" );
191         return;
192     }
193     va_start( args, psz_format );
194     static char *psz_foo = "|   |   |   |   |   |   |   |   |   |";
195     char *psz_foo2 = (char*)malloc( ( i_level * 4 + 3 + strlen( psz_format ) ) * sizeof(char) );
196     strncpy( psz_foo2, psz_foo, 4 * i_level );
197     psz_foo2[ 4 * i_level ] = '+';
198     psz_foo2[ 4 * i_level + 1 ] = ' ';
199     strcpy( &psz_foo2[ 4 * i_level + 2 ], psz_format );
200     __msg_GenericVa( VLC_OBJECT(p_this), VLC_MSG_DBG, "mkv", psz_foo2, args );
201     free( psz_foo2 );
202     va_end( args );
203 }
204     
205 /*****************************************************************************
206  * Stream managment
207  *****************************************************************************/
208 class vlc_stream_io_callback: public IOCallback
209 {
210   private:
211     stream_t       *s;
212     vlc_bool_t     mb_eof;
213
214   public:
215     vlc_stream_io_callback( stream_t * );
216
217     virtual uint32   read            ( void *p_buffer, size_t i_size);
218     virtual void     setFilePointer  ( int64_t i_offset, seek_mode mode = seek_beginning );
219     virtual size_t   write           ( const void *p_buffer, size_t i_size);
220     virtual uint64   getFilePointer  ( void );
221     virtual void     close           ( void );
222 };
223
224 /*****************************************************************************
225  * Ebml Stream parser
226  *****************************************************************************/
227 class EbmlParser
228 {
229   public:
230     EbmlParser( EbmlStream *es, EbmlElement *el_start );
231     ~EbmlParser( void );
232
233     void Up( void );
234     void Down( void );
235     EbmlElement *Get( void );
236     void        Keep( void );
237
238     int GetLevel( void );
239
240   private:
241     EbmlStream  *m_es;
242     int         mi_level;
243     EbmlElement *m_el[10];
244
245     EbmlElement *m_got;
246
247     int         mi_user_level;
248     vlc_bool_t  mb_keep;
249 };
250
251
252 /*****************************************************************************
253  * Some functions to manipulate memory
254  *****************************************************************************/
255 #define GetFOURCC( p )  __GetFOURCC( (uint8_t*)p )
256 static vlc_fourcc_t __GetFOURCC( uint8_t *p )
257 {
258     return VLC_FOURCC( p[0], p[1], p[2], p[3] );
259 }
260
261 /*****************************************************************************
262  * definitions of structures and functions used by this plugins
263  *****************************************************************************/
264 typedef struct
265 {
266     vlc_bool_t  b_default;
267     vlc_bool_t  b_enabled;
268     int         i_number;
269
270     int         i_extra_data;
271     uint8_t     *p_extra_data;
272
273     char         *psz_codec;
274
275     uint64_t     i_default_duration;
276     float        f_timecodescale;
277
278     /* video */
279     es_format_t fmt;
280     float       f_fps;
281     es_out_id_t *p_es;
282
283     vlc_bool_t      b_inited;
284     /* data to be send first */
285     int             i_data_init;
286     uint8_t         *p_data_init;
287
288     /* hack : it's for seek */
289     vlc_bool_t      b_search_keyframe;
290
291     /* informative */
292     char         *psz_codec_name;
293     char         *psz_codec_settings;
294     char         *psz_codec_info_url;
295     char         *psz_codec_download_url;
296     
297     /* encryption/compression */
298     int           i_compression_type;
299
300 } mkv_track_t;
301
302 typedef struct
303 {
304     int     i_track;
305     int     i_block_number;
306
307     int64_t i_position;
308     int64_t i_time;
309
310     vlc_bool_t b_key;
311 } mkv_index_t;
312
313 class chapter_item_t
314 {
315 public:
316     chapter_item_t()
317     :i_start_time(0)
318     ,i_end_time(-1)
319     ,i_user_start_time(-1)
320     ,i_user_end_time(-1)
321     ,i_seekpoint_num(-1)
322     ,b_display_seekpoint(true)
323     ,psz_parent(NULL)
324     {}
325     
326     int64_t RefreshChapters( bool b_ordered, int64_t i_prev_user_time, input_title_t & title );
327     const chapter_item_t * FindTimecode( mtime_t i_timecode ) const;
328     
329     int64_t                     i_start_time, i_end_time;
330     int64_t                     i_user_start_time, i_user_end_time; /* the time in the stream when an edition is ordered */
331     std::vector<chapter_item_t> sub_chapters;
332     int                         i_seekpoint_num;
333     int64_t                     i_uid;
334     bool                        b_display_seekpoint;
335     std::string                 psz_name;
336     chapter_item_t              *psz_parent;
337     
338     bool operator<( const chapter_item_t & item ) const
339     {
340         return ( i_user_start_time < item.i_user_start_time || (i_user_start_time == item.i_user_start_time && i_user_end_time < item.i_user_end_time) );
341     }
342
343 protected:
344     bool Enter();
345     bool Leave();
346 };
347
348 class chapter_edition_t 
349 {
350 public:
351     chapter_edition_t()
352     :i_uid(-1)
353     ,b_ordered(false)
354     {}
355     
356     void RefreshChapters( input_title_t & title );
357     double Duration() const;
358     const chapter_item_t * FindTimecode( mtime_t i_timecode ) const;
359     
360     std::vector<chapter_item_t> chapters;
361     int64_t                     i_uid;
362     bool                        b_ordered;
363 };
364
365 class demux_sys_t
366 {
367 public:
368     demux_sys_t()
369         :in(NULL)
370         ,es(NULL)
371         ,ep(NULL)
372         ,i_timescale(0)
373         ,f_duration(0.0)
374         ,i_track(0)
375         ,track(NULL)
376         ,i_cues_position(0)
377         ,i_chapters_position(0)
378         ,i_tags_position(0)
379         ,segment(NULL)
380         ,cluster(NULL)
381         ,i_pts(0)
382         ,i_start_pts(0)
383         ,i_chapter_time(0)
384         ,b_cues(false)
385         ,i_index(0)
386         ,i_index_max(0)
387         ,index(NULL)
388         ,psz_muxing_application(NULL)
389         ,psz_writing_application(NULL)
390         ,psz_segment_filename(NULL)
391         ,psz_title(NULL)
392         ,psz_date_utc(NULL)
393         ,meta(NULL)
394         ,title(NULL)
395         ,i_current_edition(0)
396         ,psz_current_chapter(NULL)
397     {}
398
399     vlc_stream_io_callback  *in;
400     EbmlStream              *es;
401     EbmlParser              *ep;
402
403     /* time scale */
404     uint64_t                i_timescale;
405
406     /* duration of the segment */
407     float                   f_duration;
408
409     /* all tracks */
410     int                     i_track;
411     mkv_track_t             *track;
412
413     /* from seekhead */
414     int64_t                 i_cues_position;
415     int64_t                 i_chapters_position;
416     int64_t                 i_tags_position;
417
418     /* current data */
419     KaxSegment              *segment;
420     KaxCluster              *cluster;
421     KaxSegmentUID           segment_uid;
422
423     mtime_t                 i_pts;
424     mtime_t                 i_start_pts;
425     mtime_t                 i_chapter_time;
426
427     vlc_bool_t              b_cues;
428     int                     i_index;
429     int                     i_index_max;
430     mkv_index_t             *index;
431
432     /* info */
433     char                    *psz_muxing_application;
434     char                    *psz_writing_application;
435     char                    *psz_segment_filename;
436     char                    *psz_title;
437     char                    *psz_date_utc;
438
439     vlc_meta_t              *meta;
440
441     input_title_t           *title;
442
443     std::vector<KaxSegmentFamily> families;
444     std::vector<KaxSegment*>      family_members;
445     
446     std::vector<chapter_edition_t> editions;
447     int                            i_current_edition;
448     const chapter_item_t           *psz_current_chapter;
449 };
450
451 static int  Demux  ( demux_t * );
452 static int  Control( demux_t *, int, va_list );
453 static void Seek   ( demux_t *, mtime_t i_date, double f_percent, const chapter_item_t *psz_chapter );
454
455 #define MKVD_TIMECODESCALE 1000000
456
457 #define MKV_IS_ID( el, C ) ( EbmlId( (*el) ) == C::ClassInfos.GlobalId )
458
459 static void IndexAppendCluster  ( demux_t *p_demux, KaxCluster *cluster );
460 static char *UTF8ToStr          ( const UTFstring &u );
461 static void LoadCues            ( demux_t * );
462 static void InformationCreate  ( demux_t * );
463
464 static void ParseInfo( demux_t *, EbmlElement *info );
465 static void ParseTracks( demux_t *, EbmlElement *tracks );
466 static void ParseSeekHead( demux_t *, EbmlElement *seekhead );
467 static void ParseChapters( demux_t *, EbmlElement *chapters );
468
469 /*****************************************************************************
470  * Open: initializes matroska demux structures
471  *****************************************************************************/
472 static int Open( vlc_object_t * p_this )
473 {
474     demux_t     *p_demux = (demux_t*)p_this;
475     demux_sys_t *p_sys;
476     uint8_t     *p_peek;
477     std::string  s_path, s_filename;
478     int          i_upper_lvl;
479     size_t       i;
480
481     int          i_track;
482
483     EbmlElement *el = NULL, *el1 = NULL;
484
485     /* peek the begining */
486     if( stream_Peek( p_demux->s, &p_peek, 4 ) < 4 )
487     {
488         msg_Warn( p_demux, "cannot peek" );
489         return VLC_EGENERIC;
490     }
491
492     /* is a valid file */
493     if( p_peek[0] != 0x1a || p_peek[1] != 0x45 ||
494         p_peek[2] != 0xdf || p_peek[3] != 0xa3 )
495     {
496         msg_Warn( p_demux, "matroska module discarded "
497                            "(invalid header 0x%.2x%.2x%.2x%.2x)",
498                            p_peek[0], p_peek[1], p_peek[2], p_peek[3] );
499         return VLC_EGENERIC;
500     }
501
502     /* Set the demux function */
503     p_demux->pf_demux   = Demux;
504     p_demux->pf_control = Control;
505     p_demux->p_sys      = p_sys = new demux_sys_t;
506
507     p_sys->in = new vlc_stream_io_callback( p_demux->s );
508     p_sys->es = new EbmlStream( *p_sys->in );
509     p_sys->f_duration   = -1;
510     p_sys->i_timescale     = MKVD_TIMECODESCALE;
511     p_sys->i_track      = 0;
512     p_sys->track        = (mkv_track_t*)malloc( sizeof( mkv_track_t ) );
513     p_sys->i_pts   = 0;
514     p_sys->i_cues_position = -1;
515     p_sys->i_chapters_position = -1;
516     p_sys->i_tags_position = -1;
517
518     p_sys->b_cues       = VLC_FALSE;
519     p_sys->i_index      = 0;
520     p_sys->i_index_max  = 1024;
521     p_sys->index        = (mkv_index_t*)malloc( sizeof( mkv_index_t ) *
522                                                 p_sys->i_index_max );
523
524     p_sys->psz_muxing_application = NULL;
525     p_sys->psz_writing_application = NULL;
526     p_sys->psz_segment_filename = NULL;
527     p_sys->psz_title = NULL;
528     p_sys->psz_date_utc = NULL;;
529     p_sys->meta = NULL;
530     p_sys->title = NULL;
531
532     if( p_sys->es == NULL )
533     {
534         msg_Err( p_demux, "failed to create EbmlStream" );
535         delete p_sys->in;
536         delete p_sys;
537         return VLC_EGENERIC;
538     }
539     /* Find the EbmlHead element */
540     el = p_sys->es->FindNextID(EbmlHead::ClassInfos, 0xFFFFFFFFL);
541     if( el == NULL )
542     {
543         msg_Err( p_demux, "cannot find EbmlHead" );
544         goto error;
545     }
546     msg_Dbg( p_demux, "EbmlHead" );
547     /* skip it */
548     el->SkipData( *p_sys->es, el->Generic().Context );
549     delete el;
550
551     /* Find a segment */
552     el = p_sys->es->FindNextID( KaxSegment::ClassInfos, 0xFFFFFFFFL);
553     if( el == NULL )
554     {
555         msg_Err( p_demux, "cannot find KaxSegment" );
556         goto error;
557     }
558     MkvTree( p_demux, 0, "Segment" );
559     p_sys->segment = (KaxSegment*)el;
560     p_sys->cluster = NULL;
561
562     p_sys->ep = new EbmlParser( p_sys->es, el );
563
564     while( ( el1 = p_sys->ep->Get() ) != NULL )
565     {
566         if( MKV_IS_ID( el1, KaxInfo ) )
567         {
568             ParseInfo( p_demux, el1 );
569         }
570         else if( MKV_IS_ID( el1, KaxTracks ) )
571         {
572             ParseTracks( p_demux, el1 );
573         }
574         else if( MKV_IS_ID( el1, KaxSeekHead ) )
575         {
576             ParseSeekHead( p_demux, el1 );
577         }
578         else if( MKV_IS_ID( el1, KaxCues ) )
579         {
580             msg_Dbg( p_demux, "|   + Cues" );
581         }
582         else if( MKV_IS_ID( el1, KaxCluster ) )
583         {
584             msg_Dbg( p_demux, "|   + Cluster" );
585
586             p_sys->cluster = (KaxCluster*)el1;
587
588             p_sys->ep->Down();
589             /* stop parsing the stream */
590             break;
591         }
592         else if( MKV_IS_ID( el1, KaxAttachments ) )
593         {
594             msg_Dbg( p_demux, "|   + Attachments FIXME TODO (but probably never supported)" );
595         }
596         else if( MKV_IS_ID( el1, KaxChapters ) )
597         {
598             msg_Dbg( p_demux, "|   + Chapters" );
599             ParseChapters( p_demux, el1 );
600         }
601         else if( MKV_IS_ID( el1, KaxTag ) )
602         {
603             msg_Dbg( p_demux, "|   + Tags FIXME TODO" );
604         }
605         else
606         {
607             msg_Dbg( p_demux, "|   + Unknown (%s)", typeid(*el1).name() );
608         }
609     }
610
611     /* get the files from the same dir from the same family (based on p_demux->psz_path) */
612     /* _todo_ handle multi-segment files */
613     if (p_demux->psz_path[0] != '\0' && (!strcmp(p_demux->psz_access, "") || !strcmp(p_demux->psz_access, "")))
614     {
615         // assume it's a regular file
616         // get the directory path
617         s_path = p_demux->psz_path;
618         if (s_path.at(s_path.length() - 1) == DIRECTORY_SEPARATOR)
619         {
620             s_path = s_path.substr(0,s_path.length()-1);
621         }
622         else
623         {
624             if (s_path.find_last_of(DIRECTORY_SEPARATOR) > 0) 
625             {
626                 s_path = s_path.substr(0,s_path.find_last_of(DIRECTORY_SEPARATOR));
627             }
628         }
629
630         struct dirent *p_file_item;
631         DIR *p_src_dir = opendir(s_path.c_str());
632
633         if (p_src_dir != NULL)
634         {
635             while ((p_file_item = (dirent *) readdir(p_src_dir)))
636             {
637                 if (strlen(p_file_item->d_name) > 4)
638                 {
639                     s_filename = s_path + DIRECTORY_SEPARATOR + p_file_item->d_name;
640
641                     if (!s_filename.compare(p_demux->psz_path))
642                         continue;
643
644 #if defined(__GNUC__) && (__GNUC__ < 3)
645                     if (!s_filename.compare("mkv", s_filename.length() - 3, 3) || 
646                         !s_filename.compare("mka", s_filename.length() - 3, 3))
647 #else
648                     if (!s_filename.compare(s_filename.length() - 3, 3, "mkv") || 
649                         !s_filename.compare(s_filename.length() - 3, 3, "mka"))
650 #endif
651                     {
652                         // test wether this file belongs to the our family
653                         bool b_keep_file_opened = false;
654                         StdIOCallback *p_file_io = new StdIOCallback(s_filename.c_str(), MODE_READ);
655                         EbmlStream *p_stream = new EbmlStream(*p_file_io);
656                         EbmlElement *p_l0, *p_l1, *p_l2;
657
658                         // verify the EBML Header
659                         p_l0 = p_stream->FindNextID(EbmlHead::ClassInfos, 0xFFFFFFFFL);
660                         if (p_l0 == NULL)
661                         {
662                             delete p_stream;
663                             delete p_file_io;
664                             continue;
665                         }
666
667                         p_l0->SkipData(*p_stream, EbmlHead_Context);
668                         delete p_l0;
669
670                         // find all segments in this file
671                         p_l0 = p_stream->FindNextID(KaxSegment::ClassInfos, 0xFFFFFFFFL);
672                         if (p_l0 == NULL)
673                         {
674                             delete p_stream;
675                             delete p_file_io;
676                             continue;
677                         }
678
679                         i_upper_lvl = 0;
680
681                         while (p_l0 != 0)
682                         {
683                             if (EbmlId(*p_l0) == KaxSegment::ClassInfos.GlobalId)
684                             {
685                                 EbmlParser  *ep;
686                                 KaxSegmentUID *p_uid = NULL;
687
688                                 ep = new EbmlParser(p_stream, p_l0);
689                                 bool b_this_segment_matches = false;
690                                 while ((p_l1 = ep->Get()))
691                                 {
692                                     if (MKV_IS_ID(p_l1, KaxInfo))
693                                     {
694                                         // find the families of this segment
695                                         KaxInfo *p_info = static_cast<KaxInfo*>(p_l1);
696
697                                         p_info->Read(*p_stream, KaxInfo::ClassInfos.Context, i_upper_lvl, p_l2, true);
698                                         for( i = 0; i < p_info->ListSize() && !b_this_segment_matches; i++ )
699                                         {
700                                             EbmlElement *l = (*p_info)[i];
701
702                                             if( MKV_IS_ID( l, KaxSegmentUID ) )
703                                             {
704                                                 p_uid = static_cast<KaxSegmentUID*>(l);
705                                                 if (p_sys->segment_uid == *p_uid)
706                                                     break;
707                                             }
708                                             else if( MKV_IS_ID( l, KaxSegmentFamily ) )
709                                             {
710                                                 KaxSegmentFamily *p_fam = static_cast<KaxSegmentFamily*>(l);
711                                                 std::vector<KaxSegmentFamily>::iterator iter;
712                                                 for( iter = p_sys->families.begin();
713                                                      iter != p_sys->families.end();
714                                                      iter++ )
715                                                 {
716                                                     if( *iter == *p_fam )
717                                                     {
718                                                         b_this_segment_matches = true;
719                                                         break;
720                                                     }
721                                                 }
722                                             }
723                                         }
724                                         break;
725                                     }
726                                 }
727
728                                 if (b_this_segment_matches)
729                                 {
730                                     b_keep_file_opened = true;
731                                 }
732                             }
733
734                             p_l0->SkipData(*p_stream, EbmlHead_Context);
735                             delete p_l0;
736                             p_l0 = p_stream->FindNextID(KaxSegment::ClassInfos, 0xFFFFFFFFL);
737                         }
738
739                         if (!b_keep_file_opened)
740                         {
741                             delete p_stream;
742                             delete p_file_io;
743                         }
744                     }
745                 }
746             }
747             closedir( p_src_dir );
748         }
749     }
750
751
752     if( p_sys->cluster == NULL )
753     {
754         msg_Err( p_demux, "cannot find any cluster, damaged file ?" );
755         goto error;
756     }
757
758     /* *** Load the cue if found *** */
759     if( p_sys->i_cues_position >= 0 )
760     {
761         vlc_bool_t b_seekable;
762
763         stream_Control( p_demux->s, STREAM_CAN_FASTSEEK, &b_seekable );
764         if( b_seekable )
765         {
766             LoadCues( p_demux );
767         }
768     }
769
770     if( !p_sys->b_cues || p_sys->i_index <= 0 )
771     {
772         msg_Warn( p_demux, "no cues/empty cues found->seek won't be precise" );
773
774         IndexAppendCluster( p_demux, p_sys->cluster );
775
776         p_sys->b_cues = VLC_FALSE;
777     }
778
779     /* add all es */
780     msg_Dbg( p_demux, "found %d es", p_sys->i_track );
781     for( i_track = 0; i_track < p_sys->i_track; i_track++ )
782     {
783 #define tk  p_sys->track[i_track]
784         if( tk.fmt.i_cat == UNKNOWN_ES )
785         {
786             msg_Warn( p_demux, "invalid track[%d, n=%d]", i_track, tk.i_number );
787             tk.p_es = NULL;
788             continue;
789         }
790
791         if( !strcmp( tk.psz_codec, "V_MS/VFW/FOURCC" ) )
792         {
793             if( tk.i_extra_data < (int)sizeof( BITMAPINFOHEADER ) )
794             {
795                 msg_Err( p_demux, "missing/invalid BITMAPINFOHEADER" );
796                 tk.fmt.i_codec = VLC_FOURCC( 'u', 'n', 'd', 'f' );
797             }
798             else
799             {
800                 BITMAPINFOHEADER *p_bih = (BITMAPINFOHEADER*)tk.p_extra_data;
801
802                 tk.fmt.video.i_width = GetDWLE( &p_bih->biWidth );
803                 tk.fmt.video.i_height= GetDWLE( &p_bih->biHeight );
804                 tk.fmt.i_codec       = GetFOURCC( &p_bih->biCompression );
805
806                 tk.fmt.i_extra       = GetDWLE( &p_bih->biSize ) - sizeof( BITMAPINFOHEADER );
807                 if( tk.fmt.i_extra > 0 )
808                 {
809                     tk.fmt.p_extra = malloc( tk.fmt.i_extra );
810                     memcpy( tk.fmt.p_extra, &p_bih[1], tk.fmt.i_extra );
811                 }
812             }
813         }
814         else if( !strcmp( tk.psz_codec, "V_MPEG1" ) ||
815                  !strcmp( tk.psz_codec, "V_MPEG2" ) )
816         {
817             tk.fmt.i_codec = VLC_FOURCC( 'm', 'p', 'g', 'v' );
818         }
819         else if( !strncmp( tk.psz_codec, "V_MPEG4", 7 ) )
820         {
821             if( !strcmp( tk.psz_codec, "V_MPEG4/MS/V3" ) )
822             {
823                 tk.fmt.i_codec = VLC_FOURCC( 'D', 'I', 'V', '3' );
824             }
825             else if( !strcmp( tk.psz_codec, "V_MPEG4/ISO/AVC" ) )
826             {
827                 tk.fmt.i_codec = VLC_FOURCC( 'a', 'v', 'c', '1' );
828                 tk.fmt.b_packetized = VLC_FALSE;
829                 tk.fmt.i_extra = tk.i_extra_data;
830                 tk.fmt.p_extra = malloc( tk.i_extra_data );
831                 memcpy( tk.fmt.p_extra,tk.p_extra_data, tk.i_extra_data );
832             }
833             else
834             {
835                 tk.fmt.i_codec = VLC_FOURCC( 'm', 'p', '4', 'v' );
836             }
837         }
838         else if( !strcmp( tk.psz_codec, "V_QUICKTIME" ) )
839         {
840             MP4_Box_t *p_box = (MP4_Box_t*)malloc( sizeof( MP4_Box_t ) );
841             stream_t *p_mp4_stream = stream_MemoryNew( VLC_OBJECT(p_demux),
842                                                        tk.p_extra_data,
843                                                        tk.i_extra_data );
844             MP4_ReadBoxCommon( p_mp4_stream, p_box );
845             MP4_ReadBox_sample_vide( p_mp4_stream, p_box );
846             tk.fmt.i_codec = p_box->i_type;
847             tk.fmt.video.i_width = p_box->data.p_sample_vide->i_width;
848             tk.fmt.video.i_height = p_box->data.p_sample_vide->i_height;
849             tk.fmt.i_extra = p_box->data.p_sample_vide->i_qt_image_description;
850             tk.fmt.p_extra = malloc( tk.fmt.i_extra );
851             memcpy( tk.fmt.p_extra, p_box->data.p_sample_vide->p_qt_image_description, tk.fmt.i_extra );
852             MP4_FreeBox_sample_vide( p_box );
853             stream_MemoryDelete( p_mp4_stream, VLC_TRUE );
854         }
855         else if( !strcmp( tk.psz_codec, "A_MS/ACM" ) )
856         {
857             if( tk.i_extra_data < (int)sizeof( WAVEFORMATEX ) )
858             {
859                 msg_Err( p_demux, "missing/invalid WAVEFORMATEX" );
860                 tk.fmt.i_codec = VLC_FOURCC( 'u', 'n', 'd', 'f' );
861             }
862             else
863             {
864                 WAVEFORMATEX *p_wf = (WAVEFORMATEX*)tk.p_extra_data;
865
866                 wf_tag_to_fourcc( GetWLE( &p_wf->wFormatTag ), &tk.fmt.i_codec, NULL );
867
868                 tk.fmt.audio.i_channels   = GetWLE( &p_wf->nChannels );
869                 tk.fmt.audio.i_rate = GetDWLE( &p_wf->nSamplesPerSec );
870                 tk.fmt.i_bitrate    = GetDWLE( &p_wf->nAvgBytesPerSec ) * 8;
871                 tk.fmt.audio.i_blockalign = GetWLE( &p_wf->nBlockAlign );;
872                 tk.fmt.audio.i_bitspersample = GetWLE( &p_wf->wBitsPerSample );
873
874                 tk.fmt.i_extra            = GetWLE( &p_wf->cbSize );
875                 if( tk.fmt.i_extra > 0 )
876                 {
877                     tk.fmt.p_extra = malloc( tk.fmt.i_extra );
878                     memcpy( tk.fmt.p_extra, &p_wf[1], tk.fmt.i_extra );
879                 }
880             }
881         }
882         else if( !strcmp( tk.psz_codec, "A_MPEG/L3" ) ||
883                  !strcmp( tk.psz_codec, "A_MPEG/L2" ) ||
884                  !strcmp( tk.psz_codec, "A_MPEG/L1" ) )
885         {
886             tk.fmt.i_codec = VLC_FOURCC( 'm', 'p', 'g', 'a' );
887         }
888         else if( !strcmp( tk.psz_codec, "A_AC3" ) )
889         {
890             tk.fmt.i_codec = VLC_FOURCC( 'a', '5', '2', ' ' );
891         }
892         else if( !strcmp( tk.psz_codec, "A_DTS" ) )
893         {
894             tk.fmt.i_codec = VLC_FOURCC( 'd', 't', 's', ' ' );
895         }
896         else if( !strcmp( tk.psz_codec, "A_FLAC" ) )
897         {
898             tk.fmt.i_codec = VLC_FOURCC( 'f', 'l', 'a', 'c' );
899             tk.fmt.i_extra = tk.i_extra_data;
900             tk.fmt.p_extra = malloc( tk.i_extra_data );
901             memcpy( tk.fmt.p_extra,tk.p_extra_data, tk.i_extra_data );
902         }
903         else if( !strcmp( tk.psz_codec, "A_VORBIS" ) )
904         {
905             int i, i_offset = 1, i_size[3], i_extra;
906             uint8_t *p_extra;
907
908             tk.fmt.i_codec = VLC_FOURCC( 'v', 'o', 'r', 'b' );
909
910             /* Split the 3 headers */
911             if( tk.p_extra_data[0] != 0x02 )
912                 msg_Err( p_demux, "invalid vorbis header" );
913
914             for( i = 0; i < 2; i++ )
915             {
916                 i_size[i] = 0;
917                 while( i_offset < tk.i_extra_data )
918                 {
919                     i_size[i] += tk.p_extra_data[i_offset];
920                     if( tk.p_extra_data[i_offset++] != 0xff ) break;
921                 }
922             }
923
924             i_size[0] = __MIN(i_size[0], tk.i_extra_data - i_offset);
925             i_size[1] = __MIN(i_size[1], tk.i_extra_data -i_offset -i_size[0]);
926             i_size[2] = tk.i_extra_data - i_offset - i_size[0] - i_size[1];
927
928             tk.fmt.i_extra = 3 * 2 + i_size[0] + i_size[1] + i_size[2];
929             tk.fmt.p_extra = malloc( tk.fmt.i_extra );
930             p_extra = (uint8_t *)tk.fmt.p_extra; i_extra = 0;
931             for( i = 0; i < 3; i++ )
932             {
933                 *(p_extra++) = i_size[i] >> 8;
934                 *(p_extra++) = i_size[i] & 0xFF;
935                 memcpy( p_extra, tk.p_extra_data + i_offset + i_extra,
936                         i_size[i] );
937                 p_extra += i_size[i];
938                 i_extra += i_size[i];
939             }
940         }
941         else if( !strncmp( tk.psz_codec, "A_AAC/MPEG2/", strlen( "A_AAC/MPEG2/" ) ) ||
942                  !strncmp( tk.psz_codec, "A_AAC/MPEG4/", strlen( "A_AAC/MPEG4/" ) ) )
943         {
944             int i_profile, i_srate;
945             static unsigned int i_sample_rates[] =
946             {
947                     96000, 88200, 64000, 48000, 44100, 32000, 24000, 22050,
948                         16000, 12000, 11025, 8000,  7350,  0,     0,     0
949             };
950
951             tk.fmt.i_codec = VLC_FOURCC( 'm', 'p', '4', 'a' );
952             /* create data for faad (MP4DecSpecificDescrTag)*/
953
954             if( !strcmp( &tk.psz_codec[12], "MAIN" ) )
955             {
956                 i_profile = 0;
957             }
958             else if( !strcmp( &tk.psz_codec[12], "LC" ) )
959             {
960                 i_profile = 1;
961             }
962             else if( !strcmp( &tk.psz_codec[12], "SSR" ) )
963             {
964                 i_profile = 2;
965             }
966             else
967             {
968                 i_profile = 3;
969             }
970
971             for( i_srate = 0; i_srate < 13; i_srate++ )
972             {
973                 if( i_sample_rates[i_srate] == tk.fmt.audio.i_rate )
974                 {
975                     break;
976                 }
977             }
978             msg_Dbg( p_demux, "profile=%d srate=%d", i_profile, i_srate );
979
980             tk.fmt.i_extra = 2;
981             tk.fmt.p_extra = malloc( tk.fmt.i_extra );
982             ((uint8_t*)tk.fmt.p_extra)[0] = ((i_profile + 1) << 3) | ((i_srate&0xe) >> 1);
983             ((uint8_t*)tk.fmt.p_extra)[1] = ((i_srate & 0x1) << 7) | (tk.fmt.audio.i_channels << 3);
984         }
985         else if( !strcmp( tk.psz_codec, "A_PCM/INT/BIG" ) ||
986                  !strcmp( tk.psz_codec, "A_PCM/INT/LIT" ) ||
987                  !strcmp( tk.psz_codec, "A_PCM/FLOAT/IEEE" ) )
988         {
989             if( !strcmp( tk.psz_codec, "A_PCM/INT/BIG" ) )
990             {
991                 tk.fmt.i_codec = VLC_FOURCC( 't', 'w', 'o', 's' );
992             }
993             else
994             {
995                 tk.fmt.i_codec = VLC_FOURCC( 'a', 'r', 'a', 'w' );
996             }
997             tk.fmt.audio.i_blockalign = ( tk.fmt.audio.i_bitspersample + 7 ) / 8 * tk.fmt.audio.i_channels;
998         }
999         else if( !strcmp( tk.psz_codec, "A_TTA1" ) )
1000         {
1001             /* FIXME: support this codec */
1002             msg_Err( p_demux, "TTA not supported yet[%d, n=%d]", i_track, tk.i_number );
1003             tk.fmt.i_codec = VLC_FOURCC( 'u', 'n', 'd', 'f' );
1004         }
1005         else if( !strcmp( tk.psz_codec, "A_WAVPACK4" ) )
1006         {
1007             /* FIXME: support this codec */
1008             msg_Err( p_demux, "Wavpack not supported yet[%d, n=%d]", i_track, tk.i_number );
1009             tk.fmt.i_codec = VLC_FOURCC( 'u', 'n', 'd', 'f' );
1010         }
1011         else if( !strcmp( tk.psz_codec, "S_TEXT/UTF8" ) )
1012         {
1013             tk.fmt.i_codec = VLC_FOURCC( 's', 'u', 'b', 't' );
1014             tk.fmt.subs.psz_encoding = strdup( "UTF-8" );
1015         }
1016         else if( !strcmp( tk.psz_codec, "S_TEXT/SSA" ) ||
1017                  !strcmp( tk.psz_codec, "S_TEXT/ASS" ) ||
1018                  !strcmp( tk.psz_codec, "S_SSA" ) ||
1019                  !strcmp( tk.psz_codec, "S_ASS" ))
1020         {
1021             tk.fmt.i_codec = VLC_FOURCC( 's', 's', 'a', ' ' );
1022             tk.fmt.subs.psz_encoding = strdup( "UTF-8" );
1023         }
1024         else if( !strcmp( tk.psz_codec, "S_VOBSUB" ) )
1025         {
1026             tk.fmt.i_codec = VLC_FOURCC( 's','p','u',' ' );
1027             if( tk.i_extra_data )
1028             {
1029                 char *p_start;
1030                 char *p_buf = (char *)malloc( tk.i_extra_data + 1);
1031                 memcpy( p_buf, tk.p_extra_data , tk.i_extra_data );
1032                 p_buf[tk.i_extra_data] = '\0';
1033                 
1034                 p_start = strstr( p_buf, "size:" );
1035                 if( sscanf( p_start, "size: %dx%d",
1036                         &tk.fmt.subs.spu.i_original_frame_width, &tk.fmt.subs.spu.i_original_frame_height ) == 2 )
1037                 {
1038                     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 );
1039                 }
1040                 else
1041                 {
1042                     msg_Warn( p_demux, "reading original frame size for vobsub failed" );
1043                 }
1044                 free( p_buf );
1045             }
1046         }
1047         else if( !strcmp( tk.psz_codec, "B_VOBBTN" ) )
1048         {
1049             /* FIXME: support this codec */
1050             msg_Err( p_demux, "Vob Buttons not supported yet[%d, n=%d]", i_track, tk.i_number );
1051             tk.fmt.i_codec = VLC_FOURCC( 'u', 'n', 'd', 'f' );
1052         }
1053         else
1054         {
1055             msg_Err( p_demux, "unknow codec id=`%s'", tk.psz_codec );
1056             tk.fmt.i_codec = VLC_FOURCC( 'u', 'n', 'd', 'f' );
1057         }
1058         if( tk.b_default )
1059         {
1060             tk.fmt.i_priority = 1000;
1061         }
1062
1063         tk.p_es = es_out_Add( p_demux->out, &tk.fmt );
1064 #undef tk
1065     }
1066
1067     /* add information */
1068     InformationCreate( p_demux );
1069
1070     return VLC_SUCCESS;
1071
1072 error:
1073     delete p_sys->es;
1074     delete p_sys->in;
1075     delete p_sys;
1076     return VLC_EGENERIC;
1077 }
1078
1079 /*****************************************************************************
1080  * Close: frees unused data
1081  *****************************************************************************/
1082 static void Close( vlc_object_t *p_this )
1083 {
1084     demux_t     *p_demux = (demux_t*)p_this;
1085     demux_sys_t *p_sys   = p_demux->p_sys;
1086     int         i_track;
1087
1088     for( i_track = 0; i_track < p_sys->i_track; i_track++ )
1089     {
1090 #define tk  p_sys->track[i_track]
1091         if( tk.fmt.psz_description )
1092         {
1093             free( tk.fmt.psz_description );
1094         }
1095         if( tk.psz_codec )
1096         {
1097             free( tk.psz_codec );
1098         }
1099         if( tk.fmt.psz_language )
1100         {
1101             free( tk.fmt.psz_language );
1102         }
1103 #undef tk
1104     }
1105     free( p_sys->track );
1106
1107     if( p_sys->psz_writing_application  )
1108     {
1109         free( p_sys->psz_writing_application );
1110     }
1111     if( p_sys->psz_muxing_application  )
1112     {
1113         free( p_sys->psz_muxing_application );
1114     }
1115
1116     delete p_sys->segment;
1117
1118     delete p_sys->ep;
1119     delete p_sys->es;
1120     delete p_sys->in;
1121     delete p_sys;
1122 }
1123
1124 /*****************************************************************************
1125  * Control:
1126  *****************************************************************************/
1127 static int Control( demux_t *p_demux, int i_query, va_list args )
1128 {
1129     demux_sys_t *p_sys = p_demux->p_sys;
1130     int64_t     *pi64;
1131     double      *pf, f;
1132     int         i_skp;
1133     mtime_t     *i_sk_time;
1134
1135     vlc_meta_t **pp_meta;
1136
1137     switch( i_query )
1138     {
1139         case DEMUX_GET_META:
1140             pp_meta = (vlc_meta_t**)va_arg( args, vlc_meta_t** );
1141             *pp_meta = vlc_meta_Duplicate( p_sys->meta );
1142             return VLC_SUCCESS;
1143
1144         case DEMUX_GET_LENGTH:
1145             pi64 = (int64_t*)va_arg( args, int64_t * );
1146             if( p_sys->f_duration > 0.0 )
1147             {
1148                 *pi64 = (int64_t)(p_sys->f_duration * 1000);
1149                 return VLC_SUCCESS;
1150             }
1151             return VLC_EGENERIC;
1152
1153         case DEMUX_GET_POSITION:
1154             pf = (double*)va_arg( args, double * );
1155 /*            if (p_sys->i_pts < p_sys->i_start_pts)
1156                 *pf = (double)p_sys->i_start_pts / (1000.0 * p_sys->f_duration);
1157             else*/
1158                 *pf = (double)p_sys->i_pts / (1000.0 * p_sys->f_duration);
1159             return VLC_SUCCESS;
1160
1161         case DEMUX_SET_POSITION:
1162             f = (double)va_arg( args, double );
1163             Seek( p_demux, -1, f, NULL );
1164             return VLC_SUCCESS;
1165
1166         case DEMUX_GET_TIME:
1167             pi64 = (int64_t*)va_arg( args, int64_t * );
1168 /*            if (p_sys->i_pts < p_sys->i_start_pts)
1169                 *pi64 = p_sys->i_start_pts;
1170             else*/
1171                 *pi64 = p_sys->i_pts;
1172             return VLC_SUCCESS;
1173
1174         case DEMUX_GET_TITLE_INFO:
1175             if( p_sys->title && p_sys->title->i_seekpoint > 0 )
1176             {
1177                 input_title_t ***ppp_title = (input_title_t***)va_arg( args, input_title_t*** );
1178                 int *pi_int    = (int*)va_arg( args, int* );
1179
1180                 *pi_int = 1;
1181                 *ppp_title = (input_title_t**)malloc( sizeof( input_title_t**) );
1182
1183                 (*ppp_title)[0] = vlc_input_title_Duplicate( p_sys->title );
1184
1185                 return VLC_SUCCESS;
1186             }
1187             return VLC_EGENERIC;
1188
1189         case DEMUX_SET_TITLE:
1190             /* TODO handle editions as titles & DVD titles as well */
1191             if( p_sys->title && p_sys->title->i_seekpoint > 0 )
1192             {
1193                 return VLC_SUCCESS;
1194             }
1195             return VLC_EGENERIC;
1196
1197         case DEMUX_SET_SEEKPOINT:
1198             /* FIXME do a better implementation */
1199             i_skp = (int)va_arg( args, int );
1200
1201             if( p_sys->title && i_skp < p_sys->title->i_seekpoint)
1202             {
1203                 Seek( p_demux, (int64_t)p_sys->title->seekpoint[i_skp]->i_time_offset, -1, NULL);
1204                 p_demux->info.i_seekpoint |= INPUT_UPDATE_SEEKPOINT;
1205                 p_demux->info.i_seekpoint = i_skp;
1206                 return VLC_SUCCESS;
1207             }
1208             return VLC_EGENERIC;
1209
1210         case DEMUX_GET_SEEKPOINT_TIME:
1211             i_skp = (int)va_arg( args, int );
1212             i_sk_time = (mtime_t *)va_arg( args, mtime_t * );
1213             if( p_sys->title && i_skp < p_sys->title->i_seekpoint)
1214             {
1215                 *i_sk_time = p_sys->title->seekpoint[i_skp]->i_time_offset;
1216                 return VLC_SUCCESS;
1217             }
1218             return VLC_EGENERIC;
1219
1220         case DEMUX_SET_TIME:
1221         case DEMUX_GET_FPS:
1222         default:
1223             return VLC_EGENERIC;
1224     }
1225 }
1226
1227 static int BlockGet( demux_t *p_demux, KaxBlock **pp_block, int64_t *pi_ref1, int64_t *pi_ref2, int64_t *pi_duration )
1228 {
1229     demux_sys_t *p_sys = p_demux->p_sys;
1230
1231     *pp_block = NULL;
1232     *pi_ref1  = -1;
1233     *pi_ref2  = -1;
1234
1235     for( ;; )
1236     {
1237         EbmlElement *el;
1238         int         i_level;
1239
1240         if( p_demux->b_die )
1241         {
1242             return VLC_EGENERIC;
1243         }
1244
1245         el = p_sys->ep->Get();
1246         i_level = p_sys->ep->GetLevel();
1247
1248         if( el == NULL && *pp_block != NULL )
1249         {
1250             /* update the index */
1251 #define idx p_sys->index[p_sys->i_index - 1]
1252             if( p_sys->i_index > 0 && idx.i_time == -1 )
1253             {
1254                 idx.i_time        = (*pp_block)->GlobalTimecode() / (mtime_t)1000;
1255                 idx.b_key         = *pi_ref1 == -1 ? VLC_TRUE : VLC_FALSE;
1256             }
1257 #undef idx
1258             return VLC_SUCCESS;
1259         }
1260
1261         if( el == NULL )
1262         {
1263             if( p_sys->ep->GetLevel() > 1 )
1264             {
1265                 p_sys->ep->Up();
1266                 continue;
1267             }
1268             msg_Warn( p_demux, "EOF" );
1269             return VLC_EGENERIC;
1270         }
1271
1272         /* do parsing */
1273         if( i_level == 1 )
1274         {
1275             if( MKV_IS_ID( el, KaxCluster ) )
1276             {
1277                 p_sys->cluster = (KaxCluster*)el;
1278
1279                 /* add it to the index */
1280                 if( p_sys->i_index == 0 ||
1281                     ( p_sys->i_index > 0 && p_sys->index[p_sys->i_index - 1].i_position < (int64_t)p_sys->cluster->GetElementPosition() ) )
1282                 {
1283                     IndexAppendCluster( p_demux, p_sys->cluster );
1284                 }
1285
1286                 p_sys->ep->Down();
1287             }
1288             else if( MKV_IS_ID( el, KaxCues ) )
1289             {
1290                 msg_Warn( p_demux, "find KaxCues FIXME" );
1291                 return VLC_EGENERIC;
1292             }
1293             else
1294             {
1295                 msg_Dbg( p_demux, "unknown (%s)", typeid( el ).name() );
1296             }
1297         }
1298         else if( i_level == 2 )
1299         {
1300             if( MKV_IS_ID( el, KaxClusterTimecode ) )
1301             {
1302                 KaxClusterTimecode &ctc = *(KaxClusterTimecode*)el;
1303
1304                 ctc.ReadData( p_sys->es->I_O(), SCOPE_ALL_DATA );
1305                 p_sys->cluster->InitTimecode( uint64( ctc ), p_sys->i_timescale );
1306             }
1307             else if( MKV_IS_ID( el, KaxBlockGroup ) )
1308             {
1309                 p_sys->ep->Down();
1310             }
1311         }
1312         else if( i_level == 3 )
1313         {
1314             if( MKV_IS_ID( el, KaxBlock ) )
1315             {
1316                 *pp_block = (KaxBlock*)el;
1317
1318                 (*pp_block)->ReadData( p_sys->es->I_O() );
1319                 (*pp_block)->SetParent( *p_sys->cluster );
1320
1321                 p_sys->ep->Keep();
1322             }
1323             else if( MKV_IS_ID( el, KaxBlockDuration ) )
1324             {
1325                 KaxBlockDuration &dur = *(KaxBlockDuration*)el;
1326
1327                 dur.ReadData( p_sys->es->I_O() );
1328                 *pi_duration = uint64( dur );
1329             }
1330             else if( MKV_IS_ID( el, KaxReferenceBlock ) )
1331             {
1332                 KaxReferenceBlock &ref = *(KaxReferenceBlock*)el;
1333
1334                 ref.ReadData( p_sys->es->I_O() );
1335                 if( *pi_ref1 == -1 )
1336                 {
1337                     *pi_ref1 = int64( ref );
1338                 }
1339                 else
1340                 {
1341                     *pi_ref2 = int64( ref );
1342                 }
1343             }
1344         }
1345         else
1346         {
1347             msg_Err( p_demux, "invalid level = %d", i_level );
1348             return VLC_EGENERIC;
1349         }
1350     }
1351 }
1352
1353 static block_t *MemToBlock( demux_t *p_demux, uint8_t *p_mem, int i_mem)
1354 {
1355     block_t *p_block;
1356     if( !(p_block = block_New( p_demux, i_mem ) ) ) return NULL;
1357     memcpy( p_block->p_buffer, p_mem, i_mem );
1358     //p_block->i_rate = p_input->stream.control.i_rate;
1359     return p_block;
1360 }
1361
1362 static void BlockDecode( demux_t *p_demux, KaxBlock *block, mtime_t i_pts,
1363                          mtime_t i_duration )
1364 {
1365     demux_sys_t *p_sys = p_demux->p_sys;
1366
1367     int             i_track;
1368     unsigned int    i;
1369     vlc_bool_t      b;
1370
1371 #define tk  p_sys->track[i_track]
1372     for( i_track = 0; i_track < p_sys->i_track; i_track++ )
1373     {
1374         if( tk.i_number == block->TrackNum() )
1375         {
1376             break;
1377         }
1378     }
1379
1380     if( i_track >= p_sys->i_track )
1381     {
1382         msg_Err( p_demux, "invalid track number=%d", block->TrackNum() );
1383         return;
1384     }
1385     if( tk.p_es == NULL )
1386     {
1387         msg_Err( p_demux, "unknown track number=%d", block->TrackNum() );
1388         return;
1389     }
1390     if( i_pts < p_sys->i_start_pts && tk.fmt.i_cat == AUDIO_ES )
1391     {
1392         return; /* discard audio packets that shouldn't be rendered */
1393     }
1394
1395     es_out_Control( p_demux->out, ES_OUT_GET_ES_STATE, tk.p_es, &b );
1396     if( !b )
1397     {
1398         tk.b_inited = VLC_FALSE;
1399         return;
1400     }
1401
1402     /* First send init data */
1403     if( !tk.b_inited && tk.i_data_init > 0 )
1404     {
1405         block_t *p_init;
1406
1407         msg_Dbg( p_demux, "sending header (%d bytes)", tk.i_data_init );
1408         p_init = MemToBlock( p_demux, tk.p_data_init, tk.i_data_init );
1409         if( p_init ) es_out_Send( p_demux->out, tk.p_es, p_init );
1410     }
1411     tk.b_inited = VLC_TRUE;
1412
1413
1414     for( i = 0; i < block->NumberFrames(); i++ )
1415     {
1416         block_t *p_block;
1417         DataBuffer &data = block->GetBuffer(i);
1418
1419         p_block = MemToBlock( p_demux, data.Buffer(), data.Size() );
1420
1421         if( p_block == NULL )
1422         {
1423             break;
1424         }
1425
1426 #if defined(HAVE_ZLIB_H)
1427         if( tk.i_compression_type )
1428         {
1429             p_block = block_zlib_decompress( VLC_OBJECT(p_demux), p_block );
1430         }
1431 #endif
1432
1433         // TODO implement correct timestamping when B frames are used
1434         if( tk.fmt.i_cat != VIDEO_ES )
1435         {
1436             p_block->i_dts = p_block->i_pts = i_pts;
1437         }
1438         else
1439         {
1440             p_block->i_dts = i_pts;
1441             p_block->i_pts = 0;
1442         }
1443
1444         if( tk.fmt.i_cat == SPU_ES && strcmp( tk.psz_codec, "S_VOBSUB" ) )
1445         {
1446             p_block->i_length = i_duration * 1000;
1447         }
1448         es_out_Send( p_demux->out, tk.p_es, p_block );
1449
1450         /* use time stamp only for first block */
1451         i_pts = 0;
1452     }
1453
1454 #undef tk
1455 }
1456
1457 static void UpdateCurrentToChapter( demux_t & demux )
1458 {
1459     demux_sys_t & sys = *demux.p_sys;
1460     const chapter_item_t *psz_curr_chapter;
1461
1462     /* update current chapter/seekpoint */
1463     if ( sys.editions.size())
1464     {
1465         /* 1st, we need to know in which chapter we are */
1466         psz_curr_chapter = sys.editions[sys.i_current_edition].FindTimecode( sys.i_pts );
1467
1468         /* we have moved to a new chapter */
1469         if (sys.psz_current_chapter != NULL && psz_curr_chapter != NULL && sys.psz_current_chapter != psz_curr_chapter)
1470         {
1471             if (sys.psz_current_chapter->i_seekpoint_num != psz_curr_chapter->i_seekpoint_num && psz_curr_chapter->i_seekpoint_num > 0)
1472             {
1473                 demux.info.i_update |= INPUT_UPDATE_SEEKPOINT;
1474                 demux.info.i_seekpoint = psz_curr_chapter->i_seekpoint_num - 1;
1475             }
1476
1477             if (sys.editions[sys.i_current_edition].b_ordered )
1478             {
1479                 /* TODO check if we need to silently seek to a new location in the stream (switch to another chapter) */
1480                 if (sys.psz_current_chapter->i_end_time != psz_curr_chapter->i_start_time)
1481                     Seek(&demux, sys.i_pts, -1, psz_curr_chapter);
1482                 /* count the last duration time found for each track in a table (-1 not found, -2 silent) */
1483                 /* only seek after each duration >= end timecode of the current chapter */
1484             }
1485
1486 //            sys.i_user_time = psz_curr_chapter->i_user_start_time - psz_curr_chapter->i_start_time;
1487 //            sys.i_start_pts = psz_curr_chapter->i_user_start_time;
1488         }
1489         sys.psz_current_chapter = psz_curr_chapter;
1490     }
1491 }
1492
1493 static void Seek( demux_t *p_demux, mtime_t i_date, double f_percent, const chapter_item_t *psz_chapter)
1494 {
1495     demux_sys_t *p_sys = p_demux->p_sys;
1496     mtime_t i_time_offset = 0;
1497
1498     KaxBlock    *block;
1499     int64_t     i_block_duration;
1500     int64_t     i_block_ref1;
1501     int64_t     i_block_ref2;
1502
1503     int         i_index = 0;
1504     int         i_track_skipping;
1505     int         i_track;
1506
1507     msg_Dbg( p_demux, "seek request to "I64Fd" (%f%%)", i_date, f_percent );
1508     if( i_date < 0 && f_percent < 0 )
1509     {
1510         msg_Warn( p_demux, "cannot seek nowhere !" );
1511         return;
1512     }
1513     if( f_percent > 1.0 )
1514     {
1515         msg_Warn( p_demux, "cannot seek so far !" );
1516         return;
1517     }
1518
1519     delete p_sys->ep;
1520     p_sys->ep = new EbmlParser( p_sys->es, p_sys->segment );
1521     p_sys->cluster = NULL;
1522
1523     /* seek without index or without date */
1524     if( f_percent >= 0 && (config_GetInt( p_demux, "mkv-seek-percent" ) || !p_sys->b_cues || i_date < 0 ))
1525     {
1526         if (p_sys->f_duration >= 0)
1527         {
1528             i_date = int64_t( f_percent * p_sys->f_duration * 1000.0 );
1529         }
1530         else
1531         {
1532             int64_t i_pos = int64_t( f_percent * stream_Size( p_demux->s ) );
1533
1534             msg_Dbg( p_demux, "inacurate way of seeking" );
1535             for( i_index = 0; i_index < p_sys->i_index; i_index++ )
1536             {
1537                 if( p_sys->index[i_index].i_position >= i_pos)
1538                 {
1539                     break;
1540                 }
1541             }
1542             if( i_index == p_sys->i_index )
1543             {
1544                 i_index--;
1545             }
1546
1547             i_date = p_sys->index[i_index].i_time;
1548
1549 #if 0
1550             if( p_sys->index[i_index].i_position < i_pos )
1551             {
1552                 EbmlElement *el;
1553
1554                 msg_Warn( p_demux, "searching for cluster, could take some time" );
1555
1556                 /* search a cluster */
1557                 while( ( el = p_sys->ep->Get() ) != NULL )
1558                 {
1559                     if( MKV_IS_ID( el, KaxCluster ) )
1560                     {
1561                         KaxCluster *cluster = (KaxCluster*)el;
1562
1563                         /* add it to the index */
1564                         IndexAppendCluster( p_demux, cluster );
1565
1566                         if( (int64_t)cluster->GetElementPosition() >= i_pos )
1567                         {
1568                             p_sys->cluster = cluster;
1569                             p_sys->ep->Down();
1570                             break;
1571                         }
1572                     }
1573                 }
1574             }
1575 #endif
1576         }
1577     }
1578
1579     // find the actual time for an ordered edition
1580     if ( psz_chapter == NULL )
1581     {
1582         if ( p_sys->editions.size() && p_sys->editions[p_sys->i_current_edition].b_ordered )
1583         {
1584             /* 1st, we need to know in which chapter we are */
1585             psz_chapter = p_sys->editions[p_sys->i_current_edition].FindTimecode( i_date );
1586         }
1587     }
1588
1589     if ( psz_chapter != NULL )
1590     {
1591         p_sys->psz_current_chapter = psz_chapter;
1592         p_sys->i_chapter_time = i_time_offset = psz_chapter->i_user_start_time - psz_chapter->i_start_time;
1593         p_demux->info.i_update |= INPUT_UPDATE_SEEKPOINT;
1594         p_demux->info.i_seekpoint = psz_chapter->i_seekpoint_num - 1;
1595     }
1596
1597     for( ; i_index < p_sys->i_index; i_index++ )
1598     {
1599         if( p_sys->index[i_index].i_time + i_time_offset > i_date )
1600         {
1601             break;
1602         }
1603     }
1604
1605     if( i_index > 0 )
1606     {
1607         i_index--;
1608     }
1609
1610     msg_Dbg( p_demux, "seek got "I64Fd" (%d%%)",
1611                 p_sys->index[i_index].i_time,
1612                 (int)( 100 * p_sys->index[i_index].i_position /
1613                     stream_Size( p_demux->s ) ) );
1614
1615     p_sys->in->setFilePointer( p_sys->index[i_index].i_position,
1616                                 seek_beginning );
1617
1618     p_sys->i_start_pts = i_date;
1619
1620     es_out_Control( p_demux->out, ES_OUT_RESET_PCR );
1621
1622     /* now parse until key frame */
1623 #define tk  p_sys->track[i_track]
1624     i_track_skipping = 0;
1625     for( i_track = 0; i_track < p_sys->i_track; i_track++ )
1626     {
1627         if( tk.fmt.i_cat == VIDEO_ES )
1628         {
1629             tk.b_search_keyframe = VLC_TRUE;
1630             i_track_skipping++;
1631         }
1632         es_out_Control( p_demux->out, ES_OUT_SET_NEXT_DISPLAY_TIME, tk.p_es, i_date );
1633     }
1634
1635
1636     while( i_track_skipping > 0 )
1637     {
1638         if( BlockGet( p_demux, &block, &i_block_ref1, &i_block_ref2, &i_block_duration ) )
1639         {
1640             msg_Warn( p_demux, "cannot get block EOF?" );
1641
1642             return;
1643         }
1644
1645         for( i_track = 0; i_track < p_sys->i_track; i_track++ )
1646         {
1647             if( tk.i_number == block->TrackNum() )
1648             {
1649                 break;
1650             }
1651         }
1652
1653         p_sys->i_pts = p_sys->i_chapter_time + block->GlobalTimecode() / (mtime_t) 1000;
1654
1655         if( i_track < p_sys->i_track )
1656         {
1657             if( tk.fmt.i_cat == VIDEO_ES )
1658             {
1659                 if( i_block_ref1 == -1 && tk.b_search_keyframe )
1660                 {
1661                     tk.b_search_keyframe = VLC_FALSE;
1662                     i_track_skipping--;
1663                 }
1664                 if( !tk.b_search_keyframe )
1665                 {
1666                     BlockDecode( p_demux, block, p_sys->i_pts, 0 );
1667                 }
1668             }
1669         }
1670
1671         delete block;
1672     }
1673 #undef tk
1674 }
1675
1676 /*****************************************************************************
1677  * Demux: reads and demuxes data packets
1678  *****************************************************************************
1679  * Returns -1 in case of error, 0 in case of EOF, 1 otherwise
1680  *****************************************************************************/
1681 static int Demux( demux_t *p_demux)
1682 {
1683     demux_sys_t *p_sys = p_demux->p_sys;
1684     int            i_block_count = 0;
1685
1686     KaxBlock *block;
1687     int64_t i_block_duration;
1688     int64_t i_block_ref1;
1689     int64_t i_block_ref2;
1690
1691     for( ;; )
1692     {
1693         if( p_sys->i_pts >= p_sys->i_start_pts  )
1694             UpdateCurrentToChapter( *p_demux );
1695         
1696         if ( p_sys->editions.size() && p_sys->editions[p_sys->i_current_edition].b_ordered && p_sys->psz_current_chapter == NULL )
1697         {
1698             /* nothing left to read in this ordered edition */
1699             return 0;
1700         }
1701
1702         if( BlockGet( p_demux, &block, &i_block_ref1, &i_block_ref2, &i_block_duration ) )
1703         {
1704             if ( p_sys->editions.size() && p_sys->editions[p_sys->i_current_edition].b_ordered )
1705             {
1706                 // check if there are more chapters to read
1707                 if ( p_sys->psz_current_chapter != NULL )
1708                 {
1709                     p_sys->i_pts = p_sys->psz_current_chapter->i_user_end_time;
1710                     return 1;
1711                 }
1712
1713                 return 0;
1714             }
1715             msg_Warn( p_demux, "cannot get block EOF?" );
1716
1717             return 0;
1718         }
1719
1720         p_sys->i_pts = p_sys->i_chapter_time + block->GlobalTimecode() / (mtime_t) 1000;
1721
1722         if( p_sys->i_pts >= p_sys->i_start_pts  )
1723         {
1724             es_out_Control( p_demux->out, ES_OUT_SET_PCR, p_sys->i_pts );
1725         }
1726
1727         BlockDecode( p_demux, block, p_sys->i_pts, i_block_duration );
1728
1729         delete block;
1730         i_block_count++;
1731
1732         // TODO optimize when there is need to leave or when seeking has been called
1733         if( i_block_count > 5 )
1734         {
1735             return 1;
1736         }
1737     }
1738 }
1739
1740
1741
1742 /*****************************************************************************
1743  * Stream managment
1744  *****************************************************************************/
1745 vlc_stream_io_callback::vlc_stream_io_callback( stream_t *s_ )
1746 {
1747     s = s_;
1748     mb_eof = VLC_FALSE;
1749 }
1750
1751 uint32 vlc_stream_io_callback::read( void *p_buffer, size_t i_size )
1752 {
1753     if( i_size <= 0 || mb_eof )
1754     {
1755         return 0;
1756     }
1757
1758     return stream_Read( s, p_buffer, i_size );
1759 }
1760 void vlc_stream_io_callback::setFilePointer(int64_t i_offset, seek_mode mode )
1761 {
1762     int64_t i_pos;
1763
1764     switch( mode )
1765     {
1766         case seek_beginning:
1767             i_pos = i_offset;
1768             break;
1769         case seek_end:
1770             i_pos = stream_Size( s ) - i_offset;
1771             break;
1772         default:
1773             i_pos= stream_Tell( s ) + i_offset;
1774             break;
1775     }
1776
1777     if( i_pos < 0 || i_pos >= stream_Size( s ) )
1778     {
1779         mb_eof = VLC_TRUE;
1780         return;
1781     }
1782
1783     mb_eof = VLC_FALSE;
1784     if( stream_Seek( s, i_pos ) )
1785     {
1786         mb_eof = VLC_TRUE;
1787     }
1788     return;
1789 }
1790 size_t vlc_stream_io_callback::write( const void *p_buffer, size_t i_size )
1791 {
1792     return 0;
1793 }
1794 uint64 vlc_stream_io_callback::getFilePointer( void )
1795 {
1796     return stream_Tell( s );
1797 }
1798 void vlc_stream_io_callback::close( void )
1799 {
1800     return;
1801 }
1802
1803
1804 /*****************************************************************************
1805  * Ebml Stream parser
1806  *****************************************************************************/
1807 EbmlParser::EbmlParser( EbmlStream *es, EbmlElement *el_start )
1808 {
1809     int i;
1810
1811     m_es = es;
1812     m_got = NULL;
1813     m_el[0] = el_start;
1814
1815     for( i = 1; i < 6; i++ )
1816     {
1817         m_el[i] = NULL;
1818     }
1819     mi_level = 1;
1820     mi_user_level = 1;
1821     mb_keep = VLC_FALSE;
1822 }
1823
1824 EbmlParser::~EbmlParser( void )
1825 {
1826     int i;
1827
1828     for( i = 1; i < mi_level; i++ )
1829     {
1830         if( !mb_keep )
1831         {
1832             delete m_el[i];
1833         }
1834         mb_keep = VLC_FALSE;
1835     }
1836 }
1837
1838 void EbmlParser::Up( void )
1839 {
1840     if( mi_user_level == mi_level )
1841     {
1842         fprintf( stderr," arrrrrrrrrrrrrg Up cannot escape itself\n" );
1843     }
1844
1845     mi_user_level--;
1846 }
1847
1848 void EbmlParser::Down( void )
1849 {
1850     mi_user_level++;
1851     mi_level++;
1852 }
1853
1854 void EbmlParser::Keep( void )
1855 {
1856     mb_keep = VLC_TRUE;
1857 }
1858
1859 int EbmlParser::GetLevel( void )
1860 {
1861     return mi_user_level;
1862 }
1863
1864 EbmlElement *EbmlParser::Get( void )
1865 {
1866     int i_ulev = 0;
1867
1868     if( mi_user_level != mi_level )
1869     {
1870         return NULL;
1871     }
1872     if( m_got )
1873     {
1874         EbmlElement *ret = m_got;
1875         m_got = NULL;
1876
1877         return ret;
1878     }
1879
1880     if( m_el[mi_level] )
1881     {
1882         m_el[mi_level]->SkipData( *m_es, m_el[mi_level]->Generic().Context );
1883         if( !mb_keep )
1884         {
1885             delete m_el[mi_level];
1886         }
1887         mb_keep = VLC_FALSE;
1888     }
1889
1890     m_el[mi_level] = m_es->FindNextElement( m_el[mi_level - 1]->Generic().Context, i_ulev, 0xFFFFFFFFL, true, 1 );
1891     if( i_ulev > 0 )
1892     {
1893         while( i_ulev > 0 )
1894         {
1895             if( mi_level == 1 )
1896             {
1897                 mi_level = 0;
1898                 return NULL;
1899             }
1900
1901             delete m_el[mi_level - 1];
1902             m_got = m_el[mi_level -1] = m_el[mi_level];
1903             m_el[mi_level] = NULL;
1904
1905             mi_level--;
1906             i_ulev--;
1907         }
1908         return NULL;
1909     }
1910     else if( m_el[mi_level] == NULL )
1911     {
1912         fprintf( stderr," m_el[mi_level] == NULL\n" );
1913     }
1914
1915     return m_el[mi_level];
1916 }
1917
1918
1919 /*****************************************************************************
1920  * Tools
1921  *  * LoadCues : load the cues element and update index
1922  *
1923  *  * LoadTags : load ... the tags element
1924  *
1925  *  * InformationCreate : create all information, load tags if present
1926  *
1927  *****************************************************************************/
1928 static void LoadCues( demux_t *p_demux )
1929 {
1930     demux_sys_t *p_sys = p_demux->p_sys;
1931     int64_t     i_sav_position = p_sys->in->getFilePointer();
1932     EbmlParser  *ep;
1933     EbmlElement *el, *cues;
1934
1935     msg_Dbg( p_demux, "loading cues" );
1936     p_sys->in->setFilePointer( p_sys->i_cues_position, seek_beginning );
1937     cues = p_sys->es->FindNextID( KaxCues::ClassInfos, 0xFFFFFFFFL);
1938
1939     if( cues == NULL )
1940     {
1941         msg_Err( p_demux, "cannot load cues (broken seekhead or file)" );
1942         p_sys->in->setFilePointer( i_sav_position, seek_beginning );
1943         return;
1944     }
1945
1946     ep = new EbmlParser( p_sys->es, cues );
1947     while( ( el = ep->Get() ) != NULL )
1948     {
1949         if( MKV_IS_ID( el, KaxCuePoint ) )
1950         {
1951 #define idx p_sys->index[p_sys->i_index]
1952
1953             idx.i_track       = -1;
1954             idx.i_block_number= -1;
1955             idx.i_position    = -1;
1956             idx.i_time        = 0;
1957             idx.b_key         = VLC_TRUE;
1958
1959             ep->Down();
1960             while( ( el = ep->Get() ) != NULL )
1961             {
1962                 if( MKV_IS_ID( el, KaxCueTime ) )
1963                 {
1964                     KaxCueTime &ctime = *(KaxCueTime*)el;
1965
1966                     ctime.ReadData( p_sys->es->I_O() );
1967
1968                     idx.i_time = uint64( ctime ) * p_sys->i_timescale / (mtime_t)1000;
1969                 }
1970                 else if( MKV_IS_ID( el, KaxCueTrackPositions ) )
1971                 {
1972                     ep->Down();
1973                     while( ( el = ep->Get() ) != NULL )
1974                     {
1975                         if( MKV_IS_ID( el, KaxCueTrack ) )
1976                         {
1977                             KaxCueTrack &ctrack = *(KaxCueTrack*)el;
1978
1979                             ctrack.ReadData( p_sys->es->I_O() );
1980                             idx.i_track = uint16( ctrack );
1981                         }
1982                         else if( MKV_IS_ID( el, KaxCueClusterPosition ) )
1983                         {
1984                             KaxCueClusterPosition &ccpos = *(KaxCueClusterPosition*)el;
1985
1986                             ccpos.ReadData( p_sys->es->I_O() );
1987                             idx.i_position = p_sys->segment->GetGlobalPosition( uint64( ccpos ) );
1988                         }
1989                         else if( MKV_IS_ID( el, KaxCueBlockNumber ) )
1990                         {
1991                             KaxCueBlockNumber &cbnum = *(KaxCueBlockNumber*)el;
1992
1993                             cbnum.ReadData( p_sys->es->I_O() );
1994                             idx.i_block_number = uint32( cbnum );
1995                         }
1996                         else
1997                         {
1998                             msg_Dbg( p_demux, "         * Unknown (%s)", typeid(*el).name() );
1999                         }
2000                     }
2001                     ep->Up();
2002                 }
2003                 else
2004                 {
2005                     msg_Dbg( p_demux, "     * Unknown (%s)", typeid(*el).name() );
2006                 }
2007             }
2008             ep->Up();
2009
2010 #if 0
2011             msg_Dbg( p_demux, " * added time="I64Fd" pos="I64Fd
2012                      " track=%d bnum=%d", idx.i_time, idx.i_position,
2013                      idx.i_track, idx.i_block_number );
2014 #endif
2015
2016             p_sys->i_index++;
2017             if( p_sys->i_index >= p_sys->i_index_max )
2018             {
2019                 p_sys->i_index_max += 1024;
2020                 p_sys->index = (mkv_index_t*)realloc( p_sys->index, sizeof( mkv_index_t ) * p_sys->i_index_max );
2021             }
2022 #undef idx
2023         }
2024         else
2025         {
2026             msg_Dbg( p_demux, " * Unknown (%s)", typeid(*el).name() );
2027         }
2028     }
2029     delete ep;
2030     delete cues;
2031
2032     p_sys->b_cues = VLC_TRUE;
2033
2034     msg_Dbg( p_demux, "loading cues done." );
2035     p_sys->in->setFilePointer( i_sav_position, seek_beginning );
2036 }
2037
2038 static void LoadTags( demux_t *p_demux )
2039 {
2040     demux_sys_t *p_sys = p_demux->p_sys;
2041     int64_t     i_sav_position = p_sys->in->getFilePointer();
2042     EbmlParser  *ep;
2043     EbmlElement *el, *tags;
2044
2045     msg_Dbg( p_demux, "loading tags" );
2046     p_sys->in->setFilePointer( p_sys->i_tags_position, seek_beginning );
2047     tags = p_sys->es->FindNextID( KaxTags::ClassInfos, 0xFFFFFFFFL);
2048
2049     if( tags == NULL )
2050     {
2051         msg_Err( p_demux, "cannot load tags (broken seekhead or file)" );
2052         p_sys->in->setFilePointer( i_sav_position, seek_beginning );
2053         return;
2054     }
2055
2056     msg_Dbg( p_demux, "Tags" );
2057     ep = new EbmlParser( p_sys->es, tags );
2058     while( ( el = ep->Get() ) != NULL )
2059     {
2060         if( MKV_IS_ID( el, KaxTag ) )
2061         {
2062             msg_Dbg( p_demux, "+ Tag" );
2063             ep->Down();
2064             while( ( el = ep->Get() ) != NULL )
2065             {
2066                 if( MKV_IS_ID( el, KaxTagTargets ) )
2067                 {
2068                     msg_Dbg( p_demux, "|   + Targets" );
2069                     ep->Down();
2070                     while( ( el = ep->Get() ) != NULL )
2071                     {
2072                         msg_Dbg( p_demux, "|   |   + Unknown (%s)", typeid( *el ).name() );
2073                     }
2074                     ep->Up();
2075                 }
2076                 else if( MKV_IS_ID( el, KaxTagGeneral ) )
2077                 {
2078                     msg_Dbg( p_demux, "|   + General" );
2079                     ep->Down();
2080                     while( ( el = ep->Get() ) != NULL )
2081                     {
2082                         msg_Dbg( p_demux, "|   |   + Unknown (%s)", typeid( *el ).name() );
2083                     }
2084                     ep->Up();
2085                 }
2086                 else if( MKV_IS_ID( el, KaxTagGenres ) )
2087                 {
2088                     msg_Dbg( p_demux, "|   + Genres" );
2089                     ep->Down();
2090                     while( ( el = ep->Get() ) != NULL )
2091                     {
2092                         msg_Dbg( p_demux, "|   |   + Unknown (%s)", typeid( *el ).name() );
2093                     }
2094                     ep->Up();
2095                 }
2096                 else if( MKV_IS_ID( el, KaxTagAudioSpecific ) )
2097                 {
2098                     msg_Dbg( p_demux, "|   + Audio Specific" );
2099                     ep->Down();
2100                     while( ( el = ep->Get() ) != NULL )
2101                     {
2102                         msg_Dbg( p_demux, "|   |   + Unknown (%s)", typeid( *el ).name() );
2103                     }
2104                     ep->Up();
2105                 }
2106                 else if( MKV_IS_ID( el, KaxTagImageSpecific ) )
2107                 {
2108                     msg_Dbg( p_demux, "|   + Images Specific" );
2109                     ep->Down();
2110                     while( ( el = ep->Get() ) != NULL )
2111                     {
2112                         msg_Dbg( p_demux, "|   |   + Unknown (%s)", typeid( *el ).name() );
2113                     }
2114                     ep->Up();
2115                 }
2116                 else if( MKV_IS_ID( el, KaxTagMultiComment ) )
2117                 {
2118                     msg_Dbg( p_demux, "|   + Multi Comment" );
2119                 }
2120                 else if( MKV_IS_ID( el, KaxTagMultiCommercial ) )
2121                 {
2122                     msg_Dbg( p_demux, "|   + Multi Commercial" );
2123                 }
2124                 else if( MKV_IS_ID( el, KaxTagMultiDate ) )
2125                 {
2126                     msg_Dbg( p_demux, "|   + Multi Date" );
2127                 }
2128                 else if( MKV_IS_ID( el, KaxTagMultiEntity ) )
2129                 {
2130                     msg_Dbg( p_demux, "|   + Multi Entity" );
2131                 }
2132                 else if( MKV_IS_ID( el, KaxTagMultiIdentifier ) )
2133                 {
2134                     msg_Dbg( p_demux, "|   + Multi Identifier" );
2135                 }
2136                 else if( MKV_IS_ID( el, KaxTagMultiLegal ) )
2137                 {
2138                     msg_Dbg( p_demux, "|   + Multi Legal" );
2139                 }
2140                 else if( MKV_IS_ID( el, KaxTagMultiTitle ) )
2141                 {
2142                     msg_Dbg( p_demux, "|   + Multi Title" );
2143                 }
2144                 else
2145                 {
2146                     msg_Dbg( p_demux, "|   + Unknown (%s)", typeid( *el ).name() );
2147                 }
2148             }
2149             ep->Up();
2150         }
2151         else
2152         {
2153             msg_Dbg( p_demux, "+ Unknown (%s)", typeid( *el ).name() );
2154         }
2155     }
2156     delete ep;
2157     delete tags;
2158
2159     msg_Dbg( p_demux, "loading tags done." );
2160     p_sys->in->setFilePointer( i_sav_position, seek_beginning );
2161 }
2162
2163 /*****************************************************************************
2164  * ParseInfo:
2165  *****************************************************************************/
2166 static void ParseSeekHead( demux_t *p_demux, EbmlElement *seekhead )
2167 {
2168     demux_sys_t *p_sys = p_demux->p_sys;
2169     EbmlElement *el;
2170     EbmlMaster  *m;
2171     unsigned int i;
2172     int i_upper_level = 0;
2173
2174     msg_Dbg( p_demux, "|   + Seek head" );
2175
2176     /* Master elements */
2177     m = static_cast<EbmlMaster *>(seekhead);
2178     m->Read( *p_sys->es, seekhead->Generic().Context, i_upper_level, el, true );
2179
2180     for( i = 0; i < m->ListSize(); i++ )
2181     {
2182         EbmlElement *l = (*m)[i];
2183
2184         if( MKV_IS_ID( l, KaxSeek ) )
2185         {
2186             EbmlMaster *sk = static_cast<EbmlMaster *>(l);
2187             EbmlId id = EbmlVoid::ClassInfos.GlobalId;
2188             int64_t i_pos = -1;
2189
2190             unsigned int j;
2191
2192             for( j = 0; j < sk->ListSize(); j++ )
2193             {
2194                 EbmlElement *l = (*sk)[j];
2195
2196                 if( MKV_IS_ID( l, KaxSeekID ) )
2197                 {
2198                     KaxSeekID &sid = *(KaxSeekID*)l;
2199                     id = EbmlId( sid.GetBuffer(), sid.GetSize() );
2200                 }
2201                 else if( MKV_IS_ID( l, KaxSeekPosition ) )
2202                 {
2203                     KaxSeekPosition &spos = *(KaxSeekPosition*)l;
2204                     i_pos = uint64( spos );
2205                 }
2206                 else
2207                 {
2208                     msg_Dbg( p_demux, "|   |   |   + Unknown (%s)", typeid(*l).name() );
2209                 }
2210             }
2211
2212             if( i_pos >= 0 )
2213             {
2214                 if( id == KaxCues::ClassInfos.GlobalId )
2215                 {
2216                     msg_Dbg( p_demux, "|   |   |   = cues at "I64Fd, i_pos );
2217                     p_sys->i_cues_position = p_sys->segment->GetGlobalPosition( i_pos );
2218                 }
2219                 else if( id == KaxChapters::ClassInfos.GlobalId )
2220                 {
2221                     msg_Dbg( p_demux, "|   |   |   = chapters at "I64Fd, i_pos );
2222                     p_sys->i_chapters_position = p_sys->segment->GetGlobalPosition( i_pos );
2223                 }
2224                 else if( id == KaxTags::ClassInfos.GlobalId )
2225                 {
2226                     msg_Dbg( p_demux, "|   |   |   = tags at "I64Fd, i_pos );
2227                     p_sys->i_tags_position = p_sys->segment->GetGlobalPosition( i_pos );
2228                 }
2229             }
2230         }
2231         else
2232         {
2233             msg_Dbg( p_demux, "|   |   + Unknown (%s)", typeid(*l).name() );
2234         }
2235     }
2236 }
2237
2238 /*****************************************************************************
2239  * ParseTracks:
2240  *****************************************************************************/
2241 static void ParseTrackEntry( demux_t *p_demux, EbmlMaster *m )
2242 {
2243     demux_sys_t *p_sys = p_demux->p_sys;
2244     unsigned int i;
2245
2246     mkv_track_t *tk;
2247
2248     msg_Dbg( p_demux, "|   |   + Track Entry" );
2249
2250     p_sys->i_track++;
2251     p_sys->track = (mkv_track_t*)realloc( p_sys->track, sizeof( mkv_track_t ) * (p_sys->i_track + 1 ) );
2252
2253     /* Init the track */
2254     tk = &p_sys->track[p_sys->i_track - 1];
2255
2256     memset( tk, 0, sizeof( mkv_track_t ) );
2257
2258     es_format_Init( &tk->fmt, UNKNOWN_ES, 0 );
2259     tk->fmt.psz_language = strdup("English");
2260     tk->fmt.psz_description = NULL;
2261
2262     tk->b_default = VLC_TRUE;
2263     tk->b_enabled = VLC_TRUE;
2264     tk->i_number = p_sys->i_track - 1;
2265     tk->i_extra_data = 0;
2266     tk->p_extra_data = NULL;
2267     tk->psz_codec = NULL;
2268     tk->i_default_duration = 0;
2269     tk->f_timecodescale = 1.0;
2270
2271     tk->b_inited = VLC_FALSE;
2272     tk->i_data_init = 0;
2273     tk->p_data_init = NULL;
2274
2275     tk->psz_codec_name = NULL;
2276     tk->psz_codec_settings = NULL;
2277     tk->psz_codec_info_url = NULL;
2278     tk->psz_codec_download_url = NULL;
2279     
2280     tk->i_compression_type = MATROSKA_COMPRESSION_NONE;
2281
2282     for( i = 0; i < m->ListSize(); i++ )
2283     {
2284         EbmlElement *l = (*m)[i];
2285
2286         if( MKV_IS_ID( l, KaxTrackNumber ) )
2287         {
2288             KaxTrackNumber &tnum = *(KaxTrackNumber*)l;
2289
2290             tk->i_number = uint32( tnum );
2291             msg_Dbg( p_demux, "|   |   |   + Track Number=%u", uint32( tnum ) );
2292         }
2293         else  if( MKV_IS_ID( l, KaxTrackUID ) )
2294         {
2295             KaxTrackUID &tuid = *(KaxTrackUID*)l;
2296
2297             msg_Dbg( p_demux, "|   |   |   + Track UID=%u",  uint32( tuid ) );
2298         }
2299         else  if( MKV_IS_ID( l, KaxTrackType ) )
2300         {
2301             char *psz_type;
2302             KaxTrackType &ttype = *(KaxTrackType*)l;
2303
2304             switch( uint8(ttype) )
2305             {
2306                 case track_audio:
2307                     psz_type = "audio";
2308                     tk->fmt.i_cat = AUDIO_ES;
2309                     break;
2310                 case track_video:
2311                     psz_type = "video";
2312                     tk->fmt.i_cat = VIDEO_ES;
2313                     break;
2314                 case track_subtitle:
2315                     psz_type = "subtitle";
2316                     tk->fmt.i_cat = SPU_ES;
2317                     break;
2318                 default:
2319                     psz_type = "unknown";
2320                     tk->fmt.i_cat = UNKNOWN_ES;
2321                     break;
2322             }
2323
2324             msg_Dbg( p_demux, "|   |   |   + Track Type=%s", psz_type );
2325         }
2326 //        else  if( EbmlId( *l ) == KaxTrackFlagEnabled::ClassInfos.GlobalId )
2327 //        {
2328 //            KaxTrackFlagEnabled &fenb = *(KaxTrackFlagEnabled*)l;
2329
2330 //            tk->b_enabled = uint32( fenb );
2331 //            msg_Dbg( p_demux, "|   |   |   + Track Enabled=%u",
2332 //                     uint32( fenb )  );
2333 //        }
2334         else  if( MKV_IS_ID( l, KaxTrackFlagDefault ) )
2335         {
2336             KaxTrackFlagDefault &fdef = *(KaxTrackFlagDefault*)l;
2337
2338             tk->b_default = uint32( fdef );
2339             msg_Dbg( p_demux, "|   |   |   + Track Default=%u", uint32( fdef )  );
2340         }
2341         else  if( MKV_IS_ID( l, KaxTrackFlagLacing ) )
2342         {
2343             KaxTrackFlagLacing &lac = *(KaxTrackFlagLacing*)l;
2344
2345             msg_Dbg( p_demux, "|   |   |   + Track Lacing=%d", uint32( lac ) );
2346         }
2347         else  if( MKV_IS_ID( l, KaxTrackMinCache ) )
2348         {
2349             KaxTrackMinCache &cmin = *(KaxTrackMinCache*)l;
2350
2351             msg_Dbg( p_demux, "|   |   |   + Track MinCache=%d", uint32( cmin ) );
2352         }
2353         else  if( MKV_IS_ID( l, KaxTrackMaxCache ) )
2354         {
2355             KaxTrackMaxCache &cmax = *(KaxTrackMaxCache*)l;
2356
2357             msg_Dbg( p_demux, "|   |   |   + Track MaxCache=%d", uint32( cmax ) );
2358         }
2359         else  if( MKV_IS_ID( l, KaxTrackDefaultDuration ) )
2360         {
2361             KaxTrackDefaultDuration &defd = *(KaxTrackDefaultDuration*)l;
2362
2363             tk->i_default_duration = uint64(defd);
2364             msg_Dbg( p_demux, "|   |   |   + Track Default Duration="I64Fd, uint64(defd) );
2365         }
2366         else  if( MKV_IS_ID( l, KaxTrackTimecodeScale ) )
2367         {
2368             KaxTrackTimecodeScale &ttcs = *(KaxTrackTimecodeScale*)l;
2369
2370             tk->f_timecodescale = float( ttcs );
2371             msg_Dbg( p_demux, "|   |   |   + Track TimeCodeScale=%f", tk->f_timecodescale );
2372         }
2373         else if( MKV_IS_ID( l, KaxTrackName ) )
2374         {
2375             KaxTrackName &tname = *(KaxTrackName*)l;
2376
2377             tk->fmt.psz_description = UTF8ToStr( UTFstring( tname ) );
2378             msg_Dbg( p_demux, "|   |   |   + Track Name=%s", tk->fmt.psz_description );
2379         }
2380         else  if( MKV_IS_ID( l, KaxTrackLanguage ) )
2381         {
2382             KaxTrackLanguage &lang = *(KaxTrackLanguage*)l;
2383
2384             tk->fmt.psz_language = strdup( string( lang ).c_str() );
2385             msg_Dbg( p_demux,
2386                      "|   |   |   + Track Language=`%s'", tk->fmt.psz_language );
2387         }
2388         else  if( MKV_IS_ID( l, KaxCodecID ) )
2389         {
2390             KaxCodecID &codecid = *(KaxCodecID*)l;
2391
2392             tk->psz_codec = strdup( string( codecid ).c_str() );
2393             msg_Dbg( p_demux, "|   |   |   + Track CodecId=%s", string( codecid ).c_str() );
2394         }
2395         else  if( MKV_IS_ID( l, KaxCodecPrivate ) )
2396         {
2397             KaxCodecPrivate &cpriv = *(KaxCodecPrivate*)l;
2398
2399             tk->i_extra_data = cpriv.GetSize();
2400             if( tk->i_extra_data > 0 )
2401             {
2402                 tk->p_extra_data = (uint8_t*)malloc( tk->i_extra_data );
2403                 memcpy( tk->p_extra_data, cpriv.GetBuffer(), tk->i_extra_data );
2404             }
2405             msg_Dbg( p_demux, "|   |   |   + Track CodecPrivate size="I64Fd, cpriv.GetSize() );
2406         }
2407         else if( MKV_IS_ID( l, KaxCodecName ) )
2408         {
2409             KaxCodecName &cname = *(KaxCodecName*)l;
2410
2411             tk->psz_codec_name = UTF8ToStr( UTFstring( cname ) );
2412             msg_Dbg( p_demux, "|   |   |   + Track Codec Name=%s", tk->psz_codec_name );
2413         }
2414         else if( MKV_IS_ID( l, KaxContentEncodings ) )
2415         {
2416             EbmlMaster *cencs = static_cast<EbmlMaster*>(l);
2417             MkvTree( p_demux, 3, "Content Encodings" );
2418             for( unsigned int i = 0; i < cencs->ListSize(); i++ )
2419             {
2420                 EbmlElement *l2 = (*cencs)[i];
2421                 if( MKV_IS_ID( l2, KaxContentEncoding ) )
2422                 {
2423                     MkvTree( p_demux, 4, "Content Encoding" );
2424                     EbmlMaster *cenc = static_cast<EbmlMaster*>(l2);
2425                     for( unsigned int i = 0; i < cenc->ListSize(); i++ )
2426                     {
2427                         EbmlElement *l3 = (*cenc)[i];
2428                         if( MKV_IS_ID( l3, KaxContentEncodingOrder ) )
2429                         {
2430                             KaxContentEncodingOrder &encord = *(KaxContentEncodingOrder*)l3;
2431                             MkvTree( p_demux, 5, "Order: %i", uint32( encord ) );
2432                         }
2433                         else if( MKV_IS_ID( l3, KaxContentEncodingScope ) )
2434                         {
2435                             KaxContentEncodingScope &encscope = *(KaxContentEncodingScope*)l3;
2436                             MkvTree( p_demux, 5, "Scope: %i", uint32( encscope ) );
2437                         }
2438                         else if( MKV_IS_ID( l3, KaxContentEncodingType ) )
2439                         {
2440                             KaxContentEncodingType &enctype = *(KaxContentEncodingType*)l3;
2441                             MkvTree( p_demux, 5, "Type: %i", uint32( enctype ) );
2442                         }
2443                         else if( MKV_IS_ID( l3, KaxContentCompression ) )
2444                         {
2445                             EbmlMaster *compr = static_cast<EbmlMaster*>(l3);
2446                             MkvTree( p_demux, 5, "Content Compression" );
2447                             for( unsigned int i = 0; i < compr->ListSize(); i++ )
2448                             {
2449                                 EbmlElement *l4 = (*compr)[i];
2450                                 if( MKV_IS_ID( l4, KaxContentCompAlgo ) )
2451                                 {
2452                                     KaxContentCompAlgo &compalg = *(KaxContentCompAlgo*)l4;
2453                                     MkvTree( p_demux, 6, "Compression Algorithm: %i", uint32(compalg) );
2454                                     if( uint32( compalg ) == 0 )
2455                                     {
2456                                         tk->i_compression_type = MATROSKA_COMPRESSION_ZLIB;
2457                                     }
2458                                 }
2459                                 else
2460                                 {
2461                                     MkvTree( p_demux, 6, "Unknown (%s)", typeid(*l4).name() );
2462                                 }
2463                             }
2464                         }
2465
2466                         else
2467                         {
2468                             MkvTree( p_demux, 5, "Unknown (%s)", typeid(*l3).name() );
2469                         }
2470                     }
2471                     
2472                 }
2473                 else
2474                 {
2475                     MkvTree( p_demux, 4, "Unknown (%s)", typeid(*l2).name() );
2476                 }
2477             }
2478                 
2479         }
2480 //        else if( EbmlId( *l ) == KaxCodecSettings::ClassInfos.GlobalId )
2481 //        {
2482 //            KaxCodecSettings &cset = *(KaxCodecSettings*)l;
2483
2484 //            tk->psz_codec_settings = UTF8ToStr( UTFstring( cset ) );
2485 //            msg_Dbg( p_demux, "|   |   |   + Track Codec Settings=%s", tk->psz_codec_settings );
2486 //        }
2487 //        else if( EbmlId( *l ) == KaxCodecInfoURL::ClassInfos.GlobalId )
2488 //        {
2489 //            KaxCodecInfoURL &ciurl = *(KaxCodecInfoURL*)l;
2490
2491 //            tk->psz_codec_info_url = strdup( string( ciurl ).c_str() );
2492 //            msg_Dbg( p_demux, "|   |   |   + Track Codec Info URL=%s", tk->psz_codec_info_url );
2493 //        }
2494 //        else if( EbmlId( *l ) == KaxCodecDownloadURL::ClassInfos.GlobalId )
2495 //        {
2496 //            KaxCodecDownloadURL &cdurl = *(KaxCodecDownloadURL*)l;
2497
2498 //            tk->psz_codec_download_url = strdup( string( cdurl ).c_str() );
2499 //            msg_Dbg( p_demux, "|   |   |   + Track Codec Info URL=%s", tk->psz_codec_download_url );
2500 //        }
2501 //        else if( EbmlId( *l ) == KaxCodecDecodeAll::ClassInfos.GlobalId )
2502 //        {
2503 //            KaxCodecDecodeAll &cdall = *(KaxCodecDecodeAll*)l;
2504
2505 //            msg_Dbg( p_demux, "|   |   |   + Track Codec Decode All=%u <== UNUSED", uint8( cdall ) );
2506 //        }
2507 //        else if( EbmlId( *l ) == KaxTrackOverlay::ClassInfos.GlobalId )
2508 //        {
2509 //            KaxTrackOverlay &tovr = *(KaxTrackOverlay*)l;
2510
2511 //            msg_Dbg( p_demux, "|   |   |   + Track Overlay=%u <== UNUSED", uint32( tovr ) );
2512 //        }
2513         else  if( MKV_IS_ID( l, KaxTrackVideo ) )
2514         {
2515             EbmlMaster *tkv = static_cast<EbmlMaster*>(l);
2516             unsigned int j;
2517
2518             msg_Dbg( p_demux, "|   |   |   + Track Video" );
2519             tk->f_fps = 0.0;
2520
2521             for( j = 0; j < tkv->ListSize(); j++ )
2522             {
2523                 EbmlElement *l = (*tkv)[j];
2524 //                if( EbmlId( *el4 ) == KaxVideoFlagInterlaced::ClassInfos.GlobalId )
2525 //                {
2526 //                    KaxVideoFlagInterlaced &fint = *(KaxVideoFlagInterlaced*)el4;
2527
2528 //                    msg_Dbg( p_demux, "|   |   |   |   + Track Video Interlaced=%u", uint8( fint ) );
2529 //                }
2530 //                else if( EbmlId( *el4 ) == KaxVideoStereoMode::ClassInfos.GlobalId )
2531 //                {
2532 //                    KaxVideoStereoMode &stereo = *(KaxVideoStereoMode*)el4;
2533
2534 //                    msg_Dbg( p_demux, "|   |   |   |   + Track Video Stereo Mode=%u", uint8( stereo ) );
2535 //                }
2536 //                else
2537                 if( MKV_IS_ID( l, KaxVideoPixelWidth ) )
2538                 {
2539                     KaxVideoPixelWidth &vwidth = *(KaxVideoPixelWidth*)l;
2540
2541                     tk->fmt.video.i_width = uint16( vwidth );
2542                     msg_Dbg( p_demux, "|   |   |   |   + width=%d", uint16( vwidth ) );
2543                 }
2544                 else if( MKV_IS_ID( l, KaxVideoPixelHeight ) )
2545                 {
2546                     KaxVideoPixelWidth &vheight = *(KaxVideoPixelWidth*)l;
2547
2548                     tk->fmt.video.i_height = uint16( vheight );
2549                     msg_Dbg( p_demux, "|   |   |   |   + height=%d", uint16( vheight ) );
2550                 }
2551                 else if( MKV_IS_ID( l, KaxVideoDisplayWidth ) )
2552                 {
2553                     KaxVideoDisplayWidth &vwidth = *(KaxVideoDisplayWidth*)l;
2554
2555                     tk->fmt.video.i_visible_width = uint16( vwidth );
2556                     msg_Dbg( p_demux, "|   |   |   |   + display width=%d", uint16( vwidth ) );
2557                 }
2558                 else if( MKV_IS_ID( l, KaxVideoDisplayHeight ) )
2559                 {
2560                     KaxVideoDisplayWidth &vheight = *(KaxVideoDisplayWidth*)l;
2561
2562                     tk->fmt.video.i_visible_height = uint16( vheight );
2563                     msg_Dbg( p_demux, "|   |   |   |   + display height=%d", uint16( vheight ) );
2564                 }
2565                 else if( MKV_IS_ID( l, KaxVideoFrameRate ) )
2566                 {
2567                     KaxVideoFrameRate &vfps = *(KaxVideoFrameRate*)l;
2568
2569                     tk->f_fps = float( vfps );
2570                     msg_Dbg( p_demux, "   |   |   |   + fps=%f", float( vfps ) );
2571                 }
2572 //                else if( EbmlId( *l ) == KaxVideoDisplayUnit::ClassInfos.GlobalId )
2573 //                {
2574 //                     KaxVideoDisplayUnit &vdmode = *(KaxVideoDisplayUnit*)l;
2575
2576 //                    msg_Dbg( p_demux, "|   |   |   |   + Track Video Display Unit=%s",
2577 //                             uint8( vdmode ) == 0 ? "pixels" : ( uint8( vdmode ) == 1 ? "centimeters": "inches" ) );
2578 //                }
2579 //                else if( EbmlId( *l ) == KaxVideoAspectRatio::ClassInfos.GlobalId )
2580 //                {
2581 //                    KaxVideoAspectRatio &ratio = *(KaxVideoAspectRatio*)l;
2582
2583 //                    msg_Dbg( p_demux, "   |   |   |   + Track Video Aspect Ratio Type=%u", uint8( ratio ) );
2584 //                }
2585 //                else if( EbmlId( *l ) == KaxVideoGamma::ClassInfos.GlobalId )
2586 //                {
2587 //                    KaxVideoGamma &gamma = *(KaxVideoGamma*)l;
2588
2589 //                    msg_Dbg( p_demux, "   |   |   |   + fps=%f", float( gamma ) );
2590 //                }
2591                 else
2592                 {
2593                     msg_Dbg( p_demux, "|   |   |   |   + Unknown (%s)", typeid(*l).name() );
2594                 }
2595             }
2596         }
2597         else  if( MKV_IS_ID( l, KaxTrackAudio ) )
2598         {
2599             EbmlMaster *tka = static_cast<EbmlMaster*>(l);
2600             unsigned int j;
2601
2602             msg_Dbg( p_demux, "|   |   |   + Track Audio" );
2603
2604             for( j = 0; j < tka->ListSize(); j++ )
2605             {
2606                 EbmlElement *l = (*tka)[j];
2607
2608                 if( MKV_IS_ID( l, KaxAudioSamplingFreq ) )
2609                 {
2610                     KaxAudioSamplingFreq &afreq = *(KaxAudioSamplingFreq*)l;
2611
2612                     tk->fmt.audio.i_rate = (int)float( afreq );
2613                     msg_Dbg( p_demux, "|   |   |   |   + afreq=%d", tk->fmt.audio.i_rate );
2614                 }
2615                 else if( MKV_IS_ID( l, KaxAudioChannels ) )
2616                 {
2617                     KaxAudioChannels &achan = *(KaxAudioChannels*)l;
2618
2619                     tk->fmt.audio.i_channels = uint8( achan );
2620                     msg_Dbg( p_demux, "|   |   |   |   + achan=%u", uint8( achan ) );
2621                 }
2622                 else if( MKV_IS_ID( l, KaxAudioBitDepth ) )
2623                 {
2624                     KaxAudioBitDepth &abits = *(KaxAudioBitDepth*)l;
2625
2626                     tk->fmt.audio.i_bitspersample = uint8( abits );
2627                     msg_Dbg( p_demux, "|   |   |   |   + abits=%u", uint8( abits ) );
2628                 }
2629                 else
2630                 {
2631                     msg_Dbg( p_demux, "|   |   |   |   + Unknown (%s)", typeid(*l).name() );
2632                 }
2633             }
2634         }
2635         else
2636         {
2637             msg_Dbg( p_demux, "|   |   |   + Unknown (%s)",
2638                      typeid(*l).name() );
2639         }
2640     }
2641 }
2642
2643 static void ParseTracks( demux_t *p_demux, EbmlElement *tracks )
2644 {
2645     demux_sys_t *p_sys = p_demux->p_sys;
2646     EbmlElement *el;
2647     EbmlMaster  *m;
2648     unsigned int i;
2649     int i_upper_level = 0;
2650
2651     msg_Dbg( p_demux, "|   + Tracks" );
2652
2653     /* Master elements */
2654     m = static_cast<EbmlMaster *>(tracks);
2655     m->Read( *p_sys->es, tracks->Generic().Context, i_upper_level, el, true );
2656
2657     for( i = 0; i < m->ListSize(); i++ )
2658     {
2659         EbmlElement *l = (*m)[i];
2660
2661         if( MKV_IS_ID( l, KaxTrackEntry ) )
2662         {
2663             ParseTrackEntry( p_demux, static_cast<EbmlMaster *>(l) );
2664         }
2665         else
2666         {
2667             msg_Dbg( p_demux, "|   |   + Unknown (%s)", typeid(*l).name() );
2668         }
2669     }
2670 }
2671
2672 /*****************************************************************************
2673  * ParseInfo:
2674  *****************************************************************************/
2675 static void ParseInfo( demux_t *p_demux, EbmlElement *info )
2676 {
2677     demux_sys_t *p_sys = p_demux->p_sys;
2678     EbmlElement *el;
2679     EbmlMaster  *m;
2680     unsigned int i;
2681     int i_upper_level = 0;
2682
2683     msg_Dbg( p_demux, "|   + Information" );
2684
2685     /* Master elements */
2686     m = static_cast<EbmlMaster *>(info);
2687     m->Read( *p_sys->es, info->Generic().Context, i_upper_level, el, true );
2688
2689     for( i = 0; i < m->ListSize(); i++ )
2690     {
2691         EbmlElement *l = (*m)[i];
2692
2693         if( MKV_IS_ID( l, KaxSegmentUID ) )
2694         {
2695             p_sys->segment_uid = *(new KaxSegmentUID(*static_cast<KaxSegmentUID*>(l)));
2696
2697             msg_Dbg( p_demux, "|   |   + UID=%d", *(uint32*)p_sys->segment_uid.GetBuffer() );
2698         }
2699         else if( MKV_IS_ID( l, KaxTimecodeScale ) )
2700         {
2701             KaxTimecodeScale &tcs = *(KaxTimecodeScale*)l;
2702
2703             p_sys->i_timescale = uint64(tcs);
2704
2705             msg_Dbg( p_demux, "|   |   + TimecodeScale="I64Fd,
2706                      p_sys->i_timescale );
2707         }
2708         else if( MKV_IS_ID( l, KaxDuration ) )
2709         {
2710             KaxDuration &dur = *(KaxDuration*)l;
2711
2712             p_sys->f_duration = float(dur);
2713
2714             msg_Dbg( p_demux, "|   |   + Duration=%f",
2715                      p_sys->f_duration );
2716         }
2717         else if( MKV_IS_ID( l, KaxMuxingApp ) )
2718         {
2719             KaxMuxingApp &mapp = *(KaxMuxingApp*)l;
2720
2721             p_sys->psz_muxing_application = UTF8ToStr( UTFstring( mapp ) );
2722
2723             msg_Dbg( p_demux, "|   |   + Muxing Application=%s",
2724                      p_sys->psz_muxing_application );
2725         }
2726         else if( MKV_IS_ID( l, KaxWritingApp ) )
2727         {
2728             KaxWritingApp &wapp = *(KaxWritingApp*)l;
2729
2730             p_sys->psz_writing_application = UTF8ToStr( UTFstring( wapp ) );
2731
2732             msg_Dbg( p_demux, "|   |   + Writing Application=%s",
2733                      p_sys->psz_writing_application );
2734         }
2735         else if( MKV_IS_ID( l, KaxSegmentFilename ) )
2736         {
2737             KaxSegmentFilename &sfn = *(KaxSegmentFilename*)l;
2738
2739             p_sys->psz_segment_filename = UTF8ToStr( UTFstring( sfn ) );
2740
2741             msg_Dbg( p_demux, "|   |   + Segment Filename=%s",
2742                      p_sys->psz_segment_filename );
2743         }
2744         else if( MKV_IS_ID( l, KaxTitle ) )
2745         {
2746             KaxTitle &title = *(KaxTitle*)l;
2747
2748             p_sys->psz_title = UTF8ToStr( UTFstring( title ) );
2749
2750             msg_Dbg( p_demux, "|   |   + Title=%s", p_sys->psz_title );
2751         }
2752         if( MKV_IS_ID( l, KaxSegmentFamily ) )
2753         {
2754             KaxSegmentFamily *uid = static_cast<KaxSegmentFamily*>(l);
2755
2756             p_sys->families.push_back(*uid);
2757
2758             msg_Dbg( p_demux, "|   |   + family=%d", *(uint32*)uid->GetBuffer() );
2759         }
2760 #if defined( HAVE_GMTIME_R ) && !defined( SYS_DARWIN )
2761         else if( MKV_IS_ID( l, KaxDateUTC ) )
2762         {
2763             KaxDateUTC &date = *(KaxDateUTC*)l;
2764             time_t i_date;
2765             struct tm tmres;
2766             char   buffer[256];
2767
2768             i_date = date.GetEpochDate();
2769             memset( buffer, 0, 256 );
2770             if( gmtime_r( &i_date, &tmres ) &&
2771                 asctime_r( &tmres, buffer ) )
2772             {
2773                 buffer[strlen( buffer)-1]= '\0';
2774                 p_sys->psz_date_utc = strdup( buffer );
2775                 msg_Dbg( p_demux, "|   |   + Date=%s", p_sys->psz_date_utc );
2776             }
2777         }
2778 #endif
2779         else
2780         {
2781             msg_Dbg( p_demux, "|   |   + Unknown (%s)", typeid(*l).name() );
2782         }
2783     }
2784
2785     p_sys->f_duration *= p_sys->i_timescale / 1000000.0;
2786 }
2787
2788
2789 /*****************************************************************************
2790  * ParseChapterAtom
2791  *****************************************************************************/
2792 static void ParseChapterAtom( demux_t *p_demux, int i_level, EbmlMaster *ca, chapter_item_t & chapters )
2793 {
2794     demux_sys_t *p_sys = p_demux->p_sys;
2795     unsigned int i;
2796
2797     if( p_sys->title == NULL )
2798     {
2799         p_sys->title = vlc_input_title_New();
2800     }
2801
2802     msg_Dbg( p_demux, "|   |   |   + ChapterAtom (level=%d)", i_level );
2803     for( i = 0; i < ca->ListSize(); i++ )
2804     {
2805         EbmlElement *l = (*ca)[i];
2806
2807         if( MKV_IS_ID( l, KaxChapterUID ) )
2808         {
2809             chapters.i_uid = uint64_t(*(KaxChapterUID*)l);
2810             msg_Dbg( p_demux, "|   |   |   |   + ChapterUID: %lld", chapters.i_uid );
2811         }
2812         else if( MKV_IS_ID( l, KaxChapterFlagHidden ) )
2813         {
2814             KaxChapterFlagHidden &flag =*(KaxChapterFlagHidden*)l;
2815             chapters.b_display_seekpoint = uint8( flag ) == 0;
2816
2817             msg_Dbg( p_demux, "|   |   |   |   + ChapterFlagHidden: %s", chapters.b_display_seekpoint ? "no":"yes" );
2818         }
2819         else if( MKV_IS_ID( l, KaxChapterTimeStart ) )
2820         {
2821             KaxChapterTimeStart &start =*(KaxChapterTimeStart*)l;
2822             chapters.i_start_time = uint64( start ) / I64C(1000);
2823
2824             msg_Dbg( p_demux, "|   |   |   |   + ChapterTimeStart: %lld", chapters.i_start_time );
2825         }
2826         else if( MKV_IS_ID( l, KaxChapterTimeEnd ) )
2827         {
2828             KaxChapterTimeEnd &end =*(KaxChapterTimeEnd*)l;
2829             chapters.i_end_time = uint64( end ) / I64C(1000);
2830
2831             msg_Dbg( p_demux, "|   |   |   |   + ChapterTimeEnd: %lld", chapters.i_end_time );
2832         }
2833         else if( MKV_IS_ID( l, KaxChapterDisplay ) )
2834         {
2835             EbmlMaster *cd = static_cast<EbmlMaster *>(l);
2836             unsigned int j;
2837
2838             msg_Dbg( p_demux, "|   |   |   |   + ChapterDisplay" );
2839             for( j = 0; j < cd->ListSize(); j++ )
2840             {
2841                 EbmlElement *l= (*cd)[j];
2842
2843                 if( MKV_IS_ID( l, KaxChapterString ) )
2844                 {
2845                     int k;
2846
2847                     KaxChapterString &name =*(KaxChapterString*)l;
2848                     for (k = 0; k < i_level; k++)
2849                         chapters.psz_name += '+';
2850                     chapters.psz_name += ' ';
2851                     chapters.psz_name += UTF8ToStr( UTFstring( name ) );
2852
2853                     msg_Dbg( p_demux, "|   |   |   |   |    + ChapterString '%s'", UTF8ToStr(UTFstring(name)) );
2854                 }
2855                 else if( MKV_IS_ID( l, KaxChapterLanguage ) )
2856                 {
2857                     KaxChapterLanguage &lang =*(KaxChapterLanguage*)l;
2858                     const char *psz = string( lang ).c_str();
2859
2860                     msg_Dbg( p_demux, "|   |   |   |   |    + ChapterLanguage '%s'", psz );
2861                 }
2862                 else if( MKV_IS_ID( l, KaxChapterCountry ) )
2863                 {
2864                     KaxChapterCountry &ct =*(KaxChapterCountry*)l;
2865                     const char *psz = string( ct ).c_str();
2866
2867                     msg_Dbg( p_demux, "|   |   |   |   |    + ChapterCountry '%s'", psz );
2868                 }
2869             }
2870         }
2871         else if( MKV_IS_ID( l, KaxChapterAtom ) )
2872         {
2873             chapter_item_t new_sub_chapter;
2874             ParseChapterAtom( p_demux, i_level+1, static_cast<EbmlMaster *>(l), new_sub_chapter );
2875             new_sub_chapter.psz_parent = &chapters;
2876             chapters.sub_chapters.push_back( new_sub_chapter );
2877         }
2878     }
2879 }
2880
2881 /*****************************************************************************
2882  * ParseChapters:
2883  *****************************************************************************/
2884 static void ParseChapters( demux_t *p_demux, EbmlElement *chapters )
2885 {
2886     demux_sys_t *p_sys = p_demux->p_sys;
2887     EbmlElement *el;
2888     EbmlMaster  *m;
2889     unsigned int i;
2890     int i_upper_level = 0;
2891     int i_default_edition = 0;
2892     float f_duration;
2893
2894     /* Master elements */
2895     m = static_cast<EbmlMaster *>(chapters);
2896     m->Read( *p_sys->es, chapters->Generic().Context, i_upper_level, el, true );
2897
2898     for( i = 0; i < m->ListSize(); i++ )
2899     {
2900         EbmlElement *l = (*m)[i];
2901
2902         if( MKV_IS_ID( l, KaxEditionEntry ) )
2903         {
2904             chapter_edition_t edition;
2905             
2906             EbmlMaster *E = static_cast<EbmlMaster *>(l );
2907             unsigned int j;
2908             msg_Dbg( p_demux, "|   |   + EditionEntry" );
2909             for( j = 0; j < E->ListSize(); j++ )
2910             {
2911                 EbmlElement *l = (*E)[j];
2912
2913                 if( MKV_IS_ID( l, KaxChapterAtom ) )
2914                 {
2915                     chapter_item_t new_sub_chapter;
2916                     ParseChapterAtom( p_demux, 0, static_cast<EbmlMaster *>(l), new_sub_chapter );
2917                     edition.chapters.push_back( new_sub_chapter );
2918                 }
2919                 else if( MKV_IS_ID( l, KaxEditionUID ) )
2920                 {
2921                     edition.i_uid = uint64(*static_cast<KaxEditionUID *>( l ));
2922                 }
2923                 else if( MKV_IS_ID( l, KaxEditionFlagOrdered ) )
2924                 {
2925                     edition.b_ordered = uint8(*static_cast<KaxEditionFlagOrdered *>( l )) != 0;
2926                 }
2927                 else if( MKV_IS_ID( l, KaxEditionFlagDefault ) )
2928                 {
2929                     if (uint8(*static_cast<KaxEditionFlagDefault *>( l )) != 0)
2930                         i_default_edition = p_sys->editions.size();
2931                 }
2932                 else
2933                 {
2934                     msg_Dbg( p_demux, "|   |   |   + Unknown (%s)", typeid(*l).name() );
2935                 }
2936             }
2937             p_sys->editions.push_back( edition );
2938         }
2939         else
2940         {
2941             msg_Dbg( p_demux, "|   |   + Unknown (%s)", typeid(*l).name() );
2942         }
2943     }
2944
2945     for( i = 0; i < p_sys->editions.size(); i++ )
2946     {
2947         p_sys->editions[i].RefreshChapters( *p_sys->title );
2948     }
2949     
2950     p_sys->i_current_edition = i_default_edition;
2951     
2952     if ( p_sys->editions[i_default_edition].b_ordered )
2953     {
2954         /* update the duration of the segment according to the sum of all sub chapters */
2955         f_duration = p_sys->editions[i_default_edition].Duration() / I64C(1000);
2956         if (f_duration > 0.0)
2957             p_sys->f_duration = f_duration;
2958     }
2959 }
2960
2961 /*****************************************************************************
2962  * InformationCreate:
2963  *****************************************************************************/
2964 static void InformationCreate( demux_t *p_demux )
2965 {
2966     demux_sys_t *p_sys = p_demux->p_sys;
2967     int         i_track;
2968
2969     p_sys->meta = vlc_meta_New();
2970
2971     if( p_sys->psz_title )
2972     {
2973         vlc_meta_Add( p_sys->meta, VLC_META_TITLE, p_sys->psz_title );
2974     }
2975     if( p_sys->psz_date_utc )
2976     {
2977         vlc_meta_Add( p_sys->meta, VLC_META_DATE, p_sys->psz_date_utc );
2978     }
2979     if( p_sys->psz_segment_filename )
2980     {
2981         vlc_meta_Add( p_sys->meta, _("Segment filename"), p_sys->psz_segment_filename );
2982     }
2983     if( p_sys->psz_muxing_application )
2984     {
2985         vlc_meta_Add( p_sys->meta, _("Muxing application"), p_sys->psz_muxing_application );
2986     }
2987     if( p_sys->psz_writing_application )
2988     {
2989         vlc_meta_Add( p_sys->meta, _("Writing application"), p_sys->psz_writing_application );
2990     }
2991
2992     for( i_track = 0; i_track < p_sys->i_track; i_track++ )
2993     {
2994         mkv_track_t *tk = &p_sys->track[i_track];
2995         vlc_meta_t *mtk = vlc_meta_New();
2996
2997         p_sys->meta->track = (vlc_meta_t**)realloc( p_sys->meta->track,
2998                                                     sizeof( vlc_meta_t * ) * ( p_sys->meta->i_track + 1 ) );
2999         p_sys->meta->track[p_sys->meta->i_track++] = mtk;
3000
3001         if( tk->fmt.psz_description )
3002         {
3003             vlc_meta_Add( p_sys->meta, VLC_META_DESCRIPTION, tk->fmt.psz_description );
3004         }
3005         if( tk->psz_codec_name )
3006         {
3007             vlc_meta_Add( p_sys->meta, VLC_META_CODEC_NAME, tk->psz_codec_name );
3008         }
3009         if( tk->psz_codec_settings )
3010         {
3011             vlc_meta_Add( p_sys->meta, VLC_META_SETTING, tk->psz_codec_settings );
3012         }
3013         if( tk->psz_codec_info_url )
3014         {
3015             vlc_meta_Add( p_sys->meta, VLC_META_CODEC_DESCRIPTION, tk->psz_codec_info_url );
3016         }
3017         if( tk->psz_codec_download_url )
3018         {
3019             vlc_meta_Add( p_sys->meta, VLC_META_URL, tk->psz_codec_download_url );
3020         }
3021     }
3022
3023     if( p_sys->i_tags_position >= 0 )
3024     {
3025         vlc_bool_t b_seekable;
3026
3027         stream_Control( p_demux->s, STREAM_CAN_FASTSEEK, &b_seekable );
3028         if( b_seekable )
3029         {
3030             LoadTags( p_demux );
3031         }
3032     }
3033 }
3034
3035
3036 /*****************************************************************************
3037  * Divers
3038  *****************************************************************************/
3039
3040 static void IndexAppendCluster( demux_t *p_demux, KaxCluster *cluster )
3041 {
3042     demux_sys_t *p_sys = p_demux->p_sys;
3043
3044 #define idx p_sys->index[p_sys->i_index]
3045     idx.i_track       = -1;
3046     idx.i_block_number= -1;
3047     idx.i_position    = cluster->GetElementPosition();
3048     idx.i_time        = -1;
3049     idx.b_key         = VLC_TRUE;
3050
3051     p_sys->i_index++;
3052     if( p_sys->i_index >= p_sys->i_index_max )
3053     {
3054         p_sys->i_index_max += 1024;
3055         p_sys->index = (mkv_index_t*)realloc( p_sys->index, sizeof( mkv_index_t ) * p_sys->i_index_max );
3056     }
3057 #undef idx
3058 }
3059
3060 static char * UTF8ToStr( const UTFstring &u )
3061 {
3062     int     i_src;
3063     const wchar_t *src;
3064     char *dst, *p;
3065
3066     i_src = u.length();
3067     src   = u.c_str();
3068
3069     p = dst = (char*)malloc( i_src + 1);
3070     while( i_src > 0 )
3071     {
3072         if( *src < 255 )
3073         {
3074             *p++ = (char)*src;
3075         }
3076         else
3077         {
3078             *p++ = '?';
3079         }
3080         src++;
3081         i_src--;
3082     }
3083     *p++= '\0';
3084
3085     return dst;
3086 }
3087
3088 void chapter_edition_t::RefreshChapters( input_title_t & title )
3089 {
3090     int64_t i_prev_user_time = 0;
3091     std::vector<chapter_item_t>::iterator index = chapters.begin();
3092
3093     while ( index != chapters.end() )
3094     {
3095         i_prev_user_time = (*index).RefreshChapters( b_ordered, i_prev_user_time, title );
3096         index++;
3097     }
3098 }
3099
3100 int64_t chapter_item_t::RefreshChapters( bool b_ordered, int64_t i_prev_user_time, input_title_t & title )
3101 {
3102     int64_t i_user_time = i_prev_user_time;
3103     
3104     // first the sub-chapters, and then ourself
3105     std::vector<chapter_item_t>::iterator index = sub_chapters.begin();
3106     while ( index != sub_chapters.end() )
3107     {
3108         i_user_time = (*index).RefreshChapters( b_ordered, i_user_time, title );
3109         index++;
3110     }
3111
3112     if ( b_ordered )
3113     {
3114         i_user_start_time = i_prev_user_time;
3115         if ( i_end_time != -1 && i_user_time == i_prev_user_time )
3116         {
3117             i_user_end_time = i_user_start_time - i_start_time + i_end_time;
3118         }
3119         else
3120         {
3121             i_user_end_time = i_user_time;
3122         }
3123     }
3124     else
3125     {
3126         std::sort( sub_chapters.begin(), sub_chapters.end() );
3127         i_user_start_time = i_start_time;
3128         i_user_end_time = i_end_time;
3129     }
3130
3131     if (b_display_seekpoint)
3132     {
3133         seekpoint_t *sk = vlc_seekpoint_New();
3134
3135 //        sk->i_level = i_level;
3136         sk->i_time_offset = i_start_time;
3137         sk->psz_name = strdup( psz_name.c_str() );
3138
3139         // A start time of '0' is ok. A missing ChapterTime element is ok, too, because '0' is its default value.
3140         title.i_seekpoint++;
3141         title.seekpoint = (seekpoint_t**)realloc( title.seekpoint, title.i_seekpoint * sizeof( seekpoint_t* ) );
3142         title.seekpoint[title.i_seekpoint-1] = sk;
3143     }
3144
3145     i_seekpoint_num = title.i_seekpoint;
3146
3147     return i_user_end_time;
3148 }
3149
3150 double chapter_edition_t::Duration() const
3151 {
3152     double f_result = 0.0;
3153     
3154     if ( chapters.size() )
3155     {
3156         std::vector<chapter_item_t>::const_iterator index = chapters.end();
3157         index--;
3158         f_result = (*index).i_user_end_time;
3159     }
3160     
3161     return f_result;
3162 }
3163
3164 const chapter_item_t *chapter_item_t::FindTimecode( mtime_t i_user_timecode ) const
3165 {
3166     const chapter_item_t *psz_result = NULL;
3167
3168     if (i_user_timecode >= i_user_start_time && i_user_timecode < i_user_end_time)
3169     {
3170         std::vector<chapter_item_t>::const_iterator index = sub_chapters.begin();
3171         while ( index != sub_chapters.end() && psz_result == NULL )
3172         {
3173             psz_result = (*index).FindTimecode( i_user_timecode );
3174             index++;
3175         }
3176         
3177         if ( psz_result == NULL )
3178             psz_result = this;
3179     }
3180
3181     return psz_result;
3182 }
3183
3184 const chapter_item_t *chapter_edition_t::FindTimecode( mtime_t i_user_timecode ) const
3185 {
3186     const chapter_item_t *psz_result = NULL;
3187
3188     std::vector<chapter_item_t>::const_iterator index = chapters.begin();
3189     while ( index != chapters.end() && psz_result == NULL )
3190     {
3191         psz_result = (*index).FindTimecode( i_user_timecode );
3192         index++;
3193     }
3194
3195     return psz_result;
3196 }