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