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