]> git.sesse.net Git - ffmpeg/blob - libavcodec/utils.c
Merge remote-tracking branch 'qatar/master'
[ffmpeg] / libavcodec / utils.c
1 /*
2  * utils for libavcodec
3  * Copyright (c) 2001 Fabrice Bellard
4  * Copyright (c) 2002-2004 Michael Niedermayer <michaelni@gmx.at>
5  *
6  * This file is part of FFmpeg.
7  *
8  * FFmpeg is free software; you can redistribute it and/or
9  * modify it under the terms of the GNU Lesser General Public
10  * License as published by the Free Software Foundation; either
11  * version 2.1 of the License, or (at your option) any later version.
12  *
13  * FFmpeg is distributed in the hope that it will be useful,
14  * but WITHOUT ANY WARRANTY; without even the implied warranty of
15  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
16  * Lesser General Public License for more details.
17  *
18  * You should have received a copy of the GNU Lesser General Public
19  * License along with FFmpeg; if not, write to the Free Software
20  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
21  */
22
23 /**
24  * @file
25  * utils.
26  */
27
28 #include "libavutil/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 "libavutil/avassert.h"
38 #include "avcodec.h"
39 #include "dsputil.h"
40 #include "libavutil/opt.h"
41 #include "imgconvert.h"
42 #include "thread.h"
43 #include "audioconvert.h"
44 #include "internal.h"
45 #include "bytestream.h"
46 #include <stdlib.h>
47 #include <stdarg.h>
48 #include <limits.h>
49 #include <float.h>
50
51 static int volatile entangled_thread_counter=0;
52 static int (*ff_lockmgr_cb)(void **mutex, enum AVLockOp op);
53 static void *codec_mutex;
54 static void *avformat_mutex;
55
56 void *av_fast_realloc(void *ptr, unsigned int *size, size_t min_size)
57 {
58     if(min_size < *size)
59         return ptr;
60
61     min_size= FFMAX(17*min_size/16 + 32, min_size);
62
63     ptr= av_realloc(ptr, min_size);
64     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
65         min_size= 0;
66
67     *size= min_size;
68
69     return ptr;
70 }
71
72 static inline int ff_fast_malloc(void *ptr, unsigned int *size, size_t min_size, int zero_realloc)
73 {
74     void **p = ptr;
75     if (min_size < *size)
76         return 0;
77     min_size= FFMAX(17*min_size/16 + 32, min_size);
78     av_free(*p);
79     *p = zero_realloc ? av_mallocz(min_size) : av_malloc(min_size);
80     if (!*p) min_size = 0;
81     *size= min_size;
82     return 1;
83 }
84
85 void av_fast_malloc(void *ptr, unsigned int *size, size_t min_size)
86 {
87     ff_fast_malloc(ptr, size, min_size, 0);
88 }
89
90 void av_fast_padded_malloc(void *ptr, unsigned int *size, size_t min_size)
91 {
92     uint8_t **p = ptr;
93     if (min_size > SIZE_MAX - FF_INPUT_BUFFER_PADDING_SIZE) {
94         av_freep(p);
95         *size = 0;
96         return;
97     }
98     if (!ff_fast_malloc(p, size, min_size + FF_INPUT_BUFFER_PADDING_SIZE, 1))
99         memset(*p + min_size, 0, FF_INPUT_BUFFER_PADDING_SIZE);
100 }
101
102 /* encoder management */
103 static AVCodec *first_avcodec = NULL;
104
105 AVCodec *av_codec_next(AVCodec *c){
106     if(c) return c->next;
107     else  return first_avcodec;
108 }
109
110 static void avcodec_init(void)
111 {
112     static int initialized = 0;
113
114     if (initialized != 0)
115         return;
116     initialized = 1;
117
118     ff_dsputil_static_init();
119 }
120
121 int av_codec_is_encoder(AVCodec *codec)
122 {
123     return codec && (codec->encode || codec->encode2);
124 }
125
126 int av_codec_is_decoder(AVCodec *codec)
127 {
128     return codec && codec->decode;
129 }
130
131 void avcodec_register(AVCodec *codec)
132 {
133     AVCodec **p;
134     avcodec_init();
135     p = &first_avcodec;
136     while (*p != NULL) p = &(*p)->next;
137     *p = codec;
138     codec->next = NULL;
139
140     if (codec->init_static_data)
141         codec->init_static_data(codec);
142 }
143
144 unsigned avcodec_get_edge_width(void)
145 {
146     return EDGE_WIDTH;
147 }
148
149 void avcodec_set_dimensions(AVCodecContext *s, int width, int height){
150     s->coded_width = width;
151     s->coded_height= height;
152     s->width = -((-width )>>s->lowres);
153     s->height= -((-height)>>s->lowres);
154 }
155
156 #define INTERNAL_BUFFER_SIZE (32+1)
157
158 void avcodec_align_dimensions2(AVCodecContext *s, int *width, int *height,
159                                int linesize_align[AV_NUM_DATA_POINTERS])
160 {
161     int i;
162     int w_align= 1;
163     int h_align= 1;
164
165     switch(s->pix_fmt){
166     case PIX_FMT_YUV420P:
167     case PIX_FMT_YUYV422:
168     case PIX_FMT_UYVY422:
169     case PIX_FMT_YUV422P:
170     case PIX_FMT_YUV440P:
171     case PIX_FMT_YUV444P:
172     case PIX_FMT_GBRP:
173     case PIX_FMT_GRAY8:
174     case PIX_FMT_GRAY16BE:
175     case PIX_FMT_GRAY16LE:
176     case PIX_FMT_YUVJ420P:
177     case PIX_FMT_YUVJ422P:
178     case PIX_FMT_YUVJ440P:
179     case PIX_FMT_YUVJ444P:
180     case PIX_FMT_YUVA420P:
181     case PIX_FMT_YUVA422P:
182     case PIX_FMT_YUVA444P:
183     case PIX_FMT_YUV420P9LE:
184     case PIX_FMT_YUV420P9BE:
185     case PIX_FMT_YUV420P10LE:
186     case PIX_FMT_YUV420P10BE:
187     case PIX_FMT_YUV422P9LE:
188     case PIX_FMT_YUV422P9BE:
189     case PIX_FMT_YUV422P10LE:
190     case PIX_FMT_YUV422P10BE:
191     case PIX_FMT_YUV444P9LE:
192     case PIX_FMT_YUV444P9BE:
193     case PIX_FMT_YUV444P10LE:
194     case PIX_FMT_YUV444P10BE:
195     case PIX_FMT_GBRP9LE:
196     case PIX_FMT_GBRP9BE:
197     case PIX_FMT_GBRP10LE:
198     case PIX_FMT_GBRP10BE:
199         w_align = 16; //FIXME assume 16 pixel per macroblock
200         h_align = 16 * 2; // interlaced needs 2 macroblocks height
201         break;
202     case PIX_FMT_YUV411P:
203     case PIX_FMT_UYYVYY411:
204         w_align=32;
205         h_align=8;
206         break;
207     case PIX_FMT_YUV410P:
208         if(s->codec_id == CODEC_ID_SVQ1){
209             w_align=64;
210             h_align=64;
211         }
212     case PIX_FMT_RGB555:
213         if(s->codec_id == CODEC_ID_RPZA){
214             w_align=4;
215             h_align=4;
216         }
217     case PIX_FMT_PAL8:
218     case PIX_FMT_BGR8:
219     case PIX_FMT_RGB8:
220         if(s->codec_id == CODEC_ID_SMC){
221             w_align=4;
222             h_align=4;
223         }
224         break;
225     case PIX_FMT_BGR24:
226         if((s->codec_id == CODEC_ID_MSZH) || (s->codec_id == CODEC_ID_ZLIB)){
227             w_align=4;
228             h_align=4;
229         }
230         break;
231     default:
232         w_align= 1;
233         h_align= 1;
234         break;
235     }
236
237     if(s->codec_id == CODEC_ID_IFF_ILBM || s->codec_id == CODEC_ID_IFF_BYTERUN1){
238         w_align= FFMAX(w_align, 8);
239     }
240
241     *width = FFALIGN(*width , w_align);
242     *height= FFALIGN(*height, h_align);
243     if(s->codec_id == CODEC_ID_H264 || s->lowres)
244         *height+=2; // some of the optimized chroma MC reads one line too much
245                     // which is also done in mpeg decoders with lowres > 0
246
247     for (i = 0; i < 4; i++)
248         linesize_align[i] = STRIDE_ALIGN;
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 void ff_init_buffer_info(AVCodecContext *s, AVFrame *pic)
264 {
265     if (s->pkt) {
266         pic->pkt_pts = s->pkt->pts;
267         pic->pkt_pos = s->pkt->pos;
268         pic->pkt_duration = s->pkt->duration;
269     } else {
270         pic->pkt_pts = AV_NOPTS_VALUE;
271         pic->pkt_pos = -1;
272         pic->pkt_duration = 0;
273     }
274     pic->reordered_opaque= s->reordered_opaque;
275     pic->sample_aspect_ratio = s->sample_aspect_ratio;
276     pic->width               = s->width;
277     pic->height              = s->height;
278     pic->format              = s->pix_fmt;
279 }
280
281 int avcodec_fill_audio_frame(AVFrame *frame, int nb_channels,
282                              enum AVSampleFormat sample_fmt, const uint8_t *buf,
283                              int buf_size, int align)
284 {
285     int ch, planar, needed_size, ret = 0;
286
287     needed_size = av_samples_get_buffer_size(NULL, nb_channels,
288                                              frame->nb_samples, sample_fmt,
289                                              align);
290     if (buf_size < needed_size)
291         return AVERROR(EINVAL);
292
293     planar = av_sample_fmt_is_planar(sample_fmt);
294     if (planar && nb_channels > AV_NUM_DATA_POINTERS) {
295         if (!(frame->extended_data = av_mallocz(nb_channels *
296                                                 sizeof(*frame->extended_data))))
297             return AVERROR(ENOMEM);
298     } else {
299         frame->extended_data = frame->data;
300     }
301
302     if ((ret = av_samples_fill_arrays(frame->extended_data, &frame->linesize[0],
303                                       (uint8_t *)(intptr_t)buf, nb_channels, frame->nb_samples,
304                                       sample_fmt, align)) < 0) {
305         if (frame->extended_data != frame->data)
306             av_freep(&frame->extended_data);
307         return ret;
308     }
309     if (frame->extended_data != frame->data) {
310         for (ch = 0; ch < AV_NUM_DATA_POINTERS; ch++)
311             frame->data[ch] = frame->extended_data[ch];
312     }
313
314     return ret;
315 }
316
317 static int audio_get_buffer(AVCodecContext *avctx, AVFrame *frame)
318 {
319     AVCodecInternal *avci = avctx->internal;
320     InternalBuffer *buf;
321     int buf_size, ret;
322
323     buf_size = av_samples_get_buffer_size(NULL, avctx->channels,
324                                           frame->nb_samples, avctx->sample_fmt,
325                                           0);
326     if (buf_size < 0)
327         return AVERROR(EINVAL);
328
329     /* allocate InternalBuffer if needed */
330     if (!avci->buffer) {
331         avci->buffer = av_mallocz(sizeof(InternalBuffer));
332         if (!avci->buffer)
333             return AVERROR(ENOMEM);
334     }
335     buf = avci->buffer;
336
337     /* if there is a previously-used internal buffer, check its size and
338        channel count to see if we can reuse it */
339     if (buf->extended_data) {
340         /* if current buffer is too small, free it */
341         if (buf->extended_data[0] && buf_size > buf->audio_data_size) {
342             av_free(buf->extended_data[0]);
343             if (buf->extended_data != buf->data)
344                 av_freep(&buf->extended_data);
345             buf->extended_data = NULL;
346             buf->data[0] = NULL;
347         }
348         /* if number of channels has changed, reset and/or free extended data
349            pointers but leave data buffer in buf->data[0] for reuse */
350         if (buf->nb_channels != avctx->channels) {
351             if (buf->extended_data != buf->data)
352                 av_free(buf->extended_data);
353             buf->extended_data = NULL;
354         }
355     }
356
357     /* if there is no previous buffer or the previous buffer cannot be used
358        as-is, allocate a new buffer and/or rearrange the channel pointers */
359     if (!buf->extended_data) {
360         if (!buf->data[0]) {
361             if (!(buf->data[0] = av_mallocz(buf_size)))
362                 return AVERROR(ENOMEM);
363             buf->audio_data_size = buf_size;
364         }
365         if ((ret = avcodec_fill_audio_frame(frame, avctx->channels,
366                                             avctx->sample_fmt, buf->data[0],
367                                             buf->audio_data_size, 0)))
368             return ret;
369
370         if (frame->extended_data == frame->data)
371             buf->extended_data = buf->data;
372         else
373             buf->extended_data = frame->extended_data;
374         memcpy(buf->data, frame->data, sizeof(frame->data));
375         buf->linesize[0] = frame->linesize[0];
376         buf->nb_channels = avctx->channels;
377     } else {
378         /* copy InternalBuffer info to the AVFrame */
379         frame->extended_data = buf->extended_data;
380         frame->linesize[0]   = buf->linesize[0];
381         memcpy(frame->data, buf->data, sizeof(frame->data));
382     }
383
384     frame->type          = FF_BUFFER_TYPE_INTERNAL;
385
386     if (avctx->pkt) {
387         frame->pkt_pts = avctx->pkt->pts;
388         frame->pkt_pos = avctx->pkt->pos;
389         frame->pkt_duration = avctx->pkt->duration;
390     } else {
391         frame->pkt_pts = AV_NOPTS_VALUE;
392         frame->pkt_pos = -1;
393         frame->pkt_duration = 0;
394     }
395
396     frame->reordered_opaque = avctx->reordered_opaque;
397
398     frame->sample_rate    = avctx->sample_rate;
399     frame->format         = avctx->sample_fmt;
400     frame->channel_layout = avctx->channel_layout;
401
402     if (avctx->debug & FF_DEBUG_BUFFERS)
403         av_log(avctx, AV_LOG_DEBUG, "default_get_buffer called on frame %p, "
404                "internal audio buffer used\n", frame);
405
406     return 0;
407 }
408
409 static int video_get_buffer(AVCodecContext *s, AVFrame *pic)
410 {
411     int i;
412     int w= s->width;
413     int h= s->height;
414     InternalBuffer *buf;
415     AVCodecInternal *avci = s->internal;
416
417     if(pic->data[0]!=NULL) {
418         av_log(s, AV_LOG_ERROR, "pic->data[0]!=NULL in avcodec_default_get_buffer\n");
419         return -1;
420     }
421     if(avci->buffer_count >= INTERNAL_BUFFER_SIZE) {
422         av_log(s, AV_LOG_ERROR, "buffer_count overflow (missing release_buffer?)\n");
423         return -1;
424     }
425
426     if(av_image_check_size(w, h, 0, s) || s->pix_fmt<0)
427         return -1;
428
429     if (!avci->buffer) {
430         avci->buffer = av_mallocz((INTERNAL_BUFFER_SIZE+1) *
431                                   sizeof(InternalBuffer));
432     }
433
434     buf = &avci->buffer[avci->buffer_count];
435
436     if(buf->base[0] && (buf->width != w || buf->height != h || buf->pix_fmt != s->pix_fmt)){
437         for (i = 0; i < AV_NUM_DATA_POINTERS; i++) {
438             av_freep(&buf->base[i]);
439             buf->data[i]= NULL;
440         }
441     }
442
443     if (!buf->base[0]) {
444         int h_chroma_shift, v_chroma_shift;
445         int size[4] = {0};
446         int tmpsize;
447         int unaligned;
448         AVPicture picture;
449         int stride_align[AV_NUM_DATA_POINTERS];
450         const int pixel_size = av_pix_fmt_descriptors[s->pix_fmt].comp[0].step_minus1+1;
451
452         avcodec_get_chroma_sub_sample(s->pix_fmt, &h_chroma_shift, &v_chroma_shift);
453
454         avcodec_align_dimensions2(s, &w, &h, stride_align);
455
456         if(!(s->flags&CODEC_FLAG_EMU_EDGE)){
457             w+= EDGE_WIDTH*2;
458             h+= EDGE_WIDTH*2;
459         }
460
461         do {
462             // NOTE: do not align linesizes individually, this breaks e.g. assumptions
463             // that linesize[0] == 2*linesize[1] in the MPEG-encoder for 4:2:2
464             av_image_fill_linesizes(picture.linesize, s->pix_fmt, w);
465             // increase alignment of w for next try (rhs gives the lowest bit set in w)
466             w += w & ~(w-1);
467
468             unaligned = 0;
469             for (i=0; i<4; i++){
470                 unaligned |= picture.linesize[i] % stride_align[i];
471             }
472         } while (unaligned);
473
474         tmpsize = av_image_fill_pointers(picture.data, s->pix_fmt, h, NULL, picture.linesize);
475         if (tmpsize < 0)
476             return -1;
477
478         for (i=0; i<3 && picture.data[i+1]; i++)
479             size[i] = picture.data[i+1] - picture.data[i];
480         size[i] = tmpsize - (picture.data[i] - picture.data[0]);
481
482         memset(buf->base, 0, sizeof(buf->base));
483         memset(buf->data, 0, sizeof(buf->data));
484
485         for(i=0; i<4 && size[i]; i++){
486             const int h_shift= i==0 ? 0 : h_chroma_shift;
487             const int v_shift= i==0 ? 0 : v_chroma_shift;
488
489             buf->linesize[i]= picture.linesize[i];
490
491             buf->base[i]= av_malloc(size[i]+16); //FIXME 16
492             if(buf->base[i]==NULL) return -1;
493             memset(buf->base[i], 128, size[i]);
494
495             // no edge if EDGE EMU or not planar YUV
496             if((s->flags&CODEC_FLAG_EMU_EDGE) || !size[2])
497                 buf->data[i] = buf->base[i];
498             else
499                 buf->data[i] = buf->base[i] + FFALIGN((buf->linesize[i]*EDGE_WIDTH>>v_shift) + (pixel_size*EDGE_WIDTH>>h_shift), stride_align[i]);
500         }
501         for (; i < AV_NUM_DATA_POINTERS; i++) {
502             buf->base[i] = buf->data[i] = NULL;
503             buf->linesize[i] = 0;
504         }
505         if(size[1] && !size[2])
506             ff_set_systematic_pal2((uint32_t*)buf->data[1], s->pix_fmt);
507         buf->width  = s->width;
508         buf->height = s->height;
509         buf->pix_fmt= s->pix_fmt;
510     }
511     pic->type= FF_BUFFER_TYPE_INTERNAL;
512
513     for (i = 0; i < AV_NUM_DATA_POINTERS; i++) {
514         pic->base[i]= buf->base[i];
515         pic->data[i]= buf->data[i];
516         pic->linesize[i]= buf->linesize[i];
517     }
518     pic->extended_data = pic->data;
519     avci->buffer_count++;
520     pic->width  = buf->width;
521     pic->height = buf->height;
522     pic->format = buf->pix_fmt;
523     pic->sample_aspect_ratio = s->sample_aspect_ratio;
524
525     if (s->pkt) {
526         pic->pkt_pts = s->pkt->pts;
527         pic->pkt_pos = s->pkt->pos;
528         pic->pkt_duration = s->pkt->duration;
529     } else {
530         pic->pkt_pts = AV_NOPTS_VALUE;
531         pic->pkt_pos = -1;
532         pic->pkt_duration = 0;
533     }
534     pic->reordered_opaque= s->reordered_opaque;
535     pic->sample_aspect_ratio = s->sample_aspect_ratio;
536     pic->width               = s->width;
537     pic->height              = s->height;
538     pic->format              = s->pix_fmt;
539
540     if(s->debug&FF_DEBUG_BUFFERS)
541         av_log(s, AV_LOG_DEBUG, "default_get_buffer called on pic %p, %d "
542                "buffers used\n", pic, avci->buffer_count);
543
544     return 0;
545 }
546
547 int avcodec_default_get_buffer(AVCodecContext *avctx, AVFrame *frame)
548 {
549     switch (avctx->codec_type) {
550     case AVMEDIA_TYPE_VIDEO:
551         return video_get_buffer(avctx, frame);
552     case AVMEDIA_TYPE_AUDIO:
553         return audio_get_buffer(avctx, frame);
554     default:
555         return -1;
556     }
557 }
558
559 void avcodec_default_release_buffer(AVCodecContext *s, AVFrame *pic){
560     int i;
561     InternalBuffer *buf, *last;
562     AVCodecInternal *avci = s->internal;
563
564     av_assert0(s->codec_type == AVMEDIA_TYPE_VIDEO);
565
566     assert(pic->type==FF_BUFFER_TYPE_INTERNAL);
567     assert(avci->buffer_count);
568
569     if (avci->buffer) {
570         buf = NULL; /* avoids warning */
571         for (i = 0; i < avci->buffer_count; i++) { //just 3-5 checks so is not worth to optimize
572             buf = &avci->buffer[i];
573             if (buf->data[0] == pic->data[0])
574                 break;
575         }
576         av_assert0(i < avci->buffer_count);
577         avci->buffer_count--;
578         last = &avci->buffer[avci->buffer_count];
579
580         if (buf != last)
581             FFSWAP(InternalBuffer, *buf, *last);
582     }
583
584     for (i = 0; i < AV_NUM_DATA_POINTERS; i++) {
585         pic->data[i]=NULL;
586 //        pic->base[i]=NULL;
587     }
588 //printf("R%X\n", pic->opaque);
589
590     if(s->debug&FF_DEBUG_BUFFERS)
591         av_log(s, AV_LOG_DEBUG, "default_release_buffer called on pic %p, %d "
592                "buffers used\n", pic, avci->buffer_count);
593 }
594
595 int avcodec_default_reget_buffer(AVCodecContext *s, AVFrame *pic){
596     AVFrame temp_pic;
597     int i;
598
599     av_assert0(s->codec_type == AVMEDIA_TYPE_VIDEO);
600
601     if (pic->data[0] && (pic->width != s->width || pic->height != s->height || pic->format != s->pix_fmt)) {
602         av_log(s, AV_LOG_WARNING, "Picture changed from size:%dx%d fmt:%s to size:%dx%d fmt:%s in reget buffer()\n",
603                pic->width, pic->height, av_get_pix_fmt_name(pic->format), s->width, s->height, av_get_pix_fmt_name(s->pix_fmt));
604         s->release_buffer(s, pic);
605     }
606
607     ff_init_buffer_info(s, pic);
608
609     /* If no picture return a new buffer */
610     if(pic->data[0] == NULL) {
611         /* We will copy from buffer, so must be readable */
612         pic->buffer_hints |= FF_BUFFER_HINTS_READABLE;
613         return s->get_buffer(s, pic);
614     }
615
616     assert(s->pix_fmt == pic->format);
617
618     /* If internal buffer type return the same buffer */
619     if(pic->type == FF_BUFFER_TYPE_INTERNAL) {
620         return 0;
621     }
622
623     /*
624      * Not internal type and reget_buffer not overridden, emulate cr buffer
625      */
626     temp_pic = *pic;
627     for(i = 0; i < AV_NUM_DATA_POINTERS; i++)
628         pic->data[i] = pic->base[i] = NULL;
629     pic->opaque = NULL;
630     /* Allocate new frame */
631     if (s->get_buffer(s, pic))
632         return -1;
633     /* Copy image data from old buffer to new buffer */
634     av_picture_copy((AVPicture*)pic, (AVPicture*)&temp_pic, s->pix_fmt, s->width,
635              s->height);
636     s->release_buffer(s, &temp_pic); // Release old frame
637     return 0;
638 }
639
640 int avcodec_default_execute(AVCodecContext *c, int (*func)(AVCodecContext *c2, void *arg2),void *arg, int *ret, int count, int size){
641     int i;
642
643     for(i=0; i<count; i++){
644         int r= func(c, (char*)arg + i*size);
645         if(ret) ret[i]= r;
646     }
647     return 0;
648 }
649
650 int avcodec_default_execute2(AVCodecContext *c, int (*func)(AVCodecContext *c2, void *arg2, int jobnr, int threadnr),void *arg, int *ret, int count){
651     int i;
652
653     for(i=0; i<count; i++){
654         int r= func(c, arg, i, 0);
655         if(ret) ret[i]= r;
656     }
657     return 0;
658 }
659
660 enum PixelFormat avcodec_default_get_format(struct AVCodecContext *s, const enum PixelFormat *fmt){
661     while (*fmt != PIX_FMT_NONE && ff_is_hwaccel_pix_fmt(*fmt))
662         ++fmt;
663     return fmt[0];
664 }
665
666 void avcodec_get_frame_defaults(AVFrame *pic){
667     memset(pic, 0, sizeof(AVFrame));
668
669     pic->pts = pic->pkt_dts = pic->pkt_pts = pic->best_effort_timestamp = AV_NOPTS_VALUE;
670     pic->pkt_duration = 0;
671     pic->pkt_pos = -1;
672     pic->key_frame= 1;
673     pic->sample_aspect_ratio = (AVRational){0, 1};
674     pic->format = -1;           /* unknown */
675 }
676
677 AVFrame *avcodec_alloc_frame(void){
678     AVFrame *pic= av_malloc(sizeof(AVFrame));
679
680     if(pic==NULL) return NULL;
681
682     avcodec_get_frame_defaults(pic);
683
684     return pic;
685 }
686
687 #define MAKE_ACCESSORS(str, name, type, field) \
688     type av_##name##_get_##field(const str *s) { return s->field; } \
689     void av_##name##_set_##field(str *s, type v) { s->field = v; }
690
691 MAKE_ACCESSORS(AVFrame, frame, int64_t, best_effort_timestamp)
692 MAKE_ACCESSORS(AVFrame, frame, int64_t, pkt_duration)
693 MAKE_ACCESSORS(AVFrame, frame, int64_t, pkt_pos)
694 MAKE_ACCESSORS(AVFrame, frame, int64_t, channel_layout)
695 MAKE_ACCESSORS(AVFrame, frame, int,     sample_rate)
696
697 static void avcodec_get_subtitle_defaults(AVSubtitle *sub)
698 {
699     memset(sub, 0, sizeof(*sub));
700     sub->pts = AV_NOPTS_VALUE;
701 }
702
703 static int get_bit_rate(AVCodecContext *ctx)
704 {
705     int bit_rate;
706     int bits_per_sample;
707
708     switch(ctx->codec_type) {
709     case AVMEDIA_TYPE_VIDEO:
710     case AVMEDIA_TYPE_DATA:
711     case AVMEDIA_TYPE_SUBTITLE:
712     case AVMEDIA_TYPE_ATTACHMENT:
713         bit_rate = ctx->bit_rate;
714         break;
715     case AVMEDIA_TYPE_AUDIO:
716         bits_per_sample = av_get_bits_per_sample(ctx->codec_id);
717         bit_rate = bits_per_sample ? ctx->sample_rate * ctx->channels * bits_per_sample : ctx->bit_rate;
718         break;
719     default:
720         bit_rate = 0;
721         break;
722     }
723     return bit_rate;
724 }
725
726 #if FF_API_AVCODEC_OPEN
727 int attribute_align_arg avcodec_open(AVCodecContext *avctx, AVCodec *codec)
728 {
729     return avcodec_open2(avctx, codec, NULL);
730 }
731 #endif
732
733 int attribute_align_arg avcodec_open2(AVCodecContext *avctx, AVCodec *codec, AVDictionary **options)
734 {
735     int ret = 0;
736     AVDictionary *tmp = NULL;
737
738     if (avcodec_is_open(avctx))
739         return 0;
740
741     if ((!codec && !avctx->codec)) {
742         av_log(avctx, AV_LOG_ERROR, "No codec provided to avcodec_open2().\n");
743         return AVERROR(EINVAL);
744     }
745     if ((codec && avctx->codec && codec != avctx->codec)) {
746         av_log(avctx, AV_LOG_ERROR, "This AVCodecContext was allocated for %s, "
747                "but %s passed to avcodec_open2().\n", avctx->codec->name, codec->name);
748         return AVERROR(EINVAL);
749     }
750     if (!codec)
751         codec = avctx->codec;
752
753     if (avctx->extradata_size < 0 || avctx->extradata_size >= FF_MAX_EXTRADATA_SIZE)
754         return AVERROR(EINVAL);
755
756     if (options)
757         av_dict_copy(&tmp, *options, 0);
758
759     /* If there is a user-supplied mutex locking routine, call it. */
760     if (ff_lockmgr_cb) {
761         if ((*ff_lockmgr_cb)(&codec_mutex, AV_LOCK_OBTAIN))
762             return -1;
763     }
764
765     entangled_thread_counter++;
766     if(entangled_thread_counter != 1){
767         av_log(avctx, AV_LOG_ERROR, "insufficient thread locking around avcodec_open/close()\n");
768         ret = -1;
769         goto end;
770     }
771
772     avctx->internal = av_mallocz(sizeof(AVCodecInternal));
773     if (!avctx->internal) {
774         ret = AVERROR(ENOMEM);
775         goto end;
776     }
777
778     if (codec->priv_data_size > 0) {
779       if(!avctx->priv_data){
780         avctx->priv_data = av_mallocz(codec->priv_data_size);
781         if (!avctx->priv_data) {
782             ret = AVERROR(ENOMEM);
783             goto end;
784         }
785         if (codec->priv_class) {
786             *(const AVClass**)avctx->priv_data= codec->priv_class;
787             av_opt_set_defaults(avctx->priv_data);
788         }
789       }
790       if (codec->priv_class && (ret = av_opt_set_dict(avctx->priv_data, &tmp)) < 0)
791           goto free_and_end;
792     } else {
793         avctx->priv_data = NULL;
794     }
795     if ((ret = av_opt_set_dict(avctx, &tmp)) < 0)
796         goto free_and_end;
797
798     if (codec->capabilities & CODEC_CAP_EXPERIMENTAL)
799         if (avctx->strict_std_compliance > FF_COMPLIANCE_EXPERIMENTAL) {
800             av_log(avctx, AV_LOG_ERROR, "Codec is experimental but experimental codecs are not enabled, try -strict -2\n");
801             ret = -1;
802             goto free_and_end;
803         }
804
805     //We only call avcodec_set_dimensions() for non h264 codecs so as not to overwrite previously setup dimensions
806     if(!( avctx->coded_width && avctx->coded_height && avctx->width && avctx->height && avctx->codec_id == CODEC_ID_H264)){
807     if(avctx->coded_width && avctx->coded_height)
808         avcodec_set_dimensions(avctx, avctx->coded_width, avctx->coded_height);
809     else if(avctx->width && avctx->height)
810         avcodec_set_dimensions(avctx, avctx->width, avctx->height);
811     }
812
813     if ((avctx->coded_width || avctx->coded_height || avctx->width || avctx->height)
814         && (  av_image_check_size(avctx->coded_width, avctx->coded_height, 0, avctx) < 0
815            || av_image_check_size(avctx->width,       avctx->height,       0, avctx) < 0)) {
816         av_log(avctx, AV_LOG_WARNING, "ignoring invalid width/height values\n");
817         avcodec_set_dimensions(avctx, 0, 0);
818     }
819
820     /* if the decoder init function was already called previously,
821        free the already allocated subtitle_header before overwriting it */
822     if (av_codec_is_decoder(codec))
823         av_freep(&avctx->subtitle_header);
824
825 #define SANE_NB_CHANNELS 128U
826     if (avctx->channels > SANE_NB_CHANNELS) {
827         ret = AVERROR(EINVAL);
828         goto free_and_end;
829     }
830
831     avctx->codec = codec;
832     if ((avctx->codec_type == AVMEDIA_TYPE_UNKNOWN || avctx->codec_type == codec->type) &&
833         avctx->codec_id == CODEC_ID_NONE) {
834         avctx->codec_type = codec->type;
835         avctx->codec_id   = codec->id;
836     }
837     if (avctx->codec_id != codec->id || (avctx->codec_type != codec->type
838                            && avctx->codec_type != AVMEDIA_TYPE_ATTACHMENT)) {
839         av_log(avctx, AV_LOG_ERROR, "codec type or id mismatches\n");
840         ret = AVERROR(EINVAL);
841         goto free_and_end;
842     }
843     avctx->frame_number = 0;
844
845     if (avctx->codec_type == AVMEDIA_TYPE_AUDIO &&
846         (!avctx->time_base.num || !avctx->time_base.den)) {
847         avctx->time_base.num = 1;
848         avctx->time_base.den = avctx->sample_rate;
849     }
850
851     if (!HAVE_THREADS)
852         av_log(avctx, AV_LOG_WARNING, "Warning: not compiled with thread support, using thread emulation\n");
853
854     if (HAVE_THREADS && !avctx->thread_opaque) {
855         ret = ff_thread_init(avctx);
856         if (ret < 0) {
857             goto free_and_end;
858         }
859     }
860     if (!HAVE_THREADS && !(codec->capabilities & CODEC_CAP_AUTO_THREADS))
861         avctx->thread_count = 1;
862
863     if (avctx->codec->max_lowres < avctx->lowres || avctx->lowres < 0) {
864         av_log(avctx, AV_LOG_ERROR, "The maximum value for lowres supported by the decoder is %d\n",
865                avctx->codec->max_lowres);
866         ret = AVERROR(EINVAL);
867         goto free_and_end;
868     }
869
870     if (av_codec_is_encoder(avctx->codec)) {
871         int i;
872         if (avctx->codec->sample_fmts) {
873             for (i = 0; avctx->codec->sample_fmts[i] != AV_SAMPLE_FMT_NONE; i++)
874                 if (avctx->sample_fmt == avctx->codec->sample_fmts[i])
875                     break;
876             if (avctx->codec->sample_fmts[i] == AV_SAMPLE_FMT_NONE) {
877                 av_log(avctx, AV_LOG_ERROR, "Specified sample_fmt is not supported.\n");
878                 ret = AVERROR(EINVAL);
879                 goto free_and_end;
880             }
881         }
882         if (avctx->codec->pix_fmts) {
883             for (i = 0; avctx->codec->pix_fmts[i] != PIX_FMT_NONE; i++)
884                 if (avctx->pix_fmt == avctx->codec->pix_fmts[i])
885                     break;
886             if (avctx->codec->pix_fmts[i] == PIX_FMT_NONE
887                 && !((avctx->codec_id == CODEC_ID_MJPEG || avctx->codec_id == CODEC_ID_LJPEG)
888                      && avctx->strict_std_compliance <= FF_COMPLIANCE_UNOFFICIAL)) {
889                 av_log(avctx, AV_LOG_ERROR, "Specified pix_fmt is not supported\n");
890                 ret = AVERROR(EINVAL);
891                 goto free_and_end;
892             }
893         }
894         if (avctx->codec->supported_samplerates) {
895             for (i = 0; avctx->codec->supported_samplerates[i] != 0; i++)
896                 if (avctx->sample_rate == avctx->codec->supported_samplerates[i])
897                     break;
898             if (avctx->codec->supported_samplerates[i] == 0) {
899                 av_log(avctx, AV_LOG_ERROR, "Specified sample_rate is not supported\n");
900                 ret = AVERROR(EINVAL);
901                 goto free_and_end;
902             }
903         }
904         if (avctx->codec->channel_layouts) {
905             if (!avctx->channel_layout) {
906                 av_log(avctx, AV_LOG_WARNING, "channel_layout not specified\n");
907             } else {
908                 for (i = 0; avctx->codec->channel_layouts[i] != 0; i++)
909                     if (avctx->channel_layout == avctx->codec->channel_layouts[i])
910                         break;
911                 if (avctx->codec->channel_layouts[i] == 0) {
912                     av_log(avctx, AV_LOG_ERROR, "Specified channel_layout is not supported\n");
913                     ret = AVERROR(EINVAL);
914                     goto free_and_end;
915                 }
916             }
917         }
918         if (avctx->channel_layout && avctx->channels) {
919             if (av_get_channel_layout_nb_channels(avctx->channel_layout) != avctx->channels) {
920                 av_log(avctx, AV_LOG_ERROR, "channel layout does not match number of channels\n");
921                 ret = AVERROR(EINVAL);
922                 goto free_and_end;
923             }
924         } else if (avctx->channel_layout) {
925             avctx->channels = av_get_channel_layout_nb_channels(avctx->channel_layout);
926         }
927     }
928
929     avctx->pts_correction_num_faulty_pts =
930     avctx->pts_correction_num_faulty_dts = 0;
931     avctx->pts_correction_last_pts =
932     avctx->pts_correction_last_dts = INT64_MIN;
933
934     if(avctx->codec->init && !(avctx->active_thread_type&FF_THREAD_FRAME)){
935         ret = avctx->codec->init(avctx);
936         if (ret < 0) {
937             goto free_and_end;
938         }
939     }
940
941     ret=0;
942
943     if (av_codec_is_decoder(avctx->codec)) {
944         if (!avctx->bit_rate)
945             avctx->bit_rate = get_bit_rate(avctx);
946         /* validate channel layout from the decoder */
947         if (avctx->channel_layout &&
948             av_get_channel_layout_nb_channels(avctx->channel_layout) != avctx->channels) {
949             av_log(avctx, AV_LOG_WARNING, "channel layout does not match number of channels\n");
950             avctx->channel_layout = 0;
951         }
952     }
953 end:
954     entangled_thread_counter--;
955
956     /* Release any user-supplied mutex. */
957     if (ff_lockmgr_cb) {
958         (*ff_lockmgr_cb)(&codec_mutex, AV_LOCK_RELEASE);
959     }
960     if (options) {
961         av_dict_free(options);
962         *options = tmp;
963     }
964
965     return ret;
966 free_and_end:
967     av_dict_free(&tmp);
968     av_freep(&avctx->priv_data);
969     av_freep(&avctx->internal);
970     avctx->codec= NULL;
971     goto end;
972 }
973
974 int ff_alloc_packet2(AVCodecContext *avctx, AVPacket *avpkt, int size)
975 {
976     if (size < 0 || avpkt->size < 0 || size > INT_MAX - FF_INPUT_BUFFER_PADDING_SIZE) {
977         av_log(avctx, AV_LOG_ERROR, "Size %d invalid\n", size);
978         return AVERROR(EINVAL);
979     }
980
981     av_assert0(!avpkt->data || avpkt->data != avctx->internal->byte_buffer);
982     if (!avpkt->data || avpkt->size < size) {
983         av_fast_padded_malloc(&avctx->internal->byte_buffer, &avctx->internal->byte_buffer_size, size);
984         avpkt->data = avctx->internal->byte_buffer;
985         avpkt->size = avctx->internal->byte_buffer_size;
986         avpkt->destruct = NULL;
987     }
988
989     if (avpkt->data) {
990         void *destruct = avpkt->destruct;
991
992         if (avpkt->size < size) {
993             av_log(avctx, AV_LOG_ERROR, "User packet is too small (%d < %d)\n", avpkt->size, size);
994             return AVERROR(EINVAL);
995         }
996
997         av_init_packet(avpkt);
998         avpkt->destruct = destruct;
999         avpkt->size = size;
1000         return 0;
1001     } else {
1002         int ret = av_new_packet(avpkt, size);
1003         if (ret < 0)
1004             av_log(avctx, AV_LOG_ERROR, "Failed to allocate packet of size %d\n", size);
1005         return ret;
1006     }
1007 }
1008
1009 int ff_alloc_packet(AVPacket *avpkt, int size)
1010 {
1011     return ff_alloc_packet2(NULL, avpkt, size);
1012 }
1013
1014 /**
1015  * Pad last frame with silence.
1016  */
1017 static int pad_last_frame(AVCodecContext *s, AVFrame **dst, const AVFrame *src)
1018 {
1019     AVFrame *frame = NULL;
1020     uint8_t *buf   = NULL;
1021     int ret;
1022
1023     if (!(frame = avcodec_alloc_frame()))
1024         return AVERROR(ENOMEM);
1025     *frame = *src;
1026
1027     if ((ret = av_samples_get_buffer_size(&frame->linesize[0], s->channels,
1028                                           s->frame_size, s->sample_fmt, 0)) < 0)
1029         goto fail;
1030
1031     if (!(buf = av_malloc(ret))) {
1032         ret = AVERROR(ENOMEM);
1033         goto fail;
1034     }
1035
1036     frame->nb_samples = s->frame_size;
1037     if ((ret = avcodec_fill_audio_frame(frame, s->channels, s->sample_fmt,
1038                                         buf, ret, 0)) < 0)
1039         goto fail;
1040     if ((ret = av_samples_copy(frame->extended_data, src->extended_data, 0, 0,
1041                                src->nb_samples, s->channels, s->sample_fmt)) < 0)
1042         goto fail;
1043     if ((ret = av_samples_set_silence(frame->extended_data, src->nb_samples,
1044                                       frame->nb_samples - src->nb_samples,
1045                                       s->channels, s->sample_fmt)) < 0)
1046         goto fail;
1047
1048     *dst = frame;
1049
1050     return 0;
1051
1052 fail:
1053     if (frame->extended_data != frame->data)
1054         av_freep(&frame->extended_data);
1055     av_freep(&buf);
1056     av_freep(&frame);
1057     return ret;
1058 }
1059
1060 int attribute_align_arg avcodec_encode_audio2(AVCodecContext *avctx,
1061                                               AVPacket *avpkt,
1062                                               const AVFrame *frame,
1063                                               int *got_packet_ptr)
1064 {
1065     AVFrame tmp;
1066     AVFrame *padded_frame = NULL;
1067     int ret;
1068     AVPacket user_pkt = *avpkt;
1069     int needs_realloc = !user_pkt.data;
1070
1071     *got_packet_ptr = 0;
1072
1073     if (!(avctx->codec->capabilities & CODEC_CAP_DELAY) && !frame) {
1074         av_free_packet(avpkt);
1075         av_init_packet(avpkt);
1076         return 0;
1077     }
1078
1079     /* ensure that extended_data is properly set */
1080     if (frame && !frame->extended_data) {
1081         if (av_sample_fmt_is_planar(avctx->sample_fmt) &&
1082             avctx->channels > AV_NUM_DATA_POINTERS) {
1083             av_log(avctx, AV_LOG_ERROR, "Encoding to a planar sample format, "
1084                    "with more than %d channels, but extended_data is not set.\n",
1085                    AV_NUM_DATA_POINTERS);
1086             return AVERROR(EINVAL);
1087         }
1088         av_log(avctx, AV_LOG_WARNING, "extended_data is not set.\n");
1089
1090         tmp = *frame;
1091         tmp.extended_data = tmp.data;
1092         frame = &tmp;
1093     }
1094
1095     /* check for valid frame size */
1096     if (frame) {
1097         if (avctx->codec->capabilities & CODEC_CAP_SMALL_LAST_FRAME) {
1098             if (frame->nb_samples > avctx->frame_size)
1099                 return AVERROR(EINVAL);
1100         } else if (!(avctx->codec->capabilities & CODEC_CAP_VARIABLE_FRAME_SIZE)) {
1101             if (frame->nb_samples < avctx->frame_size &&
1102                 !avctx->internal->last_audio_frame) {
1103                 ret = pad_last_frame(avctx, &padded_frame, frame);
1104                 if (ret < 0)
1105                     return ret;
1106
1107                 frame = padded_frame;
1108                 avctx->internal->last_audio_frame = 1;
1109             }
1110
1111             if (frame->nb_samples != avctx->frame_size)
1112                 return AVERROR(EINVAL);
1113         }
1114     }
1115
1116     ret = avctx->codec->encode2(avctx, avpkt, frame, got_packet_ptr);
1117     if (!ret) {
1118         if (*got_packet_ptr) {
1119             if (!(avctx->codec->capabilities & CODEC_CAP_DELAY)) {
1120                 if (avpkt->pts == AV_NOPTS_VALUE)
1121                     avpkt->pts = frame->pts;
1122                 if (!avpkt->duration)
1123                     avpkt->duration = ff_samples_to_time_base(avctx,
1124                                                               frame->nb_samples);
1125             }
1126             avpkt->dts = avpkt->pts;
1127         } else {
1128             avpkt->size = 0;
1129         }
1130     }
1131     if (avpkt->data && avpkt->data == avctx->internal->byte_buffer) {
1132         needs_realloc = 0;
1133         if (user_pkt.data) {
1134             if (user_pkt.size >= avpkt->size) {
1135                 memcpy(user_pkt.data, avpkt->data, avpkt->size);
1136             } else {
1137                 av_log(avctx, AV_LOG_ERROR, "Provided packet is too small, needs to be %d\n", avpkt->size);
1138                 avpkt->size = user_pkt.size;
1139                 ret = -1;
1140             }
1141             avpkt->data     = user_pkt.data;
1142             avpkt->destruct = user_pkt.destruct;
1143         } else {
1144             if (av_dup_packet(avpkt) < 0) {
1145                 ret = AVERROR(ENOMEM);
1146             }
1147         }
1148     }
1149
1150     if (!ret) {
1151         if (needs_realloc && avpkt->data) {
1152             uint8_t *new_data = av_realloc(avpkt->data, avpkt->size + FF_INPUT_BUFFER_PADDING_SIZE);
1153             if (new_data)
1154                 avpkt->data = new_data;
1155         }
1156
1157         avctx->frame_number++;
1158     }
1159
1160     if (ret < 0 || !*got_packet_ptr) {
1161         av_free_packet(avpkt);
1162         av_init_packet(avpkt);
1163         return ret;
1164     }
1165
1166     /* NOTE: if we add any audio encoders which output non-keyframe packets,
1167              this needs to be moved to the encoders, but for now we can do it
1168              here to simplify things */
1169     avpkt->flags |= AV_PKT_FLAG_KEY;
1170
1171     if (padded_frame) {
1172         av_freep(&padded_frame->data[0]);
1173         if (padded_frame->extended_data != padded_frame->data)
1174             av_freep(&padded_frame->extended_data);
1175         av_freep(&padded_frame);
1176     }
1177
1178     return ret;
1179 }
1180
1181 #if FF_API_OLD_DECODE_AUDIO
1182 int attribute_align_arg avcodec_encode_audio(AVCodecContext *avctx,
1183                                              uint8_t *buf, int buf_size,
1184                                              const short *samples)
1185 {
1186     AVPacket pkt;
1187     AVFrame frame0;
1188     AVFrame *frame;
1189     int ret, samples_size, got_packet;
1190
1191     av_init_packet(&pkt);
1192     pkt.data = buf;
1193     pkt.size = buf_size;
1194
1195     if (samples) {
1196         frame = &frame0;
1197         avcodec_get_frame_defaults(frame);
1198
1199         if (avctx->frame_size) {
1200             frame->nb_samples = avctx->frame_size;
1201         } else {
1202             /* if frame_size is not set, the number of samples must be
1203                calculated from the buffer size */
1204             int64_t nb_samples;
1205             if (!av_get_bits_per_sample(avctx->codec_id)) {
1206                 av_log(avctx, AV_LOG_ERROR, "avcodec_encode_audio() does not "
1207                        "support this codec\n");
1208                 return AVERROR(EINVAL);
1209             }
1210             nb_samples = (int64_t)buf_size * 8 /
1211                          (av_get_bits_per_sample(avctx->codec_id) *
1212                          avctx->channels);
1213             if (nb_samples >= INT_MAX)
1214                 return AVERROR(EINVAL);
1215             frame->nb_samples = nb_samples;
1216         }
1217
1218         /* it is assumed that the samples buffer is large enough based on the
1219            relevant parameters */
1220         samples_size = av_samples_get_buffer_size(NULL, avctx->channels,
1221                                                   frame->nb_samples,
1222                                                   avctx->sample_fmt, 1);
1223         if ((ret = avcodec_fill_audio_frame(frame, avctx->channels,
1224                                             avctx->sample_fmt,
1225                                             (const uint8_t *) samples,
1226                                             samples_size, 1)))
1227             return ret;
1228
1229         /* fabricate frame pts from sample count.
1230            this is needed because the avcodec_encode_audio() API does not have
1231            a way for the user to provide pts */
1232         if(avctx->sample_rate && avctx->time_base.num)
1233             frame->pts = ff_samples_to_time_base(avctx,
1234                                                 avctx->internal->sample_count);
1235         else
1236             frame->pts = AV_NOPTS_VALUE;
1237         avctx->internal->sample_count += frame->nb_samples;
1238     } else {
1239         frame = NULL;
1240     }
1241
1242     got_packet = 0;
1243     ret = avcodec_encode_audio2(avctx, &pkt, frame, &got_packet);
1244     if (!ret && got_packet && avctx->coded_frame) {
1245         avctx->coded_frame->pts       = pkt.pts;
1246         avctx->coded_frame->key_frame = !!(pkt.flags & AV_PKT_FLAG_KEY);
1247     }
1248     /* free any side data since we cannot return it */
1249     ff_packet_free_side_data(&pkt);
1250
1251     if (frame && frame->extended_data != frame->data)
1252         av_freep(&frame->extended_data);
1253
1254     return ret ? ret : pkt.size;
1255 }
1256 #endif
1257
1258 #if FF_API_OLD_ENCODE_VIDEO
1259 int attribute_align_arg avcodec_encode_video(AVCodecContext *avctx, uint8_t *buf, int buf_size,
1260                          const AVFrame *pict)
1261 {
1262     AVPacket pkt;
1263     int ret, got_packet = 0;
1264
1265     if(buf_size < FF_MIN_BUFFER_SIZE){
1266         av_log(avctx, AV_LOG_ERROR, "buffer smaller than minimum size\n");
1267         return -1;
1268     }
1269
1270     av_init_packet(&pkt);
1271     pkt.data = buf;
1272     pkt.size = buf_size;
1273
1274     ret = avcodec_encode_video2(avctx, &pkt, pict, &got_packet);
1275     if (!ret && got_packet && avctx->coded_frame) {
1276         avctx->coded_frame->pts       = pkt.pts;
1277         avctx->coded_frame->key_frame = !!(pkt.flags & AV_PKT_FLAG_KEY);
1278     }
1279
1280     /* free any side data since we cannot return it */
1281     if (pkt.side_data_elems > 0) {
1282         int i;
1283         for (i = 0; i < pkt.side_data_elems; i++)
1284             av_free(pkt.side_data[i].data);
1285         av_freep(&pkt.side_data);
1286         pkt.side_data_elems = 0;
1287     }
1288
1289     return ret ? ret : pkt.size;
1290 }
1291 #endif
1292
1293 int attribute_align_arg avcodec_encode_video2(AVCodecContext *avctx,
1294                                               AVPacket *avpkt,
1295                                               const AVFrame *frame,
1296                                               int *got_packet_ptr)
1297 {
1298     int ret;
1299     AVPacket user_pkt = *avpkt;
1300     int needs_realloc = !user_pkt.data;
1301
1302     *got_packet_ptr = 0;
1303
1304     if (!(avctx->codec->capabilities & CODEC_CAP_DELAY) && !frame) {
1305         av_free_packet(avpkt);
1306         av_init_packet(avpkt);
1307         avpkt->size     = 0;
1308         return 0;
1309     }
1310
1311     if (av_image_check_size(avctx->width, avctx->height, 0, avctx))
1312         return AVERROR(EINVAL);
1313
1314     av_assert0(avctx->codec->encode2);
1315
1316     ret = avctx->codec->encode2(avctx, avpkt, frame, got_packet_ptr);
1317     av_assert0(ret <= 0);
1318
1319     if (avpkt->data && avpkt->data == avctx->internal->byte_buffer) {
1320         needs_realloc = 0;
1321         if (user_pkt.data) {
1322             if (user_pkt.size >= avpkt->size) {
1323                 memcpy(user_pkt.data, avpkt->data, avpkt->size);
1324             } else {
1325                 av_log(avctx, AV_LOG_ERROR, "Provided packet is too small, needs to be %d\n", avpkt->size);
1326                 avpkt->size = user_pkt.size;
1327                 ret = -1;
1328             }
1329             avpkt->data     = user_pkt.data;
1330             avpkt->destruct = user_pkt.destruct;
1331         } else {
1332             if (av_dup_packet(avpkt) < 0) {
1333                 ret = AVERROR(ENOMEM);
1334             }
1335         }
1336     }
1337
1338     if (!ret) {
1339         if (!*got_packet_ptr)
1340             avpkt->size = 0;
1341         else if (!(avctx->codec->capabilities & CODEC_CAP_DELAY))
1342             avpkt->pts = avpkt->dts = frame->pts;
1343
1344         if (needs_realloc && avpkt->data &&
1345             avpkt->destruct == av_destruct_packet) {
1346             uint8_t *new_data = av_realloc(avpkt->data, avpkt->size + FF_INPUT_BUFFER_PADDING_SIZE);
1347             if (new_data)
1348                 avpkt->data = new_data;
1349         }
1350
1351         avctx->frame_number++;
1352     }
1353
1354     if (ret < 0 || !*got_packet_ptr)
1355         av_free_packet(avpkt);
1356
1357     emms_c();
1358     return ret;
1359 }
1360
1361 int avcodec_encode_subtitle(AVCodecContext *avctx, uint8_t *buf, int buf_size,
1362                             const AVSubtitle *sub)
1363 {
1364     int ret;
1365     if(sub->start_display_time) {
1366         av_log(avctx, AV_LOG_ERROR, "start_display_time must be 0.\n");
1367         return -1;
1368     }
1369
1370     ret = avctx->codec->encode(avctx, buf, buf_size, (void *)(intptr_t)sub);
1371     avctx->frame_number++;
1372     return ret;
1373 }
1374
1375 /**
1376  * Attempt to guess proper monotonic timestamps for decoded video frames
1377  * which might have incorrect times. Input timestamps may wrap around, in
1378  * which case the output will as well.
1379  *
1380  * @param pts the pts field of the decoded AVPacket, as passed through
1381  * AVFrame.pkt_pts
1382  * @param dts the dts field of the decoded AVPacket
1383  * @return one of the input values, may be AV_NOPTS_VALUE
1384  */
1385 static int64_t guess_correct_pts(AVCodecContext *ctx,
1386                                  int64_t reordered_pts, int64_t dts)
1387 {
1388     int64_t pts = AV_NOPTS_VALUE;
1389
1390     if (dts != AV_NOPTS_VALUE) {
1391         ctx->pts_correction_num_faulty_dts += dts <= ctx->pts_correction_last_dts;
1392         ctx->pts_correction_last_dts = dts;
1393     }
1394     if (reordered_pts != AV_NOPTS_VALUE) {
1395         ctx->pts_correction_num_faulty_pts += reordered_pts <= ctx->pts_correction_last_pts;
1396         ctx->pts_correction_last_pts = reordered_pts;
1397     }
1398     if ((ctx->pts_correction_num_faulty_pts<=ctx->pts_correction_num_faulty_dts || dts == AV_NOPTS_VALUE)
1399        && reordered_pts != AV_NOPTS_VALUE)
1400         pts = reordered_pts;
1401     else
1402         pts = dts;
1403
1404     return pts;
1405 }
1406
1407 static void apply_param_change(AVCodecContext *avctx, AVPacket *avpkt)
1408 {
1409     int size = 0;
1410     const uint8_t *data;
1411     uint32_t flags;
1412
1413     if (!(avctx->codec->capabilities & CODEC_CAP_PARAM_CHANGE))
1414         return;
1415
1416     data = av_packet_get_side_data(avpkt, AV_PKT_DATA_PARAM_CHANGE, &size);
1417     if (!data || size < 4)
1418         return;
1419     flags = bytestream_get_le32(&data);
1420     size -= 4;
1421     if (size < 4) /* Required for any of the changes */
1422         return;
1423     if (flags & AV_SIDE_DATA_PARAM_CHANGE_CHANNEL_COUNT) {
1424         avctx->channels = bytestream_get_le32(&data);
1425         size -= 4;
1426     }
1427     if (flags & AV_SIDE_DATA_PARAM_CHANGE_CHANNEL_LAYOUT) {
1428         if (size < 8)
1429             return;
1430         avctx->channel_layout = bytestream_get_le64(&data);
1431         size -= 8;
1432     }
1433     if (size < 4)
1434         return;
1435     if (flags & AV_SIDE_DATA_PARAM_CHANGE_SAMPLE_RATE) {
1436         avctx->sample_rate = bytestream_get_le32(&data);
1437         size -= 4;
1438     }
1439     if (flags & AV_SIDE_DATA_PARAM_CHANGE_DIMENSIONS) {
1440         if (size < 8)
1441             return;
1442         avctx->width  = bytestream_get_le32(&data);
1443         avctx->height = bytestream_get_le32(&data);
1444         avcodec_set_dimensions(avctx, avctx->width, avctx->height);
1445         size -= 8;
1446     }
1447 }
1448
1449 int attribute_align_arg avcodec_decode_video2(AVCodecContext *avctx, AVFrame *picture,
1450                          int *got_picture_ptr,
1451                          const AVPacket *avpkt)
1452 {
1453     int ret;
1454     // copy to ensure we do not change avpkt
1455     AVPacket tmp = *avpkt;
1456
1457     if (avctx->codec->type != AVMEDIA_TYPE_VIDEO) {
1458         av_log(avctx, AV_LOG_ERROR, "Invalid media type for video\n");
1459         return AVERROR(EINVAL);
1460     }
1461
1462     *got_picture_ptr= 0;
1463     if((avctx->coded_width||avctx->coded_height) && av_image_check_size(avctx->coded_width, avctx->coded_height, 0, avctx))
1464         return AVERROR(EINVAL);
1465
1466     if((avctx->codec->capabilities & CODEC_CAP_DELAY) || avpkt->size || (avctx->active_thread_type&FF_THREAD_FRAME)){
1467         int did_split = av_packet_split_side_data(&tmp);
1468         apply_param_change(avctx, &tmp);
1469         avctx->pkt = &tmp;
1470         if (HAVE_THREADS && avctx->active_thread_type&FF_THREAD_FRAME)
1471              ret = ff_thread_decode_frame(avctx, picture, got_picture_ptr,
1472                                           &tmp);
1473         else {
1474             ret = avctx->codec->decode(avctx, picture, got_picture_ptr,
1475                               &tmp);
1476             picture->pkt_dts= avpkt->dts;
1477
1478             if(!avctx->has_b_frames){
1479             picture->pkt_pos= avpkt->pos;
1480             }
1481             //FIXME these should be under if(!avctx->has_b_frames)
1482             if (!picture->sample_aspect_ratio.num)
1483                 picture->sample_aspect_ratio = avctx->sample_aspect_ratio;
1484             if (!picture->width)
1485                 picture->width = avctx->width;
1486             if (!picture->height)
1487                 picture->height = avctx->height;
1488             if (picture->format == PIX_FMT_NONE)
1489                 picture->format = avctx->pix_fmt;
1490         }
1491
1492         emms_c(); //needed to avoid an emms_c() call before every return;
1493
1494         avctx->pkt = NULL;
1495         if (did_split) {
1496             ff_packet_free_side_data(&tmp);
1497             if(ret == tmp.size)
1498                 ret = avpkt->size;
1499         }
1500
1501         if (*got_picture_ptr){
1502             avctx->frame_number++;
1503             picture->best_effort_timestamp = guess_correct_pts(avctx,
1504                                                             picture->pkt_pts,
1505                                                             picture->pkt_dts);
1506         }
1507     }else
1508         ret= 0;
1509
1510     return ret;
1511 }
1512
1513 #if FF_API_OLD_DECODE_AUDIO
1514 int attribute_align_arg avcodec_decode_audio3(AVCodecContext *avctx, int16_t *samples,
1515                          int *frame_size_ptr,
1516                          AVPacket *avpkt)
1517 {
1518     AVFrame frame;
1519     int ret, got_frame = 0;
1520
1521     if (avctx->get_buffer != avcodec_default_get_buffer) {
1522         av_log(avctx, AV_LOG_ERROR, "Custom get_buffer() for use with"
1523                "avcodec_decode_audio3() detected. Overriding with avcodec_default_get_buffer\n");
1524         av_log(avctx, AV_LOG_ERROR, "Please port your application to "
1525                "avcodec_decode_audio4()\n");
1526         avctx->get_buffer = avcodec_default_get_buffer;
1527         avctx->release_buffer = avcodec_default_release_buffer;
1528     }
1529
1530     ret = avcodec_decode_audio4(avctx, &frame, &got_frame, avpkt);
1531
1532     if (ret >= 0 && got_frame) {
1533         int ch, plane_size;
1534         int planar = av_sample_fmt_is_planar(avctx->sample_fmt);
1535         int data_size = av_samples_get_buffer_size(&plane_size, avctx->channels,
1536                                                    frame.nb_samples,
1537                                                    avctx->sample_fmt, 1);
1538         if (*frame_size_ptr < data_size) {
1539             av_log(avctx, AV_LOG_ERROR, "output buffer size is too small for "
1540                    "the current frame (%d < %d)\n", *frame_size_ptr, data_size);
1541             return AVERROR(EINVAL);
1542         }
1543
1544         memcpy(samples, frame.extended_data[0], plane_size);
1545
1546         if (planar && avctx->channels > 1) {
1547             uint8_t *out = ((uint8_t *)samples) + plane_size;
1548             for (ch = 1; ch < avctx->channels; ch++) {
1549                 memcpy(out, frame.extended_data[ch], plane_size);
1550                 out += plane_size;
1551             }
1552         }
1553         *frame_size_ptr = data_size;
1554     } else {
1555         *frame_size_ptr = 0;
1556     }
1557     return ret;
1558 }
1559 #endif
1560
1561 int attribute_align_arg avcodec_decode_audio4(AVCodecContext *avctx,
1562                                               AVFrame *frame,
1563                                               int *got_frame_ptr,
1564                                               const AVPacket *avpkt)
1565 {
1566     int ret = 0;
1567
1568     *got_frame_ptr = 0;
1569
1570     if (!avpkt->data && avpkt->size) {
1571         av_log(avctx, AV_LOG_ERROR, "invalid packet: NULL data, size != 0\n");
1572         return AVERROR(EINVAL);
1573     }
1574     if (avctx->codec->type != AVMEDIA_TYPE_AUDIO) {
1575         av_log(avctx, AV_LOG_ERROR, "Invalid media type for audio\n");
1576         return AVERROR(EINVAL);
1577     }
1578
1579     if ((avctx->codec->capabilities & CODEC_CAP_DELAY) || avpkt->size) {
1580         // copy to ensure we do not change avpkt
1581         AVPacket tmp = *avpkt;
1582         int did_split = av_packet_split_side_data(&tmp);
1583         apply_param_change(avctx, &tmp);
1584
1585         avctx->pkt = &tmp;
1586         ret = avctx->codec->decode(avctx, frame, got_frame_ptr, &tmp);
1587         if (ret >= 0 && *got_frame_ptr) {
1588             avctx->frame_number++;
1589             frame->pkt_dts = avpkt->dts;
1590             if (frame->format == AV_SAMPLE_FMT_NONE)
1591                 frame->format = avctx->sample_fmt;
1592             if (!frame->channel_layout)
1593                 frame->channel_layout = avctx->channel_layout;
1594             if (!frame->sample_rate)
1595                 frame->sample_rate = avctx->sample_rate;
1596         }
1597
1598         avctx->pkt = NULL;
1599         if (did_split) {
1600             ff_packet_free_side_data(&tmp);
1601             if(ret == tmp.size)
1602                 ret = avpkt->size;
1603         }
1604     }
1605     return ret;
1606 }
1607
1608 int avcodec_decode_subtitle2(AVCodecContext *avctx, AVSubtitle *sub,
1609                             int *got_sub_ptr,
1610                             AVPacket *avpkt)
1611 {
1612     int ret;
1613
1614     if (avctx->codec->type != AVMEDIA_TYPE_SUBTITLE) {
1615         av_log(avctx, AV_LOG_ERROR, "Invalid media type for subtitles\n");
1616         return AVERROR(EINVAL);
1617     }
1618
1619     avctx->pkt = avpkt;
1620     *got_sub_ptr = 0;
1621     avcodec_get_subtitle_defaults(sub);
1622     ret = avctx->codec->decode(avctx, sub, got_sub_ptr, avpkt);
1623     if (*got_sub_ptr)
1624         avctx->frame_number++;
1625     return ret;
1626 }
1627
1628 void avsubtitle_free(AVSubtitle *sub)
1629 {
1630     int i;
1631
1632     for (i = 0; i < sub->num_rects; i++)
1633     {
1634         av_freep(&sub->rects[i]->pict.data[0]);
1635         av_freep(&sub->rects[i]->pict.data[1]);
1636         av_freep(&sub->rects[i]->pict.data[2]);
1637         av_freep(&sub->rects[i]->pict.data[3]);
1638         av_freep(&sub->rects[i]->text);
1639         av_freep(&sub->rects[i]->ass);
1640         av_freep(&sub->rects[i]);
1641     }
1642
1643     av_freep(&sub->rects);
1644
1645     memset(sub, 0, sizeof(AVSubtitle));
1646 }
1647
1648 av_cold int avcodec_close(AVCodecContext *avctx)
1649 {
1650     /* If there is a user-supplied mutex locking routine, call it. */
1651     if (ff_lockmgr_cb) {
1652         if ((*ff_lockmgr_cb)(&codec_mutex, AV_LOCK_OBTAIN))
1653             return -1;
1654     }
1655
1656     entangled_thread_counter++;
1657     if(entangled_thread_counter != 1){
1658         av_log(avctx, AV_LOG_ERROR, "insufficient thread locking around avcodec_open/close()\n");
1659         entangled_thread_counter--;
1660         return -1;
1661     }
1662
1663     if (avcodec_is_open(avctx)) {
1664         if (HAVE_THREADS && avctx->thread_opaque)
1665             ff_thread_free(avctx);
1666         if (avctx->codec && avctx->codec->close)
1667             avctx->codec->close(avctx);
1668         avcodec_default_free_buffers(avctx);
1669         avctx->coded_frame = NULL;
1670         avctx->internal->byte_buffer_size = 0;
1671         av_freep(&avctx->internal->byte_buffer);
1672         av_freep(&avctx->internal);
1673     }
1674
1675     if (avctx->priv_data && avctx->codec && avctx->codec->priv_class)
1676         av_opt_free(avctx->priv_data);
1677     av_opt_free(avctx);
1678     av_freep(&avctx->priv_data);
1679     if (av_codec_is_encoder(avctx->codec))
1680         av_freep(&avctx->extradata);
1681     avctx->codec = NULL;
1682     avctx->active_thread_type = 0;
1683     entangled_thread_counter--;
1684
1685     /* Release any user-supplied mutex. */
1686     if (ff_lockmgr_cb) {
1687         (*ff_lockmgr_cb)(&codec_mutex, AV_LOCK_RELEASE);
1688     }
1689     return 0;
1690 }
1691
1692 static enum CodecID remap_deprecated_codec_id(enum CodecID id)
1693 {
1694     switch(id){
1695         //This is for future deprecatec codec ids, its empty since
1696         //last major bump but will fill up again over time, please dont remove it
1697 //         case CODEC_ID_UTVIDEO_DEPRECATED: return CODEC_ID_UTVIDEO;
1698         default                         : return id;
1699     }
1700 }
1701
1702 AVCodec *avcodec_find_encoder(enum CodecID id)
1703 {
1704     AVCodec *p, *experimental=NULL;
1705     p = first_avcodec;
1706     id= remap_deprecated_codec_id(id);
1707     while (p) {
1708         if (av_codec_is_encoder(p) && p->id == id) {
1709             if (p->capabilities & CODEC_CAP_EXPERIMENTAL && !experimental) {
1710                 experimental = p;
1711             } else
1712                 return p;
1713         }
1714         p = p->next;
1715     }
1716     return experimental;
1717 }
1718
1719 AVCodec *avcodec_find_encoder_by_name(const char *name)
1720 {
1721     AVCodec *p;
1722     if (!name)
1723         return NULL;
1724     p = first_avcodec;
1725     while (p) {
1726         if (av_codec_is_encoder(p) && strcmp(name,p->name) == 0)
1727             return p;
1728         p = p->next;
1729     }
1730     return NULL;
1731 }
1732
1733 AVCodec *avcodec_find_decoder(enum CodecID id)
1734 {
1735     AVCodec *p, *experimental=NULL;
1736     p = first_avcodec;
1737     id= remap_deprecated_codec_id(id);
1738     while (p) {
1739         if (av_codec_is_decoder(p) && p->id == id) {
1740             if (p->capabilities & CODEC_CAP_EXPERIMENTAL && !experimental) {
1741                 experimental = p;
1742             } else
1743                 return p;
1744         }
1745         p = p->next;
1746     }
1747     return experimental;
1748 }
1749
1750 AVCodec *avcodec_find_decoder_by_name(const char *name)
1751 {
1752     AVCodec *p;
1753     if (!name)
1754         return NULL;
1755     p = first_avcodec;
1756     while (p) {
1757         if (av_codec_is_decoder(p) && strcmp(name,p->name) == 0)
1758             return p;
1759         p = p->next;
1760     }
1761     return NULL;
1762 }
1763
1764 const char *avcodec_get_name(enum CodecID id)
1765 {
1766     AVCodec *codec;
1767
1768 #if !CONFIG_SMALL
1769     switch (id) {
1770 #include "libavcodec/codec_names.h"
1771     }
1772     av_log(NULL, AV_LOG_WARNING, "Codec 0x%x is not in the full list.\n", id);
1773 #endif
1774     codec = avcodec_find_decoder(id);
1775     if (codec)
1776         return codec->name;
1777     codec = avcodec_find_encoder(id);
1778     if (codec)
1779         return codec->name;
1780     return "unknown_codec";
1781 }
1782
1783 size_t av_get_codec_tag_string(char *buf, size_t buf_size, unsigned int codec_tag)
1784 {
1785     int i, len, ret = 0;
1786
1787 #define IS_PRINT(x)                                               \
1788     (((x) >= '0' && (x) <= '9') ||                                \
1789      ((x) >= 'a' && (x) <= 'z') || ((x) >= 'A' && (x) <= 'Z') ||  \
1790      ((x) == '.' || (x) == ' '))
1791
1792     for (i = 0; i < 4; i++) {
1793         len = snprintf(buf, buf_size,
1794                        IS_PRINT(codec_tag&0xFF) ? "%c" : "[%d]", codec_tag&0xFF);
1795         buf      += len;
1796         buf_size  = buf_size > len ? buf_size - len : 0;
1797         ret      += len;
1798         codec_tag>>=8;
1799     }
1800     return ret;
1801 }
1802
1803 void avcodec_string(char *buf, int buf_size, AVCodecContext *enc, int encode)
1804 {
1805     const char *codec_type;
1806     const char *codec_name;
1807     const char *profile = NULL;
1808     AVCodec *p;
1809     int bitrate;
1810     AVRational display_aspect_ratio;
1811
1812     if (!buf || buf_size <= 0)
1813         return;
1814     codec_type = av_get_media_type_string(enc->codec_type);
1815     codec_name = avcodec_get_name(enc->codec_id);
1816     if (enc->profile != FF_PROFILE_UNKNOWN) {
1817         if (enc->codec)
1818             p = enc->codec;
1819         else
1820             p = encode ? avcodec_find_encoder(enc->codec_id) :
1821                         avcodec_find_decoder(enc->codec_id);
1822         if (p)
1823             profile = av_get_profile_name(p, enc->profile);
1824     }
1825
1826     snprintf(buf, buf_size, "%s: %s%s", codec_type ? codec_type : "unknown",
1827              codec_name, enc->mb_decision ? " (hq)" : "");
1828     buf[0] ^= 'a' ^ 'A'; /* first letter in uppercase */
1829     if (profile)
1830         snprintf(buf + strlen(buf), buf_size - strlen(buf), " (%s)", profile);
1831     if (enc->codec_tag) {
1832         char tag_buf[32];
1833         av_get_codec_tag_string(tag_buf, sizeof(tag_buf), enc->codec_tag);
1834         snprintf(buf + strlen(buf), buf_size - strlen(buf),
1835                  " (%s / 0x%04X)", tag_buf, enc->codec_tag);
1836     }
1837     switch(enc->codec_type) {
1838     case AVMEDIA_TYPE_VIDEO:
1839         if (enc->pix_fmt != PIX_FMT_NONE) {
1840             snprintf(buf + strlen(buf), buf_size - strlen(buf),
1841                      ", %s",
1842                      av_get_pix_fmt_name(enc->pix_fmt));
1843         }
1844         if (enc->width) {
1845             snprintf(buf + strlen(buf), buf_size - strlen(buf),
1846                      ", %dx%d",
1847                      enc->width, enc->height);
1848             if (enc->sample_aspect_ratio.num) {
1849                 av_reduce(&display_aspect_ratio.num, &display_aspect_ratio.den,
1850                           enc->width*enc->sample_aspect_ratio.num,
1851                           enc->height*enc->sample_aspect_ratio.den,
1852                           1024*1024);
1853                 snprintf(buf + strlen(buf), buf_size - strlen(buf),
1854                          " [SAR %d:%d DAR %d:%d]",
1855                          enc->sample_aspect_ratio.num, enc->sample_aspect_ratio.den,
1856                          display_aspect_ratio.num, display_aspect_ratio.den);
1857             }
1858             if(av_log_get_level() >= AV_LOG_DEBUG){
1859                 int g= av_gcd(enc->time_base.num, enc->time_base.den);
1860                 snprintf(buf + strlen(buf), buf_size - strlen(buf),
1861                      ", %d/%d",
1862                      enc->time_base.num/g, enc->time_base.den/g);
1863             }
1864         }
1865         if (encode) {
1866             snprintf(buf + strlen(buf), buf_size - strlen(buf),
1867                      ", q=%d-%d", enc->qmin, enc->qmax);
1868         }
1869         break;
1870     case AVMEDIA_TYPE_AUDIO:
1871         if (enc->sample_rate) {
1872             snprintf(buf + strlen(buf), buf_size - strlen(buf),
1873                      ", %d Hz", enc->sample_rate);
1874         }
1875         av_strlcat(buf, ", ", buf_size);
1876         av_get_channel_layout_string(buf + strlen(buf), buf_size - strlen(buf), enc->channels, enc->channel_layout);
1877         if (enc->sample_fmt != AV_SAMPLE_FMT_NONE) {
1878             snprintf(buf + strlen(buf), buf_size - strlen(buf),
1879                      ", %s", av_get_sample_fmt_name(enc->sample_fmt));
1880         }
1881         break;
1882     default:
1883         return;
1884     }
1885     if (encode) {
1886         if (enc->flags & CODEC_FLAG_PASS1)
1887             snprintf(buf + strlen(buf), buf_size - strlen(buf),
1888                      ", pass 1");
1889         if (enc->flags & CODEC_FLAG_PASS2)
1890             snprintf(buf + strlen(buf), buf_size - strlen(buf),
1891                      ", pass 2");
1892     }
1893     bitrate = get_bit_rate(enc);
1894     if (bitrate != 0) {
1895         snprintf(buf + strlen(buf), buf_size - strlen(buf),
1896                  ", %d kb/s", bitrate / 1000);
1897     }
1898 }
1899
1900 const char *av_get_profile_name(const AVCodec *codec, int profile)
1901 {
1902     const AVProfile *p;
1903     if (profile == FF_PROFILE_UNKNOWN || !codec->profiles)
1904         return NULL;
1905
1906     for (p = codec->profiles; p->profile != FF_PROFILE_UNKNOWN; p++)
1907         if (p->profile == profile)
1908             return p->name;
1909
1910     return NULL;
1911 }
1912
1913 unsigned avcodec_version( void )
1914 {
1915 //    av_assert0(CODEC_ID_V410==164);
1916     av_assert0(CODEC_ID_PCM_S8_PLANAR==65563);
1917     av_assert0(CODEC_ID_ADPCM_G722==69660);
1918 //     av_assert0(CODEC_ID_BMV_AUDIO==86071);
1919     av_assert0(CODEC_ID_SRT==94216);
1920     av_assert0(LIBAVCODEC_VERSION_MICRO >= 100);
1921
1922   return LIBAVCODEC_VERSION_INT;
1923 }
1924
1925 const char *avcodec_configuration(void)
1926 {
1927     return FFMPEG_CONFIGURATION;
1928 }
1929
1930 const char *avcodec_license(void)
1931 {
1932 #define LICENSE_PREFIX "libavcodec license: "
1933     return LICENSE_PREFIX FFMPEG_LICENSE + sizeof(LICENSE_PREFIX) - 1;
1934 }
1935
1936 void avcodec_flush_buffers(AVCodecContext *avctx)
1937 {
1938     if(HAVE_THREADS && avctx->active_thread_type&FF_THREAD_FRAME)
1939         ff_thread_flush(avctx);
1940     else if(avctx->codec->flush)
1941         avctx->codec->flush(avctx);
1942
1943     avctx->pts_correction_last_pts =
1944     avctx->pts_correction_last_dts = INT64_MIN;
1945 }
1946
1947 static void video_free_buffers(AVCodecContext *s)
1948 {
1949     AVCodecInternal *avci = s->internal;
1950     int i, j;
1951
1952     if (!avci->buffer)
1953         return;
1954
1955     if (avci->buffer_count)
1956         av_log(s, AV_LOG_WARNING, "Found %i unreleased buffers!\n",
1957                avci->buffer_count);
1958     for(i=0; i<INTERNAL_BUFFER_SIZE; i++){
1959         InternalBuffer *buf = &avci->buffer[i];
1960         for(j=0; j<4; j++){
1961             av_freep(&buf->base[j]);
1962             buf->data[j]= NULL;
1963         }
1964     }
1965     av_freep(&avci->buffer);
1966
1967     avci->buffer_count=0;
1968 }
1969
1970 static void audio_free_buffers(AVCodecContext *avctx)
1971 {
1972     AVCodecInternal *avci = avctx->internal;
1973     InternalBuffer *buf;
1974
1975     if (!avci->buffer)
1976         return;
1977     buf = avci->buffer;
1978
1979     if (buf->extended_data) {
1980         av_free(buf->extended_data[0]);
1981         if (buf->extended_data != buf->data)
1982             av_freep(&buf->extended_data);
1983     }
1984     av_freep(&avci->buffer);
1985 }
1986
1987 void avcodec_default_free_buffers(AVCodecContext *avctx)
1988 {
1989     switch (avctx->codec_type) {
1990     case AVMEDIA_TYPE_VIDEO:
1991         video_free_buffers(avctx);
1992         break;
1993     case AVMEDIA_TYPE_AUDIO:
1994         audio_free_buffers(avctx);
1995         break;
1996     default:
1997         break;
1998     }
1999 }
2000
2001 int av_get_exact_bits_per_sample(enum CodecID codec_id)
2002 {
2003     switch(codec_id){
2004     case CODEC_ID_ADPCM_CT:
2005     case CODEC_ID_ADPCM_IMA_APC:
2006     case CODEC_ID_ADPCM_IMA_EA_SEAD:
2007     case CODEC_ID_ADPCM_IMA_WS:
2008     case CODEC_ID_ADPCM_G722:
2009     case CODEC_ID_ADPCM_YAMAHA:
2010         return 4;
2011     case CODEC_ID_PCM_ALAW:
2012     case CODEC_ID_PCM_MULAW:
2013     case CODEC_ID_PCM_S8:
2014     case CODEC_ID_PCM_U8:
2015     case CODEC_ID_PCM_ZORK:
2016         return 8;
2017     case CODEC_ID_PCM_S16BE:
2018     case CODEC_ID_PCM_S16LE:
2019     case CODEC_ID_PCM_S16LE_PLANAR:
2020     case CODEC_ID_PCM_U16BE:
2021     case CODEC_ID_PCM_U16LE:
2022         return 16;
2023     case CODEC_ID_PCM_S24DAUD:
2024     case CODEC_ID_PCM_S24BE:
2025     case CODEC_ID_PCM_S24LE:
2026     case CODEC_ID_PCM_U24BE:
2027     case CODEC_ID_PCM_U24LE:
2028         return 24;
2029     case CODEC_ID_PCM_S32BE:
2030     case CODEC_ID_PCM_S32LE:
2031     case CODEC_ID_PCM_U32BE:
2032     case CODEC_ID_PCM_U32LE:
2033     case CODEC_ID_PCM_F32BE:
2034     case CODEC_ID_PCM_F32LE:
2035         return 32;
2036     case CODEC_ID_PCM_F64BE:
2037     case CODEC_ID_PCM_F64LE:
2038         return 64;
2039     default:
2040         return 0;
2041     }
2042 }
2043
2044 enum CodecID av_get_pcm_codec(enum AVSampleFormat fmt, int be)
2045 {
2046     static const enum CodecID map[AV_SAMPLE_FMT_NB][2] = {
2047         [AV_SAMPLE_FMT_U8  ] = { CODEC_ID_PCM_U8,    CODEC_ID_PCM_U8    },
2048         [AV_SAMPLE_FMT_S16 ] = { CODEC_ID_PCM_S16LE, CODEC_ID_PCM_S16BE },
2049         [AV_SAMPLE_FMT_S32 ] = { CODEC_ID_PCM_S32LE, CODEC_ID_PCM_S32BE },
2050         [AV_SAMPLE_FMT_FLT ] = { CODEC_ID_PCM_F32LE, CODEC_ID_PCM_F32BE },
2051         [AV_SAMPLE_FMT_DBL ] = { CODEC_ID_PCM_F64LE, CODEC_ID_PCM_F64BE },
2052         [AV_SAMPLE_FMT_U8P ] = { CODEC_ID_PCM_U8,    CODEC_ID_PCM_U8    },
2053         [AV_SAMPLE_FMT_S16P] = { CODEC_ID_PCM_S16LE, CODEC_ID_PCM_S16BE },
2054         [AV_SAMPLE_FMT_S32P] = { CODEC_ID_PCM_S32LE, CODEC_ID_PCM_S32BE },
2055         [AV_SAMPLE_FMT_FLTP] = { CODEC_ID_PCM_F32LE, CODEC_ID_PCM_F32BE },
2056         [AV_SAMPLE_FMT_DBLP] = { CODEC_ID_PCM_F64LE, CODEC_ID_PCM_F64BE },
2057     };
2058     if (fmt < 0 || fmt >= AV_SAMPLE_FMT_NB)
2059         return CODEC_ID_NONE;
2060     if (be < 0 || be > 1)
2061         be = AV_NE(1, 0);
2062     return map[fmt][be];
2063 }
2064
2065 int av_get_bits_per_sample(enum CodecID codec_id)
2066 {
2067     switch (codec_id) {
2068     case CODEC_ID_ADPCM_SBPRO_2:
2069         return 2;
2070     case CODEC_ID_ADPCM_SBPRO_3:
2071         return 3;
2072     case CODEC_ID_ADPCM_SBPRO_4:
2073     case CODEC_ID_ADPCM_IMA_WAV:
2074     case CODEC_ID_ADPCM_IMA_QT:
2075     case CODEC_ID_ADPCM_SWF:
2076     case CODEC_ID_ADPCM_MS:
2077         return 4;
2078     default:
2079         return av_get_exact_bits_per_sample(codec_id);
2080     }
2081 }
2082
2083 int av_get_audio_frame_duration(AVCodecContext *avctx, int frame_bytes)
2084 {
2085     int id, sr, ch, ba, tag, bps;
2086
2087     id  = avctx->codec_id;
2088     sr  = avctx->sample_rate;
2089     ch  = avctx->channels;
2090     ba  = avctx->block_align;
2091     tag = avctx->codec_tag;
2092     bps = av_get_exact_bits_per_sample(avctx->codec_id);
2093
2094     /* codecs with an exact constant bits per sample */
2095     if (bps > 0 && ch > 0 && frame_bytes > 0 && ch < 32768 && bps < 32768)
2096         return (frame_bytes * 8LL) / (bps * ch);
2097     bps = avctx->bits_per_coded_sample;
2098
2099     /* codecs with a fixed packet duration */
2100     switch (id) {
2101     case CODEC_ID_ADPCM_ADX:    return   32;
2102     case CODEC_ID_ADPCM_IMA_QT: return   64;
2103     case CODEC_ID_ADPCM_EA_XAS: return  128;
2104     case CODEC_ID_AMR_NB:
2105     case CODEC_ID_GSM:
2106     case CODEC_ID_QCELP:
2107     case CODEC_ID_RA_144:
2108     case CODEC_ID_RA_288:       return  160;
2109     case CODEC_ID_IMC:          return  256;
2110     case CODEC_ID_AMR_WB:
2111     case CODEC_ID_GSM_MS:       return  320;
2112     case CODEC_ID_MP1:          return  384;
2113     case CODEC_ID_ATRAC1:       return  512;
2114     case CODEC_ID_ATRAC3:       return 1024;
2115     case CODEC_ID_MP2:
2116     case CODEC_ID_MUSEPACK7:    return 1152;
2117     case CODEC_ID_AC3:          return 1536;
2118     }
2119
2120     if (sr > 0) {
2121         /* calc from sample rate */
2122         if (id == CODEC_ID_TTA)
2123             return 256 * sr / 245;
2124
2125         if (ch > 0) {
2126             /* calc from sample rate and channels */
2127             if (id == CODEC_ID_BINKAUDIO_DCT)
2128                 return (480 << (sr / 22050)) / ch;
2129         }
2130     }
2131
2132     if (ba > 0) {
2133         /* calc from block_align */
2134         if (id == CODEC_ID_SIPR) {
2135             switch (ba) {
2136             case 20: return 160;
2137             case 19: return 144;
2138             case 29: return 288;
2139             case 37: return 480;
2140             }
2141         }
2142     }
2143
2144     if (frame_bytes > 0) {
2145         /* calc from frame_bytes only */
2146         if (id == CODEC_ID_TRUESPEECH)
2147             return 240 * (frame_bytes / 32);
2148         if (id == CODEC_ID_NELLYMOSER)
2149             return 256 * (frame_bytes / 64);
2150
2151         if (bps > 0) {
2152             /* calc from frame_bytes and bits_per_coded_sample */
2153             if (id == CODEC_ID_ADPCM_G726)
2154                 return frame_bytes * 8 / bps;
2155         }
2156
2157         if (ch > 0) {
2158             /* calc from frame_bytes and channels */
2159             switch (id) {
2160             case CODEC_ID_ADPCM_4XM:
2161             case CODEC_ID_ADPCM_IMA_ISS:
2162                 return (frame_bytes - 4 * ch) * 2 / ch;
2163             case CODEC_ID_ADPCM_IMA_SMJPEG:
2164                 return (frame_bytes - 4) * 2 / ch;
2165             case CODEC_ID_ADPCM_IMA_AMV:
2166                 return (frame_bytes - 8) * 2 / ch;
2167             case CODEC_ID_ADPCM_XA:
2168                 return (frame_bytes / 128) * 224 / ch;
2169             case CODEC_ID_INTERPLAY_DPCM:
2170                 return (frame_bytes - 6 - ch) / ch;
2171             case CODEC_ID_ROQ_DPCM:
2172                 return (frame_bytes - 8) / ch;
2173             case CODEC_ID_XAN_DPCM:
2174                 return (frame_bytes - 2 * ch) / ch;
2175             case CODEC_ID_MACE3:
2176                 return 3 * frame_bytes / ch;
2177             case CODEC_ID_MACE6:
2178                 return 6 * frame_bytes / ch;
2179             case CODEC_ID_PCM_LXF:
2180                 return 2 * (frame_bytes / (5 * ch));
2181             }
2182
2183             if (tag) {
2184                 /* calc from frame_bytes, channels, and codec_tag */
2185                 if (id == CODEC_ID_SOL_DPCM) {
2186                     if (tag == 3)
2187                         return frame_bytes / ch;
2188                     else
2189                         return frame_bytes * 2 / ch;
2190                 }
2191             }
2192
2193             if (ba > 0) {
2194                 /* calc from frame_bytes, channels, and block_align */
2195                 int blocks = frame_bytes / ba;
2196                 switch (avctx->codec_id) {
2197                 case CODEC_ID_ADPCM_IMA_WAV:
2198                     return blocks * (1 + (ba - 4 * ch) / (4 * ch) * 8);
2199                 case CODEC_ID_ADPCM_IMA_DK3:
2200                     return blocks * (((ba - 16) * 2 / 3 * 4) / ch);
2201                 case CODEC_ID_ADPCM_IMA_DK4:
2202                     return blocks * (1 + (ba - 4 * ch) * 2 / ch);
2203                 case CODEC_ID_ADPCM_MS:
2204                     return blocks * (2 + (ba - 7 * ch) * 2 / ch);
2205                 }
2206             }
2207
2208             if (bps > 0) {
2209                 /* calc from frame_bytes, channels, and bits_per_coded_sample */
2210                 switch (avctx->codec_id) {
2211                 case CODEC_ID_PCM_DVD:
2212                     if(bps<4)
2213                         return 0;
2214                     return 2 * (frame_bytes / ((bps * 2 / 8) * ch));
2215                 case CODEC_ID_PCM_BLURAY:
2216                     if(bps<4)
2217                         return 0;
2218                     return frame_bytes / ((FFALIGN(ch, 2) * bps) / 8);
2219                 case CODEC_ID_S302M:
2220                     return 2 * (frame_bytes / ((bps + 4) / 4)) / ch;
2221                 }
2222             }
2223         }
2224     }
2225
2226     return 0;
2227 }
2228
2229 #if !HAVE_THREADS
2230 int ff_thread_init(AVCodecContext *s){
2231     return -1;
2232 }
2233 #endif
2234
2235 unsigned int av_xiphlacing(unsigned char *s, unsigned int v)
2236 {
2237     unsigned int n = 0;
2238
2239     while(v >= 0xff) {
2240         *s++ = 0xff;
2241         v -= 0xff;
2242         n++;
2243     }
2244     *s = v;
2245     n++;
2246     return n;
2247 }
2248
2249 int ff_match_2uint16(const uint16_t (*tab)[2], int size, int a, int b){
2250     int i;
2251     for(i=0; i<size && !(tab[i][0]==a && tab[i][1]==b); i++);
2252     return i;
2253 }
2254
2255 void av_log_missing_feature(void *avc, const char *feature, int want_sample)
2256 {
2257     av_log(avc, AV_LOG_WARNING, "%s not implemented. Update your FFmpeg "
2258             "version to the newest one from Git. If the problem still "
2259             "occurs, it means that your file has a feature which has not "
2260             "been implemented.\n", feature);
2261     if(want_sample)
2262         av_log_ask_for_sample(avc, NULL);
2263 }
2264
2265 void av_log_ask_for_sample(void *avc, const char *msg, ...)
2266 {
2267     va_list argument_list;
2268
2269     va_start(argument_list, msg);
2270
2271     if (msg)
2272         av_vlog(avc, AV_LOG_WARNING, msg, argument_list);
2273     av_log(avc, AV_LOG_WARNING, "If you want to help, upload a sample "
2274             "of this file to ftp://upload.ffmpeg.org/MPlayer/incoming/ "
2275             "and contact the ffmpeg-devel mailing list.\n");
2276
2277     va_end(argument_list);
2278 }
2279
2280 static AVHWAccel *first_hwaccel = NULL;
2281
2282 void av_register_hwaccel(AVHWAccel *hwaccel)
2283 {
2284     AVHWAccel **p = &first_hwaccel;
2285     while (*p)
2286         p = &(*p)->next;
2287     *p = hwaccel;
2288     hwaccel->next = NULL;
2289 }
2290
2291 AVHWAccel *av_hwaccel_next(AVHWAccel *hwaccel)
2292 {
2293     return hwaccel ? hwaccel->next : first_hwaccel;
2294 }
2295
2296 AVHWAccel *ff_find_hwaccel(enum CodecID codec_id, enum PixelFormat pix_fmt)
2297 {
2298     AVHWAccel *hwaccel=NULL;
2299
2300     while((hwaccel= av_hwaccel_next(hwaccel))){
2301         if (   hwaccel->id      == codec_id
2302             && hwaccel->pix_fmt == pix_fmt)
2303             return hwaccel;
2304     }
2305     return NULL;
2306 }
2307
2308 int av_lockmgr_register(int (*cb)(void **mutex, enum AVLockOp op))
2309 {
2310     if (ff_lockmgr_cb) {
2311         if (ff_lockmgr_cb(&codec_mutex, AV_LOCK_DESTROY))
2312             return -1;
2313         if (ff_lockmgr_cb(&avformat_mutex, AV_LOCK_DESTROY))
2314             return -1;
2315     }
2316
2317     ff_lockmgr_cb = cb;
2318
2319     if (ff_lockmgr_cb) {
2320         if (ff_lockmgr_cb(&codec_mutex, AV_LOCK_CREATE))
2321             return -1;
2322         if (ff_lockmgr_cb(&avformat_mutex, AV_LOCK_CREATE))
2323             return -1;
2324     }
2325     return 0;
2326 }
2327
2328 int avpriv_lock_avformat(void)
2329 {
2330     if (ff_lockmgr_cb) {
2331         if ((*ff_lockmgr_cb)(&avformat_mutex, AV_LOCK_OBTAIN))
2332             return -1;
2333     }
2334     return 0;
2335 }
2336
2337 int avpriv_unlock_avformat(void)
2338 {
2339     if (ff_lockmgr_cb) {
2340         if ((*ff_lockmgr_cb)(&avformat_mutex, AV_LOCK_RELEASE))
2341             return -1;
2342     }
2343     return 0;
2344 }
2345
2346 unsigned int avpriv_toupper4(unsigned int x)
2347 {
2348     return     toupper( x     &0xFF)
2349             + (toupper((x>>8 )&0xFF)<<8 )
2350             + (toupper((x>>16)&0xFF)<<16)
2351             + (toupper((x>>24)&0xFF)<<24);
2352 }
2353
2354 #if !HAVE_THREADS
2355
2356 int ff_thread_get_buffer(AVCodecContext *avctx, AVFrame *f)
2357 {
2358     f->owner = avctx;
2359
2360     ff_init_buffer_info(avctx, f);
2361
2362     return avctx->get_buffer(avctx, f);
2363 }
2364
2365 void ff_thread_release_buffer(AVCodecContext *avctx, AVFrame *f)
2366 {
2367     f->owner->release_buffer(f->owner, f);
2368 }
2369
2370 void ff_thread_finish_setup(AVCodecContext *avctx)
2371 {
2372 }
2373
2374 void ff_thread_report_progress(AVFrame *f, int progress, int field)
2375 {
2376 }
2377
2378 void ff_thread_await_progress(AVFrame *f, int progress, int field)
2379 {
2380 }
2381
2382 int ff_thread_can_start_frame(AVCodecContext *avctx)
2383 {
2384     return 1;
2385 }
2386
2387 #endif
2388
2389 enum AVMediaType avcodec_get_type(enum CodecID codec_id)
2390 {
2391     AVCodec *c= avcodec_find_decoder(codec_id);
2392     if(!c)
2393         c= avcodec_find_encoder(codec_id);
2394     if(c)
2395         return c->type;
2396
2397     if (codec_id <= CODEC_ID_NONE)
2398         return AVMEDIA_TYPE_UNKNOWN;
2399     else if (codec_id < CODEC_ID_FIRST_AUDIO)
2400         return AVMEDIA_TYPE_VIDEO;
2401     else if (codec_id < CODEC_ID_FIRST_SUBTITLE)
2402         return AVMEDIA_TYPE_AUDIO;
2403     else if (codec_id < CODEC_ID_FIRST_UNKNOWN)
2404         return AVMEDIA_TYPE_SUBTITLE;
2405
2406     return AVMEDIA_TYPE_UNKNOWN;
2407 }
2408
2409 int avcodec_is_open(AVCodecContext *s)
2410 {
2411     return !!s->internal;
2412 }