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