]> git.sesse.net Git - vlc/blob - modules/demux/mkv/matroska_segment.cpp
split add_file into add_loadfile and add_savefile
[vlc] / modules / demux / mkv / matroska_segment.cpp
1 /*****************************************************************************
2  * mkv.cpp : matroska demuxer
3  *****************************************************************************
4  * Copyright (C) 2003-2010 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 #include "matroska_segment.hpp"
26
27 #include "chapters.hpp"
28
29 #include "demux.hpp"
30
31 extern "C" {
32 #include "../vobsub.h"
33 }
34
35 #include <vlc_codecs.h>
36
37 /* GetFourCC helper */
38 #define GetFOURCC( p )  __GetFOURCC( (uint8_t*)p )
39 static vlc_fourcc_t __GetFOURCC( uint8_t *p )
40 {
41     return VLC_FOURCC( p[0], p[1], p[2], p[3] );
42 }
43
44 /* Destructor */
45 matroska_segment_c::~matroska_segment_c()
46 {
47     for( size_t i_track = 0; i_track < tracks.size(); i_track++ )
48     {
49         delete tracks[i_track]->p_compression_data;
50         es_format_Clean( &tracks[i_track]->fmt );
51         free( tracks[i_track]->p_extra_data );
52         free( tracks[i_track]->psz_codec );
53         delete tracks[i_track];
54     }
55
56     free( psz_writing_application );
57     free( psz_muxing_application );
58     free( psz_segment_filename );
59     free( psz_title );
60     free( psz_date_utc );
61     free( p_indexes );
62
63     delete ep;
64     delete segment;
65     delete p_segment_uid;
66     delete p_prev_segment_uid;
67     delete p_next_segment_uid;
68
69     std::vector<chapter_edition_c*>::iterator index = stored_editions.begin();
70     while ( index != stored_editions.end() )
71     {
72         delete (*index);
73         index++;
74     }
75     std::vector<chapter_translation_c*>::iterator indext = translations.begin();
76     while ( indext != translations.end() )
77     {
78         delete (*indext);
79         indext++;
80     }
81     std::vector<KaxSegmentFamily*>::iterator indexf = families.begin();
82     while ( indexf != families.end() )
83     {
84         delete (*indexf);
85         indexf++;
86    }
87 }
88
89
90 /*****************************************************************************
91  * Tools                                                                     *
92  *****************************************************************************
93  *  * LoadCues : load the cues element and update index
94  *  * LoadTags : load ... the tags element
95  *  * InformationCreate : create all information, load tags if present
96  *****************************************************************************/
97 void matroska_segment_c::LoadCues( KaxCues *cues )
98 {
99     EbmlParser  *ep;
100     EbmlElement *el;
101
102     if( b_cues )
103     {
104         msg_Err( &sys.demuxer, "There can be only 1 Cues per section." );
105         return;
106     }
107
108     ep = new EbmlParser( &es, cues, &sys.demuxer );
109     while( ( el = ep->Get() ) != NULL )
110     {
111         if( MKV_IS_ID( el, KaxCuePoint ) )
112         {
113 #define idx p_indexes[i_index]
114
115             idx.i_track       = -1;
116             idx.i_block_number= -1;
117             idx.i_position    = -1;
118             idx.i_time        = 0;
119             idx.b_key         = true;
120
121             ep->Down();
122             while( ( el = ep->Get() ) != NULL )
123             {
124                 if( MKV_IS_ID( el, KaxCueTime ) )
125                 {
126                     KaxCueTime &ctime = *(KaxCueTime*)el;
127
128                     ctime.ReadData( es.I_O() );
129
130                     idx.i_time = uint64( ctime ) * i_timescale / (mtime_t)1000;
131                 }
132                 else if( MKV_IS_ID( el, KaxCueTrackPositions ) )
133                 {
134                     ep->Down();
135                     while( ( el = ep->Get() ) != NULL )
136                     {
137                         if( MKV_IS_ID( el, KaxCueTrack ) )
138                         {
139                             KaxCueTrack &ctrack = *(KaxCueTrack*)el;
140
141                             ctrack.ReadData( es.I_O() );
142                             idx.i_track = uint16( ctrack );
143                         }
144                         else if( MKV_IS_ID( el, KaxCueClusterPosition ) )
145                         {
146                             KaxCueClusterPosition &ccpos = *(KaxCueClusterPosition*)el;
147
148                             ccpos.ReadData( es.I_O() );
149                             idx.i_position = segment->GetGlobalPosition( uint64( ccpos ) );
150                         }
151                         else if( MKV_IS_ID( el, KaxCueBlockNumber ) )
152                         {
153                             KaxCueBlockNumber &cbnum = *(KaxCueBlockNumber*)el;
154
155                             cbnum.ReadData( es.I_O() );
156                             idx.i_block_number = uint32( cbnum );
157                         }
158                         else
159                         {
160                             msg_Dbg( &sys.demuxer, "         * Unknown (%s)", typeid(*el).name() );
161                         }
162                     }
163                     ep->Up();
164                 }
165                 else
166                 {
167                     msg_Dbg( &sys.demuxer, "     * Unknown (%s)", typeid(*el).name() );
168                 }
169             }
170             ep->Up();
171
172 #if 0
173             msg_Dbg( &sys.demuxer, " * added time=%"PRId64" pos=%"PRId64
174                      " track=%d bnum=%d", idx.i_time, idx.i_position,
175                      idx.i_track, idx.i_block_number );
176 #endif
177
178             i_index++;
179             if( i_index >= i_index_max )
180             {
181                 i_index_max += 1024;
182                 p_indexes = (mkv_index_t*)xrealloc( p_indexes,
183                                         sizeof( mkv_index_t ) * i_index_max );
184             }
185 #undef idx
186         }
187         else
188         {
189             msg_Dbg( &sys.demuxer, " * Unknown (%s)", typeid(*el).name() );
190         }
191     }
192     delete ep;
193     b_cues = true;
194     msg_Dbg( &sys.demuxer, "|   - loading cues done." );
195 }
196
197
198 #define PARSE_TAG( type ) \
199     do { \
200     msg_Dbg( &sys.demuxer, "|   + " type ); \
201     ep->Down();                             \
202     while( ( el = ep->Get() ) != NULL )     \
203     {                                       \
204         msg_Dbg( &sys.demuxer, "|   |   + Unknown (%s)", typeid( *el ).name() ); \
205     }                                      \
206     ep->Up(); } while( 0 )
207
208 static const struct {
209     vlc_meta_type_t type;
210     const char *key;
211 } metadata_map[] = { {vlc_meta_Title,       "TITLE"},
212                      {vlc_meta_Artist,      "ARTIST"},
213                      {vlc_meta_Genre,       "GENRE"},
214                      {vlc_meta_Copyright,   "COPYRIGHT"},
215                      {vlc_meta_Description, "DESCRIPTION"},
216                      {vlc_meta_Publisher,   "PUBLISHER"},
217                      {vlc_meta_URL,         "URL"},
218                      {vlc_meta_Title,       NULL},
219 };
220
221 void matroska_segment_c::ParseSimpleTags( KaxTagSimple *tag )
222 {
223     EbmlElement *el;
224     EbmlParser *ep = new EbmlParser( &es, tag, &sys.demuxer );
225     char *k = NULL, *v = NULL;
226
227     if( !sys.meta )
228         sys.meta = vlc_meta_New();
229
230     msg_Dbg( &sys.demuxer, "|   + Simple Tag ");
231     while( ( el = ep->Get() ) != NULL )
232     {
233         if( MKV_IS_ID( el, KaxTagName ) )
234         {
235             KaxTagName &key = *(KaxTagName*)el;
236             key.ReadData( es.I_O(), SCOPE_ALL_DATA );
237             k = strdup( UTFstring( key ).GetUTF8().c_str() );
238         }
239         if( MKV_IS_ID( el, KaxTagString ) )
240         {
241             KaxTagString &value = *(KaxTagString*)el;
242             value.ReadData( es.I_O(), SCOPE_ALL_DATA );
243             v = strdup( UTFstring( value ).GetUTF8().c_str() );
244         }
245     }
246     delete ep;
247
248     if( !k || !v )
249     {
250         msg_Warn( &sys.demuxer, "Invalid MKV SimpleTag found.");
251         return;
252     }
253
254     for( int i = 0; metadata_map[i].key; i++ )
255     {
256         if( !strcmp( k, metadata_map[i].key ) )
257         {
258             vlc_meta_Set( sys.meta, metadata_map[i].type, v );
259             goto done;
260         }
261     }
262     vlc_meta_AddExtra( sys.meta, k, v );
263 done:
264     free( k );
265     free( v );
266     return;
267 }
268
269 void matroska_segment_c::LoadTags( KaxTags *tags )
270 {
271     /* Master elements */
272     EbmlParser *ep = new EbmlParser( &es, tags, &sys.demuxer );
273     EbmlElement *el;
274
275     while( ( el = ep->Get() ) != NULL )
276     {
277         if( MKV_IS_ID( el, KaxTag ) )
278         {
279             msg_Dbg( &sys.demuxer, "+ Tag" );
280             ep->Down();
281             while( ( el = ep->Get() ) != NULL )
282             {
283                 if( MKV_IS_ID( el, KaxTagTargets ) )
284                     PARSE_TAG( "Targets" );
285                 else if( MKV_IS_ID( el, KaxTagGeneral ) )
286                     PARSE_TAG( "General" );
287                 else if( MKV_IS_ID( el, KaxTagGenres ) )
288                     PARSE_TAG( "Genres" );
289                 else if( MKV_IS_ID( el, KaxTagAudioSpecific ) )
290                     PARSE_TAG( "Audio Specific" );
291                 else if( MKV_IS_ID( el, KaxTagImageSpecific ) )
292                     PARSE_TAG( "Images Specific" );
293                 else if( MKV_IS_ID( el, KaxTagMultiComment ) )
294                 {
295                     msg_Dbg( &sys.demuxer, "|   + Multi Comment" );
296                 }
297                 else if( MKV_IS_ID( el, KaxTagMultiCommercial ) )
298                 {
299                     msg_Dbg( &sys.demuxer, "|   + Multi Commercial" );
300                 }
301                 else if( MKV_IS_ID( el, KaxTagMultiDate ) )
302                 {
303                     msg_Dbg( &sys.demuxer, "|   + Multi Date" );
304                 }
305                 else if( MKV_IS_ID( el, KaxTagMultiEntity ) )
306                 {
307                     msg_Dbg( &sys.demuxer, "|   + Multi Entity" );
308                 }
309                 else if( MKV_IS_ID( el, KaxTagMultiIdentifier ) )
310                 {
311                     msg_Dbg( &sys.demuxer, "|   + Multi Identifier" );
312                 }
313                 else if( MKV_IS_ID( el, KaxTagMultiLegal ) )
314                 {
315                     msg_Dbg( &sys.demuxer, "|   + Multi Legal" );
316                 }
317                 else if( MKV_IS_ID( el, KaxTagMultiTitle ) )
318                 {
319                     msg_Dbg( &sys.demuxer, "|   + Multi Title" );
320                 }
321                 else if( MKV_IS_ID( el, KaxTagSimple ) )
322                     ParseSimpleTags( static_cast<KaxTagSimple*>( el ) );
323                 else
324                 {
325                     msg_Dbg( &sys.demuxer, "|   + LoadTag Unknown (%s)", typeid( *el ).name() );
326                 }
327             }
328             ep->Up();
329         }
330         else
331         {
332             msg_Dbg( &sys.demuxer, "+ Unknown (%s)", typeid( *el ).name() );
333         }
334     }
335     delete ep;
336
337     msg_Dbg( &sys.demuxer, "loading tags done." );
338 }
339 #undef PARSE_TAG
340
341 /*****************************************************************************
342  * InformationCreate:
343  *****************************************************************************/
344 void matroska_segment_c::InformationCreate( )
345 {
346 #if 0
347     sys.meta = vlc_meta_New();
348
349     if( psz_title )
350     {
351         vlc_meta_SetTitle( sys.meta, psz_title );
352     }
353     if( psz_date_utc )
354     {
355         vlc_meta_SetDate( sys.meta, psz_date_utc );
356     }
357
358     if( psz_segment_filename )
359     {
360         fprintf( stderr, "***** WARNING: Unhandled meta - Use custom\n" );
361     }
362     if( psz_muxing_application )
363     {
364         fprintf( stderr, "***** WARNING: Unhandled meta - Use custom\n" );
365     }
366     if( psz_writing_application )
367     {
368         fprintf( stderr, "***** WARNING: Unhandled meta - Use custom\n" );
369     }
370
371     for( size_t i_track = 0; i_track < tracks.size(); i_track++ )
372     {
373 //        mkv_track_t *tk = tracks[i_track];
374 //        vlc_meta_t *mtk = vlc_meta_New();
375         fprintf( stderr, "***** WARNING: Unhandled child meta\n");
376     }
377 #endif
378 #if 0
379     if( i_tags_position >= 0 )
380     {
381         bool b_seekable;
382
383         stream_Control( sys.demuxer.s, STREAM_CAN_FASTSEEK, &b_seekable );
384         if( b_seekable )
385         {
386             LoadTags( );
387         }
388     }
389 #endif
390 }
391
392
393 /*****************************************************************************
394  * Misc
395  *****************************************************************************/
396
397 void matroska_segment_c::IndexAppendCluster( KaxCluster *cluster )
398 {
399 #define idx p_indexes[i_index]
400     idx.i_track       = -1;
401     idx.i_block_number= -1;
402     idx.i_position    = cluster->GetElementPosition();
403     idx.i_time        = -1;
404     idx.b_key         = true;
405
406     i_index++;
407     if( i_index >= i_index_max )
408     {
409         i_index_max += 1024;
410         p_indexes = (mkv_index_t*)xrealloc( p_indexes,
411                                         sizeof( mkv_index_t ) * i_index_max );
412     }
413 #undef idx
414 }
415
416 bool matroska_segment_c::PreloadFamily( const matroska_segment_c & of_segment )
417 {
418     if ( b_preloaded )
419         return false;
420
421     for (size_t i=0; i<families.size(); i++)
422     {
423         for (size_t j=0; j<of_segment.families.size(); j++)
424         {
425             if ( *(families[i]) == *(of_segment.families[j]) )
426                 return Preload( );
427         }
428     }
429
430     return false;
431 }
432
433 bool matroska_segment_c::CompareSegmentUIDs( const matroska_segment_c * p_item_a, const matroska_segment_c * p_item_b )
434 {
435     EbmlBinary *p_tmp;
436
437     if ( p_item_a == NULL || p_item_b == NULL )
438         return false;
439
440     p_tmp = (EbmlBinary *)p_item_a->p_segment_uid;
441     if ( p_item_b->p_prev_segment_uid != NULL
442           && *p_tmp == *p_item_b->p_prev_segment_uid )
443         return true;
444
445     p_tmp = (EbmlBinary *)p_item_a->p_next_segment_uid;
446     if ( !p_tmp )
447         return false;
448
449     if ( p_item_b->p_segment_uid != NULL
450           && *p_tmp == *p_item_b->p_segment_uid )
451         return true;
452
453     if ( p_item_b->p_prev_segment_uid != NULL
454           && *p_tmp == *p_item_b->p_prev_segment_uid )
455         return true;
456
457     return false;
458 }
459
460 bool matroska_segment_c::Preload( )
461 {
462     if ( b_preloaded )
463         return false;
464
465     EbmlElement *el = NULL;
466
467     ep->Reset( &sys.demuxer );
468
469     while( ( el = ep->Get() ) != NULL )
470     {
471         if( MKV_IS_ID( el, KaxSeekHead ) )
472         {
473             /* Multiple allowed */
474             /* We bail at 10, to prevent possible recursion */
475             msg_Dbg(  &sys.demuxer, "|   + Seek head" );
476             if( i_seekhead_count < 10 )
477             {
478                 i_seekhead_position = (int64_t) es.I_O().getFilePointer();
479                 ParseSeekHead( static_cast<KaxSeekHead*>( el ) );
480             }
481         }
482         else if( MKV_IS_ID( el, KaxInfo ) )
483         {
484             /* Multiple allowed, mandatory */
485             msg_Dbg(  &sys.demuxer, "|   + Information" );
486             if( i_info_position < 0 ) // FIXME
487                 ParseInfo( static_cast<KaxInfo*>( el ) );
488             i_info_position = (int64_t) es.I_O().getFilePointer();
489         }
490         else if( MKV_IS_ID( el, KaxTracks ) )
491         {
492             /* Multiple allowed */
493             msg_Dbg(  &sys.demuxer, "|   + Tracks" );
494             if( i_tracks_position < 0 ) // FIXME
495                 ParseTracks( static_cast<KaxTracks*>( el ) );
496             if ( tracks.size() == 0 )
497             {
498                 msg_Err( &sys.demuxer, "No tracks supported" );
499                 return false;
500             }
501             i_tracks_position = (int64_t) es.I_O().getFilePointer();
502         }
503         else if( MKV_IS_ID( el, KaxCues ) )
504         {
505             msg_Dbg(  &sys.demuxer, "|   + Cues" );
506             if( i_cues_position < 0 )
507                 LoadCues( static_cast<KaxCues*>( el ) );
508             i_cues_position = (int64_t) es.I_O().getFilePointer();
509         }
510         else if( MKV_IS_ID( el, KaxCluster ) )
511         {
512             msg_Dbg( &sys.demuxer, "|   + Cluster" );
513
514             cluster = (KaxCluster*)el;
515
516             i_cluster_pos = i_start_pos = cluster->GetElementPosition();
517             ParseCluster( );
518
519             ep->Down();
520             /* stop pre-parsing the stream */
521             break;
522         }
523         else if( MKV_IS_ID( el, KaxAttachments ) )
524         {
525             msg_Dbg( &sys.demuxer, "|   + Attachments" );
526             if( i_attachments_position < 0 )
527                 ParseAttachments( static_cast<KaxAttachments*>( el ) );
528             i_attachments_position = (int64_t) es.I_O().getFilePointer();
529         }
530         else if( MKV_IS_ID( el, KaxChapters ) )
531         {
532             msg_Dbg( &sys.demuxer, "|   + Chapters" );
533             if( i_chapters_position < 0 )
534                 ParseChapters( static_cast<KaxChapters*>( el ) );
535             i_chapters_position = (int64_t) es.I_O().getFilePointer();
536         }
537         else if( MKV_IS_ID( el, KaxTag ) )
538         {
539             msg_Dbg( &sys.demuxer, "|   + Tags" );
540             if( i_tags_position < 0) // FIXME
541                 ;//LoadTags( static_cast<KaxTags*>( el ) );
542             i_tags_position = (int64_t) es.I_O().getFilePointer();
543         }
544         else if( MKV_IS_ID( el, EbmlVoid ) )
545             msg_Dbg( &sys.demuxer, "|   + Void" );
546         else
547             msg_Dbg( &sys.demuxer, "|   + Preload Unknown (%s)", typeid(*el).name() );
548     }
549
550     b_preloaded = true;
551
552     return true;
553 }
554
555 /* Here we try to load elements that were found in Seek Heads, but not yet parsed */
556 bool matroska_segment_c::LoadSeekHeadItem( const EbmlCallbacks & ClassInfos, int64_t i_element_position )
557 {
558     int64_t     i_sav_position = (int64_t)es.I_O().getFilePointer();
559     EbmlElement *el;
560
561     es.I_O().setFilePointer( i_element_position, seek_beginning );
562     el = es.FindNextID( ClassInfos, 0xFFFFFFFFL);
563
564     if( el == NULL )
565     {
566         msg_Err( &sys.demuxer, "cannot load some cues/chapters/tags etc. (broken seekhead or file)" );
567         es.I_O().setFilePointer( i_sav_position, seek_beginning );
568         return false;
569     }
570
571     if( MKV_IS_ID( el, KaxSeekHead ) )
572     {
573         /* Multiple allowed */
574         msg_Dbg( &sys.demuxer, "|   + Seek head" );
575         if( i_seekhead_count < 10 )
576         {
577             i_seekhead_position = i_element_position;
578             ParseSeekHead( static_cast<KaxSeekHead*>( el ) );
579         }
580     }
581     else if( MKV_IS_ID( el, KaxInfo ) ) // FIXME
582     {
583         /* Multiple allowed, mandatory */
584         msg_Dbg( &sys.demuxer, "|   + Information" );
585         if( i_info_position < 0 )
586             ParseInfo( static_cast<KaxInfo*>( el ) );
587         i_info_position = i_element_position;
588     }
589     else if( MKV_IS_ID( el, KaxTracks ) ) // FIXME
590     {
591         /* Multiple allowed */
592         msg_Dbg( &sys.demuxer, "|   + Tracks" );
593         if( i_tracks_position < 0 )
594             ParseTracks( static_cast<KaxTracks*>( el ) );
595         if ( tracks.size() == 0 )
596         {
597             msg_Err( &sys.demuxer, "No tracks supported" );
598             delete el;
599             es.I_O().setFilePointer( i_sav_position, seek_beginning );
600             return false;
601         }
602         i_tracks_position = i_element_position;
603     }
604     else if( MKV_IS_ID( el, KaxCues ) )
605     {
606         msg_Dbg( &sys.demuxer, "|   + Cues" );
607         if( i_cues_position < 0 )
608             LoadCues( static_cast<KaxCues*>( el ) );
609         i_cues_position = i_element_position;
610     }
611     else if( MKV_IS_ID( el, KaxAttachments ) )
612     {
613         msg_Dbg( &sys.demuxer, "|   + Attachments" );
614         if( i_attachments_position < 0 )
615             ParseAttachments( static_cast<KaxAttachments*>( el ) );
616         i_attachments_position = i_element_position;
617     }
618     else if( MKV_IS_ID( el, KaxChapters ) )
619     {
620         msg_Dbg( &sys.demuxer, "|   + Chapters" );
621         if( i_chapters_position < 0 )
622             ParseChapters( static_cast<KaxChapters*>( el ) );
623         i_chapters_position = i_element_position;
624     }
625     else if( MKV_IS_ID( el, KaxTags ) )
626     {
627         msg_Dbg( &sys.demuxer, "|   + Tags" );
628         if( i_tags_position < 0 )
629             LoadTags( static_cast<KaxTags*>( el ) );
630         i_tags_position = i_element_position;
631     }
632     else
633     {
634         msg_Dbg( &sys.demuxer, "|   + LoadSeekHeadItem Unknown (%s)", typeid(*el).name() );
635     }
636     delete el;
637
638     es.I_O().setFilePointer( i_sav_position, seek_beginning );
639     return true;
640 }
641
642 void matroska_segment_c::Seek( mtime_t i_date, mtime_t i_time_offset, int64_t i_global_position )
643 {
644     KaxBlock    *block;
645     KaxSimpleBlock *simpleblock;
646     int         i_track_skipping;
647     int64_t     i_block_duration;
648     size_t      i_track;
649     int64_t     i_seek_position = i_start_pos;
650     int64_t     i_seek_time = i_start_time;
651
652     if( i_global_position >= 0 )
653     {
654         /* Special case for seeking in files with no cues */
655         EbmlElement *el = NULL;
656         es.I_O().setFilePointer( i_start_pos, seek_beginning );
657         delete ep;
658         ep = new EbmlParser( &es, segment, &sys.demuxer );
659         cluster = NULL;
660
661         while( ( el = ep->Get() ) != NULL )
662         {
663             if( MKV_IS_ID( el, KaxCluster ) )
664             {
665                 cluster = (KaxCluster *)el;
666                 i_cluster_pos = cluster->GetElementPosition();
667                 if( i_index == 0 ||
668                         ( i_index > 0 && p_indexes[i_index - 1].i_position < (int64_t)cluster->GetElementPosition() ) )
669                 {
670                     IndexAppendCluster( cluster );
671                 }
672                 if( es.I_O().getFilePointer() >= i_global_position )
673                 {
674                     ParseCluster();
675                     msg_Dbg( &sys.demuxer, "we found a cluster that is in the neighbourhood" );
676                     return;
677                 }
678             }
679         }
680         msg_Err( &sys.demuxer, "This file has no cues, and we were unable to seek to the requested position by parsing." );
681         return;
682     }
683
684     if ( i_index > 0 )
685     {
686         int i_idx = 0;
687
688         for( ; i_idx < i_index; i_idx++ )
689         {
690             if( p_indexes[i_idx].i_time + i_time_offset > i_date )
691             {
692                 break;
693             }
694         }
695
696         if( i_idx > 0 )
697         {
698             i_idx--;
699         }
700
701         i_seek_position = p_indexes[i_idx].i_position;
702         i_seek_time = p_indexes[i_idx].i_time;
703     }
704
705     msg_Dbg( &sys.demuxer, "seek got %"PRId64" (%d%%)",
706                 i_seek_time, (int)( 100 * i_seek_position / stream_Size( sys.demuxer.s ) ) );
707
708     es.I_O().setFilePointer( i_seek_position, seek_beginning );
709
710     delete ep;
711     ep = new EbmlParser( &es, segment, &sys.demuxer );
712     cluster = NULL;
713
714     sys.i_start_pts = i_date;
715
716     /* now parse until key frame */
717     i_track_skipping = 0;
718     for( i_track = 0; i_track < tracks.size(); i_track++ )
719     {
720         if( tracks[i_track]->fmt.i_cat == VIDEO_ES )
721         {
722             tracks[i_track]->b_search_keyframe = true;
723             i_track_skipping++;
724         }
725     }
726     es_out_Control( sys.demuxer.out, ES_OUT_SET_NEXT_DISPLAY_TIME, i_date );
727
728     while( i_track_skipping > 0 )
729     {
730         bool b_key_picture;
731         bool b_discardable_picture;
732         if( BlockGet( block, simpleblock, &b_key_picture, &b_discardable_picture, &i_block_duration ) )
733         {
734             msg_Warn( &sys.demuxer, "cannot get block EOF?" );
735
736             return;
737         }
738
739         for( i_track = 0; i_track < tracks.size(); i_track++ )
740         {
741             if( (simpleblock && tracks[i_track]->i_number == simpleblock->TrackNum()) ||
742                 (block && tracks[i_track]->i_number == block->TrackNum()) )
743             {
744                 break;
745             }
746         }
747
748         if( simpleblock )
749             sys.i_pts = (sys.i_chapter_time + simpleblock->GlobalTimecode()) / (mtime_t) 1000;
750         else
751             sys.i_pts = (sys.i_chapter_time + block->GlobalTimecode()) / (mtime_t) 1000;
752
753         if( i_track < tracks.size() )
754         {
755             if( sys.i_pts > sys.i_start_pts )
756             {
757                 cluster = static_cast<KaxCluster*>(ep->UnGet( i_block_pos, i_cluster_pos ));
758                 i_track_skipping = 0;
759             }
760             else if( tracks[i_track]->fmt.i_cat == VIDEO_ES )
761             {
762                 if( b_key_picture && tracks[i_track]->b_search_keyframe )
763                 {
764                     tracks[i_track]->b_search_keyframe = false;
765                     i_track_skipping--;
766                 }
767                 if( !tracks[i_track]->b_search_keyframe )
768                 {
769                     BlockDecode( &sys.demuxer, block, simpleblock, sys.i_pts, 0, b_key_picture || b_discardable_picture );
770                 }
771             }
772         }
773
774         delete block;
775     }
776
777     /* FIXME current ES_OUT_SET_NEXT_DISPLAY_TIME does not work that well if
778      * the delay is too high. */
779     if( sys.i_pts + 500*1000 < sys.i_start_pts )
780     {
781         sys.i_start_pts = sys.i_pts;
782
783         es_out_Control( sys.demuxer.out, ES_OUT_SET_NEXT_DISPLAY_TIME, sys.i_start_pts );
784     }
785 }
786
787 int matroska_segment_c::BlockFindTrackIndex( size_t *pi_track,
788                                              const KaxBlock *p_block, const KaxSimpleBlock *p_simpleblock )
789 {
790     size_t i_track;
791     for( i_track = 0; i_track < tracks.size(); i_track++ )
792     {
793         const mkv_track_t *tk = tracks[i_track];
794
795         if( ( p_block != NULL && tk->i_number == p_block->TrackNum() ) ||
796             ( p_simpleblock != NULL && tk->i_number == p_simpleblock->TrackNum() ) )
797         {
798             break;
799         }
800     }
801
802     if( i_track >= tracks.size() )
803         return VLC_EGENERIC;
804
805     if( pi_track )
806         *pi_track = i_track;
807     return VLC_SUCCESS;
808 }
809
810 static inline void fill_extra_data( mkv_track_t *p_tk, unsigned int offset )
811 {
812     if(p_tk->i_extra_data <= offset) return;
813     p_tk->fmt.i_extra = p_tk->i_extra_data - offset;
814     p_tk->fmt.p_extra = xmalloc( p_tk->fmt.i_extra );
815     if(!p_tk->fmt.p_extra) { p_tk->fmt.i_extra = 0; return; };
816     memcpy( p_tk->fmt.p_extra, p_tk->p_extra_data + offset, p_tk->fmt.i_extra );
817 }
818
819 bool matroska_segment_c::Select( mtime_t i_start_time )
820 {
821     /* add all es */
822     msg_Dbg( &sys.demuxer, "found %d es", (int)tracks.size() );
823     sys.b_pci_packet_set = false;
824
825     for( size_t i_track = 0; i_track < tracks.size(); i_track++ )
826     {
827         mkv_track_t *p_tk = tracks[i_track];
828         es_format_t *p_fmt = &p_tk->fmt;
829
830         if( p_fmt->i_cat == UNKNOWN_ES || !p_tk->psz_codec )
831         {
832             msg_Warn( &sys.demuxer, "invalid track[%d, n=%d]", (int)i_track, p_tk->i_number );
833             p_tk->p_es = NULL;
834             continue;
835         }
836
837         if( !strcmp( p_tk->psz_codec, "V_MS/VFW/FOURCC" ) )
838         {
839             if( p_tk->i_extra_data < (int)sizeof( BITMAPINFOHEADER ) )
840             {
841                 msg_Err( &sys.demuxer, "missing/invalid BITMAPINFOHEADER" );
842                 p_tk->fmt.i_codec = VLC_FOURCC( 'u', 'n', 'd', 'f' );
843             }
844             else
845             {
846                 BITMAPINFOHEADER *p_bih = (BITMAPINFOHEADER*)p_tk->p_extra_data;
847
848                 p_tk->fmt.video.i_width = GetDWLE( &p_bih->biWidth );
849                 p_tk->fmt.video.i_height= GetDWLE( &p_bih->biHeight );
850                 p_tk->fmt.i_codec       = GetFOURCC( &p_bih->biCompression );
851
852                 p_tk->fmt.i_extra       = GetDWLE( &p_bih->biSize ) - sizeof( BITMAPINFOHEADER );
853                 if( p_tk->fmt.i_extra > 0 )
854                 {
855                     p_tk->fmt.p_extra = xmalloc( p_tk->fmt.i_extra );
856                     memcpy( p_tk->fmt.p_extra, &p_bih[1], p_tk->fmt.i_extra );
857                 }
858             }
859             p_tk->b_dts_only = true;
860         }
861         else if( !strcmp( p_tk->psz_codec, "V_MPEG1" ) ||
862                  !strcmp( p_tk->psz_codec, "V_MPEG2" ) )
863         {
864             p_tk->fmt.i_codec = VLC_CODEC_MPGV;
865             if( p_tk->i_extra_data )
866                 fill_extra_data( p_tk, 0 );
867         }
868         else if( !strncmp( p_tk->psz_codec, "V_THEORA", 8 ) )
869         {
870             p_tk->fmt.i_codec = VLC_CODEC_THEORA;
871             fill_extra_data( p_tk, 0 );
872             p_tk->b_pts_only = true;
873         }
874         else if( !strncmp( p_tk->psz_codec, "V_REAL/RV", 9 ) )
875         {
876             uint8_t *p = p_tk->p_extra_data;
877
878             if( !strcmp( p_tk->psz_codec, "V_REAL/RV10" ) )
879                 p_fmt->i_codec = VLC_CODEC_RV10;
880             else if( !strcmp( p_tk->psz_codec, "V_REAL/RV20" ) )
881                 p_fmt->i_codec = VLC_CODEC_RV20;
882             else if( !strcmp( p_tk->psz_codec, "V_REAL/RV30" ) )
883                 p_fmt->i_codec = VLC_CODEC_RV30;
884             else if( !strcmp( p_tk->psz_codec, "V_REAL/RV40" ) )
885                 p_fmt->i_codec = VLC_CODEC_RV40;
886
887             /* Extract the framerate from the header */
888             if( p_tk->i_extra_data >= 26 &&
889                 p[4] == 'V' && p[5] == 'I' && p[6] == 'D' && p[7] == 'O' &&
890                 p[8] == 'R' && p[9] == 'V' &&
891                 (p[10] == '3' || p[10] == '4') && p[11] == '0' )
892             {
893                 p_tk->fmt.video.i_frame_rate = 
894                     p[22] << 24 | p[23] << 16 | p[24] << 8 | p[25] << 0;
895                 p_tk->fmt.video.i_frame_rate_base = 65536;
896             }
897
898             fill_extra_data( p_tk, 26 );
899             p_tk->b_dts_only = true;
900         }
901         else if( !strncmp( p_tk->psz_codec, "V_DIRAC", 7 ) )
902         {
903             p_tk->fmt.i_codec = VLC_CODEC_DIRAC;
904         }
905         else if( !strncmp( p_tk->psz_codec, "V_VP8", 5 ) )
906         {
907             p_tk->fmt.i_codec = VLC_CODEC_VP8;
908             p_tk->b_pts_only = true;
909         }
910         else if( !strncmp( p_tk->psz_codec, "V_MPEG4", 7 ) )
911         {
912             if( !strcmp( p_tk->psz_codec, "V_MPEG4/MS/V3" ) )
913             {
914                 p_tk->fmt.i_codec = VLC_CODEC_DIV3;
915             }
916             else if( !strncmp( p_tk->psz_codec, "V_MPEG4/ISO", 11 ) )
917             {
918                 /* A MPEG 4 codec, SP, ASP, AP or AVC */
919                 if( !strcmp( p_tk->psz_codec, "V_MPEG4/ISO/AVC" ) )
920                     p_tk->fmt.i_codec = VLC_FOURCC( 'a', 'v', 'c', '1' );
921                 else
922                     p_tk->fmt.i_codec = VLC_CODEC_MP4V;
923                 fill_extra_data( p_tk, 0 );
924             }
925         }
926         else if( !strcmp( p_tk->psz_codec, "V_QUICKTIME" ) )
927         {
928             MP4_Box_t *p_box = (MP4_Box_t*)xmalloc( sizeof( MP4_Box_t ) );
929             stream_t *p_mp4_stream = stream_MemoryNew( VLC_OBJECT(&sys.demuxer),
930                                                        p_tk->p_extra_data,
931                                                        p_tk->i_extra_data,
932                                                        true );
933             if( MP4_ReadBoxCommon( p_mp4_stream, p_box ) &&
934                 MP4_ReadBox_sample_vide( p_mp4_stream, p_box ) )
935             {
936                 p_tk->fmt.i_codec = p_box->i_type;
937                 p_tk->fmt.video.i_width = p_box->data.p_sample_vide->i_width;
938                 p_tk->fmt.video.i_height = p_box->data.p_sample_vide->i_height;
939                 p_tk->fmt.i_extra = p_box->data.p_sample_vide->i_qt_image_description;
940                 p_tk->fmt.p_extra = xmalloc( p_tk->fmt.i_extra );
941                 memcpy( p_tk->fmt.p_extra, p_box->data.p_sample_vide->p_qt_image_description, p_tk->fmt.i_extra );
942                 MP4_FreeBox_sample_vide( p_box );
943             }
944             else
945             {
946                 free( p_box );
947             }
948             stream_Delete( p_mp4_stream );
949         }
950         else if( !strcmp( p_tk->psz_codec, "V_MJPEG" ) )
951         {
952             p_tk->fmt.i_codec = VLC_CODEC_MJPG;
953         }
954         else if( !strcmp( p_tk->psz_codec, "A_MS/ACM" ) )
955         {
956             if( p_tk->i_extra_data < (int)sizeof( WAVEFORMATEX ) )
957             {
958                 msg_Err( &sys.demuxer, "missing/invalid WAVEFORMATEX" );
959                 p_tk->fmt.i_codec = VLC_FOURCC( 'u', 'n', 'd', 'f' );
960             }
961             else
962             {
963                 WAVEFORMATEX *p_wf = (WAVEFORMATEX*)p_tk->p_extra_data;
964
965                 wf_tag_to_fourcc( GetWLE( &p_wf->wFormatTag ), &p_tk->fmt.i_codec, NULL );
966
967                 p_tk->fmt.audio.i_channels   = GetWLE( &p_wf->nChannels );
968                 p_tk->fmt.audio.i_rate = GetDWLE( &p_wf->nSamplesPerSec );
969                 p_tk->fmt.i_bitrate    = GetDWLE( &p_wf->nAvgBytesPerSec ) * 8;
970                 p_tk->fmt.audio.i_blockalign = GetWLE( &p_wf->nBlockAlign );;
971                 p_tk->fmt.audio.i_bitspersample = GetWLE( &p_wf->wBitsPerSample );
972
973                 p_tk->fmt.i_extra            = GetWLE( &p_wf->cbSize );
974                 if( p_tk->fmt.i_extra > 0 )
975                 {
976                     p_tk->fmt.p_extra = xmalloc( p_tk->fmt.i_extra );
977                     memcpy( p_tk->fmt.p_extra, &p_wf[1], p_tk->fmt.i_extra );
978                 }
979             }
980         }
981         else if( !strcmp( p_tk->psz_codec, "A_MPEG/L3" ) ||
982                  !strcmp( p_tk->psz_codec, "A_MPEG/L2" ) ||
983                  !strcmp( p_tk->psz_codec, "A_MPEG/L1" ) )
984         {
985             p_tk->fmt.i_codec = VLC_CODEC_MPGA;
986         }
987         else if( !strcmp( p_tk->psz_codec, "A_AC3" ) )
988         {
989             p_tk->fmt.i_codec = VLC_CODEC_A52;
990         }
991         else if( !strcmp( p_tk->psz_codec, "A_EAC3" ) )
992         {
993             p_tk->fmt.i_codec = VLC_CODEC_EAC3;
994         }
995         else if( !strcmp( p_tk->psz_codec, "A_DTS" ) )
996         {
997             p_tk->fmt.i_codec = VLC_CODEC_DTS;
998         }
999         else if( !strcmp( p_tk->psz_codec, "A_MLP" ) )
1000         {
1001             p_tk->fmt.i_codec = VLC_CODEC_MLP;
1002         }
1003         else if( !strcmp( p_tk->psz_codec, "A_TRUEHD" ) )
1004         {
1005             /* FIXME when more samples arrive */
1006             p_tk->fmt.i_codec = VLC_CODEC_TRUEHD;
1007             p_fmt->b_packetized = false;
1008         }
1009         else if( !strcmp( p_tk->psz_codec, "A_FLAC" ) )
1010         {
1011             p_tk->fmt.i_codec = VLC_CODEC_FLAC;
1012             fill_extra_data( p_tk, 0 );
1013         }
1014         else if( !strcmp( p_tk->psz_codec, "A_VORBIS" ) )
1015         {
1016             p_tk->fmt.i_codec = VLC_CODEC_VORBIS;
1017             fill_extra_data( p_tk, 0 );
1018         }
1019         else if( !strncmp( p_tk->psz_codec, "A_AAC/MPEG2/", strlen( "A_AAC/MPEG2/" ) ) ||
1020                  !strncmp( p_tk->psz_codec, "A_AAC/MPEG4/", strlen( "A_AAC/MPEG4/" ) ) )
1021         {
1022             int i_profile, i_srate, sbr = 0;
1023             static const unsigned int i_sample_rates[] =
1024             {
1025                     96000, 88200, 64000, 48000, 44100, 32000, 24000, 22050,
1026                     16000, 12000, 11025,  8000,  7350,     0,     0,     0
1027             };
1028
1029             p_tk->fmt.i_codec = VLC_CODEC_MP4A;
1030             /* create data for faad (MP4DecSpecificDescrTag)*/
1031
1032             if( !strcmp( &p_tk->psz_codec[12], "MAIN" ) )
1033             {
1034                 i_profile = 0;
1035             }
1036             else if( !strcmp( &p_tk->psz_codec[12], "LC" ) )
1037             {
1038                 i_profile = 1;
1039             }
1040             else if( !strcmp( &p_tk->psz_codec[12], "SSR" ) )
1041             {
1042                 i_profile = 2;
1043             }
1044             else if( !strcmp( &p_tk->psz_codec[12], "LC/SBR" ) )
1045             {
1046                 i_profile = 1;
1047                 sbr = 1;
1048             }
1049             else
1050             {
1051                 i_profile = 3;
1052             }
1053
1054             for( i_srate = 0; i_srate < 13; i_srate++ )
1055             {
1056                 if( i_sample_rates[i_srate] == p_tk->i_original_rate )
1057                 {
1058                     break;
1059                 }
1060             }
1061             msg_Dbg( &sys.demuxer, "profile=%d srate=%d", i_profile, i_srate );
1062
1063             p_tk->fmt.i_extra = sbr ? 5 : 2;
1064             p_tk->fmt.p_extra = xmalloc( p_tk->fmt.i_extra );
1065             ((uint8_t*)p_tk->fmt.p_extra)[0] = ((i_profile + 1) << 3) | ((i_srate&0xe) >> 1);
1066             ((uint8_t*)p_tk->fmt.p_extra)[1] = ((i_srate & 0x1) << 7) | (p_tk->fmt.audio.i_channels << 3);
1067             if (sbr != 0)
1068             {
1069                 int syncExtensionType = 0x2B7;
1070                 int iDSRI;
1071                 for (iDSRI=0; iDSRI<13; iDSRI++)
1072                     if( i_sample_rates[iDSRI] == p_tk->fmt.audio.i_rate )
1073                         break;
1074                 ((uint8_t*)p_tk->fmt.p_extra)[2] = (syncExtensionType >> 3) & 0xFF;
1075                 ((uint8_t*)p_tk->fmt.p_extra)[3] = ((syncExtensionType & 0x7) << 5) | 5;
1076                 ((uint8_t*)p_tk->fmt.p_extra)[4] = ((1 & 0x1) << 7) | (iDSRI << 3);
1077             }
1078         }
1079         else if( !strcmp( p_tk->psz_codec, "A_AAC" ) )
1080         {
1081             p_tk->fmt.i_codec = VLC_CODEC_MP4A;
1082             fill_extra_data( p_tk, 0 );
1083         }
1084         else if( !strcmp( p_tk->psz_codec, "A_WAVPACK4" ) )
1085         {
1086             p_tk->fmt.i_codec = VLC_CODEC_WAVPACK;
1087             fill_extra_data( p_tk, 0 );
1088         }
1089         else if( !strcmp( p_tk->psz_codec, "A_TTA1" ) )
1090         {
1091             p_fmt->i_codec = VLC_CODEC_TTA;
1092             if( p_tk->i_extra_data > 0 )
1093             {
1094               fill_extra_data( p_tk, 0 );
1095             }
1096             else
1097             {
1098                 p_fmt->i_extra = 30;
1099                 p_fmt->p_extra = xmalloc( p_fmt->i_extra );
1100                 uint8_t *p_extra = (uint8_t*)p_fmt->p_extra;
1101                 memcpy( &p_extra[ 0], "TTA1", 4 );
1102                 SetWLE( &p_extra[ 4], 1 );
1103                 SetWLE( &p_extra[ 6], p_fmt->audio.i_channels );
1104                 SetWLE( &p_extra[ 8], p_fmt->audio.i_bitspersample );
1105                 SetDWLE( &p_extra[10], p_fmt->audio.i_rate );
1106                 SetDWLE( &p_extra[14], 0xffffffff );
1107                 memset( &p_extra[18], 0, 30  - 18 );
1108             }
1109         }
1110         else if( !strcmp( p_tk->psz_codec, "A_PCM/INT/BIG" ) ||
1111                  !strcmp( p_tk->psz_codec, "A_PCM/INT/LIT" ) ||
1112                  !strcmp( p_tk->psz_codec, "A_PCM/FLOAT/IEEE" ) )
1113         {
1114             if( !strcmp( p_tk->psz_codec, "A_PCM/INT/BIG" ) )
1115             {
1116                 p_tk->fmt.i_codec = VLC_FOURCC( 't', 'w', 'o', 's' );
1117             }
1118             else
1119             {
1120                 p_tk->fmt.i_codec = VLC_FOURCC( 'a', 'r', 'a', 'w' );
1121             }
1122             p_tk->fmt.audio.i_blockalign = ( p_tk->fmt.audio.i_bitspersample + 7 ) / 8 * p_tk->fmt.audio.i_channels;
1123         }
1124         else if( !strncmp( p_tk->psz_codec, "A_REAL/", 7 ) )
1125         {
1126             if( !strcmp( p_tk->psz_codec, "A_REAL/COOK" ) )
1127                 p_tk->fmt.i_codec = VLC_CODEC_COOK;
1128             else if( !strcmp( p_tk->psz_codec, "A_REAL/ATRC" ) )
1129                 p_tk->fmt.i_codec = VLC_CODEC_ATRAC3;
1130             else if( !strcmp( p_tk->psz_codec, "A_REAL/28_8" ) )
1131                 p_tk->fmt.i_codec = VLC_CODEC_RA_288;
1132             /* FIXME 14_4, RALF and SIPR */
1133             fill_extra_data( p_tk, p_tk->fmt.i_codec == VLC_CODEC_RA_288 ? 0 : 0 /*78 - FIXME need to implement reading support for cook */ );
1134         }
1135         else if( !strcmp( p_tk->psz_codec, "A_REAL/14_4" ) )
1136         {
1137             p_fmt->i_codec = VLC_CODEC_RA_144;
1138             p_fmt->audio.i_channels = 1;
1139             p_fmt->audio.i_rate = 8000;
1140             p_fmt->audio.i_blockalign = 0x14;
1141         }
1142         /* disabled due to the potential "S_KATE" namespace issue */
1143         else if( !strcmp( p_tk->psz_codec, "S_KATE" ) )
1144         {
1145             int i, i_offset = 1, i_extra, num_headers, size_so_far;
1146             uint8_t *p_extra;
1147
1148             p_tk->fmt.i_codec = VLC_CODEC_KATE;
1149             p_tk->fmt.subs.psz_encoding = strdup( "UTF-8" );
1150
1151             fill_extra_data( p_tk, 0 );
1152         }
1153         else if( !strcmp( p_tk->psz_codec, "S_TEXT/ASCII" ) )
1154         {
1155             p_fmt->i_codec = VLC_CODEC_SUBT;
1156             p_fmt->subs.psz_encoding = NULL; /* Is there a place where it is stored ? */
1157         }
1158         else if( !strcmp( p_tk->psz_codec, "S_TEXT/UTF8" ) )
1159         {
1160             p_tk->fmt.i_codec = VLC_CODEC_SUBT;
1161             p_tk->fmt.subs.psz_encoding = strdup( "UTF-8" );
1162         }
1163         else if( !strcmp( p_tk->psz_codec, "S_TEXT/USF" ) )
1164         {
1165             p_tk->fmt.i_codec = VLC_FOURCC( 'u', 's', 'f', ' ' );
1166             p_tk->fmt.subs.psz_encoding = strdup( "UTF-8" );
1167             if( p_tk->i_extra_data )
1168                 fill_extra_data( p_tk, 0 );
1169         }
1170         else if( !strcmp( p_tk->psz_codec, "S_TEXT/SSA" ) ||
1171                  !strcmp( p_tk->psz_codec, "S_TEXT/ASS" ) ||
1172                  !strcmp( p_tk->psz_codec, "S_SSA" ) ||
1173                  !strcmp( p_tk->psz_codec, "S_ASS" ))
1174         {
1175             p_tk->fmt.i_codec = VLC_CODEC_SSA;
1176             p_tk->fmt.subs.psz_encoding = strdup( "UTF-8" );
1177             if( p_tk->i_extra_data )
1178                 fill_extra_data( p_tk, 0 );
1179         }
1180         else if( !strcmp( p_tk->psz_codec, "S_VOBSUB" ) )
1181         {
1182             p_tk->fmt.i_codec = VLC_CODEC_SPU;
1183             if( p_tk->i_extra_data )
1184             {
1185                 char *psz_start;
1186                 char *psz_buf = (char *)malloc( p_tk->i_extra_data + 1);
1187                 if( psz_buf != NULL )
1188                 {
1189                     memcpy( psz_buf, p_tk->p_extra_data , p_tk->i_extra_data );
1190                     psz_buf[p_tk->i_extra_data] = '\0';
1191
1192                     psz_start = strstr( psz_buf, "size:" );
1193                     if( psz_start &&
1194                         vobsub_size_parse( psz_start,
1195                                            &p_tk->fmt.subs.spu.i_original_frame_width,
1196                                            &p_tk->fmt.subs.spu.i_original_frame_height ) == VLC_SUCCESS )
1197                     {
1198                         msg_Dbg( &sys.demuxer, "original frame size vobsubs: %dx%d",
1199                                  p_tk->fmt.subs.spu.i_original_frame_width,
1200                                  p_tk->fmt.subs.spu.i_original_frame_height );
1201                     }
1202                     else
1203                     {
1204                         msg_Warn( &sys.demuxer, "reading original frame size for vobsub failed" );
1205                     }
1206
1207                     psz_start = strstr( psz_buf, "palette:" );
1208                     if( psz_start &&
1209                         vobsub_palette_parse( psz_start, &p_tk->fmt.subs.spu.palette[1] ) == VLC_SUCCESS )
1210                     {
1211                         p_tk->fmt.subs.spu.palette[0] =  0xBeef;
1212                         msg_Dbg( &sys.demuxer, "vobsub palette read" );
1213                     }
1214                     else
1215                     {
1216                         msg_Warn( &sys.demuxer, "reading original palette failed" );
1217                     }
1218                     free( psz_buf );
1219                 }
1220             }
1221         }
1222         else if( !strcmp( p_tk->psz_codec, "S_HDMV/PGS" ) )
1223         {
1224             p_tk->fmt.i_codec = VLC_CODEC_BD_PG;
1225         }
1226         else if( !strcmp( p_tk->psz_codec, "B_VOBBTN" ) )
1227         {
1228             p_tk->fmt.i_cat = NAV_ES;
1229             continue;
1230         }
1231         else
1232         {
1233             msg_Err( &sys.demuxer, "unknown codec id=`%s'", p_tk->psz_codec );
1234             p_tk->fmt.i_codec = VLC_FOURCC( 'u', 'n', 'd', 'f' );
1235         }
1236         if( p_tk->b_default )
1237         {
1238             p_tk->fmt.i_priority = 1000;
1239         }
1240
1241         p_tk->p_es = es_out_Add( sys.demuxer.out, &p_tk->fmt );
1242
1243         /* Turn on a subtitles track if it has been flagged as default -
1244          * but only do this if no subtitles track has already been engaged,
1245          * either by an earlier 'default track' (??) or by default
1246          * language choice behaviour.
1247          */
1248         if( p_tk->b_default )
1249         {
1250             es_out_Control( sys.demuxer.out,
1251                             ES_OUT_SET_ES_DEFAULT,
1252                             p_tk->p_es );
1253         }
1254     }
1255     es_out_Control( sys.demuxer.out, ES_OUT_SET_NEXT_DISPLAY_TIME, i_start_time );
1256
1257     sys.i_start_pts = i_start_time;
1258     // reset the stream reading to the first cluster of the segment used
1259     es.I_O().setFilePointer( i_start_pos );
1260
1261     delete ep;
1262     ep = new EbmlParser( &es, segment, &sys.demuxer );
1263
1264     return true;
1265 }
1266
1267 void matroska_segment_c::UnSelect( )
1268 {
1269     for( size_t i_track = 0; i_track < tracks.size(); i_track++ )
1270     {
1271         if ( tracks[i_track]->p_es != NULL )
1272         {
1273 //            es_format_Clean( &tracks[i_track]->fmt );
1274             es_out_Del( sys.demuxer.out, tracks[i_track]->p_es );
1275             tracks[i_track]->p_es = NULL;
1276         }
1277     }
1278     delete ep;
1279     ep = NULL;
1280 }
1281
1282 int matroska_segment_c::BlockGet( KaxBlock * & pp_block, KaxSimpleBlock * & pp_simpleblock, bool *pb_key_picture, bool *pb_discardable_picture, int64_t *pi_duration )
1283 {
1284     pp_simpleblock = NULL;
1285     pp_block = NULL;
1286
1287     *pb_key_picture         = true;
1288     *pb_discardable_picture = false;
1289
1290     for( ;; )
1291     {
1292         EbmlElement *el = NULL;
1293         int         i_level;
1294
1295         if ( ep == NULL )
1296             return VLC_EGENERIC;
1297
1298         if( pp_simpleblock != NULL || ((el = ep->Get()) == NULL && pp_block != NULL) )
1299         {
1300             /* Check blocks validity to protect againts broken files */
1301             if( BlockFindTrackIndex( NULL, pp_block , pp_simpleblock ) )
1302             {
1303                 delete pp_block;
1304                 pp_simpleblock = NULL;
1305                 pp_block = NULL;
1306                 continue;
1307             }
1308             if( pp_simpleblock != NULL )
1309             {
1310                 *pb_key_picture         = pp_simpleblock->IsKeyframe();
1311                 *pb_discardable_picture = pp_simpleblock->IsDiscardable();
1312             }
1313
1314             /* update the index */
1315 #define idx p_indexes[i_index - 1]
1316             if( i_index > 0 && idx.i_time == -1 )
1317             {
1318                 if ( pp_simpleblock != NULL )
1319                     idx.i_time        = pp_simpleblock->GlobalTimecode() / (mtime_t)1000;
1320                 else
1321                     idx.i_time        = (*pp_block).GlobalTimecode() / (mtime_t)1000;
1322                 idx.b_key         = *pb_key_picture;
1323             }
1324 #undef idx
1325             return VLC_SUCCESS;
1326         }
1327
1328         i_level = ep->GetLevel();
1329
1330         if( el == NULL )
1331         {
1332             if( i_level > 1 )
1333             {
1334                 ep->Up();
1335                 continue;
1336             }
1337             msg_Warn( &sys.demuxer, "EOF" );
1338             return VLC_EGENERIC;
1339         }
1340
1341         /* Verify that we are still inside our cluster
1342          * It can happens whith broken files and when seeking
1343          * without index */
1344         if( i_level > 1 )
1345         {
1346             if( cluster && !ep->IsTopPresent( cluster ) )
1347             {
1348                 msg_Warn( &sys.demuxer, "Unexpected escape from current cluster" );
1349                 cluster = NULL;
1350             }
1351             if( !cluster )
1352                 continue;
1353         }
1354
1355         /* do parsing */
1356         switch ( i_level )
1357         {
1358         case 1:
1359             if( MKV_IS_ID( el, KaxCluster ) )
1360             {
1361                 cluster = (KaxCluster*)el;
1362                 i_cluster_pos = cluster->GetElementPosition();
1363
1364                 /* add it to the index */
1365                 if( i_index == 0 ||
1366                     ( i_index > 0 && p_indexes[i_index - 1].i_position < (int64_t)cluster->GetElementPosition() ) )
1367                 {
1368                     IndexAppendCluster( cluster );
1369                 }
1370
1371                 // reset silent tracks
1372                 for (size_t i=0; i<tracks.size(); i++)
1373                 {
1374                     tracks[i]->b_silent = false;
1375                 }
1376
1377                 ep->Down();
1378             }
1379             else if( MKV_IS_ID( el, KaxCues ) )
1380             {
1381                 msg_Warn( &sys.demuxer, "find KaxCues FIXME" );
1382                 return VLC_EGENERIC;
1383             }
1384             else
1385             {
1386                 msg_Dbg( &sys.demuxer, "unknown (%s)", typeid( el ).name() );
1387             }
1388             break;
1389         case 2:
1390             if( MKV_IS_ID( el, KaxClusterTimecode ) )
1391             {
1392                 KaxClusterTimecode &ctc = *(KaxClusterTimecode*)el;
1393
1394                 ctc.ReadData( es.I_O(), SCOPE_ALL_DATA );
1395                 cluster->InitTimecode( uint64( ctc ), i_timescale );
1396             }
1397             else if( MKV_IS_ID( el, KaxClusterSilentTracks ) )
1398             {
1399                 ep->Down();
1400             }
1401             else if( MKV_IS_ID( el, KaxBlockGroup ) )
1402             {
1403                 i_block_pos = el->GetElementPosition();
1404                 ep->Down();
1405             }
1406             else if( MKV_IS_ID( el, KaxSimpleBlock ) )
1407             {
1408                 pp_simpleblock = (KaxSimpleBlock*)el;
1409
1410                 pp_simpleblock->ReadData( es.I_O() );
1411                 pp_simpleblock->SetParent( *cluster );
1412             }
1413             break;
1414         case 3:
1415             if( MKV_IS_ID( el, KaxBlock ) )
1416             {
1417                 pp_block = (KaxBlock*)el;
1418
1419                 pp_block->ReadData( es.I_O() );
1420                 pp_block->SetParent( *cluster );
1421
1422                 ep->Keep();
1423             }
1424             else if( MKV_IS_ID( el, KaxBlockDuration ) )
1425             {
1426                 KaxBlockDuration &dur = *(KaxBlockDuration*)el;
1427
1428                 dur.ReadData( es.I_O() );
1429                 *pi_duration = uint64( dur );
1430             }
1431             else if( MKV_IS_ID( el, KaxReferenceBlock ) )
1432             {
1433                 KaxReferenceBlock &ref = *(KaxReferenceBlock*)el;
1434
1435                 ref.ReadData( es.I_O() );
1436
1437                 if( *pb_key_picture )
1438                     *pb_key_picture = false;
1439                 else if( int64( ref ) > 0 )
1440                     *pb_discardable_picture = true;
1441             }
1442             else if( MKV_IS_ID( el, KaxClusterSilentTrackNumber ) )
1443             {
1444                 KaxClusterSilentTrackNumber &track_num = *(KaxClusterSilentTrackNumber*)el;
1445                 track_num.ReadData( es.I_O() );
1446                 // find the track
1447                 for (size_t i=0; i<tracks.size(); i++)
1448                 {
1449                     if ( tracks[i]->i_number == uint32(track_num))
1450                     {
1451                         tracks[i]->b_silent = true;
1452                         break;
1453                     }
1454                 }
1455             }
1456             break;
1457         default:
1458             msg_Err( &sys.demuxer, "invalid level = %d", i_level );
1459             return VLC_EGENERIC;
1460         }
1461     }
1462 }
1463