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