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