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>
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>
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>
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>
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>
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>
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>
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>
* 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>
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>
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>
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>
- 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>
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)