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