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