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