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
373 int got_frame, actual_got_frame, did_split;
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 FF_DISABLE_DEPRECATION_WARNINGS
396 did_split = avci->compat_decode_partial_size ?
397 ff_packet_split_and_drop_side_data(&tmp) :
398 av_packet_split_side_data(&tmp);
401 ret = extract_packet_props(avctx->internal, &tmp);
405 ret = apply_param_change(avctx, &tmp);
409 FF_ENABLE_DEPRECATION_WARNINGS
414 if (HAVE_THREADS && avctx->active_thread_type & FF_THREAD_FRAME) {
415 ret = ff_thread_decode_frame(avctx, frame, &got_frame, &tmp);
417 ret = avctx->codec->decode(avctx, frame, &got_frame, &tmp);
419 if (!(avctx->codec->caps_internal & FF_CODEC_CAP_SETS_PKT_DTS))
420 frame->pkt_dts = pkt->dts;
421 if (avctx->codec->type == AVMEDIA_TYPE_VIDEO) {
422 if(!avctx->has_b_frames)
423 frame->pkt_pos = pkt->pos;
424 //FIXME these should be under if(!avctx->has_b_frames)
425 /* get_buffer is supposed to set frame parameters */
426 if (!(avctx->codec->capabilities & AV_CODEC_CAP_DR1)) {
427 if (!frame->sample_aspect_ratio.num) frame->sample_aspect_ratio = avctx->sample_aspect_ratio;
428 if (!frame->width) frame->width = avctx->width;
429 if (!frame->height) frame->height = avctx->height;
430 if (frame->format == AV_PIX_FMT_NONE) frame->format = avctx->pix_fmt;
435 actual_got_frame = got_frame;
437 if (avctx->codec->type == AVMEDIA_TYPE_VIDEO) {
438 if (frame->flags & AV_FRAME_FLAG_DISCARD)
441 frame->best_effort_timestamp = guess_correct_pts(avctx,
444 } else if (avctx->codec->type == AVMEDIA_TYPE_AUDIO) {
447 uint32_t discard_padding = 0;
448 uint8_t skip_reason = 0;
449 uint8_t discard_reason = 0;
451 if (ret >= 0 && got_frame) {
452 frame->best_effort_timestamp = guess_correct_pts(avctx,
455 if (frame->format == AV_SAMPLE_FMT_NONE)
456 frame->format = avctx->sample_fmt;
457 if (!frame->channel_layout)
458 frame->channel_layout = avctx->channel_layout;
459 if (!frame->channels)
460 frame->channels = avctx->channels;
461 if (!frame->sample_rate)
462 frame->sample_rate = avctx->sample_rate;
465 side= av_packet_get_side_data(pkt, AV_PKT_DATA_SKIP_SAMPLES, &side_size);
466 if(side && side_size>=10) {
467 avctx->internal->skip_samples = AV_RL32(side) * avctx->internal->skip_samples_multiplier;
468 discard_padding = AV_RL32(side + 4);
469 av_log(avctx, AV_LOG_DEBUG, "skip %d / discard %d samples due to side data\n",
470 avctx->internal->skip_samples, (int)discard_padding);
471 skip_reason = AV_RL8(side + 8);
472 discard_reason = AV_RL8(side + 9);
475 if ((frame->flags & AV_FRAME_FLAG_DISCARD) && got_frame &&
476 !(avctx->flags2 & AV_CODEC_FLAG2_SKIP_MANUAL)) {
477 avctx->internal->skip_samples = FFMAX(0, avctx->internal->skip_samples - frame->nb_samples);
481 if (avctx->internal->skip_samples > 0 && got_frame &&
482 !(avctx->flags2 & AV_CODEC_FLAG2_SKIP_MANUAL)) {
483 if(frame->nb_samples <= avctx->internal->skip_samples){
485 avctx->internal->skip_samples -= frame->nb_samples;
486 av_log(avctx, AV_LOG_DEBUG, "skip whole frame, skip left: %d\n",
487 avctx->internal->skip_samples);
489 av_samples_copy(frame->extended_data, frame->extended_data, 0, avctx->internal->skip_samples,
490 frame->nb_samples - avctx->internal->skip_samples, avctx->channels, frame->format);
491 if(avctx->pkt_timebase.num && avctx->sample_rate) {
492 int64_t diff_ts = av_rescale_q(avctx->internal->skip_samples,
493 (AVRational){1, avctx->sample_rate},
494 avctx->pkt_timebase);
495 if(frame->pts!=AV_NOPTS_VALUE)
496 frame->pts += diff_ts;
498 FF_DISABLE_DEPRECATION_WARNINGS
499 if(frame->pkt_pts!=AV_NOPTS_VALUE)
500 frame->pkt_pts += diff_ts;
501 FF_ENABLE_DEPRECATION_WARNINGS
503 if(frame->pkt_dts!=AV_NOPTS_VALUE)
504 frame->pkt_dts += diff_ts;
505 if (frame->pkt_duration >= diff_ts)
506 frame->pkt_duration -= diff_ts;
508 av_log(avctx, AV_LOG_WARNING, "Could not update timestamps for skipped samples.\n");
510 av_log(avctx, AV_LOG_DEBUG, "skip %d/%d samples\n",
511 avctx->internal->skip_samples, frame->nb_samples);
512 frame->nb_samples -= avctx->internal->skip_samples;
513 avctx->internal->skip_samples = 0;
517 if (discard_padding > 0 && discard_padding <= frame->nb_samples && got_frame &&
518 !(avctx->flags2 & AV_CODEC_FLAG2_SKIP_MANUAL)) {
519 if (discard_padding == frame->nb_samples) {
522 if(avctx->pkt_timebase.num && avctx->sample_rate) {
523 int64_t diff_ts = av_rescale_q(frame->nb_samples - discard_padding,
524 (AVRational){1, avctx->sample_rate},
525 avctx->pkt_timebase);
526 frame->pkt_duration = diff_ts;
528 av_log(avctx, AV_LOG_WARNING, "Could not update timestamps for discarded samples.\n");
530 av_log(avctx, AV_LOG_DEBUG, "discard %d/%d samples\n",
531 (int)discard_padding, frame->nb_samples);
532 frame->nb_samples -= discard_padding;
536 if ((avctx->flags2 & AV_CODEC_FLAG2_SKIP_MANUAL) && got_frame) {
537 AVFrameSideData *fside = av_frame_new_side_data(frame, AV_FRAME_DATA_SKIP_SAMPLES, 10);
539 AV_WL32(fside->data, avctx->internal->skip_samples);
540 AV_WL32(fside->data + 4, discard_padding);
541 AV_WL8(fside->data + 8, skip_reason);
542 AV_WL8(fside->data + 9, discard_reason);
543 avctx->internal->skip_samples = 0;
549 av_packet_free_side_data(&tmp);
555 if (avctx->codec->type == AVMEDIA_TYPE_AUDIO &&
556 !avci->showed_multi_packet_warning &&
557 ret >= 0 && ret != pkt->size && !(avctx->codec->capabilities & AV_CODEC_CAP_SUBFRAMES)) {
558 av_log(avctx, AV_LOG_WARNING, "Multiple frames in a packet.\n");
559 avci->showed_multi_packet_warning = 1;
563 av_frame_unref(frame);
565 if (ret >= 0 && avctx->codec->type == AVMEDIA_TYPE_VIDEO && !(avctx->flags & AV_CODEC_FLAG_TRUNCATED))
568 #if FF_API_AVCTX_TIMEBASE
569 if (avctx->framerate.num > 0 && avctx->framerate.den > 0)
570 avctx->time_base = av_inv_q(av_mul_q(avctx->framerate, (AVRational){avctx->ticks_per_frame, 1}));
573 /* do not stop draining when actual_got_frame != 0 or ret < 0 */
574 /* got_frame == 0 but actual_got_frame != 0 when frame is discarded */
575 if (avctx->internal->draining && !actual_got_frame) {
577 /* prevent infinite loop if a decoder wrongly always return error on draining */
578 /* reasonable nb_errors_max = maximum b frames + thread count */
579 int nb_errors_max = 20 + (HAVE_THREADS && avctx->active_thread_type & FF_THREAD_FRAME ?
580 avctx->thread_count : 1);
582 if (avci->nb_draining_errors++ >= nb_errors_max) {
583 av_log(avctx, AV_LOG_ERROR, "Too many errors when draining, this is a bug. "
584 "Stop draining and force EOF.\n");
585 avci->draining_done = 1;
589 avci->draining_done = 1;
593 avci->compat_decode_consumed += ret;
595 if (ret >= pkt->size || ret < 0) {
596 av_packet_unref(pkt);
600 pkt->data += consumed;
601 pkt->size -= consumed;
602 avci->last_pkt_props->size -= consumed; // See extract_packet_props() comment.
603 pkt->pts = AV_NOPTS_VALUE;
604 pkt->dts = AV_NOPTS_VALUE;
605 avci->last_pkt_props->pts = AV_NOPTS_VALUE;
606 avci->last_pkt_props->dts = AV_NOPTS_VALUE;
610 av_assert0(frame->buf[0]);
612 return ret < 0 ? ret : 0;
615 static int decode_simple_receive_frame(AVCodecContext *avctx, AVFrame *frame)
619 while (!frame->buf[0]) {
620 ret = decode_simple_internal(avctx, frame);
628 static int decode_receive_frame_internal(AVCodecContext *avctx, AVFrame *frame)
630 AVCodecInternal *avci = avctx->internal;
633 av_assert0(!frame->buf[0]);
635 if (avctx->codec->receive_frame)
636 ret = avctx->codec->receive_frame(avctx, frame);
638 ret = decode_simple_receive_frame(avctx, frame);
640 if (ret == AVERROR_EOF)
641 avci->draining_done = 1;
646 int attribute_align_arg avcodec_send_packet(AVCodecContext *avctx, const AVPacket *avpkt)
648 AVCodecInternal *avci = avctx->internal;
651 if (!avcodec_is_open(avctx) || !av_codec_is_decoder(avctx->codec))
652 return AVERROR(EINVAL);
654 if (avctx->internal->draining)
657 if (avpkt && !avpkt->size && avpkt->data)
658 return AVERROR(EINVAL);
660 ret = bsfs_init(avctx);
664 av_packet_unref(avci->buffer_pkt);
665 if (avpkt && (avpkt->data || avpkt->side_data_elems)) {
666 ret = av_packet_ref(avci->buffer_pkt, avpkt);
671 ret = av_bsf_send_packet(avci->filter.bsfs[0], avci->buffer_pkt);
673 av_packet_unref(avci->buffer_pkt);
677 if (!avci->buffer_frame->buf[0]) {
678 ret = decode_receive_frame_internal(avctx, avci->buffer_frame);
679 if (ret < 0 && ret != AVERROR(EAGAIN) && ret != AVERROR_EOF)
686 static int calc_cropping_offsets(size_t offsets[4], const AVFrame *frame,
687 const AVPixFmtDescriptor *desc)
691 for (i = 0; frame->data[i]; i++) {
692 const AVComponentDescriptor *comp = NULL;
693 int shift_x = (i == 1 || i == 2) ? desc->log2_chroma_w : 0;
694 int shift_y = (i == 1 || i == 2) ? desc->log2_chroma_h : 0;
696 if (desc->flags & (AV_PIX_FMT_FLAG_PAL | AV_PIX_FMT_FLAG_PSEUDOPAL) && i == 1) {
701 /* find any component descriptor for this plane */
702 for (j = 0; j < desc->nb_components; j++) {
703 if (desc->comp[j].plane == i) {
704 comp = &desc->comp[j];
711 offsets[i] = (frame->crop_top >> shift_y) * frame->linesize[i] +
712 (frame->crop_left >> shift_x) * comp->step;
718 static int apply_cropping(AVCodecContext *avctx, AVFrame *frame)
720 const AVPixFmtDescriptor *desc;
724 /* make sure we are noisy about decoders returning invalid cropping data */
725 if (frame->crop_left >= INT_MAX - frame->crop_right ||
726 frame->crop_top >= INT_MAX - frame->crop_bottom ||
727 (frame->crop_left + frame->crop_right) >= frame->width ||
728 (frame->crop_top + frame->crop_bottom) >= frame->height) {
729 av_log(avctx, AV_LOG_WARNING,
730 "Invalid cropping information set by a decoder: "
731 "%"SIZE_SPECIFIER"/%"SIZE_SPECIFIER"/%"SIZE_SPECIFIER"/%"SIZE_SPECIFIER" "
732 "(frame size %dx%d). This is a bug, please report it\n",
733 frame->crop_left, frame->crop_right, frame->crop_top, frame->crop_bottom,
734 frame->width, frame->height);
735 frame->crop_left = 0;
736 frame->crop_right = 0;
738 frame->crop_bottom = 0;
742 if (!avctx->apply_cropping)
745 desc = av_pix_fmt_desc_get(frame->format);
749 /* Apply just the right/bottom cropping for hwaccel formats. Bitstream
750 * formats cannot be easily handled here either (and corresponding decoders
751 * should not export any cropping anyway), so do the same for those as well.
753 if (desc->flags & (AV_PIX_FMT_FLAG_BITSTREAM | AV_PIX_FMT_FLAG_HWACCEL)) {
754 frame->width -= frame->crop_right;
755 frame->height -= frame->crop_bottom;
756 frame->crop_right = 0;
757 frame->crop_bottom = 0;
761 /* calculate the offsets for each plane */
762 calc_cropping_offsets(offsets, frame, desc);
764 /* adjust the offsets to avoid breaking alignment */
765 if (!(avctx->flags & AV_CODEC_FLAG_UNALIGNED)) {
766 int min_log2_align = INT_MAX;
768 for (i = 0; frame->data[i]; i++) {
769 int log2_align = offsets[i] ? ff_ctz(offsets[i]) : INT_MAX;
770 min_log2_align = FFMIN(log2_align, min_log2_align);
773 if (min_log2_align < 5) {
774 frame->crop_left &= ~((1 << min_log2_align) - 1);
775 calc_cropping_offsets(offsets, frame, desc);
779 for (i = 0; frame->data[i]; i++)
780 frame->data[i] += offsets[i];
782 frame->width -= (frame->crop_left + frame->crop_right);
783 frame->height -= (frame->crop_top + frame->crop_bottom);
784 frame->crop_left = 0;
785 frame->crop_right = 0;
787 frame->crop_bottom = 0;
792 int attribute_align_arg avcodec_receive_frame(AVCodecContext *avctx, AVFrame *frame)
794 AVCodecInternal *avci = avctx->internal;
797 av_frame_unref(frame);
799 if (!avcodec_is_open(avctx) || !av_codec_is_decoder(avctx->codec))
800 return AVERROR(EINVAL);
802 ret = bsfs_init(avctx);
806 if (avci->buffer_frame->buf[0]) {
807 av_frame_move_ref(frame, avci->buffer_frame);
809 ret = decode_receive_frame_internal(avctx, frame);
814 if (avctx->codec_type == AVMEDIA_TYPE_VIDEO) {
815 ret = apply_cropping(avctx, frame);
817 av_frame_unref(frame);
822 avctx->frame_number++;
827 static int compat_decode(AVCodecContext *avctx, AVFrame *frame,
828 int *got_frame, const AVPacket *pkt)
830 AVCodecInternal *avci = avctx->internal;
833 av_assert0(avci->compat_decode_consumed == 0);
836 avci->compat_decode = 1;
838 if (avci->compat_decode_partial_size > 0 &&
839 avci->compat_decode_partial_size != pkt->size) {
840 av_log(avctx, AV_LOG_ERROR,
841 "Got unexpected packet size after a partial decode\n");
842 ret = AVERROR(EINVAL);
846 if (!avci->compat_decode_partial_size) {
847 ret = avcodec_send_packet(avctx, pkt);
848 if (ret == AVERROR_EOF)
850 else if (ret == AVERROR(EAGAIN)) {
851 /* we fully drain all the output in each decode call, so this should not
860 ret = avcodec_receive_frame(avctx, frame);
862 if (ret == AVERROR(EAGAIN) || ret == AVERROR_EOF)
867 if (frame != avci->compat_decode_frame) {
868 if (!avctx->refcounted_frames) {
869 ret = unrefcount_frame(avci, frame);
875 frame = avci->compat_decode_frame;
877 if (!avci->compat_decode_warned) {
878 av_log(avctx, AV_LOG_WARNING, "The deprecated avcodec_decode_* "
879 "API cannot return all the frames for this decoder. "
880 "Some frames will be dropped. Update your code to the "
881 "new decoding API to fix this.\n");
882 avci->compat_decode_warned = 1;
886 if (avci->draining || (!avctx->codec->bsfs && avci->compat_decode_consumed < pkt->size))
892 /* if there are any bsfs then assume full packet is always consumed */
893 if (avctx->codec->bsfs)
896 ret = FFMIN(avci->compat_decode_consumed, pkt->size);
898 avci->compat_decode_consumed = 0;
899 avci->compat_decode_partial_size = (ret >= 0) ? pkt->size - ret : 0;
904 int attribute_align_arg avcodec_decode_video2(AVCodecContext *avctx, AVFrame *picture,
905 int *got_picture_ptr,
906 const AVPacket *avpkt)
908 return compat_decode(avctx, picture, got_picture_ptr, avpkt);
911 int attribute_align_arg avcodec_decode_audio4(AVCodecContext *avctx,
914 const AVPacket *avpkt)
916 return compat_decode(avctx, frame, got_frame_ptr, avpkt);
919 static void get_subtitle_defaults(AVSubtitle *sub)
921 memset(sub, 0, sizeof(*sub));
922 sub->pts = AV_NOPTS_VALUE;
925 #define UTF8_MAX_BYTES 4 /* 5 and 6 bytes sequences should not be used */
926 static int recode_subtitle(AVCodecContext *avctx,
927 AVPacket *outpkt, const AVPacket *inpkt)
930 iconv_t cd = (iconv_t)-1;
937 if (avctx->sub_charenc_mode != FF_SUB_CHARENC_MODE_PRE_DECODER || inpkt->size == 0)
941 cd = iconv_open("UTF-8", avctx->sub_charenc);
942 av_assert0(cd != (iconv_t)-1);
947 if (inl >= INT_MAX / UTF8_MAX_BYTES - AV_INPUT_BUFFER_PADDING_SIZE) {
948 av_log(avctx, AV_LOG_ERROR, "Subtitles packet is too big for recoding\n");
949 ret = AVERROR(ENOMEM);
953 ret = av_new_packet(&tmp, inl * UTF8_MAX_BYTES);
956 outpkt->buf = tmp.buf;
957 outpkt->data = tmp.data;
958 outpkt->size = tmp.size;
962 if (iconv(cd, &inb, &inl, &outb, &outl) == (size_t)-1 ||
963 iconv(cd, NULL, NULL, &outb, &outl) == (size_t)-1 ||
964 outl >= outpkt->size || inl != 0) {
965 ret = FFMIN(AVERROR(errno), -1);
966 av_log(avctx, AV_LOG_ERROR, "Unable to recode subtitle event \"%s\" "
967 "from %s to UTF-8\n", inpkt->data, avctx->sub_charenc);
968 av_packet_unref(&tmp);
971 outpkt->size -= outl;
972 memset(outpkt->data + outpkt->size, 0, outl);
975 if (cd != (iconv_t)-1)
979 av_log(avctx, AV_LOG_ERROR, "requesting subtitles recoding without iconv");
980 return AVERROR(EINVAL);
984 static int utf8_check(const uint8_t *str)
987 uint32_t codepoint, min;
991 GET_UTF8(codepoint, *(byte++), return 0;);
992 min = byte - str == 1 ? 0 : byte - str == 2 ? 0x80 :
993 1 << (5 * (byte - str) - 4);
994 if (codepoint < min || codepoint >= 0x110000 ||
995 codepoint == 0xFFFE /* BOM */ ||
996 codepoint >= 0xD800 && codepoint <= 0xDFFF /* surrogates */)
1003 #if FF_API_ASS_TIMING
1004 static void insert_ts(AVBPrint *buf, int ts)
1007 av_bprintf(buf, "9:59:59.99,");
1011 h = ts/360000; ts -= 360000*h;
1012 m = ts/ 6000; ts -= 6000*m;
1013 s = ts/ 100; ts -= 100*s;
1014 av_bprintf(buf, "%d:%02d:%02d.%02d,", h, m, s, ts);
1018 static int convert_sub_to_old_ass_form(AVSubtitle *sub, const AVPacket *pkt, AVRational tb)
1023 av_bprint_init(&buf, 0, AV_BPRINT_SIZE_UNLIMITED);
1025 for (i = 0; i < sub->num_rects; i++) {
1028 AVSubtitleRect *rect = sub->rects[i];
1029 int ts_start, ts_duration = -1;
1032 if (rect->type != SUBTITLE_ASS || !strncmp(rect->ass, "Dialogue: ", 10))
1035 av_bprint_clear(&buf);
1037 /* skip ReadOrder */
1038 dialog = strchr(rect->ass, ',');
1043 /* extract Layer or Marked */
1044 layer = strtol(dialog, (char**)&dialog, 10);
1049 /* rescale timing to ASS time base (ms) */
1050 ts_start = av_rescale_q(pkt->pts, tb, av_make_q(1, 100));
1051 if (pkt->duration != -1)
1052 ts_duration = av_rescale_q(pkt->duration, tb, av_make_q(1, 100));
1053 sub->end_display_time = FFMAX(sub->end_display_time, 10 * ts_duration);
1055 /* construct ASS (standalone file form with timestamps) string */
1056 av_bprintf(&buf, "Dialogue: %ld,", layer);
1057 insert_ts(&buf, ts_start);
1058 insert_ts(&buf, ts_duration == -1 ? -1 : ts_start + ts_duration);
1059 av_bprintf(&buf, "%s\r\n", dialog);
1061 final_dialog = av_strdup(buf.str);
1062 if (!av_bprint_is_complete(&buf) || !final_dialog) {
1063 av_freep(&final_dialog);
1064 av_bprint_finalize(&buf, NULL);
1065 return AVERROR(ENOMEM);
1067 av_freep(&rect->ass);
1068 rect->ass = final_dialog;
1071 av_bprint_finalize(&buf, NULL);
1076 int avcodec_decode_subtitle2(AVCodecContext *avctx, AVSubtitle *sub,
1081 AVCodecInternal *avci = avctx->internal;
1083 if (!avpkt->data && avpkt->size) {
1084 av_log(avctx, AV_LOG_ERROR, "invalid packet: NULL data, size != 0\n");
1085 return AVERROR(EINVAL);
1088 return AVERROR(EINVAL);
1089 if (avctx->codec->type != AVMEDIA_TYPE_SUBTITLE) {
1090 av_log(avctx, AV_LOG_ERROR, "Invalid media type for subtitles\n");
1091 return AVERROR(EINVAL);
1095 get_subtitle_defaults(sub);
1097 if ((avctx->codec->capabilities & AV_CODEC_CAP_DELAY) || avpkt->size) {
1098 AVPacket pkt_recoded;
1099 AVPacket tmp = *avpkt;
1101 FF_DISABLE_DEPRECATION_WARNINGS
1102 int did_split = avci->compat_decode_partial_size ?
1103 ff_packet_split_and_drop_side_data(&tmp) :
1104 av_packet_split_side_data(&tmp);
1105 //apply_param_change(avctx, &tmp);
1108 /* FFMIN() prevents overflow in case the packet wasn't allocated with
1110 * If the side data is smaller than the buffer padding size, the
1111 * remaining bytes should have already been filled with zeros by the
1112 * original packet allocation anyway. */
1113 memset(tmp.data + tmp.size, 0,
1114 FFMIN(avpkt->size - tmp.size, AV_INPUT_BUFFER_PADDING_SIZE));
1116 FF_ENABLE_DEPRECATION_WARNINGS
1120 ret = recode_subtitle(avctx, &pkt_recoded, &tmp);
1124 ret = extract_packet_props(avctx->internal, &pkt_recoded);
1128 if (avctx->pkt_timebase.num && avpkt->pts != AV_NOPTS_VALUE)
1129 sub->pts = av_rescale_q(avpkt->pts,
1130 avctx->pkt_timebase, AV_TIME_BASE_Q);
1131 ret = avctx->codec->decode(avctx, sub, got_sub_ptr, &pkt_recoded);
1132 av_assert1((ret >= 0) >= !!*got_sub_ptr &&
1133 !!*got_sub_ptr >= !!sub->num_rects);
1135 #if FF_API_ASS_TIMING
1136 if (avctx->sub_text_format == FF_SUB_TEXT_FMT_ASS_WITH_TIMINGS
1137 && *got_sub_ptr && sub->num_rects) {
1138 const AVRational tb = avctx->pkt_timebase.num ? avctx->pkt_timebase
1140 int err = convert_sub_to_old_ass_form(sub, avpkt, tb);
1146 if (sub->num_rects && !sub->end_display_time && avpkt->duration &&
1147 avctx->pkt_timebase.num) {
1148 AVRational ms = { 1, 1000 };
1149 sub->end_display_time = av_rescale_q(avpkt->duration,
1150 avctx->pkt_timebase, ms);
1153 if (avctx->codec_descriptor->props & AV_CODEC_PROP_BITMAP_SUB)
1155 else if (avctx->codec_descriptor->props & AV_CODEC_PROP_TEXT_SUB)
1158 for (i = 0; i < sub->num_rects; i++) {
1159 if (sub->rects[i]->ass && !utf8_check(sub->rects[i]->ass)) {
1160 av_log(avctx, AV_LOG_ERROR,
1161 "Invalid UTF-8 in decoded subtitles text; "
1162 "maybe missing -sub_charenc option\n");
1163 avsubtitle_free(sub);
1164 ret = AVERROR_INVALIDDATA;
1169 if (tmp.data != pkt_recoded.data) { // did we recode?
1170 /* prevent from destroying side data from original packet */
1171 pkt_recoded.side_data = NULL;
1172 pkt_recoded.side_data_elems = 0;
1174 av_packet_unref(&pkt_recoded);
1180 av_packet_free_side_data(&tmp);
1187 avctx->frame_number++;
1193 static int is_hwaccel_pix_fmt(enum AVPixelFormat pix_fmt)
1195 const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(pix_fmt);
1196 return desc->flags & AV_PIX_FMT_FLAG_HWACCEL;
1199 enum AVPixelFormat avcodec_default_get_format(struct AVCodecContext *s, const enum AVPixelFormat *fmt)
1201 while (*fmt != AV_PIX_FMT_NONE && is_hwaccel_pix_fmt(*fmt))
1206 static AVHWAccel *find_hwaccel(enum AVCodecID codec_id,
1207 enum AVPixelFormat pix_fmt)
1209 AVHWAccel *hwaccel = NULL;
1211 while ((hwaccel = av_hwaccel_next(hwaccel)))
1212 if (hwaccel->id == codec_id
1213 && hwaccel->pix_fmt == pix_fmt)
1218 static int setup_hwaccel(AVCodecContext *avctx,
1219 const enum AVPixelFormat fmt,
1222 AVHWAccel *hwa = find_hwaccel(avctx->codec_id, fmt);
1226 av_log(avctx, AV_LOG_ERROR,
1227 "Could not find an AVHWAccel for the pixel format: %s",
1229 return AVERROR(ENOENT);
1232 if (hwa->capabilities & HWACCEL_CODEC_CAP_EXPERIMENTAL &&
1233 avctx->strict_std_compliance > FF_COMPLIANCE_EXPERIMENTAL) {
1234 av_log(avctx, AV_LOG_WARNING, "Ignoring experimental hwaccel: %s\n",
1236 return AVERROR_PATCHWELCOME;
1239 if (hwa->priv_data_size) {
1240 avctx->internal->hwaccel_priv_data = av_mallocz(hwa->priv_data_size);
1241 if (!avctx->internal->hwaccel_priv_data)
1242 return AVERROR(ENOMEM);
1246 ret = hwa->init(avctx);
1248 av_freep(&avctx->internal->hwaccel_priv_data);
1253 avctx->hwaccel = hwa;
1258 int ff_get_format(AVCodecContext *avctx, const enum AVPixelFormat *fmt)
1260 const AVPixFmtDescriptor *desc;
1261 enum AVPixelFormat *choices;
1262 enum AVPixelFormat ret;
1265 while (fmt[n] != AV_PIX_FMT_NONE)
1269 avctx->sw_pix_fmt = fmt[n - 1];
1270 av_assert2(!is_hwaccel_pix_fmt(avctx->sw_pix_fmt));
1272 choices = av_malloc_array(n + 1, sizeof(*choices));
1274 return AV_PIX_FMT_NONE;
1276 memcpy(choices, fmt, (n + 1) * sizeof(*choices));
1279 if (avctx->hwaccel && avctx->hwaccel->uninit)
1280 avctx->hwaccel->uninit(avctx);
1281 av_freep(&avctx->internal->hwaccel_priv_data);
1282 avctx->hwaccel = NULL;
1284 av_buffer_unref(&avctx->hw_frames_ctx);
1286 ret = avctx->get_format(avctx, choices);
1288 desc = av_pix_fmt_desc_get(ret);
1290 ret = AV_PIX_FMT_NONE;
1294 if (!(desc->flags & AV_PIX_FMT_FLAG_HWACCEL))
1296 #if FF_API_CAP_VDPAU
1297 if (avctx->codec->capabilities&AV_CODEC_CAP_HWACCEL_VDPAU)
1301 if (avctx->hw_frames_ctx) {
1302 AVHWFramesContext *hw_frames_ctx = (AVHWFramesContext*)avctx->hw_frames_ctx->data;
1303 if (hw_frames_ctx->format != ret) {
1304 av_log(avctx, AV_LOG_ERROR, "Format returned from get_buffer() "
1305 "does not match the format of provided AVHWFramesContext\n");
1306 ret = AV_PIX_FMT_NONE;
1311 if (!setup_hwaccel(avctx, ret, desc->name))
1314 /* Remove failed hwaccel from choices */
1315 for (n = 0; choices[n] != ret; n++)
1316 av_assert0(choices[n] != AV_PIX_FMT_NONE);
1319 choices[n] = choices[n + 1];
1320 while (choices[n++] != AV_PIX_FMT_NONE);
1327 static int update_frame_pool(AVCodecContext *avctx, AVFrame *frame)
1329 FramePool *pool = avctx->internal->pool;
1332 switch (avctx->codec_type) {
1333 case AVMEDIA_TYPE_VIDEO: {
1336 int size[4] = { 0 };
1337 int w = frame->width;
1338 int h = frame->height;
1339 int tmpsize, unaligned;
1341 if (pool->format == frame->format &&
1342 pool->width == frame->width && pool->height == frame->height)
1345 avcodec_align_dimensions2(avctx, &w, &h, pool->stride_align);
1348 // NOTE: do not align linesizes individually, this breaks e.g. assumptions
1349 // that linesize[0] == 2*linesize[1] in the MPEG-encoder for 4:2:2
1350 ret = av_image_fill_linesizes(linesize, avctx->pix_fmt, w);
1353 // increase alignment of w for next try (rhs gives the lowest bit set in w)
1357 for (i = 0; i < 4; i++)
1358 unaligned |= linesize[i] % pool->stride_align[i];
1359 } while (unaligned);
1361 tmpsize = av_image_fill_pointers(data, avctx->pix_fmt, h,
1366 for (i = 0; i < 3 && data[i + 1]; i++)
1367 size[i] = data[i + 1] - data[i];
1368 size[i] = tmpsize - (data[i] - data[0]);
1370 for (i = 0; i < 4; i++) {
1371 av_buffer_pool_uninit(&pool->pools[i]);
1372 pool->linesize[i] = linesize[i];
1374 pool->pools[i] = av_buffer_pool_init(size[i] + 16 + STRIDE_ALIGN - 1,
1375 CONFIG_MEMORY_POISONING ?
1378 if (!pool->pools[i]) {
1379 ret = AVERROR(ENOMEM);
1384 pool->format = frame->format;
1385 pool->width = frame->width;
1386 pool->height = frame->height;
1390 case AVMEDIA_TYPE_AUDIO: {
1391 int ch = frame->channels; //av_get_channel_layout_nb_channels(frame->channel_layout);
1392 int planar = av_sample_fmt_is_planar(frame->format);
1393 int planes = planar ? ch : 1;
1395 if (pool->format == frame->format && pool->planes == planes &&
1396 pool->channels == ch && frame->nb_samples == pool->samples)
1399 av_buffer_pool_uninit(&pool->pools[0]);
1400 ret = av_samples_get_buffer_size(&pool->linesize[0], ch,
1401 frame->nb_samples, frame->format, 0);
1405 pool->pools[0] = av_buffer_pool_init(pool->linesize[0], NULL);
1406 if (!pool->pools[0]) {
1407 ret = AVERROR(ENOMEM);
1411 pool->format = frame->format;
1412 pool->planes = planes;
1413 pool->channels = ch;
1414 pool->samples = frame->nb_samples;
1417 default: av_assert0(0);
1421 for (i = 0; i < 4; i++)
1422 av_buffer_pool_uninit(&pool->pools[i]);
1424 pool->planes = pool->channels = pool->samples = 0;
1425 pool->width = pool->height = 0;
1429 static int audio_get_buffer(AVCodecContext *avctx, AVFrame *frame)
1431 FramePool *pool = avctx->internal->pool;
1432 int planes = pool->planes;
1435 frame->linesize[0] = pool->linesize[0];
1437 if (planes > AV_NUM_DATA_POINTERS) {
1438 frame->extended_data = av_mallocz_array(planes, sizeof(*frame->extended_data));
1439 frame->nb_extended_buf = planes - AV_NUM_DATA_POINTERS;
1440 frame->extended_buf = av_mallocz_array(frame->nb_extended_buf,
1441 sizeof(*frame->extended_buf));
1442 if (!frame->extended_data || !frame->extended_buf) {
1443 av_freep(&frame->extended_data);
1444 av_freep(&frame->extended_buf);
1445 return AVERROR(ENOMEM);
1448 frame->extended_data = frame->data;
1449 av_assert0(frame->nb_extended_buf == 0);
1452 for (i = 0; i < FFMIN(planes, AV_NUM_DATA_POINTERS); i++) {
1453 frame->buf[i] = av_buffer_pool_get(pool->pools[0]);
1456 frame->extended_data[i] = frame->data[i] = frame->buf[i]->data;
1458 for (i = 0; i < frame->nb_extended_buf; i++) {
1459 frame->extended_buf[i] = av_buffer_pool_get(pool->pools[0]);
1460 if (!frame->extended_buf[i])
1462 frame->extended_data[i + AV_NUM_DATA_POINTERS] = frame->extended_buf[i]->data;
1465 if (avctx->debug & FF_DEBUG_BUFFERS)
1466 av_log(avctx, AV_LOG_DEBUG, "default_get_buffer called on frame %p", frame);
1470 av_frame_unref(frame);
1471 return AVERROR(ENOMEM);
1474 static int video_get_buffer(AVCodecContext *s, AVFrame *pic)
1476 FramePool *pool = s->internal->pool;
1477 const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(pic->format);
1480 if (pic->data[0] || pic->data[1] || pic->data[2] || pic->data[3]) {
1481 av_log(s, AV_LOG_ERROR, "pic->data[*]!=NULL in avcodec_default_get_buffer\n");
1486 av_log(s, AV_LOG_ERROR,
1487 "Unable to get pixel format descriptor for format %s\n",
1488 av_get_pix_fmt_name(pic->format));
1489 return AVERROR(EINVAL);
1492 memset(pic->data, 0, sizeof(pic->data));
1493 pic->extended_data = pic->data;
1495 for (i = 0; i < 4 && pool->pools[i]; i++) {
1496 pic->linesize[i] = pool->linesize[i];
1498 pic->buf[i] = av_buffer_pool_get(pool->pools[i]);
1502 pic->data[i] = pic->buf[i]->data;
1504 for (; i < AV_NUM_DATA_POINTERS; i++) {
1505 pic->data[i] = NULL;
1506 pic->linesize[i] = 0;
1508 if (desc->flags & AV_PIX_FMT_FLAG_PAL ||
1509 desc->flags & AV_PIX_FMT_FLAG_PSEUDOPAL)
1510 avpriv_set_systematic_pal2((uint32_t *)pic->data[1], pic->format);
1512 if (s->debug & FF_DEBUG_BUFFERS)
1513 av_log(s, AV_LOG_DEBUG, "default_get_buffer called on pic %p\n", pic);
1517 av_frame_unref(pic);
1518 return AVERROR(ENOMEM);
1521 int avcodec_default_get_buffer2(AVCodecContext *avctx, AVFrame *frame, int flags)
1525 if (avctx->hw_frames_ctx)
1526 return av_hwframe_get_buffer(avctx->hw_frames_ctx, frame, 0);
1528 if ((ret = update_frame_pool(avctx, frame)) < 0)
1531 switch (avctx->codec_type) {
1532 case AVMEDIA_TYPE_VIDEO:
1533 return video_get_buffer(avctx, frame);
1534 case AVMEDIA_TYPE_AUDIO:
1535 return audio_get_buffer(avctx, frame);
1541 static int add_metadata_from_side_data(const AVPacket *avpkt, AVFrame *frame)
1544 const uint8_t *side_metadata;
1546 AVDictionary **frame_md = &frame->metadata;
1548 side_metadata = av_packet_get_side_data(avpkt,
1549 AV_PKT_DATA_STRINGS_METADATA, &size);
1550 return av_packet_unpack_dictionary(side_metadata, size, frame_md);
1553 int ff_init_buffer_info(AVCodecContext *avctx, AVFrame *frame)
1555 const AVPacket *pkt = avctx->internal->last_pkt_props;
1557 static const struct {
1558 enum AVPacketSideDataType packet;
1559 enum AVFrameSideDataType frame;
1561 { AV_PKT_DATA_REPLAYGAIN , AV_FRAME_DATA_REPLAYGAIN },
1562 { AV_PKT_DATA_DISPLAYMATRIX, AV_FRAME_DATA_DISPLAYMATRIX },
1563 { AV_PKT_DATA_SPHERICAL, AV_FRAME_DATA_SPHERICAL },
1564 { AV_PKT_DATA_STEREO3D, AV_FRAME_DATA_STEREO3D },
1565 { AV_PKT_DATA_AUDIO_SERVICE_TYPE, AV_FRAME_DATA_AUDIO_SERVICE_TYPE },
1566 { AV_PKT_DATA_MASTERING_DISPLAY_METADATA, AV_FRAME_DATA_MASTERING_DISPLAY_METADATA },
1567 { AV_PKT_DATA_CONTENT_LIGHT_LEVEL, AV_FRAME_DATA_CONTENT_LIGHT_LEVEL },
1571 frame->pts = pkt->pts;
1573 FF_DISABLE_DEPRECATION_WARNINGS
1574 frame->pkt_pts = pkt->pts;
1575 FF_ENABLE_DEPRECATION_WARNINGS
1577 frame->pkt_pos = pkt->pos;
1578 frame->pkt_duration = pkt->duration;
1579 frame->pkt_size = pkt->size;
1581 for (i = 0; i < FF_ARRAY_ELEMS(sd); i++) {
1583 uint8_t *packet_sd = av_packet_get_side_data(pkt, sd[i].packet, &size);
1585 AVFrameSideData *frame_sd = av_frame_new_side_data(frame,
1589 return AVERROR(ENOMEM);
1591 memcpy(frame_sd->data, packet_sd, size);
1594 add_metadata_from_side_data(pkt, frame);
1596 if (pkt->flags & AV_PKT_FLAG_DISCARD) {
1597 frame->flags |= AV_FRAME_FLAG_DISCARD;
1599 frame->flags = (frame->flags & ~AV_FRAME_FLAG_DISCARD);
1602 frame->reordered_opaque = avctx->reordered_opaque;
1604 if (frame->color_primaries == AVCOL_PRI_UNSPECIFIED)
1605 frame->color_primaries = avctx->color_primaries;
1606 if (frame->color_trc == AVCOL_TRC_UNSPECIFIED)
1607 frame->color_trc = avctx->color_trc;
1608 if (frame->colorspace == AVCOL_SPC_UNSPECIFIED)
1609 frame->colorspace = avctx->colorspace;
1610 if (frame->color_range == AVCOL_RANGE_UNSPECIFIED)
1611 frame->color_range = avctx->color_range;
1612 if (frame->chroma_location == AVCHROMA_LOC_UNSPECIFIED)
1613 frame->chroma_location = avctx->chroma_sample_location;
1615 switch (avctx->codec->type) {
1616 case AVMEDIA_TYPE_VIDEO:
1617 frame->format = avctx->pix_fmt;
1618 if (!frame->sample_aspect_ratio.num)
1619 frame->sample_aspect_ratio = avctx->sample_aspect_ratio;
1621 if (frame->width && frame->height &&
1622 av_image_check_sar(frame->width, frame->height,
1623 frame->sample_aspect_ratio) < 0) {
1624 av_log(avctx, AV_LOG_WARNING, "ignoring invalid SAR: %u/%u\n",
1625 frame->sample_aspect_ratio.num,
1626 frame->sample_aspect_ratio.den);
1627 frame->sample_aspect_ratio = (AVRational){ 0, 1 };
1631 case AVMEDIA_TYPE_AUDIO:
1632 if (!frame->sample_rate)
1633 frame->sample_rate = avctx->sample_rate;
1634 if (frame->format < 0)
1635 frame->format = avctx->sample_fmt;
1636 if (!frame->channel_layout) {
1637 if (avctx->channel_layout) {
1638 if (av_get_channel_layout_nb_channels(avctx->channel_layout) !=
1640 av_log(avctx, AV_LOG_ERROR, "Inconsistent channel "
1641 "configuration.\n");
1642 return AVERROR(EINVAL);
1645 frame->channel_layout = avctx->channel_layout;
1647 if (avctx->channels > FF_SANE_NB_CHANNELS) {
1648 av_log(avctx, AV_LOG_ERROR, "Too many channels: %d.\n",
1650 return AVERROR(ENOSYS);
1654 frame->channels = avctx->channels;
1660 int ff_decode_frame_props(AVCodecContext *avctx, AVFrame *frame)
1662 return ff_init_buffer_info(avctx, frame);
1665 static void validate_avframe_allocation(AVCodecContext *avctx, AVFrame *frame)
1667 if (avctx->codec_type == AVMEDIA_TYPE_VIDEO) {
1669 int num_planes = av_pix_fmt_count_planes(frame->format);
1670 const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(frame->format);
1671 int flags = desc ? desc->flags : 0;
1672 if (num_planes == 1 && (flags & AV_PIX_FMT_FLAG_PAL))
1674 for (i = 0; i < num_planes; i++) {
1675 av_assert0(frame->data[i]);
1677 // For now do not enforce anything for palette of pseudopal formats
1678 if (num_planes == 1 && (flags & AV_PIX_FMT_FLAG_PSEUDOPAL))
1680 // For formats without data like hwaccel allow unused pointers to be non-NULL.
1681 for (i = num_planes; num_planes > 0 && i < FF_ARRAY_ELEMS(frame->data); i++) {
1683 av_log(avctx, AV_LOG_ERROR, "Buffer returned by get_buffer2() did not zero unused plane pointers\n");
1684 frame->data[i] = NULL;
1689 static int get_buffer_internal(AVCodecContext *avctx, AVFrame *frame, int flags)
1691 const AVHWAccel *hwaccel = avctx->hwaccel;
1692 int override_dimensions = 1;
1695 if (avctx->codec_type == AVMEDIA_TYPE_VIDEO) {
1696 if ((ret = av_image_check_size2(avctx->width, avctx->height, avctx->max_pixels, AV_PIX_FMT_NONE, 0, avctx)) < 0 || avctx->pix_fmt<0) {
1697 av_log(avctx, AV_LOG_ERROR, "video_get_buffer: image parameters invalid\n");
1698 return AVERROR(EINVAL);
1701 if (frame->width <= 0 || frame->height <= 0) {
1702 frame->width = FFMAX(avctx->width, AV_CEIL_RSHIFT(avctx->coded_width, avctx->lowres));
1703 frame->height = FFMAX(avctx->height, AV_CEIL_RSHIFT(avctx->coded_height, avctx->lowres));
1704 override_dimensions = 0;
1707 if (frame->data[0] || frame->data[1] || frame->data[2] || frame->data[3]) {
1708 av_log(avctx, AV_LOG_ERROR, "pic->data[*]!=NULL in get_buffer_internal\n");
1709 return AVERROR(EINVAL);
1712 ret = ff_decode_frame_props(avctx, frame);
1717 if (hwaccel->alloc_frame) {
1718 ret = hwaccel->alloc_frame(avctx, frame);
1722 avctx->sw_pix_fmt = avctx->pix_fmt;
1724 ret = avctx->get_buffer2(avctx, frame, flags);
1726 validate_avframe_allocation(avctx, frame);
1729 if (avctx->codec_type == AVMEDIA_TYPE_VIDEO && !override_dimensions &&
1730 !(avctx->codec->caps_internal & FF_CODEC_CAP_EXPORTS_CROPPING)) {
1731 frame->width = avctx->width;
1732 frame->height = avctx->height;
1738 int ff_get_buffer(AVCodecContext *avctx, AVFrame *frame, int flags)
1740 int ret = get_buffer_internal(avctx, frame, flags);
1742 av_log(avctx, AV_LOG_ERROR, "get_buffer() failed\n");
1743 frame->width = frame->height = 0;
1748 static int reget_buffer_internal(AVCodecContext *avctx, AVFrame *frame)
1753 av_assert0(avctx->codec_type == AVMEDIA_TYPE_VIDEO);
1755 if (frame->data[0] && (frame->width != avctx->width || frame->height != avctx->height || frame->format != avctx->pix_fmt)) {
1756 av_log(avctx, AV_LOG_WARNING, "Picture changed from size:%dx%d fmt:%s to size:%dx%d fmt:%s in reget buffer()\n",
1757 frame->width, frame->height, av_get_pix_fmt_name(frame->format), avctx->width, avctx->height, av_get_pix_fmt_name(avctx->pix_fmt));
1758 av_frame_unref(frame);
1761 ff_init_buffer_info(avctx, frame);
1763 if (!frame->data[0])
1764 return ff_get_buffer(avctx, frame, AV_GET_BUFFER_FLAG_REF);
1766 if (av_frame_is_writable(frame))
1767 return ff_decode_frame_props(avctx, frame);
1769 tmp = av_frame_alloc();
1771 return AVERROR(ENOMEM);
1773 av_frame_move_ref(tmp, frame);
1775 ret = ff_get_buffer(avctx, frame, AV_GET_BUFFER_FLAG_REF);
1777 av_frame_free(&tmp);
1781 av_frame_copy(frame, tmp);
1782 av_frame_free(&tmp);
1787 int ff_reget_buffer(AVCodecContext *avctx, AVFrame *frame)
1789 int ret = reget_buffer_internal(avctx, frame);
1791 av_log(avctx, AV_LOG_ERROR, "reget_buffer() failed\n");
1795 void avcodec_flush_buffers(AVCodecContext *avctx)
1797 avctx->internal->draining = 0;
1798 avctx->internal->draining_done = 0;
1799 avctx->internal->nb_draining_errors = 0;
1800 av_frame_unref(avctx->internal->buffer_frame);
1801 av_frame_unref(avctx->internal->compat_decode_frame);
1802 av_packet_unref(avctx->internal->buffer_pkt);
1803 avctx->internal->buffer_pkt_valid = 0;
1805 av_packet_unref(avctx->internal->ds.in_pkt);
1807 if (HAVE_THREADS && avctx->active_thread_type & FF_THREAD_FRAME)
1808 ff_thread_flush(avctx);
1809 else if (avctx->codec->flush)
1810 avctx->codec->flush(avctx);
1812 avctx->pts_correction_last_pts =
1813 avctx->pts_correction_last_dts = INT64_MIN;
1815 ff_decode_bsfs_uninit(avctx);
1817 if (!avctx->refcounted_frames)
1818 av_frame_unref(avctx->internal->to_free);
1821 void ff_decode_bsfs_uninit(AVCodecContext *avctx)
1823 DecodeFilterContext *s = &avctx->internal->filter;
1826 for (i = 0; i < s->nb_bsfs; i++)
1827 av_bsf_free(&s->bsfs[i]);