2 * generic decoding-related code
4 * This file is part of FFmpeg.
6 * FFmpeg is free software; you can redistribute it and/or
7 * modify it under the terms of the GNU Lesser General Public
8 * License as published by the Free Software Foundation; either
9 * version 2.1 of the License, or (at your option) any later version.
11 * FFmpeg is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14 * Lesser General Public License for more details.
16 * You should have received a copy of the GNU Lesser General Public
17 * License along with FFmpeg; if not, write to the Free Software
18 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
30 #include "libavutil/avassert.h"
31 #include "libavutil/avstring.h"
32 #include "libavutil/bprint.h"
33 #include "libavutil/common.h"
34 #include "libavutil/frame.h"
35 #include "libavutil/hwcontext.h"
36 #include "libavutil/imgutils.h"
37 #include "libavutil/internal.h"
38 #include "libavutil/intmath.h"
39 #include "libavutil/opt.h"
42 #include "bytestream.h"
46 #include "packet_internal.h"
49 typedef struct FramePool {
51 * Pools for each data plane. For audio all the planes have the same size,
52 * so only pools[0] is used.
54 AVBufferPool *pools[4];
61 int stride_align[AV_NUM_DATA_POINTERS];
68 static int apply_param_change(AVCodecContext *avctx, const AVPacket *avpkt)
75 data = av_packet_get_side_data(avpkt, AV_PKT_DATA_PARAM_CHANGE, &size);
79 if (!(avctx->codec->capabilities & AV_CODEC_CAP_PARAM_CHANGE)) {
80 av_log(avctx, AV_LOG_ERROR, "This decoder does not support parameter "
81 "changes, but PARAM_CHANGE side data was sent to it.\n");
82 ret = AVERROR(EINVAL);
89 flags = bytestream_get_le32(&data);
92 if (flags & AV_SIDE_DATA_PARAM_CHANGE_CHANNEL_COUNT) {
95 val = bytestream_get_le32(&data);
96 if (val <= 0 || val > INT_MAX) {
97 av_log(avctx, AV_LOG_ERROR, "Invalid channel count");
98 ret = AVERROR_INVALIDDATA;
101 avctx->channels = val;
104 if (flags & AV_SIDE_DATA_PARAM_CHANGE_CHANNEL_LAYOUT) {
107 avctx->channel_layout = bytestream_get_le64(&data);
110 if (flags & AV_SIDE_DATA_PARAM_CHANGE_SAMPLE_RATE) {
113 val = bytestream_get_le32(&data);
114 if (val <= 0 || val > INT_MAX) {
115 av_log(avctx, AV_LOG_ERROR, "Invalid sample rate");
116 ret = AVERROR_INVALIDDATA;
119 avctx->sample_rate = val;
122 if (flags & AV_SIDE_DATA_PARAM_CHANGE_DIMENSIONS) {
125 avctx->width = bytestream_get_le32(&data);
126 avctx->height = bytestream_get_le32(&data);
128 ret = ff_set_dimensions(avctx, avctx->width, avctx->height);
135 av_log(avctx, AV_LOG_ERROR, "PARAM_CHANGE side data too small.\n");
136 ret = AVERROR_INVALIDDATA;
139 av_log(avctx, AV_LOG_ERROR, "Error applying parameter changes.\n");
140 if (avctx->err_recognition & AV_EF_EXPLODE)
146 #define IS_EMPTY(pkt) (!(pkt)->data)
148 static int extract_packet_props(AVCodecInternal *avci, AVPacket *pkt)
152 ret = avpriv_packet_list_put(&avci->pkt_props, &avci->pkt_props_tail, pkt,
153 av_packet_copy_props, 0);
156 avci->pkt_props_tail->pkt.size = pkt->size; // HACK: Needed for ff_decode_frame_props().
157 avci->pkt_props_tail->pkt.data = (void*)1; // HACK: Needed for IS_EMPTY().
159 if (IS_EMPTY(avci->last_pkt_props)) {
160 ret = avpriv_packet_list_get(&avci->pkt_props,
161 &avci->pkt_props_tail,
162 avci->last_pkt_props);
163 av_assert0(ret != AVERROR(EAGAIN));
168 static int unrefcount_frame(AVCodecInternal *avci, AVFrame *frame)
172 /* move the original frame to our backup */
173 av_frame_unref(avci->to_free);
174 av_frame_move_ref(avci->to_free, frame);
176 /* now copy everything except the AVBufferRefs back
177 * note that we make a COPY of the side data, so calling av_frame_free() on
178 * the caller's frame will work properly */
179 ret = av_frame_copy_props(frame, avci->to_free);
183 memcpy(frame->data, avci->to_free->data, sizeof(frame->data));
184 memcpy(frame->linesize, avci->to_free->linesize, sizeof(frame->linesize));
185 if (avci->to_free->extended_data != avci->to_free->data) {
186 int planes = avci->to_free->channels;
187 int size = planes * sizeof(*frame->extended_data);
190 av_frame_unref(frame);
194 frame->extended_data = av_malloc(size);
195 if (!frame->extended_data) {
196 av_frame_unref(frame);
197 return AVERROR(ENOMEM);
199 memcpy(frame->extended_data, avci->to_free->extended_data,
202 frame->extended_data = frame->data;
204 frame->format = avci->to_free->format;
205 frame->width = avci->to_free->width;
206 frame->height = avci->to_free->height;
207 frame->channel_layout = avci->to_free->channel_layout;
208 frame->nb_samples = avci->to_free->nb_samples;
209 frame->channels = avci->to_free->channels;
214 int ff_decode_bsfs_init(AVCodecContext *avctx)
216 AVCodecInternal *avci = avctx->internal;
222 ret = av_bsf_list_parse_str(avctx->codec->bsfs, &avci->bsf);
224 av_log(avctx, AV_LOG_ERROR, "Error parsing decoder bitstream filters '%s': %s\n", avctx->codec->bsfs, av_err2str(ret));
225 if (ret != AVERROR(ENOMEM))
230 /* We do not currently have an API for passing the input timebase into decoders,
231 * but no filters used here should actually need it.
232 * So we make up some plausible-looking number (the MPEG 90kHz timebase) */
233 avci->bsf->time_base_in = (AVRational){ 1, 90000 };
234 ret = avcodec_parameters_from_context(avci->bsf->par_in, avctx);
238 ret = av_bsf_init(avci->bsf);
244 av_bsf_free(&avci->bsf);
248 int ff_decode_get_packet(AVCodecContext *avctx, AVPacket *pkt)
250 AVCodecInternal *avci = avctx->internal;
256 ret = av_bsf_receive_packet(avci->bsf, pkt);
257 if (ret == AVERROR_EOF)
262 ret = extract_packet_props(avctx->internal, pkt);
266 ret = apply_param_change(avctx, pkt);
270 if (avctx->codec->receive_frame)
271 avci->compat_decode_consumed += pkt->size;
275 av_packet_unref(pkt);
280 * Attempt to guess proper monotonic timestamps for decoded video frames
281 * which might have incorrect times. Input timestamps may wrap around, in
282 * which case the output will as well.
284 * @param pts the pts field of the decoded AVPacket, as passed through
286 * @param dts the dts field of the decoded AVPacket
287 * @return one of the input values, may be AV_NOPTS_VALUE
289 static int64_t guess_correct_pts(AVCodecContext *ctx,
290 int64_t reordered_pts, int64_t dts)
292 int64_t pts = AV_NOPTS_VALUE;
294 if (dts != AV_NOPTS_VALUE) {
295 ctx->pts_correction_num_faulty_dts += dts <= ctx->pts_correction_last_dts;
296 ctx->pts_correction_last_dts = dts;
297 } else if (reordered_pts != AV_NOPTS_VALUE)
298 ctx->pts_correction_last_dts = reordered_pts;
300 if (reordered_pts != AV_NOPTS_VALUE) {
301 ctx->pts_correction_num_faulty_pts += reordered_pts <= ctx->pts_correction_last_pts;
302 ctx->pts_correction_last_pts = reordered_pts;
303 } else if(dts != AV_NOPTS_VALUE)
304 ctx->pts_correction_last_pts = dts;
306 if ((ctx->pts_correction_num_faulty_pts<=ctx->pts_correction_num_faulty_dts || dts == AV_NOPTS_VALUE)
307 && reordered_pts != AV_NOPTS_VALUE)
316 * The core of the receive_frame_wrapper for the decoders implementing
317 * the simple API. Certain decoders might consume partial packets without
318 * returning any output, so this function needs to be called in a loop until it
321 static inline int decode_simple_internal(AVCodecContext *avctx, AVFrame *frame, int64_t *discarded_samples)
323 AVCodecInternal *avci = avctx->internal;
324 DecodeSimpleContext *ds = &avci->ds;
325 AVPacket *pkt = ds->in_pkt;
326 // copy to ensure we do not change pkt
327 int got_frame, actual_got_frame;
330 if (!pkt->data && !avci->draining) {
331 av_packet_unref(pkt);
332 ret = ff_decode_get_packet(avctx, pkt);
333 if (ret < 0 && ret != AVERROR_EOF)
337 // Some codecs (at least wma lossless) will crash when feeding drain packets
338 // after EOF was signaled.
339 if (avci->draining_done)
343 !(avctx->codec->capabilities & AV_CODEC_CAP_DELAY ||
344 avctx->active_thread_type & FF_THREAD_FRAME))
349 if (HAVE_THREADS && avctx->active_thread_type & FF_THREAD_FRAME) {
350 ret = ff_thread_decode_frame(avctx, frame, &got_frame, pkt);
352 ret = avctx->codec->decode(avctx, frame, &got_frame, pkt);
354 if (!(avctx->codec->caps_internal & FF_CODEC_CAP_SETS_PKT_DTS))
355 frame->pkt_dts = pkt->dts;
356 if (avctx->codec->type == AVMEDIA_TYPE_VIDEO) {
357 if(!avctx->has_b_frames)
358 frame->pkt_pos = pkt->pos;
359 //FIXME these should be under if(!avctx->has_b_frames)
360 /* get_buffer is supposed to set frame parameters */
361 if (!(avctx->codec->capabilities & AV_CODEC_CAP_DR1)) {
362 if (!frame->sample_aspect_ratio.num) frame->sample_aspect_ratio = avctx->sample_aspect_ratio;
363 if (!frame->width) frame->width = avctx->width;
364 if (!frame->height) frame->height = avctx->height;
365 if (frame->format == AV_PIX_FMT_NONE) frame->format = avctx->pix_fmt;
370 actual_got_frame = got_frame;
372 if (avctx->codec->type == AVMEDIA_TYPE_VIDEO) {
373 if (frame->flags & AV_FRAME_FLAG_DISCARD)
376 frame->best_effort_timestamp = guess_correct_pts(avctx,
379 } else if (avctx->codec->type == AVMEDIA_TYPE_AUDIO) {
382 uint32_t discard_padding = 0;
383 uint8_t skip_reason = 0;
384 uint8_t discard_reason = 0;
386 if (ret >= 0 && got_frame) {
387 frame->best_effort_timestamp = guess_correct_pts(avctx,
390 if (frame->format == AV_SAMPLE_FMT_NONE)
391 frame->format = avctx->sample_fmt;
392 if (!frame->channel_layout)
393 frame->channel_layout = avctx->channel_layout;
394 if (!frame->channels)
395 frame->channels = avctx->channels;
396 if (!frame->sample_rate)
397 frame->sample_rate = avctx->sample_rate;
400 side= av_packet_get_side_data(avci->last_pkt_props, AV_PKT_DATA_SKIP_SAMPLES, &side_size);
401 if(side && side_size>=10) {
402 avci->skip_samples = AV_RL32(side) * avci->skip_samples_multiplier;
403 discard_padding = AV_RL32(side + 4);
404 av_log(avctx, AV_LOG_DEBUG, "skip %d / discard %d samples due to side data\n",
405 avci->skip_samples, (int)discard_padding);
406 skip_reason = AV_RL8(side + 8);
407 discard_reason = AV_RL8(side + 9);
410 if ((frame->flags & AV_FRAME_FLAG_DISCARD) && got_frame &&
411 !(avctx->flags2 & AV_CODEC_FLAG2_SKIP_MANUAL)) {
412 avci->skip_samples = FFMAX(0, avci->skip_samples - frame->nb_samples);
414 *discarded_samples += frame->nb_samples;
417 if (avci->skip_samples > 0 && got_frame &&
418 !(avctx->flags2 & AV_CODEC_FLAG2_SKIP_MANUAL)) {
419 if(frame->nb_samples <= avci->skip_samples){
421 *discarded_samples += frame->nb_samples;
422 avci->skip_samples -= frame->nb_samples;
423 av_log(avctx, AV_LOG_DEBUG, "skip whole frame, skip left: %d\n",
426 av_samples_copy(frame->extended_data, frame->extended_data, 0, avci->skip_samples,
427 frame->nb_samples - avci->skip_samples, avctx->channels, frame->format);
428 if(avctx->pkt_timebase.num && avctx->sample_rate) {
429 int64_t diff_ts = av_rescale_q(avci->skip_samples,
430 (AVRational){1, avctx->sample_rate},
431 avctx->pkt_timebase);
432 if(frame->pts!=AV_NOPTS_VALUE)
433 frame->pts += diff_ts;
435 FF_DISABLE_DEPRECATION_WARNINGS
436 if(frame->pkt_pts!=AV_NOPTS_VALUE)
437 frame->pkt_pts += diff_ts;
438 FF_ENABLE_DEPRECATION_WARNINGS
440 if(frame->pkt_dts!=AV_NOPTS_VALUE)
441 frame->pkt_dts += diff_ts;
442 if (frame->pkt_duration >= diff_ts)
443 frame->pkt_duration -= diff_ts;
445 av_log(avctx, AV_LOG_WARNING, "Could not update timestamps for skipped samples.\n");
447 av_log(avctx, AV_LOG_DEBUG, "skip %d/%d samples\n",
448 avci->skip_samples, frame->nb_samples);
449 *discarded_samples += avci->skip_samples;
450 frame->nb_samples -= avci->skip_samples;
451 avci->skip_samples = 0;
455 if (discard_padding > 0 && discard_padding <= frame->nb_samples && got_frame &&
456 !(avctx->flags2 & AV_CODEC_FLAG2_SKIP_MANUAL)) {
457 if (discard_padding == frame->nb_samples) {
458 *discarded_samples += frame->nb_samples;
461 if(avctx->pkt_timebase.num && avctx->sample_rate) {
462 int64_t diff_ts = av_rescale_q(frame->nb_samples - discard_padding,
463 (AVRational){1, avctx->sample_rate},
464 avctx->pkt_timebase);
465 frame->pkt_duration = diff_ts;
467 av_log(avctx, AV_LOG_WARNING, "Could not update timestamps for discarded samples.\n");
469 av_log(avctx, AV_LOG_DEBUG, "discard %d/%d samples\n",
470 (int)discard_padding, frame->nb_samples);
471 frame->nb_samples -= discard_padding;
475 if ((avctx->flags2 & AV_CODEC_FLAG2_SKIP_MANUAL) && got_frame) {
476 AVFrameSideData *fside = av_frame_new_side_data(frame, AV_FRAME_DATA_SKIP_SAMPLES, 10);
478 AV_WL32(fside->data, avci->skip_samples);
479 AV_WL32(fside->data + 4, discard_padding);
480 AV_WL8(fside->data + 8, skip_reason);
481 AV_WL8(fside->data + 9, discard_reason);
482 avci->skip_samples = 0;
487 if (avctx->codec->type == AVMEDIA_TYPE_AUDIO &&
488 !avci->showed_multi_packet_warning &&
489 ret >= 0 && ret != pkt->size && !(avctx->codec->capabilities & AV_CODEC_CAP_SUBFRAMES)) {
490 av_log(avctx, AV_LOG_WARNING, "Multiple frames in a packet.\n");
491 avci->showed_multi_packet_warning = 1;
495 av_frame_unref(frame);
497 if (ret >= 0 && avctx->codec->type == AVMEDIA_TYPE_VIDEO && !(avctx->flags & AV_CODEC_FLAG_TRUNCATED))
500 #if FF_API_AVCTX_TIMEBASE
501 if (avctx->framerate.num > 0 && avctx->framerate.den > 0)
502 avctx->time_base = av_inv_q(av_mul_q(avctx->framerate, (AVRational){avctx->ticks_per_frame, 1}));
505 /* do not stop draining when actual_got_frame != 0 or ret < 0 */
506 /* got_frame == 0 but actual_got_frame != 0 when frame is discarded */
507 if (avci->draining && !actual_got_frame) {
509 /* prevent infinite loop if a decoder wrongly always return error on draining */
510 /* reasonable nb_errors_max = maximum b frames + thread count */
511 int nb_errors_max = 20 + (HAVE_THREADS && avctx->active_thread_type & FF_THREAD_FRAME ?
512 avctx->thread_count : 1);
514 if (avci->nb_draining_errors++ >= nb_errors_max) {
515 av_log(avctx, AV_LOG_ERROR, "Too many errors when draining, this is a bug. "
516 "Stop draining and force EOF.\n");
517 avci->draining_done = 1;
521 avci->draining_done = 1;
525 avci->compat_decode_consumed += ret;
527 if (ret >= pkt->size || ret < 0) {
528 av_packet_unref(pkt);
529 av_packet_unref(avci->last_pkt_props);
533 pkt->data += consumed;
534 pkt->size -= consumed;
535 avci->last_pkt_props->size -= consumed; // See extract_packet_props() comment.
536 pkt->pts = AV_NOPTS_VALUE;
537 pkt->dts = AV_NOPTS_VALUE;
538 avci->last_pkt_props->pts = AV_NOPTS_VALUE;
539 avci->last_pkt_props->dts = AV_NOPTS_VALUE;
543 av_assert0(frame->buf[0]);
545 return ret < 0 ? ret : 0;
548 static int decode_simple_receive_frame(AVCodecContext *avctx, AVFrame *frame)
551 int64_t discarded_samples = 0;
553 while (!frame->buf[0]) {
554 if (discarded_samples > avctx->max_samples)
555 return AVERROR(EAGAIN);
556 ret = decode_simple_internal(avctx, frame, &discarded_samples);
564 static int decode_receive_frame_internal(AVCodecContext *avctx, AVFrame *frame)
566 AVCodecInternal *avci = avctx->internal;
569 av_assert0(!frame->buf[0]);
571 if (avctx->codec->receive_frame) {
572 ret = avctx->codec->receive_frame(avctx, frame);
573 if (ret != AVERROR(EAGAIN))
574 av_packet_unref(avci->last_pkt_props);
576 ret = decode_simple_receive_frame(avctx, frame);
578 if (ret == AVERROR_EOF)
579 avci->draining_done = 1;
582 /* the only case where decode data is not set should be decoders
583 * that do not call ff_get_buffer() */
584 av_assert0((frame->private_ref && frame->private_ref->size == sizeof(FrameDecodeData)) ||
585 !(avctx->codec->capabilities & AV_CODEC_CAP_DR1));
587 if (frame->private_ref) {
588 FrameDecodeData *fdd = (FrameDecodeData*)frame->private_ref->data;
590 if (fdd->post_process) {
591 ret = fdd->post_process(avctx, frame);
593 av_frame_unref(frame);
600 /* free the per-frame decode data */
601 av_buffer_unref(&frame->private_ref);
606 int attribute_align_arg avcodec_send_packet(AVCodecContext *avctx, const AVPacket *avpkt)
608 AVCodecInternal *avci = avctx->internal;
611 if (!avcodec_is_open(avctx) || !av_codec_is_decoder(avctx->codec))
612 return AVERROR(EINVAL);
614 if (avctx->internal->draining)
617 if (avpkt && !avpkt->size && avpkt->data)
618 return AVERROR(EINVAL);
620 av_packet_unref(avci->buffer_pkt);
621 if (avpkt && (avpkt->data || avpkt->side_data_elems)) {
622 ret = av_packet_ref(avci->buffer_pkt, avpkt);
627 ret = av_bsf_send_packet(avci->bsf, avci->buffer_pkt);
629 av_packet_unref(avci->buffer_pkt);
633 if (!avci->buffer_frame->buf[0]) {
634 ret = decode_receive_frame_internal(avctx, avci->buffer_frame);
635 if (ret < 0 && ret != AVERROR(EAGAIN) && ret != AVERROR_EOF)
642 static int apply_cropping(AVCodecContext *avctx, AVFrame *frame)
644 /* make sure we are noisy about decoders returning invalid cropping data */
645 if (frame->crop_left >= INT_MAX - frame->crop_right ||
646 frame->crop_top >= INT_MAX - frame->crop_bottom ||
647 (frame->crop_left + frame->crop_right) >= frame->width ||
648 (frame->crop_top + frame->crop_bottom) >= frame->height) {
649 av_log(avctx, AV_LOG_WARNING,
650 "Invalid cropping information set by a decoder: "
651 "%"SIZE_SPECIFIER"/%"SIZE_SPECIFIER"/%"SIZE_SPECIFIER"/%"SIZE_SPECIFIER" "
652 "(frame size %dx%d). This is a bug, please report it\n",
653 frame->crop_left, frame->crop_right, frame->crop_top, frame->crop_bottom,
654 frame->width, frame->height);
655 frame->crop_left = 0;
656 frame->crop_right = 0;
658 frame->crop_bottom = 0;
662 if (!avctx->apply_cropping)
665 return av_frame_apply_cropping(frame, avctx->flags & AV_CODEC_FLAG_UNALIGNED ?
666 AV_FRAME_CROP_UNALIGNED : 0);
669 int attribute_align_arg avcodec_receive_frame(AVCodecContext *avctx, AVFrame *frame)
671 AVCodecInternal *avci = avctx->internal;
674 av_frame_unref(frame);
676 if (!avcodec_is_open(avctx) || !av_codec_is_decoder(avctx->codec))
677 return AVERROR(EINVAL);
679 if (avci->buffer_frame->buf[0]) {
680 av_frame_move_ref(frame, avci->buffer_frame);
682 ret = decode_receive_frame_internal(avctx, frame);
687 if (avctx->codec_type == AVMEDIA_TYPE_VIDEO) {
688 ret = apply_cropping(avctx, frame);
690 av_frame_unref(frame);
695 avctx->frame_number++;
697 if (avctx->flags & AV_CODEC_FLAG_DROPCHANGED) {
699 if (avctx->frame_number == 1) {
700 avci->initial_format = frame->format;
701 switch(avctx->codec_type) {
702 case AVMEDIA_TYPE_VIDEO:
703 avci->initial_width = frame->width;
704 avci->initial_height = frame->height;
706 case AVMEDIA_TYPE_AUDIO:
707 avci->initial_sample_rate = frame->sample_rate ? frame->sample_rate :
709 avci->initial_channels = frame->channels;
710 avci->initial_channel_layout = frame->channel_layout;
715 if (avctx->frame_number > 1) {
716 changed = avci->initial_format != frame->format;
718 switch(avctx->codec_type) {
719 case AVMEDIA_TYPE_VIDEO:
720 changed |= avci->initial_width != frame->width ||
721 avci->initial_height != frame->height;
723 case AVMEDIA_TYPE_AUDIO:
724 changed |= avci->initial_sample_rate != frame->sample_rate ||
725 avci->initial_sample_rate != avctx->sample_rate ||
726 avci->initial_channels != frame->channels ||
727 avci->initial_channel_layout != frame->channel_layout;
732 avci->changed_frames_dropped++;
733 av_log(avctx, AV_LOG_INFO, "dropped changed frame #%d pts %"PRId64
734 " drop count: %d \n",
735 avctx->frame_number, frame->pts,
736 avci->changed_frames_dropped);
737 av_frame_unref(frame);
738 return AVERROR_INPUT_CHANGED;
745 static int compat_decode(AVCodecContext *avctx, AVFrame *frame,
746 int *got_frame, const AVPacket *pkt)
748 AVCodecInternal *avci = avctx->internal;
751 av_assert0(avci->compat_decode_consumed == 0);
753 if (avci->draining_done && pkt && pkt->size != 0) {
754 av_log(avctx, AV_LOG_WARNING, "Got unexpected packet after EOF\n");
755 avcodec_flush_buffers(avctx);
760 if (avci->compat_decode_partial_size > 0 &&
761 avci->compat_decode_partial_size != pkt->size) {
762 av_log(avctx, AV_LOG_ERROR,
763 "Got unexpected packet size after a partial decode\n");
764 ret = AVERROR(EINVAL);
768 if (!avci->compat_decode_partial_size) {
769 ret = avcodec_send_packet(avctx, pkt);
770 if (ret == AVERROR_EOF)
772 else if (ret == AVERROR(EAGAIN)) {
773 /* we fully drain all the output in each decode call, so this should not
782 ret = avcodec_receive_frame(avctx, frame);
784 if (ret == AVERROR(EAGAIN) || ret == AVERROR_EOF)
789 if (frame != avci->compat_decode_frame) {
790 if (!avctx->refcounted_frames) {
791 ret = unrefcount_frame(avci, frame);
797 frame = avci->compat_decode_frame;
799 if (!avci->compat_decode_warned) {
800 av_log(avctx, AV_LOG_WARNING, "The deprecated avcodec_decode_* "
801 "API cannot return all the frames for this decoder. "
802 "Some frames will be dropped. Update your code to the "
803 "new decoding API to fix this.\n");
804 avci->compat_decode_warned = 1;
808 if (avci->draining || (!avctx->codec->bsfs && avci->compat_decode_consumed < pkt->size))
814 /* if there are any bsfs then assume full packet is always consumed */
815 if (avctx->codec->bsfs)
818 ret = FFMIN(avci->compat_decode_consumed, pkt->size);
820 avci->compat_decode_consumed = 0;
821 avci->compat_decode_partial_size = (ret >= 0) ? pkt->size - ret : 0;
826 int attribute_align_arg avcodec_decode_video2(AVCodecContext *avctx, AVFrame *picture,
827 int *got_picture_ptr,
828 const AVPacket *avpkt)
830 return compat_decode(avctx, picture, got_picture_ptr, avpkt);
833 int attribute_align_arg avcodec_decode_audio4(AVCodecContext *avctx,
836 const AVPacket *avpkt)
838 return compat_decode(avctx, frame, got_frame_ptr, avpkt);
841 static void get_subtitle_defaults(AVSubtitle *sub)
843 memset(sub, 0, sizeof(*sub));
844 sub->pts = AV_NOPTS_VALUE;
847 #define UTF8_MAX_BYTES 4 /* 5 and 6 bytes sequences should not be used */
848 static int recode_subtitle(AVCodecContext *avctx,
849 AVPacket *outpkt, const AVPacket *inpkt)
852 iconv_t cd = (iconv_t)-1;
859 if (avctx->sub_charenc_mode != FF_SUB_CHARENC_MODE_PRE_DECODER || inpkt->size == 0)
863 cd = iconv_open("UTF-8", avctx->sub_charenc);
864 av_assert0(cd != (iconv_t)-1);
869 if (inl >= INT_MAX / UTF8_MAX_BYTES - AV_INPUT_BUFFER_PADDING_SIZE) {
870 av_log(avctx, AV_LOG_ERROR, "Subtitles packet is too big for recoding\n");
871 ret = AVERROR(ENOMEM);
875 ret = av_new_packet(&tmp, inl * UTF8_MAX_BYTES);
878 outpkt->buf = tmp.buf;
879 outpkt->data = tmp.data;
880 outpkt->size = tmp.size;
884 if (iconv(cd, &inb, &inl, &outb, &outl) == (size_t)-1 ||
885 iconv(cd, NULL, NULL, &outb, &outl) == (size_t)-1 ||
886 outl >= outpkt->size || inl != 0) {
887 ret = FFMIN(AVERROR(errno), -1);
888 av_log(avctx, AV_LOG_ERROR, "Unable to recode subtitle event \"%s\" "
889 "from %s to UTF-8\n", inpkt->data, avctx->sub_charenc);
890 av_packet_unref(&tmp);
893 outpkt->size -= outl;
894 memset(outpkt->data + outpkt->size, 0, outl);
897 if (cd != (iconv_t)-1)
901 av_log(avctx, AV_LOG_ERROR, "requesting subtitles recoding without iconv");
902 return AVERROR(EINVAL);
906 static int utf8_check(const uint8_t *str)
909 uint32_t codepoint, min;
913 GET_UTF8(codepoint, *(byte++), return 0;);
914 min = byte - str == 1 ? 0 : byte - str == 2 ? 0x80 :
915 1 << (5 * (byte - str) - 4);
916 if (codepoint < min || codepoint >= 0x110000 ||
917 codepoint == 0xFFFE /* BOM */ ||
918 codepoint >= 0xD800 && codepoint <= 0xDFFF /* surrogates */)
925 #if FF_API_ASS_TIMING
926 static void insert_ts(AVBPrint *buf, int ts)
929 av_bprintf(buf, "9:59:59.99,");
933 h = ts/360000; ts -= 360000*h;
934 m = ts/ 6000; ts -= 6000*m;
935 s = ts/ 100; ts -= 100*s;
936 av_bprintf(buf, "%d:%02d:%02d.%02d,", h, m, s, ts);
940 static int convert_sub_to_old_ass_form(AVSubtitle *sub, const AVPacket *pkt, AVRational tb)
945 av_bprint_init(&buf, 0, AV_BPRINT_SIZE_UNLIMITED);
947 for (i = 0; i < sub->num_rects; i++) {
950 AVSubtitleRect *rect = sub->rects[i];
951 int ts_start, ts_duration = -1;
954 if (rect->type != SUBTITLE_ASS || !strncmp(rect->ass, "Dialogue: ", 10))
957 av_bprint_clear(&buf);
960 dialog = strchr(rect->ass, ',');
965 /* extract Layer or Marked */
966 layer = strtol(dialog, (char**)&dialog, 10);
971 /* rescale timing to ASS time base (ms) */
972 ts_start = av_rescale_q(pkt->pts, tb, av_make_q(1, 100));
973 if (pkt->duration != -1)
974 ts_duration = av_rescale_q(pkt->duration, tb, av_make_q(1, 100));
975 sub->end_display_time = FFMAX(sub->end_display_time, 10 * ts_duration);
977 /* construct ASS (standalone file form with timestamps) string */
978 av_bprintf(&buf, "Dialogue: %ld,", layer);
979 insert_ts(&buf, ts_start);
980 insert_ts(&buf, ts_duration == -1 ? -1 : ts_start + ts_duration);
981 av_bprintf(&buf, "%s\r\n", dialog);
983 final_dialog = av_strdup(buf.str);
984 if (!av_bprint_is_complete(&buf) || !final_dialog) {
985 av_freep(&final_dialog);
986 av_bprint_finalize(&buf, NULL);
987 return AVERROR(ENOMEM);
989 av_freep(&rect->ass);
990 rect->ass = final_dialog;
993 av_bprint_finalize(&buf, NULL);
998 int avcodec_decode_subtitle2(AVCodecContext *avctx, AVSubtitle *sub,
1004 if (!avpkt->data && avpkt->size) {
1005 av_log(avctx, AV_LOG_ERROR, "invalid packet: NULL data, size != 0\n");
1006 return AVERROR(EINVAL);
1009 return AVERROR(EINVAL);
1010 if (avctx->codec->type != AVMEDIA_TYPE_SUBTITLE) {
1011 av_log(avctx, AV_LOG_ERROR, "Invalid media type for subtitles\n");
1012 return AVERROR(EINVAL);
1016 get_subtitle_defaults(sub);
1018 if ((avctx->codec->capabilities & AV_CODEC_CAP_DELAY) || avpkt->size) {
1019 AVPacket pkt_recoded = *avpkt;
1021 ret = recode_subtitle(avctx, &pkt_recoded, avpkt);
1025 ret = extract_packet_props(avctx->internal, &pkt_recoded);
1029 if (avctx->pkt_timebase.num && avpkt->pts != AV_NOPTS_VALUE)
1030 sub->pts = av_rescale_q(avpkt->pts,
1031 avctx->pkt_timebase, AV_TIME_BASE_Q);
1032 ret = avctx->codec->decode(avctx, sub, got_sub_ptr, &pkt_recoded);
1033 av_assert1((ret >= 0) >= !!*got_sub_ptr &&
1034 !!*got_sub_ptr >= !!sub->num_rects);
1036 #if FF_API_ASS_TIMING
1037 if (avctx->sub_text_format == FF_SUB_TEXT_FMT_ASS_WITH_TIMINGS
1038 && *got_sub_ptr && sub->num_rects) {
1039 const AVRational tb = avctx->pkt_timebase.num ? avctx->pkt_timebase
1041 int err = convert_sub_to_old_ass_form(sub, avpkt, tb);
1047 if (sub->num_rects && !sub->end_display_time && avpkt->duration &&
1048 avctx->pkt_timebase.num) {
1049 AVRational ms = { 1, 1000 };
1050 sub->end_display_time = av_rescale_q(avpkt->duration,
1051 avctx->pkt_timebase, ms);
1054 if (avctx->codec_descriptor->props & AV_CODEC_PROP_BITMAP_SUB)
1056 else if (avctx->codec_descriptor->props & AV_CODEC_PROP_TEXT_SUB)
1059 for (i = 0; i < sub->num_rects; i++) {
1060 if (avctx->sub_charenc_mode != FF_SUB_CHARENC_MODE_IGNORE &&
1061 sub->rects[i]->ass && !utf8_check(sub->rects[i]->ass)) {
1062 av_log(avctx, AV_LOG_ERROR,
1063 "Invalid UTF-8 in decoded subtitles text; "
1064 "maybe missing -sub_charenc option\n");
1065 avsubtitle_free(sub);
1066 ret = AVERROR_INVALIDDATA;
1071 if (avpkt->data != pkt_recoded.data) { // did we recode?
1072 /* prevent from destroying side data from original packet */
1073 pkt_recoded.side_data = NULL;
1074 pkt_recoded.side_data_elems = 0;
1076 av_packet_unref(&pkt_recoded);
1081 avctx->frame_number++;
1087 enum AVPixelFormat avcodec_default_get_format(struct AVCodecContext *avctx,
1088 const enum AVPixelFormat *fmt)
1090 const AVPixFmtDescriptor *desc;
1091 const AVCodecHWConfig *config;
1094 // If a device was supplied when the codec was opened, assume that the
1095 // user wants to use it.
1096 if (avctx->hw_device_ctx && avctx->codec->hw_configs) {
1097 AVHWDeviceContext *device_ctx =
1098 (AVHWDeviceContext*)avctx->hw_device_ctx->data;
1100 config = &avctx->codec->hw_configs[i]->public;
1103 if (!(config->methods &
1104 AV_CODEC_HW_CONFIG_METHOD_HW_DEVICE_CTX))
1106 if (device_ctx->type != config->device_type)
1108 for (n = 0; fmt[n] != AV_PIX_FMT_NONE; n++) {
1109 if (config->pix_fmt == fmt[n])
1114 // No device or other setup, so we have to choose from things which
1115 // don't any other external information.
1117 // If the last element of the list is a software format, choose it
1118 // (this should be best software format if any exist).
1119 for (n = 0; fmt[n] != AV_PIX_FMT_NONE; n++);
1120 desc = av_pix_fmt_desc_get(fmt[n - 1]);
1121 if (!(desc->flags & AV_PIX_FMT_FLAG_HWACCEL))
1124 // Finally, traverse the list in order and choose the first entry
1125 // with no external dependencies (if there is no hardware configuration
1126 // information available then this just picks the first entry).
1127 for (n = 0; fmt[n] != AV_PIX_FMT_NONE; n++) {
1129 config = avcodec_get_hw_config(avctx->codec, i);
1132 if (config->pix_fmt == fmt[n])
1136 // No specific config available, so the decoder must be able
1137 // to handle this format without any additional setup.
1140 if (config->methods & AV_CODEC_HW_CONFIG_METHOD_INTERNAL) {
1141 // Usable with only internal setup.
1146 // Nothing is usable, give up.
1147 return AV_PIX_FMT_NONE;
1150 int ff_decode_get_hw_frames_ctx(AVCodecContext *avctx,
1151 enum AVHWDeviceType dev_type)
1153 AVHWDeviceContext *device_ctx;
1154 AVHWFramesContext *frames_ctx;
1157 if (!avctx->hwaccel)
1158 return AVERROR(ENOSYS);
1160 if (avctx->hw_frames_ctx)
1162 if (!avctx->hw_device_ctx) {
1163 av_log(avctx, AV_LOG_ERROR, "A hardware frames or device context is "
1164 "required for hardware accelerated decoding.\n");
1165 return AVERROR(EINVAL);
1168 device_ctx = (AVHWDeviceContext *)avctx->hw_device_ctx->data;
1169 if (device_ctx->type != dev_type) {
1170 av_log(avctx, AV_LOG_ERROR, "Device type %s expected for hardware "
1171 "decoding, but got %s.\n", av_hwdevice_get_type_name(dev_type),
1172 av_hwdevice_get_type_name(device_ctx->type));
1173 return AVERROR(EINVAL);
1176 ret = avcodec_get_hw_frames_parameters(avctx,
1177 avctx->hw_device_ctx,
1178 avctx->hwaccel->pix_fmt,
1179 &avctx->hw_frames_ctx);
1183 frames_ctx = (AVHWFramesContext*)avctx->hw_frames_ctx->data;
1186 if (frames_ctx->initial_pool_size) {
1187 // We guarantee 4 base work surfaces. The function above guarantees 1
1188 // (the absolute minimum), so add the missing count.
1189 frames_ctx->initial_pool_size += 3;
1192 ret = av_hwframe_ctx_init(avctx->hw_frames_ctx);
1194 av_buffer_unref(&avctx->hw_frames_ctx);
1201 int avcodec_get_hw_frames_parameters(AVCodecContext *avctx,
1202 AVBufferRef *device_ref,
1203 enum AVPixelFormat hw_pix_fmt,
1204 AVBufferRef **out_frames_ref)
1206 AVBufferRef *frames_ref = NULL;
1207 const AVCodecHWConfigInternal *hw_config;
1208 const AVHWAccel *hwa;
1212 hw_config = avctx->codec->hw_configs[i];
1214 return AVERROR(ENOENT);
1215 if (hw_config->public.pix_fmt == hw_pix_fmt)
1219 hwa = hw_config->hwaccel;
1220 if (!hwa || !hwa->frame_params)
1221 return AVERROR(ENOENT);
1223 frames_ref = av_hwframe_ctx_alloc(device_ref);
1225 return AVERROR(ENOMEM);
1227 ret = hwa->frame_params(avctx, frames_ref);
1229 AVHWFramesContext *frames_ctx = (AVHWFramesContext*)frames_ref->data;
1231 if (frames_ctx->initial_pool_size) {
1232 // If the user has requested that extra output surfaces be
1233 // available then add them here.
1234 if (avctx->extra_hw_frames > 0)
1235 frames_ctx->initial_pool_size += avctx->extra_hw_frames;
1237 // If frame threading is enabled then an extra surface per thread
1238 // is also required.
1239 if (avctx->active_thread_type & FF_THREAD_FRAME)
1240 frames_ctx->initial_pool_size += avctx->thread_count;
1243 *out_frames_ref = frames_ref;
1245 av_buffer_unref(&frames_ref);
1250 static int hwaccel_init(AVCodecContext *avctx,
1251 const AVCodecHWConfigInternal *hw_config)
1253 const AVHWAccel *hwaccel;
1256 hwaccel = hw_config->hwaccel;
1257 if (hwaccel->capabilities & AV_HWACCEL_CODEC_CAP_EXPERIMENTAL &&
1258 avctx->strict_std_compliance > FF_COMPLIANCE_EXPERIMENTAL) {
1259 av_log(avctx, AV_LOG_WARNING, "Ignoring experimental hwaccel: %s\n",
1261 return AVERROR_PATCHWELCOME;
1264 if (hwaccel->priv_data_size) {
1265 avctx->internal->hwaccel_priv_data =
1266 av_mallocz(hwaccel->priv_data_size);
1267 if (!avctx->internal->hwaccel_priv_data)
1268 return AVERROR(ENOMEM);
1271 avctx->hwaccel = hwaccel;
1272 if (hwaccel->init) {
1273 err = hwaccel->init(avctx);
1275 av_log(avctx, AV_LOG_ERROR, "Failed setup for format %s: "
1276 "hwaccel initialisation returned error.\n",
1277 av_get_pix_fmt_name(hw_config->public.pix_fmt));
1278 av_freep(&avctx->internal->hwaccel_priv_data);
1279 avctx->hwaccel = NULL;
1287 static void hwaccel_uninit(AVCodecContext *avctx)
1289 if (avctx->hwaccel && avctx->hwaccel->uninit)
1290 avctx->hwaccel->uninit(avctx);
1292 av_freep(&avctx->internal->hwaccel_priv_data);
1294 avctx->hwaccel = NULL;
1296 av_buffer_unref(&avctx->hw_frames_ctx);
1299 int ff_get_format(AVCodecContext *avctx, const enum AVPixelFormat *fmt)
1301 const AVPixFmtDescriptor *desc;
1302 enum AVPixelFormat *choices;
1303 enum AVPixelFormat ret, user_choice;
1304 const AVCodecHWConfigInternal *hw_config;
1305 const AVCodecHWConfig *config;
1308 // Find end of list.
1309 for (n = 0; fmt[n] != AV_PIX_FMT_NONE; n++);
1310 // Must contain at least one entry.
1312 // If a software format is available, it must be the last entry.
1313 desc = av_pix_fmt_desc_get(fmt[n - 1]);
1314 if (desc->flags & AV_PIX_FMT_FLAG_HWACCEL) {
1315 // No software format is available.
1317 avctx->sw_pix_fmt = fmt[n - 1];
1320 choices = av_malloc_array(n + 1, sizeof(*choices));
1322 return AV_PIX_FMT_NONE;
1324 memcpy(choices, fmt, (n + 1) * sizeof(*choices));
1327 // Remove the previous hwaccel, if there was one.
1328 hwaccel_uninit(avctx);
1330 user_choice = avctx->get_format(avctx, choices);
1331 if (user_choice == AV_PIX_FMT_NONE) {
1332 // Explicitly chose nothing, give up.
1333 ret = AV_PIX_FMT_NONE;
1337 desc = av_pix_fmt_desc_get(user_choice);
1339 av_log(avctx, AV_LOG_ERROR, "Invalid format returned by "
1340 "get_format() callback.\n");
1341 ret = AV_PIX_FMT_NONE;
1344 av_log(avctx, AV_LOG_DEBUG, "Format %s chosen by get_format().\n",
1347 for (i = 0; i < n; i++) {
1348 if (choices[i] == user_choice)
1352 av_log(avctx, AV_LOG_ERROR, "Invalid return from get_format(): "
1353 "%s not in possible list.\n", desc->name);
1354 ret = AV_PIX_FMT_NONE;
1358 if (avctx->codec->hw_configs) {
1360 hw_config = avctx->codec->hw_configs[i];
1363 if (hw_config->public.pix_fmt == user_choice)
1371 // No config available, so no extra setup required.
1375 config = &hw_config->public;
1377 if (config->methods &
1378 AV_CODEC_HW_CONFIG_METHOD_HW_FRAMES_CTX &&
1379 avctx->hw_frames_ctx) {
1380 const AVHWFramesContext *frames_ctx =
1381 (AVHWFramesContext*)avctx->hw_frames_ctx->data;
1382 if (frames_ctx->format != user_choice) {
1383 av_log(avctx, AV_LOG_ERROR, "Invalid setup for format %s: "
1384 "does not match the format of the provided frames "
1385 "context.\n", desc->name);
1388 } else if (config->methods &
1389 AV_CODEC_HW_CONFIG_METHOD_HW_DEVICE_CTX &&
1390 avctx->hw_device_ctx) {
1391 const AVHWDeviceContext *device_ctx =
1392 (AVHWDeviceContext*)avctx->hw_device_ctx->data;
1393 if (device_ctx->type != config->device_type) {
1394 av_log(avctx, AV_LOG_ERROR, "Invalid setup for format %s: "
1395 "does not match the type of the provided device "
1396 "context.\n", desc->name);
1399 } else if (config->methods &
1400 AV_CODEC_HW_CONFIG_METHOD_INTERNAL) {
1401 // Internal-only setup, no additional configuration.
1402 } else if (config->methods &
1403 AV_CODEC_HW_CONFIG_METHOD_AD_HOC) {
1404 // Some ad-hoc configuration we can't see and can't check.
1406 av_log(avctx, AV_LOG_ERROR, "Invalid setup for format %s: "
1407 "missing configuration.\n", desc->name);
1410 if (hw_config->hwaccel) {
1411 av_log(avctx, AV_LOG_DEBUG, "Format %s requires hwaccel "
1412 "initialisation.\n", desc->name);
1413 err = hwaccel_init(avctx, hw_config);
1421 av_log(avctx, AV_LOG_DEBUG, "Format %s not usable, retrying "
1422 "get_format() without it.\n", desc->name);
1423 for (i = 0; i < n; i++) {
1424 if (choices[i] == user_choice)
1427 for (; i + 1 < n; i++)
1428 choices[i] = choices[i + 1];
1436 static void frame_pool_free(void *opaque, uint8_t *data)
1438 FramePool *pool = (FramePool*)data;
1441 for (i = 0; i < FF_ARRAY_ELEMS(pool->pools); i++)
1442 av_buffer_pool_uninit(&pool->pools[i]);
1447 static AVBufferRef *frame_pool_alloc(void)
1449 FramePool *pool = av_mallocz(sizeof(*pool));
1455 buf = av_buffer_create((uint8_t*)pool, sizeof(*pool),
1456 frame_pool_free, NULL, 0);
1465 static int update_frame_pool(AVCodecContext *avctx, AVFrame *frame)
1467 FramePool *pool = avctx->internal->pool ?
1468 (FramePool*)avctx->internal->pool->data : NULL;
1469 AVBufferRef *pool_buf;
1470 int i, ret, ch, planes;
1472 if (avctx->codec_type == AVMEDIA_TYPE_AUDIO) {
1473 int planar = av_sample_fmt_is_planar(frame->format);
1474 ch = frame->channels;
1475 planes = planar ? ch : 1;
1478 if (pool && pool->format == frame->format) {
1479 if (avctx->codec_type == AVMEDIA_TYPE_VIDEO &&
1480 pool->width == frame->width && pool->height == frame->height)
1482 if (avctx->codec_type == AVMEDIA_TYPE_AUDIO && pool->planes == planes &&
1483 pool->channels == ch && frame->nb_samples == pool->samples)
1487 pool_buf = frame_pool_alloc();
1489 return AVERROR(ENOMEM);
1490 pool = (FramePool*)pool_buf->data;
1492 switch (avctx->codec_type) {
1493 case AVMEDIA_TYPE_VIDEO: {
1495 int w = frame->width;
1496 int h = frame->height;
1498 ptrdiff_t linesize1[4];
1501 avcodec_align_dimensions2(avctx, &w, &h, pool->stride_align);
1504 // NOTE: do not align linesizes individually, this breaks e.g. assumptions
1505 // that linesize[0] == 2*linesize[1] in the MPEG-encoder for 4:2:2
1506 ret = av_image_fill_linesizes(linesize, avctx->pix_fmt, w);
1509 // increase alignment of w for next try (rhs gives the lowest bit set in w)
1513 for (i = 0; i < 4; i++)
1514 unaligned |= linesize[i] % pool->stride_align[i];
1515 } while (unaligned);
1517 for (i = 0; i < 4; i++)
1518 linesize1[i] = linesize[i];
1519 ret = av_image_fill_plane_sizes(size, avctx->pix_fmt, h, linesize1);
1523 for (i = 0; i < 4; i++) {
1524 pool->linesize[i] = linesize[i];
1526 if (size[i] > INT_MAX - (16 + STRIDE_ALIGN - 1)) {
1527 ret = AVERROR(EINVAL);
1530 pool->pools[i] = av_buffer_pool_init(size[i] + 16 + STRIDE_ALIGN - 1,
1531 CONFIG_MEMORY_POISONING ?
1534 if (!pool->pools[i]) {
1535 ret = AVERROR(ENOMEM);
1540 pool->format = frame->format;
1541 pool->width = frame->width;
1542 pool->height = frame->height;
1546 case AVMEDIA_TYPE_AUDIO: {
1547 ret = av_samples_get_buffer_size(&pool->linesize[0], ch,
1548 frame->nb_samples, frame->format, 0);
1552 pool->pools[0] = av_buffer_pool_init(pool->linesize[0], NULL);
1553 if (!pool->pools[0]) {
1554 ret = AVERROR(ENOMEM);
1558 pool->format = frame->format;
1559 pool->planes = planes;
1560 pool->channels = ch;
1561 pool->samples = frame->nb_samples;
1564 default: av_assert0(0);
1567 av_buffer_unref(&avctx->internal->pool);
1568 avctx->internal->pool = pool_buf;
1572 av_buffer_unref(&pool_buf);
1576 static int audio_get_buffer(AVCodecContext *avctx, AVFrame *frame)
1578 FramePool *pool = (FramePool*)avctx->internal->pool->data;
1579 int planes = pool->planes;
1582 frame->linesize[0] = pool->linesize[0];
1584 if (planes > AV_NUM_DATA_POINTERS) {
1585 frame->extended_data = av_mallocz_array(planes, sizeof(*frame->extended_data));
1586 frame->nb_extended_buf = planes - AV_NUM_DATA_POINTERS;
1587 frame->extended_buf = av_mallocz_array(frame->nb_extended_buf,
1588 sizeof(*frame->extended_buf));
1589 if (!frame->extended_data || !frame->extended_buf) {
1590 av_freep(&frame->extended_data);
1591 av_freep(&frame->extended_buf);
1592 return AVERROR(ENOMEM);
1595 frame->extended_data = frame->data;
1596 av_assert0(frame->nb_extended_buf == 0);
1599 for (i = 0; i < FFMIN(planes, AV_NUM_DATA_POINTERS); i++) {
1600 frame->buf[i] = av_buffer_pool_get(pool->pools[0]);
1603 frame->extended_data[i] = frame->data[i] = frame->buf[i]->data;
1605 for (i = 0; i < frame->nb_extended_buf; i++) {
1606 frame->extended_buf[i] = av_buffer_pool_get(pool->pools[0]);
1607 if (!frame->extended_buf[i])
1609 frame->extended_data[i + AV_NUM_DATA_POINTERS] = frame->extended_buf[i]->data;
1612 if (avctx->debug & FF_DEBUG_BUFFERS)
1613 av_log(avctx, AV_LOG_DEBUG, "default_get_buffer called on frame %p", frame);
1617 av_frame_unref(frame);
1618 return AVERROR(ENOMEM);
1621 static int video_get_buffer(AVCodecContext *s, AVFrame *pic)
1623 FramePool *pool = (FramePool*)s->internal->pool->data;
1624 const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(pic->format);
1627 if (pic->data[0] || pic->data[1] || pic->data[2] || pic->data[3]) {
1628 av_log(s, AV_LOG_ERROR, "pic->data[*]!=NULL in avcodec_default_get_buffer\n");
1633 av_log(s, AV_LOG_ERROR,
1634 "Unable to get pixel format descriptor for format %s\n",
1635 av_get_pix_fmt_name(pic->format));
1636 return AVERROR(EINVAL);
1639 memset(pic->data, 0, sizeof(pic->data));
1640 pic->extended_data = pic->data;
1642 for (i = 0; i < 4 && pool->pools[i]; i++) {
1643 pic->linesize[i] = pool->linesize[i];
1645 pic->buf[i] = av_buffer_pool_get(pool->pools[i]);
1649 pic->data[i] = pic->buf[i]->data;
1651 for (; i < AV_NUM_DATA_POINTERS; i++) {
1652 pic->data[i] = NULL;
1653 pic->linesize[i] = 0;
1655 if (desc->flags & AV_PIX_FMT_FLAG_PAL ||
1656 ((desc->flags & FF_PSEUDOPAL) && pic->data[1]))
1657 avpriv_set_systematic_pal2((uint32_t *)pic->data[1], pic->format);
1659 if (s->debug & FF_DEBUG_BUFFERS)
1660 av_log(s, AV_LOG_DEBUG, "default_get_buffer called on pic %p\n", pic);
1664 av_frame_unref(pic);
1665 return AVERROR(ENOMEM);
1668 int avcodec_default_get_buffer2(AVCodecContext *avctx, AVFrame *frame, int flags)
1672 if (avctx->hw_frames_ctx) {
1673 ret = av_hwframe_get_buffer(avctx->hw_frames_ctx, frame, 0);
1674 frame->width = avctx->coded_width;
1675 frame->height = avctx->coded_height;
1679 if ((ret = update_frame_pool(avctx, frame)) < 0)
1682 switch (avctx->codec_type) {
1683 case AVMEDIA_TYPE_VIDEO:
1684 return video_get_buffer(avctx, frame);
1685 case AVMEDIA_TYPE_AUDIO:
1686 return audio_get_buffer(avctx, frame);
1692 static int add_metadata_from_side_data(const AVPacket *avpkt, AVFrame *frame)
1695 const uint8_t *side_metadata;
1697 AVDictionary **frame_md = &frame->metadata;
1699 side_metadata = av_packet_get_side_data(avpkt,
1700 AV_PKT_DATA_STRINGS_METADATA, &size);
1701 return av_packet_unpack_dictionary(side_metadata, size, frame_md);
1704 int ff_decode_frame_props(AVCodecContext *avctx, AVFrame *frame)
1706 AVPacket *pkt = avctx->internal->last_pkt_props;
1708 static const struct {
1709 enum AVPacketSideDataType packet;
1710 enum AVFrameSideDataType frame;
1712 { AV_PKT_DATA_REPLAYGAIN , AV_FRAME_DATA_REPLAYGAIN },
1713 { AV_PKT_DATA_DISPLAYMATRIX, AV_FRAME_DATA_DISPLAYMATRIX },
1714 { AV_PKT_DATA_SPHERICAL, AV_FRAME_DATA_SPHERICAL },
1715 { AV_PKT_DATA_STEREO3D, AV_FRAME_DATA_STEREO3D },
1716 { AV_PKT_DATA_AUDIO_SERVICE_TYPE, AV_FRAME_DATA_AUDIO_SERVICE_TYPE },
1717 { AV_PKT_DATA_MASTERING_DISPLAY_METADATA, AV_FRAME_DATA_MASTERING_DISPLAY_METADATA },
1718 { AV_PKT_DATA_CONTENT_LIGHT_LEVEL, AV_FRAME_DATA_CONTENT_LIGHT_LEVEL },
1719 { AV_PKT_DATA_A53_CC, AV_FRAME_DATA_A53_CC },
1720 { AV_PKT_DATA_ICC_PROFILE, AV_FRAME_DATA_ICC_PROFILE },
1721 { AV_PKT_DATA_S12M_TIMECODE, AV_FRAME_DATA_S12M_TIMECODE },
1725 avpriv_packet_list_get(&avctx->internal->pkt_props,
1726 &avctx->internal->pkt_props_tail,
1730 frame->pts = pkt->pts;
1732 FF_DISABLE_DEPRECATION_WARNINGS
1733 frame->pkt_pts = pkt->pts;
1734 FF_ENABLE_DEPRECATION_WARNINGS
1736 frame->pkt_pos = pkt->pos;
1737 frame->pkt_duration = pkt->duration;
1738 frame->pkt_size = pkt->size;
1740 for (i = 0; i < FF_ARRAY_ELEMS(sd); i++) {
1742 uint8_t *packet_sd = av_packet_get_side_data(pkt, sd[i].packet, &size);
1744 AVFrameSideData *frame_sd = av_frame_new_side_data(frame,
1748 return AVERROR(ENOMEM);
1750 memcpy(frame_sd->data, packet_sd, size);
1753 add_metadata_from_side_data(pkt, frame);
1755 if (pkt->flags & AV_PKT_FLAG_DISCARD) {
1756 frame->flags |= AV_FRAME_FLAG_DISCARD;
1758 frame->flags = (frame->flags & ~AV_FRAME_FLAG_DISCARD);
1761 frame->reordered_opaque = avctx->reordered_opaque;
1763 if (frame->color_primaries == AVCOL_PRI_UNSPECIFIED)
1764 frame->color_primaries = avctx->color_primaries;
1765 if (frame->color_trc == AVCOL_TRC_UNSPECIFIED)
1766 frame->color_trc = avctx->color_trc;
1767 if (frame->colorspace == AVCOL_SPC_UNSPECIFIED)
1768 frame->colorspace = avctx->colorspace;
1769 if (frame->color_range == AVCOL_RANGE_UNSPECIFIED)
1770 frame->color_range = avctx->color_range;
1771 if (frame->chroma_location == AVCHROMA_LOC_UNSPECIFIED)
1772 frame->chroma_location = avctx->chroma_sample_location;
1774 switch (avctx->codec->type) {
1775 case AVMEDIA_TYPE_VIDEO:
1776 frame->format = avctx->pix_fmt;
1777 if (!frame->sample_aspect_ratio.num)
1778 frame->sample_aspect_ratio = avctx->sample_aspect_ratio;
1780 if (frame->width && frame->height &&
1781 av_image_check_sar(frame->width, frame->height,
1782 frame->sample_aspect_ratio) < 0) {
1783 av_log(avctx, AV_LOG_WARNING, "ignoring invalid SAR: %u/%u\n",
1784 frame->sample_aspect_ratio.num,
1785 frame->sample_aspect_ratio.den);
1786 frame->sample_aspect_ratio = (AVRational){ 0, 1 };
1790 case AVMEDIA_TYPE_AUDIO:
1791 if (!frame->sample_rate)
1792 frame->sample_rate = avctx->sample_rate;
1793 if (frame->format < 0)
1794 frame->format = avctx->sample_fmt;
1795 if (!frame->channel_layout) {
1796 if (avctx->channel_layout) {
1797 if (av_get_channel_layout_nb_channels(avctx->channel_layout) !=
1799 av_log(avctx, AV_LOG_ERROR, "Inconsistent channel "
1800 "configuration.\n");
1801 return AVERROR(EINVAL);
1804 frame->channel_layout = avctx->channel_layout;
1806 if (avctx->channels > FF_SANE_NB_CHANNELS) {
1807 av_log(avctx, AV_LOG_ERROR, "Too many channels: %d.\n",
1809 return AVERROR(ENOSYS);
1813 frame->channels = avctx->channels;
1819 static void validate_avframe_allocation(AVCodecContext *avctx, AVFrame *frame)
1821 if (avctx->codec_type == AVMEDIA_TYPE_VIDEO) {
1823 int num_planes = av_pix_fmt_count_planes(frame->format);
1824 const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(frame->format);
1825 int flags = desc ? desc->flags : 0;
1826 if (num_planes == 1 && (flags & AV_PIX_FMT_FLAG_PAL))
1828 if ((flags & FF_PSEUDOPAL) && frame->data[1])
1830 for (i = 0; i < num_planes; i++) {
1831 av_assert0(frame->data[i]);
1833 // For formats without data like hwaccel allow unused pointers to be non-NULL.
1834 for (i = num_planes; num_planes > 0 && i < FF_ARRAY_ELEMS(frame->data); i++) {
1836 av_log(avctx, AV_LOG_ERROR, "Buffer returned by get_buffer2() did not zero unused plane pointers\n");
1837 frame->data[i] = NULL;
1842 static void decode_data_free(void *opaque, uint8_t *data)
1844 FrameDecodeData *fdd = (FrameDecodeData*)data;
1846 if (fdd->post_process_opaque_free)
1847 fdd->post_process_opaque_free(fdd->post_process_opaque);
1849 if (fdd->hwaccel_priv_free)
1850 fdd->hwaccel_priv_free(fdd->hwaccel_priv);
1855 int ff_attach_decode_data(AVFrame *frame)
1857 AVBufferRef *fdd_buf;
1858 FrameDecodeData *fdd;
1860 av_assert1(!frame->private_ref);
1861 av_buffer_unref(&frame->private_ref);
1863 fdd = av_mallocz(sizeof(*fdd));
1865 return AVERROR(ENOMEM);
1867 fdd_buf = av_buffer_create((uint8_t*)fdd, sizeof(*fdd), decode_data_free,
1868 NULL, AV_BUFFER_FLAG_READONLY);
1871 return AVERROR(ENOMEM);
1874 frame->private_ref = fdd_buf;
1879 int ff_get_buffer(AVCodecContext *avctx, AVFrame *frame, int flags)
1881 const AVHWAccel *hwaccel = avctx->hwaccel;
1882 int override_dimensions = 1;
1885 if (avctx->codec_type == AVMEDIA_TYPE_VIDEO) {
1886 if ((unsigned)avctx->width > INT_MAX - STRIDE_ALIGN ||
1887 (ret = av_image_check_size2(FFALIGN(avctx->width, STRIDE_ALIGN), avctx->height, avctx->max_pixels, AV_PIX_FMT_NONE, 0, avctx)) < 0 || avctx->pix_fmt<0) {
1888 av_log(avctx, AV_LOG_ERROR, "video_get_buffer: image parameters invalid\n");
1889 ret = AVERROR(EINVAL);
1893 if (frame->width <= 0 || frame->height <= 0) {
1894 frame->width = FFMAX(avctx->width, AV_CEIL_RSHIFT(avctx->coded_width, avctx->lowres));
1895 frame->height = FFMAX(avctx->height, AV_CEIL_RSHIFT(avctx->coded_height, avctx->lowres));
1896 override_dimensions = 0;
1899 if (frame->data[0] || frame->data[1] || frame->data[2] || frame->data[3]) {
1900 av_log(avctx, AV_LOG_ERROR, "pic->data[*]!=NULL in get_buffer_internal\n");
1901 ret = AVERROR(EINVAL);
1904 } else if (avctx->codec_type == AVMEDIA_TYPE_AUDIO) {
1905 if (frame->nb_samples * (int64_t)avctx->channels > avctx->max_samples) {
1906 av_log(avctx, AV_LOG_ERROR, "samples per frame %d, exceeds max_samples %"PRId64"\n", frame->nb_samples, avctx->max_samples);
1907 ret = AVERROR(EINVAL);
1911 ret = ff_decode_frame_props(avctx, frame);
1916 if (hwaccel->alloc_frame) {
1917 ret = hwaccel->alloc_frame(avctx, frame);
1921 avctx->sw_pix_fmt = avctx->pix_fmt;
1923 ret = avctx->get_buffer2(avctx, frame, flags);
1927 validate_avframe_allocation(avctx, frame);
1929 ret = ff_attach_decode_data(frame);
1934 if (avctx->codec_type == AVMEDIA_TYPE_VIDEO && !override_dimensions &&
1935 !(avctx->codec->caps_internal & FF_CODEC_CAP_EXPORTS_CROPPING)) {
1936 frame->width = avctx->width;
1937 frame->height = avctx->height;
1942 av_log(avctx, AV_LOG_ERROR, "get_buffer() failed\n");
1943 av_frame_unref(frame);
1949 static int reget_buffer_internal(AVCodecContext *avctx, AVFrame *frame, int flags)
1954 av_assert0(avctx->codec_type == AVMEDIA_TYPE_VIDEO);
1956 if (frame->data[0] && (frame->width != avctx->width || frame->height != avctx->height || frame->format != avctx->pix_fmt)) {
1957 av_log(avctx, AV_LOG_WARNING, "Picture changed from size:%dx%d fmt:%s to size:%dx%d fmt:%s in reget buffer()\n",
1958 frame->width, frame->height, av_get_pix_fmt_name(frame->format), avctx->width, avctx->height, av_get_pix_fmt_name(avctx->pix_fmt));
1959 av_frame_unref(frame);
1962 if (!frame->data[0])
1963 return ff_get_buffer(avctx, frame, AV_GET_BUFFER_FLAG_REF);
1965 if ((flags & FF_REGET_BUFFER_FLAG_READONLY) || av_frame_is_writable(frame))
1966 return ff_decode_frame_props(avctx, frame);
1968 tmp = av_frame_alloc();
1970 return AVERROR(ENOMEM);
1972 av_frame_move_ref(tmp, frame);
1974 ret = ff_get_buffer(avctx, frame, AV_GET_BUFFER_FLAG_REF);
1976 av_frame_free(&tmp);
1980 av_frame_copy(frame, tmp);
1981 av_frame_free(&tmp);
1986 int ff_reget_buffer(AVCodecContext *avctx, AVFrame *frame, int flags)
1988 int ret = reget_buffer_internal(avctx, frame, flags);
1990 av_log(avctx, AV_LOG_ERROR, "reget_buffer() failed\n");