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