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