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