]> git.sesse.net Git - ffmpeg/blob - libavcodec/utils.c
h264: move intra4x4_pred_mode[_cache] into the per-slice context
[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_frame_unref(frame);                                          \
731         ret = AVERROR(ENOMEM);                                          \
732         goto fail;                                                      \
733     }                                                                   \
734 } while (0)
735
736         if (avctx->codec_type == AVMEDIA_TYPE_VIDEO) {
737             const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(frame->format);
738
739             planes = av_pix_fmt_count_planes(frame->format);
740             /* workaround for AVHWAccel plane count of 0, buf[0] is used as
741                check for allocated buffers: make libavcodec happy */
742             if (desc && desc->flags & AV_PIX_FMT_FLAG_HWACCEL)
743                 planes = 1;
744             if (!desc || planes <= 0) {
745                 ret = AVERROR(EINVAL);
746                 goto fail;
747             }
748
749             for (i = 0; i < planes; i++) {
750                 int v_shift    = (i == 1 || i == 2) ? desc->log2_chroma_h : 0;
751                 int plane_size = (frame->height >> v_shift) * frame->linesize[i];
752
753                 WRAP_PLANE(frame->buf[i], frame->data[i], plane_size);
754             }
755         } else {
756             int planar = av_sample_fmt_is_planar(frame->format);
757             planes = planar ? avctx->channels : 1;
758
759             if (planes > FF_ARRAY_ELEMS(frame->buf)) {
760                 frame->nb_extended_buf = planes - FF_ARRAY_ELEMS(frame->buf);
761                 frame->extended_buf = av_malloc(sizeof(*frame->extended_buf) *
762                                                 frame->nb_extended_buf);
763                 if (!frame->extended_buf) {
764                     ret = AVERROR(ENOMEM);
765                     goto fail;
766                 }
767             }
768
769             for (i = 0; i < FFMIN(planes, FF_ARRAY_ELEMS(frame->buf)); i++)
770                 WRAP_PLANE(frame->buf[i], frame->extended_data[i], frame->linesize[0]);
771
772             for (i = 0; i < frame->nb_extended_buf; i++)
773                 WRAP_PLANE(frame->extended_buf[i],
774                            frame->extended_data[i + FF_ARRAY_ELEMS(frame->buf)],
775                            frame->linesize[0]);
776         }
777
778         av_buffer_unref(&dummy_buf);
779
780         frame->width  = avctx->width;
781         frame->height = avctx->height;
782
783         return 0;
784
785 fail:
786         avctx->release_buffer(avctx, frame);
787         av_freep(&priv);
788         av_buffer_unref(&dummy_buf);
789         return ret;
790     }
791 FF_ENABLE_DEPRECATION_WARNINGS
792 #endif
793
794     ret = avctx->get_buffer2(avctx, frame, flags);
795
796 end:
797     if (avctx->codec_type == AVMEDIA_TYPE_VIDEO && !override_dimensions) {
798         frame->width  = avctx->width;
799         frame->height = avctx->height;
800     }
801
802     return ret;
803 }
804
805 int ff_reget_buffer(AVCodecContext *avctx, AVFrame *frame)
806 {
807     AVFrame *tmp;
808     int ret;
809
810     av_assert0(avctx->codec_type == AVMEDIA_TYPE_VIDEO);
811
812     if (!frame->data[0])
813         return ff_get_buffer(avctx, frame, AV_GET_BUFFER_FLAG_REF);
814
815     if (av_frame_is_writable(frame))
816         return ff_decode_frame_props(avctx, frame);
817
818     tmp = av_frame_alloc();
819     if (!tmp)
820         return AVERROR(ENOMEM);
821
822     av_frame_move_ref(tmp, frame);
823
824     ret = ff_get_buffer(avctx, frame, AV_GET_BUFFER_FLAG_REF);
825     if (ret < 0) {
826         av_frame_free(&tmp);
827         return ret;
828     }
829
830     av_frame_copy(frame, tmp);
831     av_frame_free(&tmp);
832
833     return 0;
834 }
835
836 #if FF_API_GET_BUFFER
837 void avcodec_default_release_buffer(AVCodecContext *s, AVFrame *pic)
838 {
839     av_frame_unref(pic);
840 }
841
842 int avcodec_default_reget_buffer(AVCodecContext *s, AVFrame *pic)
843 {
844     av_assert0(0);
845     return AVERROR_BUG;
846 }
847 #endif
848
849 int avcodec_default_execute(AVCodecContext *c, int (*func)(AVCodecContext *c2, void *arg2), void *arg, int *ret, int count, int size)
850 {
851     int i;
852
853     for (i = 0; i < count; i++) {
854         int r = func(c, (char *)arg + i * size);
855         if (ret)
856             ret[i] = r;
857     }
858     return 0;
859 }
860
861 int avcodec_default_execute2(AVCodecContext *c, int (*func)(AVCodecContext *c2, void *arg2, int jobnr, int threadnr), void *arg, int *ret, int count)
862 {
863     int i;
864
865     for (i = 0; i < count; i++) {
866         int r = func(c, arg, i, 0);
867         if (ret)
868             ret[i] = r;
869     }
870     return 0;
871 }
872
873 static int is_hwaccel_pix_fmt(enum AVPixelFormat pix_fmt)
874 {
875     const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(pix_fmt);
876     return desc->flags & AV_PIX_FMT_FLAG_HWACCEL;
877 }
878
879 enum AVPixelFormat avcodec_default_get_format(struct AVCodecContext *s, const enum AVPixelFormat *fmt)
880 {
881     while (*fmt != AV_PIX_FMT_NONE && is_hwaccel_pix_fmt(*fmt))
882         ++fmt;
883     return fmt[0];
884 }
885
886 static AVHWAccel *find_hwaccel(enum AVCodecID codec_id,
887                                enum AVPixelFormat pix_fmt)
888 {
889     AVHWAccel *hwaccel = NULL;
890
891     while ((hwaccel = av_hwaccel_next(hwaccel)))
892         if (hwaccel->id == codec_id
893             && hwaccel->pix_fmt == pix_fmt)
894             return hwaccel;
895     return NULL;
896 }
897
898 static int setup_hwaccel(AVCodecContext *avctx,
899                          const enum AVPixelFormat fmt,
900                          const char *name)
901 {
902     AVHWAccel *hwa = find_hwaccel(avctx->codec_id, fmt);
903     int ret        = 0;
904
905     if (!hwa) {
906         av_log(avctx, AV_LOG_ERROR,
907                "Could not find an AVHWAccel for the pixel format: %s",
908                name);
909         return AVERROR(ENOENT);
910     }
911
912     if (hwa->priv_data_size) {
913         avctx->internal->hwaccel_priv_data = av_mallocz(hwa->priv_data_size);
914         if (!avctx->internal->hwaccel_priv_data)
915             return AVERROR(ENOMEM);
916     }
917
918     if (hwa->init) {
919         ret = hwa->init(avctx);
920         if (ret < 0) {
921             av_freep(&avctx->internal->hwaccel_priv_data);
922             return ret;
923         }
924     }
925
926     avctx->hwaccel = hwa;
927
928     return 0;
929 }
930
931 int ff_get_format(AVCodecContext *avctx, const enum AVPixelFormat *fmt)
932 {
933     const AVPixFmtDescriptor *desc;
934     enum AVPixelFormat *choices;
935     enum AVPixelFormat ret;
936     unsigned n = 0;
937
938     while (fmt[n] != AV_PIX_FMT_NONE)
939         ++n;
940
941     av_assert0(n >= 1);
942     avctx->sw_pix_fmt = fmt[n - 1];
943     av_assert2(!is_hwaccel_pix_fmt(avctx->sw_pix_fmt));
944
945     choices = av_malloc_array(n + 1, sizeof(*choices));
946     if (!choices)
947         return AV_PIX_FMT_NONE;
948
949     memcpy(choices, fmt, (n + 1) * sizeof(*choices));
950
951     for (;;) {
952         if (avctx->hwaccel && avctx->hwaccel->uninit)
953             avctx->hwaccel->uninit(avctx);
954         av_freep(&avctx->internal->hwaccel_priv_data);
955         avctx->hwaccel = NULL;
956
957         ret = avctx->get_format(avctx, choices);
958
959         desc = av_pix_fmt_desc_get(ret);
960         if (!desc) {
961             ret = AV_PIX_FMT_NONE;
962             break;
963         }
964
965         if (!(desc->flags & AV_PIX_FMT_FLAG_HWACCEL))
966             break;
967
968         if (!setup_hwaccel(avctx, ret, desc->name))
969             break;
970
971         /* Remove failed hwaccel from choices */
972         for (n = 0; choices[n] != ret; n++)
973             av_assert0(choices[n] != AV_PIX_FMT_NONE);
974
975         do
976             choices[n] = choices[n + 1];
977         while (choices[n++] != AV_PIX_FMT_NONE);
978     }
979
980     av_freep(&choices);
981     return ret;
982 }
983
984 #if FF_API_AVFRAME_LAVC
985 void avcodec_get_frame_defaults(AVFrame *frame)
986 {
987     if (frame->extended_data != frame->data)
988         av_freep(&frame->extended_data);
989
990     memset(frame, 0, sizeof(AVFrame));
991
992     frame->pts                 = AV_NOPTS_VALUE;
993     frame->key_frame           = 1;
994     frame->sample_aspect_ratio = (AVRational) {0, 1 };
995     frame->format              = -1; /* unknown */
996     frame->extended_data       = frame->data;
997 }
998
999 AVFrame *avcodec_alloc_frame(void)
1000 {
1001     AVFrame *frame = av_mallocz(sizeof(AVFrame));
1002
1003     if (!frame)
1004         return NULL;
1005
1006 FF_DISABLE_DEPRECATION_WARNINGS
1007     avcodec_get_frame_defaults(frame);
1008 FF_ENABLE_DEPRECATION_WARNINGS
1009
1010     return frame;
1011 }
1012
1013 void avcodec_free_frame(AVFrame **frame)
1014 {
1015     av_frame_free(frame);
1016 }
1017 #endif
1018
1019 int attribute_align_arg avcodec_open2(AVCodecContext *avctx, const AVCodec *codec, AVDictionary **options)
1020 {
1021     int ret = 0;
1022     AVDictionary *tmp = NULL;
1023
1024     if (avcodec_is_open(avctx))
1025         return 0;
1026
1027     if ((!codec && !avctx->codec)) {
1028         av_log(avctx, AV_LOG_ERROR, "No codec provided to avcodec_open2().\n");
1029         return AVERROR(EINVAL);
1030     }
1031     if ((codec && avctx->codec && codec != avctx->codec)) {
1032         av_log(avctx, AV_LOG_ERROR, "This AVCodecContext was allocated for %s, "
1033                                     "but %s passed to avcodec_open2().\n", avctx->codec->name, codec->name);
1034         return AVERROR(EINVAL);
1035     }
1036     if (!codec)
1037         codec = avctx->codec;
1038
1039     if (avctx->extradata_size < 0 || avctx->extradata_size >= FF_MAX_EXTRADATA_SIZE)
1040         return AVERROR(EINVAL);
1041
1042     if (options)
1043         av_dict_copy(&tmp, *options, 0);
1044
1045     /* If there is a user-supplied mutex locking routine, call it. */
1046     if (lockmgr_cb) {
1047         if ((*lockmgr_cb)(&codec_mutex, AV_LOCK_OBTAIN))
1048             return -1;
1049     }
1050
1051     entangled_thread_counter++;
1052     if (entangled_thread_counter != 1 &&
1053         !(codec->caps_internal & FF_CODEC_CAP_INIT_THREADSAFE)) {
1054         av_log(avctx, AV_LOG_ERROR,
1055                "Insufficient thread locking. At least %d threads are "
1056                "calling avcodec_open2() at the same time right now.\n",
1057                entangled_thread_counter);
1058         ret = -1;
1059         goto end;
1060     }
1061
1062     avctx->internal = av_mallocz(sizeof(AVCodecInternal));
1063     if (!avctx->internal) {
1064         ret = AVERROR(ENOMEM);
1065         goto end;
1066     }
1067
1068     avctx->internal->pool = av_mallocz(sizeof(*avctx->internal->pool));
1069     if (!avctx->internal->pool) {
1070         ret = AVERROR(ENOMEM);
1071         goto free_and_end;
1072     }
1073
1074     avctx->internal->to_free = av_frame_alloc();
1075     if (!avctx->internal->to_free) {
1076         ret = AVERROR(ENOMEM);
1077         goto free_and_end;
1078     }
1079
1080     if (codec->priv_data_size > 0) {
1081         if (!avctx->priv_data) {
1082             avctx->priv_data = av_mallocz(codec->priv_data_size);
1083             if (!avctx->priv_data) {
1084                 ret = AVERROR(ENOMEM);
1085                 goto end;
1086             }
1087             if (codec->priv_class) {
1088                 *(const AVClass **)avctx->priv_data = codec->priv_class;
1089                 av_opt_set_defaults(avctx->priv_data);
1090             }
1091         }
1092         if (codec->priv_class && (ret = av_opt_set_dict(avctx->priv_data, &tmp)) < 0)
1093             goto free_and_end;
1094     } else {
1095         avctx->priv_data = NULL;
1096     }
1097     if ((ret = av_opt_set_dict(avctx, &tmp)) < 0)
1098         goto free_and_end;
1099
1100     if (avctx->coded_width && avctx->coded_height && !avctx->width && !avctx->height)
1101         ret = ff_set_dimensions(avctx, avctx->coded_width, avctx->coded_height);
1102     else if (avctx->width && avctx->height)
1103         ret = ff_set_dimensions(avctx, avctx->width, avctx->height);
1104     if (ret < 0)
1105         goto free_and_end;
1106
1107     if ((avctx->coded_width || avctx->coded_height || avctx->width || avctx->height)
1108         && (  av_image_check_size(avctx->coded_width, avctx->coded_height, 0, avctx) < 0
1109            || av_image_check_size(avctx->width,       avctx->height,       0, avctx) < 0)) {
1110         av_log(avctx, AV_LOG_WARNING, "ignoring invalid width/height values\n");
1111         ff_set_dimensions(avctx, 0, 0);
1112     }
1113
1114     if (avctx->width > 0 && avctx->height > 0) {
1115         if (av_image_check_sar(avctx->width, avctx->height,
1116                                avctx->sample_aspect_ratio) < 0) {
1117             av_log(avctx, AV_LOG_WARNING, "ignoring invalid SAR: %u/%u\n",
1118                    avctx->sample_aspect_ratio.num,
1119                    avctx->sample_aspect_ratio.den);
1120             avctx->sample_aspect_ratio = (AVRational){ 0, 1 };
1121         }
1122     }
1123
1124     /* if the decoder init function was already called previously,
1125      * free the already allocated subtitle_header before overwriting it */
1126     if (av_codec_is_decoder(codec))
1127         av_freep(&avctx->subtitle_header);
1128
1129     if (avctx->channels > FF_SANE_NB_CHANNELS) {
1130         ret = AVERROR(EINVAL);
1131         goto free_and_end;
1132     }
1133
1134     avctx->codec = codec;
1135     if ((avctx->codec_type == AVMEDIA_TYPE_UNKNOWN || avctx->codec_type == codec->type) &&
1136         avctx->codec_id == AV_CODEC_ID_NONE) {
1137         avctx->codec_type = codec->type;
1138         avctx->codec_id   = codec->id;
1139     }
1140     if (avctx->codec_id != codec->id || (avctx->codec_type != codec->type
1141                                          && avctx->codec_type != AVMEDIA_TYPE_ATTACHMENT)) {
1142         av_log(avctx, AV_LOG_ERROR, "codec type or id mismatches\n");
1143         ret = AVERROR(EINVAL);
1144         goto free_and_end;
1145     }
1146     avctx->frame_number = 0;
1147
1148     if (avctx->codec->capabilities & CODEC_CAP_EXPERIMENTAL &&
1149         avctx->strict_std_compliance > FF_COMPLIANCE_EXPERIMENTAL) {
1150         ret = AVERROR_EXPERIMENTAL;
1151         goto free_and_end;
1152     }
1153
1154     if (avctx->codec_type == AVMEDIA_TYPE_AUDIO &&
1155         (!avctx->time_base.num || !avctx->time_base.den)) {
1156         avctx->time_base.num = 1;
1157         avctx->time_base.den = avctx->sample_rate;
1158     }
1159
1160     if (HAVE_THREADS) {
1161         ret = ff_thread_init(avctx);
1162         if (ret < 0) {
1163             goto free_and_end;
1164         }
1165     }
1166     if (!HAVE_THREADS && !(codec->capabilities & CODEC_CAP_AUTO_THREADS))
1167         avctx->thread_count = 1;
1168
1169     if (av_codec_is_encoder(avctx->codec)) {
1170         int i;
1171         if (avctx->codec->sample_fmts) {
1172             for (i = 0; avctx->codec->sample_fmts[i] != AV_SAMPLE_FMT_NONE; i++) {
1173                 if (avctx->sample_fmt == avctx->codec->sample_fmts[i])
1174                     break;
1175                 if (avctx->channels == 1 &&
1176                     av_get_planar_sample_fmt(avctx->sample_fmt) ==
1177                     av_get_planar_sample_fmt(avctx->codec->sample_fmts[i])) {
1178                     avctx->sample_fmt = avctx->codec->sample_fmts[i];
1179                     break;
1180                 }
1181             }
1182             if (avctx->codec->sample_fmts[i] == AV_SAMPLE_FMT_NONE) {
1183                 av_log(avctx, AV_LOG_ERROR, "Specified sample_fmt is not supported.\n");
1184                 ret = AVERROR(EINVAL);
1185                 goto free_and_end;
1186             }
1187         }
1188         if (avctx->codec->pix_fmts) {
1189             for (i = 0; avctx->codec->pix_fmts[i] != AV_PIX_FMT_NONE; i++)
1190                 if (avctx->pix_fmt == avctx->codec->pix_fmts[i])
1191                     break;
1192             if (avctx->codec->pix_fmts[i] == AV_PIX_FMT_NONE) {
1193                 av_log(avctx, AV_LOG_ERROR, "Specified pix_fmt is not supported\n");
1194                 ret = AVERROR(EINVAL);
1195                 goto free_and_end;
1196             }
1197             if (avctx->codec->pix_fmts[i] == AV_PIX_FMT_YUVJ420P ||
1198                 avctx->codec->pix_fmts[i] == AV_PIX_FMT_YUVJ422P ||
1199                 avctx->codec->pix_fmts[i] == AV_PIX_FMT_YUVJ440P ||
1200                 avctx->codec->pix_fmts[i] == AV_PIX_FMT_YUVJ444P)
1201                 avctx->color_range = AVCOL_RANGE_JPEG;
1202         }
1203         if (avctx->codec->supported_samplerates) {
1204             for (i = 0; avctx->codec->supported_samplerates[i] != 0; i++)
1205                 if (avctx->sample_rate == avctx->codec->supported_samplerates[i])
1206                     break;
1207             if (avctx->codec->supported_samplerates[i] == 0) {
1208                 av_log(avctx, AV_LOG_ERROR, "Specified sample_rate is not supported\n");
1209                 ret = AVERROR(EINVAL);
1210                 goto free_and_end;
1211             }
1212         }
1213         if (avctx->codec->channel_layouts) {
1214             if (!avctx->channel_layout) {
1215                 av_log(avctx, AV_LOG_WARNING, "channel_layout not specified\n");
1216             } else {
1217                 for (i = 0; avctx->codec->channel_layouts[i] != 0; i++)
1218                     if (avctx->channel_layout == avctx->codec->channel_layouts[i])
1219                         break;
1220                 if (avctx->codec->channel_layouts[i] == 0) {
1221                     av_log(avctx, AV_LOG_ERROR, "Specified channel_layout is not supported\n");
1222                     ret = AVERROR(EINVAL);
1223                     goto free_and_end;
1224                 }
1225             }
1226         }
1227         if (avctx->channel_layout && avctx->channels) {
1228             if (av_get_channel_layout_nb_channels(avctx->channel_layout) != avctx->channels) {
1229                 av_log(avctx, AV_LOG_ERROR, "channel layout does not match number of channels\n");
1230                 ret = AVERROR(EINVAL);
1231                 goto free_and_end;
1232             }
1233         } else if (avctx->channel_layout) {
1234             avctx->channels = av_get_channel_layout_nb_channels(avctx->channel_layout);
1235         }
1236
1237         if (!avctx->rc_initial_buffer_occupancy)
1238             avctx->rc_initial_buffer_occupancy = avctx->rc_buffer_size * 3 / 4;
1239     }
1240
1241     if (avctx->codec->init && !(avctx->active_thread_type & FF_THREAD_FRAME)) {
1242         ret = avctx->codec->init(avctx);
1243         if (ret < 0) {
1244             goto free_and_end;
1245         }
1246     }
1247
1248 #if FF_API_AUDIOENC_DELAY
1249     if (av_codec_is_encoder(avctx->codec))
1250         avctx->delay = avctx->initial_padding;
1251 #endif
1252
1253     if (av_codec_is_decoder(avctx->codec)) {
1254         /* validate channel layout from the decoder */
1255         if (avctx->channel_layout) {
1256             int channels = av_get_channel_layout_nb_channels(avctx->channel_layout);
1257             if (!avctx->channels)
1258                 avctx->channels = channels;
1259             else if (channels != avctx->channels) {
1260                 av_log(avctx, AV_LOG_WARNING,
1261                        "channel layout does not match number of channels\n");
1262                 avctx->channel_layout = 0;
1263             }
1264         }
1265         if (avctx->channels && avctx->channels < 0 ||
1266             avctx->channels > FF_SANE_NB_CHANNELS) {
1267             ret = AVERROR(EINVAL);
1268             goto free_and_end;
1269         }
1270
1271 #if FF_API_AVCTX_TIMEBASE
1272         if (avctx->framerate.num > 0 && avctx->framerate.den > 0)
1273             avctx->time_base = av_inv_q(avctx->framerate);
1274 #endif
1275     }
1276 end:
1277     entangled_thread_counter--;
1278
1279     /* Release any user-supplied mutex. */
1280     if (lockmgr_cb) {
1281         (*lockmgr_cb)(&codec_mutex, AV_LOCK_RELEASE);
1282     }
1283     if (options) {
1284         av_dict_free(options);
1285         *options = tmp;
1286     }
1287
1288     return ret;
1289 free_and_end:
1290     if (avctx->codec &&
1291         (avctx->codec->caps_internal & FF_CODEC_CAP_INIT_CLEANUP))
1292         avctx->codec->close(avctx);
1293
1294     av_dict_free(&tmp);
1295     av_freep(&avctx->priv_data);
1296     if (avctx->internal) {
1297         av_frame_free(&avctx->internal->to_free);
1298         av_freep(&avctx->internal->pool);
1299     }
1300     av_freep(&avctx->internal);
1301     avctx->codec = NULL;
1302     goto end;
1303 }
1304
1305 int ff_alloc_packet(AVPacket *avpkt, int size)
1306 {
1307     if (size > INT_MAX - FF_INPUT_BUFFER_PADDING_SIZE)
1308         return AVERROR(EINVAL);
1309
1310     if (avpkt->data) {
1311         AVBufferRef *buf = avpkt->buf;
1312 #if FF_API_DESTRUCT_PACKET
1313 FF_DISABLE_DEPRECATION_WARNINGS
1314         void *destruct = avpkt->destruct;
1315 FF_ENABLE_DEPRECATION_WARNINGS
1316 #endif
1317
1318         if (avpkt->size < size)
1319             return AVERROR(EINVAL);
1320
1321         av_init_packet(avpkt);
1322 #if FF_API_DESTRUCT_PACKET
1323 FF_DISABLE_DEPRECATION_WARNINGS
1324         avpkt->destruct = destruct;
1325 FF_ENABLE_DEPRECATION_WARNINGS
1326 #endif
1327         avpkt->buf      = buf;
1328         avpkt->size     = size;
1329         return 0;
1330     } else {
1331         return av_new_packet(avpkt, size);
1332     }
1333 }
1334
1335 /**
1336  * Pad last frame with silence.
1337  */
1338 static int pad_last_frame(AVCodecContext *s, AVFrame **dst, const AVFrame *src)
1339 {
1340     AVFrame *frame = NULL;
1341     int ret;
1342
1343     if (!(frame = av_frame_alloc()))
1344         return AVERROR(ENOMEM);
1345
1346     frame->format         = src->format;
1347     frame->channel_layout = src->channel_layout;
1348     frame->nb_samples     = s->frame_size;
1349     ret = av_frame_get_buffer(frame, 32);
1350     if (ret < 0)
1351         goto fail;
1352
1353     ret = av_frame_copy_props(frame, src);
1354     if (ret < 0)
1355         goto fail;
1356
1357     if ((ret = av_samples_copy(frame->extended_data, src->extended_data, 0, 0,
1358                                src->nb_samples, s->channels, s->sample_fmt)) < 0)
1359         goto fail;
1360     if ((ret = av_samples_set_silence(frame->extended_data, src->nb_samples,
1361                                       frame->nb_samples - src->nb_samples,
1362                                       s->channels, s->sample_fmt)) < 0)
1363         goto fail;
1364
1365     *dst = frame;
1366
1367     return 0;
1368
1369 fail:
1370     av_frame_free(&frame);
1371     return ret;
1372 }
1373
1374 int attribute_align_arg avcodec_encode_audio2(AVCodecContext *avctx,
1375                                               AVPacket *avpkt,
1376                                               const AVFrame *frame,
1377                                               int *got_packet_ptr)
1378 {
1379     AVFrame tmp;
1380     AVFrame *padded_frame = NULL;
1381     int ret;
1382     int user_packet = !!avpkt->data;
1383
1384     *got_packet_ptr = 0;
1385
1386     if (!(avctx->codec->capabilities & CODEC_CAP_DELAY) && !frame) {
1387         av_free_packet(avpkt);
1388         av_init_packet(avpkt);
1389         return 0;
1390     }
1391
1392     /* ensure that extended_data is properly set */
1393     if (frame && !frame->extended_data) {
1394         if (av_sample_fmt_is_planar(avctx->sample_fmt) &&
1395             avctx->channels > AV_NUM_DATA_POINTERS) {
1396             av_log(avctx, AV_LOG_ERROR, "Encoding to a planar sample format, "
1397                                         "with more than %d channels, but extended_data is not set.\n",
1398                    AV_NUM_DATA_POINTERS);
1399             return AVERROR(EINVAL);
1400         }
1401         av_log(avctx, AV_LOG_WARNING, "extended_data is not set.\n");
1402
1403         tmp = *frame;
1404         tmp.extended_data = tmp.data;
1405         frame = &tmp;
1406     }
1407
1408     /* extract audio service type metadata */
1409     if (frame) {
1410         AVFrameSideData *sd = av_frame_get_side_data(frame, AV_FRAME_DATA_AUDIO_SERVICE_TYPE);
1411         if (sd && sd->size >= sizeof(enum AVAudioServiceType))
1412             avctx->audio_service_type = *(enum AVAudioServiceType*)sd->data;
1413     }
1414
1415     /* check for valid frame size */
1416     if (frame) {
1417         if (avctx->codec->capabilities & CODEC_CAP_SMALL_LAST_FRAME) {
1418             if (frame->nb_samples > avctx->frame_size)
1419                 return AVERROR(EINVAL);
1420         } else if (!(avctx->codec->capabilities & CODEC_CAP_VARIABLE_FRAME_SIZE)) {
1421             if (frame->nb_samples < avctx->frame_size &&
1422                 !avctx->internal->last_audio_frame) {
1423                 ret = pad_last_frame(avctx, &padded_frame, frame);
1424                 if (ret < 0)
1425                     return ret;
1426
1427                 frame = padded_frame;
1428                 avctx->internal->last_audio_frame = 1;
1429             }
1430
1431             if (frame->nb_samples != avctx->frame_size) {
1432                 ret = AVERROR(EINVAL);
1433                 goto end;
1434             }
1435         }
1436     }
1437
1438     ret = avctx->codec->encode2(avctx, avpkt, frame, got_packet_ptr);
1439     if (!ret) {
1440         if (*got_packet_ptr) {
1441             if (!(avctx->codec->capabilities & CODEC_CAP_DELAY)) {
1442                 if (avpkt->pts == AV_NOPTS_VALUE)
1443                     avpkt->pts = frame->pts;
1444                 if (!avpkt->duration)
1445                     avpkt->duration = ff_samples_to_time_base(avctx,
1446                                                               frame->nb_samples);
1447             }
1448             avpkt->dts = avpkt->pts;
1449         } else {
1450             avpkt->size = 0;
1451         }
1452
1453         if (!user_packet && avpkt->size) {
1454             ret = av_buffer_realloc(&avpkt->buf, avpkt->size);
1455             if (ret >= 0)
1456                 avpkt->data = avpkt->buf->data;
1457         }
1458
1459         avctx->frame_number++;
1460     }
1461
1462     if (ret < 0 || !*got_packet_ptr) {
1463         av_free_packet(avpkt);
1464         av_init_packet(avpkt);
1465         goto end;
1466     }
1467
1468     /* NOTE: if we add any audio encoders which output non-keyframe packets,
1469      *       this needs to be moved to the encoders, but for now we can do it
1470      *       here to simplify things */
1471     avpkt->flags |= AV_PKT_FLAG_KEY;
1472
1473 end:
1474     av_frame_free(&padded_frame);
1475
1476 #if FF_API_AUDIOENC_DELAY
1477     avctx->delay = avctx->initial_padding;
1478 #endif
1479
1480     return ret;
1481 }
1482
1483 int attribute_align_arg avcodec_encode_video2(AVCodecContext *avctx,
1484                                               AVPacket *avpkt,
1485                                               const AVFrame *frame,
1486                                               int *got_packet_ptr)
1487 {
1488     int ret;
1489     int user_packet = !!avpkt->data;
1490
1491     *got_packet_ptr = 0;
1492
1493     if (!(avctx->codec->capabilities & CODEC_CAP_DELAY) && !frame) {
1494         av_free_packet(avpkt);
1495         av_init_packet(avpkt);
1496         avpkt->size = 0;
1497         return 0;
1498     }
1499
1500     if (av_image_check_size(avctx->width, avctx->height, 0, avctx))
1501         return AVERROR(EINVAL);
1502
1503     av_assert0(avctx->codec->encode2);
1504
1505     ret = avctx->codec->encode2(avctx, avpkt, frame, got_packet_ptr);
1506     if (!ret) {
1507         if (!*got_packet_ptr)
1508             avpkt->size = 0;
1509         else if (!(avctx->codec->capabilities & CODEC_CAP_DELAY))
1510             avpkt->pts = avpkt->dts = frame->pts;
1511
1512         if (!user_packet && avpkt->size) {
1513             ret = av_buffer_realloc(&avpkt->buf, avpkt->size);
1514             if (ret >= 0)
1515                 avpkt->data = avpkt->buf->data;
1516         }
1517
1518         avctx->frame_number++;
1519     }
1520
1521     if (ret < 0 || !*got_packet_ptr)
1522         av_free_packet(avpkt);
1523
1524     emms_c();
1525     return ret;
1526 }
1527
1528 int avcodec_encode_subtitle(AVCodecContext *avctx, uint8_t *buf, int buf_size,
1529                             const AVSubtitle *sub)
1530 {
1531     int ret;
1532     if (sub->start_display_time) {
1533         av_log(avctx, AV_LOG_ERROR, "start_display_time must be 0.\n");
1534         return -1;
1535     }
1536     if (sub->num_rects == 0 || !sub->rects)
1537         return -1;
1538     ret = avctx->codec->encode_sub(avctx, buf, buf_size, sub);
1539     avctx->frame_number++;
1540     return ret;
1541 }
1542
1543 static int apply_param_change(AVCodecContext *avctx, AVPacket *avpkt)
1544 {
1545     int size = 0, ret;
1546     const uint8_t *data;
1547     uint32_t flags;
1548
1549     data = av_packet_get_side_data(avpkt, AV_PKT_DATA_PARAM_CHANGE, &size);
1550     if (!data)
1551         return 0;
1552
1553     if (!(avctx->codec->capabilities & CODEC_CAP_PARAM_CHANGE)) {
1554         av_log(avctx, AV_LOG_ERROR, "This decoder does not support parameter "
1555                "changes, but PARAM_CHANGE side data was sent to it.\n");
1556         return AVERROR(EINVAL);
1557     }
1558
1559     if (size < 4)
1560         goto fail;
1561
1562     flags = bytestream_get_le32(&data);
1563     size -= 4;
1564
1565     if (flags & AV_SIDE_DATA_PARAM_CHANGE_CHANNEL_COUNT) {
1566         if (size < 4)
1567             goto fail;
1568         avctx->channels = bytestream_get_le32(&data);
1569         size -= 4;
1570     }
1571     if (flags & AV_SIDE_DATA_PARAM_CHANGE_CHANNEL_LAYOUT) {
1572         if (size < 8)
1573             goto fail;
1574         avctx->channel_layout = bytestream_get_le64(&data);
1575         size -= 8;
1576     }
1577     if (flags & AV_SIDE_DATA_PARAM_CHANGE_SAMPLE_RATE) {
1578         if (size < 4)
1579             goto fail;
1580         avctx->sample_rate = bytestream_get_le32(&data);
1581         size -= 4;
1582     }
1583     if (flags & AV_SIDE_DATA_PARAM_CHANGE_DIMENSIONS) {
1584         if (size < 8)
1585             goto fail;
1586         avctx->width  = bytestream_get_le32(&data);
1587         avctx->height = bytestream_get_le32(&data);
1588         size -= 8;
1589         ret = ff_set_dimensions(avctx, avctx->width, avctx->height);
1590         if (ret < 0)
1591             return ret;
1592     }
1593
1594     return 0;
1595 fail:
1596     av_log(avctx, AV_LOG_ERROR, "PARAM_CHANGE side data too small.\n");
1597     return AVERROR_INVALIDDATA;
1598 }
1599
1600 static int unrefcount_frame(AVCodecInternal *avci, AVFrame *frame)
1601 {
1602     int ret;
1603
1604     /* move the original frame to our backup */
1605     av_frame_unref(avci->to_free);
1606     av_frame_move_ref(avci->to_free, frame);
1607
1608     /* now copy everything except the AVBufferRefs back
1609      * note that we make a COPY of the side data, so calling av_frame_free() on
1610      * the caller's frame will work properly */
1611     ret = av_frame_copy_props(frame, avci->to_free);
1612     if (ret < 0)
1613         return ret;
1614
1615     memcpy(frame->data,     avci->to_free->data,     sizeof(frame->data));
1616     memcpy(frame->linesize, avci->to_free->linesize, sizeof(frame->linesize));
1617     if (avci->to_free->extended_data != avci->to_free->data) {
1618         int planes = av_get_channel_layout_nb_channels(avci->to_free->channel_layout);
1619         int size   = planes * sizeof(*frame->extended_data);
1620
1621         if (!size) {
1622             av_frame_unref(frame);
1623             return AVERROR_BUG;
1624         }
1625
1626         frame->extended_data = av_malloc(size);
1627         if (!frame->extended_data) {
1628             av_frame_unref(frame);
1629             return AVERROR(ENOMEM);
1630         }
1631         memcpy(frame->extended_data, avci->to_free->extended_data,
1632                size);
1633     } else
1634         frame->extended_data = frame->data;
1635
1636     frame->format         = avci->to_free->format;
1637     frame->width          = avci->to_free->width;
1638     frame->height         = avci->to_free->height;
1639     frame->channel_layout = avci->to_free->channel_layout;
1640     frame->nb_samples     = avci->to_free->nb_samples;
1641
1642     return 0;
1643 }
1644
1645 int attribute_align_arg avcodec_decode_video2(AVCodecContext *avctx, AVFrame *picture,
1646                                               int *got_picture_ptr,
1647                                               AVPacket *avpkt)
1648 {
1649     AVCodecInternal *avci = avctx->internal;
1650     int ret;
1651
1652     *got_picture_ptr = 0;
1653     if ((avctx->coded_width || avctx->coded_height) && av_image_check_size(avctx->coded_width, avctx->coded_height, 0, avctx))
1654         return -1;
1655
1656     avctx->internal->pkt = avpkt;
1657     ret = apply_param_change(avctx, avpkt);
1658     if (ret < 0) {
1659         av_log(avctx, AV_LOG_ERROR, "Error applying parameter changes.\n");
1660         if (avctx->err_recognition & AV_EF_EXPLODE)
1661             return ret;
1662     }
1663
1664     av_frame_unref(picture);
1665
1666     if ((avctx->codec->capabilities & CODEC_CAP_DELAY) || avpkt->size || (avctx->active_thread_type & FF_THREAD_FRAME)) {
1667         if (HAVE_THREADS && avctx->active_thread_type & FF_THREAD_FRAME)
1668             ret = ff_thread_decode_frame(avctx, picture, got_picture_ptr,
1669                                          avpkt);
1670         else {
1671             ret = avctx->codec->decode(avctx, picture, got_picture_ptr,
1672                                        avpkt);
1673             picture->pkt_dts = avpkt->dts;
1674             /* get_buffer is supposed to set frame parameters */
1675             if (!(avctx->codec->capabilities & CODEC_CAP_DR1)) {
1676                 picture->sample_aspect_ratio = avctx->sample_aspect_ratio;
1677                 picture->width               = avctx->width;
1678                 picture->height              = avctx->height;
1679                 picture->format              = avctx->pix_fmt;
1680             }
1681         }
1682
1683         emms_c(); //needed to avoid an emms_c() call before every return;
1684
1685         if (*got_picture_ptr) {
1686             if (!avctx->refcounted_frames) {
1687                 int err = unrefcount_frame(avci, picture);
1688                 if (err < 0)
1689                     return err;
1690             }
1691
1692             avctx->frame_number++;
1693         } else
1694             av_frame_unref(picture);
1695     } else
1696         ret = 0;
1697
1698 #if FF_API_AVCTX_TIMEBASE
1699     if (avctx->framerate.num > 0 && avctx->framerate.den > 0)
1700         avctx->time_base = av_inv_q(avctx->framerate);
1701 #endif
1702
1703     return ret;
1704 }
1705
1706 int attribute_align_arg avcodec_decode_audio4(AVCodecContext *avctx,
1707                                               AVFrame *frame,
1708                                               int *got_frame_ptr,
1709                                               AVPacket *avpkt)
1710 {
1711     AVCodecInternal *avci = avctx->internal;
1712     int ret = 0;
1713
1714     *got_frame_ptr = 0;
1715
1716     avctx->internal->pkt = avpkt;
1717
1718     if (!avpkt->data && avpkt->size) {
1719         av_log(avctx, AV_LOG_ERROR, "invalid packet: NULL data, size != 0\n");
1720         return AVERROR(EINVAL);
1721     }
1722
1723     ret = apply_param_change(avctx, avpkt);
1724     if (ret < 0) {
1725         av_log(avctx, AV_LOG_ERROR, "Error applying parameter changes.\n");
1726         if (avctx->err_recognition & AV_EF_EXPLODE)
1727             return ret;
1728     }
1729
1730     av_frame_unref(frame);
1731
1732     if ((avctx->codec->capabilities & CODEC_CAP_DELAY) || avpkt->size) {
1733         ret = avctx->codec->decode(avctx, frame, got_frame_ptr, avpkt);
1734         if (ret >= 0 && *got_frame_ptr) {
1735             avctx->frame_number++;
1736             frame->pkt_dts = avpkt->dts;
1737             if (frame->format == AV_SAMPLE_FMT_NONE)
1738                 frame->format = avctx->sample_fmt;
1739
1740             if (!avctx->refcounted_frames) {
1741                 int err = unrefcount_frame(avci, frame);
1742                 if (err < 0)
1743                     return err;
1744             }
1745         } else
1746             av_frame_unref(frame);
1747     }
1748
1749
1750     return ret;
1751 }
1752
1753 int avcodec_decode_subtitle2(AVCodecContext *avctx, AVSubtitle *sub,
1754                              int *got_sub_ptr,
1755                              AVPacket *avpkt)
1756 {
1757     int ret;
1758
1759     avctx->internal->pkt = avpkt;
1760     *got_sub_ptr = 0;
1761     ret = avctx->codec->decode(avctx, sub, got_sub_ptr, avpkt);
1762     if (*got_sub_ptr)
1763         avctx->frame_number++;
1764     return ret;
1765 }
1766
1767 void avsubtitle_free(AVSubtitle *sub)
1768 {
1769     int i;
1770
1771     for (i = 0; i < sub->num_rects; i++) {
1772         av_freep(&sub->rects[i]->pict.data[0]);
1773         av_freep(&sub->rects[i]->pict.data[1]);
1774         av_freep(&sub->rects[i]->pict.data[2]);
1775         av_freep(&sub->rects[i]->pict.data[3]);
1776         av_freep(&sub->rects[i]->text);
1777         av_freep(&sub->rects[i]->ass);
1778         av_freep(&sub->rects[i]);
1779     }
1780
1781     av_freep(&sub->rects);
1782
1783     memset(sub, 0, sizeof(AVSubtitle));
1784 }
1785
1786 av_cold int avcodec_close(AVCodecContext *avctx)
1787 {
1788     if (avcodec_is_open(avctx)) {
1789         FramePool *pool = avctx->internal->pool;
1790         int i;
1791         if (HAVE_THREADS && avctx->internal->thread_ctx)
1792             ff_thread_free(avctx);
1793         if (avctx->codec && avctx->codec->close)
1794             avctx->codec->close(avctx);
1795         avctx->coded_frame = NULL;
1796         av_frame_free(&avctx->internal->to_free);
1797         for (i = 0; i < FF_ARRAY_ELEMS(pool->pools); i++)
1798             av_buffer_pool_uninit(&pool->pools[i]);
1799         av_freep(&avctx->internal->pool);
1800
1801         if (avctx->hwaccel && avctx->hwaccel->uninit)
1802             avctx->hwaccel->uninit(avctx);
1803         av_freep(&avctx->internal->hwaccel_priv_data);
1804
1805         av_freep(&avctx->internal);
1806     }
1807
1808     if (avctx->priv_data && avctx->codec && avctx->codec->priv_class)
1809         av_opt_free(avctx->priv_data);
1810     av_opt_free(avctx);
1811     av_freep(&avctx->priv_data);
1812     if (av_codec_is_encoder(avctx->codec))
1813         av_freep(&avctx->extradata);
1814     avctx->codec = NULL;
1815     avctx->active_thread_type = 0;
1816
1817     return 0;
1818 }
1819
1820 static AVCodec *find_encdec(enum AVCodecID id, int encoder)
1821 {
1822     AVCodec *p, *experimental = NULL;
1823     p = first_avcodec;
1824     while (p) {
1825         if ((encoder ? av_codec_is_encoder(p) : av_codec_is_decoder(p)) &&
1826             p->id == id) {
1827             if (p->capabilities & CODEC_CAP_EXPERIMENTAL && !experimental) {
1828                 experimental = p;
1829             } else
1830                 return p;
1831         }
1832         p = p->next;
1833     }
1834     return experimental;
1835 }
1836
1837 AVCodec *avcodec_find_encoder(enum AVCodecID id)
1838 {
1839     return find_encdec(id, 1);
1840 }
1841
1842 AVCodec *avcodec_find_encoder_by_name(const char *name)
1843 {
1844     AVCodec *p;
1845     if (!name)
1846         return NULL;
1847     p = first_avcodec;
1848     while (p) {
1849         if (av_codec_is_encoder(p) && strcmp(name, p->name) == 0)
1850             return p;
1851         p = p->next;
1852     }
1853     return NULL;
1854 }
1855
1856 AVCodec *avcodec_find_decoder(enum AVCodecID id)
1857 {
1858     return find_encdec(id, 0);
1859 }
1860
1861 AVCodec *avcodec_find_decoder_by_name(const char *name)
1862 {
1863     AVCodec *p;
1864     if (!name)
1865         return NULL;
1866     p = first_avcodec;
1867     while (p) {
1868         if (av_codec_is_decoder(p) && strcmp(name, p->name) == 0)
1869             return p;
1870         p = p->next;
1871     }
1872     return NULL;
1873 }
1874
1875 static int get_bit_rate(AVCodecContext *ctx)
1876 {
1877     int bit_rate;
1878     int bits_per_sample;
1879
1880     switch (ctx->codec_type) {
1881     case AVMEDIA_TYPE_VIDEO:
1882     case AVMEDIA_TYPE_DATA:
1883     case AVMEDIA_TYPE_SUBTITLE:
1884     case AVMEDIA_TYPE_ATTACHMENT:
1885         bit_rate = ctx->bit_rate;
1886         break;
1887     case AVMEDIA_TYPE_AUDIO:
1888         bits_per_sample = av_get_bits_per_sample(ctx->codec_id);
1889         bit_rate = bits_per_sample ? ctx->sample_rate * ctx->channels * bits_per_sample : ctx->bit_rate;
1890         break;
1891     default:
1892         bit_rate = 0;
1893         break;
1894     }
1895     return bit_rate;
1896 }
1897
1898 size_t av_get_codec_tag_string(char *buf, size_t buf_size, unsigned int codec_tag)
1899 {
1900     int i, len, ret = 0;
1901
1902 #define TAG_PRINT(x)                                              \
1903     (((x) >= '0' && (x) <= '9') ||                                \
1904      ((x) >= 'a' && (x) <= 'z') || ((x) >= 'A' && (x) <= 'Z') ||  \
1905      ((x) == '.' || (x) == ' '))
1906
1907     for (i = 0; i < 4; i++) {
1908         len = snprintf(buf, buf_size,
1909                        TAG_PRINT(codec_tag & 0xFF) ? "%c" : "[%d]", codec_tag & 0xFF);
1910         buf        += len;
1911         buf_size    = buf_size > len ? buf_size - len : 0;
1912         ret        += len;
1913         codec_tag >>= 8;
1914     }
1915     return ret;
1916 }
1917
1918 void avcodec_string(char *buf, int buf_size, AVCodecContext *enc, int encode)
1919 {
1920     const char *codec_name;
1921     const char *profile = NULL;
1922     const AVCodec *p;
1923     char buf1[32];
1924     int bitrate;
1925     int new_line = 0;
1926     AVRational display_aspect_ratio;
1927
1928     if (enc->codec)
1929         p = enc->codec;
1930     else if (encode)
1931         p = avcodec_find_encoder(enc->codec_id);
1932     else
1933         p = avcodec_find_decoder(enc->codec_id);
1934
1935     if (p) {
1936         codec_name = p->name;
1937         profile = av_get_profile_name(p, enc->profile);
1938     } else if (enc->codec_id == AV_CODEC_ID_MPEG2TS) {
1939         /* fake mpeg2 transport stream codec (currently not
1940          * registered) */
1941         codec_name = "mpeg2ts";
1942     } else {
1943         /* output avi tags */
1944         char tag_buf[32];
1945         av_get_codec_tag_string(tag_buf, sizeof(tag_buf), enc->codec_tag);
1946         snprintf(buf1, sizeof(buf1), "%s / 0x%04X", tag_buf, enc->codec_tag);
1947         codec_name = buf1;
1948     }
1949
1950     switch (enc->codec_type) {
1951     case AVMEDIA_TYPE_VIDEO:
1952         snprintf(buf, buf_size,
1953                  "Video: %s%s",
1954                  codec_name, enc->mb_decision ? " (hq)" : "");
1955         if (profile)
1956             snprintf(buf + strlen(buf), buf_size - strlen(buf),
1957                      " (%s)", profile);
1958         if (enc->codec_tag) {
1959             char tag_buf[32];
1960             av_get_codec_tag_string(tag_buf, sizeof(tag_buf), enc->codec_tag);
1961             snprintf(buf + strlen(buf), buf_size - strlen(buf),
1962                      " [%s / 0x%04X]", tag_buf, enc->codec_tag);
1963         }
1964
1965         av_strlcat(buf, "\n      ", buf_size);
1966         snprintf(buf + strlen(buf), buf_size - strlen(buf),
1967                  "%s", enc->pix_fmt == AV_PIX_FMT_NONE ? "none" :
1968                      av_get_pix_fmt_name(enc->pix_fmt));
1969
1970         if (enc->color_range != AVCOL_RANGE_UNSPECIFIED)
1971             snprintf(buf + strlen(buf), buf_size - strlen(buf), ", %s",
1972                      av_color_range_name(enc->color_range));
1973         if (enc->colorspace != AVCOL_SPC_UNSPECIFIED ||
1974             enc->color_primaries != AVCOL_PRI_UNSPECIFIED ||
1975             enc->color_trc != AVCOL_TRC_UNSPECIFIED) {
1976             new_line = 1;
1977             snprintf(buf + strlen(buf), buf_size - strlen(buf), ", %s/%s/%s",
1978                      av_color_space_name(enc->colorspace),
1979                      av_color_primaries_name(enc->color_primaries),
1980                      av_color_transfer_name(enc->color_trc));
1981         }
1982         if (av_log_get_level() >= AV_LOG_DEBUG &&
1983             enc->chroma_sample_location != AVCHROMA_LOC_UNSPECIFIED)
1984             snprintf(buf + strlen(buf), buf_size - strlen(buf), ", %s",
1985                      av_chroma_location_name(enc->chroma_sample_location));
1986
1987         if (enc->width) {
1988             av_strlcat(buf, new_line ? "\n      " : ", ", buf_size);
1989
1990             snprintf(buf + strlen(buf), buf_size - strlen(buf),
1991                      "%dx%d",
1992                      enc->width, enc->height);
1993
1994             if (av_log_get_level() >= AV_LOG_VERBOSE &&
1995                 (enc->width != enc->coded_width ||
1996                  enc->height != enc->coded_height))
1997                 snprintf(buf + strlen(buf), buf_size - strlen(buf),
1998                          " (%dx%d)", enc->coded_width, enc->coded_height);
1999
2000             if (enc->sample_aspect_ratio.num) {
2001                 av_reduce(&display_aspect_ratio.num, &display_aspect_ratio.den,
2002                           enc->width * enc->sample_aspect_ratio.num,
2003                           enc->height * enc->sample_aspect_ratio.den,
2004                           1024 * 1024);
2005                 snprintf(buf + strlen(buf), buf_size - strlen(buf),
2006                          " [PAR %d:%d DAR %d:%d]",
2007                          enc->sample_aspect_ratio.num, enc->sample_aspect_ratio.den,
2008                          display_aspect_ratio.num, display_aspect_ratio.den);
2009             }
2010             if (av_log_get_level() >= AV_LOG_DEBUG) {
2011                 int g = av_gcd(enc->time_base.num, enc->time_base.den);
2012                 snprintf(buf + strlen(buf), buf_size - strlen(buf),
2013                          ", %d/%d",
2014                          enc->time_base.num / g, enc->time_base.den / g);
2015             }
2016         }
2017         if (encode) {
2018             snprintf(buf + strlen(buf), buf_size - strlen(buf),
2019                      ", q=%d-%d", enc->qmin, enc->qmax);
2020         }
2021         break;
2022     case AVMEDIA_TYPE_AUDIO:
2023         snprintf(buf, buf_size,
2024                  "Audio: %s",
2025                  codec_name);
2026         if (profile)
2027             snprintf(buf + strlen(buf), buf_size - strlen(buf),
2028                      " (%s)", profile);
2029         if (enc->codec_tag) {
2030             char tag_buf[32];
2031             av_get_codec_tag_string(tag_buf, sizeof(tag_buf), enc->codec_tag);
2032             snprintf(buf + strlen(buf), buf_size - strlen(buf),
2033                      " [%s / 0x%04X]", tag_buf, enc->codec_tag);
2034         }
2035
2036         av_strlcat(buf, "\n      ", buf_size);
2037         if (enc->sample_rate) {
2038             snprintf(buf + strlen(buf), buf_size - strlen(buf),
2039                      "%d Hz, ", enc->sample_rate);
2040         }
2041         av_get_channel_layout_string(buf + strlen(buf), buf_size - strlen(buf), enc->channels, enc->channel_layout);
2042         if (enc->sample_fmt != AV_SAMPLE_FMT_NONE) {
2043             snprintf(buf + strlen(buf), buf_size - strlen(buf),
2044                      ", %s", av_get_sample_fmt_name(enc->sample_fmt));
2045         }
2046         break;
2047     case AVMEDIA_TYPE_DATA:
2048         snprintf(buf, buf_size, "Data: %s", codec_name);
2049         break;
2050     case AVMEDIA_TYPE_SUBTITLE:
2051         snprintf(buf, buf_size, "Subtitle: %s", codec_name);
2052         break;
2053     case AVMEDIA_TYPE_ATTACHMENT:
2054         snprintf(buf, buf_size, "Attachment: %s", codec_name);
2055         break;
2056     default:
2057         snprintf(buf, buf_size, "Invalid Codec type %d", enc->codec_type);
2058         return;
2059     }
2060     if (encode) {
2061         if (enc->flags & CODEC_FLAG_PASS1)
2062             snprintf(buf + strlen(buf), buf_size - strlen(buf),
2063                      ", pass 1");
2064         if (enc->flags & CODEC_FLAG_PASS2)
2065             snprintf(buf + strlen(buf), buf_size - strlen(buf),
2066                      ", pass 2");
2067     }
2068     bitrate = get_bit_rate(enc);
2069     if (bitrate != 0) {
2070         snprintf(buf + strlen(buf), buf_size - strlen(buf),
2071                  ", %d kb/s", bitrate / 1000);
2072     }
2073 }
2074
2075 const char *av_get_profile_name(const AVCodec *codec, int profile)
2076 {
2077     const AVProfile *p;
2078     if (profile == FF_PROFILE_UNKNOWN || !codec->profiles)
2079         return NULL;
2080
2081     for (p = codec->profiles; p->profile != FF_PROFILE_UNKNOWN; p++)
2082         if (p->profile == profile)
2083             return p->name;
2084
2085     return NULL;
2086 }
2087
2088 unsigned avcodec_version(void)
2089 {
2090     return LIBAVCODEC_VERSION_INT;
2091 }
2092
2093 const char *avcodec_configuration(void)
2094 {
2095     return LIBAV_CONFIGURATION;
2096 }
2097
2098 const char *avcodec_license(void)
2099 {
2100 #define LICENSE_PREFIX "libavcodec license: "
2101     return LICENSE_PREFIX LIBAV_LICENSE + sizeof(LICENSE_PREFIX) - 1;
2102 }
2103
2104 void avcodec_flush_buffers(AVCodecContext *avctx)
2105 {
2106     if (HAVE_THREADS && avctx->active_thread_type & FF_THREAD_FRAME)
2107         ff_thread_flush(avctx);
2108     else if (avctx->codec->flush)
2109         avctx->codec->flush(avctx);
2110
2111     if (!avctx->refcounted_frames)
2112         av_frame_unref(avctx->internal->to_free);
2113 }
2114
2115 int av_get_exact_bits_per_sample(enum AVCodecID codec_id)
2116 {
2117     switch (codec_id) {
2118     case AV_CODEC_ID_ADPCM_CT:
2119     case AV_CODEC_ID_ADPCM_IMA_APC:
2120     case AV_CODEC_ID_ADPCM_IMA_EA_SEAD:
2121     case AV_CODEC_ID_ADPCM_IMA_WS:
2122     case AV_CODEC_ID_ADPCM_G722:
2123     case AV_CODEC_ID_ADPCM_YAMAHA:
2124         return 4;
2125     case AV_CODEC_ID_PCM_ALAW:
2126     case AV_CODEC_ID_PCM_MULAW:
2127     case AV_CODEC_ID_PCM_S8:
2128     case AV_CODEC_ID_PCM_U8:
2129     case AV_CODEC_ID_PCM_ZORK:
2130         return 8;
2131     case AV_CODEC_ID_PCM_S16BE:
2132     case AV_CODEC_ID_PCM_S16LE:
2133     case AV_CODEC_ID_PCM_S16LE_PLANAR:
2134     case AV_CODEC_ID_PCM_U16BE:
2135     case AV_CODEC_ID_PCM_U16LE:
2136         return 16;
2137     case AV_CODEC_ID_PCM_S24DAUD:
2138     case AV_CODEC_ID_PCM_S24BE:
2139     case AV_CODEC_ID_PCM_S24LE:
2140     case AV_CODEC_ID_PCM_S24LE_PLANAR:
2141     case AV_CODEC_ID_PCM_U24BE:
2142     case AV_CODEC_ID_PCM_U24LE:
2143         return 24;
2144     case AV_CODEC_ID_PCM_S32BE:
2145     case AV_CODEC_ID_PCM_S32LE:
2146     case AV_CODEC_ID_PCM_S32LE_PLANAR:
2147     case AV_CODEC_ID_PCM_U32BE:
2148     case AV_CODEC_ID_PCM_U32LE:
2149     case AV_CODEC_ID_PCM_F32BE:
2150     case AV_CODEC_ID_PCM_F32LE:
2151         return 32;
2152     case AV_CODEC_ID_PCM_F64BE:
2153     case AV_CODEC_ID_PCM_F64LE:
2154         return 64;
2155     default:
2156         return 0;
2157     }
2158 }
2159
2160 int av_get_bits_per_sample(enum AVCodecID codec_id)
2161 {
2162     switch (codec_id) {
2163     case AV_CODEC_ID_ADPCM_SBPRO_2:
2164         return 2;
2165     case AV_CODEC_ID_ADPCM_SBPRO_3:
2166         return 3;
2167     case AV_CODEC_ID_ADPCM_SBPRO_4:
2168     case AV_CODEC_ID_ADPCM_IMA_WAV:
2169     case AV_CODEC_ID_ADPCM_IMA_QT:
2170     case AV_CODEC_ID_ADPCM_SWF:
2171     case AV_CODEC_ID_ADPCM_MS:
2172         return 4;
2173     default:
2174         return av_get_exact_bits_per_sample(codec_id);
2175     }
2176 }
2177
2178 int av_get_audio_frame_duration(AVCodecContext *avctx, int frame_bytes)
2179 {
2180     int id, sr, ch, ba, tag, bps;
2181
2182     id  = avctx->codec_id;
2183     sr  = avctx->sample_rate;
2184     ch  = avctx->channels;
2185     ba  = avctx->block_align;
2186     tag = avctx->codec_tag;
2187     bps = av_get_exact_bits_per_sample(avctx->codec_id);
2188
2189     /* codecs with an exact constant bits per sample */
2190     if (bps > 0 && ch > 0 && frame_bytes > 0)
2191         return (frame_bytes * 8) / (bps * ch);
2192     bps = avctx->bits_per_coded_sample;
2193
2194     /* codecs with a fixed packet duration */
2195     switch (id) {
2196     case AV_CODEC_ID_ADPCM_ADX:    return   32;
2197     case AV_CODEC_ID_ADPCM_IMA_QT: return   64;
2198     case AV_CODEC_ID_ADPCM_EA_XAS: return  128;
2199     case AV_CODEC_ID_AMR_NB:
2200     case AV_CODEC_ID_GSM:
2201     case AV_CODEC_ID_QCELP:
2202     case AV_CODEC_ID_RA_144:
2203     case AV_CODEC_ID_RA_288:       return  160;
2204     case AV_CODEC_ID_IMC:          return  256;
2205     case AV_CODEC_ID_AMR_WB:
2206     case AV_CODEC_ID_GSM_MS:       return  320;
2207     case AV_CODEC_ID_MP1:          return  384;
2208     case AV_CODEC_ID_ATRAC1:       return  512;
2209     case AV_CODEC_ID_ATRAC3:       return 1024;
2210     case AV_CODEC_ID_MP2:
2211     case AV_CODEC_ID_MUSEPACK7:    return 1152;
2212     case AV_CODEC_ID_AC3:          return 1536;
2213     }
2214
2215     if (sr > 0) {
2216         /* calc from sample rate */
2217         if (id == AV_CODEC_ID_TTA)
2218             return 256 * sr / 245;
2219
2220         if (ch > 0) {
2221             /* calc from sample rate and channels */
2222             if (id == AV_CODEC_ID_BINKAUDIO_DCT)
2223                 return (480 << (sr / 22050)) / ch;
2224         }
2225     }
2226
2227     if (ba > 0) {
2228         /* calc from block_align */
2229         if (id == AV_CODEC_ID_SIPR) {
2230             switch (ba) {
2231             case 20: return 160;
2232             case 19: return 144;
2233             case 29: return 288;
2234             case 37: return 480;
2235             }
2236         } else if (id == AV_CODEC_ID_ILBC) {
2237             switch (ba) {
2238             case 38: return 160;
2239             case 50: return 240;
2240             }
2241         }
2242     }
2243
2244     if (frame_bytes > 0) {
2245         /* calc from frame_bytes only */
2246         if (id == AV_CODEC_ID_TRUESPEECH)
2247             return 240 * (frame_bytes / 32);
2248         if (id == AV_CODEC_ID_NELLYMOSER)
2249             return 256 * (frame_bytes / 64);
2250
2251         if (bps > 0) {
2252             /* calc from frame_bytes and bits_per_coded_sample */
2253             if (id == AV_CODEC_ID_ADPCM_G726)
2254                 return frame_bytes * 8 / bps;
2255         }
2256
2257         if (ch > 0) {
2258             /* calc from frame_bytes and channels */
2259             switch (id) {
2260             case AV_CODEC_ID_ADPCM_4XM:
2261             case AV_CODEC_ID_ADPCM_IMA_ISS:
2262                 return (frame_bytes - 4 * ch) * 2 / ch;
2263             case AV_CODEC_ID_ADPCM_IMA_SMJPEG:
2264                 return (frame_bytes - 4) * 2 / ch;
2265             case AV_CODEC_ID_ADPCM_IMA_AMV:
2266                 return (frame_bytes - 8) * 2 / ch;
2267             case AV_CODEC_ID_ADPCM_XA:
2268                 return (frame_bytes / 128) * 224 / ch;
2269             case AV_CODEC_ID_INTERPLAY_DPCM:
2270                 return (frame_bytes - 6 - ch) / ch;
2271             case AV_CODEC_ID_ROQ_DPCM:
2272                 return (frame_bytes - 8) / ch;
2273             case AV_CODEC_ID_XAN_DPCM:
2274                 return (frame_bytes - 2 * ch) / ch;
2275             case AV_CODEC_ID_MACE3:
2276                 return 3 * frame_bytes / ch;
2277             case AV_CODEC_ID_MACE6:
2278                 return 6 * frame_bytes / ch;
2279             case AV_CODEC_ID_PCM_LXF:
2280                 return 2 * (frame_bytes / (5 * ch));
2281             }
2282
2283             if (tag) {
2284                 /* calc from frame_bytes, channels, and codec_tag */
2285                 if (id == AV_CODEC_ID_SOL_DPCM) {
2286                     if (tag == 3)
2287                         return frame_bytes / ch;
2288                     else
2289                         return frame_bytes * 2 / ch;
2290                 }
2291             }
2292
2293             if (ba > 0) {
2294                 /* calc from frame_bytes, channels, and block_align */
2295                 int blocks = frame_bytes / ba;
2296                 switch (avctx->codec_id) {
2297                 case AV_CODEC_ID_ADPCM_IMA_WAV:
2298                     return blocks * (1 + (ba - 4 * ch) / (4 * ch) * 8);
2299                 case AV_CODEC_ID_ADPCM_IMA_DK3:
2300                     return blocks * (((ba - 16) * 2 / 3 * 4) / ch);
2301                 case AV_CODEC_ID_ADPCM_IMA_DK4:
2302                     return blocks * (1 + (ba - 4 * ch) * 2 / ch);
2303                 case AV_CODEC_ID_ADPCM_MS:
2304                     return blocks * (2 + (ba - 7 * ch) * 2 / ch);
2305                 }
2306             }
2307
2308             if (bps > 0) {
2309                 /* calc from frame_bytes, channels, and bits_per_coded_sample */
2310                 switch (avctx->codec_id) {
2311                 case AV_CODEC_ID_PCM_DVD:
2312                     return 2 * (frame_bytes / ((bps * 2 / 8) * ch));
2313                 case AV_CODEC_ID_PCM_BLURAY:
2314                     return frame_bytes / ((FFALIGN(ch, 2) * bps) / 8);
2315                 case AV_CODEC_ID_S302M:
2316                     return 2 * (frame_bytes / ((bps + 4) / 4)) / ch;
2317                 }
2318             }
2319         }
2320     }
2321
2322     return 0;
2323 }
2324
2325 #if !HAVE_THREADS
2326 int ff_thread_init(AVCodecContext *s)
2327 {
2328     return -1;
2329 }
2330
2331 #endif
2332
2333 unsigned int av_xiphlacing(unsigned char *s, unsigned int v)
2334 {
2335     unsigned int n = 0;
2336
2337     while (v >= 0xff) {
2338         *s++ = 0xff;
2339         v -= 0xff;
2340         n++;
2341     }
2342     *s = v;
2343     n++;
2344     return n;
2345 }
2346
2347 int ff_match_2uint16(const uint16_t(*tab)[2], int size, int a, int b)
2348 {
2349     int i;
2350     for (i = 0; i < size && !(tab[i][0] == a && tab[i][1] == b); i++) ;
2351     return i;
2352 }
2353
2354 #if FF_API_MISSING_SAMPLE
2355 FF_DISABLE_DEPRECATION_WARNINGS
2356 void av_log_missing_feature(void *avc, const char *feature, int want_sample)
2357 {
2358     av_log(avc, AV_LOG_WARNING, "%s is not implemented. Update your Libav "
2359             "version to the newest one from Git. If the problem still "
2360             "occurs, it means that your file has a feature which has not "
2361             "been implemented.\n", feature);
2362     if(want_sample)
2363         av_log_ask_for_sample(avc, NULL);
2364 }
2365
2366 void av_log_ask_for_sample(void *avc, const char *msg, ...)
2367 {
2368     va_list argument_list;
2369
2370     va_start(argument_list, msg);
2371
2372     if (msg)
2373         av_vlog(avc, AV_LOG_WARNING, msg, argument_list);
2374     av_log(avc, AV_LOG_WARNING, "If you want to help, upload a sample "
2375             "of this file to ftp://upload.libav.org/incoming/ "
2376             "and contact the libav-devel mailing list.\n");
2377
2378     va_end(argument_list);
2379 }
2380 FF_ENABLE_DEPRECATION_WARNINGS
2381 #endif /* FF_API_MISSING_SAMPLE */
2382
2383 static AVHWAccel *first_hwaccel = NULL;
2384
2385 void av_register_hwaccel(AVHWAccel *hwaccel)
2386 {
2387     AVHWAccel **p = &first_hwaccel;
2388     while (*p)
2389         p = &(*p)->next;
2390     *p = hwaccel;
2391     hwaccel->next = NULL;
2392 }
2393
2394 AVHWAccel *av_hwaccel_next(const AVHWAccel *hwaccel)
2395 {
2396     return hwaccel ? hwaccel->next : first_hwaccel;
2397 }
2398
2399 int av_lockmgr_register(int (*cb)(void **mutex, enum AVLockOp op))
2400 {
2401     if (lockmgr_cb) {
2402         // There is no good way to rollback a failure to destroy the
2403         // mutex, so we ignore failures.
2404         lockmgr_cb(&codec_mutex,    AV_LOCK_DESTROY);
2405         lockmgr_cb(&avformat_mutex, AV_LOCK_DESTROY);
2406         lockmgr_cb     = NULL;
2407         codec_mutex    = NULL;
2408         avformat_mutex = NULL;
2409     }
2410
2411     if (cb) {
2412         void *new_codec_mutex    = NULL;
2413         void *new_avformat_mutex = NULL;
2414         int err;
2415         if (err = cb(&new_codec_mutex, AV_LOCK_CREATE)) {
2416             return err > 0 ? AVERROR_UNKNOWN : err;
2417         }
2418         if (err = cb(&new_avformat_mutex, AV_LOCK_CREATE)) {
2419             // Ignore failures to destroy the newly created mutex.
2420             cb(&new_codec_mutex, AV_LOCK_DESTROY);
2421             return err > 0 ? AVERROR_UNKNOWN : err;
2422         }
2423         lockmgr_cb     = cb;
2424         codec_mutex    = new_codec_mutex;
2425         avformat_mutex = new_avformat_mutex;
2426     }
2427
2428     return 0;
2429 }
2430
2431 int avpriv_lock_avformat(void)
2432 {
2433     if (lockmgr_cb) {
2434         if ((*lockmgr_cb)(&avformat_mutex, AV_LOCK_OBTAIN))
2435             return -1;
2436     }
2437     return 0;
2438 }
2439
2440 int avpriv_unlock_avformat(void)
2441 {
2442     if (lockmgr_cb) {
2443         if ((*lockmgr_cb)(&avformat_mutex, AV_LOCK_RELEASE))
2444             return -1;
2445     }
2446     return 0;
2447 }
2448
2449 unsigned int avpriv_toupper4(unsigned int x)
2450 {
2451     return av_toupper(x & 0xFF) +
2452           (av_toupper((x >>  8) & 0xFF) << 8)  +
2453           (av_toupper((x >> 16) & 0xFF) << 16) +
2454           (av_toupper((x >> 24) & 0xFF) << 24);
2455 }
2456
2457 int ff_thread_ref_frame(ThreadFrame *dst, ThreadFrame *src)
2458 {
2459     int ret;
2460
2461     dst->owner = src->owner;
2462
2463     ret = av_frame_ref(dst->f, src->f);
2464     if (ret < 0)
2465         return ret;
2466
2467     if (src->progress &&
2468         !(dst->progress = av_buffer_ref(src->progress))) {
2469         ff_thread_release_buffer(dst->owner, dst);
2470         return AVERROR(ENOMEM);
2471     }
2472
2473     return 0;
2474 }
2475
2476 #if !HAVE_THREADS
2477
2478 int ff_thread_get_buffer(AVCodecContext *avctx, ThreadFrame *f, int flags)
2479 {
2480     f->owner = avctx;
2481     return ff_get_buffer(avctx, f->f, flags);
2482 }
2483
2484 void ff_thread_release_buffer(AVCodecContext *avctx, ThreadFrame *f)
2485 {
2486     if (f->f)
2487         av_frame_unref(f->f);
2488 }
2489
2490 void ff_thread_finish_setup(AVCodecContext *avctx)
2491 {
2492 }
2493
2494 void ff_thread_report_progress(ThreadFrame *f, int progress, int field)
2495 {
2496 }
2497
2498 void ff_thread_await_progress(ThreadFrame *f, int progress, int field)
2499 {
2500 }
2501
2502 #endif
2503
2504 enum AVMediaType avcodec_get_type(enum AVCodecID codec_id)
2505 {
2506     if (codec_id <= AV_CODEC_ID_NONE)
2507         return AVMEDIA_TYPE_UNKNOWN;
2508     else if (codec_id < AV_CODEC_ID_FIRST_AUDIO)
2509         return AVMEDIA_TYPE_VIDEO;
2510     else if (codec_id < AV_CODEC_ID_FIRST_SUBTITLE)
2511         return AVMEDIA_TYPE_AUDIO;
2512     else if (codec_id < AV_CODEC_ID_FIRST_UNKNOWN)
2513         return AVMEDIA_TYPE_SUBTITLE;
2514
2515     return AVMEDIA_TYPE_UNKNOWN;
2516 }
2517
2518 int avcodec_is_open(AVCodecContext *s)
2519 {
2520     return !!s->internal;
2521 }
2522
2523 const uint8_t *avpriv_find_start_code(const uint8_t *restrict p,
2524                                       const uint8_t *end,
2525                                       uint32_t * restrict state)
2526 {
2527     int i;
2528
2529     assert(p <= end);
2530     if (p >= end)
2531         return end;
2532
2533     for (i = 0; i < 3; i++) {
2534         uint32_t tmp = *state << 8;
2535         *state = tmp + *(p++);
2536         if (tmp == 0x100 || p == end)
2537             return p;
2538     }
2539
2540     while (p < end) {
2541         if      (p[-1] > 1      ) p += 3;
2542         else if (p[-2]          ) p += 2;
2543         else if (p[-3]|(p[-1]-1)) p++;
2544         else {
2545             p++;
2546             break;
2547         }
2548     }
2549
2550     p = FFMIN(p, end) - 4;
2551     *state = AV_RB32(p);
2552
2553     return p + 4;
2554 }