]> git.sesse.net Git - ffmpeg/blob - libavcodec/utils.c
4d736d2e7d2fdb106519b61b5941732b2fa1d815
[ffmpeg] / libavcodec / utils.c
1 /*
2  * utils for libavcodec
3  * Copyright (c) 2001 Fabrice Bellard
4  * Copyright (c) 2002-2004 Michael Niedermayer <michaelni@gmx.at>
5  *
6  * This file is part of FFmpeg.
7  *
8  * FFmpeg is free software; you can redistribute it and/or
9  * modify it under the terms of the GNU Lesser General Public
10  * License as published by the Free Software Foundation; either
11  * version 2.1 of the License, or (at your option) any later version.
12  *
13  * FFmpeg is distributed in the hope that it will be useful,
14  * but WITHOUT ANY WARRANTY; without even the implied warranty of
15  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
16  * Lesser General Public License for more details.
17  *
18  * You should have received a copy of the GNU Lesser General Public
19  * License along with FFmpeg; if not, write to the Free Software
20  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
21  */
22
23 /**
24  * @file
25  * utils.
26  */
27
28 #include "config.h"
29 #include "libavutil/attributes.h"
30 #include "libavutil/avassert.h"
31 #include "libavutil/avstring.h"
32 #include "libavutil/bprint.h"
33 #include "libavutil/channel_layout.h"
34 #include "libavutil/crc.h"
35 #include "libavutil/frame.h"
36 #include "libavutil/hwcontext.h"
37 #include "libavutil/internal.h"
38 #include "libavutil/mathematics.h"
39 #include "libavutil/mem_internal.h"
40 #include "libavutil/pixdesc.h"
41 #include "libavutil/imgutils.h"
42 #include "libavutil/samplefmt.h"
43 #include "libavutil/dict.h"
44 #include "libavutil/thread.h"
45 #include "avcodec.h"
46 #include "decode.h"
47 #include "hwaccel.h"
48 #include "libavutil/opt.h"
49 #include "me_cmp.h"
50 #include "mpegvideo.h"
51 #include "thread.h"
52 #include "frame_thread_encoder.h"
53 #include "internal.h"
54 #include "raw.h"
55 #include "bytestream.h"
56 #include "version.h"
57 #include <stdlib.h>
58 #include <stdarg.h>
59 #include <stdatomic.h>
60 #include <limits.h>
61 #include <float.h>
62 #if CONFIG_ICONV
63 # include <iconv.h>
64 #endif
65
66 #include "libavutil/ffversion.h"
67 const char av_codec_ffversion[] = "FFmpeg version " FFMPEG_VERSION;
68
69 static AVMutex codec_mutex = AV_MUTEX_INITIALIZER;
70
71 void av_fast_padded_malloc(void *ptr, unsigned int *size, size_t min_size)
72 {
73     uint8_t **p = ptr;
74     if (min_size > SIZE_MAX - AV_INPUT_BUFFER_PADDING_SIZE) {
75         av_freep(p);
76         *size = 0;
77         return;
78     }
79     if (!ff_fast_malloc(p, size, min_size + AV_INPUT_BUFFER_PADDING_SIZE, 1))
80         memset(*p + min_size, 0, AV_INPUT_BUFFER_PADDING_SIZE);
81 }
82
83 void av_fast_padded_mallocz(void *ptr, unsigned int *size, size_t min_size)
84 {
85     uint8_t **p = ptr;
86     if (min_size > SIZE_MAX - AV_INPUT_BUFFER_PADDING_SIZE) {
87         av_freep(p);
88         *size = 0;
89         return;
90     }
91     if (!ff_fast_malloc(p, size, min_size + AV_INPUT_BUFFER_PADDING_SIZE, 1))
92         memset(*p, 0, min_size + AV_INPUT_BUFFER_PADDING_SIZE);
93 }
94
95 /* encoder management */
96 static AVCodec *first_avcodec = NULL;
97 static AVCodec **last_avcodec = &first_avcodec;
98
99 AVCodec *av_codec_next(const AVCodec *c)
100 {
101     if (c)
102         return c->next;
103     else
104         return first_avcodec;
105 }
106
107 static av_cold void avcodec_init(void)
108 {
109     static int initialized = 0;
110
111     if (initialized != 0)
112         return;
113     initialized = 1;
114
115     if (CONFIG_ME_CMP)
116         ff_me_cmp_init_static();
117 }
118
119 int av_codec_is_encoder(const AVCodec *codec)
120 {
121     return codec && (codec->encode_sub || codec->encode2 ||codec->send_frame);
122 }
123
124 int av_codec_is_decoder(const AVCodec *codec)
125 {
126     return codec && (codec->decode || codec->receive_frame);
127 }
128
129 static AVMutex codec_register_mutex = AV_MUTEX_INITIALIZER;
130
131 av_cold void avcodec_register(AVCodec *codec)
132 {
133     AVCodec **p;
134     avcodec_init();
135
136     ff_mutex_lock(&codec_register_mutex);
137     p = last_avcodec;
138
139     while (*p)
140         p = &(*p)->next;
141     *p          = codec;
142     codec->next = NULL;
143     last_avcodec = &codec->next;
144
145     ff_mutex_unlock(&codec_register_mutex);
146
147     if (codec->init_static_data)
148         codec->init_static_data(codec);
149 }
150
151 int ff_set_dimensions(AVCodecContext *s, int width, int height)
152 {
153     int ret = av_image_check_size2(width, height, s->max_pixels, AV_PIX_FMT_NONE, 0, s);
154
155     if (ret < 0)
156         width = height = 0;
157
158     s->coded_width  = width;
159     s->coded_height = height;
160     s->width        = AV_CEIL_RSHIFT(width,  s->lowres);
161     s->height       = AV_CEIL_RSHIFT(height, s->lowres);
162
163     return ret;
164 }
165
166 int ff_set_sar(AVCodecContext *avctx, AVRational sar)
167 {
168     int ret = av_image_check_sar(avctx->width, avctx->height, sar);
169
170     if (ret < 0) {
171         av_log(avctx, AV_LOG_WARNING, "ignoring invalid SAR: %d/%d\n",
172                sar.num, sar.den);
173         avctx->sample_aspect_ratio = (AVRational){ 0, 1 };
174         return ret;
175     } else {
176         avctx->sample_aspect_ratio = sar;
177     }
178     return 0;
179 }
180
181 int ff_side_data_update_matrix_encoding(AVFrame *frame,
182                                         enum AVMatrixEncoding matrix_encoding)
183 {
184     AVFrameSideData *side_data;
185     enum AVMatrixEncoding *data;
186
187     side_data = av_frame_get_side_data(frame, AV_FRAME_DATA_MATRIXENCODING);
188     if (!side_data)
189         side_data = av_frame_new_side_data(frame, AV_FRAME_DATA_MATRIXENCODING,
190                                            sizeof(enum AVMatrixEncoding));
191
192     if (!side_data)
193         return AVERROR(ENOMEM);
194
195     data  = (enum AVMatrixEncoding*)side_data->data;
196     *data = matrix_encoding;
197
198     return 0;
199 }
200
201 void avcodec_align_dimensions2(AVCodecContext *s, int *width, int *height,
202                                int linesize_align[AV_NUM_DATA_POINTERS])
203 {
204     int i;
205     int w_align = 1;
206     int h_align = 1;
207     AVPixFmtDescriptor const *desc = av_pix_fmt_desc_get(s->pix_fmt);
208
209     if (desc) {
210         w_align = 1 << desc->log2_chroma_w;
211         h_align = 1 << desc->log2_chroma_h;
212     }
213
214     switch (s->pix_fmt) {
215     case AV_PIX_FMT_YUV420P:
216     case AV_PIX_FMT_YUYV422:
217     case AV_PIX_FMT_YVYU422:
218     case AV_PIX_FMT_UYVY422:
219     case AV_PIX_FMT_YUV422P:
220     case AV_PIX_FMT_YUV440P:
221     case AV_PIX_FMT_YUV444P:
222     case AV_PIX_FMT_GBRP:
223     case AV_PIX_FMT_GBRAP:
224     case AV_PIX_FMT_GRAY8:
225     case AV_PIX_FMT_GRAY16BE:
226     case AV_PIX_FMT_GRAY16LE:
227     case AV_PIX_FMT_YUVJ420P:
228     case AV_PIX_FMT_YUVJ422P:
229     case AV_PIX_FMT_YUVJ440P:
230     case AV_PIX_FMT_YUVJ444P:
231     case AV_PIX_FMT_YUVA420P:
232     case AV_PIX_FMT_YUVA422P:
233     case AV_PIX_FMT_YUVA444P:
234     case AV_PIX_FMT_YUV420P9LE:
235     case AV_PIX_FMT_YUV420P9BE:
236     case AV_PIX_FMT_YUV420P10LE:
237     case AV_PIX_FMT_YUV420P10BE:
238     case AV_PIX_FMT_YUV420P12LE:
239     case AV_PIX_FMT_YUV420P12BE:
240     case AV_PIX_FMT_YUV420P14LE:
241     case AV_PIX_FMT_YUV420P14BE:
242     case AV_PIX_FMT_YUV420P16LE:
243     case AV_PIX_FMT_YUV420P16BE:
244     case AV_PIX_FMT_YUVA420P9LE:
245     case AV_PIX_FMT_YUVA420P9BE:
246     case AV_PIX_FMT_YUVA420P10LE:
247     case AV_PIX_FMT_YUVA420P10BE:
248     case AV_PIX_FMT_YUVA420P16LE:
249     case AV_PIX_FMT_YUVA420P16BE:
250     case AV_PIX_FMT_YUV422P9LE:
251     case AV_PIX_FMT_YUV422P9BE:
252     case AV_PIX_FMT_YUV422P10LE:
253     case AV_PIX_FMT_YUV422P10BE:
254     case AV_PIX_FMT_YUV422P12LE:
255     case AV_PIX_FMT_YUV422P12BE:
256     case AV_PIX_FMT_YUV422P14LE:
257     case AV_PIX_FMT_YUV422P14BE:
258     case AV_PIX_FMT_YUV422P16LE:
259     case AV_PIX_FMT_YUV422P16BE:
260     case AV_PIX_FMT_YUVA422P9LE:
261     case AV_PIX_FMT_YUVA422P9BE:
262     case AV_PIX_FMT_YUVA422P10LE:
263     case AV_PIX_FMT_YUVA422P10BE:
264     case AV_PIX_FMT_YUVA422P16LE:
265     case AV_PIX_FMT_YUVA422P16BE:
266     case AV_PIX_FMT_YUV440P10LE:
267     case AV_PIX_FMT_YUV440P10BE:
268     case AV_PIX_FMT_YUV440P12LE:
269     case AV_PIX_FMT_YUV440P12BE:
270     case AV_PIX_FMT_YUV444P9LE:
271     case AV_PIX_FMT_YUV444P9BE:
272     case AV_PIX_FMT_YUV444P10LE:
273     case AV_PIX_FMT_YUV444P10BE:
274     case AV_PIX_FMT_YUV444P12LE:
275     case AV_PIX_FMT_YUV444P12BE:
276     case AV_PIX_FMT_YUV444P14LE:
277     case AV_PIX_FMT_YUV444P14BE:
278     case AV_PIX_FMT_YUV444P16LE:
279     case AV_PIX_FMT_YUV444P16BE:
280     case AV_PIX_FMT_YUVA444P9LE:
281     case AV_PIX_FMT_YUVA444P9BE:
282     case AV_PIX_FMT_YUVA444P10LE:
283     case AV_PIX_FMT_YUVA444P10BE:
284     case AV_PIX_FMT_YUVA444P16LE:
285     case AV_PIX_FMT_YUVA444P16BE:
286     case AV_PIX_FMT_GBRP9LE:
287     case AV_PIX_FMT_GBRP9BE:
288     case AV_PIX_FMT_GBRP10LE:
289     case AV_PIX_FMT_GBRP10BE:
290     case AV_PIX_FMT_GBRP12LE:
291     case AV_PIX_FMT_GBRP12BE:
292     case AV_PIX_FMT_GBRP14LE:
293     case AV_PIX_FMT_GBRP14BE:
294     case AV_PIX_FMT_GBRP16LE:
295     case AV_PIX_FMT_GBRP16BE:
296     case AV_PIX_FMT_GBRAP12LE:
297     case AV_PIX_FMT_GBRAP12BE:
298     case AV_PIX_FMT_GBRAP16LE:
299     case AV_PIX_FMT_GBRAP16BE:
300         w_align = 16; //FIXME assume 16 pixel per macroblock
301         h_align = 16 * 2; // interlaced needs 2 macroblocks height
302         break;
303     case AV_PIX_FMT_YUV411P:
304     case AV_PIX_FMT_YUVJ411P:
305     case AV_PIX_FMT_UYYVYY411:
306         w_align = 32;
307         h_align = 16 * 2;
308         break;
309     case AV_PIX_FMT_YUV410P:
310         if (s->codec_id == AV_CODEC_ID_SVQ1) {
311             w_align = 64;
312             h_align = 64;
313         }
314         break;
315     case AV_PIX_FMT_RGB555:
316         if (s->codec_id == AV_CODEC_ID_RPZA) {
317             w_align = 4;
318             h_align = 4;
319         }
320         if (s->codec_id == AV_CODEC_ID_INTERPLAY_VIDEO) {
321             w_align = 8;
322             h_align = 8;
323         }
324         break;
325     case AV_PIX_FMT_PAL8:
326     case AV_PIX_FMT_BGR8:
327     case AV_PIX_FMT_RGB8:
328         if (s->codec_id == AV_CODEC_ID_SMC ||
329             s->codec_id == AV_CODEC_ID_CINEPAK) {
330             w_align = 4;
331             h_align = 4;
332         }
333         if (s->codec_id == AV_CODEC_ID_JV ||
334             s->codec_id == AV_CODEC_ID_INTERPLAY_VIDEO) {
335             w_align = 8;
336             h_align = 8;
337         }
338         break;
339     case AV_PIX_FMT_BGR24:
340         if ((s->codec_id == AV_CODEC_ID_MSZH) ||
341             (s->codec_id == AV_CODEC_ID_ZLIB)) {
342             w_align = 4;
343             h_align = 4;
344         }
345         break;
346     case AV_PIX_FMT_RGB24:
347         if (s->codec_id == AV_CODEC_ID_CINEPAK) {
348             w_align = 4;
349             h_align = 4;
350         }
351         break;
352     default:
353         break;
354     }
355
356     if (s->codec_id == AV_CODEC_ID_IFF_ILBM) {
357         w_align = FFMAX(w_align, 8);
358     }
359
360     *width  = FFALIGN(*width, w_align);
361     *height = FFALIGN(*height, h_align);
362     if (s->codec_id == AV_CODEC_ID_H264 || s->lowres) {
363         // some of the optimized chroma MC reads one line too much
364         // which is also done in mpeg decoders with lowres > 0
365         *height += 2;
366
367         // H.264 uses edge emulation for out of frame motion vectors, for this
368         // it requires a temporary area large enough to hold a 21x21 block,
369         // increasing witdth ensure that the temporary area is large enough,
370         // the next rounded up width is 32
371         *width = FFMAX(*width, 32);
372     }
373
374     for (i = 0; i < 4; i++)
375         linesize_align[i] = STRIDE_ALIGN;
376 }
377
378 void avcodec_align_dimensions(AVCodecContext *s, int *width, int *height)
379 {
380     const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(s->pix_fmt);
381     int chroma_shift = desc->log2_chroma_w;
382     int linesize_align[AV_NUM_DATA_POINTERS];
383     int align;
384
385     avcodec_align_dimensions2(s, width, height, linesize_align);
386     align               = FFMAX(linesize_align[0], linesize_align[3]);
387     linesize_align[1] <<= chroma_shift;
388     linesize_align[2] <<= chroma_shift;
389     align               = FFMAX3(align, linesize_align[1], linesize_align[2]);
390     *width              = FFALIGN(*width, align);
391 }
392
393 int avcodec_enum_to_chroma_pos(int *xpos, int *ypos, enum AVChromaLocation pos)
394 {
395     if (pos <= AVCHROMA_LOC_UNSPECIFIED || pos >= AVCHROMA_LOC_NB)
396         return AVERROR(EINVAL);
397     pos--;
398
399     *xpos = (pos&1) * 128;
400     *ypos = ((pos>>1)^(pos<4)) * 128;
401
402     return 0;
403 }
404
405 enum AVChromaLocation avcodec_chroma_pos_to_enum(int xpos, int ypos)
406 {
407     int pos, xout, yout;
408
409     for (pos = AVCHROMA_LOC_UNSPECIFIED + 1; pos < AVCHROMA_LOC_NB; pos++) {
410         if (avcodec_enum_to_chroma_pos(&xout, &yout, pos) == 0 && xout == xpos && yout == ypos)
411             return pos;
412     }
413     return AVCHROMA_LOC_UNSPECIFIED;
414 }
415
416 int avcodec_fill_audio_frame(AVFrame *frame, int nb_channels,
417                              enum AVSampleFormat sample_fmt, const uint8_t *buf,
418                              int buf_size, int align)
419 {
420     int ch, planar, needed_size, ret = 0;
421
422     needed_size = av_samples_get_buffer_size(NULL, nb_channels,
423                                              frame->nb_samples, sample_fmt,
424                                              align);
425     if (buf_size < needed_size)
426         return AVERROR(EINVAL);
427
428     planar = av_sample_fmt_is_planar(sample_fmt);
429     if (planar && nb_channels > AV_NUM_DATA_POINTERS) {
430         if (!(frame->extended_data = av_mallocz_array(nb_channels,
431                                                 sizeof(*frame->extended_data))))
432             return AVERROR(ENOMEM);
433     } else {
434         frame->extended_data = frame->data;
435     }
436
437     if ((ret = av_samples_fill_arrays(frame->extended_data, &frame->linesize[0],
438                                       (uint8_t *)(intptr_t)buf, nb_channels, frame->nb_samples,
439                                       sample_fmt, align)) < 0) {
440         if (frame->extended_data != frame->data)
441             av_freep(&frame->extended_data);
442         return ret;
443     }
444     if (frame->extended_data != frame->data) {
445         for (ch = 0; ch < AV_NUM_DATA_POINTERS; ch++)
446             frame->data[ch] = frame->extended_data[ch];
447     }
448
449     return ret;
450 }
451
452 void ff_color_frame(AVFrame *frame, const int c[4])
453 {
454     const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(frame->format);
455     int p, y, x;
456
457     av_assert0(desc->flags & AV_PIX_FMT_FLAG_PLANAR);
458
459     for (p = 0; p<desc->nb_components; p++) {
460         uint8_t *dst = frame->data[p];
461         int is_chroma = p == 1 || p == 2;
462         int bytes  = is_chroma ? AV_CEIL_RSHIFT(frame->width,  desc->log2_chroma_w) : frame->width;
463         int height = is_chroma ? AV_CEIL_RSHIFT(frame->height, desc->log2_chroma_h) : frame->height;
464         for (y = 0; y < height; y++) {
465             if (desc->comp[0].depth >= 9) {
466                 for (x = 0; x<bytes; x++)
467                     ((uint16_t*)dst)[x] = c[p];
468             }else
469                 memset(dst, c[p], bytes);
470             dst += frame->linesize[p];
471         }
472     }
473 }
474
475 int avcodec_default_execute(AVCodecContext *c, int (*func)(AVCodecContext *c2, void *arg2), void *arg, int *ret, int count, int size)
476 {
477     int i;
478
479     for (i = 0; i < count; i++) {
480         int r = func(c, (char *)arg + i * size);
481         if (ret)
482             ret[i] = r;
483     }
484     emms_c();
485     return 0;
486 }
487
488 int avcodec_default_execute2(AVCodecContext *c, int (*func)(AVCodecContext *c2, void *arg2, int jobnr, int threadnr), void *arg, int *ret, int count)
489 {
490     int i;
491
492     for (i = 0; i < count; i++) {
493         int r = func(c, arg, i, 0);
494         if (ret)
495             ret[i] = r;
496     }
497     emms_c();
498     return 0;
499 }
500
501 enum AVPixelFormat avpriv_find_pix_fmt(const PixelFormatTag *tags,
502                                        unsigned int fourcc)
503 {
504     while (tags->pix_fmt >= 0) {
505         if (tags->fourcc == fourcc)
506             return tags->pix_fmt;
507         tags++;
508     }
509     return AV_PIX_FMT_NONE;
510 }
511
512 #if FF_API_CODEC_GET_SET
513 MAKE_ACCESSORS(AVCodecContext, codec, AVRational, pkt_timebase)
514 MAKE_ACCESSORS(AVCodecContext, codec, const AVCodecDescriptor *, codec_descriptor)
515 MAKE_ACCESSORS(AVCodecContext, codec, int, lowres)
516 MAKE_ACCESSORS(AVCodecContext, codec, int, seek_preroll)
517 MAKE_ACCESSORS(AVCodecContext, codec, uint16_t*, chroma_intra_matrix)
518
519 unsigned av_codec_get_codec_properties(const AVCodecContext *codec)
520 {
521     return codec->properties;
522 }
523
524 int av_codec_get_max_lowres(const AVCodec *codec)
525 {
526     return codec->max_lowres;
527 }
528 #endif
529
530 int avpriv_codec_get_cap_skip_frame_fill_param(const AVCodec *codec){
531     return !!(codec->caps_internal & FF_CODEC_CAP_SKIP_FRAME_FILL_PARAM);
532 }
533
534 static int64_t get_bit_rate(AVCodecContext *ctx)
535 {
536     int64_t bit_rate;
537     int bits_per_sample;
538
539     switch (ctx->codec_type) {
540     case AVMEDIA_TYPE_VIDEO:
541     case AVMEDIA_TYPE_DATA:
542     case AVMEDIA_TYPE_SUBTITLE:
543     case AVMEDIA_TYPE_ATTACHMENT:
544         bit_rate = ctx->bit_rate;
545         break;
546     case AVMEDIA_TYPE_AUDIO:
547         bits_per_sample = av_get_bits_per_sample(ctx->codec_id);
548         bit_rate = bits_per_sample ? ctx->sample_rate * (int64_t)ctx->channels * bits_per_sample : ctx->bit_rate;
549         break;
550     default:
551         bit_rate = 0;
552         break;
553     }
554     return bit_rate;
555 }
556
557
558 static void ff_lock_avcodec(AVCodecContext *log_ctx, const AVCodec *codec)
559 {
560     if (!(codec->caps_internal & FF_CODEC_CAP_INIT_THREADSAFE) && codec->init)
561         ff_mutex_lock(&codec_mutex);
562 }
563
564 static void ff_unlock_avcodec(const AVCodec *codec)
565 {
566     if (!(codec->caps_internal & FF_CODEC_CAP_INIT_THREADSAFE) && codec->init)
567         ff_mutex_unlock(&codec_mutex);
568 }
569
570 int attribute_align_arg ff_codec_open2_recursive(AVCodecContext *avctx, const AVCodec *codec, AVDictionary **options)
571 {
572     int ret = 0;
573
574     ff_unlock_avcodec(codec);
575
576     ret = avcodec_open2(avctx, codec, options);
577
578     ff_lock_avcodec(avctx, codec);
579     return ret;
580 }
581
582 int attribute_align_arg avcodec_open2(AVCodecContext *avctx, const AVCodec *codec, AVDictionary **options)
583 {
584     int ret = 0;
585     AVDictionary *tmp = NULL;
586     const AVPixFmtDescriptor *pixdesc;
587
588     if (avcodec_is_open(avctx))
589         return 0;
590
591     if ((!codec && !avctx->codec)) {
592         av_log(avctx, AV_LOG_ERROR, "No codec provided to avcodec_open2()\n");
593         return AVERROR(EINVAL);
594     }
595     if ((codec && avctx->codec && codec != avctx->codec)) {
596         av_log(avctx, AV_LOG_ERROR, "This AVCodecContext was allocated for %s, "
597                                     "but %s passed to avcodec_open2()\n", avctx->codec->name, codec->name);
598         return AVERROR(EINVAL);
599     }
600     if (!codec)
601         codec = avctx->codec;
602
603     if (avctx->extradata_size < 0 || avctx->extradata_size >= FF_MAX_EXTRADATA_SIZE)
604         return AVERROR(EINVAL);
605
606     if (options)
607         av_dict_copy(&tmp, *options, 0);
608
609     ff_lock_avcodec(avctx, codec);
610
611     avctx->internal = av_mallocz(sizeof(AVCodecInternal));
612     if (!avctx->internal) {
613         ret = AVERROR(ENOMEM);
614         goto end;
615     }
616
617     avctx->internal->pool = av_mallocz(sizeof(*avctx->internal->pool));
618     if (!avctx->internal->pool) {
619         ret = AVERROR(ENOMEM);
620         goto free_and_end;
621     }
622
623     avctx->internal->to_free = av_frame_alloc();
624     if (!avctx->internal->to_free) {
625         ret = AVERROR(ENOMEM);
626         goto free_and_end;
627     }
628
629     avctx->internal->compat_decode_frame = av_frame_alloc();
630     if (!avctx->internal->compat_decode_frame) {
631         ret = AVERROR(ENOMEM);
632         goto free_and_end;
633     }
634
635     avctx->internal->buffer_frame = av_frame_alloc();
636     if (!avctx->internal->buffer_frame) {
637         ret = AVERROR(ENOMEM);
638         goto free_and_end;
639     }
640
641     avctx->internal->buffer_pkt = av_packet_alloc();
642     if (!avctx->internal->buffer_pkt) {
643         ret = AVERROR(ENOMEM);
644         goto free_and_end;
645     }
646
647     avctx->internal->ds.in_pkt = av_packet_alloc();
648     if (!avctx->internal->ds.in_pkt) {
649         ret = AVERROR(ENOMEM);
650         goto free_and_end;
651     }
652
653     avctx->internal->last_pkt_props = av_packet_alloc();
654     if (!avctx->internal->last_pkt_props) {
655         ret = AVERROR(ENOMEM);
656         goto free_and_end;
657     }
658
659     avctx->internal->skip_samples_multiplier = 1;
660
661     if (codec->priv_data_size > 0) {
662         if (!avctx->priv_data) {
663             avctx->priv_data = av_mallocz(codec->priv_data_size);
664             if (!avctx->priv_data) {
665                 ret = AVERROR(ENOMEM);
666                 goto end;
667             }
668             if (codec->priv_class) {
669                 *(const AVClass **)avctx->priv_data = codec->priv_class;
670                 av_opt_set_defaults(avctx->priv_data);
671             }
672         }
673         if (codec->priv_class && (ret = av_opt_set_dict(avctx->priv_data, &tmp)) < 0)
674             goto free_and_end;
675     } else {
676         avctx->priv_data = NULL;
677     }
678     if ((ret = av_opt_set_dict(avctx, &tmp)) < 0)
679         goto free_and_end;
680
681     if (avctx->codec_whitelist && av_match_list(codec->name, avctx->codec_whitelist, ',') <= 0) {
682         av_log(avctx, AV_LOG_ERROR, "Codec (%s) not on whitelist \'%s\'\n", codec->name, avctx->codec_whitelist);
683         ret = AVERROR(EINVAL);
684         goto free_and_end;
685     }
686
687     // only call ff_set_dimensions() for non H.264/VP6F/DXV codecs so as not to overwrite previously setup dimensions
688     if (!(avctx->coded_width && avctx->coded_height && avctx->width && avctx->height &&
689           (avctx->codec_id == AV_CODEC_ID_H264 || avctx->codec_id == AV_CODEC_ID_VP6F || avctx->codec_id == AV_CODEC_ID_DXV))) {
690     if (avctx->coded_width && avctx->coded_height)
691         ret = ff_set_dimensions(avctx, avctx->coded_width, avctx->coded_height);
692     else if (avctx->width && avctx->height)
693         ret = ff_set_dimensions(avctx, avctx->width, avctx->height);
694     if (ret < 0)
695         goto free_and_end;
696     }
697
698     if ((avctx->coded_width || avctx->coded_height || avctx->width || avctx->height)
699         && (  av_image_check_size2(avctx->coded_width, avctx->coded_height, avctx->max_pixels, AV_PIX_FMT_NONE, 0, avctx) < 0
700            || av_image_check_size2(avctx->width,       avctx->height,       avctx->max_pixels, AV_PIX_FMT_NONE, 0, avctx) < 0)) {
701         av_log(avctx, AV_LOG_WARNING, "Ignoring invalid width/height values\n");
702         ff_set_dimensions(avctx, 0, 0);
703     }
704
705     if (avctx->width > 0 && avctx->height > 0) {
706         if (av_image_check_sar(avctx->width, avctx->height,
707                                avctx->sample_aspect_ratio) < 0) {
708             av_log(avctx, AV_LOG_WARNING, "ignoring invalid SAR: %u/%u\n",
709                    avctx->sample_aspect_ratio.num,
710                    avctx->sample_aspect_ratio.den);
711             avctx->sample_aspect_ratio = (AVRational){ 0, 1 };
712         }
713     }
714
715     /* if the decoder init function was already called previously,
716      * free the already allocated subtitle_header before overwriting it */
717     if (av_codec_is_decoder(codec))
718         av_freep(&avctx->subtitle_header);
719
720     if (avctx->channels > FF_SANE_NB_CHANNELS) {
721         ret = AVERROR(EINVAL);
722         goto free_and_end;
723     }
724
725     avctx->codec = codec;
726     if ((avctx->codec_type == AVMEDIA_TYPE_UNKNOWN || avctx->codec_type == codec->type) &&
727         avctx->codec_id == AV_CODEC_ID_NONE) {
728         avctx->codec_type = codec->type;
729         avctx->codec_id   = codec->id;
730     }
731     if (avctx->codec_id != codec->id || (avctx->codec_type != codec->type
732                                          && avctx->codec_type != AVMEDIA_TYPE_ATTACHMENT)) {
733         av_log(avctx, AV_LOG_ERROR, "Codec type or id mismatches\n");
734         ret = AVERROR(EINVAL);
735         goto free_and_end;
736     }
737     avctx->frame_number = 0;
738     avctx->codec_descriptor = avcodec_descriptor_get(avctx->codec_id);
739
740     if ((avctx->codec->capabilities & AV_CODEC_CAP_EXPERIMENTAL) &&
741         avctx->strict_std_compliance > FF_COMPLIANCE_EXPERIMENTAL) {
742         const char *codec_string = av_codec_is_encoder(codec) ? "encoder" : "decoder";
743         AVCodec *codec2;
744         av_log(avctx, AV_LOG_ERROR,
745                "The %s '%s' is experimental but experimental codecs are not enabled, "
746                "add '-strict %d' if you want to use it.\n",
747                codec_string, codec->name, FF_COMPLIANCE_EXPERIMENTAL);
748         codec2 = av_codec_is_encoder(codec) ? avcodec_find_encoder(codec->id) : avcodec_find_decoder(codec->id);
749         if (!(codec2->capabilities & AV_CODEC_CAP_EXPERIMENTAL))
750             av_log(avctx, AV_LOG_ERROR, "Alternatively use the non experimental %s '%s'.\n",
751                 codec_string, codec2->name);
752         ret = AVERROR_EXPERIMENTAL;
753         goto free_and_end;
754     }
755
756     if (avctx->codec_type == AVMEDIA_TYPE_AUDIO &&
757         (!avctx->time_base.num || !avctx->time_base.den)) {
758         avctx->time_base.num = 1;
759         avctx->time_base.den = avctx->sample_rate;
760     }
761
762     if (!HAVE_THREADS)
763         av_log(avctx, AV_LOG_WARNING, "Warning: not compiled with thread support, using thread emulation\n");
764
765     if (CONFIG_FRAME_THREAD_ENCODER && av_codec_is_encoder(avctx->codec)) {
766         ff_unlock_avcodec(codec); //we will instantiate a few encoders thus kick the counter to prevent false detection of a problem
767         ret = ff_frame_thread_encoder_init(avctx, options ? *options : NULL);
768         ff_lock_avcodec(avctx, codec);
769         if (ret < 0)
770             goto free_and_end;
771     }
772
773     if (HAVE_THREADS
774         && !(avctx->internal->frame_thread_encoder && (avctx->active_thread_type&FF_THREAD_FRAME))) {
775         ret = ff_thread_init(avctx);
776         if (ret < 0) {
777             goto free_and_end;
778         }
779     }
780     if (!HAVE_THREADS && !(codec->capabilities & AV_CODEC_CAP_AUTO_THREADS))
781         avctx->thread_count = 1;
782
783     if (avctx->codec->max_lowres < avctx->lowres || avctx->lowres < 0) {
784         av_log(avctx, AV_LOG_WARNING, "The maximum value for lowres supported by the decoder is %d\n",
785                avctx->codec->max_lowres);
786         avctx->lowres = avctx->codec->max_lowres;
787     }
788
789     if (av_codec_is_encoder(avctx->codec)) {
790         int i;
791 #if FF_API_CODED_FRAME
792 FF_DISABLE_DEPRECATION_WARNINGS
793         avctx->coded_frame = av_frame_alloc();
794         if (!avctx->coded_frame) {
795             ret = AVERROR(ENOMEM);
796             goto free_and_end;
797         }
798 FF_ENABLE_DEPRECATION_WARNINGS
799 #endif
800
801         if (avctx->time_base.num <= 0 || avctx->time_base.den <= 0) {
802             av_log(avctx, AV_LOG_ERROR, "The encoder timebase is not set.\n");
803             ret = AVERROR(EINVAL);
804             goto free_and_end;
805         }
806
807         if (avctx->codec->sample_fmts) {
808             for (i = 0; avctx->codec->sample_fmts[i] != AV_SAMPLE_FMT_NONE; i++) {
809                 if (avctx->sample_fmt == avctx->codec->sample_fmts[i])
810                     break;
811                 if (avctx->channels == 1 &&
812                     av_get_planar_sample_fmt(avctx->sample_fmt) ==
813                     av_get_planar_sample_fmt(avctx->codec->sample_fmts[i])) {
814                     avctx->sample_fmt = avctx->codec->sample_fmts[i];
815                     break;
816                 }
817             }
818             if (avctx->codec->sample_fmts[i] == AV_SAMPLE_FMT_NONE) {
819                 char buf[128];
820                 snprintf(buf, sizeof(buf), "%d", avctx->sample_fmt);
821                 av_log(avctx, AV_LOG_ERROR, "Specified sample format %s is invalid or not supported\n",
822                        (char *)av_x_if_null(av_get_sample_fmt_name(avctx->sample_fmt), buf));
823                 ret = AVERROR(EINVAL);
824                 goto free_and_end;
825             }
826         }
827         if (avctx->codec->pix_fmts) {
828             for (i = 0; avctx->codec->pix_fmts[i] != AV_PIX_FMT_NONE; i++)
829                 if (avctx->pix_fmt == avctx->codec->pix_fmts[i])
830                     break;
831             if (avctx->codec->pix_fmts[i] == AV_PIX_FMT_NONE
832                 && !((avctx->codec_id == AV_CODEC_ID_MJPEG || avctx->codec_id == AV_CODEC_ID_LJPEG)
833                      && avctx->strict_std_compliance <= FF_COMPLIANCE_UNOFFICIAL)) {
834                 char buf[128];
835                 snprintf(buf, sizeof(buf), "%d", avctx->pix_fmt);
836                 av_log(avctx, AV_LOG_ERROR, "Specified pixel format %s is invalid or not supported\n",
837                        (char *)av_x_if_null(av_get_pix_fmt_name(avctx->pix_fmt), buf));
838                 ret = AVERROR(EINVAL);
839                 goto free_and_end;
840             }
841             if (avctx->codec->pix_fmts[i] == AV_PIX_FMT_YUVJ420P ||
842                 avctx->codec->pix_fmts[i] == AV_PIX_FMT_YUVJ411P ||
843                 avctx->codec->pix_fmts[i] == AV_PIX_FMT_YUVJ422P ||
844                 avctx->codec->pix_fmts[i] == AV_PIX_FMT_YUVJ440P ||
845                 avctx->codec->pix_fmts[i] == AV_PIX_FMT_YUVJ444P)
846                 avctx->color_range = AVCOL_RANGE_JPEG;
847         }
848         if (avctx->codec->supported_samplerates) {
849             for (i = 0; avctx->codec->supported_samplerates[i] != 0; i++)
850                 if (avctx->sample_rate == avctx->codec->supported_samplerates[i])
851                     break;
852             if (avctx->codec->supported_samplerates[i] == 0) {
853                 av_log(avctx, AV_LOG_ERROR, "Specified sample rate %d is not supported\n",
854                        avctx->sample_rate);
855                 ret = AVERROR(EINVAL);
856                 goto free_and_end;
857             }
858         }
859         if (avctx->sample_rate < 0) {
860             av_log(avctx, AV_LOG_ERROR, "Specified sample rate %d is not supported\n",
861                     avctx->sample_rate);
862             ret = AVERROR(EINVAL);
863             goto free_and_end;
864         }
865         if (avctx->codec->channel_layouts) {
866             if (!avctx->channel_layout) {
867                 av_log(avctx, AV_LOG_WARNING, "Channel layout not specified\n");
868             } else {
869                 for (i = 0; avctx->codec->channel_layouts[i] != 0; i++)
870                     if (avctx->channel_layout == avctx->codec->channel_layouts[i])
871                         break;
872                 if (avctx->codec->channel_layouts[i] == 0) {
873                     char buf[512];
874                     av_get_channel_layout_string(buf, sizeof(buf), -1, avctx->channel_layout);
875                     av_log(avctx, AV_LOG_ERROR, "Specified channel layout '%s' is not supported\n", buf);
876                     ret = AVERROR(EINVAL);
877                     goto free_and_end;
878                 }
879             }
880         }
881         if (avctx->channel_layout && avctx->channels) {
882             int channels = av_get_channel_layout_nb_channels(avctx->channel_layout);
883             if (channels != avctx->channels) {
884                 char buf[512];
885                 av_get_channel_layout_string(buf, sizeof(buf), -1, avctx->channel_layout);
886                 av_log(avctx, AV_LOG_ERROR,
887                        "Channel layout '%s' with %d channels does not match number of specified channels %d\n",
888                        buf, channels, avctx->channels);
889                 ret = AVERROR(EINVAL);
890                 goto free_and_end;
891             }
892         } else if (avctx->channel_layout) {
893             avctx->channels = av_get_channel_layout_nb_channels(avctx->channel_layout);
894         }
895         if (avctx->channels < 0) {
896             av_log(avctx, AV_LOG_ERROR, "Specified number of channels %d is not supported\n",
897                     avctx->channels);
898             ret = AVERROR(EINVAL);
899             goto free_and_end;
900         }
901         if(avctx->codec_type == AVMEDIA_TYPE_VIDEO) {
902             pixdesc = av_pix_fmt_desc_get(avctx->pix_fmt);
903             if (    avctx->bits_per_raw_sample < 0
904                 || (avctx->bits_per_raw_sample > 8 && pixdesc->comp[0].depth <= 8)) {
905                 av_log(avctx, AV_LOG_WARNING, "Specified bit depth %d not possible with the specified pixel formats depth %d\n",
906                     avctx->bits_per_raw_sample, pixdesc->comp[0].depth);
907                 avctx->bits_per_raw_sample = pixdesc->comp[0].depth;
908             }
909             if (avctx->width <= 0 || avctx->height <= 0) {
910                 av_log(avctx, AV_LOG_ERROR, "dimensions not set\n");
911                 ret = AVERROR(EINVAL);
912                 goto free_and_end;
913             }
914         }
915         if (   (avctx->codec_type == AVMEDIA_TYPE_VIDEO || avctx->codec_type == AVMEDIA_TYPE_AUDIO)
916             && avctx->bit_rate>0 && avctx->bit_rate<1000) {
917             av_log(avctx, AV_LOG_WARNING, "Bitrate %"PRId64" is extremely low, maybe you mean %"PRId64"k\n", avctx->bit_rate, avctx->bit_rate);
918         }
919
920         if (!avctx->rc_initial_buffer_occupancy)
921             avctx->rc_initial_buffer_occupancy = avctx->rc_buffer_size * 3LL / 4;
922
923         if (avctx->ticks_per_frame && avctx->time_base.num &&
924             avctx->ticks_per_frame > INT_MAX / avctx->time_base.num) {
925             av_log(avctx, AV_LOG_ERROR,
926                    "ticks_per_frame %d too large for the timebase %d/%d.",
927                    avctx->ticks_per_frame,
928                    avctx->time_base.num,
929                    avctx->time_base.den);
930             goto free_and_end;
931         }
932
933         if (avctx->hw_frames_ctx) {
934             AVHWFramesContext *frames_ctx = (AVHWFramesContext*)avctx->hw_frames_ctx->data;
935             if (frames_ctx->format != avctx->pix_fmt) {
936                 av_log(avctx, AV_LOG_ERROR,
937                        "Mismatching AVCodecContext.pix_fmt and AVHWFramesContext.format\n");
938                 ret = AVERROR(EINVAL);
939                 goto free_and_end;
940             }
941             if (avctx->sw_pix_fmt != AV_PIX_FMT_NONE &&
942                 avctx->sw_pix_fmt != frames_ctx->sw_format) {
943                 av_log(avctx, AV_LOG_ERROR,
944                        "Mismatching AVCodecContext.sw_pix_fmt (%s) "
945                        "and AVHWFramesContext.sw_format (%s)\n",
946                        av_get_pix_fmt_name(avctx->sw_pix_fmt),
947                        av_get_pix_fmt_name(frames_ctx->sw_format));
948                 ret = AVERROR(EINVAL);
949                 goto free_and_end;
950             }
951             avctx->sw_pix_fmt = frames_ctx->sw_format;
952         }
953     }
954
955     avctx->pts_correction_num_faulty_pts =
956     avctx->pts_correction_num_faulty_dts = 0;
957     avctx->pts_correction_last_pts =
958     avctx->pts_correction_last_dts = INT64_MIN;
959
960     if (   !CONFIG_GRAY && avctx->flags & AV_CODEC_FLAG_GRAY
961         && avctx->codec_descriptor->type == AVMEDIA_TYPE_VIDEO)
962         av_log(avctx, AV_LOG_WARNING,
963                "gray decoding requested but not enabled at configuration time\n");
964
965     if (   avctx->codec->init && (!(avctx->active_thread_type&FF_THREAD_FRAME)
966         || avctx->internal->frame_thread_encoder)) {
967         ret = avctx->codec->init(avctx);
968         if (ret < 0) {
969             goto free_and_end;
970         }
971     }
972
973     ret=0;
974
975     if (av_codec_is_decoder(avctx->codec)) {
976         if (!avctx->bit_rate)
977             avctx->bit_rate = get_bit_rate(avctx);
978         /* validate channel layout from the decoder */
979         if (avctx->channel_layout) {
980             int channels = av_get_channel_layout_nb_channels(avctx->channel_layout);
981             if (!avctx->channels)
982                 avctx->channels = channels;
983             else if (channels != avctx->channels) {
984                 char buf[512];
985                 av_get_channel_layout_string(buf, sizeof(buf), -1, avctx->channel_layout);
986                 av_log(avctx, AV_LOG_WARNING,
987                        "Channel layout '%s' with %d channels does not match specified number of channels %d: "
988                        "ignoring specified channel layout\n",
989                        buf, channels, avctx->channels);
990                 avctx->channel_layout = 0;
991             }
992         }
993         if (avctx->channels && avctx->channels < 0 ||
994             avctx->channels > FF_SANE_NB_CHANNELS) {
995             ret = AVERROR(EINVAL);
996             goto free_and_end;
997         }
998         if (avctx->sub_charenc) {
999             if (avctx->codec_type != AVMEDIA_TYPE_SUBTITLE) {
1000                 av_log(avctx, AV_LOG_ERROR, "Character encoding is only "
1001                        "supported with subtitles codecs\n");
1002                 ret = AVERROR(EINVAL);
1003                 goto free_and_end;
1004             } else if (avctx->codec_descriptor->props & AV_CODEC_PROP_BITMAP_SUB) {
1005                 av_log(avctx, AV_LOG_WARNING, "Codec '%s' is bitmap-based, "
1006                        "subtitles character encoding will be ignored\n",
1007                        avctx->codec_descriptor->name);
1008                 avctx->sub_charenc_mode = FF_SUB_CHARENC_MODE_DO_NOTHING;
1009             } else {
1010                 /* input character encoding is set for a text based subtitle
1011                  * codec at this point */
1012                 if (avctx->sub_charenc_mode == FF_SUB_CHARENC_MODE_AUTOMATIC)
1013                     avctx->sub_charenc_mode = FF_SUB_CHARENC_MODE_PRE_DECODER;
1014
1015                 if (avctx->sub_charenc_mode == FF_SUB_CHARENC_MODE_PRE_DECODER) {
1016 #if CONFIG_ICONV
1017                     iconv_t cd = iconv_open("UTF-8", avctx->sub_charenc);
1018                     if (cd == (iconv_t)-1) {
1019                         ret = AVERROR(errno);
1020                         av_log(avctx, AV_LOG_ERROR, "Unable to open iconv context "
1021                                "with input character encoding \"%s\"\n", avctx->sub_charenc);
1022                         goto free_and_end;
1023                     }
1024                     iconv_close(cd);
1025 #else
1026                     av_log(avctx, AV_LOG_ERROR, "Character encoding subtitles "
1027                            "conversion needs a libavcodec built with iconv support "
1028                            "for this codec\n");
1029                     ret = AVERROR(ENOSYS);
1030                     goto free_and_end;
1031 #endif
1032                 }
1033             }
1034         }
1035
1036 #if FF_API_AVCTX_TIMEBASE
1037         if (avctx->framerate.num > 0 && avctx->framerate.den > 0)
1038             avctx->time_base = av_inv_q(av_mul_q(avctx->framerate, (AVRational){avctx->ticks_per_frame, 1}));
1039 #endif
1040     }
1041     if (codec->priv_data_size > 0 && avctx->priv_data && codec->priv_class) {
1042         av_assert0(*(const AVClass **)avctx->priv_data == codec->priv_class);
1043     }
1044
1045 end:
1046     ff_unlock_avcodec(codec);
1047     if (options) {
1048         av_dict_free(options);
1049         *options = tmp;
1050     }
1051
1052     return ret;
1053 free_and_end:
1054     if (avctx->codec &&
1055         (avctx->codec->caps_internal & FF_CODEC_CAP_INIT_CLEANUP))
1056         avctx->codec->close(avctx);
1057
1058     if (codec->priv_class && codec->priv_data_size)
1059         av_opt_free(avctx->priv_data);
1060     av_opt_free(avctx);
1061
1062 #if FF_API_CODED_FRAME
1063 FF_DISABLE_DEPRECATION_WARNINGS
1064     av_frame_free(&avctx->coded_frame);
1065 FF_ENABLE_DEPRECATION_WARNINGS
1066 #endif
1067
1068     av_dict_free(&tmp);
1069     av_freep(&avctx->priv_data);
1070     if (avctx->internal) {
1071         av_frame_free(&avctx->internal->to_free);
1072         av_frame_free(&avctx->internal->compat_decode_frame);
1073         av_frame_free(&avctx->internal->buffer_frame);
1074         av_packet_free(&avctx->internal->buffer_pkt);
1075         av_packet_free(&avctx->internal->last_pkt_props);
1076
1077         av_packet_free(&avctx->internal->ds.in_pkt);
1078
1079         av_freep(&avctx->internal->pool);
1080     }
1081     av_freep(&avctx->internal);
1082     avctx->codec = NULL;
1083     goto end;
1084 }
1085
1086 void avsubtitle_free(AVSubtitle *sub)
1087 {
1088     int i;
1089
1090     for (i = 0; i < sub->num_rects; i++) {
1091         av_freep(&sub->rects[i]->data[0]);
1092         av_freep(&sub->rects[i]->data[1]);
1093         av_freep(&sub->rects[i]->data[2]);
1094         av_freep(&sub->rects[i]->data[3]);
1095         av_freep(&sub->rects[i]->text);
1096         av_freep(&sub->rects[i]->ass);
1097         av_freep(&sub->rects[i]);
1098     }
1099
1100     av_freep(&sub->rects);
1101
1102     memset(sub, 0, sizeof(AVSubtitle));
1103 }
1104
1105 av_cold int avcodec_close(AVCodecContext *avctx)
1106 {
1107     int i;
1108
1109     if (!avctx)
1110         return 0;
1111
1112     if (avcodec_is_open(avctx)) {
1113         FramePool *pool = avctx->internal->pool;
1114         if (CONFIG_FRAME_THREAD_ENCODER &&
1115             avctx->internal->frame_thread_encoder && avctx->thread_count > 1) {
1116             ff_frame_thread_encoder_free(avctx);
1117         }
1118         if (HAVE_THREADS && avctx->internal->thread_ctx)
1119             ff_thread_free(avctx);
1120         if (avctx->codec && avctx->codec->close)
1121             avctx->codec->close(avctx);
1122         avctx->internal->byte_buffer_size = 0;
1123         av_freep(&avctx->internal->byte_buffer);
1124         av_frame_free(&avctx->internal->to_free);
1125         av_frame_free(&avctx->internal->compat_decode_frame);
1126         av_frame_free(&avctx->internal->buffer_frame);
1127         av_packet_free(&avctx->internal->buffer_pkt);
1128         av_packet_free(&avctx->internal->last_pkt_props);
1129
1130         av_packet_free(&avctx->internal->ds.in_pkt);
1131
1132         for (i = 0; i < FF_ARRAY_ELEMS(pool->pools); i++)
1133             av_buffer_pool_uninit(&pool->pools[i]);
1134         av_freep(&avctx->internal->pool);
1135
1136         if (avctx->hwaccel && avctx->hwaccel->uninit)
1137             avctx->hwaccel->uninit(avctx);
1138         av_freep(&avctx->internal->hwaccel_priv_data);
1139
1140         ff_decode_bsfs_uninit(avctx);
1141
1142         av_freep(&avctx->internal);
1143     }
1144
1145     for (i = 0; i < avctx->nb_coded_side_data; i++)
1146         av_freep(&avctx->coded_side_data[i].data);
1147     av_freep(&avctx->coded_side_data);
1148     avctx->nb_coded_side_data = 0;
1149
1150     av_buffer_unref(&avctx->hw_frames_ctx);
1151     av_buffer_unref(&avctx->hw_device_ctx);
1152
1153     if (avctx->priv_data && avctx->codec && avctx->codec->priv_class)
1154         av_opt_free(avctx->priv_data);
1155     av_opt_free(avctx);
1156     av_freep(&avctx->priv_data);
1157     if (av_codec_is_encoder(avctx->codec)) {
1158         av_freep(&avctx->extradata);
1159 #if FF_API_CODED_FRAME
1160 FF_DISABLE_DEPRECATION_WARNINGS
1161         av_frame_free(&avctx->coded_frame);
1162 FF_ENABLE_DEPRECATION_WARNINGS
1163 #endif
1164     }
1165     avctx->codec = NULL;
1166     avctx->active_thread_type = 0;
1167
1168     return 0;
1169 }
1170
1171 static enum AVCodecID remap_deprecated_codec_id(enum AVCodecID id)
1172 {
1173     switch(id){
1174         //This is for future deprecatec codec ids, its empty since
1175         //last major bump but will fill up again over time, please don't remove it
1176         default                                         : return id;
1177     }
1178 }
1179
1180 static AVCodec *find_encdec(enum AVCodecID id, int encoder)
1181 {
1182     AVCodec *p, *experimental = NULL;
1183     p = first_avcodec;
1184     id= remap_deprecated_codec_id(id);
1185     while (p) {
1186         if ((encoder ? av_codec_is_encoder(p) : av_codec_is_decoder(p)) &&
1187             p->id == id) {
1188             if (p->capabilities & AV_CODEC_CAP_EXPERIMENTAL && !experimental) {
1189                 experimental = p;
1190             } else
1191                 return p;
1192         }
1193         p = p->next;
1194     }
1195     return experimental;
1196 }
1197
1198 AVCodec *avcodec_find_encoder(enum AVCodecID id)
1199 {
1200     return find_encdec(id, 1);
1201 }
1202
1203 AVCodec *avcodec_find_encoder_by_name(const char *name)
1204 {
1205     AVCodec *p;
1206     if (!name)
1207         return NULL;
1208     p = first_avcodec;
1209     while (p) {
1210         if (av_codec_is_encoder(p) && strcmp(name, p->name) == 0)
1211             return p;
1212         p = p->next;
1213     }
1214     return NULL;
1215 }
1216
1217 AVCodec *avcodec_find_decoder(enum AVCodecID id)
1218 {
1219     return find_encdec(id, 0);
1220 }
1221
1222 AVCodec *avcodec_find_decoder_by_name(const char *name)
1223 {
1224     AVCodec *p;
1225     if (!name)
1226         return NULL;
1227     p = first_avcodec;
1228     while (p) {
1229         if (av_codec_is_decoder(p) && strcmp(name, p->name) == 0)
1230             return p;
1231         p = p->next;
1232     }
1233     return NULL;
1234 }
1235
1236 const char *avcodec_get_name(enum AVCodecID id)
1237 {
1238     const AVCodecDescriptor *cd;
1239     AVCodec *codec;
1240
1241     if (id == AV_CODEC_ID_NONE)
1242         return "none";
1243     cd = avcodec_descriptor_get(id);
1244     if (cd)
1245         return cd->name;
1246     av_log(NULL, AV_LOG_WARNING, "Codec 0x%x is not in the full list.\n", id);
1247     codec = avcodec_find_decoder(id);
1248     if (codec)
1249         return codec->name;
1250     codec = avcodec_find_encoder(id);
1251     if (codec)
1252         return codec->name;
1253     return "unknown_codec";
1254 }
1255
1256 size_t av_get_codec_tag_string(char *buf, size_t buf_size, unsigned int codec_tag)
1257 {
1258     int i, len, ret = 0;
1259
1260 #define TAG_PRINT(x)                                              \
1261     (((x) >= '0' && (x) <= '9') ||                                \
1262      ((x) >= 'a' && (x) <= 'z') || ((x) >= 'A' && (x) <= 'Z') ||  \
1263      ((x) == '.' || (x) == ' ' || (x) == '-' || (x) == '_'))
1264
1265     for (i = 0; i < 4; i++) {
1266         len = snprintf(buf, buf_size,
1267                        TAG_PRINT(codec_tag & 0xFF) ? "%c" : "[%d]", codec_tag & 0xFF);
1268         buf        += len;
1269         buf_size    = buf_size > len ? buf_size - len : 0;
1270         ret        += len;
1271         codec_tag >>= 8;
1272     }
1273     return ret;
1274 }
1275
1276 void avcodec_string(char *buf, int buf_size, AVCodecContext *enc, int encode)
1277 {
1278     const char *codec_type;
1279     const char *codec_name;
1280     const char *profile = NULL;
1281     int64_t bitrate;
1282     int new_line = 0;
1283     AVRational display_aspect_ratio;
1284     const char *separator = enc->dump_separator ? (const char *)enc->dump_separator : ", ";
1285
1286     if (!buf || buf_size <= 0)
1287         return;
1288     codec_type = av_get_media_type_string(enc->codec_type);
1289     codec_name = avcodec_get_name(enc->codec_id);
1290     profile = avcodec_profile_name(enc->codec_id, enc->profile);
1291
1292     snprintf(buf, buf_size, "%s: %s", codec_type ? codec_type : "unknown",
1293              codec_name);
1294     buf[0] ^= 'a' ^ 'A'; /* first letter in uppercase */
1295
1296     if (enc->codec && strcmp(enc->codec->name, codec_name))
1297         snprintf(buf + strlen(buf), buf_size - strlen(buf), " (%s)", enc->codec->name);
1298
1299     if (profile)
1300         snprintf(buf + strlen(buf), buf_size - strlen(buf), " (%s)", profile);
1301     if (   enc->codec_type == AVMEDIA_TYPE_VIDEO
1302         && av_log_get_level() >= AV_LOG_VERBOSE
1303         && enc->refs)
1304         snprintf(buf + strlen(buf), buf_size - strlen(buf),
1305                  ", %d reference frame%s",
1306                  enc->refs, enc->refs > 1 ? "s" : "");
1307
1308     if (enc->codec_tag)
1309         snprintf(buf + strlen(buf), buf_size - strlen(buf), " (%s / 0x%04X)",
1310                  av_fourcc2str(enc->codec_tag), enc->codec_tag);
1311
1312     switch (enc->codec_type) {
1313     case AVMEDIA_TYPE_VIDEO:
1314         {
1315             char detail[256] = "(";
1316
1317             av_strlcat(buf, separator, buf_size);
1318
1319             snprintf(buf + strlen(buf), buf_size - strlen(buf),
1320                  "%s", enc->pix_fmt == AV_PIX_FMT_NONE ? "none" :
1321                      av_get_pix_fmt_name(enc->pix_fmt));
1322             if (enc->bits_per_raw_sample && enc->pix_fmt != AV_PIX_FMT_NONE &&
1323                 enc->bits_per_raw_sample < av_pix_fmt_desc_get(enc->pix_fmt)->comp[0].depth)
1324                 av_strlcatf(detail, sizeof(detail), "%d bpc, ", enc->bits_per_raw_sample);
1325             if (enc->color_range != AVCOL_RANGE_UNSPECIFIED)
1326                 av_strlcatf(detail, sizeof(detail), "%s, ",
1327                             av_color_range_name(enc->color_range));
1328
1329             if (enc->colorspace != AVCOL_SPC_UNSPECIFIED ||
1330                 enc->color_primaries != AVCOL_PRI_UNSPECIFIED ||
1331                 enc->color_trc != AVCOL_TRC_UNSPECIFIED) {
1332                 if (enc->colorspace != (int)enc->color_primaries ||
1333                     enc->colorspace != (int)enc->color_trc) {
1334                     new_line = 1;
1335                     av_strlcatf(detail, sizeof(detail), "%s/%s/%s, ",
1336                                 av_color_space_name(enc->colorspace),
1337                                 av_color_primaries_name(enc->color_primaries),
1338                                 av_color_transfer_name(enc->color_trc));
1339                 } else
1340                     av_strlcatf(detail, sizeof(detail), "%s, ",
1341                                 av_get_colorspace_name(enc->colorspace));
1342             }
1343
1344             if (enc->field_order != AV_FIELD_UNKNOWN) {
1345                 const char *field_order = "progressive";
1346                 if (enc->field_order == AV_FIELD_TT)
1347                     field_order = "top first";
1348                 else if (enc->field_order == AV_FIELD_BB)
1349                     field_order = "bottom first";
1350                 else if (enc->field_order == AV_FIELD_TB)
1351                     field_order = "top coded first (swapped)";
1352                 else if (enc->field_order == AV_FIELD_BT)
1353                     field_order = "bottom coded first (swapped)";
1354
1355                 av_strlcatf(detail, sizeof(detail), "%s, ", field_order);
1356             }
1357
1358             if (av_log_get_level() >= AV_LOG_VERBOSE &&
1359                 enc->chroma_sample_location != AVCHROMA_LOC_UNSPECIFIED)
1360                 av_strlcatf(detail, sizeof(detail), "%s, ",
1361                             av_chroma_location_name(enc->chroma_sample_location));
1362
1363             if (strlen(detail) > 1) {
1364                 detail[strlen(detail) - 2] = 0;
1365                 av_strlcatf(buf, buf_size, "%s)", detail);
1366             }
1367         }
1368
1369         if (enc->width) {
1370             av_strlcat(buf, new_line ? separator : ", ", buf_size);
1371
1372             snprintf(buf + strlen(buf), buf_size - strlen(buf),
1373                      "%dx%d",
1374                      enc->width, enc->height);
1375
1376             if (av_log_get_level() >= AV_LOG_VERBOSE &&
1377                 (enc->width != enc->coded_width ||
1378                  enc->height != enc->coded_height))
1379                 snprintf(buf + strlen(buf), buf_size - strlen(buf),
1380                          " (%dx%d)", enc->coded_width, enc->coded_height);
1381
1382             if (enc->sample_aspect_ratio.num) {
1383                 av_reduce(&display_aspect_ratio.num, &display_aspect_ratio.den,
1384                           enc->width * (int64_t)enc->sample_aspect_ratio.num,
1385                           enc->height * (int64_t)enc->sample_aspect_ratio.den,
1386                           1024 * 1024);
1387                 snprintf(buf + strlen(buf), buf_size - strlen(buf),
1388                          " [SAR %d:%d DAR %d:%d]",
1389                          enc->sample_aspect_ratio.num, enc->sample_aspect_ratio.den,
1390                          display_aspect_ratio.num, display_aspect_ratio.den);
1391             }
1392             if (av_log_get_level() >= AV_LOG_DEBUG) {
1393                 int g = av_gcd(enc->time_base.num, enc->time_base.den);
1394                 snprintf(buf + strlen(buf), buf_size - strlen(buf),
1395                          ", %d/%d",
1396                          enc->time_base.num / g, enc->time_base.den / g);
1397             }
1398         }
1399         if (encode) {
1400             snprintf(buf + strlen(buf), buf_size - strlen(buf),
1401                      ", q=%d-%d", enc->qmin, enc->qmax);
1402         } else {
1403             if (enc->properties & FF_CODEC_PROPERTY_CLOSED_CAPTIONS)
1404                 snprintf(buf + strlen(buf), buf_size - strlen(buf),
1405                          ", Closed Captions");
1406             if (enc->properties & FF_CODEC_PROPERTY_LOSSLESS)
1407                 snprintf(buf + strlen(buf), buf_size - strlen(buf),
1408                          ", lossless");
1409         }
1410         break;
1411     case AVMEDIA_TYPE_AUDIO:
1412         av_strlcat(buf, separator, buf_size);
1413
1414         if (enc->sample_rate) {
1415             snprintf(buf + strlen(buf), buf_size - strlen(buf),
1416                      "%d Hz, ", enc->sample_rate);
1417         }
1418         av_get_channel_layout_string(buf + strlen(buf), buf_size - strlen(buf), enc->channels, enc->channel_layout);
1419         if (enc->sample_fmt != AV_SAMPLE_FMT_NONE) {
1420             snprintf(buf + strlen(buf), buf_size - strlen(buf),
1421                      ", %s", av_get_sample_fmt_name(enc->sample_fmt));
1422         }
1423         if (   enc->bits_per_raw_sample > 0
1424             && enc->bits_per_raw_sample != av_get_bytes_per_sample(enc->sample_fmt) * 8)
1425             snprintf(buf + strlen(buf), buf_size - strlen(buf),
1426                      " (%d bit)", enc->bits_per_raw_sample);
1427         if (av_log_get_level() >= AV_LOG_VERBOSE) {
1428             if (enc->initial_padding)
1429                 snprintf(buf + strlen(buf), buf_size - strlen(buf),
1430                          ", delay %d", enc->initial_padding);
1431             if (enc->trailing_padding)
1432                 snprintf(buf + strlen(buf), buf_size - strlen(buf),
1433                          ", padding %d", enc->trailing_padding);
1434         }
1435         break;
1436     case AVMEDIA_TYPE_DATA:
1437         if (av_log_get_level() >= AV_LOG_DEBUG) {
1438             int g = av_gcd(enc->time_base.num, enc->time_base.den);
1439             if (g)
1440                 snprintf(buf + strlen(buf), buf_size - strlen(buf),
1441                          ", %d/%d",
1442                          enc->time_base.num / g, enc->time_base.den / g);
1443         }
1444         break;
1445     case AVMEDIA_TYPE_SUBTITLE:
1446         if (enc->width)
1447             snprintf(buf + strlen(buf), buf_size - strlen(buf),
1448                      ", %dx%d", enc->width, enc->height);
1449         break;
1450     default:
1451         return;
1452     }
1453     if (encode) {
1454         if (enc->flags & AV_CODEC_FLAG_PASS1)
1455             snprintf(buf + strlen(buf), buf_size - strlen(buf),
1456                      ", pass 1");
1457         if (enc->flags & AV_CODEC_FLAG_PASS2)
1458             snprintf(buf + strlen(buf), buf_size - strlen(buf),
1459                      ", pass 2");
1460     }
1461     bitrate = get_bit_rate(enc);
1462     if (bitrate != 0) {
1463         snprintf(buf + strlen(buf), buf_size - strlen(buf),
1464                  ", %"PRId64" kb/s", bitrate / 1000);
1465     } else if (enc->rc_max_rate > 0) {
1466         snprintf(buf + strlen(buf), buf_size - strlen(buf),
1467                  ", max. %"PRId64" kb/s", enc->rc_max_rate / 1000);
1468     }
1469 }
1470
1471 const char *av_get_profile_name(const AVCodec *codec, int profile)
1472 {
1473     const AVProfile *p;
1474     if (profile == FF_PROFILE_UNKNOWN || !codec->profiles)
1475         return NULL;
1476
1477     for (p = codec->profiles; p->profile != FF_PROFILE_UNKNOWN; p++)
1478         if (p->profile == profile)
1479             return p->name;
1480
1481     return NULL;
1482 }
1483
1484 const char *avcodec_profile_name(enum AVCodecID codec_id, int profile)
1485 {
1486     const AVCodecDescriptor *desc = avcodec_descriptor_get(codec_id);
1487     const AVProfile *p;
1488
1489     if (profile == FF_PROFILE_UNKNOWN || !desc || !desc->profiles)
1490         return NULL;
1491
1492     for (p = desc->profiles; p->profile != FF_PROFILE_UNKNOWN; p++)
1493         if (p->profile == profile)
1494             return p->name;
1495
1496     return NULL;
1497 }
1498
1499 unsigned avcodec_version(void)
1500 {
1501 //    av_assert0(AV_CODEC_ID_V410==164);
1502     av_assert0(AV_CODEC_ID_PCM_S8_PLANAR==65563);
1503     av_assert0(AV_CODEC_ID_ADPCM_G722==69660);
1504 //     av_assert0(AV_CODEC_ID_BMV_AUDIO==86071);
1505     av_assert0(AV_CODEC_ID_SRT==94216);
1506     av_assert0(LIBAVCODEC_VERSION_MICRO >= 100);
1507
1508     return LIBAVCODEC_VERSION_INT;
1509 }
1510
1511 const char *avcodec_configuration(void)
1512 {
1513     return FFMPEG_CONFIGURATION;
1514 }
1515
1516 const char *avcodec_license(void)
1517 {
1518 #define LICENSE_PREFIX "libavcodec license: "
1519     return LICENSE_PREFIX FFMPEG_LICENSE + sizeof(LICENSE_PREFIX) - 1;
1520 }
1521
1522 int av_get_exact_bits_per_sample(enum AVCodecID codec_id)
1523 {
1524     switch (codec_id) {
1525     case AV_CODEC_ID_8SVX_EXP:
1526     case AV_CODEC_ID_8SVX_FIB:
1527     case AV_CODEC_ID_ADPCM_CT:
1528     case AV_CODEC_ID_ADPCM_IMA_APC:
1529     case AV_CODEC_ID_ADPCM_IMA_EA_SEAD:
1530     case AV_CODEC_ID_ADPCM_IMA_OKI:
1531     case AV_CODEC_ID_ADPCM_IMA_WS:
1532     case AV_CODEC_ID_ADPCM_G722:
1533     case AV_CODEC_ID_ADPCM_YAMAHA:
1534     case AV_CODEC_ID_ADPCM_AICA:
1535         return 4;
1536     case AV_CODEC_ID_DSD_LSBF:
1537     case AV_CODEC_ID_DSD_MSBF:
1538     case AV_CODEC_ID_DSD_LSBF_PLANAR:
1539     case AV_CODEC_ID_DSD_MSBF_PLANAR:
1540     case AV_CODEC_ID_PCM_ALAW:
1541     case AV_CODEC_ID_PCM_MULAW:
1542     case AV_CODEC_ID_PCM_S8:
1543     case AV_CODEC_ID_PCM_S8_PLANAR:
1544     case AV_CODEC_ID_PCM_U8:
1545     case AV_CODEC_ID_PCM_ZORK:
1546     case AV_CODEC_ID_SDX2_DPCM:
1547         return 8;
1548     case AV_CODEC_ID_PCM_S16BE:
1549     case AV_CODEC_ID_PCM_S16BE_PLANAR:
1550     case AV_CODEC_ID_PCM_S16LE:
1551     case AV_CODEC_ID_PCM_S16LE_PLANAR:
1552     case AV_CODEC_ID_PCM_U16BE:
1553     case AV_CODEC_ID_PCM_U16LE:
1554         return 16;
1555     case AV_CODEC_ID_PCM_S24DAUD:
1556     case AV_CODEC_ID_PCM_S24BE:
1557     case AV_CODEC_ID_PCM_S24LE:
1558     case AV_CODEC_ID_PCM_S24LE_PLANAR:
1559     case AV_CODEC_ID_PCM_U24BE:
1560     case AV_CODEC_ID_PCM_U24LE:
1561         return 24;
1562     case AV_CODEC_ID_PCM_S32BE:
1563     case AV_CODEC_ID_PCM_S32LE:
1564     case AV_CODEC_ID_PCM_S32LE_PLANAR:
1565     case AV_CODEC_ID_PCM_U32BE:
1566     case AV_CODEC_ID_PCM_U32LE:
1567     case AV_CODEC_ID_PCM_F32BE:
1568     case AV_CODEC_ID_PCM_F32LE:
1569     case AV_CODEC_ID_PCM_F24LE:
1570     case AV_CODEC_ID_PCM_F16LE:
1571         return 32;
1572     case AV_CODEC_ID_PCM_F64BE:
1573     case AV_CODEC_ID_PCM_F64LE:
1574     case AV_CODEC_ID_PCM_S64BE:
1575     case AV_CODEC_ID_PCM_S64LE:
1576         return 64;
1577     default:
1578         return 0;
1579     }
1580 }
1581
1582 enum AVCodecID av_get_pcm_codec(enum AVSampleFormat fmt, int be)
1583 {
1584     static const enum AVCodecID map[AV_SAMPLE_FMT_NB][2] = {
1585         [AV_SAMPLE_FMT_U8  ] = { AV_CODEC_ID_PCM_U8,    AV_CODEC_ID_PCM_U8    },
1586         [AV_SAMPLE_FMT_S16 ] = { AV_CODEC_ID_PCM_S16LE, AV_CODEC_ID_PCM_S16BE },
1587         [AV_SAMPLE_FMT_S32 ] = { AV_CODEC_ID_PCM_S32LE, AV_CODEC_ID_PCM_S32BE },
1588         [AV_SAMPLE_FMT_FLT ] = { AV_CODEC_ID_PCM_F32LE, AV_CODEC_ID_PCM_F32BE },
1589         [AV_SAMPLE_FMT_DBL ] = { AV_CODEC_ID_PCM_F64LE, AV_CODEC_ID_PCM_F64BE },
1590         [AV_SAMPLE_FMT_U8P ] = { AV_CODEC_ID_PCM_U8,    AV_CODEC_ID_PCM_U8    },
1591         [AV_SAMPLE_FMT_S16P] = { AV_CODEC_ID_PCM_S16LE, AV_CODEC_ID_PCM_S16BE },
1592         [AV_SAMPLE_FMT_S32P] = { AV_CODEC_ID_PCM_S32LE, AV_CODEC_ID_PCM_S32BE },
1593         [AV_SAMPLE_FMT_S64P] = { AV_CODEC_ID_PCM_S64LE, AV_CODEC_ID_PCM_S64BE },
1594         [AV_SAMPLE_FMT_FLTP] = { AV_CODEC_ID_PCM_F32LE, AV_CODEC_ID_PCM_F32BE },
1595         [AV_SAMPLE_FMT_DBLP] = { AV_CODEC_ID_PCM_F64LE, AV_CODEC_ID_PCM_F64BE },
1596     };
1597     if (fmt < 0 || fmt >= AV_SAMPLE_FMT_NB)
1598         return AV_CODEC_ID_NONE;
1599     if (be < 0 || be > 1)
1600         be = AV_NE(1, 0);
1601     return map[fmt][be];
1602 }
1603
1604 int av_get_bits_per_sample(enum AVCodecID codec_id)
1605 {
1606     switch (codec_id) {
1607     case AV_CODEC_ID_ADPCM_SBPRO_2:
1608         return 2;
1609     case AV_CODEC_ID_ADPCM_SBPRO_3:
1610         return 3;
1611     case AV_CODEC_ID_ADPCM_SBPRO_4:
1612     case AV_CODEC_ID_ADPCM_IMA_WAV:
1613     case AV_CODEC_ID_ADPCM_IMA_QT:
1614     case AV_CODEC_ID_ADPCM_SWF:
1615     case AV_CODEC_ID_ADPCM_MS:
1616         return 4;
1617     default:
1618         return av_get_exact_bits_per_sample(codec_id);
1619     }
1620 }
1621
1622 static int get_audio_frame_duration(enum AVCodecID id, int sr, int ch, int ba,
1623                                     uint32_t tag, int bits_per_coded_sample, int64_t bitrate,
1624                                     uint8_t * extradata, int frame_size, int frame_bytes)
1625 {
1626     int bps = av_get_exact_bits_per_sample(id);
1627     int framecount = (ba > 0 && frame_bytes / ba > 0) ? frame_bytes / ba : 1;
1628
1629     /* codecs with an exact constant bits per sample */
1630     if (bps > 0 && ch > 0 && frame_bytes > 0 && ch < 32768 && bps < 32768)
1631         return (frame_bytes * 8LL) / (bps * ch);
1632     bps = bits_per_coded_sample;
1633
1634     /* codecs with a fixed packet duration */
1635     switch (id) {
1636     case AV_CODEC_ID_ADPCM_ADX:    return   32;
1637     case AV_CODEC_ID_ADPCM_IMA_QT: return   64;
1638     case AV_CODEC_ID_ADPCM_EA_XAS: return  128;
1639     case AV_CODEC_ID_AMR_NB:
1640     case AV_CODEC_ID_EVRC:
1641     case AV_CODEC_ID_GSM:
1642     case AV_CODEC_ID_QCELP:
1643     case AV_CODEC_ID_RA_288:       return  160;
1644     case AV_CODEC_ID_AMR_WB:
1645     case AV_CODEC_ID_GSM_MS:       return  320;
1646     case AV_CODEC_ID_MP1:          return  384;
1647     case AV_CODEC_ID_ATRAC1:       return  512;
1648     case AV_CODEC_ID_ATRAC3:       return 1024 * framecount;
1649     case AV_CODEC_ID_ATRAC3P:      return 2048;
1650     case AV_CODEC_ID_MP2:
1651     case AV_CODEC_ID_MUSEPACK7:    return 1152;
1652     case AV_CODEC_ID_AC3:          return 1536;
1653     }
1654
1655     if (sr > 0) {
1656         /* calc from sample rate */
1657         if (id == AV_CODEC_ID_TTA)
1658             return 256 * sr / 245;
1659         else if (id == AV_CODEC_ID_DST)
1660             return 588 * sr / 44100;
1661
1662         if (ch > 0) {
1663             /* calc from sample rate and channels */
1664             if (id == AV_CODEC_ID_BINKAUDIO_DCT)
1665                 return (480 << (sr / 22050)) / ch;
1666         }
1667
1668         if (id == AV_CODEC_ID_MP3)
1669             return sr <= 24000 ? 576 : 1152;
1670     }
1671
1672     if (ba > 0) {
1673         /* calc from block_align */
1674         if (id == AV_CODEC_ID_SIPR) {
1675             switch (ba) {
1676             case 20: return 160;
1677             case 19: return 144;
1678             case 29: return 288;
1679             case 37: return 480;
1680             }
1681         } else if (id == AV_CODEC_ID_ILBC) {
1682             switch (ba) {
1683             case 38: return 160;
1684             case 50: return 240;
1685             }
1686         }
1687     }
1688
1689     if (frame_bytes > 0) {
1690         /* calc from frame_bytes only */
1691         if (id == AV_CODEC_ID_TRUESPEECH)
1692             return 240 * (frame_bytes / 32);
1693         if (id == AV_CODEC_ID_NELLYMOSER)
1694             return 256 * (frame_bytes / 64);
1695         if (id == AV_CODEC_ID_RA_144)
1696             return 160 * (frame_bytes / 20);
1697         if (id == AV_CODEC_ID_G723_1)
1698             return 240 * (frame_bytes / 24);
1699
1700         if (bps > 0) {
1701             /* calc from frame_bytes and bits_per_coded_sample */
1702             if (id == AV_CODEC_ID_ADPCM_G726 || id == AV_CODEC_ID_ADPCM_G726LE)
1703                 return frame_bytes * 8 / bps;
1704         }
1705
1706         if (ch > 0 && ch < INT_MAX/16) {
1707             /* calc from frame_bytes and channels */
1708             switch (id) {
1709             case AV_CODEC_ID_ADPCM_AFC:
1710                 return frame_bytes / (9 * ch) * 16;
1711             case AV_CODEC_ID_ADPCM_PSX:
1712             case AV_CODEC_ID_ADPCM_DTK:
1713                 return frame_bytes / (16 * ch) * 28;
1714             case AV_CODEC_ID_ADPCM_4XM:
1715             case AV_CODEC_ID_ADPCM_IMA_DAT4:
1716             case AV_CODEC_ID_ADPCM_IMA_ISS:
1717                 return (frame_bytes - 4 * ch) * 2 / ch;
1718             case AV_CODEC_ID_ADPCM_IMA_SMJPEG:
1719                 return (frame_bytes - 4) * 2 / ch;
1720             case AV_CODEC_ID_ADPCM_IMA_AMV:
1721                 return (frame_bytes - 8) * 2 / ch;
1722             case AV_CODEC_ID_ADPCM_THP:
1723             case AV_CODEC_ID_ADPCM_THP_LE:
1724                 if (extradata)
1725                     return frame_bytes * 14 / (8 * ch);
1726                 break;
1727             case AV_CODEC_ID_ADPCM_XA:
1728                 return (frame_bytes / 128) * 224 / ch;
1729             case AV_CODEC_ID_INTERPLAY_DPCM:
1730                 return (frame_bytes - 6 - ch) / ch;
1731             case AV_CODEC_ID_ROQ_DPCM:
1732                 return (frame_bytes - 8) / ch;
1733             case AV_CODEC_ID_XAN_DPCM:
1734                 return (frame_bytes - 2 * ch) / ch;
1735             case AV_CODEC_ID_MACE3:
1736                 return 3 * frame_bytes / ch;
1737             case AV_CODEC_ID_MACE6:
1738                 return 6 * frame_bytes / ch;
1739             case AV_CODEC_ID_PCM_LXF:
1740                 return 2 * (frame_bytes / (5 * ch));
1741             case AV_CODEC_ID_IAC:
1742             case AV_CODEC_ID_IMC:
1743                 return 4 * frame_bytes / ch;
1744             }
1745
1746             if (tag) {
1747                 /* calc from frame_bytes, channels, and codec_tag */
1748                 if (id == AV_CODEC_ID_SOL_DPCM) {
1749                     if (tag == 3)
1750                         return frame_bytes / ch;
1751                     else
1752                         return frame_bytes * 2 / ch;
1753                 }
1754             }
1755
1756             if (ba > 0) {
1757                 /* calc from frame_bytes, channels, and block_align */
1758                 int blocks = frame_bytes / ba;
1759                 switch (id) {
1760                 case AV_CODEC_ID_ADPCM_IMA_WAV:
1761                     if (bps < 2 || bps > 5)
1762                         return 0;
1763                     return blocks * (1 + (ba - 4 * ch) / (bps * ch) * 8);
1764                 case AV_CODEC_ID_ADPCM_IMA_DK3:
1765                     return blocks * (((ba - 16) * 2 / 3 * 4) / ch);
1766                 case AV_CODEC_ID_ADPCM_IMA_DK4:
1767                     return blocks * (1 + (ba - 4 * ch) * 2 / ch);
1768                 case AV_CODEC_ID_ADPCM_IMA_RAD:
1769                     return blocks * ((ba - 4 * ch) * 2 / ch);
1770                 case AV_CODEC_ID_ADPCM_MS:
1771                     return blocks * (2 + (ba - 7 * ch) * 2 / ch);
1772                 case AV_CODEC_ID_ADPCM_MTAF:
1773                     return blocks * (ba - 16) * 2 / ch;
1774                 }
1775             }
1776
1777             if (bps > 0) {
1778                 /* calc from frame_bytes, channels, and bits_per_coded_sample */
1779                 switch (id) {
1780                 case AV_CODEC_ID_PCM_DVD:
1781                     if(bps<4 || frame_bytes<3)
1782                         return 0;
1783                     return 2 * ((frame_bytes - 3) / ((bps * 2 / 8) * ch));
1784                 case AV_CODEC_ID_PCM_BLURAY:
1785                     if(bps<4 || frame_bytes<4)
1786                         return 0;
1787                     return (frame_bytes - 4) / ((FFALIGN(ch, 2) * bps) / 8);
1788                 case AV_CODEC_ID_S302M:
1789                     return 2 * (frame_bytes / ((bps + 4) / 4)) / ch;
1790                 }
1791             }
1792         }
1793     }
1794
1795     /* Fall back on using frame_size */
1796     if (frame_size > 1 && frame_bytes)
1797         return frame_size;
1798
1799     //For WMA we currently have no other means to calculate duration thus we
1800     //do it here by assuming CBR, which is true for all known cases.
1801     if (bitrate > 0 && frame_bytes > 0 && sr > 0 && ba > 1) {
1802         if (id == AV_CODEC_ID_WMAV1 || id == AV_CODEC_ID_WMAV2)
1803             return  (frame_bytes * 8LL * sr) / bitrate;
1804     }
1805
1806     return 0;
1807 }
1808
1809 int av_get_audio_frame_duration(AVCodecContext *avctx, int frame_bytes)
1810 {
1811     return get_audio_frame_duration(avctx->codec_id, avctx->sample_rate,
1812                                     avctx->channels, avctx->block_align,
1813                                     avctx->codec_tag, avctx->bits_per_coded_sample,
1814                                     avctx->bit_rate, avctx->extradata, avctx->frame_size,
1815                                     frame_bytes);
1816 }
1817
1818 int av_get_audio_frame_duration2(AVCodecParameters *par, int frame_bytes)
1819 {
1820     return get_audio_frame_duration(par->codec_id, par->sample_rate,
1821                                     par->channels, par->block_align,
1822                                     par->codec_tag, par->bits_per_coded_sample,
1823                                     par->bit_rate, par->extradata, par->frame_size,
1824                                     frame_bytes);
1825 }
1826
1827 #if !HAVE_THREADS
1828 int ff_thread_init(AVCodecContext *s)
1829 {
1830     return -1;
1831 }
1832
1833 #endif
1834
1835 unsigned int av_xiphlacing(unsigned char *s, unsigned int v)
1836 {
1837     unsigned int n = 0;
1838
1839     while (v >= 0xff) {
1840         *s++ = 0xff;
1841         v -= 0xff;
1842         n++;
1843     }
1844     *s = v;
1845     n++;
1846     return n;
1847 }
1848
1849 int ff_match_2uint16(const uint16_t(*tab)[2], int size, int a, int b)
1850 {
1851     int i;
1852     for (i = 0; i < size && !(tab[i][0] == a && tab[i][1] == b); i++) ;
1853     return i;
1854 }
1855
1856 const AVCodecHWConfig *avcodec_get_hw_config(const AVCodec *codec, int index)
1857 {
1858     int i;
1859     if (!codec->hw_configs || index < 0)
1860         return NULL;
1861     for (i = 0; i <= index; i++)
1862         if (!codec->hw_configs[i])
1863             return NULL;
1864     return &codec->hw_configs[index]->public;
1865 }
1866
1867 #if FF_API_USER_VISIBLE_AVHWACCEL
1868 AVHWAccel *av_hwaccel_next(const AVHWAccel *hwaccel)
1869 {
1870     return NULL;
1871 }
1872
1873 void av_register_hwaccel(AVHWAccel *hwaccel)
1874 {
1875 }
1876 #endif
1877
1878 #if FF_API_LOCKMGR
1879 int av_lockmgr_register(int (*cb)(void **mutex, enum AVLockOp op))
1880 {
1881     return 0;
1882 }
1883 #endif
1884
1885 unsigned int avpriv_toupper4(unsigned int x)
1886 {
1887     return av_toupper(x & 0xFF) +
1888           (av_toupper((x >>  8) & 0xFF) << 8)  +
1889           (av_toupper((x >> 16) & 0xFF) << 16) +
1890 ((unsigned)av_toupper((x >> 24) & 0xFF) << 24);
1891 }
1892
1893 int ff_thread_ref_frame(ThreadFrame *dst, ThreadFrame *src)
1894 {
1895     int ret;
1896
1897     dst->owner[0] = src->owner[0];
1898     dst->owner[1] = src->owner[1];
1899
1900     ret = av_frame_ref(dst->f, src->f);
1901     if (ret < 0)
1902         return ret;
1903
1904     av_assert0(!dst->progress);
1905
1906     if (src->progress &&
1907         !(dst->progress = av_buffer_ref(src->progress))) {
1908         ff_thread_release_buffer(dst->owner[0], dst);
1909         return AVERROR(ENOMEM);
1910     }
1911
1912     return 0;
1913 }
1914
1915 #if !HAVE_THREADS
1916
1917 enum AVPixelFormat ff_thread_get_format(AVCodecContext *avctx, const enum AVPixelFormat *fmt)
1918 {
1919     return ff_get_format(avctx, fmt);
1920 }
1921
1922 int ff_thread_get_buffer(AVCodecContext *avctx, ThreadFrame *f, int flags)
1923 {
1924     f->owner[0] = f->owner[1] = avctx;
1925     return ff_get_buffer(avctx, f->f, flags);
1926 }
1927
1928 void ff_thread_release_buffer(AVCodecContext *avctx, ThreadFrame *f)
1929 {
1930     if (f->f)
1931         av_frame_unref(f->f);
1932 }
1933
1934 void ff_thread_finish_setup(AVCodecContext *avctx)
1935 {
1936 }
1937
1938 void ff_thread_report_progress(ThreadFrame *f, int progress, int field)
1939 {
1940 }
1941
1942 void ff_thread_await_progress(ThreadFrame *f, int progress, int field)
1943 {
1944 }
1945
1946 int ff_thread_can_start_frame(AVCodecContext *avctx)
1947 {
1948     return 1;
1949 }
1950
1951 int ff_alloc_entries(AVCodecContext *avctx, int count)
1952 {
1953     return 0;
1954 }
1955
1956 void ff_reset_entries(AVCodecContext *avctx)
1957 {
1958 }
1959
1960 void ff_thread_await_progress2(AVCodecContext *avctx, int field, int thread, int shift)
1961 {
1962 }
1963
1964 void ff_thread_report_progress2(AVCodecContext *avctx, int field, int thread, int n)
1965 {
1966 }
1967
1968 #endif
1969
1970 int avcodec_is_open(AVCodecContext *s)
1971 {
1972     return !!s->internal;
1973 }
1974
1975 int avpriv_bprint_to_extradata(AVCodecContext *avctx, struct AVBPrint *buf)
1976 {
1977     int ret;
1978     char *str;
1979
1980     ret = av_bprint_finalize(buf, &str);
1981     if (ret < 0)
1982         return ret;
1983     if (!av_bprint_is_complete(buf)) {
1984         av_free(str);
1985         return AVERROR(ENOMEM);
1986     }
1987
1988     avctx->extradata = str;
1989     /* Note: the string is NUL terminated (so extradata can be read as a
1990      * string), but the ending character is not accounted in the size (in
1991      * binary formats you are likely not supposed to mux that character). When
1992      * extradata is copied, it is also padded with AV_INPUT_BUFFER_PADDING_SIZE
1993      * zeros. */
1994     avctx->extradata_size = buf->len;
1995     return 0;
1996 }
1997
1998 const uint8_t *avpriv_find_start_code(const uint8_t *av_restrict p,
1999                                       const uint8_t *end,
2000                                       uint32_t *av_restrict state)
2001 {
2002     int i;
2003
2004     av_assert0(p <= end);
2005     if (p >= end)
2006         return end;
2007
2008     for (i = 0; i < 3; i++) {
2009         uint32_t tmp = *state << 8;
2010         *state = tmp + *(p++);
2011         if (tmp == 0x100 || p == end)
2012             return p;
2013     }
2014
2015     while (p < end) {
2016         if      (p[-1] > 1      ) p += 3;
2017         else if (p[-2]          ) p += 2;
2018         else if (p[-3]|(p[-1]-1)) p++;
2019         else {
2020             p++;
2021             break;
2022         }
2023     }
2024
2025     p = FFMIN(p, end) - 4;
2026     *state = AV_RB32(p);
2027
2028     return p + 4;
2029 }
2030
2031 AVCPBProperties *av_cpb_properties_alloc(size_t *size)
2032 {
2033     AVCPBProperties *props = av_mallocz(sizeof(AVCPBProperties));
2034     if (!props)
2035         return NULL;
2036
2037     if (size)
2038         *size = sizeof(*props);
2039
2040     props->vbv_delay = UINT64_MAX;
2041
2042     return props;
2043 }
2044
2045 AVCPBProperties *ff_add_cpb_side_data(AVCodecContext *avctx)
2046 {
2047     AVPacketSideData *tmp;
2048     AVCPBProperties  *props;
2049     size_t size;
2050
2051     props = av_cpb_properties_alloc(&size);
2052     if (!props)
2053         return NULL;
2054
2055     tmp = av_realloc_array(avctx->coded_side_data, avctx->nb_coded_side_data + 1, sizeof(*tmp));
2056     if (!tmp) {
2057         av_freep(&props);
2058         return NULL;
2059     }
2060
2061     avctx->coded_side_data = tmp;
2062     avctx->nb_coded_side_data++;
2063
2064     avctx->coded_side_data[avctx->nb_coded_side_data - 1].type = AV_PKT_DATA_CPB_PROPERTIES;
2065     avctx->coded_side_data[avctx->nb_coded_side_data - 1].data = (uint8_t*)props;
2066     avctx->coded_side_data[avctx->nb_coded_side_data - 1].size = size;
2067
2068     return props;
2069 }
2070
2071 static void codec_parameters_reset(AVCodecParameters *par)
2072 {
2073     av_freep(&par->extradata);
2074
2075     memset(par, 0, sizeof(*par));
2076
2077     par->codec_type          = AVMEDIA_TYPE_UNKNOWN;
2078     par->codec_id            = AV_CODEC_ID_NONE;
2079     par->format              = -1;
2080     par->field_order         = AV_FIELD_UNKNOWN;
2081     par->color_range         = AVCOL_RANGE_UNSPECIFIED;
2082     par->color_primaries     = AVCOL_PRI_UNSPECIFIED;
2083     par->color_trc           = AVCOL_TRC_UNSPECIFIED;
2084     par->color_space         = AVCOL_SPC_UNSPECIFIED;
2085     par->chroma_location     = AVCHROMA_LOC_UNSPECIFIED;
2086     par->sample_aspect_ratio = (AVRational){ 0, 1 };
2087     par->profile             = FF_PROFILE_UNKNOWN;
2088     par->level               = FF_LEVEL_UNKNOWN;
2089 }
2090
2091 AVCodecParameters *avcodec_parameters_alloc(void)
2092 {
2093     AVCodecParameters *par = av_mallocz(sizeof(*par));
2094
2095     if (!par)
2096         return NULL;
2097     codec_parameters_reset(par);
2098     return par;
2099 }
2100
2101 void avcodec_parameters_free(AVCodecParameters **ppar)
2102 {
2103     AVCodecParameters *par = *ppar;
2104
2105     if (!par)
2106         return;
2107     codec_parameters_reset(par);
2108
2109     av_freep(ppar);
2110 }
2111
2112 int avcodec_parameters_copy(AVCodecParameters *dst, const AVCodecParameters *src)
2113 {
2114     codec_parameters_reset(dst);
2115     memcpy(dst, src, sizeof(*dst));
2116
2117     dst->extradata      = NULL;
2118     dst->extradata_size = 0;
2119     if (src->extradata) {
2120         dst->extradata = av_mallocz(src->extradata_size + AV_INPUT_BUFFER_PADDING_SIZE);
2121         if (!dst->extradata)
2122             return AVERROR(ENOMEM);
2123         memcpy(dst->extradata, src->extradata, src->extradata_size);
2124         dst->extradata_size = src->extradata_size;
2125     }
2126
2127     return 0;
2128 }
2129
2130 int avcodec_parameters_from_context(AVCodecParameters *par,
2131                                     const AVCodecContext *codec)
2132 {
2133     codec_parameters_reset(par);
2134
2135     par->codec_type = codec->codec_type;
2136     par->codec_id   = codec->codec_id;
2137     par->codec_tag  = codec->codec_tag;
2138
2139     par->bit_rate              = codec->bit_rate;
2140     par->bits_per_coded_sample = codec->bits_per_coded_sample;
2141     par->bits_per_raw_sample   = codec->bits_per_raw_sample;
2142     par->profile               = codec->profile;
2143     par->level                 = codec->level;
2144
2145     switch (par->codec_type) {
2146     case AVMEDIA_TYPE_VIDEO:
2147         par->format              = codec->pix_fmt;
2148         par->width               = codec->width;
2149         par->height              = codec->height;
2150         par->field_order         = codec->field_order;
2151         par->color_range         = codec->color_range;
2152         par->color_primaries     = codec->color_primaries;
2153         par->color_trc           = codec->color_trc;
2154         par->color_space         = codec->colorspace;
2155         par->chroma_location     = codec->chroma_sample_location;
2156         par->sample_aspect_ratio = codec->sample_aspect_ratio;
2157         par->video_delay         = codec->has_b_frames;
2158         break;
2159     case AVMEDIA_TYPE_AUDIO:
2160         par->format           = codec->sample_fmt;
2161         par->channel_layout   = codec->channel_layout;
2162         par->channels         = codec->channels;
2163         par->sample_rate      = codec->sample_rate;
2164         par->block_align      = codec->block_align;
2165         par->frame_size       = codec->frame_size;
2166         par->initial_padding  = codec->initial_padding;
2167         par->trailing_padding = codec->trailing_padding;
2168         par->seek_preroll     = codec->seek_preroll;
2169         break;
2170     case AVMEDIA_TYPE_SUBTITLE:
2171         par->width  = codec->width;
2172         par->height = codec->height;
2173         break;
2174     }
2175
2176     if (codec->extradata) {
2177         par->extradata = av_mallocz(codec->extradata_size + AV_INPUT_BUFFER_PADDING_SIZE);
2178         if (!par->extradata)
2179             return AVERROR(ENOMEM);
2180         memcpy(par->extradata, codec->extradata, codec->extradata_size);
2181         par->extradata_size = codec->extradata_size;
2182     }
2183
2184     return 0;
2185 }
2186
2187 int avcodec_parameters_to_context(AVCodecContext *codec,
2188                                   const AVCodecParameters *par)
2189 {
2190     codec->codec_type = par->codec_type;
2191     codec->codec_id   = par->codec_id;
2192     codec->codec_tag  = par->codec_tag;
2193
2194     codec->bit_rate              = par->bit_rate;
2195     codec->bits_per_coded_sample = par->bits_per_coded_sample;
2196     codec->bits_per_raw_sample   = par->bits_per_raw_sample;
2197     codec->profile               = par->profile;
2198     codec->level                 = par->level;
2199
2200     switch (par->codec_type) {
2201     case AVMEDIA_TYPE_VIDEO:
2202         codec->pix_fmt                = par->format;
2203         codec->width                  = par->width;
2204         codec->height                 = par->height;
2205         codec->field_order            = par->field_order;
2206         codec->color_range            = par->color_range;
2207         codec->color_primaries        = par->color_primaries;
2208         codec->color_trc              = par->color_trc;
2209         codec->colorspace             = par->color_space;
2210         codec->chroma_sample_location = par->chroma_location;
2211         codec->sample_aspect_ratio    = par->sample_aspect_ratio;
2212         codec->has_b_frames           = par->video_delay;
2213         break;
2214     case AVMEDIA_TYPE_AUDIO:
2215         codec->sample_fmt       = par->format;
2216         codec->channel_layout   = par->channel_layout;
2217         codec->channels         = par->channels;
2218         codec->sample_rate      = par->sample_rate;
2219         codec->block_align      = par->block_align;
2220         codec->frame_size       = par->frame_size;
2221         codec->delay            =
2222         codec->initial_padding  = par->initial_padding;
2223         codec->trailing_padding = par->trailing_padding;
2224         codec->seek_preroll     = par->seek_preroll;
2225         break;
2226     case AVMEDIA_TYPE_SUBTITLE:
2227         codec->width  = par->width;
2228         codec->height = par->height;
2229         break;
2230     }
2231
2232     if (par->extradata) {
2233         av_freep(&codec->extradata);
2234         codec->extradata = av_mallocz(par->extradata_size + AV_INPUT_BUFFER_PADDING_SIZE);
2235         if (!codec->extradata)
2236             return AVERROR(ENOMEM);
2237         memcpy(codec->extradata, par->extradata, par->extradata_size);
2238         codec->extradata_size = par->extradata_size;
2239     }
2240
2241     return 0;
2242 }
2243
2244 int ff_alloc_a53_sei(const AVFrame *frame, size_t prefix_len,
2245                      void **data, size_t *sei_size)
2246 {
2247     AVFrameSideData *side_data = NULL;
2248     uint8_t *sei_data;
2249
2250     if (frame)
2251         side_data = av_frame_get_side_data(frame, AV_FRAME_DATA_A53_CC);
2252
2253     if (!side_data) {
2254         *data = NULL;
2255         return 0;
2256     }
2257
2258     *sei_size = side_data->size + 11;
2259     *data = av_mallocz(*sei_size + prefix_len);
2260     if (!*data)
2261         return AVERROR(ENOMEM);
2262     sei_data = (uint8_t*)*data + prefix_len;
2263
2264     // country code
2265     sei_data[0] = 181;
2266     sei_data[1] = 0;
2267     sei_data[2] = 49;
2268
2269     /**
2270      * 'GA94' is standard in North America for ATSC, but hard coding
2271      * this style may not be the right thing to do -- other formats
2272      * do exist. This information is not available in the side_data
2273      * so we are going with this right now.
2274      */
2275     AV_WL32(sei_data + 3, MKTAG('G', 'A', '9', '4'));
2276     sei_data[7] = 3;
2277     sei_data[8] = ((side_data->size/3) & 0x1f) | 0x40;
2278     sei_data[9] = 0;
2279
2280     memcpy(sei_data + 10, side_data->data, side_data->size);
2281
2282     sei_data[side_data->size+10] = 255;
2283
2284     return 0;
2285 }
2286
2287 int64_t ff_guess_coded_bitrate(AVCodecContext *avctx)
2288 {
2289     AVRational framerate = avctx->framerate;
2290     int bits_per_coded_sample = avctx->bits_per_coded_sample;
2291     int64_t bitrate;
2292
2293     if (!(framerate.num && framerate.den))
2294         framerate = av_inv_q(avctx->time_base);
2295     if (!(framerate.num && framerate.den))
2296         return 0;
2297
2298     if (!bits_per_coded_sample) {
2299         const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(avctx->pix_fmt);
2300         bits_per_coded_sample = av_get_bits_per_pixel(desc);
2301     }
2302     bitrate = (int64_t)bits_per_coded_sample * avctx->width * avctx->height *
2303               framerate.num / framerate.den;
2304
2305     return bitrate;
2306 }