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)
75 data = av_packet_get_side_data(avpkt, AV_PKT_DATA_PARAM_CHANGE, &size);
79 if (!(avctx->codec->capabilities & AV_CODEC_CAP_PARAM_CHANGE)) {
80 av_log(avctx, AV_LOG_ERROR, "This decoder does not support parameter "
81 "changes, but PARAM_CHANGE side data was sent to it.\n");
82 ret = AVERROR(EINVAL);
89 flags = bytestream_get_le32(&data);
92 if (flags & AV_SIDE_DATA_PARAM_CHANGE_CHANNEL_COUNT) {
95 val = bytestream_get_le32(&data);
96 if (val <= 0 || val > INT_MAX) {
97 av_log(avctx, AV_LOG_ERROR, "Invalid channel count");
98 ret = AVERROR_INVALIDDATA;
101 avctx->channels = val;
104 if (flags & AV_SIDE_DATA_PARAM_CHANGE_CHANNEL_LAYOUT) {
107 avctx->channel_layout = bytestream_get_le64(&data);
110 if (flags & AV_SIDE_DATA_PARAM_CHANGE_SAMPLE_RATE) {
113 val = bytestream_get_le32(&data);
114 if (val <= 0 || val > INT_MAX) {
115 av_log(avctx, AV_LOG_ERROR, "Invalid sample rate");
116 ret = AVERROR_INVALIDDATA;
119 avctx->sample_rate = val;
122 if (flags & AV_SIDE_DATA_PARAM_CHANGE_DIMENSIONS) {
125 avctx->width = bytestream_get_le32(&data);
126 avctx->height = bytestream_get_le32(&data);
128 ret = ff_set_dimensions(avctx, avctx->width, avctx->height);
135 av_log(avctx, AV_LOG_ERROR, "PARAM_CHANGE side data too small.\n");
136 ret = AVERROR_INVALIDDATA;
139 av_log(avctx, AV_LOG_ERROR, "Error applying parameter changes.\n");
140 if (avctx->err_recognition & AV_EF_EXPLODE)
146 #define IS_EMPTY(pkt) (!(pkt)->data)
148 static int copy_packet_props(AVPacket *dst, const AVPacket *src)
150 int ret = av_packet_copy_props(dst, src);
154 dst->size = src->size; // HACK: Needed for ff_decode_frame_props().
155 dst->data = (void*)1; // HACK: Needed for IS_EMPTY().
160 static int extract_packet_props(AVCodecInternal *avci, const AVPacket *pkt)
162 AVPacket tmp = { 0 };
165 if (IS_EMPTY(avci->last_pkt_props)) {
166 if (av_fifo_size(avci->pkt_props) >= sizeof(*pkt)) {
167 av_fifo_generic_read(avci->pkt_props, avci->last_pkt_props,
168 sizeof(*avci->last_pkt_props), NULL);
170 return copy_packet_props(avci->last_pkt_props, pkt);
173 if (av_fifo_space(avci->pkt_props) < sizeof(*pkt)) {
174 ret = av_fifo_grow(avci->pkt_props, sizeof(*pkt));
179 ret = copy_packet_props(&tmp, pkt);
183 av_fifo_generic_write(avci->pkt_props, &tmp, sizeof(tmp), NULL);
188 int ff_decode_bsfs_init(AVCodecContext *avctx)
190 AVCodecInternal *avci = avctx->internal;
196 ret = av_bsf_list_parse_str(avctx->codec->bsfs, &avci->bsf);
198 av_log(avctx, AV_LOG_ERROR, "Error parsing decoder bitstream filters '%s': %s\n", avctx->codec->bsfs, av_err2str(ret));
199 if (ret != AVERROR(ENOMEM))
204 /* We do not currently have an API for passing the input timebase into decoders,
205 * but no filters used here should actually need it.
206 * So we make up some plausible-looking number (the MPEG 90kHz timebase) */
207 avci->bsf->time_base_in = (AVRational){ 1, 90000 };
208 ret = avcodec_parameters_from_context(avci->bsf->par_in, avctx);
212 ret = av_bsf_init(avci->bsf);
218 av_bsf_free(&avci->bsf);
222 int ff_decode_get_packet(AVCodecContext *avctx, AVPacket *pkt)
224 AVCodecInternal *avci = avctx->internal;
230 ret = av_bsf_receive_packet(avci->bsf, pkt);
231 if (ret == AVERROR_EOF)
236 ret = extract_packet_props(avctx->internal, pkt);
240 ret = apply_param_change(avctx, pkt);
244 #if FF_API_OLD_ENCDEC
245 if (avctx->codec->receive_frame)
246 avci->compat_decode_consumed += pkt->size;
251 av_packet_unref(pkt);
256 * Attempt to guess proper monotonic timestamps for decoded video frames
257 * which might have incorrect times. Input timestamps may wrap around, in
258 * which case the output will as well.
260 * @param pts the pts field of the decoded AVPacket, as passed through
262 * @param dts the dts field of the decoded AVPacket
263 * @return one of the input values, may be AV_NOPTS_VALUE
265 static int64_t guess_correct_pts(AVCodecContext *ctx,
266 int64_t reordered_pts, int64_t dts)
268 int64_t pts = AV_NOPTS_VALUE;
270 if (dts != AV_NOPTS_VALUE) {
271 ctx->pts_correction_num_faulty_dts += dts <= ctx->pts_correction_last_dts;
272 ctx->pts_correction_last_dts = dts;
273 } else if (reordered_pts != AV_NOPTS_VALUE)
274 ctx->pts_correction_last_dts = reordered_pts;
276 if (reordered_pts != AV_NOPTS_VALUE) {
277 ctx->pts_correction_num_faulty_pts += reordered_pts <= ctx->pts_correction_last_pts;
278 ctx->pts_correction_last_pts = reordered_pts;
279 } else if(dts != AV_NOPTS_VALUE)
280 ctx->pts_correction_last_pts = dts;
282 if ((ctx->pts_correction_num_faulty_pts<=ctx->pts_correction_num_faulty_dts || dts == AV_NOPTS_VALUE)
283 && reordered_pts != AV_NOPTS_VALUE)
292 * The core of the receive_frame_wrapper for the decoders implementing
293 * the simple API. Certain decoders might consume partial packets without
294 * returning any output, so this function needs to be called in a loop until it
297 static inline int decode_simple_internal(AVCodecContext *avctx, AVFrame *frame, int64_t *discarded_samples)
299 AVCodecInternal *avci = avctx->internal;
300 DecodeSimpleContext *ds = &avci->ds;
301 AVPacket *pkt = ds->in_pkt;
302 // copy to ensure we do not change pkt
303 int got_frame, actual_got_frame;
306 if (!pkt->data && !avci->draining) {
307 av_packet_unref(pkt);
308 ret = ff_decode_get_packet(avctx, pkt);
309 if (ret < 0 && ret != AVERROR_EOF)
313 // Some codecs (at least wma lossless) will crash when feeding drain packets
314 // after EOF was signaled.
315 if (avci->draining_done)
319 !(avctx->codec->capabilities & AV_CODEC_CAP_DELAY ||
320 avctx->active_thread_type & FF_THREAD_FRAME))
325 if (HAVE_THREADS && avctx->active_thread_type & FF_THREAD_FRAME) {
326 ret = ff_thread_decode_frame(avctx, frame, &got_frame, pkt);
328 ret = avctx->codec->decode(avctx, frame, &got_frame, pkt);
330 if (!(avctx->codec->caps_internal & FF_CODEC_CAP_SETS_PKT_DTS))
331 frame->pkt_dts = pkt->dts;
332 if (avctx->codec->type == AVMEDIA_TYPE_VIDEO) {
333 if(!avctx->has_b_frames)
334 frame->pkt_pos = pkt->pos;
335 //FIXME these should be under if(!avctx->has_b_frames)
336 /* get_buffer is supposed to set frame parameters */
337 if (!(avctx->codec->capabilities & AV_CODEC_CAP_DR1)) {
338 if (!frame->sample_aspect_ratio.num) frame->sample_aspect_ratio = avctx->sample_aspect_ratio;
339 if (!frame->width) frame->width = avctx->width;
340 if (!frame->height) frame->height = avctx->height;
341 if (frame->format == AV_PIX_FMT_NONE) frame->format = avctx->pix_fmt;
346 actual_got_frame = got_frame;
348 if (avctx->codec->type == AVMEDIA_TYPE_VIDEO) {
349 if (frame->flags & AV_FRAME_FLAG_DISCARD)
351 } else if (avctx->codec->type == AVMEDIA_TYPE_AUDIO) {
353 buffer_size_t side_size;
354 uint32_t discard_padding = 0;
355 uint8_t skip_reason = 0;
356 uint8_t discard_reason = 0;
358 if (ret >= 0 && got_frame) {
359 if (frame->format == AV_SAMPLE_FMT_NONE)
360 frame->format = avctx->sample_fmt;
361 if (!frame->channel_layout)
362 frame->channel_layout = avctx->channel_layout;
363 if (!frame->channels)
364 frame->channels = avctx->channels;
365 if (!frame->sample_rate)
366 frame->sample_rate = avctx->sample_rate;
369 side= av_packet_get_side_data(avci->last_pkt_props, AV_PKT_DATA_SKIP_SAMPLES, &side_size);
370 if(side && side_size>=10) {
371 avci->skip_samples = AV_RL32(side) * avci->skip_samples_multiplier;
372 discard_padding = AV_RL32(side + 4);
373 av_log(avctx, AV_LOG_DEBUG, "skip %d / discard %d samples due to side data\n",
374 avci->skip_samples, (int)discard_padding);
375 skip_reason = AV_RL8(side + 8);
376 discard_reason = AV_RL8(side + 9);
379 if ((frame->flags & AV_FRAME_FLAG_DISCARD) && got_frame &&
380 !(avctx->flags2 & AV_CODEC_FLAG2_SKIP_MANUAL)) {
381 avci->skip_samples = FFMAX(0, avci->skip_samples - frame->nb_samples);
383 *discarded_samples += frame->nb_samples;
386 if (avci->skip_samples > 0 && got_frame &&
387 !(avctx->flags2 & AV_CODEC_FLAG2_SKIP_MANUAL)) {
388 if(frame->nb_samples <= avci->skip_samples){
390 *discarded_samples += frame->nb_samples;
391 avci->skip_samples -= frame->nb_samples;
392 av_log(avctx, AV_LOG_DEBUG, "skip whole frame, skip left: %d\n",
395 av_samples_copy(frame->extended_data, frame->extended_data, 0, avci->skip_samples,
396 frame->nb_samples - avci->skip_samples, avctx->channels, frame->format);
397 if(avctx->pkt_timebase.num && avctx->sample_rate) {
398 int64_t diff_ts = av_rescale_q(avci->skip_samples,
399 (AVRational){1, avctx->sample_rate},
400 avctx->pkt_timebase);
401 if(frame->pts!=AV_NOPTS_VALUE)
402 frame->pts += diff_ts;
404 FF_DISABLE_DEPRECATION_WARNINGS
405 if(frame->pkt_pts!=AV_NOPTS_VALUE)
406 frame->pkt_pts += diff_ts;
407 FF_ENABLE_DEPRECATION_WARNINGS
409 if(frame->pkt_dts!=AV_NOPTS_VALUE)
410 frame->pkt_dts += diff_ts;
411 if (frame->pkt_duration >= diff_ts)
412 frame->pkt_duration -= diff_ts;
414 av_log(avctx, AV_LOG_WARNING, "Could not update timestamps for skipped samples.\n");
416 av_log(avctx, AV_LOG_DEBUG, "skip %d/%d samples\n",
417 avci->skip_samples, frame->nb_samples);
418 *discarded_samples += avci->skip_samples;
419 frame->nb_samples -= avci->skip_samples;
420 avci->skip_samples = 0;
424 if (discard_padding > 0 && discard_padding <= frame->nb_samples && got_frame &&
425 !(avctx->flags2 & AV_CODEC_FLAG2_SKIP_MANUAL)) {
426 if (discard_padding == frame->nb_samples) {
427 *discarded_samples += frame->nb_samples;
430 if(avctx->pkt_timebase.num && avctx->sample_rate) {
431 int64_t diff_ts = av_rescale_q(frame->nb_samples - discard_padding,
432 (AVRational){1, avctx->sample_rate},
433 avctx->pkt_timebase);
434 frame->pkt_duration = diff_ts;
436 av_log(avctx, AV_LOG_WARNING, "Could not update timestamps for discarded samples.\n");
438 av_log(avctx, AV_LOG_DEBUG, "discard %d/%d samples\n",
439 (int)discard_padding, frame->nb_samples);
440 frame->nb_samples -= discard_padding;
444 if ((avctx->flags2 & AV_CODEC_FLAG2_SKIP_MANUAL) && got_frame) {
445 AVFrameSideData *fside = av_frame_new_side_data(frame, AV_FRAME_DATA_SKIP_SAMPLES, 10);
447 AV_WL32(fside->data, avci->skip_samples);
448 AV_WL32(fside->data + 4, discard_padding);
449 AV_WL8(fside->data + 8, skip_reason);
450 AV_WL8(fside->data + 9, discard_reason);
451 avci->skip_samples = 0;
456 if (avctx->codec->type == AVMEDIA_TYPE_AUDIO &&
457 !avci->showed_multi_packet_warning &&
458 ret >= 0 && ret != pkt->size && !(avctx->codec->capabilities & AV_CODEC_CAP_SUBFRAMES)) {
459 av_log(avctx, AV_LOG_WARNING, "Multiple frames in a packet.\n");
460 avci->showed_multi_packet_warning = 1;
464 av_frame_unref(frame);
466 if (ret >= 0 && avctx->codec->type == AVMEDIA_TYPE_VIDEO && !(avctx->flags & AV_CODEC_FLAG_TRUNCATED))
469 #if FF_API_AVCTX_TIMEBASE
470 if (avctx->framerate.num > 0 && avctx->framerate.den > 0)
471 avctx->time_base = av_inv_q(av_mul_q(avctx->framerate, (AVRational){avctx->ticks_per_frame, 1}));
474 /* do not stop draining when actual_got_frame != 0 or ret < 0 */
475 /* got_frame == 0 but actual_got_frame != 0 when frame is discarded */
476 if (avci->draining && !actual_got_frame) {
478 /* prevent infinite loop if a decoder wrongly always return error on draining */
479 /* reasonable nb_errors_max = maximum b frames + thread count */
480 int nb_errors_max = 20 + (HAVE_THREADS && avctx->active_thread_type & FF_THREAD_FRAME ?
481 avctx->thread_count : 1);
483 if (avci->nb_draining_errors++ >= nb_errors_max) {
484 av_log(avctx, AV_LOG_ERROR, "Too many errors when draining, this is a bug. "
485 "Stop draining and force EOF.\n");
486 avci->draining_done = 1;
490 avci->draining_done = 1;
494 #if FF_API_OLD_ENCDEC
495 avci->compat_decode_consumed += ret;
498 if (ret >= pkt->size || ret < 0) {
499 av_packet_unref(pkt);
500 av_packet_unref(avci->last_pkt_props);
504 pkt->data += consumed;
505 pkt->size -= consumed;
506 avci->last_pkt_props->size -= consumed; // See extract_packet_props() comment.
507 pkt->pts = AV_NOPTS_VALUE;
508 pkt->dts = AV_NOPTS_VALUE;
509 avci->last_pkt_props->pts = AV_NOPTS_VALUE;
510 avci->last_pkt_props->dts = AV_NOPTS_VALUE;
514 av_assert0(frame->buf[0]);
516 return ret < 0 ? ret : 0;
519 static int decode_simple_receive_frame(AVCodecContext *avctx, AVFrame *frame)
522 int64_t discarded_samples = 0;
524 while (!frame->buf[0]) {
525 if (discarded_samples > avctx->max_samples)
526 return AVERROR(EAGAIN);
527 ret = decode_simple_internal(avctx, frame, &discarded_samples);
535 static int decode_receive_frame_internal(AVCodecContext *avctx, AVFrame *frame)
537 AVCodecInternal *avci = avctx->internal;
540 av_assert0(!frame->buf[0]);
542 if (avctx->codec->receive_frame) {
543 ret = avctx->codec->receive_frame(avctx, frame);
544 if (ret != AVERROR(EAGAIN))
545 av_packet_unref(avci->last_pkt_props);
547 ret = decode_simple_receive_frame(avctx, frame);
549 if (ret == AVERROR_EOF)
550 avci->draining_done = 1;
553 frame->best_effort_timestamp = guess_correct_pts(avctx,
557 /* the only case where decode data is not set should be decoders
558 * that do not call ff_get_buffer() */
559 av_assert0((frame->private_ref && frame->private_ref->size == sizeof(FrameDecodeData)) ||
560 !(avctx->codec->capabilities & AV_CODEC_CAP_DR1));
562 if (frame->private_ref) {
563 FrameDecodeData *fdd = (FrameDecodeData*)frame->private_ref->data;
565 if (fdd->post_process) {
566 ret = fdd->post_process(avctx, frame);
568 av_frame_unref(frame);
575 /* free the per-frame decode data */
576 av_buffer_unref(&frame->private_ref);
581 int attribute_align_arg avcodec_send_packet(AVCodecContext *avctx, const AVPacket *avpkt)
583 AVCodecInternal *avci = avctx->internal;
586 if (!avcodec_is_open(avctx) || !av_codec_is_decoder(avctx->codec))
587 return AVERROR(EINVAL);
589 if (avctx->internal->draining)
592 if (avpkt && !avpkt->size && avpkt->data)
593 return AVERROR(EINVAL);
595 av_packet_unref(avci->buffer_pkt);
596 if (avpkt && (avpkt->data || avpkt->side_data_elems)) {
597 ret = av_packet_ref(avci->buffer_pkt, avpkt);
602 ret = av_bsf_send_packet(avci->bsf, avci->buffer_pkt);
604 av_packet_unref(avci->buffer_pkt);
608 if (!avci->buffer_frame->buf[0]) {
609 ret = decode_receive_frame_internal(avctx, avci->buffer_frame);
610 if (ret < 0 && ret != AVERROR(EAGAIN) && ret != AVERROR_EOF)
617 static int apply_cropping(AVCodecContext *avctx, AVFrame *frame)
619 /* make sure we are noisy about decoders returning invalid cropping data */
620 if (frame->crop_left >= INT_MAX - frame->crop_right ||
621 frame->crop_top >= INT_MAX - frame->crop_bottom ||
622 (frame->crop_left + frame->crop_right) >= frame->width ||
623 (frame->crop_top + frame->crop_bottom) >= frame->height) {
624 av_log(avctx, AV_LOG_WARNING,
625 "Invalid cropping information set by a decoder: "
626 "%"SIZE_SPECIFIER"/%"SIZE_SPECIFIER"/%"SIZE_SPECIFIER"/%"SIZE_SPECIFIER" "
627 "(frame size %dx%d). This is a bug, please report it\n",
628 frame->crop_left, frame->crop_right, frame->crop_top, frame->crop_bottom,
629 frame->width, frame->height);
630 frame->crop_left = 0;
631 frame->crop_right = 0;
633 frame->crop_bottom = 0;
637 if (!avctx->apply_cropping)
640 return av_frame_apply_cropping(frame, avctx->flags & AV_CODEC_FLAG_UNALIGNED ?
641 AV_FRAME_CROP_UNALIGNED : 0);
644 int attribute_align_arg avcodec_receive_frame(AVCodecContext *avctx, AVFrame *frame)
646 AVCodecInternal *avci = avctx->internal;
649 av_frame_unref(frame);
651 if (!avcodec_is_open(avctx) || !av_codec_is_decoder(avctx->codec))
652 return AVERROR(EINVAL);
654 if (avci->buffer_frame->buf[0]) {
655 av_frame_move_ref(frame, avci->buffer_frame);
657 ret = decode_receive_frame_internal(avctx, frame);
662 if (avctx->codec_type == AVMEDIA_TYPE_VIDEO) {
663 ret = apply_cropping(avctx, frame);
665 av_frame_unref(frame);
670 avctx->frame_number++;
672 if (avctx->flags & AV_CODEC_FLAG_DROPCHANGED) {
674 if (avctx->frame_number == 1) {
675 avci->initial_format = frame->format;
676 switch(avctx->codec_type) {
677 case AVMEDIA_TYPE_VIDEO:
678 avci->initial_width = frame->width;
679 avci->initial_height = frame->height;
681 case AVMEDIA_TYPE_AUDIO:
682 avci->initial_sample_rate = frame->sample_rate ? frame->sample_rate :
684 avci->initial_channels = frame->channels;
685 avci->initial_channel_layout = frame->channel_layout;
690 if (avctx->frame_number > 1) {
691 changed = avci->initial_format != frame->format;
693 switch(avctx->codec_type) {
694 case AVMEDIA_TYPE_VIDEO:
695 changed |= avci->initial_width != frame->width ||
696 avci->initial_height != frame->height;
698 case AVMEDIA_TYPE_AUDIO:
699 changed |= avci->initial_sample_rate != frame->sample_rate ||
700 avci->initial_sample_rate != avctx->sample_rate ||
701 avci->initial_channels != frame->channels ||
702 avci->initial_channel_layout != frame->channel_layout;
707 avci->changed_frames_dropped++;
708 av_log(avctx, AV_LOG_INFO, "dropped changed frame #%d pts %"PRId64
709 " drop count: %d \n",
710 avctx->frame_number, frame->pts,
711 avci->changed_frames_dropped);
712 av_frame_unref(frame);
713 return AVERROR_INPUT_CHANGED;
720 #if FF_API_OLD_ENCDEC
721 FF_DISABLE_DEPRECATION_WARNINGS
722 static int unrefcount_frame(AVCodecInternal *avci, AVFrame *frame)
726 /* move the original frame to our backup */
727 av_frame_unref(avci->to_free);
728 av_frame_move_ref(avci->to_free, frame);
730 /* now copy everything except the AVBufferRefs back
731 * note that we make a COPY of the side data, so calling av_frame_free() on
732 * the caller's frame will work properly */
733 ret = av_frame_copy_props(frame, avci->to_free);
737 memcpy(frame->data, avci->to_free->data, sizeof(frame->data));
738 memcpy(frame->linesize, avci->to_free->linesize, sizeof(frame->linesize));
739 if (avci->to_free->extended_data != avci->to_free->data) {
740 int planes = avci->to_free->channels;
741 int size = planes * sizeof(*frame->extended_data);
744 av_frame_unref(frame);
748 frame->extended_data = av_malloc(size);
749 if (!frame->extended_data) {
750 av_frame_unref(frame);
751 return AVERROR(ENOMEM);
753 memcpy(frame->extended_data, avci->to_free->extended_data,
756 frame->extended_data = frame->data;
758 frame->format = avci->to_free->format;
759 frame->width = avci->to_free->width;
760 frame->height = avci->to_free->height;
761 frame->channel_layout = avci->to_free->channel_layout;
762 frame->nb_samples = avci->to_free->nb_samples;
763 frame->channels = avci->to_free->channels;
768 static int compat_decode(AVCodecContext *avctx, AVFrame *frame,
769 int *got_frame, const AVPacket *pkt)
771 AVCodecInternal *avci = avctx->internal;
774 av_assert0(avci->compat_decode_consumed == 0);
776 if (avci->draining_done && pkt && pkt->size != 0) {
777 av_log(avctx, AV_LOG_WARNING, "Got unexpected packet after EOF\n");
778 avcodec_flush_buffers(avctx);
783 if (avci->compat_decode_partial_size > 0 &&
784 avci->compat_decode_partial_size != pkt->size) {
785 av_log(avctx, AV_LOG_ERROR,
786 "Got unexpected packet size after a partial decode\n");
787 ret = AVERROR(EINVAL);
791 if (!avci->compat_decode_partial_size) {
792 ret = avcodec_send_packet(avctx, pkt);
793 if (ret == AVERROR_EOF)
795 else if (ret == AVERROR(EAGAIN)) {
796 /* we fully drain all the output in each decode call, so this should not
805 ret = avcodec_receive_frame(avctx, frame);
807 if (ret == AVERROR(EAGAIN) || ret == AVERROR_EOF)
812 if (frame != avci->compat_decode_frame) {
813 if (!avctx->refcounted_frames) {
814 ret = unrefcount_frame(avci, frame);
820 frame = avci->compat_decode_frame;
822 if (!avci->compat_decode_warned) {
823 av_log(avctx, AV_LOG_WARNING, "The deprecated avcodec_decode_* "
824 "API cannot return all the frames for this decoder. "
825 "Some frames will be dropped. Update your code to the "
826 "new decoding API to fix this.\n");
827 avci->compat_decode_warned = 1;
831 if (avci->draining || (!avctx->codec->bsfs && avci->compat_decode_consumed < pkt->size))
837 /* if there are any bsfs then assume full packet is always consumed */
838 if (avctx->codec->bsfs)
841 ret = FFMIN(avci->compat_decode_consumed, pkt->size);
843 avci->compat_decode_consumed = 0;
844 avci->compat_decode_partial_size = (ret >= 0) ? pkt->size - ret : 0;
849 int attribute_align_arg avcodec_decode_video2(AVCodecContext *avctx, AVFrame *picture,
850 int *got_picture_ptr,
851 const AVPacket *avpkt)
853 return compat_decode(avctx, picture, got_picture_ptr, avpkt);
856 int attribute_align_arg avcodec_decode_audio4(AVCodecContext *avctx,
859 const AVPacket *avpkt)
861 return compat_decode(avctx, frame, got_frame_ptr, avpkt);
863 FF_ENABLE_DEPRECATION_WARNINGS
866 static void get_subtitle_defaults(AVSubtitle *sub)
868 memset(sub, 0, sizeof(*sub));
869 sub->pts = AV_NOPTS_VALUE;
872 #define UTF8_MAX_BYTES 4 /* 5 and 6 bytes sequences should not be used */
873 static int recode_subtitle(AVCodecContext *avctx, AVPacket **outpkt,
874 AVPacket *inpkt, AVPacket *buf_pkt)
877 iconv_t cd = (iconv_t)-1;
883 if (avctx->sub_charenc_mode != FF_SUB_CHARENC_MODE_PRE_DECODER || inpkt->size == 0) {
892 if (inl >= INT_MAX / UTF8_MAX_BYTES - AV_INPUT_BUFFER_PADDING_SIZE) {
893 av_log(avctx, AV_LOG_ERROR, "Subtitles packet is too big for recoding\n");
894 return AVERROR(ERANGE);
897 cd = iconv_open("UTF-8", avctx->sub_charenc);
898 av_assert0(cd != (iconv_t)-1);
900 ret = av_new_packet(buf_pkt, inl * UTF8_MAX_BYTES);
903 ret = av_packet_copy_props(buf_pkt, inpkt);
906 outb = buf_pkt->data;
907 outl = buf_pkt->size;
909 if (iconv(cd, &inb, &inl, &outb, &outl) == (size_t)-1 ||
910 iconv(cd, NULL, NULL, &outb, &outl) == (size_t)-1 ||
911 outl >= buf_pkt->size || inl != 0) {
912 ret = FFMIN(AVERROR(errno), -1);
913 av_log(avctx, AV_LOG_ERROR, "Unable to recode subtitle event \"%s\" "
914 "from %s to UTF-8\n", inpkt->data, avctx->sub_charenc);
917 buf_pkt->size -= outl;
918 memset(buf_pkt->data + buf_pkt->size, 0, outl);
924 av_packet_unref(buf_pkt);
925 if (cd != (iconv_t)-1)
929 av_log(avctx, AV_LOG_ERROR, "requesting subtitles recoding without iconv");
930 return AVERROR(EINVAL);
934 static int utf8_check(const uint8_t *str)
937 uint32_t codepoint, min;
941 GET_UTF8(codepoint, *(byte++), return 0;);
942 min = byte - str == 1 ? 0 : byte - str == 2 ? 0x80 :
943 1 << (5 * (byte - str) - 4);
944 if (codepoint < min || codepoint >= 0x110000 ||
945 codepoint == 0xFFFE /* BOM */ ||
946 codepoint >= 0xD800 && codepoint <= 0xDFFF /* surrogates */)
953 #if FF_API_ASS_TIMING
954 static void insert_ts(AVBPrint *buf, int ts)
957 av_bprintf(buf, "9:59:59.99,");
961 h = ts/360000; ts -= 360000*h;
962 m = ts/ 6000; ts -= 6000*m;
963 s = ts/ 100; ts -= 100*s;
964 av_bprintf(buf, "%d:%02d:%02d.%02d,", h, m, s, ts);
968 static int convert_sub_to_old_ass_form(AVSubtitle *sub, const AVPacket *pkt, AVRational tb)
973 av_bprint_init(&buf, 0, AV_BPRINT_SIZE_UNLIMITED);
975 for (i = 0; i < sub->num_rects; i++) {
978 AVSubtitleRect *rect = sub->rects[i];
979 int ts_start, ts_duration = -1;
982 if (rect->type != SUBTITLE_ASS || !strncmp(rect->ass, "Dialogue: ", 10))
985 av_bprint_clear(&buf);
988 dialog = strchr(rect->ass, ',');
993 /* extract Layer or Marked */
994 layer = strtol(dialog, (char**)&dialog, 10);
999 /* rescale timing to ASS time base (ms) */
1000 ts_start = av_rescale_q(pkt->pts, tb, av_make_q(1, 100));
1001 if (pkt->duration != -1)
1002 ts_duration = av_rescale_q(pkt->duration, tb, av_make_q(1, 100));
1003 sub->end_display_time = FFMAX(sub->end_display_time, 10 * ts_duration);
1005 /* construct ASS (standalone file form with timestamps) string */
1006 av_bprintf(&buf, "Dialogue: %ld,", layer);
1007 insert_ts(&buf, ts_start);
1008 insert_ts(&buf, ts_duration == -1 ? -1 : ts_start + ts_duration);
1009 av_bprintf(&buf, "%s\r\n", dialog);
1011 final_dialog = av_strdup(buf.str);
1012 if (!av_bprint_is_complete(&buf) || !final_dialog) {
1013 av_freep(&final_dialog);
1014 av_bprint_finalize(&buf, NULL);
1015 return AVERROR(ENOMEM);
1017 av_freep(&rect->ass);
1018 rect->ass = final_dialog;
1021 av_bprint_finalize(&buf, NULL);
1026 int avcodec_decode_subtitle2(AVCodecContext *avctx, AVSubtitle *sub,
1032 if (!avpkt->data && avpkt->size) {
1033 av_log(avctx, AV_LOG_ERROR, "invalid packet: NULL data, size != 0\n");
1034 return AVERROR(EINVAL);
1037 return AVERROR(EINVAL);
1038 if (avctx->codec->type != AVMEDIA_TYPE_SUBTITLE) {
1039 av_log(avctx, AV_LOG_ERROR, "Invalid media type for subtitles\n");
1040 return AVERROR(EINVAL);
1044 get_subtitle_defaults(sub);
1046 if ((avctx->codec->capabilities & AV_CODEC_CAP_DELAY) || avpkt->size) {
1047 AVCodecInternal *avci = avctx->internal;
1050 ret = recode_subtitle(avctx, &pkt, avpkt, avci->buffer_pkt);
1054 if (avctx->pkt_timebase.num && avpkt->pts != AV_NOPTS_VALUE)
1055 sub->pts = av_rescale_q(avpkt->pts,
1056 avctx->pkt_timebase, AV_TIME_BASE_Q);
1057 ret = avctx->codec->decode(avctx, sub, got_sub_ptr, pkt);
1058 av_assert1((ret >= 0) >= !!*got_sub_ptr &&
1059 !!*got_sub_ptr >= !!sub->num_rects);
1061 #if FF_API_ASS_TIMING
1062 if (avctx->sub_text_format == FF_SUB_TEXT_FMT_ASS_WITH_TIMINGS
1063 && *got_sub_ptr && sub->num_rects) {
1064 const AVRational tb = avctx->pkt_timebase.num ? avctx->pkt_timebase
1066 int err = convert_sub_to_old_ass_form(sub, avpkt, tb);
1072 if (sub->num_rects && !sub->end_display_time && avpkt->duration &&
1073 avctx->pkt_timebase.num) {
1074 AVRational ms = { 1, 1000 };
1075 sub->end_display_time = av_rescale_q(avpkt->duration,
1076 avctx->pkt_timebase, ms);
1079 if (avctx->codec_descriptor->props & AV_CODEC_PROP_BITMAP_SUB)
1081 else if (avctx->codec_descriptor->props & AV_CODEC_PROP_TEXT_SUB)
1084 for (unsigned i = 0; i < sub->num_rects; i++) {
1085 if (avctx->sub_charenc_mode != FF_SUB_CHARENC_MODE_IGNORE &&
1086 sub->rects[i]->ass && !utf8_check(sub->rects[i]->ass)) {
1087 av_log(avctx, AV_LOG_ERROR,
1088 "Invalid UTF-8 in decoded subtitles text; "
1089 "maybe missing -sub_charenc option\n");
1090 avsubtitle_free(sub);
1091 ret = AVERROR_INVALIDDATA;
1097 avctx->frame_number++;
1099 if (pkt == avci->buffer_pkt) // did we recode?
1100 av_packet_unref(avci->buffer_pkt);
1106 enum AVPixelFormat avcodec_default_get_format(struct AVCodecContext *avctx,
1107 const enum AVPixelFormat *fmt)
1109 const AVPixFmtDescriptor *desc;
1110 const AVCodecHWConfig *config;
1113 // If a device was supplied when the codec was opened, assume that the
1114 // user wants to use it.
1115 if (avctx->hw_device_ctx && avctx->codec->hw_configs) {
1116 AVHWDeviceContext *device_ctx =
1117 (AVHWDeviceContext*)avctx->hw_device_ctx->data;
1119 config = &avctx->codec->hw_configs[i]->public;
1122 if (!(config->methods &
1123 AV_CODEC_HW_CONFIG_METHOD_HW_DEVICE_CTX))
1125 if (device_ctx->type != config->device_type)
1127 for (n = 0; fmt[n] != AV_PIX_FMT_NONE; n++) {
1128 if (config->pix_fmt == fmt[n])
1133 // No device or other setup, so we have to choose from things which
1134 // don't any other external information.
1136 // If the last element of the list is a software format, choose it
1137 // (this should be best software format if any exist).
1138 for (n = 0; fmt[n] != AV_PIX_FMT_NONE; n++);
1139 desc = av_pix_fmt_desc_get(fmt[n - 1]);
1140 if (!(desc->flags & AV_PIX_FMT_FLAG_HWACCEL))
1143 // Finally, traverse the list in order and choose the first entry
1144 // with no external dependencies (if there is no hardware configuration
1145 // information available then this just picks the first entry).
1146 for (n = 0; fmt[n] != AV_PIX_FMT_NONE; n++) {
1148 config = avcodec_get_hw_config(avctx->codec, i);
1151 if (config->pix_fmt == fmt[n])
1155 // No specific config available, so the decoder must be able
1156 // to handle this format without any additional setup.
1159 if (config->methods & AV_CODEC_HW_CONFIG_METHOD_INTERNAL) {
1160 // Usable with only internal setup.
1165 // Nothing is usable, give up.
1166 return AV_PIX_FMT_NONE;
1169 int ff_decode_get_hw_frames_ctx(AVCodecContext *avctx,
1170 enum AVHWDeviceType dev_type)
1172 AVHWDeviceContext *device_ctx;
1173 AVHWFramesContext *frames_ctx;
1176 if (!avctx->hwaccel)
1177 return AVERROR(ENOSYS);
1179 if (avctx->hw_frames_ctx)
1181 if (!avctx->hw_device_ctx) {
1182 av_log(avctx, AV_LOG_ERROR, "A hardware frames or device context is "
1183 "required for hardware accelerated decoding.\n");
1184 return AVERROR(EINVAL);
1187 device_ctx = (AVHWDeviceContext *)avctx->hw_device_ctx->data;
1188 if (device_ctx->type != dev_type) {
1189 av_log(avctx, AV_LOG_ERROR, "Device type %s expected for hardware "
1190 "decoding, but got %s.\n", av_hwdevice_get_type_name(dev_type),
1191 av_hwdevice_get_type_name(device_ctx->type));
1192 return AVERROR(EINVAL);
1195 ret = avcodec_get_hw_frames_parameters(avctx,
1196 avctx->hw_device_ctx,
1197 avctx->hwaccel->pix_fmt,
1198 &avctx->hw_frames_ctx);
1202 frames_ctx = (AVHWFramesContext*)avctx->hw_frames_ctx->data;
1205 if (frames_ctx->initial_pool_size) {
1206 // We guarantee 4 base work surfaces. The function above guarantees 1
1207 // (the absolute minimum), so add the missing count.
1208 frames_ctx->initial_pool_size += 3;
1211 ret = av_hwframe_ctx_init(avctx->hw_frames_ctx);
1213 av_buffer_unref(&avctx->hw_frames_ctx);
1220 int avcodec_get_hw_frames_parameters(AVCodecContext *avctx,
1221 AVBufferRef *device_ref,
1222 enum AVPixelFormat hw_pix_fmt,
1223 AVBufferRef **out_frames_ref)
1225 AVBufferRef *frames_ref = NULL;
1226 const AVCodecHWConfigInternal *hw_config;
1227 const AVHWAccel *hwa;
1231 hw_config = avctx->codec->hw_configs[i];
1233 return AVERROR(ENOENT);
1234 if (hw_config->public.pix_fmt == hw_pix_fmt)
1238 hwa = hw_config->hwaccel;
1239 if (!hwa || !hwa->frame_params)
1240 return AVERROR(ENOENT);
1242 frames_ref = av_hwframe_ctx_alloc(device_ref);
1244 return AVERROR(ENOMEM);
1246 ret = hwa->frame_params(avctx, frames_ref);
1248 AVHWFramesContext *frames_ctx = (AVHWFramesContext*)frames_ref->data;
1250 if (frames_ctx->initial_pool_size) {
1251 // If the user has requested that extra output surfaces be
1252 // available then add them here.
1253 if (avctx->extra_hw_frames > 0)
1254 frames_ctx->initial_pool_size += avctx->extra_hw_frames;
1256 // If frame threading is enabled then an extra surface per thread
1257 // is also required.
1258 if (avctx->active_thread_type & FF_THREAD_FRAME)
1259 frames_ctx->initial_pool_size += avctx->thread_count;
1262 *out_frames_ref = frames_ref;
1264 av_buffer_unref(&frames_ref);
1269 static int hwaccel_init(AVCodecContext *avctx,
1270 const AVCodecHWConfigInternal *hw_config)
1272 const AVHWAccel *hwaccel;
1275 hwaccel = hw_config->hwaccel;
1276 if (hwaccel->capabilities & AV_HWACCEL_CODEC_CAP_EXPERIMENTAL &&
1277 avctx->strict_std_compliance > FF_COMPLIANCE_EXPERIMENTAL) {
1278 av_log(avctx, AV_LOG_WARNING, "Ignoring experimental hwaccel: %s\n",
1280 return AVERROR_PATCHWELCOME;
1283 if (hwaccel->priv_data_size) {
1284 avctx->internal->hwaccel_priv_data =
1285 av_mallocz(hwaccel->priv_data_size);
1286 if (!avctx->internal->hwaccel_priv_data)
1287 return AVERROR(ENOMEM);
1290 avctx->hwaccel = hwaccel;
1291 if (hwaccel->init) {
1292 err = hwaccel->init(avctx);
1294 av_log(avctx, AV_LOG_ERROR, "Failed setup for format %s: "
1295 "hwaccel initialisation returned error.\n",
1296 av_get_pix_fmt_name(hw_config->public.pix_fmt));
1297 av_freep(&avctx->internal->hwaccel_priv_data);
1298 avctx->hwaccel = NULL;
1306 static void hwaccel_uninit(AVCodecContext *avctx)
1308 if (avctx->hwaccel && avctx->hwaccel->uninit)
1309 avctx->hwaccel->uninit(avctx);
1311 av_freep(&avctx->internal->hwaccel_priv_data);
1313 avctx->hwaccel = NULL;
1315 av_buffer_unref(&avctx->hw_frames_ctx);
1318 int ff_get_format(AVCodecContext *avctx, const enum AVPixelFormat *fmt)
1320 const AVPixFmtDescriptor *desc;
1321 enum AVPixelFormat *choices;
1322 enum AVPixelFormat ret, user_choice;
1323 const AVCodecHWConfigInternal *hw_config;
1324 const AVCodecHWConfig *config;
1327 // Find end of list.
1328 for (n = 0; fmt[n] != AV_PIX_FMT_NONE; n++);
1329 // Must contain at least one entry.
1331 // If a software format is available, it must be the last entry.
1332 desc = av_pix_fmt_desc_get(fmt[n - 1]);
1333 if (desc->flags & AV_PIX_FMT_FLAG_HWACCEL) {
1334 // No software format is available.
1336 avctx->sw_pix_fmt = fmt[n - 1];
1339 choices = av_malloc_array(n + 1, sizeof(*choices));
1341 return AV_PIX_FMT_NONE;
1343 memcpy(choices, fmt, (n + 1) * sizeof(*choices));
1346 // Remove the previous hwaccel, if there was one.
1347 hwaccel_uninit(avctx);
1349 user_choice = avctx->get_format(avctx, choices);
1350 if (user_choice == AV_PIX_FMT_NONE) {
1351 // Explicitly chose nothing, give up.
1352 ret = AV_PIX_FMT_NONE;
1356 desc = av_pix_fmt_desc_get(user_choice);
1358 av_log(avctx, AV_LOG_ERROR, "Invalid format returned by "
1359 "get_format() callback.\n");
1360 ret = AV_PIX_FMT_NONE;
1363 av_log(avctx, AV_LOG_DEBUG, "Format %s chosen by get_format().\n",
1366 for (i = 0; i < n; i++) {
1367 if (choices[i] == user_choice)
1371 av_log(avctx, AV_LOG_ERROR, "Invalid return from get_format(): "
1372 "%s not in possible list.\n", desc->name);
1373 ret = AV_PIX_FMT_NONE;
1377 if (avctx->codec->hw_configs) {
1379 hw_config = avctx->codec->hw_configs[i];
1382 if (hw_config->public.pix_fmt == user_choice)
1390 // No config available, so no extra setup required.
1394 config = &hw_config->public;
1396 if (config->methods &
1397 AV_CODEC_HW_CONFIG_METHOD_HW_FRAMES_CTX &&
1398 avctx->hw_frames_ctx) {
1399 const AVHWFramesContext *frames_ctx =
1400 (AVHWFramesContext*)avctx->hw_frames_ctx->data;
1401 if (frames_ctx->format != user_choice) {
1402 av_log(avctx, AV_LOG_ERROR, "Invalid setup for format %s: "
1403 "does not match the format of the provided frames "
1404 "context.\n", desc->name);
1407 } else if (config->methods &
1408 AV_CODEC_HW_CONFIG_METHOD_HW_DEVICE_CTX &&
1409 avctx->hw_device_ctx) {
1410 const AVHWDeviceContext *device_ctx =
1411 (AVHWDeviceContext*)avctx->hw_device_ctx->data;
1412 if (device_ctx->type != config->device_type) {
1413 av_log(avctx, AV_LOG_ERROR, "Invalid setup for format %s: "
1414 "does not match the type of the provided device "
1415 "context.\n", desc->name);
1418 } else if (config->methods &
1419 AV_CODEC_HW_CONFIG_METHOD_INTERNAL) {
1420 // Internal-only setup, no additional configuration.
1421 } else if (config->methods &
1422 AV_CODEC_HW_CONFIG_METHOD_AD_HOC) {
1423 // Some ad-hoc configuration we can't see and can't check.
1425 av_log(avctx, AV_LOG_ERROR, "Invalid setup for format %s: "
1426 "missing configuration.\n", desc->name);
1429 if (hw_config->hwaccel) {
1430 av_log(avctx, AV_LOG_DEBUG, "Format %s requires hwaccel "
1431 "initialisation.\n", desc->name);
1432 err = hwaccel_init(avctx, hw_config);
1440 av_log(avctx, AV_LOG_DEBUG, "Format %s not usable, retrying "
1441 "get_format() without it.\n", desc->name);
1442 for (i = 0; i < n; i++) {
1443 if (choices[i] == user_choice)
1446 for (; i + 1 < n; i++)
1447 choices[i] = choices[i + 1];
1455 static void frame_pool_free(void *opaque, uint8_t *data)
1457 FramePool *pool = (FramePool*)data;
1460 for (i = 0; i < FF_ARRAY_ELEMS(pool->pools); i++)
1461 av_buffer_pool_uninit(&pool->pools[i]);
1466 static AVBufferRef *frame_pool_alloc(void)
1468 FramePool *pool = av_mallocz(sizeof(*pool));
1474 buf = av_buffer_create((uint8_t*)pool, sizeof(*pool),
1475 frame_pool_free, NULL, 0);
1484 static int update_frame_pool(AVCodecContext *avctx, AVFrame *frame)
1486 FramePool *pool = avctx->internal->pool ?
1487 (FramePool*)avctx->internal->pool->data : NULL;
1488 AVBufferRef *pool_buf;
1489 int i, ret, ch, planes;
1491 if (avctx->codec_type == AVMEDIA_TYPE_AUDIO) {
1492 int planar = av_sample_fmt_is_planar(frame->format);
1493 ch = frame->channels;
1494 planes = planar ? ch : 1;
1497 if (pool && pool->format == frame->format) {
1498 if (avctx->codec_type == AVMEDIA_TYPE_VIDEO &&
1499 pool->width == frame->width && pool->height == frame->height)
1501 if (avctx->codec_type == AVMEDIA_TYPE_AUDIO && pool->planes == planes &&
1502 pool->channels == ch && frame->nb_samples == pool->samples)
1506 pool_buf = frame_pool_alloc();
1508 return AVERROR(ENOMEM);
1509 pool = (FramePool*)pool_buf->data;
1511 switch (avctx->codec_type) {
1512 case AVMEDIA_TYPE_VIDEO: {
1514 int w = frame->width;
1515 int h = frame->height;
1517 ptrdiff_t linesize1[4];
1520 avcodec_align_dimensions2(avctx, &w, &h, pool->stride_align);
1523 // NOTE: do not align linesizes individually, this breaks e.g. assumptions
1524 // that linesize[0] == 2*linesize[1] in the MPEG-encoder for 4:2:2
1525 ret = av_image_fill_linesizes(linesize, avctx->pix_fmt, w);
1528 // increase alignment of w for next try (rhs gives the lowest bit set in w)
1532 for (i = 0; i < 4; i++)
1533 unaligned |= linesize[i] % pool->stride_align[i];
1534 } while (unaligned);
1536 for (i = 0; i < 4; i++)
1537 linesize1[i] = linesize[i];
1538 ret = av_image_fill_plane_sizes(size, avctx->pix_fmt, h, linesize1);
1542 for (i = 0; i < 4; i++) {
1543 pool->linesize[i] = linesize[i];
1545 if (size[i] > INT_MAX - (16 + STRIDE_ALIGN - 1)) {
1546 ret = AVERROR(EINVAL);
1549 pool->pools[i] = av_buffer_pool_init(size[i] + 16 + STRIDE_ALIGN - 1,
1550 CONFIG_MEMORY_POISONING ?
1553 if (!pool->pools[i]) {
1554 ret = AVERROR(ENOMEM);
1559 pool->format = frame->format;
1560 pool->width = frame->width;
1561 pool->height = frame->height;
1565 case AVMEDIA_TYPE_AUDIO: {
1566 ret = av_samples_get_buffer_size(&pool->linesize[0], ch,
1567 frame->nb_samples, frame->format, 0);
1571 pool->pools[0] = av_buffer_pool_init(pool->linesize[0], NULL);
1572 if (!pool->pools[0]) {
1573 ret = AVERROR(ENOMEM);
1577 pool->format = frame->format;
1578 pool->planes = planes;
1579 pool->channels = ch;
1580 pool->samples = frame->nb_samples;
1583 default: av_assert0(0);
1586 av_buffer_unref(&avctx->internal->pool);
1587 avctx->internal->pool = pool_buf;
1591 av_buffer_unref(&pool_buf);
1595 static int audio_get_buffer(AVCodecContext *avctx, AVFrame *frame)
1597 FramePool *pool = (FramePool*)avctx->internal->pool->data;
1598 int planes = pool->planes;
1601 frame->linesize[0] = pool->linesize[0];
1603 if (planes > AV_NUM_DATA_POINTERS) {
1604 frame->extended_data = av_mallocz_array(planes, sizeof(*frame->extended_data));
1605 frame->nb_extended_buf = planes - AV_NUM_DATA_POINTERS;
1606 frame->extended_buf = av_mallocz_array(frame->nb_extended_buf,
1607 sizeof(*frame->extended_buf));
1608 if (!frame->extended_data || !frame->extended_buf) {
1609 av_freep(&frame->extended_data);
1610 av_freep(&frame->extended_buf);
1611 return AVERROR(ENOMEM);
1614 frame->extended_data = frame->data;
1615 av_assert0(frame->nb_extended_buf == 0);
1618 for (i = 0; i < FFMIN(planes, AV_NUM_DATA_POINTERS); i++) {
1619 frame->buf[i] = av_buffer_pool_get(pool->pools[0]);
1622 frame->extended_data[i] = frame->data[i] = frame->buf[i]->data;
1624 for (i = 0; i < frame->nb_extended_buf; i++) {
1625 frame->extended_buf[i] = av_buffer_pool_get(pool->pools[0]);
1626 if (!frame->extended_buf[i])
1628 frame->extended_data[i + AV_NUM_DATA_POINTERS] = frame->extended_buf[i]->data;
1631 if (avctx->debug & FF_DEBUG_BUFFERS)
1632 av_log(avctx, AV_LOG_DEBUG, "default_get_buffer called on frame %p", frame);
1636 av_frame_unref(frame);
1637 return AVERROR(ENOMEM);
1640 static int video_get_buffer(AVCodecContext *s, AVFrame *pic)
1642 FramePool *pool = (FramePool*)s->internal->pool->data;
1643 const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(pic->format);
1646 if (pic->data[0] || pic->data[1] || pic->data[2] || pic->data[3]) {
1647 av_log(s, AV_LOG_ERROR, "pic->data[*]!=NULL in avcodec_default_get_buffer\n");
1652 av_log(s, AV_LOG_ERROR,
1653 "Unable to get pixel format descriptor for format %s\n",
1654 av_get_pix_fmt_name(pic->format));
1655 return AVERROR(EINVAL);
1658 memset(pic->data, 0, sizeof(pic->data));
1659 pic->extended_data = pic->data;
1661 for (i = 0; i < 4 && pool->pools[i]; i++) {
1662 pic->linesize[i] = pool->linesize[i];
1664 pic->buf[i] = av_buffer_pool_get(pool->pools[i]);
1668 pic->data[i] = pic->buf[i]->data;
1670 for (; i < AV_NUM_DATA_POINTERS; i++) {
1671 pic->data[i] = NULL;
1672 pic->linesize[i] = 0;
1674 if (desc->flags & AV_PIX_FMT_FLAG_PAL ||
1675 ((desc->flags & FF_PSEUDOPAL) && pic->data[1]))
1676 avpriv_set_systematic_pal2((uint32_t *)pic->data[1], pic->format);
1678 if (s->debug & FF_DEBUG_BUFFERS)
1679 av_log(s, AV_LOG_DEBUG, "default_get_buffer called on pic %p\n", pic);
1683 av_frame_unref(pic);
1684 return AVERROR(ENOMEM);
1687 int avcodec_default_get_buffer2(AVCodecContext *avctx, AVFrame *frame, int flags)
1691 if (avctx->hw_frames_ctx) {
1692 ret = av_hwframe_get_buffer(avctx->hw_frames_ctx, frame, 0);
1693 frame->width = avctx->coded_width;
1694 frame->height = avctx->coded_height;
1698 if ((ret = update_frame_pool(avctx, frame)) < 0)
1701 switch (avctx->codec_type) {
1702 case AVMEDIA_TYPE_VIDEO:
1703 return video_get_buffer(avctx, frame);
1704 case AVMEDIA_TYPE_AUDIO:
1705 return audio_get_buffer(avctx, frame);
1711 static int add_metadata_from_side_data(const AVPacket *avpkt, AVFrame *frame)
1714 const uint8_t *side_metadata;
1716 AVDictionary **frame_md = &frame->metadata;
1718 side_metadata = av_packet_get_side_data(avpkt,
1719 AV_PKT_DATA_STRINGS_METADATA, &size);
1720 return av_packet_unpack_dictionary(side_metadata, size, frame_md);
1723 int ff_decode_frame_props(AVCodecContext *avctx, AVFrame *frame)
1725 AVPacket *pkt = avctx->internal->last_pkt_props;
1727 static const struct {
1728 enum AVPacketSideDataType packet;
1729 enum AVFrameSideDataType frame;
1731 { AV_PKT_DATA_REPLAYGAIN , AV_FRAME_DATA_REPLAYGAIN },
1732 { AV_PKT_DATA_DISPLAYMATRIX, AV_FRAME_DATA_DISPLAYMATRIX },
1733 { AV_PKT_DATA_SPHERICAL, AV_FRAME_DATA_SPHERICAL },
1734 { AV_PKT_DATA_STEREO3D, AV_FRAME_DATA_STEREO3D },
1735 { AV_PKT_DATA_AUDIO_SERVICE_TYPE, AV_FRAME_DATA_AUDIO_SERVICE_TYPE },
1736 { AV_PKT_DATA_MASTERING_DISPLAY_METADATA, AV_FRAME_DATA_MASTERING_DISPLAY_METADATA },
1737 { AV_PKT_DATA_CONTENT_LIGHT_LEVEL, AV_FRAME_DATA_CONTENT_LIGHT_LEVEL },
1738 { AV_PKT_DATA_A53_CC, AV_FRAME_DATA_A53_CC },
1739 { AV_PKT_DATA_ICC_PROFILE, AV_FRAME_DATA_ICC_PROFILE },
1740 { AV_PKT_DATA_S12M_TIMECODE, AV_FRAME_DATA_S12M_TIMECODE },
1743 if (IS_EMPTY(pkt) && av_fifo_size(avctx->internal->pkt_props) >= sizeof(*pkt))
1744 av_fifo_generic_read(avctx->internal->pkt_props,
1745 pkt, sizeof(*pkt), NULL);
1748 frame->pts = pkt->pts;
1750 FF_DISABLE_DEPRECATION_WARNINGS
1751 frame->pkt_pts = pkt->pts;
1752 FF_ENABLE_DEPRECATION_WARNINGS
1754 frame->pkt_pos = pkt->pos;
1755 frame->pkt_duration = pkt->duration;
1756 frame->pkt_size = pkt->size;
1758 for (i = 0; i < FF_ARRAY_ELEMS(sd); i++) {
1760 uint8_t *packet_sd = av_packet_get_side_data(pkt, sd[i].packet, &size);
1762 AVFrameSideData *frame_sd = av_frame_new_side_data(frame,
1766 return AVERROR(ENOMEM);
1768 memcpy(frame_sd->data, packet_sd, size);
1771 add_metadata_from_side_data(pkt, frame);
1773 if (pkt->flags & AV_PKT_FLAG_DISCARD) {
1774 frame->flags |= AV_FRAME_FLAG_DISCARD;
1776 frame->flags = (frame->flags & ~AV_FRAME_FLAG_DISCARD);
1779 frame->reordered_opaque = avctx->reordered_opaque;
1781 if (frame->color_primaries == AVCOL_PRI_UNSPECIFIED)
1782 frame->color_primaries = avctx->color_primaries;
1783 if (frame->color_trc == AVCOL_TRC_UNSPECIFIED)
1784 frame->color_trc = avctx->color_trc;
1785 if (frame->colorspace == AVCOL_SPC_UNSPECIFIED)
1786 frame->colorspace = avctx->colorspace;
1787 if (frame->color_range == AVCOL_RANGE_UNSPECIFIED)
1788 frame->color_range = avctx->color_range;
1789 if (frame->chroma_location == AVCHROMA_LOC_UNSPECIFIED)
1790 frame->chroma_location = avctx->chroma_sample_location;
1792 switch (avctx->codec->type) {
1793 case AVMEDIA_TYPE_VIDEO:
1794 frame->format = avctx->pix_fmt;
1795 if (!frame->sample_aspect_ratio.num)
1796 frame->sample_aspect_ratio = avctx->sample_aspect_ratio;
1798 if (frame->width && frame->height &&
1799 av_image_check_sar(frame->width, frame->height,
1800 frame->sample_aspect_ratio) < 0) {
1801 av_log(avctx, AV_LOG_WARNING, "ignoring invalid SAR: %u/%u\n",
1802 frame->sample_aspect_ratio.num,
1803 frame->sample_aspect_ratio.den);
1804 frame->sample_aspect_ratio = (AVRational){ 0, 1 };
1808 case AVMEDIA_TYPE_AUDIO:
1809 if (!frame->sample_rate)
1810 frame->sample_rate = avctx->sample_rate;
1811 if (frame->format < 0)
1812 frame->format = avctx->sample_fmt;
1813 if (!frame->channel_layout) {
1814 if (avctx->channel_layout) {
1815 if (av_get_channel_layout_nb_channels(avctx->channel_layout) !=
1817 av_log(avctx, AV_LOG_ERROR, "Inconsistent channel "
1818 "configuration.\n");
1819 return AVERROR(EINVAL);
1822 frame->channel_layout = avctx->channel_layout;
1824 if (avctx->channels > FF_SANE_NB_CHANNELS) {
1825 av_log(avctx, AV_LOG_ERROR, "Too many channels: %d.\n",
1827 return AVERROR(ENOSYS);
1831 frame->channels = avctx->channels;
1837 static void validate_avframe_allocation(AVCodecContext *avctx, AVFrame *frame)
1839 if (avctx->codec_type == AVMEDIA_TYPE_VIDEO) {
1841 int num_planes = av_pix_fmt_count_planes(frame->format);
1842 const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(frame->format);
1843 int flags = desc ? desc->flags : 0;
1844 if (num_planes == 1 && (flags & AV_PIX_FMT_FLAG_PAL))
1846 if ((flags & FF_PSEUDOPAL) && frame->data[1])
1848 for (i = 0; i < num_planes; i++) {
1849 av_assert0(frame->data[i]);
1851 // For formats without data like hwaccel allow unused pointers to be non-NULL.
1852 for (i = num_planes; num_planes > 0 && i < FF_ARRAY_ELEMS(frame->data); i++) {
1854 av_log(avctx, AV_LOG_ERROR, "Buffer returned by get_buffer2() did not zero unused plane pointers\n");
1855 frame->data[i] = NULL;
1860 static void decode_data_free(void *opaque, uint8_t *data)
1862 FrameDecodeData *fdd = (FrameDecodeData*)data;
1864 if (fdd->post_process_opaque_free)
1865 fdd->post_process_opaque_free(fdd->post_process_opaque);
1867 if (fdd->hwaccel_priv_free)
1868 fdd->hwaccel_priv_free(fdd->hwaccel_priv);
1873 int ff_attach_decode_data(AVFrame *frame)
1875 AVBufferRef *fdd_buf;
1876 FrameDecodeData *fdd;
1878 av_assert1(!frame->private_ref);
1879 av_buffer_unref(&frame->private_ref);
1881 fdd = av_mallocz(sizeof(*fdd));
1883 return AVERROR(ENOMEM);
1885 fdd_buf = av_buffer_create((uint8_t*)fdd, sizeof(*fdd), decode_data_free,
1886 NULL, AV_BUFFER_FLAG_READONLY);
1889 return AVERROR(ENOMEM);
1892 frame->private_ref = fdd_buf;
1897 int ff_get_buffer(AVCodecContext *avctx, AVFrame *frame, int flags)
1899 const AVHWAccel *hwaccel = avctx->hwaccel;
1900 int override_dimensions = 1;
1903 if (avctx->codec_type == AVMEDIA_TYPE_VIDEO) {
1904 if ((unsigned)avctx->width > INT_MAX - STRIDE_ALIGN ||
1905 (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) {
1906 av_log(avctx, AV_LOG_ERROR, "video_get_buffer: image parameters invalid\n");
1907 ret = AVERROR(EINVAL);
1911 if (frame->width <= 0 || frame->height <= 0) {
1912 frame->width = FFMAX(avctx->width, AV_CEIL_RSHIFT(avctx->coded_width, avctx->lowres));
1913 frame->height = FFMAX(avctx->height, AV_CEIL_RSHIFT(avctx->coded_height, avctx->lowres));
1914 override_dimensions = 0;
1917 if (frame->data[0] || frame->data[1] || frame->data[2] || frame->data[3]) {
1918 av_log(avctx, AV_LOG_ERROR, "pic->data[*]!=NULL in get_buffer_internal\n");
1919 ret = AVERROR(EINVAL);
1922 } else if (avctx->codec_type == AVMEDIA_TYPE_AUDIO) {
1923 if (frame->nb_samples * (int64_t)avctx->channels > avctx->max_samples) {
1924 av_log(avctx, AV_LOG_ERROR, "samples per frame %d, exceeds max_samples %"PRId64"\n", frame->nb_samples, avctx->max_samples);
1925 ret = AVERROR(EINVAL);
1929 ret = ff_decode_frame_props(avctx, frame);
1934 if (hwaccel->alloc_frame) {
1935 ret = hwaccel->alloc_frame(avctx, frame);
1939 avctx->sw_pix_fmt = avctx->pix_fmt;
1941 ret = avctx->get_buffer2(avctx, frame, flags);
1945 validate_avframe_allocation(avctx, frame);
1947 ret = ff_attach_decode_data(frame);
1952 if (avctx->codec_type == AVMEDIA_TYPE_VIDEO && !override_dimensions &&
1953 !(avctx->codec->caps_internal & FF_CODEC_CAP_EXPORTS_CROPPING)) {
1954 frame->width = avctx->width;
1955 frame->height = avctx->height;
1960 av_log(avctx, AV_LOG_ERROR, "get_buffer() failed\n");
1961 av_frame_unref(frame);
1967 static int reget_buffer_internal(AVCodecContext *avctx, AVFrame *frame, int flags)
1972 av_assert0(avctx->codec_type == AVMEDIA_TYPE_VIDEO);
1974 if (frame->data[0] && (frame->width != avctx->width || frame->height != avctx->height || frame->format != avctx->pix_fmt)) {
1975 av_log(avctx, AV_LOG_WARNING, "Picture changed from size:%dx%d fmt:%s to size:%dx%d fmt:%s in reget buffer()\n",
1976 frame->width, frame->height, av_get_pix_fmt_name(frame->format), avctx->width, avctx->height, av_get_pix_fmt_name(avctx->pix_fmt));
1977 av_frame_unref(frame);
1980 if (!frame->data[0])
1981 return ff_get_buffer(avctx, frame, AV_GET_BUFFER_FLAG_REF);
1983 if ((flags & FF_REGET_BUFFER_FLAG_READONLY) || av_frame_is_writable(frame))
1984 return ff_decode_frame_props(avctx, frame);
1986 tmp = av_frame_alloc();
1988 return AVERROR(ENOMEM);
1990 av_frame_move_ref(tmp, frame);
1992 ret = ff_get_buffer(avctx, frame, AV_GET_BUFFER_FLAG_REF);
1994 av_frame_free(&tmp);
1998 av_frame_copy(frame, tmp);
1999 av_frame_free(&tmp);
2004 int ff_reget_buffer(AVCodecContext *avctx, AVFrame *frame, int flags)
2006 int ret = reget_buffer_internal(avctx, frame, flags);
2008 av_log(avctx, AV_LOG_ERROR, "reget_buffer() failed\n");