]> 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                 av_log(avctx, AV_LOG_ERROR, "Specified pix_fmt is not supported\n");
888                 ret = AVERROR(EINVAL);
889                 goto free_and_end;
890             }
891         }
892         if (avctx->codec->supported_samplerates) {
893             for (i = 0; avctx->codec->supported_samplerates[i] != 0; i++)
894                 if (avctx->sample_rate == avctx->codec->supported_samplerates[i])
895                     break;
896             if (avctx->codec->supported_samplerates[i] == 0) {
897                 av_log(avctx, AV_LOG_ERROR, "Specified sample_rate is not supported\n");
898                 ret = AVERROR(EINVAL);
899                 goto free_and_end;
900             }
901         }
902         if (avctx->codec->channel_layouts) {
903             if (!avctx->channel_layout) {
904                 av_log(avctx, AV_LOG_WARNING, "channel_layout not specified\n");
905             } else {
906                 for (i = 0; avctx->codec->channel_layouts[i] != 0; i++)
907                     if (avctx->channel_layout == avctx->codec->channel_layouts[i])
908                         break;
909                 if (avctx->codec->channel_layouts[i] == 0) {
910                     av_log(avctx, AV_LOG_ERROR, "Specified channel_layout is not supported\n");
911                     ret = AVERROR(EINVAL);
912                     goto free_and_end;
913                 }
914             }
915         }
916         if (avctx->channel_layout && avctx->channels) {
917             if (av_get_channel_layout_nb_channels(avctx->channel_layout) != avctx->channels) {
918                 av_log(avctx, AV_LOG_ERROR, "channel layout does not match number of channels\n");
919                 ret = AVERROR(EINVAL);
920                 goto free_and_end;
921             }
922         } else if (avctx->channel_layout) {
923             avctx->channels = av_get_channel_layout_nb_channels(avctx->channel_layout);
924         }
925     }
926
927     avctx->pts_correction_num_faulty_pts =
928     avctx->pts_correction_num_faulty_dts = 0;
929     avctx->pts_correction_last_pts =
930     avctx->pts_correction_last_dts = INT64_MIN;
931
932     if(avctx->codec->init && !(avctx->active_thread_type&FF_THREAD_FRAME)){
933         ret = avctx->codec->init(avctx);
934         if (ret < 0) {
935             goto free_and_end;
936         }
937     }
938
939     ret=0;
940
941     if (av_codec_is_decoder(avctx->codec)) {
942         if (!avctx->bit_rate)
943             avctx->bit_rate = get_bit_rate(avctx);
944         /* validate channel layout from the decoder */
945         if (avctx->channel_layout &&
946             av_get_channel_layout_nb_channels(avctx->channel_layout) != avctx->channels) {
947             av_log(avctx, AV_LOG_WARNING, "channel layout does not match number of channels\n");
948             avctx->channel_layout = 0;
949         }
950     }
951 end:
952     entangled_thread_counter--;
953
954     /* Release any user-supplied mutex. */
955     if (ff_lockmgr_cb) {
956         (*ff_lockmgr_cb)(&codec_mutex, AV_LOCK_RELEASE);
957     }
958     if (options) {
959         av_dict_free(options);
960         *options = tmp;
961     }
962
963     return ret;
964 free_and_end:
965     av_dict_free(&tmp);
966     av_freep(&avctx->priv_data);
967     av_freep(&avctx->internal);
968     avctx->codec= NULL;
969     goto end;
970 }
971
972 int ff_alloc_packet2(AVCodecContext *avctx, AVPacket *avpkt, int size)
973 {
974     if (size < 0 || avpkt->size < 0 || size > INT_MAX - FF_INPUT_BUFFER_PADDING_SIZE) {
975         av_log(avctx, AV_LOG_ERROR, "Size %d invalid\n", size);
976         return AVERROR(EINVAL);
977     }
978
979     av_assert0(!avpkt->data || avpkt->data != avctx->internal->byte_buffer);
980     if (!avpkt->data || avpkt->size < size) {
981         av_fast_padded_malloc(&avctx->internal->byte_buffer, &avctx->internal->byte_buffer_size, size);
982         avpkt->data = avctx->internal->byte_buffer;
983         avpkt->size = avctx->internal->byte_buffer_size;
984         avpkt->destruct = NULL;
985     }
986
987     if (avpkt->data) {
988         void *destruct = avpkt->destruct;
989
990         if (avpkt->size < size) {
991             av_log(avctx, AV_LOG_ERROR, "User packet is too small (%d < %d)\n", avpkt->size, size);
992             return AVERROR(EINVAL);
993         }
994
995         av_init_packet(avpkt);
996         avpkt->destruct = destruct;
997         avpkt->size = size;
998         return 0;
999     } else {
1000         int ret = av_new_packet(avpkt, size);
1001         if (ret < 0)
1002             av_log(avctx, AV_LOG_ERROR, "Failed to allocate packet of size %d\n", size);
1003         return ret;
1004     }
1005 }
1006
1007 int ff_alloc_packet(AVPacket *avpkt, int size)
1008 {
1009     return ff_alloc_packet2(NULL, avpkt, size);
1010 }
1011
1012 /**
1013  * Pad last frame with silence.
1014  */
1015 static int pad_last_frame(AVCodecContext *s, AVFrame **dst, const AVFrame *src)
1016 {
1017     AVFrame *frame = NULL;
1018     uint8_t *buf   = NULL;
1019     int ret;
1020
1021     if (!(frame = avcodec_alloc_frame()))
1022         return AVERROR(ENOMEM);
1023     *frame = *src;
1024
1025     if ((ret = av_samples_get_buffer_size(&frame->linesize[0], s->channels,
1026                                           s->frame_size, s->sample_fmt, 0)) < 0)
1027         goto fail;
1028
1029     if (!(buf = av_malloc(ret))) {
1030         ret = AVERROR(ENOMEM);
1031         goto fail;
1032     }
1033
1034     frame->nb_samples = s->frame_size;
1035     if ((ret = avcodec_fill_audio_frame(frame, s->channels, s->sample_fmt,
1036                                         buf, ret, 0)) < 0)
1037         goto fail;
1038     if ((ret = av_samples_copy(frame->extended_data, src->extended_data, 0, 0,
1039                                src->nb_samples, s->channels, s->sample_fmt)) < 0)
1040         goto fail;
1041     if ((ret = av_samples_set_silence(frame->extended_data, src->nb_samples,
1042                                       frame->nb_samples - src->nb_samples,
1043                                       s->channels, s->sample_fmt)) < 0)
1044         goto fail;
1045
1046     *dst = frame;
1047
1048     return 0;
1049
1050 fail:
1051     if (frame->extended_data != frame->data)
1052         av_freep(&frame->extended_data);
1053     av_freep(&buf);
1054     av_freep(&frame);
1055     return ret;
1056 }
1057
1058 int attribute_align_arg avcodec_encode_audio2(AVCodecContext *avctx,
1059                                               AVPacket *avpkt,
1060                                               const AVFrame *frame,
1061                                               int *got_packet_ptr)
1062 {
1063     AVFrame tmp;
1064     AVFrame *padded_frame = NULL;
1065     int ret;
1066     AVPacket user_pkt = *avpkt;
1067     int needs_realloc = !user_pkt.data;
1068
1069     *got_packet_ptr = 0;
1070
1071     if (!(avctx->codec->capabilities & CODEC_CAP_DELAY) && !frame) {
1072         av_free_packet(avpkt);
1073         av_init_packet(avpkt);
1074         return 0;
1075     }
1076
1077     /* ensure that extended_data is properly set */
1078     if (frame && !frame->extended_data) {
1079         if (av_sample_fmt_is_planar(avctx->sample_fmt) &&
1080             avctx->channels > AV_NUM_DATA_POINTERS) {
1081             av_log(avctx, AV_LOG_ERROR, "Encoding to a planar sample format, "
1082                    "with more than %d channels, but extended_data is not set.\n",
1083                    AV_NUM_DATA_POINTERS);
1084             return AVERROR(EINVAL);
1085         }
1086         av_log(avctx, AV_LOG_WARNING, "extended_data is not set.\n");
1087
1088         tmp = *frame;
1089         tmp.extended_data = tmp.data;
1090         frame = &tmp;
1091     }
1092
1093     /* check for valid frame size */
1094     if (frame) {
1095         if (avctx->codec->capabilities & CODEC_CAP_SMALL_LAST_FRAME) {
1096             if (frame->nb_samples > avctx->frame_size)
1097                 return AVERROR(EINVAL);
1098         } else if (!(avctx->codec->capabilities & CODEC_CAP_VARIABLE_FRAME_SIZE)) {
1099             if (frame->nb_samples < avctx->frame_size &&
1100                 !avctx->internal->last_audio_frame) {
1101                 ret = pad_last_frame(avctx, &padded_frame, frame);
1102                 if (ret < 0)
1103                     return ret;
1104
1105                 frame = padded_frame;
1106                 avctx->internal->last_audio_frame = 1;
1107             }
1108
1109             if (frame->nb_samples != avctx->frame_size)
1110                 return AVERROR(EINVAL);
1111         }
1112     }
1113
1114     ret = avctx->codec->encode2(avctx, avpkt, frame, got_packet_ptr);
1115     if (!ret) {
1116         if (*got_packet_ptr) {
1117             if (!(avctx->codec->capabilities & CODEC_CAP_DELAY)) {
1118                 if (avpkt->pts == AV_NOPTS_VALUE)
1119                     avpkt->pts = frame->pts;
1120                 if (!avpkt->duration)
1121                     avpkt->duration = ff_samples_to_time_base(avctx,
1122                                                               frame->nb_samples);
1123             }
1124             avpkt->dts = avpkt->pts;
1125         } else {
1126             avpkt->size = 0;
1127         }
1128     }
1129     if (avpkt->data && avpkt->data == avctx->internal->byte_buffer) {
1130         needs_realloc = 0;
1131         if (user_pkt.data) {
1132             if (user_pkt.size >= avpkt->size) {
1133                 memcpy(user_pkt.data, avpkt->data, avpkt->size);
1134             } else {
1135                 av_log(avctx, AV_LOG_ERROR, "Provided packet is too small, needs to be %d\n", avpkt->size);
1136                 avpkt->size = user_pkt.size;
1137                 ret = -1;
1138             }
1139             avpkt->data     = user_pkt.data;
1140             avpkt->destruct = user_pkt.destruct;
1141         } else {
1142             if (av_dup_packet(avpkt) < 0) {
1143                 ret = AVERROR(ENOMEM);
1144             }
1145         }
1146     }
1147
1148     if (!ret) {
1149         if (needs_realloc && avpkt->data) {
1150             uint8_t *new_data = av_realloc(avpkt->data, avpkt->size + FF_INPUT_BUFFER_PADDING_SIZE);
1151             if (new_data)
1152                 avpkt->data = new_data;
1153         }
1154
1155         avctx->frame_number++;
1156     }
1157
1158     if (ret < 0 || !*got_packet_ptr) {
1159         av_free_packet(avpkt);
1160         av_init_packet(avpkt);
1161         return ret;
1162     }
1163
1164     /* NOTE: if we add any audio encoders which output non-keyframe packets,
1165              this needs to be moved to the encoders, but for now we can do it
1166              here to simplify things */
1167     avpkt->flags |= AV_PKT_FLAG_KEY;
1168
1169     if (padded_frame) {
1170         av_freep(&padded_frame->data[0]);
1171         if (padded_frame->extended_data != padded_frame->data)
1172             av_freep(&padded_frame->extended_data);
1173         av_freep(&padded_frame);
1174     }
1175
1176     return ret;
1177 }
1178
1179 #if FF_API_OLD_DECODE_AUDIO
1180 int attribute_align_arg avcodec_encode_audio(AVCodecContext *avctx,
1181                                              uint8_t *buf, int buf_size,
1182                                              const short *samples)
1183 {
1184     AVPacket pkt;
1185     AVFrame frame0;
1186     AVFrame *frame;
1187     int ret, samples_size, got_packet;
1188
1189     av_init_packet(&pkt);
1190     pkt.data = buf;
1191     pkt.size = buf_size;
1192
1193     if (samples) {
1194         frame = &frame0;
1195         avcodec_get_frame_defaults(frame);
1196
1197         if (avctx->frame_size) {
1198             frame->nb_samples = avctx->frame_size;
1199         } else {
1200             /* if frame_size is not set, the number of samples must be
1201                calculated from the buffer size */
1202             int64_t nb_samples;
1203             if (!av_get_bits_per_sample(avctx->codec_id)) {
1204                 av_log(avctx, AV_LOG_ERROR, "avcodec_encode_audio() does not "
1205                        "support this codec\n");
1206                 return AVERROR(EINVAL);
1207             }
1208             nb_samples = (int64_t)buf_size * 8 /
1209                          (av_get_bits_per_sample(avctx->codec_id) *
1210                          avctx->channels);
1211             if (nb_samples >= INT_MAX)
1212                 return AVERROR(EINVAL);
1213             frame->nb_samples = nb_samples;
1214         }
1215
1216         /* it is assumed that the samples buffer is large enough based on the
1217            relevant parameters */
1218         samples_size = av_samples_get_buffer_size(NULL, avctx->channels,
1219                                                   frame->nb_samples,
1220                                                   avctx->sample_fmt, 1);
1221         if ((ret = avcodec_fill_audio_frame(frame, avctx->channels,
1222                                             avctx->sample_fmt,
1223                                             (const uint8_t *) samples,
1224                                             samples_size, 1)))
1225             return ret;
1226
1227         /* fabricate frame pts from sample count.
1228            this is needed because the avcodec_encode_audio() API does not have
1229            a way for the user to provide pts */
1230         if(avctx->sample_rate && avctx->time_base.num)
1231             frame->pts = ff_samples_to_time_base(avctx,
1232                                                 avctx->internal->sample_count);
1233         else
1234             frame->pts = AV_NOPTS_VALUE;
1235         avctx->internal->sample_count += frame->nb_samples;
1236     } else {
1237         frame = NULL;
1238     }
1239
1240     got_packet = 0;
1241     ret = avcodec_encode_audio2(avctx, &pkt, frame, &got_packet);
1242     if (!ret && got_packet && avctx->coded_frame) {
1243         avctx->coded_frame->pts       = pkt.pts;
1244         avctx->coded_frame->key_frame = !!(pkt.flags & AV_PKT_FLAG_KEY);
1245     }
1246     /* free any side data since we cannot return it */
1247     ff_packet_free_side_data(&pkt);
1248
1249     if (frame && frame->extended_data != frame->data)
1250         av_freep(&frame->extended_data);
1251
1252     return ret ? ret : pkt.size;
1253 }
1254 #endif
1255
1256 #if FF_API_OLD_ENCODE_VIDEO
1257 int attribute_align_arg avcodec_encode_video(AVCodecContext *avctx, uint8_t *buf, int buf_size,
1258                          const AVFrame *pict)
1259 {
1260     AVPacket pkt;
1261     int ret, got_packet = 0;
1262
1263     if(buf_size < FF_MIN_BUFFER_SIZE){
1264         av_log(avctx, AV_LOG_ERROR, "buffer smaller than minimum size\n");
1265         return -1;
1266     }
1267
1268     av_init_packet(&pkt);
1269     pkt.data = buf;
1270     pkt.size = buf_size;
1271
1272     ret = avcodec_encode_video2(avctx, &pkt, pict, &got_packet);
1273     if (!ret && got_packet && avctx->coded_frame) {
1274         avctx->coded_frame->pts       = pkt.pts;
1275         avctx->coded_frame->key_frame = !!(pkt.flags & AV_PKT_FLAG_KEY);
1276     }
1277
1278     /* free any side data since we cannot return it */
1279     if (pkt.side_data_elems > 0) {
1280         int i;
1281         for (i = 0; i < pkt.side_data_elems; i++)
1282             av_free(pkt.side_data[i].data);
1283         av_freep(&pkt.side_data);
1284         pkt.side_data_elems = 0;
1285     }
1286
1287     return ret ? ret : pkt.size;
1288 }
1289 #endif
1290
1291 int attribute_align_arg avcodec_encode_video2(AVCodecContext *avctx,
1292                                               AVPacket *avpkt,
1293                                               const AVFrame *frame,
1294                                               int *got_packet_ptr)
1295 {
1296     int ret;
1297     AVPacket user_pkt = *avpkt;
1298     int needs_realloc = !user_pkt.data;
1299
1300     *got_packet_ptr = 0;
1301
1302     if (!(avctx->codec->capabilities & CODEC_CAP_DELAY) && !frame) {
1303         av_free_packet(avpkt);
1304         av_init_packet(avpkt);
1305         avpkt->size     = 0;
1306         return 0;
1307     }
1308
1309     if (av_image_check_size(avctx->width, avctx->height, 0, avctx))
1310         return AVERROR(EINVAL);
1311
1312     av_assert0(avctx->codec->encode2);
1313
1314     ret = avctx->codec->encode2(avctx, avpkt, frame, got_packet_ptr);
1315     av_assert0(ret <= 0);
1316
1317     if (avpkt->data && avpkt->data == avctx->internal->byte_buffer) {
1318         needs_realloc = 0;
1319         if (user_pkt.data) {
1320             if (user_pkt.size >= avpkt->size) {
1321                 memcpy(user_pkt.data, avpkt->data, avpkt->size);
1322             } else {
1323                 av_log(avctx, AV_LOG_ERROR, "Provided packet is too small, needs to be %d\n", avpkt->size);
1324                 avpkt->size = user_pkt.size;
1325                 ret = -1;
1326             }
1327             avpkt->data     = user_pkt.data;
1328             avpkt->destruct = user_pkt.destruct;
1329         } else {
1330             if (av_dup_packet(avpkt) < 0) {
1331                 ret = AVERROR(ENOMEM);
1332             }
1333         }
1334     }
1335
1336     if (!ret) {
1337         if (!*got_packet_ptr)
1338             avpkt->size = 0;
1339         else if (!(avctx->codec->capabilities & CODEC_CAP_DELAY))
1340             avpkt->pts = avpkt->dts = frame->pts;
1341
1342         if (needs_realloc && avpkt->data &&
1343             avpkt->destruct == av_destruct_packet) {
1344             uint8_t *new_data = av_realloc(avpkt->data, avpkt->size + FF_INPUT_BUFFER_PADDING_SIZE);
1345             if (new_data)
1346                 avpkt->data = new_data;
1347         }
1348
1349         avctx->frame_number++;
1350     }
1351
1352     if (ret < 0 || !*got_packet_ptr)
1353         av_free_packet(avpkt);
1354
1355     emms_c();
1356     return ret;
1357 }
1358
1359 int avcodec_encode_subtitle(AVCodecContext *avctx, uint8_t *buf, int buf_size,
1360                             const AVSubtitle *sub)
1361 {
1362     int ret;
1363     if(sub->start_display_time) {
1364         av_log(avctx, AV_LOG_ERROR, "start_display_time must be 0.\n");
1365         return -1;
1366     }
1367
1368     ret = avctx->codec->encode(avctx, buf, buf_size, (void *)(intptr_t)sub);
1369     avctx->frame_number++;
1370     return ret;
1371 }
1372
1373 /**
1374  * Attempt to guess proper monotonic timestamps for decoded video frames
1375  * which might have incorrect times. Input timestamps may wrap around, in
1376  * which case the output will as well.
1377  *
1378  * @param pts the pts field of the decoded AVPacket, as passed through
1379  * AVFrame.pkt_pts
1380  * @param dts the dts field of the decoded AVPacket
1381  * @return one of the input values, may be AV_NOPTS_VALUE
1382  */
1383 static int64_t guess_correct_pts(AVCodecContext *ctx,
1384                                  int64_t reordered_pts, int64_t dts)
1385 {
1386     int64_t pts = AV_NOPTS_VALUE;
1387
1388     if (dts != AV_NOPTS_VALUE) {
1389         ctx->pts_correction_num_faulty_dts += dts <= ctx->pts_correction_last_dts;
1390         ctx->pts_correction_last_dts = dts;
1391     }
1392     if (reordered_pts != AV_NOPTS_VALUE) {
1393         ctx->pts_correction_num_faulty_pts += reordered_pts <= ctx->pts_correction_last_pts;
1394         ctx->pts_correction_last_pts = reordered_pts;
1395     }
1396     if ((ctx->pts_correction_num_faulty_pts<=ctx->pts_correction_num_faulty_dts || dts == AV_NOPTS_VALUE)
1397        && reordered_pts != AV_NOPTS_VALUE)
1398         pts = reordered_pts;
1399     else
1400         pts = dts;
1401
1402     return pts;
1403 }
1404
1405 static void apply_param_change(AVCodecContext *avctx, AVPacket *avpkt)
1406 {
1407     int size = 0;
1408     const uint8_t *data;
1409     uint32_t flags;
1410
1411     if (!(avctx->codec->capabilities & CODEC_CAP_PARAM_CHANGE))
1412         return;
1413
1414     data = av_packet_get_side_data(avpkt, AV_PKT_DATA_PARAM_CHANGE, &size);
1415     if (!data || size < 4)
1416         return;
1417     flags = bytestream_get_le32(&data);
1418     size -= 4;
1419     if (size < 4) /* Required for any of the changes */
1420         return;
1421     if (flags & AV_SIDE_DATA_PARAM_CHANGE_CHANNEL_COUNT) {
1422         avctx->channels = bytestream_get_le32(&data);
1423         size -= 4;
1424     }
1425     if (flags & AV_SIDE_DATA_PARAM_CHANGE_CHANNEL_LAYOUT) {
1426         if (size < 8)
1427             return;
1428         avctx->channel_layout = bytestream_get_le64(&data);
1429         size -= 8;
1430     }
1431     if (size < 4)
1432         return;
1433     if (flags & AV_SIDE_DATA_PARAM_CHANGE_SAMPLE_RATE) {
1434         avctx->sample_rate = bytestream_get_le32(&data);
1435         size -= 4;
1436     }
1437     if (flags & AV_SIDE_DATA_PARAM_CHANGE_DIMENSIONS) {
1438         if (size < 8)
1439             return;
1440         avctx->width  = bytestream_get_le32(&data);
1441         avctx->height = bytestream_get_le32(&data);
1442         avcodec_set_dimensions(avctx, avctx->width, avctx->height);
1443         size -= 8;
1444     }
1445 }
1446
1447 int attribute_align_arg avcodec_decode_video2(AVCodecContext *avctx, AVFrame *picture,
1448                          int *got_picture_ptr,
1449                          const AVPacket *avpkt)
1450 {
1451     int ret;
1452     // copy to ensure we do not change avpkt
1453     AVPacket tmp = *avpkt;
1454
1455     if (avctx->codec->type != AVMEDIA_TYPE_VIDEO) {
1456         av_log(avctx, AV_LOG_ERROR, "Invalid media type for video\n");
1457         return AVERROR(EINVAL);
1458     }
1459
1460     *got_picture_ptr= 0;
1461     if((avctx->coded_width||avctx->coded_height) && av_image_check_size(avctx->coded_width, avctx->coded_height, 0, avctx))
1462         return -1;
1463
1464     if((avctx->codec->capabilities & CODEC_CAP_DELAY) || avpkt->size || (avctx->active_thread_type&FF_THREAD_FRAME)){
1465         int did_split = av_packet_split_side_data(&tmp);
1466         apply_param_change(avctx, &tmp);
1467         avctx->pkt = &tmp;
1468         if (HAVE_THREADS && avctx->active_thread_type&FF_THREAD_FRAME)
1469              ret = ff_thread_decode_frame(avctx, picture, got_picture_ptr,
1470                                           &tmp);
1471         else {
1472             ret = avctx->codec->decode(avctx, picture, got_picture_ptr,
1473                               &tmp);
1474             picture->pkt_dts= avpkt->dts;
1475
1476             if(!avctx->has_b_frames){
1477             picture->pkt_pos= avpkt->pos;
1478             }
1479             //FIXME these should be under if(!avctx->has_b_frames)
1480             if (!picture->sample_aspect_ratio.num)
1481                 picture->sample_aspect_ratio = avctx->sample_aspect_ratio;
1482             if (!picture->width)
1483                 picture->width = avctx->width;
1484             if (!picture->height)
1485                 picture->height = avctx->height;
1486             if (picture->format == PIX_FMT_NONE)
1487                 picture->format = avctx->pix_fmt;
1488         }
1489
1490         emms_c(); //needed to avoid an emms_c() call before every return;
1491
1492         avctx->pkt = NULL;
1493         if (did_split) {
1494             ff_packet_free_side_data(&tmp);
1495             if(ret == tmp.size)
1496                 ret = avpkt->size;
1497         }
1498
1499         if (*got_picture_ptr){
1500             avctx->frame_number++;
1501             picture->best_effort_timestamp = guess_correct_pts(avctx,
1502                                                             picture->pkt_pts,
1503                                                             picture->pkt_dts);
1504         }
1505     }else
1506         ret= 0;
1507
1508     return ret;
1509 }
1510
1511 #if FF_API_OLD_DECODE_AUDIO
1512 int attribute_align_arg avcodec_decode_audio3(AVCodecContext *avctx, int16_t *samples,
1513                          int *frame_size_ptr,
1514                          AVPacket *avpkt)
1515 {
1516     AVFrame frame;
1517     int ret, got_frame = 0;
1518
1519     if (avctx->get_buffer != avcodec_default_get_buffer) {
1520         av_log(avctx, AV_LOG_ERROR, "Custom get_buffer() for use with"
1521                "avcodec_decode_audio3() detected. Overriding with avcodec_default_get_buffer\n");
1522         av_log(avctx, AV_LOG_ERROR, "Please port your application to "
1523                "avcodec_decode_audio4()\n");
1524         avctx->get_buffer = avcodec_default_get_buffer;
1525         avctx->release_buffer = avcodec_default_release_buffer;
1526     }
1527
1528     ret = avcodec_decode_audio4(avctx, &frame, &got_frame, avpkt);
1529
1530     if (ret >= 0 && got_frame) {
1531         int ch, plane_size;
1532         int planar = av_sample_fmt_is_planar(avctx->sample_fmt);
1533         int data_size = av_samples_get_buffer_size(&plane_size, avctx->channels,
1534                                                    frame.nb_samples,
1535                                                    avctx->sample_fmt, 1);
1536         if (*frame_size_ptr < data_size) {
1537             av_log(avctx, AV_LOG_ERROR, "output buffer size is too small for "
1538                    "the current frame (%d < %d)\n", *frame_size_ptr, data_size);
1539             return AVERROR(EINVAL);
1540         }
1541
1542         memcpy(samples, frame.extended_data[0], plane_size);
1543
1544         if (planar && avctx->channels > 1) {
1545             uint8_t *out = ((uint8_t *)samples) + plane_size;
1546             for (ch = 1; ch < avctx->channels; ch++) {
1547                 memcpy(out, frame.extended_data[ch], plane_size);
1548                 out += plane_size;
1549             }
1550         }
1551         *frame_size_ptr = data_size;
1552     } else {
1553         *frame_size_ptr = 0;
1554     }
1555     return ret;
1556 }
1557 #endif
1558
1559 int attribute_align_arg avcodec_decode_audio4(AVCodecContext *avctx,
1560                                               AVFrame *frame,
1561                                               int *got_frame_ptr,
1562                                               const AVPacket *avpkt)
1563 {
1564     int ret = 0;
1565
1566     *got_frame_ptr = 0;
1567
1568     if (!avpkt->data && avpkt->size) {
1569         av_log(avctx, AV_LOG_ERROR, "invalid packet: NULL data, size != 0\n");
1570         return AVERROR(EINVAL);
1571     }
1572     if (avctx->codec->type != AVMEDIA_TYPE_AUDIO) {
1573         av_log(avctx, AV_LOG_ERROR, "Invalid media type for audio\n");
1574         return AVERROR(EINVAL);
1575     }
1576
1577     if ((avctx->codec->capabilities & CODEC_CAP_DELAY) || avpkt->size) {
1578         // copy to ensure we do not change avpkt
1579         AVPacket tmp = *avpkt;
1580         int did_split = av_packet_split_side_data(&tmp);
1581         apply_param_change(avctx, &tmp);
1582
1583         avctx->pkt = &tmp;
1584         ret = avctx->codec->decode(avctx, frame, got_frame_ptr, &tmp);
1585         if (ret >= 0 && *got_frame_ptr) {
1586             avctx->frame_number++;
1587             frame->pkt_dts = avpkt->dts;
1588             if (frame->format == AV_SAMPLE_FMT_NONE)
1589                 frame->format = avctx->sample_fmt;
1590             if (!frame->channel_layout)
1591                 frame->channel_layout = avctx->channel_layout;
1592             if (!frame->sample_rate)
1593                 frame->sample_rate = avctx->sample_rate;
1594         }
1595
1596         avctx->pkt = NULL;
1597         if (did_split) {
1598             ff_packet_free_side_data(&tmp);
1599             if(ret == tmp.size)
1600                 ret = avpkt->size;
1601         }
1602     }
1603     return ret;
1604 }
1605
1606 int avcodec_decode_subtitle2(AVCodecContext *avctx, AVSubtitle *sub,
1607                             int *got_sub_ptr,
1608                             AVPacket *avpkt)
1609 {
1610     int ret;
1611
1612     if (avctx->codec->type != AVMEDIA_TYPE_SUBTITLE) {
1613         av_log(avctx, AV_LOG_ERROR, "Invalid media type for subtitles\n");
1614         return AVERROR(EINVAL);
1615     }
1616
1617     avctx->pkt = avpkt;
1618     *got_sub_ptr = 0;
1619     avcodec_get_subtitle_defaults(sub);
1620     ret = avctx->codec->decode(avctx, sub, got_sub_ptr, avpkt);
1621     if (*got_sub_ptr)
1622         avctx->frame_number++;
1623     return ret;
1624 }
1625
1626 void avsubtitle_free(AVSubtitle *sub)
1627 {
1628     int i;
1629
1630     for (i = 0; i < sub->num_rects; i++)
1631     {
1632         av_freep(&sub->rects[i]->pict.data[0]);
1633         av_freep(&sub->rects[i]->pict.data[1]);
1634         av_freep(&sub->rects[i]->pict.data[2]);
1635         av_freep(&sub->rects[i]->pict.data[3]);
1636         av_freep(&sub->rects[i]->text);
1637         av_freep(&sub->rects[i]->ass);
1638         av_freep(&sub->rects[i]);
1639     }
1640
1641     av_freep(&sub->rects);
1642
1643     memset(sub, 0, sizeof(AVSubtitle));
1644 }
1645
1646 av_cold int avcodec_close(AVCodecContext *avctx)
1647 {
1648     /* If there is a user-supplied mutex locking routine, call it. */
1649     if (ff_lockmgr_cb) {
1650         if ((*ff_lockmgr_cb)(&codec_mutex, AV_LOCK_OBTAIN))
1651             return -1;
1652     }
1653
1654     entangled_thread_counter++;
1655     if(entangled_thread_counter != 1){
1656         av_log(avctx, AV_LOG_ERROR, "insufficient thread locking around avcodec_open/close()\n");
1657         entangled_thread_counter--;
1658         return -1;
1659     }
1660
1661     if (avcodec_is_open(avctx)) {
1662         if (HAVE_THREADS && avctx->thread_opaque)
1663             ff_thread_free(avctx);
1664         if (avctx->codec && avctx->codec->close)
1665             avctx->codec->close(avctx);
1666         avcodec_default_free_buffers(avctx);
1667         avctx->coded_frame = NULL;
1668         avctx->internal->byte_buffer_size = 0;
1669         av_freep(&avctx->internal->byte_buffer);
1670         av_freep(&avctx->internal);
1671     }
1672
1673     if (avctx->priv_data && avctx->codec && avctx->codec->priv_class)
1674         av_opt_free(avctx->priv_data);
1675     av_opt_free(avctx);
1676     av_freep(&avctx->priv_data);
1677     if (av_codec_is_encoder(avctx->codec))
1678         av_freep(&avctx->extradata);
1679     avctx->codec = NULL;
1680     avctx->active_thread_type = 0;
1681     entangled_thread_counter--;
1682
1683     /* Release any user-supplied mutex. */
1684     if (ff_lockmgr_cb) {
1685         (*ff_lockmgr_cb)(&codec_mutex, AV_LOCK_RELEASE);
1686     }
1687     return 0;
1688 }
1689
1690 static enum CodecID remap_deprecated_codec_id(enum CodecID id)
1691 {
1692     switch(id){
1693         //This is for future deprecatec codec ids, its empty since
1694         //last major bump but will fill up again over time, please dont remove it
1695 //         case CODEC_ID_UTVIDEO_DEPRECATED: return CODEC_ID_UTVIDEO;
1696         default                         : return id;
1697     }
1698 }
1699
1700 AVCodec *avcodec_find_encoder(enum CodecID id)
1701 {
1702     AVCodec *p, *experimental=NULL;
1703     p = first_avcodec;
1704     id= remap_deprecated_codec_id(id);
1705     while (p) {
1706         if (av_codec_is_encoder(p) && p->id == id) {
1707             if (p->capabilities & CODEC_CAP_EXPERIMENTAL && !experimental) {
1708                 experimental = p;
1709             } else
1710                 return p;
1711         }
1712         p = p->next;
1713     }
1714     return experimental;
1715 }
1716
1717 AVCodec *avcodec_find_encoder_by_name(const char *name)
1718 {
1719     AVCodec *p;
1720     if (!name)
1721         return NULL;
1722     p = first_avcodec;
1723     while (p) {
1724         if (av_codec_is_encoder(p) && strcmp(name,p->name) == 0)
1725             return p;
1726         p = p->next;
1727     }
1728     return NULL;
1729 }
1730
1731 AVCodec *avcodec_find_decoder(enum CodecID id)
1732 {
1733     AVCodec *p, *experimental=NULL;
1734     p = first_avcodec;
1735     id= remap_deprecated_codec_id(id);
1736     while (p) {
1737         if (av_codec_is_decoder(p) && p->id == id) {
1738             if (p->capabilities & CODEC_CAP_EXPERIMENTAL && !experimental) {
1739                 experimental = p;
1740             } else
1741                 return p;
1742         }
1743         p = p->next;
1744     }
1745     return experimental;
1746 }
1747
1748 AVCodec *avcodec_find_decoder_by_name(const char *name)
1749 {
1750     AVCodec *p;
1751     if (!name)
1752         return NULL;
1753     p = first_avcodec;
1754     while (p) {
1755         if (av_codec_is_decoder(p) && strcmp(name,p->name) == 0)
1756             return p;
1757         p = p->next;
1758     }
1759     return NULL;
1760 }
1761
1762 const char *avcodec_get_name(enum CodecID id)
1763 {
1764     AVCodec *codec;
1765
1766 #if !CONFIG_SMALL
1767     switch (id) {
1768 #include "libavcodec/codec_names.h"
1769     }
1770     av_log(NULL, AV_LOG_WARNING, "Codec 0x%x is not in the full list.\n", id);
1771 #endif
1772     codec = avcodec_find_decoder(id);
1773     if (codec)
1774         return codec->name;
1775     codec = avcodec_find_encoder(id);
1776     if (codec)
1777         return codec->name;
1778     return "unknown_codec";
1779 }
1780
1781 size_t av_get_codec_tag_string(char *buf, size_t buf_size, unsigned int codec_tag)
1782 {
1783     int i, len, ret = 0;
1784
1785 #define IS_PRINT(x)                                               \
1786     (((x) >= '0' && (x) <= '9') ||                                \
1787      ((x) >= 'a' && (x) <= 'z') || ((x) >= 'A' && (x) <= 'Z') ||  \
1788      ((x) == '.' || (x) == ' '))
1789
1790     for (i = 0; i < 4; i++) {
1791         len = snprintf(buf, buf_size,
1792                        IS_PRINT(codec_tag&0xFF) ? "%c" : "[%d]", codec_tag&0xFF);
1793         buf      += len;
1794         buf_size  = buf_size > len ? buf_size - len : 0;
1795         ret      += len;
1796         codec_tag>>=8;
1797     }
1798     return ret;
1799 }
1800
1801 void avcodec_string(char *buf, int buf_size, AVCodecContext *enc, int encode)
1802 {
1803     const char *codec_type;
1804     const char *codec_name;
1805     const char *profile = NULL;
1806     AVCodec *p;
1807     int bitrate;
1808     AVRational display_aspect_ratio;
1809
1810     if (!buf || buf_size <= 0)
1811         return;
1812     codec_type = av_get_media_type_string(enc->codec_type);
1813     codec_name = avcodec_get_name(enc->codec_id);
1814     if (enc->profile != FF_PROFILE_UNKNOWN) {
1815         if (enc->codec)
1816             p = enc->codec;
1817         else
1818             p = encode ? avcodec_find_encoder(enc->codec_id) :
1819                         avcodec_find_decoder(enc->codec_id);
1820         if (p)
1821             profile = av_get_profile_name(p, enc->profile);
1822     }
1823
1824     snprintf(buf, buf_size, "%s: %s%s", codec_type ? codec_type : "unknown",
1825              codec_name, enc->mb_decision ? " (hq)" : "");
1826     buf[0] ^= 'a' ^ 'A'; /* first letter in uppercase */
1827     if (profile)
1828         snprintf(buf + strlen(buf), buf_size - strlen(buf), " (%s)", profile);
1829     if (enc->codec_tag) {
1830         char tag_buf[32];
1831         av_get_codec_tag_string(tag_buf, sizeof(tag_buf), enc->codec_tag);
1832         snprintf(buf + strlen(buf), buf_size - strlen(buf),
1833                  " (%s / 0x%04X)", tag_buf, enc->codec_tag);
1834     }
1835     switch(enc->codec_type) {
1836     case AVMEDIA_TYPE_VIDEO:
1837         if (enc->pix_fmt != PIX_FMT_NONE) {
1838             snprintf(buf + strlen(buf), buf_size - strlen(buf),
1839                      ", %s",
1840                      av_get_pix_fmt_name(enc->pix_fmt));
1841         }
1842         if (enc->width) {
1843             snprintf(buf + strlen(buf), buf_size - strlen(buf),
1844                      ", %dx%d",
1845                      enc->width, enc->height);
1846             if (enc->sample_aspect_ratio.num) {
1847                 av_reduce(&display_aspect_ratio.num, &display_aspect_ratio.den,
1848                           enc->width*enc->sample_aspect_ratio.num,
1849                           enc->height*enc->sample_aspect_ratio.den,
1850                           1024*1024);
1851                 snprintf(buf + strlen(buf), buf_size - strlen(buf),
1852                          " [SAR %d:%d DAR %d:%d]",
1853                          enc->sample_aspect_ratio.num, enc->sample_aspect_ratio.den,
1854                          display_aspect_ratio.num, display_aspect_ratio.den);
1855             }
1856             if(av_log_get_level() >= AV_LOG_DEBUG){
1857                 int g= av_gcd(enc->time_base.num, enc->time_base.den);
1858                 snprintf(buf + strlen(buf), buf_size - strlen(buf),
1859                      ", %d/%d",
1860                      enc->time_base.num/g, enc->time_base.den/g);
1861             }
1862         }
1863         if (encode) {
1864             snprintf(buf + strlen(buf), buf_size - strlen(buf),
1865                      ", q=%d-%d", enc->qmin, enc->qmax);
1866         }
1867         break;
1868     case AVMEDIA_TYPE_AUDIO:
1869         if (enc->sample_rate) {
1870             snprintf(buf + strlen(buf), buf_size - strlen(buf),
1871                      ", %d Hz", enc->sample_rate);
1872         }
1873         av_strlcat(buf, ", ", buf_size);
1874         av_get_channel_layout_string(buf + strlen(buf), buf_size - strlen(buf), enc->channels, enc->channel_layout);
1875         if (enc->sample_fmt != AV_SAMPLE_FMT_NONE) {
1876             snprintf(buf + strlen(buf), buf_size - strlen(buf),
1877                      ", %s", av_get_sample_fmt_name(enc->sample_fmt));
1878         }
1879         break;
1880     default:
1881         return;
1882     }
1883     if (encode) {
1884         if (enc->flags & CODEC_FLAG_PASS1)
1885             snprintf(buf + strlen(buf), buf_size - strlen(buf),
1886                      ", pass 1");
1887         if (enc->flags & CODEC_FLAG_PASS2)
1888             snprintf(buf + strlen(buf), buf_size - strlen(buf),
1889                      ", pass 2");
1890     }
1891     bitrate = get_bit_rate(enc);
1892     if (bitrate != 0) {
1893         snprintf(buf + strlen(buf), buf_size - strlen(buf),
1894                  ", %d kb/s", bitrate / 1000);
1895     }
1896 }
1897
1898 const char *av_get_profile_name(const AVCodec *codec, int profile)
1899 {
1900     const AVProfile *p;
1901     if (profile == FF_PROFILE_UNKNOWN || !codec->profiles)
1902         return NULL;
1903
1904     for (p = codec->profiles; p->profile != FF_PROFILE_UNKNOWN; p++)
1905         if (p->profile == profile)
1906             return p->name;
1907
1908     return NULL;
1909 }
1910
1911 unsigned avcodec_version( void )
1912 {
1913 //    av_assert0(CODEC_ID_V410==164);
1914     av_assert0(CODEC_ID_PCM_S8_PLANAR==65563);
1915     av_assert0(CODEC_ID_ADPCM_G722==69660);
1916 //     av_assert0(CODEC_ID_BMV_AUDIO==86071);
1917     av_assert0(CODEC_ID_SRT==94216);
1918     av_assert0(LIBAVCODEC_VERSION_MICRO >= 100);
1919
1920   return LIBAVCODEC_VERSION_INT;
1921 }
1922
1923 const char *avcodec_configuration(void)
1924 {
1925     return FFMPEG_CONFIGURATION;
1926 }
1927
1928 const char *avcodec_license(void)
1929 {
1930 #define LICENSE_PREFIX "libavcodec license: "
1931     return LICENSE_PREFIX FFMPEG_LICENSE + sizeof(LICENSE_PREFIX) - 1;
1932 }
1933
1934 void avcodec_flush_buffers(AVCodecContext *avctx)
1935 {
1936     if(HAVE_THREADS && avctx->active_thread_type&FF_THREAD_FRAME)
1937         ff_thread_flush(avctx);
1938     else if(avctx->codec->flush)
1939         avctx->codec->flush(avctx);
1940
1941     avctx->pts_correction_last_pts =
1942     avctx->pts_correction_last_dts = INT64_MIN;
1943 }
1944
1945 static void video_free_buffers(AVCodecContext *s)
1946 {
1947     AVCodecInternal *avci = s->internal;
1948     int i, j;
1949
1950     if (!avci->buffer)
1951         return;
1952
1953     if (avci->buffer_count)
1954         av_log(s, AV_LOG_WARNING, "Found %i unreleased buffers!\n",
1955                avci->buffer_count);
1956     for(i=0; i<INTERNAL_BUFFER_SIZE; i++){
1957         InternalBuffer *buf = &avci->buffer[i];
1958         for(j=0; j<4; j++){
1959             av_freep(&buf->base[j]);
1960             buf->data[j]= NULL;
1961         }
1962     }
1963     av_freep(&avci->buffer);
1964
1965     avci->buffer_count=0;
1966 }
1967
1968 static void audio_free_buffers(AVCodecContext *avctx)
1969 {
1970     AVCodecInternal *avci = avctx->internal;
1971     InternalBuffer *buf;
1972
1973     if (!avci->buffer)
1974         return;
1975     buf = avci->buffer;
1976
1977     if (buf->extended_data) {
1978         av_free(buf->extended_data[0]);
1979         if (buf->extended_data != buf->data)
1980             av_freep(&buf->extended_data);
1981     }
1982     av_freep(&avci->buffer);
1983 }
1984
1985 void avcodec_default_free_buffers(AVCodecContext *avctx)
1986 {
1987     switch (avctx->codec_type) {
1988     case AVMEDIA_TYPE_VIDEO:
1989         video_free_buffers(avctx);
1990         break;
1991     case AVMEDIA_TYPE_AUDIO:
1992         audio_free_buffers(avctx);
1993         break;
1994     default:
1995         break;
1996     }
1997 }
1998
1999 int av_get_exact_bits_per_sample(enum CodecID codec_id)
2000 {
2001     switch(codec_id){
2002     case CODEC_ID_ADPCM_CT:
2003     case CODEC_ID_ADPCM_IMA_APC:
2004     case CODEC_ID_ADPCM_IMA_EA_SEAD:
2005     case CODEC_ID_ADPCM_IMA_WS:
2006     case CODEC_ID_ADPCM_G722:
2007     case CODEC_ID_ADPCM_YAMAHA:
2008         return 4;
2009     case CODEC_ID_PCM_ALAW:
2010     case CODEC_ID_PCM_MULAW:
2011     case CODEC_ID_PCM_S8:
2012     case CODEC_ID_PCM_U8:
2013     case CODEC_ID_PCM_ZORK:
2014         return 8;
2015     case CODEC_ID_PCM_S16BE:
2016     case CODEC_ID_PCM_S16LE:
2017     case CODEC_ID_PCM_S16LE_PLANAR:
2018     case CODEC_ID_PCM_U16BE:
2019     case CODEC_ID_PCM_U16LE:
2020         return 16;
2021     case CODEC_ID_PCM_S24DAUD:
2022     case CODEC_ID_PCM_S24BE:
2023     case CODEC_ID_PCM_S24LE:
2024     case CODEC_ID_PCM_U24BE:
2025     case CODEC_ID_PCM_U24LE:
2026         return 24;
2027     case CODEC_ID_PCM_S32BE:
2028     case CODEC_ID_PCM_S32LE:
2029     case CODEC_ID_PCM_U32BE:
2030     case CODEC_ID_PCM_U32LE:
2031     case CODEC_ID_PCM_F32BE:
2032     case CODEC_ID_PCM_F32LE:
2033         return 32;
2034     case CODEC_ID_PCM_F64BE:
2035     case CODEC_ID_PCM_F64LE:
2036         return 64;
2037     default:
2038         return 0;
2039     }
2040 }
2041
2042 enum CodecID av_get_pcm_codec(enum AVSampleFormat fmt, int be)
2043 {
2044     static const enum CodecID map[AV_SAMPLE_FMT_NB][2] = {
2045         [AV_SAMPLE_FMT_U8  ] = { CODEC_ID_PCM_U8,    CODEC_ID_PCM_U8    },
2046         [AV_SAMPLE_FMT_S16 ] = { CODEC_ID_PCM_S16LE, CODEC_ID_PCM_S16BE },
2047         [AV_SAMPLE_FMT_S32 ] = { CODEC_ID_PCM_S32LE, CODEC_ID_PCM_S32BE },
2048         [AV_SAMPLE_FMT_FLT ] = { CODEC_ID_PCM_F32LE, CODEC_ID_PCM_F32BE },
2049         [AV_SAMPLE_FMT_DBL ] = { CODEC_ID_PCM_F64LE, CODEC_ID_PCM_F64BE },
2050         [AV_SAMPLE_FMT_U8P ] = { CODEC_ID_PCM_U8,    CODEC_ID_PCM_U8    },
2051         [AV_SAMPLE_FMT_S16P] = { CODEC_ID_PCM_S16LE, CODEC_ID_PCM_S16BE },
2052         [AV_SAMPLE_FMT_S32P] = { CODEC_ID_PCM_S32LE, CODEC_ID_PCM_S32BE },
2053         [AV_SAMPLE_FMT_FLTP] = { CODEC_ID_PCM_F32LE, CODEC_ID_PCM_F32BE },
2054         [AV_SAMPLE_FMT_DBLP] = { CODEC_ID_PCM_F64LE, CODEC_ID_PCM_F64BE },
2055     };
2056     if (fmt < 0 || fmt >= AV_SAMPLE_FMT_NB)
2057         return CODEC_ID_NONE;
2058     if (be < 0 || be > 1)
2059         be = AV_NE(1, 0);
2060     return map[fmt][be];
2061 }
2062
2063 int av_get_bits_per_sample(enum CodecID codec_id)
2064 {
2065     switch (codec_id) {
2066     case CODEC_ID_ADPCM_SBPRO_2:
2067         return 2;
2068     case CODEC_ID_ADPCM_SBPRO_3:
2069         return 3;
2070     case CODEC_ID_ADPCM_SBPRO_4:
2071     case CODEC_ID_ADPCM_IMA_WAV:
2072     case CODEC_ID_ADPCM_IMA_QT:
2073     case CODEC_ID_ADPCM_SWF:
2074     case CODEC_ID_ADPCM_MS:
2075         return 4;
2076     default:
2077         return av_get_exact_bits_per_sample(codec_id);
2078     }
2079 }
2080
2081 int av_get_audio_frame_duration(AVCodecContext *avctx, int frame_bytes)
2082 {
2083     int id, sr, ch, ba, tag, bps;
2084
2085     id  = avctx->codec_id;
2086     sr  = avctx->sample_rate;
2087     ch  = avctx->channels;
2088     ba  = avctx->block_align;
2089     tag = avctx->codec_tag;
2090     bps = av_get_exact_bits_per_sample(avctx->codec_id);
2091
2092     /* codecs with an exact constant bits per sample */
2093     if (bps > 0 && ch > 0 && frame_bytes > 0 && ch < 32768 && bps < 32768)
2094         return (frame_bytes * 8LL) / (bps * ch);
2095     bps = avctx->bits_per_coded_sample;
2096
2097     /* codecs with a fixed packet duration */
2098     switch (id) {
2099     case CODEC_ID_ADPCM_ADX:    return   32;
2100     case CODEC_ID_ADPCM_IMA_QT: return   64;
2101     case CODEC_ID_ADPCM_EA_XAS: return  128;
2102     case CODEC_ID_AMR_NB:
2103     case CODEC_ID_GSM:
2104     case CODEC_ID_QCELP:
2105     case CODEC_ID_RA_144:
2106     case CODEC_ID_RA_288:       return  160;
2107     case CODEC_ID_IMC:          return  256;
2108     case CODEC_ID_AMR_WB:
2109     case CODEC_ID_GSM_MS:       return  320;
2110     case CODEC_ID_MP1:          return  384;
2111     case CODEC_ID_ATRAC1:       return  512;
2112     case CODEC_ID_ATRAC3:       return 1024;
2113     case CODEC_ID_MP2:
2114     case CODEC_ID_MUSEPACK7:    return 1152;
2115     case CODEC_ID_AC3:          return 1536;
2116     }
2117
2118     if (sr > 0) {
2119         /* calc from sample rate */
2120         if (id == CODEC_ID_TTA)
2121             return 256 * sr / 245;
2122
2123         if (ch > 0) {
2124             /* calc from sample rate and channels */
2125             if (id == CODEC_ID_BINKAUDIO_DCT)
2126                 return (480 << (sr / 22050)) / ch;
2127         }
2128     }
2129
2130     if (ba > 0) {
2131         /* calc from block_align */
2132         if (id == CODEC_ID_SIPR) {
2133             switch (ba) {
2134             case 20: return 160;
2135             case 19: return 144;
2136             case 29: return 288;
2137             case 37: return 480;
2138             }
2139         }
2140     }
2141
2142     if (frame_bytes > 0) {
2143         /* calc from frame_bytes only */
2144         if (id == CODEC_ID_TRUESPEECH)
2145             return 240 * (frame_bytes / 32);
2146         if (id == CODEC_ID_NELLYMOSER)
2147             return 256 * (frame_bytes / 64);
2148
2149         if (bps > 0) {
2150             /* calc from frame_bytes and bits_per_coded_sample */
2151             if (id == CODEC_ID_ADPCM_G726)
2152                 return frame_bytes * 8 / bps;
2153         }
2154
2155         if (ch > 0) {
2156             /* calc from frame_bytes and channels */
2157             switch (id) {
2158             case CODEC_ID_ADPCM_4XM:
2159             case CODEC_ID_ADPCM_IMA_ISS:
2160                 return (frame_bytes - 4 * ch) * 2 / ch;
2161             case CODEC_ID_ADPCM_IMA_SMJPEG:
2162                 return (frame_bytes - 4) * 2 / ch;
2163             case CODEC_ID_ADPCM_IMA_AMV:
2164                 return (frame_bytes - 8) * 2 / ch;
2165             case CODEC_ID_ADPCM_XA:
2166                 return (frame_bytes / 128) * 224 / ch;
2167             case CODEC_ID_INTERPLAY_DPCM:
2168                 return (frame_bytes - 6 - ch) / ch;
2169             case CODEC_ID_ROQ_DPCM:
2170                 return (frame_bytes - 8) / ch;
2171             case CODEC_ID_XAN_DPCM:
2172                 return (frame_bytes - 2 * ch) / ch;
2173             case CODEC_ID_MACE3:
2174                 return 3 * frame_bytes / ch;
2175             case CODEC_ID_MACE6:
2176                 return 6 * frame_bytes / ch;
2177             case CODEC_ID_PCM_LXF:
2178                 return 2 * (frame_bytes / (5 * ch));
2179             }
2180
2181             if (tag) {
2182                 /* calc from frame_bytes, channels, and codec_tag */
2183                 if (id == CODEC_ID_SOL_DPCM) {
2184                     if (tag == 3)
2185                         return frame_bytes / ch;
2186                     else
2187                         return frame_bytes * 2 / ch;
2188                 }
2189             }
2190
2191             if (ba > 0) {
2192                 /* calc from frame_bytes, channels, and block_align */
2193                 int blocks = frame_bytes / ba;
2194                 switch (avctx->codec_id) {
2195                 case CODEC_ID_ADPCM_IMA_WAV:
2196                     return blocks * (1 + (ba - 4 * ch) / (4 * ch) * 8);
2197                 case CODEC_ID_ADPCM_IMA_DK3:
2198                     return blocks * (((ba - 16) * 2 / 3 * 4) / ch);
2199                 case CODEC_ID_ADPCM_IMA_DK4:
2200                     return blocks * (1 + (ba - 4 * ch) * 2 / ch);
2201                 case CODEC_ID_ADPCM_MS:
2202                     return blocks * (2 + (ba - 7 * ch) * 2 / ch);
2203                 }
2204             }
2205
2206             if (bps > 0) {
2207                 /* calc from frame_bytes, channels, and bits_per_coded_sample */
2208                 switch (avctx->codec_id) {
2209                 case CODEC_ID_PCM_DVD:
2210                     if(bps<4)
2211                         return 0;
2212                     return 2 * (frame_bytes / ((bps * 2 / 8) * ch));
2213                 case CODEC_ID_PCM_BLURAY:
2214                     if(bps<4)
2215                         return 0;
2216                     return frame_bytes / ((FFALIGN(ch, 2) * bps) / 8);
2217                 case CODEC_ID_S302M:
2218                     return 2 * (frame_bytes / ((bps + 4) / 4)) / ch;
2219                 }
2220             }
2221         }
2222     }
2223
2224     return 0;
2225 }
2226
2227 #if !HAVE_THREADS
2228 int ff_thread_init(AVCodecContext *s){
2229     return -1;
2230 }
2231 #endif
2232
2233 unsigned int av_xiphlacing(unsigned char *s, unsigned int v)
2234 {
2235     unsigned int n = 0;
2236
2237     while(v >= 0xff) {
2238         *s++ = 0xff;
2239         v -= 0xff;
2240         n++;
2241     }
2242     *s = v;
2243     n++;
2244     return n;
2245 }
2246
2247 int ff_match_2uint16(const uint16_t (*tab)[2], int size, int a, int b){
2248     int i;
2249     for(i=0; i<size && !(tab[i][0]==a && tab[i][1]==b); i++);
2250     return i;
2251 }
2252
2253 void av_log_missing_feature(void *avc, const char *feature, int want_sample)
2254 {
2255     av_log(avc, AV_LOG_WARNING, "%s not implemented. Update your FFmpeg "
2256             "version to the newest one from Git. If the problem still "
2257             "occurs, it means that your file has a feature which has not "
2258             "been implemented.\n", feature);
2259     if(want_sample)
2260         av_log_ask_for_sample(avc, NULL);
2261 }
2262
2263 void av_log_ask_for_sample(void *avc, const char *msg, ...)
2264 {
2265     va_list argument_list;
2266
2267     va_start(argument_list, msg);
2268
2269     if (msg)
2270         av_vlog(avc, AV_LOG_WARNING, msg, argument_list);
2271     av_log(avc, AV_LOG_WARNING, "If you want to help, upload a sample "
2272             "of this file to ftp://upload.ffmpeg.org/MPlayer/incoming/ "
2273             "and contact the ffmpeg-devel mailing list.\n");
2274
2275     va_end(argument_list);
2276 }
2277
2278 static AVHWAccel *first_hwaccel = NULL;
2279
2280 void av_register_hwaccel(AVHWAccel *hwaccel)
2281 {
2282     AVHWAccel **p = &first_hwaccel;
2283     while (*p)
2284         p = &(*p)->next;
2285     *p = hwaccel;
2286     hwaccel->next = NULL;
2287 }
2288
2289 AVHWAccel *av_hwaccel_next(AVHWAccel *hwaccel)
2290 {
2291     return hwaccel ? hwaccel->next : first_hwaccel;
2292 }
2293
2294 AVHWAccel *ff_find_hwaccel(enum CodecID codec_id, enum PixelFormat pix_fmt)
2295 {
2296     AVHWAccel *hwaccel=NULL;
2297
2298     while((hwaccel= av_hwaccel_next(hwaccel))){
2299         if (   hwaccel->id      == codec_id
2300             && hwaccel->pix_fmt == pix_fmt)
2301             return hwaccel;
2302     }
2303     return NULL;
2304 }
2305
2306 int av_lockmgr_register(int (*cb)(void **mutex, enum AVLockOp op))
2307 {
2308     if (ff_lockmgr_cb) {
2309         if (ff_lockmgr_cb(&codec_mutex, AV_LOCK_DESTROY))
2310             return -1;
2311         if (ff_lockmgr_cb(&avformat_mutex, AV_LOCK_DESTROY))
2312             return -1;
2313     }
2314
2315     ff_lockmgr_cb = cb;
2316
2317     if (ff_lockmgr_cb) {
2318         if (ff_lockmgr_cb(&codec_mutex, AV_LOCK_CREATE))
2319             return -1;
2320         if (ff_lockmgr_cb(&avformat_mutex, AV_LOCK_CREATE))
2321             return -1;
2322     }
2323     return 0;
2324 }
2325
2326 int avpriv_lock_avformat(void)
2327 {
2328     if (ff_lockmgr_cb) {
2329         if ((*ff_lockmgr_cb)(&avformat_mutex, AV_LOCK_OBTAIN))
2330             return -1;
2331     }
2332     return 0;
2333 }
2334
2335 int avpriv_unlock_avformat(void)
2336 {
2337     if (ff_lockmgr_cb) {
2338         if ((*ff_lockmgr_cb)(&avformat_mutex, AV_LOCK_RELEASE))
2339             return -1;
2340     }
2341     return 0;
2342 }
2343
2344 unsigned int avpriv_toupper4(unsigned int x)
2345 {
2346     return     toupper( x     &0xFF)
2347             + (toupper((x>>8 )&0xFF)<<8 )
2348             + (toupper((x>>16)&0xFF)<<16)
2349             + (toupper((x>>24)&0xFF)<<24);
2350 }
2351
2352 #if !HAVE_THREADS
2353
2354 int ff_thread_get_buffer(AVCodecContext *avctx, AVFrame *f)
2355 {
2356     f->owner = avctx;
2357
2358     ff_init_buffer_info(avctx, f);
2359
2360     return avctx->get_buffer(avctx, f);
2361 }
2362
2363 void ff_thread_release_buffer(AVCodecContext *avctx, AVFrame *f)
2364 {
2365     f->owner->release_buffer(f->owner, f);
2366 }
2367
2368 void ff_thread_finish_setup(AVCodecContext *avctx)
2369 {
2370 }
2371
2372 void ff_thread_report_progress(AVFrame *f, int progress, int field)
2373 {
2374 }
2375
2376 void ff_thread_await_progress(AVFrame *f, int progress, int field)
2377 {
2378 }
2379
2380 int ff_thread_can_start_frame(AVCodecContext *avctx)
2381 {
2382     return 1;
2383 }
2384
2385 #endif
2386
2387 enum AVMediaType avcodec_get_type(enum CodecID codec_id)
2388 {
2389     AVCodec *c= avcodec_find_decoder(codec_id);
2390     if(!c)
2391         c= avcodec_find_encoder(codec_id);
2392     if(c)
2393         return c->type;
2394
2395     if (codec_id <= CODEC_ID_NONE)
2396         return AVMEDIA_TYPE_UNKNOWN;
2397     else if (codec_id < CODEC_ID_FIRST_AUDIO)
2398         return AVMEDIA_TYPE_VIDEO;
2399     else if (codec_id < CODEC_ID_FIRST_SUBTITLE)
2400         return AVMEDIA_TYPE_AUDIO;
2401     else if (codec_id < CODEC_ID_FIRST_UNKNOWN)
2402         return AVMEDIA_TYPE_SUBTITLE;
2403
2404     return AVMEDIA_TYPE_UNKNOWN;
2405 }
2406
2407 int avcodec_is_open(AVCodecContext *s)
2408 {
2409     return !!s->internal;
2410 }