]> git.sesse.net Git - ffmpeg/blob - libavcodec/utils.c
Merge remote-tracking branch 'qatar/master'
[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         frame->pkt_pts = avctx->internal->pkt ? avctx->internal->pkt->pts : AV_NOPTS_VALUE;
1011         frame->reordered_opaque = avctx->reordered_opaque;
1012         return 0;
1013     }
1014
1015     av_frame_move_ref(&tmp, frame);
1016
1017     ret = ff_get_buffer(avctx, frame, AV_GET_BUFFER_FLAG_REF);
1018     if (ret < 0) {
1019         av_frame_unref(&tmp);
1020         return ret;
1021     }
1022
1023     av_image_copy(frame->data, frame->linesize, tmp.data, tmp.linesize,
1024                   frame->format, frame->width, frame->height);
1025
1026     av_frame_unref(&tmp);
1027
1028     return 0;
1029 }
1030
1031 int ff_reget_buffer(AVCodecContext *avctx, AVFrame *frame)
1032 {
1033     int ret = reget_buffer_internal(avctx, frame);
1034     if (ret < 0)
1035         av_log(avctx, AV_LOG_ERROR, "reget_buffer() failed\n");
1036     return ret;
1037 }
1038
1039 #if FF_API_GET_BUFFER
1040 void avcodec_default_release_buffer(AVCodecContext *s, AVFrame *pic)
1041 {
1042     av_assert0(s->codec_type == AVMEDIA_TYPE_VIDEO);
1043
1044     av_frame_unref(pic);
1045 }
1046
1047 int avcodec_default_reget_buffer(AVCodecContext *s, AVFrame *pic)
1048 {
1049     av_assert0(0);
1050     return AVERROR_BUG;
1051 }
1052 #endif
1053
1054 int avcodec_default_execute(AVCodecContext *c, int (*func)(AVCodecContext *c2, void *arg2), void *arg, int *ret, int count, int size)
1055 {
1056     int i;
1057
1058     for (i = 0; i < count; i++) {
1059         int r = func(c, (char *)arg + i * size);
1060         if (ret)
1061             ret[i] = r;
1062     }
1063     return 0;
1064 }
1065
1066 int avcodec_default_execute2(AVCodecContext *c, int (*func)(AVCodecContext *c2, void *arg2, int jobnr, int threadnr), void *arg, int *ret, int count)
1067 {
1068     int i;
1069
1070     for (i = 0; i < count; i++) {
1071         int r = func(c, arg, i, 0);
1072         if (ret)
1073             ret[i] = r;
1074     }
1075     return 0;
1076 }
1077
1078 static int is_hwaccel_pix_fmt(enum AVPixelFormat pix_fmt)
1079 {
1080     const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(pix_fmt);
1081     return desc->flags & AV_PIX_FMT_FLAG_HWACCEL;
1082 }
1083
1084 enum AVPixelFormat avcodec_default_get_format(struct AVCodecContext *s, const enum AVPixelFormat *fmt)
1085 {
1086     while (*fmt != AV_PIX_FMT_NONE && is_hwaccel_pix_fmt(*fmt))
1087         ++fmt;
1088     return fmt[0];
1089 }
1090
1091 #if FF_API_AVFRAME_LAVC
1092 void avcodec_get_frame_defaults(AVFrame *frame)
1093 {
1094 #if LIBAVCODEC_VERSION_MAJOR >= 55
1095      // extended_data should explicitly be freed when needed, this code is unsafe currently
1096      // also this is not compatible to the <55 ABI/API
1097     if (frame->extended_data != frame->data && 0)
1098         av_freep(&frame->extended_data);
1099 #endif
1100
1101     memset(frame, 0, sizeof(AVFrame));
1102     av_frame_unref(frame);
1103 }
1104
1105 AVFrame *avcodec_alloc_frame(void)
1106 {
1107     return av_frame_alloc();
1108 }
1109
1110 void avcodec_free_frame(AVFrame **frame)
1111 {
1112     av_frame_free(frame);
1113 }
1114 #endif
1115
1116 MAKE_ACCESSORS(AVCodecContext, codec, AVRational, pkt_timebase)
1117 MAKE_ACCESSORS(AVCodecContext, codec, const AVCodecDescriptor *, codec_descriptor)
1118 MAKE_ACCESSORS(AVCodecContext, codec, int, lowres)
1119 MAKE_ACCESSORS(AVCodecContext, codec, int, seek_preroll)
1120
1121 int av_codec_get_max_lowres(const AVCodec *codec)
1122 {
1123     return codec->max_lowres;
1124 }
1125
1126 static void avcodec_get_subtitle_defaults(AVSubtitle *sub)
1127 {
1128     memset(sub, 0, sizeof(*sub));
1129     sub->pts = AV_NOPTS_VALUE;
1130 }
1131
1132 static int get_bit_rate(AVCodecContext *ctx)
1133 {
1134     int bit_rate;
1135     int bits_per_sample;
1136
1137     switch (ctx->codec_type) {
1138     case AVMEDIA_TYPE_VIDEO:
1139     case AVMEDIA_TYPE_DATA:
1140     case AVMEDIA_TYPE_SUBTITLE:
1141     case AVMEDIA_TYPE_ATTACHMENT:
1142         bit_rate = ctx->bit_rate;
1143         break;
1144     case AVMEDIA_TYPE_AUDIO:
1145         bits_per_sample = av_get_bits_per_sample(ctx->codec_id);
1146         bit_rate = bits_per_sample ? ctx->sample_rate * ctx->channels * bits_per_sample : ctx->bit_rate;
1147         break;
1148     default:
1149         bit_rate = 0;
1150         break;
1151     }
1152     return bit_rate;
1153 }
1154
1155 int attribute_align_arg ff_codec_open2_recursive(AVCodecContext *avctx, const AVCodec *codec, AVDictionary **options)
1156 {
1157     int ret = 0;
1158
1159     ff_unlock_avcodec();
1160
1161     ret = avcodec_open2(avctx, codec, options);
1162
1163     ff_lock_avcodec(avctx);
1164     return ret;
1165 }
1166
1167 int attribute_align_arg avcodec_open2(AVCodecContext *avctx, const AVCodec *codec, AVDictionary **options)
1168 {
1169     int ret = 0;
1170     AVDictionary *tmp = NULL;
1171
1172     if (avcodec_is_open(avctx))
1173         return 0;
1174
1175     if ((!codec && !avctx->codec)) {
1176         av_log(avctx, AV_LOG_ERROR, "No codec provided to avcodec_open2()\n");
1177         return AVERROR(EINVAL);
1178     }
1179     if ((codec && avctx->codec && codec != avctx->codec)) {
1180         av_log(avctx, AV_LOG_ERROR, "This AVCodecContext was allocated for %s, "
1181                                     "but %s passed to avcodec_open2()\n", avctx->codec->name, codec->name);
1182         return AVERROR(EINVAL);
1183     }
1184     if (!codec)
1185         codec = avctx->codec;
1186
1187     if (avctx->extradata_size < 0 || avctx->extradata_size >= FF_MAX_EXTRADATA_SIZE)
1188         return AVERROR(EINVAL);
1189
1190     if (options)
1191         av_dict_copy(&tmp, *options, 0);
1192
1193     ret = ff_lock_avcodec(avctx);
1194     if (ret < 0)
1195         return ret;
1196
1197     avctx->internal = av_mallocz(sizeof(AVCodecInternal));
1198     if (!avctx->internal) {
1199         ret = AVERROR(ENOMEM);
1200         goto end;
1201     }
1202
1203     avctx->internal->pool = av_mallocz(sizeof(*avctx->internal->pool));
1204     if (!avctx->internal->pool) {
1205         ret = AVERROR(ENOMEM);
1206         goto free_and_end;
1207     }
1208
1209     avctx->internal->to_free = av_frame_alloc();
1210     if (!avctx->internal->to_free) {
1211         ret = AVERROR(ENOMEM);
1212         goto free_and_end;
1213     }
1214
1215     if (codec->priv_data_size > 0) {
1216         if (!avctx->priv_data) {
1217             avctx->priv_data = av_mallocz(codec->priv_data_size);
1218             if (!avctx->priv_data) {
1219                 ret = AVERROR(ENOMEM);
1220                 goto end;
1221             }
1222             if (codec->priv_class) {
1223                 *(const AVClass **)avctx->priv_data = codec->priv_class;
1224                 av_opt_set_defaults(avctx->priv_data);
1225             }
1226         }
1227         if (codec->priv_class && (ret = av_opt_set_dict(avctx->priv_data, &tmp)) < 0)
1228             goto free_and_end;
1229     } else {
1230         avctx->priv_data = NULL;
1231     }
1232     if ((ret = av_opt_set_dict(avctx, &tmp)) < 0)
1233         goto free_and_end;
1234
1235     // only call ff_set_dimensions() for non H.264/VP6F codecs so as not to overwrite previously setup dimensions
1236     if (!(avctx->coded_width && avctx->coded_height && avctx->width && avctx->height &&
1237           (avctx->codec_id == AV_CODEC_ID_H264 || avctx->codec_id == AV_CODEC_ID_VP6F))) {
1238     if (avctx->coded_width && avctx->coded_height)
1239         ret = ff_set_dimensions(avctx, avctx->coded_width, avctx->coded_height);
1240     else if (avctx->width && avctx->height)
1241         ret = ff_set_dimensions(avctx, avctx->width, avctx->height);
1242     if (ret < 0)
1243         goto free_and_end;
1244     }
1245
1246     if ((avctx->coded_width || avctx->coded_height || avctx->width || avctx->height)
1247         && (  av_image_check_size(avctx->coded_width, avctx->coded_height, 0, avctx) < 0
1248            || av_image_check_size(avctx->width,       avctx->height,       0, avctx) < 0)) {
1249         av_log(avctx, AV_LOG_WARNING, "Ignoring invalid width/height values\n");
1250         ff_set_dimensions(avctx, 0, 0);
1251     }
1252
1253     /* if the decoder init function was already called previously,
1254      * free the already allocated subtitle_header before overwriting it */
1255     if (av_codec_is_decoder(codec))
1256         av_freep(&avctx->subtitle_header);
1257
1258     if (avctx->channels > FF_SANE_NB_CHANNELS) {
1259         ret = AVERROR(EINVAL);
1260         goto free_and_end;
1261     }
1262
1263     avctx->codec = codec;
1264     if ((avctx->codec_type == AVMEDIA_TYPE_UNKNOWN || avctx->codec_type == codec->type) &&
1265         avctx->codec_id == AV_CODEC_ID_NONE) {
1266         avctx->codec_type = codec->type;
1267         avctx->codec_id   = codec->id;
1268     }
1269     if (avctx->codec_id != codec->id || (avctx->codec_type != codec->type
1270                                          && avctx->codec_type != AVMEDIA_TYPE_ATTACHMENT)) {
1271         av_log(avctx, AV_LOG_ERROR, "Codec type or id mismatches\n");
1272         ret = AVERROR(EINVAL);
1273         goto free_and_end;
1274     }
1275     avctx->frame_number = 0;
1276     avctx->codec_descriptor = avcodec_descriptor_get(avctx->codec_id);
1277
1278     if (avctx->codec->capabilities & CODEC_CAP_EXPERIMENTAL &&
1279         avctx->strict_std_compliance > FF_COMPLIANCE_EXPERIMENTAL) {
1280         const char *codec_string = av_codec_is_encoder(codec) ? "encoder" : "decoder";
1281         AVCodec *codec2;
1282         av_log(avctx, AV_LOG_ERROR,
1283                "The %s '%s' is experimental but experimental codecs are not enabled, "
1284                "add '-strict %d' if you want to use it.\n",
1285                codec_string, codec->name, FF_COMPLIANCE_EXPERIMENTAL);
1286         codec2 = av_codec_is_encoder(codec) ? avcodec_find_encoder(codec->id) : avcodec_find_decoder(codec->id);
1287         if (!(codec2->capabilities & CODEC_CAP_EXPERIMENTAL))
1288             av_log(avctx, AV_LOG_ERROR, "Alternatively use the non experimental %s '%s'.\n",
1289                 codec_string, codec2->name);
1290         ret = AVERROR_EXPERIMENTAL;
1291         goto free_and_end;
1292     }
1293
1294     if (avctx->codec_type == AVMEDIA_TYPE_AUDIO &&
1295         (!avctx->time_base.num || !avctx->time_base.den)) {
1296         avctx->time_base.num = 1;
1297         avctx->time_base.den = avctx->sample_rate;
1298     }
1299
1300     if (!HAVE_THREADS)
1301         av_log(avctx, AV_LOG_WARNING, "Warning: not compiled with thread support, using thread emulation\n");
1302
1303     if (CONFIG_FRAME_THREAD_ENCODER) {
1304         ff_unlock_avcodec(); //we will instanciate a few encoders thus kick the counter to prevent false detection of a problem
1305         ret = ff_frame_thread_encoder_init(avctx, options ? *options : NULL);
1306         ff_lock_avcodec(avctx);
1307         if (ret < 0)
1308             goto free_and_end;
1309     }
1310
1311     if (HAVE_THREADS
1312         && !(avctx->internal->frame_thread_encoder && (avctx->active_thread_type&FF_THREAD_FRAME))) {
1313         ret = ff_thread_init(avctx);
1314         if (ret < 0) {
1315             goto free_and_end;
1316         }
1317     }
1318     if (!HAVE_THREADS && !(codec->capabilities & CODEC_CAP_AUTO_THREADS))
1319         avctx->thread_count = 1;
1320
1321     if (avctx->codec->max_lowres < avctx->lowres || avctx->lowres < 0) {
1322         av_log(avctx, AV_LOG_ERROR, "The maximum value for lowres supported by the decoder is %d\n",
1323                avctx->codec->max_lowres);
1324         ret = AVERROR(EINVAL);
1325         goto free_and_end;
1326     }
1327
1328     if (av_codec_is_encoder(avctx->codec)) {
1329         int i;
1330         if (avctx->codec->sample_fmts) {
1331             for (i = 0; avctx->codec->sample_fmts[i] != AV_SAMPLE_FMT_NONE; i++) {
1332                 if (avctx->sample_fmt == avctx->codec->sample_fmts[i])
1333                     break;
1334                 if (avctx->channels == 1 &&
1335                     av_get_planar_sample_fmt(avctx->sample_fmt) ==
1336                     av_get_planar_sample_fmt(avctx->codec->sample_fmts[i])) {
1337                     avctx->sample_fmt = avctx->codec->sample_fmts[i];
1338                     break;
1339                 }
1340             }
1341             if (avctx->codec->sample_fmts[i] == AV_SAMPLE_FMT_NONE) {
1342                 char buf[128];
1343                 snprintf(buf, sizeof(buf), "%d", avctx->sample_fmt);
1344                 av_log(avctx, AV_LOG_ERROR, "Specified sample format %s is invalid or not supported\n",
1345                        (char *)av_x_if_null(av_get_sample_fmt_name(avctx->sample_fmt), buf));
1346                 ret = AVERROR(EINVAL);
1347                 goto free_and_end;
1348             }
1349         }
1350         if (avctx->codec->pix_fmts) {
1351             for (i = 0; avctx->codec->pix_fmts[i] != AV_PIX_FMT_NONE; i++)
1352                 if (avctx->pix_fmt == avctx->codec->pix_fmts[i])
1353                     break;
1354             if (avctx->codec->pix_fmts[i] == AV_PIX_FMT_NONE
1355                 && !((avctx->codec_id == AV_CODEC_ID_MJPEG || avctx->codec_id == AV_CODEC_ID_LJPEG)
1356                      && avctx->strict_std_compliance <= FF_COMPLIANCE_UNOFFICIAL)) {
1357                 char buf[128];
1358                 snprintf(buf, sizeof(buf), "%d", avctx->pix_fmt);
1359                 av_log(avctx, AV_LOG_ERROR, "Specified pixel format %s is invalid or not supported\n",
1360                        (char *)av_x_if_null(av_get_pix_fmt_name(avctx->pix_fmt), buf));
1361                 ret = AVERROR(EINVAL);
1362                 goto free_and_end;
1363             }
1364         }
1365         if (avctx->codec->supported_samplerates) {
1366             for (i = 0; avctx->codec->supported_samplerates[i] != 0; i++)
1367                 if (avctx->sample_rate == avctx->codec->supported_samplerates[i])
1368                     break;
1369             if (avctx->codec->supported_samplerates[i] == 0) {
1370                 av_log(avctx, AV_LOG_ERROR, "Specified sample rate %d is not supported\n",
1371                        avctx->sample_rate);
1372                 ret = AVERROR(EINVAL);
1373                 goto free_and_end;
1374             }
1375         }
1376         if (avctx->codec->channel_layouts) {
1377             if (!avctx->channel_layout) {
1378                 av_log(avctx, AV_LOG_WARNING, "Channel layout not specified\n");
1379             } else {
1380                 for (i = 0; avctx->codec->channel_layouts[i] != 0; i++)
1381                     if (avctx->channel_layout == avctx->codec->channel_layouts[i])
1382                         break;
1383                 if (avctx->codec->channel_layouts[i] == 0) {
1384                     char buf[512];
1385                     av_get_channel_layout_string(buf, sizeof(buf), -1, avctx->channel_layout);
1386                     av_log(avctx, AV_LOG_ERROR, "Specified channel layout '%s' is not supported\n", buf);
1387                     ret = AVERROR(EINVAL);
1388                     goto free_and_end;
1389                 }
1390             }
1391         }
1392         if (avctx->channel_layout && avctx->channels) {
1393             int channels = av_get_channel_layout_nb_channels(avctx->channel_layout);
1394             if (channels != avctx->channels) {
1395                 char buf[512];
1396                 av_get_channel_layout_string(buf, sizeof(buf), -1, avctx->channel_layout);
1397                 av_log(avctx, AV_LOG_ERROR,
1398                        "Channel layout '%s' with %d channels does not match number of specified channels %d\n",
1399                        buf, channels, avctx->channels);
1400                 ret = AVERROR(EINVAL);
1401                 goto free_and_end;
1402             }
1403         } else if (avctx->channel_layout) {
1404             avctx->channels = av_get_channel_layout_nb_channels(avctx->channel_layout);
1405         }
1406         if(avctx->codec_type == AVMEDIA_TYPE_VIDEO &&
1407            avctx->codec_id != AV_CODEC_ID_PNG // For mplayer
1408         ) {
1409             if (avctx->width <= 0 || avctx->height <= 0) {
1410                 av_log(avctx, AV_LOG_ERROR, "dimensions not set\n");
1411                 ret = AVERROR(EINVAL);
1412                 goto free_and_end;
1413             }
1414         }
1415         if (   (avctx->codec_type == AVMEDIA_TYPE_VIDEO || avctx->codec_type == AVMEDIA_TYPE_AUDIO)
1416             && avctx->bit_rate>0 && avctx->bit_rate<1000) {
1417             av_log(avctx, AV_LOG_WARNING, "Bitrate %d is extremely low, maybe you mean %dk\n", avctx->bit_rate, avctx->bit_rate);
1418         }
1419
1420         if (!avctx->rc_initial_buffer_occupancy)
1421             avctx->rc_initial_buffer_occupancy = avctx->rc_buffer_size * 3 / 4;
1422     }
1423
1424     avctx->pts_correction_num_faulty_pts =
1425     avctx->pts_correction_num_faulty_dts = 0;
1426     avctx->pts_correction_last_pts =
1427     avctx->pts_correction_last_dts = INT64_MIN;
1428
1429     if (   avctx->codec->init && (!(avctx->active_thread_type&FF_THREAD_FRAME)
1430         || avctx->internal->frame_thread_encoder)) {
1431         ret = avctx->codec->init(avctx);
1432         if (ret < 0) {
1433             goto free_and_end;
1434         }
1435     }
1436
1437     ret=0;
1438
1439     if (av_codec_is_decoder(avctx->codec)) {
1440         if (!avctx->bit_rate)
1441             avctx->bit_rate = get_bit_rate(avctx);
1442         /* validate channel layout from the decoder */
1443         if (avctx->channel_layout) {
1444             int channels = av_get_channel_layout_nb_channels(avctx->channel_layout);
1445             if (!avctx->channels)
1446                 avctx->channels = channels;
1447             else if (channels != avctx->channels) {
1448                 char buf[512];
1449                 av_get_channel_layout_string(buf, sizeof(buf), -1, avctx->channel_layout);
1450                 av_log(avctx, AV_LOG_WARNING,
1451                        "Channel layout '%s' with %d channels does not match specified number of channels %d: "
1452                        "ignoring specified channel layout\n",
1453                        buf, channels, avctx->channels);
1454                 avctx->channel_layout = 0;
1455             }
1456         }
1457         if (avctx->channels && avctx->channels < 0 ||
1458             avctx->channels > FF_SANE_NB_CHANNELS) {
1459             ret = AVERROR(EINVAL);
1460             goto free_and_end;
1461         }
1462         if (avctx->sub_charenc) {
1463             if (avctx->codec_type != AVMEDIA_TYPE_SUBTITLE) {
1464                 av_log(avctx, AV_LOG_ERROR, "Character encoding is only "
1465                        "supported with subtitles codecs\n");
1466                 ret = AVERROR(EINVAL);
1467                 goto free_and_end;
1468             } else if (avctx->codec_descriptor->props & AV_CODEC_PROP_BITMAP_SUB) {
1469                 av_log(avctx, AV_LOG_WARNING, "Codec '%s' is bitmap-based, "
1470                        "subtitles character encoding will be ignored\n",
1471                        avctx->codec_descriptor->name);
1472                 avctx->sub_charenc_mode = FF_SUB_CHARENC_MODE_DO_NOTHING;
1473             } else {
1474                 /* input character encoding is set for a text based subtitle
1475                  * codec at this point */
1476                 if (avctx->sub_charenc_mode == FF_SUB_CHARENC_MODE_AUTOMATIC)
1477                     avctx->sub_charenc_mode = FF_SUB_CHARENC_MODE_PRE_DECODER;
1478
1479                 if (avctx->sub_charenc_mode == FF_SUB_CHARENC_MODE_PRE_DECODER) {
1480 #if CONFIG_ICONV
1481                     iconv_t cd = iconv_open("UTF-8", avctx->sub_charenc);
1482                     if (cd == (iconv_t)-1) {
1483                         av_log(avctx, AV_LOG_ERROR, "Unable to open iconv context "
1484                                "with input character encoding \"%s\"\n", avctx->sub_charenc);
1485                         ret = AVERROR(errno);
1486                         goto free_and_end;
1487                     }
1488                     iconv_close(cd);
1489 #else
1490                     av_log(avctx, AV_LOG_ERROR, "Character encoding subtitles "
1491                            "conversion needs a libavcodec built with iconv support "
1492                            "for this codec\n");
1493                     ret = AVERROR(ENOSYS);
1494                     goto free_and_end;
1495 #endif
1496                 }
1497             }
1498         }
1499     }
1500 end:
1501     ff_unlock_avcodec();
1502     if (options) {
1503         av_dict_free(options);
1504         *options = tmp;
1505     }
1506
1507     return ret;
1508 free_and_end:
1509     av_dict_free(&tmp);
1510     av_freep(&avctx->priv_data);
1511     if (avctx->internal) {
1512         av_frame_free(&avctx->internal->to_free);
1513         av_freep(&avctx->internal->pool);
1514     }
1515     av_freep(&avctx->internal);
1516     avctx->codec = NULL;
1517     goto end;
1518 }
1519
1520 int ff_alloc_packet2(AVCodecContext *avctx, AVPacket *avpkt, int64_t size)
1521 {
1522     if (avpkt->size < 0) {
1523         av_log(avctx, AV_LOG_ERROR, "Invalid negative user packet size %d\n", avpkt->size);
1524         return AVERROR(EINVAL);
1525     }
1526     if (size < 0 || size > INT_MAX - FF_INPUT_BUFFER_PADDING_SIZE) {
1527         av_log(avctx, AV_LOG_ERROR, "Invalid minimum required packet size %"PRId64" (max allowed is %d)\n",
1528                size, INT_MAX - FF_INPUT_BUFFER_PADDING_SIZE);
1529         return AVERROR(EINVAL);
1530     }
1531
1532     if (avctx) {
1533         av_assert0(!avpkt->data || avpkt->data != avctx->internal->byte_buffer);
1534         if (!avpkt->data || avpkt->size < size) {
1535             av_fast_padded_malloc(&avctx->internal->byte_buffer, &avctx->internal->byte_buffer_size, size);
1536             avpkt->data = avctx->internal->byte_buffer;
1537             avpkt->size = avctx->internal->byte_buffer_size;
1538             avpkt->destruct = NULL;
1539         }
1540     }
1541
1542     if (avpkt->data) {
1543         AVBufferRef *buf = avpkt->buf;
1544 #if FF_API_DESTRUCT_PACKET
1545 FF_DISABLE_DEPRECATION_WARNINGS
1546         void *destruct = avpkt->destruct;
1547 FF_ENABLE_DEPRECATION_WARNINGS
1548 #endif
1549
1550         if (avpkt->size < size) {
1551             av_log(avctx, AV_LOG_ERROR, "User packet is too small (%d < %"PRId64")\n", avpkt->size, size);
1552             return AVERROR(EINVAL);
1553         }
1554
1555         av_init_packet(avpkt);
1556 #if FF_API_DESTRUCT_PACKET
1557 FF_DISABLE_DEPRECATION_WARNINGS
1558         avpkt->destruct = destruct;
1559 FF_ENABLE_DEPRECATION_WARNINGS
1560 #endif
1561         avpkt->buf      = buf;
1562         avpkt->size     = size;
1563         return 0;
1564     } else {
1565         int ret = av_new_packet(avpkt, size);
1566         if (ret < 0)
1567             av_log(avctx, AV_LOG_ERROR, "Failed to allocate packet of size %"PRId64"\n", size);
1568         return ret;
1569     }
1570 }
1571
1572 int ff_alloc_packet(AVPacket *avpkt, int size)
1573 {
1574     return ff_alloc_packet2(NULL, avpkt, size);
1575 }
1576
1577 /**
1578  * Pad last frame with silence.
1579  */
1580 static int pad_last_frame(AVCodecContext *s, AVFrame **dst, const AVFrame *src)
1581 {
1582     AVFrame *frame = NULL;
1583     int ret;
1584
1585     if (!(frame = av_frame_alloc()))
1586         return AVERROR(ENOMEM);
1587
1588     frame->format         = src->format;
1589     frame->channel_layout = src->channel_layout;
1590     av_frame_set_channels(frame, av_frame_get_channels(src));
1591     frame->nb_samples     = s->frame_size;
1592     ret = av_frame_get_buffer(frame, 32);
1593     if (ret < 0)
1594         goto fail;
1595
1596     ret = av_frame_copy_props(frame, src);
1597     if (ret < 0)
1598         goto fail;
1599
1600     if ((ret = av_samples_copy(frame->extended_data, src->extended_data, 0, 0,
1601                                src->nb_samples, s->channels, s->sample_fmt)) < 0)
1602         goto fail;
1603     if ((ret = av_samples_set_silence(frame->extended_data, src->nb_samples,
1604                                       frame->nb_samples - src->nb_samples,
1605                                       s->channels, s->sample_fmt)) < 0)
1606         goto fail;
1607
1608     *dst = frame;
1609
1610     return 0;
1611
1612 fail:
1613     av_frame_free(&frame);
1614     return ret;
1615 }
1616
1617 int attribute_align_arg avcodec_encode_audio2(AVCodecContext *avctx,
1618                                               AVPacket *avpkt,
1619                                               const AVFrame *frame,
1620                                               int *got_packet_ptr)
1621 {
1622     AVFrame tmp;
1623     AVFrame *padded_frame = NULL;
1624     int ret;
1625     AVPacket user_pkt = *avpkt;
1626     int needs_realloc = !user_pkt.data;
1627
1628     *got_packet_ptr = 0;
1629
1630     if (!(avctx->codec->capabilities & CODEC_CAP_DELAY) && !frame) {
1631         av_free_packet(avpkt);
1632         av_init_packet(avpkt);
1633         return 0;
1634     }
1635
1636     /* ensure that extended_data is properly set */
1637     if (frame && !frame->extended_data) {
1638         if (av_sample_fmt_is_planar(avctx->sample_fmt) &&
1639             avctx->channels > AV_NUM_DATA_POINTERS) {
1640             av_log(avctx, AV_LOG_ERROR, "Encoding to a planar sample format, "
1641                                         "with more than %d channels, but extended_data is not set.\n",
1642                    AV_NUM_DATA_POINTERS);
1643             return AVERROR(EINVAL);
1644         }
1645         av_log(avctx, AV_LOG_WARNING, "extended_data is not set.\n");
1646
1647         tmp = *frame;
1648         tmp.extended_data = tmp.data;
1649         frame = &tmp;
1650     }
1651
1652     /* check for valid frame size */
1653     if (frame) {
1654         if (avctx->codec->capabilities & CODEC_CAP_SMALL_LAST_FRAME) {
1655             if (frame->nb_samples > avctx->frame_size) {
1656                 av_log(avctx, AV_LOG_ERROR, "more samples than frame size (avcodec_encode_audio2)\n");
1657                 return AVERROR(EINVAL);
1658             }
1659         } else if (!(avctx->codec->capabilities & CODEC_CAP_VARIABLE_FRAME_SIZE)) {
1660             if (frame->nb_samples < avctx->frame_size &&
1661                 !avctx->internal->last_audio_frame) {
1662                 ret = pad_last_frame(avctx, &padded_frame, frame);
1663                 if (ret < 0)
1664                     return ret;
1665
1666                 frame = padded_frame;
1667                 avctx->internal->last_audio_frame = 1;
1668             }
1669
1670             if (frame->nb_samples != avctx->frame_size) {
1671                 av_log(avctx, AV_LOG_ERROR, "nb_samples (%d) != frame_size (%d) (avcodec_encode_audio2)\n", frame->nb_samples, avctx->frame_size);
1672                 ret = AVERROR(EINVAL);
1673                 goto end;
1674             }
1675         }
1676     }
1677
1678     ret = avctx->codec->encode2(avctx, avpkt, frame, got_packet_ptr);
1679     if (!ret) {
1680         if (*got_packet_ptr) {
1681             if (!(avctx->codec->capabilities & CODEC_CAP_DELAY)) {
1682                 if (avpkt->pts == AV_NOPTS_VALUE)
1683                     avpkt->pts = frame->pts;
1684                 if (!avpkt->duration)
1685                     avpkt->duration = ff_samples_to_time_base(avctx,
1686                                                               frame->nb_samples);
1687             }
1688             avpkt->dts = avpkt->pts;
1689         } else {
1690             avpkt->size = 0;
1691         }
1692     }
1693     if (avpkt->data && avpkt->data == avctx->internal->byte_buffer) {
1694         needs_realloc = 0;
1695         if (user_pkt.data) {
1696             if (user_pkt.size >= avpkt->size) {
1697                 memcpy(user_pkt.data, avpkt->data, avpkt->size);
1698             } else {
1699                 av_log(avctx, AV_LOG_ERROR, "Provided packet is too small, needs to be %d\n", avpkt->size);
1700                 avpkt->size = user_pkt.size;
1701                 ret = -1;
1702             }
1703             avpkt->buf      = user_pkt.buf;
1704             avpkt->data     = user_pkt.data;
1705             avpkt->destruct = user_pkt.destruct;
1706         } else {
1707             if (av_dup_packet(avpkt) < 0) {
1708                 ret = AVERROR(ENOMEM);
1709             }
1710         }
1711     }
1712
1713     if (!ret) {
1714         if (needs_realloc && avpkt->data) {
1715             ret = av_buffer_realloc(&avpkt->buf, avpkt->size + FF_INPUT_BUFFER_PADDING_SIZE);
1716             if (ret >= 0)
1717                 avpkt->data = avpkt->buf->data;
1718         }
1719
1720         avctx->frame_number++;
1721     }
1722
1723     if (ret < 0 || !*got_packet_ptr) {
1724         av_free_packet(avpkt);
1725         av_init_packet(avpkt);
1726         goto end;
1727     }
1728
1729     /* NOTE: if we add any audio encoders which output non-keyframe packets,
1730      *       this needs to be moved to the encoders, but for now we can do it
1731      *       here to simplify things */
1732     avpkt->flags |= AV_PKT_FLAG_KEY;
1733
1734 end:
1735     av_frame_free(&padded_frame);
1736
1737     return ret;
1738 }
1739
1740 #if FF_API_OLD_ENCODE_AUDIO
1741 int attribute_align_arg avcodec_encode_audio(AVCodecContext *avctx,
1742                                              uint8_t *buf, int buf_size,
1743                                              const short *samples)
1744 {
1745     AVPacket pkt;
1746     AVFrame *frame;
1747     int ret, samples_size, got_packet;
1748
1749     av_init_packet(&pkt);
1750     pkt.data = buf;
1751     pkt.size = buf_size;
1752
1753     if (samples) {
1754         frame = av_frame_alloc();
1755         if (!frame)
1756             return AVERROR(ENOMEM);
1757
1758         if (avctx->frame_size) {
1759             frame->nb_samples = avctx->frame_size;
1760         } else {
1761             /* if frame_size is not set, the number of samples must be
1762              * calculated from the buffer size */
1763             int64_t nb_samples;
1764             if (!av_get_bits_per_sample(avctx->codec_id)) {
1765                 av_log(avctx, AV_LOG_ERROR, "avcodec_encode_audio() does not "
1766                                             "support this codec\n");
1767                 av_frame_free(&frame);
1768                 return AVERROR(EINVAL);
1769             }
1770             nb_samples = (int64_t)buf_size * 8 /
1771                          (av_get_bits_per_sample(avctx->codec_id) *
1772                           avctx->channels);
1773             if (nb_samples >= INT_MAX) {
1774                 av_frame_free(&frame);
1775                 return AVERROR(EINVAL);
1776             }
1777             frame->nb_samples = nb_samples;
1778         }
1779
1780         /* it is assumed that the samples buffer is large enough based on the
1781          * relevant parameters */
1782         samples_size = av_samples_get_buffer_size(NULL, avctx->channels,
1783                                                   frame->nb_samples,
1784                                                   avctx->sample_fmt, 1);
1785         if ((ret = avcodec_fill_audio_frame(frame, avctx->channels,
1786                                             avctx->sample_fmt,
1787                                             (const uint8_t *)samples,
1788                                             samples_size, 1)) < 0) {
1789             av_frame_free(&frame);
1790             return ret;
1791         }
1792
1793         /* fabricate frame pts from sample count.
1794          * this is needed because the avcodec_encode_audio() API does not have
1795          * a way for the user to provide pts */
1796         if (avctx->sample_rate && avctx->time_base.num)
1797             frame->pts = ff_samples_to_time_base(avctx,
1798                                                  avctx->internal->sample_count);
1799         else
1800             frame->pts = AV_NOPTS_VALUE;
1801         avctx->internal->sample_count += frame->nb_samples;
1802     } else {
1803         frame = NULL;
1804     }
1805
1806     got_packet = 0;
1807     ret = avcodec_encode_audio2(avctx, &pkt, frame, &got_packet);
1808     if (!ret && got_packet && avctx->coded_frame) {
1809         avctx->coded_frame->pts       = pkt.pts;
1810         avctx->coded_frame->key_frame = !!(pkt.flags & AV_PKT_FLAG_KEY);
1811     }
1812     /* free any side data since we cannot return it */
1813     av_packet_free_side_data(&pkt);
1814
1815     if (frame && frame->extended_data != frame->data)
1816         av_freep(&frame->extended_data);
1817
1818     av_frame_free(&frame);
1819     return ret ? ret : pkt.size;
1820 }
1821
1822 #endif
1823
1824 #if FF_API_OLD_ENCODE_VIDEO
1825 int attribute_align_arg avcodec_encode_video(AVCodecContext *avctx, uint8_t *buf, int buf_size,
1826                                              const AVFrame *pict)
1827 {
1828     AVPacket pkt;
1829     int ret, got_packet = 0;
1830
1831     if (buf_size < FF_MIN_BUFFER_SIZE) {
1832         av_log(avctx, AV_LOG_ERROR, "buffer smaller than minimum size\n");
1833         return -1;
1834     }
1835
1836     av_init_packet(&pkt);
1837     pkt.data = buf;
1838     pkt.size = buf_size;
1839
1840     ret = avcodec_encode_video2(avctx, &pkt, pict, &got_packet);
1841     if (!ret && got_packet && avctx->coded_frame) {
1842         avctx->coded_frame->pts       = pkt.pts;
1843         avctx->coded_frame->key_frame = !!(pkt.flags & AV_PKT_FLAG_KEY);
1844     }
1845
1846     /* free any side data since we cannot return it */
1847     if (pkt.side_data_elems > 0) {
1848         int i;
1849         for (i = 0; i < pkt.side_data_elems; i++)
1850             av_free(pkt.side_data[i].data);
1851         av_freep(&pkt.side_data);
1852         pkt.side_data_elems = 0;
1853     }
1854
1855     return ret ? ret : pkt.size;
1856 }
1857
1858 #endif
1859
1860 int attribute_align_arg avcodec_encode_video2(AVCodecContext *avctx,
1861                                               AVPacket *avpkt,
1862                                               const AVFrame *frame,
1863                                               int *got_packet_ptr)
1864 {
1865     int ret;
1866     AVPacket user_pkt = *avpkt;
1867     int needs_realloc = !user_pkt.data;
1868
1869     *got_packet_ptr = 0;
1870
1871     if(CONFIG_FRAME_THREAD_ENCODER &&
1872        avctx->internal->frame_thread_encoder && (avctx->active_thread_type&FF_THREAD_FRAME))
1873         return ff_thread_video_encode_frame(avctx, avpkt, frame, got_packet_ptr);
1874
1875     if ((avctx->flags&CODEC_FLAG_PASS1) && avctx->stats_out)
1876         avctx->stats_out[0] = '\0';
1877
1878     if (!(avctx->codec->capabilities & CODEC_CAP_DELAY) && !frame) {
1879         av_free_packet(avpkt);
1880         av_init_packet(avpkt);
1881         avpkt->size = 0;
1882         return 0;
1883     }
1884
1885     if (av_image_check_size(avctx->width, avctx->height, 0, avctx))
1886         return AVERROR(EINVAL);
1887
1888     av_assert0(avctx->codec->encode2);
1889
1890     ret = avctx->codec->encode2(avctx, avpkt, frame, got_packet_ptr);
1891     av_assert0(ret <= 0);
1892
1893     if (avpkt->data && avpkt->data == avctx->internal->byte_buffer) {
1894         needs_realloc = 0;
1895         if (user_pkt.data) {
1896             if (user_pkt.size >= avpkt->size) {
1897                 memcpy(user_pkt.data, avpkt->data, avpkt->size);
1898             } else {
1899                 av_log(avctx, AV_LOG_ERROR, "Provided packet is too small, needs to be %d\n", avpkt->size);
1900                 avpkt->size = user_pkt.size;
1901                 ret = -1;
1902             }
1903             avpkt->buf      = user_pkt.buf;
1904             avpkt->data     = user_pkt.data;
1905             avpkt->destruct = user_pkt.destruct;
1906         } else {
1907             if (av_dup_packet(avpkt) < 0) {
1908                 ret = AVERROR(ENOMEM);
1909             }
1910         }
1911     }
1912
1913     if (!ret) {
1914         if (!*got_packet_ptr)
1915             avpkt->size = 0;
1916         else if (!(avctx->codec->capabilities & CODEC_CAP_DELAY))
1917             avpkt->pts = avpkt->dts = frame->pts;
1918
1919         if (needs_realloc && avpkt->data) {
1920             ret = av_buffer_realloc(&avpkt->buf, avpkt->size + FF_INPUT_BUFFER_PADDING_SIZE);
1921             if (ret >= 0)
1922                 avpkt->data = avpkt->buf->data;
1923         }
1924
1925         avctx->frame_number++;
1926     }
1927
1928     if (ret < 0 || !*got_packet_ptr)
1929         av_free_packet(avpkt);
1930     else
1931         av_packet_merge_side_data(avpkt);
1932
1933     emms_c();
1934     return ret;
1935 }
1936
1937 int avcodec_encode_subtitle(AVCodecContext *avctx, uint8_t *buf, int buf_size,
1938                             const AVSubtitle *sub)
1939 {
1940     int ret;
1941     if (sub->start_display_time) {
1942         av_log(avctx, AV_LOG_ERROR, "start_display_time must be 0.\n");
1943         return -1;
1944     }
1945
1946     ret = avctx->codec->encode_sub(avctx, buf, buf_size, sub);
1947     avctx->frame_number++;
1948     return ret;
1949 }
1950
1951 /**
1952  * Attempt to guess proper monotonic timestamps for decoded video frames
1953  * which might have incorrect times. Input timestamps may wrap around, in
1954  * which case the output will as well.
1955  *
1956  * @param pts the pts field of the decoded AVPacket, as passed through
1957  * AVFrame.pkt_pts
1958  * @param dts the dts field of the decoded AVPacket
1959  * @return one of the input values, may be AV_NOPTS_VALUE
1960  */
1961 static int64_t guess_correct_pts(AVCodecContext *ctx,
1962                                  int64_t reordered_pts, int64_t dts)
1963 {
1964     int64_t pts = AV_NOPTS_VALUE;
1965
1966     if (dts != AV_NOPTS_VALUE) {
1967         ctx->pts_correction_num_faulty_dts += dts <= ctx->pts_correction_last_dts;
1968         ctx->pts_correction_last_dts = dts;
1969     }
1970     if (reordered_pts != AV_NOPTS_VALUE) {
1971         ctx->pts_correction_num_faulty_pts += reordered_pts <= ctx->pts_correction_last_pts;
1972         ctx->pts_correction_last_pts = reordered_pts;
1973     }
1974     if ((ctx->pts_correction_num_faulty_pts<=ctx->pts_correction_num_faulty_dts || dts == AV_NOPTS_VALUE)
1975        && reordered_pts != AV_NOPTS_VALUE)
1976         pts = reordered_pts;
1977     else
1978         pts = dts;
1979
1980     return pts;
1981 }
1982
1983 static int apply_param_change(AVCodecContext *avctx, AVPacket *avpkt)
1984 {
1985     int size = 0, ret;
1986     const uint8_t *data;
1987     uint32_t flags;
1988
1989     data = av_packet_get_side_data(avpkt, AV_PKT_DATA_PARAM_CHANGE, &size);
1990     if (!data)
1991         return 0;
1992
1993     if (!(avctx->codec->capabilities & CODEC_CAP_PARAM_CHANGE)) {
1994         av_log(avctx, AV_LOG_ERROR, "This decoder does not support parameter "
1995                "changes, but PARAM_CHANGE side data was sent to it.\n");
1996         return AVERROR(EINVAL);
1997     }
1998
1999     if (size < 4)
2000         goto fail;
2001
2002     flags = bytestream_get_le32(&data);
2003     size -= 4;
2004
2005     if (flags & AV_SIDE_DATA_PARAM_CHANGE_CHANNEL_COUNT) {
2006         if (size < 4)
2007             goto fail;
2008         avctx->channels = bytestream_get_le32(&data);
2009         size -= 4;
2010     }
2011     if (flags & AV_SIDE_DATA_PARAM_CHANGE_CHANNEL_LAYOUT) {
2012         if (size < 8)
2013             goto fail;
2014         avctx->channel_layout = bytestream_get_le64(&data);
2015         size -= 8;
2016     }
2017     if (flags & AV_SIDE_DATA_PARAM_CHANGE_SAMPLE_RATE) {
2018         if (size < 4)
2019             goto fail;
2020         avctx->sample_rate = bytestream_get_le32(&data);
2021         size -= 4;
2022     }
2023     if (flags & AV_SIDE_DATA_PARAM_CHANGE_DIMENSIONS) {
2024         if (size < 8)
2025             goto fail;
2026         avctx->width  = bytestream_get_le32(&data);
2027         avctx->height = bytestream_get_le32(&data);
2028         size -= 8;
2029         ret = ff_set_dimensions(avctx, avctx->width, avctx->height);
2030         if (ret < 0)
2031             return ret;
2032     }
2033
2034     return 0;
2035 fail:
2036     av_log(avctx, AV_LOG_ERROR, "PARAM_CHANGE side data too small.\n");
2037     return AVERROR_INVALIDDATA;
2038 }
2039
2040 static int add_metadata_from_side_data(AVCodecContext *avctx, AVFrame *frame)
2041 {
2042     int size;
2043     const uint8_t *side_metadata;
2044
2045     AVDictionary **frame_md = avpriv_frame_get_metadatap(frame);
2046
2047     side_metadata = av_packet_get_side_data(avctx->internal->pkt,
2048                                             AV_PKT_DATA_STRINGS_METADATA, &size);
2049     return av_packet_unpack_dictionary(side_metadata, size, frame_md);
2050 }
2051
2052 static int unrefcount_frame(AVCodecInternal *avci, AVFrame *frame)
2053 {
2054     int ret;
2055
2056     /* move the original frame to our backup */
2057     av_frame_unref(avci->to_free);
2058     av_frame_move_ref(avci->to_free, frame);
2059
2060     /* now copy everything except the AVBufferRefs back
2061      * note that we make a COPY of the side data, so calling av_frame_free() on
2062      * the caller's frame will work properly */
2063     ret = av_frame_copy_props(frame, avci->to_free);
2064     if (ret < 0)
2065         return ret;
2066
2067     memcpy(frame->data,     avci->to_free->data,     sizeof(frame->data));
2068     memcpy(frame->linesize, avci->to_free->linesize, sizeof(frame->linesize));
2069     if (avci->to_free->extended_data != avci->to_free->data) {
2070         int planes = av_frame_get_channels(avci->to_free);
2071         int size   = planes * sizeof(*frame->extended_data);
2072
2073         if (!size) {
2074             av_frame_unref(frame);
2075             return AVERROR_BUG;
2076         }
2077
2078         frame->extended_data = av_malloc(size);
2079         if (!frame->extended_data) {
2080             av_frame_unref(frame);
2081             return AVERROR(ENOMEM);
2082         }
2083         memcpy(frame->extended_data, avci->to_free->extended_data,
2084                size);
2085     } else
2086         frame->extended_data = frame->data;
2087
2088     frame->format         = avci->to_free->format;
2089     frame->width          = avci->to_free->width;
2090     frame->height         = avci->to_free->height;
2091     frame->channel_layout = avci->to_free->channel_layout;
2092     frame->nb_samples     = avci->to_free->nb_samples;
2093     av_frame_set_channels(frame, av_frame_get_channels(avci->to_free));
2094
2095     return 0;
2096 }
2097
2098 int attribute_align_arg avcodec_decode_video2(AVCodecContext *avctx, AVFrame *picture,
2099                                               int *got_picture_ptr,
2100                                               const AVPacket *avpkt)
2101 {
2102     AVCodecInternal *avci = avctx->internal;
2103     int ret;
2104     // copy to ensure we do not change avpkt
2105     AVPacket tmp = *avpkt;
2106
2107     if (!avctx->codec)
2108         return AVERROR(EINVAL);
2109     if (avctx->codec->type != AVMEDIA_TYPE_VIDEO) {
2110         av_log(avctx, AV_LOG_ERROR, "Invalid media type for video\n");
2111         return AVERROR(EINVAL);
2112     }
2113
2114     *got_picture_ptr = 0;
2115     if ((avctx->coded_width || avctx->coded_height) && av_image_check_size(avctx->coded_width, avctx->coded_height, 0, avctx))
2116         return AVERROR(EINVAL);
2117
2118     av_frame_unref(picture);
2119
2120     if ((avctx->codec->capabilities & CODEC_CAP_DELAY) || avpkt->size || (avctx->active_thread_type & FF_THREAD_FRAME)) {
2121         int did_split = av_packet_split_side_data(&tmp);
2122         ret = apply_param_change(avctx, &tmp);
2123         if (ret < 0) {
2124             av_log(avctx, AV_LOG_ERROR, "Error applying parameter changes.\n");
2125             if (avctx->err_recognition & AV_EF_EXPLODE)
2126                 goto fail;
2127         }
2128
2129         avctx->internal->pkt = &tmp;
2130         if (HAVE_THREADS && avctx->active_thread_type & FF_THREAD_FRAME)
2131             ret = ff_thread_decode_frame(avctx, picture, got_picture_ptr,
2132                                          &tmp);
2133         else {
2134             ret = avctx->codec->decode(avctx, picture, got_picture_ptr,
2135                                        &tmp);
2136             picture->pkt_dts = avpkt->dts;
2137
2138             if(!avctx->has_b_frames){
2139                 av_frame_set_pkt_pos(picture, avpkt->pos);
2140             }
2141             //FIXME these should be under if(!avctx->has_b_frames)
2142             /* get_buffer is supposed to set frame parameters */
2143             if (!(avctx->codec->capabilities & CODEC_CAP_DR1)) {
2144                 if (!picture->sample_aspect_ratio.num)    picture->sample_aspect_ratio = avctx->sample_aspect_ratio;
2145                 if (!picture->width)                      picture->width               = avctx->width;
2146                 if (!picture->height)                     picture->height              = avctx->height;
2147                 if (picture->format == AV_PIX_FMT_NONE)   picture->format              = avctx->pix_fmt;
2148             }
2149         }
2150         add_metadata_from_side_data(avctx, picture);
2151
2152 fail:
2153         emms_c(); //needed to avoid an emms_c() call before every return;
2154
2155         avctx->internal->pkt = NULL;
2156         if (did_split) {
2157             av_packet_free_side_data(&tmp);
2158             if(ret == tmp.size)
2159                 ret = avpkt->size;
2160         }
2161
2162         if (*got_picture_ptr) {
2163             if (!avctx->refcounted_frames) {
2164                 int err = unrefcount_frame(avci, picture);
2165                 if (err < 0)
2166                     return err;
2167             }
2168
2169             avctx->frame_number++;
2170             av_frame_set_best_effort_timestamp(picture,
2171                                                guess_correct_pts(avctx,
2172                                                                  picture->pkt_pts,
2173                                                                  picture->pkt_dts));
2174         } else
2175             av_frame_unref(picture);
2176     } else
2177         ret = 0;
2178
2179     /* many decoders assign whole AVFrames, thus overwriting extended_data;
2180      * make sure it's set correctly */
2181     av_assert0(!picture->extended_data || picture->extended_data == picture->data);
2182
2183     return ret;
2184 }
2185
2186 #if FF_API_OLD_DECODE_AUDIO
2187 int attribute_align_arg avcodec_decode_audio3(AVCodecContext *avctx, int16_t *samples,
2188                                               int *frame_size_ptr,
2189                                               AVPacket *avpkt)
2190 {
2191     AVFrame *frame = av_frame_alloc();
2192     int ret, got_frame = 0;
2193
2194     if (!frame)
2195         return AVERROR(ENOMEM);
2196     if (avctx->get_buffer != avcodec_default_get_buffer) {
2197         av_log(avctx, AV_LOG_ERROR, "Custom get_buffer() for use with"
2198                                     "avcodec_decode_audio3() detected. Overriding with avcodec_default_get_buffer\n");
2199         av_log(avctx, AV_LOG_ERROR, "Please port your application to "
2200                                     "avcodec_decode_audio4()\n");
2201         avctx->get_buffer = avcodec_default_get_buffer;
2202         avctx->release_buffer = avcodec_default_release_buffer;
2203     }
2204
2205     ret = avcodec_decode_audio4(avctx, frame, &got_frame, avpkt);
2206
2207     if (ret >= 0 && got_frame) {
2208         int ch, plane_size;
2209         int planar    = av_sample_fmt_is_planar(avctx->sample_fmt);
2210         int data_size = av_samples_get_buffer_size(&plane_size, avctx->channels,
2211                                                    frame->nb_samples,
2212                                                    avctx->sample_fmt, 1);
2213         if (*frame_size_ptr < data_size) {
2214             av_log(avctx, AV_LOG_ERROR, "output buffer size is too small for "
2215                                         "the current frame (%d < %d)\n", *frame_size_ptr, data_size);
2216             av_frame_free(&frame);
2217             return AVERROR(EINVAL);
2218         }
2219
2220         memcpy(samples, frame->extended_data[0], plane_size);
2221
2222         if (planar && avctx->channels > 1) {
2223             uint8_t *out = ((uint8_t *)samples) + plane_size;
2224             for (ch = 1; ch < avctx->channels; ch++) {
2225                 memcpy(out, frame->extended_data[ch], plane_size);
2226                 out += plane_size;
2227             }
2228         }
2229         *frame_size_ptr = data_size;
2230     } else {
2231         *frame_size_ptr = 0;
2232     }
2233     av_frame_free(&frame);
2234     return ret;
2235 }
2236
2237 #endif
2238
2239 int attribute_align_arg avcodec_decode_audio4(AVCodecContext *avctx,
2240                                               AVFrame *frame,
2241                                               int *got_frame_ptr,
2242                                               const AVPacket *avpkt)
2243 {
2244     AVCodecInternal *avci = avctx->internal;
2245     int ret = 0;
2246
2247     *got_frame_ptr = 0;
2248
2249     if (!avpkt->data && avpkt->size) {
2250         av_log(avctx, AV_LOG_ERROR, "invalid packet: NULL data, size != 0\n");
2251         return AVERROR(EINVAL);
2252     }
2253     if (!avctx->codec)
2254         return AVERROR(EINVAL);
2255     if (avctx->codec->type != AVMEDIA_TYPE_AUDIO) {
2256         av_log(avctx, AV_LOG_ERROR, "Invalid media type for audio\n");
2257         return AVERROR(EINVAL);
2258     }
2259
2260     av_frame_unref(frame);
2261
2262     if ((avctx->codec->capabilities & CODEC_CAP_DELAY) || avpkt->size || (avctx->active_thread_type & FF_THREAD_FRAME)) {
2263         uint8_t *side;
2264         int side_size;
2265         uint32_t discard_padding = 0;
2266         // copy to ensure we do not change avpkt
2267         AVPacket tmp = *avpkt;
2268         int did_split = av_packet_split_side_data(&tmp);
2269         ret = apply_param_change(avctx, &tmp);
2270         if (ret < 0) {
2271             av_log(avctx, AV_LOG_ERROR, "Error applying parameter changes.\n");
2272             if (avctx->err_recognition & AV_EF_EXPLODE)
2273                 goto fail;
2274         }
2275
2276         avctx->internal->pkt = &tmp;
2277         if (HAVE_THREADS && avctx->active_thread_type & FF_THREAD_FRAME)
2278             ret = ff_thread_decode_frame(avctx, frame, got_frame_ptr, &tmp);
2279         else {
2280             ret = avctx->codec->decode(avctx, frame, got_frame_ptr, &tmp);
2281             frame->pkt_dts = avpkt->dts;
2282         }
2283         if (ret >= 0 && *got_frame_ptr) {
2284             add_metadata_from_side_data(avctx, frame);
2285             avctx->frame_number++;
2286             av_frame_set_best_effort_timestamp(frame,
2287                                                guess_correct_pts(avctx,
2288                                                                  frame->pkt_pts,
2289                                                                  frame->pkt_dts));
2290             if (frame->format == AV_SAMPLE_FMT_NONE)
2291                 frame->format = avctx->sample_fmt;
2292             if (!frame->channel_layout)
2293                 frame->channel_layout = avctx->channel_layout;
2294             if (!av_frame_get_channels(frame))
2295                 av_frame_set_channels(frame, avctx->channels);
2296             if (!frame->sample_rate)
2297                 frame->sample_rate = avctx->sample_rate;
2298         }
2299
2300         side= av_packet_get_side_data(avctx->internal->pkt, AV_PKT_DATA_SKIP_SAMPLES, &side_size);
2301         if(side && side_size>=10) {
2302             avctx->internal->skip_samples = AV_RL32(side);
2303             av_log(avctx, AV_LOG_DEBUG, "skip %d samples due to side data\n",
2304                    avctx->internal->skip_samples);
2305             discard_padding = AV_RL32(side + 4);
2306         }
2307         if (avctx->internal->skip_samples && *got_frame_ptr) {
2308             if(frame->nb_samples <= avctx->internal->skip_samples){
2309                 *got_frame_ptr = 0;
2310                 avctx->internal->skip_samples -= frame->nb_samples;
2311                 av_log(avctx, AV_LOG_DEBUG, "skip whole frame, skip left: %d\n",
2312                        avctx->internal->skip_samples);
2313             } else {
2314                 av_samples_copy(frame->extended_data, frame->extended_data, 0, avctx->internal->skip_samples,
2315                                 frame->nb_samples - avctx->internal->skip_samples, avctx->channels, frame->format);
2316                 if(avctx->pkt_timebase.num && avctx->sample_rate) {
2317                     int64_t diff_ts = av_rescale_q(avctx->internal->skip_samples,
2318                                                    (AVRational){1, avctx->sample_rate},
2319                                                    avctx->pkt_timebase);
2320                     if(frame->pkt_pts!=AV_NOPTS_VALUE)
2321                         frame->pkt_pts += diff_ts;
2322                     if(frame->pkt_dts!=AV_NOPTS_VALUE)
2323                         frame->pkt_dts += diff_ts;
2324                     if (av_frame_get_pkt_duration(frame) >= diff_ts)
2325                         av_frame_set_pkt_duration(frame, av_frame_get_pkt_duration(frame) - diff_ts);
2326                 } else {
2327                     av_log(avctx, AV_LOG_WARNING, "Could not update timestamps for skipped samples.\n");
2328                 }
2329                 av_log(avctx, AV_LOG_DEBUG, "skip %d/%d samples\n",
2330                        avctx->internal->skip_samples, frame->nb_samples);
2331                 frame->nb_samples -= avctx->internal->skip_samples;
2332                 avctx->internal->skip_samples = 0;
2333             }
2334         }
2335
2336         if (discard_padding > 0 && discard_padding <= frame->nb_samples && *got_frame_ptr) {
2337             if (discard_padding == frame->nb_samples) {
2338                 *got_frame_ptr = 0;
2339             } else {
2340                 if(avctx->pkt_timebase.num && avctx->sample_rate) {
2341                     int64_t diff_ts = av_rescale_q(frame->nb_samples - discard_padding,
2342                                                    (AVRational){1, avctx->sample_rate},
2343                                                    avctx->pkt_timebase);
2344                     if (av_frame_get_pkt_duration(frame) >= diff_ts)
2345                         av_frame_set_pkt_duration(frame, av_frame_get_pkt_duration(frame) - diff_ts);
2346                 } else {
2347                     av_log(avctx, AV_LOG_WARNING, "Could not update timestamps for discarded samples.\n");
2348                 }
2349                 av_log(avctx, AV_LOG_DEBUG, "discard %d/%d samples\n",
2350                        discard_padding, frame->nb_samples);
2351                 frame->nb_samples -= discard_padding;
2352             }
2353         }
2354 fail:
2355         avctx->internal->pkt = NULL;
2356         if (did_split) {
2357             av_packet_free_side_data(&tmp);
2358             if(ret == tmp.size)
2359                 ret = avpkt->size;
2360         }
2361
2362         if (ret >= 0 && *got_frame_ptr) {
2363             if (!avctx->refcounted_frames) {
2364                 int err = unrefcount_frame(avci, frame);
2365                 if (err < 0)
2366                     return err;
2367             }
2368         } else
2369             av_frame_unref(frame);
2370     }
2371
2372     return ret;
2373 }
2374
2375 #define UTF8_MAX_BYTES 4 /* 5 and 6 bytes sequences should not be used */
2376 static int recode_subtitle(AVCodecContext *avctx,
2377                            AVPacket *outpkt, const AVPacket *inpkt)
2378 {
2379 #if CONFIG_ICONV
2380     iconv_t cd = (iconv_t)-1;
2381     int ret = 0;
2382     char *inb, *outb;
2383     size_t inl, outl;
2384     AVPacket tmp;
2385 #endif
2386
2387     if (avctx->sub_charenc_mode != FF_SUB_CHARENC_MODE_PRE_DECODER || inpkt->size == 0)
2388         return 0;
2389
2390 #if CONFIG_ICONV
2391     cd = iconv_open("UTF-8", avctx->sub_charenc);
2392     av_assert0(cd != (iconv_t)-1);
2393
2394     inb = inpkt->data;
2395     inl = inpkt->size;
2396
2397     if (inl >= INT_MAX / UTF8_MAX_BYTES - FF_INPUT_BUFFER_PADDING_SIZE) {
2398         av_log(avctx, AV_LOG_ERROR, "Subtitles packet is too big for recoding\n");
2399         ret = AVERROR(ENOMEM);
2400         goto end;
2401     }
2402
2403     ret = av_new_packet(&tmp, inl * UTF8_MAX_BYTES);
2404     if (ret < 0)
2405         goto end;
2406     outpkt->buf  = tmp.buf;
2407     outpkt->data = tmp.data;
2408     outpkt->size = tmp.size;
2409     outb = outpkt->data;
2410     outl = outpkt->size;
2411
2412     if (iconv(cd, &inb, &inl, &outb, &outl) == (size_t)-1 ||
2413         iconv(cd, NULL, NULL, &outb, &outl) == (size_t)-1 ||
2414         outl >= outpkt->size || inl != 0) {
2415         av_log(avctx, AV_LOG_ERROR, "Unable to recode subtitle event \"%s\" "
2416                "from %s to UTF-8\n", inpkt->data, avctx->sub_charenc);
2417         av_free_packet(&tmp);
2418         ret = AVERROR(errno);
2419         goto end;
2420     }
2421     outpkt->size -= outl;
2422     memset(outpkt->data + outpkt->size, 0, outl);
2423
2424 end:
2425     if (cd != (iconv_t)-1)
2426         iconv_close(cd);
2427     return ret;
2428 #else
2429     av_assert0(!"requesting subtitles recoding without iconv");
2430 #endif
2431 }
2432
2433 static int utf8_check(const uint8_t *str)
2434 {
2435     const uint8_t *byte;
2436     uint32_t codepoint, min;
2437
2438     while (*str) {
2439         byte = str;
2440         GET_UTF8(codepoint, *(byte++), return 0;);
2441         min = byte - str == 1 ? 0 : byte - str == 2 ? 0x80 :
2442               1 << (5 * (byte - str) - 4);
2443         if (codepoint < min || codepoint >= 0x110000 ||
2444             codepoint == 0xFFFE /* BOM */ ||
2445             codepoint >= 0xD800 && codepoint <= 0xDFFF /* surrogates */)
2446             return 0;
2447         str = byte;
2448     }
2449     return 1;
2450 }
2451
2452 int avcodec_decode_subtitle2(AVCodecContext *avctx, AVSubtitle *sub,
2453                              int *got_sub_ptr,
2454                              AVPacket *avpkt)
2455 {
2456     int i, ret = 0;
2457
2458     if (!avpkt->data && avpkt->size) {
2459         av_log(avctx, AV_LOG_ERROR, "invalid packet: NULL data, size != 0\n");
2460         return AVERROR(EINVAL);
2461     }
2462     if (!avctx->codec)
2463         return AVERROR(EINVAL);
2464     if (avctx->codec->type != AVMEDIA_TYPE_SUBTITLE) {
2465         av_log(avctx, AV_LOG_ERROR, "Invalid media type for subtitles\n");
2466         return AVERROR(EINVAL);
2467     }
2468
2469     *got_sub_ptr = 0;
2470     avcodec_get_subtitle_defaults(sub);
2471
2472     if ((avctx->codec->capabilities & CODEC_CAP_DELAY) || avpkt->size) {
2473         AVPacket pkt_recoded;
2474         AVPacket tmp = *avpkt;
2475         int did_split = av_packet_split_side_data(&tmp);
2476         //apply_param_change(avctx, &tmp);
2477
2478         if (did_split) {
2479             /* FFMIN() prevents overflow in case the packet wasn't allocated with
2480              * proper padding.
2481              * If the side data is smaller than the buffer padding size, the
2482              * remaining bytes should have already been filled with zeros by the
2483              * original packet allocation anyway. */
2484             memset(tmp.data + tmp.size, 0,
2485                    FFMIN(avpkt->size - tmp.size, FF_INPUT_BUFFER_PADDING_SIZE));
2486         }
2487
2488         pkt_recoded = tmp;
2489         ret = recode_subtitle(avctx, &pkt_recoded, &tmp);
2490         if (ret < 0) {
2491             *got_sub_ptr = 0;
2492         } else {
2493             avctx->internal->pkt = &pkt_recoded;
2494
2495             if (avctx->pkt_timebase.den && avpkt->pts != AV_NOPTS_VALUE)
2496                 sub->pts = av_rescale_q(avpkt->pts,
2497                                         avctx->pkt_timebase, AV_TIME_BASE_Q);
2498             ret = avctx->codec->decode(avctx, sub, got_sub_ptr, &pkt_recoded);
2499             av_assert1((ret >= 0) >= !!*got_sub_ptr &&
2500                        !!*got_sub_ptr >= !!sub->num_rects);
2501
2502             if (sub->num_rects && !sub->end_display_time && avpkt->duration &&
2503                 avctx->pkt_timebase.num) {
2504                 AVRational ms = { 1, 1000 };
2505                 sub->end_display_time = av_rescale_q(avpkt->duration,
2506                                                      avctx->pkt_timebase, ms);
2507             }
2508
2509             for (i = 0; i < sub->num_rects; i++) {
2510                 if (sub->rects[i]->ass && !utf8_check(sub->rects[i]->ass)) {
2511                     av_log(avctx, AV_LOG_ERROR,
2512                            "Invalid UTF-8 in decoded subtitles text; "
2513                            "maybe missing -sub_charenc option\n");
2514                     avsubtitle_free(sub);
2515                     return AVERROR_INVALIDDATA;
2516                 }
2517             }
2518
2519             if (tmp.data != pkt_recoded.data) { // did we recode?
2520                 /* prevent from destroying side data from original packet */
2521                 pkt_recoded.side_data = NULL;
2522                 pkt_recoded.side_data_elems = 0;
2523
2524                 av_free_packet(&pkt_recoded);
2525             }
2526             if (avctx->codec_descriptor->props & AV_CODEC_PROP_BITMAP_SUB)
2527                 sub->format = 0;
2528             else if (avctx->codec_descriptor->props & AV_CODEC_PROP_TEXT_SUB)
2529                 sub->format = 1;
2530             avctx->internal->pkt = NULL;
2531         }
2532
2533         if (did_split) {
2534             av_packet_free_side_data(&tmp);
2535             if(ret == tmp.size)
2536                 ret = avpkt->size;
2537         }
2538
2539         if (*got_sub_ptr)
2540             avctx->frame_number++;
2541     }
2542
2543     return ret;
2544 }
2545
2546 void avsubtitle_free(AVSubtitle *sub)
2547 {
2548     int i;
2549
2550     for (i = 0; i < sub->num_rects; i++) {
2551         av_freep(&sub->rects[i]->pict.data[0]);
2552         av_freep(&sub->rects[i]->pict.data[1]);
2553         av_freep(&sub->rects[i]->pict.data[2]);
2554         av_freep(&sub->rects[i]->pict.data[3]);
2555         av_freep(&sub->rects[i]->text);
2556         av_freep(&sub->rects[i]->ass);
2557         av_freep(&sub->rects[i]);
2558     }
2559
2560     av_freep(&sub->rects);
2561
2562     memset(sub, 0, sizeof(AVSubtitle));
2563 }
2564
2565 av_cold int ff_codec_close_recursive(AVCodecContext *avctx)
2566 {
2567     int ret = 0;
2568
2569     ff_unlock_avcodec();
2570
2571     ret = avcodec_close(avctx);
2572
2573     ff_lock_avcodec(NULL);
2574     return ret;
2575 }
2576
2577 av_cold int avcodec_close(AVCodecContext *avctx)
2578 {
2579     int ret;
2580
2581     if (!avctx)
2582         return 0;
2583
2584     ret = ff_lock_avcodec(avctx);
2585     if (ret < 0)
2586         return ret;
2587
2588     if (avcodec_is_open(avctx)) {
2589         FramePool *pool = avctx->internal->pool;
2590         int i;
2591         if (CONFIG_FRAME_THREAD_ENCODER &&
2592             avctx->internal->frame_thread_encoder && avctx->thread_count > 1) {
2593             ff_unlock_avcodec();
2594             ff_frame_thread_encoder_free(avctx);
2595             ff_lock_avcodec(avctx);
2596         }
2597         if (HAVE_THREADS && avctx->internal->thread_ctx)
2598             ff_thread_free(avctx);
2599         if (avctx->codec && avctx->codec->close)
2600             avctx->codec->close(avctx);
2601         avctx->coded_frame = NULL;
2602         avctx->internal->byte_buffer_size = 0;
2603         av_freep(&avctx->internal->byte_buffer);
2604         av_frame_free(&avctx->internal->to_free);
2605         for (i = 0; i < FF_ARRAY_ELEMS(pool->pools); i++)
2606             av_buffer_pool_uninit(&pool->pools[i]);
2607         av_freep(&avctx->internal->pool);
2608         av_freep(&avctx->internal);
2609     }
2610
2611     if (avctx->priv_data && avctx->codec && avctx->codec->priv_class)
2612         av_opt_free(avctx->priv_data);
2613     av_opt_free(avctx);
2614     av_freep(&avctx->priv_data);
2615     if (av_codec_is_encoder(avctx->codec))
2616         av_freep(&avctx->extradata);
2617     avctx->codec = NULL;
2618     avctx->active_thread_type = 0;
2619
2620     ff_unlock_avcodec();
2621     return 0;
2622 }
2623
2624 static enum AVCodecID remap_deprecated_codec_id(enum AVCodecID id)
2625 {
2626     switch(id){
2627         //This is for future deprecatec codec ids, its empty since
2628         //last major bump but will fill up again over time, please don't remove it
2629 //         case AV_CODEC_ID_UTVIDEO_DEPRECATED: return AV_CODEC_ID_UTVIDEO;
2630         case AV_CODEC_ID_OPUS_DEPRECATED: return AV_CODEC_ID_OPUS;
2631         case AV_CODEC_ID_TAK_DEPRECATED : return AV_CODEC_ID_TAK;
2632         case AV_CODEC_ID_PCM_S24LE_PLANAR_DEPRECATED : return AV_CODEC_ID_PCM_S24LE_PLANAR;
2633         case AV_CODEC_ID_PCM_S32LE_PLANAR_DEPRECATED : return AV_CODEC_ID_PCM_S32LE_PLANAR;
2634         case AV_CODEC_ID_ESCAPE130_DEPRECATED : return AV_CODEC_ID_ESCAPE130;
2635         case AV_CODEC_ID_G2M_DEPRECATED : return AV_CODEC_ID_G2M;
2636         case AV_CODEC_ID_WEBP_DEPRECATED: return AV_CODEC_ID_WEBP;
2637         case AV_CODEC_ID_HEVC_DEPRECATED: return AV_CODEC_ID_HEVC;
2638         default                         : return id;
2639     }
2640 }
2641
2642 static AVCodec *find_encdec(enum AVCodecID id, int encoder)
2643 {
2644     AVCodec *p, *experimental = NULL;
2645     p = first_avcodec;
2646     id= remap_deprecated_codec_id(id);
2647     while (p) {
2648         if ((encoder ? av_codec_is_encoder(p) : av_codec_is_decoder(p)) &&
2649             p->id == id) {
2650             if (p->capabilities & CODEC_CAP_EXPERIMENTAL && !experimental) {
2651                 experimental = p;
2652             } else
2653                 return p;
2654         }
2655         p = p->next;
2656     }
2657     return experimental;
2658 }
2659
2660 AVCodec *avcodec_find_encoder(enum AVCodecID id)
2661 {
2662     return find_encdec(id, 1);
2663 }
2664
2665 AVCodec *avcodec_find_encoder_by_name(const char *name)
2666 {
2667     AVCodec *p;
2668     if (!name)
2669         return NULL;
2670     p = first_avcodec;
2671     while (p) {
2672         if (av_codec_is_encoder(p) && strcmp(name, p->name) == 0)
2673             return p;
2674         p = p->next;
2675     }
2676     return NULL;
2677 }
2678
2679 AVCodec *avcodec_find_decoder(enum AVCodecID id)
2680 {
2681     return find_encdec(id, 0);
2682 }
2683
2684 AVCodec *avcodec_find_decoder_by_name(const char *name)
2685 {
2686     AVCodec *p;
2687     if (!name)
2688         return NULL;
2689     p = first_avcodec;
2690     while (p) {
2691         if (av_codec_is_decoder(p) && strcmp(name, p->name) == 0)
2692             return p;
2693         p = p->next;
2694     }
2695     return NULL;
2696 }
2697
2698 const char *avcodec_get_name(enum AVCodecID id)
2699 {
2700     const AVCodecDescriptor *cd;
2701     AVCodec *codec;
2702
2703     if (id == AV_CODEC_ID_NONE)
2704         return "none";
2705     cd = avcodec_descriptor_get(id);
2706     if (cd)
2707         return cd->name;
2708     av_log(NULL, AV_LOG_WARNING, "Codec 0x%x is not in the full list.\n", id);
2709     codec = avcodec_find_decoder(id);
2710     if (codec)
2711         return codec->name;
2712     codec = avcodec_find_encoder(id);
2713     if (codec)
2714         return codec->name;
2715     return "unknown_codec";
2716 }
2717
2718 size_t av_get_codec_tag_string(char *buf, size_t buf_size, unsigned int codec_tag)
2719 {
2720     int i, len, ret = 0;
2721
2722 #define TAG_PRINT(x)                                              \
2723     (((x) >= '0' && (x) <= '9') ||                                \
2724      ((x) >= 'a' && (x) <= 'z') || ((x) >= 'A' && (x) <= 'Z') ||  \
2725      ((x) == '.' || (x) == ' ' || (x) == '-' || (x) == '_'))
2726
2727     for (i = 0; i < 4; i++) {
2728         len = snprintf(buf, buf_size,
2729                        TAG_PRINT(codec_tag & 0xFF) ? "%c" : "[%d]", codec_tag & 0xFF);
2730         buf        += len;
2731         buf_size    = buf_size > len ? buf_size - len : 0;
2732         ret        += len;
2733         codec_tag >>= 8;
2734     }
2735     return ret;
2736 }
2737
2738 void avcodec_string(char *buf, int buf_size, AVCodecContext *enc, int encode)
2739 {
2740     const char *codec_type;
2741     const char *codec_name;
2742     const char *profile = NULL;
2743     const AVCodec *p;
2744     int bitrate;
2745     AVRational display_aspect_ratio;
2746
2747     if (!buf || buf_size <= 0)
2748         return;
2749     codec_type = av_get_media_type_string(enc->codec_type);
2750     codec_name = avcodec_get_name(enc->codec_id);
2751     if (enc->profile != FF_PROFILE_UNKNOWN) {
2752         if (enc->codec)
2753             p = enc->codec;
2754         else
2755             p = encode ? avcodec_find_encoder(enc->codec_id) :
2756                         avcodec_find_decoder(enc->codec_id);
2757         if (p)
2758             profile = av_get_profile_name(p, enc->profile);
2759     }
2760
2761     snprintf(buf, buf_size, "%s: %s", codec_type ? codec_type : "unknown",
2762              codec_name);
2763     buf[0] ^= 'a' ^ 'A'; /* first letter in uppercase */
2764
2765     if (enc->codec && strcmp(enc->codec->name, codec_name))
2766         snprintf(buf + strlen(buf), buf_size - strlen(buf), " (%s)", enc->codec->name);
2767
2768     if (profile)
2769         snprintf(buf + strlen(buf), buf_size - strlen(buf), " (%s)", profile);
2770     if (enc->codec_tag) {
2771         char tag_buf[32];
2772         av_get_codec_tag_string(tag_buf, sizeof(tag_buf), enc->codec_tag);
2773         snprintf(buf + strlen(buf), buf_size - strlen(buf),
2774                  " (%s / 0x%04X)", tag_buf, enc->codec_tag);
2775     }
2776
2777     switch (enc->codec_type) {
2778     case AVMEDIA_TYPE_VIDEO:
2779         if (enc->pix_fmt != AV_PIX_FMT_NONE) {
2780             char detail[256] = "(";
2781             const char *colorspace_name;
2782             snprintf(buf + strlen(buf), buf_size - strlen(buf),
2783                      ", %s",
2784                      av_get_pix_fmt_name(enc->pix_fmt));
2785             if (enc->bits_per_raw_sample &&
2786                 enc->bits_per_raw_sample <= av_pix_fmt_desc_get(enc->pix_fmt)->comp[0].depth_minus1)
2787                 av_strlcatf(detail, sizeof(detail), "%d bpc, ", enc->bits_per_raw_sample);
2788             if (enc->color_range != AVCOL_RANGE_UNSPECIFIED)
2789                 av_strlcatf(detail, sizeof(detail),
2790                             enc->color_range == AVCOL_RANGE_MPEG ? "tv, ": "pc, ");
2791
2792             colorspace_name = av_get_colorspace_name(enc->colorspace);
2793             if (colorspace_name)
2794                 av_strlcatf(detail, sizeof(detail), "%s, ", colorspace_name);
2795
2796             if (strlen(detail) > 1) {
2797                 detail[strlen(detail) - 2] = 0;
2798                 av_strlcatf(buf, buf_size, "%s)", detail);
2799             }
2800         }
2801         if (enc->width) {
2802             snprintf(buf + strlen(buf), buf_size - strlen(buf),
2803                      ", %dx%d",
2804                      enc->width, enc->height);
2805             if (enc->sample_aspect_ratio.num) {
2806                 av_reduce(&display_aspect_ratio.num, &display_aspect_ratio.den,
2807                           enc->width * enc->sample_aspect_ratio.num,
2808                           enc->height * enc->sample_aspect_ratio.den,
2809                           1024 * 1024);
2810                 snprintf(buf + strlen(buf), buf_size - strlen(buf),
2811                          " [SAR %d:%d DAR %d:%d]",
2812                          enc->sample_aspect_ratio.num, enc->sample_aspect_ratio.den,
2813                          display_aspect_ratio.num, display_aspect_ratio.den);
2814             }
2815             if (av_log_get_level() >= AV_LOG_DEBUG) {
2816                 int g = av_gcd(enc->time_base.num, enc->time_base.den);
2817                 snprintf(buf + strlen(buf), buf_size - strlen(buf),
2818                          ", %d/%d",
2819                          enc->time_base.num / g, enc->time_base.den / g);
2820             }
2821         }
2822         if (encode) {
2823             snprintf(buf + strlen(buf), buf_size - strlen(buf),
2824                      ", q=%d-%d", enc->qmin, enc->qmax);
2825         }
2826         break;
2827     case AVMEDIA_TYPE_AUDIO:
2828         if (enc->sample_rate) {
2829             snprintf(buf + strlen(buf), buf_size - strlen(buf),
2830                      ", %d Hz", enc->sample_rate);
2831         }
2832         av_strlcat(buf, ", ", buf_size);
2833         av_get_channel_layout_string(buf + strlen(buf), buf_size - strlen(buf), enc->channels, enc->channel_layout);
2834         if (enc->sample_fmt != AV_SAMPLE_FMT_NONE) {
2835             snprintf(buf + strlen(buf), buf_size - strlen(buf),
2836                      ", %s", av_get_sample_fmt_name(enc->sample_fmt));
2837         }
2838         break;
2839     case AVMEDIA_TYPE_DATA:
2840         if (av_log_get_level() >= AV_LOG_DEBUG) {
2841             int g = av_gcd(enc->time_base.num, enc->time_base.den);
2842             if (g)
2843                 snprintf(buf + strlen(buf), buf_size - strlen(buf),
2844                          ", %d/%d",
2845                          enc->time_base.num / g, enc->time_base.den / g);
2846         }
2847         break;
2848     case AVMEDIA_TYPE_SUBTITLE:
2849         if (enc->width)
2850             snprintf(buf + strlen(buf), buf_size - strlen(buf),
2851                      ", %dx%d", enc->width, enc->height);
2852         break;
2853     default:
2854         return;
2855     }
2856     if (encode) {
2857         if (enc->flags & CODEC_FLAG_PASS1)
2858             snprintf(buf + strlen(buf), buf_size - strlen(buf),
2859                      ", pass 1");
2860         if (enc->flags & CODEC_FLAG_PASS2)
2861             snprintf(buf + strlen(buf), buf_size - strlen(buf),
2862                      ", pass 2");
2863     }
2864     bitrate = get_bit_rate(enc);
2865     if (bitrate != 0) {
2866         snprintf(buf + strlen(buf), buf_size - strlen(buf),
2867                  ", %d kb/s", bitrate / 1000);
2868     } else if (enc->rc_max_rate > 0) {
2869         snprintf(buf + strlen(buf), buf_size - strlen(buf),
2870                  ", max. %d kb/s", enc->rc_max_rate / 1000);
2871     }
2872 }
2873
2874 const char *av_get_profile_name(const AVCodec *codec, int profile)
2875 {
2876     const AVProfile *p;
2877     if (profile == FF_PROFILE_UNKNOWN || !codec->profiles)
2878         return NULL;
2879
2880     for (p = codec->profiles; p->profile != FF_PROFILE_UNKNOWN; p++)
2881         if (p->profile == profile)
2882             return p->name;
2883
2884     return NULL;
2885 }
2886
2887 unsigned avcodec_version(void)
2888 {
2889 //    av_assert0(AV_CODEC_ID_V410==164);
2890     av_assert0(AV_CODEC_ID_PCM_S8_PLANAR==65563);
2891     av_assert0(AV_CODEC_ID_ADPCM_G722==69660);
2892 //     av_assert0(AV_CODEC_ID_BMV_AUDIO==86071);
2893     av_assert0(AV_CODEC_ID_SRT==94216);
2894     av_assert0(LIBAVCODEC_VERSION_MICRO >= 100);
2895
2896     av_assert0(CODEC_ID_CLLC == AV_CODEC_ID_CLLC);
2897     av_assert0(CODEC_ID_PCM_S8_PLANAR == AV_CODEC_ID_PCM_S8_PLANAR);
2898     av_assert0(CODEC_ID_ADPCM_IMA_APC == AV_CODEC_ID_ADPCM_IMA_APC);
2899     av_assert0(CODEC_ID_ILBC == AV_CODEC_ID_ILBC);
2900     av_assert0(CODEC_ID_SRT == AV_CODEC_ID_SRT);
2901     return LIBAVCODEC_VERSION_INT;
2902 }
2903
2904 const char *avcodec_configuration(void)
2905 {
2906     return FFMPEG_CONFIGURATION;
2907 }
2908
2909 const char *avcodec_license(void)
2910 {
2911 #define LICENSE_PREFIX "libavcodec license: "
2912     return LICENSE_PREFIX FFMPEG_LICENSE + sizeof(LICENSE_PREFIX) - 1;
2913 }
2914
2915 void avcodec_flush_buffers(AVCodecContext *avctx)
2916 {
2917     if (HAVE_THREADS && avctx->active_thread_type & FF_THREAD_FRAME)
2918         ff_thread_flush(avctx);
2919     else if (avctx->codec->flush)
2920         avctx->codec->flush(avctx);
2921
2922     avctx->pts_correction_last_pts =
2923     avctx->pts_correction_last_dts = INT64_MIN;
2924
2925     if (!avctx->refcounted_frames)
2926         av_frame_unref(avctx->internal->to_free);
2927 }
2928
2929 int av_get_exact_bits_per_sample(enum AVCodecID codec_id)
2930 {
2931     switch (codec_id) {
2932     case AV_CODEC_ID_8SVX_EXP:
2933     case AV_CODEC_ID_8SVX_FIB:
2934     case AV_CODEC_ID_ADPCM_CT:
2935     case AV_CODEC_ID_ADPCM_IMA_APC:
2936     case AV_CODEC_ID_ADPCM_IMA_EA_SEAD:
2937     case AV_CODEC_ID_ADPCM_IMA_OKI:
2938     case AV_CODEC_ID_ADPCM_IMA_WS:
2939     case AV_CODEC_ID_ADPCM_G722:
2940     case AV_CODEC_ID_ADPCM_YAMAHA:
2941         return 4;
2942     case AV_CODEC_ID_PCM_ALAW:
2943     case AV_CODEC_ID_PCM_MULAW:
2944     case AV_CODEC_ID_PCM_S8:
2945     case AV_CODEC_ID_PCM_S8_PLANAR:
2946     case AV_CODEC_ID_PCM_U8:
2947     case AV_CODEC_ID_PCM_ZORK:
2948         return 8;
2949     case AV_CODEC_ID_PCM_S16BE:
2950     case AV_CODEC_ID_PCM_S16BE_PLANAR:
2951     case AV_CODEC_ID_PCM_S16LE:
2952     case AV_CODEC_ID_PCM_S16LE_PLANAR:
2953     case AV_CODEC_ID_PCM_U16BE:
2954     case AV_CODEC_ID_PCM_U16LE:
2955         return 16;
2956     case AV_CODEC_ID_PCM_S24DAUD:
2957     case AV_CODEC_ID_PCM_S24BE:
2958     case AV_CODEC_ID_PCM_S24LE:
2959     case AV_CODEC_ID_PCM_S24LE_PLANAR:
2960     case AV_CODEC_ID_PCM_U24BE:
2961     case AV_CODEC_ID_PCM_U24LE:
2962         return 24;
2963     case AV_CODEC_ID_PCM_S32BE:
2964     case AV_CODEC_ID_PCM_S32LE:
2965     case AV_CODEC_ID_PCM_S32LE_PLANAR:
2966     case AV_CODEC_ID_PCM_U32BE:
2967     case AV_CODEC_ID_PCM_U32LE:
2968     case AV_CODEC_ID_PCM_F32BE:
2969     case AV_CODEC_ID_PCM_F32LE:
2970         return 32;
2971     case AV_CODEC_ID_PCM_F64BE:
2972     case AV_CODEC_ID_PCM_F64LE:
2973         return 64;
2974     default:
2975         return 0;
2976     }
2977 }
2978
2979 enum AVCodecID av_get_pcm_codec(enum AVSampleFormat fmt, int be)
2980 {
2981     static const enum AVCodecID map[AV_SAMPLE_FMT_NB][2] = {
2982         [AV_SAMPLE_FMT_U8  ] = { AV_CODEC_ID_PCM_U8,    AV_CODEC_ID_PCM_U8    },
2983         [AV_SAMPLE_FMT_S16 ] = { AV_CODEC_ID_PCM_S16LE, AV_CODEC_ID_PCM_S16BE },
2984         [AV_SAMPLE_FMT_S32 ] = { AV_CODEC_ID_PCM_S32LE, AV_CODEC_ID_PCM_S32BE },
2985         [AV_SAMPLE_FMT_FLT ] = { AV_CODEC_ID_PCM_F32LE, AV_CODEC_ID_PCM_F32BE },
2986         [AV_SAMPLE_FMT_DBL ] = { AV_CODEC_ID_PCM_F64LE, AV_CODEC_ID_PCM_F64BE },
2987         [AV_SAMPLE_FMT_U8P ] = { AV_CODEC_ID_PCM_U8,    AV_CODEC_ID_PCM_U8    },
2988         [AV_SAMPLE_FMT_S16P] = { AV_CODEC_ID_PCM_S16LE, AV_CODEC_ID_PCM_S16BE },
2989         [AV_SAMPLE_FMT_S32P] = { AV_CODEC_ID_PCM_S32LE, AV_CODEC_ID_PCM_S32BE },
2990         [AV_SAMPLE_FMT_FLTP] = { AV_CODEC_ID_PCM_F32LE, AV_CODEC_ID_PCM_F32BE },
2991         [AV_SAMPLE_FMT_DBLP] = { AV_CODEC_ID_PCM_F64LE, AV_CODEC_ID_PCM_F64BE },
2992     };
2993     if (fmt < 0 || fmt >= AV_SAMPLE_FMT_NB)
2994         return AV_CODEC_ID_NONE;
2995     if (be < 0 || be > 1)
2996         be = AV_NE(1, 0);
2997     return map[fmt][be];
2998 }
2999
3000 int av_get_bits_per_sample(enum AVCodecID codec_id)
3001 {
3002     switch (codec_id) {
3003     case AV_CODEC_ID_ADPCM_SBPRO_2:
3004         return 2;
3005     case AV_CODEC_ID_ADPCM_SBPRO_3:
3006         return 3;
3007     case AV_CODEC_ID_ADPCM_SBPRO_4:
3008     case AV_CODEC_ID_ADPCM_IMA_WAV:
3009     case AV_CODEC_ID_ADPCM_IMA_QT:
3010     case AV_CODEC_ID_ADPCM_SWF:
3011     case AV_CODEC_ID_ADPCM_MS:
3012         return 4;
3013     default:
3014         return av_get_exact_bits_per_sample(codec_id);
3015     }
3016 }
3017
3018 int av_get_audio_frame_duration(AVCodecContext *avctx, int frame_bytes)
3019 {
3020     int id, sr, ch, ba, tag, bps;
3021
3022     id  = avctx->codec_id;
3023     sr  = avctx->sample_rate;
3024     ch  = avctx->channels;
3025     ba  = avctx->block_align;
3026     tag = avctx->codec_tag;
3027     bps = av_get_exact_bits_per_sample(avctx->codec_id);
3028
3029     /* codecs with an exact constant bits per sample */
3030     if (bps > 0 && ch > 0 && frame_bytes > 0 && ch < 32768 && bps < 32768)
3031         return (frame_bytes * 8LL) / (bps * ch);
3032     bps = avctx->bits_per_coded_sample;
3033
3034     /* codecs with a fixed packet duration */
3035     switch (id) {
3036     case AV_CODEC_ID_ADPCM_ADX:    return   32;
3037     case AV_CODEC_ID_ADPCM_IMA_QT: return   64;
3038     case AV_CODEC_ID_ADPCM_EA_XAS: return  128;
3039     case AV_CODEC_ID_AMR_NB:
3040     case AV_CODEC_ID_EVRC:
3041     case AV_CODEC_ID_GSM:
3042     case AV_CODEC_ID_QCELP:
3043     case AV_CODEC_ID_RA_288:       return  160;
3044     case AV_CODEC_ID_AMR_WB:
3045     case AV_CODEC_ID_GSM_MS:       return  320;
3046     case AV_CODEC_ID_MP1:          return  384;
3047     case AV_CODEC_ID_ATRAC1:       return  512;
3048     case AV_CODEC_ID_ATRAC3:       return 1024;
3049     case AV_CODEC_ID_MP2:
3050     case AV_CODEC_ID_MUSEPACK7:    return 1152;
3051     case AV_CODEC_ID_AC3:          return 1536;
3052     }
3053
3054     if (sr > 0) {
3055         /* calc from sample rate */
3056         if (id == AV_CODEC_ID_TTA)
3057             return 256 * sr / 245;
3058
3059         if (ch > 0) {
3060             /* calc from sample rate and channels */
3061             if (id == AV_CODEC_ID_BINKAUDIO_DCT)
3062                 return (480 << (sr / 22050)) / ch;
3063         }
3064     }
3065
3066     if (ba > 0) {
3067         /* calc from block_align */
3068         if (id == AV_CODEC_ID_SIPR) {
3069             switch (ba) {
3070             case 20: return 160;
3071             case 19: return 144;
3072             case 29: return 288;
3073             case 37: return 480;
3074             }
3075         } else if (id == AV_CODEC_ID_ILBC) {
3076             switch (ba) {
3077             case 38: return 160;
3078             case 50: return 240;
3079             }
3080         }
3081     }
3082
3083     if (frame_bytes > 0) {
3084         /* calc from frame_bytes only */
3085         if (id == AV_CODEC_ID_TRUESPEECH)
3086             return 240 * (frame_bytes / 32);
3087         if (id == AV_CODEC_ID_NELLYMOSER)
3088             return 256 * (frame_bytes / 64);
3089         if (id == AV_CODEC_ID_RA_144)
3090             return 160 * (frame_bytes / 20);
3091         if (id == AV_CODEC_ID_G723_1)
3092             return 240 * (frame_bytes / 24);
3093
3094         if (bps > 0) {
3095             /* calc from frame_bytes and bits_per_coded_sample */
3096             if (id == AV_CODEC_ID_ADPCM_G726)
3097                 return frame_bytes * 8 / bps;
3098         }
3099
3100         if (ch > 0) {
3101             /* calc from frame_bytes and channels */
3102             switch (id) {
3103             case AV_CODEC_ID_ADPCM_AFC:
3104                 return frame_bytes / (9 * ch) * 16;
3105             case AV_CODEC_ID_ADPCM_DTK:
3106                 return frame_bytes / (16 * ch) * 28;
3107             case AV_CODEC_ID_ADPCM_4XM:
3108             case AV_CODEC_ID_ADPCM_IMA_ISS:
3109                 return (frame_bytes - 4 * ch) * 2 / ch;
3110             case AV_CODEC_ID_ADPCM_IMA_SMJPEG:
3111                 return (frame_bytes - 4) * 2 / ch;
3112             case AV_CODEC_ID_ADPCM_IMA_AMV:
3113                 return (frame_bytes - 8) * 2 / ch;
3114             case AV_CODEC_ID_ADPCM_XA:
3115                 return (frame_bytes / 128) * 224 / ch;
3116             case AV_CODEC_ID_INTERPLAY_DPCM:
3117                 return (frame_bytes - 6 - ch) / ch;
3118             case AV_CODEC_ID_ROQ_DPCM:
3119                 return (frame_bytes - 8) / ch;
3120             case AV_CODEC_ID_XAN_DPCM:
3121                 return (frame_bytes - 2 * ch) / ch;
3122             case AV_CODEC_ID_MACE3:
3123                 return 3 * frame_bytes / ch;
3124             case AV_CODEC_ID_MACE6:
3125                 return 6 * frame_bytes / ch;
3126             case AV_CODEC_ID_PCM_LXF:
3127                 return 2 * (frame_bytes / (5 * ch));
3128             case AV_CODEC_ID_IAC:
3129             case AV_CODEC_ID_IMC:
3130                 return 4 * frame_bytes / ch;
3131             }
3132
3133             if (tag) {
3134                 /* calc from frame_bytes, channels, and codec_tag */
3135                 if (id == AV_CODEC_ID_SOL_DPCM) {
3136                     if (tag == 3)
3137                         return frame_bytes / ch;
3138                     else
3139                         return frame_bytes * 2 / ch;
3140                 }
3141             }
3142
3143             if (ba > 0) {
3144                 /* calc from frame_bytes, channels, and block_align */
3145                 int blocks = frame_bytes / ba;
3146                 switch (avctx->codec_id) {
3147                 case AV_CODEC_ID_ADPCM_IMA_WAV:
3148                     if (bps < 2 || bps > 5)
3149                         return 0;
3150                     return blocks * (1 + (ba - 4 * ch) / (bps * ch) * 8);
3151                 case AV_CODEC_ID_ADPCM_IMA_DK3:
3152                     return blocks * (((ba - 16) * 2 / 3 * 4) / ch);
3153                 case AV_CODEC_ID_ADPCM_IMA_DK4:
3154                     return blocks * (1 + (ba - 4 * ch) * 2 / ch);
3155                 case AV_CODEC_ID_ADPCM_IMA_RAD:
3156                     return blocks * ((ba - 4 * ch) * 2 / ch);
3157                 case AV_CODEC_ID_ADPCM_MS:
3158                     return blocks * (2 + (ba - 7 * ch) * 2 / ch);
3159                 }
3160             }
3161
3162             if (bps > 0) {
3163                 /* calc from frame_bytes, channels, and bits_per_coded_sample */
3164                 switch (avctx->codec_id) {
3165                 case AV_CODEC_ID_PCM_DVD:
3166                     if(bps<4)
3167                         return 0;
3168                     return 2 * (frame_bytes / ((bps * 2 / 8) * ch));
3169                 case AV_CODEC_ID_PCM_BLURAY:
3170                     if(bps<4)
3171                         return 0;
3172                     return frame_bytes / ((FFALIGN(ch, 2) * bps) / 8);
3173                 case AV_CODEC_ID_S302M:
3174                     return 2 * (frame_bytes / ((bps + 4) / 4)) / ch;
3175                 }
3176             }
3177         }
3178     }
3179
3180     return 0;
3181 }
3182
3183 #if !HAVE_THREADS
3184 int ff_thread_init(AVCodecContext *s)
3185 {
3186     return -1;
3187 }
3188
3189 #endif
3190
3191 unsigned int av_xiphlacing(unsigned char *s, unsigned int v)
3192 {
3193     unsigned int n = 0;
3194
3195     while (v >= 0xff) {
3196         *s++ = 0xff;
3197         v -= 0xff;
3198         n++;
3199     }
3200     *s = v;
3201     n++;
3202     return n;
3203 }
3204
3205 int ff_match_2uint16(const uint16_t(*tab)[2], int size, int a, int b)
3206 {
3207     int i;
3208     for (i = 0; i < size && !(tab[i][0] == a && tab[i][1] == b); i++) ;
3209     return i;
3210 }
3211
3212 #if FF_API_MISSING_SAMPLE
3213 FF_DISABLE_DEPRECATION_WARNINGS
3214 void av_log_missing_feature(void *avc, const char *feature, int want_sample)
3215 {
3216     av_log(avc, AV_LOG_WARNING, "%s is not implemented. Update your FFmpeg "
3217             "version to the newest one from Git. If the problem still "
3218             "occurs, it means that your file has a feature which has not "
3219             "been implemented.\n", feature);
3220     if(want_sample)
3221         av_log_ask_for_sample(avc, NULL);
3222 }
3223
3224 void av_log_ask_for_sample(void *avc, const char *msg, ...)
3225 {
3226     va_list argument_list;
3227
3228     va_start(argument_list, msg);
3229
3230     if (msg)
3231         av_vlog(avc, AV_LOG_WARNING, msg, argument_list);
3232     av_log(avc, AV_LOG_WARNING, "If you want to help, upload a sample "
3233             "of this file to ftp://upload.ffmpeg.org/MPlayer/incoming/ "
3234             "and contact the ffmpeg-devel mailing list.\n");
3235
3236     va_end(argument_list);
3237 }
3238 FF_ENABLE_DEPRECATION_WARNINGS
3239 #endif /* FF_API_MISSING_SAMPLE */
3240
3241 static AVHWAccel *first_hwaccel = NULL;
3242 static AVHWAccel **last_hwaccel = &first_hwaccel;
3243
3244 void av_register_hwaccel(AVHWAccel *hwaccel)
3245 {
3246     AVHWAccel **p = last_hwaccel;
3247     hwaccel->next = NULL;
3248     while(*p || avpriv_atomic_ptr_cas((void * volatile *)p, NULL, hwaccel))
3249         p = &(*p)->next;
3250     last_hwaccel = &hwaccel->next;
3251 }
3252
3253 AVHWAccel *av_hwaccel_next(AVHWAccel *hwaccel)
3254 {
3255     return hwaccel ? hwaccel->next : first_hwaccel;
3256 }
3257
3258 AVHWAccel *ff_find_hwaccel(AVCodecContext *avctx)
3259 {
3260     enum AVCodecID codec_id = avctx->codec->id;
3261     enum AVPixelFormat pix_fmt = avctx->pix_fmt;
3262
3263     AVHWAccel *hwaccel = NULL;
3264
3265     while ((hwaccel = av_hwaccel_next(hwaccel)))
3266         if (hwaccel->id == codec_id
3267             && hwaccel->pix_fmt == pix_fmt)
3268             return hwaccel;
3269     return NULL;
3270 }
3271
3272 int av_lockmgr_register(int (*cb)(void **mutex, enum AVLockOp op))
3273 {
3274     if (lockmgr_cb) {
3275         if (lockmgr_cb(&codec_mutex, AV_LOCK_DESTROY))
3276             return -1;
3277         if (lockmgr_cb(&avformat_mutex, AV_LOCK_DESTROY))
3278             return -1;
3279     }
3280
3281     lockmgr_cb = cb;
3282
3283     if (lockmgr_cb) {
3284         if (lockmgr_cb(&codec_mutex, AV_LOCK_CREATE))
3285             return -1;
3286         if (lockmgr_cb(&avformat_mutex, AV_LOCK_CREATE))
3287             return -1;
3288     }
3289     return 0;
3290 }
3291
3292 int ff_lock_avcodec(AVCodecContext *log_ctx)
3293 {
3294     if (lockmgr_cb) {
3295         if ((*lockmgr_cb)(&codec_mutex, AV_LOCK_OBTAIN))
3296             return -1;
3297     }
3298     entangled_thread_counter++;
3299     if (entangled_thread_counter != 1) {
3300         av_log(log_ctx, AV_LOG_ERROR, "Insufficient thread locking around avcodec_open/close()\n");
3301         if (!lockmgr_cb)
3302             av_log(log_ctx, AV_LOG_ERROR, "No lock manager is set, please see av_lockmgr_register()\n");
3303         ff_avcodec_locked = 1;
3304         ff_unlock_avcodec();
3305         return AVERROR(EINVAL);
3306     }
3307     av_assert0(!ff_avcodec_locked);
3308     ff_avcodec_locked = 1;
3309     return 0;
3310 }
3311
3312 int ff_unlock_avcodec(void)
3313 {
3314     av_assert0(ff_avcodec_locked);
3315     ff_avcodec_locked = 0;
3316     entangled_thread_counter--;
3317     if (lockmgr_cb) {
3318         if ((*lockmgr_cb)(&codec_mutex, AV_LOCK_RELEASE))
3319             return -1;
3320     }
3321     return 0;
3322 }
3323
3324 int avpriv_lock_avformat(void)
3325 {
3326     if (lockmgr_cb) {
3327         if ((*lockmgr_cb)(&avformat_mutex, AV_LOCK_OBTAIN))
3328             return -1;
3329     }
3330     return 0;
3331 }
3332
3333 int avpriv_unlock_avformat(void)
3334 {
3335     if (lockmgr_cb) {
3336         if ((*lockmgr_cb)(&avformat_mutex, AV_LOCK_RELEASE))
3337             return -1;
3338     }
3339     return 0;
3340 }
3341
3342 unsigned int avpriv_toupper4(unsigned int x)
3343 {
3344     return av_toupper(x & 0xFF) +
3345           (av_toupper((x >>  8) & 0xFF) << 8)  +
3346           (av_toupper((x >> 16) & 0xFF) << 16) +
3347           (av_toupper((x >> 24) & 0xFF) << 24);
3348 }
3349
3350 int ff_thread_ref_frame(ThreadFrame *dst, ThreadFrame *src)
3351 {
3352     int ret;
3353
3354     dst->owner = src->owner;
3355
3356     ret = av_frame_ref(dst->f, src->f);
3357     if (ret < 0)
3358         return ret;
3359
3360     if (src->progress &&
3361         !(dst->progress = av_buffer_ref(src->progress))) {
3362         ff_thread_release_buffer(dst->owner, dst);
3363         return AVERROR(ENOMEM);
3364     }
3365
3366     return 0;
3367 }
3368
3369 #if !HAVE_THREADS
3370
3371 enum AVPixelFormat ff_thread_get_format(AVCodecContext *avctx, const enum AVPixelFormat *fmt)
3372 {
3373     return avctx->get_format(avctx, fmt);
3374 }
3375
3376 int ff_thread_get_buffer(AVCodecContext *avctx, ThreadFrame *f, int flags)
3377 {
3378     f->owner = avctx;
3379     return ff_get_buffer(avctx, f->f, flags);
3380 }
3381
3382 void ff_thread_release_buffer(AVCodecContext *avctx, ThreadFrame *f)
3383 {
3384     av_frame_unref(f->f);
3385 }
3386
3387 void ff_thread_finish_setup(AVCodecContext *avctx)
3388 {
3389 }
3390
3391 void ff_thread_report_progress(ThreadFrame *f, int progress, int field)
3392 {
3393 }
3394
3395 void ff_thread_await_progress(ThreadFrame *f, int progress, int field)
3396 {
3397 }
3398
3399 int ff_thread_can_start_frame(AVCodecContext *avctx)
3400 {
3401     return 1;
3402 }
3403
3404 int ff_alloc_entries(AVCodecContext *avctx, int count)
3405 {
3406     return 0;
3407 }
3408
3409 void ff_reset_entries(AVCodecContext *avctx)
3410 {
3411 }
3412
3413 void ff_thread_await_progress2(AVCodecContext *avctx, int field, int thread, int shift)
3414 {
3415 }
3416
3417 void ff_thread_report_progress2(AVCodecContext *avctx, int field, int thread, int n)
3418 {
3419 }
3420
3421 #endif
3422
3423 enum AVMediaType avcodec_get_type(enum AVCodecID codec_id)
3424 {
3425     AVCodec *c= avcodec_find_decoder(codec_id);
3426     if(!c)
3427         c= avcodec_find_encoder(codec_id);
3428     if(c)
3429         return c->type;
3430
3431     if (codec_id <= AV_CODEC_ID_NONE)
3432         return AVMEDIA_TYPE_UNKNOWN;
3433     else if (codec_id < AV_CODEC_ID_FIRST_AUDIO)
3434         return AVMEDIA_TYPE_VIDEO;
3435     else if (codec_id < AV_CODEC_ID_FIRST_SUBTITLE)
3436         return AVMEDIA_TYPE_AUDIO;
3437     else if (codec_id < AV_CODEC_ID_FIRST_UNKNOWN)
3438         return AVMEDIA_TYPE_SUBTITLE;
3439
3440     return AVMEDIA_TYPE_UNKNOWN;
3441 }
3442
3443 int avcodec_is_open(AVCodecContext *s)
3444 {
3445     return !!s->internal;
3446 }
3447
3448 int avpriv_bprint_to_extradata(AVCodecContext *avctx, struct AVBPrint *buf)
3449 {
3450     int ret;
3451     char *str;
3452
3453     ret = av_bprint_finalize(buf, &str);
3454     if (ret < 0)
3455         return ret;
3456     avctx->extradata = str;
3457     /* Note: the string is NUL terminated (so extradata can be read as a
3458      * string), but the ending character is not accounted in the size (in
3459      * binary formats you are likely not supposed to mux that character). When
3460      * extradata is copied, it is also padded with FF_INPUT_BUFFER_PADDING_SIZE
3461      * zeros. */
3462     avctx->extradata_size = buf->len;
3463     return 0;
3464 }
3465
3466 const uint8_t *avpriv_find_start_code(const uint8_t *av_restrict p,
3467                                       const uint8_t *end,
3468                                       uint32_t *av_restrict state)
3469 {
3470     int i;
3471
3472     av_assert0(p <= end);
3473     if (p >= end)
3474         return end;
3475
3476     for (i = 0; i < 3; i++) {
3477         uint32_t tmp = *state << 8;
3478         *state = tmp + *(p++);
3479         if (tmp == 0x100 || p == end)
3480             return p;
3481     }
3482
3483     while (p < end) {
3484         if      (p[-1] > 1      ) p += 3;
3485         else if (p[-2]          ) p += 2;
3486         else if (p[-3]|(p[-1]-1)) p++;
3487         else {
3488             p++;
3489             break;
3490         }
3491     }
3492
3493     p = FFMIN(p, end) - 4;
3494     *state = AV_RB32(p);
3495
3496     return p + 4;
3497 }