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