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