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"
40 #include "bytestream.h"
45 static int apply_param_change(AVCodecContext *avctx, const AVPacket *avpkt)
52 data = av_packet_get_side_data(avpkt, AV_PKT_DATA_PARAM_CHANGE, &size);
56 if (!(avctx->codec->capabilities & AV_CODEC_CAP_PARAM_CHANGE)) {
57 av_log(avctx, AV_LOG_ERROR, "This decoder does not support parameter "
58 "changes, but PARAM_CHANGE side data was sent to it.\n");
59 ret = AVERROR(EINVAL);
66 flags = bytestream_get_le32(&data);
69 if (flags & AV_SIDE_DATA_PARAM_CHANGE_CHANNEL_COUNT) {
72 val = bytestream_get_le32(&data);
73 if (val <= 0 || val > INT_MAX) {
74 av_log(avctx, AV_LOG_ERROR, "Invalid channel count");
75 ret = AVERROR_INVALIDDATA;
78 avctx->channels = val;
81 if (flags & AV_SIDE_DATA_PARAM_CHANGE_CHANNEL_LAYOUT) {
84 avctx->channel_layout = bytestream_get_le64(&data);
87 if (flags & AV_SIDE_DATA_PARAM_CHANGE_SAMPLE_RATE) {
90 val = bytestream_get_le32(&data);
91 if (val <= 0 || val > INT_MAX) {
92 av_log(avctx, AV_LOG_ERROR, "Invalid sample rate");
93 ret = AVERROR_INVALIDDATA;
96 avctx->sample_rate = val;
99 if (flags & AV_SIDE_DATA_PARAM_CHANGE_DIMENSIONS) {
102 avctx->width = bytestream_get_le32(&data);
103 avctx->height = bytestream_get_le32(&data);
105 ret = ff_set_dimensions(avctx, avctx->width, avctx->height);
112 av_log(avctx, AV_LOG_ERROR, "PARAM_CHANGE side data too small.\n");
113 ret = AVERROR_INVALIDDATA;
116 av_log(avctx, AV_LOG_ERROR, "Error applying parameter changes.\n");
117 if (avctx->err_recognition & AV_EF_EXPLODE)
123 static int extract_packet_props(AVCodecInternal *avci, const AVPacket *pkt)
127 av_packet_unref(avci->last_pkt_props);
129 ret = av_packet_copy_props(avci->last_pkt_props, pkt);
131 avci->last_pkt_props->size = pkt->size; // HACK: Needed for ff_init_buffer_info().
136 static int unrefcount_frame(AVCodecInternal *avci, AVFrame *frame)
140 /* move the original frame to our backup */
141 av_frame_unref(avci->to_free);
142 av_frame_move_ref(avci->to_free, frame);
144 /* now copy everything except the AVBufferRefs back
145 * note that we make a COPY of the side data, so calling av_frame_free() on
146 * the caller's frame will work properly */
147 ret = av_frame_copy_props(frame, avci->to_free);
151 memcpy(frame->data, avci->to_free->data, sizeof(frame->data));
152 memcpy(frame->linesize, avci->to_free->linesize, sizeof(frame->linesize));
153 if (avci->to_free->extended_data != avci->to_free->data) {
154 int planes = avci->to_free->channels;
155 int size = planes * sizeof(*frame->extended_data);
158 av_frame_unref(frame);
162 frame->extended_data = av_malloc(size);
163 if (!frame->extended_data) {
164 av_frame_unref(frame);
165 return AVERROR(ENOMEM);
167 memcpy(frame->extended_data, avci->to_free->extended_data,
170 frame->extended_data = frame->data;
172 frame->format = avci->to_free->format;
173 frame->width = avci->to_free->width;
174 frame->height = avci->to_free->height;
175 frame->channel_layout = avci->to_free->channel_layout;
176 frame->nb_samples = avci->to_free->nb_samples;
177 frame->channels = avci->to_free->channels;
182 static int bsfs_init(AVCodecContext *avctx)
184 AVCodecInternal *avci = avctx->internal;
185 DecodeFilterContext *s = &avci->filter;
186 const char *bsfs_str;
192 bsfs_str = avctx->codec->bsfs ? avctx->codec->bsfs : "null";
193 while (bsfs_str && *bsfs_str) {
195 const AVBitStreamFilter *filter;
198 bsf = av_get_token(&bsfs_str, ",");
200 ret = AVERROR(ENOMEM);
204 filter = av_bsf_get_by_name(bsf);
206 av_log(avctx, AV_LOG_ERROR, "A non-existing bitstream filter %s "
207 "requested by a decoder. This is a bug, please report it.\n",
215 tmp = av_realloc_array(s->bsfs, s->nb_bsfs + 1, sizeof(*s->bsfs));
217 ret = AVERROR(ENOMEM);
223 ret = av_bsf_alloc(filter, &s->bsfs[s->nb_bsfs - 1]);
227 if (s->nb_bsfs == 1) {
228 /* We do not currently have an API for passing the input timebase into decoders,
229 * but no filters used here should actually need it.
230 * So we make up some plausible-looking number (the MPEG 90kHz timebase) */
231 s->bsfs[s->nb_bsfs - 1]->time_base_in = (AVRational){ 1, 90000 };
232 ret = avcodec_parameters_from_context(s->bsfs[s->nb_bsfs - 1]->par_in,
235 s->bsfs[s->nb_bsfs - 1]->time_base_in = s->bsfs[s->nb_bsfs - 2]->time_base_out;
236 ret = avcodec_parameters_copy(s->bsfs[s->nb_bsfs - 1]->par_in,
237 s->bsfs[s->nb_bsfs - 2]->par_out);
242 ret = av_bsf_init(s->bsfs[s->nb_bsfs - 1]);
249 ff_decode_bsfs_uninit(avctx);
253 /* try to get one output packet from the filter chain */
254 static int bsfs_poll(AVCodecContext *avctx, AVPacket *pkt)
256 DecodeFilterContext *s = &avctx->internal->filter;
259 /* start with the last filter in the chain */
260 idx = s->nb_bsfs - 1;
262 /* request a packet from the currently selected filter */
263 ret = av_bsf_receive_packet(s->bsfs[idx], pkt);
264 if (ret == AVERROR(EAGAIN)) {
265 /* no packets available, try the next filter up the chain */
269 } else if (ret < 0 && ret != AVERROR_EOF) {
273 /* got a packet or EOF -- pass it to the caller or to the next filter
275 if (idx == s->nb_bsfs - 1) {
279 ret = av_bsf_send_packet(s->bsfs[idx], ret < 0 ? NULL : pkt);
281 av_log(avctx, AV_LOG_ERROR,
282 "Error pre-processing a packet before decoding\n");
283 av_packet_unref(pkt);
289 return AVERROR(EAGAIN);
292 int ff_decode_get_packet(AVCodecContext *avctx, AVPacket *pkt)
294 AVCodecInternal *avci = avctx->internal;
300 ret = bsfs_poll(avctx, pkt);
301 if (ret == AVERROR_EOF)
306 ret = extract_packet_props(avctx->internal, pkt);
310 ret = apply_param_change(avctx, pkt);
314 if (avctx->codec->receive_frame)
315 avci->compat_decode_consumed += pkt->size;
319 av_packet_unref(pkt);
324 * Attempt to guess proper monotonic timestamps for decoded video frames
325 * which might have incorrect times. Input timestamps may wrap around, in
326 * which case the output will as well.
328 * @param pts the pts field of the decoded AVPacket, as passed through
330 * @param dts the dts field of the decoded AVPacket
331 * @return one of the input values, may be AV_NOPTS_VALUE
333 static int64_t guess_correct_pts(AVCodecContext *ctx,
334 int64_t reordered_pts, int64_t dts)
336 int64_t pts = AV_NOPTS_VALUE;
338 if (dts != AV_NOPTS_VALUE) {
339 ctx->pts_correction_num_faulty_dts += dts <= ctx->pts_correction_last_dts;
340 ctx->pts_correction_last_dts = dts;
341 } else if (reordered_pts != AV_NOPTS_VALUE)
342 ctx->pts_correction_last_dts = reordered_pts;
344 if (reordered_pts != AV_NOPTS_VALUE) {
345 ctx->pts_correction_num_faulty_pts += reordered_pts <= ctx->pts_correction_last_pts;
346 ctx->pts_correction_last_pts = reordered_pts;
347 } else if(dts != AV_NOPTS_VALUE)
348 ctx->pts_correction_last_pts = dts;
350 if ((ctx->pts_correction_num_faulty_pts<=ctx->pts_correction_num_faulty_dts || dts == AV_NOPTS_VALUE)
351 && reordered_pts != AV_NOPTS_VALUE)
360 * The core of the receive_frame_wrapper for the decoders implementing
361 * the simple API. Certain decoders might consume partial packets without
362 * returning any output, so this function needs to be called in a loop until it
365 static int decode_simple_internal(AVCodecContext *avctx, AVFrame *frame)
367 AVCodecInternal *avci = avctx->internal;
368 DecodeSimpleContext *ds = &avci->ds;
369 AVPacket *pkt = ds->in_pkt;
370 // copy to ensure we do not change pkt
372 int got_frame, actual_got_frame, did_split;
375 if (!pkt->data && !avci->draining) {
376 av_packet_unref(pkt);
377 ret = ff_decode_get_packet(avctx, pkt);
378 if (ret < 0 && ret != AVERROR_EOF)
382 // Some codecs (at least wma lossless) will crash when feeding drain packets
383 // after EOF was signaled.
384 if (avci->draining_done)
388 !(avctx->codec->capabilities & AV_CODEC_CAP_DELAY ||
389 avctx->active_thread_type & FF_THREAD_FRAME))
394 FF_DISABLE_DEPRECATION_WARNINGS
395 did_split = avci->compat_decode_partial_size ?
396 ff_packet_split_and_drop_side_data(&tmp) :
397 av_packet_split_side_data(&tmp);
400 ret = extract_packet_props(avctx->internal, &tmp);
404 ret = apply_param_change(avctx, &tmp);
408 FF_ENABLE_DEPRECATION_WARNINGS
413 if (HAVE_THREADS && avctx->active_thread_type & FF_THREAD_FRAME) {
414 ret = ff_thread_decode_frame(avctx, frame, &got_frame, &tmp);
416 ret = avctx->codec->decode(avctx, frame, &got_frame, &tmp);
418 if (!(avctx->codec->caps_internal & FF_CODEC_CAP_SETS_PKT_DTS))
419 frame->pkt_dts = pkt->dts;
420 if (avctx->codec->type == AVMEDIA_TYPE_VIDEO) {
421 if(!avctx->has_b_frames)
422 frame->pkt_pos = pkt->pos;
423 //FIXME these should be under if(!avctx->has_b_frames)
424 /* get_buffer is supposed to set frame parameters */
425 if (!(avctx->codec->capabilities & AV_CODEC_CAP_DR1)) {
426 if (!frame->sample_aspect_ratio.num) frame->sample_aspect_ratio = avctx->sample_aspect_ratio;
427 if (!frame->width) frame->width = avctx->width;
428 if (!frame->height) frame->height = avctx->height;
429 if (frame->format == AV_PIX_FMT_NONE) frame->format = avctx->pix_fmt;
434 actual_got_frame = got_frame;
436 if (avctx->codec->type == AVMEDIA_TYPE_VIDEO) {
437 if (frame->flags & AV_FRAME_FLAG_DISCARD)
440 frame->best_effort_timestamp = guess_correct_pts(avctx,
443 } else if (avctx->codec->type == AVMEDIA_TYPE_AUDIO) {
446 uint32_t discard_padding = 0;
447 uint8_t skip_reason = 0;
448 uint8_t discard_reason = 0;
450 if (ret >= 0 && got_frame) {
451 frame->best_effort_timestamp = guess_correct_pts(avctx,
454 if (frame->format == AV_SAMPLE_FMT_NONE)
455 frame->format = avctx->sample_fmt;
456 if (!frame->channel_layout)
457 frame->channel_layout = avctx->channel_layout;
458 if (!frame->channels)
459 frame->channels = avctx->channels;
460 if (!frame->sample_rate)
461 frame->sample_rate = avctx->sample_rate;
464 side= av_packet_get_side_data(pkt, AV_PKT_DATA_SKIP_SAMPLES, &side_size);
465 if(side && side_size>=10) {
466 avctx->internal->skip_samples = AV_RL32(side) * avctx->internal->skip_samples_multiplier;
467 discard_padding = AV_RL32(side + 4);
468 av_log(avctx, AV_LOG_DEBUG, "skip %d / discard %d samples due to side data\n",
469 avctx->internal->skip_samples, (int)discard_padding);
470 skip_reason = AV_RL8(side + 8);
471 discard_reason = AV_RL8(side + 9);
474 if ((frame->flags & AV_FRAME_FLAG_DISCARD) && got_frame &&
475 !(avctx->flags2 & AV_CODEC_FLAG2_SKIP_MANUAL)) {
476 avctx->internal->skip_samples = FFMAX(0, avctx->internal->skip_samples - frame->nb_samples);
480 if (avctx->internal->skip_samples > 0 && got_frame &&
481 !(avctx->flags2 & AV_CODEC_FLAG2_SKIP_MANUAL)) {
482 if(frame->nb_samples <= avctx->internal->skip_samples){
484 avctx->internal->skip_samples -= frame->nb_samples;
485 av_log(avctx, AV_LOG_DEBUG, "skip whole frame, skip left: %d\n",
486 avctx->internal->skip_samples);
488 av_samples_copy(frame->extended_data, frame->extended_data, 0, avctx->internal->skip_samples,
489 frame->nb_samples - avctx->internal->skip_samples, avctx->channels, frame->format);
490 if(avctx->pkt_timebase.num && avctx->sample_rate) {
491 int64_t diff_ts = av_rescale_q(avctx->internal->skip_samples,
492 (AVRational){1, avctx->sample_rate},
493 avctx->pkt_timebase);
494 if(frame->pts!=AV_NOPTS_VALUE)
495 frame->pts += diff_ts;
497 FF_DISABLE_DEPRECATION_WARNINGS
498 if(frame->pkt_pts!=AV_NOPTS_VALUE)
499 frame->pkt_pts += diff_ts;
500 FF_ENABLE_DEPRECATION_WARNINGS
502 if(frame->pkt_dts!=AV_NOPTS_VALUE)
503 frame->pkt_dts += diff_ts;
504 if (frame->pkt_duration >= diff_ts)
505 frame->pkt_duration -= diff_ts;
507 av_log(avctx, AV_LOG_WARNING, "Could not update timestamps for skipped samples.\n");
509 av_log(avctx, AV_LOG_DEBUG, "skip %d/%d samples\n",
510 avctx->internal->skip_samples, frame->nb_samples);
511 frame->nb_samples -= avctx->internal->skip_samples;
512 avctx->internal->skip_samples = 0;
516 if (discard_padding > 0 && discard_padding <= frame->nb_samples && got_frame &&
517 !(avctx->flags2 & AV_CODEC_FLAG2_SKIP_MANUAL)) {
518 if (discard_padding == frame->nb_samples) {
521 if(avctx->pkt_timebase.num && avctx->sample_rate) {
522 int64_t diff_ts = av_rescale_q(frame->nb_samples - discard_padding,
523 (AVRational){1, avctx->sample_rate},
524 avctx->pkt_timebase);
525 frame->pkt_duration = diff_ts;
527 av_log(avctx, AV_LOG_WARNING, "Could not update timestamps for discarded samples.\n");
529 av_log(avctx, AV_LOG_DEBUG, "discard %d/%d samples\n",
530 (int)discard_padding, frame->nb_samples);
531 frame->nb_samples -= discard_padding;
535 if ((avctx->flags2 & AV_CODEC_FLAG2_SKIP_MANUAL) && got_frame) {
536 AVFrameSideData *fside = av_frame_new_side_data(frame, AV_FRAME_DATA_SKIP_SAMPLES, 10);
538 AV_WL32(fside->data, avctx->internal->skip_samples);
539 AV_WL32(fside->data + 4, discard_padding);
540 AV_WL8(fside->data + 8, skip_reason);
541 AV_WL8(fside->data + 9, discard_reason);
542 avctx->internal->skip_samples = 0;
548 av_packet_free_side_data(&tmp);
554 if (avctx->codec->type == AVMEDIA_TYPE_AUDIO &&
555 !avci->showed_multi_packet_warning &&
556 ret >= 0 && ret != pkt->size && !(avctx->codec->capabilities & AV_CODEC_CAP_SUBFRAMES)) {
557 av_log(avctx, AV_LOG_WARNING, "Multiple frames in a packet.\n");
558 avci->showed_multi_packet_warning = 1;
562 av_frame_unref(frame);
564 if (ret >= 0 && avctx->codec->type == AVMEDIA_TYPE_VIDEO && !(avctx->flags & AV_CODEC_FLAG_TRUNCATED))
567 #if FF_API_AVCTX_TIMEBASE
568 if (avctx->framerate.num > 0 && avctx->framerate.den > 0)
569 avctx->time_base = av_inv_q(av_mul_q(avctx->framerate, (AVRational){avctx->ticks_per_frame, 1}));
572 /* do not stop draining when actual_got_frame != 0 or ret < 0 */
573 /* got_frame == 0 but actual_got_frame != 0 when frame is discarded */
574 if (avctx->internal->draining && !actual_got_frame) {
576 /* prevent infinite loop if a decoder wrongly always return error on draining */
577 /* reasonable nb_errors_max = maximum b frames + thread count */
578 int nb_errors_max = 20 + (HAVE_THREADS && avctx->active_thread_type & FF_THREAD_FRAME ?
579 avctx->thread_count : 1);
581 if (avci->nb_draining_errors++ >= nb_errors_max) {
582 av_log(avctx, AV_LOG_ERROR, "Too many errors when draining, this is a bug. "
583 "Stop draining and force EOF.\n");
584 avci->draining_done = 1;
588 avci->draining_done = 1;
592 avci->compat_decode_consumed += ret;
594 if (ret >= pkt->size || ret < 0) {
595 av_packet_unref(pkt);
599 pkt->data += consumed;
600 pkt->size -= consumed;
601 avci->last_pkt_props->size -= consumed; // See extract_packet_props() comment.
602 pkt->pts = AV_NOPTS_VALUE;
603 pkt->dts = AV_NOPTS_VALUE;
604 avci->last_pkt_props->pts = AV_NOPTS_VALUE;
605 avci->last_pkt_props->dts = AV_NOPTS_VALUE;
609 av_assert0(frame->buf[0]);
611 return ret < 0 ? ret : 0;
614 static int decode_simple_receive_frame(AVCodecContext *avctx, AVFrame *frame)
618 while (!frame->buf[0]) {
619 ret = decode_simple_internal(avctx, frame);
627 static int decode_receive_frame_internal(AVCodecContext *avctx, AVFrame *frame)
629 AVCodecInternal *avci = avctx->internal;
632 av_assert0(!frame->buf[0]);
634 if (avctx->codec->receive_frame)
635 ret = avctx->codec->receive_frame(avctx, frame);
637 ret = decode_simple_receive_frame(avctx, frame);
639 if (ret == AVERROR_EOF)
640 avci->draining_done = 1;
645 int attribute_align_arg avcodec_send_packet(AVCodecContext *avctx, const AVPacket *avpkt)
647 AVCodecInternal *avci = avctx->internal;
650 if (!avcodec_is_open(avctx) || !av_codec_is_decoder(avctx->codec))
651 return AVERROR(EINVAL);
653 if (avctx->internal->draining)
656 if (avpkt && !avpkt->size && avpkt->data)
657 return AVERROR(EINVAL);
659 ret = bsfs_init(avctx);
663 av_packet_unref(avci->buffer_pkt);
664 if (avpkt && (avpkt->data || avpkt->side_data_elems)) {
665 ret = av_packet_ref(avci->buffer_pkt, avpkt);
670 ret = av_bsf_send_packet(avci->filter.bsfs[0], avci->buffer_pkt);
672 av_packet_unref(avci->buffer_pkt);
676 if (!avci->buffer_frame->buf[0]) {
677 ret = decode_receive_frame_internal(avctx, avci->buffer_frame);
678 if (ret < 0 && ret != AVERROR(EAGAIN) && ret != AVERROR_EOF)
685 int attribute_align_arg avcodec_receive_frame(AVCodecContext *avctx, AVFrame *frame)
687 AVCodecInternal *avci = avctx->internal;
690 av_frame_unref(frame);
692 if (!avcodec_is_open(avctx) || !av_codec_is_decoder(avctx->codec))
693 return AVERROR(EINVAL);
695 ret = bsfs_init(avctx);
699 if (avci->buffer_frame->buf[0]) {
700 av_frame_move_ref(frame, avci->buffer_frame);
702 ret = decode_receive_frame_internal(avctx, frame);
707 avctx->frame_number++;
712 static int compat_decode(AVCodecContext *avctx, AVFrame *frame,
713 int *got_frame, const AVPacket *pkt)
715 AVCodecInternal *avci = avctx->internal;
718 av_assert0(avci->compat_decode_consumed == 0);
721 avci->compat_decode = 1;
723 if (avci->compat_decode_partial_size > 0 &&
724 avci->compat_decode_partial_size != pkt->size) {
725 av_log(avctx, AV_LOG_ERROR,
726 "Got unexpected packet size after a partial decode\n");
727 ret = AVERROR(EINVAL);
731 if (!avci->compat_decode_partial_size) {
732 ret = avcodec_send_packet(avctx, pkt);
733 if (ret == AVERROR_EOF)
735 else if (ret == AVERROR(EAGAIN)) {
736 /* we fully drain all the output in each decode call, so this should not
745 ret = avcodec_receive_frame(avctx, frame);
747 if (ret == AVERROR(EAGAIN) || ret == AVERROR_EOF)
752 if (frame != avci->compat_decode_frame) {
753 if (!avctx->refcounted_frames) {
754 ret = unrefcount_frame(avci, frame);
760 frame = avci->compat_decode_frame;
762 if (!avci->compat_decode_warned) {
763 av_log(avctx, AV_LOG_WARNING, "The deprecated avcodec_decode_* "
764 "API cannot return all the frames for this decoder. "
765 "Some frames will be dropped. Update your code to the "
766 "new decoding API to fix this.\n");
767 avci->compat_decode_warned = 1;
771 if (avci->draining || (!avctx->codec->bsfs && avci->compat_decode_consumed < pkt->size))
777 /* if there are any bsfs then assume full packet is always consumed */
778 if (avctx->codec->bsfs)
781 ret = FFMIN(avci->compat_decode_consumed, pkt->size);
783 avci->compat_decode_consumed = 0;
784 avci->compat_decode_partial_size = (ret >= 0) ? pkt->size - ret : 0;
789 int attribute_align_arg avcodec_decode_video2(AVCodecContext *avctx, AVFrame *picture,
790 int *got_picture_ptr,
791 const AVPacket *avpkt)
793 return compat_decode(avctx, picture, got_picture_ptr, avpkt);
796 int attribute_align_arg avcodec_decode_audio4(AVCodecContext *avctx,
799 const AVPacket *avpkt)
801 return compat_decode(avctx, frame, got_frame_ptr, avpkt);
804 static void get_subtitle_defaults(AVSubtitle *sub)
806 memset(sub, 0, sizeof(*sub));
807 sub->pts = AV_NOPTS_VALUE;
810 #define UTF8_MAX_BYTES 4 /* 5 and 6 bytes sequences should not be used */
811 static int recode_subtitle(AVCodecContext *avctx,
812 AVPacket *outpkt, const AVPacket *inpkt)
815 iconv_t cd = (iconv_t)-1;
822 if (avctx->sub_charenc_mode != FF_SUB_CHARENC_MODE_PRE_DECODER || inpkt->size == 0)
826 cd = iconv_open("UTF-8", avctx->sub_charenc);
827 av_assert0(cd != (iconv_t)-1);
832 if (inl >= INT_MAX / UTF8_MAX_BYTES - AV_INPUT_BUFFER_PADDING_SIZE) {
833 av_log(avctx, AV_LOG_ERROR, "Subtitles packet is too big for recoding\n");
834 ret = AVERROR(ENOMEM);
838 ret = av_new_packet(&tmp, inl * UTF8_MAX_BYTES);
841 outpkt->buf = tmp.buf;
842 outpkt->data = tmp.data;
843 outpkt->size = tmp.size;
847 if (iconv(cd, &inb, &inl, &outb, &outl) == (size_t)-1 ||
848 iconv(cd, NULL, NULL, &outb, &outl) == (size_t)-1 ||
849 outl >= outpkt->size || inl != 0) {
850 ret = FFMIN(AVERROR(errno), -1);
851 av_log(avctx, AV_LOG_ERROR, "Unable to recode subtitle event \"%s\" "
852 "from %s to UTF-8\n", inpkt->data, avctx->sub_charenc);
853 av_packet_unref(&tmp);
856 outpkt->size -= outl;
857 memset(outpkt->data + outpkt->size, 0, outl);
860 if (cd != (iconv_t)-1)
864 av_log(avctx, AV_LOG_ERROR, "requesting subtitles recoding without iconv");
865 return AVERROR(EINVAL);
869 static int utf8_check(const uint8_t *str)
872 uint32_t codepoint, min;
876 GET_UTF8(codepoint, *(byte++), return 0;);
877 min = byte - str == 1 ? 0 : byte - str == 2 ? 0x80 :
878 1 << (5 * (byte - str) - 4);
879 if (codepoint < min || codepoint >= 0x110000 ||
880 codepoint == 0xFFFE /* BOM */ ||
881 codepoint >= 0xD800 && codepoint <= 0xDFFF /* surrogates */)
888 #if FF_API_ASS_TIMING
889 static void insert_ts(AVBPrint *buf, int ts)
892 av_bprintf(buf, "9:59:59.99,");
896 h = ts/360000; ts -= 360000*h;
897 m = ts/ 6000; ts -= 6000*m;
898 s = ts/ 100; ts -= 100*s;
899 av_bprintf(buf, "%d:%02d:%02d.%02d,", h, m, s, ts);
903 static int convert_sub_to_old_ass_form(AVSubtitle *sub, const AVPacket *pkt, AVRational tb)
908 av_bprint_init(&buf, 0, AV_BPRINT_SIZE_UNLIMITED);
910 for (i = 0; i < sub->num_rects; i++) {
913 AVSubtitleRect *rect = sub->rects[i];
914 int ts_start, ts_duration = -1;
917 if (rect->type != SUBTITLE_ASS || !strncmp(rect->ass, "Dialogue: ", 10))
920 av_bprint_clear(&buf);
923 dialog = strchr(rect->ass, ',');
928 /* extract Layer or Marked */
929 layer = strtol(dialog, (char**)&dialog, 10);
934 /* rescale timing to ASS time base (ms) */
935 ts_start = av_rescale_q(pkt->pts, tb, av_make_q(1, 100));
936 if (pkt->duration != -1)
937 ts_duration = av_rescale_q(pkt->duration, tb, av_make_q(1, 100));
938 sub->end_display_time = FFMAX(sub->end_display_time, 10 * ts_duration);
940 /* construct ASS (standalone file form with timestamps) string */
941 av_bprintf(&buf, "Dialogue: %ld,", layer);
942 insert_ts(&buf, ts_start);
943 insert_ts(&buf, ts_duration == -1 ? -1 : ts_start + ts_duration);
944 av_bprintf(&buf, "%s\r\n", dialog);
946 final_dialog = av_strdup(buf.str);
947 if (!av_bprint_is_complete(&buf) || !final_dialog) {
948 av_freep(&final_dialog);
949 av_bprint_finalize(&buf, NULL);
950 return AVERROR(ENOMEM);
952 av_freep(&rect->ass);
953 rect->ass = final_dialog;
956 av_bprint_finalize(&buf, NULL);
961 int avcodec_decode_subtitle2(AVCodecContext *avctx, AVSubtitle *sub,
966 AVCodecInternal *avci = avctx->internal;
968 if (!avpkt->data && avpkt->size) {
969 av_log(avctx, AV_LOG_ERROR, "invalid packet: NULL data, size != 0\n");
970 return AVERROR(EINVAL);
973 return AVERROR(EINVAL);
974 if (avctx->codec->type != AVMEDIA_TYPE_SUBTITLE) {
975 av_log(avctx, AV_LOG_ERROR, "Invalid media type for subtitles\n");
976 return AVERROR(EINVAL);
980 get_subtitle_defaults(sub);
982 if ((avctx->codec->capabilities & AV_CODEC_CAP_DELAY) || avpkt->size) {
983 AVPacket pkt_recoded;
984 AVPacket tmp = *avpkt;
986 FF_DISABLE_DEPRECATION_WARNINGS
987 int did_split = avci->compat_decode_partial_size ?
988 ff_packet_split_and_drop_side_data(&tmp) :
989 av_packet_split_side_data(&tmp);
990 //apply_param_change(avctx, &tmp);
993 /* FFMIN() prevents overflow in case the packet wasn't allocated with
995 * If the side data is smaller than the buffer padding size, the
996 * remaining bytes should have already been filled with zeros by the
997 * original packet allocation anyway. */
998 memset(tmp.data + tmp.size, 0,
999 FFMIN(avpkt->size - tmp.size, AV_INPUT_BUFFER_PADDING_SIZE));
1001 FF_ENABLE_DEPRECATION_WARNINGS
1005 ret = recode_subtitle(avctx, &pkt_recoded, &tmp);
1009 ret = extract_packet_props(avctx->internal, &pkt_recoded);
1013 if (avctx->pkt_timebase.num && avpkt->pts != AV_NOPTS_VALUE)
1014 sub->pts = av_rescale_q(avpkt->pts,
1015 avctx->pkt_timebase, AV_TIME_BASE_Q);
1016 ret = avctx->codec->decode(avctx, sub, got_sub_ptr, &pkt_recoded);
1017 av_assert1((ret >= 0) >= !!*got_sub_ptr &&
1018 !!*got_sub_ptr >= !!sub->num_rects);
1020 #if FF_API_ASS_TIMING
1021 if (avctx->sub_text_format == FF_SUB_TEXT_FMT_ASS_WITH_TIMINGS
1022 && *got_sub_ptr && sub->num_rects) {
1023 const AVRational tb = avctx->pkt_timebase.num ? avctx->pkt_timebase
1025 int err = convert_sub_to_old_ass_form(sub, avpkt, tb);
1031 if (sub->num_rects && !sub->end_display_time && avpkt->duration &&
1032 avctx->pkt_timebase.num) {
1033 AVRational ms = { 1, 1000 };
1034 sub->end_display_time = av_rescale_q(avpkt->duration,
1035 avctx->pkt_timebase, ms);
1038 if (avctx->codec_descriptor->props & AV_CODEC_PROP_BITMAP_SUB)
1040 else if (avctx->codec_descriptor->props & AV_CODEC_PROP_TEXT_SUB)
1043 for (i = 0; i < sub->num_rects; i++) {
1044 if (sub->rects[i]->ass && !utf8_check(sub->rects[i]->ass)) {
1045 av_log(avctx, AV_LOG_ERROR,
1046 "Invalid UTF-8 in decoded subtitles text; "
1047 "maybe missing -sub_charenc option\n");
1048 avsubtitle_free(sub);
1049 ret = AVERROR_INVALIDDATA;
1054 if (tmp.data != pkt_recoded.data) { // did we recode?
1055 /* prevent from destroying side data from original packet */
1056 pkt_recoded.side_data = NULL;
1057 pkt_recoded.side_data_elems = 0;
1059 av_packet_unref(&pkt_recoded);
1065 av_packet_free_side_data(&tmp);
1072 avctx->frame_number++;
1078 static int is_hwaccel_pix_fmt(enum AVPixelFormat pix_fmt)
1080 const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(pix_fmt);
1081 return desc->flags & AV_PIX_FMT_FLAG_HWACCEL;
1084 enum AVPixelFormat avcodec_default_get_format(struct AVCodecContext *s, const enum AVPixelFormat *fmt)
1086 while (*fmt != AV_PIX_FMT_NONE && is_hwaccel_pix_fmt(*fmt))
1091 static AVHWAccel *find_hwaccel(enum AVCodecID codec_id,
1092 enum AVPixelFormat pix_fmt)
1094 AVHWAccel *hwaccel = NULL;
1096 while ((hwaccel = av_hwaccel_next(hwaccel)))
1097 if (hwaccel->id == codec_id
1098 && hwaccel->pix_fmt == pix_fmt)
1103 static int setup_hwaccel(AVCodecContext *avctx,
1104 const enum AVPixelFormat fmt,
1107 AVHWAccel *hwa = find_hwaccel(avctx->codec_id, fmt);
1111 av_log(avctx, AV_LOG_ERROR,
1112 "Could not find an AVHWAccel for the pixel format: %s",
1114 return AVERROR(ENOENT);
1117 if (hwa->capabilities & HWACCEL_CODEC_CAP_EXPERIMENTAL &&
1118 avctx->strict_std_compliance > FF_COMPLIANCE_EXPERIMENTAL) {
1119 av_log(avctx, AV_LOG_WARNING, "Ignoring experimental hwaccel: %s\n",
1121 return AVERROR_PATCHWELCOME;
1124 if (hwa->priv_data_size) {
1125 avctx->internal->hwaccel_priv_data = av_mallocz(hwa->priv_data_size);
1126 if (!avctx->internal->hwaccel_priv_data)
1127 return AVERROR(ENOMEM);
1131 ret = hwa->init(avctx);
1133 av_freep(&avctx->internal->hwaccel_priv_data);
1138 avctx->hwaccel = hwa;
1143 int ff_get_format(AVCodecContext *avctx, const enum AVPixelFormat *fmt)
1145 const AVPixFmtDescriptor *desc;
1146 enum AVPixelFormat *choices;
1147 enum AVPixelFormat ret;
1150 while (fmt[n] != AV_PIX_FMT_NONE)
1154 avctx->sw_pix_fmt = fmt[n - 1];
1155 av_assert2(!is_hwaccel_pix_fmt(avctx->sw_pix_fmt));
1157 choices = av_malloc_array(n + 1, sizeof(*choices));
1159 return AV_PIX_FMT_NONE;
1161 memcpy(choices, fmt, (n + 1) * sizeof(*choices));
1164 if (avctx->hwaccel && avctx->hwaccel->uninit)
1165 avctx->hwaccel->uninit(avctx);
1166 av_freep(&avctx->internal->hwaccel_priv_data);
1167 avctx->hwaccel = NULL;
1169 av_buffer_unref(&avctx->hw_frames_ctx);
1171 ret = avctx->get_format(avctx, choices);
1173 desc = av_pix_fmt_desc_get(ret);
1175 ret = AV_PIX_FMT_NONE;
1179 if (!(desc->flags & AV_PIX_FMT_FLAG_HWACCEL))
1181 #if FF_API_CAP_VDPAU
1182 if (avctx->codec->capabilities&AV_CODEC_CAP_HWACCEL_VDPAU)
1186 if (avctx->hw_frames_ctx) {
1187 AVHWFramesContext *hw_frames_ctx = (AVHWFramesContext*)avctx->hw_frames_ctx->data;
1188 if (hw_frames_ctx->format != ret) {
1189 av_log(avctx, AV_LOG_ERROR, "Format returned from get_buffer() "
1190 "does not match the format of provided AVHWFramesContext\n");
1191 ret = AV_PIX_FMT_NONE;
1196 if (!setup_hwaccel(avctx, ret, desc->name))
1199 /* Remove failed hwaccel from choices */
1200 for (n = 0; choices[n] != ret; n++)
1201 av_assert0(choices[n] != AV_PIX_FMT_NONE);
1204 choices[n] = choices[n + 1];
1205 while (choices[n++] != AV_PIX_FMT_NONE);
1212 static int update_frame_pool(AVCodecContext *avctx, AVFrame *frame)
1214 FramePool *pool = avctx->internal->pool;
1217 switch (avctx->codec_type) {
1218 case AVMEDIA_TYPE_VIDEO: {
1221 int size[4] = { 0 };
1222 int w = frame->width;
1223 int h = frame->height;
1224 int tmpsize, unaligned;
1226 if (pool->format == frame->format &&
1227 pool->width == frame->width && pool->height == frame->height)
1230 avcodec_align_dimensions2(avctx, &w, &h, pool->stride_align);
1233 // NOTE: do not align linesizes individually, this breaks e.g. assumptions
1234 // that linesize[0] == 2*linesize[1] in the MPEG-encoder for 4:2:2
1235 ret = av_image_fill_linesizes(linesize, avctx->pix_fmt, w);
1238 // increase alignment of w for next try (rhs gives the lowest bit set in w)
1242 for (i = 0; i < 4; i++)
1243 unaligned |= linesize[i] % pool->stride_align[i];
1244 } while (unaligned);
1246 tmpsize = av_image_fill_pointers(data, avctx->pix_fmt, h,
1251 for (i = 0; i < 3 && data[i + 1]; i++)
1252 size[i] = data[i + 1] - data[i];
1253 size[i] = tmpsize - (data[i] - data[0]);
1255 for (i = 0; i < 4; i++) {
1256 av_buffer_pool_uninit(&pool->pools[i]);
1257 pool->linesize[i] = linesize[i];
1259 pool->pools[i] = av_buffer_pool_init(size[i] + 16 + STRIDE_ALIGN - 1,
1260 CONFIG_MEMORY_POISONING ?
1263 if (!pool->pools[i]) {
1264 ret = AVERROR(ENOMEM);
1269 pool->format = frame->format;
1270 pool->width = frame->width;
1271 pool->height = frame->height;
1275 case AVMEDIA_TYPE_AUDIO: {
1276 int ch = frame->channels; //av_get_channel_layout_nb_channels(frame->channel_layout);
1277 int planar = av_sample_fmt_is_planar(frame->format);
1278 int planes = planar ? ch : 1;
1280 if (pool->format == frame->format && pool->planes == planes &&
1281 pool->channels == ch && frame->nb_samples == pool->samples)
1284 av_buffer_pool_uninit(&pool->pools[0]);
1285 ret = av_samples_get_buffer_size(&pool->linesize[0], ch,
1286 frame->nb_samples, frame->format, 0);
1290 pool->pools[0] = av_buffer_pool_init(pool->linesize[0], NULL);
1291 if (!pool->pools[0]) {
1292 ret = AVERROR(ENOMEM);
1296 pool->format = frame->format;
1297 pool->planes = planes;
1298 pool->channels = ch;
1299 pool->samples = frame->nb_samples;
1302 default: av_assert0(0);
1306 for (i = 0; i < 4; i++)
1307 av_buffer_pool_uninit(&pool->pools[i]);
1309 pool->planes = pool->channels = pool->samples = 0;
1310 pool->width = pool->height = 0;
1314 static int audio_get_buffer(AVCodecContext *avctx, AVFrame *frame)
1316 FramePool *pool = avctx->internal->pool;
1317 int planes = pool->planes;
1320 frame->linesize[0] = pool->linesize[0];
1322 if (planes > AV_NUM_DATA_POINTERS) {
1323 frame->extended_data = av_mallocz_array(planes, sizeof(*frame->extended_data));
1324 frame->nb_extended_buf = planes - AV_NUM_DATA_POINTERS;
1325 frame->extended_buf = av_mallocz_array(frame->nb_extended_buf,
1326 sizeof(*frame->extended_buf));
1327 if (!frame->extended_data || !frame->extended_buf) {
1328 av_freep(&frame->extended_data);
1329 av_freep(&frame->extended_buf);
1330 return AVERROR(ENOMEM);
1333 frame->extended_data = frame->data;
1334 av_assert0(frame->nb_extended_buf == 0);
1337 for (i = 0; i < FFMIN(planes, AV_NUM_DATA_POINTERS); i++) {
1338 frame->buf[i] = av_buffer_pool_get(pool->pools[0]);
1341 frame->extended_data[i] = frame->data[i] = frame->buf[i]->data;
1343 for (i = 0; i < frame->nb_extended_buf; i++) {
1344 frame->extended_buf[i] = av_buffer_pool_get(pool->pools[0]);
1345 if (!frame->extended_buf[i])
1347 frame->extended_data[i + AV_NUM_DATA_POINTERS] = frame->extended_buf[i]->data;
1350 if (avctx->debug & FF_DEBUG_BUFFERS)
1351 av_log(avctx, AV_LOG_DEBUG, "default_get_buffer called on frame %p", frame);
1355 av_frame_unref(frame);
1356 return AVERROR(ENOMEM);
1359 static int video_get_buffer(AVCodecContext *s, AVFrame *pic)
1361 FramePool *pool = s->internal->pool;
1362 const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(pic->format);
1365 if (pic->data[0] || pic->data[1] || pic->data[2] || pic->data[3]) {
1366 av_log(s, AV_LOG_ERROR, "pic->data[*]!=NULL in avcodec_default_get_buffer\n");
1371 av_log(s, AV_LOG_ERROR,
1372 "Unable to get pixel format descriptor for format %s\n",
1373 av_get_pix_fmt_name(pic->format));
1374 return AVERROR(EINVAL);
1377 memset(pic->data, 0, sizeof(pic->data));
1378 pic->extended_data = pic->data;
1380 for (i = 0; i < 4 && pool->pools[i]; i++) {
1381 pic->linesize[i] = pool->linesize[i];
1383 pic->buf[i] = av_buffer_pool_get(pool->pools[i]);
1387 pic->data[i] = pic->buf[i]->data;
1389 for (; i < AV_NUM_DATA_POINTERS; i++) {
1390 pic->data[i] = NULL;
1391 pic->linesize[i] = 0;
1393 if (desc->flags & AV_PIX_FMT_FLAG_PAL ||
1394 desc->flags & AV_PIX_FMT_FLAG_PSEUDOPAL)
1395 avpriv_set_systematic_pal2((uint32_t *)pic->data[1], pic->format);
1397 if (s->debug & FF_DEBUG_BUFFERS)
1398 av_log(s, AV_LOG_DEBUG, "default_get_buffer called on pic %p\n", pic);
1402 av_frame_unref(pic);
1403 return AVERROR(ENOMEM);
1406 int avcodec_default_get_buffer2(AVCodecContext *avctx, AVFrame *frame, int flags)
1410 if (avctx->hw_frames_ctx)
1411 return av_hwframe_get_buffer(avctx->hw_frames_ctx, frame, 0);
1413 if ((ret = update_frame_pool(avctx, frame)) < 0)
1416 switch (avctx->codec_type) {
1417 case AVMEDIA_TYPE_VIDEO:
1418 return video_get_buffer(avctx, frame);
1419 case AVMEDIA_TYPE_AUDIO:
1420 return audio_get_buffer(avctx, frame);
1426 static int add_metadata_from_side_data(const AVPacket *avpkt, AVFrame *frame)
1429 const uint8_t *side_metadata;
1431 AVDictionary **frame_md = &frame->metadata;
1433 side_metadata = av_packet_get_side_data(avpkt,
1434 AV_PKT_DATA_STRINGS_METADATA, &size);
1435 return av_packet_unpack_dictionary(side_metadata, size, frame_md);
1438 int ff_init_buffer_info(AVCodecContext *avctx, AVFrame *frame)
1440 const AVPacket *pkt = avctx->internal->last_pkt_props;
1442 static const struct {
1443 enum AVPacketSideDataType packet;
1444 enum AVFrameSideDataType frame;
1446 { AV_PKT_DATA_REPLAYGAIN , AV_FRAME_DATA_REPLAYGAIN },
1447 { AV_PKT_DATA_DISPLAYMATRIX, AV_FRAME_DATA_DISPLAYMATRIX },
1448 { AV_PKT_DATA_SPHERICAL, AV_FRAME_DATA_SPHERICAL },
1449 { AV_PKT_DATA_STEREO3D, AV_FRAME_DATA_STEREO3D },
1450 { AV_PKT_DATA_AUDIO_SERVICE_TYPE, AV_FRAME_DATA_AUDIO_SERVICE_TYPE },
1451 { AV_PKT_DATA_MASTERING_DISPLAY_METADATA, AV_FRAME_DATA_MASTERING_DISPLAY_METADATA },
1452 { AV_PKT_DATA_CONTENT_LIGHT_LEVEL, AV_FRAME_DATA_CONTENT_LIGHT_LEVEL },
1456 frame->pts = pkt->pts;
1458 FF_DISABLE_DEPRECATION_WARNINGS
1459 frame->pkt_pts = pkt->pts;
1460 FF_ENABLE_DEPRECATION_WARNINGS
1462 frame->pkt_pos = pkt->pos;
1463 frame->pkt_duration = pkt->duration;
1464 frame->pkt_size = pkt->size;
1466 for (i = 0; i < FF_ARRAY_ELEMS(sd); i++) {
1468 uint8_t *packet_sd = av_packet_get_side_data(pkt, sd[i].packet, &size);
1470 AVFrameSideData *frame_sd = av_frame_new_side_data(frame,
1474 return AVERROR(ENOMEM);
1476 memcpy(frame_sd->data, packet_sd, size);
1479 add_metadata_from_side_data(pkt, frame);
1481 if (pkt->flags & AV_PKT_FLAG_DISCARD) {
1482 frame->flags |= AV_FRAME_FLAG_DISCARD;
1484 frame->flags = (frame->flags & ~AV_FRAME_FLAG_DISCARD);
1487 frame->reordered_opaque = avctx->reordered_opaque;
1489 if (frame->color_primaries == AVCOL_PRI_UNSPECIFIED)
1490 frame->color_primaries = avctx->color_primaries;
1491 if (frame->color_trc == AVCOL_TRC_UNSPECIFIED)
1492 frame->color_trc = avctx->color_trc;
1493 if (frame->colorspace == AVCOL_SPC_UNSPECIFIED)
1494 frame->colorspace = avctx->colorspace;
1495 if (frame->color_range == AVCOL_RANGE_UNSPECIFIED)
1496 frame->color_range = avctx->color_range;
1497 if (frame->chroma_location == AVCHROMA_LOC_UNSPECIFIED)
1498 frame->chroma_location = avctx->chroma_sample_location;
1500 switch (avctx->codec->type) {
1501 case AVMEDIA_TYPE_VIDEO:
1502 frame->format = avctx->pix_fmt;
1503 if (!frame->sample_aspect_ratio.num)
1504 frame->sample_aspect_ratio = avctx->sample_aspect_ratio;
1506 if (frame->width && frame->height &&
1507 av_image_check_sar(frame->width, frame->height,
1508 frame->sample_aspect_ratio) < 0) {
1509 av_log(avctx, AV_LOG_WARNING, "ignoring invalid SAR: %u/%u\n",
1510 frame->sample_aspect_ratio.num,
1511 frame->sample_aspect_ratio.den);
1512 frame->sample_aspect_ratio = (AVRational){ 0, 1 };
1516 case AVMEDIA_TYPE_AUDIO:
1517 if (!frame->sample_rate)
1518 frame->sample_rate = avctx->sample_rate;
1519 if (frame->format < 0)
1520 frame->format = avctx->sample_fmt;
1521 if (!frame->channel_layout) {
1522 if (avctx->channel_layout) {
1523 if (av_get_channel_layout_nb_channels(avctx->channel_layout) !=
1525 av_log(avctx, AV_LOG_ERROR, "Inconsistent channel "
1526 "configuration.\n");
1527 return AVERROR(EINVAL);
1530 frame->channel_layout = avctx->channel_layout;
1532 if (avctx->channels > FF_SANE_NB_CHANNELS) {
1533 av_log(avctx, AV_LOG_ERROR, "Too many channels: %d.\n",
1535 return AVERROR(ENOSYS);
1539 frame->channels = avctx->channels;
1545 int ff_decode_frame_props(AVCodecContext *avctx, AVFrame *frame)
1547 return ff_init_buffer_info(avctx, frame);
1550 static void validate_avframe_allocation(AVCodecContext *avctx, AVFrame *frame)
1552 if (avctx->codec_type == AVMEDIA_TYPE_VIDEO) {
1554 int num_planes = av_pix_fmt_count_planes(frame->format);
1555 const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(frame->format);
1556 int flags = desc ? desc->flags : 0;
1557 if (num_planes == 1 && (flags & AV_PIX_FMT_FLAG_PAL))
1559 for (i = 0; i < num_planes; i++) {
1560 av_assert0(frame->data[i]);
1562 // For now do not enforce anything for palette of pseudopal formats
1563 if (num_planes == 1 && (flags & AV_PIX_FMT_FLAG_PSEUDOPAL))
1565 // For formats without data like hwaccel allow unused pointers to be non-NULL.
1566 for (i = num_planes; num_planes > 0 && i < FF_ARRAY_ELEMS(frame->data); i++) {
1568 av_log(avctx, AV_LOG_ERROR, "Buffer returned by get_buffer2() did not zero unused plane pointers\n");
1569 frame->data[i] = NULL;
1574 static int get_buffer_internal(AVCodecContext *avctx, AVFrame *frame, int flags)
1576 const AVHWAccel *hwaccel = avctx->hwaccel;
1577 int override_dimensions = 1;
1580 if (avctx->codec_type == AVMEDIA_TYPE_VIDEO) {
1581 if ((ret = av_image_check_size2(avctx->width, avctx->height, avctx->max_pixels, AV_PIX_FMT_NONE, 0, avctx)) < 0 || avctx->pix_fmt<0) {
1582 av_log(avctx, AV_LOG_ERROR, "video_get_buffer: image parameters invalid\n");
1583 return AVERROR(EINVAL);
1586 if (frame->width <= 0 || frame->height <= 0) {
1587 frame->width = FFMAX(avctx->width, AV_CEIL_RSHIFT(avctx->coded_width, avctx->lowres));
1588 frame->height = FFMAX(avctx->height, AV_CEIL_RSHIFT(avctx->coded_height, avctx->lowres));
1589 override_dimensions = 0;
1592 if (frame->data[0] || frame->data[1] || frame->data[2] || frame->data[3]) {
1593 av_log(avctx, AV_LOG_ERROR, "pic->data[*]!=NULL in get_buffer_internal\n");
1594 return AVERROR(EINVAL);
1597 ret = ff_decode_frame_props(avctx, frame);
1602 if (hwaccel->alloc_frame) {
1603 ret = hwaccel->alloc_frame(avctx, frame);
1607 avctx->sw_pix_fmt = avctx->pix_fmt;
1609 ret = avctx->get_buffer2(avctx, frame, flags);
1611 validate_avframe_allocation(avctx, frame);
1614 if (avctx->codec_type == AVMEDIA_TYPE_VIDEO && !override_dimensions) {
1615 frame->width = avctx->width;
1616 frame->height = avctx->height;
1622 int ff_get_buffer(AVCodecContext *avctx, AVFrame *frame, int flags)
1624 int ret = get_buffer_internal(avctx, frame, flags);
1626 av_log(avctx, AV_LOG_ERROR, "get_buffer() failed\n");
1627 frame->width = frame->height = 0;
1632 static int reget_buffer_internal(AVCodecContext *avctx, AVFrame *frame)
1637 av_assert0(avctx->codec_type == AVMEDIA_TYPE_VIDEO);
1639 if (frame->data[0] && (frame->width != avctx->width || frame->height != avctx->height || frame->format != avctx->pix_fmt)) {
1640 av_log(avctx, AV_LOG_WARNING, "Picture changed from size:%dx%d fmt:%s to size:%dx%d fmt:%s in reget buffer()\n",
1641 frame->width, frame->height, av_get_pix_fmt_name(frame->format), avctx->width, avctx->height, av_get_pix_fmt_name(avctx->pix_fmt));
1642 av_frame_unref(frame);
1645 ff_init_buffer_info(avctx, frame);
1647 if (!frame->data[0])
1648 return ff_get_buffer(avctx, frame, AV_GET_BUFFER_FLAG_REF);
1650 if (av_frame_is_writable(frame))
1651 return ff_decode_frame_props(avctx, frame);
1653 tmp = av_frame_alloc();
1655 return AVERROR(ENOMEM);
1657 av_frame_move_ref(tmp, frame);
1659 ret = ff_get_buffer(avctx, frame, AV_GET_BUFFER_FLAG_REF);
1661 av_frame_free(&tmp);
1665 av_frame_copy(frame, tmp);
1666 av_frame_free(&tmp);
1671 int ff_reget_buffer(AVCodecContext *avctx, AVFrame *frame)
1673 int ret = reget_buffer_internal(avctx, frame);
1675 av_log(avctx, AV_LOG_ERROR, "reget_buffer() failed\n");
1679 void avcodec_flush_buffers(AVCodecContext *avctx)
1681 avctx->internal->draining = 0;
1682 avctx->internal->draining_done = 0;
1683 avctx->internal->nb_draining_errors = 0;
1684 av_frame_unref(avctx->internal->buffer_frame);
1685 av_frame_unref(avctx->internal->compat_decode_frame);
1686 av_packet_unref(avctx->internal->buffer_pkt);
1687 avctx->internal->buffer_pkt_valid = 0;
1689 av_packet_unref(avctx->internal->ds.in_pkt);
1691 if (HAVE_THREADS && avctx->active_thread_type & FF_THREAD_FRAME)
1692 ff_thread_flush(avctx);
1693 else if (avctx->codec->flush)
1694 avctx->codec->flush(avctx);
1696 avctx->pts_correction_last_pts =
1697 avctx->pts_correction_last_dts = INT64_MIN;
1699 ff_decode_bsfs_uninit(avctx);
1701 if (!avctx->refcounted_frames)
1702 av_frame_unref(avctx->internal->to_free);
1705 void ff_decode_bsfs_uninit(AVCodecContext *avctx)
1707 DecodeFilterContext *s = &avctx->internal->filter;
1710 for (i = 0; i < s->nb_bsfs; i++)
1711 av_bsf_free(&s->bsfs[i]);