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