]> git.sesse.net Git - ffmpeg/blob - libavcodec/utils.c
avcodec/utils: use a minimum 32pixel width in avcodec_align_dimensions2() for H.264
[ffmpeg] / libavcodec / utils.c
1 /*
2  * utils for libavcodec
3  * Copyright (c) 2001 Fabrice Bellard
4  * Copyright (c) 2002-2004 Michael Niedermayer <michaelni@gmx.at>
5  *
6  * This file is part of FFmpeg.
7  *
8  * FFmpeg is free software; you can redistribute it and/or
9  * modify it under the terms of the GNU Lesser General Public
10  * License as published by the Free Software Foundation; either
11  * version 2.1 of the License, or (at your option) any later version.
12  *
13  * FFmpeg is distributed in the hope that it will be useful,
14  * but WITHOUT ANY WARRANTY; without even the implied warranty of
15  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
16  * Lesser General Public License for more details.
17  *
18  * You should have received a copy of the GNU Lesser General Public
19  * License along with FFmpeg; if not, write to the Free Software
20  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
21  */
22
23 /**
24  * @file
25  * utils.
26  */
27
28 #include "config.h"
29 #include "libavutil/atomic.h"
30 #include "libavutil/attributes.h"
31 #include "libavutil/avassert.h"
32 #include "libavutil/avstring.h"
33 #include "libavutil/bprint.h"
34 #include "libavutil/channel_layout.h"
35 #include "libavutil/crc.h"
36 #include "libavutil/frame.h"
37 #include "libavutil/internal.h"
38 #include "libavutil/mathematics.h"
39 #include "libavutil/pixdesc.h"
40 #include "libavutil/imgutils.h"
41 #include "libavutil/samplefmt.h"
42 #include "libavutil/dict.h"
43 #include "avcodec.h"
44 #include "libavutil/opt.h"
45 #include "me_cmp.h"
46 #include "mpegvideo.h"
47 #include "thread.h"
48 #include "frame_thread_encoder.h"
49 #include "internal.h"
50 #include "raw.h"
51 #include "bytestream.h"
52 #include "version.h"
53 #include <stdlib.h>
54 #include <stdarg.h>
55 #include <limits.h>
56 #include <float.h>
57 #if CONFIG_ICONV
58 # include <iconv.h>
59 #endif
60
61 #if HAVE_PTHREADS
62 #include <pthread.h>
63 #elif HAVE_W32THREADS
64 #include "compat/w32pthreads.h"
65 #elif HAVE_OS2THREADS
66 #include "compat/os2threads.h"
67 #endif
68
69 #include "libavutil/ffversion.h"
70 const char av_codec_ffversion[] = "FFmpeg version " FFMPEG_VERSION;
71
72 #if HAVE_PTHREADS || HAVE_W32THREADS || HAVE_OS2THREADS
73 static int default_lockmgr_cb(void **arg, enum AVLockOp op)
74 {
75     void * volatile * mutex = arg;
76     int err;
77
78     switch (op) {
79     case AV_LOCK_CREATE:
80         return 0;
81     case AV_LOCK_OBTAIN:
82         if (!*mutex) {
83             pthread_mutex_t *tmp = av_malloc(sizeof(pthread_mutex_t));
84             if (!tmp)
85                 return AVERROR(ENOMEM);
86             if ((err = pthread_mutex_init(tmp, NULL))) {
87                 av_free(tmp);
88                 return AVERROR(err);
89             }
90             if (avpriv_atomic_ptr_cas(mutex, NULL, tmp)) {
91                 pthread_mutex_destroy(tmp);
92                 av_free(tmp);
93             }
94         }
95
96         if ((err = pthread_mutex_lock(*mutex)))
97             return AVERROR(err);
98
99         return 0;
100     case AV_LOCK_RELEASE:
101         if ((err = pthread_mutex_unlock(*mutex)))
102             return AVERROR(err);
103
104         return 0;
105     case AV_LOCK_DESTROY:
106         if (*mutex)
107             pthread_mutex_destroy(*mutex);
108         av_free(*mutex);
109         avpriv_atomic_ptr_cas(mutex, *mutex, NULL);
110         return 0;
111     }
112     return 1;
113 }
114 static int (*lockmgr_cb)(void **mutex, enum AVLockOp op) = default_lockmgr_cb;
115 #else
116 static int (*lockmgr_cb)(void **mutex, enum AVLockOp op) = NULL;
117 #endif
118
119
120 volatile int ff_avcodec_locked;
121 static int volatile entangled_thread_counter = 0;
122 static void *codec_mutex;
123 static void *avformat_mutex;
124
125 static inline int ff_fast_malloc(void *ptr, unsigned int *size, size_t min_size, int zero_realloc)
126 {
127     void **p = ptr;
128     if (min_size <= *size && *p)
129         return 0;
130     min_size = FFMAX(17 * min_size / 16 + 32, min_size);
131     av_free(*p);
132     *p = zero_realloc ? av_mallocz(min_size) : av_malloc(min_size);
133     if (!*p)
134         min_size = 0;
135     *size = min_size;
136     return 1;
137 }
138
139 void av_fast_padded_malloc(void *ptr, unsigned int *size, size_t min_size)
140 {
141     uint8_t **p = ptr;
142     if (min_size > SIZE_MAX - FF_INPUT_BUFFER_PADDING_SIZE) {
143         av_freep(p);
144         *size = 0;
145         return;
146     }
147     if (!ff_fast_malloc(p, size, min_size + FF_INPUT_BUFFER_PADDING_SIZE, 1))
148         memset(*p + min_size, 0, FF_INPUT_BUFFER_PADDING_SIZE);
149 }
150
151 void av_fast_padded_mallocz(void *ptr, unsigned int *size, size_t min_size)
152 {
153     uint8_t **p = ptr;
154     if (min_size > SIZE_MAX - FF_INPUT_BUFFER_PADDING_SIZE) {
155         av_freep(p);
156         *size = 0;
157         return;
158     }
159     if (!ff_fast_malloc(p, size, min_size + FF_INPUT_BUFFER_PADDING_SIZE, 1))
160         memset(*p, 0, min_size + FF_INPUT_BUFFER_PADDING_SIZE);
161 }
162
163 /* encoder management */
164 static AVCodec *first_avcodec = NULL;
165 static AVCodec **last_avcodec = &first_avcodec;
166
167 AVCodec *av_codec_next(const AVCodec *c)
168 {
169     if (c)
170         return c->next;
171     else
172         return first_avcodec;
173 }
174
175 static av_cold void avcodec_init(void)
176 {
177     static int initialized = 0;
178
179     if (initialized != 0)
180         return;
181     initialized = 1;
182
183     if (CONFIG_ME_CMP)
184         ff_me_cmp_init_static();
185 }
186
187 int av_codec_is_encoder(const AVCodec *codec)
188 {
189     return codec && (codec->encode_sub || codec->encode2);
190 }
191
192 int av_codec_is_decoder(const AVCodec *codec)
193 {
194     return codec && codec->decode;
195 }
196
197 av_cold void avcodec_register(AVCodec *codec)
198 {
199     AVCodec **p;
200     avcodec_init();
201     p = last_avcodec;
202     codec->next = NULL;
203
204     while(*p || avpriv_atomic_ptr_cas((void * volatile *)p, NULL, codec))
205         p = &(*p)->next;
206     last_avcodec = &codec->next;
207
208     if (codec->init_static_data)
209         codec->init_static_data(codec);
210 }
211
212 #if FF_API_EMU_EDGE
213 unsigned avcodec_get_edge_width(void)
214 {
215     return EDGE_WIDTH;
216 }
217 #endif
218
219 #if FF_API_SET_DIMENSIONS
220 void avcodec_set_dimensions(AVCodecContext *s, int width, int height)
221 {
222     int ret = ff_set_dimensions(s, width, height);
223     if (ret < 0) {
224         av_log(s, AV_LOG_WARNING, "Failed to set dimensions %d %d\n", width, height);
225     }
226 }
227 #endif
228
229 int ff_set_dimensions(AVCodecContext *s, int width, int height)
230 {
231     int ret = av_image_check_size(width, height, 0, s);
232
233     if (ret < 0)
234         width = height = 0;
235
236     s->coded_width  = width;
237     s->coded_height = height;
238     s->width        = FF_CEIL_RSHIFT(width,  s->lowres);
239     s->height       = FF_CEIL_RSHIFT(height, s->lowres);
240
241     return ret;
242 }
243
244 int ff_set_sar(AVCodecContext *avctx, AVRational sar)
245 {
246     int ret = av_image_check_sar(avctx->width, avctx->height, sar);
247
248     if (ret < 0) {
249         av_log(avctx, AV_LOG_WARNING, "ignoring invalid SAR: %d/%d\n",
250                sar.num, sar.den);
251         avctx->sample_aspect_ratio = (AVRational){ 0, 1 };
252         return ret;
253     } else {
254         avctx->sample_aspect_ratio = sar;
255     }
256     return 0;
257 }
258
259 int ff_side_data_update_matrix_encoding(AVFrame *frame,
260                                         enum AVMatrixEncoding matrix_encoding)
261 {
262     AVFrameSideData *side_data;
263     enum AVMatrixEncoding *data;
264
265     side_data = av_frame_get_side_data(frame, AV_FRAME_DATA_MATRIXENCODING);
266     if (!side_data)
267         side_data = av_frame_new_side_data(frame, AV_FRAME_DATA_MATRIXENCODING,
268                                            sizeof(enum AVMatrixEncoding));
269
270     if (!side_data)
271         return AVERROR(ENOMEM);
272
273     data  = (enum AVMatrixEncoding*)side_data->data;
274     *data = matrix_encoding;
275
276     return 0;
277 }
278
279 void avcodec_align_dimensions2(AVCodecContext *s, int *width, int *height,
280                                int linesize_align[AV_NUM_DATA_POINTERS])
281 {
282     int i;
283     int w_align = 1;
284     int h_align = 1;
285     AVPixFmtDescriptor const *desc = av_pix_fmt_desc_get(s->pix_fmt);
286
287     if (desc) {
288         w_align = 1 << desc->log2_chroma_w;
289         h_align = 1 << desc->log2_chroma_h;
290     }
291
292     switch (s->pix_fmt) {
293     case AV_PIX_FMT_YUV420P:
294     case AV_PIX_FMT_YUYV422:
295     case AV_PIX_FMT_YVYU422:
296     case AV_PIX_FMT_UYVY422:
297     case AV_PIX_FMT_YUV422P:
298     case AV_PIX_FMT_YUV440P:
299     case AV_PIX_FMT_YUV444P:
300     case AV_PIX_FMT_GBRP:
301     case AV_PIX_FMT_GBRAP:
302     case AV_PIX_FMT_GRAY8:
303     case AV_PIX_FMT_GRAY16BE:
304     case AV_PIX_FMT_GRAY16LE:
305     case AV_PIX_FMT_YUVJ420P:
306     case AV_PIX_FMT_YUVJ422P:
307     case AV_PIX_FMT_YUVJ440P:
308     case AV_PIX_FMT_YUVJ444P:
309     case AV_PIX_FMT_YUVA420P:
310     case AV_PIX_FMT_YUVA422P:
311     case AV_PIX_FMT_YUVA444P:
312     case AV_PIX_FMT_YUV420P9LE:
313     case AV_PIX_FMT_YUV420P9BE:
314     case AV_PIX_FMT_YUV420P10LE:
315     case AV_PIX_FMT_YUV420P10BE:
316     case AV_PIX_FMT_YUV420P12LE:
317     case AV_PIX_FMT_YUV420P12BE:
318     case AV_PIX_FMT_YUV420P14LE:
319     case AV_PIX_FMT_YUV420P14BE:
320     case AV_PIX_FMT_YUV420P16LE:
321     case AV_PIX_FMT_YUV420P16BE:
322     case AV_PIX_FMT_YUVA420P9LE:
323     case AV_PIX_FMT_YUVA420P9BE:
324     case AV_PIX_FMT_YUVA420P10LE:
325     case AV_PIX_FMT_YUVA420P10BE:
326     case AV_PIX_FMT_YUVA420P16LE:
327     case AV_PIX_FMT_YUVA420P16BE:
328     case AV_PIX_FMT_YUV422P9LE:
329     case AV_PIX_FMT_YUV422P9BE:
330     case AV_PIX_FMT_YUV422P10LE:
331     case AV_PIX_FMT_YUV422P10BE:
332     case AV_PIX_FMT_YUV422P12LE:
333     case AV_PIX_FMT_YUV422P12BE:
334     case AV_PIX_FMT_YUV422P14LE:
335     case AV_PIX_FMT_YUV422P14BE:
336     case AV_PIX_FMT_YUV422P16LE:
337     case AV_PIX_FMT_YUV422P16BE:
338     case AV_PIX_FMT_YUVA422P9LE:
339     case AV_PIX_FMT_YUVA422P9BE:
340     case AV_PIX_FMT_YUVA422P10LE:
341     case AV_PIX_FMT_YUVA422P10BE:
342     case AV_PIX_FMT_YUVA422P16LE:
343     case AV_PIX_FMT_YUVA422P16BE:
344     case AV_PIX_FMT_YUV440P10LE:
345     case AV_PIX_FMT_YUV440P10BE:
346     case AV_PIX_FMT_YUV440P12LE:
347     case AV_PIX_FMT_YUV440P12BE:
348     case AV_PIX_FMT_YUV444P9LE:
349     case AV_PIX_FMT_YUV444P9BE:
350     case AV_PIX_FMT_YUV444P10LE:
351     case AV_PIX_FMT_YUV444P10BE:
352     case AV_PIX_FMT_YUV444P12LE:
353     case AV_PIX_FMT_YUV444P12BE:
354     case AV_PIX_FMT_YUV444P14LE:
355     case AV_PIX_FMT_YUV444P14BE:
356     case AV_PIX_FMT_YUV444P16LE:
357     case AV_PIX_FMT_YUV444P16BE:
358     case AV_PIX_FMT_YUVA444P9LE:
359     case AV_PIX_FMT_YUVA444P9BE:
360     case AV_PIX_FMT_YUVA444P10LE:
361     case AV_PIX_FMT_YUVA444P10BE:
362     case AV_PIX_FMT_YUVA444P16LE:
363     case AV_PIX_FMT_YUVA444P16BE:
364     case AV_PIX_FMT_GBRP9LE:
365     case AV_PIX_FMT_GBRP9BE:
366     case AV_PIX_FMT_GBRP10LE:
367     case AV_PIX_FMT_GBRP10BE:
368     case AV_PIX_FMT_GBRP12LE:
369     case AV_PIX_FMT_GBRP12BE:
370     case AV_PIX_FMT_GBRP14LE:
371     case AV_PIX_FMT_GBRP14BE:
372     case AV_PIX_FMT_GBRP16LE:
373     case AV_PIX_FMT_GBRP16BE:
374         w_align = 16; //FIXME assume 16 pixel per macroblock
375         h_align = 16 * 2; // interlaced needs 2 macroblocks height
376         break;
377     case AV_PIX_FMT_YUV411P:
378     case AV_PIX_FMT_YUVJ411P:
379     case AV_PIX_FMT_UYYVYY411:
380         w_align = 32;
381         h_align = 16 * 2;
382         break;
383     case AV_PIX_FMT_YUV410P:
384         if (s->codec_id == AV_CODEC_ID_SVQ1) {
385             w_align = 64;
386             h_align = 64;
387         }
388         break;
389     case AV_PIX_FMT_RGB555:
390         if (s->codec_id == AV_CODEC_ID_RPZA) {
391             w_align = 4;
392             h_align = 4;
393         }
394         break;
395     case AV_PIX_FMT_PAL8:
396     case AV_PIX_FMT_BGR8:
397     case AV_PIX_FMT_RGB8:
398         if (s->codec_id == AV_CODEC_ID_SMC ||
399             s->codec_id == AV_CODEC_ID_CINEPAK) {
400             w_align = 4;
401             h_align = 4;
402         }
403         if (s->codec_id == AV_CODEC_ID_JV) {
404             w_align = 8;
405             h_align = 8;
406         }
407         break;
408     case AV_PIX_FMT_BGR24:
409         if ((s->codec_id == AV_CODEC_ID_MSZH) ||
410             (s->codec_id == AV_CODEC_ID_ZLIB)) {
411             w_align = 4;
412             h_align = 4;
413         }
414         break;
415     case AV_PIX_FMT_RGB24:
416         if (s->codec_id == AV_CODEC_ID_CINEPAK) {
417             w_align = 4;
418             h_align = 4;
419         }
420         break;
421     default:
422         break;
423     }
424
425     if (s->codec_id == AV_CODEC_ID_IFF_ILBM || s->codec_id == AV_CODEC_ID_IFF_BYTERUN1) {
426         w_align = FFMAX(w_align, 8);
427     }
428
429     *width  = FFALIGN(*width, w_align);
430     *height = FFALIGN(*height, h_align);
431     if (s->codec_id == AV_CODEC_ID_H264 || s->lowres) {
432         // some of the optimized chroma MC reads one line too much
433         // which is also done in mpeg decoders with lowres > 0
434         *height += 2;
435         *width = FFMAX(*width, 32);
436     }
437
438     for (i = 0; i < 4; i++)
439         linesize_align[i] = STRIDE_ALIGN;
440 }
441
442 void avcodec_align_dimensions(AVCodecContext *s, int *width, int *height)
443 {
444     const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(s->pix_fmt);
445     int chroma_shift = desc->log2_chroma_w;
446     int linesize_align[AV_NUM_DATA_POINTERS];
447     int align;
448
449     avcodec_align_dimensions2(s, width, height, linesize_align);
450     align               = FFMAX(linesize_align[0], linesize_align[3]);
451     linesize_align[1] <<= chroma_shift;
452     linesize_align[2] <<= chroma_shift;
453     align               = FFMAX3(align, linesize_align[1], linesize_align[2]);
454     *width              = FFALIGN(*width, align);
455 }
456
457 int avcodec_enum_to_chroma_pos(int *xpos, int *ypos, enum AVChromaLocation pos)
458 {
459     if (pos <= AVCHROMA_LOC_UNSPECIFIED || pos >= AVCHROMA_LOC_NB)
460         return AVERROR(EINVAL);
461     pos--;
462
463     *xpos = (pos&1) * 128;
464     *ypos = ((pos>>1)^(pos<4)) * 128;
465
466     return 0;
467 }
468
469 enum AVChromaLocation avcodec_chroma_pos_to_enum(int xpos, int ypos)
470 {
471     int pos, xout, yout;
472
473     for (pos = AVCHROMA_LOC_UNSPECIFIED + 1; pos < AVCHROMA_LOC_NB; pos++) {
474         if (avcodec_enum_to_chroma_pos(&xout, &yout, pos) == 0 && xout == xpos && yout == ypos)
475             return pos;
476     }
477     return AVCHROMA_LOC_UNSPECIFIED;
478 }
479
480 int avcodec_fill_audio_frame(AVFrame *frame, int nb_channels,
481                              enum AVSampleFormat sample_fmt, const uint8_t *buf,
482                              int buf_size, int align)
483 {
484     int ch, planar, needed_size, ret = 0;
485
486     needed_size = av_samples_get_buffer_size(NULL, nb_channels,
487                                              frame->nb_samples, sample_fmt,
488                                              align);
489     if (buf_size < needed_size)
490         return AVERROR(EINVAL);
491
492     planar = av_sample_fmt_is_planar(sample_fmt);
493     if (planar && nb_channels > AV_NUM_DATA_POINTERS) {
494         if (!(frame->extended_data = av_mallocz_array(nb_channels,
495                                                 sizeof(*frame->extended_data))))
496             return AVERROR(ENOMEM);
497     } else {
498         frame->extended_data = frame->data;
499     }
500
501     if ((ret = av_samples_fill_arrays(frame->extended_data, &frame->linesize[0],
502                                       (uint8_t *)(intptr_t)buf, nb_channels, frame->nb_samples,
503                                       sample_fmt, align)) < 0) {
504         if (frame->extended_data != frame->data)
505             av_freep(&frame->extended_data);
506         return ret;
507     }
508     if (frame->extended_data != frame->data) {
509         for (ch = 0; ch < AV_NUM_DATA_POINTERS; ch++)
510             frame->data[ch] = frame->extended_data[ch];
511     }
512
513     return ret;
514 }
515
516 static int update_frame_pool(AVCodecContext *avctx, AVFrame *frame)
517 {
518     FramePool *pool = avctx->internal->pool;
519     int i, ret;
520
521     switch (avctx->codec_type) {
522     case AVMEDIA_TYPE_VIDEO: {
523         AVPicture picture;
524         int size[4] = { 0 };
525         int w = frame->width;
526         int h = frame->height;
527         int tmpsize, unaligned;
528
529         if (pool->format == frame->format &&
530             pool->width == frame->width && pool->height == frame->height)
531             return 0;
532
533         avcodec_align_dimensions2(avctx, &w, &h, pool->stride_align);
534
535         do {
536             // NOTE: do not align linesizes individually, this breaks e.g. assumptions
537             // that linesize[0] == 2*linesize[1] in the MPEG-encoder for 4:2:2
538             av_image_fill_linesizes(picture.linesize, avctx->pix_fmt, w);
539             // increase alignment of w for next try (rhs gives the lowest bit set in w)
540             w += w & ~(w - 1);
541
542             unaligned = 0;
543             for (i = 0; i < 4; i++)
544                 unaligned |= picture.linesize[i] % pool->stride_align[i];
545         } while (unaligned);
546
547         tmpsize = av_image_fill_pointers(picture.data, avctx->pix_fmt, h,
548                                          NULL, picture.linesize);
549         if (tmpsize < 0)
550             return -1;
551
552         for (i = 0; i < 3 && picture.data[i + 1]; i++)
553             size[i] = picture.data[i + 1] - picture.data[i];
554         size[i] = tmpsize - (picture.data[i] - picture.data[0]);
555
556         for (i = 0; i < 4; i++) {
557             av_buffer_pool_uninit(&pool->pools[i]);
558             pool->linesize[i] = picture.linesize[i];
559             if (size[i]) {
560                 pool->pools[i] = av_buffer_pool_init(size[i] + 16 + STRIDE_ALIGN - 1,
561                                                      CONFIG_MEMORY_POISONING ?
562                                                         NULL :
563                                                         av_buffer_allocz);
564                 if (!pool->pools[i]) {
565                     ret = AVERROR(ENOMEM);
566                     goto fail;
567                 }
568             }
569         }
570         pool->format = frame->format;
571         pool->width  = frame->width;
572         pool->height = frame->height;
573
574         break;
575         }
576     case AVMEDIA_TYPE_AUDIO: {
577         int ch     = av_frame_get_channels(frame); //av_get_channel_layout_nb_channels(frame->channel_layout);
578         int planar = av_sample_fmt_is_planar(frame->format);
579         int planes = planar ? ch : 1;
580
581         if (pool->format == frame->format && pool->planes == planes &&
582             pool->channels == ch && frame->nb_samples == pool->samples)
583             return 0;
584
585         av_buffer_pool_uninit(&pool->pools[0]);
586         ret = av_samples_get_buffer_size(&pool->linesize[0], ch,
587                                          frame->nb_samples, frame->format, 0);
588         if (ret < 0)
589             goto fail;
590
591         pool->pools[0] = av_buffer_pool_init(pool->linesize[0], NULL);
592         if (!pool->pools[0]) {
593             ret = AVERROR(ENOMEM);
594             goto fail;
595         }
596
597         pool->format     = frame->format;
598         pool->planes     = planes;
599         pool->channels   = ch;
600         pool->samples = frame->nb_samples;
601         break;
602         }
603     default: av_assert0(0);
604     }
605     return 0;
606 fail:
607     for (i = 0; i < 4; i++)
608         av_buffer_pool_uninit(&pool->pools[i]);
609     pool->format = -1;
610     pool->planes = pool->channels = pool->samples = 0;
611     pool->width  = pool->height = 0;
612     return ret;
613 }
614
615 static int audio_get_buffer(AVCodecContext *avctx, AVFrame *frame)
616 {
617     FramePool *pool = avctx->internal->pool;
618     int planes = pool->planes;
619     int i;
620
621     frame->linesize[0] = pool->linesize[0];
622
623     if (planes > AV_NUM_DATA_POINTERS) {
624         frame->extended_data = av_mallocz_array(planes, sizeof(*frame->extended_data));
625         frame->nb_extended_buf = planes - AV_NUM_DATA_POINTERS;
626         frame->extended_buf  = av_mallocz_array(frame->nb_extended_buf,
627                                           sizeof(*frame->extended_buf));
628         if (!frame->extended_data || !frame->extended_buf) {
629             av_freep(&frame->extended_data);
630             av_freep(&frame->extended_buf);
631             return AVERROR(ENOMEM);
632         }
633     } else {
634         frame->extended_data = frame->data;
635         av_assert0(frame->nb_extended_buf == 0);
636     }
637
638     for (i = 0; i < FFMIN(planes, AV_NUM_DATA_POINTERS); i++) {
639         frame->buf[i] = av_buffer_pool_get(pool->pools[0]);
640         if (!frame->buf[i])
641             goto fail;
642         frame->extended_data[i] = frame->data[i] = frame->buf[i]->data;
643     }
644     for (i = 0; i < frame->nb_extended_buf; i++) {
645         frame->extended_buf[i] = av_buffer_pool_get(pool->pools[0]);
646         if (!frame->extended_buf[i])
647             goto fail;
648         frame->extended_data[i + AV_NUM_DATA_POINTERS] = frame->extended_buf[i]->data;
649     }
650
651     if (avctx->debug & FF_DEBUG_BUFFERS)
652         av_log(avctx, AV_LOG_DEBUG, "default_get_buffer called on frame %p", frame);
653
654     return 0;
655 fail:
656     av_frame_unref(frame);
657     return AVERROR(ENOMEM);
658 }
659
660 static int video_get_buffer(AVCodecContext *s, AVFrame *pic)
661 {
662     FramePool *pool = s->internal->pool;
663     int i;
664
665     if (pic->data[0]) {
666         av_log(s, AV_LOG_ERROR, "pic->data[0]!=NULL in avcodec_default_get_buffer\n");
667         return -1;
668     }
669
670     memset(pic->data, 0, sizeof(pic->data));
671     pic->extended_data = pic->data;
672
673     for (i = 0; i < 4 && pool->pools[i]; i++) {
674         pic->linesize[i] = pool->linesize[i];
675
676         pic->buf[i] = av_buffer_pool_get(pool->pools[i]);
677         if (!pic->buf[i])
678             goto fail;
679
680         pic->data[i] = pic->buf[i]->data;
681     }
682     for (; i < AV_NUM_DATA_POINTERS; i++) {
683         pic->data[i] = NULL;
684         pic->linesize[i] = 0;
685     }
686     if (pic->data[1] && !pic->data[2])
687         avpriv_set_systematic_pal2((uint32_t *)pic->data[1], s->pix_fmt);
688
689     if (s->debug & FF_DEBUG_BUFFERS)
690         av_log(s, AV_LOG_DEBUG, "default_get_buffer called on pic %p\n", pic);
691
692     return 0;
693 fail:
694     av_frame_unref(pic);
695     return AVERROR(ENOMEM);
696 }
697
698 void avpriv_color_frame(AVFrame *frame, const int c[4])
699 {
700     const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(frame->format);
701     int p, y, x;
702
703     av_assert0(desc->flags & AV_PIX_FMT_FLAG_PLANAR);
704
705     for (p = 0; p<desc->nb_components; p++) {
706         uint8_t *dst = frame->data[p];
707         int is_chroma = p == 1 || p == 2;
708         int bytes  = is_chroma ? FF_CEIL_RSHIFT(frame->width,  desc->log2_chroma_w) : frame->width;
709         int height = is_chroma ? FF_CEIL_RSHIFT(frame->height, desc->log2_chroma_h) : frame->height;
710         for (y = 0; y < height; y++) {
711             if (desc->comp[0].depth_minus1 >= 8) {
712                 for (x = 0; x<bytes; x++)
713                     ((uint16_t*)dst)[x] = c[p];
714             }else
715                 memset(dst, c[p], bytes);
716             dst += frame->linesize[p];
717         }
718     }
719 }
720
721 int avcodec_default_get_buffer2(AVCodecContext *avctx, AVFrame *frame, int flags)
722 {
723     int ret;
724
725     if ((ret = update_frame_pool(avctx, frame)) < 0)
726         return ret;
727
728 #if FF_API_GET_BUFFER
729 FF_DISABLE_DEPRECATION_WARNINGS
730     frame->type = FF_BUFFER_TYPE_INTERNAL;
731 FF_ENABLE_DEPRECATION_WARNINGS
732 #endif
733
734     switch (avctx->codec_type) {
735     case AVMEDIA_TYPE_VIDEO:
736         return video_get_buffer(avctx, frame);
737     case AVMEDIA_TYPE_AUDIO:
738         return audio_get_buffer(avctx, frame);
739     default:
740         return -1;
741     }
742 }
743
744 static int add_metadata_from_side_data(AVPacket *avpkt, AVFrame *frame)
745 {
746     int size;
747     const uint8_t *side_metadata;
748
749     AVDictionary **frame_md = avpriv_frame_get_metadatap(frame);
750
751     side_metadata = av_packet_get_side_data(avpkt,
752                                             AV_PKT_DATA_STRINGS_METADATA, &size);
753     return av_packet_unpack_dictionary(side_metadata, size, frame_md);
754 }
755
756 int ff_init_buffer_info(AVCodecContext *avctx, AVFrame *frame)
757 {
758     AVPacket *pkt = avctx->internal->pkt;
759     int i;
760     static const struct {
761         enum AVPacketSideDataType packet;
762         enum AVFrameSideDataType frame;
763     } sd[] = {
764         { AV_PKT_DATA_REPLAYGAIN ,   AV_FRAME_DATA_REPLAYGAIN },
765         { AV_PKT_DATA_DISPLAYMATRIX, AV_FRAME_DATA_DISPLAYMATRIX },
766         { AV_PKT_DATA_STEREO3D,      AV_FRAME_DATA_STEREO3D },
767         { AV_PKT_DATA_AUDIO_SERVICE_TYPE, AV_FRAME_DATA_AUDIO_SERVICE_TYPE },
768     };
769
770     if (pkt) {
771         frame->pkt_pts = pkt->pts;
772         av_frame_set_pkt_pos     (frame, pkt->pos);
773         av_frame_set_pkt_duration(frame, pkt->duration);
774         av_frame_set_pkt_size    (frame, pkt->size);
775
776         for (i = 0; i < FF_ARRAY_ELEMS(sd); i++) {
777             int size;
778             uint8_t *packet_sd = av_packet_get_side_data(pkt, sd[i].packet, &size);
779             if (packet_sd) {
780                 AVFrameSideData *frame_sd = av_frame_new_side_data(frame,
781                                                                    sd[i].frame,
782                                                                    size);
783                 if (!frame_sd)
784                     return AVERROR(ENOMEM);
785
786                 memcpy(frame_sd->data, packet_sd, size);
787             }
788         }
789         add_metadata_from_side_data(pkt, frame);
790     } else {
791         frame->pkt_pts = AV_NOPTS_VALUE;
792         av_frame_set_pkt_pos     (frame, -1);
793         av_frame_set_pkt_duration(frame, 0);
794         av_frame_set_pkt_size    (frame, -1);
795     }
796     frame->reordered_opaque = avctx->reordered_opaque;
797
798     if (frame->color_primaries == AVCOL_PRI_UNSPECIFIED)
799         frame->color_primaries = avctx->color_primaries;
800     if (frame->color_trc == AVCOL_TRC_UNSPECIFIED)
801         frame->color_trc = avctx->color_trc;
802     if (av_frame_get_colorspace(frame) == AVCOL_SPC_UNSPECIFIED)
803         av_frame_set_colorspace(frame, avctx->colorspace);
804     if (av_frame_get_color_range(frame) == AVCOL_RANGE_UNSPECIFIED)
805         av_frame_set_color_range(frame, avctx->color_range);
806     if (frame->chroma_location == AVCHROMA_LOC_UNSPECIFIED)
807         frame->chroma_location = avctx->chroma_sample_location;
808
809     switch (avctx->codec->type) {
810     case AVMEDIA_TYPE_VIDEO:
811         frame->format              = avctx->pix_fmt;
812         if (!frame->sample_aspect_ratio.num)
813             frame->sample_aspect_ratio = avctx->sample_aspect_ratio;
814
815         if (frame->width && frame->height &&
816             av_image_check_sar(frame->width, frame->height,
817                                frame->sample_aspect_ratio) < 0) {
818             av_log(avctx, AV_LOG_WARNING, "ignoring invalid SAR: %u/%u\n",
819                    frame->sample_aspect_ratio.num,
820                    frame->sample_aspect_ratio.den);
821             frame->sample_aspect_ratio = (AVRational){ 0, 1 };
822         }
823
824         break;
825     case AVMEDIA_TYPE_AUDIO:
826         if (!frame->sample_rate)
827             frame->sample_rate    = avctx->sample_rate;
828         if (frame->format < 0)
829             frame->format         = avctx->sample_fmt;
830         if (!frame->channel_layout) {
831             if (avctx->channel_layout) {
832                  if (av_get_channel_layout_nb_channels(avctx->channel_layout) !=
833                      avctx->channels) {
834                      av_log(avctx, AV_LOG_ERROR, "Inconsistent channel "
835                             "configuration.\n");
836                      return AVERROR(EINVAL);
837                  }
838
839                 frame->channel_layout = avctx->channel_layout;
840             } else {
841                 if (avctx->channels > FF_SANE_NB_CHANNELS) {
842                     av_log(avctx, AV_LOG_ERROR, "Too many channels: %d.\n",
843                            avctx->channels);
844                     return AVERROR(ENOSYS);
845                 }
846             }
847         }
848         av_frame_set_channels(frame, avctx->channels);
849         break;
850     }
851     return 0;
852 }
853
854 #if FF_API_GET_BUFFER
855 FF_DISABLE_DEPRECATION_WARNINGS
856 int avcodec_default_get_buffer(AVCodecContext *avctx, AVFrame *frame)
857 {
858     return avcodec_default_get_buffer2(avctx, frame, 0);
859 }
860
861 typedef struct CompatReleaseBufPriv {
862     AVCodecContext avctx;
863     AVFrame frame;
864     uint8_t avframe_padding[1024]; // hack to allow linking to a avutil with larger AVFrame
865 } CompatReleaseBufPriv;
866
867 static void compat_free_buffer(void *opaque, uint8_t *data)
868 {
869     CompatReleaseBufPriv *priv = opaque;
870     if (priv->avctx.release_buffer)
871         priv->avctx.release_buffer(&priv->avctx, &priv->frame);
872     av_freep(&priv);
873 }
874
875 static void compat_release_buffer(void *opaque, uint8_t *data)
876 {
877     AVBufferRef *buf = opaque;
878     av_buffer_unref(&buf);
879 }
880 FF_ENABLE_DEPRECATION_WARNINGS
881 #endif
882
883 int ff_decode_frame_props(AVCodecContext *avctx, AVFrame *frame)
884 {
885     return ff_init_buffer_info(avctx, frame);
886 }
887
888 static int get_buffer_internal(AVCodecContext *avctx, AVFrame *frame, int flags)
889 {
890     const AVHWAccel *hwaccel = avctx->hwaccel;
891     int override_dimensions = 1;
892     int ret;
893
894     if (avctx->codec_type == AVMEDIA_TYPE_VIDEO) {
895         if ((ret = av_image_check_size(avctx->width, avctx->height, 0, avctx)) < 0 || avctx->pix_fmt<0) {
896             av_log(avctx, AV_LOG_ERROR, "video_get_buffer: image parameters invalid\n");
897             return AVERROR(EINVAL);
898         }
899     }
900     if (avctx->codec_type == AVMEDIA_TYPE_VIDEO) {
901         if (frame->width <= 0 || frame->height <= 0) {
902             frame->width  = FFMAX(avctx->width,  FF_CEIL_RSHIFT(avctx->coded_width,  avctx->lowres));
903             frame->height = FFMAX(avctx->height, FF_CEIL_RSHIFT(avctx->coded_height, avctx->lowres));
904             override_dimensions = 0;
905         }
906     }
907     ret = ff_decode_frame_props(avctx, frame);
908     if (ret < 0)
909         return ret;
910
911     if (hwaccel) {
912         if (hwaccel->alloc_frame) {
913             ret = hwaccel->alloc_frame(avctx, frame);
914             goto end;
915         }
916     } else
917         avctx->sw_pix_fmt = avctx->pix_fmt;
918
919 #if FF_API_GET_BUFFER
920 FF_DISABLE_DEPRECATION_WARNINGS
921     /*
922      * Wrap an old get_buffer()-allocated buffer in a bunch of AVBuffers.
923      * We wrap each plane in its own AVBuffer. Each of those has a reference to
924      * a dummy AVBuffer as its private data, unreffing it on free.
925      * When all the planes are freed, the dummy buffer's free callback calls
926      * release_buffer().
927      */
928     if (avctx->get_buffer) {
929         CompatReleaseBufPriv *priv = NULL;
930         AVBufferRef *dummy_buf = NULL;
931         int planes, i, ret;
932
933         if (flags & AV_GET_BUFFER_FLAG_REF)
934             frame->reference    = 1;
935
936         ret = avctx->get_buffer(avctx, frame);
937         if (ret < 0)
938             return ret;
939
940         /* return if the buffers are already set up
941          * this would happen e.g. when a custom get_buffer() calls
942          * avcodec_default_get_buffer
943          */
944         if (frame->buf[0])
945             goto end0;
946
947         priv = av_mallocz(sizeof(*priv));
948         if (!priv) {
949             ret = AVERROR(ENOMEM);
950             goto fail;
951         }
952         priv->avctx = *avctx;
953         priv->frame = *frame;
954
955         dummy_buf = av_buffer_create(NULL, 0, compat_free_buffer, priv, 0);
956         if (!dummy_buf) {
957             ret = AVERROR(ENOMEM);
958             goto fail;
959         }
960
961 #define WRAP_PLANE(ref_out, data, data_size)                            \
962 do {                                                                    \
963     AVBufferRef *dummy_ref = av_buffer_ref(dummy_buf);                  \
964     if (!dummy_ref) {                                                   \
965         ret = AVERROR(ENOMEM);                                          \
966         goto fail;                                                      \
967     }                                                                   \
968     ref_out = av_buffer_create(data, data_size, compat_release_buffer,  \
969                                dummy_ref, 0);                           \
970     if (!ref_out) {                                                     \
971         av_buffer_unref(&dummy_ref);                                    \
972         av_frame_unref(frame);                                          \
973         ret = AVERROR(ENOMEM);                                          \
974         goto fail;                                                      \
975     }                                                                   \
976 } while (0)
977
978         if (avctx->codec_type == AVMEDIA_TYPE_VIDEO) {
979             const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(frame->format);
980
981             planes = av_pix_fmt_count_planes(frame->format);
982             /* workaround for AVHWAccel plane count of 0, buf[0] is used as
983                check for allocated buffers: make libavcodec happy */
984             if (desc && desc->flags & AV_PIX_FMT_FLAG_HWACCEL)
985                 planes = 1;
986             if (!desc || planes <= 0) {
987                 ret = AVERROR(EINVAL);
988                 goto fail;
989             }
990
991             for (i = 0; i < planes; i++) {
992                 int v_shift    = (i == 1 || i == 2) ? desc->log2_chroma_h : 0;
993                 int plane_size = (frame->height >> v_shift) * frame->linesize[i];
994
995                 WRAP_PLANE(frame->buf[i], frame->data[i], plane_size);
996             }
997         } else {
998             int planar = av_sample_fmt_is_planar(frame->format);
999             planes = planar ? avctx->channels : 1;
1000
1001             if (planes > FF_ARRAY_ELEMS(frame->buf)) {
1002                 frame->nb_extended_buf = planes - FF_ARRAY_ELEMS(frame->buf);
1003                 frame->extended_buf = av_malloc_array(sizeof(*frame->extended_buf),
1004                                                 frame->nb_extended_buf);
1005                 if (!frame->extended_buf) {
1006                     ret = AVERROR(ENOMEM);
1007                     goto fail;
1008                 }
1009             }
1010
1011             for (i = 0; i < FFMIN(planes, FF_ARRAY_ELEMS(frame->buf)); i++)
1012                 WRAP_PLANE(frame->buf[i], frame->extended_data[i], frame->linesize[0]);
1013
1014             for (i = 0; i < frame->nb_extended_buf; i++)
1015                 WRAP_PLANE(frame->extended_buf[i],
1016                            frame->extended_data[i + FF_ARRAY_ELEMS(frame->buf)],
1017                            frame->linesize[0]);
1018         }
1019
1020         av_buffer_unref(&dummy_buf);
1021
1022 end0:
1023         frame->width  = avctx->width;
1024         frame->height = avctx->height;
1025
1026         return 0;
1027
1028 fail:
1029         avctx->release_buffer(avctx, frame);
1030         av_freep(&priv);
1031         av_buffer_unref(&dummy_buf);
1032         return ret;
1033     }
1034 FF_ENABLE_DEPRECATION_WARNINGS
1035 #endif
1036
1037     ret = avctx->get_buffer2(avctx, frame, flags);
1038
1039 end:
1040     if (avctx->codec_type == AVMEDIA_TYPE_VIDEO && !override_dimensions) {
1041         frame->width  = avctx->width;
1042         frame->height = avctx->height;
1043     }
1044
1045     return ret;
1046 }
1047
1048 int ff_get_buffer(AVCodecContext *avctx, AVFrame *frame, int flags)
1049 {
1050     int ret = get_buffer_internal(avctx, frame, flags);
1051     if (ret < 0)
1052         av_log(avctx, AV_LOG_ERROR, "get_buffer() failed\n");
1053     return ret;
1054 }
1055
1056 static int reget_buffer_internal(AVCodecContext *avctx, AVFrame *frame)
1057 {
1058     AVFrame *tmp;
1059     int ret;
1060
1061     av_assert0(avctx->codec_type == AVMEDIA_TYPE_VIDEO);
1062
1063     if (frame->data[0] && (frame->width != avctx->width || frame->height != avctx->height || frame->format != avctx->pix_fmt)) {
1064         av_log(avctx, AV_LOG_WARNING, "Picture changed from size:%dx%d fmt:%s to size:%dx%d fmt:%s in reget buffer()\n",
1065                frame->width, frame->height, av_get_pix_fmt_name(frame->format), avctx->width, avctx->height, av_get_pix_fmt_name(avctx->pix_fmt));
1066         av_frame_unref(frame);
1067     }
1068
1069     ff_init_buffer_info(avctx, frame);
1070
1071     if (!frame->data[0])
1072         return ff_get_buffer(avctx, frame, AV_GET_BUFFER_FLAG_REF);
1073
1074     if (av_frame_is_writable(frame))
1075         return ff_decode_frame_props(avctx, frame);
1076
1077     tmp = av_frame_alloc();
1078     if (!tmp)
1079         return AVERROR(ENOMEM);
1080
1081     av_frame_move_ref(tmp, frame);
1082
1083     ret = ff_get_buffer(avctx, frame, AV_GET_BUFFER_FLAG_REF);
1084     if (ret < 0) {
1085         av_frame_free(&tmp);
1086         return ret;
1087     }
1088
1089     av_frame_copy(frame, tmp);
1090     av_frame_free(&tmp);
1091
1092     return 0;
1093 }
1094
1095 int ff_reget_buffer(AVCodecContext *avctx, AVFrame *frame)
1096 {
1097     int ret = reget_buffer_internal(avctx, frame);
1098     if (ret < 0)
1099         av_log(avctx, AV_LOG_ERROR, "reget_buffer() failed\n");
1100     return ret;
1101 }
1102
1103 #if FF_API_GET_BUFFER
1104 void avcodec_default_release_buffer(AVCodecContext *s, AVFrame *pic)
1105 {
1106     av_assert0(s->codec_type == AVMEDIA_TYPE_VIDEO);
1107
1108     av_frame_unref(pic);
1109 }
1110
1111 int avcodec_default_reget_buffer(AVCodecContext *s, AVFrame *pic)
1112 {
1113     av_assert0(0);
1114     return AVERROR_BUG;
1115 }
1116 #endif
1117
1118 int avcodec_default_execute(AVCodecContext *c, int (*func)(AVCodecContext *c2, void *arg2), void *arg, int *ret, int count, int size)
1119 {
1120     int i;
1121
1122     for (i = 0; i < count; i++) {
1123         int r = func(c, (char *)arg + i * size);
1124         if (ret)
1125             ret[i] = r;
1126     }
1127     return 0;
1128 }
1129
1130 int avcodec_default_execute2(AVCodecContext *c, int (*func)(AVCodecContext *c2, void *arg2, int jobnr, int threadnr), void *arg, int *ret, int count)
1131 {
1132     int i;
1133
1134     for (i = 0; i < count; i++) {
1135         int r = func(c, arg, i, 0);
1136         if (ret)
1137             ret[i] = r;
1138     }
1139     return 0;
1140 }
1141
1142 enum AVPixelFormat avpriv_find_pix_fmt(const PixelFormatTag *tags,
1143                                        unsigned int fourcc)
1144 {
1145     while (tags->pix_fmt >= 0) {
1146         if (tags->fourcc == fourcc)
1147             return tags->pix_fmt;
1148         tags++;
1149     }
1150     return AV_PIX_FMT_NONE;
1151 }
1152
1153 static int is_hwaccel_pix_fmt(enum AVPixelFormat pix_fmt)
1154 {
1155     const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(pix_fmt);
1156     return desc->flags & AV_PIX_FMT_FLAG_HWACCEL;
1157 }
1158
1159 enum AVPixelFormat avcodec_default_get_format(struct AVCodecContext *s, const enum AVPixelFormat *fmt)
1160 {
1161     while (*fmt != AV_PIX_FMT_NONE && is_hwaccel_pix_fmt(*fmt))
1162         ++fmt;
1163     return fmt[0];
1164 }
1165
1166 static AVHWAccel *find_hwaccel(enum AVCodecID codec_id,
1167                                enum AVPixelFormat pix_fmt)
1168 {
1169     AVHWAccel *hwaccel = NULL;
1170
1171     while ((hwaccel = av_hwaccel_next(hwaccel)))
1172         if (hwaccel->id == codec_id
1173             && hwaccel->pix_fmt == pix_fmt)
1174             return hwaccel;
1175     return NULL;
1176 }
1177
1178 static int setup_hwaccel(AVCodecContext *avctx,
1179                          const enum AVPixelFormat fmt,
1180                          const char *name)
1181 {
1182     AVHWAccel *hwa = find_hwaccel(avctx->codec_id, fmt);
1183     int ret        = 0;
1184
1185     if (!hwa) {
1186         av_log(avctx, AV_LOG_ERROR,
1187                "Could not find an AVHWAccel for the pixel format: %s",
1188                name);
1189         return AVERROR(ENOENT);
1190     }
1191
1192     if (hwa->capabilities & HWACCEL_CODEC_CAP_EXPERIMENTAL &&
1193         avctx->strict_std_compliance > FF_COMPLIANCE_EXPERIMENTAL) {
1194         av_log(avctx, AV_LOG_WARNING, "Ignoring experimental hwaccel: %s\n",
1195                hwa->name);
1196         return AVERROR_PATCHWELCOME;
1197     }
1198
1199     if (hwa->priv_data_size) {
1200         avctx->internal->hwaccel_priv_data = av_mallocz(hwa->priv_data_size);
1201         if (!avctx->internal->hwaccel_priv_data)
1202             return AVERROR(ENOMEM);
1203     }
1204
1205     if (hwa->init) {
1206         ret = hwa->init(avctx);
1207         if (ret < 0) {
1208             av_freep(&avctx->internal->hwaccel_priv_data);
1209             return ret;
1210         }
1211     }
1212
1213     avctx->hwaccel = hwa;
1214
1215     return 0;
1216 }
1217
1218 int ff_get_format(AVCodecContext *avctx, const enum AVPixelFormat *fmt)
1219 {
1220     const AVPixFmtDescriptor *desc;
1221     enum AVPixelFormat *choices;
1222     enum AVPixelFormat ret;
1223     unsigned n = 0;
1224
1225     while (fmt[n] != AV_PIX_FMT_NONE)
1226         ++n;
1227
1228     av_assert0(n >= 1);
1229     avctx->sw_pix_fmt = fmt[n - 1];
1230     av_assert2(!is_hwaccel_pix_fmt(avctx->sw_pix_fmt));
1231
1232     choices = av_malloc_array(n + 1, sizeof(*choices));
1233     if (!choices)
1234         return AV_PIX_FMT_NONE;
1235
1236     memcpy(choices, fmt, (n + 1) * sizeof(*choices));
1237
1238     for (;;) {
1239         if (avctx->hwaccel && avctx->hwaccel->uninit)
1240             avctx->hwaccel->uninit(avctx);
1241         av_freep(&avctx->internal->hwaccel_priv_data);
1242         avctx->hwaccel = NULL;
1243
1244         ret = avctx->get_format(avctx, choices);
1245
1246         desc = av_pix_fmt_desc_get(ret);
1247         if (!desc) {
1248             ret = AV_PIX_FMT_NONE;
1249             break;
1250         }
1251
1252         if (!(desc->flags & AV_PIX_FMT_FLAG_HWACCEL))
1253             break;
1254         if (avctx->codec->capabilities&CODEC_CAP_HWACCEL_VDPAU)
1255             break;
1256
1257         if (!setup_hwaccel(avctx, ret, desc->name))
1258             break;
1259
1260         /* Remove failed hwaccel from choices */
1261         for (n = 0; choices[n] != ret; n++)
1262             av_assert0(choices[n] != AV_PIX_FMT_NONE);
1263
1264         do
1265             choices[n] = choices[n + 1];
1266         while (choices[n++] != AV_PIX_FMT_NONE);
1267     }
1268
1269     av_freep(&choices);
1270     return ret;
1271 }
1272
1273 #if FF_API_AVFRAME_LAVC
1274 void avcodec_get_frame_defaults(AVFrame *frame)
1275 {
1276 #if LIBAVCODEC_VERSION_MAJOR >= 55
1277      // extended_data should explicitly be freed when needed, this code is unsafe currently
1278      // also this is not compatible to the <55 ABI/API
1279     if (frame->extended_data != frame->data && 0)
1280         av_freep(&frame->extended_data);
1281 #endif
1282
1283     memset(frame, 0, sizeof(AVFrame));
1284     av_frame_unref(frame);
1285 }
1286
1287 AVFrame *avcodec_alloc_frame(void)
1288 {
1289     return av_frame_alloc();
1290 }
1291
1292 void avcodec_free_frame(AVFrame **frame)
1293 {
1294     av_frame_free(frame);
1295 }
1296 #endif
1297
1298 MAKE_ACCESSORS(AVCodecContext, codec, AVRational, pkt_timebase)
1299 MAKE_ACCESSORS(AVCodecContext, codec, const AVCodecDescriptor *, codec_descriptor)
1300 MAKE_ACCESSORS(AVCodecContext, codec, int, lowres)
1301 MAKE_ACCESSORS(AVCodecContext, codec, int, seek_preroll)
1302 MAKE_ACCESSORS(AVCodecContext, codec, uint16_t*, chroma_intra_matrix)
1303
1304 int av_codec_get_max_lowres(const AVCodec *codec)
1305 {
1306     return codec->max_lowres;
1307 }
1308
1309 static void get_subtitle_defaults(AVSubtitle *sub)
1310 {
1311     memset(sub, 0, sizeof(*sub));
1312     sub->pts = AV_NOPTS_VALUE;
1313 }
1314
1315 static int get_bit_rate(AVCodecContext *ctx)
1316 {
1317     int bit_rate;
1318     int bits_per_sample;
1319
1320     switch (ctx->codec_type) {
1321     case AVMEDIA_TYPE_VIDEO:
1322     case AVMEDIA_TYPE_DATA:
1323     case AVMEDIA_TYPE_SUBTITLE:
1324     case AVMEDIA_TYPE_ATTACHMENT:
1325         bit_rate = ctx->bit_rate;
1326         break;
1327     case AVMEDIA_TYPE_AUDIO:
1328         bits_per_sample = av_get_bits_per_sample(ctx->codec_id);
1329         bit_rate = bits_per_sample ? ctx->sample_rate * ctx->channels * bits_per_sample : ctx->bit_rate;
1330         break;
1331     default:
1332         bit_rate = 0;
1333         break;
1334     }
1335     return bit_rate;
1336 }
1337
1338 int attribute_align_arg ff_codec_open2_recursive(AVCodecContext *avctx, const AVCodec *codec, AVDictionary **options)
1339 {
1340     int ret = 0;
1341
1342     ff_unlock_avcodec();
1343
1344     ret = avcodec_open2(avctx, codec, options);
1345
1346     ff_lock_avcodec(avctx, codec);
1347     return ret;
1348 }
1349
1350 int attribute_align_arg avcodec_open2(AVCodecContext *avctx, const AVCodec *codec, AVDictionary **options)
1351 {
1352     int ret = 0;
1353     AVDictionary *tmp = NULL;
1354
1355     if (avcodec_is_open(avctx))
1356         return 0;
1357
1358     if ((!codec && !avctx->codec)) {
1359         av_log(avctx, AV_LOG_ERROR, "No codec provided to avcodec_open2()\n");
1360         return AVERROR(EINVAL);
1361     }
1362     if ((codec && avctx->codec && codec != avctx->codec)) {
1363         av_log(avctx, AV_LOG_ERROR, "This AVCodecContext was allocated for %s, "
1364                                     "but %s passed to avcodec_open2()\n", avctx->codec->name, codec->name);
1365         return AVERROR(EINVAL);
1366     }
1367     if (!codec)
1368         codec = avctx->codec;
1369
1370     if (avctx->extradata_size < 0 || avctx->extradata_size >= FF_MAX_EXTRADATA_SIZE)
1371         return AVERROR(EINVAL);
1372
1373     if (options)
1374         av_dict_copy(&tmp, *options, 0);
1375
1376     ret = ff_lock_avcodec(avctx, codec);
1377     if (ret < 0)
1378         return ret;
1379
1380     avctx->internal = av_mallocz(sizeof(AVCodecInternal));
1381     if (!avctx->internal) {
1382         ret = AVERROR(ENOMEM);
1383         goto end;
1384     }
1385
1386     avctx->internal->pool = av_mallocz(sizeof(*avctx->internal->pool));
1387     if (!avctx->internal->pool) {
1388         ret = AVERROR(ENOMEM);
1389         goto free_and_end;
1390     }
1391
1392     avctx->internal->to_free = av_frame_alloc();
1393     if (!avctx->internal->to_free) {
1394         ret = AVERROR(ENOMEM);
1395         goto free_and_end;
1396     }
1397
1398     if (codec->priv_data_size > 0) {
1399         if (!avctx->priv_data) {
1400             avctx->priv_data = av_mallocz(codec->priv_data_size);
1401             if (!avctx->priv_data) {
1402                 ret = AVERROR(ENOMEM);
1403                 goto end;
1404             }
1405             if (codec->priv_class) {
1406                 *(const AVClass **)avctx->priv_data = codec->priv_class;
1407                 av_opt_set_defaults(avctx->priv_data);
1408             }
1409         }
1410         if (codec->priv_class && (ret = av_opt_set_dict(avctx->priv_data, &tmp)) < 0)
1411             goto free_and_end;
1412     } else {
1413         avctx->priv_data = NULL;
1414     }
1415     if ((ret = av_opt_set_dict(avctx, &tmp)) < 0)
1416         goto free_and_end;
1417
1418     if (avctx->codec_whitelist && av_match_list(codec->name, avctx->codec_whitelist, ',') <= 0) {
1419         av_log(avctx, AV_LOG_ERROR, "Codec (%s) not on whitelist\n", codec->name);
1420         ret = AVERROR(EINVAL);
1421         goto free_and_end;
1422     }
1423
1424     // only call ff_set_dimensions() for non H.264/VP6F codecs so as not to overwrite previously setup dimensions
1425     if (!(avctx->coded_width && avctx->coded_height && avctx->width && avctx->height &&
1426           (avctx->codec_id == AV_CODEC_ID_H264 || avctx->codec_id == AV_CODEC_ID_VP6F))) {
1427     if (avctx->coded_width && avctx->coded_height)
1428         ret = ff_set_dimensions(avctx, avctx->coded_width, avctx->coded_height);
1429     else if (avctx->width && avctx->height)
1430         ret = ff_set_dimensions(avctx, avctx->width, avctx->height);
1431     if (ret < 0)
1432         goto free_and_end;
1433     }
1434
1435     if ((avctx->coded_width || avctx->coded_height || avctx->width || avctx->height)
1436         && (  av_image_check_size(avctx->coded_width, avctx->coded_height, 0, avctx) < 0
1437            || av_image_check_size(avctx->width,       avctx->height,       0, avctx) < 0)) {
1438         av_log(avctx, AV_LOG_WARNING, "Ignoring invalid width/height values\n");
1439         ff_set_dimensions(avctx, 0, 0);
1440     }
1441
1442     if (avctx->width > 0 && avctx->height > 0) {
1443         if (av_image_check_sar(avctx->width, avctx->height,
1444                                avctx->sample_aspect_ratio) < 0) {
1445             av_log(avctx, AV_LOG_WARNING, "ignoring invalid SAR: %u/%u\n",
1446                    avctx->sample_aspect_ratio.num,
1447                    avctx->sample_aspect_ratio.den);
1448             avctx->sample_aspect_ratio = (AVRational){ 0, 1 };
1449         }
1450     }
1451
1452     /* if the decoder init function was already called previously,
1453      * free the already allocated subtitle_header before overwriting it */
1454     if (av_codec_is_decoder(codec))
1455         av_freep(&avctx->subtitle_header);
1456
1457     if (avctx->channels > FF_SANE_NB_CHANNELS) {
1458         ret = AVERROR(EINVAL);
1459         goto free_and_end;
1460     }
1461
1462     avctx->codec = codec;
1463     if ((avctx->codec_type == AVMEDIA_TYPE_UNKNOWN || avctx->codec_type == codec->type) &&
1464         avctx->codec_id == AV_CODEC_ID_NONE) {
1465         avctx->codec_type = codec->type;
1466         avctx->codec_id   = codec->id;
1467     }
1468     if (avctx->codec_id != codec->id || (avctx->codec_type != codec->type
1469                                          && avctx->codec_type != AVMEDIA_TYPE_ATTACHMENT)) {
1470         av_log(avctx, AV_LOG_ERROR, "Codec type or id mismatches\n");
1471         ret = AVERROR(EINVAL);
1472         goto free_and_end;
1473     }
1474     avctx->frame_number = 0;
1475     avctx->codec_descriptor = avcodec_descriptor_get(avctx->codec_id);
1476
1477     if (avctx->codec->capabilities & CODEC_CAP_EXPERIMENTAL &&
1478         avctx->strict_std_compliance > FF_COMPLIANCE_EXPERIMENTAL) {
1479         const char *codec_string = av_codec_is_encoder(codec) ? "encoder" : "decoder";
1480         AVCodec *codec2;
1481         av_log(avctx, AV_LOG_ERROR,
1482                "The %s '%s' is experimental but experimental codecs are not enabled, "
1483                "add '-strict %d' if you want to use it.\n",
1484                codec_string, codec->name, FF_COMPLIANCE_EXPERIMENTAL);
1485         codec2 = av_codec_is_encoder(codec) ? avcodec_find_encoder(codec->id) : avcodec_find_decoder(codec->id);
1486         if (!(codec2->capabilities & CODEC_CAP_EXPERIMENTAL))
1487             av_log(avctx, AV_LOG_ERROR, "Alternatively use the non experimental %s '%s'.\n",
1488                 codec_string, codec2->name);
1489         ret = AVERROR_EXPERIMENTAL;
1490         goto free_and_end;
1491     }
1492
1493     if (avctx->codec_type == AVMEDIA_TYPE_AUDIO &&
1494         (!avctx->time_base.num || !avctx->time_base.den)) {
1495         avctx->time_base.num = 1;
1496         avctx->time_base.den = avctx->sample_rate;
1497     }
1498
1499     if (!HAVE_THREADS)
1500         av_log(avctx, AV_LOG_WARNING, "Warning: not compiled with thread support, using thread emulation\n");
1501
1502     if (CONFIG_FRAME_THREAD_ENCODER) {
1503         ff_unlock_avcodec(); //we will instanciate a few encoders thus kick the counter to prevent false detection of a problem
1504         ret = ff_frame_thread_encoder_init(avctx, options ? *options : NULL);
1505         ff_lock_avcodec(avctx, codec);
1506         if (ret < 0)
1507             goto free_and_end;
1508     }
1509
1510     if (HAVE_THREADS
1511         && !(avctx->internal->frame_thread_encoder && (avctx->active_thread_type&FF_THREAD_FRAME))) {
1512         ret = ff_thread_init(avctx);
1513         if (ret < 0) {
1514             goto free_and_end;
1515         }
1516     }
1517     if (!HAVE_THREADS && !(codec->capabilities & CODEC_CAP_AUTO_THREADS))
1518         avctx->thread_count = 1;
1519
1520     if (avctx->codec->max_lowres < avctx->lowres || avctx->lowres < 0) {
1521         av_log(avctx, AV_LOG_ERROR, "The maximum value for lowres supported by the decoder is %d\n",
1522                avctx->codec->max_lowres);
1523         ret = AVERROR(EINVAL);
1524         goto free_and_end;
1525     }
1526
1527 #if FF_API_VISMV
1528     if (avctx->debug_mv)
1529         av_log(avctx, AV_LOG_WARNING, "The 'vismv' option is deprecated, "
1530                "see the codecview filter instead.\n");
1531 #endif
1532
1533     if (av_codec_is_encoder(avctx->codec)) {
1534         int i;
1535         if (avctx->codec->sample_fmts) {
1536             for (i = 0; avctx->codec->sample_fmts[i] != AV_SAMPLE_FMT_NONE; i++) {
1537                 if (avctx->sample_fmt == avctx->codec->sample_fmts[i])
1538                     break;
1539                 if (avctx->channels == 1 &&
1540                     av_get_planar_sample_fmt(avctx->sample_fmt) ==
1541                     av_get_planar_sample_fmt(avctx->codec->sample_fmts[i])) {
1542                     avctx->sample_fmt = avctx->codec->sample_fmts[i];
1543                     break;
1544                 }
1545             }
1546             if (avctx->codec->sample_fmts[i] == AV_SAMPLE_FMT_NONE) {
1547                 char buf[128];
1548                 snprintf(buf, sizeof(buf), "%d", avctx->sample_fmt);
1549                 av_log(avctx, AV_LOG_ERROR, "Specified sample format %s is invalid or not supported\n",
1550                        (char *)av_x_if_null(av_get_sample_fmt_name(avctx->sample_fmt), buf));
1551                 ret = AVERROR(EINVAL);
1552                 goto free_and_end;
1553             }
1554         }
1555         if (avctx->codec->pix_fmts) {
1556             for (i = 0; avctx->codec->pix_fmts[i] != AV_PIX_FMT_NONE; i++)
1557                 if (avctx->pix_fmt == avctx->codec->pix_fmts[i])
1558                     break;
1559             if (avctx->codec->pix_fmts[i] == AV_PIX_FMT_NONE
1560                 && !((avctx->codec_id == AV_CODEC_ID_MJPEG || avctx->codec_id == AV_CODEC_ID_LJPEG)
1561                      && avctx->strict_std_compliance <= FF_COMPLIANCE_UNOFFICIAL)) {
1562                 char buf[128];
1563                 snprintf(buf, sizeof(buf), "%d", avctx->pix_fmt);
1564                 av_log(avctx, AV_LOG_ERROR, "Specified pixel format %s is invalid or not supported\n",
1565                        (char *)av_x_if_null(av_get_pix_fmt_name(avctx->pix_fmt), buf));
1566                 ret = AVERROR(EINVAL);
1567                 goto free_and_end;
1568             }
1569             if (avctx->codec->pix_fmts[i] == AV_PIX_FMT_YUVJ420P ||
1570                 avctx->codec->pix_fmts[i] == AV_PIX_FMT_YUVJ411P ||
1571                 avctx->codec->pix_fmts[i] == AV_PIX_FMT_YUVJ422P ||
1572                 avctx->codec->pix_fmts[i] == AV_PIX_FMT_YUVJ440P ||
1573                 avctx->codec->pix_fmts[i] == AV_PIX_FMT_YUVJ444P)
1574                 avctx->color_range = AVCOL_RANGE_JPEG;
1575         }
1576         if (avctx->codec->supported_samplerates) {
1577             for (i = 0; avctx->codec->supported_samplerates[i] != 0; i++)
1578                 if (avctx->sample_rate == avctx->codec->supported_samplerates[i])
1579                     break;
1580             if (avctx->codec->supported_samplerates[i] == 0) {
1581                 av_log(avctx, AV_LOG_ERROR, "Specified sample rate %d is not supported\n",
1582                        avctx->sample_rate);
1583                 ret = AVERROR(EINVAL);
1584                 goto free_and_end;
1585             }
1586         }
1587         if (avctx->codec->channel_layouts) {
1588             if (!avctx->channel_layout) {
1589                 av_log(avctx, AV_LOG_WARNING, "Channel layout not specified\n");
1590             } else {
1591                 for (i = 0; avctx->codec->channel_layouts[i] != 0; i++)
1592                     if (avctx->channel_layout == avctx->codec->channel_layouts[i])
1593                         break;
1594                 if (avctx->codec->channel_layouts[i] == 0) {
1595                     char buf[512];
1596                     av_get_channel_layout_string(buf, sizeof(buf), -1, avctx->channel_layout);
1597                     av_log(avctx, AV_LOG_ERROR, "Specified channel layout '%s' is not supported\n", buf);
1598                     ret = AVERROR(EINVAL);
1599                     goto free_and_end;
1600                 }
1601             }
1602         }
1603         if (avctx->channel_layout && avctx->channels) {
1604             int channels = av_get_channel_layout_nb_channels(avctx->channel_layout);
1605             if (channels != avctx->channels) {
1606                 char buf[512];
1607                 av_get_channel_layout_string(buf, sizeof(buf), -1, avctx->channel_layout);
1608                 av_log(avctx, AV_LOG_ERROR,
1609                        "Channel layout '%s' with %d channels does not match number of specified channels %d\n",
1610                        buf, channels, avctx->channels);
1611                 ret = AVERROR(EINVAL);
1612                 goto free_and_end;
1613             }
1614         } else if (avctx->channel_layout) {
1615             avctx->channels = av_get_channel_layout_nb_channels(avctx->channel_layout);
1616         }
1617         if(avctx->codec_type == AVMEDIA_TYPE_VIDEO) {
1618             if (avctx->width <= 0 || avctx->height <= 0) {
1619                 av_log(avctx, AV_LOG_ERROR, "dimensions not set\n");
1620                 ret = AVERROR(EINVAL);
1621                 goto free_and_end;
1622             }
1623         }
1624         if (   (avctx->codec_type == AVMEDIA_TYPE_VIDEO || avctx->codec_type == AVMEDIA_TYPE_AUDIO)
1625             && avctx->bit_rate>0 && avctx->bit_rate<1000) {
1626             av_log(avctx, AV_LOG_WARNING, "Bitrate %d is extremely low, maybe you mean %dk\n", avctx->bit_rate, avctx->bit_rate);
1627         }
1628
1629         if (!avctx->rc_initial_buffer_occupancy)
1630             avctx->rc_initial_buffer_occupancy = avctx->rc_buffer_size * 3 / 4;
1631     }
1632
1633     avctx->pts_correction_num_faulty_pts =
1634     avctx->pts_correction_num_faulty_dts = 0;
1635     avctx->pts_correction_last_pts =
1636     avctx->pts_correction_last_dts = INT64_MIN;
1637
1638     if (   !CONFIG_GRAY && avctx->flags & CODEC_FLAG_GRAY
1639         && avctx->codec_descriptor->type == AVMEDIA_TYPE_VIDEO)
1640         av_log(avctx, AV_LOG_WARNING,
1641                "gray decoding requested but not enabled at configuration time\n");
1642
1643     if (   avctx->codec->init && (!(avctx->active_thread_type&FF_THREAD_FRAME)
1644         || avctx->internal->frame_thread_encoder)) {
1645         ret = avctx->codec->init(avctx);
1646         if (ret < 0) {
1647             goto free_and_end;
1648         }
1649     }
1650
1651     ret=0;
1652
1653 #if FF_API_AUDIOENC_DELAY
1654     if (av_codec_is_encoder(avctx->codec))
1655         avctx->delay = avctx->initial_padding;
1656 #endif
1657
1658     if (av_codec_is_decoder(avctx->codec)) {
1659         if (!avctx->bit_rate)
1660             avctx->bit_rate = get_bit_rate(avctx);
1661         /* validate channel layout from the decoder */
1662         if (avctx->channel_layout) {
1663             int channels = av_get_channel_layout_nb_channels(avctx->channel_layout);
1664             if (!avctx->channels)
1665                 avctx->channels = channels;
1666             else if (channels != avctx->channels) {
1667                 char buf[512];
1668                 av_get_channel_layout_string(buf, sizeof(buf), -1, avctx->channel_layout);
1669                 av_log(avctx, AV_LOG_WARNING,
1670                        "Channel layout '%s' with %d channels does not match specified number of channels %d: "
1671                        "ignoring specified channel layout\n",
1672                        buf, channels, avctx->channels);
1673                 avctx->channel_layout = 0;
1674             }
1675         }
1676         if (avctx->channels && avctx->channels < 0 ||
1677             avctx->channels > FF_SANE_NB_CHANNELS) {
1678             ret = AVERROR(EINVAL);
1679             goto free_and_end;
1680         }
1681         if (avctx->sub_charenc) {
1682             if (avctx->codec_type != AVMEDIA_TYPE_SUBTITLE) {
1683                 av_log(avctx, AV_LOG_ERROR, "Character encoding is only "
1684                        "supported with subtitles codecs\n");
1685                 ret = AVERROR(EINVAL);
1686                 goto free_and_end;
1687             } else if (avctx->codec_descriptor->props & AV_CODEC_PROP_BITMAP_SUB) {
1688                 av_log(avctx, AV_LOG_WARNING, "Codec '%s' is bitmap-based, "
1689                        "subtitles character encoding will be ignored\n",
1690                        avctx->codec_descriptor->name);
1691                 avctx->sub_charenc_mode = FF_SUB_CHARENC_MODE_DO_NOTHING;
1692             } else {
1693                 /* input character encoding is set for a text based subtitle
1694                  * codec at this point */
1695                 if (avctx->sub_charenc_mode == FF_SUB_CHARENC_MODE_AUTOMATIC)
1696                     avctx->sub_charenc_mode = FF_SUB_CHARENC_MODE_PRE_DECODER;
1697
1698                 if (avctx->sub_charenc_mode == FF_SUB_CHARENC_MODE_PRE_DECODER) {
1699 #if CONFIG_ICONV
1700                     iconv_t cd = iconv_open("UTF-8", avctx->sub_charenc);
1701                     if (cd == (iconv_t)-1) {
1702                         ret = AVERROR(errno);
1703                         av_log(avctx, AV_LOG_ERROR, "Unable to open iconv context "
1704                                "with input character encoding \"%s\"\n", avctx->sub_charenc);
1705                         goto free_and_end;
1706                     }
1707                     iconv_close(cd);
1708 #else
1709                     av_log(avctx, AV_LOG_ERROR, "Character encoding subtitles "
1710                            "conversion needs a libavcodec built with iconv support "
1711                            "for this codec\n");
1712                     ret = AVERROR(ENOSYS);
1713                     goto free_and_end;
1714 #endif
1715                 }
1716             }
1717         }
1718
1719 #if FF_API_AVCTX_TIMEBASE
1720         if (avctx->framerate.num > 0 && avctx->framerate.den > 0)
1721             avctx->time_base = av_inv_q(av_mul_q(avctx->framerate, (AVRational){avctx->ticks_per_frame, 1}));
1722 #endif
1723     }
1724     if (codec->priv_data_size > 0 && avctx->priv_data && codec->priv_class) {
1725         av_assert0(*(const AVClass **)avctx->priv_data == codec->priv_class);
1726     }
1727
1728 end:
1729     ff_unlock_avcodec();
1730     if (options) {
1731         av_dict_free(options);
1732         *options = tmp;
1733     }
1734
1735     return ret;
1736 free_and_end:
1737     if (avctx->codec &&
1738         (avctx->codec->caps_internal & FF_CODEC_CAP_INIT_CLEANUP))
1739         avctx->codec->close(avctx);
1740
1741     if (codec->priv_class && codec->priv_data_size)
1742         av_opt_free(avctx->priv_data);
1743     av_opt_free(avctx);
1744
1745     av_dict_free(&tmp);
1746     av_freep(&avctx->priv_data);
1747     if (avctx->internal) {
1748         av_frame_free(&avctx->internal->to_free);
1749         av_freep(&avctx->internal->pool);
1750     }
1751     av_freep(&avctx->internal);
1752     avctx->codec = NULL;
1753     goto end;
1754 }
1755
1756 int ff_alloc_packet2(AVCodecContext *avctx, AVPacket *avpkt, int64_t size)
1757 {
1758     if (avpkt->size < 0) {
1759         av_log(avctx, AV_LOG_ERROR, "Invalid negative user packet size %d\n", avpkt->size);
1760         return AVERROR(EINVAL);
1761     }
1762     if (size < 0 || size > INT_MAX - FF_INPUT_BUFFER_PADDING_SIZE) {
1763         av_log(avctx, AV_LOG_ERROR, "Invalid minimum required packet size %"PRId64" (max allowed is %d)\n",
1764                size, INT_MAX - FF_INPUT_BUFFER_PADDING_SIZE);
1765         return AVERROR(EINVAL);
1766     }
1767
1768     if (avctx) {
1769         av_assert0(!avpkt->data || avpkt->data != avctx->internal->byte_buffer);
1770         if (!avpkt->data || avpkt->size < size) {
1771             av_fast_padded_malloc(&avctx->internal->byte_buffer, &avctx->internal->byte_buffer_size, size);
1772             avpkt->data = avctx->internal->byte_buffer;
1773             avpkt->size = avctx->internal->byte_buffer_size;
1774 #if FF_API_DESTRUCT_PACKET
1775 FF_DISABLE_DEPRECATION_WARNINGS
1776             avpkt->destruct = NULL;
1777 FF_ENABLE_DEPRECATION_WARNINGS
1778 #endif
1779         }
1780     }
1781
1782     if (avpkt->data) {
1783         AVBufferRef *buf = avpkt->buf;
1784 #if FF_API_DESTRUCT_PACKET
1785 FF_DISABLE_DEPRECATION_WARNINGS
1786         void *destruct = avpkt->destruct;
1787 FF_ENABLE_DEPRECATION_WARNINGS
1788 #endif
1789
1790         if (avpkt->size < size) {
1791             av_log(avctx, AV_LOG_ERROR, "User packet is too small (%d < %"PRId64")\n", avpkt->size, size);
1792             return AVERROR(EINVAL);
1793         }
1794
1795         av_init_packet(avpkt);
1796 #if FF_API_DESTRUCT_PACKET
1797 FF_DISABLE_DEPRECATION_WARNINGS
1798         avpkt->destruct = destruct;
1799 FF_ENABLE_DEPRECATION_WARNINGS
1800 #endif
1801         avpkt->buf      = buf;
1802         avpkt->size     = size;
1803         return 0;
1804     } else {
1805         int ret = av_new_packet(avpkt, size);
1806         if (ret < 0)
1807             av_log(avctx, AV_LOG_ERROR, "Failed to allocate packet of size %"PRId64"\n", size);
1808         return ret;
1809     }
1810 }
1811
1812 int ff_alloc_packet(AVPacket *avpkt, int size)
1813 {
1814     return ff_alloc_packet2(NULL, avpkt, size);
1815 }
1816
1817 /**
1818  * Pad last frame with silence.
1819  */
1820 static int pad_last_frame(AVCodecContext *s, AVFrame **dst, const AVFrame *src)
1821 {
1822     AVFrame *frame = NULL;
1823     int ret;
1824
1825     if (!(frame = av_frame_alloc()))
1826         return AVERROR(ENOMEM);
1827
1828     frame->format         = src->format;
1829     frame->channel_layout = src->channel_layout;
1830     av_frame_set_channels(frame, av_frame_get_channels(src));
1831     frame->nb_samples     = s->frame_size;
1832     ret = av_frame_get_buffer(frame, 32);
1833     if (ret < 0)
1834         goto fail;
1835
1836     ret = av_frame_copy_props(frame, src);
1837     if (ret < 0)
1838         goto fail;
1839
1840     if ((ret = av_samples_copy(frame->extended_data, src->extended_data, 0, 0,
1841                                src->nb_samples, s->channels, s->sample_fmt)) < 0)
1842         goto fail;
1843     if ((ret = av_samples_set_silence(frame->extended_data, src->nb_samples,
1844                                       frame->nb_samples - src->nb_samples,
1845                                       s->channels, s->sample_fmt)) < 0)
1846         goto fail;
1847
1848     *dst = frame;
1849
1850     return 0;
1851
1852 fail:
1853     av_frame_free(&frame);
1854     return ret;
1855 }
1856
1857 int attribute_align_arg avcodec_encode_audio2(AVCodecContext *avctx,
1858                                               AVPacket *avpkt,
1859                                               const AVFrame *frame,
1860                                               int *got_packet_ptr)
1861 {
1862     AVFrame *extended_frame = NULL;
1863     AVFrame *padded_frame = NULL;
1864     int ret;
1865     AVPacket user_pkt = *avpkt;
1866     int needs_realloc = !user_pkt.data;
1867
1868     *got_packet_ptr = 0;
1869
1870     if (!(avctx->codec->capabilities & CODEC_CAP_DELAY) && !frame) {
1871         av_free_packet(avpkt);
1872         av_init_packet(avpkt);
1873         return 0;
1874     }
1875
1876     /* ensure that extended_data is properly set */
1877     if (frame && !frame->extended_data) {
1878         if (av_sample_fmt_is_planar(avctx->sample_fmt) &&
1879             avctx->channels > AV_NUM_DATA_POINTERS) {
1880             av_log(avctx, AV_LOG_ERROR, "Encoding to a planar sample format, "
1881                                         "with more than %d channels, but extended_data is not set.\n",
1882                    AV_NUM_DATA_POINTERS);
1883             return AVERROR(EINVAL);
1884         }
1885         av_log(avctx, AV_LOG_WARNING, "extended_data is not set.\n");
1886
1887         extended_frame = av_frame_alloc();
1888         if (!extended_frame)
1889             return AVERROR(ENOMEM);
1890
1891         memcpy(extended_frame, frame, sizeof(AVFrame));
1892         extended_frame->extended_data = extended_frame->data;
1893         frame = extended_frame;
1894     }
1895
1896     /* extract audio service type metadata */
1897     if (frame) {
1898         AVFrameSideData *sd = av_frame_get_side_data(frame, AV_FRAME_DATA_AUDIO_SERVICE_TYPE);
1899         if (sd && sd->size >= sizeof(enum AVAudioServiceType))
1900             avctx->audio_service_type = *(enum AVAudioServiceType*)sd->data;
1901     }
1902
1903     /* check for valid frame size */
1904     if (frame) {
1905         if (avctx->codec->capabilities & CODEC_CAP_SMALL_LAST_FRAME) {
1906             if (frame->nb_samples > avctx->frame_size) {
1907                 av_log(avctx, AV_LOG_ERROR, "more samples than frame size (avcodec_encode_audio2)\n");
1908                 ret = AVERROR(EINVAL);
1909                 goto end;
1910             }
1911         } else if (!(avctx->codec->capabilities & CODEC_CAP_VARIABLE_FRAME_SIZE)) {
1912             if (frame->nb_samples < avctx->frame_size &&
1913                 !avctx->internal->last_audio_frame) {
1914                 ret = pad_last_frame(avctx, &padded_frame, frame);
1915                 if (ret < 0)
1916                     goto end;
1917
1918                 frame = padded_frame;
1919                 avctx->internal->last_audio_frame = 1;
1920             }
1921
1922             if (frame->nb_samples != avctx->frame_size) {
1923                 av_log(avctx, AV_LOG_ERROR, "nb_samples (%d) != frame_size (%d) (avcodec_encode_audio2)\n", frame->nb_samples, avctx->frame_size);
1924                 ret = AVERROR(EINVAL);
1925                 goto end;
1926             }
1927         }
1928     }
1929
1930     ret = avctx->codec->encode2(avctx, avpkt, frame, got_packet_ptr);
1931     if (!ret) {
1932         if (*got_packet_ptr) {
1933             if (!(avctx->codec->capabilities & CODEC_CAP_DELAY)) {
1934                 if (avpkt->pts == AV_NOPTS_VALUE)
1935                     avpkt->pts = frame->pts;
1936                 if (!avpkt->duration)
1937                     avpkt->duration = ff_samples_to_time_base(avctx,
1938                                                               frame->nb_samples);
1939             }
1940             avpkt->dts = avpkt->pts;
1941         } else {
1942             avpkt->size = 0;
1943         }
1944     }
1945     if (avpkt->data && avpkt->data == avctx->internal->byte_buffer) {
1946         needs_realloc = 0;
1947         if (user_pkt.data) {
1948             if (user_pkt.size >= avpkt->size) {
1949                 memcpy(user_pkt.data, avpkt->data, avpkt->size);
1950             } else {
1951                 av_log(avctx, AV_LOG_ERROR, "Provided packet is too small, needs to be %d\n", avpkt->size);
1952                 avpkt->size = user_pkt.size;
1953                 ret = -1;
1954             }
1955             avpkt->buf      = user_pkt.buf;
1956             avpkt->data     = user_pkt.data;
1957 #if FF_API_DESTRUCT_PACKET
1958 FF_DISABLE_DEPRECATION_WARNINGS
1959             avpkt->destruct = user_pkt.destruct;
1960 FF_ENABLE_DEPRECATION_WARNINGS
1961 #endif
1962         } else {
1963             if (av_dup_packet(avpkt) < 0) {
1964                 ret = AVERROR(ENOMEM);
1965             }
1966         }
1967     }
1968
1969     if (!ret) {
1970         if (needs_realloc && avpkt->data) {
1971             ret = av_buffer_realloc(&avpkt->buf, avpkt->size + FF_INPUT_BUFFER_PADDING_SIZE);
1972             if (ret >= 0)
1973                 avpkt->data = avpkt->buf->data;
1974         }
1975
1976         avctx->frame_number++;
1977     }
1978
1979     if (ret < 0 || !*got_packet_ptr) {
1980         av_free_packet(avpkt);
1981         av_init_packet(avpkt);
1982         goto end;
1983     }
1984
1985     /* NOTE: if we add any audio encoders which output non-keyframe packets,
1986      *       this needs to be moved to the encoders, but for now we can do it
1987      *       here to simplify things */
1988     avpkt->flags |= AV_PKT_FLAG_KEY;
1989
1990 end:
1991     av_frame_free(&padded_frame);
1992     av_free(extended_frame);
1993
1994 #if FF_API_AUDIOENC_DELAY
1995     avctx->delay = avctx->initial_padding;
1996 #endif
1997
1998     return ret;
1999 }
2000
2001 #if FF_API_OLD_ENCODE_AUDIO
2002 int attribute_align_arg avcodec_encode_audio(AVCodecContext *avctx,
2003                                              uint8_t *buf, int buf_size,
2004                                              const short *samples)
2005 {
2006     AVPacket pkt;
2007     AVFrame *frame;
2008     int ret, samples_size, got_packet;
2009
2010     av_init_packet(&pkt);
2011     pkt.data = buf;
2012     pkt.size = buf_size;
2013
2014     if (samples) {
2015         frame = av_frame_alloc();
2016         if (!frame)
2017             return AVERROR(ENOMEM);
2018
2019         if (avctx->frame_size) {
2020             frame->nb_samples = avctx->frame_size;
2021         } else {
2022             /* if frame_size is not set, the number of samples must be
2023              * calculated from the buffer size */
2024             int64_t nb_samples;
2025             if (!av_get_bits_per_sample(avctx->codec_id)) {
2026                 av_log(avctx, AV_LOG_ERROR, "avcodec_encode_audio() does not "
2027                                             "support this codec\n");
2028                 av_frame_free(&frame);
2029                 return AVERROR(EINVAL);
2030             }
2031             nb_samples = (int64_t)buf_size * 8 /
2032                          (av_get_bits_per_sample(avctx->codec_id) *
2033                           avctx->channels);
2034             if (nb_samples >= INT_MAX) {
2035                 av_frame_free(&frame);
2036                 return AVERROR(EINVAL);
2037             }
2038             frame->nb_samples = nb_samples;
2039         }
2040
2041         /* it is assumed that the samples buffer is large enough based on the
2042          * relevant parameters */
2043         samples_size = av_samples_get_buffer_size(NULL, avctx->channels,
2044                                                   frame->nb_samples,
2045                                                   avctx->sample_fmt, 1);
2046         if ((ret = avcodec_fill_audio_frame(frame, avctx->channels,
2047                                             avctx->sample_fmt,
2048                                             (const uint8_t *)samples,
2049                                             samples_size, 1)) < 0) {
2050             av_frame_free(&frame);
2051             return ret;
2052         }
2053
2054         /* fabricate frame pts from sample count.
2055          * this is needed because the avcodec_encode_audio() API does not have
2056          * a way for the user to provide pts */
2057         if (avctx->sample_rate && avctx->time_base.num)
2058             frame->pts = ff_samples_to_time_base(avctx,
2059                                                  avctx->internal->sample_count);
2060         else
2061             frame->pts = AV_NOPTS_VALUE;
2062         avctx->internal->sample_count += frame->nb_samples;
2063     } else {
2064         frame = NULL;
2065     }
2066
2067     got_packet = 0;
2068     ret = avcodec_encode_audio2(avctx, &pkt, frame, &got_packet);
2069     if (!ret && got_packet && avctx->coded_frame) {
2070         avctx->coded_frame->pts       = pkt.pts;
2071         avctx->coded_frame->key_frame = !!(pkt.flags & AV_PKT_FLAG_KEY);
2072     }
2073     /* free any side data since we cannot return it */
2074     av_packet_free_side_data(&pkt);
2075
2076     if (frame && frame->extended_data != frame->data)
2077         av_freep(&frame->extended_data);
2078
2079     av_frame_free(&frame);
2080     return ret ? ret : pkt.size;
2081 }
2082
2083 #endif
2084
2085 #if FF_API_OLD_ENCODE_VIDEO
2086 int attribute_align_arg avcodec_encode_video(AVCodecContext *avctx, uint8_t *buf, int buf_size,
2087                                              const AVFrame *pict)
2088 {
2089     AVPacket pkt;
2090     int ret, got_packet = 0;
2091
2092     if (buf_size < FF_MIN_BUFFER_SIZE) {
2093         av_log(avctx, AV_LOG_ERROR, "buffer smaller than minimum size\n");
2094         return -1;
2095     }
2096
2097     av_init_packet(&pkt);
2098     pkt.data = buf;
2099     pkt.size = buf_size;
2100
2101     ret = avcodec_encode_video2(avctx, &pkt, pict, &got_packet);
2102     if (!ret && got_packet && avctx->coded_frame) {
2103         avctx->coded_frame->pts       = pkt.pts;
2104         avctx->coded_frame->key_frame = !!(pkt.flags & AV_PKT_FLAG_KEY);
2105     }
2106
2107     /* free any side data since we cannot return it */
2108     if (pkt.side_data_elems > 0) {
2109         int i;
2110         for (i = 0; i < pkt.side_data_elems; i++)
2111             av_free(pkt.side_data[i].data);
2112         av_freep(&pkt.side_data);
2113         pkt.side_data_elems = 0;
2114     }
2115
2116     return ret ? ret : pkt.size;
2117 }
2118
2119 #endif
2120
2121 int attribute_align_arg avcodec_encode_video2(AVCodecContext *avctx,
2122                                               AVPacket *avpkt,
2123                                               const AVFrame *frame,
2124                                               int *got_packet_ptr)
2125 {
2126     int ret;
2127     AVPacket user_pkt = *avpkt;
2128     int needs_realloc = !user_pkt.data;
2129
2130     *got_packet_ptr = 0;
2131
2132     if(CONFIG_FRAME_THREAD_ENCODER &&
2133        avctx->internal->frame_thread_encoder && (avctx->active_thread_type&FF_THREAD_FRAME))
2134         return ff_thread_video_encode_frame(avctx, avpkt, frame, got_packet_ptr);
2135
2136     if ((avctx->flags&CODEC_FLAG_PASS1) && avctx->stats_out)
2137         avctx->stats_out[0] = '\0';
2138
2139     if (!(avctx->codec->capabilities & CODEC_CAP_DELAY) && !frame) {
2140         av_free_packet(avpkt);
2141         av_init_packet(avpkt);
2142         avpkt->size = 0;
2143         return 0;
2144     }
2145
2146     if (av_image_check_size(avctx->width, avctx->height, 0, avctx))
2147         return AVERROR(EINVAL);
2148
2149     if (frame && frame->format == AV_PIX_FMT_NONE)
2150         av_log(avctx, AV_LOG_WARNING, "AVFrame.format is not set\n");
2151     if (frame && (frame->width == 0 || frame->height == 0))
2152         av_log(avctx, AV_LOG_WARNING, "AVFrame.width or height is not set\n");
2153
2154     av_assert0(avctx->codec->encode2);
2155
2156     ret = avctx->codec->encode2(avctx, avpkt, frame, got_packet_ptr);
2157     av_assert0(ret <= 0);
2158
2159     if (avpkt->data && avpkt->data == avctx->internal->byte_buffer) {
2160         needs_realloc = 0;
2161         if (user_pkt.data) {
2162             if (user_pkt.size >= avpkt->size) {
2163                 memcpy(user_pkt.data, avpkt->data, avpkt->size);
2164             } else {
2165                 av_log(avctx, AV_LOG_ERROR, "Provided packet is too small, needs to be %d\n", avpkt->size);
2166                 avpkt->size = user_pkt.size;
2167                 ret = -1;
2168             }
2169             avpkt->buf      = user_pkt.buf;
2170             avpkt->data     = user_pkt.data;
2171 #if FF_API_DESTRUCT_PACKET
2172 FF_DISABLE_DEPRECATION_WARNINGS
2173             avpkt->destruct = user_pkt.destruct;
2174 FF_ENABLE_DEPRECATION_WARNINGS
2175 #endif
2176         } else {
2177             if (av_dup_packet(avpkt) < 0) {
2178                 ret = AVERROR(ENOMEM);
2179             }
2180         }
2181     }
2182
2183     if (!ret) {
2184         if (!*got_packet_ptr)
2185             avpkt->size = 0;
2186         else if (!(avctx->codec->capabilities & CODEC_CAP_DELAY))
2187             avpkt->pts = avpkt->dts = frame->pts;
2188
2189         if (needs_realloc && avpkt->data) {
2190             ret = av_buffer_realloc(&avpkt->buf, avpkt->size + FF_INPUT_BUFFER_PADDING_SIZE);
2191             if (ret >= 0)
2192                 avpkt->data = avpkt->buf->data;
2193         }
2194
2195         avctx->frame_number++;
2196     }
2197
2198     if (ret < 0 || !*got_packet_ptr)
2199         av_free_packet(avpkt);
2200     else
2201         av_packet_merge_side_data(avpkt);
2202
2203     emms_c();
2204     return ret;
2205 }
2206
2207 int avcodec_encode_subtitle(AVCodecContext *avctx, uint8_t *buf, int buf_size,
2208                             const AVSubtitle *sub)
2209 {
2210     int ret;
2211     if (sub->start_display_time) {
2212         av_log(avctx, AV_LOG_ERROR, "start_display_time must be 0.\n");
2213         return -1;
2214     }
2215
2216     ret = avctx->codec->encode_sub(avctx, buf, buf_size, sub);
2217     avctx->frame_number++;
2218     return ret;
2219 }
2220
2221 /**
2222  * Attempt to guess proper monotonic timestamps for decoded video frames
2223  * which might have incorrect times. Input timestamps may wrap around, in
2224  * which case the output will as well.
2225  *
2226  * @param pts the pts field of the decoded AVPacket, as passed through
2227  * AVFrame.pkt_pts
2228  * @param dts the dts field of the decoded AVPacket
2229  * @return one of the input values, may be AV_NOPTS_VALUE
2230  */
2231 static int64_t guess_correct_pts(AVCodecContext *ctx,
2232                                  int64_t reordered_pts, int64_t dts)
2233 {
2234     int64_t pts = AV_NOPTS_VALUE;
2235
2236     if (dts != AV_NOPTS_VALUE) {
2237         ctx->pts_correction_num_faulty_dts += dts <= ctx->pts_correction_last_dts;
2238         ctx->pts_correction_last_dts = dts;
2239     } else if (reordered_pts != AV_NOPTS_VALUE)
2240         ctx->pts_correction_last_dts = reordered_pts;
2241
2242     if (reordered_pts != AV_NOPTS_VALUE) {
2243         ctx->pts_correction_num_faulty_pts += reordered_pts <= ctx->pts_correction_last_pts;
2244         ctx->pts_correction_last_pts = reordered_pts;
2245     } else if(dts != AV_NOPTS_VALUE)
2246         ctx->pts_correction_last_pts = dts;
2247
2248     if ((ctx->pts_correction_num_faulty_pts<=ctx->pts_correction_num_faulty_dts || dts == AV_NOPTS_VALUE)
2249        && reordered_pts != AV_NOPTS_VALUE)
2250         pts = reordered_pts;
2251     else
2252         pts = dts;
2253
2254     return pts;
2255 }
2256
2257 static int apply_param_change(AVCodecContext *avctx, AVPacket *avpkt)
2258 {
2259     int size = 0, ret;
2260     const uint8_t *data;
2261     uint32_t flags;
2262     int64_t val;
2263
2264     data = av_packet_get_side_data(avpkt, AV_PKT_DATA_PARAM_CHANGE, &size);
2265     if (!data)
2266         return 0;
2267
2268     if (!(avctx->codec->capabilities & CODEC_CAP_PARAM_CHANGE)) {
2269         av_log(avctx, AV_LOG_ERROR, "This decoder does not support parameter "
2270                "changes, but PARAM_CHANGE side data was sent to it.\n");
2271         return AVERROR(EINVAL);
2272     }
2273
2274     if (size < 4)
2275         goto fail;
2276
2277     flags = bytestream_get_le32(&data);
2278     size -= 4;
2279
2280     if (flags & AV_SIDE_DATA_PARAM_CHANGE_CHANNEL_COUNT) {
2281         if (size < 4)
2282             goto fail;
2283         val = bytestream_get_le32(&data);
2284         if (val <= 0 || val > INT_MAX) {
2285             av_log(avctx, AV_LOG_ERROR, "Invalid channel count");
2286             return AVERROR_INVALIDDATA;
2287         }
2288         avctx->channels = val;
2289         size -= 4;
2290     }
2291     if (flags & AV_SIDE_DATA_PARAM_CHANGE_CHANNEL_LAYOUT) {
2292         if (size < 8)
2293             goto fail;
2294         avctx->channel_layout = bytestream_get_le64(&data);
2295         size -= 8;
2296     }
2297     if (flags & AV_SIDE_DATA_PARAM_CHANGE_SAMPLE_RATE) {
2298         if (size < 4)
2299             goto fail;
2300         val = bytestream_get_le32(&data);
2301         if (val <= 0 || val > INT_MAX) {
2302             av_log(avctx, AV_LOG_ERROR, "Invalid sample rate");
2303             return AVERROR_INVALIDDATA;
2304         }
2305         avctx->sample_rate = val;
2306         size -= 4;
2307     }
2308     if (flags & AV_SIDE_DATA_PARAM_CHANGE_DIMENSIONS) {
2309         if (size < 8)
2310             goto fail;
2311         avctx->width  = bytestream_get_le32(&data);
2312         avctx->height = bytestream_get_le32(&data);
2313         size -= 8;
2314         ret = ff_set_dimensions(avctx, avctx->width, avctx->height);
2315         if (ret < 0)
2316             return ret;
2317     }
2318
2319     return 0;
2320 fail:
2321     av_log(avctx, AV_LOG_ERROR, "PARAM_CHANGE side data too small.\n");
2322     return AVERROR_INVALIDDATA;
2323 }
2324
2325 static int unrefcount_frame(AVCodecInternal *avci, AVFrame *frame)
2326 {
2327     int ret;
2328
2329     /* move the original frame to our backup */
2330     av_frame_unref(avci->to_free);
2331     av_frame_move_ref(avci->to_free, frame);
2332
2333     /* now copy everything except the AVBufferRefs back
2334      * note that we make a COPY of the side data, so calling av_frame_free() on
2335      * the caller's frame will work properly */
2336     ret = av_frame_copy_props(frame, avci->to_free);
2337     if (ret < 0)
2338         return ret;
2339
2340     memcpy(frame->data,     avci->to_free->data,     sizeof(frame->data));
2341     memcpy(frame->linesize, avci->to_free->linesize, sizeof(frame->linesize));
2342     if (avci->to_free->extended_data != avci->to_free->data) {
2343         int planes = av_frame_get_channels(avci->to_free);
2344         int size   = planes * sizeof(*frame->extended_data);
2345
2346         if (!size) {
2347             av_frame_unref(frame);
2348             return AVERROR_BUG;
2349         }
2350
2351         frame->extended_data = av_malloc(size);
2352         if (!frame->extended_data) {
2353             av_frame_unref(frame);
2354             return AVERROR(ENOMEM);
2355         }
2356         memcpy(frame->extended_data, avci->to_free->extended_data,
2357                size);
2358     } else
2359         frame->extended_data = frame->data;
2360
2361     frame->format         = avci->to_free->format;
2362     frame->width          = avci->to_free->width;
2363     frame->height         = avci->to_free->height;
2364     frame->channel_layout = avci->to_free->channel_layout;
2365     frame->nb_samples     = avci->to_free->nb_samples;
2366     av_frame_set_channels(frame, av_frame_get_channels(avci->to_free));
2367
2368     return 0;
2369 }
2370
2371 int attribute_align_arg avcodec_decode_video2(AVCodecContext *avctx, AVFrame *picture,
2372                                               int *got_picture_ptr,
2373                                               const AVPacket *avpkt)
2374 {
2375     AVCodecInternal *avci = avctx->internal;
2376     int ret;
2377     // copy to ensure we do not change avpkt
2378     AVPacket tmp = *avpkt;
2379
2380     if (!avctx->codec)
2381         return AVERROR(EINVAL);
2382     if (avctx->codec->type != AVMEDIA_TYPE_VIDEO) {
2383         av_log(avctx, AV_LOG_ERROR, "Invalid media type for video\n");
2384         return AVERROR(EINVAL);
2385     }
2386
2387     *got_picture_ptr = 0;
2388     if ((avctx->coded_width || avctx->coded_height) && av_image_check_size(avctx->coded_width, avctx->coded_height, 0, avctx))
2389         return AVERROR(EINVAL);
2390
2391     av_frame_unref(picture);
2392
2393     if ((avctx->codec->capabilities & CODEC_CAP_DELAY) || avpkt->size || (avctx->active_thread_type & FF_THREAD_FRAME)) {
2394         int did_split = av_packet_split_side_data(&tmp);
2395         ret = apply_param_change(avctx, &tmp);
2396         if (ret < 0) {
2397             av_log(avctx, AV_LOG_ERROR, "Error applying parameter changes.\n");
2398             if (avctx->err_recognition & AV_EF_EXPLODE)
2399                 goto fail;
2400         }
2401
2402         avctx->internal->pkt = &tmp;
2403         if (HAVE_THREADS && avctx->active_thread_type & FF_THREAD_FRAME)
2404             ret = ff_thread_decode_frame(avctx, picture, got_picture_ptr,
2405                                          &tmp);
2406         else {
2407             ret = avctx->codec->decode(avctx, picture, got_picture_ptr,
2408                                        &tmp);
2409             picture->pkt_dts = avpkt->dts;
2410
2411             if(!avctx->has_b_frames){
2412                 av_frame_set_pkt_pos(picture, avpkt->pos);
2413             }
2414             //FIXME these should be under if(!avctx->has_b_frames)
2415             /* get_buffer is supposed to set frame parameters */
2416             if (!(avctx->codec->capabilities & CODEC_CAP_DR1)) {
2417                 if (!picture->sample_aspect_ratio.num)    picture->sample_aspect_ratio = avctx->sample_aspect_ratio;
2418                 if (!picture->width)                      picture->width               = avctx->width;
2419                 if (!picture->height)                     picture->height              = avctx->height;
2420                 if (picture->format == AV_PIX_FMT_NONE)   picture->format              = avctx->pix_fmt;
2421             }
2422         }
2423
2424 fail:
2425         emms_c(); //needed to avoid an emms_c() call before every return;
2426
2427         avctx->internal->pkt = NULL;
2428         if (did_split) {
2429             av_packet_free_side_data(&tmp);
2430             if(ret == tmp.size)
2431                 ret = avpkt->size;
2432         }
2433
2434         if (*got_picture_ptr) {
2435             if (!avctx->refcounted_frames) {
2436                 int err = unrefcount_frame(avci, picture);
2437                 if (err < 0)
2438                     return err;
2439             }
2440
2441             avctx->frame_number++;
2442             av_frame_set_best_effort_timestamp(picture,
2443                                                guess_correct_pts(avctx,
2444                                                                  picture->pkt_pts,
2445                                                                  picture->pkt_dts));
2446         } else
2447             av_frame_unref(picture);
2448     } else
2449         ret = 0;
2450
2451     /* many decoders assign whole AVFrames, thus overwriting extended_data;
2452      * make sure it's set correctly */
2453     av_assert0(!picture->extended_data || picture->extended_data == picture->data);
2454
2455 #if FF_API_AVCTX_TIMEBASE
2456     if (avctx->framerate.num > 0 && avctx->framerate.den > 0)
2457         avctx->time_base = av_inv_q(av_mul_q(avctx->framerate, (AVRational){avctx->ticks_per_frame, 1}));
2458 #endif
2459
2460     return ret;
2461 }
2462
2463 #if FF_API_OLD_DECODE_AUDIO
2464 int attribute_align_arg avcodec_decode_audio3(AVCodecContext *avctx, int16_t *samples,
2465                                               int *frame_size_ptr,
2466                                               AVPacket *avpkt)
2467 {
2468     AVFrame *frame = av_frame_alloc();
2469     int ret, got_frame = 0;
2470
2471     if (!frame)
2472         return AVERROR(ENOMEM);
2473     if (avctx->get_buffer != avcodec_default_get_buffer) {
2474         av_log(avctx, AV_LOG_ERROR, "Custom get_buffer() for use with"
2475                                     "avcodec_decode_audio3() detected. Overriding with avcodec_default_get_buffer\n");
2476         av_log(avctx, AV_LOG_ERROR, "Please port your application to "
2477                                     "avcodec_decode_audio4()\n");
2478         avctx->get_buffer = avcodec_default_get_buffer;
2479         avctx->release_buffer = avcodec_default_release_buffer;
2480     }
2481
2482     ret = avcodec_decode_audio4(avctx, frame, &got_frame, avpkt);
2483
2484     if (ret >= 0 && got_frame) {
2485         int ch, plane_size;
2486         int planar    = av_sample_fmt_is_planar(avctx->sample_fmt);
2487         int data_size = av_samples_get_buffer_size(&plane_size, avctx->channels,
2488                                                    frame->nb_samples,
2489                                                    avctx->sample_fmt, 1);
2490         if (*frame_size_ptr < data_size) {
2491             av_log(avctx, AV_LOG_ERROR, "output buffer size is too small for "
2492                                         "the current frame (%d < %d)\n", *frame_size_ptr, data_size);
2493             av_frame_free(&frame);
2494             return AVERROR(EINVAL);
2495         }
2496
2497         memcpy(samples, frame->extended_data[0], plane_size);
2498
2499         if (planar && avctx->channels > 1) {
2500             uint8_t *out = ((uint8_t *)samples) + plane_size;
2501             for (ch = 1; ch < avctx->channels; ch++) {
2502                 memcpy(out, frame->extended_data[ch], plane_size);
2503                 out += plane_size;
2504             }
2505         }
2506         *frame_size_ptr = data_size;
2507     } else {
2508         *frame_size_ptr = 0;
2509     }
2510     av_frame_free(&frame);
2511     return ret;
2512 }
2513
2514 #endif
2515
2516 int attribute_align_arg avcodec_decode_audio4(AVCodecContext *avctx,
2517                                               AVFrame *frame,
2518                                               int *got_frame_ptr,
2519                                               const AVPacket *avpkt)
2520 {
2521     AVCodecInternal *avci = avctx->internal;
2522     int ret = 0;
2523
2524     *got_frame_ptr = 0;
2525
2526     if (!avpkt->data && avpkt->size) {
2527         av_log(avctx, AV_LOG_ERROR, "invalid packet: NULL data, size != 0\n");
2528         return AVERROR(EINVAL);
2529     }
2530     if (!avctx->codec)
2531         return AVERROR(EINVAL);
2532     if (avctx->codec->type != AVMEDIA_TYPE_AUDIO) {
2533         av_log(avctx, AV_LOG_ERROR, "Invalid media type for audio\n");
2534         return AVERROR(EINVAL);
2535     }
2536
2537     av_frame_unref(frame);
2538
2539     if ((avctx->codec->capabilities & CODEC_CAP_DELAY) || avpkt->size || (avctx->active_thread_type & FF_THREAD_FRAME)) {
2540         uint8_t *side;
2541         int side_size;
2542         uint32_t discard_padding = 0;
2543         uint8_t skip_reason = 0;
2544         uint8_t discard_reason = 0;
2545         // copy to ensure we do not change avpkt
2546         AVPacket tmp = *avpkt;
2547         int did_split = av_packet_split_side_data(&tmp);
2548         ret = apply_param_change(avctx, &tmp);
2549         if (ret < 0) {
2550             av_log(avctx, AV_LOG_ERROR, "Error applying parameter changes.\n");
2551             if (avctx->err_recognition & AV_EF_EXPLODE)
2552                 goto fail;
2553         }
2554
2555         avctx->internal->pkt = &tmp;
2556         if (HAVE_THREADS && avctx->active_thread_type & FF_THREAD_FRAME)
2557             ret = ff_thread_decode_frame(avctx, frame, got_frame_ptr, &tmp);
2558         else {
2559             ret = avctx->codec->decode(avctx, frame, got_frame_ptr, &tmp);
2560             av_assert0(ret <= tmp.size);
2561             frame->pkt_dts = avpkt->dts;
2562         }
2563         if (ret >= 0 && *got_frame_ptr) {
2564             avctx->frame_number++;
2565             av_frame_set_best_effort_timestamp(frame,
2566                                                guess_correct_pts(avctx,
2567                                                                  frame->pkt_pts,
2568                                                                  frame->pkt_dts));
2569             if (frame->format == AV_SAMPLE_FMT_NONE)
2570                 frame->format = avctx->sample_fmt;
2571             if (!frame->channel_layout)
2572                 frame->channel_layout = avctx->channel_layout;
2573             if (!av_frame_get_channels(frame))
2574                 av_frame_set_channels(frame, avctx->channels);
2575             if (!frame->sample_rate)
2576                 frame->sample_rate = avctx->sample_rate;
2577         }
2578
2579         side= av_packet_get_side_data(avctx->internal->pkt, AV_PKT_DATA_SKIP_SAMPLES, &side_size);
2580         if(side && side_size>=10) {
2581             avctx->internal->skip_samples = AV_RL32(side);
2582             discard_padding = AV_RL32(side + 4);
2583             av_log(avctx, AV_LOG_DEBUG, "skip %d / discard %d samples due to side data\n",
2584                    avctx->internal->skip_samples, (int)discard_padding);
2585             skip_reason = AV_RL8(side + 8);
2586             discard_reason = AV_RL8(side + 9);
2587         }
2588         if (avctx->internal->skip_samples && *got_frame_ptr &&
2589             !(avctx->flags2 & CODEC_FLAG2_SKIP_MANUAL)) {
2590             if(frame->nb_samples <= avctx->internal->skip_samples){
2591                 *got_frame_ptr = 0;
2592                 avctx->internal->skip_samples -= frame->nb_samples;
2593                 av_log(avctx, AV_LOG_DEBUG, "skip whole frame, skip left: %d\n",
2594                        avctx->internal->skip_samples);
2595             } else {
2596                 av_samples_copy(frame->extended_data, frame->extended_data, 0, avctx->internal->skip_samples,
2597                                 frame->nb_samples - avctx->internal->skip_samples, avctx->channels, frame->format);
2598                 if(avctx->pkt_timebase.num && avctx->sample_rate) {
2599                     int64_t diff_ts = av_rescale_q(avctx->internal->skip_samples,
2600                                                    (AVRational){1, avctx->sample_rate},
2601                                                    avctx->pkt_timebase);
2602                     if(frame->pkt_pts!=AV_NOPTS_VALUE)
2603                         frame->pkt_pts += diff_ts;
2604                     if(frame->pkt_dts!=AV_NOPTS_VALUE)
2605                         frame->pkt_dts += diff_ts;
2606                     if (av_frame_get_pkt_duration(frame) >= diff_ts)
2607                         av_frame_set_pkt_duration(frame, av_frame_get_pkt_duration(frame) - diff_ts);
2608                 } else {
2609                     av_log(avctx, AV_LOG_WARNING, "Could not update timestamps for skipped samples.\n");
2610                 }
2611                 av_log(avctx, AV_LOG_DEBUG, "skip %d/%d samples\n",
2612                        avctx->internal->skip_samples, frame->nb_samples);
2613                 frame->nb_samples -= avctx->internal->skip_samples;
2614                 avctx->internal->skip_samples = 0;
2615             }
2616         }
2617
2618         if (discard_padding > 0 && discard_padding <= frame->nb_samples && *got_frame_ptr &&
2619             !(avctx->flags2 & CODEC_FLAG2_SKIP_MANUAL)) {
2620             if (discard_padding == frame->nb_samples) {
2621                 *got_frame_ptr = 0;
2622             } else {
2623                 if(avctx->pkt_timebase.num && avctx->sample_rate) {
2624                     int64_t diff_ts = av_rescale_q(frame->nb_samples - discard_padding,
2625                                                    (AVRational){1, avctx->sample_rate},
2626                                                    avctx->pkt_timebase);
2627                     if (av_frame_get_pkt_duration(frame) >= diff_ts)
2628                         av_frame_set_pkt_duration(frame, av_frame_get_pkt_duration(frame) - diff_ts);
2629                 } else {
2630                     av_log(avctx, AV_LOG_WARNING, "Could not update timestamps for discarded samples.\n");
2631                 }
2632                 av_log(avctx, AV_LOG_DEBUG, "discard %d/%d samples\n",
2633                        (int)discard_padding, frame->nb_samples);
2634                 frame->nb_samples -= discard_padding;
2635             }
2636         }
2637
2638         if ((avctx->flags2 & CODEC_FLAG2_SKIP_MANUAL) && *got_frame_ptr) {
2639             AVFrameSideData *fside = av_frame_new_side_data(frame, AV_FRAME_DATA_SKIP_SAMPLES, 10);
2640             if (fside) {
2641                 AV_WL32(fside->data, avctx->internal->skip_samples);
2642                 AV_WL32(fside->data + 4, discard_padding);
2643                 AV_WL8(fside->data + 8, skip_reason);
2644                 AV_WL8(fside->data + 9, discard_reason);
2645                 avctx->internal->skip_samples = 0;
2646             }
2647         }
2648 fail:
2649         avctx->internal->pkt = NULL;
2650         if (did_split) {
2651             av_packet_free_side_data(&tmp);
2652             if(ret == tmp.size)
2653                 ret = avpkt->size;
2654         }
2655
2656         if (ret >= 0 && *got_frame_ptr) {
2657             if (!avctx->refcounted_frames) {
2658                 int err = unrefcount_frame(avci, frame);
2659                 if (err < 0)
2660                     return err;
2661             }
2662         } else
2663             av_frame_unref(frame);
2664     }
2665
2666     return ret;
2667 }
2668
2669 #define UTF8_MAX_BYTES 4 /* 5 and 6 bytes sequences should not be used */
2670 static int recode_subtitle(AVCodecContext *avctx,
2671                            AVPacket *outpkt, const AVPacket *inpkt)
2672 {
2673 #if CONFIG_ICONV
2674     iconv_t cd = (iconv_t)-1;
2675     int ret = 0;
2676     char *inb, *outb;
2677     size_t inl, outl;
2678     AVPacket tmp;
2679 #endif
2680
2681     if (avctx->sub_charenc_mode != FF_SUB_CHARENC_MODE_PRE_DECODER || inpkt->size == 0)
2682         return 0;
2683
2684 #if CONFIG_ICONV
2685     cd = iconv_open("UTF-8", avctx->sub_charenc);
2686     av_assert0(cd != (iconv_t)-1);
2687
2688     inb = inpkt->data;
2689     inl = inpkt->size;
2690
2691     if (inl >= INT_MAX / UTF8_MAX_BYTES - FF_INPUT_BUFFER_PADDING_SIZE) {
2692         av_log(avctx, AV_LOG_ERROR, "Subtitles packet is too big for recoding\n");
2693         ret = AVERROR(ENOMEM);
2694         goto end;
2695     }
2696
2697     ret = av_new_packet(&tmp, inl * UTF8_MAX_BYTES);
2698     if (ret < 0)
2699         goto end;
2700     outpkt->buf  = tmp.buf;
2701     outpkt->data = tmp.data;
2702     outpkt->size = tmp.size;
2703     outb = outpkt->data;
2704     outl = outpkt->size;
2705
2706     if (iconv(cd, &inb, &inl, &outb, &outl) == (size_t)-1 ||
2707         iconv(cd, NULL, NULL, &outb, &outl) == (size_t)-1 ||
2708         outl >= outpkt->size || inl != 0) {
2709         ret = FFMIN(AVERROR(errno), -1);
2710         av_log(avctx, AV_LOG_ERROR, "Unable to recode subtitle event \"%s\" "
2711                "from %s to UTF-8\n", inpkt->data, avctx->sub_charenc);
2712         av_free_packet(&tmp);
2713         goto end;
2714     }
2715     outpkt->size -= outl;
2716     memset(outpkt->data + outpkt->size, 0, outl);
2717
2718 end:
2719     if (cd != (iconv_t)-1)
2720         iconv_close(cd);
2721     return ret;
2722 #else
2723     av_log(avctx, AV_LOG_ERROR, "requesting subtitles recoding without iconv");
2724     return AVERROR(EINVAL);
2725 #endif
2726 }
2727
2728 static int utf8_check(const uint8_t *str)
2729 {
2730     const uint8_t *byte;
2731     uint32_t codepoint, min;
2732
2733     while (*str) {
2734         byte = str;
2735         GET_UTF8(codepoint, *(byte++), return 0;);
2736         min = byte - str == 1 ? 0 : byte - str == 2 ? 0x80 :
2737               1 << (5 * (byte - str) - 4);
2738         if (codepoint < min || codepoint >= 0x110000 ||
2739             codepoint == 0xFFFE /* BOM */ ||
2740             codepoint >= 0xD800 && codepoint <= 0xDFFF /* surrogates */)
2741             return 0;
2742         str = byte;
2743     }
2744     return 1;
2745 }
2746
2747 int avcodec_decode_subtitle2(AVCodecContext *avctx, AVSubtitle *sub,
2748                              int *got_sub_ptr,
2749                              AVPacket *avpkt)
2750 {
2751     int i, ret = 0;
2752
2753     if (!avpkt->data && avpkt->size) {
2754         av_log(avctx, AV_LOG_ERROR, "invalid packet: NULL data, size != 0\n");
2755         return AVERROR(EINVAL);
2756     }
2757     if (!avctx->codec)
2758         return AVERROR(EINVAL);
2759     if (avctx->codec->type != AVMEDIA_TYPE_SUBTITLE) {
2760         av_log(avctx, AV_LOG_ERROR, "Invalid media type for subtitles\n");
2761         return AVERROR(EINVAL);
2762     }
2763
2764     *got_sub_ptr = 0;
2765     get_subtitle_defaults(sub);
2766
2767     if ((avctx->codec->capabilities & CODEC_CAP_DELAY) || avpkt->size) {
2768         AVPacket pkt_recoded;
2769         AVPacket tmp = *avpkt;
2770         int did_split = av_packet_split_side_data(&tmp);
2771         //apply_param_change(avctx, &tmp);
2772
2773         if (did_split) {
2774             /* FFMIN() prevents overflow in case the packet wasn't allocated with
2775              * proper padding.
2776              * If the side data is smaller than the buffer padding size, the
2777              * remaining bytes should have already been filled with zeros by the
2778              * original packet allocation anyway. */
2779             memset(tmp.data + tmp.size, 0,
2780                    FFMIN(avpkt->size - tmp.size, FF_INPUT_BUFFER_PADDING_SIZE));
2781         }
2782
2783         pkt_recoded = tmp;
2784         ret = recode_subtitle(avctx, &pkt_recoded, &tmp);
2785         if (ret < 0) {
2786             *got_sub_ptr = 0;
2787         } else {
2788             avctx->internal->pkt = &pkt_recoded;
2789
2790             if (avctx->pkt_timebase.den && avpkt->pts != AV_NOPTS_VALUE)
2791                 sub->pts = av_rescale_q(avpkt->pts,
2792                                         avctx->pkt_timebase, AV_TIME_BASE_Q);
2793             ret = avctx->codec->decode(avctx, sub, got_sub_ptr, &pkt_recoded);
2794             av_assert1((ret >= 0) >= !!*got_sub_ptr &&
2795                        !!*got_sub_ptr >= !!sub->num_rects);
2796
2797             if (sub->num_rects && !sub->end_display_time && avpkt->duration &&
2798                 avctx->pkt_timebase.num) {
2799                 AVRational ms = { 1, 1000 };
2800                 sub->end_display_time = av_rescale_q(avpkt->duration,
2801                                                      avctx->pkt_timebase, ms);
2802             }
2803
2804             for (i = 0; i < sub->num_rects; i++) {
2805                 if (sub->rects[i]->ass && !utf8_check(sub->rects[i]->ass)) {
2806                     av_log(avctx, AV_LOG_ERROR,
2807                            "Invalid UTF-8 in decoded subtitles text; "
2808                            "maybe missing -sub_charenc option\n");
2809                     avsubtitle_free(sub);
2810                     return AVERROR_INVALIDDATA;
2811                 }
2812             }
2813
2814             if (tmp.data != pkt_recoded.data) { // did we recode?
2815                 /* prevent from destroying side data from original packet */
2816                 pkt_recoded.side_data = NULL;
2817                 pkt_recoded.side_data_elems = 0;
2818
2819                 av_free_packet(&pkt_recoded);
2820             }
2821             if (avctx->codec_descriptor->props & AV_CODEC_PROP_BITMAP_SUB)
2822                 sub->format = 0;
2823             else if (avctx->codec_descriptor->props & AV_CODEC_PROP_TEXT_SUB)
2824                 sub->format = 1;
2825             avctx->internal->pkt = NULL;
2826         }
2827
2828         if (did_split) {
2829             av_packet_free_side_data(&tmp);
2830             if(ret == tmp.size)
2831                 ret = avpkt->size;
2832         }
2833
2834         if (*got_sub_ptr)
2835             avctx->frame_number++;
2836     }
2837
2838     return ret;
2839 }
2840
2841 void avsubtitle_free(AVSubtitle *sub)
2842 {
2843     int i;
2844
2845     for (i = 0; i < sub->num_rects; i++) {
2846         av_freep(&sub->rects[i]->pict.data[0]);
2847         av_freep(&sub->rects[i]->pict.data[1]);
2848         av_freep(&sub->rects[i]->pict.data[2]);
2849         av_freep(&sub->rects[i]->pict.data[3]);
2850         av_freep(&sub->rects[i]->text);
2851         av_freep(&sub->rects[i]->ass);
2852         av_freep(&sub->rects[i]);
2853     }
2854
2855     av_freep(&sub->rects);
2856
2857     memset(sub, 0, sizeof(AVSubtitle));
2858 }
2859
2860 av_cold int avcodec_close(AVCodecContext *avctx)
2861 {
2862     if (!avctx)
2863         return 0;
2864
2865     if (avcodec_is_open(avctx)) {
2866         FramePool *pool = avctx->internal->pool;
2867         int i;
2868         if (CONFIG_FRAME_THREAD_ENCODER &&
2869             avctx->internal->frame_thread_encoder && avctx->thread_count > 1) {
2870             ff_frame_thread_encoder_free(avctx);
2871         }
2872         if (HAVE_THREADS && avctx->internal->thread_ctx)
2873             ff_thread_free(avctx);
2874         if (avctx->codec && avctx->codec->close)
2875             avctx->codec->close(avctx);
2876         avctx->coded_frame = NULL;
2877         avctx->internal->byte_buffer_size = 0;
2878         av_freep(&avctx->internal->byte_buffer);
2879         av_frame_free(&avctx->internal->to_free);
2880         for (i = 0; i < FF_ARRAY_ELEMS(pool->pools); i++)
2881             av_buffer_pool_uninit(&pool->pools[i]);
2882         av_freep(&avctx->internal->pool);
2883
2884         if (avctx->hwaccel && avctx->hwaccel->uninit)
2885             avctx->hwaccel->uninit(avctx);
2886         av_freep(&avctx->internal->hwaccel_priv_data);
2887
2888         av_freep(&avctx->internal);
2889     }
2890
2891     if (avctx->priv_data && avctx->codec && avctx->codec->priv_class)
2892         av_opt_free(avctx->priv_data);
2893     av_opt_free(avctx);
2894     av_freep(&avctx->priv_data);
2895     if (av_codec_is_encoder(avctx->codec))
2896         av_freep(&avctx->extradata);
2897     avctx->codec = NULL;
2898     avctx->active_thread_type = 0;
2899
2900     return 0;
2901 }
2902
2903 static enum AVCodecID remap_deprecated_codec_id(enum AVCodecID id)
2904 {
2905     switch(id){
2906         //This is for future deprecatec codec ids, its empty since
2907         //last major bump but will fill up again over time, please don't remove it
2908 //         case AV_CODEC_ID_UTVIDEO_DEPRECATED: return AV_CODEC_ID_UTVIDEO;
2909         case AV_CODEC_ID_BRENDER_PIX_DEPRECATED         : return AV_CODEC_ID_BRENDER_PIX;
2910         case AV_CODEC_ID_OPUS_DEPRECATED                : return AV_CODEC_ID_OPUS;
2911         case AV_CODEC_ID_TAK_DEPRECATED                 : return AV_CODEC_ID_TAK;
2912         case AV_CODEC_ID_PAF_AUDIO_DEPRECATED           : return AV_CODEC_ID_PAF_AUDIO;
2913         case AV_CODEC_ID_PCM_S16BE_PLANAR_DEPRECATED    : return AV_CODEC_ID_PCM_S16BE_PLANAR;
2914         case AV_CODEC_ID_PCM_S24LE_PLANAR_DEPRECATED    : return AV_CODEC_ID_PCM_S24LE_PLANAR;
2915         case AV_CODEC_ID_PCM_S32LE_PLANAR_DEPRECATED    : return AV_CODEC_ID_PCM_S32LE_PLANAR;
2916         case AV_CODEC_ID_ADPCM_VIMA_DEPRECATED          : return AV_CODEC_ID_ADPCM_VIMA;
2917         case AV_CODEC_ID_ESCAPE130_DEPRECATED           : return AV_CODEC_ID_ESCAPE130;
2918         case AV_CODEC_ID_EXR_DEPRECATED                 : return AV_CODEC_ID_EXR;
2919         case AV_CODEC_ID_G2M_DEPRECATED                 : return AV_CODEC_ID_G2M;
2920         case AV_CODEC_ID_PAF_VIDEO_DEPRECATED           : return AV_CODEC_ID_PAF_VIDEO;
2921         case AV_CODEC_ID_WEBP_DEPRECATED                : return AV_CODEC_ID_WEBP;
2922         case AV_CODEC_ID_HEVC_DEPRECATED                : return AV_CODEC_ID_HEVC;
2923         case AV_CODEC_ID_MVC1_DEPRECATED                : return AV_CODEC_ID_MVC1;
2924         case AV_CODEC_ID_MVC2_DEPRECATED                : return AV_CODEC_ID_MVC2;
2925         case AV_CODEC_ID_SANM_DEPRECATED                : return AV_CODEC_ID_SANM;
2926         case AV_CODEC_ID_SGIRLE_DEPRECATED              : return AV_CODEC_ID_SGIRLE;
2927         case AV_CODEC_ID_VP7_DEPRECATED                 : return AV_CODEC_ID_VP7;
2928         default                                         : return id;
2929     }
2930 }
2931
2932 static AVCodec *find_encdec(enum AVCodecID id, int encoder)
2933 {
2934     AVCodec *p, *experimental = NULL;
2935     p = first_avcodec;
2936     id= remap_deprecated_codec_id(id);
2937     while (p) {
2938         if ((encoder ? av_codec_is_encoder(p) : av_codec_is_decoder(p)) &&
2939             p->id == id) {
2940             if (p->capabilities & CODEC_CAP_EXPERIMENTAL && !experimental) {
2941                 experimental = p;
2942             } else
2943                 return p;
2944         }
2945         p = p->next;
2946     }
2947     return experimental;
2948 }
2949
2950 AVCodec *avcodec_find_encoder(enum AVCodecID id)
2951 {
2952     return find_encdec(id, 1);
2953 }
2954
2955 AVCodec *avcodec_find_encoder_by_name(const char *name)
2956 {
2957     AVCodec *p;
2958     if (!name)
2959         return NULL;
2960     p = first_avcodec;
2961     while (p) {
2962         if (av_codec_is_encoder(p) && strcmp(name, p->name) == 0)
2963             return p;
2964         p = p->next;
2965     }
2966     return NULL;
2967 }
2968
2969 AVCodec *avcodec_find_decoder(enum AVCodecID id)
2970 {
2971     return find_encdec(id, 0);
2972 }
2973
2974 AVCodec *avcodec_find_decoder_by_name(const char *name)
2975 {
2976     AVCodec *p;
2977     if (!name)
2978         return NULL;
2979     p = first_avcodec;
2980     while (p) {
2981         if (av_codec_is_decoder(p) && strcmp(name, p->name) == 0)
2982             return p;
2983         p = p->next;
2984     }
2985     return NULL;
2986 }
2987
2988 const char *avcodec_get_name(enum AVCodecID id)
2989 {
2990     const AVCodecDescriptor *cd;
2991     AVCodec *codec;
2992
2993     if (id == AV_CODEC_ID_NONE)
2994         return "none";
2995     cd = avcodec_descriptor_get(id);
2996     if (cd)
2997         return cd->name;
2998     av_log(NULL, AV_LOG_WARNING, "Codec 0x%x is not in the full list.\n", id);
2999     codec = avcodec_find_decoder(id);
3000     if (codec)
3001         return codec->name;
3002     codec = avcodec_find_encoder(id);
3003     if (codec)
3004         return codec->name;
3005     return "unknown_codec";
3006 }
3007
3008 size_t av_get_codec_tag_string(char *buf, size_t buf_size, unsigned int codec_tag)
3009 {
3010     int i, len, ret = 0;
3011
3012 #define TAG_PRINT(x)                                              \
3013     (((x) >= '0' && (x) <= '9') ||                                \
3014      ((x) >= 'a' && (x) <= 'z') || ((x) >= 'A' && (x) <= 'Z') ||  \
3015      ((x) == '.' || (x) == ' ' || (x) == '-' || (x) == '_'))
3016
3017     for (i = 0; i < 4; i++) {
3018         len = snprintf(buf, buf_size,
3019                        TAG_PRINT(codec_tag & 0xFF) ? "%c" : "[%d]", codec_tag & 0xFF);
3020         buf        += len;
3021         buf_size    = buf_size > len ? buf_size - len : 0;
3022         ret        += len;
3023         codec_tag >>= 8;
3024     }
3025     return ret;
3026 }
3027
3028 void avcodec_string(char *buf, int buf_size, AVCodecContext *enc, int encode)
3029 {
3030     const char *codec_type;
3031     const char *codec_name;
3032     const char *profile = NULL;
3033     const AVCodec *p;
3034     int bitrate;
3035     int new_line = 0;
3036     AVRational display_aspect_ratio;
3037     const char *separator = enc->dump_separator ? (const char *)enc->dump_separator : ", ";
3038
3039     if (!buf || buf_size <= 0)
3040         return;
3041     codec_type = av_get_media_type_string(enc->codec_type);
3042     codec_name = avcodec_get_name(enc->codec_id);
3043     if (enc->profile != FF_PROFILE_UNKNOWN) {
3044         if (enc->codec)
3045             p = enc->codec;
3046         else
3047             p = encode ? avcodec_find_encoder(enc->codec_id) :
3048                         avcodec_find_decoder(enc->codec_id);
3049         if (p)
3050             profile = av_get_profile_name(p, enc->profile);
3051     }
3052
3053     snprintf(buf, buf_size, "%s: %s", codec_type ? codec_type : "unknown",
3054              codec_name);
3055     buf[0] ^= 'a' ^ 'A'; /* first letter in uppercase */
3056
3057     if (enc->codec && strcmp(enc->codec->name, codec_name))
3058         snprintf(buf + strlen(buf), buf_size - strlen(buf), " (%s)", enc->codec->name);
3059
3060     if (profile)
3061         snprintf(buf + strlen(buf), buf_size - strlen(buf), " (%s)", profile);
3062     if (   enc->codec_type == AVMEDIA_TYPE_VIDEO
3063         && av_log_get_level() >= AV_LOG_VERBOSE
3064         && enc->refs)
3065         snprintf(buf + strlen(buf), buf_size - strlen(buf),
3066                  ", %d reference frame%s",
3067                  enc->refs, enc->refs > 1 ? "s" : "");
3068
3069     if (enc->codec_tag) {
3070         char tag_buf[32];
3071         av_get_codec_tag_string(tag_buf, sizeof(tag_buf), enc->codec_tag);
3072         snprintf(buf + strlen(buf), buf_size - strlen(buf),
3073                  " (%s / 0x%04X)", tag_buf, enc->codec_tag);
3074     }
3075
3076     switch (enc->codec_type) {
3077     case AVMEDIA_TYPE_VIDEO:
3078         {
3079             char detail[256] = "(";
3080
3081             av_strlcat(buf, separator, buf_size);
3082
3083             snprintf(buf + strlen(buf), buf_size - strlen(buf),
3084                  "%s", enc->pix_fmt == AV_PIX_FMT_NONE ? "none" :
3085                      av_get_pix_fmt_name(enc->pix_fmt));
3086             if (enc->bits_per_raw_sample && enc->pix_fmt != AV_PIX_FMT_NONE &&
3087                 enc->bits_per_raw_sample <= av_pix_fmt_desc_get(enc->pix_fmt)->comp[0].depth_minus1)
3088                 av_strlcatf(detail, sizeof(detail), "%d bpc, ", enc->bits_per_raw_sample);
3089             if (enc->color_range != AVCOL_RANGE_UNSPECIFIED)
3090                 av_strlcatf(detail, sizeof(detail), "%s, ",
3091                             av_color_range_name(enc->color_range));
3092
3093             if (enc->colorspace != AVCOL_SPC_UNSPECIFIED ||
3094                 enc->color_primaries != AVCOL_PRI_UNSPECIFIED ||
3095                 enc->color_trc != AVCOL_TRC_UNSPECIFIED) {
3096                 if (enc->colorspace != (int)enc->color_primaries ||
3097                     enc->colorspace != (int)enc->color_trc) {
3098                     new_line = 1;
3099                     av_strlcatf(detail, sizeof(detail), "%s/%s/%s, ",
3100                                 av_color_space_name(enc->colorspace),
3101                                 av_color_primaries_name(enc->color_primaries),
3102                                 av_color_transfer_name(enc->color_trc));
3103                 } else
3104                     av_strlcatf(detail, sizeof(detail), "%s, ",
3105                                 av_get_colorspace_name(enc->colorspace));
3106             }
3107
3108             if (av_log_get_level() >= AV_LOG_DEBUG &&
3109                 enc->chroma_sample_location != AVCHROMA_LOC_UNSPECIFIED)
3110                 av_strlcatf(detail, sizeof(detail), "%s, ",
3111                             av_chroma_location_name(enc->chroma_sample_location));
3112
3113             if (strlen(detail) > 1) {
3114                 detail[strlen(detail) - 2] = 0;
3115                 av_strlcatf(buf, buf_size, "%s)", detail);
3116             }
3117         }
3118
3119         if (enc->width) {
3120             av_strlcat(buf, new_line ? separator : ", ", buf_size);
3121
3122             snprintf(buf + strlen(buf), buf_size - strlen(buf),
3123                      "%dx%d",
3124                      enc->width, enc->height);
3125
3126             if (av_log_get_level() >= AV_LOG_VERBOSE &&
3127                 (enc->width != enc->coded_width ||
3128                  enc->height != enc->coded_height))
3129                 snprintf(buf + strlen(buf), buf_size - strlen(buf),
3130                          " (%dx%d)", enc->coded_width, enc->coded_height);
3131
3132             if (enc->sample_aspect_ratio.num) {
3133                 av_reduce(&display_aspect_ratio.num, &display_aspect_ratio.den,
3134                           enc->width * enc->sample_aspect_ratio.num,
3135                           enc->height * enc->sample_aspect_ratio.den,
3136                           1024 * 1024);
3137                 snprintf(buf + strlen(buf), buf_size - strlen(buf),
3138                          " [SAR %d:%d DAR %d:%d]",
3139                          enc->sample_aspect_ratio.num, enc->sample_aspect_ratio.den,
3140                          display_aspect_ratio.num, display_aspect_ratio.den);
3141             }
3142             if (av_log_get_level() >= AV_LOG_DEBUG) {
3143                 int g = av_gcd(enc->time_base.num, enc->time_base.den);
3144                 snprintf(buf + strlen(buf), buf_size - strlen(buf),
3145                          ", %d/%d",
3146                          enc->time_base.num / g, enc->time_base.den / g);
3147             }
3148         }
3149         if (encode) {
3150             snprintf(buf + strlen(buf), buf_size - strlen(buf),
3151                      ", q=%d-%d", enc->qmin, enc->qmax);
3152         }
3153         break;
3154     case AVMEDIA_TYPE_AUDIO:
3155         av_strlcat(buf, separator, buf_size);
3156
3157         if (enc->sample_rate) {
3158             snprintf(buf + strlen(buf), buf_size - strlen(buf),
3159                      "%d Hz, ", enc->sample_rate);
3160         }
3161         av_get_channel_layout_string(buf + strlen(buf), buf_size - strlen(buf), enc->channels, enc->channel_layout);
3162         if (enc->sample_fmt != AV_SAMPLE_FMT_NONE) {
3163             snprintf(buf + strlen(buf), buf_size - strlen(buf),
3164                      ", %s", av_get_sample_fmt_name(enc->sample_fmt));
3165         }
3166         if (   enc->bits_per_raw_sample > 0
3167             && enc->bits_per_raw_sample != av_get_bytes_per_sample(enc->sample_fmt) * 8)
3168             snprintf(buf + strlen(buf), buf_size - strlen(buf),
3169                      " (%d bit)", enc->bits_per_raw_sample);
3170         break;
3171     case AVMEDIA_TYPE_DATA:
3172         if (av_log_get_level() >= AV_LOG_DEBUG) {
3173             int g = av_gcd(enc->time_base.num, enc->time_base.den);
3174             if (g)
3175                 snprintf(buf + strlen(buf), buf_size - strlen(buf),
3176                          ", %d/%d",
3177                          enc->time_base.num / g, enc->time_base.den / g);
3178         }
3179         break;
3180     case AVMEDIA_TYPE_SUBTITLE:
3181         if (enc->width)
3182             snprintf(buf + strlen(buf), buf_size - strlen(buf),
3183                      ", %dx%d", enc->width, enc->height);
3184         break;
3185     default:
3186         return;
3187     }
3188     if (encode) {
3189         if (enc->flags & CODEC_FLAG_PASS1)
3190             snprintf(buf + strlen(buf), buf_size - strlen(buf),
3191                      ", pass 1");
3192         if (enc->flags & CODEC_FLAG_PASS2)
3193             snprintf(buf + strlen(buf), buf_size - strlen(buf),
3194                      ", pass 2");
3195     }
3196     bitrate = get_bit_rate(enc);
3197     if (bitrate != 0) {
3198         snprintf(buf + strlen(buf), buf_size - strlen(buf),
3199                  ", %d kb/s", bitrate / 1000);
3200     } else if (enc->rc_max_rate > 0) {
3201         snprintf(buf + strlen(buf), buf_size - strlen(buf),
3202                  ", max. %d kb/s", enc->rc_max_rate / 1000);
3203     }
3204 }
3205
3206 const char *av_get_profile_name(const AVCodec *codec, int profile)
3207 {
3208     const AVProfile *p;
3209     if (profile == FF_PROFILE_UNKNOWN || !codec->profiles)
3210         return NULL;
3211
3212     for (p = codec->profiles; p->profile != FF_PROFILE_UNKNOWN; p++)
3213         if (p->profile == profile)
3214             return p->name;
3215
3216     return NULL;
3217 }
3218
3219 unsigned avcodec_version(void)
3220 {
3221 //    av_assert0(AV_CODEC_ID_V410==164);
3222     av_assert0(AV_CODEC_ID_PCM_S8_PLANAR==65563);
3223     av_assert0(AV_CODEC_ID_ADPCM_G722==69660);
3224 //     av_assert0(AV_CODEC_ID_BMV_AUDIO==86071);
3225     av_assert0(AV_CODEC_ID_SRT==94216);
3226     av_assert0(LIBAVCODEC_VERSION_MICRO >= 100);
3227
3228     av_assert0(CODEC_ID_CLLC == AV_CODEC_ID_CLLC);
3229     av_assert0(CODEC_ID_PCM_S8_PLANAR == AV_CODEC_ID_PCM_S8_PLANAR);
3230     av_assert0(CODEC_ID_ADPCM_IMA_APC == AV_CODEC_ID_ADPCM_IMA_APC);
3231     av_assert0(CODEC_ID_ILBC == AV_CODEC_ID_ILBC);
3232     av_assert0(CODEC_ID_SRT == AV_CODEC_ID_SRT);
3233     return LIBAVCODEC_VERSION_INT;
3234 }
3235
3236 const char *avcodec_configuration(void)
3237 {
3238     return FFMPEG_CONFIGURATION;
3239 }
3240
3241 const char *avcodec_license(void)
3242 {
3243 #define LICENSE_PREFIX "libavcodec license: "
3244     return LICENSE_PREFIX FFMPEG_LICENSE + sizeof(LICENSE_PREFIX) - 1;
3245 }
3246
3247 void avcodec_flush_buffers(AVCodecContext *avctx)
3248 {
3249     if (HAVE_THREADS && avctx->active_thread_type & FF_THREAD_FRAME)
3250         ff_thread_flush(avctx);
3251     else if (avctx->codec->flush)
3252         avctx->codec->flush(avctx);
3253
3254     avctx->pts_correction_last_pts =
3255     avctx->pts_correction_last_dts = INT64_MIN;
3256
3257     if (!avctx->refcounted_frames)
3258         av_frame_unref(avctx->internal->to_free);
3259 }
3260
3261 int av_get_exact_bits_per_sample(enum AVCodecID codec_id)
3262 {
3263     switch (codec_id) {
3264     case AV_CODEC_ID_8SVX_EXP:
3265     case AV_CODEC_ID_8SVX_FIB:
3266     case AV_CODEC_ID_ADPCM_CT:
3267     case AV_CODEC_ID_ADPCM_IMA_APC:
3268     case AV_CODEC_ID_ADPCM_IMA_EA_SEAD:
3269     case AV_CODEC_ID_ADPCM_IMA_OKI:
3270     case AV_CODEC_ID_ADPCM_IMA_WS:
3271     case AV_CODEC_ID_ADPCM_G722:
3272     case AV_CODEC_ID_ADPCM_YAMAHA:
3273         return 4;
3274     case AV_CODEC_ID_DSD_LSBF:
3275     case AV_CODEC_ID_DSD_MSBF:
3276     case AV_CODEC_ID_DSD_LSBF_PLANAR:
3277     case AV_CODEC_ID_DSD_MSBF_PLANAR:
3278     case AV_CODEC_ID_PCM_ALAW:
3279     case AV_CODEC_ID_PCM_MULAW:
3280     case AV_CODEC_ID_PCM_S8:
3281     case AV_CODEC_ID_PCM_S8_PLANAR:
3282     case AV_CODEC_ID_PCM_U8:
3283     case AV_CODEC_ID_PCM_ZORK:
3284         return 8;
3285     case AV_CODEC_ID_PCM_S16BE:
3286     case AV_CODEC_ID_PCM_S16BE_PLANAR:
3287     case AV_CODEC_ID_PCM_S16LE:
3288     case AV_CODEC_ID_PCM_S16LE_PLANAR:
3289     case AV_CODEC_ID_PCM_U16BE:
3290     case AV_CODEC_ID_PCM_U16LE:
3291         return 16;
3292     case AV_CODEC_ID_PCM_S24DAUD:
3293     case AV_CODEC_ID_PCM_S24BE:
3294     case AV_CODEC_ID_PCM_S24LE:
3295     case AV_CODEC_ID_PCM_S24LE_PLANAR:
3296     case AV_CODEC_ID_PCM_U24BE:
3297     case AV_CODEC_ID_PCM_U24LE:
3298         return 24;
3299     case AV_CODEC_ID_PCM_S32BE:
3300     case AV_CODEC_ID_PCM_S32LE:
3301     case AV_CODEC_ID_PCM_S32LE_PLANAR:
3302     case AV_CODEC_ID_PCM_U32BE:
3303     case AV_CODEC_ID_PCM_U32LE:
3304     case AV_CODEC_ID_PCM_F32BE:
3305     case AV_CODEC_ID_PCM_F32LE:
3306         return 32;
3307     case AV_CODEC_ID_PCM_F64BE:
3308     case AV_CODEC_ID_PCM_F64LE:
3309         return 64;
3310     default:
3311         return 0;
3312     }
3313 }
3314
3315 enum AVCodecID av_get_pcm_codec(enum AVSampleFormat fmt, int be)
3316 {
3317     static const enum AVCodecID map[AV_SAMPLE_FMT_NB][2] = {
3318         [AV_SAMPLE_FMT_U8  ] = { AV_CODEC_ID_PCM_U8,    AV_CODEC_ID_PCM_U8    },
3319         [AV_SAMPLE_FMT_S16 ] = { AV_CODEC_ID_PCM_S16LE, AV_CODEC_ID_PCM_S16BE },
3320         [AV_SAMPLE_FMT_S32 ] = { AV_CODEC_ID_PCM_S32LE, AV_CODEC_ID_PCM_S32BE },
3321         [AV_SAMPLE_FMT_FLT ] = { AV_CODEC_ID_PCM_F32LE, AV_CODEC_ID_PCM_F32BE },
3322         [AV_SAMPLE_FMT_DBL ] = { AV_CODEC_ID_PCM_F64LE, AV_CODEC_ID_PCM_F64BE },
3323         [AV_SAMPLE_FMT_U8P ] = { AV_CODEC_ID_PCM_U8,    AV_CODEC_ID_PCM_U8    },
3324         [AV_SAMPLE_FMT_S16P] = { AV_CODEC_ID_PCM_S16LE, AV_CODEC_ID_PCM_S16BE },
3325         [AV_SAMPLE_FMT_S32P] = { AV_CODEC_ID_PCM_S32LE, AV_CODEC_ID_PCM_S32BE },
3326         [AV_SAMPLE_FMT_FLTP] = { AV_CODEC_ID_PCM_F32LE, AV_CODEC_ID_PCM_F32BE },
3327         [AV_SAMPLE_FMT_DBLP] = { AV_CODEC_ID_PCM_F64LE, AV_CODEC_ID_PCM_F64BE },
3328     };
3329     if (fmt < 0 || fmt >= AV_SAMPLE_FMT_NB)
3330         return AV_CODEC_ID_NONE;
3331     if (be < 0 || be > 1)
3332         be = AV_NE(1, 0);
3333     return map[fmt][be];
3334 }
3335
3336 int av_get_bits_per_sample(enum AVCodecID codec_id)
3337 {
3338     switch (codec_id) {
3339     case AV_CODEC_ID_ADPCM_SBPRO_2:
3340         return 2;
3341     case AV_CODEC_ID_ADPCM_SBPRO_3:
3342         return 3;
3343     case AV_CODEC_ID_ADPCM_SBPRO_4:
3344     case AV_CODEC_ID_ADPCM_IMA_WAV:
3345     case AV_CODEC_ID_ADPCM_IMA_QT:
3346     case AV_CODEC_ID_ADPCM_SWF:
3347     case AV_CODEC_ID_ADPCM_MS:
3348         return 4;
3349     default:
3350         return av_get_exact_bits_per_sample(codec_id);
3351     }
3352 }
3353
3354 int av_get_audio_frame_duration(AVCodecContext *avctx, int frame_bytes)
3355 {
3356     int id, sr, ch, ba, tag, bps;
3357
3358     id  = avctx->codec_id;
3359     sr  = avctx->sample_rate;
3360     ch  = avctx->channels;
3361     ba  = avctx->block_align;
3362     tag = avctx->codec_tag;
3363     bps = av_get_exact_bits_per_sample(avctx->codec_id);
3364
3365     /* codecs with an exact constant bits per sample */
3366     if (bps > 0 && ch > 0 && frame_bytes > 0 && ch < 32768 && bps < 32768)
3367         return (frame_bytes * 8LL) / (bps * ch);
3368     bps = avctx->bits_per_coded_sample;
3369
3370     /* codecs with a fixed packet duration */
3371     switch (id) {
3372     case AV_CODEC_ID_ADPCM_ADX:    return   32;
3373     case AV_CODEC_ID_ADPCM_IMA_QT: return   64;
3374     case AV_CODEC_ID_ADPCM_EA_XAS: return  128;
3375     case AV_CODEC_ID_AMR_NB:
3376     case AV_CODEC_ID_EVRC:
3377     case AV_CODEC_ID_GSM:
3378     case AV_CODEC_ID_QCELP:
3379     case AV_CODEC_ID_RA_288:       return  160;
3380     case AV_CODEC_ID_AMR_WB:
3381     case AV_CODEC_ID_GSM_MS:       return  320;
3382     case AV_CODEC_ID_MP1:          return  384;
3383     case AV_CODEC_ID_ATRAC1:       return  512;
3384     case AV_CODEC_ID_ATRAC3:       return 1024;
3385     case AV_CODEC_ID_ATRAC3P:      return 2048;
3386     case AV_CODEC_ID_MP2:
3387     case AV_CODEC_ID_MUSEPACK7:    return 1152;
3388     case AV_CODEC_ID_AC3:          return 1536;
3389     }
3390
3391     if (sr > 0) {
3392         /* calc from sample rate */
3393         if (id == AV_CODEC_ID_TTA)
3394             return 256 * sr / 245;
3395
3396         if (ch > 0) {
3397             /* calc from sample rate and channels */
3398             if (id == AV_CODEC_ID_BINKAUDIO_DCT)
3399                 return (480 << (sr / 22050)) / ch;
3400         }
3401     }
3402
3403     if (ba > 0) {
3404         /* calc from block_align */
3405         if (id == AV_CODEC_ID_SIPR) {
3406             switch (ba) {
3407             case 20: return 160;
3408             case 19: return 144;
3409             case 29: return 288;
3410             case 37: return 480;
3411             }
3412         } else if (id == AV_CODEC_ID_ILBC) {
3413             switch (ba) {
3414             case 38: return 160;
3415             case 50: return 240;
3416             }
3417         }
3418     }
3419
3420     if (frame_bytes > 0) {
3421         /* calc from frame_bytes only */
3422         if (id == AV_CODEC_ID_TRUESPEECH)
3423             return 240 * (frame_bytes / 32);
3424         if (id == AV_CODEC_ID_NELLYMOSER)
3425             return 256 * (frame_bytes / 64);
3426         if (id == AV_CODEC_ID_RA_144)
3427             return 160 * (frame_bytes / 20);
3428         if (id == AV_CODEC_ID_G723_1)
3429             return 240 * (frame_bytes / 24);
3430
3431         if (bps > 0) {
3432             /* calc from frame_bytes and bits_per_coded_sample */
3433             if (id == AV_CODEC_ID_ADPCM_G726)
3434                 return frame_bytes * 8 / bps;
3435         }
3436
3437         if (ch > 0) {
3438             /* calc from frame_bytes and channels */
3439             switch (id) {
3440             case AV_CODEC_ID_ADPCM_AFC:
3441                 return frame_bytes / (9 * ch) * 16;
3442             case AV_CODEC_ID_ADPCM_DTK:
3443                 return frame_bytes / (16 * ch) * 28;
3444             case AV_CODEC_ID_ADPCM_4XM:
3445             case AV_CODEC_ID_ADPCM_IMA_ISS:
3446                 return (frame_bytes - 4 * ch) * 2 / ch;
3447             case AV_CODEC_ID_ADPCM_IMA_SMJPEG:
3448                 return (frame_bytes - 4) * 2 / ch;
3449             case AV_CODEC_ID_ADPCM_IMA_AMV:
3450                 return (frame_bytes - 8) * 2 / ch;
3451             case AV_CODEC_ID_ADPCM_THP:
3452             case AV_CODEC_ID_ADPCM_THP_LE:
3453                 if (avctx->extradata)
3454                     return frame_bytes * 14 / (8 * ch);
3455                 break;
3456             case AV_CODEC_ID_ADPCM_XA:
3457                 return (frame_bytes / 128) * 224 / ch;
3458             case AV_CODEC_ID_INTERPLAY_DPCM:
3459                 return (frame_bytes - 6 - ch) / ch;
3460             case AV_CODEC_ID_ROQ_DPCM:
3461                 return (frame_bytes - 8) / ch;
3462             case AV_CODEC_ID_XAN_DPCM:
3463                 return (frame_bytes - 2 * ch) / ch;
3464             case AV_CODEC_ID_MACE3:
3465                 return 3 * frame_bytes / ch;
3466             case AV_CODEC_ID_MACE6:
3467                 return 6 * frame_bytes / ch;
3468             case AV_CODEC_ID_PCM_LXF:
3469                 return 2 * (frame_bytes / (5 * ch));
3470             case AV_CODEC_ID_IAC:
3471             case AV_CODEC_ID_IMC:
3472                 return 4 * frame_bytes / ch;
3473             }
3474
3475             if (tag) {
3476                 /* calc from frame_bytes, channels, and codec_tag */
3477                 if (id == AV_CODEC_ID_SOL_DPCM) {
3478                     if (tag == 3)
3479                         return frame_bytes / ch;
3480                     else
3481                         return frame_bytes * 2 / ch;
3482                 }
3483             }
3484
3485             if (ba > 0) {
3486                 /* calc from frame_bytes, channels, and block_align */
3487                 int blocks = frame_bytes / ba;
3488                 switch (avctx->codec_id) {
3489                 case AV_CODEC_ID_ADPCM_IMA_WAV:
3490                     if (bps < 2 || bps > 5)
3491                         return 0;
3492                     return blocks * (1 + (ba - 4 * ch) / (bps * ch) * 8);
3493                 case AV_CODEC_ID_ADPCM_IMA_DK3:
3494                     return blocks * (((ba - 16) * 2 / 3 * 4) / ch);
3495                 case AV_CODEC_ID_ADPCM_IMA_DK4:
3496                     return blocks * (1 + (ba - 4 * ch) * 2 / ch);
3497                 case AV_CODEC_ID_ADPCM_IMA_RAD:
3498                     return blocks * ((ba - 4 * ch) * 2 / ch);
3499                 case AV_CODEC_ID_ADPCM_MS:
3500                     return blocks * (2 + (ba - 7 * ch) * 2 / ch);
3501                 }
3502             }
3503
3504             if (bps > 0) {
3505                 /* calc from frame_bytes, channels, and bits_per_coded_sample */
3506                 switch (avctx->codec_id) {
3507                 case AV_CODEC_ID_PCM_DVD:
3508                     if(bps<4)
3509                         return 0;
3510                     return 2 * (frame_bytes / ((bps * 2 / 8) * ch));
3511                 case AV_CODEC_ID_PCM_BLURAY:
3512                     if(bps<4)
3513                         return 0;
3514                     return frame_bytes / ((FFALIGN(ch, 2) * bps) / 8);
3515                 case AV_CODEC_ID_S302M:
3516                     return 2 * (frame_bytes / ((bps + 4) / 4)) / ch;
3517                 }
3518             }
3519         }
3520     }
3521
3522     /* Fall back on using frame_size */
3523     if (avctx->frame_size > 1 && frame_bytes)
3524         return avctx->frame_size;
3525
3526     //For WMA we currently have no other means to calculate duration thus we
3527     //do it here by assuming CBR, which is true for all known cases.
3528     if (avctx->bit_rate>0 && frame_bytes>0 && avctx->sample_rate>0 && avctx->block_align>1) {
3529         if (avctx->codec_id == AV_CODEC_ID_WMAV1 || avctx->codec_id == AV_CODEC_ID_WMAV2)
3530             return  (frame_bytes * 8LL * avctx->sample_rate) / avctx->bit_rate;
3531     }
3532
3533     return 0;
3534 }
3535
3536 #if !HAVE_THREADS
3537 int ff_thread_init(AVCodecContext *s)
3538 {
3539     return -1;
3540 }
3541
3542 #endif
3543
3544 unsigned int av_xiphlacing(unsigned char *s, unsigned int v)
3545 {
3546     unsigned int n = 0;
3547
3548     while (v >= 0xff) {
3549         *s++ = 0xff;
3550         v -= 0xff;
3551         n++;
3552     }
3553     *s = v;
3554     n++;
3555     return n;
3556 }
3557
3558 int ff_match_2uint16(const uint16_t(*tab)[2], int size, int a, int b)
3559 {
3560     int i;
3561     for (i = 0; i < size && !(tab[i][0] == a && tab[i][1] == b); i++) ;
3562     return i;
3563 }
3564
3565 #if FF_API_MISSING_SAMPLE
3566 FF_DISABLE_DEPRECATION_WARNINGS
3567 void av_log_missing_feature(void *avc, const char *feature, int want_sample)
3568 {
3569     av_log(avc, AV_LOG_WARNING, "%s is not implemented. Update your FFmpeg "
3570             "version to the newest one from Git. If the problem still "
3571             "occurs, it means that your file has a feature which has not "
3572             "been implemented.\n", feature);
3573     if(want_sample)
3574         av_log_ask_for_sample(avc, NULL);
3575 }
3576
3577 void av_log_ask_for_sample(void *avc, const char *msg, ...)
3578 {
3579     va_list argument_list;
3580
3581     va_start(argument_list, msg);
3582
3583     if (msg)
3584         av_vlog(avc, AV_LOG_WARNING, msg, argument_list);
3585     av_log(avc, AV_LOG_WARNING, "If you want to help, upload a sample "
3586             "of this file to ftp://upload.ffmpeg.org/incoming/ "
3587             "and contact the ffmpeg-devel mailing list. (ffmpeg-devel@ffmpeg.org)\n");
3588
3589     va_end(argument_list);
3590 }
3591 FF_ENABLE_DEPRECATION_WARNINGS
3592 #endif /* FF_API_MISSING_SAMPLE */
3593
3594 static AVHWAccel *first_hwaccel = NULL;
3595 static AVHWAccel **last_hwaccel = &first_hwaccel;
3596
3597 void av_register_hwaccel(AVHWAccel *hwaccel)
3598 {
3599     AVHWAccel **p = last_hwaccel;
3600     hwaccel->next = NULL;
3601     while(*p || avpriv_atomic_ptr_cas((void * volatile *)p, NULL, hwaccel))
3602         p = &(*p)->next;
3603     last_hwaccel = &hwaccel->next;
3604 }
3605
3606 AVHWAccel *av_hwaccel_next(const AVHWAccel *hwaccel)
3607 {
3608     return hwaccel ? hwaccel->next : first_hwaccel;
3609 }
3610
3611 int av_lockmgr_register(int (*cb)(void **mutex, enum AVLockOp op))
3612 {
3613     if (lockmgr_cb) {
3614         // There is no good way to rollback a failure to destroy the
3615         // mutex, so we ignore failures.
3616         lockmgr_cb(&codec_mutex,    AV_LOCK_DESTROY);
3617         lockmgr_cb(&avformat_mutex, AV_LOCK_DESTROY);
3618         lockmgr_cb     = NULL;
3619         codec_mutex    = NULL;
3620         avformat_mutex = NULL;
3621     }
3622
3623     if (cb) {
3624         void *new_codec_mutex    = NULL;
3625         void *new_avformat_mutex = NULL;
3626         int err;
3627         if (err = cb(&new_codec_mutex, AV_LOCK_CREATE)) {
3628             return err > 0 ? AVERROR_UNKNOWN : err;
3629         }
3630         if (err = cb(&new_avformat_mutex, AV_LOCK_CREATE)) {
3631             // Ignore failures to destroy the newly created mutex.
3632             cb(&new_codec_mutex, AV_LOCK_DESTROY);
3633             return err > 0 ? AVERROR_UNKNOWN : err;
3634         }
3635         lockmgr_cb     = cb;
3636         codec_mutex    = new_codec_mutex;
3637         avformat_mutex = new_avformat_mutex;
3638     }
3639
3640     return 0;
3641 }
3642
3643 int ff_lock_avcodec(AVCodecContext *log_ctx, const AVCodec *codec)
3644 {
3645     if (lockmgr_cb) {
3646         if ((*lockmgr_cb)(&codec_mutex, AV_LOCK_OBTAIN))
3647             return -1;
3648     }
3649
3650     if (avpriv_atomic_int_add_and_fetch(&entangled_thread_counter, 1) != 1 &&
3651         !(codec->caps_internal & FF_CODEC_CAP_INIT_THREADSAFE)) {
3652         av_log(log_ctx, AV_LOG_ERROR,
3653                "Insufficient thread locking. At least %d threads are "
3654                "calling avcodec_open2() at the same time right now.\n",
3655                entangled_thread_counter);
3656         if (!lockmgr_cb)
3657             av_log(log_ctx, AV_LOG_ERROR, "No lock manager is set, please see av_lockmgr_register()\n");
3658         ff_avcodec_locked = 1;
3659         ff_unlock_avcodec();
3660         return AVERROR(EINVAL);
3661     }
3662     av_assert0(!ff_avcodec_locked);
3663     ff_avcodec_locked = 1;
3664     return 0;
3665 }
3666
3667 int ff_unlock_avcodec(void)
3668 {
3669     av_assert0(ff_avcodec_locked);
3670     ff_avcodec_locked = 0;
3671     avpriv_atomic_int_add_and_fetch(&entangled_thread_counter, -1);
3672     if (lockmgr_cb) {
3673         if ((*lockmgr_cb)(&codec_mutex, AV_LOCK_RELEASE))
3674             return -1;
3675     }
3676
3677     return 0;
3678 }
3679
3680 int avpriv_lock_avformat(void)
3681 {
3682     if (lockmgr_cb) {
3683         if ((*lockmgr_cb)(&avformat_mutex, AV_LOCK_OBTAIN))
3684             return -1;
3685     }
3686     return 0;
3687 }
3688
3689 int avpriv_unlock_avformat(void)
3690 {
3691     if (lockmgr_cb) {
3692         if ((*lockmgr_cb)(&avformat_mutex, AV_LOCK_RELEASE))
3693             return -1;
3694     }
3695     return 0;
3696 }
3697
3698 unsigned int avpriv_toupper4(unsigned int x)
3699 {
3700     return av_toupper(x & 0xFF) +
3701           (av_toupper((x >>  8) & 0xFF) << 8)  +
3702           (av_toupper((x >> 16) & 0xFF) << 16) +
3703 ((unsigned)av_toupper((x >> 24) & 0xFF) << 24);
3704 }
3705
3706 int ff_thread_ref_frame(ThreadFrame *dst, ThreadFrame *src)
3707 {
3708     int ret;
3709
3710     dst->owner = src->owner;
3711
3712     ret = av_frame_ref(dst->f, src->f);
3713     if (ret < 0)
3714         return ret;
3715
3716     av_assert0(!dst->progress);
3717
3718     if (src->progress &&
3719         !(dst->progress = av_buffer_ref(src->progress))) {
3720         ff_thread_release_buffer(dst->owner, dst);
3721         return AVERROR(ENOMEM);
3722     }
3723
3724     return 0;
3725 }
3726
3727 #if !HAVE_THREADS
3728
3729 enum AVPixelFormat ff_thread_get_format(AVCodecContext *avctx, const enum AVPixelFormat *fmt)
3730 {
3731     return ff_get_format(avctx, fmt);
3732 }
3733
3734 int ff_thread_get_buffer(AVCodecContext *avctx, ThreadFrame *f, int flags)
3735 {
3736     f->owner = avctx;
3737     return ff_get_buffer(avctx, f->f, flags);
3738 }
3739
3740 void ff_thread_release_buffer(AVCodecContext *avctx, ThreadFrame *f)
3741 {
3742     if (f->f)
3743         av_frame_unref(f->f);
3744 }
3745
3746 void ff_thread_finish_setup(AVCodecContext *avctx)
3747 {
3748 }
3749
3750 void ff_thread_report_progress(ThreadFrame *f, int progress, int field)
3751 {
3752 }
3753
3754 void ff_thread_await_progress(ThreadFrame *f, int progress, int field)
3755 {
3756 }
3757
3758 int ff_thread_can_start_frame(AVCodecContext *avctx)
3759 {
3760     return 1;
3761 }
3762
3763 int ff_alloc_entries(AVCodecContext *avctx, int count)
3764 {
3765     return 0;
3766 }
3767
3768 void ff_reset_entries(AVCodecContext *avctx)
3769 {
3770 }
3771
3772 void ff_thread_await_progress2(AVCodecContext *avctx, int field, int thread, int shift)
3773 {
3774 }
3775
3776 void ff_thread_report_progress2(AVCodecContext *avctx, int field, int thread, int n)
3777 {
3778 }
3779
3780 #endif
3781
3782 enum AVMediaType avcodec_get_type(enum AVCodecID codec_id)
3783 {
3784     AVCodec *c= avcodec_find_decoder(codec_id);
3785     if(!c)
3786         c= avcodec_find_encoder(codec_id);
3787     if(c)
3788         return c->type;
3789
3790     if (codec_id <= AV_CODEC_ID_NONE)
3791         return AVMEDIA_TYPE_UNKNOWN;
3792     else if (codec_id < AV_CODEC_ID_FIRST_AUDIO)
3793         return AVMEDIA_TYPE_VIDEO;
3794     else if (codec_id < AV_CODEC_ID_FIRST_SUBTITLE)
3795         return AVMEDIA_TYPE_AUDIO;
3796     else if (codec_id < AV_CODEC_ID_FIRST_UNKNOWN)
3797         return AVMEDIA_TYPE_SUBTITLE;
3798
3799     return AVMEDIA_TYPE_UNKNOWN;
3800 }
3801
3802 int avcodec_is_open(AVCodecContext *s)
3803 {
3804     return !!s->internal;
3805 }
3806
3807 int avpriv_bprint_to_extradata(AVCodecContext *avctx, struct AVBPrint *buf)
3808 {
3809     int ret;
3810     char *str;
3811
3812     ret = av_bprint_finalize(buf, &str);
3813     if (ret < 0)
3814         return ret;
3815     if (!av_bprint_is_complete(buf)) {
3816         av_free(str);
3817         return AVERROR(ENOMEM);
3818     }
3819
3820     avctx->extradata = str;
3821     /* Note: the string is NUL terminated (so extradata can be read as a
3822      * string), but the ending character is not accounted in the size (in
3823      * binary formats you are likely not supposed to mux that character). When
3824      * extradata is copied, it is also padded with FF_INPUT_BUFFER_PADDING_SIZE
3825      * zeros. */
3826     avctx->extradata_size = buf->len;
3827     return 0;
3828 }
3829
3830 const uint8_t *avpriv_find_start_code(const uint8_t *av_restrict p,
3831                                       const uint8_t *end,
3832                                       uint32_t *av_restrict state)
3833 {
3834     int i;
3835
3836     av_assert0(p <= end);
3837     if (p >= end)
3838         return end;
3839
3840     for (i = 0; i < 3; i++) {
3841         uint32_t tmp = *state << 8;
3842         *state = tmp + *(p++);
3843         if (tmp == 0x100 || p == end)
3844             return p;
3845     }
3846
3847     while (p < end) {
3848         if      (p[-1] > 1      ) p += 3;
3849         else if (p[-2]          ) p += 2;
3850         else if (p[-3]|(p[-1]-1)) p++;
3851         else {
3852             p++;
3853             break;
3854         }
3855     }
3856
3857     p = FFMIN(p, end) - 4;
3858     *state = AV_RB32(p);
3859
3860     return p + 4;
3861 }