]> git.sesse.net Git - vlc/blob - modules/demux/mkv/mkv.cpp
MKV: Don't delete es at EOF in Demux() but in Close()
[vlc] / modules / demux / mkv / mkv.cpp
1 /*****************************************************************************
2  * mkv.cpp : matroska demuxer
3  *****************************************************************************
4  * Copyright (C) 2003-2005, 2008, 2010 the VideoLAN team
5  * $Id$
6  *
7  * Authors: Laurent Aimar <fenrir@via.ecp.fr>
8  *          Steve Lhomme <steve.lhomme@free.fr>
9  *
10  * This program is free software; you can redistribute it and/or modify
11  * it under the terms of the GNU General Public License as published by
12  * the Free Software Foundation; either version 2 of the License, or
13  * (at your option) any later version.
14  *
15  * This program is distributed in the hope that it will be useful,
16  * but WITHOUT ANY WARRANTY; without even the implied warranty of
17  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
18  * GNU General Public License for more details.
19  *
20  * You should have received a copy of the GNU General Public License
21  * along with this program; if not, write to the Free Software
22  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA.
23  *****************************************************************************/
24
25 #include "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", false,
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
96     /* peek the begining */
97     if( stream_Peek( p_demux->s, &p_peek, 4 ) < 4 ) return VLC_EGENERIC;
98
99     /* is a valid file */
100     if( p_peek[0] != 0x1a || p_peek[1] != 0x45 ||
101         p_peek[2] != 0xdf || p_peek[3] != 0xa3 ) return VLC_EGENERIC;
102
103     /* Set the demux function */
104     p_demux->pf_demux   = Demux;
105     p_demux->pf_control = Control;
106     p_demux->p_sys      = p_sys = new demux_sys_t( *p_demux );
107
108     p_io_callback = new vlc_stream_io_callback( p_demux->s, false );
109     p_io_stream = new EbmlStream( *p_io_callback );
110
111     if( p_io_stream == NULL )
112     {
113         msg_Err( p_demux, "failed to create EbmlStream" );
114         delete p_io_callback;
115         delete p_sys;
116         return VLC_EGENERIC;
117     }
118
119     p_stream = p_sys->AnalyseAllSegmentsFound( p_demux, p_io_stream, true );
120     if( p_stream == NULL )
121     {
122         msg_Err( p_demux, "cannot find KaxSegment or missing mandatory KaxInfo" );
123         goto error;
124     }
125     p_sys->streams.push_back( p_stream );
126
127     p_stream->p_io_callback = p_io_callback;
128     p_stream->p_estream = p_io_stream;
129
130     for (size_t i=0; i<p_stream->segments.size(); i++)
131     {
132         p_stream->segments[i]->Preload();
133     }
134
135     p_segment = p_stream->segments[0];
136     if( p_segment->cluster == NULL )
137     {
138         msg_Err( p_demux, "cannot find any cluster, damaged file ?" );
139         goto error;
140     }
141
142     if (var_InheritBool( p_demux, "mkv-preload-local-dir" ))
143     {
144         /* get the files from the same dir from the same family (based on p_demux->psz_path) */
145         if ( p_demux->psz_file && !strcmp( p_demux->psz_access, "file" ) )
146         {
147             // assume it's a regular file
148             // get the directory path
149             s_path = p_demux->psz_file;
150             if (s_path.at(s_path.length() - 1) == DIR_SEP_CHAR)
151             {
152                 s_path = s_path.substr(0,s_path.length()-1);
153             }
154             else
155             {
156                 if (s_path.find_last_of(DIR_SEP_CHAR) > 0)
157                 {
158                     s_path = s_path.substr(0,s_path.find_last_of(DIR_SEP_CHAR));
159                 }
160             }
161
162             DIR *p_src_dir = vlc_opendir(s_path.c_str());
163
164             if (p_src_dir != NULL)
165             {
166                 char *psz_file;
167                 while ((psz_file = vlc_readdir(p_src_dir)) != NULL)
168                 {
169                     if (strlen(psz_file) > 4)
170                     {
171                         s_filename = s_path + DIR_SEP_CHAR + psz_file;
172
173 #ifdef WIN32
174                         if (!strcasecmp(s_filename.c_str(), p_demux->psz_file))
175 #else
176                         if (!s_filename.compare(p_demux->psz_file))
177 #endif
178                         {
179                             free (psz_file);
180                             continue; // don't reuse the original opened file
181                         }
182
183                         if (!s_filename.compare(s_filename.length() - 3, 3, "mkv") ||
184                             !s_filename.compare(s_filename.length() - 3, 3, "mka"))
185                         {
186                             // test wether this file belongs to our family
187                             const uint8_t *p_peek;
188                             bool          file_ok = false;
189                             std::string   s_url = make_URI( s_filename.c_str(), "file" );
190                             stream_t      *p_file_stream = stream_UrlNew(
191                                                             p_demux,
192                                                             s_url.c_str() );
193                             /* peek the begining */
194                             if( p_file_stream &&
195                                 stream_Peek( p_file_stream, &p_peek, 4 ) >= 4
196                                 && p_peek[0] == 0x1a && p_peek[1] == 0x45 &&
197                                 p_peek[2] == 0xdf && p_peek[3] == 0xa3 ) file_ok = true;
198
199                             if ( file_ok )
200                             {
201                                 vlc_stream_io_callback *p_file_io = new vlc_stream_io_callback( p_file_stream, true );
202                                 EbmlStream *p_estream = new EbmlStream(*p_file_io);
203
204                                 p_stream = p_sys->AnalyseAllSegmentsFound( p_demux, p_estream );
205
206                                 if ( p_stream == NULL )
207                                 {
208                                     msg_Dbg( p_demux, "the file '%s' will not be used", s_filename.c_str() );
209                                     delete p_estream;
210                                     delete p_file_io;
211                                 }
212                                 else
213                                 {
214                                     p_stream->p_io_callback = p_file_io;
215                                     p_stream->p_estream = p_estream;
216                                     p_sys->streams.push_back( p_stream );
217                                 }
218                             }
219                             else
220                             {
221                                 if( p_file_stream ) {
222                                     stream_Delete( p_file_stream );
223                                 }
224                                 msg_Dbg( p_demux, "the file '%s' cannot be opened", s_filename.c_str() );
225                             }
226                         }
227                     }
228                     free (psz_file);
229                 }
230                 closedir( p_src_dir );
231             }
232         }
233
234         p_sys->PreloadFamily( *p_segment );
235     }
236
237     if ( !p_sys->PreloadLinked() ||
238          !p_sys->PreparePlayback( NULL ) )
239     {
240         msg_Err( p_demux, "cannot use the segment" );
241         goto error;
242     }
243
244     p_sys->InitUi();
245
246     return VLC_SUCCESS;
247
248 error:
249     delete p_sys;
250     return VLC_EGENERIC;
251 }
252
253 /*****************************************************************************
254  * Close: frees unused data
255  *****************************************************************************/
256 static void Close( vlc_object_t *p_this )
257 {
258     demux_t     *p_demux = (demux_t*)p_this;
259     demux_sys_t *p_sys   = p_demux->p_sys;
260     virtual_segment_c *p_vsegment = p_sys->p_current_segment;
261     if( p_vsegment )
262     {
263         matroska_segment_c *p_segment = p_vsegment->CurrentSegment();
264         if( p_segment )
265             p_segment->UnSelect();
266     }
267
268     delete p_sys;
269 }
270
271 /*****************************************************************************
272  * Control:
273  *****************************************************************************/
274 static int Control( demux_t *p_demux, int i_query, va_list args )
275 {
276     demux_sys_t        *p_sys = p_demux->p_sys;
277     int64_t     *pi64, i64;
278     double      *pf, f;
279     int         i_skp;
280     size_t      i_idx;
281
282     vlc_meta_t *p_meta;
283     input_attachment_t ***ppp_attach;
284     int *pi_int;
285
286     switch( i_query )
287     {
288         case DEMUX_GET_ATTACHMENTS:
289             ppp_attach = (input_attachment_t***)va_arg( args, input_attachment_t*** );
290             pi_int = (int*)va_arg( args, int * );
291
292             if( p_sys->stored_attachments.size() <= 0 )
293                 return VLC_EGENERIC;
294
295             *pi_int = p_sys->stored_attachments.size();
296             *ppp_attach = (input_attachment_t**)malloc( sizeof(input_attachment_t**) *
297                                                         p_sys->stored_attachments.size() );
298             if( !(*ppp_attach) )
299                 return VLC_ENOMEM;
300             for( size_t i = 0; i < p_sys->stored_attachments.size(); i++ )
301             {
302                 attachment_c *a = p_sys->stored_attachments[i];
303                 (*ppp_attach)[i] = vlc_input_attachment_New( a->fileName(), a->mimeType(), NULL,
304                                                              a->p_data, a->size() );
305             }
306             return VLC_SUCCESS;
307
308         case DEMUX_GET_META:
309             p_meta = (vlc_meta_t*)va_arg( args, vlc_meta_t* );
310             vlc_meta_Merge( p_meta, p_sys->meta );
311             return VLC_SUCCESS;
312
313         case DEMUX_GET_LENGTH:
314             pi64 = (int64_t*)va_arg( args, int64_t * );
315             if( p_sys->f_duration > 0.0 )
316             {
317                 *pi64 = (int64_t)(p_sys->f_duration * 1000);
318                 return VLC_SUCCESS;
319             }
320             return VLC_EGENERIC;
321
322         case DEMUX_GET_POSITION:
323             pf = (double*)va_arg( args, double * );
324             if ( p_sys->f_duration > 0.0 )
325                 *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);
326             return VLC_SUCCESS;
327
328         case DEMUX_SET_POSITION:
329             f = (double)va_arg( args, double );
330             Seek( p_demux, -1, f, NULL );
331             return VLC_SUCCESS;
332
333         case DEMUX_GET_TIME:
334             pi64 = (int64_t*)va_arg( args, int64_t * );
335             *pi64 = p_sys->i_pts;
336             return VLC_SUCCESS;
337
338         case DEMUX_GET_TITLE_INFO:
339             if( p_sys->titles.size() > 1 || ( p_sys->titles.size() == 1 && p_sys->titles[0]->i_seekpoint > 0 ) )
340             {
341                 input_title_t ***ppp_title = (input_title_t***)va_arg( args, input_title_t*** );
342                 int *pi_int    = (int*)va_arg( args, int* );
343
344                 *pi_int = p_sys->titles.size();
345                 *ppp_title = (input_title_t**)malloc( sizeof( input_title_t**) * p_sys->titles.size() );
346
347                 for( size_t i = 0; i < p_sys->titles.size(); i++ )
348                 {
349                     (*ppp_title)[i] = vlc_input_title_Duplicate( p_sys->titles[i] );
350                 }
351                 return VLC_SUCCESS;
352             }
353             return VLC_EGENERIC;
354
355         case DEMUX_SET_TITLE:
356             /* TODO handle editions as titles */
357             i_idx = (int)va_arg( args, int );
358             if( i_idx < p_sys->used_segments.size() )
359             {
360                 p_sys->JumpTo( *p_sys->used_segments[i_idx], NULL );
361                 return VLC_SUCCESS;
362             }
363             return VLC_EGENERIC;
364
365         case DEMUX_SET_SEEKPOINT:
366             i_skp = (int)va_arg( args, int );
367
368             // TODO change the way it works with the << & >> buttons on the UI (+1/-1 instead of a number)
369             if( p_sys->titles.size() && i_skp < p_sys->titles[p_sys->i_current_title]->i_seekpoint)
370             {
371                 Seek( p_demux, (int64_t)p_sys->titles[p_sys->i_current_title]->seekpoint[i_skp]->i_time_offset, -1, NULL);
372                 p_demux->info.i_seekpoint |= INPUT_UPDATE_SEEKPOINT;
373                 p_demux->info.i_seekpoint = i_skp;
374                 return VLC_SUCCESS;
375             }
376             return VLC_EGENERIC;
377
378         case DEMUX_GET_FPS:
379             pf = (double *)va_arg( args, double * );
380             *pf = 0.0;
381             if( p_sys->p_current_segment && p_sys->p_current_segment->CurrentSegment() )
382             {
383                 const matroska_segment_c *p_segment = p_sys->p_current_segment->CurrentSegment();
384                 for( size_t i = 0; i < p_segment->tracks.size(); i++ )
385                 {
386                     mkv_track_t *tk = p_segment->tracks[i];
387                     if( tk->fmt.i_cat == VIDEO_ES && tk->fmt.video.i_frame_rate_base > 0 )
388                     {
389                         *pf = (double)tk->fmt.video.i_frame_rate / tk->fmt.video.i_frame_rate_base;
390                         break;
391                     }
392                 }
393             }
394             return VLC_SUCCESS;
395
396         case DEMUX_SET_TIME:
397             i64 = (int64_t) va_arg( args, int64_t );
398             msg_Dbg(p_demux,"SET_TIME to %"PRId64, i64 );
399             Seek( p_demux, i64, -1, NULL );
400             return VLC_SUCCESS;
401         default:
402             return VLC_EGENERIC;
403     }
404 }
405
406 /* Seek */
407 static void Seek( demux_t *p_demux, mtime_t i_date, double f_percent, virtual_chapter_c *p_chapter )
408 {
409     demux_sys_t        *p_sys = p_demux->p_sys;
410     virtual_segment_c  *p_vsegment = p_sys->p_current_segment;
411     matroska_segment_c *p_segment = p_vsegment->CurrentSegment();
412     mtime_t            i_time_offset = 0;
413     int64_t            i_global_position = -1;
414
415     int         i_index;
416
417     msg_Dbg( p_demux, "seek request to %"PRId64" (%f%%)", i_date, f_percent );
418     if( i_date < 0 && f_percent < 0 )
419     {
420         msg_Warn( p_demux, "cannot seek nowhere!" );
421         return;
422     }
423     if( f_percent > 1.0 )
424     {
425         msg_Warn( p_demux, "cannot seek so far!" );
426         return;
427     }
428     if( p_sys->f_duration < 0 )
429     {
430         msg_Warn( p_demux, "cannot seek without duration!");
431         return;
432     }
433
434     /* seek without index or without date */
435     if( f_percent >= 0 && (var_InheritBool( p_demux, "mkv-seek-percent" ) || !p_segment->b_cues || i_date < 0 ))
436     {
437         i_date = int64_t( f_percent * p_sys->f_duration * 1000.0 );
438         if( !p_segment->b_cues )
439         {
440             int64_t i_pos = int64_t( f_percent * stream_Size( p_demux->s ) );
441
442             msg_Dbg( p_demux, "lengthy way of seeking for pos:%"PRId64, i_pos );
443             for( i_index = 0; i_index < p_segment->i_index; i_index++ )
444             {
445                 if( p_segment->p_indexes[i_index].i_position >= i_pos &&
446                     p_segment->p_indexes[i_index].i_time > 0 )
447                     break;
448             }
449             if( i_index == p_segment->i_index )
450                 i_index--;
451
452             if( p_segment->p_indexes[i_index].i_position < i_pos )
453             {
454                 msg_Dbg( p_demux, "no cues, seek request to global pos: %"PRId64, i_pos );
455                 i_global_position = i_pos;
456             }
457         }
458     }
459     p_vsegment->Seek( *p_demux, i_date, i_time_offset, p_chapter, i_global_position );
460 }
461
462 /* Utility function for BlockDecode */
463 static block_t *MemToBlock( uint8_t *p_mem, size_t i_mem, size_t offset)
464 {
465     if( unlikely( i_mem > SIZE_MAX - offset ) )
466         return NULL;
467
468     block_t *p_block = block_New( p_demux, i_mem + offset );
469     if( likely(p_block != NULL) )
470     {
471         memcpy( p_block->p_buffer + offset, p_mem, i_mem );
472     }
473     return p_block;
474 }
475
476 /* Needed by matroska_segment::Seek() and Seek */
477 void BlockDecode( demux_t *p_demux, KaxBlock *block, KaxSimpleBlock *simpleblock,
478                          mtime_t i_pts, mtime_t i_duration, bool f_mandatory )
479 {
480     demux_sys_t        *p_sys = p_demux->p_sys;
481     matroska_segment_c *p_segment = p_sys->p_current_segment->CurrentSegment();
482
483     if( !p_segment ) return;
484
485     size_t          i_track;
486     if( p_segment->BlockFindTrackIndex( &i_track, block, simpleblock ) )
487     {
488         msg_Err( p_demux, "invalid track number" );
489         return;
490     }
491
492     mkv_track_t *tk = p_segment->tracks[i_track];
493
494     if( tk->fmt.i_cat != NAV_ES && tk->p_es == NULL )
495     {
496         msg_Err( p_demux, "unknown track number" );
497         return;
498     }
499     if( i_pts + i_duration < p_sys->i_start_pts && tk->fmt.i_cat == AUDIO_ES )
500     {
501         return; /* discard audio packets that shouldn't be rendered */
502     }
503
504     if ( tk->fmt.i_cat != NAV_ES )
505     {
506         bool b;
507         es_out_Control( p_demux->out, ES_OUT_GET_ES_STATE, tk->p_es, &b );
508
509         if( !b )
510         {
511             tk->b_inited = false;
512             return;
513         }
514     }
515
516
517     /* First send init data */
518     if( !tk->b_inited && tk->i_data_init > 0 )
519     {
520         block_t *p_init;
521
522         msg_Dbg( p_demux, "sending header (%d bytes)", tk->i_data_init );
523         p_init = MemToBlock( tk->p_data_init, tk->i_data_init, 0 );
524         if( p_init ) es_out_Send( p_demux->out, tk->p_es, p_init );
525     }
526     tk->b_inited = true;
527
528
529     size_t frame_size = 0;
530     size_t block_size = 0;
531
532     if( simpleblock != NULL )
533         block_size = simpleblock->GetSize();
534     else
535         block_size = block->GetSize();
536  
537     for( unsigned int i = 0;
538          ( block != NULL && i < block->NumberFrames()) || ( simpleblock != NULL && i < simpleblock->NumberFrames() );
539          i++ )
540     {
541         block_t *p_block;
542         DataBuffer *data;
543         if( simpleblock != NULL )
544         {
545             data = &simpleblock->GetBuffer(i);
546             // condition when the DTS is correct (keyframe or B frame == NOT P frame)
547             f_mandatory = simpleblock->IsDiscardable() || simpleblock->IsKeyframe();
548         }
549         else
550         {
551             data = &block->GetBuffer(i);
552             // condition when the DTS is correct (keyframe or B frame == NOT P frame)
553         }
554         frame_size += data->Size();
555         if( !data->Buffer() || data->Size() > SIZE_MAX || frame_size > block_size  )
556         {
557             msg_Warn( p_demux, "Cannot read frame (too long or no frame)" );
558             break;
559         }
560
561         if( tk->i_compression_type == MATROSKA_COMPRESSION_HEADER && tk->p_compression_data != NULL )
562             p_block = MemToBlock( data->Buffer(), data->Size(), tk->p_compression_data->GetSize() );
563         else
564             p_block = MemToBlock( data->Buffer(), data->Size(), 0 );
565
566         if( p_block == NULL )
567         {
568             break;
569         }
570
571 #if defined(HAVE_ZLIB_H)
572         if( tk->i_compression_type == MATROSKA_COMPRESSION_ZLIB )
573         {
574             p_block = block_zlib_decompress( VLC_OBJECT(p_demux), p_block );
575             if( p_block == NULL )
576                 break;
577         }
578         else
579 #endif
580         if( tk->i_compression_type == MATROSKA_COMPRESSION_HEADER )
581         {
582             memcpy( p_block->p_buffer, tk->p_compression_data->GetBuffer(), tk->p_compression_data->GetSize() );
583         }
584
585         if ( tk->fmt.i_cat == NAV_ES )
586         {
587             // TODO handle the start/stop times of this packet
588             p_sys->p_ev->SetPci( (const pci_t *)&p_block->p_buffer[1]);
589             block_Release( p_block );
590             return;
591         }
592         // correct timestamping when B frames are used
593         if( tk->fmt.i_cat != VIDEO_ES )
594         {
595             p_block->i_dts = p_block->i_pts = i_pts;
596         }
597         else
598         {
599             if( tk->b_dts_only )
600             {
601                 p_block->i_pts = VLC_TS_INVALID;
602                 p_block->i_dts = i_pts;
603             }
604             else if( tk->b_pts_only )
605             {
606                 p_block->i_pts = i_pts;
607                 p_block->i_dts = i_pts;
608             }
609             else
610             {
611                 p_block->i_pts = i_pts;
612                 if ( f_mandatory )
613                     p_block->i_dts = p_block->i_pts;
614                 else
615                     p_block->i_dts = min( i_pts, tk->i_last_dts + (mtime_t)(tk->i_default_duration >> 10));
616             }
617         }
618         tk->i_last_dts = p_block->i_dts;
619
620 #if 0
621 msg_Dbg( p_demux, "block i_dts: %"PRId64" / i_pts: %"PRId64, p_block->i_dts, p_block->i_pts);
622 #endif
623         if( strcmp( tk->psz_codec, "S_VOBSUB" ) )
624         {
625             p_block->i_length = i_duration * 1000;
626         }
627
628         /* FIXME remove when VLC_TS_INVALID work is done */
629         if( i == 0 || p_block->i_dts > VLC_TS_INVALID )
630             p_block->i_dts += VLC_TS_0;
631         if( !tk->b_dts_only && ( i == 0 || p_block->i_pts > VLC_TS_INVALID ) )
632             p_block->i_pts += VLC_TS_0;
633
634         es_out_Send( p_demux->out, tk->p_es, p_block );
635
636         /* use time stamp only for first block */
637         i_pts = VLC_TS_INVALID;
638     }
639 }
640
641 /*****************************************************************************
642  * Demux: reads and demuxes data packets
643  *****************************************************************************
644  * Returns -1 in case of error, 0 in case of EOF, 1 otherwise
645  *****************************************************************************/
646 static int Demux( demux_t *p_demux)
647 {
648     demux_sys_t        *p_sys = p_demux->p_sys;
649
650     vlc_mutex_lock( &p_sys->lock_demuxer );
651
652     virtual_segment_c  *p_vsegment = p_sys->p_current_segment;
653     matroska_segment_c *p_segment = p_vsegment->CurrentSegment();
654     if ( p_segment == NULL ) return 0;
655     int                i_block_count = 0;
656     int                i_return = 0;
657
658     for( ;; )
659     {
660         if ( p_sys->demuxer.b_die )
661             break;
662
663         if( p_sys->i_pts >= p_sys->i_start_pts  )
664             if ( p_vsegment->UpdateCurrentToChapter( *p_demux ) )
665             {
666                 i_return = 1;
667                 break;
668             }
669
670         if ( p_vsegment->CurrentEdition() &&
671              p_vsegment->CurrentEdition()->b_ordered &&
672              p_vsegment->CurrentChapter() == NULL )
673             /* nothing left to read in this ordered edition */
674             break;
675
676         KaxBlock *block;
677         KaxSimpleBlock *simpleblock;
678         int64_t i_block_duration = 0;
679         bool b_key_picture;
680         bool b_discardable_picture;
681         if( p_segment->BlockGet( block, simpleblock, &b_key_picture, &b_discardable_picture, &i_block_duration ) )
682         {
683             if ( p_vsegment->CurrentEdition() && p_vsegment->CurrentEdition()->b_ordered )
684             {
685                 const virtual_chapter_c *p_chap = p_vsegment->CurrentChapter();
686                 // check if there are more chapters to read
687                 if ( p_chap != NULL )
688                 {
689                     /* TODO handle successive chapters with the same user_start_time/user_end_time
690                     */
691                     p_sys->i_pts = p_chap->i_virtual_stop_time;
692                     p_sys->i_pts++; // trick to avoid staying on segments with no duration and no content
693
694                     i_return = 1;
695                 }
696
697                 break;
698             }
699             else
700             {
701                 msg_Warn( p_demux, "cannot get block EOF?" );
702                 es_out_Control( p_demux->out, ES_OUT_RESET_PCR );
703                 break;
704             }
705         }
706
707         if( simpleblock != NULL )
708             p_sys->i_pts = p_sys->i_chapter_time + ( simpleblock->GlobalTimecode() / (mtime_t) 1000 );
709         else
710             p_sys->i_pts = p_sys->i_chapter_time + ( block->GlobalTimecode() / (mtime_t) 1000 );
711
712         /* The blocks are in coding order so we can safely consider that only references are in chronological order */
713         if( simpleblock == NULL || b_key_picture )
714             es_out_Control( p_demux->out, ES_OUT_SET_PCR, VLC_TS_0 + p_sys->i_pts );
715
716         if( p_sys->i_pts >= p_sys->i_start_pts  )
717         {
718             if ( p_vsegment->UpdateCurrentToChapter( *p_demux ) )
719             {
720                 i_return = 1;
721                 delete block;
722                 break;
723             }
724         }
725
726         if ( p_vsegment->CurrentEdition() &&
727              p_vsegment->CurrentEdition()->b_ordered &&
728              p_vsegment->CurrentChapter() == NULL )
729         {
730             /* nothing left to read in this ordered edition */
731             delete block;
732             break;
733         }
734
735         BlockDecode( p_demux, block, simpleblock, p_sys->i_pts, i_block_duration, b_key_picture || b_discardable_picture );
736
737         delete block;
738         i_block_count++;
739
740         // TODO optimize when there is need to leave or when seeking has been called
741         if( i_block_count > 5 )
742         {
743             i_return = 1;
744             break;
745         }
746     }
747
748     vlc_mutex_unlock( &p_sys->lock_demuxer );
749
750     return i_return;
751 }
752