zmc's capture, decoder and analysis threads, zms, zmu and the web
interface read and write Monitor::SharedData while the others run, but
its scalar fields were plain members. ThreadSanitizer reported races on
capture_fps, state and analysing, and the action word was worse: zmu
sets bits with |= while zmc clears others with &=, and as plain
read-modify-writes either side could write back a word read before the
other's change and drop its bit.
Wrap every scalar SharedData field in SharedValue<T>, which holds only
the value and does each access as a relaxed __atomic builtin (C++17 has
no std::atomic_ref). Loads and stores keep their meaning, |=, &= and ++
become single atomic operations, and copying one field to another is
deleted because it would not be atomic. The layout Memory.pm and
Monitor.php read is unchanged: the 8-byte fields are aligned to 8 so
clang on i386 doesn't call libatomic, and they already sat on 8-byte
offsets. Values passed through printf-style varargs now call load(),
which -Wformat found. MonitorLink's SharedData pointer drops volatile,
which the atomics replace.
The test checks every field offset against Monitor.php, that the
wrapper reads and writes the plain value, and that setting and clearing
action bits from two threads loses none (plain fields lost 3 to 33 of
200000 rounds here).
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Cleared after sendFrame(), a command the command thread handled while
the frame was going out (a second zoom click, say) had its got_command
overwritten, and its frame waited for the 5 s keepalive. Clear it
before the send instead; such a command then gets its own frame on the
next pass. One keepalive per command as before.
refs #5263
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Once the replay buffer of a buffered live stream has wrapped, the slot
at temp_write_index holds the oldest stored frame. SLOWFWD from the
newest frame stepped onto it, sent that oldest frame and then matched
the read == write check, which resumes live play: the viewer saw a jump
back by the buffer's length followed by live video. Treat that slot as
the end of the buffer, like the slot not written yet before the buffer
wraps, and stay on the current frame. Stepping back onto it from the
oldest-but-one frame now also stays instead of resuming live.
fixes#5267
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
checkCommandQueue sets got_command after every command so that a paused
stream shows the effect of a command (a zoom, for instance) straight
away. Nothing cleared it, so once any command had arrived the paused
branch of buffered live playback re-sent its frame on every pass of the
loop, at the stream's frame rate, instead of every 5 s. Clear it once
the frame has gone out.
fixes#5263
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>
MonitorStream::sendFrame(filepath) sends a swap file as it is when the
stream is JPEG at scale 100 without zoom, which is what buffered live
playback (rewind, fast reverse, step) uses. That path wrote only
Content-Length and X-Timestamp, so the part had no --ZoneMinderFrame
boundary and no Content-Type, and the multipart/x-mixed-replace stream
broke. The boundary and Content-Type were written here until the merge
in dbb2535a6 dropped them.
Write them as sendFrame(Image *) does. Test: the raw path's output
starts with the boundary and Content-Type.
fixes#5226
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
SLOWFWD and SLOWREV on a live stream with a replay buffer move
temp_read_index one slot and send that slot's swap file without checking
that it was written. Stepping forward from the newest stored frame lands
on temp_write_index, and stepping back past the oldest stored frame lands
on a slot not filled yet. Either way the file name is empty,
sendFrame() fails with "Can't open : No such file or directory" and the
stream ends.
Check swap_image->valid as the playback branch above does, and stay on
the current frame when the slot holds nothing.
fixes#5224
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
MonitorStream::runStream saved paused_image only when paused differed
from its value read at the top of the same pass (was_paused). That worked
while commands were read inside the loop between the two reads. Since
commands run on their own thread (aa030afcb), both reads see the same
value except in a short window, so a paused live stream without a replay
buffer held no image: it sent no keepalive frame every 5 s as intended,
and ZOOMIN while paused had no image to resend at the new zoom.
Take the image on any pass that is paused and holds none, once capture
has written a frame, the same condition the stopped branch uses.
fixes#5222
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The delayed/paused branch of MonitorStream::runStream sent paused_image
twice whenever the zoom changed, without checking that one was held.
paused_image is reset as soon as the stream is not paused, and PLAY after
PAUSE leaves delayed set for one pass of the loop when there is no replay
buffer, so PAUSE, PLAY, ZOOMIN on a live stream with buffer=0 passed a
null Image to StreamBase::prepareImage and nph-zms died with SIGSEGV.
Check paused_image as the keepalive branch below already does. When no
paused image is held, the next live frame goes out with the new zoom.
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>
Two problems on the exit paths out of the runStream loop, both raised in review.
paused_image and stopped_image were raw pointers freed only by a later iteration
observing that the state had changed. Any break leaves the function with one
still allocated: the stopped-state ttl break added by this branch, and the ttl
and frames_to_send breaks at the bottom of the loop that predate it. Hold both
in unique_ptr so the exit path stops mattering.
More seriously, those breaks leave zm_terminate false. StreamBase::checkCommandQueue
loops on !zm_terminate around a recvfrom with a one second SO_RCVTIMEO, so it
returns only once that flag is set, and runStream joins it unconditionally when
connkey is set. A stream that ended on its ttl or its frame count therefore sat
in join() rather than exiting, which is another way for a zms to outlive its
client. Set the flag on all three.
The two sendFrame failure breaks and the feof/ferror breaks already did this,
which is what the pattern should have been throughout.
Verified by reading: checkCommandQueue's only loop condition is the flag. Not
reproduced end to end, because no zmc is running on this machine and a stream
against a monitor with no capture takes the not-initialised path instead, which
already sets the flag correctly on its own timeout.
zms builds clean with no new warnings. C++ suite 133/133 on this branch.
Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01UkQwahn9pi1y4wJe9BTxjM
A zms in the stopped state could never exit. The branch handling it slept and
continued without writing anything, so the socket was never touched and a
client that had gone away was never discovered - no write, no EPIPE, no
SIGPIPE. The continue also skipped the ttl check at the bottom of the loop, so
even a deadline set by the caller did not apply. The only way out was an
explicit CMD_QUIT, and any stream that missed one stayed until the machine was
restarted.
That is what accumulates on the montage page: the tab is hidden, the browser
side sends CMD_STOP, and if the stream is later replaced rather than resumed,
nothing can address the old process again and it sleeps forever.
Hold the last captured frame on entering the stopped state and re-send it
every five seconds, the way the paused state already does, and apply ttl here
too. The frame is what makes a departed client detectable; it also keeps the
connection open for the resume that stopped is meant to allow, which is what
the state was documented to do. Where nothing has been captured yet there is
no frame to hold, so a text frame is sent instead - the write matters more
than what is in it.
setLastViewed is deliberately still not called: capture and decoding should not
be held active for a stream that is not playing.
refs #4706
Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Add instrumentation to trace which stream type and workload precede the
occasional runaway memory growth in nph-zms.
- zm_utils: add zm_get_rss_kb() reading resident set size from
/proc/self/statm
- zms: log a one-shot Debug summary of the decoded request (source, mode,
monitor/event, connkey, scale, buffer, ttl, rss) so a runaway process
can be tied to its stream parameters
- MonitorStream/EventStream: emit a periodic Debug RSS trace every 30s.
The EventStream trace includes frames-vector size and frame_count,
which scale with reloaded event length and will show whether the
in-process event reload path drives the growth
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
The command_processor thread was started in runStream() before
temp_image_buffer_count, the read/write indices and temp_image_buffer were
assigned, so a command arriving in that window observed a half-initialised
stream (the root cause behind the divide-by-zero guarded in the previous
commit). Keep the thread object declared up front for the join(), but defer
its launch until after the playback_buffer setup so processCommand can only
run against fully initialised state.
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
MonitorStream::processCommand computed buffer_level by dividing by
temp_image_buffer_count (and via MOD_ADD modulo) while only guarding on
playback_buffer. processCommand runs on the command_processor thread,
started in runStream before temp_image_buffer_count is assigned from
playback_buffer. In that window temp_image_buffer_count is still 0 while
playback_buffer is already > 0, so a command arriving then divided by
zero and raised SIGFPE, crashing nph-zms.
Extract the percentage math into MonitorStreamBufferLevel which returns 0
when the buffer count is not positive, and add Catch2 coverage for the
zero-count and wrap-around cases.
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Avoid sleeping up to MAX_SLEEP (500ms) at the end of runStream when
termination has been requested, so zms shuts down more promptly.
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
zm_terminate is written from signal handlers and read from daemon loops.
A plain bool is undefined to access from a signal handler and may be hoisted
out of a loop by the optimizer. std::atomic<bool> is lock-free on supported
platforms and matches the already-atomic per-object terminate_ flags. Update
the three Debug() vararg sites to call .load() since atomics can't pass
through ...
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
- Added zm_get_pix_fmt_name() in zm_pixformat.h: av_get_pix_fmt_name()
returns nullptr for unknown formats (including AV_PIX_FMT_NONE), and
passing nullptr to %s is undefined and can crash. Wraps with an
"unknown" fallback. Replaced the five raw uses flagged by review
(RemoteCameraRtsp/FfmpegCamera/VncCamera/LocalCamera constructors and
MonitorStream::sendFrame's Debug log) with the wrapper. Each can hit
AV_PIX_FMT_NONE before the first frame or via an unexpected
(colours, subpixelorder) pair.
- Monitor::GetImage and Monitor::getSnapshot now route the slot read
through ReadShmFrame so the per-slot AVPixelFormat zmc recorded is
adopted on image_buffer[index] before its bytes are interpreted.
Without this, the JPEG encode in GetImage and the ZMPacket returned
by getSnapshot would interpret SHM bytes using the placeholder format
set at attach time and produce garbled output when the slot's actual
format differs (the contract previously relied on callers calling
ReadShmFrame themselves). getSnapshot/GetTimestamp drop const since
ReadShmFrame mutates image_buffer[index]; callers in this codebase
already use a non-const Monitor pointer.
- Monitor::connect: updated the misleading "+64 bytes reserved" comment
to match the actual reservation of 63 + (alignof(AVPixelFormat) - 1).
refs #4788
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
When CMD_STOP is sent via AJAX using ZMS MJPEG streaming, the response
was incorrectly returning paused=true instead of indicating a stopped
state (paused=false).
Changes:
- Add `stopped` boolean to StreamBase (zm_stream.h)
- MonitorStream: CMD_STOP now sets stopped=true, paused=false instead
of paused=true; run loop skips frame sending when stopped
- EventStream: CMD_STOP sets stopped=true (was already setting
paused=false); run loop skips frame sending when stopped
- All other play/pause commands reset stopped=false
- Both streams include stopped field in the status response struct
- stream.php unpacks the new stopped field from MSG_DATA_WATCH and
MSG_DATA_EVENT responses
- MonitorStream.js handles stopped status in UI (shows 'Stopped' mode)
- EventStream.js tracks stopped state from server response
Fixes issue: CMD_STOP response paused=true should be paused=false
Agent-Logs-Url: https://github.com/ZoneMinder/zoneminder/sessions/ba9cb47a-a3e8-4e13-aec7-c9cd258e2a3d
Co-authored-by: connortechnology <925519+connortechnology@users.noreply.github.com>
The deprecated Monitors.Colours column was driving the on-disk SHM
image_buffer slot format end-to-end: zmc allocated each slot in
camera->Colours()/SubpixelOrder() shape, zms attached and built its
own per-process Image objects assuming the same shape. Anything that
wrote a different format into a slot — i.e. anything that wasn't
already RGB32 on a Colours=4 monitor — left zmc's local Image with
the new format but zms reading the bytes as RGB32. The visible
artefacts varied with the format pair (4 small images per row for
YUV420P-into-RGB32, 3 tiles for the planar-as-RGB24 fallthrough,
fully garbled colours for image_pixelformats overlapping alarm_image,
etc.) but the underlying contract was just broken — the SHM had no
representation of the per-slot format.
Make the SHM transport any format Image supports without an upfront
convert step:
- Place image_pixelformats[] correctly. mem_size already reserved
image_buffer_count*sizeof(AVPixelFormat) at the end of the SHM
region, but the pointer was set to shared_images +
image_buffer_count*image_size — overlapping the alarm_image
region. zmc's writes scribbled into alarm_image; zms read alarm
pixel data back as enum values. Move it to
+2*image_buffer_count*image_size, after both image regions.
- Add Monitor::WriteShmFrame(index, capture_image): no conversion,
just Assign and record image_pixelformats[index] =
capture_image->AVPixFormat(). Used by both the normal Decode path
and the signal-loss path so they share the same cross-process
format-consistency contract.
- Add Monitor::ReadShmFrame(index): the read-side counterpart. Calls
image_buffer[index]->AVPixFormat(image_pixelformats[index]) before
returning so other-process Image objects interpret the SHM bytes
correctly per-frame. zm_monitorstream's image_buffer[index]
accesses go through this accessor.
- image_buffer[i] / alarm_image: initial format is now just a
placeholder (YUV420P), with allocation sized from
camera->ImageSize() as the upper bound. The actual format carried
in each slot is the one zmc wrote, recorded in image_pixelformats
and adopted on read.
This means the typical capture pipelines run with zero sws_scale
calls in the SHM hot path:
- H.264/H.265 sw decode -> YUV420P -> identity copy via
av_image_copy in Image::Assign(AVFrame*).
- LocalCamera/MJPEG -> RGB32 (DecodeJpeg target) -> SHM holds RGB32;
zms reads RGB32 directly.
- H.265 hwaccel -> NV12 -> falls through to YUV420P (NV12 isn't in
zm_pixformat) — one convert at decode time, then passthrough
through the rest of the pipeline.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
When setStreamStart()->loadMonitor() failed (e.g. monitor id not found,
shm not yet mapped), zms continued into runStream() for non-SINGLE
stream types and dereferenced a null Monitor shared_ptr at
monitor->GetFPS(), crashing in get_capture_fps with fault address 0x618.
Bail early after the STREAM_SINGLE branch with a "Not connected" text
frame, mirroring the SINGLE-type recovery. For STREAM_JPEG, emit the
multipart Content-Type first so sendTextFrame produces a well-formed
response. Placed before openComms()/command_processor spawn so there
is no resource teardown to do on the bail path.
When a browser closes a streaming connection, fwrite to stdout raises
SIGPIPE. Without a handler the default action terminates the process
immediately, skipping exit_zm() and leaving the DB handle and log
unclosed.
Add zm_pipe_handler that sets zm_terminate so zms falls out of its
streaming loop and exits through the normal shutdown path. Clarify
the sendFrame comment to match.
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
Add a boolean analysis_image field to the CMD_QUERY status response that
reports whether zms is actually sending analysis images (with motion zone
overlays) or regular capture images. This lets MonitorStream.js detect
when the stream state is out of sync with what the client requested and
re-send the CMD_ANALYZE_ON/OFF command to correct it.
The field is true only when frame_type is FRAME_ANALYSIS, shared memory
is valid, and the monitor has analysis enabled — matching the same
condition used to select the image in the streaming loop.
Co-Authored-By: Claude Opus 4.6 <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>
Add SharedData field and methods to track when analysis images are being
viewed, mirroring the existing last_viewed_time functionality. This allows
the analysis process to know if someone is actively viewing analysis images.
- Add last_analysis_viewed_time to SharedData struct
- Add getLastAnalysisViewed(), setLastAnalysisViewed(), hasAnalysisViewers()
- Update MonitorStream to set flag when streaming FRAME_ANALYSIS
🤖 Generated with [Claude Code](https://claude.com/claude-code)
Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>