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