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