]> git.sesse.net Git - ffmpeg/blob - libavcodec/utils.c
Merge commit '0b300daad2f5cb59a7c06dde5ac701685e6edf16'
[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->flags&CODEC_FLAG_PASS1) && avctx->stats_out)
1470         avctx->stats_out[0] = '\0';
1471
1472     if (!(avctx->codec->capabilities & CODEC_CAP_DELAY) && !frame) {
1473         av_free_packet(avpkt);
1474         av_init_packet(avpkt);
1475         avpkt->size = 0;
1476         return 0;
1477     }
1478
1479     if (av_image_check_size(avctx->width, avctx->height, 0, avctx))
1480         return AVERROR(EINVAL);
1481
1482     av_assert0(avctx->codec->encode2);
1483
1484     ret = avctx->codec->encode2(avctx, avpkt, frame, got_packet_ptr);
1485     av_assert0(ret <= 0);
1486
1487     if (avpkt->data && avpkt->data == avctx->internal->byte_buffer) {
1488         needs_realloc = 0;
1489         if (user_pkt.data) {
1490             if (user_pkt.size >= avpkt->size) {
1491                 memcpy(user_pkt.data, avpkt->data, avpkt->size);
1492             } else {
1493                 av_log(avctx, AV_LOG_ERROR, "Provided packet is too small, needs to be %d\n", avpkt->size);
1494                 avpkt->size = user_pkt.size;
1495                 ret = -1;
1496             }
1497             avpkt->data     = user_pkt.data;
1498             avpkt->destruct = user_pkt.destruct;
1499         } else {
1500             if (av_dup_packet(avpkt) < 0) {
1501                 ret = AVERROR(ENOMEM);
1502             }
1503         }
1504     }
1505
1506     if (!ret) {
1507         if (!*got_packet_ptr)
1508             avpkt->size = 0;
1509         else if (!(avctx->codec->capabilities & CODEC_CAP_DELAY))
1510             avpkt->pts = avpkt->dts = frame->pts;
1511
1512         if (needs_realloc && avpkt->data &&
1513             avpkt->destruct == av_destruct_packet) {
1514             uint8_t *new_data = av_realloc(avpkt->data, avpkt->size + FF_INPUT_BUFFER_PADDING_SIZE);
1515             if (new_data)
1516                 avpkt->data = new_data;
1517         }
1518
1519         avctx->frame_number++;
1520     }
1521
1522     if (ret < 0 || !*got_packet_ptr)
1523         av_free_packet(avpkt);
1524
1525     emms_c();
1526     return ret;
1527 }
1528
1529 int avcodec_encode_subtitle(AVCodecContext *avctx, uint8_t *buf, int buf_size,
1530                             const AVSubtitle *sub)
1531 {
1532     int ret;
1533     if (sub->start_display_time) {
1534         av_log(avctx, AV_LOG_ERROR, "start_display_time must be 0.\n");
1535         return -1;
1536     }
1537
1538     ret = avctx->codec->encode_sub(avctx, buf, buf_size, sub);
1539     avctx->frame_number++;
1540     return ret;
1541 }
1542
1543 /**
1544  * Attempt to guess proper monotonic timestamps for decoded video frames
1545  * which might have incorrect times. Input timestamps may wrap around, in
1546  * which case the output will as well.
1547  *
1548  * @param pts the pts field of the decoded AVPacket, as passed through
1549  * AVFrame.pkt_pts
1550  * @param dts the dts field of the decoded AVPacket
1551  * @return one of the input values, may be AV_NOPTS_VALUE
1552  */
1553 static int64_t guess_correct_pts(AVCodecContext *ctx,
1554                                  int64_t reordered_pts, int64_t dts)
1555 {
1556     int64_t pts = AV_NOPTS_VALUE;
1557
1558     if (dts != AV_NOPTS_VALUE) {
1559         ctx->pts_correction_num_faulty_dts += dts <= ctx->pts_correction_last_dts;
1560         ctx->pts_correction_last_dts = dts;
1561     }
1562     if (reordered_pts != AV_NOPTS_VALUE) {
1563         ctx->pts_correction_num_faulty_pts += reordered_pts <= ctx->pts_correction_last_pts;
1564         ctx->pts_correction_last_pts = reordered_pts;
1565     }
1566     if ((ctx->pts_correction_num_faulty_pts<=ctx->pts_correction_num_faulty_dts || dts == AV_NOPTS_VALUE)
1567        && reordered_pts != AV_NOPTS_VALUE)
1568         pts = reordered_pts;
1569     else
1570         pts = dts;
1571
1572     return pts;
1573 }
1574
1575 static void apply_param_change(AVCodecContext *avctx, AVPacket *avpkt)
1576 {
1577     int size = 0;
1578     const uint8_t *data;
1579     uint32_t flags;
1580
1581     if (!(avctx->codec->capabilities & CODEC_CAP_PARAM_CHANGE))
1582         return;
1583
1584     data = av_packet_get_side_data(avpkt, AV_PKT_DATA_PARAM_CHANGE, &size);
1585     if (!data || size < 4)
1586         return;
1587     flags = bytestream_get_le32(&data);
1588     size -= 4;
1589     if (size < 4) /* Required for any of the changes */
1590         return;
1591     if (flags & AV_SIDE_DATA_PARAM_CHANGE_CHANNEL_COUNT) {
1592         avctx->channels = bytestream_get_le32(&data);
1593         size -= 4;
1594     }
1595     if (flags & AV_SIDE_DATA_PARAM_CHANGE_CHANNEL_LAYOUT) {
1596         if (size < 8)
1597             return;
1598         avctx->channel_layout = bytestream_get_le64(&data);
1599         size -= 8;
1600     }
1601     if (size < 4)
1602         return;
1603     if (flags & AV_SIDE_DATA_PARAM_CHANGE_SAMPLE_RATE) {
1604         avctx->sample_rate = bytestream_get_le32(&data);
1605         size -= 4;
1606     }
1607     if (flags & AV_SIDE_DATA_PARAM_CHANGE_DIMENSIONS) {
1608         if (size < 8)
1609             return;
1610         avctx->width  = bytestream_get_le32(&data);
1611         avctx->height = bytestream_get_le32(&data);
1612         avcodec_set_dimensions(avctx, avctx->width, avctx->height);
1613         size -= 8;
1614     }
1615 }
1616
1617 static int add_metadata_from_side_data(AVCodecContext *avctx, AVFrame *frame)
1618 {
1619     int size, ret = 0;
1620     const uint8_t *side_metadata;
1621     const uint8_t *end;
1622
1623     av_dict_free(&avctx->metadata);
1624     side_metadata = av_packet_get_side_data(avctx->pkt,
1625                                             AV_PKT_DATA_STRINGS_METADATA, &size);
1626     if (!side_metadata)
1627         goto end;
1628     end = side_metadata + size;
1629     while (side_metadata < end) {
1630         const uint8_t *key = side_metadata;
1631         const uint8_t *val = side_metadata + strlen(key) + 1;
1632         int ret = av_dict_set(&frame->metadata, key, val, 0);
1633         if (ret < 0)
1634             break;
1635         side_metadata = val + strlen(val) + 1;
1636     }
1637 end:
1638     avctx->metadata = frame->metadata;
1639     return ret;
1640 }
1641
1642 int attribute_align_arg avcodec_decode_video2(AVCodecContext *avctx, AVFrame *picture,
1643                                               int *got_picture_ptr,
1644                                               const AVPacket *avpkt)
1645 {
1646     int ret;
1647     // copy to ensure we do not change avpkt
1648     AVPacket tmp = *avpkt;
1649
1650     if (avctx->codec->type != AVMEDIA_TYPE_VIDEO) {
1651         av_log(avctx, AV_LOG_ERROR, "Invalid media type for video\n");
1652         return AVERROR(EINVAL);
1653     }
1654
1655     *got_picture_ptr = 0;
1656     if ((avctx->coded_width || avctx->coded_height) && av_image_check_size(avctx->coded_width, avctx->coded_height, 0, avctx))
1657         return AVERROR(EINVAL);
1658
1659     avcodec_get_frame_defaults(picture);
1660
1661     if ((avctx->codec->capabilities & CODEC_CAP_DELAY) || avpkt->size || (avctx->active_thread_type & FF_THREAD_FRAME)) {
1662         int did_split = av_packet_split_side_data(&tmp);
1663         apply_param_change(avctx, &tmp);
1664         avctx->pkt = &tmp;
1665         if (HAVE_THREADS && avctx->active_thread_type & FF_THREAD_FRAME)
1666             ret = ff_thread_decode_frame(avctx, picture, got_picture_ptr,
1667                                          &tmp);
1668         else {
1669             ret = avctx->codec->decode(avctx, picture, got_picture_ptr,
1670                                        &tmp);
1671             picture->pkt_dts             = avpkt->dts;
1672
1673             if(!avctx->has_b_frames){
1674                 picture->pkt_pos         = avpkt->pos;
1675             }
1676             //FIXME these should be under if(!avctx->has_b_frames)
1677             if (!picture->sample_aspect_ratio.num) picture->sample_aspect_ratio = avctx->sample_aspect_ratio;
1678             if (!picture->width)                   picture->width               = avctx->width;
1679             if (!picture->height)                  picture->height              = avctx->height;
1680             if (picture->format == AV_PIX_FMT_NONE)   picture->format              = avctx->pix_fmt;
1681         }
1682         add_metadata_from_side_data(avctx, picture);
1683
1684         emms_c(); //needed to avoid an emms_c() call before every return;
1685
1686         avctx->pkt = NULL;
1687         if (did_split) {
1688             ff_packet_free_side_data(&tmp);
1689             if(ret == tmp.size)
1690                 ret = avpkt->size;
1691         }
1692
1693         if (*got_picture_ptr){
1694             avctx->frame_number++;
1695             picture->best_effort_timestamp = guess_correct_pts(avctx,
1696                                                             picture->pkt_pts,
1697                                                             picture->pkt_dts);
1698         }
1699     } else
1700         ret = 0;
1701
1702     /* many decoders assign whole AVFrames, thus overwriting extended_data;
1703      * make sure it's set correctly */
1704     picture->extended_data = picture->data;
1705
1706     return ret;
1707 }
1708
1709 #if FF_API_OLD_DECODE_AUDIO
1710 int attribute_align_arg avcodec_decode_audio3(AVCodecContext *avctx, int16_t *samples,
1711                                               int *frame_size_ptr,
1712                                               AVPacket *avpkt)
1713 {
1714     AVFrame frame = {0};
1715     int ret, got_frame = 0;
1716
1717     if (avctx->get_buffer != avcodec_default_get_buffer) {
1718         av_log(avctx, AV_LOG_ERROR, "Custom get_buffer() for use with"
1719                                     "avcodec_decode_audio3() detected. Overriding with avcodec_default_get_buffer\n");
1720         av_log(avctx, AV_LOG_ERROR, "Please port your application to "
1721                                     "avcodec_decode_audio4()\n");
1722         avctx->get_buffer = avcodec_default_get_buffer;
1723         avctx->release_buffer = avcodec_default_release_buffer;
1724     }
1725
1726     ret = avcodec_decode_audio4(avctx, &frame, &got_frame, avpkt);
1727
1728     if (ret >= 0 && got_frame) {
1729         int ch, plane_size;
1730         int planar    = av_sample_fmt_is_planar(avctx->sample_fmt);
1731         int data_size = av_samples_get_buffer_size(&plane_size, avctx->channels,
1732                                                    frame.nb_samples,
1733                                                    avctx->sample_fmt, 1);
1734         if (*frame_size_ptr < data_size) {
1735             av_log(avctx, AV_LOG_ERROR, "output buffer size is too small for "
1736                                         "the current frame (%d < %d)\n", *frame_size_ptr, data_size);
1737             return AVERROR(EINVAL);
1738         }
1739
1740         memcpy(samples, frame.extended_data[0], plane_size);
1741
1742         if (planar && avctx->channels > 1) {
1743             uint8_t *out = ((uint8_t *)samples) + plane_size;
1744             for (ch = 1; ch < avctx->channels; ch++) {
1745                 memcpy(out, frame.extended_data[ch], plane_size);
1746                 out += plane_size;
1747             }
1748         }
1749         *frame_size_ptr = data_size;
1750     } else {
1751         *frame_size_ptr = 0;
1752     }
1753     return ret;
1754 }
1755
1756 #endif
1757
1758 int attribute_align_arg avcodec_decode_audio4(AVCodecContext *avctx,
1759                                               AVFrame *frame,
1760                                               int *got_frame_ptr,
1761                                               const AVPacket *avpkt)
1762 {
1763     int planar, channels;
1764     int ret = 0;
1765
1766     *got_frame_ptr = 0;
1767
1768     if (!avpkt->data && avpkt->size) {
1769         av_log(avctx, AV_LOG_ERROR, "invalid packet: NULL data, size != 0\n");
1770         return AVERROR(EINVAL);
1771     }
1772     if (avctx->codec->type != AVMEDIA_TYPE_AUDIO) {
1773         av_log(avctx, AV_LOG_ERROR, "Invalid media type for audio\n");
1774         return AVERROR(EINVAL);
1775     }
1776
1777     avcodec_get_frame_defaults(frame);
1778
1779     if ((avctx->codec->capabilities & CODEC_CAP_DELAY) || avpkt->size) {
1780         uint8_t *side;
1781         int side_size;
1782         // copy to ensure we do not change avpkt
1783         AVPacket tmp = *avpkt;
1784         int did_split = av_packet_split_side_data(&tmp);
1785         apply_param_change(avctx, &tmp);
1786
1787         avctx->pkt = &tmp;
1788         ret = avctx->codec->decode(avctx, frame, got_frame_ptr, &tmp);
1789         if (ret >= 0 && *got_frame_ptr) {
1790             avctx->frame_number++;
1791             frame->pkt_dts = avpkt->dts;
1792             frame->best_effort_timestamp = guess_correct_pts(avctx,
1793                                                              frame->pkt_pts,
1794                                                              frame->pkt_dts);
1795             if (frame->format == AV_SAMPLE_FMT_NONE)
1796                 frame->format = avctx->sample_fmt;
1797             if (!frame->channel_layout)
1798                 frame->channel_layout = avctx->channel_layout;
1799             if (!frame->channels)
1800                 frame->channels = avctx->channels;
1801             if (!frame->sample_rate)
1802                 frame->sample_rate = avctx->sample_rate;
1803         }
1804         add_metadata_from_side_data(avctx, frame);
1805
1806         side= av_packet_get_side_data(avctx->pkt, AV_PKT_DATA_SKIP_SAMPLES, &side_size);
1807         if(side && side_size>=10) {
1808             avctx->internal->skip_samples = AV_RL32(side);
1809             av_log(avctx, AV_LOG_DEBUG, "skip %d samples due to side data\n",
1810                    avctx->internal->skip_samples);
1811         }
1812         if (avctx->internal->skip_samples) {
1813             if(frame->nb_samples <= avctx->internal->skip_samples){
1814                 *got_frame_ptr = 0;
1815                 avctx->internal->skip_samples -= frame->nb_samples;
1816                 av_log(avctx, AV_LOG_DEBUG, "skip whole frame, skip left: %d\n",
1817                        avctx->internal->skip_samples);
1818             } else {
1819                 av_samples_copy(frame->extended_data, frame->extended_data, 0, avctx->internal->skip_samples,
1820                                 frame->nb_samples - avctx->internal->skip_samples, avctx->channels, frame->format);
1821                 if(avctx->pkt_timebase.num && avctx->sample_rate) {
1822                     int64_t diff_ts = av_rescale_q(avctx->internal->skip_samples,
1823                                                    (AVRational){1, avctx->sample_rate},
1824                                                    avctx->pkt_timebase);
1825                     if(frame->pkt_pts!=AV_NOPTS_VALUE)
1826                         frame->pkt_pts += diff_ts;
1827                     if(frame->pkt_dts!=AV_NOPTS_VALUE)
1828                         frame->pkt_dts += diff_ts;
1829                     if (frame->pkt_duration >= diff_ts)
1830                         frame->pkt_duration -= diff_ts;
1831                 } else {
1832                     av_log(avctx, AV_LOG_WARNING, "Could not update timestamps for skipped samples.\n");
1833                 }
1834                 av_log(avctx, AV_LOG_DEBUG, "skip %d/%d samples\n",
1835                        avctx->internal->skip_samples, frame->nb_samples);
1836                 frame->nb_samples -= avctx->internal->skip_samples;
1837                 avctx->internal->skip_samples = 0;
1838             }
1839         }
1840
1841         avctx->pkt = NULL;
1842         if (did_split) {
1843             ff_packet_free_side_data(&tmp);
1844             if(ret == tmp.size)
1845                 ret = avpkt->size;
1846         }
1847     }
1848
1849     /* many decoders assign whole AVFrames, thus overwriting extended_data;
1850      * make sure it's set correctly; assume decoders that actually use
1851      * extended_data are doing it correctly */
1852     if (*got_frame_ptr) {
1853         planar   = av_sample_fmt_is_planar(frame->format);
1854         channels = av_get_channel_layout_nb_channels(frame->channel_layout);
1855         if (!(planar && channels > AV_NUM_DATA_POINTERS))
1856             frame->extended_data = frame->data;
1857     } else {
1858         frame->extended_data = NULL;
1859     }
1860
1861     return ret;
1862 }
1863
1864 int avcodec_decode_subtitle2(AVCodecContext *avctx, AVSubtitle *sub,
1865                              int *got_sub_ptr,
1866                              AVPacket *avpkt)
1867 {
1868     int ret = 0;
1869
1870     if (avctx->codec->type != AVMEDIA_TYPE_SUBTITLE) {
1871         av_log(avctx, AV_LOG_ERROR, "Invalid media type for subtitles\n");
1872         return AVERROR(EINVAL);
1873     }
1874
1875     *got_sub_ptr = 0;
1876     avcodec_get_subtitle_defaults(sub);
1877
1878     if (avpkt->size) {
1879         AVPacket tmp = *avpkt;
1880         int did_split = av_packet_split_side_data(&tmp);
1881         //apply_param_change(avctx, &tmp);
1882
1883         avctx->pkt = &tmp;
1884
1885     if (avctx->pkt_timebase.den && avpkt->pts != AV_NOPTS_VALUE)
1886         sub->pts = av_rescale_q(avpkt->pts,
1887                                 avctx->pkt_timebase, AV_TIME_BASE_Q);
1888         ret = avctx->codec->decode(avctx, sub, got_sub_ptr, &tmp);
1889
1890         avctx->pkt = NULL;
1891         if (did_split) {
1892             ff_packet_free_side_data(&tmp);
1893             if(ret == tmp.size)
1894                 ret = avpkt->size;
1895         }
1896
1897     if (*got_sub_ptr)
1898         avctx->frame_number++;
1899     }
1900
1901     return ret;
1902 }
1903
1904 void avsubtitle_free(AVSubtitle *sub)
1905 {
1906     int i;
1907
1908     for (i = 0; i < sub->num_rects; i++) {
1909         av_freep(&sub->rects[i]->pict.data[0]);
1910         av_freep(&sub->rects[i]->pict.data[1]);
1911         av_freep(&sub->rects[i]->pict.data[2]);
1912         av_freep(&sub->rects[i]->pict.data[3]);
1913         av_freep(&sub->rects[i]->text);
1914         av_freep(&sub->rects[i]->ass);
1915         av_freep(&sub->rects[i]);
1916     }
1917
1918     av_freep(&sub->rects);
1919
1920     memset(sub, 0, sizeof(AVSubtitle));
1921 }
1922
1923 av_cold int ff_codec_close_recursive(AVCodecContext *avctx)
1924 {
1925     int ret = 0;
1926
1927     entangled_thread_counter--;
1928     /* Release any user-supplied mutex. */
1929     if (ff_lockmgr_cb) {
1930         (*ff_lockmgr_cb)(&codec_mutex, AV_LOCK_RELEASE);
1931     }
1932
1933     ret = avcodec_close(avctx);
1934
1935     /* If there is a user-supplied mutex locking routine, call it. */
1936     if (ff_lockmgr_cb) {
1937         if ((*ff_lockmgr_cb)(&codec_mutex, AV_LOCK_OBTAIN))
1938             return -1;
1939     }
1940     entangled_thread_counter++;
1941     return ret;
1942 }
1943
1944 av_cold int avcodec_close(AVCodecContext *avctx)
1945 {
1946     /* If there is a user-supplied mutex locking routine, call it. */
1947     if (ff_lockmgr_cb) {
1948         if ((*ff_lockmgr_cb)(&codec_mutex, AV_LOCK_OBTAIN))
1949             return -1;
1950     }
1951
1952     entangled_thread_counter++;
1953     if (entangled_thread_counter != 1) {
1954         av_log(avctx, AV_LOG_ERROR, "insufficient thread locking around avcodec_open/close()\n");
1955         entangled_thread_counter--;
1956         return -1;
1957     }
1958
1959     if (avcodec_is_open(avctx)) {
1960         if (HAVE_THREADS && avctx->internal->frame_thread_encoder && avctx->thread_count > 1) {
1961             entangled_thread_counter --;
1962             ff_frame_thread_encoder_free(avctx);
1963             entangled_thread_counter ++;
1964         }
1965         if (HAVE_THREADS && avctx->thread_opaque)
1966             ff_thread_free(avctx);
1967         if (avctx->codec && avctx->codec->close)
1968             avctx->codec->close(avctx);
1969         avcodec_default_free_buffers(avctx);
1970         avctx->coded_frame = NULL;
1971         avctx->internal->byte_buffer_size = 0;
1972         av_freep(&avctx->internal->byte_buffer);
1973         av_freep(&avctx->internal);
1974         av_dict_free(&avctx->metadata);
1975     }
1976
1977     if (avctx->priv_data && avctx->codec && avctx->codec->priv_class)
1978         av_opt_free(avctx->priv_data);
1979     av_opt_free(avctx);
1980     av_freep(&avctx->priv_data);
1981     if (av_codec_is_encoder(avctx->codec))
1982         av_freep(&avctx->extradata);
1983     avctx->codec = NULL;
1984     avctx->active_thread_type = 0;
1985     entangled_thread_counter--;
1986
1987     /* Release any user-supplied mutex. */
1988     if (ff_lockmgr_cb) {
1989         (*ff_lockmgr_cb)(&codec_mutex, AV_LOCK_RELEASE);
1990     }
1991     return 0;
1992 }
1993
1994 static enum AVCodecID remap_deprecated_codec_id(enum AVCodecID id)
1995 {
1996     switch(id){
1997         //This is for future deprecatec codec ids, its empty since
1998         //last major bump but will fill up again over time, please don't remove it
1999 //         case AV_CODEC_ID_UTVIDEO_DEPRECATED: return AV_CODEC_ID_UTVIDEO;
2000         case AV_CODEC_ID_OPUS_DEPRECATED: return AV_CODEC_ID_OPUS;
2001         default                         : return id;
2002     }
2003 }
2004
2005 static AVCodec *find_encdec(enum AVCodecID id, int encoder)
2006 {
2007     AVCodec *p, *experimental = NULL;
2008     p = first_avcodec;
2009     id= remap_deprecated_codec_id(id);
2010     while (p) {
2011         if ((encoder ? av_codec_is_encoder(p) : av_codec_is_decoder(p)) &&
2012             p->id == id) {
2013             if (p->capabilities & CODEC_CAP_EXPERIMENTAL && !experimental) {
2014                 experimental = p;
2015             } else
2016                 return p;
2017         }
2018         p = p->next;
2019     }
2020     return experimental;
2021 }
2022
2023 AVCodec *avcodec_find_encoder(enum AVCodecID id)
2024 {
2025     return find_encdec(id, 1);
2026 }
2027
2028 AVCodec *avcodec_find_encoder_by_name(const char *name)
2029 {
2030     AVCodec *p;
2031     if (!name)
2032         return NULL;
2033     p = first_avcodec;
2034     while (p) {
2035         if (av_codec_is_encoder(p) && strcmp(name, p->name) == 0)
2036             return p;
2037         p = p->next;
2038     }
2039     return NULL;
2040 }
2041
2042 AVCodec *avcodec_find_decoder(enum AVCodecID id)
2043 {
2044     return find_encdec(id, 0);
2045 }
2046
2047 AVCodec *avcodec_find_decoder_by_name(const char *name)
2048 {
2049     AVCodec *p;
2050     if (!name)
2051         return NULL;
2052     p = first_avcodec;
2053     while (p) {
2054         if (av_codec_is_decoder(p) && strcmp(name, p->name) == 0)
2055             return p;
2056         p = p->next;
2057     }
2058     return NULL;
2059 }
2060
2061 const char *avcodec_get_name(enum AVCodecID id)
2062 {
2063     const AVCodecDescriptor *cd;
2064     AVCodec *codec;
2065
2066     if (id == AV_CODEC_ID_NONE)
2067         return "none";
2068     cd = avcodec_descriptor_get(id);
2069     if (cd)
2070         return cd->name;
2071     av_log(NULL, AV_LOG_WARNING, "Codec 0x%x is not in the full list.\n", id);
2072     codec = avcodec_find_decoder(id);
2073     if (codec)
2074         return codec->name;
2075     codec = avcodec_find_encoder(id);
2076     if (codec)
2077         return codec->name;
2078     return "unknown_codec";
2079 }
2080
2081 size_t av_get_codec_tag_string(char *buf, size_t buf_size, unsigned int codec_tag)
2082 {
2083     int i, len, ret = 0;
2084
2085 #define IS_PRINT(x)                                               \
2086     (((x) >= '0' && (x) <= '9') ||                                \
2087      ((x) >= 'a' && (x) <= 'z') || ((x) >= 'A' && (x) <= 'Z') ||  \
2088      ((x) == '.' || (x) == ' ' || (x) == '-'))
2089
2090     for (i = 0; i < 4; i++) {
2091         len = snprintf(buf, buf_size,
2092                        IS_PRINT(codec_tag&0xFF) ? "%c" : "[%d]", codec_tag&0xFF);
2093         buf        += len;
2094         buf_size    = buf_size > len ? buf_size - len : 0;
2095         ret        += len;
2096         codec_tag >>= 8;
2097     }
2098     return ret;
2099 }
2100
2101 void avcodec_string(char *buf, int buf_size, AVCodecContext *enc, int encode)
2102 {
2103     const char *codec_type;
2104     const char *codec_name;
2105     const char *profile = NULL;
2106     const AVCodec *p;
2107     int bitrate;
2108     AVRational display_aspect_ratio;
2109
2110     if (!buf || buf_size <= 0)
2111         return;
2112     codec_type = av_get_media_type_string(enc->codec_type);
2113     codec_name = avcodec_get_name(enc->codec_id);
2114     if (enc->profile != FF_PROFILE_UNKNOWN) {
2115         if (enc->codec)
2116             p = enc->codec;
2117         else
2118             p = encode ? avcodec_find_encoder(enc->codec_id) :
2119                         avcodec_find_decoder(enc->codec_id);
2120         if (p)
2121             profile = av_get_profile_name(p, enc->profile);
2122     }
2123
2124     snprintf(buf, buf_size, "%s: %s%s", codec_type ? codec_type : "unknown",
2125              codec_name, enc->mb_decision ? " (hq)" : "");
2126     buf[0] ^= 'a' ^ 'A'; /* first letter in uppercase */
2127     if (profile)
2128         snprintf(buf + strlen(buf), buf_size - strlen(buf), " (%s)", profile);
2129     if (enc->codec_tag) {
2130         char tag_buf[32];
2131         av_get_codec_tag_string(tag_buf, sizeof(tag_buf), enc->codec_tag);
2132         snprintf(buf + strlen(buf), buf_size - strlen(buf),
2133                  " (%s / 0x%04X)", tag_buf, enc->codec_tag);
2134     }
2135
2136     switch (enc->codec_type) {
2137     case AVMEDIA_TYPE_VIDEO:
2138         if (enc->pix_fmt != AV_PIX_FMT_NONE) {
2139             snprintf(buf + strlen(buf), buf_size - strlen(buf),
2140                      ", %s",
2141                      av_get_pix_fmt_name(enc->pix_fmt));
2142         }
2143         if (enc->width) {
2144             snprintf(buf + strlen(buf), buf_size - strlen(buf),
2145                      ", %dx%d",
2146                      enc->width, enc->height);
2147             if (enc->sample_aspect_ratio.num) {
2148                 av_reduce(&display_aspect_ratio.num, &display_aspect_ratio.den,
2149                           enc->width * enc->sample_aspect_ratio.num,
2150                           enc->height * enc->sample_aspect_ratio.den,
2151                           1024 * 1024);
2152                 snprintf(buf + strlen(buf), buf_size - strlen(buf),
2153                          " [SAR %d:%d DAR %d:%d]",
2154                          enc->sample_aspect_ratio.num, enc->sample_aspect_ratio.den,
2155                          display_aspect_ratio.num, display_aspect_ratio.den);
2156             }
2157             if (av_log_get_level() >= AV_LOG_DEBUG) {
2158                 int g = av_gcd(enc->time_base.num, enc->time_base.den);
2159                 snprintf(buf + strlen(buf), buf_size - strlen(buf),
2160                          ", %d/%d",
2161                          enc->time_base.num / g, enc->time_base.den / g);
2162             }
2163         }
2164         if (encode) {
2165             snprintf(buf + strlen(buf), buf_size - strlen(buf),
2166                      ", q=%d-%d", enc->qmin, enc->qmax);
2167         }
2168         break;
2169     case AVMEDIA_TYPE_AUDIO:
2170         if (enc->sample_rate) {
2171             snprintf(buf + strlen(buf), buf_size - strlen(buf),
2172                      ", %d Hz", enc->sample_rate);
2173         }
2174         av_strlcat(buf, ", ", buf_size);
2175         av_get_channel_layout_string(buf + strlen(buf), buf_size - strlen(buf), enc->channels, enc->channel_layout);
2176         if (enc->sample_fmt != AV_SAMPLE_FMT_NONE) {
2177             snprintf(buf + strlen(buf), buf_size - strlen(buf),
2178                      ", %s", av_get_sample_fmt_name(enc->sample_fmt));
2179         }
2180         break;
2181     default:
2182         return;
2183     }
2184     if (encode) {
2185         if (enc->flags & CODEC_FLAG_PASS1)
2186             snprintf(buf + strlen(buf), buf_size - strlen(buf),
2187                      ", pass 1");
2188         if (enc->flags & CODEC_FLAG_PASS2)
2189             snprintf(buf + strlen(buf), buf_size - strlen(buf),
2190                      ", pass 2");
2191     }
2192     bitrate = get_bit_rate(enc);
2193     if (bitrate != 0) {
2194         snprintf(buf + strlen(buf), buf_size - strlen(buf),
2195                  ", %d kb/s", bitrate / 1000);
2196     }
2197 }
2198
2199 const char *av_get_profile_name(const AVCodec *codec, int profile)
2200 {
2201     const AVProfile *p;
2202     if (profile == FF_PROFILE_UNKNOWN || !codec->profiles)
2203         return NULL;
2204
2205     for (p = codec->profiles; p->profile != FF_PROFILE_UNKNOWN; p++)
2206         if (p->profile == profile)
2207             return p->name;
2208
2209     return NULL;
2210 }
2211
2212 unsigned avcodec_version(void)
2213 {
2214 //    av_assert0(AV_CODEC_ID_V410==164);
2215     av_assert0(AV_CODEC_ID_PCM_S8_PLANAR==65563);
2216     av_assert0(AV_CODEC_ID_ADPCM_G722==69660);
2217 //     av_assert0(AV_CODEC_ID_BMV_AUDIO==86071);
2218     av_assert0(AV_CODEC_ID_SRT==94216);
2219     av_assert0(LIBAVCODEC_VERSION_MICRO >= 100);
2220
2221     return LIBAVCODEC_VERSION_INT;
2222 }
2223
2224 const char *avcodec_configuration(void)
2225 {
2226     return FFMPEG_CONFIGURATION;
2227 }
2228
2229 const char *avcodec_license(void)
2230 {
2231 #define LICENSE_PREFIX "libavcodec license: "
2232     return LICENSE_PREFIX FFMPEG_LICENSE + sizeof(LICENSE_PREFIX) - 1;
2233 }
2234
2235 void avcodec_flush_buffers(AVCodecContext *avctx)
2236 {
2237     if (HAVE_THREADS && avctx->active_thread_type & FF_THREAD_FRAME)
2238         ff_thread_flush(avctx);
2239     else if (avctx->codec->flush)
2240         avctx->codec->flush(avctx);
2241
2242     avctx->pts_correction_last_pts =
2243     avctx->pts_correction_last_dts = INT64_MIN;
2244 }
2245
2246 static void video_free_buffers(AVCodecContext *s)
2247 {
2248     AVCodecInternal *avci = s->internal;
2249     int i, j;
2250
2251     if (!avci->buffer)
2252         return;
2253
2254     if (avci->buffer_count)
2255         av_log(s, AV_LOG_WARNING, "Found %i unreleased buffers!\n",
2256                avci->buffer_count);
2257     for (i = 0; i < INTERNAL_BUFFER_SIZE; i++) {
2258         InternalBuffer *buf = &avci->buffer[i];
2259         for (j = 0; j < 4; j++) {
2260             av_freep(&buf->base[j]);
2261             buf->data[j] = NULL;
2262         }
2263     }
2264     av_freep(&avci->buffer);
2265
2266     avci->buffer_count = 0;
2267 }
2268
2269 static void audio_free_buffers(AVCodecContext *avctx)
2270 {
2271     AVCodecInternal *avci = avctx->internal;
2272     InternalBuffer *buf;
2273
2274     if (!avci->buffer)
2275         return;
2276     buf = avci->buffer;
2277
2278     if (buf->extended_data) {
2279         av_free(buf->extended_data[0]);
2280         if (buf->extended_data != buf->data)
2281             av_freep(&buf->extended_data);
2282     }
2283     av_freep(&avci->buffer);
2284 }
2285
2286 void avcodec_default_free_buffers(AVCodecContext *avctx)
2287 {
2288     switch (avctx->codec_type) {
2289     case AVMEDIA_TYPE_VIDEO:
2290         video_free_buffers(avctx);
2291         break;
2292     case AVMEDIA_TYPE_AUDIO:
2293         audio_free_buffers(avctx);
2294         break;
2295     default:
2296         break;
2297     }
2298 }
2299
2300 int av_get_exact_bits_per_sample(enum AVCodecID codec_id)
2301 {
2302     switch (codec_id) {
2303     case AV_CODEC_ID_8SVX_EXP:
2304     case AV_CODEC_ID_8SVX_FIB:
2305     case AV_CODEC_ID_ADPCM_CT:
2306     case AV_CODEC_ID_ADPCM_IMA_APC:
2307     case AV_CODEC_ID_ADPCM_IMA_EA_SEAD:
2308     case AV_CODEC_ID_ADPCM_IMA_OKI:
2309     case AV_CODEC_ID_ADPCM_IMA_WS:
2310     case AV_CODEC_ID_ADPCM_G722:
2311     case AV_CODEC_ID_ADPCM_YAMAHA:
2312         return 4;
2313     case AV_CODEC_ID_PCM_ALAW:
2314     case AV_CODEC_ID_PCM_MULAW:
2315     case AV_CODEC_ID_PCM_S8:
2316     case AV_CODEC_ID_PCM_S8_PLANAR:
2317     case AV_CODEC_ID_PCM_U8:
2318     case AV_CODEC_ID_PCM_ZORK:
2319         return 8;
2320     case AV_CODEC_ID_PCM_S16BE:
2321     case AV_CODEC_ID_PCM_S16BE_PLANAR:
2322     case AV_CODEC_ID_PCM_S16LE:
2323     case AV_CODEC_ID_PCM_S16LE_PLANAR:
2324     case AV_CODEC_ID_PCM_U16BE:
2325     case AV_CODEC_ID_PCM_U16LE:
2326         return 16;
2327     case AV_CODEC_ID_PCM_S24DAUD:
2328     case AV_CODEC_ID_PCM_S24BE:
2329     case AV_CODEC_ID_PCM_S24LE:
2330     case AV_CODEC_ID_PCM_S24LE_PLANAR:
2331     case AV_CODEC_ID_PCM_U24BE:
2332     case AV_CODEC_ID_PCM_U24LE:
2333         return 24;
2334     case AV_CODEC_ID_PCM_S32BE:
2335     case AV_CODEC_ID_PCM_S32LE:
2336     case AV_CODEC_ID_PCM_S32LE_PLANAR:
2337     case AV_CODEC_ID_PCM_U32BE:
2338     case AV_CODEC_ID_PCM_U32LE:
2339     case AV_CODEC_ID_PCM_F32BE:
2340     case AV_CODEC_ID_PCM_F32LE:
2341         return 32;
2342     case AV_CODEC_ID_PCM_F64BE:
2343     case AV_CODEC_ID_PCM_F64LE:
2344         return 64;
2345     default:
2346         return 0;
2347     }
2348 }
2349
2350 enum AVCodecID av_get_pcm_codec(enum AVSampleFormat fmt, int be)
2351 {
2352     static const enum AVCodecID map[AV_SAMPLE_FMT_NB][2] = {
2353         [AV_SAMPLE_FMT_U8  ] = { AV_CODEC_ID_PCM_U8,    AV_CODEC_ID_PCM_U8    },
2354         [AV_SAMPLE_FMT_S16 ] = { AV_CODEC_ID_PCM_S16LE, AV_CODEC_ID_PCM_S16BE },
2355         [AV_SAMPLE_FMT_S32 ] = { AV_CODEC_ID_PCM_S32LE, AV_CODEC_ID_PCM_S32BE },
2356         [AV_SAMPLE_FMT_FLT ] = { AV_CODEC_ID_PCM_F32LE, AV_CODEC_ID_PCM_F32BE },
2357         [AV_SAMPLE_FMT_DBL ] = { AV_CODEC_ID_PCM_F64LE, AV_CODEC_ID_PCM_F64BE },
2358         [AV_SAMPLE_FMT_U8P ] = { AV_CODEC_ID_PCM_U8,    AV_CODEC_ID_PCM_U8    },
2359         [AV_SAMPLE_FMT_S16P] = { AV_CODEC_ID_PCM_S16LE, AV_CODEC_ID_PCM_S16BE },
2360         [AV_SAMPLE_FMT_S32P] = { AV_CODEC_ID_PCM_S32LE, AV_CODEC_ID_PCM_S32BE },
2361         [AV_SAMPLE_FMT_FLTP] = { AV_CODEC_ID_PCM_F32LE, AV_CODEC_ID_PCM_F32BE },
2362         [AV_SAMPLE_FMT_DBLP] = { AV_CODEC_ID_PCM_F64LE, AV_CODEC_ID_PCM_F64BE },
2363     };
2364     if (fmt < 0 || fmt >= AV_SAMPLE_FMT_NB)
2365         return AV_CODEC_ID_NONE;
2366     if (be < 0 || be > 1)
2367         be = AV_NE(1, 0);
2368     return map[fmt][be];
2369 }
2370
2371 int av_get_bits_per_sample(enum AVCodecID codec_id)
2372 {
2373     switch (codec_id) {
2374     case AV_CODEC_ID_ADPCM_SBPRO_2:
2375         return 2;
2376     case AV_CODEC_ID_ADPCM_SBPRO_3:
2377         return 3;
2378     case AV_CODEC_ID_ADPCM_SBPRO_4:
2379     case AV_CODEC_ID_ADPCM_IMA_WAV:
2380     case AV_CODEC_ID_ADPCM_IMA_QT:
2381     case AV_CODEC_ID_ADPCM_SWF:
2382     case AV_CODEC_ID_ADPCM_MS:
2383         return 4;
2384     default:
2385         return av_get_exact_bits_per_sample(codec_id);
2386     }
2387 }
2388
2389 int av_get_audio_frame_duration(AVCodecContext *avctx, int frame_bytes)
2390 {
2391     int id, sr, ch, ba, tag, bps;
2392
2393     id  = avctx->codec_id;
2394     sr  = avctx->sample_rate;
2395     ch  = avctx->channels;
2396     ba  = avctx->block_align;
2397     tag = avctx->codec_tag;
2398     bps = av_get_exact_bits_per_sample(avctx->codec_id);
2399
2400     /* codecs with an exact constant bits per sample */
2401     if (bps > 0 && ch > 0 && frame_bytes > 0 && ch < 32768 && bps < 32768)
2402         return (frame_bytes * 8LL) / (bps * ch);
2403     bps = avctx->bits_per_coded_sample;
2404
2405     /* codecs with a fixed packet duration */
2406     switch (id) {
2407     case AV_CODEC_ID_ADPCM_ADX:    return   32;
2408     case AV_CODEC_ID_ADPCM_IMA_QT: return   64;
2409     case AV_CODEC_ID_ADPCM_EA_XAS: return  128;
2410     case AV_CODEC_ID_AMR_NB:
2411     case AV_CODEC_ID_GSM:
2412     case AV_CODEC_ID_QCELP:
2413     case AV_CODEC_ID_RA_288:       return  160;
2414     case AV_CODEC_ID_AMR_WB:
2415     case AV_CODEC_ID_GSM_MS:       return  320;
2416     case AV_CODEC_ID_MP1:          return  384;
2417     case AV_CODEC_ID_ATRAC1:       return  512;
2418     case AV_CODEC_ID_ATRAC3:       return 1024;
2419     case AV_CODEC_ID_MP2:
2420     case AV_CODEC_ID_MUSEPACK7:    return 1152;
2421     case AV_CODEC_ID_AC3:          return 1536;
2422     }
2423
2424     if (sr > 0) {
2425         /* calc from sample rate */
2426         if (id == AV_CODEC_ID_TTA)
2427             return 256 * sr / 245;
2428
2429         if (ch > 0) {
2430             /* calc from sample rate and channels */
2431             if (id == AV_CODEC_ID_BINKAUDIO_DCT)
2432                 return (480 << (sr / 22050)) / ch;
2433         }
2434     }
2435
2436     if (ba > 0) {
2437         /* calc from block_align */
2438         if (id == AV_CODEC_ID_SIPR) {
2439             switch (ba) {
2440             case 20: return 160;
2441             case 19: return 144;
2442             case 29: return 288;
2443             case 37: return 480;
2444             }
2445         } else if (id == AV_CODEC_ID_ILBC) {
2446             switch (ba) {
2447             case 38: return 160;
2448             case 50: return 240;
2449             }
2450         }
2451     }
2452
2453     if (frame_bytes > 0) {
2454         /* calc from frame_bytes only */
2455         if (id == AV_CODEC_ID_TRUESPEECH)
2456             return 240 * (frame_bytes / 32);
2457         if (id == AV_CODEC_ID_NELLYMOSER)
2458             return 256 * (frame_bytes / 64);
2459         if (id == AV_CODEC_ID_RA_144)
2460             return 160 * (frame_bytes / 20);
2461         if (id == AV_CODEC_ID_G723_1)
2462             return 240 * (frame_bytes / 24);
2463
2464         if (bps > 0) {
2465             /* calc from frame_bytes and bits_per_coded_sample */
2466             if (id == AV_CODEC_ID_ADPCM_G726)
2467                 return frame_bytes * 8 / bps;
2468         }
2469
2470         if (ch > 0) {
2471             /* calc from frame_bytes and channels */
2472             switch (id) {
2473             case AV_CODEC_ID_ADPCM_AFC:
2474                 return frame_bytes / (9 * ch) * 16;
2475             case AV_CODEC_ID_ADPCM_4XM:
2476             case AV_CODEC_ID_ADPCM_IMA_ISS:
2477                 return (frame_bytes - 4 * ch) * 2 / ch;
2478             case AV_CODEC_ID_ADPCM_IMA_SMJPEG:
2479                 return (frame_bytes - 4) * 2 / ch;
2480             case AV_CODEC_ID_ADPCM_IMA_AMV:
2481                 return (frame_bytes - 8) * 2 / ch;
2482             case AV_CODEC_ID_ADPCM_XA:
2483                 return (frame_bytes / 128) * 224 / ch;
2484             case AV_CODEC_ID_INTERPLAY_DPCM:
2485                 return (frame_bytes - 6 - ch) / ch;
2486             case AV_CODEC_ID_ROQ_DPCM:
2487                 return (frame_bytes - 8) / ch;
2488             case AV_CODEC_ID_XAN_DPCM:
2489                 return (frame_bytes - 2 * ch) / ch;
2490             case AV_CODEC_ID_MACE3:
2491                 return 3 * frame_bytes / ch;
2492             case AV_CODEC_ID_MACE6:
2493                 return 6 * frame_bytes / ch;
2494             case AV_CODEC_ID_PCM_LXF:
2495                 return 2 * (frame_bytes / (5 * ch));
2496             case AV_CODEC_ID_IAC:
2497             case AV_CODEC_ID_IMC:
2498                 return 4 * frame_bytes / ch;
2499             }
2500
2501             if (tag) {
2502                 /* calc from frame_bytes, channels, and codec_tag */
2503                 if (id == AV_CODEC_ID_SOL_DPCM) {
2504                     if (tag == 3)
2505                         return frame_bytes / ch;
2506                     else
2507                         return frame_bytes * 2 / ch;
2508                 }
2509             }
2510
2511             if (ba > 0) {
2512                 /* calc from frame_bytes, channels, and block_align */
2513                 int blocks = frame_bytes / ba;
2514                 switch (avctx->codec_id) {
2515                 case AV_CODEC_ID_ADPCM_IMA_WAV:
2516                     return blocks * (1 + (ba - 4 * ch) / (4 * ch) * 8);
2517                 case AV_CODEC_ID_ADPCM_IMA_DK3:
2518                     return blocks * (((ba - 16) * 2 / 3 * 4) / ch);
2519                 case AV_CODEC_ID_ADPCM_IMA_DK4:
2520                     return blocks * (1 + (ba - 4 * ch) * 2 / ch);
2521                 case AV_CODEC_ID_ADPCM_MS:
2522                     return blocks * (2 + (ba - 7 * ch) * 2 / ch);
2523                 }
2524             }
2525
2526             if (bps > 0) {
2527                 /* calc from frame_bytes, channels, and bits_per_coded_sample */
2528                 switch (avctx->codec_id) {
2529                 case AV_CODEC_ID_PCM_DVD:
2530                     if(bps<4)
2531                         return 0;
2532                     return 2 * (frame_bytes / ((bps * 2 / 8) * ch));
2533                 case AV_CODEC_ID_PCM_BLURAY:
2534                     if(bps<4)
2535                         return 0;
2536                     return frame_bytes / ((FFALIGN(ch, 2) * bps) / 8);
2537                 case AV_CODEC_ID_S302M:
2538                     return 2 * (frame_bytes / ((bps + 4) / 4)) / ch;
2539                 }
2540             }
2541         }
2542     }
2543
2544     return 0;
2545 }
2546
2547 #if !HAVE_THREADS
2548 int ff_thread_init(AVCodecContext *s)
2549 {
2550     return -1;
2551 }
2552
2553 #endif
2554
2555 unsigned int av_xiphlacing(unsigned char *s, unsigned int v)
2556 {
2557     unsigned int n = 0;
2558
2559     while (v >= 0xff) {
2560         *s++ = 0xff;
2561         v -= 0xff;
2562         n++;
2563     }
2564     *s = v;
2565     n++;
2566     return n;
2567 }
2568
2569 int ff_match_2uint16(const uint16_t(*tab)[2], int size, int a, int b)
2570 {
2571     int i;
2572     for (i = 0; i < size && !(tab[i][0] == a && tab[i][1] == b); i++) ;
2573     return i;
2574 }
2575
2576 void av_log_missing_feature(void *avc, const char *feature, int want_sample)
2577 {
2578     av_log(avc, AV_LOG_WARNING, "%s is not implemented. Update your FFmpeg "
2579             "version to the newest one from Git. If the problem still "
2580             "occurs, it means that your file has a feature which has not "
2581             "been implemented.\n", feature);
2582     if(want_sample)
2583         av_log_ask_for_sample(avc, NULL);
2584 }
2585
2586 void av_log_ask_for_sample(void *avc, const char *msg, ...)
2587 {
2588     va_list argument_list;
2589
2590     va_start(argument_list, msg);
2591
2592     if (msg)
2593         av_vlog(avc, AV_LOG_WARNING, msg, argument_list);
2594     av_log(avc, AV_LOG_WARNING, "If you want to help, upload a sample "
2595             "of this file to ftp://upload.ffmpeg.org/MPlayer/incoming/ "
2596             "and contact the ffmpeg-devel mailing list.\n");
2597
2598     va_end(argument_list);
2599 }
2600
2601 static AVHWAccel *first_hwaccel = NULL;
2602
2603 void av_register_hwaccel(AVHWAccel *hwaccel)
2604 {
2605     AVHWAccel **p = &first_hwaccel;
2606     while (*p)
2607         p = &(*p)->next;
2608     *p = hwaccel;
2609     hwaccel->next = NULL;
2610 }
2611
2612 AVHWAccel *av_hwaccel_next(AVHWAccel *hwaccel)
2613 {
2614     return hwaccel ? hwaccel->next : first_hwaccel;
2615 }
2616
2617 AVHWAccel *ff_find_hwaccel(enum AVCodecID codec_id, enum AVPixelFormat pix_fmt)
2618 {
2619     AVHWAccel *hwaccel = NULL;
2620
2621     while ((hwaccel = av_hwaccel_next(hwaccel)))
2622         if (hwaccel->id == codec_id
2623             && hwaccel->pix_fmt == pix_fmt)
2624             return hwaccel;
2625     return NULL;
2626 }
2627
2628 int av_lockmgr_register(int (*cb)(void **mutex, enum AVLockOp op))
2629 {
2630     if (ff_lockmgr_cb) {
2631         if (ff_lockmgr_cb(&codec_mutex, AV_LOCK_DESTROY))
2632             return -1;
2633         if (ff_lockmgr_cb(&avformat_mutex, AV_LOCK_DESTROY))
2634             return -1;
2635     }
2636
2637     ff_lockmgr_cb = cb;
2638
2639     if (ff_lockmgr_cb) {
2640         if (ff_lockmgr_cb(&codec_mutex, AV_LOCK_CREATE))
2641             return -1;
2642         if (ff_lockmgr_cb(&avformat_mutex, AV_LOCK_CREATE))
2643             return -1;
2644     }
2645     return 0;
2646 }
2647
2648 int avpriv_lock_avformat(void)
2649 {
2650     if (ff_lockmgr_cb) {
2651         if ((*ff_lockmgr_cb)(&avformat_mutex, AV_LOCK_OBTAIN))
2652             return -1;
2653     }
2654     return 0;
2655 }
2656
2657 int avpriv_unlock_avformat(void)
2658 {
2659     if (ff_lockmgr_cb) {
2660         if ((*ff_lockmgr_cb)(&avformat_mutex, AV_LOCK_RELEASE))
2661             return -1;
2662     }
2663     return 0;
2664 }
2665
2666 unsigned int avpriv_toupper4(unsigned int x)
2667 {
2668     return toupper(x & 0xFF)
2669            + (toupper((x >> 8) & 0xFF) << 8)
2670            + (toupper((x >> 16) & 0xFF) << 16)
2671            + (toupper((x >> 24) & 0xFF) << 24);
2672 }
2673
2674 #if !HAVE_THREADS
2675
2676 int ff_thread_get_buffer(AVCodecContext *avctx, AVFrame *f)
2677 {
2678     f->owner = avctx;
2679
2680     ff_init_buffer_info(avctx, f);
2681
2682     return avctx->get_buffer(avctx, f);
2683 }
2684
2685 void ff_thread_release_buffer(AVCodecContext *avctx, AVFrame *f)
2686 {
2687     f->owner->release_buffer(f->owner, f);
2688 }
2689
2690 void ff_thread_finish_setup(AVCodecContext *avctx)
2691 {
2692 }
2693
2694 void ff_thread_report_progress(AVFrame *f, int progress, int field)
2695 {
2696 }
2697
2698 void ff_thread_await_progress(AVFrame *f, int progress, int field)
2699 {
2700 }
2701
2702 int ff_thread_can_start_frame(AVCodecContext *avctx)
2703 {
2704     return 1;
2705 }
2706
2707 #endif
2708
2709 enum AVMediaType avcodec_get_type(enum AVCodecID codec_id)
2710 {
2711     AVCodec *c= avcodec_find_decoder(codec_id);
2712     if(!c)
2713         c= avcodec_find_encoder(codec_id);
2714     if(c)
2715         return c->type;
2716
2717     if (codec_id <= AV_CODEC_ID_NONE)
2718         return AVMEDIA_TYPE_UNKNOWN;
2719     else if (codec_id < AV_CODEC_ID_FIRST_AUDIO)
2720         return AVMEDIA_TYPE_VIDEO;
2721     else if (codec_id < AV_CODEC_ID_FIRST_SUBTITLE)
2722         return AVMEDIA_TYPE_AUDIO;
2723     else if (codec_id < AV_CODEC_ID_FIRST_UNKNOWN)
2724         return AVMEDIA_TYPE_SUBTITLE;
2725
2726     return AVMEDIA_TYPE_UNKNOWN;
2727 }
2728
2729 int avcodec_is_open(AVCodecContext *s)
2730 {
2731     return !!s->internal;
2732 }