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