Define C++ types in namespaces
[vlc.git] / modules / demux / mkv / mkv.cpp
blobaf6554dcb2f6e37a7169848d77ea63defcabea64
1 /*****************************************************************************
2 * mkv.cpp : matroska demuxer
3 *****************************************************************************
4 * Copyright (C) 2003-2005, 2008, 2010 VLC authors and VideoLAN
5 * $Id$
7 * Authors: Laurent Aimar <fenrir@via.ecp.fr>
8 * Steve Lhomme <steve.lhomme@free.fr>
10 * This program is free software; you can redistribute it and/or modify it
11 * under the terms of the GNU Lesser General Public License as published by
12 * the Free Software Foundation; either version 2.1 of the License, or
13 * (at your option) any later version.
15 * This program is distributed in the hope that it will be useful,
16 * but WITHOUT ANY WARRANTY; without even the implied warranty of
17 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
18 * GNU Lesser General Public License for more details.
20 * You should have received a copy of the GNU Lesser General Public License
21 * along with this program; if not, write to the Free Software Foundation,
22 * Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA.
23 *****************************************************************************/
25 #include "mkv.hpp"
26 #include "util.hpp"
28 #include "matroska_segment.hpp"
29 #include "demux.hpp"
31 #include "chapters.hpp"
32 #include "Ebml_parser.hpp"
34 #include <new>
36 #include <vlc_fs.h>
37 #include <vlc_url.h>
39 /*****************************************************************************
40 * Module descriptor
41 *****************************************************************************/
42 namespace mkv {
43 static int Open ( vlc_object_t * );
44 static void Close( vlc_object_t * );
45 } // namespace
47 using namespace mkv;
48 vlc_module_begin ()
49 set_shortname( "Matroska" )
50 set_description( N_("Matroska stream demuxer" ) )
51 set_capability( "demux", 50 )
52 set_callbacks( Open, Close )
53 set_category( CAT_INPUT )
54 set_subcategory( SUBCAT_INPUT_DEMUX )
56 add_bool( "mkv-use-ordered-chapters", true,
57 N_("Respect ordered chapters"),
58 N_("Play chapters in the order specified in the segment."), false );
60 add_bool( "mkv-use-chapter-codec", true,
61 N_("Chapter codecs"),
62 N_("Use chapter codecs found in the segment."), true );
64 add_bool( "mkv-preload-local-dir", true,
65 N_("Preload MKV files in the same directory"),
66 N_("Preload matroska files in the same directory to find linked segments (not good for broken files)."), false );
68 add_bool( "mkv-seek-percent", false,
69 N_("Seek based on percent not time"),
70 N_("Seek based on percent not time."), true );
72 add_bool( "mkv-use-dummy", false,
73 N_("Dummy Elements"),
74 N_("Read and discard unknown EBML elements (not good for broken files)."), true );
76 add_bool( "mkv-preload-clusters", false,
77 N_("Preload clusters"),
78 N_("Find all cluster positions by jumping cluster-to-cluster before playback"), true );
80 add_shortcut( "mka", "mkv" )
81 vlc_module_end ()
83 namespace mkv {
85 struct demux_sys_t;
87 static int Demux ( demux_t * );
88 static int Control( demux_t *, int, va_list );
89 static int Seek ( demux_t *, vlc_tick_t i_mk_date, double f_percent, virtual_chapter_c *p_vchapter, bool b_precise = true );
91 /*****************************************************************************
92 * Open: initializes matroska demux structures
93 *****************************************************************************/
94 static int Open( vlc_object_t * p_this )
96 demux_t *p_demux = (demux_t*)p_this;
97 demux_sys_t *p_sys;
98 matroska_stream_c *p_stream;
99 matroska_segment_c *p_segment;
100 const uint8_t *p_peek;
101 std::string s_path, s_filename;
102 bool b_need_preload = false;
104 /* peek the begining */
105 if( vlc_stream_Peek( p_demux->s, &p_peek, 4 ) < 4 ) return VLC_EGENERIC;
107 /* is a valid file */
108 if( p_peek[0] != 0x1a || p_peek[1] != 0x45 ||
109 p_peek[2] != 0xdf || p_peek[3] != 0xa3 ) return VLC_EGENERIC;
111 /* Set the demux function */
112 p_demux->pf_demux = Demux;
113 p_demux->pf_control = Control;
114 p_demux->p_sys = p_sys = new demux_sys_t( *p_demux );
116 vlc_stream_Control( p_demux->s, STREAM_CAN_SEEK, &p_sys->b_seekable );
117 if ( vlc_stream_Control( p_demux->s, STREAM_CAN_FASTSEEK, &p_sys->b_fastseekable ) )
118 p_sys->b_fastseekable = false;
120 es_out_Control( p_demux->out, ES_OUT_SET_ES_CAT_POLICY, VIDEO_ES,
121 ES_OUT_ES_POLICY_EXCLUSIVE );
123 p_stream = new matroska_stream_c( p_demux->s, false );
124 if ( unlikely(p_stream == NULL) )
126 msg_Err( p_demux, "failed to create matroska_stream_c" );
127 delete p_sys;
128 return VLC_ENOMEM;
130 p_sys->streams.push_back( p_stream );
132 if( !p_sys->AnalyseAllSegmentsFound( p_demux, p_stream ) )
134 msg_Err( p_demux, "cannot find KaxSegment or missing mandatory KaxInfo" );
135 goto error;
138 for (size_t i=0; i<p_stream->segments.size(); i++)
140 p_stream->segments[i]->Preload();
141 b_need_preload |= p_stream->segments[i]->b_ref_external_segments;
142 if ( p_stream->segments[i]->translations.size() &&
143 p_stream->segments[i]->translations[0]->codec_id == MATROSKA_CHAPTER_CODEC_DVD &&
144 p_stream->segments[i]->families.size() )
145 b_need_preload = true;
148 p_segment = p_stream->segments[0];
149 if( p_segment->cluster == NULL && p_segment->stored_editions.size() == 0 )
151 msg_Err( p_demux, "cannot find any cluster or chapter, damaged file ?" );
152 goto error;
155 if (b_need_preload && var_InheritBool( p_demux, "mkv-preload-local-dir" ))
157 msg_Dbg( p_demux, "Preloading local dir" );
158 /* get the files from the same dir from the same family (based on p_demux->psz_path) */
159 if ( p_demux->psz_filepath && !strncasecmp( p_demux->psz_url, "file:", 5 ) )
161 // assume it's a regular file
162 // get the directory path
163 s_path = p_demux->psz_filepath;
164 if (s_path.at(s_path.length() - 1) == DIR_SEP_CHAR)
166 s_path = s_path.substr(0,s_path.length()-1);
168 else
170 if (s_path.find_last_of(DIR_SEP_CHAR) > 0)
172 s_path = s_path.substr(0,s_path.find_last_of(DIR_SEP_CHAR));
176 DIR *p_src_dir = vlc_opendir(s_path.c_str());
178 if (p_src_dir != NULL)
180 const char *psz_file;
181 while ((psz_file = vlc_readdir(p_src_dir)) != NULL)
183 if (strlen(psz_file) > 4)
185 s_filename = s_path + DIR_SEP_CHAR + psz_file;
187 #if defined(_WIN32) || defined(__OS2__)
188 if (!strcasecmp(s_filename.c_str(), p_demux->psz_filepath))
189 #else
190 if (!s_filename.compare(p_demux->psz_filepath))
191 #endif
193 continue; // don't reuse the original opened file
196 if (!strcasecmp(s_filename.c_str() + s_filename.length() - 4, ".mkv") ||
197 !strcasecmp(s_filename.c_str() + s_filename.length() - 4, ".mka"))
199 // test whether this file belongs to our family
200 const uint8_t *p_peek;
201 bool file_ok = false;
202 char *psz_url = vlc_path2uri( s_filename.c_str(), "file" );
203 stream_t *p_file_stream = vlc_stream_NewURL(
204 p_demux,
205 psz_url );
206 /* peek the begining */
207 if( p_file_stream &&
208 vlc_stream_Peek( p_file_stream, &p_peek, 4 ) >= 4
209 && p_peek[0] == 0x1a && p_peek[1] == 0x45 &&
210 p_peek[2] == 0xdf && p_peek[3] == 0xa3 ) file_ok = true;
212 if ( file_ok )
214 matroska_stream_c *p_stream = new matroska_stream_c( p_file_stream, true );
216 if ( !p_sys->AnalyseAllSegmentsFound( p_demux, p_stream ) )
218 msg_Dbg( p_demux, "the file '%s' will not be used", s_filename.c_str() );
219 delete p_stream;
221 else
223 p_sys->streams.push_back( p_stream );
226 else
228 if( p_file_stream ) {
229 vlc_stream_Delete( p_file_stream );
231 msg_Dbg( p_demux, "the file '%s' cannot be opened", s_filename.c_str() );
233 free( psz_url );
237 closedir( p_src_dir );
241 p_sys->PreloadFamily( *p_segment );
243 else if (b_need_preload)
244 msg_Warn( p_demux, "This file references other files, you may want to enable the preload of local directory");
246 if ( !p_sys->PreloadLinked() ||
247 !p_sys->PreparePlayback( *p_sys->p_current_vsegment, 0 ) )
249 msg_Err( p_demux, "cannot use the segment" );
250 goto error;
253 p_sys->FreeUnused();
255 p_sys->InitUi();
257 return VLC_SUCCESS;
259 error:
260 delete p_sys;
261 return VLC_EGENERIC;
264 /*****************************************************************************
265 * Close: frees unused data
266 *****************************************************************************/
267 static void Close( vlc_object_t *p_this )
269 demux_t *p_demux = reinterpret_cast<demux_t*>( p_this );
270 demux_sys_t *p_sys = (demux_sys_t *)p_demux->p_sys;
271 virtual_segment_c *p_vsegment = p_sys->p_current_vsegment;
272 if( p_vsegment )
274 matroska_segment_c *p_segment = p_vsegment->CurrentSegment();
275 if( p_segment )
276 p_segment->ESDestroy();
279 delete p_sys;
282 /*****************************************************************************
283 * Control:
284 *****************************************************************************/
285 static int Control( demux_t *p_demux, int i_query, va_list args )
287 demux_sys_t *p_sys = (demux_sys_t *)p_demux->p_sys;
288 int64_t *pi64, i64;
289 double *pf, f;
290 int i_skp;
291 size_t i_idx;
292 bool b;
294 vlc_meta_t *p_meta;
295 input_attachment_t ***ppp_attach;
296 int *pi_int;
298 switch( i_query )
300 case DEMUX_CAN_SEEK:
301 return vlc_stream_vaControl( p_demux->s, i_query, args );
303 case DEMUX_GET_ATTACHMENTS:
304 ppp_attach = va_arg( args, input_attachment_t*** );
305 pi_int = va_arg( args, int * );
307 if( p_sys->stored_attachments.size() <= 0 )
308 return VLC_EGENERIC;
310 *pi_int = p_sys->stored_attachments.size();
311 *ppp_attach = static_cast<input_attachment_t**>( vlc_alloc( p_sys->stored_attachments.size(),
312 sizeof(input_attachment_t*) ) );
313 if( !(*ppp_attach) )
314 return VLC_ENOMEM;
315 for( size_t i = 0; i < p_sys->stored_attachments.size(); i++ )
317 attachment_c *a = p_sys->stored_attachments[i];
318 (*ppp_attach)[i] = vlc_input_attachment_New( a->fileName(), a->mimeType(), NULL,
319 a->p_data, a->size() );
320 if( !(*ppp_attach)[i] )
322 free(*ppp_attach);
323 return VLC_ENOMEM;
326 return VLC_SUCCESS;
328 case DEMUX_GET_META:
329 p_meta = va_arg( args, vlc_meta_t* );
330 vlc_meta_Merge( p_meta, p_sys->meta );
331 return VLC_SUCCESS;
333 case DEMUX_GET_LENGTH:
334 pi64 = va_arg( args, int64_t * );
335 if( p_sys->f_duration > 0.0 )
336 *pi64 = static_cast<int64_t>( p_sys->f_duration * 1000 );
337 else
338 *pi64 = VLC_TICK_INVALID;
339 return VLC_SUCCESS;
341 case DEMUX_GET_POSITION:
342 pf = va_arg( args, double * );
343 if ( p_sys->f_duration > 0.0 )
344 *pf = static_cast<double> (p_sys->i_pcr >= (p_sys->i_start_pts + p_sys->i_mk_chapter_time) ?
345 p_sys->i_pcr :
346 (p_sys->i_start_pts + p_sys->i_mk_chapter_time) ) / (1000.0 * p_sys->f_duration);
347 return VLC_SUCCESS;
349 case DEMUX_SET_POSITION:
350 if( p_sys->f_duration > 0.0 )
352 f = va_arg( args, double );
353 b = va_arg( args, int ); /* precise? */
354 return Seek( p_demux, -1, f, NULL, b );
356 return VLC_EGENERIC;
358 case DEMUX_GET_TIME:
359 pi64 = va_arg( args, int64_t * );
360 *pi64 = p_sys->i_pcr;
361 return VLC_SUCCESS;
363 case DEMUX_GET_TITLE_INFO:
364 if( p_sys->titles.size() > 1 || ( p_sys->titles.size() == 1 && p_sys->titles[0]->i_seekpoint > 0 ) )
366 input_title_t ***ppp_title = va_arg( args, input_title_t*** );
367 int *pi_int = va_arg( args, int* );
369 *pi_int = p_sys->titles.size();
370 *ppp_title = static_cast<input_title_t**>( vlc_alloc( p_sys->titles.size(), sizeof( input_title_t* ) ) );
372 for( size_t i = 0; i < p_sys->titles.size(); i++ )
373 (*ppp_title)[i] = vlc_input_title_Duplicate( p_sys->titles[i] );
374 return VLC_SUCCESS;
376 return VLC_EGENERIC;
378 case DEMUX_SET_TITLE:
379 /* handle editions as titles */
380 i_idx = va_arg( args, int );
381 if(i_idx < p_sys->titles.size() && p_sys->titles[i_idx]->i_seekpoint)
383 const int i_edition = p_sys->p_current_vsegment->i_current_edition;
384 const int i_title = p_sys->i_current_title;
385 p_sys->p_current_vsegment->i_current_edition = i_idx;
386 p_sys->i_current_title = i_idx;
387 if( VLC_SUCCESS ==
388 Seek( p_demux, static_cast<int64_t>( p_sys->titles[i_idx]->seekpoint[0]->i_time_offset ), -1, NULL) )
390 p_sys->i_updates |= INPUT_UPDATE_SEEKPOINT|INPUT_UPDATE_TITLE;
391 p_sys->i_current_seekpoint = 0;
392 p_sys->f_duration = (float) p_sys->titles[i_idx]->i_length / 1000.f;
393 return VLC_SUCCESS;
395 else
397 p_sys->p_current_vsegment->i_current_edition = i_edition;
398 p_sys->i_current_title = i_title;
401 return VLC_EGENERIC;
403 case DEMUX_SET_SEEKPOINT:
404 i_skp = va_arg( args, int );
406 // TODO change the way it works with the << & >> buttons on the UI (+1/-1 instead of a number)
407 if( p_sys->titles.size() && i_skp < p_sys->titles[p_sys->i_current_title]->i_seekpoint)
409 int i_ret = Seek( p_demux, static_cast<int64_t>( p_sys->titles[p_sys->i_current_title]->seekpoint[i_skp]->i_time_offset ), -1, NULL);
410 if( i_ret == VLC_SUCCESS )
412 p_sys->i_updates |= INPUT_UPDATE_SEEKPOINT;
413 p_sys->i_current_seekpoint = i_skp;
415 return i_ret;
417 return VLC_EGENERIC;
419 case DEMUX_TEST_AND_CLEAR_FLAGS:
421 unsigned *restrict flags = va_arg( args, unsigned * );
422 *flags &= p_sys->i_updates;
423 p_sys->i_updates &= ~*flags;
424 return VLC_SUCCESS;
427 case DEMUX_GET_TITLE:
428 *va_arg( args, int * ) = p_sys->i_current_title;
429 return VLC_SUCCESS;
431 case DEMUX_GET_SEEKPOINT:
432 *va_arg( args, int * ) = p_sys->i_current_seekpoint;
433 return VLC_SUCCESS;
435 case DEMUX_GET_FPS:
436 pf = va_arg( args, double * );
437 *pf = 0.0;
438 if( p_sys->p_current_vsegment && p_sys->p_current_vsegment->CurrentSegment() )
440 typedef matroska_segment_c::tracks_map_t tracks_map_t;
442 const matroska_segment_c *p_segment = p_sys->p_current_vsegment->CurrentSegment();
443 for( tracks_map_t::const_iterator it = p_segment->tracks.begin(); it != p_segment->tracks.end(); ++it )
445 const mkv_track_t &track = *it->second;
447 if( track.fmt.i_cat == VIDEO_ES && track.fmt.video.i_frame_rate_base > 0 )
449 *pf = (double)track.fmt.video.i_frame_rate / track.fmt.video.i_frame_rate_base;
450 break;
454 return VLC_SUCCESS;
456 case DEMUX_SET_TIME:
457 i64 = va_arg( args, int64_t );
458 b = va_arg( args, int ); /* precise? */
459 msg_Dbg(p_demux,"SET_TIME to %" PRId64, i64 );
460 return Seek( p_demux, i64, -1, NULL, b );
462 case DEMUX_CAN_PAUSE:
463 case DEMUX_SET_PAUSE_STATE:
464 case DEMUX_CAN_CONTROL_PACE:
465 case DEMUX_GET_PTS_DELAY:
466 return demux_vaControlHelper( p_demux->s, 0, -1, 0, 1, i_query, args );
468 default:
469 return VLC_EGENERIC;
473 /* Seek */
474 static int Seek( demux_t *p_demux, vlc_tick_t i_mk_date, double f_percent, virtual_chapter_c *p_vchapter, bool b_precise )
476 demux_sys_t *p_sys = (demux_sys_t *)p_demux->p_sys;
477 virtual_segment_c *p_vsegment = p_sys->p_current_vsegment;
478 matroska_segment_c *p_segment = p_vsegment->CurrentSegment();
480 if( f_percent < 0 ) msg_Dbg( p_demux, "seek request to i_pos = %" PRId64, i_mk_date );
481 else msg_Dbg( p_demux, "seek request to %.2f%%", f_percent * 100 );
483 if( i_mk_date < 0 && f_percent < 0 )
485 msg_Warn( p_demux, "cannot seek nowhere!" );
486 return VLC_EGENERIC;
488 if( f_percent > 1.0 )
490 msg_Warn( p_demux, "cannot seek so far!" );
491 return VLC_EGENERIC;
493 if( p_sys->f_duration < 0 )
495 msg_Warn( p_demux, "cannot seek without duration!");
496 return VLC_EGENERIC;
498 if( !p_segment )
500 msg_Warn( p_demux, "cannot seek without valid segment position");
501 return VLC_EGENERIC;
504 /* seek without index or without date */
505 if( f_percent >= 0 && (var_InheritBool( p_demux, "mkv-seek-percent" ) || i_mk_date < 0 ))
507 i_mk_date = int64_t( f_percent * p_sys->f_duration * 1000.0 );
509 return p_vsegment->Seek( *p_demux, i_mk_date, p_vchapter, b_precise ) ? VLC_SUCCESS : VLC_EGENERIC;
512 /* Needed by matroska_segment::Seek() and Seek */
513 void BlockDecode( demux_t *p_demux, KaxBlock *block, KaxSimpleBlock *simpleblock,
514 vlc_tick_t i_pts, vlc_tick_t i_duration, bool b_key_picture,
515 bool b_discardable_picture )
517 demux_sys_t *p_sys = (demux_sys_t *)p_demux->p_sys;
518 matroska_segment_c *p_segment = p_sys->p_current_vsegment->CurrentSegment();
520 if( !p_segment ) return;
522 mkv_track_t *p_track = p_segment->FindTrackByBlock( block, simpleblock );
523 if( p_track == NULL )
525 msg_Err( p_demux, "invalid track number" );
526 return;
529 mkv_track_t &track = *p_track;
531 if( track.fmt.i_cat != DATA_ES && track.p_es == NULL )
533 msg_Err( p_demux, "unknown track number" );
534 return;
537 i_pts -= track.i_codec_delay;
539 if ( track.fmt.i_cat != DATA_ES )
541 bool b;
542 es_out_Control( p_demux->out, ES_OUT_GET_ES_STATE, track.p_es, &b );
544 if( !b )
546 if( track.fmt.i_cat == VIDEO_ES || track.fmt.i_cat == AUDIO_ES )
547 track.i_last_dts = VLC_TICK_INVALID;
548 return;
552 size_t frame_size = 0;
553 size_t block_size = 0;
555 if( simpleblock != NULL )
556 block_size = simpleblock->GetSize();
557 else
558 block_size = block->GetSize();
560 const unsigned int i_number_frames = block != NULL ? block->NumberFrames() :
561 ( simpleblock != NULL ? simpleblock->NumberFrames() : 0 );
563 for( unsigned int i_frame = 0; i_frame < i_number_frames; i_frame++ )
565 block_t *p_block;
566 DataBuffer *data;
567 if( simpleblock != NULL )
569 data = &simpleblock->GetBuffer(i_frame);
571 else
573 data = &block->GetBuffer(i_frame);
575 frame_size += data->Size();
576 if( !data->Buffer() || data->Size() > frame_size || frame_size > block_size )
578 msg_Warn( p_demux, "Cannot read frame (too long or no frame)" );
579 break;
581 size_t extra_data = track.fmt.i_codec == VLC_CODEC_PRORES ? 8 : 0;
583 if( track.i_compression_type == MATROSKA_COMPRESSION_HEADER &&
584 track.p_compression_data != NULL &&
585 track.i_encoding_scope & MATROSKA_ENCODING_SCOPE_ALL_FRAMES )
586 p_block = MemToBlock( data->Buffer(), data->Size(), track.p_compression_data->GetSize() + extra_data );
587 else if( unlikely( track.fmt.i_codec == VLC_CODEC_WAVPACK ) )
588 p_block = packetize_wavpack( track, data->Buffer(), data->Size() );
589 else
590 p_block = MemToBlock( data->Buffer(), data->Size(), extra_data );
592 if( p_block == NULL )
594 break;
597 #if defined(HAVE_ZLIB_H)
598 if( track.i_compression_type == MATROSKA_COMPRESSION_ZLIB &&
599 track.i_encoding_scope & MATROSKA_ENCODING_SCOPE_ALL_FRAMES )
601 p_block = block_zlib_decompress( VLC_OBJECT(p_demux), p_block );
602 if( p_block == NULL )
603 break;
605 else
606 #endif
607 if( track.i_compression_type == MATROSKA_COMPRESSION_HEADER &&
608 track.i_encoding_scope & MATROSKA_ENCODING_SCOPE_ALL_FRAMES )
610 memcpy( p_block->p_buffer, track.p_compression_data->GetBuffer(), track.p_compression_data->GetSize() );
612 if ( track.fmt.i_codec == VLC_CODEC_PRORES )
613 memcpy( p_block->p_buffer + 4, "icpf", 4 );
615 if ( b_key_picture )
616 p_block->i_flags |= BLOCK_FLAG_TYPE_I;
618 switch( track.fmt.i_codec )
620 case VLC_CODEC_COOK:
621 case VLC_CODEC_ATRAC3:
623 handle_real_audio(p_demux, &track, p_block, i_pts);
624 block_Release(p_block);
625 i_pts = ( track.i_default_duration )?
626 i_pts + ( vlc_tick_t )track.i_default_duration:
627 VLC_TICK_INVALID;
628 continue;
631 case VLC_CODEC_WEBVTT:
633 p_block = block_Realloc( p_block, 16, p_block->i_buffer );
634 if( !p_block )
635 continue;
636 SetDWBE( p_block->p_buffer, p_block->i_buffer );
637 memcpy( &p_block->p_buffer[4], "vttc", 4 );
638 SetDWBE( &p_block->p_buffer[8], p_block->i_buffer - 8 );
639 memcpy( &p_block->p_buffer[12], "payl", 4 );
641 break;
643 case VLC_CODEC_OPUS:
644 vlc_tick_t i_length = i_duration * track. f_timecodescale *
645 (double) p_segment->i_timescale / 1000.0;
646 if ( i_length < 0 ) i_length = 0;
647 p_block->i_nb_samples = i_length * track.fmt.audio.i_rate
648 / CLOCK_FREQ;
649 break;
652 if( track.fmt.i_cat != VIDEO_ES )
654 if ( track.fmt.i_cat == DATA_ES )
656 // TODO handle the start/stop times of this packet
657 p_sys->p_ev->SetPci( (const pci_t *)&p_block->p_buffer[1]);
658 block_Release( p_block );
659 return;
661 p_block->i_dts = p_block->i_pts = i_pts;
663 else
665 // correct timestamping when B frames are used
666 if( track.b_dts_only )
668 p_block->i_pts = VLC_TICK_INVALID;
669 p_block->i_dts = i_pts;
671 else if( track.b_pts_only )
673 p_block->i_pts = i_pts;
674 p_block->i_dts = i_pts;
676 else
678 p_block->i_pts = i_pts;
679 // condition when the DTS is correct (keyframe or B frame == NOT P frame)
680 if ( b_key_picture || b_discardable_picture )
681 p_block->i_dts = p_block->i_pts;
682 else if ( track.i_last_dts == VLC_TICK_INVALID )
683 p_block->i_dts = i_pts;
684 else
685 p_block->i_dts = std::min( i_pts, track.i_last_dts + ( vlc_tick_t )track.i_default_duration );
689 send_Block( p_demux, &track, p_block, i_number_frames, i_duration );
691 /* use time stamp only for first block */
692 i_pts = ( track.i_default_duration )?
693 i_pts + ( vlc_tick_t )track.i_default_duration:
694 ( track.fmt.b_packetized ) ? VLC_TICK_INVALID : i_pts + 1;
698 /*****************************************************************************
699 * Demux: reads and demuxes data packets
700 *****************************************************************************
701 * Returns -1 in case of error, 0 in case of EOF, 1 otherwise
702 *****************************************************************************/
703 static int Demux( demux_t *p_demux)
705 demux_sys_t *p_sys = (demux_sys_t *)p_demux->p_sys;
707 vlc_mutex_locker demux_lock ( &p_sys->lock_demuxer );
709 virtual_segment_c *p_vsegment = p_sys->p_current_vsegment;
711 if( p_sys->i_pts >= p_sys->i_start_pts )
713 if ( p_vsegment->UpdateCurrentToChapter( *p_demux ) )
714 return 1;
715 p_vsegment = p_sys->p_current_vsegment;
718 matroska_segment_c *p_segment = p_vsegment->CurrentSegment();
719 if ( p_segment == NULL )
720 return 0;
722 KaxBlock *block;
723 KaxSimpleBlock *simpleblock;
724 int64_t i_block_duration = 0;
725 bool b_key_picture;
726 bool b_discardable_picture;
728 if( p_segment->BlockGet( block, simpleblock, &b_key_picture, &b_discardable_picture, &i_block_duration ) )
730 if ( p_vsegment->CurrentEdition() && p_vsegment->CurrentEdition()->b_ordered )
732 const virtual_chapter_c *p_chap = p_vsegment->CurrentChapter();
733 // check if there are more chapters to read
734 if ( p_chap != NULL )
736 /* TODO handle successive chapters with the same user_start_time/user_end_time
738 p_sys->i_pts = p_chap->i_mk_virtual_stop_time + VLC_TICK_0;
739 p_sys->i_pts++; // trick to avoid staying on segments with no duration and no content
741 return 1;
745 msg_Warn( p_demux, "cannot get block EOF?" );
746 return 0;
750 mkv_track_t *p_track = p_segment->FindTrackByBlock( block, simpleblock );
752 if( p_track == NULL )
754 msg_Err( p_demux, "invalid track number" );
755 delete block;
756 return 0;
759 mkv_track_t &track = *p_track;
762 if( track.i_skip_until_fpos != std::numeric_limits<uint64_t>::max() ) {
764 uint64_t block_fpos = 0;
766 if( block ) block_fpos = block->GetElementPosition();
767 else block_fpos = simpleblock->GetElementPosition();
769 if ( track.i_skip_until_fpos > block_fpos )
771 delete block;
772 return 1; // this block shall be ignored
777 /* update pcr */
779 vlc_tick_t i_pcr = VLC_TICK_INVALID;
781 typedef matroska_segment_c::tracks_map_t tracks_map_t;
783 for( tracks_map_t::const_iterator it = p_segment->tracks.begin(); it != p_segment->tracks.end(); ++it )
785 mkv_track_t &track = *it->second;
787 if( track.i_last_dts == VLC_TICK_INVALID )
788 continue;
790 if( track.fmt.i_cat != VIDEO_ES && track.fmt.i_cat != AUDIO_ES )
791 continue;
793 if( track.i_last_dts < i_pcr || i_pcr == VLC_TICK_INVALID )
795 i_pcr = track.i_last_dts;
799 if( i_pcr != VLC_TICK_INVALID && i_pcr > p_sys->i_pcr )
801 if( es_out_SetPCR( p_demux->out, i_pcr ) )
803 msg_Err( p_demux, "ES_OUT_SET_PCR failed, aborting." );
804 return 0;
807 p_sys->i_pcr = i_pcr;
811 /* set pts */
813 p_sys->i_pts = p_sys->i_mk_chapter_time + VLC_TICK_0;
815 if( simpleblock != NULL ) p_sys->i_pts += simpleblock->GlobalTimecode() / INT64_C( 1000 );
816 else p_sys->i_pts += block->GlobalTimecode() / INT64_C( 1000 );
819 if ( p_vsegment->CurrentEdition() &&
820 p_vsegment->CurrentEdition()->b_ordered &&
821 p_vsegment->CurrentChapter() == NULL )
823 /* nothing left to read in this ordered edition */
824 delete block;
825 return 0;
828 BlockDecode( p_demux, block, simpleblock, p_sys->i_pts, i_block_duration, b_key_picture, b_discardable_picture );
830 delete block;
832 return 1;
835 mkv_track_t::mkv_track_t(enum es_format_category_e es_cat) :
836 b_default(true)
837 ,b_enabled(true)
838 ,b_forced(false)
839 ,i_number(0)
840 ,i_extra_data(0)
841 ,p_extra_data(NULL)
842 ,b_dts_only(false)
843 ,b_pts_only(false)
844 ,b_no_duration(false)
845 ,i_default_duration(0)
846 ,f_timecodescale(1.0)
847 ,i_last_dts(VLC_TICK_INVALID)
848 ,i_skip_until_fpos(std::numeric_limits<uint64_t>::max())
849 ,f_fps(0)
850 ,p_es(NULL)
851 ,i_original_rate(0)
852 ,i_chans_to_reorder(0)
853 ,p_sys(NULL)
854 ,b_discontinuity(false)
855 ,i_compression_type(MATROSKA_COMPRESSION_NONE)
856 ,i_encoding_scope(MATROSKA_ENCODING_SCOPE_ALL_FRAMES)
857 ,p_compression_data(NULL)
858 ,i_seek_preroll(0)
859 ,i_codec_delay(0)
861 std::memset( &pi_chan_table, 0, sizeof( pi_chan_table ) );
863 es_format_Init(&fmt, es_cat, 0);
865 switch( es_cat )
867 case AUDIO_ES:
868 fmt.audio.i_channels = 1;
869 fmt.audio.i_rate = 8000;
870 /* fall through */
871 case VIDEO_ES:
872 case SPU_ES:
873 fmt.psz_language = strdup("English");
874 break;
875 default:
876 // no language needed
877 break;
881 mkv_track_t::~mkv_track_t()
883 es_format_Clean( &fmt );
884 assert(p_es == NULL); // did we leak an ES ?
886 free(p_extra_data);
888 delete p_compression_data;
889 delete p_sys;
892 matroska_stream_c::matroska_stream_c( stream_t *s, bool owner )
893 :io_callback( s, owner )
894 ,estream( io_callback )
897 bool matroska_stream_c::isUsed() const
899 for( size_t j = 0; j < segments.size(); j++ )
901 if( segments[j]->b_preloaded )
902 return true;
904 return false;
907 } // namespace