mkv.cpp: update the seekpoint location after a manual seek
[vlc.git] / 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(false)
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
1134     vlc_meta_t **pp_meta;
1135
1136     switch( i_query )
1137     {
1138         case DEMUX_GET_META:
1139             pp_meta = (vlc_meta_t**)va_arg( args, vlc_meta_t** );
1140             *pp_meta = vlc_meta_Duplicate( p_sys->meta );
1141             return VLC_SUCCESS;
1142
1143         case DEMUX_GET_LENGTH:
1144             pi64 = (int64_t*)va_arg( args, int64_t * );
1145             if( p_sys->f_duration > 0.0 )
1146             {
1147                 *pi64 = (int64_t)(p_sys->f_duration * 1000);
1148                 return VLC_SUCCESS;
1149             }
1150             return VLC_EGENERIC;
1151
1152         case DEMUX_GET_POSITION:
1153             pf = (double*)va_arg( args, double * );
1154 /*            if (p_sys->i_pts < p_sys->i_start_pts)
1155                 *pf = (double)p_sys->i_start_pts / (1000.0 * p_sys->f_duration);
1156             else*/
1157                 *pf = (double)p_sys->i_pts / (1000.0 * p_sys->f_duration);
1158             return VLC_SUCCESS;
1159
1160         case DEMUX_SET_POSITION:
1161             f = (double)va_arg( args, double );
1162             Seek( p_demux, -1, f, NULL );
1163             return VLC_SUCCESS;
1164
1165         case DEMUX_GET_TIME:
1166             pi64 = (int64_t*)va_arg( args, int64_t * );
1167 /*            if (p_sys->i_pts < p_sys->i_start_pts)
1168                 *pi64 = p_sys->i_start_pts;
1169             else*/
1170                 *pi64 = p_sys->i_pts;
1171             return VLC_SUCCESS;
1172
1173         case DEMUX_GET_TITLE_INFO:
1174             if( p_sys->title && p_sys->title->i_seekpoint > 0 )
1175             {
1176                 input_title_t ***ppp_title = (input_title_t***)va_arg( args, input_title_t*** );
1177                 int *pi_int    = (int*)va_arg( args, int* );
1178
1179                 *pi_int = 1;
1180                 *ppp_title = (input_title_t**)malloc( sizeof( input_title_t**) );
1181
1182                 (*ppp_title)[0] = vlc_input_title_Duplicate( p_sys->title );
1183
1184                 return VLC_SUCCESS;
1185             }
1186             return VLC_EGENERIC;
1187
1188         case DEMUX_SET_TITLE:
1189             /* TODO handle editions as titles & DVD titles as well */
1190             if( p_sys->title && p_sys->title->i_seekpoint > 0 )
1191             {
1192                 return VLC_SUCCESS;
1193             }
1194             return VLC_EGENERIC;
1195
1196         case DEMUX_SET_SEEKPOINT:
1197             /* FIXME do a better implementation */
1198             i_skp = (int)va_arg( args, int );
1199
1200             if( p_sys->title && i_skp < p_sys->title->i_seekpoint)
1201             {
1202                 Seek( p_demux, (int64_t)p_sys->title->seekpoint[i_skp]->i_time_offset, -1, NULL);
1203                 p_demux->info.i_seekpoint |= INPUT_UPDATE_SEEKPOINT;
1204                 p_demux->info.i_seekpoint = i_skp;
1205                 return VLC_SUCCESS;
1206             }
1207             return VLC_EGENERIC;
1208
1209
1210         case DEMUX_SET_TIME:
1211         case DEMUX_GET_FPS:
1212         default:
1213             return VLC_EGENERIC;
1214     }
1215 }
1216
1217 static int BlockGet( demux_t *p_demux, KaxBlock **pp_block, int64_t *pi_ref1, int64_t *pi_ref2, int64_t *pi_duration )
1218 {
1219     demux_sys_t *p_sys = p_demux->p_sys;
1220
1221     *pp_block = NULL;
1222     *pi_ref1  = -1;
1223     *pi_ref2  = -1;
1224
1225     for( ;; )
1226     {
1227         EbmlElement *el;
1228         int         i_level;
1229
1230         if( p_demux->b_die )
1231         {
1232             return VLC_EGENERIC;
1233         }
1234
1235         el = p_sys->ep->Get();
1236         i_level = p_sys->ep->GetLevel();
1237
1238         if( el == NULL && *pp_block != NULL )
1239         {
1240             /* update the index */
1241 #define idx p_sys->index[p_sys->i_index - 1]
1242             if( p_sys->i_index > 0 && idx.i_time == -1 )
1243             {
1244                 idx.i_time        = (*pp_block)->GlobalTimecode() / (mtime_t)1000;
1245                 idx.b_key         = *pi_ref1 == -1 ? VLC_TRUE : VLC_FALSE;
1246             }
1247 #undef idx
1248             return VLC_SUCCESS;
1249         }
1250
1251         if( el == NULL )
1252         {
1253             if( p_sys->ep->GetLevel() > 1 )
1254             {
1255                 p_sys->ep->Up();
1256                 continue;
1257             }
1258             msg_Warn( p_demux, "EOF" );
1259             return VLC_EGENERIC;
1260         }
1261
1262         /* do parsing */
1263         if( i_level == 1 )
1264         {
1265             if( MKV_IS_ID( el, KaxCluster ) )
1266             {
1267                 p_sys->cluster = (KaxCluster*)el;
1268
1269                 /* add it to the index */
1270                 if( p_sys->i_index == 0 ||
1271                     ( p_sys->i_index > 0 && p_sys->index[p_sys->i_index - 1].i_position < (int64_t)p_sys->cluster->GetElementPosition() ) )
1272                 {
1273                     IndexAppendCluster( p_demux, p_sys->cluster );
1274                 }
1275
1276                 p_sys->ep->Down();
1277             }
1278             else if( MKV_IS_ID( el, KaxCues ) )
1279             {
1280                 msg_Warn( p_demux, "find KaxCues FIXME" );
1281                 return VLC_EGENERIC;
1282             }
1283             else
1284             {
1285                 msg_Dbg( p_demux, "unknown (%s)", typeid( el ).name() );
1286             }
1287         }
1288         else if( i_level == 2 )
1289         {
1290             if( MKV_IS_ID( el, KaxClusterTimecode ) )
1291             {
1292                 KaxClusterTimecode &ctc = *(KaxClusterTimecode*)el;
1293
1294                 ctc.ReadData( p_sys->es->I_O(), SCOPE_ALL_DATA );
1295                 p_sys->cluster->InitTimecode( uint64( ctc ), p_sys->i_timescale );
1296             }
1297             else if( MKV_IS_ID( el, KaxBlockGroup ) )
1298             {
1299                 p_sys->ep->Down();
1300             }
1301         }
1302         else if( i_level == 3 )
1303         {
1304             if( MKV_IS_ID( el, KaxBlock ) )
1305             {
1306                 *pp_block = (KaxBlock*)el;
1307
1308                 (*pp_block)->ReadData( p_sys->es->I_O() );
1309                 (*pp_block)->SetParent( *p_sys->cluster );
1310
1311                 p_sys->ep->Keep();
1312             }
1313             else if( MKV_IS_ID( el, KaxBlockDuration ) )
1314             {
1315                 KaxBlockDuration &dur = *(KaxBlockDuration*)el;
1316
1317                 dur.ReadData( p_sys->es->I_O() );
1318                 *pi_duration = uint64( dur );
1319             }
1320             else if( MKV_IS_ID( el, KaxReferenceBlock ) )
1321             {
1322                 KaxReferenceBlock &ref = *(KaxReferenceBlock*)el;
1323
1324                 ref.ReadData( p_sys->es->I_O() );
1325                 if( *pi_ref1 == -1 )
1326                 {
1327                     *pi_ref1 = int64( ref );
1328                 }
1329                 else
1330                 {
1331                     *pi_ref2 = int64( ref );
1332                 }
1333             }
1334         }
1335         else
1336         {
1337             msg_Err( p_demux, "invalid level = %d", i_level );
1338             return VLC_EGENERIC;
1339         }
1340     }
1341 }
1342
1343 static block_t *MemToBlock( demux_t *p_demux, uint8_t *p_mem, int i_mem)
1344 {
1345     block_t *p_block;
1346     if( !(p_block = block_New( p_demux, i_mem ) ) ) return NULL;
1347     memcpy( p_block->p_buffer, p_mem, i_mem );
1348     //p_block->i_rate = p_input->stream.control.i_rate;
1349     return p_block;
1350 }
1351
1352 static void BlockDecode( demux_t *p_demux, KaxBlock *block, mtime_t i_pts,
1353                          mtime_t i_duration )
1354 {
1355     demux_sys_t *p_sys = p_demux->p_sys;
1356
1357     int             i_track;
1358     unsigned int    i;
1359     vlc_bool_t      b;
1360
1361 #define tk  p_sys->track[i_track]
1362     for( i_track = 0; i_track < p_sys->i_track; i_track++ )
1363     {
1364         if( tk.i_number == block->TrackNum() )
1365         {
1366             break;
1367         }
1368     }
1369
1370     if( i_track >= p_sys->i_track )
1371     {
1372         msg_Err( p_demux, "invalid track number=%d", block->TrackNum() );
1373         return;
1374     }
1375     if( tk.p_es == NULL )
1376     {
1377         msg_Err( p_demux, "unknown track number=%d", block->TrackNum() );
1378         return;
1379     }
1380     if( i_pts < p_sys->i_start_pts && tk.fmt.i_cat == AUDIO_ES )
1381     {
1382         return; /* discard audio packets that shouldn't be rendered */
1383     }
1384
1385     es_out_Control( p_demux->out, ES_OUT_GET_ES_STATE, tk.p_es, &b );
1386     if( !b )
1387     {
1388         tk.b_inited = VLC_FALSE;
1389         return;
1390     }
1391
1392     /* First send init data */
1393     if( !tk.b_inited && tk.i_data_init > 0 )
1394     {
1395         block_t *p_init;
1396
1397         msg_Dbg( p_demux, "sending header (%d bytes)", tk.i_data_init );
1398         p_init = MemToBlock( p_demux, tk.p_data_init, tk.i_data_init );
1399         if( p_init ) es_out_Send( p_demux->out, tk.p_es, p_init );
1400     }
1401     tk.b_inited = VLC_TRUE;
1402
1403
1404     for( i = 0; i < block->NumberFrames(); i++ )
1405     {
1406         block_t *p_block;
1407         DataBuffer &data = block->GetBuffer(i);
1408
1409         p_block = MemToBlock( p_demux, data.Buffer(), data.Size() );
1410
1411         if( p_block == NULL )
1412         {
1413             break;
1414         }
1415
1416 #if defined(HAVE_ZLIB_H)
1417         if( tk.i_compression_type )
1418         {
1419             p_block = block_zlib_decompress( VLC_OBJECT(p_demux), p_block );
1420         }
1421 #endif
1422
1423         if( tk.fmt.i_cat != VIDEO_ES )
1424         {
1425             p_block->i_dts = p_block->i_pts = i_pts;
1426         }
1427         else
1428         {
1429             p_block->i_pts = i_pts;
1430             p_block->i_dts = 0;
1431         }
1432
1433         if( tk.fmt.i_cat == SPU_ES && strcmp( tk.psz_codec, "S_VOBSUB" ) )
1434         {
1435             p_block->i_length = i_duration * 1000;
1436         }
1437         es_out_Send( p_demux->out, tk.p_es, p_block );
1438
1439         /* use time stamp only for first block */
1440         i_pts = 0;
1441     }
1442
1443 #undef tk
1444 }
1445
1446 static void UpdateCurrentToChapter( demux_t & demux )
1447 {
1448     demux_sys_t & sys = *demux.p_sys;
1449     const chapter_item_t *psz_curr_chapter;
1450
1451     /* update current chapter/seekpoint */
1452     if ( sys.editions.size())
1453     {
1454         /* 1st, we need to know in which chapter we are */
1455         psz_curr_chapter = sys.editions[sys.i_current_edition].FindTimecode( sys.i_pts );
1456
1457         /* we have moved to a new chapter */
1458         if (sys.psz_current_chapter != NULL && psz_curr_chapter != NULL && sys.psz_current_chapter != psz_curr_chapter)
1459         {
1460             if (sys.psz_current_chapter->i_seekpoint_num != psz_curr_chapter->i_seekpoint_num && psz_curr_chapter->i_seekpoint_num > 0)
1461             {
1462                 demux.info.i_update |= INPUT_UPDATE_SEEKPOINT;
1463                 demux.info.i_seekpoint = psz_curr_chapter->i_seekpoint_num - 1;
1464             }
1465
1466             if (sys.editions[sys.i_current_edition].b_ordered )
1467             {
1468                 /* TODO check if we need to silently seek to a new location in the stream (switch to another chapter) */
1469                 if (sys.psz_current_chapter->i_end_time != psz_curr_chapter->i_start_time)
1470                     Seek(&demux, sys.i_pts, -1, psz_curr_chapter);
1471                 /* count the last duration time found for each track in a table (-1 not found, -2 silent) */
1472                 /* only seek after each duration >= end timecode of the current chapter */
1473             }
1474
1475 //            sys.i_user_time = psz_curr_chapter->i_user_start_time - psz_curr_chapter->i_start_time;
1476 //            sys.i_start_pts = psz_curr_chapter->i_user_start_time;
1477         }
1478         sys.psz_current_chapter = psz_curr_chapter;
1479     }
1480 }
1481
1482 static void Seek( demux_t *p_demux, mtime_t i_date, double f_percent, const chapter_item_t *psz_chapter)
1483 {
1484     demux_sys_t *p_sys = p_demux->p_sys;
1485     mtime_t i_time_offset = 0;
1486
1487     KaxBlock    *block;
1488     int64_t     i_block_duration;
1489     int64_t     i_block_ref1;
1490     int64_t     i_block_ref2;
1491
1492     int         i_index = 0;
1493     int         i_track_skipping;
1494     int         i_track;
1495
1496     msg_Dbg( p_demux, "seek request to "I64Fd" (%f%%)", i_date, f_percent );
1497     if( i_date < 0 && f_percent < 0 )
1498     {
1499         msg_Warn( p_demux, "cannot seek nowhere !" );
1500         return;
1501     }
1502     if( f_percent > 1.0 )
1503     {
1504         msg_Warn( p_demux, "cannot seek so far !" );
1505         return;
1506     }
1507
1508     delete p_sys->ep;
1509     p_sys->ep = new EbmlParser( p_sys->es, p_sys->segment );
1510     p_sys->cluster = NULL;
1511
1512     /* seek without index or without date */
1513     if( f_percent >= 0 && (config_GetInt( p_demux, "mkv-seek-percent" ) || !p_sys->b_cues || i_date < 0 ))
1514     {
1515         if (p_sys->f_duration >= 0)
1516         {
1517             i_date = int64_t( f_percent * p_sys->f_duration * 1000.0 );
1518         }
1519         else
1520         {
1521             int64_t i_pos = int64_t( f_percent * stream_Size( p_demux->s ) );
1522
1523             msg_Dbg( p_demux, "inacurate way of seeking" );
1524             for( i_index = 0; i_index < p_sys->i_index; i_index++ )
1525             {
1526                 if( p_sys->index[i_index].i_position >= i_pos)
1527                 {
1528                     break;
1529                 }
1530             }
1531             if( i_index == p_sys->i_index )
1532             {
1533                 i_index--;
1534             }
1535
1536             i_date = p_sys->index[i_index].i_time;
1537
1538 #if 0
1539             if( p_sys->index[i_index].i_position < i_pos )
1540             {
1541                 EbmlElement *el;
1542
1543                 msg_Warn( p_demux, "searching for cluster, could take some time" );
1544
1545                 /* search a cluster */
1546                 while( ( el = p_sys->ep->Get() ) != NULL )
1547                 {
1548                     if( MKV_IS_ID( el, KaxCluster ) )
1549                     {
1550                         KaxCluster *cluster = (KaxCluster*)el;
1551
1552                         /* add it to the index */
1553                         IndexAppendCluster( p_demux, cluster );
1554
1555                         if( (int64_t)cluster->GetElementPosition() >= i_pos )
1556                         {
1557                             p_sys->cluster = cluster;
1558                             p_sys->ep->Down();
1559                             break;
1560                         }
1561                     }
1562                 }
1563             }
1564 #endif
1565         }
1566     }
1567
1568     // find the actual time for an ordered edition
1569     if ( psz_chapter == NULL )
1570     {
1571         if ( p_sys->editions.size() && p_sys->editions[p_sys->i_current_edition].b_ordered )
1572         {
1573             /* 1st, we need to know in which chapter we are */
1574             psz_chapter = p_sys->editions[p_sys->i_current_edition].FindTimecode( i_date );
1575         }
1576     }
1577
1578     if ( psz_chapter != NULL )
1579     {
1580         p_sys->psz_current_chapter = psz_chapter;
1581         p_sys->i_chapter_time = i_time_offset = psz_chapter->i_user_start_time - psz_chapter->i_start_time;
1582         p_demux->info.i_update |= INPUT_UPDATE_SEEKPOINT;
1583         p_demux->info.i_seekpoint = psz_chapter->i_seekpoint_num - 1;
1584     }
1585
1586     for( ; i_index < p_sys->i_index; i_index++ )
1587     {
1588         if( p_sys->index[i_index].i_time + i_time_offset > i_date )
1589         {
1590             break;
1591         }
1592     }
1593
1594     if( i_index > 0 )
1595     {
1596         i_index--;
1597     }
1598
1599     msg_Dbg( p_demux, "seek got "I64Fd" (%d%%)",
1600                 p_sys->index[i_index].i_time,
1601                 (int)( 100 * p_sys->index[i_index].i_position /
1602                     stream_Size( p_demux->s ) ) );
1603
1604     p_sys->in->setFilePointer( p_sys->index[i_index].i_position,
1605                                 seek_beginning );
1606
1607     p_sys->i_start_pts = i_date;
1608
1609     es_out_Control( p_demux->out, ES_OUT_RESET_PCR );
1610
1611     /* now parse until key frame */
1612 #define tk  p_sys->track[i_track]
1613     i_track_skipping = 0;
1614     for( i_track = 0; i_track < p_sys->i_track; i_track++ )
1615     {
1616         if( tk.fmt.i_cat == VIDEO_ES )
1617         {
1618             tk.b_search_keyframe = VLC_TRUE;
1619             i_track_skipping++;
1620         }
1621         es_out_Control( p_demux->out, ES_OUT_SET_NEXT_DISPLAY_TIME, tk.p_es, i_date );
1622     }
1623
1624
1625     while( i_track_skipping > 0 )
1626     {
1627         if( BlockGet( p_demux, &block, &i_block_ref1, &i_block_ref2, &i_block_duration ) )
1628         {
1629             msg_Warn( p_demux, "cannot get block EOF?" );
1630
1631             return;
1632         }
1633
1634         for( i_track = 0; i_track < p_sys->i_track; i_track++ )
1635         {
1636             if( tk.i_number == block->TrackNum() )
1637             {
1638                 break;
1639             }
1640         }
1641
1642         p_sys->i_pts = p_sys->i_chapter_time + block->GlobalTimecode() / (mtime_t) 1000;
1643
1644         if( i_track < p_sys->i_track )
1645         {
1646             if( tk.fmt.i_cat == VIDEO_ES )
1647             {
1648                 if( i_block_ref1 == -1 && tk.b_search_keyframe )
1649                 {
1650                     tk.b_search_keyframe = VLC_FALSE;
1651                     i_track_skipping--;
1652                 }
1653                 if( !tk.b_search_keyframe )
1654                 {
1655                     BlockDecode( p_demux, block, p_sys->i_pts, 0 );
1656                 }
1657             }
1658         }
1659
1660         delete block;
1661     }
1662 #undef tk
1663 }
1664
1665 /*****************************************************************************
1666  * Demux: reads and demuxes data packets
1667  *****************************************************************************
1668  * Returns -1 in case of error, 0 in case of EOF, 1 otherwise
1669  *****************************************************************************/
1670 static int Demux( demux_t *p_demux)
1671 {
1672     demux_sys_t *p_sys = p_demux->p_sys;
1673     int            i_block_count = 0;
1674
1675     KaxBlock *block;
1676     int64_t i_block_duration;
1677     int64_t i_block_ref1;
1678     int64_t i_block_ref2;
1679
1680     for( ;; )
1681     {
1682         if( p_sys->i_pts >= p_sys->i_start_pts  )
1683             UpdateCurrentToChapter( *p_demux );
1684         
1685         if ( p_sys->editions.size() && p_sys->editions[p_sys->i_current_edition].b_ordered && p_sys->psz_current_chapter == NULL )
1686         {
1687             /* nothing left to read in this ordered edition */
1688             return 0;
1689         }
1690
1691         if( BlockGet( p_demux, &block, &i_block_ref1, &i_block_ref2, &i_block_duration ) )
1692         {
1693             if ( p_sys->editions.size() && p_sys->editions[p_sys->i_current_edition].b_ordered )
1694             {
1695                 // check if there are more chapters to read
1696                 if ( p_sys->psz_current_chapter != NULL )
1697                 {
1698                     p_sys->i_pts = p_sys->psz_current_chapter->i_user_end_time;
1699                     return 1;
1700                 }
1701
1702                 return 0;
1703             }
1704             msg_Warn( p_demux, "cannot get block EOF?" );
1705
1706             return 0;
1707         }
1708
1709         p_sys->i_pts = p_sys->i_chapter_time + block->GlobalTimecode() / (mtime_t) 1000;
1710
1711         if( p_sys->i_pts >= p_sys->i_start_pts  )
1712         {
1713             es_out_Control( p_demux->out, ES_OUT_SET_PCR, p_sys->i_pts );
1714         }
1715
1716         BlockDecode( p_demux, block, p_sys->i_pts, i_block_duration );
1717
1718         delete block;
1719         i_block_count++;
1720
1721         // TODO optimize when there is need to leave or when seeking has been called
1722         if( i_block_count > 5 )
1723         {
1724             return 1;
1725         }
1726     }
1727 }
1728
1729
1730
1731 /*****************************************************************************
1732  * Stream managment
1733  *****************************************************************************/
1734 vlc_stream_io_callback::vlc_stream_io_callback( stream_t *s_ )
1735 {
1736     s = s_;
1737     mb_eof = VLC_FALSE;
1738 }
1739
1740 uint32 vlc_stream_io_callback::read( void *p_buffer, size_t i_size )
1741 {
1742     if( i_size <= 0 || mb_eof )
1743     {
1744         return 0;
1745     }
1746
1747     return stream_Read( s, p_buffer, i_size );
1748 }
1749 void vlc_stream_io_callback::setFilePointer(int64_t i_offset, seek_mode mode )
1750 {
1751     int64_t i_pos;
1752
1753     switch( mode )
1754     {
1755         case seek_beginning:
1756             i_pos = i_offset;
1757             break;
1758         case seek_end:
1759             i_pos = stream_Size( s ) - i_offset;
1760             break;
1761         default:
1762             i_pos= stream_Tell( s ) + i_offset;
1763             break;
1764     }
1765
1766     if( i_pos < 0 || i_pos >= stream_Size( s ) )
1767     {
1768         mb_eof = VLC_TRUE;
1769         return;
1770     }
1771
1772     mb_eof = VLC_FALSE;
1773     if( stream_Seek( s, i_pos ) )
1774     {
1775         mb_eof = VLC_TRUE;
1776     }
1777     return;
1778 }
1779 size_t vlc_stream_io_callback::write( const void *p_buffer, size_t i_size )
1780 {
1781     return 0;
1782 }
1783 uint64 vlc_stream_io_callback::getFilePointer( void )
1784 {
1785     return stream_Tell( s );
1786 }
1787 void vlc_stream_io_callback::close( void )
1788 {
1789     return;
1790 }
1791
1792
1793 /*****************************************************************************
1794  * Ebml Stream parser
1795  *****************************************************************************/
1796 EbmlParser::EbmlParser( EbmlStream *es, EbmlElement *el_start )
1797 {
1798     int i;
1799
1800     m_es = es;
1801     m_got = NULL;
1802     m_el[0] = el_start;
1803
1804     for( i = 1; i < 6; i++ )
1805     {
1806         m_el[i] = NULL;
1807     }
1808     mi_level = 1;
1809     mi_user_level = 1;
1810     mb_keep = VLC_FALSE;
1811 }
1812
1813 EbmlParser::~EbmlParser( void )
1814 {
1815     int i;
1816
1817     for( i = 1; i < mi_level; i++ )
1818     {
1819         if( !mb_keep )
1820         {
1821             delete m_el[i];
1822         }
1823         mb_keep = VLC_FALSE;
1824     }
1825 }
1826
1827 void EbmlParser::Up( void )
1828 {
1829     if( mi_user_level == mi_level )
1830     {
1831         fprintf( stderr," arrrrrrrrrrrrrg Up cannot escape itself\n" );
1832     }
1833
1834     mi_user_level--;
1835 }
1836
1837 void EbmlParser::Down( void )
1838 {
1839     mi_user_level++;
1840     mi_level++;
1841 }
1842
1843 void EbmlParser::Keep( void )
1844 {
1845     mb_keep = VLC_TRUE;
1846 }
1847
1848 int EbmlParser::GetLevel( void )
1849 {
1850     return mi_user_level;
1851 }
1852
1853 EbmlElement *EbmlParser::Get( void )
1854 {
1855     int i_ulev = 0;
1856
1857     if( mi_user_level != mi_level )
1858     {
1859         return NULL;
1860     }
1861     if( m_got )
1862     {
1863         EbmlElement *ret = m_got;
1864         m_got = NULL;
1865
1866         return ret;
1867     }
1868
1869     if( m_el[mi_level] )
1870     {
1871         m_el[mi_level]->SkipData( *m_es, m_el[mi_level]->Generic().Context );
1872         if( !mb_keep )
1873         {
1874             delete m_el[mi_level];
1875         }
1876         mb_keep = VLC_FALSE;
1877     }
1878
1879     m_el[mi_level] = m_es->FindNextElement( m_el[mi_level - 1]->Generic().Context, i_ulev, 0xFFFFFFFFL, true, 1 );
1880     if( i_ulev > 0 )
1881     {
1882         while( i_ulev > 0 )
1883         {
1884             if( mi_level == 1 )
1885             {
1886                 mi_level = 0;
1887                 return NULL;
1888             }
1889
1890             delete m_el[mi_level - 1];
1891             m_got = m_el[mi_level -1] = m_el[mi_level];
1892             m_el[mi_level] = NULL;
1893
1894             mi_level--;
1895             i_ulev--;
1896         }
1897         return NULL;
1898     }
1899     else if( m_el[mi_level] == NULL )
1900     {
1901         fprintf( stderr," m_el[mi_level] == NULL\n" );
1902     }
1903
1904     return m_el[mi_level];
1905 }
1906
1907
1908 /*****************************************************************************
1909  * Tools
1910  *  * LoadCues : load the cues element and update index
1911  *
1912  *  * LoadTags : load ... the tags element
1913  *
1914  *  * InformationCreate : create all information, load tags if present
1915  *
1916  *****************************************************************************/
1917 static void LoadCues( demux_t *p_demux )
1918 {
1919     demux_sys_t *p_sys = p_demux->p_sys;
1920     int64_t     i_sav_position = p_sys->in->getFilePointer();
1921     EbmlParser  *ep;
1922     EbmlElement *el, *cues;
1923
1924     msg_Dbg( p_demux, "loading cues" );
1925     p_sys->in->setFilePointer( p_sys->i_cues_position, seek_beginning );
1926     cues = p_sys->es->FindNextID( KaxCues::ClassInfos, 0xFFFFFFFFL);
1927
1928     if( cues == NULL )
1929     {
1930         msg_Err( p_demux, "cannot load cues (broken seekhead or file)" );
1931         p_sys->in->setFilePointer( i_sav_position, seek_beginning );
1932         return;
1933     }
1934
1935     ep = new EbmlParser( p_sys->es, cues );
1936     while( ( el = ep->Get() ) != NULL )
1937     {
1938         if( MKV_IS_ID( el, KaxCuePoint ) )
1939         {
1940 #define idx p_sys->index[p_sys->i_index]
1941
1942             idx.i_track       = -1;
1943             idx.i_block_number= -1;
1944             idx.i_position    = -1;
1945             idx.i_time        = 0;
1946             idx.b_key         = VLC_TRUE;
1947
1948             ep->Down();
1949             while( ( el = ep->Get() ) != NULL )
1950             {
1951                 if( MKV_IS_ID( el, KaxCueTime ) )
1952                 {
1953                     KaxCueTime &ctime = *(KaxCueTime*)el;
1954
1955                     ctime.ReadData( p_sys->es->I_O() );
1956
1957                     idx.i_time = uint64( ctime ) * p_sys->i_timescale / (mtime_t)1000;
1958                 }
1959                 else if( MKV_IS_ID( el, KaxCueTrackPositions ) )
1960                 {
1961                     ep->Down();
1962                     while( ( el = ep->Get() ) != NULL )
1963                     {
1964                         if( MKV_IS_ID( el, KaxCueTrack ) )
1965                         {
1966                             KaxCueTrack &ctrack = *(KaxCueTrack*)el;
1967
1968                             ctrack.ReadData( p_sys->es->I_O() );
1969                             idx.i_track = uint16( ctrack );
1970                         }
1971                         else if( MKV_IS_ID( el, KaxCueClusterPosition ) )
1972                         {
1973                             KaxCueClusterPosition &ccpos = *(KaxCueClusterPosition*)el;
1974
1975                             ccpos.ReadData( p_sys->es->I_O() );
1976                             idx.i_position = p_sys->segment->GetGlobalPosition( uint64( ccpos ) );
1977                         }
1978                         else if( MKV_IS_ID( el, KaxCueBlockNumber ) )
1979                         {
1980                             KaxCueBlockNumber &cbnum = *(KaxCueBlockNumber*)el;
1981
1982                             cbnum.ReadData( p_sys->es->I_O() );
1983                             idx.i_block_number = uint32( cbnum );
1984                         }
1985                         else
1986                         {
1987                             msg_Dbg( p_demux, "         * Unknown (%s)", typeid(*el).name() );
1988                         }
1989                     }
1990                     ep->Up();
1991                 }
1992                 else
1993                 {
1994                     msg_Dbg( p_demux, "     * Unknown (%s)", typeid(*el).name() );
1995                 }
1996             }
1997             ep->Up();
1998
1999 #if 0
2000             msg_Dbg( p_demux, " * added time="I64Fd" pos="I64Fd
2001                      " track=%d bnum=%d", idx.i_time, idx.i_position,
2002                      idx.i_track, idx.i_block_number );
2003 #endif
2004
2005             p_sys->i_index++;
2006             if( p_sys->i_index >= p_sys->i_index_max )
2007             {
2008                 p_sys->i_index_max += 1024;
2009                 p_sys->index = (mkv_index_t*)realloc( p_sys->index, sizeof( mkv_index_t ) * p_sys->i_index_max );
2010             }
2011 #undef idx
2012         }
2013         else
2014         {
2015             msg_Dbg( p_demux, " * Unknown (%s)", typeid(*el).name() );
2016         }
2017     }
2018     delete ep;
2019     delete cues;
2020
2021     p_sys->b_cues = VLC_TRUE;
2022
2023     msg_Dbg( p_demux, "loading cues done." );
2024     p_sys->in->setFilePointer( i_sav_position, seek_beginning );
2025 }
2026
2027 static void LoadTags( demux_t *p_demux )
2028 {
2029     demux_sys_t *p_sys = p_demux->p_sys;
2030     int64_t     i_sav_position = p_sys->in->getFilePointer();
2031     EbmlParser  *ep;
2032     EbmlElement *el, *tags;
2033
2034     msg_Dbg( p_demux, "loading tags" );
2035     p_sys->in->setFilePointer( p_sys->i_tags_position, seek_beginning );
2036     tags = p_sys->es->FindNextID( KaxTags::ClassInfos, 0xFFFFFFFFL);
2037
2038     if( tags == NULL )
2039     {
2040         msg_Err( p_demux, "cannot load tags (broken seekhead or file)" );
2041         p_sys->in->setFilePointer( i_sav_position, seek_beginning );
2042         return;
2043     }
2044
2045     msg_Dbg( p_demux, "Tags" );
2046     ep = new EbmlParser( p_sys->es, tags );
2047     while( ( el = ep->Get() ) != NULL )
2048     {
2049         if( MKV_IS_ID( el, KaxTag ) )
2050         {
2051             msg_Dbg( p_demux, "+ Tag" );
2052             ep->Down();
2053             while( ( el = ep->Get() ) != NULL )
2054             {
2055                 if( MKV_IS_ID( el, KaxTagTargets ) )
2056                 {
2057                     msg_Dbg( p_demux, "|   + Targets" );
2058                     ep->Down();
2059                     while( ( el = ep->Get() ) != NULL )
2060                     {
2061                         msg_Dbg( p_demux, "|   |   + Unknown (%s)", typeid( *el ).name() );
2062                     }
2063                     ep->Up();
2064                 }
2065                 else if( MKV_IS_ID( el, KaxTagGeneral ) )
2066                 {
2067                     msg_Dbg( p_demux, "|   + General" );
2068                     ep->Down();
2069                     while( ( el = ep->Get() ) != NULL )
2070                     {
2071                         msg_Dbg( p_demux, "|   |   + Unknown (%s)", typeid( *el ).name() );
2072                     }
2073                     ep->Up();
2074                 }
2075                 else if( MKV_IS_ID( el, KaxTagGenres ) )
2076                 {
2077                     msg_Dbg( p_demux, "|   + Genres" );
2078                     ep->Down();
2079                     while( ( el = ep->Get() ) != NULL )
2080                     {
2081                         msg_Dbg( p_demux, "|   |   + Unknown (%s)", typeid( *el ).name() );
2082                     }
2083                     ep->Up();
2084                 }
2085                 else if( MKV_IS_ID( el, KaxTagAudioSpecific ) )
2086                 {
2087                     msg_Dbg( p_demux, "|   + Audio Specific" );
2088                     ep->Down();
2089                     while( ( el = ep->Get() ) != NULL )
2090                     {
2091                         msg_Dbg( p_demux, "|   |   + Unknown (%s)", typeid( *el ).name() );
2092                     }
2093                     ep->Up();
2094                 }
2095                 else if( MKV_IS_ID( el, KaxTagImageSpecific ) )
2096                 {
2097                     msg_Dbg( p_demux, "|   + Images Specific" );
2098                     ep->Down();
2099                     while( ( el = ep->Get() ) != NULL )
2100                     {
2101                         msg_Dbg( p_demux, "|   |   + Unknown (%s)", typeid( *el ).name() );
2102                     }
2103                     ep->Up();
2104                 }
2105                 else if( MKV_IS_ID( el, KaxTagMultiComment ) )
2106                 {
2107                     msg_Dbg( p_demux, "|   + Multi Comment" );
2108                 }
2109                 else if( MKV_IS_ID( el, KaxTagMultiCommercial ) )
2110                 {
2111                     msg_Dbg( p_demux, "|   + Multi Commercial" );
2112                 }
2113                 else if( MKV_IS_ID( el, KaxTagMultiDate ) )
2114                 {
2115                     msg_Dbg( p_demux, "|   + Multi Date" );
2116                 }
2117                 else if( MKV_IS_ID( el, KaxTagMultiEntity ) )
2118                 {
2119                     msg_Dbg( p_demux, "|   + Multi Entity" );
2120                 }
2121                 else if( MKV_IS_ID( el, KaxTagMultiIdentifier ) )
2122                 {
2123                     msg_Dbg( p_demux, "|   + Multi Identifier" );
2124                 }
2125                 else if( MKV_IS_ID( el, KaxTagMultiLegal ) )
2126                 {
2127                     msg_Dbg( p_demux, "|   + Multi Legal" );
2128                 }
2129                 else if( MKV_IS_ID( el, KaxTagMultiTitle ) )
2130                 {
2131                     msg_Dbg( p_demux, "|   + Multi Title" );
2132                 }
2133                 else
2134                 {
2135                     msg_Dbg( p_demux, "|   + Unknown (%s)", typeid( *el ).name() );
2136                 }
2137             }
2138             ep->Up();
2139         }
2140         else
2141         {
2142             msg_Dbg( p_demux, "+ Unknown (%s)", typeid( *el ).name() );
2143         }
2144     }
2145     delete ep;
2146     delete tags;
2147
2148     msg_Dbg( p_demux, "loading tags done." );
2149     p_sys->in->setFilePointer( i_sav_position, seek_beginning );
2150 }
2151
2152 /*****************************************************************************
2153  * ParseInfo:
2154  *****************************************************************************/
2155 static void ParseSeekHead( demux_t *p_demux, EbmlElement *seekhead )
2156 {
2157     demux_sys_t *p_sys = p_demux->p_sys;
2158     EbmlElement *el;
2159     EbmlMaster  *m;
2160     unsigned int i;
2161     int i_upper_level = 0;
2162
2163     msg_Dbg( p_demux, "|   + Seek head" );
2164
2165     /* Master elements */
2166     m = static_cast<EbmlMaster *>(seekhead);
2167     m->Read( *p_sys->es, seekhead->Generic().Context, i_upper_level, el, true );
2168
2169     for( i = 0; i < m->ListSize(); i++ )
2170     {
2171         EbmlElement *l = (*m)[i];
2172
2173         if( MKV_IS_ID( l, KaxSeek ) )
2174         {
2175             EbmlMaster *sk = static_cast<EbmlMaster *>(l);
2176             EbmlId id = EbmlVoid::ClassInfos.GlobalId;
2177             int64_t i_pos = -1;
2178
2179             unsigned int j;
2180
2181             for( j = 0; j < sk->ListSize(); j++ )
2182             {
2183                 EbmlElement *l = (*sk)[j];
2184
2185                 if( MKV_IS_ID( l, KaxSeekID ) )
2186                 {
2187                     KaxSeekID &sid = *(KaxSeekID*)l;
2188                     id = EbmlId( sid.GetBuffer(), sid.GetSize() );
2189                 }
2190                 else if( MKV_IS_ID( l, KaxSeekPosition ) )
2191                 {
2192                     KaxSeekPosition &spos = *(KaxSeekPosition*)l;
2193                     i_pos = uint64( spos );
2194                 }
2195                 else
2196                 {
2197                     msg_Dbg( p_demux, "|   |   |   + Unknown (%s)", typeid(*l).name() );
2198                 }
2199             }
2200
2201             if( i_pos >= 0 )
2202             {
2203                 if( id == KaxCues::ClassInfos.GlobalId )
2204                 {
2205                     msg_Dbg( p_demux, "|   |   |   = cues at "I64Fd, i_pos );
2206                     p_sys->i_cues_position = p_sys->segment->GetGlobalPosition( i_pos );
2207                 }
2208                 else if( id == KaxChapters::ClassInfos.GlobalId )
2209                 {
2210                     msg_Dbg( p_demux, "|   |   |   = chapters at "I64Fd, i_pos );
2211                     p_sys->i_chapters_position = p_sys->segment->GetGlobalPosition( i_pos );
2212                 }
2213                 else if( id == KaxTags::ClassInfos.GlobalId )
2214                 {
2215                     msg_Dbg( p_demux, "|   |   |   = tags at "I64Fd, i_pos );
2216                     p_sys->i_tags_position = p_sys->segment->GetGlobalPosition( i_pos );
2217                 }
2218             }
2219         }
2220         else
2221         {
2222             msg_Dbg( p_demux, "|   |   + Unknown (%s)", typeid(*l).name() );
2223         }
2224     }
2225 }
2226
2227 /*****************************************************************************
2228  * ParseTracks:
2229  *****************************************************************************/
2230 static void ParseTrackEntry( demux_t *p_demux, EbmlMaster *m )
2231 {
2232     demux_sys_t *p_sys = p_demux->p_sys;
2233     unsigned int i;
2234
2235     mkv_track_t *tk;
2236
2237     msg_Dbg( p_demux, "|   |   + Track Entry" );
2238
2239     p_sys->i_track++;
2240     p_sys->track = (mkv_track_t*)realloc( p_sys->track, sizeof( mkv_track_t ) * (p_sys->i_track + 1 ) );
2241
2242     /* Init the track */
2243     tk = &p_sys->track[p_sys->i_track - 1];
2244
2245     memset( tk, 0, sizeof( mkv_track_t ) );
2246
2247     es_format_Init( &tk->fmt, UNKNOWN_ES, 0 );
2248     tk->fmt.psz_language = strdup("English");
2249     tk->fmt.psz_description = NULL;
2250
2251     tk->b_default = VLC_TRUE;
2252     tk->b_enabled = VLC_TRUE;
2253     tk->i_number = p_sys->i_track - 1;
2254     tk->i_extra_data = 0;
2255     tk->p_extra_data = NULL;
2256     tk->psz_codec = NULL;
2257     tk->i_default_duration = 0;
2258     tk->f_timecodescale = 1.0;
2259
2260     tk->b_inited = VLC_FALSE;
2261     tk->i_data_init = 0;
2262     tk->p_data_init = NULL;
2263
2264     tk->psz_codec_name = NULL;
2265     tk->psz_codec_settings = NULL;
2266     tk->psz_codec_info_url = NULL;
2267     tk->psz_codec_download_url = NULL;
2268     
2269     tk->i_compression_type = MATROSKA_COMPRESSION_NONE;
2270
2271     for( i = 0; i < m->ListSize(); i++ )
2272     {
2273         EbmlElement *l = (*m)[i];
2274
2275         if( MKV_IS_ID( l, KaxTrackNumber ) )
2276         {
2277             KaxTrackNumber &tnum = *(KaxTrackNumber*)l;
2278
2279             tk->i_number = uint32( tnum );
2280             msg_Dbg( p_demux, "|   |   |   + Track Number=%u", uint32( tnum ) );
2281         }
2282         else  if( MKV_IS_ID( l, KaxTrackUID ) )
2283         {
2284             KaxTrackUID &tuid = *(KaxTrackUID*)l;
2285
2286             msg_Dbg( p_demux, "|   |   |   + Track UID=%u",  uint32( tuid ) );
2287         }
2288         else  if( MKV_IS_ID( l, KaxTrackType ) )
2289         {
2290             char *psz_type;
2291             KaxTrackType &ttype = *(KaxTrackType*)l;
2292
2293             switch( uint8(ttype) )
2294             {
2295                 case track_audio:
2296                     psz_type = "audio";
2297                     tk->fmt.i_cat = AUDIO_ES;
2298                     break;
2299                 case track_video:
2300                     psz_type = "video";
2301                     tk->fmt.i_cat = VIDEO_ES;
2302                     break;
2303                 case track_subtitle:
2304                     psz_type = "subtitle";
2305                     tk->fmt.i_cat = SPU_ES;
2306                     break;
2307                 default:
2308                     psz_type = "unknown";
2309                     tk->fmt.i_cat = UNKNOWN_ES;
2310                     break;
2311             }
2312
2313             msg_Dbg( p_demux, "|   |   |   + Track Type=%s", psz_type );
2314         }
2315 //        else  if( EbmlId( *l ) == KaxTrackFlagEnabled::ClassInfos.GlobalId )
2316 //        {
2317 //            KaxTrackFlagEnabled &fenb = *(KaxTrackFlagEnabled*)l;
2318
2319 //            tk->b_enabled = uint32( fenb );
2320 //            msg_Dbg( p_demux, "|   |   |   + Track Enabled=%u",
2321 //                     uint32( fenb )  );
2322 //        }
2323         else  if( MKV_IS_ID( l, KaxTrackFlagDefault ) )
2324         {
2325             KaxTrackFlagDefault &fdef = *(KaxTrackFlagDefault*)l;
2326
2327             tk->b_default = uint32( fdef );
2328             msg_Dbg( p_demux, "|   |   |   + Track Default=%u", uint32( fdef )  );
2329         }
2330         else  if( MKV_IS_ID( l, KaxTrackFlagLacing ) )
2331         {
2332             KaxTrackFlagLacing &lac = *(KaxTrackFlagLacing*)l;
2333
2334             msg_Dbg( p_demux, "|   |   |   + Track Lacing=%d", uint32( lac ) );
2335         }
2336         else  if( MKV_IS_ID( l, KaxTrackMinCache ) )
2337         {
2338             KaxTrackMinCache &cmin = *(KaxTrackMinCache*)l;
2339
2340             msg_Dbg( p_demux, "|   |   |   + Track MinCache=%d", uint32( cmin ) );
2341         }
2342         else  if( MKV_IS_ID( l, KaxTrackMaxCache ) )
2343         {
2344             KaxTrackMaxCache &cmax = *(KaxTrackMaxCache*)l;
2345
2346             msg_Dbg( p_demux, "|   |   |   + Track MaxCache=%d", uint32( cmax ) );
2347         }
2348         else  if( MKV_IS_ID( l, KaxTrackDefaultDuration ) )
2349         {
2350             KaxTrackDefaultDuration &defd = *(KaxTrackDefaultDuration*)l;
2351
2352             tk->i_default_duration = uint64(defd);
2353             msg_Dbg( p_demux, "|   |   |   + Track Default Duration="I64Fd, uint64(defd) );
2354         }
2355         else  if( MKV_IS_ID( l, KaxTrackTimecodeScale ) )
2356         {
2357             KaxTrackTimecodeScale &ttcs = *(KaxTrackTimecodeScale*)l;
2358
2359             tk->f_timecodescale = float( ttcs );
2360             msg_Dbg( p_demux, "|   |   |   + Track TimeCodeScale=%f", tk->f_timecodescale );
2361         }
2362         else if( MKV_IS_ID( l, KaxTrackName ) )
2363         {
2364             KaxTrackName &tname = *(KaxTrackName*)l;
2365
2366             tk->fmt.psz_description = UTF8ToStr( UTFstring( tname ) );
2367             msg_Dbg( p_demux, "|   |   |   + Track Name=%s", tk->fmt.psz_description );
2368         }
2369         else  if( MKV_IS_ID( l, KaxTrackLanguage ) )
2370         {
2371             KaxTrackLanguage &lang = *(KaxTrackLanguage*)l;
2372
2373             tk->fmt.psz_language = strdup( string( lang ).c_str() );
2374             msg_Dbg( p_demux,
2375                      "|   |   |   + Track Language=`%s'", tk->fmt.psz_language );
2376         }
2377         else  if( MKV_IS_ID( l, KaxCodecID ) )
2378         {
2379             KaxCodecID &codecid = *(KaxCodecID*)l;
2380
2381             tk->psz_codec = strdup( string( codecid ).c_str() );
2382             msg_Dbg( p_demux, "|   |   |   + Track CodecId=%s", string( codecid ).c_str() );
2383         }
2384         else  if( MKV_IS_ID( l, KaxCodecPrivate ) )
2385         {
2386             KaxCodecPrivate &cpriv = *(KaxCodecPrivate*)l;
2387
2388             tk->i_extra_data = cpriv.GetSize();
2389             if( tk->i_extra_data > 0 )
2390             {
2391                 tk->p_extra_data = (uint8_t*)malloc( tk->i_extra_data );
2392                 memcpy( tk->p_extra_data, cpriv.GetBuffer(), tk->i_extra_data );
2393             }
2394             msg_Dbg( p_demux, "|   |   |   + Track CodecPrivate size="I64Fd, cpriv.GetSize() );
2395         }
2396         else if( MKV_IS_ID( l, KaxCodecName ) )
2397         {
2398             KaxCodecName &cname = *(KaxCodecName*)l;
2399
2400             tk->psz_codec_name = UTF8ToStr( UTFstring( cname ) );
2401             msg_Dbg( p_demux, "|   |   |   + Track Codec Name=%s", tk->psz_codec_name );
2402         }
2403         else if( MKV_IS_ID( l, KaxContentEncodings ) )
2404         {
2405             EbmlMaster *cencs = static_cast<EbmlMaster*>(l);
2406             MkvTree( p_demux, 3, "Content Encodings" );
2407             for( unsigned int i = 0; i < cencs->ListSize(); i++ )
2408             {
2409                 EbmlElement *l2 = (*cencs)[i];
2410                 if( MKV_IS_ID( l2, KaxContentEncoding ) )
2411                 {
2412                     MkvTree( p_demux, 4, "Content Encoding" );
2413                     EbmlMaster *cenc = static_cast<EbmlMaster*>(l2);
2414                     for( unsigned int i = 0; i < cenc->ListSize(); i++ )
2415                     {
2416                         EbmlElement *l3 = (*cenc)[i];
2417                         if( MKV_IS_ID( l3, KaxContentEncodingOrder ) )
2418                         {
2419                             KaxContentEncodingOrder &encord = *(KaxContentEncodingOrder*)l3;
2420                             MkvTree( p_demux, 5, "Order: %i", uint32( encord ) );
2421                         }
2422                         else if( MKV_IS_ID( l3, KaxContentEncodingScope ) )
2423                         {
2424                             KaxContentEncodingScope &encscope = *(KaxContentEncodingScope*)l3;
2425                             MkvTree( p_demux, 5, "Scope: %i", uint32( encscope ) );
2426                         }
2427                         else if( MKV_IS_ID( l3, KaxContentEncodingType ) )
2428                         {
2429                             KaxContentEncodingType &enctype = *(KaxContentEncodingType*)l3;
2430                             MkvTree( p_demux, 5, "Type: %i", uint32( enctype ) );
2431                         }
2432                         else if( MKV_IS_ID( l3, KaxContentCompression ) )
2433                         {
2434                             EbmlMaster *compr = static_cast<EbmlMaster*>(l3);
2435                             MkvTree( p_demux, 5, "Content Compression" );
2436                             for( unsigned int i = 0; i < compr->ListSize(); i++ )
2437                             {
2438                                 EbmlElement *l4 = (*compr)[i];
2439                                 if( MKV_IS_ID( l4, KaxContentCompAlgo ) )
2440                                 {
2441                                     KaxContentCompAlgo &compalg = *(KaxContentCompAlgo*)l4;
2442                                     MkvTree( p_demux, 6, "Compression Algorithm: %i", uint32(compalg) );
2443                                     if( uint32( compalg ) == 0 )
2444                                     {
2445                                         tk->i_compression_type = MATROSKA_COMPRESSION_ZLIB;
2446                                     }
2447                                 }
2448                                 else
2449                                 {
2450                                     MkvTree( p_demux, 6, "Unknown (%s)", typeid(*l4).name() );
2451                                 }
2452                             }
2453                         }
2454
2455                         else
2456                         {
2457                             MkvTree( p_demux, 5, "Unknown (%s)", typeid(*l3).name() );
2458                         }
2459                     }
2460                     
2461                 }
2462                 else
2463                 {
2464                     MkvTree( p_demux, 4, "Unknown (%s)", typeid(*l2).name() );
2465                 }
2466             }
2467                 
2468         }
2469 //        else if( EbmlId( *l ) == KaxCodecSettings::ClassInfos.GlobalId )
2470 //        {
2471 //            KaxCodecSettings &cset = *(KaxCodecSettings*)l;
2472
2473 //            tk->psz_codec_settings = UTF8ToStr( UTFstring( cset ) );
2474 //            msg_Dbg( p_demux, "|   |   |   + Track Codec Settings=%s", tk->psz_codec_settings );
2475 //        }
2476 //        else if( EbmlId( *l ) == KaxCodecInfoURL::ClassInfos.GlobalId )
2477 //        {
2478 //            KaxCodecInfoURL &ciurl = *(KaxCodecInfoURL*)l;
2479
2480 //            tk->psz_codec_info_url = strdup( string( ciurl ).c_str() );
2481 //            msg_Dbg( p_demux, "|   |   |   + Track Codec Info URL=%s", tk->psz_codec_info_url );
2482 //        }
2483 //        else if( EbmlId( *l ) == KaxCodecDownloadURL::ClassInfos.GlobalId )
2484 //        {
2485 //            KaxCodecDownloadURL &cdurl = *(KaxCodecDownloadURL*)l;
2486
2487 //            tk->psz_codec_download_url = strdup( string( cdurl ).c_str() );
2488 //            msg_Dbg( p_demux, "|   |   |   + Track Codec Info URL=%s", tk->psz_codec_download_url );
2489 //        }
2490 //        else if( EbmlId( *l ) == KaxCodecDecodeAll::ClassInfos.GlobalId )
2491 //        {
2492 //            KaxCodecDecodeAll &cdall = *(KaxCodecDecodeAll*)l;
2493
2494 //            msg_Dbg( p_demux, "|   |   |   + Track Codec Decode All=%u <== UNUSED", uint8( cdall ) );
2495 //        }
2496 //        else if( EbmlId( *l ) == KaxTrackOverlay::ClassInfos.GlobalId )
2497 //        {
2498 //            KaxTrackOverlay &tovr = *(KaxTrackOverlay*)l;
2499
2500 //            msg_Dbg( p_demux, "|   |   |   + Track Overlay=%u <== UNUSED", uint32( tovr ) );
2501 //        }
2502         else  if( MKV_IS_ID( l, KaxTrackVideo ) )
2503         {
2504             EbmlMaster *tkv = static_cast<EbmlMaster*>(l);
2505             unsigned int j;
2506
2507             msg_Dbg( p_demux, "|   |   |   + Track Video" );
2508             tk->f_fps = 0.0;
2509
2510             for( j = 0; j < tkv->ListSize(); j++ )
2511             {
2512                 EbmlElement *l = (*tkv)[j];
2513 //                if( EbmlId( *el4 ) == KaxVideoFlagInterlaced::ClassInfos.GlobalId )
2514 //                {
2515 //                    KaxVideoFlagInterlaced &fint = *(KaxVideoFlagInterlaced*)el4;
2516
2517 //                    msg_Dbg( p_demux, "|   |   |   |   + Track Video Interlaced=%u", uint8( fint ) );
2518 //                }
2519 //                else if( EbmlId( *el4 ) == KaxVideoStereoMode::ClassInfos.GlobalId )
2520 //                {
2521 //                    KaxVideoStereoMode &stereo = *(KaxVideoStereoMode*)el4;
2522
2523 //                    msg_Dbg( p_demux, "|   |   |   |   + Track Video Stereo Mode=%u", uint8( stereo ) );
2524 //                }
2525 //                else
2526                 if( MKV_IS_ID( l, KaxVideoPixelWidth ) )
2527                 {
2528                     KaxVideoPixelWidth &vwidth = *(KaxVideoPixelWidth*)l;
2529
2530                     tk->fmt.video.i_width = uint16( vwidth );
2531                     msg_Dbg( p_demux, "|   |   |   |   + width=%d", uint16( vwidth ) );
2532                 }
2533                 else if( MKV_IS_ID( l, KaxVideoPixelHeight ) )
2534                 {
2535                     KaxVideoPixelWidth &vheight = *(KaxVideoPixelWidth*)l;
2536
2537                     tk->fmt.video.i_height = uint16( vheight );
2538                     msg_Dbg( p_demux, "|   |   |   |   + height=%d", uint16( vheight ) );
2539                 }
2540                 else if( MKV_IS_ID( l, KaxVideoDisplayWidth ) )
2541                 {
2542                     KaxVideoDisplayWidth &vwidth = *(KaxVideoDisplayWidth*)l;
2543
2544                     tk->fmt.video.i_visible_width = uint16( vwidth );
2545                     msg_Dbg( p_demux, "|   |   |   |   + display width=%d", uint16( vwidth ) );
2546                 }
2547                 else if( MKV_IS_ID( l, KaxVideoDisplayHeight ) )
2548                 {
2549                     KaxVideoDisplayWidth &vheight = *(KaxVideoDisplayWidth*)l;
2550
2551                     tk->fmt.video.i_visible_height = uint16( vheight );
2552                     msg_Dbg( p_demux, "|   |   |   |   + display height=%d", uint16( vheight ) );
2553                 }
2554                 else if( MKV_IS_ID( l, KaxVideoFrameRate ) )
2555                 {
2556                     KaxVideoFrameRate &vfps = *(KaxVideoFrameRate*)l;
2557
2558                     tk->f_fps = float( vfps );
2559                     msg_Dbg( p_demux, "   |   |   |   + fps=%f", float( vfps ) );
2560                 }
2561 //                else if( EbmlId( *l ) == KaxVideoDisplayUnit::ClassInfos.GlobalId )
2562 //                {
2563 //                     KaxVideoDisplayUnit &vdmode = *(KaxVideoDisplayUnit*)l;
2564
2565 //                    msg_Dbg( p_demux, "|   |   |   |   + Track Video Display Unit=%s",
2566 //                             uint8( vdmode ) == 0 ? "pixels" : ( uint8( vdmode ) == 1 ? "centimeters": "inches" ) );
2567 //                }
2568 //                else if( EbmlId( *l ) == KaxVideoAspectRatio::ClassInfos.GlobalId )
2569 //                {
2570 //                    KaxVideoAspectRatio &ratio = *(KaxVideoAspectRatio*)l;
2571
2572 //                    msg_Dbg( p_demux, "   |   |   |   + Track Video Aspect Ratio Type=%u", uint8( ratio ) );
2573 //                }
2574 //                else if( EbmlId( *l ) == KaxVideoGamma::ClassInfos.GlobalId )
2575 //                {
2576 //                    KaxVideoGamma &gamma = *(KaxVideoGamma*)l;
2577
2578 //                    msg_Dbg( p_demux, "   |   |   |   + fps=%f", float( gamma ) );
2579 //                }
2580                 else
2581                 {
2582                     msg_Dbg( p_demux, "|   |   |   |   + Unknown (%s)", typeid(*l).name() );
2583                 }
2584             }
2585         }
2586         else  if( MKV_IS_ID( l, KaxTrackAudio ) )
2587         {
2588             EbmlMaster *tka = static_cast<EbmlMaster*>(l);
2589             unsigned int j;
2590
2591             msg_Dbg( p_demux, "|   |   |   + Track Audio" );
2592
2593             for( j = 0; j < tka->ListSize(); j++ )
2594             {
2595                 EbmlElement *l = (*tka)[j];
2596
2597                 if( MKV_IS_ID( l, KaxAudioSamplingFreq ) )
2598                 {
2599                     KaxAudioSamplingFreq &afreq = *(KaxAudioSamplingFreq*)l;
2600
2601                     tk->fmt.audio.i_rate = (int)float( afreq );
2602                     msg_Dbg( p_demux, "|   |   |   |   + afreq=%d", tk->fmt.audio.i_rate );
2603                 }
2604                 else if( MKV_IS_ID( l, KaxAudioChannels ) )
2605                 {
2606                     KaxAudioChannels &achan = *(KaxAudioChannels*)l;
2607
2608                     tk->fmt.audio.i_channels = uint8( achan );
2609                     msg_Dbg( p_demux, "|   |   |   |   + achan=%u", uint8( achan ) );
2610                 }
2611                 else if( MKV_IS_ID( l, KaxAudioBitDepth ) )
2612                 {
2613                     KaxAudioBitDepth &abits = *(KaxAudioBitDepth*)l;
2614
2615                     tk->fmt.audio.i_bitspersample = uint8( abits );
2616                     msg_Dbg( p_demux, "|   |   |   |   + abits=%u", uint8( abits ) );
2617                 }
2618                 else
2619                 {
2620                     msg_Dbg( p_demux, "|   |   |   |   + Unknown (%s)", typeid(*l).name() );
2621                 }
2622             }
2623         }
2624         else
2625         {
2626             msg_Dbg( p_demux, "|   |   |   + Unknown (%s)",
2627                      typeid(*l).name() );
2628         }
2629     }
2630 }
2631
2632 static void ParseTracks( demux_t *p_demux, EbmlElement *tracks )
2633 {
2634     demux_sys_t *p_sys = p_demux->p_sys;
2635     EbmlElement *el;
2636     EbmlMaster  *m;
2637     unsigned int i;
2638     int i_upper_level = 0;
2639
2640     msg_Dbg( p_demux, "|   + Tracks" );
2641
2642     /* Master elements */
2643     m = static_cast<EbmlMaster *>(tracks);
2644     m->Read( *p_sys->es, tracks->Generic().Context, i_upper_level, el, true );
2645
2646     for( i = 0; i < m->ListSize(); i++ )
2647     {
2648         EbmlElement *l = (*m)[i];
2649
2650         if( MKV_IS_ID( l, KaxTrackEntry ) )
2651         {
2652             ParseTrackEntry( p_demux, static_cast<EbmlMaster *>(l) );
2653         }
2654         else
2655         {
2656             msg_Dbg( p_demux, "|   |   + Unknown (%s)", typeid(*l).name() );
2657         }
2658     }
2659 }
2660
2661 /*****************************************************************************
2662  * ParseInfo:
2663  *****************************************************************************/
2664 static void ParseInfo( demux_t *p_demux, EbmlElement *info )
2665 {
2666     demux_sys_t *p_sys = p_demux->p_sys;
2667     EbmlElement *el;
2668     EbmlMaster  *m;
2669     unsigned int i;
2670     int i_upper_level = 0;
2671
2672     msg_Dbg( p_demux, "|   + Information" );
2673
2674     /* Master elements */
2675     m = static_cast<EbmlMaster *>(info);
2676     m->Read( *p_sys->es, info->Generic().Context, i_upper_level, el, true );
2677
2678     for( i = 0; i < m->ListSize(); i++ )
2679     {
2680         EbmlElement *l = (*m)[i];
2681
2682         if( MKV_IS_ID( l, KaxSegmentUID ) )
2683         {
2684             p_sys->segment_uid = *(new KaxSegmentUID(*static_cast<KaxSegmentUID*>(l)));
2685
2686             msg_Dbg( p_demux, "|   |   + UID=%d", *(uint32*)p_sys->segment_uid.GetBuffer() );
2687         }
2688         else if( MKV_IS_ID( l, KaxTimecodeScale ) )
2689         {
2690             KaxTimecodeScale &tcs = *(KaxTimecodeScale*)l;
2691
2692             p_sys->i_timescale = uint64(tcs);
2693
2694             msg_Dbg( p_demux, "|   |   + TimecodeScale="I64Fd,
2695                      p_sys->i_timescale );
2696         }
2697         else if( MKV_IS_ID( l, KaxDuration ) )
2698         {
2699             KaxDuration &dur = *(KaxDuration*)l;
2700
2701             p_sys->f_duration = float(dur);
2702
2703             msg_Dbg( p_demux, "|   |   + Duration=%f",
2704                      p_sys->f_duration );
2705         }
2706         else if( MKV_IS_ID( l, KaxMuxingApp ) )
2707         {
2708             KaxMuxingApp &mapp = *(KaxMuxingApp*)l;
2709
2710             p_sys->psz_muxing_application = UTF8ToStr( UTFstring( mapp ) );
2711
2712             msg_Dbg( p_demux, "|   |   + Muxing Application=%s",
2713                      p_sys->psz_muxing_application );
2714         }
2715         else if( MKV_IS_ID( l, KaxWritingApp ) )
2716         {
2717             KaxWritingApp &wapp = *(KaxWritingApp*)l;
2718
2719             p_sys->psz_writing_application = UTF8ToStr( UTFstring( wapp ) );
2720
2721             msg_Dbg( p_demux, "|   |   + Writing Application=%s",
2722                      p_sys->psz_writing_application );
2723         }
2724         else if( MKV_IS_ID( l, KaxSegmentFilename ) )
2725         {
2726             KaxSegmentFilename &sfn = *(KaxSegmentFilename*)l;
2727
2728             p_sys->psz_segment_filename = UTF8ToStr( UTFstring( sfn ) );
2729
2730             msg_Dbg( p_demux, "|   |   + Segment Filename=%s",
2731                      p_sys->psz_segment_filename );
2732         }
2733         else if( MKV_IS_ID( l, KaxTitle ) )
2734         {
2735             KaxTitle &title = *(KaxTitle*)l;
2736
2737             p_sys->psz_title = UTF8ToStr( UTFstring( title ) );
2738
2739             msg_Dbg( p_demux, "|   |   + Title=%s", p_sys->psz_title );
2740         }
2741         if( MKV_IS_ID( l, KaxSegmentFamily ) )
2742         {
2743             KaxSegmentFamily *uid = static_cast<KaxSegmentFamily*>(l);
2744
2745             p_sys->families.push_back(*uid);
2746
2747             msg_Dbg( p_demux, "|   |   + family=%d", *(uint32*)uid->GetBuffer() );
2748         }
2749 #if defined( HAVE_GMTIME_R ) && !defined( SYS_DARWIN )
2750         else if( MKV_IS_ID( l, KaxDateUTC ) )
2751         {
2752             KaxDateUTC &date = *(KaxDateUTC*)l;
2753             time_t i_date;
2754             struct tm tmres;
2755             char   buffer[256];
2756
2757             i_date = date.GetEpochDate();
2758             memset( buffer, 0, 256 );
2759             if( gmtime_r( &i_date, &tmres ) &&
2760                 asctime_r( &tmres, buffer ) )
2761             {
2762                 buffer[strlen( buffer)-1]= '\0';
2763                 p_sys->psz_date_utc = strdup( buffer );
2764                 msg_Dbg( p_demux, "|   |   + Date=%s", p_sys->psz_date_utc );
2765             }
2766         }
2767 #endif
2768         else
2769         {
2770             msg_Dbg( p_demux, "|   |   + Unknown (%s)", typeid(*l).name() );
2771         }
2772     }
2773
2774     p_sys->f_duration *= p_sys->i_timescale / 1000000.0;
2775 }
2776
2777
2778 /*****************************************************************************
2779  * ParseChapterAtom
2780  *****************************************************************************/
2781 static void ParseChapterAtom( demux_t *p_demux, int i_level, EbmlMaster *ca, chapter_item_t & chapters )
2782 {
2783     demux_sys_t *p_sys = p_demux->p_sys;
2784     unsigned int i;
2785
2786     if( p_sys->title == NULL )
2787     {
2788         p_sys->title = vlc_input_title_New();
2789     }
2790
2791     msg_Dbg( p_demux, "|   |   |   + ChapterAtom (level=%d)", i_level );
2792     for( i = 0; i < ca->ListSize(); i++ )
2793     {
2794         EbmlElement *l = (*ca)[i];
2795
2796         if( MKV_IS_ID( l, KaxChapterUID ) )
2797         {
2798             chapters.i_uid = uint64_t(*(KaxChapterUID*)l);
2799             msg_Dbg( p_demux, "|   |   |   |   + ChapterUID: %lld", chapters.i_uid );
2800         }
2801         else if( MKV_IS_ID( l, KaxChapterFlagHidden ) )
2802         {
2803             KaxChapterFlagHidden &flag =*(KaxChapterFlagHidden*)l;
2804             chapters.b_display_seekpoint = uint8( flag ) == 0;
2805
2806             msg_Dbg( p_demux, "|   |   |   |   + ChapterFlagHidden: %s", chapters.b_display_seekpoint ? "no":"yes" );
2807         }
2808         else if( MKV_IS_ID( l, KaxChapterTimeStart ) )
2809         {
2810             KaxChapterTimeStart &start =*(KaxChapterTimeStart*)l;
2811             chapters.i_start_time = uint64( start ) / I64C(1000);
2812
2813             msg_Dbg( p_demux, "|   |   |   |   + ChapterTimeStart: %lld", chapters.i_start_time );
2814         }
2815         else if( MKV_IS_ID( l, KaxChapterTimeEnd ) )
2816         {
2817             KaxChapterTimeEnd &end =*(KaxChapterTimeEnd*)l;
2818             chapters.i_end_time = uint64( end ) / I64C(1000);
2819
2820             msg_Dbg( p_demux, "|   |   |   |   + ChapterTimeEnd: %lld", chapters.i_end_time );
2821         }
2822         else if( MKV_IS_ID( l, KaxChapterDisplay ) )
2823         {
2824             EbmlMaster *cd = static_cast<EbmlMaster *>(l);
2825             unsigned int j;
2826
2827             msg_Dbg( p_demux, "|   |   |   |   + ChapterDisplay" );
2828             for( j = 0; j < cd->ListSize(); j++ )
2829             {
2830                 EbmlElement *l= (*cd)[j];
2831
2832                 if( MKV_IS_ID( l, KaxChapterString ) )
2833                 {
2834                     int k;
2835
2836                     KaxChapterString &name =*(KaxChapterString*)l;
2837                     for (k = 0; k < i_level; k++)
2838                         chapters.psz_name += '+';
2839                     chapters.psz_name += ' ';
2840                     chapters.psz_name += UTF8ToStr( UTFstring( name ) );
2841
2842                     msg_Dbg( p_demux, "|   |   |   |   |    + ChapterString '%s'", UTF8ToStr(UTFstring(name)) );
2843                 }
2844                 else if( MKV_IS_ID( l, KaxChapterLanguage ) )
2845                 {
2846                     KaxChapterLanguage &lang =*(KaxChapterLanguage*)l;
2847                     const char *psz = string( lang ).c_str();
2848
2849                     msg_Dbg( p_demux, "|   |   |   |   |    + ChapterLanguage '%s'", psz );
2850                 }
2851                 else if( MKV_IS_ID( l, KaxChapterCountry ) )
2852                 {
2853                     KaxChapterCountry &ct =*(KaxChapterCountry*)l;
2854                     const char *psz = string( ct ).c_str();
2855
2856                     msg_Dbg( p_demux, "|   |   |   |   |    + ChapterCountry '%s'", psz );
2857                 }
2858             }
2859         }
2860         else if( MKV_IS_ID( l, KaxChapterAtom ) )
2861         {
2862             chapter_item_t new_sub_chapter;
2863             ParseChapterAtom( p_demux, i_level+1, static_cast<EbmlMaster *>(l), new_sub_chapter );
2864             new_sub_chapter.psz_parent = &chapters;
2865             chapters.sub_chapters.push_back( new_sub_chapter );
2866         }
2867     }
2868 }
2869
2870 /*****************************************************************************
2871  * ParseChapters:
2872  *****************************************************************************/
2873 static void ParseChapters( demux_t *p_demux, EbmlElement *chapters )
2874 {
2875     demux_sys_t *p_sys = p_demux->p_sys;
2876     EbmlElement *el;
2877     EbmlMaster  *m;
2878     unsigned int i;
2879     int i_upper_level = 0;
2880     int i_default_edition = 0;
2881     float f_duration;
2882
2883     /* Master elements */
2884     m = static_cast<EbmlMaster *>(chapters);
2885     m->Read( *p_sys->es, chapters->Generic().Context, i_upper_level, el, true );
2886
2887     for( i = 0; i < m->ListSize(); i++ )
2888     {
2889         EbmlElement *l = (*m)[i];
2890
2891         if( MKV_IS_ID( l, KaxEditionEntry ) )
2892         {
2893             chapter_edition_t edition;
2894             
2895             EbmlMaster *E = static_cast<EbmlMaster *>(l );
2896             unsigned int j;
2897             msg_Dbg( p_demux, "|   |   + EditionEntry" );
2898             for( j = 0; j < E->ListSize(); j++ )
2899             {
2900                 EbmlElement *l = (*E)[j];
2901
2902                 if( MKV_IS_ID( l, KaxChapterAtom ) )
2903                 {
2904                     chapter_item_t new_sub_chapter;
2905                     ParseChapterAtom( p_demux, 0, static_cast<EbmlMaster *>(l), new_sub_chapter );
2906                     edition.chapters.push_back( new_sub_chapter );
2907                 }
2908                 else if( MKV_IS_ID( l, KaxEditionUID ) )
2909                 {
2910                     edition.i_uid = uint64(*static_cast<KaxEditionUID *>( l ));
2911                 }
2912                 else if( MKV_IS_ID( l, KaxEditionFlagOrdered ) )
2913                 {
2914                     edition.b_ordered = uint8(*static_cast<KaxEditionFlagOrdered *>( l )) != 0;
2915                 }
2916                 else if( MKV_IS_ID( l, KaxEditionFlagDefault ) )
2917                 {
2918                     if (uint8(*static_cast<KaxEditionFlagDefault *>( l )) != 0)
2919                         i_default_edition = p_sys->editions.size();
2920                 }
2921                 else
2922                 {
2923                     msg_Dbg( p_demux, "|   |   |   + Unknown (%s)", typeid(*l).name() );
2924                 }
2925             }
2926             p_sys->editions.push_back( edition );
2927         }
2928         else
2929         {
2930             msg_Dbg( p_demux, "|   |   + Unknown (%s)", typeid(*l).name() );
2931         }
2932     }
2933
2934     for( i = 0; i < p_sys->editions.size(); i++ )
2935     {
2936         p_sys->editions[i].RefreshChapters( *p_sys->title );
2937     }
2938     
2939     p_sys->i_current_edition = i_default_edition;
2940     
2941     if ( p_sys->editions[i_default_edition].b_ordered )
2942     {
2943         /* update the duration of the segment according to the sum of all sub chapters */
2944         f_duration = p_sys->editions[i_default_edition].Duration() / I64C(1000);
2945         if (f_duration > 0.0)
2946             p_sys->f_duration = f_duration;
2947     }
2948 }
2949
2950 /*****************************************************************************
2951  * InformationCreate:
2952  *****************************************************************************/
2953 static void InformationCreate( demux_t *p_demux )
2954 {
2955     demux_sys_t *p_sys = p_demux->p_sys;
2956     int         i_track;
2957
2958     p_sys->meta = vlc_meta_New();
2959
2960     if( p_sys->psz_title )
2961     {
2962         vlc_meta_Add( p_sys->meta, VLC_META_TITLE, p_sys->psz_title );
2963     }
2964     if( p_sys->psz_date_utc )
2965     {
2966         vlc_meta_Add( p_sys->meta, VLC_META_DATE, p_sys->psz_date_utc );
2967     }
2968     if( p_sys->psz_segment_filename )
2969     {
2970         vlc_meta_Add( p_sys->meta, _("Segment filename"), p_sys->psz_segment_filename );
2971     }
2972     if( p_sys->psz_muxing_application )
2973     {
2974         vlc_meta_Add( p_sys->meta, _("Muxing application"), p_sys->psz_muxing_application );
2975     }
2976     if( p_sys->psz_writing_application )
2977     {
2978         vlc_meta_Add( p_sys->meta, _("Writing application"), p_sys->psz_writing_application );
2979     }
2980
2981     for( i_track = 0; i_track < p_sys->i_track; i_track++ )
2982     {
2983         mkv_track_t *tk = &p_sys->track[i_track];
2984         vlc_meta_t *mtk = vlc_meta_New();
2985
2986         p_sys->meta->track = (vlc_meta_t**)realloc( p_sys->meta->track,
2987                                                     sizeof( vlc_meta_t * ) * ( p_sys->meta->i_track + 1 ) );
2988         p_sys->meta->track[p_sys->meta->i_track++] = mtk;
2989
2990         if( tk->fmt.psz_description )
2991         {
2992             vlc_meta_Add( p_sys->meta, VLC_META_DESCRIPTION, tk->fmt.psz_description );
2993         }
2994         if( tk->psz_codec_name )
2995         {
2996             vlc_meta_Add( p_sys->meta, VLC_META_CODEC_NAME, tk->psz_codec_name );
2997         }
2998         if( tk->psz_codec_settings )
2999         {
3000             vlc_meta_Add( p_sys->meta, VLC_META_SETTING, tk->psz_codec_settings );
3001         }
3002         if( tk->psz_codec_info_url )
3003         {
3004             vlc_meta_Add( p_sys->meta, VLC_META_CODEC_DESCRIPTION, tk->psz_codec_info_url );
3005         }
3006         if( tk->psz_codec_download_url )
3007         {
3008             vlc_meta_Add( p_sys->meta, VLC_META_URL, tk->psz_codec_download_url );
3009         }
3010     }
3011
3012     if( p_sys->i_tags_position >= 0 )
3013     {
3014         vlc_bool_t b_seekable;
3015
3016         stream_Control( p_demux->s, STREAM_CAN_FASTSEEK, &b_seekable );
3017         if( b_seekable )
3018         {
3019             LoadTags( p_demux );
3020         }
3021     }
3022 }
3023
3024
3025 /*****************************************************************************
3026  * Divers
3027  *****************************************************************************/
3028
3029 static void IndexAppendCluster( demux_t *p_demux, KaxCluster *cluster )
3030 {
3031     demux_sys_t *p_sys = p_demux->p_sys;
3032
3033 #define idx p_sys->index[p_sys->i_index]
3034     idx.i_track       = -1;
3035     idx.i_block_number= -1;
3036     idx.i_position    = cluster->GetElementPosition();
3037     idx.i_time        = -1;
3038     idx.b_key         = VLC_TRUE;
3039
3040     p_sys->i_index++;
3041     if( p_sys->i_index >= p_sys->i_index_max )
3042     {
3043         p_sys->i_index_max += 1024;
3044         p_sys->index = (mkv_index_t*)realloc( p_sys->index, sizeof( mkv_index_t ) * p_sys->i_index_max );
3045     }
3046 #undef idx
3047 }
3048
3049 static char * UTF8ToStr( const UTFstring &u )
3050 {
3051     int     i_src;
3052     const wchar_t *src;
3053     char *dst, *p;
3054
3055     i_src = u.length();
3056     src   = u.c_str();
3057
3058     p = dst = (char*)malloc( i_src + 1);
3059     while( i_src > 0 )
3060     {
3061         if( *src < 255 )
3062         {
3063             *p++ = (char)*src;
3064         }
3065         else
3066         {
3067             *p++ = '?';
3068         }
3069         src++;
3070         i_src--;
3071     }
3072     *p++= '\0';
3073
3074     return dst;
3075 }
3076
3077 void chapter_edition_t::RefreshChapters( input_title_t & title )
3078 {
3079     int64_t i_prev_user_time = 0;
3080     std::vector<chapter_item_t>::iterator index = chapters.begin();
3081
3082     while ( index != chapters.end() )
3083     {
3084         i_prev_user_time = (*index).RefreshChapters( b_ordered, i_prev_user_time, title );
3085         index++;
3086     }
3087 }
3088
3089 int64_t chapter_item_t::RefreshChapters( bool b_ordered, int64_t i_prev_user_time, input_title_t & title )
3090 {
3091     int64_t i_user_time = i_prev_user_time;
3092     
3093     // first the sub-chapters, and then ourself
3094     std::vector<chapter_item_t>::iterator index = sub_chapters.begin();
3095     while ( index != sub_chapters.end() )
3096     {
3097         i_user_time = (*index).RefreshChapters( b_ordered, i_user_time, title );
3098         index++;
3099     }
3100
3101     if ( b_ordered )
3102     {
3103         i_user_start_time = i_prev_user_time;
3104         if ( i_end_time != -1 && i_user_time == i_prev_user_time )
3105         {
3106             i_user_end_time = i_user_start_time - i_start_time + i_end_time;
3107         }
3108         else
3109         {
3110             i_user_end_time = i_user_time;
3111         }
3112     }
3113     else
3114     {
3115         std::sort( sub_chapters.begin(), sub_chapters.end() );
3116         i_user_start_time = i_start_time;
3117         i_user_end_time = i_end_time;
3118     }
3119
3120     if (b_display_seekpoint)
3121     {
3122         seekpoint_t *sk = vlc_seekpoint_New();
3123
3124 //        sk->i_level = i_level;
3125         sk->i_time_offset = i_start_time;
3126         sk->psz_name = strdup( psz_name.c_str() );
3127
3128         // A start time of '0' is ok. A missing ChapterTime element is ok, too, because '0' is its default value.
3129         title.i_seekpoint++;
3130         title.seekpoint = (seekpoint_t**)realloc( title.seekpoint, title.i_seekpoint * sizeof( seekpoint_t* ) );
3131         title.seekpoint[title.i_seekpoint-1] = sk;
3132     }
3133
3134     i_seekpoint_num = title.i_seekpoint;
3135
3136     return i_user_end_time;
3137 }
3138
3139 double chapter_edition_t::Duration() const
3140 {
3141     double f_result = 0.0;
3142     
3143     if ( chapters.size() )
3144     {
3145         std::vector<chapter_item_t>::const_iterator index = chapters.end();
3146         index--;
3147         f_result = (*index).i_user_end_time;
3148     }
3149     
3150     return f_result;
3151 }
3152
3153 const chapter_item_t *chapter_item_t::FindTimecode( mtime_t i_user_timecode ) const
3154 {
3155     const chapter_item_t *psz_result = NULL;
3156
3157     if (i_user_timecode >= i_user_start_time && i_user_timecode < i_user_end_time)
3158     {
3159         std::vector<chapter_item_t>::const_iterator index = sub_chapters.begin();
3160         while ( index != sub_chapters.end() && psz_result == NULL )
3161         {
3162             psz_result = (*index).FindTimecode( i_user_timecode );
3163             index++;
3164         }
3165         
3166         if ( psz_result == NULL )
3167             psz_result = this;
3168     }
3169
3170     return psz_result;
3171 }
3172
3173 const chapter_item_t *chapter_edition_t::FindTimecode( mtime_t i_user_timecode ) const
3174 {
3175     const chapter_item_t *psz_result = NULL;
3176
3177     std::vector<chapter_item_t>::const_iterator index = chapters.begin();
3178     while ( index != chapters.end() && psz_result == NULL )
3179     {
3180         psz_result = (*index).FindTimecode( i_user_timecode );
3181         index++;
3182     }
3183
3184     return psz_result;
3185 }