]> git.sesse.net Git - vlc/blob - modules/demux/mkv/mkv.cpp
MKV: kill warnings.
[vlc] / modules / demux / mkv / mkv.cpp
1 /*****************************************************************************
2  * mkv.cpp : matroska demuxer
3  *****************************************************************************
4  * Copyright (C) 2003-2004 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 /*****************************************************************************
37  * Module descriptor
38  *****************************************************************************/
39 static int  Open ( vlc_object_t * );
40 static void Close( vlc_object_t * );
41
42 vlc_module_begin ()
43     set_shortname( "Matroska" )
44     set_description( N_("Matroska stream demuxer" ) )
45     set_capability( "demux", 0 )
46     set_callbacks( Open, Close )
47     set_category( CAT_INPUT )
48     set_subcategory( SUBCAT_INPUT_DEMUX )
49
50     add_bool( "mkv-use-ordered-chapters", 1, NULL,
51             N_("Ordered chapters"),
52             N_("Play ordered chapters as specified in the segment."), true );
53
54     add_bool( "mkv-use-chapter-codec", 1, NULL,
55             N_("Chapter codecs"),
56             N_("Use chapter codecs found in the segment."), true );
57
58     add_bool( "mkv-preload-local-dir", 1, NULL,
59             N_("Preload Directory"),
60             N_("Preload matroska files from the same family in the same directory (not good for broken files)."), true );
61
62     add_bool( "mkv-seek-percent", 0, NULL,
63             N_("Seek based on percent not time"),
64             N_("Seek based on percent not time."), true );
65
66     add_bool( "mkv-use-dummy", 0, NULL,
67             N_("Dummy Elements"),
68             N_("Read and discard unknown EBML elements (not good for broken files)."), true );
69
70     add_shortcut( "mka" )
71     add_shortcut( "mkv" )
72 vlc_module_end ()
73
74 class demux_sys_t;
75
76 static int  Demux  ( demux_t * );
77 static int  Control( demux_t *, int, va_list );
78 static void Seek   ( demux_t *, mtime_t i_date, double f_percent, chapter_item_c *psz_chapter );
79
80 /*****************************************************************************
81  * Open: initializes matroska demux structures
82  *****************************************************************************/
83 static int Open( vlc_object_t * p_this )
84 {
85     demux_t            *p_demux = (demux_t*)p_this;
86     demux_sys_t        *p_sys;
87     matroska_stream_c  *p_stream;
88     matroska_segment_c *p_segment;
89     const uint8_t      *p_peek;
90     std::string         s_path, s_filename;
91     vlc_stream_io_callback *p_io_callback;
92     EbmlStream         *p_io_stream;
93
94     /* peek the begining */
95     if( stream_Peek( p_demux->s, &p_peek, 4 ) < 4 ) return VLC_EGENERIC;
96
97     /* is a valid file */
98     if( p_peek[0] != 0x1a || p_peek[1] != 0x45 ||
99         p_peek[2] != 0xdf || p_peek[3] != 0xa3 ) return VLC_EGENERIC;
100
101     /* Set the demux function */
102     p_demux->pf_demux   = Demux;
103     p_demux->pf_control = Control;
104     p_demux->p_sys      = p_sys = new demux_sys_t( *p_demux );
105
106     p_io_callback = new vlc_stream_io_callback( p_demux->s, false );
107     p_io_stream = new EbmlStream( *p_io_callback );
108
109     if( p_io_stream == NULL )
110     {
111         msg_Err( p_demux, "failed to create EbmlStream" );
112         delete p_io_callback;
113         delete p_sys;
114         return VLC_EGENERIC;
115     }
116
117     p_stream = p_sys->AnalyseAllSegmentsFound( p_demux, p_io_stream, true );
118     if( p_stream == NULL )
119     {
120         msg_Err( p_demux, "cannot find KaxSegment" );
121         goto error;
122     }
123     p_sys->streams.push_back( p_stream );
124
125     p_stream->p_in = p_io_callback;
126     p_stream->p_es = p_io_stream;
127
128     for (size_t i=0; i<p_stream->segments.size(); i++)
129     {
130         p_stream->segments[i]->Preload();
131     }
132
133     p_segment = p_stream->segments[0];
134     if( p_segment->cluster == NULL )
135     {
136         msg_Err( p_demux, "cannot find any cluster, damaged file ?" );
137         goto error;
138     }
139
140     if (config_GetInt( p_demux, "mkv-preload-local-dir" ))
141     {
142         /* get the files from the same dir from the same family (based on p_demux->psz_path) */
143         if (p_demux->psz_path[0] != '\0' && !strcmp(p_demux->psz_access, ""))
144         {
145             // assume it's a regular file
146             // get the directory path
147             s_path = p_demux->psz_path;
148             if (s_path.at(s_path.length() - 1) == DIRECTORY_SEPARATOR)
149             {
150                 s_path = s_path.substr(0,s_path.length()-1);
151             }
152             else
153             {
154                 if (s_path.find_last_of(DIRECTORY_SEPARATOR) > 0)
155                 {
156                     s_path = s_path.substr(0,s_path.find_last_of(DIRECTORY_SEPARATOR));
157                 }
158             }
159
160             DIR *p_src_dir = utf8_opendir(s_path.c_str());
161
162             if (p_src_dir != NULL)
163             {
164                 char *psz_file;
165                 while ((psz_file = utf8_readdir(p_src_dir)) != NULL)
166                 {
167                     if (strlen(psz_file) > 4)
168                     {
169                         s_filename = s_path + DIRECTORY_SEPARATOR + psz_file;
170
171 #ifdef WIN32
172                         if (!strcasecmp(s_filename.c_str(), p_demux->psz_path))
173 #else
174                         if (!s_filename.compare(p_demux->psz_path))
175 #endif
176                         {
177                             free (psz_file);
178                             continue; // don't reuse the original opened file
179                         }
180
181 #if defined(__GNUC__) && (__GNUC__ < 3)
182                         if (!s_filename.compare("mkv", s_filename.length() - 3, 3) ||
183                             !s_filename.compare("mka", s_filename.length() - 3, 3))
184 #else
185                         if (!s_filename.compare(s_filename.length() - 3, 3, "mkv") ||
186                             !s_filename.compare(s_filename.length() - 3, 3, "mka"))
187 #endif
188                         {
189                             // test wether this file belongs to our family
190                             const uint8_t *p_peek;
191                             bool          file_ok = false;
192                             stream_t      *p_file_stream = stream_UrlNew(
193                                                             p_demux,
194                                                             s_filename.c_str());
195                             /* peek the begining */
196                             if( p_file_stream &&
197                                 stream_Peek( p_file_stream, &p_peek, 4 ) >= 4
198                                 && p_peek[0] == 0x1a && p_peek[1] == 0x45 &&
199                                 p_peek[2] == 0xdf && p_peek[3] == 0xa3 ) file_ok = true;
200
201                             if ( file_ok )
202                             {
203                                 vlc_stream_io_callback *p_file_io = new vlc_stream_io_callback( p_file_stream, true );
204                                 EbmlStream *p_estream = new EbmlStream(*p_file_io);
205
206                                 p_stream = p_sys->AnalyseAllSegmentsFound( p_demux, p_estream );
207
208                                 if ( p_stream == NULL )
209                                 {
210                                     msg_Dbg( p_demux, "the file '%s' will not be used", s_filename.c_str() );
211                                     delete p_estream;
212                                     delete p_file_io;
213                                 }
214                                 else
215                                 {
216                                     p_stream->p_in = p_file_io;
217                                     p_stream->p_es = p_estream;
218                                     p_sys->streams.push_back( p_stream );
219                                 }
220                             }
221                             else
222                             {
223                                 if( p_file_stream ) {
224                                     stream_Delete( p_file_stream );
225                                 }
226                                 msg_Dbg( p_demux, "the file '%s' cannot be opened", s_filename.c_str() );
227                             }
228                         }
229                     }
230                     free (psz_file);
231                 }
232                 closedir( p_src_dir );
233             }
234         }
235
236         p_sys->PreloadFamily( *p_segment );
237     }
238
239     p_sys->PreloadLinked( p_segment );
240
241     if ( !p_sys->PreparePlayback( NULL ) )
242     {
243         msg_Err( p_demux, "cannot use the segment" );
244         goto error;
245     }
246
247     p_sys->StartUiThread();
248  
249     return VLC_SUCCESS;
250
251 error:
252     delete p_sys;
253     return VLC_EGENERIC;
254 }
255
256 /*****************************************************************************
257  * Close: frees unused data
258  *****************************************************************************/
259 static void Close( vlc_object_t *p_this )
260 {
261     demux_t     *p_demux = (demux_t*)p_this;
262     demux_sys_t *p_sys   = p_demux->p_sys;
263
264     delete p_sys;
265 }
266
267 /*****************************************************************************
268  * Control:
269  *****************************************************************************/
270 static int Control( demux_t *p_demux, int i_query, va_list args )
271 {
272     demux_sys_t        *p_sys = p_demux->p_sys;
273     int64_t     *pi64;
274     double      *pf, f;
275     int         i_skp;
276     size_t      i_idx;
277
278     vlc_meta_t *p_meta;
279     input_attachment_t ***ppp_attach;
280     int *pi_int;
281
282     switch( i_query )
283     {
284         case DEMUX_GET_ATTACHMENTS:
285             ppp_attach = (input_attachment_t***)va_arg( args, input_attachment_t*** );
286             pi_int = (int*)va_arg( args, int * );
287
288             if( p_sys->stored_attachments.size() <= 0 )
289                 return VLC_EGENERIC;
290
291             *pi_int = p_sys->stored_attachments.size();
292             *ppp_attach = (input_attachment_t**)malloc( sizeof(input_attachment_t**) *
293                                                         p_sys->stored_attachments.size() );
294             if( !(*ppp_attach) )
295                 return VLC_ENOMEM;
296             for( size_t i = 0; i < p_sys->stored_attachments.size(); i++ )
297             {
298                 attachment_c *a = p_sys->stored_attachments[i];
299                 (*ppp_attach)[i] = vlc_input_attachment_New( a->psz_file_name.c_str(), a->psz_mime_type.c_str(), NULL,
300                                                              a->p_data, a->i_size );
301             }
302             return VLC_SUCCESS;
303
304         case DEMUX_GET_META:
305             p_meta = (vlc_meta_t*)va_arg( args, vlc_meta_t* );
306             vlc_meta_Merge( p_meta, p_sys->meta );
307             return VLC_SUCCESS;
308
309         case DEMUX_GET_LENGTH:
310             pi64 = (int64_t*)va_arg( args, int64_t * );
311             if( p_sys->f_duration > 0.0 )
312             {
313                 *pi64 = (int64_t)(p_sys->f_duration * 1000);
314                 return VLC_SUCCESS;
315             }
316             return VLC_EGENERIC;
317
318         case DEMUX_GET_POSITION:
319             pf = (double*)va_arg( args, double * );
320             if ( p_sys->f_duration > 0.0 )
321                 *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);
322             return VLC_SUCCESS;
323
324         case DEMUX_SET_POSITION:
325             f = (double)va_arg( args, double );
326             Seek( p_demux, -1, f, NULL );
327             return VLC_SUCCESS;
328
329         case DEMUX_GET_TIME:
330             pi64 = (int64_t*)va_arg( args, int64_t * );
331             *pi64 = p_sys->i_pts;
332             return VLC_SUCCESS;
333
334         case DEMUX_GET_TITLE_INFO:
335             if( p_sys->titles.size() > 1 || ( p_sys->titles.size() == 1 && p_sys->titles[0]->i_seekpoint > 0 ) )
336             {
337                 input_title_t ***ppp_title = (input_title_t***)va_arg( args, input_title_t*** );
338                 int *pi_int    = (int*)va_arg( args, int* );
339
340                 *pi_int = p_sys->titles.size();
341                 *ppp_title = (input_title_t**)malloc( sizeof( input_title_t**) * p_sys->titles.size() );
342
343                 for( size_t i = 0; i < p_sys->titles.size(); i++ )
344                 {
345                     (*ppp_title)[i] = vlc_input_title_Duplicate( p_sys->titles[i] );
346                 }
347                 return VLC_SUCCESS;
348             }
349             return VLC_EGENERIC;
350
351         case DEMUX_SET_TITLE:
352             /* TODO handle editions as titles */
353             i_idx = (int)va_arg( args, int );
354             if( i_idx < p_sys->used_segments.size() )
355             {
356                 p_sys->JumpTo( *p_sys->used_segments[i_idx], NULL );
357                 return VLC_SUCCESS;
358             }
359             return VLC_EGENERIC;
360
361         case DEMUX_SET_SEEKPOINT:
362             i_skp = (int)va_arg( args, int );
363
364             // TODO change the way it works with the << & >> buttons on the UI (+1/-1 instead of a number)
365             if( p_sys->titles.size() && i_skp < p_sys->titles[p_sys->i_current_title]->i_seekpoint)
366             {
367                 Seek( p_demux, (int64_t)p_sys->titles[p_sys->i_current_title]->seekpoint[i_skp]->i_time_offset, -1, NULL);
368                 p_demux->info.i_seekpoint |= INPUT_UPDATE_SEEKPOINT;
369                 p_demux->info.i_seekpoint = i_skp;
370                 return VLC_SUCCESS;
371             }
372             return VLC_EGENERIC;
373
374         case DEMUX_GET_FPS:
375             pf = (double *)va_arg( args, double * );
376             *pf = 0.0;
377             if( p_sys->p_current_segment && p_sys->p_current_segment->Segment() )
378             {
379                 const matroska_segment_c *p_segment = p_sys->p_current_segment->Segment();
380                 for( size_t i = 0; i < p_segment->tracks.size(); i++ )
381                 {
382                     mkv_track_t *tk = p_segment->tracks[i];
383                     if( tk->fmt.i_cat == VIDEO_ES && tk->fmt.video.i_frame_rate_base > 0 )
384                     {
385                         *pf = (double)tk->fmt.video.i_frame_rate / tk->fmt.video.i_frame_rate_base;
386                         break;
387                     }
388                 }
389             }
390             return VLC_SUCCESS;
391
392         case DEMUX_SET_TIME:
393         default:
394             return VLC_EGENERIC;
395     }
396 }
397
398 /* Seek */
399 static void Seek( demux_t *p_demux, mtime_t i_date, double f_percent, chapter_item_c *psz_chapter )
400 {
401     demux_sys_t        *p_sys = p_demux->p_sys;
402     virtual_segment_c  *p_vsegment = p_sys->p_current_segment;
403     matroska_segment_c *p_segment = p_vsegment->Segment();
404     mtime_t            i_time_offset = 0;
405     int64_t            i_global_position = -1;
406
407     int         i_index;
408
409     msg_Dbg( p_demux, "seek request to %"PRId64" (%f%%)", i_date, f_percent );
410     if( i_date < 0 && f_percent < 0 )
411     {
412         msg_Warn( p_demux, "cannot seek nowhere !" );
413         return;
414     }
415     if( f_percent > 1.0 )
416     {
417         msg_Warn( p_demux, "cannot seek so far !" );
418         return;
419     }
420
421     /* seek without index or without date */
422     if( f_percent >= 0 && (config_GetInt( p_demux, "mkv-seek-percent" ) || !p_segment->b_cues || i_date < 0 ))
423     {
424         if( p_sys->f_duration >= 0 && p_segment->b_cues )
425         {
426             i_date = int64_t( f_percent * p_sys->f_duration * 1000.0 );
427         }
428         else
429         {
430             int64_t i_pos = int64_t( f_percent * stream_Size( p_demux->s ) );
431
432             msg_Dbg( p_demux, "inaccurate way of seeking for pos:%"PRId64, i_pos );
433             for( i_index = 0; i_index < p_segment->i_index; i_index++ )
434             {
435                 if( p_segment->b_cues && p_segment->p_indexes[i_index].i_position < i_pos )
436                     break;
437                 if( !p_segment->b_cues && p_segment->p_indexes[i_index].i_position >= i_pos && p_segment->p_indexes[i_index].i_time > 0 )
438                     break;
439             }
440             if( i_index == p_segment->i_index )
441             {
442                 i_index--;
443             }
444
445             i_date = p_segment->p_indexes[i_index].i_time;
446
447             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 ))
448             {
449                 msg_Dbg( p_demux, "no cues, seek request to global pos: %"PRId64, i_pos );
450                 i_global_position = i_pos;
451             }
452         }
453     }
454
455     p_vsegment->Seek( *p_demux, i_date, i_time_offset, psz_chapter, i_global_position );
456 }
457
458 /* Utility function for BlockDecode */
459 static block_t *MemToBlock( demux_t *p_demux, uint8_t *p_mem, int i_mem, size_t offset)
460 {
461     block_t *p_block;
462     if( !(p_block = block_New( p_demux, i_mem + offset ) ) ) return NULL;
463     memcpy( p_block->p_buffer + offset, p_mem, i_mem );
464     //p_block->i_rate = p_input->stream.control.i_rate;
465     return p_block;
466 }
467
468 /* Needed by matroska_segment::Seek() */
469 static void BlockDecode( demux_t *p_demux, KaxBlock *block, KaxSimpleBlock *simpleblock,
470                          mtime_t i_pts, mtime_t i_duration, bool f_mandatory )
471 {
472     demux_sys_t        *p_sys = p_demux->p_sys;
473     matroska_segment_c *p_segment = p_sys->p_current_segment->Segment();
474
475     size_t          i_track;
476     unsigned int    i;
477     bool            b;
478
479     if( p_segment->BlockFindTrackIndex( &i_track, block, simpleblock ) )
480     {
481         msg_Err( p_demux, "invalid track number" );
482         return;
483     }
484
485     mkv_track_t *tk = p_segment->tracks[i_track];
486
487     if( tk->fmt.i_cat != NAV_ES && tk->p_es == NULL )
488     {
489         msg_Err( p_demux, "unknown track number" );
490         return;
491     }
492     if( i_pts + i_duration < p_sys->i_start_pts && tk->fmt.i_cat == AUDIO_ES )
493     {
494         return; /* discard audio packets that shouldn't be rendered */
495     }
496
497     if ( tk->fmt.i_cat != NAV_ES )
498     {
499         es_out_Control( p_demux->out, ES_OUT_GET_ES_STATE, tk->p_es, &b );
500
501         if( !b )
502         {
503             tk->b_inited = false;
504             return;
505         }
506     }
507
508
509     /* First send init data */
510     if( !tk->b_inited && tk->i_data_init > 0 )
511     {
512         block_t *p_init;
513
514         msg_Dbg( p_demux, "sending header (%d bytes)", tk->i_data_init );
515         p_init = MemToBlock( p_demux, tk->p_data_init, tk->i_data_init, 0 );
516         if( p_init ) es_out_Send( p_demux->out, tk->p_es, p_init );
517     }
518     tk->b_inited = true;
519
520
521     for( i = 0;
522          (block != NULL && i < block->NumberFrames()) || (simpleblock != NULL && i < simpleblock->NumberFrames());
523          i++ )
524     {
525         block_t *p_block;
526         DataBuffer *data;
527         if( simpleblock != NULL )
528         {
529             data = &simpleblock->GetBuffer(i);
530             // condition when the DTS is correct (keyframe or B frame == NOT P frame)
531             f_mandatory = simpleblock->IsDiscardable() || simpleblock->IsKeyframe();
532         }
533         else
534         {
535             data = &block->GetBuffer(i);
536         }
537
538         if( tk->i_compression_type == MATROSKA_COMPRESSION_HEADER && tk->p_compression_data != NULL )
539             p_block = MemToBlock( p_demux, data->Buffer(), data->Size(), tk->p_compression_data->GetSize() );
540         else
541             p_block = MemToBlock( p_demux, 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         }
553         else
554 #endif
555         if( tk->i_compression_type == MATROSKA_COMPRESSION_HEADER )
556         {
557             memcpy( p_block->p_buffer, tk->p_compression_data->GetBuffer(), tk->p_compression_data->GetSize() );
558         }
559
560         if ( tk->fmt.i_cat == NAV_ES )
561         {
562             // TODO handle the start/stop times of this packet
563             if ( p_sys->b_ui_hooked )
564             {
565                 vlc_mutex_lock( &p_sys->p_ev->lock );
566                 memcpy( &p_sys->pci_packet, &p_block->p_buffer[1], sizeof(pci_t) );
567                 p_sys->SwapButtons();
568                 p_sys->b_pci_packet_set = true;
569                 vlc_mutex_unlock( &p_sys->p_ev->lock );
570                 block_Release( p_block );
571             }
572             return;
573         }
574         // correct timestamping when B frames are used
575         if( tk->fmt.i_cat != VIDEO_ES )
576         {
577             p_block->i_dts = p_block->i_pts = i_pts;
578         }
579         else
580         {
581             if( !strcmp( tk->psz_codec, "V_MS/VFW/FOURCC" ) )
582             {
583                 // in VFW we have no idea about B frames
584                 p_block->i_pts = 0;
585                 p_block->i_dts = i_pts;
586             }
587             else
588             {
589                 p_block->i_pts = i_pts;
590                 if ( f_mandatory )
591                     p_block->i_dts = p_block->i_pts;
592                 else
593                     p_block->i_dts = min( i_pts, tk->i_last_dts + (mtime_t)(tk->i_default_duration >> 10));
594                 p_sys->i_pts = p_block->i_dts;
595             }
596         }
597         tk->i_last_dts = p_block->i_dts;
598
599 #if 0
600 msg_Dbg( p_demux, "block i_dts: %"PRId64" / i_pts: %"PRId64, p_block->i_dts, p_block->i_pts);
601 #endif
602         if( strcmp( tk->psz_codec, "S_VOBSUB" ) )
603         {
604             p_block->i_length = i_duration * 1000;
605         }
606
607         es_out_Send( p_demux->out, tk->p_es, p_block );
608
609         /* use time stamp only for first block */
610         i_pts = 0;
611     }
612 }
613
614
615 void matroska_segment_c::Seek( mtime_t i_date, mtime_t i_time_offset, int64_t i_global_position )
616 {
617     KaxBlock    *block;
618     KaxSimpleBlock *simpleblock;
619     int         i_track_skipping;
620     int64_t     i_block_duration;
621     int64_t     i_block_ref1;
622     int64_t     i_block_ref2;
623     size_t      i_track;
624     int64_t     i_seek_position = i_start_pos;
625     int64_t     i_seek_time = i_start_time;
626
627     if( i_global_position >= 0 )
628     {
629         /* Special case for seeking in files with no cues */
630         EbmlElement *el = NULL;
631         es.I_O().setFilePointer( i_start_pos, seek_beginning );
632         delete ep;
633         ep = new EbmlParser( &es, segment, &sys.demuxer );
634         cluster = NULL;
635
636         while( ( el = ep->Get() ) != NULL )
637         {
638             if( MKV_IS_ID( el, KaxCluster ) )
639             {
640                 cluster = (KaxCluster *)el;
641                 i_cluster_pos = cluster->GetElementPosition();
642                 if( i_index == 0 ||
643                         ( i_index > 0 && p_indexes[i_index - 1].i_position < (int64_t)cluster->GetElementPosition() ) )
644                 {
645                     IndexAppendCluster( cluster );
646                 }
647                 if( es.I_O().getFilePointer() >= i_global_position )
648                 {
649                     ParseCluster();
650                     msg_Dbg( &sys.demuxer, "we found a cluster that is in the neighbourhood" );
651                     return;
652                 }
653             }
654         }
655         msg_Err( &sys.demuxer, "This file has no cues, and we were unable to seek to the requested position by parsing." );
656         return;
657     }
658
659     if ( i_index > 0 )
660     {
661         int i_idx = 0;
662
663         for( ; i_idx < i_index; i_idx++ )
664         {
665             if( p_indexes[i_idx].i_time + i_time_offset > i_date )
666             {
667                 break;
668             }
669         }
670
671         if( i_idx > 0 )
672         {
673             i_idx--;
674         }
675
676         i_seek_position = p_indexes[i_idx].i_position;
677         i_seek_time = p_indexes[i_idx].i_time;
678     }
679
680     msg_Dbg( &sys.demuxer, "seek got %"PRId64" (%d%%)",
681                 i_seek_time, (int)( 100 * i_seek_position / stream_Size( sys.demuxer.s ) ) );
682
683     es.I_O().setFilePointer( i_seek_position, seek_beginning );
684
685     delete ep;
686     ep = new EbmlParser( &es, segment, &sys.demuxer );
687     cluster = NULL;
688
689     sys.i_start_pts = i_date;
690
691     /* now parse until key frame */
692     i_track_skipping = 0;
693     for( i_track = 0; i_track < tracks.size(); i_track++ )
694     {
695         if( tracks[i_track]->fmt.i_cat == VIDEO_ES )
696         {
697             tracks[i_track]->b_search_keyframe = true;
698             i_track_skipping++;
699         }
700     }
701     es_out_Control( sys.demuxer.out, ES_OUT_SET_NEXT_DISPLAY_TIME, i_date );
702
703     while( i_track_skipping > 0 )
704     {
705         if( BlockGet( block, simpleblock, &i_block_ref1, &i_block_ref2, &i_block_duration ) )
706         {
707             msg_Warn( &sys.demuxer, "cannot get block EOF?" );
708
709             return;
710         }
711         ep->Down();
712
713         for( i_track = 0; i_track < tracks.size(); i_track++ )
714         {
715             if( (simpleblock && tracks[i_track]->i_number == simpleblock->TrackNum()) ||
716                 (block && tracks[i_track]->i_number == block->TrackNum()) )
717             {
718                 break;
719             }
720         }
721
722         if( simpleblock )
723             sys.i_pts = (sys.i_chapter_time + simpleblock->GlobalTimecode()) / (mtime_t) 1000;
724         else
725             sys.i_pts = (sys.i_chapter_time + block->GlobalTimecode()) / (mtime_t) 1000;
726
727         if( i_track < tracks.size() )
728         {
729             if( sys.i_pts >= sys.i_start_pts )
730             {
731                 cluster = static_cast<KaxCluster*>(ep->UnGet( i_block_pos, i_cluster_pos ));
732                 i_track_skipping = 0;
733             }
734             else if( tracks[i_track]->fmt.i_cat == VIDEO_ES )
735             {
736                 if( i_block_ref1 == 0 && tracks[i_track]->b_search_keyframe )
737                 {
738                     tracks[i_track]->b_search_keyframe = false;
739                     i_track_skipping--;
740                 }
741                 if( !tracks[i_track]->b_search_keyframe )
742                 {
743                     BlockDecode( &sys.demuxer, block, simpleblock, sys.i_pts, 0, i_block_ref1 >= 0 || i_block_ref2 > 0 );
744                 }
745             }
746         }
747
748         delete block;
749     }
750
751     /* FIXME current ES_OUT_SET_NEXT_DISPLAY_TIME does not work that well if
752      * the delay is too high. */
753     if( sys.i_pts + 500*1000 < sys.i_start_pts )
754     {
755         sys.i_start_pts = sys.i_pts;
756
757         es_out_Control( sys.demuxer.out, ES_OUT_SET_NEXT_DISPLAY_TIME, sys.i_start_pts );
758     }
759 }
760
761
762 /*****************************************************************************
763  * Demux: reads and demuxes data packets
764  *****************************************************************************
765  * Returns -1 in case of error, 0 in case of EOF, 1 otherwise
766  *****************************************************************************/
767 static int Demux( demux_t *p_demux)
768 {
769     demux_sys_t        *p_sys = p_demux->p_sys;
770
771     vlc_mutex_lock( &p_sys->lock_demuxer );
772
773     virtual_segment_c  *p_vsegment = p_sys->p_current_segment;
774     matroska_segment_c *p_segment = p_vsegment->Segment();
775     if ( p_segment == NULL ) return 0;
776     int                i_block_count = 0;
777     int                i_return = 0;
778
779     for( ;; )
780     {
781         if ( p_sys->demuxer.b_die )
782             break;
783
784         if( p_sys->i_pts >= p_sys->i_start_pts  )
785             if ( p_vsegment->UpdateCurrentToChapter( *p_demux ) )
786             {
787                 i_return = 1;
788                 break;
789             }
790  
791         if ( p_vsegment->Edition() && p_vsegment->Edition()->b_ordered && p_vsegment->CurrentChapter() == NULL )
792         {
793             /* nothing left to read in this ordered edition */
794             if ( !p_vsegment->SelectNext() )
795                 break;
796             p_segment->UnSelect( );
797  
798             es_out_Control( p_demux->out, ES_OUT_RESET_PCR );
799
800             /* switch to the next segment */
801             p_segment = p_vsegment->Segment();
802             if ( !p_segment->Select( 0 ) )
803             {
804                 msg_Err( p_demux, "Failed to select new segment" );
805                 break;
806             }
807             continue;
808         }
809
810         KaxBlock *block;
811         KaxSimpleBlock *simpleblock;
812         int64_t i_block_duration = 0;
813         int64_t i_block_ref1;
814         int64_t i_block_ref2;
815
816         if( p_segment->BlockGet( block, simpleblock, &i_block_ref1, &i_block_ref2, &i_block_duration ) )
817         {
818             if ( p_vsegment->Edition() && p_vsegment->Edition()->b_ordered )
819             {
820                 const chapter_item_c *p_chap = p_vsegment->CurrentChapter();
821                 // check if there are more chapters to read
822                 if ( p_chap != NULL )
823                 {
824                     /* TODO handle successive chapters with the same user_start_time/user_end_time
825                     if ( p_chap->i_user_start_time == p_chap->i_user_start_time )
826                         p_vsegment->SelectNext();
827                     */
828                     p_sys->i_pts = p_chap->i_user_end_time;
829                     p_sys->i_pts++; // trick to avoid staying on segments with no duration and no content
830
831                     i_return = 1;
832                 }
833
834                 break;
835             }
836             else
837             {
838                 msg_Warn( p_demux, "cannot get block EOF?" );
839                 p_segment->UnSelect( );
840  
841                 es_out_Control( p_demux->out, ES_OUT_RESET_PCR );
842
843                 /* switch to the next segment */
844                 if ( !p_vsegment->SelectNext() )
845                     // no more segments in this stream
846                     break;
847                 p_segment = p_vsegment->Segment();
848                 if ( !p_segment->Select( 0 ) )
849                 {
850                     msg_Err( p_demux, "Failed to select new segment" );
851                     break;
852                 }
853
854                 continue;
855             }
856         }
857
858         if( simpleblock != NULL )
859             p_sys->i_pts = (p_sys->i_chapter_time + simpleblock->GlobalTimecode()) / (mtime_t) 1000;
860         else
861             p_sys->i_pts = (p_sys->i_chapter_time + block->GlobalTimecode()) / (mtime_t) 1000;
862
863         es_out_Control( p_demux->out, ES_OUT_SET_PCR, p_sys->i_pts );
864
865         if( p_sys->i_pts >= p_sys->i_start_pts  )
866         {
867             if ( p_vsegment->UpdateCurrentToChapter( *p_demux ) )
868             {
869                 i_return = 1;
870                 delete block;
871                 break;
872             }
873         }
874  
875         if ( p_vsegment->Edition() && p_vsegment->Edition()->b_ordered && p_vsegment->CurrentChapter() == NULL )
876         {
877             /* nothing left to read in this ordered edition */
878             if ( !p_vsegment->SelectNext() )
879             {
880                 delete block;
881                 break;
882             }
883             p_segment->UnSelect( );
884  
885             es_out_Control( p_demux->out, ES_OUT_RESET_PCR );
886
887             /* switch to the next segment */
888             p_segment = p_vsegment->Segment();
889             if ( !p_segment->Select( 0 ) )
890             {
891                 msg_Err( p_demux, "Failed to select new segment" );
892                 delete block;
893                 break;
894             }
895             delete block;
896             continue;
897         }
898
899         BlockDecode( p_demux, block, simpleblock, p_sys->i_pts, i_block_duration, i_block_ref1 >= 0 || i_block_ref2 > 0 );
900
901         delete block;
902         i_block_count++;
903
904         // TODO optimize when there is need to leave or when seeking has been called
905         if( i_block_count > 5 )
906         {
907             i_return = 1;
908             break;
909         }
910     }
911
912     vlc_mutex_unlock( &p_sys->lock_demuxer );
913
914     return i_return;
915 }
916