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