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