Coverage Report

Created: 2026-11-12 07:28

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