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