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