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