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