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