MKV: Copy mkv.cpp to many different files.
[vlc.git] / modules / demux / mkv / chapter_command.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 #include "vlc_keys.h"
102
103 extern "C" {
104    #include "../mp4/libmp4.h"
105 }
106 #ifdef HAVE_ZLIB_H
107 #   include <zlib.h>
108 #endif
109
110 /*****************************************************************************
111  * Module descriptor
112  *****************************************************************************/
113 static int  Open ( vlc_object_t * );
114 static void Close( vlc_object_t * );
115
116 vlc_module_begin();
117     set_shortname( "Matroska" );
118     set_description( N_("Matroska stream demuxer" ) );
119     set_capability( "demux", 0 );
120     set_callbacks( Open, Close );
121     set_category( CAT_INPUT );
122     set_subcategory( SUBCAT_INPUT_DEMUX );
123
124     add_bool( "mkv-use-ordered-chapters", 1, NULL,
125             N_("Ordered chapters"),
126             N_("Play ordered chapters as specified in the segment."), true );
127
128     add_bool( "mkv-use-chapter-codec", 1, NULL,
129             N_("Chapter codecs"),
130             N_("Use chapter codecs found in the segment."), true );
131
132     add_bool( "mkv-preload-local-dir", 1, NULL,
133             N_("Preload Directory"),
134             N_("Preload matroska files from the same family in the same directory (not good for broken files)."), true );
135
136     add_bool( "mkv-seek-percent", 0, NULL,
137             N_("Seek based on percent not time"),
138             N_("Seek based on percent not time."), true );
139
140     add_bool( "mkv-use-dummy", 0, NULL,
141             N_("Dummy Elements"),
142             N_("Read and discard unknown EBML elements (not good for broken files)."), true );
143
144     add_shortcut( "mka" );
145     add_shortcut( "mkv" );
146 vlc_module_end();
147
148
149
150 #define MATROSKA_COMPRESSION_NONE  -1
151 #define MATROSKA_COMPRESSION_ZLIB   0
152 #define MATROSKA_COMPRESSION_BLIB   1
153 #define MATROSKA_COMPRESSION_LZOX   2
154 #define MATROSKA_COMPRESSION_HEADER 3
155
156 #define MKVD_TIMECODESCALE 1000000
157
158 ////////////////////////////////////////////////////////////////////////////////////////////////////////////////
159 #undef ATTRIBUTE_PACKED
160 #undef PRAGMA_PACK_BEGIN
161 #undef PRAGMA_PACK_END
162
163 #if defined(__GNUC__)
164 #if __GNUC__ > 2 || (__GNUC__ == 2 && __GNUC_MINOR__ >= 95)
165 #define ATTRIBUTE_PACKED __attribute__ ((packed))
166 #define PRAGMA_PACK 0
167 #endif
168 #endif
169
170 #if !defined(ATTRIBUTE_PACKED)
171 #define ATTRIBUTE_PACKED
172 #define PRAGMA_PACK 1
173 #endif
174
175 #if PRAGMA_PACK
176 #pragma pack(1)
177 #endif
178
179 /*************************************
180 *  taken from libdvdnav / libdvdread
181 **************************************/
182
183 /**
184  * DVD Time Information.
185  */
186 typedef struct {
187   uint8_t hour;
188   uint8_t minute;
189   uint8_t second;
190   uint8_t frame_u; /* The two high bits are the frame rate. */
191 } ATTRIBUTE_PACKED dvd_time_t;
192
193 /**
194  * User Operations.
195  */
196 typedef struct {
197 #ifdef WORDS_BIGENDIAN
198   unsigned char zero                           : 7; /* 25-31 */
199   unsigned char video_pres_mode_change         : 1; /* 24 */
200  
201   unsigned char karaoke_audio_pres_mode_change : 1; /* 23 */
202   unsigned char angle_change                   : 1;
203   unsigned char subpic_stream_change           : 1;
204   unsigned char audio_stream_change            : 1;
205   unsigned char pause_on                       : 1;
206   unsigned char still_off                      : 1;
207   unsigned char button_select_or_activate      : 1;
208   unsigned char resume                         : 1; /* 16 */
209  
210   unsigned char chapter_menu_call              : 1; /* 15 */
211   unsigned char angle_menu_call                : 1;
212   unsigned char audio_menu_call                : 1;
213   unsigned char subpic_menu_call               : 1;
214   unsigned char root_menu_call                 : 1;
215   unsigned char title_menu_call                : 1;
216   unsigned char backward_scan                  : 1;
217   unsigned char forward_scan                   : 1; /* 8 */
218  
219   unsigned char next_pg_search                 : 1; /* 7 */
220   unsigned char prev_or_top_pg_search          : 1;
221   unsigned char time_or_chapter_search         : 1;
222   unsigned char go_up                          : 1;
223   unsigned char stop                           : 1;
224   unsigned char title_play                     : 1;
225   unsigned char chapter_search_or_play         : 1;
226   unsigned char title_or_time_play             : 1; /* 0 */
227 #else
228   unsigned char video_pres_mode_change         : 1; /* 24 */
229   unsigned char zero                           : 7; /* 25-31 */
230  
231   unsigned char resume                         : 1; /* 16 */
232   unsigned char button_select_or_activate      : 1;
233   unsigned char still_off                      : 1;
234   unsigned char pause_on                       : 1;
235   unsigned char audio_stream_change            : 1;
236   unsigned char subpic_stream_change           : 1;
237   unsigned char angle_change                   : 1;
238   unsigned char karaoke_audio_pres_mode_change : 1; /* 23 */
239  
240   unsigned char forward_scan                   : 1; /* 8 */
241   unsigned char backward_scan                  : 1;
242   unsigned char title_menu_call                : 1;
243   unsigned char root_menu_call                 : 1;
244   unsigned char subpic_menu_call               : 1;
245   unsigned char audio_menu_call                : 1;
246   unsigned char angle_menu_call                : 1;
247   unsigned char chapter_menu_call              : 1; /* 15 */
248  
249   unsigned char title_or_time_play             : 1; /* 0 */
250   unsigned char chapter_search_or_play         : 1;
251   unsigned char title_play                     : 1;
252   unsigned char stop                           : 1;
253   unsigned char go_up                          : 1;
254   unsigned char time_or_chapter_search         : 1;
255   unsigned char prev_or_top_pg_search          : 1;
256   unsigned char next_pg_search                 : 1; /* 7 */
257 #endif
258 } ATTRIBUTE_PACKED user_ops_t;
259
260 /**
261  * Type to store per-command data.
262  */
263 typedef struct {
264   uint8_t bytes[8];
265 } ATTRIBUTE_PACKED vm_cmd_t;
266 #define COMMAND_DATA_SIZE 8
267
268 /**
269  * PCI General Information
270  */
271 typedef struct {
272   uint32_t nv_pck_lbn;      /**< sector address of this nav pack */
273   uint16_t vobu_cat;        /**< 'category' of vobu */
274   uint16_t zero1;           /**< reserved */
275   user_ops_t vobu_uop_ctl;  /**< UOP of vobu */
276   uint32_t vobu_s_ptm;      /**< start presentation time of vobu */
277   uint32_t vobu_e_ptm;      /**< end presentation time of vobu */
278   uint32_t vobu_se_e_ptm;   /**< end ptm of sequence end in vobu */
279   dvd_time_t e_eltm;        /**< Cell elapsed time */
280   char vobu_isrc[32];
281 } ATTRIBUTE_PACKED pci_gi_t;
282
283 /**
284  * Non Seamless Angle Information
285  */
286 typedef struct {
287   uint32_t nsml_agl_dsta[9];  /**< address of destination vobu in AGL_C#n */
288 } ATTRIBUTE_PACKED nsml_agli_t;
289
290 /**
291  * Highlight General Information
292  *
293  * For btngrX_dsp_ty the bits have the following meaning:
294  * 000b: normal 4/3 only buttons
295  * XX1b: wide (16/9) buttons
296  * X1Xb: letterbox buttons
297  * 1XXb: pan&scan buttons
298  */
299 typedef struct {
300   uint16_t hli_ss; /**< status, only low 2 bits 0: no buttons, 1: different 2: equal 3: eual except for button cmds */
301   uint32_t hli_s_ptm;              /**< start ptm of hli */
302   uint32_t hli_e_ptm;              /**< end ptm of hli */
303   uint32_t btn_se_e_ptm;           /**< end ptm of button select */
304 #ifdef WORDS_BIGENDIAN
305   unsigned char zero1 : 2;          /**< reserved */
306   unsigned char btngr_ns : 2;       /**< number of button groups 1, 2 or 3 with 36/18/12 buttons */
307   unsigned char zero2 : 1;          /**< reserved */
308   unsigned char btngr1_dsp_ty : 3;  /**< display type of subpic stream for button group 1 */
309   unsigned char zero3 : 1;          /**< reserved */
310   unsigned char btngr2_dsp_ty : 3;  /**< display type of subpic stream for button group 2 */
311   unsigned char zero4 : 1;          /**< reserved */
312   unsigned char btngr3_dsp_ty : 3;  /**< display type of subpic stream for button group 3 */
313 #else
314   unsigned char btngr1_dsp_ty : 3;
315   unsigned char zero2 : 1;
316   unsigned char btngr_ns : 2;
317   unsigned char zero1 : 2;
318   unsigned char btngr3_dsp_ty : 3;
319   unsigned char zero4 : 1;
320   unsigned char btngr2_dsp_ty : 3;
321   unsigned char zero3 : 1;
322 #endif
323   uint8_t btn_ofn;     /**< button offset number range 0-255 */
324   uint8_t btn_ns;      /**< number of valid buttons  <= 36/18/12 (low 6 bits) */
325   uint8_t nsl_btn_ns;  /**< number of buttons selectable by U_BTNNi (low 6 bits)   nsl_btn_ns <= btn_ns */
326   uint8_t zero5;       /**< reserved */
327   uint8_t fosl_btnn;   /**< forcedly selected button  (low 6 bits) */
328   uint8_t foac_btnn;   /**< forcedly activated button (low 6 bits) */
329 } ATTRIBUTE_PACKED hl_gi_t;
330
331
332 /**
333  * Button Color Information Table
334  * Each entry beeing a 32bit word that contains the color indexs and alpha
335  * values to use.  They are all represented by 4 bit number and stored
336  * like this [Ci3, Ci2, Ci1, Ci0, A3, A2, A1, A0].   The actual palette
337  * that the indexes reference is in the PGC.
338  * \todo split the uint32_t into a struct
339  */
340 typedef struct {
341   uint32_t btn_coli[3][2];  /**< [button color number-1][select:0/action:1] */
342 } ATTRIBUTE_PACKED btn_colit_t;
343
344 /**
345  * Button Information
346  *
347  * NOTE: I've had to change the structure from the disk layout to get
348  * the packing to work with Sun's Forte C compiler.
349  * The 4 and 7 bytes are 'rotated' was: ABC DEF GHIJ  is: ABCG DEFH IJ
350  */
351 typedef struct {
352 #ifdef WORDS_BIGENDIAN
353   uint32        btn_coln         : 2;  /**< button color number */
354   uint32        x_start          : 10; /**< x start offset within the overlay */
355   uint32        zero1            : 2;  /**< reserved */
356   uint32        x_end            : 10; /**< x end offset within the overlay */
357
358   uint32        zero3            : 2;  /**< reserved */
359   uint32        up               : 6;  /**< button index when pressing up */
360
361   uint32        auto_action_mode : 2;  /**< 0: no, 1: activated if selected */
362   uint32        y_start          : 10; /**< y start offset within the overlay */
363   uint32        zero2            : 2;  /**< reserved */
364   uint32        y_end            : 10; /**< y end offset within the overlay */
365
366   uint32        zero4            : 2;  /**< reserved */
367   uint32        down             : 6;  /**< button index when pressing down */
368   unsigned char zero5            : 2;  /**< reserved */
369   unsigned char left             : 6;  /**< button index when pressing left */
370   unsigned char zero6            : 2;  /**< reserved */
371   unsigned char right            : 6;  /**< button index when pressing right */
372 #else
373   uint32        x_end            : 10;
374   uint32        zero1            : 2;
375   uint32        x_start          : 10;
376   uint32        btn_coln         : 2;
377
378   uint32        up               : 6;
379   uint32        zero3            : 2;
380
381   uint32        y_end            : 10;
382   uint32        zero2            : 2;
383   uint32        y_start          : 10;
384   uint32        auto_action_mode : 2;
385
386   uint32        down             : 6;
387   uint32        zero4            : 2;
388   unsigned char left             : 6;
389   unsigned char zero5            : 2;
390   unsigned char right            : 6;
391   unsigned char zero6            : 2;
392 #endif
393   vm_cmd_t cmd;
394 } ATTRIBUTE_PACKED btni_t;
395
396 /**
397  * Highlight Information
398  */
399 typedef struct {
400   hl_gi_t     hl_gi;
401   btn_colit_t btn_colit;
402   btni_t      btnit[36];
403 } ATTRIBUTE_PACKED hli_t;
404
405 /**
406  * PCI packet
407  */
408 typedef struct {
409   pci_gi_t    pci_gi;
410   nsml_agli_t nsml_agli;
411   hli_t       hli;
412   uint8_t     zero1[189];
413 } ATTRIBUTE_PACKED pci_t;
414
415
416 #if PRAGMA_PACK
417 #pragma pack()
418 #endif
419 ////////////////////////////////////////////////////////////////////////////////////////////////////////////////
420
421
422 /**
423  * What's between a directory and a filename?
424  */
425 #if defined( WIN32 )
426     #define DIRECTORY_SEPARATOR '\\'
427 #else
428     #define DIRECTORY_SEPARATOR '/'
429 #endif
430
431 using namespace LIBMATROSKA_NAMESPACE;
432 using namespace std;
433
434 /*****************************************************************************
435  * Local prototypes
436  *****************************************************************************/
437 #ifdef HAVE_ZLIB_H
438 block_t *block_zlib_decompress( vlc_object_t *p_this, block_t *p_in_block ) {
439     int result, dstsize, n;
440     unsigned char *dst;
441     block_t *p_block;
442     z_stream d_stream;
443
444     d_stream.zalloc = (alloc_func)0;
445     d_stream.zfree = (free_func)0;
446     d_stream.opaque = (voidpf)0;
447     result = inflateInit(&d_stream);
448     if( result != Z_OK )
449     {
450         msg_Dbg( p_this, "inflateInit() failed. Result: %d", result );
451         return NULL;
452     }
453
454     d_stream.next_in = (Bytef *)p_in_block->p_buffer;
455     d_stream.avail_in = p_in_block->i_buffer;
456     n = 0;
457     p_block = block_New( p_this, 0 );
458     dst = NULL;
459     do
460     {
461         n++;
462         p_block = block_Realloc( p_block, 0, n * 1000 );
463         dst = (unsigned char *)p_block->p_buffer;
464         d_stream.next_out = (Bytef *)&dst[(n - 1) * 1000];
465         d_stream.avail_out = 1000;
466         result = inflate(&d_stream, Z_NO_FLUSH);
467         if( ( result != Z_OK ) && ( result != Z_STREAM_END ) )
468         {
469             msg_Dbg( p_this, "Zlib decompression failed. Result: %d", result );
470             return NULL;
471         }
472     }
473     while( ( d_stream.avail_out == 0 ) && ( d_stream.avail_in != 0 ) &&
474            ( result != Z_STREAM_END ) );
475
476     dstsize = d_stream.total_out;
477     inflateEnd( &d_stream );
478
479     p_block = block_Realloc( p_block, 0, dstsize );
480     p_block->i_buffer = dstsize;
481     block_Release( p_in_block );
482
483     return p_block;
484 }
485 #endif
486
487 /**
488  * Helper function to print the mkv parse tree
489  */
490 static void MkvTree( demux_t & demuxer, int i_level, const char *psz_format, ... )
491 {
492     va_list args;
493     if( i_level > 9 )
494     {
495         msg_Err( &demuxer, "too deep tree" );
496         return;
497     }
498     va_start( args, psz_format );
499     static const char psz_foo[] = "|   |   |   |   |   |   |   |   |   |";
500     char *psz_foo2 = (char*)malloc( ( i_level * 4 + 3 + strlen( psz_format ) ) * sizeof(char) );
501     strncpy( psz_foo2, psz_foo, 4 * i_level );
502     psz_foo2[ 4 * i_level ] = '+';
503     psz_foo2[ 4 * i_level + 1 ] = ' ';
504     strcpy( &psz_foo2[ 4 * i_level + 2 ], psz_format );
505     __msg_GenericVa( VLC_OBJECT(&demuxer),VLC_MSG_DBG, "mkv", psz_foo2, args );
506     free( psz_foo2 );
507     va_end( args );
508 }
509
510 /*****************************************************************************
511  * Stream managment
512  *****************************************************************************/
513 class vlc_stream_io_callback: public IOCallback
514 {
515   private:
516     stream_t       *s;
517     bool           mb_eof;
518     bool           b_owner;
519
520   public:
521     vlc_stream_io_callback( stream_t *, bool );
522
523     virtual ~vlc_stream_io_callback()
524     {
525         if( b_owner )
526             stream_Delete( s );
527     }
528
529     virtual uint32   read            ( void *p_buffer, size_t i_size);
530     virtual void     setFilePointer  ( int64_t i_offset, seek_mode mode = seek_beginning );
531     virtual size_t   write           ( const void *p_buffer, size_t i_size);
532     virtual uint64   getFilePointer  ( void );
533     virtual void     close           ( void );
534 };
535
536 /*****************************************************************************
537  * Ebml Stream parser
538  *****************************************************************************/
539 class EbmlParser
540 {
541   public:
542     EbmlParser( EbmlStream *es, EbmlElement *el_start, demux_t *p_demux );
543     virtual ~EbmlParser( void );
544
545     void Up( void );
546     void Down( void );
547     void Reset( demux_t *p_demux );
548     EbmlElement *Get( void );
549     void        Keep( void );
550     EbmlElement *UnGet( uint64 i_block_pos, uint64 i_cluster_pos );
551
552     int  GetLevel( void );
553
554     /* Is the provided element presents in our upper elements */
555     bool IsTopPresent( EbmlElement * );
556
557   private:
558     EbmlStream  *m_es;
559     int         mi_level;
560     EbmlElement *m_el[10];
561     int64_t      mi_remain_size[10];
562
563     EbmlElement *m_got;
564
565     int         mi_user_level;
566     bool        mb_keep;
567     bool        mb_dummy;
568 };
569
570
571 /*****************************************************************************
572  * Some functions to manipulate memory
573  *****************************************************************************/
574 #define GetFOURCC( p )  __GetFOURCC( (uint8_t*)p )
575 static vlc_fourcc_t __GetFOURCC( uint8_t *p )
576 {
577     return VLC_FOURCC( p[0], p[1], p[2], p[3] );
578 }
579
580 /*****************************************************************************
581  * definitions of structures and functions used by this plugins
582  *****************************************************************************/
583 typedef struct
584 {
585 //    ~mkv_track_t();
586
587     bool         b_default;
588     bool         b_enabled;
589     unsigned int i_number;
590
591     int          i_extra_data;
592     uint8_t      *p_extra_data;
593
594     char         *psz_codec;
595
596     uint64_t     i_default_duration;
597     float        f_timecodescale;
598     mtime_t      i_last_dts;
599
600     /* video */
601     es_format_t fmt;
602     float       f_fps;
603     es_out_id_t *p_es;
604
605     /* audio */
606     unsigned int i_original_rate;
607
608     bool            b_inited;
609     /* data to be send first */
610     int             i_data_init;
611     uint8_t         *p_data_init;
612
613     /* hack : it's for seek */
614     bool            b_search_keyframe;
615     bool            b_silent;
616
617     /* informative */
618     const char   *psz_codec_name;
619     const char   *psz_codec_settings;
620     const char   *psz_codec_info_url;
621     const char   *psz_codec_download_url;
622
623     /* encryption/compression */
624     int                    i_compression_type;
625     KaxContentCompSettings *p_compression_data;
626
627 } mkv_track_t;
628
629 typedef struct
630 {
631     int     i_track;
632     int     i_block_number;
633
634     int64_t i_position;
635     int64_t i_time;
636
637     bool       b_key;
638 } mkv_index_t;
639
640 class demux_sys_t;
641
642 const binary MATROSKA_DVD_LEVEL_SS   = 0x30;
643 const binary MATROSKA_DVD_LEVEL_LU   = 0x2A;
644 const binary MATROSKA_DVD_LEVEL_TT   = 0x28;
645 const binary MATROSKA_DVD_LEVEL_PGC  = 0x20;
646 const binary MATROSKA_DVD_LEVEL_PG   = 0x18;
647 const binary MATROSKA_DVD_LEVEL_PTT  = 0x10;
648 const binary MATROSKA_DVD_LEVEL_CN   = 0x08;
649
650 class chapter_codec_cmds_c
651 {
652 public:
653     chapter_codec_cmds_c( demux_sys_t & demuxer, int codec_id = -1)
654     :p_private_data(NULL)
655     ,i_codec_id( codec_id )
656     ,sys( demuxer )
657     {}
658  
659     virtual ~chapter_codec_cmds_c()
660     {
661         delete p_private_data;
662         std::vector<KaxChapterProcessData*>::iterator indexe = enter_cmds.begin();
663         while ( indexe != enter_cmds.end() )
664         {
665             delete (*indexe);
666             indexe++;
667         }
668         std::vector<KaxChapterProcessData*>::iterator indexl = leave_cmds.begin();
669         while ( indexl != leave_cmds.end() )
670         {
671             delete (*indexl);
672             indexl++;
673         }
674         std::vector<KaxChapterProcessData*>::iterator indexd = during_cmds.begin();
675         while ( indexd != during_cmds.end() )
676         {
677             delete (*indexd);
678             indexd++;
679         }
680     }
681
682     void SetPrivate( const KaxChapterProcessPrivate & private_data )
683     {
684         p_private_data = new KaxChapterProcessPrivate( private_data );
685     }
686
687     void AddCommand( const KaxChapterProcessCommand & command );
688  
689     /// \return wether the codec has seeked in the files or not
690     virtual bool Enter() { return false; }
691     virtual bool Leave() { return false; }
692     virtual std::string GetCodecName( bool f_for_title = false ) const { return ""; }
693     virtual int16 GetTitleNumber() { return -1; }
694
695     KaxChapterProcessPrivate *p_private_data;
696
697 protected:
698     std::vector<KaxChapterProcessData*> enter_cmds;
699     std::vector<KaxChapterProcessData*> during_cmds;
700     std::vector<KaxChapterProcessData*> leave_cmds;
701
702     int i_codec_id;
703     demux_sys_t & sys;
704 };
705
706 class dvd_command_interpretor_c
707 {
708 public:
709     dvd_command_interpretor_c( demux_sys_t & demuxer )
710     :sys( demuxer )
711     {
712         memset( p_PRMs, 0, sizeof(p_PRMs) );
713         p_PRMs[ 0x80 + 1 ] = 15;
714         p_PRMs[ 0x80 + 2 ] = 62;
715         p_PRMs[ 0x80 + 3 ] = 1;
716         p_PRMs[ 0x80 + 4 ] = 1;
717         p_PRMs[ 0x80 + 7 ] = 1;
718         p_PRMs[ 0x80 + 8 ] = 1;
719         p_PRMs[ 0x80 + 16 ] = 0xFFFFu;
720         p_PRMs[ 0x80 + 18 ] = 0xFFFFu;
721     }
722  
723     bool Interpret( const binary * p_command, size_t i_size = 8 );
724  
725     uint16 GetPRM( size_t index ) const
726     {
727         if ( index < 256 )
728             return p_PRMs[ index ];
729         else return 0;
730     }
731
732     uint16 GetGPRM( size_t index ) const
733     {
734         if ( index >= 0 && index < 16 )
735             return p_PRMs[ index ];
736         else return 0;
737     }
738
739     uint16 GetSPRM( size_t index ) const
740     {
741         // 21,22,23 reserved for future use
742         if ( index >= 0x80 && index < 0x95 )
743             return p_PRMs[ index ];
744         else return 0;
745     }
746
747     bool SetPRM( size_t index, uint16 value )
748     {
749         if ( index >= 0 && index < 16 )
750         {
751             p_PRMs[ index ] = value;
752             return true;
753         }
754         return false;
755     }
756  
757     bool SetGPRM( size_t index, uint16 value )
758     {
759         if ( index >= 0 && index < 16 )
760         {
761             p_PRMs[ index ] = value;
762             return true;
763         }
764         return false;
765     }
766
767     bool SetSPRM( size_t index, uint16 value )
768     {
769         if ( index > 0x80 && index <= 0x8D && index != 0x8C )
770         {
771             p_PRMs[ index ] = value;
772             return true;
773         }
774         return false;
775     }
776
777 protected:
778     std::string GetRegTypeName( bool b_value, uint16 value ) const
779     {
780         std::string result;
781         char s_value[6], s_reg_value[6];
782         sprintf( s_value, "%.5d", value );
783
784         if ( b_value )
785         {
786             result = "value (";
787             result += s_value;
788             result += ")";
789         }
790         else if ( value < 0x80 )
791         {
792             sprintf( s_reg_value, "%.5d", GetPRM( value ) );
793             result = "GPreg[";
794             result += s_value;
795             result += "] (";
796             result += s_reg_value;
797             result += ")";
798         }
799         else
800         {
801             sprintf( s_reg_value, "%.5d", GetPRM( value ) );
802             result = "SPreg[";
803             result += s_value;
804             result += "] (";
805             result += s_reg_value;
806             result += ")";
807         }
808         return result;
809     }
810
811     uint16       p_PRMs[256];
812     demux_sys_t  & sys;
813  
814     // DVD command IDs
815
816     // Tests
817     // wether it's a comparison on the value or register
818     static const uint16 CMD_DVD_TEST_VALUE          = 0x80;
819     static const uint16 CMD_DVD_IF_GPREG_AND        = (1 << 4);
820     static const uint16 CMD_DVD_IF_GPREG_EQUAL      = (2 << 4);
821     static const uint16 CMD_DVD_IF_GPREG_NOT_EQUAL  = (3 << 4);
822     static const uint16 CMD_DVD_IF_GPREG_SUP_EQUAL  = (4 << 4);
823     static const uint16 CMD_DVD_IF_GPREG_SUP        = (5 << 4);
824     static const uint16 CMD_DVD_IF_GPREG_INF_EQUAL  = (6 << 4);
825     static const uint16 CMD_DVD_IF_GPREG_INF        = (7 << 4);
826  
827     static const uint16 CMD_DVD_NOP                    = 0x0000;
828     static const uint16 CMD_DVD_GOTO_LINE              = 0x0001;
829     static const uint16 CMD_DVD_BREAK                  = 0x0002;
830     // Links
831     static const uint16 CMD_DVD_NOP2                   = 0x2001;
832     static const uint16 CMD_DVD_LINKPGCN               = 0x2004;
833     static const uint16 CMD_DVD_LINKPGN                = 0x2006;
834     static const uint16 CMD_DVD_LINKCN                 = 0x2007;
835     static const uint16 CMD_DVD_JUMP_TT                = 0x3002;
836     static const uint16 CMD_DVD_JUMPVTS_TT             = 0x3003;
837     static const uint16 CMD_DVD_JUMPVTS_PTT            = 0x3005;
838     static const uint16 CMD_DVD_JUMP_SS                = 0x3006;
839     static const uint16 CMD_DVD_CALLSS_VTSM1           = 0x3008;
840     //
841     static const uint16 CMD_DVD_SET_HL_BTNN2           = 0x4600;
842     static const uint16 CMD_DVD_SET_HL_BTNN_LINKPGCN1  = 0x4604;
843     static const uint16 CMD_DVD_SET_STREAM             = 0x5100;
844     static const uint16 CMD_DVD_SET_GPRMMD             = 0x5300;
845     static const uint16 CMD_DVD_SET_HL_BTNN1           = 0x5600;
846     static const uint16 CMD_DVD_SET_HL_BTNN_LINKPGCN2  = 0x5604;
847     static const uint16 CMD_DVD_SET_HL_BTNN_LINKCN     = 0x5607;
848     // Operations
849     static const uint16 CMD_DVD_MOV_SPREG_PREG         = 0x6100;
850     static const uint16 CMD_DVD_GPREG_MOV_VALUE        = 0x7100;
851     static const uint16 CMD_DVD_SUB_GPREG              = 0x7400;
852     static const uint16 CMD_DVD_MULT_GPREG             = 0x7500;
853     static const uint16 CMD_DVD_GPREG_DIV_VALUE        = 0x7600;
854     static const uint16 CMD_DVD_GPREG_AND_VALUE        = 0x7900;
855  
856     // callbacks when browsing inside CodecPrivate
857     static bool MatchIsDomain     ( const chapter_codec_cmds_c &data, const void *p_cookie, size_t i_cookie_size );
858     static bool MatchIsVMG        ( const chapter_codec_cmds_c &data, const void *p_cookie, size_t i_cookie_size );
859     static bool MatchVTSNumber    ( const chapter_codec_cmds_c &data, const void *p_cookie, size_t i_cookie_size );
860     static bool MatchVTSMNumber   ( const chapter_codec_cmds_c &data, const void *p_cookie, size_t i_cookie_size );
861     static bool MatchTitleNumber  ( const chapter_codec_cmds_c &data, const void *p_cookie, size_t i_cookie_size );
862     static bool MatchPgcType      ( const chapter_codec_cmds_c &data, const void *p_cookie, size_t i_cookie_size );
863     static bool MatchPgcNumber    ( const chapter_codec_cmds_c &data, const void *p_cookie, size_t i_cookie_size );
864     static bool MatchChapterNumber( const chapter_codec_cmds_c &data, const void *p_cookie, size_t i_cookie_size );
865     static bool MatchCellNumber   ( const chapter_codec_cmds_c &data, const void *p_cookie, size_t i_cookie_size );
866 };
867
868 class dvd_chapter_codec_c : public chapter_codec_cmds_c
869 {
870 public:
871     dvd_chapter_codec_c( demux_sys_t & sys )
872     :chapter_codec_cmds_c( sys, 1 )
873     {}
874
875     bool Enter();
876     bool Leave();
877     std::string GetCodecName( bool f_for_title = false ) const;
878     int16 GetTitleNumber();
879 };
880
881 class matroska_script_interpretor_c
882 {
883 public:
884     matroska_script_interpretor_c( demux_sys_t & demuxer )
885     :sys( demuxer )
886     {}
887
888     bool Interpret( const binary * p_command, size_t i_size );
889  
890     // DVD command IDs
891     static const std::string CMD_MS_GOTO_AND_PLAY;
892  
893 protected:
894     demux_sys_t  & sys;
895 };
896
897 const std::string matroska_script_interpretor_c::CMD_MS_GOTO_AND_PLAY = "GotoAndPlay";
898
899
900 class matroska_script_codec_c : public chapter_codec_cmds_c
901 {
902 public:
903     matroska_script_codec_c( demux_sys_t & sys )
904     :chapter_codec_cmds_c( sys, 0 )
905     ,interpretor( sys )
906     {}
907
908     bool Enter();
909     bool Leave();
910
911 protected:
912     matroska_script_interpretor_c interpretor;
913 };
914
915 class chapter_translation_c
916 {
917 public:
918     chapter_translation_c()
919         :p_translated(NULL)
920     {}
921
922     ~chapter_translation_c()
923     {
924         delete p_translated;
925     }
926
927     KaxChapterTranslateID  *p_translated;
928     unsigned int           codec_id;
929     std::vector<uint64_t>  editions;
930 };
931
932 class chapter_item_c
933 {
934 public:
935     chapter_item_c()
936     :i_start_time(0)
937     ,i_end_time(-1)
938     ,i_user_start_time(-1)
939     ,i_user_end_time(-1)
940     ,i_seekpoint_num(-1)
941     ,b_display_seekpoint(true)
942     ,b_user_display(false)
943     ,psz_parent(NULL)
944     ,b_is_leaving(false)
945     {}
946
947     virtual ~chapter_item_c()
948     {
949         std::vector<chapter_codec_cmds_c*>::iterator index = codecs.begin();
950         while ( index != codecs.end() )
951         {
952             delete (*index);
953             index++;
954         }
955         std::vector<chapter_item_c*>::iterator index_ = sub_chapters.begin();
956         while ( index_ != sub_chapters.end() )
957         {
958             delete (*index_);
959             index_++;
960         }
961     }
962
963     int64_t RefreshChapters( bool b_ordered, int64_t i_prev_user_time );
964     int PublishChapters( input_title_t & title, int & i_user_chapters, int i_level = 0 );
965     virtual chapter_item_c * FindTimecode( mtime_t i_timecode, const chapter_item_c * p_current, bool & b_found );
966     void Append( const chapter_item_c & edition );
967     chapter_item_c * FindChapter( int64_t i_find_uid );
968     virtual chapter_item_c *BrowseCodecPrivate( unsigned int codec_id,
969                                     bool (*match)(const chapter_codec_cmds_c &data, const void *p_cookie, size_t i_cookie_size ),
970                                     const void *p_cookie,
971                                     size_t i_cookie_size );
972     std::string                 GetCodecName( bool f_for_title = false ) const;
973     bool                        ParentOf( const chapter_item_c & item ) const;
974     int16                       GetTitleNumber( ) const;
975  
976     int64_t                     i_start_time, i_end_time;
977     int64_t                     i_user_start_time, i_user_end_time; /* the time in the stream when an edition is ordered */
978     std::vector<chapter_item_c*> sub_chapters;
979     int                         i_seekpoint_num;
980     int64_t                     i_uid;
981     bool                        b_display_seekpoint;
982     bool                        b_user_display;
983     std::string                 psz_name;
984     chapter_item_c              *psz_parent;
985     bool                        b_is_leaving;
986  
987     std::vector<chapter_codec_cmds_c*> codecs;
988
989     static bool CompareTimecode( const chapter_item_c * itemA, const chapter_item_c * itemB )
990     {
991         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) );
992     }
993
994     bool Enter( bool b_do_subchapters );
995     bool Leave( bool b_do_subchapters );
996     bool EnterAndLeave( chapter_item_c *p_item, bool b_enter = true );
997 };
998
999 class chapter_edition_c : public chapter_item_c
1000 {
1001 public:
1002     chapter_edition_c()
1003     :b_ordered(false)
1004     {}
1005  
1006     void RefreshChapters( );
1007     mtime_t Duration() const;
1008     std::string GetMainName() const;
1009     chapter_item_c * FindTimecode( mtime_t i_timecode, const chapter_item_c * p_current );
1010  
1011     bool                        b_ordered;
1012 };
1013
1014 class matroska_segment_c
1015 {
1016 public:
1017     matroska_segment_c( demux_sys_t & demuxer, EbmlStream & estream )
1018         :segment(NULL)
1019         ,es(estream)
1020         ,i_timescale(MKVD_TIMECODESCALE)
1021         ,i_duration(-1)
1022         ,i_start_time(0)
1023         ,i_cues_position(-1)
1024         ,i_info_position(-1)
1025         ,i_chapters_position(-1)
1026         ,i_tags_position(-1)
1027         ,i_tracks_position(-1)
1028         ,i_attachments_position(-1)
1029         ,i_seekhead_position(-1)
1030         ,i_seekhead_count(0)
1031         ,cluster(NULL)
1032         ,i_block_pos(0)
1033         ,i_cluster_pos(0)
1034         ,i_start_pos(0)
1035         ,p_segment_uid(NULL)
1036         ,p_prev_segment_uid(NULL)
1037         ,p_next_segment_uid(NULL)
1038         ,b_cues(false)
1039         ,i_index(0)
1040         ,i_index_max(1024)
1041         ,psz_muxing_application(NULL)
1042         ,psz_writing_application(NULL)
1043         ,psz_segment_filename(NULL)
1044         ,psz_title(NULL)
1045         ,psz_date_utc(NULL)
1046         ,i_default_edition(0)
1047         ,sys(demuxer)
1048         ,ep(NULL)
1049         ,b_preloaded(false)
1050     {
1051         p_indexes = (mkv_index_t*)malloc( sizeof( mkv_index_t ) * i_index_max );
1052     }
1053
1054     virtual ~matroska_segment_c()
1055     {
1056         for( size_t i_track = 0; i_track < tracks.size(); i_track++ )
1057         {
1058             delete tracks[i_track]->p_compression_data;
1059             es_format_Clean( &tracks[i_track]->fmt );
1060             free( tracks[i_track]->p_extra_data );
1061             free( tracks[i_track]->psz_codec );
1062             delete tracks[i_track];
1063         }
1064
1065         free( psz_writing_application );
1066         free( psz_muxing_application );
1067         free( psz_segment_filename );
1068         free( psz_title );
1069         free( psz_date_utc );
1070         free( p_indexes );
1071
1072         delete ep;
1073         delete segment;
1074         delete p_segment_uid;
1075         delete p_prev_segment_uid;
1076         delete p_next_segment_uid;
1077
1078         std::vector<chapter_edition_c*>::iterator index = stored_editions.begin();
1079         while ( index != stored_editions.end() )
1080         {
1081             delete (*index);
1082             index++;
1083         }
1084         std::vector<chapter_translation_c*>::iterator indext = translations.begin();
1085         while ( indext != translations.end() )
1086         {
1087             delete (*indext);
1088             indext++;
1089         }
1090         std::vector<KaxSegmentFamily*>::iterator indexf = families.begin();
1091         while ( indexf != families.end() )
1092         {
1093             delete (*indexf);
1094             indexf++;
1095         }
1096     }
1097
1098     KaxSegment              *segment;
1099     EbmlStream              & es;
1100
1101     /* time scale */
1102     uint64_t                i_timescale;
1103
1104     /* duration of the segment */
1105     mtime_t                 i_duration;
1106     mtime_t                 i_start_time;
1107
1108     /* all tracks */
1109     std::vector<mkv_track_t*> tracks;
1110
1111     /* from seekhead */
1112     int                     i_seekhead_count;
1113     int64_t                 i_seekhead_position;
1114     int64_t                 i_cues_position;
1115     int64_t                 i_tracks_position;
1116     int64_t                 i_info_position;
1117     int64_t                 i_chapters_position;
1118     int64_t                 i_tags_position;
1119     int64_t                 i_attachments_position;
1120
1121     KaxCluster              *cluster;
1122     uint64                  i_block_pos;
1123     uint64                  i_cluster_pos;
1124     int64_t                 i_start_pos;
1125     KaxSegmentUID           *p_segment_uid;
1126     KaxPrevUID              *p_prev_segment_uid;
1127     KaxNextUID              *p_next_segment_uid;
1128
1129     bool                    b_cues;
1130     int                     i_index;
1131     int                     i_index_max;
1132     mkv_index_t             *p_indexes;
1133
1134     /* info */
1135     char                    *psz_muxing_application;
1136     char                    *psz_writing_application;
1137     char                    *psz_segment_filename;
1138     char                    *psz_title;
1139     char                    *psz_date_utc;
1140
1141     /* !!!!! GCC 3.3 bug on Darwin !!!!! */
1142     /* when you remove this variable the compiler issues an atomicity error */
1143     /* this variable only works when using std::vector<chapter_edition_c> */
1144     std::vector<chapter_edition_c*> stored_editions;
1145     int                             i_default_edition;
1146
1147     std::vector<chapter_translation_c*> translations;
1148     std::vector<KaxSegmentFamily*>  families;
1149  
1150     demux_sys_t                    & sys;
1151     EbmlParser                     *ep;
1152     bool                           b_preloaded;
1153
1154     bool Preload( );
1155     bool LoadSeekHeadItem( const EbmlCallbacks & ClassInfos, int64_t i_element_position );
1156     bool PreloadFamily( const matroska_segment_c & segment );
1157     void ParseInfo( KaxInfo *info );
1158     void ParseAttachments( KaxAttachments *attachments );
1159     void ParseChapters( KaxChapters *chapters );
1160     void ParseSeekHead( KaxSeekHead *seekhead );
1161     void ParseTracks( KaxTracks *tracks );
1162     void ParseChapterAtom( int i_level, KaxChapterAtom *ca, chapter_item_c & chapters );
1163     void ParseTrackEntry( KaxTrackEntry *m );
1164     void ParseCluster( );
1165     void IndexAppendCluster( KaxCluster *cluster );
1166     void LoadCues( KaxCues *cues );
1167     void LoadTags( KaxTags *tags );
1168     void InformationCreate( );
1169     void Seek( mtime_t i_date, mtime_t i_time_offset, int64_t i_global_position );
1170     int BlockGet( KaxBlock * &, KaxSimpleBlock * &, int64_t *, int64_t *, int64_t *);
1171
1172     int BlockFindTrackIndex( size_t *pi_track,
1173                              const KaxBlock *, const KaxSimpleBlock * );
1174
1175
1176     bool Select( mtime_t i_start_time );
1177     void UnSelect( );
1178
1179     static bool CompareSegmentUIDs( const matroska_segment_c * item_a, const matroska_segment_c * item_b );
1180 };
1181
1182 // class holding hard-linked segment together in the playback order
1183 class virtual_segment_c
1184 {
1185 public:
1186     virtual_segment_c( matroska_segment_c *p_segment )
1187         :p_editions(NULL)
1188         ,i_sys_title(0)
1189         ,i_current_segment(0)
1190         ,i_current_edition(-1)
1191         ,psz_current_chapter(NULL)
1192     {
1193         linked_segments.push_back( p_segment );
1194
1195         AppendUID( p_segment->p_segment_uid );
1196         AppendUID( p_segment->p_prev_segment_uid );
1197         AppendUID( p_segment->p_next_segment_uid );
1198     }
1199
1200     void Sort();
1201     size_t AddSegment( matroska_segment_c *p_segment );
1202     void PreloadLinked( );
1203     mtime_t Duration( ) const;
1204     void Seek( demux_t & demuxer, mtime_t i_date, mtime_t i_time_offset, chapter_item_c *psz_chapter, int64_t i_global_position );
1205
1206     inline chapter_edition_c *Edition()
1207     {
1208         if ( i_current_edition >= 0 && size_t(i_current_edition) < p_editions->size() )
1209             return (*p_editions)[i_current_edition];
1210         return NULL;
1211     }
1212
1213     matroska_segment_c * Segment() const
1214     {
1215         if ( linked_segments.size() == 0 || i_current_segment >= linked_segments.size() )
1216             return NULL;
1217         return linked_segments[i_current_segment];
1218     }
1219
1220     inline chapter_item_c *CurrentChapter() {
1221         return psz_current_chapter;
1222     }
1223
1224     bool SelectNext()
1225     {
1226         if ( i_current_segment < linked_segments.size()-1 )
1227         {
1228             i_current_segment++;
1229             return true;
1230         }
1231         return false;
1232     }
1233
1234     bool FindUID( KaxSegmentUID & uid ) const
1235     {
1236         for ( size_t i=0; i<linked_uids.size(); i++ )
1237         {
1238             if ( linked_uids[i] == uid )
1239                 return true;
1240         }
1241         return false;
1242     }
1243
1244     bool UpdateCurrentToChapter( demux_t & demux );
1245     void PrepareChapters( );
1246
1247     chapter_item_c *BrowseCodecPrivate( unsigned int codec_id,
1248                                         bool (*match)(const chapter_codec_cmds_c &data, const void *p_cookie, size_t i_cookie_size ),
1249                                         const void *p_cookie,
1250                                         size_t i_cookie_size );
1251     chapter_item_c *FindChapter( int64_t i_find_uid );
1252
1253     std::vector<chapter_edition_c*>  *p_editions;
1254     int                              i_sys_title;
1255
1256 protected:
1257     std::vector<matroska_segment_c*> linked_segments;
1258     std::vector<KaxSegmentUID>       linked_uids;
1259     size_t                           i_current_segment;
1260
1261     int                              i_current_edition;
1262     chapter_item_c                   *psz_current_chapter;
1263
1264     void                             AppendUID( const EbmlBinary * UID );
1265 };
1266
1267 class matroska_stream_c
1268 {
1269 public:
1270     matroska_stream_c( demux_sys_t & demuxer )
1271         :p_in(NULL)
1272         ,p_es(NULL)
1273         ,sys(demuxer)
1274     {}
1275
1276     virtual ~matroska_stream_c()
1277     {
1278         delete p_in;
1279         delete p_es;
1280     }
1281
1282     IOCallback         *p_in;
1283     EbmlStream         *p_es;
1284
1285     std::vector<matroska_segment_c*> segments;
1286
1287     demux_sys_t                      & sys;
1288 };
1289
1290 typedef struct
1291 {
1292     VLC_COMMON_MEMBERS
1293
1294     demux_t        *p_demux;
1295     vlc_mutex_t     lock;
1296
1297     bool            b_moved;
1298     bool            b_clicked;
1299     int             i_key_action;
1300
1301 } event_thread_t;
1302
1303
1304 class attachment_c
1305 {
1306 public:
1307     attachment_c()
1308         :p_data(NULL)
1309         ,i_size(0)
1310     {}
1311     virtual ~attachment_c()
1312     {
1313         free( p_data );
1314     }
1315
1316     std::string    psz_file_name;
1317     std::string    psz_mime_type;
1318     void          *p_data;
1319     int            i_size;
1320 };
1321
1322 class demux_sys_t
1323 {
1324 public:
1325     demux_sys_t( demux_t & demux )
1326         :demuxer(demux)
1327         ,i_pts(0)
1328         ,i_start_pts(0)
1329         ,i_chapter_time(0)
1330         ,meta(NULL)
1331         ,i_current_title(0)
1332         ,p_current_segment(NULL)
1333         ,dvd_interpretor( *this )
1334         ,f_duration(-1.0)
1335         ,b_ui_hooked(false)
1336         ,p_input(NULL)
1337         ,b_pci_packet_set(false)
1338         ,p_ev(NULL)
1339     {
1340         vlc_mutex_init( &lock_demuxer );
1341     }
1342
1343     virtual ~demux_sys_t()
1344     {
1345         StopUiThread();
1346         size_t i;
1347         for ( i=0; i<streams.size(); i++ )
1348             delete streams[i];
1349         for ( i=0; i<opened_segments.size(); i++ )
1350             delete opened_segments[i];
1351         for ( i=0; i<used_segments.size(); i++ )
1352             delete used_segments[i];
1353         for ( i=0; i<stored_attachments.size(); i++ )
1354             delete stored_attachments[i];
1355         if( meta ) vlc_meta_Delete( meta );
1356
1357         while( titles.size() )
1358         { vlc_input_title_Delete( titles.back() ); titles.pop_back();}
1359
1360         vlc_mutex_destroy( &lock_demuxer );
1361     }
1362
1363     /* current data */
1364     demux_t                 & demuxer;
1365
1366     mtime_t                 i_pts;
1367     mtime_t                 i_start_pts;
1368     mtime_t                 i_chapter_time;
1369
1370     vlc_meta_t              *meta;
1371
1372     std::vector<input_title_t*>      titles; // matroska editions
1373     size_t                           i_current_title;
1374
1375     std::vector<matroska_stream_c*>  streams;
1376     std::vector<attachment_c*>       stored_attachments;
1377     std::vector<matroska_segment_c*> opened_segments;
1378     std::vector<virtual_segment_c*>  used_segments;
1379     virtual_segment_c                *p_current_segment;
1380
1381     dvd_command_interpretor_c        dvd_interpretor;
1382
1383     /* duration of the stream */
1384     float                   f_duration;
1385
1386     matroska_segment_c *FindSegment( const EbmlBinary & uid ) const;
1387     chapter_item_c *BrowseCodecPrivate( unsigned int codec_id,
1388                                         bool (*match)(const chapter_codec_cmds_c &data, const void *p_cookie, size_t i_cookie_size ),
1389                                         const void *p_cookie,
1390                                         size_t i_cookie_size,
1391                                         virtual_segment_c * & p_segment_found );
1392     chapter_item_c *FindChapter( int64_t i_find_uid, virtual_segment_c * & p_segment_found );
1393
1394     void PreloadFamily( const matroska_segment_c & of_segment );
1395     void PreloadLinked( matroska_segment_c *p_segment );
1396     bool PreparePlayback( virtual_segment_c *p_new_segment );
1397     matroska_stream_c *AnalyseAllSegmentsFound( demux_t *p_demux, EbmlStream *p_estream, bool b_initial = false );
1398     void JumpTo( virtual_segment_c & p_segment, chapter_item_c * p_chapter );
1399
1400     void StartUiThread();
1401     void StopUiThread();
1402     bool b_ui_hooked;
1403     inline void SwapButtons();
1404
1405     /* for spu variables */
1406     input_thread_t *p_input;
1407     pci_t          pci_packet;
1408     bool           b_pci_packet_set;
1409     uint8_t        palette[4][4];
1410     vlc_mutex_t    lock_demuxer;
1411
1412     /* event */
1413     event_thread_t *p_ev;
1414     static void * EventThread( vlc_object_t *p_this );
1415     static int EventMouse( vlc_object_t *p_this, char const *psz_var,
1416                        vlc_value_t oldval, vlc_value_t newval, void *p_data );
1417     static int EventKey( vlc_object_t *p_this, char const *psz_var,
1418                      vlc_value_t oldval, vlc_value_t newval, void *p_data );
1419
1420
1421
1422 protected:
1423     virtual_segment_c *VirtualFromSegments( matroska_segment_c *p_segment ) const;
1424     bool IsUsedSegment( matroska_segment_c &p_segment ) const;
1425 };
1426
1427 static int  Demux  ( demux_t * );
1428 static int  Control( demux_t *, int, va_list );
1429 static void Seek   ( demux_t *, mtime_t i_date, double f_percent, chapter_item_c *psz_chapter );
1430
1431 #define MKV_IS_ID( el, C ) ( EbmlId( (*el) ) == C::ClassInfos.GlobalId )
1432
1433 static inline char * ToUTF8( const UTFstring &u )
1434 {
1435     return strdup( u.GetUTF8().c_str() );
1436 }
1437
1438 /*****************************************************************************
1439  * Open: initializes matroska demux structures
1440  *****************************************************************************/
1441 static int Open( vlc_object_t * p_this )
1442 {
1443     demux_t            *p_demux = (demux_t*)p_this;
1444     demux_sys_t        *p_sys;
1445     matroska_stream_c  *p_stream;
1446     matroska_segment_c *p_segment;
1447     const uint8_t      *p_peek;
1448     std::string         s_path, s_filename;
1449     vlc_stream_io_callback *p_io_callback;
1450     EbmlStream         *p_io_stream;
1451
1452     /* peek the begining */
1453     if( stream_Peek( p_demux->s, &p_peek, 4 ) < 4 ) return VLC_EGENERIC;
1454
1455     /* is a valid file */
1456     if( p_peek[0] != 0x1a || p_peek[1] != 0x45 ||
1457         p_peek[2] != 0xdf || p_peek[3] != 0xa3 ) return VLC_EGENERIC;
1458
1459     /* Set the demux function */
1460     p_demux->pf_demux   = Demux;
1461     p_demux->pf_control = Control;
1462     p_demux->p_sys      = p_sys = new demux_sys_t( *p_demux );
1463
1464     p_io_callback = new vlc_stream_io_callback( p_demux->s, false );
1465     p_io_stream = new EbmlStream( *p_io_callback );
1466
1467     if( p_io_stream == NULL )
1468     {
1469         msg_Err( p_demux, "failed to create EbmlStream" );
1470         delete p_io_callback;
1471         delete p_sys;
1472         return VLC_EGENERIC;
1473     }
1474
1475     p_stream = p_sys->AnalyseAllSegmentsFound( p_demux, p_io_stream, true );
1476     if( p_stream == NULL )
1477     {
1478         msg_Err( p_demux, "cannot find KaxSegment" );
1479         goto error;
1480     }
1481     p_sys->streams.push_back( p_stream );
1482
1483     p_stream->p_in = p_io_callback;
1484     p_stream->p_es = p_io_stream;
1485
1486     for (size_t i=0; i<p_stream->segments.size(); i++)
1487     {
1488         p_stream->segments[i]->Preload();
1489     }
1490
1491     p_segment = p_stream->segments[0];
1492     if( p_segment->cluster == NULL )
1493     {
1494         msg_Err( p_demux, "cannot find any cluster, damaged file ?" );
1495         goto error;
1496     }
1497
1498     if (config_GetInt( p_demux, "mkv-preload-local-dir" ))
1499     {
1500         /* get the files from the same dir from the same family (based on p_demux->psz_path) */
1501         if (p_demux->psz_path[0] != '\0' && !strcmp(p_demux->psz_access, ""))
1502         {
1503             // assume it's a regular file
1504             // get the directory path
1505             s_path = p_demux->psz_path;
1506             if (s_path.at(s_path.length() - 1) == DIRECTORY_SEPARATOR)
1507             {
1508                 s_path = s_path.substr(0,s_path.length()-1);
1509             }
1510             else
1511             {
1512                 if (s_path.find_last_of(DIRECTORY_SEPARATOR) > 0)
1513                 {
1514                     s_path = s_path.substr(0,s_path.find_last_of(DIRECTORY_SEPARATOR));
1515                 }
1516             }
1517
1518             DIR *p_src_dir = utf8_opendir(s_path.c_str());
1519
1520             if (p_src_dir != NULL)
1521             {
1522                 char *psz_file;
1523                 while ((psz_file = utf8_readdir(p_src_dir)) != NULL)
1524                 {
1525                     if (strlen(psz_file) > 4)
1526                     {
1527                         s_filename = s_path + DIRECTORY_SEPARATOR + psz_file;
1528
1529 #ifdef WIN32
1530                         if (!strcasecmp(s_filename.c_str(), p_demux->psz_path))
1531 #else
1532                         if (!s_filename.compare(p_demux->psz_path))
1533 #endif
1534                         {
1535                             free (psz_file);
1536                             continue; // don't reuse the original opened file
1537                         }
1538
1539 #if defined(__GNUC__) && (__GNUC__ < 3)
1540                         if (!s_filename.compare("mkv", s_filename.length() - 3, 3) ||
1541                             !s_filename.compare("mka", s_filename.length() - 3, 3))
1542 #else
1543                         if (!s_filename.compare(s_filename.length() - 3, 3, "mkv") ||
1544                             !s_filename.compare(s_filename.length() - 3, 3, "mka"))
1545 #endif
1546                         {
1547                             // test wether this file belongs to our family
1548                             const uint8_t *p_peek;
1549                             bool          file_ok = false;
1550                             stream_t      *p_file_stream = stream_UrlNew(
1551                                                             p_demux,
1552                                                             s_filename.c_str());
1553                             /* peek the begining */
1554                             if( p_file_stream &&
1555                                 stream_Peek( p_file_stream, &p_peek, 4 ) >= 4
1556                                 && p_peek[0] == 0x1a && p_peek[1] == 0x45 &&
1557                                 p_peek[2] == 0xdf && p_peek[3] == 0xa3 ) file_ok = true;
1558
1559                             if ( file_ok )
1560                             {
1561                                 vlc_stream_io_callback *p_file_io = new vlc_stream_io_callback( p_file_stream, true );
1562                                 EbmlStream *p_estream = new EbmlStream(*p_file_io);
1563
1564                                 p_stream = p_sys->AnalyseAllSegmentsFound( p_demux, p_estream );
1565
1566                                 if ( p_stream == NULL )
1567                                 {
1568                                     msg_Dbg( p_demux, "the file '%s' will not be used", s_filename.c_str() );
1569                                     delete p_estream;
1570                                     delete p_file_io;
1571                                 }
1572                                 else
1573                                 {
1574                                     p_stream->p_in = p_file_io;
1575                                     p_stream->p_es = p_estream;
1576                                     p_sys->streams.push_back( p_stream );
1577                                 }
1578                             }
1579                             else
1580                             {
1581                                 if( p_file_stream ) {
1582                                     stream_Delete( p_file_stream );
1583                                 }
1584                                 msg_Dbg( p_demux, "the file '%s' cannot be opened", s_filename.c_str() );
1585                             }
1586                         }
1587                     }
1588                     free (psz_file);
1589                 }
1590                 closedir( p_src_dir );
1591             }
1592         }
1593
1594         p_sys->PreloadFamily( *p_segment );
1595     }
1596
1597     p_sys->PreloadLinked( p_segment );
1598
1599     if ( !p_sys->PreparePlayback( NULL ) )
1600     {
1601         msg_Err( p_demux, "cannot use the segment" );
1602         goto error;
1603     }
1604
1605     p_sys->StartUiThread();
1606  
1607     return VLC_SUCCESS;
1608
1609 error:
1610     delete p_sys;
1611     return VLC_EGENERIC;
1612 }
1613
1614 /*****************************************************************************
1615  * Close: frees unused data
1616  *****************************************************************************/
1617 static void Close( vlc_object_t *p_this )
1618 {
1619     demux_t     *p_demux = (demux_t*)p_this;
1620     demux_sys_t *p_sys   = p_demux->p_sys;
1621
1622     delete p_sys;
1623 }
1624
1625 /*****************************************************************************
1626  * Control:
1627  *****************************************************************************/
1628 static int Control( demux_t *p_demux, int i_query, va_list args )
1629 {
1630     demux_sys_t        *p_sys = p_demux->p_sys;
1631     int64_t     *pi64;
1632     double      *pf, f;
1633     int         i_skp;
1634     size_t      i_idx;
1635
1636     vlc_meta_t *p_meta;
1637     input_attachment_t ***ppp_attach;
1638     int *pi_int;
1639     int i;
1640
1641     switch( i_query )
1642     {
1643         case DEMUX_GET_ATTACHMENTS:
1644             ppp_attach = (input_attachment_t***)va_arg( args, input_attachment_t*** );
1645             pi_int = (int*)va_arg( args, int * );
1646
1647             if( p_sys->stored_attachments.size() <= 0 )
1648                 return VLC_EGENERIC;
1649
1650             *pi_int = p_sys->stored_attachments.size();
1651             *ppp_attach = (input_attachment_t**)malloc( sizeof(input_attachment_t**) *
1652                                                         p_sys->stored_attachments.size() );
1653             if( !(*ppp_attach) )
1654                 return VLC_ENOMEM;
1655             for( i = 0; i < p_sys->stored_attachments.size(); i++ )
1656             {
1657                 attachment_c *a = p_sys->stored_attachments[i];
1658                 (*ppp_attach)[i] = vlc_input_attachment_New( a->psz_file_name.c_str(), a->psz_mime_type.c_str(), NULL,
1659                                                              a->p_data, a->i_size );
1660             }
1661             return VLC_SUCCESS;
1662
1663         case DEMUX_GET_META:
1664             p_meta = (vlc_meta_t*)va_arg( args, vlc_meta_t* );
1665             vlc_meta_Merge( p_meta, p_sys->meta );
1666             return VLC_SUCCESS;
1667
1668         case DEMUX_GET_LENGTH:
1669             pi64 = (int64_t*)va_arg( args, int64_t * );
1670             if( p_sys->f_duration > 0.0 )
1671             {
1672                 *pi64 = (int64_t)(p_sys->f_duration * 1000);
1673                 return VLC_SUCCESS;
1674             }
1675             return VLC_EGENERIC;
1676
1677         case DEMUX_GET_POSITION:
1678             pf = (double*)va_arg( args, double * );
1679             if ( p_sys->f_duration > 0.0 )
1680                 *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);
1681             return VLC_SUCCESS;
1682
1683         case DEMUX_SET_POSITION:
1684             f = (double)va_arg( args, double );
1685             Seek( p_demux, -1, f, NULL );
1686             return VLC_SUCCESS;
1687
1688         case DEMUX_GET_TIME:
1689             pi64 = (int64_t*)va_arg( args, int64_t * );
1690             *pi64 = p_sys->i_pts;
1691             return VLC_SUCCESS;
1692
1693         case DEMUX_GET_TITLE_INFO:
1694             if( p_sys->titles.size() > 1 || ( p_sys->titles.size() == 1 && p_sys->titles[0]->i_seekpoint > 0 ) )
1695             {
1696                 input_title_t ***ppp_title = (input_title_t***)va_arg( args, input_title_t*** );
1697                 int *pi_int    = (int*)va_arg( args, int* );
1698
1699                 *pi_int = p_sys->titles.size();
1700                 *ppp_title = (input_title_t**)malloc( sizeof( input_title_t**) * p_sys->titles.size() );
1701
1702                 for( size_t i = 0; i < p_sys->titles.size(); i++ )
1703                 {
1704                     (*ppp_title)[i] = vlc_input_title_Duplicate( p_sys->titles[i] );
1705                 }
1706                 return VLC_SUCCESS;
1707             }
1708             return VLC_EGENERIC;
1709
1710         case DEMUX_SET_TITLE:
1711             /* TODO handle editions as titles */
1712             i_idx = (int)va_arg( args, int );
1713             if( i_idx < p_sys->used_segments.size() )
1714             {
1715                 p_sys->JumpTo( *p_sys->used_segments[i_idx], NULL );
1716                 return VLC_SUCCESS;
1717             }
1718             return VLC_EGENERIC;
1719
1720         case DEMUX_SET_SEEKPOINT:
1721             i_skp = (int)va_arg( args, int );
1722
1723             // TODO change the way it works with the << & >> buttons on the UI (+1/-1 instead of a number)
1724             if( p_sys->titles.size() && i_skp < p_sys->titles[p_sys->i_current_title]->i_seekpoint)
1725             {
1726                 Seek( p_demux, (int64_t)p_sys->titles[p_sys->i_current_title]->seekpoint[i_skp]->i_time_offset, -1, NULL);
1727                 p_demux->info.i_seekpoint |= INPUT_UPDATE_SEEKPOINT;
1728                 p_demux->info.i_seekpoint = i_skp;
1729                 return VLC_SUCCESS;
1730             }
1731             return VLC_EGENERIC;
1732
1733         case DEMUX_GET_FPS:
1734             pf = (double *)va_arg( args, double * );
1735             *pf = 0.0;
1736             if( p_sys->p_current_segment && p_sys->p_current_segment->Segment() )
1737             {
1738                 const matroska_segment_c *p_segment = p_sys->p_current_segment->Segment();
1739                 for( size_t i = 0; i < p_segment->tracks.size(); i++ )
1740                 {
1741                     mkv_track_t *tk = p_segment->tracks[i];
1742                     if( tk->fmt.i_cat == VIDEO_ES && tk->fmt.video.i_frame_rate_base > 0 )
1743                     {
1744                         *pf = (double)tk->fmt.video.i_frame_rate / tk->fmt.video.i_frame_rate_base;
1745                         break;
1746                     }
1747                 }
1748             }
1749             return VLC_SUCCESS;
1750
1751         case DEMUX_SET_TIME:
1752         default:
1753             return VLC_EGENERIC;
1754     }
1755 }
1756
1757 int matroska_segment_c::BlockGet( KaxBlock * & pp_block, KaxSimpleBlock * & pp_simpleblock, int64_t *pi_ref1, int64_t *pi_ref2, int64_t *pi_duration )
1758 {
1759     pp_simpleblock = NULL;
1760     pp_block = NULL;
1761     *pi_ref1  = 0;
1762     *pi_ref2  = 0;
1763
1764     for( ;; )
1765     {
1766         EbmlElement *el = NULL;
1767         int         i_level;
1768
1769         if ( ep == NULL )
1770             return VLC_EGENERIC;
1771
1772         if( pp_simpleblock != NULL || ((el = ep->Get()) == NULL && pp_block != NULL) )
1773         {
1774             /* Check blocks validity to protect againts broken files */
1775             if( BlockFindTrackIndex( NULL, pp_block , pp_simpleblock ) )
1776             {
1777                 delete pp_block;
1778                 pp_simpleblock = NULL;
1779                 pp_block = NULL;
1780                 continue;
1781             }
1782
1783             /* update the index */
1784 #define idx p_indexes[i_index - 1]
1785             if( i_index > 0 && idx.i_time == -1 )
1786             {
1787                 if ( pp_simpleblock != NULL )
1788                     idx.i_time        = pp_simpleblock->GlobalTimecode() / (mtime_t)1000;
1789                 else
1790                     idx.i_time        = (*pp_block).GlobalTimecode() / (mtime_t)1000;
1791                 idx.b_key         = *pi_ref1 == 0 ? true : false;
1792             }
1793 #undef idx
1794             return VLC_SUCCESS;
1795         }
1796
1797         i_level = ep->GetLevel();
1798
1799         if( el == NULL )
1800         {
1801             if( i_level > 1 )
1802             {
1803                 ep->Up();
1804                 continue;
1805             }
1806             msg_Warn( &sys.demuxer, "EOF" );
1807             return VLC_EGENERIC;
1808         }
1809
1810         /* Verify that we are still inside our cluster
1811          * It can happens whith broken files and when seeking
1812          * without index */
1813         if( i_level > 1 )
1814         {
1815             if( cluster && !ep->IsTopPresent( cluster ) )
1816             {
1817                 msg_Warn( &sys.demuxer, "Unexpected escape from current cluster" );
1818                 cluster = NULL;
1819             }
1820             if( !cluster )
1821                 continue;
1822         }
1823
1824         /* do parsing */
1825         switch ( i_level )
1826         {
1827         case 1:
1828             if( MKV_IS_ID( el, KaxCluster ) )
1829             {
1830                 cluster = (KaxCluster*)el;
1831                 i_cluster_pos = cluster->GetElementPosition();
1832
1833                 /* add it to the index */
1834                 if( i_index == 0 ||
1835                     ( i_index > 0 && p_indexes[i_index - 1].i_position < (int64_t)cluster->GetElementPosition() ) )
1836                 {
1837                     IndexAppendCluster( cluster );
1838                 }
1839
1840                 // reset silent tracks
1841                 for (size_t i=0; i<tracks.size(); i++)
1842                 {
1843                     tracks[i]->b_silent = false;
1844                 }
1845
1846                 ep->Down();
1847             }
1848             else if( MKV_IS_ID( el, KaxCues ) )
1849             {
1850                 msg_Warn( &sys.demuxer, "find KaxCues FIXME" );
1851                 return VLC_EGENERIC;
1852             }
1853             else
1854             {
1855                 msg_Dbg( &sys.demuxer, "unknown (%s)", typeid( el ).name() );
1856             }
1857             break;
1858         case 2:
1859             if( MKV_IS_ID( el, KaxClusterTimecode ) )
1860             {
1861                 KaxClusterTimecode &ctc = *(KaxClusterTimecode*)el;
1862
1863                 ctc.ReadData( es.I_O(), SCOPE_ALL_DATA );
1864                 cluster->InitTimecode( uint64( ctc ), i_timescale );
1865             }
1866             else if( MKV_IS_ID( el, KaxClusterSilentTracks ) )
1867             {
1868                 ep->Down();
1869             }
1870             else if( MKV_IS_ID( el, KaxBlockGroup ) )
1871             {
1872                 i_block_pos = el->GetElementPosition();
1873                 ep->Down();
1874             }
1875             else if( MKV_IS_ID( el, KaxSimpleBlock ) )
1876             {
1877                 pp_simpleblock = (KaxSimpleBlock*)el;
1878
1879                 pp_simpleblock->ReadData( es.I_O() );
1880                 pp_simpleblock->SetParent( *cluster );
1881             }
1882             break;
1883         case 3:
1884             if( MKV_IS_ID( el, KaxBlock ) )
1885             {
1886                 pp_block = (KaxBlock*)el;
1887
1888                 pp_block->ReadData( es.I_O() );
1889                 pp_block->SetParent( *cluster );
1890
1891                 ep->Keep();
1892             }
1893             else if( MKV_IS_ID( el, KaxBlockDuration ) )
1894             {
1895                 KaxBlockDuration &dur = *(KaxBlockDuration*)el;
1896
1897                 dur.ReadData( es.I_O() );
1898                 *pi_duration = uint64( dur );
1899             }
1900             else if( MKV_IS_ID( el, KaxReferenceBlock ) )
1901             {
1902                 KaxReferenceBlock &ref = *(KaxReferenceBlock*)el;
1903
1904                 ref.ReadData( es.I_O() );
1905                 if( *pi_ref1 == 0 )
1906                 {
1907                     *pi_ref1 = int64( ref ) * cluster->GlobalTimecodeScale();
1908                 }
1909                 else if( *pi_ref2 == 0 )
1910                 {
1911                     *pi_ref2 = int64( ref ) * cluster->GlobalTimecodeScale();
1912                 }
1913             }
1914             else if( MKV_IS_ID( el, KaxClusterSilentTrackNumber ) )
1915             {
1916                 KaxClusterSilentTrackNumber &track_num = *(KaxClusterSilentTrackNumber*)el;
1917                 track_num.ReadData( es.I_O() );
1918                 // find the track
1919                 for (size_t i=0; i<tracks.size(); i++)
1920                 {
1921                     if ( tracks[i]->i_number == uint32(track_num))
1922                     {
1923                         tracks[i]->b_silent = true;
1924                         break;
1925                     }
1926                 }
1927             }
1928             break;
1929         default:
1930             msg_Err( &sys.demuxer, "invalid level = %d", i_level );
1931             return VLC_EGENERIC;
1932         }
1933     }
1934 }
1935
1936 static block_t *MemToBlock( demux_t *p_demux, uint8_t *p_mem, int i_mem, size_t offset)
1937 {
1938     block_t *p_block;
1939     if( !(p_block = block_New( p_demux, i_mem + offset ) ) ) return NULL;
1940     memcpy( p_block->p_buffer + offset, p_mem, i_mem );
1941     //p_block->i_rate = p_input->stream.control.i_rate;
1942     return p_block;
1943 }
1944
1945 static void BlockDecode( demux_t *p_demux, KaxBlock *block, KaxSimpleBlock *simpleblock,
1946                          mtime_t i_pts, mtime_t i_duration, bool f_mandatory )
1947 {
1948     demux_sys_t        *p_sys = p_demux->p_sys;
1949     matroska_segment_c *p_segment = p_sys->p_current_segment->Segment();
1950
1951     size_t          i_track;
1952     unsigned int    i;
1953     bool            b;
1954
1955     if( p_segment->BlockFindTrackIndex( &i_track, block, simpleblock ) )
1956     {
1957         msg_Err( p_demux, "invalid track number" );
1958         return;
1959     }
1960
1961     mkv_track_t *tk = p_segment->tracks[i_track];
1962
1963     if( tk->fmt.i_cat != NAV_ES && tk->p_es == NULL )
1964     {
1965         msg_Err( p_demux, "unknown track number" );
1966         return;
1967     }
1968     if( i_pts + i_duration < p_sys->i_start_pts && tk->fmt.i_cat == AUDIO_ES )
1969     {
1970         return; /* discard audio packets that shouldn't be rendered */
1971     }
1972
1973     if ( tk->fmt.i_cat != NAV_ES )
1974     {
1975         es_out_Control( p_demux->out, ES_OUT_GET_ES_STATE, tk->p_es, &b );
1976
1977         if( !b )
1978         {
1979             tk->b_inited = false;
1980             return;
1981         }
1982     }
1983
1984
1985     /* First send init data */
1986     if( !tk->b_inited && tk->i_data_init > 0 )
1987     {
1988         block_t *p_init;
1989
1990         msg_Dbg( p_demux, "sending header (%d bytes)", tk->i_data_init );
1991         p_init = MemToBlock( p_demux, tk->p_data_init, tk->i_data_init, 0 );
1992         if( p_init ) es_out_Send( p_demux->out, tk->p_es, p_init );
1993     }
1994     tk->b_inited = true;
1995
1996
1997     for( i = 0;
1998          (block != NULL && i < block->NumberFrames()) || (simpleblock != NULL && i < simpleblock->NumberFrames());
1999          i++ )
2000     {
2001         block_t *p_block;
2002         DataBuffer *data;
2003         if( simpleblock != NULL )
2004         {
2005             data = &simpleblock->GetBuffer(i);
2006             // condition when the DTS is correct (keyframe or B frame == NOT P frame)
2007             f_mandatory = simpleblock->IsDiscardable() || simpleblock->IsKeyframe();
2008         }
2009         else
2010         {
2011             data = &block->GetBuffer(i);
2012         }
2013
2014         if( tk->i_compression_type == MATROSKA_COMPRESSION_HEADER && tk->p_compression_data != NULL )
2015             p_block = MemToBlock( p_demux, data->Buffer(), data->Size(), tk->p_compression_data->GetSize() );
2016         else
2017             p_block = MemToBlock( p_demux, data->Buffer(), data->Size(), 0 );
2018
2019         if( p_block == NULL )
2020         {
2021             break;
2022         }
2023
2024 #if defined(HAVE_ZLIB_H)
2025         if( tk->i_compression_type == MATROSKA_COMPRESSION_ZLIB )
2026         {
2027             p_block = block_zlib_decompress( VLC_OBJECT(p_demux), p_block );
2028         }
2029         else
2030 #endif
2031         if( tk->i_compression_type == MATROSKA_COMPRESSION_HEADER )
2032         {
2033             memcpy( p_block->p_buffer, tk->p_compression_data->GetBuffer(), tk->p_compression_data->GetSize() );
2034         }
2035
2036         if ( tk->fmt.i_cat == NAV_ES )
2037         {
2038             // TODO handle the start/stop times of this packet
2039             if ( p_sys->b_ui_hooked )
2040             {
2041                 vlc_mutex_lock( &p_sys->p_ev->lock );
2042                 memcpy( &p_sys->pci_packet, &p_block->p_buffer[1], sizeof(pci_t) );
2043                 p_sys->SwapButtons();
2044                 p_sys->b_pci_packet_set = true;
2045                 vlc_mutex_unlock( &p_sys->p_ev->lock );
2046                 block_Release( p_block );
2047             }
2048             return;
2049         }
2050         // correct timestamping when B frames are used
2051         if( tk->fmt.i_cat != VIDEO_ES )
2052         {
2053             p_block->i_dts = p_block->i_pts = i_pts;
2054         }
2055         else
2056         {
2057             if( !strcmp( tk->psz_codec, "V_MS/VFW/FOURCC" ) )
2058             {
2059                 // in VFW we have no idea about B frames
2060                 p_block->i_pts = 0;
2061                 p_block->i_dts = i_pts;
2062             }
2063             else
2064             {
2065                 p_block->i_pts = i_pts;
2066                 if ( f_mandatory )
2067                     p_block->i_dts = p_block->i_pts;
2068                 else
2069                     p_block->i_dts = min( i_pts, tk->i_last_dts + (mtime_t)(tk->i_default_duration >> 10));
2070                 p_sys->i_pts = p_block->i_dts;
2071             }
2072         }
2073         tk->i_last_dts = p_block->i_dts;
2074
2075 #if 0
2076 msg_Dbg( p_demux, "block i_dts: %"PRId64" / i_pts: %"PRId64, p_block->i_dts, p_block->i_pts);
2077 #endif
2078         if( strcmp( tk->psz_codec, "S_VOBSUB" ) )
2079         {
2080             p_block->i_length = i_duration * 1000;
2081         }
2082
2083         es_out_Send( p_demux->out, tk->p_es, p_block );
2084
2085         /* use time stamp only for first block */
2086         i_pts = 0;
2087     }
2088 }
2089
2090 matroska_stream_c *demux_sys_t::AnalyseAllSegmentsFound( demux_t *p_demux, EbmlStream *p_estream, bool b_initial )
2091 {
2092     int i_upper_lvl = 0;
2093     size_t i;
2094     EbmlElement *p_l0, *p_l1, *p_l2;
2095     bool b_keep_stream = false, b_keep_segment;
2096
2097     // verify the EBML Header
2098     p_l0 = p_estream->FindNextID(EbmlHead::ClassInfos, 0xFFFFFFFFL);
2099     if (p_l0 == NULL)
2100     {
2101         msg_Err( p_demux, "No EBML header found" );
2102         return NULL;
2103     }
2104
2105     // verify we can read this Segment, we only support Matroska version 1 for now
2106     p_l0->Read(*p_estream, EbmlHead::ClassInfos.Context, i_upper_lvl, p_l0, true);
2107
2108     EDocType doc_type = GetChild<EDocType>(*static_cast<EbmlHead*>(p_l0));
2109     if (std::string(doc_type) != "matroska")
2110     {
2111         msg_Err( p_demux, "Not a Matroska file : DocType = %s ", std::string(doc_type).c_str());
2112         return NULL;
2113     }
2114
2115     EDocTypeReadVersion doc_read_version = GetChild<EDocTypeReadVersion>(*static_cast<EbmlHead*>(p_l0));
2116     if (uint64(doc_read_version) > 2)
2117     {
2118         msg_Err( p_demux, "This matroska file is needs version %"PRId64" and this VLC only supports version 1 & 2", uint64(doc_read_version));
2119         return NULL;
2120     }
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                                                        true );
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_EAC3" ) )
2414         {
2415             tracks[i_track]->fmt.i_codec = VLC_FOURCC( 'e', 'a', 'c', '3' );
2416         }
2417         else if( !strcmp( tracks[i_track]->psz_codec, "A_DTS" ) )
2418         {
2419             tracks[i_track]->fmt.i_codec = VLC_FOURCC( 'd', 't', 's', ' ' );
2420         }
2421         else if( !strcmp( tracks[i_track]->psz_codec, "A_FLAC" ) )
2422         {
2423             tracks[i_track]->fmt.i_codec = VLC_FOURCC( 'f', 'l', 'a', 'c' );
2424             tracks[i_track]->fmt.i_extra = tracks[i_track]->i_extra_data;
2425             tracks[i_track]->fmt.p_extra = malloc( tracks[i_track]->i_extra_data );
2426             memcpy( tracks[i_track]->fmt.p_extra,tracks[i_track]->p_extra_data, tracks[i_track]->i_extra_data );
2427         }
2428         else if( !strcmp( tracks[i_track]->psz_codec, "A_VORBIS" ) )
2429         {
2430             int i, i_offset = 1, i_size[3], i_extra;
2431             uint8_t *p_extra;
2432
2433             tracks[i_track]->fmt.i_codec = VLC_FOURCC( 'v', 'o', 'r', 'b' );
2434
2435             /* Split the 3 headers */
2436             if( tracks[i_track]->p_extra_data[0] != 0x02 )
2437                 msg_Err( &sys.demuxer, "invalid vorbis header" );
2438
2439             for( i = 0; i < 2; i++ )
2440             {
2441                 i_size[i] = 0;
2442                 while( i_offset < tracks[i_track]->i_extra_data )
2443                 {
2444                     i_size[i] += tracks[i_track]->p_extra_data[i_offset];
2445                     if( tracks[i_track]->p_extra_data[i_offset++] != 0xff ) break;
2446                 }
2447             }
2448
2449             i_size[0] = __MIN(i_size[0], tracks[i_track]->i_extra_data - i_offset);
2450             i_size[1] = __MIN(i_size[1], tracks[i_track]->i_extra_data -i_offset -i_size[0]);
2451             i_size[2] = tracks[i_track]->i_extra_data - i_offset - i_size[0] - i_size[1];
2452
2453             tracks[i_track]->fmt.i_extra = 3 * 2 + i_size[0] + i_size[1] + i_size[2];
2454             tracks[i_track]->fmt.p_extra = malloc( tracks[i_track]->fmt.i_extra );
2455             p_extra = (uint8_t *)tracks[i_track]->fmt.p_extra; i_extra = 0;
2456             for( i = 0; i < 3; i++ )
2457             {
2458                 *(p_extra++) = i_size[i] >> 8;
2459                 *(p_extra++) = i_size[i] & 0xFF;
2460                 memcpy( p_extra, tracks[i_track]->p_extra_data + i_offset + i_extra,
2461                         i_size[i] );
2462                 p_extra += i_size[i];
2463                 i_extra += i_size[i];
2464             }
2465         }
2466         else if( !strncmp( tracks[i_track]->psz_codec, "A_AAC/MPEG2/", strlen( "A_AAC/MPEG2/" ) ) ||
2467                  !strncmp( tracks[i_track]->psz_codec, "A_AAC/MPEG4/", strlen( "A_AAC/MPEG4/" ) ) )
2468         {
2469             int i_profile, i_srate, sbr = 0;
2470             static const unsigned int i_sample_rates[] =
2471             {
2472                     96000, 88200, 64000, 48000, 44100, 32000, 24000, 22050,
2473                         16000, 12000, 11025, 8000,  7350,  0,     0,     0
2474             };
2475
2476             tracks[i_track]->fmt.i_codec = VLC_FOURCC( 'm', 'p', '4', 'a' );
2477             /* create data for faad (MP4DecSpecificDescrTag)*/
2478
2479             if( !strcmp( &tracks[i_track]->psz_codec[12], "MAIN" ) )
2480             {
2481                 i_profile = 0;
2482             }
2483             else if( !strcmp( &tracks[i_track]->psz_codec[12], "LC" ) )
2484             {
2485                 i_profile = 1;
2486             }
2487             else if( !strcmp( &tracks[i_track]->psz_codec[12], "SSR" ) )
2488             {
2489                 i_profile = 2;
2490             }
2491             else if( !strcmp( &tracks[i_track]->psz_codec[12], "LC/SBR" ) )
2492             {
2493                 i_profile = 1;
2494                 sbr = 1;
2495             }
2496             else
2497             {
2498                 i_profile = 3;
2499             }
2500
2501             for( i_srate = 0; i_srate < 13; i_srate++ )
2502             {
2503                 if( i_sample_rates[i_srate] == tracks[i_track]->i_original_rate )
2504                 {
2505                     break;
2506                 }
2507             }
2508             msg_Dbg( &sys.demuxer, "profile=%d srate=%d", i_profile, i_srate );
2509
2510             tracks[i_track]->fmt.i_extra = sbr ? 5 : 2;
2511             tracks[i_track]->fmt.p_extra = malloc( tracks[i_track]->fmt.i_extra );
2512             ((uint8_t*)tracks[i_track]->fmt.p_extra)[0] = ((i_profile + 1) << 3) | ((i_srate&0xe) >> 1);
2513             ((uint8_t*)tracks[i_track]->fmt.p_extra)[1] = ((i_srate & 0x1) << 7) | (tracks[i_track]->fmt.audio.i_channels << 3);
2514             if (sbr != 0)
2515             {
2516                 int syncExtensionType = 0x2B7;
2517                 int iDSRI;
2518                 for (iDSRI=0; iDSRI<13; iDSRI++)
2519                     if( i_sample_rates[iDSRI] == tracks[i_track]->fmt.audio.i_rate )
2520                         break;
2521                 ((uint8_t*)tracks[i_track]->fmt.p_extra)[2] = (syncExtensionType >> 3) & 0xFF;
2522                 ((uint8_t*)tracks[i_track]->fmt.p_extra)[3] = ((syncExtensionType & 0x7) << 5) | 5;
2523                 ((uint8_t*)tracks[i_track]->fmt.p_extra)[4] = ((1 & 0x1) << 7) | (iDSRI << 3);
2524             }
2525         }
2526         else if( !strcmp( tracks[i_track]->psz_codec, "A_AAC" ) )
2527         {
2528             tracks[i_track]->fmt.i_codec = VLC_FOURCC( 'm', 'p', '4', 'a' );
2529             tracks[i_track]->fmt.i_extra = tracks[i_track]->i_extra_data;
2530             tracks[i_track]->fmt.p_extra = malloc( tracks[i_track]->i_extra_data );
2531             memcpy( tracks[i_track]->fmt.p_extra, tracks[i_track]->p_extra_data, tracks[i_track]->i_extra_data );
2532         }
2533         else if( !strcmp( tracks[i_track]->psz_codec, "A_WAVPACK4" ) )
2534         {
2535             tracks[i_track]->fmt.i_codec = VLC_FOURCC( 'W', 'V', 'P', 'K' );
2536             tracks[i_track]->fmt.i_extra = tracks[i_track]->i_extra_data;
2537             tracks[i_track]->fmt.p_extra = malloc( tracks[i_track]->i_extra_data );
2538             memcpy( tracks[i_track]->fmt.p_extra, tracks[i_track]->p_extra_data, tracks[i_track]->i_extra_data );
2539         }
2540         else if( !strcmp( tracks[i_track]->psz_codec, "A_TTA1" ) )
2541         {
2542             tracks[i_track]->fmt.i_codec = VLC_FOURCC( 'T', 'T', 'A', '1' );
2543             tracks[i_track]->fmt.i_extra = tracks[i_track]->i_extra_data;
2544             tracks[i_track]->fmt.p_extra = malloc( tracks[i_track]->i_extra_data );
2545             memcpy( tracks[i_track]->fmt.p_extra, tracks[i_track]->p_extra_data, tracks[i_track]->i_extra_data );
2546         }
2547         else if( !strcmp( tracks[i_track]->psz_codec, "A_PCM/INT/BIG" ) ||
2548                  !strcmp( tracks[i_track]->psz_codec, "A_PCM/INT/LIT" ) ||
2549                  !strcmp( tracks[i_track]->psz_codec, "A_PCM/FLOAT/IEEE" ) )
2550         {
2551             if( !strcmp( tracks[i_track]->psz_codec, "A_PCM/INT/BIG" ) )
2552             {
2553                 tracks[i_track]->fmt.i_codec = VLC_FOURCC( 't', 'w', 'o', 's' );
2554             }
2555             else
2556             {
2557                 tracks[i_track]->fmt.i_codec = VLC_FOURCC( 'a', 'r', 'a', 'w' );
2558             }
2559             tracks[i_track]->fmt.audio.i_blockalign = ( tracks[i_track]->fmt.audio.i_bitspersample + 7 ) / 8 * tracks[i_track]->fmt.audio.i_channels;
2560         }
2561         /* disabled due to the potential "S_KATE" namespace issue */
2562         else if( !strcmp( tracks[i_track]->psz_codec, "S_KATE" ) )
2563         {
2564             int i, i_offset = 1, *i_size, i_extra, num_headers, size_so_far;
2565             uint8_t *p_extra;
2566
2567             tracks[i_track]->fmt.i_codec = VLC_FOURCC( 'k', 'a', 't', 'e' );
2568             tracks[i_track]->fmt.subs.psz_encoding = strdup( "UTF-8" );
2569
2570             /* Recover the number of headers to expect */
2571             num_headers = tracks[i_track]->p_extra_data[0]+1;
2572             msg_Dbg( &sys.demuxer, "kate in mkv detected: %d headers in %u bytes",
2573                 num_headers, tracks[i_track]->i_extra_data);
2574
2575             /* this won't overflow the stack as is can allocate only 1020 bytes max */
2576             i_size = (int*)alloca(num_headers*sizeof(int));
2577
2578             /* Split the headers */
2579             size_so_far = 0;
2580             for( i = 0; i < num_headers-1; i++ )
2581             {
2582                 i_size[i] = 0;
2583                 while( i_offset < tracks[i_track]->i_extra_data )
2584                 {
2585                     i_size[i] += tracks[i_track]->p_extra_data[i_offset];
2586                     if( tracks[i_track]->p_extra_data[i_offset++] != 0xff ) break;
2587                 }
2588                 msg_Dbg( &sys.demuxer, "kate header %d is %d bytes", i, i_size[i]);
2589                 size_so_far += i_size[i];
2590             }
2591             i_size[num_headers-1] = tracks[i_track]->i_extra_data - (size_so_far+i_offset);
2592             msg_Dbg( &sys.demuxer, "kate last header (%d) is %d bytes", num_headers-1, i_size[num_headers-1]);
2593
2594             tracks[i_track]->fmt.i_extra = 1 + num_headers * 2 + size_so_far + i_size[num_headers-1];
2595             tracks[i_track]->fmt.p_extra = malloc( tracks[i_track]->fmt.i_extra );
2596
2597             p_extra = (uint8_t *)tracks[i_track]->fmt.p_extra;
2598             i_extra = 0;
2599             *(p_extra++) = num_headers;
2600             ++i_extra;
2601             for( i = 0; i < num_headers; i++ )
2602             {
2603                 *(p_extra++) = i_size[i] >> 8;
2604                 *(p_extra++) = i_size[i] & 0xFF;
2605                 memcpy( p_extra, tracks[i_track]->p_extra_data + i_offset + i_extra-1,
2606                         i_size[i] );
2607                 p_extra += i_size[i];
2608                 i_extra += i_size[i];
2609             }
2610         }
2611         else if( !strcmp( tracks[i_track]->psz_codec, "S_TEXT/UTF8" ) )
2612         {
2613             tracks[i_track]->fmt.i_codec = VLC_FOURCC( 's', 'u', 'b', 't' );
2614             tracks[i_track]->fmt.subs.psz_encoding = strdup( "UTF-8" );
2615         }
2616         else if( !strcmp( tracks[i_track]->psz_codec, "S_TEXT/USF" ) )
2617         {
2618             tracks[i_track]->fmt.i_codec = VLC_FOURCC( 'u', 's', 'f', ' ' );
2619             tracks[i_track]->fmt.subs.psz_encoding = strdup( "UTF-8" );
2620             if( tracks[i_track]->i_extra_data )
2621             {
2622                 tracks[i_track]->fmt.i_extra = tracks[i_track]->i_extra_data;
2623                 tracks[i_track]->fmt.p_extra = malloc( tracks[i_track]->i_extra_data );
2624                 memcpy( tracks[i_track]->fmt.p_extra, tracks[i_track]->p_extra_data, tracks[i_track]->i_extra_data );
2625             }
2626         }
2627         else if( !strcmp( tracks[i_track]->psz_codec, "S_TEXT/SSA" ) ||
2628                  !strcmp( tracks[i_track]->psz_codec, "S_TEXT/ASS" ) ||
2629                  !strcmp( tracks[i_track]->psz_codec, "S_SSA" ) ||
2630                  !strcmp( tracks[i_track]->psz_codec, "S_ASS" ))
2631         {
2632             tracks[i_track]->fmt.i_codec = VLC_FOURCC( 's', 's', 'a', ' ' );
2633             tracks[i_track]->fmt.subs.psz_encoding = strdup( "UTF-8" );
2634             if( tracks[i_track]->i_extra_data )
2635             {
2636                 tracks[i_track]->fmt.i_extra = tracks[i_track]->i_extra_data;
2637                 tracks[i_track]->fmt.p_extra = malloc( tracks[i_track]->i_extra_data );
2638                 memcpy( tracks[i_track]->fmt.p_extra, tracks[i_track]->p_extra_data, tracks[i_track]->i_extra_data );
2639             }
2640         }
2641         else if( !strcmp( tracks[i_track]->psz_codec, "S_VOBSUB" ) )
2642         {
2643             tracks[i_track]->fmt.i_codec = VLC_FOURCC( 's','p','u',' ' );
2644             if( tracks[i_track]->i_extra_data )
2645             {
2646                 char *p_start;
2647                 char *p_buf = (char *)malloc( tracks[i_track]->i_extra_data + 1);
2648                 memcpy( p_buf, tracks[i_track]->p_extra_data , tracks[i_track]->i_extra_data );
2649                 p_buf[tracks[i_track]->i_extra_data] = '\0';
2650  
2651                 p_start = strstr( p_buf, "size:" );
2652                 if( sscanf( p_start, "size: %dx%d",
2653                         &tracks[i_track]->fmt.subs.spu.i_original_frame_width, &tracks[i_track]->fmt.subs.spu.i_original_frame_height ) == 2 )
2654                 {
2655                     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 );
2656                 }
2657                 else
2658                 {
2659                     msg_Warn( &sys.demuxer, "reading original frame size for vobsub failed" );
2660                 }
2661                 free( p_buf );
2662             }
2663         }
2664         else if( !strcmp( tracks[i_track]->psz_codec, "B_VOBBTN" ) )
2665         {
2666             tracks[i_track]->fmt.i_cat = NAV_ES;
2667             continue;
2668         }
2669         else
2670         {
2671             msg_Err( &sys.demuxer, "unknown codec id=`%s'", tracks[i_track]->psz_codec );
2672             tracks[i_track]->fmt.i_codec = VLC_FOURCC( 'u', 'n', 'd', 'f' );
2673         }
2674         if( tracks[i_track]->b_default )
2675         {
2676             tracks[i_track]->fmt.i_priority = 1000;
2677         }
2678
2679         tracks[i_track]->p_es = es_out_Add( sys.demuxer.out, &tracks[i_track]->fmt );
2680
2681         /* Turn on a subtitles track if it has been flagged as default -
2682          * but only do this if no subtitles track has already been engaged,
2683          * either by an earlier 'default track' (??) or by default
2684          * language choice behaviour.
2685          */
2686         if( tracks[i_track]->b_default )
2687         {
2688             es_out_Control( sys.demuxer.out,
2689                             ES_OUT_SET_DEFAULT,
2690                             tracks[i_track]->p_es );
2691         }
2692
2693         es_out_Control( sys.demuxer.out, ES_OUT_SET_NEXT_DISPLAY_TIME, tracks[i_track]->p_es, i_start_time );
2694     }
2695  
2696     sys.i_start_pts = i_start_time;
2697     // reset the stream reading to the first cluster of the segment used
2698     es.I_O().setFilePointer( i_start_pos );
2699
2700     delete ep;
2701     ep = new EbmlParser( &es, segment, &sys.demuxer );
2702
2703     return true;
2704 }
2705
2706 void demux_sys_t::StartUiThread()
2707 {
2708     if ( !b_ui_hooked )
2709     {
2710         msg_Dbg( &demuxer, "Starting the UI Hook" );
2711         b_ui_hooked = true;
2712         /* FIXME hack hack hack hack FIXME */
2713         /* Get p_input and create variable */
2714         p_input = (input_thread_t *) vlc_object_find( &demuxer, VLC_OBJECT_INPUT, FIND_PARENT );
2715         var_Create( p_input, "x-start", VLC_VAR_INTEGER );
2716         var_Create( p_input, "y-start", VLC_VAR_INTEGER );
2717         var_Create( p_input, "x-end", VLC_VAR_INTEGER );
2718         var_Create( p_input, "y-end", VLC_VAR_INTEGER );
2719         var_Create( p_input, "color", VLC_VAR_ADDRESS );
2720         var_Create( p_input, "menu-palette", VLC_VAR_ADDRESS );
2721         var_Create( p_input, "highlight", VLC_VAR_BOOL );
2722         var_Create( p_input, "highlight-mutex", VLC_VAR_MUTEX );
2723
2724         /* Now create our event thread catcher */
2725         p_ev = (event_thread_t *) vlc_object_create( &demuxer, sizeof( event_thread_t ) );
2726         p_ev->p_demux = &demuxer;
2727         p_ev->b_die = false;
2728         vlc_mutex_init( &p_ev->lock );
2729         vlc_thread_create( p_ev, "mkv event thread handler", EventThread,
2730                         VLC_THREAD_PRIORITY_LOW, false );
2731     }
2732 }
2733
2734 void demux_sys_t::StopUiThread()
2735 {
2736     if ( b_ui_hooked )
2737     {
2738         vlc_object_kill( p_ev );
2739         vlc_thread_join( p_ev );
2740         vlc_object_release( p_ev );
2741
2742         p_ev = NULL;
2743
2744         var_Destroy( p_input, "highlight-mutex" );
2745         var_Destroy( p_input, "highlight" );
2746         var_Destroy( p_input, "x-start" );
2747         var_Destroy( p_input, "x-end" );
2748         var_Destroy( p_input, "y-start" );
2749         var_Destroy( p_input, "y-end" );
2750         var_Destroy( p_input, "color" );
2751         var_Destroy( p_input, "menu-palette" );
2752
2753         vlc_object_release( p_input );
2754
2755         msg_Dbg( &demuxer, "Stopping the UI Hook" );
2756     }
2757     b_ui_hooked = false;
2758 }
2759
2760 int demux_sys_t::EventMouse( vlc_object_t *p_this, char const *psz_var,
2761                        vlc_value_t oldval, vlc_value_t newval, void *p_data )
2762 {
2763     event_thread_t *p_ev = (event_thread_t *) p_data;
2764     vlc_mutex_lock( &p_ev->lock );
2765     if( psz_var[6] == 'c' )
2766     {
2767         p_ev->b_clicked = true;
2768         msg_Dbg( p_this, "Event Mouse: clicked");
2769     }
2770     else if( psz_var[6] == 'm' )
2771         p_ev->b_moved = true;
2772     vlc_mutex_unlock( &p_ev->lock );
2773
2774     return VLC_SUCCESS;
2775 }
2776
2777 int demux_sys_t::EventKey( vlc_object_t *p_this, char const *,
2778                            vlc_value_t, vlc_value_t newval, void *p_data )
2779 {
2780     event_thread_t *p_ev = (event_thread_t *) p_data;
2781     vlc_mutex_lock( &p_ev->lock );
2782     p_ev->i_key_action = newval.i_int;
2783     vlc_mutex_unlock( &p_ev->lock );
2784     msg_Dbg( p_this, "Event Key");
2785
2786     return VLC_SUCCESS;
2787 }
2788
2789 void * demux_sys_t::EventThread( vlc_object_t *p_this )
2790 {
2791     event_thread_t *p_ev = (event_thread_t*)p_this;
2792     demux_sys_t    *p_sys = p_ev->p_demux->p_sys;
2793     vlc_object_t   *p_vout = NULL;
2794     int canc = vlc_savecancel ();
2795
2796     p_ev->b_moved   = false;
2797     p_ev->b_clicked = false;
2798     p_ev->i_key_action = 0;
2799
2800     /* catch all key event */
2801     var_AddCallback( p_ev->p_libvlc, "key-action", EventKey, p_ev );
2802
2803     /* main loop */
2804     while( vlc_object_alive (p_ev) )
2805     {
2806         if ( !p_sys->b_pci_packet_set )
2807         {
2808             /* Wait 100ms */
2809             msleep( 100000 );
2810             continue;
2811         }
2812
2813         bool b_activated = false;
2814
2815         /* KEY part */
2816         if( p_ev->i_key_action )
2817         {
2818             int i;
2819
2820             msg_Dbg( p_ev->p_demux, "Handle Key Event");
2821
2822             vlc_mutex_lock( &p_ev->lock );
2823
2824             pci_t *pci = (pci_t *) &p_sys->pci_packet;
2825
2826             uint16 i_curr_button = p_sys->dvd_interpretor.GetSPRM( 0x88 );
2827
2828             switch( p_ev->i_key_action )
2829             {
2830             case ACTIONID_NAV_LEFT:
2831                 if ( i_curr_button > 0 && i_curr_button <= pci->hli.hl_gi.btn_ns )
2832                 {
2833                     btni_t *p_button_ptr = &(pci->hli.btnit[i_curr_button-1]);
2834                     if ( p_button_ptr->left > 0 && p_button_ptr->left <= pci->hli.hl_gi.btn_ns )
2835                     {
2836                         i_curr_button = p_button_ptr->left;
2837                         p_sys->dvd_interpretor.SetSPRM( 0x88, i_curr_button );
2838                         btni_t button_ptr = pci->hli.btnit[i_curr_button-1];
2839                         if ( button_ptr.auto_action_mode )
2840                         {
2841                             vlc_mutex_unlock( &p_ev->lock );
2842                             vlc_mutex_lock( &p_sys->lock_demuxer );
2843
2844                             // process the button action
2845                             p_sys->dvd_interpretor.Interpret( button_ptr.cmd.bytes, 8 );
2846
2847                             vlc_mutex_unlock( &p_sys->lock_demuxer );
2848                             vlc_mutex_lock( &p_ev->lock );
2849                         }
2850                     }
2851                 }
2852                 break;
2853             case ACTIONID_NAV_RIGHT:
2854                 if ( i_curr_button > 0 && i_curr_button <= pci->hli.hl_gi.btn_ns )
2855                 {
2856                     btni_t *p_button_ptr = &(pci->hli.btnit[i_curr_button-1]);
2857                     if ( p_button_ptr->right > 0 && p_button_ptr->right <= pci->hli.hl_gi.btn_ns )
2858                     {
2859                         i_curr_button = p_button_ptr->right;
2860                         p_sys->dvd_interpretor.SetSPRM( 0x88, i_curr_button );
2861                         btni_t button_ptr = pci->hli.btnit[i_curr_button-1];
2862                         if ( button_ptr.auto_action_mode )
2863                         {
2864                             vlc_mutex_unlock( &p_ev->lock );
2865                             vlc_mutex_lock( &p_sys->lock_demuxer );
2866
2867                             // process the button action
2868                             p_sys->dvd_interpretor.Interpret( button_ptr.cmd.bytes, 8 );
2869
2870                             vlc_mutex_unlock( &p_sys->lock_demuxer );
2871                             vlc_mutex_lock( &p_ev->lock );
2872                         }
2873                     }
2874                 }
2875                 break;
2876             case ACTIONID_NAV_UP:
2877                 if ( i_curr_button > 0 && i_curr_button <= pci->hli.hl_gi.btn_ns )
2878                 {
2879                     btni_t *p_button_ptr = &(pci->hli.btnit[i_curr_button-1]);
2880                     if ( p_button_ptr->up > 0 && p_button_ptr->up <= pci->hli.hl_gi.btn_ns )
2881                     {
2882                         i_curr_button = p_button_ptr->up;
2883                         p_sys->dvd_interpretor.SetSPRM( 0x88, i_curr_button );
2884                         btni_t button_ptr = pci->hli.btnit[i_curr_button-1];
2885                         if ( button_ptr.auto_action_mode )
2886                         {
2887                             vlc_mutex_unlock( &p_ev->lock );
2888                             vlc_mutex_lock( &p_sys->lock_demuxer );
2889
2890                             // process the button action
2891                             p_sys->dvd_interpretor.Interpret( button_ptr.cmd.bytes, 8 );
2892
2893                             vlc_mutex_unlock( &p_sys->lock_demuxer );
2894                             vlc_mutex_lock( &p_ev->lock );
2895                         }
2896                     }
2897                 }
2898                 break;
2899             case ACTIONID_NAV_DOWN:
2900                 if ( i_curr_button > 0 && i_curr_button <= pci->hli.hl_gi.btn_ns )
2901                 {
2902                     btni_t *p_button_ptr = &(pci->hli.btnit[i_curr_button-1]);
2903                     if ( p_button_ptr->down > 0 && p_button_ptr->down <= pci->hli.hl_gi.btn_ns )
2904                     {
2905                         i_curr_button = p_button_ptr->down;
2906                         p_sys->dvd_interpretor.SetSPRM( 0x88, i_curr_button );
2907                         btni_t button_ptr = pci->hli.btnit[i_curr_button-1];
2908                         if ( button_ptr.auto_action_mode )
2909                         {
2910                             vlc_mutex_unlock( &p_ev->lock );
2911                             vlc_mutex_lock( &p_sys->lock_demuxer );
2912
2913                             // process the button action
2914                             p_sys->dvd_interpretor.Interpret( button_ptr.cmd.bytes, 8 );
2915
2916                             vlc_mutex_unlock( &p_sys->lock_demuxer );
2917                             vlc_mutex_lock( &p_ev->lock );
2918                         }
2919                     }
2920                 }
2921                 break;
2922             case ACTIONID_NAV_ACTIVATE:
2923                 b_activated = true;
2924  
2925                 if ( i_curr_button > 0 && i_curr_button <= pci->hli.hl_gi.btn_ns )
2926                 {
2927                     btni_t button_ptr = pci->hli.btnit[i_curr_button-1];
2928
2929                     vlc_mutex_unlock( &p_ev->lock );
2930                     vlc_mutex_lock( &p_sys->lock_demuxer );
2931
2932                     // process the button action
2933                     p_sys->dvd_interpretor.Interpret( button_ptr.cmd.bytes, 8 );
2934
2935                     vlc_mutex_unlock( &p_sys->lock_demuxer );
2936                     vlc_mutex_lock( &p_ev->lock );
2937                 }
2938                 break;
2939             default:
2940                 break;
2941             }
2942             p_ev->i_key_action = 0;
2943             vlc_mutex_unlock( &p_ev->lock );
2944         }
2945
2946         /* MOUSE part */
2947         if( p_vout && ( p_ev->b_moved || p_ev->b_clicked ) )
2948         {
2949             vlc_value_t valx, valy;
2950
2951             vlc_mutex_lock( &p_ev->lock );
2952             pci_t *pci = (pci_t *) &p_sys->pci_packet;
2953             var_Get( p_vout, "mouse-x", &valx );
2954             var_Get( p_vout, "mouse-y", &valy );
2955
2956             if( p_ev->b_clicked )
2957             {
2958                 int32_t button;
2959                 int32_t best,dist,d;
2960                 int32_t mx,my,dx,dy;
2961
2962                 msg_Dbg( p_ev->p_demux, "Handle Mouse Event: Mouse clicked x(%d)*y(%d)", (unsigned)valx.i_int, (unsigned)valy.i_int);
2963
2964                 b_activated = true;
2965                 // get current button
2966                 best = 0;
2967                 dist = 0x08000000; /* >> than  (720*720)+(567*567); */
2968                 for(button = 1; button <= pci->hli.hl_gi.btn_ns; button++)
2969                 {
2970                     btni_t *button_ptr = &(pci->hli.btnit[button-1]);
2971
2972                     if(((unsigned)valx.i_int >= button_ptr->x_start)
2973                      && ((unsigned)valx.i_int <= button_ptr->x_end)
2974                      && ((unsigned)valy.i_int >= button_ptr->y_start)
2975                      && ((unsigned)valy.i_int <= button_ptr->y_end))
2976                     {
2977                         mx = (button_ptr->x_start + button_ptr->x_end)/2;
2978                         my = (button_ptr->y_start + button_ptr->y_end)/2;
2979                         dx = mx - valx.i_int;
2980                         dy = my - valy.i_int;
2981                         d = (dx*dx) + (dy*dy);
2982                         /* If the mouse is within the button and the mouse is closer
2983                         * to the center of this button then it is the best choice. */
2984                         if(d < dist) {
2985                             dist = d;
2986                             best = button;
2987                         }
2988                     }
2989                 }
2990
2991                 if ( best != 0)
2992                 {
2993                     btni_t button_ptr = pci->hli.btnit[best-1];
2994                     uint16 i_curr_button = p_sys->dvd_interpretor.GetSPRM( 0x88 );
2995
2996                     msg_Dbg( &p_sys->demuxer, "Clicked button %d", best );
2997                     vlc_mutex_unlock( &p_ev->lock );
2998                     vlc_mutex_lock( &p_sys->lock_demuxer );
2999
3000                     // process the button action
3001                     p_sys->dvd_interpretor.SetSPRM( 0x88, best );
3002                     p_sys->dvd_interpretor.Interpret( button_ptr.cmd.bytes, 8 );
3003
3004                     msg_Dbg( &p_sys->demuxer, "Processed button %d", best );
3005
3006                     // select new button
3007                     if ( best != i_curr_button )
3008                     {
3009                         vlc_value_t val;
3010
3011                         if( var_Get( p_sys->p_input, "highlight-mutex", &val ) == VLC_SUCCESS )
3012                         {
3013                             vlc_mutex_t *p_mutex = (vlc_mutex_t *) val.p_address;
3014                             uint32_t i_palette;
3015
3016                             if(button_ptr.btn_coln != 0) {
3017                                 i_palette = pci->hli.btn_colit.btn_coli[button_ptr.btn_coln-1][1];
3018                             } else {
3019                                 i_palette = 0;
3020                             }
3021
3022                             for( int i = 0; i < 4; i++ )
3023                             {
3024                                 uint32_t i_yuv = 0xFF;//p_sys->clut[(hl.palette>>(16+i*4))&0x0f];
3025                                 uint8_t i_alpha = (i_palette>>(i*4))&0x0f;
3026                                 i_alpha = i_alpha == 0xf ? 0xff : i_alpha << 4;
3027
3028                                 p_sys->palette[i][0] = (i_yuv >> 16) & 0xff;
3029                                 p_sys->palette[i][1] = (i_yuv >> 0) & 0xff;
3030                                 p_sys->palette[i][2] = (i_yuv >> 8) & 0xff;
3031                                 p_sys->palette[i][3] = i_alpha;
3032                             }
3033
3034                             vlc_mutex_lock( p_mutex );
3035                             val.i_int = button_ptr.x_start; var_Set( p_sys->p_input, "x-start", val );
3036                             val.i_int = button_ptr.x_end;   var_Set( p_sys->p_input, "x-end",   val );
3037                             val.i_int = button_ptr.y_start; var_Set( p_sys->p_input, "y-start", val );
3038                             val.i_int = button_ptr.y_end;   var_Set( p_sys->p_input, "y-end",   val );
3039
3040                             val.p_address = (void *)p_sys->palette;
3041                             var_Set( p_sys->p_input, "menu-palette", val );
3042
3043                             val.b_bool = true; var_Set( p_sys->p_input, "highlight", val );
3044                             vlc_mutex_unlock( p_mutex );
3045                         }
3046                     }
3047                     vlc_mutex_unlock( &p_sys->lock_demuxer );
3048                     vlc_mutex_lock( &p_ev->lock );
3049                 }
3050             }
3051             else if( p_ev->b_moved )
3052             {
3053 //                dvdnav_mouse_select( NULL, pci, valx.i_int, valy.i_int );
3054             }
3055
3056             p_ev->b_moved = false;
3057             p_ev->b_clicked = false;
3058             vlc_mutex_unlock( &p_ev->lock );
3059         }
3060
3061         /* VOUT part */
3062         if( p_vout && !vlc_object_alive (p_vout) )
3063         {
3064             var_DelCallback( p_vout, "mouse-moved", EventMouse, p_ev );
3065             var_DelCallback( p_vout, "mouse-clicked", EventMouse, p_ev );
3066             vlc_object_release( p_vout );
3067             p_vout = NULL;
3068         }
3069
3070         else if( p_vout == NULL )
3071         {
3072             p_vout = (vlc_object_t*) vlc_object_find( p_sys->p_input, VLC_OBJECT_VOUT,
3073                                       FIND_CHILD );
3074             if( p_vout)
3075             {
3076                 var_AddCallback( p_vout, "mouse-moved", EventMouse, p_ev );
3077                 var_AddCallback( p_vout, "mouse-clicked", EventMouse, p_ev );
3078             }
3079         }
3080
3081         /* Wait a bit, 10ms */
3082         msleep( 10000 );
3083     }
3084
3085     /* Release callback */
3086     if( p_vout )
3087     {
3088         var_DelCallback( p_vout, "mouse-moved", EventMouse, p_ev );
3089         var_DelCallback( p_vout, "mouse-clicked", EventMouse, p_ev );
3090         vlc_object_release( p_vout );
3091     }
3092     var_DelCallback( p_ev->p_libvlc, "key-action", EventKey, p_ev );
3093
3094     vlc_mutex_destroy( &p_ev->lock );
3095
3096     vlc_restorecancel (canc);
3097     return VLC_SUCCESS;
3098 }
3099
3100 void matroska_segment_c::UnSelect( )
3101 {
3102     size_t i_track;
3103
3104     for( i_track = 0; i_track < tracks.size(); i_track++ )
3105     {
3106         if ( tracks[i_track]->p_es != NULL )
3107         {
3108 //            es_format_Clean( &tracks[i_track]->fmt );
3109             es_out_Del( sys.demuxer.out, tracks[i_track]->p_es );
3110             tracks[i_track]->p_es = NULL;
3111         }
3112     }
3113     delete ep;
3114     ep = NULL;
3115 }
3116
3117 void virtual_segment_c::PrepareChapters( )
3118 {
3119     if ( linked_segments.size() == 0 )
3120         return;
3121
3122     // !!! should be called only once !!!
3123     matroska_segment_c