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