]> git.sesse.net Git - ffmpeg/blob - libavcodec/utils.c
lavc: update the fallback versions of ff_thread_*
[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         if (!frame->width)
556             frame->width               = avctx->width;
557         if (!frame->height)
558             frame->height              = avctx->height;
559         if (frame->format < 0)
560             frame->format              = avctx->pix_fmt;
561         if (!frame->sample_aspect_ratio.num)
562             frame->sample_aspect_ratio = avctx->sample_aspect_ratio;
563
564         if ((ret = av_image_check_size(avctx->width, avctx->height, 0, avctx)) < 0)
565             return ret;
566         break;
567     case AVMEDIA_TYPE_AUDIO:
568         if (!frame->sample_rate)
569             frame->sample_rate    = avctx->sample_rate;
570         if (frame->format < 0)
571             frame->format         = avctx->sample_fmt;
572         if (!frame->channel_layout) {
573             if (avctx->channel_layout) {
574                  if (av_get_channel_layout_nb_channels(avctx->channel_layout) !=
575                      avctx->channels) {
576                      av_log(avctx, AV_LOG_ERROR, "Inconsistent channel "
577                             "configuration.\n");
578                      return AVERROR(EINVAL);
579                  }
580
581                 frame->channel_layout = avctx->channel_layout;
582             } else {
583                 if (avctx->channels > FF_SANE_NB_CHANNELS) {
584                     av_log(avctx, AV_LOG_ERROR, "Too many channels: %d.\n",
585                            avctx->channels);
586                     return AVERROR(ENOSYS);
587                 }
588
589                 frame->channel_layout = av_get_default_channel_layout(avctx->channels);
590                 if (!frame->channel_layout)
591                     frame->channel_layout = (1ULL << avctx->channels) - 1;
592             }
593         }
594         break;
595     default: return AVERROR(EINVAL);
596     }
597
598     frame->pkt_pts = avctx->pkt ? avctx->pkt->pts : AV_NOPTS_VALUE;
599     frame->reordered_opaque = avctx->reordered_opaque;
600
601 #if FF_API_GET_BUFFER
602     /*
603      * Wrap an old get_buffer()-allocated buffer in an bunch of AVBuffers.
604      * We wrap each plane in its own AVBuffer. Each of those has a reference to
605      * a dummy AVBuffer as its private data, unreffing it on free.
606      * When all the planes are freed, the dummy buffer's free callback calls
607      * release_buffer().
608      */
609     if (avctx->get_buffer) {
610         CompatReleaseBufPriv *priv = NULL;
611         AVBufferRef *dummy_buf = NULL;
612         int planes, i, ret;
613
614         if (flags & AV_GET_BUFFER_FLAG_REF)
615             frame->reference    = 1;
616
617         ret = avctx->get_buffer(avctx, frame);
618         if (ret < 0)
619             return ret;
620
621         /* return if the buffers are already set up
622          * this would happen e.g. when a custom get_buffer() calls
623          * avcodec_default_get_buffer
624          */
625         if (frame->buf[0])
626             return 0;
627
628         priv = av_mallocz(sizeof(*priv));
629         if (!priv) {
630             ret = AVERROR(ENOMEM);
631             goto fail;
632         }
633         priv->avctx = *avctx;
634         priv->frame = *frame;
635
636         dummy_buf = av_buffer_create(NULL, 0, compat_free_buffer, priv, 0);
637         if (!dummy_buf) {
638             ret = AVERROR(ENOMEM);
639             goto fail;
640         }
641
642 #define WRAP_PLANE(ref_out, data, data_size)                            \
643 do {                                                                    \
644     AVBufferRef *dummy_ref = av_buffer_ref(dummy_buf);                  \
645     if (!dummy_ref) {                                                   \
646         ret = AVERROR(ENOMEM);                                          \
647         goto fail;                                                      \
648     }                                                                   \
649     ref_out = av_buffer_create(data, data_size, compat_release_buffer,  \
650                                dummy_ref, 0);                           \
651     if (!ref_out) {                                                     \
652         av_frame_unref(frame);                                          \
653         ret = AVERROR(ENOMEM);                                          \
654         goto fail;                                                      \
655     }                                                                   \
656 } while (0)
657
658         if (avctx->codec_type == AVMEDIA_TYPE_VIDEO) {
659             const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(frame->format);
660
661             if (!desc) {
662                 ret = AVERROR(EINVAL);
663                 goto fail;
664             }
665             planes = (desc->flags & PIX_FMT_PLANAR) ? desc->nb_components : 1;
666
667             for (i = 0; i < planes; i++) {
668                 int h_shift    = (i == 1 || i == 2) ? desc->log2_chroma_h : 0;
669                 int plane_size = (frame->width >> h_shift) * frame->linesize[i];
670
671                 WRAP_PLANE(frame->buf[i], frame->data[i], plane_size);
672             }
673         } else {
674             int planar = av_sample_fmt_is_planar(frame->format);
675             planes = planar ? avctx->channels : 1;
676
677             if (planes > FF_ARRAY_ELEMS(frame->buf)) {
678                 frame->nb_extended_buf = planes - FF_ARRAY_ELEMS(frame->buf);
679                 frame->extended_buf = av_malloc(sizeof(*frame->extended_buf) *
680                                                 frame->nb_extended_buf);
681                 if (!frame->extended_buf) {
682                     ret = AVERROR(ENOMEM);
683                     goto fail;
684                 }
685             }
686
687             for (i = 0; i < FFMIN(planes, FF_ARRAY_ELEMS(frame->buf)); i++)
688                 WRAP_PLANE(frame->buf[i], frame->extended_data[i], frame->linesize[0]);
689
690             for (i = 0; i < planes - FF_ARRAY_ELEMS(frame->buf); i++)
691                 WRAP_PLANE(frame->extended_buf[i],
692                            frame->extended_data[i + FF_ARRAY_ELEMS(frame->buf)],
693                            frame->linesize[0]);
694         }
695
696         av_buffer_unref(&dummy_buf);
697
698         return 0;
699
700 fail:
701         avctx->release_buffer(avctx, frame);
702         av_freep(&priv);
703         av_buffer_unref(&dummy_buf);
704         return ret;
705     }
706 #endif
707
708     return avctx->get_buffer2(avctx, frame, flags);
709 }
710
711 int ff_reget_buffer(AVCodecContext *avctx, AVFrame *frame)
712 {
713     AVFrame tmp;
714     int ret;
715
716     av_assert0(avctx->codec_type == AVMEDIA_TYPE_VIDEO);
717
718     if (!frame->data[0])
719         return ff_get_buffer(avctx, frame, AV_GET_BUFFER_FLAG_REF);
720
721     if (av_frame_is_writable(frame))
722         return 0;
723
724     av_frame_move_ref(&tmp, frame);
725
726     ret = ff_get_buffer(avctx, frame, AV_GET_BUFFER_FLAG_REF);
727     if (ret < 0) {
728         av_frame_unref(&tmp);
729         return ret;
730     }
731
732     av_image_copy(frame->data, frame->linesize, tmp.data, tmp.linesize,
733                   frame->format, frame->width, frame->height);
734
735     av_frame_unref(&tmp);
736
737     return 0;
738 }
739
740 #if FF_API_GET_BUFFER
741 void avcodec_default_release_buffer(AVCodecContext *s, AVFrame *pic)
742 {
743     av_frame_unref(pic);
744 }
745
746 int avcodec_default_reget_buffer(AVCodecContext *s, AVFrame *pic)
747 {
748     av_assert0(0);
749 }
750 #endif
751
752 int avcodec_default_execute(AVCodecContext *c, int (*func)(AVCodecContext *c2, void *arg2), void *arg, int *ret, int count, int size)
753 {
754     int i;
755
756     for (i = 0; i < count; i++) {
757         int r = func(c, (char *)arg + i * size);
758         if (ret)
759             ret[i] = r;
760     }
761     return 0;
762 }
763
764 int avcodec_default_execute2(AVCodecContext *c, int (*func)(AVCodecContext *c2, void *arg2, int jobnr, int threadnr), void *arg, int *ret, int count)
765 {
766     int i;
767
768     for (i = 0; i < count; i++) {
769         int r = func(c, arg, i, 0);
770         if (ret)
771             ret[i] = r;
772     }
773     return 0;
774 }
775
776 static int is_hwaccel_pix_fmt(enum AVPixelFormat pix_fmt)
777 {
778     const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(pix_fmt);
779     return desc->flags & PIX_FMT_HWACCEL;
780 }
781
782 enum AVPixelFormat avcodec_default_get_format(struct AVCodecContext *s, const enum AVPixelFormat *fmt)
783 {
784     while (*fmt != AV_PIX_FMT_NONE && is_hwaccel_pix_fmt(*fmt))
785         ++fmt;
786     return fmt[0];
787 }
788
789 void avcodec_get_frame_defaults(AVFrame *frame)
790 {
791     if (frame->extended_data != frame->data)
792         av_freep(&frame->extended_data);
793
794     memset(frame, 0, sizeof(AVFrame));
795
796     frame->pts                 = AV_NOPTS_VALUE;
797     frame->key_frame           = 1;
798     frame->sample_aspect_ratio = (AVRational) {0, 1 };
799     frame->format              = -1; /* unknown */
800     frame->extended_data       = frame->data;
801 }
802
803 AVFrame *avcodec_alloc_frame(void)
804 {
805     AVFrame *frame = av_mallocz(sizeof(AVFrame));
806
807     if (frame == NULL)
808         return NULL;
809
810     avcodec_get_frame_defaults(frame);
811
812     return frame;
813 }
814
815 void avcodec_free_frame(AVFrame **frame)
816 {
817     AVFrame *f;
818
819     if (!frame || !*frame)
820         return;
821
822     f = *frame;
823
824     if (f->extended_data != f->data)
825         av_freep(&f->extended_data);
826
827     av_freep(frame);
828 }
829
830 int attribute_align_arg avcodec_open2(AVCodecContext *avctx, const AVCodec *codec, AVDictionary **options)
831 {
832     int ret = 0;
833     AVDictionary *tmp = NULL;
834
835     if (avcodec_is_open(avctx))
836         return 0;
837
838     if ((!codec && !avctx->codec)) {
839         av_log(avctx, AV_LOG_ERROR, "No codec provided to avcodec_open2().\n");
840         return AVERROR(EINVAL);
841     }
842     if ((codec && avctx->codec && codec != avctx->codec)) {
843         av_log(avctx, AV_LOG_ERROR, "This AVCodecContext was allocated for %s, "
844                                     "but %s passed to avcodec_open2().\n", avctx->codec->name, codec->name);
845         return AVERROR(EINVAL);
846     }
847     if (!codec)
848         codec = avctx->codec;
849
850     if (avctx->extradata_size < 0 || avctx->extradata_size >= FF_MAX_EXTRADATA_SIZE)
851         return AVERROR(EINVAL);
852
853     if (options)
854         av_dict_copy(&tmp, *options, 0);
855
856     /* If there is a user-supplied mutex locking routine, call it. */
857     if (ff_lockmgr_cb) {
858         if ((*ff_lockmgr_cb)(&codec_mutex, AV_LOCK_OBTAIN))
859             return -1;
860     }
861
862     entangled_thread_counter++;
863     if (entangled_thread_counter != 1) {
864         av_log(avctx, AV_LOG_ERROR, "insufficient thread locking around avcodec_open/close()\n");
865         ret = -1;
866         goto end;
867     }
868
869     avctx->internal = av_mallocz(sizeof(AVCodecInternal));
870     if (!avctx->internal) {
871         ret = AVERROR(ENOMEM);
872         goto end;
873     }
874
875     avctx->internal->pool = av_mallocz(sizeof(*avctx->internal->pool));
876     if (!avctx->internal->pool) {
877         ret = AVERROR(ENOMEM);
878         goto free_and_end;
879     }
880
881     if (codec->priv_data_size > 0) {
882         if (!avctx->priv_data) {
883             avctx->priv_data = av_mallocz(codec->priv_data_size);
884             if (!avctx->priv_data) {
885                 ret = AVERROR(ENOMEM);
886                 goto end;
887             }
888             if (codec->priv_class) {
889                 *(const AVClass **)avctx->priv_data = codec->priv_class;
890                 av_opt_set_defaults(avctx->priv_data);
891             }
892         }
893         if (codec->priv_class && (ret = av_opt_set_dict(avctx->priv_data, &tmp)) < 0)
894             goto free_and_end;
895     } else {
896         avctx->priv_data = NULL;
897     }
898     if ((ret = av_opt_set_dict(avctx, &tmp)) < 0)
899         goto free_and_end;
900
901     if (avctx->coded_width && avctx->coded_height)
902         avcodec_set_dimensions(avctx, avctx->coded_width, avctx->coded_height);
903     else if (avctx->width && avctx->height)
904         avcodec_set_dimensions(avctx, avctx->width, avctx->height);
905
906     if ((avctx->coded_width || avctx->coded_height || avctx->width || avctx->height)
907         && (  av_image_check_size(avctx->coded_width, avctx->coded_height, 0, avctx) < 0
908            || av_image_check_size(avctx->width,       avctx->height,       0, avctx) < 0)) {
909         av_log(avctx, AV_LOG_WARNING, "ignoring invalid width/height values\n");
910         avcodec_set_dimensions(avctx, 0, 0);
911     }
912
913     /* if the decoder init function was already called previously,
914      * free the already allocated subtitle_header before overwriting it */
915     if (av_codec_is_decoder(codec))
916         av_freep(&avctx->subtitle_header);
917
918     if (avctx->channels > FF_SANE_NB_CHANNELS) {
919         ret = AVERROR(EINVAL);
920         goto free_and_end;
921     }
922
923     avctx->codec = codec;
924     if ((avctx->codec_type == AVMEDIA_TYPE_UNKNOWN || avctx->codec_type == codec->type) &&
925         avctx->codec_id == AV_CODEC_ID_NONE) {
926         avctx->codec_type = codec->type;
927         avctx->codec_id   = codec->id;
928     }
929     if (avctx->codec_id != codec->id || (avctx->codec_type != codec->type
930                                          && avctx->codec_type != AVMEDIA_TYPE_ATTACHMENT)) {
931         av_log(avctx, AV_LOG_ERROR, "codec type or id mismatches\n");
932         ret = AVERROR(EINVAL);
933         goto free_and_end;
934     }
935     avctx->frame_number = 0;
936
937     if (avctx->codec->capabilities & CODEC_CAP_EXPERIMENTAL &&
938         avctx->strict_std_compliance > FF_COMPLIANCE_EXPERIMENTAL) {
939         ret = AVERROR_EXPERIMENTAL;
940         goto free_and_end;
941     }
942
943     if (avctx->codec_type == AVMEDIA_TYPE_AUDIO &&
944         (!avctx->time_base.num || !avctx->time_base.den)) {
945         avctx->time_base.num = 1;
946         avctx->time_base.den = avctx->sample_rate;
947     }
948
949     if (HAVE_THREADS && !avctx->thread_opaque) {
950         ret = ff_thread_init(avctx);
951         if (ret < 0) {
952             goto free_and_end;
953         }
954     }
955     if (!HAVE_THREADS && !(codec->capabilities & CODEC_CAP_AUTO_THREADS))
956         avctx->thread_count = 1;
957
958     if (av_codec_is_encoder(avctx->codec)) {
959         int i;
960         if (avctx->codec->sample_fmts) {
961             for (i = 0; avctx->codec->sample_fmts[i] != AV_SAMPLE_FMT_NONE; i++) {
962                 if (avctx->sample_fmt == avctx->codec->sample_fmts[i])
963                     break;
964                 if (avctx->channels == 1 &&
965                     av_get_planar_sample_fmt(avctx->sample_fmt) ==
966                     av_get_planar_sample_fmt(avctx->codec->sample_fmts[i])) {
967                     avctx->sample_fmt = avctx->codec->sample_fmts[i];
968                     break;
969                 }
970             }
971             if (avctx->codec->sample_fmts[i] == AV_SAMPLE_FMT_NONE) {
972                 av_log(avctx, AV_LOG_ERROR, "Specified sample_fmt is not supported.\n");
973                 ret = AVERROR(EINVAL);
974                 goto free_and_end;
975             }
976         }
977         if (avctx->codec->pix_fmts) {
978             for (i = 0; avctx->codec->pix_fmts[i] != AV_PIX_FMT_NONE; i++)
979                 if (avctx->pix_fmt == avctx->codec->pix_fmts[i])
980                     break;
981             if (avctx->codec->pix_fmts[i] == AV_PIX_FMT_NONE) {
982                 av_log(avctx, AV_LOG_ERROR, "Specified pix_fmt is not supported\n");
983                 ret = AVERROR(EINVAL);
984                 goto free_and_end;
985             }
986         }
987         if (avctx->codec->supported_samplerates) {
988             for (i = 0; avctx->codec->supported_samplerates[i] != 0; i++)
989                 if (avctx->sample_rate == avctx->codec->supported_samplerates[i])
990                     break;
991             if (avctx->codec->supported_samplerates[i] == 0) {
992                 av_log(avctx, AV_LOG_ERROR, "Specified sample_rate is not supported\n");
993                 ret = AVERROR(EINVAL);
994                 goto free_and_end;
995             }
996         }
997         if (avctx->codec->channel_layouts) {
998             if (!avctx->channel_layout) {
999                 av_log(avctx, AV_LOG_WARNING, "channel_layout not specified\n");
1000             } else {
1001                 for (i = 0; avctx->codec->channel_layouts[i] != 0; i++)
1002                     if (avctx->channel_layout == avctx->codec->channel_layouts[i])
1003                         break;
1004                 if (avctx->codec->channel_layouts[i] == 0) {
1005                     av_log(avctx, AV_LOG_ERROR, "Specified channel_layout is not supported\n");
1006                     ret = AVERROR(EINVAL);
1007                     goto free_and_end;
1008                 }
1009             }
1010         }
1011         if (avctx->channel_layout && avctx->channels) {
1012             if (av_get_channel_layout_nb_channels(avctx->channel_layout) != avctx->channels) {
1013                 av_log(avctx, AV_LOG_ERROR, "channel layout does not match number of channels\n");
1014                 ret = AVERROR(EINVAL);
1015                 goto free_and_end;
1016             }
1017         } else if (avctx->channel_layout) {
1018             avctx->channels = av_get_channel_layout_nb_channels(avctx->channel_layout);
1019         }
1020
1021         if (!avctx->rc_initial_buffer_occupancy)
1022             avctx->rc_initial_buffer_occupancy = avctx->rc_buffer_size * 3 / 4;
1023     }
1024
1025     if (avctx->codec->init && !(avctx->active_thread_type & FF_THREAD_FRAME)) {
1026         ret = avctx->codec->init(avctx);
1027         if (ret < 0) {
1028             goto free_and_end;
1029         }
1030     }
1031
1032     if (av_codec_is_decoder(avctx->codec)) {
1033         /* validate channel layout from the decoder */
1034         if (avctx->channel_layout) {
1035             int channels = av_get_channel_layout_nb_channels(avctx->channel_layout);
1036             if (!avctx->channels)
1037                 avctx->channels = channels;
1038             else if (channels != avctx->channels) {
1039                 av_log(avctx, AV_LOG_WARNING,
1040                        "channel layout does not match number of channels\n");
1041                 avctx->channel_layout = 0;
1042             }
1043         }
1044         if (avctx->channels && avctx->channels < 0 ||
1045             avctx->channels > FF_SANE_NB_CHANNELS) {
1046             ret = AVERROR(EINVAL);
1047             goto free_and_end;
1048         }
1049     }
1050 end:
1051     entangled_thread_counter--;
1052
1053     /* Release any user-supplied mutex. */
1054     if (ff_lockmgr_cb) {
1055         (*ff_lockmgr_cb)(&codec_mutex, AV_LOCK_RELEASE);
1056     }
1057     if (options) {
1058         av_dict_free(options);
1059         *options = tmp;
1060     }
1061
1062     return ret;
1063 free_and_end:
1064     av_dict_free(&tmp);
1065     av_freep(&avctx->priv_data);
1066     if (avctx->internal)
1067         av_freep(&avctx->internal->pool);
1068     av_freep(&avctx->internal);
1069     avctx->codec = NULL;
1070     goto end;
1071 }
1072
1073 int ff_alloc_packet(AVPacket *avpkt, int size)
1074 {
1075     if (size > INT_MAX - FF_INPUT_BUFFER_PADDING_SIZE)
1076         return AVERROR(EINVAL);
1077
1078     if (avpkt->data) {
1079         AVBufferRef *buf = avpkt->buf;
1080 #if FF_API_DESTRUCT_PACKET
1081         void *destruct = avpkt->destruct;
1082 #endif
1083
1084         if (avpkt->size < size)
1085             return AVERROR(EINVAL);
1086
1087         av_init_packet(avpkt);
1088 #if FF_API_DESTRUCT_PACKET
1089         avpkt->destruct = destruct;
1090 #endif
1091         avpkt->buf      = buf;
1092         avpkt->size     = size;
1093         return 0;
1094     } else {
1095         return av_new_packet(avpkt, size);
1096     }
1097 }
1098
1099 /**
1100  * Pad last frame with silence.
1101  */
1102 static int pad_last_frame(AVCodecContext *s, AVFrame **dst, const AVFrame *src)
1103 {
1104     AVFrame *frame = NULL;
1105     uint8_t *buf   = NULL;
1106     int ret;
1107
1108     if (!(frame = avcodec_alloc_frame()))
1109         return AVERROR(ENOMEM);
1110     *frame = *src;
1111
1112     if ((ret = av_samples_get_buffer_size(&frame->linesize[0], s->channels,
1113                                           s->frame_size, s->sample_fmt, 0)) < 0)
1114         goto fail;
1115
1116     if (!(buf = av_malloc(ret))) {
1117         ret = AVERROR(ENOMEM);
1118         goto fail;
1119     }
1120
1121     frame->nb_samples = s->frame_size;
1122     if ((ret = avcodec_fill_audio_frame(frame, s->channels, s->sample_fmt,
1123                                         buf, ret, 0)) < 0)
1124         goto fail;
1125     if ((ret = av_samples_copy(frame->extended_data, src->extended_data, 0, 0,
1126                                src->nb_samples, s->channels, s->sample_fmt)) < 0)
1127         goto fail;
1128     if ((ret = av_samples_set_silence(frame->extended_data, src->nb_samples,
1129                                       frame->nb_samples - src->nb_samples,
1130                                       s->channels, s->sample_fmt)) < 0)
1131         goto fail;
1132
1133     *dst = frame;
1134
1135     return 0;
1136
1137 fail:
1138     if (frame->extended_data != frame->data)
1139         av_freep(&frame->extended_data);
1140     av_freep(&buf);
1141     av_freep(&frame);
1142     return ret;
1143 }
1144
1145 int attribute_align_arg avcodec_encode_audio2(AVCodecContext *avctx,
1146                                               AVPacket *avpkt,
1147                                               const AVFrame *frame,
1148                                               int *got_packet_ptr)
1149 {
1150     AVFrame tmp;
1151     AVFrame *padded_frame = NULL;
1152     int ret;
1153     int user_packet = !!avpkt->data;
1154
1155     *got_packet_ptr = 0;
1156
1157     if (!(avctx->codec->capabilities & CODEC_CAP_DELAY) && !frame) {
1158         av_free_packet(avpkt);
1159         av_init_packet(avpkt);
1160         return 0;
1161     }
1162
1163     /* ensure that extended_data is properly set */
1164     if (frame && !frame->extended_data) {
1165         if (av_sample_fmt_is_planar(avctx->sample_fmt) &&
1166             avctx->channels > AV_NUM_DATA_POINTERS) {
1167             av_log(avctx, AV_LOG_ERROR, "Encoding to a planar sample format, "
1168                                         "with more than %d channels, but extended_data is not set.\n",
1169                    AV_NUM_DATA_POINTERS);
1170             return AVERROR(EINVAL);
1171         }
1172         av_log(avctx, AV_LOG_WARNING, "extended_data is not set.\n");
1173
1174         tmp = *frame;
1175         tmp.extended_data = tmp.data;
1176         frame = &tmp;
1177     }
1178
1179     /* check for valid frame size */
1180     if (frame) {
1181         if (avctx->codec->capabilities & CODEC_CAP_SMALL_LAST_FRAME) {
1182             if (frame->nb_samples > avctx->frame_size)
1183                 return AVERROR(EINVAL);
1184         } else if (!(avctx->codec->capabilities & CODEC_CAP_VARIABLE_FRAME_SIZE)) {
1185             if (frame->nb_samples < avctx->frame_size &&
1186                 !avctx->internal->last_audio_frame) {
1187                 ret = pad_last_frame(avctx, &padded_frame, frame);
1188                 if (ret < 0)
1189                     return ret;
1190
1191                 frame = padded_frame;
1192                 avctx->internal->last_audio_frame = 1;
1193             }
1194
1195             if (frame->nb_samples != avctx->frame_size) {
1196                 ret = AVERROR(EINVAL);
1197                 goto end;
1198             }
1199         }
1200     }
1201
1202     ret = avctx->codec->encode2(avctx, avpkt, frame, got_packet_ptr);
1203     if (!ret) {
1204         if (*got_packet_ptr) {
1205             if (!(avctx->codec->capabilities & CODEC_CAP_DELAY)) {
1206                 if (avpkt->pts == AV_NOPTS_VALUE)
1207                     avpkt->pts = frame->pts;
1208                 if (!avpkt->duration)
1209                     avpkt->duration = ff_samples_to_time_base(avctx,
1210                                                               frame->nb_samples);
1211             }
1212             avpkt->dts = avpkt->pts;
1213         } else {
1214             avpkt->size = 0;
1215         }
1216
1217         if (!user_packet && avpkt->size) {
1218             ret = av_buffer_realloc(&avpkt->buf, avpkt->size);
1219             if (ret >= 0)
1220                 avpkt->data = avpkt->buf->data;
1221         }
1222
1223         avctx->frame_number++;
1224     }
1225
1226     if (ret < 0 || !*got_packet_ptr) {
1227         av_free_packet(avpkt);
1228         av_init_packet(avpkt);
1229         goto end;
1230     }
1231
1232     /* NOTE: if we add any audio encoders which output non-keyframe packets,
1233      *       this needs to be moved to the encoders, but for now we can do it
1234      *       here to simplify things */
1235     avpkt->flags |= AV_PKT_FLAG_KEY;
1236
1237 end:
1238     if (padded_frame) {
1239         av_freep(&padded_frame->data[0]);
1240         if (padded_frame->extended_data != padded_frame->data)
1241             av_freep(&padded_frame->extended_data);
1242         av_freep(&padded_frame);
1243     }
1244
1245     return ret;
1246 }
1247
1248 #if FF_API_OLD_ENCODE_AUDIO
1249 int attribute_align_arg avcodec_encode_audio(AVCodecContext *avctx,
1250                                              uint8_t *buf, int buf_size,
1251                                              const short *samples)
1252 {
1253     AVPacket pkt;
1254     AVFrame frame0 = { { 0 } };
1255     AVFrame *frame;
1256     int ret, samples_size, got_packet;
1257
1258     av_init_packet(&pkt);
1259     pkt.data = buf;
1260     pkt.size = buf_size;
1261
1262     if (samples) {
1263         frame = &frame0;
1264         avcodec_get_frame_defaults(frame);
1265
1266         if (avctx->frame_size) {
1267             frame->nb_samples = avctx->frame_size;
1268         } else {
1269             /* if frame_size is not set, the number of samples must be
1270              * calculated from the buffer size */
1271             int64_t nb_samples;
1272             if (!av_get_bits_per_sample(avctx->codec_id)) {
1273                 av_log(avctx, AV_LOG_ERROR, "avcodec_encode_audio() does not "
1274                                             "support this codec\n");
1275                 return AVERROR(EINVAL);
1276             }
1277             nb_samples = (int64_t)buf_size * 8 /
1278                          (av_get_bits_per_sample(avctx->codec_id) *
1279                           avctx->channels);
1280             if (nb_samples >= INT_MAX)
1281                 return AVERROR(EINVAL);
1282             frame->nb_samples = nb_samples;
1283         }
1284
1285         /* it is assumed that the samples buffer is large enough based on the
1286          * relevant parameters */
1287         samples_size = av_samples_get_buffer_size(NULL, avctx->channels,
1288                                                   frame->nb_samples,
1289                                                   avctx->sample_fmt, 1);
1290         if ((ret = avcodec_fill_audio_frame(frame, avctx->channels,
1291                                             avctx->sample_fmt,
1292                                             (const uint8_t *)samples,
1293                                             samples_size, 1)))
1294             return ret;
1295
1296         /* fabricate frame pts from sample count.
1297          * this is needed because the avcodec_encode_audio() API does not have
1298          * a way for the user to provide pts */
1299         frame->pts = ff_samples_to_time_base(avctx,
1300                                              avctx->internal->sample_count);
1301         avctx->internal->sample_count += frame->nb_samples;
1302     } else {
1303         frame = NULL;
1304     }
1305
1306     got_packet = 0;
1307     ret = avcodec_encode_audio2(avctx, &pkt, frame, &got_packet);
1308     if (!ret && got_packet && avctx->coded_frame) {
1309         avctx->coded_frame->pts       = pkt.pts;
1310         avctx->coded_frame->key_frame = !!(pkt.flags & AV_PKT_FLAG_KEY);
1311     }
1312     /* free any side data since we cannot return it */
1313     if (pkt.side_data_elems > 0) {
1314         int i;
1315         for (i = 0; i < pkt.side_data_elems; i++)
1316             av_free(pkt.side_data[i].data);
1317         av_freep(&pkt.side_data);
1318         pkt.side_data_elems = 0;
1319     }
1320
1321     if (frame && frame->extended_data != frame->data)
1322         av_free(frame->extended_data);
1323
1324     return ret ? ret : pkt.size;
1325 }
1326
1327 #endif
1328
1329 #if FF_API_OLD_ENCODE_VIDEO
1330 int attribute_align_arg avcodec_encode_video(AVCodecContext *avctx, uint8_t *buf, int buf_size,
1331                                              const AVFrame *pict)
1332 {
1333     AVPacket pkt;
1334     int ret, got_packet = 0;
1335
1336     if (buf_size < FF_MIN_BUFFER_SIZE) {
1337         av_log(avctx, AV_LOG_ERROR, "buffer smaller than minimum size\n");
1338         return -1;
1339     }
1340
1341     av_init_packet(&pkt);
1342     pkt.data = buf;
1343     pkt.size = buf_size;
1344
1345     ret = avcodec_encode_video2(avctx, &pkt, pict, &got_packet);
1346     if (!ret && got_packet && avctx->coded_frame) {
1347         avctx->coded_frame->pts       = pkt.pts;
1348         avctx->coded_frame->key_frame = !!(pkt.flags & AV_PKT_FLAG_KEY);
1349     }
1350
1351     /* free any side data since we cannot return it */
1352     if (pkt.side_data_elems > 0) {
1353         int i;
1354         for (i = 0; i < pkt.side_data_elems; i++)
1355             av_free(pkt.side_data[i].data);
1356         av_freep(&pkt.side_data);
1357         pkt.side_data_elems = 0;
1358     }
1359
1360     return ret ? ret : pkt.size;
1361 }
1362
1363 #endif
1364
1365 int attribute_align_arg avcodec_encode_video2(AVCodecContext *avctx,
1366                                               AVPacket *avpkt,
1367                                               const AVFrame *frame,
1368                                               int *got_packet_ptr)
1369 {
1370     int ret;
1371     int user_packet = !!avpkt->data;
1372
1373     *got_packet_ptr = 0;
1374
1375     if (!(avctx->codec->capabilities & CODEC_CAP_DELAY) && !frame) {
1376         av_free_packet(avpkt);
1377         av_init_packet(avpkt);
1378         avpkt->size = 0;
1379         return 0;
1380     }
1381
1382     if (av_image_check_size(avctx->width, avctx->height, 0, avctx))
1383         return AVERROR(EINVAL);
1384
1385     av_assert0(avctx->codec->encode2);
1386
1387     ret = avctx->codec->encode2(avctx, avpkt, frame, got_packet_ptr);
1388     if (!ret) {
1389         if (!*got_packet_ptr)
1390             avpkt->size = 0;
1391         else if (!(avctx->codec->capabilities & CODEC_CAP_DELAY))
1392             avpkt->pts = avpkt->dts = frame->pts;
1393
1394         if (!user_packet && avpkt->size) {
1395             ret = av_buffer_realloc(&avpkt->buf, avpkt->size);
1396             if (ret >= 0)
1397                 avpkt->data = avpkt->buf->data;
1398         }
1399
1400         avctx->frame_number++;
1401     }
1402
1403     if (ret < 0 || !*got_packet_ptr)
1404         av_free_packet(avpkt);
1405
1406     emms_c();
1407     return ret;
1408 }
1409
1410 int avcodec_encode_subtitle(AVCodecContext *avctx, uint8_t *buf, int buf_size,
1411                             const AVSubtitle *sub)
1412 {
1413     int ret;
1414     if (sub->start_display_time) {
1415         av_log(avctx, AV_LOG_ERROR, "start_display_time must be 0.\n");
1416         return -1;
1417     }
1418     if (sub->num_rects == 0 || !sub->rects)
1419         return -1;
1420     ret = avctx->codec->encode_sub(avctx, buf, buf_size, sub);
1421     avctx->frame_number++;
1422     return ret;
1423 }
1424
1425 static void apply_param_change(AVCodecContext *avctx, AVPacket *avpkt)
1426 {
1427     int size = 0;
1428     const uint8_t *data;
1429     uint32_t flags;
1430
1431     if (!(avctx->codec->capabilities & CODEC_CAP_PARAM_CHANGE))
1432         return;
1433
1434     data = av_packet_get_side_data(avpkt, AV_PKT_DATA_PARAM_CHANGE, &size);
1435     if (!data || size < 4)
1436         return;
1437     flags = bytestream_get_le32(&data);
1438     size -= 4;
1439     if (size < 4) /* Required for any of the changes */
1440         return;
1441     if (flags & AV_SIDE_DATA_PARAM_CHANGE_CHANNEL_COUNT) {
1442         avctx->channels = bytestream_get_le32(&data);
1443         size -= 4;
1444     }
1445     if (flags & AV_SIDE_DATA_PARAM_CHANGE_CHANNEL_LAYOUT) {
1446         if (size < 8)
1447             return;
1448         avctx->channel_layout = bytestream_get_le64(&data);
1449         size -= 8;
1450     }
1451     if (size < 4)
1452         return;
1453     if (flags & AV_SIDE_DATA_PARAM_CHANGE_SAMPLE_RATE) {
1454         avctx->sample_rate = bytestream_get_le32(&data);
1455         size -= 4;
1456     }
1457     if (flags & AV_SIDE_DATA_PARAM_CHANGE_DIMENSIONS) {
1458         if (size < 8)
1459             return;
1460         avctx->width  = bytestream_get_le32(&data);
1461         avctx->height = bytestream_get_le32(&data);
1462         avcodec_set_dimensions(avctx, avctx->width, avctx->height);
1463         size -= 8;
1464     }
1465 }
1466
1467 int attribute_align_arg avcodec_decode_video2(AVCodecContext *avctx, AVFrame *picture,
1468                                               int *got_picture_ptr,
1469                                               AVPacket *avpkt)
1470 {
1471     AVCodecInternal *avci = avctx->internal;
1472     int ret;
1473
1474     *got_picture_ptr = 0;
1475     if ((avctx->coded_width || avctx->coded_height) && av_image_check_size(avctx->coded_width, avctx->coded_height, 0, avctx))
1476         return -1;
1477
1478     avctx->pkt = avpkt;
1479     apply_param_change(avctx, avpkt);
1480
1481     avcodec_get_frame_defaults(picture);
1482
1483     if (!avctx->refcounted_frames)
1484         av_frame_unref(&avci->to_free);
1485
1486     if ((avctx->codec->capabilities & CODEC_CAP_DELAY) || avpkt->size || (avctx->active_thread_type & FF_THREAD_FRAME)) {
1487         if (HAVE_THREADS && avctx->active_thread_type & FF_THREAD_FRAME)
1488             ret = ff_thread_decode_frame(avctx, picture, got_picture_ptr,
1489                                          avpkt);
1490         else {
1491             ret = avctx->codec->decode(avctx, picture, got_picture_ptr,
1492                                        avpkt);
1493             picture->pkt_dts = avpkt->dts;
1494             /* get_buffer is supposed to set frame parameters */
1495             if (!(avctx->codec->capabilities & CODEC_CAP_DR1)) {
1496                 picture->sample_aspect_ratio = avctx->sample_aspect_ratio;
1497                 picture->width               = avctx->width;
1498                 picture->height              = avctx->height;
1499                 picture->format              = avctx->pix_fmt;
1500             }
1501         }
1502
1503         emms_c(); //needed to avoid an emms_c() call before every return;
1504
1505         if (ret < 0 && picture->data[0])
1506             av_frame_unref(picture);
1507
1508         if (*got_picture_ptr) {
1509             if (!avctx->refcounted_frames) {
1510                 avci->to_free = *picture;
1511                 avci->to_free.extended_data = avci->to_free.data;
1512             }
1513
1514             avctx->frame_number++;
1515         }
1516     } else
1517         ret = 0;
1518
1519     /* many decoders assign whole AVFrames, thus overwriting extended_data;
1520      * make sure it's set correctly */
1521     picture->extended_data = picture->data;
1522
1523     return ret;
1524 }
1525
1526 #if FF_API_OLD_DECODE_AUDIO
1527 int attribute_align_arg avcodec_decode_audio3(AVCodecContext *avctx, int16_t *samples,
1528                                               int *frame_size_ptr,
1529                                               AVPacket *avpkt)
1530 {
1531     AVFrame frame = { { 0 } };
1532     int ret, got_frame = 0;
1533
1534     if (avctx->get_buffer != avcodec_default_get_buffer) {
1535         av_log(avctx, AV_LOG_ERROR, "Custom get_buffer() for use with"
1536                                     "avcodec_decode_audio3() detected. Overriding with avcodec_default_get_buffer\n");
1537         av_log(avctx, AV_LOG_ERROR, "Please port your application to "
1538                                     "avcodec_decode_audio4()\n");
1539         avctx->get_buffer = avcodec_default_get_buffer;
1540     }
1541
1542     ret = avcodec_decode_audio4(avctx, &frame, &got_frame, avpkt);
1543
1544     if (ret >= 0 && got_frame) {
1545         int ch, plane_size;
1546         int planar    = av_sample_fmt_is_planar(avctx->sample_fmt);
1547         int data_size = av_samples_get_buffer_size(&plane_size, avctx->channels,
1548                                                    frame.nb_samples,
1549                                                    avctx->sample_fmt, 1);
1550         if (*frame_size_ptr < data_size) {
1551             av_log(avctx, AV_LOG_ERROR, "output buffer size is too small for "
1552                                         "the current frame (%d < %d)\n", *frame_size_ptr, data_size);
1553             return AVERROR(EINVAL);
1554         }
1555
1556         memcpy(samples, frame.extended_data[0], plane_size);
1557
1558         if (planar && avctx->channels > 1) {
1559             uint8_t *out = ((uint8_t *)samples) + plane_size;
1560             for (ch = 1; ch < avctx->channels; ch++) {
1561                 memcpy(out, frame.extended_data[ch], plane_size);
1562                 out += plane_size;
1563             }
1564         }
1565         *frame_size_ptr = data_size;
1566     } else {
1567         *frame_size_ptr = 0;
1568     }
1569     return ret;
1570 }
1571
1572 #endif
1573
1574 int attribute_align_arg avcodec_decode_audio4(AVCodecContext *avctx,
1575                                               AVFrame *frame,
1576                                               int *got_frame_ptr,
1577                                               AVPacket *avpkt)
1578 {
1579     AVCodecInternal *avci = avctx->internal;
1580     int planar, channels;
1581     int ret = 0;
1582
1583     *got_frame_ptr = 0;
1584
1585     avctx->pkt = avpkt;
1586
1587     if (!avpkt->data && avpkt->size) {
1588         av_log(avctx, AV_LOG_ERROR, "invalid packet: NULL data, size != 0\n");
1589         return AVERROR(EINVAL);
1590     }
1591
1592     apply_param_change(avctx, avpkt);
1593
1594     avcodec_get_frame_defaults(frame);
1595
1596     if (!avctx->refcounted_frames)
1597         av_frame_unref(&avci->to_free);
1598
1599     if ((avctx->codec->capabilities & CODEC_CAP_DELAY) || avpkt->size) {
1600         ret = avctx->codec->decode(avctx, frame, got_frame_ptr, avpkt);
1601         if (ret >= 0 && *got_frame_ptr) {
1602             avctx->frame_number++;
1603             frame->pkt_dts = avpkt->dts;
1604             if (frame->format == AV_SAMPLE_FMT_NONE)
1605                 frame->format = avctx->sample_fmt;
1606
1607             if (!avctx->refcounted_frames) {
1608                 avci->to_free = *frame;
1609                 avci->to_free.extended_data = avci->to_free.data;
1610             }
1611         }
1612
1613         if (ret < 0 && frame->data[0])
1614             av_frame_unref(frame);
1615     }
1616
1617     /* many decoders assign whole AVFrames, thus overwriting extended_data;
1618      * make sure it's set correctly; assume decoders that actually use
1619      * extended_data are doing it correctly */
1620     planar   = av_sample_fmt_is_planar(frame->format);
1621     channels = av_get_channel_layout_nb_channels(frame->channel_layout);
1622     if (!(planar && channels > AV_NUM_DATA_POINTERS))
1623         frame->extended_data = frame->data;
1624
1625     return ret;
1626 }
1627
1628 int avcodec_decode_subtitle2(AVCodecContext *avctx, AVSubtitle *sub,
1629                              int *got_sub_ptr,
1630                              AVPacket *avpkt)
1631 {
1632     int ret;
1633
1634     avctx->pkt = avpkt;
1635     *got_sub_ptr = 0;
1636     ret = avctx->codec->decode(avctx, sub, got_sub_ptr, avpkt);
1637     if (*got_sub_ptr)
1638         avctx->frame_number++;
1639     return ret;
1640 }
1641
1642 void avsubtitle_free(AVSubtitle *sub)
1643 {
1644     int i;
1645
1646     for (i = 0; i < sub->num_rects; i++) {
1647         av_freep(&sub->rects[i]->pict.data[0]);
1648         av_freep(&sub->rects[i]->pict.data[1]);
1649         av_freep(&sub->rects[i]->pict.data[2]);
1650         av_freep(&sub->rects[i]->pict.data[3]);
1651         av_freep(&sub->rects[i]->text);
1652         av_freep(&sub->rects[i]->ass);
1653         av_freep(&sub->rects[i]);
1654     }
1655
1656     av_freep(&sub->rects);
1657
1658     memset(sub, 0, sizeof(AVSubtitle));
1659 }
1660
1661 av_cold int avcodec_close(AVCodecContext *avctx)
1662 {
1663     /* If there is a user-supplied mutex locking routine, call it. */
1664     if (ff_lockmgr_cb) {
1665         if ((*ff_lockmgr_cb)(&codec_mutex, AV_LOCK_OBTAIN))
1666             return -1;
1667     }
1668
1669     entangled_thread_counter++;
1670     if (entangled_thread_counter != 1) {
1671         av_log(avctx, AV_LOG_ERROR, "insufficient thread locking around avcodec_open/close()\n");
1672         entangled_thread_counter--;
1673         return -1;
1674     }
1675
1676     if (avcodec_is_open(avctx)) {
1677         FramePool *pool = avctx->internal->pool;
1678         int i;
1679         if (HAVE_THREADS && avctx->thread_opaque)
1680             ff_thread_free(avctx);
1681         if (avctx->codec && avctx->codec->close)
1682             avctx->codec->close(avctx);
1683         avctx->coded_frame = NULL;
1684         if (!avctx->refcounted_frames)
1685             av_frame_unref(&avctx->internal->to_free);
1686         for (i = 0; i < FF_ARRAY_ELEMS(pool->pools); i++)
1687             av_buffer_pool_uninit(&pool->pools[i]);
1688         av_freep(&avctx->internal->pool);
1689         av_freep(&avctx->internal);
1690     }
1691
1692     if (avctx->priv_data && avctx->codec && avctx->codec->priv_class)
1693         av_opt_free(avctx->priv_data);
1694     av_opt_free(avctx);
1695     av_freep(&avctx->priv_data);
1696     if (av_codec_is_encoder(avctx->codec))
1697         av_freep(&avctx->extradata);
1698     avctx->codec = NULL;
1699     avctx->active_thread_type = 0;
1700     entangled_thread_counter--;
1701
1702     /* Release any user-supplied mutex. */
1703     if (ff_lockmgr_cb) {
1704         (*ff_lockmgr_cb)(&codec_mutex, AV_LOCK_RELEASE);
1705     }
1706     return 0;
1707 }
1708
1709 static AVCodec *find_encdec(enum AVCodecID id, int encoder)
1710 {
1711     AVCodec *p, *experimental = NULL;
1712     p = first_avcodec;
1713     while (p) {
1714         if ((encoder ? av_codec_is_encoder(p) : av_codec_is_decoder(p)) &&
1715             p->id == id) {
1716             if (p->capabilities & CODEC_CAP_EXPERIMENTAL && !experimental) {
1717                 experimental = p;
1718             } else
1719                 return p;
1720         }
1721         p = p->next;
1722     }
1723     return experimental;
1724 }
1725
1726 AVCodec *avcodec_find_encoder(enum AVCodecID id)
1727 {
1728     return find_encdec(id, 1);
1729 }
1730
1731 AVCodec *avcodec_find_encoder_by_name(const char *name)
1732 {
1733     AVCodec *p;
1734     if (!name)
1735         return NULL;
1736     p = first_avcodec;
1737     while (p) {
1738         if (av_codec_is_encoder(p) && strcmp(name, p->name) == 0)
1739             return p;
1740         p = p->next;
1741     }
1742     return NULL;
1743 }
1744
1745 AVCodec *avcodec_find_decoder(enum AVCodecID id)
1746 {
1747     return find_encdec(id, 0);
1748 }
1749
1750 AVCodec *avcodec_find_decoder_by_name(const char *name)
1751 {
1752     AVCodec *p;
1753     if (!name)
1754         return NULL;
1755     p = first_avcodec;
1756     while (p) {
1757         if (av_codec_is_decoder(p) && strcmp(name, p->name) == 0)
1758             return p;
1759         p = p->next;
1760     }
1761     return NULL;
1762 }
1763
1764 static int get_bit_rate(AVCodecContext *ctx)
1765 {
1766     int bit_rate;
1767     int bits_per_sample;
1768
1769     switch (ctx->codec_type) {
1770     case AVMEDIA_TYPE_VIDEO:
1771     case AVMEDIA_TYPE_DATA:
1772     case AVMEDIA_TYPE_SUBTITLE:
1773     case AVMEDIA_TYPE_ATTACHMENT:
1774         bit_rate = ctx->bit_rate;
1775         break;
1776     case AVMEDIA_TYPE_AUDIO:
1777         bits_per_sample = av_get_bits_per_sample(ctx->codec_id);
1778         bit_rate = bits_per_sample ? ctx->sample_rate * ctx->channels * bits_per_sample : ctx->bit_rate;
1779         break;
1780     default:
1781         bit_rate = 0;
1782         break;
1783     }
1784     return bit_rate;
1785 }
1786
1787 size_t av_get_codec_tag_string(char *buf, size_t buf_size, unsigned int codec_tag)
1788 {
1789     int i, len, ret = 0;
1790
1791 #define TAG_PRINT(x)                                              \
1792     (((x) >= '0' && (x) <= '9') ||                                \
1793      ((x) >= 'a' && (x) <= 'z') || ((x) >= 'A' && (x) <= 'Z') ||  \
1794      ((x) == '.' || (x) == ' '))
1795
1796     for (i = 0; i < 4; i++) {
1797         len = snprintf(buf, buf_size,
1798                        TAG_PRINT(codec_tag & 0xFF) ? "%c" : "[%d]", codec_tag & 0xFF);
1799         buf        += len;
1800         buf_size    = buf_size > len ? buf_size - len : 0;
1801         ret        += len;
1802         codec_tag >>= 8;
1803     }
1804     return ret;
1805 }
1806
1807 void avcodec_string(char *buf, int buf_size, AVCodecContext *enc, int encode)
1808 {
1809     const char *codec_name;
1810     const char *profile = NULL;
1811     const AVCodec *p;
1812     char buf1[32];
1813     int bitrate;
1814     AVRational display_aspect_ratio;
1815
1816     if (enc->codec)
1817         p = enc->codec;
1818     else if (encode)
1819         p = avcodec_find_encoder(enc->codec_id);
1820     else
1821         p = avcodec_find_decoder(enc->codec_id);
1822
1823     if (p) {
1824         codec_name = p->name;
1825         profile = av_get_profile_name(p, enc->profile);
1826     } else if (enc->codec_id == AV_CODEC_ID_MPEG2TS) {
1827         /* fake mpeg2 transport stream codec (currently not
1828          * registered) */
1829         codec_name = "mpeg2ts";
1830     } else if (enc->codec_name[0] != '\0') {
1831         codec_name = enc->codec_name;
1832     } else {
1833         /* output avi tags */
1834         char tag_buf[32];
1835         av_get_codec_tag_string(tag_buf, sizeof(tag_buf), enc->codec_tag);
1836         snprintf(buf1, sizeof(buf1), "%s / 0x%04X", tag_buf, enc->codec_tag);
1837         codec_name = buf1;
1838     }
1839
1840     switch (enc->codec_type) {
1841     case AVMEDIA_TYPE_VIDEO:
1842         snprintf(buf, buf_size,
1843                  "Video: %s%s",
1844                  codec_name, enc->mb_decision ? " (hq)" : "");
1845         if (profile)
1846             snprintf(buf + strlen(buf), buf_size - strlen(buf),
1847                      " (%s)", profile);
1848         if (enc->pix_fmt != AV_PIX_FMT_NONE) {
1849             snprintf(buf + strlen(buf), buf_size - strlen(buf),
1850                      ", %s",
1851                      av_get_pix_fmt_name(enc->pix_fmt));
1852         }
1853         if (enc->width) {
1854             snprintf(buf + strlen(buf), buf_size - strlen(buf),
1855                      ", %dx%d",
1856                      enc->width, enc->height);
1857             if (enc->sample_aspect_ratio.num) {
1858                 av_reduce(&display_aspect_ratio.num, &display_aspect_ratio.den,
1859                           enc->width * enc->sample_aspect_ratio.num,
1860                           enc->height * enc->sample_aspect_ratio.den,
1861                           1024 * 1024);
1862                 snprintf(buf + strlen(buf), buf_size - strlen(buf),
1863                          " [PAR %d:%d DAR %d:%d]",
1864                          enc->sample_aspect_ratio.num, enc->sample_aspect_ratio.den,
1865                          display_aspect_ratio.num, display_aspect_ratio.den);
1866             }
1867             if (av_log_get_level() >= AV_LOG_DEBUG) {
1868                 int g = av_gcd(enc->time_base.num, enc->time_base.den);
1869                 snprintf(buf + strlen(buf), buf_size - strlen(buf),
1870                          ", %d/%d",
1871                          enc->time_base.num / g, enc->time_base.den / g);
1872             }
1873         }
1874         if (encode) {
1875             snprintf(buf + strlen(buf), buf_size - strlen(buf),
1876                      ", q=%d-%d", enc->qmin, enc->qmax);
1877         }
1878         break;
1879     case AVMEDIA_TYPE_AUDIO:
1880         snprintf(buf, buf_size,
1881                  "Audio: %s",
1882                  codec_name);
1883         if (profile)
1884             snprintf(buf + strlen(buf), buf_size - strlen(buf),
1885                      " (%s)", profile);
1886         if (enc->sample_rate) {
1887             snprintf(buf + strlen(buf), buf_size - strlen(buf),
1888                      ", %d Hz", enc->sample_rate);
1889         }
1890         av_strlcat(buf, ", ", buf_size);
1891         av_get_channel_layout_string(buf + strlen(buf), buf_size - strlen(buf), enc->channels, enc->channel_layout);
1892         if (enc->sample_fmt != AV_SAMPLE_FMT_NONE) {
1893             snprintf(buf + strlen(buf), buf_size - strlen(buf),
1894                      ", %s", av_get_sample_fmt_name(enc->sample_fmt));
1895         }
1896         break;
1897     case AVMEDIA_TYPE_DATA:
1898         snprintf(buf, buf_size, "Data: %s", codec_name);
1899         break;
1900     case AVMEDIA_TYPE_SUBTITLE:
1901         snprintf(buf, buf_size, "Subtitle: %s", codec_name);
1902         break;
1903     case AVMEDIA_TYPE_ATTACHMENT:
1904         snprintf(buf, buf_size, "Attachment: %s", codec_name);
1905         break;
1906     default:
1907         snprintf(buf, buf_size, "Invalid Codec type %d", enc->codec_type);
1908         return;
1909     }
1910     if (encode) {
1911         if (enc->flags & CODEC_FLAG_PASS1)
1912             snprintf(buf + strlen(buf), buf_size - strlen(buf),
1913                      ", pass 1");
1914         if (enc->flags & CODEC_FLAG_PASS2)
1915             snprintf(buf + strlen(buf), buf_size - strlen(buf),
1916                      ", pass 2");
1917     }
1918     bitrate = get_bit_rate(enc);
1919     if (bitrate != 0) {
1920         snprintf(buf + strlen(buf), buf_size - strlen(buf),
1921                  ", %d kb/s", bitrate / 1000);
1922     }
1923 }
1924
1925 const char *av_get_profile_name(const AVCodec *codec, int profile)
1926 {
1927     const AVProfile *p;
1928     if (profile == FF_PROFILE_UNKNOWN || !codec->profiles)
1929         return NULL;
1930
1931     for (p = codec->profiles; p->profile != FF_PROFILE_UNKNOWN; p++)
1932         if (p->profile == profile)
1933             return p->name;
1934
1935     return NULL;
1936 }
1937
1938 unsigned avcodec_version(void)
1939 {
1940     return LIBAVCODEC_VERSION_INT;
1941 }
1942
1943 const char *avcodec_configuration(void)
1944 {
1945     return LIBAV_CONFIGURATION;
1946 }
1947
1948 const char *avcodec_license(void)
1949 {
1950 #define LICENSE_PREFIX "libavcodec license: "
1951     return LICENSE_PREFIX LIBAV_LICENSE + sizeof(LICENSE_PREFIX) - 1;
1952 }
1953
1954 void avcodec_flush_buffers(AVCodecContext *avctx)
1955 {
1956     if (HAVE_THREADS && avctx->active_thread_type & FF_THREAD_FRAME)
1957         ff_thread_flush(avctx);
1958     else if (avctx->codec->flush)
1959         avctx->codec->flush(avctx);
1960 }
1961
1962 int av_get_exact_bits_per_sample(enum AVCodecID codec_id)
1963 {
1964     switch (codec_id) {
1965     case AV_CODEC_ID_ADPCM_CT:
1966     case AV_CODEC_ID_ADPCM_IMA_APC:
1967     case AV_CODEC_ID_ADPCM_IMA_EA_SEAD:
1968     case AV_CODEC_ID_ADPCM_IMA_WS:
1969     case AV_CODEC_ID_ADPCM_G722:
1970     case AV_CODEC_ID_ADPCM_YAMAHA:
1971         return 4;
1972     case AV_CODEC_ID_PCM_ALAW:
1973     case AV_CODEC_ID_PCM_MULAW:
1974     case AV_CODEC_ID_PCM_S8:
1975     case AV_CODEC_ID_PCM_U8:
1976     case AV_CODEC_ID_PCM_ZORK:
1977         return 8;
1978     case AV_CODEC_ID_PCM_S16BE:
1979     case AV_CODEC_ID_PCM_S16LE:
1980     case AV_CODEC_ID_PCM_S16LE_PLANAR:
1981     case AV_CODEC_ID_PCM_U16BE:
1982     case AV_CODEC_ID_PCM_U16LE:
1983         return 16;
1984     case AV_CODEC_ID_PCM_S24DAUD:
1985     case AV_CODEC_ID_PCM_S24BE:
1986     case AV_CODEC_ID_PCM_S24LE:
1987     case AV_CODEC_ID_PCM_U24BE:
1988     case AV_CODEC_ID_PCM_U24LE:
1989         return 24;
1990     case AV_CODEC_ID_PCM_S32BE:
1991     case AV_CODEC_ID_PCM_S32LE:
1992     case AV_CODEC_ID_PCM_U32BE:
1993     case AV_CODEC_ID_PCM_U32LE:
1994     case AV_CODEC_ID_PCM_F32BE:
1995     case AV_CODEC_ID_PCM_F32LE:
1996         return 32;
1997     case AV_CODEC_ID_PCM_F64BE:
1998     case AV_CODEC_ID_PCM_F64LE:
1999         return 64;
2000     default:
2001         return 0;
2002     }
2003 }
2004
2005 int av_get_bits_per_sample(enum AVCodecID codec_id)
2006 {
2007     switch (codec_id) {
2008     case AV_CODEC_ID_ADPCM_SBPRO_2:
2009         return 2;
2010     case AV_CODEC_ID_ADPCM_SBPRO_3:
2011         return 3;
2012     case AV_CODEC_ID_ADPCM_SBPRO_4:
2013     case AV_CODEC_ID_ADPCM_IMA_WAV:
2014     case AV_CODEC_ID_ADPCM_IMA_QT:
2015     case AV_CODEC_ID_ADPCM_SWF:
2016     case AV_CODEC_ID_ADPCM_MS:
2017         return 4;
2018     default:
2019         return av_get_exact_bits_per_sample(codec_id);
2020     }
2021 }
2022
2023 int av_get_audio_frame_duration(AVCodecContext *avctx, int frame_bytes)
2024 {
2025     int id, sr, ch, ba, tag, bps;
2026
2027     id  = avctx->codec_id;
2028     sr  = avctx->sample_rate;
2029     ch  = avctx->channels;
2030     ba  = avctx->block_align;
2031     tag = avctx->codec_tag;
2032     bps = av_get_exact_bits_per_sample(avctx->codec_id);
2033
2034     /* codecs with an exact constant bits per sample */
2035     if (bps > 0 && ch > 0 && frame_bytes > 0)
2036         return (frame_bytes * 8) / (bps * ch);
2037     bps = avctx->bits_per_coded_sample;
2038
2039     /* codecs with a fixed packet duration */
2040     switch (id) {
2041     case AV_CODEC_ID_ADPCM_ADX:    return   32;
2042     case AV_CODEC_ID_ADPCM_IMA_QT: return   64;
2043     case AV_CODEC_ID_ADPCM_EA_XAS: return  128;
2044     case AV_CODEC_ID_AMR_NB:
2045     case AV_CODEC_ID_GSM:
2046     case AV_CODEC_ID_QCELP:
2047     case AV_CODEC_ID_RA_144:
2048     case AV_CODEC_ID_RA_288:       return  160;
2049     case AV_CODEC_ID_IMC:          return  256;
2050     case AV_CODEC_ID_AMR_WB:
2051     case AV_CODEC_ID_GSM_MS:       return  320;
2052     case AV_CODEC_ID_MP1:          return  384;
2053     case AV_CODEC_ID_ATRAC1:       return  512;
2054     case AV_CODEC_ID_ATRAC3:       return 1024;
2055     case AV_CODEC_ID_MP2:
2056     case AV_CODEC_ID_MUSEPACK7:    return 1152;
2057     case AV_CODEC_ID_AC3:          return 1536;
2058     }
2059
2060     if (sr > 0) {
2061         /* calc from sample rate */
2062         if (id == AV_CODEC_ID_TTA)
2063             return 256 * sr / 245;
2064
2065         if (ch > 0) {
2066             /* calc from sample rate and channels */
2067             if (id == AV_CODEC_ID_BINKAUDIO_DCT)
2068                 return (480 << (sr / 22050)) / ch;
2069         }
2070     }
2071
2072     if (ba > 0) {
2073         /* calc from block_align */
2074         if (id == AV_CODEC_ID_SIPR) {
2075             switch (ba) {
2076             case 20: return 160;
2077             case 19: return 144;
2078             case 29: return 288;
2079             case 37: return 480;
2080             }
2081         } else if (id == AV_CODEC_ID_ILBC) {
2082             switch (ba) {
2083             case 38: return 160;
2084             case 50: return 240;
2085             }
2086         }
2087     }
2088
2089     if (frame_bytes > 0) {
2090         /* calc from frame_bytes only */
2091         if (id == AV_CODEC_ID_TRUESPEECH)
2092             return 240 * (frame_bytes / 32);
2093         if (id == AV_CODEC_ID_NELLYMOSER)
2094             return 256 * (frame_bytes / 64);
2095
2096         if (bps > 0) {
2097             /* calc from frame_bytes and bits_per_coded_sample */
2098             if (id == AV_CODEC_ID_ADPCM_G726)
2099                 return frame_bytes * 8 / bps;
2100         }
2101
2102         if (ch > 0) {
2103             /* calc from frame_bytes and channels */
2104             switch (id) {
2105             case AV_CODEC_ID_ADPCM_4XM:
2106             case AV_CODEC_ID_ADPCM_IMA_ISS:
2107                 return (frame_bytes - 4 * ch) * 2 / ch;
2108             case AV_CODEC_ID_ADPCM_IMA_SMJPEG:
2109                 return (frame_bytes - 4) * 2 / ch;
2110             case AV_CODEC_ID_ADPCM_IMA_AMV:
2111                 return (frame_bytes - 8) * 2 / ch;
2112             case AV_CODEC_ID_ADPCM_XA:
2113                 return (frame_bytes / 128) * 224 / ch;
2114             case AV_CODEC_ID_INTERPLAY_DPCM:
2115                 return (frame_bytes - 6 - ch) / ch;
2116             case AV_CODEC_ID_ROQ_DPCM:
2117                 return (frame_bytes - 8) / ch;
2118             case AV_CODEC_ID_XAN_DPCM:
2119                 return (frame_bytes - 2 * ch) / ch;
2120             case AV_CODEC_ID_MACE3:
2121                 return 3 * frame_bytes / ch;
2122             case AV_CODEC_ID_MACE6:
2123                 return 6 * frame_bytes / ch;
2124             case AV_CODEC_ID_PCM_LXF:
2125                 return 2 * (frame_bytes / (5 * ch));
2126             }
2127
2128             if (tag) {
2129                 /* calc from frame_bytes, channels, and codec_tag */
2130                 if (id == AV_CODEC_ID_SOL_DPCM) {
2131                     if (tag == 3)
2132                         return frame_bytes / ch;
2133                     else
2134                         return frame_bytes * 2 / ch;
2135                 }
2136             }
2137
2138             if (ba > 0) {
2139                 /* calc from frame_bytes, channels, and block_align */
2140                 int blocks = frame_bytes / ba;
2141                 switch (avctx->codec_id) {
2142                 case AV_CODEC_ID_ADPCM_IMA_WAV:
2143                     return blocks * (1 + (ba - 4 * ch) / (4 * ch) * 8);
2144                 case AV_CODEC_ID_ADPCM_IMA_DK3:
2145                     return blocks * (((ba - 16) * 2 / 3 * 4) / ch);
2146                 case AV_CODEC_ID_ADPCM_IMA_DK4:
2147                     return blocks * (1 + (ba - 4 * ch) * 2 / ch);
2148                 case AV_CODEC_ID_ADPCM_MS:
2149                     return blocks * (2 + (ba - 7 * ch) * 2 / ch);
2150                 }
2151             }
2152
2153             if (bps > 0) {
2154                 /* calc from frame_bytes, channels, and bits_per_coded_sample */
2155                 switch (avctx->codec_id) {
2156                 case AV_CODEC_ID_PCM_DVD:
2157                     return 2 * (frame_bytes / ((bps * 2 / 8) * ch));
2158                 case AV_CODEC_ID_PCM_BLURAY:
2159                     return frame_bytes / ((FFALIGN(ch, 2) * bps) / 8);
2160                 case AV_CODEC_ID_S302M:
2161                     return 2 * (frame_bytes / ((bps + 4) / 4)) / ch;
2162                 }
2163             }
2164         }
2165     }
2166
2167     return 0;
2168 }
2169
2170 #if !HAVE_THREADS
2171 int ff_thread_init(AVCodecContext *s)
2172 {
2173     return -1;
2174 }
2175
2176 #endif
2177
2178 unsigned int av_xiphlacing(unsigned char *s, unsigned int v)
2179 {
2180     unsigned int n = 0;
2181
2182     while (v >= 0xff) {
2183         *s++ = 0xff;
2184         v -= 0xff;
2185         n++;
2186     }
2187     *s = v;
2188     n++;
2189     return n;
2190 }
2191
2192 int ff_match_2uint16(const uint16_t(*tab)[2], int size, int a, int b)
2193 {
2194     int i;
2195     for (i = 0; i < size && !(tab[i][0] == a && tab[i][1] == b); i++) ;
2196     return i;
2197 }
2198
2199 void av_log_missing_feature(void *avc, const char *feature, int want_sample)
2200 {
2201     av_log(avc, AV_LOG_WARNING, "%s is not implemented. Update your Libav "
2202             "version to the newest one from Git. If the problem still "
2203             "occurs, it means that your file has a feature which has not "
2204             "been implemented.\n", feature);
2205     if(want_sample)
2206         av_log_ask_for_sample(avc, NULL);
2207 }
2208
2209 void av_log_ask_for_sample(void *avc, const char *msg, ...)
2210 {
2211     va_list argument_list;
2212
2213     va_start(argument_list, msg);
2214
2215     if (msg)
2216         av_vlog(avc, AV_LOG_WARNING, msg, argument_list);
2217     av_log(avc, AV_LOG_WARNING, "If you want to help, upload a sample "
2218             "of this file to ftp://upload.libav.org/incoming/ "
2219             "and contact the libav-devel mailing list.\n");
2220
2221     va_end(argument_list);
2222 }
2223
2224 static AVHWAccel *first_hwaccel = NULL;
2225
2226 void av_register_hwaccel(AVHWAccel *hwaccel)
2227 {
2228     AVHWAccel **p = &first_hwaccel;
2229     while (*p)
2230         p = &(*p)->next;
2231     *p = hwaccel;
2232     hwaccel->next = NULL;
2233 }
2234
2235 AVHWAccel *av_hwaccel_next(AVHWAccel *hwaccel)
2236 {
2237     return hwaccel ? hwaccel->next : first_hwaccel;
2238 }
2239
2240 AVHWAccel *ff_find_hwaccel(enum AVCodecID codec_id, enum AVPixelFormat pix_fmt)
2241 {
2242     AVHWAccel *hwaccel = NULL;
2243
2244     while ((hwaccel = av_hwaccel_next(hwaccel)))
2245         if (hwaccel->id == codec_id
2246             && hwaccel->pix_fmt == pix_fmt)
2247             return hwaccel;
2248     return NULL;
2249 }
2250
2251 int av_lockmgr_register(int (*cb)(void **mutex, enum AVLockOp op))
2252 {
2253     if (ff_lockmgr_cb) {
2254         if (ff_lockmgr_cb(&codec_mutex, AV_LOCK_DESTROY))
2255             return -1;
2256         if (ff_lockmgr_cb(&avformat_mutex, AV_LOCK_DESTROY))
2257             return -1;
2258     }
2259
2260     ff_lockmgr_cb = cb;
2261
2262     if (ff_lockmgr_cb) {
2263         if (ff_lockmgr_cb(&codec_mutex, AV_LOCK_CREATE))
2264             return -1;
2265         if (ff_lockmgr_cb(&avformat_mutex, AV_LOCK_CREATE))
2266             return -1;
2267     }
2268     return 0;
2269 }
2270
2271 int avpriv_lock_avformat(void)
2272 {
2273     if (ff_lockmgr_cb) {
2274         if ((*ff_lockmgr_cb)(&avformat_mutex, AV_LOCK_OBTAIN))
2275             return -1;
2276     }
2277     return 0;
2278 }
2279
2280 int avpriv_unlock_avformat(void)
2281 {
2282     if (ff_lockmgr_cb) {
2283         if ((*ff_lockmgr_cb)(&avformat_mutex, AV_LOCK_RELEASE))
2284             return -1;
2285     }
2286     return 0;
2287 }
2288
2289 unsigned int avpriv_toupper4(unsigned int x)
2290 {
2291     return av_toupper(x & 0xFF) +
2292           (av_toupper((x >>  8) & 0xFF) << 8)  +
2293           (av_toupper((x >> 16) & 0xFF) << 16) +
2294           (av_toupper((x >> 24) & 0xFF) << 24);
2295 }
2296
2297 int ff_thread_ref_frame(ThreadFrame *dst, ThreadFrame *src)
2298 {
2299     int ret;
2300
2301     dst->owner = src->owner;
2302
2303     ret = av_frame_ref(dst->f, src->f);
2304     if (ret < 0)
2305         return ret;
2306
2307     if (src->progress &&
2308         !(dst->progress = av_buffer_ref(src->progress))) {
2309         ff_thread_release_buffer(dst->owner, dst);
2310         return AVERROR(ENOMEM);
2311     }
2312
2313     return 0;
2314 }
2315
2316 #if !HAVE_THREADS
2317
2318 int ff_thread_get_buffer(AVCodecContext *avctx, ThreadFrame *f, int flags)
2319 {
2320     f->owner = avctx;
2321     return ff_get_buffer(avctx, f->f, flags);
2322 }
2323
2324 void ff_thread_release_buffer(AVCodecContext *avctx, ThreadFrame *f)
2325 {
2326     av_frame_unref(f->f);
2327 }
2328
2329 void ff_thread_finish_setup(AVCodecContext *avctx)
2330 {
2331 }
2332
2333 void ff_thread_report_progress(ThreadFrame *f, int progress, int field)
2334 {
2335 }
2336
2337 void ff_thread_await_progress(ThreadFrame *f, int progress, int field)
2338 {
2339 }
2340
2341 #endif
2342
2343 enum AVMediaType avcodec_get_type(enum AVCodecID codec_id)
2344 {
2345     if (codec_id <= AV_CODEC_ID_NONE)
2346         return AVMEDIA_TYPE_UNKNOWN;
2347     else if (codec_id < AV_CODEC_ID_FIRST_AUDIO)
2348         return AVMEDIA_TYPE_VIDEO;
2349     else if (codec_id < AV_CODEC_ID_FIRST_SUBTITLE)
2350         return AVMEDIA_TYPE_AUDIO;
2351     else if (codec_id < AV_CODEC_ID_FIRST_UNKNOWN)
2352         return AVMEDIA_TYPE_SUBTITLE;
2353
2354     return AVMEDIA_TYPE_UNKNOWN;
2355 }
2356
2357 int avcodec_is_open(AVCodecContext *s)
2358 {
2359     return !!s->internal;
2360 }