- WTF?! Do not use non-existant vlc_closedir_wrapper
[vlc.git] / 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 #include <stdlib.h>                                      /* malloc(), free() */
29
30 #include <vlc/vlc.h>
31
32 #ifdef HAVE_TIME_H
33 #   include <time.h>                                               /* time() */
34 #endif
35
36
37 #include <vlc_codecs.h>               /* BITMAPINFOHEADER, WAVEFORMATEX */
38 #include "iso_lang.h"
39 #include "vlc_meta.h"
40 #include <vlc_charset.h>
41 #include <vlc_input.h>
42 #include <vlc_demux.h>
43
44 #include <iostream>
45 #include <cassert>
46 #include <typeinfo>
47 #include <string>
48 #include <vector>
49 #include <algorithm>
50
51 #ifdef HAVE_DIRENT_H
52 #   include <dirent.h>
53 #endif
54
55 /* libebml and matroska */
56 #include "ebml/EbmlHead.h"
57 #include "ebml/EbmlSubHead.h"
58 #include "ebml/EbmlStream.h"
59 #include "ebml/EbmlContexts.h"
60 #include "ebml/EbmlVoid.h"
61 #include "ebml/EbmlVersion.h"
62 #include "ebml/StdIOCallback.h"
63
64 #include "matroska/KaxAttachments.h"
65 #include "matroska/KaxBlock.h"
66 #include "matroska/KaxBlockData.h"
67 #include "matroska/KaxChapters.h"
68 #include "matroska/KaxCluster.h"
69 #include "matroska/KaxClusterData.h"
70 #include "matroska/KaxContexts.h"
71 #include "matroska/KaxCues.h"
72 #include "matroska/KaxCuesData.h"
73 #include "matroska/KaxInfo.h"
74 #include "matroska/KaxInfoData.h"
75 #include "matroska/KaxSeekHead.h"
76 #include "matroska/KaxSegment.h"
77 #include "matroska/KaxTag.h"
78 #include "matroska/KaxTags.h"
79 #include "matroska/KaxTagMulti.h"
80 #include "matroska/KaxTracks.h"
81 #include "matroska/KaxTrackAudio.h"
82 #include "matroska/KaxTrackVideo.h"
83 #include "matroska/KaxTrackEntryData.h"
84 #include "matroska/KaxContentEncoding.h"
85 #include "matroska/KaxVersion.h"
86
87 #include "ebml/StdIOCallback.h"
88
89 #if LIBMATROSKA_VERSION < 0x000706
90 START_LIBMATROSKA_NAMESPACE
91 extern const EbmlSemanticContext MATROSKA_DLL_API KaxMatroska_Context;
92 END_LIBMATROSKA_NAMESPACE
93 #endif
94
95 #include "vlc_keys.h"
96
97 extern "C" {
98    #include "mp4/libmp4.h"
99 }
100 #ifdef HAVE_ZLIB_H
101 #   include <zlib.h>
102 #endif
103
104 #define MATROSKA_COMPRESSION_NONE  -1
105 #define MATROSKA_COMPRESSION_ZLIB   0
106 #define MATROSKA_COMPRESSION_BLIB   1
107 #define MATROSKA_COMPRESSION_LZOX   2
108 #define MATROSKA_COMPRESSION_HEADER 3
109
110 #define MKVD_TIMECODESCALE 1000000
111
112 ////////////////////////////////////////////////////////////////////////////////////////////////////////////////
113 #undef ATTRIBUTE_PACKED
114 #undef PRAGMA_PACK_BEGIN
115 #undef PRAGMA_PACK_END
116
117 #if defined(__GNUC__)
118 #if __GNUC__ > 2 || (__GNUC__ == 2 && __GNUC_MINOR__ >= 95)
119 #define ATTRIBUTE_PACKED __attribute__ ((packed))
120 #define PRAGMA_PACK 0
121 #endif
122 #endif
123
124 #if !defined(ATTRIBUTE_PACKED)
125 #define ATTRIBUTE_PACKED
126 #define PRAGMA_PACK 1
127 #endif
128
129 #if PRAGMA_PACK
130 #pragma pack(1)
131 #endif
132
133 /*************************************
134 *  taken from libdvdnav / libdvdread
135 **************************************/
136
137 /**
138  * DVD Time Information.
139  */
140 typedef struct {
141   uint8_t hour;
142   uint8_t minute;
143   uint8_t second;
144   uint8_t frame_u; /* The two high bits are the frame rate. */
145 } ATTRIBUTE_PACKED dvd_time_t;
146
147 /**
148  * User Operations.
149  */
150 typedef struct {
151 #ifdef WORDS_BIGENDIAN
152   unsigned char zero                           : 7; /* 25-31 */
153   unsigned char video_pres_mode_change         : 1; /* 24 */
154   
155   unsigned char karaoke_audio_pres_mode_change : 1; /* 23 */
156   unsigned char angle_change                   : 1;
157   unsigned char subpic_stream_change           : 1;
158   unsigned char audio_stream_change            : 1;
159   unsigned char pause_on                       : 1;
160   unsigned char still_off                      : 1;
161   unsigned char button_select_or_activate      : 1;
162   unsigned char resume                         : 1; /* 16 */
163   
164   unsigned char chapter_menu_call              : 1; /* 15 */
165   unsigned char angle_menu_call                : 1;
166   unsigned char audio_menu_call                : 1;
167   unsigned char subpic_menu_call               : 1;
168   unsigned char root_menu_call                 : 1;
169   unsigned char title_menu_call                : 1;
170   unsigned char backward_scan                  : 1;
171   unsigned char forward_scan                   : 1; /* 8 */
172   
173   unsigned char next_pg_search                 : 1; /* 7 */
174   unsigned char prev_or_top_pg_search          : 1;
175   unsigned char time_or_chapter_search         : 1;
176   unsigned char go_up                          : 1;
177   unsigned char stop                           : 1;
178   unsigned char title_play                     : 1;
179   unsigned char chapter_search_or_play         : 1;
180   unsigned char title_or_time_play             : 1; /* 0 */
181 #else
182   unsigned char video_pres_mode_change         : 1; /* 24 */
183   unsigned char zero                           : 7; /* 25-31 */
184   
185   unsigned char resume                         : 1; /* 16 */
186   unsigned char button_select_or_activate      : 1;
187   unsigned char still_off                      : 1;
188   unsigned char pause_on                       : 1;
189   unsigned char audio_stream_change            : 1;
190   unsigned char subpic_stream_change           : 1;
191   unsigned char angle_change                   : 1;
192   unsigned char karaoke_audio_pres_mode_change : 1; /* 23 */
193   
194   unsigned char forward_scan                   : 1; /* 8 */
195   unsigned char backward_scan                  : 1;
196   unsigned char title_menu_call                : 1;
197   unsigned char root_menu_call                 : 1;
198   unsigned char subpic_menu_call               : 1;
199   unsigned char audio_menu_call                : 1;
200   unsigned char angle_menu_call                : 1;
201   unsigned char chapter_menu_call              : 1; /* 15 */
202   
203   unsigned char title_or_time_play             : 1; /* 0 */
204   unsigned char chapter_search_or_play         : 1;
205   unsigned char title_play                     : 1;
206   unsigned char stop                           : 1;
207   unsigned char go_up                          : 1;
208   unsigned char time_or_chapter_search         : 1;
209   unsigned char prev_or_top_pg_search          : 1;
210   unsigned char next_pg_search                 : 1; /* 7 */
211 #endif
212 } ATTRIBUTE_PACKED user_ops_t;
213
214 /**
215  * Type to store per-command data.
216  */
217 typedef struct {
218   uint8_t bytes[8];
219 } ATTRIBUTE_PACKED vm_cmd_t;
220 #define COMMAND_DATA_SIZE 8
221
222 /**
223  * PCI General Information
224  */
225 typedef struct {
226   uint32_t nv_pck_lbn;      /**< sector address of this nav pack */
227   uint16_t vobu_cat;        /**< 'category' of vobu */
228   uint16_t zero1;           /**< reserved */
229   user_ops_t vobu_uop_ctl;  /**< UOP of vobu */
230   uint32_t vobu_s_ptm;      /**< start presentation time of vobu */
231   uint32_t vobu_e_ptm;      /**< end presentation time of vobu */
232   uint32_t vobu_se_e_ptm;   /**< end ptm of sequence end in vobu */
233   dvd_time_t e_eltm;        /**< Cell elapsed time */
234   char vobu_isrc[32];
235 } ATTRIBUTE_PACKED pci_gi_t;
236
237 /**
238  * Non Seamless Angle Information
239  */
240 typedef struct {
241   uint32_t nsml_agl_dsta[9];  /**< address of destination vobu in AGL_C#n */
242 } ATTRIBUTE_PACKED nsml_agli_t;
243
244 /**
245  * Highlight General Information
246  *
247  * For btngrX_dsp_ty the bits have the following meaning:
248  * 000b: normal 4/3 only buttons
249  * XX1b: wide (16/9) buttons
250  * X1Xb: letterbox buttons
251  * 1XXb: pan&scan buttons
252  */
253 typedef struct {
254   uint16_t hli_ss; /**< status, only low 2 bits 0: no buttons, 1: different 2: equal 3: eual except for button cmds */
255   uint32_t hli_s_ptm;              /**< start ptm of hli */
256   uint32_t hli_e_ptm;              /**< end ptm of hli */
257   uint32_t btn_se_e_ptm;           /**< end ptm of button select */
258 #ifdef WORDS_BIGENDIAN
259   unsigned char zero1 : 2;          /**< reserved */
260   unsigned char btngr_ns : 2;       /**< number of button groups 1, 2 or 3 with 36/18/12 buttons */
261   unsigned char zero2 : 1;          /**< reserved */
262   unsigned char btngr1_dsp_ty : 3;  /**< display type of subpic stream for button group 1 */
263   unsigned char zero3 : 1;          /**< reserved */
264   unsigned char btngr2_dsp_ty : 3;  /**< display type of subpic stream for button group 2 */
265   unsigned char zero4 : 1;          /**< reserved */
266   unsigned char btngr3_dsp_ty : 3;  /**< display type of subpic stream for button group 3 */
267 #else
268   unsigned char btngr1_dsp_ty : 3;
269   unsigned char zero2 : 1;
270   unsigned char btngr_ns : 2;
271   unsigned char zero1 : 2;
272   unsigned char btngr3_dsp_ty : 3;
273   unsigned char zero4 : 1;
274   unsigned char btngr2_dsp_ty : 3;
275   unsigned char zero3 : 1;
276 #endif
277   uint8_t btn_ofn;     /**< button offset number range 0-255 */
278   uint8_t btn_ns;      /**< number of valid buttons  <= 36/18/12 (low 6 bits) */
279   uint8_t nsl_btn_ns;  /**< number of buttons selectable by U_BTNNi (low 6 bits)   nsl_btn_ns <= btn_ns */
280   uint8_t zero5;       /**< reserved */
281   uint8_t fosl_btnn;   /**< forcedly selected button  (low 6 bits) */
282   uint8_t foac_btnn;   /**< forcedly activated button (low 6 bits) */
283 } ATTRIBUTE_PACKED hl_gi_t;
284
285
286 /**
287  * Button Color Information Table
288  * Each entry beeing a 32bit word that contains the color indexs and alpha
289  * values to use.  They are all represented by 4 bit number and stored
290  * like this [Ci3, Ci2, Ci1, Ci0, A3, A2, A1, A0].   The actual palette
291  * that the indexes reference is in the PGC.
292  * \todo split the uint32_t into a struct
293  */
294 typedef struct {
295   uint32_t btn_coli[3][2];  /**< [button color number-1][select:0/action:1] */
296 } ATTRIBUTE_PACKED btn_colit_t;
297
298 /**
299  * Button Information
300  *
301  * NOTE: I've had to change the structure from the disk layout to get
302  * the packing to work with Sun's Forte C compiler.
303  * The 4 and 7 bytes are 'rotated' was: ABC DEF GHIJ  is: ABCG DEFH IJ
304  */
305 typedef struct {
306 #ifdef WORDS_BIGENDIAN
307   uint32        btn_coln         : 2;  /**< button color number */
308   uint32        x_start          : 10; /**< x start offset within the overlay */
309   uint32        zero1            : 2;  /**< reserved */
310   uint32        x_end            : 10; /**< x end offset within the overlay */
311
312   uint32        zero3            : 2;  /**< reserved */
313   uint32        up               : 6;  /**< button index when pressing up */
314
315   uint32        auto_action_mode : 2;  /**< 0: no, 1: activated if selected */
316   uint32        y_start          : 10; /**< y start offset within the overlay */
317   uint32        zero2            : 2;  /**< reserved */
318   uint32        y_end            : 10; /**< y end offset within the overlay */
319
320   uint32        zero4            : 2;  /**< reserved */
321   uint32        down             : 6;  /**< button index when pressing down */
322   unsigned char zero5            : 2;  /**< reserved */
323   unsigned char left             : 6;  /**< button index when pressing left */
324   unsigned char zero6            : 2;  /**< reserved */
325   unsigned char right            : 6;  /**< button index when pressing right */
326 #else
327   uint32        x_end            : 10;
328   uint32        zero1            : 2;
329   uint32        x_start          : 10;
330   uint32        btn_coln         : 2;
331
332   uint32        up               : 6;
333   uint32        zero3            : 2;
334
335   uint32        y_end            : 10;
336   uint32        zero2            : 2;
337   uint32        y_start          : 10;
338   uint32        auto_action_mode : 2;
339
340   uint32        down             : 6;
341   uint32        zero4            : 2;
342   unsigned char left             : 6;
343   unsigned char zero5            : 2;
344   unsigned char right            : 6;
345   unsigned char zero6            : 2;
346 #endif
347   vm_cmd_t cmd;
348 } ATTRIBUTE_PACKED btni_t;
349
350 /**
351  * Highlight Information
352  */
353 typedef struct {
354   hl_gi_t     hl_gi;
355   btn_colit_t btn_colit;
356   btni_t      btnit[36];
357 } ATTRIBUTE_PACKED hli_t;
358
359 /**
360  * PCI packet
361  */
362 typedef struct {
363   pci_gi_t    pci_gi;
364   nsml_agli_t nsml_agli;
365   hli_t       hli;
366   uint8_t     zero1[189];
367 } ATTRIBUTE_PACKED pci_t;
368
369
370 #if PRAGMA_PACK
371 #pragma pack()
372 #endif
373 ////////////////////////////////////////////////////////////////////////////////////////////////////////////////
374
375
376 /**
377  * What's between a directory and a filename?
378  */
379 #if defined( WIN32 )
380     #define DIRECTORY_SEPARATOR '\\'
381 #else
382     #define DIRECTORY_SEPARATOR '/'
383 #endif
384
385 using namespace LIBMATROSKA_NAMESPACE;
386 using namespace std;
387
388 /*****************************************************************************
389  * Module descriptor
390  *****************************************************************************/
391 static int  Open ( vlc_object_t * );
392 static void Close( vlc_object_t * );
393
394 vlc_module_begin();
395     set_shortname( "Matroska" );
396     set_description( _("Matroska stream demuxer" ) );
397     set_capability( "demux2", 50 );
398     set_callbacks( Open, Close );
399     set_category( CAT_INPUT );
400     set_subcategory( SUBCAT_INPUT_DEMUX );
401
402     add_bool( "mkv-use-ordered-chapters", 1, NULL,
403             N_("Ordered chapters"),
404             N_("Play ordered chapters as specified in the segment."), VLC_TRUE );
405
406     add_bool( "mkv-use-chapter-codec", 1, NULL,
407             N_("Chapter codecs"),
408             N_("Use chapter codecs found in the segment."), VLC_TRUE );
409
410     add_bool( "mkv-preload-local-dir", 1, NULL,
411             N_("Preload Directory"),
412             N_("Preload matroska files from the same family in the same directory (not good for broken files)."), VLC_TRUE );
413
414     add_bool( "mkv-seek-percent", 0, NULL,
415             N_("Seek based on percent not time"),
416             N_("Seek based on percent not time."), VLC_TRUE );
417
418     add_bool( "mkv-use-dummy", 0, NULL,
419             N_("Dummy Elements"),
420             N_("Read and discard unknown EBML elements (not good for broken files)."), VLC_TRUE );
421
422     add_shortcut( "mka" );
423     add_shortcut( "mkv" );
424 vlc_module_end();
425
426 /*****************************************************************************
427  * Local prototypes
428  *****************************************************************************/
429 #ifdef HAVE_ZLIB_H
430 block_t *block_zlib_decompress( vlc_object_t *p_this, block_t *p_in_block ) {
431     int result, dstsize, n;
432     unsigned char *dst;
433     block_t *p_block;
434     z_stream d_stream;
435
436     d_stream.zalloc = (alloc_func)0;
437     d_stream.zfree = (free_func)0;
438     d_stream.opaque = (voidpf)0;
439     result = inflateInit(&d_stream);
440     if( result != Z_OK )
441     {
442         msg_Dbg( p_this, "inflateInit() failed. Result: %d", result );
443         return NULL;
444     }
445
446     d_stream.next_in = (Bytef *)p_in_block->p_buffer;
447     d_stream.avail_in = p_in_block->i_buffer;
448     n = 0;
449     p_block = block_New( p_this, 0 );
450     dst = NULL;
451     do
452     {
453         n++;
454         p_block = block_Realloc( p_block, 0, n * 1000 );
455         dst = (unsigned char *)p_block->p_buffer;
456         d_stream.next_out = (Bytef *)&dst[(n - 1) * 1000];
457         d_stream.avail_out = 1000;
458         result = inflate(&d_stream, Z_NO_FLUSH);
459         if( ( result != Z_OK ) && ( result != Z_STREAM_END ) )
460         {
461             msg_Dbg( p_this, "Zlib decompression failed. Result: %d", result );
462             return NULL;
463         }
464     }
465     while( ( d_stream.avail_out == 0 ) && ( d_stream.avail_in != 0 ) &&
466            ( result != Z_STREAM_END ) );
467
468     dstsize = d_stream.total_out;
469     inflateEnd( &d_stream );
470
471     p_block = block_Realloc( p_block, 0, dstsize );
472     p_block->i_buffer = dstsize;
473     block_Release( p_in_block );
474
475     return p_block;
476 }
477 #endif
478
479 /**
480  * Helper function to print the mkv parse tree
481  */
482 static void MkvTree( demux_t & demuxer, int i_level, const char *psz_format, ... )
483 {
484     va_list args;
485     if( i_level > 9 )
486     {
487         msg_Err( &demuxer, "too deep tree" );
488         return;
489     }
490     va_start( args, psz_format );
491     static const char psz_foo[] = "|   |   |   |   |   |   |   |   |   |";
492     char *psz_foo2 = (char*)malloc( ( i_level * 4 + 3 + strlen( psz_format ) ) * sizeof(char) );
493     strncpy( psz_foo2, psz_foo, 4 * i_level );
494     psz_foo2[ 4 * i_level ] = '+';
495     psz_foo2[ 4 * i_level + 1 ] = ' ';
496     strcpy( &psz_foo2[ 4 * i_level + 2 ], psz_format );
497     __msg_GenericVa( VLC_OBJECT(&demuxer), MSG_QUEUE_NORMAL, VLC_MSG_DBG, "mkv", psz_foo2, args );
498     free( psz_foo2 );
499     va_end( args );
500 }
501
502 /*****************************************************************************
503  * Stream managment
504  *****************************************************************************/
505 class vlc_stream_io_callback: public IOCallback
506 {
507   private:
508     stream_t       *s;
509     vlc_bool_t     mb_eof;
510     vlc_bool_t     b_owner;
511
512   public:
513     vlc_stream_io_callback( stream_t *, vlc_bool_t );
514
515     virtual ~vlc_stream_io_callback()
516     {
517         if( b_owner )
518             stream_Delete( s );
519     }
520
521     virtual uint32   read            ( void *p_buffer, size_t i_size);
522     virtual void     setFilePointer  ( int64_t i_offset, seek_mode mode = seek_beginning );
523     virtual size_t   write           ( const void *p_buffer, size_t i_size);
524     virtual uint64   getFilePointer  ( void );
525     virtual void     close           ( void );
526 };
527
528 /*****************************************************************************
529  * Ebml Stream parser
530  *****************************************************************************/
531 class EbmlParser
532 {
533   public:
534     EbmlParser( EbmlStream *es, EbmlElement *el_start, demux_t *p_demux );
535     virtual ~EbmlParser( void );
536
537     void Up( void );
538     void Down( void );
539     void Reset( demux_t *p_demux );
540     EbmlElement *Get( void );
541     void        Keep( void );
542     EbmlElement *UnGet( uint64 i_block_pos, uint64 i_cluster_pos );
543
544     int GetLevel( void );
545
546   private:
547     EbmlStream  *m_es;
548     int         mi_level;
549     EbmlElement *m_el[10];
550     int64_t      mi_remain_size[10];
551
552     EbmlElement *m_got;
553
554     int         mi_user_level;
555     vlc_bool_t  mb_keep;
556     vlc_bool_t  mb_dummy;
557 };
558
559
560 /*****************************************************************************
561  * Some functions to manipulate memory
562  *****************************************************************************/
563 #define GetFOURCC( p )  __GetFOURCC( (uint8_t*)p )
564 static vlc_fourcc_t __GetFOURCC( uint8_t *p )
565 {
566     return VLC_FOURCC( p[0], p[1], p[2], p[3] );
567 }
568
569 /*****************************************************************************
570  * definitions of structures and functions used by this plugins
571  *****************************************************************************/
572 typedef struct
573 {
574 //    ~mkv_track_t();
575
576     vlc_bool_t   b_default;
577     vlc_bool_t   b_enabled;
578     unsigned int i_number;
579
580     int          i_extra_data;
581     uint8_t      *p_extra_data;
582
583     char         *psz_codec;
584
585     uint64_t     i_default_duration;
586     float        f_timecodescale;
587     mtime_t      i_last_dts;
588
589     /* video */
590     es_format_t fmt;
591     float       f_fps;
592     es_out_id_t *p_es;
593
594     /* audio */
595     unsigned int i_original_rate;
596
597     vlc_bool_t      b_inited;
598     /* data to be send first */
599     int             i_data_init;
600     uint8_t         *p_data_init;
601
602     /* hack : it's for seek */
603     vlc_bool_t      b_search_keyframe;
604     vlc_bool_t      b_silent;
605
606     /* informative */
607     const char   *psz_codec_name;
608     const char   *psz_codec_settings;
609     const char   *psz_codec_info_url;
610     const char   *psz_codec_download_url;
611
612     /* encryption/compression */
613     int                    i_compression_type;
614     KaxContentCompSettings *p_compression_data;
615
616 } mkv_track_t;
617
618 typedef struct
619 {
620     int     i_track;
621     int     i_block_number;
622
623     int64_t i_position;
624     int64_t i_time;
625
626     vlc_bool_t b_key;
627 } mkv_index_t;
628
629 class demux_sys_t;
630
631 const binary MATROSKA_DVD_LEVEL_SS   = 0x30;
632 const binary MATROSKA_DVD_LEVEL_LU   = 0x2A;
633 const binary MATROSKA_DVD_LEVEL_TT   = 0x28;
634 const binary MATROSKA_DVD_LEVEL_PGC  = 0x20;
635 const binary MATROSKA_DVD_LEVEL_PG   = 0x18;
636 const binary MATROSKA_DVD_LEVEL_PTT  = 0x10;
637 const binary MATROSKA_DVD_LEVEL_CN   = 0x08;
638
639 class chapter_codec_cmds_c
640 {
641 public:
642     chapter_codec_cmds_c( demux_sys_t & demuxer, int codec_id = -1)
643     :p_private_data(NULL)
644     ,i_codec_id( codec_id )
645     ,sys( demuxer )
646     {}
647         
648     virtual ~chapter_codec_cmds_c()
649     {
650         delete p_private_data;
651         std::vector<KaxChapterProcessData*>::iterator indexe = enter_cmds.begin();
652         while ( indexe != enter_cmds.end() )
653         {
654             delete (*indexe);
655             indexe++;
656         }
657         std::vector<KaxChapterProcessData*>::iterator indexl = leave_cmds.begin();
658         while ( indexl != leave_cmds.end() )
659         {
660             delete (*indexl);
661             indexl++;
662         }
663         std::vector<KaxChapterProcessData*>::iterator indexd = during_cmds.begin();
664         while ( indexd != during_cmds.end() )
665         {
666             delete (*indexd);
667             indexd++;
668         }
669     }
670
671     void SetPrivate( const KaxChapterProcessPrivate & private_data )
672     {
673         p_private_data = new KaxChapterProcessPrivate( private_data );
674     }
675
676     void AddCommand( const KaxChapterProcessCommand & command );
677     
678     /// \return wether the codec has seeked in the files or not
679     virtual bool Enter() { return false; }
680     virtual bool Leave() { return false; }
681     virtual std::string GetCodecName( bool f_for_title = false ) const { return ""; }
682     virtual int16 GetTitleNumber() { return -1; }
683
684     KaxChapterProcessPrivate *p_private_data;
685
686 protected:
687     std::vector<KaxChapterProcessData*> enter_cmds;
688     std::vector<KaxChapterProcessData*> during_cmds;
689     std::vector<KaxChapterProcessData*> leave_cmds;
690
691     int i_codec_id;
692     demux_sys_t & sys;
693 };
694
695 class dvd_command_interpretor_c
696 {
697 public:
698     dvd_command_interpretor_c( demux_sys_t & demuxer )
699     :sys( demuxer )
700     {
701         memset( p_PRMs, 0, sizeof(p_PRMs) );
702         p_PRMs[ 0x80 + 1 ] = 15;
703         p_PRMs[ 0x80 + 2 ] = 62;
704         p_PRMs[ 0x80 + 3 ] = 1;
705         p_PRMs[ 0x80 + 4 ] = 1;
706         p_PRMs[ 0x80 + 7 ] = 1;
707         p_PRMs[ 0x80 + 8 ] = 1;
708         p_PRMs[ 0x80 + 16 ] = 0xFFFFu;
709         p_PRMs[ 0x80 + 18 ] = 0xFFFFu;
710     }
711     
712     bool Interpret( const binary * p_command, size_t i_size = 8 );
713     
714     uint16 GetPRM( size_t index ) const
715     {
716         if ( index < 256 )
717             return p_PRMs[ index ];
718         else return 0;
719     }
720
721     uint16 GetGPRM( size_t index ) const
722     {
723         if ( index >= 0 && index < 16 )
724             return p_PRMs[ index ];
725         else return 0;
726     }
727
728     uint16 GetSPRM( size_t index ) const
729     {
730         // 21,22,23 reserved for future use
731         if ( index >= 0x80 && index < 0x95 )
732             return p_PRMs[ index ];
733         else return 0;
734     }
735
736     bool SetPRM( size_t index, uint16 value )
737     {
738         if ( index >= 0 && index < 16 )
739         {
740             p_PRMs[ index ] = value;
741             return true;
742         }
743         return false;
744     }
745     
746     bool SetGPRM( size_t index, uint16 value )
747     {
748         if ( index >= 0 && index < 16 )
749         {
750             p_PRMs[ index ] = value;
751             return true;
752         }
753         return false;
754     }
755
756     bool SetSPRM( size_t index, uint16 value )
757     {
758         if ( index > 0x80 && index <= 0x8D && index != 0x8C )
759         {
760             p_PRMs[ index ] = value;
761             return true;
762         }
763         return false;
764     }
765
766 protected:
767     std::string GetRegTypeName( bool b_value, uint16 value ) const
768     {
769         std::string result;
770         char s_value[6], s_reg_value[6];
771         sprintf( s_value, "%.5d", value );
772
773         if ( b_value )
774         {
775             result = "value (";
776             result += s_value;
777             result += ")";
778         }
779         else if ( value < 0x80 )
780         {
781             sprintf( s_reg_value, "%.5d", GetPRM( value ) );
782             result = "GPreg[";
783             result += s_value;
784             result += "] (";
785             result += s_reg_value;
786             result += ")";
787         }
788         else
789         {
790             sprintf( s_reg_value, "%.5d", GetPRM( value ) );
791             result = "SPreg[";
792             result += s_value;
793             result += "] (";
794             result += s_reg_value;
795             result += ")";
796         }
797         return result;
798     }
799
800     uint16       p_PRMs[256];
801     demux_sys_t  & sys;
802     
803     // DVD command IDs
804
805     // Tests
806     // wether it's a comparison on the value or register
807     static const uint16 CMD_DVD_TEST_VALUE          = 0x80;
808     static const uint16 CMD_DVD_IF_GPREG_AND        = (1 << 4);
809     static const uint16 CMD_DVD_IF_GPREG_EQUAL      = (2 << 4);
810     static const uint16 CMD_DVD_IF_GPREG_NOT_EQUAL  = (3 << 4);
811     static const uint16 CMD_DVD_IF_GPREG_SUP_EQUAL  = (4 << 4);
812     static const uint16 CMD_DVD_IF_GPREG_SUP        = (5 << 4);
813     static const uint16 CMD_DVD_IF_GPREG_INF_EQUAL  = (6 << 4);
814     static const uint16 CMD_DVD_IF_GPREG_INF        = (7 << 4);
815     
816     static const uint16 CMD_DVD_NOP                    = 0x0000;
817     static const uint16 CMD_DVD_GOTO_LINE              = 0x0001;
818     static const uint16 CMD_DVD_BREAK                  = 0x0002;
819     // Links
820     static const uint16 CMD_DVD_NOP2                   = 0x2001;
821     static const uint16 CMD_DVD_LINKPGCN               = 0x2004;
822     static const uint16 CMD_DVD_LINKPGN                = 0x2006;
823     static const uint16 CMD_DVD_LINKCN                 = 0x2007;
824     static const uint16 CMD_DVD_JUMP_TT                = 0x3002;
825     static const uint16 CMD_DVD_JUMPVTS_TT             = 0x3003;
826     static const uint16 CMD_DVD_JUMPVTS_PTT            = 0x3005;
827     static const uint16 CMD_DVD_JUMP_SS                = 0x3006;
828     static const uint16 CMD_DVD_CALLSS_VTSM1           = 0x3008;
829     //
830     static const uint16 CMD_DVD_SET_HL_BTNN2           = 0x4600;
831     static const uint16 CMD_DVD_SET_HL_BTNN_LINKPGCN1  = 0x4604;
832     static const uint16 CMD_DVD_SET_STREAM             = 0x5100;
833     static const uint16 CMD_DVD_SET_GPRMMD             = 0x5300;
834     static const uint16 CMD_DVD_SET_HL_BTNN1           = 0x5600;
835     static const uint16 CMD_DVD_SET_HL_BTNN_LINKPGCN2  = 0x5604;
836     static const uint16 CMD_DVD_SET_HL_BTNN_LINKCN     = 0x5607;
837     // Operations
838     static const uint16 CMD_DVD_MOV_SPREG_PREG         = 0x6100;
839     static const uint16 CMD_DVD_GPREG_MOV_VALUE        = 0x7100;
840     static const uint16 CMD_DVD_SUB_GPREG              = 0x7400;
841     static const uint16 CMD_DVD_MULT_GPREG             = 0x7500;
842     static const uint16 CMD_DVD_GPREG_DIV_VALUE        = 0x7600;
843     static const uint16 CMD_DVD_GPREG_AND_VALUE        = 0x7900;
844     
845     // callbacks when browsing inside CodecPrivate
846     static bool MatchIsDomain     ( const chapter_codec_cmds_c &data, const void *p_cookie, size_t i_cookie_size );
847     static bool MatchIsVMG        ( const chapter_codec_cmds_c &data, const void *p_cookie, size_t i_cookie_size );
848     static bool MatchVTSNumber    ( const chapter_codec_cmds_c &data, const void *p_cookie, size_t i_cookie_size );
849     static bool MatchVTSMNumber   ( const chapter_codec_cmds_c &data, const void *p_cookie, size_t i_cookie_size );
850     static bool MatchTitleNumber  ( const chapter_codec_cmds_c &data, const void *p_cookie, size_t i_cookie_size );
851     static bool MatchPgcType      ( const chapter_codec_cmds_c &data, const void *p_cookie, size_t i_cookie_size );
852     static bool MatchPgcNumber    ( const chapter_codec_cmds_c &data, const void *p_cookie, size_t i_cookie_size );
853     static bool MatchChapterNumber( const chapter_codec_cmds_c &data, const void *p_cookie, size_t i_cookie_size );
854     static bool MatchCellNumber   ( const chapter_codec_cmds_c &data, const void *p_cookie, size_t i_cookie_size );
855 };
856
857 class dvd_chapter_codec_c : public chapter_codec_cmds_c
858 {
859 public:
860     dvd_chapter_codec_c( demux_sys_t & sys )
861     :chapter_codec_cmds_c( sys, 1 )
862     {}
863
864     bool Enter();
865     bool Leave();
866     std::string GetCodecName( bool f_for_title = false ) const;
867     int16 GetTitleNumber();
868 };
869
870 class matroska_script_interpretor_c
871 {
872 public:
873     matroska_script_interpretor_c( demux_sys_t & demuxer )
874     :sys( demuxer )
875     {}
876
877     bool Interpret( const binary * p_command, size_t i_size );
878     
879     // DVD command IDs
880     static const std::string CMD_MS_GOTO_AND_PLAY;
881     
882 protected:
883     demux_sys_t  & sys;
884 };
885
886 const std::string matroska_script_interpretor_c::CMD_MS_GOTO_AND_PLAY = "GotoAndPlay";
887
888
889 class matroska_script_codec_c : public chapter_codec_cmds_c
890 {
891 public:
892     matroska_script_codec_c( demux_sys_t & sys )
893     :chapter_codec_cmds_c( sys, 0 )
894     ,interpretor( sys )
895     {}
896
897     bool Enter();
898     bool Leave();
899
900 protected:
901     matroska_script_interpretor_c interpretor;
902 };
903
904 class chapter_translation_c
905 {
906 public:
907     chapter_translation_c()
908         :p_translated(NULL)
909     {}
910
911     ~chapter_translation_c()
912     {
913         delete p_translated;
914     }
915
916     KaxChapterTranslateID  *p_translated;
917     unsigned int           codec_id;
918     std::vector<uint64_t>  editions;
919 };
920
921 class chapter_item_c
922 {
923 public:
924     chapter_item_c()
925     :i_start_time(0)
926     ,i_end_time(-1)
927     ,i_user_start_time(-1)
928     ,i_user_end_time(-1)
929     ,i_seekpoint_num(-1)
930     ,b_display_seekpoint(true)
931     ,b_user_display(false)
932     ,psz_parent(NULL)
933     ,b_is_leaving(false)
934     {}
935
936     virtual ~chapter_item_c()
937     {
938         std::vector<chapter_codec_cmds_c*>::iterator index = codecs.begin();
939         while ( index != codecs.end() )
940         {
941             delete (*index);
942             index++;
943         }
944         std::vector<chapter_item_c*>::iterator index_ = sub_chapters.begin();
945         while ( index_ != sub_chapters.end() )
946         {
947             delete (*index_);
948             index_++;
949         }
950     }
951
952     int64_t RefreshChapters( bool b_ordered, int64_t i_prev_user_time );
953     int PublishChapters( input_title_t & title, int & i_user_chapters, int i_level = 0 );
954     virtual chapter_item_c * FindTimecode( mtime_t i_timecode, const chapter_item_c * p_current, bool & b_found );
955     void Append( const chapter_item_c & edition );
956     chapter_item_c * FindChapter( int64_t i_find_uid );
957     virtual chapter_item_c *BrowseCodecPrivate( unsigned int codec_id,
958                                     bool (*match)(const chapter_codec_cmds_c &data, const void *p_cookie, size_t i_cookie_size ),
959                                     const void *p_cookie,
960                                     size_t i_cookie_size );
961     std::string                 GetCodecName( bool f_for_title = false ) const;
962     bool                        ParentOf( const chapter_item_c & item ) const;
963     int16                       GetTitleNumber( ) const;
964     
965     int64_t                     i_start_time, i_end_time;
966     int64_t                     i_user_start_time, i_user_end_time; /* the time in the stream when an edition is ordered */
967     std::vector<chapter_item_c*> sub_chapters;
968     int                         i_seekpoint_num;
969     int64_t                     i_uid;
970     bool                        b_display_seekpoint;
971     bool                        b_user_display;
972     std::string                 psz_name;
973     chapter_item_c              *psz_parent;
974     bool                        b_is_leaving;
975     
976     std::vector<chapter_codec_cmds_c*> codecs;
977
978     static bool CompareTimecode( const chapter_item_c * itemA, const chapter_item_c * itemB )
979     {
980         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) );
981     }
982
983     bool Enter( bool b_do_subchapters );
984     bool Leave( bool b_do_subchapters );
985     bool EnterAndLeave( chapter_item_c *p_item, bool b_enter = true );
986 };
987
988 class chapter_edition_c : public chapter_item_c
989 {
990 public:
991     chapter_edition_c()
992     :b_ordered(false)
993     {}
994     
995     void RefreshChapters( );
996     mtime_t Duration() const;
997     std::string GetMainName() const;
998     chapter_item_c * FindTimecode( mtime_t i_timecode, const chapter_item_c * p_current );
999     
1000     bool                        b_ordered;
1001 };
1002
1003 class matroska_segment_c
1004 {
1005 public:
1006     matroska_segment_c( demux_sys_t & demuxer, EbmlStream & estream )
1007         :segment(NULL)
1008         ,es(estream)
1009         ,i_timescale(MKVD_TIMECODESCALE)
1010         ,i_duration(-1)
1011         ,i_start_time(0)
1012         ,i_cues_position(-1)
1013         ,i_chapters_position(-1)
1014         ,i_tags_position(-1)
1015         ,cluster(NULL)
1016         ,i_block_pos(0)
1017         ,i_cluster_pos(0)
1018         ,i_start_pos(0)
1019         ,p_segment_uid(NULL)
1020         ,p_prev_segment_uid(NULL)
1021         ,p_next_segment_uid(NULL)
1022         ,b_cues(VLC_FALSE)
1023         ,i_index(0)
1024         ,i_index_max(1024)
1025         ,psz_muxing_application(NULL)
1026         ,psz_writing_application(NULL)
1027         ,psz_segment_filename(NULL)
1028         ,psz_title(NULL)
1029         ,psz_date_utc(NULL)
1030         ,i_default_edition(0)
1031         ,sys(demuxer)
1032         ,ep(NULL)
1033         ,b_preloaded(false)
1034     {
1035         p_indexes = (mkv_index_t*)malloc( sizeof( mkv_index_t ) * i_index_max );
1036     }
1037
1038     virtual ~matroska_segment_c()
1039     {
1040         for( size_t i_track = 0; i_track < tracks.size(); i_track++ )
1041         {
1042             if ( tracks[i_track]->p_compression_data )
1043             {
1044                 delete tracks[i_track]->p_compression_data;
1045             }
1046             es_format_Clean( &tracks[i_track]->fmt );
1047             if( tracks[i_track]->p_extra_data )
1048                 free( tracks[i_track]->p_extra_data );
1049             if( tracks[i_track]->psz_codec )
1050                 free( tracks[i_track]->psz_codec );
1051             delete tracks[i_track];
1052         }
1053
1054         if( psz_writing_application )
1055         {
1056             free( psz_writing_application );
1057         }
1058         if( psz_muxing_application )
1059         {
1060             free( psz_muxing_application );
1061         }
1062         if( psz_segment_filename )
1063         {
1064             free( psz_segment_filename );
1065         }
1066         if( psz_title )
1067         {
1068             free( psz_title );
1069         }
1070         if( psz_date_utc )
1071         {
1072             free( psz_date_utc );
1073         }
1074         if ( p_indexes )
1075             free( p_indexes );
1076
1077         delete ep;
1078         delete segment;
1079         delete p_segment_uid;
1080         delete p_prev_segment_uid;
1081         delete p_next_segment_uid;
1082
1083         std::vector<chapter_edition_c*>::iterator index = stored_editions.begin();
1084         while ( index != stored_editions.end() )
1085         {
1086             delete (*index);
1087             index++;
1088         }
1089         std::vector<chapter_translation_c*>::iterator indext = translations.begin();
1090         while ( indext != translations.end() )
1091         {
1092             delete (*indext);
1093             indext++;
1094         }
1095         std::vector<KaxSegmentFamily*>::iterator indexf = families.begin();
1096         while ( indexf != families.end() )
1097         {
1098             delete (*indexf);
1099             indexf++;
1100         }
1101     }
1102
1103     KaxSegment              *segment;
1104     EbmlStream              & es;
1105
1106     /* time scale */
1107     uint64_t                i_timescale;
1108
1109     /* duration of the segment */
1110     mtime_t                 i_duration;
1111     mtime_t                 i_start_time;
1112
1113     /* all tracks */
1114     std::vector<mkv_track_t*> tracks;
1115
1116     /* from seekhead */
1117     int64_t                 i_cues_position;
1118     int64_t                 i_chapters_position;
1119     int64_t                 i_tags_position;
1120
1121     KaxCluster              *cluster;
1122     uint64                  i_block_pos;
1123     uint64                  i_cluster_pos;
1124     int64_t                 i_start_pos;
1125     KaxSegmentUID           *p_segment_uid;
1126     KaxPrevUID              *p_prev_segment_uid;
1127     KaxNextUID              *p_next_segment_uid;
1128
1129     vlc_bool_t              b_cues;
1130     int                     i_index;
1131     int                     i_index_max;
1132     mkv_index_t             *p_indexes;
1133
1134     /* info */
1135     char                    *psz_muxing_application;
1136     char                    *psz_writing_application;
1137     char                    *psz_segment_filename;
1138     char                    *psz_title;
1139     char                    *psz_date_utc;
1140
1141     /* !!!!! GCC 3.3 bug on Darwin !!!!! */
1142     /* when you remove this variable the compiler issues an atomicity error */
1143     /* this variable only works when using std::vector<chapter_edition_c> */
1144     std::vector<chapter_edition_c*> stored_editions;
1145     int                             i_default_edition;
1146
1147     std::vector<chapter_translation_c*> translations;
1148     std::vector<KaxSegmentFamily*>  families;
1149     
1150     demux_sys_t                    & sys;
1151     EbmlParser                     *ep;
1152     bool                           b_preloaded;
1153
1154     bool Preload( );
1155     bool PreloadFamily( const matroska_segment_c & segment );
1156     void ParseInfo( KaxInfo *info );
1157     void ParseChapters( KaxChapters *chapters );
1158     void ParseSeekHead( KaxSeekHead *seekhead );
1159     void ParseTracks( KaxTracks *tracks );
1160     void ParseChapterAtom( int i_level, KaxChapterAtom *ca, chapter_item_c & chapters );
1161     void ParseTrackEntry( KaxTrackEntry *m );
1162     void ParseCluster( );
1163     void IndexAppendCluster( KaxCluster *cluster );
1164     void LoadCues( );
1165     void LoadTags( );
1166     void InformationCreate( );
1167     void Seek( mtime_t i_date, mtime_t i_time_offset );
1168 #if LIBMATROSKA_VERSION >= 0x000800
1169     int BlockGet( KaxBlock * &, KaxSimpleBlock * &, int64_t *, int64_t *, int64_t *);
1170 #else
1171     int BlockGet( KaxBlock * &, int64_t *, int64_t *, int64_t *);
1172 #endif
1173     bool Select( mtime_t i_start_time );
1174     void UnSelect( );
1175
1176     static bool CompareSegmentUIDs( const matroska_segment_c * item_a, const matroska_segment_c * item_b );
1177 };
1178
1179 // class holding hard-linked segment together in the playback order
1180 class virtual_segment_c
1181 {
1182 public:
1183     virtual_segment_c( matroska_segment_c *p_segment )
1184         :p_editions(NULL)
1185         ,i_sys_title(0)
1186         ,i_current_segment(0)
1187         ,i_current_edition(-1)
1188         ,psz_current_chapter(NULL)
1189     {
1190         linked_segments.push_back( p_segment );
1191
1192         AppendUID( p_segment->p_segment_uid );
1193         AppendUID( p_segment->p_prev_segment_uid );
1194         AppendUID( p_segment->p_next_segment_uid );
1195     }
1196
1197     void Sort();
1198     size_t AddSegment( matroska_segment_c *p_segment );
1199     void PreloadLinked( );
1200     mtime_t Duration( ) const;
1201     void LoadCues( );
1202     void Seek( demux_t & demuxer, mtime_t i_date, mtime_t i_time_offset, chapter_item_c *psz_chapter );
1203
1204     inline chapter_edition_c *Edition()
1205     {
1206         if ( i_current_edition >= 0 && size_t(i_current_edition) < p_editions->size() )
1207             return (*p_editions)[i_current_edition];
1208         return NULL;
1209     }
1210
1211     matroska_segment_c * Segment() const
1212     {
1213         if ( linked_segments.size() == 0 || i_current_segment >= linked_segments.size() )
1214             return NULL;
1215         return linked_segments[i_current_segment];
1216     }
1217
1218     inline chapter_item_c *CurrentChapter() {
1219         return psz_current_chapter;
1220     }
1221
1222     bool SelectNext()
1223     {
1224         if ( i_current_segment < linked_segments.size()-1 )
1225         {
1226             i_current_segment++;
1227             return true;
1228         }
1229         return false;
1230     }
1231
1232     bool FindUID( KaxSegmentUID & uid ) const
1233     {
1234         for ( size_t i=0; i<linked_uids.size(); i++ )
1235         {
1236             if ( linked_uids[i] == uid )
1237                 return true;
1238         }
1239         return false;
1240     }
1241
1242     bool UpdateCurrentToChapter( demux_t & demux );
1243     void PrepareChapters( );
1244
1245     chapter_item_c *BrowseCodecPrivate( unsigned int codec_id,
1246                                         bool (*match)(const chapter_codec_cmds_c &data, const void *p_cookie, size_t i_cookie_size ),
1247                                         const void *p_cookie,
1248                                         size_t i_cookie_size );
1249     chapter_item_c *FindChapter( int64_t i_find_uid );
1250
1251     std::vector<chapter_edition_c*>  *p_editions;
1252     int                              i_sys_title;
1253
1254 protected:
1255     std::vector<matroska_segment_c*> linked_segments;
1256     std::vector<KaxSegmentUID>       linked_uids;
1257     size_t                           i_current_segment;
1258
1259     int                              i_current_edition;
1260     chapter_item_c                   *psz_current_chapter;
1261
1262     void                             AppendUID( const EbmlBinary * UID );
1263 };
1264
1265 class matroska_stream_c
1266 {
1267 public:
1268     matroska_stream_c( demux_sys_t & demuxer )
1269         :p_in(NULL)
1270         ,p_es(NULL)
1271         ,sys(demuxer)
1272     {}
1273
1274     virtual ~matroska_stream_c()
1275     {
1276         delete p_in;
1277         delete p_es;
1278     }
1279
1280     IOCallback         *p_in;
1281     EbmlStream         *p_es;
1282
1283     std::vector<matroska_segment_c*> segments;
1284
1285     demux_sys_t                      & sys;
1286 };
1287
1288 typedef struct
1289 {
1290     VLC_COMMON_MEMBERS
1291
1292     demux_t        *p_demux;
1293     vlc_mutex_t     lock;
1294
1295     vlc_bool_t      b_moved;
1296     vlc_bool_t      b_clicked;
1297     vlc_bool_t      b_key;
1298
1299 } event_thread_t;
1300
1301 class demux_sys_t
1302 {
1303 public:
1304     demux_sys_t( demux_t & demux )
1305         :demuxer(demux)
1306         ,i_pts(0)
1307         ,i_start_pts(0)
1308         ,i_chapter_time(0)
1309         ,meta(NULL)
1310         ,i_current_title(0)
1311         ,p_current_segment(NULL)
1312         ,dvd_interpretor( *this )
1313         ,f_duration(-1.0)
1314         ,b_ui_hooked(false)
1315         ,p_input(NULL)
1316         ,b_pci_packet_set(false)
1317         ,p_ev(NULL)
1318     {
1319         vlc_mutex_init( &demuxer, &lock_demuxer );
1320     }
1321
1322     virtual ~demux_sys_t()
1323     {
1324         StopUiThread();
1325         size_t i;
1326         for ( i=0; i<streams.size(); i++ )
1327             delete streams[i];
1328         for ( i=0; i<opened_segments.size(); i++ )
1329             delete opened_segments[i];
1330         for ( i=0; i<used_segments.size(); i++ )
1331             delete used_segments[i];
1332         if( meta ) vlc_meta_Delete( meta );
1333
1334         while( titles.size() )
1335         { vlc_input_title_Delete( titles.back() ); titles.pop_back();}
1336
1337         vlc_mutex_destroy( &lock_demuxer );
1338     }
1339
1340     /* current data */
1341     demux_t                 & demuxer;
1342
1343     mtime_t                 i_pts;
1344     mtime_t                 i_start_pts;
1345     mtime_t                 i_chapter_time;
1346
1347     vlc_meta_t              *meta;
1348
1349     std::vector<input_title_t*>      titles; // matroska editions
1350     size_t                           i_current_title;
1351
1352     std::vector<matroska_stream_c*>  streams;
1353     std::vector<matroska_segment_c*> opened_segments;
1354     std::vector<virtual_segment_c*>  used_segments;
1355     virtual_segment_c                *p_current_segment;
1356
1357     dvd_command_interpretor_c        dvd_interpretor;
1358
1359     /* duration of the stream */
1360     float                   f_duration;
1361
1362     matroska_segment_c *FindSegment( const EbmlBinary & uid ) const;
1363     chapter_item_c *BrowseCodecPrivate( unsigned int codec_id,
1364                                         bool (*match)(const chapter_codec_cmds_c &data, const void *p_cookie, size_t i_cookie_size ),
1365                                         const void *p_cookie,
1366                                         size_t i_cookie_size,
1367                                         virtual_segment_c * & p_segment_found );
1368     chapter_item_c *FindChapter( int64_t i_find_uid, virtual_segment_c * & p_segment_found );
1369
1370     void PreloadFamily( const matroska_segment_c & of_segment );
1371     void PreloadLinked( matroska_segment_c *p_segment );
1372     bool PreparePlayback( virtual_segment_c *p_new_segment );
1373     matroska_stream_c *AnalyseAllSegmentsFound( demux_t *p_demux, EbmlStream *p_estream, bool b_initial = false );
1374     void JumpTo( virtual_segment_c & p_segment, chapter_item_c * p_chapter );
1375
1376     void StartUiThread();
1377     void StopUiThread();
1378     bool b_ui_hooked;
1379     inline void SwapButtons();
1380
1381     /* for spu variables */
1382     input_thread_t *p_input;
1383     pci_t          pci_packet;
1384     bool           b_pci_packet_set;
1385     uint8_t        palette[4][4];
1386     vlc_mutex_t    lock_demuxer;
1387
1388     /* event */
1389     event_thread_t *p_ev;
1390     static int EventThread( vlc_object_t *p_this );
1391     static int EventMouse( vlc_object_t *p_this, char const *psz_var,
1392                        vlc_value_t oldval, vlc_value_t newval, void *p_data );
1393     static int EventKey( vlc_object_t *p_this, char const *psz_var,
1394                      vlc_value_t oldval, vlc_value_t newval, void *p_data );
1395
1396
1397
1398 protected:
1399     virtual_segment_c *VirtualFromSegments( matroska_segment_c *p_segment ) const;
1400     bool IsUsedSegment( matroska_segment_c &p_segment ) const;
1401 };
1402
1403 static int  Demux  ( demux_t * );
1404 static int  Control( demux_t *, int, va_list );
1405 static void Seek   ( demux_t *, mtime_t i_date, double f_percent, chapter_item_c *psz_chapter );
1406
1407 #define MKV_IS_ID( el, C ) ( EbmlId( (*el) ) == C::ClassInfos.GlobalId )
1408
1409 static inline char * ToUTF8( const UTFstring &u )
1410 {
1411     return strdup( u.GetUTF8().c_str() );
1412 }
1413
1414 /*****************************************************************************
1415  * Open: initializes matroska demux structures
1416  *****************************************************************************/
1417 static int Open( vlc_object_t * p_this )
1418 {
1419     demux_t            *p_demux = (demux_t*)p_this;
1420     demux_sys_t        *p_sys;
1421     matroska_stream_c  *p_stream;
1422     matroska_segment_c *p_segment;
1423     uint8_t            *p_peek;
1424     std::string        s_path, s_filename;
1425     vlc_stream_io_callback *p_io_callback;
1426     EbmlStream         *p_io_stream;
1427
1428     /* peek the begining */
1429     if( stream_Peek( p_demux->s, &p_peek, 4 ) < 4 ) return VLC_EGENERIC;
1430
1431     /* is a valid file */
1432     if( p_peek[0] != 0x1a || p_peek[1] != 0x45 ||
1433         p_peek[2] != 0xdf || p_peek[3] != 0xa3 ) return VLC_EGENERIC;
1434
1435     /* Set the demux function */
1436     p_demux->pf_demux   = Demux;
1437     p_demux->pf_control = Control;
1438     p_demux->p_sys      = p_sys = new demux_sys_t( *p_demux );
1439
1440     p_io_callback = new vlc_stream_io_callback( p_demux->s, VLC_FALSE );
1441     p_io_stream = new EbmlStream( *p_io_callback );
1442
1443     if( p_io_stream == NULL )
1444     {
1445         msg_Err( p_demux, "failed to create EbmlStream" );
1446         delete p_io_callback;
1447         delete p_sys;
1448         return VLC_EGENERIC;
1449     }
1450
1451     p_stream = p_sys->AnalyseAllSegmentsFound( p_demux, p_io_stream, true );
1452     if( p_stream == NULL )
1453     {
1454         msg_Err( p_demux, "cannot find KaxSegment" );
1455         goto error;
1456     }
1457     p_sys->streams.push_back( p_stream );
1458
1459     p_stream->p_in = p_io_callback;
1460     p_stream->p_es = p_io_stream;
1461
1462     for (size_t i=0; i<p_stream->segments.size(); i++)
1463     {
1464         p_stream->segments[i]->Preload();
1465     }
1466
1467     p_segment = p_stream->segments[0];
1468     if( p_segment->cluster != NULL )
1469     {
1470         msg_Warn( p_demux, "cannot find any cluster, damaged file ?" );
1471
1472         // reset the stream reading to the first cluster of the segment used
1473         p_stream->p_in->setFilePointer( p_segment->cluster->GetElementPosition() );
1474     }
1475
1476     if (config_GetInt( p_demux, "mkv-preload-local-dir" ))
1477     {
1478         /* get the files from the same dir from the same family (based on p_demux->psz_path) */
1479         if (p_demux->psz_path[0] != '\0' && !strcmp(p_demux->psz_access, ""))
1480         {
1481             // assume it's a regular file
1482             // get the directory path
1483             s_path = p_demux->psz_path;
1484             if (s_path.at(s_path.length() - 1) == DIRECTORY_SEPARATOR)
1485             {
1486                 s_path = s_path.substr(0,s_path.length()-1);
1487             }
1488             else
1489             {
1490                 if (s_path.find_last_of(DIRECTORY_SEPARATOR) > 0)
1491                 {
1492                     s_path = s_path.substr(0,s_path.find_last_of(DIRECTORY_SEPARATOR));
1493                 }
1494             }
1495
1496             DIR *p_src_dir = utf8_opendir(s_path.c_str());
1497
1498             if (p_src_dir != NULL)
1499             {
1500                 const char *psz_file;
1501                 while ((psz_file = utf8_readdir(p_src_dir)) != NULL)
1502                 {
1503                     if (strlen(psz_file) > 4)
1504                     {
1505                         s_filename = s_path + DIRECTORY_SEPARATOR + psz_file;
1506
1507 #ifdef WIN32
1508                         if (!strcasecmp(s_filename.c_str(), p_demux->psz_path))
1509 #else
1510                         if (!s_filename.compare(p_demux->psz_path))
1511 #endif
1512                             continue; // don't reuse the original opened file
1513
1514 #if defined(__GNUC__) && (__GNUC__ < 3)
1515                         if (!s_filename.compare("mkv", s_filename.length() - 3, 3) ||
1516                             !s_filename.compare("mka", s_filename.length() - 3, 3))
1517 #else
1518                         if (!s_filename.compare(s_filename.length() - 3, 3, "mkv") ||
1519                             !s_filename.compare(s_filename.length() - 3, 3, "mka"))
1520 #endif
1521                         {
1522                             // test wether this file belongs to our family
1523                             stream_t *p_file_stream = stream_UrlNew( p_demux, s_filename.c_str());
1524                             if ( p_file_stream != NULL )
1525                             {
1526                                 vlc_stream_io_callback *p_file_io = new vlc_stream_io_callback( p_file_stream, VLC_TRUE );
1527                                 EbmlStream *p_estream = new EbmlStream(*p_file_io);
1528
1529                                 p_stream = p_sys->AnalyseAllSegmentsFound( p_demux, p_estream );
1530
1531                                 if ( p_stream == NULL )
1532                                 {
1533                                     msg_Dbg( p_demux, "the file '%s' will not be used", s_filename.c_str() );
1534                                     delete p_estream;
1535                                     delete p_file_io;
1536                                 }
1537                                 else
1538                                 {
1539                                     p_stream->p_in = p_file_io;
1540                                     p_stream->p_es = p_estream;
1541                                     p_sys->streams.push_back( p_stream );
1542                                 }
1543                             }
1544                             else
1545                             {
1546                                 msg_Dbg( p_demux, "the file '%s' cannot be opened", s_filename.c_str() );
1547                             }
1548                         }
1549                     }
1550                     free (psz_file);
1551                 }
1552                 closedir( p_src_dir );
1553             }
1554         }
1555
1556         p_sys->PreloadFamily( *p_segment );
1557     }
1558
1559     p_sys->PreloadLinked( p_segment );
1560
1561     if ( !p_sys->PreparePlayback( NULL ) )
1562     {
1563         msg_Err( p_demux, "cannot use the segment" );
1564         goto error;
1565     }
1566
1567     p_sys->StartUiThread();
1568     
1569     return VLC_SUCCESS;
1570
1571 error:
1572     delete p_sys;
1573     return VLC_EGENERIC;
1574 }
1575
1576 /*****************************************************************************
1577  * Close: frees unused data
1578  *****************************************************************************/
1579 static void Close( vlc_object_t *p_this )
1580 {
1581     demux_t     *p_demux = (demux_t*)p_this;
1582     demux_sys_t *p_sys   = p_demux->p_sys;
1583
1584     delete p_sys;
1585 }
1586
1587 /*****************************************************************************
1588  * Control:
1589  *****************************************************************************/
1590 static int Control( demux_t *p_demux, int i_query, va_list args )
1591 {
1592     demux_sys_t        *p_sys = p_demux->p_sys;
1593     int64_t     *pi64;
1594     double      *pf, f;
1595     int         i_skp;
1596     size_t      i_idx;
1597
1598     vlc_meta_t *p_meta;
1599
1600     switch( i_query )
1601     {
1602         case DEMUX_GET_META:
1603             p_meta = (vlc_meta_t*)va_arg( args, vlc_meta_t* );
1604             vlc_meta_Merge( p_meta, p_sys->meta );
1605             return VLC_SUCCESS;
1606
1607         case DEMUX_GET_LENGTH:
1608             pi64 = (int64_t*)va_arg( args, int64_t * );
1609             if( p_sys->f_duration > 0.0 )
1610             {
1611                 *pi64 = (int64_t)(p_sys->f_duration * 1000);
1612                 return VLC_SUCCESS;
1613             }
1614             return VLC_EGENERIC;
1615
1616         case DEMUX_GET_POSITION:
1617             pf = (double*)va_arg( args, double * );
1618             if ( p_sys->f_duration > 0.0 )
1619                 *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);
1620             return VLC_SUCCESS;
1621
1622         case DEMUX_SET_POSITION:
1623             f = (double)va_arg( args, double );
1624             Seek( p_demux, -1, f, NULL );
1625             return VLC_SUCCESS;
1626
1627         case DEMUX_GET_TIME:
1628             pi64 = (int64_t*)va_arg( args, int64_t * );
1629             *pi64 = p_sys->i_pts;
1630             return VLC_SUCCESS;
1631
1632         case DEMUX_GET_TITLE_INFO:
1633             if( p_sys->titles.size() )
1634             {
1635                 input_title_t ***ppp_title = (input_title_t***)va_arg( args, input_title_t*** );
1636                 int *pi_int    = (int*)va_arg( args, int* );
1637
1638                 *pi_int = p_sys->titles.size();
1639                 *ppp_title = (input_title_t**)malloc( sizeof( input_title_t**) * p_sys->titles.size() );
1640
1641                 for( size_t i = 0; i < p_sys->titles.size(); i++ )
1642                 {
1643                     (*ppp_title)[i] = vlc_input_title_Duplicate( p_sys->titles[i] );
1644                 }
1645
1646                 return VLC_SUCCESS;
1647             }
1648             return VLC_EGENERIC;
1649
1650         case DEMUX_SET_TITLE:
1651             /* TODO handle editions as titles */
1652             i_idx = (int)va_arg( args, int );
1653             if( i_idx < p_sys->used_segments.size() )
1654             {
1655                 p_sys->JumpTo( *p_sys->used_segments[i_idx], NULL );
1656                 return VLC_SUCCESS;
1657             }
1658             return VLC_EGENERIC;
1659
1660         case DEMUX_SET_SEEKPOINT:
1661             i_skp = (int)va_arg( args, int );
1662
1663             // TODO change the way it works with the << & >> buttons on the UI (+1/-1 instead of a number)
1664             if( p_sys->titles.size() && i_skp < p_sys->titles[p_sys->i_current_title]->i_seekpoint)
1665             {
1666                 Seek( p_demux, (int64_t)p_sys->titles[p_sys->i_current_title]->seekpoint[i_skp]->i_time_offset, -1, NULL);
1667                 p_demux->info.i_seekpoint |= INPUT_UPDATE_SEEKPOINT;
1668                 p_demux->info.i_seekpoint = i_skp;
1669                 return VLC_SUCCESS;
1670             }
1671             return VLC_EGENERIC;
1672
1673         case DEMUX_SET_TIME:
1674         case DEMUX_GET_FPS:
1675         default:
1676             return VLC_EGENERIC;
1677     }
1678 }
1679
1680 #if LIBMATROSKA_VERSION >= 0x000800
1681 int matroska_segment_c::BlockGet( KaxBlock * & pp_block, KaxSimpleBlock * & pp_simpleblock, int64_t *pi_ref1, int64_t *pi_ref2, int64_t *pi_duration )
1682 #else
1683 int matroska_segment_c::BlockGet( KaxBlock * & pp_block, int64_t *pi_ref1, int64_t *pi_ref2, int64_t *pi_duration )
1684 #endif
1685 {
1686 #if LIBMATROSKA_VERSION >= 0x000800
1687     pp_simpleblock = NULL;
1688 #endif
1689     pp_block = NULL;
1690     *pi_ref1  = 0;
1691     *pi_ref2  = 0;
1692
1693     for( ;; )
1694     {
1695         EbmlElement *el = NULL;
1696         int         i_level;
1697
1698         if ( ep == NULL )
1699             return VLC_EGENERIC;
1700
1701 #if LIBMATROSKA_VERSION >= 0x000800
1702         if( pp_simpleblock != NULL || ((el = ep->Get()) == NULL && pp_block != NULL) )
1703 #else
1704         if( (el = ep->Get()) == NULL && pp_block != NULL )
1705 #endif
1706         {
1707             /* update the index */
1708 #define idx p_indexes[i_index - 1]
1709             if( i_index > 0 && idx.i_time == -1 )
1710             {
1711 #if LIBMATROSKA_VERSION >= 0x000800
1712                 if ( pp_simpleblock != NULL )
1713                     idx.i_time        = pp_simpleblock->GlobalTimecode() / (mtime_t)1000;
1714                 else
1715 #endif
1716                     idx.i_time        = (*pp_block).GlobalTimecode() / (mtime_t)1000;
1717                 idx.b_key         = *pi_ref1 == 0 ? VLC_TRUE : VLC_FALSE;
1718             }
1719 #undef idx
1720             return VLC_SUCCESS;
1721         }
1722
1723         i_level = ep->GetLevel();
1724
1725         if( el == NULL )
1726         {
1727             if( i_level > 1 )
1728             {
1729                 ep->Up();
1730                 continue;
1731             }
1732             msg_Warn( &sys.demuxer, "EOF" );
1733             return VLC_EGENERIC;
1734         }
1735
1736         /* do parsing */
1737         switch ( i_level )
1738         {
1739         case 1:
1740             if( MKV_IS_ID( el, KaxCluster ) )
1741             {
1742                 cluster = (KaxCluster*)el;
1743                 i_cluster_pos = cluster->GetElementPosition();
1744
1745                 /* add it to the index */
1746                 if( i_index == 0 ||
1747                     ( i_index > 0 && p_indexes[i_index - 1].i_position < (int64_t)cluster->GetElementPosition() ) )
1748                 {
1749                     IndexAppendCluster( cluster );
1750                 }
1751
1752                 // reset silent tracks
1753                 for (size_t i=0; i<tracks.size(); i++)
1754                 {
1755                     tracks[i]->b_silent = VLC_FALSE;
1756                 }
1757
1758                 ep->Down();
1759             }
1760             else if( MKV_IS_ID( el, KaxCues ) )
1761             {
1762                 msg_Warn( &sys.demuxer, "find KaxCues FIXME" );
1763                 return VLC_EGENERIC;
1764             }
1765             else
1766             {
1767                 msg_Dbg( &sys.demuxer, "unknown (%s)", typeid( el ).name() );
1768             }
1769             break;
1770         case 2:
1771             if( MKV_IS_ID( el, KaxClusterTimecode ) )
1772             {
1773                 KaxClusterTimecode &ctc = *(KaxClusterTimecode*)el;
1774
1775                 ctc.ReadData( es.I_O(), SCOPE_ALL_DATA );
1776                 cluster->InitTimecode( uint64( ctc ), i_timescale );
1777             }
1778             else if( MKV_IS_ID( el, KaxClusterSilentTracks ) )
1779             {
1780                 ep->Down();
1781             }
1782             else if( MKV_IS_ID( el, KaxBlockGroup ) )
1783             {
1784                 i_block_pos = el->GetElementPosition();
1785                 ep->Down();
1786             }
1787 #if LIBMATROSKA_VERSION >= 0x000800
1788             else if( MKV_IS_ID( el, KaxSimpleBlock ) )
1789             {
1790                 pp_simpleblock = (KaxSimpleBlock*)el;
1791
1792                 pp_simpleblock->ReadData( es.I_O() );
1793                 pp_simpleblock->SetParent( *cluster );
1794             }
1795 #endif
1796             break;
1797         case 3:
1798             if( MKV_IS_ID( el, KaxBlock ) )
1799             {
1800                 pp_block = (KaxBlock*)el;
1801
1802                 pp_block->ReadData( es.I_O() );
1803                 pp_block->SetParent( *cluster );
1804
1805                 ep->Keep();
1806             }
1807             else if( MKV_IS_ID( el, KaxBlockDuration ) )
1808             {
1809                 KaxBlockDuration &dur = *(KaxBlockDuration*)el;
1810
1811                 dur.ReadData( es.I_O() );
1812                 *pi_duration = uint64( dur );
1813             }
1814             else if( MKV_IS_ID( el, KaxReferenceBlock ) )
1815             {
1816                 KaxReferenceBlock &ref = *(KaxReferenceBlock*)el;
1817
1818                 ref.ReadData( es.I_O() );
1819                 if( *pi_ref1 == 0 )
1820                 {
1821                     *pi_ref1 = int64( ref ) * cluster->GlobalTimecodeScale();
1822                 }
1823                 else if( *pi_ref2 == 0 )
1824                 {
1825                     *pi_ref2 = int64( ref ) * cluster->GlobalTimecodeScale();
1826                 }
1827             }
1828             else if( MKV_IS_ID( el, KaxClusterSilentTrackNumber ) )
1829             {
1830                 KaxClusterSilentTrackNumber &track_num = *(KaxClusterSilentTrackNumber*)el;
1831                 track_num.ReadData( es.I_O() );
1832                 // find the track
1833                 for (size_t i=0; i<tracks.size(); i++)
1834                 {
1835                     if ( tracks[i]->i_number == uint32(track_num))
1836                     {
1837                         tracks[i]->b_silent = VLC_TRUE;
1838                         break;
1839                     }
1840                 }
1841             }
1842             break;
1843         default:
1844             msg_Err( &sys.demuxer, "invalid level = %d", i_level );
1845             return VLC_EGENERIC;
1846         }
1847     }
1848 }
1849
1850 static block_t *MemToBlock( demux_t *p_demux, uint8_t *p_mem, int i_mem, size_t offset)
1851 {
1852     block_t *p_block;
1853     if( !(p_block = block_New( p_demux, i_mem + offset ) ) ) return NULL;
1854     memcpy( p_block->p_buffer + offset, p_mem, i_mem );
1855     //p_block->i_rate = p_input->stream.control.i_rate;
1856     return p_block;
1857 }
1858
1859 #if LIBMATROSKA_VERSION >= 0x000800
1860 static void BlockDecode( demux_t *p_demux, KaxBlock *block, KaxSimpleBlock *simpleblock,
1861                          mtime_t i_pts, mtime_t i_duration, bool f_mandatory )
1862 #else
1863 static void BlockDecode( demux_t *p_demux, KaxBlock *block, mtime_t i_pts,
1864                          mtime_t i_duration, bool f_mandatory )
1865 #endif
1866 {
1867     demux_sys_t        *p_sys = p_demux->p_sys;
1868     matroska_segment_c *p_segment = p_sys->p_current_segment->Segment();
1869
1870     size_t          i_track;
1871     unsigned int    i;
1872     vlc_bool_t      b;
1873
1874 #define tk  p_segment->tracks[i_track]
1875     for( i_track = 0; i_track < p_segment->tracks.size(); i_track++ )
1876     {
1877 #if LIBMATROSKA_VERSION >= 0x000800
1878         if( (block != NULL && tk->i_number == block->TrackNum()) ||
1879             (simpleblock != NULL && tk->i_number == simpleblock->TrackNum()))
1880 #else
1881         if( tk->i_number == block->TrackNum() )
1882 #endif
1883         {
1884             break;
1885         }
1886     }
1887
1888     if( i_track >= p_segment->tracks.size() )
1889     {
1890         msg_Err( p_demux, "invalid track number=%d", block->TrackNum() );
1891         return;
1892     }
1893     if( tk->fmt.i_cat != NAV_ES && tk->p_es == NULL )
1894     {
1895         msg_Err( p_demux, "unknown track number=%d", block->TrackNum() );
1896         return;
1897     }
1898     if( i_pts + i_duration < p_sys->i_start_pts && tk->fmt.i_cat == AUDIO_ES )
1899     {
1900         return; /* discard audio packets that shouldn't be rendered */
1901     }
1902
1903     if ( tk->fmt.i_cat != NAV_ES )
1904     {
1905         es_out_Control( p_demux->out, ES_OUT_GET_ES_STATE, tk->p_es, &b );
1906
1907         if( !b )
1908         {
1909             tk->b_inited = VLC_FALSE;
1910             return;
1911         }
1912     }
1913
1914
1915     /* First send init data */
1916     if( !tk->b_inited && tk->i_data_init > 0 )
1917     {
1918         block_t *p_init;
1919
1920         msg_Dbg( p_demux, "sending header (%d bytes)", tk->i_data_init );
1921         p_init = MemToBlock( p_demux, tk->p_data_init, tk->i_data_init, 0 );
1922         if( p_init ) es_out_Send( p_demux->out, tk->p_es, p_init );
1923     }
1924     tk->b_inited = VLC_TRUE;
1925
1926
1927 #if LIBMATROSKA_VERSION >= 0x000800
1928     for( i = 0;
1929         (block != NULL && i < block->NumberFrames()) || (simpleblock != NULL && i < simpleblock->NumberFrames());
1930         i++ )
1931 #else
1932     for( i = 0; i < block->NumberFrames(); i++ )
1933 #endif
1934     {
1935         block_t *p_block;
1936         DataBuffer *data;
1937 #if LIBMATROSKA_VERSION >= 0x000800
1938         if ( simpleblock != NULL )
1939         {
1940             data = &simpleblock->GetBuffer(i);
1941             // condition when the DTS is correct (keyframe or B frame == NOT P frame)
1942             f_mandatory = simpleblock->IsDiscardable() || simpleblock->IsKeyframe();
1943         }
1944         else
1945 #endif
1946         data = &block->GetBuffer(i);
1947
1948         if( tk->i_compression_type == MATROSKA_COMPRESSION_HEADER && tk->p_compression_data != NULL )
1949             p_block = MemToBlock( p_demux, data->Buffer(), data->Size(), tk->p_compression_data->GetSize() );
1950         else
1951             p_block = MemToBlock( p_demux, data->Buffer(), data->Size(), 0 );
1952
1953         if( p_block == NULL )
1954         {
1955             break;
1956         }
1957
1958 #if defined(HAVE_ZLIB_H)
1959         if( tk->i_compression_type == MATROSKA_COMPRESSION_ZLIB )
1960         {
1961             p_block = block_zlib_decompress( VLC_OBJECT(p_demux), p_block );
1962         }
1963         else
1964 #endif
1965         if( tk->i_compression_type == MATROSKA_COMPRESSION_HEADER )
1966         {
1967             memcpy( p_block->p_buffer, tk->p_compression_data->GetBuffer(), tk->p_compression_data->GetSize() );
1968         }
1969
1970         if ( tk->fmt.i_cat == NAV_ES )
1971         {
1972             // TODO handle the start/stop times of this packet
1973             if ( p_sys->b_ui_hooked )
1974             {
1975                 vlc_mutex_lock( &p_sys->p_ev->lock );
1976                 memcpy( &p_sys->pci_packet, &p_block->p_buffer[1], sizeof(pci_t) );
1977                 p_sys->SwapButtons();
1978                 p_sys->b_pci_packet_set = true;
1979                 vlc_mutex_unlock( &p_sys->p_ev->lock );
1980                 block_Release( p_block );
1981             }
1982             return;
1983         }
1984         // correct timestamping when B frames are used
1985         if( tk->fmt.i_cat != VIDEO_ES )
1986         {
1987             p_block->i_dts = p_block->i_pts = i_pts;
1988         }
1989         else
1990         {
1991             if( !strcmp( tk->psz_codec, "V_MS/VFW/FOURCC" ) )
1992             {
1993                 // in VFW we have no idea about B frames
1994                 p_block->i_pts = 0;
1995                 p_block->i_dts = i_pts;
1996             }
1997             else
1998             {
1999                 p_block->i_pts = i_pts;
2000                 if ( f_mandatory )
2001                     p_block->i_dts = p_block->i_pts;
2002                 else
2003                     p_block->i_dts = min( i_pts, tk->i_last_dts + (mtime_t)(tk->i_default_duration >> 10));
2004                 p_sys->i_pts = p_block->i_dts;
2005             }
2006         }
2007         tk->i_last_dts = p_block->i_dts;
2008
2009 #if 0
2010 msg_Dbg( p_demux, "block i_dts: "I64Fd" / i_pts: "I64Fd, p_block->i_dts, p_block->i_pts);
2011 #endif
2012         if( strcmp( tk->psz_codec, "S_VOBSUB" ) )
2013         {
2014             p_block->i_length = i_duration * 1000;
2015         }
2016
2017         es_out_Send( p_demux->out, tk->p_es, p_block );
2018
2019         /* use time stamp only for first block */
2020         i_pts = 0;
2021     }
2022
2023 #undef tk
2024 }
2025
2026 matroska_stream_c *demux_sys_t::AnalyseAllSegmentsFound( demux_t *p_demux, EbmlStream *p_estream, bool b_initial )
2027 {
2028     int i_upper_lvl = 0;
2029     size_t i;
2030     EbmlElement *p_l0, *p_l1, *p_l2;
2031     bool b_keep_stream = false, b_keep_segment;
2032
2033     // verify the EBML Header
2034     p_l0 = p_estream->FindNextID(EbmlHead::ClassInfos, 0xFFFFFFFFL);
2035     if (p_l0 == NULL)
2036     {
2037         msg_Err( p_demux, "No EBML header found" );
2038         return NULL;
2039     }
2040
2041     // verify we can read this Segment, we only support Matroska version 1 for now
2042     p_l0->Read(*p_estream, EbmlHead::ClassInfos.Context, i_upper_lvl, p_l0, true);
2043
2044     EDocType doc_type = GetChild<EDocType>(*static_cast<EbmlHead*>(p_l0));
2045     if (std::string(doc_type) != "matroska")
2046     {
2047         msg_Err( p_demux, "Not a Matroska file : DocType = %s ", std::string(doc_type).c_str());
2048         return NULL;
2049     }
2050
2051     EDocTypeReadVersion doc_read_version = GetChild<EDocTypeReadVersion>(*static_cast<EbmlHead*>(p_l0));
2052 #if LIBMATROSKA_VERSION >= 0x000800
2053     if (uint64(doc_read_version) > 2)
2054     {
2055         msg_Err( p_demux, "This matroska file is needs version "I64Fd" and this VLC only supports version 1 & 2", uint64(doc_read_version));
2056         return NULL;
2057     }
2058 #else
2059     if (uint64(doc_read_version) != 1)
2060     {
2061         msg_Err( p_demux, "This matroska file is needs version "I64Fd" and this VLC only supports version 1", uint64(doc_read_version));
2062         return NULL;
2063     }
2064 #endif
2065
2066     delete p_l0;
2067
2068
2069     // find all segments in this file
2070     p_l0 = p_estream->FindNextID(KaxSegment::ClassInfos, 0xFFFFFFFFFLL);
2071     if (p_l0 == NULL)
2072     {
2073         return NULL;
2074     }
2075
2076     matroska_stream_c *p_stream1 = new matroska_stream_c( *this );
2077
2078     while (p_l0 != 0)
2079     {
2080         if (EbmlId(*p_l0) == KaxSegment::ClassInfos.GlobalId)
2081         {
2082             EbmlParser  *ep;
2083             matroska_segment_c *p_segment1 = new matroska_segment_c( *this, *p_estream );
2084             b_keep_segment = b_initial;
2085
2086             ep = new EbmlParser(p_estream, p_l0, &demuxer );
2087             p_segment1->ep = ep;
2088             p_segment1->segment = (KaxSegment*)p_l0;
2089
2090             while ((p_l1 = ep->Get()))
2091             {
2092                 if (MKV_IS_ID(p_l1, KaxInfo))
2093                 {
2094                     // find the families of this segment
2095                     KaxInfo *p_info = static_cast<KaxInfo*>(p_l1);
2096
2097                     p_info->Read(*p_estream, KaxInfo::ClassInfos.Context, i_upper_lvl, p_l2, true);
2098                     for( i = 0; i < p_info->ListSize(); i++ )
2099                     {
2100                         EbmlElement *l = (*p_info)[i];
2101
2102                         if( MKV_IS_ID( l, KaxSegmentUID ) )
2103                         {
2104                             KaxSegmentUID *p_uid = static_cast<KaxSegmentUID*>(l);
2105                             b_keep_segment = (FindSegment( *p_uid ) == NULL);
2106                             if ( !b_keep_segment )
2107                                 break; // this segment is already known
2108                             opened_segments.push_back( p_segment1 );
2109                             delete p_segment1->p_segment_uid;
2110                             p_segment1->p_segment_uid = new KaxSegmentUID(*p_uid);
2111                         }
2112                         else if( MKV_IS_ID( l, KaxPrevUID ) )
2113                         {
2114                             p_segment1->p_prev_segment_uid = new KaxPrevUID( *static_cast<KaxPrevUID*>(l) );
2115                         }
2116                         else if( MKV_IS_ID( l, KaxNextUID ) )
2117                         {
2118                             p_segment1->p_next_segment_uid = new KaxNextUID( *static_cast<KaxNextUID*>(l) );
2119                         }
2120                         else if( MKV_IS_ID( l, KaxSegmentFamily ) )
2121                         {
2122                             KaxSegmentFamily *p_fam = new KaxSegmentFamily( *static_cast<KaxSegmentFamily*>(l) );
2123                             p_segment1->families.push_back( p_fam );
2124                         }
2125                     }
2126                     break;
2127                 }
2128             }
2129             if ( b_keep_segment )
2130             {
2131                 b_keep_stream = true;
2132                 p_stream1->segments.push_back( p_segment1 );
2133             }
2134             else
2135                 delete p_segment1;
2136         }
2137         if (p_l0->IsFiniteSize() )
2138         {
2139             p_l0->SkipData(*p_estream, KaxMatroska_Context);
2140             p_l0 = p_estream->FindNextID(KaxSegment::ClassInfos, 0xFFFFFFFFL);
2141         }
2142         else
2143             p_l0 = p_l0->SkipData(*p_estream, KaxSegment_Context);
2144     }
2145
2146     if ( !b_keep_stream )
2147     {
2148         delete p_stream1;
2149         p_stream1 = NULL;
2150     }
2151
2152     return p_stream1;
2153 }
2154
2155 bool matroska_segment_c::Select( mtime_t i_start_time )
2156 {
2157     size_t i_track;
2158
2159     /* add all es */
2160     msg_Dbg( &sys.demuxer, "found %d es", (int)tracks.size() );
2161     sys.b_pci_packet_set = false;
2162
2163     for( i_track = 0; i_track < tracks.size(); i_track++ )
2164     {
2165         if( tracks[i_track]->fmt.i_cat == UNKNOWN_ES )
2166         {
2167             msg_Warn( &sys.demuxer, "invalid track[%d, n=%d]", (int)i_track, tracks[i_track]->i_number );
2168             tracks[i_track]->p_es = NULL;
2169             continue;
2170         }
2171
2172         if( !strcmp( tracks[i_track]->psz_codec, "V_MS/VFW/FOURCC" ) )
2173         {
2174             if( tracks[i_track]->i_extra_data < (int)sizeof( BITMAPINFOHEADER ) )
2175             {
2176                 msg_Err( &sys.demuxer, "missing/invalid BITMAPINFOHEADER" );
2177                 tracks[i_track]->fmt.i_codec = VLC_FOURCC( 'u', 'n', 'd', 'f' );
2178             }
2179             else
2180             {
2181                 BITMAPINFOHEADER *p_bih = (BITMAPINFOHEADER*)tracks[i_track]->p_extra_data;
2182
2183                 tracks[i_track]->fmt.video.i_width = GetDWLE( &p_bih->biWidth );
2184                 tracks[i_track]->fmt.video.i_height= GetDWLE( &p_bih->biHeight );
2185                 tracks[i_track]->fmt.i_codec       = GetFOURCC( &p_bih->biCompression );
2186
2187                 tracks[i_track]->fmt.i_extra       = GetDWLE( &p_bih->biSize ) - sizeof( BITMAPINFOHEADER );
2188                 if( tracks[i_track]->fmt.i_extra > 0 )
2189                 {
2190                     tracks[i_track]->fmt.p_extra = malloc( tracks[i_track]->fmt.i_extra );
2191                     memcpy( tracks[i_track]->fmt.p_extra, &p_bih[1], tracks[i_track]->fmt.i_extra );
2192                 }
2193             }
2194         }
2195         else if( !strcmp( tracks[i_track]->psz_codec, "V_MPEG1" ) ||
2196                  !strcmp( tracks[i_track]->psz_codec, "V_MPEG2" ) )
2197         {
2198             tracks[i_track]->fmt.i_codec = VLC_FOURCC( 'm', 'p', 'g', 'v' );
2199         }
2200         else if( !strncmp( tracks[i_track]->psz_codec, "V_MPEG4", 7 ) )
2201         {
2202             if( !strcmp( tracks[i_track]->psz_codec, "V_MPEG4/MS/V3" ) )
2203             {
2204                 tracks[i_track]->fmt.i_codec = VLC_FOURCC( 'D', 'I', 'V', '3' );
2205             }
2206             else if( !strncmp( tracks[i_track]->psz_codec, "V_MPEG4/ISO", 11 ) )
2207             {
2208                 /* A MPEG 4 codec, SP, ASP, AP or AVC */
2209                 if( !strcmp( tracks[i_track]->psz_codec, "V_MPEG4/ISO/AVC" ) )
2210                     tracks[i_track]->fmt.i_codec = VLC_FOURCC( 'a', 'v', 'c', '1' );
2211                 else
2212                     tracks[i_track]->fmt.i_codec = VLC_FOURCC( 'm', 'p', '4', 'v' );
2213                 tracks[i_track]->fmt.i_extra = tracks[i_track]->i_extra_data;
2214                 tracks[i_track]->fmt.p_extra = malloc( tracks[i_track]->i_extra_data );
2215                 memcpy( tracks[i_track]->fmt.p_extra,tracks[i_track]->p_extra_data, tracks[i_track]->i_extra_data );
2216             }
2217         }
2218         else if( !strcmp( tracks[i_track]->psz_codec, "V_QUICKTIME" ) )
2219         {
2220             MP4_Box_t *p_box = (MP4_Box_t*)malloc( sizeof( MP4_Box_t ) );
2221             stream_t *p_mp4_stream = stream_MemoryNew( VLC_OBJECT(&sys.demuxer),
2222                                                        tracks[i_track]->p_extra_data,
2223                                                        tracks[i_track]->i_extra_data,
2224                                                        VLC_FALSE );
2225             MP4_ReadBoxCommon( p_mp4_stream, p_box );
2226             MP4_ReadBox_sample_vide( p_mp4_stream, p_box );
2227             tracks[i_track]->fmt.i_codec = p_box->i_type;
2228             tracks[i_track]->fmt.video.i_width = p_box->data.p_sample_vide->i_width;
2229             tracks[i_track]->fmt.video.i_height = p_box->data.p_sample_vide->i_height;
2230             tracks[i_track]->fmt.i_extra = p_box->data.p_sample_vide->i_qt_image_description;
2231             tracks[i_track]->fmt.p_extra = malloc( tracks[i_track]->fmt.i_extra );
2232             memcpy( tracks[i_track]->fmt.p_extra, p_box->data.p_sample_vide->p_qt_image_description, tracks[i_track]->fmt.i_extra );
2233             MP4_FreeBox_sample_vide( p_box );
2234             stream_Delete( p_mp4_stream );
2235         }
2236         else if( !strcmp( tracks[i_track]->psz_codec, "A_MS/ACM" ) )
2237         {
2238             if( tracks[i_track]->i_extra_data < (int)sizeof( WAVEFORMATEX ) )
2239             {
2240                 msg_Err( &sys.demuxer, "missing/invalid WAVEFORMATEX" );
2241                 tracks[i_track]->fmt.i_codec = VLC_FOURCC( 'u', 'n', 'd', 'f' );
2242             }
2243             else
2244             {
2245                 WAVEFORMATEX *p_wf = (WAVEFORMATEX*)tracks[i_track]->p_extra_data;
2246
2247                 wf_tag_to_fourcc( GetWLE( &p_wf->wFormatTag ), &tracks[i_track]->fmt.i_codec, NULL );
2248
2249                 tracks[i_track]->fmt.audio.i_channels   = GetWLE( &p_wf->nChannels );
2250                 tracks[i_track]->fmt.audio.i_rate = GetDWLE( &p_wf->nSamplesPerSec );
2251                 tracks[i_track]->fmt.i_bitrate    = GetDWLE( &p_wf->nAvgBytesPerSec ) * 8;
2252                 tracks[i_track]->fmt.audio.i_blockalign = GetWLE( &p_wf->nBlockAlign );;
2253                 tracks[i_track]->fmt.audio.i_bitspersample = GetWLE( &p_wf->wBitsPerSample );
2254
2255                 tracks[i_track]->fmt.i_extra            = GetWLE( &p_wf->cbSize );
2256                 if( tracks[i_track]->fmt.i_extra > 0 )
2257                 {
2258                     tracks[i_track]->fmt.p_extra = malloc( tracks[i_track]->fmt.i_extra );
2259                     memcpy( tracks[i_track]->fmt.p_extra, &p_wf[1], tracks[i_track]->fmt.i_extra );
2260                 }
2261             }
2262         }
2263         else if( !strcmp( tracks[i_track]->psz_codec, "A_MPEG/L3" ) ||
2264                  !strcmp( tracks[i_track]->psz_codec, "A_MPEG/L2" ) ||
2265                  !strcmp( tracks[i_track]->psz_codec, "A_MPEG/L1" ) )
2266         {
2267             tracks[i_track]->fmt.i_codec = VLC_FOURCC( 'm', 'p', 'g', 'a' );
2268         }
2269         else if( !strcmp( tracks[i_track]->psz_codec, "A_AC3" ) )
2270         {
2271             tracks[i_track]->fmt.i_codec = VLC_FOURCC( 'a', '5', '2', ' ' );
2272         }
2273         else if( !strcmp( tracks[i_track]->psz_codec, "A_DTS" ) )
2274         {
2275             tracks[i_track]->fmt.i_codec = VLC_FOURCC( 'd', 't', 's', ' ' );
2276         }
2277         else if( !strcmp( tracks[i_track]->psz_codec, "A_FLAC" ) )
2278         {
2279             tracks[i_track]->fmt.i_codec = VLC_FOURCC( 'f', 'l', 'a', 'c' );
2280             tracks[i_track]->fmt.i_extra = tracks[i_track]->i_extra_data;
2281             tracks[i_track]->fmt.p_extra = malloc( tracks[i_track]->i_extra_data );
2282             memcpy( tracks[i_track]->fmt.p_extra,tracks[i_track]->p_extra_data, tracks[i_track]->i_extra_data );
2283         }
2284         else if( !strcmp( tracks[i_track]->psz_codec, "A_VORBIS" ) )
2285         {
2286             int i, i_offset = 1, i_size[3], i_extra;
2287             uint8_t *p_extra;
2288
2289             tracks[i_track]->fmt.i_codec = VLC_FOURCC( 'v', 'o', 'r', 'b' );
2290
2291             /* Split the 3 headers */
2292             if( tracks[i_track]->p_extra_data[0] != 0x02 )
2293                 msg_Err( &sys.demuxer, "invalid vorbis header" );
2294
2295             for( i = 0; i < 2; i++ )
2296             {
2297                 i_size[i] = 0;
2298                 while( i_offset < tracks[i_track]->i_extra_data )
2299                 {
2300                     i_size[i] += tracks[i_track]->p_extra_data[i_offset];
2301                     if( tracks[i_track]->p_extra_data[i_offset++] != 0xff ) break;
2302                 }
2303             }
2304
2305             i_size[0] = __MIN(i_size[0], tracks[i_track]->i_extra_data - i_offset);
2306             i_size[1] = __MIN(i_size[1], tracks[i_track]->i_extra_data -i_offset -i_size[0]);
2307             i_size[2] = tracks[i_track]->i_extra_data - i_offset - i_size[0] - i_size[1];
2308
2309             tracks[i_track]->fmt.i_extra = 3 * 2 + i_size[0] + i_size[1] + i_size[2];
2310             tracks[i_track]->fmt.p_extra = malloc( tracks[i_track]->fmt.i_extra );
2311             p_extra = (uint8_t *)tracks[i_track]->fmt.p_extra; i_extra = 0;
2312             for( i = 0; i < 3; i++ )
2313             {
2314                 *(p_extra++) = i_size[i] >> 8;
2315                 *(p_extra++) = i_size[i] & 0xFF;
2316                 memcpy( p_extra, tracks[i_track]->p_extra_data + i_offset + i_extra,
2317                         i_size[i] );
2318                 p_extra += i_size[i];
2319                 i_extra += i_size[i];
2320             }
2321         }
2322         else if( !strncmp( tracks[i_track]->psz_codec, "A_AAC/MPEG2/", strlen( "A_AAC/MPEG2/" ) ) ||
2323                  !strncmp( tracks[i_track]->psz_codec, "A_AAC/MPEG4/", strlen( "A_AAC/MPEG4/" ) ) )
2324         {
2325             int i_profile, i_srate, sbr = 0;
2326             static unsigned int i_sample_rates[] =
2327             {
2328                     96000, 88200, 64000, 48000, 44100, 32000, 24000, 22050,
2329                         16000, 12000, 11025, 8000,  7350,  0,     0,     0
2330             };
2331
2332             tracks[i_track]->fmt.i_codec = VLC_FOURCC( 'm', 'p', '4', 'a' );
2333             /* create data for faad (MP4DecSpecificDescrTag)*/
2334
2335             if( !strcmp( &tracks[i_track]->psz_codec[12], "MAIN" ) )
2336             {
2337                 i_profile = 0;
2338             }
2339             else if( !strcmp( &tracks[i_track]->psz_codec[12], "LC" ) )
2340             {
2341                 i_profile = 1;
2342             }
2343             else if( !strcmp( &tracks[i_track]->psz_codec[12], "SSR" ) )
2344             {
2345                 i_profile = 2;
2346             }
2347             else if( !strcmp( &tracks[i_track]->psz_codec[12], "LC/SBR" ) )
2348             {
2349                 i_profile = 1;
2350                 sbr = 1;
2351             }
2352             else
2353             {
2354                 i_profile = 3;
2355             }
2356
2357             for( i_srate = 0; i_srate < 13; i_srate++ )
2358             {
2359                 if( i_sample_rates[i_srate] == tracks[i_track]->i_original_rate )
2360                 {
2361                     break;
2362                 }
2363             }
2364             msg_Dbg( &sys.demuxer, "profile=%d srate=%d", i_profile, i_srate );
2365
2366             tracks[i_track]->fmt.i_extra = sbr ? 5 : 2;
2367             tracks[i_track]->fmt.p_extra = malloc( tracks[i_track]->fmt.i_extra );
2368             ((uint8_t*)tracks[i_track]->fmt.p_extra)[0] = ((i_profile + 1) << 3) | ((i_srate&0xe) >> 1);
2369             ((uint8_t*)tracks[i_track]->fmt.p_extra)[1] = ((i_srate & 0x1) << 7) | (tracks[i_track]->fmt.audio.i_channels << 3);
2370             if (sbr != 0)
2371             {
2372                 int syncExtensionType = 0x2B7;
2373                 int iDSRI;
2374                 for (iDSRI=0; iDSRI<13; iDSRI++)
2375                     if( i_sample_rates[iDSRI] == tracks[i_track]->fmt.audio.i_rate )
2376                         break;
2377                 ((uint8_t*)tracks[i_track]->fmt.p_extra)[2] = (syncExtensionType >> 3) & 0xFF;
2378                 ((uint8_t*)tracks[i_track]->fmt.p_extra)[3] = ((syncExtensionType & 0x7) << 5) | 5;
2379                 ((uint8_t*)tracks[i_track]->fmt.p_extra)[4] = ((1 & 0x1) << 7) | (iDSRI << 3);
2380             }
2381         }
2382         else if( !strcmp( tracks[i_track]->psz_codec, "A_AAC" ) )
2383         {
2384             tracks[i_track]->fmt.i_codec = VLC_FOURCC( 'm', 'p', '4', 'a' );
2385             tracks[i_track]->fmt.i_extra = tracks[i_track]->i_extra_data;
2386             tracks[i_track]->fmt.p_extra = malloc( tracks[i_track]->i_extra_data );
2387             memcpy( tracks[i_track]->fmt.p_extra, tracks[i_track]->p_extra_data, tracks[i_track]->i_extra_data );
2388         }
2389         else if( !strcmp( tracks[i_track]->psz_codec, "A_WAVPACK4" ) )
2390         {
2391             tracks[i_track]->fmt.i_codec = VLC_FOURCC( 'W', 'V', 'P', 'K' );
2392             tracks[i_track]->fmt.i_extra = tracks[i_track]->i_extra_data;
2393             tracks[i_track]->fmt.p_extra = malloc( tracks[i_track]->i_extra_data );
2394             memcpy( tracks[i_track]->fmt.p_extra, tracks[i_track]->p_extra_data, tracks[i_track]->i_extra_data );
2395         }
2396         else if( !strcmp( tracks[i_track]->psz_codec, "A_TTA1" ) )
2397         {
2398             tracks[i_track]->fmt.i_codec = VLC_FOURCC( 'T', 'T', 'A', '1' );
2399             tracks[i_track]->fmt.i_extra = tracks[i_track]->i_extra_data;
2400             tracks[i_track]->fmt.p_extra = malloc( tracks[i_track]->i_extra_data );
2401             memcpy( tracks[i_track]->fmt.p_extra, tracks[i_track]->p_extra_data, tracks[i_track]->i_extra_data );
2402         }
2403         else if( !strcmp( tracks[i_track]->psz_codec, "A_PCM/INT/BIG" ) ||
2404                  !strcmp( tracks[i_track]->psz_codec, "A_PCM/INT/LIT" ) ||
2405                  !strcmp( tracks[i_track]->psz_codec, "A_PCM/FLOAT/IEEE" ) )
2406         {
2407             if( !strcmp( tracks[i_track]->psz_codec, "A_PCM/INT/BIG" ) )
2408             {
2409                 tracks[i_track]->fmt.i_codec = VLC_FOURCC( 't', 'w', 'o', 's' );
2410             }
2411             else
2412             {
2413                 tracks[i_track]->fmt.i_codec = VLC_FOURCC( 'a', 'r', 'a', 'w' );
2414             }
2415             tracks[i_track]->fmt.audio.i_blockalign = ( tracks[i_track]->fmt.audio.i_bitspersample + 7 ) / 8 * tracks[i_track]->fmt.audio.i_channels;
2416         }
2417         else if( !strcmp( tracks[i_track]->psz_codec, "S_TEXT/UTF8" ) )
2418         {
2419             tracks[i_track]->fmt.i_codec = VLC_FOURCC( 's', 'u', 'b', 't' );
2420             tracks[i_track]->fmt.subs.psz_encoding = strdup( "UTF-8" );
2421         }
2422         else if( !strcmp( tracks[i_track]->psz_codec, "S_TEXT/SSA" ) ||
2423                  !strcmp( tracks[i_track]->psz_codec, "S_TEXT/ASS" ) ||
2424                  !strcmp( tracks[i_track]->psz_codec, "S_SSA" ) ||
2425                  !strcmp( tracks[i_track]->psz_codec, "S_ASS" ))
2426         {
2427             tracks[i_track]->fmt.i_codec = VLC_FOURCC( 's', 's', 'a', ' ' );
2428             tracks[i_track]->fmt.subs.psz_encoding = strdup( "UTF-8" );
2429             if( tracks[i_track]->i_extra_data )
2430             {
2431                 tracks[i_track]->fmt.i_extra = tracks[i_track]->i_extra_data;
2432                 tracks[i_track]->fmt.p_extra = malloc( tracks[i_track]->i_extra_data );
2433                 memcpy( tracks[i_track]->fmt.p_extra, tracks[i_track]->p_extra_data, tracks[i_track]->i_extra_data );
2434             }
2435         }
2436         else if( !strcmp( tracks[i_track]->psz_codec, "S_VOBSUB" ) )
2437         {
2438             tracks[i_track]->fmt.i_codec = VLC_FOURCC( 's','p','u',' ' );
2439             if( tracks[i_track]->i_extra_data )
2440             {
2441                 char *p_start;
2442                 char *p_buf = (char *)malloc( tracks[i_track]->i_extra_data + 1);
2443                 memcpy( p_buf, tracks[i_track]->p_extra_data , tracks[i_track]->i_extra_data );
2444                 p_buf[tracks[i_track]->i_extra_data] = '\0';
2445                 
2446                 p_start = strstr( p_buf, "size:" );
2447                 if( sscanf( p_start, "size: %dx%d",
2448                         &tracks[i_track]->fmt.subs.spu.i_original_frame_width, &tracks[i_track]->fmt.subs.spu.i_original_frame_height ) == 2 )
2449                 {
2450                     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 );
2451                 }
2452                 else
2453                 {
2454                     msg_Warn( &sys.demuxer, "reading original frame size for vobsub failed" );
2455                 }
2456                 free( p_buf );
2457             }
2458         }
2459         else if( !strcmp( tracks[i_track]->psz_codec, "B_VOBBTN" ) )
2460         {
2461             tracks[i_track]->fmt.i_cat = NAV_ES;
2462             continue;
2463         }
2464         else
2465         {
2466             msg_Err( &sys.demuxer, "unknow codec id=`%s'", tracks[i_track]->psz_codec );
2467             tracks[i_track]->fmt.i_codec = VLC_FOURCC( 'u', 'n', 'd', 'f' );
2468         }
2469         if( tracks[i_track]->b_default )
2470         {
2471             tracks[i_track]->fmt.i_priority = 1000;
2472         }
2473
2474         tracks[i_track]->p_es = es_out_Add( sys.demuxer.out, &tracks[i_track]->fmt );
2475
2476         es_out_Control( sys.demuxer.out, ES_OUT_SET_NEXT_DISPLAY_TIME, tracks[i_track]->p_es, i_start_time );
2477     }
2478     
2479     sys.i_start_pts = i_start_time;
2480     // reset the stream reading to the first cluster of the segment used
2481     es.I_O().setFilePointer( i_start_pos );
2482
2483     delete ep;
2484     ep = new EbmlParser( &es, segment, &sys.demuxer );
2485
2486     return true;
2487 }
2488
2489 void demux_sys_t::StartUiThread()
2490 {
2491     if ( !b_ui_hooked )
2492     {
2493         msg_Dbg( &demuxer, "Starting the UI Hook" );
2494         b_ui_hooked = true;
2495         /* FIXME hack hack hack hack FIXME */
2496         /* Get p_input and create variable */
2497         p_input = (input_thread_t *) vlc_object_find( &demuxer, VLC_OBJECT_INPUT, FIND_PARENT );
2498         var_Create( p_input, "x-start", VLC_VAR_INTEGER );
2499         var_Create( p_input, "y-start", VLC_VAR_INTEGER );
2500         var_Create( p_input, "x-end", VLC_VAR_INTEGER );
2501         var_Create( p_input, "y-end", VLC_VAR_INTEGER );
2502         var_Create( p_input, "color", VLC_VAR_ADDRESS );
2503         var_Create( p_input, "menu-palette", VLC_VAR_ADDRESS );
2504         var_Create( p_input, "highlight", VLC_VAR_BOOL );
2505         var_Create( p_input, "highlight-mutex", VLC_VAR_MUTEX );
2506
2507         /* Now create our event thread catcher */
2508         p_ev = (event_thread_t *) vlc_object_create( &demuxer, sizeof( event_thread_t ) );
2509         p_ev->p_demux = &demuxer;
2510         p_ev->b_die = VLC_FALSE;
2511         vlc_mutex_init( p_ev, &p_ev->lock );
2512         vlc_thread_create( p_ev, "mkv event thread handler", EventThread,
2513                         VLC_THREAD_PRIORITY_LOW, VLC_FALSE );
2514     }
2515 }
2516
2517 void demux_sys_t::StopUiThread()
2518 {
2519     if ( b_ui_hooked )
2520     {
2521         p_ev->b_die = VLC_TRUE;
2522
2523         vlc_thread_join( p_ev );
2524         vlc_object_destroy( p_ev );
2525
2526         p_ev = NULL;
2527
2528         var_Destroy( p_input, "highlight-mutex" );
2529         var_Destroy( p_input, "highlight" );
2530         var_Destroy( p_input, "x-start" );
2531         var_Destroy( p_input, "x-end" );
2532         var_Destroy( p_input, "y-start" );
2533         var_Destroy( p_input, "y-end" );
2534         var_Destroy( p_input, "color" );
2535         var_Destroy( p_input, "menu-palette" );
2536
2537         vlc_object_release( p_input );
2538
2539         msg_Dbg( &demuxer, "Stopping the UI Hook" );
2540     }
2541     b_ui_hooked = false;
2542 }
2543
2544 int demux_sys_t::EventMouse( vlc_object_t *p_this, char const *psz_var,
2545                        vlc_value_t oldval, vlc_value_t newval, void *p_data )
2546 {
2547     event_thread_t *p_ev = (event_thread_t *) p_data;
2548     vlc_mutex_lock( &p_ev->lock );
2549     if( psz_var[6] == 'c' )
2550     {
2551         p_ev->b_clicked = VLC_TRUE;
2552         msg_Dbg( p_this, "Event Mouse: clicked");
2553     }
2554     else if( psz_var[6] == 'm' )
2555         p_ev->b_moved = VLC_TRUE;
2556     vlc_mutex_unlock( &p_ev->lock );
2557
2558     return VLC_SUCCESS;
2559 }
2560
2561 int demux_sys_t::EventKey( vlc_object_t *p_this, char const *psz_var,
2562                      vlc_value_t oldval, vlc_value_t newval, void *p_data )
2563 {
2564     event_thread_t *p_ev = (event_thread_t *) p_data;
2565     vlc_mutex_lock( &p_ev->lock );
2566     p_ev->b_key = VLC_TRUE;
2567     vlc_mutex_unlock( &p_ev->lock );
2568     msg_Dbg( p_this, "Event Key");
2569
2570     return VLC_SUCCESS;
2571 }
2572
2573 int demux_sys_t::EventThread( vlc_object_t *p_this )
2574 {
2575     event_thread_t *p_ev = (event_thread_t*)p_this;
2576     demux_sys_t    *p_sys = p_ev->p_demux->p_sys;
2577     vlc_object_t   *p_vout = NULL;
2578
2579     p_ev->b_moved   = VLC_FALSE;
2580     p_ev->b_clicked = VLC_FALSE;
2581     p_ev->b_key     = VLC_FALSE;
2582
2583     /* catch all key event */
2584     var_AddCallback( p_ev->p_libvlc, "key-pressed", EventKey, p_ev );
2585
2586     /* main loop */
2587     while( !p_ev->b_die )
2588     {
2589         if ( !p_sys->b_pci_packet_set )
2590         {
2591             /* Wait 100ms */
2592             msleep( 100000 );
2593             continue;
2594         }
2595
2596         vlc_bool_t b_activated = VLC_FALSE;
2597
2598         /* KEY part */
2599         if( p_ev->b_key )
2600         {
2601             vlc_value_t valk;
2602             struct libvlc_int_t::hotkey *p_hotkeys = p_ev->p_libvlc->p_hotkeys;
2603             int i, i_action = -1;
2604
2605             msg_Dbg( p_ev->p_demux, "Handle Key Event");
2606
2607             vlc_mutex_lock( &p_ev->lock );
2608
2609             pci_t *pci = (pci_t *) &p_sys->pci_packet;
2610
2611             var_Get( p_ev->p_libvlc, "key-pressed", &valk );
2612             for( i = 0; p_hotkeys[i].psz_action != NULL; i++ )
2613             {
2614                 if( p_hotkeys[i].i_key == valk.i_int )
2615                 {
2616                     i_action = p_hotkeys[i].i_action;
2617                 }
2618             }
2619
2620             uint16 i_curr_button = p_sys->dvd_interpretor.GetSPRM( 0x88 );
2621
2622             switch( i_action )
2623             {
2624             case ACTIONID_NAV_LEFT:
2625                 if ( i_curr_button > 0 && i_curr_button <= pci->hli.hl_gi.btn_ns )
2626                 {
2627                     btni_t *p_button_ptr = &(pci->hli.btnit[i_curr_button-1]);
2628                     if ( p_button_ptr->left > 0 && p_button_ptr->left <= pci->hli.hl_gi.btn_ns )
2629                     {
2630                         i_curr_button = p_button_ptr->left;
2631                         p_sys->dvd_interpretor.SetSPRM( 0x88, i_curr_button );
2632                         btni_t button_ptr = pci->hli.btnit[i_curr_button-1];
2633                         if ( button_ptr.auto_action_mode )
2634                         {
2635                             vlc_mutex_unlock( &p_ev->lock );
2636                             vlc_mutex_lock( &p_sys->lock_demuxer );
2637
2638                             // process the button action
2639                             p_sys->dvd_interpretor.Interpret( button_ptr.cmd.bytes, 8 );
2640
2641                             vlc_mutex_unlock( &p_sys->lock_demuxer );
2642                             vlc_mutex_lock( &p_ev->lock );
2643                         }
2644                     }
2645                 }
2646                 break;
2647             case ACTIONID_NAV_RIGHT:
2648                 if ( i_curr_button > 0 && i_curr_button <= pci->hli.hl_gi.btn_ns )
2649                 {
2650                     btni_t *p_button_ptr = &(pci->hli.btnit[i_curr_button-1]);
2651                     if ( p_button_ptr->right > 0 && p_button_ptr->right <= pci->hli.hl_gi.btn_ns )
2652                     {
2653                         i_curr_button = p_button_ptr->right;
2654                         p_sys->dvd_interpretor.SetSPRM( 0x88, i_curr_button );
2655                         btni_t button_ptr = pci->hli.btnit[i_curr_button-1];
2656                         if ( button_ptr.auto_action_mode )
2657                         {
2658                             vlc_mutex_unlock( &p_ev->lock );
2659                             vlc_mutex_lock( &p_sys->lock_demuxer );
2660
2661                             // process the button action
2662                             p_sys->dvd_interpretor.Interpret( button_ptr.cmd.bytes, 8 );
2663
2664                             vlc_mutex_unlock( &p_sys->lock_demuxer );
2665                             vlc_mutex_lock( &p_ev->lock );
2666                         }
2667                     }
2668                 }
2669                 break;
2670             case ACTIONID_NAV_UP:
2671                 if ( i_curr_button > 0 && i_curr_button <= pci->hli.hl_gi.btn_ns )
2672                 {
2673                     btni_t *p_button_ptr = &(pci->hli.btnit[i_curr_button-1]);
2674                     if ( p_button_ptr->up > 0 && p_button_ptr->up <= pci->hli.hl_gi.btn_ns )
2675                     {
2676                         i_curr_button = p_button_ptr->up;
2677                         p_sys->dvd_interpretor.SetSPRM( 0x88, i_curr_button );
2678                         btni_t button_ptr = pci->hli.btnit[i_curr_button-1];
2679                         if ( button_ptr.auto_action_mode )
2680                         {
2681                             vlc_mutex_unlock( &p_ev->lock );
2682                             vlc_mutex_lock( &p_sys->lock_demuxer );
2683
2684                             // process the button action
2685                             p_sys->dvd_interpretor.Interpret( button_ptr.cmd.bytes, 8 );
2686
2687                             vlc_mutex_unlock( &p_sys->lock_demuxer );
2688                             vlc_mutex_lock( &p_ev->lock );
2689                         }
2690                     }
2691                 }
2692                 break;
2693             case ACTIONID_NAV_DOWN:
2694                 if ( i_curr_button > 0 && i_curr_button <= pci->hli.hl_gi.btn_ns )
2695                 {
2696                     btni_t *p_button_ptr = &(pci->hli.btnit[i_curr_button-1]);
2697                     if ( p_button_ptr->down > 0 && p_button_ptr->down <= pci->hli.hl_gi.btn_ns )
2698                     {
2699                         i_curr_button = p_button_ptr->down;
2700                         p_sys->dvd_interpretor.SetSPRM( 0x88, i_curr_button );
2701                         btni_t button_ptr = pci->hli.btnit[i_curr_button-1];
2702                         if ( button_ptr.auto_action_mode )
2703                         {
2704                             vlc_mutex_unlock( &p_ev->lock );
2705                             vlc_mutex_lock( &p_sys->lock_demuxer );
2706
2707                             // process the button action
2708                             p_sys->dvd_interpretor.Interpret( button_ptr.cmd.bytes, 8 );
2709
2710                             vlc_mutex_unlock( &p_sys->lock_demuxer );
2711                             vlc_mutex_lock( &p_ev->lock );
2712                         }
2713                     }
2714                 }
2715                 break;
2716             case ACTIONID_NAV_ACTIVATE:
2717                 b_activated = VLC_TRUE;
2718         
2719                 if ( i_curr_button > 0 && i_curr_button <= pci->hli.hl_gi.btn_ns )
2720                 {
2721                     btni_t button_ptr = pci->hli.btnit[i_curr_button-1];
2722
2723                     vlc_mutex_unlock( &p_ev->lock );
2724                     vlc_mutex_lock( &p_sys->lock_demuxer );
2725
2726                     // process the button action
2727                     p_sys->dvd_interpretor.Interpret( button_ptr.cmd.bytes, 8 );
2728
2729                     vlc_mutex_unlock( &p_sys->lock_demuxer );
2730                     vlc_mutex_lock( &p_ev->lock );
2731                 }
2732                 break;
2733             default:
2734                 break;
2735             }
2736             p_ev->b_key = VLC_FALSE;
2737             vlc_mutex_unlock( &p_ev->lock );
2738         }
2739
2740         /* MOUSE part */
2741         if( p_vout && ( p_ev->b_moved || p_ev->b_clicked ) )
2742         {
2743             vlc_value_t valx, valy;
2744
2745             vlc_mutex_lock( &p_ev->lock );
2746             pci_t *pci = (pci_t *) &p_sys->pci_packet;
2747             var_Get( p_vout, "mouse-x", &valx );
2748             var_Get( p_vout, "mouse-y", &valy );
2749
2750             if( p_ev->b_clicked )
2751             {
2752                 int32_t button;
2753                 int32_t best,dist,d;
2754                 int32_t mx,my,dx,dy;
2755
2756                 msg_Dbg( p_ev->p_demux, "Handle Mouse Event: Mouse clicked x(%d)*y(%d)", (unsigned)valx.i_int, (unsigned)valy.i_int);
2757
2758                 b_activated = VLC_TRUE;
2759                 // get current button
2760                 best = 0;
2761                 dist = 0x08000000; /* >> than  (720*720)+(567*567); */
2762                 for(button = 1; button <= pci->hli.hl_gi.btn_ns; button++)
2763                 {
2764                     btni_t *button_ptr = &(pci->hli.btnit[button-1]);
2765
2766                     if(((unsigned)valx.i_int >= button_ptr->x_start)
2767                      && ((unsigned)valx.i_int <= button_ptr->x_end)
2768                      && ((unsigned)valy.i_int >= button_ptr->y_start)
2769                      && ((unsigned)valy.i_int <= button_ptr->y_end))
2770                     {
2771                         mx = (button_ptr->x_start + button_ptr->x_end)/2;
2772                         my = (button_ptr->y_start + button_ptr->y_end)/2;
2773                         dx = mx - valx.i_int;
2774                         dy = my - valy.i_int;
2775                         d = (dx*dx) + (dy*dy);
2776                         /* If the mouse is within the button and the mouse is closer
2777                         * to the center of this button then it is the best choice. */
2778                         if(d < dist) {
2779                             dist = d;
2780                             best = button;
2781                         }
2782                     }
2783                 }
2784
2785                 if ( best != 0)
2786                 {
2787                     btni_t button_ptr = pci->hli.btnit[best-1];
2788                     uint16 i_curr_button = p_sys->dvd_interpretor.GetSPRM( 0x88 );
2789
2790                     msg_Dbg( &p_sys->demuxer, "Clicked button %d", best );
2791                     vlc_mutex_unlock( &p_ev->lock );
2792                     vlc_mutex_lock( &p_sys->lock_demuxer );
2793
2794                     // process the button action
2795                     p_sys->dvd_interpretor.SetSPRM( 0x88, best );
2796                     p_sys->dvd_interpretor.Interpret( button_ptr.cmd.bytes, 8 );
2797
2798                     msg_Dbg( &p_sys->demuxer, "Processed button %d", best );
2799
2800                     // select new button
2801                     if ( best != i_curr_button )
2802                     {
2803                         vlc_value_t val;
2804
2805                         if( var_Get( p_sys->p_input, "highlight-mutex", &val ) == VLC_SUCCESS )
2806                         {
2807                             vlc_mutex_t *p_mutex = (vlc_mutex_t *) val.p_address;
2808                             uint32_t i_palette;
2809
2810                             if(button_ptr.btn_coln != 0) {
2811                                 i_palette = pci->hli.btn_colit.btn_coli[button_ptr.btn_coln-1][1];
2812                             } else {
2813                                 i_palette = 0;
2814                             }
2815
2816                             for( int i = 0; i < 4; i++ )
2817                             {
2818                                 uint32_t i_yuv = 0xFF;//p_sys->clut[(hl.palette>>(16+i*4))&0x0f];
2819                                 uint8_t i_alpha = (i_palette>>(i*4))&0x0f;
2820                                 i_alpha = i_alpha == 0xf ? 0xff : i_alpha << 4;
2821
2822                                 p_sys->palette[i][0] = (i_yuv >> 16) & 0xff;
2823                                 p_sys->palette[i][1] = (i_yuv >> 0) & 0xff;
2824                                 p_sys->palette[i][2] = (i_yuv >> 8) & 0xff;
2825                                 p_sys->palette[i][3] = i_alpha;
2826                             }
2827
2828                             vlc_mutex_lock( p_mutex );
2829                             val.i_int = button_ptr.x_start; var_Set( p_sys->p_input, "x-start", val );
2830                             val.i_int = button_ptr.x_end;   var_Set( p_sys->p_input, "x-end",   val );
2831                             val.i_int = button_ptr.y_start; var_Set( p_sys->p_input, "y-start", val );
2832                             val.i_int = button_ptr.y_end;   var_Set( p_sys->p_input, "y-end",   val );
2833
2834                             val.p_address = (void *)p_sys->palette;
2835                             var_Set( p_sys->p_input, "menu-palette", val );
2836
2837                             val.b_bool = VLC_TRUE; var_Set( p_sys->p_input, "highlight", val );
2838                             vlc_mutex_unlock( p_mutex );
2839                         }
2840                     }
2841                     vlc_mutex_unlock( &p_sys->lock_demuxer );
2842                     vlc_mutex_lock( &p_ev->lock );
2843                 }
2844             }
2845             else if( p_ev->b_moved )
2846             {
2847 //                dvdnav_mouse_select( NULL, pci, valx.i_int, valy.i_int );
2848             }
2849
2850             p_ev->b_moved = VLC_FALSE;
2851             p_ev->b_clicked = VLC_FALSE;
2852             vlc_mutex_unlock( &p_ev->lock );
2853         }
2854
2855         /* VOUT part */
2856         if( p_vout && p_vout->b_die )
2857         {
2858             var_DelCallback( p_vout, "mouse-moved", EventMouse, p_ev );
2859             var_DelCallback( p_vout, "mouse-clicked", EventMouse, p_ev );
2860             vlc_object_release( p_vout );
2861             p_vout = NULL;
2862         }
2863
2864         else if( p_vout == NULL )
2865         {
2866             p_vout = (vlc_object_t*) vlc_object_find( p_sys->p_input, VLC_OBJECT_VOUT,
2867                                       FIND_CHILD );
2868             if( p_vout)
2869             {
2870                 var_AddCallback( p_vout, "mouse-moved", EventMouse, p_ev );
2871                 var_AddCallback( p_vout, "mouse-clicked", EventMouse, p_ev );
2872             }
2873         }
2874
2875         /* Wait a bit, 10ms */
2876         msleep( 10000 );
2877     }
2878
2879     /* Release callback */
2880     if( p_vout )
2881     {
2882         var_DelCallback( p_vout, "mouse-moved", EventMouse, p_ev );
2883         var_DelCallback( p_vout, "mouse-clicked", EventMouse, p_ev );
2884         vlc_object_release( p_vout );
2885     }
2886     var_DelCallback( p_ev->p_libvlc, "key-pressed", EventKey, p_ev );
2887
2888     vlc_mutex_destroy( &p_ev->lock );
2889
2890     return VLC_SUCCESS;
2891 }
2892
2893 void matroska_segment_c::UnSelect( )
2894 {
2895     size_t i_track;
2896
2897     for( i_track = 0; i_track < tracks.size(); i_track++ )
2898     {
2899         if ( tracks[i_track]->p_es != NULL )
2900         {
2901 //            es_format_Clean( &tracks[i_track]->fmt );
2902             es_out_Del( sys.demuxer.out, tracks[i_track]->p_es );
2903             tracks[i_track]->p_es = NULL;
2904         }
2905     }
2906     delete ep;
2907     ep = NULL;
2908 }
2909
2910 void virtual_segment_c::PrepareChapters( )
2911 {
2912     if ( linked_segments.size() == 0 )
2913         return;
2914
2915     // !!! should be called only once !!!
2916     matroska_segment_c *p_segment;
2917     size_t i, j;
2918
2919     // copy editions from the first segment
2920     p_segment = linked_segments[0];
2921     p_editions = &p_segment->stored_editions;
2922
2923     for ( i=1 ; i<linked_segments.size(); i++ )
2924     {
2925         p_segment = linked_segments[i];
2926         // FIXME assume we have the same editions in all segments
2927         for (j=0; j<p_segment->stored_editions.size(); j++)
2928             (*p_editions)[j]->Append( *p_segment->stored_editions[j] );
2929     }
2930 }
2931
2932 std::string chapter_edition_c::GetMainName() const
2933 {
2934     if ( sub_chapters.size() )
2935     {
2936         return sub_chapters[0]->GetCodecName( true );
2937     }
2938     return "";
2939 }
2940
2941 int chapter_item_c::PublishChapters( input_title_t & title, int & i_user_chapters, int i_level )
2942 {
2943     // add support for meta-elements from codec like DVD Titles
2944     if ( !b_display_seekpoint || psz_name == "" )
2945     {
2946         psz_name = GetCodecName();
2947         if ( psz_name != "" )
2948             b_display_seekpoint = true;
2949     }
2950
2951     if (b_display_seekpoint)
2952     {
2953         seekpoint_t *sk = vlc_seekpoint_New();
2954
2955         sk->i_level = i_level;
2956         sk->i_time_offset = i_start_time;
2957         sk->psz_name = strdup( psz_name.c_str() );
2958
2959         // A start time of '0' is ok. A missing ChapterTime element is ok, too, because '0' is its default value.
2960         title.i_seekpoint++;
2961         title.seekpoint = (seekpoint_t**)realloc( title.seekpoint, title.i_seekpoint * sizeof( seekpoint_t* ) );
2962         title.seekpoint[title.i_seekpoint-1] = sk;
2963
2964         if ( b_user_display )
2965             i_user_chapters++;
2966     }
2967
2968     for ( size_t i=0; i<sub_chapters.size() ; i++)
2969     {
2970         sub_chapters[i]->PublishChapters( title, i_user_chapters, i_level+1 );
2971     }
2972
2973     i_seekpoint_num = i_user_chapters;
2974
2975     return i_user_chapters;
2976 }
2977
2978 bool virtual_segment_c::UpdateCurrentToChapter( demux_t & demux )
2979 {
2980     demux_sys_t & sys = *demux.p_sys;
2981     chapter_item_c *psz_curr_chapter;
2982     bool b_has_seeked = false;
2983
2984     /* update current chapter/seekpoint */
2985     if ( p_editions->size() )
2986     {
2987         /* 1st, we need to know in which chapter we are */
2988         psz_curr_chapter = (*p_editions)[i_current_edition]->FindTimecode( sys.i_pts, psz_current_chapter );
2989
2990         /* we have moved to a new chapter */
2991         if (psz_curr_chapter != NULL && psz_current_chapter != psz_curr_chapter)
2992         {
2993             if ( (*p_editions)[i_current_edition]->b_ordered )
2994             {
2995                 // Leave/Enter up to the link point
2996                 b_has_seeked = psz_curr_chapter->EnterAndLeave( psz_current_chapter );
2997                 if ( !b_has_seeked )
2998                 {
2999                     // only physically seek if necessary
3000                     if ( psz_current_chapter == NULL || (psz_current_chapter->i_end_time != psz_curr_chapter->i_start_time) )
3001                         Seek( demux, sys.i_pts, 0, psz_curr_chapter );
3002                 }
3003             }
3004             
3005             if ( !b_has_seeked )
3006             {
3007                 psz_current_chapter = psz_curr_chapter;
3008                 if ( psz_curr_chapter->i_seekpoint_num > 0 )
3009                 {
3010                     demux.info.i_update |= INPUT_UPDATE_TITLE | INPUT_UPDATE_SEEKPOINT;
3011                     demux.info.i_title = sys.i_current_title = i_sys_title;
3012                     demux.info.i_seekpoint = psz_curr_chapter->i_seekpoint_num - 1;
3013                 }
3014             }
3015
3016             return true;
3017         }
3018         else if (psz_curr_chapter == NULL)
3019         {
3020             // out of the scope of the data described by chapters, leave the edition
3021             if ( (*p_editions)[i_current_edition]->b_ordered && psz_current_chapter != NULL )
3022             {
3023                 if ( !(*p_editions)[i_current_edition]->EnterAndLeave( psz_current_chapter, false ) )
3024                     psz_current_chapter = NULL;
3025                 else
3026                     return true;
3027             }
3028         }
3029     }
3030     return false;
3031 }
3032
3033 chapter_item_c *virtual_segment_c::BrowseCodecPrivate( unsigned int codec_id,
3034                                     bool (*match)(const chapter_codec_cmds_c &data, const void *p_cookie, size_t i_cookie_size ),
3035                                     const void *p_cookie,
3036                                     size_t i_cookie_size )
3037 {
3038     // FIXME don't assume it is the first edition
3039     std::vector<chapter_edition_c*>::iterator index = p_editions->begin();
3040     if ( index != p_editions->end() )
3041     {
3042         chapter_item_c *p_result = (*index)->BrowseCodecPrivate( codec_id, match, p_cookie, i_cookie_size );
3043         if ( p_result != NULL )
3044             return p_result;
3045     }
3046     return NULL;
3047 }
3048
3049 chapter_item_c *virtual_segment_c::FindChapter( int64_t i_find_uid )
3050 {
3051     // FIXME don't assume it is the first edition
3052     std::vector<chapter_edition_c*>::iterator index = p_editions->begin();
3053     if ( index != p_editions->end() )
3054     {
3055         chapter_item_c *p_result = (*index)->FindChapter( i_find_uid );
3056         if ( p_result != NULL )
3057             return p_result;
3058     }
3059     return NULL;
3060 }
3061
3062 chapter_item_c *chapter_item_c::BrowseCodecPrivate( unsigned int codec_id,
3063                                     bool (*match)(const chapter_codec_cmds_c &data, const void *p_cookie, size_t i_cookie_size ),
3064                                     const void *p_cookie,
3065                                     size_t i_cookie_size )
3066 {
3067     // this chapter
3068     std::vector<chapter_codec_cmds_c*>::const_iterator index = codecs.begin();
3069     while ( index != codecs.end() )
3070     {
3071         if ( match( **index ,p_cookie, i_cookie_size ) )
3072             return this;
3073         index++;
3074     }
3075     
3076     // sub-chapters
3077     chapter_item_c *p_result = NULL;
3078     std::vector<chapter_item_c*>::const_iterator index2 = sub_chapters.begin();
3079     while ( index2 != sub_chapters.end() )
3080     {
3081         p_result = (*index2)->BrowseCodecPrivate( codec_id, match, p_cookie, i_cookie_size );
3082         if ( p_result != NULL )
3083             return p_result;
3084         index2++;
3085     }
3086     
3087     return p_result;
3088 }
3089
3090 void chapter_item_c::Append( const chapter_item_c & chapter )
3091 {
3092     // we are appending content for the same chapter UID
3093     size_t i;
3094     chapter_item_c *p_chapter;
3095
3096     for ( i=0; i<chapter.sub_chapters.size(); i++ )
3097     {
3098         p_chapter = FindChapter( chapter.sub_chapters[i]->i_uid );
3099         if ( p_chapter != NULL )
3100         {
3101             p_chapter->Append( *chapter.sub_chapters[i] );
3102         }
3103         else
3104         {
3105             sub_chapters.push_back( chapter.sub_chapters[i] );
3106         }
3107     }
3108
3109     i_user_start_time = min( i_user_start_time, chapter.i_user_start_time );
3110     i_user_end_time = max( i_user_end_time, chapter.i_user_end_time );
3111 }
3112
3113 chapter_item_c * chapter_item_c::FindChapter( int64_t i_find_uid )
3114 {
3115     size_t i;
3116     chapter_item_c *p_result = NULL;
3117
3118     if ( i_uid == i_find_uid )
3119         return this;
3120
3121     for ( i=0; i<sub_chapters.size(); i++)
3122     {
3123         p_result = sub_chapters[i]->FindChapter( i_find_uid );
3124         if ( p_result != NULL )
3125             break;
3126     }
3127     return p_result;
3128 }
3129
3130 std::string chapter_item_c::GetCodecName( bool f_for_title ) const
3131 {
3132     std::string result;
3133
3134     std::vector<chapter_codec_cmds_c*>::const_iterator index = codecs.begin();
3135     while ( index != codecs.end() )
3136     {
3137         result = (*index)->GetCodecName( f_for_title );
3138         if ( result != "" )
3139             break;
3140         index++;
3141     }
3142
3143     return result;
3144 }
3145
3146 std::string dvd_chapter_codec_c::GetCodecName( bool f_for_title ) const
3147 {
3148     std::string result;
3149     if ( p_private_data->GetSize() >= 3)
3150     {
3151         const binary* p_data = p_private_data->GetBuffer();
3152 /*        if ( p_data[0] == MATROSKA_DVD_LEVEL_TT )
3153         {
3154             uint16_t i_title = (p_data[1] << 8) + p_data[2];
3155             char psz_str[11];
3156             sprintf( psz_str, " %d  ---", i_title );
3157             result = N_("---  DVD Title");
3158             result += psz_str;
3159         }
3160         else */ if ( p_data[0] == MATROSKA_DVD_LEVEL_LU )
3161         {
3162             char psz_str[11];
3163             sprintf( psz_str, " (%c%c)  ---", p_data[1], p_data[2] );
3164             result = N_("---  DVD Menu");
3165             result += psz_str;
3166         }
3167         else if ( p_data[0] == MATROSKA_DVD_LEVEL_SS && f_for_title )
3168         {
3169             if ( p_data[1] == 0x00 )
3170                 result = N_("First Played");
3171             else if ( p_data[1] == 0xC0 )
3172                 result = N_("Video Manager");
3173             else if ( p_data[1] == 0x80 )
3174             {
3175                 uint16_t i_title = (p_data[2] << 8) + p_data[3];
3176                 char psz_str[20];
3177                 sprintf( psz_str, " %d -----", i_title );
3178                 result = N_("----- Title");
3179                 result += psz_str;
3180             }
3181         }
3182     }
3183
3184     return result;
3185 }
3186
3187 int16 chapter_item_c::GetTitleNumber( ) const
3188 {
3189     int result = -1;
3190
3191     std::vector<chapter_codec_cmds_c*>::const_iterator index = codecs.begin();
3192     while ( index != codecs.end() )
3193     {
3194         result = (*index)->GetTitleNumber( );
3195         if ( result >= 0 )
3196             break;
3197         index++;
3198     }
3199
3200     return result;
3201 }
3202
3203 int16 dvd_chapter_codec_c::GetTitleNumber()
3204 {
3205     if ( p_private_data->GetSize() >= 3)
3206     {
3207         const binary* p_data = p_private_data->GetBuffer();
3208         if ( p_data[0] == MATROSKA_DVD_LEVEL_SS )
3209         {
3210             return int16( (p_data[2] << 8) + p_data[3] );
3211         }
3212     }
3213     return -1;
3214 }
3215
3216 static void Seek( demux_t *p_demux, mtime_t i_date, double f_percent, chapter_item_c *psz_chapter )
3217 {
3218     demux_sys_t        *p_sys = p_demux->p_sys;
3219     virtual_segment_c  *p_vsegment = p_sys->p_current_segment;
3220     matroska_segment_c *p_segment = p_vsegment->Segment();
3221     mtime_t            i_time_offset = 0;
3222
3223     int         i_index;
3224
3225     msg_Dbg( p_demux, "seek request to "I64Fd" (%f%%)", i_date, f_percent );
3226     if( i_date < 0 && f_percent < 0 )
3227     {
3228         msg_Warn( p_demux, "cannot seek nowhere !" );
3229         return;
3230     }
3231     if( f_percent > 1.0 )
3232     {
3233         msg_Warn( p_demux, "cannot seek so far !" );
3234         return;
3235     }
3236
3237     /* seek without index or without date */
3238     if( f_percent >= 0 && (config_GetInt( p_demux, "mkv-seek-percent" ) || !p_segment->b_cues || i_date < 0 ))
3239     {
3240         if (p_sys->f_duration >= 0)
3241         {
3242             i_date = int64_t( f_percent * p_sys->f_duration * 1000.0 );
3243         }
3244         else
3245         {
3246             int64_t i_pos = int64_t( f_percent * stream_Size( p_demux->s ) );
3247
3248             msg_Dbg( p_demux, "inacurate way of seeking" );
3249             for( i_index = 0; i_index < p_segment->i_index; i_index++ )
3250             {
3251                 if( p_segment->p_indexes[i_index].i_position >= i_pos)
3252                 {
3253                     break;
3254                 }
3255             }
3256             if( i_index == p_segment->i_index )
3257             {
3258                 i_index--;
3259             }
3260
3261             i_date = p_segment->p_indexes[i_index].i_time;
3262
3263 #if 0
3264             if( p_segment->p_indexes[i_index].i_position < i_pos )
3265             {
3266                 EbmlElement *el;
3267
3268                 msg_Warn( p_demux, "searching for cluster, could take some time" );
3269
3270                 /* search a cluster */
3271                 while( ( el = p_sys->ep->Get() ) != NULL )
3272                 {
3273                     if( MKV_IS_ID( el, KaxCluster ) )
3274                     {
3275                         KaxCluster *cluster = (KaxCluster*)el;
3276
3277                         /* add it to the index */
3278                         p_segment->IndexAppendCluster( cluster );
3279
3280                         if( (int64_t)cluster->GetElementPosition() >= i_pos )
3281                         {
3282                             p_sys->cluster = cluster;
3283                             p_sys->ep->Down();
3284                             break;
3285                         }
3286                     }
3287                 }
3288             }
3289 #endif
3290         }
3291     }
3292
3293     p_vsegment->Seek( *p_demux, i_date, i_time_offset, psz_chapter );
3294 }
3295
3296 /*****************************************************************************
3297  * Demux: reads and demuxes data packets
3298  *****************************************************************************
3299  * Returns -1 in case of error, 0 in case of EOF, 1 otherwise
3300  *****************************************************************************/
3301 static int Demux( demux_t *p_demux)
3302 {
3303     demux_sys_t        *p_sys = p_demux->p_sys;
3304
3305     vlc_mutex_lock( &p_sys->lock_demuxer );
3306
3307     virtual_segment_c  *p_vsegment = p_sys->p_current_segment;
3308     matroska_segment_c *p_segment = p_vsegment->Segment();
3309     if ( p_segment == NULL ) return 0;
3310     int                i_block_count = 0;
3311     int                i_return = 0;
3312
3313     for( ;; )
3314     {
3315         if ( p_sys->demuxer.b_die )
3316             break;
3317
3318         if( p_sys->i_pts >= p_sys->i_start_pts  )
3319             if ( p_vsegment->UpdateCurrentToChapter( *p_demux ) )
3320             {
3321                 i_return = 1;
3322                 break;
3323             }
3324         
3325         if ( p_vsegment->Edition() && p_vsegment->Edition()->b_ordered && p_vsegment->CurrentChapter() == NULL )
3326         {
3327             /* nothing left to read in this ordered edition */
3328             if ( !p_vsegment->SelectNext() )
3329                 break;
3330             p_segment->UnSelect( );
3331             
3332             es_out_Control( p_demux->out, ES_OUT_RESET_PCR );
3333
3334             /* switch to the next segment */
3335             p_segment = p_vsegment->Segment();
3336             if ( !p_segment->Select( 0 ) )