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