Coverage Report

Created: 2026-10-28 07:09

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