qt: playlist: use item title if available
[vlc.git] / modules / demux / mkv / mkv.cpp
1 /*****************************************************************************
2  * mkv.cpp : matroska demuxer
3  *****************************************************************************
4  * Copyright (C) 2003-2005, 2008, 2010 VLC authors and VideoLAN
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 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.
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 Lesser General Public License for more details.
19  *
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  *****************************************************************************/
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 <new>
35
36 #include <vlc_fs.h>
37 #include <vlc_url.h>
38
39 /*****************************************************************************
40  * Module descriptor
41  *****************************************************************************/
42 namespace mkv {
43 static int  Open ( vlc_object_t * );
44 static void Close( vlc_object_t * );
45 } // namespace
46
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 )
55
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 );
59
60     add_bool( "mkv-use-chapter-codec", true,
61             N_("Chapter codecs"),
62             N_("Use chapter codecs found in the segment."), true );
63
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 );
67
68     add_bool( "mkv-seek-percent", false,
69             N_("Seek based on percent not time"),
70             N_("Seek based on percent not time."), true );
71
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 );
75
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 );
79
80     add_shortcut( "mka", "mkv" )
81 vlc_module_end ()
82
83 namespace mkv {
84
85 struct demux_sys_t;
86
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 );
90
91 /*****************************************************************************
92  * Open: initializes matroska demux structures
93  *****************************************************************************/
94 static int Open( vlc_object_t * p_this )
95 {
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;
103
104     /* peek the begining */
105     if( vlc_stream_Peek( p_demux->s, &p_peek, 4 ) < 4 ) return VLC_EGENERIC;
106
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;
110
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 );
115
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;
119
120     es_out_Control( p_demux->out, ES_OUT_SET_ES_CAT_POLICY, VIDEO_ES,
121                     ES_OUT_ES_POLICY_EXCLUSIVE );
122
123     p_stream = new matroska_stream_c( p_demux->s, false );
124     if ( unlikely(p_stream == NULL) )
125     {
126         msg_Err( p_demux, "failed to create matroska_stream_c" );
127         delete p_sys;
128         return VLC_ENOMEM;
129     }
130     p_sys->streams.push_back( p_stream );
131
132     if( !p_sys->AnalyseAllSegmentsFound( p_demux, p_stream ) )
133     {
134         msg_Err( p_demux, "cannot find KaxSegment or missing mandatory KaxInfo" );
135         goto error;
136     }
137
138     for (size_t i=0; i<p_stream->segments.size(); i++)
139     {
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;
146     }
147
148     p_segment = p_stream->segments[0];
149     if( p_segment->cluster == NULL && p_segment->stored_editions.size() == 0 )
150     {
151         msg_Err( p_demux, "cannot find any cluster or chapter, damaged file ?" );
152         goto error;
153     }
154
155     if (b_need_preload && var_InheritBool( p_demux, "mkv-preload-local-dir" ))
156     {
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 ) )
160         {
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)
165             {
166                 s_path = s_path.substr(0,s_path.length()-1);
167             }
168             else
169             {
170                 if (s_path.find_last_of(DIR_SEP_CHAR) > 0)
171                 {
172                     s_path = s_path.substr(0,s_path.find_last_of(DIR_SEP_CHAR));
173                 }
174             }
175
176             DIR *p_src_dir = vlc_opendir(s_path.c_str());
177
178             if (p_src_dir != NULL)
179             {
180                 const char *psz_file;
181                 while ((psz_file = vlc_readdir(p_src_dir)) != NULL)
182                 {
183                     if (strlen(psz_file) > 4)
184                     {
185                         s_filename = s_path + DIR_SEP_CHAR + psz_file;
186
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
192                         {
193                             continue; // don't reuse the original opened file
194                         }
195
196                         if (!strcasecmp(s_filename.c_str() + s_filename.length() - 4, ".mkv") ||
197                             !strcasecmp(s_filename.c_str() + s_filename.length() - 4, ".mka"))
198                         {
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;
211
212                             if ( file_ok )
213                             {
214                                 matroska_stream_c *p_stream = new matroska_stream_c( p_file_stream, true );
215
216                                 if ( !p_sys->AnalyseAllSegmentsFound( p_demux, p_stream ) )
217                                 {
218                                     msg_Dbg( p_demux, "the file '%s' will not be used", s_filename.c_str() );
219                                     delete p_stream;
220                                 }
221                                 else
222                                 {
223                                     p_sys->streams.push_back( p_stream );
224                                 }
225                             }
226                             else
227                             {
228                                 if( p_file_stream ) {
229                                     vlc_stream_Delete( p_file_stream );
230                                 }
231                                 msg_Dbg( p_demux, "the file '%s' cannot be opened", s_filename.c_str() );
232                             }
233                             free( psz_url );
234                         }
235                     }
236                 }
237                 closedir( p_src_dir );
238             }
239         }
240
241         p_sys->PreloadFamily( *p_segment );
242     }
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");
245
246     if ( !p_sys->PreloadLinked() ||
247          !p_sys->PreparePlayback( *p_sys->p_current_vsegment, 0 ) )
248     {
249         msg_Err( p_demux, "cannot use the segment" );
250         goto error;
251     }
252
253     p_sys->FreeUnused();
254
255     p_sys->InitUi();
256
257     return VLC_SUCCESS;
258
259 error:
260     delete p_sys;
261     return VLC_EGENERIC;
262 }
263
264 /*****************************************************************************
265  * Close: frees unused data
266  *****************************************************************************/
267 static void Close( vlc_object_t *p_this )
268 {
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 )
273     {
274         matroska_segment_c *p_segment = p_vsegment->CurrentSegment();
275         if( p_segment )
276             p_segment->ESDestroy();
277     }
278
279     delete p_sys;
280 }
281
282 /*****************************************************************************
283  * Control:
284  *****************************************************************************/
285 static int Control( demux_t *p_demux, int i_query, va_list args )
286 {
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;
293
294     vlc_meta_t *p_meta;
295     input_attachment_t ***ppp_attach;
296     int *pi_int;
297
298     switch( i_query )
299     {
300         case DEMUX_CAN_SEEK:
301             return vlc_stream_vaControl( p_demux->s, i_query, args );
302
303         case DEMUX_GET_ATTACHMENTS:
304             ppp_attach = va_arg( args, input_attachment_t*** );
305             pi_int = va_arg( args, int * );
306
307             if( p_sys->stored_attachments.size() <= 0 )
308                 return VLC_EGENERIC;
309
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++ )
316             {
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] )
321                 {
322                     free(*ppp_attach);
323                     return VLC_ENOMEM;
324                 }
325             }
326             return VLC_SUCCESS;
327
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;
332
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;
340
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;
348
349         case DEMUX_SET_POSITION:
350             if( p_sys->f_duration > 0.0 )
351             {
352                 f = va_arg( args, double );
353                 b = va_arg( args, int ); /* precise? */
354                 return Seek( p_demux, -1, f, NULL, b );
355             }
356             return VLC_EGENERIC;
357
358         case DEMUX_GET_TIME:
359             pi64 = va_arg( args, int64_t * );
360             *pi64 = p_sys->i_pcr;
361             return VLC_SUCCESS;
362
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 ) )
365             {
366                 input_title_t ***ppp_title = va_arg( args, input_title_t*** );
367                 int *pi_int = va_arg( args, int* );
368
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* ) ) );
371
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;
375             }
376             return VLC_EGENERIC;
377
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)
382             {
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) )
389                 {
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;
394                 }
395                 else
396                 {
397                     p_sys->p_current_vsegment->i_current_edition = i_edition;
398                     p_sys->i_current_title = i_title;
399                 }
400             }
401             return VLC_EGENERIC;
402
403         case DEMUX_SET_SEEKPOINT:
404             i_skp = va_arg( args, int );
405
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)
408             {
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 )
411                 {
412                     p_sys->i_updates |= INPUT_UPDATE_SEEKPOINT;
413                     p_sys->i_current_seekpoint = i_skp;
414                 }
415                 return i_ret;
416             }
417             return VLC_EGENERIC;
418
419         case DEMUX_TEST_AND_CLEAR_FLAGS:
420         {
421             unsigned *restrict flags = va_arg( args, unsigned * );
422             *flags &= p_sys->i_updates;
423             p_sys->i_updates &= ~*flags;
424             return VLC_SUCCESS;
425         }
426
427         case DEMUX_GET_TITLE:
428             *va_arg( args, int * ) = p_sys->i_current_title;
429             return VLC_SUCCESS;
430
431         case DEMUX_GET_SEEKPOINT:
432             *va_arg( args, int * ) = p_sys->i_current_seekpoint;
433             return VLC_SUCCESS;
434
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() )
439             {
440                 typedef matroska_segment_c::tracks_map_t tracks_map_t;
441
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 )
444                 {
445                     const mkv_track_t &track = *it->second;
446
447                     if( track.fmt.i_cat == VIDEO_ES && track.fmt.video.i_frame_rate_base > 0 )
448                     {
449                         *pf = (double)track.fmt.video.i_frame_rate / track.fmt.video.i_frame_rate_base;
450                         break;
451                     }
452                 }
453             }
454             return VLC_SUCCESS;
455
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 );
461
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 );
467
468         default:
469             return VLC_EGENERIC;
470     }
471 }
472
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 )
475 {
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();
479
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 );
482
483     if( i_mk_date < 0 && f_percent < 0 )
484     {
485         msg_Warn( p_demux, "cannot seek nowhere!" );
486         return VLC_EGENERIC;
487     }
488     if( f_percent > 1.0 )
489     {
490         msg_Warn( p_demux, "cannot seek so far!" );
491         return VLC_EGENERIC;
492     }
493     if( p_sys->f_duration < 0 )
494     {
495         msg_Warn( p_demux, "cannot seek without duration!");
496         return VLC_EGENERIC;
497     }
498     if( !p_segment )
499     {
500         msg_Warn( p_demux, "cannot seek without valid segment position");
501         return VLC_EGENERIC;
502     }
503
504     /* seek without index or without date */
505     if( f_percent >= 0 && (var_InheritBool( p_demux, "mkv-seek-percent" ) || i_mk_date < 0 ))
506     {
507         i_mk_date = int64_t( f_percent * p_sys->f_duration * 1000.0 );
508     }
509     return p_vsegment->Seek( *p_demux, i_mk_date, p_vchapter, b_precise ) ? VLC_SUCCESS : VLC_EGENERIC;
510 }
511
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 )
516 {
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();
519
520     KaxInternalBlock& internal_block = simpleblock
521         ? static_cast<KaxInternalBlock&>( *simpleblock )
522         : static_cast<KaxInternalBlock&>( *block );
523
524     if( !p_segment ) return;
525
526     mkv_track_t *p_track = p_segment->FindTrackByBlock( block, simpleblock );
527     if( p_track == NULL )
528     {
529         msg_Err( p_demux, "invalid track number" );
530         return;
531     }
532
533     mkv_track_t &track = *p_track;
534
535     if( track.fmt.i_cat != DATA_ES && track.p_es == NULL )
536     {
537         msg_Err( p_demux, "unknown track number" );
538         return;
539     }
540
541     i_pts -= track.i_codec_delay;
542
543     if ( track.fmt.i_cat != DATA_ES )
544     {
545         bool b;
546         es_out_Control( p_demux->out, ES_OUT_GET_ES_STATE, track.p_es, &b );
547
548         if( !b )
549         {
550             if( track.fmt.i_cat == VIDEO_ES || track.fmt.i_cat == AUDIO_ES )
551                 track.i_last_dts = VLC_TICK_INVALID;
552             return;
553         }
554     }
555
556     size_t frame_size = 0;
557     size_t block_size = internal_block.GetSize();
558     const unsigned i_number_frames = internal_block.NumberFrames();
559
560     for( unsigned int i_frame = 0; i_frame < i_number_frames; i_frame++ )
561     {
562         block_t *p_block;
563         DataBuffer *data = &internal_block.GetBuffer(i_frame);
564
565         frame_size += data->Size();
566         if( !data->Buffer() || data->Size() > frame_size || frame_size > block_size  )
567         {
568             msg_Warn( p_demux, "Cannot read frame (too long or no frame)" );
569             break;
570         }
571         size_t extra_data = track.fmt.i_codec == VLC_CODEC_PRORES ? 8 : 0;
572
573         if( track.i_compression_type == MATROSKA_COMPRESSION_HEADER &&
574             track.p_compression_data != NULL &&
575             track.i_encoding_scope & MATROSKA_ENCODING_SCOPE_ALL_FRAMES )
576             p_block = MemToBlock( data->Buffer(), data->Size(), track.p_compression_data->GetSize() + extra_data );
577         else if( unlikely( track.fmt.i_codec == VLC_CODEC_WAVPACK ) )
578             p_block = packetize_wavpack( track, data->Buffer(), data->Size() );
579         else
580             p_block = MemToBlock( data->Buffer(), data->Size(), extra_data );
581
582         if( p_block == NULL )
583         {
584             break;
585         }
586
587 #if defined(HAVE_ZLIB_H)
588         if( track.i_compression_type == MATROSKA_COMPRESSION_ZLIB &&
589             track.i_encoding_scope & MATROSKA_ENCODING_SCOPE_ALL_FRAMES )
590         {
591             p_block = block_zlib_decompress( VLC_OBJECT(p_demux), p_block );
592             if( p_block == NULL )
593                 break;
594         }
595         else
596 #endif
597         if( track.i_compression_type == MATROSKA_COMPRESSION_HEADER &&
598             track.i_encoding_scope & MATROSKA_ENCODING_SCOPE_ALL_FRAMES )
599         {
600             memcpy( p_block->p_buffer, track.p_compression_data->GetBuffer(), track.p_compression_data->GetSize() );
601         }
602         if ( track.fmt.i_codec == VLC_CODEC_PRORES )
603             memcpy( p_block->p_buffer + 4, "icpf", 4 );
604
605         if ( b_key_picture )
606             p_block->i_flags |= BLOCK_FLAG_TYPE_I;
607
608         switch( track.fmt.i_codec )
609         {
610         case VLC_CODEC_COOK:
611         case VLC_CODEC_ATRAC3:
612         {
613             handle_real_audio(p_demux, &track, p_block, i_pts);
614             block_Release(p_block);
615             i_pts = ( track.i_default_duration )?
616                 i_pts + ( vlc_tick_t )track.i_default_duration:
617                 VLC_TICK_INVALID;
618             continue;
619          }
620
621          case VLC_CODEC_WEBVTT:
622             {
623                 p_block = block_Realloc( p_block, 16, p_block->i_buffer );
624                 if( !p_block )
625                     continue;
626                 SetDWBE( p_block->p_buffer, p_block->i_buffer );
627                 memcpy( &p_block->p_buffer[4], "vttc", 4 );
628                 SetDWBE( &p_block->p_buffer[8], p_block->i_buffer - 8 );
629                 memcpy( &p_block->p_buffer[12], "payl", 4 );
630             }
631             break;
632
633          case VLC_CODEC_OPUS:
634             {
635                 vlc_tick_t i_length = i_duration * track. f_timecodescale *
636                         (double) p_segment->i_timescale / 1000.0;
637                 if ( i_length < 0 ) i_length = 0;
638                 p_block->i_nb_samples = i_length * track.fmt.audio.i_rate
639                         / CLOCK_FREQ;
640             }
641             break;
642
643          case VLC_CODEC_DVBS:
644             {
645                 p_block = block_Realloc( p_block, 2, p_block->i_buffer + 1);
646
647                 if( unlikely( !p_block ) )
648                     continue;
649
650                 p_block->p_buffer[0] = 0x20; // data identifier
651                 p_block->p_buffer[1] = 0x00; // subtitle stream id
652                 p_block->p_buffer[ p_block->i_buffer - 1 ] = 0x3f; // end marker
653             }
654             break;
655         }
656
657         if( track.fmt.i_cat != VIDEO_ES )
658         {
659             if ( track.fmt.i_cat == DATA_ES )
660             {
661                 // TODO handle the start/stop times of this packet
662                 p_sys->p_ev->SetPci( (const pci_t *)&p_block->p_buffer[1]);
663                 block_Release( p_block );
664                 return;
665             }
666             p_block->i_dts = p_block->i_pts = i_pts;
667         }
668         else
669         {
670             // correct timestamping when B frames are used
671             if( track.b_dts_only )
672             {
673                 p_block->i_pts = VLC_TICK_INVALID;
674                 p_block->i_dts = i_pts;
675             }
676             else if( track.b_pts_only )
677             {
678                 p_block->i_pts = i_pts;
679                 p_block->i_dts = i_pts;
680             }
681             else
682             {
683                 p_block->i_pts = i_pts;
684                 // condition when the DTS is correct (keyframe or B frame == NOT P frame)
685                 if ( b_key_picture || b_discardable_picture )
686                         p_block->i_dts = p_block->i_pts;
687                 else if ( track.i_last_dts == VLC_TICK_INVALID )
688                     p_block->i_dts = i_pts;
689                 else
690                     p_block->i_dts = std::min( i_pts, track.i_last_dts + ( vlc_tick_t )track.i_default_duration );
691             }
692         }
693
694         send_Block( p_demux, &track, p_block, i_number_frames, i_duration );
695
696         /* use time stamp only for first block */
697         i_pts = ( track.i_default_duration )?
698                  i_pts + ( vlc_tick_t )track.i_default_duration:
699                  ( track.fmt.b_packetized ) ? VLC_TICK_INVALID : i_pts + 1;
700     }
701 }
702
703 /*****************************************************************************
704  * Demux: reads and demuxes data packets
705  *****************************************************************************
706  * Returns -1 in case of error, 0 in case of EOF, 1 otherwise
707  *****************************************************************************/
708 static int Demux( demux_t *p_demux)
709 {
710     demux_sys_t *p_sys = (demux_sys_t *)p_demux->p_sys;
711
712     vlc_mutex_locker demux_lock ( &p_sys->lock_demuxer );
713
714     virtual_segment_c  *p_vsegment = p_sys->p_current_vsegment;
715
716     if( p_sys->i_pts >= p_sys->i_start_pts )
717     {
718         if ( p_vsegment->UpdateCurrentToChapter( *p_demux ) )
719             return VLC_DEMUXER_SUCCESS;
720         p_vsegment = p_sys->p_current_vsegment;
721     }
722
723     matroska_segment_c *p_segment = p_vsegment->CurrentSegment();
724     if ( p_segment == NULL )
725         return VLC_DEMUXER_EOF;
726
727     KaxBlock *block;
728     KaxSimpleBlock *simpleblock;
729     int64_t i_block_duration = 0;
730     bool b_key_picture;
731     bool b_discardable_picture;
732
733     if( p_segment->BlockGet( block, simpleblock, &b_key_picture, &b_discardable_picture, &i_block_duration ) )
734     {
735         if ( p_vsegment->CurrentEdition() && p_vsegment->CurrentEdition()->b_ordered )
736         {
737             const virtual_chapter_c *p_chap = p_vsegment->CurrentChapter();
738             // check if there are more chapters to read
739             if ( p_chap != NULL )
740             {
741                 /* TODO handle successive chapters with the same user_start_time/user_end_time
742                 */
743                 p_sys->i_pts = p_chap->i_mk_virtual_stop_time + VLC_TICK_0;
744                 p_sys->i_pts++; // trick to avoid staying on segments with no duration and no content
745
746                 return VLC_DEMUXER_SUCCESS;
747             }
748         }
749
750         msg_Warn( p_demux, "cannot get block EOF?" );
751         return VLC_DEMUXER_EOF;
752     }
753
754     KaxInternalBlock& internal_block = block
755         ? static_cast<KaxInternalBlock&>( *block )
756         : static_cast<KaxInternalBlock&>( *simpleblock );
757
758     {
759         mkv_track_t *p_track = p_segment->FindTrackByBlock( block, simpleblock );
760
761         if( p_track == NULL )
762         {
763             msg_Err( p_demux, "invalid track number" );
764             delete block;
765             return VLC_DEMUXER_EGENERIC;
766         }
767
768         mkv_track_t &track = *p_track;
769
770
771         if( track.i_skip_until_fpos != std::numeric_limits<uint64_t>::max() ) {
772
773             uint64_t block_fpos = internal_block.GetElementPosition();
774
775             if ( track.i_skip_until_fpos > block_fpos )
776             {
777                 delete block;
778                 return VLC_DEMUXER_SUCCESS; // this block shall be ignored
779             }
780         }
781     }
782
783     /* update pcr */
784     {
785         vlc_tick_t i_pcr = VLC_TICK_INVALID;
786
787         typedef matroska_segment_c::tracks_map_t tracks_map_t;
788
789         for( tracks_map_t::const_iterator it = p_segment->tracks.begin(); it != p_segment->tracks.end(); ++it )
790         {
791             mkv_track_t &track = *it->second;
792
793             if( track.i_last_dts == VLC_TICK_INVALID )
794                 continue;
795
796             if( track.fmt.i_cat != VIDEO_ES && track.fmt.i_cat != AUDIO_ES )
797                 continue;
798
799             if( track.i_last_dts < i_pcr || i_pcr == VLC_TICK_INVALID )
800             {
801                 i_pcr = track.i_last_dts;
802             }
803         }
804
805         if( i_pcr != VLC_TICK_INVALID && i_pcr > p_sys->i_pcr )
806         {
807             if( es_out_SetPCR( p_demux->out, i_pcr ) )
808             {
809                 msg_Err( p_demux, "ES_OUT_SET_PCR failed, aborting." );
810                 return VLC_DEMUXER_EGENERIC;
811             }
812
813             p_sys->i_pcr = i_pcr;
814         }
815     }
816
817     /* set pts */
818     {
819         p_sys->i_pts = p_sys->i_mk_chapter_time + VLC_TICK_0;
820         p_sys->i_pts += internal_block.GlobalTimecode() / INT64_C( 1000 );
821     }
822
823     if ( p_vsegment->CurrentEdition() &&
824          p_vsegment->CurrentEdition()->b_ordered &&
825          p_vsegment->CurrentChapter() == NULL )
826     {
827         /* nothing left to read in this ordered edition */
828         delete block;
829         return VLC_DEMUXER_EOF;
830     }
831
832     BlockDecode( p_demux, block, simpleblock, p_sys->i_pts, i_block_duration, b_key_picture, b_discardable_picture );
833
834     delete block;
835
836     return VLC_DEMUXER_SUCCESS;
837 }
838
839 mkv_track_t::mkv_track_t(enum es_format_category_e es_cat) :
840     b_default(true)
841   ,b_enabled(true)
842   ,b_forced(false)
843   ,i_number(0)
844   ,i_extra_data(0)
845   ,p_extra_data(NULL)
846   ,b_dts_only(false)
847   ,b_pts_only(false)
848   ,b_no_duration(false)
849   ,i_default_duration(0)
850   ,f_timecodescale(1.0)
851   ,i_last_dts(VLC_TICK_INVALID)
852   ,i_skip_until_fpos(std::numeric_limits<uint64_t>::max())
853   ,f_fps(0)
854   ,p_es(NULL)
855   ,i_original_rate(0)
856   ,i_chans_to_reorder(0)
857   ,p_sys(NULL)
858   ,b_discontinuity(false)
859   ,i_compression_type(MATROSKA_COMPRESSION_NONE)
860   ,i_encoding_scope(MATROSKA_ENCODING_SCOPE_ALL_FRAMES)
861   ,p_compression_data(NULL)
862   ,i_seek_preroll(0)
863   ,i_codec_delay(0)
864 {
865     std::memset( &pi_chan_table, 0, sizeof( pi_chan_table ) );
866
867     es_format_Init(&fmt, es_cat, 0);
868
869     switch( es_cat )
870     {
871         case AUDIO_ES:
872             fmt.audio.i_channels = 1;
873             fmt.audio.i_rate = 8000;
874             /* fall through */
875         case VIDEO_ES:
876         case SPU_ES:
877             fmt.psz_language = strdup("English");
878             break;
879         default:
880             // no language needed
881             break;
882     }
883 }
884
885 mkv_track_t::~mkv_track_t()
886 {
887     es_format_Clean( &fmt );
888     assert(p_es == NULL); // did we leak an ES ?
889
890     free(p_extra_data);
891
892     delete p_compression_data;
893     delete p_sys;
894 }
895
896 matroska_stream_c::matroska_stream_c( stream_t *s, bool owner )
897     :io_callback( s, owner )
898     ,estream( io_callback )
899 {}
900
901 bool matroska_stream_c::isUsed() const
902 {
903     for( size_t j = 0; j < segments.size(); j++ )
904     {
905         if( segments[j]->b_preloaded )
906             return true;
907     }
908     return false;
909 }
910
911 } // namespace