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