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