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