]> git.sesse.net Git - vlc/blob - modules/demux/mkv.cpp
Ignore invalid blocks (on broken files).
[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_info_position(-1)
1031         ,i_chapters_position(-1)
1032         ,i_tags_position(-1)
1033         ,i_tracks_position(-1)
1034         ,i_attachments_position(-1)
1035         ,i_seekhead_position(-1)
1036         ,i_seekhead_count(0)
1037         ,cluster(NULL)
1038         ,i_block_pos(0)
1039         ,i_cluster_pos(0)
1040         ,i_start_pos(0)
1041         ,p_segment_uid(NULL)
1042         ,p_prev_segment_uid(NULL)
1043         ,p_next_segment_uid(NULL)
1044         ,b_cues(false)
1045         ,i_index(0)
1046         ,i_index_max(1024)
1047         ,psz_muxing_application(NULL)
1048         ,psz_writing_application(NULL)
1049         ,psz_segment_filename(NULL)
1050         ,psz_title(NULL)
1051         ,psz_date_utc(NULL)
1052         ,i_default_edition(0)
1053         ,sys(demuxer)
1054         ,ep(NULL)
1055         ,b_preloaded(false)
1056     {
1057         p_indexes = (mkv_index_t*)malloc( sizeof( mkv_index_t ) * i_index_max );
1058     }
1059
1060     virtual ~matroska_segment_c()
1061     {
1062         for( size_t i_track = 0; i_track < tracks.size(); i_track++ )
1063         {
1064             delete tracks[i_track]->p_compression_data;
1065             es_format_Clean( &tracks[i_track]->fmt );
1066             free( tracks[i_track]->p_extra_data );
1067             free( tracks[i_track]->psz_codec );
1068             delete tracks[i_track];
1069         }
1070
1071         free( psz_writing_application );
1072         free( psz_muxing_application );
1073         free( psz_segment_filename );
1074         free( psz_title );
1075         free( psz_date_utc );
1076         free( p_indexes );
1077
1078         delete ep;
1079         delete segment;
1080         delete p_segment_uid;
1081         delete p_prev_segment_uid;
1082         delete p_next_segment_uid;
1083
1084         std::vector<chapter_edition_c*>::iterator index = stored_editions.begin();
1085         while ( index != stored_editions.end() )
1086         {
1087             delete (*index);
1088             index++;
1089         }
1090         std::vector<chapter_translation_c*>::iterator indext = translations.begin();
1091         while ( indext != translations.end() )
1092         {
1093             delete (*indext);
1094             indext++;
1095         }
1096         std::vector<KaxSegmentFamily*>::iterator indexf = families.begin();
1097         while ( indexf != families.end() )
1098         {
1099             delete (*indexf);
1100             indexf++;
1101         }
1102     }
1103
1104     KaxSegment              *segment;
1105     EbmlStream              & es;
1106
1107     /* time scale */
1108     uint64_t                i_timescale;
1109
1110     /* duration of the segment */
1111     mtime_t                 i_duration;
1112     mtime_t                 i_start_time;
1113
1114     /* all tracks */
1115     std::vector<mkv_track_t*> tracks;
1116
1117     /* from seekhead */
1118     int                     i_seekhead_count;
1119     int64_t                 i_seekhead_position;
1120     int64_t                 i_cues_position;
1121     int64_t                 i_tracks_position;
1122     int64_t                 i_info_position;
1123     int64_t                 i_chapters_position;
1124     int64_t                 i_tags_position;
1125     int64_t                 i_attachments_position;
1126
1127     KaxCluster              *cluster;
1128     uint64                  i_block_pos;
1129     uint64                  i_cluster_pos;
1130     int64_t                 i_start_pos;
1131     KaxSegmentUID           *p_segment_uid;
1132     KaxPrevUID              *p_prev_segment_uid;
1133     KaxNextUID              *p_next_segment_uid;
1134
1135     bool                    b_cues;
1136     int                     i_index;
1137     int                     i_index_max;
1138     mkv_index_t             *p_indexes;
1139
1140     /* info */
1141     char                    *psz_muxing_application;
1142     char                    *psz_writing_application;
1143     char                    *psz_segment_filename;
1144     char                    *psz_title;
1145     char                    *psz_date_utc;
1146
1147     /* !!!!! GCC 3.3 bug on Darwin !!!!! */
1148     /* when you remove this variable the compiler issues an atomicity error */
1149     /* this variable only works when using std::vector<chapter_edition_c> */
1150     std::vector<chapter_edition_c*> stored_editions;
1151     int                             i_default_edition;
1152
1153     std::vector<chapter_translation_c*> translations;
1154     std::vector<KaxSegmentFamily*>  families;
1155  
1156     demux_sys_t                    & sys;
1157     EbmlParser                     *ep;
1158     bool                           b_preloaded;
1159
1160     bool Preload( );
1161     bool LoadSeekHeadItem( const EbmlCallbacks & ClassInfos, int64_t i_element_position );
1162     bool PreloadFamily( const matroska_segment_c & segment );
1163     void ParseInfo( KaxInfo *info );
1164     void ParseAttachments( KaxAttachments *attachments );
1165     void ParseChapters( KaxChapters *chapters );
1166     void ParseSeekHead( KaxSeekHead *seekhead );
1167     void ParseTracks( KaxTracks *tracks );
1168     void ParseChapterAtom( int i_level, KaxChapterAtom *ca, chapter_item_c & chapters );
1169     void ParseTrackEntry( KaxTrackEntry *m );
1170     void ParseCluster( );
1171     void IndexAppendCluster( KaxCluster *cluster );
1172     void LoadCues( KaxCues *cues );
1173     void LoadTags( KaxTags *tags );
1174     void InformationCreate( );
1175     void Seek( mtime_t i_date, mtime_t i_time_offset, int64_t i_global_position );
1176 #if LIBMATROSKA_VERSION >= 0x000800
1177     int BlockGet( KaxBlock * &, KaxSimpleBlock * &, int64_t *, int64_t *, int64_t *);
1178 #else
1179     int BlockGet( KaxBlock * &, int64_t *, int64_t *, int64_t *);
1180 #endif
1181     bool Select( mtime_t i_start_time );
1182     void UnSelect( );
1183
1184     static bool CompareSegmentUIDs( const matroska_segment_c * item_a, const matroska_segment_c * item_b );
1185 };
1186
1187 // class holding hard-linked segment together in the playback order
1188 class virtual_segment_c
1189 {
1190 public:
1191     virtual_segment_c( matroska_segment_c *p_segment )
1192         :p_editions(NULL)
1193         ,i_sys_title(0)
1194         ,i_current_segment(0)
1195         ,i_current_edition(-1)
1196         ,psz_current_chapter(NULL)
1197     {
1198         linked_segments.push_back( p_segment );
1199
1200         AppendUID( p_segment->p_segment_uid );
1201         AppendUID( p_segment->p_prev_segment_uid );
1202         AppendUID( p_segment->p_next_segment_uid );
1203     }
1204
1205     void Sort();
1206     size_t AddSegment( matroska_segment_c *p_segment );
1207     void PreloadLinked( );
1208     mtime_t Duration( ) const;
1209     void Seek( demux_t & demuxer, mtime_t i_date, mtime_t i_time_offset, chapter_item_c *psz_chapter, int64_t i_global_position );
1210
1211     inline chapter_edition_c *Edition()
1212     {
1213         if ( i_current_edition >= 0 && size_t(i_current_edition) < p_editions->size() )
1214             return (*p_editions)[i_current_edition];
1215         return NULL;
1216     }
1217
1218     matroska_segment_c * Segment() const
1219     {
1220         if ( linked_segments.size() == 0 || i_current_segment >= linked_segments.size() )
1221             return NULL;
1222         return linked_segments[i_current_segment];
1223     }
1224
1225     inline chapter_item_c *CurrentChapter() {
1226         return psz_current_chapter;
1227     }
1228
1229     bool SelectNext()
1230     {
1231         if ( i_current_segment < linked_segments.size()-1 )
1232         {
1233             i_current_segment++;
1234             return true;
1235         }
1236         return false;
1237     }
1238
1239     bool FindUID( KaxSegmentUID & uid ) const
1240     {
1241         for ( size_t i=0; i<linked_uids.size(); i++ )
1242         {
1243             if ( linked_uids[i] == uid )
1244                 return true;
1245         }
1246         return false;
1247     }
1248
1249     bool UpdateCurrentToChapter( demux_t & demux );
1250     void PrepareChapters( );
1251
1252     chapter_item_c *BrowseCodecPrivate( unsigned int codec_id,
1253                                         bool (*match)(const chapter_codec_cmds_c &data, const void *p_cookie, size_t i_cookie_size ),
1254                                         const void *p_cookie,
1255                                         size_t i_cookie_size );
1256     chapter_item_c *FindChapter( int64_t i_find_uid );
1257
1258     std::vector<chapter_edition_c*>  *p_editions;
1259     int                              i_sys_title;
1260
1261 protected:
1262     std::vector<matroska_segment_c*> linked_segments;
1263     std::vector<KaxSegmentUID>       linked_uids;
1264     size_t                           i_current_segment;
1265
1266     int                              i_current_edition;
1267     chapter_item_c                   *psz_current_chapter;
1268
1269     void                             AppendUID( const EbmlBinary * UID );
1270 };
1271
1272 class matroska_stream_c
1273 {
1274 public:
1275     matroska_stream_c( demux_sys_t & demuxer )
1276         :p_in(NULL)
1277         ,p_es(NULL)
1278         ,sys(demuxer)
1279     {}
1280
1281     virtual ~matroska_stream_c()
1282     {
1283         delete p_in;
1284         delete p_es;
1285     }
1286
1287     IOCallback         *p_in;
1288     EbmlStream         *p_es;
1289
1290     std::vector<matroska_segment_c*> segments;
1291
1292     demux_sys_t                      & sys;
1293 };
1294
1295 typedef struct
1296 {
1297     VLC_COMMON_MEMBERS
1298
1299     demux_t        *p_demux;
1300     vlc_mutex_t     lock;
1301
1302     bool            b_moved;
1303     bool            b_clicked;
1304     int             i_key_action;
1305
1306 } event_thread_t;
1307
1308
1309 class attachment_c
1310 {
1311 public:
1312     attachment_c()
1313         :p_data(NULL)
1314         ,i_size(0)
1315     {}
1316     virtual ~attachment_c()
1317     {
1318         free( p_data );
1319     }
1320
1321     std::string    psz_file_name;
1322     std::string    psz_mime_type;
1323     void          *p_data;
1324     int            i_size;
1325 };
1326
1327 class demux_sys_t
1328 {
1329 public:
1330     demux_sys_t( demux_t & demux )
1331         :demuxer(demux)
1332         ,i_pts(0)
1333         ,i_start_pts(0)
1334         ,i_chapter_time(0)
1335         ,meta(NULL)
1336         ,i_current_title(0)
1337         ,p_current_segment(NULL)
1338         ,dvd_interpretor( *this )
1339         ,f_duration(-1.0)
1340         ,b_ui_hooked(false)
1341         ,p_input(NULL)
1342         ,b_pci_packet_set(false)
1343         ,p_ev(NULL)
1344     {
1345         vlc_mutex_init( &lock_demuxer );
1346     }
1347
1348     virtual ~demux_sys_t()
1349     {
1350         StopUiThread();
1351         size_t i;
1352         for ( i=0; i<streams.size(); i++ )
1353             delete streams[i];
1354         for ( i=0; i<opened_segments.size(); i++ )
1355             delete opened_segments[i];
1356         for ( i=0; i<used_segments.size(); i++ )
1357             delete used_segments[i];
1358         for ( i=0; i<stored_attachments.size(); i++ )
1359             delete stored_attachments[i];
1360         if( meta ) vlc_meta_Delete( meta );
1361
1362         while( titles.size() )
1363         { vlc_input_title_Delete( titles.back() ); titles.pop_back();}
1364
1365         vlc_mutex_destroy( &lock_demuxer );
1366     }
1367
1368     /* current data */
1369     demux_t                 & demuxer;
1370
1371     mtime_t                 i_pts;
1372     mtime_t                 i_start_pts;
1373     mtime_t                 i_chapter_time;
1374
1375     vlc_meta_t              *meta;
1376
1377     std::vector<input_title_t*>      titles; // matroska editions
1378     size_t                           i_current_title;
1379
1380     std::vector<matroska_stream_c*>  streams;
1381     std::vector<attachment_c*>       stored_attachments;
1382     std::vector<matroska_segment_c*> opened_segments;
1383     std::vector<virtual_segment_c*>  used_segments;
1384     virtual_segment_c                *p_current_segment;
1385
1386     dvd_command_interpretor_c        dvd_interpretor;
1387
1388     /* duration of the stream */
1389     float                   f_duration;
1390
1391     matroska_segment_c *FindSegment( const EbmlBinary & uid ) const;
1392     chapter_item_c *BrowseCodecPrivate( unsigned int codec_id,
1393                                         bool (*match)(const chapter_codec_cmds_c &data, const void *p_cookie, size_t i_cookie_size ),
1394                                         const void *p_cookie,
1395                                         size_t i_cookie_size,
1396                                         virtual_segment_c * & p_segment_found );
1397     chapter_item_c *FindChapter( int64_t i_find_uid, virtual_segment_c * & p_segment_found );
1398
1399     void PreloadFamily( const matroska_segment_c & of_segment );
1400     void PreloadLinked( matroska_segment_c *p_segment );
1401     bool PreparePlayback( virtual_segment_c *p_new_segment );
1402     matroska_stream_c *AnalyseAllSegmentsFound( demux_t *p_demux, EbmlStream *p_estream, bool b_initial = false );
1403     void JumpTo( virtual_segment_c & p_segment, chapter_item_c * p_chapter );
1404
1405     void StartUiThread();
1406     void StopUiThread();
1407     bool b_ui_hooked;
1408     inline void SwapButtons();
1409
1410     /* for spu variables */
1411     input_thread_t *p_input;
1412     pci_t          pci_packet;
1413     bool           b_pci_packet_set;
1414     uint8_t        palette[4][4];
1415     vlc_mutex_t    lock_demuxer;
1416
1417     /* event */
1418     event_thread_t *p_ev;
1419     static void * EventThread( vlc_object_t *p_this );
1420     static int EventMouse( vlc_object_t *p_this, char const *psz_var,
1421                        vlc_value_t oldval, vlc_value_t newval, void *p_data );
1422     static int EventKey( vlc_object_t *p_this, char const *psz_var,
1423                      vlc_value_t oldval, vlc_value_t newval, void *p_data );
1424
1425
1426
1427 protected:
1428     virtual_segment_c *VirtualFromSegments( matroska_segment_c *p_segment ) const;
1429     bool IsUsedSegment( matroska_segment_c &p_segment ) const;
1430 };
1431
1432 static int  Demux  ( demux_t * );
1433 static int  Control( demux_t *, int, va_list );
1434 static void Seek   ( demux_t *, mtime_t i_date, double f_percent, chapter_item_c *psz_chapter );
1435
1436 #define MKV_IS_ID( el, C ) ( EbmlId( (*el) ) == C::ClassInfos.GlobalId )
1437
1438 static inline char * ToUTF8( const UTFstring &u )
1439 {
1440     return strdup( u.GetUTF8().c_str() );
1441 }
1442
1443 /*****************************************************************************
1444  * Open: initializes matroska demux structures
1445  *****************************************************************************/
1446 static int Open( vlc_object_t * p_this )
1447 {
1448     demux_t            *p_demux = (demux_t*)p_this;
1449     demux_sys_t        *p_sys;
1450     matroska_stream_c  *p_stream;
1451     matroska_segment_c *p_segment;
1452     const uint8_t      *p_peek;
1453     std::string         s_path, s_filename;
1454     vlc_stream_io_callback *p_io_callback;
1455     EbmlStream         *p_io_stream;
1456
1457     /* peek the begining */
1458     if( stream_Peek( p_demux->s, &p_peek, 4 ) < 4 ) return VLC_EGENERIC;
1459
1460     /* is a valid file */
1461     if( p_peek[0] != 0x1a || p_peek[1] != 0x45 ||
1462         p_peek[2] != 0xdf || p_peek[3] != 0xa3 ) return VLC_EGENERIC;
1463
1464     /* Set the demux function */
1465     p_demux->pf_demux   = Demux;
1466     p_demux->pf_control = Control;
1467     p_demux->p_sys      = p_sys = new demux_sys_t( *p_demux );
1468
1469     p_io_callback = new vlc_stream_io_callback( p_demux->s, false );
1470     p_io_stream = new EbmlStream( *p_io_callback );
1471
1472     if( p_io_stream == NULL )
1473     {
1474         msg_Err( p_demux, "failed to create EbmlStream" );
1475         delete p_io_callback;
1476         delete p_sys;
1477         return VLC_EGENERIC;
1478     }
1479
1480     p_stream = p_sys->AnalyseAllSegmentsFound( p_demux, p_io_stream, true );
1481     if( p_stream == NULL )
1482     {
1483         msg_Err( p_demux, "cannot find KaxSegment" );
1484         goto error;
1485     }
1486     p_sys->streams.push_back( p_stream );
1487
1488     p_stream->p_in = p_io_callback;
1489     p_stream->p_es = p_io_stream;
1490
1491     for (size_t i=0; i<p_stream->segments.size(); i++)
1492     {
1493         p_stream->segments[i]->Preload();
1494     }
1495
1496     p_segment = p_stream->segments[0];
1497     if( p_segment->cluster == NULL )
1498     {
1499         msg_Err( p_demux, "cannot find any cluster, damaged file ?" );
1500         goto error;
1501     }
1502
1503     if (config_GetInt( p_demux, "mkv-preload-local-dir" ))
1504     {
1505         /* get the files from the same dir from the same family (based on p_demux->psz_path) */
1506         if (p_demux->psz_path[0] != '\0' && !strcmp(p_demux->psz_access, ""))
1507         {
1508             // assume it's a regular file
1509             // get the directory path
1510             s_path = p_demux->psz_path;
1511             if (s_path.at(s_path.length() - 1) == DIRECTORY_SEPARATOR)
1512             {
1513                 s_path = s_path.substr(0,s_path.length()-1);
1514             }
1515             else
1516             {
1517                 if (s_path.find_last_of(DIRECTORY_SEPARATOR) > 0)
1518                 {
1519                     s_path = s_path.substr(0,s_path.find_last_of(DIRECTORY_SEPARATOR));
1520                 }
1521             }
1522
1523             DIR *p_src_dir = utf8_opendir(s_path.c_str());
1524
1525             if (p_src_dir != NULL)
1526             {
1527                 char *psz_file;
1528                 while ((psz_file = utf8_readdir(p_src_dir)) != NULL)
1529                 {
1530                     if (strlen(psz_file) > 4)
1531                     {
1532                         s_filename = s_path + DIRECTORY_SEPARATOR + psz_file;
1533
1534 #ifdef WIN32
1535                         if (!strcasecmp(s_filename.c_str(), p_demux->psz_path))
1536 #else
1537                         if (!s_filename.compare(p_demux->psz_path))
1538 #endif
1539                         {
1540                             free (psz_file);
1541                             continue; // don't reuse the original opened file
1542                         }
1543
1544 #if defined(__GNUC__) && (__GNUC__ < 3)
1545                         if (!s_filename.compare("mkv", s_filename.length() - 3, 3) ||
1546                             !s_filename.compare("mka", s_filename.length() - 3, 3))
1547 #else
1548                         if (!s_filename.compare(s_filename.length() - 3, 3, "mkv") ||
1549                             !s_filename.compare(s_filename.length() - 3, 3, "mka"))
1550 #endif
1551                         {
1552                             // test wether this file belongs to our family
1553                             const uint8_t *p_peek;
1554                             bool          file_ok = false;
1555                             stream_t      *p_file_stream = stream_UrlNew(
1556                                                             p_demux,
1557                                                             s_filename.c_str());
1558                             /* peek the begining */
1559                             if( p_file_stream &&
1560                                 stream_Peek( p_file_stream, &p_peek, 4 ) >= 4
1561                                 && p_peek[0] == 0x1a && p_peek[1] == 0x45 &&
1562                                 p_peek[2] == 0xdf && p_peek[3] == 0xa3 ) file_ok = true;
1563
1564                             if ( file_ok )
1565                             {
1566                                 vlc_stream_io_callback *p_file_io = new vlc_stream_io_callback( p_file_stream, true );
1567                                 EbmlStream *p_estream = new EbmlStream(*p_file_io);
1568
1569                                 p_stream = p_sys->AnalyseAllSegmentsFound( p_demux, p_estream );
1570
1571                                 if ( p_stream == NULL )
1572                                 {
1573                                     msg_Dbg( p_demux, "the file '%s' will not be used", s_filename.c_str() );
1574                                     delete p_estream;
1575                                     delete p_file_io;
1576                                 }
1577                                 else
1578                                 {
1579                                     p_stream->p_in = p_file_io;
1580                                     p_stream->p_es = p_estream;
1581                                     p_sys->streams.push_back( p_stream );
1582                                 }
1583                             }
1584                             else
1585                             {
1586                                 if( p_file_stream ) {
1587                                     stream_Delete( p_file_stream );
1588                                 }
1589                                 msg_Dbg( p_demux, "the file '%s' cannot be opened", s_filename.c_str() );
1590                             }
1591                         }
1592                     }
1593                     free (psz_file);
1594                 }
1595                 closedir( p_src_dir );
1596             }
1597         }
1598
1599         p_sys->PreloadFamily( *p_segment );
1600     }
1601
1602     p_sys->PreloadLinked( p_segment );
1603
1604     if ( !p_sys->PreparePlayback( NULL ) )
1605     {
1606         msg_Err( p_demux, "cannot use the segment" );
1607         goto error;
1608     }
1609
1610     p_sys->StartUiThread();
1611  
1612     return VLC_SUCCESS;
1613
1614 error:
1615     delete p_sys;
1616     return VLC_EGENERIC;
1617 }
1618
1619 /*****************************************************************************
1620  * Close: frees unused data
1621  *****************************************************************************/
1622 static void Close( vlc_object_t *p_this )
1623 {
1624     demux_t     *p_demux = (demux_t*)p_this;
1625     demux_sys_t *p_sys   = p_demux->p_sys;
1626
1627     delete p_sys;
1628 }
1629
1630 /*****************************************************************************
1631  * Control:
1632  *****************************************************************************/
1633 static int Control( demux_t *p_demux, int i_query, va_list args )
1634 {
1635     demux_sys_t        *p_sys = p_demux->p_sys;
1636     int64_t     *pi64;
1637     double      *pf, f;
1638     int         i_skp;
1639     size_t      i_idx;
1640
1641     vlc_meta_t *p_meta;
1642     input_attachment_t ***ppp_attach;
1643     int *pi_int;
1644     int i;
1645
1646     switch( i_query )
1647     {
1648         case DEMUX_GET_ATTACHMENTS:
1649             ppp_attach = (input_attachment_t***)va_arg( args, input_attachment_t*** );
1650             pi_int = (int*)va_arg( args, int * );
1651
1652             if( p_sys->stored_attachments.size() <= 0 )
1653                 return VLC_EGENERIC;
1654
1655             *pi_int = p_sys->stored_attachments.size();
1656             *ppp_attach = (input_attachment_t**)malloc( sizeof(input_attachment_t**) *
1657                                                         p_sys->stored_attachments.size() );
1658             if( !(*ppp_attach) )
1659                 return VLC_ENOMEM;
1660             for( i = 0; i < p_sys->stored_attachments.size(); i++ )
1661             {
1662                 attachment_c *a = p_sys->stored_attachments[i];
1663                 (*ppp_attach)[i] = vlc_input_attachment_New( a->psz_file_name.c_str(), a->psz_mime_type.c_str(), NULL,
1664                                                              a->p_data, a->i_size );
1665             }
1666             return VLC_SUCCESS;
1667
1668         case DEMUX_GET_META:
1669             p_meta = (vlc_meta_t*)va_arg( args, vlc_meta_t* );
1670             vlc_meta_Merge( p_meta, p_sys->meta );
1671             return VLC_SUCCESS;
1672
1673         case DEMUX_GET_LENGTH:
1674             pi64 = (int64_t*)va_arg( args, int64_t * );
1675             if( p_sys->f_duration > 0.0 )
1676             {
1677                 *pi64 = (int64_t)(p_sys->f_duration * 1000);
1678                 return VLC_SUCCESS;
1679             }
1680             return VLC_EGENERIC;
1681
1682         case DEMUX_GET_POSITION:
1683             pf = (double*)va_arg( args, double * );
1684             if ( p_sys->f_duration > 0.0 )
1685                 *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);
1686             return VLC_SUCCESS;
1687
1688         case DEMUX_SET_POSITION:
1689             f = (double)va_arg( args, double );
1690             Seek( p_demux, -1, f, NULL );
1691             return VLC_SUCCESS;
1692
1693         case DEMUX_GET_TIME:
1694             pi64 = (int64_t*)va_arg( args, int64_t * );
1695             *pi64 = p_sys->i_pts;
1696             return VLC_SUCCESS;
1697
1698         case DEMUX_GET_TITLE_INFO:
1699             if( p_sys->titles.size() > 1 || ( p_sys->titles.size() == 1 && p_sys->titles[0]->i_seekpoint > 0 ) )
1700             {
1701                 input_title_t ***ppp_title = (input_title_t***)va_arg( args, input_title_t*** );
1702                 int *pi_int    = (int*)va_arg( args, int* );
1703
1704                 *pi_int = p_sys->titles.size();
1705                 *ppp_title = (input_title_t**)malloc( sizeof( input_title_t**) * p_sys->titles.size() );
1706
1707                 for( size_t i = 0; i < p_sys->titles.size(); i++ )
1708                 {
1709                     (*ppp_title)[i] = vlc_input_title_Duplicate( p_sys->titles[i] );
1710                 }
1711                 return VLC_SUCCESS;
1712             }
1713             return VLC_EGENERIC;
1714
1715         case DEMUX_SET_TITLE:
1716             /* TODO handle editions as titles */
1717             i_idx = (int)va_arg( args, int );
1718             if( i_idx < p_sys->used_segments.size() )
1719             {
1720                 p_sys->JumpTo( *p_sys->used_segments[i_idx], NULL );
1721                 return VLC_SUCCESS;
1722             }
1723             return VLC_EGENERIC;
1724
1725         case DEMUX_SET_SEEKPOINT:
1726             i_skp = (int)va_arg( args, int );
1727
1728             // TODO change the way it works with the << & >> buttons on the UI (+1/-1 instead of a number)
1729             if( p_sys->titles.size() && i_skp < p_sys->titles[p_sys->i_current_title]->i_seekpoint)
1730             {
1731                 Seek( p_demux, (int64_t)p_sys->titles[p_sys->i_current_title]->seekpoint[i_skp]->i_time_offset, -1, NULL);
1732                 p_demux->info.i_seekpoint |= INPUT_UPDATE_SEEKPOINT;
1733                 p_demux->info.i_seekpoint = i_skp;
1734                 return VLC_SUCCESS;
1735             }
1736             return VLC_EGENERIC;
1737
1738         case DEMUX_SET_TIME:
1739         case DEMUX_GET_FPS:
1740         default:
1741             return VLC_EGENERIC;
1742     }
1743 }
1744
1745 #if LIBMATROSKA_VERSION >= 0x000800
1746 int matroska_segment_c::BlockGet( KaxBlock * & pp_block, KaxSimpleBlock * & pp_simpleblock, int64_t *pi_ref1, int64_t *pi_ref2, int64_t *pi_duration )
1747 #else
1748 int matroska_segment_c::BlockGet( KaxBlock * & pp_block, int64_t *pi_ref1, int64_t *pi_ref2, int64_t *pi_duration )
1749 #endif
1750 {
1751 #if LIBMATROSKA_VERSION >= 0x000800
1752     pp_simpleblock = NULL;
1753 #endif
1754     pp_block = NULL;
1755     *pi_ref1  = 0;
1756     *pi_ref2  = 0;
1757
1758     for( ;; )
1759     {
1760         EbmlElement *el = NULL;
1761         int         i_level;
1762
1763         if ( ep == NULL )
1764             return VLC_EGENERIC;
1765
1766 #if LIBMATROSKA_VERSION >= 0x000800
1767         if( pp_simpleblock != NULL || ((el = ep->Get()) == NULL && pp_block != NULL) )
1768 #else
1769         if( (el = ep->Get()) == NULL && pp_block != NULL )
1770 #endif
1771         {
1772             /* Check blocks validity to protect againts broken files */
1773             if(
1774 #if LIBMATROSKA_VERSION >= 0x000800
1775                 pp_simpleblock && pp_simpleblock->TrackNum() >= tracks.size() ||
1776 #else
1777                 false ||
1778 #endif
1779                 pp_block && pp_block->TrackNum() >= tracks.size() )
1780             {
1781                 delete pp_block;
1782 #if LIBMATROSKA_VERSION >= 0x000800
1783                 pp_simpleblock = NULL;
1784 #endif
1785                 pp_block = NULL;
1786                 continue;
1787             }
1788
1789             /* update the index */
1790 #define idx p_indexes[i_index - 1]
1791             if( i_index > 0 && idx.i_time == -1 )
1792             {
1793 #if LIBMATROSKA_VERSION >= 0x000800
1794                 if ( pp_simpleblock != NULL )
1795                     idx.i_time        = pp_simpleblock->GlobalTimecode() / (mtime_t)1000;
1796                 else
1797 #endif
1798                     idx.i_time        = (*pp_block).GlobalTimecode() / (mtime_t)1000;
1799                 idx.b_key         = *pi_ref1 == 0 ? true : false;
1800             }
1801 #undef idx
1802             return VLC_SUCCESS;
1803         }
1804
1805         i_level = ep->GetLevel();
1806
1807         if( el == NULL )
1808         {
1809             if( i_level > 1 )
1810             {
1811                 ep->Up();
1812                 continue;
1813             }
1814             msg_Warn( &sys.demuxer, "EOF" );
1815             return VLC_EGENERIC;
1816         }
1817
1818         /* Verify that we are still inside our cluster
1819          * It can happens whith broken files and when seeking
1820          * without index */
1821         if( i_level > 1 )
1822         {
1823             if( cluster && !ep->IsTopPresent( cluster ) )
1824             {
1825                 msg_Warn( &sys.demuxer, "Unexpected escape from current cluster" );
1826                 cluster = NULL;
1827             }
1828             if( !cluster )
1829                 continue;
1830         }
1831
1832         /* do parsing */
1833         switch ( i_level )
1834         {
1835         case 1:
1836             if( MKV_IS_ID( el, KaxCluster ) )
1837             {
1838                 cluster = (KaxCluster*)el;
1839                 i_cluster_pos = cluster->GetElementPosition();
1840
1841                 /* add it to the index */
1842                 if( i_index == 0 ||
1843                     ( i_index > 0 && p_indexes[i_index - 1].i_position < (int64_t)cluster->GetElementPosition() ) )
1844                 {
1845                     IndexAppendCluster( cluster );
1846                 }
1847
1848                 // reset silent tracks
1849                 for (size_t i=0; i<tracks.size(); i++)
1850                 {
1851                     tracks[i]->b_silent = false;
1852                 }
1853
1854                 ep->Down();
1855             }
1856             else if( MKV_IS_ID( el, KaxCues ) )
1857             {
1858                 msg_Warn( &sys.demuxer, "find KaxCues FIXME" );
1859                 return VLC_EGENERIC;
1860             }
1861             else
1862             {
1863                 msg_Dbg( &sys.demuxer, "unknown (%s)", typeid( el ).name() );
1864             }
1865             break;
1866         case 2:
1867             if( MKV_IS_ID( el, KaxClusterTimecode ) )
1868             {
1869                 KaxClusterTimecode &ctc = *(KaxClusterTimecode*)el;
1870
1871                 ctc.ReadData( es.I_O(), SCOPE_ALL_DATA );
1872                 cluster->InitTimecode( uint64( ctc ), i_timescale );
1873             }
1874             else if( MKV_IS_ID( el, KaxClusterSilentTracks ) )
1875             {
1876                 ep->Down();
1877             }
1878             else if( MKV_IS_ID( el, KaxBlockGroup ) )
1879             {
1880                 i_block_pos = el->GetElementPosition();
1881                 ep->Down();
1882             }
1883 #if LIBMATROSKA_VERSION >= 0x000800
1884             else if( MKV_IS_ID( el, KaxSimpleBlock ) )
1885             {
1886                 pp_simpleblock = (KaxSimpleBlock*)el;
1887
1888                 pp_simpleblock->ReadData( es.I_O() );
1889                 pp_simpleblock->SetParent( *cluster );
1890             }
1891 #endif
1892             break;
1893         case 3:
1894             if( MKV_IS_ID( el, KaxBlock ) )
1895             {
1896                 pp_block = (KaxBlock*)el;
1897
1898                 pp_block->ReadData( es.I_O() );
1899                 pp_block->SetParent( *cluster );
1900
1901                 ep->Keep();
1902             }
1903             else if( MKV_IS_ID( el, KaxBlockDuration ) )
1904             {
1905                 KaxBlockDuration &dur = *(KaxBlockDuration*)el;
1906
1907                 dur.ReadData( es.I_O() );
1908                 *pi_duration = uint64( dur );
1909             }
1910             else if( MKV_IS_ID( el, KaxReferenceBlock ) )
1911             {
1912                 KaxReferenceBlock &ref = *(KaxReferenceBlock*)el;
1913
1914                 ref.ReadData( es.I_O() );
1915                 if( *pi_ref1 == 0 )
1916                 {
1917                     *pi_ref1 = int64( ref ) * cluster->GlobalTimecodeScale();
1918                 }
1919                 else if( *pi_ref2 == 0 )
1920                 {
1921                     *pi_ref2 = int64( ref ) * cluster->GlobalTimecodeScale();
1922                 }
1923             }
1924             else if( MKV_IS_ID( el, KaxClusterSilentTrackNumber ) )
1925             {
1926                 KaxClusterSilentTrackNumber &track_num = *(KaxClusterSilentTrackNumber*)el;
1927                 track_num.ReadData( es.I_O() );
1928                 // find the track
1929                 for (size_t i=0; i<tracks.size(); i++)
1930                 {
1931                     if ( tracks[i]->i_number == uint32(track_num))
1932                     {
1933                         tracks[i]->b_silent = true;
1934                         break;
1935                     }
1936                 }
1937             }
1938             break;
1939         default:
1940             msg_Err( &sys.demuxer, "invalid level = %d", i_level );
1941             return VLC_EGENERIC;
1942         }
1943     }
1944 }
1945
1946 static block_t *MemToBlock( demux_t *p_demux, uint8_t *p_mem, int i_mem, size_t offset)
1947 {
1948     block_t *p_block;
1949     if( !(p_block = block_New( p_demux, i_mem + offset ) ) ) return NULL;
1950     memcpy( p_block->p_buffer + offset, p_mem, i_mem );
1951     //p_block->i_rate = p_input->stream.control.i_rate;
1952     return p_block;
1953 }
1954
1955 #if LIBMATROSKA_VERSION >= 0x000800
1956 static void BlockDecode( demux_t *p_demux, KaxBlock *block, KaxSimpleBlock *simpleblock,
1957                          mtime_t i_pts, mtime_t i_duration, bool f_mandatory )
1958 #else
1959 static void BlockDecode( demux_t *p_demux, KaxBlock *block, mtime_t i_pts,
1960                          mtime_t i_duration, bool f_mandatory )
1961 #endif
1962 {
1963     demux_sys_t        *p_sys = p_demux->p_sys;
1964     matroska_segment_c *p_segment = p_sys->p_current_segment->Segment();
1965
1966     size_t          i_track;
1967     unsigned int    i;
1968     bool            b;
1969
1970 #define tk  p_segment->tracks[i_track]
1971     for( i_track = 0; i_track < p_segment->tracks.size(); i_track++ )
1972     {
1973 #if LIBMATROSKA_VERSION >= 0x000800
1974         if( (block != NULL && tk->i_number == block->TrackNum()) ||
1975             (simpleblock != NULL && tk->i_number == simpleblock->TrackNum()))
1976 #else
1977         if( tk->i_number == block->TrackNum() )
1978 #endif
1979         {
1980             break;
1981         }
1982     }
1983
1984     if( i_track >= p_segment->tracks.size() )
1985     {
1986         msg_Err( p_demux, "invalid track number" );
1987         return;
1988     }
1989     if( tk->fmt.i_cat != NAV_ES && tk->p_es == NULL )
1990     {
1991         msg_Err( p_demux, "unknown track number" );
1992         return;
1993     }
1994     if( i_pts + i_duration < p_sys->i_start_pts && tk->fmt.i_cat == AUDIO_ES )
1995     {
1996         return; /* discard audio packets that shouldn't be rendered */
1997     }
1998
1999     if ( tk->fmt.i_cat != NAV_ES )
2000     {
2001         es_out_Control( p_demux->out, ES_OUT_GET_ES_STATE, tk->p_es, &b );
2002
2003         if( !b )
2004         {
2005             tk->b_inited = false;
2006             return;
2007         }
2008     }
2009
2010
2011     /* First send init data */
2012     if( !tk->b_inited && tk->i_data_init > 0 )
2013     {
2014         block_t *p_init;
2015
2016         msg_Dbg( p_demux, "sending header (%d bytes)", tk->i_data_init );
2017         p_init = MemToBlock( p_demux, tk->p_data_init, tk->i_data_init, 0 );
2018         if( p_init ) es_out_Send( p_demux->out, tk->p_es, p_init );
2019     }
2020     tk->b_inited = true;
2021
2022
2023 #if LIBMATROSKA_VERSION >= 0x000800
2024     for( i = 0;
2025         (block != NULL && i < block->NumberFrames()) || (simpleblock != NULL && i < simpleblock->NumberFrames());
2026         i++ )
2027 #else
2028     for( i = 0; i < block->NumberFrames(); i++ )
2029 #endif
2030     {
2031         block_t *p_block;
2032         DataBuffer *data;
2033 #if LIBMATROSKA_VERSION >= 0x000800
2034         if ( simpleblock != NULL )
2035         {
2036             data = &simpleblock->GetBuffer(i);
2037             // condition when the DTS is correct (keyframe or B frame == NOT P frame)
2038             f_mandatory = simpleblock->IsDiscardable() || simpleblock->IsKeyframe();
2039         }
2040         else
2041 #endif
2042         data = &block->GetBuffer(i);
2043
2044         if( tk->i_compression_type == MATROSKA_COMPRESSION_HEADER && tk->p_compression_data != NULL )
2045             p_block = MemToBlock( p_demux, data->Buffer(), data->Size(), tk->p_compression_data->GetSize() );
2046         else
2047             p_block = MemToBlock( p_demux, data->Buffer(), data->Size(), 0 );
2048
2049         if( p_block == NULL )
2050         {
2051             break;
2052         }
2053
2054 #if defined(HAVE_ZLIB_H)
2055         if( tk->i_compression_type == MATROSKA_COMPRESSION_ZLIB )
2056         {
2057             p_block = block_zlib_decompress( VLC_OBJECT(p_demux), p_block );
2058         }
2059         else
2060 #endif
2061         if( tk->i_compression_type == MATROSKA_COMPRESSION_HEADER )
2062         {
2063             memcpy( p_block->p_buffer, tk->p_compression_data->GetBuffer(), tk->p_compression_data->GetSize() );
2064         }
2065
2066         if ( tk->fmt.i_cat == NAV_ES )
2067         {
2068             // TODO handle the start/stop times of this packet
2069             if ( p_sys->b_ui_hooked )
2070             {
2071                 vlc_mutex_lock( &p_sys->p_ev->lock );
2072                 memcpy( &p_sys->pci_packet, &p_block->p_buffer[1], sizeof(pci_t) );
2073                 p_sys->SwapButtons();
2074                 p_sys->b_pci_packet_set = true;
2075                 vlc_mutex_unlock( &p_sys->p_ev->lock );
2076                 block_Release( p_block );
2077             }
2078             return;
2079         }
2080         // correct timestamping when B frames are used
2081         if( tk->fmt.i_cat != VIDEO_ES )
2082         {
2083             p_block->i_dts = p_block->i_pts = i_pts;
2084         }
2085         else
2086         {
2087             if( !strcmp( tk->psz_codec, "V_MS/VFW/FOURCC" ) )
2088             {
2089                 // in VFW we have no idea about B frames
2090                 p_block->i_pts = 0;
2091                 p_block->i_dts = i_pts;
2092             }
2093             else
2094             {
2095                 p_block->i_pts = i_pts;
2096                 if ( f_mandatory )
2097                     p_block->i_dts = p_block->i_pts;
2098                 else
2099                     p_block->i_dts = min( i_pts, tk->i_last_dts + (mtime_t)(tk->i_default_duration >> 10));
2100                 p_sys->i_pts = p_block->i_dts;
2101             }
2102         }
2103         tk->i_last_dts = p_block->i_dts;
2104
2105 #if 0
2106 msg_Dbg( p_demux, "block i_dts: %"PRId64" / i_pts: %"PRId64, p_block->i_dts, p_block->i_pts);
2107 #endif
2108         if( strcmp( tk->psz_codec, "S_VOBSUB" ) )
2109         {
2110             p_block->i_length = i_duration * 1000;
2111         }
2112
2113         es_out_Send( p_demux->out, tk->p_es, p_block );
2114
2115         /* use time stamp only for first block */
2116         i_pts = 0;
2117     }
2118
2119 #undef tk
2120 }
2121
2122 matroska_stream_c *demux_sys_t::AnalyseAllSegmentsFound( demux_t *p_demux, EbmlStream *p_estream, bool b_initial )
2123 {
2124     int i_upper_lvl = 0;
2125     size_t i;
2126     EbmlElement *p_l0, *p_l1, *p_l2;
2127     bool b_keep_stream = false, b_keep_segment;
2128
2129     // verify the EBML Header
2130     p_l0 = p_estream->FindNextID(EbmlHead::ClassInfos, 0xFFFFFFFFL);
2131     if (p_l0 == NULL)
2132     {
2133         msg_Err( p_demux, "No EBML header found" );
2134         return NULL;
2135     }
2136
2137     // verify we can read this Segment, we only support Matroska version 1 for now
2138     p_l0->Read(*p_estream, EbmlHead::ClassInfos.Context, i_upper_lvl, p_l0, true);
2139
2140     EDocType doc_type = GetChild<EDocType>(*static_cast<EbmlHead*>(p_l0));
2141     if (std::string(doc_type) != "matroska")
2142     {
2143         msg_Err( p_demux, "Not a Matroska file : DocType = %s ", std::string(doc_type).c_str());
2144         return NULL;
2145     }
2146
2147     EDocTypeReadVersion doc_read_version = GetChild<EDocTypeReadVersion>(*static_cast<EbmlHead*>(p_l0));
2148 #if LIBMATROSKA_VERSION >= 0x000800
2149     if (uint64(doc_read_version) > 2)
2150     {
2151         msg_Err( p_demux, "This matroska file is needs version %"PRId64" and this VLC only supports version 1 & 2", uint64(doc_read_version));
2152         return NULL;
2153     }
2154 #else
2155     if (uint64(doc_read_version) != 1)
2156     {
2157         msg_Err( p_demux, "This matroska file is needs version %"PRId64" and this VLC only supports version 1", uint64(doc_read_version));
2158         return NULL;
2159     }
2160 #endif
2161
2162     delete p_l0;
2163
2164
2165     // find all segments in this file
2166     p_l0 = p_estream->FindNextID(KaxSegment::ClassInfos, 0xFFFFFFFFFLL);
2167     if (p_l0 == NULL)
2168     {
2169         return NULL;
2170     }
2171
2172     matroska_stream_c *p_stream1 = new matroska_stream_c( *this );
2173
2174     while (p_l0 != 0)
2175     {
2176         if (EbmlId(*p_l0) == KaxSegment::ClassInfos.GlobalId)
2177         {
2178             EbmlParser  *ep;
2179             matroska_segment_c *p_segment1 = new matroska_segment_c( *this, *p_estream );
2180             b_keep_segment = b_initial;
2181
2182             ep = new EbmlParser(p_estream, p_l0, &demuxer );
2183             p_segment1->ep = ep;
2184             p_segment1->segment = (KaxSegment*)p_l0;
2185
2186             while ((p_l1 = ep->Get()))
2187             {
2188                 if (MKV_IS_ID(p_l1, KaxInfo))
2189                 {
2190                     // find the families of this segment
2191                     KaxInfo *p_info = static_cast<KaxInfo*>(p_l1);
2192
2193                     p_info->Read(*p_estream, KaxInfo::ClassInfos.Context, i_upper_lvl, p_l2, true);
2194                     for( i = 0; i < p_info->ListSize(); i++ )
2195                     {
2196                         EbmlElement *l = (*p_info)[i];
2197
2198                         if( MKV_IS_ID( l, KaxSegmentUID ) )
2199                         {
2200                             KaxSegmentUID *p_uid = static_cast<KaxSegmentUID*>(l);
2201                             b_keep_segment = (FindSegment( *p_uid ) == NULL);
2202                             if ( !b_keep_segment )
2203                                 break; // this segment is already known
2204                             opened_segments.push_back( p_segment1 );
2205                             delete p_segment1->p_segment_uid;
2206                             p_segment1->p_segment_uid = new KaxSegmentUID(*p_uid);
2207                         }
2208                         else if( MKV_IS_ID( l, KaxPrevUID ) )
2209                         {
2210                             p_segment1->p_prev_segment_uid = new KaxPrevUID( *static_cast<KaxPrevUID*>(l) );
2211                         }
2212                         else if( MKV_IS_ID( l, KaxNextUID ) )
2213                         {
2214                             p_segment1->p_next_segment_uid = new KaxNextUID( *static_cast<KaxNextUID*>(l) );
2215                         }
2216                         else if( MKV_IS_ID( l, KaxSegmentFamily ) )
2217                         {
2218                             KaxSegmentFamily *p_fam = new KaxSegmentFamily( *static_cast<KaxSegmentFamily*>(l) );
2219                             p_segment1->families.push_back( p_fam );
2220                         }
2221                     }
2222                     break;
2223                 }
2224             }
2225             if ( b_keep_segment )
2226             {
2227                 b_keep_stream = true;
2228                 p_stream1->segments.push_back( p_segment1 );
2229             }
2230             else
2231             {
2232                 p_segment1->segment = NULL;
2233                 delete p_segment1;
2234             }
2235         }
2236         if (p_l0->IsFiniteSize() )
2237         {
2238             p_l0->SkipData(*p_estream, KaxMatroska_Context);
2239             p_l0 = p_estream->FindNextID(KaxSegment::ClassInfos, 0xFFFFFFFFL);
2240         }
2241         else
2242             p_l0 = p_l0->SkipData(*p_estream, KaxSegment_Context);
2243     }
2244
2245     if ( !b_keep_stream )
2246     {
2247         delete p_stream1;
2248         p_stream1 = NULL;
2249     }
2250
2251     return p_stream1;
2252 }
2253
2254 bool matroska_segment_c::Select( mtime_t i_start_time )
2255 {
2256     size_t i_track;
2257
2258     /* add all es */
2259     msg_Dbg( &sys.demuxer, "found %d es", (int)tracks.size() );
2260     sys.b_pci_packet_set = false;
2261
2262     for( i_track = 0; i_track < tracks.size(); i_track++ )
2263     {
2264         if( tracks[i_track]->fmt.i_cat == UNKNOWN_ES )
2265         {
2266             msg_Warn( &sys.demuxer, "invalid track[%d, n=%d]", (int)i_track, tracks[i_track]->i_number );
2267             tracks[i_track]->p_es = NULL;
2268             continue;
2269         }
2270
2271         if( !strcmp( tracks[i_track]->psz_codec, "V_MS/VFW/FOURCC" ) )
2272         {
2273             if( tracks[i_track]->i_extra_data < (int)sizeof( BITMAPINFOHEADER ) )
2274             {
2275                 msg_Err( &sys.demuxer, "missing/invalid BITMAPINFOHEADER" );
2276                 tracks[i_track]->fmt.i_codec = VLC_FOURCC( 'u', 'n', 'd', 'f' );
2277             }
2278             else
2279             {
2280                 BITMAPINFOHEADER *p_bih = (BITMAPINFOHEADER*)tracks[i_track]->p_extra_data;
2281
2282                 tracks[i_track]->fmt.video.i_width = GetDWLE( &p_bih->biWidth );
2283                 tracks[i_track]->fmt.video.i_height= GetDWLE( &p_bih->biHeight );
2284                 tracks[i_track]->fmt.i_codec       = GetFOURCC( &p_bih->biCompression );
2285
2286                 tracks[i_track]->fmt.i_extra       = GetDWLE( &p_bih->biSize ) - sizeof( BITMAPINFOHEADER );
2287                 if( tracks[i_track]->fmt.i_extra > 0 )
2288                 {
2289                     tracks[i_track]->fmt.p_extra = malloc( tracks[i_track]->fmt.i_extra );
2290                     memcpy( tracks[i_track]->fmt.p_extra, &p_bih[1], tracks[i_track]->fmt.i_extra );
2291                 }
2292             }
2293         }
2294         else if( !strcmp( tracks[i_track]->psz_codec, "V_MPEG1" ) ||
2295                  !strcmp( tracks[i_track]->psz_codec, "V_MPEG2" ) )
2296         {
2297             tracks[i_track]->fmt.i_codec = VLC_FOURCC( 'm', 'p', 'g', 'v' );
2298         }
2299         else if( !strncmp( tracks[i_track]->psz_codec, "V_THEORA", 8 ) )
2300         {
2301             uint8_t *p_data = tracks[i_track]->p_extra_data;
2302             tracks[i_track]->fmt.i_codec = VLC_FOURCC( 't', 'h', 'e', 'o' );
2303             if( tracks[i_track]->i_extra_data >= 4 ) {
2304                 if( p_data[0] == 2 ) {
2305                     int i = 1;
2306                     int i_size1 = 0, i_size2 = 0;
2307                     p_data++;
2308                     /* read size of first header packet */
2309                     while( *p_data == 0xFF &&
2310                            i < tracks[i_track]->i_extra_data )
2311                     {
2312                         i_size1 += *p_data;
2313                         p_data++;
2314                         i++;
2315                     }
2316                     i_size1 += *p_data;
2317                     p_data++;
2318                     i++;
2319                     msg_Dbg( &sys.demuxer, "first theora header size %d", i_size1 );
2320                     /* read size of second header packet */
2321                     while( *p_data == 0xFF &&
2322                            i < tracks[i_track]->i_extra_data )
2323                     {
2324                         i_size2 += *p_data;
2325                         p_data++;
2326                         i++;
2327                     }
2328                     i_size2 += *p_data;
2329                     p_data++;
2330                     i++;
2331                     int i_size3 = tracks[i_track]->i_extra_data - i - i_size1
2332                         - i_size2;
2333                     msg_Dbg( &sys.demuxer, "second theora header size %d", i_size2 );
2334                     msg_Dbg( &sys.demuxer, "third theora header size %d", i_size3 );
2335                     tracks[i_track]->fmt.i_extra = i_size1 + i_size2 + i_size3
2336                         + 6;
2337                     if( i_size1 > 0 && i_size2 > 0 && i_size3 > 0  ) {
2338                         tracks[i_track]->fmt.p_extra =
2339                             malloc( tracks[i_track]->fmt.i_extra );
2340                         uint8_t *p_out = (uint8_t*)tracks[i_track]->fmt.p_extra;
2341                         *p_out++ = (i_size1>>8) & 0xFF;
2342                         *p_out++ = i_size1 & 0xFF;
2343                         memcpy( p_out, p_data, i_size1 );
2344                         p_data += i_size1;
2345                         p_out += i_size1;
2346  
2347                         *p_out++ = (i_size2>>8) & 0xFF;
2348                         *p_out++ = i_size2 & 0xFF;
2349                         memcpy( p_out, p_data, i_size2 );
2350                         p_data += i_size2;
2351                         p_out += i_size2;
2352
2353                         *p_out++ = (i_size3>>8) & 0xFF;
2354                         *p_out++ = i_size3 & 0xFF;
2355                         memcpy( p_out, p_data, i_size3 );
2356                         p_data += i_size3;
2357                         p_out += i_size3;
2358                     }
2359                     else
2360                     {
2361                         msg_Err( &sys.demuxer, "inconsistant theora extradata" );
2362                     }
2363                 }
2364                 else {
2365                     msg_Err( &sys.demuxer, "Wrong number of ogg packets with theora headers (%d)", p_data[0] + 1 );
2366                 }
2367             }
2368         }
2369         else if( !strncmp( tracks[i_track]->psz_codec, "V_REAL/RV", 9 ) )
2370         {
2371             if( !strcmp( tracks[i_track]->psz_codec, "V_REAL/RV10" ) )
2372                 tracks[i_track]->fmt.i_codec = VLC_FOURCC( 'R', 'V', '1', '0' );
2373             else if( !strcmp( tracks[i_track]->psz_codec, "V_REAL/RV20" ) )
2374                 tracks[i_track]->fmt.i_codec = VLC_FOURCC( 'R', 'V', '2', '0' );
2375             else if( !strcmp( tracks[i_track]->psz_codec, "V_REAL/RV30" ) )
2376                 tracks[i_track]->fmt.i_codec = VLC_FOURCC( 'R', 'V', '3', '0' );
2377             else if( !strcmp( tracks[i_track]->psz_codec, "V_REAL/RV40" ) )
2378                 tracks[i_track]->fmt.i_codec = VLC_FOURCC( 'R', 'V', '4', '0' );
2379         }
2380         else if( !strncmp( tracks[i_track]->psz_codec, "V_MPEG4", 7 ) )
2381         {
2382             if( !strcmp( tracks[i_track]->psz_codec, "V_MPEG4/MS/V3" ) )
2383             {
2384                 tracks[i_track]->fmt.i_codec = VLC_FOURCC( 'D', 'I', 'V', '3' );
2385             }
2386             else if( !strncmp( tracks[i_track]->psz_codec, "V_MPEG4/ISO", 11 ) )
2387             {
2388                 /* A MPEG 4 codec, SP, ASP, AP or AVC */
2389                 if( !strcmp( tracks[i_track]->psz_codec, "V_MPEG4/ISO/AVC" ) )
2390                     tracks[i_track]->fmt.i_codec = VLC_FOURCC( 'a', 'v', 'c', '1' );
2391                 else
2392                     tracks[i_track]->fmt.i_codec = VLC_FOURCC( 'm', 'p', '4', 'v' );
2393                 tracks[i_track]->fmt.i_extra = tracks[i_track]->i_extra_data;
2394                 tracks[i_track]->fmt.p_extra = malloc( tracks[i_track]->i_extra_data );
2395                 memcpy( tracks[i_track]->fmt.p_extra,tracks[i_track]->p_extra_data, tracks[i_track]->i_extra_data );
2396             }
2397         }
2398         else if( !strcmp( tracks[i_track]->psz_codec, "V_QUICKTIME" ) )
2399         {
2400             MP4_Box_t *p_box = (MP4_Box_t*)malloc( sizeof( MP4_Box_t ) );
2401             stream_t *p_mp4_stream = stream_MemoryNew( VLC_OBJECT(&sys.demuxer),
2402                                                        tracks[i_track]->p_extra_data,
2403                                                        tracks[i_track]->i_extra_data,
2404                                                        false );
2405             MP4_ReadBoxCommon( p_mp4_stream, p_box );
2406             MP4_ReadBox_sample_vide( p_mp4_stream, p_box );
2407             tracks[i_track]->fmt.i_codec = p_box->i_type;
2408             tracks[i_track]->fmt.video.i_width = p_box->data.p_sample_vide->i_width;
2409             tracks[i_track]->fmt.video.i_height = p_box->data.p_sample_vide->i_height;
2410             tracks[i_track]->fmt.i_extra = p_box->data.p_sample_vide->i_qt_image_description;
2411             tracks[i_track]->fmt.p_extra = malloc( tracks[i_track]->fmt.i_extra );
2412             memcpy( tracks[i_track]->fmt.p_extra, p_box->data.p_sample_vide->p_qt_image_description, tracks[i_track]->fmt.i_extra );
2413             MP4_FreeBox_sample_vide( p_box );
2414             stream_Delete( p_mp4_stream );
2415         }
2416         else if( !strcmp( tracks[i_track]->psz_codec, "A_MS/ACM" ) )
2417         {
2418             if( tracks[i_track]->i_extra_data < (int)sizeof( WAVEFORMATEX ) )
2419             {
2420                 msg_Err( &sys.demuxer, "missing/invalid WAVEFORMATEX" );
2421                 tracks[i_track]->fmt.i_codec = VLC_FOURCC( 'u', 'n', 'd', 'f' );
2422             }
2423             else
2424             {
2425                 WAVEFORMATEX *p_wf = (WAVEFORMATEX*)tracks[i_track]->p_extra_data;
2426
2427                 wf_tag_to_fourcc( GetWLE( &p_wf->wFormatTag ), &tracks[i_track]->fmt.i_codec, NULL );
2428
2429                 tracks[i_track]->fmt.audio.i_channels   = GetWLE( &p_wf->nChannels );
2430                 tracks[i_track]->fmt.audio.i_rate = GetDWLE( &p_wf->nSamplesPerSec );
2431                 tracks[i_track]->fmt.i_bitrate    = GetDWLE( &p_wf->nAvgBytesPerSec ) * 8;
2432                 tracks[i_track]->fmt.audio.i_blockalign = GetWLE( &p_wf->nBlockAlign );;
2433                 tracks[i_track]->fmt.audio.i_bitspersample = GetWLE( &p_wf->wBitsPerSample );
2434
2435                 tracks[i_track]->fmt.i_extra            = GetWLE( &p_wf->cbSize );
2436                 if( tracks[i_track]->fmt.i_extra > 0 )
2437                 {
2438                     tracks[i_track]->fmt.p_extra = malloc( tracks[i_track]->fmt.i_extra );
2439                     memcpy( tracks[i_track]->fmt.p_extra, &p_wf[1], tracks[i_track]->fmt.i_extra );
2440                 }
2441             }
2442         }
2443         else if( !strcmp( tracks[i_track]->psz_codec, "A_MPEG/L3" ) ||
2444                  !strcmp( tracks[i_track]->psz_codec, "A_MPEG/L2" ) ||
2445                  !strcmp( tracks[i_track]->psz_codec, "A_MPEG/L1" ) )
2446         {
2447             tracks[i_track]->fmt.i_codec = VLC_FOURCC( 'm', 'p', 'g', 'a' );
2448         }
2449         else if( !strcmp( tracks[i_track]->psz_codec, "A_AC3" ) )
2450         {
2451             tracks[i_track]->fmt.i_codec = VLC_FOURCC( 'a', '5', '2', ' ' );
2452         }
2453         else if( !strcmp( tracks[i_track]->psz_codec, "A_DTS" ) )
2454         {
2455             tracks[i_track]->fmt.i_codec = VLC_FOURCC( 'd', 't', 's', ' ' );
2456         }
2457         else if( !strcmp( tracks[i_track]->psz_codec, "A_FLAC" ) )
2458         {
2459             tracks[i_track]->fmt.i_codec = VLC_FOURCC( 'f', 'l', 'a', 'c' );
2460             tracks[i_track]->fmt.i_extra = tracks[i_track]->i_extra_data;
2461             tracks[i_track]->fmt.p_extra = malloc( tracks[i_track]->i_extra_data );
2462             memcpy( tracks[i_track]->fmt.p_extra,tracks[i_track]->p_extra_data, tracks[i_track]->i_extra_data );
2463         }
2464         else if( !strcmp( tracks[i_track]->psz_codec, "A_VORBIS" ) )
2465         {
2466             int i, i_offset = 1, i_size[3], i_extra;
2467             uint8_t *p_extra;
2468
2469             tracks[i_track]->fmt.i_codec = VLC_FOURCC( 'v', 'o', 'r', 'b' );
2470
2471             /* Split the 3 headers */
2472             if( tracks[i_track]->p_extra_data[0] != 0x02 )
2473                 msg_Err( &sys.demuxer, "invalid vorbis header" );
2474
2475             for( i = 0; i < 2; i++ )
2476             {
2477                 i_size[i] = 0;
2478                 while( i_offset < tracks[i_track]->i_extra_data )
2479                 {
2480                     i_size[i] += tracks[i_track]->p_extra_data[i_offset];
2481                     if( tracks[i_track]->p_extra_data[i_offset++] != 0xff ) break;
2482                 }
2483             }
2484
2485             i_size[0] = __MIN(i_size[0], tracks[i_track]->i_extra_data - i_offset);
2486             i_size[1] = __MIN(i_size[1], tracks[i_track]->i_extra_data -i_offset -i_size[0]);
2487             i_size[2] = tracks[i_track]->i_extra_data - i_offset - i_size[0] - i_size[1];
2488
2489             tracks[i_track]->fmt.i_extra = 3 * 2 + i_size[0] + i_size[1] + i_size[2];
2490             tracks[i_track]->fmt.p_extra = malloc( tracks[i_track]->fmt.i_extra );
2491             p_extra = (uint8_t *)tracks[i_track]->fmt.p_extra; i_extra = 0;
2492             for( i = 0; i < 3; i++ )
2493             {
2494                 *(p_extra++) = i_size[i] >> 8;
2495                 *(p_extra++) = i_size[i] & 0xFF;
2496                 memcpy( p_extra, tracks[i_track]->p_extra_data + i_offset + i_extra,
2497                         i_size[i] );
2498                 p_extra += i_size[i];
2499                 i_extra += i_size[i];
2500             }
2501         }
2502         else if( !strncmp( tracks[i_track]->psz_codec, "A_AAC/MPEG2/", strlen( "A_AAC/MPEG2/" ) ) ||
2503                  !strncmp( tracks[i_track]->psz_codec, "A_AAC/MPEG4/", strlen( "A_AAC/MPEG4/" ) ) )
2504         {
2505             int i_profile, i_srate, sbr = 0;
2506             static const unsigned int i_sample_rates[] =
2507             {
2508                     96000, 88200, 64000, 48000, 44100, 32000, 24000, 22050,
2509                         16000, 12000, 11025, 8000,  7350,  0,     0,     0
2510             };
2511
2512             tracks[i_track]->fmt.i_codec = VLC_FOURCC( 'm', 'p', '4', 'a' );
2513             /* create data for faad (MP4DecSpecificDescrTag)*/
2514
2515             if( !strcmp( &tracks[i_track]->psz_codec[12], "MAIN" ) )
2516             {
2517                 i_profile = 0;
2518             }
2519             else if( !strcmp( &tracks[i_track]->psz_codec[12], "LC" ) )
2520             {
2521                 i_profile = 1;
2522             }
2523             else if( !strcmp( &tracks[i_track]->psz_codec[12], "SSR" ) )
2524             {
2525                 i_profile = 2;
2526             }
2527             else if( !strcmp( &tracks[i_track]->psz_codec[12], "LC/SBR" ) )
2528             {
2529                 i_profile = 1;
2530                 sbr = 1;
2531             }
2532             else
2533             {
2534                 i_profile = 3;
2535             }
2536
2537             for( i_srate = 0; i_srate < 13; i_srate++ )
2538             {
2539                 if( i_sample_rates[i_srate] == tracks[i_track]->i_original_rate )
2540                 {
2541                     break;
2542                 }
2543             }
2544             msg_Dbg( &sys.demuxer, "profile=%d srate=%d", i_profile, i_srate );
2545
2546             tracks[i_track]->fmt.i_extra = sbr ? 5 : 2;
2547             tracks[i_track]->fmt.p_extra = malloc( tracks[i_track]->fmt.i_extra );
2548             ((uint8_t*)tracks[i_track]->fmt.p_extra)[0] = ((i_profile + 1) << 3) | ((i_srate&0xe) >> 1);
2549             ((uint8_t*)tracks[i_track]->fmt.p_extra)[1] = ((i_srate & 0x1) << 7) | (tracks[i_track]->fmt.audio.i_channels << 3);
2550             if (sbr != 0)
2551             {
2552                 int syncExtensionType = 0x2B7;
2553                 int iDSRI;
2554                 for (iDSRI=0; iDSRI<13; iDSRI++)
2555                     if( i_sample_rates[iDSRI] == tracks[i_track]->fmt.audio.i_rate )
2556                         break;
2557                 ((uint8_t*)tracks[i_track]->fmt.p_extra)[2] = (syncExtensionType >> 3) & 0xFF;
2558                 ((uint8_t*)tracks[i_track]->fmt.p_extra)[3] = ((syncExtensionType & 0x7) << 5) | 5;
2559                 ((uint8_t*)tracks[i_track]->fmt.p_extra)[4] = ((1 & 0x1) << 7) | (iDSRI << 3);
2560             }
2561         }
2562         else if( !strcmp( tracks[i_track]->psz_codec, "A_AAC" ) )
2563         {
2564             tracks[i_track]->fmt.i_codec = VLC_FOURCC( 'm', 'p', '4', 'a' );
2565             tracks[i_track]->fmt.i_extra = tracks[i_track]->i_extra_data;
2566             tracks[i_track]->fmt.p_extra = malloc( tracks[i_track]->i_extra_data );
2567             memcpy( tracks[i_track]->fmt.p_extra, tracks[i_track]->p_extra_data, tracks[i_track]->i_extra_data );
2568         }
2569         else if( !strcmp( tracks[i_track]->psz_codec, "A_WAVPACK4" ) )
2570         {
2571             tracks[i_track]->fmt.i_codec = VLC_FOURCC( 'W', 'V', 'P', 'K' );
2572             tracks[i_track]->fmt.i_extra = tracks[i_track]->i_extra_data;
2573             tracks[i_track]->fmt.p_extra = malloc( tracks[i_track]->i_extra_data );
2574             memcpy( tracks[i_track]->fmt.p_extra, tracks[i_track]->p_extra_data, tracks[i_track]->i_extra_data );
2575         }
2576         else if( !strcmp( tracks[i_track]->psz_codec, "A_TTA1" ) )
2577         {
2578             tracks[i_track]->fmt.i_codec = VLC_FOURCC( 'T', 'T', 'A', '1' );
2579             tracks[i_track]->fmt.i_extra = tracks[i_track]->i_extra_data;
2580             tracks[i_track]->fmt.p_extra = malloc( tracks[i_track]->i_extra_data );
2581             memcpy( tracks[i_track]->fmt.p_extra, tracks[i_track]->p_extra_data, tracks[i_track]->i_extra_data );
2582         }
2583         else if( !strcmp( tracks[i_track]->psz_codec, "A_PCM/INT/BIG" ) ||
2584                  !strcmp( tracks[i_track]->psz_codec, "A_PCM/INT/LIT" ) ||
2585                  !strcmp( tracks[i_track]->psz_codec, "A_PCM/FLOAT/IEEE" ) )
2586         {
2587             if( !strcmp( tracks[i_track]->psz_codec, "A_PCM/INT/BIG" ) )
2588             {
2589                 tracks[i_track]->fmt.i_codec = VLC_FOURCC( 't', 'w', 'o', 's' );
2590             }
2591             else
2592             {
2593                 tracks[i_track]->fmt.i_codec = VLC_FOURCC( 'a', 'r', 'a', 'w' );
2594             }
2595             tracks[i_track]->fmt.audio.i_blockalign = ( tracks[i_track]->fmt.audio.i_bitspersample + 7 ) / 8 * tracks[i_track]->fmt.audio.i_channels;
2596         }
2597         /* disabled due to the potential "S_KATE" namespace issue */
2598         else if( !strcmp( tracks[i_track]->psz_codec, "S_KATE" ) )
2599         {
2600             int i, i_offset = 1, *i_size, i_extra, num_headers, size_so_far;
2601             uint8_t *p_extra;
2602
2603             tracks[i_track]->fmt.i_codec = VLC_FOURCC( 'k', 'a', 't', 'e' );
2604             tracks[i_track]->fmt.subs.psz_encoding = strdup( "UTF-8" );
2605
2606             /* Recover the number of headers to expect */
2607             num_headers = tracks[i_track]->p_extra_data[0]+1;
2608             msg_Dbg( &sys.demuxer, "kate in mkv detected: %d headers in %u bytes",
2609                 num_headers, tracks[i_track]->i_extra_data);
2610
2611             /* this won't overflow the stack as is can allocate only 1020 bytes max */
2612             i_size = (int*)alloca(num_headers*sizeof(int));
2613
2614             /* Split the headers */
2615             size_so_far = 0;
2616             for( i = 0; i < num_headers-1; i++ )
2617             {
2618                 i_size[i] = 0;
2619                 while( i_offset < tracks[i_track]->i_extra_data )
2620                 {
2621                     i_size[i] += tracks[i_track]->p_extra_data[i_offset];
2622                     if( tracks[i_track]->p_extra_data[i_offset++] != 0xff ) break;
2623                 }
2624                 msg_Dbg( &sys.demuxer, "kate header %d is %d bytes", i, i_size[i]);
2625                 size_so_far += i_size[i];
2626             }
2627             i_size[num_headers-1] = tracks[i_track]->i_extra_data - (size_so_far+i_offset);
2628             msg_Dbg( &sys.demuxer, "kate last header (%d) is %d bytes", num_headers-1, i_size[num_headers-1]);
2629
2630             tracks[i_track]->fmt.i_extra = 1 + num_headers * 2 + size_so_far + i_size[num_headers-1];
2631             tracks[i_track]->fmt.p_extra = malloc( tracks[i_track]->fmt.i_extra );
2632
2633             p_extra = (uint8_t *)tracks[i_track]->fmt.p_extra;
2634             i_extra = 0;
2635             *(p_extra++) = num_headers;
2636             ++i_extra;
2637             for( i = 0; i < num_headers; i++ )
2638             {
2639                 *(p_extra++) = i_size[i] >> 8;
2640                 *(p_extra++) = i_size[i] & 0xFF;
2641                 memcpy( p_extra, tracks[i_track]->p_extra_data + i_offset + i_extra-1,
2642                         i_size[i] );
2643                 p_extra += i_size[i];
2644                 i_extra += i_size[i];
2645             }
2646         }
2647         else if( !strcmp( tracks[i_track]->psz_codec, "S_TEXT/UTF8" ) )
2648         {
2649             tracks[i_track]->fmt.i_codec = VLC_FOURCC( 's', 'u', 'b', 't' );
2650             tracks[i_track]->fmt.subs.psz_encoding = strdup( "UTF-8" );
2651         }
2652         else if( !strcmp( tracks[i_track]->psz_codec, "S_TEXT/USF" ) )
2653         {
2654             tracks[i_track]->fmt.i_codec = VLC_FOURCC( 'u', 's', 'f', ' ' );
2655             tracks[i_track]->fmt.subs.psz_encoding = strdup( "UTF-8" );
2656             if( tracks[i_track]->i_extra_data )
2657             {
2658                 tracks[i_track]->fmt.i_extra = tracks[i_track]->i_extra_data;
2659                 tracks[i_track]->fmt.p_extra = malloc( tracks[i_track]->i_extra_data );
2660                 memcpy( tracks[i_track]->fmt.p_extra, tracks[i_track]->p_extra_data, tracks[i_track]->i_extra_data );
2661             }
2662         }
2663         else if( !strcmp( tracks[i_track]->psz_codec, "S_TEXT/SSA" ) ||
2664                  !strcmp( tracks[i_track]->psz_codec, "S_TEXT/ASS" ) ||
2665                  !strcmp( tracks[i_track]->psz_codec, "S_SSA" ) ||
2666                  !strcmp( tracks[i_track]->psz_codec, "S_ASS" ))
2667         {
2668             tracks[i_track]->fmt.i_codec = VLC_FOURCC( 's', 's', 'a', ' ' );
2669             tracks[i_track]->fmt.subs.psz_encoding = strdup( "UTF-8" );
2670             if( tracks[i_track]->i_extra_data )
2671             {
2672                 tracks[i_track]->fmt.i_extra = tracks[i_track]->i_extra_data;
2673                 tracks[i_track]->fmt.p_extra = malloc( tracks[i_track]->i_extra_data );
2674                 memcpy( tracks[i_track]->fmt.p_extra, tracks[i_track]->p_extra_data, tracks[i_track]->i_extra_data );
2675             }
2676         }
2677         else if( !strcmp( tracks[i_track]->psz_codec, "S_VOBSUB" ) )
2678         {
2679             tracks[i_track]->fmt.i_codec = VLC_FOURCC( 's','p','u',' ' );
2680             if( tracks[i_track]->i_extra_data )
2681             {
2682                 char *p_start;
2683                 char *p_buf = (char *)malloc( tracks[i_track]->i_extra_data + 1);
2684                 memcpy( p_buf, tracks[i_track]->p_extra_data , tracks[i_track]->i_extra_data );
2685                 p_buf[tracks[i_track]->i_extra_data] = '\0';
2686  
2687                 p_start = strstr( p_buf, "size:" );
2688                 if( sscanf( p_start, "size: %dx%d",
2689                         &tracks[i_track]->fmt.subs.spu.i_original_frame_width, &tracks[i_track]->fmt.subs.spu.i_original_frame_height ) == 2 )
2690                 {
2691                     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 );
2692                 }
2693                 else
2694                 {
2695                     msg_Warn( &sys.demuxer, "reading original frame size for vobsub failed" );
2696                 }
2697                 free( p_buf );
2698             }
2699         }
2700         else if( !strcmp( tracks[i_track]->psz_codec, "B_VOBBTN" ) )
2701         {
2702             tracks[i_track]->fmt.i_cat = NAV_ES;
2703             continue;
2704         }
2705         else
2706         {
2707             msg_Err( &sys.demuxer, "unknown codec id=`%s'", tracks[i_track]->psz_codec );
2708             tracks[i_track]->fmt.i_codec = VLC_FOURCC( 'u', 'n', 'd', 'f' );
2709         }
2710         if( tracks[i_track]->b_default )
2711         {
2712             tracks[i_track]->fmt.i_priority = 1000;
2713         }
2714
2715         tracks[i_track]->p_es = es_out_Add( sys.demuxer.out, &tracks[i_track]->fmt );
2716
2717         /* Turn on a subtitles track if it has been flagged as default -
2718          * but only do this if no subtitles track has already been engaged,
2719          * either by an earlier 'default track' (??) or by default
2720          * language choice behaviour.
2721          */
2722         if( tracks[i_track]->b_default )
2723         {
2724             es_out_Control( sys.demuxer.out,
2725                             ES_OUT_SET_DEFAULT,
2726                             tracks[i_track]->p_es );
2727         }
2728
2729         es_out_Control( sys.demuxer.out, ES_OUT_SET_NEXT_DISPLAY_TIME, tracks[i_track]->p_es, i_start_time );
2730     }
2731  
2732     sys.i_start_pts = i_start_time;
2733     // reset the stream reading to the first cluster of the segment used
2734     es.I_O().setFilePointer( i_start_pos );
2735
2736     delete ep;
2737     ep = new EbmlParser( &es, segment, &sys.demuxer );
2738
2739     return true;
2740 }
2741
2742 void demux_sys_t::StartUiThread()
2743 {
2744     if ( !b_ui_hooked )
2745     {
2746         msg_Dbg( &demuxer, "Starting the UI Hook" );
2747         b_ui_hooked = true;
2748         /* FIXME hack hack hack hack FIXME */
2749         /* Get p_input and create variable */
2750         p_input = (input_thread_t *) vlc_object_find( &demuxer, VLC_OBJECT_INPUT, FIND_PARENT );
2751         var_Create( p_input, "x-start", VLC_VAR_INTEGER );
2752         var_Create( p_input, "y-start", VLC_VAR_INTEGER );
2753         var_Create( p_input, "x-end", VLC_VAR_INTEGER );
2754         var_Create( p_input, "y-end", VLC_VAR_INTEGER );
2755         var_Create( p_input, "color", VLC_VAR_ADDRESS );
2756         var_Create( p_input, "menu-palette", VLC_VAR_ADDRESS );
2757         var_Create( p_input, "highlight", VLC_VAR_BOOL );
2758         var_Create( p_input, "highlight-mutex", VLC_VAR_MUTEX );
2759
2760         /* Now create our event thread catcher */
2761         p_ev = (event_thread_t *) vlc_object_create( &demuxer, sizeof( event_thread_t ) );
2762         p_ev->p_demux = &demuxer;
2763         p_ev->b_die = false;
2764         vlc_mutex_init( &p_ev->lock );
2765         vlc_thread_create( p_ev, "mkv event thread handler", EventThread,
2766                         VLC_THREAD_PRIORITY_LOW, false );
2767     }
2768 }
2769
2770 void demux_sys_t::StopUiThread()
2771 {
2772     if ( b_ui_hooked )
2773     {
2774         vlc_object_kill( p_ev );
2775         vlc_thread_join( p_ev );
2776         vlc_object_release( p_ev );
2777
2778         p_ev = NULL;
2779
2780         var_Destroy( p_input, "highlight-mutex" );
2781         var_Destroy( p_input, "highlight" );
2782         var_Destroy( p_input, "x-start" );
2783         var_Destroy( p_input, "x-end" );
2784         var_Destroy( p_input, "y-start" );
2785         var_Destroy( p_input, "y-end" );
2786         var_Destroy( p_input, "color" );
2787         var_Destroy( p_input, "menu-palette" );
2788
2789         vlc_object_release( p_input );
2790
2791         msg_Dbg( &demuxer, "Stopping the UI Hook" );
2792     }
2793     b_ui_hooked = false;
2794 }
2795
2796 int demux_sys_t::EventMouse( vlc_object_t *p_this, char const *psz_var,
2797                        vlc_value_t oldval, vlc_value_t newval, void *p_data )
2798 {
2799     event_thread_t *p_ev = (event_thread_t *) p_data;
2800     vlc_mutex_lock( &p_ev->lock );
2801     if( psz_var[6] == 'c' )
2802     {
2803         p_ev->b_clicked = true;
2804         msg_Dbg( p_this, "Event Mouse: clicked");
2805     }
2806     else if( psz_var[6] == 'm' )
2807         p_ev->b_moved = true;
2808     vlc_mutex_unlock( &p_ev->lock );
2809
2810     return VLC_SUCCESS;
2811 }
2812
2813 int demux_sys_t::EventKey( vlc_object_t *p_this, char const *,
2814                            vlc_value_t, vlc_value_t newval, void *p_data )
2815 {
2816     event_thread_t *p_ev = (event_thread_t *) p_data;
2817     vlc_mutex_lock( &p_ev->lock );
2818     p_ev->i_key_action = newval.i_int;
2819     vlc_mutex_unlock( &p_ev->lock );
2820     msg_Dbg( p_this, "Event Key");
2821
2822     return VLC_SUCCESS;
2823 }
2824
2825 void * demux_sys_t::EventThread( vlc_object_t *p_this )
2826 {
2827     event_thread_t *p_ev = (event_thread_t*)p_this;
2828     demux_sys_t    *p_sys = p_ev->p_demux->p_sys;
2829     vlc_object_t   *p_vout = NULL;
2830
2831     p_ev->b_moved   = false;
2832     p_ev->b_clicked = false;
2833     p_ev->i_key_action = 0;
2834
2835     /* catch all key event */
2836     var_AddCallback( p_ev->p_libvlc, "key-action", EventKey, p_ev );
2837
2838     /* main loop */
2839     while( vlc_object_alive (p_ev) )
2840     {
2841         if ( !p_sys->b_pci_packet_set )
2842         {
2843             /* Wait 100ms */
2844             msleep( 100000 );
2845             continue;
2846         }
2847
2848         bool b_activated = false;
2849
2850         /* KEY part */
2851         if( p_ev->i_key_action )
2852         {
2853             int i;
2854
2855             msg_Dbg( p_ev->p_demux, "Handle Key Event");
2856
2857             vlc_mutex_lock( &p_ev->lock );
2858
2859             pci_t *pci = (pci_t *) &p_sys->pci_packet;
2860
2861             uint16 i_curr_button = p_sys->dvd_interpretor.GetSPRM( 0x88 );
2862
2863             switch( p_ev->i_key_action )
2864             {
2865             case ACTIONID_NAV_LEFT:
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->left > 0 && p_button_ptr->left <= pci->hli.hl_gi.btn_ns )
2870                     {
2871                         i_curr_button = p_button_ptr->left;
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_RIGHT:
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->right > 0 && p_button_ptr->right <= pci->hli.hl_gi.btn_ns )
2893                     {
2894                         i_curr_button = p_button_ptr->right;
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_UP:
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->up > 0 && p_button_ptr->up <= pci->hli.hl_gi.btn_ns )
2916                     {
2917                         i_curr_button = p_button_ptr->up;
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_DOWN:
2935                 if ( i_curr_button > 0 && i_curr_button <= pci->hli.hl_gi.btn_ns )
2936                 {
2937                     btni_t *p_button_ptr = &(pci->hli.btnit[i_curr_button-1]);
2938                     if ( p_button_ptr->down > 0 && p_button_ptr->down <= pci->hli.hl_gi.btn_ns )
2939                     {
2940                         i_curr_button = p_button_ptr->down;
2941                         p_sys->dvd_interpretor.SetSPRM( 0x88, i_curr_button );
2942                         btni_t button_ptr = pci->hli.btnit[i_curr_button-1];
2943                         if ( button_ptr.auto_action_mode )
2944                         {
2945                             vlc_mutex_unlock( &p_ev->lock );
2946                             vlc_mutex_lock( &p_sys->lock_demuxer );
2947
2948                             // process the button action
2949                             p_sys->dvd_interpretor.Interpret( button_ptr.cmd.bytes, 8 );
2950
2951                             vlc_mutex_unlock( &p_sys->lock_demuxer );
2952                             vlc_mutex_lock( &p_ev->lock );
2953                         }
2954                     }
2955                 }
2956                 break;
2957             case ACTIONID_NAV_ACTIVATE:
2958                 b_activated = true;
2959  
2960                 if ( i_curr_button > 0 && i_curr_button <= pci->hli.hl_gi.btn_ns )
2961                 {
2962                     btni_t button_ptr = pci->hli.btnit[i_curr_button-1];
2963
2964                     vlc_mutex_unlock( &p_ev->lock );
2965                     vlc_mutex_lock( &p_sys->lock_demuxer );
2966
2967                     // process the button action
2968                     p_sys->dvd_interpretor.Interpret( button_ptr.cmd.bytes, 8 );
2969
2970                     vlc_mutex_unlock( &p_sys->lock_demuxer );
2971                     vlc_mutex_lock( &p_ev->lock );
2972                 }
2973                 break;
2974             default:
2975                 break;
2976             }
2977             p_ev->i_key_action = 0;
2978             vlc_mutex_unlock( &p_ev->lock );
2979         }
2980
2981         /* MOUSE part */
2982         if( p_vout && ( p_ev->b_moved || p_ev->b_clicked ) )
2983         {
2984             vlc_value_t valx, valy;
2985
2986             vlc_mutex_lock( &p_ev->lock );
2987             pci_t *pci = (pci_t *) &p_sys->pci_packet;
2988             var_Get( p_vout, "mouse-x", &valx );
2989             var_Get( p_vout, "mouse-y", &valy );
2990
2991             if( p_ev->b_clicked )
2992             {
2993                 int32_t button;
2994                 int32_t best,dist,d;
2995                 int32_t mx,my,dx,dy;
2996
2997                 msg_Dbg( p_ev->p_demux, "Handle Mouse Event: Mouse clicked x(%d)*y(%d)", (unsigned)valx.i_int, (unsigned)valy.i_int);
2998
2999                 b_activated = true;
3000                 // get current button
3001                 best = 0;
3002                 dist = 0x08000000; /* >> than  (720*720)+(567*567); */
3003                 for(button = 1; button <= pci->hli.hl_gi.btn_ns; button++)
3004                 {
3005                     btni_t *button_ptr = &(pci->hli.btnit[button-1]);
3006
3007                     if(((unsigned)valx.i_int >= button_ptr->x_start)
3008                      && ((unsigned)valx.i_int <= button_ptr->x_end)
3009                      && ((unsigned)valy.i_int >= button_ptr->y_start)
3010                      && ((unsigned)valy.i_int <= button_ptr->y_end))
3011                     {
3012                         mx = (button_ptr->x_start + button_ptr->x_end)/2;
3013                         my = (button_ptr->y_start + button_ptr->y_end)/2;
3014                         dx = mx - valx.i_int;
3015                         dy = my - valy.i_int;
3016                         d = (dx*dx) + (dy*dy);
3017                         /* If the mouse is within the button and the mouse is closer
3018                         * to the center of this button then it is the best choice. */
3019                         if(d < dist) {
3020                             dist = d;
3021                             best = button;
3022                         }
3023                     }
3024                 }
3025
3026                 if ( best != 0)
3027                 {
3028                     btni_t button_ptr = pci->hli.btnit[best-1];
3029                     uint16 i_curr_button = p_sys->dvd_interpretor.GetSPRM( 0x88 );
3030
3031                     msg_Dbg( &p_sys->demuxer, "Clicked button %d", best );
3032                     vlc_mutex_unlock( &p_ev->lock );
3033                     vlc_mutex_lock( &p_sys->lock_demuxer );
3034
3035                     // process the button action
3036                     p_sys->dvd_interpretor.SetSPRM( 0x88, best );
3037                     p_sys->dvd_interpretor.Interpret( button_ptr.cmd.bytes, 8 );
3038
3039                     msg_Dbg( &p_sys->demuxer, "Processed button %d", best );
3040
3041                     // select new button
3042                     if ( best != i_curr_button )
3043                     {
3044                         vlc_value_t val;
3045
3046                         if( var_Get( p_sys->p_input, "highlight-mutex", &val ) == VLC_SUCCESS )
3047                         {
3048                             vlc_mutex_t *p_mutex = (vlc_mutex_t *) val.p_address;
3049                             uint32_t i_palette;
3050
3051                             if(button_ptr.btn_coln != 0) {
3052                                 i_palette = pci->hli.btn_colit.btn_coli[button_ptr.btn_coln-1][1];
3053                             } else {
3054                                 i_palette = 0;
3055                             }
3056
3057                             for( int i = 0; i < 4; i++ )
3058                             {
3059                                 uint32_t i_yuv = 0xFF;//p_sys->clut[(hl.palette>>(16+i*4))&0x0f];
3060                                 uint8_t i_alpha = (i_palette>>(i*4))&0x0f;
3061                                 i_alpha = i_alpha == 0xf ? 0xff : i_alpha << 4;
3062
3063                                 p_sys->palette[i][0] = (i_yuv >> 16) & 0xff;
3064                                 p_sys->palette[i][1] = (i_yuv >> 0) & 0xff;
3065                                 p_sys->palette[i][2] = (i_yuv >> 8) & 0xff;
3066                                 p_sys->palette[i][3] = i_alpha;
3067                             }
3068
3069                             vlc_mutex_lock( p_mutex );
3070                             val.i_int = button_ptr.x_start; var_Set( p_sys->p_input, "x-start", val );
3071                             val.i_int = button_ptr.x_end;   var_Set( p_sys->p_input, "x-end",   val );
3072                             val.i_int = button_ptr.y_start; var_Set( p_sys->p_input, "y-start", val );
3073                             val.i_int = button_ptr.y_end;   var_Set( p_sys->p_input, "y-end",   val );
3074
3075                             val.p_address = (void *)p_sys->palette;
3076                             var_Set( p_sys->p_input, "menu-palette", val );
3077
3078                             val.b_bool = true; var_Set( p_sys->p_input, "highlight", val );
3079                             vlc_mutex_unlock( p_mutex );
3080                         }
3081                     }
3082                     vlc_mutex_unlock( &p_sys->lock_demuxer );
3083                     vlc_mutex_lock( &p_ev->lock );
3084                 }
3085             }
3086             else if( p_ev->b_moved )
3087             {
3088 //                dvdnav_mouse_select( NULL, pci, valx.i_int, valy.i_int );
3089             }
3090
3091             p_ev->b_moved = false;
3092             p_ev->b_clicked = false;
3093             vlc_mutex_unlock( &p_ev->lock );
3094         }
3095
3096         /* VOUT part */
3097         if( p_vout && !vlc_object_alive (p_vout) )
3098         {
3099             var_DelCallback( p_vout, "mouse-moved", EventMouse, p_ev );
3100             var_DelCallback( p_vout, "mouse-clicked", EventMouse, p_ev );
3101             vlc_object_release( p_vout );
3102             p_vout = NULL;
3103         }
3104
3105         else if( p_vout == NULL )
3106         {
3107             p_vout = (vlc_object_t*) vlc_object_find( p_sys->p_input, VLC_OBJECT_VOUT,
3108                                       FIND_CHILD );
3109             if( p_vout)
3110             {
3111                 var_AddCallback( p_vout, "mouse-moved", EventMouse, p_ev );
3112                 var_AddCallback( p_vout, "mouse-clicked", EventMouse, p_ev );
3113             }
3114         }
3115
3116         /* Wait a bit, 10ms */
3117         msleep( 10000 );
3118     }
3119
3120     /* Release callback */
3121     if( p_vout )
3122     {
3123         var_DelCallback( p_vout, "mouse-moved", EventMouse, p_ev );
3124         var_DelCallback( p_vout, "mouse-clicked", EventMouse, p_ev );
3125         vlc_object_release( p_vout );
3126     }
3127     var_DelCallback( p_ev->p_libvlc, "key-action", EventKey, p_ev );
3128
3129     vlc_mutex_destroy( &p_ev->lock );
3130
3131     return VLC_SUCCESS;
3132 }
3133
3134 void matroska_segment_c::UnSelect( )
3135 {
3136     size_t i_track;
3137
3138     for( i_track = 0; i_track < tracks.size(); i_track++ )
3139     {
3140         if ( tracks[i_track]->p_es != NULL )
3141         {
3142 //            es_format_Clean( &tracks[i_track]->fmt );
3143             es_out_Del( sys.demuxer.out, tracks[i_track]->p_es );
3144             tracks[i_track]->p_es = NULL;
3145         }
3146     }
3147     delete ep;
3148     ep = NULL;
3149 }
3150
3151 void virtual_segment_c::PrepareChapters( )
3152 {
3153     if ( linked_segments.size() == 0 )
3154         return;
3155
3156     // !!! should be called only once !!!
3157     matroska_segment_c *p_segment;
3158     size_t i, j;
3159
3160     // copy editions from the first segment
3161     p_segment = linked_segments[0];
3162     p_editions = &p_segment->stored_editions;
3163
3164     for ( i=1 ; i<linked_segments.size(); i++ )
3165     {
3166         p_segment = linked_segments[i];
3167         // FIXME assume we have the same editions in all segments
3168         for (j=0; j<p_segment->stored_editions.size(); j++)
3169         {
3170             if( j >= p_editions->size() ) /* Protect against broken files (?) */
3171                 break;
3172             (*p_editions)[j]->Append( *p_segment->stored_editions[j] );
3173         }
3174     }
3175 }
3176
3177 std::string chapter_edition_c::GetMainName() const
3178 {
3179     if ( sub_chapters.size() )
3180     {
3181         return sub_chapters[0]->GetCodecName( true );
3182     }
3183     return "";
3184 }
3185
3186 int chapter_item_c::PublishChapters( input_title_t & title, int & i_user_chapters, int i_level )
3187 {
3188     // add support for meta-elements from codec like DVD Titles
3189     if ( !b_display_seekpoint || psz_name == "" )
3190     {
3191         psz_name = GetCodecName();
3192         if ( psz_name != "" )
3193             b_display_seekpoint = true;
3194     }
3195
3196     if (b_display_seekpoint)
3197     {
3198         seekpoint_t *sk = vlc_seekpoint_New();
3199
3200         sk->i_level = i_level;
3201         sk->i_time_offset = i_start_time;
3202         sk->psz_name = strdup( psz_name.c_str() );
3203
3204         // A start time of '0' is ok. A missing ChapterTime element is ok, too, because '0' is its default value.
3205         title.i_seekpoint++;
3206         title.seekpoint = (seekpoint_t**)realloc( title.seekpoint, title.i_seekpoint * sizeof( seekpoint_t* ) );
3207         title.seekpoint[title.i_seekpoint-1] = sk;
3208
3209         if ( b_user_display )
3210             i_user_chapters++;
3211     }
3212
3213     for ( size_t i=0; i<sub_chapters.size() ; i++)
3214     {
3215         sub_chapters[i]->PublishChapters( title, i_user_chapters, i_level+1 );
3216     }
3217
3218     i_seekpoint_num = i_user_chapters;
3219
3220     return i_user_chapters;
3221 }
3222
3223 bool virtual_segment_c::UpdateCurrentToChapter( demux_t & demux )
3224 {
3225     demux_sys_t & sys = *demux.p_sys;
3226     chapter_item_c *psz_curr_chapter;
3227     bool b_has_seeked = false;
3228
3229     /* update current chapter/seekpoint */
3230     if ( p_editions->size() )
3231     {
3232         /* 1st, we need to know in which chapter we are */
3233         psz_curr_chapter = (*p_editions)[i_current_edition]->FindTimecode( sys.i_pts, psz_current_chapter );
3234
3235         /* we have moved to a new chapter */
3236         if (psz_curr_chapter != NULL && psz_current_chapter != psz_curr_chapter)
3237         {
3238             if ( (*p_editions)[i_current_edition]->b_ordered )
3239             {
3240                 // Leave/Enter up to the link point
3241                 b_has_seeked = psz_curr_chapter->EnterAndLeave( psz_current_chapter );
3242                 if ( !b_has_seeked )
3243                 {
3244                     // only physically seek if necessary
3245                     if ( psz_current_chapter == NULL || (psz_current_chapter->i_end_time != psz_curr_chapter->i_start_time) )
3246                         Seek( demux, sys.i_pts, 0, psz_curr_chapter, -1 );
3247                 }
3248             }
3249  
3250             if ( !b_has_seeked )
3251             {
3252                 psz_current_chapter = psz_curr_chapter;
3253                 if ( psz_curr_chapter->i_seekpoint_num > 0 )
3254                 {
3255                     demux.info.i_update |= INPUT_UPDATE_TITLE | INPUT_UPDATE_SEEKPOINT;
3256                     demux.info.i_title = sys.i_current_title = i_sys_title;
3257                     demux.info.i_seekpoint = psz_curr_chapter->i_seekpoint_num - 1;
3258                 }
3259             }
3260
3261             return true;
3262         }
3263         else if (psz_curr_chapter == NULL)
3264         {
3265             // out of the scope of the data described by chapters, leave the edition
3266             if ( (*p_editions)[i_current_edition]->b_ordered && psz_current_chapter != NULL )
3267             {
3268                 if ( !(*p_editions)[i_current_edition]->EnterAndLeave( psz_current_chapter, false ) )
3269                     psz_current_chapter = NULL;
3270                 else
3271                     return true;
3272             }
3273         }
3274     }
3275     return false;
3276 }
3277
3278 chapter_item_c *virtual_segment_c::BrowseCodecPrivate( unsigned int codec_id,
3279                                     bool (*match)(const chapter_codec_cmds_c &data, const void *p_cookie, size_t i_cookie_size ),
3280                                     const void *p_cookie,
3281                                     size_t i_cookie_size )
3282 {
3283     // FIXME don't assume it is the first edition
3284     std::vector<chapter_edition_c*>::iterator index = p_editions->begin();
3285     if ( index != p_editions->end() )
3286     {
3287         chapter_item_c *p_result = (*index)->BrowseCodecPrivate( codec_id, match, p_cookie, i_cookie_size );
3288         if ( p_result != NULL )
3289             return p_result;
3290     }
3291     return NULL;
3292 }
3293
3294 chapter_item_c *virtual_segment_c::FindChapter( int64_t i_find_uid )
3295 {
3296     // FIXME don't assume it is the first edition
3297     std::vector<chapter_edition_c*>::iterator index = p_editions->begin();
3298     if ( index != p_editions->end() )
3299     {
3300         chapter_item_c *p_result = (*index)->FindChapter( i_find_uid );
3301         if ( p_result != NULL )
3302             return p_result;
3303     }
3304     return NULL;
3305 }
3306
3307 chapter_item_c *chapter_item_c::BrowseCodecPrivate( unsigned int codec_id,
3308                                     bool (*match)(const chapter_codec_cmds_c &data, const void *p_cookie, size_t i_cookie_size ),
3309                                     const void *p_cookie,
3310                                     size_t i_cookie_size )
3311 {
3312     // this chapter
3313     std::vector<chapter_codec_cmds_c*>::const_iterator index = codecs.begin();
3314     while ( index != codecs.end() )
3315     {
3316         if ( match( **index ,p_cookie, i_cookie_size ) )
3317             return this;
3318         index++;
3319     }
3320  
3321     // sub-chapters
3322     chapter_item_c *p_result = NULL;
3323     std::vector<chapter_item_c*>::const_iterator index2 = sub_chapters.begin();
3324     while ( index2 != sub_chapters.end() )
3325     {
3326         p_result = (*index2)->BrowseCodecPrivate( codec_id, match, p_cookie, i_cookie_size );
3327         if ( p_result != NULL )
3328             return p_result;
3329         index2++;
3330     }
3331  
3332     return p_result;
3333 }
3334
3335 void chapter_item_c::Append( const chapter_item_c & chapter )
3336 {
3337     // we are appending content for the same chapter UID
3338     size_t i;
3339     chapter_item_c *p_chapter;
3340
3341     for ( i=0; i<chapter.sub_chapters.size(); i++ )
3342     {
3343         p_chapter = FindChapter( chapter.sub_chapters[i]->i_uid );
3344         if ( p_chapter != NULL )
3345         {
3346             p_chapter->Append( *chapter.sub_chapters[i] );
3347         }
3348         else
3349         {
3350             sub_chapters.push_back( chapter.sub_chapters[i] );
3351         }
3352     }
3353
3354     i_user_start_time = min( i_user_start_time, chapter.i_user_start_time );
3355     i_user_end_time = max( i_user_end_time, chapter.i_user_end_time );
3356 }
3357
3358 chapter_item_c * chapter_item_c::FindChapter( int64_t i_find_uid )
3359 {
3360     size_t i;
3361     chapter_item_c *p_result = NULL;
3362
3363     if ( i_uid == i_find_uid )
3364         return this;
3365
3366     for ( i=0; i<sub_chapters.size(); i++)
3367     {
3368         p_result = sub_chapters[i]->FindChapter( i_find_uid );
3369         if ( p_result != NULL )
3370             break;
3371     }
3372     return p_result;
3373 }
3374
3375 std::string chapter_item_c::GetCodecName( bool f_for_title ) const
3376 {
3377     std::string result;
3378
3379     std::vector<chapter_codec_cmds_c*>::const_iterator index = codecs.begin();
3380     while ( index != codecs.end() )
3381     {
3382         result = (*index)->GetCodecName( f_for_title );
3383         if ( result != "" )
3384             break;
3385         index++;
3386     }
3387
3388     return result;
3389 }
3390
3391 std::string dvd_chapter_codec_c::GetCodecName( bool f_for_title ) const
3392 {
3393     std::string result;
3394     if ( p_private_data->GetSize() >= 3)
3395     {
3396         const binary* p_data = p_private_data->GetBuffer();
3397 /*        if ( p_data[0] == MATROSKA_DVD_LEVEL_TT )
3398         {
3399             uint16_t i_title = (p_data[1] << 8) + p_data[2];
3400             char psz_str[11];
3401             sprintf( psz_str, " %d  ---", i_title );
3402             result = N_("---  DVD Title");
3403             result += psz_str;
3404         }
3405         else */ if ( p_data[0] == MATROSKA_DVD_LEVEL_LU )
3406         {
3407             char psz_str[11];
3408             sprintf( psz_str, " (%c%c)  ---", p_data[1], p_data[2] );
3409             result = N_("---  DVD Menu");
3410             result += psz_str;
3411         }
3412         else if ( p_data[0] == MATROSKA_DVD_LEVEL_SS && f_for_title )
3413         {
3414             if ( p_data[1] == 0x00 )
3415                 result = N_("First Played");
3416             else if ( p_data[1] == 0xC0 )
3417                 result = N_("Video Manager");
3418             else if ( p_data[1] == 0x80 )
3419             {
3420                 uint16_t i_title = (p_data[2] << 8) + p_data[3];
3421                 char psz_str[20];
3422                 sprintf( psz_str, " %d -----", i_title );
3423                 result = N_("----- Title");
3424                 result += psz_str;
3425             }
3426         }
3427     }
3428
3429     return result;
3430 }
3431
3432 int16 chapter_item_c::GetTitleNumber( ) const
3433 {
3434     int result = -1;
3435
3436     std::vector<chapter_codec_cmds_c*>::const_iterator index = codecs.begin();
3437     while ( index != codecs.end() )
3438     {
3439         result = (*index)->GetTitleNumber( );
3440         if ( result >= 0 )
3441             break;
3442         index++;
3443     }
3444
3445     return result;
3446 }
3447
3448 int16 dvd_chapter_codec_c::GetTitleNumber()
3449 {
3450     if ( p_private_data->GetSize() >= 3)
3451     {
3452         const binary* p_data = p_private_data->GetBuffer();
3453         if ( p_data[0] == MATROSKA_DVD_LEVEL_SS )
3454         {
3455             return int16( (p_data[2] << 8) + p_data[3] );
3456         }
3457     }
3458     return -1;
3459 }
3460
3461 static void Seek( demux_t *p_demux, mtime_t i_date, double f_percent, chapter_item_c *psz_chapter )
3462 {
3463     demux_sys_t        *p_sys = p_demux->p_sys;
3464     virtual_segment_c  *p_vsegment = p_sys->p_current_segment;
3465     matroska_segment_c *p_segment = p_vsegment->Segment();
3466     mtime_t            i_time_offset = 0;
3467     int64_t            i_global_position = -1;
3468
3469     int         i_index;
3470
3471     msg_Dbg( p_demux, "seek request to %"PRId64" (%f%%)", i_date, f_percent );
3472     if( i_date < 0 && f_percent < 0 )
3473     {
3474         msg_Warn( p_demux, "cannot seek nowhere !" );
3475         return;
3476     }
3477     if( f_percent > 1.0 )
3478     {
3479         msg_Warn( p_demux, "cannot seek so far !" );
3480         return;
3481     }
3482
3483     /* seek without index or without date */
3484     if( f_percent >= 0 && (config_GetInt( p_demux, "mkv-seek-percent" ) || !p_segment->b_cues || i_date < 0 ))
3485     {
3486         if( p_sys->f_duration >= 0 && p_segment->b_cues )
3487         {
3488             i_date = int64_t( f_percent * p_sys->f_duration * 1000.0 );
3489         }
3490         else
3491         {
3492             int64_t i_pos = int64_t( f_percent * stream_Size( p_demux->s ) );
3493
3494             msg_Dbg( p_demux, "inaccurate way of seeking for pos:%"PRId64, i_pos );
3495             for( i_index = 0; i_index < p_segment->i_index; i_index++ )
3496             {
3497                 if( p_segment->b_cues && p_segment->p_indexes[i_index].i_position < i_pos )
3498                     break;
3499                 if( !p_segment->b_cues && p_segment->p_indexes[i_index].i_position >= i_pos && p_segment->p_indexes[i_index].i_time > 0 )
3500                     break;
3501             }
3502             if( i_index == p_segment->i_index )
3503             {
3504                 i_index--;
3505             }
3506
3507             i_date = p_segment->p_indexes[i_index].i_time;
3508
3509             if( !p_segment->b_cues && ( p_segment->p_indexes[i_index].i_position < i_pos || p_segment->p_indexes[i_index].i_position - i_pos > 2000000 ))
3510             {
3511                 msg_Dbg( p_demux, "no cues, seek request to global pos: %"PRId64, i_pos );
3512                 i_global_position = i_pos;
3513             }
3514         }
3515     }
3516
3517     p_vsegment->Seek( *p_demux, i_date, i_time_offset, psz_chapter, i_global_position );
3518 }
3519
3520 /*****************************************************************************
3521  * Demux: reads and demuxes data packets
3522  *****************************************************************************
3523  * Returns -1 in case of error, 0 in case of EOF, 1 otherwise
3524  *****************************************************************************/
3525 static int Demux( demux_t *p_demux)
3526 {
3527     demux_sys_t        *p_sys = p_demux->p_sys;
3528
3529     vlc_mutex_lock( &p_sys->lock_demuxer );
3530
3531     virtual_segment_c  *p_vsegment = p_sys->p_current_segment;
3532     matroska_segment_c *p_segment = p_vsegment->Segment();
3533     if ( p_segment == NULL ) return 0;
3534     int                i_block_count = 0;
3535     int                i_return = 0;
3536
3537     for( ;; )
3538     {
3539         if ( p_sys->demuxer.b_die )
3540             break;
3541
3542         if( p_sys->i_pts >= p_sys->i_start_pts  )
3543             if ( p_vsegment->UpdateCurrentToChapter( *p_demux ) )
3544             {
3545                 i_return = 1;
3546                 break;
3547             }
3548  
3549         if ( p_vsegment->Edition() && p_vsegment->Edition()->b_ordered && p_vsegment->CurrentChapter() == NULL )
3550         {
3551             /* nothing left to read in this ordered edition */
3552             if ( !p_vsegment->SelectNext() )
3553                 break;
3554             p_segment->UnSelect( );
3555  
3556             es_out_Control( p_demux->out, ES_OUT_RESET_PCR );
3557
3558             /* switch to the next segment */
3559             p_segment = p_vsegment->Segment();
3560             if ( !p_segment->Select( 0 ) )
3561             {
3562                 msg_Err( p_demux, "Failed to select new segment" );
3563                 break;
3564             }
3565             continue;
3566         }
3567
3568         KaxBlock *block;
3569         int64_t i_block_duration = 0;
3570         int64_t i_block_ref1;
3571         int64_t i_block_ref2;
3572
3573 #if LIBMATROSKA_VERSION >= 0x000800
3574         KaxSimpleBlock *simpleblock;
3575
3576         if( p_segment->BlockGet( block, simpleblock, &i_block_ref1, &i_block_ref2, &i_block_duration ) )
3577 #else
3578         if( p_segment->BlockGet( block, &i_block_ref1, &i_block_ref2, &i_block_duration ) )
3579 #endif
3580         {
3581             if ( p_vsegment->Edition() && p_vsegment->Edition()->b_ordered )
3582             {
3583                 const chapter_item_c *p_chap = p_vsegment->CurrentChapter();
3584                 // check if there are more chapters to read
3585                 if ( p_chap != NULL )
3586                 {
3587                     /* TODO handle successive chapters with the same user_start_time/user_end_time
3588                     if ( p_chap->i_user_start_time == p_chap->i_user_start_time )
3589                         p_vsegment->SelectNext();
3590                     */
3591                     p_sys->i_pts = p_chap->i_user_end_time;
3592                     p_sys->i_pts++; // trick to avoid staying on segments with no duration and no content
3593
3594                     i_return = 1;
3595                 }
3596
3597                 break;
3598             }
3599             else
3600             {
3601                 msg_Warn( p_demux, "cannot get block EOF?" );
3602                 p_segment->UnSelect( );
3603  
3604                 es_out_Control( p_demux->out, ES_OUT_RESET_PCR );
3605
3606                 /* switch to the next segment */
3607                 if ( !p_vsegment->SelectNext() )
3608                     // no more segments in this stream
3609                     break;
3610                 p_segment = p_vsegment->Segment();
3611                 if ( !p_segment->Select( 0 ) )
3612                 {
3613                     msg_Err( p_demux, "Failed to select new segment" );
3614                     break;
3615                 }
3616
3617                 continue;
3618             }
3619         }
3620
3621 #if LIBMATROSKA_VERSION >= 0x000800
3622         if ( simpleblock != NULL )
3623             p_sys->i_pts = (p_sys->i_chapter_time + simpleblock->GlobalTimecode()) / (mtime_t) 1000;
3624         else
3625 #endif
3626         p_sys->i_pts = (p_sys->i_chapter_time + block->GlobalTimecode()) / (mtime_t) 1000;
3627
3628         if( p_sys->i_pts >= p_sys->i_start_pts  )
3629         {
3630             es_out_Control( p_demux->out, ES_OUT_SET_PCR, p_sys->i_pts );
3631
3632             if ( p_vsegment->UpdateCurrentToChapter( *p_demux ) )
3633             {
3634                 i_return = 1;
3635                 delete block;
3636                 break;
3637             }
3638         }
3639  
3640         if ( p_vsegment->Edition() && p_vsegment->Edition()->b_ordered && p_vsegment->CurrentChapter() == NULL )
3641         {
3642             /* nothing left to read in this ordered edition */
3643             if ( !p_vsegment->SelectNext() )
3644             {
3645                 delete block;
3646                 break;
3647             }
3648             p_segment->UnSelect( );
3649  
3650             es_out_Control( p_demux->out, ES_OUT_RESET_PCR );
3651
3652             /* switch to the next segment */
3653             p_segment = p_vsegment->Segment();
3654             if ( !p_segment->Select( 0 ) )
3655             {
3656                 msg_Err( p_demux, "Failed to select new segment" );
3657                 delete block;
3658                 break;
3659             }
3660             delete block;
3661             continue;
3662         }
3663
3664 #if LIBMATROSKA_VERSION >= 0x000800
3665         BlockDecode( p_demux, block, simpleblock, p_sys->i_pts, i_block_duration, i_block_ref1 >= 0 || i_block_ref2 > 0 );
3666 #else
3667         BlockDecode( p_demux, block, p_sys->i_pts, i_block_duration, i_block_ref1 >= 0 || i_block_ref2 > 0 );
3668 #endif
3669
3670         delete block;
3671         i_block_count++;
3672
3673         // TODO optimize when there is need to leave or when seeking has been called
3674         if( i_block_count > 5 )
3675         {
3676             i_return = 1;
3677             break;
3678         }
3679     }
3680
3681     vlc_mutex_unlock( &p_sys->lock_demuxer );
3682
3683     return i_return;
3684 }
3685
3686
3687
3688 /*****************************************************************************
3689  * Stream managment
3690  *****************************************************************************/
3691 vlc_stream_io_callback::vlc_stream_io_callback( stream_t *s_, bool b_owner_ )
3692 {
3693     s = s_;
3694     b_owner = b_owner_;
3695     mb_eof = false;
3696 }
3697
3698 uint32 vlc_stream_io_callback::read( void *p_buffer, size_t i_size )
3699 {
3700     if( i_size <= 0 || mb_eof )
3701     {
3702         return 0;
3703     }
3704
3705     return stream_Read( s, p_buffer, i_size );
3706 }
3707 void vlc_stream_io_callback::setFilePointer(int64_t i_offset, seek_mode mode )
3708 {
3709     int64_t i_pos;
3710
3711     switch( mode )
3712     {
3713         case seek_beginning:
3714             i_pos = i_offset;
3715             break;
3716         case seek_end:
3717             i_pos = stream_Size( s ) - i_offset;
3718             break;
3719         default:
3720             i_pos= stream_Tell( s ) + i_offset;
3721             break;
3722     }
3723
3724     if( i_pos < 0 || i_pos >= stream_Size( s ) )
3725     {
3726         mb_eof = true;
3727         return;
3728     }
3729
3730     mb_eof = false;
3731     if( stream_Seek( s, i_pos ) )
3732     {
3733         mb_eof = true;
3734     }
3735     return;
3736 }
3737 size_t vlc_stream_io_callback::write( const void *p_buffer, size_t i_size )
3738 {
3739     return 0;
3740 }
3741 uint64 vlc_stream_io_callback::getFilePointer( void )
3742 {
3743     if ( s == NULL )
3744         return 0;
3745     return stream_Tell( s );
3746 }
3747 void vlc_stream_io_callback::close( void )
3748 {
3749     return;
3750 }
3751
3752
3753 /*****************************************************************************
3754  * Ebml Stream parser
3755  *****************************************************************************/
3756 EbmlParser::EbmlParser( EbmlStream *es, EbmlElement *el_start, demux_t *p_demux )
3757 {
3758     int i;
3759
3760     m_es = es;
3761     m_got = NULL;
3762     m_el[0] = el_start;
3763     mi_remain_size[0] = el_start->GetSize();
3764
3765     for( i = 1; i < 6; i++ )
3766     {
3767         m_el[i] = NULL;
3768     }
3769     mi_level = 1;
3770     mi_user_level = 1;
3771     mb_keep = false;
3772     mb_dummy = config_GetInt( p_demux, "mkv-use-dummy" );
3773 }
3774
3775 EbmlParser::~EbmlParser( void )
3776 {
3777     int i;
3778
3779     for( i = 1; i < mi_level; i++ )
3780     {
3781         if( !mb_keep )
3782         {
3783             delete m_el[i];
3784         }
3785         mb_keep = false;
3786     }
3787 }
3788
3789 EbmlElement* EbmlParser::UnGet( uint64 i_block_pos, uint64 i_cluster_pos )
3790 {
3791     if ( mi_user_level > mi_level )
3792     {
3793         while ( mi_user_level != mi_level )
3794         {
3795             delete m_el[mi_user_level];
3796             m_el[mi_user_level] = NULL;
3797             mi_user_level--;
3798         }
3799     }
3800     m_got = NULL;
3801     mb_keep = false;
3802     if ( m_el[1]->GetElementPosition() == i_cluster_pos )
3803     {
3804         m_es->I_O().setFilePointer( i_block_pos, seek_beginning );
3805         return (EbmlMaster*) m_el[1];
3806     }
3807     else
3808     {
3809         // seek to the previous Cluster
3810         m_es->I_O().setFilePointer( i_cluster_pos, seek_beginning );
3811         mi_level--;
3812         mi_user_level--;
3813         delete m_el[mi_level];
3814         m_el[mi_level] = NULL;
3815         return NULL;
3816     }
3817 }
3818
3819 void EbmlParser::Up( void )
3820 {
3821     if( mi_user_level == mi_level )
3822     {
3823         fprintf( stderr," arrrrrrrrrrrrrg Up cannot escape itself\n" );
3824     }
3825
3826     mi_user_level--;
3827 }
3828
3829 void EbmlParser::Down( void )
3830 {
3831     mi_user_level++;
3832     mi_level++;
3833 }
3834
3835 void EbmlParser::Keep( void )
3836 {
3837     mb_keep = true;
3838 }
3839
3840 int EbmlParser::GetLevel( void )
3841 {
3842     return mi_user_level;
3843 }
3844
3845 void EbmlParser::Reset( demux_t *p_demux )
3846 {
3847     while ( mi_level > 0)
3848     {
3849         delete m_el[mi_level];
3850         m_el[mi_level] = NULL;
3851         mi_level--;
3852     }
3853     mi_user_level = mi_level = 1;
3854 #if LIBEBML_VERSION >= 0x000704
3855     // a little faster and cleaner
3856     m_es->I_O().setFilePointer( static_cast<KaxSegment*>(m_el[0])->GetGlobalPosition(0) );
3857 #else
3858     m_es->I_O().setFilePointer( m_el[0]->GetElementPosition() + m_el[0]->ElementSize(true) - m_el[0]->GetSize() );
3859 #endif
3860     mb_dummy = config_GetInt( p_demux, "mkv-use-dummy" );
3861 }
3862
3863 #if LIBMATROSKA_VERSION >= 0x000800
3864 /* This function workarounds a bug in KaxBlockVirtual implementation */
3865 class KaxBlockVirtualWorkaround : public KaxBlockVirtual
3866 {
3867 public:
3868     void Fix()
3869     {
3870         if( Data == DataBlock )
3871             SetBuffer( NULL, 0 );
3872     }
3873 };
3874 #endif
3875
3876 EbmlElement *EbmlParser::Get( void )
3877 {
3878     int i_ulev = 0;
3879
3880     if( mi_user_level != mi_level )
3881     {
3882         return NULL;
3883     }
3884     if( m_got )
3885     {
3886         EbmlElement *ret = m_got;
3887         m_got = NULL;
3888
3889         return ret;
3890     }
3891
3892     if( m_el[mi_level] )
3893     {
3894         m_el[mi_level]->SkipData( *m_es, m_el[mi_level]->Generic().Context );
3895         if( !mb_keep )
3896         {
3897 #if LIBMATROSKA_VERSION >= 0x000800
3898             if( MKV_IS_ID( m_el[mi_level], KaxBlockVirtual ) )
3899                 static_cast<KaxBlockVirtualWorkaround*>(m_el[mi_level])->Fix();
3900 #endif
3901             delete m_el[mi_level];
3902         }
3903         mb_keep = false;
3904     }
3905
3906     m_el[mi_level] = m_es->FindNextElement( m_el[mi_level - 1]->Generic().Context, i_ulev, 0xFFFFFFFFL, mb_dummy != 0, 1 );
3907 //    mi_remain_size[mi_level] = m_el[mi_level]->GetSize();
3908     if( i_ulev > 0 )
3909     {
3910         while( i_ulev > 0 )
3911         {
3912             if( mi_level == 1 )
3913             {
3914                 mi_level = 0;
3915                 return NULL;
3916             }
3917
3918             delete m_el[mi_level - 1];
3919             m_got = m_el[mi_level -1] = m_el[mi_level];
3920             m_el[mi_level] = NULL;
3921
3922             mi_level--;
3923             i_ulev--;
3924         }
3925         return NULL;
3926     }
3927     else if( m_el[mi_level] == NULL )
3928     {
3929         fprintf( stderr," m_el[mi_level] == NULL\n" );
3930     }
3931
3932     return m_el[mi_level];
3933 }
3934
3935 bool EbmlParser::IsTopPresent( EbmlElement *el )
3936 {
3937     for( int i = 0; i < mi_level; i++ )
3938     {
3939         if( m_el[i] && m_el[i] == el )
3940             return true;
3941     }
3942     return false;
3943 }
3944
3945 /*****************************************************************************
3946  * Tools
3947  *  * LoadCues : load the cues element and update index
3948  *
3949  *  * LoadTags : load ... the tags element
3950  *
3951  *  * InformationCreate : create all information, load tags if present
3952  *
3953  *****************************************************************************/
3954 void matroska_segment_c::LoadCues( KaxCues *cues )
3955 {
3956     EbmlParser  *ep;
3957     EbmlElement *el;
3958     size_t i, j;
3959
3960     if( b_cues )
3961     {
3962         msg_Err( &sys.demuxer, "There can be only 1 Cues per section." );
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     b_cues = true;
4051     msg_Dbg( &sys.demuxer, "|   - loading cues done." );
4052 }
4053
4054 void matroska_segment_c::LoadTags( KaxTags *tags )
4055 {
4056     EbmlParser  *ep;
4057     EbmlElement *el;
4058     size_t i, j;
4059
4060     /* Master elements */
4061     ep = new EbmlParser( &es, tags, &sys.demuxer );
4062
4063     while( ( el = ep->Get() ) != NULL )
4064     {
4065         if( MKV_IS_ID( el, KaxTag ) )
4066         {
4067             msg_Dbg( &sys.demuxer, "+ Tag" );
4068             ep->Down();
4069             while( ( el = ep->Get() ) != NULL )
4070             {
4071                 if( MKV_IS_ID( el, KaxTagTargets ) )
4072                 {
4073                     msg_Dbg( &sys.demuxer, "|   + Targets" );
4074                     ep->Down();
4075                     while( ( el = ep->Get() ) != NULL )
4076                     {
4077                         msg_Dbg( &sys.demuxer, "|   |   + Unknown (%s)", typeid( *el ).name() );
4078                     }
4079                     ep->Up();
4080                 }
4081                 else if( MKV_IS_ID( el, KaxTagGeneral ) )
4082                 {
4083                     msg_Dbg( &sys.demuxer, "|   + General" );
4084                     ep->Down();
4085                     while( ( el = ep->Get() ) != NULL )
4086                     {
4087                         msg_Dbg( &sys.demuxer, "|   |   + Unknown (%s)", typeid( *el ).name() );
4088                     }
4089                     ep->Up();
4090                 }
4091                 else if( MKV_IS_ID( el, KaxTagGenres ) )
4092                 {
4093                     msg_Dbg( &sys.demuxer, "|   + Genres" );
4094                     ep->Down();
4095                     while( ( el = ep->Get() ) != NULL )
4096                     {
4097                         msg_Dbg( &sys.demuxer, "|   |   + Unknown (%s)", typeid( *el ).name() );
4098                     }
4099                     ep->Up();
4100                 }
4101                 else if( MKV_IS_ID( el, KaxTagAudioSpecific ) )
4102                 {
4103                     msg_Dbg( &sys.demuxer, "|   + Audio Specific" );
4104                     ep->Down();
4105                     while( ( el = ep->Get() ) != NULL )
4106                     {
4107                         msg_Dbg( &sys.demuxer, "|   |   + Unknown (%s)", typeid( *el ).name() );
4108                     }
4109                     ep->Up();
4110                 }
4111                 else if( MKV_IS_ID( el, KaxTagImageSpecific ) )
4112                 {
4113                     msg_Dbg( &sys.demuxer, "|   + Images Specific" );
4114                     ep->Down();
4115                     while( ( el = ep->Get() ) != NULL )
4116                     {
4117                         msg_Dbg( &sys.demuxer, "|   |   + Unknown (%s)", typeid( *el ).name() );
4118                     }
4119                     ep->Up();
4120                 }
4121                 else if( MKV_IS_ID( el, KaxTagMultiComment ) )
4122                 {
4123                     msg_Dbg( &sys.demuxer, "|   + Multi Comment" );
4124                 }
4125                 else if( MKV_IS_ID( el, KaxTagMultiCommercial ) )
4126                 {
4127                     msg_Dbg( &sys.demuxer, "|   + Multi Commercial" );
4128                 }
4129                 else if( MKV_IS_ID( el, KaxTagMultiDate ) )
4130                 {
4131                     msg_Dbg( &sys.demuxer, "|   + Multi Date" );
4132                 }
4133                 else if( MKV_IS_ID( el, KaxTagMultiEntity ) )
4134                 {
4135                     msg_Dbg( &sys.demuxer, "|   + Multi Entity" );
4136                 }
4137                 else if( MKV_IS_ID( el, KaxTagMultiIdentifier ) )
4138                 {
4139                     msg_Dbg( &sys.demuxer, "|   + Multi Identifier" );
4140                 }
4141                 else if( MKV_IS_ID( el, KaxTagMultiLegal ) )
4142                 {
4143                     msg_Dbg( &sys.demuxer, "|   + Multi Legal" );
4144                 }
4145                 else if( MKV_IS_ID( el, KaxTagMultiTitle ) )
4146                 {
4147                     msg_Dbg( &sys.demuxer, "|   + Multi Title" );
4148                 }
4149                 else
4150                 {
4151                     msg_Dbg( &sys.demuxer, "|   + LoadTag Unknown (%s)", typeid( *el ).name() );
4152                 }
4153             }
4154             ep->Up();
4155         }
4156         else
4157         {
4158             msg_Dbg( &sys.demuxer, "+ Unknown (%s)", typeid( *el ).name() );
4159         }
4160     }
4161     delete ep;
4162
4163     msg_Dbg( &sys.demuxer, "loading tags done." );
4164 }
4165
4166 /*****************************************************************************
4167  * ParseSeekHead:
4168  *****************************************************************************/
4169 void matroska_segment_c::ParseSeekHead( KaxSeekHead *seekhead )
4170 {
4171     EbmlParser  *ep;
4172     EbmlElement *l;
4173     size_t i, j;
4174     int i_upper_level = 0;
4175     bool b_seekable;
4176
4177     i_seekhead_count++;
4178
4179     stream_Control( sys.demuxer.s, STREAM_CAN_SEEK, &b_seekable );
4180     if( !b_seekable )
4181         return;
4182
4183     ep = new EbmlParser( &es, seekhead, &sys.demuxer );
4184
4185     while( ( l = ep->Get() ) != NULL )
4186     {
4187         if( MKV_IS_ID( l, KaxSeek ) )
4188         {
4189             EbmlId id = EbmlVoid::ClassInfos.GlobalId;
4190             int64_t i_pos = -1;
4191
4192             msg_Dbg( &sys.demuxer, "|   |   + Seek" );
4193             ep->Down();
4194             while( ( l = ep->Get() ) != NULL )
4195             {
4196                 if( MKV_IS_ID( l, KaxSeekID ) )
4197                 {
4198                     KaxSeekID &sid = *(KaxSeekID*)l;
4199                     sid.ReadData( es.I_O() );
4200                     id = EbmlId( sid.GetBuffer(), sid.GetSize() );
4201                 }
4202                 else if( MKV_IS_ID( l, KaxSeekPosition ) )
4203                 {
4204                     KaxSeekPosition &spos = *(KaxSeekPosition*)l;
4205                     spos.ReadData( es.I_O() );
4206                     i_pos = (int64_t)segment->GetGlobalPosition( uint64( spos ) );
4207                 }
4208                 else
4209                 {
4210                     /* Many mkvmerge files hit this case. It seems to be a broken SeekHead */
4211                     msg_Dbg( &sys.demuxer, "|   |   + Unknown (%s)", typeid(*l).name()  );
4212                 }
4213             }
4214             ep->Up();
4215
4216             if( i_pos >= 0 )
4217             {
4218                 if( id == KaxCues::ClassInfos.GlobalId )
4219                 {
4220                     msg_Dbg( &sys.demuxer, "|   - cues at %"PRId64, i_pos );
4221                     LoadSeekHeadItem( KaxCues::ClassInfos, i_pos );
4222                 }
4223                 else if( id == KaxInfo::ClassInfos.GlobalId )
4224                 {
4225                     msg_Dbg( &sys.demuxer, "|   - info at %"PRId64, i_pos );
4226                     LoadSeekHeadItem( KaxInfo::ClassInfos, i_pos );
4227                 }
4228                 else if( id == KaxChapters::ClassInfos.GlobalId )
4229                 {
4230                     msg_Dbg( &sys.demuxer, "|   - chapters at %"PRId64, i_pos );
4231                     LoadSeekHeadItem( KaxChapters::ClassInfos, i_pos );
4232                 }
4233                 else if( id == KaxTags::ClassInfos.GlobalId )
4234                 {
4235                     msg_Dbg( &sys.demuxer, "|   - tags at %"PRId64, i_pos );
4236                     LoadSeekHeadItem( KaxTags::ClassInfos, i_pos );
4237                 }
4238                 else if( id == KaxSeekHead::ClassInfos.GlobalId )
4239                 {
4240                     msg_Dbg( &sys.demuxer, "|   - chained seekhead at %"PRId64, i_pos );
4241                     LoadSeekHeadItem( KaxSeekHead::ClassInfos, i_pos );
4242                 }
4243                 else if( id == KaxTracks::ClassInfos.GlobalId )
4244                 {
4245                     msg_Dbg( &sys.demuxer, "|   - tracks at %"PRId64, i_pos );
4246                     LoadSeekHeadItem( KaxTracks::ClassInfos, i_pos );
4247                 }
4248                 else if( id == KaxAttachments::ClassInfos.GlobalId )
4249                 {
4250                     msg_Dbg( &sys.demuxer, "|   - attachments at %"PRId64, i_pos );
4251                     LoadSeekHeadItem( KaxAttachments::ClassInfos, i_pos );
4252                 }
4253                 else
4254                     msg_Dbg( &sys.demuxer, "|   - unknown seekhead reference at %"PRId64, i_pos );
4255             }
4256         }
4257         else
4258             msg_Dbg( &sys.demuxer, "|   |   + ParseSeekHead Unknown (%s)", typeid(*l).name() );
4259     }
4260     delete ep;
4261 }
4262
4263 /*****************************************************************************
4264  * ParseTrackEntry:
4265  *****************************************************************************/
4266 void matroska_segment_c::ParseTrackEntry( KaxTrackEntry *m )
4267 {
4268     size_t i, j, k, n;
4269     bool bSupported = true;
4270
4271     mkv_track_t *tk;
4272
4273     msg_Dbg( &sys.demuxer, "|   |   + Track Entry" );
4274
4275     tk = new mkv_track_t();
4276
4277     /* Init the track */
4278     memset( tk, 0, sizeof( mkv_track_t ) );
4279
4280     es_format_Init( &tk->fmt, UNKNOWN_ES, 0 );
4281     tk->fmt.psz_language = strdup("English");
4282     tk->fmt.psz_description = NULL;
4283
4284     tk->b_default = true;
4285     tk->b_enabled = true;
4286     tk->b_silent = false;
4287     tk->i_number = tracks.size() - 1;
4288     tk->i_extra_data = 0;
4289     tk->p_extra_data = NULL;
4290     tk->psz_codec = NULL;
4291     tk->i_default_duration = 0;
4292     tk->f_timecodescale = 1.0;
4293
4294     tk->b_inited = false;
4295     tk->i_data_init = 0;
4296     tk->p_data_init = NULL;
4297
4298     tk->psz_codec_name = NULL;
4299     tk->psz_codec_settings = NULL;
4300     tk->psz_codec_info_url = NULL;
4301     tk->psz_codec_download_url = NULL;
4302  
4303     tk->i_compression_type = MATROSKA_COMPRESSION_NONE;
4304     tk->p_compression_data = NULL;
4305
4306     for( i = 0; i < m->ListSize(); i++ )
4307     {
4308         EbmlElement *l = (*m)[i];
4309
4310         if( MKV_IS_ID( l, KaxTrackNumber ) )
4311         {
4312             KaxTrackNumber &tnum = *(KaxTrackNumber*)l;
4313
4314             tk->i_number = uint32( tnum );
4315             msg_Dbg( &sys.demuxer, "|   |   |   + Track Number=%u", uint32( tnum ) );
4316         }
4317         else  if( MKV_IS_ID( l, KaxTrackUID ) )
4318         {
4319             KaxTrackUID &tuid = *(KaxTrackUID*)l;
4320
4321             msg_Dbg( &sys.demuxer, "|   |   |   + Track UID=%u",  uint32( tuid ) );
4322         }
4323         else  if( MKV_IS_ID( l, KaxTrackType ) )
4324         {
4325             const char *psz_type;
4326             KaxTrackType &ttype = *(KaxTrackType*)l;
4327
4328             switch( uint8(ttype) )
4329             {
4330                 case track_audio:
4331                     psz_type = "audio";
4332                     tk->fmt.i_cat = AUDIO_ES;
4333                     break;
4334                 case track_video:
4335                     psz_type = "video";
4336                     tk->fmt.i_cat = VIDEO_ES;
4337                     break;
4338                 case track_subtitle:
4339                     psz_type = "subtitle";
4340                     tk->fmt.i_cat = SPU_ES;
4341                     break;
4342                 case track_buttons:
4343                     psz_type = "buttons";
4344                     tk->fmt.i_cat = SPU_ES;
4345                     break;
4346                 default:
4347                     psz_type = "unknown";
4348                     tk->fmt.i_cat = UNKNOWN_ES;
4349                     break;
4350             }
4351
4352             msg_Dbg( &sys.demuxer, "|   |   |   + Track Type=%s", psz_type );
4353         }
4354 //        else  if( EbmlId( *l ) == KaxTrackFlagEnabled::ClassInfos.GlobalId )
4355 //        {
4356 //            KaxTrackFlagEnabled &fenb = *(KaxTrackFlagEnabled*)l;
4357
4358 //            tk->b_enabled = uint32( fenb );
4359 //            msg_Dbg( &sys.demuxer, "|   |   |   + Track Enabled=%u",
4360 //                     uint32( fenb )  );
4361 //        }
4362         else  if( MKV_IS_ID( l, KaxTrackFlagDefault ) )
4363         {
4364             KaxTrackFlagDefault &fdef = *(KaxTrackFlagDefault*)l;
4365
4366             tk->b_default = uint32( fdef );
4367             msg_Dbg( &sys.demuxer, "|   |   |   + Track Default=%u", uint32( fdef )  );
4368         }
4369         else  if( MKV_IS_ID( l, KaxTrackFlagLacing ) )
4370         {
4371             KaxTrackFlagLacing &lac = *(KaxTrackFlagLacing*)l;
4372
4373             msg_Dbg( &sys.demuxer, "|   |   |   + Track Lacing=%d", uint32( lac ) );
4374         }
4375         else  if( MKV_IS_ID( l, KaxTrackMinCache ) )
4376         {
4377             KaxTrackMinCache &cmin = *(KaxTrackMinCache*)l;
4378
4379             msg_Dbg( &sys.demuxer, "|   |   |   + Track MinCache=%d", uint32( cmin ) );
4380         }
4381         else  if( MKV_IS_ID( l, KaxTrackMaxCache ) )
4382         {
4383             KaxTrackMaxCache &cmax = *(KaxTrackMaxCache*)l;
4384
4385             msg_Dbg( &sys.demuxer, "|   |   |   + Track MaxCache=%d", uint32( cmax ) );
4386         }
4387         else  if( MKV_IS_ID( l, KaxTrackDefaultDuration ) )
4388         {
4389             KaxTrackDefaultDuration &defd = *(KaxTrackDefaultDuration*)l;
4390
4391             tk->i_default_duration = uint64(defd);
4392             msg_Dbg( &sys.demuxer, "|   |   |   + Track Default Duration=%"PRId64, uint64(defd) );
4393         }
4394         else  if( MKV_IS_ID( l, KaxTrackTimecodeScale ) )
4395         {
4396             KaxTrackTimecodeScale &ttcs = *(KaxTrackTimecodeScale*)l;
4397
4398             tk->f_timecodescale = float( ttcs );
4399             msg_Dbg( &sys.demuxer, "|   |   |   + Track TimeCodeScale=%f", tk->f_timecodescale );
4400         }
4401         else if( MKV_IS_ID( l, KaxTrackName ) )
4402         {
4403             KaxTrackName &tname = *(KaxTrackName*)l;
4404
4405             tk->fmt.psz_description = ToUTF8( UTFstring( tname ) );
4406             msg_Dbg( &sys.demuxer, "|   |   |   + Track Name=%s", tk->fmt.psz_description );
4407         }
4408         else  if( MKV_IS_ID( l, KaxTrackLanguage ) )
4409         {
4410             KaxTrackLanguage &lang = *(KaxTrackLanguage*)l;
4411
4412             if ( tk->fmt.psz_language != NULL )
4413                 free( tk->fmt.psz_language );
4414             tk->fmt.psz_language = strdup( string( lang ).c_str() );
4415             msg_Dbg( &sys.demuxer,
4416                      "|   |   |   + Track Language=`%s'", tk->fmt.psz_language );
4417         }
4418         else  if( MKV_IS_ID( l, KaxCodecID ) )
4419         {
4420             KaxCodecID &codecid = *(KaxCodecID*)l;
4421
4422             tk->psz_codec = strdup( string( codecid ).c_str() );
4423             msg_Dbg( &sys.demuxer, "|   |   |   + Track CodecId=%s", string( codecid ).c_str() );
4424         }
4425         else  if( MKV_IS_ID( l, KaxCodecPrivate ) )
4426         {
4427             KaxCodecPrivate &cpriv = *(KaxCodecPrivate*)l;
4428
4429             tk->i_extra_data = cpriv.GetSize();
4430             if( tk->i_extra_data > 0 )
4431             {
4432                 tk->p_extra_data = (uint8_t*)malloc( tk->i_extra_data );
4433                 memcpy( tk->p_extra_data, cpriv.GetBuffer(), tk->i_extra_data );
4434             }
4435             msg_Dbg( &sys.demuxer, "|   |   |   + Track CodecPrivate size=%"PRId64, cpriv.GetSize() );
4436         }
4437         else if( MKV_IS_ID( l, KaxCodecName ) )
4438         {
4439             KaxCodecName &cname = *(KaxCodecName*)l;
4440
4441             tk->psz_codec_name = ToUTF8( UTFstring( cname ) );
4442             msg_Dbg( &sys.demuxer, "|   |   |   + Track Codec Name=%s", tk->psz_codec_name );
4443         }
4444         else if( MKV_IS_ID( l, KaxContentEncodings ) )
4445         {
4446             EbmlMaster *cencs = static_cast<EbmlMaster*>(l);
4447             MkvTree( sys.demuxer, 3, "Content Encodings" );
4448             if ( cencs->ListSize() > 1 )
4449             {
4450                 msg_Err( &sys.demuxer, "Multiple Compression method not supported" );
4451                 bSupported = false;
4452             }
4453             for( j = 0; j < cencs->ListSize(); j++ )
4454             {
4455                 EbmlElement *l2 = (*cencs)[j];
4456                 if( MKV_IS_ID( l2, KaxContentEncoding ) )
4457                 {
4458                     MkvTree( sys.demuxer, 4, "Content Encoding" );
4459                     EbmlMaster *cenc = static_cast<EbmlMaster*>(l2);
4460                     for( k = 0; k < cenc->ListSize(); k++ )
4461                     {
4462                         EbmlElement *l3 = (*cenc)[k];
4463                         if( MKV_IS_ID( l3, KaxContentEncodingOrder ) )
4464                         {
4465                             KaxContentEncodingOrder &encord = *(KaxContentEncodingOrder*)l3;
4466                             MkvTree( sys.demuxer, 5, "Order: %i", uint32( encord ) );
4467                         }
4468                         else if( MKV_IS_ID( l3, KaxContentEncodingScope ) )
4469                         {
4470                             KaxContentEncodingScope &encscope = *(KaxContentEncodingScope*)l3;
4471                             MkvTree( sys.demuxer, 5, "Scope: %i", uint32( encscope ) );
4472                         }
4473                         else if( MKV_IS_ID( l3, KaxContentEncodingType ) )
4474                         {
4475                             KaxContentEncodingType &enctype = *(KaxContentEncodingType*)l3;
4476                             MkvTree( sys.demuxer, 5, "Type: %i", uint32( enctype ) );
4477                         }
4478                         else if( MKV_IS_ID( l3, KaxContentCompression ) )
4479                         {
4480                             EbmlMaster *compr = static_cast<EbmlMaster*>(l3);
4481                             MkvTree( sys.demuxer, 5, "Content Compression" );
4482                             for( n = 0; n < compr->ListSize(); n++ )
4483                             {
4484                                 EbmlElement *l4 = (*compr)[n];
4485                                 if( MKV_IS_ID( l4, KaxContentCompAlgo ) )
4486                                 {
4487                                     KaxContentCompAlgo &compalg = *(KaxContentCompAlgo*)l4;
4488                                     MkvTree( sys.demuxer, 6, "Compression Algorithm: %i", uint32(compalg) );
4489                                     tk->i_compression_type = uint32( compalg );
4490                                     if ( ( tk->i_compression_type != MATROSKA_COMPRESSION_ZLIB ) &&
4491                                          ( tk->i_compression_type != MATROSKA_COMPRESSION_HEADER ) )
4492                                     {
4493                                         msg_Err( &sys.demuxer, "Track Compression method %d not supported", tk->i_compression_type );
4494                                         bSupported = false;
4495                                     }
4496                                 }
4497                                 else if( MKV_IS_ID( l4, KaxContentCompSettings ) )
4498                                 {
4499                                     tk->p_compression_data = new KaxContentCompSettings( *(KaxContentCompSettings*)l4 );
4500                                 }
4501                                 else
4502                                 {
4503                                     MkvTree( sys.demuxer, 6, "Unknown (%s)", typeid(*l4).name() );
4504                                 }
4505                             }
4506                         }
4507                         else
4508                         {
4509                             MkvTree( sys.demuxer, 5, "Unknown (%s)", typeid(*l3).name() );
4510                         }
4511                     }
4512                 }
4513                 else
4514                 {
4515                     MkvTree( sys.demuxer, 4, "Unknown (%s)", typeid(*l2).name() );
4516                 }
4517             }
4518         }
4519 //        else if( EbmlId( *l ) == KaxCodecSettings::ClassInfos.GlobalId )
4520 //        {
4521 //            KaxCodecSettings &cset = *(KaxCodecSettings*)l;
4522
4523 //            tk->psz_codec_settings = ToUTF8( UTFstring( cset ) );
4524 //            msg_Dbg( &sys.demuxer, "|   |   |   + Track Codec Settings=%s", tk->psz_codec_settings );
4525 //        }
4526 //        else if( EbmlId( *l ) == KaxCodecInfoURL::ClassInfos.GlobalId )
4527 //        {
4528 //            KaxCodecInfoURL &ciurl = *(KaxCodecInfoURL*)l;
4529
4530 //            tk->psz_codec_info_url = strdup( string( ciurl ).c_str() );
4531 //            msg_Dbg( &sys.demuxer, "|   |   |   + Track Codec Info URL=%s", tk->psz_codec_info_url );
4532 //        }
4533 //        else if( EbmlId( *l ) == KaxCodecDownloadURL::ClassInfos.GlobalId )
4534 //        {
4535 //            KaxCodecDownloadURL &cdurl = *(KaxCodecDownloadURL*)l;
4536
4537 //            tk->psz_codec_download_url = strdup( string( cdurl ).c_str() );
4538 //            msg_Dbg( &sys.demuxer, "|   |   |   + Track Codec Info URL=%s", tk->psz_codec_download_url );
4539 //        }
4540 //        else if( EbmlId( *l ) == KaxCodecDecodeAll::ClassInfos.GlobalId )
4541 //        {
4542 //            KaxCodecDecodeAll &cdall = *(KaxCodecDecodeAll*)l;
4543
4544 //            msg_Dbg( &sys.demuxer, "|   |   |   + Track Codec Decode All=%u <== UNUSED", uint8( cdall ) );
4545 //        }
4546 //        else if( EbmlId( *l ) == KaxTrackOverlay::ClassInfos.GlobalId )
4547 //        {
4548 //            KaxTrackOverlay &tovr = *(KaxTrackOverlay*)l;
4549
4550 //            msg_Dbg( &sys.demuxer, "|   |   |   + Track Overlay=%u <== UNUSED", uint32( tovr ) );
4551 //        }
4552         else  if( MKV_IS_ID( l, KaxTrackVideo ) )
4553         {
4554             EbmlMaster *tkv = static_cast<EbmlMaster*>(l);
4555             unsigned int j;
4556             unsigned int i_crop_right = 0, i_crop_left = 0, i_crop_top = 0, i_crop_bottom = 0;
4557             unsigned int i_display_unit = 0, i_display_width = 0, i_display_height = 0;
4558
4559             msg_Dbg( &sys.demuxer, "|   |   |   + Track Video" );
4560             tk->f_fps = 0.0;
4561
4562             tk->fmt.video.i_frame_rate_base = (unsigned int)(tk->i_default_duration / 1000);
4563             tk->fmt.video.i_frame_rate = 1000000;
4564  
4565             for( j = 0; j < tkv->ListSize(); j++ )
4566             {
4567                 EbmlElement *l = (*tkv)[j];
4568 //                if( EbmlId( *el4 ) == KaxVideoFlagInterlaced::ClassInfos.GlobalId )
4569 //                {
4570 //                    KaxVideoFlagInterlaced &fint = *(KaxVideoFlagInterlaced*)el4;
4571
4572 //                    msg_Dbg( &sys.demuxer, "|   |   |   |   + Track Video Interlaced=%u", uint8( fint ) );
4573 //                }
4574 //                else if( EbmlId( *el4 ) == KaxVideoStereoMode::ClassInfos.GlobalId )
4575 //                {
4576 //                    KaxVideoStereoMode &stereo = *(KaxVideoStereoMode*)el4;
4577
4578 //                    msg_Dbg( &sys.demuxer, "|   |   |   |   + Track Video Stereo Mode=%u", uint8( stereo ) );
4579 //                }
4580 //                else
4581                 if( MKV_IS_ID( l, KaxVideoPixelWidth ) )
4582                 {
4583                     KaxVideoPixelWidth &vwidth = *(KaxVideoPixelWidth*)l;
4584
4585                     tk->fmt.video.i_width += uint16( vwidth );
4586                     msg_Dbg( &sys.demuxer, "|   |   |   |   + width=%d", uint16( vwidth ) );
4587                 }
4588                 else if( MKV_IS_ID( l, KaxVideoPixelHeight ) )
4589                 {
4590                     KaxVideoPixelWidth &vheight = *(KaxVideoPixelWidth*)l;
4591
4592                     tk->fmt.video.i_height += uint16( vheight );
4593                     msg_Dbg( &sys.demuxer, "|   |   |   |   + height=%d", uint16( vheight ) );
4594                 }
4595                 else if( MKV_IS_ID( l, KaxVideoDisplayWidth ) )
4596                 {
4597                     KaxVideoDisplayWidth &vwidth = *(KaxVideoDisplayWidth*)l;
4598
4599                     i_display_width = uint16( vwidth );
4600                     msg_Dbg( &sys.demuxer, "|   |   |   |   + display width=%d", uint16( vwidth ) );
4601                 }
4602                 else if( MKV_IS_ID( l, KaxVideoDisplayHeight ) )
4603                 {
4604                     KaxVideoDisplayWidth &vheight = *(KaxVideoDisplayWidth*)l;
4605
4606                     i_display_height = uint16( vheight );
4607                     msg_Dbg( &sys.demuxer, "|   |   |   |   + display height=%d", uint16( vheight ) );
4608                 }
4609                 else if( MKV_IS_ID( l, KaxVideoPixelCropBottom ) )
4610                 {
4611                     KaxVideoPixelCropBottom &cropval = *(KaxVideoPixelCropBottom*)l;
4612
4613                     i_crop_bottom = uint16( cropval );
4614                     msg_Dbg( &sys.demuxer, "|   |   |   |   + crop pixel bottom=%d", uint16( cropval ) );
4615                 }
4616                 else if( MKV_IS_ID( l, KaxVideoPixelCropTop ) )
4617                 {
4618                     KaxVideoPixelCropTop &cropval = *(KaxVideoPixelCropTop*)l;
4619
4620                     i_crop_top = uint16( cropval );
4621                     msg_Dbg( &sys.demuxer, "|   |   |   |   + crop pixel top=%d", uint16( cropval ) );
4622                 }
4623                 else if( MKV_IS_ID( l, KaxVideoPixelCropRight ) )
4624                 {
4625                     KaxVideoPixelCropRight &cropval = *(KaxVideoPixelCropRight*)l;
4626
4627                     i_crop_right = uint16( cropval );
4628                     msg_Dbg( &sys.demuxer, "|   |   |   |   + crop pixel right=%d", uint16( cropval ) );
4629                 }
4630                 else if( MKV_IS_ID( l, KaxVideoPixelCropLeft ) )
4631                 {
4632                     KaxVideoPixelCropLeft &cropval = *(KaxVideoPixelCropLeft*)l;
4633
4634                     i_crop_left = uint16( cropval );
4635                     msg_Dbg( &sys.demuxer, "|   |   |   |   + crop pixel left=%d", uint16( cropval ) );
4636                 }
4637                 else if( MKV_IS_ID( l, KaxVideoFrameRate ) )
4638                 {
4639                     KaxVideoFrameRate &vfps = *(KaxVideoFrameRate*)l;
4640
4641                     tk->f_fps = float( vfps );
4642                     msg_Dbg( &sys.demuxer, "   |   |   |   + fps=%f", float( vfps ) );
4643                 }
4644                 else if( EbmlId( *l ) == KaxVideoDisplayUnit::ClassInfos.GlobalId )
4645                 {
4646                     KaxVideoDisplayUnit &vdmode = *(KaxVideoDisplayUnit*)l;
4647
4648                     i_display_unit = uint8( vdmode );
4649                     msg_Dbg( &sys.demuxer, "|   |   |   |   + Track Video Display Unit=%s",
4650                              uint8( vdmode ) == 0 ? "pixels" : ( uint8( vdmode ) == 1 ? "centimeters": "inches" ) );
4651                 }
4652 //                else if( EbmlId( *l ) == KaxVideoAspectRatio::ClassInfos.GlobalId )
4653 //                {
4654 //                    KaxVideoAspectRatio &ratio = *(KaxVideoAspectRatio*)l;
4655
4656 //                    msg_Dbg( &sys.demuxer, "   |   |   |   + Track Video Aspect Ratio Type=%u", uint8( ratio ) );
4657 //                }
4658 //                else if( EbmlId( *l ) == KaxVideoGamma::ClassInfos.GlobalId )
4659 //                {
4660 //                    KaxVideoGamma &gamma = *(KaxVideoGamma*)l;
4661
4662 //                    msg_Dbg( &sys.demuxer, "   |   |   |   + gamma=%f", float( gamma ) );
4663 //                }
4664                 else
4665                 {
4666                     msg_Dbg( &sys.demuxer, "|   |   |   |   + Unknown (%s)", typeid(*l).name() );
4667                 }
4668             }
4669             if( i_display_height && i_display_width )
4670                 tk->fmt.video.i_aspect = VOUT_ASPECT_FACTOR * i_display_width / i_display_height;
4671             if( i_crop_left || i_crop_right || i_crop_top || i_crop_bottom )
4672             {
4673                 tk->fmt.video.i_visible_width = tk->fmt.video.i_width;
4674                 tk->fmt.video.i_visible_height = tk->fmt.video.i_height;
4675                 tk->fmt.video.i_x_offset = i_crop_left;
4676                 tk->fmt.video.i_y_offset = i_crop_top;
4677                 tk->fmt.video.i_visible_width -= i_crop_left + i_crop_right;
4678                 tk->fmt.video.i_visible_height -= i_crop_top + i_crop_bottom;
4679             }
4680             /* FIXME: i_display_* allows you to not only set DAR, but also a zoom factor.
4681                we do not support this atm */
4682         }
4683         else  if( MKV_IS_ID( l, KaxTrackAudio ) )
4684         {
4685             EbmlMaster *tka = static_cast<EbmlMaster*>(l);
4686             unsigned int j;
4687
4688             msg_Dbg( &sys.demuxer, "|   |   |   + Track Audio" );
4689
4690             for( j = 0; j < tka->ListSize(); j++ )
4691             {
4692                 EbmlElement *l = (*tka)[j];
4693
4694                 if( MKV_IS_ID( l, KaxAudioSamplingFreq ) )
4695                 {
4696                     KaxAudioSamplingFreq &afreq = *(KaxAudioSamplingFreq*)l;
4697
4698                     tk->i_original_rate = tk->fmt.audio.i_rate = (int)float( afreq );
4699                     msg_Dbg( &sys.demuxer, "|   |   |   |   + afreq=%d", tk->fmt.audio.i_rate );
4700                 }
4701                 else if( MKV_IS_ID( l, KaxAudioOutputSamplingFreq ) )
4702                 {
4703                     KaxAudioOutputSamplingFreq &afreq = *(KaxAudioOutputSamplingFreq*)l;
4704
4705                     tk->fmt.audio.i_rate = (int)float( afreq );
4706                     msg_Dbg( &sys.demuxer, "|   |   |   |   + aoutfreq=%d", tk->fmt.audio.i_rate );
4707                 }
4708                 else if( MKV_IS_ID( l, KaxAudioChannels ) )
4709                 {
4710                     KaxAudioChannels &achan = *(KaxAudioChannels*)l;
4711
4712                     tk->fmt.audio.i_channels = uint8( achan );
4713                     msg_Dbg( &sys.demuxer, "|   |   |   |   + achan=%u", uint8( achan ) );
4714                 }
4715                 else if( MKV_IS_ID( l, KaxAudioBitDepth ) )
4716                 {
4717                     KaxAudioBitDepth &abits = *(KaxAudioBitDepth*)l;
4718
4719                     tk->fmt.audio.i_bitspersample = uint8( abits );
4720                     msg_Dbg( &sys.demuxer, "|   |   |   |   + abits=%u", uint8( abits ) );
4721                 }
4722                 else
4723                 {
4724                     msg_Dbg( &sys.demuxer, "|   |   |   |   + Unknown (%s)", typeid(*l).name() );
4725                 }
4726             }
4727         }
4728         else
4729         {
4730             msg_Dbg( &sys.demuxer, "|   |   |   + Unknown (%s)",
4731                      typeid(*l).name() );
4732         }
4733     }
4734
4735     if ( bSupported )
4736     {
4737         tracks.push_back( tk );
4738     }
4739     else
4740     {
4741         msg_Err( &sys.demuxer, "Track Entry %d not supported", tk->i_number );
4742         delete tk;
4743     }
4744 }
4745
4746 /*****************************************************************************
4747  * ParseTracks:
4748  *****************************************************************************/
4749 void matroska_segment_c::ParseTracks( KaxTracks *tracks )
4750 {
4751     EbmlElement *el;
4752     unsigned int i;
4753     int i_upper_level = 0;
4754
4755     /* Master elements */
4756     tracks->Read( es, tracks->Generic().Context, i_upper_level, el, true );
4757
4758     for( i = 0; i < tracks->ListSize(); i++ )
4759     {
4760         EbmlElement *l = (*tracks)[i];
4761
4762         if( MKV_IS_ID( l, KaxTrackEntry ) )
4763         {
4764             ParseTrackEntry( static_cast<KaxTrackEntry *>(l) );
4765         }
4766         else
4767         {
4768             msg_Dbg( &sys.demuxer, "|   |   + Unknown (%s)", typeid(*l).name() );
4769         }
4770     }
4771 }
4772
4773 /*****************************************************************************
4774  * ParseInfo:
4775  *****************************************************************************/
4776 void matroska_segment_c::ParseInfo( KaxInfo *info )
4777 {
4778     EbmlElement *el;
4779     EbmlMaster  *m;
4780     size_t i, j;
4781     int i_upper_level = 0;
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 )
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 #if 0
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 #endif
5253 }
5254
5255
5256 /*****************************************************************************
5257  * Misc
5258  *****************************************************************************/
5259
5260 void matroska_segment_c::IndexAppendCluster( KaxCluster *cluster )
5261 {
5262 #define idx p_indexes[i_index]
5263     idx.i_track       = -1;
5264     idx.i_block_number= -1;
5265     idx.i_position    = cluster->GetElementPosition();
5266     idx.i_time        = -1;
5267     idx.b_key         = true;
5268
5269     i_index++;
5270     if( i_index >= i_index_max )
5271     {
5272         i_index_max += 1024;
5273         p_indexes = (mkv_index_t*)realloc( p_indexes, sizeof( mkv_index_t ) * i_index_max );
5274     }
5275 #undef idx
5276 }
5277
5278 void chapter_edition_c::RefreshChapters( )
5279 {
5280     chapter_item_c::RefreshChapters( b_ordered, -1 );
5281     b_display_seekpoint = false;
5282 }
5283
5284 int64_t chapter_item_c::RefreshChapters( bool b_ordered, int64_t i_prev_user_time )
5285 {
5286     int64_t i_user_time = i_prev_user_time;
5287  
5288     // first the sub-chapters, and then ourself
5289     std::vector<chapter_item_c*>::iterator index = sub_chapters.begin();
5290     while ( index != sub_chapters.end() )
5291     {
5292         i_user_time = (*index)->RefreshChapters( b_ordered, i_user_time );
5293         index++;
5294     }
5295
5296     if ( b_ordered )
5297     {
5298         // the ordered chapters always start at zero
5299         if ( i_prev_user_time == -1 )
5300         {
5301             if ( i_user_time == -1 )
5302                 i_user_time = 0;
5303             i_prev_user_time = 0;
5304         }
5305
5306         i_user_start_time = i_prev_user_time;
5307         if ( i_end_time != -1 && i_user_time == i_prev_user_time )
5308         {
5309             i_user_end_time = i_user_start_time - i_start_time + i_end_time;
5310         }
5311         else
5312         {
5313             i_user_end_time = i_user_time;
5314         }
5315     }
5316     else
5317     {
5318         if ( sub_chapters.begin() != sub_chapters.end() )
5319             std::sort( sub_chapters.begin(), sub_chapters.end(), chapter_item_c::CompareTimecode );
5320         i_user_start_time = i_start_time;
5321         if ( i_end_time != -1 )
5322             i_user_end_time = i_end_time;
5323         else if ( i_user_time != -1 )
5324             i_user_end_time = i_user_time;
5325         else
5326             i_user_end_time = i_user_start_time;
5327     }
5328
5329     return i_user_end_time;
5330 }
5331
5332 mtime_t chapter_edition_c::Duration() const
5333 {
5334     mtime_t i_result = 0;
5335  
5336     if ( sub_chapters.size() )
5337     {
5338         std::vector<chapter_item_c*>::const_iterator index = sub_chapters.end();
5339         index--;
5340         i_result = (*index)->i_user_end_time;
5341     }
5342  
5343     return i_result;
5344 }
5345
5346 chapter_item_c * chapter_edition_c::FindTimecode( mtime_t i_timecode, const chapter_item_c * p_current )
5347 {
5348     if ( !b_ordered )
5349         p_current = NULL;
5350     bool b_found_current = false;
5351     return chapter_item_c::FindTimecode( i_timecode, p_current, b_found_current );
5352 }
5353
5354 chapter_item_c *chapter_item_c::FindTimecode( mtime_t i_user_timecode, const chapter_item_c * p_current, bool & b_found )
5355 {
5356     chapter_item_c *psz_result = NULL;
5357
5358     if ( p_current == this )
5359         b_found = true;
5360
5361     if ( i_user_timecode >= i_user_start_time &&
5362         ( i_user_timecode < i_user_end_time ||
5363           ( i_user_start_time == i_user_end_time && i_user_timecode == i_user_end_time )))
5364     {
5365         std::vector<chapter_item_c*>::iterator index = sub_chapters.begin();
5366         while ( index != sub_chapters.end() && ((p_current == NULL && psz_result == NULL) || (p_current != NULL && (!b_found || psz_result == NULL))))
5367         {
5368             psz_result = (*index)->FindTimecode( i_user_timecode, p_current, b_found );
5369             index++;
5370         }
5371  
5372         if ( psz_result == NULL )
5373             psz_result = this;
5374     }
5375
5376     return psz_result;
5377 }
5378
5379 bool chapter_item_c::ParentOf( const chapter_item_c & item ) const
5380 {
5381     if ( &item == this )
5382         return true;
5383
5384     std::vector<chapter_item_c*>::const_iterator index = sub_chapters.begin();
5385     while ( index != sub_chapters.end() )
5386     {
5387         if ( (*index)->ParentOf( item ) )
5388             return true;
5389         index++;
5390     }
5391
5392     return false;
5393 }
5394
5395 void demux_sys_t::PreloadFamily( const matroska_segment_c & of_segment )
5396 {
5397     for (size_t i=0; i<opened_segments.size(); i++)
5398     {
5399         opened_segments[i]->PreloadFamily( of_segment );
5400     }
5401 }
5402 bool matroska_segment_c::PreloadFamily( const matroska_segment_c & of_segment )
5403 {
5404     if ( b_preloaded )
5405         return false;
5406
5407     for (size_t i=0; i<families.size(); i++)
5408     {
5409         for (size_t j=0; j<of_segment.families.size(); j++)
5410         {
5411             if ( *(families[i]) == *(of_segment.families[j]) )
5412                 return Preload( );
5413         }
5414     }
5415
5416     return false;
5417 }
5418
5419 // preload all the linked segments for all preloaded segments
5420 void demux_sys_t::PreloadLinked( matroska_segment_c *p_segment )
5421 {
5422     size_t i_preloaded, i, j;
5423     virtual_segment_c *p_seg;
5424
5425     p_current_segment = VirtualFromSegments( p_segment );
5426  
5427     used_segments.push_back( p_current_segment );
5428
5429     // create all the other virtual segments of the family
5430     do {
5431         i_preloaded = 0;
5432         for ( i=0; i< opened_segments.size(); i++ )
5433         {
5434             if ( opened_segments[i]->b_preloaded && !IsUsedSegment( *opened_segments[i] ) )
5435             {
5436                 p_seg = VirtualFromSegments( opened_segments[i] );
5437                 used_segments.push_back( p_seg );
5438                 i_preloaded++;
5439             }
5440         }
5441     } while ( i_preloaded ); // worst case: will stop when all segments are found as family related
5442
5443     // publish all editions of all usable segment
5444     for ( i=0; i< used_segments.size(); i++ )
5445     {
5446         p_seg = used_segments[i];
5447         if ( p_seg->p_editions != NULL )
5448         {
5449             std::string sz_name;
5450             input_title_t *p_title = vlc_input_title_New();
5451             p_seg->i_sys_title = i;
5452             int i_chapters;
5453
5454             // TODO use a name for each edition, let the TITLE deal with a codec name
5455             for ( j=0; j<p_seg->p_editions->size(); j++ )
5456             {
5457                 if ( p_title->psz_name == NULL )
5458                 {
5459                     sz_name = (*p_seg->p_editions)[j]->GetMainName();
5460                     if ( sz_name != "" )
5461                         p_title->psz_name = strdup( sz_name.c_str() );
5462                 }
5463
5464                 chapter_edition_c *p_edition = (*p_seg->p_editions)[j];
5465
5466                 i_chapters = 0;
5467                 p_edition->PublishChapters( *p_title, i_chapters, 0 );
5468             }
5469
5470             // create a name if there is none
5471             if ( p_title->psz_name == NULL )
5472             {
5473                 sz_name = N_("Segment");
5474                 char psz_str[6];
5475                 sprintf( psz_str, " %d", (int)i );
5476                 sz_name += psz_str;
5477                 p_title->psz_name = strdup( sz_name.c_str() );
5478             }
5479
5480             titles.push_back( p_title );
5481         }
5482     }
5483
5484     // TODO decide which segment should be first used (VMG for DVD)
5485 }
5486
5487 bool demux_sys_t::IsUsedSegment( matroska_segment_c &segment ) const
5488 {
5489     for ( size_t i=0; i< used_segments.size(); i++ )
5490     {
5491         if ( used_segments[i]->FindUID( *segment.p_segment_uid ) )
5492             return true;
5493     }
5494     return false;
5495 }
5496
5497 virtual_segment_c *demux_sys_t::VirtualFromSegments( matroska_segment_c *p_segment ) const
5498 {
5499     size_t i_preloaded, i;
5500
5501     virtual_segment_c *p_result = new virtual_segment_c( p_segment );
5502
5503     // fill our current virtual segment with all hard linked segments
5504     do {
5505         i_preloaded = 0;
5506         for ( i=0; i< opened_segments.size(); i++ )
5507         {
5508             i_preloaded += p_result->AddSegment( opened_segments[i] );
5509         }
5510     } while ( i_preloaded ); // worst case: will stop when all segments are found as linked
5511
5512     p_result->Sort( );
5513
5514     p_result->PreloadLinked( );
5515
5516     p_result->PrepareChapters( );
5517
5518     return p_result;
5519 }
5520
5521 bool demux_sys_t::PreparePlayback( virtual_segment_c *p_new_segment )
5522 {
5523     if ( p_new_segment != NULL && p_new_segment != p_current_segment )
5524     {
5525         if ( p_current_segment != NULL && p_current_segment->Segment() != NULL )
5526             p_current_segment->Segment()->UnSelect();
5527
5528         p_current_segment = p_new_segment;
5529         i_current_title = p_new_segment->i_sys_title;
5530     }
5531     if( !p_current_segment->Segment()->b_cues )
5532         msg_Warn( &p_current_segment->Segment()->sys.demuxer, "no cues/empty cues found->seek won't be precise" );
5533
5534     f_duration = p_current_segment->Duration();
5535
5536     /* add information */
5537     p_current_segment->Segment()->InformationCreate( );
5538     p_current_segment->Segment()->Select( 0 );
5539
5540     return true;
5541 }
5542
5543 void demux_sys_t::JumpTo( virtual_segment_c & vsegment, chapter_item_c * p_chapter )
5544 {
5545     // if the segment is not part of the current segment, select the new one
5546     if ( &vsegment != p_current_segment )
5547     {
5548         PreparePlayback( &vsegment );
5549     }
5550
5551     if ( p_chapter != NULL )
5552     {
5553         if ( !p_chapter->Enter( true ) )
5554         {
5555             // jump to the location in the found segment
5556             vsegment.Seek( demuxer, p_chapter->i_user_start_time, -1, p_chapter, -1 );
5557         }
5558     }
5559  
5560 }
5561
5562 bool matroska_segment_c::CompareSegmentUIDs( const matroska_segment_c * p_item_a, const matroska_segment_c * p_item_b )
5563 {
5564     EbmlBinary *p_tmp;
5565
5566     if ( p_item_a == NULL || p_item_b == NULL )
5567         return false;
5568
5569     p_tmp = (EbmlBinary *)p_item_a->p_segment_uid;
5570     if ( p_item_b->p_prev_segment_uid != NULL
5571           && *p_tmp == *p_item_b->p_prev_segment_uid )
5572         return true;
5573
5574     p_tmp = (EbmlBinary *)p_item_a->p_next_segment_uid;
5575     if ( !p_tmp )
5576         return false;
5577  
5578     if ( p_item_b->p_segment_uid != NULL
5579           && *p_tmp == *p_item_b->p_segment_uid )
5580         return true;
5581
5582     if ( p_item_b->p_prev_segment_uid != NULL
5583           && *p_tmp == *p_item_b->p_prev_segment_uid )
5584         return true;
5585
5586     return false;
5587 }
5588
5589 bool matroska_segment_c::Preload( )
5590 {
5591     if ( b_preloaded )
5592         return false;
5593
5594     EbmlElement *el = NULL;
5595
5596     ep->Reset( &sys.demuxer );
5597
5598     while( ( el = ep->Get() ) != NULL )
5599     {
5600         if( MKV_IS_ID( el, KaxSeekHead ) )
5601         {
5602             /* Multiple allowed */
5603             /* We bail at 10, to prevent possible recursion */
5604             msg_Dbg(  &sys.demuxer, "|   + Seek head" );
5605             if( i_seekhead_count < 10 )
5606             {
5607                 i_seekhead_position = (int64_t) es.I_O().getFilePointer();
5608                 ParseSeekHead( static_cast<KaxSeekHead*>( el ) );
5609             }
5610         }
5611         else if( MKV_IS_ID( el, KaxInfo ) )
5612         {
5613             /* Multiple allowed, mandatory */
5614             msg_Dbg(  &sys.demuxer, "|   + Information" );
5615             if( i_info_position < 0 ) // FIXME
5616                 ParseInfo( static_cast<KaxInfo*>( el ) );
5617             i_info_position = (int64_t) es.I_O().getFilePointer();
5618         }
5619         else if( MKV_IS_ID( el, KaxTracks ) )
5620         {
5621             /* Multiple allowed */
5622             msg_Dbg(  &sys.demuxer, "|   + Tracks" );
5623             if( i_tracks_position < 0 ) // FIXME
5624                 ParseTracks( static_cast<KaxTracks*>( el ) );
5625             if ( tracks.size() == 0 )
5626             {
5627                 msg_Err( &sys.demuxer, "No tracks supported" );
5628                 return false;
5629             }
5630             i_tracks_position = (int64_t) es.I_O().getFilePointer();
5631         }
5632         else if( MKV_IS_ID( el, KaxCues ) )
5633         {
5634             msg_Dbg(  &sys.demuxer, "|   + Cues" );
5635             if( i_cues_position < 0 )
5636                 LoadCues( static_cast<KaxCues*>( el ) );
5637             i_cues_position = (int64_t) es.I_O().getFilePointer();
5638         }
5639         else if( MKV_IS_ID( el, KaxCluster ) )
5640         {
5641             msg_Dbg( &sys.demuxer, "|   + Cluster" );
5642
5643             cluster = (KaxCluster*)el;
5644
5645             i_cluster_pos = i_start_pos = cluster->GetElementPosition();
5646             ParseCluster( );
5647
5648             ep->Down();
5649             /* stop pre-parsing the stream */
5650             break;
5651         }
5652         else if( MKV_IS_ID( el, KaxAttachments ) )
5653         {
5654             msg_Dbg( &sys.demuxer, "|   + Attachments" );
5655             if( i_attachments_position < 0 )
5656                 ParseAttachments( static_cast<KaxAttachments*>( el ) );
5657             i_attachments_position = (int64_t) es.I_O().getFilePointer();
5658         }
5659         else if( MKV_IS_ID( el, KaxChapters ) )
5660         {
5661             msg_Dbg( &sys.demuxer, "|   + Chapters" );
5662             if( i_chapters_position < 0 )
5663                 ParseChapters( static_cast<KaxChapters*>( el ) );
5664             i_chapters_position = (int64_t) es.I_O().getFilePointer();
5665         }
5666         else if( MKV_IS_ID( el, KaxTag ) )
5667         {
5668             msg_Dbg( &sys.demuxer, "|   + Tags" );
5669             if( i_tags_position < 0) // FIXME
5670                 ;//LoadTags( static_cast<KaxTags*>( el ) );
5671             i_tags_position = (int64_t) es.I_O().getFilePointer();
5672         }
5673         else
5674             msg_Dbg( &sys.demuxer, "|   + Preload Unknown (%s)", typeid(*el).name() );
5675     }
5676
5677     b_preloaded = true;
5678
5679     return true;
5680 }
5681
5682 /* Here we try to load elements that were found in Seek Heads, but not yet parsed */
5683 bool matroska_segment_c::LoadSeekHeadItem( const EbmlCallbacks & ClassInfos, int64_t i_element_position )
5684 {
5685     int64_t     i_sav_position = (int64_t)es.I_O().getFilePointer();
5686     EbmlElement *el;
5687
5688     es.I_O().setFilePointer( i_element_position, seek_beginning );
5689     el = es.FindNextID( ClassInfos, 0xFFFFFFFFL);
5690
5691     if( el == NULL )
5692     {
5693         msg_Err( &sys.demuxer, "cannot load some cues/chapters/tags etc. (broken seekhead or file)" );
5694         es.I_O().setFilePointer( i_sav_position, seek_beginning );
5695         return false;
5696     }
5697
5698     if( MKV_IS_ID( el, KaxSeekHead ) )
5699     {
5700         /* Multiple allowed */
5701         msg_Dbg( &sys.demuxer, "|   + Seek head" );
5702         if( i_seekhead_count < 10 )
5703         {
5704             i_seekhead_position = i_element_position;
5705             ParseSeekHead( static_cast<KaxSeekHead*>( el ) );
5706         }
5707     }
5708     else if( MKV_IS_ID( el, KaxInfo ) ) // FIXME
5709     {
5710         /* Multiple allowed, mandatory */
5711         msg_Dbg( &sys.demuxer, "|   + Information" );
5712         if( i_info_position < 0 )
5713             ParseInfo( static_cast<KaxInfo*>( el ) );
5714         i_info_position = i_element_position;
5715     }
5716     else if( MKV_IS_ID( el, KaxTracks ) ) // FIXME
5717     {
5718         /* Multiple allowed */
5719         msg_Dbg( &sys.demuxer, "|   + Tracks" );
5720         if( i_tracks_position < 0 )
5721             ParseTracks( static_cast<KaxTracks*>( el ) );
5722         if ( tracks.size() == 0 )
5723         {
5724             msg_Err( &sys.demuxer, "No tracks supported" );
5725             delete el;
5726             es.I_O().setFilePointer( i_sav_position, seek_beginning );
5727             return false;
5728         }
5729         i_tracks_position = i_element_position;
5730     }
5731     else if( MKV_IS_ID( el, KaxCues ) )
5732     {
5733         msg_Dbg( &sys.demuxer, "|   + Cues" );
5734         if( i_cues_position < 0 )
5735             LoadCues( static_cast<KaxCues*>( el ) );
5736         i_cues_position = i_element_position;
5737     }
5738     else if( MKV_IS_ID( el, KaxAttachments ) )
5739     {
5740         msg_Dbg( &sys.demuxer, "|   + Attachments" );
5741         if( i_attachments_position < 0 )
5742             ParseAttachments( static_cast<KaxAttachments*>( el ) );
5743         i_attachments_position = i_element_position;
5744     }
5745     else if( MKV_IS_ID( el, KaxChapters ) )
5746     {
5747         msg_Dbg( &sys.demuxer, "|   + Chapters" );
5748         if( i_chapters_position < 0 )
5749             ParseChapters( static_cast<KaxChapters*>( el ) );
5750         i_chapters_position = i_element_position;
5751     }
5752     else if( MKV_IS_ID( el, KaxTag ) ) // FIXME
5753     {
5754         msg_Dbg( &sys.demuxer, "|   + Tags" );
5755         if( i_tags_position < 0 )
5756             ;//LoadTags( static_cast<KaxTags*>( el ) );
5757         i_tags_position = i_element_position;
5758     }
5759     else
5760     {
5761         msg_Dbg( &sys.demuxer, "|   + LoadSeekHeadItem Unknown (%s)", typeid(*el).name() );
5762     }
5763     delete el;
5764
5765     es.I_O().setFilePointer( i_sav_position, seek_beginning );
5766     return true;
5767 }
5768
5769 matroska_segment_c *demux_sys_t::FindSegment( const EbmlBinary & uid ) const
5770 {
5771     for (size_t i=0; i<opened_segments.size(); i++)
5772     {
5773         if ( *opened_segments[i]->p_segment_uid == uid )
5774             return opened_segments[i];
5775     }
5776     return NULL;
5777 }
5778
5779 chapter_item_c *demux_sys_t::BrowseCodecPrivate( unsigned int codec_id,
5780                                         bool (*match)(const chapter_codec_cmds_c &data, const void *p_cookie, size_t i_cookie_size ),
5781                                         const void *p_cookie,
5782                                         size_t i_cookie_size,
5783                                         virtual_segment_c * &p_segment_found )
5784 {
5785     chapter_item_c *p_result = NULL;
5786     for (size_t i=0; i<used_segments.size(); i++)
5787     {
5788         p_result = used_segments[i]->BrowseCodecPrivate( codec_id, match, p_cookie, i_cookie_size );
5789         if ( p_result != NULL )
5790         {
5791             p_segment_found = used_segments[i];
5792             break;
5793         }
5794     }
5795     return p_result;
5796 }
5797
5798 chapter_item_c *demux_sys_t::FindChapter( int64_t i_find_uid, virtual_segment_c * & p_segment_found )
5799 {
5800     chapter_item_c *p_result = NULL;
5801     for (size_t i=0; i<used_segments.size(); i++)
5802     {
5803         p_result = used_segments[i]->FindChapter( i_find_uid );
5804         if ( p_result != NULL )
5805         {
5806             p_segment_found = used_segments[i];
5807             break;
5808         }
5809     }
5810     return p_result;
5811 }
5812
5813 void virtual_segment_c::Sort()
5814 {
5815     // keep the current segment index
5816     matroska_segment_c *p_segment = linked_segments[i_current_segment];
5817
5818     std::sort( linked_segments.begin(), linked_segments.end(), matroska_segment_c::CompareSegmentUIDs );
5819
5820     for ( i_current_segment=0; i_current_segment<linked_segments.size(); i_current_segment++)
5821         if ( linked_segments[i_current_segment] == p_segment )
5822             break;
5823 }
5824
5825 size_t virtual_segment_c::AddSegment( matroska_segment_c *p_segment )
5826 {
5827     size_t i;
5828     // check if it's not already in here
5829     for ( i=0; i<linked_segments.size(); i++ )
5830     {
5831         if ( linked_segments[i]->p_segment_uid != NULL
5832             && p_segment->p_segment_uid != NULL
5833             && *p_segment->p_segment_uid == *linked_segments[i]->p_segment_uid )
5834             return 0;
5835     }
5836
5837     // find possible mates
5838     for ( i=0; i<linked_uids.size(); i++ )
5839     {
5840         if (   (p_segment->p_segment_uid != NULL && *p_segment->p_segment_uid == linked_uids[i])
5841             || (p_segment->p_prev_segment_uid != NULL && *p_segment->p_prev_segment_uid == linked_uids[i])
5842             || (p_segment->p_next_segment_uid !=NULL && *p_segment->p_next_segment_uid == linked_uids[i]) )
5843         {
5844             linked_segments.push_back( p_segment );
5845
5846             AppendUID( p_segment->p_prev_segment_uid );
5847             AppendUID( p_segment->p_next_segment_uid );
5848
5849             return 1;
5850         }
5851     }
5852     return 0;
5853 }
5854
5855 void virtual_segment_c::PreloadLinked( )
5856 {
5857     for ( size_t i=0; i<linked_segments.size(); i++ )
5858     {
5859         linked_segments[i]->Preload( );
5860     }
5861     i_current_edition = linked_segments[0]->i_default_edition;
5862 }
5863
5864 mtime_t virtual_segment_c::Duration() const
5865 {
5866     mtime_t i_duration;
5867     if ( linked_segments.size() == 0 )
5868         i_duration = 0;
5869     else {
5870         matroska_segment_c *p_last_segment = linked_segments[linked_segments.size()-1];
5871 //        p_last_segment->ParseCluster( );
5872
5873         i_duration = p_last_segment->i_start_time / 1000 + p_last_segment->i_duration;
5874     }
5875     return i_duration;
5876 }
5877
5878 void virtual_segment_c::AppendUID( const EbmlBinary * p_UID )
5879 {
5880     if ( p_UID == NULL )
5881         return;
5882     if ( p_UID->GetBuffer() == NULL )
5883         return;
5884
5885     for (size_t i=0; i<linked_uids.size(); i++)
5886     {
5887         if ( *p_UID == linked_uids[i] )
5888             return;
5889     }
5890     linked_uids.push_back( *(KaxSegmentUID*)(p_UID) );
5891 }
5892
5893 void matroska_segment_c::Seek( mtime_t i_date, mtime_t i_time_offset, int64_t i_global_position )
5894 {
5895     KaxBlock    *block;
5896 #if LIBMATROSKA_VERSION >= 0x000800
5897     KaxSimpleBlock *simpleblock;
5898 #endif
5899     int         i_track_skipping;
5900     int64_t     i_block_duration;
5901     int64_t     i_block_ref1;
5902     int64_t     i_block_ref2;
5903     size_t      i_track;
5904     int64_t     i_seek_position = i_start_pos;
5905     int64_t     i_seek_time = i_start_time;
5906
5907     if( i_global_position >= 0 )
5908     {
5909         /* Special case for seeking in files with no cues */
5910         EbmlElement *el = NULL;
5911         es.I_O().setFilePointer( i_start_pos, seek_beginning );
5912         delete ep;
5913         ep = new EbmlParser( &es, segment, &sys.demuxer );
5914         cluster = NULL;
5915
5916         while( ( el = ep->Get() ) != NULL )
5917         {
5918             if( MKV_IS_ID( el, KaxCluster ) )
5919             {
5920                 cluster = (KaxCluster *)el;
5921                 i_cluster_pos = cluster->GetElementPosition();
5922                 if( i_index == 0 ||
5923                         ( i_index > 0 && p_indexes[i_index - 1].i_position < (int64_t)cluster->GetElementPosition() ) )
5924                 {
5925                     IndexAppendCluster( cluster );
5926                 }
5927                 if( es.I_O().getFilePointer() >= i_global_position )
5928                 {
5929                     ParseCluster();
5930                     msg_Dbg( &sys.demuxer, "we found a cluster that is in the neighbourhood" );
5931                     es_out_Control( sys.demuxer.out, ES_OUT_RESET_PCR );
5932                     return;
5933                 }
5934             }
5935         }
5936         msg_Err( &sys.demuxer, "This file has no cues, and we were unable to seek to the requested position by parsing." );
5937         return;
5938     }
5939
5940     if ( i_index > 0 )
5941     {
5942         int i_idx = 0;
5943
5944         for( ; i_idx < i_index; i_idx++ )
5945         {
5946             if( p_indexes[i_idx].i_time + i_time_offset > i_date )
5947             {
5948                 break;
5949             }
5950         }
5951
5952         if( i_idx > 0 )
5953         {
5954             i_idx--;
5955         }
5956
5957         i_seek_position = p_indexes[i_idx].i_position;
5958         i_seek_time = p_indexes[i_idx].i_time;
5959     }
5960
5961     msg_Dbg( &sys.demuxer, "seek got %"PRId64" (%d%%)",
5962                 i_seek_time, (int)( 100 * i_seek_position / stream_Size( sys.demuxer.s ) ) );
5963
5964     es.I_O().setFilePointer( i_seek_position, seek_beginning );
5965
5966     delete ep;
5967     ep = new EbmlParser( &es, segment, &sys.demuxer );
5968     cluster = NULL;
5969
5970     sys.i_start_pts = i_date;
5971
5972     es_out_Control( sys.demuxer.out, ES_OUT_RESET_PCR );
5973
5974     /* now parse until key frame */
5975     i_track_skipping = 0;
5976     for( i_track = 0; i_track < tracks.size(); i_track++ )
5977     {
5978         if( tracks[i_track]->fmt.i_cat == VIDEO_ES )
5979         {
5980             tracks[i_track]->b_search_keyframe = true;
5981             i_track_skipping++;
5982         }
5983         es_out_Control( sys.demuxer.out, ES_OUT_SET_NEXT_DISPLAY_TIME, tracks[i_track]->p_es, i_date );
5984     }
5985
5986     while( i_track_skipping > 0 )
5987     {
5988 #if LIBMATROSKA_VERSION >= 0x000800
5989         if( BlockGet( block, simpleblock, &i_block_ref1, &i_block_ref2, &i_block_duration ) )
5990 #else
5991         if( BlockGet( block, &i_block_ref1, &i_block_ref2, &i_block_duration ) )
5992 #endif
5993         {
5994             msg_Warn( &sys.demuxer, "cannot get block EOF?" );
5995
5996             return;
5997         }
5998         ep->Down();
5999
6000         for( i_track = 0; i_track < tracks.size(); i_track++ )
6001         {
6002 #if LIBMATROSKA_VERSION >= 0x000800
6003             if( (simpleblock && tracks[i_track]->i_number == simpleblock->TrackNum()) ||
6004                 (block && tracks[i_track]->i_number == block->TrackNum()) )
6005 #else
6006             if( tracks[i_track]->i_number == block->TrackNum() )
6007 #endif
6008             {
6009                 break;
6010             }
6011         }
6012
6013 #if LIBMATROSKA_VERSION >= 0x000800
6014         if( simpleblock )
6015             sys.i_pts = (sys.i_chapter_time + simpleblock->GlobalTimecode()) / (mtime_t) 1000;
6016         else
6017 #endif
6018             sys.i_pts = (sys.i_chapter_time + block->GlobalTimecode()) / (mtime_t) 1000;
6019
6020         if( i_track < tracks.size() )
6021         {
6022             if( sys.i_pts >= sys.i_start_pts )
6023             {
6024                 cluster = static_cast<KaxCluster*>(ep->UnGet( i_block_pos, i_cluster_pos ));
6025                 i_track_skipping = 0;
6026             }
6027             else if( tracks[i_track]->fmt.i_cat == VIDEO_ES )
6028             {
6029                 if( i_block_ref1 == 0 && tracks[i_track]->b_search_keyframe )
6030                 {
6031                     tracks[i_track]->b_search_keyframe = false;
6032                     i_track_skipping--;
6033                 }
6034                 if( !tracks[i_track]->b_search_keyframe )
6035                 {
6036                     
6037             //es_out_Control( sys.demuxer.out, ES_OUT_SET_PCR, sys.i_pts );
6038 #if LIBMATROSKA_VERSION >= 0x000800
6039                     BlockDecode( &sys.demuxer, block, simpleblock, sys.i_pts, 0, i_block_ref1 >= 0 || i_block_ref2 > 0 );
6040 #else
6041                     BlockDecode( &sys.demuxer, block, sys.i_pts, 0, i_block_ref1 >= 0 || i_block_ref2 > 0 );
6042 #endif
6043                 }
6044             }
6045         }
6046
6047         delete block;
6048     }
6049
6050     /* FIXME current ES_OUT_SET_NEXT_DISPLAY_TIME does not work that well if
6051      * the delay is too high. */
6052     if( sys.i_pts + 500*1000 < sys.i_start_pts )
6053     {
6054         sys.i_start_pts = sys.i_pts;
6055
6056         for( i_track = 0; i_track < tracks.size(); i_track++ )
6057             es_out_Control( sys.demuxer.out, ES_OUT_SET_NEXT_DISPLAY_TIME, tracks[i_track]->p_es, sys.i_start_pts );
6058     }
6059 }
6060
6061 void virtual_segment_c::Seek( demux_t & demuxer, mtime_t i_date, mtime_t i_time_offset, chapter_item_c *psz_chapter, int64_t i_global_position )
6062 {
6063     demux_sys_t *p_sys = demuxer.p_sys;
6064     size_t i;
6065
6066     // find the actual time for an ordered edition
6067     if ( psz_chapter == NULL )
6068     {
6069         if ( Edition() && Edition()->b_ordered )
6070         {
6071             /* 1st, we need to know in which chapter we are */
6072             psz_chapter = (*p_editions)[i_current_edition]->FindTimecode( i_date, psz_current_chapter );
6073         }
6074     }
6075
6076     if ( psz_chapter != NULL )
6077     {
6078         psz_current_chapter = psz_chapter;
6079         p_sys->i_chapter_time = i_time_offset = psz_chapter->i_user_start_time - psz_chapter->i_start_time;
6080         if ( psz_chapter->i_seekpoint_num > 0 )
6081         {
6082             demuxer.info.i_update |= INPUT_UPDATE_TITLE | INPUT_UPDATE_SEEKPOINT;
6083             demuxer.info.i_title = p_sys->i_current_title = i_sys_title;
6084             demuxer.info.i_seekpoint = psz_chapter->i_seekpoint_num - 1;
6085         }
6086     }
6087
6088     // find the best matching segment
6089     for ( i=0; i<linked_segments.size(); i++ )
6090     {
6091         if ( i_date < linked_segments[i]->i_start_time )
6092             break;
6093     }
6094
6095     if ( i > 0 )
6096         i--;
6097
6098     if ( i_current_segment != i  )
6099     {
6100         linked_segments[i_current_segment]->UnSelect();
6101         linked_segments[i]->Select( i_date );
6102         i_current_segment = i;
6103     }
6104
6105     linked_segments[i]->Seek( i_date, i_time_offset, i_global_position );
6106 }
6107
6108 void chapter_codec_cmds_c::AddCommand( const KaxChapterProcessCommand & command )
6109 {
6110     size_t i;
6111
6112     uint32 codec_time = uint32(-1);
6113     for( i = 0; i < command.ListSize(); i++ )
6114     {
6115         const EbmlElement *k = command[i];
6116
6117         if( MKV_IS_ID( k, KaxChapterProcessTime ) )
6118         {
6119             codec_time = uint32( *static_cast<const KaxChapterProcessTime*>( k ) );
6120             break;
6121         }
6122     }
6123
6124     for( i = 0; i < command.ListSize(); i++ )
6125     {
6126         const EbmlElement *k = command[i];
6127
6128         if( MKV_IS_ID( k, KaxChapterProcessData ) )
6129         {
6130             KaxChapterProcessData *p_data =  new KaxChapterProcessData( *static_cast<const KaxChapterProcessData*>( k ) );
6131             switch ( codec_time )
6132             {
6133             case 0:
6134                 during_cmds.push_back( p_data );
6135                 break;
6136             case 1:
6137                 enter_cmds.push_back( p_data );
6138                 break;
6139             case 2:
6140                 leave_cmds.push_back( p_data );
6141                 break;
6142             default:
6143                 delete p_data;
6144             }
6145         }
6146     }
6147 }
6148
6149 bool chapter_item_c::Enter( bool b_do_subs )
6150 {
6151     bool f_result = false;
6152     std::vector<chapter_codec_cmds_c*>::iterator index = codecs.begin();
6153     while ( index != codecs.end() )
6154     {
6155         f_result |= (*index)->Enter();
6156         index++;
6157     }
6158
6159     if ( b_do_subs )
6160     {
6161         // sub chapters
6162         std::vector<chapter_item_c*>::iterator index_ = sub_chapters.begin();
6163         while ( index_ != sub_chapters.end() )
6164         {
6165             f_result |= (*index_)->Enter( true );
6166             index_++;
6167         }
6168     }
6169     return f_result;
6170 }
6171
6172 bool chapter_item_c::Leave( bool b_do_subs )
6173 {
6174     bool f_result = false;
6175     b_is_leaving = true;
6176     std::vector<chapter_codec_cmds_c*>::iterator index = codecs.begin();
6177     while ( index != codecs.end() )
6178     {
6179         f_result |= (*index)->Leave();
6180         index++;
6181     }
6182
6183     if ( b_do_subs )
6184     {
6185         // sub chapters
6186         std::vector<chapter_item_c*>::iterator index_ = sub_chapters.begin();
6187         while ( index_ != sub_chapters.end() )
6188         {
6189             f_result |= (*index_)->Leave( true );
6190             index_++;
6191         }
6192     }
6193     b_is_leaving = false;
6194     return f_result;
6195 }
6196
6197 bool chapter_item_c::EnterAndLeave( chapter_item_c *p_item, bool b_final_enter )
6198 {
6199     chapter_item_c *p_common_parent = p_item;
6200
6201     // leave, up to a common parent
6202     while ( p_common_parent != NULL && !p_common_parent->ParentOf( *this ) )
6203     {
6204         if ( !p_common_parent->b_is_leaving && p_common_parent->Leave( false ) )
6205             return true;
6206         p_common_parent = p_common_parent->psz_parent;
6207     }
6208
6209     // enter from the parent to <this>
6210     if ( p_common_parent != NULL )
6211     {
6212         do
6213         {
6214             if ( p_common_parent == this )
6215                 return Enter( true );
6216
6217             for ( size_t i = 0; i<p_common_parent->sub_chapters.size(); i++ )
6218             {
6219                 if ( p_common_parent->sub_chapters[i]->ParentOf( *this ) )
6220                 {
6221                     p_common_parent = p_common_parent->sub_chapters[i];
6222                     if ( p_common_parent != this )
6223                         if ( p_common_parent->Enter( false ) )
6224                             return true;
6225
6226                     break;
6227                 }
6228             }
6229         } while ( 1 );
6230     }
6231
6232     if ( b_final_enter )
6233         return Enter( true );
6234     else
6235         return false;
6236 }
6237
6238 bool dvd_chapter_codec_c::Enter()
6239 {
6240     bool f_result = false;
6241     std::vector<KaxChapterProcessData*>::iterator index = enter_cmds.begin();
6242     while ( index != enter_cmds.end() )
6243     {
6244         if ( (*index)->GetSize() )
6245         {
6246             binary *p_data = (*index)->GetBuffer();
6247             size_t i_size = *p_data++;
6248             // avoid reading too much from the buffer
6249             i_size = __MIN( i_size, ((*index)->GetSize() - 1) >> 3 );
6250             for ( ; i_size > 0; i_size--, p_data += 8 )
6251             {
6252                 msg_Dbg( &sys.demuxer, "Matroska DVD enter command" );
6253                 f_result |= sys.dvd_interpretor.Interpret( p_data );
6254             }
6255         }
6256         index++;
6257     }
6258     return f_result;
6259 }
6260
6261 bool dvd_chapter_codec_c::Leave()
6262 {
6263     bool f_result = false;
6264     std::vector<KaxChapterProcessData*>::iterator index = leave_cmds.begin();
6265     while ( index != leave_cmds.end() )
6266     {
6267         if ( (*index)->GetSize() )
6268         {
6269             binary *p_data = (*index)->GetBuffer();
6270             size_t i_size = *p_data++;
6271             // avoid reading too much from the buffer
6272             i_size = __MIN( i_size, ((*index)->GetSize() - 1) >> 3 );
6273             for ( ; i_size > 0; i_size--, p_data += 8 )
6274             {
6275                 msg_Dbg( &sys.demuxer, "Matroska DVD leave command" );
6276                 f_result |= sys.dvd_interpretor.Interpret( p_data );
6277             }
6278         }
6279         index++;
6280     }
6281     return f_result;
6282 }
6283
6284 // see http://www.dvd-replica.com/DVD/vmcmdset.php for a description of DVD commands
6285 bool dvd_command_interpretor_c::Interpret( const binary * p_command, size_t i_size )
6286 {
6287     if ( i_size != 8 )
6288         return false;
6289
6290     virtual_segment_c *p_segment = NULL;
6291     chapter_item_c *p_chapter = NULL;
6292     bool f_result = false;
6293     uint16 i_command = ( p_command[0] << 8 ) + p_command[1];
6294
6295     // handle register tests if there are some
6296     if ( (i_command & 0xF0) != 0 )
6297     {
6298         bool b_test_positive = true;//(i_command & CMD_DVD_IF_NOT) == 0;
6299         bool b_test_value    = (i_command & CMD_DVD_TEST_VALUE) != 0;
6300         uint8 i_test = i_command & 0x70;
6301         uint16 i_value;
6302
6303         // see http://dvd.sourceforge.net/dvdinfo/vmi.html
6304         uint8  i_cr1;
6305         uint16 i_cr2;
6306         switch ( i_command >> 12 )
6307         {
6308         default:
6309             i_cr1 = p_command[3];
6310             i_cr2 = (p_command[4] << 8) + p_command[5];
6311             break;
6312         case 3:
6313         case 4:
6314         case 5:
6315             i_cr1 = p_command[6];
6316             i_cr2 = p_command[7];
6317             b_test_value = false;
6318             break;
6319         case 6:
6320         case 7:
6321             if ( ((p_command[1] >> 4) & 0x7) == 0)
6322             {
6323                 i_cr1 = p_command[2];
6324                 i_cr2 = (p_command[6] << 8) + p_command[7];
6325             }
6326             else
6327             {
6328                 i_cr1 = p_command[2];
6329                 i_cr2 = (p_command[6] << 8) + p_command[7];
6330             }
6331             break;
6332         }
6333
6334         if ( b_test_value )
6335             i_value = i_cr2;
6336         else
6337             i_value = GetPRM( i_cr2 );
6338
6339         switch ( i_test )
6340         {
6341         case CMD_DVD_IF_GPREG_EQUAL:
6342             // if equals
6343             msg_Dbg( &sys.demuxer, "IF %s EQUALS %s", GetRegTypeName( false, i_cr1 ).c_str(), GetRegTypeName( b_test_value, i_value ).c_str() );
6344             if (!( GetPRM( i_cr1 ) == i_value ))
6345             {
6346                 b_test_positive = false;
6347             }
6348             break;
6349         case CMD_DVD_IF_GPREG_NOT_EQUAL:
6350             // if not equals
6351             msg_Dbg( &sys.demuxer, "IF %s NOT EQUALS %s", GetRegTypeName( false, i_cr1 ).c_str(), GetRegTypeName( b_test_value, i_value ).c_str() );
6352             if (!( GetPRM( i_cr1 ) != i_value ))
6353             {
6354                 b_test_positive = false;
6355             }
6356             break;
6357         case CMD_DVD_IF_GPREG_INF:
6358             // if inferior
6359             msg_Dbg( &sys.demuxer, "IF %s < %s", GetRegTypeName( false, p_command[3] ).c_str(), GetRegTypeName( b_test_value, i_value ).c_str() );
6360             if (!( GetPRM( i_cr1 ) < i_value ))
6361             {
6362                 b_test_positive = false;
6363             }
6364             break;
6365         case CMD_DVD_IF_GPREG_INF_EQUAL:
6366             // if inferior or equal
6367             msg_Dbg( &sys.demuxer, "IF %s < %s", GetRegTypeName( false, p_command[3] ).c_str(), GetRegTypeName( b_test_value, i_value ).c_str() );
6368             if (!( GetPRM( i_cr1 ) <= i_value ))
6369             {
6370                 b_test_positive = false;
6371             }
6372             break;
6373         case CMD_DVD_IF_GPREG_AND:
6374             // if logical and
6375             msg_Dbg( &sys.demuxer, "IF %s & %s", GetRegTypeName( false, p_command[3] ).c_str(), GetRegTypeName( b_test_value, i_value ).c_str() );
6376             if (!( GetPRM( i_cr1 ) & i_value ))
6377             {
6378                 b_test_positive = false;
6379             }
6380             break;
6381         case CMD_DVD_IF_GPREG_SUP:
6382             // if superior
6383             msg_Dbg( &sys.demuxer, "IF %s >= %s", GetRegTypeName( false, p_command[3] ).c_str(), GetRegTypeName( b_test_value, i_value ).c_str() );
6384             if (!( GetPRM( i_cr1 ) > i_value ))
6385             {
6386                 b_test_positive = false;
6387             }
6388             break;
6389         case CMD_DVD_IF_GPREG_SUP_EQUAL:
6390             // if superior or equal
6391             msg_Dbg( &sys.demuxer, "IF %s >= %s", GetRegTypeName( false, p_command[3] ).c_str(), GetRegTypeName( b_test_value, i_value ).c_str() );
6392             if (!( GetPRM( i_cr1 ) >= i_value ))
6393             {
6394                 b_test_positive = false;
6395             }
6396             break;
6397         }
6398
6399         if ( !b_test_positive )
6400             return false;
6401     }
6402  
6403     // strip the test command
6404     i_command &= 0xFF0F;
6405  
6406     switch ( i_command )
6407     {
6408     case CMD_DVD_NOP:
6409     case CMD_DVD_NOP2:
6410         {
6411             msg_Dbg( &sys.demuxer, "NOP" );
6412             break;
6413         }
6414     case CMD_DVD_BREAK:
6415         {
6416             msg_Dbg( &sys.demuxer, "Break" );
6417             // TODO
6418             break;
6419         }
6420     case CMD_DVD_JUMP_TT:
6421         {
6422             uint8 i_title = p_command[5];
6423             msg_Dbg( &sys.demuxer, "JumpTT %d", i_title );
6424
6425             // find in the ChapProcessPrivate matching this Title level
6426             p_chapter = sys.BrowseCodecPrivate( 1, MatchTitleNumber, &i_title, sizeof(i_title), p_segment );
6427             if ( p_segment != NULL )
6428             {
6429                 sys.JumpTo( *p_segment, p_chapter );
6430                 f_result = true;
6431             }
6432
6433             break;
6434         }
6435     case CMD_DVD_CALLSS_VTSM1:
6436         {
6437             msg_Dbg( &sys.demuxer, "CallSS" );
6438             binary p_type;
6439             switch( (p_command[6] & 0xC0) >> 6 ) {
6440                 case 0:
6441                     p_type = p_command[5] & 0x0F;
6442                     switch ( p_type )
6443                     {
6444                     case 0x00:
6445                         msg_Dbg( &sys.demuxer, "CallSS PGC (rsm_cell %x)", p_command[4]);
6446                         break;
6447                     case 0x02:
6448                         msg_Dbg( &sys.demuxer, "CallSS Title Entry (rsm_cell %x)", p_command[4]);
6449                         break;
6450                     case 0x03:
6451                         msg_Dbg( &sys.demuxer, "CallSS Root Menu (rsm_cell %x)", p_command[4]);
6452                         break;
6453                     case 0x04:
6454                         msg_Dbg( &sys.demuxer, "CallSS Subpicture Menu (rsm_cell %x)", p_command[4]);
6455                         break;
6456                     case 0x05:
6457                         msg_Dbg( &sys.demuxer, "CallSS Audio Menu (rsm_cell %x)", p_command[4]);
6458                         break;
6459                     case 0x06:
6460                         msg_Dbg( &sys.demuxer, "CallSS Angle Menu (rsm_cell %x)", p_command[4]);
6461                         break;
6462                     case 0x07:
6463                         msg_Dbg( &sys.demuxer, "CallSS Chapter Menu (rsm_cell %x)", p_command[4]);
6464                         break;
6465                     default:
6466                         msg_Dbg( &sys.demuxer, "CallSS <unknown> (rsm_cell %x)", p_command[4]);
6467                         break;
6468                     }
6469                     p_chapter = sys.BrowseCodecPrivate( 1, MatchPgcType, &p_type, 1, p_segment );
6470                     if ( p_segment != NULL )
6471                     {
6472                         sys.JumpTo( *p_segment, p_chapter );
6473                         f_result = true;
6474                     }
6475                 break;
6476                 case 1:
6477                     msg_Dbg( &sys.demuxer, "CallSS VMGM (menu %d, rsm_cell %x)", p_command[5] & 0x0F, p_command[4]);
6478                 break;
6479                 case 2:
6480                     msg_Dbg( &sys.demuxer, "CallSS VTSM (menu %d, rsm_cell %x)", p_command[5] & 0x0F, p_command[4]);
6481                 break;
6482                 case 3:
6483                     msg_Dbg( &sys.demuxer, "CallSS VMGM (pgc %d, rsm_cell %x)", (p_command[2] << 8) + p_command[3], p_command[4]);
6484                 break;
6485             }
6486             break;
6487         }
6488     case CMD_DVD_JUMP_SS:
6489         {
6490             msg_Dbg( &sys.demuxer, "JumpSS");
6491             binary p_type;
6492             switch( (p_command[5] & 0xC0) >> 6 ) {
6493                 case 0:
6494                     msg_Dbg( &sys.demuxer, "JumpSS FP");
6495                 break;
6496                 case 1:
6497                     p_type = p_command[5] & 0x0F;
6498                     switch ( p_type )
6499                     {
6500                     case 0x02:
6501                         msg_Dbg( &sys.demuxer, "JumpSS VMGM Title Entry");
6502                         break;
6503                     case 0x03:
6504                         msg_Dbg( &sys.demuxer, "JumpSS VMGM Root Menu");
6505                         break;
6506                     case 0x04:
6507                         msg_Dbg( &sys.demuxer, "JumpSS VMGM Subpicture Menu");
6508                         break;
6509                     case 0x05:
6510                         msg_Dbg( &sys.demuxer, "JumpSS VMGM Audio Menu");
6511                         break;
6512                     case 0x06:
6513                         msg_Dbg( &sys.demuxer, "JumpSS VMGM Angle Menu");
6514                         break;
6515                     case 0x07:
6516                         msg_Dbg( &sys.demuxer, "JumpSS VMGM Chapter Menu");
6517                         break;
6518                     default:
6519                         msg_Dbg( &sys.demuxer, "JumpSS <unknown>");
6520                         break;
6521                     }
6522                     // find the VMG
6523                     p_chapter = sys.BrowseCodecPrivate( 1, MatchIsVMG, NULL, 0, p_segment );
6524                     if ( p_segment != NULL )
6525                     {
6526                         p_chapter = p_segment->BrowseCodecPrivate( 1, MatchPgcType, &p_type, 1 );
6527                         if ( p_chapter != NULL )
6528                         {
6529                             sys.JumpTo( *p_segment, p_chapter );
6530                             f_result = true;
6531                         }
6532                     }
6533                 break;
6534                 case 2:
6535                     p_type = p_command[5] & 0x0F;
6536                     switch ( p_type )
6537                     {
6538                     case 0x02:
6539                         msg_Dbg( &sys.demuxer, "JumpSS VTSM (vts %d, ttn %d) Title Entry", p_command[4], p_command[3]);
6540                         break;
6541                     case 0x03:
6542                         msg_Dbg( &sys.demuxer, "JumpSS VTSM (vts %d, ttn %d) Root Menu", p_command[4], p_command[3]);
6543                         break;
6544                     case 0x04:
6545                         msg_Dbg( &sys.demuxer, "JumpSS VTSM (vts %d, ttn %d) Subpicture Menu", p_command[4], p_command[3]);
6546                         break;
6547                     case 0x05:
6548                         msg_Dbg( &sys.demuxer, "JumpSS VTSM (vts %d, ttn %d) Audio Menu", p_command[4], p_command[3]);
6549                         break;
6550                     case 0x06:
6551                         msg_Dbg( &sys.demuxer, "JumpSS VTSM (vts %d, ttn %d) Angle Menu", p_command[4], p_command[3]);
6552                         break;
6553                     case 0x07:
6554                         msg_Dbg( &sys.demuxer, "JumpSS VTSM (vts %d, ttn %d) Chapter Menu", p_command[4], p_command[3]);
6555                         break;
6556                     default:
6557                         msg_Dbg( &sys.demuxer, "JumpSS VTSM (vts %d, ttn %d) <unknown>", p_command[4], p_command[3]);
6558                         break;
6559                     }
6560
6561                     p_chapter = sys.BrowseCodecPrivate( 1, MatchVTSMNumber, &p_command[4], 1, p_segment );
6562
6563                     if ( p_segment != NULL && p_chapter != NULL )
6564                     {
6565                         // find the title in the VTS
6566                         p_chapter = p_chapter->BrowseCodecPrivate( 1, MatchTitleNumber, &p_command[3], 1 );
6567                         if ( p_chapter != NULL )
6568                         {
6569                             // find the specified menu in the VTSM
6570                             p_chapter = p_segment->BrowseCodecPrivate( 1, MatchPgcType, &p_type, 1 );
6571                             if ( p_chapter != NULL )
6572                             {
6573                                 sys.JumpTo( *p_segment, p_chapter );
6574                                 f_result = true;
6575                             }
6576                         }
6577                         else
6578                             msg_Dbg( &sys.demuxer, "Title (%d) does not exist in this VTS", p_command[3] );
6579                     }
6580                     else
6581                         msg_Dbg( &sys.demuxer, "DVD Domain VTS (%d) not found", p_command[4] );
6582                 break;
6583                 case 3:
6584                     msg_Dbg( &sys.demuxer, "JumpSS VMGM (pgc %d)", (p_command[2] << 8) + p_command[3]);
6585                 break;
6586             }
6587             break;
6588         }
6589     case CMD_DVD_JUMPVTS_PTT:
6590         {
6591             uint8 i_title = p_command[5];
6592             uint8 i_ptt = p_command[3];
6593
6594             msg_Dbg( &sys.demuxer, "JumpVTS Title (%d) PTT (%d)", i_title, i_ptt);
6595
6596             // find the current VTS content segment
6597             p_chapter = sys.p_current_segment->BrowseCodecPrivate( 1, MatchIsDomain, NULL, 0 );
6598             if ( p_chapter != NULL )
6599             {
6600                 int16 i_curr_title = p_chapter->GetTitleNumber( );
6601                 if ( i_curr_title > 0 )
6602                 {
6603                     p_chapter = sys.BrowseCodecPrivate( 1, MatchVTSNumber, &i_curr_title, sizeof(i_curr_title), p_segment );
6604
6605                     if ( p_segment != NULL && p_chapter != NULL )
6606                     {
6607                         // find the title in the VTS
6608                         p_chapter = p_chapter->BrowseCodecPrivate( 1, MatchTitleNumber, &i_title, sizeof(i_title) );
6609                         if ( p_chapter != NULL )
6610                         {
6611                             // find the chapter in the title
6612                             p_chapter = p_chapter->BrowseCodecPrivate( 1, MatchChapterNumber, &i_ptt, sizeof(i_ptt) );
6613                             if ( p_chapter != NULL )
6614                             {
6615                                 sys.JumpTo( *p_segment, p_chapter );
6616                                 f_result = true;
6617                             }
6618                         }
6619                     else
6620                         msg_Dbg( &sys.demuxer, "Title (%d) does not exist in this VTS", i_title );
6621                     }
6622                     else
6623                         msg_Dbg( &sys.demuxer, "DVD Domain VTS (%d) not found", i_curr_title );
6624                 }
6625                 else
6626                     msg_Dbg( &sys.demuxer, "JumpVTS_PTT command found but not in a VTS(M)");
6627             }
6628             else
6629                 msg_Dbg( &sys.demuxer, "JumpVTS_PTT command but the DVD domain wasn't found");
6630             break;
6631         }
6632     case CMD_DVD_SET_GPRMMD:
6633         {
6634             msg_Dbg( &sys.demuxer, "Set GPRMMD [%d]=%d", (p_command[4] << 8) + p_command[5], (p_command[2] << 8) + p_command[3]);
6635  
6636             if ( !SetGPRM( (p_command[4] << 8) + p_command[5], (p_command[2] << 8) + p_command[3] ) )
6637                 msg_Dbg( &sys.demuxer, "Set GPRMMD failed" );
6638             break;
6639         }
6640     case CMD_DVD_LINKPGCN:
6641         {
6642             uint16 i_pgcn = (p_command[6] << 8) + p_command[7];
6643  
6644             msg_Dbg( &sys.demuxer, "Link PGCN(%d)", i_pgcn );
6645             p_chapter = sys.p_current_segment->BrowseCodecPrivate( 1, MatchPgcNumber, &i_pgcn, 2 );
6646             if ( p_chapter != NULL )
6647             {
6648                 if ( !p_chapter->Enter( true ) )
6649                     // jump to the location in the found segment
6650                     sys.p_current_segment->Seek( sys.demuxer, p_chapter->i_user_start_time, -1, p_chapter, -1 );
6651
6652                 f_result = true;
6653             }
6654             break;
6655         }
6656     case CMD_DVD_LINKCN:
6657         {
6658             uint8 i_cn = p_command[7];
6659  
6660             p_chapter = sys.p_current_segment->CurrentChapter();
6661
6662             msg_Dbg( &sys.demuxer, "LinkCN (cell %d)", i_cn );
6663             p_chapter = p_chapter->BrowseCodecPrivate( 1, MatchCellNumber, &i_cn, 1 );
6664             if ( p_chapter != NULL )
6665             {
6666                 if ( !p_chapter->Enter( true ) )
6667                     // jump to the location in the found segment
6668                     sys.p_current_segment->Seek( sys.demuxer, p_chapter->i_user_start_time, -1, p_chapter, -1 );
6669
6670                 f_result = true;
6671             }
6672             break;
6673         }
6674     case CMD_DVD_GOTO_LINE:
6675         {
6676             msg_Dbg( &sys.demuxer, "GotoLine (%d)", (p_command[6] << 8) + p_command[7] );
6677             // TODO
6678             break;
6679         }
6680     case CMD_DVD_SET_HL_BTNN1:
6681         {
6682             msg_Dbg( &sys.demuxer, "SetHL_BTN (%d)", p_command[4] );
6683             SetSPRM( 0x88, p_command[4] );
6684             break;
6685         }
6686     default:
6687         {
6688             msg_Dbg( &sys.demuxer, "unsupported command : %02X %02X %02X %02X %02X %02X %02X %02X"
6689                      ,p_command[0]
6690                      ,p_command[1]
6691                      ,p_command[2]
6692                      ,p_command[3]
6693                      ,p_command[4]
6694                      ,p_command[5]
6695                      ,p_command[6]
6696                      ,p_command[7]);
6697             break;
6698         }
6699     }
6700
6701     return f_result;
6702 }
6703
6704 bool dvd_command_interpretor_c::MatchIsDomain( const chapter_codec_cmds_c &data, const void *p_cookie, size_t i_cookie_size )
6705 {
6706     return ( data.p_private_data != NULL && data.p_private_data->GetBuffer()[0] == MATROSKA_DVD_LEVEL_SS );
6707 }
6708
6709 bool dvd_command_interpretor_c::MatchIsVMG( const chapter_codec_cmds_c &data, const void *p_cookie, size_t i_cookie_size )
6710 {
6711     if ( data.p_private_data == NULL || data.p_private_data->GetSize() < 2 )
6712         return false;
6713
6714     return ( data.p_private_data->GetBuffer()[0] == MATROSKA_DVD_LEVEL_SS && data.p_private_data->GetBuffer()[1] == 0xC0);
6715 }
6716
6717 bool dvd_command_interpretor_c::MatchVTSNumber( const chapter_codec_cmds_c &data, const void *p_cookie, size_t i_cookie_size )
6718 {
6719     if ( i_cookie_size != 2 || data.p_private_data == NULL || data.p_private_data->GetSize() < 4 )
6720         return false;
6721  
6722     if ( data.p_private_data->GetBuffer()[0] != MATROSKA_DVD_LEVEL_SS || data.p_private_data->GetBuffer()[1] != 0x80 )
6723         return false;
6724
6725     uint16 i_gtitle = (data.p_private_data->GetBuffer()[2] << 8 ) + data.p_private_data->GetBuffer()[3];
6726     uint16 i_title = *(uint16*)p_cookie;
6727
6728     return (i_gtitle == i_title);
6729 }
6730
6731 bool dvd_command_interpretor_c::MatchVTSMNumber( const chapter_codec_cmds_c &data, const void *p_cookie, size_t i_cookie_size )
6732 {
6733     if ( i_cookie_size != 1 || data.p_private_data == NULL || data.p_private_data->GetSize() < 4 )
6734         return false;
6735  
6736     if ( data.p_private_data->GetBuffer()[0] != MATROSKA_DVD_LEVEL_SS || data.p_private_data->GetBuffer()[1] != 0x40 )
6737         return false;
6738
6739     uint8 i_gtitle = data.p_private_data->GetBuffer()[3];
6740     uint8 i_title = *(uint8*)p_cookie;
6741
6742     return (i_gtitle == i_title);
6743 }
6744
6745 bool dvd_command_interpretor_c::MatchTitleNumber( const chapter_codec_cmds_c &data, const void *p_cookie, size_t i_cookie_size )
6746 {
6747     if ( i_cookie_size != 1 || data.p_private_data == NULL || data.p_private_data->GetSize() < 4 )
6748         return false;
6749  
6750     if ( data.p_private_data->GetBuffer()[0] != MATROSKA_DVD_LEVEL_TT )
6751         return false;
6752
6753     uint16 i_gtitle = (data.p_private_data->GetBuffer()[1] << 8 ) + data.p_private_data->GetBuffer()[2];
6754     uint8 i_title = *(uint8*)p_cookie;
6755
6756     return (i_gtitle == i_title);
6757 }
6758
6759 bool dvd_command_interpretor_c::MatchPgcType( const chapter_codec_cmds_c &data, const void *p_cookie, size_t i_cookie_size )
6760 {
6761     if ( i_cookie_size != 1 || data.p_private_data == NULL || data.p_private_data->GetSize() < 8 )
6762         return false;
6763  
6764     if ( data.p_private_data->GetBuffer()[0] != MATROSKA_DVD_LEVEL_PGC )
6765         return false;
6766
6767     uint8 i_pgc_type = data.p_private_data->GetBuffer()[3] & 0x0F;
6768     uint8 i_pgc = *(uint8*)p_cookie;
6769
6770     return (i_pgc_type == i_pgc);
6771 }
6772
6773 bool dvd_command_interpretor_c::MatchPgcNumber( const chapter_codec_cmds_c &data, const void *p_cookie, size_t i_cookie_size )
6774 {
6775     if ( i_cookie_size != 2 || data.p_private_data == NULL || data.p_private_data->GetSize() < 8 )
6776         return false;
6777  
6778     if ( data.p_private_data->GetBuffer()[0] != MATROSKA_DVD_LEVEL_PGC )
6779         return false;
6780
6781     uint16 *i_pgc_n = (uint16 *)p_cookie;
6782     uint16 i_pgc_num = (data.p_private_data->GetBuffer()[1] << 8) + data.p_private_data->GetBuffer()[2];
6783
6784     return (i_pgc_num == *i_pgc_n);
6785 }
6786
6787 bool dvd_command_interpretor_c::MatchChapterNumber( const chapter_codec_cmds_c &data, const void *p_cookie, size_t i_cookie_size )
6788 {
6789     if ( i_cookie_size != 1 || data.p_private_data == NULL || data.p_private_data->GetSize() < 2 )
6790         return false;
6791  
6792     if ( data.p_private_data->GetBuffer()[0] != MATROSKA_DVD_LEVEL_PTT )
6793         return false;
6794
6795     uint8 i_chapter = data.p_private_data->GetBuffer()[1];
6796     uint8 i_ptt = *(uint8*)p_cookie;
6797
6798     return (i_chapter == i_ptt);
6799 }
6800
6801 bool dvd_command_interpretor_c::MatchCellNumber( const chapter_codec_cmds_c &data, const void *p_cookie, size_t i_cookie_size )
6802 {
6803     if ( i_cookie_size != 1 || data.p_private_data == NULL || data.p_private_data->GetSize() < 5 )
6804         return false;
6805  
6806     if ( data.p_private_data->GetBuffer()[0] != MATROSKA_DVD_LEVEL_CN )
6807         return false;
6808
6809     uint8 *i_cell_n = (uint8 *)p_cookie;
6810     uint8 i_cell_num = data.p_private_data->GetBuffer()[3];
6811
6812     return (i_cell_num == *i_cell_n);
6813 }
6814
6815 bool matroska_script_codec_c::Enter()
6816 {
6817     bool f_result = false;
6818     std::vector<KaxChapterProcessData*>::iterator index = enter_cmds.begin();
6819     while ( index != enter_cmds.end() )
6820     {
6821         if ( (*index)->GetSize() )
6822         {
6823             msg_Dbg( &sys.demuxer, "Matroska Script enter command" );
6824             f_result |= interpretor.Interpret( (*index)->GetBuffer(), (*index)->GetSize() );
6825         }
6826         index++;
6827     }
6828     return f_result;
6829 }
6830
6831 bool matroska_script_codec_c::Leave()
6832 {
6833     bool f_result = false;
6834     std::vector<KaxChapterProcessData*>::iterator index = leave_cmds.begin();
6835     while ( index != leave_cmds.end() )
6836     {
6837         if ( (*index)->GetSize() )
6838         {
6839             msg_Dbg( &sys.demuxer, "Matroska Script leave command" );
6840             f_result |= interpretor.Interpret( (*index)->GetBuffer(), (*index)->GetSize() );
6841         }
6842         index++;
6843     }
6844     return f_result;
6845 }
6846
6847 // see http://www.matroska.org/technical/specs/chapters/index.html#mscript
6848 //  for a description of existing commands
6849 bool matroska_script_interpretor_c::Interpret( const binary * p_command, size_t i_size )
6850 {
6851     bool b_result = false;
6852
6853     char *psz_str = (char*) malloc( i_size + 1 );
6854     memcpy( psz_str, p_command, i_size );
6855     psz_str[ i_size ] = '\0';
6856
6857     std::string sz_command = psz_str;
6858     free( psz_str );
6859
6860     msg_Dbg( &sys.demuxer, "command : %s", sz_command.c_str() );
6861
6862 #if defined(__GNUC__) && (__GNUC__ < 3)
6863     if ( sz_command.compare( CMD_MS_GOTO_AND_PLAY, 0, CMD_MS_GOTO_AND_PLAY.size() ) == 0 )
6864 #else
6865     if ( sz_command.compare( 0, CMD_MS_GOTO_AND_PLAY.size(), CMD_MS_GOTO_AND_PLAY ) == 0 )
6866 #endif
6867     {
6868         size_t i,j;
6869
6870         // find the (
6871         for ( i=CMD_MS_GOTO_AND_PLAY.size(); i<sz_command.size(); i++)
6872         {
6873             if ( sz_command[i] == '(' )
6874             {
6875                 i++;
6876                 break;
6877             }
6878         }
6879         // find the )
6880         for ( j=i; j<sz_command.size(); j++)
6881         {
6882             if ( sz_command[j] == ')' )
6883             {
6884                 i--;
6885                 break;
6886             }
6887         }
6888
6889         std::string st = sz_command.substr( i+1, j-i-1 );
6890         int64_t i_chapter_uid = atoi( st.c_str() );
6891
6892         virtual_segment_c *p_segment;
6893         chapter_item_c *p_chapter = sys.FindChapter( i_chapter_uid, p_segment );
6894
6895         if ( p_chapter == NULL )
6896             msg_Dbg( &sys.demuxer, "Chapter %"PRId64" not found", i_chapter_uid);
6897         else
6898         {
6899             if ( !p_chapter->EnterAndLeave( sys.p_current_segment->CurrentChapter() ) )
6900                 p_segment->Seek( sys.demuxer, p_chapter->i_user_start_time, -1, p_chapter, -1 );
6901             b_result = true;
6902         }
6903     }
6904
6905     return b_result;
6906 }
6907
6908 void demux_sys_t::SwapButtons()
6909 {
6910 #ifndef WORDS_BIGENDIAN
6911     uint8_t button, i, j;
6912
6913     for( button = 1; button <= pci_packet.hli.hl_gi.btn_ns; button++) {
6914         btni_t *button_ptr = &(pci_packet.hli.btnit[button-1]);
6915         binary *p_data = (binary*) button_ptr;
6916
6917         uint16 i_x_start = ((p_data[0] & 0x3F) << 4 ) + ( p_data[1] >> 4 );
6918         uint16 i_x_end   = ((p_data[1] & 0x03) << 8 ) + p_data[2];
6919         uint16 i_y_start = ((p_data[3] & 0x3F) << 4 ) + ( p_data[4] >> 4 );
6920         uint16 i_y_end   = ((p_data[4] & 0x03) << 8 ) + p_data[5];
6921         button_ptr->x_start = i_x_start;
6922         button_ptr->x_end   = i_x_end;
6923         button_ptr->y_start = i_y_start;
6924         button_ptr->y_end   = i_y_end;
6925
6926     }
6927     for ( i = 0; i<3; i++ )
6928     {
6929         for ( j = 0; j<2; j++ )
6930         {
6931             pci_packet.hli.btn_colit.btn_coli[i][j] = U32_AT( &pci_packet.hli.btn_colit.btn_coli[i][j] );
6932         }
6933     }
6934 #endif
6935 }