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