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