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