Coverage Report

Created: 2026-07-15 07:31

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/ffmpeg/libavformat/avformat.c
Line
Count
Source
1
/*
2
 * Various functions used by both muxers and demuxers
3
 * Copyright (c) 2000, 2001, 2002 Fabrice Bellard
4
 *
5
 * This file is part of FFmpeg.
6
 *
7
 * FFmpeg is free software; you can redistribute it and/or
8
 * modify it under the terms of the GNU Lesser General Public
9
 * License as published by the Free Software Foundation; either
10
 * version 2.1 of the License, or (at your option) any later version.
11
 *
12
 * FFmpeg is distributed in the hope that it will be useful,
13
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
15
 * Lesser General Public License for more details.
16
 *
17
 * You should have received a copy of the GNU Lesser General Public
18
 * License along with FFmpeg; if not, write to the Free Software
19
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
20
 */
21
22
#include <math.h>
23
#include "libavutil/avassert.h"
24
#include "libavutil/avstring.h"
25
#include "libavutil/channel_layout.h"
26
#include "libavutil/frame.h"
27
#include "libavutil/iamf.h"
28
#include "libavutil/mem.h"
29
#include "libavutil/opt.h"
30
#include "libavutil/pixfmt.h"
31
#include "libavutil/samplefmt.h"
32
#include "libavcodec/avcodec.h"
33
#include "libavcodec/codec.h"
34
#include "libavcodec/bsf.h"
35
#include "libavcodec/codec_desc.h"
36
#include "packet_internal.h"
37
#include "avformat.h"
38
#include "avformat_internal.h"
39
#include "avio.h"
40
#include "demux.h"
41
#include "mux.h"
42
#include "internal.h"
43
#include "url.h"
44
45
void ff_free_stream(AVStream **pst)
46
0
{
47
0
    AVStream *st = *pst;
48
0
    FFStream *const sti = ffstream(st);
49
50
0
    if (!st)
51
0
        return;
52
53
0
    if (st->attached_pic.data)
54
0
        av_packet_unref(&st->attached_pic);
55
56
0
    av_parser_close(sti->parser);
57
0
    avcodec_free_context(&sti->avctx);
58
0
    av_bsf_free(&sti->bsfc);
59
0
    av_freep(&sti->index_entries);
60
0
    av_freep(&sti->probe_data.buf);
61
62
0
    av_packet_free(&sti->parse_pkt);
63
64
0
    av_bsf_free(&sti->extract_extradata.bsf);
65
66
0
    if (sti->info) {
67
0
        av_freep(&sti->info->duration_error);
68
0
        av_freep(&sti->info);
69
0
    }
70
71
0
    av_dict_free(&st->metadata);
72
0
    avcodec_parameters_free(&st->codecpar);
73
0
    av_freep(&st->priv_data);
74
75
0
    av_freep(pst);
76
0
}
77
78
void ff_free_stream_group(AVStreamGroup **pstg)
79
0
{
80
0
    AVStreamGroup *stg = *pstg;
81
82
0
    if (!stg)
83
0
        return;
84
85
0
    av_freep(&stg->streams);
86
0
    av_dict_free(&stg->metadata);
87
0
    av_freep(&stg->priv_data);
88
0
    switch (stg->type) {
89
0
    case AV_STREAM_GROUP_PARAMS_IAMF_AUDIO_ELEMENT: {
90
0
        av_iamf_audio_element_free(&stg->params.iamf_audio_element);
91
0
        break;
92
0
    }
93
0
    case AV_STREAM_GROUP_PARAMS_IAMF_MIX_PRESENTATION: {
94
0
        av_iamf_mix_presentation_free(&stg->params.iamf_mix_presentation);
95
0
        break;
96
0
    }
97
0
    case AV_STREAM_GROUP_PARAMS_TILE_GRID:
98
0
        av_opt_free(stg->params.tile_grid);
99
0
        av_freep(&stg->params.tile_grid->offsets);
100
0
        av_packet_side_data_free(&stg->params.tile_grid->coded_side_data,
101
0
                                 &stg->params.tile_grid->nb_coded_side_data);
102
0
        av_freep(&stg->params.tile_grid);
103
0
        break;
104
0
    case AV_STREAM_GROUP_PARAMS_TREF:
105
0
        av_opt_free(stg->params.tref);
106
0
        av_freep(&stg->params.tref);
107
0
        break;
108
0
    case AV_STREAM_GROUP_PARAMS_LCEVC:
109
0
    case AV_STREAM_GROUP_PARAMS_DOLBY_VISION:
110
0
        av_opt_free(stg->params.layered_video);
111
0
        av_freep(&stg->params.layered_video);
112
0
        break;
113
0
    default:
114
0
        break;
115
0
    }
116
117
0
    av_freep(pstg);
118
0
}
119
120
void ff_remove_stream(AVFormatContext *s, AVStream *st)
121
0
{
122
0
    av_assert0(s->nb_streams>0);
123
0
    av_assert0(s->streams[ s->nb_streams - 1 ] == st);
124
125
0
    ff_free_stream(&s->streams[ --s->nb_streams ]);
126
0
}
127
128
void ff_remove_stream_group(AVFormatContext *s, AVStreamGroup *stg)
129
0
{
130
0
    av_assert0(s->nb_stream_groups > 0);
131
0
    av_assert0(s->stream_groups[ s->nb_stream_groups - 1 ] == stg);
132
133
0
    ff_free_stream_group(&s->stream_groups[ --s->nb_stream_groups ]);
134
0
}
135
136
/* XXX: suppress the packet queue */
137
void ff_flush_packet_queue(AVFormatContext *s)
138
0
{
139
0
    FormatContextInternal *const fci = ff_fc_internal(s);
140
0
    FFFormatContext *const si = &fci->fc;
141
0
    ff_packet_list_free(&fci->parse_queue);
142
0
    ff_packet_list_free(&si->packet_buffer);
143
0
    ff_packet_list_free(&fci->raw_packet_buffer);
144
145
0
    fci->raw_packet_buffer_size = 0;
146
0
}
147
148
void avformat_free_context(AVFormatContext *s)
149
1.57k
{
150
1.57k
    FormatContextInternal *fci;
151
1.57k
    FFFormatContext *si;
152
153
1.57k
    if (!s)
154
0
        return;
155
1.57k
    fci = ff_fc_internal(s);
156
1.57k
    si  = &fci->fc;
157
158
1.57k
    if (s->oformat && ffofmt(s->oformat)->deinit && fci->initialized)
159
0
        ffofmt(s->oformat)->deinit(s);
160
161
1.57k
    av_opt_free(s);
162
1.57k
    if (s->iformat && s->iformat->priv_class && s->priv_data)
163
0
        av_opt_free(s->priv_data);
164
1.57k
    if (s->oformat && s->oformat->priv_class && s->priv_data)
165
0
        av_opt_free(s->priv_data);
166
167
1.57k
    for (unsigned i = 0; i < s->nb_streams; i++)
168
0
        ff_free_stream(&s->streams[i]);
169
1.57k
    for (unsigned i = 0; i < s->nb_stream_groups; i++)
170
0
        ff_free_stream_group(&s->stream_groups[i]);
171
1.57k
    s->nb_stream_groups = 0;
172
1.57k
    s->nb_streams = 0;
173
174
1.57k
    for (unsigned i = 0; i < s->nb_programs; i++) {
175
0
        av_dict_free(&s->programs[i]->metadata);
176
0
        av_freep(&s->programs[i]->stream_index);
177
0
        av_freep(&s->programs[i]);
178
0
    }
179
1.57k
    s->nb_programs = 0;
180
181
1.57k
    av_freep(&s->programs);
182
1.57k
    av_freep(&s->priv_data);
183
1.57k
    while (s->nb_chapters--) {
184
0
        av_dict_free(&s->chapters[s->nb_chapters]->metadata);
185
0
        av_freep(&s->chapters[s->nb_chapters]);
186
0
    }
187
1.57k
    av_freep(&s->chapters);
188
1.57k
    av_dict_free(&s->metadata);
189
1.57k
    av_dict_free(&si->id3v2_meta);
190
1.57k
    av_packet_free(&si->pkt);
191
1.57k
    av_packet_free(&si->parse_pkt);
192
1.57k
    ff_packet_list_free(&si->packet_buffer);
193
1.57k
    av_freep(&s->streams);
194
1.57k
    av_freep(&s->stream_groups);
195
1.57k
    if (s->iformat)
196
0
        ff_flush_packet_queue(s);
197
1.57k
    av_freep(&s->url);
198
1.57k
    av_freep(&s->name);
199
1.57k
    av_free(s);
200
1.57k
}
201
202
/**
203
 * Copy all stream parameters from source to destination stream, with the
204
 * exception of the index field, which is usually set by avformat_new_stream().
205
 *
206
 * @param dst pointer to destination AVStream
207
 * @param src pointer to source AVStream
208
 * @return >=0 on success, AVERROR code on error
209
 */
210
static int stream_params_copy(AVStream *dst, const AVStream *src)
211
0
{
212
0
    int ret;
213
214
0
    dst->id                  = src->id;
215
0
    dst->time_base           = src->time_base;
216
0
    dst->start_time          = src->start_time;
217
0
    dst->duration            = src->duration;
218
0
    dst->nb_frames           = src->nb_frames;
219
0
    dst->disposition         = src->disposition;
220
0
    dst->discard             = src->discard;
221
0
    dst->sample_aspect_ratio = src->sample_aspect_ratio;
222
0
    dst->avg_frame_rate      = src->avg_frame_rate;
223
0
    dst->event_flags         = src->event_flags;
224
0
    dst->r_frame_rate        = src->r_frame_rate;
225
0
    dst->pts_wrap_bits       = src->pts_wrap_bits;
226
227
0
    av_dict_free(&dst->metadata);
228
0
    ret = av_dict_copy(&dst->metadata, src->metadata, 0);
229
0
    if (ret < 0)
230
0
        return ret;
231
232
0
    ret = avcodec_parameters_copy(dst->codecpar, src->codecpar);
233
0
    if (ret < 0)
234
0
        return ret;
235
236
0
    av_packet_unref(&dst->attached_pic);
237
0
    if (src->attached_pic.data) {
238
0
        ret = av_packet_ref(&dst->attached_pic, &src->attached_pic);
239
0
        if (ret < 0)
240
0
            return ret;
241
0
    }
242
243
0
    return 0;
244
0
}
245
246
AVStream *ff_stream_clone(AVFormatContext *dst_ctx, const AVStream *src)
247
0
{
248
0
    AVStream *st;
249
0
    int ret;
250
251
0
    st = avformat_new_stream(dst_ctx, NULL);
252
0
    if (!st)
253
0
        return NULL;
254
255
0
    ret = stream_params_copy(st, src);
256
0
    if (ret < 0) {
257
0
        ff_remove_stream(dst_ctx, st);
258
0
        return NULL;
259
0
    }
260
261
0
    return st;
262
0
}
263
264
const char *avformat_stream_group_name(enum AVStreamGroupParamsType type)
265
0
{
266
0
    switch(type) {
267
0
    case AV_STREAM_GROUP_PARAMS_IAMF_AUDIO_ELEMENT:        return "IAMF Audio Element";
268
0
    case AV_STREAM_GROUP_PARAMS_IAMF_MIX_PRESENTATION:     return "IAMF Mix Presentation";
269
0
    case AV_STREAM_GROUP_PARAMS_TILE_GRID:                 return "Tile Grid";
270
0
    case AV_STREAM_GROUP_PARAMS_LCEVC:                     return "LCEVC (Split video and enhancement)";
271
0
    case AV_STREAM_GROUP_PARAMS_TREF:                      return "Track Reference";
272
0
    case AV_STREAM_GROUP_PARAMS_DOLBY_VISION:              return "Dolby Vision (Split base and enhancement layer)";
273
0
    }
274
0
    return NULL;
275
0
}
276
277
AVProgram *av_new_program(AVFormatContext *ac, int id)
278
0
{
279
0
    AVProgram *program = NULL;
280
0
    int ret;
281
282
0
    av_log(ac, AV_LOG_TRACE, "new_program: id=0x%04x\n", id);
283
284
0
    for (unsigned i = 0; i < ac->nb_programs; i++)
285
0
        if (ac->programs[i]->id == id)
286
0
            program = ac->programs[i];
287
288
0
    if (!program) {
289
0
        program = av_mallocz(sizeof(*program));
290
0
        if (!program)
291
0
            return NULL;
292
0
        ret = av_dynarray_add_nofree(&ac->programs, &ac->nb_programs, program);
293
0
        if (ret < 0) {
294
0
            av_free(program);
295
0
            return NULL;
296
0
        }
297
0
        program->discard = AVDISCARD_NONE;
298
0
        program->pmt_version = -1;
299
0
        program->id = id;
300
0
        program->pts_wrap_reference = AV_NOPTS_VALUE;
301
0
        program->pts_wrap_behavior = AV_PTS_WRAP_IGNORE;
302
0
        program->start_time =
303
0
        program->end_time   = AV_NOPTS_VALUE;
304
0
    }
305
0
    return program;
306
0
}
307
308
int av_program_add_stream_index2(AVFormatContext *ac, int progid, unsigned idx)
309
0
{
310
0
    AVProgram *program = NULL;
311
0
    void *tmp;
312
313
0
    if (idx >= ac->nb_streams) {
314
0
        av_log(ac, AV_LOG_ERROR, "stream index %d is greater than stream count %d\n", idx, ac->nb_streams);
315
0
        return AVERROR(EINVAL);
316
0
    }
317
318
0
    for (unsigned i = 0; i < ac->nb_programs; i++) {
319
0
        if (ac->programs[i]->id != progid)
320
0
            continue;
321
0
        program = ac->programs[i];
322
0
        for (unsigned j = 0; j < program->nb_stream_indexes; j++)
323
0
            if (program->stream_index[j] == idx)
324
0
                return 0;
325
326
0
        tmp = av_realloc_array(program->stream_index, program->nb_stream_indexes+1, sizeof(unsigned int));
327
0
        if (!tmp)
328
0
            return AVERROR(ENOMEM);
329
0
        program->stream_index = tmp;
330
0
        program->stream_index[program->nb_stream_indexes++] = idx;
331
0
        return 0;
332
0
    }
333
334
0
    av_log(ac, AV_LOG_ERROR, "no program with id %d found\n", progid);
335
0
    return AVERROR(EINVAL);
336
0
}
337
338
void av_program_add_stream_index(AVFormatContext *ac, int progid, unsigned idx)
339
0
{
340
0
    av_program_add_stream_index2(ac, progid, idx);
341
0
    return;
342
0
}
343
344
int av_program_copy(AVFormatContext *dst, const AVFormatContext *src, int progid, int flags)
345
0
{
346
0
    const AVProgram *src_prog = NULL;
347
0
    AVProgram *dst_prog = NULL;
348
0
    int ret, idx = -1, match = -1;
349
0
    int overwrite = flags & AVFMT_PROGCOPY_OVERWRITE;
350
351
0
    if ((flags & AVFMT_PROGCOPY_MATCH_BY_ID) && (flags & AVFMT_PROGCOPY_MATCH_BY_INDEX))
352
0
        return AVERROR(EINVAL);
353
0
    else if (flags & AVFMT_PROGCOPY_MATCH_BY_ID)
354
0
        match = 0;
355
0
    else if (flags & AVFMT_PROGCOPY_MATCH_BY_INDEX)
356
0
        match = 1;
357
358
0
    for (unsigned i = 0; i < src->nb_programs; i++) {
359
0
        if (src->programs[i]->id == progid) {
360
0
            if (src_prog) {
361
0
                av_log(dst, AV_LOG_ERROR, "multiple programs found in source with same id 0x%04x. Not copying.\n", progid);
362
0
                return AVERROR(EINVAL);
363
0
            } else {
364
0
                src_prog = src->programs[i];
365
0
            }
366
0
        }
367
0
    }
368
369
0
    if (!src_prog) {
370
0
        av_log(dst, AV_LOG_ERROR, "source program not found: id=0x%04x\n", progid);
371
0
        return AVERROR(EINVAL);
372
0
    }
373
374
0
    for (unsigned i = 0; i < dst->nb_programs; i++) {
375
0
        if (dst->programs[i]->id == progid) {
376
0
            if (idx > -1) {
377
0
                av_log(dst, AV_LOG_ERROR, "multiple programs found in target with same id 0x%04x. Not copying.\n", progid);
378
0
                return AVERROR(EINVAL);
379
0
            } else {
380
0
                idx = i;
381
0
            }
382
0
        }
383
0
    }
384
385
0
    if (idx >= 0 && !overwrite)
386
0
        return AVERROR(EEXIST);
387
388
0
    av_log(dst, AV_LOG_TRACE, "%s program: id=0x%04x\n", idx >= 0 ? "overwriting" : "copying", progid);
389
390
0
    if (idx >= 0) {
391
0
        dst_prog = dst->programs[idx];
392
0
        av_dict_free(&dst_prog->metadata);
393
0
        av_freep(&dst_prog->stream_index);
394
0
        dst_prog->nb_stream_indexes = 0;
395
0
    } else {
396
0
        dst_prog = av_new_program(dst, progid);
397
0
        if (!dst_prog)
398
0
            return AVERROR(ENOMEM);
399
0
    }
400
401
    /* public fields */
402
0
    dst_prog->id          = src_prog->id;
403
0
    dst_prog->flags       = src_prog->flags;
404
0
    dst_prog->discard     = src_prog->discard;
405
0
    dst_prog->program_num = src_prog->program_num;
406
0
    dst_prog->pmt_pid     = src_prog->pmt_pid;
407
0
    dst_prog->pcr_pid     = src_prog->pcr_pid;
408
0
    dst_prog->pmt_version = src_prog->pmt_version;
409
410
0
    if (match == -1 && src->nb_streams) {
411
0
        match = 0;
412
0
        for (unsigned i = 0; i < src->nb_streams && !match; i++) {
413
0
            int src_id = src->streams[i]->id;
414
0
            if (!src_id) {
415
0
                match = 1;
416
0
                break;
417
0
            }
418
0
            for (unsigned j=i+1; j < src->nb_streams; j++) {
419
0
                int sib_id = src->streams[j]->id;
420
0
                if (src_id == sib_id) {
421
0
                    match = 1;
422
0
                    break;
423
0
                }
424
0
            }
425
0
        }
426
0
    }
427
428
0
    for (unsigned i = 0; i < dst->nb_streams; i++) {
429
0
        int dst_val = match ? i : dst->streams[i]->id;
430
431
0
        for (unsigned j = 0; j < src_prog->nb_stream_indexes; j++) {
432
0
            int src_val = match ? src_prog->stream_index[j] : src->streams[src_prog->stream_index[j]]->id;
433
434
0
            if (dst_val == src_val) {
435
0
                ret = av_program_add_stream_index2(dst, dst_prog->id, i);
436
0
                if (ret < 0)
437
0
                    return ret;
438
0
            }
439
0
        }
440
0
    }
441
442
0
    ret = av_dict_copy(&dst_prog->metadata, src_prog->metadata, 0);
443
0
    if (ret < 0)
444
0
        return ret;
445
446
0
    return 0;
447
0
}
448
449
AVProgram *av_find_program_from_stream(AVFormatContext *ic, AVProgram *last, int s)
450
0
{
451
0
    for (unsigned i = 0; i < ic->nb_programs; i++) {
452
0
        if (ic->programs[i] == last) {
453
0
            last = NULL;
454
0
        } else {
455
0
            if (!last)
456
0
                for (unsigned j = 0; j < ic->programs[i]->nb_stream_indexes; j++)
457
0
                    if (ic->programs[i]->stream_index[j] == s)
458
0
                        return ic->programs[i];
459
0
        }
460
0
    }
461
0
    return NULL;
462
0
}
463
464
int av_find_default_stream_index(AVFormatContext *s)
465
0
{
466
0
    int best_stream = 0;
467
0
    int best_score = INT_MIN;
468
469
0
    if (s->nb_streams <= 0)
470
0
        return -1;
471
0
    for (unsigned i = 0; i < s->nb_streams; i++) {
472
0
        const AVStream *const st = s->streams[i];
473
0
        const FFStream *const sti = cffstream(st);
474
0
        int score = 0;
475
0
        if (st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO) {
476
0
            if (st->disposition & AV_DISPOSITION_ATTACHED_PIC)
477
0
                score -= 400;
478
0
            if (st->codecpar->width && st->codecpar->height)
479
0
                score += 50;
480
0
            score+= 25;
481
0
        }
482
0
        if (st->codecpar->codec_type == AVMEDIA_TYPE_AUDIO) {
483
0
            if (st->codecpar->sample_rate)
484
0
                score += 50;
485
0
        }
486
0
        if (sti->codec_info_nb_frames)
487
0
            score += 12;
488
489
0
        if (st->discard != AVDISCARD_ALL)
490
0
            score += 200;
491
492
0
        if (score > best_score) {
493
0
            best_score = score;
494
0
            best_stream = i;
495
0
        }
496
0
    }
497
0
    return best_stream;
498
0
}
499
500
int av_find_best_stream(AVFormatContext *ic, enum AVMediaType type,
501
                        int wanted_stream_nb, int related_stream,
502
                        const AVCodec **decoder_ret, int flags)
503
0
{
504
0
    int nb_streams = ic->nb_streams;
505
0
    int ret = AVERROR_STREAM_NOT_FOUND;
506
0
    int best_count = -1, best_multiframe = -1, best_disposition = -1;
507
0
    int count, multiframe, disposition;
508
0
    int64_t best_bitrate = -1;
509
0
    int64_t bitrate;
510
0
    unsigned *program = NULL;
511
0
    const AVCodec *decoder = NULL, *best_decoder = NULL;
512
513
0
    if (related_stream >= 0 && wanted_stream_nb < 0) {
514
0
        AVProgram *p = av_find_program_from_stream(ic, NULL, related_stream);
515
0
        if (p) {
516
0
            program    = p->stream_index;
517
0
            nb_streams = p->nb_stream_indexes;
518
0
        }
519
0
    }
520
0
    for (unsigned i = 0; i < nb_streams; i++) {
521
0
        int real_stream_index = program ? program[i] : i;
522
0
        AVStream *st          = ic->streams[real_stream_index];
523
0
        AVCodecParameters *par = st->codecpar;
524
0
        if (par->codec_type != type)
525
0
            continue;
526
0
        if (wanted_stream_nb >= 0 && real_stream_index != wanted_stream_nb)
527
0
            continue;
528
0
        if (type == AVMEDIA_TYPE_AUDIO && !(par->ch_layout.nb_channels && par->sample_rate))
529
0
            continue;
530
0
        if (decoder_ret) {
531
0
            decoder = ff_find_decoder(ic, st, par->codec_id);
532
0
            if (!decoder) {
533
0
                if (ret < 0)
534
0
                    ret = AVERROR_DECODER_NOT_FOUND;
535
0
                continue;
536
0
            }
537
0
        }
538
0
        disposition = !(st->disposition & (AV_DISPOSITION_HEARING_IMPAIRED | AV_DISPOSITION_VISUAL_IMPAIRED))
539
0
                      + !! (st->disposition & AV_DISPOSITION_DEFAULT);
540
0
        count = ffstream(st)->codec_info_nb_frames;
541
0
        bitrate = par->bit_rate;
542
0
        multiframe = FFMIN(5, count);
543
0
        if ((best_disposition >  disposition) ||
544
0
            (best_disposition == disposition && best_multiframe >  multiframe) ||
545
0
            (best_disposition == disposition && best_multiframe == multiframe && best_bitrate >  bitrate) ||
546
0
            (best_disposition == disposition && best_multiframe == multiframe && best_bitrate == bitrate && best_count >= count))
547
0
            continue;
548
0
        best_disposition = disposition;
549
0
        best_count   = count;
550
0
        best_bitrate = bitrate;
551
0
        best_multiframe = multiframe;
552
0
        ret          = real_stream_index;
553
0
        best_decoder = decoder;
554
0
        if (program && i == nb_streams - 1 && ret < 0) {
555
0
            program    = NULL;
556
0
            nb_streams = ic->nb_streams;
557
            /* no related stream found, try again with everything */
558
0
            i = 0;
559
0
        }
560
0
    }
561
0
    if (decoder_ret)
562
0
        *decoder_ret = best_decoder;
563
0
    return ret;
564
0
}
565
566
/**
567
 * Matches a stream specifier (but ignores requested index).
568
 *
569
 * @param indexptr set to point to the requested stream index if there is one
570
 *
571
 * @return <0 on error
572
 *         0  if st is NOT a matching stream
573
 *         >0 if st is a matching stream
574
 */
575
static int match_stream_specifier(const AVFormatContext *s, const AVStream *st,
576
                                  const char *spec, const char **indexptr,
577
                                  const AVStreamGroup **g, const AVProgram **p)
578
0
{
579
0
    int match = 1;                      /* Stores if the specifier matches so far. */
580
0
    while (*spec) {
581
0
        if (*spec <= '9' && *spec >= '0') { /* opt:index */
582
0
            if (indexptr)
583
0
                *indexptr = spec;
584
0
            return match;
585
0
        } else if (*spec == 'v' || *spec == 'a' || *spec == 's' || *spec == 'd' ||
586
0
                   *spec == 't' || *spec == 'V') { /* opt:[vasdtV] */
587
0
            enum AVMediaType type;
588
0
            int nopic = 0;
589
590
0
            switch (*spec++) {
591
0
            case 'v': type = AVMEDIA_TYPE_VIDEO;      break;
592
0
            case 'a': type = AVMEDIA_TYPE_AUDIO;      break;
593
0
            case 's': type = AVMEDIA_TYPE_SUBTITLE;   break;
594
0
            case 'd': type = AVMEDIA_TYPE_DATA;       break;
595
0
            case 't': type = AVMEDIA_TYPE_ATTACHMENT; break;
596
0
            case 'V': type = AVMEDIA_TYPE_VIDEO; nopic = 1; break;
597
0
            default:  av_assert0(0);
598
0
            }
599
0
            if (*spec && *spec++ != ':')         /* If we are not at the end, then another specifier must follow. */
600
0
                return AVERROR(EINVAL);
601
602
0
            if (type != st->codecpar->codec_type)
603
0
                match = 0;
604
0
            if (nopic && (st->disposition & AV_DISPOSITION_ATTACHED_PIC))
605
0
                match = 0;
606
0
        } else if (*spec == 'g' && *(spec + 1) == ':') {
607
0
            int64_t group_idx = -1, group_id = -1;
608
0
            int found = 0;
609
0
            char *endptr;
610
0
            spec += 2;
611
0
            if (*spec == '#' || (*spec == 'i' && *(spec + 1) == ':')) {
612
0
                spec += 1 + (*spec == 'i');
613
0
                group_id = strtol(spec, &endptr, 0);
614
0
                if (spec == endptr || (*endptr && *endptr++ != ':'))
615
0
                    return AVERROR(EINVAL);
616
0
                spec = endptr;
617
0
            } else {
618
0
                group_idx = strtol(spec, &endptr, 0);
619
                /* Disallow empty id and make sure that if we are not at the end, then another specifier must follow. */
620
0
                if (spec == endptr || (*endptr && *endptr++ != ':'))
621
0
                    return AVERROR(EINVAL);
622
0
                spec = endptr;
623
0
            }
624
0
            if (match) {
625
0
                if (group_id > 0) {
626
0
                    for (unsigned i = 0; i < s->nb_stream_groups; i++) {
627
0
                        if (group_id == s->stream_groups[i]->id) {
628
0
                            group_idx = i;
629
0
                            break;
630
0
                        }
631
0
                    }
632
0
                }
633
0
                if (group_idx < 0 || group_idx >= s->nb_stream_groups)
634
0
                    return AVERROR(EINVAL);
635
0
                for (unsigned j = 0; j < s->stream_groups[group_idx]->nb_streams; j++) {
636
0
                    if (st->index == s->stream_groups[group_idx]->streams[j]->index) {
637
0
                        found = 1;
638
0
                        if (g)
639
0
                            *g = s->stream_groups[group_idx];
640
0
                        break;
641
0
                    }
642
0
                }
643
0
            }
644
0
            if (!found)
645
0
                match = 0;
646
0
        } else if (*spec == 'p' && *(spec + 1) == ':') {
647
0
            int prog_id;
648
0
            int found = 0;
649
0
            char *endptr;
650
0
            spec += 2;
651
0
            prog_id = strtol(spec, &endptr, 0);
652
            /* Disallow empty id and make sure that if we are not at the end, then another specifier must follow. */
653
0
            if (spec == endptr || (*endptr && *endptr++ != ':'))
654
0
                return AVERROR(EINVAL);
655
0
            spec = endptr;
656
0
            if (match) {
657
0
                for (unsigned i = 0; i < s->nb_programs; i++) {
658
0
                    if (s->programs[i]->id != prog_id)
659
0
                        continue;
660
661
0
                    for (unsigned j = 0; j < s->programs[i]->nb_stream_indexes; j++) {
662
0
                        if (st->index == s->programs[i]->stream_index[j]) {
663
0
                            found = 1;
664
0
                            if (p)
665
0
                                *p = s->programs[i];
666
0
                            i = s->nb_programs;
667
0
                            break;
668
0
                        }
669
0
                    }
670
0
                }
671
0
            }
672
0
            if (!found)
673
0
                match = 0;
674
0
        } else if (*spec == '#' ||
675
0
                   (*spec == 'i' && *(spec + 1) == ':')) {
676
0
            int stream_id;
677
0
            char *endptr;
678
0
            spec += 1 + (*spec == 'i');
679
0
            stream_id = strtol(spec, &endptr, 0);
680
0
            if (spec == endptr || *endptr)                /* Disallow empty id and make sure we are at the end. */
681
0
                return AVERROR(EINVAL);
682
0
            return match && (stream_id == st->id);
683
0
        } else if (*spec == 'm' && *(spec + 1) == ':') {
684
0
            const AVDictionaryEntry *tag;
685
0
            int ret;
686
687
0
            if (match) {
688
0
                spec += 2;
689
0
                const char *val = strchr(spec, ':');
690
691
0
                char *key = val ? av_strndup(spec, val - spec) : av_strdup(spec);
692
0
                if (!key)
693
0
                    return AVERROR(ENOMEM);
694
695
0
                tag = av_dict_get(st->metadata, key, NULL, 0);
696
0
                if (tag) {
697
0
                    if (!val || !strcmp(tag->value, val + 1))
698
0
                        ret = 1;
699
0
                    else
700
0
                        ret = 0;
701
0
                } else
702
0
                    ret = 0;
703
704
0
                av_freep(&key);
705
0
            }
706
0
            return match && ret;
707
0
        } else if (*spec == 'u' && *(spec + 1) == '\0') {
708
0
            const AVCodecParameters *par = st->codecpar;
709
0
            int val;
710
0
            switch (par->codec_type) {
711
0
            case AVMEDIA_TYPE_AUDIO:
712
0
                val = par->sample_rate && par->ch_layout.nb_channels;
713
0
                if (par->format == AV_SAMPLE_FMT_NONE)
714
0
                    return 0;
715
0
                break;
716
0
            case AVMEDIA_TYPE_VIDEO:
717
0
                val = par->width && par->height;
718
0
                if (par->format == AV_PIX_FMT_NONE)
719
0
                    return 0;
720
0
                break;
721
0
            case AVMEDIA_TYPE_UNKNOWN:
722
0
                val = 0;
723
0
                break;
724
0
            default:
725
0
                val = 1;
726
0
                break;
727
0
            }
728
0
            return match && (par->codec_id != AV_CODEC_ID_NONE && val != 0);
729
0
        } else {
730
0
            return AVERROR(EINVAL);
731
0
        }
732
0
    }
733
734
0
    return match;
735
0
}
736
737
int avformat_match_stream_specifier(AVFormatContext *s, AVStream *st,
738
                                    const char *spec)
739
0
{
740
0
    int ret, index;
741
0
    char *endptr;
742
0
    const char *indexptr = NULL;
743
0
    const AVStreamGroup *g = NULL;
744
0
    const AVProgram *p = NULL;
745
0
    int nb_streams;
746
747
0
    ret = match_stream_specifier(s, st, spec, &indexptr, &g, &p);
748
0
    if (ret < 0)
749
0
        goto error;
750
751
0
    if (!indexptr)
752
0
        return ret;
753
754
0
    index = strtol(indexptr, &endptr, 0);
755
0
    if (*endptr) {                  /* We can't have anything after the requested index. */
756
0
        ret = AVERROR(EINVAL);
757
0
        goto error;
758
0
    }
759
760
    /* This is not really needed but saves us a loop for simple stream index specifiers. */
761
0
    if (spec == indexptr)
762
0
        return (index == st->index);
763
764
    /* If we requested a matching stream index, we have to ensure st is that. */
765
0
    nb_streams = g ? g->nb_streams : (p ? p->nb_stream_indexes : s->nb_streams);
766
0
    for (int i = 0; i < nb_streams && index >= 0; i++) {
767
0
        unsigned idx = g ? g->streams[i]->index : (p ? p->stream_index[i] : i);
768
0
        const AVStream *candidate = s->streams[idx];
769
0
        ret = match_stream_specifier(s, candidate, spec, NULL, NULL, NULL);
770
0
        if (ret < 0)
771
0
            goto error;
772
0
        if (ret > 0 && index-- == 0 && st == candidate)
773
0
            return 1;
774
0
    }
775
0
    return 0;
776
777
0
error:
778
0
    if (ret == AVERROR(EINVAL))
779
0
        av_log(s, AV_LOG_ERROR, "Invalid stream specifier: %s.\n", spec);
780
0
    return ret;
781
0
}
782
783
AVRational av_guess_sample_aspect_ratio(AVFormatContext *format, AVStream *stream, AVFrame *frame)
784
0
{
785
0
    AVRational undef = {0, 1};
786
0
    AVRational stream_sample_aspect_ratio = stream ? stream->sample_aspect_ratio : undef;
787
0
    AVRational codec_sample_aspect_ratio  = stream && stream->codecpar ? stream->codecpar->sample_aspect_ratio : undef;
788
0
    AVRational frame_sample_aspect_ratio  = frame  ? frame->sample_aspect_ratio  : codec_sample_aspect_ratio;
789
790
0
    av_reduce(&stream_sample_aspect_ratio.num, &stream_sample_aspect_ratio.den,
791
0
               stream_sample_aspect_ratio.num,  stream_sample_aspect_ratio.den, INT_MAX);
792
0
    if (stream_sample_aspect_ratio.num <= 0 || stream_sample_aspect_ratio.den <= 0)
793
0
        stream_sample_aspect_ratio = undef;
794
795
0
    av_reduce(&frame_sample_aspect_ratio.num, &frame_sample_aspect_ratio.den,
796
0
               frame_sample_aspect_ratio.num,  frame_sample_aspect_ratio.den, INT_MAX);
797
0
    if (frame_sample_aspect_ratio.num <= 0 || frame_sample_aspect_ratio.den <= 0)
798
0
        frame_sample_aspect_ratio = undef;
799
800
0
    if (stream_sample_aspect_ratio.num)
801
0
        return stream_sample_aspect_ratio;
802
0
    else
803
0
        return frame_sample_aspect_ratio;
804
0
}
805
806
AVRational av_guess_frame_rate(AVFormatContext *format, AVStream *st, AVFrame *frame)
807
0
{
808
0
    AVRational fr = st->r_frame_rate;
809
0
    const AVCodecDescriptor *desc = cffstream(st)->codec_desc;
810
0
    AVRational   avg_fr = st->avg_frame_rate;
811
812
0
    if (avg_fr.num > 0 && avg_fr.den > 0 && fr.num > 0 && fr.den > 0 &&
813
0
        av_q2d(avg_fr) < 70 && av_q2d(fr) > 210) {
814
0
        fr = avg_fr;
815
0
    }
816
817
0
    if (desc && (desc->props & AV_CODEC_PROP_FIELDS)) {
818
0
        const AVCodecContext *const avctx = ffstream(st)->avctx;
819
0
        AVRational codec_fr = avctx->framerate;
820
821
0
        if (   codec_fr.num > 0 && codec_fr.den > 0 &&
822
0
            (fr.num == 0 || av_q2d(codec_fr) < av_q2d(fr)*0.7 && fabs(1.0 - av_q2d(av_div_q(avg_fr, fr))) > 0.1))
823
0
            fr = codec_fr;
824
0
    }
825
826
0
    return fr;
827
0
}
828
829
void avpriv_set_pts_info(AVStream *st, int pts_wrap_bits,
830
                         unsigned int pts_num, unsigned int pts_den)
831
0
{
832
0
    FFStream *const sti = ffstream(st);
833
0
    AVRational new_tb;
834
0
    if (av_reduce(&new_tb.num, &new_tb.den, pts_num, pts_den, INT_MAX)) {
835
0
        if (new_tb.num != pts_num)
836
0
            av_log(NULL, AV_LOG_DEBUG,
837
0
                   "st:%d removing common factor %d from timebase\n",
838
0
                   st->index, pts_num / new_tb.num);
839
0
    } else
840
0
        av_log(NULL, AV_LOG_WARNING,
841
0
               "st:%d has too large timebase, reducing\n", st->index);
842
843
0
    if (new_tb.num <= 0 || new_tb.den <= 0) {
844
0
        av_log(NULL, AV_LOG_ERROR,
845
0
               "Ignoring attempt to set invalid timebase %d/%d for st:%d\n",
846
0
               new_tb.num, new_tb.den,
847
0
               st->index);
848
0
        return;
849
0
    }
850
0
    st->time_base     = new_tb;
851
0
    if (sti->avctx)
852
0
        sti->avctx->pkt_timebase = new_tb;
853
0
    st->pts_wrap_bits = pts_wrap_bits;
854
0
}
855
856
const AVCodec *ff_find_decoder(AVFormatContext *s, const AVStream *st,
857
                               enum AVCodecID codec_id)
858
0
{
859
0
    switch (st->codecpar->codec_type) {
860
0
    case AVMEDIA_TYPE_VIDEO:
861
0
        if (s->video_codec)    return s->video_codec;
862
0
        break;
863
0
    case AVMEDIA_TYPE_AUDIO:
864
0
        if (s->audio_codec)    return s->audio_codec;
865
0
        break;
866
0
    case AVMEDIA_TYPE_SUBTITLE:
867
0
        if (s->subtitle_codec) return s->subtitle_codec;
868
0
        break;
869
0
    }
870
871
0
    return avcodec_find_decoder(codec_id);
872
0
}
873
874
int ff_copy_whiteblacklists(AVFormatContext *dst, const AVFormatContext *src)
875
0
{
876
0
#define OFF(field) offsetof(AVFormatContext, field)
877
0
    static const unsigned offsets[] = {
878
0
        OFF(codec_whitelist),    OFF(format_whitelist),
879
0
        OFF(protocol_whitelist), OFF(protocol_blacklist),
880
0
    };
881
0
#undef OFF
882
0
    av_assert0(!dst->codec_whitelist &&
883
0
               !dst->format_whitelist &&
884
0
               !dst->protocol_whitelist &&
885
0
               !dst->protocol_blacklist);
886
0
    for (unsigned i = 0; i < FF_ARRAY_ELEMS(offsets); i++) {
887
0
        const char *src_str = *(char *const*)((const char*)src + offsets[i]);
888
889
0
        if (src_str) {
890
0
            char *dst_str = av_strdup(src_str);
891
0
            if (!dst_str) {
892
0
                av_log(dst, AV_LOG_ERROR, "Failed to duplicate black/whitelist\n");
893
0
                return AVERROR(ENOMEM);
894
0
            }
895
896
0
            *(char **)((char*)dst + offsets[i]) = dst_str;
897
0
        }
898
0
    }
899
0
    if (src->recursion_limit <= 0) {
900
0
        av_log(dst, AV_LOG_ERROR, "Too deep recursion\n");
901
0
        return AVERROR_INVALIDDATA;
902
0
    }
903
0
    dst->recursion_limit = src->recursion_limit - 1;
904
0
    return 0;
905
0
}
906
907
int ff_is_intra_only(enum AVCodecID id)
908
0
{
909
0
    const AVCodecDescriptor *d = avcodec_descriptor_get(id);
910
0
    if (!d)
911
0
        return 0;
912
0
    if ((d->type == AVMEDIA_TYPE_VIDEO || d->type == AVMEDIA_TYPE_AUDIO) &&
913
0
        !(d->props & AV_CODEC_PROP_INTRA_ONLY))
914
0
        return 0;
915
0
    return 1;
916
0
}
917
918
void ff_format_set_url(AVFormatContext *s, char *url)
919
0
{
920
0
    av_assert0(url);
921
0
    av_freep(&s->url);
922
0
    s->url = url;
923
0
}
924
925
int ff_format_check_set_url(AVFormatContext *s, const char *url)
926
0
{
927
0
    URLComponents uc;
928
0
    av_assert0(url);
929
0
    char proto[64];
930
931
0
    int ret = ff_url_decompose(&uc, url, NULL);
932
0
    if (ret < 0)
933
0
        return ret;
934
0
    av_strlcpy(proto, uc.scheme, FFMIN(sizeof(proto), uc.url_component_end_scheme - uc.scheme));
935
936
0
    if (s->protocol_whitelist && av_match_list(proto, s->protocol_whitelist, ',') <= 0) {
937
0
        av_log(s, AV_LOG_ERROR, "Protocol '%s' not on whitelist '%s'!\n", proto, s->protocol_whitelist);
938
0
        return AVERROR(EINVAL);
939
0
    }
940
941
0
    if (s->protocol_blacklist && av_match_list(proto, s->protocol_blacklist, ',') > 0) {
942
0
        av_log(s, AV_LOG_ERROR, "Protocol '%s' on blacklist '%s'!\n", proto, s->protocol_blacklist);
943
0
        return AVERROR(EINVAL);
944
0
    }
945
946
0
    char *urldup = av_strdup(url);
947
0
    if (!urldup)
948
0
        return AVERROR(ENOMEM);
949
950
0
    av_freep(&s->url);
951
0
    s->url = urldup;
952
0
    return 0;
953
0
}
954
955
956
int ff_format_io_close(AVFormatContext *s, AVIOContext **pb)
957
0
{
958
0
    int ret = 0;
959
0
    if (*pb)
960
0
        ret = s->io_close2(s, *pb);
961
    *pb = NULL;
962
0
    return ret;
963
0
}