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