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