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