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