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