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