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