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