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