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