]> git.sesse.net Git - vlc/blob - modules/demux/mkv/mkv.cpp
Revert "demuxers: adjust es_out_Control( out, ES_OUT_GET_ES_STATE, ... ) to new protytpe"
[vlc] / modules / demux / mkv / mkv.cpp
1 /*****************************************************************************
2  * mkv.cpp : matroska demuxer
3  *****************************************************************************
4  * Copyright (C) 2003-2005, 2008, 2010 VLC authors and VideoLAN
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 it
11  * under the terms of the GNU Lesser General Public License as published by
12  * the Free Software Foundation; either version 2.1 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 Lesser General Public License for more details.
19  *
20  * You should have received a copy of the GNU Lesser General Public License
21  * along with this program; if not, write to the Free Software Foundation,
22  * Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA.
23  *****************************************************************************/
24
25 #include "mkv.hpp"
26 #include "util.hpp"
27
28 #include "matroska_segment.hpp"
29 #include "demux.hpp"
30
31 #include "chapters.hpp"
32 #include "Ebml_parser.hpp"
33
34 #include "stream_io_callback.hpp"
35
36 #include <vlc_fs.h>
37 #include <vlc_url.h>
38
39 /*****************************************************************************
40  * Module descriptor
41  *****************************************************************************/
42 static int  Open ( vlc_object_t * );
43 static void Close( vlc_object_t * );
44
45 vlc_module_begin ()
46     set_shortname( "Matroska" )
47     set_description( N_("Matroska stream demuxer" ) )
48     set_capability( "demux", 50 )
49     set_callbacks( Open, Close )
50     set_category( CAT_INPUT )
51     set_subcategory( SUBCAT_INPUT_DEMUX )
52
53     add_bool( "mkv-use-ordered-chapters", true,
54             N_("Respect ordered chapters"),
55             N_("Play chapters in the order specified in the segment."), false );
56
57     add_bool( "mkv-use-chapter-codec", true,
58             N_("Chapter codecs"),
59             N_("Use chapter codecs found in the segment."), true );
60
61     add_bool( "mkv-preload-local-dir", true,
62             N_("Preload MKV files in the same directory"),
63             N_("Preload matroska files in the same directory to find linked segments (not good for broken files)."), false );
64
65     add_bool( "mkv-seek-percent", false,
66             N_("Seek based on percent not time"),
67             N_("Seek based on percent not time."), true );
68
69     add_bool( "mkv-use-dummy", false,
70             N_("Dummy Elements"),
71             N_("Read and discard unknown EBML elements (not good for broken files)."), true );
72
73     add_shortcut( "mka", "mkv" )
74 vlc_module_end ()
75
76 class demux_sys_t;
77
78 static int  Demux  ( demux_t * );
79 static int  Control( demux_t *, int, va_list );
80 static void Seek   ( demux_t *, mtime_t i_date, double f_percent, virtual_chapter_c *p_chapter );
81
82 /*****************************************************************************
83  * Open: initializes matroska demux structures
84  *****************************************************************************/
85 static int Open( vlc_object_t * p_this )
86 {
87     demux_t            *p_demux = (demux_t*)p_this;
88     demux_sys_t        *p_sys;
89     matroska_stream_c  *p_stream;
90     matroska_segment_c *p_segment;
91     const uint8_t      *p_peek;
92     std::string         s_path, s_filename;
93     vlc_stream_io_callback *p_io_callback;
94     EbmlStream         *p_io_stream;
95     bool                b_need_preload = false;
96
97     /* peek the begining */
98     if( stream_Peek( p_demux->s, &p_peek, 4 ) < 4 ) return VLC_EGENERIC;
99
100     /* is a valid file */
101     if( p_peek[0] != 0x1a || p_peek[1] != 0x45 ||
102         p_peek[2] != 0xdf || p_peek[3] != 0xa3 ) return VLC_EGENERIC;
103
104     /* Set the demux function */
105     p_demux->pf_demux   = Demux;
106     p_demux->pf_control = Control;
107     p_demux->p_sys      = p_sys = new demux_sys_t( *p_demux );
108
109     p_io_callback = new vlc_stream_io_callback( p_demux->s, false );
110     p_io_stream = new EbmlStream( *p_io_callback );
111
112     if( p_io_stream == NULL )
113     {
114         msg_Err( p_demux, "failed to create EbmlStream" );
115         delete p_io_callback;
116         delete p_sys;
117         return VLC_EGENERIC;
118     }
119
120     p_stream = p_sys->AnalyseAllSegmentsFound( p_demux, p_io_stream, true );
121     if( p_stream == NULL )
122     {
123         msg_Err( p_demux, "cannot find KaxSegment or missing mandatory KaxInfo" );
124         goto error;
125     }
126     p_sys->streams.push_back( p_stream );
127
128     p_stream->p_io_callback = p_io_callback;
129     p_stream->p_estream = p_io_stream;
130
131     for (size_t i=0; i<p_stream->segments.size(); i++)
132     {
133         p_stream->segments[i]->Preload();
134         b_need_preload |= p_stream->segments[i]->b_ref_external_segments;
135     }
136
137     p_segment = p_stream->segments[0];
138     if( p_segment->cluster == NULL )
139     {
140         msg_Err( p_demux, "cannot find any cluster, damaged file ?" );
141         goto error;
142     }
143
144     if (b_need_preload && var_InheritBool( p_demux, "mkv-preload-local-dir" ))
145     {
146         msg_Dbg( p_demux, "Preloading local dir" );
147         /* get the files from the same dir from the same family (based on p_demux->psz_path) */
148         if ( p_demux->psz_file && !strcmp( p_demux->psz_access, "file" ) )
149         {
150             // assume it's a regular file
151             // get the directory path
152             s_path = p_demux->psz_file;
153             if (s_path.at(s_path.length() - 1) == DIR_SEP_CHAR)
154             {
155                 s_path = s_path.substr(0,s_path.length()-1);
156             }
157             else
158             {
159                 if (s_path.find_last_of(DIR_SEP_CHAR) > 0)
160                 {
161                     s_path = s_path.substr(0,s_path.find_last_of(DIR_SEP_CHAR));
162                 }
163             }
164
165             DIR *p_src_dir = vlc_opendir(s_path.c_str());
166
167             if (p_src_dir != NULL)
168             {
169                 const char *psz_file;
170                 while ((psz_file = vlc_readdir(p_src_dir)) != NULL)
171                 {
172                     if (strlen(psz_file) > 4)
173                     {
174                         s_filename = s_path + DIR_SEP_CHAR + psz_file;
175
176 #if defined(_WIN32) || defined(__OS2__)
177                         if (!strcasecmp(s_filename.c_str(), p_demux->psz_file))
178 #else
179                         if (!s_filename.compare(p_demux->psz_file))
180 #endif
181                         {
182                             continue; // don't reuse the original opened file
183                         }
184
185                         if (!s_filename.compare(s_filename.length() - 3, 3, "mkv") ||
186                             !s_filename.compare(s_filename.length() - 3, 3, "mka"))
187                         {
188                             // test whether this file belongs to our family
189                             const uint8_t *p_peek;
190                             bool          file_ok = false;
191 #warning Memory leak!
192                             std::string   s_url = vlc_path2uri( s_filename.c_str(), "file" );
193                             stream_t      *p_file_stream = stream_UrlNew(
194                                                             p_demux,
195                                                             s_url.c_str() );
196                             /* peek the begining */
197                             if( p_file_stream &&
198                                 stream_Peek( p_file_stream, &p_peek, 4 ) >= 4
199                                 && p_peek[0] == 0x1a && p_peek[1] == 0x45 &&
200                                 p_peek[2] == 0xdf && p_peek[3] == 0xa3 ) file_ok = true;
201
202                             if ( file_ok )
203                             {
204                                 vlc_stream_io_callback *p_file_io = new vlc_stream_io_callback( p_file_stream, true );
205                                 EbmlStream *p_estream = new EbmlStream(*p_file_io);
206
207                                 p_stream = p_sys->AnalyseAllSegmentsFound( p_demux, p_estream );
208
209                                 if ( p_stream == NULL )
210                                 {
211                                     msg_Dbg( p_demux, "the file '%s' will not be used", s_filename.c_str() );
212                                     delete p_estream;
213                                     delete p_file_io;
214                                 }
215                                 else
216                                 {
217                                     p_stream->p_io_callback = p_file_io;
218                                     p_stream->p_estream = p_estream;
219                                     p_sys->streams.push_back( p_stream );
220                                 }
221                             }
222                             else
223                             {
224                                 if( p_file_stream ) {
225                                     stream_Delete( p_file_stream );
226                                 }
227                                 msg_Dbg( p_demux, "the file '%s' cannot be opened", s_filename.c_str() );
228                             }
229                         }
230                     }
231                 }
232                 closedir( p_src_dir );
233             }
234         }
235
236         p_sys->PreloadFamily( *p_segment );
237     }
238     else if (b_need_preload)
239         msg_Warn( p_demux, "This file references other files, you may want to enable the preload of local directory");
240
241     if ( !p_sys->PreloadLinked() ||
242          !p_sys->PreparePlayback( NULL ) )
243     {
244         msg_Err( p_demux, "cannot use the segment" );
245         goto error;
246     }
247
248     p_sys->FreeUnused();
249
250     p_sys->InitUi();
251
252     return VLC_SUCCESS;
253
254 error:
255     delete p_sys;
256     return VLC_EGENERIC;
257 }
258
259 /*****************************************************************************
260  * Close: frees unused data
261  *****************************************************************************/
262 static void Close( vlc_object_t *p_this )
263 {
264     demux_t     *p_demux = (demux_t*)p_this;
265     demux_sys_t *p_sys   = p_demux->p_sys;
266     virtual_segment_c *p_vsegment = p_sys->p_current_segment;
267     if( p_vsegment )
268     {
269         matroska_segment_c *p_segment = p_vsegment->CurrentSegment();
270         if( p_segment )
271             p_segment->UnSelect();
272     }
273
274     delete p_sys;
275 }
276
277 /*****************************************************************************
278  * Control:
279  *****************************************************************************/
280 static int Control( demux_t *p_demux, int i_query, va_list args )
281 {
282     demux_sys_t        *p_sys = p_demux->p_sys;
283     int64_t     *pi64, i64;
284     double      *pf, f;
285     int         i_skp;
286     size_t      i_idx;
287
288     vlc_meta_t *p_meta;
289     input_attachment_t ***ppp_attach;
290     int *pi_int;
291
292     switch( i_query )
293     {
294         case DEMUX_GET_ATTACHMENTS:
295             ppp_attach = (input_attachment_t***)va_arg( args, input_attachment_t*** );
296             pi_int = (int*)va_arg( args, int * );
297
298             if( p_sys->stored_attachments.size() <= 0 )
299                 return VLC_EGENERIC;
300
301             *pi_int = p_sys->stored_attachments.size();
302             *ppp_attach = (input_attachment_t**)malloc( sizeof(input_attachment_t*) *
303                                                         p_sys->stored_attachments.size() );
304             if( !(*ppp_attach) )
305                 return VLC_ENOMEM;
306             for( size_t i = 0; i < p_sys->stored_attachments.size(); i++ )
307             {
308                 attachment_c *a = p_sys->stored_attachments[i];
309                 (*ppp_attach)[i] = vlc_input_attachment_New( a->fileName(), a->mimeType(), NULL,
310                                                              a->p_data, a->size() );
311             }
312             return VLC_SUCCESS;
313
314         case DEMUX_GET_META:
315             p_meta = (vlc_meta_t*)va_arg( args, vlc_meta_t* );
316             vlc_meta_Merge( p_meta, p_sys->meta );
317             return VLC_SUCCESS;
318
319         case DEMUX_GET_LENGTH:
320             pi64 = (int64_t*)va_arg( args, int64_t * );
321             if( p_sys->f_duration > 0.0 )
322             {
323                 *pi64 = (int64_t)(p_sys->f_duration * 1000);
324                 return VLC_SUCCESS;
325             }
326             return VLC_EGENERIC;
327
328         case DEMUX_GET_POSITION:
329             pf = (double*)va_arg( args, double * );
330             if ( p_sys->f_duration > 0.0 )
331                 *pf = (double)(p_sys->i_pts >= p_sys->i_start_pts ? p_sys->i_pts : p_sys->i_start_pts ) / (1000.0 * p_sys->f_duration);
332             return VLC_SUCCESS;
333
334         case DEMUX_SET_POSITION:
335             if( p_sys->f_duration > 0.0 )
336             {
337                 f = (double)va_arg( args, double );
338                 Seek( p_demux, -1, f, NULL );
339                 return VLC_SUCCESS;
340             }
341             return VLC_EGENERIC;
342
343         case DEMUX_GET_TIME:
344             pi64 = (int64_t*)va_arg( args, int64_t * );
345             *pi64 = p_sys->i_pts;
346             return VLC_SUCCESS;
347
348         case DEMUX_GET_TITLE_INFO:
349             if( p_sys->titles.size() > 1 || ( p_sys->titles.size() == 1 && p_sys->titles[0]->i_seekpoint > 0 ) )
350             {
351                 input_title_t ***ppp_title = (input_title_t***)va_arg( args, input_title_t*** );
352                 int *pi_int    = (int*)va_arg( args, int* );
353
354                 *pi_int = p_sys->titles.size();
355                 *ppp_title = (input_title_t**)malloc( sizeof( input_title_t* ) * p_sys->titles.size() );
356
357                 for( size_t i = 0; i < p_sys->titles.size(); i++ )
358                     (*ppp_title)[i] = vlc_input_title_Duplicate( p_sys->titles[i] );
359                 return VLC_SUCCESS;
360             }
361             return VLC_EGENERIC;
362
363         case DEMUX_SET_TITLE:
364             /* handle editions as titles */
365             i_idx = (int)va_arg( args, int );
366             if(i_idx <  p_sys->titles.size() && p_sys->titles[i_idx]->i_seekpoint)
367             {
368                 p_sys->p_current_segment->i_current_edition = i_idx;
369                 p_sys->i_current_title = i_idx;
370                 p_sys->p_current_segment->p_current_chapter = p_sys->p_current_segment->editions[p_sys->p_current_segment->i_current_edition]->getChapterbyTimecode(0);
371
372                 Seek( p_demux, (int64_t)p_sys->titles[i_idx]->seekpoint[0]->i_time_offset, -1, NULL);
373                 p_demux->info.i_update |= INPUT_UPDATE_SEEKPOINT;
374                 p_demux->info.i_seekpoint = 0;
375                 p_sys->f_duration = (float) p_sys->titles[i_idx]->i_length / 1000.f;
376                 return VLC_SUCCESS;
377             }
378             return VLC_EGENERIC;
379
380         case DEMUX_SET_SEEKPOINT:
381             i_skp = (int)va_arg( args, int );
382
383             // TODO change the way it works with the << & >> buttons on the UI (+1/-1 instead of a number)
384             if( p_sys->titles.size() && i_skp < p_sys->titles[p_sys->i_current_title]->i_seekpoint)
385             {
386                 Seek( p_demux, (int64_t)p_sys->titles[p_sys->i_current_title]->seekpoint[i_skp]->i_time_offset, -1, NULL);
387                 p_demux->info.i_update |= INPUT_UPDATE_SEEKPOINT;
388                 p_demux->info.i_seekpoint = i_skp;
389                 return VLC_SUCCESS;
390             }
391             return VLC_EGENERIC;
392
393         case DEMUX_GET_FPS:
394             pf = (double *)va_arg( args, double * );
395             *pf = 0.0;
396             if( p_sys->p_current_segment && p_sys->p_current_segment->CurrentSegment() )
397             {
398                 const matroska_segment_c *p_segment = p_sys->p_current_segment->CurrentSegment();
399                 for( size_t i = 0; i < p_segment->tracks.size(); i++ )
400                 {
401                     mkv_track_t *tk = p_segment->tracks[i];
402                     if( tk->fmt.i_cat == VIDEO_ES && tk->fmt.video.i_frame_rate_base > 0 )
403                     {
404                         *pf = (double)tk->fmt.video.i_frame_rate / tk->fmt.video.i_frame_rate_base;
405                         break;
406                     }
407                 }
408             }
409             return VLC_SUCCESS;
410
411         case DEMUX_SET_TIME:
412             i64 = (int64_t) va_arg( args, int64_t );
413             msg_Dbg(p_demux,"SET_TIME to %"PRId64, i64 );
414             Seek( p_demux, i64, -1, NULL );
415             return VLC_SUCCESS;
416         default:
417             return VLC_EGENERIC;
418     }
419 }
420
421 /* Seek */
422 static void Seek( demux_t *p_demux, mtime_t i_date, double f_percent, virtual_chapter_c *p_chapter )
423 {
424     demux_sys_t        *p_sys = p_demux->p_sys;
425     virtual_segment_c  *p_vsegment = p_sys->p_current_segment;
426     matroska_segment_c *p_segment = p_vsegment->CurrentSegment();
427     mtime_t            i_time_offset = 0;
428     int64_t            i_global_position = -1;
429
430     int         i_index;
431
432     msg_Dbg( p_demux, "seek request to %"PRId64" (%f%%)", i_date, f_percent );
433     if( i_date < 0 && f_percent < 0 )
434     {
435         msg_Warn( p_demux, "cannot seek nowhere!" );
436         return;
437     }
438     if( f_percent > 1.0 )
439     {
440         msg_Warn( p_demux, "cannot seek so far!" );
441         return;
442     }
443     if( p_sys->f_duration < 0 )
444     {
445         msg_Warn( p_demux, "cannot seek without duration!");
446         return;
447     }
448
449     /* seek without index or without date */
450     if( f_percent >= 0 && (var_InheritBool( p_demux, "mkv-seek-percent" ) || !p_segment->b_cues || i_date < 0 ))
451     {
452         i_date = int64_t( f_percent * p_sys->f_duration * 1000.0 );
453         if( !p_segment->b_cues )
454         {
455             int64_t i_pos = int64_t( f_percent * stream_Size( p_demux->s ) );
456
457             msg_Dbg( p_demux, "lengthy way of seeking for pos:%"PRId64, i_pos );
458             for( i_index = 0; i_index < p_segment->i_index; i_index++ )
459             {
460                 if( p_segment->p_indexes[i_index].i_position >= i_pos &&
461                     p_segment->p_indexes[i_index].i_time > 0 )
462                     break;
463             }
464             if( i_index == p_segment->i_index )
465                 i_index--;
466
467             if( p_segment->p_indexes[i_index].i_position < i_pos )
468             {
469                 msg_Dbg( p_demux, "no cues, seek request to global pos: %"PRId64, i_pos );
470                 i_global_position = i_pos;
471             }
472         }
473     }
474     p_vsegment->Seek( *p_demux, i_date, i_time_offset, p_chapter, i_global_position );
475 }
476
477 /* Needed by matroska_segment::Seek() and Seek */
478 void BlockDecode( demux_t *p_demux, KaxBlock *block, KaxSimpleBlock *simpleblock,
479                          mtime_t i_pts, mtime_t i_duration, bool f_mandatory )
480 {
481     demux_sys_t        *p_sys = p_demux->p_sys;
482     matroska_segment_c *p_segment = p_sys->p_current_segment->CurrentSegment();
483
484     if( !p_segment ) return;
485
486     size_t          i_track;
487     if( p_segment->BlockFindTrackIndex( &i_track, block, simpleblock ) )
488     {
489         msg_Err( p_demux, "invalid track number" );
490         return;
491     }
492
493     mkv_track_t *tk = p_segment->tracks[i_track];
494
495     if( tk->fmt.i_cat != NAV_ES && tk->p_es == NULL )
496     {
497         msg_Err( p_demux, "unknown track number" );
498         return;
499     }
500
501     i_pts -= tk->i_codec_delay;
502
503     if ( tk->fmt.i_cat != NAV_ES )
504     {
505         bool b;
506         es_out_Control( p_demux->out, ES_OUT_GET_ES_STATE, tk->p_es, &b );
507
508         if( !b )
509         {
510             tk->b_inited = false;
511             if( tk->fmt.i_cat == VIDEO_ES || tk->fmt.i_cat == AUDIO_ES )
512                 tk->i_last_dts = i_pts;
513             return;
514         }
515     }
516
517
518     /* First send init data */
519     if( !tk->b_inited && tk->i_data_init > 0 )
520     {
521         block_t *p_init;
522
523         msg_Dbg( p_demux, "sending header (%d bytes)", tk->i_data_init );
524         p_init = MemToBlock( tk->p_data_init, tk->i_data_init, 0 );
525         if( p_init ) es_out_Send( p_demux->out, tk->p_es, p_init );
526     }
527     tk->b_inited = true;
528
529
530     size_t frame_size = 0;
531     size_t block_size = 0;
532
533     if( simpleblock != NULL )
534         block_size = simpleblock->GetSize();
535     else
536         block_size = block->GetSize();
537  
538     for( unsigned int i = 0;
539          ( block != NULL && i < block->NumberFrames()) || ( simpleblock != NULL && i < simpleblock->NumberFrames() );
540          i++ )
541     {
542         block_t *p_block;
543         DataBuffer *data;
544         if( simpleblock != NULL )
545         {
546             data = &simpleblock->GetBuffer(i);
547             // condition when the DTS is correct (keyframe or B frame == NOT P frame)
548             f_mandatory = simpleblock->IsDiscardable() || simpleblock->IsKeyframe();
549         }
550         else
551         {
552             data = &block->GetBuffer(i);
553             // condition when the DTS is correct (keyframe or B frame == NOT P frame)
554         }
555         frame_size += data->Size();
556         if( !data->Buffer() || data->Size() > SIZE_MAX || frame_size > block_size  )
557         {
558             msg_Warn( p_demux, "Cannot read frame (too long or no frame)" );
559             break;
560         }
561
562         if( tk->i_compression_type == MATROSKA_COMPRESSION_HEADER &&
563             tk->p_compression_data != NULL &&
564             tk->i_encoding_scope & MATROSKA_ENCODING_SCOPE_ALL_FRAMES )
565             p_block = MemToBlock( data->Buffer(), data->Size(), tk->p_compression_data->GetSize() );
566         else if( unlikely( tk->fmt.i_codec == VLC_CODEC_WAVPACK ) )
567             p_block = packetize_wavpack(tk, data->Buffer(), data->Size());
568         else
569             p_block = MemToBlock( data->Buffer(), data->Size(), 0 );
570
571         if( p_block == NULL )
572         {
573             break;
574         }
575
576 #if defined(HAVE_ZLIB_H)
577         if( tk->i_compression_type == MATROSKA_COMPRESSION_ZLIB &&
578             tk->i_encoding_scope & MATROSKA_ENCODING_SCOPE_ALL_FRAMES )
579         {
580             p_block = block_zlib_decompress( VLC_OBJECT(p_demux), p_block );
581             if( p_block == NULL )
582                 break;
583         }
584         else
585 #endif
586         if( tk->i_compression_type == MATROSKA_COMPRESSION_HEADER &&
587             tk->i_encoding_scope & MATROSKA_ENCODING_SCOPE_ALL_FRAMES )
588         {
589             memcpy( p_block->p_buffer, tk->p_compression_data->GetBuffer(), tk->p_compression_data->GetSize() );
590         }
591         switch( tk->fmt.i_codec )
592         {
593         case VLC_CODEC_COOK:
594         case VLC_CODEC_ATRAC3:
595         {
596             handle_real_audio(p_demux, tk, p_block, i_pts);
597             block_Release(p_block);
598             i_pts = ( tk->i_default_duration )?
599                 i_pts + ( mtime_t )( tk->i_default_duration / 1000 ):
600                 VLC_TS_INVALID;
601             continue;
602          }
603          case VLC_CODEC_OPUS:
604             if( i_duration > 0 )
605             {
606                 mtime_t i_length = i_duration * tk-> f_timecodescale *
607                     (double) p_segment->i_timescale / 1000.0;
608                 p_block->i_nb_samples = i_length * tk->fmt.audio.i_rate
609                      / CLOCK_FREQ;
610                 break;
611             }
612             else if( i_duration < 0 )
613             {
614                 /* Opus uses p_block->i_length to handle discard padding */
615                 p_block->i_length = -1 * i_duration * tk->fmt.audio.i_rate
616                     / CLOCK_FREQ;
617             }
618             break;
619         }
620
621         
622         if( tk->fmt.i_cat != VIDEO_ES )
623         {
624             if ( tk->fmt.i_cat == NAV_ES )
625             {
626                 // TODO handle the start/stop times of this packet
627                 p_sys->p_ev->SetPci( (const pci_t *)&p_block->p_buffer[1]);
628                 block_Release( p_block );
629                 return;
630             }
631             else if( tk->fmt.i_cat == AUDIO_ES )
632             {
633                 if( tk->i_chans_to_reorder )
634                     aout_ChannelReorder( p_block->p_buffer, p_block->i_buffer,
635                                          tk->fmt.audio.i_channels,
636                                          tk->pi_chan_table, tk->fmt.i_codec );
637
638             }
639             p_block->i_dts = p_block->i_pts = i_pts;
640         }
641         else
642         {
643             // correct timestamping when B frames are used
644             if( tk->b_dts_only )
645             {
646                 p_block->i_pts = VLC_TS_INVALID;
647                 p_block->i_dts = i_pts;
648             }
649             else if( tk->b_pts_only )
650             {
651                 p_block->i_pts = i_pts;
652                 p_block->i_dts = i_pts;
653             }
654             else
655             {
656                 p_block->i_pts = i_pts;
657                 if ( f_mandatory )
658                     p_block->i_dts = p_block->i_pts;
659                 else
660                     p_block->i_dts = min( i_pts, tk->i_last_dts + ( mtime_t )( tk->i_default_duration / 1000 ) );
661             }
662         }
663         if( tk->fmt.i_cat == VIDEO_ES || tk->fmt.i_cat == AUDIO_ES )
664             tk->i_last_dts = p_block->i_dts;
665
666 #if 0
667 msg_Dbg( p_demux, "block i_dts: %"PRId64" / i_pts: %"PRId64, p_block->i_dts, p_block->i_pts);
668 #endif
669         if( !tk->b_no_duration )
670         {
671             p_block->i_length = i_duration * tk-> f_timecodescale *
672                 (double) p_segment->i_timescale / 1000.0;
673         }
674
675         /* FIXME remove when VLC_TS_INVALID work is done */
676         if( i == 0 || p_block->i_dts > VLC_TS_INVALID )
677             p_block->i_dts += VLC_TS_0;
678         if( !tk->b_dts_only && ( i == 0 || p_block->i_pts > VLC_TS_INVALID ) )
679             p_block->i_pts += VLC_TS_0;
680
681         es_out_Send( p_demux->out, tk->p_es, p_block );
682
683         /* use time stamp only for first block */
684         i_pts = ( tk->i_default_duration )?
685                  i_pts + ( mtime_t )( tk->i_default_duration / 1000 ):
686                  VLC_TS_INVALID;
687     }
688 }
689
690 /*****************************************************************************
691  * Demux: reads and demuxes data packets
692  *****************************************************************************
693  * Returns -1 in case of error, 0 in case of EOF, 1 otherwise
694  *****************************************************************************/
695 static int Demux( demux_t *p_demux)
696 {
697     demux_sys_t        *p_sys = p_demux->p_sys;
698
699     vlc_mutex_lock( &p_sys->lock_demuxer );
700
701     virtual_segment_c  *p_vsegment = p_sys->p_current_segment;
702     matroska_segment_c *p_segment = p_vsegment->CurrentSegment();
703     if ( p_segment == NULL )
704     {
705         vlc_mutex_unlock( &p_sys->lock_demuxer );
706         return 0;
707     }
708     int                i_block_count = 0;
709     int                i_return = 0;
710
711     for( ;; )
712     {
713         if( p_sys->i_pts >= p_sys->i_start_pts  )
714             if ( p_vsegment->UpdateCurrentToChapter( *p_demux ) )
715             {
716                 i_return = 1;
717                 break;
718             }
719
720         if ( p_vsegment->CurrentEdition() &&
721              p_vsegment->CurrentEdition()->b_ordered &&
722              p_vsegment->CurrentChapter() == NULL )
723             /* nothing left to read in this ordered edition */
724             break;
725
726         KaxBlock *block;
727         KaxSimpleBlock *simpleblock;
728         int64_t i_block_duration = 0;
729         bool b_key_picture;
730         bool b_discardable_picture;
731         if( p_segment->BlockGet( block, simpleblock, &b_key_picture, &b_discardable_picture, &i_block_duration ) )
732         {
733             if ( p_vsegment->CurrentEdition() && p_vsegment->CurrentEdition()->b_ordered )
734             {
735                 const virtual_chapter_c *p_chap = p_vsegment->CurrentChapter();
736                 // check if there are more chapters to read
737                 if ( p_chap != NULL )
738                 {
739                     /* TODO handle successive chapters with the same user_start_time/user_end_time
740                     */
741                     p_sys->i_pts = p_chap->i_virtual_stop_time;
742                     p_sys->i_pts++; // trick to avoid staying on segments with no duration and no content
743
744                     i_return = 1;
745                 }
746
747                 break;
748             }
749             else
750             {
751                 msg_Warn( p_demux, "cannot get block EOF?" );
752                 break;
753             }
754         }
755
756         if( simpleblock != NULL )
757             p_sys->i_pts = p_sys->i_chapter_time + ( (mtime_t)simpleblock->GlobalTimecode() / INT64_C(1000) );
758         else
759             p_sys->i_pts = p_sys->i_chapter_time + ( (mtime_t)block->GlobalTimecode() / INT64_C(1000) );
760
761         mtime_t i_pcr = VLC_TS_INVALID;
762         for( size_t i = 0; i < p_segment->tracks.size(); i++)
763             if( p_segment->tracks[i]->i_last_dts > VLC_TS_INVALID &&
764                 ( p_segment->tracks[i]->i_last_dts < i_pcr || i_pcr == VLC_TS_INVALID ))
765                 i_pcr = p_segment->tracks[i]->i_last_dts;
766
767         if( i_pcr > p_sys->i_pcr + 300000 )
768         {
769             es_out_Control( p_demux->out, ES_OUT_SET_PCR, VLC_TS_0 + p_sys->i_pcr );
770             p_sys->i_pcr = i_pcr;
771         }
772
773         if( p_sys->i_pts >= p_sys->i_start_pts  )
774         {
775             if ( p_vsegment->UpdateCurrentToChapter( *p_demux ) )
776             {
777                 i_return = 1;
778                 delete block;
779                 break;
780             }
781         }
782
783         if ( p_vsegment->CurrentEdition() &&
784              p_vsegment->CurrentEdition()->b_ordered &&
785              p_vsegment->CurrentChapter() == NULL )
786         {
787             /* nothing left to read in this ordered edition */
788             delete block;
789             break;
790         }
791
792         BlockDecode( p_demux, block, simpleblock, p_sys->i_pts, i_block_duration, b_key_picture || b_discardable_picture );
793
794         delete block;
795         i_block_count++;
796
797         // TODO optimize when there is need to leave or when seeking has been called
798         if( i_block_count > 5 )
799         {
800             i_return = 1;
801             break;
802         }
803     }
804
805     vlc_mutex_unlock( &p_sys->lock_demuxer );
806
807     return i_return;
808 }
809