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