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(avci->last_pkt_props, 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 log2_crop_align = frame->crop_left ? ff_ctz(frame->crop_left) : INT_MAX;
767 int min_log2_align = INT_MAX;
769 for (i = 0; frame->data[i]; i++) {
770 int log2_align = offsets[i] ? ff_ctz(offsets[i]) : INT_MAX;
771 min_log2_align = FFMIN(log2_align, min_log2_align);
774 /* we assume, and it should always be true, that the data alignment is
775 * related to the cropping alignment by a constant power-of-2 factor */
776 if (log2_crop_align < min_log2_align)
779 if (min_log2_align < 5) {
780 frame->crop_left &= ~((1 << (5 + log2_crop_align - min_log2_align)) - 1);
781 calc_cropping_offsets(offsets, frame, desc);
785 for (i = 0; frame->data[i]; i++)
786 frame->data[i] += offsets[i];
788 frame->width -= (frame->crop_left + frame->crop_right);
789 frame->height -= (frame->crop_top + frame->crop_bottom);
790 frame->crop_left = 0;
791 frame->crop_right = 0;
793 frame->crop_bottom = 0;
798 int attribute_align_arg avcodec_receive_frame(AVCodecContext *avctx, AVFrame *frame)
800 AVCodecInternal *avci = avctx->internal;
803 av_frame_unref(frame);
805 if (!avcodec_is_open(avctx) || !av_codec_is_decoder(avctx->codec))
806 return AVERROR(EINVAL);
808 ret = bsfs_init(avctx);
812 if (avci->buffer_frame->buf[0]) {
813 av_frame_move_ref(frame, avci->buffer_frame);
815 ret = decode_receive_frame_internal(avctx, frame);
820 if (avctx->codec_type == AVMEDIA_TYPE_VIDEO) {
821 ret = apply_cropping(avctx, frame);
823 av_frame_unref(frame);
828 avctx->frame_number++;
833 static int compat_decode(AVCodecContext *avctx, AVFrame *frame,
834 int *got_frame, const AVPacket *pkt)
836 AVCodecInternal *avci = avctx->internal;
839 av_assert0(avci->compat_decode_consumed == 0);
842 avci->compat_decode = 1;
844 if (avci->compat_decode_partial_size > 0 &&
845 avci->compat_decode_partial_size != pkt->size) {
846 av_log(avctx, AV_LOG_ERROR,
847 "Got unexpected packet size after a partial decode\n");
848 ret = AVERROR(EINVAL);
852 if (!avci->compat_decode_partial_size) {
853 ret = avcodec_send_packet(avctx, pkt);
854 if (ret == AVERROR_EOF)
856 else if (ret == AVERROR(EAGAIN)) {
857 /* we fully drain all the output in each decode call, so this should not
866 ret = avcodec_receive_frame(avctx, frame);
868 if (ret == AVERROR(EAGAIN) || ret == AVERROR_EOF)
873 if (frame != avci->compat_decode_frame) {
874 if (!avctx->refcounted_frames) {
875 ret = unrefcount_frame(avci, frame);
881 frame = avci->compat_decode_frame;
883 if (!avci->compat_decode_warned) {
884 av_log(avctx, AV_LOG_WARNING, "The deprecated avcodec_decode_* "
885 "API cannot return all the frames for this decoder. "
886 "Some frames will be dropped. Update your code to the "
887 "new decoding API to fix this.\n");
888 avci->compat_decode_warned = 1;
892 if (avci->draining || (!avctx->codec->bsfs && avci->compat_decode_consumed < pkt->size))
898 /* if there are any bsfs then assume full packet is always consumed */
899 if (avctx->codec->bsfs)
902 ret = FFMIN(avci->compat_decode_consumed, pkt->size);
904 avci->compat_decode_consumed = 0;
905 avci->compat_decode_partial_size = (ret >= 0) ? pkt->size - ret : 0;
910 int attribute_align_arg avcodec_decode_video2(AVCodecContext *avctx, AVFrame *picture,
911 int *got_picture_ptr,
912 const AVPacket *avpkt)
914 return compat_decode(avctx, picture, got_picture_ptr, avpkt);
917 int attribute_align_arg avcodec_decode_audio4(AVCodecContext *avctx,
920 const AVPacket *avpkt)
922 return compat_decode(avctx, frame, got_frame_ptr, avpkt);
925 static void get_subtitle_defaults(AVSubtitle *sub)
927 memset(sub, 0, sizeof(*sub));
928 sub->pts = AV_NOPTS_VALUE;
931 #define UTF8_MAX_BYTES 4 /* 5 and 6 bytes sequences should not be used */
932 static int recode_subtitle(AVCodecContext *avctx,
933 AVPacket *outpkt, const AVPacket *inpkt)
936 iconv_t cd = (iconv_t)-1;
943 if (avctx->sub_charenc_mode != FF_SUB_CHARENC_MODE_PRE_DECODER || inpkt->size == 0)
947 cd = iconv_open("UTF-8", avctx->sub_charenc);
948 av_assert0(cd != (iconv_t)-1);
953 if (inl >= INT_MAX / UTF8_MAX_BYTES - AV_INPUT_BUFFER_PADDING_SIZE) {
954 av_log(avctx, AV_LOG_ERROR, "Subtitles packet is too big for recoding\n");
955 ret = AVERROR(ENOMEM);
959 ret = av_new_packet(&tmp, inl * UTF8_MAX_BYTES);
962 outpkt->buf = tmp.buf;
963 outpkt->data = tmp.data;
964 outpkt->size = tmp.size;
968 if (iconv(cd, &inb, &inl, &outb, &outl) == (size_t)-1 ||
969 iconv(cd, NULL, NULL, &outb, &outl) == (size_t)-1 ||
970 outl >= outpkt->size || inl != 0) {
971 ret = FFMIN(AVERROR(errno), -1);
972 av_log(avctx, AV_LOG_ERROR, "Unable to recode subtitle event \"%s\" "
973 "from %s to UTF-8\n", inpkt->data, avctx->sub_charenc);
974 av_packet_unref(&tmp);
977 outpkt->size -= outl;
978 memset(outpkt->data + outpkt->size, 0, outl);
981 if (cd != (iconv_t)-1)
985 av_log(avctx, AV_LOG_ERROR, "requesting subtitles recoding without iconv");
986 return AVERROR(EINVAL);
990 static int utf8_check(const uint8_t *str)
993 uint32_t codepoint, min;
997 GET_UTF8(codepoint, *(byte++), return 0;);
998 min = byte - str == 1 ? 0 : byte - str == 2 ? 0x80 :
999 1 << (5 * (byte - str) - 4);
1000 if (codepoint < min || codepoint >= 0x110000 ||
1001 codepoint == 0xFFFE /* BOM */ ||
1002 codepoint >= 0xD800 && codepoint <= 0xDFFF /* surrogates */)
1009 #if FF_API_ASS_TIMING
1010 static void insert_ts(AVBPrint *buf, int ts)
1013 av_bprintf(buf, "9:59:59.99,");
1017 h = ts/360000; ts -= 360000*h;
1018 m = ts/ 6000; ts -= 6000*m;
1019 s = ts/ 100; ts -= 100*s;
1020 av_bprintf(buf, "%d:%02d:%02d.%02d,", h, m, s, ts);
1024 static int convert_sub_to_old_ass_form(AVSubtitle *sub, const AVPacket *pkt, AVRational tb)
1029 av_bprint_init(&buf, 0, AV_BPRINT_SIZE_UNLIMITED);
1031 for (i = 0; i < sub->num_rects; i++) {
1034 AVSubtitleRect *rect = sub->rects[i];
1035 int ts_start, ts_duration = -1;
1038 if (rect->type != SUBTITLE_ASS || !strncmp(rect->ass, "Dialogue: ", 10))
1041 av_bprint_clear(&buf);
1043 /* skip ReadOrder */
1044 dialog = strchr(rect->ass, ',');
1049 /* extract Layer or Marked */
1050 layer = strtol(dialog, (char**)&dialog, 10);
1055 /* rescale timing to ASS time base (ms) */
1056 ts_start = av_rescale_q(pkt->pts, tb, av_make_q(1, 100));
1057 if (pkt->duration != -1)
1058 ts_duration = av_rescale_q(pkt->duration, tb, av_make_q(1, 100));
1059 sub->end_display_time = FFMAX(sub->end_display_time, 10 * ts_duration);
1061 /* construct ASS (standalone file form with timestamps) string */
1062 av_bprintf(&buf, "Dialogue: %ld,", layer);
1063 insert_ts(&buf, ts_start);
1064 insert_ts(&buf, ts_duration == -1 ? -1 : ts_start + ts_duration);
1065 av_bprintf(&buf, "%s\r\n", dialog);
1067 final_dialog = av_strdup(buf.str);
1068 if (!av_bprint_is_complete(&buf) || !final_dialog) {
1069 av_freep(&final_dialog);
1070 av_bprint_finalize(&buf, NULL);
1071 return AVERROR(ENOMEM);
1073 av_freep(&rect->ass);
1074 rect->ass = final_dialog;
1077 av_bprint_finalize(&buf, NULL);
1082 int avcodec_decode_subtitle2(AVCodecContext *avctx, AVSubtitle *sub,
1087 AVCodecInternal *avci = avctx->internal;
1089 if (!avpkt->data && avpkt->size) {
1090 av_log(avctx, AV_LOG_ERROR, "invalid packet: NULL data, size != 0\n");
1091 return AVERROR(EINVAL);
1094 return AVERROR(EINVAL);
1095 if (avctx->codec->type != AVMEDIA_TYPE_SUBTITLE) {
1096 av_log(avctx, AV_LOG_ERROR, "Invalid media type for subtitles\n");
1097 return AVERROR(EINVAL);
1101 get_subtitle_defaults(sub);
1103 if ((avctx->codec->capabilities & AV_CODEC_CAP_DELAY) || avpkt->size) {
1104 AVPacket pkt_recoded;
1105 AVPacket tmp = *avpkt;
1107 FF_DISABLE_DEPRECATION_WARNINGS
1108 int did_split = avci->compat_decode_partial_size ?
1109 ff_packet_split_and_drop_side_data(&tmp) :
1110 av_packet_split_side_data(&tmp);
1111 //apply_param_change(avctx, &tmp);
1114 /* FFMIN() prevents overflow in case the packet wasn't allocated with
1116 * If the side data is smaller than the buffer padding size, the
1117 * remaining bytes should have already been filled with zeros by the
1118 * original packet allocation anyway. */
1119 memset(tmp.data + tmp.size, 0,
1120 FFMIN(avpkt->size - tmp.size, AV_INPUT_BUFFER_PADDING_SIZE));
1122 FF_ENABLE_DEPRECATION_WARNINGS
1126 ret = recode_subtitle(avctx, &pkt_recoded, &tmp);
1130 ret = extract_packet_props(avctx->internal, &pkt_recoded);
1134 if (avctx->pkt_timebase.num && avpkt->pts != AV_NOPTS_VALUE)
1135 sub->pts = av_rescale_q(avpkt->pts,
1136 avctx->pkt_timebase, AV_TIME_BASE_Q);
1137 ret = avctx->codec->decode(avctx, sub, got_sub_ptr, &pkt_recoded);
1138 av_assert1((ret >= 0) >= !!*got_sub_ptr &&
1139 !!*got_sub_ptr >= !!sub->num_rects);
1141 #if FF_API_ASS_TIMING
1142 if (avctx->sub_text_format == FF_SUB_TEXT_FMT_ASS_WITH_TIMINGS
1143 && *got_sub_ptr && sub->num_rects) {
1144 const AVRational tb = avctx->pkt_timebase.num ? avctx->pkt_timebase
1146 int err = convert_sub_to_old_ass_form(sub, avpkt, tb);
1152 if (sub->num_rects && !sub->end_display_time && avpkt->duration &&
1153 avctx->pkt_timebase.num) {
1154 AVRational ms = { 1, 1000 };
1155 sub->end_display_time = av_rescale_q(avpkt->duration,
1156 avctx->pkt_timebase, ms);
1159 if (avctx->codec_descriptor->props & AV_CODEC_PROP_BITMAP_SUB)
1161 else if (avctx->codec_descriptor->props & AV_CODEC_PROP_TEXT_SUB)
1164 for (i = 0; i < sub->num_rects; i++) {
1165 if (sub->rects[i]->ass && !utf8_check(sub->rects[i]->ass)) {
1166 av_log(avctx, AV_LOG_ERROR,
1167 "Invalid UTF-8 in decoded subtitles text; "
1168 "maybe missing -sub_charenc option\n");
1169 avsubtitle_free(sub);
1170 ret = AVERROR_INVALIDDATA;
1175 if (tmp.data != pkt_recoded.data) { // did we recode?
1176 /* prevent from destroying side data from original packet */
1177 pkt_recoded.side_data = NULL;
1178 pkt_recoded.side_data_elems = 0;
1180 av_packet_unref(&pkt_recoded);
1186 av_packet_free_side_data(&tmp);
1193 avctx->frame_number++;
1199 static int is_hwaccel_pix_fmt(enum AVPixelFormat pix_fmt)
1201 const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(pix_fmt);
1202 return desc->flags & AV_PIX_FMT_FLAG_HWACCEL;
1205 enum AVPixelFormat avcodec_default_get_format(struct AVCodecContext *s, const enum AVPixelFormat *fmt)
1207 while (*fmt != AV_PIX_FMT_NONE && is_hwaccel_pix_fmt(*fmt))
1212 static AVHWAccel *find_hwaccel(enum AVCodecID codec_id,
1213 enum AVPixelFormat pix_fmt)
1215 AVHWAccel *hwaccel = NULL;
1217 while ((hwaccel = av_hwaccel_next(hwaccel)))
1218 if (hwaccel->id == codec_id
1219 && hwaccel->pix_fmt == pix_fmt)
1224 static int setup_hwaccel(AVCodecContext *avctx,
1225 const enum AVPixelFormat fmt,
1228 AVHWAccel *hwa = find_hwaccel(avctx->codec_id, fmt);
1232 av_log(avctx, AV_LOG_ERROR,
1233 "Could not find an AVHWAccel for the pixel format: %s",
1235 return AVERROR(ENOENT);
1238 if (hwa->capabilities & HWACCEL_CODEC_CAP_EXPERIMENTAL &&
1239 avctx->strict_std_compliance > FF_COMPLIANCE_EXPERIMENTAL) {
1240 av_log(avctx, AV_LOG_WARNING, "Ignoring experimental hwaccel: %s\n",
1242 return AVERROR_PATCHWELCOME;
1245 if (hwa->priv_data_size) {
1246 avctx->internal->hwaccel_priv_data = av_mallocz(hwa->priv_data_size);
1247 if (!avctx->internal->hwaccel_priv_data)
1248 return AVERROR(ENOMEM);
1251 avctx->hwaccel = hwa;
1253 ret = hwa->init(avctx);
1255 av_freep(&avctx->internal->hwaccel_priv_data);
1256 avctx->hwaccel = NULL;
1264 int ff_get_format(AVCodecContext *avctx, const enum AVPixelFormat *fmt)
1266 const AVPixFmtDescriptor *desc;
1267 enum AVPixelFormat *choices;
1268 enum AVPixelFormat ret;
1271 while (fmt[n] != AV_PIX_FMT_NONE)
1275 avctx->sw_pix_fmt = fmt[n - 1];
1276 av_assert2(!is_hwaccel_pix_fmt(avctx->sw_pix_fmt));
1278 choices = av_malloc_array(n + 1, sizeof(*choices));
1280 return AV_PIX_FMT_NONE;
1282 memcpy(choices, fmt, (n + 1) * sizeof(*choices));
1285 if (avctx->hwaccel && avctx->hwaccel->uninit)
1286 avctx->hwaccel->uninit(avctx);
1287 av_freep(&avctx->internal->hwaccel_priv_data);
1288 avctx->hwaccel = NULL;
1290 av_buffer_unref(&avctx->hw_frames_ctx);
1292 ret = avctx->get_format(avctx, choices);
1294 desc = av_pix_fmt_desc_get(ret);
1296 ret = AV_PIX_FMT_NONE;
1300 if (!(desc->flags & AV_PIX_FMT_FLAG_HWACCEL))
1302 #if FF_API_CAP_VDPAU
1303 if (avctx->codec->capabilities&AV_CODEC_CAP_HWACCEL_VDPAU)
1307 if (avctx->hw_frames_ctx) {
1308 AVHWFramesContext *hw_frames_ctx = (AVHWFramesContext*)avctx->hw_frames_ctx->data;
1309 if (hw_frames_ctx->format != ret) {
1310 av_log(avctx, AV_LOG_ERROR, "Format returned from get_buffer() "
1311 "does not match the format of provided AVHWFramesContext\n");
1312 ret = AV_PIX_FMT_NONE;
1317 if (!setup_hwaccel(avctx, ret, desc->name))
1320 /* Remove failed hwaccel from choices */
1321 for (n = 0; choices[n] != ret; n++)
1322 av_assert0(choices[n] != AV_PIX_FMT_NONE);
1325 choices[n] = choices[n + 1];
1326 while (choices[n++] != AV_PIX_FMT_NONE);
1333 static int update_frame_pool(AVCodecContext *avctx, AVFrame *frame)
1335 FramePool *pool = avctx->internal->pool;
1338 switch (avctx->codec_type) {
1339 case AVMEDIA_TYPE_VIDEO: {
1342 int size[4] = { 0 };
1343 int w = frame->width;
1344 int h = frame->height;
1345 int tmpsize, unaligned;
1347 if (pool->format == frame->format &&
1348 pool->width == frame->width && pool->height == frame->height)
1351 avcodec_align_dimensions2(avctx, &w, &h, pool->stride_align);
1354 // NOTE: do not align linesizes individually, this breaks e.g. assumptions
1355 // that linesize[0] == 2*linesize[1] in the MPEG-encoder for 4:2:2
1356 ret = av_image_fill_linesizes(linesize, avctx->pix_fmt, w);
1359 // increase alignment of w for next try (rhs gives the lowest bit set in w)
1363 for (i = 0; i < 4; i++)
1364 unaligned |= linesize[i] % pool->stride_align[i];
1365 } while (unaligned);
1367 tmpsize = av_image_fill_pointers(data, avctx->pix_fmt, h,
1372 for (i = 0; i < 3 && data[i + 1]; i++)
1373 size[i] = data[i + 1] - data[i];
1374 size[i] = tmpsize - (data[i] - data[0]);
1376 for (i = 0; i < 4; i++) {
1377 av_buffer_pool_uninit(&pool->pools[i]);
1378 pool->linesize[i] = linesize[i];
1380 pool->pools[i] = av_buffer_pool_init(size[i] + 16 + STRIDE_ALIGN - 1,
1381 CONFIG_MEMORY_POISONING ?
1384 if (!pool->pools[i]) {
1385 ret = AVERROR(ENOMEM);
1390 pool->format = frame->format;
1391 pool->width = frame->width;
1392 pool->height = frame->height;
1396 case AVMEDIA_TYPE_AUDIO: {
1397 int ch = frame->channels; //av_get_channel_layout_nb_channels(frame->channel_layout);
1398 int planar = av_sample_fmt_is_planar(frame->format);
1399 int planes = planar ? ch : 1;
1401 if (pool->format == frame->format && pool->planes == planes &&
1402 pool->channels == ch && frame->nb_samples == pool->samples)
1405 av_buffer_pool_uninit(&pool->pools[0]);
1406 ret = av_samples_get_buffer_size(&pool->linesize[0], ch,
1407 frame->nb_samples, frame->format, 0);
1411 pool->pools[0] = av_buffer_pool_init(pool->linesize[0], NULL);
1412 if (!pool->pools[0]) {
1413 ret = AVERROR(ENOMEM);
1417 pool->format = frame->format;
1418 pool->planes = planes;
1419 pool->channels = ch;
1420 pool->samples = frame->nb_samples;
1423 default: av_assert0(0);
1427 for (i = 0; i < 4; i++)
1428 av_buffer_pool_uninit(&pool->pools[i]);
1430 pool->planes = pool->channels = pool->samples = 0;
1431 pool->width = pool->height = 0;
1435 static int audio_get_buffer(AVCodecContext *avctx, AVFrame *frame)
1437 FramePool *pool = avctx->internal->pool;
1438 int planes = pool->planes;
1441 frame->linesize[0] = pool->linesize[0];
1443 if (planes > AV_NUM_DATA_POINTERS) {
1444 frame->extended_data = av_mallocz_array(planes, sizeof(*frame->extended_data));
1445 frame->nb_extended_buf = planes - AV_NUM_DATA_POINTERS;
1446 frame->extended_buf = av_mallocz_array(frame->nb_extended_buf,
1447 sizeof(*frame->extended_buf));
1448 if (!frame->extended_data || !frame->extended_buf) {
1449 av_freep(&frame->extended_data);
1450 av_freep(&frame->extended_buf);
1451 return AVERROR(ENOMEM);
1454 frame->extended_data = frame->data;
1455 av_assert0(frame->nb_extended_buf == 0);
1458 for (i = 0; i < FFMIN(planes, AV_NUM_DATA_POINTERS); i++) {
1459 frame->buf[i] = av_buffer_pool_get(pool->pools[0]);
1462 frame->extended_data[i] = frame->data[i] = frame->buf[i]->data;
1464 for (i = 0; i < frame->nb_extended_buf; i++) {
1465 frame->extended_buf[i] = av_buffer_pool_get(pool->pools[0]);
1466 if (!frame->extended_buf[i])
1468 frame->extended_data[i + AV_NUM_DATA_POINTERS] = frame->extended_buf[i]->data;
1471 if (avctx->debug & FF_DEBUG_BUFFERS)
1472 av_log(avctx, AV_LOG_DEBUG, "default_get_buffer called on frame %p", frame);
1476 av_frame_unref(frame);
1477 return AVERROR(ENOMEM);
1480 static int video_get_buffer(AVCodecContext *s, AVFrame *pic)
1482 FramePool *pool = s->internal->pool;
1483 const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(pic->format);
1486 if (pic->data[0] || pic->data[1] || pic->data[2] || pic->data[3]) {
1487 av_log(s, AV_LOG_ERROR, "pic->data[*]!=NULL in avcodec_default_get_buffer\n");
1492 av_log(s, AV_LOG_ERROR,
1493 "Unable to get pixel format descriptor for format %s\n",
1494 av_get_pix_fmt_name(pic->format));
1495 return AVERROR(EINVAL);
1498 memset(pic->data, 0, sizeof(pic->data));
1499 pic->extended_data = pic->data;
1501 for (i = 0; i < 4 && pool->pools[i]; i++) {
1502 pic->linesize[i] = pool->linesize[i];
1504 pic->buf[i] = av_buffer_pool_get(pool->pools[i]);
1508 pic->data[i] = pic->buf[i]->data;
1510 for (; i < AV_NUM_DATA_POINTERS; i++) {
1511 pic->data[i] = NULL;
1512 pic->linesize[i] = 0;
1514 if (desc->flags & AV_PIX_FMT_FLAG_PAL ||
1515 desc->flags & AV_PIX_FMT_FLAG_PSEUDOPAL)
1516 avpriv_set_systematic_pal2((uint32_t *)pic->data[1], pic->format);
1518 if (s->debug & FF_DEBUG_BUFFERS)
1519 av_log(s, AV_LOG_DEBUG, "default_get_buffer called on pic %p\n", pic);
1523 av_frame_unref(pic);
1524 return AVERROR(ENOMEM);
1527 int avcodec_default_get_buffer2(AVCodecContext *avctx, AVFrame *frame, int flags)
1531 if (avctx->hw_frames_ctx) {
1532 ret = av_hwframe_get_buffer(avctx->hw_frames_ctx, frame, 0);
1533 frame->width = avctx->coded_width;
1534 frame->height = avctx->coded_height;
1538 if ((ret = update_frame_pool(avctx, frame)) < 0)
1541 switch (avctx->codec_type) {
1542 case AVMEDIA_TYPE_VIDEO:
1543 return video_get_buffer(avctx, frame);
1544 case AVMEDIA_TYPE_AUDIO:
1545 return audio_get_buffer(avctx, frame);
1551 static int add_metadata_from_side_data(const AVPacket *avpkt, AVFrame *frame)
1554 const uint8_t *side_metadata;
1556 AVDictionary **frame_md = &frame->metadata;
1558 side_metadata = av_packet_get_side_data(avpkt,
1559 AV_PKT_DATA_STRINGS_METADATA, &size);
1560 return av_packet_unpack_dictionary(side_metadata, size, frame_md);
1563 int ff_init_buffer_info(AVCodecContext *avctx, AVFrame *frame)
1565 const AVPacket *pkt = avctx->internal->last_pkt_props;
1567 static const struct {
1568 enum AVPacketSideDataType packet;
1569 enum AVFrameSideDataType frame;
1571 { AV_PKT_DATA_REPLAYGAIN , AV_FRAME_DATA_REPLAYGAIN },
1572 { AV_PKT_DATA_DISPLAYMATRIX, AV_FRAME_DATA_DISPLAYMATRIX },
1573 { AV_PKT_DATA_SPHERICAL, AV_FRAME_DATA_SPHERICAL },
1574 { AV_PKT_DATA_STEREO3D, AV_FRAME_DATA_STEREO3D },
1575 { AV_PKT_DATA_AUDIO_SERVICE_TYPE, AV_FRAME_DATA_AUDIO_SERVICE_TYPE },
1576 { AV_PKT_DATA_MASTERING_DISPLAY_METADATA, AV_FRAME_DATA_MASTERING_DISPLAY_METADATA },
1577 { AV_PKT_DATA_CONTENT_LIGHT_LEVEL, AV_FRAME_DATA_CONTENT_LIGHT_LEVEL },
1581 frame->pts = pkt->pts;
1583 FF_DISABLE_DEPRECATION_WARNINGS
1584 frame->pkt_pts = pkt->pts;
1585 FF_ENABLE_DEPRECATION_WARNINGS
1587 frame->pkt_pos = pkt->pos;
1588 frame->pkt_duration = pkt->duration;
1589 frame->pkt_size = pkt->size;
1591 for (i = 0; i < FF_ARRAY_ELEMS(sd); i++) {
1593 uint8_t *packet_sd = av_packet_get_side_data(pkt, sd[i].packet, &size);
1595 AVFrameSideData *frame_sd = av_frame_new_side_data(frame,
1599 return AVERROR(ENOMEM);
1601 memcpy(frame_sd->data, packet_sd, size);
1604 add_metadata_from_side_data(pkt, frame);
1606 if (pkt->flags & AV_PKT_FLAG_DISCARD) {
1607 frame->flags |= AV_FRAME_FLAG_DISCARD;
1609 frame->flags = (frame->flags & ~AV_FRAME_FLAG_DISCARD);
1612 frame->reordered_opaque = avctx->reordered_opaque;
1614 if (frame->color_primaries == AVCOL_PRI_UNSPECIFIED)
1615 frame->color_primaries = avctx->color_primaries;
1616 if (frame->color_trc == AVCOL_TRC_UNSPECIFIED)
1617 frame->color_trc = avctx->color_trc;
1618 if (frame->colorspace == AVCOL_SPC_UNSPECIFIED)
1619 frame->colorspace = avctx->colorspace;
1620 if (frame->color_range == AVCOL_RANGE_UNSPECIFIED)
1621 frame->color_range = avctx->color_range;
1622 if (frame->chroma_location == AVCHROMA_LOC_UNSPECIFIED)
1623 frame->chroma_location = avctx->chroma_sample_location;
1625 switch (avctx->codec->type) {
1626 case AVMEDIA_TYPE_VIDEO:
1627 frame->format = avctx->pix_fmt;
1628 if (!frame->sample_aspect_ratio.num)
1629 frame->sample_aspect_ratio = avctx->sample_aspect_ratio;
1631 if (frame->width && frame->height &&
1632 av_image_check_sar(frame->width, frame->height,
1633 frame->sample_aspect_ratio) < 0) {
1634 av_log(avctx, AV_LOG_WARNING, "ignoring invalid SAR: %u/%u\n",
1635 frame->sample_aspect_ratio.num,
1636 frame->sample_aspect_ratio.den);
1637 frame->sample_aspect_ratio = (AVRational){ 0, 1 };
1641 case AVMEDIA_TYPE_AUDIO:
1642 if (!frame->sample_rate)
1643 frame->sample_rate = avctx->sample_rate;
1644 if (frame->format < 0)
1645 frame->format = avctx->sample_fmt;
1646 if (!frame->channel_layout) {
1647 if (avctx->channel_layout) {
1648 if (av_get_channel_layout_nb_channels(avctx->channel_layout) !=
1650 av_log(avctx, AV_LOG_ERROR, "Inconsistent channel "
1651 "configuration.\n");
1652 return AVERROR(EINVAL);
1655 frame->channel_layout = avctx->channel_layout;
1657 if (avctx->channels > FF_SANE_NB_CHANNELS) {
1658 av_log(avctx, AV_LOG_ERROR, "Too many channels: %d.\n",
1660 return AVERROR(ENOSYS);
1664 frame->channels = avctx->channels;
1670 int ff_decode_frame_props(AVCodecContext *avctx, AVFrame *frame)
1672 return ff_init_buffer_info(avctx, frame);
1675 static void validate_avframe_allocation(AVCodecContext *avctx, AVFrame *frame)
1677 if (avctx->codec_type == AVMEDIA_TYPE_VIDEO) {
1679 int num_planes = av_pix_fmt_count_planes(frame->format);
1680 const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(frame->format);
1681 int flags = desc ? desc->flags : 0;
1682 if (num_planes == 1 && (flags & AV_PIX_FMT_FLAG_PAL))
1684 for (i = 0; i < num_planes; i++) {
1685 av_assert0(frame->data[i]);
1687 // For now do not enforce anything for palette of pseudopal formats
1688 if (num_planes == 1 && (flags & AV_PIX_FMT_FLAG_PSEUDOPAL))
1690 // For formats without data like hwaccel allow unused pointers to be non-NULL.
1691 for (i = num_planes; num_planes > 0 && i < FF_ARRAY_ELEMS(frame->data); i++) {
1693 av_log(avctx, AV_LOG_ERROR, "Buffer returned by get_buffer2() did not zero unused plane pointers\n");
1694 frame->data[i] = NULL;
1699 static int get_buffer_internal(AVCodecContext *avctx, AVFrame *frame, int flags)
1701 const AVHWAccel *hwaccel = avctx->hwaccel;
1702 int override_dimensions = 1;
1705 if (avctx->codec_type == AVMEDIA_TYPE_VIDEO) {
1706 if ((ret = av_image_check_size2(avctx->width, avctx->height, avctx->max_pixels, AV_PIX_FMT_NONE, 0, avctx)) < 0 || avctx->pix_fmt<0) {
1707 av_log(avctx, AV_LOG_ERROR, "video_get_buffer: image parameters invalid\n");
1708 return AVERROR(EINVAL);
1711 if (frame->width <= 0 || frame->height <= 0) {
1712 frame->width = FFMAX(avctx->width, AV_CEIL_RSHIFT(avctx->coded_width, avctx->lowres));
1713 frame->height = FFMAX(avctx->height, AV_CEIL_RSHIFT(avctx->coded_height, avctx->lowres));
1714 override_dimensions = 0;
1717 if (frame->data[0] || frame->data[1] || frame->data[2] || frame->data[3]) {
1718 av_log(avctx, AV_LOG_ERROR, "pic->data[*]!=NULL in get_buffer_internal\n");
1719 return AVERROR(EINVAL);
1722 ret = ff_decode_frame_props(avctx, frame);
1727 if (hwaccel->alloc_frame) {
1728 ret = hwaccel->alloc_frame(avctx, frame);
1732 avctx->sw_pix_fmt = avctx->pix_fmt;
1734 ret = avctx->get_buffer2(avctx, frame, flags);
1736 validate_avframe_allocation(avctx, frame);
1739 if (avctx->codec_type == AVMEDIA_TYPE_VIDEO && !override_dimensions &&
1740 !(avctx->codec->caps_internal & FF_CODEC_CAP_EXPORTS_CROPPING)) {
1741 frame->width = avctx->width;
1742 frame->height = avctx->height;
1748 int ff_get_buffer(AVCodecContext *avctx, AVFrame *frame, int flags)
1750 int ret = get_buffer_internal(avctx, frame, flags);
1752 av_log(avctx, AV_LOG_ERROR, "get_buffer() failed\n");
1753 frame->width = frame->height = 0;
1758 static int reget_buffer_internal(AVCodecContext *avctx, AVFrame *frame)
1763 av_assert0(avctx->codec_type == AVMEDIA_TYPE_VIDEO);
1765 if (frame->data[0] && (frame->width != avctx->width || frame->height != avctx->height || frame->format != avctx->pix_fmt)) {
1766 av_log(avctx, AV_LOG_WARNING, "Picture changed from size:%dx%d fmt:%s to size:%dx%d fmt:%s in reget buffer()\n",
1767 frame->width, frame->height, av_get_pix_fmt_name(frame->format), avctx->width, avctx->height, av_get_pix_fmt_name(avctx->pix_fmt));
1768 av_frame_unref(frame);
1771 ff_init_buffer_info(avctx, frame);
1773 if (!frame->data[0])
1774 return ff_get_buffer(avctx, frame, AV_GET_BUFFER_FLAG_REF);
1776 if (av_frame_is_writable(frame))
1777 return ff_decode_frame_props(avctx, frame);
1779 tmp = av_frame_alloc();
1781 return AVERROR(ENOMEM);
1783 av_frame_move_ref(tmp, frame);
1785 ret = ff_get_buffer(avctx, frame, AV_GET_BUFFER_FLAG_REF);
1787 av_frame_free(&tmp);
1791 av_frame_copy(frame, tmp);
1792 av_frame_free(&tmp);
1797 int ff_reget_buffer(AVCodecContext *avctx, AVFrame *frame)
1799 int ret = reget_buffer_internal(avctx, frame);
1801 av_log(avctx, AV_LOG_ERROR, "reget_buffer() failed\n");
1805 void avcodec_flush_buffers(AVCodecContext *avctx)
1807 avctx->internal->draining = 0;
1808 avctx->internal->draining_done = 0;
1809 avctx->internal->nb_draining_errors = 0;
1810 av_frame_unref(avctx->internal->buffer_frame);
1811 av_frame_unref(avctx->internal->compat_decode_frame);
1812 av_packet_unref(avctx->internal->buffer_pkt);
1813 avctx->internal->buffer_pkt_valid = 0;
1815 av_packet_unref(avctx->internal->ds.in_pkt);
1817 if (HAVE_THREADS && avctx->active_thread_type & FF_THREAD_FRAME)
1818 ff_thread_flush(avctx);
1819 else if (avctx->codec->flush)
1820 avctx->codec->flush(avctx);
1822 avctx->pts_correction_last_pts =
1823 avctx->pts_correction_last_dts = INT64_MIN;
1825 ff_decode_bsfs_uninit(avctx);
1827 if (!avctx->refcounted_frames)
1828 av_frame_unref(avctx->internal->to_free);
1831 void ff_decode_bsfs_uninit(AVCodecContext *avctx)
1833 DecodeFilterContext *s = &avctx->internal->filter;
1836 for (i = 0; i < s->nb_bsfs; i++)
1837 av_bsf_free(&s->bsfs[i]);