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