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