Coverage Report

Created: 2026-09-28 07:27

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/vlc/modules/demux/mkv/mkv.cpp
Line
Count
Source
1
/*****************************************************************************
2
 * mkv.cpp : matroska demuxer
3
 *****************************************************************************
4
 * Copyright (C) 2003-2005, 2008, 2010 VLC authors and VideoLAN
5
 *
6
 * Authors: Laurent Aimar <fenrir@via.ecp.fr>
7
 *          Steve Lhomme <steve.lhomme@free.fr>
8
 *
9
 * This program is free software; you can redistribute it and/or modify it
10
 * under the terms of the GNU Lesser General Public License as published by
11
 * the Free Software Foundation; either version 2.1 of the License, or
12
 * (at your option) any later version.
13
 *
14
 * This program is distributed in the hope that it will be useful,
15
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
16
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
17
 * GNU Lesser General Public License for more details.
18
 *
19
 * You should have received a copy of the GNU Lesser General Public License
20
 * along with this program; if not, write to the Free Software Foundation,
21
 * Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA.
22
 *****************************************************************************/
23
24
#include "mkv.hpp"
25
#include "util.hpp"
26
27
#include "matroska_segment.hpp"
28
#include "demux.hpp"
29
#include "virtual_segment.hpp"
30
#include "chapters.hpp"
31
#include "Ebml_parser.hpp"
32
33
#include <new>
34
#include <limits>
35
36
extern "C" {
37
    #include "../av1_unpack.h"
38
}
39
40
#include <vlc_fs.h>
41
#include <vlc_url.h>
42
#include <vlc_ancillary.h>
43
44
/*****************************************************************************
45
 * Module descriptor
46
 *****************************************************************************/
47
namespace mkv {
48
static int  Open ( vlc_object_t * );
49
static int  OpenTrusted ( vlc_object_t * );
50
static void Close( vlc_object_t * );
51
} // namespace
52
53
using namespace mkv;
54
174
vlc_module_begin ()
55
87
    set_shortname( "Matroska" )
56
87
    set_description( N_("Matroska stream demuxer" ) )
57
87
    set_capability( "demux", 50 )
58
174
    set_callbacks( Open, Close )
59
87
    set_subcategory( SUBCAT_INPUT_DEMUX )
60
61
87
    add_bool( "mkv-use-ordered-chapters", true,
62
87
            N_("Respect ordered chapters"),
63
87
            N_("Play chapters in the order specified in the segment.") )
64
65
87
    add_bool( "mkv-use-chapter-codec", true,
66
87
            N_("Chapter codecs"),
67
87
            N_("Use chapter codecs found in the segment.") )
68
69
87
    add_bool( "mkv-preload-local-dir", true,
70
87
            N_("Preload MKV files in the same directory"),
71
87
            N_("Preload matroska files in the same directory to find linked segments (not good for broken files).") )
72
73
87
    add_bool( "mkv-seek-percent", false,
74
87
            N_("Seek based on percent not time"),
75
87
            nullptr )
76
77
87
    add_bool( "mkv-use-dummy", false,
78
87
            N_("Dummy Elements"),
79
87
            N_("Read and discard unknown EBML elements (not good for broken files).") )
80
81
87
    add_bool( "mkv-preload-clusters", false,
82
87
            N_("Preload clusters"),
83
87
            N_("Find all cluster positions by jumping cluster-to-cluster before playback") )
84
85
87
    add_shortcut( "mka", "mkv" )
86
87
    add_file_extension("mka")
87
87
    add_file_extension("mks")
88
87
    add_file_extension("mkv")
89
90
87
    add_submodule()
91
174
        set_callbacks( OpenTrusted, Close )
92
87
        set_capability( "demux", 0 )
93
87
        add_shortcut( "mka_trusted", "mkv_trusted" )
94
87
vlc_module_end ()
95
96
namespace mkv {
97
98
struct demux_sys_t;
99
100
static int  Demux  ( demux_t * );
101
static int  Control( demux_t *, int, va_list );
102
static int  Seek   ( demux_t *, vlc_tick_t i_mk_date, double f_percent, bool b_precise = true );
103
104
/*****************************************************************************
105
 * Open: initializes matroska demux structures
106
 *****************************************************************************/
107
static int OpenInternal( demux_t *p_demux, bool trust_cues )
108
2.06k
{
109
2.06k
    demux_sys_t        *p_sys;
110
2.06k
    matroska_stream_c  *p_stream;
111
2.06k
    matroska_segment_c *p_segment;
112
2.06k
    const uint8_t      *p_peek;
113
2.06k
    std::string         s_path, s_filename;
114
2.06k
    bool                b_need_preload = false;
115
116
    /* peek the beginning */
117
2.06k
    if( vlc_stream_Peek( p_demux->s, &p_peek, 4 ) < 4 ) return VLC_EGENERIC;
118
119
    /* is a valid file */
120
2.06k
    if( p_peek[0] != 0x1a || p_peek[1] != 0x45 ||
121
2.04k
        p_peek[2] != 0xdf || p_peek[3] != 0xa3 ) return VLC_EGENERIC;
122
123
    /* Set the demux function */
124
2.04k
    p_demux->pf_demux   = Demux;
125
2.04k
    p_demux->pf_control = Control;
126
2.04k
    p_demux->p_sys      = p_sys = new demux_sys_t( *p_demux, trust_cues );
127
128
2.04k
    vlc_stream_Control( p_demux->s, STREAM_CAN_SEEK, &p_sys->b_seekable );
129
2.04k
    if ( !p_sys->b_seekable || vlc_stream_Control(
130
2.04k
          p_demux->s, STREAM_CAN_FASTSEEK, &p_sys->b_fastseekable ) )
131
0
        p_sys->b_fastseekable = false;
132
133
2.04k
    es_out_Control( p_demux->out, ES_OUT_SET_ES_CAT_POLICY, VIDEO_ES,
134
2.04k
                    ES_OUT_ES_POLICY_EXCLUSIVE );
135
136
2.04k
    p_stream = new matroska_stream_c( p_demux->s, false );
137
2.04k
    if ( unlikely(p_stream == NULL) )
138
0
    {
139
0
        msg_Err( p_demux, "failed to create matroska_stream_c" );
140
0
        delete p_sys;
141
0
        return VLC_ENOMEM;
142
0
    }
143
2.04k
    p_sys->streams.push_back( p_stream );
144
145
2.04k
    if( !p_sys->AnalyseAllSegmentsFound( p_demux, p_stream ) )
146
0
    {
147
0
        msg_Err( p_demux, "cannot find KaxSegment or missing mandatory KaxInfo" );
148
0
        goto error;
149
0
    }
150
151
4.09k
    for (size_t i=0; i<p_stream->segments.size(); i++)
152
2.04k
    {
153
2.04k
        p_stream->segments[i]->Preload();
154
2.04k
        b_need_preload |= p_stream->segments[i]->b_ref_external_segments;
155
2.04k
        if ( p_stream->segments[i]->translations.size() &&
156
0
             p_stream->segments[i]->translations[0]->codec_id == MATROSKA_CHAPTER_CODEC_DVD &&
157
0
             p_stream->segments[i]->families.size() )
158
0
            b_need_preload = true;
159
2.04k
    }
160
161
2.04k
    p_segment = p_stream->segments[0];
162
2.04k
    if( p_segment->cluster == NULL && p_segment->stored_editions.size() == 0 )
163
29
    {
164
29
        msg_Err( p_demux, "cannot find any cluster or chapter, damaged file ?" );
165
29
        goto error;
166
29
    }
167
168
2.02k
    if (b_need_preload && var_InheritBool( p_demux, "mkv-preload-local-dir" ))
169
0
    {
170
0
        msg_Dbg( p_demux, "Preloading local dir" );
171
        /* get the files from the same dir from the same family (based on p_demux->psz_path) */
172
0
        if ( p_demux->psz_filepath && !strncasecmp( p_demux->psz_url, "file:", 5 ) )
173
0
        {
174
            // assume it's a regular file
175
            // get the directory path
176
0
            s_path = p_demux->psz_filepath;
177
0
            if (s_path.at(s_path.length() - 1) == DIR_SEP_CHAR)
178
0
            {
179
0
                s_path = s_path.substr(0,s_path.length()-1);
180
0
            }
181
0
            else
182
0
            {
183
0
                if (s_path.find_last_of(DIR_SEP_CHAR) > 0)
184
0
                {
185
0
                    s_path = s_path.substr(0,s_path.find_last_of(DIR_SEP_CHAR));
186
0
                }
187
0
            }
188
189
0
            vlc_DIR *p_src_dir = vlc_opendir(s_path.c_str());
190
191
0
            if (p_src_dir != NULL)
192
0
            {
193
0
                const char *psz_file;
194
0
                while ((psz_file = vlc_readdir(p_src_dir)) != NULL)
195
0
                {
196
0
                    if (strnlen(psz_file, 4+1) > 4)
197
0
                    {
198
0
                        s_filename = s_path + DIR_SEP_CHAR + psz_file;
199
200
#if defined(_WIN32) || defined(__OS2__)
201
                        if (!strcasecmp(s_filename.c_str(), p_demux->psz_filepath))
202
#else
203
0
                        if (!s_filename.compare(p_demux->psz_filepath))
204
0
#endif
205
0
                        {
206
0
                            continue; // don't reuse the original opened file
207
0
                        }
208
209
0
                        if (!strcasecmp(s_filename.c_str() + s_filename.length() - 4, ".mkv") ||
210
0
                            !strcasecmp(s_filename.c_str() + s_filename.length() - 4, ".mka"))
211
0
                        {
212
                            // test whether this file belongs to our family
213
0
                            bool          file_ok = false;
214
0
                            char          *psz_url = vlc_path2uri( s_filename.c_str(), "file" );
215
0
                            stream_t      *p_file_stream = vlc_stream_NewURL(
216
0
                                                            p_demux,
217
0
                                                            psz_url );
218
                            /* peek the beginning */
219
0
                            if( p_file_stream &&
220
0
                                vlc_stream_Peek( p_file_stream, &p_peek, 4 ) >= 4
221
0
                                && p_peek[0] == 0x1a && p_peek[1] == 0x45 &&
222
0
                                p_peek[2] == 0xdf && p_peek[3] == 0xa3 ) file_ok = true;
223
224
0
                            if ( file_ok )
225
0
                            {
226
0
                                matroska_stream_c *p_preload_stream = new matroska_stream_c( p_file_stream, true );
227
228
0
                                if ( !p_sys->AnalyseAllSegmentsFound( p_demux, p_preload_stream ) )
229
0
                                {
230
0
                                    msg_Dbg( p_demux, "the file '%s' will not be used", s_filename.c_str() );
231
0
                                    delete p_preload_stream;
232
0
                                }
233
0
                                else
234
0
                                {
235
0
                                    p_sys->streams.push_back( p_preload_stream );
236
0
                                }
237
0
                            }
238
0
                            else
239
0
                            {
240
0
                                if( p_file_stream ) {
241
0
                                    vlc_stream_Delete( p_file_stream );
242
0
                                }
243
0
                                msg_Dbg( p_demux, "the file '%s' cannot be opened", s_filename.c_str() );
244
0
                            }
245
0
                            free( psz_url );
246
0
                        }
247
0
                    }
248
0
                }
249
0
                vlc_closedir( p_src_dir );
250
0
            }
251
0
        }
252
253
0
        p_sys->PreloadFamily( *p_segment );
254
0
    }
255
2.02k
    else if (b_need_preload)
256
0
        msg_Warn( p_demux, "This file references other files, you may want to enable the preload of local directory");
257
258
2.02k
    if ( !p_sys->PreloadLinked() ||
259
2.01k
         !p_sys->PreparePlayback( *p_sys->GetCurrentVSegment() ) )
260
10
    {
261
10
        msg_Err( p_demux, "cannot use the segment" );
262
10
        goto error;
263
10
    }
264
    /* Seek to the beginning */
265
2.01k
    p_sys->GetCurrentVSegment()->Seek( *p_demux, 0, p_sys->GetCurrentVSegment()->CurrentChapter() );
266
267
2.01k
    if (!p_sys->FreeUnused())
268
0
    {
269
0
        msg_Err( p_demux, "no usable segment" );
270
0
        goto error;
271
0
    }
272
273
2.01k
    return VLC_SUCCESS;
274
275
39
error:
276
39
    delete p_sys;
277
39
    return VLC_EGENERIC;
278
2.01k
}
279
280
static int Open( vlc_object_t *p_this )
281
2.05k
{
282
2.05k
    demux_t *p_demux = (demux_t*)p_this;
283
2.05k
    return OpenInternal( p_demux, false );
284
2.05k
}
285
286
static int OpenTrusted( vlc_object_t *p_this )
287
19
{
288
19
    demux_t *p_demux = (demux_t*)p_this;
289
19
    return OpenInternal( p_demux, true );
290
19
}
291
292
/*****************************************************************************
293
 * Close: frees unused data
294
 *****************************************************************************/
295
static void Close( vlc_object_t *p_this )
296
2.01k
{
297
2.01k
    demux_t     *p_demux = reinterpret_cast<demux_t*>( p_this );
298
2.01k
    demux_sys_t *p_sys = (demux_sys_t *)p_demux->p_sys;
299
2.01k
    virtual_segment_c *p_vsegment = p_sys->GetCurrentVSegment();
300
2.01k
    if( p_vsegment )
301
2.01k
    {
302
2.01k
        matroska_segment_c *p_segment = p_vsegment->CurrentSegment();
303
2.01k
        if( p_segment )
304
1.97k
            p_segment->ESDestroy();
305
2.01k
    }
306
307
2.01k
    delete p_sys;
308
2.01k
}
309
310
/*****************************************************************************
311
 * Control:
312
 *****************************************************************************/
313
static int Control( demux_t *p_demux, int i_query, va_list args )
314
0
{
315
0
    demux_sys_t *p_sys = (demux_sys_t *)p_demux->p_sys;
316
0
    vlc_tick_t  i64;
317
0
    double      *pf, f;
318
0
    int         i_skp;
319
0
    size_t      i_idx;
320
0
    bool            b;
321
322
0
    vlc_meta_t *p_meta;
323
0
    input_attachment_t ***ppp_attach;
324
0
    int *pi_int;
325
326
0
    switch( i_query )
327
0
    {
328
0
        case DEMUX_CAN_SEEK:
329
0
            return vlc_stream_vaControl( p_demux->s, i_query, args );
330
331
0
        case DEMUX_GET_ATTACHMENTS:
332
0
            ppp_attach = va_arg( args, input_attachment_t*** );
333
0
            pi_int = va_arg( args, int * );
334
335
0
            if( p_sys->stored_attachments.size() <= 0 )
336
0
                return VLC_EGENERIC;
337
338
0
            *pi_int = p_sys->stored_attachments.size();
339
0
            *ppp_attach = static_cast<input_attachment_t**>( vlc_alloc( p_sys->stored_attachments.size(),
340
0
                                                        sizeof(input_attachment_t*) ) );
341
0
            if( !(*ppp_attach) )
342
0
                return VLC_ENOMEM;
343
0
            for( size_t i = 0; i < p_sys->stored_attachments.size(); i++ )
344
0
            {
345
0
                (*ppp_attach)[i] = vlc_input_attachment_Hold( p_sys->stored_attachments[i].get() );
346
0
            }
347
0
            return VLC_SUCCESS;
348
349
0
        case DEMUX_GET_META:
350
0
            p_meta = va_arg( args, vlc_meta_t* );
351
0
            vlc_meta_Merge( p_meta, p_sys->meta );
352
0
            return VLC_SUCCESS;
353
354
0
        case DEMUX_GET_LENGTH:
355
0
            if( p_sys->i_duration > 0 )
356
0
                *va_arg( args, vlc_tick_t * ) = p_sys->i_duration;
357
0
            else
358
0
                *va_arg( args, vlc_tick_t * ) = VLC_TICK_INVALID;
359
0
            return VLC_SUCCESS;
360
361
0
        case DEMUX_GET_POSITION:
362
0
            pf = va_arg( args, double * );
363
0
            if ( p_sys->i_duration > 0 )
364
0
                *pf = static_cast<double> (p_sys->i_pcr >= (p_sys->i_start_pts + p_sys->i_mk_chapter_time) ?
365
0
                                               p_sys->i_pcr :
366
0
                                               (p_sys->i_start_pts + p_sys->i_mk_chapter_time) ) / p_sys->i_duration;
367
0
            return VLC_SUCCESS;
368
369
0
        case DEMUX_SET_POSITION:
370
0
            if( p_sys->i_duration > 0)
371
0
            {
372
0
                f = va_arg( args, double );
373
0
                b = va_arg( args, int ); /* precise? */
374
0
                return Seek( p_demux, -1, f, b );
375
0
            }
376
0
            return VLC_EGENERIC;
377
378
0
        case DEMUX_GET_TIME:
379
0
            *va_arg( args, vlc_tick_t * ) = p_sys->i_pcr;
380
0
            return VLC_SUCCESS;
381
382
0
        case DEMUX_GET_TITLE_INFO:
383
0
            if( p_sys->titles.size() > 1 || ( p_sys->titles.size() == 1 && p_sys->titles[0]->i_seekpoint > 0 ) )
384
0
            {
385
0
                input_title_t ***ppp_title = va_arg( args, input_title_t*** );
386
0
                pi_int = va_arg( args, int* );
387
388
0
                *pi_int = p_sys->titles.size();
389
0
                *ppp_title = static_cast<input_title_t**>( vlc_alloc( p_sys->titles.size(), sizeof( input_title_t* ) ) );
390
391
0
                for( size_t i = 0; i < p_sys->titles.size(); i++ )
392
0
                    (*ppp_title)[i] = vlc_input_title_Duplicate( p_sys->titles[i] );
393
0
                return VLC_SUCCESS;
394
0
            }
395
0
            return VLC_EGENERIC;
396
397
0
        case DEMUX_SET_TITLE:
398
            /* handle editions as titles */
399
0
            i_idx = va_arg( args, int );
400
0
            if(i_idx <  p_sys->titles.size() && p_sys->titles[i_idx]->i_seekpoint)
401
0
            {
402
0
                const int i_edition = p_sys->GetCurrentVSegment()->i_current_edition;
403
0
                const int i_title = p_sys->i_current_title;
404
0
                p_sys->GetCurrentVSegment()->i_current_edition = i_idx;
405
0
                p_sys->i_current_title = i_idx;
406
0
                if( VLC_SUCCESS ==
407
0
                    Seek( p_demux, p_sys->titles[i_idx]->seekpoint[0]->i_time_offset, -1 ) )
408
0
                {
409
0
                    p_sys->i_updates |= INPUT_UPDATE_SEEKPOINT|INPUT_UPDATE_TITLE;
410
0
                    p_sys->i_current_seekpoint = 0;
411
0
                    p_sys->i_duration = p_sys->titles[i_idx]->i_length;
412
0
                    return VLC_SUCCESS;
413
0
                }
414
0
                else
415
0
                {
416
0
                    p_sys->GetCurrentVSegment()->i_current_edition = i_edition;
417
0
                    p_sys->i_current_title = i_title;
418
0
                }
419
0
            }
420
0
            return VLC_EGENERIC;
421
422
0
        case DEMUX_SET_SEEKPOINT:
423
0
            i_skp = va_arg( args, int );
424
425
            // TODO change the way it works with the << & >> buttons on the UI (+1/-1 instead of a number)
426
0
            if( p_sys->titles.size() && i_skp < p_sys->titles[p_sys->i_current_title]->i_seekpoint)
427
0
            {
428
0
                int i_ret = Seek( p_demux, p_sys->titles[p_sys->i_current_title]->seekpoint[i_skp]->i_time_offset, -1 );
429
0
                if( i_ret == VLC_SUCCESS )
430
0
                {
431
0
                    p_sys->i_updates |= INPUT_UPDATE_SEEKPOINT;
432
0
                    p_sys->i_current_seekpoint = i_skp;
433
0
                }
434
0
                return i_ret;
435
0
            }
436
0
            return VLC_EGENERIC;
437
438
0
        case DEMUX_TEST_AND_CLEAR_FLAGS:
439
0
        {
440
0
            unsigned *restrict flags = va_arg( args, unsigned * );
441
0
            *flags &= p_sys->i_updates;
442
0
            p_sys->i_updates &= ~*flags;
443
0
            return VLC_SUCCESS;
444
0
        }
445
446
0
        case DEMUX_GET_TITLE:
447
0
            *va_arg( args, int * ) = p_sys->i_current_title;
448
0
            return VLC_SUCCESS;
449
450
0
        case DEMUX_GET_SEEKPOINT:
451
0
            *va_arg( args, int * ) = p_sys->i_current_seekpoint;
452
0
            return VLC_SUCCESS;
453
454
0
        case DEMUX_GET_FPS:
455
0
            pf = va_arg( args, double * );
456
0
            *pf = 0.0;
457
0
            if( p_sys->GetCurrentVSegment() && p_sys->GetCurrentVSegment()->CurrentSegment() )
458
0
            {
459
0
                const matroska_segment_c *p_segment = p_sys->GetCurrentVSegment()->CurrentSegment();
460
0
                for( const auto & it : p_segment->tracks )
461
0
                {
462
0
                    const auto &track = it.second;
463
464
0
                    if( track->fmt.i_cat == VIDEO_ES && track->fmt.video.i_frame_rate_base > 0 )
465
0
                    {
466
0
                        *pf = (double)track->fmt.video.i_frame_rate / track->fmt.video.i_frame_rate_base;
467
0
                        break;
468
0
                    }
469
0
                }
470
0
            }
471
0
            return VLC_SUCCESS;
472
473
0
        case DEMUX_SET_TIME:
474
0
            i64 = va_arg( args, vlc_tick_t );
475
0
            b = va_arg( args, int ); /* precise? */
476
0
            msg_Dbg(p_demux,"SET_TIME to %" PRId64, i64 );
477
0
            return Seek( p_demux, i64, -1, b );
478
479
0
        case DEMUX_NAV_ACTIVATE:
480
0
        case DEMUX_NAV_UP:
481
0
        case DEMUX_NAV_DOWN:
482
0
        case DEMUX_NAV_LEFT:
483
0
        case DEMUX_NAV_RIGHT:
484
0
        case DEMUX_NAV_POPUP:
485
0
        case DEMUX_NAV_MENU:
486
0
            return p_sys->ev.SendEventNav( static_cast<demux_query_e>(i_query) );
487
488
0
        case DEMUX_CAN_PAUSE:
489
0
        case DEMUX_SET_PAUSE_STATE:
490
0
        case DEMUX_CAN_CONTROL_PACE:
491
0
        case DEMUX_GET_PTS_DELAY:
492
0
            return demux_vaControlHelper( p_demux->s, 0, -1, 0, 1, i_query, args );
493
494
0
        default:
495
0
            return VLC_EGENERIC;
496
0
    }
497
0
}
498
499
/* Seek */
500
static int Seek( demux_t *p_demux, vlc_tick_t i_mk_date, double f_percent, bool b_precise )
501
0
{
502
0
    demux_sys_t *p_sys = (demux_sys_t *)p_demux->p_sys;
503
0
    virtual_segment_c  *p_vsegment = p_sys->GetCurrentVSegment();
504
505
0
    if( f_percent < 0 ) msg_Dbg( p_demux, "seek request to i_pos = %" PRId64, i_mk_date );
506
0
    else                msg_Dbg( p_demux, "seek request to %.2f%%", f_percent * 100 );
507
508
0
    if( i_mk_date < 0 && f_percent < 0 )
509
0
    {
510
0
        msg_Warn( p_demux, "cannot seek nowhere!" );
511
0
        return VLC_EGENERIC;
512
0
    }
513
0
    if( f_percent > 1.0 )
514
0
    {
515
0
        msg_Warn( p_demux, "cannot seek so far!" );
516
0
        return VLC_EGENERIC;
517
0
    }
518
0
    if( p_sys->i_duration < 0 )
519
0
    {
520
0
        msg_Warn( p_demux, "cannot seek without duration!");
521
0
        return VLC_EGENERIC;
522
0
    }
523
524
    /* seek without index or without date */
525
0
    if( f_percent >= 0 && (var_InheritBool( p_demux, "mkv-seek-percent" ) || i_mk_date < 0 ))
526
0
    {
527
0
        i_mk_date = vlc_tick_t( f_percent * p_sys->i_duration );
528
0
    }
529
0
    return p_vsegment->Seek( *p_demux, i_mk_date, nullptr, b_precise ) ? VLC_SUCCESS : VLC_EGENERIC;
530
0
}
531
532
static void ReleaseVpxAlpha(void *opaque)
533
0
{
534
0
    auto alpha = static_cast<vlc_vpx_alpha_t*>(opaque);
535
0
    free(alpha->data);
536
0
    delete alpha;
537
0
}
538
539
/* Needed by matroska_segment::Seek() and Seek */
540
static void BlockDecode( demux_t *p_demux, KaxBlock *block, KaxSimpleBlock *simpleblock,
541
                  const KaxBlockAdditions *additions,
542
                  vlc_tick_t i_pts, uint64_t i_duration, bool b_key_picture,
543
                  bool b_discardable_picture )
544
62.0k
{
545
62.0k
    demux_sys_t *p_sys = (demux_sys_t *)p_demux->p_sys;
546
62.0k
    matroska_segment_c *p_segment = p_sys->GetCurrentVSegment()->CurrentSegment();
547
548
62.0k
    KaxInternalBlock& internal_block = simpleblock
549
62.0k
        ? static_cast<KaxInternalBlock&>( *simpleblock )
550
62.0k
        : static_cast<KaxInternalBlock&>( *block );
551
552
62.0k
    if( !p_segment ) return;
553
554
62.0k
    mkv_track_t *p_track = p_segment->FindTrackByBlock( block, simpleblock );
555
62.0k
    if( p_track == NULL )
556
0
    {
557
0
        msg_Err( p_demux, "invalid track number" );
558
0
        return;
559
0
    }
560
561
62.0k
    mkv_track_t &track = *p_track;
562
563
62.0k
    if( track.fmt.i_cat != DATA_ES && track.p_es == NULL )
564
20
    {
565
20
        msg_Err( p_demux, "unknown track number %u (%4.4s)",
566
20
                 track.i_number, (const char *) &track.fmt.i_codec );
567
20
        return;
568
20
    }
569
570
62.0k
    if (i_pts != VLC_TICK_INVALID)
571
62.0k
        i_pts += p_segment->pcr_shift - track.i_codec_delay;
572
573
62.0k
    if ( track.fmt.i_cat != DATA_ES )
574
62.0k
    {
575
62.0k
        bool b;
576
62.0k
        es_out_Control( p_demux->out, ES_OUT_GET_ES_STATE, track.p_es, &b );
577
578
62.0k
        if( !b )
579
0
        {
580
0
            if( track.fmt.i_cat == VIDEO_ES || track.fmt.i_cat == AUDIO_ES )
581
0
                track.i_last_dts = VLC_TICK_INVALID;
582
0
            return;
583
0
        }
584
62.0k
    }
585
586
62.0k
    size_t frame_size = 0;
587
62.0k
    size_t block_size = internal_block.GetSize();
588
62.0k
    const unsigned i_number_frames = internal_block.NumberFrames();
589
590
605k
    for( unsigned int i_frame = 0; i_frame < i_number_frames; i_frame++ )
591
543k
    {
592
543k
        block_t *p_block;
593
543k
        DataBuffer *data = &internal_block.GetBuffer(i_frame);
594
595
543k
        frame_size += data->Size();
596
543k
        if( !data->Buffer() || data->Size() > frame_size || frame_size > block_size  )
597
0
        {
598
0
            msg_Warn( p_demux, "Cannot read frame (too long or no frame)" );
599
0
            break;
600
0
        }
601
543k
        size_t extra_data = track.fmt.i_codec == VLC_CODEC_PRORES ? 8 : 0;
602
603
543k
        if( track.i_compression_type == MATROSKA_COMPRESSION_HEADER &&
604
165k
            track.i_encoding_scope & MATROSKA_ENCODING_SCOPE_ALL_FRAMES )
605
165k
            p_block = MemToBlock( data->Buffer(), data->Size(), track.p_compression_data->GetSize() + extra_data );
606
377k
        else if( unlikely( track.fmt.i_codec == VLC_CODEC_WAVPACK ) )
607
1.48k
            p_block = packetize_wavpack( track, data->Buffer(), data->Size() );
608
376k
        else
609
376k
            p_block = MemToBlock( data->Buffer(), data->Size(), extra_data );
610
611
543k
        if( p_block == NULL )
612
0
        {
613
0
            break;
614
0
        }
615
616
543k
#ifdef HAVE_ZLIB
617
543k
        if( track.i_compression_type == MATROSKA_COMPRESSION_ZLIB &&
618
435
            track.i_encoding_scope & MATROSKA_ENCODING_SCOPE_ALL_FRAMES )
619
435
        {
620
435
            p_block = block_zlib_decompress( VLC_OBJECT(p_demux), p_block );
621
435
            if( p_block == NULL )
622
0
                break;
623
435
        }
624
542k
        else
625
542k
#endif
626
542k
        if( track.i_compression_type == MATROSKA_COMPRESSION_LZOX &&
627
1.70k
            track.i_encoding_scope & MATROSKA_ENCODING_SCOPE_ALL_FRAMES )
628
1.70k
        {
629
1.70k
            p_block = block_lzo1x_decompress( VLC_OBJECT(p_demux), p_block );
630
1.70k
            if( p_block == NULL )
631
0
                break;
632
1.70k
        }
633
541k
        else
634
541k
        if( track.i_compression_type == MATROSKA_COMPRESSION_HEADER &&
635
165k
            track.i_encoding_scope & MATROSKA_ENCODING_SCOPE_ALL_FRAMES )
636
165k
        {
637
165k
            memcpy( p_block->p_buffer, track.p_compression_data->GetBuffer(), track.p_compression_data->GetSize() );
638
165k
        }
639
543k
        if ( track.fmt.i_codec == VLC_CODEC_PRORES )
640
0
        {
641
0
            SetDWBE( p_block->p_buffer, p_block->i_buffer - 8);
642
0
            memcpy( p_block->p_buffer + 4, "icpf", 4 );
643
0
        }
644
645
543k
        if ( b_key_picture )
646
194k
            p_block->i_flags |= BLOCK_FLAG_TYPE_I;
647
648
543k
        switch( track.fmt.i_codec )
649
543k
        {
650
351
        case VLC_CODEC_COOK:
651
351
        case VLC_CODEC_ATRAC3:
652
351
        {
653
351
            handle_real_audio(p_demux, &track, p_block, i_pts);
654
351
            block_Release(p_block);
655
351
            i_pts = ( track.i_default_duration )?
656
0
                i_pts + track.i_default_duration:
657
351
                VLC_TICK_INVALID;
658
351
            continue;
659
351
         }
660
661
0
         case VLC_CODEC_WEBVTT:
662
0
            {
663
0
                const uint8_t *p_addition = NULL;
664
0
                size_t i_addition = 0;
665
0
                if(additions)
666
0
                {
667
0
                    auto blockmore = FindChild<const KaxBlockMore>(*additions);
668
0
                    if(blockmore)
669
0
                    {
670
0
                        auto addition = FindChild<const KaxBlockAdditional>(*blockmore);
671
0
                        if(addition)
672
0
                        {
673
0
                            i_addition = static_cast<std::string::size_type>(addition->GetSize());
674
0
                            p_addition = reinterpret_cast<const uint8_t *>(addition->GetBuffer());
675
0
                        }
676
0
                    }
677
0
                }
678
0
                p_block = WEBVTT_Repack_Sample( p_block, /* D_WEBVTT -> webm */
679
0
                                                !p_track->codec.compare( 0, 1, "D" ),
680
0
                                                p_addition, i_addition );
681
0
                if( !p_block )
682
0
                    continue;
683
0
            }
684
0
            break;
685
686
3.04k
         case VLC_CODEC_OPUS:
687
3.04k
            {
688
3.04k
                vlc_tick_t i_length = VLC_TICK_FROM_NS(i_duration * track.f_timecodescale *
689
3.04k
                                                       p_segment->i_timescale);
690
3.04k
                if ( i_length < 0 ) i_length = 0;
691
3.04k
                p_block->i_nb_samples = samples_from_vlc_tick(i_length, track.fmt.audio.i_rate);
692
3.04k
            }
693
3.04k
            break;
694
695
0
         case VLC_CODEC_DVBS:
696
0
            {
697
0
                p_block = block_Realloc( p_block, 2, p_block->i_buffer + 1);
698
699
0
                if( unlikely( !p_block ) )
700
0
                    continue;
701
702
0
                p_block->p_buffer[0] = 0x20; // data identifier
703
0
                p_block->p_buffer[1] = 0x00; // subtitle stream id
704
0
                p_block->p_buffer[ p_block->i_buffer - 1 ] = 0x3f; // end marker
705
0
            }
706
0
            break;
707
708
141k
          case VLC_CODEC_AV1:
709
141k
            p_block = AV1_Unpack_Sample( p_block );
710
141k
            if( unlikely( !p_block ) )
711
0
                continue;
712
141k
            break;
713
714
141k
        case VLC_CODEC_VP8:
715
19.0k
        case VLC_CODEC_VP9:
716
19.0k
            if (additions && track.fmt.i_level) // contains alpha extradata
717
1.98k
            {
718
1.98k
                auto blockMore = FindChild<const KaxBlockMore>(*additions);
719
1.98k
                if(blockMore == nullptr)
720
3
                    break;
721
1.98k
                auto addId = FindChild<const KaxBlockAddID>(*blockMore);
722
1.98k
                if(addId == nullptr)
723
8
                    break;
724
1.97k
                if (static_cast<uint64_t>(*addId) != 1)
725
0
                    break;
726
727
1.97k
                auto addition = FindChild<const KaxBlockAdditional>(*blockMore);
728
1.97k
                if(addition == nullptr)
729
4
                    break;
730
731
1.97k
                auto alpha_data = new(std::nothrow) vlc_vpx_alpha_t();
732
1.97k
                if (unlikely(alpha_data == nullptr))
733
0
                {
734
0
                    block_Release( p_block );
735
0
                    return;
736
0
                }
737
1.97k
                alpha_data->data = static_cast<uint8_t*>(malloc(addition->GetSize()));
738
1.97k
                if (unlikely(alpha_data->data == nullptr))
739
0
                {
740
0
                    delete alpha_data;
741
0
                    block_Release( p_block );
742
0
                    return;
743
0
                }
744
1.97k
                alpha_data->size = addition->GetSize();
745
1.97k
                memcpy(alpha_data->data, addition->GetBuffer(), addition->GetSize());
746
1.97k
                vlc_ancillary *alpha =
747
1.97k
                    vlc_ancillary_CreateWithFreeCb(alpha_data, VLC_ANCILLARY_ID_VPX_ALPHA,
748
1.97k
                                                   ReleaseVpxAlpha);
749
1.97k
                if (likely(alpha != NULL))
750
1.97k
                {
751
1.97k
                    if(vlc_frame_AttachAncillary(p_block, alpha) != VLC_SUCCESS){
752
0
                        vlc_ancillary_Release(alpha);
753
0
                        block_Release(p_block);
754
0
                        return;
755
0
                    }
756
1.97k
                }
757
0
                else
758
0
                {
759
0
                    ReleaseVpxAlpha(alpha_data);
760
0
                    block_Release( p_block );
761
0
                    return;
762
0
                }
763
1.97k
            }
764
19.0k
            break;
765
543k
        }
766
767
542k
        if( track.fmt.i_cat != VIDEO_ES )
768
269k
        {
769
269k
            if ( track.fmt.i_cat == DATA_ES )
770
0
            {
771
                // TODO handle the start/stop times of this packet
772
0
                p_sys->ev.SendData( track, p_block );
773
0
                return;
774
0
            }
775
269k
            p_block->i_dts = p_block->i_pts = i_pts;
776
269k
        }
777
273k
        else
778
273k
        {
779
            // correct timestamping when B frames are used
780
273k
            if( track.b_dts_only )
781
1.93k
            {
782
1.93k
                p_block->i_pts = VLC_TICK_INVALID;
783
1.93k
                p_block->i_dts = i_pts;
784
1.93k
            }
785
271k
            else if( track.b_pts_only )
786
193k
            {
787
193k
                p_block->i_pts = i_pts;
788
193k
                p_block->i_dts = i_pts;
789
193k
            }
790
77.9k
            else
791
77.9k
            {
792
77.9k
                p_block->i_pts = i_pts;
793
                // condition when the DTS is correct (keyframe or B frame == NOT P frame)
794
77.9k
                if ( b_key_picture || b_discardable_picture )
795
7.77k
                        p_block->i_dts = p_block->i_pts;
796
70.1k
                else if ( track.i_last_dts == VLC_TICK_INVALID )
797
87
                    p_block->i_dts = i_pts;
798
70.1k
                else
799
70.1k
                    p_block->i_dts = std::min( i_pts, track.i_last_dts + track.i_default_duration );
800
77.9k
            }
801
273k
        }
802
803
542k
        send_Block( p_demux, &track, p_block, i_number_frames, i_duration );
804
805
        /* use time stamp only for first block */
806
542k
        i_pts = ( track.i_default_duration )?
807
127k
                 i_pts + track.i_default_duration:
808
542k
                 ( track.fmt.b_packetized ) ? VLC_TICK_INVALID : i_pts + 1;
809
542k
    }
810
62.0k
}
811
812
/*****************************************************************************
813
 * Demux: reads and demuxes data packets
814
 *****************************************************************************
815
 * Returns -1 in case of error, 0 in case of EOF, 1 otherwise
816
 *****************************************************************************/
817
static int Demux( demux_t *p_demux)
818
64.1k
{
819
64.1k
    demux_sys_t *p_sys = (demux_sys_t *)p_demux->p_sys;
820
821
64.1k
    vlc_mutex_locker demux_lock ( &p_sys->lock_demuxer );
822
823
64.1k
    virtual_segment_c  *p_vsegment = p_sys->GetCurrentVSegment();
824
825
64.1k
    if( p_sys->i_pts >= p_sys->i_start_pts )
826
58.1k
    {
827
58.1k
        if ( p_vsegment->UpdateCurrentToChapter( *p_demux ) )
828
26
            return VLC_DEMUXER_SUCCESS;
829
58.1k
        p_vsegment = p_sys->GetCurrentVSegment();
830
58.1k
    }
831
832
64.1k
    matroska_segment_c *p_segment = p_vsegment->CurrentSegment();
833
64.1k
    if ( p_segment == NULL )
834
35
        return VLC_DEMUXER_EOF;
835
836
64.1k
    KaxBlock *block;
837
64.1k
    KaxSimpleBlock *simpleblock;
838
64.1k
    KaxBlockAdditions *additions;
839
64.1k
    uint64_t i_block_duration = 0;
840
64.1k
    bool b_key_picture;
841
64.1k
    bool b_discardable_picture;
842
843
64.1k
    if( p_segment->BlockGet( block, simpleblock, additions,
844
64.1k
                             &b_key_picture, &b_discardable_picture, &i_block_duration ) )
845
2.03k
    {
846
2.03k
        if ( p_vsegment->CurrentEdition() && p_vsegment->CurrentEdition()->b_ordered )
847
56
        {
848
56
            const virtual_chapter_c *p_chap = p_vsegment->CurrentChapter();
849
            // check if there are more chapters to read
850
56
            if ( p_chap != NULL )
851
56
            {
852
                /* TODO handle successive chapters with the same user_start_time/user_end_time
853
                */
854
56
                p_sys->i_pts = p_chap->i_mk_virtual_stop_time + VLC_TICK_0;
855
56
                p_sys->i_pts++; // trick to avoid staying on segments with no duration and no content
856
857
56
                return VLC_DEMUXER_SUCCESS;
858
56
            }
859
56
        }
860
861
1.97k
        msg_Warn( p_demux, "cannot get block EOF?" );
862
1.97k
        return VLC_DEMUXER_EOF;
863
2.03k
    }
864
865
62.0k
    KaxInternalBlock& internal_block = block
866
62.0k
        ? static_cast<KaxInternalBlock&>( *block )
867
62.0k
        : static_cast<KaxInternalBlock&>( *simpleblock );
868
869
62.0k
    {
870
62.0k
        mkv_track_t *p_track = p_segment->FindTrackByBlock( block, simpleblock );
871
872
62.0k
        if( p_track == NULL )
873
0
        {
874
0
            msg_Err( p_demux, "invalid track number" );
875
0
            delete block;
876
0
            delete additions;
877
0
            return VLC_DEMUXER_EGENERIC;
878
0
        }
879
880
62.0k
        mkv_track_t &track = *p_track;
881
882
883
62.0k
        if( track.i_skip_until_fpos != std::numeric_limits<uint64_t>::max() ) {
884
885
62.0k
            uint64_t block_fpos = internal_block.GetElementPosition();
886
887
62.0k
            if ( track.i_skip_until_fpos > block_fpos )
888
49
            {
889
49
                delete block;
890
49
                delete additions;
891
49
                return VLC_DEMUXER_SUCCESS; // this block shall be ignored
892
49
            }
893
62.0k
        }
894
62.0k
    }
895
896
62.0k
    if (UpdatePCR( p_demux ) != VLC_SUCCESS)
897
0
    {
898
0
        msg_Err( p_demux, "ES_OUT_SET_PCR failed, aborting." );
899
0
        delete block;
900
0
        delete additions;
901
0
        return VLC_DEMUXER_EGENERIC;
902
0
    }
903
904
    /* set pts */
905
62.0k
    {
906
62.0k
        p_sys->i_pts = p_sys->i_mk_chapter_time + VLC_TICK_0;
907
62.0k
        p_sys->i_pts += VLC_TICK_FROM_NS(internal_block.GlobalTimestamp());
908
62.0k
    }
909
910
62.0k
    if ( p_vsegment->CurrentEdition() &&
911
62.0k
         p_vsegment->CurrentEdition()->b_ordered &&
912
9.31k
         p_vsegment->CurrentChapter() == NULL )
913
0
    {
914
        /* nothing left to read in this ordered edition */
915
0
        delete block;
916
0
        delete additions;
917
0
        return VLC_DEMUXER_EOF;
918
0
    }
919
920
62.0k
    BlockDecode( p_demux, block, simpleblock, additions,
921
62.0k
                 p_sys->i_pts, i_block_duration, b_key_picture, b_discardable_picture );
922
923
62.0k
    delete block;
924
62.0k
    delete additions;
925
926
62.0k
    return VLC_DEMUXER_SUCCESS;
927
62.0k
}
928
929
mkv_track_t::mkv_track_t(enum es_format_category_e es_cat) :
930
3.78k
    b_default(true)
931
3.78k
  ,b_enabled(true)
932
3.78k
  ,b_forced(false)
933
3.78k
  ,i_number(0)
934
3.78k
  ,i_extra_data(0)
935
3.78k
  ,p_extra_data(NULL)
936
3.78k
  ,b_dts_only(false)
937
3.78k
  ,b_pts_only(false)
938
3.78k
  ,b_no_duration(false)
939
3.78k
  ,i_default_duration(0)
940
3.78k
  ,f_timecodescale(1.0)
941
3.78k
  ,i_last_dts(VLC_TICK_INVALID)
942
3.78k
  ,i_skip_until_fpos(std::numeric_limits<uint64_t>::max())
943
3.78k
  ,f_fps(0)
944
3.78k
  ,p_es(NULL)
945
3.78k
  ,i_original_rate(0)
946
3.78k
  ,i_chans_to_reorder(0)
947
3.78k
  ,p_sys(NULL)
948
3.78k
  ,b_discontinuity(false)
949
3.78k
  ,b_has_alpha(false)
950
3.78k
  ,i_compression_type(MATROSKA_COMPRESSION_NONE)
951
3.78k
  ,i_encoding_scope(MATROSKA_ENCODING_SCOPE_ALL_FRAMES)
952
3.78k
  ,p_compression_data(NULL)
953
3.78k
  ,i_seek_preroll(0)
954
3.78k
  ,i_codec_delay(0)
955
3.78k
{
956
3.78k
    std::memset( &pi_chan_table, 0, sizeof( pi_chan_table ) );
957
958
3.78k
    es_format_Init(&fmt, es_cat, 0);
959
960
3.78k
    switch( es_cat )
961
3.78k
    {
962
1.32k
        case AUDIO_ES:
963
1.32k
            fmt.audio.i_channels = 1;
964
1.32k
            fmt.audio.i_rate = 8000;
965
            /* fall through */
966
3.13k
        case VIDEO_ES:
967
3.72k
        case SPU_ES:
968
3.72k
            fmt.psz_language = strdup("eng");
969
3.72k
            break;
970
64
        default:
971
            // no language needed
972
64
            break;
973
3.78k
    }
974
3.78k
}
975
976
mkv_track_t::~mkv_track_t()
977
3.78k
{
978
3.78k
    es_format_Clean( &fmt );
979
3.78k
    assert(p_es == NULL); // did we leak an ES ?
980
981
3.78k
    free(p_extra_data);
982
983
3.78k
    delete p_compression_data;
984
3.78k
    delete p_sys;
985
3.78k
}
986
987
matroska_stream_c::matroska_stream_c( stream_t *s, bool owner )
988
2.04k
    :io_callback( s, owner )
989
2.04k
    ,estream( io_callback )
990
2.04k
{}
991
992
bool matroska_stream_c::isUsed() const
993
2.01k
{
994
2.01k
    for( size_t j = 0; j < segments.size(); j++ )
995
2.01k
    {
996
2.01k
        if( segments[j]->b_preloaded )
997
2.01k
            return true;
998
2.01k
    }
999
0
    return false;
1000
2.01k
}
1001
1002
} // namespace