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