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