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