]> git.sesse.net Git - vlc/blob - modules/demux/mkv.cpp
mkv.cpp: process the LinkPGCN DVD command correctly
[vlc] / modules / demux / mkv.cpp
1 /*****************************************************************************
2  * mkv.cpp : matroska demuxer
3  *****************************************************************************
4  * Copyright (C) 2003-2004 VideoLAN
5  * $Id$
6  *
7  * Authors: Laurent Aimar <fenrir@via.ecp.fr>
8  *          Steve Lhomme <steve.lhomme@free.fr>
9  *
10  * This program is free software; you can redistribute it and/or modify
11  * it under the terms of the GNU General Public License as published by
12  * the Free Software Foundation; either version 2 of the License, or
13  * (at your option) any later version.
14  *
15  * This program is distributed in the hope that it will be useful,
16  * but WITHOUT ANY WARRANTY; without even the implied warranty of
17  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
18  * GNU General Public License for more details.
19  *
20  * You should have received a copy of the GNU General Public License
21  * along with this program; if not, write to the Free Software
22  * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111, USA.
23  *****************************************************************************/
24
25 /*****************************************************************************
26  * Preamble
27  *****************************************************************************/
28 #include <stdlib.h>                                      /* malloc(), free() */
29
30 #include <vlc/vlc.h>
31
32 #ifdef HAVE_TIME_H
33 #   include <time.h>                                               /* time() */
34 #endif
35
36 #include <vlc/input.h>
37
38 #include <codecs.h>                        /* BITMAPINFOHEADER, WAVEFORMATEX */
39 #include "iso_lang.h"
40 #include "vlc_meta.h"
41
42 #include <iostream>
43 #include <cassert>
44 #include <typeinfo>
45 #include <string>
46 #include <vector>
47 #include <algorithm>
48
49 #ifdef HAVE_DIRENT_H
50 #   include <dirent.h>
51 #endif
52
53 /* libebml and matroska */
54 #include "ebml/EbmlHead.h"
55 #include "ebml/EbmlSubHead.h"
56 #include "ebml/EbmlStream.h"
57 #include "ebml/EbmlContexts.h"
58 #include "ebml/EbmlVoid.h"
59 #include "ebml/EbmlVersion.h"
60 #include "ebml/StdIOCallback.h"
61
62 #include "matroska/KaxAttachments.h"
63 #include "matroska/KaxBlock.h"
64 #include "matroska/KaxBlockData.h"
65 #include "matroska/KaxChapters.h"
66 #include "matroska/KaxCluster.h"
67 #include "matroska/KaxClusterData.h"
68 #include "matroska/KaxContexts.h"
69 #include "matroska/KaxCues.h"
70 #include "matroska/KaxCuesData.h"
71 #include "matroska/KaxInfo.h"
72 #include "matroska/KaxInfoData.h"
73 #include "matroska/KaxSeekHead.h"
74 #include "matroska/KaxSegment.h"
75 #include "matroska/KaxTag.h"
76 #include "matroska/KaxTags.h"
77 #include "matroska/KaxTagMulti.h"
78 #include "matroska/KaxTracks.h"
79 #include "matroska/KaxTrackAudio.h"
80 #include "matroska/KaxTrackVideo.h"
81 #include "matroska/KaxTrackEntryData.h"
82 #include "matroska/KaxContentEncoding.h"
83 #include "matroska/KaxVersion.h"
84
85 #include "ebml/StdIOCallback.h"
86
87 #include "vlc_keys.h"
88
89 extern "C" {
90    #include "mp4/libmp4.h"
91 }
92 #ifdef HAVE_ZLIB_H
93 #   include <zlib.h>
94 #endif
95
96 #define MATROSKA_COMPRESSION_NONE 0
97 #define MATROSKA_COMPRESSION_ZLIB 1
98
99 #define MKVD_TIMECODESCALE 1000000
100
101 ////////////////////////////////////////////////////////////////////////////////////////////////////////////////
102 #ifdef VSLHC1
103 #define DVDNAV_COMPILE
104 #include <dvdnav.h>
105 #else /* VSLHC */
106
107 #undef ATTRIBUTE_PACKED
108 #undef PRAGMA_PACK_BEGIN 
109 #undef PRAGMA_PACK_END
110
111 #if defined(__GNUC__)
112 #if __GNUC__ > 2 || (__GNUC__ == 2 && __GNUC_MINOR__ >= 95)
113 #define ATTRIBUTE_PACKED __attribute__ ((packed))
114 #define PRAGMA_PACK 0
115 #endif
116 #endif
117
118 #if !defined(ATTRIBUTE_PACKED)
119 #define ATTRIBUTE_PACKED
120 #define PRAGMA_PACK 1
121 #endif
122
123 #if PRAGMA_PACK
124 #pragma pack(1)
125 #endif
126
127 /*************************************
128 *  taken from libdvdnav / libdvdread
129 **************************************/
130
131 /**
132  * DVD Time Information.
133  */
134 typedef struct {
135   uint8_t hour;
136   uint8_t minute;
137   uint8_t second;
138   uint8_t frame_u; /* The two high bits are the frame rate. */
139 } ATTRIBUTE_PACKED dvd_time_t;
140
141 /**
142  * User Operations.
143  */
144 typedef struct {
145 #ifdef WORDS_BIGENDIAN
146   unsigned char zero                           : 7; /* 25-31 */
147   unsigned char video_pres_mode_change         : 1; /* 24 */
148   
149   unsigned char karaoke_audio_pres_mode_change : 1; /* 23 */
150   unsigned char angle_change                   : 1;
151   unsigned char subpic_stream_change           : 1;
152   unsigned char audio_stream_change            : 1;
153   unsigned char pause_on                       : 1;
154   unsigned char still_off                      : 1;
155   unsigned char button_select_or_activate      : 1;
156   unsigned char resume                         : 1; /* 16 */
157   
158   unsigned char chapter_menu_call              : 1; /* 15 */
159   unsigned char angle_menu_call                : 1;
160   unsigned char audio_menu_call                : 1;
161   unsigned char subpic_menu_call               : 1;
162   unsigned char root_menu_call                 : 1;
163   unsigned char title_menu_call                : 1;
164   unsigned char backward_scan                  : 1;
165   unsigned char forward_scan                   : 1; /* 8 */
166   
167   unsigned char next_pg_search                 : 1; /* 7 */
168   unsigned char prev_or_top_pg_search          : 1;
169   unsigned char time_or_chapter_search         : 1;
170   unsigned char go_up                          : 1;
171   unsigned char stop                           : 1;
172   unsigned char title_play                     : 1;
173   unsigned char chapter_search_or_play         : 1;
174   unsigned char title_or_time_play             : 1; /* 0 */
175 #else
176   unsigned char video_pres_mode_change         : 1; /* 24 */
177   unsigned char zero                           : 7; /* 25-31 */
178   
179   unsigned char resume                         : 1; /* 16 */
180   unsigned char button_select_or_activate      : 1;
181   unsigned char still_off                      : 1;
182   unsigned char pause_on                       : 1;
183   unsigned char audio_stream_change            : 1;
184   unsigned char subpic_stream_change           : 1;
185   unsigned char angle_change                   : 1;
186   unsigned char karaoke_audio_pres_mode_change : 1; /* 23 */
187   
188   unsigned char forward_scan                   : 1; /* 8 */
189   unsigned char backward_scan                  : 1;
190   unsigned char title_menu_call                : 1;
191   unsigned char root_menu_call                 : 1;
192   unsigned char subpic_menu_call               : 1;
193   unsigned char audio_menu_call                : 1;
194   unsigned char angle_menu_call                : 1;
195   unsigned char chapter_menu_call              : 1; /* 15 */
196   
197   unsigned char title_or_time_play             : 1; /* 0 */
198   unsigned char chapter_search_or_play         : 1;
199   unsigned char title_play                     : 1;
200   unsigned char stop                           : 1;
201   unsigned char go_up                          : 1;
202   unsigned char time_or_chapter_search         : 1;
203   unsigned char prev_or_top_pg_search          : 1;
204   unsigned char next_pg_search                 : 1; /* 7 */
205 #endif
206 } ATTRIBUTE_PACKED user_ops_t;
207
208 /**
209  * Type to store per-command data.
210  */
211 typedef struct {
212   uint8_t bytes[8];
213 } ATTRIBUTE_PACKED vm_cmd_t;
214 #define COMMAND_DATA_SIZE 8
215
216 /**
217  * PCI General Information 
218  */
219 typedef struct {
220   uint32_t nv_pck_lbn;      /**< sector address of this nav pack */
221   uint16_t vobu_cat;        /**< 'category' of vobu */
222   uint16_t zero1;           /**< reserved */
223   user_ops_t vobu_uop_ctl;  /**< UOP of vobu */
224   uint32_t vobu_s_ptm;      /**< start presentation time of vobu */
225   uint32_t vobu_e_ptm;      /**< end presentation time of vobu */
226   uint32_t vobu_se_e_ptm;   /**< end ptm of sequence end in vobu */
227   dvd_time_t e_eltm;        /**< Cell elapsed time */
228   char vobu_isrc[32];
229 } ATTRIBUTE_PACKED pci_gi_t;
230
231 /**
232  * Non Seamless Angle Information
233  */
234 typedef struct {
235   uint32_t nsml_agl_dsta[9];  /**< address of destination vobu in AGL_C#n */
236 } ATTRIBUTE_PACKED nsml_agli_t;
237
238 /** 
239  * Highlight General Information 
240  *
241  * For btngrX_dsp_ty the bits have the following meaning:
242  * 000b: normal 4/3 only buttons
243  * XX1b: wide (16/9) buttons
244  * X1Xb: letterbox buttons
245  * 1XXb: pan&scan buttons
246  */
247 typedef struct {
248   uint16_t hli_ss; /**< status, only low 2 bits 0: no buttons, 1: different 2: equal 3: eual except for button cmds */
249   uint32_t hli_s_ptm;              /**< start ptm of hli */
250   uint32_t hli_e_ptm;              /**< end ptm of hli */
251   uint32_t btn_se_e_ptm;           /**< end ptm of button select */
252 #ifdef WORDS_BIGENDIAN
253   unsigned char zero1 : 2;          /**< reserved */
254   unsigned char btngr_ns : 2;       /**< number of button groups 1, 2 or 3 with 36/18/12 buttons */
255   unsigned char zero2 : 1;          /**< reserved */
256   unsigned char btngr1_dsp_ty : 3;  /**< display type of subpic stream for button group 1 */
257   unsigned char zero3 : 1;          /**< reserved */
258   unsigned char btngr2_dsp_ty : 3;  /**< display type of subpic stream for button group 2 */
259   unsigned char zero4 : 1;          /**< reserved */
260   unsigned char btngr3_dsp_ty : 3;  /**< display type of subpic stream for button group 3 */
261 #else
262   unsigned char btngr1_dsp_ty : 3;
263   unsigned char zero2 : 1;
264   unsigned char btngr_ns : 2;
265   unsigned char zero1 : 2;
266   unsigned char btngr3_dsp_ty : 3;
267   unsigned char zero4 : 1;
268   unsigned char btngr2_dsp_ty : 3;
269   unsigned char zero3 : 1;
270 #endif
271   uint8_t btn_ofn;     /**< button offset number range 0-255 */
272   uint8_t btn_ns;      /**< number of valid buttons  <= 36/18/12 (low 6 bits) */  
273   uint8_t nsl_btn_ns;  /**< number of buttons selectable by U_BTNNi (low 6 bits)   nsl_btn_ns <= btn_ns */
274   uint8_t zero5;       /**< reserved */
275   uint8_t fosl_btnn;   /**< forcedly selected button  (low 6 bits) */
276   uint8_t foac_btnn;   /**< forcedly activated button (low 6 bits) */
277 } ATTRIBUTE_PACKED hl_gi_t;
278
279
280 /** 
281  * Button Color Information Table 
282  * Each entry beeing a 32bit word that contains the color indexs and alpha
283  * values to use.  They are all represented by 4 bit number and stored
284  * like this [Ci3, Ci2, Ci1, Ci0, A3, A2, A1, A0].   The actual palette
285  * that the indexes reference is in the PGC.
286  * @TODO split the uint32_t into a struct
287  */
288 typedef struct {
289   uint32_t btn_coli[3][2];  /**< [button color number-1][select:0/action:1] */
290 } ATTRIBUTE_PACKED btn_colit_t;
291
292 /** 
293  * Button Information
294  *
295  * NOTE: I've had to change the structure from the disk layout to get
296  * the packing to work with Sun's Forte C compiler.
297  * The 4 and 7 bytes are 'rotated' was: ABC DEF GHIJ  is: ABCG DEFH IJ
298  */
299 typedef struct {
300 #ifdef WORDS_BIGENDIAN
301   uint32        btn_coln         : 2;  /**< button color number */
302   uint32        x_start          : 10; /**< x start offset within the overlay */
303   uint32        zero1            : 2;  /**< reserved */
304   uint32        x_end            : 10; /**< x end offset within the overlay */
305
306   uint32        zero3            : 2;  /**< reserved */
307   uint32        up               : 6;  /**< button index when pressing up */
308
309   uint32        auto_action_mode : 2;  /**< 0: no, 1: activated if selected */
310   uint32        y_start          : 10; /**< y start offset within the overlay */
311   uint32        zero2            : 2;  /**< reserved */
312   uint32        y_end            : 10; /**< y end offset within the overlay */
313
314   uint32        zero4            : 2;  /**< reserved */
315   uint32        down             : 6;  /**< button index when pressing down */
316   unsigned char zero5            : 2;  /**< reserved */
317   unsigned char left             : 6;  /**< button index when pressing left */
318   unsigned char zero6            : 2;  /**< reserved */
319   unsigned char right            : 6;  /**< button index when pressing right */
320 #else
321   uint32        x_end            : 10;
322   uint32        zero1            : 2;
323   uint32        x_start          : 10;
324   uint32        btn_coln         : 2;
325
326   uint32        up               : 6;
327   uint32        zero3            : 2;
328
329   uint32        y_end            : 10;
330   uint32        zero2            : 2;
331   uint32        y_start          : 10;
332   uint32        auto_action_mode : 2;
333
334   uint32        down             : 6;
335   uint32        zero4            : 2;
336   unsigned char left             : 6;
337   unsigned char zero5            : 2;
338   unsigned char right            : 6;
339   unsigned char zero6            : 2;
340 #endif
341   vm_cmd_t cmd;
342 } ATTRIBUTE_PACKED btni_t;
343
344 /**
345  * Highlight Information 
346  */
347 typedef struct {
348   hl_gi_t     hl_gi;
349   btn_colit_t btn_colit;
350   btni_t      btnit[36];
351 } ATTRIBUTE_PACKED hli_t;
352
353 /**
354  * PCI packet
355  */
356 typedef struct {
357   pci_gi_t    pci_gi;
358   nsml_agli_t nsml_agli;
359   hli_t       hli;
360   uint8_t     zero1[189];
361 } ATTRIBUTE_PACKED pci_t;
362
363
364 #if PRAGMA_PACK
365 #pragma pack()
366 #endif
367
368 #endif /* VSLHC */
369 ////////////////////////////////////////////////////////////////////////////////////////////////////////////////
370
371
372 /**
373  * What's between a directory and a filename?
374  */
375 #if defined( WIN32 )
376     #define DIRECTORY_SEPARATOR '\\'
377 #else
378     #define DIRECTORY_SEPARATOR '/'
379 #endif
380
381 using namespace LIBMATROSKA_NAMESPACE;
382 using namespace std;
383
384 /*****************************************************************************
385  * Module descriptor
386  *****************************************************************************/
387 static int  Open ( vlc_object_t * );
388 static void Close( vlc_object_t * );
389
390 vlc_module_begin();
391     set_shortname( _("Matroska") );
392     set_description( _("Matroska stream demuxer" ) );
393     set_capability( "demux2", 50 );
394     set_callbacks( Open, Close );
395     set_category( CAT_INPUT );
396     set_subcategory( SUBCAT_INPUT_DEMUX );
397
398     add_bool( "mkv-use-ordered-chapters", 1, NULL,
399             N_("Ordered chapters"),
400             N_("Play ordered chapters as specified in the segment"), VLC_TRUE );
401
402     add_bool( "mkv-use-chapter-codec", 1, NULL,
403             N_("Chapter codecs"),
404             N_("Use chapter codecs found in the segment"), VLC_TRUE );
405
406     add_bool( "mkv-seek-percent", 0, NULL,
407             N_("Seek based on percent not time"),
408             N_("Seek based on percent not time"), VLC_TRUE );
409
410     add_bool( "mkv-use-dummy", 0, NULL,
411             N_("Dummy Elements"),
412             N_("Read and discard unknown EBML elements (not good for broken files)"), VLC_TRUE );
413
414     add_shortcut( "mka" );
415     add_shortcut( "mkv" );
416 vlc_module_end();
417
418 /*****************************************************************************
419  * Local prototypes
420  *****************************************************************************/
421 #ifdef HAVE_ZLIB_H
422 block_t *block_zlib_decompress( vlc_object_t *p_this, block_t *p_in_block ) {
423     int result, dstsize, n;
424     unsigned char *dst;
425     block_t *p_block;
426     z_stream d_stream;
427
428     d_stream.zalloc = (alloc_func)0;
429     d_stream.zfree = (free_func)0;
430     d_stream.opaque = (voidpf)0;
431     result = inflateInit(&d_stream);
432     if( result != Z_OK )
433     {
434         msg_Dbg( p_this, "inflateInit() failed. Result: %d", result );
435         return NULL;
436     }
437
438     d_stream.next_in = (Bytef *)p_in_block->p_buffer;
439     d_stream.avail_in = p_in_block->i_buffer;
440     n = 0;
441     p_block = block_New( p_this, 0 );
442     dst = NULL;
443     do
444     {
445         n++;
446         p_block = block_Realloc( p_block, 0, n * 1000 );
447         dst = (unsigned char *)p_block->p_buffer;
448         d_stream.next_out = (Bytef *)&dst[(n - 1) * 1000];
449         d_stream.avail_out = 1000;
450         result = inflate(&d_stream, Z_NO_FLUSH);
451         if( ( result != Z_OK ) && ( result != Z_STREAM_END ) )
452         {
453             msg_Dbg( p_this, "Zlib decompression failed. Result: %d", result );
454             return NULL;
455         }
456     }
457     while( ( d_stream.avail_out == 0 ) && ( d_stream.avail_in != 0 ) &&
458            ( result != Z_STREAM_END ) );
459
460     dstsize = d_stream.total_out;
461     inflateEnd( &d_stream );
462
463     p_block = block_Realloc( p_block, 0, dstsize );
464     p_block->i_buffer = dstsize;
465     block_Release( p_in_block );
466
467     return p_block;
468 }
469 #endif
470
471 /**
472  * Helper function to print the mkv parse tree
473  */
474 static void MkvTree( demux_t & demuxer, int i_level, char *psz_format, ... )
475 {
476     va_list args;
477     if( i_level > 9 )
478     {
479         msg_Err( &demuxer, "too deep tree" );
480         return;
481     }
482     va_start( args, psz_format );
483     static char *psz_foo = "|   |   |   |   |   |   |   |   |   |";
484     char *psz_foo2 = (char*)malloc( ( i_level * 4 + 3 + strlen( psz_format ) ) * sizeof(char) );
485     strncpy( psz_foo2, psz_foo, 4 * i_level );
486     psz_foo2[ 4 * i_level ] = '+';
487     psz_foo2[ 4 * i_level + 1 ] = ' ';
488     strcpy( &psz_foo2[ 4 * i_level + 2 ], psz_format );
489     __msg_GenericVa( VLC_OBJECT(&demuxer), VLC_MSG_DBG, "mkv", psz_foo2, args );
490     free( psz_foo2 );
491     va_end( args );
492 }
493     
494 /*****************************************************************************
495  * Stream managment
496  *****************************************************************************/
497 class vlc_stream_io_callback: public IOCallback
498 {
499   private:
500     stream_t       *s;
501     vlc_bool_t     mb_eof;
502
503   public:
504     vlc_stream_io_callback( stream_t * );
505
506     virtual uint32   read            ( void *p_buffer, size_t i_size);
507     virtual void     setFilePointer  ( int64_t i_offset, seek_mode mode = seek_beginning );
508     virtual size_t   write           ( const void *p_buffer, size_t i_size);
509     virtual uint64   getFilePointer  ( void );
510     virtual void     close           ( void );
511 };
512
513 /*****************************************************************************
514  * Ebml Stream parser
515  *****************************************************************************/
516 class EbmlParser
517 {
518   public:
519     EbmlParser( EbmlStream *es, EbmlElement *el_start, demux_t *p_demux );
520     virtual ~EbmlParser( void );
521
522     void Up( void );
523     void Down( void );
524     void Reset( demux_t *p_demux );
525     EbmlElement *Get( void );
526     void        Keep( void );
527
528     int GetLevel( void );
529
530   private:
531     EbmlStream  *m_es;
532     int         mi_level;
533     EbmlElement *m_el[10];
534     int64_t      mi_remain_size[10];
535
536     EbmlElement *m_got;
537
538     int         mi_user_level;
539     vlc_bool_t  mb_keep;
540     vlc_bool_t  mb_dummy;
541 };
542
543
544 /*****************************************************************************
545  * Some functions to manipulate memory
546  *****************************************************************************/
547 #define GetFOURCC( p )  __GetFOURCC( (uint8_t*)p )
548 static vlc_fourcc_t __GetFOURCC( uint8_t *p )
549 {
550     return VLC_FOURCC( p[0], p[1], p[2], p[3] );
551 }
552
553 /*****************************************************************************
554  * definitions of structures and functions used by this plugins
555  *****************************************************************************/
556 typedef struct
557 {
558     vlc_bool_t   b_default;
559     vlc_bool_t   b_enabled;
560     unsigned int i_number;
561
562     int          i_extra_data;
563     uint8_t      *p_extra_data;
564
565     char         *psz_codec;
566
567     uint64_t     i_default_duration;
568     float        f_timecodescale;
569
570     /* video */
571     es_format_t fmt;
572     float       f_fps;
573     es_out_id_t *p_es;
574
575     vlc_bool_t      b_inited;
576     /* data to be send first */
577     int             i_data_init;
578     uint8_t         *p_data_init;
579
580     /* hack : it's for seek */
581     vlc_bool_t      b_search_keyframe;
582     vlc_bool_t      b_silent;
583
584     /* informative */
585     char         *psz_codec_name;
586     char         *psz_codec_settings;
587     char         *psz_codec_info_url;
588     char         *psz_codec_download_url;
589     
590     /* encryption/compression */
591     int           i_compression_type;
592
593 } mkv_track_t;
594
595 typedef struct
596 {
597     int     i_track;
598     int     i_block_number;
599
600     int64_t i_position;
601     int64_t i_time;
602
603     vlc_bool_t b_key;
604 } mkv_index_t;
605
606 class demux_sys_t;
607
608 const binary MATROSKA_DVD_LEVEL_SS   = 0x30;
609 const binary MATROSKA_DVD_LEVEL_LU   = 0x2A;
610 const binary MATROSKA_DVD_LEVEL_TT   = 0x28;
611 const binary MATROSKA_DVD_LEVEL_PGC  = 0x20;
612 const binary MATROSKA_DVD_LEVEL_PG   = 0x18;
613 const binary MATROSKA_DVD_LEVEL_PTT  = 0x10;
614 const binary MATROSKA_DVD_LEVEL_CN   = 0x08;
615
616 class chapter_codec_cmds_c
617 {
618 public:
619     chapter_codec_cmds_c( demux_sys_t & demuxer, int codec_id = -1)
620     :i_codec_id( codec_id )
621     ,sys( demuxer )
622     {}
623         
624     virtual ~chapter_codec_cmds_c() {}
625
626     void SetPrivate( const KaxChapterProcessPrivate & private_data )
627     {
628         m_private_data = *( new KaxChapterProcessPrivate( private_data ) );
629     }
630
631     void AddCommand( const KaxChapterProcessCommand & command );
632     
633     /// \return wether the codec has seeked in the files or not
634     virtual bool Enter() { return false; }
635     virtual bool Leave() { return false; }
636     virtual std::string GetCodecName( bool f_for_title = false ) const { return ""; }
637
638     KaxChapterProcessPrivate m_private_data;
639
640 protected:
641     std::vector<KaxChapterProcessData> enter_cmds;
642     std::vector<KaxChapterProcessData> during_cmds;
643     std::vector<KaxChapterProcessData> leave_cmds;
644
645     int i_codec_id;
646     demux_sys_t & sys;
647 };
648
649 class dvd_command_interpretor_c
650 {
651 public:
652     dvd_command_interpretor_c( demux_sys_t & demuxer )
653     :sys( demuxer )
654     {
655         memset( p_PRMs, 0, sizeof(p_PRMs) );
656         p_PRMs[ 0x80 + 1 ] = 15;
657         p_PRMs[ 0x80 + 2 ] = 62;
658         p_PRMs[ 0x80 + 3 ] = 1;
659         p_PRMs[ 0x80 + 4 ] = 1;
660         p_PRMs[ 0x80 + 7 ] = 1;
661         p_PRMs[ 0x80 + 8 ] = 1;
662         p_PRMs[ 0x80 + 16 ] = 0xFFFFu;
663         p_PRMs[ 0x80 + 18 ] = 0xFFFFu;
664     }
665     
666     bool Interpret( const binary * p_command, size_t i_size = 8 );
667     
668     uint16 GetPRM( size_t index ) const
669     {
670         if ( index < 256 )
671             return p_PRMs[ index ];
672         else return 0;
673     }
674
675     uint16 GetGPRM( size_t index ) const
676     {
677         if ( index >= 0 && index < 16 )
678             return p_PRMs[ index ];
679         else return 0;
680     }
681
682     uint16 GetSPRM( size_t index ) const
683     {
684         // 21,22,23 reserved for future use
685         if ( index >= 0x80 && index < 0x95 )
686             return p_PRMs[ index ];
687         else return 0;
688     }
689
690     bool SetPRM( size_t index, uint16 value )
691     {
692         if ( index >= 0 && index < 16 )
693         {
694             p_PRMs[ index ] = value;
695             return true;
696         }
697         return false;
698     }
699     
700     bool SetGPRM( size_t index, uint16 value )
701     {
702         if ( index >= 0 && index < 16 )
703         {
704             p_PRMs[ index ] = value;
705             return true;
706         }
707         return false;
708     }
709
710     bool SetSPRM( size_t index, uint16 value )
711     {
712         if ( index > 0x80 && index <= 0x8D && index != 0x8C )
713         {
714             p_PRMs[ index ] = value;
715             return true;
716         }
717         return false;
718     }
719
720 protected:
721     std::string GetRegTypeName( bool b_value, uint16 value ) const
722     {
723         std::string result;
724         char s_value[6], s_reg_value[6];
725         sprintf( s_value, "%.5d", value );
726
727         if ( b_value )
728         {
729             result = "value (";
730             result += s_value;
731             result += ")";
732         }
733         else if ( value < 0x80 )
734         {
735             sprintf( s_reg_value, "%.5d", GetPRM( value ) );
736             result = "GPreg[";
737             result += s_value;
738             result += "] (";
739             result += s_reg_value;
740             result += ")";
741         }
742         else
743         {
744             sprintf( s_reg_value, "%.5d", GetPRM( value ) );
745             result = "SPreg[";
746             result += s_value;
747             result += "] (";
748             result += s_reg_value;
749             result += ")";
750         }
751         return result;
752     }
753
754     uint16       p_PRMs[256];
755     demux_sys_t  & sys;
756     
757     // DVD command IDs
758
759     // Tests
760     // wether the test has to be positive or not
761     static const uint16 CMD_DVD_IF_NOT              = 0x10;
762     // wether it's a comparison on the value or register
763     static const uint16 CMD_DVD_TEST_VALUE          = 0x80;
764     static const uint16 CMD_DVD_IF_GPREG_AND        = (0 << 5);
765     static const uint16 CMD_DVD_IF_GPREG_EQUAL      = (1 << 5);
766     static const uint16 CMD_DVD_IF_GPREG_SUP_EQUAL  = (2 << 5);
767     static const uint16 CMD_DVD_IF_GPREG_INF        = (3 << 5);
768     
769     static const uint16 CMD_DVD_NOP                    = 0x0000;
770     static const uint16 CMD_DVD_GOTO_LINE              = 0x0001;
771     static const uint16 CMD_DVD_BREAK                  = 0x0002;
772     // Links
773     static const uint16 CMD_DVD_NOP2                   = 0x2001;
774     static const uint16 CMD_DVD_LINKPGCN               = 0x2004;
775     static const uint16 CMD_DVD_LINKPGN                = 0x2006;
776     static const uint16 CMD_DVD_LINKCN                 = 0x2007;
777     static const uint16 CMD_DVD_JUMP_TT                = 0x3002;
778     static const uint16 CMD_DVD_JUMPVTS_TT             = 0x3003;
779     static const uint16 CMD_DVD_JUMP_SS                = 0x3006;
780     static const uint16 CMD_DVD_CALLSS_VTSM1           = 0x3008;
781     //
782     static const uint16 CMD_DVD_SET_HL_BTNN2           = 0x4600;
783     static const uint16 CMD_DVD_SET_HL_BTNN_LINKPGCN1  = 0x4604;
784     static const uint16 CMD_DVD_SET_AUDIO              = 0x5100;
785     static const uint16 CMD_DVD_SET_GPRMMD             = 0x5300;
786     static const uint16 CMD_DVD_SET_HL_BTNN1           = 0x5600;
787     static const uint16 CMD_DVD_SET_HL_BTNN_LINKPGCN2  = 0x5604;
788     static const uint16 CMD_DVD_SET_HL_BTNN_LINKCN     = 0x5607;
789     // Operations
790     static const uint16 CMD_DVD_MOV_SPREG_PREG         = 0x6100;
791     static const uint16 CMD_DVD_GPREG_MOV_VALUE        = 0x7100;
792     static const uint16 CMD_DVD_SUB_GPREG              = 0x7400;
793     static const uint16 CMD_DVD_MULT_GPREG             = 0x7500;
794     static const uint16 CMD_DVD_GPREG_DIV_VALUE        = 0x7600;
795     static const uint16 CMD_DVD_GPREG_AND_VALUE        = 0x7900;
796     
797     // callbacks when browsing inside CodecPrivate
798     static bool MatchTitleNumber( const chapter_codec_cmds_c &data, const void *p_cookie, size_t i_cookie_size );
799     static bool MatchPgcType    ( const chapter_codec_cmds_c &data, const void *p_cookie, size_t i_cookie_size );
800     static bool MatchPgcNumber  ( const chapter_codec_cmds_c &data, const void *p_cookie, size_t i_cookie_size );
801 };
802
803 class dvd_chapter_codec_c : public chapter_codec_cmds_c
804 {
805 public:
806     dvd_chapter_codec_c( demux_sys_t & sys )
807     :chapter_codec_cmds_c( sys, 1 )
808     {}
809
810     bool Enter();
811     bool Leave();
812     std::string GetCodecName( bool f_for_title = false ) const;
813 };
814
815 class matroska_script_interpretor_c
816 {
817 public:
818     matroska_script_interpretor_c( demux_sys_t & demuxer )
819     :sys( demuxer )
820     {}
821
822     bool Interpret( const binary * p_command, size_t i_size );
823     
824     // DVD command IDs
825     static const std::string CMD_MS_GOTO_AND_PLAY;
826     
827 protected:
828     demux_sys_t  & sys;
829 };
830
831 const std::string matroska_script_interpretor_c::CMD_MS_GOTO_AND_PLAY = "GotoAndPlay";
832
833
834 class matroska_script_codec_c : public chapter_codec_cmds_c
835 {
836 public:
837     matroska_script_codec_c( demux_sys_t & sys )
838     :chapter_codec_cmds_c( sys, 0 )
839     ,interpretor( sys )
840     {}
841
842     bool Enter();
843     bool Leave();
844
845 protected:
846     matroska_script_interpretor_c interpretor; 
847 };
848
849 class chapter_translation_c
850 {
851 public:
852     KaxChapterTranslateID  translated;
853     unsigned int           codec_id;
854     std::vector<uint64_t>  editions;
855 };
856
857 class chapter_item_c
858 {
859 public:
860     chapter_item_c()
861     :i_start_time(0)
862     ,i_end_time(-1)
863     ,i_user_start_time(-1)
864     ,i_user_end_time(-1)
865     ,i_seekpoint_num(-1)
866     ,b_display_seekpoint(true)
867     ,b_user_display(false)
868     ,psz_parent(NULL)
869     ,b_is_leaving(false)
870     {}
871
872     virtual ~chapter_item_c()
873     {
874         std::vector<chapter_codec_cmds_c*>::iterator index = codecs.begin();
875         while ( index != codecs.end() )
876         {
877             delete (*index);
878             index++;
879         }
880         std::vector<chapter_item_c*>::iterator index_ = sub_chapters.begin();
881         while ( index_ != sub_chapters.end() )
882         {
883             delete (*index_);
884             index_++;
885         }
886     }
887
888     int64_t RefreshChapters( bool b_ordered, int64_t i_prev_user_time );
889     int PublishChapters( input_title_t & title, int & i_user_chapters, int i_level = 0 );
890     chapter_item_c * FindTimecode( mtime_t i_timecode );
891     void Append( const chapter_item_c & edition );
892     chapter_item_c * FindChapter( int64_t i_find_uid );
893     virtual chapter_item_c *BrowseCodecPrivate( unsigned int codec_id, 
894                                     bool (*match)(const chapter_codec_cmds_c &data, const void *p_cookie, size_t i_cookie_size ), 
895                                     const void *p_cookie, 
896                                     size_t i_cookie_size );
897     std::string                 GetCodecName( bool f_for_title = false ) const;
898     bool                        ParentOf( const chapter_item_c & item ) const;
899     
900     int64_t                     i_start_time, i_end_time;
901     int64_t                     i_user_start_time, i_user_end_time; /* the time in the stream when an edition is ordered */
902     std::vector<chapter_item_c*> sub_chapters;
903     int                         i_seekpoint_num;
904     int64_t                     i_uid;
905     bool                        b_display_seekpoint;
906     bool                        b_user_display;
907     std::string                 psz_name;
908     chapter_item_c              *psz_parent;
909     bool                        b_is_leaving;
910     
911     std::vector<chapter_codec_cmds_c*> codecs;
912
913     bool operator<( const chapter_item_c & item ) const
914     {
915         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) );
916     }
917
918     bool Enter( bool b_do_subchapters );
919     bool Leave( bool b_do_subchapters );
920     bool EnterAndLeave( chapter_item_c *p_item );
921 };
922
923 class chapter_edition_c : public chapter_item_c
924 {
925 public:
926     chapter_edition_c()
927     :b_ordered(false)
928     {}
929     
930     void RefreshChapters( );
931     mtime_t Duration() const;
932     std::string GetMainName() const;
933     
934     bool                        b_ordered;
935 };
936
937 class matroska_segment_c
938 {
939 public:
940     matroska_segment_c( demux_sys_t & demuxer, EbmlStream & estream )
941         :segment(NULL)
942         ,es(estream)
943         ,i_timescale(MKVD_TIMECODESCALE)
944         ,i_duration(-1)
945         ,i_start_time(0)
946         ,i_cues_position(-1)
947         ,i_chapters_position(-1)
948         ,i_tags_position(-1)
949         ,cluster(NULL)
950         ,i_start_pos(0)
951         ,b_cues(VLC_FALSE)
952         ,i_index(0)
953         ,i_index_max(1024)
954         ,psz_muxing_application(NULL)
955         ,psz_writing_application(NULL)
956         ,psz_segment_filename(NULL)
957         ,psz_title(NULL)
958         ,psz_date_utc(NULL)
959         ,i_default_edition(0)
960         ,sys(demuxer)
961         ,ep(NULL)
962         ,b_preloaded(false)
963     {
964         index = (mkv_index_t*)malloc( sizeof( mkv_index_t ) * i_index_max );
965     }
966
967     virtual ~matroska_segment_c()
968     {
969         for( size_t i_track = 0; i_track < tracks.size(); i_track++ )
970         {
971             if( tracks[i_track]->fmt.psz_description )
972             {
973                 free( tracks[i_track]->fmt.psz_description );
974             }
975             if( tracks[i_track]->psz_codec )
976             {
977                 free( tracks[i_track]->psz_codec );
978             }
979             if( tracks[i_track]->fmt.psz_language )
980             {
981                 free( tracks[i_track]->fmt.psz_language );
982             }
983             delete tracks[i_track];
984         }
985         
986         if( psz_writing_application )
987         {
988             free( psz_writing_application );
989         }
990         if( psz_muxing_application )
991         {
992             free( psz_muxing_application );
993         }
994         if( psz_segment_filename )
995         {
996             free( psz_segment_filename );
997         }
998         if( psz_title )
999         {
1000             free( psz_title );
1001         }
1002         if( psz_date_utc )
1003         {
1004             free( psz_date_utc );
1005         }
1006         if ( index )
1007             free( index );
1008
1009         delete ep;
1010
1011         std::vector<chapter_edition_c*>::iterator index = stored_editions.begin();
1012         while ( index != stored_editions.end() )
1013         {
1014             delete (*index);
1015             index++;
1016         }
1017     }
1018
1019     KaxSegment              *segment;
1020     EbmlStream              & es;
1021
1022     /* time scale */
1023     uint64_t                i_timescale;
1024
1025     /* duration of the segment */
1026     mtime_t                 i_duration;
1027     mtime_t                 i_start_time;
1028
1029     /* all tracks */
1030     std::vector<mkv_track_t*> tracks;
1031
1032     /* from seekhead */
1033     int64_t                 i_cues_position;
1034     int64_t                 i_chapters_position;
1035     int64_t                 i_tags_position;
1036
1037     KaxCluster              *cluster;
1038     int64_t                 i_start_pos;
1039     KaxSegmentUID           segment_uid;
1040     KaxPrevUID              prev_segment_uid;
1041     KaxNextUID              next_segment_uid;
1042
1043     vlc_bool_t              b_cues;
1044     int                     i_index;
1045     int                     i_index_max;
1046     mkv_index_t             *index;
1047
1048     /* info */
1049     char                    *psz_muxing_application;
1050     char                    *psz_writing_application;
1051     char                    *psz_segment_filename;
1052     char                    *psz_title;
1053     char                    *psz_date_utc;
1054
1055     /* !!!!! GCC 3.3 bug on Darwin !!!!! */
1056     /* when you remove this variable the compiler issues an atomicity error */
1057     /* this variable only works when using std::vector<chapter_edition_c> */
1058     std::vector<chapter_edition_c*> stored_editions;
1059     int                             i_default_edition;
1060
1061     std::vector<chapter_translation_c> translations;
1062     std::vector<KaxSegmentFamily>  families;
1063     
1064     demux_sys_t                    & sys;
1065     EbmlParser                     *ep;
1066     bool                           b_preloaded;
1067
1068     bool Preload( );
1069     bool PreloadFamily( const matroska_segment_c & segment );
1070     void ParseInfo( KaxInfo *info );
1071     void ParseChapters( KaxChapters *chapters );
1072     void ParseSeekHead( KaxSeekHead *seekhead );
1073     void ParseTracks( KaxTracks *tracks );
1074     void ParseChapterAtom( int i_level, KaxChapterAtom *ca, chapter_item_c & chapters );
1075     void ParseTrackEntry( KaxTrackEntry *m );
1076     void ParseCluster( );
1077     void IndexAppendCluster( KaxCluster *cluster );
1078     void LoadCues( );
1079     void LoadTags( );
1080     void InformationCreate( );
1081     void Seek( mtime_t i_date, mtime_t i_time_offset );
1082     int BlockGet( KaxBlock **pp_block, int64_t *pi_ref1, int64_t *pi_ref2, int64_t *pi_duration );
1083     bool Select( mtime_t i_start_time );
1084     void UnSelect( );
1085
1086     static bool CompareSegmentUIDs( const matroska_segment_c * item_a, const matroska_segment_c * item_b );
1087 };
1088
1089 // class holding hard-linked segment together in the playback order
1090 class virtual_segment_c
1091 {
1092 public:
1093     virtual_segment_c( matroska_segment_c *p_segment )
1094         :p_editions(NULL)
1095         ,i_sys_title(0)
1096         ,i_current_segment(0)
1097         ,i_current_edition(-1)
1098         ,psz_current_chapter(NULL)
1099     {
1100         linked_segments.push_back( p_segment );
1101
1102         AppendUID( p_segment->segment_uid );
1103         AppendUID( p_segment->prev_segment_uid );
1104         AppendUID( p_segment->next_segment_uid );
1105     }
1106
1107     void Sort();
1108     size_t AddSegment( matroska_segment_c *p_segment );
1109     void PreloadLinked( );
1110     mtime_t Duration( ) const;
1111     void LoadCues( );
1112     void Seek( demux_t & demuxer, mtime_t i_date, mtime_t i_time_offset, chapter_item_c *psz_chapter );
1113
1114     inline chapter_edition_c *Edition()
1115     {
1116         if ( i_current_edition >= 0 && size_t(i_current_edition) < p_editions->size() )
1117             return (*p_editions)[i_current_edition];
1118         return NULL;
1119     }
1120
1121     matroska_segment_c * Segment() const
1122     {
1123         if ( linked_segments.size() == 0 || i_current_segment >= linked_segments.size() )
1124             return NULL;
1125         return linked_segments[i_current_segment];
1126     }
1127
1128     inline chapter_item_c *CurrentChapter() {
1129         return psz_current_chapter;
1130     }
1131
1132     bool SelectNext()
1133     {
1134         if ( i_current_segment < linked_segments.size()-1 )
1135         {
1136             i_current_segment++;
1137             return true;
1138         }
1139         return false;
1140     }
1141
1142     bool FindUID( KaxSegmentUID & uid ) const
1143     {
1144         for ( size_t i=0; i<linked_uids.size(); i++ )
1145         {
1146             if ( linked_uids[i] == uid )
1147                 return true;
1148         }
1149         return false;
1150     }
1151
1152     bool UpdateCurrentToChapter( demux_t & demux );
1153     void PrepareChapters( );
1154
1155     chapter_item_c *BrowseCodecPrivate( unsigned int codec_id, 
1156                                         bool (*match)(const chapter_codec_cmds_c &data, const void *p_cookie, size_t i_cookie_size ), 
1157                                         const void *p_cookie, 
1158                                         size_t i_cookie_size );
1159     chapter_item_c *FindChapter( int64_t i_find_uid );
1160
1161     std::vector<chapter_edition_c*>  *p_editions;
1162     int                              i_sys_title;
1163
1164 protected:
1165     std::vector<matroska_segment_c*> linked_segments;
1166     std::vector<KaxSegmentUID>       linked_uids;
1167     size_t                           i_current_segment;
1168
1169     int                              i_current_edition;
1170     chapter_item_c                   *psz_current_chapter;
1171
1172     void                             AppendUID( const EbmlBinary & UID );
1173 };
1174
1175 class matroska_stream_c
1176 {
1177 public:
1178     matroska_stream_c( demux_sys_t & demuxer )
1179         :p_in(NULL)
1180         ,p_es(NULL)
1181         ,sys(demuxer)
1182     {}
1183
1184     virtual ~matroska_stream_c()
1185     {
1186         delete p_in;
1187         delete p_es;
1188     }
1189
1190     IOCallback         *p_in;
1191     EbmlStream         *p_es;
1192
1193     std::vector<matroska_segment_c*> segments;
1194
1195     demux_sys_t                      & sys;
1196 };
1197
1198 typedef struct
1199 {
1200     VLC_COMMON_MEMBERS
1201
1202     demux_t        *p_demux;
1203     vlc_mutex_t     lock;
1204
1205     vlc_bool_t      b_moved;
1206     vlc_bool_t      b_clicked;
1207     vlc_bool_t      b_key;
1208
1209 } event_thread_t;
1210
1211 class demux_sys_t
1212 {
1213 public:
1214     demux_sys_t( demux_t & demux )
1215         :demuxer(demux)
1216         ,i_pts(0)
1217         ,i_start_pts(0)
1218         ,i_chapter_time(0)
1219         ,meta(NULL)
1220         ,i_current_title(0)
1221         ,p_current_segment(NULL)
1222         ,dvd_interpretor( *this )
1223         ,f_duration(-1.0)
1224         ,b_ui_hooked(false)
1225         ,p_input(NULL)
1226         ,i_curr_button(0)
1227         ,p_ev(NULL)
1228     {}
1229
1230     virtual ~demux_sys_t()
1231     {
1232         StopUiThread();
1233         size_t i;
1234         for ( i=0; i<streams.size(); i++ )
1235             delete streams[i];
1236         for ( i=0; i<opened_segments.size(); i++ )
1237             delete opened_segments[i];
1238         for ( i=0; i<used_segments.size(); i++ )
1239             delete used_segments[i];
1240     }
1241
1242     /* current data */
1243     demux_t                 & demuxer;
1244
1245     mtime_t                 i_pts;
1246     mtime_t                 i_start_pts;
1247     mtime_t                 i_chapter_time;
1248
1249     vlc_meta_t              *meta;
1250
1251     std::vector<input_title_t>       titles; // matroska editions
1252     size_t                           i_current_title;
1253
1254     std::vector<matroska_stream_c*>  streams;
1255     std::vector<matroska_segment_c*> opened_segments;
1256     std::vector<virtual_segment_c*>  used_segments;
1257     virtual_segment_c                *p_current_segment;
1258
1259     dvd_command_interpretor_c        dvd_interpretor;
1260
1261     /* duration of the stream */
1262     float                   f_duration;
1263
1264     matroska_segment_c *FindSegment( const EbmlBinary & uid ) const;
1265     chapter_item_c *BrowseCodecPrivate( unsigned int codec_id, 
1266                                         bool (*match)(const chapter_codec_cmds_c &data, const void *p_cookie, size_t i_cookie_size ), 
1267                                         const void *p_cookie, 
1268                                         size_t i_cookie_size, 
1269                                         virtual_segment_c * & p_segment_found );
1270     chapter_item_c *FindChapter( int64_t i_find_uid, virtual_segment_c * & p_segment_found );
1271
1272     void PreloadFamily( const matroska_segment_c & of_segment );
1273     void PreloadLinked( matroska_segment_c *p_segment );
1274     bool PreparePlayback( virtual_segment_c *p_new_segment );
1275     matroska_stream_c *AnalyseAllSegmentsFound( EbmlStream *p_estream );
1276
1277     void StartUiThread();
1278     void StopUiThread();
1279     bool b_ui_hooked;
1280     inline void SwapButtons();
1281
1282     /* for spu variables */
1283     input_thread_t *p_input;
1284     pci_t          pci_packet;
1285     int16          i_curr_button;
1286     uint8_t        alpha[4];
1287
1288     /* event */
1289     event_thread_t *p_ev;
1290     static int EventThread( vlc_object_t *p_this );
1291     static int EventMouse( vlc_object_t *p_this, char const *psz_var,
1292                        vlc_value_t oldval, vlc_value_t newval, void *p_data );
1293     static int EventKey( vlc_object_t *p_this, char const *psz_var,
1294                      vlc_value_t oldval, vlc_value_t newval, void *p_data );
1295
1296
1297
1298 protected:
1299     virtual_segment_c *VirtualFromSegments( matroska_segment_c *p_segment ) const;
1300     bool IsUsedSegment( matroska_segment_c &p_segment ) const;
1301 };
1302
1303 static int  Demux  ( demux_t * );
1304 static int  Control( demux_t *, int, va_list );
1305 static void Seek   ( demux_t *, mtime_t i_date, double f_percent, chapter_item_c *psz_chapter );
1306
1307 #define MKV_IS_ID( el, C ) ( EbmlId( (*el) ) == C::ClassInfos.GlobalId )
1308
1309 static char *UTF8ToStr          ( const UTFstring &u );
1310
1311 /*****************************************************************************
1312  * Open: initializes matroska demux structures
1313  *****************************************************************************/
1314 static int Open( vlc_object_t * p_this )
1315 {
1316     demux_t            *p_demux = (demux_t*)p_this;
1317     demux_sys_t        *p_sys;
1318     matroska_stream_c  *p_stream;
1319     matroska_segment_c *p_segment;
1320     uint8_t            *p_peek;
1321     std::string        s_path, s_filename;
1322     vlc_stream_io_callback *p_io_callback;
1323     EbmlStream         *p_io_stream;
1324
1325     /* peek the begining */
1326     if( stream_Peek( p_demux->s, &p_peek, 4 ) < 4 ) return VLC_EGENERIC;
1327
1328     /* is a valid file */
1329     if( p_peek[0] != 0x1a || p_peek[1] != 0x45 ||
1330         p_peek[2] != 0xdf || p_peek[3] != 0xa3 ) return VLC_EGENERIC;
1331
1332     /* Set the demux function */
1333     p_demux->pf_demux   = Demux;
1334     p_demux->pf_control = Control;
1335     p_demux->p_sys      = p_sys = new demux_sys_t( *p_demux );
1336
1337     p_io_callback = new vlc_stream_io_callback( p_demux->s );
1338     p_io_stream = new EbmlStream( *p_io_callback );
1339
1340     if( p_io_stream == NULL )
1341     {
1342         msg_Err( p_demux, "failed to create EbmlStream" );
1343         delete p_io_callback;
1344         delete p_sys;
1345         return VLC_EGENERIC;
1346     }
1347
1348     p_stream = p_sys->AnalyseAllSegmentsFound( p_io_stream );
1349     if( p_stream == NULL )
1350     {
1351         msg_Err( p_demux, "cannot find KaxSegment" );
1352         goto error;
1353     }
1354     p_sys->streams.push_back( p_stream );
1355
1356     p_stream->p_in = p_io_callback;
1357     p_stream->p_es = p_io_stream;
1358
1359     for (size_t i=0; i<p_stream->segments.size(); i++)
1360     {
1361         p_stream->segments[i]->Preload();
1362     }
1363
1364     p_segment = p_stream->segments[0];
1365     if( p_segment->cluster != NULL )
1366     {
1367         msg_Warn( p_demux, "cannot find any cluster, damaged file ?" );
1368
1369         // reset the stream reading to the first cluster of the segment used
1370         p_stream->p_in->setFilePointer( p_segment->cluster->GetElementPosition() );
1371     }
1372
1373     /* get the files from the same dir from the same family (based on p_demux->psz_path) */
1374     if (p_demux->psz_path[0] != '\0' && !strcmp(p_demux->psz_access, ""))
1375     {
1376         // assume it's a regular file
1377         // get the directory path
1378         s_path = p_demux->psz_path;
1379         if (s_path.at(s_path.length() - 1) == DIRECTORY_SEPARATOR)
1380         {
1381             s_path = s_path.substr(0,s_path.length()-1);
1382         }
1383         else
1384         {
1385             if (s_path.find_last_of(DIRECTORY_SEPARATOR) > 0) 
1386             {
1387                 s_path = s_path.substr(0,s_path.find_last_of(DIRECTORY_SEPARATOR));
1388             }
1389         }
1390
1391         struct dirent *p_file_item;
1392         DIR *p_src_dir = opendir(s_path.c_str());
1393
1394         if (p_src_dir != NULL)
1395         {
1396             while ((p_file_item = (dirent *) readdir(p_src_dir)))
1397             {
1398                 if (strlen(p_file_item->d_name) > 4)
1399                 {
1400                     s_filename = s_path + DIRECTORY_SEPARATOR + p_file_item->d_name;
1401
1402                     if (!s_filename.compare(p_demux->psz_path))
1403                         continue; // don't reuse the original opened file
1404
1405 #if defined(__GNUC__) && (__GNUC__ < 3)
1406                     if (!s_filename.compare("mkv", s_filename.length() - 3, 3) || 
1407                         !s_filename.compare("mka", s_filename.length() - 3, 3))
1408 #else
1409                     if (!s_filename.compare(s_filename.length() - 3, 3, "mkv") || 
1410                         !s_filename.compare(s_filename.length() - 3, 3, "mka"))
1411 #endif
1412                     {
1413                         // test wether this file belongs to the our family
1414                         StdIOCallback *p_file_io = new StdIOCallback(s_filename.c_str(), MODE_READ);
1415                         EbmlStream *p_estream = new EbmlStream(*p_file_io);
1416
1417                         p_stream = p_sys->AnalyseAllSegmentsFound( p_estream );
1418                         if ( p_stream == NULL )
1419                         {
1420                             msg_Dbg( p_demux, "the file '%s' will not be used", s_filename.c_str() );
1421                             delete p_estream;
1422                             delete p_file_io;
1423                         }
1424                         else
1425                         {
1426                             p_stream->p_in = p_file_io;
1427                             p_stream->p_es = p_estream;
1428                             p_sys->streams.push_back( p_stream );
1429                         }
1430                     }
1431                 }
1432             }
1433             closedir( p_src_dir );
1434         }
1435     }
1436
1437     p_sys->PreloadFamily( *p_segment );
1438     p_sys->PreloadLinked( p_segment );
1439     if ( !p_sys->PreparePlayback( NULL ) )
1440     {
1441         msg_Err( p_demux, "cannot use the segment" );
1442         goto error;
1443     }
1444     
1445     return VLC_SUCCESS;
1446
1447 error:
1448     delete p_sys;
1449     return VLC_EGENERIC;
1450 }
1451
1452 /*****************************************************************************
1453  * Close: frees unused data
1454  *****************************************************************************/
1455 static void Close( vlc_object_t *p_this )
1456 {
1457     demux_t     *p_demux = (demux_t*)p_this;
1458     demux_sys_t *p_sys   = p_demux->p_sys;
1459
1460     delete p_sys;
1461 }
1462
1463 /*****************************************************************************
1464  * Control:
1465  *****************************************************************************/
1466 static int Control( demux_t *p_demux, int i_query, va_list args )
1467 {
1468     demux_sys_t        *p_sys = p_demux->p_sys;
1469     int64_t     *pi64;
1470     double      *pf, f;
1471     int         i_skp;
1472     size_t      i_idx;
1473
1474     vlc_meta_t **pp_meta;
1475
1476     switch( i_query )
1477     {
1478         case DEMUX_GET_META:
1479             pp_meta = (vlc_meta_t**)va_arg( args, vlc_meta_t** );
1480             *pp_meta = vlc_meta_Duplicate( p_sys->meta );
1481             return VLC_SUCCESS;
1482
1483         case DEMUX_GET_LENGTH:
1484             pi64 = (int64_t*)va_arg( args, int64_t * );
1485             if( p_sys->f_duration > 0.0 )
1486             {
1487                 *pi64 = (int64_t)(p_sys->f_duration * 1000);
1488                 return VLC_SUCCESS;
1489             }
1490             return VLC_EGENERIC;
1491
1492         case DEMUX_GET_POSITION:
1493             pf = (double*)va_arg( args, double * );
1494             if ( p_sys->f_duration > 0.0 )
1495                 *pf = (double)(p_sys->i_pts >= p_sys->i_start_pts ? p_sys->i_pts : p_sys->i_start_pts ) / (1000.0 * p_sys->f_duration);
1496             return VLC_SUCCESS;
1497
1498         case DEMUX_SET_POSITION:
1499             f = (double)va_arg( args, double );
1500             Seek( p_demux, -1, f, NULL );
1501             return VLC_SUCCESS;
1502
1503         case DEMUX_GET_TIME:
1504             pi64 = (int64_t*)va_arg( args, int64_t * );
1505             *pi64 = p_sys->i_pts;
1506             return VLC_SUCCESS;
1507
1508         case DEMUX_GET_TITLE_INFO:
1509             if( p_sys->titles.size() )
1510             {
1511                 input_title_t ***ppp_title = (input_title_t***)va_arg( args, input_title_t*** );
1512                 int *pi_int    = (int*)va_arg( args, int* );
1513
1514                 *pi_int = p_sys->titles.size();
1515                 *ppp_title = (input_title_t**)malloc( sizeof( input_title_t**) * p_sys->titles.size() );
1516
1517                 for( size_t i = 0; i < p_sys->titles.size(); i++ )
1518                 {
1519                     (*ppp_title)[i] = vlc_input_title_Duplicate( &p_sys->titles[i] );
1520                 }
1521
1522                 return VLC_SUCCESS;
1523             }
1524             return VLC_EGENERIC;
1525
1526         case DEMUX_SET_TITLE:
1527             /* TODO handle editions as titles */
1528             i_idx = (int)va_arg( args, int );
1529             if( i_idx < p_sys->used_segments.size() )
1530             {
1531                 p_sys->PreparePlayback( p_sys->used_segments[i_idx] );
1532                 return VLC_SUCCESS;
1533             }
1534             return VLC_EGENERIC;
1535
1536         case DEMUX_SET_SEEKPOINT:
1537             i_skp = (int)va_arg( args, int );
1538
1539             // TODO change the way it works with the << & >> buttons on the UI (+1/-1 instead of a number)
1540             if( p_sys->titles.size() && i_skp < p_sys->titles[p_sys->i_current_title].i_seekpoint)
1541             {
1542                 Seek( p_demux, (int64_t)p_sys->titles[p_sys->i_current_title].seekpoint[i_skp]->i_time_offset, -1, NULL);
1543                 p_demux->info.i_seekpoint |= INPUT_UPDATE_SEEKPOINT;
1544                 p_demux->info.i_seekpoint = i_skp;
1545                 return VLC_SUCCESS;
1546             }
1547             return VLC_EGENERIC;
1548
1549         case DEMUX_SET_TIME:
1550         case DEMUX_GET_FPS:
1551         default:
1552             return VLC_EGENERIC;
1553     }
1554 }
1555
1556 int matroska_segment_c::BlockGet( KaxBlock **pp_block, int64_t *pi_ref1, int64_t *pi_ref2, int64_t *pi_duration )
1557 {
1558     *pp_block = NULL;
1559     *pi_ref1  = -1;
1560     *pi_ref2  = -1;
1561
1562     for( ;; )
1563     {
1564         EbmlElement *el;
1565         int         i_level;
1566
1567         if ( ep == NULL )
1568             return VLC_EGENERIC;
1569
1570         el = ep->Get();
1571         i_level = ep->GetLevel();
1572
1573         if( el == NULL && *pp_block != NULL )
1574         {
1575             /* update the index */
1576 #define idx index[i_index - 1]
1577             if( i_index > 0 && idx.i_time == -1 )
1578             {
1579                 idx.i_time        = (*pp_block)->GlobalTimecode() / (mtime_t)1000;
1580                 idx.b_key         = *pi_ref1 == -1 ? VLC_TRUE : VLC_FALSE;
1581             }
1582 #undef idx
1583             return VLC_SUCCESS;
1584         }
1585
1586         if( el == NULL )
1587         {
1588             if( ep->GetLevel() > 1 )
1589             {
1590                 ep->Up();
1591                 continue;
1592             }
1593             msg_Warn( &sys.demuxer, "EOF" );
1594             return VLC_EGENERIC;
1595         }
1596
1597         /* do parsing */
1598         if( i_level == 1 )
1599         {
1600             if( MKV_IS_ID( el, KaxCluster ) )
1601             {
1602                 cluster = (KaxCluster*)el;
1603
1604                 /* add it to the index */
1605                 if( i_index == 0 ||
1606                     ( i_index > 0 && index[i_index - 1].i_position < (int64_t)cluster->GetElementPosition() ) )
1607                 {
1608                     IndexAppendCluster( cluster );
1609                 }
1610
1611                 // reset silent tracks
1612                 for (size_t i=0; i<tracks.size(); i++)
1613                 {
1614                     tracks[i]->b_silent = VLC_FALSE;
1615                 }
1616
1617                 ep->Down();
1618             }
1619             else if( MKV_IS_ID( el, KaxCues ) )
1620             {
1621                 msg_Warn( &sys.demuxer, "find KaxCues FIXME" );
1622                 return VLC_EGENERIC;
1623             }
1624             else
1625             {
1626                 msg_Dbg( &sys.demuxer, "unknown (%s)", typeid( el ).name() );
1627             }
1628         }
1629         else if( i_level == 2 )
1630         {
1631             if( MKV_IS_ID( el, KaxClusterTimecode ) )
1632             {
1633                 KaxClusterTimecode &ctc = *(KaxClusterTimecode*)el;
1634
1635                 ctc.ReadData( es.I_O(), SCOPE_ALL_DATA );
1636                 cluster->InitTimecode( uint64( ctc ), i_timescale );
1637             }
1638             else if( MKV_IS_ID( el, KaxClusterSilentTracks ) )
1639             {
1640                 ep->Down();
1641             }
1642             else if( MKV_IS_ID( el, KaxBlockGroup ) )
1643             {
1644                 ep->Down();
1645             }
1646         }
1647         else if( i_level == 3 )
1648         {
1649             if( MKV_IS_ID( el, KaxBlock ) )
1650             {
1651                 *pp_block = (KaxBlock*)el;
1652
1653                 (*pp_block)->ReadData( es.I_O() );
1654                 (*pp_block)->SetParent( *cluster );
1655
1656                 ep->Keep();
1657             }
1658             else if( MKV_IS_ID( el, KaxBlockDuration ) )
1659             {
1660                 KaxBlockDuration &dur = *(KaxBlockDuration*)el;
1661
1662                 dur.ReadData( es.I_O() );
1663                 *pi_duration = uint64( dur );
1664             }
1665             else if( MKV_IS_ID( el, KaxReferenceBlock ) )
1666             {
1667                 KaxReferenceBlock &ref = *(KaxReferenceBlock*)el;
1668
1669                 ref.ReadData( es.I_O() );
1670                 if( *pi_ref1 == -1 )
1671                 {
1672                     *pi_ref1 = int64( ref );
1673                 }
1674                 else
1675                 {
1676                     *pi_ref2 = int64( ref );
1677                 }
1678             }
1679             else if( MKV_IS_ID( el, KaxClusterSilentTrackNumber ) )
1680             {
1681                 KaxClusterSilentTrackNumber &track_num = *(KaxClusterSilentTrackNumber*)el;
1682                 track_num.ReadData( es.I_O() );
1683                 // find the track
1684                 for (size_t i=0; i<tracks.size(); i++)
1685                 {
1686                     if ( tracks[i]->i_number == uint32(track_num))
1687                     {
1688                         tracks[i]->b_silent = VLC_TRUE;
1689                         break;
1690                     }
1691                 }
1692             }
1693         }
1694         else
1695         {
1696             msg_Err( &sys.demuxer, "invalid level = %d", i_level );
1697             return VLC_EGENERIC;
1698         }
1699     }
1700 }
1701
1702 static block_t *MemToBlock( demux_t *p_demux, uint8_t *p_mem, int i_mem)
1703 {
1704     block_t *p_block;
1705     if( !(p_block = block_New( p_demux, i_mem ) ) ) return NULL;
1706     memcpy( p_block->p_buffer, p_mem, i_mem );
1707     //p_block->i_rate = p_input->stream.control.i_rate;
1708     return p_block;
1709 }
1710
1711 static void BlockDecode( demux_t *p_demux, KaxBlock *block, mtime_t i_pts,
1712                          mtime_t i_duration )
1713 {
1714     demux_sys_t        *p_sys = p_demux->p_sys;
1715     matroska_segment_c *p_segment = p_sys->p_current_segment->Segment();
1716
1717     size_t          i_track;
1718     unsigned int    i;
1719     vlc_bool_t      b;
1720
1721 #define tk  p_segment->tracks[i_track]
1722     for( i_track = 0; i_track < p_segment->tracks.size(); i_track++ )
1723     {
1724         if( tk->i_number == block->TrackNum() )
1725         {
1726             break;
1727         }
1728     }
1729
1730     if( i_track >= p_segment->tracks.size() )
1731     {
1732         msg_Err( p_demux, "invalid track number=%d", block->TrackNum() );
1733         return;
1734     }
1735     if( tk->p_es == NULL )
1736     {
1737         msg_Err( p_demux, "unknown track number=%d", block->TrackNum() );
1738         return;
1739     }
1740     if( i_pts < p_sys->i_start_pts && tk->fmt.i_cat == AUDIO_ES )
1741     {
1742         return; /* discard audio packets that shouldn't be rendered */
1743     }
1744
1745     if ( tk->fmt.i_cat != SPU_ES || strcmp( tk->psz_codec, "B_VOBBTN" ) )
1746     {
1747         es_out_Control( p_demux->out, ES_OUT_GET_ES_STATE, tk->p_es, &b );
1748
1749         if( !b )
1750         {
1751             tk->b_inited = VLC_FALSE;
1752             return;
1753         }
1754     }
1755
1756
1757     /* First send init data */
1758     if( !tk->b_inited && tk->i_data_init > 0 )
1759     {
1760         block_t *p_init;
1761
1762         msg_Dbg( p_demux, "sending header (%d bytes)", tk->i_data_init );
1763         p_init = MemToBlock( p_demux, tk->p_data_init, tk->i_data_init );
1764         if( p_init ) es_out_Send( p_demux->out, tk->p_es, p_init );
1765     }
1766     tk->b_inited = VLC_TRUE;
1767
1768
1769     for( i = 0; i < block->NumberFrames(); i++ )
1770     {
1771         block_t *p_block;
1772         DataBuffer &data = block->GetBuffer(i);
1773
1774         p_block = MemToBlock( p_demux, data.Buffer(), data.Size() );
1775
1776         if( p_block == NULL )
1777         {
1778             break;
1779         }
1780
1781 #if defined(HAVE_ZLIB_H)
1782         if( tk->i_compression_type )
1783         {
1784             p_block = block_zlib_decompress( VLC_OBJECT(p_demux), p_block );
1785         }
1786 #endif
1787
1788         // TODO implement correct timestamping when B frames are used
1789         if( tk->fmt.i_cat != VIDEO_ES )
1790         {
1791             p_block->i_dts = p_block->i_pts = i_pts;
1792         }
1793         else
1794         {
1795             p_block->i_dts = i_pts;
1796             p_block->i_pts = 0;
1797         }
1798
1799         if ( tk->fmt.i_cat == SPU_ES )
1800         {
1801             if ( !strcmp( tk->psz_codec, "B_VOBBTN" ) )
1802             {
1803                 // TODO handle the start/stop times of this packet
1804                 if ( p_sys->b_ui_hooked )
1805                 {
1806                     vlc_mutex_lock( &p_sys->p_ev->lock );
1807                     memcpy( &p_sys->pci_packet, &p_block->p_buffer[1], sizeof(pci_t) );
1808                     p_sys->SwapButtons();
1809                     vlc_mutex_unlock( &p_sys->p_ev->lock );
1810                     block_Release( p_block );
1811                 }
1812                 return;
1813             }
1814
1815             else if ( strcmp( tk->psz_codec, "S_VOBSUB" ) )
1816             {
1817                 p_block->i_length = i_duration * 1000;
1818             }
1819         }
1820
1821         es_out_Send( p_demux->out, tk->p_es, p_block );
1822
1823         /* use time stamp only for first block */
1824         i_pts = 0;
1825     }
1826
1827 #undef tk
1828 }
1829
1830 matroska_stream_c *demux_sys_t::AnalyseAllSegmentsFound( EbmlStream *p_estream )
1831 {
1832     int i_upper_lvl = 0;
1833     size_t i;
1834     EbmlElement *p_l0, *p_l1, *p_l2;
1835     bool b_keep_stream = false, b_keep_segment;
1836
1837     // verify the EBML Header
1838     p_l0 = p_estream->FindNextID(EbmlHead::ClassInfos, 0xFFFFFFFFL);
1839     if (p_l0 == NULL)
1840     {
1841         return NULL;
1842     }
1843     p_l0->SkipData(*p_estream, EbmlHead_Context);
1844     delete p_l0;
1845
1846     // find all segments in this file
1847     p_l0 = p_estream->FindNextID(KaxSegment::ClassInfos, 0xFFFFFFFFL);
1848     if (p_l0 == NULL)
1849     {
1850         return NULL;
1851     }
1852
1853     matroska_stream_c *p_stream1 = new matroska_stream_c( *this );
1854
1855     while (p_l0 != 0)
1856     {
1857         if (EbmlId(*p_l0) == KaxSegment::ClassInfos.GlobalId)
1858         {
1859             EbmlParser  *ep;
1860             matroska_segment_c *p_segment1 = new matroska_segment_c( *this, *p_estream );
1861             b_keep_segment = false;
1862
1863             ep = new EbmlParser(p_estream, p_l0, &demuxer );
1864             p_segment1->ep = ep;
1865             p_segment1->segment = (KaxSegment*)p_l0;
1866
1867             while ((p_l1 = ep->Get()))
1868             {
1869                 if (MKV_IS_ID(p_l1, KaxInfo))
1870                 {
1871                     // find the families of this segment
1872                     KaxInfo *p_info = static_cast<KaxInfo*>(p_l1);
1873
1874                     p_info->Read(*p_estream, KaxInfo::ClassInfos.Context, i_upper_lvl, p_l2, true);
1875                     for( i = 0; i < p_info->ListSize(); i++ )
1876                     {
1877                         EbmlElement *l = (*p_info)[i];
1878
1879                         if( MKV_IS_ID( l, KaxSegmentUID ) )
1880                         {
1881                             KaxSegmentUID *p_uid = static_cast<KaxSegmentUID*>(l);
1882                             b_keep_segment = (FindSegment( *p_uid ) == NULL);
1883                             if ( !b_keep_segment )
1884                                 break; // this segment is already known
1885                             opened_segments.push_back( p_segment1 );
1886                             p_segment1->segment_uid = *( new KaxSegmentUID(*p_uid) );
1887                         }
1888                         else if( MKV_IS_ID( l, KaxPrevUID ) )
1889                         {
1890                             p_segment1->prev_segment_uid = *( new KaxPrevUID( *static_cast<KaxPrevUID*>(l) ) );
1891                         }
1892                         else if( MKV_IS_ID( l, KaxNextUID ) )
1893                         {
1894                             p_segment1->next_segment_uid = *( new KaxNextUID( *static_cast<KaxNextUID*>(l) ) );
1895                         }
1896                         else if( MKV_IS_ID( l, KaxSegmentFamily ) )
1897                         {
1898                             KaxSegmentFamily *p_fam = new KaxSegmentFamily( *static_cast<KaxSegmentFamily*>(l) );
1899                             p_segment1->families.push_back( *p_fam );
1900                         }
1901                     }
1902                     break;
1903                 }
1904             }
1905             if ( b_keep_segment )
1906             {
1907                 b_keep_stream = true;
1908                 p_stream1->segments.push_back( p_segment1 );
1909             }
1910             else
1911                 delete p_segment1;
1912         }
1913
1914         p_l0->SkipData(*p_estream, EbmlHead_Context);
1915         p_l0 = p_estream->FindNextID(KaxSegment::ClassInfos, 0xFFFFFFFFL);
1916     }
1917
1918     if ( !b_keep_stream )
1919     {
1920         delete p_stream1;
1921         p_stream1 = NULL;
1922     }
1923
1924     return p_stream1;
1925 }
1926
1927 bool matroska_segment_c::Select( mtime_t i_start_time )
1928 {
1929     size_t i_track;
1930
1931     /* add all es */
1932     msg_Dbg( &sys.demuxer, "found %d es", tracks.size() );
1933     sys.StopUiThread();
1934     for( i_track = 0; i_track < tracks.size(); i_track++ )
1935     {
1936         if( tracks[i_track]->fmt.i_cat == UNKNOWN_ES )
1937         {
1938             msg_Warn( &sys.demuxer, "invalid track[%d, n=%d]", i_track, tracks[i_track]->i_number );
1939             tracks[i_track]->p_es = NULL;
1940             continue;
1941         }
1942
1943         if( !strcmp( tracks[i_track]->psz_codec, "V_MS/VFW/FOURCC" ) )
1944         {
1945             if( tracks[i_track]->i_extra_data < (int)sizeof( BITMAPINFOHEADER ) )
1946             {
1947                 msg_Err( &sys.demuxer, "missing/invalid BITMAPINFOHEADER" );
1948                 tracks[i_track]->fmt.i_codec = VLC_FOURCC( 'u', 'n', 'd', 'f' );
1949             }
1950             else
1951             {
1952                 BITMAPINFOHEADER *p_bih = (BITMAPINFOHEADER*)tracks[i_track]->p_extra_data;
1953
1954                 tracks[i_track]->fmt.video.i_width = GetDWLE( &p_bih->biWidth );
1955                 tracks[i_track]->fmt.video.i_height= GetDWLE( &p_bih->biHeight );
1956                 tracks[i_track]->fmt.i_codec       = GetFOURCC( &p_bih->biCompression );
1957
1958                 tracks[i_track]->fmt.i_extra       = GetDWLE( &p_bih->biSize ) - sizeof( BITMAPINFOHEADER );
1959                 if( tracks[i_track]->fmt.i_extra > 0 )
1960                 {
1961                     tracks[i_track]->fmt.p_extra = malloc( tracks[i_track]->fmt.i_extra );
1962                     memcpy( tracks[i_track]->fmt.p_extra, &p_bih[1], tracks[i_track]->fmt.i_extra );
1963                 }
1964             }
1965         }
1966         else if( !strcmp( tracks[i_track]->psz_codec, "V_MPEG1" ) ||
1967                  !strcmp( tracks[i_track]->psz_codec, "V_MPEG2" ) )
1968         {
1969             tracks[i_track]->fmt.i_codec = VLC_FOURCC( 'm', 'p', 'g', 'v' );
1970         }
1971         else if( !strncmp( tracks[i_track]->psz_codec, "V_MPEG4", 7 ) )
1972         {
1973             if( !strcmp( tracks[i_track]->psz_codec, "V_MPEG4/MS/V3" ) )
1974             {
1975                 tracks[i_track]->fmt.i_codec = VLC_FOURCC( 'D', 'I', 'V', '3' );
1976             }
1977             else if( !strcmp( tracks[i_track]->psz_codec, "V_MPEG4/ISO/AVC" ) )
1978             {
1979                 tracks[i_track]->fmt.i_codec = VLC_FOURCC( 'a', 'v', 'c', '1' );
1980                 tracks[i_track]->fmt.b_packetized = VLC_FALSE;
1981                 tracks[i_track]->fmt.i_extra = tracks[i_track]->i_extra_data;
1982                 tracks[i_track]->fmt.p_extra = malloc( tracks[i_track]->i_extra_data );
1983                 memcpy( tracks[i_track]->fmt.p_extra,tracks[i_track]->p_extra_data, tracks[i_track]->i_extra_data );
1984             }
1985             else
1986             {
1987                 tracks[i_track]->fmt.i_codec = VLC_FOURCC( 'm', 'p', '4', 'v' );
1988             }
1989         }
1990         else if( !strcmp( tracks[i_track]->psz_codec, "V_QUICKTIME" ) )
1991         {
1992             MP4_Box_t *p_box = (MP4_Box_t*)malloc( sizeof( MP4_Box_t ) );
1993 #ifdef VSLHC
1994             stream_t *p_mp4_stream = stream_MemoryNew( VLC_OBJECT(&sys.demuxer),
1995                                                        tracks[i_track]->p_extra_data,
1996                                                        tracks[i_track]->i_extra_data );
1997 #else
1998             stream_t *p_mp4_stream = stream_MemoryNew( VLC_OBJECT(&sys.demuxer),
1999                                                        tracks[i_track]->p_extra_data,
2000                                                        tracks[i_track]->i_extra_data,
2001                                                        VLC_FALSE );
2002 #endif
2003             MP4_ReadBoxCommon( p_mp4_stream, p_box );
2004             MP4_ReadBox_sample_vide( p_mp4_stream, p_box );
2005             tracks[i_track]->fmt.i_codec = p_box->i_type;
2006             tracks[i_track]->fmt.video.i_width = p_box->data.p_sample_vide->i_width;
2007             tracks[i_track]->fmt.video.i_height = p_box->data.p_sample_vide->i_height;
2008             tracks[i_track]->fmt.i_extra = p_box->data.p_sample_vide->i_qt_image_description;
2009             tracks[i_track]->fmt.p_extra = malloc( tracks[i_track]->fmt.i_extra );
2010             memcpy( tracks[i_track]->fmt.p_extra, p_box->data.p_sample_vide->p_qt_image_description, tracks[i_track]->fmt.i_extra );
2011             MP4_FreeBox_sample_vide( p_box );
2012 #ifdef VSLHC
2013             stream_MemoryDelete( p_mp4_stream, VLC_TRUE );
2014 #else
2015             stream_Delete( p_mp4_stream );
2016 #endif        
2017         }
2018         else if( !strcmp( tracks[i_track]->psz_codec, "A_MS/ACM" ) )
2019         {
2020             if( tracks[i_track]->i_extra_data < (int)sizeof( WAVEFORMATEX ) )
2021             {
2022                 msg_Err( &sys.demuxer, "missing/invalid WAVEFORMATEX" );
2023                 tracks[i_track]->fmt.i_codec = VLC_FOURCC( 'u', 'n', 'd', 'f' );
2024             }
2025             else
2026             {
2027                 WAVEFORMATEX *p_wf = (WAVEFORMATEX*)tracks[i_track]->p_extra_data;
2028
2029                 wf_tag_to_fourcc( GetWLE( &p_wf->wFormatTag ), &tracks[i_track]->fmt.i_codec, NULL );
2030
2031                 tracks[i_track]->fmt.audio.i_channels   = GetWLE( &p_wf->nChannels );
2032                 tracks[i_track]->fmt.audio.i_rate = GetDWLE( &p_wf->nSamplesPerSec );
2033                 tracks[i_track]->fmt.i_bitrate    = GetDWLE( &p_wf->nAvgBytesPerSec ) * 8;
2034                 tracks[i_track]->fmt.audio.i_blockalign = GetWLE( &p_wf->nBlockAlign );;
2035                 tracks[i_track]->fmt.audio.i_bitspersample = GetWLE( &p_wf->wBitsPerSample );
2036
2037                 tracks[i_track]->fmt.i_extra            = GetWLE( &p_wf->cbSize );
2038                 if( tracks[i_track]->fmt.i_extra > 0 )
2039                 {
2040                     tracks[i_track]->fmt.p_extra = malloc( tracks[i_track]->fmt.i_extra );
2041                     memcpy( tracks[i_track]->fmt.p_extra, &p_wf[1], tracks[i_track]->fmt.i_extra );
2042                 }
2043             }
2044         }
2045         else if( !strcmp( tracks[i_track]->psz_codec, "A_MPEG/L3" ) ||
2046                  !strcmp( tracks[i_track]->psz_codec, "A_MPEG/L2" ) ||
2047                  !strcmp( tracks[i_track]->psz_codec, "A_MPEG/L1" ) )
2048         {
2049             tracks[i_track]->fmt.i_codec = VLC_FOURCC( 'm', 'p', 'g', 'a' );
2050         }
2051         else if( !strcmp( tracks[i_track]->psz_codec, "A_AC3" ) )
2052         {
2053             tracks[i_track]->fmt.i_codec = VLC_FOURCC( 'a', '5', '2', ' ' );
2054         }
2055         else if( !strcmp( tracks[i_track]->psz_codec, "A_DTS" ) )
2056         {
2057             tracks[i_track]->fmt.i_codec = VLC_FOURCC( 'd', 't', 's', ' ' );
2058         }
2059         else if( !strcmp( tracks[i_track]->psz_codec, "A_FLAC" ) )
2060         {
2061             tracks[i_track]->fmt.i_codec = VLC_FOURCC( 'f', 'l', 'a', 'c' );
2062             tracks[i_track]->fmt.i_extra = tracks[i_track]->i_extra_data;
2063             tracks[i_track]->fmt.p_extra = malloc( tracks[i_track]->i_extra_data );
2064             memcpy( tracks[i_track]->fmt.p_extra,tracks[i_track]->p_extra_data, tracks[i_track]->i_extra_data );
2065         }
2066         else if( !strcmp( tracks[i_track]->psz_codec, "A_VORBIS" ) )
2067         {
2068             int i, i_offset = 1, i_size[3], i_extra;
2069             uint8_t *p_extra;
2070
2071             tracks[i_track]->fmt.i_codec = VLC_FOURCC( 'v', 'o', 'r', 'b' );
2072
2073             /* Split the 3 headers */
2074             if( tracks[i_track]->p_extra_data[0] != 0x02 )
2075                 msg_Err( &sys.demuxer, "invalid vorbis header" );
2076
2077             for( i = 0; i < 2; i++ )
2078             {
2079                 i_size[i] = 0;
2080                 while( i_offset < tracks[i_track]->i_extra_data )
2081                 {
2082                     i_size[i] += tracks[i_track]->p_extra_data[i_offset];
2083                     if( tracks[i_track]->p_extra_data[i_offset++] != 0xff ) break;
2084                 }
2085             }
2086
2087             i_size[0] = __MIN(i_size[0], tracks[i_track]->i_extra_data - i_offset);
2088             i_size[1] = __MIN(i_size[1], tracks[i_track]->i_extra_data -i_offset -i_size[0]);
2089             i_size[2] = tracks[i_track]->i_extra_data - i_offset - i_size[0] - i_size[1];
2090
2091             tracks[i_track]->fmt.i_extra = 3 * 2 + i_size[0] + i_size[1] + i_size[2];
2092             tracks[i_track]->fmt.p_extra = malloc( tracks[i_track]->fmt.i_extra );
2093             p_extra = (uint8_t *)tracks[i_track]->fmt.p_extra; i_extra = 0;
2094             for( i = 0; i < 3; i++ )
2095             {
2096                 *(p_extra++) = i_size[i] >> 8;
2097                 *(p_extra++) = i_size[i] & 0xFF;
2098                 memcpy( p_extra, tracks[i_track]->p_extra_data + i_offset + i_extra,
2099                         i_size[i] );
2100                 p_extra += i_size[i];
2101                 i_extra += i_size[i];
2102             }
2103         }
2104         else if( !strncmp( tracks[i_track]->psz_codec, "A_AAC/MPEG2/", strlen( "A_AAC/MPEG2/" ) ) ||
2105                  !strncmp( tracks[i_track]->psz_codec, "A_AAC/MPEG4/", strlen( "A_AAC/MPEG4/" ) ) )
2106         {
2107             int i_profile, i_srate;
2108             static unsigned int i_sample_rates[] =
2109             {
2110                     96000, 88200, 64000, 48000, 44100, 32000, 24000, 22050,
2111                         16000, 12000, 11025, 8000,  7350,  0,     0,     0
2112             };
2113
2114             tracks[i_track]->fmt.i_codec = VLC_FOURCC( 'm', 'p', '4', 'a' );
2115             /* create data for faad (MP4DecSpecificDescrTag)*/
2116
2117             if( !strcmp( &tracks[i_track]->psz_codec[12], "MAIN" ) )
2118             {
2119                 i_profile = 0;
2120             }
2121             else if( !strcmp( &tracks[i_track]->psz_codec[12], "LC" ) )
2122             {
2123                 i_profile = 1;
2124             }
2125             else if( !strcmp( &tracks[i_track]->psz_codec[12], "SSR" ) )
2126             {
2127                 i_profile = 2;
2128             }
2129             else
2130             {
2131                 i_profile = 3;
2132             }
2133
2134             for( i_srate = 0; i_srate < 13; i_srate++ )
2135             {
2136                 if( i_sample_rates[i_srate] == tracks[i_track]->fmt.audio.i_rate )
2137                 {
2138                     break;
2139                 }
2140             }
2141             msg_Dbg( &sys.demuxer, "profile=%d srate=%d", i_profile, i_srate );
2142
2143             tracks[i_track]->fmt.i_extra = 2;
2144             tracks[i_track]->fmt.p_extra = malloc( tracks[i_track]->fmt.i_extra );
2145             ((uint8_t*)tracks[i_track]->fmt.p_extra)[0] = ((i_profile + 1) << 3) | ((i_srate&0xe) >> 1);
2146             ((uint8_t*)tracks[i_track]->fmt.p_extra)[1] = ((i_srate & 0x1) << 7) | (tracks[i_track]->fmt.audio.i_channels << 3);
2147         }
2148         else if( !strcmp( tracks[i_track]->psz_codec, "A_PCM/INT/BIG" ) ||
2149                  !strcmp( tracks[i_track]->psz_codec, "A_PCM/INT/LIT" ) ||
2150                  !strcmp( tracks[i_track]->psz_codec, "A_PCM/FLOAT/IEEE" ) )
2151         {
2152             if( !strcmp( tracks[i_track]->psz_codec, "A_PCM/INT/BIG" ) )
2153             {
2154                 tracks[i_track]->fmt.i_codec = VLC_FOURCC( 't', 'w', 'o', 's' );
2155             }
2156             else
2157             {
2158                 tracks[i_track]->fmt.i_codec = VLC_FOURCC( 'a', 'r', 'a', 'w' );
2159             }
2160             tracks[i_track]->fmt.audio.i_blockalign = ( tracks[i_track]->fmt.audio.i_bitspersample + 7 ) / 8 * tracks[i_track]->fmt.audio.i_channels;
2161         }
2162         else if( !strcmp( tracks[i_track]->psz_codec, "A_TTA1" ) )
2163         {
2164             /* FIXME: support this codec */
2165             msg_Err( &sys.demuxer, "TTA not supported yet[%d, n=%d]", i_track, tracks[i_track]->i_number );
2166             tracks[i_track]->fmt.i_codec = VLC_FOURCC( 'u', 'n', 'd', 'f' );
2167         }
2168         else if( !strcmp( tracks[i_track]->psz_codec, "A_WAVPACK4" ) )
2169         {
2170             /* FIXME: support this codec */
2171             msg_Err( &sys.demuxer, "Wavpack not supported yet[%d, n=%d]", i_track, tracks[i_track]->i_number );
2172             tracks[i_track]->fmt.i_codec = VLC_FOURCC( 'u', 'n', 'd', 'f' );
2173         }
2174         else if( !strcmp( tracks[i_track]->psz_codec, "S_TEXT/UTF8" ) )
2175         {
2176             tracks[i_track]->fmt.i_codec = VLC_FOURCC( 's', 'u', 'b', 't' );
2177             tracks[i_track]->fmt.subs.psz_encoding = strdup( "UTF-8" );
2178         }
2179         else if( !strcmp( tracks[i_track]->psz_codec, "S_TEXT/SSA" ) ||
2180                  !strcmp( tracks[i_track]->psz_codec, "S_TEXT/ASS" ) ||
2181                  !strcmp( tracks[i_track]->psz_codec, "S_SSA" ) ||
2182                  !strcmp( tracks[i_track]->psz_codec, "S_ASS" ))
2183         {
2184             tracks[i_track]->fmt.i_codec = VLC_FOURCC( 's', 's', 'a', ' ' );
2185             tracks[i_track]->fmt.subs.psz_encoding = strdup( "UTF-8" );
2186         }
2187         else if( !strcmp( tracks[i_track]->psz_codec, "S_VOBSUB" ) )
2188         {
2189             tracks[i_track]->fmt.i_codec = VLC_FOURCC( 's','p','u',' ' );
2190             if( tracks[i_track]->i_extra_data )
2191             {
2192                 char *p_start;
2193                 char *p_buf = (char *)malloc( tracks[i_track]->i_extra_data + 1);
2194                 memcpy( p_buf, tracks[i_track]->p_extra_data , tracks[i_track]->i_extra_data );
2195                 p_buf[tracks[i_track]->i_extra_data] = '\0';
2196                 
2197                 p_start = strstr( p_buf, "size:" );
2198                 if( sscanf( p_start, "size: %dx%d",
2199                         &tracks[i_track]->fmt.subs.spu.i_original_frame_width, &tracks[i_track]->fmt.subs.spu.i_original_frame_height ) == 2 )
2200                 {
2201                     msg_Dbg( &sys.demuxer, "original frame size vobsubs: %dx%d", tracks[i_track]->fmt.subs.spu.i_original_frame_width, tracks[i_track]->fmt.subs.spu.i_original_frame_height );
2202                 }
2203                 else
2204                 {
2205                     msg_Warn( &sys.demuxer, "reading original frame size for vobsub failed" );
2206                 }
2207                 free( p_buf );
2208             }
2209         }
2210         else if( !strcmp( tracks[i_track]->psz_codec, "B_VOBBTN" ) )
2211         {
2212             tracks[i_track]->fmt.i_codec = VLC_FOURCC( 's','p','u',' ' );
2213             sys.StartUiThread();
2214         }
2215         else
2216         {
2217             msg_Err( &sys.demuxer, "unknow codec id=`%s'", tracks[i_track]->psz_codec );
2218             tracks[i_track]->fmt.i_codec = VLC_FOURCC( 'u', 'n', 'd', 'f' );
2219         }
2220         if( tracks[i_track]->b_default )
2221         {
2222             tracks[i_track]->fmt.i_priority = 1000;
2223         }
2224
2225         tracks[i_track]->p_es = es_out_Add( sys.demuxer.out, &tracks[i_track]->fmt );
2226
2227         es_out_Control( sys.demuxer.out, ES_OUT_SET_NEXT_DISPLAY_TIME, tracks[i_track]->p_es, i_start_time );
2228     }
2229     
2230     sys.i_start_pts = i_start_time;
2231     // reset the stream reading to the first cluster of the segment used
2232     es.I_O().setFilePointer( i_start_pos );
2233
2234     delete ep;
2235     ep = new EbmlParser( &es, segment, &sys.demuxer );
2236
2237     return true;
2238 }
2239
2240 void demux_sys_t::StartUiThread()
2241 {
2242     if ( !b_ui_hooked )
2243     {
2244         msg_Dbg( &demuxer, "Starting the UI Hook" );
2245         b_ui_hooked = true;
2246         /* FIXME hack hack hack hack FIXME */
2247         /* Get p_input and create variable */
2248         p_input = (input_thread_t *) vlc_object_find( &demuxer, VLC_OBJECT_INPUT, FIND_PARENT );
2249         var_Create( p_input, "x-start", VLC_VAR_INTEGER );
2250         var_Create( p_input, "y-start", VLC_VAR_INTEGER );
2251         var_Create( p_input, "x-end", VLC_VAR_INTEGER );
2252         var_Create( p_input, "y-end", VLC_VAR_INTEGER );
2253         var_Create( p_input, "color", VLC_VAR_ADDRESS );
2254         var_Create( p_input, "menu-contrast", VLC_VAR_ADDRESS );
2255         var_Create( p_input, "highlight", VLC_VAR_BOOL );
2256         var_Create( p_input, "highlight-mutex", VLC_VAR_MUTEX );
2257
2258         /* Now create our event thread catcher */
2259         p_ev = (event_thread_t *) vlc_object_create( &demuxer, sizeof( event_thread_t ) );
2260         p_ev->p_demux = &demuxer;
2261         vlc_mutex_init( p_ev, &p_ev->lock );
2262         vlc_thread_create( p_ev, "mkv event thread handler", EventThread,
2263                         VLC_THREAD_PRIORITY_LOW, VLC_FALSE );
2264     }
2265 }
2266
2267 void demux_sys_t::StopUiThread()
2268 {
2269     if ( b_ui_hooked )
2270     {
2271         p_ev->b_die = VLC_TRUE;
2272
2273         var_Destroy( p_input, "highlight-mutex" );
2274         var_Destroy( p_input, "highlight" );
2275         var_Destroy( p_input, "x-start" );
2276         var_Destroy( p_input, "x-end" );
2277         var_Destroy( p_input, "y-start" );
2278         var_Destroy( p_input, "y-end" );
2279         var_Destroy( p_input, "color" );
2280         var_Destroy( p_input, "menu-contrast" );
2281
2282         vlc_thread_join( p_ev );
2283         vlc_object_destroy( p_ev );
2284
2285         msg_Dbg( &demuxer, "Stopping the UI Hook" );
2286     }
2287     b_ui_hooked = false;
2288 }
2289
2290 int demux_sys_t::EventMouse( vlc_object_t *p_this, char const *psz_var,
2291                        vlc_value_t oldval, vlc_value_t newval, void *p_data )
2292 {
2293     event_thread_t *p_ev = (event_thread_t *) p_data;
2294     vlc_mutex_lock( &p_ev->lock );
2295     if( psz_var[6] == 'c' )
2296         p_ev->b_clicked = VLC_TRUE;
2297     else if( psz_var[6] == 'm' )
2298         p_ev->b_moved = VLC_TRUE;
2299     vlc_mutex_unlock( &p_ev->lock );
2300
2301     return VLC_SUCCESS;
2302 }
2303
2304 int demux_sys_t::EventKey( vlc_object_t *p_this, char const *psz_var,
2305                      vlc_value_t oldval, vlc_value_t newval, void *p_data )
2306 {
2307     event_thread_t *p_ev = (event_thread_t *) p_data;
2308     vlc_mutex_lock( &p_ev->lock );
2309     p_ev->b_key = VLC_TRUE;
2310     vlc_mutex_unlock( &p_ev->lock );
2311
2312     return VLC_SUCCESS;
2313 }
2314
2315 int demux_sys_t::EventThread( vlc_object_t *p_this )
2316 {
2317     event_thread_t *p_ev = (event_thread_t*)p_this;
2318     demux_sys_t    *p_sys = p_ev->p_demux->p_sys;
2319     vlc_object_t   *p_vout = NULL;
2320
2321     p_ev->b_moved   = VLC_FALSE;
2322     p_ev->b_clicked = VLC_FALSE;
2323     p_ev->b_key     = VLC_FALSE;
2324
2325     /* catch all key event */
2326     var_AddCallback( p_ev->p_vlc, "key-pressed", EventKey, p_ev );
2327
2328     /* main loop */
2329     while( !p_ev->b_die )
2330     {
2331         vlc_bool_t b_activated = VLC_FALSE;
2332
2333         /* KEY part */
2334         if( p_ev->b_key )
2335         {
2336             vlc_value_t valk;
2337             struct vlc_t::hotkey *p_hotkeys = p_ev->p_vlc->p_hotkeys;
2338             int i, i_action = -1;
2339
2340             vlc_mutex_lock( &p_ev->lock );
2341
2342             pci_t *pci = (pci_t *) &p_sys->pci_packet;
2343
2344             var_Get( p_ev->p_vlc, "key-pressed", &valk );
2345             for( i = 0; p_hotkeys[i].psz_action != NULL; i++ )
2346             {
2347                 if( p_hotkeys[i].i_key == valk.i_int )
2348                 {
2349                     i_action = p_hotkeys[i].i_action;
2350                 }
2351             }
2352
2353             switch( i_action )
2354             {
2355             case ACTIONID_NAV_LEFT:
2356 //                dvdnav_left_button_select( NULL, pci );
2357                 break;
2358             case ACTIONID_NAV_RIGHT:
2359 //                dvdnav_right_button_select( NULL, pci );
2360                 break;
2361             case ACTIONID_NAV_UP:
2362 //                dvdnav_upper_button_select( NULL, pci );
2363                 break;
2364             case ACTIONID_NAV_DOWN:
2365 //                dvdnav_lower_button_select( NULL, pci );
2366                 break;
2367             case ACTIONID_NAV_ACTIVATE:
2368                 b_activated = VLC_TRUE;
2369 //                dvdnav_button_activate( NULL, pci );
2370                 break;
2371             default:
2372                 break;
2373             }
2374             p_ev->b_key = VLC_FALSE;
2375             vlc_mutex_unlock( &p_ev->lock );
2376         }
2377
2378         /* VOUT part */
2379         if( p_vout && ( p_ev->b_moved || p_ev->b_clicked ) )
2380         {
2381             vlc_value_t valx, valy;
2382
2383             vlc_mutex_lock( &p_ev->lock );
2384             pci_t *pci = (pci_t *) &p_sys->pci_packet;
2385             var_Get( p_vout, "mouse-x", &valx );
2386             var_Get( p_vout, "mouse-y", &valy );
2387
2388             if( p_ev->b_moved )
2389             {
2390 //                dvdnav_mouse_select( NULL, pci, valx.i_int, valy.i_int );
2391                 p_ev->b_moved = 0;
2392             }
2393             if( p_ev->b_clicked )
2394             {
2395                 int32_t button;
2396                 int32_t best,dist,d;
2397                 int32_t mx,my,dx,dy;
2398
2399                 b_activated = VLC_TRUE;
2400                 // get current button
2401                 best = 0;
2402                 dist = 0x08000000; /* >> than  (720*720)+(567*567); */
2403                 for(button = 1; button <= pci->hli.hl_gi.btn_ns; button++) {
2404                     btni_t *button_ptr = &(pci->hli.btnit[button-1]);
2405
2406                     if((valx.i_int >= button_ptr->x_start) && (valx.i_int <= button_ptr->x_end) &&
2407                        (valy.i_int >= button_ptr->y_start) && (valy.i_int <= button_ptr->y_end)) 
2408                     {
2409                         mx = (button_ptr->x_start + button_ptr->x_end)/2;
2410                         my = (button_ptr->y_start + button_ptr->y_end)/2;
2411                         dx = mx - valx.i_int;
2412                         dy = my - valy.i_int;
2413                         d = (dx*dx) + (dy*dy);
2414                         /* If the mouse is within the button and the mouse is closer
2415                         * to the center of this button then it is the best choice. */
2416                         if(d < dist) {
2417                             dist = d;
2418                             best = button;
2419                         }
2420                     }
2421                 }
2422                 // select new button
2423                 if ( best != 0 && best != p_sys->i_curr_button )
2424                 {
2425                     vlc_value_t val;
2426                     btni_t *button_ptr = &(pci->hli.btnit[best-1]);
2427
2428                     p_sys->dvd_interpretor.SetSPRM( 0x88, best );
2429
2430                     // process the button action
2431                     if ( !p_sys->dvd_interpretor.Interpret( button_ptr->cmd.bytes, 8 ) )
2432                     {
2433                         if( var_Get( p_sys->p_input, "highlight-mutex", &val ) == VLC_SUCCESS )
2434                         {
2435                             vlc_mutex_t *p_mutex = (vlc_mutex_t *) val.p_address;
2436                             btni_t *button_ptr = &(pci->hli.btnit[best-1]);
2437                             uint32_t i_palette;
2438
2439                             if(button_ptr->btn_coln != 0) {
2440                                 i_palette = pci->hli.btn_colit.btn_coli[button_ptr->btn_coln-1][1];
2441                             } else {
2442                                 i_palette = 0;
2443                             }
2444                             p_sys->alpha[0] = i_palette      & 0x0f;
2445                             p_sys->alpha[1] = (i_palette>>4) & 0x0f;
2446                             p_sys->alpha[2] = (i_palette>>8) & 0x0f;
2447                             p_sys->alpha[3] = (i_palette>>12)& 0x0f;
2448
2449                             vlc_mutex_lock( p_mutex );
2450                             val.i_int = button_ptr->x_start; var_Set( p_sys->p_input, "x-start", val );
2451                             val.i_int = button_ptr->x_end;   var_Set( p_sys->p_input, "x-end",   val );
2452                             val.i_int = button_ptr->y_start; var_Set( p_sys->p_input, "y-start", val );
2453                             val.i_int = button_ptr->y_end;   var_Set( p_sys->p_input, "y-end",   val );
2454
2455                             val.p_address = (void *)p_sys->alpha;
2456                             var_Set( p_sys->p_input, "menu-contrast", val );
2457
2458                             val.b_bool = VLC_TRUE; var_Set( p_sys->p_input, "highlight", val );
2459                             vlc_mutex_unlock( p_mutex );
2460
2461                             p_sys->i_curr_button = best;
2462                             msg_Dbg( &p_sys->demuxer, "Selected button %d", best );
2463                         }
2464                     }
2465                 }
2466             }
2467
2468             p_ev->b_moved = VLC_FALSE;
2469             p_ev->b_clicked = VLC_FALSE;
2470             vlc_mutex_unlock( &p_ev->lock );
2471         }
2472
2473         if( p_vout && p_vout->b_die )
2474         {
2475             var_DelCallback( p_vout, "mouse-moved", EventMouse, p_ev );
2476             var_DelCallback( p_vout, "mouse-clicked", EventMouse, p_ev );
2477             vlc_object_release( p_vout );
2478             p_vout = NULL;
2479         }
2480
2481         if( p_vout == NULL )
2482         {
2483             p_vout = (vlc_object_t*) vlc_object_find( p_sys->p_input, VLC_OBJECT_VOUT,
2484                                       FIND_CHILD );
2485             if( p_vout)
2486             {
2487                 var_AddCallback( p_vout, "mouse-moved", EventMouse, p_ev );
2488                 var_AddCallback( p_vout, "mouse-clicked", EventMouse, p_ev );
2489             }
2490         }
2491
2492         /* Wait a bit */
2493         msleep( 10000 );
2494     }
2495
2496     /* Release callback */
2497     if( p_vout )
2498     {
2499         var_DelCallback( p_vout, "mouse-moved", EventMouse, p_ev );
2500         var_DelCallback( p_vout, "mouse-clicked", EventMouse, p_ev );
2501         vlc_object_release( p_vout );
2502     }
2503     var_DelCallback( p_ev->p_vlc, "key-pressed", EventKey, p_ev );
2504
2505     vlc_mutex_destroy( &p_ev->lock );
2506
2507     return VLC_SUCCESS;
2508 }
2509
2510 void matroska_segment_c::UnSelect( )
2511 {
2512     size_t i_track;
2513
2514     sys.StopUiThread();
2515
2516     for( i_track = 0; i_track < tracks.size(); i_track++ )
2517     {
2518         if ( tracks[i_track]->p_es != NULL )
2519         {
2520             es_out_Del( sys.demuxer.out, tracks[i_track]->p_es );
2521             tracks[i_track]->p_es = NULL;
2522         }
2523     }
2524     delete ep;
2525     ep = NULL;
2526 }
2527
2528 void virtual_segment_c::PrepareChapters( )
2529 {
2530     if ( linked_segments.size() == 0 )
2531         return;
2532
2533     // !!! should be called only once !!!
2534     matroska_segment_c *p_segment;
2535     size_t i, j;
2536
2537     // copy editions from the first segment
2538     p_segment = linked_segments[0];
2539     p_editions = &p_segment->stored_editions;
2540
2541     for ( i=1 ; i<linked_segments.size(); i++ )
2542     {
2543         p_segment = linked_segments[i];
2544         // FIXME assume we have the same editions in all segments
2545         for (j=0; j<p_segment->stored_editions.size(); j++)
2546             (*p_editions)[j]->Append( *p_segment->stored_editions[j] );
2547     }
2548 }
2549
2550 std::string chapter_edition_c::GetMainName() const
2551 {
2552     if ( sub_chapters.size() )
2553     {
2554         return sub_chapters[0]->GetCodecName( true );
2555     }
2556     return "";
2557 }
2558
2559 int chapter_item_c::PublishChapters( input_title_t & title, int & i_user_chapters, int i_level )
2560 {
2561     // add support for meta-elements from codec like DVD Titles
2562     if ( !b_display_seekpoint || psz_name == "" )
2563     {
2564         psz_name = GetCodecName();
2565         if ( psz_name != "" )
2566             b_display_seekpoint = true;
2567     }
2568
2569     if (b_display_seekpoint)
2570     {
2571         seekpoint_t *sk = vlc_seekpoint_New();
2572
2573         sk->i_level = i_level;
2574         sk->i_time_offset = i_start_time;
2575         sk->psz_name = strdup( psz_name.c_str() );
2576
2577         // A start time of '0' is ok. A missing ChapterTime element is ok, too, because '0' is its default value.
2578         title.i_seekpoint++;
2579         title.seekpoint = (seekpoint_t**)realloc( title.seekpoint, title.i_seekpoint * sizeof( seekpoint_t* ) );
2580         title.seekpoint[title.i_seekpoint-1] = sk;
2581
2582         if ( b_user_display )
2583             i_user_chapters++;
2584     }
2585
2586     for ( size_t i=0; i<sub_chapters.size() ; i++)
2587     {
2588         sub_chapters[i]->PublishChapters( title, i_user_chapters, i_level+1 );
2589     }
2590
2591     i_seekpoint_num = i_user_chapters;
2592
2593     return i_user_chapters;
2594 }
2595
2596 bool virtual_segment_c::UpdateCurrentToChapter( demux_t & demux )
2597 {
2598     demux_sys_t & sys = *demux.p_sys;
2599     chapter_item_c *psz_curr_chapter;
2600
2601     /* update current chapter/seekpoint */
2602     if ( p_editions->size() )
2603     {
2604         /* 1st, we need to know in which chapter we are */
2605         psz_curr_chapter = (*p_editions)[i_current_edition]->FindTimecode( sys.i_pts );
2606
2607         /* we have moved to a new chapter */
2608         if (psz_curr_chapter != NULL && psz_current_chapter != psz_curr_chapter)
2609         {
2610             if ( (*p_editions)[i_current_edition]->b_ordered )
2611             {
2612                 // Leave/Enter up to the link point
2613                 if ( !psz_curr_chapter->EnterAndLeave( psz_current_chapter ) )
2614                 {
2615                     // only seek if necessary
2616                     if ( psz_current_chapter == NULL || (psz_current_chapter->i_end_time != psz_curr_chapter->i_start_time) )
2617                         Seek( demux, sys.i_pts, 0, psz_curr_chapter );
2618                     psz_current_chapter = psz_curr_chapter;
2619                 }
2620             }
2621             else if ( psz_curr_chapter->i_seekpoint_num > 0 )
2622             {
2623                 demux.info.i_update |= INPUT_UPDATE_TITLE | INPUT_UPDATE_SEEKPOINT;
2624                 demux.info.i_title = sys.i_current_title = i_sys_title;
2625                 demux.info.i_seekpoint = psz_curr_chapter->i_seekpoint_num - 1;
2626                 psz_current_chapter = psz_curr_chapter;
2627             }
2628             else
2629             {
2630                 psz_current_chapter = psz_curr_chapter;
2631             }
2632
2633             return true;
2634         }
2635     }
2636     return false;
2637 }
2638
2639 chapter_item_c *virtual_segment_c::BrowseCodecPrivate( unsigned int codec_id, 
2640                                     bool (*match)(const chapter_codec_cmds_c &data, const void *p_cookie, size_t i_cookie_size ), 
2641                                     const void *p_cookie, 
2642                                     size_t i_cookie_size )
2643 {
2644     // FIXME don't assume it is the first edition
2645     std::vector<chapter_edition_c*>::iterator index = p_editions->begin();
2646     if ( index != p_editions->end() )
2647     {
2648         chapter_item_c *p_result = (*index)->BrowseCodecPrivate( codec_id, match, p_cookie, i_cookie_size );
2649         if ( p_result != NULL )
2650             return p_result;
2651     }
2652     return NULL;
2653 }
2654
2655 chapter_item_c *virtual_segment_c::FindChapter( int64_t i_find_uid )
2656 {
2657     // FIXME don't assume it is the first edition
2658     std::vector<chapter_edition_c*>::iterator index = p_editions->begin();
2659     if ( index != p_editions->end() )
2660     {
2661         chapter_item_c *p_result = (*index)->FindChapter( i_find_uid );
2662         if ( p_result != NULL )
2663             return p_result;
2664     }
2665     return NULL;
2666 }
2667
2668 chapter_item_c *chapter_item_c::BrowseCodecPrivate( unsigned int codec_id, 
2669                                     bool (*match)(const chapter_codec_cmds_c &data, const void *p_cookie, size_t i_cookie_size ), 
2670                                     const void *p_cookie, 
2671                                     size_t i_cookie_size )
2672 {
2673     // this chapter
2674     std::vector<chapter_codec_cmds_c*>::const_iterator index = codecs.begin();
2675     while ( index != codecs.end() )
2676     {
2677         if ( match( **index ,p_cookie, i_cookie_size ) )
2678             return this;
2679         index++;
2680     }
2681     
2682     // sub-chapters
2683     chapter_item_c *p_result = NULL;
2684     std::vector<chapter_item_c*>::const_iterator index2 = sub_chapters.begin();
2685     while ( index2 != sub_chapters.end() )
2686     {
2687         p_result = (*index2)->BrowseCodecPrivate( codec_id, match, p_cookie, i_cookie_size );
2688         if ( p_result != NULL )
2689             return p_result;
2690         index2++;
2691     }
2692     
2693     return p_result;
2694 }
2695
2696 void chapter_item_c::Append( const chapter_item_c & chapter )
2697 {
2698     // we are appending content for the same chapter UID
2699     size_t i;
2700     chapter_item_c *p_chapter;
2701
2702     for ( i=0; i<chapter.sub_chapters.size(); i++ )
2703     {
2704         p_chapter = FindChapter( chapter.sub_chapters[i]->i_uid );
2705         if ( p_chapter != NULL )
2706         {
2707             p_chapter->Append( *chapter.sub_chapters[i] );
2708         }
2709         else
2710         {
2711             sub_chapters.push_back( chapter.sub_chapters[i] );
2712         }
2713     }
2714
2715     i_user_start_time = min( i_user_start_time, chapter.i_user_start_time );
2716     i_user_end_time = max( i_user_end_time, chapter.i_user_end_time );
2717 }
2718
2719 chapter_item_c * chapter_item_c::FindChapter( int64_t i_find_uid )
2720 {
2721     size_t i;
2722     chapter_item_c *p_result = NULL;
2723
2724     if ( i_uid == i_find_uid )
2725         return this;
2726
2727     for ( i=0; i<sub_chapters.size(); i++)
2728     {
2729         p_result = sub_chapters[i]->FindChapter( i_find_uid );
2730         if ( p_result != NULL )
2731             break;
2732     }
2733     return p_result;
2734 }
2735
2736 std::string chapter_item_c::GetCodecName( bool f_for_title ) const
2737 {
2738     std::string result;
2739
2740     std::vector<chapter_codec_cmds_c*>::const_iterator index = codecs.begin();
2741     while ( index != codecs.end() )
2742     {
2743         result = (*index)->GetCodecName( f_for_title );
2744         if ( result != "" )
2745             break;
2746         index++;
2747     }
2748
2749     return result;
2750 }
2751
2752 std::string dvd_chapter_codec_c::GetCodecName( bool f_for_title ) const
2753 {
2754     std::string result;
2755     if ( m_private_data.GetSize() >= 3)
2756     {
2757         const binary* p_data = m_private_data.GetBuffer();
2758 /*        if ( p_data[0] == MATROSKA_DVD_LEVEL_TT )
2759         {
2760             uint16_t i_title = (p_data[1] << 8) + p_data[2];
2761             char psz_str[11];
2762             sprintf( psz_str, " %d  ---", i_title );
2763             result = N_("---  DVD Title");
2764             result += psz_str;
2765         }
2766         else */ if ( p_data[0] == MATROSKA_DVD_LEVEL_LU )
2767         {
2768             char psz_str[11];
2769             sprintf( psz_str, " (%c%c)  ---", p_data[1], p_data[2] );
2770             result = N_("---  DVD Menu");
2771             result += psz_str;
2772         }
2773         else if ( p_data[0] == MATROSKA_DVD_LEVEL_SS && f_for_title )
2774         {
2775             if ( p_data[1] == 0x00 )
2776                 result = N_("First Played");
2777             else if ( p_data[1] == 0xC0 )
2778                 result = N_("Video Manager");
2779             else if ( p_data[1] == 0x80 )
2780             {
2781                 uint16_t i_title = (p_data[2] << 8) + p_data[3];
2782                 char psz_str[20];
2783                 sprintf( psz_str, " %d -----", i_title );
2784                 result = N_("----- Title");
2785                 result += psz_str;
2786             }
2787         }
2788     }
2789
2790     return result;
2791 }
2792
2793 static void Seek( demux_t *p_demux, mtime_t i_date, double f_percent, chapter_item_c *psz_chapter )
2794 {
2795     demux_sys_t        *p_sys = p_demux->p_sys;
2796     virtual_segment_c  *p_vsegment = p_sys->p_current_segment;
2797     matroska_segment_c *p_segment = p_vsegment->Segment();
2798     mtime_t            i_time_offset = 0;
2799
2800     int         i_index;
2801
2802     msg_Dbg( p_demux, "seek request to "I64Fd" (%f%%)", i_date, f_percent );
2803     if( i_date < 0 && f_percent < 0 )
2804     {
2805         msg_Warn( p_demux, "cannot seek nowhere !" );
2806         return;
2807     }
2808     if( f_percent > 1.0 )
2809     {
2810         msg_Warn( p_demux, "cannot seek so far !" );
2811         return;
2812     }
2813
2814     /* seek without index or without date */
2815     if( f_percent >= 0 && (config_GetInt( p_demux, "mkv-seek-percent" ) || !p_segment->b_cues || i_date < 0 ))
2816     {
2817         if (p_sys->f_duration >= 0)
2818         {
2819             i_date = int64_t( f_percent * p_sys->f_duration * 1000.0 );
2820         }
2821         else
2822         {
2823             int64_t i_pos = int64_t( f_percent * stream_Size( p_demux->s ) );
2824
2825             msg_Dbg( p_demux, "inacurate way of seeking" );
2826             for( i_index = 0; i_index < p_segment->i_index; i_index++ )
2827             {
2828                 if( p_segment->index[i_index].i_position >= i_pos)
2829                 {
2830                     break;
2831                 }
2832             }
2833             if( i_index == p_segment->i_index )
2834             {
2835                 i_index--;
2836             }
2837
2838             i_date = p_segment->index[i_index].i_time;
2839
2840 #if 0
2841             if( p_segment->index[i_index].i_position < i_pos )
2842             {
2843                 EbmlElement *el;
2844
2845                 msg_Warn( p_demux, "searching for cluster, could take some time" );
2846
2847                 /* search a cluster */
2848                 while( ( el = p_sys->ep->Get() ) != NULL )
2849                 {
2850                     if( MKV_IS_ID( el, KaxCluster ) )
2851                     {
2852                         KaxCluster *cluster = (KaxCluster*)el;
2853
2854                         /* add it to the index */
2855                         p_segment->IndexAppendCluster( cluster );
2856
2857                         if( (int64_t)cluster->GetElementPosition() >= i_pos )
2858                         {
2859                             p_sys->cluster = cluster;
2860                             p_sys->ep->Down();
2861                             break;
2862                         }
2863                     }
2864                 }
2865             }
2866 #endif
2867         }
2868     }
2869
2870     p_vsegment->Seek( *p_demux, i_date, i_time_offset, psz_chapter );
2871 }
2872
2873 /*****************************************************************************
2874  * Demux: reads and demuxes data packets
2875  *****************************************************************************
2876  * Returns -1 in case of error, 0 in case of EOF, 1 otherwise
2877  *****************************************************************************/
2878 static int Demux( demux_t *p_demux)
2879 {
2880     demux_sys_t        *p_sys = p_demux->p_sys;
2881     virtual_segment_c  *p_vsegment = p_sys->p_current_segment;
2882     matroska_segment_c *p_segmet = p_vsegment->Segment();
2883     if ( p_segmet == NULL ) return 0;
2884     int                i_block_count = 0;
2885
2886     KaxBlock *block;
2887     int64_t i_block_duration;
2888     int64_t i_block_ref1;
2889     int64_t i_block_ref2;
2890
2891     for( ;; )
2892     {
2893         if ( p_sys->demuxer.b_die )
2894             return 0;
2895
2896         if( p_sys->i_pts >= p_sys->i_start_pts  )
2897             if ( p_vsegment->UpdateCurrentToChapter( *p_demux ) )
2898                 return 1;
2899         
2900         if ( p_vsegment->Edition() && p_vsegment->Edition()->b_ordered && p_vsegment->CurrentChapter() == NULL )
2901         {
2902             /* nothing left to read in this ordered edition */
2903             if ( !p_vsegment->SelectNext() )
2904                 return 0;
2905             p_segmet->UnSelect( );
2906             
2907             es_out_Control( p_demux->out, ES_OUT_RESET_PCR );
2908
2909             /* switch to the next segment */
2910             p_segmet = p_vsegment->Segment();
2911             if ( !p_segmet->Select( 0 ) )
2912             {
2913                 msg_Err( p_demux, "Failed to select new segment" );
2914                 return 0;
2915             }
2916             continue;
2917         }
2918
2919
2920         if( p_segmet->BlockGet( &block, &i_block_ref1, &i_block_ref2, &i_block_duration ) )
2921         {
2922             if ( p_vsegment->Edition() && p_vsegment->Edition()->b_ordered )
2923             {
2924                 const chapter_item_c *p_chap = p_vsegment->CurrentChapter();
2925                 // check if there are more chapters to read
2926                 if ( p_chap != NULL )
2927                 {
2928                     /* TODO handle successive chapters with the same user_start_time/user_end_time
2929                     if ( p_chap->i_user_start_time == p_chap->i_user_start_time )
2930                         p_vsegment->SelectNext();
2931                     */
2932                     p_sys->i_pts = p_chap->i_user_end_time;
2933                     p_sys->i_pts++; // trick to avoid staying on segments with no duration and no content
2934
2935                     return 1;
2936                 }
2937
2938                 return 0;
2939             }
2940             msg_Warn( p_demux, "cannot get block EOF?" );
2941             p_segmet->UnSelect( );
2942             
2943             es_out_Control( p_demux->out, ES_OUT_RESET_PCR );
2944
2945             /* switch to the next segment */
2946             if ( !p_vsegment->SelectNext() )
2947                 // no more segments in this stream
2948                 return 0;
2949             p_segmet = p_vsegment->Segment();
2950             if ( !p_segmet->Select( 0 ) )
2951             {
2952                 msg_Err( p_demux, "Failed to select new segment" );
2953                 return 0;
2954             }
2955
2956             continue;
2957         }
2958
2959         p_sys->i_pts = p_sys->i_chapter_time + block->GlobalTimecode() / (mtime_t) 1000;
2960
2961         if( p_sys->i_pts >= p_sys->i_start_pts  )
2962         {
2963             es_out_Control( p_demux->out, ES_OUT_SET_PCR, p_sys->i_pts );
2964         }
2965
2966         BlockDecode( p_demux, block, p_sys->i_pts, i_block_duration );
2967
2968         delete block;
2969         i_block_count++;
2970
2971         // TODO optimize when there is need to leave or when seeking has been called
2972         if( i_block_count > 5 )
2973         {
2974             return 1;
2975         }
2976     }
2977 }
2978
2979
2980
2981 /*****************************************************************************
2982  * Stream managment
2983  *****************************************************************************/
2984 vlc_stream_io_callback::vlc_stream_io_callback( stream_t *s_ )
2985 {
2986     s = s_;
2987     mb_eof = VLC_FALSE;
2988 }
2989
2990 uint32 vlc_stream_io_callback::read( void *p_buffer, size_t i_size )
2991 {
2992     if( i_size <= 0 || mb_eof )
2993     {
2994         return 0;
2995     }
2996
2997     return stream_Read( s, p_buffer, i_size );
2998 }
2999 void vlc_stream_io_callback::setFilePointer(int64_t i_offset, seek_mode mode )
3000 {
3001     int64_t i_pos;
3002
3003     switch( mode )
3004     {
3005         case seek_beginning:
3006             i_pos = i_offset;
3007             break;
3008         case seek_end:
3009             i_pos = stream_Size( s ) - i_offset;
3010             break;
3011         default:
3012             i_pos= stream_Tell( s ) + i_offset;
3013             break;
3014     }
3015
3016     if( i_pos < 0 || i_pos >= stream_Size( s ) )
3017     {
3018         mb_eof = VLC_TRUE;
3019         return;
3020     }
3021
3022     mb_eof = VLC_FALSE;
3023     if( stream_Seek( s, i_pos ) )
3024     {
3025         mb_eof = VLC_TRUE;
3026     }
3027     return;
3028 }
3029 size_t vlc_stream_io_callback::write( const void *p_buffer, size_t i_size )
3030 {
3031     return 0;
3032 }
3033 uint64 vlc_stream_io_callback::getFilePointer( void )
3034 {
3035     return stream_Tell( s );
3036 }
3037 void vlc_stream_io_callback::close( void )
3038 {
3039     return;
3040 }
3041
3042
3043 /*****************************************************************************
3044  * Ebml Stream parser
3045  *****************************************************************************/
3046 EbmlParser::EbmlParser( EbmlStream *es, EbmlElement *el_start, demux_t *p_demux )
3047 {
3048     int i;
3049
3050     m_es = es;
3051     m_got = NULL;
3052     m_el[0] = el_start;
3053     mi_remain_size[0] = el_start->GetSize();
3054
3055     for( i = 1; i < 6; i++ )
3056     {
3057         m_el[i] = NULL;
3058     }
3059     mi_level = 1;
3060     mi_user_level = 1;
3061     mb_keep = VLC_FALSE;
3062     mb_dummy = config_GetInt( p_demux, "mkv-use-dummy" );
3063 }
3064
3065 EbmlParser::~EbmlParser( void )
3066 {
3067     int i;
3068
3069     for( i = 1; i < mi_level; i++ )
3070     {
3071         if( !mb_keep )
3072         {
3073             delete m_el[i];
3074         }
3075         mb_keep = VLC_FALSE;
3076     }
3077 }
3078
3079 void EbmlParser::Up( void )
3080 {
3081     if( mi_user_level == mi_level )
3082     {
3083         fprintf( stderr," arrrrrrrrrrrrrg Up cannot escape itself\n" );
3084     }
3085
3086     mi_user_level--;
3087 }
3088
3089 void EbmlParser::Down( void )
3090 {
3091     mi_user_level++;
3092     mi_level++;
3093 }
3094
3095 void EbmlParser::Keep( void )
3096 {
3097     mb_keep = VLC_TRUE;
3098 }
3099
3100 int EbmlParser::GetLevel( void )
3101 {
3102     return mi_user_level;
3103 }
3104
3105 void EbmlParser::Reset( demux_t *p_demux )
3106 {
3107     while ( mi_level > 0)
3108     {
3109         delete m_el[mi_level];
3110         m_el[mi_level] = NULL;
3111         mi_level--;
3112     }
3113     mi_user_level = mi_level = 1;
3114 #if LIBEBML_VERSION >= 0x000704
3115     // a little faster and cleaner
3116     m_es->I_O().setFilePointer( static_cast<KaxSegment*>(m_el[0])->GetGlobalPosition(0) );
3117 #else
3118     m_es->I_O().setFilePointer( m_el[0]->GetElementPosition() + m_el[0]->ElementSize(true) - m_el[0]->GetSize() );
3119 #endif
3120     mb_dummy = config_GetInt( p_demux, "mkv-use-dummy" );
3121 }
3122
3123 EbmlElement *EbmlParser::Get( void )
3124 {
3125     int i_ulev = 0;
3126
3127     if( mi_user_level != mi_level )
3128     {
3129         return NULL;
3130     }
3131     if( m_got )
3132     {
3133         EbmlElement *ret = m_got;
3134         m_got = NULL;
3135
3136         return ret;
3137     }
3138
3139     if( m_el[mi_level] )
3140     {
3141         m_el[mi_level]->SkipData( *m_es, m_el[mi_level]->Generic().Context );
3142         if( !mb_keep )
3143         {
3144             delete m_el[mi_level];
3145         }
3146         mb_keep = VLC_FALSE;
3147     }
3148
3149     m_el[mi_level] = m_es->FindNextElement( m_el[mi_level - 1]->Generic().Context, i_ulev, 0xFFFFFFFFL, mb_dummy, 1 );
3150 //    mi_remain_size[mi_level] = m_el[mi_level]->GetSize();
3151     if( i_ulev > 0 )
3152     {
3153         while( i_ulev > 0 )
3154         {
3155             if( mi_level == 1 )
3156             {
3157                 mi_level = 0;
3158                 return NULL;
3159             }
3160
3161             delete m_el[mi_level - 1];
3162             m_got = m_el[mi_level -1] = m_el[mi_level];
3163             m_el[mi_level] = NULL;
3164
3165             mi_level--;
3166             i_ulev--;
3167         }
3168         return NULL;
3169     }
3170     else if( m_el[mi_level] == NULL )
3171     {
3172         fprintf( stderr," m_el[mi_level] == NULL\n" );
3173     }
3174
3175     return m_el[mi_level];
3176 }
3177
3178
3179 /*****************************************************************************
3180  * Tools
3181  *  * LoadCues : load the cues element and update index
3182  *
3183  *  * LoadTags : load ... the tags element
3184  *
3185  *  * InformationCreate : create all information, load tags if present
3186  *
3187  *****************************************************************************/
3188 void matroska_segment_c::LoadCues( )
3189 {
3190     int64_t     i_sav_position = es.I_O().getFilePointer();
3191     EbmlParser  *ep;
3192     EbmlElement *el, *cues;
3193
3194     /* *** Load the cue if found *** */
3195     if( i_cues_position < 0 )
3196     {
3197         msg_Warn( &sys.demuxer, "no cues/empty cues found->seek won't be precise" );
3198
3199 //        IndexAppendCluster( cluster );
3200     }
3201
3202     vlc_bool_t b_seekable;
3203
3204     stream_Control( sys.demuxer.s, STREAM_CAN_FASTSEEK, &b_seekable );
3205     if( !b_seekable )
3206         return;
3207
3208     msg_Dbg( &sys.demuxer, "loading cues" );
3209     es.I_O().setFilePointer( i_cues_position, seek_beginning );
3210     cues = es.FindNextID( KaxCues::ClassInfos, 0xFFFFFFFFL);
3211
3212     if( cues == NULL )
3213     {
3214         msg_Err( &sys.demuxer, "cannot load cues (broken seekhead or file)" );
3215         es.I_O().setFilePointer( i_sav_position, seek_beginning );
3216         return;
3217     }
3218
3219     ep = new EbmlParser( &es, cues, &sys.demuxer );
3220     while( ( el = ep->Get() ) != NULL )
3221     {
3222         if( MKV_IS_ID( el, KaxCuePoint ) )
3223         {
3224 #define idx index[i_index]
3225
3226             idx.i_track       = -1;
3227             idx.i_block_number= -1;
3228             idx.i_position    = -1;
3229             idx.i_time        = 0;
3230             idx.b_key         = VLC_TRUE;
3231
3232             ep->Down();
3233             while( ( el = ep->Get() ) != NULL )
3234             {
3235                 if( MKV_IS_ID( el, KaxCueTime ) )
3236                 {
3237                     KaxCueTime &ctime = *(KaxCueTime*)el;
3238
3239                     ctime.ReadData( es.I_O() );
3240
3241                     idx.i_time = uint64( ctime ) * i_timescale / (mtime_t)1000;
3242                 }
3243                 else if( MKV_IS_ID( el, KaxCueTrackPositions ) )
3244                 {
3245                     ep->Down();
3246                     while( ( el = ep->Get() ) != NULL )
3247                     {
3248                         if( MKV_IS_ID( el, KaxCueTrack ) )
3249                         {
3250                             KaxCueTrack &ctrack = *(KaxCueTrack*)el;
3251
3252                             ctrack.ReadData( es.I_O() );
3253                             idx.i_track = uint16( ctrack );
3254                         }
3255                         else if( MKV_IS_ID( el, KaxCueClusterPosition ) )
3256                         {
3257                             KaxCueClusterPosition &ccpos = *(KaxCueClusterPosition*)el;
3258
3259                             ccpos.ReadData( es.I_O() );
3260                             idx.i_position = segment->GetGlobalPosition( uint64( ccpos ) );
3261                         }
3262                         else if( MKV_IS_ID( el, KaxCueBlockNumber ) )
3263                         {
3264                             KaxCueBlockNumber &cbnum = *(KaxCueBlockNumber*)el;
3265
3266                             cbnum.ReadData( es.I_O() );
3267                             idx.i_block_number = uint32( cbnum );
3268                         }
3269                         else
3270                         {
3271                             msg_Dbg( &sys.demuxer, "         * Unknown (%s)", typeid(*el).name() );
3272                         }
3273                     }
3274                     ep->Up();
3275                 }
3276                 else
3277                 {
3278                     msg_Dbg( &sys.demuxer, "     * Unknown (%s)", typeid(*el).name() );
3279                 }
3280             }
3281             ep->Up();
3282
3283 #if 0
3284             msg_Dbg( &sys.demuxer, " * added time="I64Fd" pos="I64Fd
3285                      " track=%d bnum=%d", idx.i_time, idx.i_position,
3286                      idx.i_track, idx.i_block_number );
3287 #endif
3288
3289             i_index++;
3290             if( i_index >= i_index_max )
3291             {
3292                 i_index_max += 1024;
3293                 index = (mkv_index_t*)realloc( index, sizeof( mkv_index_t ) * i_index_max );
3294             }
3295 #undef idx
3296         }
3297         else
3298         {
3299             msg_Dbg( &sys.demuxer, " * Unknown (%s)", typeid(*el).name() );
3300         }
3301     }
3302     delete ep;
3303     delete cues;
3304
3305     b_cues = VLC_TRUE;
3306
3307     msg_Dbg( &sys.demuxer, "loading cues done." );
3308     es.I_O().setFilePointer( i_sav_position, seek_beginning );
3309 }
3310
3311 void matroska_segment_c::LoadTags( )
3312 {
3313     int64_t     i_sav_position = es.I_O().getFilePointer();
3314     EbmlParser  *ep;
3315     EbmlElement *el, *tags;
3316
3317     msg_Dbg( &sys.demuxer, "loading tags" );
3318     es.I_O().setFilePointer( i_tags_position, seek_beginning );
3319     tags = es.FindNextID( KaxTags::ClassInfos, 0xFFFFFFFFL);
3320
3321     if( tags == NULL )
3322     {
3323         msg_Err( &sys.demuxer, "cannot load tags (broken seekhead or file)" );
3324         es.I_O().setFilePointer( i_sav_position, seek_beginning );
3325         return;
3326     }
3327
3328     msg_Dbg( &sys.demuxer, "Tags" );
3329     ep = new EbmlParser( &es, tags, &sys.demuxer );
3330     while( ( el = ep->Get() ) != NULL )
3331     {
3332         if( MKV_IS_ID( el, KaxTag ) )
3333         {
3334             msg_Dbg( &sys.demuxer, "+ Tag" );
3335             ep->Down();
3336             while( ( el = ep->Get() ) != NULL )
3337             {
3338                 if( MKV_IS_ID( el, KaxTagTargets ) )
3339                 {
3340                     msg_Dbg( &sys.demuxer, "|   + Targets" );
3341                     ep->Down();
3342                     while( ( el = ep->Get() ) != NULL )
3343                     {
3344                         msg_Dbg( &sys.demuxer, "|   |   + Unknown (%s)", typeid( *el ).name() );
3345                     }
3346                     ep->Up();
3347                 }
3348                 else if( MKV_IS_ID( el, KaxTagGeneral ) )
3349                 {
3350                     msg_Dbg( &sys.demuxer, "|   + General" );
3351                     ep->Down();
3352                     while( ( el = ep->Get() ) != NULL )
3353                     {
3354                         msg_Dbg( &sys.demuxer, "|   |   + Unknown (%s)", typeid( *el ).name() );
3355                     }
3356                     ep->Up();
3357                 }
3358                 else if( MKV_IS_ID( el, KaxTagGenres ) )
3359                 {
3360                     msg_Dbg( &sys.demuxer, "|   + Genres" );
3361                     ep->Down();
3362                     while( ( el = ep->Get() ) != NULL )
3363                     {
3364                         msg_Dbg( &sys.demuxer, "|   |   + Unknown (%s)", typeid( *el ).name() );
3365                     }
3366                     ep->Up();
3367                 }
3368                 else if( MKV_IS_ID( el, KaxTagAudioSpecific ) )
3369                 {
3370                     msg_Dbg( &sys.demuxer, "|   + Audio Specific" );
3371                     ep->Down();
3372                     while( ( el = ep->Get() ) != NULL )
3373                     {
3374                         msg_Dbg( &sys.demuxer, "|   |   + Unknown (%s)", typeid( *el ).name() );
3375                     }
3376                     ep->Up();
3377                 }
3378                 else if( MKV_IS_ID( el, KaxTagImageSpecific ) )
3379                 {
3380                     msg_Dbg( &sys.demuxer, "|   + Images Specific" );
3381                     ep->Down();
3382                     while( ( el = ep->Get() ) != NULL )
3383                     {
3384                         msg_Dbg( &sys.demuxer, "|   |   + Unknown (%s)", typeid( *el ).name() );
3385                     }
3386                     ep->Up();
3387                 }
3388                 else if( MKV_IS_ID( el, KaxTagMultiComment ) )
3389                 {
3390                     msg_Dbg( &sys.demuxer, "|   + Multi Comment" );
3391                 }
3392                 else if( MKV_IS_ID( el, KaxTagMultiCommercial ) )
3393                 {
3394                     msg_Dbg( &sys.demuxer, "|   + Multi Commercial" );
3395                 }
3396                 else if( MKV_IS_ID( el, KaxTagMultiDate ) )
3397                 {
3398                     msg_Dbg( &sys.demuxer, "|   + Multi Date" );
3399                 }
3400                 else if( MKV_IS_ID( el, KaxTagMultiEntity ) )
3401                 {
3402                     msg_Dbg( &sys.demuxer, "|   + Multi Entity" );
3403                 }
3404                 else if( MKV_IS_ID( el, KaxTagMultiIdentifier ) )
3405                 {
3406                     msg_Dbg( &sys.demuxer, "|   + Multi Identifier" );
3407                 }
3408                 else if( MKV_IS_ID( el, KaxTagMultiLegal ) )
3409                 {
3410                     msg_Dbg( &sys.demuxer, "|   + Multi Legal" );
3411                 }
3412                 else if( MKV_IS_ID( el, KaxTagMultiTitle ) )
3413                 {
3414                     msg_Dbg( &sys.demuxer, "|   + Multi Title" );
3415                 }
3416                 else
3417                 {
3418                     msg_Dbg( &sys.demuxer, "|   + Unknown (%s)", typeid( *el ).name() );
3419                 }
3420             }
3421             ep->Up();
3422         }
3423         else
3424         {
3425             msg_Dbg( &sys.demuxer, "+ Unknown (%s)", typeid( *el ).name() );
3426         }
3427     }
3428     delete ep;
3429     delete tags;
3430
3431     msg_Dbg( &sys.demuxer, "loading tags done." );
3432     es.I_O().setFilePointer( i_sav_position, seek_beginning );
3433 }
3434
3435 /*****************************************************************************
3436  * ParseSeekHead:
3437  *****************************************************************************/
3438 void matroska_segment_c::ParseSeekHead( KaxSeekHead *seekhead )
3439 {
3440     EbmlElement *el;
3441     size_t i, j;
3442     int i_upper_level = 0;
3443
3444     msg_Dbg( &sys.demuxer, "|   + Seek head" );
3445
3446     /* Master elements */
3447     seekhead->Read( es, seekhead->Generic().Context, i_upper_level, el, true );
3448
3449     for( i = 0; i < seekhead->ListSize(); i++ )
3450     {
3451         EbmlElement *l = (*seekhead)[i];
3452
3453         if( MKV_IS_ID( l, KaxSeek ) )
3454         {
3455             EbmlMaster *sk = static_cast<EbmlMaster *>(l);
3456             EbmlId id = EbmlVoid::ClassInfos.GlobalId;
3457             int64_t i_pos = -1;
3458
3459             for( j = 0; j < sk->ListSize(); j++ )
3460             {
3461                 EbmlElement *l = (*sk)[j];
3462
3463                 if( MKV_IS_ID( l, KaxSeekID ) )
3464                 {
3465                     KaxSeekID &sid = *(KaxSeekID*)l;
3466                     id = EbmlId( sid.GetBuffer(), sid.GetSize() );
3467                 }
3468                 else if( MKV_IS_ID( l, KaxSeekPosition ) )
3469                 {
3470                     KaxSeekPosition &spos = *(KaxSeekPosition*)l;
3471                     i_pos = uint64( spos );
3472                 }
3473                 else
3474                 {
3475                     msg_Dbg( &sys.demuxer, "|   |   |   + Unknown (%s)", typeid(*l).name() );
3476                 }
3477             }
3478
3479             if( i_pos >= 0 )
3480             {
3481                 if( id == KaxCues::ClassInfos.GlobalId )
3482                 {
3483                     msg_Dbg( &sys.demuxer, "|   |   |   = cues at "I64Fd, i_pos );
3484                     i_cues_position = segment->GetGlobalPosition( i_pos );
3485                 }
3486                 else if( id == KaxChapters::ClassInfos.GlobalId )
3487                 {
3488                     msg_Dbg( &sys.demuxer, "|   |   |   = chapters at "I64Fd, i_pos );
3489                     i_chapters_position = segment->GetGlobalPosition( i_pos );
3490                 }
3491                 else if( id == KaxTags::ClassInfos.GlobalId )
3492                 {
3493                     msg_Dbg( &sys.demuxer, "|   |   |   = tags at "I64Fd, i_pos );
3494                     i_tags_position = segment->GetGlobalPosition( i_pos );
3495                 }
3496             }
3497         }
3498         else
3499         {
3500             msg_Dbg( &sys.demuxer, "|   |   + Unknown (%s)", typeid(*l).name() );
3501         }
3502     }
3503 }
3504
3505 /*****************************************************************************
3506  * ParseTrackEntry:
3507  *****************************************************************************/
3508 void matroska_segment_c::ParseTrackEntry( KaxTrackEntry *m )
3509 {
3510     size_t i, j, k, n;
3511
3512     mkv_track_t *tk;
3513
3514     msg_Dbg( &sys.demuxer, "|   |   + Track Entry" );
3515
3516     tk = new mkv_track_t();
3517     tracks.push_back( tk );
3518
3519     /* Init the track */
3520     memset( tk, 0, sizeof( mkv_track_t ) );
3521
3522     es_format_Init( &tk->fmt, UNKNOWN_ES, 0 );
3523     tk->fmt.psz_language = strdup("English");
3524     tk->fmt.psz_description = NULL;
3525
3526     tk->b_default = VLC_TRUE;
3527     tk->b_enabled = VLC_TRUE;
3528     tk->b_silent = VLC_FALSE;
3529     tk->i_number = tracks.size() - 1;
3530     tk->i_extra_data = 0;
3531     tk->p_extra_data = NULL;
3532     tk->psz_codec = NULL;
3533     tk->i_default_duration = 0;
3534     tk->f_timecodescale = 1.0;
3535
3536     tk->b_inited = VLC_FALSE;
3537     tk->i_data_init = 0;
3538     tk->p_data_init = NULL;
3539
3540     tk->psz_codec_name = NULL;
3541     tk->psz_codec_settings = NULL;
3542     tk->psz_codec_info_url = NULL;
3543     tk->psz_codec_download_url = NULL;
3544     
3545     tk->i_compression_type = MATROSKA_COMPRESSION_NONE;
3546
3547     for( i = 0; i < m->ListSize(); i++ )
3548     {
3549         EbmlElement *l = (*m)[i];
3550
3551         if( MKV_IS_ID( l, KaxTrackNumber ) )
3552         {
3553             KaxTrackNumber &tnum = *(KaxTrackNumber*)l;
3554
3555             tk->i_number = uint32( tnum );
3556             msg_Dbg( &sys.demuxer, "|   |   |   + Track Number=%u", uint32( tnum ) );
3557         }
3558         else  if( MKV_IS_ID( l, KaxTrackUID ) )
3559         {
3560             KaxTrackUID &tuid = *(KaxTrackUID*)l;
3561
3562             msg_Dbg( &sys.demuxer, "|   |   |   + Track UID=%u",  uint32( tuid ) );
3563         }
3564         else  if( MKV_IS_ID( l, KaxTrackType ) )
3565         {
3566             char *psz_type;
3567             KaxTrackType &ttype = *(KaxTrackType*)l;
3568
3569             switch( uint8(ttype) )
3570             {
3571                 case track_audio:
3572                     psz_type = "audio";
3573                     tk->fmt.i_cat = AUDIO_ES;
3574                     break;
3575                 case track_video:
3576                     psz_type = "video";
3577                     tk->fmt.i_cat = VIDEO_ES;
3578                     break;
3579                 case track_subtitle:
3580                     psz_type = "subtitle";
3581                     tk->fmt.i_cat = SPU_ES;
3582                     break;
3583                 case track_buttons:
3584                     psz_type = "buttons";
3585                     tk->fmt.i_cat = SPU_ES;
3586                     break;
3587                 default:
3588                     psz_type = "unknown";
3589                     tk->fmt.i_cat = UNKNOWN_ES;
3590                     break;
3591             }
3592
3593             msg_Dbg( &sys.demuxer, "|   |   |   + Track Type=%s", psz_type );
3594         }
3595 //        else  if( EbmlId( *l ) == KaxTrackFlagEnabled::ClassInfos.GlobalId )
3596 //        {
3597 //            KaxTrackFlagEnabled &fenb = *(KaxTrackFlagEnabled*)l;
3598
3599 //            tk->b_enabled = uint32( fenb );
3600 //            msg_Dbg( &sys.demuxer, "|   |   |   + Track Enabled=%u",
3601 //                     uint32( fenb )  );
3602 //        }
3603         else  if( MKV_IS_ID( l, KaxTrackFlagDefault ) )
3604         {
3605             KaxTrackFlagDefault &fdef = *(KaxTrackFlagDefault*)l;
3606
3607             tk->b_default = uint32( fdef );
3608             msg_Dbg( &sys.demuxer, "|   |   |   + Track Default=%u", uint32( fdef )  );
3609         }
3610         else  if( MKV_IS_ID( l, KaxTrackFlagLacing ) )
3611         {
3612             KaxTrackFlagLacing &lac = *(KaxTrackFlagLacing*)l;
3613
3614             msg_Dbg( &sys.demuxer, "|   |   |   + Track Lacing=%d", uint32( lac ) );
3615         }
3616         else  if( MKV_IS_ID( l, KaxTrackMinCache ) )
3617         {
3618             KaxTrackMinCache &cmin = *(KaxTrackMinCache*)l;
3619
3620             msg_Dbg( &sys.demuxer, "|   |   |   + Track MinCache=%d", uint32( cmin ) );
3621         }
3622         else  if( MKV_IS_ID( l, KaxTrackMaxCache ) )
3623         {
3624             KaxTrackMaxCache &cmax = *(KaxTrackMaxCache*)l;
3625
3626             msg_Dbg( &sys.demuxer, "|   |   |   + Track MaxCache=%d", uint32( cmax ) );
3627         }
3628         else  if( MKV_IS_ID( l, KaxTrackDefaultDuration ) )
3629         {
3630             KaxTrackDefaultDuration &defd = *(KaxTrackDefaultDuration*)l;
3631
3632             tk->i_default_duration = uint64(defd);
3633             msg_Dbg( &sys.demuxer, "|   |   |   + Track Default Duration="I64Fd, uint64(defd) );
3634         }
3635         else  if( MKV_IS_ID( l, KaxTrackTimecodeScale ) )
3636         {
3637             KaxTrackTimecodeScale &ttcs = *(KaxTrackTimecodeScale*)l;
3638
3639             tk->f_timecodescale = float( ttcs );
3640             msg_Dbg( &sys.demuxer, "|   |   |   + Track TimeCodeScale=%f", tk->f_timecodescale );
3641         }
3642         else if( MKV_IS_ID( l, KaxTrackName ) )
3643         {
3644             KaxTrackName &tname = *(KaxTrackName*)l;
3645
3646             tk->fmt.psz_description = UTF8ToStr( UTFstring( tname ) );
3647             msg_Dbg( &sys.demuxer, "|   |   |   + Track Name=%s", tk->fmt.psz_description );
3648         }
3649         else  if( MKV_IS_ID( l, KaxTrackLanguage ) )
3650         {
3651             KaxTrackLanguage &lang = *(KaxTrackLanguage*)l;
3652
3653             tk->fmt.psz_language = strdup( string( lang ).c_str() );
3654             msg_Dbg( &sys.demuxer,
3655                      "|   |   |   + Track Language=`%s'", tk->fmt.psz_language );
3656         }
3657         else  if( MKV_IS_ID( l, KaxCodecID ) )
3658         {
3659             KaxCodecID &codecid = *(KaxCodecID*)l;
3660
3661             tk->psz_codec = strdup( string( codecid ).c_str() );
3662             msg_Dbg( &sys.demuxer, "|   |   |   + Track CodecId=%s", string( codecid ).c_str() );
3663         }
3664         else  if( MKV_IS_ID( l, KaxCodecPrivate ) )
3665         {
3666             KaxCodecPrivate &cpriv = *(KaxCodecPrivate*)l;
3667
3668             tk->i_extra_data = cpriv.GetSize();
3669             if( tk->i_extra_data > 0 )
3670             {
3671                 tk->p_extra_data = (uint8_t*)malloc( tk->i_extra_data );
3672                 memcpy( tk->p_extra_data, cpriv.GetBuffer(), tk->i_extra_data );
3673             }
3674             msg_Dbg( &sys.demuxer, "|   |   |   + Track CodecPrivate size="I64Fd, cpriv.GetSize() );
3675         }
3676         else if( MKV_IS_ID( l, KaxCodecName ) )
3677         {
3678             KaxCodecName &cname = *(KaxCodecName*)l;
3679
3680             tk->psz_codec_name = UTF8ToStr( UTFstring( cname ) );
3681             msg_Dbg( &sys.demuxer, "|   |   |   + Track Codec Name=%s", tk->psz_codec_name );
3682         }
3683         else if( MKV_IS_ID( l, KaxContentEncodings ) )
3684         {
3685             EbmlMaster *cencs = static_cast<EbmlMaster*>(l);
3686             MkvTree( sys.demuxer, 3, "Content Encodings" );
3687             for( j = 0; j < cencs->ListSize(); j++ )
3688             {
3689                 EbmlElement *l2 = (*cencs)[j];
3690                 if( MKV_IS_ID( l2, KaxContentEncoding ) )
3691                 {
3692                     MkvTree( sys.demuxer, 4, "Content Encoding" );
3693                     EbmlMaster *cenc = static_cast<EbmlMaster*>(l2);
3694                     for( k = 0; k < cenc->ListSize(); k++ )
3695                     {
3696                         EbmlElement *l3 = (*cenc)[k];
3697                         if( MKV_IS_ID( l3, KaxContentEncodingOrder ) )
3698                         {
3699                             KaxContentEncodingOrder &encord = *(KaxContentEncodingOrder*)l3;
3700                             MkvTree( sys.demuxer, 5, "Order: %i", uint32( encord ) );
3701                         }
3702                         else if( MKV_IS_ID( l3, KaxContentEncodingScope ) )
3703                         {
3704                             KaxContentEncodingScope &encscope = *(KaxContentEncodingScope*)l3;
3705                             MkvTree( sys.demuxer, 5, "Scope: %i", uint32( encscope ) );
3706                         }
3707                         else if( MKV_IS_ID( l3, KaxContentEncodingType ) )
3708                         {
3709                             KaxContentEncodingType &enctype = *(KaxContentEncodingType*)l3;
3710                             MkvTree( sys.demuxer, 5, "Type: %i", uint32( enctype ) );
3711                         }
3712                         else if( MKV_IS_ID( l3, KaxContentCompression ) )
3713                         {
3714                             EbmlMaster *compr = static_cast<EbmlMaster*>(l3);
3715                             MkvTree( sys.demuxer, 5, "Content Compression" );
3716                             for( n = 0; n < compr->ListSize(); n++ )
3717                             {
3718                                 EbmlElement *l4 = (*compr)[n];
3719                                 if( MKV_IS_ID( l4, KaxContentCompAlgo ) )
3720                                 {
3721                                     KaxContentCompAlgo &compalg = *(KaxContentCompAlgo*)l4;
3722                                     MkvTree( sys.demuxer, 6, "Compression Algorithm: %i", uint32(compalg) );
3723                                     if( uint32( compalg ) == 0 )
3724                                     {
3725                                         tk->i_compression_type = MATROSKA_COMPRESSION_ZLIB;
3726                                     }
3727                                 }
3728                                 else
3729                                 {
3730                                     MkvTree( sys.demuxer, 6, "Unknown (%s)", typeid(*l4).name() );
3731                                 }
3732                             }
3733                         }
3734
3735                         else
3736                         {
3737                             MkvTree( sys.demuxer, 5, "Unknown (%s)", typeid(*l3).name() );
3738                         }
3739                     }
3740                     
3741                 }
3742                 else
3743                 {
3744                     MkvTree( sys.demuxer, 4, "Unknown (%s)", typeid(*l2).name() );
3745                 }
3746             }
3747                 
3748         }
3749 //        else if( EbmlId( *l ) == KaxCodecSettings::ClassInfos.GlobalId )
3750 //        {
3751 //            KaxCodecSettings &cset = *(KaxCodecSettings*)l;
3752
3753 //            tk->psz_codec_settings = UTF8ToStr( UTFstring( cset ) );
3754 //            msg_Dbg( &sys.demuxer, "|   |   |   + Track Codec Settings=%s", tk->psz_codec_settings );
3755 //        }
3756 //        else if( EbmlId( *l ) == KaxCodecInfoURL::ClassInfos.GlobalId )
3757 //        {
3758 //            KaxCodecInfoURL &ciurl = *(KaxCodecInfoURL*)l;
3759
3760 //            tk->psz_codec_info_url = strdup( string( ciurl ).c_str() );
3761 //            msg_Dbg( &sys.demuxer, "|   |   |   + Track Codec Info URL=%s", tk->psz_codec_info_url );
3762 //        }
3763 //        else if( EbmlId( *l ) == KaxCodecDownloadURL::ClassInfos.GlobalId )
3764 //        {
3765 //            KaxCodecDownloadURL &cdurl = *(KaxCodecDownloadURL*)l;
3766
3767 //            tk->psz_codec_download_url = strdup( string( cdurl ).c_str() );
3768 //            msg_Dbg( &sys.demuxer, "|   |   |   + Track Codec Info URL=%s", tk->psz_codec_download_url );
3769 //        }
3770 //        else if( EbmlId( *l ) == KaxCodecDecodeAll::ClassInfos.GlobalId )
3771 //        {
3772 //            KaxCodecDecodeAll &cdall = *(KaxCodecDecodeAll*)l;
3773
3774 //            msg_Dbg( &sys.demuxer, "|   |   |   + Track Codec Decode All=%u <== UNUSED", uint8( cdall ) );
3775 //        }
3776 //        else if( EbmlId( *l ) == KaxTrackOverlay::ClassInfos.GlobalId )
3777 //        {
3778 //            KaxTrackOverlay &tovr = *(KaxTrackOverlay*)l;
3779
3780 //            msg_Dbg( &sys.demuxer, "|   |   |   + Track Overlay=%u <== UNUSED", uint32( tovr ) );
3781 //        }
3782         else  if( MKV_IS_ID( l, KaxTrackVideo ) )
3783         {
3784             EbmlMaster *tkv = static_cast<EbmlMaster*>(l);
3785             unsigned int j;
3786
3787             msg_Dbg( &sys.demuxer, "|   |   |   + Track Video" );
3788             tk->f_fps = 0.0;
3789
3790             for( j = 0; j < tkv->ListSize(); j++ )
3791             {
3792                 EbmlElement *l = (*tkv)[j];
3793 //                if( EbmlId( *el4 ) == KaxVideoFlagInterlaced::ClassInfos.GlobalId )
3794 //                {
3795 //                    KaxVideoFlagInterlaced &fint = *(KaxVideoFlagInterlaced*)el4;
3796
3797 //                    msg_Dbg( &sys.demuxer, "|   |   |   |   + Track Video Interlaced=%u", uint8( fint ) );
3798 //                }
3799 //                else if( EbmlId( *el4 ) == KaxVideoStereoMode::ClassInfos.GlobalId )
3800 //                {
3801 //                    KaxVideoStereoMode &stereo = *(KaxVideoStereoMode*)el4;
3802
3803 //                    msg_Dbg( &sys.demuxer, "|   |   |   |   + Track Video Stereo Mode=%u", uint8( stereo ) );
3804 //                }
3805 //                else
3806                 if( MKV_IS_ID( l, KaxVideoPixelWidth ) )
3807                 {
3808                     KaxVideoPixelWidth &vwidth = *(KaxVideoPixelWidth*)l;
3809
3810                     tk->fmt.video.i_width = uint16( vwidth );
3811                     msg_Dbg( &sys.demuxer, "|   |   |   |   + width=%d", uint16( vwidth ) );
3812                 }
3813                 else if( MKV_IS_ID( l, KaxVideoPixelHeight ) )
3814                 {
3815                     KaxVideoPixelWidth &vheight = *(KaxVideoPixelWidth*)l;
3816
3817                     tk->fmt.video.i_height = uint16( vheight );
3818                     msg_Dbg( &sys.demuxer, "|   |   |   |   + height=%d", uint16( vheight ) );
3819                 }
3820                 else if( MKV_IS_ID( l, KaxVideoDisplayWidth ) )
3821                 {
3822                     KaxVideoDisplayWidth &vwidth = *(KaxVideoDisplayWidth*)l;
3823
3824                     tk->fmt.video.i_visible_width = uint16( vwidth );
3825                     msg_Dbg( &sys.demuxer, "|   |   |   |   + display width=%d", uint16( vwidth ) );
3826                 }
3827                 else if( MKV_IS_ID( l, KaxVideoDisplayHeight ) )
3828                 {
3829                     KaxVideoDisplayWidth &vheight = *(KaxVideoDisplayWidth*)l;
3830
3831                     tk->fmt.video.i_visible_height = uint16( vheight );
3832                     msg_Dbg( &sys.demuxer, "|   |   |   |   + display height=%d", uint16( vheight ) );
3833                 }
3834                 else if( MKV_IS_ID( l, KaxVideoFrameRate ) )
3835                 {
3836                     KaxVideoFrameRate &vfps = *(KaxVideoFrameRate*)l;
3837
3838                     tk->f_fps = float( vfps );
3839                     msg_Dbg( &sys.demuxer, "   |   |   |   + fps=%f", float( vfps ) );
3840                 }
3841 //                else if( EbmlId( *l ) == KaxVideoDisplayUnit::ClassInfos.GlobalId )
3842 //                {
3843 //                     KaxVideoDisplayUnit &vdmode = *(KaxVideoDisplayUnit*)l;
3844
3845 //                    msg_Dbg( &sys.demuxer, "|   |   |   |   + Track Video Display Unit=%s",
3846 //                             uint8( vdmode ) == 0 ? "pixels" : ( uint8( vdmode ) == 1 ? "centimeters": "inches" ) );
3847 //                }
3848 //                else if( EbmlId( *l ) == KaxVideoAspectRatio::ClassInfos.GlobalId )
3849 //                {
3850 //                    KaxVideoAspectRatio &ratio = *(KaxVideoAspectRatio*)l;
3851
3852 //                    msg_Dbg( &sys.demuxer, "   |   |   |   + Track Video Aspect Ratio Type=%u", uint8( ratio ) );
3853 //                }
3854 //                else if( EbmlId( *l ) == KaxVideoGamma::ClassInfos.GlobalId )
3855 //                {
3856 //                    KaxVideoGamma &gamma = *(KaxVideoGamma*)l;
3857
3858 //                    msg_Dbg( &sys.demuxer, "   |   |   |   + fps=%f", float( gamma ) );
3859 //                }
3860                 else
3861                 {
3862                     msg_Dbg( &sys.demuxer, "|   |   |   |   + Unknown (%s)", typeid(*l).name() );
3863                 }
3864             }
3865             if ( tk->fmt.video.i_visible_height && tk->fmt.video.i_visible_width )
3866                 tk->fmt.video.i_aspect = VOUT_ASPECT_FACTOR * tk->fmt.video.i_visible_width / tk->fmt.video.i_visible_height;
3867         }
3868         else  if( MKV_IS_ID( l, KaxTrackAudio ) )
3869         {
3870             EbmlMaster *tka = static_cast<EbmlMaster*>(l);
3871             unsigned int j;
3872
3873             msg_Dbg( &sys.demuxer, "|   |   |   + Track Audio" );
3874
3875             for( j = 0; j < tka->ListSize(); j++ )
3876             {
3877                 EbmlElement *l = (*tka)[j];
3878
3879                 if( MKV_IS_ID( l, KaxAudioSamplingFreq ) )
3880                 {
3881                     KaxAudioSamplingFreq &afreq = *(KaxAudioSamplingFreq*)l;
3882
3883                     tk->fmt.audio.i_rate = (int)float( afreq );
3884                     msg_Dbg( &sys.demuxer, "|   |   |   |   + afreq=%d", tk->fmt.audio.i_rate );
3885                 }
3886                 else if( MKV_IS_ID( l, KaxAudioChannels ) )
3887                 {
3888                     KaxAudioChannels &achan = *(KaxAudioChannels*)l;
3889
3890                     tk->fmt.audio.i_channels = uint8( achan );
3891                     msg_Dbg( &sys.demuxer, "|   |   |   |   + achan=%u", uint8( achan ) );
3892                 }
3893                 else if( MKV_IS_ID( l, KaxAudioBitDepth ) )
3894                 {
3895                     KaxAudioBitDepth &abits = *(KaxAudioBitDepth*)l;
3896
3897                     tk->fmt.audio.i_bitspersample = uint8( abits );
3898                     msg_Dbg( &sys.demuxer, "|   |   |   |   + abits=%u", uint8( abits ) );
3899                 }
3900                 else
3901                 {
3902                     msg_Dbg( &sys.demuxer, "|   |   |   |   + Unknown (%s)", typeid(*l).name() );
3903                 }
3904             }
3905         }
3906         else
3907         {
3908             msg_Dbg( &sys.demuxer, "|   |   |   + Unknown (%s)",
3909                      typeid(*l).name() );
3910         }
3911     }
3912 }
3913
3914 /*****************************************************************************
3915  * ParseTracks:
3916  *****************************************************************************/
3917 void matroska_segment_c::ParseTracks( KaxTracks *tracks )
3918 {
3919     EbmlElement *el;
3920     unsigned int i;
3921     int i_upper_level = 0;
3922
3923     msg_Dbg( &sys.demuxer, "|   + Tracks" );
3924
3925     /* Master elements */
3926     tracks->Read( es, tracks->Generic().Context, i_upper_level, el, true );
3927
3928     for( i = 0; i < tracks->ListSize(); i++ )
3929     {
3930         EbmlElement *l = (*tracks)[i];
3931
3932         if( MKV_IS_ID( l, KaxTrackEntry ) )
3933         {
3934             ParseTrackEntry( static_cast<KaxTrackEntry *>(l) );
3935         }
3936         else
3937         {
3938             msg_Dbg( &sys.demuxer, "|   |   + Unknown (%s)", typeid(*l).name() );
3939         }
3940     }
3941 }
3942
3943 /*****************************************************************************
3944  * ParseInfo:
3945  *****************************************************************************/
3946 void matroska_segment_c::ParseInfo( KaxInfo *info )
3947 {
3948     EbmlElement *el;
3949     EbmlMaster  *m;
3950     size_t i, j;
3951     int i_upper_level = 0;
3952
3953     msg_Dbg( &sys.demuxer, "|   + Information" );
3954
3955     /* Master elements */
3956     m = static_cast<EbmlMaster *>(info);
3957     m->Read( es, info->Generic().Context, i_upper_level, el, true );
3958
3959     for( i = 0; i < m->ListSize(); i++ )
3960     {
3961         EbmlElement *l = (*m)[i];
3962
3963         if( MKV_IS_ID( l, KaxSegmentUID ) )
3964         {
3965             segment_uid = *(new KaxSegmentUID(*static_cast<KaxSegmentUID*>(l)));
3966
3967             msg_Dbg( &sys.demuxer, "|   |   + UID=%d", *(uint32*)segment_uid.GetBuffer() );
3968         }
3969         else if( MKV_IS_ID( l, KaxPrevUID ) )
3970         {
3971             prev_segment_uid = *(new KaxPrevUID(*static_cast<KaxPrevUID*>(l)));
3972
3973             msg_Dbg( &sys.demuxer, "|   |   + PrevUID=%d", *(uint32*)prev_segment_uid.GetBuffer() );
3974         }
3975         else if( MKV_IS_ID( l, KaxNextUID ) )
3976         {
3977             next_segment_uid = *(new KaxNextUID(*static_cast<KaxNextUID*>(l)));
3978
3979             msg_Dbg( &sys.demuxer, "|   |   + NextUID=%d", *(uint32*)next_segment_uid.GetBuffer() );
3980         }
3981         else if( MKV_IS_ID( l, KaxTimecodeScale ) )
3982         {
3983             KaxTimecodeScale &tcs = *(KaxTimecodeScale*)l;
3984
3985             i_timescale = uint64(tcs);
3986
3987             msg_Dbg( &sys.demuxer, "|   |   + TimecodeScale="I64Fd,
3988                      i_timescale );
3989         }
3990         else if( MKV_IS_ID( l, KaxDuration ) )
3991         {
3992             KaxDuration &dur = *(KaxDuration*)l;
3993
3994             i_duration = mtime_t( double( dur ) );
3995
3996             msg_Dbg( &sys.demuxer, "|   |   + Duration="I64Fd,
3997                      i_duration );
3998         }
3999         else if( MKV_IS_ID( l, KaxMuxingApp ) )
4000         {
4001             KaxMuxingApp &mapp = *(KaxMuxingApp*)l;
4002
4003             psz_muxing_application = UTF8ToStr( UTFstring( mapp ) );
4004
4005             msg_Dbg( &sys.demuxer, "|   |   + Muxing Application=%s",
4006                      psz_muxing_application );
4007         }
4008         else if( MKV_IS_ID( l, KaxWritingApp ) )
4009         {
4010             KaxWritingApp &wapp = *(KaxWritingApp*)l;
4011
4012             psz_writing_application = UTF8ToStr( UTFstring( wapp ) );
4013
4014             msg_Dbg( &sys.demuxer, "|   |   + Writing Application=%s",
4015                      psz_writing_application );
4016         }
4017         else if( MKV_IS_ID( l, KaxSegmentFilename ) )
4018         {
4019             KaxSegmentFilename &sfn = *(KaxSegmentFilename*)l;
4020
4021             psz_segment_filename = UTF8ToStr( UTFstring( sfn ) );
4022
4023             msg_Dbg( &sys.demuxer, "|   |   + Segment Filename=%s",
4024                      psz_segment_filename );
4025         }
4026         else if( MKV_IS_ID( l, KaxTitle ) )
4027         {
4028             KaxTitle &title = *(KaxTitle*)l;
4029
4030             psz_title = UTF8ToStr( UTFstring( title ) );
4031
4032             msg_Dbg( &sys.demuxer, "|   |   + Title=%s", psz_title );
4033         }
4034         else if( MKV_IS_ID( l, KaxSegmentFamily ) )
4035         {
4036             KaxSegmentFamily *uid = static_cast<KaxSegmentFamily*>(l);
4037
4038             families.push_back(*uid);
4039
4040             msg_Dbg( &sys.demuxer, "|   |   + family=%d", *(uint32*)uid->GetBuffer() );
4041         }
4042 #if defined( HAVE_GMTIME_R ) && !defined( SYS_DARWIN )
4043         else if( MKV_IS_ID( l, KaxDateUTC ) )
4044         {
4045             KaxDateUTC &date = *(KaxDateUTC*)l;
4046             time_t i_date;
4047             struct tm tmres;
4048             char   buffer[256];
4049
4050             i_date = date.GetEpochDate();
4051             memset( buffer, 0, 256 );
4052             if( gmtime_r( &i_date, &tmres ) &&
4053                 asctime_r( &tmres, buffer ) )
4054             {
4055                 buffer[strlen( buffer)-1]= '\0';
4056                 psz_date_utc = strdup( buffer );
4057                 msg_Dbg( &sys.demuxer, "|   |   + Date=%s", psz_date_utc );
4058             }
4059         }
4060 #endif
4061 #if LIBMATROSKA_VERSION >= 0x000704
4062         else if( MKV_IS_ID( l, KaxChapterTranslate ) )
4063         {
4064             KaxChapterTranslate *p_trans = static_cast<KaxChapterTranslate*>( l );
4065             chapter_translation_c translated;
4066
4067             p_trans->Read( es, p_trans->Generic().Context, i_upper_level, el, true );
4068             for( j = 0; j < p_trans->ListSize(); j++ )
4069             {
4070                 EbmlElement *l = (*p_trans)[j];
4071
4072                 if( MKV_IS_ID( l, KaxChapterTranslateEditionUID ) )
4073                 {
4074                     translated.editions.push_back( uint64( *static_cast<KaxChapterTranslateEditionUID*>( l ) ) );
4075                 }
4076                 else if( MKV_IS_ID( l, KaxChapterTranslateCodec ) )
4077                 {
4078                     translated.codec_id = uint32( *static_cast<KaxChapterTranslateCodec*>( l ) );
4079                 }
4080                 else if( MKV_IS_ID( l, KaxChapterTranslateID ) )
4081                 {
4082                     translated.translated = *( new KaxChapterTranslateID( *static_cast<KaxChapterTranslateID*>( l ) ) );
4083                 }
4084             }
4085
4086             translations.push_back( translated );
4087         }
4088 #endif
4089         else
4090         {
4091             msg_Dbg( &sys.demuxer, "|   |   + Unknown (%s)", typeid(*l).name() );
4092         }
4093     }
4094
4095     double f_dur = double(i_duration) * double(i_timescale) / 1000000.0;
4096     i_duration = mtime_t(f_dur);
4097 }
4098
4099
4100 /*****************************************************************************
4101  * ParseChapterAtom
4102  *****************************************************************************/
4103 void matroska_segment_c::ParseChapterAtom( int i_level, KaxChapterAtom *ca, chapter_item_c & chapters )
4104 {
4105     size_t i, j;
4106
4107     msg_Dbg( &sys.demuxer, "|   |   |   + ChapterAtom (level=%d)", i_level );
4108     for( i = 0; i < ca->ListSize(); i++ )
4109     {
4110         EbmlElement *l = (*ca)[i];
4111
4112         if( MKV_IS_ID( l, KaxChapterUID ) )
4113         {
4114             chapters.i_uid = uint64_t(*(KaxChapterUID*)l);
4115             msg_Dbg( &sys.demuxer, "|   |   |   |   + ChapterUID: %lld", chapters.i_uid );
4116         }
4117         else if( MKV_IS_ID( l, KaxChapterFlagHidden ) )
4118         {
4119             KaxChapterFlagHidden &flag =*(KaxChapterFlagHidden*)l;
4120             chapters.b_display_seekpoint = uint8( flag ) == 0;
4121
4122             msg_Dbg( &sys.demuxer, "|   |   |   |   + ChapterFlagHidden: %s", chapters.b_display_seekpoint ? "no":"yes" );
4123         }
4124         else if( MKV_IS_ID( l, KaxChapterTimeStart ) )
4125         {
4126             KaxChapterTimeStart &start =*(KaxChapterTimeStart*)l;
4127             chapters.i_start_time = uint64( start ) / I64C(1000);
4128
4129             msg_Dbg( &sys.demuxer, "|   |   |   |   + ChapterTimeStart: %lld", chapters.i_start_time );
4130         }
4131         else if( MKV_IS_ID( l, KaxChapterTimeEnd ) )
4132         {
4133             KaxChapterTimeEnd &end =*(KaxChapterTimeEnd*)l;
4134             chapters.i_end_time = uint64( end ) / I64C(1000);
4135
4136             msg_Dbg( &sys.demuxer, "|   |   |   |   + ChapterTimeEnd: %lld", chapters.i_end_time );
4137         }
4138         else if( MKV_IS_ID( l, KaxChapterDisplay ) )
4139         {
4140             EbmlMaster *cd = static_cast<EbmlMaster *>(l);
4141
4142             msg_Dbg( &sys.demuxer, "|   |   |   |   + ChapterDisplay" );
4143             for( j = 0; j < cd->ListSize(); j++ )
4144             {
4145                 EbmlElement *l= (*cd)[j];
4146
4147                 if( MKV_IS_ID( l, KaxChapterString ) )
4148                 {
4149                     int k;
4150
4151                     KaxChapterString &name =*(KaxChapterString*)l;
4152                     for (k = 0; k < i_level; k++)
4153                         chapters.psz_name += '+';
4154                     chapters.psz_name += ' ';
4155                     chapters.psz_name += UTF8ToStr( UTFstring( name ) );
4156                     chapters.b_user_display = true;
4157
4158                     msg_Dbg( &sys.demuxer, "|   |   |   |   |    + ChapterString '%s'", UTF8ToStr(UTFstring(name)) );
4159                 }
4160                 else if( MKV_IS_ID( l, KaxChapterLanguage ) )
4161                 {
4162                     KaxChapterLanguage &lang =*(KaxChapterLanguage*)l;
4163                     const char *psz = string( lang ).c_str();
4164
4165                     msg_Dbg( &sys.demuxer, "|   |   |   |   |    + ChapterLanguage '%s'", psz );
4166                 }
4167                 else if( MKV_IS_ID( l, KaxChapterCountry ) )
4168                 {
4169                     KaxChapterCountry &ct =*(KaxChapterCountry*)l;
4170                     const char *psz = string( ct ).c_str();
4171
4172                     msg_Dbg( &sys.demuxer, "|   |   |   |   |    + ChapterCountry '%s'", psz );
4173                 }
4174             }
4175         }
4176         else if( MKV_IS_ID( l, KaxChapterProcess ) )
4177         {
4178             msg_Dbg( &sys.demuxer, "|   |   |   |   + ChapterProcess" );
4179
4180             KaxChapterProcess *cp = static_cast<KaxChapterProcess *>(l);
4181             chapter_codec_cmds_c *p_ccodec = NULL;
4182
4183             for( j = 0; j < cp->ListSize(); j++ )
4184             {
4185                 EbmlElement *k= (*cp)[j];
4186
4187                 if( MKV_IS_ID( k, KaxChapterProcessCodecID ) )
4188                 {
4189                     KaxChapterProcessCodecID *p_codec_id = static_cast<KaxChapterProcessCodecID*>( k );
4190                     if ( uint32(*p_codec_id) == 0 )
4191                         p_ccodec = new matroska_script_codec_c( sys );
4192                     else if ( uint32(*p_codec_id) == 1 )
4193                         p_ccodec = new dvd_chapter_codec_c( sys );
4194                     break;
4195                 }
4196             }
4197
4198             if ( p_ccodec != NULL )
4199             {
4200                 for( j = 0; j < cp->ListSize(); j++ )
4201                 {
4202                     EbmlElement *k= (*cp)[j];
4203
4204                     if( MKV_IS_ID( k, KaxChapterProcessPrivate ) )
4205                     {
4206                         KaxChapterProcessPrivate * p_private = static_cast<KaxChapterProcessPrivate*>( k );
4207                         p_ccodec->SetPrivate( *p_private );
4208                     }
4209                     else if( MKV_IS_ID( k, KaxChapterProcessCommand ) )
4210                     {
4211                         p_ccodec->AddCommand( *static_cast<KaxChapterProcessCommand*>( k ) );
4212                     }
4213                 }
4214                 chapters.codecs.push_back( p_ccodec );
4215             }
4216         }
4217         else if( MKV_IS_ID( l, KaxChapterAtom ) )
4218         {
4219             chapter_item_c *new_sub_chapter = new chapter_item_c();
4220             ParseChapterAtom( i_level+1, static_cast<KaxChapterAtom *>(l), *new_sub_chapter );
4221             new_sub_chapter->psz_parent = &chapters;
4222             chapters.sub_chapters.push_back( new_sub_chapter );
4223         }
4224     }
4225 }
4226
4227 /*****************************************************************************
4228  * ParseChapters:
4229  *****************************************************************************/
4230 void matroska_segment_c::ParseChapters( KaxChapters *chapters )
4231 {
4232     EbmlElement *el;
4233     size_t i;
4234     int i_upper_level = 0;
4235     mtime_t i_dur;
4236
4237     /* Master elements */
4238     chapters->Read( es, chapters->Generic().Context, i_upper_level, el, true );
4239
4240     for( i = 0; i < chapters->ListSize(); i++ )
4241     {
4242         EbmlElement *l = (*chapters)[i];
4243
4244         if( MKV_IS_ID( l, KaxEditionEntry ) )
4245         {
4246             chapter_edition_c *p_edition = new chapter_edition_c();
4247             
4248             EbmlMaster *E = static_cast<EbmlMaster *>(l );
4249             size_t j;
4250             msg_Dbg( &sys.demuxer, "|   |   + EditionEntry" );
4251             for( j = 0; j < E->ListSize(); j++ )
4252             {
4253                 EbmlElement *l = (*E)[j];
4254
4255                 if( MKV_IS_ID( l, KaxChapterAtom ) )
4256                 {
4257                     chapter_item_c *new_sub_chapter = new chapter_item_c();
4258                     ParseChapterAtom( 0, static_cast<KaxChapterAtom *>(l), *new_sub_chapter );
4259                     p_edition->sub_chapters.push_back( new_sub_chapter );
4260                 }
4261                 else if( MKV_IS_ID( l, KaxEditionUID ) )
4262                 {
4263                     p_edition->i_uid = uint64(*static_cast<KaxEditionUID *>( l ));
4264                 }
4265                 else if( MKV_IS_ID( l, KaxEditionFlagOrdered ) )
4266                 {
4267                     p_edition->b_ordered = config_GetInt( &sys.demuxer, "mkv-use-ordered-chapters" ) ? (uint8(*static_cast<KaxEditionFlagOrdered *>( l )) != 0) : 0;
4268                 }
4269                 else if( MKV_IS_ID( l, KaxEditionFlagDefault ) )
4270                 {
4271                     if (uint8(*static_cast<KaxEditionFlagDefault *>( l )) != 0)
4272                         i_default_edition = stored_editions.size();
4273                 }
4274                 else
4275                 {
4276                     msg_Dbg( &sys.demuxer, "|   |   |   + Unknown (%s)", typeid(*l).name() );
4277                 }
4278             }
4279             stored_editions.push_back( p_edition );
4280         }
4281         else
4282         {
4283             msg_Dbg( &sys.demuxer, "|   |   + Unknown (%s)", typeid(*l).name() );
4284         }
4285     }
4286
4287     for( i = 0; i < stored_editions.size(); i++ )
4288     {
4289         stored_editions[i]->RefreshChapters( );
4290     }
4291     
4292     if ( stored_editions[i_default_edition]->b_ordered )
4293     {
4294         /* update the duration of the segment according to the sum of all sub chapters */
4295         i_dur = stored_editions[i_default_edition]->Duration() / I64C(1000);
4296         if (i_dur > 0)
4297             i_duration = i_dur;
4298     }
4299 }
4300
4301 void matroska_segment_c::ParseCluster( )
4302 {
4303     EbmlElement *el;
4304     EbmlMaster  *m;
4305     unsigned int i;
4306     int i_upper_level = 0;
4307
4308     /* Master elements */
4309     m = static_cast<EbmlMaster *>( cluster );
4310     m->Read( es, cluster->Generic().Context, i_upper_level, el, true );
4311
4312     for( i = 0; i < m->ListSize(); i++ )
4313     {
4314         EbmlElement *l = (*m)[i];
4315
4316         if( MKV_IS_ID( l, KaxClusterTimecode ) )
4317         {
4318             KaxClusterTimecode &ctc = *(KaxClusterTimecode*)l;
4319
4320             cluster->InitTimecode( uint64( ctc ), i_timescale );
4321             break;
4322         }
4323     }
4324
4325     i_start_time = cluster->GlobalTimecode() / 1000;
4326 }
4327
4328 /*****************************************************************************
4329  * InformationCreate:
4330  *****************************************************************************/
4331 void matroska_segment_c::InformationCreate( )
4332 {
4333     size_t      i_track;
4334
4335     sys.meta = vlc_meta_New();
4336
4337     if( psz_title )
4338     {
4339         vlc_meta_Add( sys.meta, VLC_META_TITLE, psz_title );
4340     }
4341     if( psz_date_utc )
4342     {
4343         vlc_meta_Add( sys.meta, VLC_META_DATE, psz_date_utc );
4344     }
4345     if( psz_segment_filename )
4346     {
4347         vlc_meta_Add( sys.meta, _("Segment filename"), psz_segment_filename );
4348     }
4349     if( psz_muxing_application )
4350     {
4351         vlc_meta_Add( sys.meta, _("Muxing application"), psz_muxing_application );
4352     }
4353     if( psz_writing_application )
4354     {
4355         vlc_meta_Add( sys.meta, _("Writing application"), psz_writing_application );
4356     }
4357
4358     for( i_track = 0; i_track < tracks.size(); i_track++ )
4359     {
4360         mkv_track_t *tk = tracks[i_track];
4361         vlc_meta_t *mtk = vlc_meta_New();
4362
4363         sys.meta->track = (vlc_meta_t**)realloc( sys.meta->track,
4364                                                     sizeof( vlc_meta_t * ) * ( sys.meta->i_track + 1 ) );
4365         sys.meta->track[sys.meta->i_track++] = mtk;
4366
4367         if( tk->fmt.psz_description )
4368         {
4369             vlc_meta_Add( sys.meta, VLC_META_DESCRIPTION, tk->fmt.psz_description );
4370         }
4371         if( tk->psz_codec_name )
4372         {
4373             vlc_meta_Add( sys.meta, VLC_META_CODEC_NAME, tk->psz_codec_name );
4374         }
4375         if( tk->psz_codec_settings )
4376         {
4377             vlc_meta_Add( sys.meta, VLC_META_SETTING, tk->psz_codec_settings );
4378         }
4379         if( tk->psz_codec_info_url )
4380         {
4381             vlc_meta_Add( sys.meta, VLC_META_CODEC_DESCRIPTION, tk->psz_codec_info_url );
4382         }
4383         if( tk->psz_codec_download_url )
4384         {
4385             vlc_meta_Add( sys.meta, VLC_META_URL, tk->psz_codec_download_url );
4386         }
4387     }
4388
4389     if( i_tags_position >= 0 )
4390     {
4391         vlc_bool_t b_seekable;
4392
4393         stream_Control( sys.demuxer.s, STREAM_CAN_FASTSEEK, &b_seekable );
4394         if( b_seekable )
4395         {
4396             LoadTags( );
4397         }
4398     }
4399 }
4400
4401
4402 /*****************************************************************************
4403  * Divers
4404  *****************************************************************************/
4405
4406 void matroska_segment_c::IndexAppendCluster( KaxCluster *cluster )
4407 {
4408 #define idx index[i_index]
4409     idx.i_track       = -1;
4410     idx.i_block_number= -1;
4411     idx.i_position    = cluster->GetElementPosition();
4412     idx.i_time        = -1;
4413     idx.b_key         = VLC_TRUE;
4414
4415     i_index++;
4416     if( i_index >= i_index_max )
4417     {
4418         i_index_max += 1024;
4419         index = (mkv_index_t*)realloc( index, sizeof( mkv_index_t ) * i_index_max );
4420     }
4421 #undef idx
4422 }
4423
4424 static char * UTF8ToStr( const UTFstring &u )
4425 {
4426     int     i_src;
4427     const wchar_t *src;
4428     char *dst, *p;
4429
4430     i_src = u.length();
4431     src   = u.c_str();
4432
4433     p = dst = (char*)malloc( i_src + 1);
4434     while( i_src > 0 )
4435     {
4436         if( *src < 255 )
4437         {
4438             *p++ = (char)*src;
4439         }
4440         else
4441         {
4442             *p++ = '?';
4443         }
4444         src++;
4445         i_src--;
4446     }
4447     *p++= '\0';
4448
4449     return dst;
4450 }
4451
4452 void chapter_edition_c::RefreshChapters( )
4453 {
4454     chapter_item_c::RefreshChapters( b_ordered, -1 );
4455     b_display_seekpoint = false;
4456 }
4457
4458 int64_t chapter_item_c::RefreshChapters( bool b_ordered, int64_t i_prev_user_time )
4459 {
4460     int64_t i_user_time = i_prev_user_time;
4461     
4462     // first the sub-chapters, and then ourself
4463     std::vector<chapter_item_c*>::iterator index = sub_chapters.begin();
4464     while ( index != sub_chapters.end() )
4465     {
4466         i_user_time = (*index)->RefreshChapters( b_ordered, i_user_time );
4467         index++;
4468     }
4469
4470     if ( b_ordered )
4471     {
4472         // the ordered chapters always start at zero
4473         if ( i_prev_user_time == -1 )
4474         {
4475             if ( i_user_time == -1 )
4476                 i_user_time = 0;
4477             i_prev_user_time = 0;
4478         }
4479
4480         i_user_start_time = i_prev_user_time;
4481         if ( i_end_time != -1 && i_user_time == i_prev_user_time )
4482         {
4483             i_user_end_time = i_user_start_time - i_start_time + i_end_time;
4484         }
4485         else
4486         {
4487             i_user_end_time = i_user_time;
4488         }
4489     }
4490     else
4491     {
4492         std::sort( sub_chapters.begin(), sub_chapters.end() );
4493         i_user_start_time = i_start_time;
4494         if ( i_end_time != -1 )
4495             i_user_end_time = i_end_time;
4496         else if ( i_user_time != -1 )
4497             i_user_end_time = i_user_time;
4498         else
4499             i_user_end_time = i_user_start_time;
4500     }
4501
4502     return i_user_end_time;
4503 }
4504
4505 mtime_t chapter_edition_c::Duration() const
4506 {
4507     mtime_t i_result = 0;
4508     
4509     if ( sub_chapters.size() )
4510     {
4511         std::vector<chapter_item_c*>::const_iterator index = sub_chapters.end();
4512         index--;
4513         i_result = (*index)->i_user_end_time;
4514     }
4515     
4516     return i_result;
4517 }
4518
4519 chapter_item_c *chapter_item_c::FindTimecode( mtime_t i_user_timecode )
4520 {
4521     chapter_item_c *psz_result = NULL;
4522
4523     if ( i_user_timecode >= i_user_start_time && 
4524         ( i_user_timecode < i_user_end_time || 
4525           ( i_user_start_time == i_user_end_time && i_user_timecode == i_user_end_time )))
4526     {
4527         std::vector<chapter_item_c*>::iterator index = sub_chapters.begin();
4528         while ( index != sub_chapters.end() && psz_result == NULL )
4529         {
4530             psz_result = (*index)->FindTimecode( i_user_timecode );
4531             index++;
4532         }
4533         
4534         if ( psz_result == NULL )
4535             psz_result = this;
4536     }
4537
4538     return psz_result;
4539 }
4540
4541 bool chapter_item_c::ParentOf( const chapter_item_c & item ) const
4542 {
4543     if ( &item == this )
4544         return true;
4545
4546     std::vector<chapter_item_c*>::const_iterator index = sub_chapters.begin();
4547     while ( index != sub_chapters.end() )
4548     {
4549         if ( (*index)->ParentOf( item ) )
4550             return true;
4551         index++;
4552     }
4553
4554     return false;
4555 }
4556
4557 void demux_sys_t::PreloadFamily( const matroska_segment_c & of_segment )
4558 {
4559     for (size_t i=0; i<opened_segments.size(); i++)
4560     {
4561         opened_segments[i]->PreloadFamily( of_segment );
4562     }
4563 }
4564 bool matroska_segment_c::PreloadFamily( const matroska_segment_c & of_segment )
4565 {
4566     if ( b_preloaded )
4567         return false;
4568
4569     for (size_t i=0; i<families.size(); i++)
4570     {
4571         for (size_t j=0; j<of_segment.families.size(); j++)
4572         {
4573             if ( families[i] == of_segment.families[j] )
4574                 return Preload( );
4575         }
4576     }
4577
4578     return false;
4579 }
4580
4581 // preload all the linked segments for all preloaded segments
4582 void demux_sys_t::PreloadLinked( matroska_segment_c *p_segment )
4583 {
4584     size_t i_preloaded, i, j;
4585     virtual_segment_c *p_seg;
4586
4587     p_current_segment = VirtualFromSegments( p_segment );
4588     
4589     used_segments.push_back( p_current_segment );
4590
4591     // create all the other virtual segments of the family
4592     do {
4593         i_preloaded = 0;
4594         for ( i=0; i< opened_segments.size(); i++ )
4595         {
4596             if ( opened_segments[i]->b_preloaded && !IsUsedSegment( *opened_segments[i] ) )
4597             {
4598                 p_seg = VirtualFromSegments( opened_segments[i] );
4599                 used_segments.push_back( p_seg );
4600                 i_preloaded++;
4601             }
4602         }
4603     } while ( i_preloaded ); // worst case: will stop when all segments are found as family related
4604
4605     // publish all editions of all usable segment
4606     for ( i=0; i< used_segments.size(); i++ )
4607     {
4608         p_seg = used_segments[i];
4609         if ( p_seg->p_editions != NULL )
4610         {
4611             std::string sz_name;
4612             input_title_t *p_title = vlc_input_title_New();
4613             p_seg->i_sys_title = i;
4614             int i_chapters;
4615
4616             // TODO use a name for each edition, let the TITLE deal with a codec name
4617             for ( j=0; j<p_seg->p_editions->size(); j++ )
4618             {
4619                 if ( p_title->psz_name == NULL )
4620                 {
4621                     sz_name = (*p_seg->p_editions)[j]->GetMainName();
4622                     if ( sz_name != "" )
4623                         p_title->psz_name = strdup( sz_name.c_str() );
4624                 }
4625
4626                 chapter_edition_c *p_edition = (*p_seg->p_editions)[j];
4627
4628                 i_chapters = 0;
4629                 p_edition->PublishChapters( *p_title, i_chapters, 0 );
4630             }
4631
4632             // create a name if there is none
4633             if ( p_title->psz_name == NULL )
4634             {
4635                 sz_name = N_("Segment ");
4636                 char psz_str[6];
4637                 sprintf( psz_str, "%d", i );
4638                 sz_name += psz_str;
4639                 p_title->psz_name = strdup( sz_name.c_str() );
4640             }
4641
4642             titles.push_back( *p_title );
4643         }
4644     }
4645
4646     // TODO decide which segment should be first used (VMG for DVD)
4647 }
4648
4649 bool demux_sys_t::IsUsedSegment( matroska_segment_c &segment ) const
4650 {
4651     for ( size_t i=0; i< used_segments.size(); i++ )
4652     {
4653         if ( used_segments[i]->FindUID( segment.segment_uid ) )
4654             return true;
4655     }
4656     return false;
4657 }
4658
4659 virtual_segment_c *demux_sys_t::VirtualFromSegments( matroska_segment_c *p_segment ) const
4660 {
4661     size_t i_preloaded, i;
4662
4663     virtual_segment_c *p_result = new virtual_segment_c( p_segment );
4664
4665     // fill our current virtual segment with all hard linked segments
4666     do {
4667         i_preloaded = 0;
4668         for ( i=0; i< opened_segments.size(); i++ )
4669         {
4670             i_preloaded += p_result->AddSegment( opened_segments[i] );
4671         }
4672     } while ( i_preloaded ); // worst case: will stop when all segments are found as linked
4673
4674     p_result->Sort( );
4675
4676     p_result->PreloadLinked( );
4677
4678     p_result->PrepareChapters( );
4679
4680     return p_result;
4681 }
4682
4683 bool demux_sys_t::PreparePlayback( virtual_segment_c *p_new_segment )
4684 {
4685     if ( p_new_segment != NULL && p_new_segment != p_current_segment )
4686     {
4687         if ( p_current_segment != NULL && p_current_segment->Segment() != NULL )
4688             p_current_segment->Segment()->UnSelect();
4689
4690         p_current_segment = p_new_segment;
4691         i_current_title = p_new_segment->i_sys_title;
4692     }
4693
4694     p_current_segment->LoadCues();
4695     f_duration = p_current_segment->Duration();
4696
4697     /* add information */
4698     p_current_segment->Segment()->InformationCreate( );
4699
4700     p_current_segment->Segment()->Select( 0 );
4701
4702     return true;
4703 }
4704
4705 bool matroska_segment_c::CompareSegmentUIDs( const matroska_segment_c * p_item_a, const matroska_segment_c * p_item_b )
4706 {
4707     EbmlBinary * p_itema = (EbmlBinary *)(&p_item_a->segment_uid);
4708     if ( *p_itema == p_item_b->prev_segment_uid )
4709         return true;
4710
4711     p_itema = (EbmlBinary *)(&p_item_a->next_segment_uid);
4712     if ( *p_itema == p_item_b->segment_uid )
4713         return true;
4714
4715     if ( *p_itema == p_item_b->prev_segment_uid )
4716         return true;
4717
4718     return false;
4719 }
4720
4721 bool matroska_segment_c::Preload( )
4722 {
4723     if ( b_preloaded )
4724         return false;
4725
4726     EbmlElement *el = NULL;
4727
4728     ep->Reset( &sys.demuxer );
4729
4730     while( ( el = ep->Get() ) != NULL )
4731     {
4732         if( MKV_IS_ID( el, KaxInfo ) )
4733         {
4734             ParseInfo( static_cast<KaxInfo*>( el ) );
4735         }
4736         else if( MKV_IS_ID( el, KaxTracks ) )
4737         {
4738             ParseTracks( static_cast<KaxTracks*>( el ) );
4739         }
4740         else if( MKV_IS_ID( el, KaxSeekHead ) )
4741         {
4742             ParseSeekHead( static_cast<KaxSeekHead*>( el ) );
4743         }
4744         else if( MKV_IS_ID( el, KaxCues ) )
4745         {
4746             msg_Dbg( &sys.demuxer, "|   + Cues" );
4747         }
4748         else if( MKV_IS_ID( el, KaxCluster ) )
4749         {
4750             msg_Dbg( &sys.demuxer, "|   + Cluster" );
4751
4752             cluster = (KaxCluster*)el;
4753
4754             i_start_pos = cluster->GetElementPosition();
4755             ParseCluster( );
4756
4757             ep->Down();
4758             /* stop parsing the stream */
4759             break;
4760         }
4761         else if( MKV_IS_ID( el, KaxAttachments ) )
4762         {
4763             msg_Dbg( &sys.demuxer, "|   + Attachments FIXME (but probably never supported)" );
4764         }
4765         else if( MKV_IS_ID( el, KaxChapters ) )
4766         {
4767             msg_Dbg( &sys.demuxer, "|   + Chapters" );
4768             ParseChapters( static_cast<KaxChapters*>( el ) );
4769         }
4770         else if( MKV_IS_ID( el, KaxTag ) )
4771         {
4772             msg_Dbg( &sys.demuxer, "|   + Tags FIXME TODO" );
4773         }
4774         else
4775         {
4776             msg_Dbg( &sys.demuxer, "|   + Unknown (%s)", typeid(*el).name() );
4777         }
4778     }
4779
4780     b_preloaded = true;
4781
4782     return true;
4783 }
4784
4785 matroska_segment_c *demux_sys_t::FindSegment( const EbmlBinary & uid ) const
4786 {
4787     for (size_t i=0; i<opened_segments.size(); i++)
4788     {
4789         if ( opened_segments[i]->segment_uid == uid )
4790             return opened_segments[i];
4791     }
4792     return NULL;
4793 }
4794
4795 chapter_item_c *demux_sys_t::BrowseCodecPrivate( unsigned int codec_id, 
4796                                         bool (*match)(const chapter_codec_cmds_c &data, const void *p_cookie, size_t i_cookie_size ), 
4797                                         const void *p_cookie, 
4798                                         size_t i_cookie_size, 
4799                                         virtual_segment_c * &p_segment_found )
4800 {
4801     chapter_item_c *p_result = NULL;
4802     for (size_t i=0; i<used_segments.size(); i++)
4803     {
4804         p_result = used_segments[i]->BrowseCodecPrivate( codec_id, match, p_cookie, i_cookie_size );
4805         if ( p_result != NULL )
4806         {
4807             p_segment_found = used_segments[i];
4808             break;
4809         }
4810     }
4811     return p_result;
4812 }
4813
4814 chapter_item_c *demux_sys_t::FindChapter( int64_t i_find_uid, virtual_segment_c * & p_segment_found )
4815 {
4816     chapter_item_c *p_result = NULL;
4817     for (size_t i=0; i<used_segments.size(); i++)
4818     {
4819         p_result = used_segments[i]->FindChapter( i_find_uid );
4820         if ( p_result != NULL )
4821         {
4822             p_segment_found = used_segments[i];
4823             break;
4824         }
4825     }
4826     return p_result;
4827 }
4828
4829 void virtual_segment_c::Sort()
4830 {
4831     // keep the current segment index
4832     matroska_segment_c *p_segment = linked_segments[i_current_segment];
4833
4834     std::sort( linked_segments.begin(), linked_segments.end(), matroska_segment_c::CompareSegmentUIDs );
4835
4836     for ( i_current_segment=0; i_current_segment<linked_segments.size(); i_current_segment++)
4837         if ( linked_segments[i_current_segment] == p_segment )
4838             break;
4839 }
4840
4841 size_t virtual_segment_c::AddSegment( matroska_segment_c *p_segment )
4842 {
4843     size_t i;
4844     // check if it's not already in here
4845     for ( i=0; i<linked_segments.size(); i++ )
4846     {
4847         if ( p_segment->segment_uid == linked_segments[i]->segment_uid )
4848             return 0;
4849     }
4850
4851     // find possible mates
4852     for ( i=0; i<linked_uids.size(); i++ )
4853     {
4854         if (   p_segment->segment_uid == linked_uids[i] 
4855             || p_segment->prev_segment_uid == linked_uids[i] 
4856             || p_segment->next_segment_uid == linked_uids[i] )
4857         {
4858             linked_segments.push_back( p_segment );
4859
4860             AppendUID( p_segment->prev_segment_uid );
4861             AppendUID( p_segment->next_segment_uid );
4862
4863             return 1;
4864         }
4865     }
4866     return 0;
4867 }
4868
4869 void virtual_segment_c::PreloadLinked( )
4870 {
4871     for ( size_t i=0; i<linked_segments.size(); i++ )
4872     {
4873         linked_segments[i]->Preload( );
4874     }
4875     i_current_edition = linked_segments[0]->i_default_edition;
4876 }
4877
4878 mtime_t virtual_segment_c::Duration() const
4879 {
4880     mtime_t i_duration;
4881     if ( linked_segments.size() == 0 )
4882         i_duration = 0;
4883     else {
4884         matroska_segment_c *p_last_segment = linked_segments[linked_segments.size()-1];
4885 //        p_last_segment->ParseCluster( );
4886
4887         i_duration = p_last_segment->i_start_time / 1000 + p_last_segment->i_duration;
4888     }
4889     return i_duration;
4890 }
4891
4892 void virtual_segment_c::LoadCues( )
4893 {
4894     for ( size_t i=0; i<linked_segments.size(); i++ )
4895     {
4896         linked_segments[i]->LoadCues();
4897     }
4898 }
4899
4900 void virtual_segment_c::AppendUID( const EbmlBinary & UID )
4901 {
4902     if ( UID.GetBuffer() == NULL )
4903         return;
4904
4905     for (size_t i=0; i<linked_uids.size(); i++)
4906     {
4907         if ( UID == linked_uids[i] )
4908             return;
4909     }
4910     linked_uids.push_back( *(KaxSegmentUID*)(&UID) );
4911 }
4912
4913 void matroska_segment_c::Seek( mtime_t i_date, mtime_t i_time_offset )
4914 {
4915     KaxBlock    *block;
4916     int         i_track_skipping;
4917     int64_t     i_block_duration;
4918     int64_t     i_block_ref1;
4919     int64_t     i_block_ref2;
4920     size_t      i_track;
4921     int64_t     i_seek_position = i_start_pos;
4922     int64_t     i_seek_time = i_start_time;
4923
4924     if ( i_index > 0 )
4925     {
4926         int i_idx = 0;
4927
4928         for( ; i_idx < i_index; i_idx++ )
4929         {
4930             if( index[i_idx].i_time + i_time_offset > i_date )
4931             {
4932                 break;
4933             }
4934         }
4935
4936         if( i_idx > 0 )
4937         {
4938             i_idx--;
4939         }
4940
4941         i_seek_position = index[i_idx].i_position;
4942         i_seek_time = index[i_idx].i_time;
4943     }
4944
4945     msg_Dbg( &sys.demuxer, "seek got "I64Fd" (%d%%)",
4946                 i_seek_time, (int)( 100 * i_seek_position / stream_Size( sys.demuxer.s ) ) );
4947
4948     es.I_O().setFilePointer( i_seek_position, seek_beginning );
4949
4950     delete ep;
4951     ep = new EbmlParser( &es, segment, &sys.demuxer );
4952     cluster = NULL;
4953
4954     sys.i_start_pts = i_date;
4955
4956     es_out_Control( sys.demuxer.out, ES_OUT_RESET_PCR );
4957
4958     /* now parse until key frame */
4959     i_track_skipping = 0;
4960     for( i_track = 0; i_track < tracks.size(); i_track++ )
4961     {
4962         if( tracks[i_track]->fmt.i_cat == VIDEO_ES )
4963         {
4964             tracks[i_track]->b_search_keyframe = VLC_TRUE;
4965             i_track_skipping++;
4966         }
4967         es_out_Control( sys.demuxer.out, ES_OUT_SET_NEXT_DISPLAY_TIME, tracks[i_track]->p_es, i_date );
4968     }
4969
4970
4971     while( i_track_skipping > 0 )
4972     {
4973         if( BlockGet( &block, &i_block_ref1, &i_block_ref2, &i_block_duration ) )
4974         {
4975             msg_Warn( &sys.demuxer, "cannot get block EOF?" );
4976
4977             return;
4978         }
4979
4980         for( i_track = 0; i_track < tracks.size(); i_track++ )
4981         {
4982             if( tracks[i_track]->i_number == block->TrackNum() )
4983             {
4984                 break;
4985             }
4986         }
4987
4988         sys.i_pts = sys.i_chapter_time + block->GlobalTimecode() / (mtime_t) 1000;
4989
4990         if( i_track < tracks.size() )
4991         {
4992             if( sys.i_pts >= sys.i_start_pts )
4993             {
4994                 BlockDecode( &sys.demuxer, block, sys.i_pts, 0 );
4995                 i_track_skipping = 0;
4996             }
4997             else if( tracks[i_track]->fmt.i_cat == VIDEO_ES )
4998             {
4999                 if( i_block_ref1 == -1 && tracks[i_track]->b_search_keyframe )
5000                 {
5001                     tracks[i_track]->b_search_keyframe = VLC_FALSE;
5002                     i_track_skipping--;
5003                 }
5004                 if( !tracks[i_track]->b_search_keyframe )
5005                 {
5006                     BlockDecode( &sys.demuxer, block, sys.i_pts, 0 );
5007                 }
5008             } 
5009         }
5010
5011         delete block;
5012     }
5013 }
5014
5015 void virtual_segment_c::Seek( demux_t & demuxer, mtime_t i_date, mtime_t i_time_offset, chapter_item_c *psz_chapter )
5016 {
5017     demux_sys_t *p_sys = demuxer.p_sys;
5018     size_t i;
5019
5020     // find the actual time for an ordered edition
5021     if ( psz_chapter == NULL )
5022     {
5023         if ( Edition() && Edition()->b_ordered )
5024         {
5025             /* 1st, we need to know in which chapter we are */
5026             psz_chapter = (*p_editions)[i_current_edition]->FindTimecode( i_date );
5027         }
5028     }
5029
5030     if ( psz_chapter != NULL )
5031     {
5032         psz_current_chapter = psz_chapter;
5033         p_sys->i_chapter_time = i_time_offset = psz_chapter->i_user_start_time - psz_chapter->i_start_time;
5034         if ( psz_chapter->i_seekpoint_num > 0 )
5035         {
5036             demuxer.info.i_update |= INPUT_UPDATE_TITLE | INPUT_UPDATE_SEEKPOINT;
5037             demuxer.info.i_title = p_sys->i_current_title = i_sys_title;
5038             demuxer.info.i_seekpoint = psz_chapter->i_seekpoint_num - 1;
5039         }
5040     }
5041
5042     // find the best matching segment
5043     for ( i=0; i<linked_segments.size(); i++ )
5044     {
5045         if ( i_date < linked_segments[i]->i_start_time )
5046             break;
5047     }
5048
5049     if ( i > 0 )
5050         i--;
5051
5052     if ( i_current_segment != i  )
5053     {
5054         linked_segments[i_current_segment]->UnSelect();
5055         linked_segments[i]->Select( i_date );
5056         i_current_segment = i;
5057     }
5058
5059     linked_segments[i]->Seek( i_date, i_time_offset );
5060 }
5061
5062 void chapter_codec_cmds_c::AddCommand( const KaxChapterProcessCommand & command )
5063 {
5064     size_t i;
5065
5066     uint32 codec_time = uint32(-1);
5067     for( i = 0; i < command.ListSize(); i++ )
5068     {
5069         const EbmlElement *k = command[i];
5070
5071         if( MKV_IS_ID( k, KaxChapterProcessTime ) )
5072         {
5073             codec_time = uint32( *static_cast<const KaxChapterProcessTime*>( k ) );
5074             break;
5075         }
5076     }
5077
5078     for( i = 0; i < command.ListSize(); i++ )
5079     {
5080         const EbmlElement *k = command[i];
5081
5082         if( MKV_IS_ID( k, KaxChapterProcessData ) )
5083         {
5084             KaxChapterProcessData *p_data =  new KaxChapterProcessData( *static_cast<const KaxChapterProcessData*>( k ) );
5085             switch ( codec_time )
5086             {
5087             case 0:
5088                 during_cmds.push_back( *p_data );
5089                 break;
5090             case 1:
5091                 enter_cmds.push_back( *p_data );
5092                 break;
5093             case 2:
5094                 leave_cmds.push_back( *p_data );
5095                 break;
5096             default:
5097                 delete p_data;
5098             }
5099         }
5100     }
5101 }
5102
5103 bool chapter_item_c::Enter( bool b_do_subs )
5104 {
5105     bool f_result = false;
5106     std::vector<chapter_codec_cmds_c*>::iterator index = codecs.begin();
5107     while ( index != codecs.end() )
5108     {
5109         f_result |= (*index)->Enter();
5110         index++;
5111     }
5112
5113     if ( b_do_subs )
5114     {
5115         // sub chapters
5116         std::vector<chapter_item_c*>::iterator index_ = sub_chapters.begin();
5117         while ( index_ != sub_chapters.end() )
5118         {
5119             f_result |= (*index_)->Enter( true );
5120             index_++;
5121         }
5122     }
5123     return f_result;
5124 }
5125
5126 bool chapter_item_c::Leave( bool b_do_subs )
5127 {
5128     bool f_result = false;
5129     b_is_leaving = true;
5130     std::vector<chapter_codec_cmds_c*>::iterator index = codecs.begin();
5131     while ( index != codecs.end() )
5132     {
5133         f_result |= (*index)->Leave();
5134         index++;
5135     }
5136
5137     if ( b_do_subs )
5138     {
5139         // sub chapters
5140         std::vector<chapter_item_c*>::iterator index_ = sub_chapters.begin();
5141         while ( index_ != sub_chapters.end() )
5142         {
5143             f_result |= (*index_)->Leave( true );
5144             index_++;
5145         }
5146     }
5147     b_is_leaving = false;
5148     return f_result;
5149 }
5150
5151 bool chapter_item_c::EnterAndLeave( chapter_item_c *p_item )
5152 {
5153     chapter_item_c *p_common_parent = p_item;
5154
5155     // leave, up to a common parent
5156     while ( p_common_parent != NULL && !p_common_parent->ParentOf( *this ) )
5157     {
5158         if ( !p_common_parent->b_is_leaving && p_common_parent->Leave( false ) )
5159             return true;
5160         p_common_parent = p_common_parent->psz_parent;
5161     }
5162
5163     // enter from the parent to <this>
5164     if ( p_common_parent != NULL )
5165     {
5166         do
5167         {
5168             if ( p_common_parent == this )
5169                 return Enter( true );
5170
5171             for ( size_t i = 0; i<p_common_parent->sub_chapters.size(); i++ )
5172             {
5173                 if ( p_common_parent->sub_chapters[i]->ParentOf( *this ) )
5174                 {
5175                     p_common_parent = p_common_parent->sub_chapters[i];
5176                     if ( p_common_parent != this )
5177                         if ( p_common_parent->Enter( false ) )
5178                             return true;
5179
5180                     break;
5181                 }
5182             }
5183         } while ( 1 );
5184     }
5185
5186     return Enter( true );
5187 }
5188
5189 bool dvd_chapter_codec_c::Enter()
5190 {
5191     bool f_result = false;
5192     std::vector<KaxChapterProcessData>::iterator index = enter_cmds.begin();
5193     while ( index != enter_cmds.end() )
5194     {
5195         if ( (*index).GetSize() )
5196         {
5197             binary *p_data = (*index).GetBuffer();
5198             size_t i_size = *p_data++;
5199             // avoid reading too much from the buffer
5200             i_size = min( i_size, ((*index).GetSize() - 1) >> 3 );
5201             for ( ; i_size > 0; i_size--, p_data += 8 )
5202             {
5203                 msg_Dbg( &sys.demuxer, "Matroska DVD enter command" );
5204                 f_result |= sys.dvd_interpretor.Interpret( p_data );
5205             }
5206         }
5207         index++;
5208     }
5209     return f_result;
5210 }
5211
5212 bool dvd_chapter_codec_c::Leave()
5213 {
5214     bool f_result = false;
5215     std::vector<KaxChapterProcessData>::iterator index = leave_cmds.begin();
5216     while ( index != leave_cmds.end() )
5217     {
5218         if ( (*index).GetSize() )
5219         {
5220             binary *p_data = (*index).GetBuffer();
5221             size_t i_size = *p_data++;
5222             // avoid reading too much from the buffer
5223             i_size = min( i_size, ((*index).GetSize() - 1) >> 3 );
5224             for ( ; i_size > 0; i_size--, p_data += 8 )
5225             {
5226                 msg_Dbg( &sys.demuxer, "Matroska DVD leave command" );
5227                 f_result |= sys.dvd_interpretor.Interpret( p_data );
5228             }
5229         }
5230         index++;
5231     }
5232     return f_result;
5233 }
5234
5235 // see http://www.dvd-replica.com/DVD/vmcmdset.php for a description of DVD commands
5236 bool dvd_command_interpretor_c::Interpret( const binary * p_command, size_t i_size )
5237 {
5238     if ( i_size != 8 )
5239         return false;
5240
5241     virtual_segment_c *p_segment;
5242     chapter_item_c *p_chapter;
5243     bool f_result = false;
5244     uint16 i_command = ( p_command[0] << 8 ) + p_command[1];
5245
5246     // handle register tests if there are some
5247     if ( (i_command & 0xF0) != 0 )
5248     {
5249         bool b_test_positive = (i_command & CMD_DVD_IF_NOT) == 0;
5250         bool b_test_value    = (i_command & CMD_DVD_TEST_VALUE) != 0;
5251         uint8 i_test = i_command & 0x70;
5252         uint16 i_value;
5253
5254         if ( b_test_value )
5255             i_value = ( p_command[4] << 8 ) + p_command[5];
5256         else
5257             i_value = GetPRM( p_command[7] );
5258
5259         switch ( i_test )
5260         {
5261         case CMD_DVD_IF_GPREG_EQUAL:
5262             // if equals
5263             msg_Dbg( &sys.demuxer, "IF %s EQUALS %s", GetRegTypeName( false, p_command[3] ).c_str(), GetRegTypeName( b_test_value, i_value ).c_str() );
5264             if (!( GetPRM( p_command[3] ) == i_value ))
5265             {
5266                 b_test_positive = !b_test_positive;
5267             }
5268             break;
5269         case CMD_DVD_IF_GPREG_INF:
5270             // if inferior
5271             msg_Dbg( &sys.demuxer, "IF %s < %s", GetRegTypeName( false, p_command[3] ).c_str(), GetRegTypeName( b_test_value, i_value ).c_str() );
5272             if (!( GetPRM( p_command[3] ) < i_value ))
5273             {
5274                 b_test_positive = !b_test_positive;
5275             }
5276             break;
5277         case CMD_DVD_IF_GPREG_AND:
5278             // if logical and
5279             msg_Dbg( &sys.demuxer, "IF %s & %s", GetRegTypeName( false, p_command[3] ).c_str(), GetRegTypeName( b_test_value, i_value ).c_str() );
5280             if (!( GetPRM( p_command[3] ) & i_value ))
5281             {
5282                 b_test_positive = !b_test_positive;
5283             }
5284             break;
5285         case CMD_DVD_IF_GPREG_SUP_EQUAL:
5286             // if superior or equal
5287             msg_Dbg( &sys.demuxer, "IF %s >= %s", GetRegTypeName( false, p_command[3] ).c_str(), GetRegTypeName( b_test_value, i_value ).c_str() );
5288             if (!( GetPRM( p_command[3] ) >= i_value ))
5289             {
5290                 b_test_positive = !b_test_positive;
5291             }
5292             break;
5293         }
5294
5295         if ( !b_test_positive )
5296             return false;
5297     }
5298     
5299     // strip the test command
5300     i_command &= 0xFF0F;
5301     
5302     switch ( i_command )
5303     {
5304     case CMD_DVD_NOP:
5305     case CMD_DVD_NOP2:
5306         {
5307             msg_Dbg( &sys.demuxer, "NOP" );
5308             break;
5309         }
5310     case CMD_DVD_BREAK:
5311         {
5312             msg_Dbg( &sys.demuxer, "Break" );
5313             // TODO
5314             break;
5315         }
5316     case CMD_DVD_JUMP_TT:
5317         {
5318             uint8 i_title = p_command[5];
5319             msg_Dbg( &sys.demuxer, "JumpTT %d", i_title );
5320
5321             // find in the ChapProcessPrivate matching this Title level
5322             p_chapter = sys.BrowseCodecPrivate( 1, MatchTitleNumber, &i_title, sizeof(i_title), p_segment );
5323             if ( p_chapter != NULL )
5324             {
5325                 // if the segment is not part of the current segment, select the new one
5326                 if ( p_segment != sys.p_current_segment )
5327                 {
5328                     sys.PreparePlayback( p_segment );
5329                 }
5330     
5331                 // jump to the location in the found segment
5332                 p_segment->Seek( sys.demuxer, p_chapter->i_user_start_time, -1, NULL );
5333                 p_chapter->Enter( true );
5334                 
5335                 f_result = true;
5336             }
5337
5338             break;
5339         }
5340     case CMD_DVD_CALLSS_VTSM1:
5341         {
5342             msg_Dbg( &sys.demuxer, "CallSS VTSM" );
5343             switch( (p_command[6] & 0xC0) >> 6 ) {
5344                 case 0:
5345                     switch ( p_command[5] )
5346                     {
5347                     case 0x00:
5348                         msg_Dbg( &sys.demuxer, "CallSS PGC (rsm_cell %x)", p_command[5]);
5349                         break;
5350                     case 0x82:
5351                         msg_Dbg( &sys.demuxer, "CallSS Title Entry (rsm_cell %x)", p_command[5]);
5352                         break;
5353                     case 0x83:
5354                         msg_Dbg( &sys.demuxer, "CallSS Root Menu (rsm_cell %x)", p_command[5]);
5355                         break;
5356                     case 0x84:
5357                         msg_Dbg( &sys.demuxer, "CallSS Subpicture Menu (rsm_cell %x)", p_command[5]);
5358                         break;
5359                     case 0x85:
5360                         msg_Dbg( &sys.demuxer, "CallSS Audio Menu (rsm_cell %x)", p_command[5]);
5361                         break;
5362                     case 0x86:
5363                         msg_Dbg( &sys.demuxer, "CallSS Angle Menu (rsm_cell %x)", p_command[5]);
5364                         break;
5365                     case 0x87:
5366                         msg_Dbg( &sys.demuxer, "CallSS Chapter Menu (rsm_cell %x)", p_command[5]);
5367                         break;
5368                     default:
5369                         msg_Dbg( &sys.demuxer, "CallSS <unknown> (rsm_cell %x)", p_command[5]);
5370                         break;
5371                     }
5372                     p_chapter = sys.BrowseCodecPrivate( 1, MatchPgcType, &p_command[5], 1, p_segment );
5373                     if ( p_chapter != NULL )
5374                     {
5375                         // if the segment is not part of the current segment, select the new one
5376                         if ( p_segment != sys.p_current_segment )
5377                         {
5378                             sys.PreparePlayback( p_segment );
5379                         }
5380             
5381                         p_chapter->Enter( true );
5382                         
5383                         // jump to the location in the found segment
5384                         p_segment->Seek( sys.demuxer, p_chapter->i_user_start_time, -1, p_chapter );
5385                         f_result = true;
5386                     }
5387                 break;
5388                 case 1:
5389                     msg_Dbg( &sys.demuxer, "CallSS VMGM (menu %d, rsm_cell %x)", p_command[6] & 0x0F, p_command[5]);
5390                 break;
5391                 case 2:
5392                     msg_Dbg( &sys.demuxer, "CallSS VTSM (menu %d, rsm_cell %x)", p_command[6] & 0x0F, p_command[5]);
5393                 break;
5394                 case 3:
5395                     msg_Dbg( &sys.demuxer, "CallSS VMGM (pgc %d, rsm_cell %x)", (p_command[3] << 8) + p_command[4], p_command[5]);
5396                 break;
5397             }
5398             break;
5399         }
5400     case CMD_DVD_SET_GPRMMD:
5401         {
5402             msg_Dbg( &sys.demuxer, "Set GPRMMD [%d]=%d", (p_command[4] << 8) + p_command[5], (p_command[2] << 8) + p_command[3]);
5403             
5404             if ( !SetGPRM( (p_command[4] << 8) + p_command[5], (p_command[2] << 8) + p_command[3] ) )
5405                 msg_Dbg( &sys.demuxer, "Set GPRMMD failed" );
5406             break;
5407         }
5408     case CMD_DVD_LINKPGCN:
5409         {
5410             uint16 i_pgcn = (p_command[6] << 8) + p_command[7];
5411             
5412             msg_Dbg( &sys.demuxer, "Link PGCN(%d)", i_pgcn );
5413             p_chapter = sys.BrowseCodecPrivate( 1, MatchPgcNumber, &i_pgcn, 1, p_segment );
5414             if ( p_chapter != NULL )
5415             {
5416                 // if the segment is not part of the current segment, select the new one
5417                 if ( p_segment != sys.p_current_segment )
5418                 {
5419                     sys.PreparePlayback( p_segment );
5420                 }
5421
5422                 p_chapter->Enter( true );
5423                 
5424                 // jump to the location in the found segment
5425                 p_segment->Seek( sys.demuxer, p_chapter->i_user_start_time, -1, p_chapter );
5426                 f_result = true;
5427             }
5428             break;
5429         }
5430     case CMD_DVD_LINKCN:
5431         {
5432             msg_Dbg( &sys.demuxer, "LinkCN (cell %d)", (p_command[6] << 8) + p_command[7] );
5433             // TODO
5434             f_result = true;
5435             break;
5436         }
5437     case CMD_DVD_GOTO_LINE:
5438         {
5439             msg_Dbg( &sys.demuxer, "GotoLine (%d)", (p_command[6] << 8) + p_command[7] );
5440             // TODO
5441             break;
5442         }
5443     default:
5444         {
5445             msg_Dbg( &sys.demuxer, "unsupported command : %02X %02X %02X %02X %02X %02X %02X %02X"
5446                      ,p_command[0]
5447                      ,p_command[1]
5448                      ,p_command[2]
5449                      ,p_command[3]
5450                      ,p_command[4]
5451                      ,p_command[5]
5452                      ,p_command[6]
5453                      ,p_command[7]);
5454             break;
5455         }
5456     }
5457
5458     return f_result;
5459 }
5460
5461 bool dvd_command_interpretor_c::MatchTitleNumber( const chapter_codec_cmds_c &data, const void *p_cookie, size_t i_cookie_size )
5462 {
5463     if ( i_cookie_size != 1 || data.m_private_data.GetSize() < 4 )
5464         return false;
5465     
5466     if ( data.m_private_data.GetBuffer()[0] != MATROSKA_DVD_LEVEL_TT )
5467         return false;
5468
5469     uint16 i_gtitle = (data.m_private_data.GetBuffer()[1] << 8 ) + data.m_private_data.GetBuffer()[2];
5470     uint8 i_title = *(uint8*)p_cookie;
5471
5472     return (i_gtitle == i_title);
5473 }
5474
5475 bool dvd_command_interpretor_c::MatchPgcType( const chapter_codec_cmds_c &data, const void *p_cookie, size_t i_cookie_size )
5476 {
5477     if ( i_cookie_size != 1 || data.m_private_data.GetSize() < 7 )
5478         return false;
5479     
5480     if ( data.m_private_data.GetBuffer()[0] != MATROSKA_DVD_LEVEL_PGC )
5481         return false;
5482
5483     uint8 i_pgc_type = data.m_private_data.GetBuffer()[3];
5484     uint8 i_pgc = *(uint8*)p_cookie;
5485
5486     return (i_pgc_type == i_pgc);
5487 }
5488
5489 bool dvd_command_interpretor_c::MatchPgcNumber( const chapter_codec_cmds_c &data, const void *p_cookie, size_t i_cookie_size )
5490 {
5491     if ( i_cookie_size != 1 || data.m_private_data.GetSize() < 7 )
5492         return false;
5493     
5494     if ( data.m_private_data.GetBuffer()[0] != MATROSKA_DVD_LEVEL_PGC )
5495         return false;
5496
5497     uint16 *i_pgc_n = (uint16 *)p_cookie;
5498     uint16 i_pgc_num = (data.m_private_data.GetBuffer()[1] << 8) + data.m_private_data.GetBuffer()[2];
5499
5500     return (i_pgc_num == *i_pgc_n);
5501 }
5502
5503 bool matroska_script_codec_c::Enter()
5504 {
5505     bool f_result = false;
5506     std::vector<KaxChapterProcessData>::iterator index = enter_cmds.begin();
5507     while ( index != enter_cmds.end() )
5508     {
5509         if ( (*index).GetSize() )
5510         {
5511             msg_Dbg( &sys.demuxer, "Matroska Script enter command" );
5512             f_result |= interpretor.Interpret( (*index).GetBuffer(), (*index).GetSize() );
5513         }
5514         index++;
5515     }
5516     return f_result;
5517 }
5518
5519 bool matroska_script_codec_c::Leave()
5520 {
5521     bool f_result = false;
5522     std::vector<KaxChapterProcessData>::iterator index = leave_cmds.begin();
5523     while ( index != leave_cmds.end() )
5524     {
5525         if ( (*index).GetSize() )
5526         {
5527             msg_Dbg( &sys.demuxer, "Matroska Script leave command" );
5528             f_result |= interpretor.Interpret( (*index).GetBuffer(), (*index).GetSize() );
5529         }
5530         index++;
5531     }
5532     return f_result;
5533 }
5534
5535 // see http://www.matroska.org/technical/specs/chapters/index.html#mscript 
5536 //  for a description of existing commands
5537 bool matroska_script_interpretor_c::Interpret( const binary * p_command, size_t i_size )
5538 {
5539     bool b_result = false;
5540
5541     char *psz_str = (char*) malloc( i_size + 1 );
5542     memcpy( psz_str, p_command, i_size );
5543     psz_str[ i_size ] = '\0';
5544
5545     std::string sz_command = psz_str;
5546     free( psz_str );
5547
5548     msg_Dbg( &sys.demuxer, "command : %s", sz_command.c_str() );
5549
5550     if ( sz_command.compare( 0, CMD_MS_GOTO_AND_PLAY.size(), CMD_MS_GOTO_AND_PLAY ) == 0 )
5551     {
5552         size_t i,j;
5553
5554         // find the (
5555         for ( i=CMD_MS_GOTO_AND_PLAY.size(); i<sz_command.size(); i++)
5556         {
5557             if ( sz_command[i] == '(' )
5558             {
5559                 i++;
5560                 break;
5561             }
5562         }
5563         // find the )
5564         for ( j=i; j<sz_command.size(); j++)
5565         {
5566             if ( sz_command[j] == ')' )
5567             {
5568                 i--;
5569                 break;
5570             }
5571         }
5572
5573         std::string st = sz_command.substr( i+1, j-i-1 );
5574         int64_t i_chapter_uid = atoi( st.c_str() );
5575
5576         virtual_segment_c *p_segment;
5577         chapter_item_c *p_chapter = sys.FindChapter( i_chapter_uid, p_segment );
5578
5579         if ( p_chapter == NULL )
5580             msg_Dbg( &sys.demuxer, "Chapter "I64Fd" not found", i_chapter_uid);
5581         else
5582         {
5583             if ( !p_chapter->EnterAndLeave( sys.p_current_segment->CurrentChapter() ) )
5584                 p_segment->Seek( sys.demuxer, p_chapter->i_user_start_time, -1, p_chapter );
5585             b_result = true;
5586         }
5587     }
5588
5589     return b_result;
5590 }
5591
5592 void demux_sys_t::SwapButtons()
5593 {
5594 #ifndef WORDS_BIGENDIAN
5595     uint8_t button, i, j;
5596
5597     for( button = 1; button <= pci_packet.hli.hl_gi.btn_ns; button++) {
5598         btni_t *button_ptr = &(pci_packet.hli.btnit[button-1]);
5599         binary *p_data = (binary*) button_ptr;
5600
5601         uint16 i_x_start = ((p_data[0] & 0x3F) << 4 ) + ( p_data[1] >> 4 );
5602         uint16 i_x_end   = ((p_data[1] & 0x03) << 8 ) + p_data[2];
5603         uint16 i_y_start = ((p_data[3] & 0x3F) << 4 ) + ( p_data[4] >> 4 );
5604         uint16 i_y_end   = ((p_data[4] & 0x03) << 8 ) + p_data[5];
5605         button_ptr->x_start = i_x_start;
5606         button_ptr->x_end   = i_x_end;
5607         button_ptr->y_start = i_y_start;
5608         button_ptr->y_end   = i_y_end;
5609
5610     }
5611     for ( i = 0; i<3; i++ )
5612     {
5613         for ( j = 0; j<2; j++ )
5614         {
5615             pci_packet.hli.btn_colit.btn_coli[i][j] = U32_AT( &pci_packet.hli.btn_colit.btn_coli[i][j] );
5616         }
5617     }
5618 #endif
5619 }