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