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