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