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