From 2cca36cec796856ccc754068ad775cce91e88a25 Mon Sep 17 00:00:00 2001
From: Sanil Dulal <sanildulal187@gmail.com>
Date: Fri, 18 Sep 2026 07:50:47 +0545
Subject: [PATCH] avformat/nutenc: fix SIGFPE on large block_align

build_frame_code() stores frame_bytes + 2 in FrameCode.size_mul, which is
uint16_t, while frame_bytes is taken from AVCodecParameters.block_align.
When remuxing, block_align comes straight from the input file: nBlockAlign
is a 16 bit field in wav/avi/asf, so 65534 is representable and reaches the
muxer unmodified. 65534 + 2 wraps to 0 and get_needed_flags then evaluates

    pkt->size / fc->size_mul

raising SIGFPE. nut_write_packet divides by the same field in three further
places. The frame code search evaluates every entry that is not marked
FLAG_INVALID, so size_mul has to stay non-zero for all of them.

Reproducible with a wav whose fmt chunk carries nBlockAlign=65534:

    ffmpeg -i poc.wav -c copy out.nut
    Floating point exception (core dumped)

Streams whose frame size is not representable now get no size optimised
frame codes instead. Values that already worked are untouched, the clamp
only triggers below 0 and above UINT16_MAX - 2, and the output for a stream
with a representable block_align is bit identical. fate-lavf-nut passes
unchanged.

Signed-off-by: Sanil Dulal <sanildulal187@gmail.com>
---
 libavformat/nutenc.c | 8 ++++++++
 1 file changed, 8 insertions(+)

diff --git a/libavformat/nutenc.c b/libavformat/nutenc.c
index 55efb11..29f635c 100644
--- a/libavformat/nutenc.c
+++ b/libavformat/nutenc.c
@@ -235,6 +235,14 @@ static void build_frame_code(AVFormatContext *s)
                 frame_bytes = frame_size * (int64_t)par->bit_rate / (8 * par->sample_rate);
             }
 
+            /* size_mul is uint16_t and the frame code search divides by
+             * it, so it must never wrap to zero. block_align is attacker
+             * controlled, it is a 16 bit field in wav/avi/asf, and 65534
+             * makes frame_bytes + 2 wrap and raises SIGFPE. Streams with an
+             * out of range frame size get no size optimised frame codes. */
+            if (frame_bytes < 0 || frame_bytes > UINT16_MAX - 2)
+                frame_bytes = 0;
+
             for (pts = 0; pts < 2; pts++) {
                 for (pred = 0; pred < 2; pred++) {
                     FrameCode *ft  = &nut->frame_code[start2];
-- 
2.42.0.windows.2

