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