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