]> git.sesse.net Git - ffmpeg/blob - libavcodec/utils.c
lavc: Drop deprecated voxware codec entry
[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/hwcontext.h"
36 #include "libavutil/internal.h"
37 #include "libavutil/mathematics.h"
38 #include "libavutil/pixdesc.h"
39 #include "libavutil/imgutils.h"
40 #include "libavutil/samplefmt.h"
41 #include "libavutil/dict.h"
42 #include "avcodec.h"
43 #include "decode.h"
44 #include "libavutil/opt.h"
45 #include "me_cmp.h"
46 #include "mpegvideo.h"
47 #include "thread.h"
48 #include "internal.h"
49 #include "bytestream.h"
50 #include "version.h"
51 #include <stdlib.h>
52 #include <stdarg.h>
53 #include <limits.h>
54 #include <float.h>
55
56 static int volatile entangled_thread_counter = 0;
57 static int (*lockmgr_cb)(void **mutex, enum AVLockOp op);
58 static void *codec_mutex;
59 static void *avformat_mutex;
60
61 void av_fast_padded_malloc(void *ptr, unsigned int *size, size_t min_size)
62 {
63     void **p = ptr;
64     if (min_size > SIZE_MAX - AV_INPUT_BUFFER_PADDING_SIZE) {
65         av_freep(p);
66         *size = 0;
67         return;
68     }
69     av_fast_malloc(p, size, min_size + AV_INPUT_BUFFER_PADDING_SIZE);
70     if (*size)
71         memset((uint8_t *)*p + min_size, 0, AV_INPUT_BUFFER_PADDING_SIZE);
72 }
73
74 /* encoder management */
75 static AVCodec *first_avcodec = NULL;
76
77 AVCodec *av_codec_next(const AVCodec *c)
78 {
79     if (c)
80         return c->next;
81     else
82         return first_avcodec;
83 }
84
85 static av_cold void avcodec_init(void)
86 {
87     static int initialized = 0;
88
89     if (initialized != 0)
90         return;
91     initialized = 1;
92
93     if (CONFIG_ME_CMP)
94         ff_me_cmp_init_static();
95 }
96
97 int av_codec_is_encoder(const AVCodec *codec)
98 {
99     return codec && (codec->encode_sub || codec->encode2 ||codec->send_frame);
100 }
101
102 int av_codec_is_decoder(const AVCodec *codec)
103 {
104     return codec && (codec->decode || codec->receive_frame);
105 }
106
107 av_cold void avcodec_register(AVCodec *codec)
108 {
109     AVCodec **p;
110     avcodec_init();
111     p = &first_avcodec;
112     while (*p)
113         p = &(*p)->next;
114     *p          = codec;
115     codec->next = NULL;
116
117     if (codec->init_static_data)
118         codec->init_static_data(codec);
119 }
120
121 #if FF_API_EMU_EDGE
122 unsigned avcodec_get_edge_width(void)
123 {
124     return EDGE_WIDTH;
125 }
126 #endif
127
128 #if FF_API_SET_DIMENSIONS
129 void avcodec_set_dimensions(AVCodecContext *s, int width, int height)
130 {
131     ff_set_dimensions(s, width, height);
132 }
133 #endif
134
135 int ff_set_dimensions(AVCodecContext *s, int width, int height)
136 {
137     int ret = av_image_check_size(width, height, 0, s);
138
139     if (ret < 0)
140         width = height = 0;
141     s->width  = s->coded_width  = width;
142     s->height = s->coded_height = height;
143
144     return ret;
145 }
146
147 int ff_set_sar(AVCodecContext *avctx, AVRational sar)
148 {
149     int ret = av_image_check_sar(avctx->width, avctx->height, sar);
150
151     if (ret < 0) {
152         av_log(avctx, AV_LOG_WARNING, "ignoring invalid SAR: %d/%d\n",
153                sar.num, sar.den);
154         avctx->sample_aspect_ratio = (AVRational){ 0, 1 };
155         return ret;
156     } else {
157         avctx->sample_aspect_ratio = sar;
158     }
159     return 0;
160 }
161
162 int ff_side_data_update_matrix_encoding(AVFrame *frame,
163                                         enum AVMatrixEncoding matrix_encoding)
164 {
165     AVFrameSideData *side_data;
166     enum AVMatrixEncoding *data;
167
168     side_data = av_frame_get_side_data(frame, AV_FRAME_DATA_MATRIXENCODING);
169     if (!side_data)
170         side_data = av_frame_new_side_data(frame, AV_FRAME_DATA_MATRIXENCODING,
171                                            sizeof(enum AVMatrixEncoding));
172
173     if (!side_data)
174         return AVERROR(ENOMEM);
175
176     data  = (enum AVMatrixEncoding*)side_data->data;
177     *data = matrix_encoding;
178
179     return 0;
180 }
181
182 void avcodec_align_dimensions2(AVCodecContext *s, int *width, int *height,
183                                int linesize_align[AV_NUM_DATA_POINTERS])
184 {
185     size_t max_align = av_cpu_max_align();
186     int i;
187     int w_align = 1;
188     int h_align = 1;
189
190     switch (s->pix_fmt) {
191     case AV_PIX_FMT_YUV420P:
192     case AV_PIX_FMT_YUYV422:
193     case AV_PIX_FMT_YVYU422:
194     case AV_PIX_FMT_UYVY422:
195     case AV_PIX_FMT_YUV422P:
196     case AV_PIX_FMT_YUV440P:
197     case AV_PIX_FMT_YUV444P:
198     case AV_PIX_FMT_GBRP:
199     case AV_PIX_FMT_GBRAP:
200     case AV_PIX_FMT_GRAY8:
201     case AV_PIX_FMT_GRAY16BE:
202     case AV_PIX_FMT_GRAY16LE:
203     case AV_PIX_FMT_YUVJ420P:
204     case AV_PIX_FMT_YUVJ422P:
205     case AV_PIX_FMT_YUVJ440P:
206     case AV_PIX_FMT_YUVJ444P:
207     case AV_PIX_FMT_YUVA420P:
208     case AV_PIX_FMT_YUVA422P:
209     case AV_PIX_FMT_YUVA444P:
210     case AV_PIX_FMT_YUV420P9LE:
211     case AV_PIX_FMT_YUV420P9BE:
212     case AV_PIX_FMT_YUV420P10LE:
213     case AV_PIX_FMT_YUV420P10BE:
214     case AV_PIX_FMT_YUV422P9LE:
215     case AV_PIX_FMT_YUV422P9BE:
216     case AV_PIX_FMT_YUV422P10LE:
217     case AV_PIX_FMT_YUV422P10BE:
218     case AV_PIX_FMT_YUVA422P10LE:
219     case AV_PIX_FMT_YUVA422P10BE:
220     case AV_PIX_FMT_YUV444P9LE:
221     case AV_PIX_FMT_YUV444P9BE:
222     case AV_PIX_FMT_YUV444P10LE:
223     case AV_PIX_FMT_YUV444P10BE:
224     case AV_PIX_FMT_YUVA444P10LE:
225     case AV_PIX_FMT_YUVA444P10BE:
226     case AV_PIX_FMT_GBRP9LE:
227     case AV_PIX_FMT_GBRP9BE:
228     case AV_PIX_FMT_GBRP10LE:
229     case AV_PIX_FMT_GBRP10BE:
230     case AV_PIX_FMT_GBRAP12LE:
231     case AV_PIX_FMT_GBRAP12BE:
232         w_align = 16; //FIXME assume 16 pixel per macroblock
233         h_align = 16 * 2; // interlaced needs 2 macroblocks height
234         break;
235     case AV_PIX_FMT_YUV411P:
236     case AV_PIX_FMT_UYYVYY411:
237         w_align = 32;
238         h_align = 8;
239         break;
240     case AV_PIX_FMT_YUV410P:
241         if (s->codec_id == AV_CODEC_ID_SVQ1) {
242             w_align = 64;
243             h_align = 64;
244         }
245     case AV_PIX_FMT_RGB555:
246         if (s->codec_id == AV_CODEC_ID_RPZA) {
247             w_align = 4;
248             h_align = 4;
249         }
250     case AV_PIX_FMT_PAL8:
251     case AV_PIX_FMT_BGR8:
252     case AV_PIX_FMT_RGB8:
253         if (s->codec_id == AV_CODEC_ID_SMC) {
254             w_align = 4;
255             h_align = 4;
256         }
257         break;
258     case AV_PIX_FMT_BGR24:
259         if ((s->codec_id == AV_CODEC_ID_MSZH) ||
260             (s->codec_id == AV_CODEC_ID_ZLIB)) {
261             w_align = 4;
262             h_align = 4;
263         }
264         break;
265     default:
266         w_align = 1;
267         h_align = 1;
268         break;
269     }
270
271     *width  = FFALIGN(*width, w_align);
272     *height = FFALIGN(*height, h_align);
273     if (s->codec_id == AV_CODEC_ID_H264)
274         // some of the optimized chroma MC reads one line too much
275         *height += 2;
276
277     for (i = 0; i < 4; i++)
278         linesize_align[i] = max_align;
279 }
280
281 void avcodec_align_dimensions(AVCodecContext *s, int *width, int *height)
282 {
283     const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(s->pix_fmt);
284     int chroma_shift = desc->log2_chroma_w;
285     int linesize_align[AV_NUM_DATA_POINTERS];
286     int align;
287
288     avcodec_align_dimensions2(s, width, height, linesize_align);
289     align               = FFMAX(linesize_align[0], linesize_align[3]);
290     linesize_align[1] <<= chroma_shift;
291     linesize_align[2] <<= chroma_shift;
292     align               = FFMAX3(align, linesize_align[1], linesize_align[2]);
293     *width              = FFALIGN(*width, align);
294 }
295
296 int avcodec_fill_audio_frame(AVFrame *frame, int nb_channels,
297                              enum AVSampleFormat sample_fmt, const uint8_t *buf,
298                              int buf_size, int align)
299 {
300     int ch, planar, needed_size, ret = 0;
301
302     needed_size = av_samples_get_buffer_size(NULL, nb_channels,
303                                              frame->nb_samples, sample_fmt,
304                                              align);
305     if (buf_size < needed_size)
306         return AVERROR(EINVAL);
307
308     planar = av_sample_fmt_is_planar(sample_fmt);
309     if (planar && nb_channels > AV_NUM_DATA_POINTERS) {
310         if (!(frame->extended_data = av_mallocz(nb_channels *
311                                                 sizeof(*frame->extended_data))))
312             return AVERROR(ENOMEM);
313     } else {
314         frame->extended_data = frame->data;
315     }
316
317     if ((ret = av_samples_fill_arrays(frame->extended_data, &frame->linesize[0],
318                                       buf, nb_channels, frame->nb_samples,
319                                       sample_fmt, align)) < 0) {
320         if (frame->extended_data != frame->data)
321             av_free(frame->extended_data);
322         return ret;
323     }
324     if (frame->extended_data != frame->data) {
325         for (ch = 0; ch < AV_NUM_DATA_POINTERS; ch++)
326             frame->data[ch] = frame->extended_data[ch];
327     }
328
329     return ret;
330 }
331
332 int avcodec_default_execute(AVCodecContext *c, int (*func)(AVCodecContext *c2, void *arg2), void *arg, int *ret, int count, int size)
333 {
334     int i;
335
336     for (i = 0; i < count; i++) {
337         int r = func(c, (char *)arg + i * size);
338         if (ret)
339             ret[i] = r;
340     }
341     return 0;
342 }
343
344 int avcodec_default_execute2(AVCodecContext *c, int (*func)(AVCodecContext *c2, void *arg2, int jobnr, int threadnr), void *arg, int *ret, int count)
345 {
346     int i;
347
348     for (i = 0; i < count; i++) {
349         int r = func(c, arg, i, 0);
350         if (ret)
351             ret[i] = r;
352     }
353     return 0;
354 }
355
356 int attribute_align_arg avcodec_open2(AVCodecContext *avctx, const AVCodec *codec, AVDictionary **options)
357 {
358     int ret = 0;
359     AVDictionary *tmp = NULL;
360
361     if (avcodec_is_open(avctx))
362         return 0;
363
364     if ((!codec && !avctx->codec)) {
365         av_log(avctx, AV_LOG_ERROR, "No codec provided to avcodec_open2().\n");
366         return AVERROR(EINVAL);
367     }
368     if ((codec && avctx->codec && codec != avctx->codec)) {
369         av_log(avctx, AV_LOG_ERROR, "This AVCodecContext was allocated for %s, "
370                                     "but %s passed to avcodec_open2().\n", avctx->codec->name, codec->name);
371         return AVERROR(EINVAL);
372     }
373     if (!codec)
374         codec = avctx->codec;
375
376     if (avctx->extradata_size < 0 || avctx->extradata_size >= FF_MAX_EXTRADATA_SIZE)
377         return AVERROR(EINVAL);
378
379     if (options)
380         av_dict_copy(&tmp, *options, 0);
381
382     /* If there is a user-supplied mutex locking routine, call it. */
383     if (!(codec->caps_internal & FF_CODEC_CAP_INIT_THREADSAFE) && codec->init) {
384         if (lockmgr_cb) {
385             if ((*lockmgr_cb)(&codec_mutex, AV_LOCK_OBTAIN))
386                 return -1;
387         }
388
389         entangled_thread_counter++;
390         if (entangled_thread_counter != 1) {
391             av_log(avctx, AV_LOG_ERROR,
392                    "Insufficient thread locking. At least %d threads are "
393                    "calling avcodec_open2() at the same time right now.\n",
394                    entangled_thread_counter);
395             ret = -1;
396             goto end;
397         }
398     }
399
400     avctx->internal = av_mallocz(sizeof(AVCodecInternal));
401     if (!avctx->internal) {
402         ret = AVERROR(ENOMEM);
403         goto end;
404     }
405
406     avctx->internal->pool = av_mallocz(sizeof(*avctx->internal->pool));
407     if (!avctx->internal->pool) {
408         ret = AVERROR(ENOMEM);
409         goto free_and_end;
410     }
411
412     avctx->internal->to_free = av_frame_alloc();
413     if (!avctx->internal->to_free) {
414         ret = AVERROR(ENOMEM);
415         goto free_and_end;
416     }
417
418     avctx->internal->compat_decode_frame = av_frame_alloc();
419     if (!avctx->internal->compat_decode_frame) {
420         ret = AVERROR(ENOMEM);
421         goto free_and_end;
422     }
423
424     avctx->internal->buffer_frame = av_frame_alloc();
425     if (!avctx->internal->buffer_frame) {
426         ret = AVERROR(ENOMEM);
427         goto free_and_end;
428     }
429
430     avctx->internal->buffer_pkt = av_packet_alloc();
431     if (!avctx->internal->buffer_pkt) {
432         ret = AVERROR(ENOMEM);
433         goto free_and_end;
434     }
435
436     avctx->internal->ds.in_pkt = av_packet_alloc();
437     if (!avctx->internal->ds.in_pkt) {
438         ret = AVERROR(ENOMEM);
439         goto free_and_end;
440     }
441
442     avctx->internal->last_pkt_props = av_packet_alloc();
443     if (!avctx->internal->last_pkt_props) {
444         ret = AVERROR(ENOMEM);
445         goto free_and_end;
446     }
447
448     if (codec->priv_data_size > 0) {
449         if (!avctx->priv_data) {
450             avctx->priv_data = av_mallocz(codec->priv_data_size);
451             if (!avctx->priv_data) {
452                 ret = AVERROR(ENOMEM);
453                 goto end;
454             }
455             if (codec->priv_class) {
456                 *(const AVClass **)avctx->priv_data = codec->priv_class;
457                 av_opt_set_defaults(avctx->priv_data);
458             }
459         }
460         if (codec->priv_class && (ret = av_opt_set_dict(avctx->priv_data, &tmp)) < 0)
461             goto free_and_end;
462     } else {
463         avctx->priv_data = NULL;
464     }
465     if ((ret = av_opt_set_dict(avctx, &tmp)) < 0)
466         goto free_and_end;
467
468     if (avctx->coded_width && avctx->coded_height && !avctx->width && !avctx->height)
469         ret = ff_set_dimensions(avctx, avctx->coded_width, avctx->coded_height);
470     else if (avctx->width && avctx->height)
471         ret = ff_set_dimensions(avctx, avctx->width, avctx->height);
472     if (ret < 0)
473         goto free_and_end;
474
475     if ((avctx->coded_width || avctx->coded_height || avctx->width || avctx->height)
476         && (  av_image_check_size(avctx->coded_width, avctx->coded_height, 0, avctx) < 0
477            || av_image_check_size(avctx->width,       avctx->height,       0, avctx) < 0)) {
478         av_log(avctx, AV_LOG_WARNING, "ignoring invalid width/height values\n");
479         ff_set_dimensions(avctx, 0, 0);
480     }
481
482     if (avctx->width > 0 && avctx->height > 0) {
483         if (av_image_check_sar(avctx->width, avctx->height,
484                                avctx->sample_aspect_ratio) < 0) {
485             av_log(avctx, AV_LOG_WARNING, "ignoring invalid SAR: %u/%u\n",
486                    avctx->sample_aspect_ratio.num,
487                    avctx->sample_aspect_ratio.den);
488             avctx->sample_aspect_ratio = (AVRational){ 0, 1 };
489         }
490     }
491
492     /* if the decoder init function was already called previously,
493      * free the already allocated subtitle_header before overwriting it */
494     if (av_codec_is_decoder(codec))
495         av_freep(&avctx->subtitle_header);
496
497     if (avctx->channels > FF_SANE_NB_CHANNELS) {
498         ret = AVERROR(EINVAL);
499         goto free_and_end;
500     }
501
502     avctx->codec = codec;
503     if ((avctx->codec_type == AVMEDIA_TYPE_UNKNOWN || avctx->codec_type == codec->type) &&
504         avctx->codec_id == AV_CODEC_ID_NONE) {
505         avctx->codec_type = codec->type;
506         avctx->codec_id   = codec->id;
507     }
508     if (avctx->codec_id != codec->id || (avctx->codec_type != codec->type
509                                          && avctx->codec_type != AVMEDIA_TYPE_ATTACHMENT)) {
510         av_log(avctx, AV_LOG_ERROR, "codec type or id mismatches\n");
511         ret = AVERROR(EINVAL);
512         goto free_and_end;
513     }
514     avctx->frame_number = 0;
515
516     if ((avctx->codec->capabilities & AV_CODEC_CAP_EXPERIMENTAL) &&
517         avctx->strict_std_compliance > FF_COMPLIANCE_EXPERIMENTAL) {
518         ret = AVERROR_EXPERIMENTAL;
519         goto free_and_end;
520     }
521
522     if (avctx->codec_type == AVMEDIA_TYPE_AUDIO &&
523         (!avctx->time_base.num || !avctx->time_base.den)) {
524         avctx->time_base.num = 1;
525         avctx->time_base.den = avctx->sample_rate;
526     }
527
528     if (HAVE_THREADS) {
529         ret = ff_thread_init(avctx);
530         if (ret < 0) {
531             goto free_and_end;
532         }
533     }
534     if (!HAVE_THREADS && !(codec->capabilities & AV_CODEC_CAP_AUTO_THREADS))
535         avctx->thread_count = 1;
536
537     if (av_codec_is_encoder(avctx->codec)) {
538         int i;
539 #if FF_API_CODED_FRAME
540 FF_DISABLE_DEPRECATION_WARNINGS
541         avctx->coded_frame = av_frame_alloc();
542         if (!avctx->coded_frame) {
543             ret = AVERROR(ENOMEM);
544             goto free_and_end;
545         }
546 FF_ENABLE_DEPRECATION_WARNINGS
547 #endif
548
549         if (avctx->time_base.num <= 0 || avctx->time_base.den <= 0) {
550             av_log(avctx, AV_LOG_ERROR, "The encoder timebase is not set.\n");
551             ret = AVERROR(EINVAL);
552             goto free_and_end;
553         }
554
555         if (avctx->codec->sample_fmts) {
556             for (i = 0; avctx->codec->sample_fmts[i] != AV_SAMPLE_FMT_NONE; i++) {
557                 if (avctx->sample_fmt == avctx->codec->sample_fmts[i])
558                     break;
559                 if (avctx->channels == 1 &&
560                     av_get_planar_sample_fmt(avctx->sample_fmt) ==
561                     av_get_planar_sample_fmt(avctx->codec->sample_fmts[i])) {
562                     avctx->sample_fmt = avctx->codec->sample_fmts[i];
563                     break;
564                 }
565             }
566             if (avctx->codec->sample_fmts[i] == AV_SAMPLE_FMT_NONE) {
567                 av_log(avctx, AV_LOG_ERROR, "Specified sample_fmt is not supported.\n");
568                 ret = AVERROR(EINVAL);
569                 goto free_and_end;
570             }
571         }
572         if (avctx->codec->pix_fmts) {
573             for (i = 0; avctx->codec->pix_fmts[i] != AV_PIX_FMT_NONE; i++)
574                 if (avctx->pix_fmt == avctx->codec->pix_fmts[i])
575                     break;
576             if (avctx->codec->pix_fmts[i] == AV_PIX_FMT_NONE) {
577                 av_log(avctx, AV_LOG_ERROR, "Specified pix_fmt is not supported\n");
578                 ret = AVERROR(EINVAL);
579                 goto free_and_end;
580             }
581             if (avctx->codec->pix_fmts[i] == AV_PIX_FMT_YUVJ420P ||
582                 avctx->codec->pix_fmts[i] == AV_PIX_FMT_YUVJ422P ||
583                 avctx->codec->pix_fmts[i] == AV_PIX_FMT_YUVJ440P ||
584                 avctx->codec->pix_fmts[i] == AV_PIX_FMT_YUVJ444P)
585                 avctx->color_range = AVCOL_RANGE_JPEG;
586         }
587         if (avctx->codec->supported_samplerates) {
588             for (i = 0; avctx->codec->supported_samplerates[i] != 0; i++)
589                 if (avctx->sample_rate == avctx->codec->supported_samplerates[i])
590                     break;
591             if (avctx->codec->supported_samplerates[i] == 0) {
592                 av_log(avctx, AV_LOG_ERROR, "Specified sample_rate is not supported\n");
593                 ret = AVERROR(EINVAL);
594                 goto free_and_end;
595             }
596         }
597         if (avctx->codec->channel_layouts) {
598             if (!avctx->channel_layout) {
599                 av_log(avctx, AV_LOG_WARNING, "channel_layout not specified\n");
600             } else {
601                 for (i = 0; avctx->codec->channel_layouts[i] != 0; i++)
602                     if (avctx->channel_layout == avctx->codec->channel_layouts[i])
603                         break;
604                 if (avctx->codec->channel_layouts[i] == 0) {
605                     av_log(avctx, AV_LOG_ERROR, "Specified channel_layout is not supported\n");
606                     ret = AVERROR(EINVAL);
607                     goto free_and_end;
608                 }
609             }
610         }
611         if (avctx->channel_layout && avctx->channels) {
612             if (av_get_channel_layout_nb_channels(avctx->channel_layout) != avctx->channels) {
613                 av_log(avctx, AV_LOG_ERROR, "channel layout does not match number of channels\n");
614                 ret = AVERROR(EINVAL);
615                 goto free_and_end;
616             }
617         } else if (avctx->channel_layout) {
618             avctx->channels = av_get_channel_layout_nb_channels(avctx->channel_layout);
619         }
620
621         if (!avctx->rc_initial_buffer_occupancy)
622             avctx->rc_initial_buffer_occupancy = avctx->rc_buffer_size * 3 / 4;
623
624         if (avctx->ticks_per_frame &&
625             avctx->ticks_per_frame > INT_MAX / avctx->time_base.num) {
626             av_log(avctx, AV_LOG_ERROR,
627                    "ticks_per_frame %d too large for the timebase %d/%d.",
628                    avctx->ticks_per_frame,
629                    avctx->time_base.num,
630                    avctx->time_base.den);
631             goto free_and_end;
632         }
633
634         if (avctx->hw_frames_ctx) {
635             AVHWFramesContext *frames_ctx = (AVHWFramesContext*)avctx->hw_frames_ctx->data;
636             if (frames_ctx->format != avctx->pix_fmt) {
637                 av_log(avctx, AV_LOG_ERROR,
638                        "Mismatching AVCodecContext.pix_fmt and AVHWFramesContext.format\n");
639                 ret = AVERROR(EINVAL);
640                 goto free_and_end;
641             }
642             if (avctx->sw_pix_fmt != AV_PIX_FMT_NONE &&
643                 avctx->sw_pix_fmt != frames_ctx->sw_format) {
644                 av_log(avctx, AV_LOG_ERROR,
645                        "Mismatching AVCodecContext.sw_pix_fmt (%s) "
646                        "and AVHWFramesContext.sw_format (%s)\n",
647                        av_get_pix_fmt_name(avctx->sw_pix_fmt),
648                        av_get_pix_fmt_name(frames_ctx->sw_format));
649                 ret = AVERROR(EINVAL);
650                 goto free_and_end;
651             }
652             avctx->sw_pix_fmt = frames_ctx->sw_format;
653         }
654     }
655
656     if (avctx->codec->init && !(avctx->active_thread_type & FF_THREAD_FRAME)) {
657         ret = avctx->codec->init(avctx);
658         if (ret < 0) {
659             goto free_and_end;
660         }
661     }
662
663 #if FF_API_AUDIOENC_DELAY
664     if (av_codec_is_encoder(avctx->codec))
665         avctx->delay = avctx->initial_padding;
666 #endif
667
668     if (av_codec_is_decoder(avctx->codec)) {
669         /* validate channel layout from the decoder */
670         if (avctx->channel_layout) {
671             int channels = av_get_channel_layout_nb_channels(avctx->channel_layout);
672             if (!avctx->channels)
673                 avctx->channels = channels;
674             else if (channels != avctx->channels) {
675                 av_log(avctx, AV_LOG_WARNING,
676                        "channel layout does not match number of channels\n");
677                 avctx->channel_layout = 0;
678             }
679         }
680         if (avctx->channels && avctx->channels < 0 ||
681             avctx->channels > FF_SANE_NB_CHANNELS) {
682             ret = AVERROR(EINVAL);
683             goto free_and_end;
684         }
685
686 #if FF_API_AVCTX_TIMEBASE
687         if (avctx->framerate.num > 0 && avctx->framerate.den > 0)
688             avctx->time_base = av_inv_q(avctx->framerate);
689 #endif
690     }
691 end:
692     if (!(codec->caps_internal & FF_CODEC_CAP_INIT_THREADSAFE) && codec->init) {
693         entangled_thread_counter--;
694
695         /* Release any user-supplied mutex. */
696         if (lockmgr_cb) {
697             (*lockmgr_cb)(&codec_mutex, AV_LOCK_RELEASE);
698         }
699     }
700
701     if (options) {
702         av_dict_free(options);
703         *options = tmp;
704     }
705
706     return ret;
707 free_and_end:
708     if (avctx->codec &&
709         (avctx->codec->caps_internal & FF_CODEC_CAP_INIT_CLEANUP))
710         avctx->codec->close(avctx);
711
712     if (avctx->priv_data && avctx->codec && avctx->codec->priv_class)
713         av_opt_free(avctx->priv_data);
714     av_opt_free(avctx);
715
716 #if FF_API_CODED_FRAME
717 FF_DISABLE_DEPRECATION_WARNINGS
718     av_frame_free(&avctx->coded_frame);
719 FF_ENABLE_DEPRECATION_WARNINGS
720 #endif
721
722     av_dict_free(&tmp);
723     av_freep(&avctx->priv_data);
724     if (avctx->internal) {
725         av_frame_free(&avctx->internal->to_free);
726         av_frame_free(&avctx->internal->compat_decode_frame);
727         av_frame_free(&avctx->internal->buffer_frame);
728         av_packet_free(&avctx->internal->buffer_pkt);
729         av_packet_free(&avctx->internal->last_pkt_props);
730
731         av_packet_free(&avctx->internal->ds.in_pkt);
732
733         av_freep(&avctx->internal->pool);
734     }
735     av_freep(&avctx->internal);
736     avctx->codec = NULL;
737     goto end;
738 }
739
740 void avsubtitle_free(AVSubtitle *sub)
741 {
742     int i;
743
744     for (i = 0; i < sub->num_rects; i++) {
745         av_freep(&sub->rects[i]->data[0]);
746         av_freep(&sub->rects[i]->data[1]);
747         av_freep(&sub->rects[i]->data[2]);
748         av_freep(&sub->rects[i]->data[3]);
749         av_freep(&sub->rects[i]->text);
750         av_freep(&sub->rects[i]->ass);
751         av_freep(&sub->rects[i]);
752     }
753
754     av_freep(&sub->rects);
755
756     memset(sub, 0, sizeof(AVSubtitle));
757 }
758
759 av_cold int avcodec_close(AVCodecContext *avctx)
760 {
761     int i;
762
763     if (avcodec_is_open(avctx)) {
764         FramePool *pool = avctx->internal->pool;
765
766         if (HAVE_THREADS && avctx->internal->thread_ctx)
767             ff_thread_free(avctx);
768         if (avctx->codec && avctx->codec->close)
769             avctx->codec->close(avctx);
770         av_frame_free(&avctx->internal->to_free);
771         av_frame_free(&avctx->internal->compat_decode_frame);
772         av_frame_free(&avctx->internal->buffer_frame);
773         av_packet_free(&avctx->internal->buffer_pkt);
774         av_packet_free(&avctx->internal->last_pkt_props);
775
776         av_packet_free(&avctx->internal->ds.in_pkt);
777
778         for (i = 0; i < FF_ARRAY_ELEMS(pool->pools); i++)
779             av_buffer_pool_uninit(&pool->pools[i]);
780         av_freep(&avctx->internal->pool);
781
782         if (avctx->hwaccel && avctx->hwaccel->uninit)
783             avctx->hwaccel->uninit(avctx);
784         av_freep(&avctx->internal->hwaccel_priv_data);
785
786         ff_decode_bsfs_uninit(avctx);
787
788         av_freep(&avctx->internal);
789     }
790
791     for (i = 0; i < avctx->nb_coded_side_data; i++)
792         av_freep(&avctx->coded_side_data[i].data);
793     av_freep(&avctx->coded_side_data);
794     avctx->nb_coded_side_data = 0;
795
796     av_buffer_unref(&avctx->hw_frames_ctx);
797     av_buffer_unref(&avctx->hw_device_ctx);
798
799     if (avctx->priv_data && avctx->codec && avctx->codec->priv_class)
800         av_opt_free(avctx->priv_data);
801     av_opt_free(avctx);
802     av_freep(&avctx->priv_data);
803     if (av_codec_is_encoder(avctx->codec)) {
804         av_freep(&avctx->extradata);
805 #if FF_API_CODED_FRAME
806 FF_DISABLE_DEPRECATION_WARNINGS
807         av_frame_free(&avctx->coded_frame);
808 FF_ENABLE_DEPRECATION_WARNINGS
809 #endif
810     }
811     avctx->codec = NULL;
812     avctx->active_thread_type = 0;
813
814     return 0;
815 }
816
817 static AVCodec *find_encdec(enum AVCodecID id, int encoder)
818 {
819     AVCodec *p, *experimental = NULL;
820     p = first_avcodec;
821     while (p) {
822         if ((encoder ? av_codec_is_encoder(p) : av_codec_is_decoder(p)) &&
823             p->id == id) {
824             if (p->capabilities & AV_CODEC_CAP_EXPERIMENTAL && !experimental) {
825                 experimental = p;
826             } else
827                 return p;
828         }
829         p = p->next;
830     }
831     return experimental;
832 }
833
834 AVCodec *avcodec_find_encoder(enum AVCodecID id)
835 {
836     return find_encdec(id, 1);
837 }
838
839 AVCodec *avcodec_find_encoder_by_name(const char *name)
840 {
841     AVCodec *p;
842     if (!name)
843         return NULL;
844     p = first_avcodec;
845     while (p) {
846         if (av_codec_is_encoder(p) && strcmp(name, p->name) == 0)
847             return p;
848         p = p->next;
849     }
850     return NULL;
851 }
852
853 AVCodec *avcodec_find_decoder(enum AVCodecID id)
854 {
855     return find_encdec(id, 0);
856 }
857
858 AVCodec *avcodec_find_decoder_by_name(const char *name)
859 {
860     AVCodec *p;
861     if (!name)
862         return NULL;
863     p = first_avcodec;
864     while (p) {
865         if (av_codec_is_decoder(p) && strcmp(name, p->name) == 0)
866             return p;
867         p = p->next;
868     }
869     return NULL;
870 }
871
872 static int get_bit_rate(AVCodecContext *ctx)
873 {
874     int bit_rate;
875     int bits_per_sample;
876
877     switch (ctx->codec_type) {
878     case AVMEDIA_TYPE_VIDEO:
879     case AVMEDIA_TYPE_DATA:
880     case AVMEDIA_TYPE_SUBTITLE:
881     case AVMEDIA_TYPE_ATTACHMENT:
882         bit_rate = ctx->bit_rate;
883         break;
884     case AVMEDIA_TYPE_AUDIO:
885         bits_per_sample = av_get_bits_per_sample(ctx->codec_id);
886         bit_rate = bits_per_sample ? ctx->sample_rate * ctx->channels * bits_per_sample : ctx->bit_rate;
887         break;
888     default:
889         bit_rate = 0;
890         break;
891     }
892     return bit_rate;
893 }
894
895 size_t av_get_codec_tag_string(char *buf, size_t buf_size, unsigned int codec_tag)
896 {
897     int i, len, ret = 0;
898
899 #define TAG_PRINT(x)                                              \
900     (((x) >= '0' && (x) <= '9') ||                                \
901      ((x) >= 'a' && (x) <= 'z') || ((x) >= 'A' && (x) <= 'Z') ||  \
902      ((x) == '.' || (x) == ' '))
903
904     for (i = 0; i < 4; i++) {
905         len = snprintf(buf, buf_size,
906                        TAG_PRINT(codec_tag & 0xFF) ? "%c" : "[%d]", codec_tag & 0xFF);
907         buf        += len;
908         buf_size    = buf_size > len ? buf_size - len : 0;
909         ret        += len;
910         codec_tag >>= 8;
911     }
912     return ret;
913 }
914
915 void avcodec_string(char *buf, int buf_size, AVCodecContext *enc, int encode)
916 {
917     const char *codec_name;
918     const char *profile = NULL;
919     char buf1[32];
920     int bitrate;
921     int new_line = 0;
922     AVRational display_aspect_ratio;
923     const AVCodecDescriptor *desc = avcodec_descriptor_get(enc->codec_id);
924
925     if (desc) {
926         codec_name = desc->name;
927         profile = avcodec_profile_name(enc->codec_id, enc->profile);
928     } else if (enc->codec_id == AV_CODEC_ID_MPEG2TS) {
929         /* fake mpeg2 transport stream codec (currently not
930          * registered) */
931         codec_name = "mpeg2ts";
932     } else {
933         /* output avi tags */
934         char tag_buf[32];
935         av_get_codec_tag_string(tag_buf, sizeof(tag_buf), enc->codec_tag);
936         snprintf(buf1, sizeof(buf1), "%s / 0x%04X", tag_buf, enc->codec_tag);
937         codec_name = buf1;
938     }
939
940     switch (enc->codec_type) {
941     case AVMEDIA_TYPE_VIDEO:
942         snprintf(buf, buf_size,
943                  "Video: %s%s",
944                  codec_name, enc->mb_decision ? " (hq)" : "");
945         if (profile)
946             snprintf(buf + strlen(buf), buf_size - strlen(buf),
947                      " (%s)", profile);
948         if (enc->codec_tag) {
949             char tag_buf[32];
950             av_get_codec_tag_string(tag_buf, sizeof(tag_buf), enc->codec_tag);
951             snprintf(buf + strlen(buf), buf_size - strlen(buf),
952                      " [%s / 0x%04X]", tag_buf, enc->codec_tag);
953         }
954
955         av_strlcat(buf, "\n      ", buf_size);
956         snprintf(buf + strlen(buf), buf_size - strlen(buf),
957                  "%s", enc->pix_fmt == AV_PIX_FMT_NONE ? "none" :
958                      av_get_pix_fmt_name(enc->pix_fmt));
959
960         if (enc->color_range != AVCOL_RANGE_UNSPECIFIED)
961             snprintf(buf + strlen(buf), buf_size - strlen(buf), ", %s",
962                      av_color_range_name(enc->color_range));
963         if (enc->colorspace != AVCOL_SPC_UNSPECIFIED ||
964             enc->color_primaries != AVCOL_PRI_UNSPECIFIED ||
965             enc->color_trc != AVCOL_TRC_UNSPECIFIED) {
966             new_line = 1;
967             snprintf(buf + strlen(buf), buf_size - strlen(buf), ", %s/%s/%s",
968                      av_color_space_name(enc->colorspace),
969                      av_color_primaries_name(enc->color_primaries),
970                      av_color_transfer_name(enc->color_trc));
971         }
972         if (av_log_get_level() >= AV_LOG_DEBUG &&
973             enc->chroma_sample_location != AVCHROMA_LOC_UNSPECIFIED)
974             snprintf(buf + strlen(buf), buf_size - strlen(buf), ", %s",
975                      av_chroma_location_name(enc->chroma_sample_location));
976
977         if (enc->width) {
978             av_strlcat(buf, new_line ? "\n      " : ", ", buf_size);
979
980             snprintf(buf + strlen(buf), buf_size - strlen(buf),
981                      "%dx%d",
982                      enc->width, enc->height);
983
984             if (av_log_get_level() >= AV_LOG_VERBOSE &&
985                 (enc->width != enc->coded_width ||
986                  enc->height != enc->coded_height))
987                 snprintf(buf + strlen(buf), buf_size - strlen(buf),
988                          " (%dx%d)", enc->coded_width, enc->coded_height);
989
990             if (enc->sample_aspect_ratio.num) {
991                 av_reduce(&display_aspect_ratio.num, &display_aspect_ratio.den,
992                           enc->width * enc->sample_aspect_ratio.num,
993                           enc->height * enc->sample_aspect_ratio.den,
994                           1024 * 1024);
995                 snprintf(buf + strlen(buf), buf_size - strlen(buf),
996                          " [PAR %d:%d DAR %d:%d]",
997                          enc->sample_aspect_ratio.num, enc->sample_aspect_ratio.den,
998                          display_aspect_ratio.num, display_aspect_ratio.den);
999             }
1000             if (av_log_get_level() >= AV_LOG_DEBUG) {
1001                 int g = av_gcd(enc->time_base.num, enc->time_base.den);
1002                 snprintf(buf + strlen(buf), buf_size - strlen(buf),
1003                          ", %d/%d",
1004                          enc->time_base.num / g, enc->time_base.den / g);
1005             }
1006         }
1007         if (encode) {
1008             snprintf(buf + strlen(buf), buf_size - strlen(buf),
1009                      ", q=%d-%d", enc->qmin, enc->qmax);
1010         }
1011         break;
1012     case AVMEDIA_TYPE_AUDIO:
1013         snprintf(buf, buf_size,
1014                  "Audio: %s",
1015                  codec_name);
1016         if (profile)
1017             snprintf(buf + strlen(buf), buf_size - strlen(buf),
1018                      " (%s)", profile);
1019         if (enc->codec_tag) {
1020             char tag_buf[32];
1021             av_get_codec_tag_string(tag_buf, sizeof(tag_buf), enc->codec_tag);
1022             snprintf(buf + strlen(buf), buf_size - strlen(buf),
1023                      " [%s / 0x%04X]", tag_buf, enc->codec_tag);
1024         }
1025
1026         av_strlcat(buf, "\n      ", buf_size);
1027         if (enc->sample_rate) {
1028             snprintf(buf + strlen(buf), buf_size - strlen(buf),
1029                      "%d Hz, ", enc->sample_rate);
1030         }
1031         av_get_channel_layout_string(buf + strlen(buf), buf_size - strlen(buf), enc->channels, enc->channel_layout);
1032         if (enc->sample_fmt != AV_SAMPLE_FMT_NONE) {
1033             snprintf(buf + strlen(buf), buf_size - strlen(buf),
1034                      ", %s", av_get_sample_fmt_name(enc->sample_fmt));
1035         }
1036         break;
1037     case AVMEDIA_TYPE_DATA:
1038         snprintf(buf, buf_size, "Data: %s", codec_name);
1039         break;
1040     case AVMEDIA_TYPE_SUBTITLE:
1041         snprintf(buf, buf_size, "Subtitle: %s", codec_name);
1042         break;
1043     case AVMEDIA_TYPE_ATTACHMENT:
1044         snprintf(buf, buf_size, "Attachment: %s", codec_name);
1045         break;
1046     default:
1047         snprintf(buf, buf_size, "Invalid Codec type %d", enc->codec_type);
1048         return;
1049     }
1050     if (encode) {
1051         if (enc->flags & AV_CODEC_FLAG_PASS1)
1052             snprintf(buf + strlen(buf), buf_size - strlen(buf),
1053                      ", pass 1");
1054         if (enc->flags & AV_CODEC_FLAG_PASS2)
1055             snprintf(buf + strlen(buf), buf_size - strlen(buf),
1056                      ", pass 2");
1057     }
1058     bitrate = get_bit_rate(enc);
1059     if (bitrate != 0) {
1060         snprintf(buf + strlen(buf), buf_size - strlen(buf),
1061                  ", %d kb/s", bitrate / 1000);
1062     }
1063 }
1064
1065 const char *av_get_profile_name(const AVCodec *codec, int profile)
1066 {
1067     const AVProfile *p;
1068     if (profile == FF_PROFILE_UNKNOWN || !codec->profiles)
1069         return NULL;
1070
1071     for (p = codec->profiles; p->profile != FF_PROFILE_UNKNOWN; p++)
1072         if (p->profile == profile)
1073             return p->name;
1074
1075     return NULL;
1076 }
1077
1078 const char *avcodec_profile_name(enum AVCodecID codec_id, int profile)
1079 {
1080     const AVCodecDescriptor *desc = avcodec_descriptor_get(codec_id);
1081     const AVProfile *p;
1082
1083     if (profile == FF_PROFILE_UNKNOWN || !desc || !desc->profiles)
1084         return NULL;
1085
1086     for (p = desc->profiles; p->profile != FF_PROFILE_UNKNOWN; p++)
1087         if (p->profile == profile)
1088             return p->name;
1089
1090     return NULL;
1091 }
1092
1093 unsigned avcodec_version(void)
1094 {
1095     return LIBAVCODEC_VERSION_INT;
1096 }
1097
1098 const char *avcodec_configuration(void)
1099 {
1100     return LIBAV_CONFIGURATION;
1101 }
1102
1103 const char *avcodec_license(void)
1104 {
1105 #define LICENSE_PREFIX "libavcodec license: "
1106     return LICENSE_PREFIX LIBAV_LICENSE + sizeof(LICENSE_PREFIX) - 1;
1107 }
1108
1109 int av_get_exact_bits_per_sample(enum AVCodecID codec_id)
1110 {
1111     switch (codec_id) {
1112     case AV_CODEC_ID_ADPCM_CT:
1113     case AV_CODEC_ID_ADPCM_IMA_APC:
1114     case AV_CODEC_ID_ADPCM_IMA_EA_SEAD:
1115     case AV_CODEC_ID_ADPCM_IMA_WS:
1116     case AV_CODEC_ID_ADPCM_G722:
1117     case AV_CODEC_ID_ADPCM_YAMAHA:
1118         return 4;
1119     case AV_CODEC_ID_PCM_ALAW:
1120     case AV_CODEC_ID_PCM_MULAW:
1121     case AV_CODEC_ID_PCM_S8:
1122     case AV_CODEC_ID_PCM_U8:
1123     case AV_CODEC_ID_PCM_ZORK:
1124         return 8;
1125     case AV_CODEC_ID_PCM_S16BE:
1126     case AV_CODEC_ID_PCM_S16BE_PLANAR:
1127     case AV_CODEC_ID_PCM_S16LE:
1128     case AV_CODEC_ID_PCM_S16LE_PLANAR:
1129     case AV_CODEC_ID_PCM_U16BE:
1130     case AV_CODEC_ID_PCM_U16LE:
1131         return 16;
1132     case AV_CODEC_ID_PCM_S24DAUD:
1133     case AV_CODEC_ID_PCM_S24BE:
1134     case AV_CODEC_ID_PCM_S24LE:
1135     case AV_CODEC_ID_PCM_S24LE_PLANAR:
1136     case AV_CODEC_ID_PCM_U24BE:
1137     case AV_CODEC_ID_PCM_U24LE:
1138         return 24;
1139     case AV_CODEC_ID_PCM_S32BE:
1140     case AV_CODEC_ID_PCM_S32LE:
1141     case AV_CODEC_ID_PCM_S32LE_PLANAR:
1142     case AV_CODEC_ID_PCM_U32BE:
1143     case AV_CODEC_ID_PCM_U32LE:
1144     case AV_CODEC_ID_PCM_F32BE:
1145     case AV_CODEC_ID_PCM_F32LE:
1146         return 32;
1147     case AV_CODEC_ID_PCM_F64BE:
1148     case AV_CODEC_ID_PCM_F64LE:
1149         return 64;
1150     default:
1151         return 0;
1152     }
1153 }
1154
1155 int av_get_bits_per_sample(enum AVCodecID codec_id)
1156 {
1157     switch (codec_id) {
1158     case AV_CODEC_ID_ADPCM_SBPRO_2:
1159         return 2;
1160     case AV_CODEC_ID_ADPCM_SBPRO_3:
1161         return 3;
1162     case AV_CODEC_ID_ADPCM_SBPRO_4:
1163     case AV_CODEC_ID_ADPCM_IMA_WAV:
1164     case AV_CODEC_ID_ADPCM_IMA_QT:
1165     case AV_CODEC_ID_ADPCM_SWF:
1166     case AV_CODEC_ID_ADPCM_MS:
1167         return 4;
1168     default:
1169         return av_get_exact_bits_per_sample(codec_id);
1170     }
1171 }
1172
1173 static int get_audio_frame_duration(enum AVCodecID id, int sr, int ch, int ba,
1174                                     uint32_t tag, int bits_per_coded_sample, int frame_bytes)
1175 {
1176     int bps = av_get_exact_bits_per_sample(id);
1177
1178     /* codecs with an exact constant bits per sample */
1179     if (bps > 0 && ch > 0 && frame_bytes > 0)
1180         return (frame_bytes * 8) / (bps * ch);
1181     bps = bits_per_coded_sample;
1182
1183     /* codecs with a fixed packet duration */
1184     switch (id) {
1185     case AV_CODEC_ID_ADPCM_ADX:    return   32;
1186     case AV_CODEC_ID_ADPCM_IMA_QT: return   64;
1187     case AV_CODEC_ID_ADPCM_EA_XAS: return  128;
1188     case AV_CODEC_ID_AMR_NB:
1189     case AV_CODEC_ID_GSM:
1190     case AV_CODEC_ID_QCELP:
1191     case AV_CODEC_ID_RA_144:
1192     case AV_CODEC_ID_RA_288:       return  160;
1193     case AV_CODEC_ID_IMC:          return  256;
1194     case AV_CODEC_ID_AMR_WB:
1195     case AV_CODEC_ID_GSM_MS:       return  320;
1196     case AV_CODEC_ID_MP1:          return  384;
1197     case AV_CODEC_ID_ATRAC1:       return  512;
1198     case AV_CODEC_ID_ATRAC3:       return 1024;
1199     case AV_CODEC_ID_MP2:
1200     case AV_CODEC_ID_MUSEPACK7:    return 1152;
1201     case AV_CODEC_ID_AC3:          return 1536;
1202     }
1203
1204     if (sr > 0) {
1205         /* calc from sample rate */
1206         if (id == AV_CODEC_ID_TTA)
1207             return 256 * sr / 245;
1208
1209         if (ch > 0) {
1210             /* calc from sample rate and channels */
1211             if (id == AV_CODEC_ID_BINKAUDIO_DCT)
1212                 return (480 << (sr / 22050)) / ch;
1213         }
1214
1215         if (id == AV_CODEC_ID_MP3)
1216             return sr <= 24000 ? 576 : 1152;
1217     }
1218
1219     if (ba > 0) {
1220         /* calc from block_align */
1221         if (id == AV_CODEC_ID_SIPR) {
1222             switch (ba) {
1223             case 20: return 160;
1224             case 19: return 144;
1225             case 29: return 288;
1226             case 37: return 480;
1227             }
1228         } else if (id == AV_CODEC_ID_ILBC) {
1229             switch (ba) {
1230             case 38: return 160;
1231             case 50: return 240;
1232             }
1233         }
1234     }
1235
1236     if (frame_bytes > 0) {
1237         /* calc from frame_bytes only */
1238         if (id == AV_CODEC_ID_TRUESPEECH)
1239             return 240 * (frame_bytes / 32);
1240         if (id == AV_CODEC_ID_NELLYMOSER)
1241             return 256 * (frame_bytes / 64);
1242
1243         if (bps > 0) {
1244             /* calc from frame_bytes and bits_per_coded_sample */
1245             if (id == AV_CODEC_ID_ADPCM_G726)
1246                 return frame_bytes * 8 / bps;
1247         }
1248
1249         if (ch > 0) {
1250             /* calc from frame_bytes and channels */
1251             switch (id) {
1252             case AV_CODEC_ID_ADPCM_4XM:
1253             case AV_CODEC_ID_ADPCM_IMA_ISS:
1254                 return (frame_bytes - 4 * ch) * 2 / ch;
1255             case AV_CODEC_ID_ADPCM_IMA_SMJPEG:
1256                 return (frame_bytes - 4) * 2 / ch;
1257             case AV_CODEC_ID_ADPCM_IMA_AMV:
1258                 return (frame_bytes - 8) * 2 / ch;
1259             case AV_CODEC_ID_ADPCM_XA:
1260                 return (frame_bytes / 128) * 224 / ch;
1261             case AV_CODEC_ID_INTERPLAY_DPCM:
1262                 return (frame_bytes - 6 - ch) / ch;
1263             case AV_CODEC_ID_ROQ_DPCM:
1264                 return (frame_bytes - 8) / ch;
1265             case AV_CODEC_ID_XAN_DPCM:
1266                 return (frame_bytes - 2 * ch) / ch;
1267             case AV_CODEC_ID_MACE3:
1268                 return 3 * frame_bytes / ch;
1269             case AV_CODEC_ID_MACE6:
1270                 return 6 * frame_bytes / ch;
1271             case AV_CODEC_ID_PCM_LXF:
1272                 return 2 * (frame_bytes / (5 * ch));
1273             }
1274
1275             if (tag) {
1276                 /* calc from frame_bytes, channels, and codec_tag */
1277                 if (id == AV_CODEC_ID_SOL_DPCM) {
1278                     if (tag == 3)
1279                         return frame_bytes / ch;
1280                     else
1281                         return frame_bytes * 2 / ch;
1282                 }
1283             }
1284
1285             if (ba > 0) {
1286                 /* calc from frame_bytes, channels, and block_align */
1287                 int blocks = frame_bytes / ba;
1288                 switch (id) {
1289                 case AV_CODEC_ID_ADPCM_IMA_WAV:
1290                     return blocks * (1 + (ba - 4 * ch) / (4 * ch) * 8);
1291                 case AV_CODEC_ID_ADPCM_IMA_DK3:
1292                     return blocks * (((ba - 16) * 2 / 3 * 4) / ch);
1293                 case AV_CODEC_ID_ADPCM_IMA_DK4:
1294                     return blocks * (1 + (ba - 4 * ch) * 2 / ch);
1295                 case AV_CODEC_ID_ADPCM_MS:
1296                     return blocks * (2 + (ba - 7 * ch) * 2 / ch);
1297                 }
1298             }
1299
1300             if (bps > 0) {
1301                 /* calc from frame_bytes, channels, and bits_per_coded_sample */
1302                 switch (id) {
1303                 case AV_CODEC_ID_PCM_DVD:
1304                     return 2 * (frame_bytes / ((bps * 2 / 8) * ch));
1305                 case AV_CODEC_ID_PCM_BLURAY:
1306                     return frame_bytes / ((FFALIGN(ch, 2) * bps) / 8);
1307                 case AV_CODEC_ID_S302M:
1308                     return 2 * (frame_bytes / ((bps + 4) / 4)) / ch;
1309                 }
1310             }
1311         }
1312     }
1313
1314     return 0;
1315 }
1316
1317 int av_get_audio_frame_duration(AVCodecContext *avctx, int frame_bytes)
1318 {
1319     return get_audio_frame_duration(avctx->codec_id, avctx->sample_rate,
1320                                     avctx->channels, avctx->block_align,
1321                                     avctx->codec_tag, avctx->bits_per_coded_sample,
1322                                     frame_bytes);
1323 }
1324
1325 int av_get_audio_frame_duration2(AVCodecParameters *par, int frame_bytes)
1326 {
1327     return get_audio_frame_duration(par->codec_id, par->sample_rate,
1328                                     par->channels, par->block_align,
1329                                     par->codec_tag, par->bits_per_coded_sample,
1330                                     frame_bytes);
1331 }
1332
1333 #if !HAVE_THREADS
1334 int ff_thread_init(AVCodecContext *s)
1335 {
1336     return -1;
1337 }
1338
1339 #endif
1340
1341 unsigned int av_xiphlacing(unsigned char *s, unsigned int v)
1342 {
1343     unsigned int n = 0;
1344
1345     while (v >= 0xff) {
1346         *s++ = 0xff;
1347         v -= 0xff;
1348         n++;
1349     }
1350     *s = v;
1351     n++;
1352     return n;
1353 }
1354
1355 int ff_match_2uint16(const uint16_t(*tab)[2], int size, int a, int b)
1356 {
1357     int i;
1358     for (i = 0; i < size && !(tab[i][0] == a && tab[i][1] == b); i++) ;
1359     return i;
1360 }
1361
1362 static AVHWAccel *first_hwaccel = NULL;
1363
1364 void av_register_hwaccel(AVHWAccel *hwaccel)
1365 {
1366     AVHWAccel **p = &first_hwaccel;
1367     while (*p)
1368         p = &(*p)->next;
1369     *p = hwaccel;
1370     hwaccel->next = NULL;
1371 }
1372
1373 AVHWAccel *av_hwaccel_next(const AVHWAccel *hwaccel)
1374 {
1375     return hwaccel ? hwaccel->next : first_hwaccel;
1376 }
1377
1378 int av_lockmgr_register(int (*cb)(void **mutex, enum AVLockOp op))
1379 {
1380     if (lockmgr_cb) {
1381         // There is no good way to rollback a failure to destroy the
1382         // mutex, so we ignore failures.
1383         lockmgr_cb(&codec_mutex,    AV_LOCK_DESTROY);
1384         lockmgr_cb(&avformat_mutex, AV_LOCK_DESTROY);
1385         lockmgr_cb     = NULL;
1386         codec_mutex    = NULL;
1387         avformat_mutex = NULL;
1388     }
1389
1390     if (cb) {
1391         void *new_codec_mutex    = NULL;
1392         void *new_avformat_mutex = NULL;
1393         int err;
1394         if (err = cb(&new_codec_mutex, AV_LOCK_CREATE)) {
1395             return err > 0 ? AVERROR_UNKNOWN : err;
1396         }
1397         if (err = cb(&new_avformat_mutex, AV_LOCK_CREATE)) {
1398             // Ignore failures to destroy the newly created mutex.
1399             cb(&new_codec_mutex, AV_LOCK_DESTROY);
1400             return err > 0 ? AVERROR_UNKNOWN : err;
1401         }
1402         lockmgr_cb     = cb;
1403         codec_mutex    = new_codec_mutex;
1404         avformat_mutex = new_avformat_mutex;
1405     }
1406
1407     return 0;
1408 }
1409
1410 int avpriv_lock_avformat(void)
1411 {
1412     if (lockmgr_cb) {
1413         if ((*lockmgr_cb)(&avformat_mutex, AV_LOCK_OBTAIN))
1414             return -1;
1415     }
1416     return 0;
1417 }
1418
1419 int avpriv_unlock_avformat(void)
1420 {
1421     if (lockmgr_cb) {
1422         if ((*lockmgr_cb)(&avformat_mutex, AV_LOCK_RELEASE))
1423             return -1;
1424     }
1425     return 0;
1426 }
1427
1428 unsigned int avpriv_toupper4(unsigned int x)
1429 {
1430     return av_toupper(x & 0xFF) +
1431           (av_toupper((x >>  8) & 0xFF) << 8)  +
1432           (av_toupper((x >> 16) & 0xFF) << 16) +
1433           (av_toupper((x >> 24) & 0xFF) << 24);
1434 }
1435
1436 int ff_thread_ref_frame(ThreadFrame *dst, ThreadFrame *src)
1437 {
1438     int ret;
1439
1440     dst->owner = src->owner;
1441
1442     ret = av_frame_ref(dst->f, src->f);
1443     if (ret < 0)
1444         return ret;
1445
1446     if (src->progress &&
1447         !(dst->progress = av_buffer_ref(src->progress))) {
1448         ff_thread_release_buffer(dst->owner, dst);
1449         return AVERROR(ENOMEM);
1450     }
1451
1452     return 0;
1453 }
1454
1455 #if !HAVE_THREADS
1456
1457 int ff_thread_get_buffer(AVCodecContext *avctx, ThreadFrame *f, int flags)
1458 {
1459     f->owner = avctx;
1460     return ff_get_buffer(avctx, f->f, flags);
1461 }
1462
1463 void ff_thread_release_buffer(AVCodecContext *avctx, ThreadFrame *f)
1464 {
1465     if (f->f)
1466         av_frame_unref(f->f);
1467 }
1468
1469 void ff_thread_finish_setup(AVCodecContext *avctx)
1470 {
1471 }
1472
1473 void ff_thread_report_progress(ThreadFrame *f, int progress, int field)
1474 {
1475 }
1476
1477 void ff_thread_await_progress(ThreadFrame *f, int progress, int field)
1478 {
1479 }
1480
1481 #endif
1482
1483 int avcodec_is_open(AVCodecContext *s)
1484 {
1485     return !!s->internal;
1486 }
1487
1488 const uint8_t *avpriv_find_start_code(const uint8_t *restrict p,
1489                                       const uint8_t *end,
1490                                       uint32_t * restrict state)
1491 {
1492     int i;
1493
1494     assert(p <= end);
1495     if (p >= end)
1496         return end;
1497
1498     for (i = 0; i < 3; i++) {
1499         uint32_t tmp = *state << 8;
1500         *state = tmp + *(p++);
1501         if (tmp == 0x100 || p == end)
1502             return p;
1503     }
1504
1505     while (p < end) {
1506         if      (p[-1] > 1      ) p += 3;
1507         else if (p[-2]          ) p += 2;
1508         else if (p[-3]|(p[-1]-1)) p++;
1509         else {
1510             p++;
1511             break;
1512         }
1513     }
1514
1515     p = FFMIN(p, end) - 4;
1516     *state = AV_RB32(p);
1517
1518     return p + 4;
1519 }
1520
1521 AVCPBProperties *av_cpb_properties_alloc(size_t *size)
1522 {
1523     AVCPBProperties *props = av_mallocz(sizeof(AVCPBProperties));
1524     if (!props)
1525         return NULL;
1526
1527     if (size)
1528         *size = sizeof(*props);
1529
1530     props->vbv_delay = UINT64_MAX;
1531
1532     return props;
1533 }
1534
1535 AVCPBProperties *ff_add_cpb_side_data(AVCodecContext *avctx)
1536 {
1537     AVPacketSideData *tmp;
1538     AVCPBProperties  *props;
1539     size_t size;
1540
1541     props = av_cpb_properties_alloc(&size);
1542     if (!props)
1543         return NULL;
1544
1545     tmp = av_realloc_array(avctx->coded_side_data, avctx->nb_coded_side_data + 1, sizeof(*tmp));
1546     if (!tmp) {
1547         av_freep(&props);
1548         return NULL;
1549     }
1550
1551     avctx->coded_side_data = tmp;
1552     avctx->nb_coded_side_data++;
1553
1554     avctx->coded_side_data[avctx->nb_coded_side_data - 1].type = AV_PKT_DATA_CPB_PROPERTIES;
1555     avctx->coded_side_data[avctx->nb_coded_side_data - 1].data = (uint8_t*)props;
1556     avctx->coded_side_data[avctx->nb_coded_side_data - 1].size = size;
1557
1558     return props;
1559 }
1560
1561 static void codec_parameters_reset(AVCodecParameters *par)
1562 {
1563     av_freep(&par->extradata);
1564
1565     memset(par, 0, sizeof(*par));
1566
1567     par->codec_type          = AVMEDIA_TYPE_UNKNOWN;
1568     par->codec_id            = AV_CODEC_ID_NONE;
1569     par->format              = -1;
1570     par->field_order         = AV_FIELD_UNKNOWN;
1571     par->color_range         = AVCOL_RANGE_UNSPECIFIED;
1572     par->color_primaries     = AVCOL_PRI_UNSPECIFIED;
1573     par->color_trc           = AVCOL_TRC_UNSPECIFIED;
1574     par->color_space         = AVCOL_SPC_UNSPECIFIED;
1575     par->chroma_location     = AVCHROMA_LOC_UNSPECIFIED;
1576     par->sample_aspect_ratio = (AVRational){ 0, 1 };
1577 }
1578
1579 AVCodecParameters *avcodec_parameters_alloc(void)
1580 {
1581     AVCodecParameters *par = av_mallocz(sizeof(*par));
1582
1583     if (!par)
1584         return NULL;
1585     codec_parameters_reset(par);
1586     return par;
1587 }
1588
1589 void avcodec_parameters_free(AVCodecParameters **ppar)
1590 {
1591     AVCodecParameters *par = *ppar;
1592
1593     if (!par)
1594         return;
1595     codec_parameters_reset(par);
1596
1597     av_freep(ppar);
1598 }
1599
1600 int avcodec_parameters_copy(AVCodecParameters *dst, const AVCodecParameters *src)
1601 {
1602     codec_parameters_reset(dst);
1603     memcpy(dst, src, sizeof(*dst));
1604
1605     dst->extradata      = NULL;
1606     dst->extradata_size = 0;
1607     if (src->extradata) {
1608         dst->extradata = av_mallocz(src->extradata_size + AV_INPUT_BUFFER_PADDING_SIZE);
1609         if (!dst->extradata)
1610             return AVERROR(ENOMEM);
1611         memcpy(dst->extradata, src->extradata, src->extradata_size);
1612         dst->extradata_size = src->extradata_size;
1613     }
1614
1615     return 0;
1616 }
1617
1618 int avcodec_parameters_from_context(AVCodecParameters *par,
1619                                     const AVCodecContext *codec)
1620 {
1621     codec_parameters_reset(par);
1622
1623     par->codec_type = codec->codec_type;
1624     par->codec_id   = codec->codec_id;
1625     par->codec_tag  = codec->codec_tag;
1626
1627     par->bit_rate              = codec->bit_rate;
1628     par->bits_per_coded_sample = codec->bits_per_coded_sample;
1629     par->profile               = codec->profile;
1630     par->level                 = codec->level;
1631
1632     switch (par->codec_type) {
1633     case AVMEDIA_TYPE_VIDEO:
1634         par->format              = codec->pix_fmt;
1635         par->width               = codec->width;
1636         par->height              = codec->height;
1637         par->field_order         = codec->field_order;
1638         par->color_range         = codec->color_range;
1639         par->color_primaries     = codec->color_primaries;
1640         par->color_trc           = codec->color_trc;
1641         par->color_space         = codec->colorspace;
1642         par->chroma_location     = codec->chroma_sample_location;
1643         par->sample_aspect_ratio = codec->sample_aspect_ratio;
1644         break;
1645     case AVMEDIA_TYPE_AUDIO:
1646         par->format          = codec->sample_fmt;
1647         par->channel_layout  = codec->channel_layout;
1648         par->channels        = codec->channels;
1649         par->sample_rate     = codec->sample_rate;
1650         par->block_align     = codec->block_align;
1651         par->initial_padding = codec->initial_padding;
1652         break;
1653     }
1654
1655     if (codec->extradata) {
1656         par->extradata = av_mallocz(codec->extradata_size + AV_INPUT_BUFFER_PADDING_SIZE);
1657         if (!par->extradata)
1658             return AVERROR(ENOMEM);
1659         memcpy(par->extradata, codec->extradata, codec->extradata_size);
1660         par->extradata_size = codec->extradata_size;
1661     }
1662
1663     return 0;
1664 }
1665
1666 int avcodec_parameters_to_context(AVCodecContext *codec,
1667                                   const AVCodecParameters *par)
1668 {
1669     codec->codec_type = par->codec_type;
1670     codec->codec_id   = par->codec_id;
1671     codec->codec_tag  = par->codec_tag;
1672
1673     codec->bit_rate              = par->bit_rate;
1674     codec->bits_per_coded_sample = par->bits_per_coded_sample;
1675     codec->profile               = par->profile;
1676     codec->level                 = par->level;
1677
1678     switch (par->codec_type) {
1679     case AVMEDIA_TYPE_VIDEO:
1680         codec->pix_fmt                = par->format;
1681         codec->width                  = par->width;
1682         codec->height                 = par->height;
1683         codec->field_order            = par->field_order;
1684         codec->color_range            = par->color_range;
1685         codec->color_primaries        = par->color_primaries;
1686         codec->color_trc              = par->color_trc;
1687         codec->colorspace             = par->color_space;
1688         codec->chroma_sample_location = par->chroma_location;
1689         codec->sample_aspect_ratio    = par->sample_aspect_ratio;
1690         break;
1691     case AVMEDIA_TYPE_AUDIO:
1692         codec->sample_fmt      = par->format;
1693         codec->channel_layout  = par->channel_layout;
1694         codec->channels        = par->channels;
1695         codec->sample_rate     = par->sample_rate;
1696         codec->block_align     = par->block_align;
1697         codec->initial_padding = par->initial_padding;
1698         break;
1699     }
1700
1701     if (par->extradata) {
1702         av_freep(&codec->extradata);
1703         codec->extradata = av_mallocz(par->extradata_size + AV_INPUT_BUFFER_PADDING_SIZE);
1704         if (!codec->extradata)
1705             return AVERROR(ENOMEM);
1706         memcpy(codec->extradata, par->extradata, par->extradata_size);
1707         codec->extradata_size = par->extradata_size;
1708     }
1709
1710     return 0;
1711 }