]> git.sesse.net Git - vlc/blob - modules/demux/mkv.cpp
mkv.cpp: make the UI hook silent when it's not used
[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         ,b_pci_packet_set(false)
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     bool           b_pci_packet_set;
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                     p_sys->b_pci_packet_set = true;
1821                     vlc_mutex_unlock( &p_sys->p_ev->lock );
1822                     block_Release( p_block );
1823                 }
1824                 return;
1825             }
1826
1827             else if ( strcmp( tk->psz_codec, "S_VOBSUB" ) )
1828             {
1829                 p_block->i_length = i_duration * 1000;
1830             }
1831         }
1832
1833         es_out_Send( p_demux->out, tk->p_es, p_block );
1834
1835         /* use time stamp only for first block */
1836         i_pts = 0;
1837     }
1838
1839 #undef tk
1840 }
1841
1842 matroska_stream_c *demux_sys_t::AnalyseAllSegmentsFound( EbmlStream *p_estream )
1843 {
1844     int i_upper_lvl = 0;
1845     size_t i;
1846     EbmlElement *p_l0, *p_l1, *p_l2;
1847     bool b_keep_stream = false, b_keep_segment;
1848
1849     // verify the EBML Header
1850     p_l0 = p_estream->FindNextID(EbmlHead::ClassInfos, 0xFFFFFFFFL);
1851     if (p_l0 == NULL)
1852     {
1853         return NULL;
1854     }
1855     p_l0->SkipData(*p_estream, EbmlHead_Context);
1856     delete p_l0;
1857
1858     // find all segments in this file
1859     p_l0 = p_estream->FindNextID(KaxSegment::ClassInfos, 0xFFFFFFFFL);
1860     if (p_l0 == NULL)
1861     {
1862         return NULL;
1863     }
1864
1865     matroska_stream_c *p_stream1 = new matroska_stream_c( *this );
1866
1867     while (p_l0 != 0)
1868     {
1869         if (EbmlId(*p_l0) == KaxSegment::ClassInfos.GlobalId)
1870         {
1871             EbmlParser  *ep;
1872             matroska_segment_c *p_segment1 = new matroska_segment_c( *this, *p_estream );
1873             b_keep_segment = false;
1874
1875             ep = new EbmlParser(p_estream, p_l0, &demuxer );
1876             p_segment1->ep = ep;
1877             p_segment1->segment = (KaxSegment*)p_l0;
1878
1879             while ((p_l1 = ep->Get()))
1880             {
1881                 if (MKV_IS_ID(p_l1, KaxInfo))
1882                 {
1883                     // find the families of this segment
1884                     KaxInfo *p_info = static_cast<KaxInfo*>(p_l1);
1885
1886                     p_info->Read(*p_estream, KaxInfo::ClassInfos.Context, i_upper_lvl, p_l2, true);
1887                     for( i = 0; i < p_info->ListSize(); i++ )
1888                     {
1889                         EbmlElement *l = (*p_info)[i];
1890
1891                         if( MKV_IS_ID( l, KaxSegmentUID ) )
1892                         {
1893                             KaxSegmentUID *p_uid = static_cast<KaxSegmentUID*>(l);
1894                             b_keep_segment = (FindSegment( *p_uid ) == NULL);
1895                             if ( !b_keep_segment )
1896                                 break; // this segment is already known
1897                             opened_segments.push_back( p_segment1 );
1898                             p_segment1->segment_uid = *( new KaxSegmentUID(*p_uid) );
1899                         }
1900                         else if( MKV_IS_ID( l, KaxPrevUID ) )
1901                         {
1902                             p_segment1->prev_segment_uid = *( new KaxPrevUID( *static_cast<KaxPrevUID*>(l) ) );
1903                         }
1904                         else if( MKV_IS_ID( l, KaxNextUID ) )
1905                         {
1906                             p_segment1->next_segment_uid = *( new KaxNextUID( *static_cast<KaxNextUID*>(l) ) );
1907                         }
1908                         else if( MKV_IS_ID( l, KaxSegmentFamily ) )
1909                         {
1910                             KaxSegmentFamily *p_fam = new KaxSegmentFamily( *static_cast<KaxSegmentFamily*>(l) );
1911                             p_segment1->families.push_back( *p_fam );
1912                         }
1913                     }
1914                     break;
1915                 }
1916             }
1917             if ( b_keep_segment )
1918             {
1919                 b_keep_stream = true;
1920                 p_stream1->segments.push_back( p_segment1 );
1921             }
1922             else
1923                 delete p_segment1;
1924         }
1925
1926         p_l0->SkipData(*p_estream, EbmlHead_Context);
1927         p_l0 = p_estream->FindNextID(KaxSegment::ClassInfos, 0xFFFFFFFFL);
1928     }
1929
1930     if ( !b_keep_stream )
1931     {
1932         delete p_stream1;
1933         p_stream1 = NULL;
1934     }
1935
1936     return p_stream1;
1937 }
1938
1939 bool matroska_segment_c::Select( mtime_t i_start_time )
1940 {
1941     size_t i_track;
1942
1943     /* add all es */
1944     msg_Dbg( &sys.demuxer, "found %d es", tracks.size() );
1945     sys.b_pci_packet_set = false;
1946     for( i_track = 0; i_track < tracks.size(); i_track++ )
1947     {
1948         if( tracks[i_track]->fmt.i_cat == UNKNOWN_ES )
1949         {
1950             msg_Warn( &sys.demuxer, "invalid track[%d, n=%d]", i_track, tracks[i_track]->i_number );
1951             tracks[i_track]->p_es = NULL;
1952             continue;
1953         }
1954
1955         if( !strcmp( tracks[i_track]->psz_codec, "V_MS/VFW/FOURCC" ) )
1956         {
1957             if( tracks[i_track]->i_extra_data < (int)sizeof( BITMAPINFOHEADER ) )
1958             {
1959                 msg_Err( &sys.demuxer, "missing/invalid BITMAPINFOHEADER" );
1960                 tracks[i_track]->fmt.i_codec = VLC_FOURCC( 'u', 'n', 'd', 'f' );
1961             }
1962             else
1963             {
1964                 BITMAPINFOHEADER *p_bih = (BITMAPINFOHEADER*)tracks[i_track]->p_extra_data;
1965
1966                 tracks[i_track]->fmt.video.i_width = GetDWLE( &p_bih->biWidth );
1967                 tracks[i_track]->fmt.video.i_height= GetDWLE( &p_bih->biHeight );
1968                 tracks[i_track]->fmt.i_codec       = GetFOURCC( &p_bih->biCompression );
1969
1970                 tracks[i_track]->fmt.i_extra       = GetDWLE( &p_bih->biSize ) - sizeof( BITMAPINFOHEADER );
1971                 if( tracks[i_track]->fmt.i_extra > 0 )
1972                 {
1973                     tracks[i_track]->fmt.p_extra = malloc( tracks[i_track]->fmt.i_extra );
1974                     memcpy( tracks[i_track]->fmt.p_extra, &p_bih[1], tracks[i_track]->fmt.i_extra );
1975                 }
1976             }
1977         }
1978         else if( !strcmp( tracks[i_track]->psz_codec, "V_MPEG1" ) ||
1979                  !strcmp( tracks[i_track]->psz_codec, "V_MPEG2" ) )
1980         {
1981             tracks[i_track]->fmt.i_codec = VLC_FOURCC( 'm', 'p', 'g', 'v' );
1982         }
1983         else if( !strncmp( tracks[i_track]->psz_codec, "V_MPEG4", 7 ) )
1984         {
1985             if( !strcmp( tracks[i_track]->psz_codec, "V_MPEG4/MS/V3" ) )
1986             {
1987                 tracks[i_track]->fmt.i_codec = VLC_FOURCC( 'D', 'I', 'V', '3' );
1988             }
1989             else if( !strcmp( tracks[i_track]->psz_codec, "V_MPEG4/ISO/AVC" ) )
1990             {
1991                 tracks[i_track]->fmt.i_codec = VLC_FOURCC( 'a', 'v', 'c', '1' );
1992                 tracks[i_track]->fmt.b_packetized = VLC_FALSE;
1993                 tracks[i_track]->fmt.i_extra = tracks[i_track]->i_extra_data;
1994                 tracks[i_track]->fmt.p_extra = malloc( tracks[i_track]->i_extra_data );
1995                 memcpy( tracks[i_track]->fmt.p_extra,tracks[i_track]->p_extra_data, tracks[i_track]->i_extra_data );
1996             }
1997             else
1998             {
1999                 tracks[i_track]->fmt.i_codec = VLC_FOURCC( 'm', 'p', '4', 'v' );
2000             }
2001         }
2002         else if( !strcmp( tracks[i_track]->psz_codec, "V_QUICKTIME" ) )
2003         {
2004             MP4_Box_t *p_box = (MP4_Box_t*)malloc( sizeof( MP4_Box_t ) );
2005 #ifdef VSLHC
2006             stream_t *p_mp4_stream = stream_MemoryNew( VLC_OBJECT(&sys.demuxer),
2007                                                        tracks[i_track]->p_extra_data,
2008                                                        tracks[i_track]->i_extra_data );
2009 #else
2010             stream_t *p_mp4_stream = stream_MemoryNew( VLC_OBJECT(&sys.demuxer),
2011                                                        tracks[i_track]->p_extra_data,
2012                                                        tracks[i_track]->i_extra_data,
2013                                                        VLC_FALSE );
2014 #endif
2015             MP4_ReadBoxCommon( p_mp4_stream, p_box );
2016             MP4_ReadBox_sample_vide( p_mp4_stream, p_box );
2017             tracks[i_track]->fmt.i_codec = p_box->i_type;
2018             tracks[i_track]->fmt.video.i_width = p_box->data.p_sample_vide->i_width;
2019             tracks[i_track]->fmt.video.i_height = p_box->data.p_sample_vide->i_height;
2020             tracks[i_track]->fmt.i_extra = p_box->data.p_sample_vide->i_qt_image_description;
2021             tracks[i_track]->fmt.p_extra = malloc( tracks[i_track]->fmt.i_extra );
2022             memcpy( tracks[i_track]->fmt.p_extra, p_box->data.p_sample_vide->p_qt_image_description, tracks[i_track]->fmt.i_extra );
2023             MP4_FreeBox_sample_vide( p_box );
2024 #ifdef VSLHC
2025             stream_MemoryDelete( p_mp4_stream, VLC_TRUE );
2026 #else
2027             stream_Delete( p_mp4_stream );
2028 #endif        
2029         }
2030         else if( !strcmp( tracks[i_track]->psz_codec, "A_MS/ACM" ) )
2031         {
2032             if( tracks[i_track]->i_extra_data < (int)sizeof( WAVEFORMATEX ) )
2033             {
2034                 msg_Err( &sys.demuxer, "missing/invalid WAVEFORMATEX" );
2035                 tracks[i_track]->fmt.i_codec = VLC_FOURCC( 'u', 'n', 'd', 'f' );
2036             }
2037             else
2038             {
2039                 WAVEFORMATEX *p_wf = (WAVEFORMATEX*)tracks[i_track]->p_extra_data;
2040
2041                 wf_tag_to_fourcc( GetWLE( &p_wf->wFormatTag ), &tracks[i_track]->fmt.i_codec, NULL );
2042
2043                 tracks[i_track]->fmt.audio.i_channels   = GetWLE( &p_wf->nChannels );
2044                 tracks[i_track]->fmt.audio.i_rate = GetDWLE( &p_wf->nSamplesPerSec );
2045                 tracks[i_track]->fmt.i_bitrate    = GetDWLE( &p_wf->nAvgBytesPerSec ) * 8;
2046                 tracks[i_track]->fmt.audio.i_blockalign = GetWLE( &p_wf->nBlockAlign );;
2047                 tracks[i_track]->fmt.audio.i_bitspersample = GetWLE( &p_wf->wBitsPerSample );
2048
2049                 tracks[i_track]->fmt.i_extra            = GetWLE( &p_wf->cbSize );
2050                 if( tracks[i_track]->fmt.i_extra > 0 )
2051                 {
2052                     tracks[i_track]->fmt.p_extra = malloc( tracks[i_track]->fmt.i_extra );
2053                     memcpy( tracks[i_track]->fmt.p_extra, &p_wf[1], tracks[i_track]->fmt.i_extra );
2054                 }
2055             }
2056         }
2057         else if( !strcmp( tracks[i_track]->psz_codec, "A_MPEG/L3" ) ||
2058                  !strcmp( tracks[i_track]->psz_codec, "A_MPEG/L2" ) ||
2059                  !strcmp( tracks[i_track]->psz_codec, "A_MPEG/L1" ) )
2060         {
2061             tracks[i_track]->fmt.i_codec = VLC_FOURCC( 'm', 'p', 'g', 'a' );
2062         }
2063         else if( !strcmp( tracks[i_track]->psz_codec, "A_AC3" ) )
2064         {
2065             tracks[i_track]->fmt.i_codec = VLC_FOURCC( 'a', '5', '2', ' ' );
2066         }
2067         else if( !strcmp( tracks[i_track]->psz_codec, "A_DTS" ) )
2068         {
2069             tracks[i_track]->fmt.i_codec = VLC_FOURCC( 'd', 't', 's', ' ' );
2070         }
2071         else if( !strcmp( tracks[i_track]->psz_codec, "A_FLAC" ) )
2072         {
2073             tracks[i_track]->fmt.i_codec = VLC_FOURCC( 'f', 'l', 'a', 'c' );
2074             tracks[i_track]->fmt.i_extra = tracks[i_track]->i_extra_data;
2075             tracks[i_track]->fmt.p_extra = malloc( tracks[i_track]->i_extra_data );
2076             memcpy( tracks[i_track]->fmt.p_extra,tracks[i_track]->p_extra_data, tracks[i_track]->i_extra_data );
2077         }
2078         else if( !strcmp( tracks[i_track]->psz_codec, "A_VORBIS" ) )
2079         {
2080             int i, i_offset = 1, i_size[3], i_extra;
2081             uint8_t *p_extra;
2082
2083             tracks[i_track]->fmt.i_codec = VLC_FOURCC( 'v', 'o', 'r', 'b' );
2084
2085             /* Split the 3 headers */
2086             if( tracks[i_track]->p_extra_data[0] != 0x02 )
2087                 msg_Err( &sys.demuxer, "invalid vorbis header" );
2088
2089             for( i = 0; i < 2; i++ )
2090             {
2091                 i_size[i] = 0;
2092                 while( i_offset < tracks[i_track]->i_extra_data )
2093                 {
2094                     i_size[i] += tracks[i_track]->p_extra_data[i_offset];
2095                     if( tracks[i_track]->p_extra_data[i_offset++] != 0xff ) break;
2096                 }
2097             }
2098
2099             i_size[0] = __MIN(i_size[0], tracks[i_track]->i_extra_data - i_offset);
2100             i_size[1] = __MIN(i_size[1], tracks[i_track]->i_extra_data -i_offset -i_size[0]);
2101             i_size[2] = tracks[i_track]->i_extra_data - i_offset - i_size[0] - i_size[1];
2102
2103             tracks[i_track]->fmt.i_extra = 3 * 2 + i_size[0] + i_size[1] + i_size[2];
2104             tracks[i_track]->fmt.p_extra = malloc( tracks[i_track]->fmt.i_extra );
2105             p_extra = (uint8_t *)tracks[i_track]->fmt.p_extra; i_extra = 0;
2106             for( i = 0; i < 3; i++ )
2107             {
2108                 *(p_extra++) = i_size[i] >> 8;
2109                 *(p_extra++) = i_size[i] & 0xFF;
2110                 memcpy( p_extra, tracks[i_track]->p_extra_data + i_offset + i_extra,
2111                         i_size[i] );
2112                 p_extra += i_size[i];
2113                 i_extra += i_size[i];
2114             }
2115         }
2116         else if( !strncmp( tracks[i_track]->psz_codec, "A_AAC/MPEG2/", strlen( "A_AAC/MPEG2/" ) ) ||
2117                  !strncmp( tracks[i_track]->psz_codec, "A_AAC/MPEG4/", strlen( "A_AAC/MPEG4/" ) ) )
2118         {
2119             int i_profile, i_srate;
2120             static unsigned int i_sample_rates[] =
2121             {
2122                     96000, 88200, 64000, 48000, 44100, 32000, 24000, 22050,
2123                         16000, 12000, 11025, 8000,  7350,  0,     0,     0
2124             };
2125
2126             tracks[i_track]->fmt.i_codec = VLC_FOURCC( 'm', 'p', '4', 'a' );
2127             /* create data for faad (MP4DecSpecificDescrTag)*/
2128
2129             if( !strcmp( &tracks[i_track]->psz_codec[12], "MAIN" ) )
2130             {
2131                 i_profile = 0;
2132             }
2133             else if( !strcmp( &tracks[i_track]->psz_codec[12], "LC" ) )
2134             {
2135                 i_profile = 1;
2136             }
2137             else if( !strcmp( &tracks[i_track]->psz_codec[12], "SSR" ) )
2138             {
2139                 i_profile = 2;
2140             }
2141             else
2142             {
2143                 i_profile = 3;
2144             }
2145
2146             for( i_srate = 0; i_srate < 13; i_srate++ )
2147             {
2148                 if( i_sample_rates[i_srate] == tracks[i_track]->fmt.audio.i_rate )
2149                 {
2150                     break;
2151                 }
2152             }
2153             msg_Dbg( &sys.demuxer, "profile=%d srate=%d", i_profile, i_srate );
2154
2155             tracks[i_track]->fmt.i_extra = 2;
2156             tracks[i_track]->fmt.p_extra = malloc( tracks[i_track]->fmt.i_extra );
2157             ((uint8_t*)tracks[i_track]->fmt.p_extra)[0] = ((i_profile + 1) << 3) | ((i_srate&0xe) >> 1);
2158             ((uint8_t*)tracks[i_track]->fmt.p_extra)[1] = ((i_srate & 0x1) << 7) | (tracks[i_track]->fmt.audio.i_channels << 3);
2159         }
2160         else if( !strcmp( tracks[i_track]->psz_codec, "A_PCM/INT/BIG" ) ||
2161                  !strcmp( tracks[i_track]->psz_codec, "A_PCM/INT/LIT" ) ||
2162                  !strcmp( tracks[i_track]->psz_codec, "A_PCM/FLOAT/IEEE" ) )
2163         {
2164             if( !strcmp( tracks[i_track]->psz_codec, "A_PCM/INT/BIG" ) )
2165             {
2166                 tracks[i_track]->fmt.i_codec = VLC_FOURCC( 't', 'w', 'o', 's' );
2167             }
2168             else
2169             {
2170                 tracks[i_track]->fmt.i_codec = VLC_FOURCC( 'a', 'r', 'a', 'w' );
2171             }
2172             tracks[i_track]->fmt.audio.i_blockalign = ( tracks[i_track]->fmt.audio.i_bitspersample + 7 ) / 8 * tracks[i_track]->fmt.audio.i_channels;
2173         }
2174         else if( !strcmp( tracks[i_track]->psz_codec, "A_TTA1" ) )
2175         {
2176             /* FIXME: support this codec */
2177             msg_Err( &sys.demuxer, "TTA not supported yet[%d, n=%d]", i_track, tracks[i_track]->i_number );
2178             tracks[i_track]->fmt.i_codec = VLC_FOURCC( 'u', 'n', 'd', 'f' );
2179         }
2180         else if( !strcmp( tracks[i_track]->psz_codec, "A_WAVPACK4" ) )
2181         {
2182             /* FIXME: support this codec */
2183             msg_Err( &sys.demuxer, "Wavpack not supported yet[%d, n=%d]", i_track, tracks[i_track]->i_number );
2184             tracks[i_track]->fmt.i_codec = VLC_FOURCC( 'u', 'n', 'd', 'f' );
2185         }
2186         else if( !strcmp( tracks[i_track]->psz_codec, "S_TEXT/UTF8" ) )
2187         {
2188             tracks[i_track]->fmt.i_codec = VLC_FOURCC( 's', 'u', 'b', 't' );
2189             tracks[i_track]->fmt.subs.psz_encoding = strdup( "UTF-8" );
2190         }
2191         else if( !strcmp( tracks[i_track]->psz_codec, "S_TEXT/SSA" ) ||
2192                  !strcmp( tracks[i_track]->psz_codec, "S_TEXT/ASS" ) ||
2193                  !strcmp( tracks[i_track]->psz_codec, "S_SSA" ) ||
2194                  !strcmp( tracks[i_track]->psz_codec, "S_ASS" ))
2195         {
2196             tracks[i_track]->fmt.i_codec = VLC_FOURCC( 's', 's', 'a', ' ' );
2197             tracks[i_track]->fmt.subs.psz_encoding = strdup( "UTF-8" );
2198         }
2199         else if( !strcmp( tracks[i_track]->psz_codec, "S_VOBSUB" ) )
2200         {
2201             tracks[i_track]->fmt.i_codec = VLC_FOURCC( 's','p','u',' ' );
2202             if( tracks[i_track]->i_extra_data )
2203             {
2204                 char *p_start;
2205                 char *p_buf = (char *)malloc( tracks[i_track]->i_extra_data + 1);
2206                 memcpy( p_buf, tracks[i_track]->p_extra_data , tracks[i_track]->i_extra_data );
2207                 p_buf[tracks[i_track]->i_extra_data] = '\0';
2208                 
2209                 p_start = strstr( p_buf, "size:" );
2210                 if( sscanf( p_start, "size: %dx%d",
2211                         &tracks[i_track]->fmt.subs.spu.i_original_frame_width, &tracks[i_track]->fmt.subs.spu.i_original_frame_height ) == 2 )
2212                 {
2213                     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 );
2214                 }
2215                 else
2216                 {
2217                     msg_Warn( &sys.demuxer, "reading original frame size for vobsub failed" );
2218                 }
2219                 free( p_buf );
2220             }
2221         }
2222         else if( !strcmp( tracks[i_track]->psz_codec, "B_VOBBTN" ) )
2223         {
2224             tracks[i_track]->fmt.i_codec = VLC_FOURCC( 's','p','u',' ' );
2225         }
2226         else
2227         {
2228             msg_Err( &sys.demuxer, "unknow codec id=`%s'", tracks[i_track]->psz_codec );
2229             tracks[i_track]->fmt.i_codec = VLC_FOURCC( 'u', 'n', 'd', 'f' );
2230         }
2231         if( tracks[i_track]->b_default )
2232         {
2233             tracks[i_track]->fmt.i_priority = 1000;
2234         }
2235
2236         tracks[i_track]->p_es = es_out_Add( sys.demuxer.out, &tracks[i_track]->fmt );
2237
2238         es_out_Control( sys.demuxer.out, ES_OUT_SET_NEXT_DISPLAY_TIME, tracks[i_track]->p_es, i_start_time );
2239     }
2240     
2241     sys.i_start_pts = i_start_time;
2242     // reset the stream reading to the first cluster of the segment used
2243     es.I_O().setFilePointer( i_start_pos );
2244
2245     delete ep;
2246     ep = new EbmlParser( &es, segment, &sys.demuxer );
2247
2248     return true;
2249 }
2250
2251 void demux_sys_t::StartUiThread()
2252 {
2253     if ( !b_ui_hooked )
2254     {
2255         msg_Dbg( &demuxer, "Starting the UI Hook" );
2256         b_ui_hooked = true;
2257         /* FIXME hack hack hack hack FIXME */
2258         /* Get p_input and create variable */
2259         p_input = (input_thread_t *) vlc_object_find( &demuxer, VLC_OBJECT_INPUT, FIND_PARENT );
2260         var_Create( p_input, "x-start", VLC_VAR_INTEGER );
2261         var_Create( p_input, "y-start", VLC_VAR_INTEGER );
2262         var_Create( p_input, "x-end", VLC_VAR_INTEGER );
2263         var_Create( p_input, "y-end", VLC_VAR_INTEGER );
2264         var_Create( p_input, "color", VLC_VAR_ADDRESS );
2265         var_Create( p_input, "menu-contrast", VLC_VAR_ADDRESS );
2266         var_Create( p_input, "highlight", VLC_VAR_BOOL );
2267         var_Create( p_input, "highlight-mutex", VLC_VAR_MUTEX );
2268
2269         /* Now create our event thread catcher */
2270         p_ev = (event_thread_t *) vlc_object_create( &demuxer, sizeof( event_thread_t ) );
2271         p_ev->p_demux = &demuxer;
2272         p_ev->b_die = VLC_FALSE;
2273         vlc_mutex_init( p_ev, &p_ev->lock );
2274         vlc_thread_create( p_ev, "mkv event thread handler", EventThread,
2275                         VLC_THREAD_PRIORITY_LOW, VLC_FALSE );
2276     }
2277 }
2278
2279 void demux_sys_t::StopUiThread()
2280 {
2281     if ( b_ui_hooked )
2282     {
2283         p_ev->b_die = VLC_TRUE;
2284
2285         vlc_thread_join( p_ev );
2286         vlc_object_destroy( p_ev );
2287
2288         p_ev = NULL;
2289
2290         var_Destroy( p_input, "highlight-mutex" );
2291         var_Destroy( p_input, "highlight" );
2292         var_Destroy( p_input, "x-start" );
2293         var_Destroy( p_input, "x-end" );
2294         var_Destroy( p_input, "y-start" );
2295         var_Destroy( p_input, "y-end" );
2296         var_Destroy( p_input, "color" );
2297         var_Destroy( p_input, "menu-contrast" );
2298
2299         msg_Dbg( &demuxer, "Stopping the UI Hook" );
2300     }
2301     b_ui_hooked = false;
2302 }
2303
2304 int demux_sys_t::EventMouse( vlc_object_t *p_this, char const *psz_var,
2305                        vlc_value_t oldval, vlc_value_t newval, void *p_data )
2306 {
2307     event_thread_t *p_ev = (event_thread_t *) p_data;
2308     vlc_mutex_lock( &p_ev->lock );
2309     if( psz_var[6] == 'c' )
2310         p_ev->b_clicked = VLC_TRUE;
2311     else if( psz_var[6] == 'm' )
2312         p_ev->b_moved = VLC_TRUE;
2313     vlc_mutex_unlock( &p_ev->lock );
2314
2315     return VLC_SUCCESS;
2316 }
2317
2318 int demux_sys_t::EventKey( vlc_object_t *p_this, char const *psz_var,
2319                      vlc_value_t oldval, vlc_value_t newval, void *p_data )
2320 {
2321     event_thread_t *p_ev = (event_thread_t *) p_data;
2322     vlc_mutex_lock( &p_ev->lock );
2323     p_ev->b_key = VLC_TRUE;
2324     vlc_mutex_unlock( &p_ev->lock );
2325
2326     return VLC_SUCCESS;
2327 }
2328
2329 int demux_sys_t::EventThread( vlc_object_t *p_this )
2330 {
2331     event_thread_t *p_ev = (event_thread_t*)p_this;
2332     demux_sys_t    *p_sys = p_ev->p_demux->p_sys;
2333     vlc_object_t   *p_vout = NULL;
2334
2335     p_ev->b_moved   = VLC_FALSE;
2336     p_ev->b_clicked = VLC_FALSE;
2337     p_ev->b_key     = VLC_FALSE;
2338
2339     /* catch all key event */
2340     var_AddCallback( p_ev->p_vlc, "key-pressed", EventKey, p_ev );
2341
2342     /* main loop */
2343     while( !p_ev->b_die )
2344     {
2345         if ( !p_sys->b_pci_packet_set )
2346         {
2347             /* Wait 100ms */
2348             msleep( 100000 );
2349             continue;
2350         }
2351
2352         vlc_bool_t b_activated = VLC_FALSE;
2353
2354         /* KEY part */
2355         if( p_ev->b_key )
2356         {
2357             vlc_value_t valk;
2358             struct vlc_t::hotkey *p_hotkeys = p_ev->p_vlc->p_hotkeys;
2359             int i, i_action = -1;
2360
2361             vlc_mutex_lock( &p_ev->lock );
2362
2363             pci_t *pci = (pci_t *) &p_sys->pci_packet;
2364
2365             var_Get( p_ev->p_vlc, "key-pressed", &valk );
2366             for( i = 0; p_hotkeys[i].psz_action != NULL; i++ )
2367             {
2368                 if( p_hotkeys[i].i_key == valk.i_int )
2369                 {
2370                     i_action = p_hotkeys[i].i_action;
2371                 }
2372             }
2373
2374             uint16 i_curr_button = p_sys->dvd_interpretor.GetSPRM( 0x88 );
2375
2376             switch( i_action )
2377             {
2378             case ACTIONID_NAV_LEFT:
2379                 if ( i_curr_button > 0 && i_curr_button <= pci->hli.hl_gi.btn_ns )
2380                 {
2381                     btni_t *p_button_ptr = &(pci->hli.btnit[i_curr_button-1]);
2382                     if ( p_button_ptr->left > 0 && p_button_ptr->left <= pci->hli.hl_gi.btn_ns )
2383                     {
2384                         i_curr_button = p_button_ptr->left;
2385                         p_sys->dvd_interpretor.SetSPRM( 0x88, i_curr_button );
2386                         btni_t button_ptr = pci->hli.btnit[i_curr_button-1];
2387                         if ( button_ptr.auto_action_mode )
2388                         {
2389                             vlc_mutex_unlock( &p_ev->lock );
2390                             vlc_mutex_lock( &p_sys->lock_demuxer );
2391
2392                             // process the button action
2393                             p_sys->dvd_interpretor.Interpret( button_ptr.cmd.bytes, 8 );
2394
2395                             vlc_mutex_unlock( &p_sys->lock_demuxer );
2396                             vlc_mutex_lock( &p_ev->lock );
2397                         }
2398                     }
2399                 }
2400                 break;
2401             case ACTIONID_NAV_RIGHT:
2402                 if ( i_curr_button > 0 && i_curr_button <= pci->hli.hl_gi.btn_ns )
2403                 {
2404                     btni_t *p_button_ptr = &(pci->hli.btnit[i_curr_button-1]);
2405                     if ( p_button_ptr->right > 0 && p_button_ptr->right <= pci->hli.hl_gi.btn_ns )
2406                     {
2407                         i_curr_button = p_button_ptr->right;
2408                         p_sys->dvd_interpretor.SetSPRM( 0x88, i_curr_button );
2409                         btni_t button_ptr = pci->hli.btnit[i_curr_button-1];
2410                         if ( button_ptr.auto_action_mode )
2411                         {
2412                             vlc_mutex_unlock( &p_ev->lock );
2413                             vlc_mutex_lock( &p_sys->lock_demuxer );
2414
2415                             // process the button action
2416                             p_sys->dvd_interpretor.Interpret( button_ptr.cmd.bytes, 8 );
2417
2418                             vlc_mutex_unlock( &p_sys->lock_demuxer );
2419                             vlc_mutex_lock( &p_ev->lock );
2420                         }
2421                     }
2422                 }
2423                 break;
2424             case ACTIONID_NAV_UP:
2425                 if ( i_curr_button > 0 && i_curr_button <= pci->hli.hl_gi.btn_ns )
2426                 {
2427                     btni_t *p_button_ptr = &(pci->hli.btnit[i_curr_button-1]);
2428                     if ( p_button_ptr->up > 0 && p_button_ptr->up <= pci->hli.hl_gi.btn_ns )
2429                     {
2430                         i_curr_button = p_button_ptr->up;
2431                         p_sys->dvd_interpretor.SetSPRM( 0x88, i_curr_button );
2432                         btni_t button_ptr = pci->hli.btnit[i_curr_button-1];
2433                         if ( button_ptr.auto_action_mode )
2434                         {
2435                             vlc_mutex_unlock( &p_ev->lock );
2436                             vlc_mutex_lock( &p_sys->lock_demuxer );
2437
2438                             // process the button action
2439                             p_sys->dvd_interpretor.Interpret( button_ptr.cmd.bytes, 8 );
2440
2441                             vlc_mutex_unlock( &p_sys->lock_demuxer );
2442                             vlc_mutex_lock( &p_ev->lock );
2443                         }
2444                     }
2445                 }
2446                 break;
2447             case ACTIONID_NAV_DOWN:
2448                 if ( i_curr_button > 0 && i_curr_button <= pci->hli.hl_gi.btn_ns )
2449                 {
2450                     btni_t *p_button_ptr = &(pci->hli.btnit[i_curr_button-1]);
2451                     if ( p_button_ptr->down > 0 && p_button_ptr->down <= pci->hli.hl_gi.btn_ns )
2452                     {
2453                         i_curr_button = p_button_ptr->down;
2454                         p_sys->dvd_interpretor.SetSPRM( 0x88, i_curr_button );
2455                         btni_t button_ptr = pci->hli.btnit[i_curr_button-1];
2456                         if ( button_ptr.auto_action_mode )
2457                         {
2458                             vlc_mutex_unlock( &p_ev->lock );
2459                             vlc_mutex_lock( &p_sys->lock_demuxer );
2460
2461                             // process the button action
2462                             p_sys->dvd_interpretor.Interpret( button_ptr.cmd.bytes, 8 );
2463
2464                             vlc_mutex_unlock( &p_sys->lock_demuxer );
2465                             vlc_mutex_lock( &p_ev->lock );
2466                         }
2467                     }
2468                 }
2469                 break;
2470             case ACTIONID_NAV_ACTIVATE:
2471                 b_activated = VLC_TRUE;
2472         
2473                 if ( i_curr_button > 0 && i_curr_button <= pci->hli.hl_gi.btn_ns )
2474                 {
2475                     btni_t button_ptr = pci->hli.btnit[i_curr_button-1];
2476
2477                     vlc_mutex_unlock( &p_ev->lock );
2478                     vlc_mutex_lock( &p_sys->lock_demuxer );
2479
2480                     // process the button action
2481                     p_sys->dvd_interpretor.Interpret( button_ptr.cmd.bytes, 8 );
2482
2483                     vlc_mutex_unlock( &p_sys->lock_demuxer );
2484                     vlc_mutex_lock( &p_ev->lock );
2485                 }
2486                 break;
2487             default:
2488                 break;
2489             }
2490             p_ev->b_key = VLC_FALSE;
2491             vlc_mutex_unlock( &p_ev->lock );
2492         }
2493
2494         /* MOUSE part */
2495         if( p_vout && ( p_ev->b_moved || p_ev->b_clicked ) )
2496         {
2497             vlc_value_t valx, valy;
2498
2499             vlc_mutex_lock( &p_ev->lock );
2500             pci_t *pci = (pci_t *) &p_sys->pci_packet;
2501             var_Get( p_vout, "mouse-x", &valx );
2502             var_Get( p_vout, "mouse-y", &valy );
2503
2504             if( p_ev->b_clicked )
2505             {
2506                 int32_t button;
2507                 int32_t best,dist,d;
2508                 int32_t mx,my,dx,dy;
2509
2510                 b_activated = VLC_TRUE;
2511                 // get current button
2512                 best = 0;
2513                 dist = 0x08000000; /* >> than  (720*720)+(567*567); */
2514                 for(button = 1; button <= pci->hli.hl_gi.btn_ns; button++) 
2515                 {
2516                     btni_t *button_ptr = &(pci->hli.btnit[button-1]);
2517
2518                     if((valx.i_int >= button_ptr->x_start) && (valx.i_int <= button_ptr->x_end) &&
2519                        (valy.i_int >= button_ptr->y_start) && (valy.i_int <= button_ptr->y_end)) 
2520                     {
2521                         mx = (button_ptr->x_start + button_ptr->x_end)/2;
2522                         my = (button_ptr->y_start + button_ptr->y_end)/2;
2523                         dx = mx - valx.i_int;
2524                         dy = my - valy.i_int;
2525                         d = (dx*dx) + (dy*dy);
2526                         /* If the mouse is within the button and the mouse is closer
2527                         * to the center of this button then it is the best choice. */
2528                         if(d < dist) {
2529                             dist = d;
2530                             best = button;
2531                         }
2532                     }
2533                 }
2534
2535                 if ( best != 0)
2536                 {
2537                     btni_t button_ptr = pci->hli.btnit[best-1];
2538                     uint16 i_curr_button = p_sys->dvd_interpretor.GetSPRM( 0x88 );
2539
2540                     msg_Dbg( &p_sys->demuxer, "Clicked button %d", best );
2541                     vlc_mutex_unlock( &p_ev->lock );
2542                     vlc_mutex_lock( &p_sys->lock_demuxer );
2543
2544                     // process the button action
2545                     p_sys->dvd_interpretor.SetSPRM( 0x88, best );
2546                     p_sys->dvd_interpretor.Interpret( button_ptr.cmd.bytes, 8 );
2547
2548                     msg_Dbg( &p_sys->demuxer, "Processed button %d", best );
2549
2550                     // select new button
2551                     if ( best != i_curr_button )
2552                     {
2553                         vlc_value_t val;
2554
2555                         if( var_Get( p_sys->p_input, "highlight-mutex", &val ) == VLC_SUCCESS )
2556                         {
2557                             vlc_mutex_t *p_mutex = (vlc_mutex_t *) val.p_address;
2558                             uint32_t i_palette;
2559
2560                             if(button_ptr.btn_coln != 0) {
2561                                 i_palette = pci->hli.btn_colit.btn_coli[button_ptr.btn_coln-1][1];
2562                             } else {
2563                                 i_palette = 0;
2564                             }
2565                             p_sys->alpha[0] = i_palette      & 0x0f;
2566                             p_sys->alpha[1] = (i_palette>>4) & 0x0f;
2567                             p_sys->alpha[2] = (i_palette>>8) & 0x0f;
2568                             p_sys->alpha[3] = (i_palette>>12)& 0x0f;
2569
2570                             vlc_mutex_lock( p_mutex );
2571                             val.i_int = button_ptr.x_start; var_Set( p_sys->p_input, "x-start", val );
2572                             val.i_int = button_ptr.x_end;   var_Set( p_sys->p_input, "x-end",   val );
2573                             val.i_int = button_ptr.y_start; var_Set( p_sys->p_input, "y-start", val );
2574                             val.i_int = button_ptr.y_end;   var_Set( p_sys->p_input, "y-end",   val );
2575
2576                             val.p_address = (void *)p_sys->alpha;
2577                             var_Set( p_sys->p_input, "menu-contrast", val );
2578
2579                             val.b_bool = VLC_TRUE; var_Set( p_sys->p_input, "highlight", val );
2580                             vlc_mutex_unlock( p_mutex );
2581                         }
2582                     }
2583                     vlc_mutex_unlock( &p_sys->lock_demuxer );
2584                     vlc_mutex_lock( &p_ev->lock );
2585                 }
2586             }
2587             else if( p_ev->b_moved )
2588             {
2589 //                dvdnav_mouse_select( NULL, pci, valx.i_int, valy.i_int );
2590             }
2591
2592             p_ev->b_moved = VLC_FALSE;
2593             p_ev->b_clicked = VLC_FALSE;
2594             vlc_mutex_unlock( &p_ev->lock );
2595         }
2596
2597         /* VOUT part */
2598         if( p_vout && p_vout->b_die )
2599         {
2600             var_DelCallback( p_vout, "mouse-moved", EventMouse, p_ev );
2601             var_DelCallback( p_vout, "mouse-clicked", EventMouse, p_ev );
2602             vlc_object_release( p_vout );
2603             p_vout = NULL;
2604         }
2605
2606         else if( p_vout == NULL )
2607         {
2608             p_vout = (vlc_object_t*) vlc_object_find( p_sys->p_input, VLC_OBJECT_VOUT,
2609                                       FIND_CHILD );
2610             if( p_vout)
2611             {
2612                 var_AddCallback( p_vout, "mouse-moved", EventMouse, p_ev );
2613                 var_AddCallback( p_vout, "mouse-clicked", EventMouse, p_ev );
2614             }
2615         }
2616
2617         /* Wait a bit, 10ms */
2618         msleep( 10000 );
2619     }
2620
2621     /* Release callback */
2622     if( p_vout )
2623     {
2624         var_DelCallback( p_vout, "mouse-moved", EventMouse, p_ev );
2625         var_DelCallback( p_vout, "mouse-clicked", EventMouse, p_ev );
2626         vlc_object_release( p_vout );
2627     }
2628     var_DelCallback( p_ev->p_vlc, "key-pressed", EventKey, p_ev );
2629
2630     vlc_mutex_destroy( &p_ev->lock );
2631
2632     return VLC_SUCCESS;
2633 }
2634
2635 void matroska_segment_c::UnSelect( )
2636 {
2637     size_t i_track;
2638
2639     for( i_track = 0; i_track < tracks.size(); i_track++ )
2640     {
2641         if ( tracks[i_track]->p_es != NULL )
2642         {
2643             es_out_Del( sys.demuxer.out, tracks[i_track]->p_es );
2644             tracks[i_track]->p_es = NULL;
2645         }
2646     }
2647     delete ep;
2648     ep = NULL;
2649 }
2650
2651 void virtual_segment_c::PrepareChapters( )
2652 {
2653     if ( linked_segments.size() == 0 )
2654         return;
2655
2656     // !!! should be called only once !!!
2657     matroska_segment_c *p_segment;
2658     size_t i, j;
2659
2660     // copy editions from the first segment
2661     p_segment = linked_segments[0];
2662     p_editions = &p_segment->stored_editions;
2663
2664     for ( i=1 ; i<linked_segments.size(); i++ )
2665     {
2666         p_segment = linked_segments[i];
2667         // FIXME assume we have the same editions in all segments
2668         for (j=0; j<p_segment->stored_editions.size(); j++)
2669             (*p_editions)[j]->Append( *p_segment->stored_editions[j] );
2670     }
2671 }
2672
2673 std::string chapter_edition_c::GetMainName() const
2674 {
2675     if ( sub_chapters.size() )
2676     {
2677         return sub_chapters[0]->GetCodecName( true );
2678     }
2679     return "";
2680 }
2681
2682 int chapter_item_c::PublishChapters( input_title_t & title, int & i_user_chapters, int i_level )
2683 {
2684     // add support for meta-elements from codec like DVD Titles
2685     if ( !b_display_seekpoint || psz_name == "" )
2686     {
2687         psz_name = GetCodecName();
2688         if ( psz_name != "" )
2689             b_display_seekpoint = true;
2690     }
2691
2692     if (b_display_seekpoint)
2693     {
2694         seekpoint_t *sk = vlc_seekpoint_New();
2695
2696         sk->i_level = i_level;
2697         sk->i_time_offset = i_start_time;
2698         sk->psz_name = strdup( psz_name.c_str() );
2699
2700         // A start time of '0' is ok. A missing ChapterTime element is ok, too, because '0' is its default value.
2701         title.i_seekpoint++;
2702         title.seekpoint = (seekpoint_t**)realloc( title.seekpoint, title.i_seekpoint * sizeof( seekpoint_t* ) );
2703         title.seekpoint[title.i_seekpoint-1] = sk;
2704
2705         if ( b_user_display )
2706             i_user_chapters++;
2707     }
2708
2709     for ( size_t i=0; i<sub_chapters.size() ; i++)
2710     {
2711         sub_chapters[i]->PublishChapters( title, i_user_chapters, i_level+1 );
2712     }
2713
2714     i_seekpoint_num = i_user_chapters;
2715
2716     return i_user_chapters;
2717 }
2718
2719 bool virtual_segment_c::UpdateCurrentToChapter( demux_t & demux )
2720 {
2721     demux_sys_t & sys = *demux.p_sys;
2722     chapter_item_c *psz_curr_chapter;
2723
2724     /* update current chapter/seekpoint */
2725     if ( p_editions->size() )
2726     {
2727         /* 1st, we need to know in which chapter we are */
2728         psz_curr_chapter = (*p_editions)[i_current_edition]->FindTimecode( sys.i_pts );
2729
2730         /* we have moved to a new chapter */
2731         if (psz_curr_chapter != NULL && psz_current_chapter != psz_curr_chapter)
2732         {
2733             if ( (*p_editions)[i_current_edition]->b_ordered )
2734             {
2735                 // Leave/Enter up to the link point
2736                 if ( !psz_curr_chapter->EnterAndLeave( psz_current_chapter ) )
2737                 {
2738                     // only seek if necessary
2739                     if ( psz_current_chapter == NULL || (psz_current_chapter->i_end_time != psz_curr_chapter->i_start_time) )
2740                         Seek( demux, sys.i_pts, 0, psz_curr_chapter );
2741                     psz_current_chapter = psz_curr_chapter;
2742                 }
2743             }
2744             else if ( psz_curr_chapter->i_seekpoint_num > 0 )
2745             {
2746                 demux.info.i_update |= INPUT_UPDATE_TITLE | INPUT_UPDATE_SEEKPOINT;
2747                 demux.info.i_title = sys.i_current_title = i_sys_title;
2748                 demux.info.i_seekpoint = psz_curr_chapter->i_seekpoint_num - 1;
2749                 psz_current_chapter = psz_curr_chapter;
2750             }
2751             else
2752             {
2753                 psz_current_chapter = psz_curr_chapter;
2754             }
2755
2756             return true;
2757         }
2758         else if (psz_curr_chapter == NULL)
2759         {
2760             // out of the scope of the data described by chapters, leave the edition
2761             if ( (*p_editions)[i_current_edition]->b_ordered && psz_current_chapter != NULL )
2762             {
2763                 if ( !(*p_editions)[i_current_edition]->EnterAndLeave( psz_current_chapter ) )
2764                     psz_current_chapter = NULL;
2765                 else
2766                     return true;
2767             }
2768         }
2769     }
2770     return false;
2771 }
2772
2773 chapter_item_c *virtual_segment_c::BrowseCodecPrivate( unsigned int codec_id, 
2774                                     bool (*match)(const chapter_codec_cmds_c &data, const void *p_cookie, size_t i_cookie_size ), 
2775                                     const void *p_cookie, 
2776                                     size_t i_cookie_size )
2777 {
2778     // FIXME don't assume it is the first edition
2779     std::vector<chapter_edition_c*>::iterator index = p_editions->begin();
2780     if ( index != p_editions->end() )
2781     {
2782         chapter_item_c *p_result = (*index)->BrowseCodecPrivate( codec_id, match, p_cookie, i_cookie_size );
2783         if ( p_result != NULL )
2784             return p_result;
2785     }
2786     return NULL;
2787 }
2788
2789 chapter_item_c *virtual_segment_c::FindChapter( int64_t i_find_uid )
2790 {
2791     // FIXME don't assume it is the first edition
2792     std::vector<chapter_edition_c*>::iterator index = p_editions->begin();
2793     if ( index != p_editions->end() )
2794     {
2795         chapter_item_c *p_result = (*index)->FindChapter( i_find_uid );
2796         if ( p_result != NULL )
2797             return p_result;
2798     }
2799     return NULL;
2800 }
2801
2802 chapter_item_c *chapter_item_c::BrowseCodecPrivate( unsigned int codec_id, 
2803                                     bool (*match)(const chapter_codec_cmds_c &data, const void *p_cookie, size_t i_cookie_size ), 
2804                                     const void *p_cookie, 
2805                                     size_t i_cookie_size )
2806 {
2807     // this chapter
2808     std::vector<chapter_codec_cmds_c*>::const_iterator index = codecs.begin();
2809     while ( index != codecs.end() )
2810     {
2811         if ( match( **index ,p_cookie, i_cookie_size ) )
2812             return this;
2813         index++;
2814     }
2815     
2816     // sub-chapters
2817     chapter_item_c *p_result = NULL;
2818     std::vector<chapter_item_c*>::const_iterator index2 = sub_chapters.begin();
2819     while ( index2 != sub_chapters.end() )
2820     {
2821         p_result = (*index2)->BrowseCodecPrivate( codec_id, match, p_cookie, i_cookie_size );
2822         if ( p_result != NULL )
2823             return p_result;
2824         index2++;
2825     }
2826     
2827     return p_result;
2828 }
2829
2830 void chapter_item_c::Append( const chapter_item_c & chapter )
2831 {
2832     // we are appending content for the same chapter UID
2833     size_t i;
2834     chapter_item_c *p_chapter;
2835
2836     for ( i=0; i<chapter.sub_chapters.size(); i++ )
2837     {
2838         p_chapter = FindChapter( chapter.sub_chapters[i]->i_uid );
2839         if ( p_chapter != NULL )
2840         {
2841             p_chapter->Append( *chapter.sub_chapters[i] );
2842         }
2843         else
2844         {
2845             sub_chapters.push_back( chapter.sub_chapters[i] );
2846         }
2847     }
2848
2849     i_user_start_time = min( i_user_start_time, chapter.i_user_start_time );
2850     i_user_end_time = max( i_user_end_time, chapter.i_user_end_time );
2851 }
2852
2853 chapter_item_c * chapter_item_c::FindChapter( int64_t i_find_uid )
2854 {
2855     size_t i;
2856     chapter_item_c *p_result = NULL;
2857
2858     if ( i_uid == i_find_uid )
2859         return this;
2860
2861     for ( i=0; i<sub_chapters.size(); i++)
2862     {
2863         p_result = sub_chapters[i]->FindChapter( i_find_uid );
2864         if ( p_result != NULL )
2865             break;
2866     }
2867     return p_result;
2868 }
2869
2870 std::string chapter_item_c::GetCodecName( bool f_for_title ) const
2871 {
2872     std::string result;
2873
2874     std::vector<chapter_codec_cmds_c*>::const_iterator index = codecs.begin();
2875     while ( index != codecs.end() )
2876     {
2877         result = (*index)->GetCodecName( f_for_title );
2878         if ( result != "" )
2879             break;
2880         index++;
2881     }
2882
2883     return result;
2884 }
2885
2886 std::string dvd_chapter_codec_c::GetCodecName( bool f_for_title ) const
2887 {
2888     std::string result;
2889     if ( m_private_data.GetSize() >= 3)
2890     {
2891         const binary* p_data = m_private_data.GetBuffer();
2892 /*        if ( p_data[0] == MATROSKA_DVD_LEVEL_TT )
2893         {
2894             uint16_t i_title = (p_data[1] << 8) + p_data[2];
2895             char psz_str[11];
2896             sprintf( psz_str, " %d  ---", i_title );
2897             result = N_("---  DVD Title");
2898             result += psz_str;
2899         }
2900         else */ if ( p_data[0] == MATROSKA_DVD_LEVEL_LU )
2901         {
2902             char psz_str[11];
2903             sprintf( psz_str, " (%c%c)  ---", p_data[1], p_data[2] );
2904             result = N_("---  DVD Menu");
2905             result += psz_str;
2906         }
2907         else if ( p_data[0] == MATROSKA_DVD_LEVEL_SS && f_for_title )
2908         {
2909             if ( p_data[1] == 0x00 )
2910                 result = N_("First Played");
2911             else if ( p_data[1] == 0xC0 )
2912                 result = N_("Video Manager");
2913             else if ( p_data[1] == 0x80 )
2914             {
2915                 uint16_t i_title = (p_data[2] << 8) + p_data[3];
2916                 char psz_str[20];
2917                 sprintf( psz_str, " %d -----", i_title );
2918                 result = N_("----- Title");
2919                 result += psz_str;
2920             }
2921         }
2922     }
2923
2924     return result;
2925 }
2926
2927 int16 chapter_item_c::GetTitleNumber( ) const
2928 {
2929     int result = -1;
2930
2931     std::vector<chapter_codec_cmds_c*>::const_iterator index = codecs.begin();
2932     while ( index != codecs.end() )
2933     {
2934         result = (*index)->GetTitleNumber( );
2935         if ( result >= 0 )
2936             break;
2937         index++;
2938     }
2939
2940     return result;
2941 }
2942
2943 int16 dvd_chapter_codec_c::GetTitleNumber()
2944 {
2945     if ( m_private_data.GetSize() >= 3)
2946     {
2947         const binary* p_data = m_private_data.GetBuffer();
2948         if ( p_data[0] == MATROSKA_DVD_LEVEL_SS )
2949         {
2950             return int16( (p_data[2] << 8) + p_data[3] );
2951         }
2952     }
2953     return -1;
2954 }
2955
2956 static void Seek( demux_t *p_demux, mtime_t i_date, double f_percent, chapter_item_c *psz_chapter )
2957 {
2958     demux_sys_t        *p_sys = p_demux->p_sys;
2959     virtual_segment_c  *p_vsegment = p_sys->p_current_segment;
2960     matroska_segment_c *p_segment = p_vsegment->Segment();
2961     mtime_t            i_time_offset = 0;
2962
2963     int         i_index;
2964
2965     msg_Dbg( p_demux, "seek request to "I64Fd" (%f%%)", i_date, f_percent );
2966     if( i_date < 0 && f_percent < 0 )
2967     {
2968         msg_Warn( p_demux, "cannot seek nowhere !" );
2969         return;
2970     }
2971     if( f_percent > 1.0 )
2972     {
2973         msg_Warn( p_demux, "cannot seek so far !" );
2974         return;
2975     }
2976
2977     /* seek without index or without date */
2978     if( f_percent >= 0 && (config_GetInt( p_demux, "mkv-seek-percent" ) || !p_segment->b_cues || i_date < 0 ))
2979     {
2980         if (p_sys->f_duration >= 0)
2981         {
2982             i_date = int64_t( f_percent * p_sys->f_duration * 1000.0 );
2983         }
2984         else
2985         {
2986             int64_t i_pos = int64_t( f_percent * stream_Size( p_demux->s ) );
2987
2988             msg_Dbg( p_demux, "inacurate way of seeking" );
2989             for( i_index = 0; i_index < p_segment->i_index; i_index++ )
2990             {
2991                 if( p_segment->index[i_index].i_position >= i_pos)
2992                 {
2993                     break;
2994                 }
2995             }
2996             if( i_index == p_segment->i_index )
2997             {
2998                 i_index--;
2999             }
3000
3001             i_date = p_segment->index[i_index].i_time;
3002
3003 #if 0
3004             if( p_segment->index[i_index].i_position < i_pos )
3005             {
3006                 EbmlElement *el;
3007
3008                 msg_Warn( p_demux, "searching for cluster, could take some time" );
3009
3010                 /* search a cluster */
3011                 while( ( el = p_sys->ep->Get() ) != NULL )
3012                 {
3013                     if( MKV_IS_ID( el, KaxCluster ) )
3014                     {
3015                         KaxCluster *cluster = (KaxCluster*)el;
3016
3017                         /* add it to the index */
3018                         p_segment->IndexAppendCluster( cluster );
3019
3020                         if( (int64_t)cluster->GetElementPosition() >= i_pos )
3021                         {
3022                             p_sys->cluster = cluster;
3023                             p_sys->ep->Down();
3024                             break;
3025                         }
3026                     }
3027                 }
3028             }
3029 #endif
3030         }
3031     }
3032
3033     p_vsegment->Seek( *p_demux, i_date, i_time_offset, psz_chapter );
3034 }
3035
3036 /*****************************************************************************
3037  * Demux: reads and demuxes data packets
3038  *****************************************************************************
3039  * Returns -1 in case of error, 0 in case of EOF, 1 otherwise
3040  *****************************************************************************/
3041 static int Demux( demux_t *p_demux)
3042 {
3043     demux_sys_t        *p_sys = p_demux->p_sys;
3044
3045     vlc_mutex_lock( &p_sys->lock_demuxer );
3046
3047     virtual_segment_c  *p_vsegment = p_sys->p_current_segment;
3048     matroska_segment_c *p_segment = p_vsegment->Segment();
3049     if ( p_segment == NULL ) return 0;
3050     int                i_block_count = 0;
3051     int                i_return = 0;
3052
3053     KaxBlock *block;
3054     int64_t i_block_duration;
3055     int64_t i_block_ref1;
3056     int64_t i_block_ref2;
3057
3058     for( ;; )
3059     {
3060         if ( p_sys->demuxer.b_die )
3061             break;
3062
3063         if( p_sys->i_pts >= p_sys->i_start_pts  )
3064             if ( p_vsegment->UpdateCurrentToChapter( *p_demux ) )
3065             {
3066                 i_return = 1;
3067                 break;
3068             }
3069         
3070         if ( p_vsegment->Edition() && p_vsegment->Edition()->b_ordered && p_vsegment->CurrentChapter() == NULL )
3071         {
3072             /* nothing left to read in this ordered edition */
3073             if ( !p_vsegment->SelectNext() )
3074                 break;
3075             p_segment->UnSelect( );
3076             
3077             es_out_Control( p_demux->out, ES_OUT_RESET_PCR );
3078
3079             /* switch to the next segment */
3080             p_segment = p_vsegment->Segment();
3081             if ( !p_segment->Select( 0 ) )
3082             {
3083                 msg_Err( p_demux, "Failed to select new segment" );
3084                 break;
3085             }
3086             continue;
3087         }
3088
3089
3090         if( p_segment->BlockGet( &block, &i_block_ref1, &i_block_ref2, &i_block_duration ) )
3091         {
3092             if ( p_vsegment->Edition() && p_vsegment->Edition()->b_ordered )
3093             {
3094                 const chapter_item_c *p_chap = p_vsegment->CurrentChapter();
3095                 // check if there are more chapters to read
3096                 if ( p_chap != NULL )
3097                 {
3098                     /* TODO handle successive chapters with the same user_start_time/user_end_time
3099                     if ( p_chap->i_user_start_time == p_chap->i_user_start_time )
3100                         p_vsegment->SelectNext();
3101                     */
3102                     p_sys->i_pts = p_chap->i_user_end_time;
3103                     p_sys->i_pts++; // trick to avoid staying on segments with no duration and no content
3104
3105                     i_return = 1;
3106                 }
3107
3108                 break;
3109             }
3110             msg_Warn( p_demux, "cannot get block EOF?" );
3111             p_segment->UnSelect( );
3112             
3113             es_out_Control( p_demux->out, ES_OUT_RESET_PCR );
3114
3115             /* switch to the next segment */
3116             if ( !p_vsegment->SelectNext() )
3117                 // no more segments in this stream
3118                 break;
3119             p_segment = p_vsegment->Segment();
3120             if ( !p_segment->Select( 0 ) )
3121             {
3122                 msg_Err( p_demux, "Failed to select new segment" );
3123                 break;
3124             }
3125
3126             continue;
3127         }
3128
3129         p_sys->i_pts = p_sys->i_chapter_time + block->GlobalTimecode() / (mtime_t) 1000;
3130
3131         if( p_sys->i_pts >= p_sys->i_start_pts  )
3132         {
3133             es_out_Control( p_demux->out, ES_OUT_SET_PCR, p_sys->i_pts );
3134         }
3135
3136         BlockDecode( p_demux, block, p_sys->i_pts, i_block_duration );
3137
3138         delete block;
3139         i_block_count++;
3140
3141         // TODO optimize when there is need to leave or when seeking has been called
3142         if( i_block_count > 5 )
3143         {
3144             i_return = 1;
3145             break;
3146         }
3147     }
3148
3149     vlc_mutex_unlock( &p_sys->lock_demuxer );
3150
3151     return i_return;
3152 }
3153
3154
3155
3156 /*****************************************************************************
3157  * Stream managment
3158  *****************************************************************************/
3159 vlc_stream_io_callback::vlc_stream_io_callback( stream_t *s_ )
3160 {
3161     s = s_;
3162     mb_eof = VLC_FALSE;
3163 }
3164
3165 uint32 vlc_stream_io_callback::read( void *p_buffer, size_t i_size )
3166 {
3167     if( i_size <= 0 || mb_eof )
3168     {
3169         return 0;
3170     }
3171
3172     return stream_Read( s, p_buffer, i_size );
3173 }
3174 void vlc_stream_io_callback::setFilePointer(int64_t i_offset, seek_mode mode )
3175 {
3176     int64_t i_pos;
3177
3178     switch( mode )
3179     {
3180         case seek_beginning:
3181             i_pos = i_offset;
3182             break;
3183         case seek_end:
3184             i_pos = stream_Size( s ) - i_offset;
3185             break;
3186         default:
3187             i_pos= stream_Tell( s ) + i_offset;
3188             break;
3189     }
3190
3191     if( i_pos < 0 || i_pos >= stream_Size( s ) )
3192     {
3193         mb_eof = VLC_TRUE;
3194         return;
3195     }
3196
3197     mb_eof = VLC_FALSE;
3198     if( stream_Seek( s, i_pos ) )
3199     {
3200         mb_eof = VLC_TRUE;
3201     }
3202     return;
3203 }
3204 size_t vlc_stream_io_callback::write( const void *p_buffer, size_t i_size )
3205 {
3206     return 0;
3207 }
3208 uint64 vlc_stream_io_callback::getFilePointer( void )
3209 {
3210     return stream_Tell( s );
3211 }
3212 void vlc_stream_io_callback::close( void )
3213 {
3214     return;
3215 }
3216
3217
3218 /*****************************************************************************
3219  * Ebml Stream parser
3220  *****************************************************************************/
3221 EbmlParser::EbmlParser( EbmlStream *es, EbmlElement *el_start, demux_t *p_demux )
3222 {
3223     int i;
3224
3225     m_es = es;
3226     m_got = NULL;
3227     m_el[0] = el_start;
3228     mi_remain_size[0] = el_start->GetSize();
3229
3230     for( i = 1; i < 6; i++ )
3231     {
3232         m_el[i] = NULL;
3233     }
3234     mi_level = 1;
3235     mi_user_level = 1;
3236     mb_keep = VLC_FALSE;
3237     mb_dummy = config_GetInt( p_demux, "mkv-use-dummy" );
3238 }
3239
3240 EbmlParser::~EbmlParser( void )
3241 {
3242     int i;
3243
3244     for( i = 1; i < mi_level; i++ )
3245     {
3246         if( !mb_keep )
3247         {
3248             delete m_el[i];
3249         }
3250         mb_keep = VLC_FALSE;
3251     }
3252 }
3253
3254 void EbmlParser::Up( void )
3255 {
3256     if( mi_user_level == mi_level )
3257     {
3258         fprintf( stderr," arrrrrrrrrrrrrg Up cannot escape itself\n" );
3259     }
3260
3261     mi_user_level--;
3262 }
3263
3264 void EbmlParser::Down( void )
3265 {
3266     mi_user_level++;
3267     mi_level++;
3268 }
3269
3270 void EbmlParser::Keep( void )
3271 {
3272     mb_keep = VLC_TRUE;
3273 }
3274
3275 int EbmlParser::GetLevel( void )
3276 {
3277     return mi_user_level;
3278 }
3279
3280 void EbmlParser::Reset( demux_t *p_demux )
3281 {
3282     while ( mi_level > 0)
3283     {
3284         delete m_el[mi_level];
3285         m_el[mi_level] = NULL;
3286         mi_level--;
3287     }
3288     mi_user_level = mi_level = 1;
3289 #if LIBEBML_VERSION >= 0x000704
3290     // a little faster and cleaner
3291     m_es->I_O().setFilePointer( static_cast<KaxSegment*>(m_el[0])->GetGlobalPosition(0) );
3292 #else
3293     m_es->I_O().setFilePointer( m_el[0]->GetElementPosition() + m_el[0]->ElementSize(true) - m_el[0]->GetSize() );
3294 #endif
3295     mb_dummy = config_GetInt( p_demux, "mkv-use-dummy" );
3296 }
3297
3298 EbmlElement *EbmlParser::Get( void )
3299 {
3300     int i_ulev = 0;
3301
3302     if( mi_user_level != mi_level )
3303     {
3304         return NULL;
3305     }
3306     if( m_got )
3307     {
3308         EbmlElement *ret = m_got;
3309         m_got = NULL;
3310
3311         return ret;
3312     }
3313
3314     if( m_el[mi_level] )
3315     {
3316         m_el[mi_level]->SkipData( *m_es, m_el[mi_level]->Generic().Context );
3317         if( !mb_keep )
3318         {
3319             delete m_el[mi_level];
3320         }
3321         mb_keep = VLC_FALSE;
3322     }
3323
3324     m_el[mi_level] = m_es->FindNextElement( m_el[mi_level - 1]->Generic().Context, i_ulev, 0xFFFFFFFFL, mb_dummy, 1 );
3325 //    mi_remain_size[mi_level] = m_el[mi_level]->GetSize();
3326     if( i_ulev > 0 )
3327     {
3328         while( i_ulev > 0 )
3329         {
3330             if( mi_level == 1 )
3331             {
3332                 mi_level = 0;
3333                 return NULL;
3334             }
3335
3336             delete m_el[mi_level - 1];
3337             m_got = m_el[mi_level -1] = m_el[mi_level];
3338             m_el[mi_level] = NULL;
3339
3340             mi_level--;
3341             i_ulev--;
3342         }
3343         return NULL;
3344     }
3345     else if( m_el[mi_level] == NULL )
3346     {
3347         fprintf( stderr," m_el[mi_level] == NULL\n" );
3348     }
3349
3350     return m_el[mi_level];
3351 }
3352
3353
3354 /*****************************************************************************
3355  * Tools
3356  *  * LoadCues : load the cues element and update index
3357  *
3358  *  * LoadTags : load ... the tags element
3359  *
3360  *  * InformationCreate : create all information, load tags if present
3361  *
3362  *****************************************************************************/
3363 void matroska_segment_c::LoadCues( )
3364 {
3365     int64_t     i_sav_position = es.I_O().getFilePointer();
3366     EbmlParser  *ep;
3367     EbmlElement *el, *cues;
3368
3369     /* *** Load the cue if found *** */
3370     if( i_cues_position < 0 )
3371     {
3372         msg_Warn( &sys.demuxer, "no cues/empty cues found->seek won't be precise" );
3373
3374 //        IndexAppendCluster( cluster );
3375     }
3376
3377     vlc_bool_t b_seekable;
3378
3379     stream_Control( sys.demuxer.s, STREAM_CAN_FASTSEEK, &b_seekable );
3380     if( !b_seekable )
3381         return;
3382
3383     msg_Dbg( &sys.demuxer, "loading cues" );
3384     es.I_O().setFilePointer( i_cues_position, seek_beginning );
3385     cues = es.FindNextID( KaxCues::ClassInfos, 0xFFFFFFFFL);
3386
3387     if( cues == NULL )
3388     {
3389         msg_Err( &sys.demuxer, "cannot load cues (broken seekhead or file)" );
3390         es.I_O().setFilePointer( i_sav_position, seek_beginning );
3391         return;
3392     }
3393
3394     ep = new EbmlParser( &es, cues, &sys.demuxer );
3395     while( ( el = ep->Get() ) != NULL )
3396     {
3397         if( MKV_IS_ID( el, KaxCuePoint ) )
3398         {
3399 #define idx index[i_index]
3400
3401             idx.i_track       = -1;
3402             idx.i_block_number= -1;
3403             idx.i_position    = -1;
3404             idx.i_time        = 0;
3405             idx.b_key         = VLC_TRUE;
3406
3407             ep->Down();
3408             while( ( el = ep->Get() ) != NULL )
3409             {
3410                 if( MKV_IS_ID( el, KaxCueTime ) )
3411                 {
3412                     KaxCueTime &ctime = *(KaxCueTime*)el;
3413
3414                     ctime.ReadData( es.I_O() );
3415
3416                     idx.i_time = uint64( ctime ) * i_timescale / (mtime_t)1000;
3417                 }
3418                 else if( MKV_IS_ID( el, KaxCueTrackPositions ) )
3419                 {
3420                     ep->Down();
3421                     while( ( el = ep->Get() ) != NULL )
3422                     {
3423                         if( MKV_IS_ID( el, KaxCueTrack ) )
3424                         {
3425                             KaxCueTrack &ctrack = *(KaxCueTrack*)el;
3426
3427                             ctrack.ReadData( es.I_O() );
3428                             idx.i_track = uint16( ctrack );
3429                         }
3430                         else if( MKV_IS_ID( el, KaxCueClusterPosition ) )
3431                         {
3432                             KaxCueClusterPosition &ccpos = *(KaxCueClusterPosition*)el;
3433
3434                             ccpos.ReadData( es.I_O() );
3435                             idx.i_position = segment->GetGlobalPosition( uint64( ccpos ) );
3436                         }
3437                         else if( MKV_IS_ID( el, KaxCueBlockNumber ) )
3438                         {
3439                             KaxCueBlockNumber &cbnum = *(KaxCueBlockNumber*)el;
3440
3441                             cbnum.ReadData( es.I_O() );
3442                             idx.i_block_number = uint32( cbnum );
3443                         }
3444                         else
3445                         {
3446                             msg_Dbg( &sys.demuxer, "         * Unknown (%s)", typeid(*el).name() );
3447                         }
3448                     }
3449                     ep->Up();
3450                 }
3451                 else
3452                 {
3453                     msg_Dbg( &sys.demuxer, "     * Unknown (%s)", typeid(*el).name() );
3454                 }
3455             }
3456             ep->Up();
3457
3458 #if 0
3459             msg_Dbg( &sys.demuxer, " * added time="I64Fd" pos="I64Fd
3460                      " track=%d bnum=%d", idx.i_time, idx.i_position,
3461                      idx.i_track, idx.i_block_number );
3462 #endif
3463
3464             i_index++;
3465             if( i_index >= i_index_max )
3466             {
3467                 i_index_max += 1024;
3468                 index = (mkv_index_t*)realloc( index, sizeof( mkv_index_t ) * i_index_max );
3469             }
3470 #undef idx
3471         }
3472         else
3473         {
3474             msg_Dbg( &sys.demuxer, " * Unknown (%s)", typeid(*el).name() );
3475         }
3476     }
3477     delete ep;
3478     delete cues;
3479
3480     b_cues = VLC_TRUE;
3481
3482     msg_Dbg( &sys.demuxer, "loading cues done." );
3483     es.I_O().setFilePointer( i_sav_position, seek_beginning );
3484 }
3485
3486 void matroska_segment_c::LoadTags( )
3487 {
3488     int64_t     i_sav_position = es.I_O().getFilePointer();
3489     EbmlParser  *ep;
3490     EbmlElement *el, *tags;
3491
3492     msg_Dbg( &sys.demuxer, "loading tags" );
3493     es.I_O().setFilePointer( i_tags_position, seek_beginning );
3494     tags = es.FindNextID( KaxTags::ClassInfos, 0xFFFFFFFFL);
3495
3496     if( tags == NULL )
3497     {
3498         msg_Err( &sys.demuxer, "cannot load tags (broken seekhead or file)" );
3499         es.I_O().setFilePointer( i_sav_position, seek_beginning );
3500         return;
3501     }
3502
3503     msg_Dbg( &sys.demuxer, "Tags" );
3504     ep = new EbmlParser( &es, tags, &sys.demuxer );
3505     while( ( el = ep->Get() ) != NULL )
3506     {
3507         if( MKV_IS_ID( el, KaxTag ) )
3508         {
3509             msg_Dbg( &sys.demuxer, "+ Tag" );
3510             ep->Down();
3511             while( ( el = ep->Get() ) != NULL )
3512             {
3513                 if( MKV_IS_ID( el, KaxTagTargets ) )
3514                 {
3515                     msg_Dbg( &sys.demuxer, "|   + Targets" );
3516                     ep->Down();
3517                     while( ( el = ep->Get() ) != NULL )
3518                     {
3519                         msg_Dbg( &sys.demuxer, "|   |   + Unknown (%s)", typeid( *el ).name() );
3520                     }
3521                     ep->Up();
3522                 }
3523                 else if( MKV_IS_ID( el, KaxTagGeneral ) )
3524                 {
3525                     msg_Dbg( &sys.demuxer, "|   + General" );
3526                     ep->Down();
3527                     while( ( el = ep->Get() ) != NULL )
3528                     {
3529                         msg_Dbg( &sys.demuxer, "|   |   + Unknown (%s)", typeid( *el ).name() );
3530                     }
3531                     ep->Up();
3532                 }
3533                 else if( MKV_IS_ID( el, KaxTagGenres ) )
3534                 {
3535                     msg_Dbg( &sys.demuxer, "|   + Genres" );
3536                     ep->Down();
3537                     while( ( el = ep->Get() ) != NULL )
3538                     {
3539                         msg_Dbg( &sys.demuxer, "|   |   + Unknown (%s)", typeid( *el ).name() );
3540                     }
3541                     ep->Up();
3542                 }
3543                 else if( MKV_IS_ID( el, KaxTagAudioSpecific ) )
3544                 {
3545                     msg_Dbg( &sys.demuxer, "|   + Audio Specific" );
3546                     ep->Down();
3547                     while( ( el = ep->Get() ) != NULL )
3548                     {
3549                         msg_Dbg( &sys.demuxer, "|   |   + Unknown (%s)", typeid( *el ).name() );
3550                     }
3551                     ep->Up();
3552                 }
3553                 else if( MKV_IS_ID( el, KaxTagImageSpecific ) )
3554                 {
3555                     msg_Dbg( &sys.demuxer, "|   + Images Specific" );
3556                     ep->Down();
3557                     while( ( el = ep->Get() ) != NULL )
3558                     {
3559                         msg_Dbg( &sys.demuxer, "|   |   + Unknown (%s)", typeid( *el ).name() );
3560                     }
3561                     ep->Up();
3562                 }
3563                 else if( MKV_IS_ID( el, KaxTagMultiComment ) )
3564                 {
3565                     msg_Dbg( &sys.demuxer, "|   + Multi Comment" );
3566                 }
3567                 else if( MKV_IS_ID( el, KaxTagMultiCommercial ) )
3568                 {
3569                     msg_Dbg( &sys.demuxer, "|   + Multi Commercial" );
3570                 }
3571                 else if( MKV_IS_ID( el, KaxTagMultiDate ) )
3572                 {
3573                     msg_Dbg( &sys.demuxer, "|   + Multi Date" );
3574                 }
3575                 else if( MKV_IS_ID( el, KaxTagMultiEntity ) )
3576                 {
3577                     msg_Dbg( &sys.demuxer, "|   + Multi Entity" );
3578                 }
3579                 else if( MKV_IS_ID( el, KaxTagMultiIdentifier ) )
3580                 {
3581                     msg_Dbg( &sys.demuxer, "|   + Multi Identifier" );
3582                 }
3583                 else if( MKV_IS_ID( el, KaxTagMultiLegal ) )
3584                 {
3585                     msg_Dbg( &sys.demuxer, "|   + Multi Legal" );
3586                 }
3587                 else if( MKV_IS_ID( el, KaxTagMultiTitle ) )
3588                 {
3589                     msg_Dbg( &sys.demuxer, "|   + Multi Title" );
3590                 }
3591                 else
3592                 {
3593                     msg_Dbg( &sys.demuxer, "|   + Unknown (%s)", typeid( *el ).name() );
3594                 }
3595             }
3596             ep->Up();
3597         }
3598         else
3599         {
3600             msg_Dbg( &sys.demuxer, "+ Unknown (%s)", typeid( *el ).name() );
3601         }
3602     }
3603     delete ep;
3604     delete tags;
3605
3606     msg_Dbg( &sys.demuxer, "loading tags done." );
3607     es.I_O().setFilePointer( i_sav_position, seek_beginning );
3608 }
3609
3610 /*****************************************************************************
3611  * ParseSeekHead:
3612  *****************************************************************************/
3613 void matroska_segment_c::ParseSeekHead( KaxSeekHead *seekhead )
3614 {
3615     EbmlElement *el;
3616     size_t i, j;
3617     int i_upper_level = 0;
3618
3619     msg_Dbg( &sys.demuxer, "|   + Seek head" );
3620
3621     /* Master elements */
3622     seekhead->Read( es, seekhead->Generic().Context, i_upper_level, el, true );
3623
3624     for( i = 0; i < seekhead->ListSize(); i++ )
3625     {
3626         EbmlElement *l = (*seekhead)[i];
3627
3628         if( MKV_IS_ID( l, KaxSeek ) )
3629         {
3630             EbmlMaster *sk = static_cast<EbmlMaster *>(l);
3631             EbmlId id = EbmlVoid::ClassInfos.GlobalId;
3632             int64_t i_pos = -1;
3633
3634             for( j = 0; j < sk->ListSize(); j++ )
3635             {
3636                 EbmlElement *l = (*sk)[j];
3637
3638                 if( MKV_IS_ID( l, KaxSeekID ) )
3639                 {
3640                     KaxSeekID &sid = *(KaxSeekID*)l;
3641                     id = EbmlId( sid.GetBuffer(), sid.GetSize() );
3642                 }
3643                 else if( MKV_IS_ID( l, KaxSeekPosition ) )
3644                 {
3645                     KaxSeekPosition &spos = *(KaxSeekPosition*)l;
3646                     i_pos = uint64( spos );
3647                 }
3648                 else
3649                 {
3650                     msg_Dbg( &sys.demuxer, "|   |   |   + Unknown (%s)", typeid(*l).name() );
3651                 }
3652             }
3653
3654             if( i_pos >= 0 )
3655             {
3656                 if( id == KaxCues::ClassInfos.GlobalId )
3657                 {
3658                     msg_Dbg( &sys.demuxer, "|   |   |   = cues at "I64Fd, i_pos );
3659                     i_cues_position = segment->GetGlobalPosition( i_pos );
3660                 }
3661                 else if( id == KaxChapters::ClassInfos.GlobalId )
3662                 {
3663                     msg_Dbg( &sys.demuxer, "|   |   |   = chapters at "I64Fd, i_pos );
3664                     i_chapters_position = segment->GetGlobalPosition( i_pos );
3665                 }
3666                 else if( id == KaxTags::ClassInfos.GlobalId )
3667                 {
3668                     msg_Dbg( &sys.demuxer, "|   |   |   = tags at "I64Fd, i_pos );
3669                     i_tags_position = segment->GetGlobalPosition( i_pos );
3670                 }
3671             }
3672         }
3673         else
3674         {
3675             msg_Dbg( &sys.demuxer, "|   |   + Unknown (%s)", typeid(*l).name() );
3676         }
3677     }
3678 }
3679
3680 /*****************************************************************************
3681  * ParseTrackEntry:
3682  *****************************************************************************/
3683 void matroska_segment_c::ParseTrackEntry( KaxTrackEntry *m )
3684 {
3685     size_t i, j, k, n;
3686
3687     mkv_track_t *tk;
3688
3689     msg_Dbg( &sys.demuxer, "|   |   + Track Entry" );
3690
3691     tk = new mkv_track_t();
3692     tracks.push_back( tk );
3693
3694     /* Init the track */
3695     memset( tk, 0, sizeof( mkv_track_t ) );
3696
3697     es_format_Init( &tk->fmt, UNKNOWN_ES, 0 );
3698     tk->fmt.psz_language = strdup("English");
3699     tk->fmt.psz_description = NULL;
3700
3701     tk->b_default = VLC_TRUE;
3702     tk->b_enabled = VLC_TRUE;
3703     tk->b_silent = VLC_FALSE;
3704     tk->i_number = tracks.size() - 1;
3705     tk->i_extra_data = 0;
3706     tk->p_extra_data = NULL;
3707     tk->psz_codec = NULL;
3708     tk->i_default_duration = 0;
3709     tk->f_timecodescale = 1.0;
3710
3711     tk->b_inited = VLC_FALSE;
3712     tk->i_data_init = 0;
3713     tk->p_data_init = NULL;
3714
3715     tk->psz_codec_name = NULL;
3716     tk->psz_codec_settings = NULL;
3717     tk->psz_codec_info_url = NULL;
3718     tk->psz_codec_download_url = NULL;
3719     
3720     tk->i_compression_type = MATROSKA_COMPRESSION_NONE;
3721
3722     for( i = 0; i < m->ListSize(); i++ )
3723     {
3724         EbmlElement *l = (*m)[i];
3725
3726         if( MKV_IS_ID( l, KaxTrackNumber ) )
3727         {
3728             KaxTrackNumber &tnum = *(KaxTrackNumber*)l;
3729
3730             tk->i_number = uint32( tnum );
3731             msg_Dbg( &sys.demuxer, "|   |   |   + Track Number=%u", uint32( tnum ) );
3732         }
3733         else  if( MKV_IS_ID( l, KaxTrackUID ) )
3734         {
3735             KaxTrackUID &tuid = *(KaxTrackUID*)l;
3736
3737             msg_Dbg( &sys.demuxer, "|   |   |   + Track UID=%u",  uint32( tuid ) );
3738         }
3739         else  if( MKV_IS_ID( l, KaxTrackType ) )
3740         {
3741             char *psz_type;
3742             KaxTrackType &ttype = *(KaxTrackType*)l;
3743
3744             switch( uint8(ttype) )
3745             {
3746                 case track_audio:
3747                     psz_type = "audio";
3748                     tk->fmt.i_cat = AUDIO_ES;
3749                     break;
3750                 case track_video:
3751                     psz_type = "video";
3752                     tk->fmt.i_cat = VIDEO_ES;
3753                     break;
3754                 case track_subtitle:
3755                     psz_type = "subtitle";
3756                     tk->fmt.i_cat = SPU_ES;
3757                     break;
3758                 case track_buttons:
3759                     psz_type = "buttons";
3760                     tk->fmt.i_cat = SPU_ES;
3761                     break;
3762                 default:
3763                     psz_type = "unknown";
3764                     tk->fmt.i_cat = UNKNOWN_ES;
3765                     break;
3766             }
3767
3768             msg_Dbg( &sys.demuxer, "|   |   |   + Track Type=%s", psz_type );
3769         }
3770 //        else  if( EbmlId( *l ) == KaxTrackFlagEnabled::ClassInfos.GlobalId )
3771 //        {
3772 //            KaxTrackFlagEnabled &fenb = *(KaxTrackFlagEnabled*)l;
3773
3774 //            tk->b_enabled = uint32( fenb );
3775 //            msg_Dbg( &sys.demuxer, "|   |   |   + Track Enabled=%u",
3776 //                     uint32( fenb )  );
3777 //        }
3778         else  if( MKV_IS_ID( l, KaxTrackFlagDefault ) )
3779         {
3780             KaxTrackFlagDefault &fdef = *(KaxTrackFlagDefault*)l;
3781
3782             tk->b_default = uint32( fdef );
3783             msg_Dbg( &sys.demuxer, "|   |   |   + Track Default=%u", uint32( fdef )  );
3784         }
3785         else  if( MKV_IS_ID( l, KaxTrackFlagLacing ) )
3786         {
3787             KaxTrackFlagLacing &lac = *(KaxTrackFlagLacing*)l;
3788
3789             msg_Dbg( &sys.demuxer, "|   |   |   + Track Lacing=%d", uint32( lac ) );
3790         }
3791         else  if( MKV_IS_ID( l, KaxTrackMinCache ) )
3792         {
3793             KaxTrackMinCache &cmin = *(KaxTrackMinCache*)l;
3794
3795             msg_Dbg( &sys.demuxer, "|   |   |   + Track MinCache=%d", uint32( cmin ) );
3796         }
3797         else  if( MKV_IS_ID( l, KaxTrackMaxCache ) )
3798         {
3799             KaxTrackMaxCache &cmax = *(KaxTrackMaxCache*)l;
3800
3801             msg_Dbg( &sys.demuxer, "|   |   |   + Track MaxCache=%d", uint32( cmax ) );
3802         }
3803         else  if( MKV_IS_ID( l, KaxTrackDefaultDuration ) )
3804         {
3805             KaxTrackDefaultDuration &defd = *(KaxTrackDefaultDuration*)l;
3806
3807             tk->i_default_duration = uint64(defd);
3808             msg_Dbg( &sys.demuxer, "|   |   |   + Track Default Duration="I64Fd, uint64(defd) );
3809         }
3810         else  if( MKV_IS_ID( l, KaxTrackTimecodeScale ) )
3811         {
3812             KaxTrackTimecodeScale &ttcs = *(KaxTrackTimecodeScale*)l;
3813
3814             tk->f_timecodescale = float( ttcs );
3815             msg_Dbg( &sys.demuxer, "|   |   |   + Track TimeCodeScale=%f", tk->f_timecodescale );
3816         }
3817         else if( MKV_IS_ID( l, KaxTrackName ) )
3818         {
3819             KaxTrackName &tname = *(KaxTrackName*)l;
3820
3821             tk->fmt.psz_description = UTF8ToStr( UTFstring( tname ) );
3822             msg_Dbg( &sys.demuxer, "|   |   |   + Track Name=%s", tk->fmt.psz_description );
3823         }
3824         else  if( MKV_IS_ID( l, KaxTrackLanguage ) )
3825         {
3826             KaxTrackLanguage &lang = *(KaxTrackLanguage*)l;
3827
3828             tk->fmt.psz_language = strdup( string( lang ).c_str() );
3829             msg_Dbg( &sys.demuxer,
3830                      "|   |   |   + Track Language=`%s'", tk->fmt.psz_language );
3831         }
3832         else  if( MKV_IS_ID( l, KaxCodecID ) )
3833         {
3834             KaxCodecID &codecid = *(KaxCodecID*)l;
3835
3836             tk->psz_codec = strdup( string( codecid ).c_str() );
3837             msg_Dbg( &sys.demuxer, "|   |   |   + Track CodecId=%s", string( codecid ).c_str() );
3838         }
3839         else  if( MKV_IS_ID( l, KaxCodecPrivate ) )
3840         {
3841             KaxCodecPrivate &cpriv = *(KaxCodecPrivate*)l;
3842
3843             tk->i_extra_data = cpriv.GetSize();
3844             if( tk->i_extra_data > 0 )
3845             {
3846                 tk->p_extra_data = (uint8_t*)malloc( tk->i_extra_data );
3847                 memcpy( tk->p_extra_data, cpriv.GetBuffer(), tk->i_extra_data );
3848             }
3849             msg_Dbg( &sys.demuxer, "|   |   |   + Track CodecPrivate size="I64Fd, cpriv.GetSize() );
3850         }
3851         else if( MKV_IS_ID( l, KaxCodecName ) )
3852         {
3853             KaxCodecName &cname = *(KaxCodecName*)l;
3854
3855             tk->psz_codec_name = UTF8ToStr( UTFstring( cname ) );
3856             msg_Dbg( &sys.demuxer, "|   |   |   + Track Codec Name=%s", tk->psz_codec_name );
3857         }
3858         else if( MKV_IS_ID( l, KaxContentEncodings ) )
3859         {
3860             EbmlMaster *cencs = static_cast<EbmlMaster*>(l);
3861             MkvTree( sys.demuxer, 3, "Content Encodings" );
3862             for( j = 0; j < cencs->ListSize(); j++ )
3863             {
3864                 EbmlElement *l2 = (*cencs)[j];
3865                 if( MKV_IS_ID( l2, KaxContentEncoding ) )
3866                 {
3867                     MkvTree( sys.demuxer, 4, "Content Encoding" );
3868                     EbmlMaster *cenc = static_cast<EbmlMaster*>(l2);
3869                     for( k = 0; k < cenc->ListSize(); k++ )
3870                     {
3871                         EbmlElement *l3 = (*cenc)[k];
3872                         if( MKV_IS_ID( l3, KaxContentEncodingOrder ) )
3873                         {
3874                             KaxContentEncodingOrder &encord = *(KaxContentEncodingOrder*)l3;
3875                             MkvTree( sys.demuxer, 5, "Order: %i", uint32( encord ) );
3876                         }
3877                         else if( MKV_IS_ID( l3, KaxContentEncodingScope ) )
3878                         {
3879                             KaxContentEncodingScope &encscope = *(KaxContentEncodingScope*)l3;
3880                             MkvTree( sys.demuxer, 5, "Scope: %i", uint32( encscope ) );
3881                         }
3882                         else if( MKV_IS_ID( l3, KaxContentEncodingType ) )
3883                         {
3884                             KaxContentEncodingType &enctype = *(KaxContentEncodingType*)l3;
3885                             MkvTree( sys.demuxer, 5, "Type: %i", uint32( enctype ) );
3886                         }
3887                         else if( MKV_IS_ID( l3, KaxContentCompression ) )
3888                         {
3889                             EbmlMaster *compr = static_cast<EbmlMaster*>(l3);
3890                             MkvTree( sys.demuxer, 5, "Content Compression" );
3891                             for( n = 0; n < compr->ListSize(); n++ )
3892                             {
3893                                 EbmlElement *l4 = (*compr)[n];
3894                                 if( MKV_IS_ID( l4, KaxContentCompAlgo ) )
3895                                 {
3896                                     KaxContentCompAlgo &compalg = *(KaxContentCompAlgo*)l4;
3897                                     MkvTree( sys.demuxer, 6, "Compression Algorithm: %i", uint32(compalg) );
3898                                     if( uint32( compalg ) == 0 )
3899                                     {
3900                                         tk->i_compression_type = MATROSKA_COMPRESSION_ZLIB;
3901                                     }
3902                                 }
3903                                 else
3904                                 {
3905                                     MkvTree( sys.demuxer, 6, "Unknown (%s)", typeid(*l4).name() );
3906                                 }
3907                             }
3908                         }
3909
3910                         else
3911                         {
3912                             MkvTree( sys.demuxer, 5, "Unknown (%s)", typeid(*l3).name() );
3913                         }
3914                     }
3915                     
3916                 }
3917                 else
3918                 {
3919                     MkvTree( sys.demuxer, 4, "Unknown (%s)", typeid(*l2).name() );
3920                 }
3921             }
3922                 
3923         }
3924 //        else if( EbmlId( *l ) == KaxCodecSettings::ClassInfos.GlobalId )
3925 //        {
3926 //            KaxCodecSettings &cset = *(KaxCodecSettings*)l;
3927
3928 //            tk->psz_codec_settings = UTF8ToStr( UTFstring( cset ) );
3929 //            msg_Dbg( &sys.demuxer, "|   |   |   + Track Codec Settings=%s", tk->psz_codec_settings );
3930 //        }
3931 //        else if( EbmlId( *l ) == KaxCodecInfoURL::ClassInfos.GlobalId )
3932 //        {
3933 //            KaxCodecInfoURL &ciurl = *(KaxCodecInfoURL*)l;
3934
3935 //            tk->psz_codec_info_url = strdup( string( ciurl ).c_str() );
3936 //            msg_Dbg( &sys.demuxer, "|   |   |   + Track Codec Info URL=%s", tk->psz_codec_info_url );
3937 //        }
3938 //        else if( EbmlId( *l ) == KaxCodecDownloadURL::ClassInfos.GlobalId )
3939 //        {
3940 //            KaxCodecDownloadURL &cdurl = *(KaxCodecDownloadURL*)l;
3941
3942 //            tk->psz_codec_download_url = strdup( string( cdurl ).c_str() );
3943 //            msg_Dbg( &sys.demuxer, "|   |   |   + Track Codec Info URL=%s", tk->psz_codec_download_url );
3944 //        }
3945 //        else if( EbmlId( *l ) == KaxCodecDecodeAll::ClassInfos.GlobalId )
3946 //        {
3947 //            KaxCodecDecodeAll &cdall = *(KaxCodecDecodeAll*)l;
3948
3949 //            msg_Dbg( &sys.demuxer, "|   |   |   + Track Codec Decode All=%u <== UNUSED", uint8( cdall ) );
3950 //        }
3951 //        else if( EbmlId( *l ) == KaxTrackOverlay::ClassInfos.GlobalId )
3952 //        {
3953 //            KaxTrackOverlay &tovr = *(KaxTrackOverlay*)l;
3954
3955 //            msg_Dbg( &sys.demuxer, "|   |   |   + Track Overlay=%u <== UNUSED", uint32( tovr ) );
3956 //        }
3957         else  if( MKV_IS_ID( l, KaxTrackVideo ) )
3958         {
3959             EbmlMaster *tkv = static_cast<EbmlMaster*>(l);
3960             unsigned int j;
3961
3962             msg_Dbg( &sys.demuxer, "|   |   |   + Track Video" );
3963             tk->f_fps = 0.0;
3964
3965             for( j = 0; j < tkv->ListSize(); j++ )
3966             {
3967                 EbmlElement *l = (*tkv)[j];
3968 //                if( EbmlId( *el4 ) == KaxVideoFlagInterlaced::ClassInfos.GlobalId )
3969 //                {
3970 //                    KaxVideoFlagInterlaced &fint = *(KaxVideoFlagInterlaced*)el4;
3971
3972 //                    msg_Dbg( &sys.demuxer, "|   |   |   |   + Track Video Interlaced=%u", uint8( fint ) );
3973 //                }
3974 //                else if( EbmlId( *el4 ) == KaxVideoStereoMode::ClassInfos.GlobalId )
3975 //                {
3976 //                    KaxVideoStereoMode &stereo = *(KaxVideoStereoMode*)el4;
3977
3978 //                    msg_Dbg( &sys.demuxer, "|   |   |   |   + Track Video Stereo Mode=%u", uint8( stereo ) );
3979 //                }
3980 //                else
3981                 if( MKV_IS_ID( l, KaxVideoPixelWidth ) )
3982                 {
3983                     KaxVideoPixelWidth &vwidth = *(KaxVideoPixelWidth*)l;
3984
3985                     tk->fmt.video.i_width = uint16( vwidth );
3986                     msg_Dbg( &sys.demuxer, "|   |   |   |   + width=%d", uint16( vwidth ) );
3987                 }
3988                 else if( MKV_IS_ID( l, KaxVideoPixelHeight ) )
3989                 {
3990                     KaxVideoPixelWidth &vheight = *(KaxVideoPixelWidth*)l;
3991
3992                     tk->fmt.video.i_height = uint16( vheight );
3993                     msg_Dbg( &sys.demuxer, "|   |   |   |   + height=%d", uint16( vheight ) );
3994                 }
3995                 else if( MKV_IS_ID( l, KaxVideoDisplayWidth ) )
3996                 {
3997                     KaxVideoDisplayWidth &vwidth = *(KaxVideoDisplayWidth*)l;
3998
3999                     tk->fmt.video.i_visible_width = uint16( vwidth );
4000                     msg_Dbg( &sys.demuxer, "|   |   |   |   + display width=%d", uint16( vwidth ) );
4001                 }
4002                 else if( MKV_IS_ID( l, KaxVideoDisplayHeight ) )
4003                 {
4004                     KaxVideoDisplayWidth &vheight = *(KaxVideoDisplayWidth*)l;
4005
4006                     tk->fmt.video.i_visible_height = uint16( vheight );
4007                     msg_Dbg( &sys.demuxer, "|   |   |   |   + display height=%d", uint16( vheight ) );
4008                 }
4009                 else if( MKV_IS_ID( l, KaxVideoFrameRate ) )
4010                 {
4011                     KaxVideoFrameRate &vfps = *(KaxVideoFrameRate*)l;
4012
4013                     tk->f_fps = float( vfps );
4014                     msg_Dbg( &sys.demuxer, "   |   |   |   + fps=%f", float( vfps ) );
4015                 }
4016 //                else if( EbmlId( *l ) == KaxVideoDisplayUnit::ClassInfos.GlobalId )
4017 //                {
4018 //                     KaxVideoDisplayUnit &vdmode = *(KaxVideoDisplayUnit*)l;
4019
4020 //                    msg_Dbg( &sys.demuxer, "|   |   |   |   + Track Video Display Unit=%s",
4021 //                             uint8( vdmode ) == 0 ? "pixels" : ( uint8( vdmode ) == 1 ? "centimeters": "inches" ) );
4022 //                }
4023 //                else if( EbmlId( *l ) == KaxVideoAspectRatio::ClassInfos.GlobalId )
4024 //                {
4025 //                    KaxVideoAspectRatio &ratio = *(KaxVideoAspectRatio*)l;
4026
4027 //                    msg_Dbg( &sys.demuxer, "   |   |   |   + Track Video Aspect Ratio Type=%u", uint8( ratio ) );
4028 //                }
4029 //                else if( EbmlId( *l ) == KaxVideoGamma::ClassInfos.GlobalId )
4030 //                {
4031 //                    KaxVideoGamma &gamma = *(KaxVideoGamma*)l;
4032
4033 //                    msg_Dbg( &sys.demuxer, "   |   |   |   + fps=%f", float( gamma ) );
4034 //                }
4035                 else
4036                 {
4037                     msg_Dbg( &sys.demuxer, "|   |   |   |   + Unknown (%s)", typeid(*l).name() );
4038                 }
4039             }
4040             if ( tk->fmt.video.i_visible_height && tk->fmt.video.i_visible_width )
4041                 tk->fmt.video.i_aspect = VOUT_ASPECT_FACTOR * tk->fmt.video.i_visible_width / tk->fmt.video.i_visible_height;
4042         }
4043         else  if( MKV_IS_ID( l, KaxTrackAudio ) )
4044         {
4045             EbmlMaster *tka = static_cast<EbmlMaster*>(l);
4046             unsigned int j;
4047
4048             msg_Dbg( &sys.demuxer, "|   |   |   + Track Audio" );
4049
4050             for( j = 0; j < tka->ListSize(); j++ )
4051             {
4052                 EbmlElement *l = (*tka)[j];
4053
4054                 if( MKV_IS_ID( l, KaxAudioSamplingFreq ) )
4055                 {
4056                     KaxAudioSamplingFreq &afreq = *(KaxAudioSamplingFreq*)l;
4057
4058                     tk->fmt.audio.i_rate = (int)float( afreq );
4059                     msg_Dbg( &sys.demuxer, "|   |   |   |   + afreq=%d", tk->fmt.audio.i_rate );
4060                 }
4061                 else if( MKV_IS_ID( l, KaxAudioChannels ) )
4062                 {
4063                     KaxAudioChannels &achan = *(KaxAudioChannels*)l;
4064
4065                     tk->fmt.audio.i_channels = uint8( achan );
4066                     msg_Dbg( &sys.demuxer, "|   |   |   |   + achan=%u", uint8( achan ) );
4067                 }
4068                 else if( MKV_IS_ID( l, KaxAudioBitDepth ) )
4069                 {
4070                     KaxAudioBitDepth &abits = *(KaxAudioBitDepth*)l;
4071
4072                     tk->fmt.audio.i_bitspersample = uint8( abits );
4073                     msg_Dbg( &sys.demuxer, "|   |   |   |   + abits=%u", uint8( abits ) );
4074                 }
4075                 else
4076                 {
4077                     msg_Dbg( &sys.demuxer, "|   |   |   |   + Unknown (%s)", typeid(*l).name() );
4078                 }
4079             }
4080         }
4081         else
4082         {
4083             msg_Dbg( &sys.demuxer, "|   |   |   + Unknown (%s)",
4084                      typeid(*l).name() );
4085         }
4086     }
4087 }
4088
4089 /*****************************************************************************
4090  * ParseTracks:
4091  *****************************************************************************/
4092 void matroska_segment_c::ParseTracks( KaxTracks *tracks )
4093 {
4094     EbmlElement *el;
4095     unsigned int i;
4096     int i_upper_level = 0;
4097
4098     msg_Dbg( &sys.demuxer, "|   + Tracks" );
4099
4100     /* Master elements */
4101     tracks->Read( es, tracks->Generic().Context, i_upper_level, el, true );
4102
4103     for( i = 0; i < tracks->ListSize(); i++ )
4104     {
4105         EbmlElement *l = (*tracks)[i];
4106
4107         if( MKV_IS_ID( l, KaxTrackEntry ) )
4108         {
4109             ParseTrackEntry( static_cast<KaxTrackEntry *>(l) );
4110         }
4111         else
4112         {
4113             msg_Dbg( &sys.demuxer, "|   |   + Unknown (%s)", typeid(*l).name() );
4114         }
4115     }
4116 }
4117
4118 /*****************************************************************************
4119  * ParseInfo:
4120  *****************************************************************************/
4121 void matroska_segment_c::ParseInfo( KaxInfo *info )
4122 {
4123     EbmlElement *el;
4124     EbmlMaster  *m;
4125     size_t i, j;
4126     int i_upper_level = 0;
4127
4128     msg_Dbg( &sys.demuxer, "|   + Information" );
4129
4130     /* Master elements */
4131     m = static_cast<EbmlMaster *>(info);
4132     m->Read( es, info->Generic().Context, i_upper_level, el, true );
4133
4134     for( i = 0; i < m->ListSize(); i++ )
4135     {
4136         EbmlElement *l = (*m)[i];
4137
4138         if( MKV_IS_ID( l, KaxSegmentUID ) )
4139         {
4140             segment_uid = *(new KaxSegmentUID(*static_cast<KaxSegmentUID*>(l)));
4141
4142             msg_Dbg( &sys.demuxer, "|   |   + UID=%d", *(uint32*)segment_uid.GetBuffer() );
4143         }
4144         else if( MKV_IS_ID( l, KaxPrevUID ) )
4145         {
4146             prev_segment_uid = *(new KaxPrevUID(*static_cast<KaxPrevUID*>(l)));
4147
4148             msg_Dbg( &sys.demuxer, "|   |   + PrevUID=%d", *(uint32*)prev_segment_uid.GetBuffer() );
4149         }
4150         else if( MKV_IS_ID( l, KaxNextUID ) )
4151         {
4152             next_segment_uid = *(new KaxNextUID(*static_cast<KaxNextUID*>(l)));
4153
4154             msg_Dbg( &sys.demuxer, "|   |   + NextUID=%d", *(uint32*)next_segment_uid.GetBuffer() );
4155         }
4156         else if( MKV_IS_ID( l, KaxTimecodeScale ) )
4157         {
4158             KaxTimecodeScale &tcs = *(KaxTimecodeScale*)l;
4159
4160             i_timescale = uint64(tcs);
4161
4162             msg_Dbg( &sys.demuxer, "|   |   + TimecodeScale="I64Fd,
4163                      i_timescale );
4164         }
4165         else if( MKV_IS_ID( l, KaxDuration ) )
4166         {
4167             KaxDuration &dur = *(KaxDuration*)l;
4168
4169             i_duration = mtime_t( double( dur ) );
4170
4171             msg_Dbg( &sys.demuxer, "|   |   + Duration="I64Fd,
4172                      i_duration );
4173         }
4174         else if( MKV_IS_ID( l, KaxMuxingApp ) )
4175         {
4176             KaxMuxingApp &mapp = *(KaxMuxingApp*)l;
4177
4178             psz_muxing_application = UTF8ToStr( UTFstring( mapp ) );
4179
4180             msg_Dbg( &sys.demuxer, "|   |   + Muxing Application=%s",
4181                      psz_muxing_application );
4182         }
4183         else if( MKV_IS_ID( l, KaxWritingApp ) )
4184         {
4185             KaxWritingApp &wapp = *(KaxWritingApp*)l;
4186
4187             psz_writing_application = UTF8ToStr( UTFstring( wapp ) );
4188
4189             msg_Dbg( &sys.demuxer, "|   |   + Writing Application=%s",
4190                      psz_writing_application );
4191         }
4192         else if( MKV_IS_ID( l, KaxSegmentFilename ) )
4193         {
4194             KaxSegmentFilename &sfn = *(KaxSegmentFilename*)l;
4195
4196             psz_segment_filename = UTF8ToStr( UTFstring( sfn ) );
4197
4198             msg_Dbg( &sys.demuxer, "|   |   + Segment Filename=%s",
4199                      psz_segment_filename );
4200         }
4201         else if( MKV_IS_ID( l, KaxTitle ) )
4202         {
4203             KaxTitle &title = *(KaxTitle*)l;
4204
4205             psz_title = UTF8ToStr( UTFstring( title ) );
4206
4207             msg_Dbg( &sys.demuxer, "|   |   + Title=%s", psz_title );
4208         }
4209         else if( MKV_IS_ID( l, KaxSegmentFamily ) )
4210         {
4211             KaxSegmentFamily *uid = static_cast<KaxSegmentFamily*>(l);
4212
4213             families.push_back(*uid);
4214
4215             msg_Dbg( &sys.demuxer, "|   |   + family=%d", *(uint32*)uid->GetBuffer() );
4216         }
4217 #if defined( HAVE_GMTIME_R ) && !defined( SYS_DARWIN )
4218         else if( MKV_IS_ID( l, KaxDateUTC ) )
4219         {
4220             KaxDateUTC &date = *(KaxDateUTC*)l;
4221             time_t i_date;
4222             struct tm tmres;
4223             char   buffer[256];
4224
4225             i_date = date.GetEpochDate();
4226             memset( buffer, 0, 256 );
4227             if( gmtime_r( &i_date, &tmres ) &&
4228                 asctime_r( &tmres, buffer ) )
4229             {
4230                 buffer[strlen( buffer)-1]= '\0';
4231                 psz_date_utc = strdup( buffer );
4232                 msg_Dbg( &sys.demuxer, "|   |   + Date=%s", psz_date_utc );
4233             }
4234         }
4235 #endif
4236 #if LIBMATROSKA_VERSION >= 0x000704
4237         else if( MKV_IS_ID( l, KaxChapterTranslate ) )
4238         {
4239             KaxChapterTranslate *p_trans = static_cast<KaxChapterTranslate*>( l );
4240             chapter_translation_c translated;
4241
4242             p_trans->Read( es, p_trans->Generic().Context, i_upper_level, el, true );
4243             for( j = 0; j < p_trans->ListSize(); j++ )
4244             {
4245                 EbmlElement *l = (*p_trans)[j];
4246
4247                 if( MKV_IS_ID( l, KaxChapterTranslateEditionUID ) )
4248                 {
4249                     translated.editions.push_back( uint64( *static_cast<KaxChapterTranslateEditionUID*>( l ) ) );
4250                 }
4251                 else if( MKV_IS_ID( l, KaxChapterTranslateCodec ) )
4252                 {
4253                     translated.codec_id = uint32( *static_cast<KaxChapterTranslateCodec*>( l ) );
4254                 }
4255                 else if( MKV_IS_ID( l, KaxChapterTranslateID ) )
4256                 {
4257                     translated.translated = *( new KaxChapterTranslateID( *static_cast<KaxChapterTranslateID*>( l ) ) );
4258                 }
4259             }
4260
4261             translations.push_back( translated );
4262         }
4263 #endif
4264         else
4265         {
4266             msg_Dbg( &sys.demuxer, "|   |   + Unknown (%s)", typeid(*l).name() );
4267         }
4268     }
4269
4270     double f_dur = double(i_duration) * double(i_timescale) / 1000000.0;
4271     i_duration = mtime_t(f_dur);
4272 }
4273
4274
4275 /*****************************************************************************
4276  * ParseChapterAtom
4277  *****************************************************************************/
4278 void matroska_segment_c::ParseChapterAtom( int i_level, KaxChapterAtom *ca, chapter_item_c & chapters )
4279 {
4280     size_t i, j;
4281
4282     msg_Dbg( &sys.demuxer, "|   |   |   + ChapterAtom (level=%d)", i_level );
4283     for( i = 0; i < ca->ListSize(); i++ )
4284     {
4285         EbmlElement *l = (*ca)[i];
4286
4287         if( MKV_IS_ID( l, KaxChapterUID ) )
4288         {
4289             chapters.i_uid = uint64_t(*(KaxChapterUID*)l);
4290             msg_Dbg( &sys.demuxer, "|   |   |   |   + ChapterUID: %lld", chapters.i_uid );
4291         }
4292         else if( MKV_IS_ID( l, KaxChapterFlagHidden ) )
4293         {
4294             KaxChapterFlagHidden &flag =*(KaxChapterFlagHidden*)l;
4295             chapters.b_display_seekpoint = uint8( flag ) == 0;
4296
4297             msg_Dbg( &sys.demuxer, "|   |   |   |   + ChapterFlagHidden: %s", chapters.b_display_seekpoint ? "no":"yes" );
4298         }
4299         else if( MKV_IS_ID( l, KaxChapterTimeStart ) )
4300         {
4301             KaxChapterTimeStart &start =*(KaxChapterTimeStart*)l;
4302             chapters.i_start_time = uint64( start ) / I64C(1000);
4303
4304             msg_Dbg( &sys.demuxer, "|   |   |   |   + ChapterTimeStart: %lld", chapters.i_start_time );
4305         }
4306         else if( MKV_IS_ID( l, KaxChapterTimeEnd ) )
4307         {
4308             KaxChapterTimeEnd &end =*(KaxChapterTimeEnd*)l;
4309             chapters.i_end_time = uint64( end ) / I64C(1000);
4310
4311             msg_Dbg( &sys.demuxer, "|   |   |   |   + ChapterTimeEnd: %lld", chapters.i_end_time );
4312         }
4313         else if( MKV_IS_ID( l, KaxChapterDisplay ) )
4314         {
4315             EbmlMaster *cd = static_cast<EbmlMaster *>(l);
4316
4317             msg_Dbg( &sys.demuxer, "|   |   |   |   + ChapterDisplay" );
4318             for( j = 0; j < cd->ListSize(); j++ )
4319             {
4320                 EbmlElement *l= (*cd)[j];
4321
4322                 if( MKV_IS_ID( l, KaxChapterString ) )
4323                 {
4324                     int k;
4325
4326                     KaxChapterString &name =*(KaxChapterString*)l;
4327                     for (k = 0; k < i_level; k++)
4328                         chapters.psz_name += '+';
4329                     chapters.psz_name += ' ';
4330                     chapters.psz_name += UTF8ToStr( UTFstring( name ) );
4331                     chapters.b_user_display = true;
4332
4333                     msg_Dbg( &sys.demuxer, "|   |   |   |   |    + ChapterString '%s'", UTF8ToStr(UTFstring(name)) );
4334                 }
4335                 else if( MKV_IS_ID( l, KaxChapterLanguage ) )
4336                 {
4337                     KaxChapterLanguage &lang =*(KaxChapterLanguage*)l;
4338                     const char *psz = string( lang ).c_str();
4339
4340                     msg_Dbg( &sys.demuxer, "|   |   |   |   |    + ChapterLanguage '%s'", psz );
4341                 }
4342                 else if( MKV_IS_ID( l, KaxChapterCountry ) )
4343                 {
4344                     KaxChapterCountry &ct =*(KaxChapterCountry*)l;
4345                     const char *psz = string( ct ).c_str();
4346
4347                     msg_Dbg( &sys.demuxer, "|   |   |   |   |    + ChapterCountry '%s'", psz );
4348                 }
4349             }
4350         }
4351         else if( MKV_IS_ID( l, KaxChapterProcess ) )
4352         {
4353             msg_Dbg( &sys.demuxer, "|   |   |   |   + ChapterProcess" );
4354
4355             KaxChapterProcess *cp = static_cast<KaxChapterProcess *>(l);
4356             chapter_codec_cmds_c *p_ccodec = NULL;
4357
4358             for( j = 0; j < cp->ListSize(); j++ )
4359             {
4360                 EbmlElement *k= (*cp)[j];
4361
4362                 if( MKV_IS_ID( k, KaxChapterProcessCodecID ) )
4363                 {
4364                     KaxChapterProcessCodecID *p_codec_id = static_cast<KaxChapterProcessCodecID*>( k );
4365                     if ( uint32(*p_codec_id) == 0 )
4366                         p_ccodec = new matroska_script_codec_c( sys );
4367                     else if ( uint32(*p_codec_id) == 1 )
4368                         p_ccodec = new dvd_chapter_codec_c( sys );
4369                     break;
4370                 }
4371             }
4372
4373             if ( p_ccodec != NULL )
4374             {
4375                 for( j = 0; j < cp->ListSize(); j++ )
4376                 {
4377                     EbmlElement *k= (*cp)[j];
4378
4379                     if( MKV_IS_ID( k, KaxChapterProcessPrivate ) )
4380                     {
4381                         KaxChapterProcessPrivate * p_private = static_cast<KaxChapterProcessPrivate*>( k );
4382                         p_ccodec->SetPrivate( *p_private );
4383                     }
4384                     else if( MKV_IS_ID( k, KaxChapterProcessCommand ) )
4385                     {
4386                         p_ccodec->AddCommand( *static_cast<KaxChapterProcessCommand*>( k ) );
4387                     }
4388                 }
4389                 chapters.codecs.push_back( p_ccodec );
4390             }
4391         }
4392         else if( MKV_IS_ID( l, KaxChapterAtom ) )
4393         {
4394             chapter_item_c *new_sub_chapter = new chapter_item_c();
4395             ParseChapterAtom( i_level+1, static_cast<KaxChapterAtom *>(l), *new_sub_chapter );
4396             new_sub_chapter->psz_parent = &chapters;
4397             chapters.sub_chapters.push_back( new_sub_chapter );
4398         }
4399     }
4400 }
4401
4402 /*****************************************************************************
4403  * ParseChapters:
4404  *****************************************************************************/
4405 void matroska_segment_c::ParseChapters( KaxChapters *chapters )
4406 {
4407     EbmlElement *el;
4408     size_t i;
4409     int i_upper_level = 0;
4410     mtime_t i_dur;
4411
4412     /* Master elements */
4413     chapters->Read( es, chapters->Generic().Context, i_upper_level, el, true );
4414
4415     for( i = 0; i < chapters->ListSize(); i++ )
4416     {
4417         EbmlElement *l = (*chapters)[i];
4418
4419         if( MKV_IS_ID( l, KaxEditionEntry ) )
4420         {
4421             chapter_edition_c *p_edition = new chapter_edition_c();
4422             
4423             EbmlMaster *E = static_cast<EbmlMaster *>(l );
4424             size_t j;
4425             msg_Dbg( &sys.demuxer, "|   |   + EditionEntry" );
4426             for( j = 0; j < E->ListSize(); j++ )
4427             {
4428                 EbmlElement *l = (*E)[j];
4429
4430                 if( MKV_IS_ID( l, KaxChapterAtom ) )
4431                 {
4432                     chapter_item_c *new_sub_chapter = new chapter_item_c();
4433                     ParseChapterAtom( 0, static_cast<KaxChapterAtom *>(l), *new_sub_chapter );
4434                     p_edition->sub_chapters.push_back( new_sub_chapter );
4435                 }
4436                 else if( MKV_IS_ID( l, KaxEditionUID ) )
4437                 {
4438                     p_edition->i_uid = uint64(*static_cast<KaxEditionUID *>( l ));
4439                 }
4440                 else if( MKV_IS_ID( l, KaxEditionFlagOrdered ) )
4441                 {
4442                     p_edition->b_ordered = config_GetInt( &sys.demuxer, "mkv-use-ordered-chapters" ) ? (uint8(*static_cast<KaxEditionFlagOrdered *>( l )) != 0) : 0;
4443                 }
4444                 else if( MKV_IS_ID( l, KaxEditionFlagDefault ) )
4445                 {
4446                     if (uint8(*static_cast<KaxEditionFlagDefault *>( l )) != 0)
4447                         i_default_edition = stored_editions.size();
4448                 }
4449                 else
4450                 {
4451                     msg_Dbg( &sys.demuxer, "|   |   |   + Unknown (%s)", typeid(*l).name() );
4452                 }
4453             }
4454             stored_editions.push_back( p_edition );
4455         }
4456         else
4457         {
4458             msg_Dbg( &sys.demuxer, "|   |   + Unknown (%s)", typeid(*l).name() );
4459         }
4460     }
4461
4462     for( i = 0; i < stored_editions.size(); i++ )
4463     {
4464         stored_editions[i]->RefreshChapters( );
4465     }
4466     
4467     if ( stored_editions[i_default_edition]->b_ordered )
4468     {
4469         /* update the duration of the segment according to the sum of all sub chapters */
4470         i_dur = stored_editions[i_default_edition]->Duration() / I64C(1000);
4471         if (i_dur > 0)
4472             i_duration = i_dur;
4473     }
4474 }
4475
4476 void matroska_segment_c::ParseCluster( )
4477 {
4478     EbmlElement *el;
4479     EbmlMaster  *m;
4480     unsigned int i;
4481     int i_upper_level = 0;
4482
4483     /* Master elements */
4484     m = static_cast<EbmlMaster *>( cluster );
4485     m->Read( es, cluster->Generic().Context, i_upper_level, el, true );
4486
4487     for( i = 0; i < m->ListSize(); i++ )
4488     {
4489         EbmlElement *l = (*m)[i];
4490
4491         if( MKV_IS_ID( l, KaxClusterTimecode ) )
4492         {
4493             KaxClusterTimecode &ctc = *(KaxClusterTimecode*)l;
4494
4495             cluster->InitTimecode( uint64( ctc ), i_timescale );
4496             break;
4497         }
4498     }
4499
4500     i_start_time = cluster->GlobalTimecode() / 1000;
4501 }
4502
4503 /*****************************************************************************
4504  * InformationCreate:
4505  *****************************************************************************/
4506 void matroska_segment_c::InformationCreate( )
4507 {
4508     size_t      i_track;
4509
4510     sys.meta = vlc_meta_New();
4511
4512     if( psz_title )
4513     {
4514         vlc_meta_Add( sys.meta, VLC_META_TITLE, psz_title );
4515     }
4516     if( psz_date_utc )
4517     {
4518         vlc_meta_Add( sys.meta, VLC_META_DATE, psz_date_utc );
4519     }
4520     if( psz_segment_filename )
4521     {
4522         vlc_meta_Add( sys.meta, _("Segment filename"), psz_segment_filename );
4523     }
4524     if( psz_muxing_application )
4525     {
4526         vlc_meta_Add( sys.meta, _("Muxing application"), psz_muxing_application );
4527     }
4528     if( psz_writing_application )
4529     {
4530         vlc_meta_Add( sys.meta, _("Writing application"), psz_writing_application );
4531     }
4532
4533     for( i_track = 0; i_track < tracks.size(); i_track++ )
4534     {
4535         mkv_track_t *tk = tracks[i_track];
4536         vlc_meta_t *mtk = vlc_meta_New();
4537
4538         sys.meta->track = (vlc_meta_t**)realloc( sys.meta->track,
4539                                                     sizeof( vlc_meta_t * ) * ( sys.meta->i_track + 1 ) );
4540         sys.meta->track[sys.meta->i_track++] = mtk;
4541
4542         if( tk->fmt.psz_description )
4543         {
4544             vlc_meta_Add( sys.meta, VLC_META_DESCRIPTION, tk->fmt.psz_description );
4545         }
4546         if( tk->psz_codec_name )
4547         {
4548             vlc_meta_Add( sys.meta, VLC_META_CODEC_NAME, tk->psz_codec_name );
4549         }
4550         if( tk->psz_codec_settings )
4551         {
4552             vlc_meta_Add( sys.meta, VLC_META_SETTING, tk->psz_codec_settings );
4553         }
4554         if( tk->psz_codec_info_url )
4555         {
4556             vlc_meta_Add( sys.meta, VLC_META_CODEC_DESCRIPTION, tk->psz_codec_info_url );
4557         }
4558         if( tk->psz_codec_download_url )
4559         {
4560             vlc_meta_Add( sys.meta, VLC_META_URL, tk->psz_codec_download_url );
4561         }
4562     }
4563
4564     if( i_tags_position >= 0 )
4565     {
4566         vlc_bool_t b_seekable;
4567
4568         stream_Control( sys.demuxer.s, STREAM_CAN_FASTSEEK, &b_seekable );
4569         if( b_seekable )
4570         {
4571             LoadTags( );
4572         }
4573     }
4574 }
4575
4576
4577 /*****************************************************************************
4578  * Divers
4579  *****************************************************************************/
4580
4581 void matroska_segment_c::IndexAppendCluster( KaxCluster *cluster )
4582 {
4583 #define idx index[i_index]
4584     idx.i_track       = -1;
4585     idx.i_block_number= -1;
4586     idx.i_position    = cluster->GetElementPosition();
4587     idx.i_time        = -1;
4588     idx.b_key         = VLC_TRUE;
4589
4590     i_index++;
4591     if( i_index >= i_index_max )
4592     {
4593         i_index_max += 1024;
4594         index = (mkv_index_t*)realloc( index, sizeof( mkv_index_t ) * i_index_max );
4595     }
4596 #undef idx
4597 }
4598
4599 static char * UTF8ToStr( const UTFstring &u )
4600 {
4601     int     i_src;
4602     const wchar_t *src;
4603     char *dst, *p;
4604
4605     i_src = u.length();
4606     src   = u.c_str();
4607
4608     p = dst = (char*)malloc( i_src + 1);
4609     while( i_src > 0 )
4610     {
4611         if( *src < 255 )
4612         {
4613             *p++ = (char)*src;
4614         }
4615         else
4616         {
4617             *p++ = '?';
4618         }
4619         src++;
4620         i_src--;
4621     }
4622     *p++= '\0';
4623
4624     return dst;
4625 }
4626
4627 void chapter_edition_c::RefreshChapters( )
4628 {
4629     chapter_item_c::RefreshChapters( b_ordered, -1 );
4630     b_display_seekpoint = false;
4631 }
4632
4633 int64_t chapter_item_c::RefreshChapters( bool b_ordered, int64_t i_prev_user_time )
4634 {
4635     int64_t i_user_time = i_prev_user_time;
4636     
4637     // first the sub-chapters, and then ourself
4638     std::vector<chapter_item_c*>::iterator index = sub_chapters.begin();
4639     while ( index != sub_chapters.end() )
4640     {
4641         i_user_time = (*index)->RefreshChapters( b_ordered, i_user_time );
4642         index++;
4643     }
4644
4645     if ( b_ordered )
4646     {
4647         // the ordered chapters always start at zero
4648         if ( i_prev_user_time == -1 )
4649         {
4650             if ( i_user_time == -1 )
4651                 i_user_time = 0;
4652             i_prev_user_time = 0;
4653         }
4654
4655         i_user_start_time = i_prev_user_time;
4656         if ( i_end_time != -1 && i_user_time == i_prev_user_time )
4657         {
4658             i_user_end_time = i_user_start_time - i_start_time + i_end_time;
4659         }
4660         else
4661         {
4662             i_user_end_time = i_user_time;
4663         }
4664     }
4665     else
4666     {
4667         std::sort( sub_chapters.begin(), sub_chapters.end() );
4668         i_user_start_time = i_start_time;
4669         if ( i_end_time != -1 )
4670             i_user_end_time = i_end_time;
4671         else if ( i_user_time != -1 )
4672             i_user_end_time = i_user_time;
4673         else
4674             i_user_end_time = i_user_start_time;
4675     }
4676
4677     return i_user_end_time;
4678 }
4679
4680 mtime_t chapter_edition_c::Duration() const
4681 {
4682     mtime_t i_result = 0;
4683     
4684     if ( sub_chapters.size() )
4685     {
4686         std::vector<chapter_item_c*>::const_iterator index = sub_chapters.end();
4687         index--;
4688         i_result = (*index)->i_user_end_time;
4689     }
4690     
4691     return i_result;
4692 }
4693
4694 chapter_item_c *chapter_item_c::FindTimecode( mtime_t i_user_timecode )
4695 {
4696     chapter_item_c *psz_result = NULL;
4697
4698     if ( i_user_timecode >= i_user_start_time && 
4699         ( i_user_timecode < i_user_end_time || 
4700           ( i_user_start_time == i_user_end_time && i_user_timecode == i_user_end_time )))
4701     {
4702         std::vector<chapter_item_c*>::iterator index = sub_chapters.begin();
4703         while ( index != sub_chapters.end() && psz_result == NULL )
4704         {
4705             psz_result = (*index)->FindTimecode( i_user_timecode );
4706             index++;
4707         }
4708         
4709         if ( psz_result == NULL )
4710             psz_result = this;
4711     }
4712
4713     return psz_result;
4714 }
4715
4716 bool chapter_item_c::ParentOf( const chapter_item_c & item ) const
4717 {
4718     if ( &item == this )
4719         return true;
4720
4721     std::vector<chapter_item_c*>::const_iterator index = sub_chapters.begin();
4722     while ( index != sub_chapters.end() )
4723     {
4724         if ( (*index)->ParentOf( item ) )
4725             return true;
4726         index++;
4727     }
4728
4729     return false;
4730 }
4731
4732 void demux_sys_t::PreloadFamily( const matroska_segment_c & of_segment )
4733 {
4734     for (size_t i=0; i<opened_segments.size(); i++)
4735     {
4736         opened_segments[i]->PreloadFamily( of_segment );
4737     }
4738 }
4739 bool matroska_segment_c::PreloadFamily( const matroska_segment_c & of_segment )
4740 {
4741     if ( b_preloaded )
4742         return false;
4743
4744     for (size_t i=0; i<families.size(); i++)
4745     {
4746         for (size_t j=0; j<of_segment.families.size(); j++)
4747         {
4748             if ( families[i] == of_segment.families[j] )
4749                 return Preload( );
4750         }
4751     }
4752
4753     return false;
4754 }
4755
4756 // preload all the linked segments for all preloaded segments
4757 void demux_sys_t::PreloadLinked( matroska_segment_c *p_segment )
4758 {
4759     size_t i_preloaded, i, j;
4760     virtual_segment_c *p_seg;
4761
4762     p_current_segment = VirtualFromSegments( p_segment );
4763     
4764     used_segments.push_back( p_current_segment );
4765
4766     // create all the other virtual segments of the family
4767     do {
4768         i_preloaded = 0;
4769         for ( i=0; i< opened_segments.size(); i++ )
4770         {
4771             if ( opened_segments[i]->b_preloaded && !IsUsedSegment( *opened_segments[i] ) )
4772             {
4773                 p_seg = VirtualFromSegments( opened_segments[i] );
4774                 used_segments.push_back( p_seg );
4775                 i_preloaded++;
4776             }
4777         }
4778     } while ( i_preloaded ); // worst case: will stop when all segments are found as family related
4779
4780     // publish all editions of all usable segment
4781     for ( i=0; i< used_segments.size(); i++ )
4782     {
4783         p_seg = used_segments[i];
4784         if ( p_seg->p_editions != NULL )
4785         {
4786             std::string sz_name;
4787             input_title_t *p_title = vlc_input_title_New();
4788             p_seg->i_sys_title = i;
4789             int i_chapters;
4790
4791             // TODO use a name for each edition, let the TITLE deal with a codec name
4792             for ( j=0; j<p_seg->p_editions->size(); j++ )
4793             {
4794                 if ( p_title->psz_name == NULL )
4795                 {
4796                     sz_name = (*p_seg->p_editions)[j]->GetMainName();
4797                     if ( sz_name != "" )
4798                         p_title->psz_name = strdup( sz_name.c_str() );
4799                 }
4800
4801                 chapter_edition_c *p_edition = (*p_seg->p_editions)[j];
4802
4803                 i_chapters = 0;
4804                 p_edition->PublishChapters( *p_title, i_chapters, 0 );
4805             }
4806
4807             // create a name if there is none
4808             if ( p_title->psz_name == NULL )
4809             {
4810                 sz_name = N_("Segment ");
4811                 char psz_str[6];
4812                 sprintf( psz_str, "%d", i );
4813                 sz_name += psz_str;
4814                 p_title->psz_name = strdup( sz_name.c_str() );
4815             }
4816
4817             titles.push_back( *p_title );
4818         }
4819     }
4820
4821     // TODO decide which segment should be first used (VMG for DVD)
4822 }
4823
4824 bool demux_sys_t::IsUsedSegment( matroska_segment_c &segment ) const
4825 {
4826     for ( size_t i=0; i< used_segments.size(); i++ )
4827     {
4828         if ( used_segments[i]->FindUID( segment.segment_uid ) )
4829             return true;
4830     }
4831     return false;
4832 }
4833
4834 virtual_segment_c *demux_sys_t::VirtualFromSegments( matroska_segment_c *p_segment ) const
4835 {
4836     size_t i_preloaded, i;
4837
4838     virtual_segment_c *p_result = new virtual_segment_c( p_segment );
4839
4840     // fill our current virtual segment with all hard linked segments
4841     do {
4842         i_preloaded = 0;
4843         for ( i=0; i< opened_segments.size(); i++ )
4844         {
4845             i_preloaded += p_result->AddSegment( opened_segments[i] );
4846         }
4847     } while ( i_preloaded ); // worst case: will stop when all segments are found as linked
4848
4849     p_result->Sort( );
4850
4851     p_result->PreloadLinked( );
4852
4853     p_result->PrepareChapters( );
4854
4855     return p_result;
4856 }
4857
4858 bool demux_sys_t::PreparePlayback( virtual_segment_c *p_new_segment )
4859 {
4860     if ( p_new_segment != NULL && p_new_segment != p_current_segment )
4861     {
4862         if ( p_current_segment != NULL && p_current_segment->Segment() != NULL )
4863             p_current_segment->Segment()->UnSelect();
4864
4865         p_current_segment = p_new_segment;
4866         i_current_title = p_new_segment->i_sys_title;
4867     }
4868
4869     p_current_segment->LoadCues();
4870     f_duration = p_current_segment->Duration();
4871
4872     /* add information */
4873     p_current_segment->Segment()->InformationCreate( );
4874
4875     p_current_segment->Segment()->Select( 0 );
4876
4877     return true;
4878 }
4879
4880 bool matroska_segment_c::CompareSegmentUIDs( const matroska_segment_c * p_item_a, const matroska_segment_c * p_item_b )
4881 {
4882     EbmlBinary * p_itema = (EbmlBinary *)(&p_item_a->segment_uid);
4883     if ( *p_itema == p_item_b->prev_segment_uid )
4884         return true;
4885
4886     p_itema = (EbmlBinary *)(&p_item_a->next_segment_uid);
4887     if ( *p_itema == p_item_b->segment_uid )
4888         return true;
4889
4890     if ( *p_itema == p_item_b->prev_segment_uid )
4891         return true;
4892
4893     return false;
4894 }
4895
4896 bool matroska_segment_c::Preload( )
4897 {
4898     if ( b_preloaded )
4899         return false;
4900
4901     EbmlElement *el = NULL;
4902
4903     ep->Reset( &sys.demuxer );
4904
4905     while( ( el = ep->Get() ) != NULL )
4906     {
4907         if( MKV_IS_ID( el, KaxInfo ) )
4908         {
4909             ParseInfo( static_cast<KaxInfo*>( el ) );
4910         }
4911         else if( MKV_IS_ID( el, KaxTracks ) )
4912         {
4913             ParseTracks( static_cast<KaxTracks*>( el ) );
4914         }
4915         else if( MKV_IS_ID( el, KaxSeekHead ) )
4916         {
4917             ParseSeekHead( static_cast<KaxSeekHead*>( el ) );
4918         }
4919         else if( MKV_IS_ID( el, KaxCues ) )
4920         {
4921             msg_Dbg( &sys.demuxer, "|   + Cues" );
4922         }
4923         else if( MKV_IS_ID( el, KaxCluster ) )
4924         {
4925             msg_Dbg( &sys.demuxer, "|   + Cluster" );
4926
4927             cluster = (KaxCluster*)el;
4928
4929             i_start_pos = cluster->GetElementPosition();
4930             ParseCluster( );
4931
4932             ep->Down();
4933             /* stop parsing the stream */
4934             break;
4935         }
4936         else if( MKV_IS_ID( el, KaxAttachments ) )
4937         {
4938             msg_Dbg( &sys.demuxer, "|   + Attachments FIXME (but probably never supported)" );
4939         }
4940         else if( MKV_IS_ID( el, KaxChapters ) )
4941         {
4942             msg_Dbg( &sys.demuxer, "|   + Chapters" );
4943             ParseChapters( static_cast<KaxChapters*>( el ) );
4944         }
4945         else if( MKV_IS_ID( el, KaxTag ) )
4946         {
4947             msg_Dbg( &sys.demuxer, "|   + Tags FIXME TODO" );
4948         }
4949         else
4950         {
4951             msg_Dbg( &sys.demuxer, "|   + Unknown (%s)", typeid(*el).name() );
4952         }
4953     }
4954
4955     b_preloaded = true;
4956
4957     return true;
4958 }
4959
4960 matroska_segment_c *demux_sys_t::FindSegment( const EbmlBinary & uid ) const
4961 {
4962     for (size_t i=0; i<opened_segments.size(); i++)
4963     {
4964         if ( opened_segments[i]->segment_uid == uid )
4965             return opened_segments[i];
4966     }
4967     return NULL;
4968 }
4969
4970 chapter_item_c *demux_sys_t::BrowseCodecPrivate( unsigned int codec_id, 
4971                                         bool (*match)(const chapter_codec_cmds_c &data, const void *p_cookie, size_t i_cookie_size ), 
4972                                         const void *p_cookie, 
4973                                         size_t i_cookie_size, 
4974                                         virtual_segment_c * &p_segment_found )
4975 {
4976     chapter_item_c *p_result = NULL;
4977     for (size_t i=0; i<used_segments.size(); i++)
4978     {
4979         p_result = used_segments[i]->BrowseCodecPrivate( codec_id, match, p_cookie, i_cookie_size );
4980         if ( p_result != NULL )
4981         {
4982             p_segment_found = used_segments[i];
4983             break;
4984         }
4985     }
4986     return p_result;
4987 }
4988
4989 chapter_item_c *demux_sys_t::FindChapter( int64_t i_find_uid, virtual_segment_c * & p_segment_found )
4990 {
4991     chapter_item_c *p_result = NULL;
4992     for (size_t i=0; i<used_segments.size(); i++)
4993     {
4994         p_result = used_segments[i]->FindChapter( i_find_uid );
4995         if ( p_result != NULL )
4996         {
4997             p_segment_found = used_segments[i];
4998             break;
4999         }
5000     }
5001     return p_result;
5002 }
5003
5004 void virtual_segment_c::Sort()
5005 {
5006     // keep the current segment index
5007     matroska_segment_c *p_segment = linked_segments[i_current_segment];
5008
5009     std::sort( linked_segments.begin(), linked_segments.end(), matroska_segment_c::CompareSegmentUIDs );
5010
5011     for ( i_current_segment=0; i_current_segment<linked_segments.size(); i_current_segment++)
5012         if ( linked_segments[i_current_segment] == p_segment )
5013             break;
5014 }
5015
5016 size_t virtual_segment_c::AddSegment( matroska_segment_c *p_segment )
5017 {
5018     size_t i;
5019     // check if it's not already in here
5020     for ( i=0; i<linked_segments.size(); i++ )
5021     {
5022         if ( p_segment->segment_uid == linked_segments[i]->segment_uid )
5023             return 0;
5024     }
5025
5026     // find possible mates
5027     for ( i=0; i<linked_uids.size(); i++ )
5028     {
5029         if (   p_segment->segment_uid == linked_uids[i] 
5030             || p_segment->prev_segment_uid == linked_uids[i] 
5031             || p_segment->next_segment_uid == linked_uids[i] )
5032         {
5033             linked_segments.push_back( p_segment );
5034
5035             AppendUID( p_segment->prev_segment_uid );
5036             AppendUID( p_segment->next_segment_uid );
5037
5038             return 1;
5039         }
5040     }
5041     return 0;
5042 }
5043
5044 void virtual_segment_c::PreloadLinked( )
5045 {
5046     for ( size_t i=0; i<linked_segments.size(); i++ )
5047     {
5048         linked_segments[i]->Preload( );
5049     }
5050     i_current_edition = linked_segments[0]->i_default_edition;
5051 }
5052
5053 mtime_t virtual_segment_c::Duration() const
5054 {
5055     mtime_t i_duration;
5056     if ( linked_segments.size() == 0 )
5057         i_duration = 0;
5058     else {
5059         matroska_segment_c *p_last_segment = linked_segments[linked_segments.size()-1];
5060 //        p_last_segment->ParseCluster( );
5061
5062         i_duration = p_last_segment->i_start_time / 1000 + p_last_segment->i_duration;
5063     }
5064     return i_duration;
5065 }
5066
5067 void virtual_segment_c::LoadCues( )
5068 {
5069     for ( size_t i=0; i<linked_segments.size(); i++ )
5070     {
5071         linked_segments[i]->LoadCues();
5072     }
5073 }
5074
5075 void virtual_segment_c::AppendUID( const EbmlBinary & UID )
5076 {
5077     if ( UID.GetBuffer() == NULL )
5078         return;
5079
5080     for (size_t i=0; i<linked_uids.size(); i++)
5081     {
5082         if ( UID == linked_uids[i] )
5083             return;
5084     }
5085     linked_uids.push_back( *(KaxSegmentUID*)(&UID) );
5086 }
5087
5088 void matroska_segment_c::Seek( mtime_t i_date, mtime_t i_time_offset )
5089 {
5090     KaxBlock    *block;
5091     int         i_track_skipping;
5092     int64_t     i_block_duration;
5093     int64_t     i_block_ref1;
5094     int64_t     i_block_ref2;
5095     size_t      i_track;
5096     int64_t     i_seek_position = i_start_pos;
5097     int64_t     i_seek_time = i_start_time;
5098
5099     if ( i_index > 0 )
5100     {
5101         int i_idx = 0;
5102
5103         for( ; i_idx < i_index; i_idx++ )
5104         {
5105             if( index[i_idx].i_time + i_time_offset > i_date )
5106             {
5107                 break;
5108             }
5109         }
5110
5111         if( i_idx > 0 )
5112         {
5113             i_idx--;
5114         }
5115
5116         i_seek_position = index[i_idx].i_position;
5117         i_seek_time = index[i_idx].i_time;
5118     }
5119
5120     msg_Dbg( &sys.demuxer, "seek got "I64Fd" (%d%%)",
5121                 i_seek_time, (int)( 100 * i_seek_position / stream_Size( sys.demuxer.s ) ) );
5122
5123     es.I_O().setFilePointer( i_seek_position, seek_beginning );
5124
5125     delete ep;
5126     ep = new EbmlParser( &es, segment, &sys.demuxer );
5127     cluster = NULL;
5128
5129     sys.i_start_pts = i_date;
5130
5131     es_out_Control( sys.demuxer.out, ES_OUT_RESET_PCR );
5132
5133     /* now parse until key frame */
5134     i_track_skipping = 0;
5135     for( i_track = 0; i_track < tracks.size(); i_track++ )
5136     {
5137         if( tracks[i_track]->fmt.i_cat == VIDEO_ES )
5138         {
5139             tracks[i_track]->b_search_keyframe = VLC_TRUE;
5140             i_track_skipping++;
5141         }
5142         es_out_Control( sys.demuxer.out, ES_OUT_SET_NEXT_DISPLAY_TIME, tracks[i_track]->p_es, i_date );
5143     }
5144
5145
5146     while( i_track_skipping > 0 )
5147     {
5148         if( BlockGet( &block, &i_block_ref1, &i_block_ref2, &i_block_duration ) )
5149         {
5150             msg_Warn( &sys.demuxer, "cannot get block EOF?" );
5151
5152             return;
5153         }
5154
5155         for( i_track = 0; i_track < tracks.size(); i_track++ )
5156         {
5157             if( tracks[i_track]->i_number == block->TrackNum() )
5158             {
5159                 break;
5160             }
5161         }
5162
5163         sys.i_pts = sys.i_chapter_time + block->GlobalTimecode() / (mtime_t) 1000;
5164
5165         if( i_track < tracks.size() )
5166         {
5167             if( sys.i_pts >= sys.i_start_pts )
5168             {
5169                 BlockDecode( &sys.demuxer, block, sys.i_pts, 0 );
5170                 i_track_skipping = 0;
5171             }
5172             else if( tracks[i_track]->fmt.i_cat == VIDEO_ES )
5173             {
5174                 if( i_block_ref1 == -1 && tracks[i_track]->b_search_keyframe )
5175                 {
5176                     tracks[i_track]->b_search_keyframe = VLC_FALSE;
5177                     i_track_skipping--;
5178                 }
5179                 if( !tracks[i_track]->b_search_keyframe )
5180                 {
5181                     BlockDecode( &sys.demuxer, block, sys.i_pts, 0 );
5182                 }
5183             } 
5184         }
5185
5186         delete block;
5187     }
5188 }
5189
5190 void virtual_segment_c::Seek( demux_t & demuxer, mtime_t i_date, mtime_t i_time_offset, chapter_item_c *psz_chapter )
5191 {
5192     demux_sys_t *p_sys = demuxer.p_sys;
5193     size_t i;
5194
5195     // find the actual time for an ordered edition
5196     if ( psz_chapter == NULL )
5197     {
5198         if ( Edition() && Edition()->b_ordered )
5199         {
5200             /* 1st, we need to know in which chapter we are */
5201             psz_chapter = (*p_editions)[i_current_edition]->FindTimecode( i_date );
5202         }
5203     }
5204
5205     if ( psz_chapter != NULL )
5206     {
5207         psz_current_chapter = psz_chapter;
5208         p_sys->i_chapter_time = i_time_offset = psz_chapter->i_user_start_time - psz_chapter->i_start_time;
5209         if ( psz_chapter->i_seekpoint_num > 0 )
5210         {
5211             demuxer.info.i_update |= INPUT_UPDATE_TITLE | INPUT_UPDATE_SEEKPOINT;
5212             demuxer.info.i_title = p_sys->i_current_title = i_sys_title;
5213             demuxer.info.i_seekpoint = psz_chapter->i_seekpoint_num - 1;
5214         }
5215     }
5216
5217     // find the best matching segment
5218     for ( i=0; i<linked_segments.size(); i++ )
5219     {
5220         if ( i_date < linked_segments[i]->i_start_time )
5221             break;
5222     }
5223
5224     if ( i > 0 )
5225         i--;
5226
5227     if ( i_current_segment != i  )
5228     {
5229         linked_segments[i_current_segment]->UnSelect();
5230         linked_segments[i]->Select( i_date );
5231         i_current_segment = i;
5232     }
5233
5234     linked_segments[i]->Seek( i_date, i_time_offset );
5235 }
5236
5237 void chapter_codec_cmds_c::AddCommand( const KaxChapterProcessCommand & command )
5238 {
5239     size_t i;
5240
5241     uint32 codec_time = uint32(-1);
5242     for( i = 0; i < command.ListSize(); i++ )
5243     {
5244         const EbmlElement *k = command[i];
5245
5246         if( MKV_IS_ID( k, KaxChapterProcessTime ) )
5247         {
5248             codec_time = uint32( *static_cast<const KaxChapterProcessTime*>( k ) );
5249             break;
5250         }
5251     }
5252
5253     for( i = 0; i < command.ListSize(); i++ )
5254     {
5255         const EbmlElement *k = command[i];
5256
5257         if( MKV_IS_ID( k, KaxChapterProcessData ) )
5258         {
5259             KaxChapterProcessData *p_data =  new KaxChapterProcessData( *static_cast<const KaxChapterProcessData*>( k ) );
5260             switch ( codec_time )
5261             {
5262             case 0:
5263                 during_cmds.push_back( *p_data );
5264                 break;
5265             case 1:
5266                 enter_cmds.push_back( *p_data );
5267                 break;
5268             case 2:
5269                 leave_cmds.push_back( *p_data );
5270                 break;
5271             default:
5272                 delete p_data;
5273             }
5274         }
5275     }
5276 }
5277
5278 bool chapter_item_c::Enter( bool b_do_subs )
5279 {
5280     bool f_result = false;
5281     std::vector<chapter_codec_cmds_c*>::iterator index = codecs.begin();
5282     while ( index != codecs.end() )
5283     {
5284         f_result |= (*index)->Enter();
5285         index++;
5286     }
5287
5288     if ( b_do_subs )
5289     {
5290         // sub chapters
5291         std::vector<chapter_item_c*>::iterator index_ = sub_chapters.begin();
5292         while ( index_ != sub_chapters.end() )
5293         {
5294             f_result |= (*index_)->Enter( true );
5295             index_++;
5296         }
5297     }
5298     return f_result;
5299 }
5300
5301 bool chapter_item_c::Leave( bool b_do_subs )
5302 {
5303     bool f_result = false;
5304     b_is_leaving = true;
5305     std::vector<chapter_codec_cmds_c*>::iterator index = codecs.begin();
5306     while ( index != codecs.end() )
5307     {
5308         f_result |= (*index)->Leave();
5309         index++;
5310     }
5311
5312     if ( b_do_subs )
5313     {
5314         // sub chapters
5315         std::vector<chapter_item_c*>::iterator index_ = sub_chapters.begin();
5316         while ( index_ != sub_chapters.end() )
5317         {
5318             f_result |= (*index_)->Leave( true );
5319             index_++;
5320         }
5321     }
5322     b_is_leaving = false;
5323     return f_result;
5324 }
5325
5326 bool chapter_item_c::EnterAndLeave( chapter_item_c *p_item )
5327 {
5328     chapter_item_c *p_common_parent = p_item;
5329
5330     // leave, up to a common parent
5331     while ( p_common_parent != NULL && !p_common_parent->ParentOf( *this ) )
5332     {
5333         if ( !p_common_parent->b_is_leaving && p_common_parent->Leave( false ) )
5334             return true;
5335         p_common_parent = p_common_parent->psz_parent;
5336     }
5337
5338     // enter from the parent to <this>
5339     if ( p_common_parent != NULL )
5340     {
5341         do
5342         {
5343             if ( p_common_parent == this )
5344                 return Enter( true );
5345
5346             for ( size_t i = 0; i<p_common_parent->sub_chapters.size(); i++ )
5347             {
5348                 if ( p_common_parent->sub_chapters[i]->ParentOf( *this ) )
5349                 {
5350                     p_common_parent = p_common_parent->sub_chapters[i];
5351                     if ( p_common_parent != this )
5352                         if ( p_common_parent->Enter( false ) )
5353                             return true;
5354
5355                     break;
5356                 }
5357             }
5358         } while ( 1 );
5359     }
5360
5361     return Enter( true );
5362 }
5363
5364 bool dvd_chapter_codec_c::Enter()
5365 {
5366     bool f_result = false;
5367     std::vector<KaxChapterProcessData>::iterator index = enter_cmds.begin();
5368     while ( index != enter_cmds.end() )
5369     {
5370         if ( (*index).GetSize() )
5371         {
5372             binary *p_data = (*index).GetBuffer();
5373             size_t i_size = *p_data++;
5374             // avoid reading too much from the buffer
5375             i_size = min( i_size, ((*index).GetSize() - 1) >> 3 );
5376             for ( ; i_size > 0; i_size--, p_data += 8 )
5377             {
5378                 msg_Dbg( &sys.demuxer, "Matroska DVD enter command" );
5379                 f_result |= sys.dvd_interpretor.Interpret( p_data );
5380             }
5381         }
5382         index++;
5383     }
5384     return f_result;
5385 }
5386
5387 bool dvd_chapter_codec_c::Leave()
5388 {
5389     bool f_result = false;
5390     std::vector<KaxChapterProcessData>::iterator index = leave_cmds.begin();
5391     while ( index != leave_cmds.end() )
5392     {
5393         if ( (*index).GetSize() )
5394         {
5395             binary *p_data = (*index).GetBuffer();
5396             size_t i_size = *p_data++;
5397             // avoid reading too much from the buffer
5398             i_size = min( i_size, ((*index).GetSize() - 1) >> 3 );
5399             for ( ; i_size > 0; i_size--, p_data += 8 )
5400             {
5401                 msg_Dbg( &sys.demuxer, "Matroska DVD leave command" );
5402                 f_result |= sys.dvd_interpretor.Interpret( p_data );
5403             }
5404         }
5405         index++;
5406     }
5407     return f_result;
5408 }
5409
5410 // see http://www.dvd-replica.com/DVD/vmcmdset.php for a description of DVD commands
5411 bool dvd_command_interpretor_c::Interpret( const binary * p_command, size_t i_size )
5412 {
5413     if ( i_size != 8 )
5414         return false;
5415
5416     virtual_segment_c *p_segment;
5417     chapter_item_c *p_chapter;
5418     bool f_result = false;
5419     uint16 i_command = ( p_command[0] << 8 ) + p_command[1];
5420
5421     // handle register tests if there are some
5422     if ( (i_command & 0xF0) != 0 )
5423     {
5424         bool b_test_positive = (i_command & CMD_DVD_IF_NOT) == 0;
5425         bool b_test_value    = (i_command & CMD_DVD_TEST_VALUE) != 0;
5426         uint8 i_test = i_command & 0x70;
5427         uint16 i_value;
5428
5429         if ( b_test_value )
5430             i_value = ( p_command[4] << 8 ) + p_command[5];
5431         else
5432             i_value = GetPRM( p_command[7] );
5433
5434         switch ( i_test )
5435         {
5436         case CMD_DVD_IF_GPREG_EQUAL:
5437             // if equals
5438             msg_Dbg( &sys.demuxer, "IF %s EQUALS %s", GetRegTypeName( false, p_command[3] ).c_str(), GetRegTypeName( b_test_value, i_value ).c_str() );
5439             if (!( GetPRM( p_command[3] ) == i_value ))
5440             {
5441                 b_test_positive = !b_test_positive;
5442             }
5443             break;
5444         case CMD_DVD_IF_GPREG_INF:
5445             // if inferior
5446             msg_Dbg( &sys.demuxer, "IF %s < %s", GetRegTypeName( false, p_command[3] ).c_str(), GetRegTypeName( b_test_value, i_value ).c_str() );
5447             if (!( GetPRM( p_command[3] ) < i_value ))
5448             {
5449                 b_test_positive = !b_test_positive;
5450             }
5451             break;
5452         case CMD_DVD_IF_GPREG_AND:
5453             // if logical and
5454             msg_Dbg( &sys.demuxer, "IF %s & %s", GetRegTypeName( false, p_command[3] ).c_str(), GetRegTypeName( b_test_value, i_value ).c_str() );
5455             if (!( GetPRM( p_command[3] ) & i_value ))
5456             {
5457                 b_test_positive = !b_test_positive;
5458             }
5459             break;
5460         case CMD_DVD_IF_GPREG_SUP_EQUAL:
5461             // if superior or equal
5462             msg_Dbg( &sys.demuxer, "IF %s >= %s", GetRegTypeName( false, p_command[3] ).c_str(), GetRegTypeName( b_test_value, i_value ).c_str() );
5463             if (!( GetPRM( p_command[3] ) >= i_value ))
5464             {
5465                 b_test_positive = !b_test_positive;
5466             }
5467             break;
5468         }
5469
5470         if ( !b_test_positive )
5471             return false;
5472     }
5473     
5474     // strip the test command
5475     i_command &= 0xFF0F;
5476     
5477     switch ( i_command )
5478     {
5479     case CMD_DVD_NOP:
5480     case CMD_DVD_NOP2:
5481         {
5482             msg_Dbg( &sys.demuxer, "NOP" );
5483             break;
5484         }
5485     case CMD_DVD_BREAK:
5486         {
5487             msg_Dbg( &sys.demuxer, "Break" );
5488             // TODO
5489             break;
5490         }
5491     case CMD_DVD_JUMP_TT:
5492         {
5493             uint8 i_title = p_command[5];
5494             msg_Dbg( &sys.demuxer, "JumpTT %d", i_title );
5495
5496             // find in the ChapProcessPrivate matching this Title level
5497             p_chapter = sys.BrowseCodecPrivate( 1, MatchTitleNumber, &i_title, sizeof(i_title), p_segment );
5498             if ( p_chapter != NULL )
5499             {
5500                 // if the segment is not part of the current segment, select the new one
5501                 if ( p_segment != sys.p_current_segment )
5502                 {
5503                     sys.PreparePlayback( p_segment );
5504                 }
5505     
5506                 // jump to the location in the found segment
5507                 p_segment->Seek( sys.demuxer, p_chapter->i_user_start_time, -1, NULL );
5508                 p_chapter->Enter( true );
5509                 
5510                 f_result = true;
5511             }
5512
5513             break;
5514         }
5515     case CMD_DVD_CALLSS_VTSM1:
5516         {
5517             msg_Dbg( &sys.demuxer, "CallSS VTSM" );
5518             switch( (p_command[6] & 0xC0) >> 6 ) {
5519                 case 0:
5520                     switch ( p_command[5] )
5521                     {
5522                     case 0x00:
5523                         msg_Dbg( &sys.demuxer, "CallSS PGC (rsm_cell %x)", p_command[5]);
5524                         break;
5525                     case 0x82:
5526                         msg_Dbg( &sys.demuxer, "CallSS Title Entry (rsm_cell %x)", p_command[5]);
5527                         break;
5528                     case 0x83:
5529                         msg_Dbg( &sys.demuxer, "CallSS Root Menu (rsm_cell %x)", p_command[5]);
5530                         break;
5531                     case 0x84:
5532                         msg_Dbg( &sys.demuxer, "CallSS Subpicture Menu (rsm_cell %x)", p_command[5]);
5533                         break;
5534                     case 0x85:
5535                         msg_Dbg( &sys.demuxer, "CallSS Audio Menu (rsm_cell %x)", p_command[5]);
5536                         break;
5537                     case 0x86:
5538                         msg_Dbg( &sys.demuxer, "CallSS Angle Menu (rsm_cell %x)", p_command[5]);
5539                         break;
5540                     case 0x87:
5541                         msg_Dbg( &sys.demuxer, "CallSS Chapter Menu (rsm_cell %x)", p_command[5]);
5542                         break;
5543                     default:
5544                         msg_Dbg( &sys.demuxer, "CallSS <unknown> (rsm_cell %x)", p_command[5]);
5545                         break;
5546                     }
5547                     p_chapter = sys.BrowseCodecPrivate( 1, MatchPgcType, &p_command[5], 1, p_segment );
5548                     if ( p_chapter != NULL )
5549                     {
5550                         // if the segment is not part of the current segment, select the new one
5551                         if ( p_segment != sys.p_current_segment )
5552                         {
5553                             sys.PreparePlayback( p_segment );
5554                         }
5555             
5556                         p_chapter->Enter( true );
5557                         
5558                         // jump to the location in the found segment
5559                         p_segment->Seek( sys.demuxer, p_chapter->i_user_start_time, -1, p_chapter );
5560                         f_result = true;
5561                     }
5562                 break;
5563                 case 1:
5564                     msg_Dbg( &sys.demuxer, "CallSS VMGM (menu %d, rsm_cell %x)", p_command[6] & 0x0F, p_command[5]);
5565                 break;
5566                 case 2:
5567                     msg_Dbg( &sys.demuxer, "CallSS VTSM (menu %d, rsm_cell %x)", p_command[6] & 0x0F, p_command[5]);
5568                 break;
5569                 case 3:
5570                     msg_Dbg( &sys.demuxer, "CallSS VMGM (pgc %d, rsm_cell %x)", (p_command[3] << 8) + p_command[4], p_command[5]);
5571                 break;
5572             }
5573             break;
5574         }
5575     case CMD_DVD_JUMPVTS_PTT:
5576         {
5577             uint8 i_title = p_command[5];
5578             uint8 i_ptt = p_command[3];
5579
5580             msg_Dbg( &sys.demuxer, "JumpVTS Title (%d) PTT (%d)", i_title, i_ptt);
5581
5582             // find the current VTS content segment
5583             p_chapter = sys.p_current_segment->BrowseCodecPrivate( 1, MatchIsDomain, NULL, 0 );
5584             if ( p_chapter != NULL )
5585             {
5586                 int16 i_curr_title = p_chapter->GetTitleNumber( );
5587                 if ( i_curr_title > 0 )
5588                 {
5589                     p_chapter = sys.BrowseCodecPrivate( 1, MatchVTSNumber, &i_curr_title, sizeof(i_curr_title), p_segment );
5590
5591                     if ( p_chapter != NULL )
5592                     {
5593                         // find the title in the VTS
5594                         p_chapter = p_chapter->BrowseCodecPrivate( 1, MatchTitleNumber, &i_title, sizeof(i_title) );
5595                         if ( p_chapter != NULL )
5596                         {
5597                             // find the chapter in the title
5598                             p_chapter = p_chapter->BrowseCodecPrivate( 1, MatchChapterNumber, &i_ptt, sizeof(i_ptt) );
5599                             if ( p_chapter != NULL )
5600                             {
5601                                 // if the segment is not part of the current segment, select the new one
5602                                 if ( p_segment != sys.p_current_segment )
5603                                 {
5604                                     sys.PreparePlayback( p_segment );
5605                                 }
5606                     
5607                                 p_chapter->Enter( true );
5608                                 
5609                                 // jump to the location in the found segment
5610                                 p_segment->Seek( sys.demuxer, p_chapter->i_user_start_time, -1, p_chapter );
5611                                 f_result = true;
5612                             }
5613                         }
5614                     else
5615                         msg_Dbg( &sys.demuxer, "Title (%d) does not exist in this VTS", i_title );
5616                     }
5617                     else
5618                         msg_Dbg( &sys.demuxer, "DVD Domain VTS (%d) not found", i_curr_title );
5619                 }
5620                 else
5621                     msg_Dbg( &sys.demuxer, "JumpVTS_PTT command found but not in a VTS(M)");
5622             }
5623             else
5624                 msg_Dbg( &sys.demuxer, "JumpVTS_PTT command but the DVD domain wasn't found");
5625             break;
5626         }
5627     case CMD_DVD_SET_GPRMMD:
5628         {
5629             msg_Dbg( &sys.demuxer, "Set GPRMMD [%d]=%d", (p_command[4] << 8) + p_command[5], (p_command[2] << 8) + p_command[3]);
5630             
5631             if ( !SetGPRM( (p_command[4] << 8) + p_command[5], (p_command[2] << 8) + p_command[3] ) )
5632                 msg_Dbg( &sys.demuxer, "Set GPRMMD failed" );
5633             break;
5634         }
5635     case CMD_DVD_LINKPGCN:
5636         {
5637             uint16 i_pgcn = (p_command[6] << 8) + p_command[7];
5638             
5639             msg_Dbg( &sys.demuxer, "Link PGCN(%d)", i_pgcn );
5640             p_chapter = sys.p_current_segment->BrowseCodecPrivate( 1, MatchPgcNumber, &i_pgcn, 2 );
5641             if ( p_chapter != NULL )
5642             {
5643                 p_chapter->Enter( true );
5644                 
5645                 // jump to the location in the found segment
5646                 sys.p_current_segment->Seek( sys.demuxer, p_chapter->i_user_start_time, -1, p_chapter );
5647                 f_result = true;
5648             }
5649             break;
5650         }
5651     case CMD_DVD_LINKCN:
5652         {
5653             uint8 i_cn = p_command[7];
5654             
5655             p_chapter = sys.p_current_segment->CurrentChapter();
5656
5657             msg_Dbg( &sys.demuxer, "LinkCN (cell %d)", i_cn );
5658             p_chapter = p_chapter->BrowseCodecPrivate( 1, MatchCellNumber, &i_cn, 1 );
5659             if ( p_chapter != NULL )
5660             {
5661                 p_chapter->Enter( true );
5662                 
5663                 // jump to the location in the found segment
5664                 sys.p_current_segment->Seek( sys.demuxer, p_chapter->i_user_start_time, -1, p_chapter );
5665                 f_result = true;
5666             }
5667             break;
5668         }
5669     case CMD_DVD_GOTO_LINE:
5670         {
5671             msg_Dbg( &sys.demuxer, "GotoLine (%d)", (p_command[6] << 8) + p_command[7] );
5672             // TODO
5673             break;
5674         }
5675     default:
5676         {
5677             msg_Dbg( &sys.demuxer, "unsupported command : %02X %02X %02X %02X %02X %02X %02X %02X"
5678                      ,p_command[0]
5679                      ,p_command[1]
5680                      ,p_command[2]
5681                      ,p_command[3]
5682                      ,p_command[4]
5683                      ,p_command[5]
5684                      ,p_command[6]
5685                      ,p_command[7]);
5686             break;
5687         }
5688     }
5689
5690     return f_result;
5691 }
5692
5693 bool dvd_command_interpretor_c::MatchIsDomain( const chapter_codec_cmds_c &data, const void *p_cookie, size_t i_cookie_size )
5694 {
5695     return ( data.m_private_data.GetBuffer()[0] == MATROSKA_DVD_LEVEL_SS );
5696 }
5697
5698 bool dvd_command_interpretor_c::MatchVTSNumber( const chapter_codec_cmds_c &data, const void *p_cookie, size_t i_cookie_size )
5699 {
5700     if ( i_cookie_size != 2 || data.m_private_data.GetSize() < 4 )
5701         return false;
5702     
5703     if ( data.m_private_data.GetBuffer()[0] != MATROSKA_DVD_LEVEL_SS || data.m_private_data.GetBuffer()[1] != 0x80 )
5704         return false;
5705
5706     uint16 i_gtitle = (data.m_private_data.GetBuffer()[2] << 8 ) + data.m_private_data.GetBuffer()[3];
5707     uint16 i_title = *(uint16*)p_cookie;
5708
5709     return (i_gtitle == i_title);
5710 }
5711
5712 bool dvd_command_interpretor_c::MatchTitleNumber( const chapter_codec_cmds_c &data, const void *p_cookie, size_t i_cookie_size )
5713 {
5714     if ( i_cookie_size != 1 || data.m_private_data.GetSize() < 4 )
5715         return false;
5716     
5717     if ( data.m_private_data.GetBuffer()[0] != MATROSKA_DVD_LEVEL_TT )
5718         return false;
5719
5720     uint16 i_gtitle = (data.m_private_data.GetBuffer()[1] << 8 ) + data.m_private_data.GetBuffer()[2];
5721     uint8 i_title = *(uint8*)p_cookie;
5722
5723     return (i_gtitle == i_title);
5724 }
5725
5726 bool dvd_command_interpretor_c::MatchPgcType( const chapter_codec_cmds_c &data, const void *p_cookie, size_t i_cookie_size )
5727 {
5728     if ( i_cookie_size != 1 || data.m_private_data.GetSize() < 8 )
5729         return false;
5730     
5731     if ( data.m_private_data.GetBuffer()[0] != MATROSKA_DVD_LEVEL_PGC )
5732         return false;
5733
5734     uint8 i_pgc_type = data.m_private_data.GetBuffer()[3];
5735     uint8 i_pgc = *(uint8*)p_cookie;
5736
5737     return (i_pgc_type == i_pgc);
5738 }
5739
5740 bool dvd_command_interpretor_c::MatchPgcNumber( const chapter_codec_cmds_c &data, const void *p_cookie, size_t i_cookie_size )
5741 {
5742     if ( i_cookie_size != 2 || data.m_private_data.GetSize() < 8 )
5743         return false;
5744     
5745     if ( data.m_private_data.GetBuffer()[0] != MATROSKA_DVD_LEVEL_PGC )
5746         return false;
5747
5748     uint16 *i_pgc_n = (uint16 *)p_cookie;
5749     uint16 i_pgc_num = (data.m_private_data.GetBuffer()[1] << 8) + data.m_private_data.GetBuffer()[2];
5750
5751     return (i_pgc_num == *i_pgc_n);
5752 }
5753
5754 bool dvd_command_interpretor_c::MatchChapterNumber( const chapter_codec_cmds_c &data, const void *p_cookie, size_t i_cookie_size )
5755 {
5756     if ( i_cookie_size != 1 || data.m_private_data.GetSize() < 2 )
5757         return false;
5758     
5759     if ( data.m_private_data.GetBuffer()[0] != MATROSKA_DVD_LEVEL_PTT )
5760         return false;
5761
5762     uint8 i_chapter = data.m_private_data.GetBuffer()[1];
5763     uint8 i_ptt = *(uint8*)p_cookie;
5764
5765     return (i_chapter == i_ptt);
5766 }
5767
5768 bool dvd_command_interpretor_c::MatchCellNumber( const chapter_codec_cmds_c &data, const void *p_cookie, size_t i_cookie_size )
5769 {
5770     if ( i_cookie_size != 1 || data.m_private_data.GetSize() < 5 )
5771         return false;
5772     
5773     if ( data.m_private_data.GetBuffer()[0] != MATROSKA_DVD_LEVEL_CN )
5774         return false;
5775
5776     uint8 *i_cell_n = (uint8 *)p_cookie;
5777     uint8 i_cell_num = data.m_private_data.GetBuffer()[3];
5778
5779     return (i_cell_num == *i_cell_n);
5780 }
5781
5782 bool matroska_script_codec_c::Enter()
5783 {
5784     bool f_result = false;
5785     std::vector<KaxChapterProcessData>::iterator index = enter_cmds.begin();
5786     while ( index != enter_cmds.end() )
5787     {
5788         if ( (*index).GetSize() )
5789         {
5790             msg_Dbg( &sys.demuxer, "Matroska Script enter command" );
5791             f_result |= interpretor.Interpret( (*index).GetBuffer(), (*index).GetSize() );
5792         }
5793         index++;
5794     }
5795     return f_result;
5796 }
5797
5798 bool matroska_script_codec_c::Leave()
5799 {
5800     bool f_result = false;
5801     std::vector<KaxChapterProcessData>::iterator index = leave_cmds.begin();
5802     while ( index != leave_cmds.end() )
5803     {
5804         if ( (*index).GetSize() )
5805         {
5806             msg_Dbg( &sys.demuxer, "Matroska Script leave command" );
5807             f_result |= interpretor.Interpret( (*index).GetBuffer(), (*index).GetSize() );
5808         }
5809         index++;
5810     }
5811     return f_result;
5812 }
5813
5814 // see http://www.matroska.org/technical/specs/chapters/index.html#mscript 
5815 //  for a description of existing commands
5816 bool matroska_script_interpretor_c::Interpret( const binary * p_command, size_t i_size )
5817 {
5818     bool b_result = false;
5819
5820     char *psz_str = (char*) malloc( i_size + 1 );
5821     memcpy( psz_str, p_command, i_size );
5822     psz_str[ i_size ] = '\0';
5823
5824     std::string sz_command = psz_str;
5825     free( psz_str );
5826
5827     msg_Dbg( &sys.demuxer, "command : %s", sz_command.c_str() );
5828
5829 #if defined(__GNUC__) && (__GNUC__ < 3)
5830     if ( sz_command.compare( CMD_MS_GOTO_AND_PLAY, 0, CMD_MS_GOTO_AND_PLAY.size() ) == 0 )
5831 #else
5832     if ( sz_command.compare( 0, CMD_MS_GOTO_AND_PLAY.size(), CMD_MS_GOTO_AND_PLAY ) == 0 )
5833 #endif
5834     {
5835         size_t i,j;
5836
5837         // find the (
5838         for ( i=CMD_MS_GOTO_AND_PLAY.size(); i<sz_command.size(); i++)
5839         {
5840             if ( sz_command[i] == '(' )
5841             {
5842                 i++;
5843                 break;
5844             }
5845         }
5846         // find the )
5847         for ( j=i; j<sz_command.size(); j++)
5848         {
5849             if ( sz_command[j] == ')' )
5850             {
5851                 i--;
5852                 break;
5853             }
5854         }
5855
5856         std::string st = sz_command.substr( i+1, j-i-1 );
5857         int64_t i_chapter_uid = atoi( st.c_str() );
5858
5859         virtual_segment_c *p_segment;
5860         chapter_item_c *p_chapter = sys.FindChapter( i_chapter_uid, p_segment );
5861
5862         if ( p_chapter == NULL )
5863             msg_Dbg( &sys.demuxer, "Chapter "I64Fd" not found", i_chapter_uid);
5864         else
5865         {
5866             if ( !p_chapter->EnterAndLeave( sys.p_current_segment->CurrentChapter() ) )
5867                 p_segment->Seek( sys.demuxer, p_chapter->i_user_start_time, -1, p_chapter );
5868             b_result = true;
5869         }
5870     }
5871
5872     return b_result;
5873 }
5874
5875 void demux_sys_t::SwapButtons()
5876 {
5877 #ifndef WORDS_BIGENDIAN
5878     uint8_t button, i, j;
5879
5880     for( button = 1; button <= pci_packet.hli.hl_gi.btn_ns; button++) {
5881         btni_t *button_ptr = &(pci_packet.hli.btnit[button-1]);
5882         binary *p_data = (binary*) button_ptr;
5883
5884         uint16 i_x_start = ((p_data[0] & 0x3F) << 4 ) + ( p_data[1] >> 4 );
5885         uint16 i_x_end   = ((p_data[1] & 0x03) << 8 ) + p_data[2];
5886         uint16 i_y_start = ((p_data[3] & 0x3F) << 4 ) + ( p_data[4] >> 4 );
5887         uint16 i_y_end   = ((p_data[4] & 0x03) << 8 ) + p_data[5];
5888         button_ptr->x_start = i_x_start;
5889         button_ptr->x_end   = i_x_end;
5890         button_ptr->y_start = i_y_start;
5891         button_ptr->y_end   = i_y_end;
5892
5893     }
5894     for ( i = 0; i<3; i++ )
5895     {
5896         for ( j = 0; j<2; j++ )
5897         {
5898             pci_packet.hli.btn_colit.btn_coli[i][j] = U32_AT( &pci_packet.hli.btn_colit.btn_coli[i][j] );
5899         }
5900     }
5901 #endif
5902 }