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