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