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