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