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