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