OSDN Git Service

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