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