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