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