]> git.sesse.net Git - ffmpeg/blob - libavcodec/utils.c
lavc decoders: work with refcounted frames.
[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 Libav.
7  *
8  * Libav 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  * Libav 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 Libav; if not, write to the Free Software
20  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
21  */
22
23 /**
24  * @file
25  * utils.
26  */
27
28 #include "config.h"
29 #include "libavutil/avassert.h"
30 #include "libavutil/avstring.h"
31 #include "libavutil/channel_layout.h"
32 #include "libavutil/crc.h"
33 #include "libavutil/frame.h"
34 #include "libavutil/mathematics.h"
35 #include "libavutil/pixdesc.h"
36 #include "libavutil/imgutils.h"
37 #include "libavutil/samplefmt.h"
38 #include "libavutil/dict.h"
39 #include "avcodec.h"
40 #include "dsputil.h"
41 #include "libavutil/opt.h"
42 #include "thread.h"
43 #include "internal.h"
44 #include "bytestream.h"
45 #include <stdlib.h>
46 #include <stdarg.h>
47 #include <limits.h>
48 #include <float.h>
49
50 static int volatile entangled_thread_counter = 0;
51 static int (*ff_lockmgr_cb)(void **mutex, enum AVLockOp op);
52 static void *codec_mutex;
53 static void *avformat_mutex;
54
55 void *av_fast_realloc(void *ptr, unsigned int *size, size_t min_size)
56 {
57     if (min_size < *size)
58         return ptr;
59
60     min_size = FFMAX(17 * min_size / 16 + 32, min_size);
61
62     ptr = av_realloc(ptr, min_size);
63     /* we could set this to the unmodified min_size but this is safer
64      * if the user lost the ptr and uses NULL now
65      */
66     if (!ptr)
67         min_size = 0;
68
69     *size = min_size;
70
71     return ptr;
72 }
73
74 void av_fast_malloc(void *ptr, unsigned int *size, size_t min_size)
75 {
76     void **p = ptr;
77     if (min_size < *size)
78         return;
79     min_size = FFMAX(17 * min_size / 16 + 32, min_size);
80     av_free(*p);
81     *p = av_malloc(min_size);
82     if (!*p)
83         min_size = 0;
84     *size = min_size;
85 }
86
87 void av_fast_padded_malloc(void *ptr, unsigned int *size, size_t min_size)
88 {
89     void **p = ptr;
90     if (min_size > SIZE_MAX - FF_INPUT_BUFFER_PADDING_SIZE) {
91         av_freep(p);
92         *size = 0;
93         return;
94     }
95     av_fast_malloc(p, size, min_size + FF_INPUT_BUFFER_PADDING_SIZE);
96     if (*size)
97         memset((uint8_t *)*p + min_size, 0, FF_INPUT_BUFFER_PADDING_SIZE);
98 }
99
100 /* encoder management */
101 static AVCodec *first_avcodec = NULL;
102
103 AVCodec *av_codec_next(const AVCodec *c)
104 {
105     if (c)
106         return c->next;
107     else
108         return first_avcodec;
109 }
110
111 static void avcodec_init(void)
112 {
113     static int initialized = 0;
114
115     if (initialized != 0)
116         return;
117     initialized = 1;
118
119     ff_dsputil_static_init();
120 }
121
122 int av_codec_is_encoder(const AVCodec *codec)
123 {
124     return codec && (codec->encode_sub || codec->encode2);
125 }
126
127 int av_codec_is_decoder(const AVCodec *codec)
128 {
129     return codec && codec->decode;
130 }
131
132 void avcodec_register(AVCodec *codec)
133 {
134     AVCodec **p;
135     avcodec_init();
136     p = &first_avcodec;
137     while (*p != NULL)
138         p = &(*p)->next;
139     *p          = codec;
140     codec->next = NULL;
141
142     if (codec->init_static_data)
143         codec->init_static_data(codec);
144 }
145
146 unsigned avcodec_get_edge_width(void)
147 {
148     return EDGE_WIDTH;
149 }
150
151 void avcodec_set_dimensions(AVCodecContext *s, int width, int height)
152 {
153     s->coded_width  = width;
154     s->coded_height = height;
155     s->width        = width;
156     s->height       = height;
157 }
158
159 #if (ARCH_ARM && HAVE_NEON) || ARCH_PPC || HAVE_MMX
160 #   define STRIDE_ALIGN 16
161 #else
162 #   define STRIDE_ALIGN 8
163 #endif
164
165 void avcodec_align_dimensions2(AVCodecContext *s, int *width, int *height,
166                                int linesize_align[AV_NUM_DATA_POINTERS])
167 {
168     int i;
169     int w_align = 1;
170     int h_align = 1;
171
172     switch (s->pix_fmt) {
173     case AV_PIX_FMT_YUV420P:
174     case AV_PIX_FMT_YUYV422:
175     case AV_PIX_FMT_UYVY422:
176     case AV_PIX_FMT_YUV422P:
177     case AV_PIX_FMT_YUV440P:
178     case AV_PIX_FMT_YUV444P:
179     case AV_PIX_FMT_GBRP:
180     case AV_PIX_FMT_GRAY8:
181     case AV_PIX_FMT_GRAY16BE:
182     case AV_PIX_FMT_GRAY16LE:
183     case AV_PIX_FMT_YUVJ420P:
184     case AV_PIX_FMT_YUVJ422P:
185     case AV_PIX_FMT_YUVJ440P:
186     case AV_PIX_FMT_YUVJ444P:
187     case AV_PIX_FMT_YUVA420P:
188     case AV_PIX_FMT_YUVA422P:
189     case AV_PIX_FMT_YUVA444P:
190     case AV_PIX_FMT_YUV420P9LE:
191     case AV_PIX_FMT_YUV420P9BE:
192     case AV_PIX_FMT_YUV420P10LE:
193     case AV_PIX_FMT_YUV420P10BE:
194     case AV_PIX_FMT_YUV422P9LE:
195     case AV_PIX_FMT_YUV422P9BE:
196     case AV_PIX_FMT_YUV422P10LE:
197     case AV_PIX_FMT_YUV422P10BE:
198     case AV_PIX_FMT_YUV444P9LE:
199     case AV_PIX_FMT_YUV444P9BE:
200     case AV_PIX_FMT_YUV444P10LE:
201     case AV_PIX_FMT_YUV444P10BE:
202     case AV_PIX_FMT_GBRP9LE:
203     case AV_PIX_FMT_GBRP9BE:
204     case AV_PIX_FMT_GBRP10LE:
205     case AV_PIX_FMT_GBRP10BE:
206         w_align = 16; //FIXME assume 16 pixel per macroblock
207         h_align = 16 * 2; // interlaced needs 2 macroblocks height
208         break;
209     case AV_PIX_FMT_YUV411P:
210     case AV_PIX_FMT_UYYVYY411:
211         w_align = 32;
212         h_align = 8;
213         break;
214     case AV_PIX_FMT_YUV410P:
215         if (s->codec_id == AV_CODEC_ID_SVQ1) {
216             w_align = 64;
217             h_align = 64;
218         }
219     case AV_PIX_FMT_RGB555:
220         if (s->codec_id == AV_CODEC_ID_RPZA) {
221             w_align = 4;
222             h_align = 4;
223         }
224     case AV_PIX_FMT_PAL8:
225     case AV_PIX_FMT_BGR8:
226     case AV_PIX_FMT_RGB8:
227         if (s->codec_id == AV_CODEC_ID_SMC) {
228             w_align = 4;
229             h_align = 4;
230         }
231         break;
232     case AV_PIX_FMT_BGR24:
233         if ((s->codec_id == AV_CODEC_ID_MSZH) ||
234             (s->codec_id == AV_CODEC_ID_ZLIB)) {
235             w_align = 4;
236             h_align = 4;
237         }
238         break;
239     default:
240         w_align = 1;
241         h_align = 1;
242         break;
243     }
244
245     *width  = FFALIGN(*width, w_align);
246     *height = FFALIGN(*height, h_align);
247     if (s->codec_id == AV_CODEC_ID_H264)
248         // some of the optimized chroma MC reads one line too much
249         *height += 2;
250
251     for (i = 0; i < 4; i++)
252         linesize_align[i] = STRIDE_ALIGN;
253 }
254
255 void avcodec_align_dimensions(AVCodecContext *s, int *width, int *height)
256 {
257     const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(s->pix_fmt);
258     int chroma_shift = desc->log2_chroma_w;
259     int linesize_align[AV_NUM_DATA_POINTERS];
260     int align;
261
262     avcodec_align_dimensions2(s, width, height, linesize_align);
263     align               = FFMAX(linesize_align[0], linesize_align[3]);
264     linesize_align[1] <<= chroma_shift;
265     linesize_align[2] <<= chroma_shift;
266     align               = FFMAX3(align, linesize_align[1], linesize_align[2]);
267     *width              = FFALIGN(*width, align);
268 }
269
270 int avcodec_fill_audio_frame(AVFrame *frame, int nb_channels,
271                              enum AVSampleFormat sample_fmt, const uint8_t *buf,
272                              int buf_size, int align)
273 {
274     int ch, planar, needed_size, ret = 0;
275
276     needed_size = av_samples_get_buffer_size(NULL, nb_channels,
277                                              frame->nb_samples, sample_fmt,
278                                              align);
279     if (buf_size < needed_size)
280         return AVERROR(EINVAL);
281
282     planar = av_sample_fmt_is_planar(sample_fmt);
283     if (planar && nb_channels > AV_NUM_DATA_POINTERS) {
284         if (!(frame->extended_data = av_mallocz(nb_channels *
285                                                 sizeof(*frame->extended_data))))
286             return AVERROR(ENOMEM);
287     } else {
288         frame->extended_data = frame->data;
289     }
290
291     if ((ret = av_samples_fill_arrays(frame->extended_data, &frame->linesize[0],
292                                       buf, nb_channels, frame->nb_samples,
293                                       sample_fmt, align)) < 0) {
294         if (frame->extended_data != frame->data)
295             av_free(frame->extended_data);
296         return ret;
297     }
298     if (frame->extended_data != frame->data) {
299         for (ch = 0; ch < AV_NUM_DATA_POINTERS; ch++)
300             frame->data[ch] = frame->extended_data[ch];
301     }
302
303     return ret;
304 }
305
306 static int update_frame_pool(AVCodecContext *avctx, AVFrame *frame)
307 {
308     FramePool *pool = avctx->internal->pool;
309     int i, ret;
310
311     switch (avctx->codec_type) {
312     case AVMEDIA_TYPE_VIDEO: {
313         AVPicture picture;
314         int size[4] = { 0 };
315         int w = frame->width;
316         int h = frame->height;
317         int tmpsize, unaligned;
318
319         if (pool->format == frame->format &&
320             pool->width == frame->width && pool->height == frame->height)
321             return 0;
322
323         avcodec_align_dimensions2(avctx, &w, &h, pool->stride_align);
324
325         if (!(avctx->flags & CODEC_FLAG_EMU_EDGE)) {
326             w += EDGE_WIDTH * 2;
327             h += EDGE_WIDTH * 2;
328         }
329
330         do {
331             // NOTE: do not align linesizes individually, this breaks e.g. assumptions
332             // that linesize[0] == 2*linesize[1] in the MPEG-encoder for 4:2:2
333             av_image_fill_linesizes(picture.linesize, avctx->pix_fmt, w);
334             // increase alignment of w for next try (rhs gives the lowest bit set in w)
335             w += w & ~(w - 1);
336
337             unaligned = 0;
338             for (i = 0; i < 4; i++)
339                 unaligned |= picture.linesize[i] % pool->stride_align[i];
340         } while (unaligned);
341
342         tmpsize = av_image_fill_pointers(picture.data, avctx->pix_fmt, h,
343                                          NULL, picture.linesize);
344         if (tmpsize < 0)
345             return -1;
346
347         for (i = 0; i < 3 && picture.data[i + 1]; i++)
348             size[i] = picture.data[i + 1] - picture.data[i];
349         size[i] = tmpsize - (picture.data[i] - picture.data[0]);
350
351         for (i = 0; i < 4; i++) {
352             av_buffer_pool_uninit(&pool->pools[i]);
353             pool->linesize[i] = picture.linesize[i];
354             if (size[i]) {
355                 pool->pools[i] = av_buffer_pool_init(size[i] + 16, NULL);
356                 if (!pool->pools[i]) {
357                     ret = AVERROR(ENOMEM);
358                     goto fail;
359                 }
360             }
361         }
362         pool->format = frame->format;
363         pool->width  = frame->width;
364         pool->height = frame->height;
365
366         break;
367         }
368     case AVMEDIA_TYPE_AUDIO: {
369         int ch     = av_get_channel_layout_nb_channels(frame->channel_layout);
370         int planar = av_sample_fmt_is_planar(frame->format);
371         int planes = planar ? ch : 1;
372
373         if (pool->format == frame->format && pool->planes == planes &&
374             pool->channels == ch && frame->nb_samples == pool->samples)
375             return 0;
376
377         av_buffer_pool_uninit(&pool->pools[0]);
378         ret = av_samples_get_buffer_size(&pool->linesize[0], ch,
379                                          frame->nb_samples, frame->format, 0);
380         if (ret < 0)
381             goto fail;
382
383         pool->pools[0] = av_buffer_pool_init(pool->linesize[0], NULL);
384         if (!pool->pools[0]) {
385             ret = AVERROR(ENOMEM);
386             goto fail;
387         }
388
389         pool->format     = frame->format;
390         pool->planes     = planes;
391         pool->channels   = ch;
392         pool->samples = frame->nb_samples;
393         break;
394         }
395     default: av_assert0(0);
396     }
397     return 0;
398 fail:
399     for (i = 0; i < 4; i++)
400         av_buffer_pool_uninit(&pool->pools[i]);
401     pool->format = -1;
402     pool->planes = pool->channels = pool->samples = 0;
403     pool->width  = pool->height = 0;
404     return ret;
405 }
406
407 static int audio_get_buffer(AVCodecContext *avctx, AVFrame *frame)
408 {
409     FramePool *pool = avctx->internal->pool;
410     int planes = pool->planes;
411     int i;
412
413     frame->linesize[0] = pool->linesize[0];
414
415     if (planes > AV_NUM_DATA_POINTERS) {
416         frame->extended_data = av_mallocz(planes * sizeof(*frame->extended_data));
417         frame->nb_extended_buf = planes - AV_NUM_DATA_POINTERS;
418         frame->extended_buf  = av_mallocz(frame->nb_extended_buf *
419                                           sizeof(*frame->extended_buf));
420         if (!frame->extended_data || !frame->extended_buf) {
421             av_freep(&frame->extended_data);
422             av_freep(&frame->extended_buf);
423             return AVERROR(ENOMEM);
424         }
425     } else
426         frame->extended_data = frame->data;
427
428     for (i = 0; i < FFMIN(planes, AV_NUM_DATA_POINTERS); i++) {
429         frame->buf[i] = av_buffer_pool_get(pool->pools[0]);
430         if (!frame->buf[i])
431             goto fail;
432         frame->extended_data[i] = frame->data[i] = frame->buf[i]->data;
433     }
434     for (i = 0; i < frame->nb_extended_buf; i++) {
435         frame->extended_buf[i] = av_buffer_pool_get(pool->pools[0]);
436         if (!frame->extended_buf[i])
437             goto fail;
438         frame->extended_data[i + AV_NUM_DATA_POINTERS] = frame->extended_buf[i]->data;
439     }
440
441     if (avctx->debug & FF_DEBUG_BUFFERS)
442         av_log(avctx, AV_LOG_DEBUG, "default_get_buffer called on frame %p", frame);
443
444     return 0;
445 fail:
446     av_frame_unref(frame);
447     return AVERROR(ENOMEM);
448 }
449
450 static int video_get_buffer(AVCodecContext *s, AVFrame *pic)
451 {
452     FramePool *pool = s->internal->pool;
453     const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(pic->format);
454     int pixel_size = desc->comp[0].step_minus1 + 1;
455     int h_chroma_shift, v_chroma_shift;
456     int i;
457
458     if (pic->data[0] != NULL) {
459         av_log(s, AV_LOG_ERROR, "pic->data[0]!=NULL in avcodec_default_get_buffer\n");
460         return -1;
461     }
462
463     memset(pic->data, 0, sizeof(pic->data));
464     pic->extended_data = pic->data;
465
466     av_pix_fmt_get_chroma_sub_sample(s->pix_fmt, &h_chroma_shift, &v_chroma_shift);
467
468     for (i = 0; i < 4 && pool->pools[i]; i++) {
469         const int h_shift = i == 0 ? 0 : h_chroma_shift;
470         const int v_shift = i == 0 ? 0 : v_chroma_shift;
471
472         pic->linesize[i] = pool->linesize[i];
473
474         pic->buf[i] = av_buffer_pool_get(pool->pools[i]);
475         if (!pic->buf[i])
476             goto fail;
477
478         // no edge if EDGE EMU or not planar YUV
479         if ((s->flags & CODEC_FLAG_EMU_EDGE) || !pool->pools[2])
480             pic->data[i] = pic->buf[i]->data;
481         else {
482             pic->data[i] = pic->buf[i]->data +
483                 FFALIGN((pic->linesize[i] * EDGE_WIDTH >> v_shift) +
484                         (pixel_size * EDGE_WIDTH >> h_shift), pool->stride_align[i]);
485         }
486     }
487     for (; i < AV_NUM_DATA_POINTERS; i++) {
488         pic->data[i] = NULL;
489         pic->linesize[i] = 0;
490     }
491     if (pic->data[1] && !pic->data[2])
492         avpriv_set_systematic_pal2((uint32_t *)pic->data[1], s->pix_fmt);
493
494     if (s->debug & FF_DEBUG_BUFFERS)
495         av_log(s, AV_LOG_DEBUG, "default_get_buffer called on pic %p\n", pic);
496
497     return 0;
498 fail:
499     av_frame_unref(pic);
500     return AVERROR(ENOMEM);
501 }
502
503 int avcodec_default_get_buffer2(AVCodecContext *avctx, AVFrame *frame, int flags)
504 {
505     int ret;
506
507     if ((ret = update_frame_pool(avctx, frame)) < 0)
508         return ret;
509
510 #if FF_API_GET_BUFFER
511     frame->type = FF_BUFFER_TYPE_INTERNAL;
512 #endif
513
514     switch (avctx->codec_type) {
515     case AVMEDIA_TYPE_VIDEO:
516         return video_get_buffer(avctx, frame);
517     case AVMEDIA_TYPE_AUDIO:
518         return audio_get_buffer(avctx, frame);
519     default:
520         return -1;
521     }
522 }
523
524 #if FF_API_GET_BUFFER
525 int avcodec_default_get_buffer(AVCodecContext *avctx, AVFrame *frame)
526 {
527     return avcodec_default_get_buffer2(avctx, frame, 0);
528 }
529
530 typedef struct CompatReleaseBufPriv {
531     AVCodecContext avctx;
532     AVFrame frame;
533 } CompatReleaseBufPriv;
534
535 static void compat_free_buffer(void *opaque, uint8_t *data)
536 {
537     CompatReleaseBufPriv *priv = opaque;
538     priv->avctx.release_buffer(&priv->avctx, &priv->frame);
539     av_freep(&priv);
540 }
541
542 static void compat_release_buffer(void *opaque, uint8_t *data)
543 {
544     AVBufferRef *buf = opaque;
545     av_buffer_unref(&buf);
546 }
547 #endif
548
549 int ff_get_buffer(AVCodecContext *avctx, AVFrame *frame, int flags)
550 {
551     int ret;
552
553     switch (avctx->codec_type) {
554     case AVMEDIA_TYPE_VIDEO:
555         frame->width               = avctx->width;
556         frame->height              = avctx->height;
557         frame->format              = avctx->pix_fmt;
558         frame->sample_aspect_ratio = avctx->sample_aspect_ratio;
559
560         if ((ret = av_image_check_size(avctx->width, avctx->height, 0, avctx)) < 0)
561             return ret;
562         break;
563     case AVMEDIA_TYPE_AUDIO:
564         frame->sample_rate    = avctx->sample_rate;
565         frame->format         = avctx->sample_fmt;
566         frame->channel_layout = avctx->channel_layout;
567         break;
568     default: return AVERROR(EINVAL);
569     }
570
571     frame->pkt_pts = avctx->pkt ? avctx->pkt->pts : AV_NOPTS_VALUE;
572     frame->reordered_opaque = avctx->reordered_opaque;
573
574 #if FF_API_GET_BUFFER
575     /*
576      * Wrap an old get_buffer()-allocated buffer in an bunch of AVBuffers.
577      * We wrap each plane in its own AVBuffer. Each of those has a reference to
578      * a dummy AVBuffer as its private data, unreffing it on free.
579      * When all the planes are freed, the dummy buffer's free callback calls
580      * release_buffer().
581      */
582     if (avctx->get_buffer) {
583         CompatReleaseBufPriv *priv = NULL;
584         AVBufferRef *dummy_buf = NULL;
585         int planes, i, ret;
586
587         if (flags & AV_GET_BUFFER_FLAG_REF)
588             frame->reference    = 1;
589
590         ret = avctx->get_buffer(avctx, frame);
591         if (ret < 0)
592             return ret;
593
594         /* return if the buffers are already set up
595          * this would happen e.g. when a custom get_buffer() calls
596          * avcodec_default_get_buffer
597          */
598         if (frame->buf[0])
599             return 0;
600
601         priv = av_mallocz(sizeof(*priv));
602         if (!priv) {
603             ret = AVERROR(ENOMEM);
604             goto fail;
605         }
606         priv->avctx = *avctx;
607         priv->frame = *frame;
608
609         dummy_buf = av_buffer_create(NULL, 0, compat_free_buffer, priv, 0);
610         if (!dummy_buf) {
611             ret = AVERROR(ENOMEM);
612             goto fail;
613         }
614
615 #define WRAP_PLANE(ref_out, data, data_size)                            \
616 do {                                                                    \
617     AVBufferRef *dummy_ref = av_buffer_ref(dummy_buf);                  \
618     if (!dummy_ref) {                                                   \
619         ret = AVERROR(ENOMEM);                                          \
620         goto fail;                                                      \
621     }                                                                   \
622     ref_out = av_buffer_create(data, data_size, compat_release_buffer,  \
623                                dummy_ref, 0);                           \
624     if (!ref_out) {                                                     \
625         av_frame_unref(frame);                                          \
626         ret = AVERROR(ENOMEM);                                          \
627         goto fail;                                                      \
628     }                                                                   \
629 } while (0)
630
631         if (avctx->codec_type == AVMEDIA_TYPE_VIDEO) {
632             const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(frame->format);
633
634             if (!desc) {
635                 ret = AVERROR(EINVAL);
636                 goto fail;
637             }
638             planes = (desc->flags & PIX_FMT_PLANAR) ? desc->nb_components : 1;
639
640             for (i = 0; i < planes; i++) {
641                 int h_shift    = (i == 1 || i == 2) ? desc->log2_chroma_h : 0;
642                 int plane_size = (frame->width >> h_shift) * frame->linesize[i];
643
644                 WRAP_PLANE(frame->buf[i], frame->data[i], plane_size);
645             }
646         } else {
647             int planar = av_sample_fmt_is_planar(frame->format);
648             planes = planar ? avctx->channels : 1;
649
650             if (planes > FF_ARRAY_ELEMS(frame->buf)) {
651                 frame->nb_extended_buf = planes - FF_ARRAY_ELEMS(frame->buf);
652                 frame->extended_buf = av_malloc(sizeof(*frame->extended_buf) *
653                                                 frame->nb_extended_buf);
654                 if (!frame->extended_buf) {
655                     ret = AVERROR(ENOMEM);
656                     goto fail;
657                 }
658             }
659
660             for (i = 0; i < FFMIN(planes, FF_ARRAY_ELEMS(frame->buf)); i++)
661                 WRAP_PLANE(frame->buf[i], frame->extended_data[i], frame->linesize[0]);
662
663             for (i = 0; i < planes - FF_ARRAY_ELEMS(frame->buf); i++)
664                 WRAP_PLANE(frame->extended_buf[i],
665                            frame->extended_data[i + FF_ARRAY_ELEMS(frame->buf)],
666                            frame->linesize[0]);
667         }
668
669         av_buffer_unref(&dummy_buf);
670
671         return 0;
672
673 fail:
674         avctx->release_buffer(avctx, frame);
675         av_freep(&priv);
676         av_buffer_unref(&dummy_buf);
677         return ret;
678     }
679 #endif
680
681     return avctx->get_buffer2(avctx, frame, flags);
682 }
683
684 int ff_reget_buffer(AVCodecContext *avctx, AVFrame *frame)
685 {
686     AVFrame tmp;
687     int ret;
688
689     av_assert0(avctx->codec_type == AVMEDIA_TYPE_VIDEO);
690
691     if (!frame->data[0])
692         return ff_get_buffer(avctx, frame, AV_GET_BUFFER_FLAG_REF);
693
694     if (av_frame_is_writable(frame))
695         return 0;
696
697     av_frame_move_ref(&tmp, frame);
698
699     ret = ff_get_buffer(avctx, frame, AV_GET_BUFFER_FLAG_REF);
700     if (ret < 0) {
701         av_frame_unref(&tmp);
702         return ret;
703     }
704
705     av_image_copy(frame->data, frame->linesize, tmp.data, tmp.linesize,
706                   frame->format, frame->width, frame->height);
707
708     av_frame_unref(&tmp);
709
710     return 0;
711 }
712
713 #if FF_API_GET_BUFFER
714 void avcodec_default_release_buffer(AVCodecContext *s, AVFrame *pic)
715 {
716     av_frame_unref(pic);
717 }
718
719 int avcodec_default_reget_buffer(AVCodecContext *s, AVFrame *pic)
720 {
721     av_assert0(0);
722 }
723 #endif
724
725 int avcodec_default_execute(AVCodecContext *c, int (*func)(AVCodecContext *c2, void *arg2), void *arg, int *ret, int count, int size)
726 {
727     int i;
728
729     for (i = 0; i < count; i++) {
730         int r = func(c, (char *)arg + i * size);
731         if (ret)
732             ret[i] = r;
733     }
734     return 0;
735 }
736
737 int avcodec_default_execute2(AVCodecContext *c, int (*func)(AVCodecContext *c2, void *arg2, int jobnr, int threadnr), void *arg, int *ret, int count)
738 {
739     int i;
740
741     for (i = 0; i < count; i++) {
742         int r = func(c, arg, i, 0);
743         if (ret)
744             ret[i] = r;
745     }
746     return 0;
747 }
748
749 static int is_hwaccel_pix_fmt(enum AVPixelFormat pix_fmt)
750 {
751     const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(pix_fmt);
752     return desc->flags & PIX_FMT_HWACCEL;
753 }
754
755 enum AVPixelFormat avcodec_default_get_format(struct AVCodecContext *s, const enum AVPixelFormat *fmt)
756 {
757     while (*fmt != AV_PIX_FMT_NONE && is_hwaccel_pix_fmt(*fmt))
758         ++fmt;
759     return fmt[0];
760 }
761
762 void avcodec_get_frame_defaults(AVFrame *frame)
763 {
764     if (frame->extended_data != frame->data)
765         av_freep(&frame->extended_data);
766
767     memset(frame, 0, sizeof(AVFrame));
768
769     frame->pts                 = AV_NOPTS_VALUE;
770     frame->key_frame           = 1;
771     frame->sample_aspect_ratio = (AVRational) {0, 1 };
772     frame->format              = -1; /* unknown */
773     frame->extended_data       = frame->data;
774 }
775
776 AVFrame *avcodec_alloc_frame(void)
777 {
778     AVFrame *frame = av_mallocz(sizeof(AVFrame));
779
780     if (frame == NULL)
781         return NULL;
782
783     avcodec_get_frame_defaults(frame);
784
785     return frame;
786 }
787
788 void avcodec_free_frame(AVFrame **frame)
789 {
790     AVFrame *f;
791
792     if (!frame || !*frame)
793         return;
794
795     f = *frame;
796
797     if (f->extended_data != f->data)
798         av_freep(&f->extended_data);
799
800     av_freep(frame);
801 }
802
803 int attribute_align_arg avcodec_open2(AVCodecContext *avctx, const AVCodec *codec, AVDictionary **options)
804 {
805     int ret = 0;
806     AVDictionary *tmp = NULL;
807
808     if (avcodec_is_open(avctx))
809         return 0;
810
811     if ((!codec && !avctx->codec)) {
812         av_log(avctx, AV_LOG_ERROR, "No codec provided to avcodec_open2().\n");
813         return AVERROR(EINVAL);
814     }
815     if ((codec && avctx->codec && codec != avctx->codec)) {
816         av_log(avctx, AV_LOG_ERROR, "This AVCodecContext was allocated for %s, "
817                                     "but %s passed to avcodec_open2().\n", avctx->codec->name, codec->name);
818         return AVERROR(EINVAL);
819     }
820     if (!codec)
821         codec = avctx->codec;
822
823     if (avctx->extradata_size < 0 || avctx->extradata_size >= FF_MAX_EXTRADATA_SIZE)
824         return AVERROR(EINVAL);
825
826     if (options)
827         av_dict_copy(&tmp, *options, 0);
828
829     /* If there is a user-supplied mutex locking routine, call it. */
830     if (ff_lockmgr_cb) {
831         if ((*ff_lockmgr_cb)(&codec_mutex, AV_LOCK_OBTAIN))
832             return -1;
833     }
834
835     entangled_thread_counter++;
836     if (entangled_thread_counter != 1) {
837         av_log(avctx, AV_LOG_ERROR, "insufficient thread locking around avcodec_open/close()\n");
838         ret = -1;
839         goto end;
840     }
841
842     avctx->internal = av_mallocz(sizeof(AVCodecInternal));
843     if (!avctx->internal) {
844         ret = AVERROR(ENOMEM);
845         goto end;
846     }
847
848     avctx->internal->pool = av_mallocz(sizeof(*avctx->internal->pool));
849     if (!avctx->internal->pool) {
850         ret = AVERROR(ENOMEM);
851         goto free_and_end;
852     }
853
854     if (codec->priv_data_size > 0) {
855         if (!avctx->priv_data) {
856             avctx->priv_data = av_mallocz(codec->priv_data_size);
857             if (!avctx->priv_data) {
858                 ret = AVERROR(ENOMEM);
859                 goto end;
860             }
861             if (codec->priv_class) {
862                 *(const AVClass **)avctx->priv_data = codec->priv_class;
863                 av_opt_set_defaults(avctx->priv_data);
864             }
865         }
866         if (codec->priv_class && (ret = av_opt_set_dict(avctx->priv_data, &tmp)) < 0)
867             goto free_and_end;
868     } else {
869         avctx->priv_data = NULL;
870     }
871     if ((ret = av_opt_set_dict(avctx, &tmp)) < 0)
872         goto free_and_end;
873
874     if (avctx->coded_width && avctx->coded_height)
875         avcodec_set_dimensions(avctx, avctx->coded_width, avctx->coded_height);
876     else if (avctx->width && avctx->height)
877         avcodec_set_dimensions(avctx, avctx->width, avctx->height);
878
879     if ((avctx->coded_width || avctx->coded_height || avctx->width || avctx->height)
880         && (  av_image_check_size(avctx->coded_width, avctx->coded_height, 0, avctx) < 0
881            || av_image_check_size(avctx->width,       avctx->height,       0, avctx) < 0)) {
882         av_log(avctx, AV_LOG_WARNING, "ignoring invalid width/height values\n");
883         avcodec_set_dimensions(avctx, 0, 0);
884     }
885
886     /* if the decoder init function was already called previously,
887      * free the already allocated subtitle_header before overwriting it */
888     if (av_codec_is_decoder(codec))
889         av_freep(&avctx->subtitle_header);
890
891     if (avctx->channels > FF_SANE_NB_CHANNELS) {
892         ret = AVERROR(EINVAL);
893         goto free_and_end;
894     }
895
896     avctx->codec = codec;
897     if ((avctx->codec_type == AVMEDIA_TYPE_UNKNOWN || avctx->codec_type == codec->type) &&
898         avctx->codec_id == AV_CODEC_ID_NONE) {
899         avctx->codec_type = codec->type;
900         avctx->codec_id   = codec->id;
901     }
902     if (avctx->codec_id != codec->id || (avctx->codec_type != codec->type
903                                          && avctx->codec_type != AVMEDIA_TYPE_ATTACHMENT)) {
904         av_log(avctx, AV_LOG_ERROR, "codec type or id mismatches\n");
905         ret = AVERROR(EINVAL);
906         goto free_and_end;
907     }
908     avctx->frame_number = 0;
909
910     if (avctx->codec->capabilities & CODEC_CAP_EXPERIMENTAL &&
911         avctx->strict_std_compliance > FF_COMPLIANCE_EXPERIMENTAL) {
912         ret = AVERROR_EXPERIMENTAL;
913         goto free_and_end;
914     }
915
916     if (avctx->codec_type == AVMEDIA_TYPE_AUDIO &&
917         (!avctx->time_base.num || !avctx->time_base.den)) {
918         avctx->time_base.num = 1;
919         avctx->time_base.den = avctx->sample_rate;
920     }
921
922     if (HAVE_THREADS && !avctx->thread_opaque) {
923         ret = ff_thread_init(avctx);
924         if (ret < 0) {
925             goto free_and_end;
926         }
927     }
928     if (!HAVE_THREADS && !(codec->capabilities & CODEC_CAP_AUTO_THREADS))
929         avctx->thread_count = 1;
930
931     if (av_codec_is_encoder(avctx->codec)) {
932         int i;
933         if (avctx->codec->sample_fmts) {
934             for (i = 0; avctx->codec->sample_fmts[i] != AV_SAMPLE_FMT_NONE; i++) {
935                 if (avctx->sample_fmt == avctx->codec->sample_fmts[i])
936                     break;
937                 if (avctx->channels == 1 &&
938                     av_get_planar_sample_fmt(avctx->sample_fmt) ==
939                     av_get_planar_sample_fmt(avctx->codec->sample_fmts[i])) {
940                     avctx->sample_fmt = avctx->codec->sample_fmts[i];
941                     break;
942                 }
943             }
944             if (avctx->codec->sample_fmts[i] == AV_SAMPLE_FMT_NONE) {
945                 av_log(avctx, AV_LOG_ERROR, "Specified sample_fmt is not supported.\n");
946                 ret = AVERROR(EINVAL);
947                 goto free_and_end;
948             }
949         }
950         if (avctx->codec->pix_fmts) {
951             for (i = 0; avctx->codec->pix_fmts[i] != AV_PIX_FMT_NONE; i++)
952                 if (avctx->pix_fmt == avctx->codec->pix_fmts[i])
953                     break;
954             if (avctx->codec->pix_fmts[i] == AV_PIX_FMT_NONE) {
955                 av_log(avctx, AV_LOG_ERROR, "Specified pix_fmt is not supported\n");
956                 ret = AVERROR(EINVAL);
957                 goto free_and_end;
958             }
959         }
960         if (avctx->codec->supported_samplerates) {
961             for (i = 0; avctx->codec->supported_samplerates[i] != 0; i++)
962                 if (avctx->sample_rate == avctx->codec->supported_samplerates[i])
963                     break;
964             if (avctx->codec->supported_samplerates[i] == 0) {
965                 av_log(avctx, AV_LOG_ERROR, "Specified sample_rate is not supported\n");
966                 ret = AVERROR(EINVAL);
967                 goto free_and_end;
968             }
969         }
970         if (avctx->codec->channel_layouts) {
971             if (!avctx->channel_layout) {
972                 av_log(avctx, AV_LOG_WARNING, "channel_layout not specified\n");
973             } else {
974                 for (i = 0; avctx->codec->channel_layouts[i] != 0; i++)
975                     if (avctx->channel_layout == avctx->codec->channel_layouts[i])
976                         break;
977                 if (avctx->codec->channel_layouts[i] == 0) {
978                     av_log(avctx, AV_LOG_ERROR, "Specified channel_layout is not supported\n");
979                     ret = AVERROR(EINVAL);
980                     goto free_and_end;
981                 }
982             }
983         }
984         if (avctx->channel_layout && avctx->channels) {
985             if (av_get_channel_layout_nb_channels(avctx->channel_layout) != avctx->channels) {
986                 av_log(avctx, AV_LOG_ERROR, "channel layout does not match number of channels\n");
987                 ret = AVERROR(EINVAL);
988                 goto free_and_end;
989             }
990         } else if (avctx->channel_layout) {
991             avctx->channels = av_get_channel_layout_nb_channels(avctx->channel_layout);
992         }
993
994         if (!avctx->rc_initial_buffer_occupancy)
995             avctx->rc_initial_buffer_occupancy = avctx->rc_buffer_size * 3 / 4;
996     }
997
998     if (avctx->codec->init && !(avctx->active_thread_type & FF_THREAD_FRAME)) {
999         ret = avctx->codec->init(avctx);
1000         if (ret < 0) {
1001             goto free_and_end;
1002         }
1003     }
1004
1005     if (av_codec_is_decoder(avctx->codec)) {
1006         /* validate channel layout from the decoder */
1007         if (avctx->channel_layout) {
1008             int channels = av_get_channel_layout_nb_channels(avctx->channel_layout);
1009             if (!avctx->channels)
1010                 avctx->channels = channels;
1011             else if (channels != avctx->channels) {
1012                 av_log(avctx, AV_LOG_WARNING,
1013                        "channel layout does not match number of channels\n");
1014                 avctx->channel_layout = 0;
1015             }
1016         }
1017         if (avctx->channels && avctx->channels < 0 ||
1018             avctx->channels > FF_SANE_NB_CHANNELS) {
1019             ret = AVERROR(EINVAL);
1020             goto free_and_end;
1021         }
1022     }
1023 end:
1024     entangled_thread_counter--;
1025
1026     /* Release any user-supplied mutex. */
1027     if (ff_lockmgr_cb) {
1028         (*ff_lockmgr_cb)(&codec_mutex, AV_LOCK_RELEASE);
1029     }
1030     if (options) {
1031         av_dict_free(options);
1032         *options = tmp;
1033     }
1034
1035     return ret;
1036 free_and_end:
1037     av_dict_free(&tmp);
1038     av_freep(&avctx->priv_data);
1039     if (avctx->internal)
1040         av_freep(&avctx->internal->pool);
1041     av_freep(&avctx->internal);
1042     avctx->codec = NULL;
1043     goto end;
1044 }
1045
1046 int ff_alloc_packet(AVPacket *avpkt, int size)
1047 {
1048     if (size > INT_MAX - FF_INPUT_BUFFER_PADDING_SIZE)
1049         return AVERROR(EINVAL);
1050
1051     if (avpkt->data) {
1052         AVBufferRef *buf = avpkt->buf;
1053 #if FF_API_DESTRUCT_PACKET
1054         void *destruct = avpkt->destruct;
1055 #endif
1056
1057         if (avpkt->size < size)
1058             return AVERROR(EINVAL);
1059
1060         av_init_packet(avpkt);
1061 #if FF_API_DESTRUCT_PACKET
1062         avpkt->destruct = destruct;
1063 #endif
1064         avpkt->buf      = buf;
1065         avpkt->size     = size;
1066         return 0;
1067     } else {
1068         return av_new_packet(avpkt, size);
1069     }
1070 }
1071
1072 /**
1073  * Pad last frame with silence.
1074  */
1075 static int pad_last_frame(AVCodecContext *s, AVFrame **dst, const AVFrame *src)
1076 {
1077     AVFrame *frame = NULL;
1078     uint8_t *buf   = NULL;
1079     int ret;
1080
1081     if (!(frame = avcodec_alloc_frame()))
1082         return AVERROR(ENOMEM);
1083     *frame = *src;
1084
1085     if ((ret = av_samples_get_buffer_size(&frame->linesize[0], s->channels,
1086                                           s->frame_size, s->sample_fmt, 0)) < 0)
1087         goto fail;
1088
1089     if (!(buf = av_malloc(ret))) {
1090         ret = AVERROR(ENOMEM);
1091         goto fail;
1092     }
1093
1094     frame->nb_samples = s->frame_size;
1095     if ((ret = avcodec_fill_audio_frame(frame, s->channels, s->sample_fmt,
1096                                         buf, ret, 0)) < 0)
1097         goto fail;
1098     if ((ret = av_samples_copy(frame->extended_data, src->extended_data, 0, 0,
1099                                src->nb_samples, s->channels, s->sample_fmt)) < 0)
1100         goto fail;
1101     if ((ret = av_samples_set_silence(frame->extended_data, src->nb_samples,
1102                                       frame->nb_samples - src->nb_samples,
1103                                       s->channels, s->sample_fmt)) < 0)
1104         goto fail;
1105
1106     *dst = frame;
1107
1108     return 0;
1109
1110 fail:
1111     if (frame->extended_data != frame->data)
1112         av_freep(&frame->extended_data);
1113     av_freep(&buf);
1114     av_freep(&frame);
1115     return ret;
1116 }
1117
1118 int attribute_align_arg avcodec_encode_audio2(AVCodecContext *avctx,
1119                                               AVPacket *avpkt,
1120                                               const AVFrame *frame,
1121                                               int *got_packet_ptr)
1122 {
1123     AVFrame tmp;
1124     AVFrame *padded_frame = NULL;
1125     int ret;
1126     int user_packet = !!avpkt->data;
1127
1128     *got_packet_ptr = 0;
1129
1130     if (!(avctx->codec->capabilities & CODEC_CAP_DELAY) && !frame) {
1131         av_free_packet(avpkt);
1132         av_init_packet(avpkt);
1133         return 0;
1134     }
1135
1136     /* ensure that extended_data is properly set */
1137     if (frame && !frame->extended_data) {
1138         if (av_sample_fmt_is_planar(avctx->sample_fmt) &&
1139             avctx->channels > AV_NUM_DATA_POINTERS) {
1140             av_log(avctx, AV_LOG_ERROR, "Encoding to a planar sample format, "
1141                                         "with more than %d channels, but extended_data is not set.\n",
1142                    AV_NUM_DATA_POINTERS);
1143             return AVERROR(EINVAL);
1144         }
1145         av_log(avctx, AV_LOG_WARNING, "extended_data is not set.\n");
1146
1147         tmp = *frame;
1148         tmp.extended_data = tmp.data;
1149         frame = &tmp;
1150     }
1151
1152     /* check for valid frame size */
1153     if (frame) {
1154         if (avctx->codec->capabilities & CODEC_CAP_SMALL_LAST_FRAME) {
1155             if (frame->nb_samples > avctx->frame_size)
1156                 return AVERROR(EINVAL);
1157         } else if (!(avctx->codec->capabilities & CODEC_CAP_VARIABLE_FRAME_SIZE)) {
1158             if (frame->nb_samples < avctx->frame_size &&
1159                 !avctx->internal->last_audio_frame) {
1160                 ret = pad_last_frame(avctx, &padded_frame, frame);
1161                 if (ret < 0)
1162                     return ret;
1163
1164                 frame = padded_frame;
1165                 avctx->internal->last_audio_frame = 1;
1166             }
1167
1168             if (frame->nb_samples != avctx->frame_size) {
1169                 ret = AVERROR(EINVAL);
1170                 goto end;
1171             }
1172         }
1173     }
1174
1175     ret = avctx->codec->encode2(avctx, avpkt, frame, got_packet_ptr);
1176     if (!ret) {
1177         if (*got_packet_ptr) {
1178             if (!(avctx->codec->capabilities & CODEC_CAP_DELAY)) {
1179                 if (avpkt->pts == AV_NOPTS_VALUE)
1180                     avpkt->pts = frame->pts;
1181                 if (!avpkt->duration)
1182                     avpkt->duration = ff_samples_to_time_base(avctx,
1183                                                               frame->nb_samples);
1184             }
1185             avpkt->dts = avpkt->pts;
1186         } else {
1187             avpkt->size = 0;
1188         }
1189
1190         if (!user_packet && avpkt->size) {
1191             ret = av_buffer_realloc(&avpkt->buf, avpkt->size);
1192             if (ret >= 0)
1193                 avpkt->data = avpkt->buf->data;
1194         }
1195
1196         avctx->frame_number++;
1197     }
1198
1199     if (ret < 0 || !*got_packet_ptr) {
1200         av_free_packet(avpkt);
1201         av_init_packet(avpkt);
1202         goto end;
1203     }
1204
1205     /* NOTE: if we add any audio encoders which output non-keyframe packets,
1206      *       this needs to be moved to the encoders, but for now we can do it
1207      *       here to simplify things */
1208     avpkt->flags |= AV_PKT_FLAG_KEY;
1209
1210 end:
1211     if (padded_frame) {
1212         av_freep(&padded_frame->data[0]);
1213         if (padded_frame->extended_data != padded_frame->data)
1214             av_freep(&padded_frame->extended_data);
1215         av_freep(&padded_frame);
1216     }
1217
1218     return ret;
1219 }
1220
1221 #if FF_API_OLD_ENCODE_AUDIO
1222 int attribute_align_arg avcodec_encode_audio(AVCodecContext *avctx,
1223                                              uint8_t *buf, int buf_size,
1224                                              const short *samples)
1225 {
1226     AVPacket pkt;
1227     AVFrame frame0 = { { 0 } };
1228     AVFrame *frame;
1229     int ret, samples_size, got_packet;
1230
1231     av_init_packet(&pkt);
1232     pkt.data = buf;
1233     pkt.size = buf_size;
1234
1235     if (samples) {
1236         frame = &frame0;
1237         avcodec_get_frame_defaults(frame);
1238
1239         if (avctx->frame_size) {
1240             frame->nb_samples = avctx->frame_size;
1241         } else {
1242             /* if frame_size is not set, the number of samples must be
1243              * calculated from the buffer size */
1244             int64_t nb_samples;
1245             if (!av_get_bits_per_sample(avctx->codec_id)) {
1246                 av_log(avctx, AV_LOG_ERROR, "avcodec_encode_audio() does not "
1247                                             "support this codec\n");
1248                 return AVERROR(EINVAL);
1249             }
1250             nb_samples = (int64_t)buf_size * 8 /
1251                          (av_get_bits_per_sample(avctx->codec_id) *
1252                           avctx->channels);
1253             if (nb_samples >= INT_MAX)
1254                 return AVERROR(EINVAL);
1255             frame->nb_samples = nb_samples;
1256         }
1257
1258         /* it is assumed that the samples buffer is large enough based on the
1259          * relevant parameters */
1260         samples_size = av_samples_get_buffer_size(NULL, avctx->channels,
1261                                                   frame->nb_samples,
1262                                                   avctx->sample_fmt, 1);
1263         if ((ret = avcodec_fill_audio_frame(frame, avctx->channels,
1264                                             avctx->sample_fmt,
1265                                             (const uint8_t *)samples,
1266                                             samples_size, 1)))
1267             return ret;
1268
1269         /* fabricate frame pts from sample count.
1270          * this is needed because the avcodec_encode_audio() API does not have
1271          * a way for the user to provide pts */
1272         frame->pts = ff_samples_to_time_base(avctx,
1273                                              avctx->internal->sample_count);
1274         avctx->internal->sample_count += frame->nb_samples;
1275     } else {
1276         frame = NULL;
1277     }
1278
1279     got_packet = 0;
1280     ret = avcodec_encode_audio2(avctx, &pkt, frame, &got_packet);
1281     if (!ret && got_packet && avctx->coded_frame) {
1282         avctx->coded_frame->pts       = pkt.pts;
1283         avctx->coded_frame->key_frame = !!(pkt.flags & AV_PKT_FLAG_KEY);
1284     }
1285     /* free any side data since we cannot return it */
1286     if (pkt.side_data_elems > 0) {
1287         int i;
1288         for (i = 0; i < pkt.side_data_elems; i++)
1289             av_free(pkt.side_data[i].data);
1290         av_freep(&pkt.side_data);
1291         pkt.side_data_elems = 0;
1292     }
1293
1294     if (frame && frame->extended_data != frame->data)
1295         av_free(frame->extended_data);
1296
1297     return ret ? ret : pkt.size;
1298 }
1299
1300 #endif
1301
1302 #if FF_API_OLD_ENCODE_VIDEO
1303 int attribute_align_arg avcodec_encode_video(AVCodecContext *avctx, uint8_t *buf, int buf_size,
1304                                              const AVFrame *pict)
1305 {
1306     AVPacket pkt;
1307     int ret, got_packet = 0;
1308
1309     if (buf_size < FF_MIN_BUFFER_SIZE) {
1310         av_log(avctx, AV_LOG_ERROR, "buffer smaller than minimum size\n");
1311         return -1;
1312     }
1313
1314     av_init_packet(&pkt);
1315     pkt.data = buf;
1316     pkt.size = buf_size;
1317
1318     ret = avcodec_encode_video2(avctx, &pkt, pict, &got_packet);
1319     if (!ret && got_packet && avctx->coded_frame) {
1320         avctx->coded_frame->pts       = pkt.pts;
1321         avctx->coded_frame->key_frame = !!(pkt.flags & AV_PKT_FLAG_KEY);
1322     }
1323
1324     /* free any side data since we cannot return it */
1325     if (pkt.side_data_elems > 0) {
1326         int i;
1327         for (i = 0; i < pkt.side_data_elems; i++)
1328             av_free(pkt.side_data[i].data);
1329         av_freep(&pkt.side_data);
1330         pkt.side_data_elems = 0;
1331     }
1332
1333     return ret ? ret : pkt.size;
1334 }
1335
1336 #endif
1337
1338 int attribute_align_arg avcodec_encode_video2(AVCodecContext *avctx,
1339                                               AVPacket *avpkt,
1340                                               const AVFrame *frame,
1341                                               int *got_packet_ptr)
1342 {
1343     int ret;
1344     int user_packet = !!avpkt->data;
1345
1346     *got_packet_ptr = 0;
1347
1348     if (!(avctx->codec->capabilities & CODEC_CAP_DELAY) && !frame) {
1349         av_free_packet(avpkt);
1350         av_init_packet(avpkt);
1351         avpkt->size = 0;
1352         return 0;
1353     }
1354
1355     if (av_image_check_size(avctx->width, avctx->height, 0, avctx))
1356         return AVERROR(EINVAL);
1357
1358     av_assert0(avctx->codec->encode2);
1359
1360     ret = avctx->codec->encode2(avctx, avpkt, frame, got_packet_ptr);
1361     if (!ret) {
1362         if (!*got_packet_ptr)
1363             avpkt->size = 0;
1364         else if (!(avctx->codec->capabilities & CODEC_CAP_DELAY))
1365             avpkt->pts = avpkt->dts = frame->pts;
1366
1367         if (!user_packet && avpkt->size) {
1368             ret = av_buffer_realloc(&avpkt->buf, avpkt->size);
1369             if (ret >= 0)
1370                 avpkt->data = avpkt->buf->data;
1371         }
1372
1373         avctx->frame_number++;
1374     }
1375
1376     if (ret < 0 || !*got_packet_ptr)
1377         av_free_packet(avpkt);
1378
1379     emms_c();
1380     return ret;
1381 }
1382
1383 int avcodec_encode_subtitle(AVCodecContext *avctx, uint8_t *buf, int buf_size,
1384                             const AVSubtitle *sub)
1385 {
1386     int ret;
1387     if (sub->start_display_time) {
1388         av_log(avctx, AV_LOG_ERROR, "start_display_time must be 0.\n");
1389         return -1;
1390     }
1391     if (sub->num_rects == 0 || !sub->rects)
1392         return -1;
1393     ret = avctx->codec->encode_sub(avctx, buf, buf_size, sub);
1394     avctx->frame_number++;
1395     return ret;
1396 }
1397
1398 static void apply_param_change(AVCodecContext *avctx, AVPacket *avpkt)
1399 {
1400     int size = 0;
1401     const uint8_t *data;
1402     uint32_t flags;
1403
1404     if (!(avctx->codec->capabilities & CODEC_CAP_PARAM_CHANGE))
1405         return;
1406
1407     data = av_packet_get_side_data(avpkt, AV_PKT_DATA_PARAM_CHANGE, &size);
1408     if (!data || size < 4)
1409         return;
1410     flags = bytestream_get_le32(&data);
1411     size -= 4;
1412     if (size < 4) /* Required for any of the changes */
1413         return;
1414     if (flags & AV_SIDE_DATA_PARAM_CHANGE_CHANNEL_COUNT) {
1415         avctx->channels = bytestream_get_le32(&data);
1416         size -= 4;
1417     }
1418     if (flags & AV_SIDE_DATA_PARAM_CHANGE_CHANNEL_LAYOUT) {
1419         if (size < 8)
1420             return;
1421         avctx->channel_layout = bytestream_get_le64(&data);
1422         size -= 8;
1423     }
1424     if (size < 4)
1425         return;
1426     if (flags & AV_SIDE_DATA_PARAM_CHANGE_SAMPLE_RATE) {
1427         avctx->sample_rate = bytestream_get_le32(&data);
1428         size -= 4;
1429     }
1430     if (flags & AV_SIDE_DATA_PARAM_CHANGE_DIMENSIONS) {
1431         if (size < 8)
1432             return;
1433         avctx->width  = bytestream_get_le32(&data);
1434         avctx->height = bytestream_get_le32(&data);
1435         avcodec_set_dimensions(avctx, avctx->width, avctx->height);
1436         size -= 8;
1437     }
1438 }
1439
1440 int attribute_align_arg avcodec_decode_video2(AVCodecContext *avctx, AVFrame *picture,
1441                                               int *got_picture_ptr,
1442                                               AVPacket *avpkt)
1443 {
1444     AVCodecInternal *avci = avctx->internal;
1445     int ret;
1446
1447     *got_picture_ptr = 0;
1448     if ((avctx->coded_width || avctx->coded_height) && av_image_check_size(avctx->coded_width, avctx->coded_height, 0, avctx))
1449         return -1;
1450
1451     avctx->pkt = avpkt;
1452     apply_param_change(avctx, avpkt);
1453
1454     avcodec_get_frame_defaults(picture);
1455
1456     if (!avctx->refcounted_frames)
1457         av_frame_unref(&avci->to_free);
1458
1459     if ((avctx->codec->capabilities & CODEC_CAP_DELAY) || avpkt->size || (avctx->active_thread_type & FF_THREAD_FRAME)) {
1460         if (HAVE_THREADS && avctx->active_thread_type & FF_THREAD_FRAME)
1461             ret = ff_thread_decode_frame(avctx, picture, got_picture_ptr,
1462                                          avpkt);
1463         else {
1464             ret = avctx->codec->decode(avctx, picture, got_picture_ptr,
1465                                        avpkt);
1466             picture->pkt_dts = avpkt->dts;
1467             /* get_buffer is supposed to set frame parameters */
1468             if (!(avctx->codec->capabilities & CODEC_CAP_DR1)) {
1469                 picture->sample_aspect_ratio = avctx->sample_aspect_ratio;
1470                 picture->width               = avctx->width;
1471                 picture->height              = avctx->height;
1472                 picture->format              = avctx->pix_fmt;
1473             }
1474         }
1475
1476         emms_c(); //needed to avoid an emms_c() call before every return;
1477
1478         if (ret < 0 && picture->data[0])
1479             av_frame_unref(picture);
1480
1481         if (*got_picture_ptr) {
1482             if (!avctx->refcounted_frames) {
1483                 avci->to_free = *picture;
1484                 avci->to_free.extended_data = avci->to_free.data;
1485             }
1486
1487             avctx->frame_number++;
1488         }
1489     } else
1490         ret = 0;
1491
1492     /* many decoders assign whole AVFrames, thus overwriting extended_data;
1493      * make sure it's set correctly */
1494     picture->extended_data = picture->data;
1495
1496     return ret;
1497 }
1498
1499 #if FF_API_OLD_DECODE_AUDIO
1500 int attribute_align_arg avcodec_decode_audio3(AVCodecContext *avctx, int16_t *samples,
1501                                               int *frame_size_ptr,
1502                                               AVPacket *avpkt)
1503 {
1504     AVFrame frame = { { 0 } };
1505     int ret, got_frame = 0;
1506
1507     if (avctx->get_buffer != avcodec_default_get_buffer) {
1508         av_log(avctx, AV_LOG_ERROR, "Custom get_buffer() for use with"
1509                                     "avcodec_decode_audio3() detected. Overriding with avcodec_default_get_buffer\n");
1510         av_log(avctx, AV_LOG_ERROR, "Please port your application to "
1511                                     "avcodec_decode_audio4()\n");
1512         avctx->get_buffer = avcodec_default_get_buffer;
1513     }
1514
1515     ret = avcodec_decode_audio4(avctx, &frame, &got_frame, avpkt);
1516
1517     if (ret >= 0 && got_frame) {
1518         int ch, plane_size;
1519         int planar    = av_sample_fmt_is_planar(avctx->sample_fmt);
1520         int data_size = av_samples_get_buffer_size(&plane_size, avctx->channels,
1521                                                    frame.nb_samples,
1522                                                    avctx->sample_fmt, 1);
1523         if (*frame_size_ptr < data_size) {
1524             av_log(avctx, AV_LOG_ERROR, "output buffer size is too small for "
1525                                         "the current frame (%d < %d)\n", *frame_size_ptr, data_size);
1526             return AVERROR(EINVAL);
1527         }
1528
1529         memcpy(samples, frame.extended_data[0], plane_size);
1530
1531         if (planar && avctx->channels > 1) {
1532             uint8_t *out = ((uint8_t *)samples) + plane_size;
1533             for (ch = 1; ch < avctx->channels; ch++) {
1534                 memcpy(out, frame.extended_data[ch], plane_size);
1535                 out += plane_size;
1536             }
1537         }
1538         *frame_size_ptr = data_size;
1539     } else {
1540         *frame_size_ptr = 0;
1541     }
1542     return ret;
1543 }
1544
1545 #endif
1546
1547 int attribute_align_arg avcodec_decode_audio4(AVCodecContext *avctx,
1548                                               AVFrame *frame,
1549                                               int *got_frame_ptr,
1550                                               AVPacket *avpkt)
1551 {
1552     AVCodecInternal *avci = avctx->internal;
1553     int planar, channels;
1554     int ret = 0;
1555
1556     *got_frame_ptr = 0;
1557
1558     avctx->pkt = avpkt;
1559
1560     if (!avpkt->data && avpkt->size) {
1561         av_log(avctx, AV_LOG_ERROR, "invalid packet: NULL data, size != 0\n");
1562         return AVERROR(EINVAL);
1563     }
1564
1565     apply_param_change(avctx, avpkt);
1566
1567     avcodec_get_frame_defaults(frame);
1568
1569     if (!avctx->refcounted_frames)
1570         av_frame_unref(&avci->to_free);
1571
1572     if ((avctx->codec->capabilities & CODEC_CAP_DELAY) || avpkt->size) {
1573         ret = avctx->codec->decode(avctx, frame, got_frame_ptr, avpkt);
1574         if (ret >= 0 && *got_frame_ptr) {
1575             avctx->frame_number++;
1576             frame->pkt_dts = avpkt->dts;
1577             if (frame->format == AV_SAMPLE_FMT_NONE)
1578                 frame->format = avctx->sample_fmt;
1579
1580             if (!avctx->refcounted_frames) {
1581                 avci->to_free = *frame;
1582                 avci->to_free.extended_data = avci->to_free.data;
1583             }
1584         }
1585
1586         if (ret < 0 && frame->data[0])
1587             av_frame_unref(frame);
1588     }
1589
1590     /* many decoders assign whole AVFrames, thus overwriting extended_data;
1591      * make sure it's set correctly; assume decoders that actually use
1592      * extended_data are doing it correctly */
1593     planar   = av_sample_fmt_is_planar(frame->format);
1594     channels = av_get_channel_layout_nb_channels(frame->channel_layout);
1595     if (!(planar && channels > AV_NUM_DATA_POINTERS))
1596         frame->extended_data = frame->data;
1597
1598     return ret;
1599 }
1600
1601 int avcodec_decode_subtitle2(AVCodecContext *avctx, AVSubtitle *sub,
1602                              int *got_sub_ptr,
1603                              AVPacket *avpkt)
1604 {
1605     int ret;
1606
1607     avctx->pkt = avpkt;
1608     *got_sub_ptr = 0;
1609     ret = avctx->codec->decode(avctx, sub, got_sub_ptr, avpkt);
1610     if (*got_sub_ptr)
1611         avctx->frame_number++;
1612     return ret;
1613 }
1614
1615 void avsubtitle_free(AVSubtitle *sub)
1616 {
1617     int i;
1618
1619     for (i = 0; i < sub->num_rects; i++) {
1620         av_freep(&sub->rects[i]->pict.data[0]);
1621         av_freep(&sub->rects[i]->pict.data[1]);
1622         av_freep(&sub->rects[i]->pict.data[2]);
1623         av_freep(&sub->rects[i]->pict.data[3]);
1624         av_freep(&sub->rects[i]->text);
1625         av_freep(&sub->rects[i]->ass);
1626         av_freep(&sub->rects[i]);
1627     }
1628
1629     av_freep(&sub->rects);
1630
1631     memset(sub, 0, sizeof(AVSubtitle));
1632 }
1633
1634 av_cold int avcodec_close(AVCodecContext *avctx)
1635 {
1636     /* If there is a user-supplied mutex locking routine, call it. */
1637     if (ff_lockmgr_cb) {
1638         if ((*ff_lockmgr_cb)(&codec_mutex, AV_LOCK_OBTAIN))
1639             return -1;
1640     }
1641
1642     entangled_thread_counter++;
1643     if (entangled_thread_counter != 1) {
1644         av_log(avctx, AV_LOG_ERROR, "insufficient thread locking around avcodec_open/close()\n");
1645         entangled_thread_counter--;
1646         return -1;
1647     }
1648
1649     if (avcodec_is_open(avctx)) {
1650         FramePool *pool = avctx->internal->pool;
1651         int i;
1652         if (HAVE_THREADS && avctx->thread_opaque)
1653             ff_thread_free(avctx);
1654         if (avctx->codec && avctx->codec->close)
1655             avctx->codec->close(avctx);
1656         avctx->coded_frame = NULL;
1657         if (!avctx->refcounted_frames)
1658             av_frame_unref(&avctx->internal->to_free);
1659         for (i = 0; i < FF_ARRAY_ELEMS(pool->pools); i++)
1660             av_buffer_pool_uninit(&pool->pools[i]);
1661         av_freep(&avctx->internal->pool);
1662         av_freep(&avctx->internal);
1663     }
1664
1665     if (avctx->priv_data && avctx->codec && avctx->codec->priv_class)
1666         av_opt_free(avctx->priv_data);
1667     av_opt_free(avctx);
1668     av_freep(&avctx->priv_data);
1669     if (av_codec_is_encoder(avctx->codec))
1670         av_freep(&avctx->extradata);
1671     avctx->codec = NULL;
1672     avctx->active_thread_type = 0;
1673     entangled_thread_counter--;
1674
1675     /* Release any user-supplied mutex. */
1676     if (ff_lockmgr_cb) {
1677         (*ff_lockmgr_cb)(&codec_mutex, AV_LOCK_RELEASE);
1678     }
1679     return 0;
1680 }
1681
1682 static AVCodec *find_encdec(enum AVCodecID id, int encoder)
1683 {
1684     AVCodec *p, *experimental = NULL;
1685     p = first_avcodec;
1686     while (p) {
1687         if ((encoder ? av_codec_is_encoder(p) : av_codec_is_decoder(p)) &&
1688             p->id == id) {
1689             if (p->capabilities & CODEC_CAP_EXPERIMENTAL && !experimental) {
1690                 experimental = p;
1691             } else
1692                 return p;
1693         }
1694         p = p->next;
1695     }
1696     return experimental;
1697 }
1698
1699 AVCodec *avcodec_find_encoder(enum AVCodecID id)
1700 {
1701     return find_encdec(id, 1);
1702 }
1703
1704 AVCodec *avcodec_find_encoder_by_name(const char *name)
1705 {
1706     AVCodec *p;
1707     if (!name)
1708         return NULL;
1709     p = first_avcodec;
1710     while (p) {
1711         if (av_codec_is_encoder(p) && strcmp(name, p->name) == 0)
1712             return p;
1713         p = p->next;
1714     }
1715     return NULL;
1716 }
1717
1718 AVCodec *avcodec_find_decoder(enum AVCodecID id)
1719 {
1720     return find_encdec(id, 0);
1721 }
1722
1723 AVCodec *avcodec_find_decoder_by_name(const char *name)
1724 {
1725     AVCodec *p;
1726     if (!name)
1727         return NULL;
1728     p = first_avcodec;
1729     while (p) {
1730         if (av_codec_is_decoder(p) && strcmp(name, p->name) == 0)
1731             return p;
1732         p = p->next;
1733     }
1734     return NULL;
1735 }
1736
1737 static int get_bit_rate(AVCodecContext *ctx)
1738 {
1739     int bit_rate;
1740     int bits_per_sample;
1741
1742     switch (ctx->codec_type) {
1743     case AVMEDIA_TYPE_VIDEO:
1744     case AVMEDIA_TYPE_DATA:
1745     case AVMEDIA_TYPE_SUBTITLE:
1746     case AVMEDIA_TYPE_ATTACHMENT:
1747         bit_rate = ctx->bit_rate;
1748         break;
1749     case AVMEDIA_TYPE_AUDIO:
1750         bits_per_sample = av_get_bits_per_sample(ctx->codec_id);
1751         bit_rate = bits_per_sample ? ctx->sample_rate * ctx->channels * bits_per_sample : ctx->bit_rate;
1752         break;
1753     default:
1754         bit_rate = 0;
1755         break;
1756     }
1757     return bit_rate;
1758 }
1759
1760 size_t av_get_codec_tag_string(char *buf, size_t buf_size, unsigned int codec_tag)
1761 {
1762     int i, len, ret = 0;
1763
1764 #define TAG_PRINT(x)                                              \
1765     (((x) >= '0' && (x) <= '9') ||                                \
1766      ((x) >= 'a' && (x) <= 'z') || ((x) >= 'A' && (x) <= 'Z') ||  \
1767      ((x) == '.' || (x) == ' '))
1768
1769     for (i = 0; i < 4; i++) {
1770         len = snprintf(buf, buf_size,
1771                        TAG_PRINT(codec_tag & 0xFF) ? "%c" : "[%d]", codec_tag & 0xFF);
1772         buf        += len;
1773         buf_size    = buf_size > len ? buf_size - len : 0;
1774         ret        += len;
1775         codec_tag >>= 8;
1776     }
1777     return ret;
1778 }
1779
1780 void avcodec_string(char *buf, int buf_size, AVCodecContext *enc, int encode)
1781 {
1782     const char *codec_name;
1783     const char *profile = NULL;
1784     const AVCodec *p;
1785     char buf1[32];
1786     int bitrate;
1787     AVRational display_aspect_ratio;
1788
1789     if (enc->codec)
1790         p = enc->codec;
1791     else if (encode)
1792         p = avcodec_find_encoder(enc->codec_id);
1793     else
1794         p = avcodec_find_decoder(enc->codec_id);
1795
1796     if (p) {
1797         codec_name = p->name;
1798         profile = av_get_profile_name(p, enc->profile);
1799     } else if (enc->codec_id == AV_CODEC_ID_MPEG2TS) {
1800         /* fake mpeg2 transport stream codec (currently not
1801          * registered) */
1802         codec_name = "mpeg2ts";
1803     } else if (enc->codec_name[0] != '\0') {
1804         codec_name = enc->codec_name;
1805     } else {
1806         /* output avi tags */
1807         char tag_buf[32];
1808         av_get_codec_tag_string(tag_buf, sizeof(tag_buf), enc->codec_tag);
1809         snprintf(buf1, sizeof(buf1), "%s / 0x%04X", tag_buf, enc->codec_tag);
1810         codec_name = buf1;
1811     }
1812
1813     switch (enc->codec_type) {
1814     case AVMEDIA_TYPE_VIDEO:
1815         snprintf(buf, buf_size,
1816                  "Video: %s%s",
1817                  codec_name, enc->mb_decision ? " (hq)" : "");
1818         if (profile)
1819             snprintf(buf + strlen(buf), buf_size - strlen(buf),
1820                      " (%s)", profile);
1821         if (enc->pix_fmt != AV_PIX_FMT_NONE) {
1822             snprintf(buf + strlen(buf), buf_size - strlen(buf),
1823                      ", %s",
1824                      av_get_pix_fmt_name(enc->pix_fmt));
1825         }
1826         if (enc->width) {
1827             snprintf(buf + strlen(buf), buf_size - strlen(buf),
1828                      ", %dx%d",
1829                      enc->width, enc->height);
1830             if (enc->sample_aspect_ratio.num) {
1831                 av_reduce(&display_aspect_ratio.num, &display_aspect_ratio.den,
1832                           enc->width * enc->sample_aspect_ratio.num,
1833                           enc->height * enc->sample_aspect_ratio.den,
1834                           1024 * 1024);
1835                 snprintf(buf + strlen(buf), buf_size - strlen(buf),
1836                          " [PAR %d:%d DAR %d:%d]",
1837                          enc->sample_aspect_ratio.num, enc->sample_aspect_ratio.den,
1838                          display_aspect_ratio.num, display_aspect_ratio.den);
1839             }
1840             if (av_log_get_level() >= AV_LOG_DEBUG) {
1841                 int g = av_gcd(enc->time_base.num, enc->time_base.den);
1842                 snprintf(buf + strlen(buf), buf_size - strlen(buf),
1843                          ", %d/%d",
1844                          enc->time_base.num / g, enc->time_base.den / g);
1845             }
1846         }
1847         if (encode) {
1848             snprintf(buf + strlen(buf), buf_size - strlen(buf),
1849                      ", q=%d-%d", enc->qmin, enc->qmax);
1850         }
1851         break;
1852     case AVMEDIA_TYPE_AUDIO:
1853         snprintf(buf, buf_size,
1854                  "Audio: %s",
1855                  codec_name);
1856         if (profile)
1857             snprintf(buf + strlen(buf), buf_size - strlen(buf),
1858                      " (%s)", profile);
1859         if (enc->sample_rate) {
1860             snprintf(buf + strlen(buf), buf_size - strlen(buf),
1861                      ", %d Hz", enc->sample_rate);
1862         }
1863         av_strlcat(buf, ", ", buf_size);
1864         av_get_channel_layout_string(buf + strlen(buf), buf_size - strlen(buf), enc->channels, enc->channel_layout);
1865         if (enc->sample_fmt != AV_SAMPLE_FMT_NONE) {
1866             snprintf(buf + strlen(buf), buf_size - strlen(buf),
1867                      ", %s", av_get_sample_fmt_name(enc->sample_fmt));
1868         }
1869         break;
1870     case AVMEDIA_TYPE_DATA:
1871         snprintf(buf, buf_size, "Data: %s", codec_name);
1872         break;
1873     case AVMEDIA_TYPE_SUBTITLE:
1874         snprintf(buf, buf_size, "Subtitle: %s", codec_name);
1875         break;
1876     case AVMEDIA_TYPE_ATTACHMENT:
1877         snprintf(buf, buf_size, "Attachment: %s", codec_name);
1878         break;
1879     default:
1880         snprintf(buf, buf_size, "Invalid Codec type %d", enc->codec_type);
1881         return;
1882     }
1883     if (encode) {
1884         if (enc->flags & CODEC_FLAG_PASS1)
1885             snprintf(buf + strlen(buf), buf_size - strlen(buf),
1886                      ", pass 1");
1887         if (enc->flags & CODEC_FLAG_PASS2)
1888             snprintf(buf + strlen(buf), buf_size - strlen(buf),
1889                      ", pass 2");
1890     }
1891     bitrate = get_bit_rate(enc);
1892     if (bitrate != 0) {
1893         snprintf(buf + strlen(buf), buf_size - strlen(buf),
1894                  ", %d kb/s", bitrate / 1000);
1895     }
1896 }
1897
1898 const char *av_get_profile_name(const AVCodec *codec, int profile)
1899 {
1900     const AVProfile *p;
1901     if (profile == FF_PROFILE_UNKNOWN || !codec->profiles)
1902         return NULL;
1903
1904     for (p = codec->profiles; p->profile != FF_PROFILE_UNKNOWN; p++)
1905         if (p->profile == profile)
1906             return p->name;
1907
1908     return NULL;
1909 }
1910
1911 unsigned avcodec_version(void)
1912 {
1913     return LIBAVCODEC_VERSION_INT;
1914 }
1915
1916 const char *avcodec_configuration(void)
1917 {
1918     return LIBAV_CONFIGURATION;
1919 }
1920
1921 const char *avcodec_license(void)
1922 {
1923 #define LICENSE_PREFIX "libavcodec license: "
1924     return LICENSE_PREFIX LIBAV_LICENSE + sizeof(LICENSE_PREFIX) - 1;
1925 }
1926
1927 void avcodec_flush_buffers(AVCodecContext *avctx)
1928 {
1929     if (HAVE_THREADS && avctx->active_thread_type & FF_THREAD_FRAME)
1930         ff_thread_flush(avctx);
1931     else if (avctx->codec->flush)
1932         avctx->codec->flush(avctx);
1933 }
1934
1935 int av_get_exact_bits_per_sample(enum AVCodecID codec_id)
1936 {
1937     switch (codec_id) {
1938     case AV_CODEC_ID_ADPCM_CT:
1939     case AV_CODEC_ID_ADPCM_IMA_APC:
1940     case AV_CODEC_ID_ADPCM_IMA_EA_SEAD:
1941     case AV_CODEC_ID_ADPCM_IMA_WS:
1942     case AV_CODEC_ID_ADPCM_G722:
1943     case AV_CODEC_ID_ADPCM_YAMAHA:
1944         return 4;
1945     case AV_CODEC_ID_PCM_ALAW:
1946     case AV_CODEC_ID_PCM_MULAW:
1947     case AV_CODEC_ID_PCM_S8:
1948     case AV_CODEC_ID_PCM_U8:
1949     case AV_CODEC_ID_PCM_ZORK:
1950         return 8;
1951     case AV_CODEC_ID_PCM_S16BE:
1952     case AV_CODEC_ID_PCM_S16LE:
1953     case AV_CODEC_ID_PCM_S16LE_PLANAR:
1954     case AV_CODEC_ID_PCM_U16BE:
1955     case AV_CODEC_ID_PCM_U16LE:
1956         return 16;
1957     case AV_CODEC_ID_PCM_S24DAUD:
1958     case AV_CODEC_ID_PCM_S24BE:
1959     case AV_CODEC_ID_PCM_S24LE:
1960     case AV_CODEC_ID_PCM_U24BE:
1961     case AV_CODEC_ID_PCM_U24LE:
1962         return 24;
1963     case AV_CODEC_ID_PCM_S32BE:
1964     case AV_CODEC_ID_PCM_S32LE:
1965     case AV_CODEC_ID_PCM_U32BE:
1966     case AV_CODEC_ID_PCM_U32LE:
1967     case AV_CODEC_ID_PCM_F32BE:
1968     case AV_CODEC_ID_PCM_F32LE:
1969         return 32;
1970     case AV_CODEC_ID_PCM_F64BE:
1971     case AV_CODEC_ID_PCM_F64LE:
1972         return 64;
1973     default:
1974         return 0;
1975     }
1976 }
1977
1978 int av_get_bits_per_sample(enum AVCodecID codec_id)
1979 {
1980     switch (codec_id) {
1981     case AV_CODEC_ID_ADPCM_SBPRO_2:
1982         return 2;
1983     case AV_CODEC_ID_ADPCM_SBPRO_3:
1984         return 3;
1985     case AV_CODEC_ID_ADPCM_SBPRO_4:
1986     case AV_CODEC_ID_ADPCM_IMA_WAV:
1987     case AV_CODEC_ID_ADPCM_IMA_QT:
1988     case AV_CODEC_ID_ADPCM_SWF:
1989     case AV_CODEC_ID_ADPCM_MS:
1990         return 4;
1991     default:
1992         return av_get_exact_bits_per_sample(codec_id);
1993     }
1994 }
1995
1996 int av_get_audio_frame_duration(AVCodecContext *avctx, int frame_bytes)
1997 {
1998     int id, sr, ch, ba, tag, bps;
1999
2000     id  = avctx->codec_id;
2001     sr  = avctx->sample_rate;
2002     ch  = avctx->channels;
2003     ba  = avctx->block_align;
2004     tag = avctx->codec_tag;
2005     bps = av_get_exact_bits_per_sample(avctx->codec_id);
2006
2007     /* codecs with an exact constant bits per sample */
2008     if (bps > 0 && ch > 0 && frame_bytes > 0)
2009         return (frame_bytes * 8) / (bps * ch);
2010     bps = avctx->bits_per_coded_sample;
2011
2012     /* codecs with a fixed packet duration */
2013     switch (id) {
2014     case AV_CODEC_ID_ADPCM_ADX:    return   32;
2015     case AV_CODEC_ID_ADPCM_IMA_QT: return   64;
2016     case AV_CODEC_ID_ADPCM_EA_XAS: return  128;
2017     case AV_CODEC_ID_AMR_NB:
2018     case AV_CODEC_ID_GSM:
2019     case AV_CODEC_ID_QCELP:
2020     case AV_CODEC_ID_RA_144:
2021     case AV_CODEC_ID_RA_288:       return  160;
2022     case AV_CODEC_ID_IMC:          return  256;
2023     case AV_CODEC_ID_AMR_WB:
2024     case AV_CODEC_ID_GSM_MS:       return  320;
2025     case AV_CODEC_ID_MP1:          return  384;
2026     case AV_CODEC_ID_ATRAC1:       return  512;
2027     case AV_CODEC_ID_ATRAC3:       return 1024;
2028     case AV_CODEC_ID_MP2:
2029     case AV_CODEC_ID_MUSEPACK7:    return 1152;
2030     case AV_CODEC_ID_AC3:          return 1536;
2031     }
2032
2033     if (sr > 0) {
2034         /* calc from sample rate */
2035         if (id == AV_CODEC_ID_TTA)
2036             return 256 * sr / 245;
2037
2038         if (ch > 0) {
2039             /* calc from sample rate and channels */
2040             if (id == AV_CODEC_ID_BINKAUDIO_DCT)
2041                 return (480 << (sr / 22050)) / ch;
2042         }
2043     }
2044
2045     if (ba > 0) {
2046         /* calc from block_align */
2047         if (id == AV_CODEC_ID_SIPR) {
2048             switch (ba) {
2049             case 20: return 160;
2050             case 19: return 144;
2051             case 29: return 288;
2052             case 37: return 480;
2053             }
2054         } else if (id == AV_CODEC_ID_ILBC) {
2055             switch (ba) {
2056             case 38: return 160;
2057             case 50: return 240;
2058             }
2059         }
2060     }
2061
2062     if (frame_bytes > 0) {
2063         /* calc from frame_bytes only */
2064         if (id == AV_CODEC_ID_TRUESPEECH)
2065             return 240 * (frame_bytes / 32);
2066         if (id == AV_CODEC_ID_NELLYMOSER)
2067             return 256 * (frame_bytes / 64);
2068
2069         if (bps > 0) {
2070             /* calc from frame_bytes and bits_per_coded_sample */
2071             if (id == AV_CODEC_ID_ADPCM_G726)
2072                 return frame_bytes * 8 / bps;
2073         }
2074
2075         if (ch > 0) {
2076             /* calc from frame_bytes and channels */
2077             switch (id) {
2078             case AV_CODEC_ID_ADPCM_4XM:
2079             case AV_CODEC_ID_ADPCM_IMA_ISS:
2080                 return (frame_bytes - 4 * ch) * 2 / ch;
2081             case AV_CODEC_ID_ADPCM_IMA_SMJPEG:
2082                 return (frame_bytes - 4) * 2 / ch;
2083             case AV_CODEC_ID_ADPCM_IMA_AMV:
2084                 return (frame_bytes - 8) * 2 / ch;
2085             case AV_CODEC_ID_ADPCM_XA:
2086                 return (frame_bytes / 128) * 224 / ch;
2087             case AV_CODEC_ID_INTERPLAY_DPCM:
2088                 return (frame_bytes - 6 - ch) / ch;
2089             case AV_CODEC_ID_ROQ_DPCM:
2090                 return (frame_bytes - 8) / ch;
2091             case AV_CODEC_ID_XAN_DPCM:
2092                 return (frame_bytes - 2 * ch) / ch;
2093             case AV_CODEC_ID_MACE3:
2094                 return 3 * frame_bytes / ch;
2095             case AV_CODEC_ID_MACE6:
2096                 return 6 * frame_bytes / ch;
2097             case AV_CODEC_ID_PCM_LXF:
2098                 return 2 * (frame_bytes / (5 * ch));
2099             }
2100
2101             if (tag) {
2102                 /* calc from frame_bytes, channels, and codec_tag */
2103                 if (id == AV_CODEC_ID_SOL_DPCM) {
2104                     if (tag == 3)
2105                         return frame_bytes / ch;
2106                     else
2107                         return frame_bytes * 2 / ch;
2108                 }
2109             }
2110
2111             if (ba > 0) {
2112                 /* calc from frame_bytes, channels, and block_align */
2113                 int blocks = frame_bytes / ba;
2114                 switch (avctx->codec_id) {
2115                 case AV_CODEC_ID_ADPCM_IMA_WAV:
2116                     return blocks * (1 + (ba - 4 * ch) / (4 * ch) * 8);
2117                 case AV_CODEC_ID_ADPCM_IMA_DK3:
2118                     return blocks * (((ba - 16) * 2 / 3 * 4) / ch);
2119                 case AV_CODEC_ID_ADPCM_IMA_DK4:
2120                     return blocks * (1 + (ba - 4 * ch) * 2 / ch);
2121                 case AV_CODEC_ID_ADPCM_MS:
2122                     return blocks * (2 + (ba - 7 * ch) * 2 / ch);
2123                 }
2124             }
2125
2126             if (bps > 0) {
2127                 /* calc from frame_bytes, channels, and bits_per_coded_sample */
2128                 switch (avctx->codec_id) {
2129                 case AV_CODEC_ID_PCM_DVD:
2130                     return 2 * (frame_bytes / ((bps * 2 / 8) * ch));
2131                 case AV_CODEC_ID_PCM_BLURAY:
2132                     return frame_bytes / ((FFALIGN(ch, 2) * bps) / 8);
2133                 case AV_CODEC_ID_S302M:
2134                     return 2 * (frame_bytes / ((bps + 4) / 4)) / ch;
2135                 }
2136             }
2137         }
2138     }
2139
2140     return 0;
2141 }
2142
2143 #if !HAVE_THREADS
2144 int ff_thread_init(AVCodecContext *s)
2145 {
2146     return -1;
2147 }
2148
2149 #endif
2150
2151 unsigned int av_xiphlacing(unsigned char *s, unsigned int v)
2152 {
2153     unsigned int n = 0;
2154
2155     while (v >= 0xff) {
2156         *s++ = 0xff;
2157         v -= 0xff;
2158         n++;
2159     }
2160     *s = v;
2161     n++;
2162     return n;
2163 }
2164
2165 int ff_match_2uint16(const uint16_t(*tab)[2], int size, int a, int b)
2166 {
2167     int i;
2168     for (i = 0; i < size && !(tab[i][0] == a && tab[i][1] == b); i++) ;
2169     return i;
2170 }
2171
2172 void av_log_missing_feature(void *avc, const char *feature, int want_sample)
2173 {
2174     av_log(avc, AV_LOG_WARNING, "%s is not implemented. Update your Libav "
2175             "version to the newest one from Git. If the problem still "
2176             "occurs, it means that your file has a feature which has not "
2177             "been implemented.\n", feature);
2178     if(want_sample)
2179         av_log_ask_for_sample(avc, NULL);
2180 }
2181
2182 void av_log_ask_for_sample(void *avc, const char *msg, ...)
2183 {
2184     va_list argument_list;
2185
2186     va_start(argument_list, msg);
2187
2188     if (msg)
2189         av_vlog(avc, AV_LOG_WARNING, msg, argument_list);
2190     av_log(avc, AV_LOG_WARNING, "If you want to help, upload a sample "
2191             "of this file to ftp://upload.libav.org/incoming/ "
2192             "and contact the libav-devel mailing list.\n");
2193
2194     va_end(argument_list);
2195 }
2196
2197 static AVHWAccel *first_hwaccel = NULL;
2198
2199 void av_register_hwaccel(AVHWAccel *hwaccel)
2200 {
2201     AVHWAccel **p = &first_hwaccel;
2202     while (*p)
2203         p = &(*p)->next;
2204     *p = hwaccel;
2205     hwaccel->next = NULL;
2206 }
2207
2208 AVHWAccel *av_hwaccel_next(AVHWAccel *hwaccel)
2209 {
2210     return hwaccel ? hwaccel->next : first_hwaccel;
2211 }
2212
2213 AVHWAccel *ff_find_hwaccel(enum AVCodecID codec_id, enum AVPixelFormat pix_fmt)
2214 {
2215     AVHWAccel *hwaccel = NULL;
2216
2217     while ((hwaccel = av_hwaccel_next(hwaccel)))
2218         if (hwaccel->id == codec_id
2219             && hwaccel->pix_fmt == pix_fmt)
2220             return hwaccel;
2221     return NULL;
2222 }
2223
2224 int av_lockmgr_register(int (*cb)(void **mutex, enum AVLockOp op))
2225 {
2226     if (ff_lockmgr_cb) {
2227         if (ff_lockmgr_cb(&codec_mutex, AV_LOCK_DESTROY))
2228             return -1;
2229         if (ff_lockmgr_cb(&avformat_mutex, AV_LOCK_DESTROY))
2230             return -1;
2231     }
2232
2233     ff_lockmgr_cb = cb;
2234
2235     if (ff_lockmgr_cb) {
2236         if (ff_lockmgr_cb(&codec_mutex, AV_LOCK_CREATE))
2237             return -1;
2238         if (ff_lockmgr_cb(&avformat_mutex, AV_LOCK_CREATE))
2239             return -1;
2240     }
2241     return 0;
2242 }
2243
2244 int avpriv_lock_avformat(void)
2245 {
2246     if (ff_lockmgr_cb) {
2247         if ((*ff_lockmgr_cb)(&avformat_mutex, AV_LOCK_OBTAIN))
2248             return -1;
2249     }
2250     return 0;
2251 }
2252
2253 int avpriv_unlock_avformat(void)
2254 {
2255     if (ff_lockmgr_cb) {
2256         if ((*ff_lockmgr_cb)(&avformat_mutex, AV_LOCK_RELEASE))
2257             return -1;
2258     }
2259     return 0;
2260 }
2261
2262 unsigned int avpriv_toupper4(unsigned int x)
2263 {
2264     return av_toupper(x & 0xFF) +
2265           (av_toupper((x >>  8) & 0xFF) << 8)  +
2266           (av_toupper((x >> 16) & 0xFF) << 16) +
2267           (av_toupper((x >> 24) & 0xFF) << 24);
2268 }
2269
2270 int ff_thread_ref_frame(ThreadFrame *dst, ThreadFrame *src)
2271 {
2272     int ret;
2273
2274     dst->owner = src->owner;
2275
2276     ret = av_frame_ref(dst->f, src->f);
2277     if (ret < 0)
2278         return ret;
2279
2280     if (src->progress &&
2281         !(dst->progress = av_buffer_ref(src->progress))) {
2282         ff_thread_release_buffer(dst->owner, dst);
2283         return AVERROR(ENOMEM);
2284     }
2285
2286     return 0;
2287 }
2288
2289 #if !HAVE_THREADS
2290
2291 int ff_thread_get_buffer(AVCodecContext *avctx, AVFrame *f, int flags)
2292 {
2293     f->owner = avctx;
2294     return ff_get_buffer(avctx, f, flags);
2295 }
2296
2297 void ff_thread_release_buffer(AVCodecContext *avctx, AVFrame *f)
2298 {
2299     av_frame_unref(f);
2300 }
2301
2302 void ff_thread_finish_setup(AVCodecContext *avctx)
2303 {
2304 }
2305
2306 void ff_thread_report_progress(AVFrame *f, int progress, int field)
2307 {
2308 }
2309
2310 void ff_thread_await_progress(AVFrame *f, int progress, int field)
2311 {
2312 }
2313
2314 #endif
2315
2316 enum AVMediaType avcodec_get_type(enum AVCodecID codec_id)
2317 {
2318     if (codec_id <= AV_CODEC_ID_NONE)
2319         return AVMEDIA_TYPE_UNKNOWN;
2320     else if (codec_id < AV_CODEC_ID_FIRST_AUDIO)
2321         return AVMEDIA_TYPE_VIDEO;
2322     else if (codec_id < AV_CODEC_ID_FIRST_SUBTITLE)
2323         return AVMEDIA_TYPE_AUDIO;
2324     else if (codec_id < AV_CODEC_ID_FIRST_UNKNOWN)
2325         return AVMEDIA_TYPE_SUBTITLE;
2326
2327     return AVMEDIA_TYPE_UNKNOWN;
2328 }
2329
2330 int avcodec_is_open(AVCodecContext *s)
2331 {
2332     return !!s->internal;
2333 }