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