]> git.sesse.net Git - vlc/blob - modules/demux/mkv.cpp
Fix typo
[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             /* update the index */
1773 #define idx p_indexes[i_index - 1]
1774             if( i_index > 0 && idx.i_time == -1 )
1775             {
1776 #if LIBMATROSKA_VERSION >= 0x000800
1777                 if ( pp_simpleblock != NULL )
1778                     idx.i_time        = pp_simpleblock->GlobalTimecode() / (mtime_t)1000;
1779                 else
1780 #endif
1781                     idx.i_time        = (*pp_block).GlobalTimecode() / (mtime_t)1000;
1782                 idx.b_key         = *pi_ref1 == 0 ? true : false;
1783             }
1784 #undef idx
1785             return VLC_SUCCESS;
1786         }
1787
1788         i_level = ep->GetLevel();
1789
1790         if( el == NULL )
1791         {
1792             if( i_level > 1 )
1793             {
1794                 ep->Up();
1795                 continue;
1796             }
1797             msg_Warn( &sys.demuxer, "EOF" );
1798             return VLC_EGENERIC;
1799         }
1800
1801         /* Verify that we are still inside our cluster
1802          * It can happens whith broken files and when seeking
1803          * without index */
1804         if( i_level > 1 )
1805         {
1806             if( cluster && !ep->IsTopPresent( cluster ) )
1807             {
1808                 msg_Warn( &sys.demuxer, "Unexpected escape from current cluster" );
1809                 cluster = NULL;
1810             }
1811             if( !cluster )
1812                 continue;
1813         }
1814
1815         /* do parsing */
1816         switch ( i_level )
1817         {
1818         case 1:
1819             if( MKV_IS_ID( el, KaxCluster ) )
1820             {
1821                 cluster = (KaxCluster*)el;
1822                 i_cluster_pos = cluster->GetElementPosition();
1823
1824                 /* add it to the index */
1825                 if( i_index == 0 ||
1826                     ( i_index > 0 && p_indexes[i_index - 1].i_position < (int64_t)cluster->GetElementPosition() ) )
1827                 {
1828                     IndexAppendCluster( cluster );
1829                 }
1830
1831                 // reset silent tracks
1832                 for (size_t i=0; i<tracks.size(); i++)
1833                 {
1834                     tracks[i]->b_silent = false;
1835                 }
1836
1837                 ep->Down();
1838             }
1839             else if( MKV_IS_ID( el, KaxCues ) )
1840             {
1841                 msg_Warn( &sys.demuxer, "find KaxCues FIXME" );
1842                 return VLC_EGENERIC;
1843             }
1844             else
1845             {
1846                 msg_Dbg( &sys.demuxer, "unknown (%s)", typeid( el ).name() );
1847             }
1848             break;
1849         case 2:
1850             if( MKV_IS_ID( el, KaxClusterTimecode ) )
1851             {
1852                 KaxClusterTimecode &ctc = *(KaxClusterTimecode*)el;
1853
1854                 ctc.ReadData( es.I_O(), SCOPE_ALL_DATA );
1855                 cluster->InitTimecode( uint64( ctc ), i_timescale );
1856             }
1857             else if( MKV_IS_ID( el, KaxClusterSilentTracks ) )
1858             {
1859                 ep->Down();
1860             }
1861             else if( MKV_IS_ID( el, KaxBlockGroup ) )
1862             {
1863                 i_block_pos = el->GetElementPosition();
1864                 ep->Down();
1865             }
1866 #if LIBMATROSKA_VERSION >= 0x000800
1867             else if( MKV_IS_ID( el, KaxSimpleBlock ) )
1868             {
1869                 pp_simpleblock = (KaxSimpleBlock*)el;
1870
1871                 pp_simpleblock->ReadData( es.I_O() );
1872                 pp_simpleblock->SetParent( *cluster );
1873             }
1874 #endif
1875             break;
1876         case 3:
1877             if( MKV_IS_ID( el, KaxBlock ) )
1878             {
1879                 pp_block = (KaxBlock*)el;
1880
1881                 pp_block->ReadData( es.I_O() );
1882                 pp_block->SetParent( *cluster );
1883
1884                 ep->Keep();
1885             }
1886             else if( MKV_IS_ID( el, KaxBlockDuration ) )
1887             {
1888                 KaxBlockDuration &dur = *(KaxBlockDuration*)el;
1889
1890                 dur.ReadData( es.I_O() );
1891                 *pi_duration = uint64( dur );
1892             }
1893             else if( MKV_IS_ID( el, KaxReferenceBlock ) )
1894             {
1895                 KaxReferenceBlock &ref = *(KaxReferenceBlock*)el;
1896
1897                 ref.ReadData( es.I_O() );
1898                 if( *pi_ref1 == 0 )
1899                 {
1900                     *pi_ref1 = int64( ref ) * cluster->GlobalTimecodeScale();
1901                 }
1902                 else if( *pi_ref2 == 0 )
1903                 {
1904                     *pi_ref2 = int64( ref ) * cluster->GlobalTimecodeScale();
1905                 }
1906             }
1907             else if( MKV_IS_ID( el, KaxClusterSilentTrackNumber ) )
1908             {
1909                 KaxClusterSilentTrackNumber &track_num = *(KaxClusterSilentTrackNumber*)el;
1910                 track_num.ReadData( es.I_O() );
1911                 // find the track
1912                 for (size_t i=0; i<tracks.size(); i++)
1913                 {
1914                     if ( tracks[i]->i_number == uint32(track_num))
1915                     {
1916                         tracks[i]->b_silent = true;
1917                         break;
1918                     }
1919                 }
1920             }
1921             break;
1922         default:
1923             msg_Err( &sys.demuxer, "invalid level = %d", i_level );
1924             return VLC_EGENERIC;
1925         }
1926     }
1927 }
1928
1929 static block_t *MemToBlock( demux_t *p_demux, uint8_t *p_mem, int i_mem, size_t offset)
1930 {
1931     block_t *p_block;
1932     if( !(p_block = block_New( p_demux, i_mem + offset ) ) ) return NULL;
1933     memcpy( p_block->p_buffer + offset, p_mem, i_mem );
1934     //p_block->i_rate = p_input->stream.control.i_rate;
1935     return p_block;
1936 }
1937
1938 #if LIBMATROSKA_VERSION >= 0x000800
1939 static void BlockDecode( demux_t *p_demux, KaxBlock *block, KaxSimpleBlock *simpleblock,
1940                          mtime_t i_pts, mtime_t i_duration, bool f_mandatory )
1941 #else
1942 static void BlockDecode( demux_t *p_demux, KaxBlock *block, mtime_t i_pts,
1943                          mtime_t i_duration, bool f_mandatory )
1944 #endif
1945 {
1946     demux_sys_t        *p_sys = p_demux->p_sys;
1947     matroska_segment_c *p_segment = p_sys->p_current_segment->Segment();
1948
1949     size_t          i_track;
1950     unsigned int    i;
1951     bool            b;
1952
1953 #define tk  p_segment->tracks[i_track]
1954     for( i_track = 0; i_track < p_segment->tracks.size(); i_track++ )
1955     {
1956 #if LIBMATROSKA_VERSION >= 0x000800
1957         if( (block != NULL && tk->i_number == block->TrackNum()) ||
1958             (simpleblock != NULL && tk->i_number == simpleblock->TrackNum()))
1959 #else
1960         if( tk->i_number == block->TrackNum() )
1961 #endif
1962         {
1963             break;
1964         }
1965     }
1966
1967     if( i_track >= p_segment->tracks.size() )
1968     {
1969         msg_Err( p_demux, "invalid track number" );
1970         return;
1971     }
1972     if( tk->fmt.i_cat != NAV_ES && tk->p_es == NULL )
1973     {
1974         msg_Err( p_demux, "unknown track number" );
1975         return;
1976     }
1977     if( i_pts + i_duration < p_sys->i_start_pts && tk->fmt.i_cat == AUDIO_ES )
1978     {
1979         return; /* discard audio packets that shouldn't be rendered */
1980     }
1981
1982     if ( tk->fmt.i_cat != NAV_ES )
1983     {
1984         es_out_Control( p_demux->out, ES_OUT_GET_ES_STATE, tk->p_es, &b );
1985
1986         if( !b )
1987         {
1988             tk->b_inited = false;
1989             return;
1990         }
1991     }
1992
1993
1994     /* First send init data */
1995     if( !tk->b_inited && tk->i_data_init > 0 )
1996     {
1997         block_t *p_init;
1998
1999         msg_Dbg( p_demux, "sending header (%d bytes)", tk->i_data_init );
2000         p_init = MemToBlock( p_demux, tk->p_data_init, tk->i_data_init, 0 );
2001         if( p_init ) es_out_Send( p_demux->out, tk->p_es, p_init );
2002     }
2003     tk->b_inited = true;
2004
2005
2006 #if LIBMATROSKA_VERSION >= 0x000800
2007     for( i = 0;
2008         (block != NULL && i < block->NumberFrames()) || (simpleblock != NULL && i < simpleblock->NumberFrames());
2009         i++ )
2010 #else
2011     for( i = 0; i < block->NumberFrames(); i++ )
2012 #endif
2013     {
2014         block_t *p_block;
2015         DataBuffer *data;
2016 #if LIBMATROSKA_VERSION >= 0x000800
2017         if ( simpleblock != NULL )
2018         {
2019             data = &simpleblock->GetBuffer(i);
2020             // condition when the DTS is correct (keyframe or B frame == NOT P frame)
2021             f_mandatory = simpleblock->IsDiscardable() || simpleblock->IsKeyframe();
2022         }
2023         else
2024 #endif
2025         data = &block->GetBuffer(i);
2026
2027         if( tk->i_compression_type == MATROSKA_COMPRESSION_HEADER && tk->p_compression_data != NULL )
2028             p_block = MemToBlock( p_demux, data->Buffer(), data->Size(), tk->p_compression_data->GetSize() );
2029         else
2030             p_block = MemToBlock( p_demux, data->Buffer(), data->Size(), 0 );
2031
2032         if( p_block == NULL )
2033         {
2034             break;
2035         }
2036
2037 #if defined(HAVE_ZLIB_H)
2038         if( tk->i_compression_type == MATROSKA_COMPRESSION_ZLIB )
2039         {
2040             p_block = block_zlib_decompress( VLC_OBJECT(p_demux), p_block );
2041         }
2042         else
2043 #endif
2044         if( tk->i_compression_type == MATROSKA_COMPRESSION_HEADER )
2045         {
2046             memcpy( p_block->p_buffer, tk->p_compression_data->GetBuffer(), tk->p_compression_data->GetSize() );
2047         }
2048
2049         if ( tk->fmt.i_cat == NAV_ES )
2050         {
2051             // TODO handle the start/stop times of this packet
2052             if ( p_sys->b_ui_hooked )
2053             {
2054                 vlc_mutex_lock( &p_sys->p_ev->lock );
2055                 memcpy( &p_sys->pci_packet, &p_block->p_buffer[1], sizeof(pci_t) );
2056                 p_sys->SwapButtons();
2057                 p_sys->b_pci_packet_set = true;
2058                 vlc_mutex_unlock( &p_sys->p_ev->lock );
2059                 block_Release( p_block );
2060             }
2061             return;
2062         }
2063         // correct timestamping when B frames are used
2064         if( tk->fmt.i_cat != VIDEO_ES )
2065         {
2066             p_block->i_dts = p_block->i_pts = i_pts;
2067         }
2068         else
2069         {
2070             if( !strcmp( tk->psz_codec, "V_MS/VFW/FOURCC" ) )
2071             {
2072                 // in VFW we have no idea about B frames
2073                 p_block->i_pts = 0;
2074                 p_block->i_dts = i_pts;
2075             }
2076             else
2077             {
2078                 p_block->i_pts = i_pts;
2079                 if ( f_mandatory )
2080                     p_block->i_dts = p_block->i_pts;
2081                 else
2082                     p_block->i_dts = min( i_pts, tk->i_last_dts + (mtime_t)(tk->i_default_duration >> 10));
2083                 p_sys->i_pts = p_block->i_dts;
2084             }
2085         }
2086         tk->i_last_dts = p_block->i_dts;
2087
2088 #if 0
2089 msg_Dbg( p_demux, "block i_dts: %"PRId64" / i_pts: %"PRId64, p_block->i_dts, p_block->i_pts);
2090 #endif
2091         if( strcmp( tk->psz_codec, "S_VOBSUB" ) )
2092         {
2093             p_block->i_length = i_duration * 1000;
2094         }
2095
2096         es_out_Send( p_demux->out, tk->p_es, p_block );
2097
2098         /* use time stamp only for first block */
2099         i_pts = 0;
2100     }
2101
2102 #undef tk
2103 }
2104
2105 matroska_stream_c *demux_sys_t::AnalyseAllSegmentsFound( demux_t *p_demux, EbmlStream *p_estream, bool b_initial )
2106 {
2107     int i_upper_lvl = 0;
2108     size_t i;
2109     EbmlElement *p_l0, *p_l1, *p_l2;
2110     bool b_keep_stream = false, b_keep_segment;
2111
2112     // verify the EBML Header
2113     p_l0 = p_estream->FindNextID(EbmlHead::ClassInfos, 0xFFFFFFFFL);
2114     if (p_l0 == NULL)
2115     {
2116         msg_Err( p_demux, "No EBML header found" );
2117         return NULL;
2118     }
2119
2120     // verify we can read this Segment, we only support Matroska version 1 for now
2121     p_l0->Read(*p_estream, EbmlHead::ClassInfos.Context, i_upper_lvl, p_l0, true);
2122
2123     EDocType doc_type = GetChild<EDocType>(*static_cast<EbmlHead*>(p_l0));
2124     if (std::string(doc_type) != "matroska")
2125     {
2126         msg_Err( p_demux, "Not a Matroska file : DocType = %s ", std::string(doc_type).c_str());
2127         return NULL;
2128     }
2129
2130     EDocTypeReadVersion doc_read_version = GetChild<EDocTypeReadVersion>(*static_cast<EbmlHead*>(p_l0));
2131 #if LIBMATROSKA_VERSION >= 0x000800
2132     if (uint64(doc_read_version) > 2)
2133     {
2134         msg_Err( p_demux, "This matroska file is needs version %"PRId64" and this VLC only supports version 1 & 2", uint64(doc_read_version));
2135         return NULL;
2136     }
2137 #else
2138     if (uint64(doc_read_version) != 1)
2139     {
2140         msg_Err( p_demux, "This matroska file is needs version %"PRId64" and this VLC only supports version 1", uint64(doc_read_version));
2141         return NULL;
2142     }
2143 #endif
2144
2145     delete p_l0;
2146
2147
2148     // find all segments in this file
2149     p_l0 = p_estream->FindNextID(KaxSegment::ClassInfos, 0xFFFFFFFFFLL);
2150     if (p_l0 == NULL)
2151     {
2152         return NULL;
2153     }
2154
2155     matroska_stream_c *p_stream1 = new matroska_stream_c( *this );
2156
2157     while (p_l0 != 0)
2158     {
2159         if (EbmlId(*p_l0) == KaxSegment::ClassInfos.GlobalId)
2160         {
2161             EbmlParser  *ep;
2162             matroska_segment_c *p_segment1 = new matroska_segment_c( *this, *p_estream );
2163             b_keep_segment = b_initial;
2164
2165             ep = new EbmlParser(p_estream, p_l0, &demuxer );
2166             p_segment1->ep = ep;
2167             p_segment1->segment = (KaxSegment*)p_l0;
2168
2169             while ((p_l1 = ep->Get()))
2170             {
2171                 if (MKV_IS_ID(p_l1, KaxInfo))
2172                 {
2173                     // find the families of this segment
2174                     KaxInfo *p_info = static_cast<KaxInfo*>(p_l1);
2175
2176                     p_info->Read(*p_estream, KaxInfo::ClassInfos.Context, i_upper_lvl, p_l2, true);
2177                     for( i = 0; i < p_info->ListSize(); i++ )
2178                     {
2179                         EbmlElement *l = (*p_info)[i];
2180
2181                         if( MKV_IS_ID( l, KaxSegmentUID ) )
2182                         {
2183                             KaxSegmentUID *p_uid = static_cast<KaxSegmentUID*>(l);
2184                             b_keep_segment = (FindSegment( *p_uid ) == NULL);
2185                             if ( !b_keep_segment )
2186                                 break; // this segment is already known
2187                             opened_segments.push_back( p_segment1 );
2188                             delete p_segment1->p_segment_uid;
2189                             p_segment1->p_segment_uid = new KaxSegmentUID(*p_uid);
2190                         }
2191                         else if( MKV_IS_ID( l, KaxPrevUID ) )
2192                         {
2193                             p_segment1->p_prev_segment_uid = new KaxPrevUID( *static_cast<KaxPrevUID*>(l) );
2194                         }
2195                         else if( MKV_IS_ID( l, KaxNextUID ) )
2196                         {
2197                             p_segment1->p_next_segment_uid = new KaxNextUID( *static_cast<KaxNextUID*>(l) );
2198                         }
2199                         else if( MKV_IS_ID( l, KaxSegmentFamily ) )
2200                         {
2201                             KaxSegmentFamily *p_fam = new KaxSegmentFamily( *static_cast<KaxSegmentFamily*>(l) );
2202                             p_segment1->families.push_back( p_fam );
2203                         }
2204                     }
2205                     break;
2206                 }
2207             }
2208             if ( b_keep_segment )
2209             {
2210                 b_keep_stream = true;
2211                 p_stream1->segments.push_back( p_segment1 );
2212             }
2213             else
2214             {
2215                 p_segment1->segment = NULL;
2216                 delete p_segment1;
2217             }
2218         }
2219         if (p_l0->IsFiniteSize() )
2220         {
2221             p_l0->SkipData(*p_estream, KaxMatroska_Context);
2222             p_l0 = p_estream->FindNextID(KaxSegment::ClassInfos, 0xFFFFFFFFL);
2223         }
2224         else
2225             p_l0 = p_l0->SkipData(*p_estream, KaxSegment_Context);
2226     }
2227
2228     if ( !b_keep_stream )
2229     {
2230         delete p_stream1;
2231         p_stream1 = NULL;
2232     }
2233
2234     return p_stream1;
2235 }
2236
2237 bool matroska_segment_c::Select( mtime_t i_start_time )
2238 {
2239     size_t i_track;
2240
2241     /* add all es */
2242     msg_Dbg( &sys.demuxer, "found %d es", (int)tracks.size() );
2243     sys.b_pci_packet_set = false;
2244
2245     for( i_track = 0; i_track < tracks.size(); i_track++ )
2246     {
2247         if( tracks[i_track]->fmt.i_cat == UNKNOWN_ES )
2248         {
2249             msg_Warn( &sys.demuxer, "invalid track[%d, n=%d]", (int)i_track, tracks[i_track]->i_number );
2250             tracks[i_track]->p_es = NULL;
2251             continue;
2252         }
2253
2254         if( !strcmp( tracks[i_track]->psz_codec, "V_MS/VFW/FOURCC" ) )
2255         {
2256             if( tracks[i_track]->i_extra_data < (int)sizeof( BITMAPINFOHEADER ) )
2257             {
2258                 msg_Err( &sys.demuxer, "missing/invalid BITMAPINFOHEADER" );
2259                 tracks[i_track]->fmt.i_codec = VLC_FOURCC( 'u', 'n', 'd', 'f' );
2260             }
2261             else
2262             {
2263                 BITMAPINFOHEADER *p_bih = (BITMAPINFOHEADER*)tracks[i_track]->p_extra_data;
2264
2265                 tracks[i_track]->fmt.video.i_width = GetDWLE( &p_bih->biWidth );
2266                 tracks[i_track]->fmt.video.i_height= GetDWLE( &p_bih->biHeight );
2267                 tracks[i_track]->fmt.i_codec       = GetFOURCC( &p_bih->biCompression );
2268
2269                 tracks[i_track]->fmt.i_extra       = GetDWLE( &p_bih->biSize ) - sizeof( BITMAPINFOHEADER );
2270                 if( tracks[i_track]->fmt.i_extra > 0 )
2271                 {
2272                     tracks[i_track]->fmt.p_extra = malloc( tracks[i_track]->fmt.i_extra );
2273                     memcpy( tracks[i_track]->fmt.p_extra, &p_bih[1], tracks[i_track]->fmt.i_extra );
2274                 }
2275             }
2276         }
2277         else if( !strcmp( tracks[i_track]->psz_codec, "V_MPEG1" ) ||
2278                  !strcmp( tracks[i_track]->psz_codec, "V_MPEG2" ) )
2279         {
2280             tracks[i_track]->fmt.i_codec = VLC_FOURCC( 'm', 'p', 'g', 'v' );
2281         }
2282         else if( !strncmp( tracks[i_track]->psz_codec, "V_THEORA", 8 ) )
2283         {
2284             uint8_t *p_data = tracks[i_track]->p_extra_data;
2285             tracks[i_track]->fmt.i_codec = VLC_FOURCC( 't', 'h', 'e', 'o' );
2286             if( tracks[i_track]->i_extra_data >= 4 ) {
2287                 if( p_data[0] == 2 ) {
2288                     int i = 1;
2289                     int i_size1 = 0, i_size2 = 0;
2290                     p_data++;
2291                     /* read size of first header packet */
2292                     while( *p_data == 0xFF &&
2293                            i < tracks[i_track]->i_extra_data )
2294                     {
2295                         i_size1 += *p_data;
2296                         p_data++;
2297                         i++;
2298                     }
2299                     i_size1 += *p_data;
2300                     p_data++;
2301                     i++;
2302                     msg_Dbg( &sys.demuxer, "first theora header size %d", i_size1 );
2303                     /* read size of second header packet */
2304                     while( *p_data == 0xFF &&
2305                            i < tracks[i_track]->i_extra_data )
2306                     {
2307                         i_size2 += *p_data;
2308                         p_data++;
2309                         i++;
2310                     }
2311                     i_size2 += *p_data;
2312                     p_data++;
2313                     i++;
2314                     int i_size3 = tracks[i_track]->i_extra_data - i - i_size1
2315                         - i_size2;
2316                     msg_Dbg( &sys.demuxer, "second theora header size %d", i_size2 );
2317                     msg_Dbg( &sys.demuxer, "third theora header size %d", i_size3 );
2318                     tracks[i_track]->fmt.i_extra = i_size1 + i_size2 + i_size3
2319                         + 6;
2320                     if( i_size1 > 0 && i_size2 > 0 && i_size3 > 0  ) {
2321                         tracks[i_track]->fmt.p_extra =
2322                             malloc( tracks[i_track]->fmt.i_extra );
2323                         uint8_t *p_out = (uint8_t*)tracks[i_track]->fmt.p_extra;
2324                         *p_out++ = (i_size1>>8) & 0xFF;
2325                         *p_out++ = i_size1 & 0xFF;
2326                         memcpy( p_out, p_data, i_size1 );
2327                         p_data += i_size1;
2328                         p_out += i_size1;
2329  
2330                         *p_out++ = (i_size2>>8) & 0xFF;
2331                         *p_out++ = i_size2 & 0xFF;
2332                         memcpy( p_out, p_data, i_size2 );
2333                         p_data += i_size2;
2334                         p_out += i_size2;
2335
2336                         *p_out++ = (i_size3>>8) & 0xFF;
2337                         *p_out++ = i_size3 & 0xFF;
2338                         memcpy( p_out, p_data, i_size3 );
2339                         p_data += i_size3;
2340                         p_out += i_size3;
2341                     }
2342                     else
2343                     {
2344                         msg_Err( &sys.demuxer, "inconsistant theora extradata" );
2345                     }
2346                 }
2347                 else {
2348                     msg_Err( &sys.demuxer, "Wrong number of ogg packets with theora headers (%d)", p_data[0] + 1 );
2349                 }
2350             }
2351         }
2352         else if( !strncmp( tracks[i_track]->psz_codec, "V_REAL/RV", 9 ) )
2353         {
2354             if( !strcmp( tracks[i_track]->psz_codec, "V_REAL/RV10" ) )
2355                 tracks[i_track]->fmt.i_codec = VLC_FOURCC( 'R', 'V', '1', '0' );
2356             else if( !strcmp( tracks[i_track]->psz_codec, "V_REAL/RV20" ) )
2357                 tracks[i_track]->fmt.i_codec = VLC_FOURCC( 'R', 'V', '2', '0' );
2358             else if( !strcmp( tracks[i_track]->psz_codec, "V_REAL/RV30" ) )
2359                 tracks[i_track]->fmt.i_codec = VLC_FOURCC( 'R', 'V', '3', '0' );
2360             else if( !strcmp( tracks[i_track]->psz_codec, "V_REAL/RV40" ) )
2361                 tracks[i_track]->fmt.i_codec = VLC_FOURCC( 'R', 'V', '4', '0' );
2362         }
2363         else if( !strncmp( tracks[i_track]->psz_codec, "V_MPEG4", 7 ) )
2364         {
2365             if( !strcmp( tracks[i_track]->psz_codec, "V_MPEG4/MS/V3" ) )
2366             {
2367                 tracks[i_track]->fmt.i_codec = VLC_FOURCC( 'D', 'I', 'V', '3' );
2368             }
2369             else if( !strncmp( tracks[i_track]->psz_codec, "V_MPEG4/ISO", 11 ) )
2370             {
2371                 /* A MPEG 4 codec, SP, ASP, AP or AVC */
2372                 if( !strcmp( tracks[i_track]->psz_codec, "V_MPEG4/ISO/AVC" ) )
2373                     tracks[i_track]->fmt.i_codec = VLC_FOURCC( 'a', 'v', 'c', '1' );
2374                 else
2375                     tracks[i_track]->fmt.i_codec = VLC_FOURCC( 'm', 'p', '4', 'v' );
2376                 tracks[i_track]->fmt.i_extra = tracks[i_track]->i_extra_data;
2377                 tracks[i_track]->fmt.p_extra = malloc( tracks[i_track]->i_extra_data );
2378                 memcpy( tracks[i_track]->fmt.p_extra,tracks[i_track]->p_extra_data, tracks[i_track]->i_extra_data );
2379             }
2380         }
2381         else if( !strcmp( tracks[i_track]->psz_codec, "V_QUICKTIME" ) )
2382         {
2383             MP4_Box_t *p_box = (MP4_Box_t*)malloc( sizeof( MP4_Box_t ) );
2384             stream_t *p_mp4_stream = stream_MemoryNew( VLC_OBJECT(&sys.demuxer),
2385                                                        tracks[i_track]->p_extra_data,
2386                                                        tracks[i_track]->i_extra_data,
2387                                                        false );
2388             MP4_ReadBoxCommon( p_mp4_stream, p_box );
2389             MP4_ReadBox_sample_vide( p_mp4_stream, p_box );
2390             tracks[i_track]->fmt.i_codec = p_box->i_type;
2391             tracks[i_track]->fmt.video.i_width = p_box->data.p_sample_vide->i_width;
2392             tracks[i_track]->fmt.video.i_height = p_box->data.p_sample_vide->i_height;
2393             tracks[i_track]->fmt.i_extra = p_box->data.p_sample_vide->i_qt_image_description;
2394             tracks[i_track]->fmt.p_extra = malloc( tracks[i_track]->fmt.i_extra );
2395             memcpy( tracks[i_track]->fmt.p_extra, p_box->data.p_sample_vide->p_qt_image_description, tracks[i_track]->fmt.i_extra );
2396             MP4_FreeBox_sample_vide( p_box );
2397             stream_Delete( p_mp4_stream );
2398         }
2399         else if( !strcmp( tracks[i_track]->psz_codec, "A_MS/ACM" ) )
2400         {
2401             if( tracks[i_track]->i_extra_data < (int)sizeof( WAVEFORMATEX ) )
2402             {
2403                 msg_Err( &sys.demuxer, "missing/invalid WAVEFORMATEX" );
2404                 tracks[i_track]->fmt.i_codec = VLC_FOURCC( 'u', 'n', 'd', 'f' );
2405             }
2406             else
2407             {
2408                 WAVEFORMATEX *p_wf = (WAVEFORMATEX*)tracks[i_track]->p_extra_data;
2409
2410                 wf_tag_to_fourcc( GetWLE( &p_wf->wFormatTag ), &tracks[i_track]->fmt.i_codec, NULL );
2411
2412                 tracks[i_track]->fmt.audio.i_channels   = GetWLE( &p_wf->nChannels );
2413                 tracks[i_track]->fmt.audio.i_rate = GetDWLE( &p_wf->nSamplesPerSec );
2414                 tracks[i_track]->fmt.i_bitrate    = GetDWLE( &p_wf->nAvgBytesPerSec ) * 8;
2415                 tracks[i_track]->fmt.audio.i_blockalign = GetWLE( &p_wf->nBlockAlign );;
2416                 tracks[i_track]->fmt.audio.i_bitspersample = GetWLE( &p_wf->wBitsPerSample );
2417
2418                 tracks[i_track]->fmt.i_extra            = GetWLE( &p_wf->cbSize );
2419                 if( tracks[i_track]->fmt.i_extra > 0 )
2420                 {
2421                     tracks[i_track]->fmt.p_extra = malloc( tracks[i_track]->fmt.i_extra );
2422                     memcpy( tracks[i_track]->fmt.p_extra, &p_wf[1], tracks[i_track]->fmt.i_extra );
2423                 }
2424             }
2425         }
2426         else if( !strcmp( tracks[i_track]->psz_codec, "A_MPEG/L3" ) ||
2427                  !strcmp( tracks[i_track]->psz_codec, "A_MPEG/L2" ) ||
2428                  !strcmp( tracks[i_track]->psz_codec, "A_MPEG/L1" ) )
2429         {
2430             tracks[i_track]->fmt.i_codec = VLC_FOURCC( 'm', 'p', 'g', 'a' );
2431         }
2432         else if( !strcmp( tracks[i_track]->psz_codec, "A_AC3" ) )
2433         {
2434             tracks[i_track]->fmt.i_codec = VLC_FOURCC( 'a', '5', '2', ' ' );
2435         }
2436         else if( !strcmp( tracks[i_track]->psz_codec, "A_DTS" ) )
2437         {
2438             tracks[i_track]->fmt.i_codec = VLC_FOURCC( 'd', 't', 's', ' ' );
2439         }
2440         else if( !strcmp( tracks[i_track]->psz_codec, "A_FLAC" ) )
2441         {
2442             tracks[i_track]->fmt.i_codec = VLC_FOURCC( 'f', 'l', 'a', 'c' );
2443             tracks[i_track]->fmt.i_extra = tracks[i_track]->i_extra_data;
2444             tracks[i_track]->fmt.p_extra = malloc( tracks[i_track]->i_extra_data );
2445             memcpy( tracks[i_track]->fmt.p_extra,tracks[i_track]->p_extra_data, tracks[i_track]->i_extra_data );
2446         }
2447         else if( !strcmp( tracks[i_track]->psz_codec, "A_VORBIS" ) )
2448         {
2449             int i, i_offset = 1, i_size[3], i_extra;
2450             uint8_t *p_extra;
2451
2452             tracks[i_track]->fmt.i_codec = VLC_FOURCC( 'v', 'o', 'r', 'b' );
2453
2454             /* Split the 3 headers */
2455             if( tracks[i_track]->p_extra_data[0] != 0x02 )
2456                 msg_Err( &sys.demuxer, "invalid vorbis header" );
2457
2458             for( i = 0; i < 2; i++ )
2459             {
2460                 i_size[i] = 0;
2461                 while( i_offset < tracks[i_track]->i_extra_data )
2462                 {
2463                     i_size[i] += tracks[i_track]->p_extra_data[i_offset];
2464                     if( tracks[i_track]->p_extra_data[i_offset++] != 0xff ) break;
2465                 }
2466             }
2467
2468             i_size[0] = __MIN(i_size[0], tracks[i_track]->i_extra_data - i_offset);
2469             i_size[1] = __MIN(i_size[1], tracks[i_track]->i_extra_data -i_offset -i_size[0]);
2470             i_size[2] = tracks[i_track]->i_extra_data - i_offset - i_size[0] - i_size[1];
2471
2472             tracks[i_track]->fmt.i_extra = 3 * 2 + i_size[0] + i_size[1] + i_size[2];
2473             tracks[i_track]->fmt.p_extra = malloc( tracks[i_track]->fmt.i_extra );
2474             p_extra = (uint8_t *)tracks[i_track]->fmt.p_extra; i_extra = 0;
2475             for( i = 0; i < 3; i++ )
2476             {
2477                 *(p_extra++) = i_size[i] >> 8;
2478                 *(p_extra++) = i_size[i] & 0xFF;
2479                 memcpy( p_extra, tracks[i_track]->p_extra_data + i_offset + i_extra,
2480                         i_size[i] );
2481                 p_extra += i_size[i];
2482                 i_extra += i_size[i];
2483             }
2484         }
2485         else if( !strncmp( tracks[i_track]->psz_codec, "A_AAC/MPEG2/", strlen( "A_AAC/MPEG2/" ) ) ||
2486                  !strncmp( tracks[i_track]->psz_codec, "A_AAC/MPEG4/", strlen( "A_AAC/MPEG4/" ) ) )
2487         {
2488             int i_profile, i_srate, sbr = 0;
2489             static const unsigned int i_sample_rates[] =
2490             {
2491                     96000, 88200, 64000, 48000, 44100, 32000, 24000, 22050,
2492                         16000, 12000, 11025, 8000,  7350,  0,     0,     0
2493             };
2494
2495             tracks[i_track]->fmt.i_codec = VLC_FOURCC( 'm', 'p', '4', 'a' );
2496             /* create data for faad (MP4DecSpecificDescrTag)*/
2497
2498             if( !strcmp( &tracks[i_track]->psz_codec[12], "MAIN" ) )
2499             {
2500                 i_profile = 0;
2501             }
2502             else if( !strcmp( &tracks[i_track]->psz_codec[12], "LC" ) )
2503             {
2504                 i_profile = 1;
2505             }
2506             else if( !strcmp( &tracks[i_track]->psz_codec[12], "SSR" ) )
2507             {
2508                 i_profile = 2;
2509             }
2510             else if( !strcmp( &tracks[i_track]->psz_codec[12], "LC/SBR" ) )
2511             {
2512                 i_profile = 1;
2513                 sbr = 1;
2514             }
2515             else
2516             {
2517                 i_profile = 3;
2518             }
2519
2520             for( i_srate = 0; i_srate < 13; i_srate++ )
2521             {
2522                 if( i_sample_rates[i_srate] == tracks[i_track]->i_original_rate )
2523                 {
2524                     break;
2525                 }
2526             }
2527             msg_Dbg( &sys.demuxer, "profile=%d srate=%d", i_profile, i_srate );
2528
2529             tracks[i_track]->fmt.i_extra = sbr ? 5 : 2;
2530             tracks[i_track]->fmt.p_extra = malloc( tracks[i_track]->fmt.i_extra );
2531             ((uint8_t*)tracks[i_track]->fmt.p_extra)[0] = ((i_profile + 1) << 3) | ((i_srate&0xe) >> 1);
2532             ((uint8_t*)tracks[i_track]->fmt.p_extra)[1] = ((i_srate & 0x1) << 7) | (tracks[i_track]->fmt.audio.i_channels << 3);
2533             if (sbr != 0)
2534             {
2535                 int syncExtensionType = 0x2B7;
2536                 int iDSRI;
2537                 for (iDSRI=0; iDSRI<13; iDSRI++)
2538                     if( i_sample_rates[iDSRI] == tracks[i_track]->fmt.audio.i_rate )
2539                         break;
2540                 ((uint8_t*)tracks[i_track]->fmt.p_extra)[2] = (syncExtensionType >> 3) & 0xFF;
2541                 ((uint8_t*)tracks[i_track]->fmt.p_extra)[3] = ((syncExtensionType & 0x7) << 5) | 5;
2542                 ((uint8_t*)tracks[i_track]->fmt.p_extra)[4] = ((1 & 0x1) << 7) | (iDSRI << 3);
2543             }
2544         }
2545         else if( !strcmp( tracks[i_track]->psz_codec, "A_AAC" ) )
2546         {
2547             tracks[i_track]->fmt.i_codec = VLC_FOURCC( 'm', 'p', '4', 'a' );
2548             tracks[i_track]->fmt.i_extra = tracks[i_track]->i_extra_data;
2549             tracks[i_track]->fmt.p_extra = malloc( tracks[i_track]->i_extra_data );
2550             memcpy( tracks[i_track]->fmt.p_extra, tracks[i_track]->p_extra_data, tracks[i_track]->i_extra_data );
2551         }
2552         else if( !strcmp( tracks[i_track]->psz_codec, "A_WAVPACK4" ) )
2553         {
2554             tracks[i_track]->fmt.i_codec = VLC_FOURCC( 'W', 'V', 'P', 'K' );
2555             tracks[i_track]->fmt.i_extra = tracks[i_track]->i_extra_data;
2556             tracks[i_track]->fmt.p_extra = malloc( tracks[i_track]->i_extra_data );
2557             memcpy( tracks[i_track]->fmt.p_extra, tracks[i_track]->p_extra_data, tracks[i_track]->i_extra_data );
2558         }
2559         else if( !strcmp( tracks[i_track]->psz_codec, "A_TTA1" ) )
2560         {
2561             tracks[i_track]->fmt.i_codec = VLC_FOURCC( 'T', 'T', 'A', '1' );
2562             tracks[i_track]->fmt.i_extra = tracks[i_track]->i_extra_data;
2563             tracks[i_track]->fmt.p_extra = malloc( tracks[i_track]->i_extra_data );
2564             memcpy( tracks[i_track]->fmt.p_extra, tracks[i_track]->p_extra_data, tracks[i_track]->i_extra_data );
2565         }
2566         else if( !strcmp( tracks[i_track]->psz_codec, "A_PCM/INT/BIG" ) ||
2567                  !strcmp( tracks[i_track]->psz_codec, "A_PCM/INT/LIT" ) ||
2568                  !strcmp( tracks[i_track]->psz_codec, "A_PCM/FLOAT/IEEE" ) )
2569         {
2570             if( !strcmp( tracks[i_track]->psz_codec, "A_PCM/INT/BIG" ) )
2571             {
2572                 tracks[i_track]->fmt.i_codec = VLC_FOURCC( 't', 'w', 'o', 's' );
2573             }
2574             else
2575             {
2576                 tracks[i_track]->fmt.i_codec = VLC_FOURCC( 'a', 'r', 'a', 'w' );
2577             }
2578             tracks[i_track]->fmt.audio.i_blockalign = ( tracks[i_track]->fmt.audio.i_bitspersample + 7 ) / 8 * tracks[i_track]->fmt.audio.i_channels;
2579         }
2580         /* disabled due to the potential "S_KATE" namespace issue */
2581         else if( !strcmp( tracks[i_track]->psz_codec, "S_KATE" ) )
2582         {
2583             int i, i_offset = 1, *i_size, i_extra, num_headers, size_so_far;
2584             uint8_t *p_extra;
2585
2586             tracks[i_track]->fmt.i_codec = VLC_FOURCC( 'k', 'a', 't', 'e' );
2587             tracks[i_track]->fmt.subs.psz_encoding = strdup( "UTF-8" );
2588
2589             /* Recover the number of headers to expect */
2590             num_headers = tracks[i_track]->p_extra_data[0]+1;
2591             msg_Dbg( &sys.demuxer, "kate in mkv detected: %d headers in %u bytes",
2592                 num_headers, tracks[i_track]->i_extra_data);
2593
2594             /* this won't overflow the stack as is can allocate only 1020 bytes max */
2595             i_size = (int*)alloca(num_headers*sizeof(int));
2596
2597             /* Split the headers */
2598             size_so_far = 0;
2599             for( i = 0; i < num_headers-1; i++ )
2600             {
2601                 i_size[i] = 0;
2602                 while( i_offset < tracks[i_track]->i_extra_data )
2603                 {
2604                     i_size[i] += tracks[i_track]->p_extra_data[i_offset];
2605                     if( tracks[i_track]->p_extra_data[i_offset++] != 0xff ) break;
2606                 }
2607                 msg_Dbg( &sys.demuxer, "kate header %d is %d bytes", i, i_size[i]);
2608                 size_so_far += i_size[i];
2609             }
2610             i_size[num_headers-1] = tracks[i_track]->i_extra_data - (size_so_far+i_offset);
2611             msg_Dbg( &sys.demuxer, "kate last header (%d) is %d bytes", num_headers-1, i_size[num_headers-1]);
2612
2613             tracks[i_track]->fmt.i_extra = 1 + num_headers * 2 + size_so_far + i_size[num_headers-1];
2614             tracks[i_track]->fmt.p_extra = malloc( tracks[i_track]->fmt.i_extra );
2615
2616             p_extra = (uint8_t *)tracks[i_track]->fmt.p_extra;
2617             i_extra = 0;
2618             *(p_extra++) = num_headers;
2619             ++i_extra;
2620             for( i = 0; i < num_headers; i++ )
2621             {
2622                 *(p_extra++) = i_size[i] >> 8;
2623                 *(p_extra++) = i_size[i] & 0xFF;
2624                 memcpy( p_extra, tracks[i_track]->p_extra_data + i_offset + i_extra-1,
2625                         i_size[i] );
2626                 p_extra += i_size[i];
2627                 i_extra += i_size[i];
2628             }
2629         }
2630         else if( !strcmp( tracks[i_track]->psz_codec, "S_TEXT/UTF8" ) )
2631         {
2632             tracks[i_track]->fmt.i_codec = VLC_FOURCC( 's', 'u', 'b', 't' );
2633             tracks[i_track]->fmt.subs.psz_encoding = strdup( "UTF-8" );
2634         }
2635         else if( !strcmp( tracks[i_track]->psz_codec, "S_TEXT/USF" ) )
2636         {
2637             tracks[i_track]->fmt.i_codec = VLC_FOURCC( 'u', 's', 'f', ' ' );
2638             tracks[i_track]->fmt.subs.psz_encoding = strdup( "UTF-8" );
2639             if( tracks[i_track]->i_extra_data )
2640             {
2641                 tracks[i_track]->fmt.i_extra = tracks[i_track]->i_extra_data;
2642                 tracks[i_track]->fmt.p_extra = malloc( tracks[i_track]->i_extra_data );
2643                 memcpy( tracks[i_track]->fmt.p_extra, tracks[i_track]->p_extra_data, tracks[i_track]->i_extra_data );
2644             }
2645         }
2646         else if( !strcmp( tracks[i_track]->psz_codec, "S_TEXT/SSA" ) ||
2647                  !strcmp( tracks[i_track]->psz_codec, "S_TEXT/ASS" ) ||
2648                  !strcmp( tracks[i_track]->psz_codec, "S_SSA" ) ||
2649                  !strcmp( tracks[i_track]->psz_codec, "S_ASS" ))
2650         {
2651             tracks[i_track]->fmt.i_codec = VLC_FOURCC( 's', 's', 'a', ' ' );
2652             tracks[i_track]->fmt.subs.psz_encoding = strdup( "UTF-8" );
2653             if( tracks[i_track]->i_extra_data )
2654             {
2655                 tracks[i_track]->fmt.i_extra = tracks[i_track]->i_extra_data;
2656                 tracks[i_track]->fmt.p_extra = malloc( tracks[i_track]->i_extra_data );
2657                 memcpy( tracks[i_track]->fmt.p_extra, tracks[i_track]->p_extra_data, tracks[i_track]->i_extra_data );
2658             }
2659         }
2660         else if( !strcmp( tracks[i_track]->psz_codec, "S_VOBSUB" ) )
2661         {
2662             tracks[i_track]->fmt.i_codec = VLC_FOURCC( 's','p','u',' ' );
2663             if( tracks[i_track]->i_extra_data )
2664             {
2665                 char *p_start;
2666                 char *p_buf = (char *)malloc( tracks[i_track]->i_extra_data + 1);
2667                 memcpy( p_buf, tracks[i_track]->p_extra_data , tracks[i_track]->i_extra_data );
2668                 p_buf[tracks[i_track]->i_extra_data] = '\0';
2669  
2670                 p_start = strstr( p_buf, "size:" );
2671                 if( sscanf( p_start, "size: %dx%d",
2672                         &tracks[i_track]->fmt.subs.spu.i_original_frame_width, &tracks[i_track]->fmt.subs.spu.i_original_frame_height ) == 2 )
2673                 {
2674                     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 );
2675                 }
2676                 else
2677                 {
2678                     msg_Warn( &sys.demuxer, "reading original frame size for vobsub failed" );
2679                 }
2680                 free( p_buf );
2681             }
2682         }
2683         else if( !strcmp( tracks[i_track]->psz_codec, "B_VOBBTN" ) )
2684         {
2685             tracks[i_track]->fmt.i_cat = NAV_ES;
2686             continue;
2687         }
2688         else
2689         {
2690             msg_Err( &sys.demuxer, "unknown codec id=`%s'", tracks[i_track]->psz_codec );
2691             tracks[i_track]->fmt.i_codec = VLC_FOURCC( 'u', 'n', 'd', 'f' );
2692         }
2693         if( tracks[i_track]->b_default )
2694         {
2695             tracks[i_track]->fmt.i_priority = 1000;
2696         }
2697
2698         tracks[i_track]->p_es = es_out_Add( sys.demuxer.out, &tracks[i_track]->fmt );
2699
2700         /* Turn on a subtitles track if it has been flagged as default -
2701          * but only do this if no subtitles track has already been engaged,
2702          * either by an earlier 'default track' (??) or by default
2703          * language choice behaviour.
2704          */
2705         if( tracks[i_track]->b_default )
2706         {
2707             es_out_Control( sys.demuxer.out,
2708                             ES_OUT_SET_DEFAULT,
2709                             tracks[i_track]->p_es );
2710         }
2711
2712         es_out_Control( sys.demuxer.out, ES_OUT_SET_NEXT_DISPLAY_TIME, tracks[i_track]->p_es, i_start_time );
2713     }
2714  
2715     sys.i_start_pts = i_start_time;
2716     // reset the stream reading to the first cluster of the segment used
2717     es.I_O().setFilePointer( i_start_pos );
2718
2719     delete ep;
2720     ep = new EbmlParser( &es, segment, &sys.demuxer );
2721
2722     return true;
2723 }
2724
2725 void demux_sys_t::StartUiThread()
2726 {
2727     if ( !b_ui_hooked )
2728     {
2729         msg_Dbg( &demuxer, "Starting the UI Hook" );
2730         b_ui_hooked = true;
2731         /* FIXME hack hack hack hack FIXME */
2732         /* Get p_input and create variable */
2733         p_input = (input_thread_t *) vlc_object_find( &demuxer, VLC_OBJECT_INPUT, FIND_PARENT );
2734         var_Create( p_input, "x-start", VLC_VAR_INTEGER );
2735         var_Create( p_input, "y-start", VLC_VAR_INTEGER );
2736         var_Create( p_input, "x-end", VLC_VAR_INTEGER );
2737         var_Create( p_input, "y-end", VLC_VAR_INTEGER );
2738         var_Create( p_input, "color", VLC_VAR_ADDRESS );
2739         var_Create( p_input, "menu-palette", VLC_VAR_ADDRESS );
2740         var_Create( p_input, "highlight", VLC_VAR_BOOL );
2741         var_Create( p_input, "highlight-mutex", VLC_VAR_MUTEX );
2742
2743         /* Now create our event thread catcher */
2744         p_ev = (event_thread_t *) vlc_object_create( &demuxer, sizeof( event_thread_t ) );
2745         p_ev->p_demux = &demuxer;
2746         p_ev->b_die = false;
2747         vlc_mutex_init( &p_ev->lock );
2748         vlc_thread_create( p_ev, "mkv event thread handler", EventThread,
2749                         VLC_THREAD_PRIORITY_LOW, false );
2750     }
2751 }
2752
2753 void demux_sys_t::StopUiThread()
2754 {
2755     if ( b_ui_hooked )
2756     {
2757         vlc_object_kill( p_ev );
2758         vlc_thread_join( p_ev );
2759         vlc_object_release( p_ev );
2760
2761         p_ev = NULL;
2762
2763         var_Destroy( p_input, "highlight-mutex" );
2764         var_Destroy( p_input, "highlight" );
2765         var_Destroy( p_input, "x-start" );
2766         var_Destroy( p_input, "x-end" );
2767         var_Destroy( p_input, "y-start" );
2768         var_Destroy( p_input, "y-end" );
2769         var_Destroy( p_input, "color" );
2770         var_Destroy( p_input, "menu-palette" );
2771
2772         vlc_object_release( p_input );
2773
2774         msg_Dbg( &demuxer, "Stopping the UI Hook" );
2775     }
2776     b_ui_hooked = false;
2777 }
2778
2779 int demux_sys_t::EventMouse( vlc_object_t *p_this, char const *psz_var,
2780                        vlc_value_t oldval, vlc_value_t newval, void *p_data )
2781 {
2782     event_thread_t *p_ev = (event_thread_t *) p_data;
2783     vlc_mutex_lock( &p_ev->lock );
2784     if( psz_var[6] == 'c' )
2785     {
2786         p_ev->b_clicked = true;
2787         msg_Dbg( p_this, "Event Mouse: clicked");
2788     }
2789     else if( psz_var[6] == 'm' )
2790         p_ev->b_moved = true;
2791     vlc_mutex_unlock( &p_ev->lock );
2792
2793     return VLC_SUCCESS;
2794 }
2795
2796 int demux_sys_t::EventKey( vlc_object_t *p_this, char const *,
2797                            vlc_value_t, 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     p_ev->i_key_action = newval.i_int;
2802     vlc_mutex_unlock( &p_ev->lock );
2803     msg_Dbg( p_this, "Event Key");
2804
2805     return VLC_SUCCESS;
2806 }
2807
2808 void * demux_sys_t::EventThread( vlc_object_t *p_this )
2809 {
2810     event_thread_t *p_ev = (event_thread_t*)p_this;
2811     demux_sys_t    *p_sys = p_ev->p_demux->p_sys;
2812     vlc_object_t   *p_vout = NULL;
2813
2814     p_ev->b_moved   = false;
2815     p_ev->b_clicked = false;
2816     p_ev->i_key_action = 0;
2817
2818     /* catch all key event */
2819     var_AddCallback( p_ev->p_libvlc, "key-action", EventKey, p_ev );
2820
2821     /* main loop */
2822     while( vlc_object_alive (p_ev) )
2823     {
2824         if ( !p_sys->b_pci_packet_set )
2825         {
2826             /* Wait 100ms */
2827             msleep( 100000 );
2828             continue;
2829         }
2830
2831         bool b_activated = false;
2832
2833         /* KEY part */
2834         if( p_ev->i_key_action )
2835         {
2836             int i;
2837
2838             msg_Dbg( p_ev->p_demux, "Handle Key Event");
2839
2840             vlc_mutex_lock( &p_ev->lock );
2841
2842             pci_t *pci = (pci_t *) &p_sys->pci_packet;
2843
2844             uint16 i_curr_button = p_sys->dvd_interpretor.GetSPRM( 0x88 );
2845
2846             switch( p_ev->i_key_action )
2847             {
2848             case ACTIONID_NAV_LEFT:
2849                 if ( i_curr_button > 0 && i_curr_button <= pci->hli.hl_gi.btn_ns )
2850                 {
2851                     btni_t *p_button_ptr = &(pci->hli.btnit[i_curr_button-1]);
2852                     if ( p_button_ptr->left > 0 && p_button_ptr->left <= pci->hli.hl_gi.btn_ns )
2853                     {
2854                         i_curr_button = p_button_ptr->left;
2855                         p_sys->dvd_interpretor.SetSPRM( 0x88, i_curr_button );
2856                         btni_t button_ptr = pci->hli.btnit[i_curr_button-1];
2857                         if ( button_ptr.auto_action_mode )
2858                         {
2859                             vlc_mutex_unlock( &p_ev->lock );
2860                             vlc_mutex_lock( &p_sys->lock_demuxer );
2861
2862                             // process the button action
2863                             p_sys->dvd_interpretor.Interpret( button_ptr.cmd.bytes, 8 );
2864
2865                             vlc_mutex_unlock( &p_sys->lock_demuxer );
2866                             vlc_mutex_lock( &p_ev->lock );
2867                         }
2868                     }
2869                 }
2870                 break;
2871             case ACTIONID_NAV_RIGHT:
2872                 if ( i_curr_button > 0 && i_curr_button <= pci->hli.hl_gi.btn_ns )
2873                 {
2874                     btni_t *p_button_ptr = &(pci->hli.btnit[i_curr_button-1]);
2875                     if ( p_button_ptr->right > 0 && p_button_ptr->right <= pci->hli.hl_gi.btn_ns )
2876                     {
2877                         i_curr_button = p_button_ptr->right;
2878                         p_sys->dvd_interpretor.SetSPRM( 0x88, i_curr_button );
2879                         btni_t button_ptr = pci->hli.btnit[i_curr_button-1];
2880                         if ( button_ptr.auto_action_mode )
2881                         {
2882                             vlc_mutex_unlock( &p_ev->lock );
2883                             vlc_mutex_lock( &p_sys->lock_demuxer );
2884
2885                             // process the button action
2886                             p_sys->dvd_interpretor.Interpret( button_ptr.cmd.bytes, 8 );
2887
2888                             vlc_mutex_unlock( &p_sys->lock_demuxer );
2889                             vlc_mutex_lock( &p_ev->lock );
2890                         }
2891                     }
2892                 }
2893                 break;
2894             case ACTIONID_NAV_UP:
2895                 if ( i_curr_button > 0 && i_curr_button <= pci->hli.hl_gi.btn_ns )
2896                 {
2897                     btni_t *p_button_ptr = &(pci->hli.btnit[i_curr_button-1]);
2898                     if ( p_button_ptr->up > 0 && p_button_ptr->up <= pci->hli.hl_gi.btn_ns )
2899                     {
2900                         i_curr_button = p_button_ptr->up;
2901                         p_sys->dvd_interpretor.SetSPRM( 0x88, i_curr_button );
2902                         btni_t button_ptr = pci->hli.btnit[i_curr_button-1];
2903                         if ( button_ptr.auto_action_mode )
2904                         {
2905                             vlc_mutex_unlock( &p_ev->lock );
2906                             vlc_mutex_lock( &p_sys->lock_demuxer );
2907
2908                             // process the button action
2909                             p_sys->dvd_interpretor.Interpret( button_ptr.cmd.bytes, 8 );
2910
2911                             vlc_mutex_unlock( &p_sys->lock_demuxer );
2912                             vlc_mutex_lock( &p_ev->lock );
2913                         }
2914                     }
2915                 }
2916                 break;
2917             case ACTIONID_NAV_DOWN:
2918                 if ( i_curr_button > 0 && i_curr_button <= pci->hli.hl_gi.btn_ns )
2919                 {
2920                     btni_t *p_button_ptr = &(pci->hli.btnit[i_curr_button-1]);
2921                     if ( p_button_ptr->down > 0 && p_button_ptr->down <= pci->hli.hl_gi.btn_ns )
2922                     {
2923                         i_curr_button = p_button_ptr->down;
2924                         p_sys->dvd_interpretor.SetSPRM( 0x88, i_curr_button );
2925                         btni_t button_ptr = pci->hli.btnit[i_curr_button-1];
2926                         if ( button_ptr.auto_action_mode )
2927                         {
2928                             vlc_mutex_unlock( &p_ev->lock );
2929                             vlc_mutex_lock( &p_sys->lock_demuxer );
2930
2931                             // process the button action
2932                             p_sys->dvd_interpretor.Interpret( button_ptr.cmd.bytes, 8 );
2933
2934                             vlc_mutex_unlock( &p_sys->lock_demuxer );
2935                             vlc_mutex_lock( &p_ev->lock );
2936                         }
2937                     }
2938                 }
2939                 break;
2940             case ACTIONID_NAV_ACTIVATE:
2941                 b_activated = true;
2942  
2943                 if ( i_curr_button > 0 && i_curr_button <= pci->hli.hl_gi.btn_ns )
2944                 {
2945                     btni_t button_ptr = pci->hli.btnit[i_curr_button-1];
2946
2947                     vlc_mutex_unlock( &p_ev->lock );
2948                     vlc_mutex_lock( &p_sys->lock_demuxer );
2949
2950                     // process the button action
2951                     p_sys->dvd_interpretor.Interpret( button_ptr.cmd.bytes, 8 );
2952
2953                     vlc_mutex_unlock( &p_sys->lock_demuxer );
2954                     vlc_mutex_lock( &p_ev->lock );
2955                 }
2956                 break;
2957             default:
2958                 break;
2959             }
2960             p_ev->i_key_action = 0;
2961             vlc_mutex_unlock( &p_ev->lock );
2962         }
2963
2964         /* MOUSE part */
2965         if( p_vout && ( p_ev->b_moved || p_ev->b_clicked ) )
2966         {
2967             vlc_value_t valx, valy;
2968
2969             vlc_mutex_lock( &p_ev->lock );
2970             pci_t *pci = (pci_t *) &p_sys->pci_packet;
2971             var_Get( p_vout, "mouse-x", &valx );
2972             var_Get( p_vout, "mouse-y", &valy );
2973
2974             if( p_ev->b_clicked )
2975             {
2976                 int32_t button;
2977                 int32_t best,dist,d;
2978                 int32_t mx,my,dx,dy;
2979
2980                 msg_Dbg( p_ev->p_demux, "Handle Mouse Event: Mouse clicked x(%d)*y(%d)", (unsigned)valx.i_int, (unsigned)valy.i_int);
2981
2982                 b_activated = true;
2983                 // get current button
2984                 best = 0;
2985                 dist = 0x08000000; /* >> than  (720*720)+(567*567); */
2986                 for(button = 1; button <= pci->hli.hl_gi.btn_ns; button++)
2987                 {
2988                     btni_t *button_ptr = &(pci->hli.btnit[button-1]);
2989
2990                     if(((unsigned)valx.i_int >= button_ptr->x_start)
2991                      && ((unsigned)valx.i_int <= button_ptr->x_end)
2992                      && ((unsigned)valy.i_int >= button_ptr->y_start)
2993                      && ((unsigned)valy.i_int <= button_ptr->y_end))
2994                     {
2995                         mx = (button_ptr->x_start + button_ptr->x_end)/2;
2996                         my = (button_ptr->y_start + button_ptr->y_end)/2;
2997                         dx = mx - valx.i_int;
2998                         dy = my - valy.i_int;
2999                         d = (dx*dx) + (dy*dy);
3000                         /* If the mouse is within the button and the mouse is closer
3001                         * to the center of this button then it is the best choice. */
3002                         if(d < dist) {
3003                             dist = d;
3004                             best = button;
3005                         }
3006                     }
3007                 }
3008
3009                 if ( best != 0)
3010                 {
3011                     btni_t button_ptr = pci->hli.btnit[best-1];
3012                     uint16 i_curr_button = p_sys->dvd_interpretor.GetSPRM( 0x88 );
3013
3014                     msg_Dbg( &p_sys->demuxer, "Clicked button %d", best );
3015                     vlc_mutex_unlock( &p_ev->lock );
3016                     vlc_mutex_lock( &p_sys->lock_demuxer );
3017
3018                     // process the button action
3019                     p_sys->dvd_interpretor.SetSPRM( 0x88, best );
3020                     p_sys->dvd_interpretor.Interpret( button_ptr.cmd.bytes, 8 );
3021
3022                     msg_Dbg( &p_sys->demuxer, "Processed button %d", best );
3023
3024                     // select new button
3025                     if ( best != i_curr_button )
3026                     {
3027                         vlc_value_t val;
3028
3029                         if( var_Get( p_sys->p_input, "highlight-mutex", &val ) == VLC_SUCCESS )
3030                         {
3031                             vlc_mutex_t *p_mutex = (vlc_mutex_t *) val.p_address;
3032                             uint32_t i_palette;
3033
3034                             if(button_ptr.btn_coln != 0) {
3035                                 i_palette = pci->hli.btn_colit.btn_coli[button_ptr.btn_coln-1][1];
3036                             } else {
3037                                 i_palette = 0;
3038                             }
3039
3040                             for( int i = 0; i < 4; i++ )
3041                             {
3042                                 uint32_t i_yuv = 0xFF;//p_sys->clut[(hl.palette>>(16+i*4))&0x0f];
3043                                 uint8_t i_alpha = (i_palette>>(i*4))&0x0f;
3044                                 i_alpha = i_alpha == 0xf ? 0xff : i_alpha << 4;
3045
3046                                 p_sys->palette[i][0] = (i_yuv >> 16) & 0xff;
3047                                 p_sys->palette[i][1] = (i_yuv >> 0) & 0xff;
3048                                 p_sys->palette[i][2] = (i_yuv >> 8) & 0xff;
3049                                 p_sys->palette[i][3] = i_alpha;
3050                             }
3051
3052                             vlc_mutex_lock( p_mutex );
3053                             val.i_int = button_ptr.x_start; var_Set( p_sys->p_input, "x-start", val );
3054                             val.i_int = button_ptr.x_end;   var_Set( p_sys->p_input, "x-end",   val );
3055                             val.i_int = button_ptr.y_start; var_Set( p_sys->p_input, "y-start", val );
3056                             val.i_int = button_ptr.y_end;   var_Set( p_sys->p_input, "y-end",   val );
3057
3058                             val.p_address = (void *)p_sys->palette;
3059                             var_Set( p_sys->p_input, "menu-palette", val );
3060
3061                             val.b_bool = true; var_Set( p_sys->p_input, "highlight", val );
3062                             vlc_mutex_unlock( p_mutex );
3063                         }
3064                     }
3065                     vlc_mutex_unlock( &p_sys->lock_demuxer );
3066                     vlc_mutex_lock( &p_ev->lock );
3067                 }
3068             }
3069             else if( p_ev->b_moved )
3070             {
3071 //                dvdnav_mouse_select( NULL, pci, valx.i_int, valy.i_int );
3072             }
3073
3074             p_ev->b_moved = false;
3075             p_ev->b_clicked = false;
3076             vlc_mutex_unlock( &p_ev->lock );
3077         }
3078
3079         /* VOUT part */
3080         if( p_vout && !vlc_object_alive (p_vout) )
3081         {
3082             var_DelCallback( p_vout, "mouse-moved", EventMouse, p_ev );
3083             var_DelCallback( p_vout, "mouse-clicked", EventMouse, p_ev );
3084             vlc_object_release( p_vout );
3085             p_vout = NULL;
3086         }
3087
3088         else if( p_vout == NULL )
3089         {
3090             p_vout = (vlc_object_t*) vlc_object_find( p_sys->p_input, VLC_OBJECT_VOUT,
3091                                       FIND_CHILD );
3092             if( p_vout)
3093             {
3094                 var_AddCallback( p_vout, "mouse-moved", EventMouse, p_ev );
3095                 var_AddCallback( p_vout, "mouse-clicked", EventMouse, p_ev );
3096             }
3097         }
3098
3099         /* Wait a bit, 10ms */
3100         msleep( 10000 );
3101     }
3102
3103     /* Release callback */
3104     if( p_vout )
3105     {
3106         var_DelCallback( p_vout, "mouse-moved", EventMouse, p_ev );
3107         var_DelCallback( p_vout, "mouse-clicked", EventMouse, p_ev );
3108         vlc_object_release( p_vout );
3109     }
3110     var_DelCallback( p_ev->p_libvlc, "key-action", EventKey, p_ev );
3111
3112     vlc_mutex_destroy( &p_ev->lock );
3113
3114     return VLC_SUCCESS;
3115 }
3116
3117 void matroska_segment_c::UnSelect( )
3118 {
3119     size_t i_track;
3120
3121     for( i_track = 0; i_track < tracks.size(); i_track++ )
3122     {
3123         if ( tracks[i_track]->p_es != NULL )
3124         {
3125 //            es_format_Clean( &tracks[i_track]->fmt );
3126             es_out_Del( sys.demuxer.out, tracks[i_track]->p_es );
3127             tracks[i_track]->p_es = NULL;
3128         }
3129     }
3130     delete ep;
3131     ep = NULL;
3132 }
3133
3134 void virtual_segment_c::PrepareChapters( )
3135 {
3136     if ( linked_segments.size() == 0 )
3137         return;
3138
3139     // !!! should be called only once !!!
3140     matroska_segment_c *p_segment;
3141     size_t i, j;
3142
3143     // copy editions from the first segment
3144     p_segment = linked_segments[0];
3145     p_editions = &p_segment->stored_editions;
3146
3147     for ( i=1 ; i<linked_segments.size(); i++ )
3148     {
3149         p_segment = linked_segments[i];
3150         // FIXME assume we have the same editions in all segments
3151         for (j=0; j<p_segment->stored_editions.size(); j++)
3152         {
3153             if( j >= p_editions->size() ) /* Protect against broken files (?) */
3154                 break;
3155             (*p_editions)[j]->Append( *p_segment->stored_editions[j] );
3156         }
3157     }
3158 }
3159
3160 std::string chapter_edition_c::GetMainName() const
3161 {
3162     if ( sub_chapters.size() )
3163     {
3164         return sub_chapters[0]->GetCodecName( true );
3165     }
3166     return "";
3167 }
3168
3169 int chapter_item_c::PublishChapters( input_title_t & title, int & i_user_chapters, int i_level )
3170 {
3171     // add support for meta-elements from codec like DVD Titles
3172     if ( !b_display_seekpoint || psz_name == "" )
3173     {
3174         psz_name = GetCodecName();
3175         if ( psz_name != "" )
3176             b_display_seekpoint = true;
3177     }
3178
3179     if (b_display_seekpoint)
3180     {
3181         seekpoint_t *sk = vlc_seekpoint_New();
3182
3183         sk->i_level = i_level;
3184         sk->i_time_offset = i_start_time;
3185         sk->psz_name = strdup( psz_name.c_str() );
3186
3187         // A start time of '0' is ok. A missing ChapterTime element is ok, too, because '0' is its default value.
3188         title.i_seekpoint++;
3189         title.seekpoint = (seekpoint_t**)realloc( title.seekpoint, title.i_seekpoint * sizeof( seekpoint_t* ) );
3190         title.seekpoint[title.i_seekpoint-1] = sk;
3191
3192         if ( b_user_display )
3193             i_user_chapters++;
3194     }
3195
3196     for ( size_t i=0; i<sub_chapters.size() ; i++)
3197     {
3198         sub_chapters[i]->PublishChapters( title, i_user_chapters, i_level+1 );
3199     }
3200
3201     i_seekpoint_num = i_user_chapters;
3202
3203     return i_user_chapters;
3204 }
3205
3206 bool virtual_segment_c::UpdateCurrentToChapter( demux_t & demux )
3207 {
3208     demux_sys_t & sys = *demux.p_sys;
3209     chapter_item_c *psz_curr_chapter;
3210     bool b_has_seeked = false;
3211
3212     /* update current chapter/seekpoint */
3213     if ( p_editions->size() )
3214     {
3215         /* 1st, we need to know in which chapter we are */
3216         psz_curr_chapter = (*p_editions)[i_current_edition]->FindTimecode( sys.i_pts, psz_current_chapter );
3217
3218         /* we have moved to a new chapter */
3219         if (psz_curr_chapter != NULL && psz_current_chapter != psz_curr_chapter)
3220         {
3221             if ( (*p_editions)[i_current_edition]->b_ordered )
3222             {
3223                 // Leave/Enter up to the link point
3224                 b_has_seeked = psz_curr_chapter->EnterAndLeave( psz_current_chapter );
3225                 if ( !b_has_seeked )
3226                 {
3227                     // only physically seek if necessary
3228                     if ( psz_current_chapter == NULL || (psz_current_chapter->i_end_time != psz_curr_chapter->i_start_time) )
3229                         Seek( demux, sys.i_pts, 0, psz_curr_chapter, -1 );
3230                 }
3231             }
3232  
3233             if ( !b_has_seeked )
3234             {
3235                 psz_current_chapter = psz_curr_chapter;
3236                 if ( psz_curr_chapter->i_seekpoint_num > 0 )
3237                 {
3238                     demux.info.i_update |= INPUT_UPDATE_TITLE | INPUT_UPDATE_SEEKPOINT;
3239                     demux.info.i_title = sys.i_current_title = i_sys_title;
3240                     demux.info.i_seekpoint = psz_curr_chapter->i_seekpoint_num - 1;
3241                 }
3242             }
3243
3244             return true;
3245         }
3246         else if (psz_curr_chapter == NULL)
3247         {
3248             // out of the scope of the data described by chapters, leave the edition
3249             if ( (*p_editions)[i_current_edition]->b_ordered && psz_current_chapter != NULL )
3250             {
3251                 if ( !(*p_editions)[i_current_edition]->EnterAndLeave( psz_current_chapter, false ) )
3252                     psz_current_chapter = NULL;
3253                 else
3254                     return true;
3255             }
3256         }
3257     }
3258     return false;
3259 }
3260
3261 chapter_item_c *virtual_segment_c::BrowseCodecPrivate( unsigned int codec_id,
3262                                     bool (*match)(const chapter_codec_cmds_c &data, const void *p_cookie, size_t i_cookie_size ),
3263                                     const void *p_cookie,
3264                                     size_t i_cookie_size )
3265 {
3266     // FIXME don't assume it is the first edition
3267     std::vector<chapter_edition_c*>::iterator index = p_editions->begin();
3268     if ( index != p_editions->end() )
3269     {
3270         chapter_item_c *p_result = (*index)->BrowseCodecPrivate( codec_id, match, p_cookie, i_cookie_size );
3271         if ( p_result != NULL )
3272             return p_result;
3273     }
3274     return NULL;
3275 }
3276
3277 chapter_item_c *virtual_segment_c::FindChapter( int64_t i_find_uid )
3278 {
3279     // FIXME don't assume it is the first edition
3280     std::vector<chapter_edition_c*>::iterator index = p_editions->begin();
3281     if ( index != p_editions->end() )
3282     {
3283         chapter_item_c *p_result = (*index)->FindChapter( i_find_uid );
3284         if ( p_result != NULL )
3285             return p_result;
3286     }
3287     return NULL;
3288 }
3289
3290 chapter_item_c *chapter_item_c::BrowseCodecPrivate( unsigned int codec_id,
3291                                     bool (*match)(const chapter_codec_cmds_c &data, const void *p_cookie, size_t i_cookie_size ),
3292                                     const void *p_cookie,
3293                                     size_t i_cookie_size )
3294 {
3295     // this chapter
3296     std::vector<chapter_codec_cmds_c*>::const_iterator index = codecs.begin();
3297     while ( index != codecs.end() )
3298     {
3299         if ( match( **index ,p_cookie, i_cookie_size ) )
3300             return this;
3301         index++;
3302     }
3303  
3304     // sub-chapters
3305     chapter_item_c *p_result = NULL;
3306     std::vector<chapter_item_c*>::const_iterator index2 = sub_chapters.begin();
3307     while ( index2 != sub_chapters.end() )
3308     {
3309         p_result = (*index2)->BrowseCodecPrivate( codec_id, match, p_cookie, i_cookie_size );
3310         if ( p_result != NULL )
3311             return p_result;
3312         index2++;
3313     }
3314  
3315     return p_result;
3316 }
3317
3318 void chapter_item_c::Append( const chapter_item_c & chapter )
3319 {
3320     // we are appending content for the same chapter UID
3321     size_t i;
3322     chapter_item_c *p_chapter;
3323
3324     for ( i=0; i<chapter.sub_chapters.size(); i++ )
3325     {
3326         p_chapter = FindChapter( chapter.sub_chapters[i]->i_uid );
3327         if ( p_chapter != NULL )
3328         {
3329             p_chapter->Append( *chapter.sub_chapters[i] );
3330         }
3331         else
3332         {
3333             sub_chapters.push_back( chapter.sub_chapters[i] );
3334         }
3335     }
3336
3337     i_user_start_time = min( i_user_start_time, chapter.i_user_start_time );
3338     i_user_end_time = max( i_user_end_time, chapter.i_user_end_time );
3339 }
3340
3341 chapter_item_c * chapter_item_c::FindChapter( int64_t i_find_uid )
3342 {
3343     size_t i;
3344     chapter_item_c *p_result = NULL;
3345
3346     if ( i_uid == i_find_uid )
3347         return this;
3348
3349     for ( i=0; i<sub_chapters.size(); i++)
3350     {
3351         p_result = sub_chapters[i]->FindChapter( i_find_uid );
3352         if ( p_result != NULL )
3353             break;
3354     }
3355     return p_result;
3356 }
3357
3358 std::string chapter_item_c::GetCodecName( bool f_for_title ) const
3359 {
3360     std::string result;
3361
3362     std::vector<chapter_codec_cmds_c*>::const_iterator index = codecs.begin();
3363     while ( index != codecs.end() )
3364     {
3365         result = (*index)->GetCodecName( f_for_title );
3366         if ( result != "" )
3367             break;
3368         index++;
3369     }
3370
3371     return result;
3372 }
3373
3374 std::string dvd_chapter_codec_c::GetCodecName( bool f_for_title ) const
3375 {
3376     std::string result;
3377     if ( p_private_data->GetSize() >= 3)
3378     {
3379         const binary* p_data = p_private_data->GetBuffer();
3380 /*        if ( p_data[0] == MATROSKA_DVD_LEVEL_TT )
3381         {
3382             uint16_t i_title = (p_data[1] << 8) + p_data[2];
3383             char psz_str[11];
3384             sprintf( psz_str, " %d  ---", i_title );
3385             result = N_("---  DVD Title");
3386             result += psz_str;
3387         }
3388         else */ if ( p_data[0] == MATROSKA_DVD_LEVEL_LU )
3389         {
3390             char psz_str[11];
3391             sprintf( psz_str, " (%c%c)  ---", p_data[1], p_data[2] );
3392             result = N_("---  DVD Menu");
3393             result += psz_str;
3394         }
3395         else if ( p_data[0] == MATROSKA_DVD_LEVEL_SS && f_for_title )
3396         {
3397             if ( p_data[1] == 0x00 )
3398                 result = N_("First Played");
3399             else if ( p_data[1] == 0xC0 )
3400                 result = N_("Video Manager");
3401             else if ( p_data[1] == 0x80 )
3402             {
3403                 uint16_t i_title = (p_data[2] << 8) + p_data[3];
3404                 char psz_str[20];
3405                 sprintf( psz_str, " %d -----", i_title );
3406                 result = N_("----- Title");
3407                 result += psz_str;
3408             }
3409         }
3410     }
3411
3412     return result;
3413 }
3414
3415 int16 chapter_item_c::GetTitleNumber( ) const
3416 {
3417     int result = -1;
3418
3419     std::vector<chapter_codec_cmds_c*>::const_iterator index = codecs.begin();
3420     while ( index != codecs.end() )
3421     {
3422         result = (*index)->GetTitleNumber( );
3423         if ( result >= 0 )
3424             break;
3425         index++;
3426     }
3427
3428     return result;
3429 }
3430
3431 int16 dvd_chapter_codec_c::GetTitleNumber()
3432 {
3433     if ( p_private_data->GetSize() >= 3)
3434     {
3435         const binary* p_data = p_private_data->GetBuffer();
3436         if ( p_data[0] == MATROSKA_DVD_LEVEL_SS )
3437         {
3438             return int16( (p_data[2] << 8) + p_data[3] );
3439         }
3440     }
3441     return -1;
3442 }
3443
3444 static void Seek( demux_t *p_demux, mtime_t i_date, double f_percent, chapter_item_c *psz_chapter )
3445 {
3446     demux_sys_t        *p_sys = p_demux->p_sys;
3447     virtual_segment_c  *p_vsegment = p_sys->p_current_segment;
3448     matroska_segment_c *p_segment = p_vsegment->Segment();
3449     mtime_t            i_time_offset = 0;
3450     int64_t            i_global_position = -1;
3451
3452     int         i_index;
3453
3454     msg_Dbg( p_demux, "seek request to %"PRId64" (%f%%)", i_date, f_percent );
3455     if( i_date < 0 && f_percent < 0 )
3456     {
3457         msg_Warn( p_demux, "cannot seek nowhere !" );
3458         return;
3459     }
3460     if( f_percent > 1.0 )
3461     {
3462         msg_Warn( p_demux, "cannot seek so far !" );
3463         return;
3464     }
3465
3466     /* seek without index or without date */
3467     if( f_percent >= 0 && (config_GetInt( p_demux, "mkv-seek-percent" ) || !p_segment->b_cues || i_date < 0 ))
3468     {
3469         if( p_sys->f_duration >= 0 && p_segment->b_cues )
3470         {
3471             i_date = int64_t( f_percent * p_sys->f_duration * 1000.0 );
3472         }
3473         else
3474         {
3475             int64_t i_pos = int64_t( f_percent * stream_Size( p_demux->s ) );
3476
3477             msg_Dbg( p_demux, "inaccurate way of seeking for pos:%"PRId64, i_pos );
3478             for( i_index = 0; i_index < p_segment->i_index; i_index++ )
3479             {
3480                 if( p_segment->b_cues && p_segment->p_indexes[i_index].i_position < i_pos )
3481                     break;
3482                 if( !p_segment->b_cues && p_segment->p_indexes[i_index].i_position >= i_pos && p_segment->p_indexes[i_index].i_time > 0 )
3483                     break;
3484             }
3485             if( i_index == p_segment->i_index )
3486             {
3487                 i_index--;
3488             }
3489
3490             i_date = p_segment->p_indexes[i_index].i_time;
3491
3492             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 ))
3493             {
3494                 msg_Dbg( p_demux, "no cues, seek request to global pos: %"PRId64, i_pos );
3495                 i_global_position = i_pos;
3496             }
3497         }
3498     }
3499
3500     p_vsegment->Seek( *p_demux, i_date, i_time_offset, psz_chapter, i_global_position );
3501 }
3502
3503 /*****************************************************************************
3504  * Demux: reads and demuxes data packets
3505  *****************************************************************************
3506  * Returns -1 in case of error, 0 in case of EOF, 1 otherwise
3507  *****************************************************************************/
3508 static int Demux( demux_t *p_demux)
3509 {
3510     demux_sys_t        *p_sys = p_demux->p_sys;
3511
3512     vlc_mutex_lock( &p_sys->lock_demuxer );
3513
3514     virtual_segment_c  *p_vsegment = p_sys->p_current_segment;
3515     matroska_segment_c *p_segment = p_vsegment->Segment();
3516     if ( p_segment == NULL ) return 0;
3517     int                i_block_count = 0;
3518     int                i_return = 0;
3519
3520     for( ;; )
3521     {
3522         if ( p_sys->demuxer.b_die )
3523             break;
3524
3525         if( p_sys->i_pts >= p_sys->i_start_pts  )
3526             if ( p_vsegment->UpdateCurrentToChapter( *p_demux ) )
3527             {
3528                 i_return = 1;
3529                 break;
3530             }
3531  
3532         if ( p_vsegment->Edition() && p_vsegment->Edition()->b_ordered && p_vsegment->CurrentChapter() == NULL )
3533         {
3534             /* nothing left to read in this ordered edition */
3535             if ( !p_vsegment->SelectNext() )
3536                 break;
3537             p_segment->UnSelect( );
3538  
3539             es_out_Control( p_demux->out, ES_OUT_RESET_PCR );
3540
3541             /* switch to the next segment */
3542             p_segment = p_vsegment->Segment();
3543             if ( !p_segment->Select( 0 ) )
3544             {
3545                 msg_Err( p_demux, "Failed to select new segment" );
3546                 break;
3547             }
3548             continue;
3549         }
3550
3551         KaxBlock *block;
3552         int64_t i_block_duration = 0;
3553         int64_t i_block_ref1;
3554         int64_t i_block_ref2;
3555
3556 #if LIBMATROSKA_VERSION >= 0x000800
3557         KaxSimpleBlock *simpleblock;
3558
3559         if( p_segment->BlockGet( block, simpleblock, &i_block_ref1, &i_block_ref2, &i_block_duration ) )
3560 #else
3561         if( p_segment->BlockGet( block, &i_block_ref1, &i_block_ref2, &i_block_duration ) )
3562 #endif
3563         {
3564             if ( p_vsegment->Edition() && p_vsegment->Edition()->b_ordered )
3565             {
3566                 const chapter_item_c *p_chap = p_vsegment->CurrentChapter();
3567                 // check if there are more chapters to read
3568                 if ( p_chap != NULL )
3569                 {
3570                     /* TODO handle successive chapters with the same user_start_time/user_end_time
3571                     if ( p_chap->i_user_start_time == p_chap->i_user_start_time )
3572                         p_vsegment->SelectNext();
3573                     */
3574                     p_sys->i_pts = p_chap->i_user_end_time;
3575                     p_sys->i_pts++; // trick to avoid staying on segments with no duration and no content
3576
3577                     i_return = 1;
3578                 }
3579
3580                 break;
3581             }
3582             else
3583             {
3584                 msg_Warn( p_demux, "cannot get block EOF?" );
3585                 p_segment->UnSelect( );
3586  
3587                 es_out_Control( p_demux->out, ES_OUT_RESET_PCR );
3588
3589                 /* switch to the next segment */
3590                 if ( !p_vsegment->SelectNext() )
3591                     // no more segments in this stream
3592                     break;
3593                 p_segment = p_vsegment->Segment();
3594                 if ( !p_segment->Select( 0 ) )
3595                 {
3596                     msg_Err( p_demux, "Failed to select new segment" );
3597                     break;
3598                 }
3599
3600                 continue;
3601             }
3602         }
3603
3604 #if LIBMATROSKA_VERSION >= 0x000800
3605         if ( simpleblock != NULL )
3606             p_sys->i_pts = (p_sys->i_chapter_time + simpleblock->GlobalTimecode()) / (mtime_t) 1000;
3607         else
3608 #endif
3609         p_sys->i_pts = (p_sys->i_chapter_time + block->GlobalTimecode()) / (mtime_t) 1000;
3610
3611         if( p_sys->i_pts >= p_sys->i_start_pts  )
3612         {
3613             es_out_Control( p_demux->out, ES_OUT_SET_PCR, p_sys->i_pts );
3614
3615             if ( p_vsegment->UpdateCurrentToChapter( *p_demux ) )
3616             {
3617                 i_return = 1;
3618                 delete block;
3619                 break;
3620             }
3621         }
3622  
3623         if ( p_vsegment->Edition() && p_vsegment->Edition()->b_ordered && p_vsegment->CurrentChapter() == NULL )
3624         {
3625             /* nothing left to read in this ordered edition */
3626             if ( !p_vsegment->SelectNext() )
3627             {
3628                 delete block;
3629                 break;
3630             }
3631             p_segment->UnSelect( );
3632  
3633             es_out_Control( p_demux->out, ES_OUT_RESET_PCR );
3634
3635             /* switch to the next segment */
3636             p_segment = p_vsegment->Segment();
3637             if ( !p_segment->Select( 0 ) )
3638             {
3639                 msg_Err( p_demux, "Failed to select new segment" );
3640                 delete block;
3641                 break;
3642             }
3643             delete block;
3644             continue;
3645         }
3646
3647 #if LIBMATROSKA_VERSION >= 0x000800
3648         BlockDecode( p_demux, block, simpleblock, p_sys->i_pts, i_block_duration, i_block_ref1 >= 0 || i_block_ref2 > 0 );
3649 #else
3650         BlockDecode( p_demux, block, p_sys->i_pts, i_block_duration, i_block_ref1 >= 0 || i_block_ref2 > 0 );
3651 #endif
3652
3653         delete block;
3654         i_block_count++;
3655
3656         // TODO optimize when there is need to leave or when seeking has been called
3657         if( i_block_count > 5 )
3658         {
3659             i_return = 1;
3660             break;
3661         }
3662     }
3663
3664     vlc_mutex_unlock( &p_sys->lock_demuxer );
3665
3666     return i_return;
3667 }
3668
3669
3670
3671 /*****************************************************************************
3672  * Stream managment
3673  *****************************************************************************/
3674 vlc_stream_io_callback::vlc_stream_io_callback( stream_t *s_, bool b_owner_ )
3675 {
3676     s = s_;
3677     b_owner = b_owner_;
3678     mb_eof = false;
3679 }
3680
3681 uint32 vlc_stream_io_callback::read( void *p_buffer, size_t i_size )
3682 {
3683     if( i_size <= 0 || mb_eof )
3684     {
3685         return 0;
3686     }
3687
3688     return stream_Read( s, p_buffer, i_size );
3689 }
3690 void vlc_stream_io_callback::setFilePointer(int64_t i_offset, seek_mode mode )
3691 {
3692     int64_t i_pos;
3693
3694     switch( mode )
3695     {
3696         case seek_beginning:
3697             i_pos = i_offset;
3698             break;
3699         case seek_end:
3700             i_pos = stream_Size( s ) - i_offset;
3701             break;
3702         default:
3703             i_pos= stream_Tell( s ) + i_offset;
3704             break;
3705     }
3706
3707     if( i_pos < 0 || i_pos >= stream_Size( s ) )
3708     {
3709         mb_eof = true;
3710         return;
3711     }
3712
3713     mb_eof = false;
3714     if( stream_Seek( s, i_pos ) )
3715     {
3716         mb_eof = true;
3717     }
3718     return;
3719 }
3720 size_t vlc_stream_io_callback::write( const void *p_buffer, size_t i_size )
3721 {
3722     return 0;
3723 }
3724 uint64 vlc_stream_io_callback::getFilePointer( void )
3725 {
3726     if ( s == NULL )
3727         return 0;
3728     return stream_Tell( s );
3729 }
3730 void vlc_stream_io_callback::close( void )
3731 {
3732     return;
3733 }
3734
3735
3736 /*****************************************************************************
3737  * Ebml Stream parser
3738  *****************************************************************************/
3739 EbmlParser::EbmlParser( EbmlStream *es, EbmlElement *el_start, demux_t *p_demux )
3740 {
3741     int i;
3742
3743     m_es = es;
3744     m_got = NULL;
3745     m_el[0] = el_start;
3746     mi_remain_size[0] = el_start->GetSize();
3747
3748     for( i = 1; i < 6; i++ )
3749     {
3750         m_el[i] = NULL;
3751     }
3752     mi_level = 1;
3753     mi_user_level = 1;
3754     mb_keep = false;
3755     mb_dummy = config_GetInt( p_demux, "mkv-use-dummy" );
3756 }
3757
3758 EbmlParser::~EbmlParser( void )
3759 {
3760     int i;
3761
3762     for( i = 1; i < mi_level; i++ )
3763     {
3764         if( !mb_keep )
3765         {
3766             delete m_el[i];
3767         }
3768         mb_keep = false;
3769     }
3770 }
3771
3772 EbmlElement* EbmlParser::UnGet( uint64 i_block_pos, uint64 i_cluster_pos )
3773 {
3774     if ( mi_user_level > mi_level )
3775     {
3776         while ( mi_user_level != mi_level )
3777         {
3778             delete m_el[mi_user_level];
3779             m_el[mi_user_level] = NULL;
3780             mi_user_level--;
3781         }
3782     }
3783     m_got = NULL;
3784     mb_keep = false;
3785     if ( m_el[1]->GetElementPosition() == i_cluster_pos )
3786     {
3787         m_es->I_O().setFilePointer( i_block_pos, seek_beginning );
3788         return (EbmlMaster*) m_el[1];
3789     }
3790     else
3791     {
3792         // seek to the previous Cluster
3793         m_es->I_O().setFilePointer( i_cluster_pos, seek_beginning );
3794         mi_level--;
3795         mi_user_level--;
3796         delete m_el[mi_level];
3797         m_el[mi_level] = NULL;
3798         return NULL;
3799     }
3800 }
3801
3802 void EbmlParser::Up( void )
3803 {
3804     if( mi_user_level == mi_level )
3805     {
3806         fprintf( stderr," arrrrrrrrrrrrrg Up cannot escape itself\n" );
3807     }
3808
3809     mi_user_level--;
3810 }
3811
3812 void EbmlParser::Down( void )
3813 {
3814     mi_user_level++;
3815     mi_level++;
3816 }
3817
3818 void EbmlParser::Keep( void )
3819 {
3820     mb_keep = true;
3821 }
3822
3823 int EbmlParser::GetLevel( void )
3824 {
3825     return mi_user_level;
3826 }
3827
3828 void EbmlParser::Reset( demux_t *p_demux )
3829 {
3830     while ( mi_level > 0)
3831     {
3832         delete m_el[mi_level];
3833         m_el[mi_level] = NULL;
3834         mi_level--;
3835     }
3836     mi_user_level = mi_level = 1;
3837 #if LIBEBML_VERSION >= 0x000704
3838     // a little faster and cleaner
3839     m_es->I_O().setFilePointer( static_cast<KaxSegment*>(m_el[0])->GetGlobalPosition(0) );
3840 #else
3841     m_es->I_O().setFilePointer( m_el[0]->GetElementPosition() + m_el[0]->ElementSize(true) - m_el[0]->GetSize() );
3842 #endif
3843     mb_dummy = config_GetInt( p_demux, "mkv-use-dummy" );
3844 }
3845
3846 EbmlElement *EbmlParser::Get( void )
3847 {
3848     int i_ulev = 0;
3849
3850     if( mi_user_level != mi_level )
3851     {
3852         return NULL;
3853     }
3854     if( m_got )
3855     {
3856         EbmlElement *ret = m_got;
3857         m_got = NULL;
3858
3859         return ret;
3860     }
3861
3862     if( m_el[mi_level] )
3863     {
3864         m_el[mi_level]->SkipData( *m_es, m_el[mi_level]->Generic().Context );
3865         if( !mb_keep )
3866         {
3867             delete m_el[mi_level];
3868         }
3869         mb_keep = false;
3870     }
3871
3872     m_el[mi_level] = m_es->FindNextElement( m_el[mi_level - 1]->Generic().Context, i_ulev, 0xFFFFFFFFL, mb_dummy != 0, 1 );
3873 //    mi_remain_size[mi_level] = m_el[mi_level]->GetSize();
3874     if( i_ulev > 0 )
3875     {
3876         while( i_ulev > 0 )
3877         {
3878             if( mi_level == 1 )
3879             {
3880                 mi_level = 0;
3881                 return NULL;
3882             }
3883
3884             delete m_el[mi_level - 1];
3885             m_got = m_el[mi_level -1] = m_el[mi_level];
3886             m_el[mi_level] = NULL;
3887
3888             mi_level--;
3889             i_ulev--;
3890         }
3891         return NULL;
3892     }
3893     else if( m_el[mi_level] == NULL )
3894     {
3895         fprintf( stderr," m_el[mi_level] == NULL\n" );
3896     }
3897
3898     return m_el[mi_level];
3899 }
3900
3901 bool EbmlParser::IsTopPresent( EbmlElement *el )
3902 {
3903     for( int i = 0; i < mi_level; i++ )
3904     {
3905         if( m_el[i] && m_el[i] == el )
3906             return true;
3907     }
3908     return false;
3909 }
3910
3911 /*****************************************************************************
3912  * Tools
3913  *  * LoadCues : load the cues element and update index
3914  *
3915  *  * LoadTags : load ... the tags element
3916  *
3917  *  * InformationCreate : create all information, load tags if present
3918  *
3919  *****************************************************************************/
3920 void matroska_segment_c::LoadCues( KaxCues *cues )
3921 {
3922     EbmlParser  *ep;
3923     EbmlElement *el;
3924     size_t i, j;
3925
3926     if( b_cues )
3927     {
3928         msg_Err( &sys.demuxer, "There can be only 1 Cues per section." );
3929         return;
3930     }
3931
3932     ep = new EbmlParser( &es, cues, &sys.demuxer );
3933     while( ( el = ep->Get() ) != NULL )
3934     {
3935         if( MKV_IS_ID( el, KaxCuePoint ) )
3936         {
3937 #define idx p_indexes[i_index]
3938
3939             idx.i_track       = -1;
3940             idx.i_block_number= -1;
3941             idx.i_position    = -1;
3942             idx.i_time        = 0;
3943             idx.b_key         = true;
3944
3945             ep->Down();
3946             while( ( el = ep->Get() ) != NULL )
3947             {
3948                 if( MKV_IS_ID( el, KaxCueTime ) )
3949                 {
3950                     KaxCueTime &ctime = *(KaxCueTime*)el;
3951
3952                     ctime.ReadData( es.I_O() );
3953
3954                     idx.i_time = uint64( ctime ) * i_timescale / (mtime_t)1000;
3955                 }
3956                 else if( MKV_IS_ID( el, KaxCueTrackPositions ) )
3957                 {
3958                     ep->Down();
3959                     while( ( el = ep->Get() ) != NULL )
3960                     {
3961                         if( MKV_IS_ID( el, KaxCueTrack ) )
3962                         {
3963                             KaxCueTrack &ctrack = *(KaxCueTrack*)el;
3964
3965                             ctrack.ReadData( es.I_O() );
3966                             idx.i_track = uint16( ctrack );
3967                         }
3968                         else if( MKV_IS_ID( el, KaxCueClusterPosition ) )
3969                         {
3970                             KaxCueClusterPosition &ccpos = *(KaxCueClusterPosition*)el;
3971
3972                             ccpos.ReadData( es.I_O() );
3973                             idx.i_position = segment->GetGlobalPosition( uint64( ccpos ) );
3974                         }
3975                         else if( MKV_IS_ID( el, KaxCueBlockNumber ) )
3976                         {
3977                             KaxCueBlockNumber &cbnum = *(KaxCueBlockNumber*)el;
3978
3979                             cbnum.ReadData( es.I_O() );
3980                             idx.i_block_number = uint32( cbnum );
3981                         }
3982                         else
3983                         {
3984                             msg_Dbg( &sys.demuxer, "         * Unknown (%s)", typeid(*el).name() );
3985                         }
3986                     }
3987                     ep->Up();
3988                 }
3989                 else
3990                 {
3991                     msg_Dbg( &sys.demuxer, "     * Unknown (%s)", typeid(*el).name() );
3992                 }
3993             }
3994             ep->Up();
3995
3996 #if 0
3997             msg_Dbg( &sys.demuxer, " * added time=%"PRId64" pos=%"PRId64
3998                      " track=%d bnum=%d", idx.i_time, idx.i_position,
3999                      idx.i_track, idx.i_block_number );
4000 #endif
4001
4002             i_index++;
4003             if( i_index >= i_index_max )
4004             {
4005                 i_index_max += 1024;
4006                 p_indexes = (mkv_index_t*)realloc( p_indexes, sizeof( mkv_index_t ) * i_index_max );
4007             }
4008 #undef idx
4009         }
4010         else
4011         {
4012             msg_Dbg( &sys.demuxer, " * Unknown (%s)", typeid(*el).name() );
4013         }
4014     }
4015     delete ep;
4016     b_cues = true;
4017     msg_Dbg( &sys.demuxer, "|   - loading cues done." );
4018 }
4019
4020 void matroska_segment_c::LoadTags( KaxTags *tags )
4021 {
4022     EbmlParser  *ep;
4023     EbmlElement *el;
4024     size_t i, j;
4025
4026     /* Master elements */
4027     ep = new EbmlParser( &es, tags, &sys.demuxer );
4028
4029     while( ( el = ep->Get() ) != NULL )
4030     {
4031         if( MKV_IS_ID( el, KaxTag ) )
4032         {
4033             msg_Dbg( &sys.demuxer, "+ Tag" );
4034             ep->Down();
4035             while( ( el = ep->Get() ) != NULL )
4036             {
4037                 if( MKV_IS_ID( el, KaxTagTargets ) )
4038                 {
4039                     msg_Dbg( &sys.demuxer, "|   + Targets" );
4040                     ep->Down();
4041                     while( ( el = ep->Get() ) != NULL )
4042                     {
4043                         msg_Dbg( &sys.demuxer, "|   |   + Unknown (%s)", typeid( *el ).name() );
4044                     }
4045                     ep->Up();
4046                 }
4047                 else if( MKV_IS_ID( el, KaxTagGeneral ) )
4048                 {
4049                     msg_Dbg( &sys.demuxer, "|   + General" );
4050                     ep->Down();
4051                     while( ( el = ep->Get() ) != NULL )
4052                     {
4053                         msg_Dbg( &sys.demuxer, "|   |   + Unknown (%s)", typeid( *el ).name() );
4054                     }
4055                     ep->Up();
4056                 }
4057                 else if( MKV_IS_ID( el, KaxTagGenres ) )
4058                 {
4059                     msg_Dbg( &sys.demuxer, "|   + Genres" );
4060                     ep->Down();
4061                     while( ( el = ep->Get() ) != NULL )
4062                     {
4063                         msg_Dbg( &sys.demuxer, "|   |   + Unknown (%s)", typeid( *el ).name() );
4064                     }
4065                     ep->Up();
4066                 }
4067                 else if( MKV_IS_ID( el, KaxTagAudioSpecific ) )
4068                 {
4069                     msg_Dbg( &sys.demuxer, "|   + Audio Specific" );
4070                     ep->Down();
4071                     while( ( el = ep->Get() ) != NULL )
4072                     {
4073                         msg_Dbg( &sys.demuxer, "|   |   + Unknown (%s)", typeid( *el ).name() );
4074                     }
4075                     ep->Up();
4076                 }
4077                 else if( MKV_IS_ID( el, KaxTagImageSpecific ) )
4078                 {
4079                     msg_Dbg( &sys.demuxer, "|   + Images Specific" );
4080                     ep->Down();
4081                     while( ( el = ep->Get() ) != NULL )
4082                     {
4083                         msg_Dbg( &sys.demuxer, "|   |   + Unknown (%s)", typeid( *el ).name() );
4084                     }
4085                     ep->Up();
4086                 }
4087                 else if( MKV_IS_ID( el, KaxTagMultiComment ) )
4088                 {
4089                     msg_Dbg( &sys.demuxer, "|   + Multi Comment" );
4090                 }
4091                 else if( MKV_IS_ID( el, KaxTagMultiCommercial ) )
4092                 {
4093                     msg_Dbg( &sys.demuxer, "|   + Multi Commercial" );
4094                 }
4095                 else if( MKV_IS_ID( el, KaxTagMultiDate ) )
4096                 {
4097                     msg_Dbg( &sys.demuxer, "|   + Multi Date" );
4098                 }
4099                 else if( MKV_IS_ID( el, KaxTagMultiEntity ) )
4100                 {
4101                     msg_Dbg( &sys.demuxer, "|   + Multi Entity" );
4102                 }
4103                 else if( MKV_IS_ID( el, KaxTagMultiIdentifier ) )
4104                 {
4105                     msg_Dbg( &sys.demuxer, "|   + Multi Identifier" );
4106                 }
4107                 else if( MKV_IS_ID( el, KaxTagMultiLegal ) )
4108                 {
4109                     msg_Dbg( &sys.demuxer, "|   + Multi Legal" );
4110                 }
4111                 else if( MKV_IS_ID( el, KaxTagMultiTitle ) )
4112                 {
4113                     msg_Dbg( &sys.demuxer, "|   + Multi Title" );
4114                 }
4115                 else
4116                 {
4117                     msg_Dbg( &sys.demuxer, "|   + LoadTag Unknown (%s)", typeid( *el ).name() );
4118                 }
4119             }
4120             ep->Up();
4121         }
4122         else
4123         {
4124             msg_Dbg( &sys.demuxer, "+ Unknown (%s)", typeid( *el ).name() );
4125         }
4126     }
4127     delete ep;
4128
4129     msg_Dbg( &sys.demuxer, "loading tags done." );
4130 }
4131
4132 /*****************************************************************************
4133  * ParseSeekHead:
4134  *****************************************************************************/
4135 void matroska_segment_c::ParseSeekHead( KaxSeekHead *seekhead )
4136 {
4137     EbmlParser  *ep;
4138     EbmlElement *l;
4139     size_t i, j;
4140     int i_upper_level = 0;
4141     bool b_seekable;
4142
4143     i_seekhead_count++;
4144
4145     stream_Control( sys.demuxer.s, STREAM_CAN_SEEK, &b_seekable );
4146     if( !b_seekable )
4147         return;
4148
4149     ep = new EbmlParser( &es, seekhead, &sys.demuxer );
4150
4151     while( ( l = ep->Get() ) != NULL )
4152     {
4153         if( MKV_IS_ID( l, KaxSeek ) )
4154         {
4155             EbmlId id = EbmlVoid::ClassInfos.GlobalId;
4156             int64_t i_pos = -1;
4157
4158             msg_Dbg( &sys.demuxer, "|   |   + Seek" );
4159             ep->Down();
4160             while( ( l = ep->Get() ) != NULL )
4161             {
4162                 if( MKV_IS_ID( l, KaxSeekID ) )
4163                 {
4164                     KaxSeekID &sid = *(KaxSeekID*)l;
4165                     sid.ReadData( es.I_O() );
4166                     id = EbmlId( sid.GetBuffer(), sid.GetSize() );
4167                 }
4168                 else if( MKV_IS_ID( l, KaxSeekPosition ) )
4169                 {
4170                     KaxSeekPosition &spos = *(KaxSeekPosition*)l;
4171                     spos.ReadData( es.I_O() );
4172                     i_pos = (int64_t)segment->GetGlobalPosition( uint64( spos ) );
4173                 }
4174                 else
4175                 {
4176                     /* Many mkvmerge files hit this case. It seems to be a broken SeekHead */
4177                     msg_Dbg( &sys.demuxer, "|   |   + Unknown (%s)", typeid(*l).name()  );
4178                 }
4179             }
4180             ep->Up();
4181
4182             if( i_pos >= 0 )
4183             {
4184                 if( id == KaxCues::ClassInfos.GlobalId )
4185                 {
4186                     msg_Dbg( &sys.demuxer, "|   - cues at %"PRId64, i_pos );
4187                     LoadSeekHeadItem( KaxCues::ClassInfos, i_pos );
4188                 }
4189                 else if( id == KaxInfo::ClassInfos.GlobalId )
4190                 {
4191                     msg_Dbg( &sys.demuxer, "|   - info at %"PRId64, i_pos );
4192                     LoadSeekHeadItem( KaxInfo::ClassInfos, i_pos );
4193                 }
4194                 else if( id == KaxChapters::ClassInfos.GlobalId )
4195                 {
4196                     msg_Dbg( &sys.demuxer, "|   - chapters at %"PRId64, i_pos );
4197                     LoadSeekHeadItem( KaxChapters::ClassInfos, i_pos );
4198                 }
4199                 else if( id == KaxTags::ClassInfos.GlobalId )
4200                 {
4201                     msg_Dbg( &sys.demuxer, "|   - tags at %"PRId64, i_pos );
4202                     LoadSeekHeadItem( KaxTags::ClassInfos, i_pos );
4203                 }
4204                 else if( id == KaxSeekHead::ClassInfos.GlobalId )
4205                 {
4206                     msg_Dbg( &sys.demuxer, "|   - chained seekhead at %"PRId64, i_pos );
4207                     LoadSeekHeadItem( KaxSeekHead::ClassInfos, i_pos );
4208                 }
4209                 else if( id == KaxTracks::ClassInfos.GlobalId )
4210                 {
4211                     msg_Dbg( &sys.demuxer, "|   - tracks at %"PRId64, i_pos );
4212                     LoadSeekHeadItem( KaxTracks::ClassInfos, i_pos );
4213                 }
4214                 else if( id == KaxAttachments::ClassInfos.GlobalId )
4215                 {
4216                     msg_Dbg( &sys.demuxer, "|   - attachments at %"PRId64, i_pos );
4217                     LoadSeekHeadItem( KaxAttachments::ClassInfos, i_pos );
4218                 }
4219                 else
4220                     msg_Dbg( &sys.demuxer, "|   - unknown seekhead reference at %"PRId64, i_pos );
4221             }
4222         }
4223         else
4224             msg_Dbg( &sys.demuxer, "|   |   + ParseSeekHead Unknown (%s)", typeid(*l).name() );
4225     }
4226     delete ep;
4227 }
4228
4229 /*****************************************************************************
4230  * ParseTrackEntry:
4231  *****************************************************************************/
4232 void matroska_segment_c::ParseTrackEntry( KaxTrackEntry *m )
4233 {
4234     size_t i, j, k, n;
4235     bool bSupported = true;
4236
4237     mkv_track_t *tk;
4238
4239     msg_Dbg( &sys.demuxer, "|   |   + Track Entry" );
4240
4241     tk = new mkv_track_t();
4242
4243     /* Init the track */
4244     memset( tk, 0, sizeof( mkv_track_t ) );
4245
4246     es_format_Init( &tk->fmt, UNKNOWN_ES, 0 );
4247     tk->fmt.psz_language = strdup("English");
4248     tk->fmt.psz_description = NULL;
4249
4250     tk->b_default = true;
4251     tk->b_enabled = true;
4252     tk->b_silent = false;
4253     tk->i_number = tracks.size() - 1;
4254     tk->i_extra_data = 0;
4255     tk->p_extra_data = NULL;
4256     tk->psz_codec = NULL;
4257     tk->i_default_duration = 0;
4258     tk->f_timecodescale = 1.0;
4259
4260     tk->b_inited = false;
4261     tk->i_data_init = 0;
4262     tk->p_data_init = NULL;
4263
4264     tk->psz_codec_name = NULL;
4265     tk->psz_codec_settings = NULL;
4266     tk->psz_codec_info_url = NULL;
4267     tk->psz_codec_download_url = NULL;
4268  
4269     tk->i_compression_type = MATROSKA_COMPRESSION_NONE;
4270     tk->p_compression_data = NULL;
4271
4272     for( i = 0; i < m->ListSize(); i++ )
4273     {
4274         EbmlElement *l = (*m)[i];
4275
4276         if( MKV_IS_ID( l, KaxTrackNumber ) )
4277         {
4278             KaxTrackNumber &tnum = *(KaxTrackNumber*)l;
4279
4280             tk->i_number = uint32( tnum );
4281             msg_Dbg( &sys.demuxer, "|   |   |   + Track Number=%u", uint32( tnum ) );
4282         }
4283         else  if( MKV_IS_ID( l, KaxTrackUID ) )
4284         {
4285             KaxTrackUID &tuid = *(KaxTrackUID*)l;
4286
4287             msg_Dbg( &sys.demuxer, "|   |   |   + Track UID=%u",  uint32( tuid ) );
4288         }
4289         else  if( MKV_IS_ID( l, KaxTrackType ) )
4290         {
4291             const char *psz_type;
4292             KaxTrackType &ttype = *(KaxTrackType*)l;
4293
4294             switch( uint8(ttype) )
4295             {
4296                 case track_audio:
4297                     psz_type = "audio";
4298                     tk->fmt.i_cat = AUDIO_ES;
4299                     break;
4300                 case track_video:
4301                     psz_type = "video";
4302                     tk->fmt.i_cat = VIDEO_ES;
4303                     break;
4304                 case track_subtitle:
4305                     psz_type = "subtitle";
4306                     tk->fmt.i_cat = SPU_ES;
4307                     break;
4308                 case track_buttons:
4309                     psz_type = "buttons";
4310                     tk->fmt.i_cat = SPU_ES;
4311                     break;
4312                 default:
4313                     psz_type = "unknown";
4314                     tk->fmt.i_cat = UNKNOWN_ES;
4315                     break;
4316             }
4317
4318             msg_Dbg( &sys.demuxer, "|   |   |   + Track Type=%s", psz_type );
4319         }
4320 //        else  if( EbmlId( *l ) == KaxTrackFlagEnabled::ClassInfos.GlobalId )
4321 //        {
4322 //            KaxTrackFlagEnabled &fenb = *(KaxTrackFlagEnabled*)l;
4323
4324 //            tk->b_enabled = uint32( fenb );
4325 //            msg_Dbg( &sys.demuxer, "|   |   |   + Track Enabled=%u",
4326 //                     uint32( fenb )  );
4327 //        }
4328         else  if( MKV_IS_ID( l, KaxTrackFlagDefault ) )
4329         {
4330             KaxTrackFlagDefault &fdef = *(KaxTrackFlagDefault*)l;
4331
4332             tk->b_default = uint32( fdef );
4333             msg_Dbg( &sys.demuxer, "|   |   |   + Track Default=%u", uint32( fdef )  );
4334         }
4335         else  if( MKV_IS_ID( l, KaxTrackFlagLacing ) )
4336         {
4337             KaxTrackFlagLacing &lac = *(KaxTrackFlagLacing*)l;
4338
4339             msg_Dbg( &sys.demuxer, "|   |   |   + Track Lacing=%d", uint32( lac ) );
4340         }
4341         else  if( MKV_IS_ID( l, KaxTrackMinCache ) )
4342         {
4343             KaxTrackMinCache &cmin = *(KaxTrackMinCache*)l;
4344
4345             msg_Dbg( &sys.demuxer, "|   |   |   + Track MinCache=%d", uint32( cmin ) );
4346         }
4347         else  if( MKV_IS_ID( l, KaxTrackMaxCache ) )
4348         {
4349             KaxTrackMaxCache &cmax = *(KaxTrackMaxCache*)l;
4350
4351             msg_Dbg( &sys.demuxer, "|   |   |   + Track MaxCache=%d", uint32( cmax ) );
4352         }
4353         else  if( MKV_IS_ID( l, KaxTrackDefaultDuration ) )
4354         {
4355             KaxTrackDefaultDuration &defd = *(KaxTrackDefaultDuration*)l;
4356
4357             tk->i_default_duration = uint64(defd);
4358             msg_Dbg( &sys.demuxer, "|   |   |   + Track Default Duration=%"PRId64, uint64(defd) );
4359         }
4360         else  if( MKV_IS_ID( l, KaxTrackTimecodeScale ) )
4361         {
4362             KaxTrackTimecodeScale &ttcs = *(KaxTrackTimecodeScale*)l;
4363
4364             tk->f_timecodescale = float( ttcs );
4365             msg_Dbg( &sys.demuxer, "|   |   |   + Track TimeCodeScale=%f", tk->f_timecodescale );
4366         }
4367         else if( MKV_IS_ID( l, KaxTrackName ) )
4368         {
4369             KaxTrackName &tname = *(KaxTrackName*)l;
4370
4371             tk->fmt.psz_description = ToUTF8( UTFstring( tname ) );
4372             msg_Dbg( &sys.demuxer, "|   |   |   + Track Name=%s", tk->fmt.psz_description );
4373         }
4374         else  if( MKV_IS_ID( l, KaxTrackLanguage ) )
4375         {
4376             KaxTrackLanguage &lang = *(KaxTrackLanguage*)l;
4377
4378             if ( tk->fmt.psz_language != NULL )
4379                 free( tk->fmt.psz_language );
4380             tk->fmt.psz_language = strdup( string( lang ).c_str() );
4381             msg_Dbg( &sys.demuxer,
4382                      "|   |   |   + Track Language=`%s'", tk->fmt.psz_language );
4383         }
4384         else  if( MKV_IS_ID( l, KaxCodecID ) )
4385         {
4386             KaxCodecID &codecid = *(KaxCodecID*)l;
4387
4388             tk->psz_codec = strdup( string( codecid ).c_str() );
4389             msg_Dbg( &sys.demuxer, "|   |   |   + Track CodecId=%s", string( codecid ).c_str() );
4390         }
4391         else  if( MKV_IS_ID( l, KaxCodecPrivate ) )
4392         {
4393             KaxCodecPrivate &cpriv = *(KaxCodecPrivate*)l;
4394
4395             tk->i_extra_data = cpriv.GetSize();
4396             if( tk->i_extra_data > 0 )
4397             {
4398                 tk->p_extra_data = (uint8_t*)malloc( tk->i_extra_data );
4399                 memcpy( tk->p_extra_data, cpriv.GetBuffer(), tk->i_extra_data );
4400             }
4401             msg_Dbg( &sys.demuxer, "|   |   |   + Track CodecPrivate size=%"PRId64, cpriv.GetSize() );
4402         }
4403         else if( MKV_IS_ID( l, KaxCodecName ) )
4404         {
4405             KaxCodecName &cname = *(KaxCodecName*)l;
4406
4407             tk->psz_codec_name = ToUTF8( UTFstring( cname ) );
4408             msg_Dbg( &sys.demuxer, "|   |   |   + Track Codec Name=%s", tk->psz_codec_name );
4409         }
4410         else if( MKV_IS_ID( l, KaxContentEncodings ) )
4411         {
4412             EbmlMaster *cencs = static_cast<EbmlMaster*>(l);
4413             MkvTree( sys.demuxer, 3, "Content Encodings" );
4414             if ( cencs->ListSize() > 1 )
4415             {
4416                 msg_Err( &sys.demuxer, "Multiple Compression method not supported" );
4417                 bSupported = false;
4418             }
4419             for( j = 0; j < cencs->ListSize(); j++ )
4420             {
4421                 EbmlElement *l2 = (*cencs)[j];
4422                 if( MKV_IS_ID( l2, KaxContentEncoding ) )
4423                 {
4424                     MkvTree( sys.demuxer, 4, "Content Encoding" );
4425                     EbmlMaster *cenc = static_cast<EbmlMaster*>(l2);
4426                     for( k = 0; k < cenc->ListSize(); k++ )
4427                     {
4428                         EbmlElement *l3 = (*cenc)[k];
4429                         if( MKV_IS_ID( l3, KaxContentEncodingOrder ) )
4430                         {
4431                             KaxContentEncodingOrder &encord = *(KaxContentEncodingOrder*)l3;
4432                             MkvTree( sys.demuxer, 5, "Order: %i", uint32( encord ) );
4433                         }
4434                         else if( MKV_IS_ID( l3, KaxContentEncodingScope ) )
4435                         {
4436                             KaxContentEncodingScope &encscope = *(KaxContentEncodingScope*)l3;
4437                             MkvTree( sys.demuxer, 5, "Scope: %i", uint32( encscope ) );
4438                         }
4439                         else if( MKV_IS_ID( l3, KaxContentEncodingType ) )
4440                         {
4441                             KaxContentEncodingType &enctype = *(KaxContentEncodingType*)l3;
4442                             MkvTree( sys.demuxer, 5, "Type: %i", uint32( enctype ) );
4443                         }
4444                         else if( MKV_IS_ID( l3, KaxContentCompression ) )
4445                         {
4446                             EbmlMaster *compr = static_cast<EbmlMaster*>(l3);
4447                             MkvTree( sys.demuxer, 5, "Content Compression" );
4448                             for( n = 0; n < compr->ListSize(); n++ )
4449                             {
4450                                 EbmlElement *l4 = (*compr)[n];
4451                                 if( MKV_IS_ID( l4, KaxContentCompAlgo ) )
4452                                 {
4453                                     KaxContentCompAlgo &compalg = *(KaxContentCompAlgo*)l4;
4454                                     MkvTree( sys.demuxer, 6, "Compression Algorithm: %i", uint32(compalg) );
4455                                     tk->i_compression_type = uint32( compalg );
4456                                     if ( ( tk->i_compression_type != MATROSKA_COMPRESSION_ZLIB ) &&
4457                                          ( tk->i_compression_type != MATROSKA_COMPRESSION_HEADER ) )
4458                                     {
4459                                         msg_Err( &sys.demuxer, "Track Compression method %d not supported", tk->i_compression_type );
4460                                         bSupported = false;
4461                                     }
4462                                 }
4463                                 else if( MKV_IS_ID( l4, KaxContentCompSettings ) )
4464                                 {
4465                                     tk->p_compression_data = new KaxContentCompSettings( *(KaxContentCompSettings*)l4 );
4466                                 }
4467                                 else
4468                                 {
4469                                     MkvTree( sys.demuxer, 6, "Unknown (%s)", typeid(*l4).name() );
4470                                 }
4471                             }
4472                         }
4473                         else
4474                         {
4475                             MkvTree( sys.demuxer, 5, "Unknown (%s)", typeid(*l3).name() );
4476                         }
4477                     }
4478                 }
4479                 else
4480                 {
4481                     MkvTree( sys.demuxer, 4, "Unknown (%s)", typeid(*l2).name() );
4482                 }
4483             }
4484         }
4485 //        else if( EbmlId( *l ) == KaxCodecSettings::ClassInfos.GlobalId )
4486 //        {
4487 //            KaxCodecSettings &cset = *(KaxCodecSettings*)l;
4488
4489 //            tk->psz_codec_settings = ToUTF8( UTFstring( cset ) );
4490 //            msg_Dbg( &sys.demuxer, "|   |   |   + Track Codec Settings=%s", tk->psz_codec_settings );
4491 //        }
4492 //        else if( EbmlId( *l ) == KaxCodecInfoURL::ClassInfos.GlobalId )
4493 //        {
4494 //            KaxCodecInfoURL &ciurl = *(KaxCodecInfoURL*)l;
4495
4496 //            tk->psz_codec_info_url = strdup( string( ciurl ).c_str() );
4497 //            msg_Dbg( &sys.demuxer, "|   |   |   + Track Codec Info URL=%s", tk->psz_codec_info_url );
4498 //        }
4499 //        else if( EbmlId( *l ) == KaxCodecDownloadURL::ClassInfos.GlobalId )
4500 //        {
4501 //            KaxCodecDownloadURL &cdurl = *(KaxCodecDownloadURL*)l;
4502
4503 //            tk->psz_codec_download_url = strdup( string( cdurl ).c_str() );
4504 //            msg_Dbg( &sys.demuxer, "|   |   |   + Track Codec Info URL=%s", tk->psz_codec_download_url );
4505 //        }
4506 //        else if( EbmlId( *l ) == KaxCodecDecodeAll::ClassInfos.GlobalId )
4507 //        {
4508 //            KaxCodecDecodeAll &cdall = *(KaxCodecDecodeAll*)l;
4509
4510 //            msg_Dbg( &sys.demuxer, "|   |   |   + Track Codec Decode All=%u <== UNUSED", uint8( cdall ) );
4511 //        }
4512 //        else if( EbmlId( *l ) == KaxTrackOverlay::ClassInfos.GlobalId )
4513 //        {
4514 //            KaxTrackOverlay &tovr = *(KaxTrackOverlay*)l;
4515
4516 //            msg_Dbg( &sys.demuxer, "|   |   |   + Track Overlay=%u <== UNUSED", uint32( tovr ) );
4517 //        }
4518         else  if( MKV_IS_ID( l, KaxTrackVideo ) )
4519         {
4520             EbmlMaster *tkv = static_cast<EbmlMaster*>(l);
4521             unsigned int j;
4522             unsigned int i_crop_right = 0, i_crop_left = 0, i_crop_top = 0, i_crop_bottom = 0;
4523             unsigned int i_display_unit = 0, i_display_width = 0, i_display_height = 0;
4524
4525             msg_Dbg( &sys.demuxer, "|   |   |   + Track Video" );
4526             tk->f_fps = 0.0;
4527
4528             tk->fmt.video.i_frame_rate_base = (unsigned int)(tk->i_default_duration / 1000);
4529             tk->fmt.video.i_frame_rate = 1000000;
4530  
4531             for( j = 0; j < tkv->ListSize(); j++ )
4532             {
4533                 EbmlElement *l = (*tkv)[j];
4534 //                if( EbmlId( *el4 ) == KaxVideoFlagInterlaced::ClassInfos.GlobalId )
4535 //                {
4536 //                    KaxVideoFlagInterlaced &fint = *(KaxVideoFlagInterlaced*)el4;
4537
4538 //                    msg_Dbg( &sys.demuxer, "|   |   |   |   + Track Video Interlaced=%u", uint8( fint ) );
4539 //                }
4540 //                else if( EbmlId( *el4 ) == KaxVideoStereoMode::ClassInfos.GlobalId )
4541 //                {
4542 //                    KaxVideoStereoMode &stereo = *(KaxVideoStereoMode*)el4;
4543
4544 //                    msg_Dbg( &sys.demuxer, "|   |   |   |   + Track Video Stereo Mode=%u", uint8( stereo ) );
4545 //                }
4546 //                else
4547                 if( MKV_IS_ID( l, KaxVideoPixelWidth ) )
4548                 {
4549                     KaxVideoPixelWidth &vwidth = *(KaxVideoPixelWidth*)l;
4550
4551                     tk->fmt.video.i_width += uint16( vwidth );
4552                     msg_Dbg( &sys.demuxer, "|   |   |   |   + width=%d", uint16( vwidth ) );
4553                 }
4554                 else if( MKV_IS_ID( l, KaxVideoPixelHeight ) )
4555                 {
4556                     KaxVideoPixelWidth &vheight = *(KaxVideoPixelWidth*)l;
4557
4558                     tk->fmt.video.i_height += uint16( vheight );
4559                     msg_Dbg( &sys.demuxer, "|   |   |   |   + height=%d", uint16( vheight ) );
4560                 }
4561                 else if( MKV_IS_ID( l, KaxVideoDisplayWidth ) )
4562                 {
4563                     KaxVideoDisplayWidth &vwidth = *(KaxVideoDisplayWidth*)l;
4564
4565                     i_display_width = uint16( vwidth );
4566                     msg_Dbg( &sys.demuxer, "|   |   |   |   + display width=%d", uint16( vwidth ) );
4567                 }
4568                 else if( MKV_IS_ID( l, KaxVideoDisplayHeight ) )
4569                 {
4570                     KaxVideoDisplayWidth &vheight = *(KaxVideoDisplayWidth*)l;
4571
4572                     i_display_height = uint16( vheight );
4573                     msg_Dbg( &sys.demuxer, "|   |   |   |   + display height=%d", uint16( vheight ) );
4574                 }
4575                 else if( MKV_IS_ID( l, KaxVideoPixelCropBottom ) )
4576                 {
4577                     KaxVideoPixelCropBottom &cropval = *(KaxVideoPixelCropBottom*)l;
4578
4579                     i_crop_bottom = uint16( cropval );
4580                     msg_Dbg( &sys.demuxer, "|   |   |   |   + crop pixel bottom=%d", uint16( cropval ) );
4581                 }
4582                 else if( MKV_IS_ID( l, KaxVideoPixelCropTop ) )
4583                 {
4584                     KaxVideoPixelCropTop &cropval = *(KaxVideoPixelCropTop*)l;
4585
4586                     i_crop_top = uint16( cropval );
4587                     msg_Dbg( &sys.demuxer, "|   |   |   |   + crop pixel top=%d", uint16( cropval ) );
4588                 }
4589                 else if( MKV_IS_ID( l, KaxVideoPixelCropRight ) )
4590                 {
4591                     KaxVideoPixelCropRight &cropval = *(KaxVideoPixelCropRight*)l;
4592
4593                     i_crop_right = uint16( cropval );
4594                     msg_Dbg( &sys.demuxer, "|   |   |   |   + crop pixel right=%d", uint16( cropval ) );
4595                 }
4596                 else if( MKV_IS_ID( l, KaxVideoPixelCropLeft ) )
4597                 {
4598                     KaxVideoPixelCropLeft &cropval = *(KaxVideoPixelCropLeft*)l;
4599
4600                     i_crop_left = uint16( cropval );
4601                     msg_Dbg( &sys.demuxer, "|   |   |   |   + crop pixel left=%d", uint16( cropval ) );
4602                 }
4603                 else if( MKV_IS_ID( l, KaxVideoFrameRate ) )
4604                 {
4605                     KaxVideoFrameRate &vfps = *(KaxVideoFrameRate*)l;
4606
4607                     tk->f_fps = float( vfps );
4608                     msg_Dbg( &sys.demuxer, "   |   |   |   + fps=%f", float( vfps ) );
4609                 }
4610                 else if( EbmlId( *l ) == KaxVideoDisplayUnit::ClassInfos.GlobalId )
4611                 {
4612                     KaxVideoDisplayUnit &vdmode = *(KaxVideoDisplayUnit*)l;
4613
4614                     i_display_unit = uint8( vdmode );
4615                     msg_Dbg( &sys.demuxer, "|   |   |   |   + Track Video Display Unit=%s",
4616                              uint8( vdmode ) == 0 ? "pixels" : ( uint8( vdmode ) == 1 ? "centimeters": "inches" ) );
4617                 }
4618 //                else if( EbmlId( *l ) == KaxVideoAspectRatio::ClassInfos.GlobalId )
4619 //                {
4620 //                    KaxVideoAspectRatio &ratio = *(KaxVideoAspectRatio*)l;
4621
4622 //                    msg_Dbg( &sys.demuxer, "   |   |   |   + Track Video Aspect Ratio Type=%u", uint8( ratio ) );
4623 //                }
4624 //                else if( EbmlId( *l ) == KaxVideoGamma::ClassInfos.GlobalId )
4625 //                {
4626 //                    KaxVideoGamma &gamma = *(KaxVideoGamma*)l;
4627
4628 //                    msg_Dbg( &sys.demuxer, "   |   |   |   + gamma=%f", float( gamma ) );
4629 //                }
4630                 else
4631                 {
4632                     msg_Dbg( &sys.demuxer, "|   |   |   |   + Unknown (%s)", typeid(*l).name() );
4633                 }
4634             }
4635             if( i_display_height && i_display_width )
4636                 tk->fmt.video.i_aspect = VOUT_ASPECT_FACTOR * i_display_width / i_display_height;
4637             if( i_crop_left || i_crop_right || i_crop_top || i_crop_bottom )
4638             {
4639                 tk->fmt.video.i_visible_width = tk->fmt.video.i_width;
4640                 tk->fmt.video.i_visible_height = tk->fmt.video.i_height;
4641                 tk->fmt.video.i_x_offset = i_crop_left;
4642                 tk->fmt.video.i_y_offset = i_crop_top;
4643                 tk->fmt.video.i_visible_width -= i_crop_left + i_crop_right;
4644                 tk->fmt.video.i_visible_height -= i_crop_top + i_crop_bottom;
4645             }
4646             /* FIXME: i_display_* allows you to not only set DAR, but also a zoom factor.
4647                we do not support this atm */
4648         }
4649         else  if( MKV_IS_ID( l, KaxTrackAudio ) )
4650         {
4651             EbmlMaster *tka = static_cast<EbmlMaster*>(l);
4652             unsigned int j;
4653
4654             msg_Dbg( &sys.demuxer, "|   |   |   + Track Audio" );
4655
4656             for( j = 0; j < tka->ListSize(); j++ )
4657             {
4658                 EbmlElement *l = (*tka)[j];
4659
4660                 if( MKV_IS_ID( l, KaxAudioSamplingFreq ) )
4661                 {
4662                     KaxAudioSamplingFreq &afreq = *(KaxAudioSamplingFreq*)l;
4663
4664                     tk->i_original_rate = tk->fmt.audio.i_rate = (int)float( afreq );
4665                     msg_Dbg( &sys.demuxer, "|   |   |   |   + afreq=%d", tk->fmt.audio.i_rate );
4666                 }
4667                 else if( MKV_IS_ID( l, KaxAudioOutputSamplingFreq ) )
4668                 {
4669                     KaxAudioOutputSamplingFreq &afreq = *(KaxAudioOutputSamplingFreq*)l;
4670
4671                     tk->fmt.audio.i_rate = (int)float( afreq );
4672                     msg_Dbg( &sys.demuxer, "|   |   |   |   + aoutfreq=%d", tk->fmt.audio.i_rate );
4673                 }
4674                 else if( MKV_IS_ID( l, KaxAudioChannels ) )
4675                 {
4676                     KaxAudioChannels &achan = *(KaxAudioChannels*)l;
4677
4678                     tk->fmt.audio.i_channels = uint8( achan );
4679                     msg_Dbg( &sys.demuxer, "|   |   |   |   + achan=%u", uint8( achan ) );
4680                 }
4681                 else if( MKV_IS_ID( l, KaxAudioBitDepth ) )
4682                 {
4683                     KaxAudioBitDepth &abits = *(KaxAudioBitDepth*)l;
4684
4685                     tk->fmt.audio.i_bitspersample = uint8( abits );
4686                     msg_Dbg( &sys.demuxer, "|   |   |   |   + abits=%u", uint8( abits ) );
4687                 }
4688                 else
4689                 {
4690                     msg_Dbg( &sys.demuxer, "|   |   |   |   + Unknown (%s)", typeid(*l).name() );
4691                 }
4692             }
4693         }
4694         else
4695         {
4696             msg_Dbg( &sys.demuxer, "|   |   |   + Unknown (%s)",
4697                      typeid(*l).name() );
4698         }
4699     }
4700
4701     if ( bSupported )
4702     {
4703         tracks.push_back( tk );
4704     }
4705     else
4706     {
4707         msg_Err( &sys.demuxer, "Track Entry %d not supported", tk->i_number );
4708         delete tk;
4709     }
4710 }
4711
4712 /*****************************************************************************
4713  * ParseTracks:
4714  *****************************************************************************/
4715 void matroska_segment_c::ParseTracks( KaxTracks *tracks )
4716 {
4717     EbmlElement *el;
4718     unsigned int i;
4719     int i_upper_level = 0;
4720
4721     /* Master elements */
4722     tracks->Read( es, tracks->Generic().Context, i_upper_level, el, true );
4723
4724     for( i = 0; i < tracks->ListSize(); i++ )
4725     {
4726         EbmlElement *l = (*tracks)[i];
4727
4728         if( MKV_IS_ID( l, KaxTrackEntry ) )
4729         {
4730             ParseTrackEntry( static_cast<KaxTrackEntry *>(l) );
4731         }
4732         else
4733         {
4734             msg_Dbg( &sys.demuxer, "|   |   + Unknown (%s)", typeid(*l).name() );
4735         }
4736     }
4737 }
4738
4739 /*****************************************************************************
4740  * ParseInfo:
4741  *****************************************************************************/
4742 void matroska_segment_c::ParseInfo( KaxInfo *info )
4743 {
4744     EbmlElement *el;
4745     EbmlMaster  *m;
4746     size_t i, j;
4747     int i_upper_level = 0;
4748
4749     /* Master elements */
4750     m = static_cast<EbmlMaster *>(info);
4751     m->Read( es, info->Generic().Context, i_upper_level, el, true );
4752
4753     for( i = 0; i < m->ListSize(); i++ )
4754     {
4755         EbmlElement *l = (*m)[i];
4756
4757         if( MKV_IS_ID( l, KaxSegmentUID ) )
4758         {
4759             if ( p_segment_uid == NULL )
4760                 p_segment_uid = new KaxSegmentUID(*static_cast<KaxSegmentUID*>(l));
4761
4762             msg_Dbg( &sys.demuxer, "|   |   + UID=%d", *(uint32*)p_segment_uid->GetBuffer() );
4763         }
4764         else if( MKV_IS_ID( l, KaxPrevUID ) )
4765         {
4766             if ( p_prev_segment_uid == NULL )
4767                 p_prev_segment_uid = new KaxPrevUID(*static_cast<KaxPrevUID*>(l));
4768
4769             msg_Dbg( &sys.demuxer, "|   |   + PrevUID=%d", *(uint32*)p_prev_segment_uid->GetBuffer() );
4770         }
4771         else if( MKV_IS_ID( l, KaxNextUID ) )
4772         {
4773             if ( p_next_segment_uid == NULL )
4774                 p_next_segment_uid = new KaxNextUID(*static_cast<KaxNextUID*>(l));
4775
4776             msg_Dbg( &sys.demuxer, "|   |   + NextUID=%d", *(uint32*)p_next_segment_uid->GetBuffer() );
4777         }
4778         else if( MKV_IS_ID( l, KaxTimecodeScale ) )
4779         {
4780             KaxTimecodeScale &tcs = *(KaxTimecodeScale*)l;
4781
4782             i_timescale = uint64(tcs);
4783
4784             msg_Dbg( &sys.demuxer, "|   |   + TimecodeScale=%"PRId64,
4785                      i_timescale );
4786         }
4787         else if( MKV_IS_ID( l, KaxDuration ) )
4788         {
4789             KaxDuration &dur = *(KaxDuration*)l;
4790
4791             i_duration = mtime_t( double( dur ) );
4792
4793             msg_Dbg( &sys.demuxer, "|   |   + Duration=%"PRId64,
4794                      i_duration );
4795         }
4796         else if( MKV_IS_ID( l, KaxMuxingApp ) )
4797         {
4798             KaxMuxingApp &mapp = *(KaxMuxingApp*)l;
4799
4800             psz_muxing_application = ToUTF8( UTFstring( mapp ) );
4801
4802             msg_Dbg( &sys.demuxer, "|   |   + Muxing Application=%s",
4803                      psz_muxing_application );
4804         }
4805         else if( MKV_IS_ID( l, KaxWritingApp ) )
4806         {
4807             KaxWritingApp &wapp = *(KaxWritingApp*)l;
4808
4809             psz_writing_application = ToUTF8( UTFstring( wapp ) );
4810
4811             msg_Dbg( &sys.demuxer, "|   |   + Writing Application=%s",
4812                      psz_writing_application );
4813         }
4814         else if( MKV_IS_ID( l, KaxSegmentFilename ) )
4815         {
4816             KaxSegmentFilename &sfn = *(KaxSegmentFilename*)l;
4817
4818             psz_segment_filename = ToUTF8( UTFstring( sfn ) );
4819
4820             msg_Dbg( &sys.demuxer, "|   |   + Segment Filename=%s",
4821                      psz_segment_filename );
4822         }
4823         else if( MKV_IS_ID( l, KaxTitle ) )
4824         {
4825             KaxTitle &title = *(KaxTitle*)l;
4826
4827             psz_title = ToUTF8( UTFstring( title ) );
4828
4829             msg_Dbg( &sys.demuxer, "|   |   + Title=%s", psz_title );
4830         }
4831         else if( MKV_IS_ID( l, KaxSegmentFamily ) )
4832         {
4833             KaxSegmentFamily *uid = static_cast<KaxSegmentFamily*>(l);
4834
4835             families.push_back( new KaxSegmentFamily(*uid) );
4836
4837             msg_Dbg( &sys.demuxer, "|   |   + family=%d", *(uint32*)uid->GetBuffer() );
4838         }
4839 #if defined( HAVE_GMTIME_R )
4840         else if( MKV_IS_ID( l, KaxDateUTC ) )
4841         {
4842             KaxDateUTC &date = *(KaxDateUTC*)l;
4843             time_t i_date;
4844             struct tm tmres;
4845             char   buffer[256];
4846
4847             i_date = date.GetEpochDate();
4848             memset( buffer, 0, 256 );
4849             if( gmtime_r( &i_date, &tmres ) &&
4850                 asctime_r( &tmres, buffer ) )
4851             {
4852                 buffer[strlen( buffer)-1]= '\0';
4853                 psz_date_utc = strdup( buffer );
4854                 msg_Dbg( &sys.demuxer, "|   |   + Date=%s", psz_date_utc );
4855             }
4856         }
4857 #endif
4858 #if LIBMATROSKA_VERSION >= 0x000704
4859         else if( MKV_IS_ID( l, KaxChapterTranslate ) )
4860         {
4861             KaxChapterTranslate *p_trans = static_cast<KaxChapterTranslate*>( l );
4862             chapter_translation_c *p_translate = new chapter_translation_c();
4863
4864             p_trans->Read( es, p_trans->Generic().Context, i_upper_level, el, true );
4865             for( j = 0; j < p_trans->ListSize(); j++ )
4866             {
4867                 EbmlElement *l = (*p_trans)[j];
4868
4869                 if( MKV_IS_ID( l, KaxChapterTranslateEditionUID ) )
4870                 {
4871                     p_translate->editions.push_back( uint64( *static_cast<KaxChapterTranslateEditionUID*>( l ) ) );
4872                 }
4873                 else if( MKV_IS_ID( l, KaxChapterTranslateCodec ) )
4874                 {
4875                     p_translate->codec_id = uint32( *static_cast<KaxChapterTranslateCodec*>( l ) );
4876                 }
4877                 else if( MKV_IS_ID( l, KaxChapterTranslateID ) )
4878                 {
4879                     p_translate->p_translated = new KaxChapterTranslateID( *static_cast<KaxChapterTranslateID*>( l ) );
4880                 }
4881             }
4882
4883             translations.push_back( p_translate );
4884         }
4885 #endif
4886         else
4887         {
4888             msg_Dbg( &sys.demuxer, "|   |   + Unknown (%s)", typeid(*l).name() );
4889         }
4890     }
4891
4892     double f_dur = double(i_duration) * double(i_timescale) / 1000000.0;
4893     i_duration = mtime_t(f_dur);
4894 }
4895
4896
4897 /*****************************************************************************
4898  * ParseChapterAtom
4899  *****************************************************************************/
4900 void matroska_segment_c::ParseChapterAtom( int i_level, KaxChapterAtom *ca, chapter_item_c & chapters )
4901 {
4902     size_t i, j;
4903
4904     msg_Dbg( &sys.demuxer, "|   |   |   + ChapterAtom (level=%d)", i_level );
4905     for( i = 0; i < ca->ListSize(); i++ )
4906     {
4907         EbmlElement *l = (*ca)[i];
4908
4909         if( MKV_IS_ID( l, KaxChapterUID ) )
4910         {
4911             chapters.i_uid = uint64_t(*(KaxChapterUID*)l);
4912             msg_Dbg( &sys.demuxer, "|   |   |   |   + ChapterUID: %lld", chapters.i_uid );
4913         }
4914         else if( MKV_IS_ID( l, KaxChapterFlagHidden ) )
4915         {
4916             KaxChapterFlagHidden &flag =*(KaxChapterFlagHidden*)l;
4917             chapters.b_display_seekpoint = uint8( flag ) == 0;
4918
4919             msg_Dbg( &sys.demuxer, "|   |   |   |   + ChapterFlagHidden: %s", chapters.b_display_seekpoint ? "no":"yes" );
4920         }
4921         else if( MKV_IS_ID( l, KaxChapterTimeStart ) )
4922         {
4923             KaxChapterTimeStart &start =*(KaxChapterTimeStart*)l;
4924             chapters.i_start_time = uint64( start ) / INT64_C(1000);
4925
4926             msg_Dbg( &sys.demuxer, "|   |   |   |   + ChapterTimeStart: %lld", chapters.i_start_time );
4927         }
4928         else if( MKV_IS_ID( l, KaxChapterTimeEnd ) )
4929         {
4930             KaxChapterTimeEnd &end =*(KaxChapterTimeEnd*)l;
4931             chapters.i_end_time = uint64( end ) / INT64_C(1000);
4932
4933             msg_Dbg( &sys.demuxer, "|   |   |   |   + ChapterTimeEnd: %lld", chapters.i_end_time );
4934         }
4935         else if( MKV_IS_ID( l, KaxChapterDisplay ) )
4936         {
4937             EbmlMaster *cd = static_cast<EbmlMaster *>(l);
4938
4939             msg_Dbg( &sys.demuxer, "|   |   |   |   + ChapterDisplay" );
4940             for( j = 0; j < cd->ListSize(); j++ )
4941             {
4942                 EbmlElement *l= (*cd)[j];
4943
4944                 if( MKV_IS_ID( l, KaxChapterString ) )
4945                 {
4946                     int k;
4947
4948                     KaxChapterString &name =*(KaxChapterString*)l;
4949                     for (k = 0; k < i_level; k++)
4950                         chapters.psz_name += '+';
4951                     chapters.psz_name += ' ';
4952                     char *psz_tmp_utf8 = ToUTF8( UTFstring( name ) );
4953                     chapters.psz_name += psz_tmp_utf8;
4954                     chapters.b_user_display = true;
4955
4956                     msg_Dbg( &sys.demuxer, "|   |   |   |   |    + ChapterString '%s'", psz_tmp_utf8 );
4957                     free( psz_tmp_utf8 );
4958                 }
4959                 else if( MKV_IS_ID( l, KaxChapterLanguage ) )
4960                 {
4961                     KaxChapterLanguage &lang =*(KaxChapterLanguage*)l;
4962                     const char *psz = string( lang ).c_str();
4963
4964                     msg_Dbg( &sys.demuxer, "|   |   |   |   |    + ChapterLanguage '%s'", psz );
4965                 }
4966                 else if( MKV_IS_ID( l, KaxChapterCountry ) )
4967                 {
4968                     KaxChapterCountry &ct =*(KaxChapterCountry*)l;
4969                     const char *psz = string( ct ).c_str();
4970
4971                     msg_Dbg( &sys.demuxer, "|   |   |   |   |    + ChapterCountry '%s'", psz );
4972                 }
4973             }
4974         }
4975         else if( MKV_IS_ID( l, KaxChapterProcess ) )
4976         {
4977             msg_Dbg( &sys.demuxer, "|   |   |   |   + ChapterProcess" );
4978
4979             KaxChapterProcess *cp = static_cast<KaxChapterProcess *>(l);
4980             chapter_codec_cmds_c *p_ccodec = NULL;
4981
4982             for( j = 0; j < cp->ListSize(); j++ )
4983             {
4984                 EbmlElement *k= (*cp)[j];
4985
4986                 if( MKV_IS_ID( k, KaxChapterProcessCodecID ) )
4987                 {
4988                     KaxChapterProcessCodecID *p_codec_id = static_cast<KaxChapterProcessCodecID*>( k );
4989                     if ( uint32(*p_codec_id) == 0 )
4990                         p_ccodec = new matroska_script_codec_c( sys );
4991                     else if ( uint32(*p_codec_id) == 1 )
4992                         p_ccodec = new dvd_chapter_codec_c( sys );
4993                     break;
4994                 }
4995             }
4996
4997             if ( p_ccodec != NULL )
4998             {
4999                 for( j = 0; j < cp->ListSize(); j++ )
5000                 {
5001                     EbmlElement *k= (*cp)[j];
5002
5003                     if( MKV_IS_ID( k, KaxChapterProcessPrivate ) )
5004                     {
5005                         KaxChapterProcessPrivate * p_private = static_cast<KaxChapterProcessPrivate*>( k );
5006                         p_ccodec->SetPrivate( *p_private );
5007                     }
5008                     else if( MKV_IS_ID( k, KaxChapterProcessCommand ) )
5009                     {
5010                         p_ccodec->AddCommand( *static_cast<KaxChapterProcessCommand*>( k ) );
5011                     }
5012                 }
5013                 chapters.codecs.push_back( p_ccodec );
5014             }
5015         }
5016         else if( MKV_IS_ID( l, KaxChapterAtom ) )
5017         {
5018             chapter_item_c *new_sub_chapter = new chapter_item_c();
5019             ParseChapterAtom( i_level+1, static_cast<KaxChapterAtom *>(l), *new_sub_chapter );
5020             new_sub_chapter->psz_parent = &chapters;
5021             chapters.sub_chapters.push_back( new_sub_chapter );
5022         }
5023     }
5024 }
5025
5026 /*****************************************************************************
5027  * ParseAttachments:
5028  *****************************************************************************/
5029 void matroska_segment_c::ParseAttachments( KaxAttachments *attachments )
5030 {
5031     EbmlElement *el;
5032     int i_upper_level = 0;
5033
5034     attachments->Read( es, attachments->Generic().Context, i_upper_level, el, true );
5035
5036     KaxAttached *attachedFile = FindChild<KaxAttached>( *attachments );
5037
5038     while( attachedFile && ( attachedFile->GetSize() > 0 ) )
5039     {
5040         std::string psz_mime_type  = GetChild<KaxMimeType>( *attachedFile );
5041         KaxFileName  &file_name    = GetChild<KaxFileName>( *attachedFile );
5042         KaxFileData  &img_data     = GetChild<KaxFileData>( *attachedFile );
5043
5044         attachment_c *new_attachment = new attachment_c();
5045
5046         if( new_attachment )
5047         {
5048             char* tmp = ToUTF8( UTFstring( file_name ) );
5049             new_attachment->psz_file_name  = tmp;
5050             free( tmp );
5051             new_attachment->psz_mime_type  = psz_mime_type;
5052             new_attachment->i_size         = img_data.GetSize();
5053             new_attachment->p_data         = malloc( img_data.GetSize() );
5054
5055             if( new_attachment->p_data )
5056             {
5057                 memcpy( new_attachment->p_data, img_data.GetBuffer(), img_data.GetSize() );
5058                 sys.stored_attachments.push_back( new_attachment );
5059             }
5060             else
5061             {
5062                 delete new_attachment;
5063             }
5064         }
5065
5066         attachedFile = &GetNextChild<KaxAttached>( *attachments, *attachedFile );
5067     }
5068 }
5069
5070 /*****************************************************************************
5071  * ParseChapters:
5072  *****************************************************************************/
5073 void matroska_segment_c::ParseChapters( KaxChapters *chapters )
5074 {
5075     EbmlElement *el;
5076     size_t i;
5077     int i_upper_level = 0;
5078     mtime_t i_dur;
5079
5080     /* Master elements */
5081     chapters->Read( es, chapters->Generic().Context, i_upper_level, el, true );
5082
5083     for( i = 0; i < chapters->ListSize(); i++ )
5084     {
5085         EbmlElement *l = (*chapters)[i];
5086
5087         if( MKV_IS_ID( l, KaxEditionEntry ) )
5088         {
5089             chapter_edition_c *p_edition = new chapter_edition_c();
5090  
5091             EbmlMaster *E = static_cast<EbmlMaster *>(l );
5092             size_t j;
5093             msg_Dbg( &sys.demuxer, "|   |   + EditionEntry" );
5094             for( j = 0; j < E->ListSize(); j++ )
5095             {
5096                 EbmlElement *l = (*E)[j];
5097
5098                 if( MKV_IS_ID( l, KaxChapterAtom ) )
5099                 {
5100                     chapter_item_c *new_sub_chapter = new chapter_item_c();
5101                     ParseChapterAtom( 0, static_cast<KaxChapterAtom *>(l), *new_sub_chapter );
5102                     p_edition->sub_chapters.push_back( new_sub_chapter );
5103                 }
5104                 else if( MKV_IS_ID( l, KaxEditionUID ) )
5105                 {
5106                     p_edition->i_uid = uint64(*static_cast<KaxEditionUID *>( l ));
5107                 }
5108                 else if( MKV_IS_ID( l, KaxEditionFlagOrdered ) )
5109                 {
5110                     p_edition->b_ordered = config_GetInt( &sys.demuxer, "mkv-use-ordered-chapters" ) ? (uint8(*static_cast<KaxEditionFlagOrdered *>( l )) != 0) : 0;
5111                 }
5112                 else if( MKV_IS_ID( l, KaxEditionFlagDefault ) )
5113                 {
5114                     if (uint8(*static_cast<KaxEditionFlagDefault *>( l )) != 0)
5115                         i_default_edition = stored_editions.size();
5116                 }
5117                 else
5118                 {
5119                     msg_Dbg( &sys.demuxer, "|   |   |   + Unknown (%s)", typeid(*l).name() );
5120                 }
5121             }
5122             stored_editions.push_back( p_edition );
5123         }
5124         else
5125         {
5126             msg_Dbg( &sys.demuxer, "|   |   + Unknown (%s)", typeid(*l).name() );
5127         }
5128     }
5129
5130     for( i = 0; i < stored_editions.size(); i++ )
5131     {
5132         stored_editions[i]->RefreshChapters( );
5133     }
5134  
5135     if ( stored_editions.size() != 0 && stored_editions[i_default_edition]->b_ordered )
5136     {
5137         /* update the duration of the segment according to the sum of all sub chapters */
5138         i_dur = stored_editions[i_default_edition]->Duration() / INT64_C(1000);
5139         if (i_dur > 0)
5140             i_duration = i_dur;
5141     }
5142 }
5143
5144 void matroska_segment_c::ParseCluster( )
5145 {
5146     EbmlElement *el;
5147     EbmlMaster  *m;
5148     unsigned int i;
5149     int i_upper_level = 0;
5150
5151     /* Master elements */
5152     m = static_cast<EbmlMaster *>( cluster );
5153     m->Read( es, cluster->Generic().Context, i_upper_level, el, true );
5154
5155     for( i = 0; i < m->ListSize(); i++ )
5156     {
5157         EbmlElement *l = (*m)[i];
5158
5159         if( MKV_IS_ID( l, KaxClusterTimecode ) )
5160         {
5161             KaxClusterTimecode &ctc = *(KaxClusterTimecode*)l;
5162
5163             cluster->InitTimecode( uint64( ctc ), i_timescale );
5164             break;
5165         }
5166     }
5167
5168     i_start_time = cluster->GlobalTimecode() / 1000;
5169 }
5170
5171 /*****************************************************************************
5172  * InformationCreate:
5173  *****************************************************************************/
5174 void matroska_segment_c::InformationCreate( )
5175 {
5176     sys.meta = vlc_meta_New();
5177
5178     if( psz_title )
5179     {
5180         vlc_meta_SetTitle( sys.meta, psz_title );
5181     }
5182     if( psz_date_utc )
5183     {
5184         vlc_meta_SetDate( sys.meta, psz_date_utc );
5185     }
5186 #if 0
5187     if( psz_segment_filename )
5188     {
5189         fprintf( stderr, "***** WARNING: Unhandled meta - Use custom\n" );
5190     }
5191     if( psz_muxing_application )
5192     {
5193         fprintf( stderr, "***** WARNING: Unhandled meta - Use custom\n" );
5194     }
5195     if( psz_writing_application )
5196     {
5197         fprintf( stderr, "***** WARNING: Unhandled meta - Use custom\n" );
5198     }
5199
5200     for( size_t i_track = 0; i_track < tracks.size(); i_track++ )
5201     {
5202 //        mkv_track_t *tk = tracks[i_track];
5203 //        vlc_meta_t *mtk = vlc_meta_New();
5204         fprintf( stderr, "***** WARNING: Unhandled child meta\n");
5205     }
5206 #endif
5207 #if 0
5208     if( i_tags_position >= 0 )
5209     {
5210         bool b_seekable;
5211
5212         stream_Control( sys.demuxer.s, STREAM_CAN_FASTSEEK, &b_seekable );
5213         if( b_seekable )
5214         {
5215             LoadTags( );
5216         }
5217     }
5218 #endif
5219 }
5220
5221
5222 /*****************************************************************************
5223  * Misc
5224  *****************************************************************************/
5225
5226 void matroska_segment_c::IndexAppendCluster( KaxCluster *cluster )
5227 {
5228 #define idx p_indexes[i_index]
5229     idx.i_track       = -1;
5230     idx.i_block_number= -1;
5231     idx.i_position    = cluster->GetElementPosition();
5232     idx.i_time        = -1;
5233     idx.b_key         = true;
5234
5235     i_index++;
5236     if( i_index >= i_index_max )
5237     {
5238         i_index_max += 1024;
5239         p_indexes = (mkv_index_t*)realloc( p_indexes, sizeof( mkv_index_t ) * i_index_max );
5240     }
5241 #undef idx
5242 }
5243
5244 void chapter_edition_c::RefreshChapters( )
5245 {
5246     chapter_item_c::RefreshChapters( b_ordered, -1 );
5247     b_display_seekpoint = false;
5248 }
5249
5250 int64_t chapter_item_c::RefreshChapters( bool b_ordered, int64_t i_prev_user_time )
5251 {
5252     int64_t i_user_time = i_prev_user_time;
5253  
5254     // first the sub-chapters, and then ourself
5255     std::vector<chapter_item_c*>::iterator index = sub_chapters.begin();
5256     while ( index != sub_chapters.end() )
5257     {
5258         i_user_time = (*index)->RefreshChapters( b_ordered, i_user_time );
5259         index++;
5260     }
5261
5262     if ( b_ordered )
5263     {
5264         // the ordered chapters always start at zero
5265         if ( i_prev_user_time == -1 )
5266         {
5267             if ( i_user_time == -1 )
5268                 i_user_time = 0;
5269             i_prev_user_time = 0;
5270         }
5271
5272         i_user_start_time = i_prev_user_time;
5273         if ( i_end_time != -1 && i_user_time == i_prev_user_time )
5274         {
5275             i_user_end_time = i_user_start_time - i_start_time + i_end_time;
5276         }
5277         else
5278         {
5279             i_user_end_time = i_user_time;
5280         }
5281     }
5282     else
5283     {
5284         if ( sub_chapters.begin() != sub_chapters.end() )
5285             std::sort( sub_chapters.begin(), sub_chapters.end(), chapter_item_c::CompareTimecode );
5286         i_user_start_time = i_start_time;
5287         if ( i_end_time != -1 )
5288             i_user_end_time = i_end_time;
5289         else if ( i_user_time != -1 )
5290             i_user_end_time = i_user_time;
5291         else
5292             i_user_end_time = i_user_start_time;
5293     }
5294
5295     return i_user_end_time;
5296 }
5297
5298 mtime_t chapter_edition_c::Duration() const
5299 {
5300     mtime_t i_result = 0;
5301  
5302     if ( sub_chapters.size() )
5303     {
5304         std::vector<chapter_item_c*>::const_iterator index = sub_chapters.end();
5305         index--;
5306         i_result = (*index)->i_user_end_time;
5307     }
5308  
5309     return i_result;
5310 }
5311
5312 chapter_item_c * chapter_edition_c::FindTimecode( mtime_t i_timecode, const chapter_item_c * p_current )
5313 {
5314     if ( !b_ordered )
5315         p_current = NULL;
5316     bool b_found_current = false;
5317     return chapter_item_c::FindTimecode( i_timecode, p_current, b_found_current );
5318 }
5319
5320 chapter_item_c *chapter_item_c::FindTimecode( mtime_t i_user_timecode, const chapter_item_c * p_current, bool & b_found )
5321 {
5322     chapter_item_c *psz_result = NULL;
5323
5324     if ( p_current == this )
5325         b_found = true;
5326
5327     if ( i_user_timecode >= i_user_start_time &&
5328         ( i_user_timecode < i_user_end_time ||
5329           ( i_user_start_time == i_user_end_time && i_user_timecode == i_user_end_time )))
5330     {
5331         std::vector<chapter_item_c*>::iterator index = sub_chapters.begin();
5332         while ( index != sub_chapters.end() && ((p_current == NULL && psz_result == NULL) || (p_current != NULL && (!b_found || psz_result == NULL))))
5333         {
5334             psz_result = (*index)->FindTimecode( i_user_timecode, p_current, b_found );
5335             index++;
5336         }
5337  
5338         if ( psz_result == NULL )
5339             psz_result = this;
5340     }
5341
5342     return psz_result;
5343 }
5344
5345 bool chapter_item_c::ParentOf( const chapter_item_c & item ) const
5346 {
5347     if ( &item == this )
5348         return true;
5349
5350     std::vector<chapter_item_c*>::const_iterator index = sub_chapters.begin();
5351     while ( index != sub_chapters.end() )
5352     {
5353         if ( (*index)->ParentOf( item ) )
5354             return true;
5355         index++;
5356     }
5357
5358     return false;
5359 }
5360
5361 void demux_sys_t::PreloadFamily( const matroska_segment_c & of_segment )
5362 {
5363     for (size_t i=0; i<opened_segments.size(); i++)
5364     {
5365         opened_segments[i]->PreloadFamily( of_segment );
5366     }
5367 }
5368 bool matroska_segment_c::PreloadFamily( const matroska_segment_c & of_segment )
5369 {
5370     if ( b_preloaded )
5371         return false;
5372
5373     for (size_t i=0; i<families.size(); i++)
5374     {
5375         for (size_t j=0; j<of_segment.families.size(); j++)
5376         {
5377             if ( *(families[i]) == *(of_segment.families[j]) )
5378                 return Preload( );
5379         }
5380     }
5381
5382     return false;
5383 }
5384
5385 // preload all the linked segments for all preloaded segments
5386 void demux_sys_t::PreloadLinked( matroska_segment_c *p_segment )
5387 {
5388     size_t i_preloaded, i, j;
5389     virtual_segment_c *p_seg;
5390
5391     p_current_segment = VirtualFromSegments( p_segment );
5392  
5393     used_segments.push_back( p_current_segment );
5394
5395     // create all the other virtual segments of the family
5396     do {
5397         i_preloaded = 0;
5398         for ( i=0; i< opened_segments.size(); i++ )
5399         {
5400             if ( opened_segments[i]->b_preloaded && !IsUsedSegment( *opened_segments[i] ) )
5401             {
5402                 p_seg = VirtualFromSegments( opened_segments[i] );
5403                 used_segments.push_back( p_seg );
5404                 i_preloaded++;
5405             }
5406         }
5407     } while ( i_preloaded ); // worst case: will stop when all segments are found as family related
5408
5409     // publish all editions of all usable segment
5410     for ( i=0; i< used_segments.size(); i++ )
5411     {
5412         p_seg = used_segments[i];
5413         if ( p_seg->p_editions != NULL )
5414         {
5415             std::string sz_name;
5416             input_title_t *p_title = vlc_input_title_New();
5417             p_seg->i_sys_title = i;
5418             int i_chapters;
5419
5420             // TODO use a name for each edition, let the TITLE deal with a codec name
5421             for ( j=0; j<p_seg->p_editions->size(); j++ )
5422             {
5423                 if ( p_title->psz_name == NULL )
5424                 {
5425                     sz_name = (*p_seg->p_editions)[j]->GetMainName();
5426                     if ( sz_name != "" )
5427                         p_title->psz_name = strdup( sz_name.c_str() );
5428                 }
5429
5430                 chapter_edition_c *p_edition = (*p_seg->p_editions)[j];
5431
5432                 i_chapters = 0;
5433                 p_edition->PublishChapters( *p_title, i_chapters, 0 );
5434             }
5435
5436             // create a name if there is none
5437             if ( p_title->psz_name == NULL )
5438             {
5439                 sz_name = N_("Segment");
5440                 char psz_str[6];
5441                 sprintf( psz_str, " %d", (int)i );
5442                 sz_name += psz_str;
5443                 p_title->psz_name = strdup( sz_name.c_str() );
5444             }
5445
5446             titles.push_back( p_title );
5447         }
5448     }
5449
5450     // TODO decide which segment should be first used (VMG for DVD)
5451 }
5452
5453 bool demux_sys_t::IsUsedSegment( matroska_segment_c &segment ) const
5454 {
5455     for ( size_t i=0; i< used_segments.size(); i++ )
5456     {
5457         if ( used_segments[i]->FindUID( *segment.p_segment_uid ) )
5458             return true;
5459     }
5460     return false;
5461 }
5462
5463 virtual_segment_c *demux_sys_t::VirtualFromSegments( matroska_segment_c *p_segment ) const
5464 {
5465     size_t i_preloaded, i;
5466
5467     virtual_segment_c *p_result = new virtual_segment_c( p_segment );
5468
5469     // fill our current virtual segment with all hard linked segments
5470     do {
5471         i_preloaded = 0;
5472         for ( i=0; i< opened_segments.size(); i++ )
5473         {
5474             i_preloaded += p_result->AddSegment( opened_segments[i] );
5475         }
5476     } while ( i_preloaded ); // worst case: will stop when all segments are found as linked
5477
5478     p_result->Sort( );
5479
5480     p_result->PreloadLinked( );
5481
5482     p_result->PrepareChapters( );
5483
5484     return p_result;
5485 }
5486
5487 bool demux_sys_t::PreparePlayback( virtual_segment_c *p_new_segment )
5488 {
5489     if ( p_new_segment != NULL && p_new_segment != p_current_segment )
5490     {
5491         if ( p_current_segment != NULL && p_current_segment->Segment() != NULL )
5492             p_current_segment->Segment()->UnSelect();
5493
5494         p_current_segment = p_new_segment;
5495         i_current_title = p_new_segment->i_sys_title;
5496     }
5497     if( !p_current_segment->Segment()->b_cues )
5498         msg_Warn( &p_current_segment->Segment()->sys.demuxer, "no cues/empty cues found->seek won't be precise" );
5499
5500     f_duration = p_current_segment->Duration();
5501
5502     /* add information */
5503     p_current_segment->Segment()->InformationCreate( );
5504     p_current_segment->Segment()->Select( 0 );
5505
5506     return true;
5507 }
5508
5509 void demux_sys_t::JumpTo( virtual_segment_c & vsegment, chapter_item_c * p_chapter )
5510 {
5511     // if the segment is not part of the current segment, select the new one
5512     if ( &vsegment != p_current_segment )
5513     {
5514         PreparePlayback( &vsegment );
5515     }
5516
5517     if ( p_chapter != NULL )
5518     {
5519         if ( !p_chapter->Enter( true ) )
5520         {
5521             // jump to the location in the found segment
5522             vsegment.Seek( demuxer, p_chapter->i_user_start_time, -1, p_chapter, -1 );
5523         }
5524     }
5525  
5526 }
5527
5528 bool matroska_segment_c::CompareSegmentUIDs( const matroska_segment_c * p_item_a, const matroska_segment_c * p_item_b )
5529 {
5530     EbmlBinary *p_tmp;
5531
5532     if ( p_item_a == NULL || p_item_b == NULL )
5533         return false;
5534
5535     p_tmp = (EbmlBinary *)p_item_a->p_segment_uid;
5536     if ( p_item_b->p_prev_segment_uid != NULL
5537           && *p_tmp == *p_item_b->p_prev_segment_uid )
5538         return true;
5539
5540     p_tmp = (EbmlBinary *)p_item_a->p_next_segment_uid;
5541     if ( !p_tmp )
5542         return false;
5543  
5544     if ( p_item_b->p_segment_uid != NULL
5545           && *p_tmp == *p_item_b->p_segment_uid )
5546         return true;
5547
5548     if ( p_item_b->p_prev_segment_uid != NULL
5549           && *p_tmp == *p_item_b->p_prev_segment_uid )
5550         return true;
5551
5552     return false;
5553 }
5554
5555 bool matroska_segment_c::Preload( )
5556 {
5557     if ( b_preloaded )
5558         return false;
5559
5560     EbmlElement *el = NULL;
5561
5562     ep->Reset( &sys.demuxer );
5563
5564     while( ( el = ep->Get() ) != NULL )
5565     {
5566         if( MKV_IS_ID( el, KaxSeekHead ) )
5567         {
5568             /* Multiple allowed */
5569             /* We bail at 10, to prevent possible recursion */
5570             msg_Dbg(  &sys.demuxer, "|   + Seek head" );
5571             if( i_seekhead_count < 10 )
5572             {
5573                 i_seekhead_position = (int64_t) es.I_O().getFilePointer();
5574                 ParseSeekHead( static_cast<KaxSeekHead*>( el ) );
5575             }
5576         }
5577         else if( MKV_IS_ID( el, KaxInfo ) )
5578         {
5579             /* Multiple allowed, mandatory */
5580             msg_Dbg(  &sys.demuxer, "|   + Information" );
5581             if( i_info_position < 0 ) // FIXME
5582                 ParseInfo( static_cast<KaxInfo*>( el ) );
5583             i_info_position = (int64_t) es.I_O().getFilePointer();
5584         }
5585         else if( MKV_IS_ID( el, KaxTracks ) )
5586         {
5587             /* Multiple allowed */
5588             msg_Dbg(  &sys.demuxer, "|   + Tracks" );
5589             if( i_tracks_position < 0 ) // FIXME
5590                 ParseTracks( static_cast<KaxTracks*>( el ) );
5591             if ( tracks.size() == 0 )
5592             {
5593                 msg_Err( &sys.demuxer, "No tracks supported" );
5594                 return false;
5595             }
5596             i_tracks_position = (int64_t) es.I_O().getFilePointer();
5597         }
5598         else if( MKV_IS_ID( el, KaxCues ) )
5599         {
5600             msg_Dbg(  &sys.demuxer, "|   + Cues" );
5601             if( i_cues_position < 0 )
5602                 LoadCues( static_cast<KaxCues*>( el ) );
5603             i_cues_position = (int64_t) es.I_O().getFilePointer();
5604         }
5605         else if( MKV_IS_ID( el, KaxCluster ) )
5606         {
5607             msg_Dbg( &sys.demuxer, "|   + Cluster" );
5608
5609             cluster = (KaxCluster*)el;
5610
5611             i_cluster_pos = i_start_pos = cluster->GetElementPosition();
5612             ParseCluster( );
5613
5614             ep->Down();
5615             /* stop pre-parsing the stream */
5616             break;
5617         }
5618         else if( MKV_IS_ID( el, KaxAttachments ) )
5619         {
5620             msg_Dbg( &sys.demuxer, "|   + Attachments" );
5621             if( i_attachments_position < 0 )
5622                 ParseAttachments( static_cast<KaxAttachments*>( el ) );
5623             i_attachments_position = (int64_t) es.I_O().getFilePointer();
5624         }
5625         else if( MKV_IS_ID( el, KaxChapters ) )
5626         {
5627             msg_Dbg( &sys.demuxer, "|   + Chapters" );
5628             if( i_chapters_position < 0 )
5629                 ParseChapters( static_cast<KaxChapters*>( el ) );
5630             i_chapters_position = (int64_t) es.I_O().getFilePointer();
5631         }
5632         else if( MKV_IS_ID( el, KaxTag ) )
5633         {
5634             msg_Dbg( &sys.demuxer, "|   + Tags" );
5635             if( i_tags_position < 0) // FIXME
5636                 ;//LoadTags( static_cast<KaxTags*>( el ) );
5637             i_tags_position = (int64_t) es.I_O().getFilePointer();
5638         }
5639         else
5640             msg_Dbg( &sys.demuxer, "|   + Preload Unknown (%s)", typeid(*el).name() );
5641     }
5642
5643     b_preloaded = true;
5644
5645     return true;
5646 }
5647
5648 /* Here we try to load elements that were found in Seek Heads, but not yet parsed */
5649 bool matroska_segment_c::LoadSeekHeadItem( const EbmlCallbacks & ClassInfos, int64_t i_element_position )
5650 {
5651     int64_t     i_sav_position = (int64_t)es.I_O().getFilePointer();
5652     EbmlElement *el;
5653
5654     es.I_O().setFilePointer( i_element_position, seek_beginning );
5655     el = es.FindNextID( ClassInfos, 0xFFFFFFFFL);
5656
5657     if( el == NULL )
5658     {
5659         msg_Err( &sys.demuxer, "cannot load some cues/chapters/tags etc. (broken seekhead or file)" );
5660         es.I_O().setFilePointer( i_sav_position, seek_beginning );
5661         return false;
5662     }
5663
5664     if( MKV_IS_ID( el, KaxSeekHead ) )
5665     {
5666         /* Multiple allowed */
5667         msg_Dbg( &sys.demuxer, "|   + Seek head" );
5668         if( i_seekhead_count < 10 )
5669         {
5670             i_seekhead_position = i_element_position;
5671             ParseSeekHead( static_cast<KaxSeekHead*>( el ) );
5672         }
5673     }
5674     else if( MKV_IS_ID( el, KaxInfo ) ) // FIXME
5675     {
5676         /* Multiple allowed, mandatory */
5677         msg_Dbg( &sys.demuxer, "|   + Information" );
5678         if( i_info_position < 0 )
5679             ParseInfo( static_cast<KaxInfo*>( el ) );
5680         i_info_position = i_element_position;
5681     }
5682     else if( MKV_IS_ID( el, KaxTracks ) ) // FIXME
5683     {
5684         /* Multiple allowed */
5685         msg_Dbg( &sys.demuxer, "|   + Tracks" );
5686         if( i_tracks_position < 0 )
5687             ParseTracks( static_cast<KaxTracks*>( el ) );
5688         if ( tracks.size() == 0 )
5689         {
5690             msg_Err( &sys.demuxer, "No tracks supported" );
5691             delete el;
5692             es.I_O().setFilePointer( i_sav_position, seek_beginning );
5693             return false;
5694         }
5695         i_tracks_position = i_element_position;
5696     }
5697     else if( MKV_IS_ID( el, KaxCues ) )
5698     {
5699         msg_Dbg( &sys.demuxer, "|   + Cues" );
5700         if( i_cues_position < 0 )
5701             LoadCues( static_cast<KaxCues*>( el ) );
5702         i_cues_position = i_element_position;
5703     }
5704     else if( MKV_IS_ID( el, KaxAttachments ) )
5705     {
5706         msg_Dbg( &sys.demuxer, "|   + Attachments" );
5707         if( i_attachments_position < 0 )
5708             ParseAttachments( static_cast<KaxAttachments*>( el ) );
5709         i_attachments_position = i_element_position;
5710     }
5711     else if( MKV_IS_ID( el, KaxChapters ) )
5712     {
5713         msg_Dbg( &sys.demuxer, "|   + Chapters" );
5714         if( i_chapters_position < 0 )
5715             ParseChapters( static_cast<KaxChapters*>( el ) );
5716         i_chapters_position = i_element_position;
5717     }
5718     else if( MKV_IS_ID( el, KaxTag ) ) // FIXME
5719     {
5720         msg_Dbg( &sys.demuxer, "|   + Tags" );
5721         if( i_tags_position < 0 )
5722             ;//LoadTags( static_cast<KaxTags*>( el ) );
5723         i_tags_position = i_element_position;
5724     }
5725     else
5726     {
5727         msg_Dbg( &sys.demuxer, "|   + LoadSeekHeadItem Unknown (%s)", typeid(*el).name() );
5728     }
5729     delete el;
5730
5731     es.I_O().setFilePointer( i_sav_position, seek_beginning );
5732     return true;
5733 }
5734
5735 matroska_segment_c *demux_sys_t::FindSegment( const EbmlBinary & uid ) const
5736 {
5737     for (size_t i=0; i<opened_segments.size(); i++)
5738     {
5739         if ( *opened_segments[i]->p_segment_uid == uid )
5740             return opened_segments[i];
5741     }
5742     return NULL;
5743 }
5744
5745 chapter_item_c *demux_sys_t::BrowseCodecPrivate( unsigned int codec_id,
5746                                         bool (*match)(const chapter_codec_cmds_c &data, const void *p_cookie, size_t i_cookie_size ),
5747                                         const void *p_cookie,
5748                                         size_t i_cookie_size,
5749                                         virtual_segment_c * &p_segment_found )
5750 {
5751     chapter_item_c *p_result = NULL;
5752     for (size_t i=0; i<used_segments.size(); i++)
5753     {
5754         p_result = used_segments[i]->BrowseCodecPrivate( codec_id, match, p_cookie, i_cookie_size );
5755         if ( p_result != NULL )
5756         {
5757             p_segment_found = used_segments[i];
5758             break;
5759         }
5760     }
5761     return p_result;
5762 }
5763
5764 chapter_item_c *demux_sys_t::FindChapter( int64_t i_find_uid, virtual_segment_c * & p_segment_found )
5765 {
5766     chapter_item_c *p_result = NULL;
5767     for (size_t i=0; i<used_segments.size(); i++)
5768     {
5769         p_result = used_segments[i]->FindChapter( i_find_uid );
5770         if ( p_result != NULL )
5771         {
5772             p_segment_found = used_segments[i];
5773             break;
5774         }
5775     }
5776     return p_result;
5777 }
5778
5779 void virtual_segment_c::Sort()
5780 {
5781     // keep the current segment index
5782     matroska_segment_c *p_segment = linked_segments[i_current_segment];
5783
5784     std::sort( linked_segments.begin(), linked_segments.end(), matroska_segment_c::CompareSegmentUIDs );
5785
5786     for ( i_current_segment=0; i_current_segment<linked_segments.size(); i_current_segment++)
5787         if ( linked_segments[i_current_segment] == p_segment )
5788             break;
5789 }
5790
5791 size_t virtual_segment_c::AddSegment( matroska_segment_c *p_segment )
5792 {
5793     size_t i;
5794     // check if it's not already in here
5795     for ( i=0; i<linked_segments.size(); i++ )
5796     {
5797         if ( linked_segments[i]->p_segment_uid != NULL
5798             && p_segment->p_segment_uid != NULL
5799             && *p_segment->p_segment_uid == *linked_segments[i]->p_segment_uid )
5800             return 0;
5801     }
5802
5803     // find possible mates
5804     for ( i=0; i<linked_uids.size(); i++ )
5805     {
5806         if (   (p_segment->p_segment_uid != NULL && *p_segment->p_segment_uid == linked_uids[i])
5807             || (p_segment->p_prev_segment_uid != NULL && *p_segment->p_prev_segment_uid == linked_uids[i])
5808             || (p_segment->p_next_segment_uid !=NULL && *p_segment->p_next_segment_uid == linked_uids[i]) )
5809         {
5810             linked_segments.push_back( p_segment );
5811
5812             AppendUID( p_segment->p_prev_segment_uid );
5813             AppendUID( p_segment->p_next_segment_uid );
5814
5815             return 1;
5816         }
5817     }
5818     return 0;
5819 }
5820
5821 void virtual_segment_c::PreloadLinked( )
5822 {
5823     for ( size_t i=0; i<linked_segments.size(); i++ )
5824     {
5825         linked_segments[i]->Preload( );
5826     }
5827     i_current_edition = linked_segments[0]->i_default_edition;
5828 }
5829
5830 mtime_t virtual_segment_c::Duration() const
5831 {
5832     mtime_t i_duration;
5833     if ( linked_segments.size() == 0 )
5834         i_duration = 0;
5835     else {
5836         matroska_segment_c *p_last_segment = linked_segments[linked_segments.size()-1];
5837 //        p_last_segment->ParseCluster( );
5838
5839         i_duration = p_last_segment->i_start_time / 1000 + p_last_segment->i_duration;
5840     }
5841     return i_duration;
5842 }
5843
5844 void virtual_segment_c::AppendUID( const EbmlBinary * p_UID )
5845 {
5846     if ( p_UID == NULL )
5847         return;
5848     if ( p_UID->GetBuffer() == NULL )
5849         return;
5850
5851     for (size_t i=0; i<linked_uids.size(); i++)
5852     {
5853         if ( *p_UID == linked_uids[i] )
5854             return;
5855     }
5856     linked_uids.push_back( *(KaxSegmentUID*)(p_UID) );
5857 }
5858
5859 void matroska_segment_c::Seek( mtime_t i_date, mtime_t i_time_offset, int64_t i_global_position )
5860 {
5861     KaxBlock    *block;
5862 #if LIBMATROSKA_VERSION >= 0x000800
5863     KaxSimpleBlock *simpleblock;
5864 #endif
5865     int         i_track_skipping;
5866     int64_t     i_block_duration;
5867     int64_t     i_block_ref1;
5868     int64_t     i_block_ref2;
5869     size_t      i_track;
5870     int64_t     i_seek_position = i_start_pos;
5871     int64_t     i_seek_time = i_start_time;
5872
5873     if( i_global_position >= 0 )
5874     {
5875         /* Special case for seeking in files with no cues */
5876         EbmlElement *el = NULL;
5877         es.I_O().setFilePointer( i_start_pos, seek_beginning );
5878         delete ep;
5879         ep = new EbmlParser( &es, segment, &sys.demuxer );
5880         cluster = NULL;
5881
5882         while( ( el = ep->Get() ) != NULL )
5883         {
5884             if( MKV_IS_ID( el, KaxCluster ) )
5885             {
5886                 cluster = (KaxCluster *)el;
5887                 i_cluster_pos = cluster->GetElementPosition();
5888                 if( i_index == 0 ||
5889                         ( i_index > 0 && p_indexes[i_index - 1].i_position < (int64_t)cluster->GetElementPosition() ) )
5890                 {
5891                     IndexAppendCluster( cluster );
5892                 }
5893                 if( es.I_O().getFilePointer() >= i_global_position )
5894                 {
5895                     ParseCluster();
5896                     msg_Dbg( &sys.demuxer, "we found a cluster that is in the neighbourhood" );
5897                     es_out_Control( sys.demuxer.out, ES_OUT_RESET_PCR );
5898                     return;
5899                 }
5900             }
5901         }
5902         msg_Err( &sys.demuxer, "This file has no cues, and we were unable to seek to the requested position by parsing." );
5903         return;
5904     }
5905
5906     if ( i_index > 0 )
5907     {
5908         int i_idx = 0;
5909
5910         for( ; i_idx < i_index; i_idx++ )
5911         {
5912             if( p_indexes[i_idx].i_time + i_time_offset > i_date )
5913             {
5914                 break;
5915             }
5916         }
5917
5918         if( i_idx > 0 )
5919         {
5920             i_idx--;
5921         }
5922
5923         i_seek_position = p_indexes[i_idx].i_position;
5924         i_seek_time = p_indexes[i_idx].i_time;
5925     }
5926
5927     msg_Dbg( &sys.demuxer, "seek got %"PRId64" (%d%%)",
5928                 i_seek_time, (int)( 100 * i_seek_position / stream_Size( sys.demuxer.s ) ) );
5929
5930     es.I_O().setFilePointer( i_seek_position, seek_beginning );
5931
5932     delete ep;
5933     ep = new EbmlParser( &es, segment, &sys.demuxer );
5934     cluster = NULL;
5935
5936     sys.i_start_pts = i_date;
5937
5938     es_out_Control( sys.demuxer.out, ES_OUT_RESET_PCR );
5939
5940     /* now parse until key frame */
5941     i_track_skipping = 0;
5942     for( i_track = 0; i_track < tracks.size(); i_track++ )
5943     {
5944         if( tracks[i_track]->fmt.i_cat == VIDEO_ES )
5945         {
5946             tracks[i_track]->b_search_keyframe = true;
5947             i_track_skipping++;
5948         }
5949         es_out_Control( sys.demuxer.out, ES_OUT_SET_NEXT_DISPLAY_TIME, tracks[i_track]->p_es, i_date );
5950     }
5951
5952     while( i_track_skipping > 0 )
5953     {
5954 #if LIBMATROSKA_VERSION >= 0x000800
5955         if( BlockGet( block, simpleblock, &i_block_ref1, &i_block_ref2, &i_block_duration ) )
5956 #else
5957         if( BlockGet( block, &i_block_ref1, &i_block_ref2, &i_block_duration ) )
5958 #endif
5959         {
5960             msg_Warn( &sys.demuxer, "cannot get block EOF?" );
5961
5962             return;
5963         }
5964         ep->Down();
5965
5966         for( i_track = 0; i_track < tracks.size(); i_track++ )
5967         {
5968 #if LIBMATROSKA_VERSION >= 0x000800
5969             if( (simpleblock && tracks[i_track]->i_number == simpleblock->TrackNum()) ||
5970                 (block && tracks[i_track]->i_number == block->TrackNum()) )
5971 #else
5972             if( tracks[i_track]->i_number == block->TrackNum() )
5973 #endif
5974             {
5975                 break;
5976             }
5977         }
5978
5979 #if LIBMATROSKA_VERSION >= 0x000800
5980         if( simpleblock )
5981             sys.i_pts = (sys.i_chapter_time + simpleblock->GlobalTimecode()) / (mtime_t) 1000;
5982         else
5983 #endif
5984             sys.i_pts = (sys.i_chapter_time + block->GlobalTimecode()) / (mtime_t) 1000;
5985
5986         if( i_track < tracks.size() )
5987         {
5988             if( sys.i_pts >= sys.i_start_pts )
5989             {
5990                 cluster = static_cast<KaxCluster*>(ep->UnGet( i_block_pos, i_cluster_pos ));
5991                 i_track_skipping = 0;
5992             }
5993             else if( tracks[i_track]->fmt.i_cat == VIDEO_ES )
5994             {
5995                 if( i_block_ref1 == 0 && tracks[i_track]->b_search_keyframe )
5996                 {
5997                     tracks[i_track]->b_search_keyframe = false;
5998                     i_track_skipping--;
5999                 }
6000                 if( !tracks[i_track]->b_search_keyframe )
6001                 {
6002                     
6003             //es_out_Control( sys.demuxer.out, ES_OUT_SET_PCR, sys.i_pts );
6004 #if LIBMATROSKA_VERSION >= 0x000800
6005                     BlockDecode( &sys.demuxer, block, simpleblock, sys.i_pts, 0, i_block_ref1 >= 0 || i_block_ref2 > 0 );
6006 #else
6007                     BlockDecode( &sys.demuxer, block, sys.i_pts, 0, i_block_ref1 >= 0 || i_block_ref2 > 0 );
6008 #endif
6009                 }
6010             }
6011         }
6012
6013         delete block;
6014     }
6015
6016     /* FIXME current ES_OUT_SET_NEXT_DISPLAY_TIME does not work that well if
6017      * the delay is too high. */
6018     if( sys.i_pts + 500*1000 < sys.i_start_pts )
6019     {
6020         sys.i_start_pts = sys.i_pts;
6021
6022         for( i_track = 0; i_track < tracks.size(); i_track++ )
6023             es_out_Control( sys.demuxer.out, ES_OUT_SET_NEXT_DISPLAY_TIME, tracks[i_track]->p_es, sys.i_start_pts );
6024     }
6025 }
6026
6027 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 )
6028 {
6029     demux_sys_t *p_sys = demuxer.p_sys;
6030     size_t i;
6031
6032     // find the actual time for an ordered edition
6033     if ( psz_chapter == NULL )
6034     {
6035         if ( Edition() && Edition()->b_ordered )
6036         {
6037             /* 1st, we need to know in which chapter we are */
6038             psz_chapter = (*p_editions)[i_current_edition]->FindTimecode( i_date, psz_current_chapter );
6039         }
6040     }
6041
6042     if ( psz_chapter != NULL )
6043     {
6044         psz_current_chapter = psz_chapter;
6045         p_sys->i_chapter_time = i_time_offset = psz_chapter->i_user_start_time - psz_chapter->i_start_time;
6046         if ( psz_chapter->i_seekpoint_num > 0 )
6047         {
6048             demuxer.info.i_update |= INPUT_UPDATE_TITLE | INPUT_UPDATE_SEEKPOINT;
6049             demuxer.info.i_title = p_sys->i_current_title = i_sys_title;
6050             demuxer.info.i_seekpoint = psz_chapter->i_seekpoint_num - 1;
6051         }
6052     }
6053
6054     // find the best matching segment
6055     for ( i=0; i<linked_segments.size(); i++ )
6056     {
6057         if ( i_date < linked_segments[i]->i_start_time )
6058             break;
6059     }
6060
6061     if ( i > 0 )
6062         i--;
6063
6064     if ( i_current_segment != i  )
6065     {
6066         linked_segments[i_current_segment]->UnSelect();
6067         linked_segments[i]->Select( i_date );
6068         i_current_segment = i;
6069     }
6070
6071     linked_segments[i]->Seek( i_date, i_time_offset, i_global_position );
6072 }
6073
6074 void chapter_codec_cmds_c::AddCommand( const KaxChapterProcessCommand & command )
6075 {
6076     size_t i;
6077
6078     uint32 codec_time = uint32(-1);
6079     for( i = 0; i < command.ListSize(); i++ )
6080     {
6081         const EbmlElement *k = command[i];
6082
6083         if( MKV_IS_ID( k, KaxChapterProcessTime ) )
6084         {
6085             codec_time = uint32( *static_cast<const KaxChapterProcessTime*>( k ) );
6086             break;
6087         }
6088     }
6089
6090     for( i = 0; i < command.ListSize(); i++ )
6091     {
6092         const EbmlElement *k = command[i];
6093
6094         if( MKV_IS_ID( k, KaxChapterProcessData ) )
6095         {
6096             KaxChapterProcessData *p_data =  new KaxChapterProcessData( *static_cast<const KaxChapterProcessData*>( k ) );
6097             switch ( codec_time )
6098             {
6099             case 0:
6100                 during_cmds.push_back( p_data );
6101                 break;
6102             case 1:
6103                 enter_cmds.push_back( p_data );
6104                 break;
6105             case 2:
6106                 leave_cmds.push_back( p_data );
6107                 break;
6108             default:
6109                 delete p_data;
6110             }
6111         }
6112     }
6113 }
6114
6115 bool chapter_item_c::Enter( bool b_do_subs )
6116 {
6117     bool f_result = false;
6118     std::vector<chapter_codec_cmds_c*>::iterator index = codecs.begin();
6119     while ( index != codecs.end() )
6120     {
6121         f_result |= (*index)->Enter();
6122         index++;
6123     }
6124
6125     if ( b_do_subs )
6126     {
6127         // sub chapters
6128         std::vector<chapter_item_c*>::iterator index_ = sub_chapters.begin();
6129         while ( index_ != sub_chapters.end() )
6130         {
6131             f_result |= (*index_)->Enter( true );
6132             index_++;
6133         }
6134     }
6135     return f_result;
6136 }
6137
6138 bool chapter_item_c::Leave( bool b_do_subs )
6139 {
6140     bool f_result = false;
6141     b_is_leaving = true;
6142     std::vector<chapter_codec_cmds_c*>::iterator index = codecs.begin();
6143     while ( index != codecs.end() )
6144     {
6145         f_result |= (*index)->Leave();
6146         index++;
6147     }
6148
6149     if ( b_do_subs )
6150     {
6151         // sub chapters
6152         std::vector<chapter_item_c*>::iterator index_ = sub_chapters.begin();
6153         while ( index_ != sub_chapters.end() )
6154         {
6155             f_result |= (*index_)->Leave( true );
6156             index_++;
6157         }
6158     }
6159     b_is_leaving = false;
6160     return f_result;
6161 }
6162
6163 bool chapter_item_c::EnterAndLeave( chapter_item_c *p_item, bool b_final_enter )
6164 {
6165     chapter_item_c *p_common_parent = p_item;
6166
6167     // leave, up to a common parent
6168     while ( p_common_parent != NULL && !p_common_parent->ParentOf( *this ) )
6169     {
6170         if ( !p_common_parent->b_is_leaving && p_common_parent->Leave( false ) )
6171             return true;
6172         p_common_parent = p_common_parent->psz_parent;
6173     }
6174
6175     // enter from the parent to <this>
6176     if ( p_common_parent != NULL )
6177     {
6178         do
6179         {
6180             if ( p_common_parent == this )
6181                 return Enter( true );
6182
6183             for ( size_t i = 0; i<p_common_parent->sub_chapters.size(); i++ )
6184             {
6185                 if ( p_common_parent->sub_chapters[i]->ParentOf( *this ) )
6186                 {
6187                     p_common_parent = p_common_parent->sub_chapters[i];
6188                     if ( p_common_parent != this )
6189                         if ( p_common_parent->Enter( false ) )
6190                             return true;
6191
6192                     break;
6193                 }
6194             }
6195         } while ( 1 );
6196     }
6197
6198     if ( b_final_enter )
6199         return Enter( true );
6200     else
6201         return false;
6202 }
6203
6204 bool dvd_chapter_codec_c::Enter()
6205 {
6206     bool f_result = false;
6207     std::vector<KaxChapterProcessData*>::iterator index = enter_cmds.begin();
6208     while ( index != enter_cmds.end() )
6209     {
6210         if ( (*index)->GetSize() )
6211         {
6212             binary *p_data = (*index)->GetBuffer();
6213             size_t i_size = *p_data++;
6214             // avoid reading too much from the buffer
6215             i_size = __MIN( i_size, ((*index)->GetSize() - 1) >> 3 );
6216             for ( ; i_size > 0; i_size--, p_data += 8 )
6217             {
6218                 msg_Dbg( &sys.demuxer, "Matroska DVD enter command" );
6219                 f_result |= sys.dvd_interpretor.Interpret( p_data );
6220             }
6221         }
6222         index++;
6223     }
6224     return f_result;
6225 }
6226
6227 bool dvd_chapter_codec_c::Leave()
6228 {
6229     bool f_result = false;
6230     std::vector<KaxChapterProcessData*>::iterator index = leave_cmds.begin();
6231     while ( index != leave_cmds.end() )
6232     {
6233         if ( (*index)->GetSize() )
6234         {
6235             binary *p_data = (*index)->GetBuffer();
6236             size_t i_size = *p_data++;
6237             // avoid reading too much from the buffer
6238             i_size = __MIN( i_size, ((*index)->GetSize() - 1) >> 3 );
6239             for ( ; i_size > 0; i_size--, p_data += 8 )
6240             {
6241                 msg_Dbg( &sys.demuxer, "Matroska DVD leave command" );
6242                 f_result |= sys.dvd_interpretor.Interpret( p_data );
6243             }
6244         }
6245         index++;
6246     }
6247     return f_result;
6248 }
6249
6250 // see http://www.dvd-replica.com/DVD/vmcmdset.php for a description of DVD commands
6251 bool dvd_command_interpretor_c::Interpret( const binary * p_command, size_t i_size )
6252 {
6253     if ( i_size != 8 )
6254         return false;
6255
6256     virtual_segment_c *p_segment = NULL;
6257     chapter_item_c *p_chapter = NULL;
6258     bool f_result = false;
6259     uint16 i_command = ( p_command[0] << 8 ) + p_command[1];
6260
6261     // handle register tests if there are some
6262     if ( (i_command & 0xF0) != 0 )
6263     {
6264         bool b_test_positive = true;//(i_command & CMD_DVD_IF_NOT) == 0;
6265         bool b_test_value    = (i_command & CMD_DVD_TEST_VALUE) != 0;
6266         uint8 i_test = i_command & 0x70;
6267         uint16 i_value;
6268
6269         // see http://dvd.sourceforge.net/dvdinfo/vmi.html
6270         uint8  i_cr1;
6271         uint16 i_cr2;
6272         switch ( i_command >> 12 )
6273         {
6274         default:
6275             i_cr1 = p_command[3];
6276             i_cr2 = (p_command[4] << 8) + p_command[5];
6277             break;
6278         case 3:
6279         case 4:
6280         case 5:
6281             i_cr1 = p_command[6];
6282             i_cr2 = p_command[7];
6283             b_test_value = false;
6284             break;
6285         case 6:
6286         case 7:
6287             if ( ((p_command[1] >> 4) & 0x7) == 0)
6288             {
6289                 i_cr1 = p_command[2];
6290                 i_cr2 = (p_command[6] << 8) + p_command[7];
6291             }
6292             else
6293             {
6294                 i_cr1 = p_command[2];
6295                 i_cr2 = (p_command[6] << 8) + p_command[7];
6296             }
6297             break;
6298         }
6299
6300         if ( b_test_value )
6301             i_value = i_cr2;
6302         else
6303             i_value = GetPRM( i_cr2 );
6304
6305         switch ( i_test )
6306         {
6307         case CMD_DVD_IF_GPREG_EQUAL:
6308             // if equals
6309             msg_Dbg( &sys.demuxer, "IF %s EQUALS %s", GetRegTypeName( false, i_cr1 ).c_str(), GetRegTypeName( b_test_value, i_value ).c_str() );
6310             if (!( GetPRM( i_cr1 ) == i_value ))
6311             {
6312                 b_test_positive = false;
6313             }
6314             break;
6315         case CMD_DVD_IF_GPREG_NOT_EQUAL:
6316             // if not equals
6317             msg_Dbg( &sys.demuxer, "IF %s NOT EQUALS %s", GetRegTypeName( false, i_cr1 ).c_str(), GetRegTypeName( b_test_value, i_value ).c_str() );
6318             if (!( GetPRM( i_cr1 ) != i_value ))
6319             {
6320                 b_test_positive = false;
6321             }
6322             break;
6323         case CMD_DVD_IF_GPREG_INF:
6324             // if inferior
6325             msg_Dbg( &sys.demuxer, "IF %s < %s", GetRegTypeName( false, p_command[3] ).c_str(), GetRegTypeName( b_test_value, i_value ).c_str() );
6326             if (!( GetPRM( i_cr1 ) < i_value ))
6327             {
6328                 b_test_positive = false;
6329             }
6330             break;
6331         case CMD_DVD_IF_GPREG_INF_EQUAL:
6332             // if inferior or equal
6333             msg_Dbg( &sys.demuxer, "IF %s < %s", GetRegTypeName( false, p_command[3] ).c_str(), GetRegTypeName( b_test_value, i_value ).c_str() );
6334             if (!( GetPRM( i_cr1 ) <= i_value ))
6335             {
6336                 b_test_positive = false;
6337             }
6338             break;
6339         case CMD_DVD_IF_GPREG_AND:
6340             // if logical and
6341             msg_Dbg( &sys.demuxer, "IF %s & %s", GetRegTypeName( false, p_command[3] ).c_str(), GetRegTypeName( b_test_value, i_value ).c_str() );
6342             if (!( GetPRM( i_cr1 ) & i_value ))
6343             {
6344                 b_test_positive = false;
6345             }
6346             break;
6347         case CMD_DVD_IF_GPREG_SUP:
6348             // if superior
6349             msg_Dbg( &sys.demuxer, "IF %s >= %s", GetRegTypeName( false, p_command[3] ).c_str(), GetRegTypeName( b_test_value, i_value ).c_str() );
6350             if (!( GetPRM( i_cr1 ) > i_value ))
6351             {
6352                 b_test_positive = false;
6353             }
6354             break;
6355         case CMD_DVD_IF_GPREG_SUP_EQUAL:
6356             // if superior or equal
6357             msg_Dbg( &sys.demuxer, "IF %s >= %s", GetRegTypeName( false, p_command[3] ).c_str(), GetRegTypeName( b_test_value, i_value ).c_str() );
6358             if (!( GetPRM( i_cr1 ) >= i_value ))
6359             {
6360                 b_test_positive = false;
6361             }
6362             break;
6363         }
6364
6365         if ( !b_test_positive )
6366             return false;
6367     }
6368  
6369     // strip the test command
6370     i_command &= 0xFF0F;
6371  
6372     switch ( i_command )
6373     {
6374     case CMD_DVD_NOP:
6375     case CMD_DVD_NOP2:
6376         {
6377             msg_Dbg( &sys.demuxer, "NOP" );
6378             break;
6379         }
6380     case CMD_DVD_BREAK:
6381         {
6382             msg_Dbg( &sys.demuxer, "Break" );
6383             // TODO
6384             break;
6385         }
6386     case CMD_DVD_JUMP_TT:
6387         {
6388             uint8 i_title = p_command[5];
6389             msg_Dbg( &sys.demuxer, "JumpTT %d", i_title );
6390
6391             // find in the ChapProcessPrivate matching this Title level
6392             p_chapter = sys.BrowseCodecPrivate( 1, MatchTitleNumber, &i_title, sizeof(i_title), p_segment );
6393             if ( p_segment != NULL )
6394             {
6395                 sys.JumpTo( *p_segment, p_chapter );
6396                 f_result = true;
6397             }
6398
6399             break;
6400         }
6401     case CMD_DVD_CALLSS_VTSM1:
6402         {
6403             msg_Dbg( &sys.demuxer, "CallSS" );
6404             binary p_type;
6405             switch( (p_command[6] & 0xC0) >> 6 ) {
6406                 case 0:
6407                     p_type = p_command[5] & 0x0F;
6408                     switch ( p_type )
6409                     {
6410                     case 0x00:
6411                         msg_Dbg( &sys.demuxer, "CallSS PGC (rsm_cell %x)", p_command[4]);
6412                         break;
6413                     case 0x02:
6414                         msg_Dbg( &sys.demuxer, "CallSS Title Entry (rsm_cell %x)", p_command[4]);
6415                         break;
6416                     case 0x03:
6417                         msg_Dbg( &sys.demuxer, "CallSS Root Menu (rsm_cell %x)", p_command[4]);
6418                         break;
6419                     case 0x04:
6420                         msg_Dbg( &sys.demuxer, "CallSS Subpicture Menu (rsm_cell %x)", p_command[4]);
6421                         break;
6422                     case 0x05:
6423                         msg_Dbg( &sys.demuxer, "CallSS Audio Menu (rsm_cell %x)", p_command[4]);
6424                         break;
6425                     case 0x06:
6426                         msg_Dbg( &sys.demuxer, "CallSS Angle Menu (rsm_cell %x)", p_command[4]);
6427                         break;
6428                     case 0x07:
6429                         msg_Dbg( &sys.demuxer, "CallSS Chapter Menu (rsm_cell %x)", p_command[4]);
6430                         break;
6431                     default:
6432                         msg_Dbg( &sys.demuxer, "CallSS <unknown> (rsm_cell %x)", p_command[4]);
6433                         break;
6434                     }
6435                     p_chapter = sys.BrowseCodecPrivate( 1, MatchPgcType, &p_type, 1, p_segment );
6436                     if ( p_segment != NULL )
6437                     {
6438                         sys.JumpTo( *p_segment, p_chapter );
6439                         f_result = true;
6440                     }
6441                 break;
6442                 case 1:
6443                     msg_Dbg( &sys.demuxer, "CallSS VMGM (menu %d, rsm_cell %x)", p_command[5] & 0x0F, p_command[4]);
6444                 break;
6445                 case 2:
6446                     msg_Dbg( &sys.demuxer, "CallSS VTSM (menu %d, rsm_cell %x)", p_command[5] & 0x0F, p_command[4]);
6447                 break;
6448                 case 3:
6449                     msg_Dbg( &sys.demuxer, "CallSS VMGM (pgc %d, rsm_cell %x)", (p_command[2] << 8) + p_command[3], p_command[4]);
6450                 break;
6451             }
6452             break;
6453         }
6454     case CMD_DVD_JUMP_SS:
6455         {
6456             msg_Dbg( &sys.demuxer, "JumpSS");
6457             binary p_type;
6458             switch( (p_command[5] & 0xC0) >> 6 ) {
6459                 case 0:
6460                     msg_Dbg( &sys.demuxer, "JumpSS FP");
6461                 break;
6462                 case 1:
6463                     p_type = p_command[5] & 0x0F;
6464                     switch ( p_type )
6465                     {
6466                     case 0x02:
6467                         msg_Dbg( &sys.demuxer, "JumpSS VMGM Title Entry");
6468                         break;
6469                     case 0x03:
6470                         msg_Dbg( &sys.demuxer, "JumpSS VMGM Root Menu");
6471                         break;
6472                     case 0x04:
6473                         msg_Dbg( &sys.demuxer, "JumpSS VMGM Subpicture Menu");
6474                         break;
6475                     case 0x05:
6476                         msg_Dbg( &sys.demuxer, "JumpSS VMGM Audio Menu");
6477                         break;
6478                     case 0x06:
6479                         msg_Dbg( &sys.demuxer, "JumpSS VMGM Angle Menu");
6480                         break;
6481                     case 0x07:
6482                         msg_Dbg( &sys.demuxer, "JumpSS VMGM Chapter Menu");
6483                         break;
6484                     default:
6485                         msg_Dbg( &sys.demuxer, "JumpSS <unknown>");
6486                         break;
6487                     }
6488                     // find the VMG
6489                     p_chapter = sys.BrowseCodecPrivate( 1, MatchIsVMG, NULL, 0, p_segment );
6490                     if ( p_segment != NULL )
6491                     {
6492                         p_chapter = p_segment->BrowseCodecPrivate( 1, MatchPgcType, &p_type, 1 );
6493                         if ( p_chapter != NULL )
6494                         {
6495                             sys.JumpTo( *p_segment, p_chapter );
6496                             f_result = true;
6497                         }
6498                     }
6499                 break;
6500                 case 2:
6501                     p_type = p_command[5] & 0x0F;
6502                     switch ( p_type )
6503                     {
6504                     case 0x02:
6505                         msg_Dbg( &sys.demuxer, "JumpSS VTSM (vts %d, ttn %d) Title Entry", p_command[4], p_command[3]);
6506                         break;
6507                     case 0x03:
6508                         msg_Dbg( &sys.demuxer, "JumpSS VTSM (vts %d, ttn %d) Root Menu", p_command[4], p_command[3]);
6509                         break;
6510                     case 0x04:
6511                         msg_Dbg( &sys.demuxer, "JumpSS VTSM (vts %d, ttn %d) Subpicture Menu", p_command[4], p_command[3]);
6512                         break;
6513                     case 0x05:
6514                         msg_Dbg( &sys.demuxer, "JumpSS VTSM (vts %d, ttn %d) Audio Menu", p_command[4], p_command[3]);
6515                         break;
6516                     case 0x06:
6517                         msg_Dbg( &sys.demuxer, "JumpSS VTSM (vts %d, ttn %d) Angle Menu", p_command[4], p_command[3]);
6518                         break;
6519                     case 0x07:
6520                         msg_Dbg( &sys.demuxer, "JumpSS VTSM (vts %d, ttn %d) Chapter Menu", p_command[4], p_command[3]);
6521                         break;
6522                     default:
6523                         msg_Dbg( &sys.demuxer, "JumpSS VTSM (vts %d, ttn %d) <unknown>", p_command[4], p_command[3]);
6524                         break;
6525                     }
6526
6527                     p_chapter = sys.BrowseCodecPrivate( 1, MatchVTSMNumber, &p_command[4], 1, p_segment );
6528
6529                     if ( p_segment != NULL && p_chapter != NULL )
6530                     {
6531                         // find the title in the VTS
6532                         p_chapter = p_chapter->BrowseCodecPrivate( 1, MatchTitleNumber, &p_command[3], 1 );
6533                         if ( p_chapter != NULL )
6534                         {
6535                             // find the specified menu in the VTSM
6536                             p_chapter = p_segment->BrowseCodecPrivate( 1, MatchPgcType, &p_type, 1 );
6537                             if ( p_chapter != NULL )
6538                             {
6539                                 sys.JumpTo( *p_segment, p_chapter );
6540                                 f_result = true;
6541                             }
6542                         }
6543                         else
6544                             msg_Dbg( &sys.demuxer, "Title (%d) does not exist in this VTS", p_command[3] );
6545                     }
6546                     else
6547                         msg_Dbg( &sys.demuxer, "DVD Domain VTS (%d) not found", p_command[4] );
6548                 break;
6549                 case 3:
6550                     msg_Dbg( &sys.demuxer, "JumpSS VMGM (pgc %d)", (p_command[2] << 8) + p_command[3]);
6551                 break;
6552             }
6553             break;
6554         }
6555     case CMD_DVD_JUMPVTS_PTT:
6556         {
6557             uint8 i_title = p_command[5];
6558             uint8 i_ptt = p_command[3];
6559
6560             msg_Dbg( &sys.demuxer, "JumpVTS Title (%d) PTT (%d)", i_title, i_ptt);
6561
6562             // find the current VTS content segment
6563             p_chapter = sys.p_current_segment->BrowseCodecPrivate( 1, MatchIsDomain, NULL, 0 );
6564             if ( p_chapter != NULL )
6565             {
6566                 int16 i_curr_title = p_chapter->GetTitleNumber( );
6567                 if ( i_curr_title > 0 )
6568                 {
6569                     p_chapter = sys.BrowseCodecPrivate( 1, MatchVTSNumber, &i_curr_title, sizeof(i_curr_title), p_segment );
6570
6571                     if ( p_segment != NULL && p_chapter != NULL )
6572                     {
6573                         // find the title in the VTS
6574                         p_chapter = p_chapter->BrowseCodecPrivate( 1, MatchTitleNumber, &i_title, sizeof(i_title) );
6575                         if ( p_chapter != NULL )
6576                         {
6577                             // find the chapter in the title
6578                             p_chapter = p_chapter->BrowseCodecPrivate( 1, MatchChapterNumber, &i_ptt, sizeof(i_ptt) );
6579                             if ( p_chapter != NULL )
6580                             {
6581                                 sys.JumpTo( *p_segment, p_chapter );
6582                                 f_result = true;
6583                             }
6584                         }
6585                     else
6586                         msg_Dbg( &sys.demuxer, "Title (%d) does not exist in this VTS", i_title );
6587                     }
6588                     else
6589                         msg_Dbg( &sys.demuxer, "DVD Domain VTS (%d) not found", i_curr_title );
6590                 }
6591                 else
6592                     msg_Dbg( &sys.demuxer, "JumpVTS_PTT command found but not in a VTS(M)");
6593             }
6594             else
6595                 msg_Dbg( &sys.demuxer, "JumpVTS_PTT command but the DVD domain wasn't found");
6596             break;
6597         }
6598     case CMD_DVD_SET_GPRMMD:
6599         {
6600             msg_Dbg( &sys.demuxer, "Set GPRMMD [%d]=%d", (p_command[4] << 8) + p_command[5], (p_command[2] << 8) + p_command[3]);
6601  
6602             if ( !SetGPRM( (p_command[4] << 8) + p_command[5], (p_command[2] << 8) + p_command[3] ) )
6603                 msg_Dbg( &sys.demuxer, "Set GPRMMD failed" );
6604             break;
6605         }
6606     case CMD_DVD_LINKPGCN:
6607         {
6608             uint16 i_pgcn = (p_command[6] << 8) + p_command[7];
6609  
6610             msg_Dbg( &sys.demuxer, "Link PGCN(%d)", i_pgcn );
6611             p_chapter = sys.p_current_segment->BrowseCodecPrivate( 1, MatchPgcNumber, &i_pgcn, 2 );
6612             if ( p_chapter != NULL )
6613             {
6614                 if ( !p_chapter->Enter( true ) )
6615                     // jump to the location in the found segment
6616                     sys.p_current_segment->Seek( sys.demuxer, p_chapter->i_user_start_time, -1, p_chapter, -1 );
6617
6618                 f_result = true;
6619             }
6620             break;
6621         }
6622     case CMD_DVD_LINKCN:
6623         {
6624             uint8 i_cn = p_command[7];
6625  
6626             p_chapter = sys.p_current_segment->CurrentChapter();
6627
6628             msg_Dbg( &sys.demuxer, "LinkCN (cell %d)", i_cn );
6629             p_chapter = p_chapter->BrowseCodecPrivate( 1, MatchCellNumber, &i_cn, 1 );
6630             if ( p_chapter != NULL )
6631             {
6632                 if ( !p_chapter->Enter( true ) )
6633                     // jump to the location in the found segment
6634                     sys.p_current_segment->Seek( sys.demuxer, p_chapter->i_user_start_time, -1, p_chapter, -1 );
6635
6636                 f_result = true;
6637             }
6638             break;
6639         }
6640     case CMD_DVD_GOTO_LINE:
6641         {
6642             msg_Dbg( &sys.demuxer, "GotoLine (%d)", (p_command[6] << 8) + p_command[7] );
6643             // TODO
6644             break;
6645         }
6646     case CMD_DVD_SET_HL_BTNN1:
6647         {
6648             msg_Dbg( &sys.demuxer, "SetHL_BTN (%d)", p_command[4] );
6649             SetSPRM( 0x88, p_command[4] );
6650             break;
6651         }
6652     default:
6653         {
6654             msg_Dbg( &sys.demuxer, "unsupported command : %02X %02X %02X %02X %02X %02X %02X %02X"
6655                      ,p_command[0]
6656                      ,p_command[1]
6657                      ,p_command[2]
6658                      ,p_command[3]
6659                      ,p_command[4]
6660                      ,p_command[5]
6661                      ,p_command[6]
6662                      ,p_command[7]);
6663             break;
6664         }
6665     }
6666
6667     return f_result;
6668 }
6669
6670 bool dvd_command_interpretor_c::MatchIsDomain( const chapter_codec_cmds_c &data, const void *p_cookie, size_t i_cookie_size )
6671 {
6672     return ( data.p_private_data != NULL && data.p_private_data->GetBuffer()[0] == MATROSKA_DVD_LEVEL_SS );
6673 }
6674
6675 bool dvd_command_interpretor_c::MatchIsVMG( const chapter_codec_cmds_c &data, const void *p_cookie, size_t i_cookie_size )
6676 {
6677     if ( data.p_private_data == NULL || data.p_private_data->GetSize() < 2 )
6678         return false;
6679
6680     return ( data.p_private_data->GetBuffer()[0] == MATROSKA_DVD_LEVEL_SS && data.p_private_data->GetBuffer()[1] == 0xC0);
6681 }
6682
6683 bool dvd_command_interpretor_c::MatchVTSNumber( const chapter_codec_cmds_c &data, const void *p_cookie, size_t i_cookie_size )
6684 {
6685     if ( i_cookie_size != 2 || data.p_private_data == NULL || data.p_private_data->GetSize() < 4 )
6686         return false;
6687  
6688     if ( data.p_private_data->GetBuffer()[0] != MATROSKA_DVD_LEVEL_SS || data.p_private_data->GetBuffer()[1] != 0x80 )
6689         return false;
6690
6691     uint16 i_gtitle = (data.p_private_data->GetBuffer()[2] << 8 ) + data.p_private_data->GetBuffer()[3];
6692     uint16 i_title = *(uint16*)p_cookie;
6693
6694     return (i_gtitle == i_title);
6695 }
6696
6697 bool dvd_command_interpretor_c::MatchVTSMNumber( const chapter_codec_cmds_c &data, const void *p_cookie, size_t i_cookie_size )
6698 {
6699     if ( i_cookie_size != 1 || data.p_private_data == NULL || data.p_private_data->GetSize() < 4 )
6700         return false;
6701  
6702     if ( data.p_private_data->GetBuffer()[0] != MATROSKA_DVD_LEVEL_SS || data.p_private_data->GetBuffer()[1] != 0x40 )
6703         return false;
6704
6705     uint8 i_gtitle = data.p_private_data->GetBuffer()[3];
6706     uint8 i_title = *(uint8*)p_cookie;
6707
6708     return (i_gtitle == i_title);
6709 }
6710
6711 bool dvd_command_interpretor_c::MatchTitleNumber( const chapter_codec_cmds_c &data, const void *p_cookie, size_t i_cookie_size )
6712 {
6713     if ( i_cookie_size != 1 || data.p_private_data == NULL || data.p_private_data->GetSize() < 4 )
6714         return false;
6715  
6716     if ( data.p_private_data->GetBuffer()[0] != MATROSKA_DVD_LEVEL_TT )
6717         return false;
6718
6719     uint16 i_gtitle = (data.p_private_data->GetBuffer()[1] << 8 ) + data.p_private_data->GetBuffer()[2];
6720     uint8 i_title = *(uint8*)p_cookie;
6721
6722     return (i_gtitle == i_title);
6723 }
6724
6725 bool dvd_command_interpretor_c::MatchPgcType( const chapter_codec_cmds_c &data, const void *p_cookie, size_t i_cookie_size )
6726 {
6727     if ( i_cookie_size != 1 || data.p_private_data == NULL || data.p_private_data->GetSize() < 8 )
6728         return false;
6729  
6730     if ( data.p_private_data->GetBuffer()[0] != MATROSKA_DVD_LEVEL_PGC )
6731         return false;
6732
6733     uint8 i_pgc_type = data.p_private_data->GetBuffer()[3] & 0x0F;
6734     uint8 i_pgc = *(uint8*)p_cookie;
6735
6736     return (i_pgc_type == i_pgc);
6737 }
6738
6739 bool dvd_command_interpretor_c::MatchPgcNumber( const chapter_codec_cmds_c &data, const void *p_cookie, size_t i_cookie_size )
6740 {
6741     if ( i_cookie_size != 2 || data.p_private_data == NULL || data.p_private_data->GetSize() < 8 )
6742         return false;
6743  
6744     if ( data.p_private_data->GetBuffer()[0] != MATROSKA_DVD_LEVEL_PGC )
6745         return false;
6746
6747     uint16 *i_pgc_n = (uint16 *)p_cookie;
6748     uint16 i_pgc_num = (data.p_private_data->GetBuffer()[1] << 8) + data.p_private_data->GetBuffer()[2];
6749
6750     return (i_pgc_num == *i_pgc_n);
6751 }
6752
6753 bool dvd_command_interpretor_c::MatchChapterNumber( const chapter_codec_cmds_c &data, const void *p_cookie, size_t i_cookie_size )
6754 {
6755     if ( i_cookie_size != 1 || data.p_private_data == NULL || data.p_private_data->GetSize() < 2 )
6756         return false;
6757  
6758     if ( data.p_private_data->GetBuffer()[0] != MATROSKA_DVD_LEVEL_PTT )
6759         return false;
6760
6761     uint8 i_chapter = data.p_private_data->GetBuffer()[1];
6762     uint8 i_ptt = *(uint8*)p_cookie;
6763
6764     return (i_chapter == i_ptt);
6765 }
6766
6767 bool dvd_command_interpretor_c::MatchCellNumber( const chapter_codec_cmds_c &data, const void *p_cookie, size_t i_cookie_size )
6768 {
6769     if ( i_cookie_size != 1 || data.p_private_data == NULL || data.p_private_data->GetSize() < 5 )
6770         return false;
6771  
6772     if ( data.p_private_data->GetBuffer()[0] != MATROSKA_DVD_LEVEL_CN )
6773         return false;
6774
6775     uint8 *i_cell_n = (uint8 *)p_cookie;
6776     uint8 i_cell_num = data.p_private_data->GetBuffer()[3];
6777
6778     return (i_cell_num == *i_cell_n);
6779 }
6780
6781 bool matroska_script_codec_c::Enter()
6782 {
6783     bool f_result = false;
6784     std::vector<KaxChapterProcessData*>::iterator index = enter_cmds.begin();
6785     while ( index != enter_cmds.end() )
6786     {
6787         if ( (*index)->GetSize() )
6788         {
6789             msg_Dbg( &sys.demuxer, "Matroska Script enter command" );
6790             f_result |= interpretor.Interpret( (*index)->GetBuffer(), (*index)->GetSize() );
6791         }
6792         index++;
6793     }
6794     return f_result;
6795 }
6796
6797 bool matroska_script_codec_c::Leave()
6798 {
6799     bool f_result = false;
6800     std::vector<KaxChapterProcessData*>::iterator index = leave_cmds.begin();
6801     while ( index != leave_cmds.end() )
6802     {
6803         if ( (*index)->GetSize() )
6804         {
6805             msg_Dbg( &sys.demuxer, "Matroska Script leave command" );
6806             f_result |= interpretor.Interpret( (*index)->GetBuffer(), (*index)->GetSize() );
6807         }
6808         index++;
6809     }
6810     return f_result;
6811 }
6812
6813 // see http://www.matroska.org/technical/specs/chapters/index.html#mscript
6814 //  for a description of existing commands
6815 bool matroska_script_interpretor_c::Interpret( const binary * p_command, size_t i_size )
6816 {
6817     bool b_result = false;
6818
6819     char *psz_str = (char*) malloc( i_size + 1 );
6820     memcpy( psz_str, p_command, i_size );
6821     psz_str[ i_size ] = '\0';
6822
6823     std::string sz_command = psz_str;
6824     free( psz_str );
6825
6826     msg_Dbg( &sys.demuxer, "command : %s", sz_command.c_str() );
6827
6828 #if defined(__GNUC__) && (__GNUC__ < 3)
6829     if ( sz_command.compare( CMD_MS_GOTO_AND_PLAY, 0, CMD_MS_GOTO_AND_PLAY.size() ) == 0 )
6830 #else
6831     if ( sz_command.compare( 0, CMD_MS_GOTO_AND_PLAY.size(), CMD_MS_GOTO_AND_PLAY ) == 0 )
6832 #endif
6833     {
6834         size_t i,j;
6835
6836         // find the (
6837         for ( i=CMD_MS_GOTO_AND_PLAY.size(); i<sz_command.size(); i++)
6838         {
6839             if ( sz_command[i] == '(' )
6840             {
6841                 i++;
6842                 break;
6843             }
6844         }
6845         // find the )
6846         for ( j=i; j<sz_command.size(); j++)
6847         {
6848             if ( sz_command[j] == ')' )
6849             {
6850                 i--;
6851                 break;
6852             }
6853         }
6854
6855         std::string st = sz_command.substr( i+1, j-i-1 );
6856         int64_t i_chapter_uid = atoi( st.c_str() );
6857
6858         virtual_segment_c *p_segment;
6859         chapter_item_c *p_chapter = sys.FindChapter( i_chapter_uid, p_segment );
6860
6861         if ( p_chapter == NULL )
6862             msg_Dbg( &sys.demuxer, "Chapter %"PRId64" not found", i_chapter_uid);
6863         else
6864         {
6865             if ( !p_chapter->EnterAndLeave( sys.p_current_segment->CurrentChapter() ) )
6866                 p_segment->Seek( sys.demuxer, p_chapter->i_user_start_time, -1, p_chapter, -1 );
6867             b_result = true;
6868         }
6869     }
6870
6871     return b_result;
6872 }
6873
6874 void demux_sys_t::SwapButtons()
6875 {
6876 #ifndef WORDS_BIGENDIAN
6877     uint8_t button, i, j;
6878
6879     for( button = 1; button <= pci_packet.hli.hl_gi.btn_ns; button++) {
6880         btni_t *button_ptr = &(pci_packet.hli.btnit[button-1]);
6881         binary *p_data = (binary*) button_ptr;
6882
6883         uint16 i_x_start = ((p_data[0] & 0x3F) << 4 ) + ( p_data[1] >> 4 );
6884         uint16 i_x_end   = ((p_data[1] & 0x03) << 8 ) + p_data[2];
6885         uint16 i_y_start = ((p_data[3] & 0x3F) << 4 ) + ( p_data[4] >> 4 );
6886         uint16 i_y_end   = ((p_data[4] & 0x03) << 8 ) + p_data[5];
6887         button_ptr->x_start = i_x_start;
6888         button_ptr->x_end   = i_x_end;
6889         button_ptr->y_start = i_y_start;
6890         button_ptr->y_end   = i_y_end;
6891
6892     }
6893     for ( i = 0; i<3; i++ )
6894     {
6895         for ( j = 0; j<2; j++ )
6896         {
6897             pci_packet.hli.btn_colit.btn_coli[i][j] = U32_AT( &pci_packet.hli.btn_colit.btn_coli[i][j] );
6898         }
6899     }
6900 #endif
6901 }