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