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