]> git.sesse.net Git - ffmpeg/blob - libavcodec/utils.c
Merge remote-tracking branch 'qatar/master'
[ffmpeg] / libavcodec / utils.c
1 /*
2  * utils for libavcodec
3  * Copyright (c) 2001 Fabrice Bellard
4  * Copyright (c) 2002-2004 Michael Niedermayer <michaelni@gmx.at>
5  *
6  * This file is part of FFmpeg.
7  *
8  * FFmpeg is free software; you can redistribute it and/or
9  * modify it under the terms of the GNU Lesser General Public
10  * License as published by the Free Software Foundation; either
11  * version 2.1 of the License, or (at your option) any later version.
12  *
13  * FFmpeg is distributed in the hope that it will be useful,
14  * but WITHOUT ANY WARRANTY; without even the implied warranty of
15  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
16  * Lesser General Public License for more details.
17  *
18  * You should have received a copy of the GNU Lesser General Public
19  * License along with FFmpeg; if not, write to the Free Software
20  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
21  */
22
23 /**
24  * @file
25  * utils.
26  */
27
28 #include "libavutil/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 || s->codec_id == CODEC_ID_PRORES)
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     if(s->codec_id == CODEC_ID_IFF_ILBM || s->codec_id == CODEC_ID_IFF_BYTERUN1){
210         w_align= FFMAX(w_align, 8);
211     }
212
213     *width = FFALIGN(*width , w_align);
214     *height= FFALIGN(*height, h_align);
215     if(s->codec_id == CODEC_ID_H264 || s->lowres)
216         *height+=2; // some of the optimized chroma MC reads one line too much
217                     // which is also done in mpeg decoders with lowres > 0
218
219     for (i = 0; i < AV_NUM_DATA_POINTERS; i++)
220         linesize_align[i] = STRIDE_ALIGN;
221 //STRIDE_ALIGN is 8 for SSE* but this does not work for SVQ1 chroma planes
222 //we could change STRIDE_ALIGN to 16 for x86/sse but it would increase the
223 //picture size unneccessarily in some cases. The solution here is not
224 //pretty and better ideas are welcome!
225 #if HAVE_MMX
226     if(s->codec_id == CODEC_ID_SVQ1 || s->codec_id == CODEC_ID_VP5 ||
227        s->codec_id == CODEC_ID_VP6 || s->codec_id == CODEC_ID_VP6F ||
228        s->codec_id == CODEC_ID_VP6A || s->codec_id == CODEC_ID_DIRAC) {
229         for (i = 0; i < AV_NUM_DATA_POINTERS; i++)
230             linesize_align[i] = 16;
231     }
232 #endif
233 }
234
235 void avcodec_align_dimensions(AVCodecContext *s, int *width, int *height){
236     int chroma_shift = av_pix_fmt_descriptors[s->pix_fmt].log2_chroma_w;
237     int linesize_align[AV_NUM_DATA_POINTERS];
238     int align;
239     avcodec_align_dimensions2(s, width, height, linesize_align);
240     align = FFMAX(linesize_align[0], linesize_align[3]);
241     linesize_align[1] <<= chroma_shift;
242     linesize_align[2] <<= chroma_shift;
243     align = FFMAX3(align, linesize_align[1], linesize_align[2]);
244     *width=FFALIGN(*width, align);
245 }
246
247 void ff_init_buffer_info(AVCodecContext *s, AVFrame *pic)
248 {
249     if (s->pkt) {
250         pic->pkt_pts = s->pkt->pts;
251         pic->pkt_pos = s->pkt->pos;
252     } else {
253         pic->pkt_pts = AV_NOPTS_VALUE;
254         pic->pkt_pos = -1;
255     }
256     pic->reordered_opaque= s->reordered_opaque;
257     pic->sample_aspect_ratio = s->sample_aspect_ratio;
258     pic->width               = s->width;
259     pic->height              = s->height;
260     pic->format              = s->pix_fmt;
261 }
262
263 static int audio_get_buffer(AVCodecContext *avctx, AVFrame *frame)
264 {
265     AVCodecInternal *avci = avctx->internal;
266     InternalBuffer *buf;
267     int buf_size, ret, i, needs_extended_data;
268
269     buf_size = av_samples_get_buffer_size(NULL, avctx->channels,
270                                           frame->nb_samples, avctx->sample_fmt,
271                                           32);
272     if (buf_size < 0)
273         return AVERROR(EINVAL);
274
275     needs_extended_data = av_sample_fmt_is_planar(avctx->sample_fmt) &&
276                           avctx->channels > AV_NUM_DATA_POINTERS;
277
278     /* allocate InternalBuffer if needed */
279     if (!avci->buffer) {
280         avci->buffer = av_mallocz(sizeof(InternalBuffer));
281         if (!avci->buffer)
282             return AVERROR(ENOMEM);
283     }
284     buf = avci->buffer;
285
286     /* if there is a previously-used internal buffer, check its size and
287        channel count to see if we can reuse it */
288     if (buf->extended_data) {
289         /* if current buffer is too small, free it */
290         if (buf->extended_data[0] && buf_size > buf->audio_data_size) {
291             av_free(buf->extended_data[0]);
292             if (buf->extended_data != buf->data)
293                 av_free(&buf->extended_data);
294             buf->extended_data = NULL;
295             buf->data[0] = NULL;
296         }
297         /* if number of channels has changed, reset and/or free extended data
298            pointers but leave data buffer in buf->data[0] for reuse */
299         if (buf->nb_channels != avctx->channels) {
300             if (buf->extended_data != buf->data)
301                 av_free(buf->extended_data);
302             buf->extended_data = NULL;
303         }
304     }
305
306     /* if there is no previous buffer or the previous buffer cannot be used
307        as-is, allocate a new buffer and/or rearrange the channel pointers */
308     if (!buf->extended_data) {
309         /* if the channel pointers will fit, just set extended_data to data,
310            otherwise allocate the extended_data channel pointers */
311         if (needs_extended_data) {
312             buf->extended_data = av_mallocz(avctx->channels *
313                                             sizeof(*buf->extended_data));
314             if (!buf->extended_data)
315                 return AVERROR(ENOMEM);
316         } else {
317             buf->extended_data = buf->data;
318         }
319
320         /* if there is a previous buffer and it is large enough, reuse it and
321            just fill-in new channel pointers and linesize, otherwise allocate
322            a new buffer */
323         if (buf->extended_data[0]) {
324             ret = av_samples_fill_arrays(buf->extended_data, &buf->linesize[0],
325                                          buf->extended_data[0], avctx->channels,
326                                          frame->nb_samples, avctx->sample_fmt,
327                                          32);
328         } else {
329             ret = av_samples_alloc(buf->extended_data, &buf->linesize[0],
330                                    avctx->channels, frame->nb_samples,
331                                    avctx->sample_fmt, 32);
332         }
333         if (ret)
334             return ret;
335
336         /* if data was not used for extended_data, we need to copy as many of
337            the extended_data channel pointers as will fit */
338         if (needs_extended_data) {
339             for (i = 0; i < AV_NUM_DATA_POINTERS; i++)
340                 buf->data[i] = buf->extended_data[i];
341         }
342         buf->audio_data_size = buf_size;
343         buf->nb_channels     = avctx->channels;
344     }
345
346     /* copy InternalBuffer info to the AVFrame */
347     frame->type          = FF_BUFFER_TYPE_INTERNAL;
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     if (avctx->pkt) {
353         frame->pkt_pts = avctx->pkt->pts;
354         frame->pkt_pos = avctx->pkt->pos;
355     } else {
356         frame->pkt_pts = AV_NOPTS_VALUE;
357         frame->pkt_pos = -1;
358     }
359
360     frame->reordered_opaque = avctx->reordered_opaque;
361
362     if (avctx->debug & FF_DEBUG_BUFFERS)
363         av_log(avctx, AV_LOG_DEBUG, "default_get_buffer called on frame %p, "
364                "internal audio buffer used\n", frame);
365
366     return 0;
367 }
368
369 static int video_get_buffer(AVCodecContext *s, AVFrame *pic)
370 {
371     int i;
372     int w= s->width;
373     int h= s->height;
374     InternalBuffer *buf;
375     int *picture_number;
376     AVCodecInternal *avci = s->internal;
377
378     if(pic->data[0]!=NULL) {
379         av_log(s, AV_LOG_ERROR, "pic->data[0]!=NULL in avcodec_default_get_buffer\n");
380         return -1;
381     }
382     if(avci->buffer_count >= INTERNAL_BUFFER_SIZE) {
383         av_log(s, AV_LOG_ERROR, "buffer_count overflow (missing release_buffer?)\n");
384         return -1;
385     }
386
387     if(av_image_check_size(w, h, 0, s))
388         return -1;
389
390     if (!avci->buffer) {
391         avci->buffer = av_mallocz((INTERNAL_BUFFER_SIZE+1) *
392                                   sizeof(InternalBuffer));
393     }
394
395     buf = &avci->buffer[avci->buffer_count];
396     picture_number = &(avci->buffer[INTERNAL_BUFFER_SIZE]).last_pic_num; //FIXME ugly hack
397     (*picture_number)++;
398
399     if(buf->base[0] && (buf->width != w || buf->height != h || buf->pix_fmt != s->pix_fmt)){
400         if(s->active_thread_type&FF_THREAD_FRAME) {
401             av_log_missing_feature(s, "Width/height changing with frame threads is", 0);
402             return -1;
403         }
404
405         for (i = 0; i < AV_NUM_DATA_POINTERS; i++) {
406             av_freep(&buf->base[i]);
407             buf->data[i]= NULL;
408         }
409     }
410
411     if(buf->base[0]){
412         pic->age= *picture_number - buf->last_pic_num;
413         buf->last_pic_num= *picture_number;
414     }else{
415         int h_chroma_shift, v_chroma_shift;
416         int size[4] = {0};
417         int tmpsize;
418         int unaligned;
419         AVPicture picture;
420         int stride_align[AV_NUM_DATA_POINTERS];
421         const int pixel_size = av_pix_fmt_descriptors[s->pix_fmt].comp[0].step_minus1+1;
422
423         avcodec_get_chroma_sub_sample(s->pix_fmt, &h_chroma_shift, &v_chroma_shift);
424
425         avcodec_align_dimensions2(s, &w, &h, stride_align);
426
427         if(!(s->flags&CODEC_FLAG_EMU_EDGE)){
428             w+= EDGE_WIDTH*2;
429             h+= EDGE_WIDTH*2;
430         }
431
432         do {
433             // NOTE: do not align linesizes individually, this breaks e.g. assumptions
434             // that linesize[0] == 2*linesize[1] in the MPEG-encoder for 4:2:2
435             av_image_fill_linesizes(picture.linesize, s->pix_fmt, w);
436             // increase alignment of w for next try (rhs gives the lowest bit set in w)
437             w += w & ~(w-1);
438
439             unaligned = 0;
440             for (i=0; i<4; i++){
441                 unaligned |= picture.linesize[i] % stride_align[i];
442             }
443         } while (unaligned);
444
445         tmpsize = av_image_fill_pointers(picture.data, s->pix_fmt, h, NULL, picture.linesize);
446         if (tmpsize < 0)
447             return -1;
448
449         for (i=0; i<3 && picture.data[i+1]; i++)
450             size[i] = picture.data[i+1] - picture.data[i];
451         size[i] = tmpsize - (picture.data[i] - picture.data[0]);
452
453         buf->last_pic_num= -256*256*256*64;
454         memset(buf->base, 0, sizeof(buf->base));
455         memset(buf->data, 0, sizeof(buf->data));
456
457         for(i=0; i<4 && size[i]; i++){
458             const int h_shift= i==0 ? 0 : h_chroma_shift;
459             const int v_shift= i==0 ? 0 : v_chroma_shift;
460
461             buf->linesize[i]= picture.linesize[i];
462
463             buf->base[i]= av_malloc(size[i]+16); //FIXME 16
464             if(buf->base[i]==NULL) return -1;
465             memset(buf->base[i], 128, size[i]);
466
467             // no edge if EDGE EMU or not planar YUV
468             if((s->flags&CODEC_FLAG_EMU_EDGE) || !size[2])
469                 buf->data[i] = buf->base[i];
470             else
471                 buf->data[i] = buf->base[i] + FFALIGN((buf->linesize[i]*EDGE_WIDTH>>v_shift) + (pixel_size*EDGE_WIDTH>>h_shift), stride_align[i]);
472         }
473         for (; i < AV_NUM_DATA_POINTERS; i++) {
474             buf->base[i] = buf->data[i] = NULL;
475             buf->linesize[i] = 0;
476         }
477         if(size[1] && !size[2])
478             ff_set_systematic_pal2((uint32_t*)buf->data[1], s->pix_fmt);
479         buf->width  = s->width;
480         buf->height = s->height;
481         buf->pix_fmt= s->pix_fmt;
482         pic->age= 256*256*256*64;
483     }
484     pic->type= FF_BUFFER_TYPE_INTERNAL;
485
486     for (i = 0; i < AV_NUM_DATA_POINTERS; i++) {
487         pic->base[i]= buf->base[i];
488         pic->data[i]= buf->data[i];
489         pic->linesize[i]= buf->linesize[i];
490     }
491     pic->extended_data = pic->data;
492     avci->buffer_count++;
493
494     if (s->pkt) {
495         pic->pkt_pts = s->pkt->pts;
496         pic->pkt_pos = s->pkt->pos;
497     } else {
498         pic->pkt_pts = AV_NOPTS_VALUE;
499         pic->pkt_pos = -1;
500     }
501     pic->reordered_opaque= s->reordered_opaque;
502     pic->sample_aspect_ratio = s->sample_aspect_ratio;
503     pic->width               = s->width;
504     pic->height              = s->height;
505     pic->format              = s->pix_fmt;
506
507     if(s->debug&FF_DEBUG_BUFFERS)
508         av_log(s, AV_LOG_DEBUG, "default_get_buffer called on pic %p, %d "
509                "buffers used\n", pic, avci->buffer_count);
510
511     return 0;
512 }
513
514 int avcodec_default_get_buffer(AVCodecContext *avctx, AVFrame *frame)
515 {
516     switch (avctx->codec_type) {
517     case AVMEDIA_TYPE_VIDEO:
518         return video_get_buffer(avctx, frame);
519     case AVMEDIA_TYPE_AUDIO:
520         return audio_get_buffer(avctx, frame);
521     default:
522         return -1;
523     }
524 }
525
526 void avcodec_default_release_buffer(AVCodecContext *s, AVFrame *pic){
527     int i;
528     InternalBuffer *buf, *last;
529     AVCodecInternal *avci = s->internal;
530
531     assert(s->codec_type == AVMEDIA_TYPE_VIDEO);
532
533     assert(pic->type==FF_BUFFER_TYPE_INTERNAL);
534     assert(avci->buffer_count);
535
536     if (avci->buffer) {
537         buf = NULL; /* avoids warning */
538         for (i = 0; i < avci->buffer_count; i++) { //just 3-5 checks so is not worth to optimize
539             buf = &avci->buffer[i];
540             if (buf->data[0] == pic->data[0])
541                 break;
542         }
543         assert(i < avci->buffer_count);
544         avci->buffer_count--;
545         last = &avci->buffer[avci->buffer_count];
546
547         FFSWAP(InternalBuffer, *buf, *last);
548     }
549
550     for (i = 0; i < AV_NUM_DATA_POINTERS; i++) {
551         pic->data[i]=NULL;
552 //        pic->base[i]=NULL;
553     }
554 //printf("R%X\n", pic->opaque);
555
556     if(s->debug&FF_DEBUG_BUFFERS)
557         av_log(s, AV_LOG_DEBUG, "default_release_buffer called on pic %p, %d "
558                "buffers used\n", pic, avci->buffer_count);
559 }
560
561 int avcodec_default_reget_buffer(AVCodecContext *s, AVFrame *pic){
562     AVFrame temp_pic;
563     int i;
564
565     assert(s->codec_type == AVMEDIA_TYPE_VIDEO);
566
567     /* If no picture return a new buffer */
568     if(pic->data[0] == NULL) {
569         /* We will copy from buffer, so must be readable */
570         pic->buffer_hints |= FF_BUFFER_HINTS_READABLE;
571         return s->get_buffer(s, pic);
572     }
573
574     /* If internal buffer type return the same buffer */
575     if(pic->type == FF_BUFFER_TYPE_INTERNAL) {
576         if(s->pkt) pic->pkt_pts= s->pkt->pts;
577         else       pic->pkt_pts= AV_NOPTS_VALUE;
578         pic->reordered_opaque= s->reordered_opaque;
579         return 0;
580     }
581
582     /*
583      * Not internal type and reget_buffer not overridden, emulate cr buffer
584      */
585     temp_pic = *pic;
586     for(i = 0; i < AV_NUM_DATA_POINTERS; i++)
587         pic->data[i] = pic->base[i] = NULL;
588     pic->opaque = NULL;
589     /* Allocate new frame */
590     if (s->get_buffer(s, pic))
591         return -1;
592     /* Copy image data from old buffer to new buffer */
593     av_picture_copy((AVPicture*)pic, (AVPicture*)&temp_pic, s->pix_fmt, s->width,
594              s->height);
595     s->release_buffer(s, &temp_pic); // Release old frame
596     return 0;
597 }
598
599 int avcodec_default_execute(AVCodecContext *c, int (*func)(AVCodecContext *c2, void *arg2),void *arg, int *ret, int count, int size){
600     int i;
601
602     for(i=0; i<count; i++){
603         int r= func(c, (char*)arg + i*size);
604         if(ret) ret[i]= r;
605     }
606     return 0;
607 }
608
609 int avcodec_default_execute2(AVCodecContext *c, int (*func)(AVCodecContext *c2, void *arg2, int jobnr, int threadnr),void *arg, int *ret, int count){
610     int i;
611
612     for(i=0; i<count; i++){
613         int r= func(c, arg, i, 0);
614         if(ret) ret[i]= r;
615     }
616     return 0;
617 }
618
619 enum PixelFormat avcodec_default_get_format(struct AVCodecContext *s, const enum PixelFormat *fmt){
620     while (*fmt != PIX_FMT_NONE && ff_is_hwaccel_pix_fmt(*fmt))
621         ++fmt;
622     return fmt[0];
623 }
624
625 void avcodec_get_frame_defaults(AVFrame *pic){
626     memset(pic, 0, sizeof(AVFrame));
627
628     pic->pts = pic->best_effort_timestamp = AV_NOPTS_VALUE;
629     pic->pkt_pos = -1;
630     pic->key_frame= 1;
631     pic->sample_aspect_ratio = (AVRational){0, 1};
632     pic->format = -1;           /* unknown */
633 }
634
635 AVFrame *avcodec_alloc_frame(void){
636     AVFrame *pic= av_malloc(sizeof(AVFrame));
637
638     if(pic==NULL) return NULL;
639
640     avcodec_get_frame_defaults(pic);
641
642     return pic;
643 }
644
645 static void avcodec_get_subtitle_defaults(AVSubtitle *sub)
646 {
647     memset(sub, 0, sizeof(*sub));
648     sub->pts = AV_NOPTS_VALUE;
649 }
650
651 #if FF_API_AVCODEC_OPEN
652 int attribute_align_arg avcodec_open(AVCodecContext *avctx, AVCodec *codec)
653 {
654     return avcodec_open2(avctx, codec, NULL);
655 }
656 #endif
657
658 int attribute_align_arg avcodec_open2(AVCodecContext *avctx, AVCodec *codec, AVDictionary **options)
659 {
660     int ret = 0;
661     AVDictionary *tmp = NULL;
662
663     if (options)
664         av_dict_copy(&tmp, *options, 0);
665
666     /* If there is a user-supplied mutex locking routine, call it. */
667     if (ff_lockmgr_cb) {
668         if ((*ff_lockmgr_cb)(&codec_mutex, AV_LOCK_OBTAIN))
669             return -1;
670     }
671
672     entangled_thread_counter++;
673     if(entangled_thread_counter != 1){
674         av_log(avctx, AV_LOG_ERROR, "insufficient thread locking around avcodec_open/close()\n");
675         ret = -1;
676         goto end;
677     }
678
679     if(avctx->codec || !codec) {
680         ret = AVERROR(EINVAL);
681         goto end;
682     }
683
684     avctx->internal = av_mallocz(sizeof(AVCodecInternal));
685     if (!avctx->internal) {
686         ret = AVERROR(ENOMEM);
687         goto end;
688     }
689
690     if (codec->priv_data_size > 0) {
691       if(!avctx->priv_data){
692         avctx->priv_data = av_mallocz(codec->priv_data_size);
693         if (!avctx->priv_data) {
694             ret = AVERROR(ENOMEM);
695             goto end;
696         }
697         if (codec->priv_class) {
698             *(AVClass**)avctx->priv_data= codec->priv_class;
699             av_opt_set_defaults(avctx->priv_data);
700         }
701       }
702       if (codec->priv_class && (ret = av_opt_set_dict(avctx->priv_data, &tmp)) < 0)
703           goto free_and_end;
704     } else {
705         avctx->priv_data = NULL;
706     }
707     if ((ret = av_opt_set_dict(avctx, &tmp)) < 0)
708         goto free_and_end;
709
710     //We only call avcodec_set_dimensions() for non h264 codecs so as not to overwrite previously setup dimensions
711     if(!( avctx->coded_width && avctx->coded_height && avctx->width && avctx->height && avctx->codec_id == CODEC_ID_H264)){
712     if(avctx->coded_width && avctx->coded_height)
713         avcodec_set_dimensions(avctx, avctx->coded_width, avctx->coded_height);
714     else if(avctx->width && avctx->height)
715         avcodec_set_dimensions(avctx, avctx->width, avctx->height);
716     }
717
718     if ((avctx->coded_width || avctx->coded_height || avctx->width || avctx->height)
719         && (  av_image_check_size(avctx->coded_width, avctx->coded_height, 0, avctx) < 0
720            || av_image_check_size(avctx->width,       avctx->height,       0, avctx) < 0)) {
721         av_log(avctx, AV_LOG_WARNING, "ignoring invalid width/height values\n");
722         avcodec_set_dimensions(avctx, 0, 0);
723     }
724
725     /* if the decoder init function was already called previously,
726        free the already allocated subtitle_header before overwriting it */
727     if (codec->decode)
728         av_freep(&avctx->subtitle_header);
729
730 #define SANE_NB_CHANNELS 128U
731     if (avctx->channels > SANE_NB_CHANNELS) {
732         ret = AVERROR(EINVAL);
733         goto free_and_end;
734     }
735
736     avctx->codec = codec;
737     if ((avctx->codec_type == AVMEDIA_TYPE_UNKNOWN || avctx->codec_type == codec->type) &&
738         avctx->codec_id == CODEC_ID_NONE) {
739         avctx->codec_type = codec->type;
740         avctx->codec_id   = codec->id;
741     }
742     if (avctx->codec_id != codec->id || (avctx->codec_type != codec->type
743                            && avctx->codec_type != AVMEDIA_TYPE_ATTACHMENT)) {
744         av_log(avctx, AV_LOG_ERROR, "codec type or id mismatches\n");
745         ret = AVERROR(EINVAL);
746         goto free_and_end;
747     }
748     avctx->frame_number = 0;
749 #if FF_API_ER
750
751     av_log(avctx, AV_LOG_DEBUG, "err{or,}_recognition separate: %d; %d\n",
752            avctx->error_recognition, avctx->err_recognition);
753     switch(avctx->error_recognition){
754         case FF_ER_EXPLODE        : avctx->err_recognition |= AV_EF_EXPLODE | AV_EF_COMPLIANT | AV_EF_CAREFUL;
755             break;
756         case FF_ER_VERY_AGGRESSIVE:
757         case FF_ER_AGGRESSIVE     : avctx->err_recognition |= AV_EF_AGGRESSIVE;
758         case FF_ER_COMPLIANT      : avctx->err_recognition |= AV_EF_COMPLIANT;
759         case FF_ER_CAREFUL        : avctx->err_recognition |= AV_EF_CAREFUL;
760     }
761
762     av_log(avctx, AV_LOG_DEBUG, "err{or,}_recognition combined: %d; %d\n",
763            avctx->error_recognition, avctx->err_recognition);
764 #endif
765
766     if (!HAVE_THREADS)
767         av_log(avctx, AV_LOG_WARNING, "Warning: not compiled with thread support, using thread emulation\n");
768
769     if (HAVE_THREADS && !avctx->thread_opaque) {
770         ret = ff_thread_init(avctx);
771         if (ret < 0) {
772             goto free_and_end;
773         }
774     }
775
776     if (avctx->codec->max_lowres < avctx->lowres || avctx->lowres < 0) {
777         av_log(avctx, AV_LOG_ERROR, "The maximum value for lowres supported by the decoder is %d\n",
778                avctx->codec->max_lowres);
779         ret = AVERROR(EINVAL);
780         goto free_and_end;
781     }
782     if (avctx->codec->encode) {
783         int i;
784         if (avctx->codec->sample_fmts) {
785             for (i = 0; avctx->codec->sample_fmts[i] != AV_SAMPLE_FMT_NONE; i++)
786                 if (avctx->sample_fmt == avctx->codec->sample_fmts[i])
787                     break;
788             if (avctx->codec->sample_fmts[i] == AV_SAMPLE_FMT_NONE) {
789                 av_log(avctx, AV_LOG_ERROR, "Specified sample_fmt is not supported.\n");
790                 ret = AVERROR(EINVAL);
791                 goto free_and_end;
792             }
793         }
794         if (avctx->codec->supported_samplerates) {
795             for (i = 0; avctx->codec->supported_samplerates[i] != 0; i++)
796                 if (avctx->sample_rate == avctx->codec->supported_samplerates[i])
797                     break;
798             if (avctx->codec->supported_samplerates[i] == 0) {
799                 av_log(avctx, AV_LOG_ERROR, "Specified sample_rate is not supported\n");
800                 ret = AVERROR(EINVAL);
801                 goto free_and_end;
802             }
803         }
804         if (avctx->codec->channel_layouts) {
805             if (!avctx->channel_layout) {
806                 av_log(avctx, AV_LOG_WARNING, "channel_layout not specified\n");
807             } else {
808                 for (i = 0; avctx->codec->channel_layouts[i] != 0; i++)
809                     if (avctx->channel_layout == avctx->codec->channel_layouts[i])
810                         break;
811                 if (avctx->codec->channel_layouts[i] == 0) {
812                     av_log(avctx, AV_LOG_ERROR, "Specified channel_layout is not supported\n");
813                     ret = AVERROR(EINVAL);
814                     goto free_and_end;
815                 }
816             }
817         }
818         if (avctx->channel_layout && avctx->channels) {
819             if (av_get_channel_layout_nb_channels(avctx->channel_layout) != avctx->channels) {
820                 av_log(avctx, AV_LOG_ERROR, "channel layout does not match number of channels\n");
821                 ret = AVERROR(EINVAL);
822                 goto free_and_end;
823             }
824         } else if (avctx->channel_layout) {
825             avctx->channels = av_get_channel_layout_nb_channels(avctx->channel_layout);
826         }
827     }
828
829     avctx->pts_correction_num_faulty_pts =
830     avctx->pts_correction_num_faulty_dts = 0;
831     avctx->pts_correction_last_pts =
832     avctx->pts_correction_last_dts = INT64_MIN;
833
834     if(avctx->codec->init && !(avctx->active_thread_type&FF_THREAD_FRAME)){
835         ret = avctx->codec->init(avctx);
836         if (ret < 0) {
837             goto free_and_end;
838         }
839     }
840
841     ret=0;
842 end:
843     entangled_thread_counter--;
844
845     /* Release any user-supplied mutex. */
846     if (ff_lockmgr_cb) {
847         (*ff_lockmgr_cb)(&codec_mutex, AV_LOCK_RELEASE);
848     }
849     if (options) {
850         av_dict_free(options);
851         *options = tmp;
852     }
853
854     return ret;
855 free_and_end:
856     av_dict_free(&tmp);
857     av_freep(&avctx->priv_data);
858     av_freep(&avctx->internal);
859     avctx->codec= NULL;
860     goto end;
861 }
862
863 int attribute_align_arg avcodec_encode_audio(AVCodecContext *avctx, uint8_t *buf, int buf_size,
864                          const short *samples)
865 {
866     if(buf_size < FF_MIN_BUFFER_SIZE && 0){
867         av_log(avctx, AV_LOG_ERROR, "buffer smaller than minimum size\n");
868         return -1;
869     }
870     if((avctx->codec->capabilities & CODEC_CAP_DELAY) || samples){
871         int ret = avctx->codec->encode(avctx, buf, buf_size, samples);
872         avctx->frame_number++;
873         return ret;
874     }else
875         return 0;
876 }
877
878 int attribute_align_arg avcodec_encode_video(AVCodecContext *avctx, uint8_t *buf, int buf_size,
879                          const AVFrame *pict)
880 {
881     if(buf_size < FF_MIN_BUFFER_SIZE){
882         av_log(avctx, AV_LOG_ERROR, "buffer smaller than minimum size\n");
883         return -1;
884     }
885     if(av_image_check_size(avctx->width, avctx->height, 0, avctx))
886         return -1;
887     if((avctx->codec->capabilities & CODEC_CAP_DELAY) || pict){
888         int ret = avctx->codec->encode(avctx, buf, buf_size, pict);
889         avctx->frame_number++;
890         emms_c(); //needed to avoid an emms_c() call before every return;
891
892         return ret;
893     }else
894         return 0;
895 }
896
897 int avcodec_encode_subtitle(AVCodecContext *avctx, uint8_t *buf, int buf_size,
898                             const AVSubtitle *sub)
899 {
900     int ret;
901     if(sub->start_display_time) {
902         av_log(avctx, AV_LOG_ERROR, "start_display_time must be 0.\n");
903         return -1;
904     }
905
906     ret = avctx->codec->encode(avctx, buf, buf_size, sub);
907     avctx->frame_number++;
908     return ret;
909 }
910
911 /**
912  * Attempt to guess proper monotonic timestamps for decoded video frames
913  * which might have incorrect times. Input timestamps may wrap around, in
914  * which case the output will as well.
915  *
916  * @param pts the pts field of the decoded AVPacket, as passed through
917  * AVFrame.pkt_pts
918  * @param dts the dts field of the decoded AVPacket
919  * @return one of the input values, may be AV_NOPTS_VALUE
920  */
921 static int64_t guess_correct_pts(AVCodecContext *ctx,
922                                  int64_t reordered_pts, int64_t dts)
923 {
924     int64_t pts = AV_NOPTS_VALUE;
925
926     if (dts != AV_NOPTS_VALUE) {
927         ctx->pts_correction_num_faulty_dts += dts <= ctx->pts_correction_last_dts;
928         ctx->pts_correction_last_dts = dts;
929     }
930     if (reordered_pts != AV_NOPTS_VALUE) {
931         ctx->pts_correction_num_faulty_pts += reordered_pts <= ctx->pts_correction_last_pts;
932         ctx->pts_correction_last_pts = reordered_pts;
933     }
934     if ((ctx->pts_correction_num_faulty_pts<=ctx->pts_correction_num_faulty_dts || dts == AV_NOPTS_VALUE)
935        && reordered_pts != AV_NOPTS_VALUE)
936         pts = reordered_pts;
937     else
938         pts = dts;
939
940     return pts;
941 }
942
943 int attribute_align_arg avcodec_decode_video2(AVCodecContext *avctx, AVFrame *picture,
944                          int *got_picture_ptr,
945                          AVPacket *avpkt)
946 {
947     int ret;
948
949     *got_picture_ptr= 0;
950     if((avctx->coded_width||avctx->coded_height) && av_image_check_size(avctx->coded_width, avctx->coded_height, 0, avctx))
951         return -1;
952
953     if((avctx->codec->capabilities & CODEC_CAP_DELAY) || avpkt->size || (avctx->active_thread_type&FF_THREAD_FRAME)){
954         av_packet_split_side_data(avpkt);
955         avctx->pkt = avpkt;
956         if (HAVE_THREADS && avctx->active_thread_type&FF_THREAD_FRAME)
957              ret = ff_thread_decode_frame(avctx, picture, got_picture_ptr,
958                                           avpkt);
959         else {
960             ret = avctx->codec->decode(avctx, picture, got_picture_ptr,
961                               avpkt);
962             picture->pkt_dts= avpkt->dts;
963
964             if(!avctx->has_b_frames){
965             picture->pkt_pos= avpkt->pos;
966             }
967             //FIXME these should be under if(!avctx->has_b_frames)
968             if (!picture->sample_aspect_ratio.num)
969                 picture->sample_aspect_ratio = avctx->sample_aspect_ratio;
970             if (!picture->width)
971                 picture->width = avctx->width;
972             if (!picture->height)
973                 picture->height = avctx->height;
974             if (picture->format == PIX_FMT_NONE)
975                 picture->format = avctx->pix_fmt;
976         }
977
978         emms_c(); //needed to avoid an emms_c() call before every return;
979
980
981         if (*got_picture_ptr){
982             avctx->frame_number++;
983             picture->best_effort_timestamp = guess_correct_pts(avctx,
984                                                             picture->pkt_pts,
985                                                             picture->pkt_dts);
986         }
987     }else
988         ret= 0;
989
990     return ret;
991 }
992
993 #if FF_API_OLD_DECODE_AUDIO
994 int attribute_align_arg avcodec_decode_audio3(AVCodecContext *avctx, int16_t *samples,
995                          int *frame_size_ptr,
996                          AVPacket *avpkt)
997 {
998     AVFrame frame;
999     int ret, got_frame = 0;
1000
1001     if (avctx->get_buffer != avcodec_default_get_buffer) {
1002         av_log(avctx, AV_LOG_ERROR, "A custom get_buffer() cannot be used with "
1003                "avcodec_decode_audio3()\n");
1004         return AVERROR(EINVAL);
1005     }
1006
1007     ret = avcodec_decode_audio4(avctx, &frame, &got_frame, avpkt);
1008
1009     if (ret >= 0 && got_frame) {
1010         int ch, plane_size;
1011         int planar = av_sample_fmt_is_planar(avctx->sample_fmt);
1012         int data_size = av_samples_get_buffer_size(&plane_size, avctx->channels,
1013                                                    frame.nb_samples,
1014                                                    avctx->sample_fmt, 1);
1015         if (*frame_size_ptr < data_size) {
1016             av_log(avctx, AV_LOG_ERROR, "output buffer size is too small for "
1017                    "the current frame (%d < %d)\n", *frame_size_ptr, data_size);
1018             return AVERROR(EINVAL);
1019         }
1020
1021         memcpy(samples, frame.extended_data[0], plane_size);
1022
1023         if (planar && avctx->channels > 1) {
1024             uint8_t *out = ((uint8_t *)samples) + plane_size;
1025             for (ch = 1; ch < avctx->channels; ch++) {
1026                 memcpy(out, frame.extended_data[ch], plane_size);
1027                 out += plane_size;
1028             }
1029         }
1030         *frame_size_ptr = data_size;
1031     } else {
1032         *frame_size_ptr = 0;
1033     }
1034     return ret;
1035 }
1036 #endif
1037
1038 int attribute_align_arg avcodec_decode_audio4(AVCodecContext *avctx,
1039                                               AVFrame *frame,
1040                                               int *got_frame_ptr,
1041                                               AVPacket *avpkt)
1042 {
1043     int ret = 0;
1044
1045     *got_frame_ptr = 0;
1046
1047     if (!avpkt->data && avpkt->size) {
1048         av_log(avctx, AV_LOG_ERROR, "invalid packet: NULL data, size != 0\n");
1049         return AVERROR(EINVAL);
1050     }
1051
1052     if ((avctx->codec->capabilities & CODEC_CAP_DELAY) || avpkt->size) {
1053         av_packet_split_side_data(avpkt);
1054         avctx->pkt = avpkt;
1055         ret = avctx->codec->decode(avctx, frame, got_frame_ptr, avpkt);
1056         if (ret >= 0 && *got_frame_ptr) {
1057             avctx->frame_number++;
1058             frame->pkt_dts = avpkt->dts;
1059         }
1060     }
1061     return ret;
1062 }
1063
1064 int avcodec_decode_subtitle2(AVCodecContext *avctx, AVSubtitle *sub,
1065                             int *got_sub_ptr,
1066                             AVPacket *avpkt)
1067 {
1068     int ret;
1069
1070     avctx->pkt = avpkt;
1071     *got_sub_ptr = 0;
1072     avcodec_get_subtitle_defaults(sub);
1073     ret = avctx->codec->decode(avctx, sub, got_sub_ptr, avpkt);
1074     if (*got_sub_ptr)
1075         avctx->frame_number++;
1076     return ret;
1077 }
1078
1079 void avsubtitle_free(AVSubtitle *sub)
1080 {
1081     int i;
1082
1083     for (i = 0; i < sub->num_rects; i++)
1084     {
1085         av_freep(&sub->rects[i]->pict.data[0]);
1086         av_freep(&sub->rects[i]->pict.data[1]);
1087         av_freep(&sub->rects[i]->pict.data[2]);
1088         av_freep(&sub->rects[i]->pict.data[3]);
1089         av_freep(&sub->rects[i]->text);
1090         av_freep(&sub->rects[i]->ass);
1091         av_freep(&sub->rects[i]);
1092     }
1093
1094     av_freep(&sub->rects);
1095
1096     memset(sub, 0, sizeof(AVSubtitle));
1097 }
1098
1099 av_cold int avcodec_close(AVCodecContext *avctx)
1100 {
1101     /* If there is a user-supplied mutex locking routine, call it. */
1102     if (ff_lockmgr_cb) {
1103         if ((*ff_lockmgr_cb)(&codec_mutex, AV_LOCK_OBTAIN))
1104             return -1;
1105     }
1106
1107     entangled_thread_counter++;
1108     if(entangled_thread_counter != 1){
1109         av_log(avctx, AV_LOG_ERROR, "insufficient thread locking around avcodec_open/close()\n");
1110         entangled_thread_counter--;
1111         return -1;
1112     }
1113
1114     if (HAVE_THREADS && avctx->thread_opaque)
1115         ff_thread_free(avctx);
1116     if (avctx->codec && avctx->codec->close)
1117         avctx->codec->close(avctx);
1118     avcodec_default_free_buffers(avctx);
1119     avctx->coded_frame = NULL;
1120     av_freep(&avctx->internal);
1121     if (avctx->codec && avctx->codec->priv_class)
1122         av_opt_free(avctx->priv_data);
1123     av_opt_free(avctx);
1124     av_freep(&avctx->priv_data);
1125     if(avctx->codec && avctx->codec->encode)
1126         av_freep(&avctx->extradata);
1127     avctx->codec = NULL;
1128     avctx->active_thread_type = 0;
1129     entangled_thread_counter--;
1130
1131     /* Release any user-supplied mutex. */
1132     if (ff_lockmgr_cb) {
1133         (*ff_lockmgr_cb)(&codec_mutex, AV_LOCK_RELEASE);
1134     }
1135     return 0;
1136 }
1137
1138 static enum CodecID remap_deprecated_codec_id(enum CodecID id)
1139 {
1140     switch(id){
1141         case CODEC_ID_G723_1_DEPRECATED : return CODEC_ID_G723_1;
1142         case CODEC_ID_G729_DEPRECATED   : return CODEC_ID_G729;
1143         case CODEC_ID_UTVIDEO_DEPRECATED: return CODEC_ID_UTVIDEO;
1144         default                         : return id;
1145     }
1146 }
1147
1148 AVCodec *avcodec_find_encoder(enum CodecID id)
1149 {
1150     AVCodec *p, *experimental=NULL;
1151     p = first_avcodec;
1152     id= remap_deprecated_codec_id(id);
1153     while (p) {
1154         if (p->encode != NULL && p->id == id) {
1155             if (p->capabilities & CODEC_CAP_EXPERIMENTAL && !experimental) {
1156                 experimental = p;
1157             } else
1158                 return p;
1159         }
1160         p = p->next;
1161     }
1162     return experimental;
1163 }
1164
1165 AVCodec *avcodec_find_encoder_by_name(const char *name)
1166 {
1167     AVCodec *p;
1168     if (!name)
1169         return NULL;
1170     p = first_avcodec;
1171     while (p) {
1172         if (p->encode != NULL && strcmp(name,p->name) == 0)
1173             return p;
1174         p = p->next;
1175     }
1176     return NULL;
1177 }
1178
1179 AVCodec *avcodec_find_decoder(enum CodecID id)
1180 {
1181     AVCodec *p, *experimental=NULL;
1182     p = first_avcodec;
1183     id= remap_deprecated_codec_id(id);
1184     while (p) {
1185         if (p->decode != NULL && p->id == id) {
1186             if (p->capabilities & CODEC_CAP_EXPERIMENTAL && !experimental) {
1187                 experimental = p;
1188             } else
1189                 return p;
1190         }
1191         p = p->next;
1192     }
1193     return experimental;
1194 }
1195
1196 AVCodec *avcodec_find_decoder_by_name(const char *name)
1197 {
1198     AVCodec *p;
1199     if (!name)
1200         return NULL;
1201     p = first_avcodec;
1202     while (p) {
1203         if (p->decode != NULL && strcmp(name,p->name) == 0)
1204             return p;
1205         p = p->next;
1206     }
1207     return NULL;
1208 }
1209
1210 static int get_bit_rate(AVCodecContext *ctx)
1211 {
1212     int bit_rate;
1213     int bits_per_sample;
1214
1215     switch(ctx->codec_type) {
1216     case AVMEDIA_TYPE_VIDEO:
1217     case AVMEDIA_TYPE_DATA:
1218     case AVMEDIA_TYPE_SUBTITLE:
1219     case AVMEDIA_TYPE_ATTACHMENT:
1220         bit_rate = ctx->bit_rate;
1221         break;
1222     case AVMEDIA_TYPE_AUDIO:
1223         bits_per_sample = av_get_bits_per_sample(ctx->codec_id);
1224         bit_rate = bits_per_sample ? ctx->sample_rate * ctx->channels * bits_per_sample : ctx->bit_rate;
1225         break;
1226     default:
1227         bit_rate = 0;
1228         break;
1229     }
1230     return bit_rate;
1231 }
1232
1233 const char *avcodec_get_name(enum CodecID id)
1234 {
1235     AVCodec *codec;
1236
1237 #if !CONFIG_SMALL
1238     switch (id) {
1239 #include "libavcodec/codec_names.h"
1240     }
1241     av_log(NULL, AV_LOG_WARNING, "Codec 0x%x is not in the full list.\n", id);
1242 #endif
1243     codec = avcodec_find_decoder(id);
1244     if (codec)
1245         return codec->name;
1246     codec = avcodec_find_encoder(id);
1247     if (codec)
1248         return codec->name;
1249     return "unknown_codec";
1250 }
1251
1252 size_t av_get_codec_tag_string(char *buf, size_t buf_size, unsigned int codec_tag)
1253 {
1254     int i, len, ret = 0;
1255
1256     for (i = 0; i < 4; i++) {
1257         len = snprintf(buf, buf_size,
1258                        isprint(codec_tag&0xFF) ? "%c" : "[%d]", codec_tag&0xFF);
1259         buf      += len;
1260         buf_size  = buf_size > len ? buf_size - len : 0;
1261         ret      += len;
1262         codec_tag>>=8;
1263     }
1264     return ret;
1265 }
1266
1267 void avcodec_string(char *buf, int buf_size, AVCodecContext *enc, int encode)
1268 {
1269     const char *codec_type;
1270     const char *codec_name;
1271     const char *profile = NULL;
1272     AVCodec *p;
1273     int bitrate;
1274     AVRational display_aspect_ratio;
1275
1276     if (!buf || buf_size <= 0)
1277         return;
1278     codec_type = av_get_media_type_string(enc->codec_type);
1279     codec_name = avcodec_get_name(enc->codec_id);
1280     if (enc->profile != FF_PROFILE_UNKNOWN) {
1281         p = encode ? avcodec_find_encoder(enc->codec_id) :
1282                      avcodec_find_decoder(enc->codec_id);
1283         if (p)
1284             profile = av_get_profile_name(p, enc->profile);
1285     }
1286
1287     snprintf(buf, buf_size, "%s: %s%s", codec_type ? codec_type : "unknown",
1288              codec_name, enc->mb_decision ? " (hq)" : "");
1289     buf[0] ^= 'a' ^ 'A'; /* first letter in uppercase */
1290     if (profile)
1291         snprintf(buf + strlen(buf), buf_size - strlen(buf), " (%s)", profile);
1292     if (enc->codec_tag) {
1293         char tag_buf[32];
1294         av_get_codec_tag_string(tag_buf, sizeof(tag_buf), enc->codec_tag);
1295         snprintf(buf + strlen(buf), buf_size - strlen(buf),
1296                  " (%s / 0x%04X)", tag_buf, enc->codec_tag);
1297     }
1298     switch(enc->codec_type) {
1299     case AVMEDIA_TYPE_VIDEO:
1300         if (enc->pix_fmt != PIX_FMT_NONE) {
1301             snprintf(buf + strlen(buf), buf_size - strlen(buf),
1302                      ", %s",
1303                      av_get_pix_fmt_name(enc->pix_fmt));
1304         }
1305         if (enc->width) {
1306             snprintf(buf + strlen(buf), buf_size - strlen(buf),
1307                      ", %dx%d",
1308                      enc->width, enc->height);
1309             if (enc->sample_aspect_ratio.num) {
1310                 av_reduce(&display_aspect_ratio.num, &display_aspect_ratio.den,
1311                           enc->width*enc->sample_aspect_ratio.num,
1312                           enc->height*enc->sample_aspect_ratio.den,
1313                           1024*1024);
1314                 snprintf(buf + strlen(buf), buf_size - strlen(buf),
1315                          " [SAR %d:%d DAR %d:%d]",
1316                          enc->sample_aspect_ratio.num, enc->sample_aspect_ratio.den,
1317                          display_aspect_ratio.num, display_aspect_ratio.den);
1318             }
1319             if(av_log_get_level() >= AV_LOG_DEBUG){
1320                 int g= av_gcd(enc->time_base.num, enc->time_base.den);
1321                 snprintf(buf + strlen(buf), buf_size - strlen(buf),
1322                      ", %d/%d",
1323                      enc->time_base.num/g, enc->time_base.den/g);
1324             }
1325         }
1326         if (encode) {
1327             snprintf(buf + strlen(buf), buf_size - strlen(buf),
1328                      ", q=%d-%d", enc->qmin, enc->qmax);
1329         }
1330         break;
1331     case AVMEDIA_TYPE_AUDIO:
1332         if (enc->sample_rate) {
1333             snprintf(buf + strlen(buf), buf_size - strlen(buf),
1334                      ", %d Hz", enc->sample_rate);
1335         }
1336         av_strlcat(buf, ", ", buf_size);
1337         av_get_channel_layout_string(buf + strlen(buf), buf_size - strlen(buf), enc->channels, enc->channel_layout);
1338         if (enc->sample_fmt != AV_SAMPLE_FMT_NONE) {
1339             snprintf(buf + strlen(buf), buf_size - strlen(buf),
1340                      ", %s", av_get_sample_fmt_name(enc->sample_fmt));
1341         }
1342         break;
1343     default:
1344         return;
1345     }
1346     if (encode) {
1347         if (enc->flags & CODEC_FLAG_PASS1)
1348             snprintf(buf + strlen(buf), buf_size - strlen(buf),
1349                      ", pass 1");
1350         if (enc->flags & CODEC_FLAG_PASS2)
1351             snprintf(buf + strlen(buf), buf_size - strlen(buf),
1352                      ", pass 2");
1353     }
1354     bitrate = get_bit_rate(enc);
1355     if (bitrate != 0) {
1356         snprintf(buf + strlen(buf), buf_size - strlen(buf),
1357                  ", %d kb/s", bitrate / 1000);
1358     }
1359 }
1360
1361 const char *av_get_profile_name(const AVCodec *codec, int profile)
1362 {
1363     const AVProfile *p;
1364     if (profile == FF_PROFILE_UNKNOWN || !codec->profiles)
1365         return NULL;
1366
1367     for (p = codec->profiles; p->profile != FF_PROFILE_UNKNOWN; p++)
1368         if (p->profile == profile)
1369             return p->name;
1370
1371     return NULL;
1372 }
1373
1374 unsigned avcodec_version( void )
1375 {
1376   return LIBAVCODEC_VERSION_INT;
1377 }
1378
1379 const char *avcodec_configuration(void)
1380 {
1381     return FFMPEG_CONFIGURATION;
1382 }
1383
1384 const char *avcodec_license(void)
1385 {
1386 #define LICENSE_PREFIX "libavcodec license: "
1387     return LICENSE_PREFIX FFMPEG_LICENSE + sizeof(LICENSE_PREFIX) - 1;
1388 }
1389
1390 void avcodec_flush_buffers(AVCodecContext *avctx)
1391 {
1392     if(HAVE_THREADS && avctx->active_thread_type&FF_THREAD_FRAME)
1393         ff_thread_flush(avctx);
1394     else if(avctx->codec->flush)
1395         avctx->codec->flush(avctx);
1396 }
1397
1398 static void video_free_buffers(AVCodecContext *s)
1399 {
1400     AVCodecInternal *avci = s->internal;
1401     int i, j;
1402
1403     if (!avci->buffer)
1404         return;
1405
1406     if (avci->buffer_count)
1407         av_log(s, AV_LOG_WARNING, "Found %i unreleased buffers!\n",
1408                avci->buffer_count);
1409     for(i=0; i<INTERNAL_BUFFER_SIZE; i++){
1410         InternalBuffer *buf = &avci->buffer[i];
1411         for(j=0; j<4; j++){
1412             av_freep(&buf->base[j]);
1413             buf->data[j]= NULL;
1414         }
1415     }
1416     av_freep(&avci->buffer);
1417
1418     avci->buffer_count=0;
1419 }
1420
1421 static void audio_free_buffers(AVCodecContext *avctx)
1422 {
1423     AVCodecInternal *avci = avctx->internal;
1424     InternalBuffer *buf;
1425
1426     if (!avci->buffer)
1427         return;
1428     buf = avci->buffer;
1429
1430     if (buf->extended_data) {
1431         av_free(buf->extended_data[0]);
1432         if (buf->extended_data != buf->data)
1433             av_free(buf->extended_data);
1434     }
1435     av_freep(&avci->buffer);
1436 }
1437
1438 void avcodec_default_free_buffers(AVCodecContext *avctx)
1439 {
1440     switch (avctx->codec_type) {
1441     case AVMEDIA_TYPE_VIDEO:
1442         video_free_buffers(avctx);
1443         break;
1444     case AVMEDIA_TYPE_AUDIO:
1445         audio_free_buffers(avctx);
1446         break;
1447     default:
1448         break;
1449     }
1450 }
1451
1452 #if FF_API_OLD_FF_PICT_TYPES
1453 char av_get_pict_type_char(int pict_type){
1454     return av_get_picture_type_char(pict_type);
1455 }
1456 #endif
1457
1458 int av_get_bits_per_sample(enum CodecID codec_id){
1459     switch(codec_id){
1460     case CODEC_ID_ADPCM_SBPRO_2:
1461         return 2;
1462     case CODEC_ID_ADPCM_SBPRO_3:
1463         return 3;
1464     case CODEC_ID_ADPCM_SBPRO_4:
1465     case CODEC_ID_ADPCM_CT:
1466     case CODEC_ID_ADPCM_IMA_WAV:
1467     case CODEC_ID_ADPCM_IMA_QT:
1468     case CODEC_ID_ADPCM_SWF:
1469     case CODEC_ID_ADPCM_MS:
1470     case CODEC_ID_ADPCM_YAMAHA:
1471     case CODEC_ID_ADPCM_G722:
1472         return 4;
1473     case CODEC_ID_PCM_ALAW:
1474     case CODEC_ID_PCM_MULAW:
1475     case CODEC_ID_PCM_S8:
1476     case CODEC_ID_PCM_U8:
1477     case CODEC_ID_PCM_ZORK:
1478         return 8;
1479     case CODEC_ID_PCM_S16BE:
1480     case CODEC_ID_PCM_S16LE:
1481     case CODEC_ID_PCM_S16LE_PLANAR:
1482     case CODEC_ID_PCM_U16BE:
1483     case CODEC_ID_PCM_U16LE:
1484         return 16;
1485     case CODEC_ID_PCM_S24DAUD:
1486     case CODEC_ID_PCM_S24BE:
1487     case CODEC_ID_PCM_S24LE:
1488     case CODEC_ID_PCM_U24BE:
1489     case CODEC_ID_PCM_U24LE:
1490         return 24;
1491     case CODEC_ID_PCM_S32BE:
1492     case CODEC_ID_PCM_S32LE:
1493     case CODEC_ID_PCM_U32BE:
1494     case CODEC_ID_PCM_U32LE:
1495     case CODEC_ID_PCM_F32BE:
1496     case CODEC_ID_PCM_F32LE:
1497         return 32;
1498     case CODEC_ID_PCM_F64BE:
1499     case CODEC_ID_PCM_F64LE:
1500         return 64;
1501     default:
1502         return 0;
1503     }
1504 }
1505
1506 #if FF_API_OLD_SAMPLE_FMT
1507 int av_get_bits_per_sample_format(enum AVSampleFormat sample_fmt) {
1508     return av_get_bytes_per_sample(sample_fmt) << 3;
1509 }
1510 #endif
1511
1512 #if !HAVE_THREADS
1513 int ff_thread_init(AVCodecContext *s){
1514     return -1;
1515 }
1516 #endif
1517
1518 unsigned int av_xiphlacing(unsigned char *s, unsigned int v)
1519 {
1520     unsigned int n = 0;
1521
1522     while(v >= 0xff) {
1523         *s++ = 0xff;
1524         v -= 0xff;
1525         n++;
1526     }
1527     *s = v;
1528     n++;
1529     return n;
1530 }
1531
1532 int ff_match_2uint16(const uint16_t (*tab)[2], int size, int a, int b){
1533     int i;
1534     for(i=0; i<size && !(tab[i][0]==a && tab[i][1]==b); i++);
1535     return i;
1536 }
1537
1538 void av_log_missing_feature(void *avc, const char *feature, int want_sample)
1539 {
1540     av_log(avc, AV_LOG_WARNING, "%s not implemented. Update your FFmpeg "
1541             "version to the newest one from Git. If the problem still "
1542             "occurs, it means that your file has a feature which has not "
1543             "been implemented.\n", feature);
1544     if(want_sample)
1545         av_log_ask_for_sample(avc, NULL);
1546 }
1547
1548 void av_log_ask_for_sample(void *avc, const char *msg, ...)
1549 {
1550     va_list argument_list;
1551
1552     va_start(argument_list, msg);
1553
1554     if (msg)
1555         av_vlog(avc, AV_LOG_WARNING, msg, argument_list);
1556     av_log(avc, AV_LOG_WARNING, "If you want to help, upload a sample "
1557             "of this file to ftp://upload.ffmpeg.org/MPlayer/incoming/ "
1558             "and contact the ffmpeg-devel mailing list.\n");
1559
1560     va_end(argument_list);
1561 }
1562
1563 static AVHWAccel *first_hwaccel = NULL;
1564
1565 void av_register_hwaccel(AVHWAccel *hwaccel)
1566 {
1567     AVHWAccel **p = &first_hwaccel;
1568     while (*p)
1569         p = &(*p)->next;
1570     *p = hwaccel;
1571     hwaccel->next = NULL;
1572 }
1573
1574 AVHWAccel *av_hwaccel_next(AVHWAccel *hwaccel)
1575 {
1576     return hwaccel ? hwaccel->next : first_hwaccel;
1577 }
1578
1579 AVHWAccel *ff_find_hwaccel(enum CodecID codec_id, enum PixelFormat pix_fmt)
1580 {
1581     AVHWAccel *hwaccel=NULL;
1582
1583     while((hwaccel= av_hwaccel_next(hwaccel))){
1584         if (   hwaccel->id      == codec_id
1585             && hwaccel->pix_fmt == pix_fmt)
1586             return hwaccel;
1587     }
1588     return NULL;
1589 }
1590
1591 int av_lockmgr_register(int (*cb)(void **mutex, enum AVLockOp op))
1592 {
1593     if (ff_lockmgr_cb) {
1594         if (ff_lockmgr_cb(&codec_mutex, AV_LOCK_DESTROY))
1595             return -1;
1596         if (ff_lockmgr_cb(&avformat_mutex, AV_LOCK_DESTROY))
1597             return -1;
1598     }
1599
1600     ff_lockmgr_cb = cb;
1601
1602     if (ff_lockmgr_cb) {
1603         if (ff_lockmgr_cb(&codec_mutex, AV_LOCK_CREATE))
1604             return -1;
1605         if (ff_lockmgr_cb(&avformat_mutex, AV_LOCK_CREATE))
1606             return -1;
1607     }
1608     return 0;
1609 }
1610
1611 int avpriv_lock_avformat(void)
1612 {
1613     if (ff_lockmgr_cb) {
1614         if ((*ff_lockmgr_cb)(&avformat_mutex, AV_LOCK_OBTAIN))
1615             return -1;
1616     }
1617     return 0;
1618 }
1619
1620 int avpriv_unlock_avformat(void)
1621 {
1622     if (ff_lockmgr_cb) {
1623         if ((*ff_lockmgr_cb)(&avformat_mutex, AV_LOCK_RELEASE))
1624             return -1;
1625     }
1626     return 0;
1627 }
1628
1629 unsigned int avpriv_toupper4(unsigned int x)
1630 {
1631     return     toupper( x     &0xFF)
1632             + (toupper((x>>8 )&0xFF)<<8 )
1633             + (toupper((x>>16)&0xFF)<<16)
1634             + (toupper((x>>24)&0xFF)<<24);
1635 }
1636
1637 #if !HAVE_THREADS
1638
1639 int ff_thread_get_buffer(AVCodecContext *avctx, AVFrame *f)
1640 {
1641     f->owner = avctx;
1642
1643     ff_init_buffer_info(avctx, f);
1644
1645     return avctx->get_buffer(avctx, f);
1646 }
1647
1648 void ff_thread_release_buffer(AVCodecContext *avctx, AVFrame *f)
1649 {
1650     f->owner->release_buffer(f->owner, f);
1651 }
1652
1653 void ff_thread_finish_setup(AVCodecContext *avctx)
1654 {
1655 }
1656
1657 void ff_thread_report_progress(AVFrame *f, int progress, int field)
1658 {
1659 }
1660
1661 void ff_thread_await_progress(AVFrame *f, int progress, int field)
1662 {
1663 }
1664
1665 #endif
1666
1667 #if FF_API_THREAD_INIT
1668 int avcodec_thread_init(AVCodecContext *s, int thread_count)
1669 {
1670     s->thread_count = thread_count;
1671     return ff_thread_init(s);
1672 }
1673 #endif
1674
1675 enum AVMediaType avcodec_get_type(enum CodecID codec_id)
1676 {
1677     AVCodec *c= avcodec_find_decoder(codec_id);
1678     if(!c)
1679         c= avcodec_find_encoder(codec_id);
1680     if(c)
1681         return c->type;
1682
1683     if (codec_id <= CODEC_ID_NONE)
1684         return AVMEDIA_TYPE_UNKNOWN;
1685     else if (codec_id < CODEC_ID_FIRST_AUDIO)
1686         return AVMEDIA_TYPE_VIDEO;
1687     else if (codec_id < CODEC_ID_FIRST_SUBTITLE)
1688         return AVMEDIA_TYPE_AUDIO;
1689     else if (codec_id < CODEC_ID_FIRST_UNKNOWN)
1690         return AVMEDIA_TYPE_SUBTITLE;
1691
1692     return AVMEDIA_TYPE_UNKNOWN;
1693 }