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"
39 #include "libavutil/opt.h"
42 #include "bytestream.h"
48 typedef struct FramePool {
50 * Pools for each data plane. For audio all the planes have the same size,
51 * so only pools[0] is used.
53 AVBufferPool *pools[4];
60 int stride_align[AV_NUM_DATA_POINTERS];
67 static int apply_param_change(AVCodecContext *avctx, const AVPacket *avpkt)
74 data = av_packet_get_side_data(avpkt, AV_PKT_DATA_PARAM_CHANGE, &size);
78 if (!(avctx->codec->capabilities & AV_CODEC_CAP_PARAM_CHANGE)) {
79 av_log(avctx, AV_LOG_ERROR, "This decoder does not support parameter "
80 "changes, but PARAM_CHANGE side data was sent to it.\n");
81 ret = AVERROR(EINVAL);
88 flags = bytestream_get_le32(&data);
91 if (flags & AV_SIDE_DATA_PARAM_CHANGE_CHANNEL_COUNT) {
94 val = bytestream_get_le32(&data);
95 if (val <= 0 || val > INT_MAX) {
96 av_log(avctx, AV_LOG_ERROR, "Invalid channel count");
97 ret = AVERROR_INVALIDDATA;
100 avctx->channels = val;
103 if (flags & AV_SIDE_DATA_PARAM_CHANGE_CHANNEL_LAYOUT) {
106 avctx->channel_layout = bytestream_get_le64(&data);
109 if (flags & AV_SIDE_DATA_PARAM_CHANGE_SAMPLE_RATE) {
112 val = bytestream_get_le32(&data);
113 if (val <= 0 || val > INT_MAX) {
114 av_log(avctx, AV_LOG_ERROR, "Invalid sample rate");
115 ret = AVERROR_INVALIDDATA;
118 avctx->sample_rate = val;
121 if (flags & AV_SIDE_DATA_PARAM_CHANGE_DIMENSIONS) {
124 avctx->width = bytestream_get_le32(&data);
125 avctx->height = bytestream_get_le32(&data);
127 ret = ff_set_dimensions(avctx, avctx->width, avctx->height);
134 av_log(avctx, AV_LOG_ERROR, "PARAM_CHANGE side data too small.\n");
135 ret = AVERROR_INVALIDDATA;
138 av_log(avctx, AV_LOG_ERROR, "Error applying parameter changes.\n");
139 if (avctx->err_recognition & AV_EF_EXPLODE)
145 static int extract_packet_props(AVCodecInternal *avci, const AVPacket *pkt)
149 av_packet_unref(avci->last_pkt_props);
151 ret = av_packet_copy_props(avci->last_pkt_props, pkt);
153 avci->last_pkt_props->size = pkt->size; // HACK: Needed for ff_decode_frame_props().
158 static int unrefcount_frame(AVCodecInternal *avci, AVFrame *frame)
162 /* move the original frame to our backup */
163 av_frame_unref(avci->to_free);
164 av_frame_move_ref(avci->to_free, frame);
166 /* now copy everything except the AVBufferRefs back
167 * note that we make a COPY of the side data, so calling av_frame_free() on
168 * the caller's frame will work properly */
169 ret = av_frame_copy_props(frame, avci->to_free);
173 memcpy(frame->data, avci->to_free->data, sizeof(frame->data));
174 memcpy(frame->linesize, avci->to_free->linesize, sizeof(frame->linesize));
175 if (avci->to_free->extended_data != avci->to_free->data) {
176 int planes = avci->to_free->channels;
177 int size = planes * sizeof(*frame->extended_data);
180 av_frame_unref(frame);
184 frame->extended_data = av_malloc(size);
185 if (!frame->extended_data) {
186 av_frame_unref(frame);
187 return AVERROR(ENOMEM);
189 memcpy(frame->extended_data, avci->to_free->extended_data,
192 frame->extended_data = frame->data;
194 frame->format = avci->to_free->format;
195 frame->width = avci->to_free->width;
196 frame->height = avci->to_free->height;
197 frame->channel_layout = avci->to_free->channel_layout;
198 frame->nb_samples = avci->to_free->nb_samples;
199 frame->channels = avci->to_free->channels;
204 int ff_decode_bsfs_init(AVCodecContext *avctx)
206 AVCodecInternal *avci = avctx->internal;
212 ret = av_bsf_list_parse_str(avctx->codec->bsfs, &avci->bsf);
214 av_log(avctx, AV_LOG_ERROR, "Error parsing decoder bitstream filters '%s': %s\n", avctx->codec->bsfs, av_err2str(ret));
215 if (ret != AVERROR(ENOMEM))
220 /* We do not currently have an API for passing the input timebase into decoders,
221 * but no filters used here should actually need it.
222 * So we make up some plausible-looking number (the MPEG 90kHz timebase) */
223 avci->bsf->time_base_in = (AVRational){ 1, 90000 };
224 ret = avcodec_parameters_from_context(avci->bsf->par_in, avctx);
228 ret = av_bsf_init(avci->bsf);
234 ff_decode_bsfs_uninit(avctx);
238 int ff_decode_get_packet(AVCodecContext *avctx, AVPacket *pkt)
240 AVCodecInternal *avci = avctx->internal;
246 ret = av_bsf_receive_packet(avci->bsf, pkt);
247 if (ret == AVERROR_EOF)
252 ret = extract_packet_props(avctx->internal, pkt);
256 ret = apply_param_change(avctx, pkt);
260 if (avctx->codec->receive_frame)
261 avci->compat_decode_consumed += pkt->size;
265 av_packet_unref(pkt);
270 * Attempt to guess proper monotonic timestamps for decoded video frames
271 * which might have incorrect times. Input timestamps may wrap around, in
272 * which case the output will as well.
274 * @param pts the pts field of the decoded AVPacket, as passed through
276 * @param dts the dts field of the decoded AVPacket
277 * @return one of the input values, may be AV_NOPTS_VALUE
279 static int64_t guess_correct_pts(AVCodecContext *ctx,
280 int64_t reordered_pts, int64_t dts)
282 int64_t pts = AV_NOPTS_VALUE;
284 if (dts != AV_NOPTS_VALUE) {
285 ctx->pts_correction_num_faulty_dts += dts <= ctx->pts_correction_last_dts;
286 ctx->pts_correction_last_dts = dts;
287 } else if (reordered_pts != AV_NOPTS_VALUE)
288 ctx->pts_correction_last_dts = reordered_pts;
290 if (reordered_pts != AV_NOPTS_VALUE) {
291 ctx->pts_correction_num_faulty_pts += reordered_pts <= ctx->pts_correction_last_pts;
292 ctx->pts_correction_last_pts = reordered_pts;
293 } else if(dts != AV_NOPTS_VALUE)
294 ctx->pts_correction_last_pts = dts;
296 if ((ctx->pts_correction_num_faulty_pts<=ctx->pts_correction_num_faulty_dts || dts == AV_NOPTS_VALUE)
297 && reordered_pts != AV_NOPTS_VALUE)
306 * The core of the receive_frame_wrapper for the decoders implementing
307 * the simple API. Certain decoders might consume partial packets without
308 * returning any output, so this function needs to be called in a loop until it
311 static int decode_simple_internal(AVCodecContext *avctx, AVFrame *frame)
313 AVCodecInternal *avci = avctx->internal;
314 DecodeSimpleContext *ds = &avci->ds;
315 AVPacket *pkt = ds->in_pkt;
316 // copy to ensure we do not change pkt
317 int got_frame, actual_got_frame;
320 if (!pkt->data && !avci->draining) {
321 av_packet_unref(pkt);
322 ret = ff_decode_get_packet(avctx, pkt);
323 if (ret < 0 && ret != AVERROR_EOF)
327 // Some codecs (at least wma lossless) will crash when feeding drain packets
328 // after EOF was signaled.
329 if (avci->draining_done)
333 !(avctx->codec->capabilities & AV_CODEC_CAP_DELAY ||
334 avctx->active_thread_type & FF_THREAD_FRAME))
339 if (HAVE_THREADS && avctx->active_thread_type & FF_THREAD_FRAME) {
340 ret = ff_thread_decode_frame(avctx, frame, &got_frame, pkt);
342 ret = avctx->codec->decode(avctx, frame, &got_frame, pkt);
344 if (!(avctx->codec->caps_internal & FF_CODEC_CAP_SETS_PKT_DTS))
345 frame->pkt_dts = pkt->dts;
346 if (avctx->codec->type == AVMEDIA_TYPE_VIDEO) {
347 if(!avctx->has_b_frames)
348 frame->pkt_pos = pkt->pos;
349 //FIXME these should be under if(!avctx->has_b_frames)
350 /* get_buffer is supposed to set frame parameters */
351 if (!(avctx->codec->capabilities & AV_CODEC_CAP_DR1)) {
352 if (!frame->sample_aspect_ratio.num) frame->sample_aspect_ratio = avctx->sample_aspect_ratio;
353 if (!frame->width) frame->width = avctx->width;
354 if (!frame->height) frame->height = avctx->height;
355 if (frame->format == AV_PIX_FMT_NONE) frame->format = avctx->pix_fmt;
360 actual_got_frame = got_frame;
362 if (avctx->codec->type == AVMEDIA_TYPE_VIDEO) {
363 if (frame->flags & AV_FRAME_FLAG_DISCARD)
366 frame->best_effort_timestamp = guess_correct_pts(avctx,
369 } else if (avctx->codec->type == AVMEDIA_TYPE_AUDIO) {
372 uint32_t discard_padding = 0;
373 uint8_t skip_reason = 0;
374 uint8_t discard_reason = 0;
376 if (ret >= 0 && got_frame) {
377 frame->best_effort_timestamp = guess_correct_pts(avctx,
380 if (frame->format == AV_SAMPLE_FMT_NONE)
381 frame->format = avctx->sample_fmt;
382 if (!frame->channel_layout)
383 frame->channel_layout = avctx->channel_layout;
384 if (!frame->channels)
385 frame->channels = avctx->channels;
386 if (!frame->sample_rate)
387 frame->sample_rate = avctx->sample_rate;
390 side= av_packet_get_side_data(avci->last_pkt_props, AV_PKT_DATA_SKIP_SAMPLES, &side_size);
391 if(side && side_size>=10) {
392 avci->skip_samples = AV_RL32(side) * avci->skip_samples_multiplier;
393 discard_padding = AV_RL32(side + 4);
394 av_log(avctx, AV_LOG_DEBUG, "skip %d / discard %d samples due to side data\n",
395 avci->skip_samples, (int)discard_padding);
396 skip_reason = AV_RL8(side + 8);
397 discard_reason = AV_RL8(side + 9);
400 if ((frame->flags & AV_FRAME_FLAG_DISCARD) && got_frame &&
401 !(avctx->flags2 & AV_CODEC_FLAG2_SKIP_MANUAL)) {
402 avci->skip_samples = FFMAX(0, avci->skip_samples - frame->nb_samples);
406 if (avci->skip_samples > 0 && got_frame &&
407 !(avctx->flags2 & AV_CODEC_FLAG2_SKIP_MANUAL)) {
408 if(frame->nb_samples <= avci->skip_samples){
410 avci->skip_samples -= frame->nb_samples;
411 av_log(avctx, AV_LOG_DEBUG, "skip whole frame, skip left: %d\n",
414 av_samples_copy(frame->extended_data, frame->extended_data, 0, avci->skip_samples,
415 frame->nb_samples - avci->skip_samples, avctx->channels, frame->format);
416 if(avctx->pkt_timebase.num && avctx->sample_rate) {
417 int64_t diff_ts = av_rescale_q(avci->skip_samples,
418 (AVRational){1, avctx->sample_rate},
419 avctx->pkt_timebase);
420 if(frame->pts!=AV_NOPTS_VALUE)
421 frame->pts += diff_ts;
423 FF_DISABLE_DEPRECATION_WARNINGS
424 if(frame->pkt_pts!=AV_NOPTS_VALUE)
425 frame->pkt_pts += diff_ts;
426 FF_ENABLE_DEPRECATION_WARNINGS
428 if(frame->pkt_dts!=AV_NOPTS_VALUE)
429 frame->pkt_dts += diff_ts;
430 if (frame->pkt_duration >= diff_ts)
431 frame->pkt_duration -= diff_ts;
433 av_log(avctx, AV_LOG_WARNING, "Could not update timestamps for skipped samples.\n");
435 av_log(avctx, AV_LOG_DEBUG, "skip %d/%d samples\n",
436 avci->skip_samples, frame->nb_samples);
437 frame->nb_samples -= avci->skip_samples;
438 avci->skip_samples = 0;
442 if (discard_padding > 0 && discard_padding <= frame->nb_samples && got_frame &&
443 !(avctx->flags2 & AV_CODEC_FLAG2_SKIP_MANUAL)) {
444 if (discard_padding == frame->nb_samples) {
447 if(avctx->pkt_timebase.num && avctx->sample_rate) {
448 int64_t diff_ts = av_rescale_q(frame->nb_samples - discard_padding,
449 (AVRational){1, avctx->sample_rate},
450 avctx->pkt_timebase);
451 frame->pkt_duration = diff_ts;
453 av_log(avctx, AV_LOG_WARNING, "Could not update timestamps for discarded samples.\n");
455 av_log(avctx, AV_LOG_DEBUG, "discard %d/%d samples\n",
456 (int)discard_padding, frame->nb_samples);
457 frame->nb_samples -= discard_padding;
461 if ((avctx->flags2 & AV_CODEC_FLAG2_SKIP_MANUAL) && got_frame) {
462 AVFrameSideData *fside = av_frame_new_side_data(frame, AV_FRAME_DATA_SKIP_SAMPLES, 10);
464 AV_WL32(fside->data, avci->skip_samples);
465 AV_WL32(fside->data + 4, discard_padding);
466 AV_WL8(fside->data + 8, skip_reason);
467 AV_WL8(fside->data + 9, discard_reason);
468 avci->skip_samples = 0;
473 if (avctx->codec->type == AVMEDIA_TYPE_AUDIO &&
474 !avci->showed_multi_packet_warning &&
475 ret >= 0 && ret != pkt->size && !(avctx->codec->capabilities & AV_CODEC_CAP_SUBFRAMES)) {
476 av_log(avctx, AV_LOG_WARNING, "Multiple frames in a packet.\n");
477 avci->showed_multi_packet_warning = 1;
481 av_frame_unref(frame);
483 if (ret >= 0 && avctx->codec->type == AVMEDIA_TYPE_VIDEO && !(avctx->flags & AV_CODEC_FLAG_TRUNCATED))
486 #if FF_API_AVCTX_TIMEBASE
487 if (avctx->framerate.num > 0 && avctx->framerate.den > 0)
488 avctx->time_base = av_inv_q(av_mul_q(avctx->framerate, (AVRational){avctx->ticks_per_frame, 1}));
491 /* do not stop draining when actual_got_frame != 0 or ret < 0 */
492 /* got_frame == 0 but actual_got_frame != 0 when frame is discarded */
493 if (avci->draining && !actual_got_frame) {
495 /* prevent infinite loop if a decoder wrongly always return error on draining */
496 /* reasonable nb_errors_max = maximum b frames + thread count */
497 int nb_errors_max = 20 + (HAVE_THREADS && avctx->active_thread_type & FF_THREAD_FRAME ?
498 avctx->thread_count : 1);
500 if (avci->nb_draining_errors++ >= nb_errors_max) {
501 av_log(avctx, AV_LOG_ERROR, "Too many errors when draining, this is a bug. "
502 "Stop draining and force EOF.\n");
503 avci->draining_done = 1;
507 avci->draining_done = 1;
511 avci->compat_decode_consumed += ret;
513 if (ret >= pkt->size || ret < 0) {
514 av_packet_unref(pkt);
518 pkt->data += consumed;
519 pkt->size -= consumed;
520 avci->last_pkt_props->size -= consumed; // See extract_packet_props() comment.
521 pkt->pts = AV_NOPTS_VALUE;
522 pkt->dts = AV_NOPTS_VALUE;
523 avci->last_pkt_props->pts = AV_NOPTS_VALUE;
524 avci->last_pkt_props->dts = AV_NOPTS_VALUE;
528 av_assert0(frame->buf[0]);
530 return ret < 0 ? ret : 0;
533 static int decode_simple_receive_frame(AVCodecContext *avctx, AVFrame *frame)
537 while (!frame->buf[0]) {
538 ret = decode_simple_internal(avctx, frame);
546 static int decode_receive_frame_internal(AVCodecContext *avctx, AVFrame *frame)
548 AVCodecInternal *avci = avctx->internal;
551 av_assert0(!frame->buf[0]);
553 if (avctx->codec->receive_frame)
554 ret = avctx->codec->receive_frame(avctx, frame);
556 ret = decode_simple_receive_frame(avctx, frame);
558 if (ret == AVERROR_EOF)
559 avci->draining_done = 1;
562 /* the only case where decode data is not set should be decoders
563 * that do not call ff_get_buffer() */
564 av_assert0((frame->private_ref && frame->private_ref->size == sizeof(FrameDecodeData)) ||
565 !(avctx->codec->capabilities & AV_CODEC_CAP_DR1));
567 if (frame->private_ref) {
568 FrameDecodeData *fdd = (FrameDecodeData*)frame->private_ref->data;
570 if (fdd->post_process) {
571 ret = fdd->post_process(avctx, frame);
573 av_frame_unref(frame);
580 /* free the per-frame decode data */
581 av_buffer_unref(&frame->private_ref);
586 int attribute_align_arg avcodec_send_packet(AVCodecContext *avctx, const AVPacket *avpkt)
588 AVCodecInternal *avci = avctx->internal;
591 if (!avcodec_is_open(avctx) || !av_codec_is_decoder(avctx->codec))
592 return AVERROR(EINVAL);
594 if (avctx->internal->draining)
597 if (avpkt && !avpkt->size && avpkt->data)
598 return AVERROR(EINVAL);
600 av_packet_unref(avci->buffer_pkt);
601 if (avpkt && (avpkt->data || avpkt->side_data_elems)) {
602 ret = av_packet_ref(avci->buffer_pkt, avpkt);
607 ret = av_bsf_send_packet(avci->bsf, avci->buffer_pkt);
609 av_packet_unref(avci->buffer_pkt);
613 if (!avci->buffer_frame->buf[0]) {
614 ret = decode_receive_frame_internal(avctx, avci->buffer_frame);
615 if (ret < 0 && ret != AVERROR(EAGAIN) && ret != AVERROR_EOF)
622 static int apply_cropping(AVCodecContext *avctx, AVFrame *frame)
624 /* make sure we are noisy about decoders returning invalid cropping data */
625 if (frame->crop_left >= INT_MAX - frame->crop_right ||
626 frame->crop_top >= INT_MAX - frame->crop_bottom ||
627 (frame->crop_left + frame->crop_right) >= frame->width ||
628 (frame->crop_top + frame->crop_bottom) >= frame->height) {
629 av_log(avctx, AV_LOG_WARNING,
630 "Invalid cropping information set by a decoder: "
631 "%"SIZE_SPECIFIER"/%"SIZE_SPECIFIER"/%"SIZE_SPECIFIER"/%"SIZE_SPECIFIER" "
632 "(frame size %dx%d). This is a bug, please report it\n",
633 frame->crop_left, frame->crop_right, frame->crop_top, frame->crop_bottom,
634 frame->width, frame->height);
635 frame->crop_left = 0;
636 frame->crop_right = 0;
638 frame->crop_bottom = 0;
642 if (!avctx->apply_cropping)
645 return av_frame_apply_cropping(frame, avctx->flags & AV_CODEC_FLAG_UNALIGNED ?
646 AV_FRAME_CROP_UNALIGNED : 0);
649 int attribute_align_arg avcodec_receive_frame(AVCodecContext *avctx, AVFrame *frame)
651 AVCodecInternal *avci = avctx->internal;
654 av_frame_unref(frame);
656 if (!avcodec_is_open(avctx) || !av_codec_is_decoder(avctx->codec))
657 return AVERROR(EINVAL);
659 if (avci->buffer_frame->buf[0]) {
660 av_frame_move_ref(frame, avci->buffer_frame);
662 ret = decode_receive_frame_internal(avctx, frame);
667 if (avctx->codec_type == AVMEDIA_TYPE_VIDEO) {
668 ret = apply_cropping(avctx, frame);
670 av_frame_unref(frame);
675 avctx->frame_number++;
677 if (avctx->flags & AV_CODEC_FLAG_DROPCHANGED) {
679 if (avctx->frame_number == 1) {
680 avci->initial_format = frame->format;
681 switch(avctx->codec_type) {
682 case AVMEDIA_TYPE_VIDEO:
683 avci->initial_width = frame->width;
684 avci->initial_height = frame->height;
686 case AVMEDIA_TYPE_AUDIO:
687 avci->initial_sample_rate = frame->sample_rate ? frame->sample_rate :
689 avci->initial_channels = frame->channels;
690 avci->initial_channel_layout = frame->channel_layout;
695 if (avctx->frame_number > 1) {
696 changed = avci->initial_format != frame->format;
698 switch(avctx->codec_type) {
699 case AVMEDIA_TYPE_VIDEO:
700 changed |= avci->initial_width != frame->width ||
701 avci->initial_height != frame->height;
703 case AVMEDIA_TYPE_AUDIO:
704 changed |= avci->initial_sample_rate != frame->sample_rate ||
705 avci->initial_sample_rate != avctx->sample_rate ||
706 avci->initial_channels != frame->channels ||
707 avci->initial_channel_layout != frame->channel_layout;
712 avci->changed_frames_dropped++;
713 av_log(avctx, AV_LOG_INFO, "dropped changed frame #%d pts %"PRId64
714 " drop count: %d \n",
715 avctx->frame_number, frame->pts,
716 avci->changed_frames_dropped);
717 av_frame_unref(frame);
718 return AVERROR_INPUT_CHANGED;
725 static int compat_decode(AVCodecContext *avctx, AVFrame *frame,
726 int *got_frame, const AVPacket *pkt)
728 AVCodecInternal *avci = avctx->internal;
731 av_assert0(avci->compat_decode_consumed == 0);
733 if (avci->draining_done && pkt && pkt->size != 0) {
734 av_log(avctx, AV_LOG_WARNING, "Got unexpected packet after EOF\n");
735 avcodec_flush_buffers(avctx);
739 avci->compat_decode = 1;
741 if (avci->compat_decode_partial_size > 0 &&
742 avci->compat_decode_partial_size != pkt->size) {
743 av_log(avctx, AV_LOG_ERROR,
744 "Got unexpected packet size after a partial decode\n");
745 ret = AVERROR(EINVAL);
749 if (!avci->compat_decode_partial_size) {
750 ret = avcodec_send_packet(avctx, pkt);
751 if (ret == AVERROR_EOF)
753 else if (ret == AVERROR(EAGAIN)) {
754 /* we fully drain all the output in each decode call, so this should not
763 ret = avcodec_receive_frame(avctx, frame);
765 if (ret == AVERROR(EAGAIN) || ret == AVERROR_EOF)
770 if (frame != avci->compat_decode_frame) {
771 if (!avctx->refcounted_frames) {
772 ret = unrefcount_frame(avci, frame);
778 frame = avci->compat_decode_frame;
780 if (!avci->compat_decode_warned) {
781 av_log(avctx, AV_LOG_WARNING, "The deprecated avcodec_decode_* "
782 "API cannot return all the frames for this decoder. "
783 "Some frames will be dropped. Update your code to the "
784 "new decoding API to fix this.\n");
785 avci->compat_decode_warned = 1;
789 if (avci->draining || (!avctx->codec->bsfs && avci->compat_decode_consumed < pkt->size))
795 /* if there are any bsfs then assume full packet is always consumed */
796 if (avctx->codec->bsfs)
799 ret = FFMIN(avci->compat_decode_consumed, pkt->size);
801 avci->compat_decode_consumed = 0;
802 avci->compat_decode_partial_size = (ret >= 0) ? pkt->size - ret : 0;
807 int attribute_align_arg avcodec_decode_video2(AVCodecContext *avctx, AVFrame *picture,
808 int *got_picture_ptr,
809 const AVPacket *avpkt)
811 return compat_decode(avctx, picture, got_picture_ptr, avpkt);
814 int attribute_align_arg avcodec_decode_audio4(AVCodecContext *avctx,
817 const AVPacket *avpkt)
819 return compat_decode(avctx, frame, got_frame_ptr, avpkt);
822 static void get_subtitle_defaults(AVSubtitle *sub)
824 memset(sub, 0, sizeof(*sub));
825 sub->pts = AV_NOPTS_VALUE;
828 #define UTF8_MAX_BYTES 4 /* 5 and 6 bytes sequences should not be used */
829 static int recode_subtitle(AVCodecContext *avctx,
830 AVPacket *outpkt, const AVPacket *inpkt)
833 iconv_t cd = (iconv_t)-1;
840 if (avctx->sub_charenc_mode != FF_SUB_CHARENC_MODE_PRE_DECODER || inpkt->size == 0)
844 cd = iconv_open("UTF-8", avctx->sub_charenc);
845 av_assert0(cd != (iconv_t)-1);
850 if (inl >= INT_MAX / UTF8_MAX_BYTES - AV_INPUT_BUFFER_PADDING_SIZE) {
851 av_log(avctx, AV_LOG_ERROR, "Subtitles packet is too big for recoding\n");
852 ret = AVERROR(ENOMEM);
856 ret = av_new_packet(&tmp, inl * UTF8_MAX_BYTES);
859 outpkt->buf = tmp.buf;
860 outpkt->data = tmp.data;
861 outpkt->size = tmp.size;
865 if (iconv(cd, &inb, &inl, &outb, &outl) == (size_t)-1 ||
866 iconv(cd, NULL, NULL, &outb, &outl) == (size_t)-1 ||
867 outl >= outpkt->size || inl != 0) {
868 ret = FFMIN(AVERROR(errno), -1);
869 av_log(avctx, AV_LOG_ERROR, "Unable to recode subtitle event \"%s\" "
870 "from %s to UTF-8\n", inpkt->data, avctx->sub_charenc);
871 av_packet_unref(&tmp);
874 outpkt->size -= outl;
875 memset(outpkt->data + outpkt->size, 0, outl);
878 if (cd != (iconv_t)-1)
882 av_log(avctx, AV_LOG_ERROR, "requesting subtitles recoding without iconv");
883 return AVERROR(EINVAL);
887 static int utf8_check(const uint8_t *str)
890 uint32_t codepoint, min;
894 GET_UTF8(codepoint, *(byte++), return 0;);
895 min = byte - str == 1 ? 0 : byte - str == 2 ? 0x80 :
896 1 << (5 * (byte - str) - 4);
897 if (codepoint < min || codepoint >= 0x110000 ||
898 codepoint == 0xFFFE /* BOM */ ||
899 codepoint >= 0xD800 && codepoint <= 0xDFFF /* surrogates */)
906 #if FF_API_ASS_TIMING
907 static void insert_ts(AVBPrint *buf, int ts)
910 av_bprintf(buf, "9:59:59.99,");
914 h = ts/360000; ts -= 360000*h;
915 m = ts/ 6000; ts -= 6000*m;
916 s = ts/ 100; ts -= 100*s;
917 av_bprintf(buf, "%d:%02d:%02d.%02d,", h, m, s, ts);
921 static int convert_sub_to_old_ass_form(AVSubtitle *sub, const AVPacket *pkt, AVRational tb)
926 av_bprint_init(&buf, 0, AV_BPRINT_SIZE_UNLIMITED);
928 for (i = 0; i < sub->num_rects; i++) {
931 AVSubtitleRect *rect = sub->rects[i];
932 int ts_start, ts_duration = -1;
935 if (rect->type != SUBTITLE_ASS || !strncmp(rect->ass, "Dialogue: ", 10))
938 av_bprint_clear(&buf);
941 dialog = strchr(rect->ass, ',');
946 /* extract Layer or Marked */
947 layer = strtol(dialog, (char**)&dialog, 10);
952 /* rescale timing to ASS time base (ms) */
953 ts_start = av_rescale_q(pkt->pts, tb, av_make_q(1, 100));
954 if (pkt->duration != -1)
955 ts_duration = av_rescale_q(pkt->duration, tb, av_make_q(1, 100));
956 sub->end_display_time = FFMAX(sub->end_display_time, 10 * ts_duration);
958 /* construct ASS (standalone file form with timestamps) string */
959 av_bprintf(&buf, "Dialogue: %ld,", layer);
960 insert_ts(&buf, ts_start);
961 insert_ts(&buf, ts_duration == -1 ? -1 : ts_start + ts_duration);
962 av_bprintf(&buf, "%s\r\n", dialog);
964 final_dialog = av_strdup(buf.str);
965 if (!av_bprint_is_complete(&buf) || !final_dialog) {
966 av_freep(&final_dialog);
967 av_bprint_finalize(&buf, NULL);
968 return AVERROR(ENOMEM);
970 av_freep(&rect->ass);
971 rect->ass = final_dialog;
974 av_bprint_finalize(&buf, NULL);
979 int avcodec_decode_subtitle2(AVCodecContext *avctx, AVSubtitle *sub,
985 if (!avpkt->data && avpkt->size) {
986 av_log(avctx, AV_LOG_ERROR, "invalid packet: NULL data, size != 0\n");
987 return AVERROR(EINVAL);
990 return AVERROR(EINVAL);
991 if (avctx->codec->type != AVMEDIA_TYPE_SUBTITLE) {
992 av_log(avctx, AV_LOG_ERROR, "Invalid media type for subtitles\n");
993 return AVERROR(EINVAL);
997 get_subtitle_defaults(sub);
999 if ((avctx->codec->capabilities & AV_CODEC_CAP_DELAY) || avpkt->size) {
1000 AVPacket pkt_recoded = *avpkt;
1002 ret = recode_subtitle(avctx, &pkt_recoded, avpkt);
1006 ret = extract_packet_props(avctx->internal, &pkt_recoded);
1010 if (avctx->pkt_timebase.num && avpkt->pts != AV_NOPTS_VALUE)
1011 sub->pts = av_rescale_q(avpkt->pts,
1012 avctx->pkt_timebase, AV_TIME_BASE_Q);
1013 ret = avctx->codec->decode(avctx, sub, got_sub_ptr, &pkt_recoded);
1014 av_assert1((ret >= 0) >= !!*got_sub_ptr &&
1015 !!*got_sub_ptr >= !!sub->num_rects);
1017 #if FF_API_ASS_TIMING
1018 if (avctx->sub_text_format == FF_SUB_TEXT_FMT_ASS_WITH_TIMINGS
1019 && *got_sub_ptr && sub->num_rects) {
1020 const AVRational tb = avctx->pkt_timebase.num ? avctx->pkt_timebase
1022 int err = convert_sub_to_old_ass_form(sub, avpkt, tb);
1028 if (sub->num_rects && !sub->end_display_time && avpkt->duration &&
1029 avctx->pkt_timebase.num) {
1030 AVRational ms = { 1, 1000 };
1031 sub->end_display_time = av_rescale_q(avpkt->duration,
1032 avctx->pkt_timebase, ms);
1035 if (avctx->codec_descriptor->props & AV_CODEC_PROP_BITMAP_SUB)
1037 else if (avctx->codec_descriptor->props & AV_CODEC_PROP_TEXT_SUB)
1040 for (i = 0; i < sub->num_rects; i++) {
1041 if (avctx->sub_charenc_mode != FF_SUB_CHARENC_MODE_IGNORE &&
1042 sub->rects[i]->ass && !utf8_check(sub->rects[i]->ass)) {
1043 av_log(avctx, AV_LOG_ERROR,
1044 "Invalid UTF-8 in decoded subtitles text; "
1045 "maybe missing -sub_charenc option\n");
1046 avsubtitle_free(sub);
1047 ret = AVERROR_INVALIDDATA;
1052 if (avpkt->data != pkt_recoded.data) { // did we recode?
1053 /* prevent from destroying side data from original packet */
1054 pkt_recoded.side_data = NULL;
1055 pkt_recoded.side_data_elems = 0;
1057 av_packet_unref(&pkt_recoded);
1062 avctx->frame_number++;
1068 enum AVPixelFormat avcodec_default_get_format(struct AVCodecContext *avctx,
1069 const enum AVPixelFormat *fmt)
1071 const AVPixFmtDescriptor *desc;
1072 const AVCodecHWConfig *config;
1075 // If a device was supplied when the codec was opened, assume that the
1076 // user wants to use it.
1077 if (avctx->hw_device_ctx && avctx->codec->hw_configs) {
1078 AVHWDeviceContext *device_ctx =
1079 (AVHWDeviceContext*)avctx->hw_device_ctx->data;
1081 config = &avctx->codec->hw_configs[i]->public;
1084 if (!(config->methods &
1085 AV_CODEC_HW_CONFIG_METHOD_HW_DEVICE_CTX))
1087 if (device_ctx->type != config->device_type)
1089 for (n = 0; fmt[n] != AV_PIX_FMT_NONE; n++) {
1090 if (config->pix_fmt == fmt[n])
1095 // No device or other setup, so we have to choose from things which
1096 // don't any other external information.
1098 // If the last element of the list is a software format, choose it
1099 // (this should be best software format if any exist).
1100 for (n = 0; fmt[n] != AV_PIX_FMT_NONE; n++);
1101 desc = av_pix_fmt_desc_get(fmt[n - 1]);
1102 if (!(desc->flags & AV_PIX_FMT_FLAG_HWACCEL))
1105 // Finally, traverse the list in order and choose the first entry
1106 // with no external dependencies (if there is no hardware configuration
1107 // information available then this just picks the first entry).
1108 for (n = 0; fmt[n] != AV_PIX_FMT_NONE; n++) {
1110 config = avcodec_get_hw_config(avctx->codec, i);
1113 if (config->pix_fmt == fmt[n])
1117 // No specific config available, so the decoder must be able
1118 // to handle this format without any additional setup.
1121 if (config->methods & AV_CODEC_HW_CONFIG_METHOD_INTERNAL) {
1122 // Usable with only internal setup.
1127 // Nothing is usable, give up.
1128 return AV_PIX_FMT_NONE;
1131 int ff_decode_get_hw_frames_ctx(AVCodecContext *avctx,
1132 enum AVHWDeviceType dev_type)
1134 AVHWDeviceContext *device_ctx;
1135 AVHWFramesContext *frames_ctx;
1138 if (!avctx->hwaccel)
1139 return AVERROR(ENOSYS);
1141 if (avctx->hw_frames_ctx)
1143 if (!avctx->hw_device_ctx) {
1144 av_log(avctx, AV_LOG_ERROR, "A hardware frames or device context is "
1145 "required for hardware accelerated decoding.\n");
1146 return AVERROR(EINVAL);
1149 device_ctx = (AVHWDeviceContext *)avctx->hw_device_ctx->data;
1150 if (device_ctx->type != dev_type) {
1151 av_log(avctx, AV_LOG_ERROR, "Device type %s expected for hardware "
1152 "decoding, but got %s.\n", av_hwdevice_get_type_name(dev_type),
1153 av_hwdevice_get_type_name(device_ctx->type));
1154 return AVERROR(EINVAL);
1157 ret = avcodec_get_hw_frames_parameters(avctx,
1158 avctx->hw_device_ctx,
1159 avctx->hwaccel->pix_fmt,
1160 &avctx->hw_frames_ctx);
1164 frames_ctx = (AVHWFramesContext*)avctx->hw_frames_ctx->data;
1167 if (frames_ctx->initial_pool_size) {
1168 // We guarantee 4 base work surfaces. The function above guarantees 1
1169 // (the absolute minimum), so add the missing count.
1170 frames_ctx->initial_pool_size += 3;
1173 ret = av_hwframe_ctx_init(avctx->hw_frames_ctx);
1175 av_buffer_unref(&avctx->hw_frames_ctx);
1182 int avcodec_get_hw_frames_parameters(AVCodecContext *avctx,
1183 AVBufferRef *device_ref,
1184 enum AVPixelFormat hw_pix_fmt,
1185 AVBufferRef **out_frames_ref)
1187 AVBufferRef *frames_ref = NULL;
1188 const AVCodecHWConfigInternal *hw_config;
1189 const AVHWAccel *hwa;
1193 hw_config = avctx->codec->hw_configs[i];
1195 return AVERROR(ENOENT);
1196 if (hw_config->public.pix_fmt == hw_pix_fmt)
1200 hwa = hw_config->hwaccel;
1201 if (!hwa || !hwa->frame_params)
1202 return AVERROR(ENOENT);
1204 frames_ref = av_hwframe_ctx_alloc(device_ref);
1206 return AVERROR(ENOMEM);
1208 ret = hwa->frame_params(avctx, frames_ref);
1210 AVHWFramesContext *frames_ctx = (AVHWFramesContext*)frames_ref->data;
1212 if (frames_ctx->initial_pool_size) {
1213 // If the user has requested that extra output surfaces be
1214 // available then add them here.
1215 if (avctx->extra_hw_frames > 0)
1216 frames_ctx->initial_pool_size += avctx->extra_hw_frames;
1218 // If frame threading is enabled then an extra surface per thread
1219 // is also required.
1220 if (avctx->active_thread_type & FF_THREAD_FRAME)
1221 frames_ctx->initial_pool_size += avctx->thread_count;
1224 *out_frames_ref = frames_ref;
1226 av_buffer_unref(&frames_ref);
1231 static int hwaccel_init(AVCodecContext *avctx,
1232 const AVCodecHWConfigInternal *hw_config)
1234 const AVHWAccel *hwaccel;
1237 hwaccel = hw_config->hwaccel;
1238 if (hwaccel->capabilities & AV_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 (hwaccel->priv_data_size) {
1246 avctx->internal->hwaccel_priv_data =
1247 av_mallocz(hwaccel->priv_data_size);
1248 if (!avctx->internal->hwaccel_priv_data)
1249 return AVERROR(ENOMEM);
1252 avctx->hwaccel = hwaccel;
1253 if (hwaccel->init) {
1254 err = hwaccel->init(avctx);
1256 av_log(avctx, AV_LOG_ERROR, "Failed setup for format %s: "
1257 "hwaccel initialisation returned error.\n",
1258 av_get_pix_fmt_name(hw_config->public.pix_fmt));
1259 av_freep(&avctx->internal->hwaccel_priv_data);
1260 avctx->hwaccel = NULL;
1268 static void hwaccel_uninit(AVCodecContext *avctx)
1270 if (avctx->hwaccel && avctx->hwaccel->uninit)
1271 avctx->hwaccel->uninit(avctx);
1273 av_freep(&avctx->internal->hwaccel_priv_data);
1275 avctx->hwaccel = NULL;
1277 av_buffer_unref(&avctx->hw_frames_ctx);
1280 int ff_get_format(AVCodecContext *avctx, const enum AVPixelFormat *fmt)
1282 const AVPixFmtDescriptor *desc;
1283 enum AVPixelFormat *choices;
1284 enum AVPixelFormat ret, user_choice;
1285 const AVCodecHWConfigInternal *hw_config;
1286 const AVCodecHWConfig *config;
1289 // Find end of list.
1290 for (n = 0; fmt[n] != AV_PIX_FMT_NONE; n++);
1291 // Must contain at least one entry.
1293 // If a software format is available, it must be the last entry.
1294 desc = av_pix_fmt_desc_get(fmt[n - 1]);
1295 if (desc->flags & AV_PIX_FMT_FLAG_HWACCEL) {
1296 // No software format is available.
1298 avctx->sw_pix_fmt = fmt[n - 1];
1301 choices = av_malloc_array(n + 1, sizeof(*choices));
1303 return AV_PIX_FMT_NONE;
1305 memcpy(choices, fmt, (n + 1) * sizeof(*choices));
1308 // Remove the previous hwaccel, if there was one.
1309 hwaccel_uninit(avctx);
1311 user_choice = avctx->get_format(avctx, choices);
1312 if (user_choice == AV_PIX_FMT_NONE) {
1313 // Explicitly chose nothing, give up.
1314 ret = AV_PIX_FMT_NONE;
1318 desc = av_pix_fmt_desc_get(user_choice);
1320 av_log(avctx, AV_LOG_ERROR, "Invalid format returned by "
1321 "get_format() callback.\n");
1322 ret = AV_PIX_FMT_NONE;
1325 av_log(avctx, AV_LOG_DEBUG, "Format %s chosen by get_format().\n",
1328 for (i = 0; i < n; i++) {
1329 if (choices[i] == user_choice)
1333 av_log(avctx, AV_LOG_ERROR, "Invalid return from get_format(): "
1334 "%s not in possible list.\n", desc->name);
1335 ret = AV_PIX_FMT_NONE;
1339 if (avctx->codec->hw_configs) {
1341 hw_config = avctx->codec->hw_configs[i];
1344 if (hw_config->public.pix_fmt == user_choice)
1352 // No config available, so no extra setup required.
1356 config = &hw_config->public;
1358 if (config->methods &
1359 AV_CODEC_HW_CONFIG_METHOD_HW_FRAMES_CTX &&
1360 avctx->hw_frames_ctx) {
1361 const AVHWFramesContext *frames_ctx =
1362 (AVHWFramesContext*)avctx->hw_frames_ctx->data;
1363 if (frames_ctx->format != user_choice) {
1364 av_log(avctx, AV_LOG_ERROR, "Invalid setup for format %s: "
1365 "does not match the format of the provided frames "
1366 "context.\n", desc->name);
1369 } else if (config->methods &
1370 AV_CODEC_HW_CONFIG_METHOD_HW_DEVICE_CTX &&
1371 avctx->hw_device_ctx) {
1372 const AVHWDeviceContext *device_ctx =
1373 (AVHWDeviceContext*)avctx->hw_device_ctx->data;
1374 if (device_ctx->type != config->device_type) {
1375 av_log(avctx, AV_LOG_ERROR, "Invalid setup for format %s: "
1376 "does not match the type of the provided device "
1377 "context.\n", desc->name);
1380 } else if (config->methods &
1381 AV_CODEC_HW_CONFIG_METHOD_INTERNAL) {
1382 // Internal-only setup, no additional configuration.
1383 } else if (config->methods &
1384 AV_CODEC_HW_CONFIG_METHOD_AD_HOC) {
1385 // Some ad-hoc configuration we can't see and can't check.
1387 av_log(avctx, AV_LOG_ERROR, "Invalid setup for format %s: "
1388 "missing configuration.\n", desc->name);
1391 if (hw_config->hwaccel) {
1392 av_log(avctx, AV_LOG_DEBUG, "Format %s requires hwaccel "
1393 "initialisation.\n", desc->name);
1394 err = hwaccel_init(avctx, hw_config);
1402 av_log(avctx, AV_LOG_DEBUG, "Format %s not usable, retrying "
1403 "get_format() without it.\n", desc->name);
1404 for (i = 0; i < n; i++) {
1405 if (choices[i] == user_choice)
1408 for (; i + 1 < n; i++)
1409 choices[i] = choices[i + 1];
1417 static void frame_pool_free(void *opaque, uint8_t *data)
1419 FramePool *pool = (FramePool*)data;
1422 for (i = 0; i < FF_ARRAY_ELEMS(pool->pools); i++)
1423 av_buffer_pool_uninit(&pool->pools[i]);
1428 static AVBufferRef *frame_pool_alloc(void)
1430 FramePool *pool = av_mallocz(sizeof(*pool));
1436 buf = av_buffer_create((uint8_t*)pool, sizeof(*pool),
1437 frame_pool_free, NULL, 0);
1446 static int update_frame_pool(AVCodecContext *avctx, AVFrame *frame)
1448 FramePool *pool = avctx->internal->pool ?
1449 (FramePool*)avctx->internal->pool->data : NULL;
1450 AVBufferRef *pool_buf;
1451 int i, ret, ch, planes;
1453 if (avctx->codec_type == AVMEDIA_TYPE_AUDIO) {
1454 int planar = av_sample_fmt_is_planar(frame->format);
1455 ch = frame->channels;
1456 planes = planar ? ch : 1;
1459 if (pool && pool->format == frame->format) {
1460 if (avctx->codec_type == AVMEDIA_TYPE_VIDEO &&
1461 pool->width == frame->width && pool->height == frame->height)
1463 if (avctx->codec_type == AVMEDIA_TYPE_AUDIO && pool->planes == planes &&
1464 pool->channels == ch && frame->nb_samples == pool->samples)
1468 pool_buf = frame_pool_alloc();
1470 return AVERROR(ENOMEM);
1471 pool = (FramePool*)pool_buf->data;
1473 switch (avctx->codec_type) {
1474 case AVMEDIA_TYPE_VIDEO: {
1477 int size[4] = { 0 };
1478 int w = frame->width;
1479 int h = frame->height;
1480 int tmpsize, unaligned;
1482 avcodec_align_dimensions2(avctx, &w, &h, pool->stride_align);
1485 // NOTE: do not align linesizes individually, this breaks e.g. assumptions
1486 // that linesize[0] == 2*linesize[1] in the MPEG-encoder for 4:2:2
1487 ret = av_image_fill_linesizes(linesize, avctx->pix_fmt, w);
1490 // increase alignment of w for next try (rhs gives the lowest bit set in w)
1494 for (i = 0; i < 4; i++)
1495 unaligned |= linesize[i] % pool->stride_align[i];
1496 } while (unaligned);
1498 tmpsize = av_image_fill_pointers(data, avctx->pix_fmt, h,
1505 for (i = 0; i < 3 && data[i + 1]; i++)
1506 size[i] = data[i + 1] - data[i];
1507 size[i] = tmpsize - (data[i] - data[0]);
1509 for (i = 0; i < 4; i++) {
1510 pool->linesize[i] = linesize[i];
1512 pool->pools[i] = av_buffer_pool_init(size[i] + 16 + STRIDE_ALIGN - 1,
1513 CONFIG_MEMORY_POISONING ?
1516 if (!pool->pools[i]) {
1517 ret = AVERROR(ENOMEM);
1522 pool->format = frame->format;
1523 pool->width = frame->width;
1524 pool->height = frame->height;
1528 case AVMEDIA_TYPE_AUDIO: {
1529 ret = av_samples_get_buffer_size(&pool->linesize[0], ch,
1530 frame->nb_samples, frame->format, 0);
1534 pool->pools[0] = av_buffer_pool_init(pool->linesize[0], NULL);
1535 if (!pool->pools[0]) {
1536 ret = AVERROR(ENOMEM);
1540 pool->format = frame->format;
1541 pool->planes = planes;
1542 pool->channels = ch;
1543 pool->samples = frame->nb_samples;
1546 default: av_assert0(0);
1549 av_buffer_unref(&avctx->internal->pool);
1550 avctx->internal->pool = pool_buf;
1554 av_buffer_unref(&pool_buf);
1558 static int audio_get_buffer(AVCodecContext *avctx, AVFrame *frame)
1560 FramePool *pool = (FramePool*)avctx->internal->pool->data;
1561 int planes = pool->planes;
1564 frame->linesize[0] = pool->linesize[0];
1566 if (planes > AV_NUM_DATA_POINTERS) {
1567 frame->extended_data = av_mallocz_array(planes, sizeof(*frame->extended_data));
1568 frame->nb_extended_buf = planes - AV_NUM_DATA_POINTERS;
1569 frame->extended_buf = av_mallocz_array(frame->nb_extended_buf,
1570 sizeof(*frame->extended_buf));
1571 if (!frame->extended_data || !frame->extended_buf) {
1572 av_freep(&frame->extended_data);
1573 av_freep(&frame->extended_buf);
1574 return AVERROR(ENOMEM);
1577 frame->extended_data = frame->data;
1578 av_assert0(frame->nb_extended_buf == 0);
1581 for (i = 0; i < FFMIN(planes, AV_NUM_DATA_POINTERS); i++) {
1582 frame->buf[i] = av_buffer_pool_get(pool->pools[0]);
1585 frame->extended_data[i] = frame->data[i] = frame->buf[i]->data;
1587 for (i = 0; i < frame->nb_extended_buf; i++) {
1588 frame->extended_buf[i] = av_buffer_pool_get(pool->pools[0]);
1589 if (!frame->extended_buf[i])
1591 frame->extended_data[i + AV_NUM_DATA_POINTERS] = frame->extended_buf[i]->data;
1594 if (avctx->debug & FF_DEBUG_BUFFERS)
1595 av_log(avctx, AV_LOG_DEBUG, "default_get_buffer called on frame %p", frame);
1599 av_frame_unref(frame);
1600 return AVERROR(ENOMEM);
1603 static int video_get_buffer(AVCodecContext *s, AVFrame *pic)
1605 FramePool *pool = (FramePool*)s->internal->pool->data;
1606 const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(pic->format);
1609 if (pic->data[0] || pic->data[1] || pic->data[2] || pic->data[3]) {
1610 av_log(s, AV_LOG_ERROR, "pic->data[*]!=NULL in avcodec_default_get_buffer\n");
1615 av_log(s, AV_LOG_ERROR,
1616 "Unable to get pixel format descriptor for format %s\n",
1617 av_get_pix_fmt_name(pic->format));
1618 return AVERROR(EINVAL);
1621 memset(pic->data, 0, sizeof(pic->data));
1622 pic->extended_data = pic->data;
1624 for (i = 0; i < 4 && pool->pools[i]; i++) {
1625 pic->linesize[i] = pool->linesize[i];
1627 pic->buf[i] = av_buffer_pool_get(pool->pools[i]);
1631 pic->data[i] = pic->buf[i]->data;
1633 for (; i < AV_NUM_DATA_POINTERS; i++) {
1634 pic->data[i] = NULL;
1635 pic->linesize[i] = 0;
1637 if (desc->flags & AV_PIX_FMT_FLAG_PAL ||
1638 ((desc->flags & FF_PSEUDOPAL) && pic->data[1]))
1639 avpriv_set_systematic_pal2((uint32_t *)pic->data[1], pic->format);
1641 if (s->debug & FF_DEBUG_BUFFERS)
1642 av_log(s, AV_LOG_DEBUG, "default_get_buffer called on pic %p\n", pic);
1646 av_frame_unref(pic);
1647 return AVERROR(ENOMEM);
1650 int avcodec_default_get_buffer2(AVCodecContext *avctx, AVFrame *frame, int flags)
1654 if (avctx->hw_frames_ctx) {
1655 ret = av_hwframe_get_buffer(avctx->hw_frames_ctx, frame, 0);
1656 frame->width = avctx->coded_width;
1657 frame->height = avctx->coded_height;
1661 if ((ret = update_frame_pool(avctx, frame)) < 0)
1664 switch (avctx->codec_type) {
1665 case AVMEDIA_TYPE_VIDEO:
1666 return video_get_buffer(avctx, frame);
1667 case AVMEDIA_TYPE_AUDIO:
1668 return audio_get_buffer(avctx, frame);
1674 static int add_metadata_from_side_data(const AVPacket *avpkt, AVFrame *frame)
1677 const uint8_t *side_metadata;
1679 AVDictionary **frame_md = &frame->metadata;
1681 side_metadata = av_packet_get_side_data(avpkt,
1682 AV_PKT_DATA_STRINGS_METADATA, &size);
1683 return av_packet_unpack_dictionary(side_metadata, size, frame_md);
1686 int ff_decode_frame_props(AVCodecContext *avctx, AVFrame *frame)
1688 const AVPacket *pkt = avctx->internal->last_pkt_props;
1690 static const struct {
1691 enum AVPacketSideDataType packet;
1692 enum AVFrameSideDataType frame;
1694 { AV_PKT_DATA_REPLAYGAIN , AV_FRAME_DATA_REPLAYGAIN },
1695 { AV_PKT_DATA_DISPLAYMATRIX, AV_FRAME_DATA_DISPLAYMATRIX },
1696 { AV_PKT_DATA_SPHERICAL, AV_FRAME_DATA_SPHERICAL },
1697 { AV_PKT_DATA_STEREO3D, AV_FRAME_DATA_STEREO3D },
1698 { AV_PKT_DATA_AUDIO_SERVICE_TYPE, AV_FRAME_DATA_AUDIO_SERVICE_TYPE },
1699 { AV_PKT_DATA_MASTERING_DISPLAY_METADATA, AV_FRAME_DATA_MASTERING_DISPLAY_METADATA },
1700 { AV_PKT_DATA_CONTENT_LIGHT_LEVEL, AV_FRAME_DATA_CONTENT_LIGHT_LEVEL },
1701 { AV_PKT_DATA_A53_CC, AV_FRAME_DATA_A53_CC },
1702 { AV_PKT_DATA_ICC_PROFILE, AV_FRAME_DATA_ICC_PROFILE },
1706 frame->pts = pkt->pts;
1708 FF_DISABLE_DEPRECATION_WARNINGS
1709 frame->pkt_pts = pkt->pts;
1710 FF_ENABLE_DEPRECATION_WARNINGS
1712 frame->pkt_pos = pkt->pos;
1713 frame->pkt_duration = pkt->duration;
1714 frame->pkt_size = pkt->size;
1716 for (i = 0; i < FF_ARRAY_ELEMS(sd); i++) {
1718 uint8_t *packet_sd = av_packet_get_side_data(pkt, sd[i].packet, &size);
1720 AVFrameSideData *frame_sd = av_frame_new_side_data(frame,
1724 return AVERROR(ENOMEM);
1726 memcpy(frame_sd->data, packet_sd, size);
1729 add_metadata_from_side_data(pkt, frame);
1731 if (pkt->flags & AV_PKT_FLAG_DISCARD) {
1732 frame->flags |= AV_FRAME_FLAG_DISCARD;
1734 frame->flags = (frame->flags & ~AV_FRAME_FLAG_DISCARD);
1737 frame->reordered_opaque = avctx->reordered_opaque;
1739 if (frame->color_primaries == AVCOL_PRI_UNSPECIFIED)
1740 frame->color_primaries = avctx->color_primaries;
1741 if (frame->color_trc == AVCOL_TRC_UNSPECIFIED)
1742 frame->color_trc = avctx->color_trc;
1743 if (frame->colorspace == AVCOL_SPC_UNSPECIFIED)
1744 frame->colorspace = avctx->colorspace;
1745 if (frame->color_range == AVCOL_RANGE_UNSPECIFIED)
1746 frame->color_range = avctx->color_range;
1747 if (frame->chroma_location == AVCHROMA_LOC_UNSPECIFIED)
1748 frame->chroma_location = avctx->chroma_sample_location;
1750 switch (avctx->codec->type) {
1751 case AVMEDIA_TYPE_VIDEO:
1752 frame->format = avctx->pix_fmt;
1753 if (!frame->sample_aspect_ratio.num)
1754 frame->sample_aspect_ratio = avctx->sample_aspect_ratio;
1756 if (frame->width && frame->height &&
1757 av_image_check_sar(frame->width, frame->height,
1758 frame->sample_aspect_ratio) < 0) {
1759 av_log(avctx, AV_LOG_WARNING, "ignoring invalid SAR: %u/%u\n",
1760 frame->sample_aspect_ratio.num,
1761 frame->sample_aspect_ratio.den);
1762 frame->sample_aspect_ratio = (AVRational){ 0, 1 };
1766 case AVMEDIA_TYPE_AUDIO:
1767 if (!frame->sample_rate)
1768 frame->sample_rate = avctx->sample_rate;
1769 if (frame->format < 0)
1770 frame->format = avctx->sample_fmt;
1771 if (!frame->channel_layout) {
1772 if (avctx->channel_layout) {
1773 if (av_get_channel_layout_nb_channels(avctx->channel_layout) !=
1775 av_log(avctx, AV_LOG_ERROR, "Inconsistent channel "
1776 "configuration.\n");
1777 return AVERROR(EINVAL);
1780 frame->channel_layout = avctx->channel_layout;
1782 if (avctx->channels > FF_SANE_NB_CHANNELS) {
1783 av_log(avctx, AV_LOG_ERROR, "Too many channels: %d.\n",
1785 return AVERROR(ENOSYS);
1789 frame->channels = avctx->channels;
1795 static void validate_avframe_allocation(AVCodecContext *avctx, AVFrame *frame)
1797 if (avctx->codec_type == AVMEDIA_TYPE_VIDEO) {
1799 int num_planes = av_pix_fmt_count_planes(frame->format);
1800 const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(frame->format);
1801 int flags = desc ? desc->flags : 0;
1802 if (num_planes == 1 && (flags & AV_PIX_FMT_FLAG_PAL))
1804 if ((flags & FF_PSEUDOPAL) && frame->data[1])
1806 for (i = 0; i < num_planes; i++) {
1807 av_assert0(frame->data[i]);
1809 // For formats without data like hwaccel allow unused pointers to be non-NULL.
1810 for (i = num_planes; num_planes > 0 && i < FF_ARRAY_ELEMS(frame->data); i++) {
1812 av_log(avctx, AV_LOG_ERROR, "Buffer returned by get_buffer2() did not zero unused plane pointers\n");
1813 frame->data[i] = NULL;
1818 static void decode_data_free(void *opaque, uint8_t *data)
1820 FrameDecodeData *fdd = (FrameDecodeData*)data;
1822 if (fdd->post_process_opaque_free)
1823 fdd->post_process_opaque_free(fdd->post_process_opaque);
1825 if (fdd->hwaccel_priv_free)
1826 fdd->hwaccel_priv_free(fdd->hwaccel_priv);
1831 int ff_attach_decode_data(AVFrame *frame)
1833 AVBufferRef *fdd_buf;
1834 FrameDecodeData *fdd;
1836 av_assert1(!frame->private_ref);
1837 av_buffer_unref(&frame->private_ref);
1839 fdd = av_mallocz(sizeof(*fdd));
1841 return AVERROR(ENOMEM);
1843 fdd_buf = av_buffer_create((uint8_t*)fdd, sizeof(*fdd), decode_data_free,
1844 NULL, AV_BUFFER_FLAG_READONLY);
1847 return AVERROR(ENOMEM);
1850 frame->private_ref = fdd_buf;
1855 int ff_get_buffer(AVCodecContext *avctx, AVFrame *frame, int flags)
1857 const AVHWAccel *hwaccel = avctx->hwaccel;
1858 int override_dimensions = 1;
1861 if (avctx->codec_type == AVMEDIA_TYPE_VIDEO) {
1862 if ((ret = av_image_check_size2(FFALIGN(avctx->width, STRIDE_ALIGN), avctx->height, avctx->max_pixels, AV_PIX_FMT_NONE, 0, avctx)) < 0 || avctx->pix_fmt<0) {
1863 av_log(avctx, AV_LOG_ERROR, "video_get_buffer: image parameters invalid\n");
1864 ret = AVERROR(EINVAL);
1868 if (frame->width <= 0 || frame->height <= 0) {
1869 frame->width = FFMAX(avctx->width, AV_CEIL_RSHIFT(avctx->coded_width, avctx->lowres));
1870 frame->height = FFMAX(avctx->height, AV_CEIL_RSHIFT(avctx->coded_height, avctx->lowres));
1871 override_dimensions = 0;
1874 if (frame->data[0] || frame->data[1] || frame->data[2] || frame->data[3]) {
1875 av_log(avctx, AV_LOG_ERROR, "pic->data[*]!=NULL in get_buffer_internal\n");
1876 ret = AVERROR(EINVAL);
1879 } else if (avctx->codec_type == AVMEDIA_TYPE_AUDIO) {
1880 if (frame->nb_samples * (int64_t)avctx->channels > avctx->max_samples) {
1881 av_log(avctx, AV_LOG_ERROR, "samples per frame %d, exceeds max_samples %"PRId64"\n", frame->nb_samples, avctx->max_samples);
1882 ret = AVERROR(EINVAL);
1886 ret = ff_decode_frame_props(avctx, frame);
1891 if (hwaccel->alloc_frame) {
1892 ret = hwaccel->alloc_frame(avctx, frame);
1896 avctx->sw_pix_fmt = avctx->pix_fmt;
1898 ret = avctx->get_buffer2(avctx, frame, flags);
1902 validate_avframe_allocation(avctx, frame);
1904 ret = ff_attach_decode_data(frame);
1908 if (avctx->codec_type == AVMEDIA_TYPE_VIDEO && !override_dimensions &&
1909 !(avctx->codec->caps_internal & FF_CODEC_CAP_EXPORTS_CROPPING)) {
1910 frame->width = avctx->width;
1911 frame->height = avctx->height;
1916 av_log(avctx, AV_LOG_ERROR, "get_buffer() failed\n");
1917 av_frame_unref(frame);
1921 static int reget_buffer_internal(AVCodecContext *avctx, AVFrame *frame, int flags)
1926 av_assert0(avctx->codec_type == AVMEDIA_TYPE_VIDEO);
1928 if (frame->data[0] && (frame->width != avctx->width || frame->height != avctx->height || frame->format != avctx->pix_fmt)) {
1929 av_log(avctx, AV_LOG_WARNING, "Picture changed from size:%dx%d fmt:%s to size:%dx%d fmt:%s in reget buffer()\n",
1930 frame->width, frame->height, av_get_pix_fmt_name(frame->format), avctx->width, avctx->height, av_get_pix_fmt_name(avctx->pix_fmt));
1931 av_frame_unref(frame);
1934 if (!frame->data[0])
1935 return ff_get_buffer(avctx, frame, AV_GET_BUFFER_FLAG_REF);
1937 if ((flags & FF_REGET_BUFFER_FLAG_READONLY) || av_frame_is_writable(frame))
1938 return ff_decode_frame_props(avctx, frame);
1940 tmp = av_frame_alloc();
1942 return AVERROR(ENOMEM);
1944 av_frame_move_ref(tmp, frame);
1946 ret = ff_get_buffer(avctx, frame, AV_GET_BUFFER_FLAG_REF);
1948 av_frame_free(&tmp);
1952 av_frame_copy(frame, tmp);
1953 av_frame_free(&tmp);
1958 int ff_reget_buffer(AVCodecContext *avctx, AVFrame *frame, int flags)
1960 int ret = reget_buffer_internal(avctx, frame, flags);
1962 av_log(avctx, AV_LOG_ERROR, "reget_buffer() failed\n");
1966 void avcodec_flush_buffers(AVCodecContext *avctx)
1968 AVCodecInternal *avci = avctx->internal;
1970 if (av_codec_is_encoder(avctx->codec)) {
1971 int caps = avctx->codec->capabilities;
1973 if (!(caps & AV_CODEC_CAP_ENCODER_FLUSH)) {
1974 // Only encoders that explicitly declare support for it can be
1975 // flushed. Otherwise, this is a no-op.
1976 av_log(avctx, AV_LOG_WARNING, "Ignoring attempt to flush encoder "
1977 "that doesn't support it\n");
1981 // We haven't implemented flushing for frame-threaded encoders.
1982 av_assert0(!(caps & AV_CODEC_CAP_FRAME_THREADS));
1986 avci->draining_done = 0;
1987 avci->nb_draining_errors = 0;
1988 av_frame_unref(avci->buffer_frame);
1989 av_frame_unref(avci->compat_decode_frame);
1990 av_packet_unref(avci->buffer_pkt);
1991 avci->buffer_pkt_valid = 0;
1993 av_packet_unref(avci->ds.in_pkt);
1995 if (HAVE_THREADS && avctx->active_thread_type & FF_THREAD_FRAME)
1996 ff_thread_flush(avctx);
1997 else if (avctx->codec->flush)
1998 avctx->codec->flush(avctx);
2000 avctx->pts_correction_last_pts =
2001 avctx->pts_correction_last_dts = INT64_MIN;
2003 if (av_codec_is_decoder(avctx->codec))
2004 av_bsf_flush(avci->bsf);
2006 if (!avctx->refcounted_frames)
2007 av_frame_unref(avci->to_free);
2010 void ff_decode_bsfs_uninit(AVCodecContext *avctx)
2012 av_bsf_free(&avctx->internal->bsf);