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