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