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