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