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