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