From 7de69e952cd7869ec2de70f351abce318c3183dc Mon Sep 17 00:00:00 2001 From: Michael Niedermayer Date: Tue, 20 Oct 2026 15:09:56 +0200 Subject: [PATCH] avcodec/decode: add a function returning subtitle packet data followed by a 0 byte Text subtitle decoders parse the packet data as a string, but the padding after it is not required to be zero, and in laced Matroska blocks it holds the next event. The data is copied only when its first padding byte is not 0. --- libavcodec/decode.c | 15 +++++++++++++-- libavcodec/decode.h | 9 +++++++++ 2 files changed, 22 insertions(+), 2 deletions(-) diff --git a/libavcodec/decode.c b/libavcodec/decode.c index 097691dd58..6584c5b5ca 100644 --- a/libavcodec/decode.c +++ b/libavcodec/decode.c @@ -936,6 +936,18 @@ static int utf8_check(const uint8_t *str) return 1; } +const char *ff_decode_subtitle_text(AVCodecContext *avctx, const AVPacket *avpkt) +{ + AVPacket *copy = avctx->internal->buffer_pkt; + + if (avpkt->size <= 0 || !avpkt->data[avpkt->size]) + return avpkt->data; + if (av_new_packet(copy, avpkt->size) < 0) + return NULL; + memcpy(copy->data, avpkt->data, avpkt->size); + return copy->data; +} + int avcodec_decode_subtitle2(AVCodecContext *avctx, AVSubtitle *sub, int *got_sub_ptr, const AVPacket *avpkt) { @@ -967,8 +979,7 @@ int avcodec_decode_subtitle2(AVCodecContext *avctx, AVSubtitle *sub, sub->pts = av_rescale_q(avpkt->pts, avctx->pkt_timebase, AV_TIME_BASE_Q); ret = ffcodec(avctx->codec)->cb.decode_sub(avctx, sub, got_sub_ptr, pkt); - if (pkt == avci->buffer_pkt) // did we recode? - av_packet_unref(avci->buffer_pkt); + av_packet_unref(avci->buffer_pkt); if (ret < 0) { *got_sub_ptr = 0; avsubtitle_free(sub); diff --git a/libavcodec/decode.h b/libavcodec/decode.h index 42f5e1e9df..cfe0a11ce5 100644 --- a/libavcodec/decode.h +++ b/libavcodec/decode.h @@ -241,4 +241,13 @@ int ff_decode_content_light_new_ext(const AVCodecContext *avctx, AVFrameSideData ***sd, int *nb_sd, struct AVContentLightMetadata **clm); +/** + * Get the data of a subtitle packet followed by a 0 byte. + * + * @return avpkt->data if avpkt->size <= 0 or its first padding byte is 0, + * otherwise a copy valid until the decode callback returns, + * NULL on allocation failure + */ +const char *ff_decode_subtitle_text(AVCodecContext *avctx, const AVPacket *avpkt); + #endif /* AVCODEC_DECODE_H */