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