Commit Graph
207 Commits
Author SHA1 Message Date
Jash Ambaliya a4027108d6 fix: a zone does not score a delta image larger than the monitor and a blob merge that changes nothing skips the frame instead of exiting refs #7654 (#7655) 2026-11-23 08:50:17 -05:00
Isaac ConnorandClaude Opus 4.8 cccb72c82a Merge pull request #6143 from pliablepixels/zone-test-upstream
feat: try zone settings on a past event from the zone editor

Conflicts resolved against current master:
- db/zm_update: master's 1.39.53 (MonitorPresets ControlId fix) kept; the PR's
  Zones.ObjectCoords migration renumbered to db/zm_update-1.39.54.sql and
  version.txt bumped to 1.39.54 (1.39.53 was already taken on master).
- src/zm_zone.cpp: kept the PR's Zone::LoadRow extraction, but its per-row
  threshold conversion now uses master's RasterArea()/PercentToPixels() instead
  of the PR's stale polygon.Area() math, so runtime zone thresholds are
  unchanged from master.
- tests/CMakeLists.txt: union of master's zm_zone_percent/zm_zone_scoring and
  the PR's zm_zone_load_row.
- tests/zm_zone_load_row.cpp: percent-coords expectation updated to the
  RasterArea/PercentToPixels conversion it now exercises.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-11-20 08:50:59 -05:00
Jash 22b363fd9e fix: clamp zone pixel thresholds to 0-255 instead of wrapping refs #6715 2026-11-18 19:27:47 +05:30
Jash 80240e1e22 fix: zones skipped in a frame drop their stats, inclusive alarm keeps a score, weighted centre rounds refs #6397 2026-11-17 11:11:09 +05:30
Jash ff15eb13d3 fix: zone scores and percentage thresholds use the pixels the zone mask covers refs #6399 2026-11-16 14:13:51 +05:30
Pliable PixelsandClaude Opus 5.5 4284ac9b18 feat: try zone settings on a past event from the zone editor refs #6140
zma gets --dry-run, --json, --zone and --set. With them it re-analyses an
event without changing anything, analyses only the chosen zone as an
Active zone, replaces its detection settings for the run, and prints each
frame's alarmed/filtered/blob counts and boxes as JSON lines. The zone is
rebuilt through Zone::LoadRow, pulled out of Zone::Load, so percentages
convert exactly as at capture time. CheckAlarms records the boxes in a
ZoneDiagnostics member on Zone, kept off ZoneStats since that is copied
into every packet.

The zone editor gets a test panel under the image. It runs zma on a picked
or typed event with the form's unsaved settings (web/ajax/zone.php checks
permissions, validates every value and allows one run per monitor), then
replays the event - mp4 or its JPEG frames - with zma's outlines, min vs
got for each check up to the first that fails, and a timeline of which
frames alarm. Min/Max, MinBlobs, OverloadFrames and the alarm frame count
are judged in the browser, so changing them needs no re-run.

The object box is saved with the zone in a new Zones.ObjectCoords column
(zm_update-1.39.53.sql) and drawn again when the zone is reopened.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-15 16:27:40 -05:00
Jash 937176452a perf: filter zone pixels with an erosion and dilation instead of rescanning boxes fixes #5530 2026-11-15 11:57:38 -05:00
Isaac Connor b8898cb518 Merge pull request #5529 from AJ0070/5528-alarmedpixels-sse2
perf: threshold zone pixels with SSE2 and sum them with psadbw
2026-11-15 10:05:54 -05:00
Isaac Connor 27d8476505 Merge pull request #5695 from AJ0070/zone-zero-area
fix: avoid dividing by a zero zone area when scoring
2026-11-14 23:37:44 -05:00
Jash d5ca347a20 fix: avoid dividing by a zero zone area when scoring fixes #5694 2026-11-15 09:47:15 +05:30
Jash 994e7c17db perf: threshold zone pixels with SSE2 and sum them with psadbw fixes #5528 2026-11-14 23:51:46 +05:30
Jash da433b3c0a fix: treat a filter width or height below 1 as no filtering fixes #5696 2026-11-14 23:49:55 +05:30
Jash a25df71b50 fix: compute the alarm box for alarmed and filtered pixel zones fixes #5700 2026-11-13 14:01:36 +05:30
Isaac Connor 7a43d5a20b Merge pull request #5534 from AJ0070/5533-blob-skip-black
perf: skip black pixels eight at a time when looking for blobs
2026-11-12 19:50:58 -05:00
Jash 13e16a2b2c perf: skip black pixels eight at a time when looking for blobs fixes #5533 2026-11-11 19:17:43 +05:30
Jash 3abf32344a perf: count zones instead of building them when a monitor is loaded without zones fixes #5517 2026-11-11 12:07:53 +05:30
Jash 451214a7b9 perf: zero only the zone pixels std_alarmedpixels does not write instead of every bbox row, fixes #5486 2026-11-08 16:07:03 +05:30
Nic BoetandClaude Opus 5.5 4daa163e70 fix: clamp pixel zone coordinates to the monitor before rasterising
Zone::Load uses integer (pixel) zone coordinates as they are, while
percentage coordinates are scaled and clamped to the monitor
(e1eb7876c). Zone::Setup then fills the polygon into a monitor-sized
image, and Image::Fill(Polygon) does not check bounds, so a pixel zone
larger than the monitor wrote past the end of that image on every zmc
start. AddressSanitizer: heap-buffer-overflow WRITE in Image::Fill
(zm_image.cpp) from Zone::Setup, Zone::Load, Monitor::connect, for a
zone of 0,0 1279,0 1279,719 0,719 on a 640x360 monitor.

Pixel zones remain where a zone was saved with integer coordinates,
through the API or before the upgrade to percentages, and the monitor
is then made smaller. Negative coordinates wrote before the buffer.

Clamp each vertex to [0, width-1] x [0, height-1] in Zone::Load, as
ParsePercentagePolygon does, and log a warning naming the zone.
Image::Outline already clamps its vertices the same way, so the filled
area and the drawn outline now agree.

fixes #5213

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-12 09:20:31 -05:00
Isaac ConnorandClaude Opus 5 bdf688eecb fix: carry the zone's alarm colour on the alarmed and filtered pixel methods
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
2026-09-22 09:57:19 -04:00
Isaac ConnorandClaude Opus 4.8 cf92249820 fix: build zone alarm highlights in YUV420P to stop spurious Colourise warning
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>
2026-06-26 16:10:07 -04:00
Isaac Connor e1eb7876c6 fix: clamp percentage polygon to width-1/height-1
ParsePercentagePolygon clamped to [0, width] / [0, height], so a new
zone created at 100% produced pixel coords equal to the monitor
dimensions. The rasterizer requires hi_x < width and hi_y < height,
so the runtime then logged warnings like
  "polygon hi_x (1920) >= image width (1920), clamping".

Clamp to width-1 / height-1 instead. Updates existing tests that
encoded the previous behavior.
2026-05-13 11:38:42 -04:00
Isaac ConnorandClaude Opus 4.6 29d371313a fix: store zone thresholds as percentages and convert to pixels at runtime
Zone threshold fields (MinAlarmPixels, MaxAlarmPixels, MinFilterPixels,
MaxFilterPixels, MinBlobPixels, MaxBlobPixels) were being corrupted on
every save because the PHP conversion used monitor pixel area instead of
zone pixel area. This caused values to inflate progressively, breaking
motion detection.

The fix changes the storage model: thresholds are now stored as
percentages of zone area (DECIMAL(7,2) columns) matching the percentage
coordinate system from zm_update-1.39.2. The C++ Zone::Load() converts
percentages to pixel counts at runtime using polygon.Area(). Legacy
pixel-coordinate zones pass through unchanged.

JS changes:
- submitForm() converts to percentages when in Pixels display mode
- Init skips applyZoneUnits() since DB values are already percentages
- limitRange() only updates field.value when constrained value differs,
  preventing oninput from stripping decimal points mid-keystroke

fixes #4690

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-09 17:16:56 -04:00
Isaac ConnorandClaude Opus 4.6 7d78b722d0 fix: auto-detect zone coordinate format instead of trusting Units field
The zone loader now ignores the Units DB field and detects the coordinate
format by checking for decimal points: decimal values are percentages,
integer-only values are legacy pixels. This fixes motion detection being
broken when zones had Units=Pixels but percentage coordinates (or vice
versa), which resulted in a ~99x99 pixel zone on a 2560x1440 monitor.

The PHP zone view now always forces Units=Percent when saving, since it
always works in percentage space. convertPixelPointsToPercent() now
returns bool to indicate whether conversion occurred.

Tests added for: truncation bug via atoi, correct percentage-to-pixel
conversion, auto-detect heuristic, and resolution independence.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-08 15:26:36 -04:00
Isaac Connor e8b5c4962e Convert warning to debug 2026-02-23 18:16:56 -05:00
Isaac ConnorandClaude Opus 4.6 47edcca6ab fix: fall back to pixel parsing when zone Units=Percent but coords exceed 100
When zones have Units='Percent' in the database but their Coords contain
pixel values (>100), ParsePercentagePolygon treats them as percentages,
causing wild scaling (e.g., 639% * 1920 / 100 = 12269) followed by
clamping to monitor bounds, producing degenerate full-frame zones.

Add a pre-check in Zone::Load that scans coordinate values before calling
ParsePercentagePolygon. If any value exceeds 100, log a warning and use
ParsePolygonString (pixel path) instead. Also add unit tests for both
ParsePolygonString and ParsePercentagePolygon.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-23 18:16:55 -05:00
Isaac ConnorandClaude Opus 4.6 995b60db80 fix: use int instead of unsigned int for zone pixel coordinates in zm_zone.cpp
The lo_x/lo_y/hi_x/hi_y variables were unsigned int despite being assigned
from signed int32 Vector2 members and compared against signed int dimensions.
This caused scattered (int) and (unsigned int) casts throughout CheckAlarms,
std_alarmedpixels, and Setup. Switching to int eliminates the casts, fixes
the signed/unsigned comparison warnings, and makes the -1 sentinel check in
std_alarmedpixels explicit rather than relying on unsigned wraparound.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-23 18:16:55 -05:00
Isaac ConnorandClaude Opus 4.6 2013339b1e fix: clamp zone polygon extents to actual frame dimensions in CheckAlarms
When a camera reconnects at a different resolution than the zone polygons
were configured for, the polygon bounding box can exceed the frame
dimensions. This caused a heap buffer overflow in the memset that zeros
the bbox rows of the diff image, confirmed by Valgrind (invalid write
at 0 bytes past a 921600-byte / 1280x720 block).

- Validate delta_image buffer and dimensions at entry
- Clamp hi_y/hi_x to image height/width before memset and pixel loops
- Guard filter, blob, and HighlightEdges loops against empty rows where
  ranges[y].lo_x is -1 (would wrap to UINT_MAX as unsigned)
- Clamp extents in std_alarmedpixels independently for defense in depth

Warning() logs identify which zones need polygon reconfiguration.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-23 18:16:55 -05:00
Isaac ConnorandClaude Opus 4.6 3e067f18b2 feat: store zone coordinates as percentages for resolution independence (src only)
Cherry-picked src/ changes from edge branch commit 17450d122.
Adds ParsePercentagePolygon() to convert percentage-based zone coordinates
to pixel values using monitor dimensions. Zone::Load() now checks the Units
column to dispatch between legacy pixel parsing and percentage-based parsing.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-12 18:06:56 -05:00
Isaac ConnorandClaude Opus 4.6 31aa65bd11 perf: split delta/mask buffers in CheckAlarms to eliminate full-image copy
Instead of copying the entire delta_image into the per-zone mask buffer
every frame (4MB memcpy for 4MP), allocate a persistent grayscale mask
and only zero the polygon bounding-box rows.  alarmedpixels_row now
reads from delta_image (const, read-only) and writes threshold results
to the separate mask buffer.

Key changes:
- alarmedpixels_row takes separate pdelta (read) and pmask (write) pointers
- std_alarmedpixels accepts both delta_image (const) and mask_image
- CheckAlarms allocates mask with explicit linesize == width to match
  filter/blob pointer arithmetic (avoids FFALIGN padding mismatch)
- Full buffer zero on allocation; bbox-only zero on reuse
- No functional change to filter, blob, or HighlightEdges stages

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-12 17:41:50 -05:00
Isaac ConnorandClaude Opus 4.6 8b3ed97fa4 perf: auto-vectorize alarmedpixels loop for SIMD on all platforms
Restructure std_alarmedpixels inner loop so GCC/Clang can auto-vectorize
it at -O2/-O3. The compiler now emits 16-byte SIMD (SSE2/NEON) processing
16 pixels per iteration instead of 1.

Three changes enable this:
- Extract inner loop into static alarmedpixels_row() with __restrict__
  on function parameters, giving the compiler a strong no-alias guarantee
- Use branchless bitwise AND instead of short-circuit && to avoid
  branches that block vectorization
- Remove per-row Debug(7) call that clobbered memory from the compiler's
  perspective, invalidating pointer analysis

The original hand-written SSE2 ASM (removed in 2011, commit 8e9ccfe1e)
had alignment restrictions and didn't use per-row polygon ranges. This
approach is portable, maintainable, and achieves equivalent throughput.

GCC confirms: "loop vectorized using 16 byte vectors"

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-12 14:36:13 -05:00
Nic BoetandClaude Opus 4.6 5fde4e5deb perf: reuse diff image buffer in Zone::CheckAlarms
Replace delete/new Image cycle with lazy-alloc + Assign(). When the
buffer already exists (every frame after the first), Assign() detects
matching dimensions and does a plain memcpy into the existing
allocation, eliminating an aligned malloc+free of ~2 MB per zone per
analyzed frame.

With 4 zones at 15 fps this removes 60 alloc/free cycles per second
from the analysis hot path. The HighlightEdges code path (analysis
images) still allocates a new Image and deletes the old diff buffer,
which is correct — the next Assign() will reallocate once to restore
the single-channel format, then resume reuse.

Behaviorally equivalent: Zone dimensions are constant during zone
lifetime, the destructor already handles cleanup via delete image,
and the only external consumer (Monitor::Analyse → AlarmImage →
Overlay) reads the image without storing pointers.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-09 19:25:58 -06:00
Isaac ConnorandClaude Opus 4.5 a96b776949 fix: apply credentials to secondary URL and fix buffer overflow in DumpSettings
- Apply credentials to secondary stream URL in FFmpegCamera (was causing 401 Unauthorized)
- Add empty check for rtsp_second_path in RTSP2WebManager before applying credentials
- Replace unsafe sprintf pattern in Monitor::DumpSettings with std::string + stringtf
- Refactor Zone::DumpSettings to return std::string instead of writing to char buffer
- Add decimal precision to event duration debug output

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-02-04 17:40:26 -05:00
Steve Gilvarry 1b527c1b62 Remove unused row index in zone load loop 2025-12-31 22:18:32 +11:00
Aaron Kling c4683d90a9 Format code using astyle google format
Commands used:
astyle --style=google --indent=spaces=2 --keep-one-line-blocks src/*.cpp
astyle --style=google --indent=spaces=2 --keep-one-line-blocks src/*.h
2024-03-26 13:43:58 -05:00
Isaac Connor 4993a55b14 Move declaration of zones down to where it is used 2024-02-07 15:56:24 -05:00
Isaac Connor d0ca677207 Fix %u instead of %d for id which is unsigned. Pass string instead of c_str 2022-07-14 12:07:26 -04:00
Isaac Connor 9093a8694b Fix crashes. Zones should use const for monitor object and not references. 2022-06-07 20:52:39 -04:00
Isaac Connor 07e32025df Just store the linked_monitors string instead of parsing and loading of related objects. Only call ReloadLinkedMonitors if doing analysis. Convert zone id's to unsigned 2022-06-07 18:36:25 -04:00
Isaac Connor 78a87517f6 convert to taking a std::shared_ptr<Monitor> instead of a Monitor *. Implement Name() which just returns the std::string label. 2022-06-07 18:18:24 -04:00
Isaac Connor e51d3a206f Use auto to get the right type for n_coords 2022-05-18 17:07:06 -04:00
Isaac Connor b254f990d0 Warn when the number of vertices changes due to clipping 2022-05-17 15:05:25 -04:00
Isaac Connor 3f7b9dfff7 fix cppcheck error about lo_x. Inner scope overwriting it. 2022-01-10 17:36:50 -05:00
Isaac Connor e8bb095730 include monitor dimensions when logging about zone mismatch 2021-11-24 14:28:31 -05:00
Mike Dussault d38a6adec4 No behavior change. Added non-const versions of Image::Buffer and fixed a few places that were casting away the constness. 2021-10-12 21:54:49 +00:00
Isaac Connor b0cf3a4732 Merge pull request #3314 from Carbenium/path-max
Fix Wformat for stringtf and convert path buffers depending on PATH_MAX to std::string
2021-07-07 11:34:03 -04:00
Peter Keresztes Schmidt 80b08a2075 Convert path buffers depending on PATH_MAX to std::string 2021-07-06 10:33:17 +02:00
Peter Keresztes Schmidt 65656de6ce db: Adjust the query methods to accept std::strings 2021-07-06 10:20:46 +02:00
Peter Keresztes Schmidt c60b577aec Convert more char array buffers to std::string
Remove now unused ZM_SQL_*SIZE defines
2021-07-06 10:20:46 +02:00
Peter Keresztes Schmidt b1de220958 Polygon: Perform clip operation on existing object instead of returning a new clipped one 2021-05-16 19:42:41 +02:00
Peter Keresztes Schmidt 29488900a1 Box: Make range calculations mathematically correct 2021-05-16 19:41:45 +02:00