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