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