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