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