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