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