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