]> git.sesse.net Git - vlc/blob - modules/demux/mkv/mkv.cpp
var_InheritInteger -> var_InheritBool
[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
38 /*****************************************************************************
39  * Module descriptor
40  *****************************************************************************/
41 static int  Open ( vlc_object_t * );
42 static void Close( vlc_object_t * );
43
44 vlc_module_begin ()
45     set_shortname( "Matroska" )
46     set_description( N_("Matroska stream demuxer" ) )
47     set_capability( "demux", 50 )
48     set_callbacks( Open, Close )
49     set_category( CAT_INPUT )
50     set_subcategory( SUBCAT_INPUT_DEMUX )
51
52     add_bool( "mkv-use-ordered-chapters", true, NULL,
53             N_("Ordered chapters"),
54             N_("Play ordered chapters as specified in the segment."), true );
55
56     add_bool( "mkv-use-chapter-codec", true, NULL,
57             N_("Chapter codecs"),
58             N_("Use chapter codecs found in the segment."), true );
59
60     add_bool( "mkv-preload-local-dir", false, NULL,
61             N_("Preload Directory"),
62             N_("Preload matroska files from the same family in the same directory (not good for broken files)."), true );
63
64     add_bool( "mkv-seek-percent", false, NULL,
65             N_("Seek based on percent not time"),
66             N_("Seek based on percent not time."), true );
67
68     add_bool( "mkv-use-dummy", false, NULL,
69             N_("Dummy Elements"),
70             N_("Read and discard unknown EBML elements (not good for broken files)."), true );
71
72     add_shortcut( "mka" )
73     add_shortcut( "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, chapter_item_c *psz_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" );
123         goto error;
124     }
125     p_sys->streams.push_back( p_stream );
126
127     p_stream->p_in = p_io_callback;
128     p_stream->p_es = 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_path[0] != '\0' && !strcmp(p_demux->psz_access, ""))
146         {
147             // assume it's a regular file
148             // get the directory path
149             s_path = p_demux->psz_path;
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_path))
175 #else
176                         if (!s_filename.compare(p_demux->psz_path))
177 #endif
178                         {
179                             free (psz_file);
180                             continue; // don't reuse the original opened file
181                         }
182
183 #if defined(__GNUC__) && (__GNUC__ < 3)
184                         if (!s_filename.compare("mkv", s_filename.length() - 3, 3) ||
185                             !s_filename.compare("mka", s_filename.length() - 3, 3))
186 #else
187                         if (!s_filename.compare(s_filename.length() - 3, 3, "mkv") ||
188                             !s_filename.compare(s_filename.length() - 3, 3, "mka"))
189 #endif
190                         {
191                             // test wether this file belongs to our family
192                             const uint8_t *p_peek;
193                             bool          file_ok = false;
194                             stream_t      *p_file_stream = stream_UrlNew(
195                                                             p_demux,
196                                                             s_filename.c_str());
197                             /* peek the begining */
198                             if( p_file_stream &&
199                                 stream_Peek( p_file_stream, &p_peek, 4 ) >= 4
200                                 && p_peek[0] == 0x1a && p_peek[1] == 0x45 &&
201                                 p_peek[2] == 0xdf && p_peek[3] == 0xa3 ) file_ok = true;
202
203                             if ( file_ok )
204                             {
205                                 vlc_stream_io_callback *p_file_io = new vlc_stream_io_callback( p_file_stream, true );
206                                 EbmlStream *p_estream = new EbmlStream(*p_file_io);
207
208                                 p_stream = p_sys->AnalyseAllSegmentsFound( p_demux, p_estream );
209
210                                 if ( p_stream == NULL )
211                                 {
212                                     msg_Dbg( p_demux, "the file '%s' will not be used", s_filename.c_str() );
213                                     delete p_estream;
214                                     delete p_file_io;
215                                 }
216                                 else
217                                 {
218                                     p_stream->p_in = p_file_io;
219                                     p_stream->p_es = p_estream;
220                                     p_sys->streams.push_back( p_stream );
221                                 }
222                             }
223                             else
224                             {
225                                 if( p_file_stream ) {
226                                     stream_Delete( p_file_stream );
227                                 }
228                                 msg_Dbg( p_demux, "the file '%s' cannot be opened", s_filename.c_str() );
229                             }
230                         }
231                     }
232                     free (psz_file);
233                 }
234                 closedir( p_src_dir );
235             }
236         }
237
238         p_sys->PreloadFamily( *p_segment );
239     }
240
241     p_sys->PreloadLinked( p_segment );
242
243     if ( !p_sys->PreparePlayback( NULL ) )
244     {
245         msg_Err( p_demux, "cannot use the segment" );
246         goto error;
247     }
248
249     p_sys->StartUiThread();
250  
251     return VLC_SUCCESS;
252
253 error:
254     delete p_sys;
255     return VLC_EGENERIC;
256 }
257
258 /*****************************************************************************
259  * Close: frees unused data
260  *****************************************************************************/
261 static void Close( vlc_object_t *p_this )
262 {
263     demux_t     *p_demux = (demux_t*)p_this;
264     demux_sys_t *p_sys   = p_demux->p_sys;
265
266     delete p_sys;
267 }
268
269 /*****************************************************************************
270  * Control:
271  *****************************************************************************/
272 static int Control( demux_t *p_demux, int i_query, va_list args )
273 {
274     demux_sys_t        *p_sys = p_demux->p_sys;
275     int64_t     *pi64;
276     double      *pf, f;
277     int         i_skp;
278     size_t      i_idx;
279
280     vlc_meta_t *p_meta;
281     input_attachment_t ***ppp_attach;
282     int *pi_int;
283
284     switch( i_query )
285     {
286         case DEMUX_GET_ATTACHMENTS:
287             ppp_attach = (input_attachment_t***)va_arg( args, input_attachment_t*** );
288             pi_int = (int*)va_arg( args, int * );
289
290             if( p_sys->stored_attachments.size() <= 0 )
291                 return VLC_EGENERIC;
292
293             *pi_int = p_sys->stored_attachments.size();
294             *ppp_attach = (input_attachment_t**)malloc( sizeof(input_attachment_t**) *
295                                                         p_sys->stored_attachments.size() );
296             if( !(*ppp_attach) )
297                 return VLC_ENOMEM;
298             for( size_t i = 0; i < p_sys->stored_attachments.size(); i++ )
299             {
300                 attachment_c *a = p_sys->stored_attachments[i];
301                 (*ppp_attach)[i] = vlc_input_attachment_New( a->psz_file_name.c_str(), a->psz_mime_type.c_str(), NULL,
302                                                              a->p_data, a->i_size );
303             }
304             return VLC_SUCCESS;
305
306         case DEMUX_GET_META:
307             p_meta = (vlc_meta_t*)va_arg( args, vlc_meta_t* );
308             vlc_meta_Merge( p_meta, p_sys->meta );
309             return VLC_SUCCESS;
310
311         case DEMUX_GET_LENGTH:
312             pi64 = (int64_t*)va_arg( args, int64_t * );
313             if( p_sys->f_duration > 0.0 )
314             {
315                 *pi64 = (int64_t)(p_sys->f_duration * 1000);
316                 return VLC_SUCCESS;
317             }
318             return VLC_EGENERIC;
319
320         case DEMUX_GET_POSITION:
321             pf = (double*)va_arg( args, double * );
322             if ( p_sys->f_duration > 0.0 )
323                 *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);
324             return VLC_SUCCESS;
325
326         case DEMUX_SET_POSITION:
327             f = (double)va_arg( args, double );
328             Seek( p_demux, -1, f, NULL );
329             return VLC_SUCCESS;
330
331         case DEMUX_GET_TIME:
332             pi64 = (int64_t*)va_arg( args, int64_t * );
333             *pi64 = p_sys->i_pts;
334             return VLC_SUCCESS;
335
336         case DEMUX_GET_TITLE_INFO:
337             if( p_sys->titles.size() > 1 || ( p_sys->titles.size() == 1 && p_sys->titles[0]->i_seekpoint > 0 ) )
338             {
339                 input_title_t ***ppp_title = (input_title_t***)va_arg( args, input_title_t*** );
340                 int *pi_int    = (int*)va_arg( args, int* );
341
342                 *pi_int = p_sys->titles.size();
343                 *ppp_title = (input_title_t**)malloc( sizeof( input_title_t**) * p_sys->titles.size() );
344
345                 for( size_t i = 0; i < p_sys->titles.size(); i++ )
346                 {
347                     (*ppp_title)[i] = vlc_input_title_Duplicate( p_sys->titles[i] );
348                 }
349                 return VLC_SUCCESS;
350             }
351             return VLC_EGENERIC;
352
353         case DEMUX_SET_TITLE:
354             /* TODO handle editions as titles */
355             i_idx = (int)va_arg( args, int );
356             if( i_idx < p_sys->used_segments.size() )
357             {
358                 p_sys->JumpTo( *p_sys->used_segments[i_idx], NULL );
359                 return VLC_SUCCESS;
360             }
361             return VLC_EGENERIC;
362
363         case DEMUX_SET_SEEKPOINT:
364             i_skp = (int)va_arg( args, int );
365
366             // TODO change the way it works with the << & >> buttons on the UI (+1/-1 instead of a number)
367             if( p_sys->titles.size() && i_skp < p_sys->titles[p_sys->i_current_title]->i_seekpoint)
368             {
369                 Seek( p_demux, (int64_t)p_sys->titles[p_sys->i_current_title]->seekpoint[i_skp]->i_time_offset, -1, NULL);
370                 p_demux->info.i_seekpoint |= INPUT_UPDATE_SEEKPOINT;
371                 p_demux->info.i_seekpoint = i_skp;
372                 return VLC_SUCCESS;
373             }
374             return VLC_EGENERIC;
375
376         case DEMUX_GET_FPS:
377             pf = (double *)va_arg( args, double * );
378             *pf = 0.0;
379             if( p_sys->p_current_segment && p_sys->p_current_segment->Segment() )
380             {
381                 const matroska_segment_c *p_segment = p_sys->p_current_segment->Segment();
382                 for( size_t i = 0; i < p_segment->tracks.size(); i++ )
383                 {
384                     mkv_track_t *tk = p_segment->tracks[i];
385                     if( tk->fmt.i_cat == VIDEO_ES && tk->fmt.video.i_frame_rate_base > 0 )
386                     {
387                         *pf = (double)tk->fmt.video.i_frame_rate / tk->fmt.video.i_frame_rate_base;
388                         break;
389                     }
390                 }
391             }
392             return VLC_SUCCESS;
393
394         case DEMUX_SET_TIME:
395         default:
396             return VLC_EGENERIC;
397     }
398 }
399
400 /* Seek */
401 static void Seek( demux_t *p_demux, mtime_t i_date, double f_percent, chapter_item_c *psz_chapter )
402 {
403     demux_sys_t        *p_sys = p_demux->p_sys;
404     virtual_segment_c  *p_vsegment = p_sys->p_current_segment;
405     matroska_segment_c *p_segment = p_vsegment->Segment();
406     mtime_t            i_time_offset = 0;
407     int64_t            i_global_position = -1;
408
409     int         i_index;
410
411     msg_Dbg( p_demux, "seek request to %"PRId64" (%f%%)", i_date, f_percent );
412     if( i_date < 0 && f_percent < 0 )
413     {
414         msg_Warn( p_demux, "cannot seek nowhere !" );
415         return;
416     }
417     if( f_percent > 1.0 )
418     {
419         msg_Warn( p_demux, "cannot seek so far !" );
420         return;
421     }
422
423     /* seek without index or without date */
424     if( f_percent >= 0 && (var_InheritBool( p_demux, "mkv-seek-percent" ) || !p_segment->b_cues || i_date < 0 ))
425     {
426         if( p_sys->f_duration >= 0 && p_segment->b_cues )
427         {
428             i_date = int64_t( f_percent * p_sys->f_duration * 1000.0 );
429         }
430         else
431         {
432             int64_t i_pos = int64_t( f_percent * stream_Size( p_demux->s ) );
433
434             msg_Dbg( p_demux, "inaccurate way of seeking for pos:%"PRId64, i_pos );
435             for( i_index = 0; i_index < p_segment->i_index; i_index++ )
436             {
437                 if( p_segment->b_cues && p_segment->p_indexes[i_index].i_position < i_pos )
438                     break;
439                 if( !p_segment->b_cues && p_segment->p_indexes[i_index].i_position >= i_pos && p_segment->p_indexes[i_index].i_time > 0 )
440                     break;
441             }
442             if( i_index == p_segment->i_index )
443             {
444                 i_index--;
445             }
446
447             i_date = p_segment->p_indexes[i_index].i_time;
448
449             if( !p_segment->b_cues && ( p_segment->p_indexes[i_index].i_position < i_pos || p_segment->p_indexes[i_index].i_position - i_pos > 2000000 ))
450             {
451                 msg_Dbg( p_demux, "no cues, seek request to global pos: %"PRId64, i_pos );
452                 i_global_position = i_pos;
453             }
454         }
455     }
456
457     p_vsegment->Seek( *p_demux, i_date, i_time_offset, psz_chapter, i_global_position );
458 }
459
460 /* Utility function for BlockDecode */
461 static block_t *MemToBlock( demux_t *p_demux, uint8_t *p_mem, size_t i_mem, size_t offset)
462 {
463     block_t *p_block;
464     if( !(p_block = block_New( p_demux, i_mem + offset ) ) ) return NULL;
465     memcpy( p_block->p_buffer + offset, p_mem, i_mem );
466     //p_block->i_rate = p_input->stream.control.i_rate;
467     return p_block;
468 }
469
470 /* Needed by matroska_segment::Seek() and Seek */
471 void BlockDecode( demux_t *p_demux, KaxBlock *block, KaxSimpleBlock *simpleblock,
472                          mtime_t i_pts, mtime_t i_duration, bool f_mandatory )
473 {
474     demux_sys_t        *p_sys = p_demux->p_sys;
475     matroska_segment_c *p_segment = p_sys->p_current_segment->Segment();
476
477     if( !p_segment ) return;
478
479     size_t          i_track;
480     if( p_segment->BlockFindTrackIndex( &i_track, block, simpleblock ) )
481     {
482         msg_Err( p_demux, "invalid track number" );
483         return;
484     }
485
486     mkv_track_t *tk = p_segment->tracks[i_track];
487
488     if( tk->fmt.i_cat != NAV_ES && tk->p_es == NULL )
489     {
490         msg_Err( p_demux, "unknown track number" );
491         return;
492     }
493     if( i_pts + i_duration < p_sys->i_start_pts && tk->fmt.i_cat == AUDIO_ES )
494     {
495         return; /* discard audio packets that shouldn't be rendered */
496     }
497
498     if ( tk->fmt.i_cat != NAV_ES )
499     {
500         bool b;
501         es_out_Control( p_demux->out, ES_OUT_GET_ES_STATE, tk->p_es, &b );
502
503         if( !b )
504         {
505             tk->b_inited = false;
506             return;
507         }
508     }
509
510
511     /* First send init data */
512     if( !tk->b_inited && tk->i_data_init > 0 )
513     {
514         block_t *p_init;
515
516         msg_Dbg( p_demux, "sending header (%d bytes)", tk->i_data_init );
517         p_init = MemToBlock( p_demux, tk->p_data_init, tk->i_data_init, 0 );
518         if( p_init ) es_out_Send( p_demux->out, tk->p_es, p_init );
519     }
520     tk->b_inited = true;
521
522
523     for( unsigned int i = 0;
524          (block != NULL && i < block->NumberFrames()) || (simpleblock != NULL && i < simpleblock->NumberFrames());
525          i++ )
526     {
527         block_t *p_block;
528         DataBuffer *data;
529         if( simpleblock != NULL )
530         {
531             data = &simpleblock->GetBuffer(i);
532             // condition when the DTS is correct (keyframe or B frame == NOT P frame)
533             f_mandatory = simpleblock->IsDiscardable() || simpleblock->IsKeyframe();
534         }
535         else
536         {
537             data = &block->GetBuffer(i);
538         }
539         if( !data->Buffer() || data->Size() > SIZE_MAX )
540             break;
541
542         if( tk->i_compression_type == MATROSKA_COMPRESSION_HEADER && tk->p_compression_data != NULL )
543             p_block = MemToBlock( p_demux, data->Buffer(), data->Size(), tk->p_compression_data->GetSize() );
544         else
545             p_block = MemToBlock( p_demux, data->Buffer(), data->Size(), 0 );
546
547         if( p_block == NULL )
548         {
549             break;
550         }
551
552 #if defined(HAVE_ZLIB_H)
553         if( tk->i_compression_type == MATROSKA_COMPRESSION_ZLIB )
554         {
555             p_block = block_zlib_decompress( VLC_OBJECT(p_demux), p_block );
556             if( p_block == NULL )
557                 break;
558         }
559         else
560 #endif
561         if( tk->i_compression_type == MATROSKA_COMPRESSION_HEADER )
562         {
563             memcpy( p_block->p_buffer, tk->p_compression_data->GetBuffer(), tk->p_compression_data->GetSize() );
564         }
565
566         if ( tk->fmt.i_cat == NAV_ES )
567         {
568             // TODO handle the start/stop times of this packet
569             if ( p_sys->b_ui_hooked )
570             {
571                 vlc_mutex_lock( &p_sys->p_ev->lock );
572                 memcpy( &p_sys->pci_packet, &p_block->p_buffer[1], sizeof(pci_t) );
573                 p_sys->SwapButtons();
574                 p_sys->b_pci_packet_set = true;
575                 vlc_mutex_unlock( &p_sys->p_ev->lock );
576                 block_Release( p_block );
577             }
578             return;
579         }
580         // correct timestamping when B frames are used
581         if( tk->fmt.i_cat != VIDEO_ES )
582         {
583             p_block->i_dts = p_block->i_pts = i_pts;
584         }
585         else
586         {
587             if( tk->b_dts_only )
588             {
589                 p_block->i_pts = VLC_TS_INVALID;
590                 p_block->i_dts = i_pts;
591             }
592             else if( tk->b_pts_only )
593             {
594                 p_block->i_pts = i_pts;
595                 p_block->i_dts = i_pts;
596             }
597             else
598             {
599                 p_block->i_pts = i_pts;
600                 if ( f_mandatory )
601                     p_block->i_dts = p_block->i_pts;
602                 else
603                     p_block->i_dts = min( i_pts, tk->i_last_dts + (mtime_t)(tk->i_default_duration >> 10));
604             }
605         }
606         tk->i_last_dts = p_block->i_dts;
607
608 #if 0
609 msg_Dbg( p_demux, "block i_dts: %"PRId64" / i_pts: %"PRId64, p_block->i_dts, p_block->i_pts);
610 #endif
611         if( strcmp( tk->psz_codec, "S_VOBSUB" ) )
612         {
613             p_block->i_length = i_duration * 1000;
614         }
615
616         /* FIXME remove when VLC_TS_INVALID work is done */
617         if( i == 0 || p_block->i_dts > VLC_TS_INVALID )
618             p_block->i_dts += VLC_TS_0;
619         if( !tk->b_dts_only && ( i == 0 || p_block->i_pts > VLC_TS_INVALID ) )
620             p_block->i_pts += VLC_TS_0;
621
622         es_out_Send( p_demux->out, tk->p_es, p_block );
623
624         /* use time stamp only for first block */
625         i_pts = VLC_TS_INVALID;
626     }
627 }
628
629 /*****************************************************************************
630  * Demux: reads and demuxes data packets
631  *****************************************************************************
632  * Returns -1 in case of error, 0 in case of EOF, 1 otherwise
633  *****************************************************************************/
634 static int Demux( demux_t *p_demux)
635 {
636     demux_sys_t        *p_sys = p_demux->p_sys;
637
638     vlc_mutex_lock( &p_sys->lock_demuxer );
639
640     virtual_segment_c  *p_vsegment = p_sys->p_current_segment;
641     matroska_segment_c *p_segment = p_vsegment->Segment();
642     if ( p_segment == NULL ) return 0;
643     int                i_block_count = 0;
644     int                i_return = 0;
645
646     for( ;; )
647     {
648         if ( p_sys->demuxer.b_die )
649             break;
650
651         if( p_sys->i_pts >= p_sys->i_start_pts  )
652             if ( p_vsegment->UpdateCurrentToChapter( *p_demux ) )
653             {
654                 i_return = 1;
655                 break;
656             }
657  
658         if ( p_vsegment->Edition() && p_vsegment->Edition()->b_ordered && p_vsegment->CurrentChapter() == NULL )
659         {
660             /* nothing left to read in this ordered edition */
661             if ( !p_vsegment->SelectNext() )
662                 break;
663             p_segment->UnSelect( );
664  
665             es_out_Control( p_demux->out, ES_OUT_RESET_PCR );
666
667             /* switch to the next segment */
668             p_segment = p_vsegment->Segment();
669             if ( !p_segment->Select( 0 ) )
670             {
671                 msg_Err( p_demux, "Failed to select new segment" );
672                 break;
673             }
674             continue;
675         }
676
677         KaxBlock *block;
678         KaxSimpleBlock *simpleblock;
679         int64_t i_block_duration = 0;
680         bool b_key_picture;
681         bool b_discardable_picture;
682         if( p_segment->BlockGet( block, simpleblock, &b_key_picture, &b_discardable_picture, &i_block_duration ) )
683         {
684             if ( p_vsegment->Edition() && p_vsegment->Edition()->b_ordered )
685             {
686                 const chapter_item_c *p_chap = p_vsegment->CurrentChapter();
687                 // check if there are more chapters to read
688                 if ( p_chap != NULL )
689                 {
690                     /* TODO handle successive chapters with the same user_start_time/user_end_time
691                     if ( p_chap->i_user_start_time == p_chap->i_user_start_time )
692                         p_vsegment->SelectNext();
693                     */
694                     p_sys->i_pts = p_chap->i_user_end_time;
695                     p_sys->i_pts++; // trick to avoid staying on segments with no duration and no content
696
697                     i_return = 1;
698                 }
699
700                 break;
701             }
702             else
703             {
704                 msg_Warn( p_demux, "cannot get block EOF?" );
705                 p_segment->UnSelect( );
706  
707                 es_out_Control( p_demux->out, ES_OUT_RESET_PCR );
708
709                 /* switch to the next segment */
710                 if ( !p_vsegment->SelectNext() )
711                     // no more segments in this stream
712                     break;
713                 p_segment = p_vsegment->Segment();
714                 if ( !p_segment->Select( 0 ) )
715                 {
716                     msg_Err( p_demux, "Failed to select new segment" );
717                     break;
718                 }
719
720                 continue;
721             }
722         }
723
724         if( simpleblock != NULL )
725             p_sys->i_pts = (p_sys->i_chapter_time + simpleblock->GlobalTimecode()) / (mtime_t) 1000;
726         else
727             p_sys->i_pts = (p_sys->i_chapter_time + block->GlobalTimecode()) / (mtime_t) 1000;
728
729         /* */
730         es_out_Control( p_demux->out, ES_OUT_SET_PCR, VLC_TS_0 + p_sys->i_pts );
731
732         if( p_sys->i_pts >= p_sys->i_start_pts  )
733         {
734             if ( p_vsegment->UpdateCurrentToChapter( *p_demux ) )
735             {
736                 i_return = 1;
737                 delete block;
738                 break;
739             }
740         }
741  
742         if ( p_vsegment->Edition() && p_vsegment->Edition()->b_ordered && p_vsegment->CurrentChapter() == NULL )
743         {
744             /* nothing left to read in this ordered edition */
745             if ( !p_vsegment->SelectNext() )
746             {
747                 delete block;
748                 break;
749             }
750             p_segment->UnSelect( );
751  
752             es_out_Control( p_demux->out, ES_OUT_RESET_PCR );
753
754             /* switch to the next segment */
755             p_segment = p_vsegment->Segment();
756             if ( !p_segment->Select( 0 ) )
757             {
758                 msg_Err( p_demux, "Failed to select new segment" );
759                 delete block;
760                 break;
761             }
762             delete block;
763             continue;
764         }
765
766         BlockDecode( p_demux, block, simpleblock, p_sys->i_pts, i_block_duration, b_key_picture || b_discardable_picture );
767
768         delete block;
769         i_block_count++;
770
771         // TODO optimize when there is need to leave or when seeking has been called
772         if( i_block_count > 5 )
773         {
774             i_return = 1;
775             break;
776         }
777     }
778
779     vlc_mutex_unlock( &p_sys->lock_demuxer );
780
781     return i_return;
782 }
783