From 2e77e06923ef2524099a5775d4bc5188a2267a6b Mon Sep 17 00:00:00 2001 From: Christopher Date: Tue, 31 Mar 2026 11:22:26 -0500 Subject: [PATCH] fix(mjpeg): correct dimension clamping and add EOI bounds guard w &= 3 and h &= 3 kept only the low 2 bits instead of rounding down to the nearest multiple of 4. For example, a 1921-pixel-wide frame would be encoded with width=1 rather than width=1920, producing a corrupt or zero-size RTP packet. The correct operator is &^= 3 (bit-clear), which zeroes the low two bits. Also guard the JPEG EOI check with len(buf) >= 2 before indexing the last two bytes, preventing a panic on a malformed/empty frame. --- pkg/mjpeg/rtp.go | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/pkg/mjpeg/rtp.go b/pkg/mjpeg/rtp.go index 7a9347ef7..193b0b6ce 100644 --- a/pkg/mjpeg/rtp.go +++ b/pkg/mjpeg/rtp.go @@ -72,7 +72,7 @@ func RTPDepay(handlerFunc core.HandlerFunc) core.HandlerFunc { return } - if end := buf[len(buf)-2:]; end[0] != 0xFF && end[1] != 0xD9 { + if len(buf) >= 2 && buf[len(buf)-2] != 0xFF && buf[len(buf)-1] != 0xD9 { buf = append(buf, 0xFF, 0xD9) } @@ -196,12 +196,12 @@ func Transcode(b []byte) ([]byte, error) { if w > 2040 { w = 2040 } else if w&3 > 0 { - w &= 3 + w &^= 3 // round down to nearest multiple of 4 } if h > 2040 { h = 2040 } else if h&3 > 0 { - h &= 3 + h &^= 3 // round down to nearest multiple of 4 } if w != wh.X || h != wh.Y {