Coverage Report

Created: 2026-07-30 07:17

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