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