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