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