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