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