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