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