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