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