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