]> git.sesse.net Git - ffmpeg/blob - libavcodec/utils.c
lavc: unify similar code merged from both branches.
[ffmpeg] / libavcodec / utils.c
1 /*
2  * utils for libavcodec
3  * Copyright (c) 2001 Fabrice Bellard
4  * Copyright (c) 2002-2004 Michael Niedermayer <michaelni@gmx.at>
5  *
6  * This file is part of FFmpeg.
7  *
8  * FFmpeg is free software; you can redistribute it and/or
9  * modify it under the terms of the GNU Lesser General Public
10  * License as published by the Free Software Foundation; either
11  * version 2.1 of the License, or (at your option) any later version.
12  *
13  * FFmpeg is distributed in the hope that it will be useful,
14  * but WITHOUT ANY WARRANTY; without even the implied warranty of
15  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
16  * Lesser General Public License for more details.
17  *
18  * You should have received a copy of the GNU Lesser General Public
19  * License along with FFmpeg; if not, write to the Free Software
20  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
21  */
22
23 /**
24  * @file
25  * utils.
26  */
27
28 #include "libavutil/avassert.h"
29 #include "libavutil/avstring.h"
30 #include "libavutil/crc.h"
31 #include "libavutil/mathematics.h"
32 #include "libavutil/pixdesc.h"
33 #include "libavutil/audioconvert.h"
34 #include "libavutil/imgutils.h"
35 #include "libavutil/samplefmt.h"
36 #include "libavutil/dict.h"
37 #include "libavutil/avassert.h"
38 #include "avcodec.h"
39 #include "dsputil.h"
40 #include "libavutil/opt.h"
41 #include "imgconvert.h"
42 #include "thread.h"
43 #include "audioconvert.h"
44 #include "internal.h"
45 #include "bytestream.h"
46 #include <stdlib.h>
47 #include <stdarg.h>
48 #include <limits.h>
49 #include <float.h>
50
51 static int volatile entangled_thread_counter=0;
52 static int (*ff_lockmgr_cb)(void **mutex, enum AVLockOp op);
53 static void *codec_mutex;
54 static void *avformat_mutex;
55
56 void *av_fast_realloc(void *ptr, unsigned int *size, size_t min_size)
57 {
58     if(min_size < *size)
59         return ptr;
60
61     min_size= FFMAX(17*min_size/16 + 32, min_size);
62
63     ptr= av_realloc(ptr, min_size);
64     if(!ptr) //we could set this to the unmodified min_size but this is safer if the user lost the ptr and uses NULL now
65         min_size= 0;
66
67     *size= min_size;
68
69     return ptr;
70 }
71
72 static inline int ff_fast_malloc(void *ptr, unsigned int *size, size_t min_size, int zero_realloc)
73 {
74     void **p = ptr;
75     if (min_size < *size)
76         return 0;
77     min_size= FFMAX(17*min_size/16 + 32, min_size);
78     av_free(*p);
79     *p = zero_realloc ? av_mallocz(min_size) : av_malloc(min_size);
80     if (!*p) min_size = 0;
81     *size= min_size;
82     return 1;
83 }
84
85 void av_fast_malloc(void *ptr, unsigned int *size, size_t min_size)
86 {
87     ff_fast_malloc(ptr, size, min_size, 0);
88 }
89
90 void av_fast_padded_malloc(void *ptr, unsigned int *size, size_t min_size)
91 {
92     uint8_t **p = ptr;
93     if (min_size > SIZE_MAX - FF_INPUT_BUFFER_PADDING_SIZE) {
94         av_freep(p);
95         *size = 0;
96         return;
97     }
98     if (!ff_fast_malloc(p, size, min_size + FF_INPUT_BUFFER_PADDING_SIZE, 1))
99         memset(*p + min_size, 0, FF_INPUT_BUFFER_PADDING_SIZE);
100 }
101
102 /* encoder management */
103 static AVCodec *first_avcodec = NULL;
104
105 AVCodec *av_codec_next(AVCodec *c){
106     if(c) return c->next;
107     else  return first_avcodec;
108 }
109
110 static void avcodec_init(void)
111 {
112     static int initialized = 0;
113
114     if (initialized != 0)
115         return;
116     initialized = 1;
117
118     ff_dsputil_static_init();
119 }
120
121 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) || s->pix_fmt<0)
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     assert(s->pix_fmt == pic->format);
607
608     /* If internal buffer type return the same buffer */
609     if(pic->type == FF_BUFFER_TYPE_INTERNAL) {
610         return 0;
611     }
612
613     /*
614      * Not internal type and reget_buffer not overridden, emulate cr buffer
615      */
616     temp_pic = *pic;
617     for(i = 0; i < AV_NUM_DATA_POINTERS; i++)
618         pic->data[i] = pic->base[i] = NULL;
619     pic->opaque = NULL;
620     /* Allocate new frame */
621     if (s->get_buffer(s, pic))
622         return -1;
623     /* Copy image data from old buffer to new buffer */
624     av_picture_copy((AVPicture*)pic, (AVPicture*)&temp_pic, s->pix_fmt, s->width,
625              s->height);
626     s->release_buffer(s, &temp_pic); // Release old frame
627     return 0;
628 }
629
630 int avcodec_default_execute(AVCodecContext *c, int (*func)(AVCodecContext *c2, void *arg2),void *arg, int *ret, int count, int size){
631     int i;
632
633     for(i=0; i<count; i++){
634         int r= func(c, (char*)arg + i*size);
635         if(ret) ret[i]= r;
636     }
637     return 0;
638 }
639
640 int avcodec_default_execute2(AVCodecContext *c, int (*func)(AVCodecContext *c2, void *arg2, int jobnr, int threadnr),void *arg, int *ret, int count){
641     int i;
642
643     for(i=0; i<count; i++){
644         int r= func(c, arg, i, 0);
645         if(ret) ret[i]= r;
646     }
647     return 0;
648 }
649
650 enum PixelFormat avcodec_default_get_format(struct AVCodecContext *s, const enum PixelFormat *fmt){
651     while (*fmt != PIX_FMT_NONE && ff_is_hwaccel_pix_fmt(*fmt))
652         ++fmt;
653     return fmt[0];
654 }
655
656 void avcodec_get_frame_defaults(AVFrame *pic){
657     memset(pic, 0, sizeof(AVFrame));
658
659     pic->pts = pic->pkt_dts = pic->pkt_pts = pic->best_effort_timestamp = AV_NOPTS_VALUE;
660     pic->pkt_pos = -1;
661     pic->key_frame= 1;
662     pic->sample_aspect_ratio = (AVRational){0, 1};
663     pic->format = -1;           /* unknown */
664 }
665
666 AVFrame *avcodec_alloc_frame(void){
667     AVFrame *pic= av_malloc(sizeof(AVFrame));
668
669     if(pic==NULL) return NULL;
670
671     avcodec_get_frame_defaults(pic);
672
673     return pic;
674 }
675
676 static void avcodec_get_subtitle_defaults(AVSubtitle *sub)
677 {
678     memset(sub, 0, sizeof(*sub));
679     sub->pts = AV_NOPTS_VALUE;
680 }
681
682 static int get_bit_rate(AVCodecContext *ctx)
683 {
684     int bit_rate;
685     int bits_per_sample;
686
687     switch(ctx->codec_type) {
688     case AVMEDIA_TYPE_VIDEO:
689     case AVMEDIA_TYPE_DATA:
690     case AVMEDIA_TYPE_SUBTITLE:
691     case AVMEDIA_TYPE_ATTACHMENT:
692         bit_rate = ctx->bit_rate;
693         break;
694     case AVMEDIA_TYPE_AUDIO:
695         bits_per_sample = av_get_bits_per_sample(ctx->codec_id);
696         bit_rate = bits_per_sample ? ctx->sample_rate * ctx->channels * bits_per_sample : ctx->bit_rate;
697         break;
698     default:
699         bit_rate = 0;
700         break;
701     }
702     return bit_rate;
703 }
704
705 #if FF_API_AVCODEC_OPEN
706 int attribute_align_arg avcodec_open(AVCodecContext *avctx, AVCodec *codec)
707 {
708     return avcodec_open2(avctx, codec, NULL);
709 }
710 #endif
711
712 int attribute_align_arg avcodec_open2(AVCodecContext *avctx, AVCodec *codec, AVDictionary **options)
713 {
714     int ret = 0;
715     AVDictionary *tmp = NULL;
716
717     if (avcodec_is_open(avctx))
718         return 0;
719
720     if ((!codec && !avctx->codec)) {
721         av_log(avctx, AV_LOG_ERROR, "No codec provided to avcodec_open2().\n");
722         return AVERROR(EINVAL);
723     }
724     if ((codec && avctx->codec && codec != avctx->codec)) {
725         av_log(avctx, AV_LOG_ERROR, "This AVCodecContext was allocated for %s, "
726                "but %s passed to avcodec_open2().\n", avctx->codec->name, codec->name);
727         return AVERROR(EINVAL);
728     }
729     if (!codec)
730         codec = avctx->codec;
731
732     if (avctx->extradata_size < 0 || avctx->extradata_size >= FF_MAX_EXTRADATA_SIZE)
733         return AVERROR(EINVAL);
734
735     if (options)
736         av_dict_copy(&tmp, *options, 0);
737
738     /* If there is a user-supplied mutex locking routine, call it. */
739     if (ff_lockmgr_cb) {
740         if ((*ff_lockmgr_cb)(&codec_mutex, AV_LOCK_OBTAIN))
741             return -1;
742     }
743
744     entangled_thread_counter++;
745     if(entangled_thread_counter != 1){
746         av_log(avctx, AV_LOG_ERROR, "insufficient thread locking around avcodec_open/close()\n");
747         ret = -1;
748         goto end;
749     }
750
751     avctx->internal = av_mallocz(sizeof(AVCodecInternal));
752     if (!avctx->internal) {
753         ret = AVERROR(ENOMEM);
754         goto end;
755     }
756
757     if (codec->priv_data_size > 0) {
758       if(!avctx->priv_data){
759         avctx->priv_data = av_mallocz(codec->priv_data_size);
760         if (!avctx->priv_data) {
761             ret = AVERROR(ENOMEM);
762             goto end;
763         }
764         if (codec->priv_class) {
765             *(AVClass**)avctx->priv_data= codec->priv_class;
766             av_opt_set_defaults(avctx->priv_data);
767         }
768       }
769       if (codec->priv_class && (ret = av_opt_set_dict(avctx->priv_data, &tmp)) < 0)
770           goto free_and_end;
771     } else {
772         avctx->priv_data = NULL;
773     }
774     if ((ret = av_opt_set_dict(avctx, &tmp)) < 0)
775         goto free_and_end;
776
777     if (codec->capabilities & CODEC_CAP_EXPERIMENTAL)
778         if (avctx->strict_std_compliance > FF_COMPLIANCE_EXPERIMENTAL) {
779             av_log(avctx, AV_LOG_ERROR, "Codec is experimental but experimental codecs are not enabled, see -strict -2\n");
780             ret = -1;
781             goto free_and_end;
782         }
783
784     //We only call avcodec_set_dimensions() for non h264 codecs so as not to overwrite previously setup dimensions
785     if(!( avctx->coded_width && avctx->coded_height && avctx->width && avctx->height && avctx->codec_id == CODEC_ID_H264)){
786     if(avctx->coded_width && avctx->coded_height)
787         avcodec_set_dimensions(avctx, avctx->coded_width, avctx->coded_height);
788     else if(avctx->width && avctx->height)
789         avcodec_set_dimensions(avctx, avctx->width, avctx->height);
790     }
791
792     if ((avctx->coded_width || avctx->coded_height || avctx->width || avctx->height)
793         && (  av_image_check_size(avctx->coded_width, avctx->coded_height, 0, avctx) < 0
794            || av_image_check_size(avctx->width,       avctx->height,       0, avctx) < 0)) {
795         av_log(avctx, AV_LOG_WARNING, "ignoring invalid width/height values\n");
796         avcodec_set_dimensions(avctx, 0, 0);
797     }
798
799     /* if the decoder init function was already called previously,
800        free the already allocated subtitle_header before overwriting it */
801     if (codec_is_decoder(codec))
802         av_freep(&avctx->subtitle_header);
803
804 #define SANE_NB_CHANNELS 128U
805     if (avctx->channels > SANE_NB_CHANNELS) {
806         ret = AVERROR(EINVAL);
807         goto free_and_end;
808     }
809
810     avctx->codec = codec;
811     if ((avctx->codec_type == AVMEDIA_TYPE_UNKNOWN || avctx->codec_type == codec->type) &&
812         avctx->codec_id == CODEC_ID_NONE) {
813         avctx->codec_type = codec->type;
814         avctx->codec_id   = codec->id;
815     }
816     if (avctx->codec_id != codec->id || (avctx->codec_type != codec->type
817                            && avctx->codec_type != AVMEDIA_TYPE_ATTACHMENT)) {
818         av_log(avctx, AV_LOG_ERROR, "codec type or id mismatches\n");
819         ret = AVERROR(EINVAL);
820         goto free_and_end;
821     }
822     avctx->frame_number = 0;
823
824     if (avctx->codec_type == AVMEDIA_TYPE_AUDIO &&
825         (!avctx->time_base.num || !avctx->time_base.den)) {
826         avctx->time_base.num = 1;
827         avctx->time_base.den = avctx->sample_rate;
828     }
829
830     if (!HAVE_THREADS)
831         av_log(avctx, AV_LOG_WARNING, "Warning: not compiled with thread support, using thread emulation\n");
832
833     if (HAVE_THREADS && !avctx->thread_opaque) {
834         ret = ff_thread_init(avctx);
835         if (ret < 0) {
836             goto free_and_end;
837         }
838     }
839     if (!HAVE_THREADS && !(codec->capabilities & CODEC_CAP_AUTO_THREADS))
840         avctx->thread_count = 1;
841
842     if (avctx->codec->max_lowres < avctx->lowres || avctx->lowres < 0) {
843         av_log(avctx, AV_LOG_ERROR, "The maximum value for lowres supported by the decoder is %d\n",
844                avctx->codec->max_lowres);
845         ret = AVERROR(EINVAL);
846         goto free_and_end;
847     }
848     if (codec_is_encoder(avctx->codec)) {
849         int i;
850         if (avctx->codec->sample_fmts) {
851             for (i = 0; avctx->codec->sample_fmts[i] != AV_SAMPLE_FMT_NONE; i++)
852                 if (avctx->sample_fmt == avctx->codec->sample_fmts[i])
853                     break;
854             if (avctx->codec->sample_fmts[i] == AV_SAMPLE_FMT_NONE) {
855                 av_log(avctx, AV_LOG_ERROR, "Specified sample_fmt is not supported.\n");
856                 ret = AVERROR(EINVAL);
857                 goto free_and_end;
858             }
859         }
860         if (avctx->codec->pix_fmts) {
861             for (i = 0; avctx->codec->pix_fmts[i] != PIX_FMT_NONE; i++)
862                 if (avctx->pix_fmt == avctx->codec->pix_fmts[i])
863                     break;
864             if (avctx->codec->pix_fmts[i] == PIX_FMT_NONE) {
865                 av_log(avctx, AV_LOG_ERROR, "Specified pix_fmt is not supported\n");
866                 ret = AVERROR(EINVAL);
867                 goto free_and_end;
868             }
869         }
870         if (avctx->codec->supported_samplerates) {
871             for (i = 0; avctx->codec->supported_samplerates[i] != 0; i++)
872                 if (avctx->sample_rate == avctx->codec->supported_samplerates[i])
873                     break;
874             if (avctx->codec->supported_samplerates[i] == 0) {
875                 av_log(avctx, AV_LOG_ERROR, "Specified sample_rate is not supported\n");
876                 ret = AVERROR(EINVAL);
877                 goto free_and_end;
878             }
879         }
880         if (avctx->codec->channel_layouts) {
881             if (!avctx->channel_layout) {
882                 av_log(avctx, AV_LOG_WARNING, "channel_layout not specified\n");
883             } else {
884                 for (i = 0; avctx->codec->channel_layouts[i] != 0; i++)
885                     if (avctx->channel_layout == avctx->codec->channel_layouts[i])
886                         break;
887                 if (avctx->codec->channel_layouts[i] == 0) {
888                     av_log(avctx, AV_LOG_ERROR, "Specified channel_layout is not supported\n");
889                     ret = AVERROR(EINVAL);
890                     goto free_and_end;
891                 }
892             }
893         }
894         if (avctx->channel_layout && avctx->channels) {
895             if (av_get_channel_layout_nb_channels(avctx->channel_layout) != avctx->channels) {
896                 av_log(avctx, AV_LOG_ERROR, "channel layout does not match number of channels\n");
897                 ret = AVERROR(EINVAL);
898                 goto free_and_end;
899             }
900         } else if (avctx->channel_layout) {
901             avctx->channels = av_get_channel_layout_nb_channels(avctx->channel_layout);
902         }
903     }
904
905     avctx->pts_correction_num_faulty_pts =
906     avctx->pts_correction_num_faulty_dts = 0;
907     avctx->pts_correction_last_pts =
908     avctx->pts_correction_last_dts = INT64_MIN;
909
910     if(avctx->codec->init && !(avctx->active_thread_type&FF_THREAD_FRAME)){
911         ret = avctx->codec->init(avctx);
912         if (ret < 0) {
913             goto free_and_end;
914         }
915     }
916
917     if (codec_is_decoder(avctx->codec) && !avctx->bit_rate)
918         avctx->bit_rate = get_bit_rate(avctx);
919
920     ret=0;
921 end:
922     entangled_thread_counter--;
923
924     /* Release any user-supplied mutex. */
925     if (ff_lockmgr_cb) {
926         (*ff_lockmgr_cb)(&codec_mutex, AV_LOCK_RELEASE);
927     }
928     if (options) {
929         av_dict_free(options);
930         *options = tmp;
931     }
932
933     return ret;
934 free_and_end:
935     av_dict_free(&tmp);
936     av_freep(&avctx->priv_data);
937     av_freep(&avctx->internal);
938     avctx->codec= NULL;
939     goto end;
940 }
941
942 int ff_alloc_packet(AVPacket *avpkt, int size)
943 {
944     if (size > INT_MAX - FF_INPUT_BUFFER_PADDING_SIZE)
945         return AVERROR(EINVAL);
946
947     if (avpkt->data) {
948         uint8_t *pkt_data;
949
950         if (avpkt->size < size)
951             return AVERROR(EINVAL);
952
953         pkt_data = avpkt->data;
954         av_init_packet(avpkt);
955         avpkt->data = pkt_data;
956         avpkt->size = size;
957         return 0;
958     } else {
959         return av_new_packet(avpkt, size);
960     }
961 }
962
963 int attribute_align_arg avcodec_encode_audio2(AVCodecContext *avctx,
964                                               AVPacket *avpkt,
965                                               const AVFrame *frame,
966                                               int *got_packet_ptr)
967 {
968     int ret;
969     int user_packet = !!avpkt->data;
970     int nb_samples;
971
972     *got_packet_ptr = 0;
973
974     if (!(avctx->codec->capabilities & CODEC_CAP_DELAY) && !frame) {
975         av_init_packet(avpkt);
976         avpkt->size = 0;
977         return 0;
978     }
979
980     /* check for valid frame size */
981     if (frame) {
982         nb_samples = frame->nb_samples;
983         if (avctx->codec->capabilities & CODEC_CAP_SMALL_LAST_FRAME) {
984             if (nb_samples > avctx->frame_size)
985                 return AVERROR(EINVAL);
986         } else if (!(avctx->codec->capabilities & CODEC_CAP_VARIABLE_FRAME_SIZE)) {
987             if (nb_samples != avctx->frame_size)
988                 return AVERROR(EINVAL);
989         }
990     } else {
991         nb_samples = avctx->frame_size;
992     }
993
994     if (avctx->codec->encode2) {
995         ret = avctx->codec->encode2(avctx, avpkt, frame, got_packet_ptr);
996         if (!ret && *got_packet_ptr) {
997             if (!(avctx->codec->capabilities & CODEC_CAP_DELAY)) {
998                 if (avpkt->pts == AV_NOPTS_VALUE)
999                     avpkt->pts = frame->pts;
1000                 if (!avpkt->duration)
1001                     avpkt->duration = ff_samples_to_time_base(avctx,
1002                                                               frame->nb_samples);
1003             }
1004             avpkt->dts = avpkt->pts;
1005         } else {
1006             avpkt->size = 0;
1007         }
1008     } else {
1009         /* for compatibility with encoders not supporting encode2(), we need to
1010            allocate a packet buffer if the user has not provided one or check
1011            the size otherwise */
1012         int fs_tmp   = 0;
1013         int buf_size = avpkt->size;
1014         if (!user_packet) {
1015             if (avctx->codec->capabilities & CODEC_CAP_VARIABLE_FRAME_SIZE) {
1016                 av_assert0(av_get_bits_per_sample(avctx->codec_id) != 0);
1017                 if (!frame)
1018                     return AVERROR(EINVAL);
1019                 buf_size = nb_samples * avctx->channels *
1020                            av_get_bits_per_sample(avctx->codec_id) / 8;
1021             } else {
1022                 /* this is a guess as to the required size.
1023                    if an encoder needs more than this, it should probably
1024                    implement encode2() */
1025                 buf_size = 2 * avctx->frame_size * avctx->channels *
1026                            av_get_bytes_per_sample(avctx->sample_fmt);
1027                 buf_size += FF_MIN_BUFFER_SIZE;
1028             }
1029         }
1030         if ((ret = ff_alloc_packet(avpkt, buf_size)))
1031             return ret;
1032
1033         /* Encoders using AVCodec.encode() that support
1034            CODEC_CAP_SMALL_LAST_FRAME require avctx->frame_size to be set to
1035            the smaller size when encoding the last frame.
1036            This code can be removed once all encoders supporting
1037            CODEC_CAP_SMALL_LAST_FRAME use encode2() */
1038         if ((avctx->codec->capabilities & CODEC_CAP_SMALL_LAST_FRAME) &&
1039             nb_samples < avctx->frame_size) {
1040             fs_tmp = avctx->frame_size;
1041             avctx->frame_size = nb_samples;
1042         }
1043
1044         /* encode the frame */
1045         ret = avctx->codec->encode(avctx, avpkt->data, avpkt->size,
1046                                    frame ? frame->data[0] : NULL);
1047         if (ret >= 0) {
1048             if (!ret) {
1049                 /* no output. if the packet data was allocated by libavcodec,
1050                    free it */
1051                 if (!user_packet)
1052                     av_freep(&avpkt->data);
1053             } else {
1054                 if (avctx->coded_frame)
1055                     avpkt->pts = avpkt->dts = avctx->coded_frame->pts;
1056                 /* Set duration for final small packet. This can be removed
1057                    once all encoders supporting CODEC_CAP_SMALL_LAST_FRAME use
1058                    encode2() */
1059                 if (fs_tmp) {
1060                     avpkt->duration = ff_samples_to_time_base(avctx,
1061                                                               avctx->frame_size);
1062                 }
1063             }
1064             avpkt->size = ret;
1065             *got_packet_ptr = (ret > 0);
1066             ret = 0;
1067         }
1068
1069         if (fs_tmp)
1070             avctx->frame_size = fs_tmp;
1071     }
1072     if (!ret)
1073         avctx->frame_number++;
1074
1075     /* NOTE: if we add any audio encoders which output non-keyframe packets,
1076              this needs to be moved to the encoders, but for now we can do it
1077              here to simplify things */
1078     avpkt->flags |= AV_PKT_FLAG_KEY;
1079
1080     return ret;
1081 }
1082
1083 #if FF_API_OLD_DECODE_AUDIO
1084 int attribute_align_arg avcodec_encode_audio(AVCodecContext *avctx,
1085                                              uint8_t *buf, int buf_size,
1086                                              const short *samples)
1087 {
1088     AVPacket pkt;
1089     AVFrame frame0;
1090     AVFrame *frame;
1091     int ret, samples_size, got_packet;
1092
1093     av_init_packet(&pkt);
1094     pkt.data = buf;
1095     pkt.size = buf_size;
1096
1097     if (samples) {
1098         frame = &frame0;
1099         avcodec_get_frame_defaults(frame);
1100
1101         if (avctx->frame_size) {
1102             frame->nb_samples = avctx->frame_size;
1103         } else {
1104             /* if frame_size is not set, the number of samples must be
1105                calculated from the buffer size */
1106             int64_t nb_samples;
1107             if (!av_get_bits_per_sample(avctx->codec_id)) {
1108                 av_log(avctx, AV_LOG_ERROR, "avcodec_encode_audio() does not "
1109                        "support this codec\n");
1110                 return AVERROR(EINVAL);
1111             }
1112             nb_samples = (int64_t)buf_size * 8 /
1113                          (av_get_bits_per_sample(avctx->codec_id) *
1114                          avctx->channels);
1115             if (nb_samples >= INT_MAX)
1116                 return AVERROR(EINVAL);
1117             frame->nb_samples = nb_samples;
1118         }
1119
1120         /* it is assumed that the samples buffer is large enough based on the
1121            relevant parameters */
1122         samples_size = av_samples_get_buffer_size(NULL, avctx->channels,
1123                                                   frame->nb_samples,
1124                                                   avctx->sample_fmt, 1);
1125         if ((ret = avcodec_fill_audio_frame(frame, avctx->channels,
1126                                             avctx->sample_fmt,
1127                                             samples, samples_size, 1)))
1128             return ret;
1129
1130         /* fabricate frame pts from sample count.
1131            this is needed because the avcodec_encode_audio() API does not have
1132            a way for the user to provide pts */
1133         if(avctx->sample_rate && avctx->time_base.num)
1134             frame->pts = ff_samples_to_time_base(avctx,
1135                                                 avctx->internal->sample_count);
1136         else
1137             frame->pts = AV_NOPTS_VALUE;
1138         avctx->internal->sample_count += frame->nb_samples;
1139     } else {
1140         frame = NULL;
1141     }
1142
1143     got_packet = 0;
1144     ret = avcodec_encode_audio2(avctx, &pkt, frame, &got_packet);
1145     if (!ret && got_packet && avctx->coded_frame) {
1146         avctx->coded_frame->pts       = pkt.pts;
1147         avctx->coded_frame->key_frame = !!(pkt.flags & AV_PKT_FLAG_KEY);
1148     }
1149     /* free any side data since we cannot return it */
1150     ff_packet_free_side_data(&pkt);
1151
1152     if (frame && frame->extended_data != frame->data)
1153         av_freep(&frame->extended_data);
1154
1155     return ret ? ret : pkt.size;
1156 }
1157 #endif
1158
1159 #if FF_API_OLD_ENCODE_VIDEO
1160 int attribute_align_arg avcodec_encode_video(AVCodecContext *avctx, uint8_t *buf, int buf_size,
1161                          const AVFrame *pict)
1162 {
1163     AVPacket pkt;
1164     int ret, got_packet = 0;
1165
1166     if(buf_size < FF_MIN_BUFFER_SIZE){
1167         av_log(avctx, AV_LOG_ERROR, "buffer smaller than minimum size\n");
1168         return -1;
1169     }
1170
1171     av_init_packet(&pkt);
1172     pkt.data = buf;
1173     pkt.size = buf_size;
1174
1175     ret = avcodec_encode_video2(avctx, &pkt, pict, &got_packet);
1176     if (!ret && got_packet && avctx->coded_frame) {
1177         avctx->coded_frame->pts       = pkt.pts;
1178         avctx->coded_frame->key_frame = !!(pkt.flags & AV_PKT_FLAG_KEY);
1179     }
1180
1181     /* free any side data since we cannot return it */
1182     if (pkt.side_data_elems > 0) {
1183         int i;
1184         for (i = 0; i < pkt.side_data_elems; i++)
1185             av_free(pkt.side_data[i].data);
1186         av_freep(&pkt.side_data);
1187         pkt.side_data_elems = 0;
1188     }
1189
1190     return ret ? ret : pkt.size;
1191 }
1192 #endif
1193
1194 int attribute_align_arg avcodec_encode_video2(AVCodecContext *avctx,
1195                                               AVPacket *avpkt,
1196                                               const AVFrame *frame,
1197                                               int *got_packet_ptr)
1198 {
1199     int ret;
1200     int user_packet = !!avpkt->data;
1201     void *new_data;
1202
1203     *got_packet_ptr = 0;
1204
1205     if (!(avctx->codec->capabilities & CODEC_CAP_DELAY) && !frame) {
1206         av_init_packet(avpkt);
1207         avpkt->size     = 0;
1208         return 0;
1209     }
1210
1211     if (av_image_check_size(avctx->width, avctx->height, 0, avctx))
1212         return AVERROR(EINVAL);
1213
1214     av_assert0(avctx->codec->encode2);
1215
1216     ret = avctx->codec->encode2(avctx, avpkt, frame, got_packet_ptr);
1217     if (!ret) {
1218         if (!*got_packet_ptr)
1219             avpkt->size = 0;
1220         else if (!(avctx->codec->capabilities & CODEC_CAP_DELAY))
1221             avpkt->pts = avpkt->dts = frame->pts;
1222
1223         if (!user_packet && avpkt->data &&
1224             avpkt->destruct == av_destruct_packet) {
1225             uint8_t *new_data = av_realloc(avpkt->data, avpkt->size + FF_INPUT_BUFFER_PADDING_SIZE);
1226             if (new_data)
1227                 avpkt->data = new_data;
1228         }
1229
1230         avctx->frame_number++;
1231     }
1232
1233     emms_c();
1234     return ret;
1235 }
1236
1237 int avcodec_encode_subtitle(AVCodecContext *avctx, uint8_t *buf, int buf_size,
1238                             const AVSubtitle *sub)
1239 {
1240     int ret;
1241     if(sub->start_display_time) {
1242         av_log(avctx, AV_LOG_ERROR, "start_display_time must be 0.\n");
1243         return -1;
1244     }
1245
1246     ret = avctx->codec->encode(avctx, buf, buf_size, sub);
1247     avctx->frame_number++;
1248     return ret;
1249 }
1250
1251 /**
1252  * Attempt to guess proper monotonic timestamps for decoded video frames
1253  * which might have incorrect times. Input timestamps may wrap around, in
1254  * which case the output will as well.
1255  *
1256  * @param pts the pts field of the decoded AVPacket, as passed through
1257  * AVFrame.pkt_pts
1258  * @param dts the dts field of the decoded AVPacket
1259  * @return one of the input values, may be AV_NOPTS_VALUE
1260  */
1261 static int64_t guess_correct_pts(AVCodecContext *ctx,
1262                                  int64_t reordered_pts, int64_t dts)
1263 {
1264     int64_t pts = AV_NOPTS_VALUE;
1265
1266     if (dts != AV_NOPTS_VALUE) {
1267         ctx->pts_correction_num_faulty_dts += dts <= ctx->pts_correction_last_dts;
1268         ctx->pts_correction_last_dts = dts;
1269     }
1270     if (reordered_pts != AV_NOPTS_VALUE) {
1271         ctx->pts_correction_num_faulty_pts += reordered_pts <= ctx->pts_correction_last_pts;
1272         ctx->pts_correction_last_pts = reordered_pts;
1273     }
1274     if ((ctx->pts_correction_num_faulty_pts<=ctx->pts_correction_num_faulty_dts || dts == AV_NOPTS_VALUE)
1275        && reordered_pts != AV_NOPTS_VALUE)
1276         pts = reordered_pts;
1277     else
1278         pts = dts;
1279
1280     return pts;
1281 }
1282
1283 static void apply_param_change(AVCodecContext *avctx, AVPacket *avpkt)
1284 {
1285     int size = 0;
1286     const uint8_t *data;
1287     uint32_t flags;
1288
1289     if (!(avctx->codec->capabilities & CODEC_CAP_PARAM_CHANGE))
1290         return;
1291
1292     data = av_packet_get_side_data(avpkt, AV_PKT_DATA_PARAM_CHANGE, &size);
1293     if (!data || size < 4)
1294         return;
1295     flags = bytestream_get_le32(&data);
1296     size -= 4;
1297     if (size < 4) /* Required for any of the changes */
1298         return;
1299     if (flags & AV_SIDE_DATA_PARAM_CHANGE_CHANNEL_COUNT) {
1300         avctx->channels = bytestream_get_le32(&data);
1301         size -= 4;
1302     }
1303     if (flags & AV_SIDE_DATA_PARAM_CHANGE_CHANNEL_LAYOUT) {
1304         if (size < 8)
1305             return;
1306         avctx->channel_layout = bytestream_get_le64(&data);
1307         size -= 8;
1308     }
1309     if (size < 4)
1310         return;
1311     if (flags & AV_SIDE_DATA_PARAM_CHANGE_SAMPLE_RATE) {
1312         avctx->sample_rate = bytestream_get_le32(&data);
1313         size -= 4;
1314     }
1315     if (flags & AV_SIDE_DATA_PARAM_CHANGE_DIMENSIONS) {
1316         if (size < 8)
1317             return;
1318         avctx->width  = bytestream_get_le32(&data);
1319         avctx->height = bytestream_get_le32(&data);
1320         avcodec_set_dimensions(avctx, avctx->width, avctx->height);
1321         size -= 8;
1322     }
1323 }
1324
1325 int attribute_align_arg avcodec_decode_video2(AVCodecContext *avctx, AVFrame *picture,
1326                          int *got_picture_ptr,
1327                          const AVPacket *avpkt)
1328 {
1329     int ret;
1330     // copy to ensure we do not change avpkt
1331     AVPacket tmp = *avpkt;
1332
1333     *got_picture_ptr= 0;
1334     if((avctx->coded_width||avctx->coded_height) && av_image_check_size(avctx->coded_width, avctx->coded_height, 0, avctx))
1335         return -1;
1336
1337     if((avctx->codec->capabilities & CODEC_CAP_DELAY) || avpkt->size || (avctx->active_thread_type&FF_THREAD_FRAME)){
1338         int did_split = av_packet_split_side_data(&tmp);
1339         apply_param_change(avctx, &tmp);
1340         avctx->pkt = &tmp;
1341         if (HAVE_THREADS && avctx->active_thread_type&FF_THREAD_FRAME)
1342              ret = ff_thread_decode_frame(avctx, picture, got_picture_ptr,
1343                                           &tmp);
1344         else {
1345             ret = avctx->codec->decode(avctx, picture, got_picture_ptr,
1346                               &tmp);
1347             picture->pkt_dts= avpkt->dts;
1348
1349             if(!avctx->has_b_frames){
1350             picture->pkt_pos= avpkt->pos;
1351             }
1352             //FIXME these should be under if(!avctx->has_b_frames)
1353             if (!picture->sample_aspect_ratio.num)
1354                 picture->sample_aspect_ratio = avctx->sample_aspect_ratio;
1355             if (!picture->width)
1356                 picture->width = avctx->width;
1357             if (!picture->height)
1358                 picture->height = avctx->height;
1359             if (picture->format == PIX_FMT_NONE)
1360                 picture->format = avctx->pix_fmt;
1361         }
1362
1363         emms_c(); //needed to avoid an emms_c() call before every return;
1364
1365         avctx->pkt = NULL;
1366         if (did_split)
1367             ff_packet_free_side_data(&tmp);
1368
1369         if (*got_picture_ptr){
1370             avctx->frame_number++;
1371             picture->best_effort_timestamp = guess_correct_pts(avctx,
1372                                                             picture->pkt_pts,
1373                                                             picture->pkt_dts);
1374         }
1375     }else
1376         ret= 0;
1377
1378     return ret;
1379 }
1380
1381 #if FF_API_OLD_DECODE_AUDIO
1382 int attribute_align_arg avcodec_decode_audio3(AVCodecContext *avctx, int16_t *samples,
1383                          int *frame_size_ptr,
1384                          AVPacket *avpkt)
1385 {
1386     AVFrame frame;
1387     int ret, got_frame = 0;
1388
1389     if (avctx->get_buffer != avcodec_default_get_buffer) {
1390         av_log(avctx, AV_LOG_ERROR, "Custom get_buffer() for use with"
1391                "avcodec_decode_audio3() detected. Overriding with avcodec_default_get_buffer\n");
1392         av_log(avctx, AV_LOG_ERROR, "Please port your application to "
1393                "avcodec_decode_audio4()\n");
1394         avctx->get_buffer = avcodec_default_get_buffer;
1395         avctx->release_buffer = avcodec_default_release_buffer;
1396     }
1397
1398     ret = avcodec_decode_audio4(avctx, &frame, &got_frame, avpkt);
1399
1400     if (ret >= 0 && got_frame) {
1401         int ch, plane_size;
1402         int planar = av_sample_fmt_is_planar(avctx->sample_fmt);
1403         int data_size = av_samples_get_buffer_size(&plane_size, avctx->channels,
1404                                                    frame.nb_samples,
1405                                                    avctx->sample_fmt, 1);
1406         if (*frame_size_ptr < data_size) {
1407             av_log(avctx, AV_LOG_ERROR, "output buffer size is too small for "
1408                    "the current frame (%d < %d)\n", *frame_size_ptr, data_size);
1409             return AVERROR(EINVAL);
1410         }
1411
1412         memcpy(samples, frame.extended_data[0], plane_size);
1413
1414         if (planar && avctx->channels > 1) {
1415             uint8_t *out = ((uint8_t *)samples) + plane_size;
1416             for (ch = 1; ch < avctx->channels; ch++) {
1417                 memcpy(out, frame.extended_data[ch], plane_size);
1418                 out += plane_size;
1419             }
1420         }
1421         *frame_size_ptr = data_size;
1422     } else {
1423         *frame_size_ptr = 0;
1424     }
1425     return ret;
1426 }
1427 #endif
1428
1429 int attribute_align_arg avcodec_decode_audio4(AVCodecContext *avctx,
1430                                               AVFrame *frame,
1431                                               int *got_frame_ptr,
1432                                               AVPacket *avpkt)
1433 {
1434     int ret = 0;
1435
1436     *got_frame_ptr = 0;
1437
1438     if (!avpkt->data && avpkt->size) {
1439         av_log(avctx, AV_LOG_ERROR, "invalid packet: NULL data, size != 0\n");
1440         return AVERROR(EINVAL);
1441     }
1442
1443     if ((avctx->codec->capabilities & CODEC_CAP_DELAY) || avpkt->size) {
1444         av_packet_split_side_data(avpkt);
1445         apply_param_change(avctx, avpkt);
1446
1447         avctx->pkt = avpkt;
1448         ret = avctx->codec->decode(avctx, frame, got_frame_ptr, avpkt);
1449         if (ret >= 0 && *got_frame_ptr) {
1450             avctx->frame_number++;
1451             frame->pkt_dts = avpkt->dts;
1452             if (frame->format == AV_SAMPLE_FMT_NONE)
1453                 frame->format = avctx->sample_fmt;
1454         }
1455     }
1456     return ret;
1457 }
1458
1459 int avcodec_decode_subtitle2(AVCodecContext *avctx, AVSubtitle *sub,
1460                             int *got_sub_ptr,
1461                             AVPacket *avpkt)
1462 {
1463     int ret;
1464
1465     avctx->pkt = avpkt;
1466     *got_sub_ptr = 0;
1467     avcodec_get_subtitle_defaults(sub);
1468     ret = avctx->codec->decode(avctx, sub, got_sub_ptr, avpkt);
1469     if (*got_sub_ptr)
1470         avctx->frame_number++;
1471     return ret;
1472 }
1473
1474 void avsubtitle_free(AVSubtitle *sub)
1475 {
1476     int i;
1477
1478     for (i = 0; i < sub->num_rects; i++)
1479     {
1480         av_freep(&sub->rects[i]->pict.data[0]);
1481         av_freep(&sub->rects[i]->pict.data[1]);
1482         av_freep(&sub->rects[i]->pict.data[2]);
1483         av_freep(&sub->rects[i]->pict.data[3]);
1484         av_freep(&sub->rects[i]->text);
1485         av_freep(&sub->rects[i]->ass);
1486         av_freep(&sub->rects[i]);
1487     }
1488
1489     av_freep(&sub->rects);
1490
1491     memset(sub, 0, sizeof(AVSubtitle));
1492 }
1493
1494 av_cold int avcodec_close(AVCodecContext *avctx)
1495 {
1496     /* If there is a user-supplied mutex locking routine, call it. */
1497     if (ff_lockmgr_cb) {
1498         if ((*ff_lockmgr_cb)(&codec_mutex, AV_LOCK_OBTAIN))
1499             return -1;
1500     }
1501
1502     entangled_thread_counter++;
1503     if(entangled_thread_counter != 1){
1504         av_log(avctx, AV_LOG_ERROR, "insufficient thread locking around avcodec_open/close()\n");
1505         entangled_thread_counter--;
1506         return -1;
1507     }
1508
1509     if (avcodec_is_open(avctx)) {
1510         if (HAVE_THREADS && avctx->thread_opaque)
1511             ff_thread_free(avctx);
1512         if (avctx->codec && avctx->codec->close)
1513             avctx->codec->close(avctx);
1514         avcodec_default_free_buffers(avctx);
1515         avctx->coded_frame = NULL;
1516         av_freep(&avctx->internal);
1517     }
1518
1519     if (avctx->priv_data && avctx->codec && avctx->codec->priv_class)
1520         av_opt_free(avctx->priv_data);
1521     av_opt_free(avctx);
1522     av_freep(&avctx->priv_data);
1523     if (codec_is_encoder(avctx->codec))
1524         av_freep(&avctx->extradata);
1525     avctx->codec = NULL;
1526     avctx->active_thread_type = 0;
1527     entangled_thread_counter--;
1528
1529     /* Release any user-supplied mutex. */
1530     if (ff_lockmgr_cb) {
1531         (*ff_lockmgr_cb)(&codec_mutex, AV_LOCK_RELEASE);
1532     }
1533     return 0;
1534 }
1535
1536 static enum CodecID remap_deprecated_codec_id(enum CodecID id)
1537 {
1538     switch(id){
1539         //This is for future deprecatec codec ids, its empty since
1540         //last major bump but will fill up again over time, please dont remove it
1541 //         case CODEC_ID_UTVIDEO_DEPRECATED: return CODEC_ID_UTVIDEO;
1542         default                         : return id;
1543     }
1544 }
1545
1546 AVCodec *avcodec_find_encoder(enum CodecID id)
1547 {
1548     AVCodec *p, *experimental=NULL;
1549     p = first_avcodec;
1550     id= remap_deprecated_codec_id(id);
1551     while (p) {
1552         if (codec_is_encoder(p) && p->id == id) {
1553             if (p->capabilities & CODEC_CAP_EXPERIMENTAL && !experimental) {
1554                 experimental = p;
1555             } else
1556                 return p;
1557         }
1558         p = p->next;
1559     }
1560     return experimental;
1561 }
1562
1563 AVCodec *avcodec_find_encoder_by_name(const char *name)
1564 {
1565     AVCodec *p;
1566     if (!name)
1567         return NULL;
1568     p = first_avcodec;
1569     while (p) {
1570         if (codec_is_encoder(p) && strcmp(name,p->name) == 0)
1571             return p;
1572         p = p->next;
1573     }
1574     return NULL;
1575 }
1576
1577 AVCodec *avcodec_find_decoder(enum CodecID id)
1578 {
1579     AVCodec *p, *experimental=NULL;
1580     p = first_avcodec;
1581     id= remap_deprecated_codec_id(id);
1582     while (p) {
1583         if (codec_is_decoder(p) && p->id == id) {
1584             if (p->capabilities & CODEC_CAP_EXPERIMENTAL && !experimental) {
1585                 experimental = p;
1586             } else
1587                 return p;
1588         }
1589         p = p->next;
1590     }
1591     return experimental;
1592 }
1593
1594 AVCodec *avcodec_find_decoder_by_name(const char *name)
1595 {
1596     AVCodec *p;
1597     if (!name)
1598         return NULL;
1599     p = first_avcodec;
1600     while (p) {
1601         if (codec_is_decoder(p) && strcmp(name,p->name) == 0)
1602             return p;
1603         p = p->next;
1604     }
1605     return NULL;
1606 }
1607
1608 const char *avcodec_get_name(enum CodecID id)
1609 {
1610     AVCodec *codec;
1611
1612 #if !CONFIG_SMALL
1613     switch (id) {
1614 #include "libavcodec/codec_names.h"
1615     }
1616     av_log(NULL, AV_LOG_WARNING, "Codec 0x%x is not in the full list.\n", id);
1617 #endif
1618     codec = avcodec_find_decoder(id);
1619     if (codec)
1620         return codec->name;
1621     codec = avcodec_find_encoder(id);
1622     if (codec)
1623         return codec->name;
1624     return "unknown_codec";
1625 }
1626
1627 size_t av_get_codec_tag_string(char *buf, size_t buf_size, unsigned int codec_tag)
1628 {
1629     int i, len, ret = 0;
1630
1631     for (i = 0; i < 4; i++) {
1632         len = snprintf(buf, buf_size,
1633                        isprint(codec_tag&0xFF) ? "%c" : "[%d]", codec_tag&0xFF);
1634         buf      += len;
1635         buf_size  = buf_size > len ? buf_size - len : 0;
1636         ret      += len;
1637         codec_tag>>=8;
1638     }
1639     return ret;
1640 }
1641
1642 void avcodec_string(char *buf, int buf_size, AVCodecContext *enc, int encode)
1643 {
1644     const char *codec_type;
1645     const char *codec_name;
1646     const char *profile = NULL;
1647     AVCodec *p;
1648     int bitrate;
1649     AVRational display_aspect_ratio;
1650
1651     if (!buf || buf_size <= 0)
1652         return;
1653     codec_type = av_get_media_type_string(enc->codec_type);
1654     codec_name = avcodec_get_name(enc->codec_id);
1655     if (enc->profile != FF_PROFILE_UNKNOWN) {
1656         p = encode ? avcodec_find_encoder(enc->codec_id) :
1657                      avcodec_find_decoder(enc->codec_id);
1658         if (p)
1659             profile = av_get_profile_name(p, enc->profile);
1660     }
1661
1662     snprintf(buf, buf_size, "%s: %s%s", codec_type ? codec_type : "unknown",
1663              codec_name, enc->mb_decision ? " (hq)" : "");
1664     buf[0] ^= 'a' ^ 'A'; /* first letter in uppercase */
1665     if (profile)
1666         snprintf(buf + strlen(buf), buf_size - strlen(buf), " (%s)", profile);
1667     if (enc->codec_tag) {
1668         char tag_buf[32];
1669         av_get_codec_tag_string(tag_buf, sizeof(tag_buf), enc->codec_tag);
1670         snprintf(buf + strlen(buf), buf_size - strlen(buf),
1671                  " (%s / 0x%04X)", tag_buf, enc->codec_tag);
1672     }
1673     switch(enc->codec_type) {
1674     case AVMEDIA_TYPE_VIDEO:
1675         if (enc->pix_fmt != PIX_FMT_NONE) {
1676             snprintf(buf + strlen(buf), buf_size - strlen(buf),
1677                      ", %s",
1678                      av_get_pix_fmt_name(enc->pix_fmt));
1679         }
1680         if (enc->width) {
1681             snprintf(buf + strlen(buf), buf_size - strlen(buf),
1682                      ", %dx%d",
1683                      enc->width, enc->height);
1684             if (enc->sample_aspect_ratio.num) {
1685                 av_reduce(&display_aspect_ratio.num, &display_aspect_ratio.den,
1686                           enc->width*enc->sample_aspect_ratio.num,
1687                           enc->height*enc->sample_aspect_ratio.den,
1688                           1024*1024);
1689                 snprintf(buf + strlen(buf), buf_size - strlen(buf),
1690                          " [SAR %d:%d DAR %d:%d]",
1691                          enc->sample_aspect_ratio.num, enc->sample_aspect_ratio.den,
1692                          display_aspect_ratio.num, display_aspect_ratio.den);
1693             }
1694             if(av_log_get_level() >= AV_LOG_DEBUG){
1695                 int g= av_gcd(enc->time_base.num, enc->time_base.den);
1696                 snprintf(buf + strlen(buf), buf_size - strlen(buf),
1697                      ", %d/%d",
1698                      enc->time_base.num/g, enc->time_base.den/g);
1699             }
1700         }
1701         if (encode) {
1702             snprintf(buf + strlen(buf), buf_size - strlen(buf),
1703                      ", q=%d-%d", enc->qmin, enc->qmax);
1704         }
1705         break;
1706     case AVMEDIA_TYPE_AUDIO:
1707         if (enc->sample_rate) {
1708             snprintf(buf + strlen(buf), buf_size - strlen(buf),
1709                      ", %d Hz", enc->sample_rate);
1710         }
1711         av_strlcat(buf, ", ", buf_size);
1712         av_get_channel_layout_string(buf + strlen(buf), buf_size - strlen(buf), enc->channels, enc->channel_layout);
1713         if (enc->sample_fmt != AV_SAMPLE_FMT_NONE) {
1714             snprintf(buf + strlen(buf), buf_size - strlen(buf),
1715                      ", %s", av_get_sample_fmt_name(enc->sample_fmt));
1716         }
1717         break;
1718     default:
1719         return;
1720     }
1721     if (encode) {
1722         if (enc->flags & CODEC_FLAG_PASS1)
1723             snprintf(buf + strlen(buf), buf_size - strlen(buf),
1724                      ", pass 1");
1725         if (enc->flags & CODEC_FLAG_PASS2)
1726             snprintf(buf + strlen(buf), buf_size - strlen(buf),
1727                      ", pass 2");
1728     }
1729     bitrate = get_bit_rate(enc);
1730     if (bitrate != 0) {
1731         snprintf(buf + strlen(buf), buf_size - strlen(buf),
1732                  ", %d kb/s", bitrate / 1000);
1733     }
1734 }
1735
1736 const char *av_get_profile_name(const AVCodec *codec, int profile)
1737 {
1738     const AVProfile *p;
1739     if (profile == FF_PROFILE_UNKNOWN || !codec->profiles)
1740         return NULL;
1741
1742     for (p = codec->profiles; p->profile != FF_PROFILE_UNKNOWN; p++)
1743         if (p->profile == profile)
1744             return p->name;
1745
1746     return NULL;
1747 }
1748
1749 unsigned avcodec_version( void )
1750 {
1751 //    av_assert0(CODEC_ID_V410==164);
1752     av_assert0(CODEC_ID_PCM_S8_PLANAR==65563);
1753     av_assert0(CODEC_ID_ADPCM_G722==69660);
1754 //     av_assert0(CODEC_ID_BMV_AUDIO==86071);
1755     av_assert0(CODEC_ID_SRT==94216);
1756     av_assert0(LIBAVCODEC_VERSION_MICRO >= 100);
1757
1758   return LIBAVCODEC_VERSION_INT;
1759 }
1760
1761 const char *avcodec_configuration(void)
1762 {
1763     return FFMPEG_CONFIGURATION;
1764 }
1765
1766 const char *avcodec_license(void)
1767 {
1768 #define LICENSE_PREFIX "libavcodec license: "
1769     return LICENSE_PREFIX FFMPEG_LICENSE + sizeof(LICENSE_PREFIX) - 1;
1770 }
1771
1772 void avcodec_flush_buffers(AVCodecContext *avctx)
1773 {
1774     if(HAVE_THREADS && avctx->active_thread_type&FF_THREAD_FRAME)
1775         ff_thread_flush(avctx);
1776     else if(avctx->codec->flush)
1777         avctx->codec->flush(avctx);
1778 }
1779
1780 static void video_free_buffers(AVCodecContext *s)
1781 {
1782     AVCodecInternal *avci = s->internal;
1783     int i, j;
1784
1785     if (!avci->buffer)
1786         return;
1787
1788     if (avci->buffer_count)
1789         av_log(s, AV_LOG_WARNING, "Found %i unreleased buffers!\n",
1790                avci->buffer_count);
1791     for(i=0; i<INTERNAL_BUFFER_SIZE; i++){
1792         InternalBuffer *buf = &avci->buffer[i];
1793         for(j=0; j<4; j++){
1794             av_freep(&buf->base[j]);
1795             buf->data[j]= NULL;
1796         }
1797     }
1798     av_freep(&avci->buffer);
1799
1800     avci->buffer_count=0;
1801 }
1802
1803 static void audio_free_buffers(AVCodecContext *avctx)
1804 {
1805     AVCodecInternal *avci = avctx->internal;
1806     InternalBuffer *buf;
1807
1808     if (!avci->buffer)
1809         return;
1810     buf = avci->buffer;
1811
1812     if (buf->extended_data) {
1813         av_free(buf->extended_data[0]);
1814         if (buf->extended_data != buf->data)
1815             av_freep(&buf->extended_data);
1816     }
1817     av_freep(&avci->buffer);
1818 }
1819
1820 void avcodec_default_free_buffers(AVCodecContext *avctx)
1821 {
1822     switch (avctx->codec_type) {
1823     case AVMEDIA_TYPE_VIDEO:
1824         video_free_buffers(avctx);
1825         break;
1826     case AVMEDIA_TYPE_AUDIO:
1827         audio_free_buffers(avctx);
1828         break;
1829     default:
1830         break;
1831     }
1832 }
1833
1834 int av_get_bits_per_sample(enum CodecID codec_id){
1835     switch(codec_id){
1836     case CODEC_ID_ADPCM_SBPRO_2:
1837         return 2;
1838     case CODEC_ID_ADPCM_SBPRO_3:
1839         return 3;
1840     case CODEC_ID_ADPCM_SBPRO_4:
1841     case CODEC_ID_ADPCM_CT:
1842     case CODEC_ID_ADPCM_IMA_APC:
1843     case CODEC_ID_ADPCM_IMA_WAV:
1844     case CODEC_ID_ADPCM_IMA_QT:
1845     case CODEC_ID_ADPCM_SWF:
1846     case CODEC_ID_ADPCM_MS:
1847     case CODEC_ID_ADPCM_YAMAHA:
1848     case CODEC_ID_ADPCM_G722:
1849         return 4;
1850     case CODEC_ID_PCM_ALAW:
1851     case CODEC_ID_PCM_MULAW:
1852     case CODEC_ID_PCM_S8:
1853     case CODEC_ID_PCM_U8:
1854     case CODEC_ID_PCM_ZORK:
1855         return 8;
1856     case CODEC_ID_PCM_S16BE:
1857     case CODEC_ID_PCM_S16LE:
1858     case CODEC_ID_PCM_S16LE_PLANAR:
1859     case CODEC_ID_PCM_U16BE:
1860     case CODEC_ID_PCM_U16LE:
1861         return 16;
1862     case CODEC_ID_PCM_S24DAUD:
1863     case CODEC_ID_PCM_S24BE:
1864     case CODEC_ID_PCM_S24LE:
1865     case CODEC_ID_PCM_U24BE:
1866     case CODEC_ID_PCM_U24LE:
1867         return 24;
1868     case CODEC_ID_PCM_S32BE:
1869     case CODEC_ID_PCM_S32LE:
1870     case CODEC_ID_PCM_U32BE:
1871     case CODEC_ID_PCM_U32LE:
1872     case CODEC_ID_PCM_F32BE:
1873     case CODEC_ID_PCM_F32LE:
1874         return 32;
1875     case CODEC_ID_PCM_F64BE:
1876     case CODEC_ID_PCM_F64LE:
1877         return 64;
1878     default:
1879         return 0;
1880     }
1881 }
1882
1883 enum CodecID av_get_pcm_codec(enum AVSampleFormat fmt, int be)
1884 {
1885     static const enum CodecID map[AV_SAMPLE_FMT_NB][2] = {
1886         [AV_SAMPLE_FMT_U8  ] = { CODEC_ID_PCM_U8,    CODEC_ID_PCM_U8    },
1887         [AV_SAMPLE_FMT_S16 ] = { CODEC_ID_PCM_S16LE, CODEC_ID_PCM_S16BE },
1888         [AV_SAMPLE_FMT_S32 ] = { CODEC_ID_PCM_S32LE, CODEC_ID_PCM_S32BE },
1889         [AV_SAMPLE_FMT_FLT ] = { CODEC_ID_PCM_F32LE, CODEC_ID_PCM_F32BE },
1890         [AV_SAMPLE_FMT_DBL ] = { CODEC_ID_PCM_F64LE, CODEC_ID_PCM_F64BE },
1891         [AV_SAMPLE_FMT_U8P ] = { CODEC_ID_PCM_U8,    CODEC_ID_PCM_U8    },
1892         [AV_SAMPLE_FMT_S16P] = { CODEC_ID_PCM_S16LE, CODEC_ID_PCM_S16BE },
1893         [AV_SAMPLE_FMT_S32P] = { CODEC_ID_PCM_S32LE, CODEC_ID_PCM_S32BE },
1894         [AV_SAMPLE_FMT_FLTP] = { CODEC_ID_PCM_F32LE, CODEC_ID_PCM_F32BE },
1895         [AV_SAMPLE_FMT_DBLP] = { CODEC_ID_PCM_F64LE, CODEC_ID_PCM_F64BE },
1896     };
1897     if (fmt < 0 || fmt >= AV_SAMPLE_FMT_NB)
1898         return CODEC_ID_NONE;
1899     if (be < 0 || be > 1)
1900         be = AV_NE(1, 0);
1901     return map[fmt][be];
1902 }
1903
1904 #if !HAVE_THREADS
1905 int ff_thread_init(AVCodecContext *s){
1906     return -1;
1907 }
1908 #endif
1909
1910 unsigned int av_xiphlacing(unsigned char *s, unsigned int v)
1911 {
1912     unsigned int n = 0;
1913
1914     while(v >= 0xff) {
1915         *s++ = 0xff;
1916         v -= 0xff;
1917         n++;
1918     }
1919     *s = v;
1920     n++;
1921     return n;
1922 }
1923
1924 int ff_match_2uint16(const uint16_t (*tab)[2], int size, int a, int b){
1925     int i;
1926     for(i=0; i<size && !(tab[i][0]==a && tab[i][1]==b); i++);
1927     return i;
1928 }
1929
1930 void av_log_missing_feature(void *avc, const char *feature, int want_sample)
1931 {
1932     av_log(avc, AV_LOG_WARNING, "%s not implemented. Update your FFmpeg "
1933             "version to the newest one from Git. If the problem still "
1934             "occurs, it means that your file has a feature which has not "
1935             "been implemented.\n", feature);
1936     if(want_sample)
1937         av_log_ask_for_sample(avc, NULL);
1938 }
1939
1940 void av_log_ask_for_sample(void *avc, const char *msg, ...)
1941 {
1942     va_list argument_list;
1943
1944     va_start(argument_list, msg);
1945
1946     if (msg)
1947         av_vlog(avc, AV_LOG_WARNING, msg, argument_list);
1948     av_log(avc, AV_LOG_WARNING, "If you want to help, upload a sample "
1949             "of this file to ftp://upload.ffmpeg.org/MPlayer/incoming/ "
1950             "and contact the ffmpeg-devel mailing list.\n");
1951
1952     va_end(argument_list);
1953 }
1954
1955 static AVHWAccel *first_hwaccel = NULL;
1956
1957 void av_register_hwaccel(AVHWAccel *hwaccel)
1958 {
1959     AVHWAccel **p = &first_hwaccel;
1960     while (*p)
1961         p = &(*p)->next;
1962     *p = hwaccel;
1963     hwaccel->next = NULL;
1964 }
1965
1966 AVHWAccel *av_hwaccel_next(AVHWAccel *hwaccel)
1967 {
1968     return hwaccel ? hwaccel->next : first_hwaccel;
1969 }
1970
1971 AVHWAccel *ff_find_hwaccel(enum CodecID codec_id, enum PixelFormat pix_fmt)
1972 {
1973     AVHWAccel *hwaccel=NULL;
1974
1975     while((hwaccel= av_hwaccel_next(hwaccel))){
1976         if (   hwaccel->id      == codec_id
1977             && hwaccel->pix_fmt == pix_fmt)
1978             return hwaccel;
1979     }
1980     return NULL;
1981 }
1982
1983 int av_lockmgr_register(int (*cb)(void **mutex, enum AVLockOp op))
1984 {
1985     if (ff_lockmgr_cb) {
1986         if (ff_lockmgr_cb(&codec_mutex, AV_LOCK_DESTROY))
1987             return -1;
1988         if (ff_lockmgr_cb(&avformat_mutex, AV_LOCK_DESTROY))
1989             return -1;
1990     }
1991
1992     ff_lockmgr_cb = cb;
1993
1994     if (ff_lockmgr_cb) {
1995         if (ff_lockmgr_cb(&codec_mutex, AV_LOCK_CREATE))
1996             return -1;
1997         if (ff_lockmgr_cb(&avformat_mutex, AV_LOCK_CREATE))
1998             return -1;
1999     }
2000     return 0;
2001 }
2002
2003 int avpriv_lock_avformat(void)
2004 {
2005     if (ff_lockmgr_cb) {
2006         if ((*ff_lockmgr_cb)(&avformat_mutex, AV_LOCK_OBTAIN))
2007             return -1;
2008     }
2009     return 0;
2010 }
2011
2012 int avpriv_unlock_avformat(void)
2013 {
2014     if (ff_lockmgr_cb) {
2015         if ((*ff_lockmgr_cb)(&avformat_mutex, AV_LOCK_RELEASE))
2016             return -1;
2017     }
2018     return 0;
2019 }
2020
2021 unsigned int avpriv_toupper4(unsigned int x)
2022 {
2023     return     toupper( x     &0xFF)
2024             + (toupper((x>>8 )&0xFF)<<8 )
2025             + (toupper((x>>16)&0xFF)<<16)
2026             + (toupper((x>>24)&0xFF)<<24);
2027 }
2028
2029 #if !HAVE_THREADS
2030
2031 int ff_thread_get_buffer(AVCodecContext *avctx, AVFrame *f)
2032 {
2033     f->owner = avctx;
2034
2035     ff_init_buffer_info(avctx, f);
2036
2037     return avctx->get_buffer(avctx, f);
2038 }
2039
2040 void ff_thread_release_buffer(AVCodecContext *avctx, AVFrame *f)
2041 {
2042     f->owner->release_buffer(f->owner, f);
2043 }
2044
2045 void ff_thread_finish_setup(AVCodecContext *avctx)
2046 {
2047 }
2048
2049 void ff_thread_report_progress(AVFrame *f, int progress, int field)
2050 {
2051 }
2052
2053 void ff_thread_await_progress(AVFrame *f, int progress, int field)
2054 {
2055 }
2056
2057 #endif
2058
2059 enum AVMediaType avcodec_get_type(enum CodecID codec_id)
2060 {
2061     AVCodec *c= avcodec_find_decoder(codec_id);
2062     if(!c)
2063         c= avcodec_find_encoder(codec_id);
2064     if(c)
2065         return c->type;
2066
2067     if (codec_id <= CODEC_ID_NONE)
2068         return AVMEDIA_TYPE_UNKNOWN;
2069     else if (codec_id < CODEC_ID_FIRST_AUDIO)
2070         return AVMEDIA_TYPE_VIDEO;
2071     else if (codec_id < CODEC_ID_FIRST_SUBTITLE)
2072         return AVMEDIA_TYPE_AUDIO;
2073     else if (codec_id < CODEC_ID_FIRST_UNKNOWN)
2074         return AVMEDIA_TYPE_SUBTITLE;
2075
2076     return AVMEDIA_TYPE_UNKNOWN;
2077 }
2078
2079 int avcodec_is_open(AVCodecContext *s)
2080 {
2081     return !!s->internal;
2082 }