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