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