mkv.cpp 28.6 KB
Newer Older
Steve Lhomme's avatar
Steve Lhomme committed
1
2
3
/*****************************************************************************
 * mkv.cpp : matroska demuxer
 *****************************************************************************
Jean-Baptiste Kempf's avatar
LGPL    
Jean-Baptiste Kempf committed
4
 * Copyright (C) 2003-2005, 2008, 2010 VLC authors and VideoLAN
Steve Lhomme's avatar
Steve Lhomme committed
5
6
7
8
9
 * $Id$
 *
 * Authors: Laurent Aimar <fenrir@via.ecp.fr>
 *          Steve Lhomme <steve.lhomme@free.fr>
 *
Jean-Baptiste Kempf's avatar
LGPL    
Jean-Baptiste Kempf committed
10
11
12
 * This program is free software; you can redistribute it and/or modify it
 * under the terms of the GNU Lesser General Public License as published by
 * the Free Software Foundation; either version 2.1 of the License, or
Steve Lhomme's avatar
Steve Lhomme committed
13
14
15
16
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
Jean-Baptiste Kempf's avatar
LGPL    
Jean-Baptiste Kempf committed
17
18
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
 * GNU Lesser General Public License for more details.
Steve Lhomme's avatar
Steve Lhomme committed
19
 *
Jean-Baptiste Kempf's avatar
LGPL    
Jean-Baptiste Kempf committed
20
21
22
 * You should have received a copy of the GNU Lesser General Public License
 * along with this program; if not, write to the Free Software Foundation,
 * Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA.
Steve Lhomme's avatar
Steve Lhomme committed
23
24
 *****************************************************************************/

25
26
#include "mkv.hpp"
#include "util.hpp"
Steve Lhomme's avatar
Steve Lhomme committed
27

28
29
#include "matroska_segment.hpp"
#include "demux.hpp"
Steve Lhomme's avatar
Steve Lhomme committed
30

31
32
#include "chapters.hpp"
#include "Ebml_parser.hpp"
Steve Lhomme's avatar
Steve Lhomme committed
33

34
#include "stream_io_callback.hpp"
Steve Lhomme's avatar
Steve Lhomme committed
35

Rémi Denis-Courmont's avatar
Rémi Denis-Courmont committed
36
#include <vlc_fs.h>
Denis Charmet's avatar
Denis Charmet committed
37
#include <vlc_url.h>
Rémi Denis-Courmont's avatar
Rémi Denis-Courmont committed
38

39
40
41
42
43
44
/*****************************************************************************
 * Module descriptor
 *****************************************************************************/
static int  Open ( vlc_object_t * );
static void Close( vlc_object_t * );

45
46
47
vlc_module_begin ()
    set_shortname( "Matroska" )
    set_description( N_("Matroska stream demuxer" ) )
48
    set_capability( "demux", 50 )
49
50
51
    set_callbacks( Open, Close )
    set_category( CAT_INPUT )
    set_subcategory( SUBCAT_INPUT_DEMUX )
52

53
    add_bool( "mkv-use-ordered-chapters", true,
54
55
            N_("Respect ordered chapters"),
            N_("Play chapters in the order specified in the segment."), false );
56

57
    add_bool( "mkv-use-chapter-codec", true,
58
59
60
            N_("Chapter codecs"),
            N_("Use chapter codecs found in the segment."), true );

61
    add_bool( "mkv-preload-local-dir", true,
62
63
            N_("Preload MKV files in the same directory"),
            N_("Preload matroska files in the same directory to find linked segments (not good for broken files)."), false );
64

65
    add_bool( "mkv-seek-percent", false,
66
67
68
            N_("Seek based on percent not time"),
            N_("Seek based on percent not time."), true );

69
    add_bool( "mkv-use-dummy", false,
70
71
72
            N_("Dummy Elements"),
            N_("Read and discard unknown EBML elements (not good for broken files)."), true );

73
    add_shortcut( "mka", "mkv" )
74
vlc_module_end ()
75

76
class demux_sys_t;
77

78
79
static int  Demux  ( demux_t * );
static int  Control( demux_t *, int, va_list );
Denis Charmet's avatar
Denis Charmet committed
80
static void Seek   ( demux_t *, mtime_t i_date, double f_percent, virtual_chapter_c *p_chapter );
81

82
83
84
85
86
87
88
89
90
91
92
93
94
/*****************************************************************************
 * Open: initializes matroska demux structures
 *****************************************************************************/
static int Open( vlc_object_t * p_this )
{
    demux_t            *p_demux = (demux_t*)p_this;
    demux_sys_t        *p_sys;
    matroska_stream_c  *p_stream;
    matroska_segment_c *p_segment;
    const uint8_t      *p_peek;
    std::string         s_path, s_filename;
    vlc_stream_io_callback *p_io_callback;
    EbmlStream         *p_io_stream;
95
    bool                b_need_preload = false;
96

97
98
    /* peek the begining */
    if( stream_Peek( p_demux->s, &p_peek, 4 ) < 4 ) return VLC_EGENERIC;
99

100
101
102
    /* is a valid file */
    if( p_peek[0] != 0x1a || p_peek[1] != 0x45 ||
        p_peek[2] != 0xdf || p_peek[3] != 0xa3 ) return VLC_EGENERIC;
Steve Lhomme's avatar
Steve Lhomme committed
103

104
105
106
107
    /* Set the demux function */
    p_demux->pf_demux   = Demux;
    p_demux->pf_control = Control;
    p_demux->p_sys      = p_sys = new demux_sys_t( *p_demux );
Steve Lhomme's avatar
Steve Lhomme committed
108

109
110
    p_io_callback = new vlc_stream_io_callback( p_demux->s, false );
    p_io_stream = new EbmlStream( *p_io_callback );
Steve Lhomme's avatar
Steve Lhomme committed
111

112
    if( p_io_stream == NULL )
Steve Lhomme's avatar
Steve Lhomme committed
113
    {
114
115
116
117
        msg_Err( p_demux, "failed to create EbmlStream" );
        delete p_io_callback;
        delete p_sys;
        return VLC_EGENERIC;
Steve Lhomme's avatar
Steve Lhomme committed
118
119
    }

120
121
    p_stream = p_sys->AnalyseAllSegmentsFound( p_demux, p_io_stream, true );
    if( p_stream == NULL )
Steve Lhomme's avatar
Steve Lhomme committed
122
    {
123
        msg_Err( p_demux, "cannot find KaxSegment or missing mandatory KaxInfo" );
124
        goto error;
Steve Lhomme's avatar
Steve Lhomme committed
125
    }
126
    p_sys->streams.push_back( p_stream );
Steve Lhomme's avatar
Steve Lhomme committed
127

128
129
    p_stream->p_io_callback = p_io_callback;
    p_stream->p_estream = p_io_stream;
Steve Lhomme's avatar
Steve Lhomme committed
130

131
132
133
    for (size_t i=0; i<p_stream->segments.size(); i++)
    {
        p_stream->segments[i]->Preload();
134
        b_need_preload |= p_stream->segments[i]->b_ref_external_segments;
135
    }
Steve Lhomme's avatar
Steve Lhomme committed
136

137
138
    p_segment = p_stream->segments[0];
    if( p_segment->cluster == NULL )
Steve Lhomme's avatar
Steve Lhomme committed
139
    {
140
141
        msg_Err( p_demux, "cannot find any cluster, damaged file ?" );
        goto error;
Steve Lhomme's avatar
Steve Lhomme committed
142
    }
143

144
    if (b_need_preload && var_InheritBool( p_demux, "mkv-preload-local-dir" ))
145
    {
146
        msg_Dbg( p_demux, "Preloading local dir" );
147
        /* get the files from the same dir from the same family (based on p_demux->psz_path) */
Denis Charmet's avatar
Denis Charmet committed
148
        if ( p_demux->psz_file && !strcmp( p_demux->psz_access, "file" ) )
149
150
151
        {
            // assume it's a regular file
            // get the directory path
152
            s_path = p_demux->psz_file;
153
            if (s_path.at(s_path.length() - 1) == DIR_SEP_CHAR)
154
155
156
157
158
            {
                s_path = s_path.substr(0,s_path.length()-1);
            }
            else
            {
159
                if (s_path.find_last_of(DIR_SEP_CHAR) > 0)
160
                {
161
                    s_path = s_path.substr(0,s_path.find_last_of(DIR_SEP_CHAR));
162
163
                }
            }
Steve Lhomme's avatar
Steve Lhomme committed
164

165
            DIR *p_src_dir = vlc_opendir(s_path.c_str());
166

167
168
            if (p_src_dir != NULL)
            {
169
                const char *psz_file;
170
                while ((psz_file = vlc_readdir(p_src_dir)) != NULL)
171
172
173
                {
                    if (strlen(psz_file) > 4)
                    {
174
                        s_filename = s_path + DIR_SEP_CHAR + psz_file;
Steve Lhomme's avatar
Steve Lhomme committed
175

176
#if defined(_WIN32) || defined(__OS2__)
177
                        if (!strcasecmp(s_filename.c_str(), p_demux->psz_file))
178
#else
179
                        if (!s_filename.compare(p_demux->psz_file))
180
181
182
183
#endif
                        {
                            continue; // don't reuse the original opened file
                        }
Steve Lhomme's avatar
Steve Lhomme committed
184

185
186
187
                        if (!s_filename.compare(s_filename.length() - 3, 3, "mkv") ||
                            !s_filename.compare(s_filename.length() - 3, 3, "mka"))
                        {
Konstantin Pavlov's avatar
Konstantin Pavlov committed
188
                            // test whether this file belongs to our family
189
190
                            const uint8_t *p_peek;
                            bool          file_ok = false;
191
192
#warning Memory leak!
                            std::string   s_url = vlc_path2uri( s_filename.c_str(), "file" );
193
194
                            stream_t      *p_file_stream = stream_UrlNew(
                                                            p_demux,
Denis Charmet's avatar
Denis Charmet committed
195
                                                            s_url.c_str() );
196
197
198
199
200
201
202
203
204
205
                            /* peek the begining */
                            if( p_file_stream &&
                                stream_Peek( p_file_stream, &p_peek, 4 ) >= 4
                                && p_peek[0] == 0x1a && p_peek[1] == 0x45 &&
                                p_peek[2] == 0xdf && p_peek[3] == 0xa3 ) file_ok = true;

                            if ( file_ok )
                            {
                                vlc_stream_io_callback *p_file_io = new vlc_stream_io_callback( p_file_stream, true );
                                EbmlStream *p_estream = new EbmlStream(*p_file_io);
Steve Lhomme's avatar
Steve Lhomme committed
206

207
                                p_stream = p_sys->AnalyseAllSegmentsFound( p_demux, p_estream );
Steve Lhomme's avatar
Steve Lhomme committed
208

209
210
211
212
213
214
215
216
                                if ( p_stream == NULL )
                                {
                                    msg_Dbg( p_demux, "the file '%s' will not be used", s_filename.c_str() );
                                    delete p_estream;
                                    delete p_file_io;
                                }
                                else
                                {
217
218
                                    p_stream->p_io_callback = p_file_io;
                                    p_stream->p_estream = p_estream;
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
                                    p_sys->streams.push_back( p_stream );
                                }
                            }
                            else
                            {
                                if( p_file_stream ) {
                                    stream_Delete( p_file_stream );
                                }
                                msg_Dbg( p_demux, "the file '%s' cannot be opened", s_filename.c_str() );
                            }
                        }
                    }
                }
                closedir( p_src_dir );
            }
        }
235

236
237
        p_sys->PreloadFamily( *p_segment );
    }
238
239
    else if (b_need_preload)
        msg_Warn( p_demux, "This file references other files, you may want to enable the preload of local directory");
Steve Lhomme's avatar
Steve Lhomme committed
240

csun's avatar
csun committed
241
242
    if ( !p_sys->PreloadLinked() ||
         !p_sys->PreparePlayback( NULL ) )
243
244
245
246
    {
        msg_Err( p_demux, "cannot use the segment" );
        goto error;
    }
Steve Lhomme's avatar
Steve Lhomme committed
247

248
249
    p_sys->FreeUnused();

250
    p_sys->InitUi();
251

252
    return VLC_SUCCESS;
Steve Lhomme's avatar
Steve Lhomme committed
253

254
255
256
257
error:
    delete p_sys;
    return VLC_EGENERIC;
}
Steve Lhomme's avatar
Steve Lhomme committed
258
259

/*****************************************************************************
260
 * Close: frees unused data
Steve Lhomme's avatar
Steve Lhomme committed
261
 *****************************************************************************/
262
static void Close( vlc_object_t *p_this )
Steve Lhomme's avatar
Steve Lhomme committed
263
{
264
265
    demux_t     *p_demux = (demux_t*)p_this;
    demux_sys_t *p_sys   = p_demux->p_sys;
266
267
268
269
270
271
272
    virtual_segment_c *p_vsegment = p_sys->p_current_segment;
    if( p_vsegment )
    {
        matroska_segment_c *p_segment = p_vsegment->CurrentSegment();
        if( p_segment )
            p_segment->UnSelect();
    }
273
274

    delete p_sys;
Steve Lhomme's avatar
Steve Lhomme committed
275
276
277
}

/*****************************************************************************
278
 * Control:
Steve Lhomme's avatar
Steve Lhomme committed
279
 *****************************************************************************/
280
static int Control( demux_t *p_demux, int i_query, va_list args )
Steve Lhomme's avatar
Steve Lhomme committed
281
{
282
    demux_sys_t        *p_sys = p_demux->p_sys;
Denis Charmet's avatar
Denis Charmet committed
283
    int64_t     *pi64, i64;
284
285
286
    double      *pf, f;
    int         i_skp;
    size_t      i_idx;
Steve Lhomme's avatar
Steve Lhomme committed
287

288
289
290
    vlc_meta_t *p_meta;
    input_attachment_t ***ppp_attach;
    int *pi_int;
Steve Lhomme's avatar
Steve Lhomme committed
291

292
293
294
295
296
    switch( i_query )
    {
        case DEMUX_GET_ATTACHMENTS:
            ppp_attach = (input_attachment_t***)va_arg( args, input_attachment_t*** );
            pi_int = (int*)va_arg( args, int * );
Steve Lhomme's avatar
Steve Lhomme committed
297

298
299
            if( p_sys->stored_attachments.size() <= 0 )
                return VLC_EGENERIC;
300

301
            *pi_int = p_sys->stored_attachments.size();
ivoire's avatar
ivoire committed
302
            *ppp_attach = (input_attachment_t**)malloc( sizeof(input_attachment_t*) *
303
304
305
                                                        p_sys->stored_attachments.size() );
            if( !(*ppp_attach) )
                return VLC_ENOMEM;
Jean-Baptiste Kempf's avatar
Jean-Baptiste Kempf committed
306
            for( size_t i = 0; i < p_sys->stored_attachments.size(); i++ )
307
308
            {
                attachment_c *a = p_sys->stored_attachments[i];
309
310
                (*ppp_attach)[i] = vlc_input_attachment_New( a->fileName(), a->mimeType(), NULL,
                                                             a->p_data, a->size() );
311
312
            }
            return VLC_SUCCESS;
Steve Lhomme's avatar
Steve Lhomme committed
313

314
315
316
317
        case DEMUX_GET_META:
            p_meta = (vlc_meta_t*)va_arg( args, vlc_meta_t* );
            vlc_meta_Merge( p_meta, p_sys->meta );
            return VLC_SUCCESS;
Steve Lhomme's avatar
Steve Lhomme committed
318

319
320
321
322
323
324
325
326
        case DEMUX_GET_LENGTH:
            pi64 = (int64_t*)va_arg( args, int64_t * );
            if( p_sys->f_duration > 0.0 )
            {
                *pi64 = (int64_t)(p_sys->f_duration * 1000);
                return VLC_SUCCESS;
            }
            return VLC_EGENERIC;
Steve Lhomme's avatar
Steve Lhomme committed
327

328
329
330
331
332
        case DEMUX_GET_POSITION:
            pf = (double*)va_arg( args, double * );
            if ( p_sys->f_duration > 0.0 )
                *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);
            return VLC_SUCCESS;
Steve Lhomme's avatar
Steve Lhomme committed
333

334
        case DEMUX_SET_POSITION:
335
336
337
338
339
340
341
            if( p_sys->f_duration > 0.0 )
            {
                f = (double)va_arg( args, double );
                Seek( p_demux, -1, f, NULL );
                return VLC_SUCCESS;
            }
            return VLC_EGENERIC;
Steve Lhomme's avatar
Steve Lhomme committed
342

343
344
345
346
        case DEMUX_GET_TIME:
            pi64 = (int64_t*)va_arg( args, int64_t * );
            *pi64 = p_sys->i_pts;
            return VLC_SUCCESS;
347

348
349
350
351
352
        case DEMUX_GET_TITLE_INFO:
            if( p_sys->titles.size() > 1 || ( p_sys->titles.size() == 1 && p_sys->titles[0]->i_seekpoint > 0 ) )
            {
                input_title_t ***ppp_title = (input_title_t***)va_arg( args, input_title_t*** );
                int *pi_int    = (int*)va_arg( args, int* );
353

354
                *pi_int = p_sys->titles.size();
355
                *ppp_title = (input_title_t**)malloc( sizeof( input_title_t* ) * p_sys->titles.size() );
Steve Lhomme's avatar
Steve Lhomme committed
356

357
358
359
360
361
                for( size_t i = 0; i < p_sys->titles.size(); i++ )
                    (*ppp_title)[i] = vlc_input_title_Duplicate( p_sys->titles[i] );
                return VLC_SUCCESS;
            }
            return VLC_EGENERIC;
362

363
        case DEMUX_SET_TITLE:
364
            /* handle editions as titles */
365
            i_idx = (int)va_arg( args, int );
366
            if(i_idx <  p_sys->titles.size() && p_sys->titles[i_idx]->i_seekpoint)
367
            {
368
369
370
371
372
                p_sys->p_current_segment->i_current_edition = i_idx;
                p_sys->i_current_title = i_idx;
                p_sys->p_current_segment->p_current_chapter = p_sys->p_current_segment->editions[p_sys->p_current_segment->i_current_edition]->getChapterbyTimecode(0);

                Seek( p_demux, (int64_t)p_sys->titles[i_idx]->seekpoint[0]->i_time_offset, -1, NULL);
373
                p_demux->info.i_update |= INPUT_UPDATE_SEEKPOINT;
374
                p_demux->info.i_seekpoint = 0;
375
                p_sys->f_duration = (float) p_sys->titles[i_idx]->i_length / 1000.f;
376
377
378
                return VLC_SUCCESS;
            }
            return VLC_EGENERIC;
379

380
381
        case DEMUX_SET_SEEKPOINT:
            i_skp = (int)va_arg( args, int );
382

383
384
385
386
            // TODO change the way it works with the << & >> buttons on the UI (+1/-1 instead of a number)
            if( p_sys->titles.size() && i_skp < p_sys->titles[p_sys->i_current_title]->i_seekpoint)
            {
                Seek( p_demux, (int64_t)p_sys->titles[p_sys->i_current_title]->seekpoint[i_skp]->i_time_offset, -1, NULL);
387
                p_demux->info.i_update |= INPUT_UPDATE_SEEKPOINT;
388
389
390
391
                p_demux->info.i_seekpoint = i_skp;
                return VLC_SUCCESS;
            }
            return VLC_EGENERIC;
392

393
394
395
        case DEMUX_GET_FPS:
            pf = (double *)va_arg( args, double * );
            *pf = 0.0;
396
            if( p_sys->p_current_segment && p_sys->p_current_segment->CurrentSegment() )
397
            {
398
                const matroska_segment_c *p_segment = p_sys->p_current_segment->CurrentSegment();
399
400
401
402
403
404
405
406
407
408
409
                for( size_t i = 0; i < p_segment->tracks.size(); i++ )
                {
                    mkv_track_t *tk = p_segment->tracks[i];
                    if( tk->fmt.i_cat == VIDEO_ES && tk->fmt.video.i_frame_rate_base > 0 )
                    {
                        *pf = (double)tk->fmt.video.i_frame_rate / tk->fmt.video.i_frame_rate_base;
                        break;
                    }
                }
            }
            return VLC_SUCCESS;
410

411
        case DEMUX_SET_TIME:
Denis Charmet's avatar
Denis Charmet committed
412
413
414
415
            i64 = (int64_t) va_arg( args, int64_t );
            msg_Dbg(p_demux,"SET_TIME to %"PRId64, i64 );
            Seek( p_demux, i64, -1, NULL );
            return VLC_SUCCESS;
416
417
        default:
            return VLC_EGENERIC;
418
    }
419
}
420

421
/* Seek */
Denis Charmet's avatar
Denis Charmet committed
422
static void Seek( demux_t *p_demux, mtime_t i_date, double f_percent, virtual_chapter_c *p_chapter )
423
424
425
{
    demux_sys_t        *p_sys = p_demux->p_sys;
    virtual_segment_c  *p_vsegment = p_sys->p_current_segment;
426
    matroska_segment_c *p_segment = p_vsegment->CurrentSegment();
427
428
    mtime_t            i_time_offset = 0;
    int64_t            i_global_position = -1;
429

430
    int         i_index;
431

432
433
    msg_Dbg( p_demux, "seek request to %"PRId64" (%f%%)", i_date, f_percent );
    if( i_date < 0 && f_percent < 0 )
Steve Lhomme's avatar
Steve Lhomme committed
434
    {
Denis Charmet's avatar
Denis Charmet committed
435
        msg_Warn( p_demux, "cannot seek nowhere!" );
436
        return;
Steve Lhomme's avatar
Steve Lhomme committed
437
    }
438
    if( f_percent > 1.0 )
Steve Lhomme's avatar
Steve Lhomme committed
439
    {
Denis Charmet's avatar
Denis Charmet committed
440
441
442
443
444
445
        msg_Warn( p_demux, "cannot seek so far!" );
        return;
    }
    if( p_sys->f_duration < 0 )
    {
        msg_Warn( p_demux, "cannot seek without duration!");
446
        return;
Steve Lhomme's avatar
Steve Lhomme committed
447
    }
448
449
450
451
452
    if( !p_segment )
    {
        msg_Warn( p_demux, "cannot seek without valid segment position");
        return;
    }
453

454
    /* seek without index or without date */
455
    if( f_percent >= 0 && (var_InheritBool( p_demux, "mkv-seek-percent" ) || !p_segment->b_cues || i_date < 0 ))
456
    {
Denis Charmet's avatar
Denis Charmet committed
457
458
        i_date = int64_t( f_percent * p_sys->f_duration * 1000.0 );
        if( !p_segment->b_cues )
459
        {
460
            int64_t i_pos = int64_t( f_percent * stream_Size( p_demux->s ) );
461

Denis Charmet's avatar
Denis Charmet committed
462
            msg_Dbg( p_demux, "lengthy way of seeking for pos:%"PRId64, i_pos );
463
464
            for( i_index = 0; i_index < p_segment->i_index; i_index++ )
            {
Denis Charmet's avatar
Denis Charmet committed
465
466
                if( p_segment->p_indexes[i_index].i_position >= i_pos &&
                    p_segment->p_indexes[i_index].i_time > 0 )
467
468
469
470
                    break;
            }
            if( i_index == p_segment->i_index )
                i_index--;
471

Denis Charmet's avatar
Denis Charmet committed
472
            if( p_segment->p_indexes[i_index].i_position < i_pos )
473
474
475
476
477
478
            {
                msg_Dbg( p_demux, "no cues, seek request to global pos: %"PRId64, i_pos );
                i_global_position = i_pos;
            }
        }
    }
479
    p_vsegment->Seek( *p_demux, i_date, i_time_offset, p_chapter, i_global_position );
480
}
481

482
483
/* Needed by matroska_segment::Seek() and Seek */
void BlockDecode( demux_t *p_demux, KaxBlock *block, KaxSimpleBlock *simpleblock,
484
                         mtime_t i_pts, mtime_t i_duration, bool f_mandatory )
485
{
486
    demux_sys_t        *p_sys = p_demux->p_sys;
487
    matroska_segment_c *p_segment = p_sys->p_current_segment->CurrentSegment();
Steve Lhomme's avatar
Steve Lhomme committed
488

489
    if( !p_segment ) return;
490

491
    size_t          i_track;
492
    if( p_segment->BlockFindTrackIndex( &i_track, block, simpleblock ) )
493
    {
494
495
        msg_Err( p_demux, "invalid track number" );
        return;
496
497
    }

498
    mkv_track_t *tk = p_segment->tracks[i_track];
499

500
    if( tk->fmt.i_cat != NAV_ES && tk->p_es == NULL )
501
    {
502
503
        msg_Err( p_demux, "unknown track number" );
        return;
504
    }
505
506

    i_pts -= tk->i_codec_delay;
Steve Lhomme's avatar
Steve Lhomme committed
507

508
    if ( tk->fmt.i_cat != NAV_ES )
509
    {
510
511
        bool b;
        es_out_Control( p_demux->out, ES_OUT_GET_ES_STATE, tk->p_es, &b );
512

513
        if( !b )
514
        {
515
            tk->b_inited = false;
516
517
            if( tk->fmt.i_cat == VIDEO_ES || tk->fmt.i_cat == AUDIO_ES )
                tk->i_last_dts = i_pts;
518
            return;
519
        }
520
521
    }

522

523
524
    /* First send init data */
    if( !tk->b_inited && tk->i_data_init > 0 )
525
    {
526
        block_t *p_init;
527

528
        msg_Dbg( p_demux, "sending header (%d bytes)", tk->i_data_init );
529
        p_init = MemToBlock( tk->p_data_init, tk->i_data_init, 0 );
530
        if( p_init ) es_out_Send( p_demux->out, tk->p_es, p_init );
531
    }
532
    tk->b_inited = true;
533

534

Denis Charmet's avatar
Denis Charmet committed
535
536
537
538
539
540
541
542
    size_t frame_size = 0;
    size_t block_size = 0;

    if( simpleblock != NULL )
        block_size = simpleblock->GetSize();
    else
        block_size = block->GetSize();
 
543
    for( unsigned int i = 0;
Denis Charmet's avatar
Denis Charmet committed
544
         ( block != NULL && i < block->NumberFrames()) || ( simpleblock != NULL && i < simpleblock->NumberFrames() );
545
         i++ )
546
    {
547
548
549
        block_t *p_block;
        DataBuffer *data;
        if( simpleblock != NULL )
550
        {
551
552
553
            data = &simpleblock->GetBuffer(i);
            // condition when the DTS is correct (keyframe or B frame == NOT P frame)
            f_mandatory = simpleblock->IsDiscardable() || simpleblock->IsKeyframe();
554
        }
555
        else
556
        {
557
            data = &block->GetBuffer(i);
Denis Charmet's avatar
Denis Charmet committed
558
            // condition when the DTS is correct (keyframe or B frame == NOT P frame)
559
        }
Denis Charmet's avatar
Denis Charmet committed
560
561
562
563
        frame_size += data->Size();
        if( !data->Buffer() || data->Size() > SIZE_MAX || frame_size > block_size  )
        {
            msg_Warn( p_demux, "Cannot read frame (too long or no frame)" );
564
            break;
Denis Charmet's avatar
Denis Charmet committed
565
        }
566

567
568
569
        if( tk->i_compression_type == MATROSKA_COMPRESSION_HEADER &&
            tk->p_compression_data != NULL &&
            tk->i_encoding_scope & MATROSKA_ENCODING_SCOPE_ALL_FRAMES )
570
            p_block = MemToBlock( data->Buffer(), data->Size(), tk->p_compression_data->GetSize() );
571
572
        else if( unlikely( tk->fmt.i_codec == VLC_CODEC_WAVPACK ) )
            p_block = packetize_wavpack(tk, data->Buffer(), data->Size());
573
        else
574
            p_block = MemToBlock( data->Buffer(), data->Size(), 0 );
575

576
        if( p_block == NULL )
577
        {
578
            break;
579
580
        }

581
#if defined(HAVE_ZLIB_H)
582
583
        if( tk->i_compression_type == MATROSKA_COMPRESSION_ZLIB &&
            tk->i_encoding_scope & MATROSKA_ENCODING_SCOPE_ALL_FRAMES )
584
        {
585
            p_block = block_zlib_decompress( VLC_OBJECT(p_demux), p_block );
586
587
            if( p_block == NULL )
                break;
588
589
590
        }
        else
#endif
591
592
        if( tk->i_compression_type == MATROSKA_COMPRESSION_HEADER &&
            tk->i_encoding_scope & MATROSKA_ENCODING_SCOPE_ALL_FRAMES )
593
        {
594
            memcpy( p_block->p_buffer, tk->p_compression_data->GetBuffer(), tk->p_compression_data->GetSize() );
595
        }
596
597
598
599
        switch( tk->fmt.i_codec )
        {
        case VLC_CODEC_COOK:
        case VLC_CODEC_ATRAC3:
Denis Charmet's avatar
Denis Charmet committed
600
601
602
603
604
605
606
        {
            handle_real_audio(p_demux, tk, p_block, i_pts);
            block_Release(p_block);
            i_pts = ( tk->i_default_duration )?
                i_pts + ( mtime_t )( tk->i_default_duration / 1000 ):
                VLC_TS_INVALID;
            continue;
607
608
         }
         case VLC_CODEC_OPUS:
609
            mtime_t i_length = i_duration * tk-> f_timecodescale *
610
                    (double) p_segment->i_timescale / 1000.0;
611
612
            if ( i_length < 0 ) i_length = 0;
            p_block->i_nb_samples = i_length * tk->fmt.audio.i_rate
613
                    / CLOCK_FREQ;
614
            break;
Denis Charmet's avatar
Denis Charmet committed
615
616
        }

617
        
618
        if( tk->fmt.i_cat != VIDEO_ES )
619
        {
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
            if ( tk->fmt.i_cat == NAV_ES )
            {
                // TODO handle the start/stop times of this packet
                p_sys->p_ev->SetPci( (const pci_t *)&p_block->p_buffer[1]);
                block_Release( p_block );
                return;
            }
            else if( tk->fmt.i_cat == AUDIO_ES )
            {
                if( tk->i_chans_to_reorder )
                    aout_ChannelReorder( p_block->p_buffer, p_block->i_buffer,
                                         tk->fmt.audio.i_channels,
                                         tk->pi_chan_table, tk->fmt.i_codec );

            }
635
            p_block->i_dts = p_block->i_pts = i_pts;
636
        }
637
638
        else
        {
639
            // correct timestamping when B frames are used
640
            if( tk->b_dts_only )
641
            {
642
                p_block->i_pts = VLC_TS_INVALID;
643
                p_block->i_dts = i_pts;
644
            }
645
646
647
648
649
            else if( tk->b_pts_only )
            {
                p_block->i_pts = i_pts;
                p_block->i_dts = i_pts;
            }
650
            else
651
            {
652
653
654
655
                p_block->i_pts = i_pts;
                if ( f_mandatory )
                    p_block->i_dts = p_block->i_pts;
                else
656
                    p_block->i_dts = min( i_pts, tk->i_last_dts + ( mtime_t )( tk->i_default_duration / 1000 ) );
657
658
            }
        }
659
660
661
        if( p_block->i_dts > VLC_TS_INVALID &&
            ( tk->fmt.i_cat == VIDEO_ES || tk->fmt.i_cat == AUDIO_ES ) )
        {
Denis Charmet's avatar
Denis Charmet committed
662
            tk->i_last_dts = p_block->i_dts;
663
        }
664

665
666
667
#if 0
msg_Dbg( p_demux, "block i_dts: %"PRId64" / i_pts: %"PRId64, p_block->i_dts, p_block->i_pts);
#endif
668
669
670
671
672
673
        if( !tk->b_no_duration )
        {
            p_block->i_length = i_duration * tk-> f_timecodescale *
                (double) p_segment->i_timescale / 1000.0;
        }

674
        /* FIXME remove when VLC_TS_INVALID work is done */
675
676
677
678
        if( i == 0 || p_block->i_dts > VLC_TS_INVALID )
            p_block->i_dts += VLC_TS_0;
        if( !tk->b_dts_only && ( i == 0 || p_block->i_pts > VLC_TS_INVALID ) )
            p_block->i_pts += VLC_TS_0;
679

680
        es_out_Send( p_demux->out, tk->p_es, p_block );
681

682
        /* use time stamp only for first block */
683
684
685
        i_pts = ( tk->i_default_duration )?
                 i_pts + ( mtime_t )( tk->i_default_duration / 1000 ):
                 VLC_TS_INVALID;
686
687
    }
}
688

689
690
691
692
693
694
/*****************************************************************************
 * Demux: reads and demuxes data packets
 *****************************************************************************
 * Returns -1 in case of error, 0 in case of EOF, 1 otherwise
 *****************************************************************************/
static int Demux( demux_t *p_demux)
695
{
696
    demux_sys_t        *p_sys = p_demux->p_sys;
697

698
    vlc_mutex_lock( &p_sys->lock_demuxer );
699

700
    virtual_segment_c  *p_vsegment = p_sys->p_current_segment;
701
    matroska_segment_c *p_segment = p_vsegment->CurrentSegment();
702
703
704
705
706
    if ( p_segment == NULL )
    {
        vlc_mutex_unlock( &p_sys->lock_demuxer );
        return 0;
    }
707
708
    int                i_block_count = 0;
    int                i_return = 0;
709

710
    for( ;; )
711
    {
712
713
714
        if( p_sys->i_pts >= p_sys->i_start_pts  )
            if ( p_vsegment->UpdateCurrentToChapter( *p_demux ) )
            {
715
                i_return = 1;
716
717
                break;
            }
718

Denis Charmet's avatar
Denis Charmet committed
719
720
721
        if ( p_vsegment->CurrentEdition() &&
             p_vsegment->CurrentEdition()->b_ordered &&
             p_vsegment->CurrentChapter() == NULL )
722
            /* nothing left to read in this ordered edition */
Denis Charmet's avatar
Denis Charmet committed
723
            break;
724

725
726
727
        KaxBlock *block;
        KaxSimpleBlock *simpleblock;
        int64_t i_block_duration = 0;
728
729
730
        bool b_key_picture;
        bool b_discardable_picture;
        if( p_segment->BlockGet( block, simpleblock, &b_key_picture, &b_discardable_picture, &i_block_duration ) )
731
        {
732
            if ( p_vsegment->CurrentEdition() && p_vsegment->CurrentEdition()->b_ordered )
733
            {
Denis Charmet's avatar
Denis Charmet committed
734
                const virtual_chapter_c *p_chap = p_vsegment->CurrentChapter();
735
736
737
738
739
                // check if there are more chapters to read
                if ( p_chap != NULL )
                {
                    /* TODO handle successive chapters with the same user_start_time/user_end_time
                    */
Denis Charmet's avatar
Denis Charmet committed
740
                    p_sys->i_pts = p_chap->i_virtual_stop_time;
741
                    p_sys->i_pts++; // trick to avoid staying on segments with no duration and no content
742

743
744
                    i_return = 1;
                }
745

746
747
748
749
750
                break;
            }
            else
            {
                msg_Warn( p_demux, "cannot get block EOF?" );
Denis Charmet's avatar
Denis Charmet committed
751
                break;
752
753
            }
        }
754

755
        if( simpleblock != NULL )
756
            p_sys->i_pts = p_sys->i_chapter_time + ( (mtime_t)simpleblock->GlobalTimecode() / INT64_C(1000) );
757
        else
758
            p_sys->i_pts = p_sys->i_chapter_time + ( (mtime_t)block->GlobalTimecode() / INT64_C(1000) );
759

Denis Charmet's avatar
Denis Charmet committed
760
761
762
763
764
765
766
        mtime_t i_pcr = VLC_TS_INVALID;
        for( size_t i = 0; i < p_segment->tracks.size(); i++)
            if( p_segment->tracks[i]->i_last_dts > VLC_TS_INVALID &&
                ( p_segment->tracks[i]->i_last_dts < i_pcr || i_pcr == VLC_TS_INVALID ))
                i_pcr = p_segment->tracks[i]->i_last_dts;

        if( i_pcr > p_sys->i_pcr + 300000 )
767
768
        {
            es_out_Control( p_demux->out, ES_OUT_SET_PCR, VLC_TS_0 + p_sys->i_pcr );
Denis Charmet's avatar
Denis Charmet committed
769
            p_sys->i_pcr = i_pcr;
770
        }
771

772
        if( p_sys->i_pts >= p_sys->i_start_pts  )
773
        {
Denis Charmet's avatar
Denis Charmet committed
774
            if ( p_vsegment->UpdateCurrentToChapter( *p_demux ) )
775
            {
776
777
                i_return = 1;
                delete block;
778
779
780
                break;
            }
        }
781

Denis Charmet's avatar
Denis Charmet committed
782
783
784
        if ( p_vsegment->CurrentEdition() &&
             p_vsegment->CurrentEdition()->b_ordered &&
             p_vsegment->CurrentChapter() == NULL )
785
        {
786
787
            /* nothing left to read in this ordered edition */
            delete block;
Denis Charmet's avatar
Denis Charmet committed
788
            break;
789
790
        }

791
        BlockDecode( p_demux, block, simpleblock, p_sys->i_pts, i_block_duration, b_key_picture || b_discardable_picture );
792

793
794
        delete block;
        i_block_count++;
795

796
797
        // TODO optimize when there is need to leave or when seeking has been called
        if( i_block_count > 5 )
798
        {
799
800
            i_return = 1;
            break;
801
802
803
        }
    }

804
    vlc_mutex_unlock( &p_sys->lock_demuxer );
805

806
    return i_return;
807
}
808