]> git.sesse.net Git - ffmpeg/blob - libavcodec/utils.c
1e0026d255852f56e0a1688ab156a61928ae134d
[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         avcodec_set_dimensions(avctx, avctx->coded_width, avctx->coded_height);
938     else if (avctx->width && avctx->height)
939         avcodec_set_dimensions(avctx, avctx->width, avctx->height);
940
941     if ((avctx->coded_width || avctx->coded_height || avctx->width || avctx->height)
942         && (  av_image_check_size(avctx->coded_width, avctx->coded_height, 0, avctx) < 0
943            || av_image_check_size(avctx->width,       avctx->height,       0, avctx) < 0)) {
944         av_log(avctx, AV_LOG_WARNING, "ignoring invalid width/height values\n");
945         avcodec_set_dimensions(avctx, 0, 0);
946     }
947
948     /* if the decoder init function was already called previously,
949      * free the already allocated subtitle_header before overwriting it */
950     if (av_codec_is_decoder(codec))
951         av_freep(&avctx->subtitle_header);
952
953     if (avctx->channels > FF_SANE_NB_CHANNELS) {
954         ret = AVERROR(EINVAL);
955         goto free_and_end;
956     }
957
958     avctx->codec = codec;
959     if ((avctx->codec_type == AVMEDIA_TYPE_UNKNOWN || avctx->codec_type == codec->type) &&
960         avctx->codec_id == AV_CODEC_ID_NONE) {
961         avctx->codec_type = codec->type;
962         avctx->codec_id   = codec->id;
963     }
964     if (avctx->codec_id != codec->id || (avctx->codec_type != codec->type
965                                          && avctx->codec_type != AVMEDIA_TYPE_ATTACHMENT)) {
966         av_log(avctx, AV_LOG_ERROR, "codec type or id mismatches\n");
967         ret = AVERROR(EINVAL);
968         goto free_and_end;
969     }
970     avctx->frame_number = 0;
971
972     if (avctx->codec->capabilities & CODEC_CAP_EXPERIMENTAL &&
973         avctx->strict_std_compliance > FF_COMPLIANCE_EXPERIMENTAL) {
974         ret = AVERROR_EXPERIMENTAL;
975         goto free_and_end;
976     }
977
978     if (avctx->codec_type == AVMEDIA_TYPE_AUDIO &&
979         (!avctx->time_base.num || !avctx->time_base.den)) {
980         avctx->time_base.num = 1;
981         avctx->time_base.den = avctx->sample_rate;
982     }
983
984     if (HAVE_THREADS) {
985         ret = ff_thread_init(avctx);
986         if (ret < 0) {
987             goto free_and_end;
988         }
989     }
990     if (!HAVE_THREADS && !(codec->capabilities & CODEC_CAP_AUTO_THREADS))
991         avctx->thread_count = 1;
992
993     if (av_codec_is_encoder(avctx->codec)) {
994         int i;
995         if (avctx->codec->sample_fmts) {
996             for (i = 0; avctx->codec->sample_fmts[i] != AV_SAMPLE_FMT_NONE; i++) {
997                 if (avctx->sample_fmt == avctx->codec->sample_fmts[i])
998                     break;
999                 if (avctx->channels == 1 &&
1000                     av_get_planar_sample_fmt(avctx->sample_fmt) ==
1001                     av_get_planar_sample_fmt(avctx->codec->sample_fmts[i])) {
1002                     avctx->sample_fmt = avctx->codec->sample_fmts[i];
1003                     break;
1004                 }
1005             }
1006             if (avctx->codec->sample_fmts[i] == AV_SAMPLE_FMT_NONE) {
1007                 av_log(avctx, AV_LOG_ERROR, "Specified sample_fmt is not supported.\n");
1008                 ret = AVERROR(EINVAL);
1009                 goto free_and_end;
1010             }
1011         }
1012         if (avctx->codec->pix_fmts) {
1013             for (i = 0; avctx->codec->pix_fmts[i] != AV_PIX_FMT_NONE; i++)
1014                 if (avctx->pix_fmt == avctx->codec->pix_fmts[i])
1015                     break;
1016             if (avctx->codec->pix_fmts[i] == AV_PIX_FMT_NONE) {
1017                 av_log(avctx, AV_LOG_ERROR, "Specified pix_fmt is not supported\n");
1018                 ret = AVERROR(EINVAL);
1019                 goto free_and_end;
1020             }
1021         }
1022         if (avctx->codec->supported_samplerates) {
1023             for (i = 0; avctx->codec->supported_samplerates[i] != 0; i++)
1024                 if (avctx->sample_rate == avctx->codec->supported_samplerates[i])
1025                     break;
1026             if (avctx->codec->supported_samplerates[i] == 0) {
1027                 av_log(avctx, AV_LOG_ERROR, "Specified sample_rate is not supported\n");
1028                 ret = AVERROR(EINVAL);
1029                 goto free_and_end;
1030             }
1031         }
1032         if (avctx->codec->channel_layouts) {
1033             if (!avctx->channel_layout) {
1034                 av_log(avctx, AV_LOG_WARNING, "channel_layout not specified\n");
1035             } else {
1036                 for (i = 0; avctx->codec->channel_layouts[i] != 0; i++)
1037                     if (avctx->channel_layout == avctx->codec->channel_layouts[i])
1038                         break;
1039                 if (avctx->codec->channel_layouts[i] == 0) {
1040                     av_log(avctx, AV_LOG_ERROR, "Specified channel_layout is not supported\n");
1041                     ret = AVERROR(EINVAL);
1042                     goto free_and_end;
1043                 }
1044             }
1045         }
1046         if (avctx->channel_layout && avctx->channels) {
1047             if (av_get_channel_layout_nb_channels(avctx->channel_layout) != avctx->channels) {
1048                 av_log(avctx, AV_LOG_ERROR, "channel layout does not match number of channels\n");
1049                 ret = AVERROR(EINVAL);
1050                 goto free_and_end;
1051             }
1052         } else if (avctx->channel_layout) {
1053             avctx->channels = av_get_channel_layout_nb_channels(avctx->channel_layout);
1054         }
1055
1056         if (!avctx->rc_initial_buffer_occupancy)
1057             avctx->rc_initial_buffer_occupancy = avctx->rc_buffer_size * 3 / 4;
1058     }
1059
1060     if (avctx->codec->init && !(avctx->active_thread_type & FF_THREAD_FRAME)) {
1061         ret = avctx->codec->init(avctx);
1062         if (ret < 0) {
1063             goto free_and_end;
1064         }
1065     }
1066
1067     if (av_codec_is_decoder(avctx->codec)) {
1068         /* validate channel layout from the decoder */
1069         if (avctx->channel_layout) {
1070             int channels = av_get_channel_layout_nb_channels(avctx->channel_layout);
1071             if (!avctx->channels)
1072                 avctx->channels = channels;
1073             else if (channels != avctx->channels) {
1074                 av_log(avctx, AV_LOG_WARNING,
1075                        "channel layout does not match number of channels\n");
1076                 avctx->channel_layout = 0;
1077             }
1078         }
1079         if (avctx->channels && avctx->channels < 0 ||
1080             avctx->channels > FF_SANE_NB_CHANNELS) {
1081             ret = AVERROR(EINVAL);
1082             goto free_and_end;
1083         }
1084     }
1085 end:
1086     entangled_thread_counter--;
1087
1088     /* Release any user-supplied mutex. */
1089     if (lockmgr_cb) {
1090         (*lockmgr_cb)(&codec_mutex, AV_LOCK_RELEASE);
1091     }
1092     if (options) {
1093         av_dict_free(options);
1094         *options = tmp;
1095     }
1096
1097     return ret;
1098 free_and_end:
1099     av_dict_free(&tmp);
1100     av_freep(&avctx->priv_data);
1101     if (avctx->internal)
1102         av_freep(&avctx->internal->pool);
1103     av_freep(&avctx->internal);
1104     avctx->codec = NULL;
1105     goto end;
1106 }
1107
1108 int ff_alloc_packet(AVPacket *avpkt, int size)
1109 {
1110     if (size > INT_MAX - FF_INPUT_BUFFER_PADDING_SIZE)
1111         return AVERROR(EINVAL);
1112
1113     if (avpkt->data) {
1114         AVBufferRef *buf = avpkt->buf;
1115 #if FF_API_DESTRUCT_PACKET
1116 FF_DISABLE_DEPRECATION_WARNINGS
1117         void *destruct = avpkt->destruct;
1118 FF_ENABLE_DEPRECATION_WARNINGS
1119 #endif
1120
1121         if (avpkt->size < size)
1122             return AVERROR(EINVAL);
1123
1124         av_init_packet(avpkt);
1125 #if FF_API_DESTRUCT_PACKET
1126 FF_DISABLE_DEPRECATION_WARNINGS
1127         avpkt->destruct = destruct;
1128 FF_ENABLE_DEPRECATION_WARNINGS
1129 #endif
1130         avpkt->buf      = buf;
1131         avpkt->size     = size;
1132         return 0;
1133     } else {
1134         return av_new_packet(avpkt, size);
1135     }
1136 }
1137
1138 /**
1139  * Pad last frame with silence.
1140  */
1141 static int pad_last_frame(AVCodecContext *s, AVFrame **dst, const AVFrame *src)
1142 {
1143     AVFrame *frame = NULL;
1144     int ret;
1145
1146     if (!(frame = avcodec_alloc_frame()))
1147         return AVERROR(ENOMEM);
1148
1149     frame->format         = src->format;
1150     frame->channel_layout = src->channel_layout;
1151     frame->nb_samples     = s->frame_size;
1152     ret = av_frame_get_buffer(frame, 32);
1153     if (ret < 0)
1154         goto fail;
1155
1156     ret = av_frame_copy_props(frame, src);
1157     if (ret < 0)
1158         goto fail;
1159
1160     if ((ret = av_samples_copy(frame->extended_data, src->extended_data, 0, 0,
1161                                src->nb_samples, s->channels, s->sample_fmt)) < 0)
1162         goto fail;
1163     if ((ret = av_samples_set_silence(frame->extended_data, src->nb_samples,
1164                                       frame->nb_samples - src->nb_samples,
1165                                       s->channels, s->sample_fmt)) < 0)
1166         goto fail;
1167
1168     *dst = frame;
1169
1170     return 0;
1171
1172 fail:
1173     av_frame_free(&frame);
1174     return ret;
1175 }
1176
1177 int attribute_align_arg avcodec_encode_audio2(AVCodecContext *avctx,
1178                                               AVPacket *avpkt,
1179                                               const AVFrame *frame,
1180                                               int *got_packet_ptr)
1181 {
1182     AVFrame tmp;
1183     AVFrame *padded_frame = NULL;
1184     int ret;
1185     int user_packet = !!avpkt->data;
1186
1187     *got_packet_ptr = 0;
1188
1189     if (!(avctx->codec->capabilities & CODEC_CAP_DELAY) && !frame) {
1190         av_free_packet(avpkt);
1191         av_init_packet(avpkt);
1192         return 0;
1193     }
1194
1195     /* ensure that extended_data is properly set */
1196     if (frame && !frame->extended_data) {
1197         if (av_sample_fmt_is_planar(avctx->sample_fmt) &&
1198             avctx->channels > AV_NUM_DATA_POINTERS) {
1199             av_log(avctx, AV_LOG_ERROR, "Encoding to a planar sample format, "
1200                                         "with more than %d channels, but extended_data is not set.\n",
1201                    AV_NUM_DATA_POINTERS);
1202             return AVERROR(EINVAL);
1203         }
1204         av_log(avctx, AV_LOG_WARNING, "extended_data is not set.\n");
1205
1206         tmp = *frame;
1207         tmp.extended_data = tmp.data;
1208         frame = &tmp;
1209     }
1210
1211     /* check for valid frame size */
1212     if (frame) {
1213         if (avctx->codec->capabilities & CODEC_CAP_SMALL_LAST_FRAME) {
1214             if (frame->nb_samples > avctx->frame_size)
1215                 return AVERROR(EINVAL);
1216         } else if (!(avctx->codec->capabilities & CODEC_CAP_VARIABLE_FRAME_SIZE)) {
1217             if (frame->nb_samples < avctx->frame_size &&
1218                 !avctx->internal->last_audio_frame) {
1219                 ret = pad_last_frame(avctx, &padded_frame, frame);
1220                 if (ret < 0)
1221                     return ret;
1222
1223                 frame = padded_frame;
1224                 avctx->internal->last_audio_frame = 1;
1225             }
1226
1227             if (frame->nb_samples != avctx->frame_size) {
1228                 ret = AVERROR(EINVAL);
1229                 goto end;
1230             }
1231         }
1232     }
1233
1234     ret = avctx->codec->encode2(avctx, avpkt, frame, got_packet_ptr);
1235     if (!ret) {
1236         if (*got_packet_ptr) {
1237             if (!(avctx->codec->capabilities & CODEC_CAP_DELAY)) {
1238                 if (avpkt->pts == AV_NOPTS_VALUE)
1239                     avpkt->pts = frame->pts;
1240                 if (!avpkt->duration)
1241                     avpkt->duration = ff_samples_to_time_base(avctx,
1242                                                               frame->nb_samples);
1243             }
1244             avpkt->dts = avpkt->pts;
1245         } else {
1246             avpkt->size = 0;
1247         }
1248
1249         if (!user_packet && avpkt->size) {
1250             ret = av_buffer_realloc(&avpkt->buf, avpkt->size);
1251             if (ret >= 0)
1252                 avpkt->data = avpkt->buf->data;
1253         }
1254
1255         avctx->frame_number++;
1256     }
1257
1258     if (ret < 0 || !*got_packet_ptr) {
1259         av_free_packet(avpkt);
1260         av_init_packet(avpkt);
1261         goto end;
1262     }
1263
1264     /* NOTE: if we add any audio encoders which output non-keyframe packets,
1265      *       this needs to be moved to the encoders, but for now we can do it
1266      *       here to simplify things */
1267     avpkt->flags |= AV_PKT_FLAG_KEY;
1268
1269 end:
1270     av_frame_free(&padded_frame);
1271
1272     return ret;
1273 }
1274
1275 int attribute_align_arg avcodec_encode_video2(AVCodecContext *avctx,
1276                                               AVPacket *avpkt,
1277                                               const AVFrame *frame,
1278                                               int *got_packet_ptr)
1279 {
1280     int ret;
1281     int user_packet = !!avpkt->data;
1282
1283     *got_packet_ptr = 0;
1284
1285     if (!(avctx->codec->capabilities & CODEC_CAP_DELAY) && !frame) {
1286         av_free_packet(avpkt);
1287         av_init_packet(avpkt);
1288         avpkt->size = 0;
1289         return 0;
1290     }
1291
1292     if (av_image_check_size(avctx->width, avctx->height, 0, avctx))
1293         return AVERROR(EINVAL);
1294
1295     av_assert0(avctx->codec->encode2);
1296
1297     ret = avctx->codec->encode2(avctx, avpkt, frame, got_packet_ptr);
1298     if (!ret) {
1299         if (!*got_packet_ptr)
1300             avpkt->size = 0;
1301         else if (!(avctx->codec->capabilities & CODEC_CAP_DELAY))
1302             avpkt->pts = avpkt->dts = frame->pts;
1303
1304         if (!user_packet && avpkt->size) {
1305             ret = av_buffer_realloc(&avpkt->buf, avpkt->size);
1306             if (ret >= 0)
1307                 avpkt->data = avpkt->buf->data;
1308         }
1309
1310         avctx->frame_number++;
1311     }
1312
1313     if (ret < 0 || !*got_packet_ptr)
1314         av_free_packet(avpkt);
1315
1316     emms_c();
1317     return ret;
1318 }
1319
1320 int avcodec_encode_subtitle(AVCodecContext *avctx, uint8_t *buf, int buf_size,
1321                             const AVSubtitle *sub)
1322 {
1323     int ret;
1324     if (sub->start_display_time) {
1325         av_log(avctx, AV_LOG_ERROR, "start_display_time must be 0.\n");
1326         return -1;
1327     }
1328     if (sub->num_rects == 0 || !sub->rects)
1329         return -1;
1330     ret = avctx->codec->encode_sub(avctx, buf, buf_size, sub);
1331     avctx->frame_number++;
1332     return ret;
1333 }
1334
1335 static int apply_param_change(AVCodecContext *avctx, AVPacket *avpkt)
1336 {
1337     int size = 0;
1338     const uint8_t *data;
1339     uint32_t flags;
1340
1341     data = av_packet_get_side_data(avpkt, AV_PKT_DATA_PARAM_CHANGE, &size);
1342     if (!data)
1343         return 0;
1344
1345     if (!(avctx->codec->capabilities & CODEC_CAP_PARAM_CHANGE)) {
1346         av_log(avctx, AV_LOG_ERROR, "This decoder does not support parameter "
1347                "changes, but PARAM_CHANGE side data was sent to it.\n");
1348         return AVERROR(EINVAL);
1349     }
1350
1351     if (size < 4)
1352         goto fail;
1353
1354     flags = bytestream_get_le32(&data);
1355     size -= 4;
1356
1357     if (flags & AV_SIDE_DATA_PARAM_CHANGE_CHANNEL_COUNT) {
1358         if (size < 4)
1359             goto fail;
1360         avctx->channels = bytestream_get_le32(&data);
1361         size -= 4;
1362     }
1363     if (flags & AV_SIDE_DATA_PARAM_CHANGE_CHANNEL_LAYOUT) {
1364         if (size < 8)
1365             goto fail;
1366         avctx->channel_layout = bytestream_get_le64(&data);
1367         size -= 8;
1368     }
1369     if (flags & AV_SIDE_DATA_PARAM_CHANGE_SAMPLE_RATE) {
1370         if (size < 4)
1371             goto fail;
1372         avctx->sample_rate = bytestream_get_le32(&data);
1373         size -= 4;
1374     }
1375     if (flags & AV_SIDE_DATA_PARAM_CHANGE_DIMENSIONS) {
1376         if (size < 8)
1377             goto fail;
1378         avctx->width  = bytestream_get_le32(&data);
1379         avctx->height = bytestream_get_le32(&data);
1380         avcodec_set_dimensions(avctx, avctx->width, avctx->height);
1381         size -= 8;
1382     }
1383
1384     return 0;
1385 fail:
1386     av_log(avctx, AV_LOG_ERROR, "PARAM_CHANGE side data too small.\n");
1387     return AVERROR_INVALIDDATA;
1388 }
1389
1390 int attribute_align_arg avcodec_decode_video2(AVCodecContext *avctx, AVFrame *picture,
1391                                               int *got_picture_ptr,
1392                                               AVPacket *avpkt)
1393 {
1394     AVCodecInternal *avci = avctx->internal;
1395     int ret;
1396
1397     *got_picture_ptr = 0;
1398     if ((avctx->coded_width || avctx->coded_height) && av_image_check_size(avctx->coded_width, avctx->coded_height, 0, avctx))
1399         return -1;
1400
1401     avctx->pkt = avpkt;
1402     ret = apply_param_change(avctx, avpkt);
1403     if (ret < 0) {
1404         av_log(avctx, AV_LOG_ERROR, "Error applying parameter changes.\n");
1405         if (avctx->err_recognition & AV_EF_EXPLODE)
1406             return ret;
1407     }
1408
1409     avcodec_get_frame_defaults(picture);
1410
1411     if (!avctx->refcounted_frames)
1412         av_frame_unref(&avci->to_free);
1413
1414     if ((avctx->codec->capabilities & CODEC_CAP_DELAY) || avpkt->size || (avctx->active_thread_type & FF_THREAD_FRAME)) {
1415         if (HAVE_THREADS && avctx->active_thread_type & FF_THREAD_FRAME)
1416             ret = ff_thread_decode_frame(avctx, picture, got_picture_ptr,
1417                                          avpkt);
1418         else {
1419             ret = avctx->codec->decode(avctx, picture, got_picture_ptr,
1420                                        avpkt);
1421             picture->pkt_dts = avpkt->dts;
1422             /* get_buffer is supposed to set frame parameters */
1423             if (!(avctx->codec->capabilities & CODEC_CAP_DR1)) {
1424                 picture->sample_aspect_ratio = avctx->sample_aspect_ratio;
1425                 picture->width               = avctx->width;
1426                 picture->height              = avctx->height;
1427                 picture->format              = avctx->pix_fmt;
1428             }
1429         }
1430
1431         emms_c(); //needed to avoid an emms_c() call before every return;
1432
1433         if (ret < 0 && picture->data[0])
1434             av_frame_unref(picture);
1435
1436         if (*got_picture_ptr) {
1437             if (!avctx->refcounted_frames) {
1438                 avci->to_free = *picture;
1439                 avci->to_free.extended_data = avci->to_free.data;
1440                 memset(picture->buf, 0, sizeof(picture->buf));
1441             }
1442
1443             avctx->frame_number++;
1444         }
1445     } else
1446         ret = 0;
1447
1448     /* many decoders assign whole AVFrames, thus overwriting extended_data;
1449      * make sure it's set correctly */
1450     picture->extended_data = picture->data;
1451
1452     return ret;
1453 }
1454
1455 int attribute_align_arg avcodec_decode_audio4(AVCodecContext *avctx,
1456                                               AVFrame *frame,
1457                                               int *got_frame_ptr,
1458                                               AVPacket *avpkt)
1459 {
1460     AVCodecInternal *avci = avctx->internal;
1461     int planar, channels;
1462     int ret = 0;
1463
1464     *got_frame_ptr = 0;
1465
1466     avctx->pkt = avpkt;
1467
1468     if (!avpkt->data && avpkt->size) {
1469         av_log(avctx, AV_LOG_ERROR, "invalid packet: NULL data, size != 0\n");
1470         return AVERROR(EINVAL);
1471     }
1472
1473     ret = apply_param_change(avctx, avpkt);
1474     if (ret < 0) {
1475         av_log(avctx, AV_LOG_ERROR, "Error applying parameter changes.\n");
1476         if (avctx->err_recognition & AV_EF_EXPLODE)
1477             return ret;
1478     }
1479
1480     avcodec_get_frame_defaults(frame);
1481
1482     if (!avctx->refcounted_frames)
1483         av_frame_unref(&avci->to_free);
1484
1485     if ((avctx->codec->capabilities & CODEC_CAP_DELAY) || avpkt->size) {
1486         ret = avctx->codec->decode(avctx, frame, got_frame_ptr, avpkt);
1487         if (ret >= 0 && *got_frame_ptr) {
1488             avctx->frame_number++;
1489             frame->pkt_dts = avpkt->dts;
1490             if (frame->format == AV_SAMPLE_FMT_NONE)
1491                 frame->format = avctx->sample_fmt;
1492
1493             if (!avctx->refcounted_frames) {
1494                 avci->to_free = *frame;
1495                 avci->to_free.extended_data = avci->to_free.data;
1496                 memset(frame->buf, 0, sizeof(frame->buf));
1497                 frame->extended_buf    = NULL;
1498                 frame->nb_extended_buf = 0;
1499             }
1500         } else if (frame->data[0])
1501             av_frame_unref(frame);
1502     }
1503
1504     /* many decoders assign whole AVFrames, thus overwriting extended_data;
1505      * make sure it's set correctly; assume decoders that actually use
1506      * extended_data are doing it correctly */
1507     planar   = av_sample_fmt_is_planar(frame->format);
1508     channels = av_get_channel_layout_nb_channels(frame->channel_layout);
1509     if (!(planar && channels > AV_NUM_DATA_POINTERS))
1510         frame->extended_data = frame->data;
1511
1512     return ret;
1513 }
1514
1515 int avcodec_decode_subtitle2(AVCodecContext *avctx, AVSubtitle *sub,
1516                              int *got_sub_ptr,
1517                              AVPacket *avpkt)
1518 {
1519     int ret;
1520
1521     avctx->pkt = avpkt;
1522     *got_sub_ptr = 0;
1523     ret = avctx->codec->decode(avctx, sub, got_sub_ptr, avpkt);
1524     if (*got_sub_ptr)
1525         avctx->frame_number++;
1526     return ret;
1527 }
1528
1529 void avsubtitle_free(AVSubtitle *sub)
1530 {
1531     int i;
1532
1533     for (i = 0; i < sub->num_rects; i++) {
1534         av_freep(&sub->rects[i]->pict.data[0]);
1535         av_freep(&sub->rects[i]->pict.data[1]);
1536         av_freep(&sub->rects[i]->pict.data[2]);
1537         av_freep(&sub->rects[i]->pict.data[3]);
1538         av_freep(&sub->rects[i]->text);
1539         av_freep(&sub->rects[i]->ass);
1540         av_freep(&sub->rects[i]);
1541     }
1542
1543     av_freep(&sub->rects);
1544
1545     memset(sub, 0, sizeof(AVSubtitle));
1546 }
1547
1548 av_cold int avcodec_close(AVCodecContext *avctx)
1549 {
1550     /* If there is a user-supplied mutex locking routine, call it. */
1551     if (lockmgr_cb) {
1552         if ((*lockmgr_cb)(&codec_mutex, AV_LOCK_OBTAIN))
1553             return -1;
1554     }
1555
1556     entangled_thread_counter++;
1557     if (entangled_thread_counter != 1) {
1558         av_log(avctx, AV_LOG_ERROR, "insufficient thread locking around avcodec_open/close()\n");
1559         entangled_thread_counter--;
1560         return -1;
1561     }
1562
1563     if (avcodec_is_open(avctx)) {
1564         FramePool *pool = avctx->internal->pool;
1565         int i;
1566         if (HAVE_THREADS && avctx->thread_opaque)
1567             ff_thread_free(avctx);
1568         if (avctx->codec && avctx->codec->close)
1569             avctx->codec->close(avctx);
1570         avctx->coded_frame = NULL;
1571         if (!avctx->refcounted_frames)
1572             av_frame_unref(&avctx->internal->to_free);
1573         for (i = 0; i < FF_ARRAY_ELEMS(pool->pools); i++)
1574             av_buffer_pool_uninit(&pool->pools[i]);
1575         av_freep(&avctx->internal->pool);
1576         av_freep(&avctx->internal);
1577     }
1578
1579     if (avctx->priv_data && avctx->codec && avctx->codec->priv_class)
1580         av_opt_free(avctx->priv_data);
1581     av_opt_free(avctx);
1582     av_freep(&avctx->priv_data);
1583     if (av_codec_is_encoder(avctx->codec))
1584         av_freep(&avctx->extradata);
1585     avctx->codec = NULL;
1586     avctx->active_thread_type = 0;
1587     entangled_thread_counter--;
1588
1589     /* Release any user-supplied mutex. */
1590     if (lockmgr_cb) {
1591         (*lockmgr_cb)(&codec_mutex, AV_LOCK_RELEASE);
1592     }
1593     return 0;
1594 }
1595
1596 static AVCodec *find_encdec(enum AVCodecID id, int encoder)
1597 {
1598     AVCodec *p, *experimental = NULL;
1599     p = first_avcodec;
1600     while (p) {
1601         if ((encoder ? av_codec_is_encoder(p) : av_codec_is_decoder(p)) &&
1602             p->id == id) {
1603             if (p->capabilities & CODEC_CAP_EXPERIMENTAL && !experimental) {
1604                 experimental = p;
1605             } else
1606                 return p;
1607         }
1608         p = p->next;
1609     }
1610     return experimental;
1611 }
1612
1613 AVCodec *avcodec_find_encoder(enum AVCodecID id)
1614 {
1615     return find_encdec(id, 1);
1616 }
1617
1618 AVCodec *avcodec_find_encoder_by_name(const char *name)
1619 {
1620     AVCodec *p;
1621     if (!name)
1622         return NULL;
1623     p = first_avcodec;
1624     while (p) {
1625         if (av_codec_is_encoder(p) && strcmp(name, p->name) == 0)
1626             return p;
1627         p = p->next;
1628     }
1629     return NULL;
1630 }
1631
1632 AVCodec *avcodec_find_decoder(enum AVCodecID id)
1633 {
1634     return find_encdec(id, 0);
1635 }
1636
1637 AVCodec *avcodec_find_decoder_by_name(const char *name)
1638 {
1639     AVCodec *p;
1640     if (!name)
1641         return NULL;
1642     p = first_avcodec;
1643     while (p) {
1644         if (av_codec_is_decoder(p) && strcmp(name, p->name) == 0)
1645             return p;
1646         p = p->next;
1647     }
1648     return NULL;
1649 }
1650
1651 static int get_bit_rate(AVCodecContext *ctx)
1652 {
1653     int bit_rate;
1654     int bits_per_sample;
1655
1656     switch (ctx->codec_type) {
1657     case AVMEDIA_TYPE_VIDEO:
1658     case AVMEDIA_TYPE_DATA:
1659     case AVMEDIA_TYPE_SUBTITLE:
1660     case AVMEDIA_TYPE_ATTACHMENT:
1661         bit_rate = ctx->bit_rate;
1662         break;
1663     case AVMEDIA_TYPE_AUDIO:
1664         bits_per_sample = av_get_bits_per_sample(ctx->codec_id);
1665         bit_rate = bits_per_sample ? ctx->sample_rate * ctx->channels * bits_per_sample : ctx->bit_rate;
1666         break;
1667     default:
1668         bit_rate = 0;
1669         break;
1670     }
1671     return bit_rate;
1672 }
1673
1674 size_t av_get_codec_tag_string(char *buf, size_t buf_size, unsigned int codec_tag)
1675 {
1676     int i, len, ret = 0;
1677
1678 #define TAG_PRINT(x)                                              \
1679     (((x) >= '0' && (x) <= '9') ||                                \
1680      ((x) >= 'a' && (x) <= 'z') || ((x) >= 'A' && (x) <= 'Z') ||  \
1681      ((x) == '.' || (x) == ' '))
1682
1683     for (i = 0; i < 4; i++) {
1684         len = snprintf(buf, buf_size,
1685                        TAG_PRINT(codec_tag & 0xFF) ? "%c" : "[%d]", codec_tag & 0xFF);
1686         buf        += len;
1687         buf_size    = buf_size > len ? buf_size - len : 0;
1688         ret        += len;
1689         codec_tag >>= 8;
1690     }
1691     return ret;
1692 }
1693
1694 void avcodec_string(char *buf, int buf_size, AVCodecContext *enc, int encode)
1695 {
1696     const char *codec_name;
1697     const char *profile = NULL;
1698     const AVCodec *p;
1699     char buf1[32];
1700     int bitrate;
1701     AVRational display_aspect_ratio;
1702
1703     if (enc->codec)
1704         p = enc->codec;
1705     else if (encode)
1706         p = avcodec_find_encoder(enc->codec_id);
1707     else
1708         p = avcodec_find_decoder(enc->codec_id);
1709
1710     if (p) {
1711         codec_name = p->name;
1712         profile = av_get_profile_name(p, enc->profile);
1713     } else if (enc->codec_id == AV_CODEC_ID_MPEG2TS) {
1714         /* fake mpeg2 transport stream codec (currently not
1715          * registered) */
1716         codec_name = "mpeg2ts";
1717     } else if (enc->codec_name[0] != '\0') {
1718         codec_name = enc->codec_name;
1719     } else {
1720         /* output avi tags */
1721         char tag_buf[32];
1722         av_get_codec_tag_string(tag_buf, sizeof(tag_buf), enc->codec_tag);
1723         snprintf(buf1, sizeof(buf1), "%s / 0x%04X", tag_buf, enc->codec_tag);
1724         codec_name = buf1;
1725     }
1726
1727     switch (enc->codec_type) {
1728     case AVMEDIA_TYPE_VIDEO:
1729         snprintf(buf, buf_size,
1730                  "Video: %s%s",
1731                  codec_name, enc->mb_decision ? " (hq)" : "");
1732         if (profile)
1733             snprintf(buf + strlen(buf), buf_size - strlen(buf),
1734                      " (%s)", profile);
1735         if (enc->pix_fmt != AV_PIX_FMT_NONE) {
1736             snprintf(buf + strlen(buf), buf_size - strlen(buf),
1737                      ", %s",
1738                      av_get_pix_fmt_name(enc->pix_fmt));
1739         }
1740         if (enc->width) {
1741             snprintf(buf + strlen(buf), buf_size - strlen(buf),
1742                      ", %dx%d",
1743                      enc->width, enc->height);
1744             if (enc->sample_aspect_ratio.num) {
1745                 av_reduce(&display_aspect_ratio.num, &display_aspect_ratio.den,
1746                           enc->width * enc->sample_aspect_ratio.num,
1747                           enc->height * enc->sample_aspect_ratio.den,
1748                           1024 * 1024);
1749                 snprintf(buf + strlen(buf), buf_size - strlen(buf),
1750                          " [PAR %d:%d DAR %d:%d]",
1751                          enc->sample_aspect_ratio.num, enc->sample_aspect_ratio.den,
1752                          display_aspect_ratio.num, display_aspect_ratio.den);
1753             }
1754             if (av_log_get_level() >= AV_LOG_DEBUG) {
1755                 int g = av_gcd(enc->time_base.num, enc->time_base.den);
1756                 snprintf(buf + strlen(buf), buf_size - strlen(buf),
1757                          ", %d/%d",
1758                          enc->time_base.num / g, enc->time_base.den / g);
1759             }
1760         }
1761         if (encode) {
1762             snprintf(buf + strlen(buf), buf_size - strlen(buf),
1763                      ", q=%d-%d", enc->qmin, enc->qmax);
1764         }
1765         break;
1766     case AVMEDIA_TYPE_AUDIO:
1767         snprintf(buf, buf_size,
1768                  "Audio: %s",
1769                  codec_name);
1770         if (profile)
1771             snprintf(buf + strlen(buf), buf_size - strlen(buf),
1772                      " (%s)", profile);
1773         if (enc->sample_rate) {
1774             snprintf(buf + strlen(buf), buf_size - strlen(buf),
1775                      ", %d Hz", enc->sample_rate);
1776         }
1777         av_strlcat(buf, ", ", buf_size);
1778         av_get_channel_layout_string(buf + strlen(buf), buf_size - strlen(buf), enc->channels, enc->channel_layout);
1779         if (enc->sample_fmt != AV_SAMPLE_FMT_NONE) {
1780             snprintf(buf + strlen(buf), buf_size - strlen(buf),
1781                      ", %s", av_get_sample_fmt_name(enc->sample_fmt));
1782         }
1783         break;
1784     case AVMEDIA_TYPE_DATA:
1785         snprintf(buf, buf_size, "Data: %s", codec_name);
1786         break;
1787     case AVMEDIA_TYPE_SUBTITLE:
1788         snprintf(buf, buf_size, "Subtitle: %s", codec_name);
1789         break;
1790     case AVMEDIA_TYPE_ATTACHMENT:
1791         snprintf(buf, buf_size, "Attachment: %s", codec_name);
1792         break;
1793     default:
1794         snprintf(buf, buf_size, "Invalid Codec type %d", enc->codec_type);
1795         return;
1796     }
1797     if (encode) {
1798         if (enc->flags & CODEC_FLAG_PASS1)
1799             snprintf(buf + strlen(buf), buf_size - strlen(buf),
1800                      ", pass 1");
1801         if (enc->flags & CODEC_FLAG_PASS2)
1802             snprintf(buf + strlen(buf), buf_size - strlen(buf),
1803                      ", pass 2");
1804     }
1805     bitrate = get_bit_rate(enc);
1806     if (bitrate != 0) {
1807         snprintf(buf + strlen(buf), buf_size - strlen(buf),
1808                  ", %d kb/s", bitrate / 1000);
1809     }
1810 }
1811
1812 const char *av_get_profile_name(const AVCodec *codec, int profile)
1813 {
1814     const AVProfile *p;
1815     if (profile == FF_PROFILE_UNKNOWN || !codec->profiles)
1816         return NULL;
1817
1818     for (p = codec->profiles; p->profile != FF_PROFILE_UNKNOWN; p++)
1819         if (p->profile == profile)
1820             return p->name;
1821
1822     return NULL;
1823 }
1824
1825 unsigned avcodec_version(void)
1826 {
1827     return LIBAVCODEC_VERSION_INT;
1828 }
1829
1830 const char *avcodec_configuration(void)
1831 {
1832     return LIBAV_CONFIGURATION;
1833 }
1834
1835 const char *avcodec_license(void)
1836 {
1837 #define LICENSE_PREFIX "libavcodec license: "
1838     return LICENSE_PREFIX LIBAV_LICENSE + sizeof(LICENSE_PREFIX) - 1;
1839 }
1840
1841 void avcodec_flush_buffers(AVCodecContext *avctx)
1842 {
1843     if (HAVE_THREADS && avctx->active_thread_type & FF_THREAD_FRAME)
1844         ff_thread_flush(avctx);
1845     else if (avctx->codec->flush)
1846         avctx->codec->flush(avctx);
1847
1848     if (!avctx->refcounted_frames)
1849         av_frame_unref(&avctx->internal->to_free);
1850 }
1851
1852 int av_get_exact_bits_per_sample(enum AVCodecID codec_id)
1853 {
1854     switch (codec_id) {
1855     case AV_CODEC_ID_ADPCM_CT:
1856     case AV_CODEC_ID_ADPCM_IMA_APC:
1857     case AV_CODEC_ID_ADPCM_IMA_EA_SEAD:
1858     case AV_CODEC_ID_ADPCM_IMA_WS:
1859     case AV_CODEC_ID_ADPCM_G722:
1860     case AV_CODEC_ID_ADPCM_YAMAHA:
1861         return 4;
1862     case AV_CODEC_ID_PCM_ALAW:
1863     case AV_CODEC_ID_PCM_MULAW:
1864     case AV_CODEC_ID_PCM_S8:
1865     case AV_CODEC_ID_PCM_U8:
1866     case AV_CODEC_ID_PCM_ZORK:
1867         return 8;
1868     case AV_CODEC_ID_PCM_S16BE:
1869     case AV_CODEC_ID_PCM_S16LE:
1870     case AV_CODEC_ID_PCM_S16LE_PLANAR:
1871     case AV_CODEC_ID_PCM_U16BE:
1872     case AV_CODEC_ID_PCM_U16LE:
1873         return 16;
1874     case AV_CODEC_ID_PCM_S24DAUD:
1875     case AV_CODEC_ID_PCM_S24BE:
1876     case AV_CODEC_ID_PCM_S24LE:
1877     case AV_CODEC_ID_PCM_S24LE_PLANAR:
1878     case AV_CODEC_ID_PCM_U24BE:
1879     case AV_CODEC_ID_PCM_U24LE:
1880         return 24;
1881     case AV_CODEC_ID_PCM_S32BE:
1882     case AV_CODEC_ID_PCM_S32LE:
1883     case AV_CODEC_ID_PCM_S32LE_PLANAR:
1884     case AV_CODEC_ID_PCM_U32BE:
1885     case AV_CODEC_ID_PCM_U32LE:
1886     case AV_CODEC_ID_PCM_F32BE:
1887     case AV_CODEC_ID_PCM_F32LE:
1888         return 32;
1889     case AV_CODEC_ID_PCM_F64BE:
1890     case AV_CODEC_ID_PCM_F64LE:
1891         return 64;
1892     default:
1893         return 0;
1894     }
1895 }
1896
1897 int av_get_bits_per_sample(enum AVCodecID codec_id)
1898 {
1899     switch (codec_id) {
1900     case AV_CODEC_ID_ADPCM_SBPRO_2:
1901         return 2;
1902     case AV_CODEC_ID_ADPCM_SBPRO_3:
1903         return 3;
1904     case AV_CODEC_ID_ADPCM_SBPRO_4:
1905     case AV_CODEC_ID_ADPCM_IMA_WAV:
1906     case AV_CODEC_ID_ADPCM_IMA_QT:
1907     case AV_CODEC_ID_ADPCM_SWF:
1908     case AV_CODEC_ID_ADPCM_MS:
1909         return 4;
1910     default:
1911         return av_get_exact_bits_per_sample(codec_id);
1912     }
1913 }
1914
1915 int av_get_audio_frame_duration(AVCodecContext *avctx, int frame_bytes)
1916 {
1917     int id, sr, ch, ba, tag, bps;
1918
1919     id  = avctx->codec_id;
1920     sr  = avctx->sample_rate;
1921     ch  = avctx->channels;
1922     ba  = avctx->block_align;
1923     tag = avctx->codec_tag;
1924     bps = av_get_exact_bits_per_sample(avctx->codec_id);
1925
1926     /* codecs with an exact constant bits per sample */
1927     if (bps > 0 && ch > 0 && frame_bytes > 0)
1928         return (frame_bytes * 8) / (bps * ch);
1929     bps = avctx->bits_per_coded_sample;
1930
1931     /* codecs with a fixed packet duration */
1932     switch (id) {
1933     case AV_CODEC_ID_ADPCM_ADX:    return   32;
1934     case AV_CODEC_ID_ADPCM_IMA_QT: return   64;
1935     case AV_CODEC_ID_ADPCM_EA_XAS: return  128;
1936     case AV_CODEC_ID_AMR_NB:
1937     case AV_CODEC_ID_GSM:
1938     case AV_CODEC_ID_QCELP:
1939     case AV_CODEC_ID_RA_144:
1940     case AV_CODEC_ID_RA_288:       return  160;
1941     case AV_CODEC_ID_IMC:          return  256;
1942     case AV_CODEC_ID_AMR_WB:
1943     case AV_CODEC_ID_GSM_MS:       return  320;
1944     case AV_CODEC_ID_MP1:          return  384;
1945     case AV_CODEC_ID_ATRAC1:       return  512;
1946     case AV_CODEC_ID_ATRAC3:       return 1024;
1947     case AV_CODEC_ID_MP2:
1948     case AV_CODEC_ID_MUSEPACK7:    return 1152;
1949     case AV_CODEC_ID_AC3:          return 1536;
1950     }
1951
1952     if (sr > 0) {
1953         /* calc from sample rate */
1954         if (id == AV_CODEC_ID_TTA)
1955             return 256 * sr / 245;
1956
1957         if (ch > 0) {
1958             /* calc from sample rate and channels */
1959             if (id == AV_CODEC_ID_BINKAUDIO_DCT)
1960                 return (480 << (sr / 22050)) / ch;
1961         }
1962     }
1963
1964     if (ba > 0) {
1965         /* calc from block_align */
1966         if (id == AV_CODEC_ID_SIPR) {
1967             switch (ba) {
1968             case 20: return 160;
1969             case 19: return 144;
1970             case 29: return 288;
1971             case 37: return 480;
1972             }
1973         } else if (id == AV_CODEC_ID_ILBC) {
1974             switch (ba) {
1975             case 38: return 160;
1976             case 50: return 240;
1977             }
1978         }
1979     }
1980
1981     if (frame_bytes > 0) {
1982         /* calc from frame_bytes only */
1983         if (id == AV_CODEC_ID_TRUESPEECH)
1984             return 240 * (frame_bytes / 32);
1985         if (id == AV_CODEC_ID_NELLYMOSER)
1986             return 256 * (frame_bytes / 64);
1987
1988         if (bps > 0) {
1989             /* calc from frame_bytes and bits_per_coded_sample */
1990             if (id == AV_CODEC_ID_ADPCM_G726)
1991                 return frame_bytes * 8 / bps;
1992         }
1993
1994         if (ch > 0) {
1995             /* calc from frame_bytes and channels */
1996             switch (id) {
1997             case AV_CODEC_ID_ADPCM_4XM:
1998             case AV_CODEC_ID_ADPCM_IMA_ISS:
1999                 return (frame_bytes - 4 * ch) * 2 / ch;
2000             case AV_CODEC_ID_ADPCM_IMA_SMJPEG:
2001                 return (frame_bytes - 4) * 2 / ch;
2002             case AV_CODEC_ID_ADPCM_IMA_AMV:
2003                 return (frame_bytes - 8) * 2 / ch;
2004             case AV_CODEC_ID_ADPCM_XA:
2005                 return (frame_bytes / 128) * 224 / ch;
2006             case AV_CODEC_ID_INTERPLAY_DPCM:
2007                 return (frame_bytes - 6 - ch) / ch;
2008             case AV_CODEC_ID_ROQ_DPCM:
2009                 return (frame_bytes - 8) / ch;
2010             case AV_CODEC_ID_XAN_DPCM:
2011                 return (frame_bytes - 2 * ch) / ch;
2012             case AV_CODEC_ID_MACE3:
2013                 return 3 * frame_bytes / ch;
2014             case AV_CODEC_ID_MACE6:
2015                 return 6 * frame_bytes / ch;
2016             case AV_CODEC_ID_PCM_LXF:
2017                 return 2 * (frame_bytes / (5 * ch));
2018             }
2019
2020             if (tag) {
2021                 /* calc from frame_bytes, channels, and codec_tag */
2022                 if (id == AV_CODEC_ID_SOL_DPCM) {
2023                     if (tag == 3)
2024                         return frame_bytes / ch;
2025                     else
2026                         return frame_bytes * 2 / ch;
2027                 }
2028             }
2029
2030             if (ba > 0) {
2031                 /* calc from frame_bytes, channels, and block_align */
2032                 int blocks = frame_bytes / ba;
2033                 switch (avctx->codec_id) {
2034                 case AV_CODEC_ID_ADPCM_IMA_WAV:
2035                     return blocks * (1 + (ba - 4 * ch) / (4 * ch) * 8);
2036                 case AV_CODEC_ID_ADPCM_IMA_DK3:
2037                     return blocks * (((ba - 16) * 2 / 3 * 4) / ch);
2038                 case AV_CODEC_ID_ADPCM_IMA_DK4:
2039                     return blocks * (1 + (ba - 4 * ch) * 2 / ch);
2040                 case AV_CODEC_ID_ADPCM_MS:
2041                     return blocks * (2 + (ba - 7 * ch) * 2 / ch);
2042                 }
2043             }
2044
2045             if (bps > 0) {
2046                 /* calc from frame_bytes, channels, and bits_per_coded_sample */
2047                 switch (avctx->codec_id) {
2048                 case AV_CODEC_ID_PCM_DVD:
2049                     return 2 * (frame_bytes / ((bps * 2 / 8) * ch));
2050                 case AV_CODEC_ID_PCM_BLURAY:
2051                     return frame_bytes / ((FFALIGN(ch, 2) * bps) / 8);
2052                 case AV_CODEC_ID_S302M:
2053                     return 2 * (frame_bytes / ((bps + 4) / 4)) / ch;
2054                 }
2055             }
2056         }
2057     }
2058
2059     return 0;
2060 }
2061
2062 #if !HAVE_THREADS
2063 int ff_thread_init(AVCodecContext *s)
2064 {
2065     return -1;
2066 }
2067
2068 #endif
2069
2070 unsigned int av_xiphlacing(unsigned char *s, unsigned int v)
2071 {
2072     unsigned int n = 0;
2073
2074     while (v >= 0xff) {
2075         *s++ = 0xff;
2076         v -= 0xff;
2077         n++;
2078     }
2079     *s = v;
2080     n++;
2081     return n;
2082 }
2083
2084 int ff_match_2uint16(const uint16_t(*tab)[2], int size, int a, int b)
2085 {
2086     int i;
2087     for (i = 0; i < size && !(tab[i][0] == a && tab[i][1] == b); i++) ;
2088     return i;
2089 }
2090
2091 #if FF_API_MISSING_SAMPLE
2092 FF_DISABLE_DEPRECATION_WARNINGS
2093 void av_log_missing_feature(void *avc, const char *feature, int want_sample)
2094 {
2095     av_log(avc, AV_LOG_WARNING, "%s is not implemented. Update your Libav "
2096             "version to the newest one from Git. If the problem still "
2097             "occurs, it means that your file has a feature which has not "
2098             "been implemented.\n", feature);
2099     if(want_sample)
2100         av_log_ask_for_sample(avc, NULL);
2101 }
2102
2103 void av_log_ask_for_sample(void *avc, const char *msg, ...)
2104 {
2105     va_list argument_list;
2106
2107     va_start(argument_list, msg);
2108
2109     if (msg)
2110         av_vlog(avc, AV_LOG_WARNING, msg, argument_list);
2111     av_log(avc, AV_LOG_WARNING, "If you want to help, upload a sample "
2112             "of this file to ftp://upload.libav.org/incoming/ "
2113             "and contact the libav-devel mailing list.\n");
2114
2115     va_end(argument_list);
2116 }
2117 FF_ENABLE_DEPRECATION_WARNINGS
2118 #endif /* FF_API_MISSING_SAMPLE */
2119
2120 static AVHWAccel *first_hwaccel = NULL;
2121
2122 void av_register_hwaccel(AVHWAccel *hwaccel)
2123 {
2124     AVHWAccel **p = &first_hwaccel;
2125     while (*p)
2126         p = &(*p)->next;
2127     *p = hwaccel;
2128     hwaccel->next = NULL;
2129 }
2130
2131 AVHWAccel *av_hwaccel_next(AVHWAccel *hwaccel)
2132 {
2133     return hwaccel ? hwaccel->next : first_hwaccel;
2134 }
2135
2136 AVHWAccel *ff_find_hwaccel(enum AVCodecID codec_id, enum AVPixelFormat pix_fmt)
2137 {
2138     AVHWAccel *hwaccel = NULL;
2139
2140     while ((hwaccel = av_hwaccel_next(hwaccel)))
2141         if (hwaccel->id == codec_id
2142             && hwaccel->pix_fmt == pix_fmt)
2143             return hwaccel;
2144     return NULL;
2145 }
2146
2147 int av_lockmgr_register(int (*cb)(void **mutex, enum AVLockOp op))
2148 {
2149     if (lockmgr_cb) {
2150         if (lockmgr_cb(&codec_mutex, AV_LOCK_DESTROY))
2151             return -1;
2152         if (lockmgr_cb(&avformat_mutex, AV_LOCK_DESTROY))
2153             return -1;
2154     }
2155
2156     lockmgr_cb = cb;
2157
2158     if (lockmgr_cb) {
2159         if (lockmgr_cb(&codec_mutex, AV_LOCK_CREATE))
2160             return -1;
2161         if (lockmgr_cb(&avformat_mutex, AV_LOCK_CREATE))
2162             return -1;
2163     }
2164     return 0;
2165 }
2166
2167 int avpriv_lock_avformat(void)
2168 {
2169     if (lockmgr_cb) {
2170         if ((*lockmgr_cb)(&avformat_mutex, AV_LOCK_OBTAIN))
2171             return -1;
2172     }
2173     return 0;
2174 }
2175
2176 int avpriv_unlock_avformat(void)
2177 {
2178     if (lockmgr_cb) {
2179         if ((*lockmgr_cb)(&avformat_mutex, AV_LOCK_RELEASE))
2180             return -1;
2181     }
2182     return 0;
2183 }
2184
2185 unsigned int avpriv_toupper4(unsigned int x)
2186 {
2187     return av_toupper(x & 0xFF) +
2188           (av_toupper((x >>  8) & 0xFF) << 8)  +
2189           (av_toupper((x >> 16) & 0xFF) << 16) +
2190           (av_toupper((x >> 24) & 0xFF) << 24);
2191 }
2192
2193 int ff_thread_ref_frame(ThreadFrame *dst, ThreadFrame *src)
2194 {
2195     int ret;
2196
2197     dst->owner = src->owner;
2198
2199     ret = av_frame_ref(dst->f, src->f);
2200     if (ret < 0)
2201         return ret;
2202
2203     if (src->progress &&
2204         !(dst->progress = av_buffer_ref(src->progress))) {
2205         ff_thread_release_buffer(dst->owner, dst);
2206         return AVERROR(ENOMEM);
2207     }
2208
2209     return 0;
2210 }
2211
2212 #if !HAVE_THREADS
2213
2214 int ff_thread_get_buffer(AVCodecContext *avctx, ThreadFrame *f, int flags)
2215 {
2216     f->owner = avctx;
2217     return ff_get_buffer(avctx, f->f, flags);
2218 }
2219
2220 void ff_thread_release_buffer(AVCodecContext *avctx, ThreadFrame *f)
2221 {
2222     av_frame_unref(f->f);
2223 }
2224
2225 void ff_thread_finish_setup(AVCodecContext *avctx)
2226 {
2227 }
2228
2229 void ff_thread_report_progress(ThreadFrame *f, int progress, int field)
2230 {
2231 }
2232
2233 void ff_thread_await_progress(ThreadFrame *f, int progress, int field)
2234 {
2235 }
2236
2237 #endif
2238
2239 enum AVMediaType avcodec_get_type(enum AVCodecID codec_id)
2240 {
2241     if (codec_id <= AV_CODEC_ID_NONE)
2242         return AVMEDIA_TYPE_UNKNOWN;
2243     else if (codec_id < AV_CODEC_ID_FIRST_AUDIO)
2244         return AVMEDIA_TYPE_VIDEO;
2245     else if (codec_id < AV_CODEC_ID_FIRST_SUBTITLE)
2246         return AVMEDIA_TYPE_AUDIO;
2247     else if (codec_id < AV_CODEC_ID_FIRST_UNKNOWN)
2248         return AVMEDIA_TYPE_SUBTITLE;
2249
2250     return AVMEDIA_TYPE_UNKNOWN;
2251 }
2252
2253 int avcodec_is_open(AVCodecContext *s)
2254 {
2255     return !!s->internal;
2256 }
2257
2258 const uint8_t *avpriv_find_start_code(const uint8_t *restrict p,
2259                                       const uint8_t *end,
2260                                       uint32_t * restrict state)
2261 {
2262     int i;
2263
2264     assert(p <= end);
2265     if (p >= end)
2266         return end;
2267
2268     for (i = 0; i < 3; i++) {
2269         uint32_t tmp = *state << 8;
2270         *state = tmp + *(p++);
2271         if (tmp == 0x100 || p == end)
2272             return p;
2273     }
2274
2275     while (p < end) {
2276         if      (p[-1] > 1      ) p += 3;
2277         else if (p[-2]          ) p += 2;
2278         else if (p[-3]|(p[-1]-1)) p++;
2279         else {
2280             p++;
2281             break;
2282         }
2283     }
2284
2285     p = FFMIN(p, end) - 4;
2286     *state = AV_RB32(p);
2287
2288     return p + 4;
2289 }