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