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