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