]> git.sesse.net Git - ffmpeg/blob - libavcodec/utils.c
Add CR/LF to a reget_buffer warning message.
[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 "libavutil/avassert.h"
37 #include "avcodec.h"
38 #include "dsputil.h"
39 #include "libavutil/opt.h"
40 #include "imgconvert.h"
41 #include "thread.h"
42 #include "audioconvert.h"
43 #include "internal.h"
44 #include "bytestream.h"
45 #include <stdlib.h>
46 #include <stdarg.h>
47 #include <limits.h>
48 #include <float.h>
49
50 static int volatile entangled_thread_counter=0;
51 static int (*ff_lockmgr_cb)(void **mutex, enum AVLockOp op);
52 static void *codec_mutex;
53 static void *avformat_mutex;
54
55 void *av_fast_realloc(void *ptr, unsigned int *size, size_t min_size)
56 {
57     if(min_size < *size)
58         return ptr;
59
60     min_size= FFMAX(17*min_size/16 + 32, min_size);
61
62     ptr= av_realloc(ptr, min_size);
63     if(!ptr) //we could set this to the unmodified min_size but this is safer if the user lost the ptr and uses NULL now
64         min_size= 0;
65
66     *size= min_size;
67
68     return ptr;
69 }
70
71 void av_fast_malloc(void *ptr, unsigned int *size, size_t min_size)
72 {
73     void **p = ptr;
74     if (min_size < *size)
75         return;
76     min_size= FFMAX(17*min_size/16 + 32, min_size);
77     av_free(*p);
78     *p = av_malloc(min_size);
79     if (!*p) min_size = 0;
80     *size= min_size;
81 }
82
83 /* encoder management */
84 static AVCodec *first_avcodec = NULL;
85
86 AVCodec *av_codec_next(AVCodec *c){
87     if(c) return c->next;
88     else  return first_avcodec;
89 }
90
91 #if !FF_API_AVCODEC_INIT
92 static
93 #endif
94 void avcodec_init(void)
95 {
96     static int initialized = 0;
97
98     if (initialized != 0)
99         return;
100     initialized = 1;
101
102     dsputil_static_init();
103 }
104
105 void avcodec_register(AVCodec *codec)
106 {
107     AVCodec **p;
108     avcodec_init();
109     p = &first_avcodec;
110     while (*p != NULL) p = &(*p)->next;
111     *p = codec;
112     codec->next = NULL;
113
114     if (codec->init_static_data)
115         codec->init_static_data(codec);
116 }
117
118 unsigned avcodec_get_edge_width(void)
119 {
120     return EDGE_WIDTH;
121 }
122
123 void avcodec_set_dimensions(AVCodecContext *s, int width, int height){
124     s->coded_width = width;
125     s->coded_height= height;
126     s->width = -((-width )>>s->lowres);
127     s->height= -((-height)>>s->lowres);
128 }
129
130 #define INTERNAL_BUFFER_SIZE (32+1)
131
132 void avcodec_align_dimensions2(AVCodecContext *s, int *width, int *height,
133                                int linesize_align[AV_NUM_DATA_POINTERS])
134 {
135     int i;
136     int w_align= 1;
137     int h_align= 1;
138
139     switch(s->pix_fmt){
140     case PIX_FMT_YUV420P:
141     case PIX_FMT_YUYV422:
142     case PIX_FMT_UYVY422:
143     case PIX_FMT_YUV422P:
144     case PIX_FMT_YUV440P:
145     case PIX_FMT_YUV444P:
146     case PIX_FMT_GBRP:
147     case PIX_FMT_GRAY8:
148     case PIX_FMT_GRAY16BE:
149     case PIX_FMT_GRAY16LE:
150     case PIX_FMT_YUVJ420P:
151     case PIX_FMT_YUVJ422P:
152     case PIX_FMT_YUVJ440P:
153     case PIX_FMT_YUVJ444P:
154     case PIX_FMT_YUVA420P:
155     case PIX_FMT_YUV420P9LE:
156     case PIX_FMT_YUV420P9BE:
157     case PIX_FMT_YUV420P10LE:
158     case PIX_FMT_YUV420P10BE:
159     case PIX_FMT_YUV422P9LE:
160     case PIX_FMT_YUV422P9BE:
161     case PIX_FMT_YUV422P10LE:
162     case PIX_FMT_YUV422P10BE:
163     case PIX_FMT_YUV444P9LE:
164     case PIX_FMT_YUV444P9BE:
165     case PIX_FMT_YUV444P10LE:
166     case PIX_FMT_YUV444P10BE:
167     case PIX_FMT_GBRP9LE:
168     case PIX_FMT_GBRP9BE:
169     case PIX_FMT_GBRP10LE:
170     case PIX_FMT_GBRP10BE:
171         w_align = 16; //FIXME assume 16 pixel per macroblock
172         h_align = 16 * 2; // interlaced needs 2 macroblocks height
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     AVCodecInternal *avci = s->internal;
376
377     if(pic->data[0]!=NULL) {
378         av_log(s, AV_LOG_ERROR, "pic->data[0]!=NULL in avcodec_default_get_buffer\n");
379         return -1;
380     }
381     if(avci->buffer_count >= INTERNAL_BUFFER_SIZE) {
382         av_log(s, AV_LOG_ERROR, "buffer_count overflow (missing release_buffer?)\n");
383         return -1;
384     }
385
386     if(av_image_check_size(w, h, 0, s))
387         return -1;
388
389     if (!avci->buffer) {
390         avci->buffer = av_mallocz((INTERNAL_BUFFER_SIZE+1) *
391                                   sizeof(InternalBuffer));
392     }
393
394     buf = &avci->buffer[avci->buffer_count];
395
396     if(buf->base[0] && (buf->width != w || buf->height != h || buf->pix_fmt != s->pix_fmt)){
397         if(s->active_thread_type&FF_THREAD_FRAME) {
398             av_log_missing_feature(s, "Width/height changing with frame threads is", 0);
399             return -1;
400         }
401
402         for (i = 0; i < AV_NUM_DATA_POINTERS; i++) {
403             av_freep(&buf->base[i]);
404             buf->data[i]= NULL;
405         }
406     }
407
408     if (!buf->base[0]) {
409         int h_chroma_shift, v_chroma_shift;
410         int size[4] = {0};
411         int tmpsize;
412         int unaligned;
413         AVPicture picture;
414         int stride_align[AV_NUM_DATA_POINTERS];
415         const int pixel_size = av_pix_fmt_descriptors[s->pix_fmt].comp[0].step_minus1+1;
416
417         avcodec_get_chroma_sub_sample(s->pix_fmt, &h_chroma_shift, &v_chroma_shift);
418
419         avcodec_align_dimensions2(s, &w, &h, stride_align);
420
421         if(!(s->flags&CODEC_FLAG_EMU_EDGE)){
422             w+= EDGE_WIDTH*2;
423             h+= EDGE_WIDTH*2;
424         }
425
426         do {
427             // NOTE: do not align linesizes individually, this breaks e.g. assumptions
428             // that linesize[0] == 2*linesize[1] in the MPEG-encoder for 4:2:2
429             av_image_fill_linesizes(picture.linesize, s->pix_fmt, w);
430             // increase alignment of w for next try (rhs gives the lowest bit set in w)
431             w += w & ~(w-1);
432
433             unaligned = 0;
434             for (i=0; i<4; i++){
435                 unaligned |= picture.linesize[i] % stride_align[i];
436             }
437         } while (unaligned);
438
439         tmpsize = av_image_fill_pointers(picture.data, s->pix_fmt, h, NULL, picture.linesize);
440         if (tmpsize < 0)
441             return -1;
442
443         for (i=0; i<3 && picture.data[i+1]; i++)
444             size[i] = picture.data[i+1] - picture.data[i];
445         size[i] = tmpsize - (picture.data[i] - picture.data[0]);
446
447         memset(buf->base, 0, sizeof(buf->base));
448         memset(buf->data, 0, sizeof(buf->data));
449
450         for(i=0; i<4 && size[i]; i++){
451             const int h_shift= i==0 ? 0 : h_chroma_shift;
452             const int v_shift= i==0 ? 0 : v_chroma_shift;
453
454             buf->linesize[i]= picture.linesize[i];
455
456             buf->base[i]= av_malloc(size[i]+16); //FIXME 16
457             if(buf->base[i]==NULL) return -1;
458             memset(buf->base[i], 128, size[i]);
459
460             // no edge if EDGE EMU or not planar YUV
461             if((s->flags&CODEC_FLAG_EMU_EDGE) || !size[2])
462                 buf->data[i] = buf->base[i];
463             else
464                 buf->data[i] = buf->base[i] + FFALIGN((buf->linesize[i]*EDGE_WIDTH>>v_shift) + (pixel_size*EDGE_WIDTH>>h_shift), stride_align[i]);
465         }
466         for (; i < AV_NUM_DATA_POINTERS; i++) {
467             buf->base[i] = buf->data[i] = NULL;
468             buf->linesize[i] = 0;
469         }
470         if(size[1] && !size[2])
471             ff_set_systematic_pal2((uint32_t*)buf->data[1], s->pix_fmt);
472         buf->width  = s->width;
473         buf->height = s->height;
474         buf->pix_fmt= s->pix_fmt;
475     }
476     pic->type= FF_BUFFER_TYPE_INTERNAL;
477
478     for (i = 0; i < AV_NUM_DATA_POINTERS; i++) {
479         pic->base[i]= buf->base[i];
480         pic->data[i]= buf->data[i];
481         pic->linesize[i]= buf->linesize[i];
482     }
483     pic->extended_data = pic->data;
484     avci->buffer_count++;
485
486     if (s->pkt) {
487         pic->pkt_pts = s->pkt->pts;
488         pic->pkt_pos = s->pkt->pos;
489     } else {
490         pic->pkt_pts = AV_NOPTS_VALUE;
491         pic->pkt_pos = -1;
492     }
493     pic->reordered_opaque= s->reordered_opaque;
494     pic->sample_aspect_ratio = s->sample_aspect_ratio;
495     pic->width               = s->width;
496     pic->height              = s->height;
497     pic->format              = s->pix_fmt;
498
499     if(s->debug&FF_DEBUG_BUFFERS)
500         av_log(s, AV_LOG_DEBUG, "default_get_buffer called on pic %p, %d "
501                "buffers used\n", pic, avci->buffer_count);
502
503     return 0;
504 }
505
506 int avcodec_default_get_buffer(AVCodecContext *avctx, AVFrame *frame)
507 {
508     switch (avctx->codec_type) {
509     case AVMEDIA_TYPE_VIDEO:
510         return video_get_buffer(avctx, frame);
511     case AVMEDIA_TYPE_AUDIO:
512         return audio_get_buffer(avctx, frame);
513     default:
514         return -1;
515     }
516 }
517
518 void avcodec_default_release_buffer(AVCodecContext *s, AVFrame *pic){
519     int i;
520     InternalBuffer *buf, *last;
521     AVCodecInternal *avci = s->internal;
522
523     assert(s->codec_type == AVMEDIA_TYPE_VIDEO);
524
525     assert(pic->type==FF_BUFFER_TYPE_INTERNAL);
526     assert(avci->buffer_count);
527
528     if (avci->buffer) {
529         buf = NULL; /* avoids warning */
530         for (i = 0; i < avci->buffer_count; i++) { //just 3-5 checks so is not worth to optimize
531             buf = &avci->buffer[i];
532             if (buf->data[0] == pic->data[0])
533                 break;
534         }
535         assert(i < avci->buffer_count);
536         avci->buffer_count--;
537         last = &avci->buffer[avci->buffer_count];
538
539         if (buf != last)
540             FFSWAP(InternalBuffer, *buf, *last);
541     }
542
543     for (i = 0; i < AV_NUM_DATA_POINTERS; i++) {
544         pic->data[i]=NULL;
545 //        pic->base[i]=NULL;
546     }
547 //printf("R%X\n", pic->opaque);
548
549     if(s->debug&FF_DEBUG_BUFFERS)
550         av_log(s, AV_LOG_DEBUG, "default_release_buffer called on pic %p, %d "
551                "buffers used\n", pic, avci->buffer_count);
552 }
553
554 int avcodec_default_reget_buffer(AVCodecContext *s, AVFrame *pic){
555     AVFrame temp_pic;
556     int i;
557
558     assert(s->codec_type == AVMEDIA_TYPE_VIDEO);
559
560     if (pic->data[0] && (pic->width != s->width || pic->height != s->height || pic->format != s->pix_fmt)) {
561         av_log(s, AV_LOG_WARNING, "Width/height/fmt changing with reget buffer\n");
562         s->release_buffer(s, pic);
563     }
564
565     /* If no picture return a new buffer */
566     if(pic->data[0] == NULL) {
567         /* We will copy from buffer, so must be readable */
568         pic->buffer_hints |= FF_BUFFER_HINTS_READABLE;
569         return s->get_buffer(s, pic);
570     }
571
572     /* If internal buffer type return the same buffer */
573     if(pic->type == FF_BUFFER_TYPE_INTERNAL) {
574         if(s->pkt) pic->pkt_pts= s->pkt->pts;
575         else       pic->pkt_pts= AV_NOPTS_VALUE;
576         pic->reordered_opaque= s->reordered_opaque;
577         return 0;
578     }
579
580     /*
581      * Not internal type and reget_buffer not overridden, emulate cr buffer
582      */
583     temp_pic = *pic;
584     for(i = 0; i < AV_NUM_DATA_POINTERS; i++)
585         pic->data[i] = pic->base[i] = NULL;
586     pic->opaque = NULL;
587     /* Allocate new frame */
588     if (s->get_buffer(s, pic))
589         return -1;
590     /* Copy image data from old buffer to new buffer */
591     av_picture_copy((AVPicture*)pic, (AVPicture*)&temp_pic, s->pix_fmt, s->width,
592              s->height);
593     s->release_buffer(s, &temp_pic); // Release old frame
594     return 0;
595 }
596
597 int avcodec_default_execute(AVCodecContext *c, int (*func)(AVCodecContext *c2, void *arg2),void *arg, int *ret, int count, int size){
598     int i;
599
600     for(i=0; i<count; i++){
601         int r= func(c, (char*)arg + i*size);
602         if(ret) ret[i]= r;
603     }
604     return 0;
605 }
606
607 int avcodec_default_execute2(AVCodecContext *c, int (*func)(AVCodecContext *c2, void *arg2, int jobnr, int threadnr),void *arg, int *ret, int count){
608     int i;
609
610     for(i=0; i<count; i++){
611         int r= func(c, arg, i, 0);
612         if(ret) ret[i]= r;
613     }
614     return 0;
615 }
616
617 enum PixelFormat avcodec_default_get_format(struct AVCodecContext *s, const enum PixelFormat *fmt){
618     while (*fmt != PIX_FMT_NONE && ff_is_hwaccel_pix_fmt(*fmt))
619         ++fmt;
620     return fmt[0];
621 }
622
623 void avcodec_get_frame_defaults(AVFrame *pic){
624     memset(pic, 0, sizeof(AVFrame));
625
626     pic->pts = pic->pkt_dts = pic->pkt_pts = pic->best_effort_timestamp = AV_NOPTS_VALUE;
627     pic->pkt_pos = -1;
628     pic->key_frame= 1;
629     pic->sample_aspect_ratio = (AVRational){0, 1};
630     pic->format = -1;           /* unknown */
631 }
632
633 AVFrame *avcodec_alloc_frame(void){
634     AVFrame *pic= av_malloc(sizeof(AVFrame));
635
636     if(pic==NULL) return NULL;
637
638     avcodec_get_frame_defaults(pic);
639
640     return pic;
641 }
642
643 static void avcodec_get_subtitle_defaults(AVSubtitle *sub)
644 {
645     memset(sub, 0, sizeof(*sub));
646     sub->pts = AV_NOPTS_VALUE;
647 }
648
649 #if FF_API_AVCODEC_OPEN
650 int attribute_align_arg avcodec_open(AVCodecContext *avctx, AVCodec *codec)
651 {
652     return avcodec_open2(avctx, codec, NULL);
653 }
654 #endif
655
656 int attribute_align_arg avcodec_open2(AVCodecContext *avctx, AVCodec *codec, AVDictionary **options)
657 {
658     int ret = 0;
659     AVDictionary *tmp = NULL;
660
661     if (avctx->extradata_size < 0 || avctx->extradata_size >= FF_MAX_EXTRADATA_SIZE)
662         return AVERROR(EINVAL);
663
664     if (options)
665         av_dict_copy(&tmp, *options, 0);
666
667     /* If there is a user-supplied mutex locking routine, call it. */
668     if (ff_lockmgr_cb) {
669         if ((*ff_lockmgr_cb)(&codec_mutex, AV_LOCK_OBTAIN))
670             return -1;
671     }
672
673     entangled_thread_counter++;
674     if(entangled_thread_counter != 1){
675         av_log(avctx, AV_LOG_ERROR, "insufficient thread locking around avcodec_open/close()\n");
676         ret = -1;
677         goto end;
678     }
679
680     if(avctx->codec || !codec) {
681         ret = AVERROR(EINVAL);
682         goto end;
683     }
684
685     avctx->internal = av_mallocz(sizeof(AVCodecInternal));
686     if (!avctx->internal) {
687         ret = AVERROR(ENOMEM);
688         goto end;
689     }
690
691     if (codec->priv_data_size > 0) {
692       if(!avctx->priv_data){
693         avctx->priv_data = av_mallocz(codec->priv_data_size);
694         if (!avctx->priv_data) {
695             ret = AVERROR(ENOMEM);
696             goto end;
697         }
698         if (codec->priv_class) {
699             *(AVClass**)avctx->priv_data= codec->priv_class;
700             av_opt_set_defaults(avctx->priv_data);
701         }
702       }
703       if (codec->priv_class && (ret = av_opt_set_dict(avctx->priv_data, &tmp)) < 0)
704           goto free_and_end;
705     } else {
706         avctx->priv_data = NULL;
707     }
708     if ((ret = av_opt_set_dict(avctx, &tmp)) < 0)
709         goto free_and_end;
710
711     if (codec->capabilities & CODEC_CAP_EXPERIMENTAL)
712         if (avctx->strict_std_compliance > FF_COMPLIANCE_EXPERIMENTAL) {
713             av_log(avctx, AV_LOG_ERROR, "Codec is experimental but experimental codecs are not enabled, see -strict -2\n");
714             ret = -1;
715             goto free_and_end;
716         }
717
718     //We only call avcodec_set_dimensions() for non h264 codecs so as not to overwrite previously setup dimensions
719     if(!( avctx->coded_width && avctx->coded_height && avctx->width && avctx->height && avctx->codec_id == CODEC_ID_H264)){
720     if(avctx->coded_width && avctx->coded_height)
721         avcodec_set_dimensions(avctx, avctx->coded_width, avctx->coded_height);
722     else if(avctx->width && avctx->height)
723         avcodec_set_dimensions(avctx, avctx->width, avctx->height);
724     }
725
726     if ((avctx->coded_width || avctx->coded_height || avctx->width || avctx->height)
727         && (  av_image_check_size(avctx->coded_width, avctx->coded_height, 0, avctx) < 0
728            || av_image_check_size(avctx->width,       avctx->height,       0, avctx) < 0)) {
729         av_log(avctx, AV_LOG_WARNING, "ignoring invalid width/height values\n");
730         avcodec_set_dimensions(avctx, 0, 0);
731     }
732
733     /* if the decoder init function was already called previously,
734        free the already allocated subtitle_header before overwriting it */
735     if (codec->decode)
736         av_freep(&avctx->subtitle_header);
737
738 #define SANE_NB_CHANNELS 128U
739     if (avctx->channels > SANE_NB_CHANNELS) {
740         ret = AVERROR(EINVAL);
741         goto free_and_end;
742     }
743
744     avctx->codec = codec;
745     if ((avctx->codec_type == AVMEDIA_TYPE_UNKNOWN || avctx->codec_type == codec->type) &&
746         avctx->codec_id == CODEC_ID_NONE) {
747         avctx->codec_type = codec->type;
748         avctx->codec_id   = codec->id;
749     }
750     if (avctx->codec_id != codec->id || (avctx->codec_type != codec->type
751                            && avctx->codec_type != AVMEDIA_TYPE_ATTACHMENT)) {
752         av_log(avctx, AV_LOG_ERROR, "codec type or id mismatches\n");
753         ret = AVERROR(EINVAL);
754         goto free_and_end;
755     }
756     avctx->frame_number = 0;
757 #if FF_API_ER
758
759     av_log(avctx, AV_LOG_DEBUG, "err{or,}_recognition separate: %d; %X\n",
760            avctx->error_recognition, avctx->err_recognition);
761     switch(avctx->error_recognition){
762         case FF_ER_EXPLODE        : avctx->err_recognition |= AV_EF_EXPLODE | AV_EF_COMPLIANT | AV_EF_CAREFUL;
763             break;
764         case FF_ER_VERY_AGGRESSIVE:
765         case FF_ER_AGGRESSIVE     : avctx->err_recognition |= AV_EF_AGGRESSIVE;
766         case FF_ER_COMPLIANT      : avctx->err_recognition |= AV_EF_COMPLIANT;
767         case FF_ER_CAREFUL        : avctx->err_recognition |= AV_EF_CAREFUL;
768     }
769
770     av_log(avctx, AV_LOG_DEBUG, "err{or,}_recognition combined: %d; %X\n",
771            avctx->error_recognition, avctx->err_recognition);
772 #endif
773
774     if (!HAVE_THREADS)
775         av_log(avctx, AV_LOG_WARNING, "Warning: not compiled with thread support, using thread emulation\n");
776
777     if (HAVE_THREADS && !avctx->thread_opaque) {
778         ret = ff_thread_init(avctx);
779         if (ret < 0) {
780             goto free_and_end;
781         }
782     }
783     if (!HAVE_THREADS && !(codec->capabilities & CODEC_CAP_AUTO_THREADS))
784         avctx->thread_count = 1;
785
786     if (avctx->codec->max_lowres < avctx->lowres || avctx->lowres < 0) {
787         av_log(avctx, AV_LOG_ERROR, "The maximum value for lowres supported by the decoder is %d\n",
788                avctx->codec->max_lowres);
789         ret = AVERROR(EINVAL);
790         goto free_and_end;
791     }
792     if (avctx->codec->encode) {
793         int i;
794         if (avctx->codec->sample_fmts) {
795             for (i = 0; avctx->codec->sample_fmts[i] != AV_SAMPLE_FMT_NONE; i++)
796                 if (avctx->sample_fmt == avctx->codec->sample_fmts[i])
797                     break;
798             if (avctx->codec->sample_fmts[i] == AV_SAMPLE_FMT_NONE) {
799                 av_log(avctx, AV_LOG_ERROR, "Specified sample_fmt is not supported.\n");
800                 ret = AVERROR(EINVAL);
801                 goto free_and_end;
802             }
803         }
804         if (avctx->codec->supported_samplerates) {
805             for (i = 0; avctx->codec->supported_samplerates[i] != 0; i++)
806                 if (avctx->sample_rate == avctx->codec->supported_samplerates[i])
807                     break;
808             if (avctx->codec->supported_samplerates[i] == 0) {
809                 av_log(avctx, AV_LOG_ERROR, "Specified sample_rate is not supported\n");
810                 ret = AVERROR(EINVAL);
811                 goto free_and_end;
812             }
813         }
814         if (avctx->codec->channel_layouts) {
815             if (!avctx->channel_layout) {
816                 av_log(avctx, AV_LOG_WARNING, "channel_layout not specified\n");
817             } else {
818                 for (i = 0; avctx->codec->channel_layouts[i] != 0; i++)
819                     if (avctx->channel_layout == avctx->codec->channel_layouts[i])
820                         break;
821                 if (avctx->codec->channel_layouts[i] == 0) {
822                     av_log(avctx, AV_LOG_ERROR, "Specified channel_layout is not supported\n");
823                     ret = AVERROR(EINVAL);
824                     goto free_and_end;
825                 }
826             }
827         }
828         if (avctx->channel_layout && avctx->channels) {
829             if (av_get_channel_layout_nb_channels(avctx->channel_layout) != avctx->channels) {
830                 av_log(avctx, AV_LOG_ERROR, "channel layout does not match number of channels\n");
831                 ret = AVERROR(EINVAL);
832                 goto free_and_end;
833             }
834         } else if (avctx->channel_layout) {
835             avctx->channels = av_get_channel_layout_nb_channels(avctx->channel_layout);
836         }
837     }
838
839     avctx->pts_correction_num_faulty_pts =
840     avctx->pts_correction_num_faulty_dts = 0;
841     avctx->pts_correction_last_pts =
842     avctx->pts_correction_last_dts = INT64_MIN;
843
844     if(avctx->codec->init && !(avctx->active_thread_type&FF_THREAD_FRAME)){
845         ret = avctx->codec->init(avctx);
846         if (ret < 0) {
847             goto free_and_end;
848         }
849     }
850
851     ret=0;
852 end:
853     entangled_thread_counter--;
854
855     /* Release any user-supplied mutex. */
856     if (ff_lockmgr_cb) {
857         (*ff_lockmgr_cb)(&codec_mutex, AV_LOCK_RELEASE);
858     }
859     if (options) {
860         av_dict_free(options);
861         *options = tmp;
862     }
863
864     return ret;
865 free_and_end:
866     av_dict_free(&tmp);
867     av_freep(&avctx->priv_data);
868     av_freep(&avctx->internal);
869     avctx->codec= NULL;
870     goto end;
871 }
872
873 int attribute_align_arg avcodec_encode_audio(AVCodecContext *avctx, uint8_t *buf, int buf_size,
874                          const short *samples)
875 {
876     if(buf_size < FF_MIN_BUFFER_SIZE && 0){
877         av_log(avctx, AV_LOG_ERROR, "buffer smaller than minimum size\n");
878         return -1;
879     }
880     if((avctx->codec->capabilities & CODEC_CAP_DELAY) || samples){
881         int ret = avctx->codec->encode(avctx, buf, buf_size, samples);
882         avctx->frame_number++;
883         return ret;
884     }else
885         return 0;
886 }
887
888 int attribute_align_arg avcodec_encode_video(AVCodecContext *avctx, uint8_t *buf, int buf_size,
889                          const AVFrame *pict)
890 {
891     if(buf_size < FF_MIN_BUFFER_SIZE){
892         av_log(avctx, AV_LOG_ERROR, "buffer smaller than minimum size\n");
893         return -1;
894     }
895     if(av_image_check_size(avctx->width, avctx->height, 0, avctx))
896         return -1;
897     if((avctx->codec->capabilities & CODEC_CAP_DELAY) || pict){
898         int ret = avctx->codec->encode(avctx, buf, buf_size, pict);
899         avctx->frame_number++;
900         emms_c(); //needed to avoid an emms_c() call before every return;
901
902         return ret;
903     }else
904         return 0;
905 }
906
907 int avcodec_encode_subtitle(AVCodecContext *avctx, uint8_t *buf, int buf_size,
908                             const AVSubtitle *sub)
909 {
910     int ret;
911     if(sub->start_display_time) {
912         av_log(avctx, AV_LOG_ERROR, "start_display_time must be 0.\n");
913         return -1;
914     }
915
916     ret = avctx->codec->encode(avctx, buf, buf_size, sub);
917     avctx->frame_number++;
918     return ret;
919 }
920
921 /**
922  * Attempt to guess proper monotonic timestamps for decoded video frames
923  * which might have incorrect times. Input timestamps may wrap around, in
924  * which case the output will as well.
925  *
926  * @param pts the pts field of the decoded AVPacket, as passed through
927  * AVFrame.pkt_pts
928  * @param dts the dts field of the decoded AVPacket
929  * @return one of the input values, may be AV_NOPTS_VALUE
930  */
931 static int64_t guess_correct_pts(AVCodecContext *ctx,
932                                  int64_t reordered_pts, int64_t dts)
933 {
934     int64_t pts = AV_NOPTS_VALUE;
935
936     if (dts != AV_NOPTS_VALUE) {
937         ctx->pts_correction_num_faulty_dts += dts <= ctx->pts_correction_last_dts;
938         ctx->pts_correction_last_dts = dts;
939     }
940     if (reordered_pts != AV_NOPTS_VALUE) {
941         ctx->pts_correction_num_faulty_pts += reordered_pts <= ctx->pts_correction_last_pts;
942         ctx->pts_correction_last_pts = reordered_pts;
943     }
944     if ((ctx->pts_correction_num_faulty_pts<=ctx->pts_correction_num_faulty_dts || dts == AV_NOPTS_VALUE)
945        && reordered_pts != AV_NOPTS_VALUE)
946         pts = reordered_pts;
947     else
948         pts = dts;
949
950     return pts;
951 }
952
953 static void apply_param_change(AVCodecContext *avctx, AVPacket *avpkt)
954 {
955     int size = 0;
956     const uint8_t *data;
957     uint32_t flags;
958
959     if (!(avctx->codec->capabilities & CODEC_CAP_PARAM_CHANGE))
960         return;
961
962     data = av_packet_get_side_data(avpkt, AV_PKT_DATA_PARAM_CHANGE, &size);
963     if (!data || size < 4)
964         return;
965     flags = bytestream_get_le32(&data);
966     size -= 4;
967     if (size < 4) /* Required for any of the changes */
968         return;
969     if (flags & AV_SIDE_DATA_PARAM_CHANGE_CHANNEL_COUNT) {
970         avctx->channels = bytestream_get_le32(&data);
971         size -= 4;
972     }
973     if (flags & AV_SIDE_DATA_PARAM_CHANGE_CHANNEL_LAYOUT) {
974         if (size < 8)
975             return;
976         avctx->channel_layout = bytestream_get_le64(&data);
977         size -= 8;
978     }
979     if (size < 4)
980         return;
981     if (flags & AV_SIDE_DATA_PARAM_CHANGE_SAMPLE_RATE) {
982         avctx->sample_rate = bytestream_get_le32(&data);
983         size -= 4;
984     }
985     if (flags & AV_SIDE_DATA_PARAM_CHANGE_DIMENSIONS) {
986         if (size < 8)
987             return;
988         avctx->width  = bytestream_get_le32(&data);
989         avctx->height = bytestream_get_le32(&data);
990         avcodec_set_dimensions(avctx, avctx->width, avctx->height);
991         size -= 8;
992     }
993 }
994
995 int attribute_align_arg avcodec_decode_video2(AVCodecContext *avctx, AVFrame *picture,
996                          int *got_picture_ptr,
997                          AVPacket *avpkt)
998 {
999     int ret;
1000
1001     *got_picture_ptr= 0;
1002     if((avctx->coded_width||avctx->coded_height) && av_image_check_size(avctx->coded_width, avctx->coded_height, 0, avctx))
1003         return -1;
1004
1005     if((avctx->codec->capabilities & CODEC_CAP_DELAY) || avpkt->size || (avctx->active_thread_type&FF_THREAD_FRAME)){
1006         av_packet_split_side_data(avpkt);
1007         apply_param_change(avctx, avpkt);
1008         avctx->pkt = avpkt;
1009         if (HAVE_THREADS && avctx->active_thread_type&FF_THREAD_FRAME)
1010              ret = ff_thread_decode_frame(avctx, picture, got_picture_ptr,
1011                                           avpkt);
1012         else {
1013             ret = avctx->codec->decode(avctx, picture, got_picture_ptr,
1014                               avpkt);
1015             picture->pkt_dts= avpkt->dts;
1016
1017             if(!avctx->has_b_frames){
1018             picture->pkt_pos= avpkt->pos;
1019             }
1020             //FIXME these should be under if(!avctx->has_b_frames)
1021             if (!picture->sample_aspect_ratio.num)
1022                 picture->sample_aspect_ratio = avctx->sample_aspect_ratio;
1023             if (!picture->width)
1024                 picture->width = avctx->width;
1025             if (!picture->height)
1026                 picture->height = avctx->height;
1027             if (picture->format == PIX_FMT_NONE)
1028                 picture->format = avctx->pix_fmt;
1029         }
1030
1031         emms_c(); //needed to avoid an emms_c() call before every return;
1032
1033
1034         if (*got_picture_ptr){
1035             avctx->frame_number++;
1036             picture->best_effort_timestamp = guess_correct_pts(avctx,
1037                                                             picture->pkt_pts,
1038                                                             picture->pkt_dts);
1039         }
1040     }else
1041         ret= 0;
1042
1043     return ret;
1044 }
1045
1046 #if FF_API_OLD_DECODE_AUDIO
1047 int attribute_align_arg avcodec_decode_audio3(AVCodecContext *avctx, int16_t *samples,
1048                          int *frame_size_ptr,
1049                          AVPacket *avpkt)
1050 {
1051     AVFrame frame;
1052     int ret, got_frame = 0;
1053
1054     if (avctx->get_buffer != avcodec_default_get_buffer) {
1055         av_log(avctx, AV_LOG_ERROR, "Overriding custom get_buffer() for "
1056                "avcodec_decode_audio3()\n");
1057         avctx->get_buffer = avcodec_default_get_buffer;
1058         avctx->release_buffer = avcodec_default_release_buffer;
1059     }
1060
1061     ret = avcodec_decode_audio4(avctx, &frame, &got_frame, avpkt);
1062
1063     if (ret >= 0 && got_frame) {
1064         int ch, plane_size;
1065         int planar = av_sample_fmt_is_planar(avctx->sample_fmt);
1066         int data_size = av_samples_get_buffer_size(&plane_size, avctx->channels,
1067                                                    frame.nb_samples,
1068                                                    avctx->sample_fmt, 1);
1069         if (*frame_size_ptr < data_size) {
1070             av_log(avctx, AV_LOG_ERROR, "output buffer size is too small for "
1071                    "the current frame (%d < %d)\n", *frame_size_ptr, data_size);
1072             return AVERROR(EINVAL);
1073         }
1074
1075         memcpy(samples, frame.extended_data[0], plane_size);
1076
1077         if (planar && avctx->channels > 1) {
1078             uint8_t *out = ((uint8_t *)samples) + plane_size;
1079             for (ch = 1; ch < avctx->channels; ch++) {
1080                 memcpy(out, frame.extended_data[ch], plane_size);
1081                 out += plane_size;
1082             }
1083         }
1084         *frame_size_ptr = data_size;
1085     } else {
1086         *frame_size_ptr = 0;
1087     }
1088     return ret;
1089 }
1090 #endif
1091
1092 int attribute_align_arg avcodec_decode_audio4(AVCodecContext *avctx,
1093                                               AVFrame *frame,
1094                                               int *got_frame_ptr,
1095                                               AVPacket *avpkt)
1096 {
1097     int ret = 0;
1098
1099     *got_frame_ptr = 0;
1100
1101     if (!avpkt->data && avpkt->size) {
1102         av_log(avctx, AV_LOG_ERROR, "invalid packet: NULL data, size != 0\n");
1103         return AVERROR(EINVAL);
1104     }
1105
1106     if ((avctx->codec->capabilities & CODEC_CAP_DELAY) || avpkt->size) {
1107         av_packet_split_side_data(avpkt);
1108         apply_param_change(avctx, avpkt);
1109
1110         avctx->pkt = avpkt;
1111         ret = avctx->codec->decode(avctx, frame, got_frame_ptr, avpkt);
1112         if (ret >= 0 && *got_frame_ptr) {
1113             avctx->frame_number++;
1114             frame->pkt_dts = avpkt->dts;
1115             if (frame->format == AV_SAMPLE_FMT_NONE)
1116                 frame->format = avctx->sample_fmt;
1117         }
1118     }
1119     return ret;
1120 }
1121
1122 int avcodec_decode_subtitle2(AVCodecContext *avctx, AVSubtitle *sub,
1123                             int *got_sub_ptr,
1124                             AVPacket *avpkt)
1125 {
1126     int ret;
1127
1128     avctx->pkt = avpkt;
1129     *got_sub_ptr = 0;
1130     avcodec_get_subtitle_defaults(sub);
1131     ret = avctx->codec->decode(avctx, sub, got_sub_ptr, avpkt);
1132     if (*got_sub_ptr)
1133         avctx->frame_number++;
1134     return ret;
1135 }
1136
1137 void avsubtitle_free(AVSubtitle *sub)
1138 {
1139     int i;
1140
1141     for (i = 0; i < sub->num_rects; i++)
1142     {
1143         av_freep(&sub->rects[i]->pict.data[0]);
1144         av_freep(&sub->rects[i]->pict.data[1]);
1145         av_freep(&sub->rects[i]->pict.data[2]);
1146         av_freep(&sub->rects[i]->pict.data[3]);
1147         av_freep(&sub->rects[i]->text);
1148         av_freep(&sub->rects[i]->ass);
1149         av_freep(&sub->rects[i]);
1150     }
1151
1152     av_freep(&sub->rects);
1153
1154     memset(sub, 0, sizeof(AVSubtitle));
1155 }
1156
1157 av_cold int avcodec_close(AVCodecContext *avctx)
1158 {
1159     /* If there is a user-supplied mutex locking routine, call it. */
1160     if (ff_lockmgr_cb) {
1161         if ((*ff_lockmgr_cb)(&codec_mutex, AV_LOCK_OBTAIN))
1162             return -1;
1163     }
1164
1165     entangled_thread_counter++;
1166     if(entangled_thread_counter != 1){
1167         av_log(avctx, AV_LOG_ERROR, "insufficient thread locking around avcodec_open/close()\n");
1168         entangled_thread_counter--;
1169         return -1;
1170     }
1171
1172     if (HAVE_THREADS && avctx->thread_opaque)
1173         ff_thread_free(avctx);
1174     if (avctx->codec && avctx->codec->close)
1175         avctx->codec->close(avctx);
1176     avcodec_default_free_buffers(avctx);
1177     avctx->coded_frame = NULL;
1178     av_freep(&avctx->internal);
1179     if (avctx->codec && avctx->codec->priv_class)
1180         av_opt_free(avctx->priv_data);
1181     av_opt_free(avctx);
1182     av_freep(&avctx->priv_data);
1183     if(avctx->codec && avctx->codec->encode)
1184         av_freep(&avctx->extradata);
1185     avctx->codec = NULL;
1186     avctx->active_thread_type = 0;
1187     entangled_thread_counter--;
1188
1189     /* Release any user-supplied mutex. */
1190     if (ff_lockmgr_cb) {
1191         (*ff_lockmgr_cb)(&codec_mutex, AV_LOCK_RELEASE);
1192     }
1193     return 0;
1194 }
1195
1196 static enum CodecID remap_deprecated_codec_id(enum CodecID id)
1197 {
1198     switch(id){
1199         case CODEC_ID_G723_1_DEPRECATED : return CODEC_ID_G723_1;
1200         case CODEC_ID_G729_DEPRECATED   : return CODEC_ID_G729;
1201         case CODEC_ID_UTVIDEO_DEPRECATED: return CODEC_ID_UTVIDEO;
1202         default                         : return id;
1203     }
1204 }
1205
1206 AVCodec *avcodec_find_encoder(enum CodecID id)
1207 {
1208     AVCodec *p, *experimental=NULL;
1209     p = first_avcodec;
1210     id= remap_deprecated_codec_id(id);
1211     while (p) {
1212         if (p->encode != NULL && p->id == id) {
1213             if (p->capabilities & CODEC_CAP_EXPERIMENTAL && !experimental) {
1214                 experimental = p;
1215             } else
1216                 return p;
1217         }
1218         p = p->next;
1219     }
1220     return experimental;
1221 }
1222
1223 AVCodec *avcodec_find_encoder_by_name(const char *name)
1224 {
1225     AVCodec *p;
1226     if (!name)
1227         return NULL;
1228     p = first_avcodec;
1229     while (p) {
1230         if (p->encode != NULL && strcmp(name,p->name) == 0)
1231             return p;
1232         p = p->next;
1233     }
1234     return NULL;
1235 }
1236
1237 AVCodec *avcodec_find_decoder(enum CodecID id)
1238 {
1239     AVCodec *p, *experimental=NULL;
1240     p = first_avcodec;
1241     id= remap_deprecated_codec_id(id);
1242     while (p) {
1243         if (p->decode != NULL && p->id == id) {
1244             if (p->capabilities & CODEC_CAP_EXPERIMENTAL && !experimental) {
1245                 experimental = p;
1246             } else
1247                 return p;
1248         }
1249         p = p->next;
1250     }
1251     return experimental;
1252 }
1253
1254 AVCodec *avcodec_find_decoder_by_name(const char *name)
1255 {
1256     AVCodec *p;
1257     if (!name)
1258         return NULL;
1259     p = first_avcodec;
1260     while (p) {
1261         if (p->decode != NULL && strcmp(name,p->name) == 0)
1262             return p;
1263         p = p->next;
1264     }
1265     return NULL;
1266 }
1267
1268 static int get_bit_rate(AVCodecContext *ctx)
1269 {
1270     int bit_rate;
1271     int bits_per_sample;
1272
1273     switch(ctx->codec_type) {
1274     case AVMEDIA_TYPE_VIDEO:
1275     case AVMEDIA_TYPE_DATA:
1276     case AVMEDIA_TYPE_SUBTITLE:
1277     case AVMEDIA_TYPE_ATTACHMENT:
1278         bit_rate = ctx->bit_rate;
1279         break;
1280     case AVMEDIA_TYPE_AUDIO:
1281         bits_per_sample = av_get_bits_per_sample(ctx->codec_id);
1282         bit_rate = bits_per_sample ? ctx->sample_rate * ctx->channels * bits_per_sample : ctx->bit_rate;
1283         break;
1284     default:
1285         bit_rate = 0;
1286         break;
1287     }
1288     return bit_rate;
1289 }
1290
1291 const char *avcodec_get_name(enum CodecID id)
1292 {
1293     AVCodec *codec;
1294
1295 #if !CONFIG_SMALL
1296     switch (id) {
1297 #include "libavcodec/codec_names.h"
1298     }
1299     av_log(NULL, AV_LOG_WARNING, "Codec 0x%x is not in the full list.\n", id);
1300 #endif
1301     codec = avcodec_find_decoder(id);
1302     if (codec)
1303         return codec->name;
1304     codec = avcodec_find_encoder(id);
1305     if (codec)
1306         return codec->name;
1307     return "unknown_codec";
1308 }
1309
1310 size_t av_get_codec_tag_string(char *buf, size_t buf_size, unsigned int codec_tag)
1311 {
1312     int i, len, ret = 0;
1313
1314     for (i = 0; i < 4; i++) {
1315         len = snprintf(buf, buf_size,
1316                        isprint(codec_tag&0xFF) ? "%c" : "[%d]", codec_tag&0xFF);
1317         buf      += len;
1318         buf_size  = buf_size > len ? buf_size - len : 0;
1319         ret      += len;
1320         codec_tag>>=8;
1321     }
1322     return ret;
1323 }
1324
1325 void avcodec_string(char *buf, int buf_size, AVCodecContext *enc, int encode)
1326 {
1327     const char *codec_type;
1328     const char *codec_name;
1329     const char *profile = NULL;
1330     AVCodec *p;
1331     int bitrate;
1332     AVRational display_aspect_ratio;
1333
1334     if (!buf || buf_size <= 0)
1335         return;
1336     codec_type = av_get_media_type_string(enc->codec_type);
1337     codec_name = avcodec_get_name(enc->codec_id);
1338     if (enc->profile != FF_PROFILE_UNKNOWN) {
1339         p = encode ? avcodec_find_encoder(enc->codec_id) :
1340                      avcodec_find_decoder(enc->codec_id);
1341         if (p)
1342             profile = av_get_profile_name(p, enc->profile);
1343     }
1344
1345     snprintf(buf, buf_size, "%s: %s%s", codec_type ? codec_type : "unknown",
1346              codec_name, enc->mb_decision ? " (hq)" : "");
1347     buf[0] ^= 'a' ^ 'A'; /* first letter in uppercase */
1348     if (profile)
1349         snprintf(buf + strlen(buf), buf_size - strlen(buf), " (%s)", profile);
1350     if (enc->codec_tag) {
1351         char tag_buf[32];
1352         av_get_codec_tag_string(tag_buf, sizeof(tag_buf), enc->codec_tag);
1353         snprintf(buf + strlen(buf), buf_size - strlen(buf),
1354                  " (%s / 0x%04X)", tag_buf, enc->codec_tag);
1355     }
1356     switch(enc->codec_type) {
1357     case AVMEDIA_TYPE_VIDEO:
1358         if (enc->pix_fmt != PIX_FMT_NONE) {
1359             snprintf(buf + strlen(buf), buf_size - strlen(buf),
1360                      ", %s",
1361                      av_get_pix_fmt_name(enc->pix_fmt));
1362         }
1363         if (enc->width) {
1364             snprintf(buf + strlen(buf), buf_size - strlen(buf),
1365                      ", %dx%d",
1366                      enc->width, enc->height);
1367             if (enc->sample_aspect_ratio.num) {
1368                 av_reduce(&display_aspect_ratio.num, &display_aspect_ratio.den,
1369                           enc->width*enc->sample_aspect_ratio.num,
1370                           enc->height*enc->sample_aspect_ratio.den,
1371                           1024*1024);
1372                 snprintf(buf + strlen(buf), buf_size - strlen(buf),
1373                          " [SAR %d:%d DAR %d:%d]",
1374                          enc->sample_aspect_ratio.num, enc->sample_aspect_ratio.den,
1375                          display_aspect_ratio.num, display_aspect_ratio.den);
1376             }
1377             if(av_log_get_level() >= AV_LOG_DEBUG){
1378                 int g= av_gcd(enc->time_base.num, enc->time_base.den);
1379                 snprintf(buf + strlen(buf), buf_size - strlen(buf),
1380                      ", %d/%d",
1381                      enc->time_base.num/g, enc->time_base.den/g);
1382             }
1383         }
1384         if (encode) {
1385             snprintf(buf + strlen(buf), buf_size - strlen(buf),
1386                      ", q=%d-%d", enc->qmin, enc->qmax);
1387         }
1388         break;
1389     case AVMEDIA_TYPE_AUDIO:
1390         if (enc->sample_rate) {
1391             snprintf(buf + strlen(buf), buf_size - strlen(buf),
1392                      ", %d Hz", enc->sample_rate);
1393         }
1394         av_strlcat(buf, ", ", buf_size);
1395         av_get_channel_layout_string(buf + strlen(buf), buf_size - strlen(buf), enc->channels, enc->channel_layout);
1396         if (enc->sample_fmt != AV_SAMPLE_FMT_NONE) {
1397             snprintf(buf + strlen(buf), buf_size - strlen(buf),
1398                      ", %s", av_get_sample_fmt_name(enc->sample_fmt));
1399         }
1400         break;
1401     default:
1402         return;
1403     }
1404     if (encode) {
1405         if (enc->flags & CODEC_FLAG_PASS1)
1406             snprintf(buf + strlen(buf), buf_size - strlen(buf),
1407                      ", pass 1");
1408         if (enc->flags & CODEC_FLAG_PASS2)
1409             snprintf(buf + strlen(buf), buf_size - strlen(buf),
1410                      ", pass 2");
1411     }
1412     bitrate = get_bit_rate(enc);
1413     if (bitrate != 0) {
1414         snprintf(buf + strlen(buf), buf_size - strlen(buf),
1415                  ", %d kb/s", bitrate / 1000);
1416     }
1417 }
1418
1419 const char *av_get_profile_name(const AVCodec *codec, int profile)
1420 {
1421     const AVProfile *p;
1422     if (profile == FF_PROFILE_UNKNOWN || !codec->profiles)
1423         return NULL;
1424
1425     for (p = codec->profiles; p->profile != FF_PROFILE_UNKNOWN; p++)
1426         if (p->profile == profile)
1427             return p->name;
1428
1429     return NULL;
1430 }
1431
1432 unsigned avcodec_version( void )
1433 {
1434     av_assert0(CODEC_ID_V410==164);
1435     av_assert0(CODEC_ID_PCM_S8_PLANAR==65563);
1436     av_assert0(CODEC_ID_ADPCM_G722==69660);
1437     av_assert0(CODEC_ID_BMV_AUDIO==86071);
1438     av_assert0(CODEC_ID_SRT==94216);
1439     av_assert0(LIBAVCODEC_VERSION_MICRO >= 100);
1440
1441   return LIBAVCODEC_VERSION_INT;
1442 }
1443
1444 const char *avcodec_configuration(void)
1445 {
1446     return FFMPEG_CONFIGURATION;
1447 }
1448
1449 const char *avcodec_license(void)
1450 {
1451 #define LICENSE_PREFIX "libavcodec license: "
1452     return LICENSE_PREFIX FFMPEG_LICENSE + sizeof(LICENSE_PREFIX) - 1;
1453 }
1454
1455 void avcodec_flush_buffers(AVCodecContext *avctx)
1456 {
1457     if(HAVE_THREADS && avctx->active_thread_type&FF_THREAD_FRAME)
1458         ff_thread_flush(avctx);
1459     else if(avctx->codec->flush)
1460         avctx->codec->flush(avctx);
1461 }
1462
1463 static void video_free_buffers(AVCodecContext *s)
1464 {
1465     AVCodecInternal *avci = s->internal;
1466     int i, j;
1467
1468     if (!avci->buffer)
1469         return;
1470
1471     if (avci->buffer_count)
1472         av_log(s, AV_LOG_WARNING, "Found %i unreleased buffers!\n",
1473                avci->buffer_count);
1474     for(i=0; i<INTERNAL_BUFFER_SIZE; i++){
1475         InternalBuffer *buf = &avci->buffer[i];
1476         for(j=0; j<4; j++){
1477             av_freep(&buf->base[j]);
1478             buf->data[j]= NULL;
1479         }
1480     }
1481     av_freep(&avci->buffer);
1482
1483     avci->buffer_count=0;
1484 }
1485
1486 static void audio_free_buffers(AVCodecContext *avctx)
1487 {
1488     AVCodecInternal *avci = avctx->internal;
1489     InternalBuffer *buf;
1490
1491     if (!avci->buffer)
1492         return;
1493     buf = avci->buffer;
1494
1495     if (buf->extended_data) {
1496         av_free(buf->extended_data[0]);
1497         if (buf->extended_data != buf->data)
1498             av_free(buf->extended_data);
1499     }
1500     av_freep(&avci->buffer);
1501 }
1502
1503 void avcodec_default_free_buffers(AVCodecContext *avctx)
1504 {
1505     switch (avctx->codec_type) {
1506     case AVMEDIA_TYPE_VIDEO:
1507         video_free_buffers(avctx);
1508         break;
1509     case AVMEDIA_TYPE_AUDIO:
1510         audio_free_buffers(avctx);
1511         break;
1512     default:
1513         break;
1514     }
1515 }
1516
1517 #if FF_API_OLD_FF_PICT_TYPES
1518 char av_get_pict_type_char(int pict_type){
1519     return av_get_picture_type_char(pict_type);
1520 }
1521 #endif
1522
1523 int av_get_bits_per_sample(enum CodecID codec_id){
1524     switch(codec_id){
1525     case CODEC_ID_ADPCM_SBPRO_2:
1526         return 2;
1527     case CODEC_ID_ADPCM_SBPRO_3:
1528         return 3;
1529     case CODEC_ID_ADPCM_SBPRO_4:
1530     case CODEC_ID_ADPCM_CT:
1531     case CODEC_ID_ADPCM_IMA_WAV:
1532     case CODEC_ID_ADPCM_IMA_QT:
1533     case CODEC_ID_ADPCM_SWF:
1534     case CODEC_ID_ADPCM_MS:
1535     case CODEC_ID_ADPCM_YAMAHA:
1536     case CODEC_ID_ADPCM_G722:
1537         return 4;
1538     case CODEC_ID_PCM_ALAW:
1539     case CODEC_ID_PCM_MULAW:
1540     case CODEC_ID_PCM_S8:
1541     case CODEC_ID_PCM_U8:
1542     case CODEC_ID_PCM_ZORK:
1543         return 8;
1544     case CODEC_ID_PCM_S16BE:
1545     case CODEC_ID_PCM_S16LE:
1546     case CODEC_ID_PCM_S16LE_PLANAR:
1547     case CODEC_ID_PCM_U16BE:
1548     case CODEC_ID_PCM_U16LE:
1549         return 16;
1550     case CODEC_ID_PCM_S24DAUD:
1551     case CODEC_ID_PCM_S24BE:
1552     case CODEC_ID_PCM_S24LE:
1553     case CODEC_ID_PCM_U24BE:
1554     case CODEC_ID_PCM_U24LE:
1555         return 24;
1556     case CODEC_ID_PCM_S32BE:
1557     case CODEC_ID_PCM_S32LE:
1558     case CODEC_ID_PCM_U32BE:
1559     case CODEC_ID_PCM_U32LE:
1560     case CODEC_ID_PCM_F32BE:
1561     case CODEC_ID_PCM_F32LE:
1562         return 32;
1563     case CODEC_ID_PCM_F64BE:
1564     case CODEC_ID_PCM_F64LE:
1565         return 64;
1566     default:
1567         return 0;
1568     }
1569 }
1570
1571 #if FF_API_OLD_SAMPLE_FMT
1572 int av_get_bits_per_sample_format(enum AVSampleFormat sample_fmt) {
1573     return av_get_bytes_per_sample(sample_fmt) << 3;
1574 }
1575 #endif
1576
1577 #if !HAVE_THREADS
1578 int ff_thread_init(AVCodecContext *s){
1579     return -1;
1580 }
1581 #endif
1582
1583 unsigned int av_xiphlacing(unsigned char *s, unsigned int v)
1584 {
1585     unsigned int n = 0;
1586
1587     while(v >= 0xff) {
1588         *s++ = 0xff;
1589         v -= 0xff;
1590         n++;
1591     }
1592     *s = v;
1593     n++;
1594     return n;
1595 }
1596
1597 int ff_match_2uint16(const uint16_t (*tab)[2], int size, int a, int b){
1598     int i;
1599     for(i=0; i<size && !(tab[i][0]==a && tab[i][1]==b); i++);
1600     return i;
1601 }
1602
1603 void av_log_missing_feature(void *avc, const char *feature, int want_sample)
1604 {
1605     av_log(avc, AV_LOG_WARNING, "%s not implemented. Update your FFmpeg "
1606             "version to the newest one from Git. If the problem still "
1607             "occurs, it means that your file has a feature which has not "
1608             "been implemented.\n", feature);
1609     if(want_sample)
1610         av_log_ask_for_sample(avc, NULL);
1611 }
1612
1613 void av_log_ask_for_sample(void *avc, const char *msg, ...)
1614 {
1615     va_list argument_list;
1616
1617     va_start(argument_list, msg);
1618
1619     if (msg)
1620         av_vlog(avc, AV_LOG_WARNING, msg, argument_list);
1621     av_log(avc, AV_LOG_WARNING, "If you want to help, upload a sample "
1622             "of this file to ftp://upload.ffmpeg.org/MPlayer/incoming/ "
1623             "and contact the ffmpeg-devel mailing list.\n");
1624
1625     va_end(argument_list);
1626 }
1627
1628 static AVHWAccel *first_hwaccel = NULL;
1629
1630 void av_register_hwaccel(AVHWAccel *hwaccel)
1631 {
1632     AVHWAccel **p = &first_hwaccel;
1633     while (*p)
1634         p = &(*p)->next;
1635     *p = hwaccel;
1636     hwaccel->next = NULL;
1637 }
1638
1639 AVHWAccel *av_hwaccel_next(AVHWAccel *hwaccel)
1640 {
1641     return hwaccel ? hwaccel->next : first_hwaccel;
1642 }
1643
1644 AVHWAccel *ff_find_hwaccel(enum CodecID codec_id, enum PixelFormat pix_fmt)
1645 {
1646     AVHWAccel *hwaccel=NULL;
1647
1648     while((hwaccel= av_hwaccel_next(hwaccel))){
1649         if (   hwaccel->id      == codec_id
1650             && hwaccel->pix_fmt == pix_fmt)
1651             return hwaccel;
1652     }
1653     return NULL;
1654 }
1655
1656 int av_lockmgr_register(int (*cb)(void **mutex, enum AVLockOp op))
1657 {
1658     if (ff_lockmgr_cb) {
1659         if (ff_lockmgr_cb(&codec_mutex, AV_LOCK_DESTROY))
1660             return -1;
1661         if (ff_lockmgr_cb(&avformat_mutex, AV_LOCK_DESTROY))
1662             return -1;
1663     }
1664
1665     ff_lockmgr_cb = cb;
1666
1667     if (ff_lockmgr_cb) {
1668         if (ff_lockmgr_cb(&codec_mutex, AV_LOCK_CREATE))
1669             return -1;
1670         if (ff_lockmgr_cb(&avformat_mutex, AV_LOCK_CREATE))
1671             return -1;
1672     }
1673     return 0;
1674 }
1675
1676 int avpriv_lock_avformat(void)
1677 {
1678     if (ff_lockmgr_cb) {
1679         if ((*ff_lockmgr_cb)(&avformat_mutex, AV_LOCK_OBTAIN))
1680             return -1;
1681     }
1682     return 0;
1683 }
1684
1685 int avpriv_unlock_avformat(void)
1686 {
1687     if (ff_lockmgr_cb) {
1688         if ((*ff_lockmgr_cb)(&avformat_mutex, AV_LOCK_RELEASE))
1689             return -1;
1690     }
1691     return 0;
1692 }
1693
1694 unsigned int avpriv_toupper4(unsigned int x)
1695 {
1696     return     toupper( x     &0xFF)
1697             + (toupper((x>>8 )&0xFF)<<8 )
1698             + (toupper((x>>16)&0xFF)<<16)
1699             + (toupper((x>>24)&0xFF)<<24);
1700 }
1701
1702 #if !HAVE_THREADS
1703
1704 int ff_thread_get_buffer(AVCodecContext *avctx, AVFrame *f)
1705 {
1706     f->owner = avctx;
1707
1708     ff_init_buffer_info(avctx, f);
1709
1710     return avctx->get_buffer(avctx, f);
1711 }
1712
1713 void ff_thread_release_buffer(AVCodecContext *avctx, AVFrame *f)
1714 {
1715     f->owner->release_buffer(f->owner, f);
1716 }
1717
1718 void ff_thread_finish_setup(AVCodecContext *avctx)
1719 {
1720 }
1721
1722 void ff_thread_report_progress(AVFrame *f, int progress, int field)
1723 {
1724 }
1725
1726 void ff_thread_await_progress(AVFrame *f, int progress, int field)
1727 {
1728 }
1729
1730 #endif
1731
1732 #if FF_API_THREAD_INIT
1733 int avcodec_thread_init(AVCodecContext *s, int thread_count)
1734 {
1735     s->thread_count = thread_count;
1736     return ff_thread_init(s);
1737 }
1738 #endif
1739
1740 enum AVMediaType avcodec_get_type(enum CodecID codec_id)
1741 {
1742     AVCodec *c= avcodec_find_decoder(codec_id);
1743     if(!c)
1744         c= avcodec_find_encoder(codec_id);
1745     if(c)
1746         return c->type;
1747
1748     if (codec_id <= CODEC_ID_NONE)
1749         return AVMEDIA_TYPE_UNKNOWN;
1750     else if (codec_id < CODEC_ID_FIRST_AUDIO)
1751         return AVMEDIA_TYPE_VIDEO;
1752     else if (codec_id < CODEC_ID_FIRST_SUBTITLE)
1753         return AVMEDIA_TYPE_AUDIO;
1754     else if (codec_id < CODEC_ID_FIRST_UNKNOWN)
1755         return AVMEDIA_TYPE_SUBTITLE;
1756
1757     return AVMEDIA_TYPE_UNKNOWN;
1758 }