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