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