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