When camera->Capture() failed, Monitor::Capture() painted a frame of the
signal check colour into the shared image ring and moved
last_write_index, while the decoder thread could still be writing the
same ring. Capture picked its slot from image_count and the decoder from
last_write_index + 1, so the two could write one slot, giving a viewer a
torn frame, or move last_write_index backwards.
With a decoder thread running, the failure path now only sets
signal = false and leaves the ring to the decoder. Viewers keep its last
frame until the reconnect. That frame was short-lived anyway: zmc closes
the monitor and reconnects straight after the failure, and connect()
clears the ring. The decoder still runs CheckSignal on every decoded
frame, so a capture card's no-signal colour is still detected. With
decoding off nothing else writes the ring, so the signal colour frame is
still written there.
The test drives Capture() with a camera that always fails: with a
decoder the ring, last_write_index and image_count are unchanged;
without one the frame goes into image_count's slot as before.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
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>
When Decode() flushes the codec because decoder_queue is full (#5363),
the next packet it sent was usually not a keyframe. The flushed codec has
no reference frames to decode it against, so until the next keyframe it
returned errors or smeared pictures, which motion detection can score as
an alarm.
After the flush, hold packets back from the codec until a keyframe, as
the KEYFRAMES decoding modes already do. The held packets take the
existing path for packets that are not decoded, so last_write_time keeps
moving and zmwatch does not restart zmc.
refs #5362
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Decode() flushes the codec once decoder_queue holds more than 2 x the
keyframe interval while the codec still wants input (#5363). The codec
legitimately holds frames back before returning one: has_b_frames for
reordering, and one per extra thread with frame threading. For an
all-intra stream (keyframe interval 1, so a limit of 2) decoded with a
raised thread_count that delay alone passes the limit, and the codec was
flushed every few frames with a Warning each time.
Add the delay to the limit in DecoderQueueLimit().
refs #5362
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The throttle in Decode() returned before sending once decoder_queue held
more than 2 x the keyframe interval. It is only reached after
receive_frame() returned EAGAIN, so the codec was waiting for exactly the
input the throttle held back: no frame ever came, last_write_time froze
and zmwatch restarted zmc 45-55 s later. Flush the codec and release the
queued packets (as on decoder thread exit) and carry on with the next
packet; a Warning says it happened.
refs #4860fixes#5362
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The codec can consume packets without returning a frame for them; H.264
does after lost or corrupt slices (RTSP over UDP). Decode() paired each
frame with the oldest decoder_queue entry, so those entries stayed queued
for good: every later frame went to an older packet, and once the queue
passed 2 x the keyframe interval the throttle stopped sending while the
codec waited for input, so decoding stopped until zmwatch restarted zmc.
Match the frame to the entry with its pts and release the entries before
it with an earlier pts (decoded, no image), as the flush paths do. A frame
older than every entry is dropped; without a usable pts the oldest entry
is used, as before.
refs #4860
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
that already exist -- lights on, lights off, play a sound -- at set times.
MonitorActions already says what to do and to which device, with triggers for
EventStart, Alarm, Manual and so on. So this adds a trigger rather than a
subsystem: an action whose TriggerOn is 'Schedule' carries a five field cron
spec, and cron runs it.
Cron, rather than a daemon of our own, because the web user owns a crontab it
can rewrite without privilege, and because the line cron runs,
30 22 * * * /usr/bin/zmcontrol.pl --id 24 --command=lightOff
is the same invocation web/includes/Monitor.php already falls back to when no
zmcontrol daemon is listening. A scheduled action therefore takes the path a
manual one does rather than a parallel one of its own. It also means no new
code runs as root, nothing new has to be supervised, and the feature is a
table column plus a crontab block.
Nothing a form can set reaches a shell. The schedule is refused unless
cronScheduleIsValid() accepts it -- five fields, numbers and the usual
*/,-/ only, with newline, carriage return and % rejected outright because
each would end the line or the command. The command itself comes from
MonitorAction::commandFor()'s fixed list and the ids are integers, so the
whole line is assembled from constrained parts. That is a narrower surface
than Filters.AutoExecuteCmd, which has taken an arbitrary command for years.
The crontab is not ours to own, so ZoneMinder rewrites only a block between
two markers and leaves every other line byte for byte. A block whose end
marker is missing, which is what an interrupted write leaves, is treated as
no block at all rather than swallowing everything after it: losing our own
stale block is the safe failure, losing the admin's entries is not. The block
is rebuilt from the table on every save, so the crontab is a projection of
the database rather than a second place to keep the truth.
zmc recognises the new trigger and skips it, so having one does not warn on
every reload, and nothing fires a scheduled action from the capture process.
An action targeting a monitor on another server is left out and logged: cron
runs zmcontrol.pl locally, and the web ui's proxy through the API has no cron
equivalent. Single server installs are unaffected.
The two pieces that can lose data or run the wrong thing are pure, and
tests/php/test_crontab.php covers them: schedule validation including the
injection cases, and splicing a block in, out and over without disturbing the
lines around it.
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
- Add a helper to add or update Go2RTC URL parameters without overwriting existing options or appending duplicate parameters.
- Allow enabling or disabling RTSP backchannel handling for cameras, including both primary and secondary stream paths.
VideoStore created and destroyed a VAAPI hardware device context for every
event, opening /dev/dri/renderD128 on open and closing it on close. On some
VAAPI drivers the teardown did not actually close the render-node fd, so a
continuously recording monitor leaked one fd per event (one per section, about
every ten minutes for the reporter). After ~1024 fds the process hit its
open-file limit and VideoStore could no longer open, falling back to jpegs.
Cache the device context on the Monitor and hand VideoStore a borrowed
reference through Monitor::GetEncoderHWDeviceContext(). The render node is now
opened once for the monitor's lifetime and reused by every event, so there is
no per-event device teardown to leak, and encoder setup is cheaper. The
contexts are released in ~Monitor once no VideoStore can be borrowing them.
The cache keys one context per (hwdevice type, device) and never evicts,
because the auto encoder list interleaves VAAPI and QSV: a single cached slot
would be dropped when a failed probe of the other type ran between two probes
of the type actually used, recreating the device every event and preserving
the leak. Keying per type keeps each device for the monitor's life regardless
of probe order.
setup_hwaccel() now reuses a device context the caller supplies and only
creates its own when none is given, so the decoder path and the fallback (when
the monitor cannot provide one) are unchanged.
Validated with a standalone reproduction against VAAPI (ffmpeg 9, Intel iHD):
creating and freeing a device per iteration keeps the renderD128 fd count flat
on this driver, while the shared-device model holds it at one for the lifetime
regardless. A Catch2 test is not added because it requires a GPU and CI runs
with the test suite disabled.
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
The latch was released in Analyse() at the isAlarmed() sample, before the
packet was committed. Two paths then spent a momentary DetectedSound pulse
without recording it:
- A video packet not yet decoded makes Analyse() return at the decode gate
before packet->score is set, and the same packet is retried. The sample --
and the release -- ran on every retry, so the pulse was gone by the time the
packet was decoded and scored, and the event recorded no alarm frame. This is
why raising AlarmFrameCount or the earlier hold did not help: the retries of
one undecoded packet consumed the latch.
- An audio packet (these cameras alarm on AudioAnalytics/DetectedSound, so audio
packets are present) could sample and release the latch, but alarm_frames
counts video frames, so the pulse was again recorded on no counted frame.
Defer the release to the point where a video packet is committed with its
score, so the latch is spent only on a frame the event actually writes.
Also keep the topic/value of the last activation and report it from
SetNoteSet() when the alarms map has already been cleared, so a momentary
pulse's event note still names the cause (e.g. AudioAnalytics/Audio/
DetectedSound/true) instead of a bare "ONVIF".
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
The ONVIF alarm was a plain atomic bool that the poll thread set and the
analysis thread sampled once per frame. A momentary alarm -- a DetectedSound
pulse the camera reports active then inactive between two analysis frames --
was raised and cleared on the raw level before any frame sampled it, so the
recorded event had no alarm frames. A motion alarm stays active for seconds
and so was always sampled, which is why MotionAlarm never showed the problem.
Replace the bool with an AlarmLatch: raise() marks the level active and that
an activation is waiting to be seen, clear() drops the level, and the analysis
thread calls observeAlarm() once it has sampled the alarm. isAlarmed() stays
true from a raise until the level is down and the activation has been observed,
so a pulse is reported on at least one frame however short it was. A
still-active alarm is unaffected. The latch is released only on a frame that
scored, so a pulse arriving just after the isAlarmed() check is kept for the
next frame rather than lost.
The activation guards in WaitForMessage() now test the raw level (alarm_.active())
instead of isAlarmed(), so a new topic still raises the level while an earlier
pulse's latch is still pending.
Add Catch2 coverage for AlarmLatch (tests/zm_onvif_alarm_latch.cpp), testable
without a gSOAP context like the other ONVIF free-function tests.
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
A monitor with Capturing=Ondemand and LinkedMonitors never recorded a linked
alarm unless someone happened to be watching it. Links are evaluated in
Analyse(), per captured packet, and zmc pauses an on-demand camera, stopping
its analysis thread, 10 s after the last viewer. While paused nothing looked
at the links, so every alarm on the linked monitor was missed. This is the
low-bandwidth setup of a substream that analyses and a main stream that
records on demand.
zmc's on-demand decision moves into Monitor::CheckOndemand(), around a
DecideOndemand() table that can be tested:
- While paused, the links are checked on every pass. The analysis thread is
stopped then, so the capture thread reads them without racing it. An alarm
reopens the camera.
- An unwatched monitor keeps capturing while it is alarmed or in its
post-event frames, instead of pausing in the middle of the event.
- A link only reports an alarm while it lasts, and reopening the camera can
take longer than that (2.5 s against a local camera). So the wake is
remembered for up to 30 s, and the first packet Analyse() scores counts it
as a linked alarm, then clears it.
Tested live on 1.38 with a paused on-demand passthrough monitor linked to an
analysing one. Before: an 8 s forced alarm on the source recorded nothing.
After: the monitor woke within 0.1 s, alarmed 2.5 s later and recorded the
event. A 1 s alarm, over before the camera reopened, was also recorded.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
#5276 re-parsed LinkedMonitors in Reload() because nothing else did until
the next reconnect. Since #5239, every reload is a reconnect: zmc Close()s
and disconnect()s the monitor, calls Reload(), then connect(), and
connect() already calls ReloadLinkedMonitors(). The call in Reload()
queried the database once per linked monitor for an expression connect()
then threw away.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Monitor::CheckAction() handled the RELOAD action (zmu --reload, or a script
setting it through ZoneMinder::Memory) by calling Reload() in place. That
runs on zmc's capture thread, and Monitor::Load() rewrites settings such as
label_format, orientation and the image sizes while the decoder and analysis
threads read them unlocked.
SIGHUP already reloads safely: zmc leaves its capture loop, Close()s and
disconnect()s each monitor, which stops those threads, then Reload()s and
reconnects. Have the action set zm_reload, as the SIGHUP handler does, so
both take that path.
zmc reloads every monitor it runs this way, not only the one the action was
sent to; zmc normally runs one.
Tested live on 1.38 with zmu --reload against a running zmc: the event closes,
the same process reloads and reconnects, capture resumes and a new event
opens.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Monitor::Reload() (the RELOAD action `zmu -m N -L` sends) re-reads the
monitor row, which replaces linked_monitors_string, but the
MonitorLinkExpression built from it is only rebuilt in connect(). The
old links stayed in use until zmc reconnected: after changing
LinkedMonitors from 3 to 4 and reloading, zmc kept scoring monitor 3
and ignored alarms on 4.
Rebuild the expression in Reload(), under event_mutex, which Analyse()
holds while it evaluates linked_monitors.
fixes#5275
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Resolves the conflict with dad9da272 (refs #4242) in Monitor::Capture():
keep the timestamp continuity block from master, followed by this
branch's signal handling. Same tree as the branch rebased onto
233a15828, which passed the holodeck checks.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Monitor::Poll() ended by sleeping until 10 s after it started, and
PollThread::Stop() joins the thread, so Monitor::Close() waited for the
rest of that sleep: up to 10 s on every stop, reconnect and reload of a
zmc whose monitor has an ONVIF event listener, Janus, RTSP2Web, Go2RTC
or the Amcrest API enabled.
Wait for the next poll in PollThread::Run() on a condition variable
that Stop() notifies. Polls still start every 10 s.
fixes#5269
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
When a camera's clock steps back by under 10 s (an NTP sync, a clock reset),
the packets after the step carry dts values behind the ones before it. The
video store patched each one to last_dts + last_duration and logged "non
increasing dts, fixing." for every packet until the event ended, thousands
per event. Splitting the event at the step doesn't help on its own: in
passthrough an event has to start on a keyframe, and the walk back for one
crosses the step again.
Handle it the way ffmpeg's demuxer does, where packets enter the pipeline:
the Monitor keeps each stream's last dts and one offset shared by all the
camera's streams. When a stream steps back by more than 1 s, the offset moves
so the stream continues one frame after where it was, and every packet gets
the offset from then on. Monitor::Capture applies it before the stream
socket, the packet queue or anything else sees the packet, and Pause() resets
it when the capture session ends. The packet queue, the event's choice of
first keyframe and the video store then see one continuous timeline: nothing
is split, flagged or patched downstream, and no video is dropped. Steps under
1 s are reordering jitter, left to the video store's reorder queue; steps of
10 s or more keep FfmpegCamera's existing handling.
tests/zm_monitor_dts.cpp covers a continuous stream, jitter, the 8.9 s and
1.048 s steps, audio following the offset video set, a missing duration and
packets without a dts.
Alternative to #5212 and #5068.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
decoding_image_count is incremented by the decoder thread and read by
Ready() on the analysis thread; motion_frame_count is incremented by
the analysis thread and read by UpdateFPS() on the capture thread. Both
were plain ints. ThreadSanitizer reports zm_monitor.cpp:3687 and :2366.
Make both std::atomic<int>, and reset decoding_image_count in Pause()
after the analysis thread is joined instead of between the decoder and
analysis joins, while Ready() could still read it.
fixes#5250
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
On GRAY8 and planar YUV images CheckSignal compared the Y byte with the
low byte of the RGB setting, which is its blue component. A camera
showing the default #0000BE decodes to Y=35 and never counted as lost;
only a colour whose blue byte happened to equal the luma matched.
Compare with the BT.601 luma of the colour in limited range (YUV420P,
YUV422P) and in full range (J formats, GRAY8). The low byte still
matches, so setups that stored the luma there (#000023, as the V4L2
probe does for GREY) keep working.
fixes#5240
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Capture set shared_data->signal to true for every packet while the
decoder set it to CheckSignal() for every decoded frame. With
SignalCheckPoints on and a camera showing its lost-signal picture,
Analyse sometimes read Capture's true between two decoded frames, so the
signal flipped back for one frame: the event was closed for signal loss
and a zero-frame "Signal: Reacquired" event opened, about once a minute.
Capture now writes true only when no decoder measures the signal: no
SignalCheckPoints, Decoding=None, or on-demand decoding with no viewer.
It still writes true for the first packet after connect(), as before, so
Analyse doesn't see a signal loss before the first decoded frame and the
first event keeps its cause. The capture-failure path still writes false.
fixes#5235
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Ffmpeg reaches the same network cameras libvlc did, so carrying a second
streaming library -- with its own threading, its own bugs and its own
build dependency -- buys nothing. The preceding migration moves existing
monitors to Ffmpeg first, so Monitor::Load cannot meet a type it no
longer recognises, which is Fatal and would stop zmc rather than skip
the monitor.
Drops LibvlcCamera, the LIBVLC camera type and its parse and
construction arms, LIBVLC_SRC and Camera::IsLibvlc, the ZM_NO_LIBVLC
option and the libvlc probe, and the HAVE_LIBVLC and HAVE_VLC_VLC_H
defines. Since the camera resolved libvlc through dlopen rather than
linking it, this removes a headers-only build dependency and a runtime
one, and nothing else needed relinking.
kOptionSeparators stays -- the Ffmpeg path still parses the Options
field with it -- but it is no longer a contract shared between two
readers, so its comment and the test that pins its behaviour are
reworded rather than removed.
Built clean from a fresh cmake configure, which no longer lists libVLC
among optional libraries; unit suite passes (147 cases, 12531
assertions); no libvlc strings remain in zmc.
Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_015Y6FieTwEXuLhhR4e2yiax
NVSocket spoke a bespoke socket protocol to one vendor's nvr. It has a
single known user, no way for anyone else to test it, and nothing it
reaches that ffmpeg cannot reach over rtsp or http, so it is removed
rather than carried further.
Drops RemoteCameraNVSocket, the NVSOCKET camera type and its parse and
construction arms, the source-type option and settings panel in the web
ui, and the stray ja_jp translation key. The preceding migration moves
any existing rows off the type first, so Monitor::Load cannot meet a
type it no longer recognises -- that path is Fatal and would stop zmc
rather than skip the monitor.
Built clean; unit suite passes (147 cases, 12531 assertions, run from
tests/ where the font fixtures' relative paths resolve). eslint clean.
Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_015Y6FieTwEXuLhhR4e2yiax
The table is indexed by Monitor::CameraType but had no entry for
LIBCURL, so every name from that point on belonged to the wrong type --
LIBCURL printed "NVSOCKET" and NVSOCKET printed "VNC" -- and VNC, the
last value, indexed one past the end of the array. The only reader is a
Debug(1) in Monitor::Load, so a VNC monitor read out of bounds whenever
debug logging was on.
Add a static_assert tying the table's length to the last enum value, so
adding or removing a camera type fails the build instead of silently
shifting the names again. Verified by removing an entry and confirming
the build fails on the assertion.
Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_015Y6FieTwEXuLhhR4e2yiax
Both reach cameras that ffmpeg reaches. Libvlc does it through a second
streaming library with its own build dependency, threading and bugs; NVSocket
speaks a bespoke socket protocol for one vendor's nvr that we have no way to
test. Neither earns the maintenance, and the same monitors work as Type Ffmpeg
with the camera's rtsp or http url.
Deprecated, not removed. A monitor using either still captures; it logs a
warning at startup naming what to change it to, and the form marks the type and
explains. That follows what Remote/RTSP did before it was removed, which is the
shape that gives people a release to move in.
The warnings were verified firing rather than assumed: switching a monitor to
each type in turn produces the expected message naming that monitor.
php -l and eslint clean; the three pre-existing duplicate lang keys are
unchanged. Suite 147 cases / 12531 assertions.
Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_015Y6FieTwEXuLhhR4e2yiax
rtsp_describe was passed to RemoteCameraRtsp and nowhere else, so with that
camera gone it was loaded from the database on every monitor read and then
ignored.
The SELECT column and its positional read come out together. They have to: the
row is walked by index, so removing one without the other silently shifts every
field after it rather than failing to build.
The Monitors.RTSPDescribe column stays. Dropping it is a migration and a web
change, which is a separate piece of work from no longer reading it.
Verified against the live database rather than by inspection, since a
misalignment here compiles perfectly: the monitor loads its name, 2560x1440
geometry, hevc codec and vaapi setting correctly, and captured 668 frames with
no errors.
Suite 147 cases / 12531 assertions.
Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_015Y6FieTwEXuLhhR4e2yiax
RemoteCameraRtsp was the last camera that opened one, so Camera's
mVideoCodecContext and getVideoCodecContext() are now written by nobody and
read only by the fallback that existed for it.
Drop both. Monitor::GetVideoCodecContext() returns the monitor's context and
nothing else, OpenDecoder() no longer has to ask whether the camera brought its
own, and FfmpegCamera::Close() stops freeing a pointer it cannot have set. The
audio decoder stays with the camera; only video moved.
This is what the previous commits were working towards: one owner for the
decoder, with the hw device reference and the hw pix fmt storage beside it, and
no path where a camera can free a context the decoder thread is using.
Verified on hardware after the removal: vaapi negotiated, 646 frames into a
recorded event, no errors. Suite 147 cases / 12531 assertions.
Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_015Y6FieTwEXuLhhR4e2yiax