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"
46 static int apply_param_change(AVCodecContext *avctx, const AVPacket *avpkt)
53 data = av_packet_get_side_data(avpkt, AV_PKT_DATA_PARAM_CHANGE, &size);
57 if (!(avctx->codec->capabilities & AV_CODEC_CAP_PARAM_CHANGE)) {
58 av_log(avctx, AV_LOG_ERROR, "This decoder does not support parameter "
59 "changes, but PARAM_CHANGE side data was sent to it.\n");
60 ret = AVERROR(EINVAL);
67 flags = bytestream_get_le32(&data);
70 if (flags & AV_SIDE_DATA_PARAM_CHANGE_CHANNEL_COUNT) {
73 val = bytestream_get_le32(&data);
74 if (val <= 0 || val > INT_MAX) {
75 av_log(avctx, AV_LOG_ERROR, "Invalid channel count");
76 ret = AVERROR_INVALIDDATA;
79 avctx->channels = val;
82 if (flags & AV_SIDE_DATA_PARAM_CHANGE_CHANNEL_LAYOUT) {
85 avctx->channel_layout = bytestream_get_le64(&data);
88 if (flags & AV_SIDE_DATA_PARAM_CHANGE_SAMPLE_RATE) {
91 val = bytestream_get_le32(&data);
92 if (val <= 0 || val > INT_MAX) {
93 av_log(avctx, AV_LOG_ERROR, "Invalid sample rate");
94 ret = AVERROR_INVALIDDATA;
97 avctx->sample_rate = val;
100 if (flags & AV_SIDE_DATA_PARAM_CHANGE_DIMENSIONS) {
103 avctx->width = bytestream_get_le32(&data);
104 avctx->height = bytestream_get_le32(&data);
106 ret = ff_set_dimensions(avctx, avctx->width, avctx->height);
113 av_log(avctx, AV_LOG_ERROR, "PARAM_CHANGE side data too small.\n");
114 ret = AVERROR_INVALIDDATA;
117 av_log(avctx, AV_LOG_ERROR, "Error applying parameter changes.\n");
118 if (avctx->err_recognition & AV_EF_EXPLODE)
124 static int extract_packet_props(AVCodecInternal *avci, const AVPacket *pkt)
128 av_packet_unref(avci->last_pkt_props);
130 ret = av_packet_copy_props(avci->last_pkt_props, pkt);
132 avci->last_pkt_props->size = pkt->size; // HACK: Needed for ff_init_buffer_info().
137 static int unrefcount_frame(AVCodecInternal *avci, AVFrame *frame)
141 /* move the original frame to our backup */
142 av_frame_unref(avci->to_free);
143 av_frame_move_ref(avci->to_free, frame);
145 /* now copy everything except the AVBufferRefs back
146 * note that we make a COPY of the side data, so calling av_frame_free() on
147 * the caller's frame will work properly */
148 ret = av_frame_copy_props(frame, avci->to_free);
152 memcpy(frame->data, avci->to_free->data, sizeof(frame->data));
153 memcpy(frame->linesize, avci->to_free->linesize, sizeof(frame->linesize));
154 if (avci->to_free->extended_data != avci->to_free->data) {
155 int planes = avci->to_free->channels;
156 int size = planes * sizeof(*frame->extended_data);
159 av_frame_unref(frame);
163 frame->extended_data = av_malloc(size);
164 if (!frame->extended_data) {
165 av_frame_unref(frame);
166 return AVERROR(ENOMEM);
168 memcpy(frame->extended_data, avci->to_free->extended_data,
171 frame->extended_data = frame->data;
173 frame->format = avci->to_free->format;
174 frame->width = avci->to_free->width;
175 frame->height = avci->to_free->height;
176 frame->channel_layout = avci->to_free->channel_layout;
177 frame->nb_samples = avci->to_free->nb_samples;
178 frame->channels = avci->to_free->channels;
183 static int bsfs_init(AVCodecContext *avctx)
185 AVCodecInternal *avci = avctx->internal;
186 DecodeFilterContext *s = &avci->filter;
187 const char *bsfs_str;
193 bsfs_str = avctx->codec->bsfs ? avctx->codec->bsfs : "null";
194 while (bsfs_str && *bsfs_str) {
196 const AVBitStreamFilter *filter;
199 bsf = av_get_token(&bsfs_str, ",");
201 ret = AVERROR(ENOMEM);
205 filter = av_bsf_get_by_name(bsf);
207 av_log(avctx, AV_LOG_ERROR, "A non-existing bitstream filter %s "
208 "requested by a decoder. This is a bug, please report it.\n",
216 tmp = av_realloc_array(s->bsfs, s->nb_bsfs + 1, sizeof(*s->bsfs));
218 ret = AVERROR(ENOMEM);
224 ret = av_bsf_alloc(filter, &s->bsfs[s->nb_bsfs - 1]);
228 if (s->nb_bsfs == 1) {
229 /* We do not currently have an API for passing the input timebase into decoders,
230 * but no filters used here should actually need it.
231 * So we make up some plausible-looking number (the MPEG 90kHz timebase) */
232 s->bsfs[s->nb_bsfs - 1]->time_base_in = (AVRational){ 1, 90000 };
233 ret = avcodec_parameters_from_context(s->bsfs[s->nb_bsfs - 1]->par_in,
236 s->bsfs[s->nb_bsfs - 1]->time_base_in = s->bsfs[s->nb_bsfs - 2]->time_base_out;
237 ret = avcodec_parameters_copy(s->bsfs[s->nb_bsfs - 1]->par_in,
238 s->bsfs[s->nb_bsfs - 2]->par_out);
243 ret = av_bsf_init(s->bsfs[s->nb_bsfs - 1]);
250 ff_decode_bsfs_uninit(avctx);
254 /* try to get one output packet from the filter chain */
255 static int bsfs_poll(AVCodecContext *avctx, AVPacket *pkt)
257 DecodeFilterContext *s = &avctx->internal->filter;
260 /* start with the last filter in the chain */
261 idx = s->nb_bsfs - 1;
263 /* request a packet from the currently selected filter */
264 ret = av_bsf_receive_packet(s->bsfs[idx], pkt);
265 if (ret == AVERROR(EAGAIN)) {
266 /* no packets available, try the next filter up the chain */
270 } else if (ret < 0 && ret != AVERROR_EOF) {
274 /* got a packet or EOF -- pass it to the caller or to the next filter
276 if (idx == s->nb_bsfs - 1) {
280 ret = av_bsf_send_packet(s->bsfs[idx], ret < 0 ? NULL : pkt);
282 av_log(avctx, AV_LOG_ERROR,
283 "Error pre-processing a packet before decoding\n");
284 av_packet_unref(pkt);
290 return AVERROR(EAGAIN);
293 int ff_decode_get_packet(AVCodecContext *avctx, AVPacket *pkt)
295 AVCodecInternal *avci = avctx->internal;
301 ret = bsfs_poll(avctx, pkt);
302 if (ret == AVERROR_EOF)
307 ret = extract_packet_props(avctx->internal, pkt);
311 ret = apply_param_change(avctx, pkt);
315 if (avctx->codec->receive_frame)
316 avci->compat_decode_consumed += pkt->size;
320 av_packet_unref(pkt);
325 * Attempt to guess proper monotonic timestamps for decoded video frames
326 * which might have incorrect times. Input timestamps may wrap around, in
327 * which case the output will as well.
329 * @param pts the pts field of the decoded AVPacket, as passed through
331 * @param dts the dts field of the decoded AVPacket
332 * @return one of the input values, may be AV_NOPTS_VALUE
334 static int64_t guess_correct_pts(AVCodecContext *ctx,
335 int64_t reordered_pts, int64_t dts)
337 int64_t pts = AV_NOPTS_VALUE;
339 if (dts != AV_NOPTS_VALUE) {
340 ctx->pts_correction_num_faulty_dts += dts <= ctx->pts_correction_last_dts;
341 ctx->pts_correction_last_dts = dts;
342 } else if (reordered_pts != AV_NOPTS_VALUE)
343 ctx->pts_correction_last_dts = reordered_pts;
345 if (reordered_pts != AV_NOPTS_VALUE) {
346 ctx->pts_correction_num_faulty_pts += reordered_pts <= ctx->pts_correction_last_pts;
347 ctx->pts_correction_last_pts = reordered_pts;
348 } else if(dts != AV_NOPTS_VALUE)
349 ctx->pts_correction_last_pts = dts;
351 if ((ctx->pts_correction_num_faulty_pts<=ctx->pts_correction_num_faulty_dts || dts == AV_NOPTS_VALUE)
352 && reordered_pts != AV_NOPTS_VALUE)
361 * The core of the receive_frame_wrapper for the decoders implementing
362 * the simple API. Certain decoders might consume partial packets without
363 * returning any output, so this function needs to be called in a loop until it
366 static int decode_simple_internal(AVCodecContext *avctx, AVFrame *frame)
368 AVCodecInternal *avci = avctx->internal;
369 DecodeSimpleContext *ds = &avci->ds;
370 AVPacket *pkt = ds->in_pkt;
371 // copy to ensure we do not change pkt
372 int got_frame, actual_got_frame;
375 if (!pkt->data && !avci->draining) {
376 av_packet_unref(pkt);
377 ret = ff_decode_get_packet(avctx, pkt);
378 if (ret < 0 && ret != AVERROR_EOF)
382 // Some codecs (at least wma lossless) will crash when feeding drain packets
383 // after EOF was signaled.
384 if (avci->draining_done)
388 !(avctx->codec->capabilities & AV_CODEC_CAP_DELAY ||
389 avctx->active_thread_type & FF_THREAD_FRAME))
394 if (HAVE_THREADS && avctx->active_thread_type & FF_THREAD_FRAME) {
395 ret = ff_thread_decode_frame(avctx, frame, &got_frame, pkt);
397 ret = avctx->codec->decode(avctx, frame, &got_frame, pkt);
399 if (!(avctx->codec->caps_internal & FF_CODEC_CAP_SETS_PKT_DTS))
400 frame->pkt_dts = pkt->dts;
401 if (avctx->codec->type == AVMEDIA_TYPE_VIDEO) {
402 if(!avctx->has_b_frames)
403 frame->pkt_pos = pkt->pos;
404 //FIXME these should be under if(!avctx->has_b_frames)
405 /* get_buffer is supposed to set frame parameters */
406 if (!(avctx->codec->capabilities & AV_CODEC_CAP_DR1)) {
407 if (!frame->sample_aspect_ratio.num) frame->sample_aspect_ratio = avctx->sample_aspect_ratio;
408 if (!frame->width) frame->width = avctx->width;
409 if (!frame->height) frame->height = avctx->height;
410 if (frame->format == AV_PIX_FMT_NONE) frame->format = avctx->pix_fmt;
415 actual_got_frame = got_frame;
417 if (avctx->codec->type == AVMEDIA_TYPE_VIDEO) {
418 if (frame->flags & AV_FRAME_FLAG_DISCARD)
421 frame->best_effort_timestamp = guess_correct_pts(avctx,
424 } else if (avctx->codec->type == AVMEDIA_TYPE_AUDIO) {
427 uint32_t discard_padding = 0;
428 uint8_t skip_reason = 0;
429 uint8_t discard_reason = 0;
431 if (ret >= 0 && got_frame) {
432 frame->best_effort_timestamp = guess_correct_pts(avctx,
435 if (frame->format == AV_SAMPLE_FMT_NONE)
436 frame->format = avctx->sample_fmt;
437 if (!frame->channel_layout)
438 frame->channel_layout = avctx->channel_layout;
439 if (!frame->channels)
440 frame->channels = avctx->channels;
441 if (!frame->sample_rate)
442 frame->sample_rate = avctx->sample_rate;
445 side= av_packet_get_side_data(avci->last_pkt_props, AV_PKT_DATA_SKIP_SAMPLES, &side_size);
446 if(side && side_size>=10) {
447 avctx->internal->skip_samples = AV_RL32(side) * avctx->internal->skip_samples_multiplier;
448 discard_padding = AV_RL32(side + 4);
449 av_log(avctx, AV_LOG_DEBUG, "skip %d / discard %d samples due to side data\n",
450 avctx->internal->skip_samples, (int)discard_padding);
451 skip_reason = AV_RL8(side + 8);
452 discard_reason = AV_RL8(side + 9);
455 if ((frame->flags & AV_FRAME_FLAG_DISCARD) && got_frame &&
456 !(avctx->flags2 & AV_CODEC_FLAG2_SKIP_MANUAL)) {
457 avctx->internal->skip_samples = FFMAX(0, avctx->internal->skip_samples - frame->nb_samples);
461 if (avctx->internal->skip_samples > 0 && got_frame &&
462 !(avctx->flags2 & AV_CODEC_FLAG2_SKIP_MANUAL)) {
463 if(frame->nb_samples <= avctx->internal->skip_samples){
465 avctx->internal->skip_samples -= frame->nb_samples;
466 av_log(avctx, AV_LOG_DEBUG, "skip whole frame, skip left: %d\n",
467 avctx->internal->skip_samples);
469 av_samples_copy(frame->extended_data, frame->extended_data, 0, avctx->internal->skip_samples,
470 frame->nb_samples - avctx->internal->skip_samples, avctx->channels, frame->format);
471 if(avctx->pkt_timebase.num && avctx->sample_rate) {
472 int64_t diff_ts = av_rescale_q(avctx->internal->skip_samples,
473 (AVRational){1, avctx->sample_rate},
474 avctx->pkt_timebase);
475 if(frame->pts!=AV_NOPTS_VALUE)
476 frame->pts += diff_ts;
478 FF_DISABLE_DEPRECATION_WARNINGS
479 if(frame->pkt_pts!=AV_NOPTS_VALUE)
480 frame->pkt_pts += diff_ts;
481 FF_ENABLE_DEPRECATION_WARNINGS
483 if(frame->pkt_dts!=AV_NOPTS_VALUE)
484 frame->pkt_dts += diff_ts;
485 if (frame->pkt_duration >= diff_ts)
486 frame->pkt_duration -= diff_ts;
488 av_log(avctx, AV_LOG_WARNING, "Could not update timestamps for skipped samples.\n");
490 av_log(avctx, AV_LOG_DEBUG, "skip %d/%d samples\n",
491 avctx->internal->skip_samples, frame->nb_samples);
492 frame->nb_samples -= avctx->internal->skip_samples;
493 avctx->internal->skip_samples = 0;
497 if (discard_padding > 0 && discard_padding <= frame->nb_samples && got_frame &&
498 !(avctx->flags2 & AV_CODEC_FLAG2_SKIP_MANUAL)) {
499 if (discard_padding == frame->nb_samples) {
502 if(avctx->pkt_timebase.num && avctx->sample_rate) {
503 int64_t diff_ts = av_rescale_q(frame->nb_samples - discard_padding,
504 (AVRational){1, avctx->sample_rate},
505 avctx->pkt_timebase);
506 frame->pkt_duration = diff_ts;
508 av_log(avctx, AV_LOG_WARNING, "Could not update timestamps for discarded samples.\n");
510 av_log(avctx, AV_LOG_DEBUG, "discard %d/%d samples\n",
511 (int)discard_padding, frame->nb_samples);
512 frame->nb_samples -= discard_padding;
516 if ((avctx->flags2 & AV_CODEC_FLAG2_SKIP_MANUAL) && got_frame) {
517 AVFrameSideData *fside = av_frame_new_side_data(frame, AV_FRAME_DATA_SKIP_SAMPLES, 10);
519 AV_WL32(fside->data, avctx->internal->skip_samples);
520 AV_WL32(fside->data + 4, discard_padding);
521 AV_WL8(fside->data + 8, skip_reason);
522 AV_WL8(fside->data + 9, discard_reason);
523 avctx->internal->skip_samples = 0;
528 if (avctx->codec->type == AVMEDIA_TYPE_AUDIO &&
529 !avci->showed_multi_packet_warning &&
530 ret >= 0 && ret != pkt->size && !(avctx->codec->capabilities & AV_CODEC_CAP_SUBFRAMES)) {
531 av_log(avctx, AV_LOG_WARNING, "Multiple frames in a packet.\n");
532 avci->showed_multi_packet_warning = 1;
536 av_frame_unref(frame);
538 if (ret >= 0 && avctx->codec->type == AVMEDIA_TYPE_VIDEO && !(avctx->flags & AV_CODEC_FLAG_TRUNCATED))
541 #if FF_API_AVCTX_TIMEBASE
542 if (avctx->framerate.num > 0 && avctx->framerate.den > 0)
543 avctx->time_base = av_inv_q(av_mul_q(avctx->framerate, (AVRational){avctx->ticks_per_frame, 1}));
546 /* do not stop draining when actual_got_frame != 0 or ret < 0 */
547 /* got_frame == 0 but actual_got_frame != 0 when frame is discarded */
548 if (avctx->internal->draining && !actual_got_frame) {
550 /* prevent infinite loop if a decoder wrongly always return error on draining */
551 /* reasonable nb_errors_max = maximum b frames + thread count */
552 int nb_errors_max = 20 + (HAVE_THREADS && avctx->active_thread_type & FF_THREAD_FRAME ?
553 avctx->thread_count : 1);
555 if (avci->nb_draining_errors++ >= nb_errors_max) {
556 av_log(avctx, AV_LOG_ERROR, "Too many errors when draining, this is a bug. "
557 "Stop draining and force EOF.\n");
558 avci->draining_done = 1;
562 avci->draining_done = 1;
566 avci->compat_decode_consumed += ret;
568 if (ret >= pkt->size || ret < 0) {
569 av_packet_unref(pkt);
573 pkt->data += consumed;
574 pkt->size -= consumed;
575 avci->last_pkt_props->size -= consumed; // See extract_packet_props() comment.
576 pkt->pts = AV_NOPTS_VALUE;
577 pkt->dts = AV_NOPTS_VALUE;
578 avci->last_pkt_props->pts = AV_NOPTS_VALUE;
579 avci->last_pkt_props->dts = AV_NOPTS_VALUE;
583 av_assert0(frame->buf[0]);
585 return ret < 0 ? ret : 0;
588 static int decode_simple_receive_frame(AVCodecContext *avctx, AVFrame *frame)
592 while (!frame->buf[0]) {
593 ret = decode_simple_internal(avctx, frame);
601 static int decode_receive_frame_internal(AVCodecContext *avctx, AVFrame *frame)
603 AVCodecInternal *avci = avctx->internal;
606 av_assert0(!frame->buf[0]);
608 if (avctx->codec->receive_frame)
609 ret = avctx->codec->receive_frame(avctx, frame);
611 ret = decode_simple_receive_frame(avctx, frame);
613 if (ret == AVERROR_EOF)
614 avci->draining_done = 1;
616 /* free the per-frame decode data */
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 av_buffer_unref(&frame->private_ref);
629 int attribute_align_arg avcodec_send_packet(AVCodecContext *avctx, const AVPacket *avpkt)
631 AVCodecInternal *avci = avctx->internal;
634 if (!avcodec_is_open(avctx) || !av_codec_is_decoder(avctx->codec))
635 return AVERROR(EINVAL);
637 if (avctx->internal->draining)
640 if (avpkt && !avpkt->size && avpkt->data)
641 return AVERROR(EINVAL);
643 ret = bsfs_init(avctx);
647 av_packet_unref(avci->buffer_pkt);
648 if (avpkt && (avpkt->data || avpkt->side_data_elems)) {
649 ret = av_packet_ref(avci->buffer_pkt, avpkt);
654 ret = av_bsf_send_packet(avci->filter.bsfs[0], avci->buffer_pkt);
656 av_packet_unref(avci->buffer_pkt);
660 if (!avci->buffer_frame->buf[0]) {
661 ret = decode_receive_frame_internal(avctx, avci->buffer_frame);
662 if (ret < 0 && ret != AVERROR(EAGAIN) && ret != AVERROR_EOF)
669 static int apply_cropping(AVCodecContext *avctx, AVFrame *frame)
671 /* make sure we are noisy about decoders returning invalid cropping data */
672 if (frame->crop_left >= INT_MAX - frame->crop_right ||
673 frame->crop_top >= INT_MAX - frame->crop_bottom ||
674 (frame->crop_left + frame->crop_right) >= frame->width ||
675 (frame->crop_top + frame->crop_bottom) >= frame->height) {
676 av_log(avctx, AV_LOG_WARNING,
677 "Invalid cropping information set by a decoder: "
678 "%"SIZE_SPECIFIER"/%"SIZE_SPECIFIER"/%"SIZE_SPECIFIER"/%"SIZE_SPECIFIER" "
679 "(frame size %dx%d). This is a bug, please report it\n",
680 frame->crop_left, frame->crop_right, frame->crop_top, frame->crop_bottom,
681 frame->width, frame->height);
682 frame->crop_left = 0;
683 frame->crop_right = 0;
685 frame->crop_bottom = 0;
689 if (!avctx->apply_cropping)
692 return av_frame_apply_cropping(frame, avctx->flags & AV_CODEC_FLAG_UNALIGNED ?
693 AV_FRAME_CROP_UNALIGNED : 0);
696 int attribute_align_arg avcodec_receive_frame(AVCodecContext *avctx, AVFrame *frame)
698 AVCodecInternal *avci = avctx->internal;
701 av_frame_unref(frame);
703 if (!avcodec_is_open(avctx) || !av_codec_is_decoder(avctx->codec))
704 return AVERROR(EINVAL);
706 ret = bsfs_init(avctx);
710 if (avci->buffer_frame->buf[0]) {
711 av_frame_move_ref(frame, avci->buffer_frame);
713 ret = decode_receive_frame_internal(avctx, frame);
718 if (avctx->codec_type == AVMEDIA_TYPE_VIDEO) {
719 ret = apply_cropping(avctx, frame);
721 av_frame_unref(frame);
726 avctx->frame_number++;
731 static int compat_decode(AVCodecContext *avctx, AVFrame *frame,
732 int *got_frame, const AVPacket *pkt)
734 AVCodecInternal *avci = avctx->internal;
737 av_assert0(avci->compat_decode_consumed == 0);
740 avci->compat_decode = 1;
742 if (avci->compat_decode_partial_size > 0 &&
743 avci->compat_decode_partial_size != pkt->size) {
744 av_log(avctx, AV_LOG_ERROR,
745 "Got unexpected packet size after a partial decode\n");
746 ret = AVERROR(EINVAL);
750 if (!avci->compat_decode_partial_size) {
751 ret = avcodec_send_packet(avctx, pkt);
752 if (ret == AVERROR_EOF)
754 else if (ret == AVERROR(EAGAIN)) {
755 /* we fully drain all the output in each decode call, so this should not
764 ret = avcodec_receive_frame(avctx, frame);
766 if (ret == AVERROR(EAGAIN) || ret == AVERROR_EOF)
771 if (frame != avci->compat_decode_frame) {
772 if (!avctx->refcounted_frames) {
773 ret = unrefcount_frame(avci, frame);
779 frame = avci->compat_decode_frame;
781 if (!avci->compat_decode_warned) {
782 av_log(avctx, AV_LOG_WARNING, "The deprecated avcodec_decode_* "
783 "API cannot return all the frames for this decoder. "
784 "Some frames will be dropped. Update your code to the "
785 "new decoding API to fix this.\n");
786 avci->compat_decode_warned = 1;
790 if (avci->draining || (!avctx->codec->bsfs && avci->compat_decode_consumed < pkt->size))
796 /* if there are any bsfs then assume full packet is always consumed */
797 if (avctx->codec->bsfs)
800 ret = FFMIN(avci->compat_decode_consumed, pkt->size);
802 avci->compat_decode_consumed = 0;
803 avci->compat_decode_partial_size = (ret >= 0) ? pkt->size - ret : 0;
808 int attribute_align_arg avcodec_decode_video2(AVCodecContext *avctx, AVFrame *picture,
809 int *got_picture_ptr,
810 const AVPacket *avpkt)
812 return compat_decode(avctx, picture, got_picture_ptr, avpkt);
815 int attribute_align_arg avcodec_decode_audio4(AVCodecContext *avctx,
818 const AVPacket *avpkt)
820 return compat_decode(avctx, frame, got_frame_ptr, avpkt);
823 static void get_subtitle_defaults(AVSubtitle *sub)
825 memset(sub, 0, sizeof(*sub));
826 sub->pts = AV_NOPTS_VALUE;
829 #define UTF8_MAX_BYTES 4 /* 5 and 6 bytes sequences should not be used */
830 static int recode_subtitle(AVCodecContext *avctx,
831 AVPacket *outpkt, const AVPacket *inpkt)
834 iconv_t cd = (iconv_t)-1;
841 if (avctx->sub_charenc_mode != FF_SUB_CHARENC_MODE_PRE_DECODER || inpkt->size == 0)
845 cd = iconv_open("UTF-8", avctx->sub_charenc);
846 av_assert0(cd != (iconv_t)-1);
851 if (inl >= INT_MAX / UTF8_MAX_BYTES - AV_INPUT_BUFFER_PADDING_SIZE) {
852 av_log(avctx, AV_LOG_ERROR, "Subtitles packet is too big for recoding\n");
853 ret = AVERROR(ENOMEM);
857 ret = av_new_packet(&tmp, inl * UTF8_MAX_BYTES);
860 outpkt->buf = tmp.buf;
861 outpkt->data = tmp.data;
862 outpkt->size = tmp.size;
866 if (iconv(cd, &inb, &inl, &outb, &outl) == (size_t)-1 ||
867 iconv(cd, NULL, NULL, &outb, &outl) == (size_t)-1 ||
868 outl >= outpkt->size || inl != 0) {
869 ret = FFMIN(AVERROR(errno), -1);
870 av_log(avctx, AV_LOG_ERROR, "Unable to recode subtitle event \"%s\" "
871 "from %s to UTF-8\n", inpkt->data, avctx->sub_charenc);
872 av_packet_unref(&tmp);
875 outpkt->size -= outl;
876 memset(outpkt->data + outpkt->size, 0, outl);
879 if (cd != (iconv_t)-1)
883 av_log(avctx, AV_LOG_ERROR, "requesting subtitles recoding without iconv");
884 return AVERROR(EINVAL);
888 static int utf8_check(const uint8_t *str)
891 uint32_t codepoint, min;
895 GET_UTF8(codepoint, *(byte++), return 0;);
896 min = byte - str == 1 ? 0 : byte - str == 2 ? 0x80 :
897 1 << (5 * (byte - str) - 4);
898 if (codepoint < min || codepoint >= 0x110000 ||
899 codepoint == 0xFFFE /* BOM */ ||
900 codepoint >= 0xD800 && codepoint <= 0xDFFF /* surrogates */)
907 #if FF_API_ASS_TIMING
908 static void insert_ts(AVBPrint *buf, int ts)
911 av_bprintf(buf, "9:59:59.99,");
915 h = ts/360000; ts -= 360000*h;
916 m = ts/ 6000; ts -= 6000*m;
917 s = ts/ 100; ts -= 100*s;
918 av_bprintf(buf, "%d:%02d:%02d.%02d,", h, m, s, ts);
922 static int convert_sub_to_old_ass_form(AVSubtitle *sub, const AVPacket *pkt, AVRational tb)
927 av_bprint_init(&buf, 0, AV_BPRINT_SIZE_UNLIMITED);
929 for (i = 0; i < sub->num_rects; i++) {
932 AVSubtitleRect *rect = sub->rects[i];
933 int ts_start, ts_duration = -1;
936 if (rect->type != SUBTITLE_ASS || !strncmp(rect->ass, "Dialogue: ", 10))
939 av_bprint_clear(&buf);
942 dialog = strchr(rect->ass, ',');
947 /* extract Layer or Marked */
948 layer = strtol(dialog, (char**)&dialog, 10);
953 /* rescale timing to ASS time base (ms) */
954 ts_start = av_rescale_q(pkt->pts, tb, av_make_q(1, 100));
955 if (pkt->duration != -1)
956 ts_duration = av_rescale_q(pkt->duration, tb, av_make_q(1, 100));
957 sub->end_display_time = FFMAX(sub->end_display_time, 10 * ts_duration);
959 /* construct ASS (standalone file form with timestamps) string */
960 av_bprintf(&buf, "Dialogue: %ld,", layer);
961 insert_ts(&buf, ts_start);
962 insert_ts(&buf, ts_duration == -1 ? -1 : ts_start + ts_duration);
963 av_bprintf(&buf, "%s\r\n", dialog);
965 final_dialog = av_strdup(buf.str);
966 if (!av_bprint_is_complete(&buf) || !final_dialog) {
967 av_freep(&final_dialog);
968 av_bprint_finalize(&buf, NULL);
969 return AVERROR(ENOMEM);
971 av_freep(&rect->ass);
972 rect->ass = final_dialog;
975 av_bprint_finalize(&buf, NULL);
980 int avcodec_decode_subtitle2(AVCodecContext *avctx, AVSubtitle *sub,
986 if (!avpkt->data && avpkt->size) {
987 av_log(avctx, AV_LOG_ERROR, "invalid packet: NULL data, size != 0\n");
988 return AVERROR(EINVAL);
991 return AVERROR(EINVAL);
992 if (avctx->codec->type != AVMEDIA_TYPE_SUBTITLE) {
993 av_log(avctx, AV_LOG_ERROR, "Invalid media type for subtitles\n");
994 return AVERROR(EINVAL);
998 get_subtitle_defaults(sub);
1000 if ((avctx->codec->capabilities & AV_CODEC_CAP_DELAY) || avpkt->size) {
1001 AVPacket pkt_recoded = *avpkt;
1003 ret = recode_subtitle(avctx, &pkt_recoded, avpkt);
1007 ret = extract_packet_props(avctx->internal, &pkt_recoded);
1011 if (avctx->pkt_timebase.num && avpkt->pts != AV_NOPTS_VALUE)
1012 sub->pts = av_rescale_q(avpkt->pts,
1013 avctx->pkt_timebase, AV_TIME_BASE_Q);
1014 ret = avctx->codec->decode(avctx, sub, got_sub_ptr, &pkt_recoded);
1015 av_assert1((ret >= 0) >= !!*got_sub_ptr &&
1016 !!*got_sub_ptr >= !!sub->num_rects);
1018 #if FF_API_ASS_TIMING
1019 if (avctx->sub_text_format == FF_SUB_TEXT_FMT_ASS_WITH_TIMINGS
1020 && *got_sub_ptr && sub->num_rects) {
1021 const AVRational tb = avctx->pkt_timebase.num ? avctx->pkt_timebase
1023 int err = convert_sub_to_old_ass_form(sub, avpkt, tb);
1029 if (sub->num_rects && !sub->end_display_time && avpkt->duration &&
1030 avctx->pkt_timebase.num) {
1031 AVRational ms = { 1, 1000 };
1032 sub->end_display_time = av_rescale_q(avpkt->duration,
1033 avctx->pkt_timebase, ms);
1036 if (avctx->codec_descriptor->props & AV_CODEC_PROP_BITMAP_SUB)
1038 else if (avctx->codec_descriptor->props & AV_CODEC_PROP_TEXT_SUB)
1041 for (i = 0; i < sub->num_rects; i++) {
1042 if (sub->rects[i]->ass && !utf8_check(sub->rects[i]->ass)) {
1043 av_log(avctx, AV_LOG_ERROR,
1044 "Invalid UTF-8 in decoded subtitles text; "
1045 "maybe missing -sub_charenc option\n");
1046 avsubtitle_free(sub);
1047 ret = AVERROR_INVALIDDATA;
1052 if (avpkt->data != pkt_recoded.data) { // did we recode?
1053 /* prevent from destroying side data from original packet */
1054 pkt_recoded.side_data = NULL;
1055 pkt_recoded.side_data_elems = 0;
1057 av_packet_unref(&pkt_recoded);
1062 avctx->frame_number++;
1068 static int is_hwaccel_pix_fmt(enum AVPixelFormat pix_fmt)
1070 const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(pix_fmt);
1071 return desc->flags & AV_PIX_FMT_FLAG_HWACCEL;
1074 enum AVPixelFormat avcodec_default_get_format(struct AVCodecContext *s, const enum AVPixelFormat *fmt)
1076 while (*fmt != AV_PIX_FMT_NONE && is_hwaccel_pix_fmt(*fmt))
1081 static AVHWAccel *find_hwaccel(enum AVCodecID codec_id,
1082 enum AVPixelFormat pix_fmt)
1084 AVHWAccel *hwaccel = NULL;
1086 while ((hwaccel = av_hwaccel_next(hwaccel)))
1087 if (hwaccel->id == codec_id
1088 && hwaccel->pix_fmt == pix_fmt)
1093 static int setup_hwaccel(AVCodecContext *avctx,
1094 const enum AVPixelFormat fmt,
1097 AVHWAccel *hwa = find_hwaccel(avctx->codec_id, fmt);
1101 av_log(avctx, AV_LOG_ERROR,
1102 "Could not find an AVHWAccel for the pixel format: %s",
1104 return AVERROR(ENOENT);
1107 if (hwa->capabilities & AV_HWACCEL_CODEC_CAP_EXPERIMENTAL &&
1108 avctx->strict_std_compliance > FF_COMPLIANCE_EXPERIMENTAL) {
1109 av_log(avctx, AV_LOG_WARNING, "Ignoring experimental hwaccel: %s\n",
1111 return AVERROR_PATCHWELCOME;
1114 if (hwa->priv_data_size) {
1115 avctx->internal->hwaccel_priv_data = av_mallocz(hwa->priv_data_size);
1116 if (!avctx->internal->hwaccel_priv_data)
1117 return AVERROR(ENOMEM);
1120 avctx->hwaccel = hwa;
1122 ret = hwa->init(avctx);
1124 av_freep(&avctx->internal->hwaccel_priv_data);
1125 avctx->hwaccel = NULL;
1133 int ff_get_format(AVCodecContext *avctx, const enum AVPixelFormat *fmt)
1135 const AVPixFmtDescriptor *desc;
1136 enum AVPixelFormat *choices;
1137 enum AVPixelFormat ret;
1140 while (fmt[n] != AV_PIX_FMT_NONE)
1144 avctx->sw_pix_fmt = fmt[n - 1];
1145 av_assert2(!is_hwaccel_pix_fmt(avctx->sw_pix_fmt));
1147 choices = av_malloc_array(n + 1, sizeof(*choices));
1149 return AV_PIX_FMT_NONE;
1151 memcpy(choices, fmt, (n + 1) * sizeof(*choices));
1154 if (avctx->hwaccel && avctx->hwaccel->uninit)
1155 avctx->hwaccel->uninit(avctx);
1156 av_freep(&avctx->internal->hwaccel_priv_data);
1157 avctx->hwaccel = NULL;
1159 av_buffer_unref(&avctx->hw_frames_ctx);
1161 ret = avctx->get_format(avctx, choices);
1163 desc = av_pix_fmt_desc_get(ret);
1165 ret = AV_PIX_FMT_NONE;
1169 if (!(desc->flags & AV_PIX_FMT_FLAG_HWACCEL))
1172 if (avctx->hw_frames_ctx) {
1173 AVHWFramesContext *hw_frames_ctx = (AVHWFramesContext*)avctx->hw_frames_ctx->data;
1174 if (hw_frames_ctx->format != ret) {
1175 av_log(avctx, AV_LOG_ERROR, "Format returned from get_buffer() "
1176 "does not match the format of provided AVHWFramesContext\n");
1177 ret = AV_PIX_FMT_NONE;
1182 if (!setup_hwaccel(avctx, ret, desc->name))
1185 /* Remove failed hwaccel from choices */
1186 for (n = 0; choices[n] != ret; n++)
1187 av_assert0(choices[n] != AV_PIX_FMT_NONE);
1190 choices[n] = choices[n + 1];
1191 while (choices[n++] != AV_PIX_FMT_NONE);
1198 static int update_frame_pool(AVCodecContext *avctx, AVFrame *frame)
1200 FramePool *pool = avctx->internal->pool;
1203 switch (avctx->codec_type) {
1204 case AVMEDIA_TYPE_VIDEO: {
1207 int size[4] = { 0 };
1208 int w = frame->width;
1209 int h = frame->height;
1210 int tmpsize, unaligned;
1212 if (pool->format == frame->format &&
1213 pool->width == frame->width && pool->height == frame->height)
1216 avcodec_align_dimensions2(avctx, &w, &h, pool->stride_align);
1219 // NOTE: do not align linesizes individually, this breaks e.g. assumptions
1220 // that linesize[0] == 2*linesize[1] in the MPEG-encoder for 4:2:2
1221 ret = av_image_fill_linesizes(linesize, avctx->pix_fmt, w);
1224 // increase alignment of w for next try (rhs gives the lowest bit set in w)
1228 for (i = 0; i < 4; i++)
1229 unaligned |= linesize[i] % pool->stride_align[i];
1230 } while (unaligned);
1232 tmpsize = av_image_fill_pointers(data, avctx->pix_fmt, h,
1237 for (i = 0; i < 3 && data[i + 1]; i++)
1238 size[i] = data[i + 1] - data[i];
1239 size[i] = tmpsize - (data[i] - data[0]);
1241 for (i = 0; i < 4; i++) {
1242 av_buffer_pool_uninit(&pool->pools[i]);
1243 pool->linesize[i] = linesize[i];
1245 pool->pools[i] = av_buffer_pool_init(size[i] + 16 + STRIDE_ALIGN - 1,
1246 CONFIG_MEMORY_POISONING ?
1249 if (!pool->pools[i]) {
1250 ret = AVERROR(ENOMEM);
1255 pool->format = frame->format;
1256 pool->width = frame->width;
1257 pool->height = frame->height;
1261 case AVMEDIA_TYPE_AUDIO: {
1262 int ch = frame->channels; //av_get_channel_layout_nb_channels(frame->channel_layout);
1263 int planar = av_sample_fmt_is_planar(frame->format);
1264 int planes = planar ? ch : 1;
1266 if (pool->format == frame->format && pool->planes == planes &&
1267 pool->channels == ch && frame->nb_samples == pool->samples)
1270 av_buffer_pool_uninit(&pool->pools[0]);
1271 ret = av_samples_get_buffer_size(&pool->linesize[0], ch,
1272 frame->nb_samples, frame->format, 0);
1276 pool->pools[0] = av_buffer_pool_init(pool->linesize[0], NULL);
1277 if (!pool->pools[0]) {
1278 ret = AVERROR(ENOMEM);
1282 pool->format = frame->format;
1283 pool->planes = planes;
1284 pool->channels = ch;
1285 pool->samples = frame->nb_samples;
1288 default: av_assert0(0);
1292 for (i = 0; i < 4; i++)
1293 av_buffer_pool_uninit(&pool->pools[i]);
1295 pool->planes = pool->channels = pool->samples = 0;
1296 pool->width = pool->height = 0;
1300 static int audio_get_buffer(AVCodecContext *avctx, AVFrame *frame)
1302 FramePool *pool = avctx->internal->pool;
1303 int planes = pool->planes;
1306 frame->linesize[0] = pool->linesize[0];
1308 if (planes > AV_NUM_DATA_POINTERS) {
1309 frame->extended_data = av_mallocz_array(planes, sizeof(*frame->extended_data));
1310 frame->nb_extended_buf = planes - AV_NUM_DATA_POINTERS;
1311 frame->extended_buf = av_mallocz_array(frame->nb_extended_buf,
1312 sizeof(*frame->extended_buf));
1313 if (!frame->extended_data || !frame->extended_buf) {
1314 av_freep(&frame->extended_data);
1315 av_freep(&frame->extended_buf);
1316 return AVERROR(ENOMEM);
1319 frame->extended_data = frame->data;
1320 av_assert0(frame->nb_extended_buf == 0);
1323 for (i = 0; i < FFMIN(planes, AV_NUM_DATA_POINTERS); i++) {
1324 frame->buf[i] = av_buffer_pool_get(pool->pools[0]);
1327 frame->extended_data[i] = frame->data[i] = frame->buf[i]->data;
1329 for (i = 0; i < frame->nb_extended_buf; i++) {
1330 frame->extended_buf[i] = av_buffer_pool_get(pool->pools[0]);
1331 if (!frame->extended_buf[i])
1333 frame->extended_data[i + AV_NUM_DATA_POINTERS] = frame->extended_buf[i]->data;
1336 if (avctx->debug & FF_DEBUG_BUFFERS)
1337 av_log(avctx, AV_LOG_DEBUG, "default_get_buffer called on frame %p", frame);
1341 av_frame_unref(frame);
1342 return AVERROR(ENOMEM);
1345 static int video_get_buffer(AVCodecContext *s, AVFrame *pic)
1347 FramePool *pool = s->internal->pool;
1348 const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(pic->format);
1351 if (pic->data[0] || pic->data[1] || pic->data[2] || pic->data[3]) {
1352 av_log(s, AV_LOG_ERROR, "pic->data[*]!=NULL in avcodec_default_get_buffer\n");
1357 av_log(s, AV_LOG_ERROR,
1358 "Unable to get pixel format descriptor for format %s\n",
1359 av_get_pix_fmt_name(pic->format));
1360 return AVERROR(EINVAL);
1363 memset(pic->data, 0, sizeof(pic->data));
1364 pic->extended_data = pic->data;
1366 for (i = 0; i < 4 && pool->pools[i]; i++) {
1367 pic->linesize[i] = pool->linesize[i];
1369 pic->buf[i] = av_buffer_pool_get(pool->pools[i]);
1373 pic->data[i] = pic->buf[i]->data;
1375 for (; i < AV_NUM_DATA_POINTERS; i++) {
1376 pic->data[i] = NULL;
1377 pic->linesize[i] = 0;
1379 if (desc->flags & AV_PIX_FMT_FLAG_PAL ||
1380 desc->flags & AV_PIX_FMT_FLAG_PSEUDOPAL)
1381 avpriv_set_systematic_pal2((uint32_t *)pic->data[1], pic->format);
1383 if (s->debug & FF_DEBUG_BUFFERS)
1384 av_log(s, AV_LOG_DEBUG, "default_get_buffer called on pic %p\n", pic);
1388 av_frame_unref(pic);
1389 return AVERROR(ENOMEM);
1392 int avcodec_default_get_buffer2(AVCodecContext *avctx, AVFrame *frame, int flags)
1396 if (avctx->hw_frames_ctx) {
1397 ret = av_hwframe_get_buffer(avctx->hw_frames_ctx, frame, 0);
1398 frame->width = avctx->coded_width;
1399 frame->height = avctx->coded_height;
1403 if ((ret = update_frame_pool(avctx, frame)) < 0)
1406 switch (avctx->codec_type) {
1407 case AVMEDIA_TYPE_VIDEO:
1408 return video_get_buffer(avctx, frame);
1409 case AVMEDIA_TYPE_AUDIO:
1410 return audio_get_buffer(avctx, frame);
1416 static int add_metadata_from_side_data(const AVPacket *avpkt, AVFrame *frame)
1419 const uint8_t *side_metadata;
1421 AVDictionary **frame_md = &frame->metadata;
1423 side_metadata = av_packet_get_side_data(avpkt,
1424 AV_PKT_DATA_STRINGS_METADATA, &size);
1425 return av_packet_unpack_dictionary(side_metadata, size, frame_md);
1428 int ff_init_buffer_info(AVCodecContext *avctx, AVFrame *frame)
1430 const AVPacket *pkt = avctx->internal->last_pkt_props;
1432 static const struct {
1433 enum AVPacketSideDataType packet;
1434 enum AVFrameSideDataType frame;
1436 { AV_PKT_DATA_REPLAYGAIN , AV_FRAME_DATA_REPLAYGAIN },
1437 { AV_PKT_DATA_DISPLAYMATRIX, AV_FRAME_DATA_DISPLAYMATRIX },
1438 { AV_PKT_DATA_SPHERICAL, AV_FRAME_DATA_SPHERICAL },
1439 { AV_PKT_DATA_STEREO3D, AV_FRAME_DATA_STEREO3D },
1440 { AV_PKT_DATA_AUDIO_SERVICE_TYPE, AV_FRAME_DATA_AUDIO_SERVICE_TYPE },
1441 { AV_PKT_DATA_MASTERING_DISPLAY_METADATA, AV_FRAME_DATA_MASTERING_DISPLAY_METADATA },
1442 { AV_PKT_DATA_CONTENT_LIGHT_LEVEL, AV_FRAME_DATA_CONTENT_LIGHT_LEVEL },
1443 { AV_PKT_DATA_A53_CC, AV_FRAME_DATA_A53_CC },
1447 frame->pts = pkt->pts;
1449 FF_DISABLE_DEPRECATION_WARNINGS
1450 frame->pkt_pts = pkt->pts;
1451 FF_ENABLE_DEPRECATION_WARNINGS
1453 frame->pkt_pos = pkt->pos;
1454 frame->pkt_duration = pkt->duration;
1455 frame->pkt_size = pkt->size;
1457 for (i = 0; i < FF_ARRAY_ELEMS(sd); i++) {
1459 uint8_t *packet_sd = av_packet_get_side_data(pkt, sd[i].packet, &size);
1461 AVFrameSideData *frame_sd = av_frame_new_side_data(frame,
1465 return AVERROR(ENOMEM);
1467 memcpy(frame_sd->data, packet_sd, size);
1470 add_metadata_from_side_data(pkt, frame);
1472 if (pkt->flags & AV_PKT_FLAG_DISCARD) {
1473 frame->flags |= AV_FRAME_FLAG_DISCARD;
1475 frame->flags = (frame->flags & ~AV_FRAME_FLAG_DISCARD);
1478 frame->reordered_opaque = avctx->reordered_opaque;
1480 if (frame->color_primaries == AVCOL_PRI_UNSPECIFIED)
1481 frame->color_primaries = avctx->color_primaries;
1482 if (frame->color_trc == AVCOL_TRC_UNSPECIFIED)
1483 frame->color_trc = avctx->color_trc;
1484 if (frame->colorspace == AVCOL_SPC_UNSPECIFIED)
1485 frame->colorspace = avctx->colorspace;
1486 if (frame->color_range == AVCOL_RANGE_UNSPECIFIED)
1487 frame->color_range = avctx->color_range;
1488 if (frame->chroma_location == AVCHROMA_LOC_UNSPECIFIED)
1489 frame->chroma_location = avctx->chroma_sample_location;
1491 switch (avctx->codec->type) {
1492 case AVMEDIA_TYPE_VIDEO:
1493 frame->format = avctx->pix_fmt;
1494 if (!frame->sample_aspect_ratio.num)
1495 frame->sample_aspect_ratio = avctx->sample_aspect_ratio;
1497 if (frame->width && frame->height &&
1498 av_image_check_sar(frame->width, frame->height,
1499 frame->sample_aspect_ratio) < 0) {
1500 av_log(avctx, AV_LOG_WARNING, "ignoring invalid SAR: %u/%u\n",
1501 frame->sample_aspect_ratio.num,
1502 frame->sample_aspect_ratio.den);
1503 frame->sample_aspect_ratio = (AVRational){ 0, 1 };
1507 case AVMEDIA_TYPE_AUDIO:
1508 if (!frame->sample_rate)
1509 frame->sample_rate = avctx->sample_rate;
1510 if (frame->format < 0)
1511 frame->format = avctx->sample_fmt;
1512 if (!frame->channel_layout) {
1513 if (avctx->channel_layout) {
1514 if (av_get_channel_layout_nb_channels(avctx->channel_layout) !=
1516 av_log(avctx, AV_LOG_ERROR, "Inconsistent channel "
1517 "configuration.\n");
1518 return AVERROR(EINVAL);
1521 frame->channel_layout = avctx->channel_layout;
1523 if (avctx->channels > FF_SANE_NB_CHANNELS) {
1524 av_log(avctx, AV_LOG_ERROR, "Too many channels: %d.\n",
1526 return AVERROR(ENOSYS);
1530 frame->channels = avctx->channels;
1536 int ff_decode_frame_props(AVCodecContext *avctx, AVFrame *frame)
1538 return ff_init_buffer_info(avctx, frame);
1541 static void validate_avframe_allocation(AVCodecContext *avctx, AVFrame *frame)
1543 if (avctx->codec_type == AVMEDIA_TYPE_VIDEO) {
1545 int num_planes = av_pix_fmt_count_planes(frame->format);
1546 const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(frame->format);
1547 int flags = desc ? desc->flags : 0;
1548 if (num_planes == 1 && (flags & AV_PIX_FMT_FLAG_PAL))
1550 for (i = 0; i < num_planes; i++) {
1551 av_assert0(frame->data[i]);
1553 // For now do not enforce anything for palette of pseudopal formats
1554 if (num_planes == 1 && (flags & AV_PIX_FMT_FLAG_PSEUDOPAL))
1556 // For formats without data like hwaccel allow unused pointers to be non-NULL.
1557 for (i = num_planes; num_planes > 0 && i < FF_ARRAY_ELEMS(frame->data); i++) {
1559 av_log(avctx, AV_LOG_ERROR, "Buffer returned by get_buffer2() did not zero unused plane pointers\n");
1560 frame->data[i] = NULL;
1565 static void decode_data_free(void *opaque, uint8_t *data)
1567 FrameDecodeData *fdd = (FrameDecodeData*)data;
1572 int ff_attach_decode_data(AVFrame *frame)
1574 AVBufferRef *fdd_buf;
1575 FrameDecodeData *fdd;
1577 av_assert1(!frame->private_ref);
1578 av_buffer_unref(&frame->private_ref);
1580 fdd = av_mallocz(sizeof(*fdd));
1582 return AVERROR(ENOMEM);
1584 fdd_buf = av_buffer_create((uint8_t*)fdd, sizeof(*fdd), decode_data_free,
1585 NULL, AV_BUFFER_FLAG_READONLY);
1588 return AVERROR(ENOMEM);
1591 frame->private_ref = fdd_buf;
1596 static int get_buffer_internal(AVCodecContext *avctx, AVFrame *frame, int flags)
1598 const AVHWAccel *hwaccel = avctx->hwaccel;
1599 int override_dimensions = 1;
1602 if (avctx->codec_type == AVMEDIA_TYPE_VIDEO) {
1603 if ((ret = av_image_check_size2(avctx->width, avctx->height, avctx->max_pixels, AV_PIX_FMT_NONE, 0, avctx)) < 0 || avctx->pix_fmt<0) {
1604 av_log(avctx, AV_LOG_ERROR, "video_get_buffer: image parameters invalid\n");
1605 return AVERROR(EINVAL);
1608 if (frame->width <= 0 || frame->height <= 0) {
1609 frame->width = FFMAX(avctx->width, AV_CEIL_RSHIFT(avctx->coded_width, avctx->lowres));
1610 frame->height = FFMAX(avctx->height, AV_CEIL_RSHIFT(avctx->coded_height, avctx->lowres));
1611 override_dimensions = 0;
1614 if (frame->data[0] || frame->data[1] || frame->data[2] || frame->data[3]) {
1615 av_log(avctx, AV_LOG_ERROR, "pic->data[*]!=NULL in get_buffer_internal\n");
1616 return AVERROR(EINVAL);
1619 ret = ff_decode_frame_props(avctx, frame);
1624 if (hwaccel->alloc_frame) {
1625 ret = hwaccel->alloc_frame(avctx, frame);
1629 avctx->sw_pix_fmt = avctx->pix_fmt;
1631 ret = avctx->get_buffer2(avctx, frame, flags);
1635 validate_avframe_allocation(avctx, frame);
1637 ret = ff_attach_decode_data(frame);
1642 if (avctx->codec_type == AVMEDIA_TYPE_VIDEO && !override_dimensions &&
1643 !(avctx->codec->caps_internal & FF_CODEC_CAP_EXPORTS_CROPPING)) {
1644 frame->width = avctx->width;
1645 frame->height = avctx->height;
1649 av_frame_unref(frame);
1654 int ff_get_buffer(AVCodecContext *avctx, AVFrame *frame, int flags)
1656 int ret = get_buffer_internal(avctx, frame, flags);
1658 av_log(avctx, AV_LOG_ERROR, "get_buffer() failed\n");
1659 frame->width = frame->height = 0;
1664 static int reget_buffer_internal(AVCodecContext *avctx, AVFrame *frame)
1669 av_assert0(avctx->codec_type == AVMEDIA_TYPE_VIDEO);
1671 if (frame->data[0] && (frame->width != avctx->width || frame->height != avctx->height || frame->format != avctx->pix_fmt)) {
1672 av_log(avctx, AV_LOG_WARNING, "Picture changed from size:%dx%d fmt:%s to size:%dx%d fmt:%s in reget buffer()\n",
1673 frame->width, frame->height, av_get_pix_fmt_name(frame->format), avctx->width, avctx->height, av_get_pix_fmt_name(avctx->pix_fmt));
1674 av_frame_unref(frame);
1677 ff_init_buffer_info(avctx, frame);
1679 if (!frame->data[0])
1680 return ff_get_buffer(avctx, frame, AV_GET_BUFFER_FLAG_REF);
1682 if (av_frame_is_writable(frame))
1683 return ff_decode_frame_props(avctx, frame);
1685 tmp = av_frame_alloc();
1687 return AVERROR(ENOMEM);
1689 av_frame_move_ref(tmp, frame);
1691 ret = ff_get_buffer(avctx, frame, AV_GET_BUFFER_FLAG_REF);
1693 av_frame_free(&tmp);
1697 av_frame_copy(frame, tmp);
1698 av_frame_free(&tmp);
1703 int ff_reget_buffer(AVCodecContext *avctx, AVFrame *frame)
1705 int ret = reget_buffer_internal(avctx, frame);
1707 av_log(avctx, AV_LOG_ERROR, "reget_buffer() failed\n");
1711 void avcodec_flush_buffers(AVCodecContext *avctx)
1713 avctx->internal->draining = 0;
1714 avctx->internal->draining_done = 0;
1715 avctx->internal->nb_draining_errors = 0;
1716 av_frame_unref(avctx->internal->buffer_frame);
1717 av_frame_unref(avctx->internal->compat_decode_frame);
1718 av_packet_unref(avctx->internal->buffer_pkt);
1719 avctx->internal->buffer_pkt_valid = 0;
1721 av_packet_unref(avctx->internal->ds.in_pkt);
1723 if (HAVE_THREADS && avctx->active_thread_type & FF_THREAD_FRAME)
1724 ff_thread_flush(avctx);
1725 else if (avctx->codec->flush)
1726 avctx->codec->flush(avctx);
1728 avctx->pts_correction_last_pts =
1729 avctx->pts_correction_last_dts = INT64_MIN;
1731 ff_decode_bsfs_uninit(avctx);
1733 if (!avctx->refcounted_frames)
1734 av_frame_unref(avctx->internal->to_free);
1737 void ff_decode_bsfs_uninit(AVCodecContext *avctx)
1739 DecodeFilterContext *s = &avctx->internal->filter;
1742 for (i = 0; i < s->nb_bsfs; i++)
1743 av_bsf_free(&s->bsfs[i]);