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