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