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