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