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