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 static int 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);
246 av_packet_unref(pkt);
251 * Attempt to guess proper monotonic timestamps for decoded video frames
252 * which might have incorrect times. Input timestamps may wrap around, in
253 * which case the output will as well.
255 * @param pts the pts field of the decoded AVPacket, as passed through
257 * @param dts the dts field of the decoded AVPacket
258 * @return one of the input values, may be AV_NOPTS_VALUE
260 static int64_t guess_correct_pts(AVCodecContext *ctx,
261 int64_t reordered_pts, int64_t dts)
263 int64_t pts = AV_NOPTS_VALUE;
265 if (dts != AV_NOPTS_VALUE) {
266 ctx->pts_correction_num_faulty_dts += dts <= ctx->pts_correction_last_dts;
267 ctx->pts_correction_last_dts = dts;
268 } else if (reordered_pts != AV_NOPTS_VALUE)
269 ctx->pts_correction_last_dts = reordered_pts;
271 if (reordered_pts != AV_NOPTS_VALUE) {
272 ctx->pts_correction_num_faulty_pts += reordered_pts <= ctx->pts_correction_last_pts;
273 ctx->pts_correction_last_pts = reordered_pts;
274 } else if(dts != AV_NOPTS_VALUE)
275 ctx->pts_correction_last_pts = dts;
277 if ((ctx->pts_correction_num_faulty_pts<=ctx->pts_correction_num_faulty_dts || dts == AV_NOPTS_VALUE)
278 && reordered_pts != AV_NOPTS_VALUE)
287 * The core of the receive_frame_wrapper for the decoders implementing
288 * the simple API. Certain decoders might consume partial packets without
289 * returning any output, so this function needs to be called in a loop until it
292 static inline int decode_simple_internal(AVCodecContext *avctx, AVFrame *frame, int64_t *discarded_samples)
294 AVCodecInternal *avci = avctx->internal;
295 DecodeSimpleContext *ds = &avci->ds;
296 AVPacket *pkt = ds->in_pkt;
297 int got_frame, actual_got_frame;
300 if (!pkt->data && !avci->draining) {
301 av_packet_unref(pkt);
302 ret = ff_decode_get_packet(avctx, pkt);
303 if (ret < 0 && ret != AVERROR_EOF)
307 // Some codecs (at least wma lossless) will crash when feeding drain packets
308 // after EOF was signaled.
309 if (avci->draining_done)
313 !(avctx->codec->capabilities & AV_CODEC_CAP_DELAY ||
314 avctx->active_thread_type & FF_THREAD_FRAME))
319 if (HAVE_THREADS && avctx->active_thread_type & FF_THREAD_FRAME) {
320 ret = ff_thread_decode_frame(avctx, frame, &got_frame, pkt);
322 ret = avctx->codec->decode(avctx, frame, &got_frame, pkt);
324 if (!(avctx->codec->caps_internal & FF_CODEC_CAP_SETS_PKT_DTS))
325 frame->pkt_dts = pkt->dts;
326 if (avctx->codec->type == AVMEDIA_TYPE_VIDEO) {
327 if(!avctx->has_b_frames)
328 frame->pkt_pos = pkt->pos;
329 //FIXME these should be under if(!avctx->has_b_frames)
330 /* get_buffer is supposed to set frame parameters */
331 if (!(avctx->codec->capabilities & AV_CODEC_CAP_DR1)) {
332 if (!frame->sample_aspect_ratio.num) frame->sample_aspect_ratio = avctx->sample_aspect_ratio;
333 if (!frame->width) frame->width = avctx->width;
334 if (!frame->height) frame->height = avctx->height;
335 if (frame->format == AV_PIX_FMT_NONE) frame->format = avctx->pix_fmt;
340 actual_got_frame = got_frame;
342 if (avctx->codec->type == AVMEDIA_TYPE_VIDEO) {
343 if (frame->flags & AV_FRAME_FLAG_DISCARD)
345 } else if (avctx->codec->type == AVMEDIA_TYPE_AUDIO) {
347 buffer_size_t side_size;
348 uint32_t discard_padding = 0;
349 uint8_t skip_reason = 0;
350 uint8_t discard_reason = 0;
352 if (ret >= 0 && got_frame) {
353 if (frame->format == AV_SAMPLE_FMT_NONE)
354 frame->format = avctx->sample_fmt;
355 if (!frame->channel_layout)
356 frame->channel_layout = avctx->channel_layout;
357 if (!frame->channels)
358 frame->channels = avctx->channels;
359 if (!frame->sample_rate)
360 frame->sample_rate = avctx->sample_rate;
363 side= av_packet_get_side_data(avci->last_pkt_props, AV_PKT_DATA_SKIP_SAMPLES, &side_size);
364 if(side && side_size>=10) {
365 avci->skip_samples = AV_RL32(side) * avci->skip_samples_multiplier;
366 discard_padding = AV_RL32(side + 4);
367 av_log(avctx, AV_LOG_DEBUG, "skip %d / discard %d samples due to side data\n",
368 avci->skip_samples, (int)discard_padding);
369 skip_reason = AV_RL8(side + 8);
370 discard_reason = AV_RL8(side + 9);
373 if ((frame->flags & AV_FRAME_FLAG_DISCARD) && got_frame &&
374 !(avctx->flags2 & AV_CODEC_FLAG2_SKIP_MANUAL)) {
375 avci->skip_samples = FFMAX(0, avci->skip_samples - frame->nb_samples);
377 *discarded_samples += frame->nb_samples;
380 if (avci->skip_samples > 0 && got_frame &&
381 !(avctx->flags2 & AV_CODEC_FLAG2_SKIP_MANUAL)) {
382 if(frame->nb_samples <= avci->skip_samples){
384 *discarded_samples += frame->nb_samples;
385 avci->skip_samples -= frame->nb_samples;
386 av_log(avctx, AV_LOG_DEBUG, "skip whole frame, skip left: %d\n",
389 av_samples_copy(frame->extended_data, frame->extended_data, 0, avci->skip_samples,
390 frame->nb_samples - avci->skip_samples, avctx->channels, frame->format);
391 if(avctx->pkt_timebase.num && avctx->sample_rate) {
392 int64_t diff_ts = av_rescale_q(avci->skip_samples,
393 (AVRational){1, avctx->sample_rate},
394 avctx->pkt_timebase);
395 if(frame->pts!=AV_NOPTS_VALUE)
396 frame->pts += diff_ts;
398 FF_DISABLE_DEPRECATION_WARNINGS
399 if(frame->pkt_pts!=AV_NOPTS_VALUE)
400 frame->pkt_pts += diff_ts;
401 FF_ENABLE_DEPRECATION_WARNINGS
403 if(frame->pkt_dts!=AV_NOPTS_VALUE)
404 frame->pkt_dts += diff_ts;
405 if (frame->pkt_duration >= diff_ts)
406 frame->pkt_duration -= diff_ts;
408 av_log(avctx, AV_LOG_WARNING, "Could not update timestamps for skipped samples.\n");
410 av_log(avctx, AV_LOG_DEBUG, "skip %d/%d samples\n",
411 avci->skip_samples, frame->nb_samples);
412 *discarded_samples += avci->skip_samples;
413 frame->nb_samples -= avci->skip_samples;
414 avci->skip_samples = 0;
418 if (discard_padding > 0 && discard_padding <= frame->nb_samples && got_frame &&
419 !(avctx->flags2 & AV_CODEC_FLAG2_SKIP_MANUAL)) {
420 if (discard_padding == frame->nb_samples) {
421 *discarded_samples += frame->nb_samples;
424 if(avctx->pkt_timebase.num && avctx->sample_rate) {
425 int64_t diff_ts = av_rescale_q(frame->nb_samples - discard_padding,
426 (AVRational){1, avctx->sample_rate},
427 avctx->pkt_timebase);
428 frame->pkt_duration = diff_ts;
430 av_log(avctx, AV_LOG_WARNING, "Could not update timestamps for discarded samples.\n");
432 av_log(avctx, AV_LOG_DEBUG, "discard %d/%d samples\n",
433 (int)discard_padding, frame->nb_samples);
434 frame->nb_samples -= discard_padding;
438 if ((avctx->flags2 & AV_CODEC_FLAG2_SKIP_MANUAL) && got_frame) {
439 AVFrameSideData *fside = av_frame_new_side_data(frame, AV_FRAME_DATA_SKIP_SAMPLES, 10);
441 AV_WL32(fside->data, avci->skip_samples);
442 AV_WL32(fside->data + 4, discard_padding);
443 AV_WL8(fside->data + 8, skip_reason);
444 AV_WL8(fside->data + 9, discard_reason);
445 avci->skip_samples = 0;
450 if (avctx->codec->type == AVMEDIA_TYPE_AUDIO &&
451 !avci->showed_multi_packet_warning &&
452 ret >= 0 && ret != pkt->size && !(avctx->codec->capabilities & AV_CODEC_CAP_SUBFRAMES)) {
453 av_log(avctx, AV_LOG_WARNING, "Multiple frames in a packet.\n");
454 avci->showed_multi_packet_warning = 1;
458 av_frame_unref(frame);
460 if (ret >= 0 && avctx->codec->type == AVMEDIA_TYPE_VIDEO && !(avctx->flags & AV_CODEC_FLAG_TRUNCATED))
463 #if FF_API_AVCTX_TIMEBASE
464 if (avctx->framerate.num > 0 && avctx->framerate.den > 0)
465 avctx->time_base = av_inv_q(av_mul_q(avctx->framerate, (AVRational){avctx->ticks_per_frame, 1}));
468 /* do not stop draining when actual_got_frame != 0 or ret < 0 */
469 /* got_frame == 0 but actual_got_frame != 0 when frame is discarded */
470 if (avci->draining && !actual_got_frame) {
472 /* prevent infinite loop if a decoder wrongly always return error on draining */
473 /* reasonable nb_errors_max = maximum b frames + thread count */
474 int nb_errors_max = 20 + (HAVE_THREADS && avctx->active_thread_type & FF_THREAD_FRAME ?
475 avctx->thread_count : 1);
477 if (avci->nb_draining_errors++ >= nb_errors_max) {
478 av_log(avctx, AV_LOG_ERROR, "Too many errors when draining, this is a bug. "
479 "Stop draining and force EOF.\n");
480 avci->draining_done = 1;
484 avci->draining_done = 1;
488 if (ret >= pkt->size || ret < 0) {
489 av_packet_unref(pkt);
490 av_packet_unref(avci->last_pkt_props);
494 pkt->data += consumed;
495 pkt->size -= consumed;
496 avci->last_pkt_props->size -= consumed; // See extract_packet_props() comment.
497 pkt->pts = AV_NOPTS_VALUE;
498 pkt->dts = AV_NOPTS_VALUE;
499 avci->last_pkt_props->pts = AV_NOPTS_VALUE;
500 avci->last_pkt_props->dts = AV_NOPTS_VALUE;
504 av_assert0(frame->buf[0]);
506 return ret < 0 ? ret : 0;
509 static int decode_simple_receive_frame(AVCodecContext *avctx, AVFrame *frame)
512 int64_t discarded_samples = 0;
514 while (!frame->buf[0]) {
515 if (discarded_samples > avctx->max_samples)
516 return AVERROR(EAGAIN);
517 ret = decode_simple_internal(avctx, frame, &discarded_samples);
525 static int decode_receive_frame_internal(AVCodecContext *avctx, AVFrame *frame)
527 AVCodecInternal *avci = avctx->internal;
530 av_assert0(!frame->buf[0]);
532 if (avctx->codec->receive_frame) {
533 ret = avctx->codec->receive_frame(avctx, frame);
534 if (ret != AVERROR(EAGAIN))
535 av_packet_unref(avci->last_pkt_props);
537 ret = decode_simple_receive_frame(avctx, frame);
539 if (ret == AVERROR_EOF)
540 avci->draining_done = 1;
543 frame->best_effort_timestamp = guess_correct_pts(avctx,
547 /* the only case where decode data is not set should be decoders
548 * that do not call ff_get_buffer() */
549 av_assert0((frame->private_ref && frame->private_ref->size == sizeof(FrameDecodeData)) ||
550 !(avctx->codec->capabilities & AV_CODEC_CAP_DR1));
552 if (frame->private_ref) {
553 FrameDecodeData *fdd = (FrameDecodeData*)frame->private_ref->data;
555 if (fdd->post_process) {
556 ret = fdd->post_process(avctx, frame);
558 av_frame_unref(frame);
565 /* free the per-frame decode data */
566 av_buffer_unref(&frame->private_ref);
571 int attribute_align_arg avcodec_send_packet(AVCodecContext *avctx, const AVPacket *avpkt)
573 AVCodecInternal *avci = avctx->internal;
576 if (!avcodec_is_open(avctx) || !av_codec_is_decoder(avctx->codec))
577 return AVERROR(EINVAL);
579 if (avctx->internal->draining)
582 if (avpkt && !avpkt->size && avpkt->data)
583 return AVERROR(EINVAL);
585 av_packet_unref(avci->buffer_pkt);
586 if (avpkt && (avpkt->data || avpkt->side_data_elems)) {
587 ret = av_packet_ref(avci->buffer_pkt, avpkt);
592 ret = av_bsf_send_packet(avci->bsf, avci->buffer_pkt);
594 av_packet_unref(avci->buffer_pkt);
598 if (!avci->buffer_frame->buf[0]) {
599 ret = decode_receive_frame_internal(avctx, avci->buffer_frame);
600 if (ret < 0 && ret != AVERROR(EAGAIN) && ret != AVERROR_EOF)
607 static int apply_cropping(AVCodecContext *avctx, AVFrame *frame)
609 /* make sure we are noisy about decoders returning invalid cropping data */
610 if (frame->crop_left >= INT_MAX - frame->crop_right ||
611 frame->crop_top >= INT_MAX - frame->crop_bottom ||
612 (frame->crop_left + frame->crop_right) >= frame->width ||
613 (frame->crop_top + frame->crop_bottom) >= frame->height) {
614 av_log(avctx, AV_LOG_WARNING,
615 "Invalid cropping information set by a decoder: "
616 "%"SIZE_SPECIFIER"/%"SIZE_SPECIFIER"/%"SIZE_SPECIFIER"/%"SIZE_SPECIFIER" "
617 "(frame size %dx%d). This is a bug, please report it\n",
618 frame->crop_left, frame->crop_right, frame->crop_top, frame->crop_bottom,
619 frame->width, frame->height);
620 frame->crop_left = 0;
621 frame->crop_right = 0;
623 frame->crop_bottom = 0;
627 if (!avctx->apply_cropping)
630 return av_frame_apply_cropping(frame, avctx->flags & AV_CODEC_FLAG_UNALIGNED ?
631 AV_FRAME_CROP_UNALIGNED : 0);
634 int attribute_align_arg avcodec_receive_frame(AVCodecContext *avctx, AVFrame *frame)
636 AVCodecInternal *avci = avctx->internal;
639 av_frame_unref(frame);
641 if (!avcodec_is_open(avctx) || !av_codec_is_decoder(avctx->codec))
642 return AVERROR(EINVAL);
644 if (avci->buffer_frame->buf[0]) {
645 av_frame_move_ref(frame, avci->buffer_frame);
647 ret = decode_receive_frame_internal(avctx, frame);
652 if (avctx->codec_type == AVMEDIA_TYPE_VIDEO) {
653 ret = apply_cropping(avctx, frame);
655 av_frame_unref(frame);
660 avctx->frame_number++;
662 if (avctx->flags & AV_CODEC_FLAG_DROPCHANGED) {
664 if (avctx->frame_number == 1) {
665 avci->initial_format = frame->format;
666 switch(avctx->codec_type) {
667 case AVMEDIA_TYPE_VIDEO:
668 avci->initial_width = frame->width;
669 avci->initial_height = frame->height;
671 case AVMEDIA_TYPE_AUDIO:
672 avci->initial_sample_rate = frame->sample_rate ? frame->sample_rate :
674 avci->initial_channels = frame->channels;
675 avci->initial_channel_layout = frame->channel_layout;
680 if (avctx->frame_number > 1) {
681 changed = avci->initial_format != frame->format;
683 switch(avctx->codec_type) {
684 case AVMEDIA_TYPE_VIDEO:
685 changed |= avci->initial_width != frame->width ||
686 avci->initial_height != frame->height;
688 case AVMEDIA_TYPE_AUDIO:
689 changed |= avci->initial_sample_rate != frame->sample_rate ||
690 avci->initial_sample_rate != avctx->sample_rate ||
691 avci->initial_channels != frame->channels ||
692 avci->initial_channel_layout != frame->channel_layout;
697 avci->changed_frames_dropped++;
698 av_log(avctx, AV_LOG_INFO, "dropped changed frame #%d pts %"PRId64
699 " drop count: %d \n",
700 avctx->frame_number, frame->pts,
701 avci->changed_frames_dropped);
702 av_frame_unref(frame);
703 return AVERROR_INPUT_CHANGED;
710 static void get_subtitle_defaults(AVSubtitle *sub)
712 memset(sub, 0, sizeof(*sub));
713 sub->pts = AV_NOPTS_VALUE;
716 #define UTF8_MAX_BYTES 4 /* 5 and 6 bytes sequences should not be used */
717 static int recode_subtitle(AVCodecContext *avctx, AVPacket **outpkt,
718 AVPacket *inpkt, AVPacket *buf_pkt)
721 iconv_t cd = (iconv_t)-1;
727 if (avctx->sub_charenc_mode != FF_SUB_CHARENC_MODE_PRE_DECODER || inpkt->size == 0) {
736 if (inl >= INT_MAX / UTF8_MAX_BYTES - AV_INPUT_BUFFER_PADDING_SIZE) {
737 av_log(avctx, AV_LOG_ERROR, "Subtitles packet is too big for recoding\n");
738 return AVERROR(ERANGE);
741 cd = iconv_open("UTF-8", avctx->sub_charenc);
742 av_assert0(cd != (iconv_t)-1);
744 ret = av_new_packet(buf_pkt, inl * UTF8_MAX_BYTES);
747 ret = av_packet_copy_props(buf_pkt, inpkt);
750 outb = buf_pkt->data;
751 outl = buf_pkt->size;
753 if (iconv(cd, &inb, &inl, &outb, &outl) == (size_t)-1 ||
754 iconv(cd, NULL, NULL, &outb, &outl) == (size_t)-1 ||
755 outl >= buf_pkt->size || inl != 0) {
756 ret = FFMIN(AVERROR(errno), -1);
757 av_log(avctx, AV_LOG_ERROR, "Unable to recode subtitle event \"%s\" "
758 "from %s to UTF-8\n", inpkt->data, avctx->sub_charenc);
761 buf_pkt->size -= outl;
762 memset(buf_pkt->data + buf_pkt->size, 0, outl);
768 av_packet_unref(buf_pkt);
769 if (cd != (iconv_t)-1)
773 av_log(avctx, AV_LOG_ERROR, "requesting subtitles recoding without iconv");
774 return AVERROR(EINVAL);
778 static int utf8_check(const uint8_t *str)
781 uint32_t codepoint, min;
785 GET_UTF8(codepoint, *(byte++), return 0;);
786 min = byte - str == 1 ? 0 : byte - str == 2 ? 0x80 :
787 1 << (5 * (byte - str) - 4);
788 if (codepoint < min || codepoint >= 0x110000 ||
789 codepoint == 0xFFFE /* BOM */ ||
790 codepoint >= 0xD800 && codepoint <= 0xDFFF /* surrogates */)
797 int avcodec_decode_subtitle2(AVCodecContext *avctx, AVSubtitle *sub,
803 if (!avpkt->data && avpkt->size) {
804 av_log(avctx, AV_LOG_ERROR, "invalid packet: NULL data, size != 0\n");
805 return AVERROR(EINVAL);
808 return AVERROR(EINVAL);
809 if (avctx->codec->type != AVMEDIA_TYPE_SUBTITLE) {
810 av_log(avctx, AV_LOG_ERROR, "Invalid media type for subtitles\n");
811 return AVERROR(EINVAL);
815 get_subtitle_defaults(sub);
817 if ((avctx->codec->capabilities & AV_CODEC_CAP_DELAY) || avpkt->size) {
818 AVCodecInternal *avci = avctx->internal;
821 ret = recode_subtitle(avctx, &pkt, avpkt, avci->buffer_pkt);
825 if (avctx->pkt_timebase.num && avpkt->pts != AV_NOPTS_VALUE)
826 sub->pts = av_rescale_q(avpkt->pts,
827 avctx->pkt_timebase, AV_TIME_BASE_Q);
828 ret = avctx->codec->decode(avctx, sub, got_sub_ptr, pkt);
829 av_assert1((ret >= 0) >= !!*got_sub_ptr &&
830 !!*got_sub_ptr >= !!sub->num_rects);
832 if (sub->num_rects && !sub->end_display_time && avpkt->duration &&
833 avctx->pkt_timebase.num) {
834 AVRational ms = { 1, 1000 };
835 sub->end_display_time = av_rescale_q(avpkt->duration,
836 avctx->pkt_timebase, ms);
839 if (avctx->codec_descriptor->props & AV_CODEC_PROP_BITMAP_SUB)
841 else if (avctx->codec_descriptor->props & AV_CODEC_PROP_TEXT_SUB)
844 for (unsigned i = 0; i < sub->num_rects; i++) {
845 if (avctx->sub_charenc_mode != FF_SUB_CHARENC_MODE_IGNORE &&
846 sub->rects[i]->ass && !utf8_check(sub->rects[i]->ass)) {
847 av_log(avctx, AV_LOG_ERROR,
848 "Invalid UTF-8 in decoded subtitles text; "
849 "maybe missing -sub_charenc option\n");
850 avsubtitle_free(sub);
851 ret = AVERROR_INVALIDDATA;
857 avctx->frame_number++;
859 if (pkt == avci->buffer_pkt) // did we recode?
860 av_packet_unref(avci->buffer_pkt);
866 enum AVPixelFormat avcodec_default_get_format(struct AVCodecContext *avctx,
867 const enum AVPixelFormat *fmt)
869 const AVPixFmtDescriptor *desc;
870 const AVCodecHWConfig *config;
873 // If a device was supplied when the codec was opened, assume that the
874 // user wants to use it.
875 if (avctx->hw_device_ctx && avctx->codec->hw_configs) {
876 AVHWDeviceContext *device_ctx =
877 (AVHWDeviceContext*)avctx->hw_device_ctx->data;
879 config = &avctx->codec->hw_configs[i]->public;
882 if (!(config->methods &
883 AV_CODEC_HW_CONFIG_METHOD_HW_DEVICE_CTX))
885 if (device_ctx->type != config->device_type)
887 for (n = 0; fmt[n] != AV_PIX_FMT_NONE; n++) {
888 if (config->pix_fmt == fmt[n])
893 // No device or other setup, so we have to choose from things which
894 // don't any other external information.
896 // If the last element of the list is a software format, choose it
897 // (this should be best software format if any exist).
898 for (n = 0; fmt[n] != AV_PIX_FMT_NONE; n++);
899 desc = av_pix_fmt_desc_get(fmt[n - 1]);
900 if (!(desc->flags & AV_PIX_FMT_FLAG_HWACCEL))
903 // Finally, traverse the list in order and choose the first entry
904 // with no external dependencies (if there is no hardware configuration
905 // information available then this just picks the first entry).
906 for (n = 0; fmt[n] != AV_PIX_FMT_NONE; n++) {
908 config = avcodec_get_hw_config(avctx->codec, i);
911 if (config->pix_fmt == fmt[n])
915 // No specific config available, so the decoder must be able
916 // to handle this format without any additional setup.
919 if (config->methods & AV_CODEC_HW_CONFIG_METHOD_INTERNAL) {
920 // Usable with only internal setup.
925 // Nothing is usable, give up.
926 return AV_PIX_FMT_NONE;
929 int ff_decode_get_hw_frames_ctx(AVCodecContext *avctx,
930 enum AVHWDeviceType dev_type)
932 AVHWDeviceContext *device_ctx;
933 AVHWFramesContext *frames_ctx;
937 return AVERROR(ENOSYS);
939 if (avctx->hw_frames_ctx)
941 if (!avctx->hw_device_ctx) {
942 av_log(avctx, AV_LOG_ERROR, "A hardware frames or device context is "
943 "required for hardware accelerated decoding.\n");
944 return AVERROR(EINVAL);
947 device_ctx = (AVHWDeviceContext *)avctx->hw_device_ctx->data;
948 if (device_ctx->type != dev_type) {
949 av_log(avctx, AV_LOG_ERROR, "Device type %s expected for hardware "
950 "decoding, but got %s.\n", av_hwdevice_get_type_name(dev_type),
951 av_hwdevice_get_type_name(device_ctx->type));
952 return AVERROR(EINVAL);
955 ret = avcodec_get_hw_frames_parameters(avctx,
956 avctx->hw_device_ctx,
957 avctx->hwaccel->pix_fmt,
958 &avctx->hw_frames_ctx);
962 frames_ctx = (AVHWFramesContext*)avctx->hw_frames_ctx->data;
965 if (frames_ctx->initial_pool_size) {
966 // We guarantee 4 base work surfaces. The function above guarantees 1
967 // (the absolute minimum), so add the missing count.
968 frames_ctx->initial_pool_size += 3;
971 ret = av_hwframe_ctx_init(avctx->hw_frames_ctx);
973 av_buffer_unref(&avctx->hw_frames_ctx);
980 int avcodec_get_hw_frames_parameters(AVCodecContext *avctx,
981 AVBufferRef *device_ref,
982 enum AVPixelFormat hw_pix_fmt,
983 AVBufferRef **out_frames_ref)
985 AVBufferRef *frames_ref = NULL;
986 const AVCodecHWConfigInternal *hw_config;
987 const AVHWAccel *hwa;
991 hw_config = avctx->codec->hw_configs[i];
993 return AVERROR(ENOENT);
994 if (hw_config->public.pix_fmt == hw_pix_fmt)
998 hwa = hw_config->hwaccel;
999 if (!hwa || !hwa->frame_params)
1000 return AVERROR(ENOENT);
1002 frames_ref = av_hwframe_ctx_alloc(device_ref);
1004 return AVERROR(ENOMEM);
1006 ret = hwa->frame_params(avctx, frames_ref);
1008 AVHWFramesContext *frames_ctx = (AVHWFramesContext*)frames_ref->data;
1010 if (frames_ctx->initial_pool_size) {
1011 // If the user has requested that extra output surfaces be
1012 // available then add them here.
1013 if (avctx->extra_hw_frames > 0)
1014 frames_ctx->initial_pool_size += avctx->extra_hw_frames;
1016 // If frame threading is enabled then an extra surface per thread
1017 // is also required.
1018 if (avctx->active_thread_type & FF_THREAD_FRAME)
1019 frames_ctx->initial_pool_size += avctx->thread_count;
1022 *out_frames_ref = frames_ref;
1024 av_buffer_unref(&frames_ref);
1029 static int hwaccel_init(AVCodecContext *avctx,
1030 const AVCodecHWConfigInternal *hw_config)
1032 const AVHWAccel *hwaccel;
1035 hwaccel = hw_config->hwaccel;
1036 if (hwaccel->capabilities & AV_HWACCEL_CODEC_CAP_EXPERIMENTAL &&
1037 avctx->strict_std_compliance > FF_COMPLIANCE_EXPERIMENTAL) {
1038 av_log(avctx, AV_LOG_WARNING, "Ignoring experimental hwaccel: %s\n",
1040 return AVERROR_PATCHWELCOME;
1043 if (hwaccel->priv_data_size) {
1044 avctx->internal->hwaccel_priv_data =
1045 av_mallocz(hwaccel->priv_data_size);
1046 if (!avctx->internal->hwaccel_priv_data)
1047 return AVERROR(ENOMEM);
1050 avctx->hwaccel = hwaccel;
1051 if (hwaccel->init) {
1052 err = hwaccel->init(avctx);
1054 av_log(avctx, AV_LOG_ERROR, "Failed setup for format %s: "
1055 "hwaccel initialisation returned error.\n",
1056 av_get_pix_fmt_name(hw_config->public.pix_fmt));
1057 av_freep(&avctx->internal->hwaccel_priv_data);
1058 avctx->hwaccel = NULL;
1066 static void hwaccel_uninit(AVCodecContext *avctx)
1068 if (avctx->hwaccel && avctx->hwaccel->uninit)
1069 avctx->hwaccel->uninit(avctx);
1071 av_freep(&avctx->internal->hwaccel_priv_data);
1073 avctx->hwaccel = NULL;
1075 av_buffer_unref(&avctx->hw_frames_ctx);
1078 int ff_get_format(AVCodecContext *avctx, const enum AVPixelFormat *fmt)
1080 const AVPixFmtDescriptor *desc;
1081 enum AVPixelFormat *choices;
1082 enum AVPixelFormat ret, user_choice;
1083 const AVCodecHWConfigInternal *hw_config;
1084 const AVCodecHWConfig *config;
1087 // Find end of list.
1088 for (n = 0; fmt[n] != AV_PIX_FMT_NONE; n++);
1089 // Must contain at least one entry.
1091 // If a software format is available, it must be the last entry.
1092 desc = av_pix_fmt_desc_get(fmt[n - 1]);
1093 if (desc->flags & AV_PIX_FMT_FLAG_HWACCEL) {
1094 // No software format is available.
1096 avctx->sw_pix_fmt = fmt[n - 1];
1099 choices = av_malloc_array(n + 1, sizeof(*choices));
1101 return AV_PIX_FMT_NONE;
1103 memcpy(choices, fmt, (n + 1) * sizeof(*choices));
1106 // Remove the previous hwaccel, if there was one.
1107 hwaccel_uninit(avctx);
1109 user_choice = avctx->get_format(avctx, choices);
1110 if (user_choice == AV_PIX_FMT_NONE) {
1111 // Explicitly chose nothing, give up.
1112 ret = AV_PIX_FMT_NONE;
1116 desc = av_pix_fmt_desc_get(user_choice);
1118 av_log(avctx, AV_LOG_ERROR, "Invalid format returned by "
1119 "get_format() callback.\n");
1120 ret = AV_PIX_FMT_NONE;
1123 av_log(avctx, AV_LOG_DEBUG, "Format %s chosen by get_format().\n",
1126 for (i = 0; i < n; i++) {
1127 if (choices[i] == user_choice)
1131 av_log(avctx, AV_LOG_ERROR, "Invalid return from get_format(): "
1132 "%s not in possible list.\n", desc->name);
1133 ret = AV_PIX_FMT_NONE;
1137 if (avctx->codec->hw_configs) {
1139 hw_config = avctx->codec->hw_configs[i];
1142 if (hw_config->public.pix_fmt == user_choice)
1150 // No config available, so no extra setup required.
1154 config = &hw_config->public;
1156 if (config->methods &
1157 AV_CODEC_HW_CONFIG_METHOD_HW_FRAMES_CTX &&
1158 avctx->hw_frames_ctx) {
1159 const AVHWFramesContext *frames_ctx =
1160 (AVHWFramesContext*)avctx->hw_frames_ctx->data;
1161 if (frames_ctx->format != user_choice) {
1162 av_log(avctx, AV_LOG_ERROR, "Invalid setup for format %s: "
1163 "does not match the format of the provided frames "
1164 "context.\n", desc->name);
1167 } else if (config->methods &
1168 AV_CODEC_HW_CONFIG_METHOD_HW_DEVICE_CTX &&
1169 avctx->hw_device_ctx) {
1170 const AVHWDeviceContext *device_ctx =
1171 (AVHWDeviceContext*)avctx->hw_device_ctx->data;
1172 if (device_ctx->type != config->device_type) {
1173 av_log(avctx, AV_LOG_ERROR, "Invalid setup for format %s: "
1174 "does not match the type of the provided device "
1175 "context.\n", desc->name);
1178 } else if (config->methods &
1179 AV_CODEC_HW_CONFIG_METHOD_INTERNAL) {
1180 // Internal-only setup, no additional configuration.
1181 } else if (config->methods &
1182 AV_CODEC_HW_CONFIG_METHOD_AD_HOC) {
1183 // Some ad-hoc configuration we can't see and can't check.
1185 av_log(avctx, AV_LOG_ERROR, "Invalid setup for format %s: "
1186 "missing configuration.\n", desc->name);
1189 if (hw_config->hwaccel) {
1190 av_log(avctx, AV_LOG_DEBUG, "Format %s requires hwaccel "
1191 "initialisation.\n", desc->name);
1192 err = hwaccel_init(avctx, hw_config);
1200 av_log(avctx, AV_LOG_DEBUG, "Format %s not usable, retrying "
1201 "get_format() without it.\n", desc->name);
1202 for (i = 0; i < n; i++) {
1203 if (choices[i] == user_choice)
1206 for (; i + 1 < n; i++)
1207 choices[i] = choices[i + 1];
1215 static void frame_pool_free(void *opaque, uint8_t *data)
1217 FramePool *pool = (FramePool*)data;
1220 for (i = 0; i < FF_ARRAY_ELEMS(pool->pools); i++)
1221 av_buffer_pool_uninit(&pool->pools[i]);
1226 static AVBufferRef *frame_pool_alloc(void)
1228 FramePool *pool = av_mallocz(sizeof(*pool));
1234 buf = av_buffer_create((uint8_t*)pool, sizeof(*pool),
1235 frame_pool_free, NULL, 0);
1244 static int update_frame_pool(AVCodecContext *avctx, AVFrame *frame)
1246 FramePool *pool = avctx->internal->pool ?
1247 (FramePool*)avctx->internal->pool->data : NULL;
1248 AVBufferRef *pool_buf;
1249 int i, ret, ch, planes;
1251 if (avctx->codec_type == AVMEDIA_TYPE_AUDIO) {
1252 int planar = av_sample_fmt_is_planar(frame->format);
1253 ch = frame->channels;
1254 planes = planar ? ch : 1;
1257 if (pool && pool->format == frame->format) {
1258 if (avctx->codec_type == AVMEDIA_TYPE_VIDEO &&
1259 pool->width == frame->width && pool->height == frame->height)
1261 if (avctx->codec_type == AVMEDIA_TYPE_AUDIO && pool->planes == planes &&
1262 pool->channels == ch && frame->nb_samples == pool->samples)
1266 pool_buf = frame_pool_alloc();
1268 return AVERROR(ENOMEM);
1269 pool = (FramePool*)pool_buf->data;
1271 switch (avctx->codec_type) {
1272 case AVMEDIA_TYPE_VIDEO: {
1274 int w = frame->width;
1275 int h = frame->height;
1277 ptrdiff_t linesize1[4];
1280 avcodec_align_dimensions2(avctx, &w, &h, pool->stride_align);
1283 // NOTE: do not align linesizes individually, this breaks e.g. assumptions
1284 // that linesize[0] == 2*linesize[1] in the MPEG-encoder for 4:2:2
1285 ret = av_image_fill_linesizes(linesize, avctx->pix_fmt, w);
1288 // increase alignment of w for next try (rhs gives the lowest bit set in w)
1292 for (i = 0; i < 4; i++)
1293 unaligned |= linesize[i] % pool->stride_align[i];
1294 } while (unaligned);
1296 for (i = 0; i < 4; i++)
1297 linesize1[i] = linesize[i];
1298 ret = av_image_fill_plane_sizes(size, avctx->pix_fmt, h, linesize1);
1302 for (i = 0; i < 4; i++) {
1303 pool->linesize[i] = linesize[i];
1305 if (size[i] > INT_MAX - (16 + STRIDE_ALIGN - 1)) {
1306 ret = AVERROR(EINVAL);
1309 pool->pools[i] = av_buffer_pool_init(size[i] + 16 + STRIDE_ALIGN - 1,
1310 CONFIG_MEMORY_POISONING ?
1313 if (!pool->pools[i]) {
1314 ret = AVERROR(ENOMEM);
1319 pool->format = frame->format;
1320 pool->width = frame->width;
1321 pool->height = frame->height;
1325 case AVMEDIA_TYPE_AUDIO: {
1326 ret = av_samples_get_buffer_size(&pool->linesize[0], ch,
1327 frame->nb_samples, frame->format, 0);
1331 pool->pools[0] = av_buffer_pool_init(pool->linesize[0], NULL);
1332 if (!pool->pools[0]) {
1333 ret = AVERROR(ENOMEM);
1337 pool->format = frame->format;
1338 pool->planes = planes;
1339 pool->channels = ch;
1340 pool->samples = frame->nb_samples;
1343 default: av_assert0(0);
1346 av_buffer_unref(&avctx->internal->pool);
1347 avctx->internal->pool = pool_buf;
1351 av_buffer_unref(&pool_buf);
1355 static int audio_get_buffer(AVCodecContext *avctx, AVFrame *frame)
1357 FramePool *pool = (FramePool*)avctx->internal->pool->data;
1358 int planes = pool->planes;
1361 frame->linesize[0] = pool->linesize[0];
1363 if (planes > AV_NUM_DATA_POINTERS) {
1364 frame->extended_data = av_mallocz_array(planes, sizeof(*frame->extended_data));
1365 frame->nb_extended_buf = planes - AV_NUM_DATA_POINTERS;
1366 frame->extended_buf = av_mallocz_array(frame->nb_extended_buf,
1367 sizeof(*frame->extended_buf));
1368 if (!frame->extended_data || !frame->extended_buf) {
1369 av_freep(&frame->extended_data);
1370 av_freep(&frame->extended_buf);
1371 return AVERROR(ENOMEM);
1374 frame->extended_data = frame->data;
1375 av_assert0(frame->nb_extended_buf == 0);
1378 for (i = 0; i < FFMIN(planes, AV_NUM_DATA_POINTERS); i++) {
1379 frame->buf[i] = av_buffer_pool_get(pool->pools[0]);
1382 frame->extended_data[i] = frame->data[i] = frame->buf[i]->data;
1384 for (i = 0; i < frame->nb_extended_buf; i++) {
1385 frame->extended_buf[i] = av_buffer_pool_get(pool->pools[0]);
1386 if (!frame->extended_buf[i])
1388 frame->extended_data[i + AV_NUM_DATA_POINTERS] = frame->extended_buf[i]->data;
1391 if (avctx->debug & FF_DEBUG_BUFFERS)
1392 av_log(avctx, AV_LOG_DEBUG, "default_get_buffer called on frame %p", frame);
1396 av_frame_unref(frame);
1397 return AVERROR(ENOMEM);
1400 static int video_get_buffer(AVCodecContext *s, AVFrame *pic)
1402 FramePool *pool = (FramePool*)s->internal->pool->data;
1403 const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(pic->format);
1406 if (pic->data[0] || pic->data[1] || pic->data[2] || pic->data[3]) {
1407 av_log(s, AV_LOG_ERROR, "pic->data[*]!=NULL in avcodec_default_get_buffer\n");
1412 av_log(s, AV_LOG_ERROR,
1413 "Unable to get pixel format descriptor for format %s\n",
1414 av_get_pix_fmt_name(pic->format));
1415 return AVERROR(EINVAL);
1418 memset(pic->data, 0, sizeof(pic->data));
1419 pic->extended_data = pic->data;
1421 for (i = 0; i < 4 && pool->pools[i]; i++) {
1422 pic->linesize[i] = pool->linesize[i];
1424 pic->buf[i] = av_buffer_pool_get(pool->pools[i]);
1428 pic->data[i] = pic->buf[i]->data;
1430 for (; i < AV_NUM_DATA_POINTERS; i++) {
1431 pic->data[i] = NULL;
1432 pic->linesize[i] = 0;
1434 if (desc->flags & AV_PIX_FMT_FLAG_PAL ||
1435 ((desc->flags & FF_PSEUDOPAL) && pic->data[1]))
1436 avpriv_set_systematic_pal2((uint32_t *)pic->data[1], pic->format);
1438 if (s->debug & FF_DEBUG_BUFFERS)
1439 av_log(s, AV_LOG_DEBUG, "default_get_buffer called on pic %p\n", pic);
1443 av_frame_unref(pic);
1444 return AVERROR(ENOMEM);
1447 int avcodec_default_get_buffer2(AVCodecContext *avctx, AVFrame *frame, int flags)
1451 if (avctx->hw_frames_ctx) {
1452 ret = av_hwframe_get_buffer(avctx->hw_frames_ctx, frame, 0);
1453 frame->width = avctx->coded_width;
1454 frame->height = avctx->coded_height;
1458 if ((ret = update_frame_pool(avctx, frame)) < 0)
1461 switch (avctx->codec_type) {
1462 case AVMEDIA_TYPE_VIDEO:
1463 return video_get_buffer(avctx, frame);
1464 case AVMEDIA_TYPE_AUDIO:
1465 return audio_get_buffer(avctx, frame);
1471 static int add_metadata_from_side_data(const AVPacket *avpkt, AVFrame *frame)
1474 const uint8_t *side_metadata;
1476 AVDictionary **frame_md = &frame->metadata;
1478 side_metadata = av_packet_get_side_data(avpkt,
1479 AV_PKT_DATA_STRINGS_METADATA, &size);
1480 return av_packet_unpack_dictionary(side_metadata, size, frame_md);
1483 int ff_decode_frame_props(AVCodecContext *avctx, AVFrame *frame)
1485 AVPacket *pkt = avctx->internal->last_pkt_props;
1486 static const struct {
1487 enum AVPacketSideDataType packet;
1488 enum AVFrameSideDataType frame;
1490 { AV_PKT_DATA_REPLAYGAIN , AV_FRAME_DATA_REPLAYGAIN },
1491 { AV_PKT_DATA_DISPLAYMATRIX, AV_FRAME_DATA_DISPLAYMATRIX },
1492 { AV_PKT_DATA_SPHERICAL, AV_FRAME_DATA_SPHERICAL },
1493 { AV_PKT_DATA_STEREO3D, AV_FRAME_DATA_STEREO3D },
1494 { AV_PKT_DATA_AUDIO_SERVICE_TYPE, AV_FRAME_DATA_AUDIO_SERVICE_TYPE },
1495 { AV_PKT_DATA_MASTERING_DISPLAY_METADATA, AV_FRAME_DATA_MASTERING_DISPLAY_METADATA },
1496 { AV_PKT_DATA_CONTENT_LIGHT_LEVEL, AV_FRAME_DATA_CONTENT_LIGHT_LEVEL },
1497 { AV_PKT_DATA_A53_CC, AV_FRAME_DATA_A53_CC },
1498 { AV_PKT_DATA_ICC_PROFILE, AV_FRAME_DATA_ICC_PROFILE },
1499 { AV_PKT_DATA_S12M_TIMECODE, AV_FRAME_DATA_S12M_TIMECODE },
1502 if (IS_EMPTY(pkt) && av_fifo_size(avctx->internal->pkt_props) >= sizeof(*pkt))
1503 av_fifo_generic_read(avctx->internal->pkt_props,
1504 pkt, sizeof(*pkt), NULL);
1506 frame->pts = pkt->pts;
1508 FF_DISABLE_DEPRECATION_WARNINGS
1509 frame->pkt_pts = pkt->pts;
1510 FF_ENABLE_DEPRECATION_WARNINGS
1512 frame->pkt_pos = pkt->pos;
1513 frame->pkt_duration = pkt->duration;
1514 frame->pkt_size = pkt->size;
1516 for (int i = 0; i < FF_ARRAY_ELEMS(sd); i++) {
1518 uint8_t *packet_sd = av_packet_get_side_data(pkt, sd[i].packet, &size);
1520 AVFrameSideData *frame_sd = av_frame_new_side_data(frame,
1524 return AVERROR(ENOMEM);
1526 memcpy(frame_sd->data, packet_sd, size);
1529 add_metadata_from_side_data(pkt, frame);
1531 if (pkt->flags & AV_PKT_FLAG_DISCARD) {
1532 frame->flags |= AV_FRAME_FLAG_DISCARD;
1534 frame->flags = (frame->flags & ~AV_FRAME_FLAG_DISCARD);
1536 frame->reordered_opaque = avctx->reordered_opaque;
1538 if (frame->color_primaries == AVCOL_PRI_UNSPECIFIED)
1539 frame->color_primaries = avctx->color_primaries;
1540 if (frame->color_trc == AVCOL_TRC_UNSPECIFIED)
1541 frame->color_trc = avctx->color_trc;
1542 if (frame->colorspace == AVCOL_SPC_UNSPECIFIED)
1543 frame->colorspace = avctx->colorspace;
1544 if (frame->color_range == AVCOL_RANGE_UNSPECIFIED)
1545 frame->color_range = avctx->color_range;
1546 if (frame->chroma_location == AVCHROMA_LOC_UNSPECIFIED)
1547 frame->chroma_location = avctx->chroma_sample_location;
1549 switch (avctx->codec->type) {
1550 case AVMEDIA_TYPE_VIDEO:
1551 frame->format = avctx->pix_fmt;
1552 if (!frame->sample_aspect_ratio.num)
1553 frame->sample_aspect_ratio = avctx->sample_aspect_ratio;
1555 if (frame->width && frame->height &&
1556 av_image_check_sar(frame->width, frame->height,
1557 frame->sample_aspect_ratio) < 0) {
1558 av_log(avctx, AV_LOG_WARNING, "ignoring invalid SAR: %u/%u\n",
1559 frame->sample_aspect_ratio.num,
1560 frame->sample_aspect_ratio.den);
1561 frame->sample_aspect_ratio = (AVRational){ 0, 1 };
1565 case AVMEDIA_TYPE_AUDIO:
1566 if (!frame->sample_rate)
1567 frame->sample_rate = avctx->sample_rate;
1568 if (frame->format < 0)
1569 frame->format = avctx->sample_fmt;
1570 if (!frame->channel_layout) {
1571 if (avctx->channel_layout) {
1572 if (av_get_channel_layout_nb_channels(avctx->channel_layout) !=
1574 av_log(avctx, AV_LOG_ERROR, "Inconsistent channel "
1575 "configuration.\n");
1576 return AVERROR(EINVAL);
1579 frame->channel_layout = avctx->channel_layout;
1581 if (avctx->channels > FF_SANE_NB_CHANNELS) {
1582 av_log(avctx, AV_LOG_ERROR, "Too many channels: %d.\n",
1584 return AVERROR(ENOSYS);
1588 frame->channels = avctx->channels;
1594 static void validate_avframe_allocation(AVCodecContext *avctx, AVFrame *frame)
1596 if (avctx->codec_type == AVMEDIA_TYPE_VIDEO) {
1598 int num_planes = av_pix_fmt_count_planes(frame->format);
1599 const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(frame->format);
1600 int flags = desc ? desc->flags : 0;
1601 if (num_planes == 1 && (flags & AV_PIX_FMT_FLAG_PAL))
1603 if ((flags & FF_PSEUDOPAL) && frame->data[1])
1605 for (i = 0; i < num_planes; i++) {
1606 av_assert0(frame->data[i]);
1608 // For formats without data like hwaccel allow unused pointers to be non-NULL.
1609 for (i = num_planes; num_planes > 0 && i < FF_ARRAY_ELEMS(frame->data); i++) {
1611 av_log(avctx, AV_LOG_ERROR, "Buffer returned by get_buffer2() did not zero unused plane pointers\n");
1612 frame->data[i] = NULL;
1617 static void decode_data_free(void *opaque, uint8_t *data)
1619 FrameDecodeData *fdd = (FrameDecodeData*)data;
1621 if (fdd->post_process_opaque_free)
1622 fdd->post_process_opaque_free(fdd->post_process_opaque);
1624 if (fdd->hwaccel_priv_free)
1625 fdd->hwaccel_priv_free(fdd->hwaccel_priv);
1630 int ff_attach_decode_data(AVFrame *frame)
1632 AVBufferRef *fdd_buf;
1633 FrameDecodeData *fdd;
1635 av_assert1(!frame->private_ref);
1636 av_buffer_unref(&frame->private_ref);
1638 fdd = av_mallocz(sizeof(*fdd));
1640 return AVERROR(ENOMEM);
1642 fdd_buf = av_buffer_create((uint8_t*)fdd, sizeof(*fdd), decode_data_free,
1643 NULL, AV_BUFFER_FLAG_READONLY);
1646 return AVERROR(ENOMEM);
1649 frame->private_ref = fdd_buf;
1654 int ff_get_buffer(AVCodecContext *avctx, AVFrame *frame, int flags)
1656 const AVHWAccel *hwaccel = avctx->hwaccel;
1657 int override_dimensions = 1;
1660 if (avctx->codec_type == AVMEDIA_TYPE_VIDEO) {
1661 if ((unsigned)avctx->width > INT_MAX - STRIDE_ALIGN ||
1662 (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) {
1663 av_log(avctx, AV_LOG_ERROR, "video_get_buffer: image parameters invalid\n");
1664 ret = AVERROR(EINVAL);
1668 if (frame->width <= 0 || frame->height <= 0) {
1669 frame->width = FFMAX(avctx->width, AV_CEIL_RSHIFT(avctx->coded_width, avctx->lowres));
1670 frame->height = FFMAX(avctx->height, AV_CEIL_RSHIFT(avctx->coded_height, avctx->lowres));
1671 override_dimensions = 0;
1674 if (frame->data[0] || frame->data[1] || frame->data[2] || frame->data[3]) {
1675 av_log(avctx, AV_LOG_ERROR, "pic->data[*]!=NULL in get_buffer_internal\n");
1676 ret = AVERROR(EINVAL);
1679 } else if (avctx->codec_type == AVMEDIA_TYPE_AUDIO) {
1680 if (frame->nb_samples * (int64_t)avctx->channels > avctx->max_samples) {
1681 av_log(avctx, AV_LOG_ERROR, "samples per frame %d, exceeds max_samples %"PRId64"\n", frame->nb_samples, avctx->max_samples);
1682 ret = AVERROR(EINVAL);
1686 ret = ff_decode_frame_props(avctx, frame);
1691 if (hwaccel->alloc_frame) {
1692 ret = hwaccel->alloc_frame(avctx, frame);
1696 avctx->sw_pix_fmt = avctx->pix_fmt;
1698 ret = avctx->get_buffer2(avctx, frame, flags);
1702 validate_avframe_allocation(avctx, frame);
1704 ret = ff_attach_decode_data(frame);
1709 if (avctx->codec_type == AVMEDIA_TYPE_VIDEO && !override_dimensions &&
1710 !(avctx->codec->caps_internal & FF_CODEC_CAP_EXPORTS_CROPPING)) {
1711 frame->width = avctx->width;
1712 frame->height = avctx->height;
1717 av_log(avctx, AV_LOG_ERROR, "get_buffer() failed\n");
1718 av_frame_unref(frame);
1724 static int reget_buffer_internal(AVCodecContext *avctx, AVFrame *frame, int flags)
1729 av_assert0(avctx->codec_type == AVMEDIA_TYPE_VIDEO);
1731 if (frame->data[0] && (frame->width != avctx->width || frame->height != avctx->height || frame->format != avctx->pix_fmt)) {
1732 av_log(avctx, AV_LOG_WARNING, "Picture changed from size:%dx%d fmt:%s to size:%dx%d fmt:%s in reget buffer()\n",
1733 frame->width, frame->height, av_get_pix_fmt_name(frame->format), avctx->width, avctx->height, av_get_pix_fmt_name(avctx->pix_fmt));
1734 av_frame_unref(frame);
1737 if (!frame->data[0])
1738 return ff_get_buffer(avctx, frame, AV_GET_BUFFER_FLAG_REF);
1740 if ((flags & FF_REGET_BUFFER_FLAG_READONLY) || av_frame_is_writable(frame))
1741 return ff_decode_frame_props(avctx, frame);
1743 tmp = av_frame_alloc();
1745 return AVERROR(ENOMEM);
1747 av_frame_move_ref(tmp, frame);
1749 ret = ff_get_buffer(avctx, frame, AV_GET_BUFFER_FLAG_REF);
1751 av_frame_free(&tmp);
1755 av_frame_copy(frame, tmp);
1756 av_frame_free(&tmp);
1761 int ff_reget_buffer(AVCodecContext *avctx, AVFrame *frame, int flags)
1763 int ret = reget_buffer_internal(avctx, frame, flags);
1765 av_log(avctx, AV_LOG_ERROR, "reget_buffer() failed\n");
1769 int ff_decode_preinit(AVCodecContext *avctx)
1773 /* if the decoder init function was already called previously,
1774 * free the already allocated subtitle_header before overwriting it */
1775 av_freep(&avctx->subtitle_header);
1777 #if FF_API_THREAD_SAFE_CALLBACKS
1778 FF_DISABLE_DEPRECATION_WARNINGS
1779 if ((avctx->thread_type & FF_THREAD_FRAME) &&
1780 avctx->get_buffer2 != avcodec_default_get_buffer2 &&
1781 !avctx->thread_safe_callbacks) {
1782 av_log(avctx, AV_LOG_WARNING, "Requested frame threading with a "
1783 "custom get_buffer2() implementation which is not marked as "
1784 "thread safe. This is not supported anymore, make your "
1785 "callback thread-safe.\n");
1787 FF_ENABLE_DEPRECATION_WARNINGS
1790 if (avctx->codec_type == AVMEDIA_TYPE_AUDIO && avctx->channels == 0 &&
1791 !(avctx->codec->capabilities & AV_CODEC_CAP_CHANNEL_CONF)) {
1792 av_log(avctx, AV_LOG_ERROR, "Decoder requires channel count but channels not set\n");
1793 return AVERROR(EINVAL);
1795 if (avctx->codec->max_lowres < avctx->lowres || avctx->lowres < 0) {
1796 av_log(avctx, AV_LOG_WARNING, "The maximum value for lowres supported by the decoder is %d\n",
1797 avctx->codec->max_lowres);
1798 avctx->lowres = avctx->codec->max_lowres;
1800 if (avctx->sub_charenc) {
1801 if (avctx->codec_type != AVMEDIA_TYPE_SUBTITLE) {
1802 av_log(avctx, AV_LOG_ERROR, "Character encoding is only "
1803 "supported with subtitles codecs\n");
1804 return AVERROR(EINVAL);
1805 } else if (avctx->codec_descriptor->props & AV_CODEC_PROP_BITMAP_SUB) {
1806 av_log(avctx, AV_LOG_WARNING, "Codec '%s' is bitmap-based, "
1807 "subtitles character encoding will be ignored\n",
1808 avctx->codec_descriptor->name);
1809 avctx->sub_charenc_mode = FF_SUB_CHARENC_MODE_DO_NOTHING;
1811 /* input character encoding is set for a text based subtitle
1812 * codec at this point */
1813 if (avctx->sub_charenc_mode == FF_SUB_CHARENC_MODE_AUTOMATIC)
1814 avctx->sub_charenc_mode = FF_SUB_CHARENC_MODE_PRE_DECODER;
1816 if (avctx->sub_charenc_mode == FF_SUB_CHARENC_MODE_PRE_DECODER) {
1818 iconv_t cd = iconv_open("UTF-8", avctx->sub_charenc);
1819 if (cd == (iconv_t)-1) {
1820 ret = AVERROR(errno);
1821 av_log(avctx, AV_LOG_ERROR, "Unable to open iconv context "
1822 "with input character encoding \"%s\"\n", avctx->sub_charenc);
1827 av_log(avctx, AV_LOG_ERROR, "Character encoding subtitles "
1828 "conversion needs a libavcodec built with iconv support "
1829 "for this codec\n");
1830 return AVERROR(ENOSYS);
1836 avctx->pts_correction_num_faulty_pts =
1837 avctx->pts_correction_num_faulty_dts = 0;
1838 avctx->pts_correction_last_pts =
1839 avctx->pts_correction_last_dts = INT64_MIN;
1841 if ( !CONFIG_GRAY && avctx->flags & AV_CODEC_FLAG_GRAY
1842 && avctx->codec_descriptor->type == AVMEDIA_TYPE_VIDEO)
1843 av_log(avctx, AV_LOG_WARNING,
1844 "gray decoding requested but not enabled at configuration time\n");
1845 if (avctx->flags2 & AV_CODEC_FLAG2_EXPORT_MVS) {
1846 avctx->export_side_data |= AV_CODEC_EXPORT_DATA_MVS;
1849 ret = decode_bsfs_init(avctx);
1856 int ff_copy_palette(void *dst, const AVPacket *src, void *logctx)
1859 const void *pal = av_packet_get_side_data(src, AV_PKT_DATA_PALETTE, &size);
1861 if (pal && size == AVPALETTE_SIZE) {
1862 memcpy(dst, pal, AVPALETTE_SIZE);
1865 av_log(logctx, AV_LOG_ERROR, "Palette size %d is wrong\n", size);