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