• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Various functions used by both muxers and demuxers
3  * Copyright (c) 2000, 2001, 2002 Fabrice Bellard
4  *
5  * This file is part of FFmpeg.
6  *
7  * FFmpeg is free software; you can redistribute it and/or
8  * modify it under the terms of the GNU Lesser General Public
9  * License as published by the Free Software Foundation; either
10  * version 2.1 of the License, or (at your option) any later version.
11  *
12  * FFmpeg is distributed in the hope that it will be useful,
13  * but WITHOUT ANY WARRANTY; without even the implied warranty of
14  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
15  * Lesser General Public License for more details.
16  *
17  * You should have received a copy of the GNU Lesser General Public
18  * License along with FFmpeg; if not, write to the Free Software
19  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
20  */
21 
22 #include <math.h>
23 #include "libavutil/avassert.h"
24 #include "libavutil/avstring.h"
25 #include "libavutil/channel_layout.h"
26 #include "libavutil/intreadwrite.h"
27 #include "libavutil/mem.h"
28 #include "libavutil/opt.h"
29 #include "libavutil/pixfmt.h"
30 #include "libavutil/samplefmt.h"
31 #include "libavcodec/avcodec.h"
32 #include "libavcodec/bsf.h"
33 #include "libavcodec/codec_desc.h"
34 #include "libavcodec/packet_internal.h"
35 #include "avformat.h"
36 #include "avio.h"
37 #include "demux.h"
38 #include "internal.h"
39 
ff_free_stream(AVStream ** pst)40 void ff_free_stream(AVStream **pst)
41 {
42     AVStream *st = *pst;
43     FFStream *const sti = ffstream(st);
44 
45     if (!st)
46         return;
47 
48     for (int i = 0; i < st->nb_side_data; i++)
49         av_freep(&st->side_data[i].data);
50     av_freep(&st->side_data);
51 
52     if (st->attached_pic.data)
53         av_packet_unref(&st->attached_pic);
54 
55     av_parser_close(sti->parser);
56     avcodec_free_context(&sti->avctx);
57     av_bsf_free(&sti->bsfc);
58     av_freep(&sti->priv_pts);
59     av_freep(&sti->index_entries);
60     av_freep(&sti->probe_data.buf);
61 
62     av_bsf_free(&sti->extract_extradata.bsf);
63 
64     if (sti->info) {
65         av_freep(&sti->info->duration_error);
66         av_freep(&sti->info);
67     }
68 
69     av_dict_free(&st->metadata);
70     avcodec_parameters_free(&st->codecpar);
71     av_freep(&st->priv_data);
72 
73     av_freep(pst);
74 }
75 
ff_remove_stream(AVFormatContext * s,AVStream * st)76 void ff_remove_stream(AVFormatContext *s, AVStream *st)
77 {
78     av_assert0(s->nb_streams>0);
79     av_assert0(s->streams[ s->nb_streams - 1 ] == st);
80 
81     ff_free_stream(&s->streams[ --s->nb_streams ]);
82 }
83 
84 /* XXX: suppress the packet queue */
ff_flush_packet_queue(AVFormatContext * s)85 void ff_flush_packet_queue(AVFormatContext *s)
86 {
87     FFFormatContext *const si = ffformatcontext(s);
88     avpriv_packet_list_free(&si->parse_queue);
89     avpriv_packet_list_free(&si->packet_buffer);
90     avpriv_packet_list_free(&si->raw_packet_buffer);
91 
92     si->raw_packet_buffer_size = 0;
93 }
94 
avformat_free_context(AVFormatContext * s)95 void avformat_free_context(AVFormatContext *s)
96 {
97     FFFormatContext *si;
98 
99     if (!s)
100         return;
101     si = ffformatcontext(s);
102 
103     if (s->oformat && s->oformat->deinit && si->initialized)
104         s->oformat->deinit(s);
105 
106     av_opt_free(s);
107     if (s->iformat && s->iformat->priv_class && s->priv_data)
108         av_opt_free(s->priv_data);
109     if (s->oformat && s->oformat->priv_class && s->priv_data)
110         av_opt_free(s->priv_data);
111 
112     for (unsigned i = 0; i < s->nb_streams; i++)
113         ff_free_stream(&s->streams[i]);
114     s->nb_streams = 0;
115 
116     for (unsigned i = 0; i < s->nb_programs; i++) {
117         av_dict_free(&s->programs[i]->metadata);
118         av_freep(&s->programs[i]->stream_index);
119         av_freep(&s->programs[i]);
120     }
121     s->nb_programs = 0;
122 
123     av_freep(&s->programs);
124     av_freep(&s->priv_data);
125     while (s->nb_chapters--) {
126         av_dict_free(&s->chapters[s->nb_chapters]->metadata);
127         av_freep(&s->chapters[s->nb_chapters]);
128     }
129     av_freep(&s->chapters);
130     av_dict_free(&s->metadata);
131     av_dict_free(&si->id3v2_meta);
132     av_packet_free(&si->pkt);
133     av_packet_free(&si->parse_pkt);
134     av_freep(&s->streams);
135     ff_flush_packet_queue(s);
136     av_freep(&s->url);
137     av_free(s);
138 }
139 
av_stream_get_side_data(const AVStream * st,enum AVPacketSideDataType type,size_t * size)140 uint8_t *av_stream_get_side_data(const AVStream *st,
141                                  enum AVPacketSideDataType type, size_t *size)
142 {
143     for (int i = 0; i < st->nb_side_data; i++) {
144         if (st->side_data[i].type == type) {
145             if (size)
146                 *size = st->side_data[i].size;
147             return st->side_data[i].data;
148         }
149     }
150     if (size)
151         *size = 0;
152     return NULL;
153 }
154 
av_stream_add_side_data(AVStream * st,enum AVPacketSideDataType type,uint8_t * data,size_t size)155 int av_stream_add_side_data(AVStream *st, enum AVPacketSideDataType type,
156                             uint8_t *data, size_t size)
157 {
158     AVPacketSideData *sd, *tmp;
159 
160     for (int i = 0; i < st->nb_side_data; i++) {
161         sd = &st->side_data[i];
162 
163         if (sd->type == type) {
164             av_freep(&sd->data);
165             sd->data = data;
166             sd->size = size;
167             return 0;
168         }
169     }
170 
171     if (st->nb_side_data + 1U > FFMIN(INT_MAX, SIZE_MAX / sizeof(*tmp)))
172         return AVERROR(ERANGE);
173 
174     tmp = av_realloc_array(st->side_data, st->nb_side_data + 1, sizeof(*tmp));
175     if (!tmp) {
176         return AVERROR(ENOMEM);
177     }
178 
179     st->side_data = tmp;
180     st->nb_side_data++;
181 
182     sd = &st->side_data[st->nb_side_data - 1];
183     sd->type = type;
184     sd->data = data;
185     sd->size = size;
186 
187     return 0;
188 }
189 
av_stream_new_side_data(AVStream * st,enum AVPacketSideDataType type,size_t size)190 uint8_t *av_stream_new_side_data(AVStream *st, enum AVPacketSideDataType type,
191                                  size_t size)
192 {
193     int ret;
194     uint8_t *data = av_malloc(size);
195 
196     if (!data)
197         return NULL;
198 
199     ret = av_stream_add_side_data(st, type, data, size);
200     if (ret < 0) {
201         av_freep(&data);
202         return NULL;
203     }
204 
205     return data;
206 }
207 
ff_stream_side_data_copy(AVStream * dst,const AVStream * src)208 int ff_stream_side_data_copy(AVStream *dst, const AVStream *src)
209 {
210     /* Free existing side data*/
211     for (int i = 0; i < dst->nb_side_data; i++)
212         av_free(dst->side_data[i].data);
213     av_freep(&dst->side_data);
214     dst->nb_side_data = 0;
215 
216     /* Copy side data if present */
217     if (src->nb_side_data) {
218         dst->side_data = av_calloc(src->nb_side_data,
219                                    sizeof(*dst->side_data));
220         if (!dst->side_data)
221             return AVERROR(ENOMEM);
222         dst->nb_side_data = src->nb_side_data;
223 
224         for (int i = 0; i < src->nb_side_data; i++) {
225             uint8_t *data = av_memdup(src->side_data[i].data,
226                                       src->side_data[i].size);
227             if (!data)
228                 return AVERROR(ENOMEM);
229             dst->side_data[i].type = src->side_data[i].type;
230             dst->side_data[i].size = src->side_data[i].size;
231             dst->side_data[i].data = data;
232         }
233     }
234 
235     return 0;
236 }
237 
av_new_program(AVFormatContext * ac,int id)238 AVProgram *av_new_program(AVFormatContext *ac, int id)
239 {
240     AVProgram *program = NULL;
241     int ret;
242 
243     av_log(ac, AV_LOG_TRACE, "new_program: id=0x%04x\n", id);
244 
245     for (unsigned i = 0; i < ac->nb_programs; i++)
246         if (ac->programs[i]->id == id)
247             program = ac->programs[i];
248 
249     if (!program) {
250         program = av_mallocz(sizeof(*program));
251         if (!program)
252             return NULL;
253         ret = av_dynarray_add_nofree(&ac->programs, &ac->nb_programs, program);
254         if (ret < 0) {
255             av_free(program);
256             return NULL;
257         }
258         program->discard = AVDISCARD_NONE;
259         program->pmt_version = -1;
260         program->id = id;
261         program->pts_wrap_reference = AV_NOPTS_VALUE;
262         program->pts_wrap_behavior = AV_PTS_WRAP_IGNORE;
263         program->start_time =
264         program->end_time   = AV_NOPTS_VALUE;
265     }
266     return program;
267 }
268 
av_program_add_stream_index(AVFormatContext * ac,int progid,unsigned idx)269 void av_program_add_stream_index(AVFormatContext *ac, int progid, unsigned idx)
270 {
271     AVProgram *program = NULL;
272     void *tmp;
273 
274     if (idx >= ac->nb_streams) {
275         av_log(ac, AV_LOG_ERROR, "stream index %d is not valid\n", idx);
276         return;
277     }
278 
279     for (unsigned i = 0; i < ac->nb_programs; i++) {
280         if (ac->programs[i]->id != progid)
281             continue;
282         program = ac->programs[i];
283         for (unsigned j = 0; j < program->nb_stream_indexes; j++)
284             if (program->stream_index[j] == idx)
285                 return;
286 
287         tmp = av_realloc_array(program->stream_index, program->nb_stream_indexes+1, sizeof(unsigned int));
288         if (!tmp)
289             return;
290         program->stream_index = tmp;
291         program->stream_index[program->nb_stream_indexes++] = idx;
292         return;
293     }
294 }
295 
av_find_program_from_stream(AVFormatContext * ic,AVProgram * last,int s)296 AVProgram *av_find_program_from_stream(AVFormatContext *ic, AVProgram *last, int s)
297 {
298     for (unsigned i = 0; i < ic->nb_programs; i++) {
299         if (ic->programs[i] == last) {
300             last = NULL;
301         } else {
302             if (!last)
303                 for (unsigned j = 0; j < ic->programs[i]->nb_stream_indexes; j++)
304                     if (ic->programs[i]->stream_index[j] == s)
305                         return ic->programs[i];
306         }
307     }
308     return NULL;
309 }
310 
av_find_default_stream_index(AVFormatContext * s)311 int av_find_default_stream_index(AVFormatContext *s)
312 {
313     int best_stream = 0;
314     int best_score = INT_MIN;
315 
316     if (s->nb_streams <= 0)
317         return -1;
318     for (unsigned i = 0; i < s->nb_streams; i++) {
319         const AVStream *const st = s->streams[i];
320         const FFStream *const sti = cffstream(st);
321         int score = 0;
322         if (st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO) {
323             if (st->disposition & AV_DISPOSITION_ATTACHED_PIC)
324                 score -= 400;
325             if (st->codecpar->width && st->codecpar->height)
326                 score += 50;
327             score+= 25;
328         }
329         if (st->codecpar->codec_type == AVMEDIA_TYPE_AUDIO) {
330             if (st->codecpar->sample_rate)
331                 score += 50;
332         }
333         if (sti->codec_info_nb_frames)
334             score += 12;
335 
336         if (st->discard != AVDISCARD_ALL)
337             score += 200;
338 
339         if (score > best_score) {
340             best_score = score;
341             best_stream = i;
342         }
343     }
344     return best_stream;
345 }
346 
av_find_best_stream(AVFormatContext * ic,enum AVMediaType type,int wanted_stream_nb,int related_stream,const AVCodec ** decoder_ret,int flags)347 int av_find_best_stream(AVFormatContext *ic, enum AVMediaType type,
348                         int wanted_stream_nb, int related_stream,
349                         const AVCodec **decoder_ret, int flags)
350 {
351     int nb_streams = ic->nb_streams;
352     int ret = AVERROR_STREAM_NOT_FOUND;
353     int best_count = -1, best_multiframe = -1, best_disposition = -1;
354     int count, multiframe, disposition;
355     int64_t best_bitrate = -1;
356     int64_t bitrate;
357     unsigned *program = NULL;
358     const AVCodec *decoder = NULL, *best_decoder = NULL;
359 
360     if (related_stream >= 0 && wanted_stream_nb < 0) {
361         AVProgram *p = av_find_program_from_stream(ic, NULL, related_stream);
362         if (p) {
363             program    = p->stream_index;
364             nb_streams = p->nb_stream_indexes;
365         }
366     }
367     for (unsigned i = 0; i < nb_streams; i++) {
368         int real_stream_index = program ? program[i] : i;
369         AVStream *st          = ic->streams[real_stream_index];
370         AVCodecParameters *par = st->codecpar;
371         if (par->codec_type != type)
372             continue;
373         if (wanted_stream_nb >= 0 && real_stream_index != wanted_stream_nb)
374             continue;
375         if (type == AVMEDIA_TYPE_AUDIO && !(par->ch_layout.nb_channels && par->sample_rate))
376             continue;
377         if (decoder_ret) {
378             decoder = ff_find_decoder(ic, st, par->codec_id);
379             if (!decoder) {
380                 if (ret < 0)
381                     ret = AVERROR_DECODER_NOT_FOUND;
382                 continue;
383             }
384         }
385         disposition = !(st->disposition & (AV_DISPOSITION_HEARING_IMPAIRED | AV_DISPOSITION_VISUAL_IMPAIRED))
386                       + !! (st->disposition & AV_DISPOSITION_DEFAULT);
387         count = ffstream(st)->codec_info_nb_frames;
388         bitrate = par->bit_rate;
389         multiframe = FFMIN(5, count);
390         if ((best_disposition >  disposition) ||
391             (best_disposition == disposition && best_multiframe >  multiframe) ||
392             (best_disposition == disposition && best_multiframe == multiframe && best_bitrate >  bitrate) ||
393             (best_disposition == disposition && best_multiframe == multiframe && best_bitrate == bitrate && best_count >= count))
394             continue;
395         best_disposition = disposition;
396         best_count   = count;
397         best_bitrate = bitrate;
398         best_multiframe = multiframe;
399         ret          = real_stream_index;
400         best_decoder = decoder;
401         if (program && i == nb_streams - 1 && ret < 0) {
402             program    = NULL;
403             nb_streams = ic->nb_streams;
404             /* no related stream found, try again with everything */
405             i = 0;
406         }
407     }
408     if (decoder_ret)
409         *decoder_ret = best_decoder;
410     return ret;
411 }
412 
413 /**
414  * Matches a stream specifier (but ignores requested index).
415  *
416  * @param indexptr set to point to the requested stream index if there is one
417  *
418  * @return <0 on error
419  *         0  if st is NOT a matching stream
420  *         >0 if st is a matching stream
421  */
match_stream_specifier(const AVFormatContext * s,const AVStream * st,const char * spec,const char ** indexptr,const AVProgram ** p)422 static int match_stream_specifier(const AVFormatContext *s, const AVStream *st,
423                                   const char *spec, const char **indexptr,
424                                   const AVProgram **p)
425 {
426     int match = 1;                      /* Stores if the specifier matches so far. */
427     while (*spec) {
428         if (*spec <= '9' && *spec >= '0') { /* opt:index */
429             if (indexptr)
430                 *indexptr = spec;
431             return match;
432         } else if (*spec == 'v' || *spec == 'a' || *spec == 's' || *spec == 'd' ||
433                    *spec == 't' || *spec == 'V') { /* opt:[vasdtV] */
434             enum AVMediaType type;
435             int nopic = 0;
436 
437             switch (*spec++) {
438             case 'v': type = AVMEDIA_TYPE_VIDEO;      break;
439             case 'a': type = AVMEDIA_TYPE_AUDIO;      break;
440             case 's': type = AVMEDIA_TYPE_SUBTITLE;   break;
441             case 'd': type = AVMEDIA_TYPE_DATA;       break;
442             case 't': type = AVMEDIA_TYPE_ATTACHMENT; break;
443             case 'V': type = AVMEDIA_TYPE_VIDEO; nopic = 1; break;
444             default:  av_assert0(0);
445             }
446             if (*spec && *spec++ != ':')         /* If we are not at the end, then another specifier must follow. */
447                 return AVERROR(EINVAL);
448 
449             if (type != st->codecpar->codec_type)
450                 match = 0;
451             if (nopic && (st->disposition & AV_DISPOSITION_ATTACHED_PIC))
452                 match = 0;
453         } else if (*spec == 'p' && *(spec + 1) == ':') {
454             int prog_id;
455             int found = 0;
456             char *endptr;
457             spec += 2;
458             prog_id = strtol(spec, &endptr, 0);
459             /* Disallow empty id and make sure that if we are not at the end, then another specifier must follow. */
460             if (spec == endptr || (*endptr && *endptr++ != ':'))
461                 return AVERROR(EINVAL);
462             spec = endptr;
463             if (match) {
464                 for (unsigned i = 0; i < s->nb_programs; i++) {
465                     if (s->programs[i]->id != prog_id)
466                         continue;
467 
468                     for (unsigned j = 0; j < s->programs[i]->nb_stream_indexes; j++) {
469                         if (st->index == s->programs[i]->stream_index[j]) {
470                             found = 1;
471                             if (p)
472                                 *p = s->programs[i];
473                             i = s->nb_programs;
474                             break;
475                         }
476                     }
477                 }
478             }
479             if (!found)
480                 match = 0;
481         } else if (*spec == '#' ||
482                    (*spec == 'i' && *(spec + 1) == ':')) {
483             int stream_id;
484             char *endptr;
485             spec += 1 + (*spec == 'i');
486             stream_id = strtol(spec, &endptr, 0);
487             if (spec == endptr || *endptr)                /* Disallow empty id and make sure we are at the end. */
488                 return AVERROR(EINVAL);
489             return match && (stream_id == st->id);
490         } else if (*spec == 'm' && *(spec + 1) == ':') {
491             const AVDictionaryEntry *tag;
492             char *key, *val;
493             int ret;
494 
495             if (match) {
496                 spec += 2;
497                 val = strchr(spec, ':');
498 
499                 key = val ? av_strndup(spec, val - spec) : av_strdup(spec);
500                 if (!key)
501                     return AVERROR(ENOMEM);
502 
503                 tag = av_dict_get(st->metadata, key, NULL, 0);
504                 if (tag) {
505                     if (!val || !strcmp(tag->value, val + 1))
506                         ret = 1;
507                     else
508                         ret = 0;
509                 } else
510                     ret = 0;
511 
512                 av_freep(&key);
513             }
514             return match && ret;
515         } else if (*spec == 'u' && *(spec + 1) == '\0') {
516             const AVCodecParameters *par = st->codecpar;
517             int val;
518             switch (par->codec_type) {
519             case AVMEDIA_TYPE_AUDIO:
520                 val = par->sample_rate && par->ch_layout.nb_channels;
521                 if (par->format == AV_SAMPLE_FMT_NONE)
522                     return 0;
523                 break;
524             case AVMEDIA_TYPE_VIDEO:
525                 val = par->width && par->height;
526                 if (par->format == AV_PIX_FMT_NONE)
527                     return 0;
528                 break;
529             case AVMEDIA_TYPE_UNKNOWN:
530                 val = 0;
531                 break;
532             default:
533                 val = 1;
534                 break;
535             }
536             return match && (par->codec_id != AV_CODEC_ID_NONE && val != 0);
537         } else {
538             return AVERROR(EINVAL);
539         }
540     }
541 
542     return match;
543 }
544 
avformat_match_stream_specifier(AVFormatContext * s,AVStream * st,const char * spec)545 int avformat_match_stream_specifier(AVFormatContext *s, AVStream *st,
546                                     const char *spec)
547 {
548     int ret, index;
549     char *endptr;
550     const char *indexptr = NULL;
551     const AVProgram *p = NULL;
552     int nb_streams;
553 
554     ret = match_stream_specifier(s, st, spec, &indexptr, &p);
555     if (ret < 0)
556         goto error;
557 
558     if (!indexptr)
559         return ret;
560 
561     index = strtol(indexptr, &endptr, 0);
562     if (*endptr) {                  /* We can't have anything after the requested index. */
563         ret = AVERROR(EINVAL);
564         goto error;
565     }
566 
567     /* This is not really needed but saves us a loop for simple stream index specifiers. */
568     if (spec == indexptr)
569         return (index == st->index);
570 
571     /* If we requested a matching stream index, we have to ensure st is that. */
572     nb_streams = p ? p->nb_stream_indexes : s->nb_streams;
573     for (int i = 0; i < nb_streams && index >= 0; i++) {
574         const AVStream *candidate = s->streams[p ? p->stream_index[i] : i];
575         ret = match_stream_specifier(s, candidate, spec, NULL, NULL);
576         if (ret < 0)
577             goto error;
578         if (ret > 0 && index-- == 0 && st == candidate)
579             return 1;
580     }
581     return 0;
582 
583 error:
584     if (ret == AVERROR(EINVAL))
585         av_log(s, AV_LOG_ERROR, "Invalid stream specifier: %s.\n", spec);
586     return ret;
587 }
588 
av_guess_sample_aspect_ratio(AVFormatContext * format,AVStream * stream,AVFrame * frame)589 AVRational av_guess_sample_aspect_ratio(AVFormatContext *format, AVStream *stream, AVFrame *frame)
590 {
591     AVRational undef = {0, 1};
592     AVRational stream_sample_aspect_ratio = stream ? stream->sample_aspect_ratio : undef;
593     AVRational codec_sample_aspect_ratio  = stream && stream->codecpar ? stream->codecpar->sample_aspect_ratio : undef;
594     AVRational frame_sample_aspect_ratio  = frame  ? frame->sample_aspect_ratio  : codec_sample_aspect_ratio;
595 
596     av_reduce(&stream_sample_aspect_ratio.num, &stream_sample_aspect_ratio.den,
597                stream_sample_aspect_ratio.num,  stream_sample_aspect_ratio.den, INT_MAX);
598     if (stream_sample_aspect_ratio.num <= 0 || stream_sample_aspect_ratio.den <= 0)
599         stream_sample_aspect_ratio = undef;
600 
601     av_reduce(&frame_sample_aspect_ratio.num, &frame_sample_aspect_ratio.den,
602                frame_sample_aspect_ratio.num,  frame_sample_aspect_ratio.den, INT_MAX);
603     if (frame_sample_aspect_ratio.num <= 0 || frame_sample_aspect_ratio.den <= 0)
604         frame_sample_aspect_ratio = undef;
605 
606     if (stream_sample_aspect_ratio.num)
607         return stream_sample_aspect_ratio;
608     else
609         return frame_sample_aspect_ratio;
610 }
611 
av_guess_frame_rate(AVFormatContext * format,AVStream * st,AVFrame * frame)612 AVRational av_guess_frame_rate(AVFormatContext *format, AVStream *st, AVFrame *frame)
613 {
614     AVRational fr = st->r_frame_rate;
615     AVCodecContext *const avctx = ffstream(st)->avctx;
616     AVRational codec_fr = avctx->framerate;
617     AVRational   avg_fr = st->avg_frame_rate;
618 
619     if (avg_fr.num > 0 && avg_fr.den > 0 && fr.num > 0 && fr.den > 0 &&
620         av_q2d(avg_fr) < 70 && av_q2d(fr) > 210) {
621         fr = avg_fr;
622     }
623 
624     if (avctx->ticks_per_frame > 1) {
625         if (   codec_fr.num > 0 && codec_fr.den > 0 &&
626             (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))
627             fr = codec_fr;
628     }
629 
630     return fr;
631 }
632 
avformat_transfer_internal_stream_timing_info(const AVOutputFormat * ofmt,AVStream * ost,const AVStream * ist,enum AVTimebaseSource copy_tb)633 int avformat_transfer_internal_stream_timing_info(const AVOutputFormat *ofmt,
634                                                   AVStream *ost, const AVStream *ist,
635                                                   enum AVTimebaseSource copy_tb)
636 {
637     const AVCodecContext *const dec_ctx = cffstream(ist)->avctx;
638     AVCodecContext       *const enc_ctx =  ffstream(ost)->avctx;
639 
640     enc_ctx->time_base = ist->time_base;
641     /*
642      * Avi is a special case here because it supports variable fps but
643      * having the fps and timebase differe significantly adds quite some
644      * overhead
645      */
646     if (!strcmp(ofmt->name, "avi")) {
647 #if FF_API_R_FRAME_RATE
648         if (copy_tb == AVFMT_TBCF_AUTO && ist->r_frame_rate.num
649             && av_q2d(ist->r_frame_rate) >= av_q2d(ist->avg_frame_rate)
650             && 0.5/av_q2d(ist->r_frame_rate) > av_q2d(ist->time_base)
651             && 0.5/av_q2d(ist->r_frame_rate) > av_q2d(dec_ctx->time_base)
652             && av_q2d(ist->time_base) < 1.0/500 && av_q2d(dec_ctx->time_base) < 1.0/500
653             || copy_tb == AVFMT_TBCF_R_FRAMERATE) {
654             enc_ctx->time_base.num = ist->r_frame_rate.den;
655             enc_ctx->time_base.den = 2*ist->r_frame_rate.num;
656             enc_ctx->ticks_per_frame = 2;
657         } else
658 #endif
659             if (copy_tb == AVFMT_TBCF_AUTO && av_q2d(dec_ctx->time_base)*dec_ctx->ticks_per_frame > 2*av_q2d(ist->time_base)
660                    && av_q2d(ist->time_base) < 1.0/500
661                    || copy_tb == AVFMT_TBCF_DECODER) {
662             enc_ctx->time_base = dec_ctx->time_base;
663             enc_ctx->time_base.num *= dec_ctx->ticks_per_frame;
664             enc_ctx->time_base.den *= 2;
665             enc_ctx->ticks_per_frame = 2;
666         }
667     } else if (!(ofmt->flags & AVFMT_VARIABLE_FPS)
668                && !av_match_name(ofmt->name, "mov,mp4,3gp,3g2,psp,ipod,ismv,f4v")) {
669         if (copy_tb == AVFMT_TBCF_AUTO && dec_ctx->time_base.den
670             && av_q2d(dec_ctx->time_base)*dec_ctx->ticks_per_frame > av_q2d(ist->time_base)
671             && av_q2d(ist->time_base) < 1.0/500
672             || copy_tb == AVFMT_TBCF_DECODER) {
673             enc_ctx->time_base = dec_ctx->time_base;
674             enc_ctx->time_base.num *= dec_ctx->ticks_per_frame;
675         }
676     }
677 
678     if ((enc_ctx->codec_tag == AV_RL32("tmcd") || ost->codecpar->codec_tag == AV_RL32("tmcd"))
679         && dec_ctx->time_base.num < dec_ctx->time_base.den
680         && dec_ctx->time_base.num > 0
681         && 121LL*dec_ctx->time_base.num > dec_ctx->time_base.den) {
682         enc_ctx->time_base = dec_ctx->time_base;
683     }
684 
685     av_reduce(&enc_ctx->time_base.num, &enc_ctx->time_base.den,
686               enc_ctx->time_base.num, enc_ctx->time_base.den, INT_MAX);
687 
688     return 0;
689 }
690 
av_stream_get_codec_timebase(const AVStream * st)691 AVRational av_stream_get_codec_timebase(const AVStream *st)
692 {
693     // See avformat_transfer_internal_stream_timing_info() TODO.
694     return cffstream(st)->avctx->time_base;
695 }
696 
avpriv_set_pts_info(AVStream * st,int pts_wrap_bits,unsigned int pts_num,unsigned int pts_den)697 void avpriv_set_pts_info(AVStream *st, int pts_wrap_bits,
698                          unsigned int pts_num, unsigned int pts_den)
699 {
700     FFStream *const sti = ffstream(st);
701     AVRational new_tb;
702     if (av_reduce(&new_tb.num, &new_tb.den, pts_num, pts_den, INT_MAX)) {
703         if (new_tb.num != pts_num)
704             av_log(NULL, AV_LOG_DEBUG,
705                    "st:%d removing common factor %d from timebase\n",
706                    st->index, pts_num / new_tb.num);
707     } else
708         av_log(NULL, AV_LOG_WARNING,
709                "st:%d has too large timebase, reducing\n", st->index);
710 
711     if (new_tb.num <= 0 || new_tb.den <= 0) {
712         av_log(NULL, AV_LOG_ERROR,
713                "Ignoring attempt to set invalid timebase %d/%d for st:%d\n",
714                new_tb.num, new_tb.den,
715                st->index);
716         return;
717     }
718     st->time_base     = new_tb;
719     sti->avctx->pkt_timebase = new_tb;
720     st->pts_wrap_bits = pts_wrap_bits;
721 }
722 
ff_find_decoder(AVFormatContext * s,const AVStream * st,enum AVCodecID codec_id)723 const AVCodec *ff_find_decoder(AVFormatContext *s, const AVStream *st,
724                                enum AVCodecID codec_id)
725 {
726     switch (st->codecpar->codec_type) {
727     case AVMEDIA_TYPE_VIDEO:
728         if (s->video_codec)    return s->video_codec;
729         break;
730     case AVMEDIA_TYPE_AUDIO:
731         if (s->audio_codec)    return s->audio_codec;
732         break;
733     case AVMEDIA_TYPE_SUBTITLE:
734         if (s->subtitle_codec) return s->subtitle_codec;
735         break;
736     }
737 
738     return avcodec_find_decoder(codec_id);
739 }
740 
ff_copy_whiteblacklists(AVFormatContext * dst,const AVFormatContext * src)741 int ff_copy_whiteblacklists(AVFormatContext *dst, const AVFormatContext *src)
742 {
743     av_assert0(!dst->codec_whitelist &&
744                !dst->format_whitelist &&
745                !dst->protocol_whitelist &&
746                !dst->protocol_blacklist);
747     dst-> codec_whitelist = av_strdup(src->codec_whitelist);
748     dst->format_whitelist = av_strdup(src->format_whitelist);
749     dst->protocol_whitelist = av_strdup(src->protocol_whitelist);
750     dst->protocol_blacklist = av_strdup(src->protocol_blacklist);
751     if (   (src-> codec_whitelist && !dst-> codec_whitelist)
752         || (src->  format_whitelist && !dst->  format_whitelist)
753         || (src->protocol_whitelist && !dst->protocol_whitelist)
754         || (src->protocol_blacklist && !dst->protocol_blacklist)) {
755         av_log(dst, AV_LOG_ERROR, "Failed to duplicate black/whitelist\n");
756         return AVERROR(ENOMEM);
757     }
758     return 0;
759 }
760 
ff_is_intra_only(enum AVCodecID id)761 int ff_is_intra_only(enum AVCodecID id)
762 {
763     const AVCodecDescriptor *d = avcodec_descriptor_get(id);
764     if (!d)
765         return 0;
766     if ((d->type == AVMEDIA_TYPE_VIDEO || d->type == AVMEDIA_TYPE_AUDIO) &&
767         !(d->props & AV_CODEC_PROP_INTRA_ONLY))
768         return 0;
769     return 1;
770 }
771 
ff_format_set_url(AVFormatContext * s,char * url)772 void ff_format_set_url(AVFormatContext *s, char *url)
773 {
774     av_assert0(url);
775     av_freep(&s->url);
776     s->url = url;
777 }
778 
ff_format_io_close(AVFormatContext * s,AVIOContext ** pb)779 int ff_format_io_close(AVFormatContext *s, AVIOContext **pb)
780 {
781     int ret = 0;
782     if (*pb) {
783         if (s->io_close == ff_format_io_close_default || s->io_close == NULL)
784             ret = s->io_close2(s, *pb);
785         else
786             s->io_close(s, *pb);
787     }
788     *pb = NULL;
789     return ret;
790 }
791