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