]> git.sesse.net Git - ffmpeg/blob - libavcodec/utils.c
sunrast: Add a sample request for TIFF, IFF, and Experimental Rastfile formats.
[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 (avctx->extradata_size < 0 || avctx->extradata_size >= FF_MAX_EXTRADATA_SIZE)
631         return AVERROR(EINVAL);
632
633     if (options)
634         av_dict_copy(&tmp, *options, 0);
635
636     /* If there is a user-supplied mutex locking routine, call it. */
637     if (ff_lockmgr_cb) {
638         if ((*ff_lockmgr_cb)(&codec_mutex, AV_LOCK_OBTAIN))
639             return -1;
640     }
641
642     entangled_thread_counter++;
643     if(entangled_thread_counter != 1){
644         av_log(avctx, AV_LOG_ERROR, "insufficient thread locking around avcodec_open/close()\n");
645         ret = -1;
646         goto end;
647     }
648
649     if(avctx->codec || !codec) {
650         ret = AVERROR(EINVAL);
651         goto end;
652     }
653
654     avctx->internal = av_mallocz(sizeof(AVCodecInternal));
655     if (!avctx->internal) {
656         ret = AVERROR(ENOMEM);
657         goto end;
658     }
659
660     if (codec->priv_data_size > 0) {
661       if(!avctx->priv_data){
662         avctx->priv_data = av_mallocz(codec->priv_data_size);
663         if (!avctx->priv_data) {
664             ret = AVERROR(ENOMEM);
665             goto end;
666         }
667         if (codec->priv_class) {
668             *(AVClass**)avctx->priv_data= codec->priv_class;
669             av_opt_set_defaults(avctx->priv_data);
670         }
671       }
672       if (codec->priv_class && (ret = av_opt_set_dict(avctx->priv_data, &tmp)) < 0)
673           goto free_and_end;
674     } else {
675         avctx->priv_data = NULL;
676     }
677     if ((ret = av_opt_set_dict(avctx, &tmp)) < 0)
678         goto free_and_end;
679
680     if(avctx->coded_width && avctx->coded_height)
681         avcodec_set_dimensions(avctx, avctx->coded_width, avctx->coded_height);
682     else if(avctx->width && avctx->height)
683         avcodec_set_dimensions(avctx, avctx->width, avctx->height);
684
685     if ((avctx->coded_width || avctx->coded_height || avctx->width || avctx->height)
686         && (  av_image_check_size(avctx->coded_width, avctx->coded_height, 0, avctx) < 0
687            || av_image_check_size(avctx->width,       avctx->height,       0, avctx) < 0)) {
688         av_log(avctx, AV_LOG_WARNING, "ignoring invalid width/height values\n");
689         avcodec_set_dimensions(avctx, 0, 0);
690     }
691
692     /* if the decoder init function was already called previously,
693        free the already allocated subtitle_header before overwriting it */
694     if (codec_is_decoder(codec))
695         av_freep(&avctx->subtitle_header);
696
697 #define SANE_NB_CHANNELS 128U
698     if (avctx->channels > SANE_NB_CHANNELS) {
699         ret = AVERROR(EINVAL);
700         goto free_and_end;
701     }
702
703     avctx->codec = codec;
704     if ((avctx->codec_type == AVMEDIA_TYPE_UNKNOWN || avctx->codec_type == codec->type) &&
705         avctx->codec_id == CODEC_ID_NONE) {
706         avctx->codec_type = codec->type;
707         avctx->codec_id   = codec->id;
708     }
709     if (avctx->codec_id != codec->id || (avctx->codec_type != codec->type
710                            && avctx->codec_type != AVMEDIA_TYPE_ATTACHMENT)) {
711         av_log(avctx, AV_LOG_ERROR, "codec type or id mismatches\n");
712         ret = AVERROR(EINVAL);
713         goto free_and_end;
714     }
715     avctx->frame_number = 0;
716
717     if (avctx->codec_type == AVMEDIA_TYPE_AUDIO &&
718         (!avctx->time_base.num || !avctx->time_base.den)) {
719         avctx->time_base.num = 1;
720         avctx->time_base.den = avctx->sample_rate;
721     }
722
723     if (HAVE_THREADS && !avctx->thread_opaque) {
724         ret = ff_thread_init(avctx);
725         if (ret < 0) {
726             goto free_and_end;
727         }
728     }
729     if (!HAVE_THREADS && !(codec->capabilities & CODEC_CAP_AUTO_THREADS))
730         avctx->thread_count = 1;
731
732     if (avctx->codec->max_lowres < avctx->lowres) {
733         av_log(avctx, AV_LOG_ERROR, "The maximum value for lowres supported by the decoder is %d\n",
734                avctx->codec->max_lowres);
735         ret = AVERROR(EINVAL);
736         goto free_and_end;
737     }
738     if (codec_is_encoder(avctx->codec)) {
739         int i;
740         if (avctx->codec->sample_fmts) {
741             for (i = 0; avctx->codec->sample_fmts[i] != AV_SAMPLE_FMT_NONE; i++)
742                 if (avctx->sample_fmt == avctx->codec->sample_fmts[i])
743                     break;
744             if (avctx->codec->sample_fmts[i] == AV_SAMPLE_FMT_NONE) {
745                 av_log(avctx, AV_LOG_ERROR, "Specified sample_fmt is not supported.\n");
746                 ret = AVERROR(EINVAL);
747                 goto free_and_end;
748             }
749         }
750         if (avctx->codec->supported_samplerates) {
751             for (i = 0; avctx->codec->supported_samplerates[i] != 0; i++)
752                 if (avctx->sample_rate == avctx->codec->supported_samplerates[i])
753                     break;
754             if (avctx->codec->supported_samplerates[i] == 0) {
755                 av_log(avctx, AV_LOG_ERROR, "Specified sample_rate is not supported\n");
756                 ret = AVERROR(EINVAL);
757                 goto free_and_end;
758             }
759         }
760         if (avctx->codec->channel_layouts) {
761             if (!avctx->channel_layout) {
762                 av_log(avctx, AV_LOG_WARNING, "channel_layout not specified\n");
763             } else {
764                 for (i = 0; avctx->codec->channel_layouts[i] != 0; i++)
765                     if (avctx->channel_layout == avctx->codec->channel_layouts[i])
766                         break;
767                 if (avctx->codec->channel_layouts[i] == 0) {
768                     av_log(avctx, AV_LOG_ERROR, "Specified channel_layout is not supported\n");
769                     ret = AVERROR(EINVAL);
770                     goto free_and_end;
771                 }
772             }
773         }
774         if (avctx->channel_layout && avctx->channels) {
775             if (av_get_channel_layout_nb_channels(avctx->channel_layout) != avctx->channels) {
776                 av_log(avctx, AV_LOG_ERROR, "channel layout does not match number of channels\n");
777                 ret = AVERROR(EINVAL);
778                 goto free_and_end;
779             }
780         } else if (avctx->channel_layout) {
781             avctx->channels = av_get_channel_layout_nb_channels(avctx->channel_layout);
782         }
783     }
784
785     if(avctx->codec->init && !(avctx->active_thread_type&FF_THREAD_FRAME)){
786         ret = avctx->codec->init(avctx);
787         if (ret < 0) {
788             goto free_and_end;
789         }
790     }
791 end:
792     entangled_thread_counter--;
793
794     /* Release any user-supplied mutex. */
795     if (ff_lockmgr_cb) {
796         (*ff_lockmgr_cb)(&codec_mutex, AV_LOCK_RELEASE);
797     }
798     if (options) {
799         av_dict_free(options);
800         *options = tmp;
801     }
802
803     return ret;
804 free_and_end:
805     av_dict_free(&tmp);
806     av_freep(&avctx->priv_data);
807     av_freep(&avctx->internal);
808     avctx->codec= NULL;
809     goto end;
810 }
811
812 int ff_alloc_packet(AVPacket *avpkt, int size)
813 {
814     if (size > INT_MAX - FF_INPUT_BUFFER_PADDING_SIZE)
815         return AVERROR(EINVAL);
816
817     if (avpkt->data) {
818         uint8_t *pkt_data;
819         int pkt_size;
820
821         if (avpkt->size < size)
822             return AVERROR(EINVAL);
823
824         pkt_data = avpkt->data;
825         pkt_size = avpkt->size;
826         av_init_packet(avpkt);
827         avpkt->data = pkt_data;
828         avpkt->size = pkt_size;
829         return 0;
830     } else {
831         return av_new_packet(avpkt, size);
832     }
833 }
834
835 int attribute_align_arg avcodec_encode_audio2(AVCodecContext *avctx,
836                                               AVPacket *avpkt,
837                                               const AVFrame *frame,
838                                               int *got_packet_ptr)
839 {
840     int ret;
841     int user_packet = !!avpkt->data;
842     int nb_samples;
843
844     if (!(avctx->codec->capabilities & CODEC_CAP_DELAY) && !frame) {
845         av_init_packet(avpkt);
846         avpkt->size = 0;
847         return 0;
848     }
849
850     /* check for valid frame size */
851     if (frame) {
852         nb_samples = frame->nb_samples;
853         if (avctx->codec->capabilities & CODEC_CAP_SMALL_LAST_FRAME) {
854             if (nb_samples > avctx->frame_size)
855                 return AVERROR(EINVAL);
856         } else if (!(avctx->codec->capabilities & CODEC_CAP_VARIABLE_FRAME_SIZE)) {
857             if (nb_samples != avctx->frame_size)
858                 return AVERROR(EINVAL);
859         }
860     } else {
861         nb_samples = avctx->frame_size;
862     }
863
864     if (avctx->codec->encode2) {
865         *got_packet_ptr = 0;
866         ret = avctx->codec->encode2(avctx, avpkt, frame, got_packet_ptr);
867         if (!ret && *got_packet_ptr &&
868             !(avctx->codec->capabilities & CODEC_CAP_DELAY)) {
869             avpkt->pts = frame->pts;
870             avpkt->duration = av_rescale_q(frame->nb_samples,
871                                            (AVRational){ 1, avctx->sample_rate },
872                                            avctx->time_base);
873         }
874     } else {
875         /* for compatibility with encoders not supporting encode2(), we need to
876            allocate a packet buffer if the user has not provided one or check
877            the size otherwise */
878         int fs_tmp   = 0;
879         int buf_size = avpkt->size;
880         if (!user_packet) {
881             if (avctx->codec->capabilities & CODEC_CAP_VARIABLE_FRAME_SIZE) {
882                 av_assert0(av_get_bits_per_sample(avctx->codec_id) != 0);
883                 buf_size = nb_samples * avctx->channels *
884                            av_get_bits_per_sample(avctx->codec_id) / 8;
885             } else {
886                 /* this is a guess as to the required size.
887                    if an encoder needs more than this, it should probably
888                    implement encode2() */
889                 buf_size = 2 * avctx->frame_size * avctx->channels *
890                            av_get_bytes_per_sample(avctx->sample_fmt);
891                 buf_size += FF_MIN_BUFFER_SIZE;
892             }
893         }
894         if ((ret = ff_alloc_packet(avpkt, buf_size)))
895             return ret;
896
897         /* Encoders using AVCodec.encode() that support
898            CODEC_CAP_SMALL_LAST_FRAME require avctx->frame_size to be set to
899            the smaller size when encoding the last frame.
900            This code can be removed once all encoders supporting
901            CODEC_CAP_SMALL_LAST_FRAME use encode2() */
902         if ((avctx->codec->capabilities & CODEC_CAP_SMALL_LAST_FRAME) &&
903             nb_samples < avctx->frame_size) {
904             fs_tmp = avctx->frame_size;
905             avctx->frame_size = nb_samples;
906         }
907
908         /* encode the frame */
909         ret = avctx->codec->encode(avctx, avpkt->data, avpkt->size,
910                                    frame ? frame->data[0] : NULL);
911         if (ret >= 0) {
912             if (!ret) {
913                 /* no output. if the packet data was allocated by libavcodec,
914                    free it */
915                 if (!user_packet)
916                     av_freep(&avpkt->data);
917             } else {
918                 if (avctx->coded_frame)
919                     avpkt->pts = avctx->coded_frame->pts;
920                 /* Set duration for final small packet. This can be removed
921                    once all encoders supporting CODEC_CAP_SMALL_LAST_FRAME use
922                    encode2() */
923                 if (fs_tmp) {
924                     avpkt->duration = av_rescale_q(avctx->frame_size,
925                                                    (AVRational){ 1, avctx->sample_rate },
926                                                    avctx->time_base);
927                 }
928             }
929             avpkt->size = ret;
930             *got_packet_ptr = (ret > 0);
931             ret = 0;
932         }
933
934         if (fs_tmp)
935             avctx->frame_size = fs_tmp;
936     }
937     if (!ret)
938         avctx->frame_number++;
939
940     /* NOTE: if we add any audio encoders which output non-keyframe packets,
941              this needs to be moved to the encoders, but for now we can do it
942              here to simplify things */
943     avpkt->flags |= AV_PKT_FLAG_KEY;
944
945     return ret;
946 }
947
948 #if FF_API_OLD_DECODE_AUDIO
949 int attribute_align_arg avcodec_encode_audio(AVCodecContext *avctx,
950                                              uint8_t *buf, int buf_size,
951                                              const short *samples)
952 {
953     AVPacket pkt;
954     AVFrame frame0;
955     AVFrame *frame;
956     int ret, samples_size, got_packet;
957
958     av_init_packet(&pkt);
959     pkt.data = buf;
960     pkt.size = buf_size;
961
962     if (samples) {
963         frame = &frame0;
964         avcodec_get_frame_defaults(frame);
965
966         if (avctx->frame_size) {
967             frame->nb_samples = avctx->frame_size;
968         } else {
969             /* if frame_size is not set, the number of samples must be
970                calculated from the buffer size */
971             int64_t nb_samples;
972             if (!av_get_bits_per_sample(avctx->codec_id)) {
973                 av_log(avctx, AV_LOG_ERROR, "avcodec_encode_audio() does not "
974                        "support this codec\n");
975                 return AVERROR(EINVAL);
976             }
977             nb_samples = (int64_t)buf_size * 8 /
978                          (av_get_bits_per_sample(avctx->codec_id) *
979                          avctx->channels);
980             if (nb_samples >= INT_MAX)
981                 return AVERROR(EINVAL);
982             frame->nb_samples = nb_samples;
983         }
984
985         /* it is assumed that the samples buffer is large enough based on the
986            relevant parameters */
987         samples_size = av_samples_get_buffer_size(NULL, avctx->channels,
988                                                   frame->nb_samples,
989                                                   avctx->sample_fmt, 1);
990         if ((ret = avcodec_fill_audio_frame(frame, avctx->channels,
991                                             avctx->sample_fmt,
992                                             samples, samples_size, 1)))
993             return ret;
994
995         /* fabricate frame pts from sample count.
996            this is needed because the avcodec_encode_audio() API does not have
997            a way for the user to provide pts */
998         frame->pts = av_rescale_q(avctx->internal->sample_count,
999                                   (AVRational){ 1, avctx->sample_rate },
1000                                   avctx->time_base);
1001         avctx->internal->sample_count += frame->nb_samples;
1002     } else {
1003         frame = NULL;
1004     }
1005
1006     got_packet = 0;
1007     ret = avcodec_encode_audio2(avctx, &pkt, frame, &got_packet);
1008     if (!ret && got_packet && avctx->coded_frame) {
1009         avctx->coded_frame->pts       = pkt.pts;
1010         avctx->coded_frame->key_frame = !!(pkt.flags & AV_PKT_FLAG_KEY);
1011     }
1012     /* free any side data since we cannot return it */
1013     if (pkt.side_data_elems > 0) {
1014         int i;
1015         for (i = 0; i < pkt.side_data_elems; i++)
1016             av_free(pkt.side_data[i].data);
1017         av_freep(&pkt.side_data);
1018         pkt.side_data_elems = 0;
1019     }
1020
1021     if (frame && frame->extended_data != frame->data)
1022         av_free(frame->extended_data);
1023
1024     return ret ? ret : pkt.size;
1025 }
1026 #endif
1027
1028 int attribute_align_arg avcodec_encode_video(AVCodecContext *avctx, uint8_t *buf, int buf_size,
1029                          const AVFrame *pict)
1030 {
1031     if(buf_size < FF_MIN_BUFFER_SIZE){
1032         av_log(avctx, AV_LOG_ERROR, "buffer smaller than minimum size\n");
1033         return -1;
1034     }
1035     if(av_image_check_size(avctx->width, avctx->height, 0, avctx))
1036         return -1;
1037     if((avctx->codec->capabilities & CODEC_CAP_DELAY) || pict){
1038         int ret = avctx->codec->encode(avctx, buf, buf_size, pict);
1039         avctx->frame_number++;
1040         emms_c(); //needed to avoid an emms_c() call before every return;
1041
1042         return ret;
1043     }else
1044         return 0;
1045 }
1046
1047 int avcodec_encode_subtitle(AVCodecContext *avctx, uint8_t *buf, int buf_size,
1048                             const AVSubtitle *sub)
1049 {
1050     int ret;
1051     if(sub->start_display_time) {
1052         av_log(avctx, AV_LOG_ERROR, "start_display_time must be 0.\n");
1053         return -1;
1054     }
1055     if(sub->num_rects == 0 || !sub->rects)
1056         return -1;
1057     ret = avctx->codec->encode(avctx, buf, buf_size, sub);
1058     avctx->frame_number++;
1059     return ret;
1060 }
1061
1062 static void apply_param_change(AVCodecContext *avctx, AVPacket *avpkt)
1063 {
1064     int size = 0;
1065     const uint8_t *data;
1066     uint32_t flags;
1067
1068     if (!(avctx->codec->capabilities & CODEC_CAP_PARAM_CHANGE))
1069         return;
1070
1071     data = av_packet_get_side_data(avpkt, AV_PKT_DATA_PARAM_CHANGE, &size);
1072     if (!data || size < 4)
1073         return;
1074     flags = bytestream_get_le32(&data);
1075     size -= 4;
1076     if (size < 4) /* Required for any of the changes */
1077         return;
1078     if (flags & AV_SIDE_DATA_PARAM_CHANGE_CHANNEL_COUNT) {
1079         avctx->channels = bytestream_get_le32(&data);
1080         size -= 4;
1081     }
1082     if (flags & AV_SIDE_DATA_PARAM_CHANGE_CHANNEL_LAYOUT) {
1083         if (size < 8)
1084             return;
1085         avctx->channel_layout = bytestream_get_le64(&data);
1086         size -= 8;
1087     }
1088     if (size < 4)
1089         return;
1090     if (flags & AV_SIDE_DATA_PARAM_CHANGE_SAMPLE_RATE) {
1091         avctx->sample_rate = bytestream_get_le32(&data);
1092         size -= 4;
1093     }
1094     if (flags & AV_SIDE_DATA_PARAM_CHANGE_DIMENSIONS) {
1095         if (size < 8)
1096             return;
1097         avctx->width  = bytestream_get_le32(&data);
1098         avctx->height = bytestream_get_le32(&data);
1099         avcodec_set_dimensions(avctx, avctx->width, avctx->height);
1100         size -= 8;
1101     }
1102 }
1103
1104 int attribute_align_arg avcodec_decode_video2(AVCodecContext *avctx, AVFrame *picture,
1105                          int *got_picture_ptr,
1106                          AVPacket *avpkt)
1107 {
1108     int ret;
1109
1110     *got_picture_ptr= 0;
1111     if((avctx->coded_width||avctx->coded_height) && av_image_check_size(avctx->coded_width, avctx->coded_height, 0, avctx))
1112         return -1;
1113
1114     avctx->pkt = avpkt;
1115     apply_param_change(avctx, avpkt);
1116
1117     if((avctx->codec->capabilities & CODEC_CAP_DELAY) || avpkt->size || (avctx->active_thread_type&FF_THREAD_FRAME)){
1118         if (HAVE_THREADS && avctx->active_thread_type&FF_THREAD_FRAME)
1119              ret = ff_thread_decode_frame(avctx, picture, got_picture_ptr,
1120                                           avpkt);
1121         else {
1122             ret = avctx->codec->decode(avctx, picture, got_picture_ptr,
1123                               avpkt);
1124             picture->pkt_dts= avpkt->dts;
1125             picture->sample_aspect_ratio = avctx->sample_aspect_ratio;
1126             picture->width  = avctx->width;
1127             picture->height = avctx->height;
1128             picture->format = avctx->pix_fmt;
1129         }
1130
1131         emms_c(); //needed to avoid an emms_c() call before every return;
1132
1133         if (*got_picture_ptr)
1134             avctx->frame_number++;
1135     }else
1136         ret= 0;
1137
1138     return ret;
1139 }
1140
1141 #if FF_API_OLD_DECODE_AUDIO
1142 int attribute_align_arg avcodec_decode_audio3(AVCodecContext *avctx, int16_t *samples,
1143                          int *frame_size_ptr,
1144                          AVPacket *avpkt)
1145 {
1146     AVFrame frame;
1147     int ret, got_frame = 0;
1148
1149     if (avctx->get_buffer != avcodec_default_get_buffer) {
1150         av_log(avctx, AV_LOG_ERROR, "Custom get_buffer() for use with"
1151                "avcodec_decode_audio3() detected. Overriding with avcodec_default_get_buffer\n");
1152         av_log(avctx, AV_LOG_ERROR, "Please port your application to "
1153                "avcodec_decode_audio4()\n");
1154         avctx->get_buffer = avcodec_default_get_buffer;
1155     }
1156
1157     ret = avcodec_decode_audio4(avctx, &frame, &got_frame, avpkt);
1158
1159     if (ret >= 0 && got_frame) {
1160         int ch, plane_size;
1161         int planar = av_sample_fmt_is_planar(avctx->sample_fmt);
1162         int data_size = av_samples_get_buffer_size(&plane_size, avctx->channels,
1163                                                    frame.nb_samples,
1164                                                    avctx->sample_fmt, 1);
1165         if (*frame_size_ptr < data_size) {
1166             av_log(avctx, AV_LOG_ERROR, "output buffer size is too small for "
1167                    "the current frame (%d < %d)\n", *frame_size_ptr, data_size);
1168             return AVERROR(EINVAL);
1169         }
1170
1171         memcpy(samples, frame.extended_data[0], plane_size);
1172
1173         if (planar && avctx->channels > 1) {
1174             uint8_t *out = ((uint8_t *)samples) + plane_size;
1175             for (ch = 1; ch < avctx->channels; ch++) {
1176                 memcpy(out, frame.extended_data[ch], plane_size);
1177                 out += plane_size;
1178             }
1179         }
1180         *frame_size_ptr = data_size;
1181     } else {
1182         *frame_size_ptr = 0;
1183     }
1184     return ret;
1185 }
1186 #endif
1187
1188 int attribute_align_arg avcodec_decode_audio4(AVCodecContext *avctx,
1189                                               AVFrame *frame,
1190                                               int *got_frame_ptr,
1191                                               AVPacket *avpkt)
1192 {
1193     int ret = 0;
1194
1195     *got_frame_ptr = 0;
1196
1197     avctx->pkt = avpkt;
1198
1199     if (!avpkt->data && avpkt->size) {
1200         av_log(avctx, AV_LOG_ERROR, "invalid packet: NULL data, size != 0\n");
1201         return AVERROR(EINVAL);
1202     }
1203
1204     apply_param_change(avctx, avpkt);
1205
1206     if ((avctx->codec->capabilities & CODEC_CAP_DELAY) || avpkt->size) {
1207         ret = avctx->codec->decode(avctx, frame, got_frame_ptr, avpkt);
1208         if (ret >= 0 && *got_frame_ptr) {
1209             avctx->frame_number++;
1210             frame->pkt_dts = avpkt->dts;
1211             if (frame->format == AV_SAMPLE_FMT_NONE)
1212                 frame->format = avctx->sample_fmt;
1213         }
1214     }
1215     return ret;
1216 }
1217
1218 int avcodec_decode_subtitle2(AVCodecContext *avctx, AVSubtitle *sub,
1219                             int *got_sub_ptr,
1220                             AVPacket *avpkt)
1221 {
1222     int ret;
1223
1224     avctx->pkt = avpkt;
1225     *got_sub_ptr = 0;
1226     ret = avctx->codec->decode(avctx, sub, got_sub_ptr, avpkt);
1227     if (*got_sub_ptr)
1228         avctx->frame_number++;
1229     return ret;
1230 }
1231
1232 void avsubtitle_free(AVSubtitle *sub)
1233 {
1234     int i;
1235
1236     for (i = 0; i < sub->num_rects; i++)
1237     {
1238         av_freep(&sub->rects[i]->pict.data[0]);
1239         av_freep(&sub->rects[i]->pict.data[1]);
1240         av_freep(&sub->rects[i]->pict.data[2]);
1241         av_freep(&sub->rects[i]->pict.data[3]);
1242         av_freep(&sub->rects[i]->text);
1243         av_freep(&sub->rects[i]->ass);
1244         av_freep(&sub->rects[i]);
1245     }
1246
1247     av_freep(&sub->rects);
1248
1249     memset(sub, 0, sizeof(AVSubtitle));
1250 }
1251
1252 av_cold int avcodec_close(AVCodecContext *avctx)
1253 {
1254     /* If there is a user-supplied mutex locking routine, call it. */
1255     if (ff_lockmgr_cb) {
1256         if ((*ff_lockmgr_cb)(&codec_mutex, AV_LOCK_OBTAIN))
1257             return -1;
1258     }
1259
1260     entangled_thread_counter++;
1261     if(entangled_thread_counter != 1){
1262         av_log(avctx, AV_LOG_ERROR, "insufficient thread locking around avcodec_open/close()\n");
1263         entangled_thread_counter--;
1264         return -1;
1265     }
1266
1267     if (HAVE_THREADS && avctx->thread_opaque)
1268         ff_thread_free(avctx);
1269     if (avctx->codec && avctx->codec->close)
1270         avctx->codec->close(avctx);
1271     avcodec_default_free_buffers(avctx);
1272     avctx->coded_frame = NULL;
1273     av_freep(&avctx->internal);
1274     if (avctx->codec && avctx->codec->priv_class)
1275         av_opt_free(avctx->priv_data);
1276     av_opt_free(avctx);
1277     av_freep(&avctx->priv_data);
1278     if (codec_is_encoder(avctx->codec))
1279         av_freep(&avctx->extradata);
1280     avctx->codec = NULL;
1281     avctx->active_thread_type = 0;
1282     entangled_thread_counter--;
1283
1284     /* Release any user-supplied mutex. */
1285     if (ff_lockmgr_cb) {
1286         (*ff_lockmgr_cb)(&codec_mutex, AV_LOCK_RELEASE);
1287     }
1288     return 0;
1289 }
1290
1291 AVCodec *avcodec_find_encoder(enum CodecID id)
1292 {
1293     AVCodec *p, *experimental=NULL;
1294     p = first_avcodec;
1295     while (p) {
1296         if (codec_is_encoder(p) && p->id == id) {
1297             if (p->capabilities & CODEC_CAP_EXPERIMENTAL && !experimental) {
1298                 experimental = p;
1299             } else
1300                 return p;
1301         }
1302         p = p->next;
1303     }
1304     return experimental;
1305 }
1306
1307 AVCodec *avcodec_find_encoder_by_name(const char *name)
1308 {
1309     AVCodec *p;
1310     if (!name)
1311         return NULL;
1312     p = first_avcodec;
1313     while (p) {
1314         if (codec_is_encoder(p) && strcmp(name,p->name) == 0)
1315             return p;
1316         p = p->next;
1317     }
1318     return NULL;
1319 }
1320
1321 AVCodec *avcodec_find_decoder(enum CodecID id)
1322 {
1323     AVCodec *p;
1324     p = first_avcodec;
1325     while (p) {
1326         if (codec_is_decoder(p) && p->id == id)
1327             return p;
1328         p = p->next;
1329     }
1330     return NULL;
1331 }
1332
1333 AVCodec *avcodec_find_decoder_by_name(const char *name)
1334 {
1335     AVCodec *p;
1336     if (!name)
1337         return NULL;
1338     p = first_avcodec;
1339     while (p) {
1340         if (codec_is_decoder(p) && strcmp(name,p->name) == 0)
1341             return p;
1342         p = p->next;
1343     }
1344     return NULL;
1345 }
1346
1347 static int get_bit_rate(AVCodecContext *ctx)
1348 {
1349     int bit_rate;
1350     int bits_per_sample;
1351
1352     switch(ctx->codec_type) {
1353     case AVMEDIA_TYPE_VIDEO:
1354     case AVMEDIA_TYPE_DATA:
1355     case AVMEDIA_TYPE_SUBTITLE:
1356     case AVMEDIA_TYPE_ATTACHMENT:
1357         bit_rate = ctx->bit_rate;
1358         break;
1359     case AVMEDIA_TYPE_AUDIO:
1360         bits_per_sample = av_get_bits_per_sample(ctx->codec_id);
1361         bit_rate = bits_per_sample ? ctx->sample_rate * ctx->channels * bits_per_sample : ctx->bit_rate;
1362         break;
1363     default:
1364         bit_rate = 0;
1365         break;
1366     }
1367     return bit_rate;
1368 }
1369
1370 size_t av_get_codec_tag_string(char *buf, size_t buf_size, unsigned int codec_tag)
1371 {
1372     int i, len, ret = 0;
1373
1374     for (i = 0; i < 4; i++) {
1375         len = snprintf(buf, buf_size,
1376                        isprint(codec_tag&0xFF) ? "%c" : "[%d]", codec_tag&0xFF);
1377         buf      += len;
1378         buf_size  = buf_size > len ? buf_size - len : 0;
1379         ret      += len;
1380         codec_tag>>=8;
1381     }
1382     return ret;
1383 }
1384
1385 void avcodec_string(char *buf, int buf_size, AVCodecContext *enc, int encode)
1386 {
1387     const char *codec_name;
1388     const char *profile = NULL;
1389     AVCodec *p;
1390     char buf1[32];
1391     int bitrate;
1392     AVRational display_aspect_ratio;
1393
1394     if (encode)
1395         p = avcodec_find_encoder(enc->codec_id);
1396     else
1397         p = avcodec_find_decoder(enc->codec_id);
1398
1399     if (p) {
1400         codec_name = p->name;
1401         profile = av_get_profile_name(p, enc->profile);
1402     } else if (enc->codec_id == CODEC_ID_MPEG2TS) {
1403         /* fake mpeg2 transport stream codec (currently not
1404            registered) */
1405         codec_name = "mpeg2ts";
1406     } else if (enc->codec_name[0] != '\0') {
1407         codec_name = enc->codec_name;
1408     } else {
1409         /* output avi tags */
1410         char tag_buf[32];
1411         av_get_codec_tag_string(tag_buf, sizeof(tag_buf), enc->codec_tag);
1412         snprintf(buf1, sizeof(buf1), "%s / 0x%04X", tag_buf, enc->codec_tag);
1413         codec_name = buf1;
1414     }
1415
1416     switch(enc->codec_type) {
1417     case AVMEDIA_TYPE_VIDEO:
1418         snprintf(buf, buf_size,
1419                  "Video: %s%s",
1420                  codec_name, enc->mb_decision ? " (hq)" : "");
1421         if (profile)
1422             snprintf(buf + strlen(buf), buf_size - strlen(buf),
1423                      " (%s)", profile);
1424         if (enc->pix_fmt != PIX_FMT_NONE) {
1425             snprintf(buf + strlen(buf), buf_size - strlen(buf),
1426                      ", %s",
1427                      av_get_pix_fmt_name(enc->pix_fmt));
1428         }
1429         if (enc->width) {
1430             snprintf(buf + strlen(buf), buf_size - strlen(buf),
1431                      ", %dx%d",
1432                      enc->width, enc->height);
1433             if (enc->sample_aspect_ratio.num) {
1434                 av_reduce(&display_aspect_ratio.num, &display_aspect_ratio.den,
1435                           enc->width*enc->sample_aspect_ratio.num,
1436                           enc->height*enc->sample_aspect_ratio.den,
1437                           1024*1024);
1438                 snprintf(buf + strlen(buf), buf_size - strlen(buf),
1439                          " [PAR %d:%d DAR %d:%d]",
1440                          enc->sample_aspect_ratio.num, enc->sample_aspect_ratio.den,
1441                          display_aspect_ratio.num, display_aspect_ratio.den);
1442             }
1443             if(av_log_get_level() >= AV_LOG_DEBUG){
1444                 int g= av_gcd(enc->time_base.num, enc->time_base.den);
1445                 snprintf(buf + strlen(buf), buf_size - strlen(buf),
1446                      ", %d/%d",
1447                      enc->time_base.num/g, enc->time_base.den/g);
1448             }
1449         }
1450         if (encode) {
1451             snprintf(buf + strlen(buf), buf_size - strlen(buf),
1452                      ", q=%d-%d", enc->qmin, enc->qmax);
1453         }
1454         break;
1455     case AVMEDIA_TYPE_AUDIO:
1456         snprintf(buf, buf_size,
1457                  "Audio: %s",
1458                  codec_name);
1459         if (profile)
1460             snprintf(buf + strlen(buf), buf_size - strlen(buf),
1461                      " (%s)", profile);
1462         if (enc->sample_rate) {
1463             snprintf(buf + strlen(buf), buf_size - strlen(buf),
1464                      ", %d Hz", enc->sample_rate);
1465         }
1466         av_strlcat(buf, ", ", buf_size);
1467         av_get_channel_layout_string(buf + strlen(buf), buf_size - strlen(buf), enc->channels, enc->channel_layout);
1468         if (enc->sample_fmt != AV_SAMPLE_FMT_NONE) {
1469             snprintf(buf + strlen(buf), buf_size - strlen(buf),
1470                      ", %s", av_get_sample_fmt_name(enc->sample_fmt));
1471         }
1472         break;
1473     case AVMEDIA_TYPE_DATA:
1474         snprintf(buf, buf_size, "Data: %s", codec_name);
1475         break;
1476     case AVMEDIA_TYPE_SUBTITLE:
1477         snprintf(buf, buf_size, "Subtitle: %s", codec_name);
1478         break;
1479     case AVMEDIA_TYPE_ATTACHMENT:
1480         snprintf(buf, buf_size, "Attachment: %s", codec_name);
1481         break;
1482     default:
1483         snprintf(buf, buf_size, "Invalid Codec type %d", enc->codec_type);
1484         return;
1485     }
1486     if (encode) {
1487         if (enc->flags & CODEC_FLAG_PASS1)
1488             snprintf(buf + strlen(buf), buf_size - strlen(buf),
1489                      ", pass 1");
1490         if (enc->flags & CODEC_FLAG_PASS2)
1491             snprintf(buf + strlen(buf), buf_size - strlen(buf),
1492                      ", pass 2");
1493     }
1494     bitrate = get_bit_rate(enc);
1495     if (bitrate != 0) {
1496         snprintf(buf + strlen(buf), buf_size - strlen(buf),
1497                  ", %d kb/s", bitrate / 1000);
1498     }
1499 }
1500
1501 const char *av_get_profile_name(const AVCodec *codec, int profile)
1502 {
1503     const AVProfile *p;
1504     if (profile == FF_PROFILE_UNKNOWN || !codec->profiles)
1505         return NULL;
1506
1507     for (p = codec->profiles; p->profile != FF_PROFILE_UNKNOWN; p++)
1508         if (p->profile == profile)
1509             return p->name;
1510
1511     return NULL;
1512 }
1513
1514 unsigned avcodec_version( void )
1515 {
1516   return LIBAVCODEC_VERSION_INT;
1517 }
1518
1519 const char *avcodec_configuration(void)
1520 {
1521     return LIBAV_CONFIGURATION;
1522 }
1523
1524 const char *avcodec_license(void)
1525 {
1526 #define LICENSE_PREFIX "libavcodec license: "
1527     return LICENSE_PREFIX LIBAV_LICENSE + sizeof(LICENSE_PREFIX) - 1;
1528 }
1529
1530 void avcodec_flush_buffers(AVCodecContext *avctx)
1531 {
1532     if(HAVE_THREADS && avctx->active_thread_type&FF_THREAD_FRAME)
1533         ff_thread_flush(avctx);
1534     else if(avctx->codec->flush)
1535         avctx->codec->flush(avctx);
1536 }
1537
1538 static void video_free_buffers(AVCodecContext *s)
1539 {
1540     AVCodecInternal *avci = s->internal;
1541     int i, j;
1542
1543     if (!avci->buffer)
1544         return;
1545
1546     if (avci->buffer_count)
1547         av_log(s, AV_LOG_WARNING, "Found %i unreleased buffers!\n",
1548                avci->buffer_count);
1549     for(i=0; i<INTERNAL_BUFFER_SIZE; i++){
1550         InternalBuffer *buf = &avci->buffer[i];
1551         for(j=0; j<4; j++){
1552             av_freep(&buf->base[j]);
1553             buf->data[j]= NULL;
1554         }
1555     }
1556     av_freep(&avci->buffer);
1557
1558     avci->buffer_count=0;
1559 }
1560
1561 static void audio_free_buffers(AVCodecContext *avctx)
1562 {
1563     AVCodecInternal *avci = avctx->internal;
1564     InternalBuffer *buf;
1565
1566     if (!avci->buffer)
1567         return;
1568     buf = avci->buffer;
1569
1570     if (buf->extended_data) {
1571         av_free(buf->extended_data[0]);
1572         if (buf->extended_data != buf->data)
1573             av_free(buf->extended_data);
1574     }
1575     av_freep(&avci->buffer);
1576 }
1577
1578 void avcodec_default_free_buffers(AVCodecContext *avctx)
1579 {
1580     switch (avctx->codec_type) {
1581     case AVMEDIA_TYPE_VIDEO:
1582         video_free_buffers(avctx);
1583         break;
1584     case AVMEDIA_TYPE_AUDIO:
1585         audio_free_buffers(avctx);
1586         break;
1587     default:
1588         break;
1589     }
1590 }
1591
1592 int av_get_bits_per_sample(enum CodecID codec_id){
1593     switch(codec_id){
1594     case CODEC_ID_ADPCM_SBPRO_2:
1595         return 2;
1596     case CODEC_ID_ADPCM_SBPRO_3:
1597         return 3;
1598     case CODEC_ID_ADPCM_SBPRO_4:
1599     case CODEC_ID_ADPCM_CT:
1600     case CODEC_ID_ADPCM_IMA_APC:
1601     case CODEC_ID_ADPCM_IMA_WAV:
1602     case CODEC_ID_ADPCM_IMA_QT:
1603     case CODEC_ID_ADPCM_SWF:
1604     case CODEC_ID_ADPCM_MS:
1605     case CODEC_ID_ADPCM_YAMAHA:
1606     case CODEC_ID_ADPCM_G722:
1607         return 4;
1608     case CODEC_ID_PCM_ALAW:
1609     case CODEC_ID_PCM_MULAW:
1610     case CODEC_ID_PCM_S8:
1611     case CODEC_ID_PCM_U8:
1612     case CODEC_ID_PCM_ZORK:
1613         return 8;
1614     case CODEC_ID_PCM_S16BE:
1615     case CODEC_ID_PCM_S16LE:
1616     case CODEC_ID_PCM_S16LE_PLANAR:
1617     case CODEC_ID_PCM_U16BE:
1618     case CODEC_ID_PCM_U16LE:
1619         return 16;
1620     case CODEC_ID_PCM_S24DAUD:
1621     case CODEC_ID_PCM_S24BE:
1622     case CODEC_ID_PCM_S24LE:
1623     case CODEC_ID_PCM_U24BE:
1624     case CODEC_ID_PCM_U24LE:
1625         return 24;
1626     case CODEC_ID_PCM_S32BE:
1627     case CODEC_ID_PCM_S32LE:
1628     case CODEC_ID_PCM_U32BE:
1629     case CODEC_ID_PCM_U32LE:
1630     case CODEC_ID_PCM_F32BE:
1631     case CODEC_ID_PCM_F32LE:
1632         return 32;
1633     case CODEC_ID_PCM_F64BE:
1634     case CODEC_ID_PCM_F64LE:
1635         return 64;
1636     default:
1637         return 0;
1638     }
1639 }
1640
1641 #if !HAVE_THREADS
1642 int ff_thread_init(AVCodecContext *s){
1643     return -1;
1644 }
1645 #endif
1646
1647 unsigned int av_xiphlacing(unsigned char *s, unsigned int v)
1648 {
1649     unsigned int n = 0;
1650
1651     while(v >= 0xff) {
1652         *s++ = 0xff;
1653         v -= 0xff;
1654         n++;
1655     }
1656     *s = v;
1657     n++;
1658     return n;
1659 }
1660
1661 int ff_match_2uint16(const uint16_t (*tab)[2], int size, int a, int b){
1662     int i;
1663     for(i=0; i<size && !(tab[i][0]==a && tab[i][1]==b); i++);
1664     return i;
1665 }
1666
1667 void av_log_missing_feature(void *avc, const char *feature, int want_sample)
1668 {
1669     av_log(avc, AV_LOG_WARNING, "%s not implemented. Update your Libav "
1670             "version to the newest one from Git. If the problem still "
1671             "occurs, it means that your file has a feature which has not "
1672             "been implemented.\n", feature);
1673     if(want_sample)
1674         av_log_ask_for_sample(avc, NULL);
1675 }
1676
1677 void av_log_ask_for_sample(void *avc, const char *msg, ...)
1678 {
1679     va_list argument_list;
1680
1681     va_start(argument_list, msg);
1682
1683     if (msg)
1684         av_vlog(avc, AV_LOG_WARNING, msg, argument_list);
1685     av_log(avc, AV_LOG_WARNING, "If you want to help, upload a sample "
1686             "of this file to ftp://upload.libav.org/incoming/ "
1687             "and contact the libav-devel mailing list.\n");
1688
1689     va_end(argument_list);
1690 }
1691
1692 static AVHWAccel *first_hwaccel = NULL;
1693
1694 void av_register_hwaccel(AVHWAccel *hwaccel)
1695 {
1696     AVHWAccel **p = &first_hwaccel;
1697     while (*p)
1698         p = &(*p)->next;
1699     *p = hwaccel;
1700     hwaccel->next = NULL;
1701 }
1702
1703 AVHWAccel *av_hwaccel_next(AVHWAccel *hwaccel)
1704 {
1705     return hwaccel ? hwaccel->next : first_hwaccel;
1706 }
1707
1708 AVHWAccel *ff_find_hwaccel(enum CodecID codec_id, enum PixelFormat pix_fmt)
1709 {
1710     AVHWAccel *hwaccel=NULL;
1711
1712     while((hwaccel= av_hwaccel_next(hwaccel))){
1713         if (   hwaccel->id      == codec_id
1714             && hwaccel->pix_fmt == pix_fmt)
1715             return hwaccel;
1716     }
1717     return NULL;
1718 }
1719
1720 int av_lockmgr_register(int (*cb)(void **mutex, enum AVLockOp op))
1721 {
1722     if (ff_lockmgr_cb) {
1723         if (ff_lockmgr_cb(&codec_mutex, AV_LOCK_DESTROY))
1724             return -1;
1725         if (ff_lockmgr_cb(&avformat_mutex, AV_LOCK_DESTROY))
1726             return -1;
1727     }
1728
1729     ff_lockmgr_cb = cb;
1730
1731     if (ff_lockmgr_cb) {
1732         if (ff_lockmgr_cb(&codec_mutex, AV_LOCK_CREATE))
1733             return -1;
1734         if (ff_lockmgr_cb(&avformat_mutex, AV_LOCK_CREATE))
1735             return -1;
1736     }
1737     return 0;
1738 }
1739
1740 int avpriv_lock_avformat(void)
1741 {
1742     if (ff_lockmgr_cb) {
1743         if ((*ff_lockmgr_cb)(&avformat_mutex, AV_LOCK_OBTAIN))
1744             return -1;
1745     }
1746     return 0;
1747 }
1748
1749 int avpriv_unlock_avformat(void)
1750 {
1751     if (ff_lockmgr_cb) {
1752         if ((*ff_lockmgr_cb)(&avformat_mutex, AV_LOCK_RELEASE))
1753             return -1;
1754     }
1755     return 0;
1756 }
1757
1758 unsigned int avpriv_toupper4(unsigned int x)
1759 {
1760     return     toupper( x     &0xFF)
1761             + (toupper((x>>8 )&0xFF)<<8 )
1762             + (toupper((x>>16)&0xFF)<<16)
1763             + (toupper((x>>24)&0xFF)<<24);
1764 }
1765
1766 #if !HAVE_THREADS
1767
1768 int ff_thread_get_buffer(AVCodecContext *avctx, AVFrame *f)
1769 {
1770     f->owner = avctx;
1771     return avctx->get_buffer(avctx, f);
1772 }
1773
1774 void ff_thread_release_buffer(AVCodecContext *avctx, AVFrame *f)
1775 {
1776     f->owner->release_buffer(f->owner, f);
1777 }
1778
1779 void ff_thread_finish_setup(AVCodecContext *avctx)
1780 {
1781 }
1782
1783 void ff_thread_report_progress(AVFrame *f, int progress, int field)
1784 {
1785 }
1786
1787 void ff_thread_await_progress(AVFrame *f, int progress, int field)
1788 {
1789 }
1790
1791 #endif
1792
1793 enum AVMediaType avcodec_get_type(enum CodecID codec_id)
1794 {
1795     if (codec_id <= CODEC_ID_NONE)
1796         return AVMEDIA_TYPE_UNKNOWN;
1797     else if (codec_id < CODEC_ID_FIRST_AUDIO)
1798         return AVMEDIA_TYPE_VIDEO;
1799     else if (codec_id < CODEC_ID_FIRST_SUBTITLE)
1800         return AVMEDIA_TYPE_AUDIO;
1801     else if (codec_id < CODEC_ID_FIRST_UNKNOWN)
1802         return AVMEDIA_TYPE_SUBTITLE;
1803
1804     return AVMEDIA_TYPE_UNKNOWN;
1805 }