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