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