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