3 * Copyright (c) 2001 Fabrice Bellard
4 * Copyright (c) 2002-2004 Michael Niedermayer <michaelni@gmx.at>
6 * This file is part of FFmpeg.
8 * FFmpeg is free software; you can redistribute it and/or
9 * modify it under the terms of the GNU Lesser General Public
10 * License as published by the Free Software Foundation; either
11 * version 2.1 of the License, or (at your option) any later version.
13 * FFmpeg is distributed in the hope that it will be useful,
14 * but WITHOUT ANY WARRANTY; without even the implied warranty of
15 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
16 * Lesser General Public License for more details.
18 * You should have received a copy of the GNU Lesser General Public
19 * License along with FFmpeg; if not, write to the Free Software
20 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
29 #include "libavutil/atomic.h"
30 #include "libavutil/attributes.h"
31 #include "libavutil/avassert.h"
32 #include "libavutil/avstring.h"
33 #include "libavutil/bprint.h"
34 #include "libavutil/channel_layout.h"
35 #include "libavutil/crc.h"
36 #include "libavutil/frame.h"
37 #include "libavutil/internal.h"
38 #include "libavutil/mathematics.h"
39 #include "libavutil/pixdesc.h"
40 #include "libavutil/imgutils.h"
41 #include "libavutil/samplefmt.h"
42 #include "libavutil/dict.h"
45 #include "libavutil/opt.h"
47 #include "frame_thread_encoder.h"
49 #include "bytestream.h"
62 #include "compat/w32pthreads.h"
64 #include "compat/os2threads.h"
67 #if HAVE_PTHREADS || HAVE_W32THREADS || HAVE_OS2THREADS
68 static int default_lockmgr_cb(void **arg, enum AVLockOp op)
70 void * volatile * mutex = arg;
78 pthread_mutex_t *tmp = av_malloc(sizeof(pthread_mutex_t));
80 return AVERROR(ENOMEM);
81 if ((err = pthread_mutex_init(tmp, NULL))) {
85 if (avpriv_atomic_ptr_cas(mutex, NULL, tmp)) {
86 pthread_mutex_destroy(tmp);
91 if ((err = pthread_mutex_lock(*mutex)))
96 if ((err = pthread_mutex_unlock(*mutex)))
100 case AV_LOCK_DESTROY:
102 pthread_mutex_destroy(*mutex);
104 avpriv_atomic_ptr_cas(mutex, *mutex, NULL);
109 static int (*lockmgr_cb)(void **mutex, enum AVLockOp op) = default_lockmgr_cb;
111 static int (*lockmgr_cb)(void **mutex, enum AVLockOp op) = NULL;
115 volatile int ff_avcodec_locked;
116 static int volatile entangled_thread_counter = 0;
117 static void *codec_mutex;
118 static void *avformat_mutex;
120 #if FF_API_FAST_MALLOC && CONFIG_SHARED && HAVE_SYMVER
121 FF_SYMVER(void*, av_fast_realloc, (void *ptr, unsigned int *size, size_t min_size), "LIBAVCODEC_55")
123 return av_fast_realloc(ptr, size, min_size);
126 FF_SYMVER(void, av_fast_malloc, (void *ptr, unsigned int *size, size_t min_size), "LIBAVCODEC_55")
128 av_fast_malloc(ptr, size, min_size);
132 static inline int ff_fast_malloc(void *ptr, unsigned int *size, size_t min_size, int zero_realloc)
135 if (min_size < *size)
137 min_size = FFMAX(17 * min_size / 16 + 32, min_size);
139 *p = zero_realloc ? av_mallocz(min_size) : av_malloc(min_size);
146 void av_fast_padded_malloc(void *ptr, unsigned int *size, size_t min_size)
149 if (min_size > SIZE_MAX - FF_INPUT_BUFFER_PADDING_SIZE) {
154 if (!ff_fast_malloc(p, size, min_size + FF_INPUT_BUFFER_PADDING_SIZE, 1))
155 memset(*p + min_size, 0, FF_INPUT_BUFFER_PADDING_SIZE);
158 void av_fast_padded_mallocz(void *ptr, unsigned int *size, size_t min_size)
161 if (min_size > SIZE_MAX - FF_INPUT_BUFFER_PADDING_SIZE) {
166 if (!ff_fast_malloc(p, size, min_size + FF_INPUT_BUFFER_PADDING_SIZE, 1))
167 memset(*p, 0, min_size + FF_INPUT_BUFFER_PADDING_SIZE);
170 /* encoder management */
171 static AVCodec *first_avcodec = NULL;
172 static AVCodec **last_avcodec = &first_avcodec;
174 AVCodec *av_codec_next(const AVCodec *c)
179 return first_avcodec;
182 static av_cold void avcodec_init(void)
184 static int initialized = 0;
186 if (initialized != 0)
191 ff_dsputil_static_init();
194 int av_codec_is_encoder(const AVCodec *codec)
196 return codec && (codec->encode_sub || codec->encode2);
199 int av_codec_is_decoder(const AVCodec *codec)
201 return codec && codec->decode;
204 av_cold void avcodec_register(AVCodec *codec)
211 while(*p || avpriv_atomic_ptr_cas((void * volatile *)p, NULL, codec))
213 last_avcodec = &codec->next;
215 if (codec->init_static_data)
216 codec->init_static_data(codec);
219 unsigned avcodec_get_edge_width(void)
224 #if FF_API_SET_DIMENSIONS
225 void avcodec_set_dimensions(AVCodecContext *s, int width, int height)
227 int ret = ff_set_dimensions(s, width, height);
229 av_log(s, AV_LOG_WARNING, "Failed to set dimensions %d %d\n", width, height);
234 int ff_set_dimensions(AVCodecContext *s, int width, int height)
236 int ret = av_image_check_size(width, height, 0, s);
241 s->coded_width = width;
242 s->coded_height = height;
243 s->width = FF_CEIL_RSHIFT(width, s->lowres);
244 s->height = FF_CEIL_RSHIFT(height, s->lowres);
249 #if HAVE_NEON || ARCH_PPC || HAVE_MMX
250 # define STRIDE_ALIGN 16
252 # define STRIDE_ALIGN 8
255 void avcodec_align_dimensions2(AVCodecContext *s, int *width, int *height,
256 int linesize_align[AV_NUM_DATA_POINTERS])
262 switch (s->pix_fmt) {
263 case AV_PIX_FMT_YUV420P:
264 case AV_PIX_FMT_YUYV422:
265 case AV_PIX_FMT_UYVY422:
266 case AV_PIX_FMT_YUV422P:
267 case AV_PIX_FMT_YUV440P:
268 case AV_PIX_FMT_YUV444P:
269 case AV_PIX_FMT_GBRAP:
270 case AV_PIX_FMT_GBRP:
271 case AV_PIX_FMT_GRAY8:
272 case AV_PIX_FMT_GRAY16BE:
273 case AV_PIX_FMT_GRAY16LE:
274 case AV_PIX_FMT_YUVJ420P:
275 case AV_PIX_FMT_YUVJ422P:
276 case AV_PIX_FMT_YUVJ440P:
277 case AV_PIX_FMT_YUVJ444P:
278 case AV_PIX_FMT_YUVA420P:
279 case AV_PIX_FMT_YUVA422P:
280 case AV_PIX_FMT_YUVA444P:
281 case AV_PIX_FMT_YUV420P9LE:
282 case AV_PIX_FMT_YUV420P9BE:
283 case AV_PIX_FMT_YUV420P10LE:
284 case AV_PIX_FMT_YUV420P10BE:
285 case AV_PIX_FMT_YUV420P12LE:
286 case AV_PIX_FMT_YUV420P12BE:
287 case AV_PIX_FMT_YUV420P14LE:
288 case AV_PIX_FMT_YUV420P14BE:
289 case AV_PIX_FMT_YUV420P16LE:
290 case AV_PIX_FMT_YUV420P16BE:
291 case AV_PIX_FMT_YUV422P9LE:
292 case AV_PIX_FMT_YUV422P9BE:
293 case AV_PIX_FMT_YUV422P10LE:
294 case AV_PIX_FMT_YUV422P10BE:
295 case AV_PIX_FMT_YUV422P12LE:
296 case AV_PIX_FMT_YUV422P12BE:
297 case AV_PIX_FMT_YUV422P14LE:
298 case AV_PIX_FMT_YUV422P14BE:
299 case AV_PIX_FMT_YUV422P16LE:
300 case AV_PIX_FMT_YUV422P16BE:
301 case AV_PIX_FMT_YUV444P9LE:
302 case AV_PIX_FMT_YUV444P9BE:
303 case AV_PIX_FMT_YUV444P10LE:
304 case AV_PIX_FMT_YUV444P10BE:
305 case AV_PIX_FMT_YUV444P12LE:
306 case AV_PIX_FMT_YUV444P12BE:
307 case AV_PIX_FMT_YUV444P14LE:
308 case AV_PIX_FMT_YUV444P14BE:
309 case AV_PIX_FMT_YUV444P16LE:
310 case AV_PIX_FMT_YUV444P16BE:
311 case AV_PIX_FMT_YUVA420P9LE:
312 case AV_PIX_FMT_YUVA420P9BE:
313 case AV_PIX_FMT_YUVA420P10LE:
314 case AV_PIX_FMT_YUVA420P10BE:
315 case AV_PIX_FMT_YUVA420P16LE:
316 case AV_PIX_FMT_YUVA420P16BE:
317 case AV_PIX_FMT_YUVA422P9LE:
318 case AV_PIX_FMT_YUVA422P9BE:
319 case AV_PIX_FMT_YUVA422P10LE:
320 case AV_PIX_FMT_YUVA422P10BE:
321 case AV_PIX_FMT_YUVA422P16LE:
322 case AV_PIX_FMT_YUVA422P16BE:
323 case AV_PIX_FMT_YUVA444P9LE:
324 case AV_PIX_FMT_YUVA444P9BE:
325 case AV_PIX_FMT_YUVA444P10LE:
326 case AV_PIX_FMT_YUVA444P10BE:
327 case AV_PIX_FMT_YUVA444P16LE:
328 case AV_PIX_FMT_YUVA444P16BE:
329 case AV_PIX_FMT_GBRP9LE:
330 case AV_PIX_FMT_GBRP9BE:
331 case AV_PIX_FMT_GBRP10LE:
332 case AV_PIX_FMT_GBRP10BE:
333 case AV_PIX_FMT_GBRP12LE:
334 case AV_PIX_FMT_GBRP12BE:
335 case AV_PIX_FMT_GBRP14LE:
336 case AV_PIX_FMT_GBRP14BE:
337 w_align = 16; //FIXME assume 16 pixel per macroblock
338 h_align = 16 * 2; // interlaced needs 2 macroblocks height
340 case AV_PIX_FMT_YUV411P:
341 case AV_PIX_FMT_YUVJ411P:
342 case AV_PIX_FMT_UYYVYY411:
346 case AV_PIX_FMT_YUV410P:
347 if (s->codec_id == AV_CODEC_ID_SVQ1) {
352 case AV_PIX_FMT_RGB555:
353 if (s->codec_id == AV_CODEC_ID_RPZA) {
358 case AV_PIX_FMT_PAL8:
359 case AV_PIX_FMT_BGR8:
360 case AV_PIX_FMT_RGB8:
361 if (s->codec_id == AV_CODEC_ID_SMC ||
362 s->codec_id == AV_CODEC_ID_CINEPAK) {
367 case AV_PIX_FMT_BGR24:
368 if ((s->codec_id == AV_CODEC_ID_MSZH) ||
369 (s->codec_id == AV_CODEC_ID_ZLIB)) {
374 case AV_PIX_FMT_RGB24:
375 if (s->codec_id == AV_CODEC_ID_CINEPAK) {
386 if (s->codec_id == AV_CODEC_ID_IFF_ILBM || s->codec_id == AV_CODEC_ID_IFF_BYTERUN1) {
387 w_align = FFMAX(w_align, 8);
390 *width = FFALIGN(*width, w_align);
391 *height = FFALIGN(*height, h_align);
392 if (s->codec_id == AV_CODEC_ID_H264 || s->lowres)
393 // some of the optimized chroma MC reads one line too much
394 // which is also done in mpeg decoders with lowres > 0
397 for (i = 0; i < 4; i++)
398 linesize_align[i] = STRIDE_ALIGN;
401 void avcodec_align_dimensions(AVCodecContext *s, int *width, int *height)
403 const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(s->pix_fmt);
404 int chroma_shift = desc->log2_chroma_w;
405 int linesize_align[AV_NUM_DATA_POINTERS];
408 avcodec_align_dimensions2(s, width, height, linesize_align);
409 align = FFMAX(linesize_align[0], linesize_align[3]);
410 linesize_align[1] <<= chroma_shift;
411 linesize_align[2] <<= chroma_shift;
412 align = FFMAX3(align, linesize_align[1], linesize_align[2]);
413 *width = FFALIGN(*width, align);
416 int avcodec_enum_to_chroma_pos(int *xpos, int *ypos, enum AVChromaLocation pos)
418 if (pos <= AVCHROMA_LOC_UNSPECIFIED || pos >= AVCHROMA_LOC_NB)
419 return AVERROR(EINVAL);
422 *xpos = (pos&1) * 128;
423 *ypos = ((pos>>1)^(pos<4)) * 128;
428 enum AVChromaLocation avcodec_chroma_pos_to_enum(int xpos, int ypos)
432 for (pos = AVCHROMA_LOC_UNSPECIFIED + 1; pos < AVCHROMA_LOC_NB; pos++) {
433 if (avcodec_enum_to_chroma_pos(&xout, &yout, pos) == 0 && xout == xpos && yout == ypos)
436 return AVCHROMA_LOC_UNSPECIFIED;
439 int avcodec_fill_audio_frame(AVFrame *frame, int nb_channels,
440 enum AVSampleFormat sample_fmt, const uint8_t *buf,
441 int buf_size, int align)
443 int ch, planar, needed_size, ret = 0;
445 needed_size = av_samples_get_buffer_size(NULL, nb_channels,
446 frame->nb_samples, sample_fmt,
448 if (buf_size < needed_size)
449 return AVERROR(EINVAL);
451 planar = av_sample_fmt_is_planar(sample_fmt);
452 if (planar && nb_channels > AV_NUM_DATA_POINTERS) {
453 if (!(frame->extended_data = av_mallocz(nb_channels *
454 sizeof(*frame->extended_data))))
455 return AVERROR(ENOMEM);
457 frame->extended_data = frame->data;
460 if ((ret = av_samples_fill_arrays(frame->extended_data, &frame->linesize[0],
461 (uint8_t *)(intptr_t)buf, nb_channels, frame->nb_samples,
462 sample_fmt, align)) < 0) {
463 if (frame->extended_data != frame->data)
464 av_freep(&frame->extended_data);
467 if (frame->extended_data != frame->data) {
468 for (ch = 0; ch < AV_NUM_DATA_POINTERS; ch++)
469 frame->data[ch] = frame->extended_data[ch];
475 static int update_frame_pool(AVCodecContext *avctx, AVFrame *frame)
477 FramePool *pool = avctx->internal->pool;
480 switch (avctx->codec_type) {
481 case AVMEDIA_TYPE_VIDEO: {
484 int w = frame->width;
485 int h = frame->height;
486 int tmpsize, unaligned;
488 if (pool->format == frame->format &&
489 pool->width == frame->width && pool->height == frame->height)
492 avcodec_align_dimensions2(avctx, &w, &h, pool->stride_align);
494 if (!(avctx->flags & CODEC_FLAG_EMU_EDGE)) {
500 // NOTE: do not align linesizes individually, this breaks e.g. assumptions
501 // that linesize[0] == 2*linesize[1] in the MPEG-encoder for 4:2:2
502 av_image_fill_linesizes(picture.linesize, avctx->pix_fmt, w);
503 // increase alignment of w for next try (rhs gives the lowest bit set in w)
507 for (i = 0; i < 4; i++)
508 unaligned |= picture.linesize[i] % pool->stride_align[i];
511 tmpsize = av_image_fill_pointers(picture.data, avctx->pix_fmt, h,
512 NULL, picture.linesize);
516 for (i = 0; i < 3 && picture.data[i + 1]; i++)
517 size[i] = picture.data[i + 1] - picture.data[i];
518 size[i] = tmpsize - (picture.data[i] - picture.data[0]);
520 for (i = 0; i < 4; i++) {
521 av_buffer_pool_uninit(&pool->pools[i]);
522 pool->linesize[i] = picture.linesize[i];
524 pool->pools[i] = av_buffer_pool_init(size[i] + 16 + STRIDE_ALIGN - 1,
525 CONFIG_MEMORY_POISONING ?
528 if (!pool->pools[i]) {
529 ret = AVERROR(ENOMEM);
534 pool->format = frame->format;
535 pool->width = frame->width;
536 pool->height = frame->height;
540 case AVMEDIA_TYPE_AUDIO: {
541 int ch = av_frame_get_channels(frame); //av_get_channel_layout_nb_channels(frame->channel_layout);
542 int planar = av_sample_fmt_is_planar(frame->format);
543 int planes = planar ? ch : 1;
545 if (pool->format == frame->format && pool->planes == planes &&
546 pool->channels == ch && frame->nb_samples == pool->samples)
549 av_buffer_pool_uninit(&pool->pools[0]);
550 ret = av_samples_get_buffer_size(&pool->linesize[0], ch,
551 frame->nb_samples, frame->format, 0);
555 pool->pools[0] = av_buffer_pool_init(pool->linesize[0], NULL);
556 if (!pool->pools[0]) {
557 ret = AVERROR(ENOMEM);
561 pool->format = frame->format;
562 pool->planes = planes;
564 pool->samples = frame->nb_samples;
567 default: av_assert0(0);
571 for (i = 0; i < 4; i++)
572 av_buffer_pool_uninit(&pool->pools[i]);
574 pool->planes = pool->channels = pool->samples = 0;
575 pool->width = pool->height = 0;
579 static int audio_get_buffer(AVCodecContext *avctx, AVFrame *frame)
581 FramePool *pool = avctx->internal->pool;
582 int planes = pool->planes;
585 frame->linesize[0] = pool->linesize[0];
587 if (planes > AV_NUM_DATA_POINTERS) {
588 frame->extended_data = av_mallocz(planes * sizeof(*frame->extended_data));
589 frame->nb_extended_buf = planes - AV_NUM_DATA_POINTERS;
590 frame->extended_buf = av_mallocz(frame->nb_extended_buf *
591 sizeof(*frame->extended_buf));
592 if (!frame->extended_data || !frame->extended_buf) {
593 av_freep(&frame->extended_data);
594 av_freep(&frame->extended_buf);
595 return AVERROR(ENOMEM);
598 frame->extended_data = frame->data;
599 av_assert0(frame->nb_extended_buf == 0);
602 for (i = 0; i < FFMIN(planes, AV_NUM_DATA_POINTERS); i++) {
603 frame->buf[i] = av_buffer_pool_get(pool->pools[0]);
606 frame->extended_data[i] = frame->data[i] = frame->buf[i]->data;
608 for (i = 0; i < frame->nb_extended_buf; i++) {
609 frame->extended_buf[i] = av_buffer_pool_get(pool->pools[0]);
610 if (!frame->extended_buf[i])
612 frame->extended_data[i + AV_NUM_DATA_POINTERS] = frame->extended_buf[i]->data;
615 if (avctx->debug & FF_DEBUG_BUFFERS)
616 av_log(avctx, AV_LOG_DEBUG, "default_get_buffer called on frame %p", frame);
620 av_frame_unref(frame);
621 return AVERROR(ENOMEM);
624 static int video_get_buffer(AVCodecContext *s, AVFrame *pic)
626 FramePool *pool = s->internal->pool;
627 const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(pic->format);
628 int pixel_size = desc->comp[0].step_minus1 + 1;
629 int h_chroma_shift, v_chroma_shift;
632 if (pic->data[0] != NULL) {
633 av_log(s, AV_LOG_ERROR, "pic->data[0]!=NULL in avcodec_default_get_buffer\n");
637 memset(pic->data, 0, sizeof(pic->data));
638 pic->extended_data = pic->data;
640 av_pix_fmt_get_chroma_sub_sample(s->pix_fmt, &h_chroma_shift, &v_chroma_shift);
642 for (i = 0; i < 4 && pool->pools[i]; i++) {
643 const int h_shift = i == 0 ? 0 : h_chroma_shift;
644 const int v_shift = i == 0 ? 0 : v_chroma_shift;
645 int is_planar = pool->pools[2] || (i==0 && s->pix_fmt == AV_PIX_FMT_GRAY8);
647 pic->linesize[i] = pool->linesize[i];
649 pic->buf[i] = av_buffer_pool_get(pool->pools[i]);
653 // no edge if EDGE EMU or not planar YUV
654 if ((s->flags & CODEC_FLAG_EMU_EDGE) || !is_planar)
655 pic->data[i] = pic->buf[i]->data;
657 pic->data[i] = pic->buf[i]->data +
658 FFALIGN((pic->linesize[i] * EDGE_WIDTH >> v_shift) +
659 (pixel_size * EDGE_WIDTH >> h_shift), pool->stride_align[i]);
662 for (; i < AV_NUM_DATA_POINTERS; i++) {
664 pic->linesize[i] = 0;
666 if (pic->data[1] && !pic->data[2])
667 avpriv_set_systematic_pal2((uint32_t *)pic->data[1], s->pix_fmt);
669 if (s->debug & FF_DEBUG_BUFFERS)
670 av_log(s, AV_LOG_DEBUG, "default_get_buffer called on pic %p\n", pic);
675 return AVERROR(ENOMEM);
678 void avpriv_color_frame(AVFrame *frame, const int c[4])
680 const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(frame->format);
683 av_assert0(desc->flags & AV_PIX_FMT_FLAG_PLANAR);
685 for (p = 0; p<desc->nb_components; p++) {
686 uint8_t *dst = frame->data[p];
687 int is_chroma = p == 1 || p == 2;
688 int bytes = is_chroma ? FF_CEIL_RSHIFT(frame->width, desc->log2_chroma_w) : frame->width;
689 int height = is_chroma ? FF_CEIL_RSHIFT(frame->height, desc->log2_chroma_h) : frame->height;
690 for (y = 0; y < height; y++) {
691 if (desc->comp[0].depth_minus1 >= 8) {
692 for (x = 0; x<bytes; x++)
693 ((uint16_t*)dst)[x] = c[p];
695 memset(dst, c[p], bytes);
696 dst += frame->linesize[p];
701 int avcodec_default_get_buffer2(AVCodecContext *avctx, AVFrame *frame, int flags)
705 if ((ret = update_frame_pool(avctx, frame)) < 0)
708 #if FF_API_GET_BUFFER
709 FF_DISABLE_DEPRECATION_WARNINGS
710 frame->type = FF_BUFFER_TYPE_INTERNAL;
711 FF_ENABLE_DEPRECATION_WARNINGS
714 switch (avctx->codec_type) {
715 case AVMEDIA_TYPE_VIDEO:
716 return video_get_buffer(avctx, frame);
717 case AVMEDIA_TYPE_AUDIO:
718 return audio_get_buffer(avctx, frame);
724 int ff_init_buffer_info(AVCodecContext *avctx, AVFrame *frame)
726 if (avctx->internal->pkt) {
727 frame->pkt_pts = avctx->internal->pkt->pts;
728 av_frame_set_pkt_pos (frame, avctx->internal->pkt->pos);
729 av_frame_set_pkt_duration(frame, avctx->internal->pkt->duration);
730 av_frame_set_pkt_size (frame, avctx->internal->pkt->size);
732 frame->pkt_pts = AV_NOPTS_VALUE;
733 av_frame_set_pkt_pos (frame, -1);
734 av_frame_set_pkt_duration(frame, 0);
735 av_frame_set_pkt_size (frame, -1);
737 frame->reordered_opaque = avctx->reordered_opaque;
739 switch (avctx->codec->type) {
740 case AVMEDIA_TYPE_VIDEO:
741 frame->width = FFMAX(avctx->width, FF_CEIL_RSHIFT(avctx->coded_width, avctx->lowres));
742 frame->height = FFMAX(avctx->height, FF_CEIL_RSHIFT(avctx->coded_height, avctx->lowres));
743 if (frame->format < 0)
744 frame->format = avctx->pix_fmt;
745 if (!frame->sample_aspect_ratio.num)
746 frame->sample_aspect_ratio = avctx->sample_aspect_ratio;
747 if (av_frame_get_colorspace(frame) == AVCOL_SPC_UNSPECIFIED)
748 av_frame_set_colorspace(frame, avctx->colorspace);
749 if (av_frame_get_color_range(frame) == AVCOL_RANGE_UNSPECIFIED)
750 av_frame_set_color_range(frame, avctx->color_range);
752 case AVMEDIA_TYPE_AUDIO:
753 if (!frame->sample_rate)
754 frame->sample_rate = avctx->sample_rate;
755 if (frame->format < 0)
756 frame->format = avctx->sample_fmt;
757 if (!frame->channel_layout) {
758 if (avctx->channel_layout) {
759 if (av_get_channel_layout_nb_channels(avctx->channel_layout) !=
761 av_log(avctx, AV_LOG_ERROR, "Inconsistent channel "
763 return AVERROR(EINVAL);
766 frame->channel_layout = avctx->channel_layout;
768 if (avctx->channels > FF_SANE_NB_CHANNELS) {
769 av_log(avctx, AV_LOG_ERROR, "Too many channels: %d.\n",
771 return AVERROR(ENOSYS);
775 av_frame_set_channels(frame, avctx->channels);
781 #if FF_API_GET_BUFFER
782 FF_DISABLE_DEPRECATION_WARNINGS
783 int avcodec_default_get_buffer(AVCodecContext *avctx, AVFrame *frame)
785 return avcodec_default_get_buffer2(avctx, frame, 0);
788 typedef struct CompatReleaseBufPriv {
789 AVCodecContext avctx;
791 } CompatReleaseBufPriv;
793 static void compat_free_buffer(void *opaque, uint8_t *data)
795 CompatReleaseBufPriv *priv = opaque;
796 if (priv->avctx.release_buffer)
797 priv->avctx.release_buffer(&priv->avctx, &priv->frame);
801 static void compat_release_buffer(void *opaque, uint8_t *data)
803 AVBufferRef *buf = opaque;
804 av_buffer_unref(&buf);
806 FF_ENABLE_DEPRECATION_WARNINGS
809 static int get_buffer_internal(AVCodecContext *avctx, AVFrame *frame, int flags)
813 if (avctx->codec_type == AVMEDIA_TYPE_VIDEO) {
814 if ((ret = av_image_check_size(avctx->width, avctx->height, 0, avctx)) < 0 || avctx->pix_fmt<0) {
815 av_log(avctx, AV_LOG_ERROR, "video_get_buffer: image parameters invalid\n");
816 return AVERROR(EINVAL);
819 if ((ret = ff_init_buffer_info(avctx, frame)) < 0)
822 #if FF_API_GET_BUFFER
823 FF_DISABLE_DEPRECATION_WARNINGS
825 * Wrap an old get_buffer()-allocated buffer in a bunch of AVBuffers.
826 * We wrap each plane in its own AVBuffer. Each of those has a reference to
827 * a dummy AVBuffer as its private data, unreffing it on free.
828 * When all the planes are freed, the dummy buffer's free callback calls
831 if (avctx->get_buffer) {
832 CompatReleaseBufPriv *priv = NULL;
833 AVBufferRef *dummy_buf = NULL;
836 if (flags & AV_GET_BUFFER_FLAG_REF)
837 frame->reference = 1;
839 ret = avctx->get_buffer(avctx, frame);
843 /* return if the buffers are already set up
844 * this would happen e.g. when a custom get_buffer() calls
845 * avcodec_default_get_buffer
850 priv = av_mallocz(sizeof(*priv));
852 ret = AVERROR(ENOMEM);
855 priv->avctx = *avctx;
856 priv->frame = *frame;
858 dummy_buf = av_buffer_create(NULL, 0, compat_free_buffer, priv, 0);
860 ret = AVERROR(ENOMEM);
864 #define WRAP_PLANE(ref_out, data, data_size) \
866 AVBufferRef *dummy_ref = av_buffer_ref(dummy_buf); \
868 ret = AVERROR(ENOMEM); \
871 ref_out = av_buffer_create(data, data_size, compat_release_buffer, \
874 av_frame_unref(frame); \
875 ret = AVERROR(ENOMEM); \
880 if (avctx->codec_type == AVMEDIA_TYPE_VIDEO) {
881 const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(frame->format);
883 planes = av_pix_fmt_count_planes(frame->format);
884 /* workaround for AVHWAccel plane count of 0, buf[0] is used as
885 check for allocated buffers: make libavcodec happy */
886 if (desc && desc->flags & AV_PIX_FMT_FLAG_HWACCEL)
888 if (!desc || planes <= 0) {
889 ret = AVERROR(EINVAL);
893 for (i = 0; i < planes; i++) {
894 int v_shift = (i == 1 || i == 2) ? desc->log2_chroma_h : 0;
895 int plane_size = (frame->height >> v_shift) * frame->linesize[i];
897 WRAP_PLANE(frame->buf[i], frame->data[i], plane_size);
900 int planar = av_sample_fmt_is_planar(frame->format);
901 planes = planar ? avctx->channels : 1;
903 if (planes > FF_ARRAY_ELEMS(frame->buf)) {
904 frame->nb_extended_buf = planes - FF_ARRAY_ELEMS(frame->buf);
905 frame->extended_buf = av_malloc(sizeof(*frame->extended_buf) *
906 frame->nb_extended_buf);
907 if (!frame->extended_buf) {
908 ret = AVERROR(ENOMEM);
913 for (i = 0; i < FFMIN(planes, FF_ARRAY_ELEMS(frame->buf)); i++)
914 WRAP_PLANE(frame->buf[i], frame->extended_data[i], frame->linesize[0]);
916 for (i = 0; i < frame->nb_extended_buf; i++)
917 WRAP_PLANE(frame->extended_buf[i],
918 frame->extended_data[i + FF_ARRAY_ELEMS(frame->buf)],
922 av_buffer_unref(&dummy_buf);
925 frame->width = avctx->width;
926 frame->height = avctx->height;
931 avctx->release_buffer(avctx, frame);
933 av_buffer_unref(&dummy_buf);
936 FF_ENABLE_DEPRECATION_WARNINGS
939 ret = avctx->get_buffer2(avctx, frame, flags);
941 if (avctx->codec_type == AVMEDIA_TYPE_VIDEO) {
942 frame->width = avctx->width;
943 frame->height = avctx->height;
949 int ff_get_buffer(AVCodecContext *avctx, AVFrame *frame, int flags)
951 int ret = get_buffer_internal(avctx, frame, flags);
953 av_log(avctx, AV_LOG_ERROR, "get_buffer() failed\n");
957 static int reget_buffer_internal(AVCodecContext *avctx, AVFrame *frame)
962 av_assert0(avctx->codec_type == AVMEDIA_TYPE_VIDEO);
964 if (frame->data[0] && (frame->width != avctx->width || frame->height != avctx->height || frame->format != avctx->pix_fmt)) {
965 av_log(avctx, AV_LOG_WARNING, "Picture changed from size:%dx%d fmt:%s to size:%dx%d fmt:%s in reget buffer()\n",
966 frame->width, frame->height, av_get_pix_fmt_name(frame->format), avctx->width, avctx->height, av_get_pix_fmt_name(avctx->pix_fmt));
967 av_frame_unref(frame);
970 ff_init_buffer_info(avctx, frame);
973 return ff_get_buffer(avctx, frame, AV_GET_BUFFER_FLAG_REF);
975 if (av_frame_is_writable(frame))
978 av_frame_move_ref(&tmp, frame);
980 ret = ff_get_buffer(avctx, frame, AV_GET_BUFFER_FLAG_REF);
982 av_frame_unref(&tmp);
986 av_image_copy(frame->data, frame->linesize, tmp.data, tmp.linesize,
987 frame->format, frame->width, frame->height);
989 av_frame_unref(&tmp);
994 int ff_reget_buffer(AVCodecContext *avctx, AVFrame *frame)
996 int ret = reget_buffer_internal(avctx, frame);
998 av_log(avctx, AV_LOG_ERROR, "reget_buffer() failed\n");
1002 #if FF_API_GET_BUFFER
1003 void avcodec_default_release_buffer(AVCodecContext *s, AVFrame *pic)
1005 av_assert0(s->codec_type == AVMEDIA_TYPE_VIDEO);
1007 av_frame_unref(pic);
1010 int avcodec_default_reget_buffer(AVCodecContext *s, AVFrame *pic)
1017 int avcodec_default_execute(AVCodecContext *c, int (*func)(AVCodecContext *c2, void *arg2), void *arg, int *ret, int count, int size)
1021 for (i = 0; i < count; i++) {
1022 int r = func(c, (char *)arg + i * size);
1029 int avcodec_default_execute2(AVCodecContext *c, int (*func)(AVCodecContext *c2, void *arg2, int jobnr, int threadnr), void *arg, int *ret, int count)
1033 for (i = 0; i < count; i++) {
1034 int r = func(c, arg, i, 0);
1041 static int is_hwaccel_pix_fmt(enum AVPixelFormat pix_fmt)
1043 const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(pix_fmt);
1044 return desc->flags & AV_PIX_FMT_FLAG_HWACCEL;
1047 enum AVPixelFormat avcodec_default_get_format(struct AVCodecContext *s, const enum AVPixelFormat *fmt)
1049 while (*fmt != AV_PIX_FMT_NONE && is_hwaccel_pix_fmt(*fmt))
1054 #if FF_API_AVFRAME_LAVC
1055 void avcodec_get_frame_defaults(AVFrame *frame)
1057 #if LIBAVCODEC_VERSION_MAJOR >= 55
1058 // extended_data should explicitly be freed when needed, this code is unsafe currently
1059 // also this is not compatible to the <55 ABI/API
1060 if (frame->extended_data != frame->data && 0)
1061 av_freep(&frame->extended_data);
1064 memset(frame, 0, sizeof(AVFrame));
1065 av_frame_unref(frame);
1068 AVFrame *avcodec_alloc_frame(void)
1070 return av_frame_alloc();
1073 void avcodec_free_frame(AVFrame **frame)
1075 av_frame_free(frame);
1079 MAKE_ACCESSORS(AVCodecContext, codec, AVRational, pkt_timebase)
1080 MAKE_ACCESSORS(AVCodecContext, codec, const AVCodecDescriptor *, codec_descriptor)
1081 MAKE_ACCESSORS(AVCodecContext, codec, int, lowres)
1082 MAKE_ACCESSORS(AVCodecContext, codec, int, seek_preroll)
1084 int av_codec_get_max_lowres(const AVCodec *codec)
1086 return codec->max_lowres;
1089 static void avcodec_get_subtitle_defaults(AVSubtitle *sub)
1091 memset(sub, 0, sizeof(*sub));
1092 sub->pts = AV_NOPTS_VALUE;
1095 static int get_bit_rate(AVCodecContext *ctx)
1098 int bits_per_sample;
1100 switch (ctx->codec_type) {
1101 case AVMEDIA_TYPE_VIDEO:
1102 case AVMEDIA_TYPE_DATA:
1103 case AVMEDIA_TYPE_SUBTITLE:
1104 case AVMEDIA_TYPE_ATTACHMENT:
1105 bit_rate = ctx->bit_rate;
1107 case AVMEDIA_TYPE_AUDIO:
1108 bits_per_sample = av_get_bits_per_sample(ctx->codec_id);
1109 bit_rate = bits_per_sample ? ctx->sample_rate * ctx->channels * bits_per_sample : ctx->bit_rate;
1118 int attribute_align_arg ff_codec_open2_recursive(AVCodecContext *avctx, const AVCodec *codec, AVDictionary **options)
1122 ff_unlock_avcodec();
1124 ret = avcodec_open2(avctx, codec, options);
1126 ff_lock_avcodec(avctx);
1130 int attribute_align_arg avcodec_open2(AVCodecContext *avctx, const AVCodec *codec, AVDictionary **options)
1133 AVDictionary *tmp = NULL;
1135 if (avcodec_is_open(avctx))
1138 if ((!codec && !avctx->codec)) {
1139 av_log(avctx, AV_LOG_ERROR, "No codec provided to avcodec_open2()\n");
1140 return AVERROR(EINVAL);
1142 if ((codec && avctx->codec && codec != avctx->codec)) {
1143 av_log(avctx, AV_LOG_ERROR, "This AVCodecContext was allocated for %s, "
1144 "but %s passed to avcodec_open2()\n", avctx->codec->name, codec->name);
1145 return AVERROR(EINVAL);
1148 codec = avctx->codec;
1150 if (avctx->extradata_size < 0 || avctx->extradata_size >= FF_MAX_EXTRADATA_SIZE)
1151 return AVERROR(EINVAL);
1154 av_dict_copy(&tmp, *options, 0);
1156 ret = ff_lock_avcodec(avctx);
1160 avctx->internal = av_mallocz(sizeof(AVCodecInternal));
1161 if (!avctx->internal) {
1162 ret = AVERROR(ENOMEM);
1166 avctx->internal->pool = av_mallocz(sizeof(*avctx->internal->pool));
1167 if (!avctx->internal->pool) {
1168 ret = AVERROR(ENOMEM);
1172 avctx->internal->to_free = av_frame_alloc();
1173 if (!avctx->internal->to_free) {
1174 ret = AVERROR(ENOMEM);
1178 if (codec->priv_data_size > 0) {
1179 if (!avctx->priv_data) {
1180 avctx->priv_data = av_mallocz(codec->priv_data_size);
1181 if (!avctx->priv_data) {
1182 ret = AVERROR(ENOMEM);
1185 if (codec->priv_class) {
1186 *(const AVClass **)avctx->priv_data = codec->priv_class;
1187 av_opt_set_defaults(avctx->priv_data);
1190 if (codec->priv_class && (ret = av_opt_set_dict(avctx->priv_data, &tmp)) < 0)
1193 avctx->priv_data = NULL;
1195 if ((ret = av_opt_set_dict(avctx, &tmp)) < 0)
1198 // only call ff_set_dimensions() for non H.264/VP6F codecs so as not to overwrite previously setup dimensions
1199 if (!(avctx->coded_width && avctx->coded_height && avctx->width && avctx->height &&
1200 (avctx->codec_id == AV_CODEC_ID_H264 || avctx->codec_id == AV_CODEC_ID_VP6F))) {
1201 if (avctx->coded_width && avctx->coded_height)
1202 ret = ff_set_dimensions(avctx, avctx->coded_width, avctx->coded_height);
1203 else if (avctx->width && avctx->height)
1204 ret = ff_set_dimensions(avctx, avctx->width, avctx->height);
1209 if ((avctx->coded_width || avctx->coded_height || avctx->width || avctx->height)
1210 && ( av_image_check_size(avctx->coded_width, avctx->coded_height, 0, avctx) < 0
1211 || av_image_check_size(avctx->width, avctx->height, 0, avctx) < 0)) {
1212 av_log(avctx, AV_LOG_WARNING, "Ignoring invalid width/height values\n");
1213 ff_set_dimensions(avctx, 0, 0);
1216 /* if the decoder init function was already called previously,
1217 * free the already allocated subtitle_header before overwriting it */
1218 if (av_codec_is_decoder(codec))
1219 av_freep(&avctx->subtitle_header);
1221 if (avctx->channels > FF_SANE_NB_CHANNELS) {
1222 ret = AVERROR(EINVAL);
1226 avctx->codec = codec;
1227 if ((avctx->codec_type == AVMEDIA_TYPE_UNKNOWN || avctx->codec_type == codec->type) &&
1228 avctx->codec_id == AV_CODEC_ID_NONE) {
1229 avctx->codec_type = codec->type;
1230 avctx->codec_id = codec->id;
1232 if (avctx->codec_id != codec->id || (avctx->codec_type != codec->type
1233 && avctx->codec_type != AVMEDIA_TYPE_ATTACHMENT)) {
1234 av_log(avctx, AV_LOG_ERROR, "Codec type or id mismatches\n");
1235 ret = AVERROR(EINVAL);
1238 avctx->frame_number = 0;
1239 avctx->codec_descriptor = avcodec_descriptor_get(avctx->codec_id);
1241 if (avctx->codec->capabilities & CODEC_CAP_EXPERIMENTAL &&
1242 avctx->strict_std_compliance > FF_COMPLIANCE_EXPERIMENTAL) {
1243 const char *codec_string = av_codec_is_encoder(codec) ? "encoder" : "decoder";
1245 av_log(avctx, AV_LOG_ERROR,
1246 "The %s '%s' is experimental but experimental codecs are not enabled, "
1247 "add '-strict %d' if you want to use it.\n",
1248 codec_string, codec->name, FF_COMPLIANCE_EXPERIMENTAL);
1249 codec2 = av_codec_is_encoder(codec) ? avcodec_find_encoder(codec->id) : avcodec_find_decoder(codec->id);
1250 if (!(codec2->capabilities & CODEC_CAP_EXPERIMENTAL))
1251 av_log(avctx, AV_LOG_ERROR, "Alternatively use the non experimental %s '%s'.\n",
1252 codec_string, codec2->name);
1253 ret = AVERROR_EXPERIMENTAL;
1257 if (avctx->codec_type == AVMEDIA_TYPE_AUDIO &&
1258 (!avctx->time_base.num || !avctx->time_base.den)) {
1259 avctx->time_base.num = 1;
1260 avctx->time_base.den = avctx->sample_rate;
1264 av_log(avctx, AV_LOG_WARNING, "Warning: not compiled with thread support, using thread emulation\n");
1266 if (CONFIG_FRAME_THREAD_ENCODER) {
1267 ff_unlock_avcodec(); //we will instanciate a few encoders thus kick the counter to prevent false detection of a problem
1268 ret = ff_frame_thread_encoder_init(avctx, options ? *options : NULL);
1269 ff_lock_avcodec(avctx);
1275 && !(avctx->internal->frame_thread_encoder && (avctx->active_thread_type&FF_THREAD_FRAME))) {
1276 ret = ff_thread_init(avctx);
1281 if (!HAVE_THREADS && !(codec->capabilities & CODEC_CAP_AUTO_THREADS))
1282 avctx->thread_count = 1;
1284 if (avctx->codec->max_lowres < avctx->lowres || avctx->lowres < 0) {
1285 av_log(avctx, AV_LOG_ERROR, "The maximum value for lowres supported by the decoder is %d\n",
1286 avctx->codec->max_lowres);
1287 ret = AVERROR(EINVAL);
1291 if (av_codec_is_encoder(avctx->codec)) {
1293 if (avctx->codec->sample_fmts) {
1294 for (i = 0; avctx->codec->sample_fmts[i] != AV_SAMPLE_FMT_NONE; i++) {
1295 if (avctx->sample_fmt == avctx->codec->sample_fmts[i])
1297 if (avctx->channels == 1 &&
1298 av_get_planar_sample_fmt(avctx->sample_fmt) ==
1299 av_get_planar_sample_fmt(avctx->codec->sample_fmts[i])) {
1300 avctx->sample_fmt = avctx->codec->sample_fmts[i];
1304 if (avctx->codec->sample_fmts[i] == AV_SAMPLE_FMT_NONE) {
1306 snprintf(buf, sizeof(buf), "%d", avctx->sample_fmt);
1307 av_log(avctx, AV_LOG_ERROR, "Specified sample format %s is invalid or not supported\n",
1308 (char *)av_x_if_null(av_get_sample_fmt_name(avctx->sample_fmt), buf));
1309 ret = AVERROR(EINVAL);
1313 if (avctx->codec->pix_fmts) {
1314 for (i = 0; avctx->codec->pix_fmts[i] != AV_PIX_FMT_NONE; i++)
1315 if (avctx->pix_fmt == avctx->codec->pix_fmts[i])
1317 if (avctx->codec->pix_fmts[i] == AV_PIX_FMT_NONE
1318 && !((avctx->codec_id == AV_CODEC_ID_MJPEG || avctx->codec_id == AV_CODEC_ID_LJPEG)
1319 && avctx->strict_std_compliance <= FF_COMPLIANCE_UNOFFICIAL)) {
1321 snprintf(buf, sizeof(buf), "%d", avctx->pix_fmt);
1322 av_log(avctx, AV_LOG_ERROR, "Specified pixel format %s is invalid or not supported\n",
1323 (char *)av_x_if_null(av_get_pix_fmt_name(avctx->pix_fmt), buf));
1324 ret = AVERROR(EINVAL);
1328 if (avctx->codec->supported_samplerates) {
1329 for (i = 0; avctx->codec->supported_samplerates[i] != 0; i++)
1330 if (avctx->sample_rate == avctx->codec->supported_samplerates[i])
1332 if (avctx->codec->supported_samplerates[i] == 0) {
1333 av_log(avctx, AV_LOG_ERROR, "Specified sample rate %d is not supported\n",
1334 avctx->sample_rate);
1335 ret = AVERROR(EINVAL);
1339 if (avctx->codec->channel_layouts) {
1340 if (!avctx->channel_layout) {
1341 av_log(avctx, AV_LOG_WARNING, "Channel layout not specified\n");
1343 for (i = 0; avctx->codec->channel_layouts[i] != 0; i++)
1344 if (avctx->channel_layout == avctx->codec->channel_layouts[i])
1346 if (avctx->codec->channel_layouts[i] == 0) {
1348 av_get_channel_layout_string(buf, sizeof(buf), -1, avctx->channel_layout);
1349 av_log(avctx, AV_LOG_ERROR, "Specified channel layout '%s' is not supported\n", buf);
1350 ret = AVERROR(EINVAL);
1355 if (avctx->channel_layout && avctx->channels) {
1356 int channels = av_get_channel_layout_nb_channels(avctx->channel_layout);
1357 if (channels != avctx->channels) {
1359 av_get_channel_layout_string(buf, sizeof(buf), -1, avctx->channel_layout);
1360 av_log(avctx, AV_LOG_ERROR,
1361 "Channel layout '%s' with %d channels does not match number of specified channels %d\n",
1362 buf, channels, avctx->channels);
1363 ret = AVERROR(EINVAL);
1366 } else if (avctx->channel_layout) {
1367 avctx->channels = av_get_channel_layout_nb_channels(avctx->channel_layout);
1369 if(avctx->codec_type == AVMEDIA_TYPE_VIDEO &&
1370 avctx->codec_id != AV_CODEC_ID_PNG // For mplayer
1372 if (avctx->width <= 0 || avctx->height <= 0) {
1373 av_log(avctx, AV_LOG_ERROR, "dimensions not set\n");
1374 ret = AVERROR(EINVAL);
1378 if ( (avctx->codec_type == AVMEDIA_TYPE_VIDEO || avctx->codec_type == AVMEDIA_TYPE_AUDIO)
1379 && avctx->bit_rate>0 && avctx->bit_rate<1000) {
1380 av_log(avctx, AV_LOG_WARNING, "Bitrate %d is extremely low, maybe you mean %dk\n", avctx->bit_rate, avctx->bit_rate);
1383 if (!avctx->rc_initial_buffer_occupancy)
1384 avctx->rc_initial_buffer_occupancy = avctx->rc_buffer_size * 3 / 4;
1387 avctx->pts_correction_num_faulty_pts =
1388 avctx->pts_correction_num_faulty_dts = 0;
1389 avctx->pts_correction_last_pts =
1390 avctx->pts_correction_last_dts = INT64_MIN;
1392 if ( avctx->codec->init && (!(avctx->active_thread_type&FF_THREAD_FRAME)
1393 || avctx->internal->frame_thread_encoder)) {
1394 ret = avctx->codec->init(avctx);
1402 if (av_codec_is_decoder(avctx->codec)) {
1403 if (!avctx->bit_rate)
1404 avctx->bit_rate = get_bit_rate(avctx);
1405 /* validate channel layout from the decoder */
1406 if (avctx->channel_layout) {
1407 int channels = av_get_channel_layout_nb_channels(avctx->channel_layout);
1408 if (!avctx->channels)
1409 avctx->channels = channels;
1410 else if (channels != avctx->channels) {
1412 av_get_channel_layout_string(buf, sizeof(buf), -1, avctx->channel_layout);
1413 av_log(avctx, AV_LOG_WARNING,
1414 "Channel layout '%s' with %d channels does not match specified number of channels %d: "
1415 "ignoring specified channel layout\n",
1416 buf, channels, avctx->channels);
1417 avctx->channel_layout = 0;
1420 if (avctx->channels && avctx->channels < 0 ||
1421 avctx->channels > FF_SANE_NB_CHANNELS) {
1422 ret = AVERROR(EINVAL);
1425 if (avctx->sub_charenc) {
1426 if (avctx->codec_type != AVMEDIA_TYPE_SUBTITLE) {
1427 av_log(avctx, AV_LOG_ERROR, "Character encoding is only "
1428 "supported with subtitles codecs\n");
1429 ret = AVERROR(EINVAL);
1431 } else if (avctx->codec_descriptor->props & AV_CODEC_PROP_BITMAP_SUB) {
1432 av_log(avctx, AV_LOG_WARNING, "Codec '%s' is bitmap-based, "
1433 "subtitles character encoding will be ignored\n",
1434 avctx->codec_descriptor->name);
1435 avctx->sub_charenc_mode = FF_SUB_CHARENC_MODE_DO_NOTHING;
1437 /* input character encoding is set for a text based subtitle
1438 * codec at this point */
1439 if (avctx->sub_charenc_mode == FF_SUB_CHARENC_MODE_AUTOMATIC)
1440 avctx->sub_charenc_mode = FF_SUB_CHARENC_MODE_PRE_DECODER;
1442 if (avctx->sub_charenc_mode == FF_SUB_CHARENC_MODE_PRE_DECODER) {
1444 iconv_t cd = iconv_open("UTF-8", avctx->sub_charenc);
1445 if (cd == (iconv_t)-1) {
1446 av_log(avctx, AV_LOG_ERROR, "Unable to open iconv context "
1447 "with input character encoding \"%s\"\n", avctx->sub_charenc);
1448 ret = AVERROR(errno);
1453 av_log(avctx, AV_LOG_ERROR, "Character encoding subtitles "
1454 "conversion needs a libavcodec built with iconv support "
1455 "for this codec\n");
1456 ret = AVERROR(ENOSYS);
1464 ff_unlock_avcodec();
1466 av_dict_free(options);
1473 av_freep(&avctx->priv_data);
1474 if (avctx->internal)
1475 av_freep(&avctx->internal->pool);
1476 av_freep(&avctx->internal);
1477 avctx->codec = NULL;
1481 int ff_alloc_packet2(AVCodecContext *avctx, AVPacket *avpkt, int64_t size)
1483 if (avpkt->size < 0) {
1484 av_log(avctx, AV_LOG_ERROR, "Invalid negative user packet size %d\n", avpkt->size);
1485 return AVERROR(EINVAL);
1487 if (size < 0 || size > INT_MAX - FF_INPUT_BUFFER_PADDING_SIZE) {
1488 av_log(avctx, AV_LOG_ERROR, "Invalid minimum required packet size %"PRId64" (max allowed is %d)\n",
1489 size, INT_MAX - FF_INPUT_BUFFER_PADDING_SIZE);
1490 return AVERROR(EINVAL);
1494 av_assert0(!avpkt->data || avpkt->data != avctx->internal->byte_buffer);
1495 if (!avpkt->data || avpkt->size < size) {
1496 av_fast_padded_malloc(&avctx->internal->byte_buffer, &avctx->internal->byte_buffer_size, size);
1497 avpkt->data = avctx->internal->byte_buffer;
1498 avpkt->size = avctx->internal->byte_buffer_size;
1499 avpkt->destruct = NULL;
1504 AVBufferRef *buf = avpkt->buf;
1505 #if FF_API_DESTRUCT_PACKET
1506 FF_DISABLE_DEPRECATION_WARNINGS
1507 void *destruct = avpkt->destruct;
1508 FF_ENABLE_DEPRECATION_WARNINGS
1511 if (avpkt->size < size) {
1512 av_log(avctx, AV_LOG_ERROR, "User packet is too small (%d < %"PRId64")\n", avpkt->size, size);
1513 return AVERROR(EINVAL);
1516 av_init_packet(avpkt);
1517 #if FF_API_DESTRUCT_PACKET
1518 FF_DISABLE_DEPRECATION_WARNINGS
1519 avpkt->destruct = destruct;
1520 FF_ENABLE_DEPRECATION_WARNINGS
1526 int ret = av_new_packet(avpkt, size);
1528 av_log(avctx, AV_LOG_ERROR, "Failed to allocate packet of size %"PRId64"\n", size);
1533 int ff_alloc_packet(AVPacket *avpkt, int size)
1535 return ff_alloc_packet2(NULL, avpkt, size);
1539 * Pad last frame with silence.
1541 static int pad_last_frame(AVCodecContext *s, AVFrame **dst, const AVFrame *src)
1543 AVFrame *frame = NULL;
1546 if (!(frame = av_frame_alloc()))
1547 return AVERROR(ENOMEM);
1549 frame->format = src->format;
1550 frame->channel_layout = src->channel_layout;
1551 av_frame_set_channels(frame, av_frame_get_channels(src));
1552 frame->nb_samples = s->frame_size;
1553 ret = av_frame_get_buffer(frame, 32);
1557 ret = av_frame_copy_props(frame, src);
1561 if ((ret = av_samples_copy(frame->extended_data, src->extended_data, 0, 0,
1562 src->nb_samples, s->channels, s->sample_fmt)) < 0)
1564 if ((ret = av_samples_set_silence(frame->extended_data, src->nb_samples,
1565 frame->nb_samples - src->nb_samples,
1566 s->channels, s->sample_fmt)) < 0)
1574 av_frame_free(&frame);
1578 int attribute_align_arg avcodec_encode_audio2(AVCodecContext *avctx,
1580 const AVFrame *frame,
1581 int *got_packet_ptr)
1584 AVFrame *padded_frame = NULL;
1586 AVPacket user_pkt = *avpkt;
1587 int needs_realloc = !user_pkt.data;
1589 *got_packet_ptr = 0;
1591 if (!(avctx->codec->capabilities & CODEC_CAP_DELAY) && !frame) {
1592 av_free_packet(avpkt);
1593 av_init_packet(avpkt);
1597 /* ensure that extended_data is properly set */
1598 if (frame && !frame->extended_data) {
1599 if (av_sample_fmt_is_planar(avctx->sample_fmt) &&
1600 avctx->channels > AV_NUM_DATA_POINTERS) {
1601 av_log(avctx, AV_LOG_ERROR, "Encoding to a planar sample format, "
1602 "with more than %d channels, but extended_data is not set.\n",
1603 AV_NUM_DATA_POINTERS);
1604 return AVERROR(EINVAL);
1606 av_log(avctx, AV_LOG_WARNING, "extended_data is not set.\n");
1609 tmp.extended_data = tmp.data;
1613 /* check for valid frame size */
1615 if (avctx->codec->capabilities & CODEC_CAP_SMALL_LAST_FRAME) {
1616 if (frame->nb_samples > avctx->frame_size) {
1617 av_log(avctx, AV_LOG_ERROR, "more samples than frame size (avcodec_encode_audio2)\n");
1618 return AVERROR(EINVAL);
1620 } else if (!(avctx->codec->capabilities & CODEC_CAP_VARIABLE_FRAME_SIZE)) {
1621 if (frame->nb_samples < avctx->frame_size &&
1622 !avctx->internal->last_audio_frame) {
1623 ret = pad_last_frame(avctx, &padded_frame, frame);
1627 frame = padded_frame;
1628 avctx->internal->last_audio_frame = 1;
1631 if (frame->nb_samples != avctx->frame_size) {
1632 av_log(avctx, AV_LOG_ERROR, "nb_samples (%d) != frame_size (%d) (avcodec_encode_audio2)\n", frame->nb_samples, avctx->frame_size);
1633 ret = AVERROR(EINVAL);
1639 ret = avctx->codec->encode2(avctx, avpkt, frame, got_packet_ptr);
1641 if (*got_packet_ptr) {
1642 if (!(avctx->codec->capabilities & CODEC_CAP_DELAY)) {
1643 if (avpkt->pts == AV_NOPTS_VALUE)
1644 avpkt->pts = frame->pts;
1645 if (!avpkt->duration)
1646 avpkt->duration = ff_samples_to_time_base(avctx,
1649 avpkt->dts = avpkt->pts;
1654 if (avpkt->data && avpkt->data == avctx->internal->byte_buffer) {
1656 if (user_pkt.data) {
1657 if (user_pkt.size >= avpkt->size) {
1658 memcpy(user_pkt.data, avpkt->data, avpkt->size);
1660 av_log(avctx, AV_LOG_ERROR, "Provided packet is too small, needs to be %d\n", avpkt->size);
1661 avpkt->size = user_pkt.size;
1664 avpkt->buf = user_pkt.buf;
1665 avpkt->data = user_pkt.data;
1666 avpkt->destruct = user_pkt.destruct;
1668 if (av_dup_packet(avpkt) < 0) {
1669 ret = AVERROR(ENOMEM);
1675 if (needs_realloc && avpkt->data) {
1676 ret = av_buffer_realloc(&avpkt->buf, avpkt->size + FF_INPUT_BUFFER_PADDING_SIZE);
1678 avpkt->data = avpkt->buf->data;
1681 avctx->frame_number++;
1684 if (ret < 0 || !*got_packet_ptr) {
1685 av_free_packet(avpkt);
1686 av_init_packet(avpkt);
1690 /* NOTE: if we add any audio encoders which output non-keyframe packets,
1691 * this needs to be moved to the encoders, but for now we can do it
1692 * here to simplify things */
1693 avpkt->flags |= AV_PKT_FLAG_KEY;
1696 av_frame_free(&padded_frame);
1701 #if FF_API_OLD_ENCODE_AUDIO
1702 int attribute_align_arg avcodec_encode_audio(AVCodecContext *avctx,
1703 uint8_t *buf, int buf_size,
1704 const short *samples)
1708 int ret, samples_size, got_packet;
1710 av_init_packet(&pkt);
1712 pkt.size = buf_size;
1715 frame = av_frame_alloc();
1717 if (avctx->frame_size) {
1718 frame->nb_samples = avctx->frame_size;
1720 /* if frame_size is not set, the number of samples must be
1721 * calculated from the buffer size */
1723 if (!av_get_bits_per_sample(avctx->codec_id)) {
1724 av_log(avctx, AV_LOG_ERROR, "avcodec_encode_audio() does not "
1725 "support this codec\n");
1726 av_frame_free(&frame);
1727 return AVERROR(EINVAL);
1729 nb_samples = (int64_t)buf_size * 8 /
1730 (av_get_bits_per_sample(avctx->codec_id) *
1732 if (nb_samples >= INT_MAX) {
1733 av_frame_free(&frame);
1734 return AVERROR(EINVAL);
1736 frame->nb_samples = nb_samples;
1739 /* it is assumed that the samples buffer is large enough based on the
1740 * relevant parameters */
1741 samples_size = av_samples_get_buffer_size(NULL, avctx->channels,
1743 avctx->sample_fmt, 1);
1744 if ((ret = avcodec_fill_audio_frame(frame, avctx->channels,
1746 (const uint8_t *)samples,
1747 samples_size, 1)) < 0) {
1748 av_frame_free(&frame);
1752 /* fabricate frame pts from sample count.
1753 * this is needed because the avcodec_encode_audio() API does not have
1754 * a way for the user to provide pts */
1755 if (avctx->sample_rate && avctx->time_base.num)
1756 frame->pts = ff_samples_to_time_base(avctx,
1757 avctx->internal->sample_count);
1759 frame->pts = AV_NOPTS_VALUE;
1760 avctx->internal->sample_count += frame->nb_samples;
1766 ret = avcodec_encode_audio2(avctx, &pkt, frame, &got_packet);
1767 if (!ret && got_packet && avctx->coded_frame) {
1768 avctx->coded_frame->pts = pkt.pts;
1769 avctx->coded_frame->key_frame = !!(pkt.flags & AV_PKT_FLAG_KEY);
1771 /* free any side data since we cannot return it */
1772 av_packet_free_side_data(&pkt);
1774 if (frame && frame->extended_data != frame->data)
1775 av_freep(&frame->extended_data);
1777 av_frame_free(&frame);
1778 return ret ? ret : pkt.size;
1783 #if FF_API_OLD_ENCODE_VIDEO
1784 int attribute_align_arg avcodec_encode_video(AVCodecContext *avctx, uint8_t *buf, int buf_size,
1785 const AVFrame *pict)
1788 int ret, got_packet = 0;
1790 if (buf_size < FF_MIN_BUFFER_SIZE) {
1791 av_log(avctx, AV_LOG_ERROR, "buffer smaller than minimum size\n");
1795 av_init_packet(&pkt);
1797 pkt.size = buf_size;
1799 ret = avcodec_encode_video2(avctx, &pkt, pict, &got_packet);
1800 if (!ret && got_packet && avctx->coded_frame) {
1801 avctx->coded_frame->pts = pkt.pts;
1802 avctx->coded_frame->key_frame = !!(pkt.flags & AV_PKT_FLAG_KEY);
1805 /* free any side data since we cannot return it */
1806 if (pkt.side_data_elems > 0) {
1808 for (i = 0; i < pkt.side_data_elems; i++)
1809 av_free(pkt.side_data[i].data);
1810 av_freep(&pkt.side_data);
1811 pkt.side_data_elems = 0;
1814 return ret ? ret : pkt.size;
1819 int attribute_align_arg avcodec_encode_video2(AVCodecContext *avctx,
1821 const AVFrame *frame,
1822 int *got_packet_ptr)
1825 AVPacket user_pkt = *avpkt;
1826 int needs_realloc = !user_pkt.data;
1828 *got_packet_ptr = 0;
1830 if(CONFIG_FRAME_THREAD_ENCODER &&
1831 avctx->internal->frame_thread_encoder && (avctx->active_thread_type&FF_THREAD_FRAME))
1832 return ff_thread_video_encode_frame(avctx, avpkt, frame, got_packet_ptr);
1834 if ((avctx->flags&CODEC_FLAG_PASS1) && avctx->stats_out)
1835 avctx->stats_out[0] = '\0';
1837 if (!(avctx->codec->capabilities & CODEC_CAP_DELAY) && !frame) {
1838 av_free_packet(avpkt);
1839 av_init_packet(avpkt);
1844 if (av_image_check_size(avctx->width, avctx->height, 0, avctx))
1845 return AVERROR(EINVAL);
1847 av_assert0(avctx->codec->encode2);
1849 ret = avctx->codec->encode2(avctx, avpkt, frame, got_packet_ptr);
1850 av_assert0(ret <= 0);
1852 if (avpkt->data && avpkt->data == avctx->internal->byte_buffer) {
1854 if (user_pkt.data) {
1855 if (user_pkt.size >= avpkt->size) {
1856 memcpy(user_pkt.data, avpkt->data, avpkt->size);
1858 av_log(avctx, AV_LOG_ERROR, "Provided packet is too small, needs to be %d\n", avpkt->size);
1859 avpkt->size = user_pkt.size;
1862 avpkt->buf = user_pkt.buf;
1863 avpkt->data = user_pkt.data;
1864 avpkt->destruct = user_pkt.destruct;
1866 if (av_dup_packet(avpkt) < 0) {
1867 ret = AVERROR(ENOMEM);
1873 if (!*got_packet_ptr)
1875 else if (!(avctx->codec->capabilities & CODEC_CAP_DELAY))
1876 avpkt->pts = avpkt->dts = frame->pts;
1878 if (needs_realloc && avpkt->data) {
1879 ret = av_buffer_realloc(&avpkt->buf, avpkt->size + FF_INPUT_BUFFER_PADDING_SIZE);
1881 avpkt->data = avpkt->buf->data;
1884 avctx->frame_number++;
1887 if (ret < 0 || !*got_packet_ptr)
1888 av_free_packet(avpkt);
1890 av_packet_merge_side_data(avpkt);
1896 int avcodec_encode_subtitle(AVCodecContext *avctx, uint8_t *buf, int buf_size,
1897 const AVSubtitle *sub)
1900 if (sub->start_display_time) {
1901 av_log(avctx, AV_LOG_ERROR, "start_display_time must be 0.\n");
1905 ret = avctx->codec->encode_sub(avctx, buf, buf_size, sub);
1906 avctx->frame_number++;
1911 * Attempt to guess proper monotonic timestamps for decoded video frames
1912 * which might have incorrect times. Input timestamps may wrap around, in
1913 * which case the output will as well.
1915 * @param pts the pts field of the decoded AVPacket, as passed through
1917 * @param dts the dts field of the decoded AVPacket
1918 * @return one of the input values, may be AV_NOPTS_VALUE
1920 static int64_t guess_correct_pts(AVCodecContext *ctx,
1921 int64_t reordered_pts, int64_t dts)
1923 int64_t pts = AV_NOPTS_VALUE;
1925 if (dts != AV_NOPTS_VALUE) {
1926 ctx->pts_correction_num_faulty_dts += dts <= ctx->pts_correction_last_dts;
1927 ctx->pts_correction_last_dts = dts;
1929 if (reordered_pts != AV_NOPTS_VALUE) {
1930 ctx->pts_correction_num_faulty_pts += reordered_pts <= ctx->pts_correction_last_pts;
1931 ctx->pts_correction_last_pts = reordered_pts;
1933 if ((ctx->pts_correction_num_faulty_pts<=ctx->pts_correction_num_faulty_dts || dts == AV_NOPTS_VALUE)
1934 && reordered_pts != AV_NOPTS_VALUE)
1935 pts = reordered_pts;
1942 static int apply_param_change(AVCodecContext *avctx, AVPacket *avpkt)
1945 const uint8_t *data;
1948 data = av_packet_get_side_data(avpkt, AV_PKT_DATA_PARAM_CHANGE, &size);
1952 if (!(avctx->codec->capabilities & CODEC_CAP_PARAM_CHANGE)) {
1953 av_log(avctx, AV_LOG_ERROR, "This decoder does not support parameter "
1954 "changes, but PARAM_CHANGE side data was sent to it.\n");
1955 return AVERROR(EINVAL);
1961 flags = bytestream_get_le32(&data);
1964 if (flags & AV_SIDE_DATA_PARAM_CHANGE_CHANNEL_COUNT) {
1967 avctx->channels = bytestream_get_le32(&data);
1970 if (flags & AV_SIDE_DATA_PARAM_CHANGE_CHANNEL_LAYOUT) {
1973 avctx->channel_layout = bytestream_get_le64(&data);
1976 if (flags & AV_SIDE_DATA_PARAM_CHANGE_SAMPLE_RATE) {
1979 avctx->sample_rate = bytestream_get_le32(&data);
1982 if (flags & AV_SIDE_DATA_PARAM_CHANGE_DIMENSIONS) {
1985 avctx->width = bytestream_get_le32(&data);
1986 avctx->height = bytestream_get_le32(&data);
1988 ret = ff_set_dimensions(avctx, avctx->width, avctx->height);
1995 av_log(avctx, AV_LOG_ERROR, "PARAM_CHANGE side data too small.\n");
1996 return AVERROR_INVALIDDATA;
1999 static int add_metadata_from_side_data(AVCodecContext *avctx, AVFrame *frame)
2002 const uint8_t *side_metadata;
2004 AVDictionary **frame_md = avpriv_frame_get_metadatap(frame);
2006 side_metadata = av_packet_get_side_data(avctx->internal->pkt,
2007 AV_PKT_DATA_STRINGS_METADATA, &size);
2008 return av_packet_unpack_dictionary(side_metadata, size, frame_md);
2011 static int unrefcount_frame(AVCodecInternal *avci, AVFrame *frame)
2015 /* move the original frame to our backup */
2016 av_frame_unref(avci->to_free);
2017 av_frame_move_ref(avci->to_free, frame);
2019 /* now copy everything except the AVBufferRefs back
2020 * note that we make a COPY of the side data, so calling av_frame_free() on
2021 * the caller's frame will work properly */
2022 ret = av_frame_copy_props(frame, avci->to_free);
2026 memcpy(frame->data, avci->to_free->data, sizeof(frame->data));
2027 memcpy(frame->linesize, avci->to_free->linesize, sizeof(frame->linesize));
2028 if (avci->to_free->extended_data != avci->to_free->data) {
2029 int planes = av_frame_get_channels(avci->to_free);
2030 int size = planes * sizeof(*frame->extended_data);
2033 av_frame_unref(frame);
2037 frame->extended_data = av_malloc(size);
2038 if (!frame->extended_data) {
2039 av_frame_unref(frame);
2040 return AVERROR(ENOMEM);
2042 memcpy(frame->extended_data, avci->to_free->extended_data,
2045 frame->extended_data = frame->data;
2047 frame->format = avci->to_free->format;
2048 frame->width = avci->to_free->width;
2049 frame->height = avci->to_free->height;
2050 frame->channel_layout = avci->to_free->channel_layout;
2051 frame->nb_samples = avci->to_free->nb_samples;
2052 av_frame_set_channels(frame, av_frame_get_channels(avci->to_free));
2057 int attribute_align_arg avcodec_decode_video2(AVCodecContext *avctx, AVFrame *picture,
2058 int *got_picture_ptr,
2059 const AVPacket *avpkt)
2061 AVCodecInternal *avci = avctx->internal;
2063 // copy to ensure we do not change avpkt
2064 AVPacket tmp = *avpkt;
2067 return AVERROR(EINVAL);
2068 if (avctx->codec->type != AVMEDIA_TYPE_VIDEO) {
2069 av_log(avctx, AV_LOG_ERROR, "Invalid media type for video\n");
2070 return AVERROR(EINVAL);
2073 *got_picture_ptr = 0;
2074 if ((avctx->coded_width || avctx->coded_height) && av_image_check_size(avctx->coded_width, avctx->coded_height, 0, avctx))
2075 return AVERROR(EINVAL);
2077 av_frame_unref(picture);
2079 if ((avctx->codec->capabilities & CODEC_CAP_DELAY) || avpkt->size || (avctx->active_thread_type & FF_THREAD_FRAME)) {
2080 int did_split = av_packet_split_side_data(&tmp);
2081 ret = apply_param_change(avctx, &tmp);
2083 av_log(avctx, AV_LOG_ERROR, "Error applying parameter changes.\n");
2084 if (avctx->err_recognition & AV_EF_EXPLODE)
2088 avctx->internal->pkt = &tmp;
2089 if (HAVE_THREADS && avctx->active_thread_type & FF_THREAD_FRAME)
2090 ret = ff_thread_decode_frame(avctx, picture, got_picture_ptr,
2093 ret = avctx->codec->decode(avctx, picture, got_picture_ptr,
2095 picture->pkt_dts = avpkt->dts;
2097 if(!avctx->has_b_frames){
2098 av_frame_set_pkt_pos(picture, avpkt->pos);
2100 //FIXME these should be under if(!avctx->has_b_frames)
2101 /* get_buffer is supposed to set frame parameters */
2102 if (!(avctx->codec->capabilities & CODEC_CAP_DR1)) {
2103 if (!picture->sample_aspect_ratio.num) picture->sample_aspect_ratio = avctx->sample_aspect_ratio;
2104 if (!picture->width) picture->width = avctx->width;
2105 if (!picture->height) picture->height = avctx->height;
2106 if (picture->format == AV_PIX_FMT_NONE) picture->format = avctx->pix_fmt;
2109 add_metadata_from_side_data(avctx, picture);
2112 emms_c(); //needed to avoid an emms_c() call before every return;
2114 avctx->internal->pkt = NULL;
2116 av_packet_free_side_data(&tmp);
2121 if (*got_picture_ptr) {
2122 if (!avctx->refcounted_frames) {
2123 int err = unrefcount_frame(avci, picture);
2128 avctx->frame_number++;
2129 av_frame_set_best_effort_timestamp(picture,
2130 guess_correct_pts(avctx,
2134 av_frame_unref(picture);
2138 /* many decoders assign whole AVFrames, thus overwriting extended_data;
2139 * make sure it's set correctly */
2140 av_assert0(!picture->extended_data || picture->extended_data == picture->data);
2145 #if FF_API_OLD_DECODE_AUDIO
2146 int attribute_align_arg avcodec_decode_audio3(AVCodecContext *avctx, int16_t *samples,
2147 int *frame_size_ptr,
2150 AVFrame *frame = av_frame_alloc();
2151 int ret, got_frame = 0;
2153 if (avctx->get_buffer != avcodec_default_get_buffer) {
2154 av_log(avctx, AV_LOG_ERROR, "Custom get_buffer() for use with"
2155 "avcodec_decode_audio3() detected. Overriding with avcodec_default_get_buffer\n");
2156 av_log(avctx, AV_LOG_ERROR, "Please port your application to "
2157 "avcodec_decode_audio4()\n");
2158 avctx->get_buffer = avcodec_default_get_buffer;
2159 avctx->release_buffer = avcodec_default_release_buffer;
2162 ret = avcodec_decode_audio4(avctx, frame, &got_frame, avpkt);
2164 if (ret >= 0 && got_frame) {
2166 int planar = av_sample_fmt_is_planar(avctx->sample_fmt);
2167 int data_size = av_samples_get_buffer_size(&plane_size, avctx->channels,
2169 avctx->sample_fmt, 1);
2170 if (*frame_size_ptr < data_size) {
2171 av_log(avctx, AV_LOG_ERROR, "output buffer size is too small for "
2172 "the current frame (%d < %d)\n", *frame_size_ptr, data_size);
2173 av_frame_free(&frame);
2174 return AVERROR(EINVAL);
2177 memcpy(samples, frame->extended_data[0], plane_size);
2179 if (planar && avctx->channels > 1) {
2180 uint8_t *out = ((uint8_t *)samples) + plane_size;
2181 for (ch = 1; ch < avctx->channels; ch++) {
2182 memcpy(out, frame->extended_data[ch], plane_size);
2186 *frame_size_ptr = data_size;
2188 *frame_size_ptr = 0;
2190 av_frame_free(&frame);
2196 int attribute_align_arg avcodec_decode_audio4(AVCodecContext *avctx,
2199 const AVPacket *avpkt)
2201 AVCodecInternal *avci = avctx->internal;
2206 if (!avpkt->data && avpkt->size) {
2207 av_log(avctx, AV_LOG_ERROR, "invalid packet: NULL data, size != 0\n");
2208 return AVERROR(EINVAL);
2211 return AVERROR(EINVAL);
2212 if (avctx->codec->type != AVMEDIA_TYPE_AUDIO) {
2213 av_log(avctx, AV_LOG_ERROR, "Invalid media type for audio\n");
2214 return AVERROR(EINVAL);
2217 av_frame_unref(frame);
2219 if ((avctx->codec->capabilities & CODEC_CAP_DELAY) || avpkt->size || (avctx->active_thread_type & FF_THREAD_FRAME)) {
2222 uint32_t discard_padding = 0;
2223 // copy to ensure we do not change avpkt
2224 AVPacket tmp = *avpkt;
2225 int did_split = av_packet_split_side_data(&tmp);
2226 ret = apply_param_change(avctx, &tmp);
2228 av_log(avctx, AV_LOG_ERROR, "Error applying parameter changes.\n");
2229 if (avctx->err_recognition & AV_EF_EXPLODE)
2233 avctx->internal->pkt = &tmp;
2234 if (HAVE_THREADS && avctx->active_thread_type & FF_THREAD_FRAME)
2235 ret = ff_thread_decode_frame(avctx, frame, got_frame_ptr, &tmp);
2237 ret = avctx->codec->decode(avctx, frame, got_frame_ptr, &tmp);
2238 frame->pkt_dts = avpkt->dts;
2240 if (ret >= 0 && *got_frame_ptr) {
2241 add_metadata_from_side_data(avctx, frame);
2242 avctx->frame_number++;
2243 av_frame_set_best_effort_timestamp(frame,
2244 guess_correct_pts(avctx,
2247 if (frame->format == AV_SAMPLE_FMT_NONE)
2248 frame->format = avctx->sample_fmt;
2249 if (!frame->channel_layout)
2250 frame->channel_layout = avctx->channel_layout;
2251 if (!av_frame_get_channels(frame))
2252 av_frame_set_channels(frame, avctx->channels);
2253 if (!frame->sample_rate)
2254 frame->sample_rate = avctx->sample_rate;
2257 side= av_packet_get_side_data(avctx->internal->pkt, AV_PKT_DATA_SKIP_SAMPLES, &side_size);
2258 if(side && side_size>=10) {
2259 avctx->internal->skip_samples = AV_RL32(side);
2260 av_log(avctx, AV_LOG_DEBUG, "skip %d samples due to side data\n",
2261 avctx->internal->skip_samples);
2262 discard_padding = AV_RL32(side + 4);
2264 if (avctx->internal->skip_samples && *got_frame_ptr) {
2265 if(frame->nb_samples <= avctx->internal->skip_samples){
2267 avctx->internal->skip_samples -= frame->nb_samples;
2268 av_log(avctx, AV_LOG_DEBUG, "skip whole frame, skip left: %d\n",
2269 avctx->internal->skip_samples);
2271 av_samples_copy(frame->extended_data, frame->extended_data, 0, avctx->internal->skip_samples,
2272 frame->nb_samples - avctx->internal->skip_samples, avctx->channels, frame->format);
2273 if(avctx->pkt_timebase.num && avctx->sample_rate) {
2274 int64_t diff_ts = av_rescale_q(avctx->internal->skip_samples,
2275 (AVRational){1, avctx->sample_rate},
2276 avctx->pkt_timebase);
2277 if(frame->pkt_pts!=AV_NOPTS_VALUE)
2278 frame->pkt_pts += diff_ts;
2279 if(frame->pkt_dts!=AV_NOPTS_VALUE)
2280 frame->pkt_dts += diff_ts;
2281 if (av_frame_get_pkt_duration(frame) >= diff_ts)
2282 av_frame_set_pkt_duration(frame, av_frame_get_pkt_duration(frame) - diff_ts);
2284 av_log(avctx, AV_LOG_WARNING, "Could not update timestamps for skipped samples.\n");
2286 av_log(avctx, AV_LOG_DEBUG, "skip %d/%d samples\n",
2287 avctx->internal->skip_samples, frame->nb_samples);
2288 frame->nb_samples -= avctx->internal->skip_samples;
2289 avctx->internal->skip_samples = 0;
2293 if (discard_padding > 0 && discard_padding <= frame->nb_samples && *got_frame_ptr) {
2294 if (discard_padding == frame->nb_samples) {
2297 if(avctx->pkt_timebase.num && avctx->sample_rate) {
2298 int64_t diff_ts = av_rescale_q(frame->nb_samples - discard_padding,
2299 (AVRational){1, avctx->sample_rate},
2300 avctx->pkt_timebase);
2301 if (av_frame_get_pkt_duration(frame) >= diff_ts)
2302 av_frame_set_pkt_duration(frame, av_frame_get_pkt_duration(frame) - diff_ts);
2304 av_log(avctx, AV_LOG_WARNING, "Could not update timestamps for discarded samples.\n");
2306 av_log(avctx, AV_LOG_DEBUG, "discard %d/%d samples\n",
2307 discard_padding, frame->nb_samples);
2308 frame->nb_samples -= discard_padding;
2312 avctx->internal->pkt = NULL;
2314 av_packet_free_side_data(&tmp);
2319 if (ret >= 0 && *got_frame_ptr) {
2320 if (!avctx->refcounted_frames) {
2321 int err = unrefcount_frame(avci, frame);
2326 av_frame_unref(frame);
2332 #define UTF8_MAX_BYTES 4 /* 5 and 6 bytes sequences should not be used */
2333 static int recode_subtitle(AVCodecContext *avctx,
2334 AVPacket *outpkt, const AVPacket *inpkt)
2337 iconv_t cd = (iconv_t)-1;
2344 if (avctx->sub_charenc_mode != FF_SUB_CHARENC_MODE_PRE_DECODER || inpkt->size == 0)
2348 cd = iconv_open("UTF-8", avctx->sub_charenc);
2349 av_assert0(cd != (iconv_t)-1);
2354 if (inl >= INT_MAX / UTF8_MAX_BYTES - FF_INPUT_BUFFER_PADDING_SIZE) {
2355 av_log(avctx, AV_LOG_ERROR, "Subtitles packet is too big for recoding\n");
2356 ret = AVERROR(ENOMEM);
2360 ret = av_new_packet(&tmp, inl * UTF8_MAX_BYTES);
2363 outpkt->buf = tmp.buf;
2364 outpkt->data = tmp.data;
2365 outpkt->size = tmp.size;
2366 outb = outpkt->data;
2367 outl = outpkt->size;
2369 if (iconv(cd, &inb, &inl, &outb, &outl) == (size_t)-1 ||
2370 iconv(cd, NULL, NULL, &outb, &outl) == (size_t)-1 ||
2371 outl >= outpkt->size || inl != 0) {
2372 av_log(avctx, AV_LOG_ERROR, "Unable to recode subtitle event \"%s\" "
2373 "from %s to UTF-8\n", inpkt->data, avctx->sub_charenc);
2374 av_free_packet(&tmp);
2375 ret = AVERROR(errno);
2378 outpkt->size -= outl;
2379 memset(outpkt->data + outpkt->size, 0, outl);
2382 if (cd != (iconv_t)-1)
2386 av_assert0(!"requesting subtitles recoding without iconv");
2390 static int utf8_check(const uint8_t *str)
2392 const uint8_t *byte;
2393 uint32_t codepoint, min;
2397 GET_UTF8(codepoint, *(byte++), return 0;);
2398 min = byte - str == 1 ? 0 : byte - str == 2 ? 0x80 :
2399 1 << (5 * (byte - str) - 4);
2400 if (codepoint < min || codepoint >= 0x110000 ||
2401 codepoint == 0xFFFE /* BOM */ ||
2402 codepoint >= 0xD800 && codepoint <= 0xDFFF /* surrogates */)
2409 int avcodec_decode_subtitle2(AVCodecContext *avctx, AVSubtitle *sub,
2415 if (!avpkt->data && avpkt->size) {
2416 av_log(avctx, AV_LOG_ERROR, "invalid packet: NULL data, size != 0\n");
2417 return AVERROR(EINVAL);
2420 return AVERROR(EINVAL);
2421 if (avctx->codec->type != AVMEDIA_TYPE_SUBTITLE) {
2422 av_log(avctx, AV_LOG_ERROR, "Invalid media type for subtitles\n");
2423 return AVERROR(EINVAL);
2427 avcodec_get_subtitle_defaults(sub);
2429 if ((avctx->codec->capabilities & CODEC_CAP_DELAY) || avpkt->size) {
2430 AVPacket pkt_recoded;
2431 AVPacket tmp = *avpkt;
2432 int did_split = av_packet_split_side_data(&tmp);
2433 //apply_param_change(avctx, &tmp);
2436 /* FFMIN() prevents overflow in case the packet wasn't allocated with
2438 * If the side data is smaller than the buffer padding size, the
2439 * remaining bytes should have already been filled with zeros by the
2440 * original packet allocation anyway. */
2441 memset(tmp.data + tmp.size, 0,
2442 FFMIN(avpkt->size - tmp.size, FF_INPUT_BUFFER_PADDING_SIZE));
2446 ret = recode_subtitle(avctx, &pkt_recoded, &tmp);
2450 avctx->internal->pkt = &pkt_recoded;
2452 if (avctx->pkt_timebase.den && avpkt->pts != AV_NOPTS_VALUE)
2453 sub->pts = av_rescale_q(avpkt->pts,
2454 avctx->pkt_timebase, AV_TIME_BASE_Q);
2455 ret = avctx->codec->decode(avctx, sub, got_sub_ptr, &pkt_recoded);
2456 av_assert1((ret >= 0) >= !!*got_sub_ptr &&
2457 !!*got_sub_ptr >= !!sub->num_rects);
2459 if (sub->num_rects && !sub->end_display_time && avpkt->duration &&
2460 avctx->pkt_timebase.num) {
2461 AVRational ms = { 1, 1000 };
2462 sub->end_display_time = av_rescale_q(avpkt->duration,
2463 avctx->pkt_timebase, ms);
2466 for (i = 0; i < sub->num_rects; i++) {
2467 if (sub->rects[i]->ass && !utf8_check(sub->rects[i]->ass)) {
2468 av_log(avctx, AV_LOG_ERROR,
2469 "Invalid UTF-8 in decoded subtitles text; "
2470 "maybe missing -sub_charenc option\n");
2471 avsubtitle_free(sub);
2472 return AVERROR_INVALIDDATA;
2476 if (tmp.data != pkt_recoded.data) { // did we recode?
2477 /* prevent from destroying side data from original packet */
2478 pkt_recoded.side_data = NULL;
2479 pkt_recoded.side_data_elems = 0;
2481 av_free_packet(&pkt_recoded);
2483 if (avctx->codec_descriptor->props & AV_CODEC_PROP_BITMAP_SUB)
2485 else if (avctx->codec_descriptor->props & AV_CODEC_PROP_TEXT_SUB)
2487 avctx->internal->pkt = NULL;
2491 av_packet_free_side_data(&tmp);
2497 avctx->frame_number++;
2503 void avsubtitle_free(AVSubtitle *sub)
2507 for (i = 0; i < sub->num_rects; i++) {
2508 av_freep(&sub->rects[i]->pict.data[0]);
2509 av_freep(&sub->rects[i]->pict.data[1]);
2510 av_freep(&sub->rects[i]->pict.data[2]);
2511 av_freep(&sub->rects[i]->pict.data[3]);
2512 av_freep(&sub->rects[i]->text);
2513 av_freep(&sub->rects[i]->ass);
2514 av_freep(&sub->rects[i]);
2517 av_freep(&sub->rects);
2519 memset(sub, 0, sizeof(AVSubtitle));
2522 av_cold int ff_codec_close_recursive(AVCodecContext *avctx)
2526 ff_unlock_avcodec();
2528 ret = avcodec_close(avctx);
2530 ff_lock_avcodec(NULL);
2534 av_cold int avcodec_close(AVCodecContext *avctx)
2541 ret = ff_lock_avcodec(avctx);
2545 if (avcodec_is_open(avctx)) {
2546 FramePool *pool = avctx->internal->pool;
2548 if (CONFIG_FRAME_THREAD_ENCODER &&
2549 avctx->internal->frame_thread_encoder && avctx->thread_count > 1) {
2550 ff_unlock_avcodec();
2551 ff_frame_thread_encoder_free(avctx);
2552 ff_lock_avcodec(avctx);
2554 if (HAVE_THREADS && avctx->internal->thread_ctx)
2555 ff_thread_free(avctx);
2556 if (avctx->codec && avctx->codec->close)
2557 avctx->codec->close(avctx);
2558 avctx->coded_frame = NULL;
2559 avctx->internal->byte_buffer_size = 0;
2560 av_freep(&avctx->internal->byte_buffer);
2561 av_frame_free(&avctx->internal->to_free);
2562 for (i = 0; i < FF_ARRAY_ELEMS(pool->pools); i++)
2563 av_buffer_pool_uninit(&pool->pools[i]);
2564 av_freep(&avctx->internal->pool);
2565 av_freep(&avctx->internal);
2568 if (avctx->priv_data && avctx->codec && avctx->codec->priv_class)
2569 av_opt_free(avctx->priv_data);
2571 av_freep(&avctx->priv_data);
2572 if (av_codec_is_encoder(avctx->codec))
2573 av_freep(&avctx->extradata);
2574 avctx->codec = NULL;
2575 avctx->active_thread_type = 0;
2577 ff_unlock_avcodec();
2581 static enum AVCodecID remap_deprecated_codec_id(enum AVCodecID id)
2584 //This is for future deprecatec codec ids, its empty since
2585 //last major bump but will fill up again over time, please don't remove it
2586 // case AV_CODEC_ID_UTVIDEO_DEPRECATED: return AV_CODEC_ID_UTVIDEO;
2587 case AV_CODEC_ID_OPUS_DEPRECATED: return AV_CODEC_ID_OPUS;
2588 case AV_CODEC_ID_TAK_DEPRECATED : return AV_CODEC_ID_TAK;
2589 case AV_CODEC_ID_PCM_S24LE_PLANAR_DEPRECATED : return AV_CODEC_ID_PCM_S24LE_PLANAR;
2590 case AV_CODEC_ID_PCM_S32LE_PLANAR_DEPRECATED : return AV_CODEC_ID_PCM_S32LE_PLANAR;
2591 case AV_CODEC_ID_ESCAPE130_DEPRECATED : return AV_CODEC_ID_ESCAPE130;
2592 case AV_CODEC_ID_G2M_DEPRECATED : return AV_CODEC_ID_G2M;
2593 case AV_CODEC_ID_WEBP_DEPRECATED: return AV_CODEC_ID_WEBP;
2594 case AV_CODEC_ID_HEVC_DEPRECATED: return AV_CODEC_ID_HEVC;
2595 default : return id;
2599 static AVCodec *find_encdec(enum AVCodecID id, int encoder)
2601 AVCodec *p, *experimental = NULL;
2603 id= remap_deprecated_codec_id(id);
2605 if ((encoder ? av_codec_is_encoder(p) : av_codec_is_decoder(p)) &&
2607 if (p->capabilities & CODEC_CAP_EXPERIMENTAL && !experimental) {
2614 return experimental;
2617 AVCodec *avcodec_find_encoder(enum AVCodecID id)
2619 return find_encdec(id, 1);
2622 AVCodec *avcodec_find_encoder_by_name(const char *name)
2629 if (av_codec_is_encoder(p) && strcmp(name, p->name) == 0)
2636 AVCodec *avcodec_find_decoder(enum AVCodecID id)
2638 return find_encdec(id, 0);
2641 AVCodec *avcodec_find_decoder_by_name(const char *name)
2648 if (av_codec_is_decoder(p) && strcmp(name, p->name) == 0)
2655 const char *avcodec_get_name(enum AVCodecID id)
2657 const AVCodecDescriptor *cd;
2660 if (id == AV_CODEC_ID_NONE)
2662 cd = avcodec_descriptor_get(id);
2665 av_log(NULL, AV_LOG_WARNING, "Codec 0x%x is not in the full list.\n", id);
2666 codec = avcodec_find_decoder(id);
2669 codec = avcodec_find_encoder(id);
2672 return "unknown_codec";
2675 size_t av_get_codec_tag_string(char *buf, size_t buf_size, unsigned int codec_tag)
2677 int i, len, ret = 0;
2679 #define TAG_PRINT(x) \
2680 (((x) >= '0' && (x) <= '9') || \
2681 ((x) >= 'a' && (x) <= 'z') || ((x) >= 'A' && (x) <= 'Z') || \
2682 ((x) == '.' || (x) == ' ' || (x) == '-' || (x) == '_'))
2684 for (i = 0; i < 4; i++) {
2685 len = snprintf(buf, buf_size,
2686 TAG_PRINT(codec_tag & 0xFF) ? "%c" : "[%d]", codec_tag & 0xFF);
2688 buf_size = buf_size > len ? buf_size - len : 0;
2695 void avcodec_string(char *buf, int buf_size, AVCodecContext *enc, int encode)
2697 const char *codec_type;
2698 const char *codec_name;
2699 const char *profile = NULL;
2702 AVRational display_aspect_ratio;
2704 if (!buf || buf_size <= 0)
2706 codec_type = av_get_media_type_string(enc->codec_type);
2707 codec_name = avcodec_get_name(enc->codec_id);
2708 if (enc->profile != FF_PROFILE_UNKNOWN) {
2712 p = encode ? avcodec_find_encoder(enc->codec_id) :
2713 avcodec_find_decoder(enc->codec_id);
2715 profile = av_get_profile_name(p, enc->profile);
2718 snprintf(buf, buf_size, "%s: %s", codec_type ? codec_type : "unknown",
2720 buf[0] ^= 'a' ^ 'A'; /* first letter in uppercase */
2722 if (enc->codec && strcmp(enc->codec->name, codec_name))
2723 snprintf(buf + strlen(buf), buf_size - strlen(buf), " (%s)", enc->codec->name);
2726 snprintf(buf + strlen(buf), buf_size - strlen(buf), " (%s)", profile);
2727 if (enc->codec_tag) {
2729 av_get_codec_tag_string(tag_buf, sizeof(tag_buf), enc->codec_tag);
2730 snprintf(buf + strlen(buf), buf_size - strlen(buf),
2731 " (%s / 0x%04X)", tag_buf, enc->codec_tag);
2734 switch (enc->codec_type) {
2735 case AVMEDIA_TYPE_VIDEO:
2736 if (enc->pix_fmt != AV_PIX_FMT_NONE) {
2737 char detail[256] = "(";
2738 const char *colorspace_name;
2739 snprintf(buf + strlen(buf), buf_size - strlen(buf),
2741 av_get_pix_fmt_name(enc->pix_fmt));
2742 if (enc->bits_per_raw_sample &&
2743 enc->bits_per_raw_sample <= av_pix_fmt_desc_get(enc->pix_fmt)->comp[0].depth_minus1)
2744 av_strlcatf(detail, sizeof(detail), "%d bpc, ", enc->bits_per_raw_sample);
2745 if (enc->color_range != AVCOL_RANGE_UNSPECIFIED)
2746 av_strlcatf(detail, sizeof(detail),
2747 enc->color_range == AVCOL_RANGE_MPEG ? "tv, ": "pc, ");
2749 colorspace_name = av_get_colorspace_name(enc->colorspace);
2750 if (colorspace_name)
2751 av_strlcatf(detail, sizeof(detail), "%s, ", colorspace_name);
2753 if (strlen(detail) > 1) {
2754 detail[strlen(detail) - 2] = 0;
2755 av_strlcatf(buf, buf_size, "%s)", detail);
2759 snprintf(buf + strlen(buf), buf_size - strlen(buf),
2761 enc->width, enc->height);
2762 if (enc->sample_aspect_ratio.num) {
2763 av_reduce(&display_aspect_ratio.num, &display_aspect_ratio.den,
2764 enc->width * enc->sample_aspect_ratio.num,
2765 enc->height * enc->sample_aspect_ratio.den,
2767 snprintf(buf + strlen(buf), buf_size - strlen(buf),
2768 " [SAR %d:%d DAR %d:%d]",
2769 enc->sample_aspect_ratio.num, enc->sample_aspect_ratio.den,
2770 display_aspect_ratio.num, display_aspect_ratio.den);
2772 if (av_log_get_level() >= AV_LOG_DEBUG) {
2773 int g = av_gcd(enc->time_base.num, enc->time_base.den);
2774 snprintf(buf + strlen(buf), buf_size - strlen(buf),
2776 enc->time_base.num / g, enc->time_base.den / g);
2780 snprintf(buf + strlen(buf), buf_size - strlen(buf),
2781 ", q=%d-%d", enc->qmin, enc->qmax);
2784 case AVMEDIA_TYPE_AUDIO:
2785 if (enc->sample_rate) {
2786 snprintf(buf + strlen(buf), buf_size - strlen(buf),
2787 ", %d Hz", enc->sample_rate);
2789 av_strlcat(buf, ", ", buf_size);
2790 av_get_channel_layout_string(buf + strlen(buf), buf_size - strlen(buf), enc->channels, enc->channel_layout);
2791 if (enc->sample_fmt != AV_SAMPLE_FMT_NONE) {
2792 snprintf(buf + strlen(buf), buf_size - strlen(buf),
2793 ", %s", av_get_sample_fmt_name(enc->sample_fmt));
2796 case AVMEDIA_TYPE_DATA:
2797 if (av_log_get_level() >= AV_LOG_DEBUG) {
2798 int g = av_gcd(enc->time_base.num, enc->time_base.den);
2800 snprintf(buf + strlen(buf), buf_size - strlen(buf),
2802 enc->time_base.num / g, enc->time_base.den / g);
2805 case AVMEDIA_TYPE_SUBTITLE:
2807 snprintf(buf + strlen(buf), buf_size - strlen(buf),
2808 ", %dx%d", enc->width, enc->height);
2814 if (enc->flags & CODEC_FLAG_PASS1)
2815 snprintf(buf + strlen(buf), buf_size - strlen(buf),
2817 if (enc->flags & CODEC_FLAG_PASS2)
2818 snprintf(buf + strlen(buf), buf_size - strlen(buf),
2821 bitrate = get_bit_rate(enc);
2823 snprintf(buf + strlen(buf), buf_size - strlen(buf),
2824 ", %d kb/s", bitrate / 1000);
2825 } else if (enc->rc_max_rate > 0) {
2826 snprintf(buf + strlen(buf), buf_size - strlen(buf),
2827 ", max. %d kb/s", enc->rc_max_rate / 1000);
2831 const char *av_get_profile_name(const AVCodec *codec, int profile)
2834 if (profile == FF_PROFILE_UNKNOWN || !codec->profiles)
2837 for (p = codec->profiles; p->profile != FF_PROFILE_UNKNOWN; p++)
2838 if (p->profile == profile)
2844 unsigned avcodec_version(void)
2846 // av_assert0(AV_CODEC_ID_V410==164);
2847 av_assert0(AV_CODEC_ID_PCM_S8_PLANAR==65563);
2848 av_assert0(AV_CODEC_ID_ADPCM_G722==69660);
2849 // av_assert0(AV_CODEC_ID_BMV_AUDIO==86071);
2850 av_assert0(AV_CODEC_ID_SRT==94216);
2851 av_assert0(LIBAVCODEC_VERSION_MICRO >= 100);
2853 av_assert0(CODEC_ID_CLLC == AV_CODEC_ID_CLLC);
2854 av_assert0(CODEC_ID_PCM_S8_PLANAR == AV_CODEC_ID_PCM_S8_PLANAR);
2855 av_assert0(CODEC_ID_ADPCM_IMA_APC == AV_CODEC_ID_ADPCM_IMA_APC);
2856 av_assert0(CODEC_ID_ILBC == AV_CODEC_ID_ILBC);
2857 av_assert0(CODEC_ID_SRT == AV_CODEC_ID_SRT);
2858 return LIBAVCODEC_VERSION_INT;
2861 const char *avcodec_configuration(void)
2863 return FFMPEG_CONFIGURATION;
2866 const char *avcodec_license(void)
2868 #define LICENSE_PREFIX "libavcodec license: "
2869 return LICENSE_PREFIX FFMPEG_LICENSE + sizeof(LICENSE_PREFIX) - 1;
2872 void avcodec_flush_buffers(AVCodecContext *avctx)
2874 if (HAVE_THREADS && avctx->active_thread_type & FF_THREAD_FRAME)
2875 ff_thread_flush(avctx);
2876 else if (avctx->codec->flush)
2877 avctx->codec->flush(avctx);
2879 avctx->pts_correction_last_pts =
2880 avctx->pts_correction_last_dts = INT64_MIN;
2882 if (!avctx->refcounted_frames)
2883 av_frame_unref(avctx->internal->to_free);
2886 int av_get_exact_bits_per_sample(enum AVCodecID codec_id)
2889 case AV_CODEC_ID_8SVX_EXP:
2890 case AV_CODEC_ID_8SVX_FIB:
2891 case AV_CODEC_ID_ADPCM_CT:
2892 case AV_CODEC_ID_ADPCM_IMA_APC:
2893 case AV_CODEC_ID_ADPCM_IMA_EA_SEAD:
2894 case AV_CODEC_ID_ADPCM_IMA_OKI:
2895 case AV_CODEC_ID_ADPCM_IMA_WS:
2896 case AV_CODEC_ID_ADPCM_G722:
2897 case AV_CODEC_ID_ADPCM_YAMAHA:
2899 case AV_CODEC_ID_PCM_ALAW:
2900 case AV_CODEC_ID_PCM_MULAW:
2901 case AV_CODEC_ID_PCM_S8:
2902 case AV_CODEC_ID_PCM_S8_PLANAR:
2903 case AV_CODEC_ID_PCM_U8:
2904 case AV_CODEC_ID_PCM_ZORK:
2906 case AV_CODEC_ID_PCM_S16BE:
2907 case AV_CODEC_ID_PCM_S16BE_PLANAR:
2908 case AV_CODEC_ID_PCM_S16LE:
2909 case AV_CODEC_ID_PCM_S16LE_PLANAR:
2910 case AV_CODEC_ID_PCM_U16BE:
2911 case AV_CODEC_ID_PCM_U16LE:
2913 case AV_CODEC_ID_PCM_S24DAUD:
2914 case AV_CODEC_ID_PCM_S24BE:
2915 case AV_CODEC_ID_PCM_S24LE:
2916 case AV_CODEC_ID_PCM_S24LE_PLANAR:
2917 case AV_CODEC_ID_PCM_U24BE:
2918 case AV_CODEC_ID_PCM_U24LE:
2920 case AV_CODEC_ID_PCM_S32BE:
2921 case AV_CODEC_ID_PCM_S32LE:
2922 case AV_CODEC_ID_PCM_S32LE_PLANAR:
2923 case AV_CODEC_ID_PCM_U32BE:
2924 case AV_CODEC_ID_PCM_U32LE:
2925 case AV_CODEC_ID_PCM_F32BE:
2926 case AV_CODEC_ID_PCM_F32LE:
2928 case AV_CODEC_ID_PCM_F64BE:
2929 case AV_CODEC_ID_PCM_F64LE:
2936 enum AVCodecID av_get_pcm_codec(enum AVSampleFormat fmt, int be)
2938 static const enum AVCodecID map[AV_SAMPLE_FMT_NB][2] = {
2939 [AV_SAMPLE_FMT_U8 ] = { AV_CODEC_ID_PCM_U8, AV_CODEC_ID_PCM_U8 },
2940 [AV_SAMPLE_FMT_S16 ] = { AV_CODEC_ID_PCM_S16LE, AV_CODEC_ID_PCM_S16BE },
2941 [AV_SAMPLE_FMT_S32 ] = { AV_CODEC_ID_PCM_S32LE, AV_CODEC_ID_PCM_S32BE },
2942 [AV_SAMPLE_FMT_FLT ] = { AV_CODEC_ID_PCM_F32LE, AV_CODEC_ID_PCM_F32BE },
2943 [AV_SAMPLE_FMT_DBL ] = { AV_CODEC_ID_PCM_F64LE, AV_CODEC_ID_PCM_F64BE },
2944 [AV_SAMPLE_FMT_U8P ] = { AV_CODEC_ID_PCM_U8, AV_CODEC_ID_PCM_U8 },
2945 [AV_SAMPLE_FMT_S16P] = { AV_CODEC_ID_PCM_S16LE, AV_CODEC_ID_PCM_S16BE },
2946 [AV_SAMPLE_FMT_S32P] = { AV_CODEC_ID_PCM_S32LE, AV_CODEC_ID_PCM_S32BE },
2947 [AV_SAMPLE_FMT_FLTP] = { AV_CODEC_ID_PCM_F32LE, AV_CODEC_ID_PCM_F32BE },
2948 [AV_SAMPLE_FMT_DBLP] = { AV_CODEC_ID_PCM_F64LE, AV_CODEC_ID_PCM_F64BE },
2950 if (fmt < 0 || fmt >= AV_SAMPLE_FMT_NB)
2951 return AV_CODEC_ID_NONE;
2952 if (be < 0 || be > 1)
2954 return map[fmt][be];
2957 int av_get_bits_per_sample(enum AVCodecID codec_id)
2960 case AV_CODEC_ID_ADPCM_SBPRO_2:
2962 case AV_CODEC_ID_ADPCM_SBPRO_3:
2964 case AV_CODEC_ID_ADPCM_SBPRO_4:
2965 case AV_CODEC_ID_ADPCM_IMA_WAV:
2966 case AV_CODEC_ID_ADPCM_IMA_QT:
2967 case AV_CODEC_ID_ADPCM_SWF:
2968 case AV_CODEC_ID_ADPCM_MS:
2971 return av_get_exact_bits_per_sample(codec_id);
2975 int av_get_audio_frame_duration(AVCodecContext *avctx, int frame_bytes)
2977 int id, sr, ch, ba, tag, bps;
2979 id = avctx->codec_id;
2980 sr = avctx->sample_rate;
2981 ch = avctx->channels;
2982 ba = avctx->block_align;
2983 tag = avctx->codec_tag;
2984 bps = av_get_exact_bits_per_sample(avctx->codec_id);
2986 /* codecs with an exact constant bits per sample */
2987 if (bps > 0 && ch > 0 && frame_bytes > 0 && ch < 32768 && bps < 32768)
2988 return (frame_bytes * 8LL) / (bps * ch);
2989 bps = avctx->bits_per_coded_sample;
2991 /* codecs with a fixed packet duration */
2993 case AV_CODEC_ID_ADPCM_ADX: return 32;
2994 case AV_CODEC_ID_ADPCM_IMA_QT: return 64;
2995 case AV_CODEC_ID_ADPCM_EA_XAS: return 128;
2996 case AV_CODEC_ID_AMR_NB:
2997 case AV_CODEC_ID_EVRC:
2998 case AV_CODEC_ID_GSM:
2999 case AV_CODEC_ID_QCELP:
3000 case AV_CODEC_ID_RA_288: return 160;
3001 case AV_CODEC_ID_AMR_WB:
3002 case AV_CODEC_ID_GSM_MS: return 320;
3003 case AV_CODEC_ID_MP1: return 384;
3004 case AV_CODEC_ID_ATRAC1: return 512;
3005 case AV_CODEC_ID_ATRAC3: return 1024;
3006 case AV_CODEC_ID_MP2:
3007 case AV_CODEC_ID_MUSEPACK7: return 1152;
3008 case AV_CODEC_ID_AC3: return 1536;
3012 /* calc from sample rate */
3013 if (id == AV_CODEC_ID_TTA)
3014 return 256 * sr / 245;
3017 /* calc from sample rate and channels */
3018 if (id == AV_CODEC_ID_BINKAUDIO_DCT)
3019 return (480 << (sr / 22050)) / ch;
3024 /* calc from block_align */
3025 if (id == AV_CODEC_ID_SIPR) {
3027 case 20: return 160;
3028 case 19: return 144;
3029 case 29: return 288;
3030 case 37: return 480;
3032 } else if (id == AV_CODEC_ID_ILBC) {
3034 case 38: return 160;
3035 case 50: return 240;
3040 if (frame_bytes > 0) {
3041 /* calc from frame_bytes only */
3042 if (id == AV_CODEC_ID_TRUESPEECH)
3043 return 240 * (frame_bytes / 32);
3044 if (id == AV_CODEC_ID_NELLYMOSER)
3045 return 256 * (frame_bytes / 64);
3046 if (id == AV_CODEC_ID_RA_144)
3047 return 160 * (frame_bytes / 20);
3048 if (id == AV_CODEC_ID_G723_1)
3049 return 240 * (frame_bytes / 24);
3052 /* calc from frame_bytes and bits_per_coded_sample */
3053 if (id == AV_CODEC_ID_ADPCM_G726)
3054 return frame_bytes * 8 / bps;
3058 /* calc from frame_bytes and channels */
3060 case AV_CODEC_ID_ADPCM_AFC:
3061 return frame_bytes / (9 * ch) * 16;
3062 case AV_CODEC_ID_ADPCM_DTK:
3063 return frame_bytes / (16 * ch) * 28;
3064 case AV_CODEC_ID_ADPCM_4XM:
3065 case AV_CODEC_ID_ADPCM_IMA_ISS:
3066 return (frame_bytes - 4 * ch) * 2 / ch;
3067 case AV_CODEC_ID_ADPCM_IMA_SMJPEG:
3068 return (frame_bytes - 4) * 2 / ch;
3069 case AV_CODEC_ID_ADPCM_IMA_AMV:
3070 return (frame_bytes - 8) * 2 / ch;
3071 case AV_CODEC_ID_ADPCM_XA:
3072 return (frame_bytes / 128) * 224 / ch;
3073 case AV_CODEC_ID_INTERPLAY_DPCM:
3074 return (frame_bytes - 6 - ch) / ch;
3075 case AV_CODEC_ID_ROQ_DPCM:
3076 return (frame_bytes - 8) / ch;
3077 case AV_CODEC_ID_XAN_DPCM:
3078 return (frame_bytes - 2 * ch) / ch;
3079 case AV_CODEC_ID_MACE3:
3080 return 3 * frame_bytes / ch;
3081 case AV_CODEC_ID_MACE6:
3082 return 6 * frame_bytes / ch;
3083 case AV_CODEC_ID_PCM_LXF:
3084 return 2 * (frame_bytes / (5 * ch));
3085 case AV_CODEC_ID_IAC:
3086 case AV_CODEC_ID_IMC:
3087 return 4 * frame_bytes / ch;
3091 /* calc from frame_bytes, channels, and codec_tag */
3092 if (id == AV_CODEC_ID_SOL_DPCM) {
3094 return frame_bytes / ch;
3096 return frame_bytes * 2 / ch;
3101 /* calc from frame_bytes, channels, and block_align */
3102 int blocks = frame_bytes / ba;
3103 switch (avctx->codec_id) {
3104 case AV_CODEC_ID_ADPCM_IMA_WAV:
3105 if (bps < 2 || bps > 5)
3107 return blocks * (1 + (ba - 4 * ch) / (bps * ch) * 8);
3108 case AV_CODEC_ID_ADPCM_IMA_DK3:
3109 return blocks * (((ba - 16) * 2 / 3 * 4) / ch);
3110 case AV_CODEC_ID_ADPCM_IMA_DK4:
3111 return blocks * (1 + (ba - 4 * ch) * 2 / ch);
3112 case AV_CODEC_ID_ADPCM_IMA_RAD:
3113 return blocks * ((ba - 4 * ch) * 2 / ch);
3114 case AV_CODEC_ID_ADPCM_MS:
3115 return blocks * (2 + (ba - 7 * ch) * 2 / ch);
3120 /* calc from frame_bytes, channels, and bits_per_coded_sample */
3121 switch (avctx->codec_id) {
3122 case AV_CODEC_ID_PCM_DVD:
3125 return 2 * (frame_bytes / ((bps * 2 / 8) * ch));
3126 case AV_CODEC_ID_PCM_BLURAY:
3129 return frame_bytes / ((FFALIGN(ch, 2) * bps) / 8);
3130 case AV_CODEC_ID_S302M:
3131 return 2 * (frame_bytes / ((bps + 4) / 4)) / ch;
3141 int ff_thread_init(AVCodecContext *s)
3148 unsigned int av_xiphlacing(unsigned char *s, unsigned int v)
3162 int ff_match_2uint16(const uint16_t(*tab)[2], int size, int a, int b)
3165 for (i = 0; i < size && !(tab[i][0] == a && tab[i][1] == b); i++) ;
3169 #if FF_API_MISSING_SAMPLE
3170 FF_DISABLE_DEPRECATION_WARNINGS
3171 void av_log_missing_feature(void *avc, const char *feature, int want_sample)
3173 av_log(avc, AV_LOG_WARNING, "%s is not implemented. Update your FFmpeg "
3174 "version to the newest one from Git. If the problem still "
3175 "occurs, it means that your file has a feature which has not "
3176 "been implemented.\n", feature);
3178 av_log_ask_for_sample(avc, NULL);
3181 void av_log_ask_for_sample(void *avc, const char *msg, ...)
3183 va_list argument_list;
3185 va_start(argument_list, msg);
3188 av_vlog(avc, AV_LOG_WARNING, msg, argument_list);
3189 av_log(avc, AV_LOG_WARNING, "If you want to help, upload a sample "
3190 "of this file to ftp://upload.ffmpeg.org/MPlayer/incoming/ "
3191 "and contact the ffmpeg-devel mailing list.\n");
3193 va_end(argument_list);
3195 FF_ENABLE_DEPRECATION_WARNINGS
3196 #endif /* FF_API_MISSING_SAMPLE */
3198 static AVHWAccel *first_hwaccel = NULL;
3199 static AVHWAccel **last_hwaccel = &first_hwaccel;
3201 void av_register_hwaccel(AVHWAccel *hwaccel)
3203 AVHWAccel **p = last_hwaccel;
3204 hwaccel->next = NULL;
3205 while(*p || avpriv_atomic_ptr_cas((void * volatile *)p, NULL, hwaccel))
3207 last_hwaccel = &hwaccel->next;
3210 AVHWAccel *av_hwaccel_next(AVHWAccel *hwaccel)
3212 return hwaccel ? hwaccel->next : first_hwaccel;
3215 AVHWAccel *ff_find_hwaccel(AVCodecContext *avctx)
3217 enum AVCodecID codec_id = avctx->codec->id;
3218 enum AVPixelFormat pix_fmt = avctx->pix_fmt;
3220 AVHWAccel *hwaccel = NULL;
3222 while ((hwaccel = av_hwaccel_next(hwaccel)))
3223 if (hwaccel->id == codec_id
3224 && hwaccel->pix_fmt == pix_fmt)
3229 int av_lockmgr_register(int (*cb)(void **mutex, enum AVLockOp op))
3232 if (lockmgr_cb(&codec_mutex, AV_LOCK_DESTROY))
3234 if (lockmgr_cb(&avformat_mutex, AV_LOCK_DESTROY))
3241 if (lockmgr_cb(&codec_mutex, AV_LOCK_CREATE))
3243 if (lockmgr_cb(&avformat_mutex, AV_LOCK_CREATE))
3249 int ff_lock_avcodec(AVCodecContext *log_ctx)
3252 if ((*lockmgr_cb)(&codec_mutex, AV_LOCK_OBTAIN))
3255 entangled_thread_counter++;
3256 if (entangled_thread_counter != 1) {
3257 av_log(log_ctx, AV_LOG_ERROR, "Insufficient thread locking around avcodec_open/close()\n");
3259 av_log(log_ctx, AV_LOG_ERROR, "No lock manager is set, please see av_lockmgr_register()\n");
3260 ff_avcodec_locked = 1;
3261 ff_unlock_avcodec();
3262 return AVERROR(EINVAL);
3264 av_assert0(!ff_avcodec_locked);
3265 ff_avcodec_locked = 1;
3269 int ff_unlock_avcodec(void)
3271 av_assert0(ff_avcodec_locked);
3272 ff_avcodec_locked = 0;
3273 entangled_thread_counter--;
3275 if ((*lockmgr_cb)(&codec_mutex, AV_LOCK_RELEASE))
3281 int avpriv_lock_avformat(void)
3284 if ((*lockmgr_cb)(&avformat_mutex, AV_LOCK_OBTAIN))
3290 int avpriv_unlock_avformat(void)
3293 if ((*lockmgr_cb)(&avformat_mutex, AV_LOCK_RELEASE))
3299 unsigned int avpriv_toupper4(unsigned int x)
3301 return av_toupper(x & 0xFF) +
3302 (av_toupper((x >> 8) & 0xFF) << 8) +
3303 (av_toupper((x >> 16) & 0xFF) << 16) +
3304 (av_toupper((x >> 24) & 0xFF) << 24);
3307 int ff_thread_ref_frame(ThreadFrame *dst, ThreadFrame *src)
3311 dst->owner = src->owner;
3313 ret = av_frame_ref(dst->f, src->f);
3317 if (src->progress &&
3318 !(dst->progress = av_buffer_ref(src->progress))) {
3319 ff_thread_release_buffer(dst->owner, dst);
3320 return AVERROR(ENOMEM);
3328 enum AVPixelFormat ff_thread_get_format(AVCodecContext *avctx, const enum AVPixelFormat *fmt)
3330 return avctx->get_format(avctx, fmt);
3333 int ff_thread_get_buffer(AVCodecContext *avctx, ThreadFrame *f, int flags)
3336 return ff_get_buffer(avctx, f->f, flags);
3339 void ff_thread_release_buffer(AVCodecContext *avctx, ThreadFrame *f)
3341 av_frame_unref(f->f);
3344 void ff_thread_finish_setup(AVCodecContext *avctx)
3348 void ff_thread_report_progress(ThreadFrame *f, int progress, int field)
3352 void ff_thread_await_progress(ThreadFrame *f, int progress, int field)
3356 int ff_thread_can_start_frame(AVCodecContext *avctx)
3361 int ff_alloc_entries(AVCodecContext *avctx, int count)
3366 void ff_reset_entries(AVCodecContext *avctx)
3370 void ff_thread_await_progress2(AVCodecContext *avctx, int field, int thread, int shift)
3374 void ff_thread_report_progress2(AVCodecContext *avctx, int field, int thread, int n)
3380 enum AVMediaType avcodec_get_type(enum AVCodecID codec_id)
3382 AVCodec *c= avcodec_find_decoder(codec_id);
3384 c= avcodec_find_encoder(codec_id);
3388 if (codec_id <= AV_CODEC_ID_NONE)
3389 return AVMEDIA_TYPE_UNKNOWN;
3390 else if (codec_id < AV_CODEC_ID_FIRST_AUDIO)
3391 return AVMEDIA_TYPE_VIDEO;
3392 else if (codec_id < AV_CODEC_ID_FIRST_SUBTITLE)
3393 return AVMEDIA_TYPE_AUDIO;
3394 else if (codec_id < AV_CODEC_ID_FIRST_UNKNOWN)
3395 return AVMEDIA_TYPE_SUBTITLE;
3397 return AVMEDIA_TYPE_UNKNOWN;
3400 int avcodec_is_open(AVCodecContext *s)
3402 return !!s->internal;
3405 int avpriv_bprint_to_extradata(AVCodecContext *avctx, struct AVBPrint *buf)
3410 ret = av_bprint_finalize(buf, &str);
3413 avctx->extradata = str;
3414 /* Note: the string is NUL terminated (so extradata can be read as a
3415 * string), but the ending character is not accounted in the size (in
3416 * binary formats you are likely not supposed to mux that character). When
3417 * extradata is copied, it is also padded with FF_INPUT_BUFFER_PADDING_SIZE
3419 avctx->extradata_size = buf->len;
3423 const uint8_t *avpriv_find_start_code(const uint8_t *av_restrict p,
3425 uint32_t *av_restrict state)
3429 av_assert0(p <= end);
3433 for (i = 0; i < 3; i++) {
3434 uint32_t tmp = *state << 8;
3435 *state = tmp + *(p++);
3436 if (tmp == 0x100 || p == end)
3441 if (p[-1] > 1 ) p += 3;
3442 else if (p[-2] ) p += 2;
3443 else if (p[-3]|(p[-1]-1)) p++;
3450 p = FFMIN(p, end) - 4;
3451 *state = AV_RB32(p);