2 * generic decoding-related code
4 * This file is part of FFmpeg.
6 * FFmpeg is free software; you can redistribute it and/or
7 * modify it under the terms of the GNU Lesser General Public
8 * License as published by the Free Software Foundation; either
9 * version 2.1 of the License, or (at your option) any later version.
11 * FFmpeg is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14 * Lesser General Public License for more details.
16 * You should have received a copy of the GNU Lesser General Public
17 * License along with FFmpeg; if not, write to the Free Software
18 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
30 #include "libavutil/avassert.h"
31 #include "libavutil/avstring.h"
32 #include "libavutil/bprint.h"
33 #include "libavutil/common.h"
34 #include "libavutil/frame.h"
35 #include "libavutil/hwcontext.h"
36 #include "libavutil/imgutils.h"
37 #include "libavutil/internal.h"
38 #include "libavutil/intmath.h"
41 #include "bytestream.h"
47 static int apply_param_change(AVCodecContext *avctx, const AVPacket *avpkt)
54 data = av_packet_get_side_data(avpkt, AV_PKT_DATA_PARAM_CHANGE, &size);
58 if (!(avctx->codec->capabilities & AV_CODEC_CAP_PARAM_CHANGE)) {
59 av_log(avctx, AV_LOG_ERROR, "This decoder does not support parameter "
60 "changes, but PARAM_CHANGE side data was sent to it.\n");
61 ret = AVERROR(EINVAL);
68 flags = bytestream_get_le32(&data);
71 if (flags & AV_SIDE_DATA_PARAM_CHANGE_CHANNEL_COUNT) {
74 val = bytestream_get_le32(&data);
75 if (val <= 0 || val > INT_MAX) {
76 av_log(avctx, AV_LOG_ERROR, "Invalid channel count");
77 ret = AVERROR_INVALIDDATA;
80 avctx->channels = val;
83 if (flags & AV_SIDE_DATA_PARAM_CHANGE_CHANNEL_LAYOUT) {
86 avctx->channel_layout = bytestream_get_le64(&data);
89 if (flags & AV_SIDE_DATA_PARAM_CHANGE_SAMPLE_RATE) {
92 val = bytestream_get_le32(&data);
93 if (val <= 0 || val > INT_MAX) {
94 av_log(avctx, AV_LOG_ERROR, "Invalid sample rate");
95 ret = AVERROR_INVALIDDATA;
98 avctx->sample_rate = val;
101 if (flags & AV_SIDE_DATA_PARAM_CHANGE_DIMENSIONS) {
104 avctx->width = bytestream_get_le32(&data);
105 avctx->height = bytestream_get_le32(&data);
107 ret = ff_set_dimensions(avctx, avctx->width, avctx->height);
114 av_log(avctx, AV_LOG_ERROR, "PARAM_CHANGE side data too small.\n");
115 ret = AVERROR_INVALIDDATA;
118 av_log(avctx, AV_LOG_ERROR, "Error applying parameter changes.\n");
119 if (avctx->err_recognition & AV_EF_EXPLODE)
125 static int extract_packet_props(AVCodecInternal *avci, const AVPacket *pkt)
129 av_packet_unref(avci->last_pkt_props);
131 ret = av_packet_copy_props(avci->last_pkt_props, pkt);
133 avci->last_pkt_props->size = pkt->size; // HACK: Needed for ff_decode_frame_props().
138 static int unrefcount_frame(AVCodecInternal *avci, AVFrame *frame)
142 /* move the original frame to our backup */
143 av_frame_unref(avci->to_free);
144 av_frame_move_ref(avci->to_free, frame);
146 /* now copy everything except the AVBufferRefs back
147 * note that we make a COPY of the side data, so calling av_frame_free() on
148 * the caller's frame will work properly */
149 ret = av_frame_copy_props(frame, avci->to_free);
153 memcpy(frame->data, avci->to_free->data, sizeof(frame->data));
154 memcpy(frame->linesize, avci->to_free->linesize, sizeof(frame->linesize));
155 if (avci->to_free->extended_data != avci->to_free->data) {
156 int planes = avci->to_free->channels;
157 int size = planes * sizeof(*frame->extended_data);
160 av_frame_unref(frame);
164 frame->extended_data = av_malloc(size);
165 if (!frame->extended_data) {
166 av_frame_unref(frame);
167 return AVERROR(ENOMEM);
169 memcpy(frame->extended_data, avci->to_free->extended_data,
172 frame->extended_data = frame->data;
174 frame->format = avci->to_free->format;
175 frame->width = avci->to_free->width;
176 frame->height = avci->to_free->height;
177 frame->channel_layout = avci->to_free->channel_layout;
178 frame->nb_samples = avci->to_free->nb_samples;
179 frame->channels = avci->to_free->channels;
184 static int bsfs_init(AVCodecContext *avctx)
186 AVCodecInternal *avci = avctx->internal;
187 DecodeFilterContext *s = &avci->filter;
188 const char *bsfs_str;
194 bsfs_str = avctx->codec->bsfs ? avctx->codec->bsfs : "null";
195 while (bsfs_str && *bsfs_str) {
197 const AVBitStreamFilter *filter;
200 bsf = av_get_token(&bsfs_str, ",");
202 ret = AVERROR(ENOMEM);
206 filter = av_bsf_get_by_name(bsf);
208 av_log(avctx, AV_LOG_ERROR, "A non-existing bitstream filter %s "
209 "requested by a decoder. This is a bug, please report it.\n",
217 tmp = av_realloc_array(s->bsfs, s->nb_bsfs + 1, sizeof(*s->bsfs));
219 ret = AVERROR(ENOMEM);
225 ret = av_bsf_alloc(filter, &s->bsfs[s->nb_bsfs - 1]);
229 if (s->nb_bsfs == 1) {
230 /* We do not currently have an API for passing the input timebase into decoders,
231 * but no filters used here should actually need it.
232 * So we make up some plausible-looking number (the MPEG 90kHz timebase) */
233 s->bsfs[s->nb_bsfs - 1]->time_base_in = (AVRational){ 1, 90000 };
234 ret = avcodec_parameters_from_context(s->bsfs[s->nb_bsfs - 1]->par_in,
237 s->bsfs[s->nb_bsfs - 1]->time_base_in = s->bsfs[s->nb_bsfs - 2]->time_base_out;
238 ret = avcodec_parameters_copy(s->bsfs[s->nb_bsfs - 1]->par_in,
239 s->bsfs[s->nb_bsfs - 2]->par_out);
244 ret = av_bsf_init(s->bsfs[s->nb_bsfs - 1]);
251 ff_decode_bsfs_uninit(avctx);
255 /* try to get one output packet from the filter chain */
256 static int bsfs_poll(AVCodecContext *avctx, AVPacket *pkt)
258 DecodeFilterContext *s = &avctx->internal->filter;
261 /* start with the last filter in the chain */
262 idx = s->nb_bsfs - 1;
264 /* request a packet from the currently selected filter */
265 ret = av_bsf_receive_packet(s->bsfs[idx], pkt);
266 if (ret == AVERROR(EAGAIN)) {
267 /* no packets available, try the next filter up the chain */
271 } else if (ret < 0 && ret != AVERROR_EOF) {
275 /* got a packet or EOF -- pass it to the caller or to the next filter
277 if (idx == s->nb_bsfs - 1) {
281 ret = av_bsf_send_packet(s->bsfs[idx], ret < 0 ? NULL : pkt);
283 av_log(avctx, AV_LOG_ERROR,
284 "Error pre-processing a packet before decoding\n");
285 av_packet_unref(pkt);
291 return AVERROR(EAGAIN);
294 int ff_decode_get_packet(AVCodecContext *avctx, AVPacket *pkt)
296 AVCodecInternal *avci = avctx->internal;
302 ret = bsfs_poll(avctx, pkt);
303 if (ret == AVERROR_EOF)
308 ret = extract_packet_props(avctx->internal, pkt);
312 ret = apply_param_change(avctx, pkt);
316 if (avctx->codec->receive_frame)
317 avci->compat_decode_consumed += pkt->size;
321 av_packet_unref(pkt);
326 * Attempt to guess proper monotonic timestamps for decoded video frames
327 * which might have incorrect times. Input timestamps may wrap around, in
328 * which case the output will as well.
330 * @param pts the pts field of the decoded AVPacket, as passed through
332 * @param dts the dts field of the decoded AVPacket
333 * @return one of the input values, may be AV_NOPTS_VALUE
335 static int64_t guess_correct_pts(AVCodecContext *ctx,
336 int64_t reordered_pts, int64_t dts)
338 int64_t pts = AV_NOPTS_VALUE;
340 if (dts != AV_NOPTS_VALUE) {
341 ctx->pts_correction_num_faulty_dts += dts <= ctx->pts_correction_last_dts;
342 ctx->pts_correction_last_dts = dts;
343 } else if (reordered_pts != AV_NOPTS_VALUE)
344 ctx->pts_correction_last_dts = reordered_pts;
346 if (reordered_pts != AV_NOPTS_VALUE) {
347 ctx->pts_correction_num_faulty_pts += reordered_pts <= ctx->pts_correction_last_pts;
348 ctx->pts_correction_last_pts = reordered_pts;
349 } else if(dts != AV_NOPTS_VALUE)
350 ctx->pts_correction_last_pts = dts;
352 if ((ctx->pts_correction_num_faulty_pts<=ctx->pts_correction_num_faulty_dts || dts == AV_NOPTS_VALUE)
353 && reordered_pts != AV_NOPTS_VALUE)
362 * The core of the receive_frame_wrapper for the decoders implementing
363 * the simple API. Certain decoders might consume partial packets without
364 * returning any output, so this function needs to be called in a loop until it
367 static int decode_simple_internal(AVCodecContext *avctx, AVFrame *frame)
369 AVCodecInternal *avci = avctx->internal;
370 DecodeSimpleContext *ds = &avci->ds;
371 AVPacket *pkt = ds->in_pkt;
372 // copy to ensure we do not change pkt
373 int got_frame, actual_got_frame;
376 if (!pkt->data && !avci->draining) {
377 av_packet_unref(pkt);
378 ret = ff_decode_get_packet(avctx, pkt);
379 if (ret < 0 && ret != AVERROR_EOF)
383 // Some codecs (at least wma lossless) will crash when feeding drain packets
384 // after EOF was signaled.
385 if (avci->draining_done)
389 !(avctx->codec->capabilities & AV_CODEC_CAP_DELAY ||
390 avctx->active_thread_type & FF_THREAD_FRAME))
395 if (HAVE_THREADS && avctx->active_thread_type & FF_THREAD_FRAME) {
396 ret = ff_thread_decode_frame(avctx, frame, &got_frame, pkt);
398 ret = avctx->codec->decode(avctx, frame, &got_frame, pkt);
400 if (!(avctx->codec->caps_internal & FF_CODEC_CAP_SETS_PKT_DTS))
401 frame->pkt_dts = pkt->dts;
402 if (avctx->codec->type == AVMEDIA_TYPE_VIDEO) {
403 if(!avctx->has_b_frames)
404 frame->pkt_pos = pkt->pos;
405 //FIXME these should be under if(!avctx->has_b_frames)
406 /* get_buffer is supposed to set frame parameters */
407 if (!(avctx->codec->capabilities & AV_CODEC_CAP_DR1)) {
408 if (!frame->sample_aspect_ratio.num) frame->sample_aspect_ratio = avctx->sample_aspect_ratio;
409 if (!frame->width) frame->width = avctx->width;
410 if (!frame->height) frame->height = avctx->height;
411 if (frame->format == AV_PIX_FMT_NONE) frame->format = avctx->pix_fmt;
416 actual_got_frame = got_frame;
418 if (avctx->codec->type == AVMEDIA_TYPE_VIDEO) {
419 if (frame->flags & AV_FRAME_FLAG_DISCARD)
422 frame->best_effort_timestamp = guess_correct_pts(avctx,
425 } else if (avctx->codec->type == AVMEDIA_TYPE_AUDIO) {
428 uint32_t discard_padding = 0;
429 uint8_t skip_reason = 0;
430 uint8_t discard_reason = 0;
432 if (ret >= 0 && got_frame) {
433 frame->best_effort_timestamp = guess_correct_pts(avctx,
436 if (frame->format == AV_SAMPLE_FMT_NONE)
437 frame->format = avctx->sample_fmt;
438 if (!frame->channel_layout)
439 frame->channel_layout = avctx->channel_layout;
440 if (!frame->channels)
441 frame->channels = avctx->channels;
442 if (!frame->sample_rate)
443 frame->sample_rate = avctx->sample_rate;
446 side= av_packet_get_side_data(avci->last_pkt_props, AV_PKT_DATA_SKIP_SAMPLES, &side_size);
447 if(side && side_size>=10) {
448 avctx->internal->skip_samples = AV_RL32(side) * avctx->internal->skip_samples_multiplier;
449 discard_padding = AV_RL32(side + 4);
450 av_log(avctx, AV_LOG_DEBUG, "skip %d / discard %d samples due to side data\n",
451 avctx->internal->skip_samples, (int)discard_padding);
452 skip_reason = AV_RL8(side + 8);
453 discard_reason = AV_RL8(side + 9);
456 if ((frame->flags & AV_FRAME_FLAG_DISCARD) && got_frame &&
457 !(avctx->flags2 & AV_CODEC_FLAG2_SKIP_MANUAL)) {
458 avctx->internal->skip_samples = FFMAX(0, avctx->internal->skip_samples - frame->nb_samples);
462 if (avctx->internal->skip_samples > 0 && got_frame &&
463 !(avctx->flags2 & AV_CODEC_FLAG2_SKIP_MANUAL)) {
464 if(frame->nb_samples <= avctx->internal->skip_samples){
466 avctx->internal->skip_samples -= frame->nb_samples;
467 av_log(avctx, AV_LOG_DEBUG, "skip whole frame, skip left: %d\n",
468 avctx->internal->skip_samples);
470 av_samples_copy(frame->extended_data, frame->extended_data, 0, avctx->internal->skip_samples,
471 frame->nb_samples - avctx->internal->skip_samples, avctx->channels, frame->format);
472 if(avctx->pkt_timebase.num && avctx->sample_rate) {
473 int64_t diff_ts = av_rescale_q(avctx->internal->skip_samples,
474 (AVRational){1, avctx->sample_rate},
475 avctx->pkt_timebase);
476 if(frame->pts!=AV_NOPTS_VALUE)
477 frame->pts += diff_ts;
479 FF_DISABLE_DEPRECATION_WARNINGS
480 if(frame->pkt_pts!=AV_NOPTS_VALUE)
481 frame->pkt_pts += diff_ts;
482 FF_ENABLE_DEPRECATION_WARNINGS
484 if(frame->pkt_dts!=AV_NOPTS_VALUE)
485 frame->pkt_dts += diff_ts;
486 if (frame->pkt_duration >= diff_ts)
487 frame->pkt_duration -= diff_ts;
489 av_log(avctx, AV_LOG_WARNING, "Could not update timestamps for skipped samples.\n");
491 av_log(avctx, AV_LOG_DEBUG, "skip %d/%d samples\n",
492 avctx->internal->skip_samples, frame->nb_samples);
493 frame->nb_samples -= avctx->internal->skip_samples;
494 avctx->internal->skip_samples = 0;
498 if (discard_padding > 0 && discard_padding <= frame->nb_samples && got_frame &&
499 !(avctx->flags2 & AV_CODEC_FLAG2_SKIP_MANUAL)) {
500 if (discard_padding == frame->nb_samples) {
503 if(avctx->pkt_timebase.num && avctx->sample_rate) {
504 int64_t diff_ts = av_rescale_q(frame->nb_samples - discard_padding,
505 (AVRational){1, avctx->sample_rate},
506 avctx->pkt_timebase);
507 frame->pkt_duration = diff_ts;
509 av_log(avctx, AV_LOG_WARNING, "Could not update timestamps for discarded samples.\n");
511 av_log(avctx, AV_LOG_DEBUG, "discard %d/%d samples\n",
512 (int)discard_padding, frame->nb_samples);
513 frame->nb_samples -= discard_padding;
517 if ((avctx->flags2 & AV_CODEC_FLAG2_SKIP_MANUAL) && got_frame) {
518 AVFrameSideData *fside = av_frame_new_side_data(frame, AV_FRAME_DATA_SKIP_SAMPLES, 10);
520 AV_WL32(fside->data, avctx->internal->skip_samples);
521 AV_WL32(fside->data + 4, discard_padding);
522 AV_WL8(fside->data + 8, skip_reason);
523 AV_WL8(fside->data + 9, discard_reason);
524 avctx->internal->skip_samples = 0;
529 if (avctx->codec->type == AVMEDIA_TYPE_AUDIO &&
530 !avci->showed_multi_packet_warning &&
531 ret >= 0 && ret != pkt->size && !(avctx->codec->capabilities & AV_CODEC_CAP_SUBFRAMES)) {
532 av_log(avctx, AV_LOG_WARNING, "Multiple frames in a packet.\n");
533 avci->showed_multi_packet_warning = 1;
537 av_frame_unref(frame);
539 if (ret >= 0 && avctx->codec->type == AVMEDIA_TYPE_VIDEO && !(avctx->flags & AV_CODEC_FLAG_TRUNCATED))
542 #if FF_API_AVCTX_TIMEBASE
543 if (avctx->framerate.num > 0 && avctx->framerate.den > 0)
544 avctx->time_base = av_inv_q(av_mul_q(avctx->framerate, (AVRational){avctx->ticks_per_frame, 1}));
547 /* do not stop draining when actual_got_frame != 0 or ret < 0 */
548 /* got_frame == 0 but actual_got_frame != 0 when frame is discarded */
549 if (avctx->internal->draining && !actual_got_frame) {
551 /* prevent infinite loop if a decoder wrongly always return error on draining */
552 /* reasonable nb_errors_max = maximum b frames + thread count */
553 int nb_errors_max = 20 + (HAVE_THREADS && avctx->active_thread_type & FF_THREAD_FRAME ?
554 avctx->thread_count : 1);
556 if (avci->nb_draining_errors++ >= nb_errors_max) {
557 av_log(avctx, AV_LOG_ERROR, "Too many errors when draining, this is a bug. "
558 "Stop draining and force EOF.\n");
559 avci->draining_done = 1;
563 avci->draining_done = 1;
567 avci->compat_decode_consumed += ret;
569 if (ret >= pkt->size || ret < 0) {
570 av_packet_unref(pkt);
574 pkt->data += consumed;
575 pkt->size -= consumed;
576 avci->last_pkt_props->size -= consumed; // See extract_packet_props() comment.
577 pkt->pts = AV_NOPTS_VALUE;
578 pkt->dts = AV_NOPTS_VALUE;
579 avci->last_pkt_props->pts = AV_NOPTS_VALUE;
580 avci->last_pkt_props->dts = AV_NOPTS_VALUE;
584 av_assert0(frame->buf[0]);
586 return ret < 0 ? ret : 0;
589 static int decode_simple_receive_frame(AVCodecContext *avctx, AVFrame *frame)
593 while (!frame->buf[0]) {
594 ret = decode_simple_internal(avctx, frame);
602 static int decode_receive_frame_internal(AVCodecContext *avctx, AVFrame *frame)
604 AVCodecInternal *avci = avctx->internal;
607 av_assert0(!frame->buf[0]);
609 if (avctx->codec->receive_frame)
610 ret = avctx->codec->receive_frame(avctx, frame);
612 ret = decode_simple_receive_frame(avctx, frame);
614 if (ret == AVERROR_EOF)
615 avci->draining_done = 1;
618 /* the only case where decode data is not set should be decoders
619 * that do not call ff_get_buffer() */
620 av_assert0((frame->private_ref && frame->private_ref->size == sizeof(FrameDecodeData)) ||
621 !(avctx->codec->capabilities & AV_CODEC_CAP_DR1));
623 if (frame->private_ref) {
624 FrameDecodeData *fdd = (FrameDecodeData*)frame->private_ref->data;
626 if (fdd->post_process) {
627 ret = fdd->post_process(avctx, frame);
629 av_frame_unref(frame);
636 /* free the per-frame decode data */
637 av_buffer_unref(&frame->private_ref);
642 int attribute_align_arg avcodec_send_packet(AVCodecContext *avctx, const AVPacket *avpkt)
644 AVCodecInternal *avci = avctx->internal;
647 if (!avcodec_is_open(avctx) || !av_codec_is_decoder(avctx->codec))
648 return AVERROR(EINVAL);
650 if (avctx->internal->draining)
653 if (avpkt && !avpkt->size && avpkt->data)
654 return AVERROR(EINVAL);
656 ret = bsfs_init(avctx);
660 av_packet_unref(avci->buffer_pkt);
661 if (avpkt && (avpkt->data || avpkt->side_data_elems)) {
662 ret = av_packet_ref(avci->buffer_pkt, avpkt);
667 ret = av_bsf_send_packet(avci->filter.bsfs[0], avci->buffer_pkt);
669 av_packet_unref(avci->buffer_pkt);
673 if (!avci->buffer_frame->buf[0]) {
674 ret = decode_receive_frame_internal(avctx, avci->buffer_frame);
675 if (ret < 0 && ret != AVERROR(EAGAIN) && ret != AVERROR_EOF)
682 static int apply_cropping(AVCodecContext *avctx, AVFrame *frame)
684 /* make sure we are noisy about decoders returning invalid cropping data */
685 if (frame->crop_left >= INT_MAX - frame->crop_right ||
686 frame->crop_top >= INT_MAX - frame->crop_bottom ||
687 (frame->crop_left + frame->crop_right) >= frame->width ||
688 (frame->crop_top + frame->crop_bottom) >= frame->height) {
689 av_log(avctx, AV_LOG_WARNING,
690 "Invalid cropping information set by a decoder: "
691 "%"SIZE_SPECIFIER"/%"SIZE_SPECIFIER"/%"SIZE_SPECIFIER"/%"SIZE_SPECIFIER" "
692 "(frame size %dx%d). This is a bug, please report it\n",
693 frame->crop_left, frame->crop_right, frame->crop_top, frame->crop_bottom,
694 frame->width, frame->height);
695 frame->crop_left = 0;
696 frame->crop_right = 0;
698 frame->crop_bottom = 0;
702 if (!avctx->apply_cropping)
705 return av_frame_apply_cropping(frame, avctx->flags & AV_CODEC_FLAG_UNALIGNED ?
706 AV_FRAME_CROP_UNALIGNED : 0);
709 int attribute_align_arg avcodec_receive_frame(AVCodecContext *avctx, AVFrame *frame)
711 AVCodecInternal *avci = avctx->internal;
714 av_frame_unref(frame);
716 if (!avcodec_is_open(avctx) || !av_codec_is_decoder(avctx->codec))
717 return AVERROR(EINVAL);
719 ret = bsfs_init(avctx);
723 if (avci->buffer_frame->buf[0]) {
724 av_frame_move_ref(frame, avci->buffer_frame);
726 ret = decode_receive_frame_internal(avctx, frame);
731 if (avctx->codec_type == AVMEDIA_TYPE_VIDEO) {
732 ret = apply_cropping(avctx, frame);
734 av_frame_unref(frame);
739 avctx->frame_number++;
744 static int compat_decode(AVCodecContext *avctx, AVFrame *frame,
745 int *got_frame, const AVPacket *pkt)
747 AVCodecInternal *avci = avctx->internal;
750 av_assert0(avci->compat_decode_consumed == 0);
752 if (avci->draining_done && pkt && pkt->size != 0) {
753 av_log(avctx, AV_LOG_WARNING, "Got unexpected packet after EOF\n");
754 avcodec_flush_buffers(avctx);
758 avci->compat_decode = 1;
760 if (avci->compat_decode_partial_size > 0 &&
761 avci->compat_decode_partial_size != pkt->size) {
762 av_log(avctx, AV_LOG_ERROR,
763 "Got unexpected packet size after a partial decode\n");
764 ret = AVERROR(EINVAL);
768 if (!avci->compat_decode_partial_size) {
769 ret = avcodec_send_packet(avctx, pkt);
770 if (ret == AVERROR_EOF)
772 else if (ret == AVERROR(EAGAIN)) {
773 /* we fully drain all the output in each decode call, so this should not
782 ret = avcodec_receive_frame(avctx, frame);
784 if (ret == AVERROR(EAGAIN) || ret == AVERROR_EOF)
789 if (frame != avci->compat_decode_frame) {
790 if (!avctx->refcounted_frames) {
791 ret = unrefcount_frame(avci, frame);
797 frame = avci->compat_decode_frame;
799 if (!avci->compat_decode_warned) {
800 av_log(avctx, AV_LOG_WARNING, "The deprecated avcodec_decode_* "
801 "API cannot return all the frames for this decoder. "
802 "Some frames will be dropped. Update your code to the "
803 "new decoding API to fix this.\n");
804 avci->compat_decode_warned = 1;
808 if (avci->draining || (!avctx->codec->bsfs && avci->compat_decode_consumed < pkt->size))
814 /* if there are any bsfs then assume full packet is always consumed */
815 if (avctx->codec->bsfs)
818 ret = FFMIN(avci->compat_decode_consumed, pkt->size);
820 avci->compat_decode_consumed = 0;
821 avci->compat_decode_partial_size = (ret >= 0) ? pkt->size - ret : 0;
826 int attribute_align_arg avcodec_decode_video2(AVCodecContext *avctx, AVFrame *picture,
827 int *got_picture_ptr,
828 const AVPacket *avpkt)
830 return compat_decode(avctx, picture, got_picture_ptr, avpkt);
833 int attribute_align_arg avcodec_decode_audio4(AVCodecContext *avctx,
836 const AVPacket *avpkt)
838 return compat_decode(avctx, frame, got_frame_ptr, avpkt);
841 static void get_subtitle_defaults(AVSubtitle *sub)
843 memset(sub, 0, sizeof(*sub));
844 sub->pts = AV_NOPTS_VALUE;
847 #define UTF8_MAX_BYTES 4 /* 5 and 6 bytes sequences should not be used */
848 static int recode_subtitle(AVCodecContext *avctx,
849 AVPacket *outpkt, const AVPacket *inpkt)
852 iconv_t cd = (iconv_t)-1;
859 if (avctx->sub_charenc_mode != FF_SUB_CHARENC_MODE_PRE_DECODER || inpkt->size == 0)
863 cd = iconv_open("UTF-8", avctx->sub_charenc);
864 av_assert0(cd != (iconv_t)-1);
869 if (inl >= INT_MAX / UTF8_MAX_BYTES - AV_INPUT_BUFFER_PADDING_SIZE) {
870 av_log(avctx, AV_LOG_ERROR, "Subtitles packet is too big for recoding\n");
871 ret = AVERROR(ENOMEM);
875 ret = av_new_packet(&tmp, inl * UTF8_MAX_BYTES);
878 outpkt->buf = tmp.buf;
879 outpkt->data = tmp.data;
880 outpkt->size = tmp.size;
884 if (iconv(cd, &inb, &inl, &outb, &outl) == (size_t)-1 ||
885 iconv(cd, NULL, NULL, &outb, &outl) == (size_t)-1 ||
886 outl >= outpkt->size || inl != 0) {
887 ret = FFMIN(AVERROR(errno), -1);
888 av_log(avctx, AV_LOG_ERROR, "Unable to recode subtitle event \"%s\" "
889 "from %s to UTF-8\n", inpkt->data, avctx->sub_charenc);
890 av_packet_unref(&tmp);
893 outpkt->size -= outl;
894 memset(outpkt->data + outpkt->size, 0, outl);
897 if (cd != (iconv_t)-1)
901 av_log(avctx, AV_LOG_ERROR, "requesting subtitles recoding without iconv");
902 return AVERROR(EINVAL);
906 static int utf8_check(const uint8_t *str)
909 uint32_t codepoint, min;
913 GET_UTF8(codepoint, *(byte++), return 0;);
914 min = byte - str == 1 ? 0 : byte - str == 2 ? 0x80 :
915 1 << (5 * (byte - str) - 4);
916 if (codepoint < min || codepoint >= 0x110000 ||
917 codepoint == 0xFFFE /* BOM */ ||
918 codepoint >= 0xD800 && codepoint <= 0xDFFF /* surrogates */)
925 #if FF_API_ASS_TIMING
926 static void insert_ts(AVBPrint *buf, int ts)
929 av_bprintf(buf, "9:59:59.99,");
933 h = ts/360000; ts -= 360000*h;
934 m = ts/ 6000; ts -= 6000*m;
935 s = ts/ 100; ts -= 100*s;
936 av_bprintf(buf, "%d:%02d:%02d.%02d,", h, m, s, ts);
940 static int convert_sub_to_old_ass_form(AVSubtitle *sub, const AVPacket *pkt, AVRational tb)
945 av_bprint_init(&buf, 0, AV_BPRINT_SIZE_UNLIMITED);
947 for (i = 0; i < sub->num_rects; i++) {
950 AVSubtitleRect *rect = sub->rects[i];
951 int ts_start, ts_duration = -1;
954 if (rect->type != SUBTITLE_ASS || !strncmp(rect->ass, "Dialogue: ", 10))
957 av_bprint_clear(&buf);
960 dialog = strchr(rect->ass, ',');
965 /* extract Layer or Marked */
966 layer = strtol(dialog, (char**)&dialog, 10);
971 /* rescale timing to ASS time base (ms) */
972 ts_start = av_rescale_q(pkt->pts, tb, av_make_q(1, 100));
973 if (pkt->duration != -1)
974 ts_duration = av_rescale_q(pkt->duration, tb, av_make_q(1, 100));
975 sub->end_display_time = FFMAX(sub->end_display_time, 10 * ts_duration);
977 /* construct ASS (standalone file form with timestamps) string */
978 av_bprintf(&buf, "Dialogue: %ld,", layer);
979 insert_ts(&buf, ts_start);
980 insert_ts(&buf, ts_duration == -1 ? -1 : ts_start + ts_duration);
981 av_bprintf(&buf, "%s\r\n", dialog);
983 final_dialog = av_strdup(buf.str);
984 if (!av_bprint_is_complete(&buf) || !final_dialog) {
985 av_freep(&final_dialog);
986 av_bprint_finalize(&buf, NULL);
987 return AVERROR(ENOMEM);
989 av_freep(&rect->ass);
990 rect->ass = final_dialog;
993 av_bprint_finalize(&buf, NULL);
998 int avcodec_decode_subtitle2(AVCodecContext *avctx, AVSubtitle *sub,
1004 if (!avpkt->data && avpkt->size) {
1005 av_log(avctx, AV_LOG_ERROR, "invalid packet: NULL data, size != 0\n");
1006 return AVERROR(EINVAL);
1009 return AVERROR(EINVAL);
1010 if (avctx->codec->type != AVMEDIA_TYPE_SUBTITLE) {
1011 av_log(avctx, AV_LOG_ERROR, "Invalid media type for subtitles\n");
1012 return AVERROR(EINVAL);
1016 get_subtitle_defaults(sub);
1018 if ((avctx->codec->capabilities & AV_CODEC_CAP_DELAY) || avpkt->size) {
1019 AVPacket pkt_recoded = *avpkt;
1021 ret = recode_subtitle(avctx, &pkt_recoded, avpkt);
1025 ret = extract_packet_props(avctx->internal, &pkt_recoded);
1029 if (avctx->pkt_timebase.num && avpkt->pts != AV_NOPTS_VALUE)
1030 sub->pts = av_rescale_q(avpkt->pts,
1031 avctx->pkt_timebase, AV_TIME_BASE_Q);
1032 ret = avctx->codec->decode(avctx, sub, got_sub_ptr, &pkt_recoded);
1033 av_assert1((ret >= 0) >= !!*got_sub_ptr &&
1034 !!*got_sub_ptr >= !!sub->num_rects);
1036 #if FF_API_ASS_TIMING
1037 if (avctx->sub_text_format == FF_SUB_TEXT_FMT_ASS_WITH_TIMINGS
1038 && *got_sub_ptr && sub->num_rects) {
1039 const AVRational tb = avctx->pkt_timebase.num ? avctx->pkt_timebase
1041 int err = convert_sub_to_old_ass_form(sub, avpkt, tb);
1047 if (sub->num_rects && !sub->end_display_time && avpkt->duration &&
1048 avctx->pkt_timebase.num) {
1049 AVRational ms = { 1, 1000 };
1050 sub->end_display_time = av_rescale_q(avpkt->duration,
1051 avctx->pkt_timebase, ms);
1054 if (avctx->codec_descriptor->props & AV_CODEC_PROP_BITMAP_SUB)
1056 else if (avctx->codec_descriptor->props & AV_CODEC_PROP_TEXT_SUB)
1059 for (i = 0; i < sub->num_rects; i++) {
1060 if (avctx->sub_charenc_mode != FF_SUB_CHARENC_MODE_IGNORE &&
1061 sub->rects[i]->ass && !utf8_check(sub->rects[i]->ass)) {
1062 av_log(avctx, AV_LOG_ERROR,
1063 "Invalid UTF-8 in decoded subtitles text; "
1064 "maybe missing -sub_charenc option\n");
1065 avsubtitle_free(sub);
1066 ret = AVERROR_INVALIDDATA;
1071 if (avpkt->data != pkt_recoded.data) { // did we recode?
1072 /* prevent from destroying side data from original packet */
1073 pkt_recoded.side_data = NULL;
1074 pkt_recoded.side_data_elems = 0;
1076 av_packet_unref(&pkt_recoded);
1081 avctx->frame_number++;
1087 enum AVPixelFormat avcodec_default_get_format(struct AVCodecContext *avctx,
1088 const enum AVPixelFormat *fmt)
1090 const AVPixFmtDescriptor *desc;
1091 const AVCodecHWConfig *config;
1094 // If a device was supplied when the codec was opened, assume that the
1095 // user wants to use it.
1096 if (avctx->hw_device_ctx && avctx->codec->hw_configs) {
1097 AVHWDeviceContext *device_ctx =
1098 (AVHWDeviceContext*)avctx->hw_device_ctx->data;
1100 config = &avctx->codec->hw_configs[i]->public;
1103 if (!(config->methods &
1104 AV_CODEC_HW_CONFIG_METHOD_HW_DEVICE_CTX))
1106 if (device_ctx->type != config->device_type)
1108 for (n = 0; fmt[n] != AV_PIX_FMT_NONE; n++) {
1109 if (config->pix_fmt == fmt[n])
1114 // No device or other setup, so we have to choose from things which
1115 // don't any other external information.
1117 // If the last element of the list is a software format, choose it
1118 // (this should be best software format if any exist).
1119 for (n = 0; fmt[n] != AV_PIX_FMT_NONE; n++);
1120 desc = av_pix_fmt_desc_get(fmt[n - 1]);
1121 if (!(desc->flags & AV_PIX_FMT_FLAG_HWACCEL))
1124 // Finally, traverse the list in order and choose the first entry
1125 // with no external dependencies (if there is no hardware configuration
1126 // information available then this just picks the first entry).
1127 for (n = 0; fmt[n] != AV_PIX_FMT_NONE; n++) {
1129 config = avcodec_get_hw_config(avctx->codec, i);
1132 if (config->pix_fmt == fmt[n])
1136 // No specific config available, so the decoder must be able
1137 // to handle this format without any additional setup.
1140 if (config->methods & AV_CODEC_HW_CONFIG_METHOD_INTERNAL) {
1141 // Usable with only internal setup.
1146 // Nothing is usable, give up.
1147 return AV_PIX_FMT_NONE;
1150 int ff_decode_get_hw_frames_ctx(AVCodecContext *avctx,
1151 enum AVHWDeviceType dev_type)
1153 AVHWDeviceContext *device_ctx;
1154 AVHWFramesContext *frames_ctx;
1157 if (!avctx->hwaccel)
1158 return AVERROR(ENOSYS);
1160 if (avctx->hw_frames_ctx)
1162 if (!avctx->hw_device_ctx) {
1163 av_log(avctx, AV_LOG_ERROR, "A hardware frames or device context is "
1164 "required for hardware accelerated decoding.\n");
1165 return AVERROR(EINVAL);
1168 device_ctx = (AVHWDeviceContext *)avctx->hw_device_ctx->data;
1169 if (device_ctx->type != dev_type) {
1170 av_log(avctx, AV_LOG_ERROR, "Device type %s expected for hardware "
1171 "decoding, but got %s.\n", av_hwdevice_get_type_name(dev_type),
1172 av_hwdevice_get_type_name(device_ctx->type));
1173 return AVERROR(EINVAL);
1176 ret = avcodec_get_hw_frames_parameters(avctx,
1177 avctx->hw_device_ctx,
1178 avctx->hwaccel->pix_fmt,
1179 &avctx->hw_frames_ctx);
1183 frames_ctx = (AVHWFramesContext*)avctx->hw_frames_ctx->data;
1186 if (frames_ctx->initial_pool_size) {
1187 // We guarantee 4 base work surfaces. The function above guarantees 1
1188 // (the absolute minimum), so add the missing count.
1189 frames_ctx->initial_pool_size += 3;
1192 ret = av_hwframe_ctx_init(avctx->hw_frames_ctx);
1194 av_buffer_unref(&avctx->hw_frames_ctx);
1201 int avcodec_get_hw_frames_parameters(AVCodecContext *avctx,
1202 AVBufferRef *device_ref,
1203 enum AVPixelFormat hw_pix_fmt,
1204 AVBufferRef **out_frames_ref)
1206 AVBufferRef *frames_ref = NULL;
1207 const AVCodecHWConfigInternal *hw_config;
1208 const AVHWAccel *hwa;
1212 hw_config = avctx->codec->hw_configs[i];
1214 return AVERROR(ENOENT);
1215 if (hw_config->public.pix_fmt == hw_pix_fmt)
1219 hwa = hw_config->hwaccel;
1220 if (!hwa || !hwa->frame_params)
1221 return AVERROR(ENOENT);
1223 frames_ref = av_hwframe_ctx_alloc(device_ref);
1225 return AVERROR(ENOMEM);
1227 ret = hwa->frame_params(avctx, frames_ref);
1229 AVHWFramesContext *frames_ctx = (AVHWFramesContext*)frames_ref->data;
1231 if (frames_ctx->initial_pool_size) {
1232 // If the user has requested that extra output surfaces be
1233 // available then add them here.
1234 if (avctx->extra_hw_frames > 0)
1235 frames_ctx->initial_pool_size += avctx->extra_hw_frames;
1237 // If frame threading is enabled then an extra surface per thread
1238 // is also required.
1239 if (avctx->active_thread_type & FF_THREAD_FRAME)
1240 frames_ctx->initial_pool_size += avctx->thread_count;
1243 *out_frames_ref = frames_ref;
1245 av_buffer_unref(&frames_ref);
1250 static int hwaccel_init(AVCodecContext *avctx,
1251 const AVCodecHWConfigInternal *hw_config)
1253 const AVHWAccel *hwaccel;
1256 hwaccel = hw_config->hwaccel;
1257 if (hwaccel->capabilities & AV_HWACCEL_CODEC_CAP_EXPERIMENTAL &&
1258 avctx->strict_std_compliance > FF_COMPLIANCE_EXPERIMENTAL) {
1259 av_log(avctx, AV_LOG_WARNING, "Ignoring experimental hwaccel: %s\n",
1261 return AVERROR_PATCHWELCOME;
1264 if (hwaccel->priv_data_size) {
1265 avctx->internal->hwaccel_priv_data =
1266 av_mallocz(hwaccel->priv_data_size);
1267 if (!avctx->internal->hwaccel_priv_data)
1268 return AVERROR(ENOMEM);
1271 avctx->hwaccel = hwaccel;
1272 if (hwaccel->init) {
1273 err = hwaccel->init(avctx);
1275 av_log(avctx, AV_LOG_ERROR, "Failed setup for format %s: "
1276 "hwaccel initialisation returned error.\n",
1277 av_get_pix_fmt_name(hw_config->public.pix_fmt));
1278 av_freep(&avctx->internal->hwaccel_priv_data);
1279 avctx->hwaccel = NULL;
1287 static void hwaccel_uninit(AVCodecContext *avctx)
1289 if (avctx->hwaccel && avctx->hwaccel->uninit)
1290 avctx->hwaccel->uninit(avctx);
1292 av_freep(&avctx->internal->hwaccel_priv_data);
1294 avctx->hwaccel = NULL;
1296 av_buffer_unref(&avctx->hw_frames_ctx);
1299 int ff_get_format(AVCodecContext *avctx, const enum AVPixelFormat *fmt)
1301 const AVPixFmtDescriptor *desc;
1302 enum AVPixelFormat *choices;
1303 enum AVPixelFormat ret, user_choice;
1304 const AVCodecHWConfigInternal *hw_config;
1305 const AVCodecHWConfig *config;
1308 // Find end of list.
1309 for (n = 0; fmt[n] != AV_PIX_FMT_NONE; n++);
1310 // Must contain at least one entry.
1312 // If a software format is available, it must be the last entry.
1313 desc = av_pix_fmt_desc_get(fmt[n - 1]);
1314 if (desc->flags & AV_PIX_FMT_FLAG_HWACCEL) {
1315 // No software format is available.
1317 avctx->sw_pix_fmt = fmt[n - 1];
1320 choices = av_malloc_array(n + 1, sizeof(*choices));
1322 return AV_PIX_FMT_NONE;
1324 memcpy(choices, fmt, (n + 1) * sizeof(*choices));
1327 // Remove the previous hwaccel, if there was one.
1328 hwaccel_uninit(avctx);
1330 user_choice = avctx->get_format(avctx, choices);
1331 if (user_choice == AV_PIX_FMT_NONE) {
1332 // Explicitly chose nothing, give up.
1333 ret = AV_PIX_FMT_NONE;
1337 desc = av_pix_fmt_desc_get(user_choice);
1339 av_log(avctx, AV_LOG_ERROR, "Invalid format returned by "
1340 "get_format() callback.\n");
1341 ret = AV_PIX_FMT_NONE;
1344 av_log(avctx, AV_LOG_DEBUG, "Format %s chosen by get_format().\n",
1347 for (i = 0; i < n; i++) {
1348 if (choices[i] == user_choice)
1352 av_log(avctx, AV_LOG_ERROR, "Invalid return from get_format(): "
1353 "%s not in possible list.\n", desc->name);
1357 if (avctx->codec->hw_configs) {
1359 hw_config = avctx->codec->hw_configs[i];
1362 if (hw_config->public.pix_fmt == user_choice)
1370 // No config available, so no extra setup required.
1374 config = &hw_config->public;
1376 if (config->methods &
1377 AV_CODEC_HW_CONFIG_METHOD_HW_FRAMES_CTX &&
1378 avctx->hw_frames_ctx) {
1379 const AVHWFramesContext *frames_ctx =
1380 (AVHWFramesContext*)avctx->hw_frames_ctx->data;
1381 if (frames_ctx->format != user_choice) {
1382 av_log(avctx, AV_LOG_ERROR, "Invalid setup for format %s: "
1383 "does not match the format of the provided frames "
1384 "context.\n", desc->name);
1387 } else if (config->methods &
1388 AV_CODEC_HW_CONFIG_METHOD_HW_DEVICE_CTX &&
1389 avctx->hw_device_ctx) {
1390 const AVHWDeviceContext *device_ctx =
1391 (AVHWDeviceContext*)avctx->hw_device_ctx->data;
1392 if (device_ctx->type != config->device_type) {
1393 av_log(avctx, AV_LOG_ERROR, "Invalid setup for format %s: "
1394 "does not match the type of the provided device "
1395 "context.\n", desc->name);
1398 } else if (config->methods &
1399 AV_CODEC_HW_CONFIG_METHOD_INTERNAL) {
1400 // Internal-only setup, no additional configuration.
1401 } else if (config->methods &
1402 AV_CODEC_HW_CONFIG_METHOD_AD_HOC) {
1403 // Some ad-hoc configuration we can't see and can't check.
1405 av_log(avctx, AV_LOG_ERROR, "Invalid setup for format %s: "
1406 "missing configuration.\n", desc->name);
1409 if (hw_config->hwaccel) {
1410 av_log(avctx, AV_LOG_DEBUG, "Format %s requires hwaccel "
1411 "initialisation.\n", desc->name);
1412 err = hwaccel_init(avctx, hw_config);
1420 av_log(avctx, AV_LOG_DEBUG, "Format %s not usable, retrying "
1421 "get_format() without it.\n", desc->name);
1422 for (i = 0; i < n; i++) {
1423 if (choices[i] == user_choice)
1426 for (; i + 1 < n; i++)
1427 choices[i] = choices[i + 1];
1435 static int update_frame_pool(AVCodecContext *avctx, AVFrame *frame)
1437 FramePool *pool = avctx->internal->pool;
1440 switch (avctx->codec_type) {
1441 case AVMEDIA_TYPE_VIDEO: {
1444 int size[4] = { 0 };
1445 int w = frame->width;
1446 int h = frame->height;
1447 int tmpsize, unaligned;
1449 if (pool->format == frame->format &&
1450 pool->width == frame->width && pool->height == frame->height)
1453 avcodec_align_dimensions2(avctx, &w, &h, pool->stride_align);
1456 // NOTE: do not align linesizes individually, this breaks e.g. assumptions
1457 // that linesize[0] == 2*linesize[1] in the MPEG-encoder for 4:2:2
1458 ret = av_image_fill_linesizes(linesize, avctx->pix_fmt, w);
1461 // increase alignment of w for next try (rhs gives the lowest bit set in w)
1465 for (i = 0; i < 4; i++)
1466 unaligned |= linesize[i] % pool->stride_align[i];
1467 } while (unaligned);
1469 tmpsize = av_image_fill_pointers(data, avctx->pix_fmt, h,
1474 for (i = 0; i < 3 && data[i + 1]; i++)
1475 size[i] = data[i + 1] - data[i];
1476 size[i] = tmpsize - (data[i] - data[0]);
1478 for (i = 0; i < 4; i++) {
1479 av_buffer_pool_uninit(&pool->pools[i]);
1480 pool->linesize[i] = linesize[i];
1482 pool->pools[i] = av_buffer_pool_init(size[i] + 16 + STRIDE_ALIGN - 1,
1483 CONFIG_MEMORY_POISONING ?
1486 if (!pool->pools[i]) {
1487 ret = AVERROR(ENOMEM);
1492 pool->format = frame->format;
1493 pool->width = frame->width;
1494 pool->height = frame->height;
1498 case AVMEDIA_TYPE_AUDIO: {
1499 int ch = frame->channels; //av_get_channel_layout_nb_channels(frame->channel_layout);
1500 int planar = av_sample_fmt_is_planar(frame->format);
1501 int planes = planar ? ch : 1;
1503 if (pool->format == frame->format && pool->planes == planes &&
1504 pool->channels == ch && frame->nb_samples == pool->samples)
1507 av_buffer_pool_uninit(&pool->pools[0]);
1508 ret = av_samples_get_buffer_size(&pool->linesize[0], ch,
1509 frame->nb_samples, frame->format, 0);
1513 pool->pools[0] = av_buffer_pool_init(pool->linesize[0], NULL);
1514 if (!pool->pools[0]) {
1515 ret = AVERROR(ENOMEM);
1519 pool->format = frame->format;
1520 pool->planes = planes;
1521 pool->channels = ch;
1522 pool->samples = frame->nb_samples;
1525 default: av_assert0(0);
1529 for (i = 0; i < 4; i++)
1530 av_buffer_pool_uninit(&pool->pools[i]);
1532 pool->planes = pool->channels = pool->samples = 0;
1533 pool->width = pool->height = 0;
1537 static int audio_get_buffer(AVCodecContext *avctx, AVFrame *frame)
1539 FramePool *pool = avctx->internal->pool;
1540 int planes = pool->planes;
1543 frame->linesize[0] = pool->linesize[0];
1545 if (planes > AV_NUM_DATA_POINTERS) {
1546 frame->extended_data = av_mallocz_array(planes, sizeof(*frame->extended_data));
1547 frame->nb_extended_buf = planes - AV_NUM_DATA_POINTERS;
1548 frame->extended_buf = av_mallocz_array(frame->nb_extended_buf,
1549 sizeof(*frame->extended_buf));
1550 if (!frame->extended_data || !frame->extended_buf) {
1551 av_freep(&frame->extended_data);
1552 av_freep(&frame->extended_buf);
1553 return AVERROR(ENOMEM);
1556 frame->extended_data = frame->data;
1557 av_assert0(frame->nb_extended_buf == 0);
1560 for (i = 0; i < FFMIN(planes, AV_NUM_DATA_POINTERS); i++) {
1561 frame->buf[i] = av_buffer_pool_get(pool->pools[0]);
1564 frame->extended_data[i] = frame->data[i] = frame->buf[i]->data;
1566 for (i = 0; i < frame->nb_extended_buf; i++) {
1567 frame->extended_buf[i] = av_buffer_pool_get(pool->pools[0]);
1568 if (!frame->extended_buf[i])
1570 frame->extended_data[i + AV_NUM_DATA_POINTERS] = frame->extended_buf[i]->data;
1573 if (avctx->debug & FF_DEBUG_BUFFERS)
1574 av_log(avctx, AV_LOG_DEBUG, "default_get_buffer called on frame %p", frame);
1578 av_frame_unref(frame);
1579 return AVERROR(ENOMEM);
1582 static int video_get_buffer(AVCodecContext *s, AVFrame *pic)
1584 FramePool *pool = s->internal->pool;
1585 const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(pic->format);
1588 if (pic->data[0] || pic->data[1] || pic->data[2] || pic->data[3]) {
1589 av_log(s, AV_LOG_ERROR, "pic->data[*]!=NULL in avcodec_default_get_buffer\n");
1594 av_log(s, AV_LOG_ERROR,
1595 "Unable to get pixel format descriptor for format %s\n",
1596 av_get_pix_fmt_name(pic->format));
1597 return AVERROR(EINVAL);
1600 memset(pic->data, 0, sizeof(pic->data));
1601 pic->extended_data = pic->data;
1603 for (i = 0; i < 4 && pool->pools[i]; i++) {
1604 pic->linesize[i] = pool->linesize[i];
1606 pic->buf[i] = av_buffer_pool_get(pool->pools[i]);
1610 pic->data[i] = pic->buf[i]->data;
1612 for (; i < AV_NUM_DATA_POINTERS; i++) {
1613 pic->data[i] = NULL;
1614 pic->linesize[i] = 0;
1616 if (desc->flags & AV_PIX_FMT_FLAG_PAL ||
1617 ((desc->flags & FF_PSEUDOPAL) && pic->data[1]))
1618 avpriv_set_systematic_pal2((uint32_t *)pic->data[1], pic->format);
1620 if (s->debug & FF_DEBUG_BUFFERS)
1621 av_log(s, AV_LOG_DEBUG, "default_get_buffer called on pic %p\n", pic);
1625 av_frame_unref(pic);
1626 return AVERROR(ENOMEM);
1629 int avcodec_default_get_buffer2(AVCodecContext *avctx, AVFrame *frame, int flags)
1633 if (avctx->hw_frames_ctx) {
1634 ret = av_hwframe_get_buffer(avctx->hw_frames_ctx, frame, 0);
1635 frame->width = avctx->coded_width;
1636 frame->height = avctx->coded_height;
1640 if ((ret = update_frame_pool(avctx, frame)) < 0)
1643 switch (avctx->codec_type) {
1644 case AVMEDIA_TYPE_VIDEO:
1645 return video_get_buffer(avctx, frame);
1646 case AVMEDIA_TYPE_AUDIO:
1647 return audio_get_buffer(avctx, frame);
1653 static int add_metadata_from_side_data(const AVPacket *avpkt, AVFrame *frame)
1656 const uint8_t *side_metadata;
1658 AVDictionary **frame_md = &frame->metadata;
1660 side_metadata = av_packet_get_side_data(avpkt,
1661 AV_PKT_DATA_STRINGS_METADATA, &size);
1662 return av_packet_unpack_dictionary(side_metadata, size, frame_md);
1665 int ff_decode_frame_props(AVCodecContext *avctx, AVFrame *frame)
1667 const AVPacket *pkt = avctx->internal->last_pkt_props;
1669 static const struct {
1670 enum AVPacketSideDataType packet;
1671 enum AVFrameSideDataType frame;
1673 { AV_PKT_DATA_REPLAYGAIN , AV_FRAME_DATA_REPLAYGAIN },
1674 { AV_PKT_DATA_DISPLAYMATRIX, AV_FRAME_DATA_DISPLAYMATRIX },
1675 { AV_PKT_DATA_SPHERICAL, AV_FRAME_DATA_SPHERICAL },
1676 { AV_PKT_DATA_STEREO3D, AV_FRAME_DATA_STEREO3D },
1677 { AV_PKT_DATA_AUDIO_SERVICE_TYPE, AV_FRAME_DATA_AUDIO_SERVICE_TYPE },
1678 { AV_PKT_DATA_MASTERING_DISPLAY_METADATA, AV_FRAME_DATA_MASTERING_DISPLAY_METADATA },
1679 { AV_PKT_DATA_CONTENT_LIGHT_LEVEL, AV_FRAME_DATA_CONTENT_LIGHT_LEVEL },
1680 { AV_PKT_DATA_A53_CC, AV_FRAME_DATA_A53_CC },
1684 frame->pts = pkt->pts;
1686 FF_DISABLE_DEPRECATION_WARNINGS
1687 frame->pkt_pts = pkt->pts;
1688 FF_ENABLE_DEPRECATION_WARNINGS
1690 frame->pkt_pos = pkt->pos;
1691 frame->pkt_duration = pkt->duration;
1692 frame->pkt_size = pkt->size;
1694 for (i = 0; i < FF_ARRAY_ELEMS(sd); i++) {
1696 uint8_t *packet_sd = av_packet_get_side_data(pkt, sd[i].packet, &size);
1698 AVFrameSideData *frame_sd = av_frame_new_side_data(frame,
1702 return AVERROR(ENOMEM);
1704 memcpy(frame_sd->data, packet_sd, size);
1707 add_metadata_from_side_data(pkt, frame);
1709 if (pkt->flags & AV_PKT_FLAG_DISCARD) {
1710 frame->flags |= AV_FRAME_FLAG_DISCARD;
1712 frame->flags = (frame->flags & ~AV_FRAME_FLAG_DISCARD);
1715 frame->reordered_opaque = avctx->reordered_opaque;
1717 if (frame->color_primaries == AVCOL_PRI_UNSPECIFIED)
1718 frame->color_primaries = avctx->color_primaries;
1719 if (frame->color_trc == AVCOL_TRC_UNSPECIFIED)
1720 frame->color_trc = avctx->color_trc;
1721 if (frame->colorspace == AVCOL_SPC_UNSPECIFIED)
1722 frame->colorspace = avctx->colorspace;
1723 if (frame->color_range == AVCOL_RANGE_UNSPECIFIED)
1724 frame->color_range = avctx->color_range;
1725 if (frame->chroma_location == AVCHROMA_LOC_UNSPECIFIED)
1726 frame->chroma_location = avctx->chroma_sample_location;
1728 switch (avctx->codec->type) {
1729 case AVMEDIA_TYPE_VIDEO:
1730 frame->format = avctx->pix_fmt;
1731 if (!frame->sample_aspect_ratio.num)
1732 frame->sample_aspect_ratio = avctx->sample_aspect_ratio;
1734 if (frame->width && frame->height &&
1735 av_image_check_sar(frame->width, frame->height,
1736 frame->sample_aspect_ratio) < 0) {
1737 av_log(avctx, AV_LOG_WARNING, "ignoring invalid SAR: %u/%u\n",
1738 frame->sample_aspect_ratio.num,
1739 frame->sample_aspect_ratio.den);
1740 frame->sample_aspect_ratio = (AVRational){ 0, 1 };
1744 case AVMEDIA_TYPE_AUDIO:
1745 if (!frame->sample_rate)
1746 frame->sample_rate = avctx->sample_rate;
1747 if (frame->format < 0)
1748 frame->format = avctx->sample_fmt;
1749 if (!frame->channel_layout) {
1750 if (avctx->channel_layout) {
1751 if (av_get_channel_layout_nb_channels(avctx->channel_layout) !=
1753 av_log(avctx, AV_LOG_ERROR, "Inconsistent channel "
1754 "configuration.\n");
1755 return AVERROR(EINVAL);
1758 frame->channel_layout = avctx->channel_layout;
1760 if (avctx->channels > FF_SANE_NB_CHANNELS) {
1761 av_log(avctx, AV_LOG_ERROR, "Too many channels: %d.\n",
1763 return AVERROR(ENOSYS);
1767 frame->channels = avctx->channels;
1773 static void validate_avframe_allocation(AVCodecContext *avctx, AVFrame *frame)
1775 if (avctx->codec_type == AVMEDIA_TYPE_VIDEO) {
1777 int num_planes = av_pix_fmt_count_planes(frame->format);
1778 const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(frame->format);
1779 int flags = desc ? desc->flags : 0;
1780 if (num_planes == 1 && (flags & AV_PIX_FMT_FLAG_PAL))
1782 if ((flags & FF_PSEUDOPAL) && frame->data[1])
1784 for (i = 0; i < num_planes; i++) {
1785 av_assert0(frame->data[i]);
1787 // For formats without data like hwaccel allow unused pointers to be non-NULL.
1788 for (i = num_planes; num_planes > 0 && i < FF_ARRAY_ELEMS(frame->data); i++) {
1790 av_log(avctx, AV_LOG_ERROR, "Buffer returned by get_buffer2() did not zero unused plane pointers\n");
1791 frame->data[i] = NULL;
1796 static void decode_data_free(void *opaque, uint8_t *data)
1798 FrameDecodeData *fdd = (FrameDecodeData*)data;
1800 if (fdd->post_process_opaque_free)
1801 fdd->post_process_opaque_free(fdd->post_process_opaque);
1803 if (fdd->hwaccel_priv_free)
1804 fdd->hwaccel_priv_free(fdd->hwaccel_priv);
1809 int ff_attach_decode_data(AVFrame *frame)
1811 AVBufferRef *fdd_buf;
1812 FrameDecodeData *fdd;
1814 av_assert1(!frame->private_ref);
1815 av_buffer_unref(&frame->private_ref);
1817 fdd = av_mallocz(sizeof(*fdd));
1819 return AVERROR(ENOMEM);
1821 fdd_buf = av_buffer_create((uint8_t*)fdd, sizeof(*fdd), decode_data_free,
1822 NULL, AV_BUFFER_FLAG_READONLY);
1825 return AVERROR(ENOMEM);
1828 frame->private_ref = fdd_buf;
1833 static int get_buffer_internal(AVCodecContext *avctx, AVFrame *frame, int flags)
1835 const AVHWAccel *hwaccel = avctx->hwaccel;
1836 int override_dimensions = 1;
1839 if (avctx->codec_type == AVMEDIA_TYPE_VIDEO) {
1840 if ((ret = av_image_check_size2(avctx->width, avctx->height, avctx->max_pixels, AV_PIX_FMT_NONE, 0, avctx)) < 0 || avctx->pix_fmt<0) {
1841 av_log(avctx, AV_LOG_ERROR, "video_get_buffer: image parameters invalid\n");
1842 return AVERROR(EINVAL);
1845 if (frame->width <= 0 || frame->height <= 0) {
1846 frame->width = FFMAX(avctx->width, AV_CEIL_RSHIFT(avctx->coded_width, avctx->lowres));
1847 frame->height = FFMAX(avctx->height, AV_CEIL_RSHIFT(avctx->coded_height, avctx->lowres));
1848 override_dimensions = 0;
1851 if (frame->data[0] || frame->data[1] || frame->data[2] || frame->data[3]) {
1852 av_log(avctx, AV_LOG_ERROR, "pic->data[*]!=NULL in get_buffer_internal\n");
1853 return AVERROR(EINVAL);
1856 ret = ff_decode_frame_props(avctx, frame);
1861 if (hwaccel->alloc_frame) {
1862 ret = hwaccel->alloc_frame(avctx, frame);
1866 avctx->sw_pix_fmt = avctx->pix_fmt;
1868 ret = avctx->get_buffer2(avctx, frame, flags);
1872 validate_avframe_allocation(avctx, frame);
1874 ret = ff_attach_decode_data(frame);
1879 if (avctx->codec_type == AVMEDIA_TYPE_VIDEO && !override_dimensions &&
1880 !(avctx->codec->caps_internal & FF_CODEC_CAP_EXPORTS_CROPPING)) {
1881 frame->width = avctx->width;
1882 frame->height = avctx->height;
1886 av_frame_unref(frame);
1891 int ff_get_buffer(AVCodecContext *avctx, AVFrame *frame, int flags)
1893 int ret = get_buffer_internal(avctx, frame, flags);
1895 av_log(avctx, AV_LOG_ERROR, "get_buffer() failed\n");
1896 frame->width = frame->height = 0;
1901 static int reget_buffer_internal(AVCodecContext *avctx, AVFrame *frame)
1906 av_assert0(avctx->codec_type == AVMEDIA_TYPE_VIDEO);
1908 if (frame->data[0] && (frame->width != avctx->width || frame->height != avctx->height || frame->format != avctx->pix_fmt)) {
1909 av_log(avctx, AV_LOG_WARNING, "Picture changed from size:%dx%d fmt:%s to size:%dx%d fmt:%s in reget buffer()\n",
1910 frame->width, frame->height, av_get_pix_fmt_name(frame->format), avctx->width, avctx->height, av_get_pix_fmt_name(avctx->pix_fmt));
1911 av_frame_unref(frame);
1914 if (!frame->data[0])
1915 return ff_get_buffer(avctx, frame, AV_GET_BUFFER_FLAG_REF);
1917 if (av_frame_is_writable(frame))
1918 return ff_decode_frame_props(avctx, frame);
1920 tmp = av_frame_alloc();
1922 return AVERROR(ENOMEM);
1924 av_frame_move_ref(tmp, frame);
1926 ret = ff_get_buffer(avctx, frame, AV_GET_BUFFER_FLAG_REF);
1928 av_frame_free(&tmp);
1932 av_frame_copy(frame, tmp);
1933 av_frame_free(&tmp);
1938 int ff_reget_buffer(AVCodecContext *avctx, AVFrame *frame)
1940 int ret = reget_buffer_internal(avctx, frame);
1942 av_log(avctx, AV_LOG_ERROR, "reget_buffer() failed\n");
1946 void avcodec_flush_buffers(AVCodecContext *avctx)
1948 avctx->internal->draining = 0;
1949 avctx->internal->draining_done = 0;
1950 avctx->internal->nb_draining_errors = 0;
1951 av_frame_unref(avctx->internal->buffer_frame);
1952 av_frame_unref(avctx->internal->compat_decode_frame);
1953 av_packet_unref(avctx->internal->buffer_pkt);
1954 avctx->internal->buffer_pkt_valid = 0;
1956 av_packet_unref(avctx->internal->ds.in_pkt);
1958 if (HAVE_THREADS && avctx->active_thread_type & FF_THREAD_FRAME)
1959 ff_thread_flush(avctx);
1960 else if (avctx->codec->flush)
1961 avctx->codec->flush(avctx);
1963 avctx->pts_correction_last_pts =
1964 avctx->pts_correction_last_dts = INT64_MIN;
1966 ff_decode_bsfs_uninit(avctx);
1968 if (!avctx->refcounted_frames)
1969 av_frame_unref(avctx->internal->to_free);
1972 void ff_decode_bsfs_uninit(AVCodecContext *avctx)
1974 DecodeFilterContext *s = &avctx->internal->filter;
1977 for (i = 0; i < s->nb_bsfs; i++)
1978 av_bsf_free(&s->bsfs[i]);