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