The in-place luma blend for planar YUV added in 0574a4eb3 calls the blend
helper with linesize * height, bypassing the block split in Blend. The
NEON helper consumes 64 bytes per iteration, so a Y plane that is not a
multiple of 64 (a 32-byte linesize and an odd height) ran its loop off the
end of memory. On macOS arm64 the Image::Blend odd-size test died with
SIGBUS whenever an earlier test had selected the SIMD helpers.
Move the block split into BlendBlocks() and use it for both paths. Add a
YUV420P case whose luma plane is 160 bytes.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Unless the buffer was held, Blend swapped the image's buffer with its
blend buffer. The blend buffer is freed with zm_freealigned(), so swapping
in a caller's buffer, or one from malloc or new, freed memory the image
did not own or freed it the wrong way: a double free for an image over a
caller's buffer. The swap also left allocation describing the old buffer.
Swap only a buffer from AllocBuffer() and swap the allocation sizes with
it; copy the result back otherwise.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Blend handed the image's whole buffer to the fast blend helper, which
consumes 16 bytes per iteration (unrolled C, SSE2) or 64 (NEON). The SIMD
variants wrap their loop counter past zero on a count that is not a
multiple of their block and run off the end of memory; the C one overruns
by up to a block. size is only a multiple of 32 for an aligned image, so an
odd number of rows at a width such as 1366 crashed NEON, and an image over a
caller's unaligned buffer could crash SSE2 too.
Blend the 64-byte bulk in place and the remainder through zero-padded
64-byte copies, so every byte still goes through the selected helper.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The NEON delta helpers consume 64 gray8 pixels or 16 rgb32 pixels per
iteration, not the 16 and 4 of the SSE2 and unrolled C ones that Delta split
each row by. A row whose bulk was a multiple of 16 but not 64 (gray8), or of 4
but not 16 (rgb32), wrapped the NEON loop counter past zero and ran off the end
of memory, so zmc crashed on ARM with motion detection at widths such as 1366.
On macOS arm64 the Delta tests die with SIGBUS when they are the first to
initialise Image, which made the macOS CI job fail depending on test order.
Split rows into 64- and 16-pixel blocks, which every variant divides, and leave
the rest to the scalar tail. Add an rgb32 case whose bulk runs one NEON block.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The delta8_* helpers consume whole blocks per iteration (16 pixels for
the gray8 unrolled/SSE2/NEON variants, 4 pixels for the rgb32 ones). The
SSE2 and NEON variants require the pixel count to be an exact multiple of
that block: a shorter count wraps the loop counter past zero and runs off
the end of memory, and the unrolled C variants overrun by up to a block.
Since PR #4788 made Delta stride-aware it drives those helpers row by row
with the row width as the count. update_function_pointers() only falls
back to the scalar helpers when total pixels % 4 is non-zero, which does
not imply each row width is block-aligned. A monitor whose width is not a
multiple of 16 (e.g. 1366) therefore reaches sse2_delta8_gray8 with a
count of 1366 and zmc dies with SIGSEGV in that loop.
Run the block-aligned bulk of each row through the fast/SIMD helper and
finish the remaining tail pixels with the matching one-pixel-at-a-time
scalar helper.
tests/zm_image_delta.cpp exercises gray8 (widths 17 and 1366) and rgb32
(width 6) at counts that select the SIMD path; each reproduces the crash
on the unfixed code and verifies the per-pixel result on the fix.
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Monitor::Decode scales the Y-channel image when the camera's resolution
differs from the monitor's. That image is get_y_image()'s zero-copy wrap of
the decoder's Y plane, whose stride is the decoder's linesize[0], not the
FFALIGN(width,32) that Scale assumed when it handed the buffer to
SWScale::Convert at align 32. Each row was read from the wrong offset, so
the scaled analysis image, and the alarm pixels drawn from it, came out
sheared.
Set up the source and destination frames in Scale, override plane 0's
stride with the Image's linesize as Rotate and Flip already do, and convert
through SWScale::Convert(AVFrame*, AVFrame*). The output layout is
unchanged (align 32).
tests/zm_image_linesize.cpp: scale a 40 wide GRAY8 plane with a 48 byte
stride and check that every output row is still flat.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
A YUV420P chroma sample covers 2x2 luma pixels. Image::Crop started the
chroma planes at lo_x >> 1 and lo_y >> 1, so a crop starting on an odd
column or row had its chroma half a pixel off its luma. nph-zms zoom picks
any position, so a zoomed live view could show colour fringes.
For planar formats, move the crop window back to the chroma grid before
copying, keeping its size. Moving left or up can't leave the image.
Also use the existing ceil_rshift() for the chroma copy sizes instead of
writing the same calculation inline, moving it above Crop.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Image::Crop copied the cropped rows into a tightly packed
width * colours buffer. Since AssignDirect checks the size against
av_image_get_buffer_size(..., 32), it refused that buffer whenever a
cropped row was not a multiple of 32 bytes, and always for YUV420P,
whose chroma planes Crop did not copy at all. It logged "Attempt to
directly assign buffer from an undersized buffer", the image stayed
uncropped and the new buffer leaked. nph-zms crops every frame of a
zoomed live stream: zoom had no effect and the process grew by one
cropped frame per frame sent (about 39 MB in 10 s at 1280x720, 5 fps).
Allocate the result with av_image_get_buffer_size at 32-byte alignment
and copy each plane with its own offset and stride, as Image::Rotate and
Image::Flip do.
fixes#5265
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Annotate() clamped the label position to [0, width - text_width] in unsigned
arithmetic. A label wider (or taller) than the frame wrapped that bound to about
four billion, so the requested LabelX/LabelY was used unchanged and glyph rows were
written past the end of the frame buffer on every captured frame. The label text,
position and size are monitor settings any editor of that monitor can change.
Compute the bounds in signed arithmetic and floor them at zero. Draw a glyph only
when its whole cell fits in the row and a line only when it fits in the frame,
rather than checking after the glyph is already drawn, and skip foreground pixels
that fall outside the row (the shipped font reaches one column past the cell).
LabelSize indexed the font variants with size - 1 through at(), so 0 or anything
above 4 threw out_of_range in the capture thread. Clamp it to the valid sizes in
Annotate() and centreCoord().
Add tests that draw into a buffer followed by a guard region, covering
oversized, overlong, overtall and out-of-range label sizes in each pixel format.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
ReadJpeg() stored the JPEG header's width and height in the Image before
calling WriteBuffer(). WriteBuffer() reallocates only when the requested
size differs from the current one, so it saw no change and kept the
existing buffer and linesize, and the scanline loop then decoded every
row of a larger file past its end. A File monitor re-reads its source
into a monitor-sized image on every capture, so whoever can write that
file could overflow zmc's heap. Stored event JPEGs read by zms take the
same path.
Leave width and height to WriteBuffer(), as DecodeJpeg() already does.
FileCamera::Capture() also now refuses a file whose dimensions do not
match the monitor, since everything downstream is sized for the monitor.
Add a Catch2 case that reads a 256x192 JPEG into a 64x48 image. It
segfaulted before this change and passes after.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The alarmed/filtered pixel check methods handed Overlay() the raw GRAY8
scoring mask. Overlay keys on a non-zero source pixel and copies that byte, so
the highlight took whatever shape one byte has in the destination format: the
red channel on an RGB32 monitor, which is the whole reason alarms have always
come out red; all three channels on RGB24, giving white; luma alone on YUV420.
The zone's configured Alarm Colour was honoured only on the blob path, which
goes through HighlightEdges.
Generalise HighlightEdges into BuildHighlight, which takes an edges_only flag
and otherwise fills every marked pixel, and build the highlight for the pixel
methods the same way the blob path already builds its outline: in the
capture's own pixel format, carrying alarm_rgb, once scoring is finished with
the GRAY8 mask. HighlightEdges stays as a thin wrapper so the blob path and
its callers are unchanged.
This is a behaviour change: monitors left on the default red see no
difference, but a zone configured with any other Alarm Colour now paints that
colour instead of red or white.
Reverting the zone hunk fails the new test in all three of its sections.
Full suite: 148 cases, 12535 assertions.
Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01WBHBB95RBX7D9p8ge2WDZb
Both functions initialised p_pixfmt before the setjmp() that installs the
libjpeg error recovery point, and only read it afterwards. GCC warns that
a longjmp() out of zm_jpeg_error_exit could restore a stale register copy:
warning: variable 'p_pixfmt' might be clobbered by 'longjmp' or 'vfork'
[-Wclobbered]
Move the initialisation below the setjmp() block instead of marking the
variable volatile. Nothing between the old and new positions uses the
value and the error paths do not reference it, so behaviour is unchanged
and no live value crosses the jump.
This unblocks builds using ENABLE_WERROR.
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
A monitor whose source signals full range (Dahua h264) decodes to
AV_PIX_FMT_YUVJ420P, and Monitor passes that format through to shared memory
unchanged. When zms scales such a frame for montage or console thumbnails,
SWScale::Convert mapped only the input format through fix_deprecated_pix_fmt()
and handed the still-deprecated YUVJ format to swscale as the destination, so
libswscale logged
deprecated pixel format used, make sure you did set range correctly
for every context it built. Watch view at 100% scale never hit it because
Image::Scale returns early when the dimensions already match.
Map deprecated formats on both sides in SWScale::Convert (both the buffer and
the AVFrame overload), in Image::Assign(AVFrame*), in
Monitor::setupConvertContext and in the LocalCamera conversion context.
Mapping the destination YUVJ format to its non-J equivalent makes swscale
default that side to limited range, which would compress full-range output.
Replace zm_sws_set_input_range() with zm_sws_set_ranges(), which takes the
original pre-fix formats for both sides and sets srcRange/dstRange accordingly.
Image::Assign(AVFrame*) now compares the mapped source and destination formats,
so a YUVJ420P frame into a YUVJ420P image takes the av_image_copy fast path
instead of running through swscale.
Image::Scale built a fresh SWScale, and therefore a fresh sws context, on every
call. That is a full sws_init_context per scaled frame per stream, and it is
what turned the warning into a per-frame flood rather than a one-off. Reuse a
thread_local SWScale; sws_getCachedContext re-inits itself when the geometry
changes.
Tests: zm_swscale_range.cpp installs an av_log callback and asserts that
SWScale::Convert with a YUVJ destination and Image::Scale on a YUVJ420P image
emit no deprecated-format message, plus a luma check that the range handling
still survives the mapping.
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01NDhTBPj9xEaT52pRmAufaP
Since decoder-native passthrough, packet->image is typically YUV420P even
when the monitor's configured Colours is RGB, so the zone alarm highlight
(built from the configured colours) arrives at Image::Overlay() as
RGB24/RGB32 while the analysis image is planar YUV420. The dispatch keyed
on zm_bytes_per_pixel(target)==1, which conflates GRAY8 with planar YUV,
so the combination fell into the Colourise() branches: Colourise() warned
'Target image is already colourised, colours: 1' and returned, after which
the overlay loop walked the planar YUV buffer as packed RGB, corrupting
the saved analysis frames.
Gate the Colourise() branches to true GRAY8 targets and add a
YUV420-target branch that converts only the marked (non-black) highlight
pixels to YUV - luma plus the shared 2x2 chroma sample - honouring the
highlight's subpixel order.
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01HoNiNxwgyaHV29CbiueCUf
On suspend-resume Monitor::CheckAction() called ref_image.DumpImgBuffer()
on the capture thread while the analysis thread was using ref_image in
DetectMotion() -> Image::Delta(). DumpImgBuffer() frees the buffer and nulls
the pointer but leaves width/height/colours intact, so Delta's "different
sized images" guard still passed and the delta helper walked from a null
base pointer, faulting at address 0 on the first row. That is the reported
"Fault address: (nil)" inside the gray8 delta helper. Portrait monitors were
not special; they just made the resume-during-analysis window easy to hit.
Move the reference-image reset onto the thread that owns ref_image:
CheckAction() sets an atomic ref_image_reset_ flag and Analyse() performs
the DumpImgBuffer() itself on its next pass, so the buffer is never freed
out from under an in-flight Delta/Blend. Reject a null buffer in Image::Delta
as a defensive backstop.
Add tests/zm_zone_stride.cpp: a regression test that reproduced the null
delta crash, plus zone coverage at portrait (1080x1920, stride-padded) and
landscape dimensions through the alarmed-pixel and blob paths.
fixes#4983
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01KQipwf632JGgNH4W7p8cqs
swscale assumes limited (MPEG, 16-235) input range by default. Mapping a
full-range JPEG format (YUVJ*) to its non-J equivalent for the conversion
therefore washes the colours out, because full-range luma/chroma gets
treated as limited.
Add pix_fmt_is_jpeg_range() and zm_sws_set_input_range(), which sets
srcRange=1 on the context when the original source format was full range.
Apply it at every conversion site that takes decoded frames: Image::Assign
and both SWScale::Convert overloads. Monitor::setupConvertContext already
did this inline with a hand-rolled switch and colorspace block; replace
that with the shared helpers to remove the duplication.
Add tests/zm_swscale_range.cpp: converting a Y=16 YUVJ420P image to RGB24
keeps luma ~16 (full range) rather than being crushed to ~0 (limited).
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Image::Assign(const AVFrame*) passed the raw decoded frame format straight
to sws_getCachedContext. When the frame is a deprecated full-range JPEG
format (YUVJ420P etc, typical of MJPEG-decoded frames), swscale logs
"deprecated pixel format used, make sure you did set range correctly",
seen from nph-zms. Run the source format through fix_deprecated_pix_fmt()
before it reaches swscale, matching what SWScale::Convert already does.
Doing it before the identity-copy check also lets a YUVJ420P->YUV420P
same-size conversion take the av_image_copy fast path.
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
The "Target image is already colourised, colours: 1" warning fired from
Image::Colourise() during zone alarm overlay on YUV420P monitors, even with
ZM_COLOUR_JPEG_FILES off.
monitor->Colours() returns 1 for both GRAY8 and planar YUV420P (the GRAY8
alias), so zm_zone.cpp misclassified YUV420P monitors as grayscale and built
an RGB24 alarm highlight. Overlaying that RGB24 highlight onto the YUV420P
analysis_image hit the RGB-on-mono branch, which calls Colourise() - valid
only for GRAY8. Colourise() warned and bailed, after which the per-pixel loop
walked the 1.5x planar buffer as 3x packed RGB (out-of-bounds write).
Resolve the real capture format via zm_pixformat_from_colours() so true GRAY8
still upgrades to an RGB24 highlight while YUV420P keeps its format. Add a
YUV420P output branch to HighlightEdges (single alarm colour written to luma
and the shared chroma sample, transparent elsewhere) and a YUV420P-on-YUV420P
branch to Overlay (copies luma where non-zero, copies each chroma sample when
any covered luma pixel is marked). Colourise() is now only reached for GRAY8.
Add Catch2 coverage for the YUV420P Overlay masking and HighlightEdges output.
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
get_y_image() wraps the decoder Y plane zero-copy but recorded
FFALIGN(width,32) as the Image stride instead of the frame's real
linesize[0]. For widths that are not a multiple of 32 the decoder packs
the plane tighter than FFALIGN, so:
- Image::Rotate/Flip re-derived the source stride via
av_image_fill_arrays(...,32) and read past the end of the borrowed
plane (and skewed Y-channel motion analysis, which reads the same
buffer).
- Image::Flip sized its destination from this->size, which is tight for a
borrowed plane and smaller than the 32-aligned layout the planes are
written at, overrunning the destination.
Record the frame's real linesize in get_y_image(); use the Image's own
linesize for the source plane-0 stride in Rotate/Flip; size Flip's
destination from av_image_get_buffer_size(...,32). All are no-ops for
self-consistent ZM-allocated (32-aligned) images.
tests/zm_image_linesize.cpp: Rotate 90/180/270 and Flip H/V over a tight,
non-32-aligned GRAY8 source verifying correct output.
refs #4788
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
SWScale::Convert chose av_image_fill_arrays alignment by heuristic
(width % 32 ? 1 : 32) for both buffers. Image buffers are always laid
out align-32, so any width not divisible by 32 made Convert read luma
rows 16 bytes short and chroma planes from packed offsets: diagonal
shear plus garbage chroma. Rotating a monitor is what produces such
widths (1280x720 ROTATE_270 -> 720 wide, 3840x2160 ROTATE_90 -> 2160
wide, both % 32 == 16), so every scaled view and every re-encode of a
rotated monitor was corrupted while unrotated monitors (1280/2688/3840
all % 32 == 0) were untouched. The rotate/flip segfault fix exposed
this: before it, rotated planar frames crashed zmc before reaching
Scale.
Alignment is a fact about how a buffer was laid out, not something
derivable from dimensions. Convert now takes explicit in/out alignment:
Image::Scale passes 32/32, the videostore encode path mirrors
get_out_frame's allocation choice, libvnc passes 1 (packed VNC
framebuffer) and 32 (Image WriteBuffer). Remove the unused
SetDefaults/ConvertDefaults API rather than threading alignments
through dead code.
Tests: new Scale regression case on a 720x1280 YUV420P image
(column-banded luma, uniform chroma) fails before the fix exactly as
observed live (sheared rows, V plane reading 0) and passes after.
Full suite 84/84.
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
Image::Rotate and Image::Flip computed chroma plane dimensions with
AV_CEIL_RSHIFT(width, log2_chroma_w). The macro's runtime form is
-((-(a)) >> (b)), which relies on arithmetic right shift of a negative
value and is only valid for signed operands - FFmpeg always passes int.
Image::width/height are unsigned, so the negation wraps, the shift is
logical, and the result is 2^31 + ceil(w/2^b) instead of ceil(w/2^b):
for 1280x720 the chroma rotate received src_w=2147484288 and
src_h=2147484008 (captured in gdb), writing gigabytes out of bounds.
Effect: zmc's decoder thread segfaulted on the first decoded frame of
any monitor with a rotated or flipped orientation and a planar pixel
format - a monitor with decoding Always crash-loops.
Replace the macro at both sites with an explicit unsigned ceiling
shift helper and a comment documenting the trap.
Tests: new tests/zm_image.cpp covers Rotate 90/180/270 and Flip on
YUV420P with per-plane marker pixels, plus odd dimensions exercising
the chroma ceiling. The Rotate cases segfault before this fix (verified,
exit 139) and pass after. Full suite 85/85 via ctest. Live-verified on
a 1280x720 ROTATE_270 monitor with decoding Always: pre-fix crash
within seconds, post-fix 90s clean run under gdb.
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
- Image::Colourise sizing-failure Error: av_image_get_buffer_size /
av_image_get_linesize return negative for AV_PIX_FMT_NONE and
unrecognised formats, so this branch fires exactly when
av_get_pix_fmt_name(p_req_pixfmt) can return nullptr. Switched to
zm_get_pix_fmt_name.
- Image::Deinterlace_4Field fallback Panic: same issue — fires when
imagePixFormat is outside our dispatch set, where av_get_pix_fmt_name
may return nullptr. Switched to zm_get_pix_fmt_name.
refs #4788
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
- Image::Delta: pass delta8_bgr/rgb/argb/abgr/bgra/rgba/gray8 directly to
delta_row() instead of dereferencing with *. They're already function
pointers; the deref is redundant and would be undefined behaviour if
any pointer were null (Initialise() sets them, but the explicit *
obscures the intent and adds nothing).
- Switched the Delta fallback Panic from av_get_pix_fmt_name() to the
nullptr-safe zm_get_pix_fmt_name() wrapper. The Panic fires exactly
when imagePixFormat is unrecognised, where the raw function would
return nullptr.
refs #4788
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>