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