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