]> git.sesse.net Git - ffmpeg/blob - libavcodec/utils.c
Revert "mjpegenc: disable huffman coding with AMV"
[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 FFmpeg.
7  *
8  * FFmpeg 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  * FFmpeg 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 FFmpeg; 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/atomic.h"
30 #include "libavutil/attributes.h"
31 #include "libavutil/avassert.h"
32 #include "libavutil/avstring.h"
33 #include "libavutil/bprint.h"
34 #include "libavutil/channel_layout.h"
35 #include "libavutil/crc.h"
36 #include "libavutil/frame.h"
37 #include "libavutil/hwcontext.h"
38 #include "libavutil/internal.h"
39 #include "libavutil/mathematics.h"
40 #include "libavutil/mem_internal.h"
41 #include "libavutil/pixdesc.h"
42 #include "libavutil/imgutils.h"
43 #include "libavutil/samplefmt.h"
44 #include "libavutil/dict.h"
45 #include "libavutil/thread.h"
46 #include "avcodec.h"
47 #include "libavutil/opt.h"
48 #include "me_cmp.h"
49 #include "mpegvideo.h"
50 #include "thread.h"
51 #include "frame_thread_encoder.h"
52 #include "internal.h"
53 #include "raw.h"
54 #include "bytestream.h"
55 #include "version.h"
56 #include <stdlib.h>
57 #include <stdarg.h>
58 #include <limits.h>
59 #include <float.h>
60 #if CONFIG_ICONV
61 # include <iconv.h>
62 #endif
63
64 #include "libavutil/ffversion.h"
65 const char av_codec_ffversion[] = "FFmpeg version " FFMPEG_VERSION;
66
67 #if HAVE_PTHREADS || HAVE_W32THREADS || HAVE_OS2THREADS
68 static int default_lockmgr_cb(void **arg, enum AVLockOp op)
69 {
70     void * volatile * mutex = arg;
71     int err;
72
73     switch (op) {
74     case AV_LOCK_CREATE:
75         return 0;
76     case AV_LOCK_OBTAIN:
77         if (!*mutex) {
78             pthread_mutex_t *tmp = av_malloc(sizeof(pthread_mutex_t));
79             if (!tmp)
80                 return AVERROR(ENOMEM);
81             if ((err = pthread_mutex_init(tmp, NULL))) {
82                 av_free(tmp);
83                 return AVERROR(err);
84             }
85             if (avpriv_atomic_ptr_cas(mutex, NULL, tmp)) {
86                 pthread_mutex_destroy(tmp);
87                 av_free(tmp);
88             }
89         }
90
91         if ((err = pthread_mutex_lock(*mutex)))
92             return AVERROR(err);
93
94         return 0;
95     case AV_LOCK_RELEASE:
96         if ((err = pthread_mutex_unlock(*mutex)))
97             return AVERROR(err);
98
99         return 0;
100     case AV_LOCK_DESTROY:
101         if (*mutex)
102             pthread_mutex_destroy(*mutex);
103         av_free(*mutex);
104         avpriv_atomic_ptr_cas(mutex, *mutex, NULL);
105         return 0;
106     }
107     return 1;
108 }
109 static int (*lockmgr_cb)(void **mutex, enum AVLockOp op) = default_lockmgr_cb;
110 #else
111 static int (*lockmgr_cb)(void **mutex, enum AVLockOp op) = NULL;
112 #endif
113
114
115 volatile int ff_avcodec_locked;
116 static int volatile entangled_thread_counter = 0;
117 static void *codec_mutex;
118 static void *avformat_mutex;
119
120 void av_fast_padded_malloc(void *ptr, unsigned int *size, size_t min_size)
121 {
122     uint8_t **p = ptr;
123     if (min_size > SIZE_MAX - AV_INPUT_BUFFER_PADDING_SIZE) {
124         av_freep(p);
125         *size = 0;
126         return;
127     }
128     if (!ff_fast_malloc(p, size, min_size + AV_INPUT_BUFFER_PADDING_SIZE, 1))
129         memset(*p + min_size, 0, AV_INPUT_BUFFER_PADDING_SIZE);
130 }
131
132 void av_fast_padded_mallocz(void *ptr, unsigned int *size, size_t min_size)
133 {
134     uint8_t **p = ptr;
135     if (min_size > SIZE_MAX - AV_INPUT_BUFFER_PADDING_SIZE) {
136         av_freep(p);
137         *size = 0;
138         return;
139     }
140     if (!ff_fast_malloc(p, size, min_size + AV_INPUT_BUFFER_PADDING_SIZE, 1))
141         memset(*p, 0, min_size + AV_INPUT_BUFFER_PADDING_SIZE);
142 }
143
144 /* encoder management */
145 static AVCodec *first_avcodec = NULL;
146 static AVCodec **last_avcodec = &first_avcodec;
147
148 AVCodec *av_codec_next(const AVCodec *c)
149 {
150     if (c)
151         return c->next;
152     else
153         return first_avcodec;
154 }
155
156 static av_cold void avcodec_init(void)
157 {
158     static int initialized = 0;
159
160     if (initialized != 0)
161         return;
162     initialized = 1;
163
164     if (CONFIG_ME_CMP)
165         ff_me_cmp_init_static();
166 }
167
168 int av_codec_is_encoder(const AVCodec *codec)
169 {
170     return codec && (codec->encode_sub || codec->encode2 ||codec->send_frame);
171 }
172
173 int av_codec_is_decoder(const AVCodec *codec)
174 {
175     return codec && (codec->decode || codec->send_packet);
176 }
177
178 av_cold void avcodec_register(AVCodec *codec)
179 {
180     AVCodec **p;
181     avcodec_init();
182     p = last_avcodec;
183     codec->next = NULL;
184
185     while(*p || avpriv_atomic_ptr_cas((void * volatile *)p, NULL, codec))
186         p = &(*p)->next;
187     last_avcodec = &codec->next;
188
189     if (codec->init_static_data)
190         codec->init_static_data(codec);
191 }
192
193 #if FF_API_EMU_EDGE
194 unsigned avcodec_get_edge_width(void)
195 {
196     return EDGE_WIDTH;
197 }
198 #endif
199
200 #if FF_API_SET_DIMENSIONS
201 void avcodec_set_dimensions(AVCodecContext *s, int width, int height)
202 {
203     int ret = ff_set_dimensions(s, width, height);
204     if (ret < 0) {
205         av_log(s, AV_LOG_WARNING, "Failed to set dimensions %d %d\n", width, height);
206     }
207 }
208 #endif
209
210 int ff_set_dimensions(AVCodecContext *s, int width, int height)
211 {
212     int ret = av_image_check_size2(width, height, s->max_pixels, AV_PIX_FMT_NONE, 0, s);
213
214     if (ret < 0)
215         width = height = 0;
216
217     s->coded_width  = width;
218     s->coded_height = height;
219     s->width        = AV_CEIL_RSHIFT(width,  s->lowres);
220     s->height       = AV_CEIL_RSHIFT(height, s->lowres);
221
222     return ret;
223 }
224
225 int ff_set_sar(AVCodecContext *avctx, AVRational sar)
226 {
227     int ret = av_image_check_sar(avctx->width, avctx->height, sar);
228
229     if (ret < 0) {
230         av_log(avctx, AV_LOG_WARNING, "ignoring invalid SAR: %d/%d\n",
231                sar.num, sar.den);
232         avctx->sample_aspect_ratio = (AVRational){ 0, 1 };
233         return ret;
234     } else {
235         avctx->sample_aspect_ratio = sar;
236     }
237     return 0;
238 }
239
240 int ff_side_data_update_matrix_encoding(AVFrame *frame,
241                                         enum AVMatrixEncoding matrix_encoding)
242 {
243     AVFrameSideData *side_data;
244     enum AVMatrixEncoding *data;
245
246     side_data = av_frame_get_side_data(frame, AV_FRAME_DATA_MATRIXENCODING);
247     if (!side_data)
248         side_data = av_frame_new_side_data(frame, AV_FRAME_DATA_MATRIXENCODING,
249                                            sizeof(enum AVMatrixEncoding));
250
251     if (!side_data)
252         return AVERROR(ENOMEM);
253
254     data  = (enum AVMatrixEncoding*)side_data->data;
255     *data = matrix_encoding;
256
257     return 0;
258 }
259
260 void avcodec_align_dimensions2(AVCodecContext *s, int *width, int *height,
261                                int linesize_align[AV_NUM_DATA_POINTERS])
262 {
263     int i;
264     int w_align = 1;
265     int h_align = 1;
266     AVPixFmtDescriptor const *desc = av_pix_fmt_desc_get(s->pix_fmt);
267
268     if (desc) {
269         w_align = 1 << desc->log2_chroma_w;
270         h_align = 1 << desc->log2_chroma_h;
271     }
272
273     switch (s->pix_fmt) {
274     case AV_PIX_FMT_YUV420P:
275     case AV_PIX_FMT_YUYV422:
276     case AV_PIX_FMT_YVYU422:
277     case AV_PIX_FMT_UYVY422:
278     case AV_PIX_FMT_YUV422P:
279     case AV_PIX_FMT_YUV440P:
280     case AV_PIX_FMT_YUV444P:
281     case AV_PIX_FMT_GBRP:
282     case AV_PIX_FMT_GBRAP:
283     case AV_PIX_FMT_GRAY8:
284     case AV_PIX_FMT_GRAY16BE:
285     case AV_PIX_FMT_GRAY16LE:
286     case AV_PIX_FMT_YUVJ420P:
287     case AV_PIX_FMT_YUVJ422P:
288     case AV_PIX_FMT_YUVJ440P:
289     case AV_PIX_FMT_YUVJ444P:
290     case AV_PIX_FMT_YUVA420P:
291     case AV_PIX_FMT_YUVA422P:
292     case AV_PIX_FMT_YUVA444P:
293     case AV_PIX_FMT_YUV420P9LE:
294     case AV_PIX_FMT_YUV420P9BE:
295     case AV_PIX_FMT_YUV420P10LE:
296     case AV_PIX_FMT_YUV420P10BE:
297     case AV_PIX_FMT_YUV420P12LE:
298     case AV_PIX_FMT_YUV420P12BE:
299     case AV_PIX_FMT_YUV420P14LE:
300     case AV_PIX_FMT_YUV420P14BE:
301     case AV_PIX_FMT_YUV420P16LE:
302     case AV_PIX_FMT_YUV420P16BE:
303     case AV_PIX_FMT_YUVA420P9LE:
304     case AV_PIX_FMT_YUVA420P9BE:
305     case AV_PIX_FMT_YUVA420P10LE:
306     case AV_PIX_FMT_YUVA420P10BE:
307     case AV_PIX_FMT_YUVA420P16LE:
308     case AV_PIX_FMT_YUVA420P16BE:
309     case AV_PIX_FMT_YUV422P9LE:
310     case AV_PIX_FMT_YUV422P9BE:
311     case AV_PIX_FMT_YUV422P10LE:
312     case AV_PIX_FMT_YUV422P10BE:
313     case AV_PIX_FMT_YUV422P12LE:
314     case AV_PIX_FMT_YUV422P12BE:
315     case AV_PIX_FMT_YUV422P14LE:
316     case AV_PIX_FMT_YUV422P14BE:
317     case AV_PIX_FMT_YUV422P16LE:
318     case AV_PIX_FMT_YUV422P16BE:
319     case AV_PIX_FMT_YUVA422P9LE:
320     case AV_PIX_FMT_YUVA422P9BE:
321     case AV_PIX_FMT_YUVA422P10LE:
322     case AV_PIX_FMT_YUVA422P10BE:
323     case AV_PIX_FMT_YUVA422P16LE:
324     case AV_PIX_FMT_YUVA422P16BE:
325     case AV_PIX_FMT_YUV440P10LE:
326     case AV_PIX_FMT_YUV440P10BE:
327     case AV_PIX_FMT_YUV440P12LE:
328     case AV_PIX_FMT_YUV440P12BE:
329     case AV_PIX_FMT_YUV444P9LE:
330     case AV_PIX_FMT_YUV444P9BE:
331     case AV_PIX_FMT_YUV444P10LE:
332     case AV_PIX_FMT_YUV444P10BE:
333     case AV_PIX_FMT_YUV444P12LE:
334     case AV_PIX_FMT_YUV444P12BE:
335     case AV_PIX_FMT_YUV444P14LE:
336     case AV_PIX_FMT_YUV444P14BE:
337     case AV_PIX_FMT_YUV444P16LE:
338     case AV_PIX_FMT_YUV444P16BE:
339     case AV_PIX_FMT_YUVA444P9LE:
340     case AV_PIX_FMT_YUVA444P9BE:
341     case AV_PIX_FMT_YUVA444P10LE:
342     case AV_PIX_FMT_YUVA444P10BE:
343     case AV_PIX_FMT_YUVA444P16LE:
344     case AV_PIX_FMT_YUVA444P16BE:
345     case AV_PIX_FMT_GBRP9LE:
346     case AV_PIX_FMT_GBRP9BE:
347     case AV_PIX_FMT_GBRP10LE:
348     case AV_PIX_FMT_GBRP10BE:
349     case AV_PIX_FMT_GBRP12LE:
350     case AV_PIX_FMT_GBRP12BE:
351     case AV_PIX_FMT_GBRP14LE:
352     case AV_PIX_FMT_GBRP14BE:
353     case AV_PIX_FMT_GBRP16LE:
354     case AV_PIX_FMT_GBRP16BE:
355     case AV_PIX_FMT_GBRAP12LE:
356     case AV_PIX_FMT_GBRAP12BE:
357     case AV_PIX_FMT_GBRAP16LE:
358     case AV_PIX_FMT_GBRAP16BE:
359         w_align = 16; //FIXME assume 16 pixel per macroblock
360         h_align = 16 * 2; // interlaced needs 2 macroblocks height
361         break;
362     case AV_PIX_FMT_YUV411P:
363     case AV_PIX_FMT_YUVJ411P:
364     case AV_PIX_FMT_UYYVYY411:
365         w_align = 32;
366         h_align = 16 * 2;
367         break;
368     case AV_PIX_FMT_YUV410P:
369         if (s->codec_id == AV_CODEC_ID_SVQ1) {
370             w_align = 64;
371             h_align = 64;
372         }
373         break;
374     case AV_PIX_FMT_RGB555:
375         if (s->codec_id == AV_CODEC_ID_RPZA) {
376             w_align = 4;
377             h_align = 4;
378         }
379         if (s->codec_id == AV_CODEC_ID_INTERPLAY_VIDEO) {
380             w_align = 8;
381             h_align = 8;
382         }
383         break;
384     case AV_PIX_FMT_PAL8:
385     case AV_PIX_FMT_BGR8:
386     case AV_PIX_FMT_RGB8:
387         if (s->codec_id == AV_CODEC_ID_SMC ||
388             s->codec_id == AV_CODEC_ID_CINEPAK) {
389             w_align = 4;
390             h_align = 4;
391         }
392         if (s->codec_id == AV_CODEC_ID_JV ||
393             s->codec_id == AV_CODEC_ID_INTERPLAY_VIDEO) {
394             w_align = 8;
395             h_align = 8;
396         }
397         break;
398     case AV_PIX_FMT_BGR24:
399         if ((s->codec_id == AV_CODEC_ID_MSZH) ||
400             (s->codec_id == AV_CODEC_ID_ZLIB)) {
401             w_align = 4;
402             h_align = 4;
403         }
404         break;
405     case AV_PIX_FMT_RGB24:
406         if (s->codec_id == AV_CODEC_ID_CINEPAK) {
407             w_align = 4;
408             h_align = 4;
409         }
410         break;
411     default:
412         break;
413     }
414
415     if (s->codec_id == AV_CODEC_ID_IFF_ILBM) {
416         w_align = FFMAX(w_align, 8);
417     }
418
419     *width  = FFALIGN(*width, w_align);
420     *height = FFALIGN(*height, h_align);
421     if (s->codec_id == AV_CODEC_ID_H264 || s->lowres) {
422         // some of the optimized chroma MC reads one line too much
423         // which is also done in mpeg decoders with lowres > 0
424         *height += 2;
425
426         // H.264 uses edge emulation for out of frame motion vectors, for this
427         // it requires a temporary area large enough to hold a 21x21 block,
428         // increasing witdth ensure that the temporary area is large enough,
429         // the next rounded up width is 32
430         *width = FFMAX(*width, 32);
431     }
432
433     for (i = 0; i < 4; i++)
434         linesize_align[i] = STRIDE_ALIGN;
435 }
436
437 void avcodec_align_dimensions(AVCodecContext *s, int *width, int *height)
438 {
439     const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(s->pix_fmt);
440     int chroma_shift = desc->log2_chroma_w;
441     int linesize_align[AV_NUM_DATA_POINTERS];
442     int align;
443
444     avcodec_align_dimensions2(s, width, height, linesize_align);
445     align               = FFMAX(linesize_align[0], linesize_align[3]);
446     linesize_align[1] <<= chroma_shift;
447     linesize_align[2] <<= chroma_shift;
448     align               = FFMAX3(align, linesize_align[1], linesize_align[2]);
449     *width              = FFALIGN(*width, align);
450 }
451
452 int avcodec_enum_to_chroma_pos(int *xpos, int *ypos, enum AVChromaLocation pos)
453 {
454     if (pos <= AVCHROMA_LOC_UNSPECIFIED || pos >= AVCHROMA_LOC_NB)
455         return AVERROR(EINVAL);
456     pos--;
457
458     *xpos = (pos&1) * 128;
459     *ypos = ((pos>>1)^(pos<4)) * 128;
460
461     return 0;
462 }
463
464 enum AVChromaLocation avcodec_chroma_pos_to_enum(int xpos, int ypos)
465 {
466     int pos, xout, yout;
467
468     for (pos = AVCHROMA_LOC_UNSPECIFIED + 1; pos < AVCHROMA_LOC_NB; pos++) {
469         if (avcodec_enum_to_chroma_pos(&xout, &yout, pos) == 0 && xout == xpos && yout == ypos)
470             return pos;
471     }
472     return AVCHROMA_LOC_UNSPECIFIED;
473 }
474
475 int avcodec_fill_audio_frame(AVFrame *frame, int nb_channels,
476                              enum AVSampleFormat sample_fmt, const uint8_t *buf,
477                              int buf_size, int align)
478 {
479     int ch, planar, needed_size, ret = 0;
480
481     needed_size = av_samples_get_buffer_size(NULL, nb_channels,
482                                              frame->nb_samples, sample_fmt,
483                                              align);
484     if (buf_size < needed_size)
485         return AVERROR(EINVAL);
486
487     planar = av_sample_fmt_is_planar(sample_fmt);
488     if (planar && nb_channels > AV_NUM_DATA_POINTERS) {
489         if (!(frame->extended_data = av_mallocz_array(nb_channels,
490                                                 sizeof(*frame->extended_data))))
491             return AVERROR(ENOMEM);
492     } else {
493         frame->extended_data = frame->data;
494     }
495
496     if ((ret = av_samples_fill_arrays(frame->extended_data, &frame->linesize[0],
497                                       (uint8_t *)(intptr_t)buf, nb_channels, frame->nb_samples,
498                                       sample_fmt, align)) < 0) {
499         if (frame->extended_data != frame->data)
500             av_freep(&frame->extended_data);
501         return ret;
502     }
503     if (frame->extended_data != frame->data) {
504         for (ch = 0; ch < AV_NUM_DATA_POINTERS; ch++)
505             frame->data[ch] = frame->extended_data[ch];
506     }
507
508     return ret;
509 }
510
511 void ff_color_frame(AVFrame *frame, const int c[4])
512 {
513     const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(frame->format);
514     int p, y, x;
515
516     av_assert0(desc->flags & AV_PIX_FMT_FLAG_PLANAR);
517
518     for (p = 0; p<desc->nb_components; p++) {
519         uint8_t *dst = frame->data[p];
520         int is_chroma = p == 1 || p == 2;
521         int bytes  = is_chroma ? AV_CEIL_RSHIFT(frame->width,  desc->log2_chroma_w) : frame->width;
522         int height = is_chroma ? AV_CEIL_RSHIFT(frame->height, desc->log2_chroma_h) : frame->height;
523         for (y = 0; y < height; y++) {
524             if (desc->comp[0].depth >= 9) {
525                 for (x = 0; x<bytes; x++)
526                     ((uint16_t*)dst)[x] = c[p];
527             }else
528                 memset(dst, c[p], bytes);
529             dst += frame->linesize[p];
530         }
531     }
532 }
533
534 int avcodec_default_execute(AVCodecContext *c, int (*func)(AVCodecContext *c2, void *arg2), void *arg, int *ret, int count, int size)
535 {
536     int i;
537
538     for (i = 0; i < count; i++) {
539         int r = func(c, (char *)arg + i * size);
540         if (ret)
541             ret[i] = r;
542     }
543     emms_c();
544     return 0;
545 }
546
547 int avcodec_default_execute2(AVCodecContext *c, int (*func)(AVCodecContext *c2, void *arg2, int jobnr, int threadnr), void *arg, int *ret, int count)
548 {
549     int i;
550
551     for (i = 0; i < count; i++) {
552         int r = func(c, arg, i, 0);
553         if (ret)
554             ret[i] = r;
555     }
556     emms_c();
557     return 0;
558 }
559
560 enum AVPixelFormat avpriv_find_pix_fmt(const PixelFormatTag *tags,
561                                        unsigned int fourcc)
562 {
563     while (tags->pix_fmt >= 0) {
564         if (tags->fourcc == fourcc)
565             return tags->pix_fmt;
566         tags++;
567     }
568     return AV_PIX_FMT_NONE;
569 }
570
571 MAKE_ACCESSORS(AVCodecContext, codec, AVRational, pkt_timebase)
572 MAKE_ACCESSORS(AVCodecContext, codec, const AVCodecDescriptor *, codec_descriptor)
573 MAKE_ACCESSORS(AVCodecContext, codec, int, lowres)
574 MAKE_ACCESSORS(AVCodecContext, codec, int, seek_preroll)
575 MAKE_ACCESSORS(AVCodecContext, codec, uint16_t*, chroma_intra_matrix)
576
577 unsigned av_codec_get_codec_properties(const AVCodecContext *codec)
578 {
579     return codec->properties;
580 }
581
582 int av_codec_get_max_lowres(const AVCodec *codec)
583 {
584     return codec->max_lowres;
585 }
586
587 int avpriv_codec_get_cap_skip_frame_fill_param(const AVCodec *codec){
588     return !!(codec->caps_internal & FF_CODEC_CAP_SKIP_FRAME_FILL_PARAM);
589 }
590
591 static int64_t get_bit_rate(AVCodecContext *ctx)
592 {
593     int64_t bit_rate;
594     int bits_per_sample;
595
596     switch (ctx->codec_type) {
597     case AVMEDIA_TYPE_VIDEO:
598     case AVMEDIA_TYPE_DATA:
599     case AVMEDIA_TYPE_SUBTITLE:
600     case AVMEDIA_TYPE_ATTACHMENT:
601         bit_rate = ctx->bit_rate;
602         break;
603     case AVMEDIA_TYPE_AUDIO:
604         bits_per_sample = av_get_bits_per_sample(ctx->codec_id);
605         bit_rate = bits_per_sample ? ctx->sample_rate * (int64_t)ctx->channels * bits_per_sample : ctx->bit_rate;
606         break;
607     default:
608         bit_rate = 0;
609         break;
610     }
611     return bit_rate;
612 }
613
614 int attribute_align_arg ff_codec_open2_recursive(AVCodecContext *avctx, const AVCodec *codec, AVDictionary **options)
615 {
616     int ret = 0;
617
618     ff_unlock_avcodec(codec);
619
620     ret = avcodec_open2(avctx, codec, options);
621
622     ff_lock_avcodec(avctx, codec);
623     return ret;
624 }
625
626 int attribute_align_arg avcodec_open2(AVCodecContext *avctx, const AVCodec *codec, AVDictionary **options)
627 {
628     int ret = 0;
629     AVDictionary *tmp = NULL;
630     const AVPixFmtDescriptor *pixdesc;
631
632     if (avcodec_is_open(avctx))
633         return 0;
634
635     if ((!codec && !avctx->codec)) {
636         av_log(avctx, AV_LOG_ERROR, "No codec provided to avcodec_open2()\n");
637         return AVERROR(EINVAL);
638     }
639     if ((codec && avctx->codec && codec != avctx->codec)) {
640         av_log(avctx, AV_LOG_ERROR, "This AVCodecContext was allocated for %s, "
641                                     "but %s passed to avcodec_open2()\n", avctx->codec->name, codec->name);
642         return AVERROR(EINVAL);
643     }
644     if (!codec)
645         codec = avctx->codec;
646
647     if (avctx->extradata_size < 0 || avctx->extradata_size >= FF_MAX_EXTRADATA_SIZE)
648         return AVERROR(EINVAL);
649
650     if (options)
651         av_dict_copy(&tmp, *options, 0);
652
653     ret = ff_lock_avcodec(avctx, codec);
654     if (ret < 0)
655         return ret;
656
657     avctx->internal = av_mallocz(sizeof(AVCodecInternal));
658     if (!avctx->internal) {
659         ret = AVERROR(ENOMEM);
660         goto end;
661     }
662
663     avctx->internal->pool = av_mallocz(sizeof(*avctx->internal->pool));
664     if (!avctx->internal->pool) {
665         ret = AVERROR(ENOMEM);
666         goto free_and_end;
667     }
668
669     avctx->internal->to_free = av_frame_alloc();
670     if (!avctx->internal->to_free) {
671         ret = AVERROR(ENOMEM);
672         goto free_and_end;
673     }
674
675     avctx->internal->buffer_frame = av_frame_alloc();
676     if (!avctx->internal->buffer_frame) {
677         ret = AVERROR(ENOMEM);
678         goto free_and_end;
679     }
680
681     avctx->internal->buffer_pkt = av_packet_alloc();
682     if (!avctx->internal->buffer_pkt) {
683         ret = AVERROR(ENOMEM);
684         goto free_and_end;
685     }
686
687     avctx->internal->skip_samples_multiplier = 1;
688
689     if (codec->priv_data_size > 0) {
690         if (!avctx->priv_data) {
691             avctx->priv_data = av_mallocz(codec->priv_data_size);
692             if (!avctx->priv_data) {
693                 ret = AVERROR(ENOMEM);
694                 goto end;
695             }
696             if (codec->priv_class) {
697                 *(const AVClass **)avctx->priv_data = codec->priv_class;
698                 av_opt_set_defaults(avctx->priv_data);
699             }
700         }
701         if (codec->priv_class && (ret = av_opt_set_dict(avctx->priv_data, &tmp)) < 0)
702             goto free_and_end;
703     } else {
704         avctx->priv_data = NULL;
705     }
706     if ((ret = av_opt_set_dict(avctx, &tmp)) < 0)
707         goto free_and_end;
708
709     if (avctx->codec_whitelist && av_match_list(codec->name, avctx->codec_whitelist, ',') <= 0) {
710         av_log(avctx, AV_LOG_ERROR, "Codec (%s) not on whitelist \'%s\'\n", codec->name, avctx->codec_whitelist);
711         ret = AVERROR(EINVAL);
712         goto free_and_end;
713     }
714
715     // only call ff_set_dimensions() for non H.264/VP6F/DXV codecs so as not to overwrite previously setup dimensions
716     if (!(avctx->coded_width && avctx->coded_height && avctx->width && avctx->height &&
717           (avctx->codec_id == AV_CODEC_ID_H264 || avctx->codec_id == AV_CODEC_ID_VP6F || avctx->codec_id == AV_CODEC_ID_DXV))) {
718     if (avctx->coded_width && avctx->coded_height)
719         ret = ff_set_dimensions(avctx, avctx->coded_width, avctx->coded_height);
720     else if (avctx->width && avctx->height)
721         ret = ff_set_dimensions(avctx, avctx->width, avctx->height);
722     if (ret < 0)
723         goto free_and_end;
724     }
725
726     if ((avctx->coded_width || avctx->coded_height || avctx->width || avctx->height)
727         && (  av_image_check_size2(avctx->coded_width, avctx->coded_height, avctx->max_pixels, AV_PIX_FMT_NONE, 0, avctx) < 0
728            || av_image_check_size2(avctx->width,       avctx->height,       avctx->max_pixels, AV_PIX_FMT_NONE, 0, avctx) < 0)) {
729         av_log(avctx, AV_LOG_WARNING, "Ignoring invalid width/height values\n");
730         ff_set_dimensions(avctx, 0, 0);
731     }
732
733     if (avctx->width > 0 && avctx->height > 0) {
734         if (av_image_check_sar(avctx->width, avctx->height,
735                                avctx->sample_aspect_ratio) < 0) {
736             av_log(avctx, AV_LOG_WARNING, "ignoring invalid SAR: %u/%u\n",
737                    avctx->sample_aspect_ratio.num,
738                    avctx->sample_aspect_ratio.den);
739             avctx->sample_aspect_ratio = (AVRational){ 0, 1 };
740         }
741     }
742
743     /* if the decoder init function was already called previously,
744      * free the already allocated subtitle_header before overwriting it */
745     if (av_codec_is_decoder(codec))
746         av_freep(&avctx->subtitle_header);
747
748     if (avctx->channels > FF_SANE_NB_CHANNELS) {
749         ret = AVERROR(EINVAL);
750         goto free_and_end;
751     }
752
753     avctx->codec = codec;
754     if ((avctx->codec_type == AVMEDIA_TYPE_UNKNOWN || avctx->codec_type == codec->type) &&
755         avctx->codec_id == AV_CODEC_ID_NONE) {
756         avctx->codec_type = codec->type;
757         avctx->codec_id   = codec->id;
758     }
759     if (avctx->codec_id != codec->id || (avctx->codec_type != codec->type
760                                          && avctx->codec_type != AVMEDIA_TYPE_ATTACHMENT)) {
761         av_log(avctx, AV_LOG_ERROR, "Codec type or id mismatches\n");
762         ret = AVERROR(EINVAL);
763         goto free_and_end;
764     }
765     avctx->frame_number = 0;
766     avctx->codec_descriptor = avcodec_descriptor_get(avctx->codec_id);
767
768     if ((avctx->codec->capabilities & AV_CODEC_CAP_EXPERIMENTAL) &&
769         avctx->strict_std_compliance > FF_COMPLIANCE_EXPERIMENTAL) {
770         const char *codec_string = av_codec_is_encoder(codec) ? "encoder" : "decoder";
771         AVCodec *codec2;
772         av_log(avctx, AV_LOG_ERROR,
773                "The %s '%s' is experimental but experimental codecs are not enabled, "
774                "add '-strict %d' if you want to use it.\n",
775                codec_string, codec->name, FF_COMPLIANCE_EXPERIMENTAL);
776         codec2 = av_codec_is_encoder(codec) ? avcodec_find_encoder(codec->id) : avcodec_find_decoder(codec->id);
777         if (!(codec2->capabilities & AV_CODEC_CAP_EXPERIMENTAL))
778             av_log(avctx, AV_LOG_ERROR, "Alternatively use the non experimental %s '%s'.\n",
779                 codec_string, codec2->name);
780         ret = AVERROR_EXPERIMENTAL;
781         goto free_and_end;
782     }
783
784     if (avctx->codec_type == AVMEDIA_TYPE_AUDIO &&
785         (!avctx->time_base.num || !avctx->time_base.den)) {
786         avctx->time_base.num = 1;
787         avctx->time_base.den = avctx->sample_rate;
788     }
789
790     if (!HAVE_THREADS)
791         av_log(avctx, AV_LOG_WARNING, "Warning: not compiled with thread support, using thread emulation\n");
792
793     if (CONFIG_FRAME_THREAD_ENCODER && av_codec_is_encoder(avctx->codec)) {
794         ff_unlock_avcodec(codec); //we will instantiate a few encoders thus kick the counter to prevent false detection of a problem
795         ret = ff_frame_thread_encoder_init(avctx, options ? *options : NULL);
796         ff_lock_avcodec(avctx, codec);
797         if (ret < 0)
798             goto free_and_end;
799     }
800
801     if (HAVE_THREADS
802         && !(avctx->internal->frame_thread_encoder && (avctx->active_thread_type&FF_THREAD_FRAME))) {
803         ret = ff_thread_init(avctx);
804         if (ret < 0) {
805             goto free_and_end;
806         }
807     }
808     if (!HAVE_THREADS && !(codec->capabilities & AV_CODEC_CAP_AUTO_THREADS))
809         avctx->thread_count = 1;
810
811     if (avctx->codec->max_lowres < avctx->lowres || avctx->lowres < 0) {
812         av_log(avctx, AV_LOG_WARNING, "The maximum value for lowres supported by the decoder is %d\n",
813                avctx->codec->max_lowres);
814         avctx->lowres = avctx->codec->max_lowres;
815     }
816
817 #if FF_API_VISMV
818     if (avctx->debug_mv)
819         av_log(avctx, AV_LOG_WARNING, "The 'vismv' option is deprecated, "
820                "see the codecview filter instead.\n");
821 #endif
822
823     if (av_codec_is_encoder(avctx->codec)) {
824         int i;
825 #if FF_API_CODED_FRAME
826 FF_DISABLE_DEPRECATION_WARNINGS
827         avctx->coded_frame = av_frame_alloc();
828         if (!avctx->coded_frame) {
829             ret = AVERROR(ENOMEM);
830             goto free_and_end;
831         }
832 FF_ENABLE_DEPRECATION_WARNINGS
833 #endif
834
835         if (avctx->time_base.num <= 0 || avctx->time_base.den <= 0) {
836             av_log(avctx, AV_LOG_ERROR, "The encoder timebase is not set.\n");
837             ret = AVERROR(EINVAL);
838             goto free_and_end;
839         }
840
841         if (avctx->codec->sample_fmts) {
842             for (i = 0; avctx->codec->sample_fmts[i] != AV_SAMPLE_FMT_NONE; i++) {
843                 if (avctx->sample_fmt == avctx->codec->sample_fmts[i])
844                     break;
845                 if (avctx->channels == 1 &&
846                     av_get_planar_sample_fmt(avctx->sample_fmt) ==
847                     av_get_planar_sample_fmt(avctx->codec->sample_fmts[i])) {
848                     avctx->sample_fmt = avctx->codec->sample_fmts[i];
849                     break;
850                 }
851             }
852             if (avctx->codec->sample_fmts[i] == AV_SAMPLE_FMT_NONE) {
853                 char buf[128];
854                 snprintf(buf, sizeof(buf), "%d", avctx->sample_fmt);
855                 av_log(avctx, AV_LOG_ERROR, "Specified sample format %s is invalid or not supported\n",
856                        (char *)av_x_if_null(av_get_sample_fmt_name(avctx->sample_fmt), buf));
857                 ret = AVERROR(EINVAL);
858                 goto free_and_end;
859             }
860         }
861         if (avctx->codec->pix_fmts) {
862             for (i = 0; avctx->codec->pix_fmts[i] != AV_PIX_FMT_NONE; i++)
863                 if (avctx->pix_fmt == avctx->codec->pix_fmts[i])
864                     break;
865             if (avctx->codec->pix_fmts[i] == AV_PIX_FMT_NONE
866                 && !((avctx->codec_id == AV_CODEC_ID_MJPEG || avctx->codec_id == AV_CODEC_ID_LJPEG)
867                      && avctx->strict_std_compliance <= FF_COMPLIANCE_UNOFFICIAL)) {
868                 char buf[128];
869                 snprintf(buf, sizeof(buf), "%d", avctx->pix_fmt);
870                 av_log(avctx, AV_LOG_ERROR, "Specified pixel format %s is invalid or not supported\n",
871                        (char *)av_x_if_null(av_get_pix_fmt_name(avctx->pix_fmt), buf));
872                 ret = AVERROR(EINVAL);
873                 goto free_and_end;
874             }
875             if (avctx->codec->pix_fmts[i] == AV_PIX_FMT_YUVJ420P ||
876                 avctx->codec->pix_fmts[i] == AV_PIX_FMT_YUVJ411P ||
877                 avctx->codec->pix_fmts[i] == AV_PIX_FMT_YUVJ422P ||
878                 avctx->codec->pix_fmts[i] == AV_PIX_FMT_YUVJ440P ||
879                 avctx->codec->pix_fmts[i] == AV_PIX_FMT_YUVJ444P)
880                 avctx->color_range = AVCOL_RANGE_JPEG;
881         }
882         if (avctx->codec->supported_samplerates) {
883             for (i = 0; avctx->codec->supported_samplerates[i] != 0; i++)
884                 if (avctx->sample_rate == avctx->codec->supported_samplerates[i])
885                     break;
886             if (avctx->codec->supported_samplerates[i] == 0) {
887                 av_log(avctx, AV_LOG_ERROR, "Specified sample rate %d is not supported\n",
888                        avctx->sample_rate);
889                 ret = AVERROR(EINVAL);
890                 goto free_and_end;
891             }
892         }
893         if (avctx->sample_rate < 0) {
894             av_log(avctx, AV_LOG_ERROR, "Specified sample rate %d is not supported\n",
895                     avctx->sample_rate);
896             ret = AVERROR(EINVAL);
897             goto free_and_end;
898         }
899         if (avctx->codec->channel_layouts) {
900             if (!avctx->channel_layout) {
901                 av_log(avctx, AV_LOG_WARNING, "Channel layout not specified\n");
902             } else {
903                 for (i = 0; avctx->codec->channel_layouts[i] != 0; i++)
904                     if (avctx->channel_layout == avctx->codec->channel_layouts[i])
905                         break;
906                 if (avctx->codec->channel_layouts[i] == 0) {
907                     char buf[512];
908                     av_get_channel_layout_string(buf, sizeof(buf), -1, avctx->channel_layout);
909                     av_log(avctx, AV_LOG_ERROR, "Specified channel layout '%s' is not supported\n", buf);
910                     ret = AVERROR(EINVAL);
911                     goto free_and_end;
912                 }
913             }
914         }
915         if (avctx->channel_layout && avctx->channels) {
916             int channels = av_get_channel_layout_nb_channels(avctx->channel_layout);
917             if (channels != avctx->channels) {
918                 char buf[512];
919                 av_get_channel_layout_string(buf, sizeof(buf), -1, avctx->channel_layout);
920                 av_log(avctx, AV_LOG_ERROR,
921                        "Channel layout '%s' with %d channels does not match number of specified channels %d\n",
922                        buf, channels, avctx->channels);
923                 ret = AVERROR(EINVAL);
924                 goto free_and_end;
925             }
926         } else if (avctx->channel_layout) {
927             avctx->channels = av_get_channel_layout_nb_channels(avctx->channel_layout);
928         }
929         if (avctx->channels < 0) {
930             av_log(avctx, AV_LOG_ERROR, "Specified number of channels %d is not supported\n",
931                     avctx->channels);
932             ret = AVERROR(EINVAL);
933             goto free_and_end;
934         }
935         if(avctx->codec_type == AVMEDIA_TYPE_VIDEO) {
936             pixdesc = av_pix_fmt_desc_get(avctx->pix_fmt);
937             if (    avctx->bits_per_raw_sample < 0
938                 || (avctx->bits_per_raw_sample > 8 && pixdesc->comp[0].depth <= 8)) {
939                 av_log(avctx, AV_LOG_WARNING, "Specified bit depth %d not possible with the specified pixel formats depth %d\n",
940                     avctx->bits_per_raw_sample, pixdesc->comp[0].depth);
941                 avctx->bits_per_raw_sample = pixdesc->comp[0].depth;
942             }
943             if (avctx->width <= 0 || avctx->height <= 0) {
944                 av_log(avctx, AV_LOG_ERROR, "dimensions not set\n");
945                 ret = AVERROR(EINVAL);
946                 goto free_and_end;
947             }
948         }
949         if (   (avctx->codec_type == AVMEDIA_TYPE_VIDEO || avctx->codec_type == AVMEDIA_TYPE_AUDIO)
950             && avctx->bit_rate>0 && avctx->bit_rate<1000) {
951             av_log(avctx, AV_LOG_WARNING, "Bitrate %"PRId64" is extremely low, maybe you mean %"PRId64"k\n", (int64_t)avctx->bit_rate, (int64_t)avctx->bit_rate);
952         }
953
954         if (!avctx->rc_initial_buffer_occupancy)
955             avctx->rc_initial_buffer_occupancy = avctx->rc_buffer_size * 3 / 4;
956
957         if (avctx->ticks_per_frame && avctx->time_base.num &&
958             avctx->ticks_per_frame > INT_MAX / avctx->time_base.num) {
959             av_log(avctx, AV_LOG_ERROR,
960                    "ticks_per_frame %d too large for the timebase %d/%d.",
961                    avctx->ticks_per_frame,
962                    avctx->time_base.num,
963                    avctx->time_base.den);
964             goto free_and_end;
965         }
966
967         if (avctx->hw_frames_ctx) {
968             AVHWFramesContext *frames_ctx = (AVHWFramesContext*)avctx->hw_frames_ctx->data;
969             if (frames_ctx->format != avctx->pix_fmt) {
970                 av_log(avctx, AV_LOG_ERROR,
971                        "Mismatching AVCodecContext.pix_fmt and AVHWFramesContext.format\n");
972                 ret = AVERROR(EINVAL);
973                 goto free_and_end;
974             }
975             if (avctx->sw_pix_fmt != AV_PIX_FMT_NONE &&
976                 avctx->sw_pix_fmt != frames_ctx->sw_format) {
977                 av_log(avctx, AV_LOG_ERROR,
978                        "Mismatching AVCodecContext.sw_pix_fmt (%s) "
979                        "and AVHWFramesContext.sw_format (%s)\n",
980                        av_get_pix_fmt_name(avctx->sw_pix_fmt),
981                        av_get_pix_fmt_name(frames_ctx->sw_format));
982                 ret = AVERROR(EINVAL);
983                 goto free_and_end;
984             }
985             avctx->sw_pix_fmt = frames_ctx->sw_format;
986         }
987     }
988
989     avctx->pts_correction_num_faulty_pts =
990     avctx->pts_correction_num_faulty_dts = 0;
991     avctx->pts_correction_last_pts =
992     avctx->pts_correction_last_dts = INT64_MIN;
993
994     if (   !CONFIG_GRAY && avctx->flags & AV_CODEC_FLAG_GRAY
995         && avctx->codec_descriptor->type == AVMEDIA_TYPE_VIDEO)
996         av_log(avctx, AV_LOG_WARNING,
997                "gray decoding requested but not enabled at configuration time\n");
998
999     if (   avctx->codec->init && (!(avctx->active_thread_type&FF_THREAD_FRAME)
1000         || avctx->internal->frame_thread_encoder)) {
1001         ret = avctx->codec->init(avctx);
1002         if (ret < 0) {
1003             goto free_and_end;
1004         }
1005     }
1006
1007     ret=0;
1008
1009 #if FF_API_AUDIOENC_DELAY
1010     if (av_codec_is_encoder(avctx->codec))
1011         avctx->delay = avctx->initial_padding;
1012 #endif
1013
1014     if (av_codec_is_decoder(avctx->codec)) {
1015         if (!avctx->bit_rate)
1016             avctx->bit_rate = get_bit_rate(avctx);
1017         /* validate channel layout from the decoder */
1018         if (avctx->channel_layout) {
1019             int channels = av_get_channel_layout_nb_channels(avctx->channel_layout);
1020             if (!avctx->channels)
1021                 avctx->channels = channels;
1022             else if (channels != avctx->channels) {
1023                 char buf[512];
1024                 av_get_channel_layout_string(buf, sizeof(buf), -1, avctx->channel_layout);
1025                 av_log(avctx, AV_LOG_WARNING,
1026                        "Channel layout '%s' with %d channels does not match specified number of channels %d: "
1027                        "ignoring specified channel layout\n",
1028                        buf, channels, avctx->channels);
1029                 avctx->channel_layout = 0;
1030             }
1031         }
1032         if (avctx->channels && avctx->channels < 0 ||
1033             avctx->channels > FF_SANE_NB_CHANNELS) {
1034             ret = AVERROR(EINVAL);
1035             goto free_and_end;
1036         }
1037         if (avctx->sub_charenc) {
1038             if (avctx->codec_type != AVMEDIA_TYPE_SUBTITLE) {
1039                 av_log(avctx, AV_LOG_ERROR, "Character encoding is only "
1040                        "supported with subtitles codecs\n");
1041                 ret = AVERROR(EINVAL);
1042                 goto free_and_end;
1043             } else if (avctx->codec_descriptor->props & AV_CODEC_PROP_BITMAP_SUB) {
1044                 av_log(avctx, AV_LOG_WARNING, "Codec '%s' is bitmap-based, "
1045                        "subtitles character encoding will be ignored\n",
1046                        avctx->codec_descriptor->name);
1047                 avctx->sub_charenc_mode = FF_SUB_CHARENC_MODE_DO_NOTHING;
1048             } else {
1049                 /* input character encoding is set for a text based subtitle
1050                  * codec at this point */
1051                 if (avctx->sub_charenc_mode == FF_SUB_CHARENC_MODE_AUTOMATIC)
1052                     avctx->sub_charenc_mode = FF_SUB_CHARENC_MODE_PRE_DECODER;
1053
1054                 if (avctx->sub_charenc_mode == FF_SUB_CHARENC_MODE_PRE_DECODER) {
1055 #if CONFIG_ICONV
1056                     iconv_t cd = iconv_open("UTF-8", avctx->sub_charenc);
1057                     if (cd == (iconv_t)-1) {
1058                         ret = AVERROR(errno);
1059                         av_log(avctx, AV_LOG_ERROR, "Unable to open iconv context "
1060                                "with input character encoding \"%s\"\n", avctx->sub_charenc);
1061                         goto free_and_end;
1062                     }
1063                     iconv_close(cd);
1064 #else
1065                     av_log(avctx, AV_LOG_ERROR, "Character encoding subtitles "
1066                            "conversion needs a libavcodec built with iconv support "
1067                            "for this codec\n");
1068                     ret = AVERROR(ENOSYS);
1069                     goto free_and_end;
1070 #endif
1071                 }
1072             }
1073         }
1074
1075 #if FF_API_AVCTX_TIMEBASE
1076         if (avctx->framerate.num > 0 && avctx->framerate.den > 0)
1077             avctx->time_base = av_inv_q(av_mul_q(avctx->framerate, (AVRational){avctx->ticks_per_frame, 1}));
1078 #endif
1079     }
1080     if (codec->priv_data_size > 0 && avctx->priv_data && codec->priv_class) {
1081         av_assert0(*(const AVClass **)avctx->priv_data == codec->priv_class);
1082     }
1083
1084 end:
1085     ff_unlock_avcodec(codec);
1086     if (options) {
1087         av_dict_free(options);
1088         *options = tmp;
1089     }
1090
1091     return ret;
1092 free_and_end:
1093     if (avctx->codec &&
1094         (avctx->codec->caps_internal & FF_CODEC_CAP_INIT_CLEANUP))
1095         avctx->codec->close(avctx);
1096
1097     if (codec->priv_class && codec->priv_data_size)
1098         av_opt_free(avctx->priv_data);
1099     av_opt_free(avctx);
1100
1101 #if FF_API_CODED_FRAME
1102 FF_DISABLE_DEPRECATION_WARNINGS
1103     av_frame_free(&avctx->coded_frame);
1104 FF_ENABLE_DEPRECATION_WARNINGS
1105 #endif
1106
1107     av_dict_free(&tmp);
1108     av_freep(&avctx->priv_data);
1109     if (avctx->internal) {
1110         av_frame_free(&avctx->internal->to_free);
1111         av_frame_free(&avctx->internal->buffer_frame);
1112         av_packet_free(&avctx->internal->buffer_pkt);
1113         av_freep(&avctx->internal->pool);
1114     }
1115     av_freep(&avctx->internal);
1116     avctx->codec = NULL;
1117     goto end;
1118 }
1119
1120 void avsubtitle_free(AVSubtitle *sub)
1121 {
1122     int i;
1123
1124     for (i = 0; i < sub->num_rects; i++) {
1125         av_freep(&sub->rects[i]->data[0]);
1126         av_freep(&sub->rects[i]->data[1]);
1127         av_freep(&sub->rects[i]->data[2]);
1128         av_freep(&sub->rects[i]->data[3]);
1129         av_freep(&sub->rects[i]->text);
1130         av_freep(&sub->rects[i]->ass);
1131         av_freep(&sub->rects[i]);
1132     }
1133
1134     av_freep(&sub->rects);
1135
1136     memset(sub, 0, sizeof(AVSubtitle));
1137 }
1138
1139 av_cold int avcodec_close(AVCodecContext *avctx)
1140 {
1141     int i;
1142
1143     if (!avctx)
1144         return 0;
1145
1146     if (avcodec_is_open(avctx)) {
1147         FramePool *pool = avctx->internal->pool;
1148         if (CONFIG_FRAME_THREAD_ENCODER &&
1149             avctx->internal->frame_thread_encoder && avctx->thread_count > 1) {
1150             ff_frame_thread_encoder_free(avctx);
1151         }
1152         if (HAVE_THREADS && avctx->internal->thread_ctx)
1153             ff_thread_free(avctx);
1154         if (avctx->codec && avctx->codec->close)
1155             avctx->codec->close(avctx);
1156         avctx->internal->byte_buffer_size = 0;
1157         av_freep(&avctx->internal->byte_buffer);
1158         av_frame_free(&avctx->internal->to_free);
1159         av_frame_free(&avctx->internal->buffer_frame);
1160         av_packet_free(&avctx->internal->buffer_pkt);
1161         for (i = 0; i < FF_ARRAY_ELEMS(pool->pools); i++)
1162             av_buffer_pool_uninit(&pool->pools[i]);
1163         av_freep(&avctx->internal->pool);
1164
1165         if (avctx->hwaccel && avctx->hwaccel->uninit)
1166             avctx->hwaccel->uninit(avctx);
1167         av_freep(&avctx->internal->hwaccel_priv_data);
1168
1169         av_freep(&avctx->internal);
1170     }
1171
1172     for (i = 0; i < avctx->nb_coded_side_data; i++)
1173         av_freep(&avctx->coded_side_data[i].data);
1174     av_freep(&avctx->coded_side_data);
1175     avctx->nb_coded_side_data = 0;
1176
1177     av_buffer_unref(&avctx->hw_frames_ctx);
1178     av_buffer_unref(&avctx->hw_device_ctx);
1179
1180     if (avctx->priv_data && avctx->codec && avctx->codec->priv_class)
1181         av_opt_free(avctx->priv_data);
1182     av_opt_free(avctx);
1183     av_freep(&avctx->priv_data);
1184     if (av_codec_is_encoder(avctx->codec)) {
1185         av_freep(&avctx->extradata);
1186 #if FF_API_CODED_FRAME
1187 FF_DISABLE_DEPRECATION_WARNINGS
1188         av_frame_free(&avctx->coded_frame);
1189 FF_ENABLE_DEPRECATION_WARNINGS
1190 #endif
1191     }
1192     avctx->codec = NULL;
1193     avctx->active_thread_type = 0;
1194
1195     return 0;
1196 }
1197
1198 static enum AVCodecID remap_deprecated_codec_id(enum AVCodecID id)
1199 {
1200     switch(id){
1201         //This is for future deprecatec codec ids, its empty since
1202         //last major bump but will fill up again over time, please don't remove it
1203         default                                         : return id;
1204     }
1205 }
1206
1207 static AVCodec *find_encdec(enum AVCodecID id, int encoder)
1208 {
1209     AVCodec *p, *experimental = NULL;
1210     p = first_avcodec;
1211     id= remap_deprecated_codec_id(id);
1212     while (p) {
1213         if ((encoder ? av_codec_is_encoder(p) : av_codec_is_decoder(p)) &&
1214             p->id == id) {
1215             if (p->capabilities & AV_CODEC_CAP_EXPERIMENTAL && !experimental) {
1216                 experimental = p;
1217             } else
1218                 return p;
1219         }
1220         p = p->next;
1221     }
1222     return experimental;
1223 }
1224
1225 AVCodec *avcodec_find_encoder(enum AVCodecID id)
1226 {
1227     return find_encdec(id, 1);
1228 }
1229
1230 AVCodec *avcodec_find_encoder_by_name(const char *name)
1231 {
1232     AVCodec *p;
1233     if (!name)
1234         return NULL;
1235     p = first_avcodec;
1236     while (p) {
1237         if (av_codec_is_encoder(p) && strcmp(name, p->name) == 0)
1238             return p;
1239         p = p->next;
1240     }
1241     return NULL;
1242 }
1243
1244 AVCodec *avcodec_find_decoder(enum AVCodecID id)
1245 {
1246     return find_encdec(id, 0);
1247 }
1248
1249 AVCodec *avcodec_find_decoder_by_name(const char *name)
1250 {
1251     AVCodec *p;
1252     if (!name)
1253         return NULL;
1254     p = first_avcodec;
1255     while (p) {
1256         if (av_codec_is_decoder(p) && strcmp(name, p->name) == 0)
1257             return p;
1258         p = p->next;
1259     }
1260     return NULL;
1261 }
1262
1263 const char *avcodec_get_name(enum AVCodecID id)
1264 {
1265     const AVCodecDescriptor *cd;
1266     AVCodec *codec;
1267
1268     if (id == AV_CODEC_ID_NONE)
1269         return "none";
1270     cd = avcodec_descriptor_get(id);
1271     if (cd)
1272         return cd->name;
1273     av_log(NULL, AV_LOG_WARNING, "Codec 0x%x is not in the full list.\n", id);
1274     codec = avcodec_find_decoder(id);
1275     if (codec)
1276         return codec->name;
1277     codec = avcodec_find_encoder(id);
1278     if (codec)
1279         return codec->name;
1280     return "unknown_codec";
1281 }
1282
1283 size_t av_get_codec_tag_string(char *buf, size_t buf_size, unsigned int codec_tag)
1284 {
1285     int i, len, ret = 0;
1286
1287 #define TAG_PRINT(x)                                              \
1288     (((x) >= '0' && (x) <= '9') ||                                \
1289      ((x) >= 'a' && (x) <= 'z') || ((x) >= 'A' && (x) <= 'Z') ||  \
1290      ((x) == '.' || (x) == ' ' || (x) == '-' || (x) == '_'))
1291
1292     for (i = 0; i < 4; i++) {
1293         len = snprintf(buf, buf_size,
1294                        TAG_PRINT(codec_tag & 0xFF) ? "%c" : "[%d]", codec_tag & 0xFF);
1295         buf        += len;
1296         buf_size    = buf_size > len ? buf_size - len : 0;
1297         ret        += len;
1298         codec_tag >>= 8;
1299     }
1300     return ret;
1301 }
1302
1303 void avcodec_string(char *buf, int buf_size, AVCodecContext *enc, int encode)
1304 {
1305     const char *codec_type;
1306     const char *codec_name;
1307     const char *profile = NULL;
1308     int64_t bitrate;
1309     int new_line = 0;
1310     AVRational display_aspect_ratio;
1311     const char *separator = enc->dump_separator ? (const char *)enc->dump_separator : ", ";
1312
1313     if (!buf || buf_size <= 0)
1314         return;
1315     codec_type = av_get_media_type_string(enc->codec_type);
1316     codec_name = avcodec_get_name(enc->codec_id);
1317     profile = avcodec_profile_name(enc->codec_id, enc->profile);
1318
1319     snprintf(buf, buf_size, "%s: %s", codec_type ? codec_type : "unknown",
1320              codec_name);
1321     buf[0] ^= 'a' ^ 'A'; /* first letter in uppercase */
1322
1323     if (enc->codec && strcmp(enc->codec->name, codec_name))
1324         snprintf(buf + strlen(buf), buf_size - strlen(buf), " (%s)", enc->codec->name);
1325
1326     if (profile)
1327         snprintf(buf + strlen(buf), buf_size - strlen(buf), " (%s)", profile);
1328     if (   enc->codec_type == AVMEDIA_TYPE_VIDEO
1329         && av_log_get_level() >= AV_LOG_VERBOSE
1330         && enc->refs)
1331         snprintf(buf + strlen(buf), buf_size - strlen(buf),
1332                  ", %d reference frame%s",
1333                  enc->refs, enc->refs > 1 ? "s" : "");
1334
1335     if (enc->codec_tag)
1336         snprintf(buf + strlen(buf), buf_size - strlen(buf), " (%s / 0x%04X)",
1337                  av_fourcc2str(enc->codec_tag), enc->codec_tag);
1338
1339     switch (enc->codec_type) {
1340     case AVMEDIA_TYPE_VIDEO:
1341         {
1342             char detail[256] = "(";
1343
1344             av_strlcat(buf, separator, buf_size);
1345
1346             snprintf(buf + strlen(buf), buf_size - strlen(buf),
1347                  "%s", enc->pix_fmt == AV_PIX_FMT_NONE ? "none" :
1348                      av_get_pix_fmt_name(enc->pix_fmt));
1349             if (enc->bits_per_raw_sample && enc->pix_fmt != AV_PIX_FMT_NONE &&
1350                 enc->bits_per_raw_sample < av_pix_fmt_desc_get(enc->pix_fmt)->comp[0].depth)
1351                 av_strlcatf(detail, sizeof(detail), "%d bpc, ", enc->bits_per_raw_sample);
1352             if (enc->color_range != AVCOL_RANGE_UNSPECIFIED)
1353                 av_strlcatf(detail, sizeof(detail), "%s, ",
1354                             av_color_range_name(enc->color_range));
1355
1356             if (enc->colorspace != AVCOL_SPC_UNSPECIFIED ||
1357                 enc->color_primaries != AVCOL_PRI_UNSPECIFIED ||
1358                 enc->color_trc != AVCOL_TRC_UNSPECIFIED) {
1359                 if (enc->colorspace != (int)enc->color_primaries ||
1360                     enc->colorspace != (int)enc->color_trc) {
1361                     new_line = 1;
1362                     av_strlcatf(detail, sizeof(detail), "%s/%s/%s, ",
1363                                 av_color_space_name(enc->colorspace),
1364                                 av_color_primaries_name(enc->color_primaries),
1365                                 av_color_transfer_name(enc->color_trc));
1366                 } else
1367                     av_strlcatf(detail, sizeof(detail), "%s, ",
1368                                 av_get_colorspace_name(enc->colorspace));
1369             }
1370
1371             if (enc->field_order != AV_FIELD_UNKNOWN) {
1372                 const char *field_order = "progressive";
1373                 if (enc->field_order == AV_FIELD_TT)
1374                     field_order = "top first";
1375                 else if (enc->field_order == AV_FIELD_BB)
1376                     field_order = "bottom first";
1377                 else if (enc->field_order == AV_FIELD_TB)
1378                     field_order = "top coded first (swapped)";
1379                 else if (enc->field_order == AV_FIELD_BT)
1380                     field_order = "bottom coded first (swapped)";
1381
1382                 av_strlcatf(detail, sizeof(detail), "%s, ", field_order);
1383             }
1384
1385             if (av_log_get_level() >= AV_LOG_VERBOSE &&
1386                 enc->chroma_sample_location != AVCHROMA_LOC_UNSPECIFIED)
1387                 av_strlcatf(detail, sizeof(detail), "%s, ",
1388                             av_chroma_location_name(enc->chroma_sample_location));
1389
1390             if (strlen(detail) > 1) {
1391                 detail[strlen(detail) - 2] = 0;
1392                 av_strlcatf(buf, buf_size, "%s)", detail);
1393             }
1394         }
1395
1396         if (enc->width) {
1397             av_strlcat(buf, new_line ? separator : ", ", buf_size);
1398
1399             snprintf(buf + strlen(buf), buf_size - strlen(buf),
1400                      "%dx%d",
1401                      enc->width, enc->height);
1402
1403             if (av_log_get_level() >= AV_LOG_VERBOSE &&
1404                 (enc->width != enc->coded_width ||
1405                  enc->height != enc->coded_height))
1406                 snprintf(buf + strlen(buf), buf_size - strlen(buf),
1407                          " (%dx%d)", enc->coded_width, enc->coded_height);
1408
1409             if (enc->sample_aspect_ratio.num) {
1410                 av_reduce(&display_aspect_ratio.num, &display_aspect_ratio.den,
1411                           enc->width * (int64_t)enc->sample_aspect_ratio.num,
1412                           enc->height * (int64_t)enc->sample_aspect_ratio.den,
1413                           1024 * 1024);
1414                 snprintf(buf + strlen(buf), buf_size - strlen(buf),
1415                          " [SAR %d:%d DAR %d:%d]",
1416                          enc->sample_aspect_ratio.num, enc->sample_aspect_ratio.den,
1417                          display_aspect_ratio.num, display_aspect_ratio.den);
1418             }
1419             if (av_log_get_level() >= AV_LOG_DEBUG) {
1420                 int g = av_gcd(enc->time_base.num, enc->time_base.den);
1421                 snprintf(buf + strlen(buf), buf_size - strlen(buf),
1422                          ", %d/%d",
1423                          enc->time_base.num / g, enc->time_base.den / g);
1424             }
1425         }
1426         if (encode) {
1427             snprintf(buf + strlen(buf), buf_size - strlen(buf),
1428                      ", q=%d-%d", enc->qmin, enc->qmax);
1429         } else {
1430             if (enc->properties & FF_CODEC_PROPERTY_CLOSED_CAPTIONS)
1431                 snprintf(buf + strlen(buf), buf_size - strlen(buf),
1432                          ", Closed Captions");
1433             if (enc->properties & FF_CODEC_PROPERTY_LOSSLESS)
1434                 snprintf(buf + strlen(buf), buf_size - strlen(buf),
1435                          ", lossless");
1436         }
1437         break;
1438     case AVMEDIA_TYPE_AUDIO:
1439         av_strlcat(buf, separator, buf_size);
1440
1441         if (enc->sample_rate) {
1442             snprintf(buf + strlen(buf), buf_size - strlen(buf),
1443                      "%d Hz, ", enc->sample_rate);
1444         }
1445         av_get_channel_layout_string(buf + strlen(buf), buf_size - strlen(buf), enc->channels, enc->channel_layout);
1446         if (enc->sample_fmt != AV_SAMPLE_FMT_NONE) {
1447             snprintf(buf + strlen(buf), buf_size - strlen(buf),
1448                      ", %s", av_get_sample_fmt_name(enc->sample_fmt));
1449         }
1450         if (   enc->bits_per_raw_sample > 0
1451             && enc->bits_per_raw_sample != av_get_bytes_per_sample(enc->sample_fmt) * 8)
1452             snprintf(buf + strlen(buf), buf_size - strlen(buf),
1453                      " (%d bit)", enc->bits_per_raw_sample);
1454         if (av_log_get_level() >= AV_LOG_VERBOSE) {
1455             if (enc->initial_padding)
1456                 snprintf(buf + strlen(buf), buf_size - strlen(buf),
1457                          ", delay %d", enc->initial_padding);
1458             if (enc->trailing_padding)
1459                 snprintf(buf + strlen(buf), buf_size - strlen(buf),
1460                          ", padding %d", enc->trailing_padding);
1461         }
1462         break;
1463     case AVMEDIA_TYPE_DATA:
1464         if (av_log_get_level() >= AV_LOG_DEBUG) {
1465             int g = av_gcd(enc->time_base.num, enc->time_base.den);
1466             if (g)
1467                 snprintf(buf + strlen(buf), buf_size - strlen(buf),
1468                          ", %d/%d",
1469                          enc->time_base.num / g, enc->time_base.den / g);
1470         }
1471         break;
1472     case AVMEDIA_TYPE_SUBTITLE:
1473         if (enc->width)
1474             snprintf(buf + strlen(buf), buf_size - strlen(buf),
1475                      ", %dx%d", enc->width, enc->height);
1476         break;
1477     default:
1478         return;
1479     }
1480     if (encode) {
1481         if (enc->flags & AV_CODEC_FLAG_PASS1)
1482             snprintf(buf + strlen(buf), buf_size - strlen(buf),
1483                      ", pass 1");
1484         if (enc->flags & AV_CODEC_FLAG_PASS2)
1485             snprintf(buf + strlen(buf), buf_size - strlen(buf),
1486                      ", pass 2");
1487     }
1488     bitrate = get_bit_rate(enc);
1489     if (bitrate != 0) {
1490         snprintf(buf + strlen(buf), buf_size - strlen(buf),
1491                  ", %"PRId64" kb/s", bitrate / 1000);
1492     } else if (enc->rc_max_rate > 0) {
1493         snprintf(buf + strlen(buf), buf_size - strlen(buf),
1494                  ", max. %"PRId64" kb/s", (int64_t)enc->rc_max_rate / 1000);
1495     }
1496 }
1497
1498 const char *av_get_profile_name(const AVCodec *codec, int profile)
1499 {
1500     const AVProfile *p;
1501     if (profile == FF_PROFILE_UNKNOWN || !codec->profiles)
1502         return NULL;
1503
1504     for (p = codec->profiles; p->profile != FF_PROFILE_UNKNOWN; p++)
1505         if (p->profile == profile)
1506             return p->name;
1507
1508     return NULL;
1509 }
1510
1511 const char *avcodec_profile_name(enum AVCodecID codec_id, int profile)
1512 {
1513     const AVCodecDescriptor *desc = avcodec_descriptor_get(codec_id);
1514     const AVProfile *p;
1515
1516     if (profile == FF_PROFILE_UNKNOWN || !desc || !desc->profiles)
1517         return NULL;
1518
1519     for (p = desc->profiles; p->profile != FF_PROFILE_UNKNOWN; p++)
1520         if (p->profile == profile)
1521             return p->name;
1522
1523     return NULL;
1524 }
1525
1526 unsigned avcodec_version(void)
1527 {
1528 //    av_assert0(AV_CODEC_ID_V410==164);
1529     av_assert0(AV_CODEC_ID_PCM_S8_PLANAR==65563);
1530     av_assert0(AV_CODEC_ID_ADPCM_G722==69660);
1531 //     av_assert0(AV_CODEC_ID_BMV_AUDIO==86071);
1532     av_assert0(AV_CODEC_ID_SRT==94216);
1533     av_assert0(LIBAVCODEC_VERSION_MICRO >= 100);
1534
1535     return LIBAVCODEC_VERSION_INT;
1536 }
1537
1538 const char *avcodec_configuration(void)
1539 {
1540     return FFMPEG_CONFIGURATION;
1541 }
1542
1543 const char *avcodec_license(void)
1544 {
1545 #define LICENSE_PREFIX "libavcodec license: "
1546     return LICENSE_PREFIX FFMPEG_LICENSE + sizeof(LICENSE_PREFIX) - 1;
1547 }
1548
1549 int av_get_exact_bits_per_sample(enum AVCodecID codec_id)
1550 {
1551     switch (codec_id) {
1552     case AV_CODEC_ID_8SVX_EXP:
1553     case AV_CODEC_ID_8SVX_FIB:
1554     case AV_CODEC_ID_ADPCM_CT:
1555     case AV_CODEC_ID_ADPCM_IMA_APC:
1556     case AV_CODEC_ID_ADPCM_IMA_EA_SEAD:
1557     case AV_CODEC_ID_ADPCM_IMA_OKI:
1558     case AV_CODEC_ID_ADPCM_IMA_WS:
1559     case AV_CODEC_ID_ADPCM_G722:
1560     case AV_CODEC_ID_ADPCM_YAMAHA:
1561     case AV_CODEC_ID_ADPCM_AICA:
1562         return 4;
1563     case AV_CODEC_ID_DSD_LSBF:
1564     case AV_CODEC_ID_DSD_MSBF:
1565     case AV_CODEC_ID_DSD_LSBF_PLANAR:
1566     case AV_CODEC_ID_DSD_MSBF_PLANAR:
1567     case AV_CODEC_ID_PCM_ALAW:
1568     case AV_CODEC_ID_PCM_MULAW:
1569     case AV_CODEC_ID_PCM_S8:
1570     case AV_CODEC_ID_PCM_S8_PLANAR:
1571     case AV_CODEC_ID_PCM_U8:
1572     case AV_CODEC_ID_PCM_ZORK:
1573     case AV_CODEC_ID_SDX2_DPCM:
1574         return 8;
1575     case AV_CODEC_ID_PCM_S16BE:
1576     case AV_CODEC_ID_PCM_S16BE_PLANAR:
1577     case AV_CODEC_ID_PCM_S16LE:
1578     case AV_CODEC_ID_PCM_S16LE_PLANAR:
1579     case AV_CODEC_ID_PCM_U16BE:
1580     case AV_CODEC_ID_PCM_U16LE:
1581         return 16;
1582     case AV_CODEC_ID_PCM_S24DAUD:
1583     case AV_CODEC_ID_PCM_S24BE:
1584     case AV_CODEC_ID_PCM_S24LE:
1585     case AV_CODEC_ID_PCM_S24LE_PLANAR:
1586     case AV_CODEC_ID_PCM_U24BE:
1587     case AV_CODEC_ID_PCM_U24LE:
1588         return 24;
1589     case AV_CODEC_ID_PCM_S32BE:
1590     case AV_CODEC_ID_PCM_S32LE:
1591     case AV_CODEC_ID_PCM_S32LE_PLANAR:
1592     case AV_CODEC_ID_PCM_U32BE:
1593     case AV_CODEC_ID_PCM_U32LE:
1594     case AV_CODEC_ID_PCM_F32BE:
1595     case AV_CODEC_ID_PCM_F32LE:
1596     case AV_CODEC_ID_PCM_F24LE:
1597     case AV_CODEC_ID_PCM_F16LE:
1598         return 32;
1599     case AV_CODEC_ID_PCM_F64BE:
1600     case AV_CODEC_ID_PCM_F64LE:
1601     case AV_CODEC_ID_PCM_S64BE:
1602     case AV_CODEC_ID_PCM_S64LE:
1603         return 64;
1604     default:
1605         return 0;
1606     }
1607 }
1608
1609 enum AVCodecID av_get_pcm_codec(enum AVSampleFormat fmt, int be)
1610 {
1611     static const enum AVCodecID map[AV_SAMPLE_FMT_NB][2] = {
1612         [AV_SAMPLE_FMT_U8  ] = { AV_CODEC_ID_PCM_U8,    AV_CODEC_ID_PCM_U8    },
1613         [AV_SAMPLE_FMT_S16 ] = { AV_CODEC_ID_PCM_S16LE, AV_CODEC_ID_PCM_S16BE },
1614         [AV_SAMPLE_FMT_S32 ] = { AV_CODEC_ID_PCM_S32LE, AV_CODEC_ID_PCM_S32BE },
1615         [AV_SAMPLE_FMT_FLT ] = { AV_CODEC_ID_PCM_F32LE, AV_CODEC_ID_PCM_F32BE },
1616         [AV_SAMPLE_FMT_DBL ] = { AV_CODEC_ID_PCM_F64LE, AV_CODEC_ID_PCM_F64BE },
1617         [AV_SAMPLE_FMT_U8P ] = { AV_CODEC_ID_PCM_U8,    AV_CODEC_ID_PCM_U8    },
1618         [AV_SAMPLE_FMT_S16P] = { AV_CODEC_ID_PCM_S16LE, AV_CODEC_ID_PCM_S16BE },
1619         [AV_SAMPLE_FMT_S32P] = { AV_CODEC_ID_PCM_S32LE, AV_CODEC_ID_PCM_S32BE },
1620         [AV_SAMPLE_FMT_S64P] = { AV_CODEC_ID_PCM_S64LE, AV_CODEC_ID_PCM_S64BE },
1621         [AV_SAMPLE_FMT_FLTP] = { AV_CODEC_ID_PCM_F32LE, AV_CODEC_ID_PCM_F32BE },
1622         [AV_SAMPLE_FMT_DBLP] = { AV_CODEC_ID_PCM_F64LE, AV_CODEC_ID_PCM_F64BE },
1623     };
1624     if (fmt < 0 || fmt >= AV_SAMPLE_FMT_NB)
1625         return AV_CODEC_ID_NONE;
1626     if (be < 0 || be > 1)
1627         be = AV_NE(1, 0);
1628     return map[fmt][be];
1629 }
1630
1631 int av_get_bits_per_sample(enum AVCodecID codec_id)
1632 {
1633     switch (codec_id) {
1634     case AV_CODEC_ID_ADPCM_SBPRO_2:
1635         return 2;
1636     case AV_CODEC_ID_ADPCM_SBPRO_3:
1637         return 3;
1638     case AV_CODEC_ID_ADPCM_SBPRO_4:
1639     case AV_CODEC_ID_ADPCM_IMA_WAV:
1640     case AV_CODEC_ID_ADPCM_IMA_QT:
1641     case AV_CODEC_ID_ADPCM_SWF:
1642     case AV_CODEC_ID_ADPCM_MS:
1643         return 4;
1644     default:
1645         return av_get_exact_bits_per_sample(codec_id);
1646     }
1647 }
1648
1649 static int get_audio_frame_duration(enum AVCodecID id, int sr, int ch, int ba,
1650                                     uint32_t tag, int bits_per_coded_sample, int64_t bitrate,
1651                                     uint8_t * extradata, int frame_size, int frame_bytes)
1652 {
1653     int bps = av_get_exact_bits_per_sample(id);
1654     int framecount = (ba > 0 && frame_bytes / ba > 0) ? frame_bytes / ba : 1;
1655
1656     /* codecs with an exact constant bits per sample */
1657     if (bps > 0 && ch > 0 && frame_bytes > 0 && ch < 32768 && bps < 32768)
1658         return (frame_bytes * 8LL) / (bps * ch);
1659     bps = bits_per_coded_sample;
1660
1661     /* codecs with a fixed packet duration */
1662     switch (id) {
1663     case AV_CODEC_ID_ADPCM_ADX:    return   32;
1664     case AV_CODEC_ID_ADPCM_IMA_QT: return   64;
1665     case AV_CODEC_ID_ADPCM_EA_XAS: return  128;
1666     case AV_CODEC_ID_AMR_NB:
1667     case AV_CODEC_ID_EVRC:
1668     case AV_CODEC_ID_GSM:
1669     case AV_CODEC_ID_QCELP:
1670     case AV_CODEC_ID_RA_288:       return  160;
1671     case AV_CODEC_ID_AMR_WB:
1672     case AV_CODEC_ID_GSM_MS:       return  320;
1673     case AV_CODEC_ID_MP1:          return  384;
1674     case AV_CODEC_ID_ATRAC1:       return  512;
1675     case AV_CODEC_ID_ATRAC3:       return 1024 * framecount;
1676     case AV_CODEC_ID_ATRAC3P:      return 2048;
1677     case AV_CODEC_ID_MP2:
1678     case AV_CODEC_ID_MUSEPACK7:    return 1152;
1679     case AV_CODEC_ID_AC3:          return 1536;
1680     }
1681
1682     if (sr > 0) {
1683         /* calc from sample rate */
1684         if (id == AV_CODEC_ID_TTA)
1685             return 256 * sr / 245;
1686         else if (id == AV_CODEC_ID_DST)
1687             return 588 * sr / 44100;
1688
1689         if (ch > 0) {
1690             /* calc from sample rate and channels */
1691             if (id == AV_CODEC_ID_BINKAUDIO_DCT)
1692                 return (480 << (sr / 22050)) / ch;
1693         }
1694     }
1695
1696     if (ba > 0) {
1697         /* calc from block_align */
1698         if (id == AV_CODEC_ID_SIPR) {
1699             switch (ba) {
1700             case 20: return 160;
1701             case 19: return 144;
1702             case 29: return 288;
1703             case 37: return 480;
1704             }
1705         } else if (id == AV_CODEC_ID_ILBC) {
1706             switch (ba) {
1707             case 38: return 160;
1708             case 50: return 240;
1709             }
1710         }
1711     }
1712
1713     if (frame_bytes > 0) {
1714         /* calc from frame_bytes only */
1715         if (id == AV_CODEC_ID_TRUESPEECH)
1716             return 240 * (frame_bytes / 32);
1717         if (id == AV_CODEC_ID_NELLYMOSER)
1718             return 256 * (frame_bytes / 64);
1719         if (id == AV_CODEC_ID_RA_144)
1720             return 160 * (frame_bytes / 20);
1721         if (id == AV_CODEC_ID_G723_1)
1722             return 240 * (frame_bytes / 24);
1723
1724         if (bps > 0) {
1725             /* calc from frame_bytes and bits_per_coded_sample */
1726             if (id == AV_CODEC_ID_ADPCM_G726)
1727                 return frame_bytes * 8 / bps;
1728         }
1729
1730         if (ch > 0 && ch < INT_MAX/16) {
1731             /* calc from frame_bytes and channels */
1732             switch (id) {
1733             case AV_CODEC_ID_ADPCM_AFC:
1734                 return frame_bytes / (9 * ch) * 16;
1735             case AV_CODEC_ID_ADPCM_PSX:
1736             case AV_CODEC_ID_ADPCM_DTK:
1737                 return frame_bytes / (16 * ch) * 28;
1738             case AV_CODEC_ID_ADPCM_4XM:
1739             case AV_CODEC_ID_ADPCM_IMA_DAT4:
1740             case AV_CODEC_ID_ADPCM_IMA_ISS:
1741                 return (frame_bytes - 4 * ch) * 2 / ch;
1742             case AV_CODEC_ID_ADPCM_IMA_SMJPEG:
1743                 return (frame_bytes - 4) * 2 / ch;
1744             case AV_CODEC_ID_ADPCM_IMA_AMV:
1745                 return (frame_bytes - 8) * 2 / ch;
1746             case AV_CODEC_ID_ADPCM_THP:
1747             case AV_CODEC_ID_ADPCM_THP_LE:
1748                 if (extradata)
1749                     return frame_bytes * 14 / (8 * ch);
1750                 break;
1751             case AV_CODEC_ID_ADPCM_XA:
1752                 return (frame_bytes / 128) * 224 / ch;
1753             case AV_CODEC_ID_INTERPLAY_DPCM:
1754                 return (frame_bytes - 6 - ch) / ch;
1755             case AV_CODEC_ID_ROQ_DPCM:
1756                 return (frame_bytes - 8) / ch;
1757             case AV_CODEC_ID_XAN_DPCM:
1758                 return (frame_bytes - 2 * ch) / ch;
1759             case AV_CODEC_ID_MACE3:
1760                 return 3 * frame_bytes / ch;
1761             case AV_CODEC_ID_MACE6:
1762                 return 6 * frame_bytes / ch;
1763             case AV_CODEC_ID_PCM_LXF:
1764                 return 2 * (frame_bytes / (5 * ch));
1765             case AV_CODEC_ID_IAC:
1766             case AV_CODEC_ID_IMC:
1767                 return 4 * frame_bytes / ch;
1768             }
1769
1770             if (tag) {
1771                 /* calc from frame_bytes, channels, and codec_tag */
1772                 if (id == AV_CODEC_ID_SOL_DPCM) {
1773                     if (tag == 3)
1774                         return frame_bytes / ch;
1775                     else
1776                         return frame_bytes * 2 / ch;
1777                 }
1778             }
1779
1780             if (ba > 0) {
1781                 /* calc from frame_bytes, channels, and block_align */
1782                 int blocks = frame_bytes / ba;
1783                 switch (id) {
1784                 case AV_CODEC_ID_ADPCM_IMA_WAV:
1785                     if (bps < 2 || bps > 5)
1786                         return 0;
1787                     return blocks * (1 + (ba - 4 * ch) / (bps * ch) * 8);
1788                 case AV_CODEC_ID_ADPCM_IMA_DK3:
1789                     return blocks * (((ba - 16) * 2 / 3 * 4) / ch);
1790                 case AV_CODEC_ID_ADPCM_IMA_DK4:
1791                     return blocks * (1 + (ba - 4 * ch) * 2 / ch);
1792                 case AV_CODEC_ID_ADPCM_IMA_RAD:
1793                     return blocks * ((ba - 4 * ch) * 2 / ch);
1794                 case AV_CODEC_ID_ADPCM_MS:
1795                     return blocks * (2 + (ba - 7 * ch) * 2 / ch);
1796                 case AV_CODEC_ID_ADPCM_MTAF:
1797                     return blocks * (ba - 16) * 2 / ch;
1798                 }
1799             }
1800
1801             if (bps > 0) {
1802                 /* calc from frame_bytes, channels, and bits_per_coded_sample */
1803                 switch (id) {
1804                 case AV_CODEC_ID_PCM_DVD:
1805                     if(bps<4)
1806                         return 0;
1807                     return 2 * (frame_bytes / ((bps * 2 / 8) * ch));
1808                 case AV_CODEC_ID_PCM_BLURAY:
1809                     if(bps<4)
1810                         return 0;
1811                     return frame_bytes / ((FFALIGN(ch, 2) * bps) / 8);
1812                 case AV_CODEC_ID_S302M:
1813                     return 2 * (frame_bytes / ((bps + 4) / 4)) / ch;
1814                 }
1815             }
1816         }
1817     }
1818
1819     /* Fall back on using frame_size */
1820     if (frame_size > 1 && frame_bytes)
1821         return frame_size;
1822
1823     //For WMA we currently have no other means to calculate duration thus we
1824     //do it here by assuming CBR, which is true for all known cases.
1825     if (bitrate > 0 && frame_bytes > 0 && sr > 0 && ba > 1) {
1826         if (id == AV_CODEC_ID_WMAV1 || id == AV_CODEC_ID_WMAV2)
1827             return  (frame_bytes * 8LL * sr) / bitrate;
1828     }
1829
1830     return 0;
1831 }
1832
1833 int av_get_audio_frame_duration(AVCodecContext *avctx, int frame_bytes)
1834 {
1835     return get_audio_frame_duration(avctx->codec_id, avctx->sample_rate,
1836                                     avctx->channels, avctx->block_align,
1837                                     avctx->codec_tag, avctx->bits_per_coded_sample,
1838                                     avctx->bit_rate, avctx->extradata, avctx->frame_size,
1839                                     frame_bytes);
1840 }
1841
1842 int av_get_audio_frame_duration2(AVCodecParameters *par, int frame_bytes)
1843 {
1844     return get_audio_frame_duration(par->codec_id, par->sample_rate,
1845                                     par->channels, par->block_align,
1846                                     par->codec_tag, par->bits_per_coded_sample,
1847                                     par->bit_rate, par->extradata, par->frame_size,
1848                                     frame_bytes);
1849 }
1850
1851 #if !HAVE_THREADS
1852 int ff_thread_init(AVCodecContext *s)
1853 {
1854     return -1;
1855 }
1856
1857 #endif
1858
1859 unsigned int av_xiphlacing(unsigned char *s, unsigned int v)
1860 {
1861     unsigned int n = 0;
1862
1863     while (v >= 0xff) {
1864         *s++ = 0xff;
1865         v -= 0xff;
1866         n++;
1867     }
1868     *s = v;
1869     n++;
1870     return n;
1871 }
1872
1873 int ff_match_2uint16(const uint16_t(*tab)[2], int size, int a, int b)
1874 {
1875     int i;
1876     for (i = 0; i < size && !(tab[i][0] == a && tab[i][1] == b); i++) ;
1877     return i;
1878 }
1879
1880 #if FF_API_MISSING_SAMPLE
1881 FF_DISABLE_DEPRECATION_WARNINGS
1882 void av_log_missing_feature(void *avc, const char *feature, int want_sample)
1883 {
1884     av_log(avc, AV_LOG_WARNING, "%s is not implemented. Update your FFmpeg "
1885             "version to the newest one from Git. If the problem still "
1886             "occurs, it means that your file has a feature which has not "
1887             "been implemented.\n", feature);
1888     if(want_sample)
1889         av_log_ask_for_sample(avc, NULL);
1890 }
1891
1892 void av_log_ask_for_sample(void *avc, const char *msg, ...)
1893 {
1894     va_list argument_list;
1895
1896     va_start(argument_list, msg);
1897
1898     if (msg)
1899         av_vlog(avc, AV_LOG_WARNING, msg, argument_list);
1900     av_log(avc, AV_LOG_WARNING, "If you want to help, upload a sample "
1901             "of this file to ftp://upload.ffmpeg.org/incoming/ "
1902             "and contact the ffmpeg-devel mailing list. (ffmpeg-devel@ffmpeg.org)\n");
1903
1904     va_end(argument_list);
1905 }
1906 FF_ENABLE_DEPRECATION_WARNINGS
1907 #endif /* FF_API_MISSING_SAMPLE */
1908
1909 static AVHWAccel *first_hwaccel = NULL;
1910 static AVHWAccel **last_hwaccel = &first_hwaccel;
1911
1912 void av_register_hwaccel(AVHWAccel *hwaccel)
1913 {
1914     AVHWAccel **p = last_hwaccel;
1915     hwaccel->next = NULL;
1916     while(*p || avpriv_atomic_ptr_cas((void * volatile *)p, NULL, hwaccel))
1917         p = &(*p)->next;
1918     last_hwaccel = &hwaccel->next;
1919 }
1920
1921 AVHWAccel *av_hwaccel_next(const AVHWAccel *hwaccel)
1922 {
1923     return hwaccel ? hwaccel->next : first_hwaccel;
1924 }
1925
1926 int av_lockmgr_register(int (*cb)(void **mutex, enum AVLockOp op))
1927 {
1928     if (lockmgr_cb) {
1929         // There is no good way to rollback a failure to destroy the
1930         // mutex, so we ignore failures.
1931         lockmgr_cb(&codec_mutex,    AV_LOCK_DESTROY);
1932         lockmgr_cb(&avformat_mutex, AV_LOCK_DESTROY);
1933         lockmgr_cb     = NULL;
1934         codec_mutex    = NULL;
1935         avformat_mutex = NULL;
1936     }
1937
1938     if (cb) {
1939         void *new_codec_mutex    = NULL;
1940         void *new_avformat_mutex = NULL;
1941         int err;
1942         if (err = cb(&new_codec_mutex, AV_LOCK_CREATE)) {
1943             return err > 0 ? AVERROR_UNKNOWN : err;
1944         }
1945         if (err = cb(&new_avformat_mutex, AV_LOCK_CREATE)) {
1946             // Ignore failures to destroy the newly created mutex.
1947             cb(&new_codec_mutex, AV_LOCK_DESTROY);
1948             return err > 0 ? AVERROR_UNKNOWN : err;
1949         }
1950         lockmgr_cb     = cb;
1951         codec_mutex    = new_codec_mutex;
1952         avformat_mutex = new_avformat_mutex;
1953     }
1954
1955     return 0;
1956 }
1957
1958 int ff_lock_avcodec(AVCodecContext *log_ctx, const AVCodec *codec)
1959 {
1960     if (codec->caps_internal & FF_CODEC_CAP_INIT_THREADSAFE || !codec->init)
1961         return 0;
1962
1963     if (lockmgr_cb) {
1964         if ((*lockmgr_cb)(&codec_mutex, AV_LOCK_OBTAIN))
1965             return -1;
1966     }
1967
1968     if (avpriv_atomic_int_add_and_fetch(&entangled_thread_counter, 1) != 1) {
1969         av_log(log_ctx, AV_LOG_ERROR,
1970                "Insufficient thread locking. At least %d threads are "
1971                "calling avcodec_open2() at the same time right now.\n",
1972                entangled_thread_counter);
1973         if (!lockmgr_cb)
1974             av_log(log_ctx, AV_LOG_ERROR, "No lock manager is set, please see av_lockmgr_register()\n");
1975         ff_avcodec_locked = 1;
1976         ff_unlock_avcodec(codec);
1977         return AVERROR(EINVAL);
1978     }
1979     av_assert0(!ff_avcodec_locked);
1980     ff_avcodec_locked = 1;
1981     return 0;
1982 }
1983
1984 int ff_unlock_avcodec(const AVCodec *codec)
1985 {
1986     if (codec->caps_internal & FF_CODEC_CAP_INIT_THREADSAFE || !codec->init)
1987         return 0;
1988
1989     av_assert0(ff_avcodec_locked);
1990     ff_avcodec_locked = 0;
1991     avpriv_atomic_int_add_and_fetch(&entangled_thread_counter, -1);
1992     if (lockmgr_cb) {
1993         if ((*lockmgr_cb)(&codec_mutex, AV_LOCK_RELEASE))
1994             return -1;
1995     }
1996
1997     return 0;
1998 }
1999
2000 int avpriv_lock_avformat(void)
2001 {
2002     if (lockmgr_cb) {
2003         if ((*lockmgr_cb)(&avformat_mutex, AV_LOCK_OBTAIN))
2004             return -1;
2005     }
2006     return 0;
2007 }
2008
2009 int avpriv_unlock_avformat(void)
2010 {
2011     if (lockmgr_cb) {
2012         if ((*lockmgr_cb)(&avformat_mutex, AV_LOCK_RELEASE))
2013             return -1;
2014     }
2015     return 0;
2016 }
2017
2018 unsigned int avpriv_toupper4(unsigned int x)
2019 {
2020     return av_toupper(x & 0xFF) +
2021           (av_toupper((x >>  8) & 0xFF) << 8)  +
2022           (av_toupper((x >> 16) & 0xFF) << 16) +
2023 ((unsigned)av_toupper((x >> 24) & 0xFF) << 24);
2024 }
2025
2026 int ff_thread_ref_frame(ThreadFrame *dst, ThreadFrame *src)
2027 {
2028     int ret;
2029
2030     dst->owner[0] = src->owner[0];
2031     dst->owner[1] = src->owner[1];
2032
2033     ret = av_frame_ref(dst->f, src->f);
2034     if (ret < 0)
2035         return ret;
2036
2037     av_assert0(!dst->progress);
2038
2039     if (src->progress &&
2040         !(dst->progress = av_buffer_ref(src->progress))) {
2041         ff_thread_release_buffer(dst->owner[0], dst);
2042         return AVERROR(ENOMEM);
2043     }
2044
2045     return 0;
2046 }
2047
2048 #if !HAVE_THREADS
2049
2050 enum AVPixelFormat ff_thread_get_format(AVCodecContext *avctx, const enum AVPixelFormat *fmt)
2051 {
2052     return ff_get_format(avctx, fmt);
2053 }
2054
2055 int ff_thread_get_buffer(AVCodecContext *avctx, ThreadFrame *f, int flags)
2056 {
2057     f->owner[0] = f->owner[1] = avctx;
2058     return ff_get_buffer(avctx, f->f, flags);
2059 }
2060
2061 void ff_thread_release_buffer(AVCodecContext *avctx, ThreadFrame *f)
2062 {
2063     if (f->f)
2064         av_frame_unref(f->f);
2065 }
2066
2067 void ff_thread_finish_setup(AVCodecContext *avctx)
2068 {
2069 }
2070
2071 void ff_thread_report_progress(ThreadFrame *f, int progress, int field)
2072 {
2073 }
2074
2075 void ff_thread_await_progress(ThreadFrame *f, int progress, int field)
2076 {
2077 }
2078
2079 int ff_thread_can_start_frame(AVCodecContext *avctx)
2080 {
2081     return 1;
2082 }
2083
2084 int ff_alloc_entries(AVCodecContext *avctx, int count)
2085 {
2086     return 0;
2087 }
2088
2089 void ff_reset_entries(AVCodecContext *avctx)
2090 {
2091 }
2092
2093 void ff_thread_await_progress2(AVCodecContext *avctx, int field, int thread, int shift)
2094 {
2095 }
2096
2097 void ff_thread_report_progress2(AVCodecContext *avctx, int field, int thread, int n)
2098 {
2099 }
2100
2101 #endif
2102
2103 int avcodec_is_open(AVCodecContext *s)
2104 {
2105     return !!s->internal;
2106 }
2107
2108 int avpriv_bprint_to_extradata(AVCodecContext *avctx, struct AVBPrint *buf)
2109 {
2110     int ret;
2111     char *str;
2112
2113     ret = av_bprint_finalize(buf, &str);
2114     if (ret < 0)
2115         return ret;
2116     if (!av_bprint_is_complete(buf)) {
2117         av_free(str);
2118         return AVERROR(ENOMEM);
2119     }
2120
2121     avctx->extradata = str;
2122     /* Note: the string is NUL terminated (so extradata can be read as a
2123      * string), but the ending character is not accounted in the size (in
2124      * binary formats you are likely not supposed to mux that character). When
2125      * extradata is copied, it is also padded with AV_INPUT_BUFFER_PADDING_SIZE
2126      * zeros. */
2127     avctx->extradata_size = buf->len;
2128     return 0;
2129 }
2130
2131 const uint8_t *avpriv_find_start_code(const uint8_t *av_restrict p,
2132                                       const uint8_t *end,
2133                                       uint32_t *av_restrict state)
2134 {
2135     int i;
2136
2137     av_assert0(p <= end);
2138     if (p >= end)
2139         return end;
2140
2141     for (i = 0; i < 3; i++) {
2142         uint32_t tmp = *state << 8;
2143         *state = tmp + *(p++);
2144         if (tmp == 0x100 || p == end)
2145             return p;
2146     }
2147
2148     while (p < end) {
2149         if      (p[-1] > 1      ) p += 3;
2150         else if (p[-2]          ) p += 2;
2151         else if (p[-3]|(p[-1]-1)) p++;
2152         else {
2153             p++;
2154             break;
2155         }
2156     }
2157
2158     p = FFMIN(p, end) - 4;
2159     *state = AV_RB32(p);
2160
2161     return p + 4;
2162 }
2163
2164 AVCPBProperties *av_cpb_properties_alloc(size_t *size)
2165 {
2166     AVCPBProperties *props = av_mallocz(sizeof(AVCPBProperties));
2167     if (!props)
2168         return NULL;
2169
2170     if (size)
2171         *size = sizeof(*props);
2172
2173     props->vbv_delay = UINT64_MAX;
2174
2175     return props;
2176 }
2177
2178 AVCPBProperties *ff_add_cpb_side_data(AVCodecContext *avctx)
2179 {
2180     AVPacketSideData *tmp;
2181     AVCPBProperties  *props;
2182     size_t size;
2183
2184     props = av_cpb_properties_alloc(&size);
2185     if (!props)
2186         return NULL;
2187
2188     tmp = av_realloc_array(avctx->coded_side_data, avctx->nb_coded_side_data + 1, sizeof(*tmp));
2189     if (!tmp) {
2190         av_freep(&props);
2191         return NULL;
2192     }
2193
2194     avctx->coded_side_data = tmp;
2195     avctx->nb_coded_side_data++;
2196
2197     avctx->coded_side_data[avctx->nb_coded_side_data - 1].type = AV_PKT_DATA_CPB_PROPERTIES;
2198     avctx->coded_side_data[avctx->nb_coded_side_data - 1].data = (uint8_t*)props;
2199     avctx->coded_side_data[avctx->nb_coded_side_data - 1].size = size;
2200
2201     return props;
2202 }
2203
2204 static void codec_parameters_reset(AVCodecParameters *par)
2205 {
2206     av_freep(&par->extradata);
2207
2208     memset(par, 0, sizeof(*par));
2209
2210     par->codec_type          = AVMEDIA_TYPE_UNKNOWN;
2211     par->codec_id            = AV_CODEC_ID_NONE;
2212     par->format              = -1;
2213     par->field_order         = AV_FIELD_UNKNOWN;
2214     par->color_range         = AVCOL_RANGE_UNSPECIFIED;
2215     par->color_primaries     = AVCOL_PRI_UNSPECIFIED;
2216     par->color_trc           = AVCOL_TRC_UNSPECIFIED;
2217     par->color_space         = AVCOL_SPC_UNSPECIFIED;
2218     par->chroma_location     = AVCHROMA_LOC_UNSPECIFIED;
2219     par->sample_aspect_ratio = (AVRational){ 0, 1 };
2220     par->profile             = FF_PROFILE_UNKNOWN;
2221     par->level               = FF_LEVEL_UNKNOWN;
2222 }
2223
2224 AVCodecParameters *avcodec_parameters_alloc(void)
2225 {
2226     AVCodecParameters *par = av_mallocz(sizeof(*par));
2227
2228     if (!par)
2229         return NULL;
2230     codec_parameters_reset(par);
2231     return par;
2232 }
2233
2234 void avcodec_parameters_free(AVCodecParameters **ppar)
2235 {
2236     AVCodecParameters *par = *ppar;
2237
2238     if (!par)
2239         return;
2240     codec_parameters_reset(par);
2241
2242     av_freep(ppar);
2243 }
2244
2245 int avcodec_parameters_copy(AVCodecParameters *dst, const AVCodecParameters *src)
2246 {
2247     codec_parameters_reset(dst);
2248     memcpy(dst, src, sizeof(*dst));
2249
2250     dst->extradata      = NULL;
2251     dst->extradata_size = 0;
2252     if (src->extradata) {
2253         dst->extradata = av_mallocz(src->extradata_size + AV_INPUT_BUFFER_PADDING_SIZE);
2254         if (!dst->extradata)
2255             return AVERROR(ENOMEM);
2256         memcpy(dst->extradata, src->extradata, src->extradata_size);
2257         dst->extradata_size = src->extradata_size;
2258     }
2259
2260     return 0;
2261 }
2262
2263 int avcodec_parameters_from_context(AVCodecParameters *par,
2264                                     const AVCodecContext *codec)
2265 {
2266     codec_parameters_reset(par);
2267
2268     par->codec_type = codec->codec_type;
2269     par->codec_id   = codec->codec_id;
2270     par->codec_tag  = codec->codec_tag;
2271
2272     par->bit_rate              = codec->bit_rate;
2273     par->bits_per_coded_sample = codec->bits_per_coded_sample;
2274     par->bits_per_raw_sample   = codec->bits_per_raw_sample;
2275     par->profile               = codec->profile;
2276     par->level                 = codec->level;
2277
2278     switch (par->codec_type) {
2279     case AVMEDIA_TYPE_VIDEO:
2280         par->format              = codec->pix_fmt;
2281         par->width               = codec->width;
2282         par->height              = codec->height;
2283         par->field_order         = codec->field_order;
2284         par->color_range         = codec->color_range;
2285         par->color_primaries     = codec->color_primaries;
2286         par->color_trc           = codec->color_trc;
2287         par->color_space         = codec->colorspace;
2288         par->chroma_location     = codec->chroma_sample_location;
2289         par->sample_aspect_ratio = codec->sample_aspect_ratio;
2290         par->video_delay         = codec->has_b_frames;
2291         break;
2292     case AVMEDIA_TYPE_AUDIO:
2293         par->format           = codec->sample_fmt;
2294         par->channel_layout   = codec->channel_layout;
2295         par->channels         = codec->channels;
2296         par->sample_rate      = codec->sample_rate;
2297         par->block_align      = codec->block_align;
2298         par->frame_size       = codec->frame_size;
2299         par->initial_padding  = codec->initial_padding;
2300         par->trailing_padding = codec->trailing_padding;
2301         par->seek_preroll     = codec->seek_preroll;
2302         break;
2303     case AVMEDIA_TYPE_SUBTITLE:
2304         par->width  = codec->width;
2305         par->height = codec->height;
2306         break;
2307     }
2308
2309     if (codec->extradata) {
2310         par->extradata = av_mallocz(codec->extradata_size + AV_INPUT_BUFFER_PADDING_SIZE);
2311         if (!par->extradata)
2312             return AVERROR(ENOMEM);
2313         memcpy(par->extradata, codec->extradata, codec->extradata_size);
2314         par->extradata_size = codec->extradata_size;
2315     }
2316
2317     return 0;
2318 }
2319
2320 int avcodec_parameters_to_context(AVCodecContext *codec,
2321                                   const AVCodecParameters *par)
2322 {
2323     codec->codec_type = par->codec_type;
2324     codec->codec_id   = par->codec_id;
2325     codec->codec_tag  = par->codec_tag;
2326
2327     codec->bit_rate              = par->bit_rate;
2328     codec->bits_per_coded_sample = par->bits_per_coded_sample;
2329     codec->bits_per_raw_sample   = par->bits_per_raw_sample;
2330     codec->profile               = par->profile;
2331     codec->level                 = par->level;
2332
2333     switch (par->codec_type) {
2334     case AVMEDIA_TYPE_VIDEO:
2335         codec->pix_fmt                = par->format;
2336         codec->width                  = par->width;
2337         codec->height                 = par->height;
2338         codec->field_order            = par->field_order;
2339         codec->color_range            = par->color_range;
2340         codec->color_primaries        = par->color_primaries;
2341         codec->color_trc              = par->color_trc;
2342         codec->colorspace             = par->color_space;
2343         codec->chroma_sample_location = par->chroma_location;
2344         codec->sample_aspect_ratio    = par->sample_aspect_ratio;
2345         codec->has_b_frames           = par->video_delay;
2346         break;
2347     case AVMEDIA_TYPE_AUDIO:
2348         codec->sample_fmt       = par->format;
2349         codec->channel_layout   = par->channel_layout;
2350         codec->channels         = par->channels;
2351         codec->sample_rate      = par->sample_rate;
2352         codec->block_align      = par->block_align;
2353         codec->frame_size       = par->frame_size;
2354         codec->delay            =
2355         codec->initial_padding  = par->initial_padding;
2356         codec->trailing_padding = par->trailing_padding;
2357         codec->seek_preroll     = par->seek_preroll;
2358         break;
2359     case AVMEDIA_TYPE_SUBTITLE:
2360         codec->width  = par->width;
2361         codec->height = par->height;
2362         break;
2363     }
2364
2365     if (par->extradata) {
2366         av_freep(&codec->extradata);
2367         codec->extradata = av_mallocz(par->extradata_size + AV_INPUT_BUFFER_PADDING_SIZE);
2368         if (!codec->extradata)
2369             return AVERROR(ENOMEM);
2370         memcpy(codec->extradata, par->extradata, par->extradata_size);
2371         codec->extradata_size = par->extradata_size;
2372     }
2373
2374     return 0;
2375 }
2376
2377 int ff_alloc_a53_sei(const AVFrame *frame, size_t prefix_len,
2378                      void **data, size_t *sei_size)
2379 {
2380     AVFrameSideData *side_data = NULL;
2381     uint8_t *sei_data;
2382
2383     if (frame)
2384         side_data = av_frame_get_side_data(frame, AV_FRAME_DATA_A53_CC);
2385
2386     if (!side_data) {
2387         *data = NULL;
2388         return 0;
2389     }
2390
2391     *sei_size = side_data->size + 11;
2392     *data = av_mallocz(*sei_size + prefix_len);
2393     if (!*data)
2394         return AVERROR(ENOMEM);
2395     sei_data = (uint8_t*)*data + prefix_len;
2396
2397     // country code
2398     sei_data[0] = 181;
2399     sei_data[1] = 0;
2400     sei_data[2] = 49;
2401
2402     /**
2403      * 'GA94' is standard in North America for ATSC, but hard coding
2404      * this style may not be the right thing to do -- other formats
2405      * do exist. This information is not available in the side_data
2406      * so we are going with this right now.
2407      */
2408     AV_WL32(sei_data + 3, MKTAG('G', 'A', '9', '4'));
2409     sei_data[7] = 3;
2410     sei_data[8] = ((side_data->size/3) & 0x1f) | 0x40;
2411     sei_data[9] = 0;
2412
2413     memcpy(sei_data + 10, side_data->data, side_data->size);
2414
2415     sei_data[side_data->size+10] = 255;
2416
2417     return 0;
2418 }
2419
2420 int64_t ff_guess_coded_bitrate(AVCodecContext *avctx)
2421 {
2422     AVRational framerate = avctx->framerate;
2423     int bits_per_coded_sample = avctx->bits_per_coded_sample;
2424     int64_t bitrate;
2425
2426     if (!(framerate.num && framerate.den))
2427         framerate = av_inv_q(avctx->time_base);
2428     if (!(framerate.num && framerate.den))
2429         return 0;
2430
2431     if (!bits_per_coded_sample) {
2432         const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(avctx->pix_fmt);
2433         bits_per_coded_sample = av_get_bits_per_pixel(desc);
2434     }
2435     bitrate = (int64_t)bits_per_coded_sample * avctx->width * avctx->height *
2436               framerate.num / framerate.den;
2437
2438     return bitrate;
2439 }