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;
207 DecodeFilterContext *s = &avci->filter;
208 const char *bsfs_str;
214 bsfs_str = avctx->codec->bsfs ? avctx->codec->bsfs : "null";
215 while (bsfs_str && *bsfs_str) {
217 const AVBitStreamFilter *filter;
218 char *bsf, *bsf_options_str, *bsf_name;
220 bsf = av_get_token(&bsfs_str, ",");
222 ret = AVERROR(ENOMEM);
225 bsf_name = av_strtok(bsf, "=", &bsf_options_str);
228 ret = AVERROR(ENOMEM);
232 filter = av_bsf_get_by_name(bsf_name);
234 av_log(avctx, AV_LOG_ERROR, "A non-existing bitstream filter %s "
235 "requested by a decoder. This is a bug, please report it.\n",
242 tmp = av_realloc_array(s->bsfs, s->nb_bsfs + 1, sizeof(*s->bsfs));
245 ret = AVERROR(ENOMEM);
250 ret = av_bsf_alloc(filter, &s->bsfs[s->nb_bsfs]);
257 if (s->nb_bsfs == 1) {
258 /* We do not currently have an API for passing the input timebase into decoders,
259 * but no filters used here should actually need it.
260 * So we make up some plausible-looking number (the MPEG 90kHz timebase) */
261 s->bsfs[s->nb_bsfs - 1]->time_base_in = (AVRational){ 1, 90000 };
262 ret = avcodec_parameters_from_context(s->bsfs[s->nb_bsfs - 1]->par_in,
265 s->bsfs[s->nb_bsfs - 1]->time_base_in = s->bsfs[s->nb_bsfs - 2]->time_base_out;
266 ret = avcodec_parameters_copy(s->bsfs[s->nb_bsfs - 1]->par_in,
267 s->bsfs[s->nb_bsfs - 2]->par_out);
274 if (bsf_options_str && filter->priv_class) {
275 const AVOption *opt = av_opt_next(s->bsfs[s->nb_bsfs - 1]->priv_data, NULL);
276 const char * shorthand[2] = {NULL};
279 shorthand[0] = opt->name;
281 ret = av_opt_set_from_string(s->bsfs[s->nb_bsfs - 1]->priv_data, bsf_options_str, shorthand, "=", ":");
283 if (ret != AVERROR(ENOMEM)) {
284 av_log(avctx, AV_LOG_ERROR, "Invalid options for bitstream filter %s "
285 "requested by the decoder. This is a bug, please report it.\n",
295 ret = av_bsf_init(s->bsfs[s->nb_bsfs - 1]);
305 ff_decode_bsfs_uninit(avctx);
309 /* try to get one output packet from the filter chain */
310 static int bsfs_poll(AVCodecContext *avctx, AVPacket *pkt)
312 DecodeFilterContext *s = &avctx->internal->filter;
315 /* start with the last filter in the chain */
316 idx = s->nb_bsfs - 1;
318 /* request a packet from the currently selected filter */
319 ret = av_bsf_receive_packet(s->bsfs[idx], pkt);
320 if (ret == AVERROR(EAGAIN)) {
321 /* no packets available, try the next filter up the chain */
324 } else if (ret < 0 && ret != AVERROR_EOF) {
328 /* got a packet or EOF -- pass it to the caller or to the next filter
330 if (idx == s->nb_bsfs - 1) {
334 ret = av_bsf_send_packet(s->bsfs[idx], ret < 0 ? NULL : pkt);
336 av_log(avctx, AV_LOG_ERROR,
337 "Error pre-processing a packet before decoding\n");
338 av_packet_unref(pkt);
344 return AVERROR(EAGAIN);
347 int ff_decode_get_packet(AVCodecContext *avctx, AVPacket *pkt)
349 AVCodecInternal *avci = avctx->internal;
355 ret = bsfs_poll(avctx, pkt);
356 if (ret == AVERROR_EOF)
361 ret = extract_packet_props(avctx->internal, pkt);
365 ret = apply_param_change(avctx, pkt);
369 if (avctx->codec->receive_frame)
370 avci->compat_decode_consumed += pkt->size;
374 av_packet_unref(pkt);
379 * Attempt to guess proper monotonic timestamps for decoded video frames
380 * which might have incorrect times. Input timestamps may wrap around, in
381 * which case the output will as well.
383 * @param pts the pts field of the decoded AVPacket, as passed through
385 * @param dts the dts field of the decoded AVPacket
386 * @return one of the input values, may be AV_NOPTS_VALUE
388 static int64_t guess_correct_pts(AVCodecContext *ctx,
389 int64_t reordered_pts, int64_t dts)
391 int64_t pts = AV_NOPTS_VALUE;
393 if (dts != AV_NOPTS_VALUE) {
394 ctx->pts_correction_num_faulty_dts += dts <= ctx->pts_correction_last_dts;
395 ctx->pts_correction_last_dts = dts;
396 } else if (reordered_pts != AV_NOPTS_VALUE)
397 ctx->pts_correction_last_dts = reordered_pts;
399 if (reordered_pts != AV_NOPTS_VALUE) {
400 ctx->pts_correction_num_faulty_pts += reordered_pts <= ctx->pts_correction_last_pts;
401 ctx->pts_correction_last_pts = reordered_pts;
402 } else if(dts != AV_NOPTS_VALUE)
403 ctx->pts_correction_last_pts = dts;
405 if ((ctx->pts_correction_num_faulty_pts<=ctx->pts_correction_num_faulty_dts || dts == AV_NOPTS_VALUE)
406 && reordered_pts != AV_NOPTS_VALUE)
415 * The core of the receive_frame_wrapper for the decoders implementing
416 * the simple API. Certain decoders might consume partial packets without
417 * returning any output, so this function needs to be called in a loop until it
420 static int decode_simple_internal(AVCodecContext *avctx, AVFrame *frame)
422 AVCodecInternal *avci = avctx->internal;
423 DecodeSimpleContext *ds = &avci->ds;
424 AVPacket *pkt = ds->in_pkt;
425 // copy to ensure we do not change pkt
426 int got_frame, actual_got_frame;
429 if (!pkt->data && !avci->draining) {
430 av_packet_unref(pkt);
431 ret = ff_decode_get_packet(avctx, pkt);
432 if (ret < 0 && ret != AVERROR_EOF)
436 // Some codecs (at least wma lossless) will crash when feeding drain packets
437 // after EOF was signaled.
438 if (avci->draining_done)
442 !(avctx->codec->capabilities & AV_CODEC_CAP_DELAY ||
443 avctx->active_thread_type & FF_THREAD_FRAME))
448 if (HAVE_THREADS && avctx->active_thread_type & FF_THREAD_FRAME) {
449 ret = ff_thread_decode_frame(avctx, frame, &got_frame, pkt);
451 ret = avctx->codec->decode(avctx, frame, &got_frame, pkt);
453 if (!(avctx->codec->caps_internal & FF_CODEC_CAP_SETS_PKT_DTS))
454 frame->pkt_dts = pkt->dts;
455 if (avctx->codec->type == AVMEDIA_TYPE_VIDEO) {
456 if(!avctx->has_b_frames)
457 frame->pkt_pos = pkt->pos;
458 //FIXME these should be under if(!avctx->has_b_frames)
459 /* get_buffer is supposed to set frame parameters */
460 if (!(avctx->codec->capabilities & AV_CODEC_CAP_DR1)) {
461 if (!frame->sample_aspect_ratio.num) frame->sample_aspect_ratio = avctx->sample_aspect_ratio;
462 if (!frame->width) frame->width = avctx->width;
463 if (!frame->height) frame->height = avctx->height;
464 if (frame->format == AV_PIX_FMT_NONE) frame->format = avctx->pix_fmt;
469 actual_got_frame = got_frame;
471 if (avctx->codec->type == AVMEDIA_TYPE_VIDEO) {
472 if (frame->flags & AV_FRAME_FLAG_DISCARD)
475 frame->best_effort_timestamp = guess_correct_pts(avctx,
478 } else if (avctx->codec->type == AVMEDIA_TYPE_AUDIO) {
481 uint32_t discard_padding = 0;
482 uint8_t skip_reason = 0;
483 uint8_t discard_reason = 0;
485 if (ret >= 0 && got_frame) {
486 frame->best_effort_timestamp = guess_correct_pts(avctx,
489 if (frame->format == AV_SAMPLE_FMT_NONE)
490 frame->format = avctx->sample_fmt;
491 if (!frame->channel_layout)
492 frame->channel_layout = avctx->channel_layout;
493 if (!frame->channels)
494 frame->channels = avctx->channels;
495 if (!frame->sample_rate)
496 frame->sample_rate = avctx->sample_rate;
499 side= av_packet_get_side_data(avci->last_pkt_props, AV_PKT_DATA_SKIP_SAMPLES, &side_size);
500 if(side && side_size>=10) {
501 avci->skip_samples = AV_RL32(side) * avci->skip_samples_multiplier;
502 discard_padding = AV_RL32(side + 4);
503 av_log(avctx, AV_LOG_DEBUG, "skip %d / discard %d samples due to side data\n",
504 avci->skip_samples, (int)discard_padding);
505 skip_reason = AV_RL8(side + 8);
506 discard_reason = AV_RL8(side + 9);
509 if ((frame->flags & AV_FRAME_FLAG_DISCARD) && got_frame &&
510 !(avctx->flags2 & AV_CODEC_FLAG2_SKIP_MANUAL)) {
511 avci->skip_samples = FFMAX(0, avci->skip_samples - frame->nb_samples);
515 if (avci->skip_samples > 0 && got_frame &&
516 !(avctx->flags2 & AV_CODEC_FLAG2_SKIP_MANUAL)) {
517 if(frame->nb_samples <= avci->skip_samples){
519 avci->skip_samples -= frame->nb_samples;
520 av_log(avctx, AV_LOG_DEBUG, "skip whole frame, skip left: %d\n",
523 av_samples_copy(frame->extended_data, frame->extended_data, 0, avci->skip_samples,
524 frame->nb_samples - avci->skip_samples, avctx->channels, frame->format);
525 if(avctx->pkt_timebase.num && avctx->sample_rate) {
526 int64_t diff_ts = av_rescale_q(avci->skip_samples,
527 (AVRational){1, avctx->sample_rate},
528 avctx->pkt_timebase);
529 if(frame->pts!=AV_NOPTS_VALUE)
530 frame->pts += diff_ts;
532 FF_DISABLE_DEPRECATION_WARNINGS
533 if(frame->pkt_pts!=AV_NOPTS_VALUE)
534 frame->pkt_pts += diff_ts;
535 FF_ENABLE_DEPRECATION_WARNINGS
537 if(frame->pkt_dts!=AV_NOPTS_VALUE)
538 frame->pkt_dts += diff_ts;
539 if (frame->pkt_duration >= diff_ts)
540 frame->pkt_duration -= diff_ts;
542 av_log(avctx, AV_LOG_WARNING, "Could not update timestamps for skipped samples.\n");
544 av_log(avctx, AV_LOG_DEBUG, "skip %d/%d samples\n",
545 avci->skip_samples, frame->nb_samples);
546 frame->nb_samples -= avci->skip_samples;
547 avci->skip_samples = 0;
551 if (discard_padding > 0 && discard_padding <= frame->nb_samples && got_frame &&
552 !(avctx->flags2 & AV_CODEC_FLAG2_SKIP_MANUAL)) {
553 if (discard_padding == frame->nb_samples) {
556 if(avctx->pkt_timebase.num && avctx->sample_rate) {
557 int64_t diff_ts = av_rescale_q(frame->nb_samples - discard_padding,
558 (AVRational){1, avctx->sample_rate},
559 avctx->pkt_timebase);
560 frame->pkt_duration = diff_ts;
562 av_log(avctx, AV_LOG_WARNING, "Could not update timestamps for discarded samples.\n");
564 av_log(avctx, AV_LOG_DEBUG, "discard %d/%d samples\n",
565 (int)discard_padding, frame->nb_samples);
566 frame->nb_samples -= discard_padding;
570 if ((avctx->flags2 & AV_CODEC_FLAG2_SKIP_MANUAL) && got_frame) {
571 AVFrameSideData *fside = av_frame_new_side_data(frame, AV_FRAME_DATA_SKIP_SAMPLES, 10);
573 AV_WL32(fside->data, avci->skip_samples);
574 AV_WL32(fside->data + 4, discard_padding);
575 AV_WL8(fside->data + 8, skip_reason);
576 AV_WL8(fside->data + 9, discard_reason);
577 avci->skip_samples = 0;
582 if (avctx->codec->type == AVMEDIA_TYPE_AUDIO &&
583 !avci->showed_multi_packet_warning &&
584 ret >= 0 && ret != pkt->size && !(avctx->codec->capabilities & AV_CODEC_CAP_SUBFRAMES)) {
585 av_log(avctx, AV_LOG_WARNING, "Multiple frames in a packet.\n");
586 avci->showed_multi_packet_warning = 1;
590 av_frame_unref(frame);
592 if (ret >= 0 && avctx->codec->type == AVMEDIA_TYPE_VIDEO && !(avctx->flags & AV_CODEC_FLAG_TRUNCATED))
595 #if FF_API_AVCTX_TIMEBASE
596 if (avctx->framerate.num > 0 && avctx->framerate.den > 0)
597 avctx->time_base = av_inv_q(av_mul_q(avctx->framerate, (AVRational){avctx->ticks_per_frame, 1}));
600 /* do not stop draining when actual_got_frame != 0 or ret < 0 */
601 /* got_frame == 0 but actual_got_frame != 0 when frame is discarded */
602 if (avci->draining && !actual_got_frame) {
604 /* prevent infinite loop if a decoder wrongly always return error on draining */
605 /* reasonable nb_errors_max = maximum b frames + thread count */
606 int nb_errors_max = 20 + (HAVE_THREADS && avctx->active_thread_type & FF_THREAD_FRAME ?
607 avctx->thread_count : 1);
609 if (avci->nb_draining_errors++ >= nb_errors_max) {
610 av_log(avctx, AV_LOG_ERROR, "Too many errors when draining, this is a bug. "
611 "Stop draining and force EOF.\n");
612 avci->draining_done = 1;
616 avci->draining_done = 1;
620 avci->compat_decode_consumed += ret;
622 if (ret >= pkt->size || ret < 0) {
623 av_packet_unref(pkt);
627 pkt->data += consumed;
628 pkt->size -= consumed;
629 avci->last_pkt_props->size -= consumed; // See extract_packet_props() comment.
630 pkt->pts = AV_NOPTS_VALUE;
631 pkt->dts = AV_NOPTS_VALUE;
632 avci->last_pkt_props->pts = AV_NOPTS_VALUE;
633 avci->last_pkt_props->dts = AV_NOPTS_VALUE;
637 av_assert0(frame->buf[0]);
639 return ret < 0 ? ret : 0;
642 static int decode_simple_receive_frame(AVCodecContext *avctx, AVFrame *frame)
646 while (!frame->buf[0]) {
647 ret = decode_simple_internal(avctx, frame);
655 static int decode_receive_frame_internal(AVCodecContext *avctx, AVFrame *frame)
657 AVCodecInternal *avci = avctx->internal;
660 av_assert0(!frame->buf[0]);
662 if (avctx->codec->receive_frame)
663 ret = avctx->codec->receive_frame(avctx, frame);
665 ret = decode_simple_receive_frame(avctx, frame);
667 if (ret == AVERROR_EOF)
668 avci->draining_done = 1;
671 /* the only case where decode data is not set should be decoders
672 * that do not call ff_get_buffer() */
673 av_assert0((frame->private_ref && frame->private_ref->size == sizeof(FrameDecodeData)) ||
674 !(avctx->codec->capabilities & AV_CODEC_CAP_DR1));
676 if (frame->private_ref) {
677 FrameDecodeData *fdd = (FrameDecodeData*)frame->private_ref->data;
679 if (fdd->post_process) {
680 ret = fdd->post_process(avctx, frame);
682 av_frame_unref(frame);
689 /* free the per-frame decode data */
690 av_buffer_unref(&frame->private_ref);
695 int attribute_align_arg avcodec_send_packet(AVCodecContext *avctx, const AVPacket *avpkt)
697 AVCodecInternal *avci = avctx->internal;
700 if (!avcodec_is_open(avctx) || !av_codec_is_decoder(avctx->codec))
701 return AVERROR(EINVAL);
703 if (avctx->internal->draining)
706 if (avpkt && !avpkt->size && avpkt->data)
707 return AVERROR(EINVAL);
709 av_packet_unref(avci->buffer_pkt);
710 if (avpkt && (avpkt->data || avpkt->side_data_elems)) {
711 ret = av_packet_ref(avci->buffer_pkt, avpkt);
716 ret = av_bsf_send_packet(avci->filter.bsfs[0], avci->buffer_pkt);
718 av_packet_unref(avci->buffer_pkt);
722 if (!avci->buffer_frame->buf[0]) {
723 ret = decode_receive_frame_internal(avctx, avci->buffer_frame);
724 if (ret < 0 && ret != AVERROR(EAGAIN) && ret != AVERROR_EOF)
731 static int apply_cropping(AVCodecContext *avctx, AVFrame *frame)
733 /* make sure we are noisy about decoders returning invalid cropping data */
734 if (frame->crop_left >= INT_MAX - frame->crop_right ||
735 frame->crop_top >= INT_MAX - frame->crop_bottom ||
736 (frame->crop_left + frame->crop_right) >= frame->width ||
737 (frame->crop_top + frame->crop_bottom) >= frame->height) {
738 av_log(avctx, AV_LOG_WARNING,
739 "Invalid cropping information set by a decoder: "
740 "%"SIZE_SPECIFIER"/%"SIZE_SPECIFIER"/%"SIZE_SPECIFIER"/%"SIZE_SPECIFIER" "
741 "(frame size %dx%d). This is a bug, please report it\n",
742 frame->crop_left, frame->crop_right, frame->crop_top, frame->crop_bottom,
743 frame->width, frame->height);
744 frame->crop_left = 0;
745 frame->crop_right = 0;
747 frame->crop_bottom = 0;
751 if (!avctx->apply_cropping)
754 return av_frame_apply_cropping(frame, avctx->flags & AV_CODEC_FLAG_UNALIGNED ?
755 AV_FRAME_CROP_UNALIGNED : 0);
758 int attribute_align_arg avcodec_receive_frame(AVCodecContext *avctx, AVFrame *frame)
760 AVCodecInternal *avci = avctx->internal;
763 av_frame_unref(frame);
765 if (!avcodec_is_open(avctx) || !av_codec_is_decoder(avctx->codec))
766 return AVERROR(EINVAL);
768 if (avci->buffer_frame->buf[0]) {
769 av_frame_move_ref(frame, avci->buffer_frame);
771 ret = decode_receive_frame_internal(avctx, frame);
776 if (avctx->codec_type == AVMEDIA_TYPE_VIDEO) {
777 ret = apply_cropping(avctx, frame);
779 av_frame_unref(frame);
784 avctx->frame_number++;
786 if (avctx->flags & AV_CODEC_FLAG_DROPCHANGED) {
788 if (avctx->frame_number == 1) {
789 avci->initial_format = frame->format;
790 switch(avctx->codec_type) {
791 case AVMEDIA_TYPE_VIDEO:
792 avci->initial_width = frame->width;
793 avci->initial_height = frame->height;
795 case AVMEDIA_TYPE_AUDIO:
796 avci->initial_sample_rate = frame->sample_rate ? frame->sample_rate :
798 avci->initial_channels = frame->channels;
799 avci->initial_channel_layout = frame->channel_layout;
804 if (avctx->frame_number > 1) {
805 changed = avci->initial_format != frame->format;
807 switch(avctx->codec_type) {
808 case AVMEDIA_TYPE_VIDEO:
809 changed |= avci->initial_width != frame->width ||
810 avci->initial_height != frame->height;
812 case AVMEDIA_TYPE_AUDIO:
813 changed |= avci->initial_sample_rate != frame->sample_rate ||
814 avci->initial_sample_rate != avctx->sample_rate ||
815 avci->initial_channels != frame->channels ||
816 avci->initial_channel_layout != frame->channel_layout;
821 avci->changed_frames_dropped++;
822 av_log(avctx, AV_LOG_INFO, "dropped changed frame #%d pts %"PRId64
823 " drop count: %d \n",
824 avctx->frame_number, frame->pts,
825 avci->changed_frames_dropped);
826 av_frame_unref(frame);
827 return AVERROR_INPUT_CHANGED;
834 static int compat_decode(AVCodecContext *avctx, AVFrame *frame,
835 int *got_frame, const AVPacket *pkt)
837 AVCodecInternal *avci = avctx->internal;
840 av_assert0(avci->compat_decode_consumed == 0);
842 if (avci->draining_done && pkt && pkt->size != 0) {
843 av_log(avctx, AV_LOG_WARNING, "Got unexpected packet after EOF\n");
844 avcodec_flush_buffers(avctx);
848 avci->compat_decode = 1;
850 if (avci->compat_decode_partial_size > 0 &&
851 avci->compat_decode_partial_size != pkt->size) {
852 av_log(avctx, AV_LOG_ERROR,
853 "Got unexpected packet size after a partial decode\n");
854 ret = AVERROR(EINVAL);
858 if (!avci->compat_decode_partial_size) {
859 ret = avcodec_send_packet(avctx, pkt);
860 if (ret == AVERROR_EOF)
862 else if (ret == AVERROR(EAGAIN)) {
863 /* we fully drain all the output in each decode call, so this should not
872 ret = avcodec_receive_frame(avctx, frame);
874 if (ret == AVERROR(EAGAIN) || ret == AVERROR_EOF)
879 if (frame != avci->compat_decode_frame) {
880 if (!avctx->refcounted_frames) {
881 ret = unrefcount_frame(avci, frame);
887 frame = avci->compat_decode_frame;
889 if (!avci->compat_decode_warned) {
890 av_log(avctx, AV_LOG_WARNING, "The deprecated avcodec_decode_* "
891 "API cannot return all the frames for this decoder. "
892 "Some frames will be dropped. Update your code to the "
893 "new decoding API to fix this.\n");
894 avci->compat_decode_warned = 1;
898 if (avci->draining || (!avctx->codec->bsfs && avci->compat_decode_consumed < pkt->size))
904 /* if there are any bsfs then assume full packet is always consumed */
905 if (avctx->codec->bsfs)
908 ret = FFMIN(avci->compat_decode_consumed, pkt->size);
910 avci->compat_decode_consumed = 0;
911 avci->compat_decode_partial_size = (ret >= 0) ? pkt->size - ret : 0;
916 int attribute_align_arg avcodec_decode_video2(AVCodecContext *avctx, AVFrame *picture,
917 int *got_picture_ptr,
918 const AVPacket *avpkt)
920 return compat_decode(avctx, picture, got_picture_ptr, avpkt);
923 int attribute_align_arg avcodec_decode_audio4(AVCodecContext *avctx,
926 const AVPacket *avpkt)
928 return compat_decode(avctx, frame, got_frame_ptr, avpkt);
931 static void get_subtitle_defaults(AVSubtitle *sub)
933 memset(sub, 0, sizeof(*sub));
934 sub->pts = AV_NOPTS_VALUE;
937 #define UTF8_MAX_BYTES 4 /* 5 and 6 bytes sequences should not be used */
938 static int recode_subtitle(AVCodecContext *avctx,
939 AVPacket *outpkt, const AVPacket *inpkt)
942 iconv_t cd = (iconv_t)-1;
949 if (avctx->sub_charenc_mode != FF_SUB_CHARENC_MODE_PRE_DECODER || inpkt->size == 0)
953 cd = iconv_open("UTF-8", avctx->sub_charenc);
954 av_assert0(cd != (iconv_t)-1);
959 if (inl >= INT_MAX / UTF8_MAX_BYTES - AV_INPUT_BUFFER_PADDING_SIZE) {
960 av_log(avctx, AV_LOG_ERROR, "Subtitles packet is too big for recoding\n");
961 ret = AVERROR(ENOMEM);
965 ret = av_new_packet(&tmp, inl * UTF8_MAX_BYTES);
968 outpkt->buf = tmp.buf;
969 outpkt->data = tmp.data;
970 outpkt->size = tmp.size;
974 if (iconv(cd, &inb, &inl, &outb, &outl) == (size_t)-1 ||
975 iconv(cd, NULL, NULL, &outb, &outl) == (size_t)-1 ||
976 outl >= outpkt->size || inl != 0) {
977 ret = FFMIN(AVERROR(errno), -1);
978 av_log(avctx, AV_LOG_ERROR, "Unable to recode subtitle event \"%s\" "
979 "from %s to UTF-8\n", inpkt->data, avctx->sub_charenc);
980 av_packet_unref(&tmp);
983 outpkt->size -= outl;
984 memset(outpkt->data + outpkt->size, 0, outl);
987 if (cd != (iconv_t)-1)
991 av_log(avctx, AV_LOG_ERROR, "requesting subtitles recoding without iconv");
992 return AVERROR(EINVAL);
996 static int utf8_check(const uint8_t *str)
999 uint32_t codepoint, min;
1003 GET_UTF8(codepoint, *(byte++), return 0;);
1004 min = byte - str == 1 ? 0 : byte - str == 2 ? 0x80 :
1005 1 << (5 * (byte - str) - 4);
1006 if (codepoint < min || codepoint >= 0x110000 ||
1007 codepoint == 0xFFFE /* BOM */ ||
1008 codepoint >= 0xD800 && codepoint <= 0xDFFF /* surrogates */)
1015 #if FF_API_ASS_TIMING
1016 static void insert_ts(AVBPrint *buf, int ts)
1019 av_bprintf(buf, "9:59:59.99,");
1023 h = ts/360000; ts -= 360000*h;
1024 m = ts/ 6000; ts -= 6000*m;
1025 s = ts/ 100; ts -= 100*s;
1026 av_bprintf(buf, "%d:%02d:%02d.%02d,", h, m, s, ts);
1030 static int convert_sub_to_old_ass_form(AVSubtitle *sub, const AVPacket *pkt, AVRational tb)
1035 av_bprint_init(&buf, 0, AV_BPRINT_SIZE_UNLIMITED);
1037 for (i = 0; i < sub->num_rects; i++) {
1040 AVSubtitleRect *rect = sub->rects[i];
1041 int ts_start, ts_duration = -1;
1044 if (rect->type != SUBTITLE_ASS || !strncmp(rect->ass, "Dialogue: ", 10))
1047 av_bprint_clear(&buf);
1049 /* skip ReadOrder */
1050 dialog = strchr(rect->ass, ',');
1055 /* extract Layer or Marked */
1056 layer = strtol(dialog, (char**)&dialog, 10);
1061 /* rescale timing to ASS time base (ms) */
1062 ts_start = av_rescale_q(pkt->pts, tb, av_make_q(1, 100));
1063 if (pkt->duration != -1)
1064 ts_duration = av_rescale_q(pkt->duration, tb, av_make_q(1, 100));
1065 sub->end_display_time = FFMAX(sub->end_display_time, 10 * ts_duration);
1067 /* construct ASS (standalone file form with timestamps) string */
1068 av_bprintf(&buf, "Dialogue: %ld,", layer);
1069 insert_ts(&buf, ts_start);
1070 insert_ts(&buf, ts_duration == -1 ? -1 : ts_start + ts_duration);
1071 av_bprintf(&buf, "%s\r\n", dialog);
1073 final_dialog = av_strdup(buf.str);
1074 if (!av_bprint_is_complete(&buf) || !final_dialog) {
1075 av_freep(&final_dialog);
1076 av_bprint_finalize(&buf, NULL);
1077 return AVERROR(ENOMEM);
1079 av_freep(&rect->ass);
1080 rect->ass = final_dialog;
1083 av_bprint_finalize(&buf, NULL);
1088 int avcodec_decode_subtitle2(AVCodecContext *avctx, AVSubtitle *sub,
1094 if (!avpkt->data && avpkt->size) {
1095 av_log(avctx, AV_LOG_ERROR, "invalid packet: NULL data, size != 0\n");
1096 return AVERROR(EINVAL);
1099 return AVERROR(EINVAL);
1100 if (avctx->codec->type != AVMEDIA_TYPE_SUBTITLE) {
1101 av_log(avctx, AV_LOG_ERROR, "Invalid media type for subtitles\n");
1102 return AVERROR(EINVAL);
1106 get_subtitle_defaults(sub);
1108 if ((avctx->codec->capabilities & AV_CODEC_CAP_DELAY) || avpkt->size) {
1109 AVPacket pkt_recoded = *avpkt;
1111 ret = recode_subtitle(avctx, &pkt_recoded, avpkt);
1115 ret = extract_packet_props(avctx->internal, &pkt_recoded);
1119 if (avctx->pkt_timebase.num && avpkt->pts != AV_NOPTS_VALUE)
1120 sub->pts = av_rescale_q(avpkt->pts,
1121 avctx->pkt_timebase, AV_TIME_BASE_Q);
1122 ret = avctx->codec->decode(avctx, sub, got_sub_ptr, &pkt_recoded);
1123 av_assert1((ret >= 0) >= !!*got_sub_ptr &&
1124 !!*got_sub_ptr >= !!sub->num_rects);
1126 #if FF_API_ASS_TIMING
1127 if (avctx->sub_text_format == FF_SUB_TEXT_FMT_ASS_WITH_TIMINGS
1128 && *got_sub_ptr && sub->num_rects) {
1129 const AVRational tb = avctx->pkt_timebase.num ? avctx->pkt_timebase
1131 int err = convert_sub_to_old_ass_form(sub, avpkt, tb);
1137 if (sub->num_rects && !sub->end_display_time && avpkt->duration &&
1138 avctx->pkt_timebase.num) {
1139 AVRational ms = { 1, 1000 };
1140 sub->end_display_time = av_rescale_q(avpkt->duration,
1141 avctx->pkt_timebase, ms);
1144 if (avctx->codec_descriptor->props & AV_CODEC_PROP_BITMAP_SUB)
1146 else if (avctx->codec_descriptor->props & AV_CODEC_PROP_TEXT_SUB)
1149 for (i = 0; i < sub->num_rects; i++) {
1150 if (avctx->sub_charenc_mode != FF_SUB_CHARENC_MODE_IGNORE &&
1151 sub->rects[i]->ass && !utf8_check(sub->rects[i]->ass)) {
1152 av_log(avctx, AV_LOG_ERROR,
1153 "Invalid UTF-8 in decoded subtitles text; "
1154 "maybe missing -sub_charenc option\n");
1155 avsubtitle_free(sub);
1156 ret = AVERROR_INVALIDDATA;
1161 if (avpkt->data != pkt_recoded.data) { // did we recode?
1162 /* prevent from destroying side data from original packet */
1163 pkt_recoded.side_data = NULL;
1164 pkt_recoded.side_data_elems = 0;
1166 av_packet_unref(&pkt_recoded);
1171 avctx->frame_number++;
1177 enum AVPixelFormat avcodec_default_get_format(struct AVCodecContext *avctx,
1178 const enum AVPixelFormat *fmt)
1180 const AVPixFmtDescriptor *desc;
1181 const AVCodecHWConfig *config;
1184 // If a device was supplied when the codec was opened, assume that the
1185 // user wants to use it.
1186 if (avctx->hw_device_ctx && avctx->codec->hw_configs) {
1187 AVHWDeviceContext *device_ctx =
1188 (AVHWDeviceContext*)avctx->hw_device_ctx->data;
1190 config = &avctx->codec->hw_configs[i]->public;
1193 if (!(config->methods &
1194 AV_CODEC_HW_CONFIG_METHOD_HW_DEVICE_CTX))
1196 if (device_ctx->type != config->device_type)
1198 for (n = 0; fmt[n] != AV_PIX_FMT_NONE; n++) {
1199 if (config->pix_fmt == fmt[n])
1204 // No device or other setup, so we have to choose from things which
1205 // don't any other external information.
1207 // If the last element of the list is a software format, choose it
1208 // (this should be best software format if any exist).
1209 for (n = 0; fmt[n] != AV_PIX_FMT_NONE; n++);
1210 desc = av_pix_fmt_desc_get(fmt[n - 1]);
1211 if (!(desc->flags & AV_PIX_FMT_FLAG_HWACCEL))
1214 // Finally, traverse the list in order and choose the first entry
1215 // with no external dependencies (if there is no hardware configuration
1216 // information available then this just picks the first entry).
1217 for (n = 0; fmt[n] != AV_PIX_FMT_NONE; n++) {
1219 config = avcodec_get_hw_config(avctx->codec, i);
1222 if (config->pix_fmt == fmt[n])
1226 // No specific config available, so the decoder must be able
1227 // to handle this format without any additional setup.
1230 if (config->methods & AV_CODEC_HW_CONFIG_METHOD_INTERNAL) {
1231 // Usable with only internal setup.
1236 // Nothing is usable, give up.
1237 return AV_PIX_FMT_NONE;
1240 int ff_decode_get_hw_frames_ctx(AVCodecContext *avctx,
1241 enum AVHWDeviceType dev_type)
1243 AVHWDeviceContext *device_ctx;
1244 AVHWFramesContext *frames_ctx;
1247 if (!avctx->hwaccel)
1248 return AVERROR(ENOSYS);
1250 if (avctx->hw_frames_ctx)
1252 if (!avctx->hw_device_ctx) {
1253 av_log(avctx, AV_LOG_ERROR, "A hardware frames or device context is "
1254 "required for hardware accelerated decoding.\n");
1255 return AVERROR(EINVAL);
1258 device_ctx = (AVHWDeviceContext *)avctx->hw_device_ctx->data;
1259 if (device_ctx->type != dev_type) {
1260 av_log(avctx, AV_LOG_ERROR, "Device type %s expected for hardware "
1261 "decoding, but got %s.\n", av_hwdevice_get_type_name(dev_type),
1262 av_hwdevice_get_type_name(device_ctx->type));
1263 return AVERROR(EINVAL);
1266 ret = avcodec_get_hw_frames_parameters(avctx,
1267 avctx->hw_device_ctx,
1268 avctx->hwaccel->pix_fmt,
1269 &avctx->hw_frames_ctx);
1273 frames_ctx = (AVHWFramesContext*)avctx->hw_frames_ctx->data;
1276 if (frames_ctx->initial_pool_size) {
1277 // We guarantee 4 base work surfaces. The function above guarantees 1
1278 // (the absolute minimum), so add the missing count.
1279 frames_ctx->initial_pool_size += 3;
1282 ret = av_hwframe_ctx_init(avctx->hw_frames_ctx);
1284 av_buffer_unref(&avctx->hw_frames_ctx);
1291 int avcodec_get_hw_frames_parameters(AVCodecContext *avctx,
1292 AVBufferRef *device_ref,
1293 enum AVPixelFormat hw_pix_fmt,
1294 AVBufferRef **out_frames_ref)
1296 AVBufferRef *frames_ref = NULL;
1297 const AVCodecHWConfigInternal *hw_config;
1298 const AVHWAccel *hwa;
1302 hw_config = avctx->codec->hw_configs[i];
1304 return AVERROR(ENOENT);
1305 if (hw_config->public.pix_fmt == hw_pix_fmt)
1309 hwa = hw_config->hwaccel;
1310 if (!hwa || !hwa->frame_params)
1311 return AVERROR(ENOENT);
1313 frames_ref = av_hwframe_ctx_alloc(device_ref);
1315 return AVERROR(ENOMEM);
1317 ret = hwa->frame_params(avctx, frames_ref);
1319 AVHWFramesContext *frames_ctx = (AVHWFramesContext*)frames_ref->data;
1321 if (frames_ctx->initial_pool_size) {
1322 // If the user has requested that extra output surfaces be
1323 // available then add them here.
1324 if (avctx->extra_hw_frames > 0)
1325 frames_ctx->initial_pool_size += avctx->extra_hw_frames;
1327 // If frame threading is enabled then an extra surface per thread
1328 // is also required.
1329 if (avctx->active_thread_type & FF_THREAD_FRAME)
1330 frames_ctx->initial_pool_size += avctx->thread_count;
1333 *out_frames_ref = frames_ref;
1335 av_buffer_unref(&frames_ref);
1340 static int hwaccel_init(AVCodecContext *avctx,
1341 const AVCodecHWConfigInternal *hw_config)
1343 const AVHWAccel *hwaccel;
1346 hwaccel = hw_config->hwaccel;
1347 if (hwaccel->capabilities & AV_HWACCEL_CODEC_CAP_EXPERIMENTAL &&
1348 avctx->strict_std_compliance > FF_COMPLIANCE_EXPERIMENTAL) {
1349 av_log(avctx, AV_LOG_WARNING, "Ignoring experimental hwaccel: %s\n",
1351 return AVERROR_PATCHWELCOME;
1354 if (hwaccel->priv_data_size) {
1355 avctx->internal->hwaccel_priv_data =
1356 av_mallocz(hwaccel->priv_data_size);
1357 if (!avctx->internal->hwaccel_priv_data)
1358 return AVERROR(ENOMEM);
1361 avctx->hwaccel = hwaccel;
1362 if (hwaccel->init) {
1363 err = hwaccel->init(avctx);
1365 av_log(avctx, AV_LOG_ERROR, "Failed setup for format %s: "
1366 "hwaccel initialisation returned error.\n",
1367 av_get_pix_fmt_name(hw_config->public.pix_fmt));
1368 av_freep(&avctx->internal->hwaccel_priv_data);
1369 avctx->hwaccel = NULL;
1377 static void hwaccel_uninit(AVCodecContext *avctx)
1379 if (avctx->hwaccel && avctx->hwaccel->uninit)
1380 avctx->hwaccel->uninit(avctx);
1382 av_freep(&avctx->internal->hwaccel_priv_data);
1384 avctx->hwaccel = NULL;
1386 av_buffer_unref(&avctx->hw_frames_ctx);
1389 int ff_get_format(AVCodecContext *avctx, const enum AVPixelFormat *fmt)
1391 const AVPixFmtDescriptor *desc;
1392 enum AVPixelFormat *choices;
1393 enum AVPixelFormat ret, user_choice;
1394 const AVCodecHWConfigInternal *hw_config;
1395 const AVCodecHWConfig *config;
1398 // Find end of list.
1399 for (n = 0; fmt[n] != AV_PIX_FMT_NONE; n++);
1400 // Must contain at least one entry.
1402 // If a software format is available, it must be the last entry.
1403 desc = av_pix_fmt_desc_get(fmt[n - 1]);
1404 if (desc->flags & AV_PIX_FMT_FLAG_HWACCEL) {
1405 // No software format is available.
1407 avctx->sw_pix_fmt = fmt[n - 1];
1410 choices = av_malloc_array(n + 1, sizeof(*choices));
1412 return AV_PIX_FMT_NONE;
1414 memcpy(choices, fmt, (n + 1) * sizeof(*choices));
1417 // Remove the previous hwaccel, if there was one.
1418 hwaccel_uninit(avctx);
1420 user_choice = avctx->get_format(avctx, choices);
1421 if (user_choice == AV_PIX_FMT_NONE) {
1422 // Explicitly chose nothing, give up.
1423 ret = AV_PIX_FMT_NONE;
1427 desc = av_pix_fmt_desc_get(user_choice);
1429 av_log(avctx, AV_LOG_ERROR, "Invalid format returned by "
1430 "get_format() callback.\n");
1431 ret = AV_PIX_FMT_NONE;
1434 av_log(avctx, AV_LOG_DEBUG, "Format %s chosen by get_format().\n",
1437 for (i = 0; i < n; i++) {
1438 if (choices[i] == user_choice)
1442 av_log(avctx, AV_LOG_ERROR, "Invalid return from get_format(): "
1443 "%s not in possible list.\n", desc->name);
1444 ret = AV_PIX_FMT_NONE;
1448 if (avctx->codec->hw_configs) {
1450 hw_config = avctx->codec->hw_configs[i];
1453 if (hw_config->public.pix_fmt == user_choice)
1461 // No config available, so no extra setup required.
1465 config = &hw_config->public;
1467 if (config->methods &
1468 AV_CODEC_HW_CONFIG_METHOD_HW_FRAMES_CTX &&
1469 avctx->hw_frames_ctx) {
1470 const AVHWFramesContext *frames_ctx =
1471 (AVHWFramesContext*)avctx->hw_frames_ctx->data;
1472 if (frames_ctx->format != user_choice) {
1473 av_log(avctx, AV_LOG_ERROR, "Invalid setup for format %s: "
1474 "does not match the format of the provided frames "
1475 "context.\n", desc->name);
1478 } else if (config->methods &
1479 AV_CODEC_HW_CONFIG_METHOD_HW_DEVICE_CTX &&
1480 avctx->hw_device_ctx) {
1481 const AVHWDeviceContext *device_ctx =
1482 (AVHWDeviceContext*)avctx->hw_device_ctx->data;
1483 if (device_ctx->type != config->device_type) {
1484 av_log(avctx, AV_LOG_ERROR, "Invalid setup for format %s: "
1485 "does not match the type of the provided device "
1486 "context.\n", desc->name);
1489 } else if (config->methods &
1490 AV_CODEC_HW_CONFIG_METHOD_INTERNAL) {
1491 // Internal-only setup, no additional configuration.
1492 } else if (config->methods &
1493 AV_CODEC_HW_CONFIG_METHOD_AD_HOC) {
1494 // Some ad-hoc configuration we can't see and can't check.
1496 av_log(avctx, AV_LOG_ERROR, "Invalid setup for format %s: "
1497 "missing configuration.\n", desc->name);
1500 if (hw_config->hwaccel) {
1501 av_log(avctx, AV_LOG_DEBUG, "Format %s requires hwaccel "
1502 "initialisation.\n", desc->name);
1503 err = hwaccel_init(avctx, hw_config);
1511 av_log(avctx, AV_LOG_DEBUG, "Format %s not usable, retrying "
1512 "get_format() without it.\n", desc->name);
1513 for (i = 0; i < n; i++) {
1514 if (choices[i] == user_choice)
1517 for (; i + 1 < n; i++)
1518 choices[i] = choices[i + 1];
1526 static void frame_pool_free(void *opaque, uint8_t *data)
1528 FramePool *pool = (FramePool*)data;
1531 for (i = 0; i < FF_ARRAY_ELEMS(pool->pools); i++)
1532 av_buffer_pool_uninit(&pool->pools[i]);
1537 static AVBufferRef *frame_pool_alloc(void)
1539 FramePool *pool = av_mallocz(sizeof(*pool));
1545 buf = av_buffer_create((uint8_t*)pool, sizeof(*pool),
1546 frame_pool_free, NULL, 0);
1555 static int update_frame_pool(AVCodecContext *avctx, AVFrame *frame)
1557 FramePool *pool = avctx->internal->pool ?
1558 (FramePool*)avctx->internal->pool->data : NULL;
1559 AVBufferRef *pool_buf;
1560 int i, ret, ch, planes;
1562 if (avctx->codec_type == AVMEDIA_TYPE_AUDIO) {
1563 int planar = av_sample_fmt_is_planar(frame->format);
1564 ch = frame->channels;
1565 planes = planar ? ch : 1;
1568 if (pool && pool->format == frame->format) {
1569 if (avctx->codec_type == AVMEDIA_TYPE_VIDEO &&
1570 pool->width == frame->width && pool->height == frame->height)
1572 if (avctx->codec_type == AVMEDIA_TYPE_AUDIO && pool->planes == planes &&
1573 pool->channels == ch && frame->nb_samples == pool->samples)
1577 pool_buf = frame_pool_alloc();
1579 return AVERROR(ENOMEM);
1580 pool = (FramePool*)pool_buf->data;
1582 switch (avctx->codec_type) {
1583 case AVMEDIA_TYPE_VIDEO: {
1586 int size[4] = { 0 };
1587 int w = frame->width;
1588 int h = frame->height;
1589 int tmpsize, unaligned;
1591 avcodec_align_dimensions2(avctx, &w, &h, pool->stride_align);
1594 // NOTE: do not align linesizes individually, this breaks e.g. assumptions
1595 // that linesize[0] == 2*linesize[1] in the MPEG-encoder for 4:2:2
1596 ret = av_image_fill_linesizes(linesize, avctx->pix_fmt, w);
1599 // increase alignment of w for next try (rhs gives the lowest bit set in w)
1603 for (i = 0; i < 4; i++)
1604 unaligned |= linesize[i] % pool->stride_align[i];
1605 } while (unaligned);
1607 tmpsize = av_image_fill_pointers(data, avctx->pix_fmt, h,
1614 for (i = 0; i < 3 && data[i + 1]; i++)
1615 size[i] = data[i + 1] - data[i];
1616 size[i] = tmpsize - (data[i] - data[0]);
1618 for (i = 0; i < 4; i++) {
1619 pool->linesize[i] = linesize[i];
1621 pool->pools[i] = av_buffer_pool_init(size[i] + 16 + STRIDE_ALIGN - 1,
1622 CONFIG_MEMORY_POISONING ?
1625 if (!pool->pools[i]) {
1626 ret = AVERROR(ENOMEM);
1631 pool->format = frame->format;
1632 pool->width = frame->width;
1633 pool->height = frame->height;
1637 case AVMEDIA_TYPE_AUDIO: {
1638 ret = av_samples_get_buffer_size(&pool->linesize[0], ch,
1639 frame->nb_samples, frame->format, 0);
1643 pool->pools[0] = av_buffer_pool_init(pool->linesize[0], NULL);
1644 if (!pool->pools[0]) {
1645 ret = AVERROR(ENOMEM);
1649 pool->format = frame->format;
1650 pool->planes = planes;
1651 pool->channels = ch;
1652 pool->samples = frame->nb_samples;
1655 default: av_assert0(0);
1658 av_buffer_unref(&avctx->internal->pool);
1659 avctx->internal->pool = pool_buf;
1663 av_buffer_unref(&pool_buf);
1667 static int audio_get_buffer(AVCodecContext *avctx, AVFrame *frame)
1669 FramePool *pool = (FramePool*)avctx->internal->pool->data;
1670 int planes = pool->planes;
1673 frame->linesize[0] = pool->linesize[0];
1675 if (planes > AV_NUM_DATA_POINTERS) {
1676 frame->extended_data = av_mallocz_array(planes, sizeof(*frame->extended_data));
1677 frame->nb_extended_buf = planes - AV_NUM_DATA_POINTERS;
1678 frame->extended_buf = av_mallocz_array(frame->nb_extended_buf,
1679 sizeof(*frame->extended_buf));
1680 if (!frame->extended_data || !frame->extended_buf) {
1681 av_freep(&frame->extended_data);
1682 av_freep(&frame->extended_buf);
1683 return AVERROR(ENOMEM);
1686 frame->extended_data = frame->data;
1687 av_assert0(frame->nb_extended_buf == 0);
1690 for (i = 0; i < FFMIN(planes, AV_NUM_DATA_POINTERS); i++) {
1691 frame->buf[i] = av_buffer_pool_get(pool->pools[0]);
1694 frame->extended_data[i] = frame->data[i] = frame->buf[i]->data;
1696 for (i = 0; i < frame->nb_extended_buf; i++) {
1697 frame->extended_buf[i] = av_buffer_pool_get(pool->pools[0]);
1698 if (!frame->extended_buf[i])
1700 frame->extended_data[i + AV_NUM_DATA_POINTERS] = frame->extended_buf[i]->data;
1703 if (avctx->debug & FF_DEBUG_BUFFERS)
1704 av_log(avctx, AV_LOG_DEBUG, "default_get_buffer called on frame %p", frame);
1708 av_frame_unref(frame);
1709 return AVERROR(ENOMEM);
1712 static int video_get_buffer(AVCodecContext *s, AVFrame *pic)
1714 FramePool *pool = (FramePool*)s->internal->pool->data;
1715 const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(pic->format);
1718 if (pic->data[0] || pic->data[1] || pic->data[2] || pic->data[3]) {
1719 av_log(s, AV_LOG_ERROR, "pic->data[*]!=NULL in avcodec_default_get_buffer\n");
1724 av_log(s, AV_LOG_ERROR,
1725 "Unable to get pixel format descriptor for format %s\n",
1726 av_get_pix_fmt_name(pic->format));
1727 return AVERROR(EINVAL);
1730 memset(pic->data, 0, sizeof(pic->data));
1731 pic->extended_data = pic->data;
1733 for (i = 0; i < 4 && pool->pools[i]; i++) {
1734 pic->linesize[i] = pool->linesize[i];
1736 pic->buf[i] = av_buffer_pool_get(pool->pools[i]);
1740 pic->data[i] = pic->buf[i]->data;
1742 for (; i < AV_NUM_DATA_POINTERS; i++) {
1743 pic->data[i] = NULL;
1744 pic->linesize[i] = 0;
1746 if (desc->flags & AV_PIX_FMT_FLAG_PAL ||
1747 ((desc->flags & FF_PSEUDOPAL) && pic->data[1]))
1748 avpriv_set_systematic_pal2((uint32_t *)pic->data[1], pic->format);
1750 if (s->debug & FF_DEBUG_BUFFERS)
1751 av_log(s, AV_LOG_DEBUG, "default_get_buffer called on pic %p\n", pic);
1755 av_frame_unref(pic);
1756 return AVERROR(ENOMEM);
1759 int avcodec_default_get_buffer2(AVCodecContext *avctx, AVFrame *frame, int flags)
1763 if (avctx->hw_frames_ctx) {
1764 ret = av_hwframe_get_buffer(avctx->hw_frames_ctx, frame, 0);
1765 frame->width = avctx->coded_width;
1766 frame->height = avctx->coded_height;
1770 if ((ret = update_frame_pool(avctx, frame)) < 0)
1773 switch (avctx->codec_type) {
1774 case AVMEDIA_TYPE_VIDEO:
1775 return video_get_buffer(avctx, frame);
1776 case AVMEDIA_TYPE_AUDIO:
1777 return audio_get_buffer(avctx, frame);
1783 static int add_metadata_from_side_data(const AVPacket *avpkt, AVFrame *frame)
1786 const uint8_t *side_metadata;
1788 AVDictionary **frame_md = &frame->metadata;
1790 side_metadata = av_packet_get_side_data(avpkt,
1791 AV_PKT_DATA_STRINGS_METADATA, &size);
1792 return av_packet_unpack_dictionary(side_metadata, size, frame_md);
1795 int ff_decode_frame_props(AVCodecContext *avctx, AVFrame *frame)
1797 const AVPacket *pkt = avctx->internal->last_pkt_props;
1799 static const struct {
1800 enum AVPacketSideDataType packet;
1801 enum AVFrameSideDataType frame;
1803 { AV_PKT_DATA_REPLAYGAIN , AV_FRAME_DATA_REPLAYGAIN },
1804 { AV_PKT_DATA_DISPLAYMATRIX, AV_FRAME_DATA_DISPLAYMATRIX },
1805 { AV_PKT_DATA_SPHERICAL, AV_FRAME_DATA_SPHERICAL },
1806 { AV_PKT_DATA_STEREO3D, AV_FRAME_DATA_STEREO3D },
1807 { AV_PKT_DATA_AUDIO_SERVICE_TYPE, AV_FRAME_DATA_AUDIO_SERVICE_TYPE },
1808 { AV_PKT_DATA_MASTERING_DISPLAY_METADATA, AV_FRAME_DATA_MASTERING_DISPLAY_METADATA },
1809 { AV_PKT_DATA_CONTENT_LIGHT_LEVEL, AV_FRAME_DATA_CONTENT_LIGHT_LEVEL },
1810 { AV_PKT_DATA_A53_CC, AV_FRAME_DATA_A53_CC },
1811 { AV_PKT_DATA_ICC_PROFILE, AV_FRAME_DATA_ICC_PROFILE },
1815 frame->pts = pkt->pts;
1817 FF_DISABLE_DEPRECATION_WARNINGS
1818 frame->pkt_pts = pkt->pts;
1819 FF_ENABLE_DEPRECATION_WARNINGS
1821 frame->pkt_pos = pkt->pos;
1822 frame->pkt_duration = pkt->duration;
1823 frame->pkt_size = pkt->size;
1825 for (i = 0; i < FF_ARRAY_ELEMS(sd); i++) {
1827 uint8_t *packet_sd = av_packet_get_side_data(pkt, sd[i].packet, &size);
1829 AVFrameSideData *frame_sd = av_frame_new_side_data(frame,
1833 return AVERROR(ENOMEM);
1835 memcpy(frame_sd->data, packet_sd, size);
1838 add_metadata_from_side_data(pkt, frame);
1840 if (pkt->flags & AV_PKT_FLAG_DISCARD) {
1841 frame->flags |= AV_FRAME_FLAG_DISCARD;
1843 frame->flags = (frame->flags & ~AV_FRAME_FLAG_DISCARD);
1846 frame->reordered_opaque = avctx->reordered_opaque;
1848 if (frame->color_primaries == AVCOL_PRI_UNSPECIFIED)
1849 frame->color_primaries = avctx->color_primaries;
1850 if (frame->color_trc == AVCOL_TRC_UNSPECIFIED)
1851 frame->color_trc = avctx->color_trc;
1852 if (frame->colorspace == AVCOL_SPC_UNSPECIFIED)
1853 frame->colorspace = avctx->colorspace;
1854 if (frame->color_range == AVCOL_RANGE_UNSPECIFIED)
1855 frame->color_range = avctx->color_range;
1856 if (frame->chroma_location == AVCHROMA_LOC_UNSPECIFIED)
1857 frame->chroma_location = avctx->chroma_sample_location;
1859 switch (avctx->codec->type) {
1860 case AVMEDIA_TYPE_VIDEO:
1861 frame->format = avctx->pix_fmt;
1862 if (!frame->sample_aspect_ratio.num)
1863 frame->sample_aspect_ratio = avctx->sample_aspect_ratio;
1865 if (frame->width && frame->height &&
1866 av_image_check_sar(frame->width, frame->height,
1867 frame->sample_aspect_ratio) < 0) {
1868 av_log(avctx, AV_LOG_WARNING, "ignoring invalid SAR: %u/%u\n",
1869 frame->sample_aspect_ratio.num,
1870 frame->sample_aspect_ratio.den);
1871 frame->sample_aspect_ratio = (AVRational){ 0, 1 };
1875 case AVMEDIA_TYPE_AUDIO:
1876 if (!frame->sample_rate)
1877 frame->sample_rate = avctx->sample_rate;
1878 if (frame->format < 0)
1879 frame->format = avctx->sample_fmt;
1880 if (!frame->channel_layout) {
1881 if (avctx->channel_layout) {
1882 if (av_get_channel_layout_nb_channels(avctx->channel_layout) !=
1884 av_log(avctx, AV_LOG_ERROR, "Inconsistent channel "
1885 "configuration.\n");
1886 return AVERROR(EINVAL);
1889 frame->channel_layout = avctx->channel_layout;
1891 if (avctx->channels > FF_SANE_NB_CHANNELS) {
1892 av_log(avctx, AV_LOG_ERROR, "Too many channels: %d.\n",
1894 return AVERROR(ENOSYS);
1898 frame->channels = avctx->channels;
1904 static void validate_avframe_allocation(AVCodecContext *avctx, AVFrame *frame)
1906 if (avctx->codec_type == AVMEDIA_TYPE_VIDEO) {
1908 int num_planes = av_pix_fmt_count_planes(frame->format);
1909 const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(frame->format);
1910 int flags = desc ? desc->flags : 0;
1911 if (num_planes == 1 && (flags & AV_PIX_FMT_FLAG_PAL))
1913 if ((flags & FF_PSEUDOPAL) && frame->data[1])
1915 for (i = 0; i < num_planes; i++) {
1916 av_assert0(frame->data[i]);
1918 // For formats without data like hwaccel allow unused pointers to be non-NULL.
1919 for (i = num_planes; num_planes > 0 && i < FF_ARRAY_ELEMS(frame->data); i++) {
1921 av_log(avctx, AV_LOG_ERROR, "Buffer returned by get_buffer2() did not zero unused plane pointers\n");
1922 frame->data[i] = NULL;
1927 static void decode_data_free(void *opaque, uint8_t *data)
1929 FrameDecodeData *fdd = (FrameDecodeData*)data;
1931 if (fdd->post_process_opaque_free)
1932 fdd->post_process_opaque_free(fdd->post_process_opaque);
1934 if (fdd->hwaccel_priv_free)
1935 fdd->hwaccel_priv_free(fdd->hwaccel_priv);
1940 int ff_attach_decode_data(AVFrame *frame)
1942 AVBufferRef *fdd_buf;
1943 FrameDecodeData *fdd;
1945 av_assert1(!frame->private_ref);
1946 av_buffer_unref(&frame->private_ref);
1948 fdd = av_mallocz(sizeof(*fdd));
1950 return AVERROR(ENOMEM);
1952 fdd_buf = av_buffer_create((uint8_t*)fdd, sizeof(*fdd), decode_data_free,
1953 NULL, AV_BUFFER_FLAG_READONLY);
1956 return AVERROR(ENOMEM);
1959 frame->private_ref = fdd_buf;
1964 int ff_get_buffer(AVCodecContext *avctx, AVFrame *frame, int flags)
1966 const AVHWAccel *hwaccel = avctx->hwaccel;
1967 int override_dimensions = 1;
1970 if (avctx->codec_type == AVMEDIA_TYPE_VIDEO) {
1971 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) {
1972 av_log(avctx, AV_LOG_ERROR, "video_get_buffer: image parameters invalid\n");
1973 ret = AVERROR(EINVAL);
1977 if (frame->width <= 0 || frame->height <= 0) {
1978 frame->width = FFMAX(avctx->width, AV_CEIL_RSHIFT(avctx->coded_width, avctx->lowres));
1979 frame->height = FFMAX(avctx->height, AV_CEIL_RSHIFT(avctx->coded_height, avctx->lowres));
1980 override_dimensions = 0;
1983 if (frame->data[0] || frame->data[1] || frame->data[2] || frame->data[3]) {
1984 av_log(avctx, AV_LOG_ERROR, "pic->data[*]!=NULL in get_buffer_internal\n");
1985 ret = AVERROR(EINVAL);
1988 } else if (avctx->codec_type == AVMEDIA_TYPE_AUDIO) {
1989 if (frame->nb_samples * (int64_t)avctx->channels > avctx->max_samples) {
1990 av_log(avctx, AV_LOG_ERROR, "samples per frame %d, exceeds max_samples %"PRId64"\n", frame->nb_samples, avctx->max_samples);
1991 ret = AVERROR(EINVAL);
1995 ret = ff_decode_frame_props(avctx, frame);
2000 if (hwaccel->alloc_frame) {
2001 ret = hwaccel->alloc_frame(avctx, frame);
2005 avctx->sw_pix_fmt = avctx->pix_fmt;
2007 ret = avctx->get_buffer2(avctx, frame, flags);
2011 validate_avframe_allocation(avctx, frame);
2013 ret = ff_attach_decode_data(frame);
2017 if (avctx->codec_type == AVMEDIA_TYPE_VIDEO && !override_dimensions &&
2018 !(avctx->codec->caps_internal & FF_CODEC_CAP_EXPORTS_CROPPING)) {
2019 frame->width = avctx->width;
2020 frame->height = avctx->height;
2025 av_log(avctx, AV_LOG_ERROR, "get_buffer() failed\n");
2026 av_frame_unref(frame);
2030 static int reget_buffer_internal(AVCodecContext *avctx, AVFrame *frame, int flags)
2035 av_assert0(avctx->codec_type == AVMEDIA_TYPE_VIDEO);
2037 if (frame->data[0] && (frame->width != avctx->width || frame->height != avctx->height || frame->format != avctx->pix_fmt)) {
2038 av_log(avctx, AV_LOG_WARNING, "Picture changed from size:%dx%d fmt:%s to size:%dx%d fmt:%s in reget buffer()\n",
2039 frame->width, frame->height, av_get_pix_fmt_name(frame->format), avctx->width, avctx->height, av_get_pix_fmt_name(avctx->pix_fmt));
2040 av_frame_unref(frame);
2043 if (!frame->data[0])
2044 return ff_get_buffer(avctx, frame, AV_GET_BUFFER_FLAG_REF);
2046 if ((flags & FF_REGET_BUFFER_FLAG_READONLY) || av_frame_is_writable(frame))
2047 return ff_decode_frame_props(avctx, frame);
2049 tmp = av_frame_alloc();
2051 return AVERROR(ENOMEM);
2053 av_frame_move_ref(tmp, frame);
2055 ret = ff_get_buffer(avctx, frame, AV_GET_BUFFER_FLAG_REF);
2057 av_frame_free(&tmp);
2061 av_frame_copy(frame, tmp);
2062 av_frame_free(&tmp);
2067 int ff_reget_buffer(AVCodecContext *avctx, AVFrame *frame, int flags)
2069 int ret = reget_buffer_internal(avctx, frame, flags);
2071 av_log(avctx, AV_LOG_ERROR, "reget_buffer() failed\n");
2075 static void bsfs_flush(AVCodecContext *avctx)
2077 DecodeFilterContext *s = &avctx->internal->filter;
2079 for (int i = 0; i < s->nb_bsfs; i++)
2080 av_bsf_flush(s->bsfs[i]);
2083 void avcodec_flush_buffers(AVCodecContext *avctx)
2085 AVCodecInternal *avci = avctx->internal;
2087 if (av_codec_is_encoder(avctx->codec)) {
2088 int caps = avctx->codec->capabilities;
2090 if (!(caps & AV_CODEC_CAP_ENCODER_FLUSH)) {
2091 // Only encoders that explicitly declare support for it can be
2092 // flushed. Otherwise, this is a no-op.
2093 av_log(avctx, AV_LOG_WARNING, "Ignoring attempt to flush encoder "
2094 "that doesn't support it\n");
2098 // We haven't implemented flushing for frame-threaded encoders.
2099 av_assert0(!(caps & AV_CODEC_CAP_FRAME_THREADS));
2103 avci->draining_done = 0;
2104 avci->nb_draining_errors = 0;
2105 av_frame_unref(avci->buffer_frame);
2106 av_frame_unref(avci->compat_decode_frame);
2107 av_packet_unref(avci->buffer_pkt);
2108 avci->buffer_pkt_valid = 0;
2110 av_packet_unref(avci->ds.in_pkt);
2112 if (HAVE_THREADS && avctx->active_thread_type & FF_THREAD_FRAME)
2113 ff_thread_flush(avctx);
2114 else if (avctx->codec->flush)
2115 avctx->codec->flush(avctx);
2117 avctx->pts_correction_last_pts =
2118 avctx->pts_correction_last_dts = INT64_MIN;
2122 if (!avctx->refcounted_frames)
2123 av_frame_unref(avci->to_free);
2126 void ff_decode_bsfs_uninit(AVCodecContext *avctx)
2128 DecodeFilterContext *s = &avctx->internal->filter;
2131 for (i = 0; i < s->nb_bsfs; i++)
2132 av_bsf_free(&s->bsfs[i]);