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