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