* mkv.cpp : begin of a matroska demuxer
[vlc.git] / modules / demux / mkv.cpp
1 /*****************************************************************************
2  * mkv.cpp : matroska demuxer
3  *****************************************************************************
4  * Copyright (C) 2001 VideoLAN
5  * $Id: mkv.cpp,v 1.1 2003/06/22 07:39:39 fenrir Exp $
6  *
7  * Authors: Laurent Aimar <fenrir@via.ecp.fr>
8  *
9  * This program is free software; you can redistribute it and/or modify
10  * it under the terms of the GNU General Public License as published by
11  * the Free Software Foundation; either version 2 of the License, or
12  * (at your option) any later version.
13  *
14  * This program is distributed in the hope that it will be useful,
15  * but WITHOUT ANY WARRANTY; without even the implied warranty of
16  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
17  * GNU General Public License for more details.
18  *
19  * You should have received a copy of the GNU General Public License
20  * along with this program; if not, write to the Free Software
21  * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111, USA.
22  *****************************************************************************/
23
24 /*****************************************************************************
25  * Preamble
26  *****************************************************************************/
27 #include <stdlib.h>                                      /* malloc(), free() */
28
29 #include <vlc/vlc.h>
30
31 #include <vlc/input.h>
32
33 #include <codecs.h>                        /* BITMAPINFOHEADER, WAVEFORMATEX */
34
35 #include <iostream>
36 #include <cassert>
37 #include <typeinfo>
38
39 /* libebml and matroska */
40 #include "ebml/EbmlHead.h"
41 #include "ebml/EbmlSubHead.h"
42 #include "ebml/EbmlStream.h"
43 #include "ebml/EbmlContexts.h"
44 #include "ebml/EbmlVersion.h"
45 #include "ebml/EbmlVoid.h"
46
47 #include "matroska/FileKax.h"
48 #include "matroska/KaxAttachements.h"
49 #include "matroska/KaxBlock.h"
50 #include "matroska/KaxBlockData.h"
51 #include "matroska/KaxChapters.h"
52 #include "matroska/KaxCluster.h"
53 #include "matroska/KaxClusterData.h"
54 #include "matroska/KaxContexts.h"
55 #include "matroska/KaxCues.h"
56 #include "matroska/KaxCuesData.h"
57 #include "matroska/KaxInfo.h"
58 #include "matroska/KaxInfoData.h"
59 #include "matroska/KaxSeekHead.h"
60 #include "matroska/KaxSegment.h"
61 #include "matroska/KaxTag.h"
62 #include "matroska/KaxTracks.h"
63 #include "matroska/KaxTrackAudio.h"
64 #include "matroska/KaxTrackVideo.h"
65
66 #include "ebml/StdIOCallback.h"
67
68 using namespace LIBMATROSKA_NAMESPACE;
69 using namespace std;
70
71
72 /*****************************************************************************
73  * Local prototypes
74  *****************************************************************************/
75 static int  Activate  ( vlc_object_t * );
76 static void Deactivate( vlc_object_t * );
77 static int  Demux     ( input_thread_t * );
78
79 /*****************************************************************************
80  * Module descriptor
81  *****************************************************************************/
82 vlc_module_begin();
83     set_description( _("mka/mkv stream demuxer" ) );
84     set_capability( "demux", 50 );
85     set_callbacks( Activate, Deactivate );
86     add_shortcut( "mka" );
87     add_shortcut( "mkv" );
88 vlc_module_end();
89
90
91 /*****************************************************************************
92  * Stream managment
93  *****************************************************************************/
94 class vlc_stream_io_callback: public IOCallback
95 {
96   private:
97     input_thread_t *p_input;
98
99   public:
100     vlc_stream_io_callback( input_thread_t * );
101
102     virtual uint32_t read            ( void *p_buffer, size_t i_size);
103     virtual void     setFilePointer  ( int64_t i_offset, seek_mode mode = seek_beginning );
104     virtual size_t   write           ( const void *p_buffer, size_t i_size);
105     virtual uint64_t getFilePointer  ( void );
106     virtual void     close           ( void );
107 };
108
109
110 vlc_stream_io_callback::vlc_stream_io_callback( input_thread_t *p_input_ )
111 {
112     p_input = p_input_;
113 }
114
115 uint32_t vlc_stream_io_callback::read( void *p_buffer, size_t i_size )
116 {
117     data_packet_t *p_data;
118
119     int i_count;
120     int i_read = 0;
121
122
123     if( !i_size )
124     {
125         return 0;
126     }
127
128     do
129     {
130         i_count = input_SplitBuffer(p_input, &p_data, __MIN( i_size, 10240 ) );
131         if( i_count <= 0 )
132         {
133             return i_read;
134         }
135         memcpy( p_buffer, p_data->p_payload_start, i_count );
136         input_DeletePacket( p_input->p_method_data, p_data );
137
138         (uint8_t*)p_buffer += i_count;
139         i_size            -= i_count;
140         i_read            += i_count;
141
142     } while( i_size );
143
144     return i_read;
145 }
146
147
148 void vlc_stream_io_callback::setFilePointer(int64_t i_offset, seek_mode mode )
149 {
150     int64_t i_pos;
151
152     vlc_mutex_lock( &p_input->stream.stream_lock );
153     switch( mode )
154     {
155         case seek_beginning:
156             i_pos = i_offset;
157             break;
158         case seek_end:
159             i_pos = p_input->stream.p_selected_area->i_size - i_offset;
160             break;
161         default:
162             i_pos= p_input->stream.p_selected_area->i_tell + i_offset;
163             break;
164     }
165     if( i_pos < 0 || i_pos > p_input->stream.p_selected_area->i_size )
166     {
167         msg_Err( p_input, "seeking to wrong place (i_pos=%lld)", i_pos );
168         vlc_mutex_unlock( &p_input->stream.stream_lock );
169         return;
170     }
171     vlc_mutex_unlock( &p_input->stream.stream_lock );
172
173     input_AccessReinit( p_input );
174     p_input->pf_seek( p_input, i_pos );
175 }
176
177 size_t vlc_stream_io_callback::write( const void *p_buffer, size_t i_size )
178 {
179     return 0;
180 }
181
182 uint64_t vlc_stream_io_callback::getFilePointer( void )
183 {
184     uint64_t i_pos;
185
186     vlc_mutex_lock( &p_input->stream.stream_lock );
187     i_pos= p_input->stream.p_selected_area->i_tell;
188     vlc_mutex_unlock( &p_input->stream.stream_lock );
189
190     return i_pos;
191 }
192
193 void vlc_stream_io_callback::close( void )
194 {
195     return;
196 }
197
198 /*****************************************************************************
199  * Ebml Stream parser
200  *****************************************************************************/
201 class EbmlParser
202 {
203     public:
204         EbmlParser( EbmlStream *es, EbmlElement *el_start );
205         ~EbmlParser( void );
206         void Up( void );
207         void Down( void );
208         EbmlElement *Get( void );
209         void        Keep( void );
210
211         int GetLevel( void );
212
213     private:
214
215     EbmlStream  *m_es;
216     int         mi_level;
217     EbmlElement *m_el[5];
218
219     EbmlElement *m_got;
220
221     int         mi_user_level;
222     vlc_bool_t  mb_keep;
223
224 };
225
226 EbmlParser::EbmlParser( EbmlStream *es, EbmlElement *el_start )
227 {
228     int i;
229
230     m_es = es;
231     m_got = NULL;
232     m_el[0] = el_start;
233
234     for( i = 1; i < 5; i++ )
235     {
236         m_el[i] = NULL;
237     }
238     mi_level = 1;
239     mi_user_level = 1;
240     mb_keep = VLC_FALSE;
241 }
242
243 EbmlParser::~EbmlParser( void )
244 {
245     int i;
246
247     for( i = 1; i < mi_level; i++ )
248     {
249         if( !mb_keep )
250         {
251             delete m_el[i];
252         }
253         mb_keep = VLC_FALSE;
254     }
255 }
256
257 void EbmlParser::Up( void )
258 {
259     if( mi_user_level == mi_level )
260     {
261         fprintf( stderr," arrrrrrrrrrrrrg Up cannot escape itself\n" );
262     }
263
264     mi_user_level--;
265 }
266
267 void EbmlParser::Down( void )
268 {
269     mi_user_level++;
270     mi_level++;
271 }
272
273 void EbmlParser::Keep( void )
274 {
275     mb_keep = VLC_TRUE;
276 }
277
278 int EbmlParser::GetLevel( void )
279 {
280     return mi_user_level;
281 }
282
283 EbmlElement *EbmlParser::Get( void )
284 {
285     int i_ulev = 0;
286
287     if( mi_user_level != mi_level )
288     {
289         return NULL;
290     }
291     if( m_got )
292     {
293         EbmlElement *ret = m_got;
294         m_got = NULL;
295
296         return ret;
297     }
298
299     if( m_el[mi_level] )
300     {
301         m_el[mi_level]->SkipData( *m_es, m_el[mi_level]->Generic().Context );
302         if( !mb_keep )
303         {
304             delete m_el[mi_level];
305         }
306         mb_keep = VLC_FALSE;
307     }
308
309     m_el[mi_level] = m_es->FindNextElement( m_el[mi_level - 1]->Generic().Context, i_ulev, 0xFFFFFFFFL, true, 1 );
310     if( i_ulev > 0 )
311     {
312         while( i_ulev > 0 )
313         {
314             if( mi_level == 1 )
315             {
316                 mi_level = 0;
317                 return NULL;
318             }
319
320             delete m_el[mi_level - 1];
321             m_got = m_el[mi_level -1] = m_el[mi_level];
322             m_el[mi_level] = NULL;
323
324             mi_level--;
325             i_ulev--;
326         }
327         return NULL;
328     }
329     else if( m_el[mi_level] == NULL )
330     {
331         fprintf( stderr," m_el[mi_level] == NULL\n" );
332     }
333
334     return m_el[mi_level];
335 }
336
337 /*****************************************************************************
338  * Some functions to manipulate memory
339  *****************************************************************************/
340 #define GetWLE( p )     __GetWLE( (uint8_t*)p )
341 #define GetDWLE( p )    __GetDWLE( (uint8_t*)p )
342 #define GetFOURCC( p )  __GetFOURCC( (uint8_t*)p )
343 static uint16_t __GetWLE( uint8_t *p )
344 {
345     return (uint16_t)p[0] | ( ((uint16_t)p[1]) << 8 );
346 }
347 static uint32_t __GetDWLE( uint8_t *p )
348 {
349     return (uint32_t)p[0] | ( ((uint32_t)p[1]) << 8 ) |
350             ( ((uint32_t)p[2]) << 16 ) | ( ((uint32_t)p[3]) << 24 );
351 }
352 static vlc_fourcc_t __GetFOURCC( uint8_t *p )
353 {
354     return VLC_FOURCC( p[0], p[1], p[2], p[3] );
355 }
356
357 /*****************************************************************************
358  * Definitions of structures and functions used by this plugins
359  *****************************************************************************/
360 typedef struct
361 {
362     int         i_cat;
363     vlc_bool_t  b_default;
364     int         i_number;
365
366     int         i_extra_data;
367     uint8_t     *p_extra_data;
368
369     char         *psz_language;
370
371     char         *psz_codec;
372     vlc_fourcc_t i_codec;
373
374     uint64_t     i_default_duration;
375     /* video */
376     int         i_width;
377     int         i_height;
378     int         i_display_width;
379     int         i_display_height;
380     float       f_fps;
381
382
383     /* audio */
384     int         i_channels;
385     int         i_samplerate;
386     int         i_bitspersample;
387
388     es_descriptor_t *p_es;
389
390
391
392     vlc_bool_t      b_inited;
393     /* data to be send first */
394     int             i_data_init;
395     uint8_t         *p_data_init;
396
397 } mkv_track_t;
398
399 struct demux_sys_t
400 {
401     vlc_stream_io_callback  *in;
402     EbmlStream              *es;
403     EbmlParser              *ep;
404
405     KaxSegment              *segment;
406     KaxCluster              *cluster;
407
408     uint64_t                tc_scale;
409     float                   f_duration;
410
411     int                     i_track;
412     mkv_track_t             *track;
413
414     mtime_t                 i_pcr;
415
416     mtime_t                 i_last_pts;
417
418     uint64_t                i_cluster_tc;
419 };
420
421 #define MKVD_TIMECODESCALE 1000000
422
423 /*****************************************************************************
424  * Activate: initializes matroska demux structures
425  *****************************************************************************/
426 static int Activate( vlc_object_t * p_this )
427 {
428     input_thread_t *p_input = (input_thread_t *)p_this;
429     demux_sys_t    *p_sys;
430     uint8_t        *p_peek;
431
432     int             i_track;
433     vlc_bool_t      b_audio_selected;
434     int             i_spu_channel, i_audio_channel;
435
436     EbmlElement     *el = NULL, *el1 = NULL, *el2 = NULL, *el3 = NULL, *el4 = NULL;
437
438     /* Initialize access plug-in structures. */
439     if( p_input->i_mtu == 0 )
440     {
441         /* Improve speed. */
442         p_input->i_bufsize = INPUT_DEFAULT_BUFSIZE;
443     }
444
445     /* Set the demux function */
446     p_input->pf_demux = Demux;
447
448     /* peek the begining */
449     if( input_Peek( p_input, &p_peek, 4 ) < 4 )
450     {
451         msg_Warn( p_input, "cannot peek" );
452         return VLC_EGENERIC;
453     }
454
455     /* is a valid file */
456     if( p_peek[0] != 0x1a || p_peek[1] != 0x45 || p_peek[2] != 0xdf || p_peek[3] != 0xa3 )
457     {
458         msg_Warn( p_input, "matroska module discarded (invalid header)" );
459         return VLC_EGENERIC;
460     }
461
462     if( p_input->stream.i_method != INPUT_METHOD_FILE || !p_input->stream.b_seekable )
463     {
464         msg_Err( p_input, "can only read matroska over seekable file yet" );
465         return VLC_EGENERIC;
466     }
467     /* FIXME FIXME FIXME */
468     p_input->stream.b_seekable = VLC_FALSE;
469     /* FIXME FIXME FIXME */
470
471
472     p_input->p_demux_data = p_sys = (demux_sys_t*)malloc( sizeof( demux_sys_t ) );
473     memset( p_sys, 0, sizeof( demux_sys_t ) );
474
475     p_sys->in = new vlc_stream_io_callback( p_input );
476     p_sys->es = new EbmlStream( *p_sys->in );
477     p_sys->f_duration   = -1;
478     p_sys->tc_scale     = MKVD_TIMECODESCALE;
479     p_sys->i_track      = 0;
480     p_sys->track        = (mkv_track_t*)malloc( sizeof( mkv_track_t ) );
481     p_sys->i_pcr        = 0;
482     p_sys->i_last_pts   = 0;
483
484     if( p_sys->es == NULL )
485     {
486         msg_Err( p_input, "failed to create EbmlStream" );
487         delete p_sys->in;
488         free( p_sys );
489         return VLC_EGENERIC;
490     }
491     /* Find the EbmlHead element */
492     el = p_sys->es->FindNextID(EbmlHead::ClassInfos, 0xFFFFFFFFL);
493     if( el == NULL )
494     {
495         msg_Err( p_input, "cannot find EbmlHead" );
496         goto error;
497     }
498     msg_Dbg( p_input, "EbmlHead" );
499     /* skip it */
500     el->SkipData( *p_sys->es, el->Generic().Context );
501     delete el;
502
503     /* Find a segment */
504     el = p_sys->es->FindNextID( KaxSegment::ClassInfos, 0xFFFFFFFFL);
505     if( el == NULL )
506     {
507         msg_Err( p_input, "cannot find KaxSegment" );
508         goto error;
509     }
510     msg_Dbg( p_input, "+ Segment" );
511     p_sys->segment = (KaxSegment*)el;
512     p_sys->cluster = NULL;
513
514     p_sys->ep = new EbmlParser( p_sys->es, el );
515
516     while( ( el1 = p_sys->ep->Get() ) != NULL )
517     {
518         if( EbmlId( *el1 ) == KaxInfo::ClassInfos.GlobalId )
519         {
520             msg_Dbg( p_input, "|   + Informations" );
521
522             p_sys->ep->Down();
523             while( ( el2 = p_sys->ep->Get() ) != NULL )
524             {
525                 if( EbmlId( *el2 ) == KaxTimecodeScale::ClassInfos.GlobalId )
526                 {
527                     KaxTimecodeScale &tcs = *(KaxTimecodeScale*)el2;
528
529                     tcs.ReadData( p_sys->es->I_O() );
530                     p_sys->tc_scale = uint64(tcs);
531
532                     msg_Dbg( p_input, "|   |   + TimecodeScale=%lld", p_sys->tc_scale );
533                 }
534                 else if( EbmlId( *el2 ) == KaxDuration::ClassInfos.GlobalId )
535                 {
536                     KaxDuration &dur = *(KaxDuration*)el2;
537
538                     dur.ReadData( p_sys->es->I_O() );
539                     p_sys->f_duration = float(dur);
540
541                     msg_Dbg( p_input, "|   |   + Duration=%f", p_sys->f_duration );
542                 }
543                 else
544                 {
545                     msg_Dbg( p_input, "|   |   + Unknow (%s)", typeid(*el2).name() );
546                 }
547             }
548             p_sys->ep->Up();
549         }
550         else if( EbmlId( *el1 ) == KaxTracks::ClassInfos.GlobalId )
551         {
552             msg_Dbg( p_input, "|   + Tracks" );
553
554             p_sys->ep->Down();
555             while( ( el2 = p_sys->ep->Get() ) != NULL )
556             {
557                 if( EbmlId( *el2 ) == KaxTrackEntry::ClassInfos.GlobalId )
558                 {
559                     msg_Dbg( p_input, "|   |   + Track Entry" );
560
561                     p_sys->i_track++;
562                     p_sys->track = (mkv_track_t*)realloc( p_sys->track, sizeof( mkv_track_t ) * (p_sys->i_track + 1 ) );
563 #define tk  p_sys->track[p_sys->i_track - 1]
564                     memset( &tk, 0, sizeof( mkv_track_t ) );
565                     tk.i_cat = UNKNOWN_ES;
566                     tk.b_default = VLC_FALSE;
567                     tk.i_number = p_sys->i_track - 1;
568                     tk.i_extra_data = 0;
569                     tk.p_extra_data = NULL;
570                     tk.i_codec = 0;
571                     tk.psz_codec = NULL;
572                     tk.psz_language = NULL;
573                     tk.i_default_duration = 0;
574
575                     tk.b_inited = VLC_FALSE;
576                     tk.i_data_init = 0;
577                     tk.p_data_init = NULL;
578
579                     p_sys->ep->Down();
580
581                     while( ( el3 = p_sys->ep->Get() ) != NULL )
582                     {
583                         if( EbmlId( *el3 ) == KaxTrackNumber::ClassInfos.GlobalId )
584                         {
585                             KaxTrackNumber &tnum = *(KaxTrackNumber*)el3;
586                             tnum.ReadData( p_sys->es->I_O() );
587
588                             tk.i_number = uint32( tnum );
589                             msg_Dbg( p_input, "|   |   |   + Track Number=%u", uint32( tnum ) );
590                         }
591                         else  if( EbmlId( *el3 ) == KaxTrackUID::ClassInfos.GlobalId )
592                         {
593                             KaxTrackUID &tuid = *(KaxTrackUID*)el3;
594                             tuid.ReadData( p_sys->es->I_O() );
595
596                             msg_Dbg( p_input, "|   |   |   + Track UID=%u", uint32( tuid ) );
597                         }
598                         else  if( EbmlId( *el3 ) == KaxTrackDefaultDuration::ClassInfos.GlobalId )
599                         {
600                             KaxTrackDefaultDuration &defd = *(KaxTrackDefaultDuration*)el3;
601                             defd.ReadData( p_sys->es->I_O() );
602
603                             tk.i_default_duration = uint64(defd);
604                             msg_Dbg( p_input, "|   |   |   + Track Default Duration=%lld", uint64(defd) );
605                         }
606                         else  if( EbmlId( *el3 ) == KaxTrackType::ClassInfos.GlobalId )
607                         {
608                             char *psz_type;
609                             KaxTrackType &ttype = *(KaxTrackType*)el3;
610                             ttype.ReadData( p_sys->es->I_O() );
611                             switch( uint8(ttype) )
612                             {
613                                 case track_audio:
614                                     psz_type = "audio";
615                                     tk.i_cat = AUDIO_ES;
616                                     break;
617                                 case track_video:
618                                     psz_type = "video";
619                                     tk.i_cat = VIDEO_ES;
620                                     break;
621                                 case track_subtitle:
622                                     psz_type = "subtitle";
623                                     tk.i_cat = SPU_ES;
624                                     break;
625                                 default:
626                                     psz_type = "unknown";
627                                     tk.i_cat = UNKNOWN_ES;
628                                     break;
629                             }
630
631                             msg_Dbg( p_input, "|   |   |   + Track Type=%s", psz_type );
632                         }
633                         else  if( EbmlId( *el3 ) == KaxTrackAudio::ClassInfos.GlobalId )
634                         {
635                             msg_Dbg( p_input, "|   |   |   + Track Audio" );
636                             tk.i_channels = 0;
637                             tk.i_samplerate = 0;
638                             tk.i_bitspersample = 0;
639
640                             p_sys->ep->Down();
641
642                             while( ( el4 = p_sys->ep->Get() ) != NULL )
643                             {
644                                 if( EbmlId( *el4 ) == KaxAudioSamplingFreq::ClassInfos.GlobalId )
645                                 {
646                                     KaxAudioSamplingFreq &afreq = *(KaxAudioSamplingFreq*)el4;
647                                     afreq.ReadData( p_sys->es->I_O() );
648
649                                     tk.i_samplerate = (int)float( afreq );
650                                     msg_Dbg( p_input, "|   |   |   |   + afreq=%d", tk.i_samplerate );
651                                 }
652                                 else if( EbmlId( *el4 ) == KaxAudioChannels::ClassInfos.GlobalId )
653                                 {
654                                     KaxAudioChannels &achan = *(KaxAudioChannels*)el4;
655                                     achan.ReadData( p_sys->es->I_O() );
656
657                                     tk.i_channels = uint8( achan );
658                                     msg_Dbg( p_input, "|   |   |   |   + achan=%u", uint8( achan ) );
659                                 }
660                                 else if( EbmlId( *el4 ) == KaxAudioBitDepth::ClassInfos.GlobalId )
661                                 {
662                                     KaxAudioBitDepth &abits = *(KaxAudioBitDepth*)el4;
663                                     abits.ReadData( p_sys->es->I_O() );
664
665                                     tk.i_bitspersample = uint8( abits );
666                                     msg_Dbg( p_input, "|   |   |   |   + abits=%u", uint8( abits ) );
667                                 }
668                                 else
669                                 {
670                                     msg_Dbg( p_input, "|   |   |   |   + Unknow (%s)", typeid(*el4).name() );
671                                 }
672                             }
673                             p_sys->ep->Up();
674                         }
675                         else  if( EbmlId( *el3 ) == KaxTrackVideo::ClassInfos.GlobalId )
676                         {
677                             msg_Dbg( p_input, "|   |   |   + Track Video" );
678                             tk.i_width  = 0;
679                             tk.i_height = 0;
680                             tk.i_display_width  = 0;
681                             tk.i_display_height = 0;
682                             tk.f_fps = 0.0;
683
684                             p_sys->ep->Down();
685
686                             while( ( el4 = p_sys->ep->Get() ) != NULL )
687                             {
688                                 if( EbmlId( *el4 ) == KaxVideoPixelWidth::ClassInfos.GlobalId )
689                                 {
690                                     KaxVideoPixelWidth &vwidth = *(KaxVideoPixelWidth*)el4;
691                                     vwidth.ReadData( p_sys->es->I_O() );
692
693                                     tk.i_width = uint16( vwidth );
694                                     msg_Dbg( p_input, "|   |   |   |   + width=%d", uint16( vwidth ) );
695                                 }
696                                 else if( EbmlId( *el4 ) == KaxVideoPixelHeight::ClassInfos.GlobalId )
697                                 {
698                                     KaxVideoPixelWidth &vheight = *(KaxVideoPixelWidth*)el4;
699                                     vheight.ReadData( p_sys->es->I_O() );
700
701                                     tk.i_height = uint16( vheight );
702                                     msg_Dbg( p_input, "|   |   |   |   + height=%d", uint16( vheight ) );
703                                 }
704                                 else if( EbmlId( *el4 ) == KaxVideoDisplayWidth::ClassInfos.GlobalId )
705                                 {
706                                     KaxVideoDisplayWidth &vwidth = *(KaxVideoDisplayWidth*)el4;
707                                     vwidth.ReadData( p_sys->es->I_O() );
708
709                                     tk.i_display_width = uint16( vwidth );
710                                     msg_Dbg( p_input, "|   |   |   |   + display width=%d", uint16( vwidth ) );
711                                 }
712                                 else if( EbmlId( *el4 ) == KaxVideoDisplayHeight::ClassInfos.GlobalId )
713                                 {
714                                     KaxVideoDisplayWidth &vheight = *(KaxVideoDisplayWidth*)el4;
715                                     vheight.ReadData( p_sys->es->I_O() );
716
717                                     tk.i_display_height = uint16( vheight );
718                                     msg_Dbg( p_input, "|   |   |   |   + display height=%d", uint16( vheight ) );
719                                 }
720                                 else if( EbmlId( *el4 ) == KaxVideoFrameRate::ClassInfos.GlobalId )
721                                 {
722                                     KaxVideoFrameRate &vfps = *(KaxVideoFrameRate*)el4;
723                                     vfps.ReadData( p_sys->es->I_O() );
724
725                                     tk.f_fps = float( vfps );
726                                     msg_Dbg( p_input, "   |   |   |   + fps=%f", float( vfps ) );
727                                 }
728                                 else
729                                 {
730                                     msg_Dbg( p_input, "|   |   |   |   + Unknow (%s)", typeid(*el4).name() );
731                                 }
732                             }
733                             p_sys->ep->Up();
734                         }
735                         else  if( EbmlId( *el3 ) == KaxCodecID::ClassInfos.GlobalId )
736                         {
737                             KaxCodecID &codecid = *(KaxCodecID*)el3;
738                             codecid.ReadData( p_sys->es->I_O() );
739
740                             tk.psz_codec = strdup( string( codecid ).c_str() );
741                             msg_Dbg( p_input, "|   |   |   + Track CodecId=%s", string( codecid ).c_str() );
742                         }
743                         else  if( EbmlId( *el3 ) == KaxCodecPrivate::ClassInfos.GlobalId )
744                         {
745                             KaxCodecPrivate &cpriv = *(KaxCodecPrivate*)el3;
746                             cpriv.ReadData( p_sys->es->I_O() );
747
748                             tk.i_extra_data = cpriv.GetSize();
749                             if( tk.i_extra_data > 0 )
750                             {
751                                 tk.p_extra_data = (uint8_t*)malloc( tk.i_extra_data );
752                                 memcpy( tk.p_extra_data, cpriv.GetBuffer(), tk.i_extra_data );
753                             }
754                             msg_Dbg( p_input, "|   |   |   + Track CodecPrivate size=%lld", cpriv.GetSize() );
755                         }
756                         else  if( EbmlId( *el3 ) == KaxTrackFlagDefault::ClassInfos.GlobalId )
757                         {
758                             KaxTrackFlagDefault &fdef = *(KaxTrackFlagDefault*)el3;
759                             fdef.ReadData( p_sys->es->I_O() );
760
761                             tk.b_default = uint32( fdef );
762                             msg_Dbg( p_input, "|   |   |   + Track Default=%u", uint32( fdef )  );
763                         }
764                         else  if( EbmlId( *el3 ) == KaxTrackLanguage::ClassInfos.GlobalId )
765                         {
766                             KaxTrackLanguage &lang = *(KaxTrackLanguage*)el3;
767
768                             lang.ReadData( p_sys->es->I_O() );
769
770                             tk.psz_language = strdup( string( lang ).c_str() );
771                             msg_Dbg( p_input, "|   |   |   + Track Language=`%s'", string( lang ).c_str() );
772                         }
773                         else  if( EbmlId( *el3 ) == KaxTrackFlagLacing::ClassInfos.GlobalId )
774                         {
775                             KaxTrackFlagLacing &lac = *(KaxTrackFlagLacing*)el3;
776                             lac.ReadData( p_sys->es->I_O() );
777
778                             msg_Dbg( p_input, "|   |   |   + Track Lacing=%d", uint32( lac ) );
779                         }
780                         else  if( EbmlId( *el3 ) == KaxTrackMinCache::ClassInfos.GlobalId )
781                         {
782                             KaxTrackMinCache &cmin = *(KaxTrackMinCache*)el3;
783                             cmin.ReadData( p_sys->es->I_O() );
784
785                             msg_Dbg( p_input, "|   |   |   + Track MinCache=%d", uint32( cmin ) );
786                         }
787                         else  if( EbmlId( *el3 ) == KaxTrackMaxCache::ClassInfos.GlobalId )
788                         {
789                             KaxTrackMaxCache &cmax = *(KaxTrackMaxCache*)el3;
790                             cmax.ReadData( p_sys->es->I_O() );
791
792                             msg_Dbg( p_input, "|   |   |   + Track MaxCache=%d", uint32( cmax ) );
793                         }
794                         else
795                         {
796                             msg_Dbg( p_input, "|   |   |   + Unknow (%s)", typeid(*el3).name() );
797                         }
798                     }
799                     p_sys->ep->Up();
800                 }
801                 else
802                 {
803                     msg_Dbg( p_input, "|   |   + Unknow (%s)", typeid(*el2).name() );
804                 }
805 #undef tk
806             }
807             p_sys->ep->Up();
808         }
809         else if( EbmlId( *el1 ) == KaxSeekHead::ClassInfos.GlobalId )
810         {
811             msg_Dbg( p_input, "|   + Seek head" );
812         }
813         else if( EbmlId( *el1 ) == KaxCues::ClassInfos.GlobalId )
814         {
815             msg_Dbg( p_input, "|   + Cues" );
816         }
817         else if( EbmlId( *el1 ) == KaxCluster::ClassInfos.GlobalId )
818         {
819             msg_Dbg( p_input, "|   + Cluster" );
820             p_sys->cluster = (KaxCluster*)el1;
821             p_sys->ep->Down();
822
823             /* stop parsing the stream */
824             break;
825         }
826         else if( EbmlId( *el1 ) == KaxAttachements::ClassInfos.GlobalId )
827         {
828             msg_Dbg( p_input, "|   + Attachements FIXME TODO (but probably never supported)" );
829         }
830         else if( EbmlId( *el1 ) == KaxChapters::ClassInfos.GlobalId )
831         {
832             msg_Dbg( p_input, "|   + Chapters FIXME TODO" );
833         }
834         else if( EbmlId( *el1 ) == KaxTag::ClassInfos.GlobalId )
835         {
836             msg_Dbg( p_input, "|   + Tags FIXME TODO" );
837         }
838         else
839         {
840             msg_Dbg( p_input, "|   + Unknow (%s)", typeid(*el1).name() );
841         }
842     }
843
844     if( p_sys->cluster == NULL )
845     {
846         msg_Err( p_input, "cannot find any cluster, damaged file ?" );
847         goto error;
848     }
849
850     /* Create one program */
851     vlc_mutex_lock( &p_input->stream.stream_lock );
852     if( input_InitStream( p_input, 0 ) == -1)
853     {
854         vlc_mutex_unlock( &p_input->stream.stream_lock );
855         msg_Err( p_input, "cannot init stream" );
856         goto error;
857     }
858     if( input_AddProgram( p_input, 0, 0) == NULL )
859     {
860         vlc_mutex_unlock( &p_input->stream.stream_lock );
861         msg_Err( p_input, "cannot add program" );
862         goto error;
863     }
864     p_input->stream.p_selected_program = p_input->stream.pp_programs[0];
865     p_input->stream.i_mux_rate = 0;
866     vlc_mutex_unlock( &p_input->stream.stream_lock );
867
868     /* add all es */
869     msg_Dbg( p_input, "found %d es", p_sys->i_track );
870     for( i_track = 0; i_track < p_sys->i_track; i_track++ )
871     {
872 #define tk  p_sys->track[i_track]
873         if( tk.i_cat == UNKNOWN_ES )
874         {
875             msg_Warn( p_input, "invalid track[%d, n=%d]", i_track, tk.i_number );
876             tk.p_es = NULL;
877             continue;
878         }
879         tk.p_es = input_AddES( p_input,
880                                p_input->stream.p_selected_program,
881                                i_track + 1,
882                                tk.i_cat,
883                                tk.psz_language, 0 );
884         if( !strcmp( tk.psz_codec, "V_MS/VFW/FOURCC" ) )
885         {
886             if( tk.i_extra_data < sizeof( BITMAPINFOHEADER ) )
887             {
888                 msg_Err( p_input, "missing/invalid BITMAPINFOHEADER" );
889                 tk.i_codec = VLC_FOURCC( 'u', 'n', 'd', 'f' );
890             }
891             else
892             {
893                 BITMAPINFOHEADER *p_bih = (BITMAPINFOHEADER*)tk.p_extra_data;
894
895                 p_bih->biSize           = GetDWLE( &p_bih->biSize );
896                 p_bih->biWidth          = GetDWLE( &p_bih->biWidth );
897                 p_bih->biHeight         = GetDWLE( &p_bih->biHeight );
898                 p_bih->biPlanes         = GetWLE( &p_bih->biPlanes );
899                 p_bih->biBitCount       = GetWLE( &p_bih->biBitCount );
900                 p_bih->biCompression    = GetFOURCC( &p_bih->biCompression );
901                 p_bih->biSizeImage      = GetDWLE( &p_bih->biSizeImage );
902                 p_bih->biXPelsPerMeter  = GetDWLE( &p_bih->biXPelsPerMeter );
903                 p_bih->biYPelsPerMeter  = GetDWLE( &p_bih->biYPelsPerMeter );
904                 p_bih->biClrUsed        = GetDWLE( &p_bih->biClrUsed );
905                 p_bih->biClrImportant   = GetDWLE( &p_bih->biClrImportant );
906
907
908                 tk.i_codec = p_bih->biCompression;
909                 tk.p_es->p_bitmapinfoheader = p_bih;
910             }
911         }
912         else if( !strcmp( tk.psz_codec, "V_MPEG1" ) ||
913                  !strcmp( tk.psz_codec, "V_MPEG2" ) )
914         {
915             tk.i_codec = VLC_FOURCC( 'm', 'p', 'g', 'v' );
916         }
917         else if( !strncmp( tk.psz_codec, "V_MPEG4", 7 ) )
918         {
919             BITMAPINFOHEADER *p_bih;
920
921             tk.i_extra_data = sizeof( BITMAPINFOHEADER );
922             tk.p_extra_data = (uint8_t*)malloc( tk.i_extra_data );
923
924             p_bih = (BITMAPINFOHEADER*)tk.p_extra_data;
925             memset( p_bih, 0, sizeof( BITMAPINFOHEADER ) );
926             p_bih->biSize  = sizeof( BITMAPINFOHEADER );
927             p_bih->biWidth = tk.i_width;
928             p_bih->biHeight= tk.i_height;
929
930             if( !strcmp( tk.psz_codec, "V_MPEG4/MS/V3" ) )
931             {
932                 tk.i_codec = VLC_FOURCC( 'D', 'I', 'V', '3' );
933             }
934             else
935             {
936                 tk.i_codec = VLC_FOURCC( 'm', 'p', '4', 'v' );
937             }
938         }
939         else if( !strcmp( tk.psz_codec, "A_MS/ACM" ) )
940         {
941             if( tk.i_extra_data < sizeof( WAVEFORMATEX ) )
942             {
943                 msg_Err( p_input, "missing/invalid WAVEFORMATEX" );
944                 tk.i_codec = VLC_FOURCC( 'u', 'n', 'd', 'f' );
945             }
946             else
947             {
948                 WAVEFORMATEX *p_wf = (WAVEFORMATEX*)tk.p_extra_data;
949
950                 p_wf->wFormatTag        = GetWLE( p_wf->wFormatTag );
951                 p_wf->nChannels         = GetWLE( p_wf->nChannels );
952                 p_wf->nSamplesPerSec    = GetDWLE( p_wf->nSamplesPerSec );
953                 p_wf->nAvgBytesPerSec   = GetDWLE( p_wf->nAvgBytesPerSec );
954                 p_wf->nBlockAlign       = GetWLE( p_wf->nBlockAlign );
955                 p_wf->wBitsPerSample    = GetWLE( p_wf->wBitsPerSample );
956                 p_wf->cbSize            = GetWLE( p_wf->cbSize );
957
958                 switch( p_wf->wFormatTag )
959                 {
960                     case WAVE_FORMAT_PCM:
961                         tk.i_codec = VLC_FOURCC( 'a', 'r', 'a', 'w' );
962                         break;
963                     case WAVE_FORMAT_ADPCM:
964                         tk.i_codec = VLC_FOURCC( 'm', 's', 0x00, 0x02 );
965                         break;
966                     case WAVE_FORMAT_ALAW:
967                         tk.i_codec = VLC_FOURCC( 'a', 'l', 'a', 'w' );
968                         break;
969                     case WAVE_FORMAT_MULAW:
970                         tk.i_codec = VLC_FOURCC( 'm', 'l', 'a', 'w' );
971                         break;
972                     case WAVE_FORMAT_IMA_ADPCM:
973                         tk.i_codec = VLC_FOURCC( 'm', 's', 0x00, 0x11 );
974                         break;
975                     case WAVE_FORMAT_MPEG:
976                     case WAVE_FORMAT_MPEGLAYER3:
977                         tk.i_codec = VLC_FOURCC( 'm', 'p', 'g', 'a' );
978                         break;
979                     case WAVE_FORMAT_A52:
980                         tk.i_codec = VLC_FOURCC( 'a', '5', '2', ' ' );
981                         break;
982                     case WAVE_FORMAT_WMA1:
983                         tk.i_codec = VLC_FOURCC( 'w', 'm', 'a', '1' );
984                         break;
985                     case WAVE_FORMAT_WMA2:
986                         tk.i_codec = VLC_FOURCC( 'w', 'm', 'a', '2' );
987                         break;
988                     case WAVE_FORMAT_WMA3:
989                         tk.i_codec = VLC_FOURCC( 'w', 'm', 'a', '3' );
990                         break;
991                     default:
992                         msg_Err( p_input, "unknown wFormatTag=0x%x", p_wf->wFormatTag );
993                         tk.i_codec = VLC_FOURCC( 'm', 's', p_wf->wFormatTag >> 8, p_wf->wFormatTag&0xff );
994                         break;
995                 }
996                 tk.p_es->p_waveformatex = p_wf;
997             }
998         }
999         else if( !strcmp( tk.psz_codec, "A_MPEG/L3" ) ||
1000                  !strcmp( tk.psz_codec, "A_MPEG/L2" ) ||
1001                  !strcmp( tk.psz_codec, "A_MPEG/L1" ) )
1002         {
1003             tk.i_codec = VLC_FOURCC( 'm', 'p', 'g', 'a' );
1004         }
1005         else if( !strcmp( tk.psz_codec, "A_AC3" ) )
1006         {
1007             tk.i_codec = VLC_FOURCC( 'a', '5', '2', ' ' );
1008         }
1009         else if( !strcmp( tk.psz_codec, "A_DTS" ) )
1010         {
1011             tk.i_codec = VLC_FOURCC( 'd', 't', 's', ' ' );
1012         }
1013         else if( !strcmp( tk.psz_codec, "A_VORBIS" ) )
1014         {
1015             tk.i_codec = VLC_FOURCC( 'v', 'o', 'r', 'b' );
1016             tk.i_data_init = tk.i_extra_data;
1017             tk.p_data_init = tk.p_extra_data;
1018         }
1019         else if( !strncmp( tk.psz_codec, "A_AAC/MPEG2/", strlen( "A_AAC/MPEG2/" ) ) ||
1020                  !strncmp( tk.psz_codec, "A_AAC/MPEG4/", strlen( "A_AAC/MPEG4/" ) ) )
1021         {
1022             int i_profile, i_srate;
1023             static int i_sample_rates[] =
1024             {
1025                     96000, 88200, 64000, 48000, 44100, 32000, 24000, 22050,
1026                         16000, 12000, 11025, 8000,  7350,  0,     0,     0
1027             };
1028             WAVEFORMATEX *p_wf;
1029
1030             tk.i_codec = VLC_FOURCC( 'm', 'p', '4', 'a' );
1031             /* create data for faad (MP4DecSpecificDescrTag)*/
1032
1033             if( !strcmp( &tk.psz_codec[12], "MAIN" ) )
1034             {
1035                 i_profile = 0;
1036             }
1037             else if( !strcmp( &tk.psz_codec[12], "LC" ) )
1038             {
1039                 i_profile = 1;
1040             }
1041             else if( !strcmp( &tk.psz_codec[12], "SSR" ) )
1042             {
1043                 i_profile = 2;
1044             }
1045             else
1046             {
1047                 i_profile = 3;
1048             }
1049
1050             for( i_srate = 0; i_srate < 13; i_srate++ )
1051             {
1052                 if( i_sample_rates[i_srate] == tk.i_samplerate )
1053                 {
1054                     break;
1055                 }
1056             }
1057             msg_Dbg( p_input, "profile=%d srate=%d", i_profile, i_srate );
1058
1059             tk.i_extra_data = sizeof( WAVEFORMATEX ) + 2;
1060             tk.p_extra_data = (uint8_t*)malloc( tk.i_extra_data );
1061             p_wf = (WAVEFORMATEX*)tk.p_extra_data;
1062
1063             p_wf->wFormatTag = WAVE_FORMAT_UNKNOWN;
1064             p_wf->nChannels  = tk.i_channels;
1065             p_wf->nSamplesPerSec = tk.i_samplerate;
1066             p_wf->nAvgBytesPerSec = 0;
1067             p_wf->nBlockAlign = 0;
1068             p_wf->wBitsPerSample = 0;
1069             p_wf->cbSize = 2;
1070
1071             tk.p_extra_data[sizeof( WAVEFORMATEX )+ 0] = ((i_profile + 1) << 3) | ((i_srate&0xe) >> 1);
1072             tk.p_extra_data[sizeof( WAVEFORMATEX )+ 1] = ((i_srate & 0x1) << 7) | (tk.i_channels << 3);
1073
1074             tk.p_es->p_waveformatex = p_wf;
1075         }
1076         else if( !strcmp( tk.psz_codec, "A_PCM/INT/BIG" ) ||
1077                  !strcmp( tk.psz_codec, "A_PCM/INT/LIT" ) ||
1078                  !strcmp( tk.psz_codec, "A_PCM/FLOAT/IEEE" ) )
1079         {
1080             WAVEFORMATEX *p_wf;
1081
1082             tk.i_extra_data = sizeof( WAVEFORMATEX );
1083             tk.p_extra_data = (uint8_t*)malloc( tk.i_extra_data );
1084
1085             p_wf = (WAVEFORMATEX*)tk.p_extra_data;
1086
1087             if( !strncmp( &tk.psz_codec[6], "INT", 3 ) )
1088             {
1089                 p_wf->wFormatTag = WAVE_FORMAT_PCM;
1090             }
1091             else
1092             {
1093                 p_wf->wFormatTag = WAVE_FORMAT_IEEE_FLOAT;
1094             }
1095             p_wf->nChannels  = tk.i_channels;
1096             p_wf->nSamplesPerSec = tk.i_samplerate;
1097             p_wf->nAvgBytesPerSec = 0;
1098             p_wf->nBlockAlign = ( tk.i_bitspersample + 7 ) / 8 * tk.i_channels;
1099             p_wf->wBitsPerSample = tk.i_bitspersample;
1100             p_wf->cbSize = 0;
1101
1102             tk.p_es->p_waveformatex = p_wf;
1103
1104             if( !strcmp( tk.psz_codec, "A_PCM/INT/BIG" ) )
1105             {
1106                 tk.i_codec = VLC_FOURCC( 't', 'w', 'o', 's' );
1107             }
1108             else
1109             {
1110                 tk.i_codec = VLC_FOURCC( 'a', 'r', 'a', 'w' );
1111             }
1112         }
1113         else if( !strcmp( tk.psz_codec, "S_TEXT/UTF8" ) )
1114         {
1115             tk.i_codec = VLC_FOURCC( 's', 'u', 'b', 't' );
1116         }
1117         else
1118         {
1119             msg_Err( p_input, "unknow codec id=`%s'", tk.psz_codec );
1120             tk.i_codec = VLC_FOURCC( 'u', 'n', 'd', 'f' );
1121         }
1122
1123         tk.p_es->i_fourcc = tk.i_codec;
1124 #undef tk
1125     }
1126
1127     /* select track all video, one audio, no spu TODO : improve */
1128     b_audio_selected = VLC_FALSE;
1129     i_audio_channel = 0;
1130     i_spu_channel = 0;
1131     for( i_track = 0; i_track < p_sys->i_track; i_track++ )
1132     {
1133 #define tk  p_sys->track[i_track]
1134         switch( tk.i_cat )
1135         {
1136             case VIDEO_ES:
1137                 vlc_mutex_lock( &p_input->stream.stream_lock );
1138                 input_SelectES( p_input, tk.p_es );
1139                 vlc_mutex_unlock( &p_input->stream.stream_lock );
1140                 break;
1141
1142             case AUDIO_ES:
1143                 if( ( !b_audio_selected && config_GetInt( p_input, "audio-channel" ) < 0 ) ||
1144                     i_audio_channel == config_GetInt( p_input, "audio-channel" ) )
1145                 {
1146                     vlc_mutex_lock( &p_input->stream.stream_lock );
1147                     input_SelectES( p_input, tk.p_es );
1148                     vlc_mutex_unlock( &p_input->stream.stream_lock );
1149
1150                     b_audio_selected = tk.p_es->p_decoder_fifo ? VLC_TRUE : VLC_FALSE;
1151                 }
1152                 i_audio_channel++;
1153                 break;
1154             case SPU_ES:
1155                 if( i_spu_channel == config_GetInt( p_input, "spu-channel" ) )
1156                 {
1157                     vlc_mutex_lock( &p_input->stream.stream_lock );
1158                     input_SelectES( p_input, tk.p_es );
1159                     vlc_mutex_unlock( &p_input->stream.stream_lock );
1160                 }
1161                 i_spu_channel++;
1162                 break;
1163         }
1164 #undef tk
1165     }
1166
1167     if( !b_audio_selected )
1168     {
1169         msg_Warn( p_input, "cannot find/select audio track" );
1170     }
1171
1172     return VLC_SUCCESS;
1173
1174 error:
1175     delete p_sys->es;
1176     delete p_sys->in;
1177     free( p_sys );
1178     return VLC_EGENERIC;
1179 }
1180
1181 /*****************************************************************************
1182  * Deactivate: frees unused data
1183  *****************************************************************************/
1184 static void Deactivate( vlc_object_t *p_this )
1185 {
1186     input_thread_t *p_input = (input_thread_t *)p_this;
1187     demux_sys_t    *p_sys   = p_input->p_demux_data;
1188
1189     int             i_track;
1190
1191     for( i_track = 0; i_track < p_sys->i_track; i_track++ )
1192     {
1193 #define tk  p_sys->track[i_track]
1194         if( tk.psz_codec )
1195         {
1196             free( tk.psz_codec );
1197         }
1198         if( tk.psz_language )
1199         {
1200             free( tk.psz_language );
1201         }
1202 #undef tk
1203     }
1204     free( p_sys->track );
1205
1206     delete p_sys->ep;
1207     delete p_sys->es;
1208     delete p_sys->in;
1209
1210     free( p_sys );
1211 }
1212
1213 /*****************************************************************************
1214  * Demux: reads and demuxes data packets
1215  *****************************************************************************
1216  * Returns -1 in case of error, 0 in case of EOF, 1 otherwise
1217  *****************************************************************************/
1218 static int Demux( input_thread_t * p_input )
1219 {
1220     demux_sys_t    *p_sys   = p_input->p_demux_data;
1221     mtime_t        i_start_pts = p_sys->i_last_pts;
1222     KaxBlock *block = NULL;
1223     int64_t i_block_duration = -1;
1224     int64_t i_block_ref1 = 0;
1225     int64_t i_block_ref2 = 0;
1226
1227     if( p_input->stream.p_selected_program->i_synchro_state == SYNCHRO_REINIT )
1228     {
1229         msg_Err( p_input, "DO NO SEEK YET" );
1230     }
1231
1232     for( ;; )
1233     {
1234         EbmlElement *el;
1235         int         i_level;
1236
1237         el = p_sys->ep->Get();
1238         i_level = p_sys->ep->GetLevel();
1239
1240         /* First send last collected blocks (before ep->Up, because of cluster) */
1241         if( el == NULL && block != NULL )
1242         {
1243             /* we have data */
1244             int i_track;
1245 #define tk  p_sys->track[i_track]
1246             for( i_track = 0; i_track < p_sys->i_track; i_track++ )
1247             {
1248                 if( tk.i_number == block->TrackNum() )
1249                 {
1250                     break;
1251                 }
1252             }
1253
1254             p_sys->i_last_pts = block->GlobalTimecode() * (mtime_t) 1000 / p_sys->tc_scale;
1255
1256             if( p_sys->i_last_pts > 0 )
1257             {
1258                 input_ClockManageRef( p_input,
1259                                       p_input->stream.p_selected_program,
1260                                       p_sys->i_last_pts * 9 / 100 );
1261             }
1262
1263             if( i_track >= p_sys->i_track )
1264             {
1265                 msg_Err( p_input, "invalid track number=%d", block->TrackNum() );
1266             }
1267             else if( tk.p_es->p_decoder_fifo != NULL )
1268             {
1269                 pes_packet_t  *p_pes;
1270                 int i;
1271
1272                 if( ( p_pes = input_NewPES( p_input->p_method_data ) ) != NULL )
1273                 {
1274                     mtime_t i_pts;
1275
1276                     i_pts = input_ClockGetTS( p_input,
1277                                               p_input->stream.p_selected_program,
1278                                               p_sys->i_last_pts * 9 / 100 );
1279
1280                     p_pes->i_pts = i_pts;
1281                     p_pes->i_dts = i_pts;
1282                     if( tk.i_cat == SPU_ES )
1283                     {
1284                         /* special case : dts mean end of display */
1285                         if( i_block_duration > 0 )
1286                         {
1287                             /* FIXME not sure about that */
1288                             p_pes->i_dts += i_block_duration * 1000;// * (mtime_t) 1000 / p_sys->tc_scale;
1289                         }
1290                         else
1291                         {
1292                             /* unknown */
1293                             p_pes->i_dts = 0;
1294                         }
1295                     }
1296
1297                     p_pes->p_first = p_pes->p_last = NULL;
1298                     p_pes->i_nb_data = 0;
1299                     p_pes->i_pes_size = 0;
1300
1301                     for( i = 0; i < block->NumberFrames(); i++ )
1302                     {
1303                         data_packet_t *p_data = NULL;
1304                         DataBuffer &data = block->GetBuffer(i);
1305
1306                         if( ( p_data = input_NewPacket( p_input->p_method_data, data.Size() ) ) != NULL )
1307                         {
1308                             memcpy( p_data->p_payload_start, data.Buffer(), data.Size() );
1309
1310                             p_data->p_payload_end = p_data->p_payload_start + data.Size();
1311
1312                             if( p_pes->p_first == NULL )
1313                             {
1314                                 p_pes->p_first = p_data;
1315                             }
1316                             else
1317                             {
1318                                 p_pes->p_last->p_next  = p_data;
1319                             }
1320                             p_pes->i_nb_data++;
1321                             p_pes->i_pes_size += data.Size();
1322                             p_pes->p_last  = p_data;
1323                         }
1324                     }
1325                     if( tk.i_cat == SPU_ES && p_pes->p_first && p_pes->i_pes_size > 0 )
1326                     {
1327                         p_pes->p_first->p_payload_end[-1] = '\0';
1328                     }
1329
1330                     if( !tk.b_inited && tk.i_data_init > 0 )
1331                     {
1332                         pes_packet_t *p_init;
1333                         data_packet_t *p_data;
1334
1335                         msg_Dbg( p_input, "sending header (%d bytes)", tk.i_data_init );
1336
1337                         p_init = input_NewPES( p_input->p_method_data );
1338
1339                         p_data = input_NewPacket( p_input->p_method_data, tk.i_data_init );
1340                         memcpy( p_data->p_payload_start, tk.p_data_init, tk.i_data_init );
1341                         p_data->p_payload_end = p_data->p_payload_start + tk.i_data_init;
1342
1343                         p_init->p_first = p_init->p_last = p_data;
1344                         p_init->i_nb_data = 1;
1345                         p_init->i_pes_size = tk.i_data_init;
1346
1347                         input_DecodePES( tk.p_es->p_decoder_fifo, p_init );
1348                     }
1349                     tk.b_inited = VLC_TRUE;
1350
1351                     input_DecodePES( tk.p_es->p_decoder_fifo, p_pes );
1352                 }
1353                 else
1354                 {
1355                     tk.b_inited = VLC_FALSE;
1356                 }
1357             }
1358 #undef tk
1359             delete block;
1360             block = NULL;
1361
1362             if( p_sys->i_last_pts > i_start_pts + (mtime_t)100000)
1363             {
1364                 return 1;
1365             }
1366         }
1367
1368         if( el == NULL )
1369         {
1370             if( p_sys->ep->GetLevel() > 1 )
1371             {
1372                 p_sys->ep->Up();
1373                 continue;
1374             }
1375             msg_Warn( p_input, "EOF" );
1376             return 0;
1377         }
1378
1379         /* do parsing */
1380         if( i_level == 1 )
1381         {
1382             if( EbmlId( *el ) == KaxCluster::ClassInfos.GlobalId )
1383             {
1384                 p_sys->cluster = (KaxCluster*)el;
1385                 p_sys->ep->Down();
1386             }
1387             else if( EbmlId( *el ) == KaxCues::ClassInfos.GlobalId )
1388             {
1389                 msg_Warn( p_input, "find KaxCues FIXME" );
1390                 return 0;
1391             }
1392             else
1393             {
1394                 msg_Dbg( p_input, "unknown (%s)", typeid( el ).name() );
1395             }
1396         }
1397         else if( i_level == 2 )
1398         {
1399             if( EbmlId( *el ) == KaxClusterTimecode::ClassInfos.GlobalId )
1400             {
1401                 KaxClusterTimecode &ctc = *(KaxClusterTimecode*)el;
1402
1403                 ctc.ReadData( p_sys->es->I_O() );
1404                 p_sys->i_cluster_tc = uint64( ctc );
1405                 p_sys->cluster->InitTimecode( p_sys->i_cluster_tc, p_sys->tc_scale );
1406             }
1407             else if( EbmlId( *el ) == KaxBlockGroup::ClassInfos.GlobalId )
1408             {
1409                 p_sys->ep->Down();
1410             }
1411         }
1412         else if( i_level == 3 )
1413         {
1414             if( EbmlId( *el ) == KaxBlock::ClassInfos.GlobalId )
1415             {
1416                 block = (KaxBlock*)el;
1417
1418                 block->ReadData( p_sys->es->I_O() );
1419                 block->SetParent( *p_sys->cluster );
1420
1421                 p_sys->ep->Keep();
1422             }
1423             else if( EbmlId( *el ) == KaxBlockDuration::ClassInfos.GlobalId )
1424             {
1425                 KaxBlockDuration &dur = *(KaxBlockDuration*)el;
1426
1427                 dur.ReadData( p_sys->es->I_O() );
1428                 i_block_duration = uint64( dur );
1429             }
1430             else if( EbmlId( *el ) == KaxReferenceBlock::ClassInfos.GlobalId )
1431             {
1432                 KaxReferenceBlock &ref = *(KaxReferenceBlock*)el;
1433
1434                 ref.ReadData( p_sys->es->I_O() );
1435                 if( i_block_ref1 == 0 )
1436                 {
1437                     i_block_ref1 = int64( ref );
1438                 }
1439                 else
1440                 {
1441                     i_block_ref2 = int64( ref );
1442                 }
1443             }
1444         }
1445         else
1446         {
1447             msg_Err( p_input, "invalid level = %d", i_level );
1448             return 0;
1449         }
1450     }
1451
1452 }
1453
1454