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