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