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