Commit Graph
134 Commits
Author SHA1 Message Date
Jash a4869e1b4e fix: stop zms crashing on a scale that gives an invalid image size fixes #5633 2026-11-13 09:16:50 +05:30
Jash 53aaaa4d07 perf: scale a streamed frame straight from shared memory into a reused image instead of copying it first fixes #5585 2026-11-12 03:43:11 +05:30
Isaac ConnorandClaude Opus 5.5 643296bf07 fix: keep the zoom crop when playback moves to a different resolution refs #4186
prepareImage keeps last_crop in the pixels of the frame it was computed for.
When event playback moves to a monitor with another resolution, the old crop
was applied to the new frame, so the zoomed area jumped or Crop refused it.
Record the frame size the crop belongs to and rescale the crop when it changes.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-05 08:30:56 -05:00
Isaac ConnorandClaude Opus 5.5 fc8791e52a fix: wait for the UI's next event in zms and encode any frame safely refs #4186
Gapless playback over zms follows the next/prev events the event view
sends with CMD_SET_EVENT. Reviewing the first version found these gaps:

- An event that ended before the UI's hint for it arrived fell back to
  zms's same-monitor query and skipped the other monitors' events again.
  The page needs a status poll and two requests to send that hint, and
  at 10x a ten second event lasts one second. Once a UI has sent any
  hint (ui_managed) zms never uses the same-monitor query: it holds on
  the last frame, like a pause, until the hint arrives, and stops after
  kHintWait (10s) if none does. Streams with no UI behave as before.
  The choice is EventStream::ChooseNeighbour, a static so it is tested.
- A hinted event deleted since the UI found it fell back to the
  same-monitor query, leaving the filter. It now stops there, as
  stream.php already does for a target deleted before forwarding.
- MPEG streams copied each frame into encoder buffers sized for the
  first frame's dimensions, format and packed stride. Text frames are
  drawn in the monitor's colours (usually RGB32) while event frames are
  RGB24, a frame from another monitor can be larger, and Image rows are
  padded to 32 bytes, so all three overran those buffers. The scaling
  added to StreamBase only handled size, and the live stream never set
  the tracked size. VideoStream::EncodeImage now converts any Image to
  the encoder's own size, format and stride with sws_scale, and every
  MPEG path uses it; the tracking in StreamBase is gone.
- loadEventData kept the previous event's video decoder when the new
  event had none, so a missing jpeg showed the previous camera's frame
  under the new event. It now drops it.
- The MPEG path only read jpegs, so an event recorded as video only
  streamed nothing. Both paths now take frames from loadFrameImage,
  which falls back to the event's video as the jpeg path already did.

tests/zm_eventstream_hints.cpp covers the message decoding, which hint
applies to which event, ChooseNeighbour (including Id order
10(M1) 11(M2) 12(M1) 13(M2), which went 11 -> 13) and PackImage.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-04 19:32:53 -05:00
Isaac Connor 42706741d3 Merge remote-tracking branch 'upstream/master' into 5186-zms-ui-next-event 2026-11-04 18:41:28 -05:00
Nic BoetandClaude Opus 4.8 1d6dcff83b fix: name zms command sockets after the user the stream serves refs GHSA-7hhq-xw65-4crf
ajax/stream.php sends stream commands (query, pause, seek, zoom, quit)
to the zms whose unix socket matches a connkey, with no permission
check. Connkeys are six random digits chosen when the stream starts,
so any logged-in user who guessed or saw one could read the status of
another user's stream, of a monitor they may not view included, and
pause or end it. A second zms started with the same connkey also waited
on the first one's lock and then took over its socket.

zms already authenticates the user and checks their access to the
monitor or event before it streams. Keep that user's id and put it in
the lock, command socket and reply socket names
(zms-<connkey>-<user id>s.sock); stream.php builds the names from the
caller's own id through zmsSocketPath(), so a request reaches only the
caller's streams. Without authentication the id is 0 on both sides.

Adds a StreamBase test in tests/zm_stream.cpp and
tests/php/test_zms_socket_path.php, which pin the same names. The
existing command-socket-teardown test is updated for the owner-suffixed
names (it postdates the reporter's base commit).

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-10-31 11:11:01 -04:00
Isaac ConnorandClaude Opus 5.5 42c37cdcbb fix: close the zms command socket as soon as the command thread stops
The command socket stayed bound until ~StreamBase(), which runs only after
the stream thread has finished. A zms that was shutting down but still busy
in the stream thread (blocked writing to a client that had gone away, for
instance) kept accepting commands it would never read. web/ajax/stream.php
then waited out its whole MSG_TIMEOUT on each one and logged "Timed out
waiting for msg ... after waiting 5000 milliseconds", where a missing socket
would have been reported as no_socket at once.

Call closeComms() when checkCommandQueue() leaves its loop. sd is only used
from the command thread, and closeComms() clears sd and lock_fd, so the
destructor's later call does nothing and cannot remove a socket bound by a
successor zms on the same connkey.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-26 17:12:27 -04:00
Isaac ConnorandClaude Opus 4.8 64d3d772bb fix: let the UI tell zms which event is next/prev for gapless playback refs #4186
When an event is streamed by zms (the MJPEG/mpeg path, not the video.js MP4
player), zms advanced to the next/prev event itself with a hardcoded query:

  SELECT Id FROM Events WHERE MonitorId = <same> AND Id <>> <current> ...

That ignores the filter and sort the user is viewing, so gapless playback of a
cross-monitor filtered list skipped every event that did not belong to the
current event's monitor -- e.g. playing monitor A's event jumped straight to
A's next event, hopping over all the interleaved monitor B events. The earlier
getNearEvents fix only corrected the video.js path and the Prev/Next buttons;
this zms auto-advance was a separate path and still wrong.

Rather than reimplement filter/sort knowledge in C++, let the UI -- which
already computes the correct next/prev from the active filter via getNearEvents
-- tell zms which events those are. A new CMD_SET_EVENT command carries a
direction, a target event id, and the source event the hint was computed for;
EventStream stores them and checkEventLoaded loads the UI-provided event when
advancing. When the UI has not supplied a usable hint it falls back to the
existing by-monitor query, so behaviour is unchanged for clients that do not
send the command.

The event view sends CMD_SET_EVENT for both next and prev after each
getNearEvents response, but only when playback is served by zms (vid == null);
the video.js path already navigates correctly on its own.

Hardening in this path:

- Authorisation: zms only authorises the event the stream started on and loads
  forwarded targets without re-checking, so a client could hand it an event
  from a monitor it cannot view. ajax/stream.php now resolves the target's
  monitor and requires canView('Events', MonitorId) before forwarding (gated on
  ZM_OPT_USE_AUTH, matching zms).

- Filter boundaries: getNearEvents returns 0 when the filter has no neighbour
  in a direction. A hint now records whether the UI supplied a value, so an
  explicit 0 stops at the boundary instead of being treated as "no hint" and
  falling back to the same-monitor query (which would leave the filtered list).

- Stale hints: next and prev arrive as separate requests and can land out of
  order. Each hint carries the source event id; processCommand refuses to store
  one whose source is not the event playing (so a late command cannot overwrite
  a valid hint), and checkEventLoaded honours a stored hint only while its
  source still matches. The event view tags each hint with the getNearEvents
  response's own EventId, not the current event, so a slow response cannot send
  a self-referential hint that loops zms on one event.

- Deleted targets: a cached neighbour may be removed by retention or another
  user before it is used. checkEventLoaded checks existence first and falls back
  rather than hitting loadEventData's fatal "not found" path; ajax/stream.php
  treats a target that no longer exists as a filter boundary instead of
  returning an error that would flag the stream broken and stop UI polling.

- Cross-resolution MPEG: the mpeg encoder is created once at the first event's
  dimensions and cannot resize mid-stream. Frame and text-frame paths share a
  scaleToEncoder() helper that scales a later, differently sized image (a
  cross-monitor advance, or a boundary text frame built at another monitor's
  size) to the encoder's dimensions before encoding rather than overrunning its
  buffers.

- Portable packing: stream.php encodes the ids as big-endian 32-bit words
  instead of pack('J'), which 32-bit PHP (still supported in the status decode)
  cannot feed a 64-bit value.

Known limitation: in a multi-server install with non-shared storage a
cross-monitor neighbour can live on another server, whose recording this zms
cannot read. Such an advance degrades to failed frames; zms self-advance is
effectively same-server (or shared-storage) only. Routing it to the serving
server, as the video.js reload path does, is left to a separate change.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-10-23 18:43:43 -04:00
Isaac Connor 7f82b7db9f Merge pull request #5264 from nabbi/fix/b78-zms-paused-keepalive
fix-low: send one paused keepalive per command in buffered live playback
2026-10-16 19:02:32 -04:00
Isaac Connor edad61f536 Merge pull request #5278 from nabbi/fix/b85-stream-crop-zoom-snapshot
fix-low: scale last_crop back with the zoom the crop was computed for
2026-10-14 18:57:36 -04:00
Nic BoetandClaude Opus 5.5 c35d10cea8 fix: don't ask for a paused frame on a status query
checkCommandQueue() set got_command after every message, CMD_QUERY too.
The watch view sends one every ZM_WEB_REFRESH_STATUS seconds (default 1),
so with the page open a paused buffered stream still re-sent its frame
about once a second. A status query doesn't change the picture: only
other commands ask for a frame now.

refs #5263

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-14 09:55:26 -05:00
Nic BoetandClaude Opus 5.5 13b7b697d6 fix: scale last_crop back with the zoom the crop was computed for
prepareImage() snapshots zoom into cur_zoom and computes the crop in
the image blown up by cur_zoom, but converted it back to base-image
units dividing by a fresh read of zoom. A ZOOMIN or ZOOMOUT landing in
between stored a crop for neither zoom: the frame showed the wrong
region, or went out uncropped when the box fell outside the image
("Attempting to crop outside image"), and since the next frame's crop
is derived from last_crop the wrong region carried on. Use cur_zoom.

fixes #5277

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-12 17:14:27 -05:00
Nic BoetandClaude Opus 5.5 22d02ce066 fix: stop the nph-zms command thread racing runStream on frame bookkeeping
checkCommandQueue runs processCommand on its own thread, which read
`now` and frame_count and wrote last_frame_sent (CMD_PAUSE) and
got_command while the streaming loop writes or reads them.
ThreadSanitizer reports these as data races (zm_monitorstream.cpp
processCommand and runStream's got_command read against the command
thread, and checkCommandQueue's `now` read against EventStream::runStream).

Make frame_count, last_frame_sent and got_command atomic, as #4939 did
for the playback state, and have the command thread read the clock
itself instead of the loop's `now`. The status reply's fps and delay are
then measured against the current time rather than the start of the
loop's last pass. Test: [races] case for the frame bookkeeping, for TSan
builds.

fixes #5230

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-12 10:55:01 -05:00
nicandClaude Opus 5.5 596fb5ab70 fix: free a stream's monitor and playback buffer when nph-zms exits (#5186)
* fix: free a stream's monitor and playback buffer when nph-zms exits

Every nph-zms exited with ~1 MB still allocated, reported by LeakSanitizer
on every stream:

- The monitor's zones each hold a shared_ptr back to it, so releasing the
  stream's reference never freed the Monitor, its zones (a full-frame zone
  image each), camera or links. zmc breaks the cycle with disconnect() on
  exit; zms never did. ~StreamBase now calls it.
- The buffered-playback SwapImage array (connkey + buffer) was never
  deleted. MonitorStream now frees it in its destructor.

Freed at process exit either way, so nothing grows, but it shows up in
every leak report and hides real ones.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* test: check a stream frees its monitor and zones on destruction refs #5186

A stream holds a monitor with one zone; once the stream is destroyed, a
weak_ptr to the monitor must have expired. Each Zone holds a shared_ptr
back to its Monitor, so without ~StreamBase breaking the cycle the monitor,
its zones and their images outlive the stream. Fails on 82901ac1f
(REQUIRE( watched.expired() )), passes with the fix. Needs no database or
sanitizer, so ci-cpp-tests runs it.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* refactor: hold the buffered-playback array in a unique_ptr refs #5186

temp_image_buffer is now a std::unique_ptr<SwapImage[]>, so it is freed
with the stream without a hand-written destructor, and the leak cannot
come back by dropping that line. The array is private and only allocated
in runStream(), so a unit test cannot see it freed without a sanitizer;
under LeakSanitizer, buffered nph-zms streams leaked 48,008 bytes from
runStream() on 82901ac1f and nothing with this branch.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-06 17:34:09 -04:00
Jash 5e0d6afaf4 fix: send pre-scaled frames as built when scale or zoom changes refs #3681 2026-08-26 18:22:39 +05:30
Jash e48ae03275 perf: scale during colour conversion in zms playback fixes #3681 2026-08-26 11:15:19 +05:30
Jash f5cfbcd54c fix: make MonitorStream playback state shared with the command thread atomic fixes #4939 2026-08-16 16:46:47 +05:30
Isaac ConnorandClaude Opus 5 e75a8b9654 fix: only unlink the command socket while holding the lock
openComms() logs an error but carries on to bind() when it cannot open or
flock() the .lock file, so a zms can be serving without holding the lock. In
that state the unlink in closeComms() could remove a socket belonging to the
zms that does hold the lock, leaving it unreachable.

Guard the unlink on lock_fd >= 0. Leaking the socket file when we never held
the lock is no worse than the behaviour before the unlink was added.

Expand the comment to spell out that this path is the command socket rather
than the .lock file, that our successor unlinks it itself on the way to bind(),
and why the unlink has to precede releasing the lock.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-08-03 08:32:01 -04:00
Isaac ConnorandClaude Opus 5 c93b8d7de5 fix: unlink the zms command socket on exit refs #5029
closeComms() left /var/lib/zoneminder/sock/zms-NNNNNNs.sock behind, and the
only thing that ever removed it was the unlink() before bind() in a later zms
that happened to draw the same connkey. Socket files accumulated indefinitely.

web/ajax/stream.php uses file_exists() on that path to decide whether zms is
listening, and waits up to a second for it to appear before giving up. A file
left by an exited zms defeats that wait: the check passes immediately, the
sendto() gets ECONNREFUSED, and the command is reported as failed even though
the new zms was about to bind. genConnKey() draws from six digits, so a page
cycling monitors every five seconds reuses a key well within an hour.

Unlink while we still hold the flock. A second zms with the same connkey blocks
on flock(LOCK_EX) in openComms() before it unlinks and binds, so it cannot have
created its own socket yet and we can't delete a file belonging to it. The lock
file itself is still left alone, since another zms may be waiting on it.

This is best effort: zms killed by a signal still leaves the socket behind. In
that case the process is usually still running, so the file being there is not
wrong.

Also reset lock_fd after closing it.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-08-03 08:03:13 -04:00
copilot-swe-agent[bot]andconnortechnology 2dfb79975d fix: prevent segfault when MPEG stream codec fails to open
Co-authored-by: connortechnology <925519+connortechnology@users.noreply.github.com>
2026-03-05 02:15:08 +00:00
Isaac ConnorandClaude Opus 4.6 29541c9aa7 fix: prevent segfault in MonitorStream::processCommand from shared memory race
The command processor thread could crash dereferencing monitor->shared_data
or monitor->trigger_data while the main thread was in loadMonitor() calling
disconnect() which munmaps shared memory and nulls those pointers.

Three fixes:
- Guard against null monitor at the top of processCommand
- Add monitor_mutex to StreamBase, held during disconnect/connect in
  loadMonitor and during shared memory reads in processCommand, so the
  command thread cannot access shared memory while it is being remapped
- Initialize status_data.analysing and status_data.score in the
  !ShmValid branch where they were previously sent uninitialized

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-23 18:19:20 -05:00
Isaac ConnorandClaude Opus 4.5 2d01a38bdc fix: correct file descriptor error checks in StreamBase
- Change lock_fd error check from <= 0 to < 0 since open() returns -1
  on error and 0 is a valid file descriptor
- Use -1 consistently as invalid fd marker
- Fix close check from > 0 to >= 0 to handle fd 0 correctly

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-02-03 16:44:50 -05:00
Isaac Connor cd3e2b5d1e fix: address bugs in videostore and stream
zm_videostore.cpp:
- Fix incorrect size passed to av_stream_add_side_data (was sizeof(int32_t),
  should be sizeof(int32_t)*9 for display matrix)
- Fix null pointer dereference of chosen_codec_data in PASSTHROUGH mode
  (use video_in_ctx->pix_fmt instead)

zm_stream.cpp:
- Fix logic error in last_crop initialization check (OR should be AND)
2026-02-02 23:26:20 -05:00
Isaac Connor 4757d711ef Change various cases of int img_buffer_size to size_t 2025-07-19 14:18:32 -04: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 3bca776214 Handle change of res/colours in zms by reloading the monitor object. 2023-12-08 10:14:38 -05:00
Isaac Connor 599d21050d Only log error when not sigpipe 2023-12-07 09:15:41 -05:00
Isaac Connor 6dc0e88988 Turn common Errors into Info beacuse they happen all the time when reloading a monitor 2023-12-06 14:40:29 -05:00
Isaac Connor 89f90dc5fa Don't output the boundary if we aren't streaming. Single jpegs don't need it and I think something was complaining about it. 2023-12-03 09:24:27 -05:00
Alejandro Criado-Pérez 543683aa4c Corrections on cpp and h files 2023-08-13 01:27:19 +02:00
Isaac Connor 2773385262 Remove redundanct frame_mod=1 2023-04-06 19:02:24 -04:00
Isaac Connor 4d716f26ee Make shm is not connected a debug... otherwise we really spam the logs. Useful error messages can go at a higher level 2022-11-16 09:07:36 -05:00
Isaac Connor 2d9bc06170 Set a 1 second timeout one the communications socket, so that our blocking commandQueue check will check zm_terminate every now an then 2022-10-26 13:09:43 -04:00
Isaac Connor 8558ade8f1 Merge branch 'master' into misc_fixes 2022-08-25 18:33:06 -04:00
Isaac Connor aa030afcb6 Make checkCommandQueue it's own thread, meaning we use blocking I/O and will still respond when it takes forever to send a jpeg. Make warning about broken stream into a Debug. The signal doesn't set zm_terminate fast enough. 2022-08-15 17:58:56 -04:00
Doug Nazar 9385127b50 Consolidate temp_img_buffer resizing and use correct delete[] operator 2022-07-30 22:27:41 -04:00
Isaac Connor 356678f164 Use ints when comparing maxfps and effectivefps so that small decimal differences in fps don't matter. 2022-07-13 18:47:27 -04:00
Isaac Connor 2cb85492e9 Clean out cruft from prepareImage. Fixes not sending scaled image. 2022-05-11 10:05:48 -04:00
Isaac Connor 3804f6c66c Finally fix centering of zoomed image 2022-05-07 11:37:58 -04:00
Isaac Connor a8583086ce Rework zooming. We now crop first, then scale to retain image fidelity as much as possible. More work to be done but is working better than the old code and I think is more readable. This also makes Box a class member instead of a static 2022-05-06 11:45:12 -04:00
Isaac Connor 5aca811d5d Don't delete the socket file because another zms might have opened it and be waiting on the lock. This should remove a ton of zms error messages 2022-04-28 19:16:22 -04:00
Isaac Connor 063f27e5f7 Debug log when failed sending 2022-04-28 16:42:16 -04:00
Isaac Connor 39d45e527c Switch from DecodingEnabled to DecodingOption. Implement the logic in ::Decode. 2022-03-28 17:44:44 -04:00
Isaac Connor bf4d2a82d6 handle when maxfps is not specified 2022-03-27 12:17:00 -04:00
Isaac Connor cd2c977ed8 Merge branch 'master' into replace_function_concept 2022-02-16 14:25:38 -05:00
Isaac Connor 67563737c3 Rework to remove static temp_img_buffer. Is now a class member. Must be allocated as needed. 2022-02-16 14:16:46 -05:00
Isaac Connor fd3a70172d Merge branch 'master' into multistream 2022-01-10 17:51:50 -05:00
Isaac Connor b406bf8fd1 remove last_send_image_width/height. Not really useful or relevant 2022-01-10 17:36:49 -05:00
Isaac Connor 657fc5cad5 convert function to relevant capturing/analysing 2022-01-07 11:52:19 -05:00
Isaac Connor 60d2186ff4 Move from SystemTimePoint to SteadyTimePoint where possible. Implement MAXFPS command. Change the logic of calculating sleep time to make more sense. Get rid of frame_mod use in favour of calculating when then next frame should get sent and just waiting till then. 2021-12-16 16:35:20 -05:00