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;
397 if(frame->pkt_dts!=AV_NOPTS_VALUE)
398 frame->pkt_dts += diff_ts;
399 if (frame->pkt_duration >= diff_ts)
400 frame->pkt_duration -= diff_ts;
402 av_log(avctx, AV_LOG_WARNING, "Could not update timestamps for skipped samples.\n");
404 av_log(avctx, AV_LOG_DEBUG, "skip %d/%d samples\n",
405 avci->skip_samples, frame->nb_samples);
406 *discarded_samples += avci->skip_samples;
407 frame->nb_samples -= avci->skip_samples;
408 avci->skip_samples = 0;
412 if (discard_padding > 0 && discard_padding <= frame->nb_samples && got_frame &&
413 !(avctx->flags2 & AV_CODEC_FLAG2_SKIP_MANUAL)) {
414 if (discard_padding == frame->nb_samples) {
415 *discarded_samples += frame->nb_samples;
418 if(avctx->pkt_timebase.num && avctx->sample_rate) {
419 int64_t diff_ts = av_rescale_q(frame->nb_samples - discard_padding,
420 (AVRational){1, avctx->sample_rate},
421 avctx->pkt_timebase);
422 frame->pkt_duration = diff_ts;
424 av_log(avctx, AV_LOG_WARNING, "Could not update timestamps for discarded samples.\n");
426 av_log(avctx, AV_LOG_DEBUG, "discard %d/%d samples\n",
427 (int)discard_padding, frame->nb_samples);
428 frame->nb_samples -= discard_padding;
432 if ((avctx->flags2 & AV_CODEC_FLAG2_SKIP_MANUAL) && got_frame) {
433 AVFrameSideData *fside = av_frame_new_side_data(frame, AV_FRAME_DATA_SKIP_SAMPLES, 10);
435 AV_WL32(fside->data, avci->skip_samples);
436 AV_WL32(fside->data + 4, discard_padding);
437 AV_WL8(fside->data + 8, skip_reason);
438 AV_WL8(fside->data + 9, discard_reason);
439 avci->skip_samples = 0;
444 if (avctx->codec->type == AVMEDIA_TYPE_AUDIO &&
445 !avci->showed_multi_packet_warning &&
446 ret >= 0 && ret != pkt->size && !(avctx->codec->capabilities & AV_CODEC_CAP_SUBFRAMES)) {
447 av_log(avctx, AV_LOG_WARNING, "Multiple frames in a packet.\n");
448 avci->showed_multi_packet_warning = 1;
452 av_frame_unref(frame);
454 if (ret >= 0 && avctx->codec->type == AVMEDIA_TYPE_VIDEO && !(avctx->flags & AV_CODEC_FLAG_TRUNCATED))
457 #if FF_API_AVCTX_TIMEBASE
458 if (avctx->framerate.num > 0 && avctx->framerate.den > 0)
459 avctx->time_base = av_inv_q(av_mul_q(avctx->framerate, (AVRational){avctx->ticks_per_frame, 1}));
462 /* do not stop draining when actual_got_frame != 0 or ret < 0 */
463 /* got_frame == 0 but actual_got_frame != 0 when frame is discarded */
464 if (avci->draining && !actual_got_frame) {
466 /* prevent infinite loop if a decoder wrongly always return error on draining */
467 /* reasonable nb_errors_max = maximum b frames + thread count */
468 int nb_errors_max = 20 + (HAVE_THREADS && avctx->active_thread_type & FF_THREAD_FRAME ?
469 avctx->thread_count : 1);
471 if (avci->nb_draining_errors++ >= nb_errors_max) {
472 av_log(avctx, AV_LOG_ERROR, "Too many errors when draining, this is a bug. "
473 "Stop draining and force EOF.\n");
474 avci->draining_done = 1;
478 avci->draining_done = 1;
482 if (ret >= pkt->size || ret < 0) {
483 av_packet_unref(pkt);
484 av_packet_unref(avci->last_pkt_props);
488 pkt->data += consumed;
489 pkt->size -= consumed;
490 avci->last_pkt_props->size -= consumed; // See extract_packet_props() comment.
491 pkt->pts = AV_NOPTS_VALUE;
492 pkt->dts = AV_NOPTS_VALUE;
493 avci->last_pkt_props->pts = AV_NOPTS_VALUE;
494 avci->last_pkt_props->dts = AV_NOPTS_VALUE;
498 av_assert0(frame->buf[0]);
500 return ret < 0 ? ret : 0;
503 static int decode_simple_receive_frame(AVCodecContext *avctx, AVFrame *frame)
506 int64_t discarded_samples = 0;
508 while (!frame->buf[0]) {
509 if (discarded_samples > avctx->max_samples)
510 return AVERROR(EAGAIN);
511 ret = decode_simple_internal(avctx, frame, &discarded_samples);
519 static int decode_receive_frame_internal(AVCodecContext *avctx, AVFrame *frame)
521 AVCodecInternal *avci = avctx->internal;
524 av_assert0(!frame->buf[0]);
526 if (avctx->codec->receive_frame) {
527 ret = avctx->codec->receive_frame(avctx, frame);
528 if (ret != AVERROR(EAGAIN))
529 av_packet_unref(avci->last_pkt_props);
531 ret = decode_simple_receive_frame(avctx, frame);
533 if (ret == AVERROR_EOF)
534 avci->draining_done = 1;
537 frame->best_effort_timestamp = guess_correct_pts(avctx,
541 /* the only case where decode data is not set should be decoders
542 * that do not call ff_get_buffer() */
543 av_assert0((frame->private_ref && frame->private_ref->size == sizeof(FrameDecodeData)) ||
544 !(avctx->codec->capabilities & AV_CODEC_CAP_DR1));
546 if (frame->private_ref) {
547 FrameDecodeData *fdd = (FrameDecodeData*)frame->private_ref->data;
549 if (fdd->post_process) {
550 ret = fdd->post_process(avctx, frame);
552 av_frame_unref(frame);
559 /* free the per-frame decode data */
560 av_buffer_unref(&frame->private_ref);
565 int attribute_align_arg avcodec_send_packet(AVCodecContext *avctx, const AVPacket *avpkt)
567 AVCodecInternal *avci = avctx->internal;
570 if (!avcodec_is_open(avctx) || !av_codec_is_decoder(avctx->codec))
571 return AVERROR(EINVAL);
573 if (avctx->internal->draining)
576 if (avpkt && !avpkt->size && avpkt->data)
577 return AVERROR(EINVAL);
579 av_packet_unref(avci->buffer_pkt);
580 if (avpkt && (avpkt->data || avpkt->side_data_elems)) {
581 ret = av_packet_ref(avci->buffer_pkt, avpkt);
586 ret = av_bsf_send_packet(avci->bsf, avci->buffer_pkt);
588 av_packet_unref(avci->buffer_pkt);
592 if (!avci->buffer_frame->buf[0]) {
593 ret = decode_receive_frame_internal(avctx, avci->buffer_frame);
594 if (ret < 0 && ret != AVERROR(EAGAIN) && ret != AVERROR_EOF)
601 static int apply_cropping(AVCodecContext *avctx, AVFrame *frame)
603 /* make sure we are noisy about decoders returning invalid cropping data */
604 if (frame->crop_left >= INT_MAX - frame->crop_right ||
605 frame->crop_top >= INT_MAX - frame->crop_bottom ||
606 (frame->crop_left + frame->crop_right) >= frame->width ||
607 (frame->crop_top + frame->crop_bottom) >= frame->height) {
608 av_log(avctx, AV_LOG_WARNING,
609 "Invalid cropping information set by a decoder: "
610 "%"SIZE_SPECIFIER"/%"SIZE_SPECIFIER"/%"SIZE_SPECIFIER"/%"SIZE_SPECIFIER" "
611 "(frame size %dx%d). This is a bug, please report it\n",
612 frame->crop_left, frame->crop_right, frame->crop_top, frame->crop_bottom,
613 frame->width, frame->height);
614 frame->crop_left = 0;
615 frame->crop_right = 0;
617 frame->crop_bottom = 0;
621 if (!avctx->apply_cropping)
624 return av_frame_apply_cropping(frame, avctx->flags & AV_CODEC_FLAG_UNALIGNED ?
625 AV_FRAME_CROP_UNALIGNED : 0);
628 int attribute_align_arg avcodec_receive_frame(AVCodecContext *avctx, AVFrame *frame)
630 AVCodecInternal *avci = avctx->internal;
633 av_frame_unref(frame);
635 if (!avcodec_is_open(avctx) || !av_codec_is_decoder(avctx->codec))
636 return AVERROR(EINVAL);
638 if (avci->buffer_frame->buf[0]) {
639 av_frame_move_ref(frame, avci->buffer_frame);
641 ret = decode_receive_frame_internal(avctx, frame);
646 if (avctx->codec_type == AVMEDIA_TYPE_VIDEO) {
647 ret = apply_cropping(avctx, frame);
649 av_frame_unref(frame);
654 avctx->frame_number++;
656 if (avctx->flags & AV_CODEC_FLAG_DROPCHANGED) {
658 if (avctx->frame_number == 1) {
659 avci->initial_format = frame->format;
660 switch(avctx->codec_type) {
661 case AVMEDIA_TYPE_VIDEO:
662 avci->initial_width = frame->width;
663 avci->initial_height = frame->height;
665 case AVMEDIA_TYPE_AUDIO:
666 avci->initial_sample_rate = frame->sample_rate ? frame->sample_rate :
668 avci->initial_channels = frame->channels;
669 avci->initial_channel_layout = frame->channel_layout;
674 if (avctx->frame_number > 1) {
675 changed = avci->initial_format != frame->format;
677 switch(avctx->codec_type) {
678 case AVMEDIA_TYPE_VIDEO:
679 changed |= avci->initial_width != frame->width ||
680 avci->initial_height != frame->height;
682 case AVMEDIA_TYPE_AUDIO:
683 changed |= avci->initial_sample_rate != frame->sample_rate ||
684 avci->initial_sample_rate != avctx->sample_rate ||
685 avci->initial_channels != frame->channels ||
686 avci->initial_channel_layout != frame->channel_layout;
691 avci->changed_frames_dropped++;
692 av_log(avctx, AV_LOG_INFO, "dropped changed frame #%d pts %"PRId64
693 " drop count: %d \n",
694 avctx->frame_number, frame->pts,
695 avci->changed_frames_dropped);
696 av_frame_unref(frame);
697 return AVERROR_INPUT_CHANGED;
704 static void get_subtitle_defaults(AVSubtitle *sub)
706 memset(sub, 0, sizeof(*sub));
707 sub->pts = AV_NOPTS_VALUE;
710 #define UTF8_MAX_BYTES 4 /* 5 and 6 bytes sequences should not be used */
711 static int recode_subtitle(AVCodecContext *avctx, AVPacket **outpkt,
712 AVPacket *inpkt, AVPacket *buf_pkt)
715 iconv_t cd = (iconv_t)-1;
721 if (avctx->sub_charenc_mode != FF_SUB_CHARENC_MODE_PRE_DECODER || inpkt->size == 0) {
730 if (inl >= INT_MAX / UTF8_MAX_BYTES - AV_INPUT_BUFFER_PADDING_SIZE) {
731 av_log(avctx, AV_LOG_ERROR, "Subtitles packet is too big for recoding\n");
732 return AVERROR(ERANGE);
735 cd = iconv_open("UTF-8", avctx->sub_charenc);
736 av_assert0(cd != (iconv_t)-1);
738 ret = av_new_packet(buf_pkt, inl * UTF8_MAX_BYTES);
741 ret = av_packet_copy_props(buf_pkt, inpkt);
744 outb = buf_pkt->data;
745 outl = buf_pkt->size;
747 if (iconv(cd, &inb, &inl, &outb, &outl) == (size_t)-1 ||
748 iconv(cd, NULL, NULL, &outb, &outl) == (size_t)-1 ||
749 outl >= buf_pkt->size || inl != 0) {
750 ret = FFMIN(AVERROR(errno), -1);
751 av_log(avctx, AV_LOG_ERROR, "Unable to recode subtitle event \"%s\" "
752 "from %s to UTF-8\n", inpkt->data, avctx->sub_charenc);
755 buf_pkt->size -= outl;
756 memset(buf_pkt->data + buf_pkt->size, 0, outl);
762 av_packet_unref(buf_pkt);
763 if (cd != (iconv_t)-1)
767 av_log(avctx, AV_LOG_ERROR, "requesting subtitles recoding without iconv");
768 return AVERROR(EINVAL);
772 static int utf8_check(const uint8_t *str)
775 uint32_t codepoint, min;
779 GET_UTF8(codepoint, *(byte++), return 0;);
780 min = byte - str == 1 ? 0 : byte - str == 2 ? 0x80 :
781 1 << (5 * (byte - str) - 4);
782 if (codepoint < min || codepoint >= 0x110000 ||
783 codepoint == 0xFFFE /* BOM */ ||
784 codepoint >= 0xD800 && codepoint <= 0xDFFF /* surrogates */)
791 int avcodec_decode_subtitle2(AVCodecContext *avctx, AVSubtitle *sub,
797 if (!avpkt->data && avpkt->size) {
798 av_log(avctx, AV_LOG_ERROR, "invalid packet: NULL data, size != 0\n");
799 return AVERROR(EINVAL);
802 return AVERROR(EINVAL);
803 if (avctx->codec->type != AVMEDIA_TYPE_SUBTITLE) {
804 av_log(avctx, AV_LOG_ERROR, "Invalid media type for subtitles\n");
805 return AVERROR(EINVAL);
809 get_subtitle_defaults(sub);
811 if ((avctx->codec->capabilities & AV_CODEC_CAP_DELAY) || avpkt->size) {
812 AVCodecInternal *avci = avctx->internal;
815 ret = recode_subtitle(avctx, &pkt, avpkt, avci->buffer_pkt);
819 if (avctx->pkt_timebase.num && avpkt->pts != AV_NOPTS_VALUE)
820 sub->pts = av_rescale_q(avpkt->pts,
821 avctx->pkt_timebase, AV_TIME_BASE_Q);
822 ret = avctx->codec->decode(avctx, sub, got_sub_ptr, pkt);
823 av_assert1((ret >= 0) >= !!*got_sub_ptr &&
824 !!*got_sub_ptr >= !!sub->num_rects);
826 if (sub->num_rects && !sub->end_display_time && avpkt->duration &&
827 avctx->pkt_timebase.num) {
828 AVRational ms = { 1, 1000 };
829 sub->end_display_time = av_rescale_q(avpkt->duration,
830 avctx->pkt_timebase, ms);
833 if (avctx->codec_descriptor->props & AV_CODEC_PROP_BITMAP_SUB)
835 else if (avctx->codec_descriptor->props & AV_CODEC_PROP_TEXT_SUB)
838 for (unsigned i = 0; i < sub->num_rects; i++) {
839 if (avctx->sub_charenc_mode != FF_SUB_CHARENC_MODE_IGNORE &&
840 sub->rects[i]->ass && !utf8_check(sub->rects[i]->ass)) {
841 av_log(avctx, AV_LOG_ERROR,
842 "Invalid UTF-8 in decoded subtitles text; "
843 "maybe missing -sub_charenc option\n");
844 avsubtitle_free(sub);
845 ret = AVERROR_INVALIDDATA;
851 avctx->frame_number++;
853 if (pkt == avci->buffer_pkt) // did we recode?
854 av_packet_unref(avci->buffer_pkt);
860 enum AVPixelFormat avcodec_default_get_format(struct AVCodecContext *avctx,
861 const enum AVPixelFormat *fmt)
863 const AVPixFmtDescriptor *desc;
864 const AVCodecHWConfig *config;
867 // If a device was supplied when the codec was opened, assume that the
868 // user wants to use it.
869 if (avctx->hw_device_ctx && avctx->codec->hw_configs) {
870 AVHWDeviceContext *device_ctx =
871 (AVHWDeviceContext*)avctx->hw_device_ctx->data;
873 config = &avctx->codec->hw_configs[i]->public;
876 if (!(config->methods &
877 AV_CODEC_HW_CONFIG_METHOD_HW_DEVICE_CTX))
879 if (device_ctx->type != config->device_type)
881 for (n = 0; fmt[n] != AV_PIX_FMT_NONE; n++) {
882 if (config->pix_fmt == fmt[n])
887 // No device or other setup, so we have to choose from things which
888 // don't any other external information.
890 // If the last element of the list is a software format, choose it
891 // (this should be best software format if any exist).
892 for (n = 0; fmt[n] != AV_PIX_FMT_NONE; n++);
893 desc = av_pix_fmt_desc_get(fmt[n - 1]);
894 if (!(desc->flags & AV_PIX_FMT_FLAG_HWACCEL))
897 // Finally, traverse the list in order and choose the first entry
898 // with no external dependencies (if there is no hardware configuration
899 // information available then this just picks the first entry).
900 for (n = 0; fmt[n] != AV_PIX_FMT_NONE; n++) {
902 config = avcodec_get_hw_config(avctx->codec, i);
905 if (config->pix_fmt == fmt[n])
909 // No specific config available, so the decoder must be able
910 // to handle this format without any additional setup.
913 if (config->methods & AV_CODEC_HW_CONFIG_METHOD_INTERNAL) {
914 // Usable with only internal setup.
919 // Nothing is usable, give up.
920 return AV_PIX_FMT_NONE;
923 int ff_decode_get_hw_frames_ctx(AVCodecContext *avctx,
924 enum AVHWDeviceType dev_type)
926 AVHWDeviceContext *device_ctx;
927 AVHWFramesContext *frames_ctx;
931 return AVERROR(ENOSYS);
933 if (avctx->hw_frames_ctx)
935 if (!avctx->hw_device_ctx) {
936 av_log(avctx, AV_LOG_ERROR, "A hardware frames or device context is "
937 "required for hardware accelerated decoding.\n");
938 return AVERROR(EINVAL);
941 device_ctx = (AVHWDeviceContext *)avctx->hw_device_ctx->data;
942 if (device_ctx->type != dev_type) {
943 av_log(avctx, AV_LOG_ERROR, "Device type %s expected for hardware "
944 "decoding, but got %s.\n", av_hwdevice_get_type_name(dev_type),
945 av_hwdevice_get_type_name(device_ctx->type));
946 return AVERROR(EINVAL);
949 ret = avcodec_get_hw_frames_parameters(avctx,
950 avctx->hw_device_ctx,
951 avctx->hwaccel->pix_fmt,
952 &avctx->hw_frames_ctx);
956 frames_ctx = (AVHWFramesContext*)avctx->hw_frames_ctx->data;
959 if (frames_ctx->initial_pool_size) {
960 // We guarantee 4 base work surfaces. The function above guarantees 1
961 // (the absolute minimum), so add the missing count.
962 frames_ctx->initial_pool_size += 3;
965 ret = av_hwframe_ctx_init(avctx->hw_frames_ctx);
967 av_buffer_unref(&avctx->hw_frames_ctx);
974 int avcodec_get_hw_frames_parameters(AVCodecContext *avctx,
975 AVBufferRef *device_ref,
976 enum AVPixelFormat hw_pix_fmt,
977 AVBufferRef **out_frames_ref)
979 AVBufferRef *frames_ref = NULL;
980 const AVCodecHWConfigInternal *hw_config;
981 const AVHWAccel *hwa;
985 hw_config = avctx->codec->hw_configs[i];
987 return AVERROR(ENOENT);
988 if (hw_config->public.pix_fmt == hw_pix_fmt)
992 hwa = hw_config->hwaccel;
993 if (!hwa || !hwa->frame_params)
994 return AVERROR(ENOENT);
996 frames_ref = av_hwframe_ctx_alloc(device_ref);
998 return AVERROR(ENOMEM);
1000 ret = hwa->frame_params(avctx, frames_ref);
1002 AVHWFramesContext *frames_ctx = (AVHWFramesContext*)frames_ref->data;
1004 if (frames_ctx->initial_pool_size) {
1005 // If the user has requested that extra output surfaces be
1006 // available then add them here.
1007 if (avctx->extra_hw_frames > 0)
1008 frames_ctx->initial_pool_size += avctx->extra_hw_frames;
1010 // If frame threading is enabled then an extra surface per thread
1011 // is also required.
1012 if (avctx->active_thread_type & FF_THREAD_FRAME)
1013 frames_ctx->initial_pool_size += avctx->thread_count;
1016 *out_frames_ref = frames_ref;
1018 av_buffer_unref(&frames_ref);
1023 static int hwaccel_init(AVCodecContext *avctx,
1024 const AVCodecHWConfigInternal *hw_config)
1026 const AVHWAccel *hwaccel;
1029 hwaccel = hw_config->hwaccel;
1030 if (hwaccel->capabilities & AV_HWACCEL_CODEC_CAP_EXPERIMENTAL &&
1031 avctx->strict_std_compliance > FF_COMPLIANCE_EXPERIMENTAL) {
1032 av_log(avctx, AV_LOG_WARNING, "Ignoring experimental hwaccel: %s\n",
1034 return AVERROR_PATCHWELCOME;
1037 if (hwaccel->priv_data_size) {
1038 avctx->internal->hwaccel_priv_data =
1039 av_mallocz(hwaccel->priv_data_size);
1040 if (!avctx->internal->hwaccel_priv_data)
1041 return AVERROR(ENOMEM);
1044 avctx->hwaccel = hwaccel;
1045 if (hwaccel->init) {
1046 err = hwaccel->init(avctx);
1048 av_log(avctx, AV_LOG_ERROR, "Failed setup for format %s: "
1049 "hwaccel initialisation returned error.\n",
1050 av_get_pix_fmt_name(hw_config->public.pix_fmt));
1051 av_freep(&avctx->internal->hwaccel_priv_data);
1052 avctx->hwaccel = NULL;
1060 static void hwaccel_uninit(AVCodecContext *avctx)
1062 if (avctx->hwaccel && avctx->hwaccel->uninit)
1063 avctx->hwaccel->uninit(avctx);
1065 av_freep(&avctx->internal->hwaccel_priv_data);
1067 avctx->hwaccel = NULL;
1069 av_buffer_unref(&avctx->hw_frames_ctx);
1072 int ff_get_format(AVCodecContext *avctx, const enum AVPixelFormat *fmt)
1074 const AVPixFmtDescriptor *desc;
1075 enum AVPixelFormat *choices;
1076 enum AVPixelFormat ret, user_choice;
1077 const AVCodecHWConfigInternal *hw_config;
1078 const AVCodecHWConfig *config;
1081 // Find end of list.
1082 for (n = 0; fmt[n] != AV_PIX_FMT_NONE; n++);
1083 // Must contain at least one entry.
1085 // If a software format is available, it must be the last entry.
1086 desc = av_pix_fmt_desc_get(fmt[n - 1]);
1087 if (desc->flags & AV_PIX_FMT_FLAG_HWACCEL) {
1088 // No software format is available.
1090 avctx->sw_pix_fmt = fmt[n - 1];
1093 choices = av_malloc_array(n + 1, sizeof(*choices));
1095 return AV_PIX_FMT_NONE;
1097 memcpy(choices, fmt, (n + 1) * sizeof(*choices));
1100 // Remove the previous hwaccel, if there was one.
1101 hwaccel_uninit(avctx);
1103 user_choice = avctx->get_format(avctx, choices);
1104 if (user_choice == AV_PIX_FMT_NONE) {
1105 // Explicitly chose nothing, give up.
1106 ret = AV_PIX_FMT_NONE;
1110 desc = av_pix_fmt_desc_get(user_choice);
1112 av_log(avctx, AV_LOG_ERROR, "Invalid format returned by "
1113 "get_format() callback.\n");
1114 ret = AV_PIX_FMT_NONE;
1117 av_log(avctx, AV_LOG_DEBUG, "Format %s chosen by get_format().\n",
1120 for (i = 0; i < n; i++) {
1121 if (choices[i] == user_choice)
1125 av_log(avctx, AV_LOG_ERROR, "Invalid return from get_format(): "
1126 "%s not in possible list.\n", desc->name);
1127 ret = AV_PIX_FMT_NONE;
1131 if (avctx->codec->hw_configs) {
1133 hw_config = avctx->codec->hw_configs[i];
1136 if (hw_config->public.pix_fmt == user_choice)
1144 // No config available, so no extra setup required.
1148 config = &hw_config->public;
1150 if (config->methods &
1151 AV_CODEC_HW_CONFIG_METHOD_HW_FRAMES_CTX &&
1152 avctx->hw_frames_ctx) {
1153 const AVHWFramesContext *frames_ctx =
1154 (AVHWFramesContext*)avctx->hw_frames_ctx->data;
1155 if (frames_ctx->format != user_choice) {
1156 av_log(avctx, AV_LOG_ERROR, "Invalid setup for format %s: "
1157 "does not match the format of the provided frames "
1158 "context.\n", desc->name);
1161 } else if (config->methods &
1162 AV_CODEC_HW_CONFIG_METHOD_HW_DEVICE_CTX &&
1163 avctx->hw_device_ctx) {
1164 const AVHWDeviceContext *device_ctx =
1165 (AVHWDeviceContext*)avctx->hw_device_ctx->data;
1166 if (device_ctx->type != config->device_type) {
1167 av_log(avctx, AV_LOG_ERROR, "Invalid setup for format %s: "
1168 "does not match the type of the provided device "
1169 "context.\n", desc->name);
1172 } else if (config->methods &
1173 AV_CODEC_HW_CONFIG_METHOD_INTERNAL) {
1174 // Internal-only setup, no additional configuration.
1175 } else if (config->methods &
1176 AV_CODEC_HW_CONFIG_METHOD_AD_HOC) {
1177 // Some ad-hoc configuration we can't see and can't check.
1179 av_log(avctx, AV_LOG_ERROR, "Invalid setup for format %s: "
1180 "missing configuration.\n", desc->name);
1183 if (hw_config->hwaccel) {
1184 av_log(avctx, AV_LOG_DEBUG, "Format %s requires hwaccel "
1185 "initialisation.\n", desc->name);
1186 err = hwaccel_init(avctx, hw_config);
1194 av_log(avctx, AV_LOG_DEBUG, "Format %s not usable, retrying "
1195 "get_format() without it.\n", desc->name);
1196 for (i = 0; i < n; i++) {
1197 if (choices[i] == user_choice)
1200 for (; i + 1 < n; i++)
1201 choices[i] = choices[i + 1];
1209 static void frame_pool_free(void *opaque, uint8_t *data)
1211 FramePool *pool = (FramePool*)data;
1214 for (i = 0; i < FF_ARRAY_ELEMS(pool->pools); i++)
1215 av_buffer_pool_uninit(&pool->pools[i]);
1220 static AVBufferRef *frame_pool_alloc(void)
1222 FramePool *pool = av_mallocz(sizeof(*pool));
1228 buf = av_buffer_create((uint8_t*)pool, sizeof(*pool),
1229 frame_pool_free, NULL, 0);
1238 static int update_frame_pool(AVCodecContext *avctx, AVFrame *frame)
1240 FramePool *pool = avctx->internal->pool ?
1241 (FramePool*)avctx->internal->pool->data : NULL;
1242 AVBufferRef *pool_buf;
1243 int i, ret, ch, planes;
1245 if (avctx->codec_type == AVMEDIA_TYPE_AUDIO) {
1246 int planar = av_sample_fmt_is_planar(frame->format);
1247 ch = frame->channels;
1248 planes = planar ? ch : 1;
1251 if (pool && pool->format == frame->format) {
1252 if (avctx->codec_type == AVMEDIA_TYPE_VIDEO &&
1253 pool->width == frame->width && pool->height == frame->height)
1255 if (avctx->codec_type == AVMEDIA_TYPE_AUDIO && pool->planes == planes &&
1256 pool->channels == ch && frame->nb_samples == pool->samples)
1260 pool_buf = frame_pool_alloc();
1262 return AVERROR(ENOMEM);
1263 pool = (FramePool*)pool_buf->data;
1265 switch (avctx->codec_type) {
1266 case AVMEDIA_TYPE_VIDEO: {
1268 int w = frame->width;
1269 int h = frame->height;
1271 ptrdiff_t linesize1[4];
1274 avcodec_align_dimensions2(avctx, &w, &h, pool->stride_align);
1277 // NOTE: do not align linesizes individually, this breaks e.g. assumptions
1278 // that linesize[0] == 2*linesize[1] in the MPEG-encoder for 4:2:2
1279 ret = av_image_fill_linesizes(linesize, avctx->pix_fmt, w);
1282 // increase alignment of w for next try (rhs gives the lowest bit set in w)
1286 for (i = 0; i < 4; i++)
1287 unaligned |= linesize[i] % pool->stride_align[i];
1288 } while (unaligned);
1290 for (i = 0; i < 4; i++)
1291 linesize1[i] = linesize[i];
1292 ret = av_image_fill_plane_sizes(size, avctx->pix_fmt, h, linesize1);
1296 for (i = 0; i < 4; i++) {
1297 pool->linesize[i] = linesize[i];
1299 if (size[i] > INT_MAX - (16 + STRIDE_ALIGN - 1)) {
1300 ret = AVERROR(EINVAL);
1303 pool->pools[i] = av_buffer_pool_init(size[i] + 16 + STRIDE_ALIGN - 1,
1304 CONFIG_MEMORY_POISONING ?
1307 if (!pool->pools[i]) {
1308 ret = AVERROR(ENOMEM);
1313 pool->format = frame->format;
1314 pool->width = frame->width;
1315 pool->height = frame->height;
1319 case AVMEDIA_TYPE_AUDIO: {
1320 ret = av_samples_get_buffer_size(&pool->linesize[0], ch,
1321 frame->nb_samples, frame->format, 0);
1325 pool->pools[0] = av_buffer_pool_init(pool->linesize[0], NULL);
1326 if (!pool->pools[0]) {
1327 ret = AVERROR(ENOMEM);
1331 pool->format = frame->format;
1332 pool->planes = planes;
1333 pool->channels = ch;
1334 pool->samples = frame->nb_samples;
1337 default: av_assert0(0);
1340 av_buffer_unref(&avctx->internal->pool);
1341 avctx->internal->pool = pool_buf;
1345 av_buffer_unref(&pool_buf);
1349 static int audio_get_buffer(AVCodecContext *avctx, AVFrame *frame)
1351 FramePool *pool = (FramePool*)avctx->internal->pool->data;
1352 int planes = pool->planes;
1355 frame->linesize[0] = pool->linesize[0];
1357 if (planes > AV_NUM_DATA_POINTERS) {
1358 frame->extended_data = av_mallocz_array(planes, sizeof(*frame->extended_data));
1359 frame->nb_extended_buf = planes - AV_NUM_DATA_POINTERS;
1360 frame->extended_buf = av_mallocz_array(frame->nb_extended_buf,
1361 sizeof(*frame->extended_buf));
1362 if (!frame->extended_data || !frame->extended_buf) {
1363 av_freep(&frame->extended_data);
1364 av_freep(&frame->extended_buf);
1365 return AVERROR(ENOMEM);
1368 frame->extended_data = frame->data;
1369 av_assert0(frame->nb_extended_buf == 0);
1372 for (i = 0; i < FFMIN(planes, AV_NUM_DATA_POINTERS); i++) {
1373 frame->buf[i] = av_buffer_pool_get(pool->pools[0]);
1376 frame->extended_data[i] = frame->data[i] = frame->buf[i]->data;
1378 for (i = 0; i < frame->nb_extended_buf; i++) {
1379 frame->extended_buf[i] = av_buffer_pool_get(pool->pools[0]);
1380 if (!frame->extended_buf[i])
1382 frame->extended_data[i + AV_NUM_DATA_POINTERS] = frame->extended_buf[i]->data;
1385 if (avctx->debug & FF_DEBUG_BUFFERS)
1386 av_log(avctx, AV_LOG_DEBUG, "default_get_buffer called on frame %p", frame);
1390 av_frame_unref(frame);
1391 return AVERROR(ENOMEM);
1394 static int video_get_buffer(AVCodecContext *s, AVFrame *pic)
1396 FramePool *pool = (FramePool*)s->internal->pool->data;
1397 const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(pic->format);
1400 if (pic->data[0] || pic->data[1] || pic->data[2] || pic->data[3]) {
1401 av_log(s, AV_LOG_ERROR, "pic->data[*]!=NULL in avcodec_default_get_buffer\n");
1406 av_log(s, AV_LOG_ERROR,
1407 "Unable to get pixel format descriptor for format %s\n",
1408 av_get_pix_fmt_name(pic->format));
1409 return AVERROR(EINVAL);
1412 memset(pic->data, 0, sizeof(pic->data));
1413 pic->extended_data = pic->data;
1415 for (i = 0; i < 4 && pool->pools[i]; i++) {
1416 pic->linesize[i] = pool->linesize[i];
1418 pic->buf[i] = av_buffer_pool_get(pool->pools[i]);
1422 pic->data[i] = pic->buf[i]->data;
1424 for (; i < AV_NUM_DATA_POINTERS; i++) {
1425 pic->data[i] = NULL;
1426 pic->linesize[i] = 0;
1428 if (desc->flags & AV_PIX_FMT_FLAG_PAL ||
1429 ((desc->flags & FF_PSEUDOPAL) && pic->data[1]))
1430 avpriv_set_systematic_pal2((uint32_t *)pic->data[1], pic->format);
1432 if (s->debug & FF_DEBUG_BUFFERS)
1433 av_log(s, AV_LOG_DEBUG, "default_get_buffer called on pic %p\n", pic);
1437 av_frame_unref(pic);
1438 return AVERROR(ENOMEM);
1441 int avcodec_default_get_buffer2(AVCodecContext *avctx, AVFrame *frame, int flags)
1445 if (avctx->hw_frames_ctx) {
1446 ret = av_hwframe_get_buffer(avctx->hw_frames_ctx, frame, 0);
1447 frame->width = avctx->coded_width;
1448 frame->height = avctx->coded_height;
1452 if ((ret = update_frame_pool(avctx, frame)) < 0)
1455 switch (avctx->codec_type) {
1456 case AVMEDIA_TYPE_VIDEO:
1457 return video_get_buffer(avctx, frame);
1458 case AVMEDIA_TYPE_AUDIO:
1459 return audio_get_buffer(avctx, frame);
1465 static int add_metadata_from_side_data(const AVPacket *avpkt, AVFrame *frame)
1468 const uint8_t *side_metadata;
1470 AVDictionary **frame_md = &frame->metadata;
1472 side_metadata = av_packet_get_side_data(avpkt,
1473 AV_PKT_DATA_STRINGS_METADATA, &size);
1474 return av_packet_unpack_dictionary(side_metadata, size, frame_md);
1477 int ff_decode_frame_props(AVCodecContext *avctx, AVFrame *frame)
1479 AVPacket *pkt = avctx->internal->last_pkt_props;
1480 static const struct {
1481 enum AVPacketSideDataType packet;
1482 enum AVFrameSideDataType frame;
1484 { AV_PKT_DATA_REPLAYGAIN , AV_FRAME_DATA_REPLAYGAIN },
1485 { AV_PKT_DATA_DISPLAYMATRIX, AV_FRAME_DATA_DISPLAYMATRIX },
1486 { AV_PKT_DATA_SPHERICAL, AV_FRAME_DATA_SPHERICAL },
1487 { AV_PKT_DATA_STEREO3D, AV_FRAME_DATA_STEREO3D },
1488 { AV_PKT_DATA_AUDIO_SERVICE_TYPE, AV_FRAME_DATA_AUDIO_SERVICE_TYPE },
1489 { AV_PKT_DATA_MASTERING_DISPLAY_METADATA, AV_FRAME_DATA_MASTERING_DISPLAY_METADATA },
1490 { AV_PKT_DATA_CONTENT_LIGHT_LEVEL, AV_FRAME_DATA_CONTENT_LIGHT_LEVEL },
1491 { AV_PKT_DATA_A53_CC, AV_FRAME_DATA_A53_CC },
1492 { AV_PKT_DATA_ICC_PROFILE, AV_FRAME_DATA_ICC_PROFILE },
1493 { AV_PKT_DATA_S12M_TIMECODE, AV_FRAME_DATA_S12M_TIMECODE },
1496 if (IS_EMPTY(pkt) && av_fifo_size(avctx->internal->pkt_props) >= sizeof(*pkt))
1497 av_fifo_generic_read(avctx->internal->pkt_props,
1498 pkt, sizeof(*pkt), NULL);
1500 frame->pts = pkt->pts;
1501 frame->pkt_pos = pkt->pos;
1502 frame->pkt_duration = pkt->duration;
1503 frame->pkt_size = pkt->size;
1505 for (int i = 0; i < FF_ARRAY_ELEMS(sd); i++) {
1507 uint8_t *packet_sd = av_packet_get_side_data(pkt, sd[i].packet, &size);
1509 AVFrameSideData *frame_sd = av_frame_new_side_data(frame,
1513 return AVERROR(ENOMEM);
1515 memcpy(frame_sd->data, packet_sd, size);
1518 add_metadata_from_side_data(pkt, frame);
1520 if (pkt->flags & AV_PKT_FLAG_DISCARD) {
1521 frame->flags |= AV_FRAME_FLAG_DISCARD;
1523 frame->flags = (frame->flags & ~AV_FRAME_FLAG_DISCARD);
1525 frame->reordered_opaque = avctx->reordered_opaque;
1527 if (frame->color_primaries == AVCOL_PRI_UNSPECIFIED)
1528 frame->color_primaries = avctx->color_primaries;
1529 if (frame->color_trc == AVCOL_TRC_UNSPECIFIED)
1530 frame->color_trc = avctx->color_trc;
1531 if (frame->colorspace == AVCOL_SPC_UNSPECIFIED)
1532 frame->colorspace = avctx->colorspace;
1533 if (frame->color_range == AVCOL_RANGE_UNSPECIFIED)
1534 frame->color_range = avctx->color_range;
1535 if (frame->chroma_location == AVCHROMA_LOC_UNSPECIFIED)
1536 frame->chroma_location = avctx->chroma_sample_location;
1538 switch (avctx->codec->type) {
1539 case AVMEDIA_TYPE_VIDEO:
1540 frame->format = avctx->pix_fmt;
1541 if (!frame->sample_aspect_ratio.num)
1542 frame->sample_aspect_ratio = avctx->sample_aspect_ratio;
1544 if (frame->width && frame->height &&
1545 av_image_check_sar(frame->width, frame->height,
1546 frame->sample_aspect_ratio) < 0) {
1547 av_log(avctx, AV_LOG_WARNING, "ignoring invalid SAR: %u/%u\n",
1548 frame->sample_aspect_ratio.num,
1549 frame->sample_aspect_ratio.den);
1550 frame->sample_aspect_ratio = (AVRational){ 0, 1 };
1554 case AVMEDIA_TYPE_AUDIO:
1555 if (!frame->sample_rate)
1556 frame->sample_rate = avctx->sample_rate;
1557 if (frame->format < 0)
1558 frame->format = avctx->sample_fmt;
1559 if (!frame->channel_layout) {
1560 if (avctx->channel_layout) {
1561 if (av_get_channel_layout_nb_channels(avctx->channel_layout) !=
1563 av_log(avctx, AV_LOG_ERROR, "Inconsistent channel "
1564 "configuration.\n");
1565 return AVERROR(EINVAL);
1568 frame->channel_layout = avctx->channel_layout;
1570 if (avctx->channels > FF_SANE_NB_CHANNELS) {
1571 av_log(avctx, AV_LOG_ERROR, "Too many channels: %d.\n",
1573 return AVERROR(ENOSYS);
1577 frame->channels = avctx->channels;
1583 static void validate_avframe_allocation(AVCodecContext *avctx, AVFrame *frame)
1585 if (avctx->codec_type == AVMEDIA_TYPE_VIDEO) {
1587 int num_planes = av_pix_fmt_count_planes(frame->format);
1588 const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(frame->format);
1589 int flags = desc ? desc->flags : 0;
1590 if (num_planes == 1 && (flags & AV_PIX_FMT_FLAG_PAL))
1592 if ((flags & FF_PSEUDOPAL) && frame->data[1])
1594 for (i = 0; i < num_planes; i++) {
1595 av_assert0(frame->data[i]);
1597 // For formats without data like hwaccel allow unused pointers to be non-NULL.
1598 for (i = num_planes; num_planes > 0 && i < FF_ARRAY_ELEMS(frame->data); i++) {
1600 av_log(avctx, AV_LOG_ERROR, "Buffer returned by get_buffer2() did not zero unused plane pointers\n");
1601 frame->data[i] = NULL;
1606 static void decode_data_free(void *opaque, uint8_t *data)
1608 FrameDecodeData *fdd = (FrameDecodeData*)data;
1610 if (fdd->post_process_opaque_free)
1611 fdd->post_process_opaque_free(fdd->post_process_opaque);
1613 if (fdd->hwaccel_priv_free)
1614 fdd->hwaccel_priv_free(fdd->hwaccel_priv);
1619 int ff_attach_decode_data(AVFrame *frame)
1621 AVBufferRef *fdd_buf;
1622 FrameDecodeData *fdd;
1624 av_assert1(!frame->private_ref);
1625 av_buffer_unref(&frame->private_ref);
1627 fdd = av_mallocz(sizeof(*fdd));
1629 return AVERROR(ENOMEM);
1631 fdd_buf = av_buffer_create((uint8_t*)fdd, sizeof(*fdd), decode_data_free,
1632 NULL, AV_BUFFER_FLAG_READONLY);
1635 return AVERROR(ENOMEM);
1638 frame->private_ref = fdd_buf;
1643 int ff_get_buffer(AVCodecContext *avctx, AVFrame *frame, int flags)
1645 const AVHWAccel *hwaccel = avctx->hwaccel;
1646 int override_dimensions = 1;
1649 if (avctx->codec_type == AVMEDIA_TYPE_VIDEO) {
1650 if ((unsigned)avctx->width > INT_MAX - STRIDE_ALIGN ||
1651 (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) {
1652 av_log(avctx, AV_LOG_ERROR, "video_get_buffer: image parameters invalid\n");
1653 ret = AVERROR(EINVAL);
1657 if (frame->width <= 0 || frame->height <= 0) {
1658 frame->width = FFMAX(avctx->width, AV_CEIL_RSHIFT(avctx->coded_width, avctx->lowres));
1659 frame->height = FFMAX(avctx->height, AV_CEIL_RSHIFT(avctx->coded_height, avctx->lowres));
1660 override_dimensions = 0;
1663 if (frame->data[0] || frame->data[1] || frame->data[2] || frame->data[3]) {
1664 av_log(avctx, AV_LOG_ERROR, "pic->data[*]!=NULL in get_buffer_internal\n");
1665 ret = AVERROR(EINVAL);
1668 } else if (avctx->codec_type == AVMEDIA_TYPE_AUDIO) {
1669 if (frame->nb_samples * (int64_t)avctx->channels > avctx->max_samples) {
1670 av_log(avctx, AV_LOG_ERROR, "samples per frame %d, exceeds max_samples %"PRId64"\n", frame->nb_samples, avctx->max_samples);
1671 ret = AVERROR(EINVAL);
1675 ret = ff_decode_frame_props(avctx, frame);
1680 if (hwaccel->alloc_frame) {
1681 ret = hwaccel->alloc_frame(avctx, frame);
1685 avctx->sw_pix_fmt = avctx->pix_fmt;
1687 ret = avctx->get_buffer2(avctx, frame, flags);
1691 validate_avframe_allocation(avctx, frame);
1693 ret = ff_attach_decode_data(frame);
1698 if (avctx->codec_type == AVMEDIA_TYPE_VIDEO && !override_dimensions &&
1699 !(avctx->codec->caps_internal & FF_CODEC_CAP_EXPORTS_CROPPING)) {
1700 frame->width = avctx->width;
1701 frame->height = avctx->height;
1706 av_log(avctx, AV_LOG_ERROR, "get_buffer() failed\n");
1707 av_frame_unref(frame);
1713 static int reget_buffer_internal(AVCodecContext *avctx, AVFrame *frame, int flags)
1718 av_assert0(avctx->codec_type == AVMEDIA_TYPE_VIDEO);
1720 if (frame->data[0] && (frame->width != avctx->width || frame->height != avctx->height || frame->format != avctx->pix_fmt)) {
1721 av_log(avctx, AV_LOG_WARNING, "Picture changed from size:%dx%d fmt:%s to size:%dx%d fmt:%s in reget buffer()\n",
1722 frame->width, frame->height, av_get_pix_fmt_name(frame->format), avctx->width, avctx->height, av_get_pix_fmt_name(avctx->pix_fmt));
1723 av_frame_unref(frame);
1726 if (!frame->data[0])
1727 return ff_get_buffer(avctx, frame, AV_GET_BUFFER_FLAG_REF);
1729 if ((flags & FF_REGET_BUFFER_FLAG_READONLY) || av_frame_is_writable(frame))
1730 return ff_decode_frame_props(avctx, frame);
1732 tmp = av_frame_alloc();
1734 return AVERROR(ENOMEM);
1736 av_frame_move_ref(tmp, frame);
1738 ret = ff_get_buffer(avctx, frame, AV_GET_BUFFER_FLAG_REF);
1740 av_frame_free(&tmp);
1744 av_frame_copy(frame, tmp);
1745 av_frame_free(&tmp);
1750 int ff_reget_buffer(AVCodecContext *avctx, AVFrame *frame, int flags)
1752 int ret = reget_buffer_internal(avctx, frame, flags);
1754 av_log(avctx, AV_LOG_ERROR, "reget_buffer() failed\n");
1758 int ff_decode_preinit(AVCodecContext *avctx)
1762 /* if the decoder init function was already called previously,
1763 * free the already allocated subtitle_header before overwriting it */
1764 av_freep(&avctx->subtitle_header);
1766 #if FF_API_THREAD_SAFE_CALLBACKS
1767 FF_DISABLE_DEPRECATION_WARNINGS
1768 if ((avctx->thread_type & FF_THREAD_FRAME) &&
1769 avctx->get_buffer2 != avcodec_default_get_buffer2 &&
1770 !avctx->thread_safe_callbacks) {
1771 av_log(avctx, AV_LOG_WARNING, "Requested frame threading with a "
1772 "custom get_buffer2() implementation which is not marked as "
1773 "thread safe. This is not supported anymore, make your "
1774 "callback thread-safe.\n");
1776 FF_ENABLE_DEPRECATION_WARNINGS
1779 if (avctx->codec_type == AVMEDIA_TYPE_AUDIO && avctx->channels == 0 &&
1780 !(avctx->codec->capabilities & AV_CODEC_CAP_CHANNEL_CONF)) {
1781 av_log(avctx, AV_LOG_ERROR, "Decoder requires channel count but channels not set\n");
1782 return AVERROR(EINVAL);
1784 if (avctx->codec->max_lowres < avctx->lowres || avctx->lowres < 0) {
1785 av_log(avctx, AV_LOG_WARNING, "The maximum value for lowres supported by the decoder is %d\n",
1786 avctx->codec->max_lowres);
1787 avctx->lowres = avctx->codec->max_lowres;
1789 if (avctx->sub_charenc) {
1790 if (avctx->codec_type != AVMEDIA_TYPE_SUBTITLE) {
1791 av_log(avctx, AV_LOG_ERROR, "Character encoding is only "
1792 "supported with subtitles codecs\n");
1793 return AVERROR(EINVAL);
1794 } else if (avctx->codec_descriptor->props & AV_CODEC_PROP_BITMAP_SUB) {
1795 av_log(avctx, AV_LOG_WARNING, "Codec '%s' is bitmap-based, "
1796 "subtitles character encoding will be ignored\n",
1797 avctx->codec_descriptor->name);
1798 avctx->sub_charenc_mode = FF_SUB_CHARENC_MODE_DO_NOTHING;
1800 /* input character encoding is set for a text based subtitle
1801 * codec at this point */
1802 if (avctx->sub_charenc_mode == FF_SUB_CHARENC_MODE_AUTOMATIC)
1803 avctx->sub_charenc_mode = FF_SUB_CHARENC_MODE_PRE_DECODER;
1805 if (avctx->sub_charenc_mode == FF_SUB_CHARENC_MODE_PRE_DECODER) {
1807 iconv_t cd = iconv_open("UTF-8", avctx->sub_charenc);
1808 if (cd == (iconv_t)-1) {
1809 ret = AVERROR(errno);
1810 av_log(avctx, AV_LOG_ERROR, "Unable to open iconv context "
1811 "with input character encoding \"%s\"\n", avctx->sub_charenc);
1816 av_log(avctx, AV_LOG_ERROR, "Character encoding subtitles "
1817 "conversion needs a libavcodec built with iconv support "
1818 "for this codec\n");
1819 return AVERROR(ENOSYS);
1825 avctx->pts_correction_num_faulty_pts =
1826 avctx->pts_correction_num_faulty_dts = 0;
1827 avctx->pts_correction_last_pts =
1828 avctx->pts_correction_last_dts = INT64_MIN;
1830 if ( !CONFIG_GRAY && avctx->flags & AV_CODEC_FLAG_GRAY
1831 && avctx->codec_descriptor->type == AVMEDIA_TYPE_VIDEO)
1832 av_log(avctx, AV_LOG_WARNING,
1833 "gray decoding requested but not enabled at configuration time\n");
1834 if (avctx->flags2 & AV_CODEC_FLAG2_EXPORT_MVS) {
1835 avctx->export_side_data |= AV_CODEC_EXPORT_DATA_MVS;
1838 ret = decode_bsfs_init(avctx);
1845 int ff_copy_palette(void *dst, const AVPacket *src, void *logctx)
1848 const void *pal = av_packet_get_side_data(src, AV_PKT_DATA_PALETTE, &size);
1850 if (pal && size == AVPALETTE_SIZE) {
1851 memcpy(dst, pal, AVPALETTE_SIZE);
1854 av_log(logctx, AV_LOG_ERROR, "Palette size %d is wrong\n", size);