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