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