mkv.cpp 26.4 KB
Newer Older
Steve Lhomme's avatar
Steve Lhomme committed
1
2
3
/*****************************************************************************
 * mkv.cpp : matroska demuxer
 *****************************************************************************
4
 * Copyright (C) 2003-2005, 2008, 2010 the VideoLAN team
Steve Lhomme's avatar
Steve Lhomme committed
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
 * $Id$
 *
 * Authors: Laurent Aimar <fenrir@via.ecp.fr>
 *          Steve Lhomme <steve.lhomme@free.fr>
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (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
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
dionoea's avatar
dionoea committed
22
 * 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
37
#include <vlc_fs.h>

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

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

52
    add_bool( "mkv-use-ordered-chapters", true,
53
54
55
            N_("Ordered chapters"),
            N_("Play ordered chapters as specified in the segment."), true );

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

60
    add_bool( "mkv-preload-local-dir", false,
61
62
63
            N_("Preload Directory"),
            N_("Preload matroska files from the same family in the same directory (not good for broken files)."), true );

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

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

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

75
class demux_sys_t;
76

77
78
static int  Demux  ( demux_t * );
static int  Control( demux_t *, int, va_list );
79
static void Seek   ( demux_t *, mtime_t i_date, double f_percent, chapter_item_c *p_chapter );
80

81
82
83
84
85
86
87
88
89
90
91
92
93
/*****************************************************************************
 * 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;
94

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

98
99
100
    /* 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
101

102
103
104
105
    /* 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
106

107
108
    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
109

110
    if( p_io_stream == NULL )
Steve Lhomme's avatar
Steve Lhomme committed
111
    {
112
113
114
115
        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
116
117
    }

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

126
127
    p_stream->p_io_callback = p_io_callback;
    p_stream->p_estream = p_io_stream;
Steve Lhomme's avatar
Steve Lhomme committed
128

129
130
131
132
    for (size_t i=0; i<p_stream->segments.size(); i++)
    {
        p_stream->segments[i]->Preload();
    }
Steve Lhomme's avatar
Steve Lhomme committed
133

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

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

161
            DIR *p_src_dir = vlc_opendir(s_path.c_str());
162

163
164
165
            if (p_src_dir != NULL)
            {
                char *psz_file;
166
                while ((psz_file = vlc_readdir(p_src_dir)) != NULL)
167
168
169
                {
                    if (strlen(psz_file) > 4)
                    {
170
                        s_filename = s_path + DIR_SEP_CHAR + psz_file;
Steve Lhomme's avatar
Steve Lhomme committed
171

172
#ifdef WIN32
173
                        if (!strcasecmp(s_filename.c_str(), p_demux->psz_file))
174
#else
175
                        if (!s_filename.compare(p_demux->psz_file))
176
177
178
179
180
#endif
                        {
                            free (psz_file);
                            continue; // don't reuse the original opened file
                        }
Steve Lhomme's avatar
Steve Lhomme committed
181

182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
                        if (!s_filename.compare(s_filename.length() - 3, 3, "mkv") ||
                            !s_filename.compare(s_filename.length() - 3, 3, "mka"))
                        {
                            // test wether this file belongs to our family
                            const uint8_t *p_peek;
                            bool          file_ok = false;
                            stream_t      *p_file_stream = stream_UrlNew(
                                                            p_demux,
                                                            s_filename.c_str());
                            /* 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
201

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

204
205
206
207
208
209
210
211
                                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
                                {
212
213
                                    p_stream->p_io_callback = p_file_io;
                                    p_stream->p_estream = p_estream;
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
                                    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() );
                            }
                        }
                    }
                    free (psz_file);
                }
                closedir( p_src_dir );
            }
        }
231

232
233
        p_sys->PreloadFamily( *p_segment );
    }
Steve Lhomme's avatar
Steve Lhomme committed
234

235
    p_sys->PreloadLinked( p_segment );
Steve Lhomme's avatar
Steve Lhomme committed
236

237
238
239
240
241
    if ( !p_sys->PreparePlayback( NULL ) )
    {
        msg_Err( p_demux, "cannot use the segment" );
        goto error;
    }
Steve Lhomme's avatar
Steve Lhomme committed
242

243
    p_sys->InitUi();
244

245
    return VLC_SUCCESS;
Steve Lhomme's avatar
Steve Lhomme committed
246

247
248
249
250
error:
    delete p_sys;
    return VLC_EGENERIC;
}
Steve Lhomme's avatar
Steve Lhomme committed
251
252

/*****************************************************************************
253
 * Close: frees unused data
Steve Lhomme's avatar
Steve Lhomme committed
254
 *****************************************************************************/
255
static void Close( vlc_object_t *p_this )
Steve Lhomme's avatar
Steve Lhomme committed
256
{
257
258
259
260
    demux_t     *p_demux = (demux_t*)p_this;
    demux_sys_t *p_sys   = p_demux->p_sys;

    delete p_sys;
Steve Lhomme's avatar
Steve Lhomme committed
261
262
263
}

/*****************************************************************************
264
 * Control:
Steve Lhomme's avatar
Steve Lhomme committed
265
 *****************************************************************************/
266
static int Control( demux_t *p_demux, int i_query, va_list args )
Steve Lhomme's avatar
Steve Lhomme committed
267
{
268
269
270
271
272
    demux_sys_t        *p_sys = p_demux->p_sys;
    int64_t     *pi64;
    double      *pf, f;
    int         i_skp;
    size_t      i_idx;
Steve Lhomme's avatar
Steve Lhomme committed
273

274
275
276
    vlc_meta_t *p_meta;
    input_attachment_t ***ppp_attach;
    int *pi_int;
Steve Lhomme's avatar
Steve Lhomme committed
277

278
279
280
281
282
    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
283

284
285
            if( p_sys->stored_attachments.size() <= 0 )
                return VLC_EGENERIC;
286

287
288
289
290
291
            *pi_int = p_sys->stored_attachments.size();
            *ppp_attach = (input_attachment_t**)malloc( sizeof(input_attachment_t**) *
                                                        p_sys->stored_attachments.size() );
            if( !(*ppp_attach) )
                return VLC_ENOMEM;
Jean-Baptiste Kempf's avatar
Jean-Baptiste Kempf committed
292
            for( size_t i = 0; i < p_sys->stored_attachments.size(); i++ )
293
294
            {
                attachment_c *a = p_sys->stored_attachments[i];
295
296
                (*ppp_attach)[i] = vlc_input_attachment_New( a->fileName(), a->mimeType(), NULL,
                                                             a->p_data, a->size() );
297
298
            }
            return VLC_SUCCESS;
Steve Lhomme's avatar
Steve Lhomme committed
299

300
301
302
303
        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
304

305
306
307
308
309
310
311
312
        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
313

314
315
316
317
318
        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
319

320
321
322
323
        case DEMUX_SET_POSITION:
            f = (double)va_arg( args, double );
            Seek( p_demux, -1, f, NULL );
            return VLC_SUCCESS;
Steve Lhomme's avatar
Steve Lhomme committed
324

325
326
327
328
        case DEMUX_GET_TIME:
            pi64 = (int64_t*)va_arg( args, int64_t * );
            *pi64 = p_sys->i_pts;
            return VLC_SUCCESS;
329

330
331
332
333
334
        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* );
335

336
337
                *pi_int = p_sys->titles.size();
                *ppp_title = (input_title_t**)malloc( sizeof( input_title_t**) * p_sys->titles.size() );
Steve Lhomme's avatar
Steve Lhomme committed
338

339
340
341
342
343
344
345
                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;
346

347
348
349
350
351
352
353
354
355
        case DEMUX_SET_TITLE:
            /* TODO handle editions as titles */
            i_idx = (int)va_arg( args, int );
            if( i_idx < p_sys->used_segments.size() )
            {
                p_sys->JumpTo( *p_sys->used_segments[i_idx], NULL );
                return VLC_SUCCESS;
            }
            return VLC_EGENERIC;
356

357
358
        case DEMUX_SET_SEEKPOINT:
            i_skp = (int)va_arg( args, int );
359

360
361
362
363
364
365
366
367
368
            // 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);
                p_demux->info.i_seekpoint |= INPUT_UPDATE_SEEKPOINT;
                p_demux->info.i_seekpoint = i_skp;
                return VLC_SUCCESS;
            }
            return VLC_EGENERIC;
369

370
371
372
        case DEMUX_GET_FPS:
            pf = (double *)va_arg( args, double * );
            *pf = 0.0;
373
            if( p_sys->p_current_segment && p_sys->p_current_segment->CurrentSegment() )
374
            {
375
                const matroska_segment_c *p_segment = p_sys->p_current_segment->CurrentSegment();
376
377
378
379
380
381
382
383
384
385
386
                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;
387

388
389
390
        case DEMUX_SET_TIME:
        default:
            return VLC_EGENERIC;
391
    }
392
}
393

394
/* Seek */
395
static void Seek( demux_t *p_demux, mtime_t i_date, double f_percent, chapter_item_c *p_chapter )
396
397
398
{
    demux_sys_t        *p_sys = p_demux->p_sys;
    virtual_segment_c  *p_vsegment = p_sys->p_current_segment;
399
    matroska_segment_c *p_segment = p_vsegment->CurrentSegment();
400
401
    mtime_t            i_time_offset = 0;
    int64_t            i_global_position = -1;
402

403
    int         i_index;
404

405
406
    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
407
    {
408
409
        msg_Warn( p_demux, "cannot seek nowhere !" );
        return;
Steve Lhomme's avatar
Steve Lhomme committed
410
    }
411
    if( f_percent > 1.0 )
Steve Lhomme's avatar
Steve Lhomme committed
412
    {
413
414
        msg_Warn( p_demux, "cannot seek so far !" );
        return;
Steve Lhomme's avatar
Steve Lhomme committed
415
    }
416

417
    /* seek without index or without date */
418
    if( f_percent >= 0 && (var_InheritBool( p_demux, "mkv-seek-percent" ) || !p_segment->b_cues || i_date < 0 ))
419
    {
420
        if( p_sys->f_duration >= 0 && p_segment->b_cues )
421
        {
422
            i_date = int64_t( f_percent * p_sys->f_duration * 1000.0 );
423
424
425
        }
        else
        {
426
            int64_t i_pos = int64_t( f_percent * stream_Size( p_demux->s ) );
427

428
429
430
431
432
433
434
435
436
437
438
439
            msg_Dbg( p_demux, "inaccurate way of seeking for pos:%"PRId64, i_pos );
            for( i_index = 0; i_index < p_segment->i_index; i_index++ )
            {
                if( p_segment->b_cues && p_segment->p_indexes[i_index].i_position < i_pos )
                    break;
                if( !p_segment->b_cues && p_segment->p_indexes[i_index].i_position >= i_pos && p_segment->p_indexes[i_index].i_time > 0 )
                    break;
            }
            if( i_index == p_segment->i_index )
            {
                i_index--;
            }
440

441
            i_date = p_segment->p_indexes[i_index].i_time;
442

443
444
445
446
447
448
449
            if( !p_segment->b_cues && ( p_segment->p_indexes[i_index].i_position < i_pos || p_segment->p_indexes[i_index].i_position - i_pos > 2000000 ))
            {
                msg_Dbg( p_demux, "no cues, seek request to global pos: %"PRId64, i_pos );
                i_global_position = i_pos;
            }
        }
    }
450

451
    p_vsegment->Seek( *p_demux, i_date, i_time_offset, p_chapter, i_global_position );
452
}
453

454
/* Utility function for BlockDecode */
455
static block_t *MemToBlock( uint8_t *p_mem, size_t i_mem, size_t offset)
456
{
457
458
459
460
461
462
    block_t *p_block = block_New( p_demux, i_mem + offset );
    if( likely(p_block != NULL) )
    {
        memcpy( p_block->p_buffer + offset, p_mem, i_mem );
        //p_block->i_rate = p_input->stream.control.i_rate;
    }
463
464
    return p_block;
}
465

466
467
/* Needed by matroska_segment::Seek() and Seek */
void BlockDecode( demux_t *p_demux, KaxBlock *block, KaxSimpleBlock *simpleblock,
468
                         mtime_t i_pts, mtime_t i_duration, bool f_mandatory )
469
{
470
    demux_sys_t        *p_sys = p_demux->p_sys;
471
    matroska_segment_c *p_segment = p_sys->p_current_segment->CurrentSegment();
Steve Lhomme's avatar
Steve Lhomme committed
472

473
    if( !p_segment ) return;
474

475
    size_t          i_track;
476
    if( p_segment->BlockFindTrackIndex( &i_track, block, simpleblock ) )
477
    {
478
479
        msg_Err( p_demux, "invalid track number" );
        return;
480
481
    }

482
    mkv_track_t *tk = p_segment->tracks[i_track];
483

484
    if( tk->fmt.i_cat != NAV_ES && tk->p_es == NULL )
485
    {
486
487
        msg_Err( p_demux, "unknown track number" );
        return;
488
    }
489
    if( i_pts + i_duration < p_sys->i_start_pts && tk->fmt.i_cat == AUDIO_ES )
490
    {
491
        return; /* discard audio packets that shouldn't be rendered */
492
    }
Steve Lhomme's avatar
Steve Lhomme committed
493

494
    if ( tk->fmt.i_cat != NAV_ES )
495
    {
496
        bool b;
497
        es_out_Control( p_demux->out, ES_OUT_GET_ES_STATE, tk->p_es, &b );
498

499
        if( !b )
500
        {
501
502
            tk->b_inited = false;
            return;
503
        }
504
505
    }

506

507
508
    /* First send init data */
    if( !tk->b_inited && tk->i_data_init > 0 )
509
    {
510
        block_t *p_init;
511

512
        msg_Dbg( p_demux, "sending header (%d bytes)", tk->i_data_init );
513
        p_init = MemToBlock( tk->p_data_init, tk->i_data_init, 0 );
514
        if( p_init ) es_out_Send( p_demux->out, tk->p_es, p_init );
515
    }
516
    tk->b_inited = true;
517

518

519
    for( unsigned int i = 0;
520
521
         (block != NULL && i < block->NumberFrames()) || (simpleblock != NULL && i < simpleblock->NumberFrames());
         i++ )
522
    {
523
524
525
        block_t *p_block;
        DataBuffer *data;
        if( simpleblock != NULL )
526
        {
527
528
529
            data = &simpleblock->GetBuffer(i);
            // condition when the DTS is correct (keyframe or B frame == NOT P frame)
            f_mandatory = simpleblock->IsDiscardable() || simpleblock->IsKeyframe();
530
        }
531
        else
532
        {
533
            data = &block->GetBuffer(i);
534
        }
535
536
        if( !data->Buffer() || data->Size() > SIZE_MAX )
            break;
537

538
        if( tk->i_compression_type == MATROSKA_COMPRESSION_HEADER && tk->p_compression_data != NULL )
539
            p_block = MemToBlock( data->Buffer(), data->Size(), tk->p_compression_data->GetSize() );
540
        else
541
            p_block = MemToBlock( data->Buffer(), data->Size(), 0 );
542

543
        if( p_block == NULL )
544
        {
545
            break;
546
547
        }

548
549
#if defined(HAVE_ZLIB_H)
        if( tk->i_compression_type == MATROSKA_COMPRESSION_ZLIB )
550
        {
551
            p_block = block_zlib_decompress( VLC_OBJECT(p_demux), p_block );
552
553
            if( p_block == NULL )
                break;
554
555
556
557
        }
        else
#endif
        if( tk->i_compression_type == MATROSKA_COMPRESSION_HEADER )
558
        {
559
            memcpy( p_block->p_buffer, tk->p_compression_data->GetBuffer(), tk->p_compression_data->GetSize() );
560
        }
561

562
        if ( tk->fmt.i_cat == NAV_ES )
563
        {
564
            // TODO handle the start/stop times of this packet
565
566
            p_sys->p_ev->SetPci( (const pci_t *)&p_block->p_buffer[1]);
            block_Release( p_block );
567
            return;
568
        }
569
570
        // correct timestamping when B frames are used
        if( tk->fmt.i_cat != VIDEO_ES )
571
        {
572
            p_block->i_dts = p_block->i_pts = i_pts;
573
        }
574
575
        else
        {
576
            if( tk->b_dts_only )
577
            {
578
                p_block->i_pts = VLC_TS_INVALID;
579
                p_block->i_dts = i_pts;
580
            }
581
582
583
584
585
            else if( tk->b_pts_only )
            {
                p_block->i_pts = i_pts;
                p_block->i_dts = i_pts;
            }
586
            else
587
            {
588
589
590
591
592
                p_block->i_pts = i_pts;
                if ( f_mandatory )
                    p_block->i_dts = p_block->i_pts;
                else
                    p_block->i_dts = min( i_pts, tk->i_last_dts + (mtime_t)(tk->i_default_duration >> 10));
593
594
            }
        }
595
        tk->i_last_dts = p_block->i_dts;
596

597
598
599
600
#if 0
msg_Dbg( p_demux, "block i_dts: %"PRId64" / i_pts: %"PRId64, p_block->i_dts, p_block->i_pts);
#endif
        if( strcmp( tk->psz_codec, "S_VOBSUB" ) )
601
        {
602
            p_block->i_length = i_duration * 1000;
603
        }
604

605
        /* FIXME remove when VLC_TS_INVALID work is done */
606
607
608
609
        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;
610

611
        es_out_Send( p_demux->out, tk->p_es, p_block );
612

613
        /* use time stamp only for first block */
614
        i_pts = VLC_TS_INVALID;
615
616
    }
}
617

618
619
620
621
622
623
/*****************************************************************************
 * 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)
624
{
625
    demux_sys_t        *p_sys = p_demux->p_sys;
626

627
    vlc_mutex_lock( &p_sys->lock_demuxer );
628

629
    virtual_segment_c  *p_vsegment = p_sys->p_current_segment;
630
    matroska_segment_c *p_segment = p_vsegment->CurrentSegment();
631
632
633
    if ( p_segment == NULL ) return 0;
    int                i_block_count = 0;
    int                i_return = 0;
634

635
    for( ;; )
636
    {
637
638
639
640
641
642
643
644
645
        if ( p_sys->demuxer.b_die )
            break;

        if( p_sys->i_pts >= p_sys->i_start_pts  )
            if ( p_vsegment->UpdateCurrentToChapter( *p_demux ) )
            {
                i_return = 1;
                break;
            }
646
647

        if ( p_vsegment->CurrentEdition() && p_vsegment->CurrentEdition()->b_ordered && p_vsegment->CurrentChapter() == NULL )
648
        {
649
650
651
652
            /* nothing left to read in this ordered edition */
            if ( !p_vsegment->SelectNext() )
                break;
            p_segment->UnSelect( );
653

654
655
656
            es_out_Control( p_demux->out, ES_OUT_RESET_PCR );

            /* switch to the next segment */
657
            p_segment = p_vsegment->CurrentSegment();
658
659
660
661
662
663
            if ( !p_segment->Select( 0 ) )
            {
                msg_Err( p_demux, "Failed to select new segment" );
                break;
            }
            continue;
664
665
        }

666
667
668
        KaxBlock *block;
        KaxSimpleBlock *simpleblock;
        int64_t i_block_duration = 0;
669
670
671
        bool b_key_picture;
        bool b_discardable_picture;
        if( p_segment->BlockGet( block, simpleblock, &b_key_picture, &b_discardable_picture, &i_block_duration ) )
672
        {
673
            if ( p_vsegment->CurrentEdition() && p_vsegment->CurrentEdition()->b_ordered )
674
675
676
677
678
679
680
681
682
683
684
            {
                const chapter_item_c *p_chap = p_vsegment->CurrentChapter();
                // 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
                    if ( p_chap->i_user_start_time == p_chap->i_user_start_time )
                        p_vsegment->SelectNext();
                    */
                    p_sys->i_pts = p_chap->i_user_end_time;
                    p_sys->i_pts++; // trick to avoid staying on segments with no duration and no content
685

686
687
                    i_return = 1;
                }
688

689
690
691
692
693
694
                break;
            }
            else
            {
                msg_Warn( p_demux, "cannot get block EOF?" );
                p_segment->UnSelect( );
695

696
                es_out_Control( p_demux->out, ES_OUT_RESET_PCR );
697

698
699
700
701
                /* switch to the next segment */
                if ( !p_vsegment->SelectNext() )
                    // no more segments in this stream
                    break;
702
                p_segment = p_vsegment->CurrentSegment();
703
704
705
706
707
                if ( !p_segment->Select( 0 ) )
                {
                    msg_Err( p_demux, "Failed to select new segment" );
                    break;
                }
708

709
710
711
                continue;
            }
        }
712

713
714
715
716
        if( simpleblock != NULL )
            p_sys->i_pts = (p_sys->i_chapter_time + simpleblock->GlobalTimecode()) / (mtime_t) 1000;
        else
            p_sys->i_pts = (p_sys->i_chapter_time + block->GlobalTimecode()) / (mtime_t) 1000;
717

718
719
        /* */
        es_out_Control( p_demux->out, ES_OUT_SET_PCR, VLC_TS_0 + p_sys->i_pts );
720

721
        if( p_sys->i_pts >= p_sys->i_start_pts  )
722
        {
723
            if ( p_vsegment->UpdateCurrentToChapter( *p_demux ) )
724
            {
725
726
                i_return = 1;
                delete block;
727
728
729
                break;
            }
        }
730
731

        if ( p_vsegment->CurrentEdition() && p_vsegment->CurrentEdition()->b_ordered && p_vsegment->CurrentChapter() == NULL )
732
        {
733
734
735
736
737
738
739
            /* nothing left to read in this ordered edition */
            if ( !p_vsegment->SelectNext() )
            {
                delete block;
                break;
            }
            p_segment->UnSelect( );
740

741
742
743
            es_out_Control( p_demux->out, ES_OUT_RESET_PCR );

            /* switch to the next segment */
744
            p_segment = p_vsegment->CurrentSegment();
745
            if ( !p_segment->Select( 0 ) )
746
            {
747
748
                msg_Err( p_demux, "Failed to select new segment" );
                delete block;
749
750
                break;
            }
751
752
            delete block;
            continue;
753
754
        }

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

757
758
        delete block;
        i_block_count++;
759

760
761
        // TODO optimize when there is need to leave or when seeking has been called
        if( i_block_count > 5 )
762
        {
763
764
            i_return = 1;
            break;
765
766
767
        }
    }

768
    vlc_mutex_unlock( &p_sys->lock_demuxer );
769

770
    return i_return;
771
}
772