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