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