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