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