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