]> git.sesse.net Git - ffmpeg/blob - libavcodec/utils.c
lavc: set AVCodecContext.codec in avcodec_get_context_defaults3().
[ffmpeg] / libavcodec / utils.c
1 /*
2  * utils for libavcodec
3  * Copyright (c) 2001 Fabrice Bellard
4  * Copyright (c) 2002-2004 Michael Niedermayer <michaelni@gmx.at>
5  *
6  * This file is part of Libav.
7  *
8  * Libav is free software; you can redistribute it and/or
9  * modify it under the terms of the GNU Lesser General Public
10  * License as published by the Free Software Foundation; either
11  * version 2.1 of the License, or (at your option) any later version.
12  *
13  * Libav is distributed in the hope that it will be useful,
14  * but WITHOUT ANY WARRANTY; without even the implied warranty of
15  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
16  * Lesser General Public License for more details.
17  *
18  * You should have received a copy of the GNU Lesser General Public
19  * License along with Libav; if not, write to the Free Software
20  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
21  */
22
23 /**
24  * @file
25  * utils.
26  */
27
28 #include "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 "avcodec.h"
38 #include "dsputil.h"
39 #include "libavutil/opt.h"
40 #include "imgconvert.h"
41 #include "thread.h"
42 #include "audioconvert.h"
43 #include "internal.h"
44 #include "bytestream.h"
45 #include <stdlib.h>
46 #include <stdarg.h>
47 #include <limits.h>
48 #include <float.h>
49
50 static int volatile entangled_thread_counter=0;
51 static int (*ff_lockmgr_cb)(void **mutex, enum AVLockOp op);
52 static void *codec_mutex;
53 static void *avformat_mutex;
54
55 void *av_fast_realloc(void *ptr, unsigned int *size, size_t min_size)
56 {
57     if(min_size < *size)
58         return ptr;
59
60     min_size= FFMAX(17*min_size/16 + 32, min_size);
61
62     ptr= av_realloc(ptr, min_size);
63     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
64         min_size= 0;
65
66     *size= min_size;
67
68     return ptr;
69 }
70
71 void av_fast_malloc(void *ptr, unsigned int *size, size_t min_size)
72 {
73     void **p = ptr;
74     if (min_size < *size)
75         return;
76     min_size= FFMAX(17*min_size/16 + 32, min_size);
77     av_free(*p);
78     *p = av_malloc(min_size);
79     if (!*p) min_size = 0;
80     *size= min_size;
81 }
82
83 /* encoder management */
84 static AVCodec *first_avcodec = NULL;
85
86 AVCodec *av_codec_next(AVCodec *c){
87     if(c) return c->next;
88     else  return first_avcodec;
89 }
90
91 static void avcodec_init(void)
92 {
93     static int initialized = 0;
94
95     if (initialized != 0)
96         return;
97     initialized = 1;
98
99     dsputil_static_init();
100 }
101
102 static av_always_inline int codec_is_encoder(AVCodec *codec)
103 {
104     return codec && (codec->encode || codec->encode2);
105 }
106
107 static av_always_inline int codec_is_decoder(AVCodec *codec)
108 {
109     return codec && codec->decode;
110 }
111
112 void avcodec_register(AVCodec *codec)
113 {
114     AVCodec **p;
115     avcodec_init();
116     p = &first_avcodec;
117     while (*p != NULL) p = &(*p)->next;
118     *p = codec;
119     codec->next = NULL;
120
121     if (codec->init_static_data)
122         codec->init_static_data(codec);
123 }
124
125 unsigned avcodec_get_edge_width(void)
126 {
127     return EDGE_WIDTH;
128 }
129
130 void avcodec_set_dimensions(AVCodecContext *s, int width, int height){
131     s->coded_width = width;
132     s->coded_height= height;
133     s->width = -((-width )>>s->lowres);
134     s->height= -((-height)>>s->lowres);
135 }
136
137 #define INTERNAL_BUFFER_SIZE (32+1)
138
139 void avcodec_align_dimensions2(AVCodecContext *s, int *width, int *height,
140                                int linesize_align[AV_NUM_DATA_POINTERS])
141 {
142     int i;
143     int w_align= 1;
144     int h_align= 1;
145
146     switch(s->pix_fmt){
147     case PIX_FMT_YUV420P:
148     case PIX_FMT_YUYV422:
149     case PIX_FMT_UYVY422:
150     case PIX_FMT_YUV422P:
151     case PIX_FMT_YUV440P:
152     case PIX_FMT_YUV444P:
153     case PIX_FMT_GBRP:
154     case PIX_FMT_GRAY8:
155     case PIX_FMT_GRAY16BE:
156     case PIX_FMT_GRAY16LE:
157     case PIX_FMT_YUVJ420P:
158     case PIX_FMT_YUVJ422P:
159     case PIX_FMT_YUVJ440P:
160     case PIX_FMT_YUVJ444P:
161     case PIX_FMT_YUVA420P:
162     case PIX_FMT_YUV420P9LE:
163     case PIX_FMT_YUV420P9BE:
164     case PIX_FMT_YUV420P10LE:
165     case PIX_FMT_YUV420P10BE:
166     case PIX_FMT_YUV422P9LE:
167     case PIX_FMT_YUV422P9BE:
168     case PIX_FMT_YUV422P10LE:
169     case PIX_FMT_YUV422P10BE:
170     case PIX_FMT_YUV444P9LE:
171     case PIX_FMT_YUV444P9BE:
172     case PIX_FMT_YUV444P10LE:
173     case PIX_FMT_YUV444P10BE:
174     case PIX_FMT_GBRP9LE:
175     case PIX_FMT_GBRP9BE:
176     case PIX_FMT_GBRP10LE:
177     case PIX_FMT_GBRP10BE:
178         w_align = 16; //FIXME assume 16 pixel per macroblock
179         h_align = 16 * 2; // interlaced needs 2 macroblocks height
180         break;
181     case PIX_FMT_YUV411P:
182     case PIX_FMT_UYYVYY411:
183         w_align=32;
184         h_align=8;
185         break;
186     case PIX_FMT_YUV410P:
187         if(s->codec_id == CODEC_ID_SVQ1){
188             w_align=64;
189             h_align=64;
190         }
191     case PIX_FMT_RGB555:
192         if(s->codec_id == CODEC_ID_RPZA){
193             w_align=4;
194             h_align=4;
195         }
196     case PIX_FMT_PAL8:
197     case PIX_FMT_BGR8:
198     case PIX_FMT_RGB8:
199         if(s->codec_id == CODEC_ID_SMC){
200             w_align=4;
201             h_align=4;
202         }
203         break;
204     case PIX_FMT_BGR24:
205         if((s->codec_id == CODEC_ID_MSZH) || (s->codec_id == CODEC_ID_ZLIB)){
206             w_align=4;
207             h_align=4;
208         }
209         break;
210     default:
211         w_align= 1;
212         h_align= 1;
213         break;
214     }
215
216     *width = FFALIGN(*width , w_align);
217     *height= FFALIGN(*height, h_align);
218     if(s->codec_id == CODEC_ID_H264 || s->lowres)
219         *height+=2; // some of the optimized chroma MC reads one line too much
220                     // which is also done in mpeg decoders with lowres > 0
221
222     for (i = 0; i < 4; i++)
223         linesize_align[i] = STRIDE_ALIGN;
224 //STRIDE_ALIGN is 8 for SSE* but this does not work for SVQ1 chroma planes
225 //we could change STRIDE_ALIGN to 16 for x86/sse but it would increase the
226 //picture size unneccessarily in some cases. The solution here is not
227 //pretty and better ideas are welcome!
228 #if HAVE_MMX
229     if(s->codec_id == CODEC_ID_SVQ1 || s->codec_id == CODEC_ID_VP5 ||
230        s->codec_id == CODEC_ID_VP6 || s->codec_id == CODEC_ID_VP6F ||
231        s->codec_id == CODEC_ID_VP6A) {
232         for (i = 0; i < 4; i++)
233             linesize_align[i] = 16;
234     }
235 #endif
236 }
237
238 void avcodec_align_dimensions(AVCodecContext *s, int *width, int *height){
239     int chroma_shift = av_pix_fmt_descriptors[s->pix_fmt].log2_chroma_w;
240     int linesize_align[AV_NUM_DATA_POINTERS];
241     int align;
242     avcodec_align_dimensions2(s, width, height, linesize_align);
243     align = FFMAX(linesize_align[0], linesize_align[3]);
244     linesize_align[1] <<= chroma_shift;
245     linesize_align[2] <<= chroma_shift;
246     align = FFMAX3(align, linesize_align[1], linesize_align[2]);
247     *width=FFALIGN(*width, align);
248 }
249
250 int avcodec_fill_audio_frame(AVFrame *frame, int nb_channels,
251                              enum AVSampleFormat sample_fmt, const uint8_t *buf,
252                              int buf_size, int align)
253 {
254     int ch, planar, needed_size, ret = 0;
255
256     needed_size = av_samples_get_buffer_size(NULL, nb_channels,
257                                              frame->nb_samples, sample_fmt,
258                                              align);
259     if (buf_size < needed_size)
260         return AVERROR(EINVAL);
261
262     planar = av_sample_fmt_is_planar(sample_fmt);
263     if (planar && nb_channels > AV_NUM_DATA_POINTERS) {
264         if (!(frame->extended_data = av_mallocz(nb_channels *
265                                                 sizeof(*frame->extended_data))))
266             return AVERROR(ENOMEM);
267     } else {
268         frame->extended_data = frame->data;
269     }
270
271     if ((ret = av_samples_fill_arrays(frame->extended_data, &frame->linesize[0],
272                                       buf, nb_channels, frame->nb_samples,
273                                       sample_fmt, align)) < 0) {
274         if (frame->extended_data != frame->data)
275             av_free(frame->extended_data);
276         return ret;
277     }
278     if (frame->extended_data != frame->data) {
279         for (ch = 0; ch < AV_NUM_DATA_POINTERS; ch++)
280             frame->data[ch] = frame->extended_data[ch];
281     }
282
283     return ret;
284 }
285
286 static int audio_get_buffer(AVCodecContext *avctx, AVFrame *frame)
287 {
288     AVCodecInternal *avci = avctx->internal;
289     InternalBuffer *buf;
290     int buf_size, ret;
291
292     buf_size = av_samples_get_buffer_size(NULL, avctx->channels,
293                                           frame->nb_samples, avctx->sample_fmt,
294                                           32);
295     if (buf_size < 0)
296         return AVERROR(EINVAL);
297
298     /* allocate InternalBuffer if needed */
299     if (!avci->buffer) {
300         avci->buffer = av_mallocz(sizeof(InternalBuffer));
301         if (!avci->buffer)
302             return AVERROR(ENOMEM);
303     }
304     buf = avci->buffer;
305
306     /* if there is a previously-used internal buffer, check its size and
307        channel count to see if we can reuse it */
308     if (buf->extended_data) {
309         /* if current buffer is too small, free it */
310         if (buf->extended_data[0] && buf_size > buf->audio_data_size) {
311             av_free(buf->extended_data[0]);
312             if (buf->extended_data != buf->data)
313                 av_free(&buf->extended_data);
314             buf->extended_data = NULL;
315             buf->data[0] = NULL;
316         }
317         /* if number of channels has changed, reset and/or free extended data
318            pointers but leave data buffer in buf->data[0] for reuse */
319         if (buf->nb_channels != avctx->channels) {
320             if (buf->extended_data != buf->data)
321                 av_free(buf->extended_data);
322             buf->extended_data = NULL;
323         }
324     }
325
326     /* if there is no previous buffer or the previous buffer cannot be used
327        as-is, allocate a new buffer and/or rearrange the channel pointers */
328     if (!buf->extended_data) {
329         if (!buf->data[0]) {
330             if (!(buf->data[0] = av_mallocz(buf_size)))
331                 return AVERROR(ENOMEM);
332             buf->audio_data_size = buf_size;
333         }
334         if ((ret = avcodec_fill_audio_frame(frame, avctx->channels,
335                                             avctx->sample_fmt, buf->data[0],
336                                             buf->audio_data_size, 32)))
337             return ret;
338
339         if (frame->extended_data == frame->data)
340             buf->extended_data = buf->data;
341         else
342             buf->extended_data = frame->extended_data;
343         memcpy(buf->data, frame->data, sizeof(frame->data));
344         buf->linesize[0] = frame->linesize[0];
345         buf->nb_channels = avctx->channels;
346     } else {
347         /* copy InternalBuffer info to the AVFrame */
348         frame->extended_data = buf->extended_data;
349         frame->linesize[0]   = buf->linesize[0];
350         memcpy(frame->data, buf->data, sizeof(frame->data));
351     }
352
353     frame->type          = FF_BUFFER_TYPE_INTERNAL;
354
355     if (avctx->pkt) frame->pkt_pts = avctx->pkt->pts;
356     else            frame->pkt_pts = AV_NOPTS_VALUE;
357     frame->reordered_opaque = avctx->reordered_opaque;
358
359     if (avctx->debug & FF_DEBUG_BUFFERS)
360         av_log(avctx, AV_LOG_DEBUG, "default_get_buffer called on frame %p, "
361                "internal audio buffer used\n", frame);
362
363     return 0;
364 }
365
366 static int video_get_buffer(AVCodecContext *s, AVFrame *pic)
367 {
368     int i;
369     int w= s->width;
370     int h= s->height;
371     InternalBuffer *buf;
372     AVCodecInternal *avci = s->internal;
373
374     if(pic->data[0]!=NULL) {
375         av_log(s, AV_LOG_ERROR, "pic->data[0]!=NULL in avcodec_default_get_buffer\n");
376         return -1;
377     }
378     if(avci->buffer_count >= INTERNAL_BUFFER_SIZE) {
379         av_log(s, AV_LOG_ERROR, "buffer_count overflow (missing release_buffer?)\n");
380         return -1;
381     }
382
383     if(av_image_check_size(w, h, 0, s))
384         return -1;
385
386     if (!avci->buffer) {
387         avci->buffer = av_mallocz((INTERNAL_BUFFER_SIZE+1) *
388                                   sizeof(InternalBuffer));
389     }
390
391     buf = &avci->buffer[avci->buffer_count];
392
393     if(buf->base[0] && (buf->width != w || buf->height != h || buf->pix_fmt != s->pix_fmt)){
394         if(s->active_thread_type&FF_THREAD_FRAME) {
395             av_log_missing_feature(s, "Width/height changing with frame threads is", 0);
396             return -1;
397         }
398
399         for (i = 0; i < AV_NUM_DATA_POINTERS; i++) {
400             av_freep(&buf->base[i]);
401             buf->data[i]= NULL;
402         }
403     }
404
405     if (!buf->base[0]) {
406         int h_chroma_shift, v_chroma_shift;
407         int size[4] = {0};
408         int tmpsize;
409         int unaligned;
410         AVPicture picture;
411         int stride_align[AV_NUM_DATA_POINTERS];
412         const int pixel_size = av_pix_fmt_descriptors[s->pix_fmt].comp[0].step_minus1+1;
413
414         avcodec_get_chroma_sub_sample(s->pix_fmt, &h_chroma_shift, &v_chroma_shift);
415
416         avcodec_align_dimensions2(s, &w, &h, stride_align);
417
418         if(!(s->flags&CODEC_FLAG_EMU_EDGE)){
419             w+= EDGE_WIDTH*2;
420             h+= EDGE_WIDTH*2;
421         }
422
423         do {
424             // NOTE: do not align linesizes individually, this breaks e.g. assumptions
425             // that linesize[0] == 2*linesize[1] in the MPEG-encoder for 4:2:2
426             av_image_fill_linesizes(picture.linesize, s->pix_fmt, w);
427             // increase alignment of w for next try (rhs gives the lowest bit set in w)
428             w += w & ~(w-1);
429
430             unaligned = 0;
431             for (i=0; i<4; i++){
432                 unaligned |= picture.linesize[i] % stride_align[i];
433             }
434         } while (unaligned);
435
436         tmpsize = av_image_fill_pointers(picture.data, s->pix_fmt, h, NULL, picture.linesize);
437         if (tmpsize < 0)
438             return -1;
439
440         for (i=0; i<3 && picture.data[i+1]; i++)
441             size[i] = picture.data[i+1] - picture.data[i];
442         size[i] = tmpsize - (picture.data[i] - picture.data[0]);
443
444         memset(buf->base, 0, sizeof(buf->base));
445         memset(buf->data, 0, sizeof(buf->data));
446
447         for(i=0; i<4 && size[i]; i++){
448             const int h_shift= i==0 ? 0 : h_chroma_shift;
449             const int v_shift= i==0 ? 0 : v_chroma_shift;
450
451             buf->linesize[i]= picture.linesize[i];
452
453             buf->base[i]= av_malloc(size[i]+16); //FIXME 16
454             if(buf->base[i]==NULL) return -1;
455             memset(buf->base[i], 128, size[i]);
456
457             // no edge if EDGE EMU or not planar YUV
458             if((s->flags&CODEC_FLAG_EMU_EDGE) || !size[2])
459                 buf->data[i] = buf->base[i];
460             else
461                 buf->data[i] = buf->base[i] + FFALIGN((buf->linesize[i]*EDGE_WIDTH>>v_shift) + (pixel_size*EDGE_WIDTH>>h_shift), stride_align[i]);
462         }
463         for (; i < AV_NUM_DATA_POINTERS; i++) {
464             buf->base[i] = buf->data[i] = NULL;
465             buf->linesize[i] = 0;
466         }
467         if(size[1] && !size[2])
468             ff_set_systematic_pal2((uint32_t*)buf->data[1], s->pix_fmt);
469         buf->width  = s->width;
470         buf->height = s->height;
471         buf->pix_fmt= s->pix_fmt;
472     }
473     pic->type= FF_BUFFER_TYPE_INTERNAL;
474
475     for (i = 0; i < AV_NUM_DATA_POINTERS; i++) {
476         pic->base[i]= buf->base[i];
477         pic->data[i]= buf->data[i];
478         pic->linesize[i]= buf->linesize[i];
479     }
480     pic->extended_data = pic->data;
481     avci->buffer_count++;
482
483     if(s->pkt) pic->pkt_pts= s->pkt->pts;
484     else       pic->pkt_pts= AV_NOPTS_VALUE;
485     pic->reordered_opaque= s->reordered_opaque;
486
487     if(s->debug&FF_DEBUG_BUFFERS)
488         av_log(s, AV_LOG_DEBUG, "default_get_buffer called on pic %p, %d "
489                "buffers used\n", pic, avci->buffer_count);
490
491     return 0;
492 }
493
494 int avcodec_default_get_buffer(AVCodecContext *avctx, AVFrame *frame)
495 {
496     switch (avctx->codec_type) {
497     case AVMEDIA_TYPE_VIDEO:
498         return video_get_buffer(avctx, frame);
499     case AVMEDIA_TYPE_AUDIO:
500         return audio_get_buffer(avctx, frame);
501     default:
502         return -1;
503     }
504 }
505
506 void avcodec_default_release_buffer(AVCodecContext *s, AVFrame *pic){
507     int i;
508     InternalBuffer *buf, *last;
509     AVCodecInternal *avci = s->internal;
510
511     assert(s->codec_type == AVMEDIA_TYPE_VIDEO);
512
513     assert(pic->type==FF_BUFFER_TYPE_INTERNAL);
514     assert(avci->buffer_count);
515
516     if (avci->buffer) {
517         buf = NULL; /* avoids warning */
518         for (i = 0; i < avci->buffer_count; i++) { //just 3-5 checks so is not worth to optimize
519             buf = &avci->buffer[i];
520             if (buf->data[0] == pic->data[0])
521                 break;
522         }
523         assert(i < avci->buffer_count);
524         avci->buffer_count--;
525         last = &avci->buffer[avci->buffer_count];
526
527         if (buf != last)
528             FFSWAP(InternalBuffer, *buf, *last);
529     }
530
531     for (i = 0; i < AV_NUM_DATA_POINTERS; i++) {
532         pic->data[i]=NULL;
533 //        pic->base[i]=NULL;
534     }
535 //printf("R%X\n", pic->opaque);
536
537     if(s->debug&FF_DEBUG_BUFFERS)
538         av_log(s, AV_LOG_DEBUG, "default_release_buffer called on pic %p, %d "
539                "buffers used\n", pic, avci->buffer_count);
540 }
541
542 int avcodec_default_reget_buffer(AVCodecContext *s, AVFrame *pic){
543     AVFrame temp_pic;
544     int i;
545
546     assert(s->codec_type == AVMEDIA_TYPE_VIDEO);
547
548     /* If no picture return a new buffer */
549     if(pic->data[0] == NULL) {
550         /* We will copy from buffer, so must be readable */
551         pic->buffer_hints |= FF_BUFFER_HINTS_READABLE;
552         return s->get_buffer(s, pic);
553     }
554
555     /* If internal buffer type return the same buffer */
556     if(pic->type == FF_BUFFER_TYPE_INTERNAL) {
557         if(s->pkt) pic->pkt_pts= s->pkt->pts;
558         else       pic->pkt_pts= AV_NOPTS_VALUE;
559         pic->reordered_opaque= s->reordered_opaque;
560         return 0;
561     }
562
563     /*
564      * Not internal type and reget_buffer not overridden, emulate cr buffer
565      */
566     temp_pic = *pic;
567     for(i = 0; i < AV_NUM_DATA_POINTERS; i++)
568         pic->data[i] = pic->base[i] = NULL;
569     pic->opaque = NULL;
570     /* Allocate new frame */
571     if (s->get_buffer(s, pic))
572         return -1;
573     /* Copy image data from old buffer to new buffer */
574     av_picture_copy((AVPicture*)pic, (AVPicture*)&temp_pic, s->pix_fmt, s->width,
575              s->height);
576     s->release_buffer(s, &temp_pic); // Release old frame
577     return 0;
578 }
579
580 int avcodec_default_execute(AVCodecContext *c, int (*func)(AVCodecContext *c2, void *arg2),void *arg, int *ret, int count, int size){
581     int i;
582
583     for(i=0; i<count; i++){
584         int r= func(c, (char*)arg + i*size);
585         if(ret) ret[i]= r;
586     }
587     return 0;
588 }
589
590 int avcodec_default_execute2(AVCodecContext *c, int (*func)(AVCodecContext *c2, void *arg2, int jobnr, int threadnr),void *arg, int *ret, int count){
591     int i;
592
593     for(i=0; i<count; i++){
594         int r= func(c, arg, i, 0);
595         if(ret) ret[i]= r;
596     }
597     return 0;
598 }
599
600 enum PixelFormat avcodec_default_get_format(struct AVCodecContext *s, const enum PixelFormat *fmt){
601     while (*fmt != PIX_FMT_NONE && ff_is_hwaccel_pix_fmt(*fmt))
602         ++fmt;
603     return fmt[0];
604 }
605
606 void avcodec_get_frame_defaults(AVFrame *pic){
607     memset(pic, 0, sizeof(AVFrame));
608
609     pic->pts= AV_NOPTS_VALUE;
610     pic->key_frame= 1;
611     pic->sample_aspect_ratio = (AVRational){0, 1};
612     pic->format = -1;           /* unknown */
613 }
614
615 AVFrame *avcodec_alloc_frame(void){
616     AVFrame *pic= av_malloc(sizeof(AVFrame));
617
618     if(pic==NULL) return NULL;
619
620     avcodec_get_frame_defaults(pic);
621
622     return pic;
623 }
624
625 int attribute_align_arg avcodec_open2(AVCodecContext *avctx, AVCodec *codec, AVDictionary **options)
626 {
627     int ret = 0;
628     AVDictionary *tmp = NULL;
629
630     if (avcodec_is_open(avctx))
631         return 0;
632
633     if ((!codec && !avctx->codec)) {
634         av_log(avctx, AV_LOG_ERROR, "No codec provided to avcodec_open2().\n");
635         return AVERROR(EINVAL);
636     }
637     if ((codec && avctx->codec && codec != avctx->codec)) {
638         av_log(avctx, AV_LOG_ERROR, "This AVCodecContext was allocated for %s, "
639                "but %s passed to avcodec_open2().\n", avctx->codec->name, codec->name);
640         return AVERROR(EINVAL);
641     }
642     if (!codec)
643         codec = avctx->codec;
644
645     if (avctx->extradata_size < 0 || avctx->extradata_size >= FF_MAX_EXTRADATA_SIZE)
646         return AVERROR(EINVAL);
647
648     if (options)
649         av_dict_copy(&tmp, *options, 0);
650
651     /* If there is a user-supplied mutex locking routine, call it. */
652     if (ff_lockmgr_cb) {
653         if ((*ff_lockmgr_cb)(&codec_mutex, AV_LOCK_OBTAIN))
654             return -1;
655     }
656
657     entangled_thread_counter++;
658     if(entangled_thread_counter != 1){
659         av_log(avctx, AV_LOG_ERROR, "insufficient thread locking around avcodec_open/close()\n");
660         ret = -1;
661         goto end;
662     }
663
664     avctx->internal = av_mallocz(sizeof(AVCodecInternal));
665     if (!avctx->internal) {
666         ret = AVERROR(ENOMEM);
667         goto end;
668     }
669
670     if (codec->priv_data_size > 0) {
671       if(!avctx->priv_data){
672         avctx->priv_data = av_mallocz(codec->priv_data_size);
673         if (!avctx->priv_data) {
674             ret = AVERROR(ENOMEM);
675             goto end;
676         }
677         if (codec->priv_class) {
678             *(AVClass**)avctx->priv_data= codec->priv_class;
679             av_opt_set_defaults(avctx->priv_data);
680         }
681       }
682       if (codec->priv_class && (ret = av_opt_set_dict(avctx->priv_data, &tmp)) < 0)
683           goto free_and_end;
684     } else {
685         avctx->priv_data = NULL;
686     }
687     if ((ret = av_opt_set_dict(avctx, &tmp)) < 0)
688         goto free_and_end;
689
690     if(avctx->coded_width && avctx->coded_height)
691         avcodec_set_dimensions(avctx, avctx->coded_width, avctx->coded_height);
692     else if(avctx->width && avctx->height)
693         avcodec_set_dimensions(avctx, avctx->width, avctx->height);
694
695     if ((avctx->coded_width || avctx->coded_height || avctx->width || avctx->height)
696         && (  av_image_check_size(avctx->coded_width, avctx->coded_height, 0, avctx) < 0
697            || av_image_check_size(avctx->width,       avctx->height,       0, avctx) < 0)) {
698         av_log(avctx, AV_LOG_WARNING, "ignoring invalid width/height values\n");
699         avcodec_set_dimensions(avctx, 0, 0);
700     }
701
702     /* if the decoder init function was already called previously,
703        free the already allocated subtitle_header before overwriting it */
704     if (codec_is_decoder(codec))
705         av_freep(&avctx->subtitle_header);
706
707 #define SANE_NB_CHANNELS 128U
708     if (avctx->channels > SANE_NB_CHANNELS) {
709         ret = AVERROR(EINVAL);
710         goto free_and_end;
711     }
712
713     avctx->codec = codec;
714     if ((avctx->codec_type == AVMEDIA_TYPE_UNKNOWN || avctx->codec_type == codec->type) &&
715         avctx->codec_id == CODEC_ID_NONE) {
716         avctx->codec_type = codec->type;
717         avctx->codec_id   = codec->id;
718     }
719     if (avctx->codec_id != codec->id || (avctx->codec_type != codec->type
720                            && avctx->codec_type != AVMEDIA_TYPE_ATTACHMENT)) {
721         av_log(avctx, AV_LOG_ERROR, "codec type or id mismatches\n");
722         ret = AVERROR(EINVAL);
723         goto free_and_end;
724     }
725     avctx->frame_number = 0;
726
727     if (avctx->codec_type == AVMEDIA_TYPE_AUDIO &&
728         (!avctx->time_base.num || !avctx->time_base.den)) {
729         avctx->time_base.num = 1;
730         avctx->time_base.den = avctx->sample_rate;
731     }
732
733     if (HAVE_THREADS && !avctx->thread_opaque) {
734         ret = ff_thread_init(avctx);
735         if (ret < 0) {
736             goto free_and_end;
737         }
738     }
739     if (!HAVE_THREADS && !(codec->capabilities & CODEC_CAP_AUTO_THREADS))
740         avctx->thread_count = 1;
741
742     if (avctx->codec->max_lowres < avctx->lowres) {
743         av_log(avctx, AV_LOG_ERROR, "The maximum value for lowres supported by the decoder is %d\n",
744                avctx->codec->max_lowres);
745         ret = AVERROR(EINVAL);
746         goto free_and_end;
747     }
748     if (codec_is_encoder(avctx->codec)) {
749         int i;
750         if (avctx->codec->sample_fmts) {
751             for (i = 0; avctx->codec->sample_fmts[i] != AV_SAMPLE_FMT_NONE; i++)
752                 if (avctx->sample_fmt == avctx->codec->sample_fmts[i])
753                     break;
754             if (avctx->codec->sample_fmts[i] == AV_SAMPLE_FMT_NONE) {
755                 av_log(avctx, AV_LOG_ERROR, "Specified sample_fmt is not supported.\n");
756                 ret = AVERROR(EINVAL);
757                 goto free_and_end;
758             }
759         }
760         if (avctx->codec->supported_samplerates) {
761             for (i = 0; avctx->codec->supported_samplerates[i] != 0; i++)
762                 if (avctx->sample_rate == avctx->codec->supported_samplerates[i])
763                     break;
764             if (avctx->codec->supported_samplerates[i] == 0) {
765                 av_log(avctx, AV_LOG_ERROR, "Specified sample_rate is not supported\n");
766                 ret = AVERROR(EINVAL);
767                 goto free_and_end;
768             }
769         }
770         if (avctx->codec->channel_layouts) {
771             if (!avctx->channel_layout) {
772                 av_log(avctx, AV_LOG_WARNING, "channel_layout not specified\n");
773             } else {
774                 for (i = 0; avctx->codec->channel_layouts[i] != 0; i++)
775                     if (avctx->channel_layout == avctx->codec->channel_layouts[i])
776                         break;
777                 if (avctx->codec->channel_layouts[i] == 0) {
778                     av_log(avctx, AV_LOG_ERROR, "Specified channel_layout is not supported\n");
779                     ret = AVERROR(EINVAL);
780                     goto free_and_end;
781                 }
782             }
783         }
784         if (avctx->channel_layout && avctx->channels) {
785             if (av_get_channel_layout_nb_channels(avctx->channel_layout) != avctx->channels) {
786                 av_log(avctx, AV_LOG_ERROR, "channel layout does not match number of channels\n");
787                 ret = AVERROR(EINVAL);
788                 goto free_and_end;
789             }
790         } else if (avctx->channel_layout) {
791             avctx->channels = av_get_channel_layout_nb_channels(avctx->channel_layout);
792         }
793     }
794
795     if(avctx->codec->init && !(avctx->active_thread_type&FF_THREAD_FRAME)){
796         ret = avctx->codec->init(avctx);
797         if (ret < 0) {
798             goto free_and_end;
799         }
800     }
801 end:
802     entangled_thread_counter--;
803
804     /* Release any user-supplied mutex. */
805     if (ff_lockmgr_cb) {
806         (*ff_lockmgr_cb)(&codec_mutex, AV_LOCK_RELEASE);
807     }
808     if (options) {
809         av_dict_free(options);
810         *options = tmp;
811     }
812
813     return ret;
814 free_and_end:
815     av_dict_free(&tmp);
816     av_freep(&avctx->priv_data);
817     av_freep(&avctx->internal);
818     avctx->codec= NULL;
819     goto end;
820 }
821
822 int ff_alloc_packet(AVPacket *avpkt, int size)
823 {
824     if (size > INT_MAX - FF_INPUT_BUFFER_PADDING_SIZE)
825         return AVERROR(EINVAL);
826
827     if (avpkt->data) {
828         uint8_t *pkt_data;
829         int pkt_size;
830
831         if (avpkt->size < size)
832             return AVERROR(EINVAL);
833
834         pkt_data = avpkt->data;
835         pkt_size = avpkt->size;
836         av_init_packet(avpkt);
837         avpkt->data = pkt_data;
838         avpkt->size = pkt_size;
839         return 0;
840     } else {
841         return av_new_packet(avpkt, size);
842     }
843 }
844
845 int attribute_align_arg avcodec_encode_audio2(AVCodecContext *avctx,
846                                               AVPacket *avpkt,
847                                               const AVFrame *frame,
848                                               int *got_packet_ptr)
849 {
850     int ret;
851     int user_packet = !!avpkt->data;
852     int nb_samples;
853
854     if (!(avctx->codec->capabilities & CODEC_CAP_DELAY) && !frame) {
855         av_init_packet(avpkt);
856         avpkt->size = 0;
857         return 0;
858     }
859
860     /* check for valid frame size */
861     if (frame) {
862         nb_samples = frame->nb_samples;
863         if (avctx->codec->capabilities & CODEC_CAP_SMALL_LAST_FRAME) {
864             if (nb_samples > avctx->frame_size)
865                 return AVERROR(EINVAL);
866         } else if (!(avctx->codec->capabilities & CODEC_CAP_VARIABLE_FRAME_SIZE)) {
867             if (nb_samples != avctx->frame_size)
868                 return AVERROR(EINVAL);
869         }
870     } else {
871         nb_samples = avctx->frame_size;
872     }
873
874     if (avctx->codec->encode2) {
875         *got_packet_ptr = 0;
876         ret = avctx->codec->encode2(avctx, avpkt, frame, got_packet_ptr);
877         if (!ret && *got_packet_ptr &&
878             !(avctx->codec->capabilities & CODEC_CAP_DELAY)) {
879             avpkt->pts = frame->pts;
880             avpkt->duration = av_rescale_q(frame->nb_samples,
881                                            (AVRational){ 1, avctx->sample_rate },
882                                            avctx->time_base);
883         }
884     } else {
885         /* for compatibility with encoders not supporting encode2(), we need to
886            allocate a packet buffer if the user has not provided one or check
887            the size otherwise */
888         int fs_tmp   = 0;
889         int buf_size = avpkt->size;
890         if (!user_packet) {
891             if (avctx->codec->capabilities & CODEC_CAP_VARIABLE_FRAME_SIZE) {
892                 av_assert0(av_get_bits_per_sample(avctx->codec_id) != 0);
893                 buf_size = nb_samples * avctx->channels *
894                            av_get_bits_per_sample(avctx->codec_id) / 8;
895             } else {
896                 /* this is a guess as to the required size.
897                    if an encoder needs more than this, it should probably
898                    implement encode2() */
899                 buf_size = 2 * avctx->frame_size * avctx->channels *
900                            av_get_bytes_per_sample(avctx->sample_fmt);
901                 buf_size += FF_MIN_BUFFER_SIZE;
902             }
903         }
904         if ((ret = ff_alloc_packet(avpkt, buf_size)))
905             return ret;
906
907         /* Encoders using AVCodec.encode() that support
908            CODEC_CAP_SMALL_LAST_FRAME require avctx->frame_size to be set to
909            the smaller size when encoding the last frame.
910            This code can be removed once all encoders supporting
911            CODEC_CAP_SMALL_LAST_FRAME use encode2() */
912         if ((avctx->codec->capabilities & CODEC_CAP_SMALL_LAST_FRAME) &&
913             nb_samples < avctx->frame_size) {
914             fs_tmp = avctx->frame_size;
915             avctx->frame_size = nb_samples;
916         }
917
918         /* encode the frame */
919         ret = avctx->codec->encode(avctx, avpkt->data, avpkt->size,
920                                    frame ? frame->data[0] : NULL);
921         if (ret >= 0) {
922             if (!ret) {
923                 /* no output. if the packet data was allocated by libavcodec,
924                    free it */
925                 if (!user_packet)
926                     av_freep(&avpkt->data);
927             } else {
928                 if (avctx->coded_frame)
929                     avpkt->pts = avctx->coded_frame->pts;
930                 /* Set duration for final small packet. This can be removed
931                    once all encoders supporting CODEC_CAP_SMALL_LAST_FRAME use
932                    encode2() */
933                 if (fs_tmp) {
934                     avpkt->duration = av_rescale_q(avctx->frame_size,
935                                                    (AVRational){ 1, avctx->sample_rate },
936                                                    avctx->time_base);
937                 }
938             }
939             avpkt->size = ret;
940             *got_packet_ptr = (ret > 0);
941             ret = 0;
942         }
943
944         if (fs_tmp)
945             avctx->frame_size = fs_tmp;
946     }
947     if (!ret)
948         avctx->frame_number++;
949
950     /* NOTE: if we add any audio encoders which output non-keyframe packets,
951              this needs to be moved to the encoders, but for now we can do it
952              here to simplify things */
953     avpkt->flags |= AV_PKT_FLAG_KEY;
954
955     return ret;
956 }
957
958 #if FF_API_OLD_DECODE_AUDIO
959 int attribute_align_arg avcodec_encode_audio(AVCodecContext *avctx,
960                                              uint8_t *buf, int buf_size,
961                                              const short *samples)
962 {
963     AVPacket pkt;
964     AVFrame frame0;
965     AVFrame *frame;
966     int ret, samples_size, got_packet;
967
968     av_init_packet(&pkt);
969     pkt.data = buf;
970     pkt.size = buf_size;
971
972     if (samples) {
973         frame = &frame0;
974         avcodec_get_frame_defaults(frame);
975
976         if (avctx->frame_size) {
977             frame->nb_samples = avctx->frame_size;
978         } else {
979             /* if frame_size is not set, the number of samples must be
980                calculated from the buffer size */
981             int64_t nb_samples;
982             if (!av_get_bits_per_sample(avctx->codec_id)) {
983                 av_log(avctx, AV_LOG_ERROR, "avcodec_encode_audio() does not "
984                        "support this codec\n");
985                 return AVERROR(EINVAL);
986             }
987             nb_samples = (int64_t)buf_size * 8 /
988                          (av_get_bits_per_sample(avctx->codec_id) *
989                          avctx->channels);
990             if (nb_samples >= INT_MAX)
991                 return AVERROR(EINVAL);
992             frame->nb_samples = nb_samples;
993         }
994
995         /* it is assumed that the samples buffer is large enough based on the
996            relevant parameters */
997         samples_size = av_samples_get_buffer_size(NULL, avctx->channels,
998                                                   frame->nb_samples,
999                                                   avctx->sample_fmt, 1);
1000         if ((ret = avcodec_fill_audio_frame(frame, avctx->channels,
1001                                             avctx->sample_fmt,
1002                                             samples, samples_size, 1)))
1003             return ret;
1004
1005         /* fabricate frame pts from sample count.
1006            this is needed because the avcodec_encode_audio() API does not have
1007            a way for the user to provide pts */
1008         frame->pts = av_rescale_q(avctx->internal->sample_count,
1009                                   (AVRational){ 1, avctx->sample_rate },
1010                                   avctx->time_base);
1011         avctx->internal->sample_count += frame->nb_samples;
1012     } else {
1013         frame = NULL;
1014     }
1015
1016     got_packet = 0;
1017     ret = avcodec_encode_audio2(avctx, &pkt, frame, &got_packet);
1018     if (!ret && got_packet && avctx->coded_frame) {
1019         avctx->coded_frame->pts       = pkt.pts;
1020         avctx->coded_frame->key_frame = !!(pkt.flags & AV_PKT_FLAG_KEY);
1021     }
1022     /* free any side data since we cannot return it */
1023     if (pkt.side_data_elems > 0) {
1024         int i;
1025         for (i = 0; i < pkt.side_data_elems; i++)
1026             av_free(pkt.side_data[i].data);
1027         av_freep(&pkt.side_data);
1028         pkt.side_data_elems = 0;
1029     }
1030
1031     if (frame && frame->extended_data != frame->data)
1032         av_free(frame->extended_data);
1033
1034     return ret ? ret : pkt.size;
1035 }
1036 #endif
1037
1038 int attribute_align_arg avcodec_encode_video(AVCodecContext *avctx, uint8_t *buf, int buf_size,
1039                          const AVFrame *pict)
1040 {
1041     if(buf_size < FF_MIN_BUFFER_SIZE){
1042         av_log(avctx, AV_LOG_ERROR, "buffer smaller than minimum size\n");
1043         return -1;
1044     }
1045     if(av_image_check_size(avctx->width, avctx->height, 0, avctx))
1046         return -1;
1047     if((avctx->codec->capabilities & CODEC_CAP_DELAY) || pict){
1048         int ret = avctx->codec->encode(avctx, buf, buf_size, pict);
1049         avctx->frame_number++;
1050         emms_c(); //needed to avoid an emms_c() call before every return;
1051
1052         return ret;
1053     }else
1054         return 0;
1055 }
1056
1057 int avcodec_encode_subtitle(AVCodecContext *avctx, uint8_t *buf, int buf_size,
1058                             const AVSubtitle *sub)
1059 {
1060     int ret;
1061     if(sub->start_display_time) {
1062         av_log(avctx, AV_LOG_ERROR, "start_display_time must be 0.\n");
1063         return -1;
1064     }
1065     if(sub->num_rects == 0 || !sub->rects)
1066         return -1;
1067     ret = avctx->codec->encode(avctx, buf, buf_size, sub);
1068     avctx->frame_number++;
1069     return ret;
1070 }
1071
1072 static void apply_param_change(AVCodecContext *avctx, AVPacket *avpkt)
1073 {
1074     int size = 0;
1075     const uint8_t *data;
1076     uint32_t flags;
1077
1078     if (!(avctx->codec->capabilities & CODEC_CAP_PARAM_CHANGE))
1079         return;
1080
1081     data = av_packet_get_side_data(avpkt, AV_PKT_DATA_PARAM_CHANGE, &size);
1082     if (!data || size < 4)
1083         return;
1084     flags = bytestream_get_le32(&data);
1085     size -= 4;
1086     if (size < 4) /* Required for any of the changes */
1087         return;
1088     if (flags & AV_SIDE_DATA_PARAM_CHANGE_CHANNEL_COUNT) {
1089         avctx->channels = bytestream_get_le32(&data);
1090         size -= 4;
1091     }
1092     if (flags & AV_SIDE_DATA_PARAM_CHANGE_CHANNEL_LAYOUT) {
1093         if (size < 8)
1094             return;
1095         avctx->channel_layout = bytestream_get_le64(&data);
1096         size -= 8;
1097     }
1098     if (size < 4)
1099         return;
1100     if (flags & AV_SIDE_DATA_PARAM_CHANGE_SAMPLE_RATE) {
1101         avctx->sample_rate = bytestream_get_le32(&data);
1102         size -= 4;
1103     }
1104     if (flags & AV_SIDE_DATA_PARAM_CHANGE_DIMENSIONS) {
1105         if (size < 8)
1106             return;
1107         avctx->width  = bytestream_get_le32(&data);
1108         avctx->height = bytestream_get_le32(&data);
1109         avcodec_set_dimensions(avctx, avctx->width, avctx->height);
1110         size -= 8;
1111     }
1112 }
1113
1114 int attribute_align_arg avcodec_decode_video2(AVCodecContext *avctx, AVFrame *picture,
1115                          int *got_picture_ptr,
1116                          AVPacket *avpkt)
1117 {
1118     int ret;
1119
1120     *got_picture_ptr= 0;
1121     if((avctx->coded_width||avctx->coded_height) && av_image_check_size(avctx->coded_width, avctx->coded_height, 0, avctx))
1122         return -1;
1123
1124     avctx->pkt = avpkt;
1125     apply_param_change(avctx, avpkt);
1126
1127     if((avctx->codec->capabilities & CODEC_CAP_DELAY) || avpkt->size || (avctx->active_thread_type&FF_THREAD_FRAME)){
1128         if (HAVE_THREADS && avctx->active_thread_type&FF_THREAD_FRAME)
1129              ret = ff_thread_decode_frame(avctx, picture, got_picture_ptr,
1130                                           avpkt);
1131         else {
1132             ret = avctx->codec->decode(avctx, picture, got_picture_ptr,
1133                               avpkt);
1134             picture->pkt_dts= avpkt->dts;
1135             picture->sample_aspect_ratio = avctx->sample_aspect_ratio;
1136             picture->width  = avctx->width;
1137             picture->height = avctx->height;
1138             picture->format = avctx->pix_fmt;
1139         }
1140
1141         emms_c(); //needed to avoid an emms_c() call before every return;
1142
1143         if (*got_picture_ptr)
1144             avctx->frame_number++;
1145     }else
1146         ret= 0;
1147
1148     return ret;
1149 }
1150
1151 #if FF_API_OLD_DECODE_AUDIO
1152 int attribute_align_arg avcodec_decode_audio3(AVCodecContext *avctx, int16_t *samples,
1153                          int *frame_size_ptr,
1154                          AVPacket *avpkt)
1155 {
1156     AVFrame frame;
1157     int ret, got_frame = 0;
1158
1159     if (avctx->get_buffer != avcodec_default_get_buffer) {
1160         av_log(avctx, AV_LOG_ERROR, "Custom get_buffer() for use with"
1161                "avcodec_decode_audio3() detected. Overriding with avcodec_default_get_buffer\n");
1162         av_log(avctx, AV_LOG_ERROR, "Please port your application to "
1163                "avcodec_decode_audio4()\n");
1164         avctx->get_buffer = avcodec_default_get_buffer;
1165     }
1166
1167     ret = avcodec_decode_audio4(avctx, &frame, &got_frame, avpkt);
1168
1169     if (ret >= 0 && got_frame) {
1170         int ch, plane_size;
1171         int planar = av_sample_fmt_is_planar(avctx->sample_fmt);
1172         int data_size = av_samples_get_buffer_size(&plane_size, avctx->channels,
1173                                                    frame.nb_samples,
1174                                                    avctx->sample_fmt, 1);
1175         if (*frame_size_ptr < data_size) {
1176             av_log(avctx, AV_LOG_ERROR, "output buffer size is too small for "
1177                    "the current frame (%d < %d)\n", *frame_size_ptr, data_size);
1178             return AVERROR(EINVAL);
1179         }
1180
1181         memcpy(samples, frame.extended_data[0], plane_size);
1182
1183         if (planar && avctx->channels > 1) {
1184             uint8_t *out = ((uint8_t *)samples) + plane_size;
1185             for (ch = 1; ch < avctx->channels; ch++) {
1186                 memcpy(out, frame.extended_data[ch], plane_size);
1187                 out += plane_size;
1188             }
1189         }
1190         *frame_size_ptr = data_size;
1191     } else {
1192         *frame_size_ptr = 0;
1193     }
1194     return ret;
1195 }
1196 #endif
1197
1198 int attribute_align_arg avcodec_decode_audio4(AVCodecContext *avctx,
1199                                               AVFrame *frame,
1200                                               int *got_frame_ptr,
1201                                               AVPacket *avpkt)
1202 {
1203     int ret = 0;
1204
1205     *got_frame_ptr = 0;
1206
1207     avctx->pkt = avpkt;
1208
1209     if (!avpkt->data && avpkt->size) {
1210         av_log(avctx, AV_LOG_ERROR, "invalid packet: NULL data, size != 0\n");
1211         return AVERROR(EINVAL);
1212     }
1213
1214     apply_param_change(avctx, avpkt);
1215
1216     if ((avctx->codec->capabilities & CODEC_CAP_DELAY) || avpkt->size) {
1217         ret = avctx->codec->decode(avctx, frame, got_frame_ptr, avpkt);
1218         if (ret >= 0 && *got_frame_ptr) {
1219             avctx->frame_number++;
1220             frame->pkt_dts = avpkt->dts;
1221             if (frame->format == AV_SAMPLE_FMT_NONE)
1222                 frame->format = avctx->sample_fmt;
1223         }
1224     }
1225     return ret;
1226 }
1227
1228 int avcodec_decode_subtitle2(AVCodecContext *avctx, AVSubtitle *sub,
1229                             int *got_sub_ptr,
1230                             AVPacket *avpkt)
1231 {
1232     int ret;
1233
1234     avctx->pkt = avpkt;
1235     *got_sub_ptr = 0;
1236     ret = avctx->codec->decode(avctx, sub, got_sub_ptr, avpkt);
1237     if (*got_sub_ptr)
1238         avctx->frame_number++;
1239     return ret;
1240 }
1241
1242 void avsubtitle_free(AVSubtitle *sub)
1243 {
1244     int i;
1245
1246     for (i = 0; i < sub->num_rects; i++)
1247     {
1248         av_freep(&sub->rects[i]->pict.data[0]);
1249         av_freep(&sub->rects[i]->pict.data[1]);
1250         av_freep(&sub->rects[i]->pict.data[2]);
1251         av_freep(&sub->rects[i]->pict.data[3]);
1252         av_freep(&sub->rects[i]->text);
1253         av_freep(&sub->rects[i]->ass);
1254         av_freep(&sub->rects[i]);
1255     }
1256
1257     av_freep(&sub->rects);
1258
1259     memset(sub, 0, sizeof(AVSubtitle));
1260 }
1261
1262 av_cold int avcodec_close(AVCodecContext *avctx)
1263 {
1264     /* If there is a user-supplied mutex locking routine, call it. */
1265     if (ff_lockmgr_cb) {
1266         if ((*ff_lockmgr_cb)(&codec_mutex, AV_LOCK_OBTAIN))
1267             return -1;
1268     }
1269
1270     entangled_thread_counter++;
1271     if(entangled_thread_counter != 1){
1272         av_log(avctx, AV_LOG_ERROR, "insufficient thread locking around avcodec_open/close()\n");
1273         entangled_thread_counter--;
1274         return -1;
1275     }
1276
1277     if (avcodec_is_open(avctx)) {
1278         if (HAVE_THREADS && avctx->thread_opaque)
1279             ff_thread_free(avctx);
1280         if (avctx->codec && avctx->codec->close)
1281             avctx->codec->close(avctx);
1282         avcodec_default_free_buffers(avctx);
1283         avctx->coded_frame = NULL;
1284         av_freep(&avctx->internal);
1285     }
1286
1287     if (avctx->priv_data && avctx->codec && avctx->codec->priv_class)
1288         av_opt_free(avctx->priv_data);
1289     av_opt_free(avctx);
1290     av_freep(&avctx->priv_data);
1291     if (codec_is_encoder(avctx->codec))
1292         av_freep(&avctx->extradata);
1293     avctx->codec = NULL;
1294     avctx->active_thread_type = 0;
1295     entangled_thread_counter--;
1296
1297     /* Release any user-supplied mutex. */
1298     if (ff_lockmgr_cb) {
1299         (*ff_lockmgr_cb)(&codec_mutex, AV_LOCK_RELEASE);
1300     }
1301     return 0;
1302 }
1303
1304 AVCodec *avcodec_find_encoder(enum CodecID id)
1305 {
1306     AVCodec *p, *experimental=NULL;
1307     p = first_avcodec;
1308     while (p) {
1309         if (codec_is_encoder(p) && p->id == id) {
1310             if (p->capabilities & CODEC_CAP_EXPERIMENTAL && !experimental) {
1311                 experimental = p;
1312             } else
1313                 return p;
1314         }
1315         p = p->next;
1316     }
1317     return experimental;
1318 }
1319
1320 AVCodec *avcodec_find_encoder_by_name(const char *name)
1321 {
1322     AVCodec *p;
1323     if (!name)
1324         return NULL;
1325     p = first_avcodec;
1326     while (p) {
1327         if (codec_is_encoder(p) && strcmp(name,p->name) == 0)
1328             return p;
1329         p = p->next;
1330     }
1331     return NULL;
1332 }
1333
1334 AVCodec *avcodec_find_decoder(enum CodecID id)
1335 {
1336     AVCodec *p;
1337     p = first_avcodec;
1338     while (p) {
1339         if (codec_is_decoder(p) && p->id == id)
1340             return p;
1341         p = p->next;
1342     }
1343     return NULL;
1344 }
1345
1346 AVCodec *avcodec_find_decoder_by_name(const char *name)
1347 {
1348     AVCodec *p;
1349     if (!name)
1350         return NULL;
1351     p = first_avcodec;
1352     while (p) {
1353         if (codec_is_decoder(p) && strcmp(name,p->name) == 0)
1354             return p;
1355         p = p->next;
1356     }
1357     return NULL;
1358 }
1359
1360 static int get_bit_rate(AVCodecContext *ctx)
1361 {
1362     int bit_rate;
1363     int bits_per_sample;
1364
1365     switch(ctx->codec_type) {
1366     case AVMEDIA_TYPE_VIDEO:
1367     case AVMEDIA_TYPE_DATA:
1368     case AVMEDIA_TYPE_SUBTITLE:
1369     case AVMEDIA_TYPE_ATTACHMENT:
1370         bit_rate = ctx->bit_rate;
1371         break;
1372     case AVMEDIA_TYPE_AUDIO:
1373         bits_per_sample = av_get_bits_per_sample(ctx->codec_id);
1374         bit_rate = bits_per_sample ? ctx->sample_rate * ctx->channels * bits_per_sample : ctx->bit_rate;
1375         break;
1376     default:
1377         bit_rate = 0;
1378         break;
1379     }
1380     return bit_rate;
1381 }
1382
1383 size_t av_get_codec_tag_string(char *buf, size_t buf_size, unsigned int codec_tag)
1384 {
1385     int i, len, ret = 0;
1386
1387     for (i = 0; i < 4; i++) {
1388         len = snprintf(buf, buf_size,
1389                        isprint(codec_tag&0xFF) ? "%c" : "[%d]", codec_tag&0xFF);
1390         buf      += len;
1391         buf_size  = buf_size > len ? buf_size - len : 0;
1392         ret      += len;
1393         codec_tag>>=8;
1394     }
1395     return ret;
1396 }
1397
1398 void avcodec_string(char *buf, int buf_size, AVCodecContext *enc, int encode)
1399 {
1400     const char *codec_name;
1401     const char *profile = NULL;
1402     AVCodec *p;
1403     char buf1[32];
1404     int bitrate;
1405     AVRational display_aspect_ratio;
1406
1407     if (encode)
1408         p = avcodec_find_encoder(enc->codec_id);
1409     else
1410         p = avcodec_find_decoder(enc->codec_id);
1411
1412     if (p) {
1413         codec_name = p->name;
1414         profile = av_get_profile_name(p, enc->profile);
1415     } else if (enc->codec_id == CODEC_ID_MPEG2TS) {
1416         /* fake mpeg2 transport stream codec (currently not
1417            registered) */
1418         codec_name = "mpeg2ts";
1419     } else if (enc->codec_name[0] != '\0') {
1420         codec_name = enc->codec_name;
1421     } else {
1422         /* output avi tags */
1423         char tag_buf[32];
1424         av_get_codec_tag_string(tag_buf, sizeof(tag_buf), enc->codec_tag);
1425         snprintf(buf1, sizeof(buf1), "%s / 0x%04X", tag_buf, enc->codec_tag);
1426         codec_name = buf1;
1427     }
1428
1429     switch(enc->codec_type) {
1430     case AVMEDIA_TYPE_VIDEO:
1431         snprintf(buf, buf_size,
1432                  "Video: %s%s",
1433                  codec_name, enc->mb_decision ? " (hq)" : "");
1434         if (profile)
1435             snprintf(buf + strlen(buf), buf_size - strlen(buf),
1436                      " (%s)", profile);
1437         if (enc->pix_fmt != PIX_FMT_NONE) {
1438             snprintf(buf + strlen(buf), buf_size - strlen(buf),
1439                      ", %s",
1440                      av_get_pix_fmt_name(enc->pix_fmt));
1441         }
1442         if (enc->width) {
1443             snprintf(buf + strlen(buf), buf_size - strlen(buf),
1444                      ", %dx%d",
1445                      enc->width, enc->height);
1446             if (enc->sample_aspect_ratio.num) {
1447                 av_reduce(&display_aspect_ratio.num, &display_aspect_ratio.den,
1448                           enc->width*enc->sample_aspect_ratio.num,
1449                           enc->height*enc->sample_aspect_ratio.den,
1450                           1024*1024);
1451                 snprintf(buf + strlen(buf), buf_size - strlen(buf),
1452                          " [PAR %d:%d DAR %d:%d]",
1453                          enc->sample_aspect_ratio.num, enc->sample_aspect_ratio.den,
1454                          display_aspect_ratio.num, display_aspect_ratio.den);
1455             }
1456             if(av_log_get_level() >= AV_LOG_DEBUG){
1457                 int g= av_gcd(enc->time_base.num, enc->time_base.den);
1458                 snprintf(buf + strlen(buf), buf_size - strlen(buf),
1459                      ", %d/%d",
1460                      enc->time_base.num/g, enc->time_base.den/g);
1461             }
1462         }
1463         if (encode) {
1464             snprintf(buf + strlen(buf), buf_size - strlen(buf),
1465                      ", q=%d-%d", enc->qmin, enc->qmax);
1466         }
1467         break;
1468     case AVMEDIA_TYPE_AUDIO:
1469         snprintf(buf, buf_size,
1470                  "Audio: %s",
1471                  codec_name);
1472         if (profile)
1473             snprintf(buf + strlen(buf), buf_size - strlen(buf),
1474                      " (%s)", profile);
1475         if (enc->sample_rate) {
1476             snprintf(buf + strlen(buf), buf_size - strlen(buf),
1477                      ", %d Hz", enc->sample_rate);
1478         }
1479         av_strlcat(buf, ", ", buf_size);
1480         av_get_channel_layout_string(buf + strlen(buf), buf_size - strlen(buf), enc->channels, enc->channel_layout);
1481         if (enc->sample_fmt != AV_SAMPLE_FMT_NONE) {
1482             snprintf(buf + strlen(buf), buf_size - strlen(buf),
1483                      ", %s", av_get_sample_fmt_name(enc->sample_fmt));
1484         }
1485         break;
1486     case AVMEDIA_TYPE_DATA:
1487         snprintf(buf, buf_size, "Data: %s", codec_name);
1488         break;
1489     case AVMEDIA_TYPE_SUBTITLE:
1490         snprintf(buf, buf_size, "Subtitle: %s", codec_name);
1491         break;
1492     case AVMEDIA_TYPE_ATTACHMENT:
1493         snprintf(buf, buf_size, "Attachment: %s", codec_name);
1494         break;
1495     default:
1496         snprintf(buf, buf_size, "Invalid Codec type %d", enc->codec_type);
1497         return;
1498     }
1499     if (encode) {
1500         if (enc->flags & CODEC_FLAG_PASS1)
1501             snprintf(buf + strlen(buf), buf_size - strlen(buf),
1502                      ", pass 1");
1503         if (enc->flags & CODEC_FLAG_PASS2)
1504             snprintf(buf + strlen(buf), buf_size - strlen(buf),
1505                      ", pass 2");
1506     }
1507     bitrate = get_bit_rate(enc);
1508     if (bitrate != 0) {
1509         snprintf(buf + strlen(buf), buf_size - strlen(buf),
1510                  ", %d kb/s", bitrate / 1000);
1511     }
1512 }
1513
1514 const char *av_get_profile_name(const AVCodec *codec, int profile)
1515 {
1516     const AVProfile *p;
1517     if (profile == FF_PROFILE_UNKNOWN || !codec->profiles)
1518         return NULL;
1519
1520     for (p = codec->profiles; p->profile != FF_PROFILE_UNKNOWN; p++)
1521         if (p->profile == profile)
1522             return p->name;
1523
1524     return NULL;
1525 }
1526
1527 unsigned avcodec_version( void )
1528 {
1529   return LIBAVCODEC_VERSION_INT;
1530 }
1531
1532 const char *avcodec_configuration(void)
1533 {
1534     return LIBAV_CONFIGURATION;
1535 }
1536
1537 const char *avcodec_license(void)
1538 {
1539 #define LICENSE_PREFIX "libavcodec license: "
1540     return LICENSE_PREFIX LIBAV_LICENSE + sizeof(LICENSE_PREFIX) - 1;
1541 }
1542
1543 void avcodec_flush_buffers(AVCodecContext *avctx)
1544 {
1545     if(HAVE_THREADS && avctx->active_thread_type&FF_THREAD_FRAME)
1546         ff_thread_flush(avctx);
1547     else if(avctx->codec->flush)
1548         avctx->codec->flush(avctx);
1549 }
1550
1551 static void video_free_buffers(AVCodecContext *s)
1552 {
1553     AVCodecInternal *avci = s->internal;
1554     int i, j;
1555
1556     if (!avci->buffer)
1557         return;
1558
1559     if (avci->buffer_count)
1560         av_log(s, AV_LOG_WARNING, "Found %i unreleased buffers!\n",
1561                avci->buffer_count);
1562     for(i=0; i<INTERNAL_BUFFER_SIZE; i++){
1563         InternalBuffer *buf = &avci->buffer[i];
1564         for(j=0; j<4; j++){
1565             av_freep(&buf->base[j]);
1566             buf->data[j]= NULL;
1567         }
1568     }
1569     av_freep(&avci->buffer);
1570
1571     avci->buffer_count=0;
1572 }
1573
1574 static void audio_free_buffers(AVCodecContext *avctx)
1575 {
1576     AVCodecInternal *avci = avctx->internal;
1577     InternalBuffer *buf;
1578
1579     if (!avci->buffer)
1580         return;
1581     buf = avci->buffer;
1582
1583     if (buf->extended_data) {
1584         av_free(buf->extended_data[0]);
1585         if (buf->extended_data != buf->data)
1586             av_free(buf->extended_data);
1587     }
1588     av_freep(&avci->buffer);
1589 }
1590
1591 void avcodec_default_free_buffers(AVCodecContext *avctx)
1592 {
1593     switch (avctx->codec_type) {
1594     case AVMEDIA_TYPE_VIDEO:
1595         video_free_buffers(avctx);
1596         break;
1597     case AVMEDIA_TYPE_AUDIO:
1598         audio_free_buffers(avctx);
1599         break;
1600     default:
1601         break;
1602     }
1603 }
1604
1605 int av_get_bits_per_sample(enum CodecID codec_id){
1606     switch(codec_id){
1607     case CODEC_ID_ADPCM_SBPRO_2:
1608         return 2;
1609     case CODEC_ID_ADPCM_SBPRO_3:
1610         return 3;
1611     case CODEC_ID_ADPCM_SBPRO_4:
1612     case CODEC_ID_ADPCM_CT:
1613     case CODEC_ID_ADPCM_IMA_APC:
1614     case CODEC_ID_ADPCM_IMA_WAV:
1615     case CODEC_ID_ADPCM_IMA_QT:
1616     case CODEC_ID_ADPCM_SWF:
1617     case CODEC_ID_ADPCM_MS:
1618     case CODEC_ID_ADPCM_YAMAHA:
1619     case CODEC_ID_ADPCM_G722:
1620         return 4;
1621     case CODEC_ID_PCM_ALAW:
1622     case CODEC_ID_PCM_MULAW:
1623     case CODEC_ID_PCM_S8:
1624     case CODEC_ID_PCM_U8:
1625     case CODEC_ID_PCM_ZORK:
1626         return 8;
1627     case CODEC_ID_PCM_S16BE:
1628     case CODEC_ID_PCM_S16LE:
1629     case CODEC_ID_PCM_S16LE_PLANAR:
1630     case CODEC_ID_PCM_U16BE:
1631     case CODEC_ID_PCM_U16LE:
1632         return 16;
1633     case CODEC_ID_PCM_S24DAUD:
1634     case CODEC_ID_PCM_S24BE:
1635     case CODEC_ID_PCM_S24LE:
1636     case CODEC_ID_PCM_U24BE:
1637     case CODEC_ID_PCM_U24LE:
1638         return 24;
1639     case CODEC_ID_PCM_S32BE:
1640     case CODEC_ID_PCM_S32LE:
1641     case CODEC_ID_PCM_U32BE:
1642     case CODEC_ID_PCM_U32LE:
1643     case CODEC_ID_PCM_F32BE:
1644     case CODEC_ID_PCM_F32LE:
1645         return 32;
1646     case CODEC_ID_PCM_F64BE:
1647     case CODEC_ID_PCM_F64LE:
1648         return 64;
1649     default:
1650         return 0;
1651     }
1652 }
1653
1654 #if !HAVE_THREADS
1655 int ff_thread_init(AVCodecContext *s){
1656     return -1;
1657 }
1658 #endif
1659
1660 unsigned int av_xiphlacing(unsigned char *s, unsigned int v)
1661 {
1662     unsigned int n = 0;
1663
1664     while(v >= 0xff) {
1665         *s++ = 0xff;
1666         v -= 0xff;
1667         n++;
1668     }
1669     *s = v;
1670     n++;
1671     return n;
1672 }
1673
1674 int ff_match_2uint16(const uint16_t (*tab)[2], int size, int a, int b){
1675     int i;
1676     for(i=0; i<size && !(tab[i][0]==a && tab[i][1]==b); i++);
1677     return i;
1678 }
1679
1680 void av_log_missing_feature(void *avc, const char *feature, int want_sample)
1681 {
1682     av_log(avc, AV_LOG_WARNING, "%s not implemented. Update your Libav "
1683             "version to the newest one from Git. If the problem still "
1684             "occurs, it means that your file has a feature which has not "
1685             "been implemented.\n", feature);
1686     if(want_sample)
1687         av_log_ask_for_sample(avc, NULL);
1688 }
1689
1690 void av_log_ask_for_sample(void *avc, const char *msg, ...)
1691 {
1692     va_list argument_list;
1693
1694     va_start(argument_list, msg);
1695
1696     if (msg)
1697         av_vlog(avc, AV_LOG_WARNING, msg, argument_list);
1698     av_log(avc, AV_LOG_WARNING, "If you want to help, upload a sample "
1699             "of this file to ftp://upload.libav.org/incoming/ "
1700             "and contact the libav-devel mailing list.\n");
1701
1702     va_end(argument_list);
1703 }
1704
1705 static AVHWAccel *first_hwaccel = NULL;
1706
1707 void av_register_hwaccel(AVHWAccel *hwaccel)
1708 {
1709     AVHWAccel **p = &first_hwaccel;
1710     while (*p)
1711         p = &(*p)->next;
1712     *p = hwaccel;
1713     hwaccel->next = NULL;
1714 }
1715
1716 AVHWAccel *av_hwaccel_next(AVHWAccel *hwaccel)
1717 {
1718     return hwaccel ? hwaccel->next : first_hwaccel;
1719 }
1720
1721 AVHWAccel *ff_find_hwaccel(enum CodecID codec_id, enum PixelFormat pix_fmt)
1722 {
1723     AVHWAccel *hwaccel=NULL;
1724
1725     while((hwaccel= av_hwaccel_next(hwaccel))){
1726         if (   hwaccel->id      == codec_id
1727             && hwaccel->pix_fmt == pix_fmt)
1728             return hwaccel;
1729     }
1730     return NULL;
1731 }
1732
1733 int av_lockmgr_register(int (*cb)(void **mutex, enum AVLockOp op))
1734 {
1735     if (ff_lockmgr_cb) {
1736         if (ff_lockmgr_cb(&codec_mutex, AV_LOCK_DESTROY))
1737             return -1;
1738         if (ff_lockmgr_cb(&avformat_mutex, AV_LOCK_DESTROY))
1739             return -1;
1740     }
1741
1742     ff_lockmgr_cb = cb;
1743
1744     if (ff_lockmgr_cb) {
1745         if (ff_lockmgr_cb(&codec_mutex, AV_LOCK_CREATE))
1746             return -1;
1747         if (ff_lockmgr_cb(&avformat_mutex, AV_LOCK_CREATE))
1748             return -1;
1749     }
1750     return 0;
1751 }
1752
1753 int avpriv_lock_avformat(void)
1754 {
1755     if (ff_lockmgr_cb) {
1756         if ((*ff_lockmgr_cb)(&avformat_mutex, AV_LOCK_OBTAIN))
1757             return -1;
1758     }
1759     return 0;
1760 }
1761
1762 int avpriv_unlock_avformat(void)
1763 {
1764     if (ff_lockmgr_cb) {
1765         if ((*ff_lockmgr_cb)(&avformat_mutex, AV_LOCK_RELEASE))
1766             return -1;
1767     }
1768     return 0;
1769 }
1770
1771 unsigned int avpriv_toupper4(unsigned int x)
1772 {
1773     return     toupper( x     &0xFF)
1774             + (toupper((x>>8 )&0xFF)<<8 )
1775             + (toupper((x>>16)&0xFF)<<16)
1776             + (toupper((x>>24)&0xFF)<<24);
1777 }
1778
1779 #if !HAVE_THREADS
1780
1781 int ff_thread_get_buffer(AVCodecContext *avctx, AVFrame *f)
1782 {
1783     f->owner = avctx;
1784     return avctx->get_buffer(avctx, f);
1785 }
1786
1787 void ff_thread_release_buffer(AVCodecContext *avctx, AVFrame *f)
1788 {
1789     f->owner->release_buffer(f->owner, f);
1790 }
1791
1792 void ff_thread_finish_setup(AVCodecContext *avctx)
1793 {
1794 }
1795
1796 void ff_thread_report_progress(AVFrame *f, int progress, int field)
1797 {
1798 }
1799
1800 void ff_thread_await_progress(AVFrame *f, int progress, int field)
1801 {
1802 }
1803
1804 #endif
1805
1806 enum AVMediaType avcodec_get_type(enum CodecID codec_id)
1807 {
1808     if (codec_id <= CODEC_ID_NONE)
1809         return AVMEDIA_TYPE_UNKNOWN;
1810     else if (codec_id < CODEC_ID_FIRST_AUDIO)
1811         return AVMEDIA_TYPE_VIDEO;
1812     else if (codec_id < CODEC_ID_FIRST_SUBTITLE)
1813         return AVMEDIA_TYPE_AUDIO;
1814     else if (codec_id < CODEC_ID_FIRST_UNKNOWN)
1815         return AVMEDIA_TYPE_SUBTITLE;
1816
1817     return AVMEDIA_TYPE_UNKNOWN;
1818 }
1819
1820 int avcodec_is_open(AVCodecContext *s)
1821 {
1822     return !!s->internal;
1823 }