Coverage Report

Created: 2026-06-30 07:56

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
166
vlc_module_begin ()
55
83
    set_shortname( "Matroska" )
56
83
    set_description( N_("Matroska stream demuxer" ) )
57
83
    set_capability( "demux", 50 )
58
166
    set_callbacks( Open, Close )
59
83
    set_subcategory( SUBCAT_INPUT_DEMUX )
60
61
83
    add_bool( "mkv-use-ordered-chapters", true,
62
83
            N_("Respect ordered chapters"),
63
83
            N_("Play chapters in the order specified in the segment.") )
64
65
83
    add_bool( "mkv-use-chapter-codec", true,
66
83
            N_("Chapter codecs"),
67
83
            N_("Use chapter codecs found in the segment.") )
68
69
83
    add_bool( "mkv-preload-local-dir", true,
70
83
            N_("Preload MKV files in the same directory"),
71
83
            N_("Preload matroska files in the same directory to find linked segments (not good for broken files).") )
72
73
83
    add_bool( "mkv-seek-percent", false,
74
83
            N_("Seek based on percent not time"),
75
83
            nullptr )
76
77
83
    add_bool( "mkv-use-dummy", false,
78
83
            N_("Dummy Elements"),
79
83
            N_("Read and discard unknown EBML elements (not good for broken files).") )
80
81
83
    add_bool( "mkv-preload-clusters", false,
82
83
            N_("Preload clusters"),
83
83
            N_("Find all cluster positions by jumping cluster-to-cluster before playback") )
84
85
83
    add_shortcut( "mka", "mkv" )
86
83
    add_file_extension("mka")
87
83
    add_file_extension("mks")
88
83
    add_file_extension("mkv")
89
90
83
    add_submodule()
91
166
        set_callbacks( OpenTrusted, Close )
92
83
        set_capability( "demux", 0 )
93
83
        add_shortcut( "mka_trusted", "mkv_trusted" )
94
83
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
3.97k
{
109
3.97k
    demux_sys_t        *p_sys;
110
3.97k
    matroska_stream_c  *p_stream;
111
3.97k
    matroska_segment_c *p_segment;
112
3.97k
    const uint8_t      *p_peek;
113
3.97k
    std::string         s_path, s_filename;
114
3.97k
    bool                b_need_preload = false;
115
116
    /* peek the beginning */
117
3.97k
    if( vlc_stream_Peek( p_demux->s, &p_peek, 4 ) < 4 ) return VLC_EGENERIC;
118
119
    /* is a valid file */
120
3.97k
    if( p_peek[0] != 0x1a || p_peek[1] != 0x45 ||
121
2.63k
        p_peek[2] != 0xdf || p_peek[3] != 0xa3 ) return VLC_EGENERIC;
122
123
    /* Set the demux function */
124
2.62k
    p_demux->pf_demux   = Demux;
125
2.62k
    p_demux->pf_control = Control;
126
2.62k
    p_demux->p_sys      = p_sys = new demux_sys_t( *p_demux, trust_cues );
127
128
2.62k
    vlc_stream_Control( p_demux->s, STREAM_CAN_SEEK, &p_sys->b_seekable );
129
2.62k
    if ( !p_sys->b_seekable || vlc_stream_Control(
130
2.62k
          p_demux->s, STREAM_CAN_FASTSEEK, &p_sys->b_fastseekable ) )
131
0
        p_sys->b_fastseekable = false;
132
133
2.62k
    es_out_Control( p_demux->out, ES_OUT_SET_ES_CAT_POLICY, VIDEO_ES,
134
2.62k
                    ES_OUT_ES_POLICY_EXCLUSIVE );
135
136
2.62k
    p_stream = new matroska_stream_c( p_demux->s, false );
137
2.62k
    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.62k
    p_sys->streams.push_back( p_stream );
144
145
2.62k
    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
5.25k
    for (size_t i=0; i<p_stream->segments.size(); i++)
152
2.62k
    {
153
2.62k
        p_stream->segments[i]->Preload();
154
2.62k
        b_need_preload |= p_stream->segments[i]->b_ref_external_segments;
155
2.62k
        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.62k
    }
160
161
2.62k
    p_segment = p_stream->segments[0];
162
2.62k
    if( p_segment->cluster == NULL && p_segment->stored_editions.size() == 0 )
163
56
    {
164
56
        msg_Err( p_demux, "cannot find any cluster or chapter, damaged file ?" );
165
56
        goto error;
166
56
    }
167
168
2.57k
    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.57k
    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.57k
    if ( !p_sys->PreloadLinked() ||
259
2.56k
         !p_sys->PreparePlayback( *p_sys->GetCurrentVSegment() ) )
260
23
    {
261
23
        msg_Err( p_demux, "cannot use the segment" );
262
23
        goto error;
263
23
    }
264
    /* Seek to the beginning */
265
2.55k
    p_sys->GetCurrentVSegment()->Seek( *p_demux, 0, p_sys->GetCurrentVSegment()->CurrentChapter() );
266
267
2.55k
    if (!p_sys->FreeUnused())
268
0
    {
269
0
        msg_Err( p_demux, "no usable segment" );
270
0
        goto error;
271
0
    }
272
273
2.55k
    return VLC_SUCCESS;
274
275
79
error:
276
79
    delete p_sys;
277
79
    return VLC_EGENERIC;
278
2.55k
}
279
280
static int Open( vlc_object_t *p_this )
281
3.96k
{
282
3.96k
    demux_t *p_demux = (demux_t*)p_this;
283
3.96k
    return OpenInternal( p_demux, false );
284
3.96k
}
285
286
static int OpenTrusted( vlc_object_t *p_this )
287
17
{
288
17
    demux_t *p_demux = (demux_t*)p_this;
289
17
    return OpenInternal( p_demux, true );
290
17
}
291
292
/*****************************************************************************
293
 * Close: frees unused data
294
 *****************************************************************************/
295
static void Close( vlc_object_t *p_this )
296
2.55k
{
297
2.55k
    demux_t     *p_demux = reinterpret_cast<demux_t*>( p_this );
298
2.55k
    demux_sys_t *p_sys = (demux_sys_t *)p_demux->p_sys;
299
2.55k
    virtual_segment_c *p_vsegment = p_sys->GetCurrentVSegment();
300
2.55k
    if( p_vsegment )
301
2.55k
    {
302
2.55k
        matroska_segment_c *p_segment = p_vsegment->CurrentSegment();
303
2.55k
        if( p_segment )
304
2.42k
            p_segment->ESDestroy();
305
2.55k
    }
306
307
2.55k
    delete p_sys;
308
2.55k
}
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, int64_t i_duration, bool b_key_picture,
543
                  bool b_discardable_picture )
544
67.7k
{
545
67.7k
    demux_sys_t *p_sys = (demux_sys_t *)p_demux->p_sys;
546
67.7k
    matroska_segment_c *p_segment = p_sys->GetCurrentVSegment()->CurrentSegment();
547
548
67.7k
    KaxInternalBlock& internal_block = simpleblock
549
67.7k
        ? static_cast<KaxInternalBlock&>( *simpleblock )
550
67.7k
        : static_cast<KaxInternalBlock&>( *block );
551
552
67.7k
    if( !p_segment ) return;
553
554
67.7k
    mkv_track_t *p_track = p_segment->FindTrackByBlock( block, simpleblock );
555
67.7k
    if( p_track == NULL )
556
0
    {
557
0
        msg_Err( p_demux, "invalid track number" );
558
0
        return;
559
0
    }
560
561
67.7k
    mkv_track_t &track = *p_track;
562
563
67.7k
    if( track.fmt.i_cat != DATA_ES && track.p_es == NULL )
564
685
    {
565
685
        msg_Err( p_demux, "unknown track number %u (%4.4s)",
566
685
                 track.i_number, (const char *) &track.fmt.i_codec );
567
685
        return;
568
685
    }
569
570
67.1k
    if (i_pts != VLC_TICK_INVALID)
571
67.1k
        i_pts += p_segment->pcr_shift - track.i_codec_delay;
572
573
67.1k
    if ( track.fmt.i_cat != DATA_ES )
574
67.1k
    {
575
67.1k
        bool b;
576
67.1k
        es_out_Control( p_demux->out, ES_OUT_GET_ES_STATE, track.p_es, &b );
577
578
67.1k
        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
67.1k
    }
585
586
67.1k
    size_t frame_size = 0;
587
67.1k
    size_t block_size = internal_block.GetSize();
588
67.1k
    const unsigned i_number_frames = internal_block.NumberFrames();
589
590
708k
    for( unsigned int i_frame = 0; i_frame < i_number_frames; i_frame++ )
591
641k
    {
592
641k
        block_t *p_block;
593
641k
        DataBuffer *data = &internal_block.GetBuffer(i_frame);
594
595
641k
        frame_size += data->Size();
596
641k
        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
641k
        size_t extra_data = track.fmt.i_codec == VLC_CODEC_PRORES ? 8 : 0;
602
603
641k
        if( track.i_compression_type == MATROSKA_COMPRESSION_HEADER &&
604
166k
            track.i_encoding_scope & MATROSKA_ENCODING_SCOPE_ALL_FRAMES )
605
166k
            p_block = MemToBlock( data->Buffer(), data->Size(), track.p_compression_data->GetSize() + extra_data );
606
474k
        else if( unlikely( track.fmt.i_codec == VLC_CODEC_WAVPACK ) )
607
209
            p_block = packetize_wavpack( track, data->Buffer(), data->Size() );
608
474k
        else
609
474k
            p_block = MemToBlock( data->Buffer(), data->Size(), extra_data );
610
611
641k
        if( p_block == NULL )
612
0
        {
613
0
            break;
614
0
        }
615
616
641k
#ifdef HAVE_ZLIB
617
641k
        if( track.i_compression_type == MATROSKA_COMPRESSION_ZLIB &&
618
1.97k
            track.i_encoding_scope & MATROSKA_ENCODING_SCOPE_ALL_FRAMES )
619
1.97k
        {
620
1.97k
            p_block = block_zlib_decompress( VLC_OBJECT(p_demux), p_block );
621
1.97k
            if( p_block == NULL )
622
0
                break;
623
1.97k
        }
624
639k
        else
625
639k
#endif
626
639k
        if( track.i_compression_type == MATROSKA_COMPRESSION_LZOX &&
627
30.0k
            track.i_encoding_scope & MATROSKA_ENCODING_SCOPE_ALL_FRAMES )
628
30.0k
        {
629
30.0k
            p_block = block_lzo1x_decompress( VLC_OBJECT(p_demux), p_block );
630
30.0k
            if( p_block == NULL )
631
0
                break;
632
30.0k
        }
633
609k
        else
634
609k
        if( track.i_compression_type == MATROSKA_COMPRESSION_HEADER &&
635
166k
            track.i_encoding_scope & MATROSKA_ENCODING_SCOPE_ALL_FRAMES )
636
166k
        {
637
166k
            memcpy( p_block->p_buffer, track.p_compression_data->GetBuffer(), track.p_compression_data->GetSize() );
638
166k
        }
639
641k
        if ( track.fmt.i_codec == VLC_CODEC_PRORES )
640
0
            memcpy( p_block->p_buffer + 4, "icpf", 4 );
641
642
641k
        if ( b_key_picture )
643
215k
            p_block->i_flags |= BLOCK_FLAG_TYPE_I;
644
645
641k
        switch( track.fmt.i_codec )
646
641k
        {
647
1.98k
        case VLC_CODEC_COOK:
648
1.98k
        case VLC_CODEC_ATRAC3:
649
1.98k
        {
650
1.98k
            handle_real_audio(p_demux, &track, p_block, i_pts);
651
1.98k
            block_Release(p_block);
652
1.98k
            i_pts = ( track.i_default_duration )?
653
0
                i_pts + track.i_default_duration:
654
1.98k
                VLC_TICK_INVALID;
655
1.98k
            continue;
656
1.98k
         }
657
658
0
         case VLC_CODEC_WEBVTT:
659
0
            {
660
0
                const uint8_t *p_addition = NULL;
661
0
                size_t i_addition = 0;
662
0
                if(additions)
663
0
                {
664
0
                    auto blockmore = FindChild<const KaxBlockMore>(*additions);
665
0
                    if(blockmore)
666
0
                    {
667
0
                        auto addition = FindChild<const KaxBlockAdditional>(*blockmore);
668
0
                        if(addition)
669
0
                        {
670
0
                            i_addition = static_cast<std::string::size_type>(addition->GetSize());
671
0
                            p_addition = reinterpret_cast<const uint8_t *>(addition->GetBuffer());
672
0
                        }
673
0
                    }
674
0
                }
675
0
                p_block = WEBVTT_Repack_Sample( p_block, /* D_WEBVTT -> webm */
676
0
                                                !p_track->codec.compare( 0, 1, "D" ),
677
0
                                                p_addition, i_addition );
678
0
                if( !p_block )
679
0
                    continue;
680
0
            }
681
0
            break;
682
683
1.65k
         case VLC_CODEC_OPUS:
684
1.65k
            {
685
1.65k
                vlc_tick_t i_length = VLC_TICK_FROM_NS(i_duration * track.f_timecodescale *
686
1.65k
                                                       p_segment->i_timescale);
687
1.65k
                if ( i_length < 0 ) i_length = 0;
688
1.65k
                p_block->i_nb_samples = samples_from_vlc_tick(i_length, track.fmt.audio.i_rate);
689
1.65k
            }
690
1.65k
            break;
691
692
40
         case VLC_CODEC_DVBS:
693
40
            {
694
40
                p_block = block_Realloc( p_block, 2, p_block->i_buffer + 1);
695
696
40
                if( unlikely( !p_block ) )
697
0
                    continue;
698
699
40
                p_block->p_buffer[0] = 0x20; // data identifier
700
40
                p_block->p_buffer[1] = 0x00; // subtitle stream id
701
40
                p_block->p_buffer[ p_block->i_buffer - 1 ] = 0x3f; // end marker
702
40
            }
703
0
            break;
704
705
207k
          case VLC_CODEC_AV1:
706
207k
            p_block = AV1_Unpack_Sample( p_block );
707
207k
            if( unlikely( !p_block ) )
708
0
                continue;
709
207k
            break;
710
711
207k
        case VLC_CODEC_VP8:
712
16.5k
        case VLC_CODEC_VP9:
713
16.5k
            if (additions && track.fmt.i_level) // contains alpha extradata
714
2.13k
            {
715
2.13k
                auto blockMore = FindChild<const KaxBlockMore>(*additions);
716
2.13k
                if(blockMore == nullptr)
717
3
                    break;
718
2.13k
                auto addId = FindChild<const KaxBlockAddID>(*blockMore);
719
2.13k
                if(addId == nullptr)
720
8
                    break;
721
2.12k
                if (static_cast<uint64_t>(*addId) != 1)
722
0
                    break;
723
724
2.12k
                auto addition = FindChild<const KaxBlockAdditional>(*blockMore);
725
2.12k
                if(addition == nullptr)
726
4
                    break;
727
728
2.12k
                auto alpha_data = new(std::nothrow) vlc_vpx_alpha_t();
729
2.12k
                if (unlikely(alpha_data == nullptr))
730
0
                {
731
0
                    block_Release( p_block );
732
0
                    return;
733
0
                }
734
2.12k
                alpha_data->data = static_cast<uint8_t*>(malloc(addition->GetSize()));
735
2.12k
                if (unlikely(alpha_data->data == nullptr))
736
0
                {
737
0
                    delete alpha_data;
738
0
                    block_Release( p_block );
739
0
                    return;
740
0
                }
741
2.12k
                alpha_data->size = addition->GetSize();
742
2.12k
                memcpy(alpha_data->data, addition->GetBuffer(), addition->GetSize());
743
2.12k
                vlc_ancillary *alpha =
744
2.12k
                    vlc_ancillary_CreateWithFreeCb(alpha_data, VLC_ANCILLARY_ID_VPX_ALPHA,
745
2.12k
                                                   ReleaseVpxAlpha);
746
2.12k
                if (likely(alpha != NULL))
747
2.12k
                {
748
2.12k
                    if(vlc_frame_AttachAncillary(p_block, alpha) != VLC_SUCCESS){
749
0
                        vlc_ancillary_Release(alpha);
750
0
                        block_Release(p_block);
751
0
                        return;
752
0
                    }
753
2.12k
                }
754
0
                else
755
0
                {
756
0
                    ReleaseVpxAlpha(alpha_data);
757
0
                    block_Release( p_block );
758
0
                    return;
759
0
                }
760
2.12k
            }
761
16.5k
            break;
762
641k
        }
763
764
639k
        if( track.fmt.i_cat != VIDEO_ES )
765
301k
        {
766
301k
            if ( track.fmt.i_cat == DATA_ES )
767
0
            {
768
                // TODO handle the start/stop times of this packet
769
0
                p_sys->ev.SendData( track, p_block );
770
0
                return;
771
0
            }
772
301k
            p_block->i_dts = p_block->i_pts = i_pts;
773
301k
        }
774
337k
        else
775
337k
        {
776
            // correct timestamping when B frames are used
777
337k
            if( track.b_dts_only )
778
1.85k
            {
779
1.85k
                p_block->i_pts = VLC_TICK_INVALID;
780
1.85k
                p_block->i_dts = i_pts;
781
1.85k
            }
782
335k
            else if( track.b_pts_only )
783
256k
            {
784
256k
                p_block->i_pts = i_pts;
785
256k
                p_block->i_dts = i_pts;
786
256k
            }
787
78.9k
            else
788
78.9k
            {
789
78.9k
                p_block->i_pts = i_pts;
790
                // condition when the DTS is correct (keyframe or B frame == NOT P frame)
791
78.9k
                if ( b_key_picture || b_discardable_picture )
792
7.27k
                        p_block->i_dts = p_block->i_pts;
793
71.6k
                else if ( track.i_last_dts == VLC_TICK_INVALID )
794
120
                    p_block->i_dts = i_pts;
795
71.5k
                else
796
71.5k
                    p_block->i_dts = std::min( i_pts, track.i_last_dts + track.i_default_duration );
797
78.9k
            }
798
337k
        }
799
800
639k
        send_Block( p_demux, &track, p_block, i_number_frames, i_duration );
801
802
        /* use time stamp only for first block */
803
639k
        i_pts = ( track.i_default_duration )?
804
130k
                 i_pts + track.i_default_duration:
805
639k
                 ( track.fmt.b_packetized ) ? VLC_TICK_INVALID : i_pts + 1;
806
639k
    }
807
67.1k
}
808
809
/*****************************************************************************
810
 * Demux: reads and demuxes data packets
811
 *****************************************************************************
812
 * Returns -1 in case of error, 0 in case of EOF, 1 otherwise
813
 *****************************************************************************/
814
static int Demux( demux_t *p_demux)
815
70.8k
{
816
70.8k
    demux_sys_t *p_sys = (demux_sys_t *)p_demux->p_sys;
817
818
70.8k
    vlc_mutex_locker demux_lock ( &p_sys->lock_demuxer );
819
820
70.8k
    virtual_segment_c  *p_vsegment = p_sys->GetCurrentVSegment();
821
822
70.8k
    if( p_sys->i_pts >= p_sys->i_start_pts )
823
63.7k
    {
824
63.7k
        if ( p_vsegment->UpdateCurrentToChapter( *p_demux ) )
825
134
            return VLC_DEMUXER_SUCCESS;
826
63.5k
        p_vsegment = p_sys->GetCurrentVSegment();
827
63.5k
    }
828
829
70.7k
    matroska_segment_c *p_segment = p_vsegment->CurrentSegment();
830
70.7k
    if ( p_segment == NULL )
831
123
        return VLC_DEMUXER_EOF;
832
833
70.6k
    KaxBlock *block;
834
70.6k
    KaxSimpleBlock *simpleblock;
835
70.6k
    KaxBlockAdditions *additions;
836
70.6k
    int64_t i_block_duration = 0;
837
70.6k
    bool b_key_picture;
838
70.6k
    bool b_discardable_picture;
839
840
70.6k
    if( p_segment->BlockGet( block, simpleblock, additions,
841
70.6k
                             &b_key_picture, &b_discardable_picture, &i_block_duration ) )
842
2.67k
    {
843
2.67k
        if ( p_vsegment->CurrentEdition() && p_vsegment->CurrentEdition()->b_ordered )
844
251
        {
845
251
            const virtual_chapter_c *p_chap = p_vsegment->CurrentChapter();
846
            // check if there are more chapters to read
847
251
            if ( p_chap != NULL )
848
251
            {
849
                /* TODO handle successive chapters with the same user_start_time/user_end_time
850
                */
851
251
                p_sys->i_pts = p_chap->i_mk_virtual_stop_time + VLC_TICK_0;
852
251
                p_sys->i_pts++; // trick to avoid staying on segments with no duration and no content
853
854
251
                return VLC_DEMUXER_SUCCESS;
855
251
            }
856
251
        }
857
858
2.42k
        msg_Warn( p_demux, "cannot get block EOF?" );
859
2.42k
        return VLC_DEMUXER_EOF;
860
2.67k
    }
861
862
67.9k
    KaxInternalBlock& internal_block = block
863
67.9k
        ? static_cast<KaxInternalBlock&>( *block )
864
67.9k
        : static_cast<KaxInternalBlock&>( *simpleblock );
865
866
67.9k
    {
867
67.9k
        mkv_track_t *p_track = p_segment->FindTrackByBlock( block, simpleblock );
868
869
67.9k
        if( p_track == NULL )
870
0
        {
871
0
            msg_Err( p_demux, "invalid track number" );
872
0
            delete block;
873
0
            delete additions;
874
0
            return VLC_DEMUXER_EGENERIC;
875
0
        }
876
877
67.9k
        mkv_track_t &track = *p_track;
878
879
880
67.9k
        if( track.i_skip_until_fpos != std::numeric_limits<uint64_t>::max() ) {
881
882
67.2k
            uint64_t block_fpos = internal_block.GetElementPosition();
883
884
67.2k
            if ( track.i_skip_until_fpos > block_fpos )
885
165
            {
886
165
                delete block;
887
165
                delete additions;
888
165
                return VLC_DEMUXER_SUCCESS; // this block shall be ignored
889
165
            }
890
67.2k
        }
891
67.9k
    }
892
893
67.7k
    if (UpdatePCR( p_demux ) != VLC_SUCCESS)
894
0
    {
895
0
        msg_Err( p_demux, "ES_OUT_SET_PCR failed, aborting." );
896
0
        delete block;
897
0
        delete additions;
898
0
        return VLC_DEMUXER_EGENERIC;
899
0
    }
900
901
    /* set pts */
902
67.7k
    {
903
67.7k
        p_sys->i_pts = p_sys->i_mk_chapter_time + VLC_TICK_0;
904
67.7k
        p_sys->i_pts += VLC_TICK_FROM_NS(internal_block.GlobalTimestamp());
905
67.7k
    }
906
907
67.7k
    if ( p_vsegment->CurrentEdition() &&
908
67.7k
         p_vsegment->CurrentEdition()->b_ordered &&
909
10.0k
         p_vsegment->CurrentChapter() == NULL )
910
0
    {
911
        /* nothing left to read in this ordered edition */
912
0
        delete block;
913
0
        delete additions;
914
0
        return VLC_DEMUXER_EOF;
915
0
    }
916
917
67.7k
    BlockDecode( p_demux, block, simpleblock, additions,
918
67.7k
                 p_sys->i_pts, i_block_duration, b_key_picture, b_discardable_picture );
919
920
67.7k
    delete block;
921
67.7k
    delete additions;
922
923
67.7k
    return VLC_DEMUXER_SUCCESS;
924
67.7k
}
925
926
mkv_track_t::mkv_track_t(enum es_format_category_e es_cat) :
927
5.37k
    b_default(true)
928
5.37k
  ,b_enabled(true)
929
5.37k
  ,b_forced(false)
930
5.37k
  ,i_number(0)
931
5.37k
  ,i_extra_data(0)
932
5.37k
  ,p_extra_data(NULL)
933
5.37k
  ,b_dts_only(false)
934
5.37k
  ,b_pts_only(false)
935
5.37k
  ,b_no_duration(false)
936
5.37k
  ,i_default_duration(0)
937
5.37k
  ,f_timecodescale(1.0)
938
5.37k
  ,i_last_dts(VLC_TICK_INVALID)
939
5.37k
  ,i_skip_until_fpos(std::numeric_limits<uint64_t>::max())
940
5.37k
  ,f_fps(0)
941
5.37k
  ,p_es(NULL)
942
5.37k
  ,i_original_rate(0)
943
5.37k
  ,i_chans_to_reorder(0)
944
5.37k
  ,p_sys(NULL)
945
5.37k
  ,b_discontinuity(false)
946
5.37k
  ,b_has_alpha(false)
947
5.37k
  ,i_compression_type(MATROSKA_COMPRESSION_NONE)
948
5.37k
  ,i_encoding_scope(MATROSKA_ENCODING_SCOPE_ALL_FRAMES)
949
5.37k
  ,p_compression_data(NULL)
950
5.37k
  ,i_seek_preroll(0)
951
5.37k
  ,i_codec_delay(0)
952
5.37k
{
953
5.37k
    std::memset( &pi_chan_table, 0, sizeof( pi_chan_table ) );
954
955
5.37k
    es_format_Init(&fmt, es_cat, 0);
956
957
5.37k
    switch( es_cat )
958
5.37k
    {
959
1.66k
        case AUDIO_ES:
960
1.66k
            fmt.audio.i_channels = 1;
961
1.66k
            fmt.audio.i_rate = 8000;
962
            /* fall through */
963
3.89k
        case VIDEO_ES:
964
4.82k
        case SPU_ES:
965
4.82k
            fmt.psz_language = strdup("eng");
966
4.82k
            break;
967
544
        default:
968
            // no language needed
969
544
            break;
970
5.37k
    }
971
5.37k
}
972
973
mkv_track_t::~mkv_track_t()
974
5.37k
{
975
5.37k
    es_format_Clean( &fmt );
976
5.37k
    assert(p_es == NULL); // did we leak an ES ?
977
978
5.37k
    free(p_extra_data);
979
980
5.37k
    delete p_compression_data;
981
5.37k
    delete p_sys;
982
5.37k
}
983
984
matroska_stream_c::matroska_stream_c( stream_t *s, bool owner )
985
2.62k
    :io_callback( s, owner )
986
2.62k
    ,estream( io_callback )
987
2.62k
{}
988
989
bool matroska_stream_c::isUsed() const
990
2.55k
{
991
2.55k
    for( size_t j = 0; j < segments.size(); j++ )
992
2.55k
    {
993
2.55k
        if( segments[j]->b_preloaded )
994
2.55k
            return true;
995
2.55k
    }
996
0
    return false;
997
2.55k
}
998
999
} // namespace