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"
41 #include "bytestream.h"
47 static int apply_param_change(AVCodecContext *avctx, const AVPacket *avpkt)
54 data = av_packet_get_side_data(avpkt, AV_PKT_DATA_PARAM_CHANGE, &size);
58 if (!(avctx->codec->capabilities & AV_CODEC_CAP_PARAM_CHANGE)) {
59 av_log(avctx, AV_LOG_ERROR, "This decoder does not support parameter "
60 "changes, but PARAM_CHANGE side data was sent to it.\n");
61 ret = AVERROR(EINVAL);
68 flags = bytestream_get_le32(&data);
71 if (flags & AV_SIDE_DATA_PARAM_CHANGE_CHANNEL_COUNT) {
74 val = bytestream_get_le32(&data);
75 if (val <= 0 || val > INT_MAX) {
76 av_log(avctx, AV_LOG_ERROR, "Invalid channel count");
77 ret = AVERROR_INVALIDDATA;
80 avctx->channels = val;
83 if (flags & AV_SIDE_DATA_PARAM_CHANGE_CHANNEL_LAYOUT) {
86 avctx->channel_layout = bytestream_get_le64(&data);
89 if (flags & AV_SIDE_DATA_PARAM_CHANGE_SAMPLE_RATE) {
92 val = bytestream_get_le32(&data);
93 if (val <= 0 || val > INT_MAX) {
94 av_log(avctx, AV_LOG_ERROR, "Invalid sample rate");
95 ret = AVERROR_INVALIDDATA;
98 avctx->sample_rate = val;
101 if (flags & AV_SIDE_DATA_PARAM_CHANGE_DIMENSIONS) {
104 avctx->width = bytestream_get_le32(&data);
105 avctx->height = bytestream_get_le32(&data);
107 ret = ff_set_dimensions(avctx, avctx->width, avctx->height);
114 av_log(avctx, AV_LOG_ERROR, "PARAM_CHANGE side data too small.\n");
115 ret = AVERROR_INVALIDDATA;
118 av_log(avctx, AV_LOG_ERROR, "Error applying parameter changes.\n");
119 if (avctx->err_recognition & AV_EF_EXPLODE)
125 static int extract_packet_props(AVCodecInternal *avci, const AVPacket *pkt)
129 av_packet_unref(avci->last_pkt_props);
131 ret = av_packet_copy_props(avci->last_pkt_props, pkt);
133 avci->last_pkt_props->size = pkt->size; // HACK: Needed for ff_init_buffer_info().
138 static int unrefcount_frame(AVCodecInternal *avci, AVFrame *frame)
142 /* move the original frame to our backup */
143 av_frame_unref(avci->to_free);
144 av_frame_move_ref(avci->to_free, frame);
146 /* now copy everything except the AVBufferRefs back
147 * note that we make a COPY of the side data, so calling av_frame_free() on
148 * the caller's frame will work properly */
149 ret = av_frame_copy_props(frame, avci->to_free);
153 memcpy(frame->data, avci->to_free->data, sizeof(frame->data));
154 memcpy(frame->linesize, avci->to_free->linesize, sizeof(frame->linesize));
155 if (avci->to_free->extended_data != avci->to_free->data) {
156 int planes = avci->to_free->channels;
157 int size = planes * sizeof(*frame->extended_data);
160 av_frame_unref(frame);
164 frame->extended_data = av_malloc(size);
165 if (!frame->extended_data) {
166 av_frame_unref(frame);
167 return AVERROR(ENOMEM);
169 memcpy(frame->extended_data, avci->to_free->extended_data,
172 frame->extended_data = frame->data;
174 frame->format = avci->to_free->format;
175 frame->width = avci->to_free->width;
176 frame->height = avci->to_free->height;
177 frame->channel_layout = avci->to_free->channel_layout;
178 frame->nb_samples = avci->to_free->nb_samples;
179 frame->channels = avci->to_free->channels;
184 static int bsfs_init(AVCodecContext *avctx)
186 AVCodecInternal *avci = avctx->internal;
187 DecodeFilterContext *s = &avci->filter;
188 const char *bsfs_str;
194 bsfs_str = avctx->codec->bsfs ? avctx->codec->bsfs : "null";
195 while (bsfs_str && *bsfs_str) {
197 const AVBitStreamFilter *filter;
200 bsf = av_get_token(&bsfs_str, ",");
202 ret = AVERROR(ENOMEM);
206 filter = av_bsf_get_by_name(bsf);
208 av_log(avctx, AV_LOG_ERROR, "A non-existing bitstream filter %s "
209 "requested by a decoder. This is a bug, please report it.\n",
217 tmp = av_realloc_array(s->bsfs, s->nb_bsfs + 1, sizeof(*s->bsfs));
219 ret = AVERROR(ENOMEM);
225 ret = av_bsf_alloc(filter, &s->bsfs[s->nb_bsfs - 1]);
229 if (s->nb_bsfs == 1) {
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 s->bsfs[s->nb_bsfs - 1]->time_base_in = (AVRational){ 1, 90000 };
234 ret = avcodec_parameters_from_context(s->bsfs[s->nb_bsfs - 1]->par_in,
237 s->bsfs[s->nb_bsfs - 1]->time_base_in = s->bsfs[s->nb_bsfs - 2]->time_base_out;
238 ret = avcodec_parameters_copy(s->bsfs[s->nb_bsfs - 1]->par_in,
239 s->bsfs[s->nb_bsfs - 2]->par_out);
244 ret = av_bsf_init(s->bsfs[s->nb_bsfs - 1]);
251 ff_decode_bsfs_uninit(avctx);
255 /* try to get one output packet from the filter chain */
256 static int bsfs_poll(AVCodecContext *avctx, AVPacket *pkt)
258 DecodeFilterContext *s = &avctx->internal->filter;
261 /* start with the last filter in the chain */
262 idx = s->nb_bsfs - 1;
264 /* request a packet from the currently selected filter */
265 ret = av_bsf_receive_packet(s->bsfs[idx], pkt);
266 if (ret == AVERROR(EAGAIN)) {
267 /* no packets available, try the next filter up the chain */
271 } else if (ret < 0 && ret != AVERROR_EOF) {
275 /* got a packet or EOF -- pass it to the caller or to the next filter
277 if (idx == s->nb_bsfs - 1) {
281 ret = av_bsf_send_packet(s->bsfs[idx], ret < 0 ? NULL : pkt);
283 av_log(avctx, AV_LOG_ERROR,
284 "Error pre-processing a packet before decoding\n");
285 av_packet_unref(pkt);
291 return AVERROR(EAGAIN);
294 int ff_decode_get_packet(AVCodecContext *avctx, AVPacket *pkt)
296 AVCodecInternal *avci = avctx->internal;
302 ret = bsfs_poll(avctx, pkt);
303 if (ret == AVERROR_EOF)
308 ret = extract_packet_props(avctx->internal, pkt);
312 ret = apply_param_change(avctx, pkt);
316 if (avctx->codec->receive_frame)
317 avci->compat_decode_consumed += pkt->size;
321 av_packet_unref(pkt);
326 * Attempt to guess proper monotonic timestamps for decoded video frames
327 * which might have incorrect times. Input timestamps may wrap around, in
328 * which case the output will as well.
330 * @param pts the pts field of the decoded AVPacket, as passed through
332 * @param dts the dts field of the decoded AVPacket
333 * @return one of the input values, may be AV_NOPTS_VALUE
335 static int64_t guess_correct_pts(AVCodecContext *ctx,
336 int64_t reordered_pts, int64_t dts)
338 int64_t pts = AV_NOPTS_VALUE;
340 if (dts != AV_NOPTS_VALUE) {
341 ctx->pts_correction_num_faulty_dts += dts <= ctx->pts_correction_last_dts;
342 ctx->pts_correction_last_dts = dts;
343 } else if (reordered_pts != AV_NOPTS_VALUE)
344 ctx->pts_correction_last_dts = reordered_pts;
346 if (reordered_pts != AV_NOPTS_VALUE) {
347 ctx->pts_correction_num_faulty_pts += reordered_pts <= ctx->pts_correction_last_pts;
348 ctx->pts_correction_last_pts = reordered_pts;
349 } else if(dts != AV_NOPTS_VALUE)
350 ctx->pts_correction_last_pts = dts;
352 if ((ctx->pts_correction_num_faulty_pts<=ctx->pts_correction_num_faulty_dts || dts == AV_NOPTS_VALUE)
353 && reordered_pts != AV_NOPTS_VALUE)
362 * The core of the receive_frame_wrapper for the decoders implementing
363 * the simple API. Certain decoders might consume partial packets without
364 * returning any output, so this function needs to be called in a loop until it
367 static int decode_simple_internal(AVCodecContext *avctx, AVFrame *frame)
369 AVCodecInternal *avci = avctx->internal;
370 DecodeSimpleContext *ds = &avci->ds;
371 AVPacket *pkt = ds->in_pkt;
372 // copy to ensure we do not change pkt
373 int got_frame, actual_got_frame;
376 if (!pkt->data && !avci->draining) {
377 av_packet_unref(pkt);
378 ret = ff_decode_get_packet(avctx, pkt);
379 if (ret < 0 && ret != AVERROR_EOF)
383 // Some codecs (at least wma lossless) will crash when feeding drain packets
384 // after EOF was signaled.
385 if (avci->draining_done)
389 !(avctx->codec->capabilities & AV_CODEC_CAP_DELAY ||
390 avctx->active_thread_type & FF_THREAD_FRAME))
395 if (HAVE_THREADS && avctx->active_thread_type & FF_THREAD_FRAME) {
396 ret = ff_thread_decode_frame(avctx, frame, &got_frame, pkt);
398 ret = avctx->codec->decode(avctx, frame, &got_frame, pkt);
400 if (!(avctx->codec->caps_internal & FF_CODEC_CAP_SETS_PKT_DTS))
401 frame->pkt_dts = pkt->dts;
402 if (avctx->codec->type == AVMEDIA_TYPE_VIDEO) {
403 if(!avctx->has_b_frames)
404 frame->pkt_pos = pkt->pos;
405 //FIXME these should be under if(!avctx->has_b_frames)
406 /* get_buffer is supposed to set frame parameters */
407 if (!(avctx->codec->capabilities & AV_CODEC_CAP_DR1)) {
408 if (!frame->sample_aspect_ratio.num) frame->sample_aspect_ratio = avctx->sample_aspect_ratio;
409 if (!frame->width) frame->width = avctx->width;
410 if (!frame->height) frame->height = avctx->height;
411 if (frame->format == AV_PIX_FMT_NONE) frame->format = avctx->pix_fmt;
416 actual_got_frame = got_frame;
418 if (avctx->codec->type == AVMEDIA_TYPE_VIDEO) {
419 if (frame->flags & AV_FRAME_FLAG_DISCARD)
422 frame->best_effort_timestamp = guess_correct_pts(avctx,
425 } else if (avctx->codec->type == AVMEDIA_TYPE_AUDIO) {
428 uint32_t discard_padding = 0;
429 uint8_t skip_reason = 0;
430 uint8_t discard_reason = 0;
432 if (ret >= 0 && got_frame) {
433 frame->best_effort_timestamp = guess_correct_pts(avctx,
436 if (frame->format == AV_SAMPLE_FMT_NONE)
437 frame->format = avctx->sample_fmt;
438 if (!frame->channel_layout)
439 frame->channel_layout = avctx->channel_layout;
440 if (!frame->channels)
441 frame->channels = avctx->channels;
442 if (!frame->sample_rate)
443 frame->sample_rate = avctx->sample_rate;
446 side= av_packet_get_side_data(avci->last_pkt_props, AV_PKT_DATA_SKIP_SAMPLES, &side_size);
447 if(side && side_size>=10) {
448 avctx->internal->skip_samples = AV_RL32(side) * avctx->internal->skip_samples_multiplier;
449 discard_padding = AV_RL32(side + 4);
450 av_log(avctx, AV_LOG_DEBUG, "skip %d / discard %d samples due to side data\n",
451 avctx->internal->skip_samples, (int)discard_padding);
452 skip_reason = AV_RL8(side + 8);
453 discard_reason = AV_RL8(side + 9);
456 if ((frame->flags & AV_FRAME_FLAG_DISCARD) && got_frame &&
457 !(avctx->flags2 & AV_CODEC_FLAG2_SKIP_MANUAL)) {
458 avctx->internal->skip_samples = FFMAX(0, avctx->internal->skip_samples - frame->nb_samples);
462 if (avctx->internal->skip_samples > 0 && got_frame &&
463 !(avctx->flags2 & AV_CODEC_FLAG2_SKIP_MANUAL)) {
464 if(frame->nb_samples <= avctx->internal->skip_samples){
466 avctx->internal->skip_samples -= frame->nb_samples;
467 av_log(avctx, AV_LOG_DEBUG, "skip whole frame, skip left: %d\n",
468 avctx->internal->skip_samples);
470 av_samples_copy(frame->extended_data, frame->extended_data, 0, avctx->internal->skip_samples,
471 frame->nb_samples - avctx->internal->skip_samples, avctx->channels, frame->format);
472 if(avctx->pkt_timebase.num && avctx->sample_rate) {
473 int64_t diff_ts = av_rescale_q(avctx->internal->skip_samples,
474 (AVRational){1, avctx->sample_rate},
475 avctx->pkt_timebase);
476 if(frame->pts!=AV_NOPTS_VALUE)
477 frame->pts += diff_ts;
479 FF_DISABLE_DEPRECATION_WARNINGS
480 if(frame->pkt_pts!=AV_NOPTS_VALUE)
481 frame->pkt_pts += diff_ts;
482 FF_ENABLE_DEPRECATION_WARNINGS
484 if(frame->pkt_dts!=AV_NOPTS_VALUE)
485 frame->pkt_dts += diff_ts;
486 if (frame->pkt_duration >= diff_ts)
487 frame->pkt_duration -= diff_ts;
489 av_log(avctx, AV_LOG_WARNING, "Could not update timestamps for skipped samples.\n");
491 av_log(avctx, AV_LOG_DEBUG, "skip %d/%d samples\n",
492 avctx->internal->skip_samples, frame->nb_samples);
493 frame->nb_samples -= avctx->internal->skip_samples;
494 avctx->internal->skip_samples = 0;
498 if (discard_padding > 0 && discard_padding <= frame->nb_samples && got_frame &&
499 !(avctx->flags2 & AV_CODEC_FLAG2_SKIP_MANUAL)) {
500 if (discard_padding == frame->nb_samples) {
503 if(avctx->pkt_timebase.num && avctx->sample_rate) {
504 int64_t diff_ts = av_rescale_q(frame->nb_samples - discard_padding,
505 (AVRational){1, avctx->sample_rate},
506 avctx->pkt_timebase);
507 frame->pkt_duration = diff_ts;
509 av_log(avctx, AV_LOG_WARNING, "Could not update timestamps for discarded samples.\n");
511 av_log(avctx, AV_LOG_DEBUG, "discard %d/%d samples\n",
512 (int)discard_padding, frame->nb_samples);
513 frame->nb_samples -= discard_padding;
517 if ((avctx->flags2 & AV_CODEC_FLAG2_SKIP_MANUAL) && got_frame) {
518 AVFrameSideData *fside = av_frame_new_side_data(frame, AV_FRAME_DATA_SKIP_SAMPLES, 10);
520 AV_WL32(fside->data, avctx->internal->skip_samples);
521 AV_WL32(fside->data + 4, discard_padding);
522 AV_WL8(fside->data + 8, skip_reason);
523 AV_WL8(fside->data + 9, discard_reason);
524 avctx->internal->skip_samples = 0;
529 if (avctx->codec->type == AVMEDIA_TYPE_AUDIO &&
530 !avci->showed_multi_packet_warning &&
531 ret >= 0 && ret != pkt->size && !(avctx->codec->capabilities & AV_CODEC_CAP_SUBFRAMES)) {
532 av_log(avctx, AV_LOG_WARNING, "Multiple frames in a packet.\n");
533 avci->showed_multi_packet_warning = 1;
537 av_frame_unref(frame);
539 if (ret >= 0 && avctx->codec->type == AVMEDIA_TYPE_VIDEO && !(avctx->flags & AV_CODEC_FLAG_TRUNCATED))
542 #if FF_API_AVCTX_TIMEBASE
543 if (avctx->framerate.num > 0 && avctx->framerate.den > 0)
544 avctx->time_base = av_inv_q(av_mul_q(avctx->framerate, (AVRational){avctx->ticks_per_frame, 1}));
547 /* do not stop draining when actual_got_frame != 0 or ret < 0 */
548 /* got_frame == 0 but actual_got_frame != 0 when frame is discarded */
549 if (avctx->internal->draining && !actual_got_frame) {
551 /* prevent infinite loop if a decoder wrongly always return error on draining */
552 /* reasonable nb_errors_max = maximum b frames + thread count */
553 int nb_errors_max = 20 + (HAVE_THREADS && avctx->active_thread_type & FF_THREAD_FRAME ?
554 avctx->thread_count : 1);
556 if (avci->nb_draining_errors++ >= nb_errors_max) {
557 av_log(avctx, AV_LOG_ERROR, "Too many errors when draining, this is a bug. "
558 "Stop draining and force EOF.\n");
559 avci->draining_done = 1;
563 avci->draining_done = 1;
567 avci->compat_decode_consumed += ret;
569 if (ret >= pkt->size || ret < 0) {
570 av_packet_unref(pkt);
574 pkt->data += consumed;
575 pkt->size -= consumed;
576 avci->last_pkt_props->size -= consumed; // See extract_packet_props() comment.
577 pkt->pts = AV_NOPTS_VALUE;
578 pkt->dts = AV_NOPTS_VALUE;
579 avci->last_pkt_props->pts = AV_NOPTS_VALUE;
580 avci->last_pkt_props->dts = AV_NOPTS_VALUE;
584 av_assert0(frame->buf[0]);
586 return ret < 0 ? ret : 0;
589 static int decode_simple_receive_frame(AVCodecContext *avctx, AVFrame *frame)
593 while (!frame->buf[0]) {
594 ret = decode_simple_internal(avctx, frame);
602 static int decode_receive_frame_internal(AVCodecContext *avctx, AVFrame *frame)
604 AVCodecInternal *avci = avctx->internal;
607 av_assert0(!frame->buf[0]);
609 if (avctx->codec->receive_frame)
610 ret = avctx->codec->receive_frame(avctx, frame);
612 ret = decode_simple_receive_frame(avctx, frame);
614 if (ret == AVERROR_EOF)
615 avci->draining_done = 1;
618 /* the only case where decode data is not set should be decoders
619 * that do not call ff_get_buffer() */
620 av_assert0((frame->private_ref && frame->private_ref->size == sizeof(FrameDecodeData)) ||
621 !(avctx->codec->capabilities & AV_CODEC_CAP_DR1));
623 if (frame->private_ref) {
624 FrameDecodeData *fdd = (FrameDecodeData*)frame->private_ref->data;
626 if (fdd->post_process) {
627 ret = fdd->post_process(avctx, frame);
629 av_frame_unref(frame);
636 /* free the per-frame decode data */
637 av_buffer_unref(&frame->private_ref);
642 int attribute_align_arg avcodec_send_packet(AVCodecContext *avctx, const AVPacket *avpkt)
644 AVCodecInternal *avci = avctx->internal;
647 if (!avcodec_is_open(avctx) || !av_codec_is_decoder(avctx->codec))
648 return AVERROR(EINVAL);
650 if (avctx->internal->draining)
653 if (avpkt && !avpkt->size && avpkt->data)
654 return AVERROR(EINVAL);
656 ret = bsfs_init(avctx);
660 av_packet_unref(avci->buffer_pkt);
661 if (avpkt && (avpkt->data || avpkt->side_data_elems)) {
662 ret = av_packet_ref(avci->buffer_pkt, avpkt);
667 ret = av_bsf_send_packet(avci->filter.bsfs[0], avci->buffer_pkt);
669 av_packet_unref(avci->buffer_pkt);
673 if (!avci->buffer_frame->buf[0]) {
674 ret = decode_receive_frame_internal(avctx, avci->buffer_frame);
675 if (ret < 0 && ret != AVERROR(EAGAIN) && ret != AVERROR_EOF)
682 static int apply_cropping(AVCodecContext *avctx, AVFrame *frame)
684 /* make sure we are noisy about decoders returning invalid cropping data */
685 if (frame->crop_left >= INT_MAX - frame->crop_right ||
686 frame->crop_top >= INT_MAX - frame->crop_bottom ||
687 (frame->crop_left + frame->crop_right) >= frame->width ||
688 (frame->crop_top + frame->crop_bottom) >= frame->height) {
689 av_log(avctx, AV_LOG_WARNING,
690 "Invalid cropping information set by a decoder: "
691 "%"SIZE_SPECIFIER"/%"SIZE_SPECIFIER"/%"SIZE_SPECIFIER"/%"SIZE_SPECIFIER" "
692 "(frame size %dx%d). This is a bug, please report it\n",
693 frame->crop_left, frame->crop_right, frame->crop_top, frame->crop_bottom,
694 frame->width, frame->height);
695 frame->crop_left = 0;
696 frame->crop_right = 0;
698 frame->crop_bottom = 0;
702 if (!avctx->apply_cropping)
705 return av_frame_apply_cropping(frame, avctx->flags & AV_CODEC_FLAG_UNALIGNED ?
706 AV_FRAME_CROP_UNALIGNED : 0);
709 int attribute_align_arg avcodec_receive_frame(AVCodecContext *avctx, AVFrame *frame)
711 AVCodecInternal *avci = avctx->internal;
714 av_frame_unref(frame);
716 if (!avcodec_is_open(avctx) || !av_codec_is_decoder(avctx->codec))
717 return AVERROR(EINVAL);
719 ret = bsfs_init(avctx);
723 if (avci->buffer_frame->buf[0]) {
724 av_frame_move_ref(frame, avci->buffer_frame);
726 ret = decode_receive_frame_internal(avctx, frame);
731 if (avctx->codec_type == AVMEDIA_TYPE_VIDEO) {
732 ret = apply_cropping(avctx, frame);
734 av_frame_unref(frame);
739 avctx->frame_number++;
744 static int compat_decode(AVCodecContext *avctx, AVFrame *frame,
745 int *got_frame, const AVPacket *pkt)
747 AVCodecInternal *avci = avctx->internal;
750 av_assert0(avci->compat_decode_consumed == 0);
752 if (avci->draining_done && pkt && pkt->size != 0) {
753 av_log(avctx, AV_LOG_WARNING, "Got unexpected packet after EOF\n");
754 avcodec_flush_buffers(avctx);
758 avci->compat_decode = 1;
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 (sub->rects[i]->ass && !utf8_check(sub->rects[i]->ass)) {
1061 av_log(avctx, AV_LOG_ERROR,
1062 "Invalid UTF-8 in decoded subtitles text; "
1063 "maybe missing -sub_charenc option\n");
1064 avsubtitle_free(sub);
1065 ret = AVERROR_INVALIDDATA;
1070 if (avpkt->data != pkt_recoded.data) { // did we recode?
1071 /* prevent from destroying side data from original packet */
1072 pkt_recoded.side_data = NULL;
1073 pkt_recoded.side_data_elems = 0;
1075 av_packet_unref(&pkt_recoded);
1080 avctx->frame_number++;
1086 enum AVPixelFormat avcodec_default_get_format(struct AVCodecContext *avctx,
1087 const enum AVPixelFormat *fmt)
1089 const AVPixFmtDescriptor *desc;
1090 const AVCodecHWConfig *config;
1093 // If a device was supplied when the codec was opened, assume that the
1094 // user wants to use it.
1095 if (avctx->hw_device_ctx && avctx->codec->hw_configs) {
1096 AVHWDeviceContext *device_ctx =
1097 (AVHWDeviceContext*)avctx->hw_device_ctx->data;
1099 config = &avctx->codec->hw_configs[i]->public;
1102 if (!(config->methods &
1103 AV_CODEC_HW_CONFIG_METHOD_HW_DEVICE_CTX))
1105 if (device_ctx->type != config->device_type)
1107 for (n = 0; fmt[n] != AV_PIX_FMT_NONE; n++) {
1108 if (config->pix_fmt == fmt[n])
1113 // No device or other setup, so we have to choose from things which
1114 // don't any other external information.
1116 // If the last element of the list is a software format, choose it
1117 // (this should be best software format if any exist).
1118 for (n = 0; fmt[n] != AV_PIX_FMT_NONE; n++);
1119 desc = av_pix_fmt_desc_get(fmt[n - 1]);
1120 if (!(desc->flags & AV_PIX_FMT_FLAG_HWACCEL))
1123 // Finally, traverse the list in order and choose the first entry
1124 // with no external dependencies (if there is no hardware configuration
1125 // information available then this just picks the first entry).
1126 for (n = 0; fmt[n] != AV_PIX_FMT_NONE; n++) {
1128 config = avcodec_get_hw_config(avctx->codec, i);
1131 if (config->pix_fmt == fmt[n])
1135 // No specific config available, so the decoder must be able
1136 // to handle this format without any additional setup.
1139 if (config->methods & AV_CODEC_HW_CONFIG_METHOD_INTERNAL) {
1140 // Usable with only internal setup.
1145 // Nothing is usable, give up.
1146 return AV_PIX_FMT_NONE;
1149 int ff_decode_get_hw_frames_ctx(AVCodecContext *avctx,
1150 enum AVHWDeviceType dev_type)
1152 AVHWDeviceContext *device_ctx;
1153 AVHWFramesContext *frames_ctx;
1156 if (!avctx->hwaccel)
1157 return AVERROR(ENOSYS);
1159 if (avctx->hw_frames_ctx)
1161 if (!avctx->hw_device_ctx) {
1162 av_log(avctx, AV_LOG_ERROR, "A hardware frames or device context is "
1163 "required for hardware accelerated decoding.\n");
1164 return AVERROR(EINVAL);
1167 device_ctx = (AVHWDeviceContext *)avctx->hw_device_ctx->data;
1168 if (device_ctx->type != dev_type) {
1169 av_log(avctx, AV_LOG_ERROR, "Device type %s expected for hardware "
1170 "decoding, but got %s.\n", av_hwdevice_get_type_name(dev_type),
1171 av_hwdevice_get_type_name(device_ctx->type));
1172 return AVERROR(EINVAL);
1175 ret = avcodec_get_hw_frames_parameters(avctx,
1176 avctx->hw_device_ctx,
1177 avctx->hwaccel->pix_fmt,
1178 &avctx->hw_frames_ctx);
1182 frames_ctx = (AVHWFramesContext*)avctx->hw_frames_ctx->data;
1185 if (frames_ctx->initial_pool_size) {
1186 // We guarantee 4 base work surfaces. The function above guarantees 1
1187 // (the absolute minimum), so add the missing count.
1188 frames_ctx->initial_pool_size += 3;
1190 // Add an additional surface per thread is frame threading is enabled.
1191 if (avctx->active_thread_type & FF_THREAD_FRAME)
1192 frames_ctx->initial_pool_size += avctx->thread_count;
1195 ret = av_hwframe_ctx_init(avctx->hw_frames_ctx);
1197 av_buffer_unref(&avctx->hw_frames_ctx);
1204 int avcodec_get_hw_frames_parameters(AVCodecContext *avctx,
1205 AVBufferRef *device_ref,
1206 enum AVPixelFormat hw_pix_fmt,
1207 AVBufferRef **out_frames_ref)
1209 AVBufferRef *frames_ref = NULL;
1210 const AVCodecHWConfigInternal *hw_config;
1211 const AVHWAccel *hwa;
1215 hw_config = avctx->codec->hw_configs[i];
1217 return AVERROR(ENOENT);
1218 if (hw_config->public.pix_fmt == hw_pix_fmt)
1222 hwa = hw_config->hwaccel;
1223 if (!hwa || !hwa->frame_params)
1224 return AVERROR(ENOENT);
1226 frames_ref = av_hwframe_ctx_alloc(device_ref);
1228 return AVERROR(ENOMEM);
1230 ret = hwa->frame_params(avctx, frames_ref);
1232 *out_frames_ref = frames_ref;
1234 av_buffer_unref(&frames_ref);
1239 static int hwaccel_init(AVCodecContext *avctx,
1240 const AVCodecHWConfigInternal *hw_config)
1242 const AVHWAccel *hwaccel;
1245 hwaccel = hw_config->hwaccel;
1246 if (hwaccel->capabilities & AV_HWACCEL_CODEC_CAP_EXPERIMENTAL &&
1247 avctx->strict_std_compliance > FF_COMPLIANCE_EXPERIMENTAL) {
1248 av_log(avctx, AV_LOG_WARNING, "Ignoring experimental hwaccel: %s\n",
1250 return AVERROR_PATCHWELCOME;
1253 if (hwaccel->priv_data_size) {
1254 avctx->internal->hwaccel_priv_data =
1255 av_mallocz(hwaccel->priv_data_size);
1256 if (!avctx->internal->hwaccel_priv_data)
1257 return AVERROR(ENOMEM);
1260 avctx->hwaccel = hwaccel;
1261 if (hwaccel->init) {
1262 err = hwaccel->init(avctx);
1264 av_log(avctx, AV_LOG_ERROR, "Failed setup for format %s: "
1265 "hwaccel initialisation returned error.\n",
1266 av_get_pix_fmt_name(hw_config->public.pix_fmt));
1267 av_freep(&avctx->internal->hwaccel_priv_data);
1268 avctx->hwaccel = NULL;
1276 static void hwaccel_uninit(AVCodecContext *avctx)
1278 if (avctx->hwaccel && avctx->hwaccel->uninit)
1279 avctx->hwaccel->uninit(avctx);
1281 av_freep(&avctx->internal->hwaccel_priv_data);
1283 avctx->hwaccel = NULL;
1285 av_buffer_unref(&avctx->hw_frames_ctx);
1288 int ff_get_format(AVCodecContext *avctx, const enum AVPixelFormat *fmt)
1290 const AVPixFmtDescriptor *desc;
1291 enum AVPixelFormat *choices;
1292 enum AVPixelFormat ret, user_choice;
1293 const AVCodecHWConfigInternal *hw_config;
1294 const AVCodecHWConfig *config;
1297 // Find end of list.
1298 for (n = 0; fmt[n] != AV_PIX_FMT_NONE; n++);
1299 // Must contain at least one entry.
1301 // If a software format is available, it must be the last entry.
1302 desc = av_pix_fmt_desc_get(fmt[n - 1]);
1303 if (desc->flags & AV_PIX_FMT_FLAG_HWACCEL) {
1304 // No software format is available.
1306 avctx->sw_pix_fmt = fmt[n - 1];
1309 choices = av_malloc_array(n + 1, sizeof(*choices));
1311 return AV_PIX_FMT_NONE;
1313 memcpy(choices, fmt, (n + 1) * sizeof(*choices));
1316 // Remove the previous hwaccel, if there was one.
1317 hwaccel_uninit(avctx);
1319 user_choice = avctx->get_format(avctx, choices);
1320 if (user_choice == AV_PIX_FMT_NONE) {
1321 // Explicitly chose nothing, give up.
1322 ret = AV_PIX_FMT_NONE;
1326 desc = av_pix_fmt_desc_get(user_choice);
1328 av_log(avctx, AV_LOG_ERROR, "Invalid format returned by "
1329 "get_format() callback.\n");
1330 ret = AV_PIX_FMT_NONE;
1333 av_log(avctx, AV_LOG_DEBUG, "Format %s chosen by get_format().\n",
1336 for (i = 0; i < n; i++) {
1337 if (choices[i] == user_choice)
1341 av_log(avctx, AV_LOG_ERROR, "Invalid return from get_format(): "
1342 "%s not in possible list.\n", desc->name);
1346 if (avctx->codec->hw_configs) {
1348 hw_config = avctx->codec->hw_configs[i];
1351 if (hw_config->public.pix_fmt == user_choice)
1359 // No config available, so no extra setup required.
1363 config = &hw_config->public;
1365 if (config->methods &
1366 AV_CODEC_HW_CONFIG_METHOD_HW_FRAMES_CTX &&
1367 avctx->hw_frames_ctx) {
1368 const AVHWFramesContext *frames_ctx =
1369 (AVHWFramesContext*)avctx->hw_frames_ctx->data;
1370 if (frames_ctx->format != user_choice) {
1371 av_log(avctx, AV_LOG_ERROR, "Invalid setup for format %s: "
1372 "does not match the format of the provided frames "
1373 "context.\n", desc->name);
1376 } else if (config->methods &
1377 AV_CODEC_HW_CONFIG_METHOD_HW_DEVICE_CTX &&
1378 avctx->hw_device_ctx) {
1379 const AVHWDeviceContext *device_ctx =
1380 (AVHWDeviceContext*)avctx->hw_device_ctx->data;
1381 if (device_ctx->type != config->device_type) {
1382 av_log(avctx, AV_LOG_ERROR, "Invalid setup for format %s: "
1383 "does not match the type of the provided device "
1384 "context.\n", desc->name);
1387 } else if (config->methods &
1388 AV_CODEC_HW_CONFIG_METHOD_INTERNAL) {
1389 // Internal-only setup, no additional configuration.
1390 } else if (config->methods &
1391 AV_CODEC_HW_CONFIG_METHOD_AD_HOC) {
1392 // Some ad-hoc configuration we can't see and can't check.
1394 av_log(avctx, AV_LOG_ERROR, "Invalid setup for format %s: "
1395 "missing configuration.\n", desc->name);
1398 if (hw_config->hwaccel) {
1399 av_log(avctx, AV_LOG_DEBUG, "Format %s requires hwaccel "
1400 "initialisation.\n", desc->name);
1401 err = hwaccel_init(avctx, hw_config);
1409 av_log(avctx, AV_LOG_DEBUG, "Format %s not usable, retrying "
1410 "get_format() without it.\n", desc->name);
1411 for (i = 0; i < n; i++) {
1412 if (choices[i] == user_choice)
1415 for (; i + 1 < n; i++)
1416 choices[i] = choices[i + 1];
1424 static int update_frame_pool(AVCodecContext *avctx, AVFrame *frame)
1426 FramePool *pool = avctx->internal->pool;
1429 switch (avctx->codec_type) {
1430 case AVMEDIA_TYPE_VIDEO: {
1433 int size[4] = { 0 };
1434 int w = frame->width;
1435 int h = frame->height;
1436 int tmpsize, unaligned;
1438 if (pool->format == frame->format &&
1439 pool->width == frame->width && pool->height == frame->height)
1442 avcodec_align_dimensions2(avctx, &w, &h, pool->stride_align);
1445 // NOTE: do not align linesizes individually, this breaks e.g. assumptions
1446 // that linesize[0] == 2*linesize[1] in the MPEG-encoder for 4:2:2
1447 ret = av_image_fill_linesizes(linesize, avctx->pix_fmt, w);
1450 // increase alignment of w for next try (rhs gives the lowest bit set in w)
1454 for (i = 0; i < 4; i++)
1455 unaligned |= linesize[i] % pool->stride_align[i];
1456 } while (unaligned);
1458 tmpsize = av_image_fill_pointers(data, avctx->pix_fmt, h,
1463 for (i = 0; i < 3 && data[i + 1]; i++)
1464 size[i] = data[i + 1] - data[i];
1465 size[i] = tmpsize - (data[i] - data[0]);
1467 for (i = 0; i < 4; i++) {
1468 av_buffer_pool_uninit(&pool->pools[i]);
1469 pool->linesize[i] = linesize[i];
1471 pool->pools[i] = av_buffer_pool_init(size[i] + 16 + STRIDE_ALIGN - 1,
1472 CONFIG_MEMORY_POISONING ?
1475 if (!pool->pools[i]) {
1476 ret = AVERROR(ENOMEM);
1481 pool->format = frame->format;
1482 pool->width = frame->width;
1483 pool->height = frame->height;
1487 case AVMEDIA_TYPE_AUDIO: {
1488 int ch = frame->channels; //av_get_channel_layout_nb_channels(frame->channel_layout);
1489 int planar = av_sample_fmt_is_planar(frame->format);
1490 int planes = planar ? ch : 1;
1492 if (pool->format == frame->format && pool->planes == planes &&
1493 pool->channels == ch && frame->nb_samples == pool->samples)
1496 av_buffer_pool_uninit(&pool->pools[0]);
1497 ret = av_samples_get_buffer_size(&pool->linesize[0], ch,
1498 frame->nb_samples, frame->format, 0);
1502 pool->pools[0] = av_buffer_pool_init(pool->linesize[0], NULL);
1503 if (!pool->pools[0]) {
1504 ret = AVERROR(ENOMEM);
1508 pool->format = frame->format;
1509 pool->planes = planes;
1510 pool->channels = ch;
1511 pool->samples = frame->nb_samples;
1514 default: av_assert0(0);
1518 for (i = 0; i < 4; i++)
1519 av_buffer_pool_uninit(&pool->pools[i]);
1521 pool->planes = pool->channels = pool->samples = 0;
1522 pool->width = pool->height = 0;
1526 static int audio_get_buffer(AVCodecContext *avctx, AVFrame *frame)
1528 FramePool *pool = avctx->internal->pool;
1529 int planes = pool->planes;
1532 frame->linesize[0] = pool->linesize[0];
1534 if (planes > AV_NUM_DATA_POINTERS) {
1535 frame->extended_data = av_mallocz_array(planes, sizeof(*frame->extended_data));
1536 frame->nb_extended_buf = planes - AV_NUM_DATA_POINTERS;
1537 frame->extended_buf = av_mallocz_array(frame->nb_extended_buf,
1538 sizeof(*frame->extended_buf));
1539 if (!frame->extended_data || !frame->extended_buf) {
1540 av_freep(&frame->extended_data);
1541 av_freep(&frame->extended_buf);
1542 return AVERROR(ENOMEM);
1545 frame->extended_data = frame->data;
1546 av_assert0(frame->nb_extended_buf == 0);
1549 for (i = 0; i < FFMIN(planes, AV_NUM_DATA_POINTERS); i++) {
1550 frame->buf[i] = av_buffer_pool_get(pool->pools[0]);
1553 frame->extended_data[i] = frame->data[i] = frame->buf[i]->data;
1555 for (i = 0; i < frame->nb_extended_buf; i++) {
1556 frame->extended_buf[i] = av_buffer_pool_get(pool->pools[0]);
1557 if (!frame->extended_buf[i])
1559 frame->extended_data[i + AV_NUM_DATA_POINTERS] = frame->extended_buf[i]->data;
1562 if (avctx->debug & FF_DEBUG_BUFFERS)
1563 av_log(avctx, AV_LOG_DEBUG, "default_get_buffer called on frame %p", frame);
1567 av_frame_unref(frame);
1568 return AVERROR(ENOMEM);
1571 static int video_get_buffer(AVCodecContext *s, AVFrame *pic)
1573 FramePool *pool = s->internal->pool;
1574 const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(pic->format);
1577 if (pic->data[0] || pic->data[1] || pic->data[2] || pic->data[3]) {
1578 av_log(s, AV_LOG_ERROR, "pic->data[*]!=NULL in avcodec_default_get_buffer\n");
1583 av_log(s, AV_LOG_ERROR,
1584 "Unable to get pixel format descriptor for format %s\n",
1585 av_get_pix_fmt_name(pic->format));
1586 return AVERROR(EINVAL);
1589 memset(pic->data, 0, sizeof(pic->data));
1590 pic->extended_data = pic->data;
1592 for (i = 0; i < 4 && pool->pools[i]; i++) {
1593 pic->linesize[i] = pool->linesize[i];
1595 pic->buf[i] = av_buffer_pool_get(pool->pools[i]);
1599 pic->data[i] = pic->buf[i]->data;
1601 for (; i < AV_NUM_DATA_POINTERS; i++) {
1602 pic->data[i] = NULL;
1603 pic->linesize[i] = 0;
1605 if (desc->flags & AV_PIX_FMT_FLAG_PAL ||
1606 desc->flags & AV_PIX_FMT_FLAG_PSEUDOPAL)
1607 avpriv_set_systematic_pal2((uint32_t *)pic->data[1], pic->format);
1609 if (s->debug & FF_DEBUG_BUFFERS)
1610 av_log(s, AV_LOG_DEBUG, "default_get_buffer called on pic %p\n", pic);
1614 av_frame_unref(pic);
1615 return AVERROR(ENOMEM);
1618 int avcodec_default_get_buffer2(AVCodecContext *avctx, AVFrame *frame, int flags)
1622 if (avctx->hw_frames_ctx) {
1623 ret = av_hwframe_get_buffer(avctx->hw_frames_ctx, frame, 0);
1624 frame->width = avctx->coded_width;
1625 frame->height = avctx->coded_height;
1629 if ((ret = update_frame_pool(avctx, frame)) < 0)
1632 switch (avctx->codec_type) {
1633 case AVMEDIA_TYPE_VIDEO:
1634 return video_get_buffer(avctx, frame);
1635 case AVMEDIA_TYPE_AUDIO:
1636 return audio_get_buffer(avctx, frame);
1642 static int add_metadata_from_side_data(const AVPacket *avpkt, AVFrame *frame)
1645 const uint8_t *side_metadata;
1647 AVDictionary **frame_md = &frame->metadata;
1649 side_metadata = av_packet_get_side_data(avpkt,
1650 AV_PKT_DATA_STRINGS_METADATA, &size);
1651 return av_packet_unpack_dictionary(side_metadata, size, frame_md);
1654 int ff_init_buffer_info(AVCodecContext *avctx, AVFrame *frame)
1656 const AVPacket *pkt = avctx->internal->last_pkt_props;
1658 static const struct {
1659 enum AVPacketSideDataType packet;
1660 enum AVFrameSideDataType frame;
1662 { AV_PKT_DATA_REPLAYGAIN , AV_FRAME_DATA_REPLAYGAIN },
1663 { AV_PKT_DATA_DISPLAYMATRIX, AV_FRAME_DATA_DISPLAYMATRIX },
1664 { AV_PKT_DATA_SPHERICAL, AV_FRAME_DATA_SPHERICAL },
1665 { AV_PKT_DATA_STEREO3D, AV_FRAME_DATA_STEREO3D },
1666 { AV_PKT_DATA_AUDIO_SERVICE_TYPE, AV_FRAME_DATA_AUDIO_SERVICE_TYPE },
1667 { AV_PKT_DATA_MASTERING_DISPLAY_METADATA, AV_FRAME_DATA_MASTERING_DISPLAY_METADATA },
1668 { AV_PKT_DATA_CONTENT_LIGHT_LEVEL, AV_FRAME_DATA_CONTENT_LIGHT_LEVEL },
1669 { AV_PKT_DATA_A53_CC, AV_FRAME_DATA_A53_CC },
1673 frame->pts = pkt->pts;
1675 FF_DISABLE_DEPRECATION_WARNINGS
1676 frame->pkt_pts = pkt->pts;
1677 FF_ENABLE_DEPRECATION_WARNINGS
1679 frame->pkt_pos = pkt->pos;
1680 frame->pkt_duration = pkt->duration;
1681 frame->pkt_size = pkt->size;
1683 for (i = 0; i < FF_ARRAY_ELEMS(sd); i++) {
1685 uint8_t *packet_sd = av_packet_get_side_data(pkt, sd[i].packet, &size);
1687 AVFrameSideData *frame_sd = av_frame_new_side_data(frame,
1691 return AVERROR(ENOMEM);
1693 memcpy(frame_sd->data, packet_sd, size);
1696 add_metadata_from_side_data(pkt, frame);
1698 if (pkt->flags & AV_PKT_FLAG_DISCARD) {
1699 frame->flags |= AV_FRAME_FLAG_DISCARD;
1701 frame->flags = (frame->flags & ~AV_FRAME_FLAG_DISCARD);
1704 frame->reordered_opaque = avctx->reordered_opaque;
1706 if (frame->color_primaries == AVCOL_PRI_UNSPECIFIED)
1707 frame->color_primaries = avctx->color_primaries;
1708 if (frame->color_trc == AVCOL_TRC_UNSPECIFIED)
1709 frame->color_trc = avctx->color_trc;
1710 if (frame->colorspace == AVCOL_SPC_UNSPECIFIED)
1711 frame->colorspace = avctx->colorspace;
1712 if (frame->color_range == AVCOL_RANGE_UNSPECIFIED)
1713 frame->color_range = avctx->color_range;
1714 if (frame->chroma_location == AVCHROMA_LOC_UNSPECIFIED)
1715 frame->chroma_location = avctx->chroma_sample_location;
1717 switch (avctx->codec->type) {
1718 case AVMEDIA_TYPE_VIDEO:
1719 frame->format = avctx->pix_fmt;
1720 if (!frame->sample_aspect_ratio.num)
1721 frame->sample_aspect_ratio = avctx->sample_aspect_ratio;
1723 if (frame->width && frame->height &&
1724 av_image_check_sar(frame->width, frame->height,
1725 frame->sample_aspect_ratio) < 0) {
1726 av_log(avctx, AV_LOG_WARNING, "ignoring invalid SAR: %u/%u\n",
1727 frame->sample_aspect_ratio.num,
1728 frame->sample_aspect_ratio.den);
1729 frame->sample_aspect_ratio = (AVRational){ 0, 1 };
1733 case AVMEDIA_TYPE_AUDIO:
1734 if (!frame->sample_rate)
1735 frame->sample_rate = avctx->sample_rate;
1736 if (frame->format < 0)
1737 frame->format = avctx->sample_fmt;
1738 if (!frame->channel_layout) {
1739 if (avctx->channel_layout) {
1740 if (av_get_channel_layout_nb_channels(avctx->channel_layout) !=
1742 av_log(avctx, AV_LOG_ERROR, "Inconsistent channel "
1743 "configuration.\n");
1744 return AVERROR(EINVAL);
1747 frame->channel_layout = avctx->channel_layout;
1749 if (avctx->channels > FF_SANE_NB_CHANNELS) {
1750 av_log(avctx, AV_LOG_ERROR, "Too many channels: %d.\n",
1752 return AVERROR(ENOSYS);
1756 frame->channels = avctx->channels;
1762 int ff_decode_frame_props(AVCodecContext *avctx, AVFrame *frame)
1764 return ff_init_buffer_info(avctx, frame);
1767 static void validate_avframe_allocation(AVCodecContext *avctx, AVFrame *frame)
1769 if (avctx->codec_type == AVMEDIA_TYPE_VIDEO) {
1771 int num_planes = av_pix_fmt_count_planes(frame->format);
1772 const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(frame->format);
1773 int flags = desc ? desc->flags : 0;
1774 if (num_planes == 1 && (flags & AV_PIX_FMT_FLAG_PAL))
1776 for (i = 0; i < num_planes; i++) {
1777 av_assert0(frame->data[i]);
1779 // For now do not enforce anything for palette of pseudopal formats
1780 if (num_planes == 1 && (flags & AV_PIX_FMT_FLAG_PSEUDOPAL))
1782 // For formats without data like hwaccel allow unused pointers to be non-NULL.
1783 for (i = num_planes; num_planes > 0 && i < FF_ARRAY_ELEMS(frame->data); i++) {
1785 av_log(avctx, AV_LOG_ERROR, "Buffer returned by get_buffer2() did not zero unused plane pointers\n");
1786 frame->data[i] = NULL;
1791 static void decode_data_free(void *opaque, uint8_t *data)
1793 FrameDecodeData *fdd = (FrameDecodeData*)data;
1795 if (fdd->post_process_opaque_free)
1796 fdd->post_process_opaque_free(fdd->post_process_opaque);
1798 if (fdd->hwaccel_priv_free)
1799 fdd->hwaccel_priv_free(fdd->hwaccel_priv);
1804 int ff_attach_decode_data(AVFrame *frame)
1806 AVBufferRef *fdd_buf;
1807 FrameDecodeData *fdd;
1809 av_assert1(!frame->private_ref);
1810 av_buffer_unref(&frame->private_ref);
1812 fdd = av_mallocz(sizeof(*fdd));
1814 return AVERROR(ENOMEM);
1816 fdd_buf = av_buffer_create((uint8_t*)fdd, sizeof(*fdd), decode_data_free,
1817 NULL, AV_BUFFER_FLAG_READONLY);
1820 return AVERROR(ENOMEM);
1823 frame->private_ref = fdd_buf;
1828 static int get_buffer_internal(AVCodecContext *avctx, AVFrame *frame, int flags)
1830 const AVHWAccel *hwaccel = avctx->hwaccel;
1831 int override_dimensions = 1;
1834 if (avctx->codec_type == AVMEDIA_TYPE_VIDEO) {
1835 if ((ret = av_image_check_size2(avctx->width, avctx->height, avctx->max_pixels, AV_PIX_FMT_NONE, 0, avctx)) < 0 || avctx->pix_fmt<0) {
1836 av_log(avctx, AV_LOG_ERROR, "video_get_buffer: image parameters invalid\n");
1837 return AVERROR(EINVAL);
1840 if (frame->width <= 0 || frame->height <= 0) {
1841 frame->width = FFMAX(avctx->width, AV_CEIL_RSHIFT(avctx->coded_width, avctx->lowres));
1842 frame->height = FFMAX(avctx->height, AV_CEIL_RSHIFT(avctx->coded_height, avctx->lowres));
1843 override_dimensions = 0;
1846 if (frame->data[0] || frame->data[1] || frame->data[2] || frame->data[3]) {
1847 av_log(avctx, AV_LOG_ERROR, "pic->data[*]!=NULL in get_buffer_internal\n");
1848 return AVERROR(EINVAL);
1851 ret = ff_decode_frame_props(avctx, frame);
1856 if (hwaccel->alloc_frame) {
1857 ret = hwaccel->alloc_frame(avctx, frame);
1861 avctx->sw_pix_fmt = avctx->pix_fmt;
1863 ret = avctx->get_buffer2(avctx, frame, flags);
1867 validate_avframe_allocation(avctx, frame);
1869 ret = ff_attach_decode_data(frame);
1874 if (avctx->codec_type == AVMEDIA_TYPE_VIDEO && !override_dimensions &&
1875 !(avctx->codec->caps_internal & FF_CODEC_CAP_EXPORTS_CROPPING)) {
1876 frame->width = avctx->width;
1877 frame->height = avctx->height;
1881 av_frame_unref(frame);
1886 int ff_get_buffer(AVCodecContext *avctx, AVFrame *frame, int flags)
1888 int ret = get_buffer_internal(avctx, frame, flags);
1890 av_log(avctx, AV_LOG_ERROR, "get_buffer() failed\n");
1891 frame->width = frame->height = 0;
1896 static int reget_buffer_internal(AVCodecContext *avctx, AVFrame *frame)
1901 av_assert0(avctx->codec_type == AVMEDIA_TYPE_VIDEO);
1903 if (frame->data[0] && (frame->width != avctx->width || frame->height != avctx->height || frame->format != avctx->pix_fmt)) {
1904 av_log(avctx, AV_LOG_WARNING, "Picture changed from size:%dx%d fmt:%s to size:%dx%d fmt:%s in reget buffer()\n",
1905 frame->width, frame->height, av_get_pix_fmt_name(frame->format), avctx->width, avctx->height, av_get_pix_fmt_name(avctx->pix_fmt));
1906 av_frame_unref(frame);
1909 ff_init_buffer_info(avctx, frame);
1911 if (!frame->data[0])
1912 return ff_get_buffer(avctx, frame, AV_GET_BUFFER_FLAG_REF);
1914 if (av_frame_is_writable(frame))
1915 return ff_decode_frame_props(avctx, frame);
1917 tmp = av_frame_alloc();
1919 return AVERROR(ENOMEM);
1921 av_frame_move_ref(tmp, frame);
1923 ret = ff_get_buffer(avctx, frame, AV_GET_BUFFER_FLAG_REF);
1925 av_frame_free(&tmp);
1929 av_frame_copy(frame, tmp);
1930 av_frame_free(&tmp);
1935 int ff_reget_buffer(AVCodecContext *avctx, AVFrame *frame)
1937 int ret = reget_buffer_internal(avctx, frame);
1939 av_log(avctx, AV_LOG_ERROR, "reget_buffer() failed\n");
1943 void avcodec_flush_buffers(AVCodecContext *avctx)
1945 avctx->internal->draining = 0;
1946 avctx->internal->draining_done = 0;
1947 avctx->internal->nb_draining_errors = 0;
1948 av_frame_unref(avctx->internal->buffer_frame);
1949 av_frame_unref(avctx->internal->compat_decode_frame);
1950 av_packet_unref(avctx->internal->buffer_pkt);
1951 avctx->internal->buffer_pkt_valid = 0;
1953 av_packet_unref(avctx->internal->ds.in_pkt);
1955 if (HAVE_THREADS && avctx->active_thread_type & FF_THREAD_FRAME)
1956 ff_thread_flush(avctx);
1957 else if (avctx->codec->flush)
1958 avctx->codec->flush(avctx);
1960 avctx->pts_correction_last_pts =
1961 avctx->pts_correction_last_dts = INT64_MIN;
1963 ff_decode_bsfs_uninit(avctx);
1965 if (!avctx->refcounted_frames)
1966 av_frame_unref(avctx->internal->to_free);
1969 void ff_decode_bsfs_uninit(AVCodecContext *avctx)
1971 DecodeFilterContext *s = &avctx->internal->filter;
1974 for (i = 0; i < s->nb_bsfs; i++)
1975 av_bsf_free(&s->bsfs[i]);