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