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