]> git.sesse.net Git - ffmpeg/blob - libavcodec/utils.c
Deprecate avctx.coded_frame
[ffmpeg] / libavcodec / utils.c
1 /*
2  * utils for libavcodec
3  * Copyright (c) 2001 Fabrice Bellard
4  * Copyright (c) 2002-2004 Michael Niedermayer <michaelni@gmx.at>
5  *
6  * This file is part of Libav.
7  *
8  * Libav is free software; you can redistribute it and/or
9  * modify it under the terms of the GNU Lesser General Public
10  * License as published by the Free Software Foundation; either
11  * version 2.1 of the License, or (at your option) any later version.
12  *
13  * Libav is distributed in the hope that it will be useful,
14  * but WITHOUT ANY WARRANTY; without even the implied warranty of
15  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
16  * Lesser General Public License for more details.
17  *
18  * You should have received a copy of the GNU Lesser General Public
19  * License along with Libav; if not, write to the Free Software
20  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
21  */
22
23 /**
24  * @file
25  * utils.
26  */
27
28 #include "config.h"
29 #include "libavutil/attributes.h"
30 #include "libavutil/avassert.h"
31 #include "libavutil/avstring.h"
32 #include "libavutil/channel_layout.h"
33 #include "libavutil/crc.h"
34 #include "libavutil/frame.h"
35 #include "libavutil/internal.h"
36 #include "libavutil/mathematics.h"
37 #include "libavutil/pixdesc.h"
38 #include "libavutil/imgutils.h"
39 #include "libavutil/samplefmt.h"
40 #include "libavutil/dict.h"
41 #include "avcodec.h"
42 #include "libavutil/opt.h"
43 #include "me_cmp.h"
44 #include "mpegvideo.h"
45 #include "thread.h"
46 #include "internal.h"
47 #include "bytestream.h"
48 #include "version.h"
49 #include <stdlib.h>
50 #include <stdarg.h>
51 #include <limits.h>
52 #include <float.h>
53
54 static int volatile entangled_thread_counter = 0;
55 static int (*lockmgr_cb)(void **mutex, enum AVLockOp op);
56 static void *codec_mutex;
57 static void *avformat_mutex;
58
59 void av_fast_padded_malloc(void *ptr, unsigned int *size, size_t min_size)
60 {
61     void **p = ptr;
62     if (min_size > SIZE_MAX - FF_INPUT_BUFFER_PADDING_SIZE) {
63         av_freep(p);
64         *size = 0;
65         return;
66     }
67     av_fast_malloc(p, size, min_size + FF_INPUT_BUFFER_PADDING_SIZE);
68     if (*size)
69         memset((uint8_t *)*p + min_size, 0, FF_INPUT_BUFFER_PADDING_SIZE);
70 }
71
72 /* encoder management */
73 static AVCodec *first_avcodec = NULL;
74
75 AVCodec *av_codec_next(const AVCodec *c)
76 {
77     if (c)
78         return c->next;
79     else
80         return first_avcodec;
81 }
82
83 static av_cold void avcodec_init(void)
84 {
85     static int initialized = 0;
86
87     if (initialized != 0)
88         return;
89     initialized = 1;
90
91     if (CONFIG_ME_CMP)
92         ff_me_cmp_init_static();
93 }
94
95 int av_codec_is_encoder(const AVCodec *codec)
96 {
97     return codec && (codec->encode_sub || codec->encode2);
98 }
99
100 int av_codec_is_decoder(const AVCodec *codec)
101 {
102     return codec && codec->decode;
103 }
104
105 av_cold void avcodec_register(AVCodec *codec)
106 {
107     AVCodec **p;
108     avcodec_init();
109     p = &first_avcodec;
110     while (*p)
111         p = &(*p)->next;
112     *p          = codec;
113     codec->next = NULL;
114
115     if (codec->init_static_data)
116         codec->init_static_data(codec);
117 }
118
119 #if FF_API_EMU_EDGE
120 unsigned avcodec_get_edge_width(void)
121 {
122     return EDGE_WIDTH;
123 }
124 #endif
125
126 #if FF_API_SET_DIMENSIONS
127 void avcodec_set_dimensions(AVCodecContext *s, int width, int height)
128 {
129     ff_set_dimensions(s, width, height);
130 }
131 #endif
132
133 int ff_set_dimensions(AVCodecContext *s, int width, int height)
134 {
135     int ret = av_image_check_size(width, height, 0, s);
136
137     if (ret < 0)
138         width = height = 0;
139     s->width  = s->coded_width  = width;
140     s->height = s->coded_height = height;
141
142     return ret;
143 }
144
145 int ff_set_sar(AVCodecContext *avctx, AVRational sar)
146 {
147     int ret = av_image_check_sar(avctx->width, avctx->height, sar);
148
149     if (ret < 0) {
150         av_log(avctx, AV_LOG_WARNING, "ignoring invalid SAR: %d/%d\n",
151                sar.num, sar.den);
152         avctx->sample_aspect_ratio = (AVRational){ 0, 1 };
153         return ret;
154     } else {
155         avctx->sample_aspect_ratio = sar;
156     }
157     return 0;
158 }
159
160 int ff_side_data_update_matrix_encoding(AVFrame *frame,
161                                         enum AVMatrixEncoding matrix_encoding)
162 {
163     AVFrameSideData *side_data;
164     enum AVMatrixEncoding *data;
165
166     side_data = av_frame_get_side_data(frame, AV_FRAME_DATA_MATRIXENCODING);
167     if (!side_data)
168         side_data = av_frame_new_side_data(frame, AV_FRAME_DATA_MATRIXENCODING,
169                                            sizeof(enum AVMatrixEncoding));
170
171     if (!side_data)
172         return AVERROR(ENOMEM);
173
174     data  = (enum AVMatrixEncoding*)side_data->data;
175     *data = matrix_encoding;
176
177     return 0;
178 }
179
180 #if HAVE_SIMD_ALIGN_16
181 #   define STRIDE_ALIGN 16
182 #else
183 #   define STRIDE_ALIGN 8
184 #endif
185
186 void avcodec_align_dimensions2(AVCodecContext *s, int *width, int *height,
187                                int linesize_align[AV_NUM_DATA_POINTERS])
188 {
189     int i;
190     int w_align = 1;
191     int h_align = 1;
192
193     switch (s->pix_fmt) {
194     case AV_PIX_FMT_YUV420P:
195     case AV_PIX_FMT_YUYV422:
196     case AV_PIX_FMT_YVYU422:
197     case AV_PIX_FMT_UYVY422:
198     case AV_PIX_FMT_YUV422P:
199     case AV_PIX_FMT_YUV440P:
200     case AV_PIX_FMT_YUV444P:
201     case AV_PIX_FMT_GBRP:
202     case AV_PIX_FMT_GBRAP:
203     case AV_PIX_FMT_GRAY8:
204     case AV_PIX_FMT_GRAY16BE:
205     case AV_PIX_FMT_GRAY16LE:
206     case AV_PIX_FMT_YUVJ420P:
207     case AV_PIX_FMT_YUVJ422P:
208     case AV_PIX_FMT_YUVJ440P:
209     case AV_PIX_FMT_YUVJ444P:
210     case AV_PIX_FMT_YUVA420P:
211     case AV_PIX_FMT_YUVA422P:
212     case AV_PIX_FMT_YUVA444P:
213     case AV_PIX_FMT_YUV420P9LE:
214     case AV_PIX_FMT_YUV420P9BE:
215     case AV_PIX_FMT_YUV420P10LE:
216     case AV_PIX_FMT_YUV420P10BE:
217     case AV_PIX_FMT_YUV422P9LE:
218     case AV_PIX_FMT_YUV422P9BE:
219     case AV_PIX_FMT_YUV422P10LE:
220     case AV_PIX_FMT_YUV422P10BE:
221     case AV_PIX_FMT_YUVA422P10LE:
222     case AV_PIX_FMT_YUVA422P10BE:
223     case AV_PIX_FMT_YUV444P9LE:
224     case AV_PIX_FMT_YUV444P9BE:
225     case AV_PIX_FMT_YUV444P10LE:
226     case AV_PIX_FMT_YUV444P10BE:
227     case AV_PIX_FMT_YUVA444P10LE:
228     case AV_PIX_FMT_YUVA444P10BE:
229     case AV_PIX_FMT_GBRP9LE:
230     case AV_PIX_FMT_GBRP9BE:
231     case AV_PIX_FMT_GBRP10LE:
232     case AV_PIX_FMT_GBRP10BE:
233         w_align = 16; //FIXME assume 16 pixel per macroblock
234         h_align = 16 * 2; // interlaced needs 2 macroblocks height
235         break;
236     case AV_PIX_FMT_YUV411P:
237     case AV_PIX_FMT_UYYVYY411:
238         w_align = 32;
239         h_align = 8;
240         break;
241     case AV_PIX_FMT_YUV410P:
242         if (s->codec_id == AV_CODEC_ID_SVQ1) {
243             w_align = 64;
244             h_align = 64;
245         }
246     case AV_PIX_FMT_RGB555:
247         if (s->codec_id == AV_CODEC_ID_RPZA) {
248             w_align = 4;
249             h_align = 4;
250         }
251     case AV_PIX_FMT_PAL8:
252     case AV_PIX_FMT_BGR8:
253     case AV_PIX_FMT_RGB8:
254         if (s->codec_id == AV_CODEC_ID_SMC) {
255             w_align = 4;
256             h_align = 4;
257         }
258         break;
259     case AV_PIX_FMT_BGR24:
260         if ((s->codec_id == AV_CODEC_ID_MSZH) ||
261             (s->codec_id == AV_CODEC_ID_ZLIB)) {
262             w_align = 4;
263             h_align = 4;
264         }
265         break;
266     default:
267         w_align = 1;
268         h_align = 1;
269         break;
270     }
271
272     *width  = FFALIGN(*width, w_align);
273     *height = FFALIGN(*height, h_align);
274     if (s->codec_id == AV_CODEC_ID_H264)
275         // some of the optimized chroma MC reads one line too much
276         *height += 2;
277
278     for (i = 0; i < 4; i++)
279         linesize_align[i] = STRIDE_ALIGN;
280 }
281
282 void avcodec_align_dimensions(AVCodecContext *s, int *width, int *height)
283 {
284     const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(s->pix_fmt);
285     int chroma_shift = desc->log2_chroma_w;
286     int linesize_align[AV_NUM_DATA_POINTERS];
287     int align;
288
289     avcodec_align_dimensions2(s, width, height, linesize_align);
290     align               = FFMAX(linesize_align[0], linesize_align[3]);
291     linesize_align[1] <<= chroma_shift;
292     linesize_align[2] <<= chroma_shift;
293     align               = FFMAX3(align, linesize_align[1], linesize_align[2]);
294     *width              = FFALIGN(*width, align);
295 }
296
297 int avcodec_fill_audio_frame(AVFrame *frame, int nb_channels,
298                              enum AVSampleFormat sample_fmt, const uint8_t *buf,
299                              int buf_size, int align)
300 {
301     int ch, planar, needed_size, ret = 0;
302
303     needed_size = av_samples_get_buffer_size(NULL, nb_channels,
304                                              frame->nb_samples, sample_fmt,
305                                              align);
306     if (buf_size < needed_size)
307         return AVERROR(EINVAL);
308
309     planar = av_sample_fmt_is_planar(sample_fmt);
310     if (planar && nb_channels > AV_NUM_DATA_POINTERS) {
311         if (!(frame->extended_data = av_mallocz(nb_channels *
312                                                 sizeof(*frame->extended_data))))
313             return AVERROR(ENOMEM);
314     } else {
315         frame->extended_data = frame->data;
316     }
317
318     if ((ret = av_samples_fill_arrays(frame->extended_data, &frame->linesize[0],
319                                       buf, nb_channels, frame->nb_samples,
320                                       sample_fmt, align)) < 0) {
321         if (frame->extended_data != frame->data)
322             av_free(frame->extended_data);
323         return ret;
324     }
325     if (frame->extended_data != frame->data) {
326         for (ch = 0; ch < AV_NUM_DATA_POINTERS; ch++)
327             frame->data[ch] = frame->extended_data[ch];
328     }
329
330     return ret;
331 }
332
333 static int update_frame_pool(AVCodecContext *avctx, AVFrame *frame)
334 {
335     FramePool *pool = avctx->internal->pool;
336     int i, ret;
337
338     switch (avctx->codec_type) {
339     case AVMEDIA_TYPE_VIDEO: {
340         AVPicture picture;
341         int size[4] = { 0 };
342         int w = frame->width;
343         int h = frame->height;
344         int tmpsize, unaligned;
345
346         if (pool->format == frame->format &&
347             pool->width == frame->width && pool->height == frame->height)
348             return 0;
349
350         avcodec_align_dimensions2(avctx, &w, &h, pool->stride_align);
351
352         do {
353             // NOTE: do not align linesizes individually, this breaks e.g. assumptions
354             // that linesize[0] == 2*linesize[1] in the MPEG-encoder for 4:2:2
355             av_image_fill_linesizes(picture.linesize, avctx->pix_fmt, w);
356             // increase alignment of w for next try (rhs gives the lowest bit set in w)
357             w += w & ~(w - 1);
358
359             unaligned = 0;
360             for (i = 0; i < 4; i++)
361                 unaligned |= picture.linesize[i] % pool->stride_align[i];
362         } while (unaligned);
363
364         tmpsize = av_image_fill_pointers(picture.data, avctx->pix_fmt, h,
365                                          NULL, picture.linesize);
366         if (tmpsize < 0)
367             return -1;
368
369         for (i = 0; i < 3 && picture.data[i + 1]; i++)
370             size[i] = picture.data[i + 1] - picture.data[i];
371         size[i] = tmpsize - (picture.data[i] - picture.data[0]);
372
373         for (i = 0; i < 4; i++) {
374             av_buffer_pool_uninit(&pool->pools[i]);
375             pool->linesize[i] = picture.linesize[i];
376             if (size[i]) {
377                 pool->pools[i] = av_buffer_pool_init(size[i] + 16, NULL);
378                 if (!pool->pools[i]) {
379                     ret = AVERROR(ENOMEM);
380                     goto fail;
381                 }
382             }
383         }
384         pool->format = frame->format;
385         pool->width  = frame->width;
386         pool->height = frame->height;
387
388         break;
389         }
390     case AVMEDIA_TYPE_AUDIO: {
391         int ch     = av_get_channel_layout_nb_channels(frame->channel_layout);
392         int planar = av_sample_fmt_is_planar(frame->format);
393         int planes = planar ? ch : 1;
394
395         if (pool->format == frame->format && pool->planes == planes &&
396             pool->channels == ch && frame->nb_samples == pool->samples)
397             return 0;
398
399         av_buffer_pool_uninit(&pool->pools[0]);
400         ret = av_samples_get_buffer_size(&pool->linesize[0], ch,
401                                          frame->nb_samples, frame->format, 0);
402         if (ret < 0)
403             goto fail;
404
405         pool->pools[0] = av_buffer_pool_init(pool->linesize[0], NULL);
406         if (!pool->pools[0]) {
407             ret = AVERROR(ENOMEM);
408             goto fail;
409         }
410
411         pool->format     = frame->format;
412         pool->planes     = planes;
413         pool->channels   = ch;
414         pool->samples = frame->nb_samples;
415         break;
416         }
417     default: av_assert0(0);
418     }
419     return 0;
420 fail:
421     for (i = 0; i < 4; i++)
422         av_buffer_pool_uninit(&pool->pools[i]);
423     pool->format = -1;
424     pool->planes = pool->channels = pool->samples = 0;
425     pool->width  = pool->height = 0;
426     return ret;
427 }
428
429 static int audio_get_buffer(AVCodecContext *avctx, AVFrame *frame)
430 {
431     FramePool *pool = avctx->internal->pool;
432     int planes = pool->planes;
433     int i;
434
435     frame->linesize[0] = pool->linesize[0];
436
437     if (planes > AV_NUM_DATA_POINTERS) {
438         frame->extended_data = av_mallocz(planes * sizeof(*frame->extended_data));
439         frame->nb_extended_buf = planes - AV_NUM_DATA_POINTERS;
440         frame->extended_buf  = av_mallocz(frame->nb_extended_buf *
441                                           sizeof(*frame->extended_buf));
442         if (!frame->extended_data || !frame->extended_buf) {
443             av_freep(&frame->extended_data);
444             av_freep(&frame->extended_buf);
445             return AVERROR(ENOMEM);
446         }
447     } else
448         frame->extended_data = frame->data;
449
450     for (i = 0; i < FFMIN(planes, AV_NUM_DATA_POINTERS); i++) {
451         frame->buf[i] = av_buffer_pool_get(pool->pools[0]);
452         if (!frame->buf[i])
453             goto fail;
454         frame->extended_data[i] = frame->data[i] = frame->buf[i]->data;
455     }
456     for (i = 0; i < frame->nb_extended_buf; i++) {
457         frame->extended_buf[i] = av_buffer_pool_get(pool->pools[0]);
458         if (!frame->extended_buf[i])
459             goto fail;
460         frame->extended_data[i + AV_NUM_DATA_POINTERS] = frame->extended_buf[i]->data;
461     }
462
463     if (avctx->debug & FF_DEBUG_BUFFERS)
464         av_log(avctx, AV_LOG_DEBUG, "default_get_buffer called on frame %p", frame);
465
466     return 0;
467 fail:
468     av_frame_unref(frame);
469     return AVERROR(ENOMEM);
470 }
471
472 static int video_get_buffer(AVCodecContext *s, AVFrame *pic)
473 {
474     FramePool *pool = s->internal->pool;
475     int i;
476
477     if (pic->data[0]) {
478         av_log(s, AV_LOG_ERROR, "pic->data[0]!=NULL in avcodec_default_get_buffer\n");
479         return -1;
480     }
481
482     memset(pic->data, 0, sizeof(pic->data));
483     pic->extended_data = pic->data;
484
485     for (i = 0; i < 4 && pool->pools[i]; i++) {
486         pic->linesize[i] = pool->linesize[i];
487
488         pic->buf[i] = av_buffer_pool_get(pool->pools[i]);
489         if (!pic->buf[i])
490             goto fail;
491
492         pic->data[i] = pic->buf[i]->data;
493     }
494     for (; i < AV_NUM_DATA_POINTERS; i++) {
495         pic->data[i] = NULL;
496         pic->linesize[i] = 0;
497     }
498     if (pic->data[1] && !pic->data[2])
499         avpriv_set_systematic_pal2((uint32_t *)pic->data[1], s->pix_fmt);
500
501     if (s->debug & FF_DEBUG_BUFFERS)
502         av_log(s, AV_LOG_DEBUG, "default_get_buffer called on pic %p\n", pic);
503
504     return 0;
505 fail:
506     av_frame_unref(pic);
507     return AVERROR(ENOMEM);
508 }
509
510 int avcodec_default_get_buffer2(AVCodecContext *avctx, AVFrame *frame, int flags)
511 {
512     int ret;
513
514     if ((ret = update_frame_pool(avctx, frame)) < 0)
515         return ret;
516
517 #if FF_API_GET_BUFFER
518 FF_DISABLE_DEPRECATION_WARNINGS
519     frame->type = FF_BUFFER_TYPE_INTERNAL;
520 FF_ENABLE_DEPRECATION_WARNINGS
521 #endif
522
523     switch (avctx->codec_type) {
524     case AVMEDIA_TYPE_VIDEO:
525         return video_get_buffer(avctx, frame);
526     case AVMEDIA_TYPE_AUDIO:
527         return audio_get_buffer(avctx, frame);
528     default:
529         return -1;
530     }
531 }
532
533 #if FF_API_GET_BUFFER
534 FF_DISABLE_DEPRECATION_WARNINGS
535 int avcodec_default_get_buffer(AVCodecContext *avctx, AVFrame *frame)
536 {
537     return avcodec_default_get_buffer2(avctx, frame, 0);
538 }
539
540 typedef struct CompatReleaseBufPriv {
541     AVCodecContext avctx;
542     AVFrame frame;
543 } CompatReleaseBufPriv;
544
545 static void compat_free_buffer(void *opaque, uint8_t *data)
546 {
547     CompatReleaseBufPriv *priv = opaque;
548     if (priv->avctx.release_buffer)
549         priv->avctx.release_buffer(&priv->avctx, &priv->frame);
550     av_freep(&priv);
551 }
552
553 static void compat_release_buffer(void *opaque, uint8_t *data)
554 {
555     AVBufferRef *buf = opaque;
556     av_buffer_unref(&buf);
557 }
558 FF_ENABLE_DEPRECATION_WARNINGS
559 #endif
560
561 int ff_decode_frame_props(AVCodecContext *avctx, AVFrame *frame)
562 {
563     AVPacket *pkt = avctx->internal->pkt;
564     int i;
565     struct {
566         enum AVPacketSideDataType packet;
567         enum AVFrameSideDataType frame;
568     } sd[] = {
569         { AV_PKT_DATA_REPLAYGAIN ,   AV_FRAME_DATA_REPLAYGAIN },
570         { AV_PKT_DATA_DISPLAYMATRIX, AV_FRAME_DATA_DISPLAYMATRIX },
571         { AV_PKT_DATA_STEREO3D,      AV_FRAME_DATA_STEREO3D },
572         { AV_PKT_DATA_AUDIO_SERVICE_TYPE, AV_FRAME_DATA_AUDIO_SERVICE_TYPE },
573     };
574
575     frame->color_primaries = avctx->color_primaries;
576     frame->color_trc       = avctx->color_trc;
577     frame->colorspace      = avctx->colorspace;
578     frame->color_range     = avctx->color_range;
579     frame->chroma_location = avctx->chroma_sample_location;
580
581     frame->reordered_opaque = avctx->reordered_opaque;
582     if (!pkt) {
583         frame->pkt_pts = AV_NOPTS_VALUE;
584         return 0;
585     }
586
587     frame->pkt_pts = pkt->pts;
588
589     for (i = 0; i < FF_ARRAY_ELEMS(sd); i++) {
590         int size;
591         uint8_t *packet_sd = av_packet_get_side_data(pkt, sd[i].packet, &size);
592         if (packet_sd) {
593             AVFrameSideData *frame_sd = av_frame_new_side_data(frame,
594                                                                sd[i].frame,
595                                                                size);
596             if (!frame_sd)
597                 return AVERROR(ENOMEM);
598
599             memcpy(frame_sd->data, packet_sd, size);
600         }
601     }
602
603     return 0;
604 }
605
606 int ff_get_buffer(AVCodecContext *avctx, AVFrame *frame, int flags)
607 {
608     const AVHWAccel *hwaccel = avctx->hwaccel;
609     int override_dimensions = 1;
610     int ret;
611
612     switch (avctx->codec_type) {
613     case AVMEDIA_TYPE_VIDEO:
614         if (frame->width <= 0 || frame->height <= 0) {
615             frame->width  = FFMAX(avctx->width, avctx->coded_width);
616             frame->height = FFMAX(avctx->height, avctx->coded_height);
617             override_dimensions = 0;
618         }
619         if (frame->format < 0)
620             frame->format              = avctx->pix_fmt;
621         if (!frame->sample_aspect_ratio.num)
622             frame->sample_aspect_ratio = avctx->sample_aspect_ratio;
623
624         if (av_image_check_sar(frame->width, frame->height,
625                                frame->sample_aspect_ratio) < 0) {
626             av_log(avctx, AV_LOG_WARNING, "ignoring invalid SAR: %u/%u\n",
627                    frame->sample_aspect_ratio.num,
628                    frame->sample_aspect_ratio.den);
629             frame->sample_aspect_ratio = (AVRational){ 0, 1 };
630         }
631
632         if ((ret = av_image_check_size(avctx->width, avctx->height, 0, avctx)) < 0)
633             return ret;
634         break;
635     case AVMEDIA_TYPE_AUDIO:
636         if (!frame->sample_rate)
637             frame->sample_rate    = avctx->sample_rate;
638         if (frame->format < 0)
639             frame->format         = avctx->sample_fmt;
640         if (!frame->channel_layout) {
641             if (avctx->channel_layout) {
642                  if (av_get_channel_layout_nb_channels(avctx->channel_layout) !=
643                      avctx->channels) {
644                      av_log(avctx, AV_LOG_ERROR, "Inconsistent channel "
645                             "configuration.\n");
646                      return AVERROR(EINVAL);
647                  }
648
649                 frame->channel_layout = avctx->channel_layout;
650             } else {
651                 if (avctx->channels > FF_SANE_NB_CHANNELS) {
652                     av_log(avctx, AV_LOG_ERROR, "Too many channels: %d.\n",
653                            avctx->channels);
654                     return AVERROR(ENOSYS);
655                 }
656
657                 frame->channel_layout = av_get_default_channel_layout(avctx->channels);
658                 if (!frame->channel_layout)
659                     frame->channel_layout = (1ULL << avctx->channels) - 1;
660             }
661         }
662         break;
663     default: return AVERROR(EINVAL);
664     }
665
666     ret = ff_decode_frame_props(avctx, frame);
667     if (ret < 0)
668         return ret;
669
670     if (hwaccel) {
671         if (hwaccel->alloc_frame) {
672             ret = hwaccel->alloc_frame(avctx, frame);
673             goto end;
674         }
675     } else
676         avctx->sw_pix_fmt = avctx->pix_fmt;
677
678 #if FF_API_GET_BUFFER
679 FF_DISABLE_DEPRECATION_WARNINGS
680     /*
681      * Wrap an old get_buffer()-allocated buffer in an bunch of AVBuffers.
682      * We wrap each plane in its own AVBuffer. Each of those has a reference to
683      * a dummy AVBuffer as its private data, unreffing it on free.
684      * When all the planes are freed, the dummy buffer's free callback calls
685      * release_buffer().
686      */
687     if (avctx->get_buffer) {
688         CompatReleaseBufPriv *priv = NULL;
689         AVBufferRef *dummy_buf = NULL;
690         int planes, i, ret;
691
692         if (flags & AV_GET_BUFFER_FLAG_REF)
693             frame->reference    = 1;
694
695         ret = avctx->get_buffer(avctx, frame);
696         if (ret < 0)
697             return ret;
698
699         /* return if the buffers are already set up
700          * this would happen e.g. when a custom get_buffer() calls
701          * avcodec_default_get_buffer
702          */
703         if (frame->buf[0])
704             return 0;
705
706         priv = av_mallocz(sizeof(*priv));
707         if (!priv) {
708             ret = AVERROR(ENOMEM);
709             goto fail;
710         }
711         priv->avctx = *avctx;
712         priv->frame = *frame;
713
714         dummy_buf = av_buffer_create(NULL, 0, compat_free_buffer, priv, 0);
715         if (!dummy_buf) {
716             ret = AVERROR(ENOMEM);
717             goto fail;
718         }
719
720 #define WRAP_PLANE(ref_out, data, data_size)                            \
721 do {                                                                    \
722     AVBufferRef *dummy_ref = av_buffer_ref(dummy_buf);                  \
723     if (!dummy_ref) {                                                   \
724         ret = AVERROR(ENOMEM);                                          \
725         goto fail;                                                      \
726     }                                                                   \
727     ref_out = av_buffer_create(data, data_size, compat_release_buffer,  \
728                                dummy_ref, 0);                           \
729     if (!ref_out) {                                                     \
730         av_buffer_unref(&dummy_ref);                                    \
731         av_frame_unref(frame);                                          \
732         ret = AVERROR(ENOMEM);                                          \
733         goto fail;                                                      \
734     }                                                                   \
735 } while (0)
736
737         if (avctx->codec_type == AVMEDIA_TYPE_VIDEO) {
738             const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(frame->format);
739
740             planes = av_pix_fmt_count_planes(frame->format);
741             /* workaround for AVHWAccel plane count of 0, buf[0] is used as
742                check for allocated buffers: make libavcodec happy */
743             if (desc && desc->flags & AV_PIX_FMT_FLAG_HWACCEL)
744                 planes = 1;
745             if (!desc || planes <= 0) {
746                 ret = AVERROR(EINVAL);
747                 goto fail;
748             }
749
750             for (i = 0; i < planes; i++) {
751                 int v_shift    = (i == 1 || i == 2) ? desc->log2_chroma_h : 0;
752                 int plane_size = (frame->height >> v_shift) * frame->linesize[i];
753
754                 WRAP_PLANE(frame->buf[i], frame->data[i], plane_size);
755             }
756         } else {
757             int planar = av_sample_fmt_is_planar(frame->format);
758             planes = planar ? avctx->channels : 1;
759
760             if (planes > FF_ARRAY_ELEMS(frame->buf)) {
761                 frame->nb_extended_buf = planes - FF_ARRAY_ELEMS(frame->buf);
762                 frame->extended_buf = av_malloc(sizeof(*frame->extended_buf) *
763                                                 frame->nb_extended_buf);
764                 if (!frame->extended_buf) {
765                     ret = AVERROR(ENOMEM);
766                     goto fail;
767                 }
768             }
769
770             for (i = 0; i < FFMIN(planes, FF_ARRAY_ELEMS(frame->buf)); i++)
771                 WRAP_PLANE(frame->buf[i], frame->extended_data[i], frame->linesize[0]);
772
773             for (i = 0; i < frame->nb_extended_buf; i++)
774                 WRAP_PLANE(frame->extended_buf[i],
775                            frame->extended_data[i + FF_ARRAY_ELEMS(frame->buf)],
776                            frame->linesize[0]);
777         }
778
779         av_buffer_unref(&dummy_buf);
780
781         frame->width  = avctx->width;
782         frame->height = avctx->height;
783
784         return 0;
785
786 fail:
787         avctx->release_buffer(avctx, frame);
788         av_freep(&priv);
789         av_buffer_unref(&dummy_buf);
790         return ret;
791     }
792 FF_ENABLE_DEPRECATION_WARNINGS
793 #endif
794
795     ret = avctx->get_buffer2(avctx, frame, flags);
796
797 end:
798     if (avctx->codec_type == AVMEDIA_TYPE_VIDEO && !override_dimensions) {
799         frame->width  = avctx->width;
800         frame->height = avctx->height;
801     }
802
803     return ret;
804 }
805
806 int ff_reget_buffer(AVCodecContext *avctx, AVFrame *frame)
807 {
808     AVFrame *tmp;
809     int ret;
810
811     av_assert0(avctx->codec_type == AVMEDIA_TYPE_VIDEO);
812
813     if (!frame->data[0])
814         return ff_get_buffer(avctx, frame, AV_GET_BUFFER_FLAG_REF);
815
816     if (av_frame_is_writable(frame))
817         return ff_decode_frame_props(avctx, frame);
818
819     tmp = av_frame_alloc();
820     if (!tmp)
821         return AVERROR(ENOMEM);
822
823     av_frame_move_ref(tmp, frame);
824
825     ret = ff_get_buffer(avctx, frame, AV_GET_BUFFER_FLAG_REF);
826     if (ret < 0) {
827         av_frame_free(&tmp);
828         return ret;
829     }
830
831     av_frame_copy(frame, tmp);
832     av_frame_free(&tmp);
833
834     return 0;
835 }
836
837 #if FF_API_GET_BUFFER
838 void avcodec_default_release_buffer(AVCodecContext *s, AVFrame *pic)
839 {
840     av_frame_unref(pic);
841 }
842
843 int avcodec_default_reget_buffer(AVCodecContext *s, AVFrame *pic)
844 {
845     av_assert0(0);
846     return AVERROR_BUG;
847 }
848 #endif
849
850 int avcodec_default_execute(AVCodecContext *c, int (*func)(AVCodecContext *c2, void *arg2), void *arg, int *ret, int count, int size)
851 {
852     int i;
853
854     for (i = 0; i < count; i++) {
855         int r = func(c, (char *)arg + i * size);
856         if (ret)
857             ret[i] = r;
858     }
859     return 0;
860 }
861
862 int avcodec_default_execute2(AVCodecContext *c, int (*func)(AVCodecContext *c2, void *arg2, int jobnr, int threadnr), void *arg, int *ret, int count)
863 {
864     int i;
865
866     for (i = 0; i < count; i++) {
867         int r = func(c, arg, i, 0);
868         if (ret)
869             ret[i] = r;
870     }
871     return 0;
872 }
873
874 static int is_hwaccel_pix_fmt(enum AVPixelFormat pix_fmt)
875 {
876     const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(pix_fmt);
877     return desc->flags & AV_PIX_FMT_FLAG_HWACCEL;
878 }
879
880 enum AVPixelFormat avcodec_default_get_format(struct AVCodecContext *s, const enum AVPixelFormat *fmt)
881 {
882     while (*fmt != AV_PIX_FMT_NONE && is_hwaccel_pix_fmt(*fmt))
883         ++fmt;
884     return fmt[0];
885 }
886
887 static AVHWAccel *find_hwaccel(enum AVCodecID codec_id,
888                                enum AVPixelFormat pix_fmt)
889 {
890     AVHWAccel *hwaccel = NULL;
891
892     while ((hwaccel = av_hwaccel_next(hwaccel)))
893         if (hwaccel->id == codec_id
894             && hwaccel->pix_fmt == pix_fmt)
895             return hwaccel;
896     return NULL;
897 }
898
899 static int setup_hwaccel(AVCodecContext *avctx,
900                          const enum AVPixelFormat fmt,
901                          const char *name)
902 {
903     AVHWAccel *hwa = find_hwaccel(avctx->codec_id, fmt);
904     int ret        = 0;
905
906     if (!hwa) {
907         av_log(avctx, AV_LOG_ERROR,
908                "Could not find an AVHWAccel for the pixel format: %s",
909                name);
910         return AVERROR(ENOENT);
911     }
912
913     if (hwa->priv_data_size) {
914         avctx->internal->hwaccel_priv_data = av_mallocz(hwa->priv_data_size);
915         if (!avctx->internal->hwaccel_priv_data)
916             return AVERROR(ENOMEM);
917     }
918
919     if (hwa->init) {
920         ret = hwa->init(avctx);
921         if (ret < 0) {
922             av_freep(&avctx->internal->hwaccel_priv_data);
923             return ret;
924         }
925     }
926
927     avctx->hwaccel = hwa;
928
929     return 0;
930 }
931
932 int ff_get_format(AVCodecContext *avctx, const enum AVPixelFormat *fmt)
933 {
934     const AVPixFmtDescriptor *desc;
935     enum AVPixelFormat *choices;
936     enum AVPixelFormat ret;
937     unsigned n = 0;
938
939     while (fmt[n] != AV_PIX_FMT_NONE)
940         ++n;
941
942     av_assert0(n >= 1);
943     avctx->sw_pix_fmt = fmt[n - 1];
944     av_assert2(!is_hwaccel_pix_fmt(avctx->sw_pix_fmt));
945
946     choices = av_malloc_array(n + 1, sizeof(*choices));
947     if (!choices)
948         return AV_PIX_FMT_NONE;
949
950     memcpy(choices, fmt, (n + 1) * sizeof(*choices));
951
952     for (;;) {
953         if (avctx->hwaccel && avctx->hwaccel->uninit)
954             avctx->hwaccel->uninit(avctx);
955         av_freep(&avctx->internal->hwaccel_priv_data);
956         avctx->hwaccel = NULL;
957
958         ret = avctx->get_format(avctx, choices);
959
960         desc = av_pix_fmt_desc_get(ret);
961         if (!desc) {
962             ret = AV_PIX_FMT_NONE;
963             break;
964         }
965
966         if (!(desc->flags & AV_PIX_FMT_FLAG_HWACCEL))
967             break;
968
969         if (!setup_hwaccel(avctx, ret, desc->name))
970             break;
971
972         /* Remove failed hwaccel from choices */
973         for (n = 0; choices[n] != ret; n++)
974             av_assert0(choices[n] != AV_PIX_FMT_NONE);
975
976         do
977             choices[n] = choices[n + 1];
978         while (choices[n++] != AV_PIX_FMT_NONE);
979     }
980
981     av_freep(&choices);
982     return ret;
983 }
984
985 #if FF_API_AVFRAME_LAVC
986 void avcodec_get_frame_defaults(AVFrame *frame)
987 {
988     if (frame->extended_data != frame->data)
989         av_freep(&frame->extended_data);
990
991     memset(frame, 0, sizeof(AVFrame));
992
993     frame->pts                 = AV_NOPTS_VALUE;
994     frame->key_frame           = 1;
995     frame->sample_aspect_ratio = (AVRational) {0, 1 };
996     frame->format              = -1; /* unknown */
997     frame->extended_data       = frame->data;
998 }
999
1000 AVFrame *avcodec_alloc_frame(void)
1001 {
1002     AVFrame *frame = av_mallocz(sizeof(AVFrame));
1003
1004     if (!frame)
1005         return NULL;
1006
1007 FF_DISABLE_DEPRECATION_WARNINGS
1008     avcodec_get_frame_defaults(frame);
1009 FF_ENABLE_DEPRECATION_WARNINGS
1010
1011     return frame;
1012 }
1013
1014 void avcodec_free_frame(AVFrame **frame)
1015 {
1016     av_frame_free(frame);
1017 }
1018 #endif
1019
1020 int attribute_align_arg avcodec_open2(AVCodecContext *avctx, const AVCodec *codec, AVDictionary **options)
1021 {
1022     int ret = 0;
1023     AVDictionary *tmp = NULL;
1024
1025     if (avcodec_is_open(avctx))
1026         return 0;
1027
1028     if ((!codec && !avctx->codec)) {
1029         av_log(avctx, AV_LOG_ERROR, "No codec provided to avcodec_open2().\n");
1030         return AVERROR(EINVAL);
1031     }
1032     if ((codec && avctx->codec && codec != avctx->codec)) {
1033         av_log(avctx, AV_LOG_ERROR, "This AVCodecContext was allocated for %s, "
1034                                     "but %s passed to avcodec_open2().\n", avctx->codec->name, codec->name);
1035         return AVERROR(EINVAL);
1036     }
1037     if (!codec)
1038         codec = avctx->codec;
1039
1040     if (avctx->extradata_size < 0 || avctx->extradata_size >= FF_MAX_EXTRADATA_SIZE)
1041         return AVERROR(EINVAL);
1042
1043     if (options)
1044         av_dict_copy(&tmp, *options, 0);
1045
1046     /* If there is a user-supplied mutex locking routine, call it. */
1047     if (lockmgr_cb) {
1048         if ((*lockmgr_cb)(&codec_mutex, AV_LOCK_OBTAIN))
1049             return -1;
1050     }
1051
1052     entangled_thread_counter++;
1053     if (entangled_thread_counter != 1 &&
1054         !(codec->caps_internal & FF_CODEC_CAP_INIT_THREADSAFE)) {
1055         av_log(avctx, AV_LOG_ERROR,
1056                "Insufficient thread locking. At least %d threads are "
1057                "calling avcodec_open2() at the same time right now.\n",
1058                entangled_thread_counter);
1059         ret = -1;
1060         goto end;
1061     }
1062
1063     avctx->internal = av_mallocz(sizeof(AVCodecInternal));
1064     if (!avctx->internal) {
1065         ret = AVERROR(ENOMEM);
1066         goto end;
1067     }
1068
1069     avctx->internal->pool = av_mallocz(sizeof(*avctx->internal->pool));
1070     if (!avctx->internal->pool) {
1071         ret = AVERROR(ENOMEM);
1072         goto free_and_end;
1073     }
1074
1075     avctx->internal->to_free = av_frame_alloc();
1076     if (!avctx->internal->to_free) {
1077         ret = AVERROR(ENOMEM);
1078         goto free_and_end;
1079     }
1080
1081     if (codec->priv_data_size > 0) {
1082         if (!avctx->priv_data) {
1083             avctx->priv_data = av_mallocz(codec->priv_data_size);
1084             if (!avctx->priv_data) {
1085                 ret = AVERROR(ENOMEM);
1086                 goto end;
1087             }
1088             if (codec->priv_class) {
1089                 *(const AVClass **)avctx->priv_data = codec->priv_class;
1090                 av_opt_set_defaults(avctx->priv_data);
1091             }
1092         }
1093         if (codec->priv_class && (ret = av_opt_set_dict(avctx->priv_data, &tmp)) < 0)
1094             goto free_and_end;
1095     } else {
1096         avctx->priv_data = NULL;
1097     }
1098     if ((ret = av_opt_set_dict(avctx, &tmp)) < 0)
1099         goto free_and_end;
1100
1101     if (avctx->coded_width && avctx->coded_height && !avctx->width && !avctx->height)
1102         ret = ff_set_dimensions(avctx, avctx->coded_width, avctx->coded_height);
1103     else if (avctx->width && avctx->height)
1104         ret = ff_set_dimensions(avctx, avctx->width, avctx->height);
1105     if (ret < 0)
1106         goto free_and_end;
1107
1108     if ((avctx->coded_width || avctx->coded_height || avctx->width || avctx->height)
1109         && (  av_image_check_size(avctx->coded_width, avctx->coded_height, 0, avctx) < 0
1110            || av_image_check_size(avctx->width,       avctx->height,       0, avctx) < 0)) {
1111         av_log(avctx, AV_LOG_WARNING, "ignoring invalid width/height values\n");
1112         ff_set_dimensions(avctx, 0, 0);
1113     }
1114
1115     if (avctx->width > 0 && avctx->height > 0) {
1116         if (av_image_check_sar(avctx->width, avctx->height,
1117                                avctx->sample_aspect_ratio) < 0) {
1118             av_log(avctx, AV_LOG_WARNING, "ignoring invalid SAR: %u/%u\n",
1119                    avctx->sample_aspect_ratio.num,
1120                    avctx->sample_aspect_ratio.den);
1121             avctx->sample_aspect_ratio = (AVRational){ 0, 1 };
1122         }
1123     }
1124
1125     /* if the decoder init function was already called previously,
1126      * free the already allocated subtitle_header before overwriting it */
1127     if (av_codec_is_decoder(codec))
1128         av_freep(&avctx->subtitle_header);
1129
1130     if (avctx->channels > FF_SANE_NB_CHANNELS) {
1131         ret = AVERROR(EINVAL);
1132         goto free_and_end;
1133     }
1134
1135     avctx->codec = codec;
1136     if ((avctx->codec_type == AVMEDIA_TYPE_UNKNOWN || avctx->codec_type == codec->type) &&
1137         avctx->codec_id == AV_CODEC_ID_NONE) {
1138         avctx->codec_type = codec->type;
1139         avctx->codec_id   = codec->id;
1140     }
1141     if (avctx->codec_id != codec->id || (avctx->codec_type != codec->type
1142                                          && avctx->codec_type != AVMEDIA_TYPE_ATTACHMENT)) {
1143         av_log(avctx, AV_LOG_ERROR, "codec type or id mismatches\n");
1144         ret = AVERROR(EINVAL);
1145         goto free_and_end;
1146     }
1147     avctx->frame_number = 0;
1148
1149     if (avctx->codec->capabilities & CODEC_CAP_EXPERIMENTAL &&
1150         avctx->strict_std_compliance > FF_COMPLIANCE_EXPERIMENTAL) {
1151         ret = AVERROR_EXPERIMENTAL;
1152         goto free_and_end;
1153     }
1154
1155     if (avctx->codec_type == AVMEDIA_TYPE_AUDIO &&
1156         (!avctx->time_base.num || !avctx->time_base.den)) {
1157         avctx->time_base.num = 1;
1158         avctx->time_base.den = avctx->sample_rate;
1159     }
1160
1161     if (HAVE_THREADS) {
1162         ret = ff_thread_init(avctx);
1163         if (ret < 0) {
1164             goto free_and_end;
1165         }
1166     }
1167     if (!HAVE_THREADS && !(codec->capabilities & CODEC_CAP_AUTO_THREADS))
1168         avctx->thread_count = 1;
1169
1170     if (av_codec_is_encoder(avctx->codec)) {
1171         int i;
1172 #if FF_API_CODED_FRAME
1173 FF_DISABLE_DEPRECATION_WARNINGS
1174         avctx->coded_frame = av_frame_alloc();
1175         if (!avctx->coded_frame) {
1176             ret = AVERROR(ENOMEM);
1177             goto free_and_end;
1178         }
1179 FF_ENABLE_DEPRECATION_WARNINGS
1180 #endif
1181         if (avctx->codec->sample_fmts) {
1182             for (i = 0; avctx->codec->sample_fmts[i] != AV_SAMPLE_FMT_NONE; i++) {
1183                 if (avctx->sample_fmt == avctx->codec->sample_fmts[i])
1184                     break;
1185                 if (avctx->channels == 1 &&
1186                     av_get_planar_sample_fmt(avctx->sample_fmt) ==
1187                     av_get_planar_sample_fmt(avctx->codec->sample_fmts[i])) {
1188                     avctx->sample_fmt = avctx->codec->sample_fmts[i];
1189                     break;
1190                 }
1191             }
1192             if (avctx->codec->sample_fmts[i] == AV_SAMPLE_FMT_NONE) {
1193                 av_log(avctx, AV_LOG_ERROR, "Specified sample_fmt is not supported.\n");
1194                 ret = AVERROR(EINVAL);
1195                 goto free_and_end;
1196             }
1197         }
1198         if (avctx->codec->pix_fmts) {
1199             for (i = 0; avctx->codec->pix_fmts[i] != AV_PIX_FMT_NONE; i++)
1200                 if (avctx->pix_fmt == avctx->codec->pix_fmts[i])
1201                     break;
1202             if (avctx->codec->pix_fmts[i] == AV_PIX_FMT_NONE) {
1203                 av_log(avctx, AV_LOG_ERROR, "Specified pix_fmt is not supported\n");
1204                 ret = AVERROR(EINVAL);
1205                 goto free_and_end;
1206             }
1207             if (avctx->codec->pix_fmts[i] == AV_PIX_FMT_YUVJ420P ||
1208                 avctx->codec->pix_fmts[i] == AV_PIX_FMT_YUVJ422P ||
1209                 avctx->codec->pix_fmts[i] == AV_PIX_FMT_YUVJ440P ||
1210                 avctx->codec->pix_fmts[i] == AV_PIX_FMT_YUVJ444P)
1211                 avctx->color_range = AVCOL_RANGE_JPEG;
1212         }
1213         if (avctx->codec->supported_samplerates) {
1214             for (i = 0; avctx->codec->supported_samplerates[i] != 0; i++)
1215                 if (avctx->sample_rate == avctx->codec->supported_samplerates[i])
1216                     break;
1217             if (avctx->codec->supported_samplerates[i] == 0) {
1218                 av_log(avctx, AV_LOG_ERROR, "Specified sample_rate is not supported\n");
1219                 ret = AVERROR(EINVAL);
1220                 goto free_and_end;
1221             }
1222         }
1223         if (avctx->codec->channel_layouts) {
1224             if (!avctx->channel_layout) {
1225                 av_log(avctx, AV_LOG_WARNING, "channel_layout not specified\n");
1226             } else {
1227                 for (i = 0; avctx->codec->channel_layouts[i] != 0; i++)
1228                     if (avctx->channel_layout == avctx->codec->channel_layouts[i])
1229                         break;
1230                 if (avctx->codec->channel_layouts[i] == 0) {
1231                     av_log(avctx, AV_LOG_ERROR, "Specified channel_layout is not supported\n");
1232                     ret = AVERROR(EINVAL);
1233                     goto free_and_end;
1234                 }
1235             }
1236         }
1237         if (avctx->channel_layout && avctx->channels) {
1238             if (av_get_channel_layout_nb_channels(avctx->channel_layout) != avctx->channels) {
1239                 av_log(avctx, AV_LOG_ERROR, "channel layout does not match number of channels\n");
1240                 ret = AVERROR(EINVAL);
1241                 goto free_and_end;
1242             }
1243         } else if (avctx->channel_layout) {
1244             avctx->channels = av_get_channel_layout_nb_channels(avctx->channel_layout);
1245         }
1246
1247         if (!avctx->rc_initial_buffer_occupancy)
1248             avctx->rc_initial_buffer_occupancy = avctx->rc_buffer_size * 3 / 4;
1249     }
1250
1251     if (avctx->codec->init && !(avctx->active_thread_type & FF_THREAD_FRAME)) {
1252         ret = avctx->codec->init(avctx);
1253         if (ret < 0) {
1254             goto free_and_end;
1255         }
1256     }
1257
1258 #if FF_API_AUDIOENC_DELAY
1259     if (av_codec_is_encoder(avctx->codec))
1260         avctx->delay = avctx->initial_padding;
1261 #endif
1262
1263     if (av_codec_is_decoder(avctx->codec)) {
1264         /* validate channel layout from the decoder */
1265         if (avctx->channel_layout) {
1266             int channels = av_get_channel_layout_nb_channels(avctx->channel_layout);
1267             if (!avctx->channels)
1268                 avctx->channels = channels;
1269             else if (channels != avctx->channels) {
1270                 av_log(avctx, AV_LOG_WARNING,
1271                        "channel layout does not match number of channels\n");
1272                 avctx->channel_layout = 0;
1273             }
1274         }
1275         if (avctx->channels && avctx->channels < 0 ||
1276             avctx->channels > FF_SANE_NB_CHANNELS) {
1277             ret = AVERROR(EINVAL);
1278             goto free_and_end;
1279         }
1280
1281 #if FF_API_AVCTX_TIMEBASE
1282         if (avctx->framerate.num > 0 && avctx->framerate.den > 0)
1283             avctx->time_base = av_inv_q(avctx->framerate);
1284 #endif
1285     }
1286 end:
1287     entangled_thread_counter--;
1288
1289     /* Release any user-supplied mutex. */
1290     if (lockmgr_cb) {
1291         (*lockmgr_cb)(&codec_mutex, AV_LOCK_RELEASE);
1292     }
1293     if (options) {
1294         av_dict_free(options);
1295         *options = tmp;
1296     }
1297
1298     return ret;
1299 free_and_end:
1300     if (avctx->codec &&
1301         (avctx->codec->caps_internal & FF_CODEC_CAP_INIT_CLEANUP))
1302         avctx->codec->close(avctx);
1303
1304     if (avctx->priv_data && avctx->codec && avctx->codec->priv_class)
1305         av_opt_free(avctx->priv_data);
1306     av_opt_free(avctx);
1307
1308 #if FF_API_CODED_FRAME
1309 FF_DISABLE_DEPRECATION_WARNINGS
1310     av_frame_free(&avctx->coded_frame);
1311 FF_ENABLE_DEPRECATION_WARNINGS
1312 #endif
1313
1314     av_dict_free(&tmp);
1315     av_freep(&avctx->priv_data);
1316     if (avctx->internal) {
1317         av_frame_free(&avctx->internal->to_free);
1318         av_freep(&avctx->internal->pool);
1319     }
1320     av_freep(&avctx->internal);
1321     avctx->codec = NULL;
1322     goto end;
1323 }
1324
1325 int ff_alloc_packet(AVPacket *avpkt, int size)
1326 {
1327     if (size > INT_MAX - FF_INPUT_BUFFER_PADDING_SIZE)
1328         return AVERROR(EINVAL);
1329
1330     if (avpkt->data) {
1331         AVBufferRef *buf = avpkt->buf;
1332 #if FF_API_DESTRUCT_PACKET
1333 FF_DISABLE_DEPRECATION_WARNINGS
1334         void *destruct = avpkt->destruct;
1335 FF_ENABLE_DEPRECATION_WARNINGS
1336 #endif
1337
1338         if (avpkt->size < size)
1339             return AVERROR(EINVAL);
1340
1341         av_init_packet(avpkt);
1342 #if FF_API_DESTRUCT_PACKET
1343 FF_DISABLE_DEPRECATION_WARNINGS
1344         avpkt->destruct = destruct;
1345 FF_ENABLE_DEPRECATION_WARNINGS
1346 #endif
1347         avpkt->buf      = buf;
1348         avpkt->size     = size;
1349         return 0;
1350     } else {
1351         return av_new_packet(avpkt, size);
1352     }
1353 }
1354
1355 /**
1356  * Pad last frame with silence.
1357  */
1358 static int pad_last_frame(AVCodecContext *s, AVFrame **dst, const AVFrame *src)
1359 {
1360     AVFrame *frame = NULL;
1361     int ret;
1362
1363     if (!(frame = av_frame_alloc()))
1364         return AVERROR(ENOMEM);
1365
1366     frame->format         = src->format;
1367     frame->channel_layout = src->channel_layout;
1368     frame->nb_samples     = s->frame_size;
1369     ret = av_frame_get_buffer(frame, 32);
1370     if (ret < 0)
1371         goto fail;
1372
1373     ret = av_frame_copy_props(frame, src);
1374     if (ret < 0)
1375         goto fail;
1376
1377     if ((ret = av_samples_copy(frame->extended_data, src->extended_data, 0, 0,
1378                                src->nb_samples, s->channels, s->sample_fmt)) < 0)
1379         goto fail;
1380     if ((ret = av_samples_set_silence(frame->extended_data, src->nb_samples,
1381                                       frame->nb_samples - src->nb_samples,
1382                                       s->channels, s->sample_fmt)) < 0)
1383         goto fail;
1384
1385     *dst = frame;
1386
1387     return 0;
1388
1389 fail:
1390     av_frame_free(&frame);
1391     return ret;
1392 }
1393
1394 int attribute_align_arg avcodec_encode_audio2(AVCodecContext *avctx,
1395                                               AVPacket *avpkt,
1396                                               const AVFrame *frame,
1397                                               int *got_packet_ptr)
1398 {
1399     AVFrame tmp;
1400     AVFrame *padded_frame = NULL;
1401     int ret;
1402     int user_packet = !!avpkt->data;
1403
1404     *got_packet_ptr = 0;
1405
1406     if (!(avctx->codec->capabilities & CODEC_CAP_DELAY) && !frame) {
1407         av_free_packet(avpkt);
1408         av_init_packet(avpkt);
1409         return 0;
1410     }
1411
1412     /* ensure that extended_data is properly set */
1413     if (frame && !frame->extended_data) {
1414         if (av_sample_fmt_is_planar(avctx->sample_fmt) &&
1415             avctx->channels > AV_NUM_DATA_POINTERS) {
1416             av_log(avctx, AV_LOG_ERROR, "Encoding to a planar sample format, "
1417                                         "with more than %d channels, but extended_data is not set.\n",
1418                    AV_NUM_DATA_POINTERS);
1419             return AVERROR(EINVAL);
1420         }
1421         av_log(avctx, AV_LOG_WARNING, "extended_data is not set.\n");
1422
1423         tmp = *frame;
1424         tmp.extended_data = tmp.data;
1425         frame = &tmp;
1426     }
1427
1428     /* extract audio service type metadata */
1429     if (frame) {
1430         AVFrameSideData *sd = av_frame_get_side_data(frame, AV_FRAME_DATA_AUDIO_SERVICE_TYPE);
1431         if (sd && sd->size >= sizeof(enum AVAudioServiceType))
1432             avctx->audio_service_type = *(enum AVAudioServiceType*)sd->data;
1433     }
1434
1435     /* check for valid frame size */
1436     if (frame) {
1437         if (avctx->codec->capabilities & CODEC_CAP_SMALL_LAST_FRAME) {
1438             if (frame->nb_samples > avctx->frame_size)
1439                 return AVERROR(EINVAL);
1440         } else if (!(avctx->codec->capabilities & CODEC_CAP_VARIABLE_FRAME_SIZE)) {
1441             if (frame->nb_samples < avctx->frame_size &&
1442                 !avctx->internal->last_audio_frame) {
1443                 ret = pad_last_frame(avctx, &padded_frame, frame);
1444                 if (ret < 0)
1445                     return ret;
1446
1447                 frame = padded_frame;
1448                 avctx->internal->last_audio_frame = 1;
1449             }
1450
1451             if (frame->nb_samples != avctx->frame_size) {
1452                 ret = AVERROR(EINVAL);
1453                 goto end;
1454             }
1455         }
1456     }
1457
1458     ret = avctx->codec->encode2(avctx, avpkt, frame, got_packet_ptr);
1459     if (!ret) {
1460         if (*got_packet_ptr) {
1461             if (!(avctx->codec->capabilities & CODEC_CAP_DELAY)) {
1462                 if (avpkt->pts == AV_NOPTS_VALUE)
1463                     avpkt->pts = frame->pts;
1464                 if (!avpkt->duration)
1465                     avpkt->duration = ff_samples_to_time_base(avctx,
1466                                                               frame->nb_samples);
1467             }
1468             avpkt->dts = avpkt->pts;
1469         } else {
1470             avpkt->size = 0;
1471         }
1472
1473         if (!user_packet && avpkt->size) {
1474             ret = av_buffer_realloc(&avpkt->buf, avpkt->size);
1475             if (ret >= 0)
1476                 avpkt->data = avpkt->buf->data;
1477         }
1478
1479         avctx->frame_number++;
1480     }
1481
1482     if (ret < 0 || !*got_packet_ptr) {
1483         av_free_packet(avpkt);
1484         av_init_packet(avpkt);
1485         goto end;
1486     }
1487
1488     /* NOTE: if we add any audio encoders which output non-keyframe packets,
1489      *       this needs to be moved to the encoders, but for now we can do it
1490      *       here to simplify things */
1491     avpkt->flags |= AV_PKT_FLAG_KEY;
1492
1493 end:
1494     av_frame_free(&padded_frame);
1495
1496 #if FF_API_AUDIOENC_DELAY
1497     avctx->delay = avctx->initial_padding;
1498 #endif
1499
1500     return ret;
1501 }
1502
1503 int attribute_align_arg avcodec_encode_video2(AVCodecContext *avctx,
1504                                               AVPacket *avpkt,
1505                                               const AVFrame *frame,
1506                                               int *got_packet_ptr)
1507 {
1508     int ret;
1509     int user_packet = !!avpkt->data;
1510
1511     *got_packet_ptr = 0;
1512
1513     if (!(avctx->codec->capabilities & CODEC_CAP_DELAY) && !frame) {
1514         av_free_packet(avpkt);
1515         av_init_packet(avpkt);
1516         avpkt->size = 0;
1517         return 0;
1518     }
1519
1520     if (av_image_check_size(avctx->width, avctx->height, 0, avctx))
1521         return AVERROR(EINVAL);
1522
1523     av_assert0(avctx->codec->encode2);
1524
1525     ret = avctx->codec->encode2(avctx, avpkt, frame, got_packet_ptr);
1526     if (!ret) {
1527         if (!*got_packet_ptr)
1528             avpkt->size = 0;
1529         else if (!(avctx->codec->capabilities & CODEC_CAP_DELAY))
1530             avpkt->pts = avpkt->dts = frame->pts;
1531
1532         if (!user_packet && avpkt->size) {
1533             ret = av_buffer_realloc(&avpkt->buf, avpkt->size);
1534             if (ret >= 0)
1535                 avpkt->data = avpkt->buf->data;
1536         }
1537
1538         avctx->frame_number++;
1539     }
1540
1541     if (ret < 0 || !*got_packet_ptr)
1542         av_free_packet(avpkt);
1543
1544     emms_c();
1545     return ret;
1546 }
1547
1548 int avcodec_encode_subtitle(AVCodecContext *avctx, uint8_t *buf, int buf_size,
1549                             const AVSubtitle *sub)
1550 {
1551     int ret;
1552     if (sub->start_display_time) {
1553         av_log(avctx, AV_LOG_ERROR, "start_display_time must be 0.\n");
1554         return -1;
1555     }
1556     if (sub->num_rects == 0 || !sub->rects)
1557         return -1;
1558     ret = avctx->codec->encode_sub(avctx, buf, buf_size, sub);
1559     avctx->frame_number++;
1560     return ret;
1561 }
1562
1563 static int apply_param_change(AVCodecContext *avctx, AVPacket *avpkt)
1564 {
1565     int size = 0, ret;
1566     const uint8_t *data;
1567     uint32_t flags;
1568
1569     data = av_packet_get_side_data(avpkt, AV_PKT_DATA_PARAM_CHANGE, &size);
1570     if (!data)
1571         return 0;
1572
1573     if (!(avctx->codec->capabilities & CODEC_CAP_PARAM_CHANGE)) {
1574         av_log(avctx, AV_LOG_ERROR, "This decoder does not support parameter "
1575                "changes, but PARAM_CHANGE side data was sent to it.\n");
1576         return AVERROR(EINVAL);
1577     }
1578
1579     if (size < 4)
1580         goto fail;
1581
1582     flags = bytestream_get_le32(&data);
1583     size -= 4;
1584
1585     if (flags & AV_SIDE_DATA_PARAM_CHANGE_CHANNEL_COUNT) {
1586         if (size < 4)
1587             goto fail;
1588         avctx->channels = bytestream_get_le32(&data);
1589         size -= 4;
1590     }
1591     if (flags & AV_SIDE_DATA_PARAM_CHANGE_CHANNEL_LAYOUT) {
1592         if (size < 8)
1593             goto fail;
1594         avctx->channel_layout = bytestream_get_le64(&data);
1595         size -= 8;
1596     }
1597     if (flags & AV_SIDE_DATA_PARAM_CHANGE_SAMPLE_RATE) {
1598         if (size < 4)
1599             goto fail;
1600         avctx->sample_rate = bytestream_get_le32(&data);
1601         size -= 4;
1602     }
1603     if (flags & AV_SIDE_DATA_PARAM_CHANGE_DIMENSIONS) {
1604         if (size < 8)
1605             goto fail;
1606         avctx->width  = bytestream_get_le32(&data);
1607         avctx->height = bytestream_get_le32(&data);
1608         size -= 8;
1609         ret = ff_set_dimensions(avctx, avctx->width, avctx->height);
1610         if (ret < 0)
1611             return ret;
1612     }
1613
1614     return 0;
1615 fail:
1616     av_log(avctx, AV_LOG_ERROR, "PARAM_CHANGE side data too small.\n");
1617     return AVERROR_INVALIDDATA;
1618 }
1619
1620 static int unrefcount_frame(AVCodecInternal *avci, AVFrame *frame)
1621 {
1622     int ret;
1623
1624     /* move the original frame to our backup */
1625     av_frame_unref(avci->to_free);
1626     av_frame_move_ref(avci->to_free, frame);
1627
1628     /* now copy everything except the AVBufferRefs back
1629      * note that we make a COPY of the side data, so calling av_frame_free() on
1630      * the caller's frame will work properly */
1631     ret = av_frame_copy_props(frame, avci->to_free);
1632     if (ret < 0)
1633         return ret;
1634
1635     memcpy(frame->data,     avci->to_free->data,     sizeof(frame->data));
1636     memcpy(frame->linesize, avci->to_free->linesize, sizeof(frame->linesize));
1637     if (avci->to_free->extended_data != avci->to_free->data) {
1638         int planes = av_get_channel_layout_nb_channels(avci->to_free->channel_layout);
1639         int size   = planes * sizeof(*frame->extended_data);
1640
1641         if (!size) {
1642             av_frame_unref(frame);
1643             return AVERROR_BUG;
1644         }
1645
1646         frame->extended_data = av_malloc(size);
1647         if (!frame->extended_data) {
1648             av_frame_unref(frame);
1649             return AVERROR(ENOMEM);
1650         }
1651         memcpy(frame->extended_data, avci->to_free->extended_data,
1652                size);
1653     } else
1654         frame->extended_data = frame->data;
1655
1656     frame->format         = avci->to_free->format;
1657     frame->width          = avci->to_free->width;
1658     frame->height         = avci->to_free->height;
1659     frame->channel_layout = avci->to_free->channel_layout;
1660     frame->nb_samples     = avci->to_free->nb_samples;
1661
1662     return 0;
1663 }
1664
1665 int attribute_align_arg avcodec_decode_video2(AVCodecContext *avctx, AVFrame *picture,
1666                                               int *got_picture_ptr,
1667                                               AVPacket *avpkt)
1668 {
1669     AVCodecInternal *avci = avctx->internal;
1670     int ret;
1671
1672     *got_picture_ptr = 0;
1673     if ((avctx->coded_width || avctx->coded_height) && av_image_check_size(avctx->coded_width, avctx->coded_height, 0, avctx))
1674         return -1;
1675
1676     avctx->internal->pkt = avpkt;
1677     ret = apply_param_change(avctx, avpkt);
1678     if (ret < 0) {
1679         av_log(avctx, AV_LOG_ERROR, "Error applying parameter changes.\n");
1680         if (avctx->err_recognition & AV_EF_EXPLODE)
1681             return ret;
1682     }
1683
1684     av_frame_unref(picture);
1685
1686     if ((avctx->codec->capabilities & CODEC_CAP_DELAY) || avpkt->size || (avctx->active_thread_type & FF_THREAD_FRAME)) {
1687         if (HAVE_THREADS && avctx->active_thread_type & FF_THREAD_FRAME)
1688             ret = ff_thread_decode_frame(avctx, picture, got_picture_ptr,
1689                                          avpkt);
1690         else {
1691             ret = avctx->codec->decode(avctx, picture, got_picture_ptr,
1692                                        avpkt);
1693             picture->pkt_dts = avpkt->dts;
1694             /* get_buffer is supposed to set frame parameters */
1695             if (!(avctx->codec->capabilities & CODEC_CAP_DR1)) {
1696                 picture->sample_aspect_ratio = avctx->sample_aspect_ratio;
1697                 picture->width               = avctx->width;
1698                 picture->height              = avctx->height;
1699                 picture->format              = avctx->pix_fmt;
1700             }
1701         }
1702
1703         emms_c(); //needed to avoid an emms_c() call before every return;
1704
1705         if (*got_picture_ptr) {
1706             if (!avctx->refcounted_frames) {
1707                 int err = unrefcount_frame(avci, picture);
1708                 if (err < 0)
1709                     return err;
1710             }
1711
1712             avctx->frame_number++;
1713         } else
1714             av_frame_unref(picture);
1715     } else
1716         ret = 0;
1717
1718 #if FF_API_AVCTX_TIMEBASE
1719     if (avctx->framerate.num > 0 && avctx->framerate.den > 0)
1720         avctx->time_base = av_inv_q(avctx->framerate);
1721 #endif
1722
1723     return ret;
1724 }
1725
1726 int attribute_align_arg avcodec_decode_audio4(AVCodecContext *avctx,
1727                                               AVFrame *frame,
1728                                               int *got_frame_ptr,
1729                                               AVPacket *avpkt)
1730 {
1731     AVCodecInternal *avci = avctx->internal;
1732     int ret = 0;
1733
1734     *got_frame_ptr = 0;
1735
1736     avctx->internal->pkt = avpkt;
1737
1738     if (!avpkt->data && avpkt->size) {
1739         av_log(avctx, AV_LOG_ERROR, "invalid packet: NULL data, size != 0\n");
1740         return AVERROR(EINVAL);
1741     }
1742
1743     ret = apply_param_change(avctx, avpkt);
1744     if (ret < 0) {
1745         av_log(avctx, AV_LOG_ERROR, "Error applying parameter changes.\n");
1746         if (avctx->err_recognition & AV_EF_EXPLODE)
1747             return ret;
1748     }
1749
1750     av_frame_unref(frame);
1751
1752     if ((avctx->codec->capabilities & CODEC_CAP_DELAY) || avpkt->size) {
1753         ret = avctx->codec->decode(avctx, frame, got_frame_ptr, avpkt);
1754         if (ret >= 0 && *got_frame_ptr) {
1755             avctx->frame_number++;
1756             frame->pkt_dts = avpkt->dts;
1757             if (frame->format == AV_SAMPLE_FMT_NONE)
1758                 frame->format = avctx->sample_fmt;
1759
1760             if (!avctx->refcounted_frames) {
1761                 int err = unrefcount_frame(avci, frame);
1762                 if (err < 0)
1763                     return err;
1764             }
1765         } else
1766             av_frame_unref(frame);
1767     }
1768
1769
1770     return ret;
1771 }
1772
1773 int avcodec_decode_subtitle2(AVCodecContext *avctx, AVSubtitle *sub,
1774                              int *got_sub_ptr,
1775                              AVPacket *avpkt)
1776 {
1777     int ret;
1778
1779     avctx->internal->pkt = avpkt;
1780     *got_sub_ptr = 0;
1781     ret = avctx->codec->decode(avctx, sub, got_sub_ptr, avpkt);
1782     if (*got_sub_ptr)
1783         avctx->frame_number++;
1784     return ret;
1785 }
1786
1787 void avsubtitle_free(AVSubtitle *sub)
1788 {
1789     int i;
1790
1791     for (i = 0; i < sub->num_rects; i++) {
1792         av_freep(&sub->rects[i]->pict.data[0]);
1793         av_freep(&sub->rects[i]->pict.data[1]);
1794         av_freep(&sub->rects[i]->pict.data[2]);
1795         av_freep(&sub->rects[i]->pict.data[3]);
1796         av_freep(&sub->rects[i]->text);
1797         av_freep(&sub->rects[i]->ass);
1798         av_freep(&sub->rects[i]);
1799     }
1800
1801     av_freep(&sub->rects);
1802
1803     memset(sub, 0, sizeof(AVSubtitle));
1804 }
1805
1806 av_cold int avcodec_close(AVCodecContext *avctx)
1807 {
1808     if (avcodec_is_open(avctx)) {
1809         FramePool *pool = avctx->internal->pool;
1810         int i;
1811         if (HAVE_THREADS && avctx->internal->thread_ctx)
1812             ff_thread_free(avctx);
1813         if (avctx->codec && avctx->codec->close)
1814             avctx->codec->close(avctx);
1815         av_frame_free(&avctx->internal->to_free);
1816         for (i = 0; i < FF_ARRAY_ELEMS(pool->pools); i++)
1817             av_buffer_pool_uninit(&pool->pools[i]);
1818         av_freep(&avctx->internal->pool);
1819
1820         if (avctx->hwaccel && avctx->hwaccel->uninit)
1821             avctx->hwaccel->uninit(avctx);
1822         av_freep(&avctx->internal->hwaccel_priv_data);
1823
1824         av_freep(&avctx->internal);
1825     }
1826
1827     if (avctx->priv_data && avctx->codec && avctx->codec->priv_class)
1828         av_opt_free(avctx->priv_data);
1829     av_opt_free(avctx);
1830     av_freep(&avctx->priv_data);
1831     if (av_codec_is_encoder(avctx->codec)) {
1832         av_freep(&avctx->extradata);
1833 #if FF_API_CODED_FRAME
1834 FF_DISABLE_DEPRECATION_WARNINGS
1835         av_frame_free(&avctx->coded_frame);
1836 FF_ENABLE_DEPRECATION_WARNINGS
1837 #endif
1838     }
1839     avctx->codec = NULL;
1840     avctx->active_thread_type = 0;
1841
1842     return 0;
1843 }
1844
1845 static AVCodec *find_encdec(enum AVCodecID id, int encoder)
1846 {
1847     AVCodec *p, *experimental = NULL;
1848     p = first_avcodec;
1849     while (p) {
1850         if ((encoder ? av_codec_is_encoder(p) : av_codec_is_decoder(p)) &&
1851             p->id == id) {
1852             if (p->capabilities & CODEC_CAP_EXPERIMENTAL && !experimental) {
1853                 experimental = p;
1854             } else
1855                 return p;
1856         }
1857         p = p->next;
1858     }
1859     return experimental;
1860 }
1861
1862 AVCodec *avcodec_find_encoder(enum AVCodecID id)
1863 {
1864     return find_encdec(id, 1);
1865 }
1866
1867 AVCodec *avcodec_find_encoder_by_name(const char *name)
1868 {
1869     AVCodec *p;
1870     if (!name)
1871         return NULL;
1872     p = first_avcodec;
1873     while (p) {
1874         if (av_codec_is_encoder(p) && strcmp(name, p->name) == 0)
1875             return p;
1876         p = p->next;
1877     }
1878     return NULL;
1879 }
1880
1881 AVCodec *avcodec_find_decoder(enum AVCodecID id)
1882 {
1883     return find_encdec(id, 0);
1884 }
1885
1886 AVCodec *avcodec_find_decoder_by_name(const char *name)
1887 {
1888     AVCodec *p;
1889     if (!name)
1890         return NULL;
1891     p = first_avcodec;
1892     while (p) {
1893         if (av_codec_is_decoder(p) && strcmp(name, p->name) == 0)
1894             return p;
1895         p = p->next;
1896     }
1897     return NULL;
1898 }
1899
1900 static int get_bit_rate(AVCodecContext *ctx)
1901 {
1902     int bit_rate;
1903     int bits_per_sample;
1904
1905     switch (ctx->codec_type) {
1906     case AVMEDIA_TYPE_VIDEO:
1907     case AVMEDIA_TYPE_DATA:
1908     case AVMEDIA_TYPE_SUBTITLE:
1909     case AVMEDIA_TYPE_ATTACHMENT:
1910         bit_rate = ctx->bit_rate;
1911         break;
1912     case AVMEDIA_TYPE_AUDIO:
1913         bits_per_sample = av_get_bits_per_sample(ctx->codec_id);
1914         bit_rate = bits_per_sample ? ctx->sample_rate * ctx->channels * bits_per_sample : ctx->bit_rate;
1915         break;
1916     default:
1917         bit_rate = 0;
1918         break;
1919     }
1920     return bit_rate;
1921 }
1922
1923 size_t av_get_codec_tag_string(char *buf, size_t buf_size, unsigned int codec_tag)
1924 {
1925     int i, len, ret = 0;
1926
1927 #define TAG_PRINT(x)                                              \
1928     (((x) >= '0' && (x) <= '9') ||                                \
1929      ((x) >= 'a' && (x) <= 'z') || ((x) >= 'A' && (x) <= 'Z') ||  \
1930      ((x) == '.' || (x) == ' '))
1931
1932     for (i = 0; i < 4; i++) {
1933         len = snprintf(buf, buf_size,
1934                        TAG_PRINT(codec_tag & 0xFF) ? "%c" : "[%d]", codec_tag & 0xFF);
1935         buf        += len;
1936         buf_size    = buf_size > len ? buf_size - len : 0;
1937         ret        += len;
1938         codec_tag >>= 8;
1939     }
1940     return ret;
1941 }
1942
1943 void avcodec_string(char *buf, int buf_size, AVCodecContext *enc, int encode)
1944 {
1945     const char *codec_name;
1946     const char *profile = NULL;
1947     const AVCodec *p;
1948     char buf1[32];
1949     int bitrate;
1950     int new_line = 0;
1951     AVRational display_aspect_ratio;
1952
1953     if (enc->codec)
1954         p = enc->codec;
1955     else if (encode)
1956         p = avcodec_find_encoder(enc->codec_id);
1957     else
1958         p = avcodec_find_decoder(enc->codec_id);
1959
1960     if (p) {
1961         codec_name = p->name;
1962         profile = av_get_profile_name(p, enc->profile);
1963     } else if (enc->codec_id == AV_CODEC_ID_MPEG2TS) {
1964         /* fake mpeg2 transport stream codec (currently not
1965          * registered) */
1966         codec_name = "mpeg2ts";
1967     } else {
1968         /* output avi tags */
1969         char tag_buf[32];
1970         av_get_codec_tag_string(tag_buf, sizeof(tag_buf), enc->codec_tag);
1971         snprintf(buf1, sizeof(buf1), "%s / 0x%04X", tag_buf, enc->codec_tag);
1972         codec_name = buf1;
1973     }
1974
1975     switch (enc->codec_type) {
1976     case AVMEDIA_TYPE_VIDEO:
1977         snprintf(buf, buf_size,
1978                  "Video: %s%s",
1979                  codec_name, enc->mb_decision ? " (hq)" : "");
1980         if (profile)
1981             snprintf(buf + strlen(buf), buf_size - strlen(buf),
1982                      " (%s)", profile);
1983         if (enc->codec_tag) {
1984             char tag_buf[32];
1985             av_get_codec_tag_string(tag_buf, sizeof(tag_buf), enc->codec_tag);
1986             snprintf(buf + strlen(buf), buf_size - strlen(buf),
1987                      " [%s / 0x%04X]", tag_buf, enc->codec_tag);
1988         }
1989
1990         av_strlcat(buf, "\n      ", buf_size);
1991         snprintf(buf + strlen(buf), buf_size - strlen(buf),
1992                  "%s", enc->pix_fmt == AV_PIX_FMT_NONE ? "none" :
1993                      av_get_pix_fmt_name(enc->pix_fmt));
1994
1995         if (enc->color_range != AVCOL_RANGE_UNSPECIFIED)
1996             snprintf(buf + strlen(buf), buf_size - strlen(buf), ", %s",
1997                      av_color_range_name(enc->color_range));
1998         if (enc->colorspace != AVCOL_SPC_UNSPECIFIED ||
1999             enc->color_primaries != AVCOL_PRI_UNSPECIFIED ||
2000             enc->color_trc != AVCOL_TRC_UNSPECIFIED) {
2001             new_line = 1;
2002             snprintf(buf + strlen(buf), buf_size - strlen(buf), ", %s/%s/%s",
2003                      av_color_space_name(enc->colorspace),
2004                      av_color_primaries_name(enc->color_primaries),
2005                      av_color_transfer_name(enc->color_trc));
2006         }
2007         if (av_log_get_level() >= AV_LOG_DEBUG &&
2008             enc->chroma_sample_location != AVCHROMA_LOC_UNSPECIFIED)
2009             snprintf(buf + strlen(buf), buf_size - strlen(buf), ", %s",
2010                      av_chroma_location_name(enc->chroma_sample_location));
2011
2012         if (enc->width) {
2013             av_strlcat(buf, new_line ? "\n      " : ", ", buf_size);
2014
2015             snprintf(buf + strlen(buf), buf_size - strlen(buf),
2016                      "%dx%d",
2017                      enc->width, enc->height);
2018
2019             if (av_log_get_level() >= AV_LOG_VERBOSE &&
2020                 (enc->width != enc->coded_width ||
2021                  enc->height != enc->coded_height))
2022                 snprintf(buf + strlen(buf), buf_size - strlen(buf),
2023                          " (%dx%d)", enc->coded_width, enc->coded_height);
2024
2025             if (enc->sample_aspect_ratio.num) {
2026                 av_reduce(&display_aspect_ratio.num, &display_aspect_ratio.den,
2027                           enc->width * enc->sample_aspect_ratio.num,
2028                           enc->height * enc->sample_aspect_ratio.den,
2029                           1024 * 1024);
2030                 snprintf(buf + strlen(buf), buf_size - strlen(buf),
2031                          " [PAR %d:%d DAR %d:%d]",
2032                          enc->sample_aspect_ratio.num, enc->sample_aspect_ratio.den,
2033                          display_aspect_ratio.num, display_aspect_ratio.den);
2034             }
2035             if (av_log_get_level() >= AV_LOG_DEBUG) {
2036                 int g = av_gcd(enc->time_base.num, enc->time_base.den);
2037                 snprintf(buf + strlen(buf), buf_size - strlen(buf),
2038                          ", %d/%d",
2039                          enc->time_base.num / g, enc->time_base.den / g);
2040             }
2041         }
2042         if (encode) {
2043             snprintf(buf + strlen(buf), buf_size - strlen(buf),
2044                      ", q=%d-%d", enc->qmin, enc->qmax);
2045         }
2046         break;
2047     case AVMEDIA_TYPE_AUDIO:
2048         snprintf(buf, buf_size,
2049                  "Audio: %s",
2050                  codec_name);
2051         if (profile)
2052             snprintf(buf + strlen(buf), buf_size - strlen(buf),
2053                      " (%s)", profile);
2054         if (enc->codec_tag) {
2055             char tag_buf[32];
2056             av_get_codec_tag_string(tag_buf, sizeof(tag_buf), enc->codec_tag);
2057             snprintf(buf + strlen(buf), buf_size - strlen(buf),
2058                      " [%s / 0x%04X]", tag_buf, enc->codec_tag);
2059         }
2060
2061         av_strlcat(buf, "\n      ", buf_size);
2062         if (enc->sample_rate) {
2063             snprintf(buf + strlen(buf), buf_size - strlen(buf),
2064                      "%d Hz, ", enc->sample_rate);
2065         }
2066         av_get_channel_layout_string(buf + strlen(buf), buf_size - strlen(buf), enc->channels, enc->channel_layout);
2067         if (enc->sample_fmt != AV_SAMPLE_FMT_NONE) {
2068             snprintf(buf + strlen(buf), buf_size - strlen(buf),
2069                      ", %s", av_get_sample_fmt_name(enc->sample_fmt));
2070         }
2071         break;
2072     case AVMEDIA_TYPE_DATA:
2073         snprintf(buf, buf_size, "Data: %s", codec_name);
2074         break;
2075     case AVMEDIA_TYPE_SUBTITLE:
2076         snprintf(buf, buf_size, "Subtitle: %s", codec_name);
2077         break;
2078     case AVMEDIA_TYPE_ATTACHMENT:
2079         snprintf(buf, buf_size, "Attachment: %s", codec_name);
2080         break;
2081     default:
2082         snprintf(buf, buf_size, "Invalid Codec type %d", enc->codec_type);
2083         return;
2084     }
2085     if (encode) {
2086         if (enc->flags & CODEC_FLAG_PASS1)
2087             snprintf(buf + strlen(buf), buf_size - strlen(buf),
2088                      ", pass 1");
2089         if (enc->flags & CODEC_FLAG_PASS2)
2090             snprintf(buf + strlen(buf), buf_size - strlen(buf),
2091                      ", pass 2");
2092     }
2093     bitrate = get_bit_rate(enc);
2094     if (bitrate != 0) {
2095         snprintf(buf + strlen(buf), buf_size - strlen(buf),
2096                  ", %d kb/s", bitrate / 1000);
2097     }
2098 }
2099
2100 const char *av_get_profile_name(const AVCodec *codec, int profile)
2101 {
2102     const AVProfile *p;
2103     if (profile == FF_PROFILE_UNKNOWN || !codec->profiles)
2104         return NULL;
2105
2106     for (p = codec->profiles; p->profile != FF_PROFILE_UNKNOWN; p++)
2107         if (p->profile == profile)
2108             return p->name;
2109
2110     return NULL;
2111 }
2112
2113 unsigned avcodec_version(void)
2114 {
2115     return LIBAVCODEC_VERSION_INT;
2116 }
2117
2118 const char *avcodec_configuration(void)
2119 {
2120     return LIBAV_CONFIGURATION;
2121 }
2122
2123 const char *avcodec_license(void)
2124 {
2125 #define LICENSE_PREFIX "libavcodec license: "
2126     return LICENSE_PREFIX LIBAV_LICENSE + sizeof(LICENSE_PREFIX) - 1;
2127 }
2128
2129 void avcodec_flush_buffers(AVCodecContext *avctx)
2130 {
2131     if (HAVE_THREADS && avctx->active_thread_type & FF_THREAD_FRAME)
2132         ff_thread_flush(avctx);
2133     else if (avctx->codec->flush)
2134         avctx->codec->flush(avctx);
2135
2136     if (!avctx->refcounted_frames)
2137         av_frame_unref(avctx->internal->to_free);
2138 }
2139
2140 int av_get_exact_bits_per_sample(enum AVCodecID codec_id)
2141 {
2142     switch (codec_id) {
2143     case AV_CODEC_ID_ADPCM_CT:
2144     case AV_CODEC_ID_ADPCM_IMA_APC:
2145     case AV_CODEC_ID_ADPCM_IMA_EA_SEAD:
2146     case AV_CODEC_ID_ADPCM_IMA_WS:
2147     case AV_CODEC_ID_ADPCM_G722:
2148     case AV_CODEC_ID_ADPCM_YAMAHA:
2149         return 4;
2150     case AV_CODEC_ID_PCM_ALAW:
2151     case AV_CODEC_ID_PCM_MULAW:
2152     case AV_CODEC_ID_PCM_S8:
2153     case AV_CODEC_ID_PCM_U8:
2154     case AV_CODEC_ID_PCM_ZORK:
2155         return 8;
2156     case AV_CODEC_ID_PCM_S16BE:
2157     case AV_CODEC_ID_PCM_S16BE_PLANAR:
2158     case AV_CODEC_ID_PCM_S16LE:
2159     case AV_CODEC_ID_PCM_S16LE_PLANAR:
2160     case AV_CODEC_ID_PCM_U16BE:
2161     case AV_CODEC_ID_PCM_U16LE:
2162         return 16;
2163     case AV_CODEC_ID_PCM_S24DAUD:
2164     case AV_CODEC_ID_PCM_S24BE:
2165     case AV_CODEC_ID_PCM_S24LE:
2166     case AV_CODEC_ID_PCM_S24LE_PLANAR:
2167     case AV_CODEC_ID_PCM_U24BE:
2168     case AV_CODEC_ID_PCM_U24LE:
2169         return 24;
2170     case AV_CODEC_ID_PCM_S32BE:
2171     case AV_CODEC_ID_PCM_S32LE:
2172     case AV_CODEC_ID_PCM_S32LE_PLANAR:
2173     case AV_CODEC_ID_PCM_U32BE:
2174     case AV_CODEC_ID_PCM_U32LE:
2175     case AV_CODEC_ID_PCM_F32BE:
2176     case AV_CODEC_ID_PCM_F32LE:
2177         return 32;
2178     case AV_CODEC_ID_PCM_F64BE:
2179     case AV_CODEC_ID_PCM_F64LE:
2180         return 64;
2181     default:
2182         return 0;
2183     }
2184 }
2185
2186 int av_get_bits_per_sample(enum AVCodecID codec_id)
2187 {
2188     switch (codec_id) {
2189     case AV_CODEC_ID_ADPCM_SBPRO_2:
2190         return 2;
2191     case AV_CODEC_ID_ADPCM_SBPRO_3:
2192         return 3;
2193     case AV_CODEC_ID_ADPCM_SBPRO_4:
2194     case AV_CODEC_ID_ADPCM_IMA_WAV:
2195     case AV_CODEC_ID_ADPCM_IMA_QT:
2196     case AV_CODEC_ID_ADPCM_SWF:
2197     case AV_CODEC_ID_ADPCM_MS:
2198         return 4;
2199     default:
2200         return av_get_exact_bits_per_sample(codec_id);
2201     }
2202 }
2203
2204 int av_get_audio_frame_duration(AVCodecContext *avctx, int frame_bytes)
2205 {
2206     int id, sr, ch, ba, tag, bps;
2207
2208     id  = avctx->codec_id;
2209     sr  = avctx->sample_rate;
2210     ch  = avctx->channels;
2211     ba  = avctx->block_align;
2212     tag = avctx->codec_tag;
2213     bps = av_get_exact_bits_per_sample(avctx->codec_id);
2214
2215     /* codecs with an exact constant bits per sample */
2216     if (bps > 0 && ch > 0 && frame_bytes > 0)
2217         return (frame_bytes * 8) / (bps * ch);
2218     bps = avctx->bits_per_coded_sample;
2219
2220     /* codecs with a fixed packet duration */
2221     switch (id) {
2222     case AV_CODEC_ID_ADPCM_ADX:    return   32;
2223     case AV_CODEC_ID_ADPCM_IMA_QT: return   64;
2224     case AV_CODEC_ID_ADPCM_EA_XAS: return  128;
2225     case AV_CODEC_ID_AMR_NB:
2226     case AV_CODEC_ID_GSM:
2227     case AV_CODEC_ID_QCELP:
2228     case AV_CODEC_ID_RA_144:
2229     case AV_CODEC_ID_RA_288:       return  160;
2230     case AV_CODEC_ID_IMC:          return  256;
2231     case AV_CODEC_ID_AMR_WB:
2232     case AV_CODEC_ID_GSM_MS:       return  320;
2233     case AV_CODEC_ID_MP1:          return  384;
2234     case AV_CODEC_ID_ATRAC1:       return  512;
2235     case AV_CODEC_ID_ATRAC3:       return 1024;
2236     case AV_CODEC_ID_MP2:
2237     case AV_CODEC_ID_MUSEPACK7:    return 1152;
2238     case AV_CODEC_ID_AC3:          return 1536;
2239     }
2240
2241     if (sr > 0) {
2242         /* calc from sample rate */
2243         if (id == AV_CODEC_ID_TTA)
2244             return 256 * sr / 245;
2245
2246         if (ch > 0) {
2247             /* calc from sample rate and channels */
2248             if (id == AV_CODEC_ID_BINKAUDIO_DCT)
2249                 return (480 << (sr / 22050)) / ch;
2250         }
2251     }
2252
2253     if (ba > 0) {
2254         /* calc from block_align */
2255         if (id == AV_CODEC_ID_SIPR) {
2256             switch (ba) {
2257             case 20: return 160;
2258             case 19: return 144;
2259             case 29: return 288;
2260             case 37: return 480;
2261             }
2262         } else if (id == AV_CODEC_ID_ILBC) {
2263             switch (ba) {
2264             case 38: return 160;
2265             case 50: return 240;
2266             }
2267         }
2268     }
2269
2270     if (frame_bytes > 0) {
2271         /* calc from frame_bytes only */
2272         if (id == AV_CODEC_ID_TRUESPEECH)
2273             return 240 * (frame_bytes / 32);
2274         if (id == AV_CODEC_ID_NELLYMOSER)
2275             return 256 * (frame_bytes / 64);
2276
2277         if (bps > 0) {
2278             /* calc from frame_bytes and bits_per_coded_sample */
2279             if (id == AV_CODEC_ID_ADPCM_G726)
2280                 return frame_bytes * 8 / bps;
2281         }
2282
2283         if (ch > 0) {
2284             /* calc from frame_bytes and channels */
2285             switch (id) {
2286             case AV_CODEC_ID_ADPCM_4XM:
2287             case AV_CODEC_ID_ADPCM_IMA_ISS:
2288                 return (frame_bytes - 4 * ch) * 2 / ch;
2289             case AV_CODEC_ID_ADPCM_IMA_SMJPEG:
2290                 return (frame_bytes - 4) * 2 / ch;
2291             case AV_CODEC_ID_ADPCM_IMA_AMV:
2292                 return (frame_bytes - 8) * 2 / ch;
2293             case AV_CODEC_ID_ADPCM_XA:
2294                 return (frame_bytes / 128) * 224 / ch;
2295             case AV_CODEC_ID_INTERPLAY_DPCM:
2296                 return (frame_bytes - 6 - ch) / ch;
2297             case AV_CODEC_ID_ROQ_DPCM:
2298                 return (frame_bytes - 8) / ch;
2299             case AV_CODEC_ID_XAN_DPCM:
2300                 return (frame_bytes - 2 * ch) / ch;
2301             case AV_CODEC_ID_MACE3:
2302                 return 3 * frame_bytes / ch;
2303             case AV_CODEC_ID_MACE6:
2304                 return 6 * frame_bytes / ch;
2305             case AV_CODEC_ID_PCM_LXF:
2306                 return 2 * (frame_bytes / (5 * ch));
2307             }
2308
2309             if (tag) {
2310                 /* calc from frame_bytes, channels, and codec_tag */
2311                 if (id == AV_CODEC_ID_SOL_DPCM) {
2312                     if (tag == 3)
2313                         return frame_bytes / ch;
2314                     else
2315                         return frame_bytes * 2 / ch;
2316                 }
2317             }
2318
2319             if (ba > 0) {
2320                 /* calc from frame_bytes, channels, and block_align */
2321                 int blocks = frame_bytes / ba;
2322                 switch (avctx->codec_id) {
2323                 case AV_CODEC_ID_ADPCM_IMA_WAV:
2324                     return blocks * (1 + (ba - 4 * ch) / (4 * ch) * 8);
2325                 case AV_CODEC_ID_ADPCM_IMA_DK3:
2326                     return blocks * (((ba - 16) * 2 / 3 * 4) / ch);
2327                 case AV_CODEC_ID_ADPCM_IMA_DK4:
2328                     return blocks * (1 + (ba - 4 * ch) * 2 / ch);
2329                 case AV_CODEC_ID_ADPCM_MS:
2330                     return blocks * (2 + (ba - 7 * ch) * 2 / ch);
2331                 }
2332             }
2333
2334             if (bps > 0) {
2335                 /* calc from frame_bytes, channels, and bits_per_coded_sample */
2336                 switch (avctx->codec_id) {
2337                 case AV_CODEC_ID_PCM_DVD:
2338                     return 2 * (frame_bytes / ((bps * 2 / 8) * ch));
2339                 case AV_CODEC_ID_PCM_BLURAY:
2340                     return frame_bytes / ((FFALIGN(ch, 2) * bps) / 8);
2341                 case AV_CODEC_ID_S302M:
2342                     return 2 * (frame_bytes / ((bps + 4) / 4)) / ch;
2343                 }
2344             }
2345         }
2346     }
2347
2348     return 0;
2349 }
2350
2351 #if !HAVE_THREADS
2352 int ff_thread_init(AVCodecContext *s)
2353 {
2354     return -1;
2355 }
2356
2357 #endif
2358
2359 unsigned int av_xiphlacing(unsigned char *s, unsigned int v)
2360 {
2361     unsigned int n = 0;
2362
2363     while (v >= 0xff) {
2364         *s++ = 0xff;
2365         v -= 0xff;
2366         n++;
2367     }
2368     *s = v;
2369     n++;
2370     return n;
2371 }
2372
2373 int ff_match_2uint16(const uint16_t(*tab)[2], int size, int a, int b)
2374 {
2375     int i;
2376     for (i = 0; i < size && !(tab[i][0] == a && tab[i][1] == b); i++) ;
2377     return i;
2378 }
2379
2380 #if FF_API_MISSING_SAMPLE
2381 FF_DISABLE_DEPRECATION_WARNINGS
2382 void av_log_missing_feature(void *avc, const char *feature, int want_sample)
2383 {
2384     av_log(avc, AV_LOG_WARNING, "%s is not implemented. Update your Libav "
2385             "version to the newest one from Git. If the problem still "
2386             "occurs, it means that your file has a feature which has not "
2387             "been implemented.\n", feature);
2388     if(want_sample)
2389         av_log_ask_for_sample(avc, NULL);
2390 }
2391
2392 void av_log_ask_for_sample(void *avc, const char *msg, ...)
2393 {
2394     va_list argument_list;
2395
2396     va_start(argument_list, msg);
2397
2398     if (msg)
2399         av_vlog(avc, AV_LOG_WARNING, msg, argument_list);
2400     av_log(avc, AV_LOG_WARNING, "If you want to help, upload a sample "
2401             "of this file to ftp://upload.libav.org/incoming/ "
2402             "and contact the libav-devel mailing list.\n");
2403
2404     va_end(argument_list);
2405 }
2406 FF_ENABLE_DEPRECATION_WARNINGS
2407 #endif /* FF_API_MISSING_SAMPLE */
2408
2409 static AVHWAccel *first_hwaccel = NULL;
2410
2411 void av_register_hwaccel(AVHWAccel *hwaccel)
2412 {
2413     AVHWAccel **p = &first_hwaccel;
2414     while (*p)
2415         p = &(*p)->next;
2416     *p = hwaccel;
2417     hwaccel->next = NULL;
2418 }
2419
2420 AVHWAccel *av_hwaccel_next(const AVHWAccel *hwaccel)
2421 {
2422     return hwaccel ? hwaccel->next : first_hwaccel;
2423 }
2424
2425 int av_lockmgr_register(int (*cb)(void **mutex, enum AVLockOp op))
2426 {
2427     if (lockmgr_cb) {
2428         // There is no good way to rollback a failure to destroy the
2429         // mutex, so we ignore failures.
2430         lockmgr_cb(&codec_mutex,    AV_LOCK_DESTROY);
2431         lockmgr_cb(&avformat_mutex, AV_LOCK_DESTROY);
2432         lockmgr_cb     = NULL;
2433         codec_mutex    = NULL;
2434         avformat_mutex = NULL;
2435     }
2436
2437     if (cb) {
2438         void *new_codec_mutex    = NULL;
2439         void *new_avformat_mutex = NULL;
2440         int err;
2441         if (err = cb(&new_codec_mutex, AV_LOCK_CREATE)) {
2442             return err > 0 ? AVERROR_UNKNOWN : err;
2443         }
2444         if (err = cb(&new_avformat_mutex, AV_LOCK_CREATE)) {
2445             // Ignore failures to destroy the newly created mutex.
2446             cb(&new_codec_mutex, AV_LOCK_DESTROY);
2447             return err > 0 ? AVERROR_UNKNOWN : err;
2448         }
2449         lockmgr_cb     = cb;
2450         codec_mutex    = new_codec_mutex;
2451         avformat_mutex = new_avformat_mutex;
2452     }
2453
2454     return 0;
2455 }
2456
2457 int avpriv_lock_avformat(void)
2458 {
2459     if (lockmgr_cb) {
2460         if ((*lockmgr_cb)(&avformat_mutex, AV_LOCK_OBTAIN))
2461             return -1;
2462     }
2463     return 0;
2464 }
2465
2466 int avpriv_unlock_avformat(void)
2467 {
2468     if (lockmgr_cb) {
2469         if ((*lockmgr_cb)(&avformat_mutex, AV_LOCK_RELEASE))
2470             return -1;
2471     }
2472     return 0;
2473 }
2474
2475 unsigned int avpriv_toupper4(unsigned int x)
2476 {
2477     return av_toupper(x & 0xFF) +
2478           (av_toupper((x >>  8) & 0xFF) << 8)  +
2479           (av_toupper((x >> 16) & 0xFF) << 16) +
2480           (av_toupper((x >> 24) & 0xFF) << 24);
2481 }
2482
2483 int ff_thread_ref_frame(ThreadFrame *dst, ThreadFrame *src)
2484 {
2485     int ret;
2486
2487     dst->owner = src->owner;
2488
2489     ret = av_frame_ref(dst->f, src->f);
2490     if (ret < 0)
2491         return ret;
2492
2493     if (src->progress &&
2494         !(dst->progress = av_buffer_ref(src->progress))) {
2495         ff_thread_release_buffer(dst->owner, dst);
2496         return AVERROR(ENOMEM);
2497     }
2498
2499     return 0;
2500 }
2501
2502 #if !HAVE_THREADS
2503
2504 int ff_thread_get_buffer(AVCodecContext *avctx, ThreadFrame *f, int flags)
2505 {
2506     f->owner = avctx;
2507     return ff_get_buffer(avctx, f->f, flags);
2508 }
2509
2510 void ff_thread_release_buffer(AVCodecContext *avctx, ThreadFrame *f)
2511 {
2512     if (f->f)
2513         av_frame_unref(f->f);
2514 }
2515
2516 void ff_thread_finish_setup(AVCodecContext *avctx)
2517 {
2518 }
2519
2520 void ff_thread_report_progress(ThreadFrame *f, int progress, int field)
2521 {
2522 }
2523
2524 void ff_thread_await_progress(ThreadFrame *f, int progress, int field)
2525 {
2526 }
2527
2528 #endif
2529
2530 enum AVMediaType avcodec_get_type(enum AVCodecID codec_id)
2531 {
2532     if (codec_id <= AV_CODEC_ID_NONE)
2533         return AVMEDIA_TYPE_UNKNOWN;
2534     else if (codec_id < AV_CODEC_ID_FIRST_AUDIO)
2535         return AVMEDIA_TYPE_VIDEO;
2536     else if (codec_id < AV_CODEC_ID_FIRST_SUBTITLE)
2537         return AVMEDIA_TYPE_AUDIO;
2538     else if (codec_id < AV_CODEC_ID_FIRST_UNKNOWN)
2539         return AVMEDIA_TYPE_SUBTITLE;
2540
2541     return AVMEDIA_TYPE_UNKNOWN;
2542 }
2543
2544 int avcodec_is_open(AVCodecContext *s)
2545 {
2546     return !!s->internal;
2547 }
2548
2549 const uint8_t *avpriv_find_start_code(const uint8_t *restrict p,
2550                                       const uint8_t *end,
2551                                       uint32_t * restrict state)
2552 {
2553     int i;
2554
2555     assert(p <= end);
2556     if (p >= end)
2557         return end;
2558
2559     for (i = 0; i < 3; i++) {
2560         uint32_t tmp = *state << 8;
2561         *state = tmp + *(p++);
2562         if (tmp == 0x100 || p == end)
2563             return p;
2564     }
2565
2566     while (p < end) {
2567         if      (p[-1] > 1      ) p += 3;
2568         else if (p[-2]          ) p += 2;
2569         else if (p[-3]|(p[-1]-1)) p++;
2570         else {
2571             p++;
2572             break;
2573         }
2574     }
2575
2576     p = FFMIN(p, end) - 4;
2577     *state = AV_RB32(p);
2578
2579     return p + 4;
2580 }