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