]> git.sesse.net Git - ffmpeg/blob - libavcodec/utils.c
2a78f7fc0ed5de4edc9b9ff4abefc8f5043f2f3c
[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 Libav.
7  *
8  * Libav 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  * Libav 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 Libav; if not, write to the Free Software
20  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
21  */
22
23 /**
24  * @file
25  * utils.
26  */
27
28 #include "config.h"
29 #include "libavutil/avassert.h"
30 #include "libavutil/avstring.h"
31 #include "libavutil/channel_layout.h"
32 #include "libavutil/crc.h"
33 #include "libavutil/mathematics.h"
34 #include "libavutil/pixdesc.h"
35 #include "libavutil/imgutils.h"
36 #include "libavutil/samplefmt.h"
37 #include "libavutil/dict.h"
38 #include "avcodec.h"
39 #include "dsputil.h"
40 #include "libavutil/opt.h"
41 #include "thread.h"
42 #include "internal.h"
43 #include "bytestream.h"
44 #include <stdlib.h>
45 #include <stdarg.h>
46 #include <limits.h>
47 #include <float.h>
48
49 static int volatile entangled_thread_counter = 0;
50 static int (*ff_lockmgr_cb)(void **mutex, enum AVLockOp op);
51 static void *codec_mutex;
52 static void *avformat_mutex;
53
54 void *av_fast_realloc(void *ptr, unsigned int *size, size_t min_size)
55 {
56     if (min_size < *size)
57         return ptr;
58
59     min_size = FFMAX(17 * min_size / 16 + 32, min_size);
60
61     ptr = av_realloc(ptr, min_size);
62     /* we could set this to the unmodified min_size but this is safer
63      * if the user lost the ptr and uses NULL now
64      */
65     if (!ptr)
66         min_size = 0;
67
68     *size = min_size;
69
70     return ptr;
71 }
72
73 void av_fast_malloc(void *ptr, unsigned int *size, size_t min_size)
74 {
75     void **p = ptr;
76     if (min_size < *size)
77         return;
78     min_size = FFMAX(17 * min_size / 16 + 32, min_size);
79     av_free(*p);
80     *p = av_malloc(min_size);
81     if (!*p)
82         min_size = 0;
83     *size = min_size;
84 }
85
86 void av_fast_padded_malloc(void *ptr, unsigned int *size, size_t min_size)
87 {
88     void **p = ptr;
89     if (min_size > SIZE_MAX - FF_INPUT_BUFFER_PADDING_SIZE) {
90         av_freep(p);
91         *size = 0;
92         return;
93     }
94     av_fast_malloc(p, size, min_size + FF_INPUT_BUFFER_PADDING_SIZE);
95     if (*size)
96         memset((uint8_t *)*p + min_size, 0, FF_INPUT_BUFFER_PADDING_SIZE);
97 }
98
99 /* encoder management */
100 static AVCodec *first_avcodec = NULL;
101
102 AVCodec *av_codec_next(const AVCodec *c)
103 {
104     if (c)
105         return c->next;
106     else
107         return first_avcodec;
108 }
109
110 static void avcodec_init(void)
111 {
112     static int initialized = 0;
113
114     if (initialized != 0)
115         return;
116     initialized = 1;
117
118     ff_dsputil_static_init();
119 }
120
121 int av_codec_is_encoder(const AVCodec *codec)
122 {
123     return codec && (codec->encode_sub || codec->encode2);
124 }
125
126 int av_codec_is_decoder(const AVCodec *codec)
127 {
128     return codec && codec->decode;
129 }
130
131 void avcodec_register(AVCodec *codec)
132 {
133     AVCodec **p;
134     avcodec_init();
135     p = &first_avcodec;
136     while (*p != NULL)
137         p = &(*p)->next;
138     *p          = codec;
139     codec->next = NULL;
140
141     if (codec->init_static_data)
142         codec->init_static_data(codec);
143 }
144
145 unsigned avcodec_get_edge_width(void)
146 {
147     return EDGE_WIDTH;
148 }
149
150 void avcodec_set_dimensions(AVCodecContext *s, int width, int height)
151 {
152     s->coded_width  = width;
153     s->coded_height = height;
154     s->width        = width;
155     s->height       = height;
156 }
157
158 #define INTERNAL_BUFFER_SIZE (32 + 1)
159
160 #if (ARCH_ARM && HAVE_NEON) || ARCH_PPC || HAVE_MMX
161 #   define STRIDE_ALIGN 16
162 #else
163 #   define STRIDE_ALIGN 8
164 #endif
165
166 void avcodec_align_dimensions2(AVCodecContext *s, int *width, int *height,
167                                int linesize_align[AV_NUM_DATA_POINTERS])
168 {
169     int i;
170     int w_align = 1;
171     int h_align = 1;
172
173     switch (s->pix_fmt) {
174     case AV_PIX_FMT_YUV420P:
175     case AV_PIX_FMT_YUYV422:
176     case AV_PIX_FMT_UYVY422:
177     case AV_PIX_FMT_YUV422P:
178     case AV_PIX_FMT_YUV440P:
179     case AV_PIX_FMT_YUV444P:
180     case AV_PIX_FMT_GBRP:
181     case AV_PIX_FMT_GRAY8:
182     case AV_PIX_FMT_GRAY16BE:
183     case AV_PIX_FMT_GRAY16LE:
184     case AV_PIX_FMT_YUVJ420P:
185     case AV_PIX_FMT_YUVJ422P:
186     case AV_PIX_FMT_YUVJ440P:
187     case AV_PIX_FMT_YUVJ444P:
188     case AV_PIX_FMT_YUVA420P:
189     case AV_PIX_FMT_YUVA422P:
190     case AV_PIX_FMT_YUVA444P:
191     case AV_PIX_FMT_YUV420P9LE:
192     case AV_PIX_FMT_YUV420P9BE:
193     case AV_PIX_FMT_YUV420P10LE:
194     case AV_PIX_FMT_YUV420P10BE:
195     case AV_PIX_FMT_YUV422P9LE:
196     case AV_PIX_FMT_YUV422P9BE:
197     case AV_PIX_FMT_YUV422P10LE:
198     case AV_PIX_FMT_YUV422P10BE:
199     case AV_PIX_FMT_YUV444P9LE:
200     case AV_PIX_FMT_YUV444P9BE:
201     case AV_PIX_FMT_YUV444P10LE:
202     case AV_PIX_FMT_YUV444P10BE:
203     case AV_PIX_FMT_GBRP9LE:
204     case AV_PIX_FMT_GBRP9BE:
205     case AV_PIX_FMT_GBRP10LE:
206     case AV_PIX_FMT_GBRP10BE:
207         w_align = 16; //FIXME assume 16 pixel per macroblock
208         h_align = 16 * 2; // interlaced needs 2 macroblocks height
209         break;
210     case AV_PIX_FMT_YUV411P:
211     case AV_PIX_FMT_UYYVYY411:
212         w_align = 32;
213         h_align = 8;
214         break;
215     case AV_PIX_FMT_YUV410P:
216         if (s->codec_id == AV_CODEC_ID_SVQ1) {
217             w_align = 64;
218             h_align = 64;
219         }
220     case AV_PIX_FMT_RGB555:
221         if (s->codec_id == AV_CODEC_ID_RPZA) {
222             w_align = 4;
223             h_align = 4;
224         }
225     case AV_PIX_FMT_PAL8:
226     case AV_PIX_FMT_BGR8:
227     case AV_PIX_FMT_RGB8:
228         if (s->codec_id == AV_CODEC_ID_SMC) {
229             w_align = 4;
230             h_align = 4;
231         }
232         break;
233     case AV_PIX_FMT_BGR24:
234         if ((s->codec_id == AV_CODEC_ID_MSZH) ||
235             (s->codec_id == AV_CODEC_ID_ZLIB)) {
236             w_align = 4;
237             h_align = 4;
238         }
239         break;
240     default:
241         w_align = 1;
242         h_align = 1;
243         break;
244     }
245
246     *width  = FFALIGN(*width, w_align);
247     *height = FFALIGN(*height, h_align);
248     if (s->codec_id == AV_CODEC_ID_H264)
249         // some of the optimized chroma MC reads one line too much
250         *height += 2;
251
252     for (i = 0; i < 4; i++)
253         linesize_align[i] = STRIDE_ALIGN;
254 }
255
256 void avcodec_align_dimensions(AVCodecContext *s, int *width, int *height)
257 {
258     const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(s->pix_fmt);
259     int chroma_shift = desc->log2_chroma_w;
260     int linesize_align[AV_NUM_DATA_POINTERS];
261     int align;
262
263     avcodec_align_dimensions2(s, width, height, linesize_align);
264     align               = FFMAX(linesize_align[0], linesize_align[3]);
265     linesize_align[1] <<= chroma_shift;
266     linesize_align[2] <<= chroma_shift;
267     align               = FFMAX3(align, linesize_align[1], linesize_align[2]);
268     *width              = FFALIGN(*width, align);
269 }
270
271 int avcodec_fill_audio_frame(AVFrame *frame, int nb_channels,
272                              enum AVSampleFormat sample_fmt, const uint8_t *buf,
273                              int buf_size, int align)
274 {
275     int ch, planar, needed_size, ret = 0;
276
277     needed_size = av_samples_get_buffer_size(NULL, nb_channels,
278                                              frame->nb_samples, sample_fmt,
279                                              align);
280     if (buf_size < needed_size)
281         return AVERROR(EINVAL);
282
283     planar = av_sample_fmt_is_planar(sample_fmt);
284     if (planar && nb_channels > AV_NUM_DATA_POINTERS) {
285         if (!(frame->extended_data = av_mallocz(nb_channels *
286                                                 sizeof(*frame->extended_data))))
287             return AVERROR(ENOMEM);
288     } else {
289         frame->extended_data = frame->data;
290     }
291
292     if ((ret = av_samples_fill_arrays(frame->extended_data, &frame->linesize[0],
293                                       buf, nb_channels, frame->nb_samples,
294                                       sample_fmt, align)) < 0) {
295         if (frame->extended_data != frame->data)
296             av_free(frame->extended_data);
297         return ret;
298     }
299     if (frame->extended_data != frame->data) {
300         for (ch = 0; ch < AV_NUM_DATA_POINTERS; ch++)
301             frame->data[ch] = frame->extended_data[ch];
302     }
303
304     return ret;
305 }
306
307 static int audio_get_buffer(AVCodecContext *avctx, AVFrame *frame)
308 {
309     AVCodecInternal *avci = avctx->internal;
310     int buf_size, ret;
311
312     av_freep(&avci->audio_data);
313     buf_size = av_samples_get_buffer_size(NULL, avctx->channels,
314                                           frame->nb_samples, avctx->sample_fmt,
315                                           0);
316     if (buf_size < 0)
317         return AVERROR(EINVAL);
318
319     frame->data[0] = av_mallocz(buf_size);
320     if (!frame->data[0])
321         return AVERROR(ENOMEM);
322
323     ret = avcodec_fill_audio_frame(frame, avctx->channels, avctx->sample_fmt,
324                                    frame->data[0], buf_size, 0);
325     if (ret < 0) {
326         av_freep(&frame->data[0]);
327         return ret;
328     }
329
330     avci->audio_data = frame->data[0];
331     if (avctx->debug & FF_DEBUG_BUFFERS)
332         av_log(avctx, AV_LOG_DEBUG, "default_get_buffer called on frame %p, "
333                                     "internal audio buffer used\n", frame);
334
335     return 0;
336 }
337
338 static int video_get_buffer(AVCodecContext *s, AVFrame *pic)
339 {
340     int i;
341     int w = s->width;
342     int h = s->height;
343     InternalBuffer *buf;
344     AVCodecInternal *avci = s->internal;
345
346     if (pic->data[0] != NULL) {
347         av_log(s, AV_LOG_ERROR, "pic->data[0]!=NULL in avcodec_default_get_buffer\n");
348         return -1;
349     }
350     if (avci->buffer_count >= INTERNAL_BUFFER_SIZE) {
351         av_log(s, AV_LOG_ERROR, "buffer_count overflow (missing release_buffer?)\n");
352         return -1;
353     }
354
355     if (av_image_check_size(w, h, 0, s))
356         return -1;
357
358     if (!avci->buffer) {
359         avci->buffer = av_mallocz((INTERNAL_BUFFER_SIZE + 1) *
360                                   sizeof(InternalBuffer));
361     }
362
363     buf = &avci->buffer[avci->buffer_count];
364
365     if (buf->base[0] && (buf->width != w || buf->height != h || buf->pix_fmt != s->pix_fmt)) {
366         for (i = 0; i < AV_NUM_DATA_POINTERS; i++) {
367             av_freep(&buf->base[i]);
368             buf->data[i] = NULL;
369         }
370     }
371
372     if (!buf->base[0]) {
373         int h_chroma_shift, v_chroma_shift;
374         int size[4] = { 0 };
375         int tmpsize;
376         int unaligned;
377         AVPicture picture;
378         int stride_align[AV_NUM_DATA_POINTERS];
379         const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(s->pix_fmt);
380         const int pixel_size = desc->comp[0].step_minus1 + 1;
381
382         av_pix_fmt_get_chroma_sub_sample(s->pix_fmt, &h_chroma_shift,
383                                          &v_chroma_shift);
384
385         avcodec_align_dimensions2(s, &w, &h, stride_align);
386
387         if (!(s->flags & CODEC_FLAG_EMU_EDGE)) {
388             w += EDGE_WIDTH * 2;
389             h += EDGE_WIDTH * 2;
390         }
391
392         do {
393             // NOTE: do not align linesizes individually, this breaks e.g. assumptions
394             // that linesize[0] == 2*linesize[1] in the MPEG-encoder for 4:2:2
395             av_image_fill_linesizes(picture.linesize, s->pix_fmt, w);
396             // increase alignment of w for next try (rhs gives the lowest bit set in w)
397             w += w & ~(w - 1);
398
399             unaligned = 0;
400             for (i = 0; i < 4; i++)
401                 unaligned |= picture.linesize[i] % stride_align[i];
402         } while (unaligned);
403
404         tmpsize = av_image_fill_pointers(picture.data, s->pix_fmt, h, NULL, picture.linesize);
405         if (tmpsize < 0)
406             return -1;
407
408         for (i = 0; i < 3 && picture.data[i + 1]; i++)
409             size[i] = picture.data[i + 1] - picture.data[i];
410         size[i] = tmpsize - (picture.data[i] - picture.data[0]);
411
412         memset(buf->base, 0, sizeof(buf->base));
413         memset(buf->data, 0, sizeof(buf->data));
414
415         for (i = 0; i < 4 && size[i]; i++) {
416             const int h_shift = i == 0 ? 0 : h_chroma_shift;
417             const int v_shift = i == 0 ? 0 : v_chroma_shift;
418
419             buf->linesize[i] = picture.linesize[i];
420
421             buf->base[i] = av_malloc(size[i] + 16); //FIXME 16
422             if (buf->base[i] == NULL)
423                 return -1;
424
425             // no edge if EDGE EMU or not planar YUV
426             if ((s->flags & CODEC_FLAG_EMU_EDGE) || !size[2])
427                 buf->data[i] = buf->base[i];
428             else
429                 buf->data[i] = buf->base[i] + FFALIGN((buf->linesize[i] * EDGE_WIDTH >> v_shift) + (pixel_size * EDGE_WIDTH >> h_shift), stride_align[i]);
430         }
431         for (; i < AV_NUM_DATA_POINTERS; i++) {
432             buf->base[i]     = buf->data[i] = NULL;
433             buf->linesize[i] = 0;
434         }
435         if (size[1] && !size[2])
436             avpriv_set_systematic_pal2((uint32_t *)buf->data[1], s->pix_fmt);
437         buf->width   = s->width;
438         buf->height  = s->height;
439         buf->pix_fmt = s->pix_fmt;
440     }
441
442     for (i = 0; i < AV_NUM_DATA_POINTERS; i++) {
443         pic->base[i]     = buf->base[i];
444         pic->data[i]     = buf->data[i];
445         pic->linesize[i] = buf->linesize[i];
446     }
447     pic->extended_data = pic->data;
448     avci->buffer_count++;
449
450     if (s->debug & FF_DEBUG_BUFFERS)
451         av_log(s, AV_LOG_DEBUG, "default_get_buffer called on pic %p, %d "
452                                 "buffers used\n", pic, avci->buffer_count);
453
454     return 0;
455 }
456
457 int avcodec_default_get_buffer(AVCodecContext *avctx, AVFrame *frame)
458 {
459     frame->type = FF_BUFFER_TYPE_INTERNAL;
460     switch (avctx->codec_type) {
461     case AVMEDIA_TYPE_VIDEO:
462         return video_get_buffer(avctx, frame);
463     case AVMEDIA_TYPE_AUDIO:
464         return audio_get_buffer(avctx, frame);
465     default:
466         return -1;
467     }
468 }
469
470 int ff_get_buffer(AVCodecContext *avctx, AVFrame *frame)
471 {
472     switch (avctx->codec_type) {
473     case AVMEDIA_TYPE_VIDEO:
474         frame->width               = avctx->width;
475         frame->height              = avctx->height;
476         frame->format              = avctx->pix_fmt;
477         frame->sample_aspect_ratio = avctx->sample_aspect_ratio;
478         break;
479     case AVMEDIA_TYPE_AUDIO:
480         frame->sample_rate    = avctx->sample_rate;
481         frame->format         = avctx->sample_fmt;
482         frame->channel_layout = avctx->channel_layout;
483         break;
484     default: return AVERROR(EINVAL);
485     }
486
487     frame->pkt_pts = avctx->pkt ? avctx->pkt->pts : AV_NOPTS_VALUE;
488     frame->reordered_opaque = avctx->reordered_opaque;
489
490     return avctx->get_buffer(avctx, frame);
491 }
492
493 void avcodec_default_release_buffer(AVCodecContext *s, AVFrame *pic)
494 {
495     int i;
496     InternalBuffer *buf, *last;
497     AVCodecInternal *avci = s->internal;
498
499     assert(s->codec_type == AVMEDIA_TYPE_VIDEO);
500
501     assert(pic->type == FF_BUFFER_TYPE_INTERNAL);
502     assert(avci->buffer_count);
503
504     if (avci->buffer) {
505         buf = NULL; /* avoids warning */
506         for (i = 0; i < avci->buffer_count; i++) { //just 3-5 checks so is not worth to optimize
507             buf = &avci->buffer[i];
508             if (buf->data[0] == pic->data[0])
509                 break;
510         }
511         assert(i < avci->buffer_count);
512         avci->buffer_count--;
513         last = &avci->buffer[avci->buffer_count];
514
515         if (buf != last)
516             FFSWAP(InternalBuffer, *buf, *last);
517     }
518
519     for (i = 0; i < AV_NUM_DATA_POINTERS; i++)
520         pic->data[i] = NULL;
521 //        pic->base[i]=NULL;
522
523     if (s->debug & FF_DEBUG_BUFFERS)
524         av_log(s, AV_LOG_DEBUG, "default_release_buffer called on pic %p, %d "
525                                 "buffers used\n", pic, avci->buffer_count);
526 }
527
528 int avcodec_default_reget_buffer(AVCodecContext *s, AVFrame *pic)
529 {
530     AVFrame temp_pic;
531     int i;
532
533     assert(s->codec_type == AVMEDIA_TYPE_VIDEO);
534
535     /* If no picture return a new buffer */
536     if (pic->data[0] == NULL) {
537         /* We will copy from buffer, so must be readable */
538         pic->buffer_hints |= FF_BUFFER_HINTS_READABLE;
539         return ff_get_buffer(s, pic);
540     }
541
542     assert(s->pix_fmt == pic->format);
543
544     /* If internal buffer type return the same buffer */
545     if (pic->type == FF_BUFFER_TYPE_INTERNAL) {
546         if (s->pkt)
547             pic->pkt_pts = s->pkt->pts;
548         else
549             pic->pkt_pts = AV_NOPTS_VALUE;
550         pic->reordered_opaque = s->reordered_opaque;
551         return 0;
552     }
553
554     /*
555      * Not internal type and reget_buffer not overridden, emulate cr buffer
556      */
557     temp_pic = *pic;
558     for (i = 0; i < AV_NUM_DATA_POINTERS; i++)
559         pic->data[i] = pic->base[i] = NULL;
560     pic->opaque = NULL;
561     /* Allocate new frame */
562     if (ff_get_buffer(s, pic))
563         return -1;
564     /* Copy image data from old buffer to new buffer */
565     av_picture_copy((AVPicture *)pic, (AVPicture *)&temp_pic, s->pix_fmt, s->width,
566                     s->height);
567     s->release_buffer(s, &temp_pic); // Release old frame
568     return 0;
569 }
570
571 int avcodec_default_execute(AVCodecContext *c, int (*func)(AVCodecContext *c2, void *arg2), void *arg, int *ret, int count, int size)
572 {
573     int i;
574
575     for (i = 0; i < count; i++) {
576         int r = func(c, (char *)arg + i * size);
577         if (ret)
578             ret[i] = r;
579     }
580     return 0;
581 }
582
583 int avcodec_default_execute2(AVCodecContext *c, int (*func)(AVCodecContext *c2, void *arg2, int jobnr, int threadnr), void *arg, int *ret, int count)
584 {
585     int i;
586
587     for (i = 0; i < count; i++) {
588         int r = func(c, arg, i, 0);
589         if (ret)
590             ret[i] = r;
591     }
592     return 0;
593 }
594
595 static int is_hwaccel_pix_fmt(enum AVPixelFormat pix_fmt)
596 {
597     const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(pix_fmt);
598     return desc->flags & PIX_FMT_HWACCEL;
599 }
600
601 enum AVPixelFormat avcodec_default_get_format(struct AVCodecContext *s, const enum AVPixelFormat *fmt)
602 {
603     while (*fmt != AV_PIX_FMT_NONE && is_hwaccel_pix_fmt(*fmt))
604         ++fmt;
605     return fmt[0];
606 }
607
608 void avcodec_get_frame_defaults(AVFrame *frame)
609 {
610     if (frame->extended_data != frame->data)
611         av_freep(&frame->extended_data);
612
613     memset(frame, 0, sizeof(AVFrame));
614
615     frame->pts                 = AV_NOPTS_VALUE;
616     frame->key_frame           = 1;
617     frame->sample_aspect_ratio = (AVRational) {0, 1 };
618     frame->format              = -1; /* unknown */
619     frame->extended_data       = frame->data;
620 }
621
622 AVFrame *avcodec_alloc_frame(void)
623 {
624     AVFrame *frame = av_mallocz(sizeof(AVFrame));
625
626     if (frame == NULL)
627         return NULL;
628
629     avcodec_get_frame_defaults(frame);
630
631     return frame;
632 }
633
634 void avcodec_free_frame(AVFrame **frame)
635 {
636     AVFrame *f;
637
638     if (!frame || !*frame)
639         return;
640
641     f = *frame;
642
643     if (f->extended_data != f->data)
644         av_freep(&f->extended_data);
645
646     av_freep(frame);
647 }
648
649 int attribute_align_arg avcodec_open2(AVCodecContext *avctx, const AVCodec *codec, AVDictionary **options)
650 {
651     int ret = 0;
652     AVDictionary *tmp = NULL;
653
654     if (avcodec_is_open(avctx))
655         return 0;
656
657     if ((!codec && !avctx->codec)) {
658         av_log(avctx, AV_LOG_ERROR, "No codec provided to avcodec_open2().\n");
659         return AVERROR(EINVAL);
660     }
661     if ((codec && avctx->codec && codec != avctx->codec)) {
662         av_log(avctx, AV_LOG_ERROR, "This AVCodecContext was allocated for %s, "
663                                     "but %s passed to avcodec_open2().\n", avctx->codec->name, codec->name);
664         return AVERROR(EINVAL);
665     }
666     if (!codec)
667         codec = avctx->codec;
668
669     if (avctx->extradata_size < 0 || avctx->extradata_size >= FF_MAX_EXTRADATA_SIZE)
670         return AVERROR(EINVAL);
671
672     if (options)
673         av_dict_copy(&tmp, *options, 0);
674
675     /* If there is a user-supplied mutex locking routine, call it. */
676     if (ff_lockmgr_cb) {
677         if ((*ff_lockmgr_cb)(&codec_mutex, AV_LOCK_OBTAIN))
678             return -1;
679     }
680
681     entangled_thread_counter++;
682     if (entangled_thread_counter != 1) {
683         av_log(avctx, AV_LOG_ERROR, "insufficient thread locking around avcodec_open/close()\n");
684         ret = -1;
685         goto end;
686     }
687
688     avctx->internal = av_mallocz(sizeof(AVCodecInternal));
689     if (!avctx->internal) {
690         ret = AVERROR(ENOMEM);
691         goto end;
692     }
693
694     if (codec->priv_data_size > 0) {
695         if (!avctx->priv_data) {
696             avctx->priv_data = av_mallocz(codec->priv_data_size);
697             if (!avctx->priv_data) {
698                 ret = AVERROR(ENOMEM);
699                 goto end;
700             }
701             if (codec->priv_class) {
702                 *(const AVClass **)avctx->priv_data = codec->priv_class;
703                 av_opt_set_defaults(avctx->priv_data);
704             }
705         }
706         if (codec->priv_class && (ret = av_opt_set_dict(avctx->priv_data, &tmp)) < 0)
707             goto free_and_end;
708     } else {
709         avctx->priv_data = NULL;
710     }
711     if ((ret = av_opt_set_dict(avctx, &tmp)) < 0)
712         goto free_and_end;
713
714     if (avctx->coded_width && avctx->coded_height)
715         avcodec_set_dimensions(avctx, avctx->coded_width, avctx->coded_height);
716     else if (avctx->width && avctx->height)
717         avcodec_set_dimensions(avctx, avctx->width, avctx->height);
718
719     if ((avctx->coded_width || avctx->coded_height || avctx->width || avctx->height)
720         && (  av_image_check_size(avctx->coded_width, avctx->coded_height, 0, avctx) < 0
721            || av_image_check_size(avctx->width,       avctx->height,       0, avctx) < 0)) {
722         av_log(avctx, AV_LOG_WARNING, "ignoring invalid width/height values\n");
723         avcodec_set_dimensions(avctx, 0, 0);
724     }
725
726     /* if the decoder init function was already called previously,
727      * free the already allocated subtitle_header before overwriting it */
728     if (av_codec_is_decoder(codec))
729         av_freep(&avctx->subtitle_header);
730
731     if (avctx->channels > FF_SANE_NB_CHANNELS) {
732         ret = AVERROR(EINVAL);
733         goto free_and_end;
734     }
735
736     avctx->codec = codec;
737     if ((avctx->codec_type == AVMEDIA_TYPE_UNKNOWN || avctx->codec_type == codec->type) &&
738         avctx->codec_id == AV_CODEC_ID_NONE) {
739         avctx->codec_type = codec->type;
740         avctx->codec_id   = codec->id;
741     }
742     if (avctx->codec_id != codec->id || (avctx->codec_type != codec->type
743                                          && avctx->codec_type != AVMEDIA_TYPE_ATTACHMENT)) {
744         av_log(avctx, AV_LOG_ERROR, "codec type or id mismatches\n");
745         ret = AVERROR(EINVAL);
746         goto free_and_end;
747     }
748     avctx->frame_number = 0;
749
750     if (avctx->codec->capabilities & CODEC_CAP_EXPERIMENTAL &&
751         avctx->strict_std_compliance > FF_COMPLIANCE_EXPERIMENTAL) {
752         ret = AVERROR_EXPERIMENTAL;
753         goto free_and_end;
754     }
755
756     if (avctx->codec_type == AVMEDIA_TYPE_AUDIO &&
757         (!avctx->time_base.num || !avctx->time_base.den)) {
758         avctx->time_base.num = 1;
759         avctx->time_base.den = avctx->sample_rate;
760     }
761
762     if (HAVE_THREADS && !avctx->thread_opaque) {
763         ret = ff_thread_init(avctx);
764         if (ret < 0) {
765             goto free_and_end;
766         }
767     }
768     if (!HAVE_THREADS && !(codec->capabilities & CODEC_CAP_AUTO_THREADS))
769         avctx->thread_count = 1;
770
771     if (av_codec_is_encoder(avctx->codec)) {
772         int i;
773         if (avctx->codec->sample_fmts) {
774             for (i = 0; avctx->codec->sample_fmts[i] != AV_SAMPLE_FMT_NONE; i++) {
775                 if (avctx->sample_fmt == avctx->codec->sample_fmts[i])
776                     break;
777                 if (avctx->channels == 1 &&
778                     av_get_planar_sample_fmt(avctx->sample_fmt) ==
779                     av_get_planar_sample_fmt(avctx->codec->sample_fmts[i])) {
780                     avctx->sample_fmt = avctx->codec->sample_fmts[i];
781                     break;
782                 }
783             }
784             if (avctx->codec->sample_fmts[i] == AV_SAMPLE_FMT_NONE) {
785                 av_log(avctx, AV_LOG_ERROR, "Specified sample_fmt is not supported.\n");
786                 ret = AVERROR(EINVAL);
787                 goto free_and_end;
788             }
789         }
790         if (avctx->codec->pix_fmts) {
791             for (i = 0; avctx->codec->pix_fmts[i] != AV_PIX_FMT_NONE; i++)
792                 if (avctx->pix_fmt == avctx->codec->pix_fmts[i])
793                     break;
794             if (avctx->codec->pix_fmts[i] == AV_PIX_FMT_NONE) {
795                 av_log(avctx, AV_LOG_ERROR, "Specified pix_fmt is not supported\n");
796                 ret = AVERROR(EINVAL);
797                 goto free_and_end;
798             }
799         }
800         if (avctx->codec->supported_samplerates) {
801             for (i = 0; avctx->codec->supported_samplerates[i] != 0; i++)
802                 if (avctx->sample_rate == avctx->codec->supported_samplerates[i])
803                     break;
804             if (avctx->codec->supported_samplerates[i] == 0) {
805                 av_log(avctx, AV_LOG_ERROR, "Specified sample_rate is not supported\n");
806                 ret = AVERROR(EINVAL);
807                 goto free_and_end;
808             }
809         }
810         if (avctx->codec->channel_layouts) {
811             if (!avctx->channel_layout) {
812                 av_log(avctx, AV_LOG_WARNING, "channel_layout not specified\n");
813             } else {
814                 for (i = 0; avctx->codec->channel_layouts[i] != 0; i++)
815                     if (avctx->channel_layout == avctx->codec->channel_layouts[i])
816                         break;
817                 if (avctx->codec->channel_layouts[i] == 0) {
818                     av_log(avctx, AV_LOG_ERROR, "Specified channel_layout is not supported\n");
819                     ret = AVERROR(EINVAL);
820                     goto free_and_end;
821                 }
822             }
823         }
824         if (avctx->channel_layout && avctx->channels) {
825             if (av_get_channel_layout_nb_channels(avctx->channel_layout) != avctx->channels) {
826                 av_log(avctx, AV_LOG_ERROR, "channel layout does not match number of channels\n");
827                 ret = AVERROR(EINVAL);
828                 goto free_and_end;
829             }
830         } else if (avctx->channel_layout) {
831             avctx->channels = av_get_channel_layout_nb_channels(avctx->channel_layout);
832         }
833
834         if (!avctx->rc_initial_buffer_occupancy)
835             avctx->rc_initial_buffer_occupancy = avctx->rc_buffer_size * 3 / 4;
836     }
837
838     if (avctx->codec->init && !(avctx->active_thread_type & FF_THREAD_FRAME)) {
839         ret = avctx->codec->init(avctx);
840         if (ret < 0) {
841             goto free_and_end;
842         }
843     }
844
845     if (av_codec_is_decoder(avctx->codec)) {
846         /* validate channel layout from the decoder */
847         if (avctx->channel_layout) {
848             int channels = av_get_channel_layout_nb_channels(avctx->channel_layout);
849             if (!avctx->channels)
850                 avctx->channels = channels;
851             else if (channels != avctx->channels) {
852                 av_log(avctx, AV_LOG_WARNING,
853                        "channel layout does not match number of channels\n");
854                 avctx->channel_layout = 0;
855             }
856         }
857         if (avctx->channels && avctx->channels < 0 ||
858             avctx->channels > FF_SANE_NB_CHANNELS) {
859             ret = AVERROR(EINVAL);
860             goto free_and_end;
861         }
862     }
863 end:
864     entangled_thread_counter--;
865
866     /* Release any user-supplied mutex. */
867     if (ff_lockmgr_cb) {
868         (*ff_lockmgr_cb)(&codec_mutex, AV_LOCK_RELEASE);
869     }
870     if (options) {
871         av_dict_free(options);
872         *options = tmp;
873     }
874
875     return ret;
876 free_and_end:
877     av_dict_free(&tmp);
878     av_freep(&avctx->priv_data);
879     av_freep(&avctx->internal);
880     avctx->codec = NULL;
881     goto end;
882 }
883
884 int ff_alloc_packet(AVPacket *avpkt, int size)
885 {
886     if (size > INT_MAX - FF_INPUT_BUFFER_PADDING_SIZE)
887         return AVERROR(EINVAL);
888
889     if (avpkt->data) {
890         void *destruct = avpkt->destruct;
891
892         if (avpkt->size < size)
893             return AVERROR(EINVAL);
894
895         av_init_packet(avpkt);
896         avpkt->destruct = destruct;
897         avpkt->size     = size;
898         return 0;
899     } else {
900         return av_new_packet(avpkt, size);
901     }
902 }
903
904 /**
905  * Pad last frame with silence.
906  */
907 static int pad_last_frame(AVCodecContext *s, AVFrame **dst, const AVFrame *src)
908 {
909     AVFrame *frame = NULL;
910     uint8_t *buf   = NULL;
911     int ret;
912
913     if (!(frame = avcodec_alloc_frame()))
914         return AVERROR(ENOMEM);
915     *frame = *src;
916
917     if ((ret = av_samples_get_buffer_size(&frame->linesize[0], s->channels,
918                                           s->frame_size, s->sample_fmt, 0)) < 0)
919         goto fail;
920
921     if (!(buf = av_malloc(ret))) {
922         ret = AVERROR(ENOMEM);
923         goto fail;
924     }
925
926     frame->nb_samples = s->frame_size;
927     if ((ret = avcodec_fill_audio_frame(frame, s->channels, s->sample_fmt,
928                                         buf, ret, 0)) < 0)
929         goto fail;
930     if ((ret = av_samples_copy(frame->extended_data, src->extended_data, 0, 0,
931                                src->nb_samples, s->channels, s->sample_fmt)) < 0)
932         goto fail;
933     if ((ret = av_samples_set_silence(frame->extended_data, src->nb_samples,
934                                       frame->nb_samples - src->nb_samples,
935                                       s->channels, s->sample_fmt)) < 0)
936         goto fail;
937
938     *dst = frame;
939
940     return 0;
941
942 fail:
943     if (frame->extended_data != frame->data)
944         av_freep(&frame->extended_data);
945     av_freep(&buf);
946     av_freep(&frame);
947     return ret;
948 }
949
950 int attribute_align_arg avcodec_encode_audio2(AVCodecContext *avctx,
951                                               AVPacket *avpkt,
952                                               const AVFrame *frame,
953                                               int *got_packet_ptr)
954 {
955     AVFrame tmp;
956     AVFrame *padded_frame = NULL;
957     int ret;
958     int user_packet = !!avpkt->data;
959
960     *got_packet_ptr = 0;
961
962     if (!(avctx->codec->capabilities & CODEC_CAP_DELAY) && !frame) {
963         av_free_packet(avpkt);
964         av_init_packet(avpkt);
965         return 0;
966     }
967
968     /* ensure that extended_data is properly set */
969     if (frame && !frame->extended_data) {
970         if (av_sample_fmt_is_planar(avctx->sample_fmt) &&
971             avctx->channels > AV_NUM_DATA_POINTERS) {
972             av_log(avctx, AV_LOG_ERROR, "Encoding to a planar sample format, "
973                                         "with more than %d channels, but extended_data is not set.\n",
974                    AV_NUM_DATA_POINTERS);
975             return AVERROR(EINVAL);
976         }
977         av_log(avctx, AV_LOG_WARNING, "extended_data is not set.\n");
978
979         tmp = *frame;
980         tmp.extended_data = tmp.data;
981         frame = &tmp;
982     }
983
984     /* check for valid frame size */
985     if (frame) {
986         if (avctx->codec->capabilities & CODEC_CAP_SMALL_LAST_FRAME) {
987             if (frame->nb_samples > avctx->frame_size)
988                 return AVERROR(EINVAL);
989         } else if (!(avctx->codec->capabilities & CODEC_CAP_VARIABLE_FRAME_SIZE)) {
990             if (frame->nb_samples < avctx->frame_size &&
991                 !avctx->internal->last_audio_frame) {
992                 ret = pad_last_frame(avctx, &padded_frame, frame);
993                 if (ret < 0)
994                     return ret;
995
996                 frame = padded_frame;
997                 avctx->internal->last_audio_frame = 1;
998             }
999
1000             if (frame->nb_samples != avctx->frame_size) {
1001                 ret = AVERROR(EINVAL);
1002                 goto end;
1003             }
1004         }
1005     }
1006
1007     ret = avctx->codec->encode2(avctx, avpkt, frame, got_packet_ptr);
1008     if (!ret) {
1009         if (*got_packet_ptr) {
1010             if (!(avctx->codec->capabilities & CODEC_CAP_DELAY)) {
1011                 if (avpkt->pts == AV_NOPTS_VALUE)
1012                     avpkt->pts = frame->pts;
1013                 if (!avpkt->duration)
1014                     avpkt->duration = ff_samples_to_time_base(avctx,
1015                                                               frame->nb_samples);
1016             }
1017             avpkt->dts = avpkt->pts;
1018         } else {
1019             avpkt->size = 0;
1020         }
1021
1022         if (!user_packet && avpkt->size) {
1023             uint8_t *new_data = av_realloc(avpkt->data, avpkt->size);
1024             if (new_data)
1025                 avpkt->data = new_data;
1026         }
1027
1028         avctx->frame_number++;
1029     }
1030
1031     if (ret < 0 || !*got_packet_ptr) {
1032         av_free_packet(avpkt);
1033         av_init_packet(avpkt);
1034         goto end;
1035     }
1036
1037     /* NOTE: if we add any audio encoders which output non-keyframe packets,
1038      *       this needs to be moved to the encoders, but for now we can do it
1039      *       here to simplify things */
1040     avpkt->flags |= AV_PKT_FLAG_KEY;
1041
1042 end:
1043     if (padded_frame) {
1044         av_freep(&padded_frame->data[0]);
1045         if (padded_frame->extended_data != padded_frame->data)
1046             av_freep(&padded_frame->extended_data);
1047         av_freep(&padded_frame);
1048     }
1049
1050     return ret;
1051 }
1052
1053 #if FF_API_OLD_ENCODE_AUDIO
1054 int attribute_align_arg avcodec_encode_audio(AVCodecContext *avctx,
1055                                              uint8_t *buf, int buf_size,
1056                                              const short *samples)
1057 {
1058     AVPacket pkt;
1059     AVFrame frame0 = { { 0 } };
1060     AVFrame *frame;
1061     int ret, samples_size, got_packet;
1062
1063     av_init_packet(&pkt);
1064     pkt.data = buf;
1065     pkt.size = buf_size;
1066
1067     if (samples) {
1068         frame = &frame0;
1069         avcodec_get_frame_defaults(frame);
1070
1071         if (avctx->frame_size) {
1072             frame->nb_samples = avctx->frame_size;
1073         } else {
1074             /* if frame_size is not set, the number of samples must be
1075              * calculated from the buffer size */
1076             int64_t nb_samples;
1077             if (!av_get_bits_per_sample(avctx->codec_id)) {
1078                 av_log(avctx, AV_LOG_ERROR, "avcodec_encode_audio() does not "
1079                                             "support this codec\n");
1080                 return AVERROR(EINVAL);
1081             }
1082             nb_samples = (int64_t)buf_size * 8 /
1083                          (av_get_bits_per_sample(avctx->codec_id) *
1084                           avctx->channels);
1085             if (nb_samples >= INT_MAX)
1086                 return AVERROR(EINVAL);
1087             frame->nb_samples = nb_samples;
1088         }
1089
1090         /* it is assumed that the samples buffer is large enough based on the
1091          * relevant parameters */
1092         samples_size = av_samples_get_buffer_size(NULL, avctx->channels,
1093                                                   frame->nb_samples,
1094                                                   avctx->sample_fmt, 1);
1095         if ((ret = avcodec_fill_audio_frame(frame, avctx->channels,
1096                                             avctx->sample_fmt,
1097                                             (const uint8_t *)samples,
1098                                             samples_size, 1)))
1099             return ret;
1100
1101         /* fabricate frame pts from sample count.
1102          * this is needed because the avcodec_encode_audio() API does not have
1103          * a way for the user to provide pts */
1104         frame->pts = ff_samples_to_time_base(avctx,
1105                                              avctx->internal->sample_count);
1106         avctx->internal->sample_count += frame->nb_samples;
1107     } else {
1108         frame = NULL;
1109     }
1110
1111     got_packet = 0;
1112     ret = avcodec_encode_audio2(avctx, &pkt, frame, &got_packet);
1113     if (!ret && got_packet && avctx->coded_frame) {
1114         avctx->coded_frame->pts       = pkt.pts;
1115         avctx->coded_frame->key_frame = !!(pkt.flags & AV_PKT_FLAG_KEY);
1116     }
1117     /* free any side data since we cannot return it */
1118     if (pkt.side_data_elems > 0) {
1119         int i;
1120         for (i = 0; i < pkt.side_data_elems; i++)
1121             av_free(pkt.side_data[i].data);
1122         av_freep(&pkt.side_data);
1123         pkt.side_data_elems = 0;
1124     }
1125
1126     if (frame && frame->extended_data != frame->data)
1127         av_free(frame->extended_data);
1128
1129     return ret ? ret : pkt.size;
1130 }
1131
1132 #endif
1133
1134 #if FF_API_OLD_ENCODE_VIDEO
1135 int attribute_align_arg avcodec_encode_video(AVCodecContext *avctx, uint8_t *buf, int buf_size,
1136                                              const AVFrame *pict)
1137 {
1138     AVPacket pkt;
1139     int ret, got_packet = 0;
1140
1141     if (buf_size < FF_MIN_BUFFER_SIZE) {
1142         av_log(avctx, AV_LOG_ERROR, "buffer smaller than minimum size\n");
1143         return -1;
1144     }
1145
1146     av_init_packet(&pkt);
1147     pkt.data = buf;
1148     pkt.size = buf_size;
1149
1150     ret = avcodec_encode_video2(avctx, &pkt, pict, &got_packet);
1151     if (!ret && got_packet && avctx->coded_frame) {
1152         avctx->coded_frame->pts       = pkt.pts;
1153         avctx->coded_frame->key_frame = !!(pkt.flags & AV_PKT_FLAG_KEY);
1154     }
1155
1156     /* free any side data since we cannot return it */
1157     if (pkt.side_data_elems > 0) {
1158         int i;
1159         for (i = 0; i < pkt.side_data_elems; i++)
1160             av_free(pkt.side_data[i].data);
1161         av_freep(&pkt.side_data);
1162         pkt.side_data_elems = 0;
1163     }
1164
1165     return ret ? ret : pkt.size;
1166 }
1167
1168 #endif
1169
1170 int attribute_align_arg avcodec_encode_video2(AVCodecContext *avctx,
1171                                               AVPacket *avpkt,
1172                                               const AVFrame *frame,
1173                                               int *got_packet_ptr)
1174 {
1175     int ret;
1176     int user_packet = !!avpkt->data;
1177
1178     *got_packet_ptr = 0;
1179
1180     if (!(avctx->codec->capabilities & CODEC_CAP_DELAY) && !frame) {
1181         av_free_packet(avpkt);
1182         av_init_packet(avpkt);
1183         avpkt->size = 0;
1184         return 0;
1185     }
1186
1187     if (av_image_check_size(avctx->width, avctx->height, 0, avctx))
1188         return AVERROR(EINVAL);
1189
1190     av_assert0(avctx->codec->encode2);
1191
1192     ret = avctx->codec->encode2(avctx, avpkt, frame, got_packet_ptr);
1193     if (!ret) {
1194         if (!*got_packet_ptr)
1195             avpkt->size = 0;
1196         else if (!(avctx->codec->capabilities & CODEC_CAP_DELAY))
1197             avpkt->pts = avpkt->dts = frame->pts;
1198
1199         if (!user_packet && avpkt->size) {
1200             uint8_t *new_data = av_realloc(avpkt->data, avpkt->size);
1201             if (new_data)
1202                 avpkt->data = new_data;
1203         }
1204
1205         avctx->frame_number++;
1206     }
1207
1208     if (ret < 0 || !*got_packet_ptr)
1209         av_free_packet(avpkt);
1210
1211     emms_c();
1212     return ret;
1213 }
1214
1215 int avcodec_encode_subtitle(AVCodecContext *avctx, uint8_t *buf, int buf_size,
1216                             const AVSubtitle *sub)
1217 {
1218     int ret;
1219     if (sub->start_display_time) {
1220         av_log(avctx, AV_LOG_ERROR, "start_display_time must be 0.\n");
1221         return -1;
1222     }
1223     if (sub->num_rects == 0 || !sub->rects)
1224         return -1;
1225     ret = avctx->codec->encode_sub(avctx, buf, buf_size, sub);
1226     avctx->frame_number++;
1227     return ret;
1228 }
1229
1230 static void apply_param_change(AVCodecContext *avctx, AVPacket *avpkt)
1231 {
1232     int size = 0;
1233     const uint8_t *data;
1234     uint32_t flags;
1235
1236     if (!(avctx->codec->capabilities & CODEC_CAP_PARAM_CHANGE))
1237         return;
1238
1239     data = av_packet_get_side_data(avpkt, AV_PKT_DATA_PARAM_CHANGE, &size);
1240     if (!data || size < 4)
1241         return;
1242     flags = bytestream_get_le32(&data);
1243     size -= 4;
1244     if (size < 4) /* Required for any of the changes */
1245         return;
1246     if (flags & AV_SIDE_DATA_PARAM_CHANGE_CHANNEL_COUNT) {
1247         avctx->channels = bytestream_get_le32(&data);
1248         size -= 4;
1249     }
1250     if (flags & AV_SIDE_DATA_PARAM_CHANGE_CHANNEL_LAYOUT) {
1251         if (size < 8)
1252             return;
1253         avctx->channel_layout = bytestream_get_le64(&data);
1254         size -= 8;
1255     }
1256     if (size < 4)
1257         return;
1258     if (flags & AV_SIDE_DATA_PARAM_CHANGE_SAMPLE_RATE) {
1259         avctx->sample_rate = bytestream_get_le32(&data);
1260         size -= 4;
1261     }
1262     if (flags & AV_SIDE_DATA_PARAM_CHANGE_DIMENSIONS) {
1263         if (size < 8)
1264             return;
1265         avctx->width  = bytestream_get_le32(&data);
1266         avctx->height = bytestream_get_le32(&data);
1267         avcodec_set_dimensions(avctx, avctx->width, avctx->height);
1268         size -= 8;
1269     }
1270 }
1271
1272 int attribute_align_arg avcodec_decode_video2(AVCodecContext *avctx, AVFrame *picture,
1273                                               int *got_picture_ptr,
1274                                               AVPacket *avpkt)
1275 {
1276     int ret;
1277
1278     *got_picture_ptr = 0;
1279     if ((avctx->coded_width || avctx->coded_height) && av_image_check_size(avctx->coded_width, avctx->coded_height, 0, avctx))
1280         return -1;
1281
1282     avctx->pkt = avpkt;
1283     apply_param_change(avctx, avpkt);
1284
1285     avcodec_get_frame_defaults(picture);
1286
1287     if ((avctx->codec->capabilities & CODEC_CAP_DELAY) || avpkt->size || (avctx->active_thread_type & FF_THREAD_FRAME)) {
1288         if (HAVE_THREADS && avctx->active_thread_type & FF_THREAD_FRAME)
1289             ret = ff_thread_decode_frame(avctx, picture, got_picture_ptr,
1290                                          avpkt);
1291         else {
1292             ret = avctx->codec->decode(avctx, picture, got_picture_ptr,
1293                                        avpkt);
1294             picture->pkt_dts = avpkt->dts;
1295             /* get_buffer is supposed to set frame parameters */
1296             if (!(avctx->codec->capabilities & CODEC_CAP_DR1)) {
1297                 picture->sample_aspect_ratio = avctx->sample_aspect_ratio;
1298                 picture->width               = avctx->width;
1299                 picture->height              = avctx->height;
1300                 picture->format              = avctx->pix_fmt;
1301             }
1302         }
1303
1304         emms_c(); //needed to avoid an emms_c() call before every return;
1305
1306         if (*got_picture_ptr)
1307             avctx->frame_number++;
1308     } else
1309         ret = 0;
1310
1311     /* many decoders assign whole AVFrames, thus overwriting extended_data;
1312      * make sure it's set correctly */
1313     picture->extended_data = picture->data;
1314
1315     return ret;
1316 }
1317
1318 #if FF_API_OLD_DECODE_AUDIO
1319 int attribute_align_arg avcodec_decode_audio3(AVCodecContext *avctx, int16_t *samples,
1320                                               int *frame_size_ptr,
1321                                               AVPacket *avpkt)
1322 {
1323     AVFrame frame = { { 0 } };
1324     int ret, got_frame = 0;
1325
1326     if (avctx->get_buffer != avcodec_default_get_buffer) {
1327         av_log(avctx, AV_LOG_ERROR, "Custom get_buffer() for use with"
1328                                     "avcodec_decode_audio3() detected. Overriding with avcodec_default_get_buffer\n");
1329         av_log(avctx, AV_LOG_ERROR, "Please port your application to "
1330                                     "avcodec_decode_audio4()\n");
1331         avctx->get_buffer = avcodec_default_get_buffer;
1332     }
1333
1334     ret = avcodec_decode_audio4(avctx, &frame, &got_frame, avpkt);
1335
1336     if (ret >= 0 && got_frame) {
1337         int ch, plane_size;
1338         int planar    = av_sample_fmt_is_planar(avctx->sample_fmt);
1339         int data_size = av_samples_get_buffer_size(&plane_size, avctx->channels,
1340                                                    frame.nb_samples,
1341                                                    avctx->sample_fmt, 1);
1342         if (*frame_size_ptr < data_size) {
1343             av_log(avctx, AV_LOG_ERROR, "output buffer size is too small for "
1344                                         "the current frame (%d < %d)\n", *frame_size_ptr, data_size);
1345             return AVERROR(EINVAL);
1346         }
1347
1348         memcpy(samples, frame.extended_data[0], plane_size);
1349
1350         if (planar && avctx->channels > 1) {
1351             uint8_t *out = ((uint8_t *)samples) + plane_size;
1352             for (ch = 1; ch < avctx->channels; ch++) {
1353                 memcpy(out, frame.extended_data[ch], plane_size);
1354                 out += plane_size;
1355             }
1356         }
1357         *frame_size_ptr = data_size;
1358     } else {
1359         *frame_size_ptr = 0;
1360     }
1361     return ret;
1362 }
1363
1364 #endif
1365
1366 int attribute_align_arg avcodec_decode_audio4(AVCodecContext *avctx,
1367                                               AVFrame *frame,
1368                                               int *got_frame_ptr,
1369                                               AVPacket *avpkt)
1370 {
1371     int planar, channels;
1372     int ret = 0;
1373
1374     *got_frame_ptr = 0;
1375
1376     avctx->pkt = avpkt;
1377
1378     if (!avpkt->data && avpkt->size) {
1379         av_log(avctx, AV_LOG_ERROR, "invalid packet: NULL data, size != 0\n");
1380         return AVERROR(EINVAL);
1381     }
1382
1383     apply_param_change(avctx, avpkt);
1384
1385     avcodec_get_frame_defaults(frame);
1386
1387     if ((avctx->codec->capabilities & CODEC_CAP_DELAY) || avpkt->size) {
1388         ret = avctx->codec->decode(avctx, frame, got_frame_ptr, avpkt);
1389         if (ret >= 0 && *got_frame_ptr) {
1390             avctx->frame_number++;
1391             frame->pkt_dts = avpkt->dts;
1392             if (frame->format == AV_SAMPLE_FMT_NONE)
1393                 frame->format = avctx->sample_fmt;
1394         }
1395     }
1396
1397     /* many decoders assign whole AVFrames, thus overwriting extended_data;
1398      * make sure it's set correctly; assume decoders that actually use
1399      * extended_data are doing it correctly */
1400     planar   = av_sample_fmt_is_planar(frame->format);
1401     channels = av_get_channel_layout_nb_channels(frame->channel_layout);
1402     if (!(planar && channels > AV_NUM_DATA_POINTERS))
1403         frame->extended_data = frame->data;
1404
1405     return ret;
1406 }
1407
1408 int avcodec_decode_subtitle2(AVCodecContext *avctx, AVSubtitle *sub,
1409                              int *got_sub_ptr,
1410                              AVPacket *avpkt)
1411 {
1412     int ret;
1413
1414     avctx->pkt = avpkt;
1415     *got_sub_ptr = 0;
1416     ret = avctx->codec->decode(avctx, sub, got_sub_ptr, avpkt);
1417     if (*got_sub_ptr)
1418         avctx->frame_number++;
1419     return ret;
1420 }
1421
1422 void avsubtitle_free(AVSubtitle *sub)
1423 {
1424     int i;
1425
1426     for (i = 0; i < sub->num_rects; i++) {
1427         av_freep(&sub->rects[i]->pict.data[0]);
1428         av_freep(&sub->rects[i]->pict.data[1]);
1429         av_freep(&sub->rects[i]->pict.data[2]);
1430         av_freep(&sub->rects[i]->pict.data[3]);
1431         av_freep(&sub->rects[i]->text);
1432         av_freep(&sub->rects[i]->ass);
1433         av_freep(&sub->rects[i]);
1434     }
1435
1436     av_freep(&sub->rects);
1437
1438     memset(sub, 0, sizeof(AVSubtitle));
1439 }
1440
1441 av_cold int avcodec_close(AVCodecContext *avctx)
1442 {
1443     /* If there is a user-supplied mutex locking routine, call it. */
1444     if (ff_lockmgr_cb) {
1445         if ((*ff_lockmgr_cb)(&codec_mutex, AV_LOCK_OBTAIN))
1446             return -1;
1447     }
1448
1449     entangled_thread_counter++;
1450     if (entangled_thread_counter != 1) {
1451         av_log(avctx, AV_LOG_ERROR, "insufficient thread locking around avcodec_open/close()\n");
1452         entangled_thread_counter--;
1453         return -1;
1454     }
1455
1456     if (avcodec_is_open(avctx)) {
1457         if (HAVE_THREADS && avctx->thread_opaque)
1458             ff_thread_free(avctx);
1459         if (avctx->codec && avctx->codec->close)
1460             avctx->codec->close(avctx);
1461         avcodec_default_free_buffers(avctx);
1462         avctx->coded_frame = NULL;
1463         av_freep(&avctx->internal);
1464     }
1465
1466     if (avctx->priv_data && avctx->codec && avctx->codec->priv_class)
1467         av_opt_free(avctx->priv_data);
1468     av_opt_free(avctx);
1469     av_freep(&avctx->priv_data);
1470     if (av_codec_is_encoder(avctx->codec))
1471         av_freep(&avctx->extradata);
1472     avctx->codec = NULL;
1473     avctx->active_thread_type = 0;
1474     entangled_thread_counter--;
1475
1476     /* Release any user-supplied mutex. */
1477     if (ff_lockmgr_cb) {
1478         (*ff_lockmgr_cb)(&codec_mutex, AV_LOCK_RELEASE);
1479     }
1480     return 0;
1481 }
1482
1483 static AVCodec *find_encdec(enum AVCodecID id, int encoder)
1484 {
1485     AVCodec *p, *experimental = NULL;
1486     p = first_avcodec;
1487     while (p) {
1488         if ((encoder ? av_codec_is_encoder(p) : av_codec_is_decoder(p)) &&
1489             p->id == id) {
1490             if (p->capabilities & CODEC_CAP_EXPERIMENTAL && !experimental) {
1491                 experimental = p;
1492             } else
1493                 return p;
1494         }
1495         p = p->next;
1496     }
1497     return experimental;
1498 }
1499
1500 AVCodec *avcodec_find_encoder(enum AVCodecID id)
1501 {
1502     return find_encdec(id, 1);
1503 }
1504
1505 AVCodec *avcodec_find_encoder_by_name(const char *name)
1506 {
1507     AVCodec *p;
1508     if (!name)
1509         return NULL;
1510     p = first_avcodec;
1511     while (p) {
1512         if (av_codec_is_encoder(p) && strcmp(name, p->name) == 0)
1513             return p;
1514         p = p->next;
1515     }
1516     return NULL;
1517 }
1518
1519 AVCodec *avcodec_find_decoder(enum AVCodecID id)
1520 {
1521     return find_encdec(id, 0);
1522 }
1523
1524 AVCodec *avcodec_find_decoder_by_name(const char *name)
1525 {
1526     AVCodec *p;
1527     if (!name)
1528         return NULL;
1529     p = first_avcodec;
1530     while (p) {
1531         if (av_codec_is_decoder(p) && strcmp(name, p->name) == 0)
1532             return p;
1533         p = p->next;
1534     }
1535     return NULL;
1536 }
1537
1538 static int get_bit_rate(AVCodecContext *ctx)
1539 {
1540     int bit_rate;
1541     int bits_per_sample;
1542
1543     switch (ctx->codec_type) {
1544     case AVMEDIA_TYPE_VIDEO:
1545     case AVMEDIA_TYPE_DATA:
1546     case AVMEDIA_TYPE_SUBTITLE:
1547     case AVMEDIA_TYPE_ATTACHMENT:
1548         bit_rate = ctx->bit_rate;
1549         break;
1550     case AVMEDIA_TYPE_AUDIO:
1551         bits_per_sample = av_get_bits_per_sample(ctx->codec_id);
1552         bit_rate = bits_per_sample ? ctx->sample_rate * ctx->channels * bits_per_sample : ctx->bit_rate;
1553         break;
1554     default:
1555         bit_rate = 0;
1556         break;
1557     }
1558     return bit_rate;
1559 }
1560
1561 size_t av_get_codec_tag_string(char *buf, size_t buf_size, unsigned int codec_tag)
1562 {
1563     int i, len, ret = 0;
1564
1565 #define TAG_PRINT(x)                                              \
1566     (((x) >= '0' && (x) <= '9') ||                                \
1567      ((x) >= 'a' && (x) <= 'z') || ((x) >= 'A' && (x) <= 'Z') ||  \
1568      ((x) == '.' || (x) == ' '))
1569
1570     for (i = 0; i < 4; i++) {
1571         len = snprintf(buf, buf_size,
1572                        TAG_PRINT(codec_tag & 0xFF) ? "%c" : "[%d]", codec_tag & 0xFF);
1573         buf        += len;
1574         buf_size    = buf_size > len ? buf_size - len : 0;
1575         ret        += len;
1576         codec_tag >>= 8;
1577     }
1578     return ret;
1579 }
1580
1581 void avcodec_string(char *buf, int buf_size, AVCodecContext *enc, int encode)
1582 {
1583     const char *codec_name;
1584     const char *profile = NULL;
1585     const AVCodec *p;
1586     char buf1[32];
1587     int bitrate;
1588     AVRational display_aspect_ratio;
1589
1590     if (enc->codec)
1591         p = enc->codec;
1592     else if (encode)
1593         p = avcodec_find_encoder(enc->codec_id);
1594     else
1595         p = avcodec_find_decoder(enc->codec_id);
1596
1597     if (p) {
1598         codec_name = p->name;
1599         profile = av_get_profile_name(p, enc->profile);
1600     } else if (enc->codec_id == AV_CODEC_ID_MPEG2TS) {
1601         /* fake mpeg2 transport stream codec (currently not
1602          * registered) */
1603         codec_name = "mpeg2ts";
1604     } else if (enc->codec_name[0] != '\0') {
1605         codec_name = enc->codec_name;
1606     } else {
1607         /* output avi tags */
1608         char tag_buf[32];
1609         av_get_codec_tag_string(tag_buf, sizeof(tag_buf), enc->codec_tag);
1610         snprintf(buf1, sizeof(buf1), "%s / 0x%04X", tag_buf, enc->codec_tag);
1611         codec_name = buf1;
1612     }
1613
1614     switch (enc->codec_type) {
1615     case AVMEDIA_TYPE_VIDEO:
1616         snprintf(buf, buf_size,
1617                  "Video: %s%s",
1618                  codec_name, enc->mb_decision ? " (hq)" : "");
1619         if (profile)
1620             snprintf(buf + strlen(buf), buf_size - strlen(buf),
1621                      " (%s)", profile);
1622         if (enc->pix_fmt != AV_PIX_FMT_NONE) {
1623             snprintf(buf + strlen(buf), buf_size - strlen(buf),
1624                      ", %s",
1625                      av_get_pix_fmt_name(enc->pix_fmt));
1626         }
1627         if (enc->width) {
1628             snprintf(buf + strlen(buf), buf_size - strlen(buf),
1629                      ", %dx%d",
1630                      enc->width, enc->height);
1631             if (enc->sample_aspect_ratio.num) {
1632                 av_reduce(&display_aspect_ratio.num, &display_aspect_ratio.den,
1633                           enc->width * enc->sample_aspect_ratio.num,
1634                           enc->height * enc->sample_aspect_ratio.den,
1635                           1024 * 1024);
1636                 snprintf(buf + strlen(buf), buf_size - strlen(buf),
1637                          " [PAR %d:%d DAR %d:%d]",
1638                          enc->sample_aspect_ratio.num, enc->sample_aspect_ratio.den,
1639                          display_aspect_ratio.num, display_aspect_ratio.den);
1640             }
1641             if (av_log_get_level() >= AV_LOG_DEBUG) {
1642                 int g = av_gcd(enc->time_base.num, enc->time_base.den);
1643                 snprintf(buf + strlen(buf), buf_size - strlen(buf),
1644                          ", %d/%d",
1645                          enc->time_base.num / g, enc->time_base.den / g);
1646             }
1647         }
1648         if (encode) {
1649             snprintf(buf + strlen(buf), buf_size - strlen(buf),
1650                      ", q=%d-%d", enc->qmin, enc->qmax);
1651         }
1652         break;
1653     case AVMEDIA_TYPE_AUDIO:
1654         snprintf(buf, buf_size,
1655                  "Audio: %s",
1656                  codec_name);
1657         if (profile)
1658             snprintf(buf + strlen(buf), buf_size - strlen(buf),
1659                      " (%s)", profile);
1660         if (enc->sample_rate) {
1661             snprintf(buf + strlen(buf), buf_size - strlen(buf),
1662                      ", %d Hz", enc->sample_rate);
1663         }
1664         av_strlcat(buf, ", ", buf_size);
1665         av_get_channel_layout_string(buf + strlen(buf), buf_size - strlen(buf), enc->channels, enc->channel_layout);
1666         if (enc->sample_fmt != AV_SAMPLE_FMT_NONE) {
1667             snprintf(buf + strlen(buf), buf_size - strlen(buf),
1668                      ", %s", av_get_sample_fmt_name(enc->sample_fmt));
1669         }
1670         break;
1671     case AVMEDIA_TYPE_DATA:
1672         snprintf(buf, buf_size, "Data: %s", codec_name);
1673         break;
1674     case AVMEDIA_TYPE_SUBTITLE:
1675         snprintf(buf, buf_size, "Subtitle: %s", codec_name);
1676         break;
1677     case AVMEDIA_TYPE_ATTACHMENT:
1678         snprintf(buf, buf_size, "Attachment: %s", codec_name);
1679         break;
1680     default:
1681         snprintf(buf, buf_size, "Invalid Codec type %d", enc->codec_type);
1682         return;
1683     }
1684     if (encode) {
1685         if (enc->flags & CODEC_FLAG_PASS1)
1686             snprintf(buf + strlen(buf), buf_size - strlen(buf),
1687                      ", pass 1");
1688         if (enc->flags & CODEC_FLAG_PASS2)
1689             snprintf(buf + strlen(buf), buf_size - strlen(buf),
1690                      ", pass 2");
1691     }
1692     bitrate = get_bit_rate(enc);
1693     if (bitrate != 0) {
1694         snprintf(buf + strlen(buf), buf_size - strlen(buf),
1695                  ", %d kb/s", bitrate / 1000);
1696     }
1697 }
1698
1699 const char *av_get_profile_name(const AVCodec *codec, int profile)
1700 {
1701     const AVProfile *p;
1702     if (profile == FF_PROFILE_UNKNOWN || !codec->profiles)
1703         return NULL;
1704
1705     for (p = codec->profiles; p->profile != FF_PROFILE_UNKNOWN; p++)
1706         if (p->profile == profile)
1707             return p->name;
1708
1709     return NULL;
1710 }
1711
1712 unsigned avcodec_version(void)
1713 {
1714     return LIBAVCODEC_VERSION_INT;
1715 }
1716
1717 const char *avcodec_configuration(void)
1718 {
1719     return LIBAV_CONFIGURATION;
1720 }
1721
1722 const char *avcodec_license(void)
1723 {
1724 #define LICENSE_PREFIX "libavcodec license: "
1725     return LICENSE_PREFIX LIBAV_LICENSE + sizeof(LICENSE_PREFIX) - 1;
1726 }
1727
1728 void avcodec_flush_buffers(AVCodecContext *avctx)
1729 {
1730     if (HAVE_THREADS && avctx->active_thread_type & FF_THREAD_FRAME)
1731         ff_thread_flush(avctx);
1732     else if (avctx->codec->flush)
1733         avctx->codec->flush(avctx);
1734 }
1735
1736 static void video_free_buffers(AVCodecContext *s)
1737 {
1738     AVCodecInternal *avci = s->internal;
1739     int i, j;
1740
1741     if (!avci->buffer)
1742         return;
1743
1744     if (avci->buffer_count)
1745         av_log(s, AV_LOG_WARNING, "Found %i unreleased buffers!\n",
1746                avci->buffer_count);
1747     for (i = 0; i < INTERNAL_BUFFER_SIZE; i++) {
1748         InternalBuffer *buf = &avci->buffer[i];
1749         for (j = 0; j < 4; j++) {
1750             av_freep(&buf->base[j]);
1751             buf->data[j] = NULL;
1752         }
1753     }
1754     av_freep(&avci->buffer);
1755
1756     avci->buffer_count = 0;
1757 }
1758
1759 static void audio_free_buffers(AVCodecContext *avctx)
1760 {
1761     AVCodecInternal *avci = avctx->internal;
1762     av_freep(&avci->audio_data);
1763 }
1764
1765 void avcodec_default_free_buffers(AVCodecContext *avctx)
1766 {
1767     switch (avctx->codec_type) {
1768     case AVMEDIA_TYPE_VIDEO:
1769         video_free_buffers(avctx);
1770         break;
1771     case AVMEDIA_TYPE_AUDIO:
1772         audio_free_buffers(avctx);
1773         break;
1774     default:
1775         break;
1776     }
1777 }
1778
1779 int av_get_exact_bits_per_sample(enum AVCodecID codec_id)
1780 {
1781     switch (codec_id) {
1782     case AV_CODEC_ID_ADPCM_CT:
1783     case AV_CODEC_ID_ADPCM_IMA_APC:
1784     case AV_CODEC_ID_ADPCM_IMA_EA_SEAD:
1785     case AV_CODEC_ID_ADPCM_IMA_WS:
1786     case AV_CODEC_ID_ADPCM_G722:
1787     case AV_CODEC_ID_ADPCM_YAMAHA:
1788         return 4;
1789     case AV_CODEC_ID_PCM_ALAW:
1790     case AV_CODEC_ID_PCM_MULAW:
1791     case AV_CODEC_ID_PCM_S8:
1792     case AV_CODEC_ID_PCM_U8:
1793     case AV_CODEC_ID_PCM_ZORK:
1794         return 8;
1795     case AV_CODEC_ID_PCM_S16BE:
1796     case AV_CODEC_ID_PCM_S16LE:
1797     case AV_CODEC_ID_PCM_S16LE_PLANAR:
1798     case AV_CODEC_ID_PCM_U16BE:
1799     case AV_CODEC_ID_PCM_U16LE:
1800         return 16;
1801     case AV_CODEC_ID_PCM_S24DAUD:
1802     case AV_CODEC_ID_PCM_S24BE:
1803     case AV_CODEC_ID_PCM_S24LE:
1804     case AV_CODEC_ID_PCM_U24BE:
1805     case AV_CODEC_ID_PCM_U24LE:
1806         return 24;
1807     case AV_CODEC_ID_PCM_S32BE:
1808     case AV_CODEC_ID_PCM_S32LE:
1809     case AV_CODEC_ID_PCM_U32BE:
1810     case AV_CODEC_ID_PCM_U32LE:
1811     case AV_CODEC_ID_PCM_F32BE:
1812     case AV_CODEC_ID_PCM_F32LE:
1813         return 32;
1814     case AV_CODEC_ID_PCM_F64BE:
1815     case AV_CODEC_ID_PCM_F64LE:
1816         return 64;
1817     default:
1818         return 0;
1819     }
1820 }
1821
1822 int av_get_bits_per_sample(enum AVCodecID codec_id)
1823 {
1824     switch (codec_id) {
1825     case AV_CODEC_ID_ADPCM_SBPRO_2:
1826         return 2;
1827     case AV_CODEC_ID_ADPCM_SBPRO_3:
1828         return 3;
1829     case AV_CODEC_ID_ADPCM_SBPRO_4:
1830     case AV_CODEC_ID_ADPCM_IMA_WAV:
1831     case AV_CODEC_ID_ADPCM_IMA_QT:
1832     case AV_CODEC_ID_ADPCM_SWF:
1833     case AV_CODEC_ID_ADPCM_MS:
1834         return 4;
1835     default:
1836         return av_get_exact_bits_per_sample(codec_id);
1837     }
1838 }
1839
1840 int av_get_audio_frame_duration(AVCodecContext *avctx, int frame_bytes)
1841 {
1842     int id, sr, ch, ba, tag, bps;
1843
1844     id  = avctx->codec_id;
1845     sr  = avctx->sample_rate;
1846     ch  = avctx->channels;
1847     ba  = avctx->block_align;
1848     tag = avctx->codec_tag;
1849     bps = av_get_exact_bits_per_sample(avctx->codec_id);
1850
1851     /* codecs with an exact constant bits per sample */
1852     if (bps > 0 && ch > 0 && frame_bytes > 0)
1853         return (frame_bytes * 8) / (bps * ch);
1854     bps = avctx->bits_per_coded_sample;
1855
1856     /* codecs with a fixed packet duration */
1857     switch (id) {
1858     case AV_CODEC_ID_ADPCM_ADX:    return   32;
1859     case AV_CODEC_ID_ADPCM_IMA_QT: return   64;
1860     case AV_CODEC_ID_ADPCM_EA_XAS: return  128;
1861     case AV_CODEC_ID_AMR_NB:
1862     case AV_CODEC_ID_GSM:
1863     case AV_CODEC_ID_QCELP:
1864     case AV_CODEC_ID_RA_144:
1865     case AV_CODEC_ID_RA_288:       return  160;
1866     case AV_CODEC_ID_IMC:          return  256;
1867     case AV_CODEC_ID_AMR_WB:
1868     case AV_CODEC_ID_GSM_MS:       return  320;
1869     case AV_CODEC_ID_MP1:          return  384;
1870     case AV_CODEC_ID_ATRAC1:       return  512;
1871     case AV_CODEC_ID_ATRAC3:       return 1024;
1872     case AV_CODEC_ID_MP2:
1873     case AV_CODEC_ID_MUSEPACK7:    return 1152;
1874     case AV_CODEC_ID_AC3:          return 1536;
1875     }
1876
1877     if (sr > 0) {
1878         /* calc from sample rate */
1879         if (id == AV_CODEC_ID_TTA)
1880             return 256 * sr / 245;
1881
1882         if (ch > 0) {
1883             /* calc from sample rate and channels */
1884             if (id == AV_CODEC_ID_BINKAUDIO_DCT)
1885                 return (480 << (sr / 22050)) / ch;
1886         }
1887     }
1888
1889     if (ba > 0) {
1890         /* calc from block_align */
1891         if (id == AV_CODEC_ID_SIPR) {
1892             switch (ba) {
1893             case 20: return 160;
1894             case 19: return 144;
1895             case 29: return 288;
1896             case 37: return 480;
1897             }
1898         } else if (id == AV_CODEC_ID_ILBC) {
1899             switch (ba) {
1900             case 38: return 160;
1901             case 50: return 240;
1902             }
1903         }
1904     }
1905
1906     if (frame_bytes > 0) {
1907         /* calc from frame_bytes only */
1908         if (id == AV_CODEC_ID_TRUESPEECH)
1909             return 240 * (frame_bytes / 32);
1910         if (id == AV_CODEC_ID_NELLYMOSER)
1911             return 256 * (frame_bytes / 64);
1912
1913         if (bps > 0) {
1914             /* calc from frame_bytes and bits_per_coded_sample */
1915             if (id == AV_CODEC_ID_ADPCM_G726)
1916                 return frame_bytes * 8 / bps;
1917         }
1918
1919         if (ch > 0) {
1920             /* calc from frame_bytes and channels */
1921             switch (id) {
1922             case AV_CODEC_ID_ADPCM_4XM:
1923             case AV_CODEC_ID_ADPCM_IMA_ISS:
1924                 return (frame_bytes - 4 * ch) * 2 / ch;
1925             case AV_CODEC_ID_ADPCM_IMA_SMJPEG:
1926                 return (frame_bytes - 4) * 2 / ch;
1927             case AV_CODEC_ID_ADPCM_IMA_AMV:
1928                 return (frame_bytes - 8) * 2 / ch;
1929             case AV_CODEC_ID_ADPCM_XA:
1930                 return (frame_bytes / 128) * 224 / ch;
1931             case AV_CODEC_ID_INTERPLAY_DPCM:
1932                 return (frame_bytes - 6 - ch) / ch;
1933             case AV_CODEC_ID_ROQ_DPCM:
1934                 return (frame_bytes - 8) / ch;
1935             case AV_CODEC_ID_XAN_DPCM:
1936                 return (frame_bytes - 2 * ch) / ch;
1937             case AV_CODEC_ID_MACE3:
1938                 return 3 * frame_bytes / ch;
1939             case AV_CODEC_ID_MACE6:
1940                 return 6 * frame_bytes / ch;
1941             case AV_CODEC_ID_PCM_LXF:
1942                 return 2 * (frame_bytes / (5 * ch));
1943             }
1944
1945             if (tag) {
1946                 /* calc from frame_bytes, channels, and codec_tag */
1947                 if (id == AV_CODEC_ID_SOL_DPCM) {
1948                     if (tag == 3)
1949                         return frame_bytes / ch;
1950                     else
1951                         return frame_bytes * 2 / ch;
1952                 }
1953             }
1954
1955             if (ba > 0) {
1956                 /* calc from frame_bytes, channels, and block_align */
1957                 int blocks = frame_bytes / ba;
1958                 switch (avctx->codec_id) {
1959                 case AV_CODEC_ID_ADPCM_IMA_WAV:
1960                     return blocks * (1 + (ba - 4 * ch) / (4 * ch) * 8);
1961                 case AV_CODEC_ID_ADPCM_IMA_DK3:
1962                     return blocks * (((ba - 16) * 2 / 3 * 4) / ch);
1963                 case AV_CODEC_ID_ADPCM_IMA_DK4:
1964                     return blocks * (1 + (ba - 4 * ch) * 2 / ch);
1965                 case AV_CODEC_ID_ADPCM_MS:
1966                     return blocks * (2 + (ba - 7 * ch) * 2 / ch);
1967                 }
1968             }
1969
1970             if (bps > 0) {
1971                 /* calc from frame_bytes, channels, and bits_per_coded_sample */
1972                 switch (avctx->codec_id) {
1973                 case AV_CODEC_ID_PCM_DVD:
1974                     return 2 * (frame_bytes / ((bps * 2 / 8) * ch));
1975                 case AV_CODEC_ID_PCM_BLURAY:
1976                     return frame_bytes / ((FFALIGN(ch, 2) * bps) / 8);
1977                 case AV_CODEC_ID_S302M:
1978                     return 2 * (frame_bytes / ((bps + 4) / 4)) / ch;
1979                 }
1980             }
1981         }
1982     }
1983
1984     return 0;
1985 }
1986
1987 #if !HAVE_THREADS
1988 int ff_thread_init(AVCodecContext *s)
1989 {
1990     return -1;
1991 }
1992
1993 #endif
1994
1995 unsigned int av_xiphlacing(unsigned char *s, unsigned int v)
1996 {
1997     unsigned int n = 0;
1998
1999     while (v >= 0xff) {
2000         *s++ = 0xff;
2001         v -= 0xff;
2002         n++;
2003     }
2004     *s = v;
2005     n++;
2006     return n;
2007 }
2008
2009 int ff_match_2uint16(const uint16_t(*tab)[2], int size, int a, int b)
2010 {
2011     int i;
2012     for (i = 0; i < size && !(tab[i][0] == a && tab[i][1] == b); i++) ;
2013     return i;
2014 }
2015
2016 void av_log_missing_feature(void *avc, const char *feature, int want_sample)
2017 {
2018     av_log(avc, AV_LOG_WARNING, "%s is not implemented. Update your Libav "
2019             "version to the newest one from Git. If the problem still "
2020             "occurs, it means that your file has a feature which has not "
2021             "been implemented.\n", feature);
2022     if(want_sample)
2023         av_log_ask_for_sample(avc, NULL);
2024 }
2025
2026 void av_log_ask_for_sample(void *avc, const char *msg, ...)
2027 {
2028     va_list argument_list;
2029
2030     va_start(argument_list, msg);
2031
2032     if (msg)
2033         av_vlog(avc, AV_LOG_WARNING, msg, argument_list);
2034     av_log(avc, AV_LOG_WARNING, "If you want to help, upload a sample "
2035             "of this file to ftp://upload.libav.org/incoming/ "
2036             "and contact the libav-devel mailing list.\n");
2037
2038     va_end(argument_list);
2039 }
2040
2041 static AVHWAccel *first_hwaccel = NULL;
2042
2043 void av_register_hwaccel(AVHWAccel *hwaccel)
2044 {
2045     AVHWAccel **p = &first_hwaccel;
2046     while (*p)
2047         p = &(*p)->next;
2048     *p = hwaccel;
2049     hwaccel->next = NULL;
2050 }
2051
2052 AVHWAccel *av_hwaccel_next(AVHWAccel *hwaccel)
2053 {
2054     return hwaccel ? hwaccel->next : first_hwaccel;
2055 }
2056
2057 AVHWAccel *ff_find_hwaccel(enum AVCodecID codec_id, enum AVPixelFormat pix_fmt)
2058 {
2059     AVHWAccel *hwaccel = NULL;
2060
2061     while ((hwaccel = av_hwaccel_next(hwaccel)))
2062         if (hwaccel->id == codec_id
2063             && hwaccel->pix_fmt == pix_fmt)
2064             return hwaccel;
2065     return NULL;
2066 }
2067
2068 int av_lockmgr_register(int (*cb)(void **mutex, enum AVLockOp op))
2069 {
2070     if (ff_lockmgr_cb) {
2071         if (ff_lockmgr_cb(&codec_mutex, AV_LOCK_DESTROY))
2072             return -1;
2073         if (ff_lockmgr_cb(&avformat_mutex, AV_LOCK_DESTROY))
2074             return -1;
2075     }
2076
2077     ff_lockmgr_cb = cb;
2078
2079     if (ff_lockmgr_cb) {
2080         if (ff_lockmgr_cb(&codec_mutex, AV_LOCK_CREATE))
2081             return -1;
2082         if (ff_lockmgr_cb(&avformat_mutex, AV_LOCK_CREATE))
2083             return -1;
2084     }
2085     return 0;
2086 }
2087
2088 int avpriv_lock_avformat(void)
2089 {
2090     if (ff_lockmgr_cb) {
2091         if ((*ff_lockmgr_cb)(&avformat_mutex, AV_LOCK_OBTAIN))
2092             return -1;
2093     }
2094     return 0;
2095 }
2096
2097 int avpriv_unlock_avformat(void)
2098 {
2099     if (ff_lockmgr_cb) {
2100         if ((*ff_lockmgr_cb)(&avformat_mutex, AV_LOCK_RELEASE))
2101             return -1;
2102     }
2103     return 0;
2104 }
2105
2106 unsigned int avpriv_toupper4(unsigned int x)
2107 {
2108     return av_toupper(x & 0xFF) +
2109           (av_toupper((x >>  8) & 0xFF) << 8)  +
2110           (av_toupper((x >> 16) & 0xFF) << 16) +
2111           (av_toupper((x >> 24) & 0xFF) << 24);
2112 }
2113
2114 #if !HAVE_THREADS
2115
2116 int ff_thread_get_buffer(AVCodecContext *avctx, AVFrame *f)
2117 {
2118     f->owner = avctx;
2119     return ff_get_buffer(avctx, f);
2120 }
2121
2122 void ff_thread_release_buffer(AVCodecContext *avctx, AVFrame *f)
2123 {
2124     f->owner->release_buffer(f->owner, f);
2125 }
2126
2127 void ff_thread_finish_setup(AVCodecContext *avctx)
2128 {
2129 }
2130
2131 void ff_thread_report_progress(AVFrame *f, int progress, int field)
2132 {
2133 }
2134
2135 void ff_thread_await_progress(AVFrame *f, int progress, int field)
2136 {
2137 }
2138
2139 #endif
2140
2141 enum AVMediaType avcodec_get_type(enum AVCodecID codec_id)
2142 {
2143     if (codec_id <= AV_CODEC_ID_NONE)
2144         return AVMEDIA_TYPE_UNKNOWN;
2145     else if (codec_id < AV_CODEC_ID_FIRST_AUDIO)
2146         return AVMEDIA_TYPE_VIDEO;
2147     else if (codec_id < AV_CODEC_ID_FIRST_SUBTITLE)
2148         return AVMEDIA_TYPE_AUDIO;
2149     else if (codec_id < AV_CODEC_ID_FIRST_UNKNOWN)
2150         return AVMEDIA_TYPE_SUBTITLE;
2151
2152     return AVMEDIA_TYPE_UNKNOWN;
2153 }
2154
2155 int avcodec_is_open(AVCodecContext *s)
2156 {
2157     return !!s->internal;
2158 }