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