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