Coverage Report

Created: 2026-10-14 06:52

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