Commit Graph
1516 Commits
Author SHA1 Message Date
Steve GilvarryandClaude Fable 5.1 2f1112cd14 fix: build the stream snapshot from one synchronized view of state and health
RefreshStreamSnapshot read the analysis thread's state member from the
capture thread (through SendStreamHealthEvent) while SetState could be
writing it, and only the health fields were under the mutex. Two threads
could also each build a snapshot and publish them in the wrong order.
SetState now mirrors the state into a field guarded by
stream_event_mutex, and the snapshot is built and published under that
one lock from the mirror and the health fields, so every snapshot is a
consistent view and the last one published is the newest.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-23 15:07:15 +10:00
Steve GilvarryandClaude Fable 5.1 7d9d97f387 fix: apply both stream parameter sets to the stream socket in one generation
Two problems with announcing streams one at a time. SetAudioParams only
bumped the generation when audio had been announced before, so audio
joining a video-only stream was appended to the current generation after
its video HELLO, which the protocol says is the last HELLO of a
generation. And a re-prime that changed both streams bumped twice:
consumers saw, and a connecting consumer was handed, an intermediate
generation pairing the new audio with the old video, which
zm_rtsp_server built a session for and tore down again.

Add StreamSocket::SetStreams(video, audio), which applies the whole set
under one lock: unchanged is a no-op, the first announcement stays in
generation 0, and any change once a video HELLO has gone out - new
parameters, a stream appearing, a stream disappearing - is exactly one
bump with every remaining stream re-announced, audio first. The single
stream setters and the new ClearVideoParams are wrappers over the same
logic, and a null or codec-less parameter set means "no such stream".
PrimeCapture passes both streams in one call.

Tests: audio joining an announced video stream bumps the generation;
SetStreams keeps the initial announcement in generation 0, changes both
streams in one generation with consistent pairing, and drops a video
stream the source no longer has.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-23 15:07:14 +10:00
Claude 7502019ecb fix: copy the stream socket path into shm without a truncating strncpy
GCC at -O2 rejects strncpy with a bound equal to the destination size
(-Werror=stringop-truncation), which failed the Release CI build. The
preceding length check already guarantees the path and its terminator
fit, so copy size()+1 bytes with memcpy instead.

refs #5143

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01T4UcdJLt1bxwdpcigGxZRD
2026-09-20 01:48:19 +00:00
Claude 21042ba2f7 fix: send audio HELLO first and keep rtsp sessions across a zmc restart
Correct three problems in the stream socket generation tracking added by
the previous review fix-up:

- ClearAudioParams bumped the generation without restarting the video
  sequence or dropping the cached keyframe, so a late joiner received a
  HELLO at generation N+1 followed by a KEYFRAME still stamped N, and
  sequences did not restart as documented. It now does the same full bump
  as SetVideoParams/SetAudioParams.
- zm_rtsp_server rebuilt the xop session whenever the generation changed,
  even with identical codec parameters. Generations restart at 0 when zmc
  restarts, so every zmc restart dropped the RTSP clients; the original
  code kept the session in that case. Unchanged parameters now just adopt
  the new generation without a teardown.
- Deciding whether audio belongs to the current generation by comparing
  per-stream generation numbers raced the two HELLOs of a generation
  (double rebuild when Update() ran between them) and cannot tell a
  producer restart apart. The producer now sends the audio HELLO before
  the video HELLO within a generation (on connect and on every bump, and
  PrimeCapture announces audio before video), so the video HELLO always
  completes a generation's parameter set. The consumer forgets the
  previous generation's HELLOs when a new generation starts and on
  disconnect, and builds only once the video HELLO of the latest
  generation is in. It also records whether audio was announced at build
  time rather than whether a packer was created, so an unsupported audio
  codec no longer triggers a rebuild on every pass.

The ordering guarantee is documented in the protocol header and the
stream socket docs. Tests pin the audio-first order on connect and on a
video reconfigure, and the keyframe drop and sequence restart on audio
removal.

refs #5143

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01T4UcdJLt1bxwdpcigGxZRD
2026-09-20 00:36:35 +00:00
Claude 89837a6b40 fix: start the monitor stream socket before capture connects
Address monitor-side stream socket review findings:

- zmc starts the stream socket before the first connect attempt, and
  SendStreamHealthEvent records the health state even when the socket is
  not up yet, so connection/prime faults during startup are observable to
  a consumer instead of being lost until the first successful prime.
- PrimeCapture announces audio whenever the camera has a decodable audio
  stream (Capture forwards audio packets unconditionally), and clears a
  previously announced stream when a re-prime no longer sees it.
- Publish the media stream socket path in the monitor shared-memory
  block (reusing the retired video_fifo_path field as stream_socket_path,
  same offset and size) so consumers discover it without hard-coding the
  convention or reading the producer's zm.conf; the PHP Monitor object
  and the ZoneMinder::Memory Perl module expose the renamed field.
- Move the wall-clock microseconds helper out of zm_monitor.cpp into
  zm_time.h as SystemClockMicros(), where time helpers belong.

refs #5143

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01T4UcdJLt1bxwdpcigGxZRD
2026-09-19 23:00:14 +00:00
Steve GilvarryandClaude Fable 5.1 84b1c06430 fix: drop the cached stream socket keyframe when the capture source closes
The keyframe cached for late joiners survived Monitor::Close(). A
consumer connecting while the camera reconnected was primed with a
keyframe from the previous capture session, whose pts can be ahead of
what the new session produces, and with identical stream parameters
there is no generation bump to warn it. Add StreamSocket::InvalidateKeyframe()
and call it from Close(); the next keyframe from the new session fills
the cache again.

Tests: after InvalidateKeyframe() a new consumer gets HELLO and then the
next live packet, with no KEYFRAME replay in between.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-16 05:12:42 +10:00
Steve GilvarryandClaude Fable 5.1 9570e24265 fix: skip the stream socket HELLO for cameras without an encoded stream
Camera::getVideoStream() creates a stream with codec id NONE for sources
that hand zmc decoded images (V4L2, MJPEG over HTTP, VNC). PrimeCapture
announced that stream anyway, and ParseHello rejects a HELLO without a
codec, so every consumer logged a malformed HELLO warning on each
connect to such a monitor although no media could ever follow. Only
announce a stream that has a codec; the socket still carries lifecycle
events for these monitors.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-16 05:12:42 +10:00
SteveGilvarryandClaude Fable 5.1 0a392802f8 feat: emit capture-fault and state-change events on the monitor stream socket
Wire the monitor lifecycle events into zmc. Monitor::SetState() replaces
the scattered shared_data->state assignments in Analyse() and connect(),
publishing a state_changed event (with previous and new state id and name)
whenever the analysis state actually changes. Monitor::SendStreamHealthEvent()
emits the capture-fault edges and tracks the active fault for the snapshot;
the snapshot is refreshed on every state or health change and after a
successful prime, so a consumer connecting mid-fault learns current status.

zmc's capture loop emits the six health transitions once per edge:
connection failed/restored around connect(), prime_capture failed/restored
around PrimeCapture(), capture_failed on pre/capture/post failure, and a
single capture_resumed once the pipeline recovers. Because the stream
socket survives camera reconnects, these are observable exactly when media
has stopped. A small mutex guards the health fields shared between the
capture thread (health events) and analysis thread (state events).

Documents the EVENT frame in docs/stream_socket.rst and decodes it in
tools/zm_stream_socket_dump.py. Full build and ctest pass (121 tests).

refs #2875

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-16 05:02:24 +10:00
SteveGilvarryandClaude Fable 5 94eeec6c2a refactor!: retire fifo path fields from SharedData
Rename video_fifo_path/audio_fifo_path to reserved_path1/2, keeping the
struct layout and 864-byte size unchanged so existing shared memory
mappers (and out-of-tree shm readers) keep working through the
transition. The fields are zeroed at startup as before, scrubbing any
stale path strings left by a pre-upgrade zmc.

The stream socket deliberately publishes nothing via shared memory: its
path is the documented convention PATH_SOCKS/stream_{monitor_id}.sock,
derivable from static config, and codec parameters travel in the HELLO
handshake instead of shm fields.

Perl (Memory.pm) and PHP shared memory maps updated to match by name;
offsets are unchanged.

Tests: full suite passes via ctest; php -l clean on Monitor.php.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-09-16 05:02:24 +10:00
SteveGilvarryandClaude Fable 5 50aa94cd1c refactor!: remove media FIFO output from zmc
The per-monitor media FIFOs (video_fifo_{id}.{codec} /
audio_fifo_{id}.{codec}) are fully replaced by the monitor stream
socket; their only in-tree consumer, zm_rtsp_server, was ported in the
previous commits. Removes:

- the Fifo writer instance API (open/close/write/writePacket, the
  O_NONBLOCK silent-drop path and the 1MB F_SETPIPE_SZ kernel buffer
  per pipe); the class keeps only the static fifo-creation helpers
  still used by the diagnostic image pipes
- fifo creation in PrimeCapture (including the codec-name-as-file-
  extension discovery hack), the write call sites in Capture (including
  the extradata-before-every-keyframe rewrite - extradata travels in
  the stream socket HELLO), and the Close()/destructor teardown
- the GetVideoFifoPath/GetAudioFifoPath accessors

The shared memory fifo path fields are retired separately in the next
commit. zm_fifo_debug and zm_fifo_stream (diagnostic pipes) are
unrelated features and unchanged.

BREAKING CHANGE: external consumers of the media FIFOs must move to
the stream socket (PATH_SOCKS/stream_{monitor_id}.sock, see
zm_stream_socket_protocol.h).

Tests: full suite passes via ctest; all binaries build clean.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-09-16 05:02:24 +10:00
SteveGilvarryandClaude Fable 5 8b0679651e feat: serve monitor media on the per-monitor stream socket
zmc now serves every monitor's compressed media on
PATH_SOCKS/stream_{monitor_id}.sock, alongside the media FIFOs (which a
later change removes). Always on, like zms streaming and zmdc.sock: the
path is a documented convention derived from static config, consumers
connect on demand, and an idle socket costs nothing. No new monitor
option, no shared memory change.

- PrimeCapture() creates and starts the socket once, then (re)applies
  video/audio codec parameters on every prime; a camera reconnect that
  changes parameters bumps the protocol generation and rebroadcasts
  HELLO to connected consumers
- Monitor::Capture() queues each video access unit (with keyframe flag)
  and audio packet by reference; payloads are never copied
- the listener survives Close() so consumers keep their connection
  across camera reconnects; it is freed in the destructor
- the FIFO's write-extradata-before-keyframe hack is not carried over:
  extradata travels in the HELLO handshake

Tests: full suite 98/98 pass via ctest; zmc/zms/zmu/zm_rtsp_server all
build with no new warnings.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-09-16 05:00:44 +10:00
Steve Gilvarry 1316ca3a33 Merge branch 'master' into 5127-packetqueue-iterator-leak 2026-09-12 15:03:28 +10:00
Steve GilvarryandClaude Opus 5 f04302d6fc fix: initialize alarm_actions_fired in declaration order
ad70d5e80 added alarm_actions_fired to the Monitor constructor's
init list between audio_alarm_score and wallclock_timestamps, but
declared the member far later in the class, after linked_monitors.
Members are initialized in declaration order regardless of the order
written here, so gcc rejects it under -Werror=reorder:

  src/zm_monitor.h:767:8: error: 'Monitor::alarm_actions_fired' will
  be initialized after
  src/zm_monitor.h:621:19: error:   'bool Monitor::wallclock_timestamps'

This is a plain bool with a constant initializer, so nothing observable
changes - only the order the entry is written in. Moved it to sit after
linked_monitors, matching where the member is declared.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01B5KL9Xbi7K5aGsauLtd8tG
2026-09-12 14:41:08 +10:00
Isaac ConnorandClaude Opus 5 99ae7b8e98 fix: free the event start iterator when openEvent cannot lock its packet fixes #5127
PacketQueue::get_event_start_packet_it() allocates a packetqueue_iterator and
registers it in PacketQueue::iterators. Every path out of Monitor::openEvent()
hands that pointer to the Event, which releases it in ~Event via free_it, except
the one that fails to lock the starting packet. That path returned nullptr and
left the iterator registered for the life of the process.

clearPackets() takes min_iterator_queue_index across all registered iterators and
stops removing at the first packet whose queue_index reaches it. An abandoned
iterator pins that to the front packet, so the trimmer removes nothing on every
invocation, and deletePacket() advances registered iterators onto the packet
after the one it removed, which drags the orphan onto each new front packet so it
can never age out. clear_packets_pending_ then latches true, downgrading the gate
so the futile scan re-runs on every video packet rather than only on keyframes.

The only removal path left is the emergency one-GOP eviction in queuePacket, so
the queue settles into refill a GOP, exceed max_video_packet_count, warn, evict a
GOP, repeat. It is pinned at its cap by construction, which is why the monitor
warns once per GOP at a constant rate for as long as zmc runs and no amount of
idle time or extra headroom recovers it.

Our trigger was an RTSP stream EOF mid-event during a reconnect on an ONVIF
camera. It is a race, so it leaks only when openEvent loses it, and each
occurrence leaks one more iterator.

Add tests covering both halves: that free_it takes an event start iterator back
out of the queue, and what an abandoned one does to trimming until it does.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-09-11 21:49:34 -04:00
Isaac ConnorandClaude Opus 5 2d6565da1f fix: stop the audio note growing the event's Notes on every frame
Event::updateNotes only inserts into the note set and rewrites the Notes
column each time it gains a string. The audio note carried the live level, so
every distinct reading added another entry and another database write, and the
event ended up recording the whole climb:

  Audio: level 10, level 11, level 12, ... level 78, ...

Measured on this install before the fix: monitor 1 reached 946 bytes of notes
and averaged 117, against 8 to 12 bytes on monitors without audio detection.

The note is now the constant AUDIO_CAUSE, matching the ONVIF and Amcrest notes
a few lines above. The level is still in the Debug line, which is where a
per-frame reading belongs.

Existing events keep their bloated notes. Rewriting recorded history to tidy
up would be worse than leaving it to age out with normal event deletion.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01UvTCzCbvGt8xKQRNCSA7o8
2026-09-11 20:13:03 -05:00
Isaac ConnorandClaude Opus 5 ad70d5e80a feat: add an AlarmEnd trigger to monitor actions
Alarm turns a light on when motion starts; nothing turned it back off. The
existing EventEnd is not the answer: the alarm ends when the monitor leaves the
alert state, while the event carries on recording for the rest of its section,
which on a continuous-recording monitor is up to ten minutes later.

Analyse() leaves the alarm condition by three paths and all three fire it: the
normal ALERT to IDLE, a signal change, and the trigger being turned off. The
abnormal two matter most - a light switched on by an alarm must not stay on
because the camera lost signal.

That needs the firing to be paired, so alarm_actions_fired is set when Alarm
fires and cleared by EndAlarmActions. It guards both directions:

  - the three call sites can run back to back, so without it one alarm could
    fire AlarmEnd several times
  - signal loss and trigger off also run on monitors that never alarmed, and an
    unpaired AlarmEnd would switch a light off for an alarm that never happened
  - the ALERT to ALARM re-trigger inside one incident deliberately does not
    re-fire Alarm, so a single AlarmEnd still has to balance it

The migration MODIFYs the enum and appends the value, so stored rows keep their
meaning; appending to an enum does not renumber what is already there.

Tested: 8 assertions over the pairing rule, run standalone because the real
class needs a database and a camera - the ordinary pair, repeated calls firing
once, an unpaired call firing nothing, two alarms pairing independently, and
the re-trigger case. The action test now also requires every trigger name to
round trip through the TriggerOn enum, so an action saved by the editor cannot
load with a trigger the C++ does not recognise and fire at the wrong moment.
Build clean at 1.39.33, Perl 15 files / 249 assertions, ESLint 0 problems,
tests/js 154 assertions, php -l clean.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01UvTCzCbvGt8xKQRNCSA7o8
2026-09-11 20:13:03 -05:00
Isaac ConnorandClaude Opus 5 c20b6a9488 docs: name the release that removes Remote/RTSP support
A deprecation warning without a version attached is one people learn to
scroll past. Both notices now say deprecated as of 1.40, removed in 1.41.

Removal is 1.41 rather than 1.40 because 1.39.x is the development series.
Anyone running stable is on 1.38 and will never see a 1.39.x warning, so
removing in 1.40 would take the feature away in the same release that first
mentions it - no notice at all for the people it affects. Warning in 1.40 and
removing in 1.41 gives stable users one release to migrate.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01UvTCzCbvGt8xKQRNCSA7o8
2026-09-11 20:13:03 -05:00
Isaac ConnorandClaude Opus 5 8d77f0f637 feat: deprecate the Remote/RTSP capture method in favour of Ffmpeg
ZoneMinder carries its own RTSP/RTP implementation - zm_rtsp.cpp,
zm_rtp_ctrl.cpp, zm_rtp_source.cpp, zm_rtp_data.cpp, zm_rtp.cpp and
zm_remote_camera_rtsp.cpp, about 66KB in total. It is hand-written parsing of
untrusted network input, which is the least rewarding kind of code to own, and
Ffmpeg already does the same job for more cameras and is maintained upstream.

This marks it deprecated. It does not remove anything and does not change how
any existing monitor captures.

The capture log now names the replacement instead of only saying the method is
going away:

  Monitor 7 (Driveway): the Remote/RTSP capture method is deprecated and will
  be removed. Change this monitor to Type 'Ffmpeg' with Source Path
  rtsp://10.0.0.5:554/live

Monitor::RtspUrlFromRemote builds that URL from the Host, Port, Path, User and
Pass the monitor already stores. It is pure so it can be tested without a
camera, and it is the piece a conversion migration will need when the code is
finally deleted.

The URL is passed through remove_authentication() before being logged, the
same helper zm_ffmpeg_camera.cpp uses. A deprecation notice that wrote camera
passwords into /var/log/zm would be a bad trade.

Credentials are percent-encoded. A password containing @ or : otherwise splits
the authority in the wrong place and yields a URL pointing at a different host,
which fails in a way that is hard to read.

In the editor the protocol is now labelled "RTSP (deprecated)" and selecting it
explains what to change to. Only the label moved: htmlSelect still emits
value="rtsp", so updateMethods and the stored value are untouched.

No auto-converting migration. Deprecating and removing are separate steps, and
silently rewriting a working monitor to Ffmpeg could break a camera that Ffmpeg
handles worse - which is the reason to warn a release ahead of removing.

Tested: 16 assertions over the URL builder, run standalone because ctest still
cannot build against the Catch2 v2 installed here - empty credentials producing
no dangling userinfo, user without password, @ : / ? # and space in passwords,
a username needing escaping, missing leading slash, empty path, absent port,
query strings surviving, and that the masked form drops the password while
keeping the host. Full build clean, Perl 15 files / 249 assertions, ESLint 0
problems, tests/js 154 assertions, php -l clean.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01UvTCzCbvGt8xKQRNCSA7o8
2026-09-11 20:13:02 -05:00
Isaac ConnorandClaude Opus 5 c7deb3faa8 feat: score monitors on how loud their audio is
ZoneMinder has carried audio for years without ever listening to it: the
packets go into the event and nothing reads them. AudioDetector decodes
them in the capture thread and reports a 0-100 level, which Analyse()
turns into score alongside motion, ONVIF and Amcrest.

The level is dBFS-derived, not a raw amplitude ratio. Linear RMS is
unusable as a setting: ordinary speech sits at 1-3% of full scale, so
every sound worth catching would be crammed into the bottom two points of
the range and no operator could tune it. Mapping -60..0 dBFS onto 0..100
puts speech around 43 instead.

Three columns on Monitors: AudioDetection to enable it, AudioThreshold
for the level to alarm at, and AudioAlarmScore for what it contributes.
AudioAlarmScore defaults to 9, matching what an ONVIF or Amcrest alarm
already adds. A threshold of 0 means off, so enabling detection without
choosing a threshold cannot alarm on silence -- a plain level >= threshold
test would alarm on every packet in that state.

The level and the alarm flag go in SharedData's two spare bytes, renamed
from reserved1/reserved2. Offsets and sizes are unchanged, so the
888-byte cross-process layout and the Memory.pm and Monitor.php offset
tables all still agree; the readers are renamed in the same commit so the
level is available to the web UI.

The decoder is opened lazily on the first audio packet rather than at
camera setup, so a monitor with detection off never carries one and a
stream that gains audio on reconnect still gets picked up. Scoring reads
the capture thread's most recent level rather than scoring per audio
packet, because the score belongs to a video frame and audio packets do
not arrive in step with them.

Tested: 242 assertions over the pure helpers - the RMS of both sample
formats, the dB scale's monotonicity and endpoints, full-scale clamping
of decoder overshoot, and the threshold-0 case. The repo's Catch2 harness
needs v3 and only v2 is installed here, so tests/zm_audio_detector.cpp
was compiled against a v2 shim to check it, and an identical set of
assertions was run standalone.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01UvTCzCbvGt8xKQRNCSA7o8
2026-09-11 20:13:02 -05:00
Isaac Connor 5951d64f29 fix: re-read monitor actions on reload, not only at startup
LoadActions() ran once during setup, so an action added or edited in the
monitor editor did nothing until that monitor's zmc was restarted. Zones
are already re-read by the Load() call in Reload(), and actions have the
same lifetime and the same editing pattern, so the two should behave the
same way.

LoadActions() clears the vector before filling it, so calling it again is
idempotent and the reload cannot accumulate duplicates.

Not covered by a test: the action tests exercise the pure mapping and
message-building functions, and there is no fixture for a database-backed
Monitor to assert the call from Reload(). Verified by inspection and a
syntax check.
2026-09-11 20:13:02 -05:00
Isaac Connor eafdffcd95 feat: add per-monitor actions that drive a light or a speaker on alarm
A camera that detects motion should be able to sound a speaker, and the
speaker is rarely the camera: it is a separate device with its own address,
credentials, stream and Controls entry. Model it as a monitor and let a
monitor's alarm drive actions on other monitors.

Add Monitors.DeviceClass enum('Camera','Speaker'). This is what the device
is, as distinct from Type, which selects the capture backend - an IP speaker
still captures over Ffmpeg like any other RTSP device, so Type could not
carry the distinction.

Add the MonitorActions table: MonitorId is the monitor that triggers,
TargetMonitorId the device acted on, and the two are frequently different.
TriggerOn covers EventStart, EventEnd, Alarm and Manual.

Which actions a device is offered is decided by its Controls row - CanLight,
CanIndicatorLight, CanAudioPlay - so a device can only be asked to do what it
has been measured to do. The editor filters on this and the save path
re-checks it, because the request is not to be trusted.

Execution goes straight to the target's zmcontrol socket rather than forking
zmcontrol.pl per action: the daemon already accepts a line of JSON there, and
it is the same path the control panel uses. ActionCommandName maps the DB
enum onto a method name as a whitelist, so nothing out of the database
reaches the control daemon uninspected. Actions are fire-and-forget - a
speaker that is offline is logged and skipped, never allowed to hold up event
handling.

Alarm actions fire only on the genuine entry into alarm, not on the
ALERT->ALARM re-entry, which would re-sound a speaker within one incident.
EventEnd runs on the calling thread before the event is handed to the closing
thread, which does not capture `this`.

Manual actions appear as buttons on the watch page, and are the reason the
control panel is now shown for a monitor that has actions but no control of
its own. Firing one sends only the action id; the command and target are
rebuilt server side, and Control rights are required on the target device and
not merely on the monitor the action hangs off.

Also add --file to zmcontrol.pl, without which audioPlay could not be driven
from the command line. The web path was unaffected as it bypasses GetOptions.

Tests: tests/zm_monitor_action.cpp covers the command whitelist, the message
format (including that file id 0 is a real id and that a stale AudioFile is
never passed to a command that takes none), trigger names, and that every
value of the ActionType enum maps to a command.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01UvTCzCbvGt8xKQRNCSA7o8
(cherry picked from commit b561341e988af69c3a46db854da410309f7cfa82)
2026-09-11 20:13:02 -05:00
Isaac ConnorandClaude Opus 5 47379cc083 fix: keep last captured image available while OnDemand capture is paused
Monitor::Pause() reset shared_data->last_write_index to image_buffer_count,
the "nothing written yet" sentinel. Once an OnDemand monitor went to sleep the
last captured image became unreachable, so zms mode=single gave up waiting and
returned "No image available." mode=jpeg worked only because runStream calls
setLastViewed() each iteration, waking capture for a fresh frame.

The zmc OnDemand loop also paused before capturing anything: on a fresh shm
last_viewed is 0, so the first iteration paused a primed camera and no initial
image was ever written for the console thumbnail. The GetLastWriteIndex()
guard that prevented this had been removed because Pause() clobbering the
index made it cycle Pause/Play.

Leave last_write_index alone in Pause() and restore the guard so capture
continues until one image has been written. The index then stays valid, so the
pause is stable and mode=single serves the last captured image.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-09-11 20:35:35 -04:00
Isaac ConnorandClaude Opus 5 ca34c4cec5 fix: retry the encoder open once a previous event has released its own
A hardware encoder has a fixed number of sessions. When one event ends and
the next begins immediately, the outgoing event's encoder is torn down on
close_event_thread, so for a moment both hold a session and the new one is
refused. That is a race against a teardown already in flight, not a real
capacity limit, and it currently costs the recording its encoding.

VideoStore::open now waits for an in-flight close before giving up: if no
encoder would open and there was a close to wait for, it joins that close and
tries once more. It only serialises when it has to, and only when there was
something to wait for. If the retry also fails the passthrough fallback still
catches it.

Most of the diff in zm_videostore.cpp is indentation: the codec loop is
unchanged and simply moved into a lambda so it can be run twice. It was
already safe to re-run -- each iteration parses its own options dictionary,
because opening destroys it, and frees its context on failure.

The rest is the threading this needs. close_event_thread was reachable from
two threads with no lock of its own: closeEvent() on the analysis thread joins
it and assigns a new one, and Pause() on the capture thread joins it twice.
That is a data race today, before any of this. It now has
close_event_thread_mutex, and all four accesses take it, including the new
Monitor::WaitForEventClose.

No lock cycle: WaitForEventClose takes only that mutex, and the thread it
joins takes no Monitor lock at all -- Event's destructor reaches Monitor only
through Substitute and EventPrefix, neither of which locks, and its database
work goes through the queue's own mutex. So a caller holding the event lock
cannot deadlock against a caller holding this one. Pause() takes it after
closeEvent() returns rather than around the call, which would self-deadlock.

Suite unchanged at 12171 assertions in 133 cases, and clean under
ThreadSanitizer with no warnings -- though that is weak evidence for this
particular change, since nothing in the suite drives Monitor's event close
path. The retry itself is still unexercised: provoking it wants two events
back to back on a monitor whose encoder has a session limit.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_015Y6FieTwEXuLhhR4e2yiax
2026-09-07 12:20:44 -04:00
singhharsh1708 d3b63386d2 refactor: drop the stale commented-out copy of load_monitor_sql 2026-09-06 11:47:01 +05:30
Isaac Connor 96a8d09ce7 Merge pull request #5088 from singhharsh1708/fix/3570-frameskip-control
refactor: remove the FrameSkip control and its unread member
2026-09-03 21:34:47 -04:00
Isaac Connor 73c9d70895 Merge remote-tracking branch 'upstream/master' 2026-09-03 18:20:30 -04:00
Isaac ConnorandClaude Opus 5 13082ce09b fix: stagger Monitor_Status writes so a mass restart doesn't sync them
last_status_time was never initialised, so it sat at the epoch and every
monitor's first UpdateFPS() saw a huge elapsed time and wrote its
Monitor_Status row immediately. The period is fixed, so from then on they
stayed in lockstep: on a site with 161 monitors the rows were only landing on
12 distinct seconds of the minute, peaking at 21 monitors writing within the
same second, against the ~2.7 you would get from an even spread.

Nothing re-randomises the offset once they are synchronised, so every restart
of the capture daemons - planned, or recovering from an incident - drops the
whole herd onto the smallest, hottest table in the schema at the moment the
system is least able to absorb it.

Phase the first write by monitor id. That spreads the writes over the update
interval and, unlike a random offset, gives the same monitor the same slot
across restarts instead of re-clustering. Name the interval while touching it;
it was a bare 10 at its only use.

Note this path is not ZM_STATS_UPDATE_INTERVAL, which only paces zmstats.pl -
Monitor::UpdateFPS() has always used its own hardcoded 10 second period.

Tested: c++ -std=c++17 -Wall -Wextra -fsyntax-only on zm_monitor.cpp, clean.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01JkE45gkMjnkTiJiUySbe7V
2026-09-03 17:19:04 -04:00
Isaac ConnorandClaude Opus 5 2890924a17 fix: guard analysis_image before overlaying alarmed zones fixes #5092
A preclusive zone is the one zone type that ends a frame marked Alarmed()
while the frame score is zero. DetectMotion() checks preclusive zones first
and, when one alarms, deliberately clears both the alarm flag and the score
before skipping the active/inclusive/exclusive loops entirely, so it returns
0 via "return score ? score : alarm".

Since the analysis_image allocation became conditional on a non-zero motion
score (refs #4996), that combination leaves packet->analysis_image null while
the zone loop below still finds zone.Alarmed() true and a non-null
zone.AlarmImage() -- Zone::CheckAlarms allocates its mask buffer
unconditionally, and preclusive zones skip the type < PRECLUSIVE block that
would have replaced it. Overlay() then dereferences null on its first line.

Reproduced on a live camera: the analysis thread faults 147us after the
preclusive zone alarms, at fault address 0x40, which is the offset of
Image::width.

  #0  Image::Overlay (this=0x0, image=...) at zm_image.cpp:2009
  #1  Monitor::Analyse (this=0x...) at zm_monitor.cpp:2380
  #2  AnalysisThread::Run () at zm_analysis_thread.cpp:35

Guarding the dereference keeps the intent of #4996: a zero-score frame is
not saved as an alarm frame, so there is nothing for the overlay to land on.
Allocating whenever any zone is alarmed would instead reintroduce the
per-frame analysis JPEG churn that #4996 removed.

The sibling call site in AnalyseFrame() already guards this way.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01QshidF3mzoCWgpehm4iCJ3
2026-09-02 20:49:50 -04:00
singhharsh1708 58ea7e3bb5 refactor: remove the FrameSkip control and its unread member refs #3570 2026-09-02 20:10:36 +05:30
Isaac Connor 5f4304c772 refactor: redesign C++ config to use name-based lookup with compiled-in defaults
Replace numeric ID-based config system with name-based lookup using
std::unordered_map. Config entries now have compiled-in default values,
and only rows where Value != DefaultValue are loaded from the database.
This eliminates the fragile dependency on sequential ID numbers that
required DB regeneration whenever a config entry was added.

The config generator (zmconfgen.pl) now produces three macros:
- ZM_CFG_DECLARE_LIST: declares Config struct members
- ZM_CFG_DEFAULTS_INIT: initializes members to compiled-in defaults
- ZM_CFG_MAP_INIT: registers name-to-member bindings for DB loading

Only daemon-relevant config entries (137 of 245) are included in the
C++ header; web-only settings (WEB_H_*, WEB_M_*, WEB_L_*, skin
defaults, etc.) are excluded.

Also fixes two pre-existing bugs exposed by removing numeric #defines:
- ZM_WATCH_MAX_DELAY was used as Seconds(139) instead of the actual
  config value (the 139 was the config table row ID, not seconds)
- ZM_OPT_USE_AUTH evaluated as if(8) (always true) instead of
  checking the actual auth setting

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
(cherry picked from commit 86d4a8e5f0)
2026-08-29 14:01:25 -04:00
Isaac Connor 2c9fc9a493 fix: use _exit instead of std::quick_exit after failed exec
std::quick_exit does not exist on OpenBSD, which is why the openbsd
branch replaced these calls with std::abort(). abort() raises SIGABRT,
so the child dumps core and the parent's wait status reports a signal
death for what is just a failed exec.

Both call sites are in a forked child whose execl/execlp failed. _exit
is POSIX, exists on OpenBSD, and is what a child in that state should
call: no atexit handlers, no flushing of stdio buffers inherited from
the parent.

Build: cmake --build . --target zmc -> clean, no warnings.
2026-08-15 21:49:33 -04:00
Isaac ConnorandClaude Opus 5 a5cd44df35 fix: map deprecated YUVJ pixel formats on the swscale output side fixes #5037
A monitor whose source signals full range (Dahua h264) decodes to
AV_PIX_FMT_YUVJ420P, and Monitor passes that format through to shared memory
unchanged. When zms scales such a frame for montage or console thumbnails,
SWScale::Convert mapped only the input format through fix_deprecated_pix_fmt()
and handed the still-deprecated YUVJ format to swscale as the destination, so
libswscale logged

  deprecated pixel format used, make sure you did set range correctly

for every context it built. Watch view at 100% scale never hit it because
Image::Scale returns early when the dimensions already match.

Map deprecated formats on both sides in SWScale::Convert (both the buffer and
the AVFrame overload), in Image::Assign(AVFrame*), in
Monitor::setupConvertContext and in the LocalCamera conversion context.

Mapping the destination YUVJ format to its non-J equivalent makes swscale
default that side to limited range, which would compress full-range output.
Replace zm_sws_set_input_range() with zm_sws_set_ranges(), which takes the
original pre-fix formats for both sides and sets srcRange/dstRange accordingly.

Image::Assign(AVFrame*) now compares the mapped source and destination formats,
so a YUVJ420P frame into a YUVJ420P image takes the av_image_copy fast path
instead of running through swscale.

Image::Scale built a fresh SWScale, and therefore a fresh sws context, on every
call. That is a full sws_init_context per scaled frame per stream, and it is
what turned the warning into a per-frame flood rather than a one-off. Reuse a
thread_local SWScale; sws_getCachedContext re-inits itself when the geometry
changes.

Tests: zm_swscale_range.cpp installs an av_log callback and asserts that
SWScale::Convert with a YUVJ destination and Image::Scale on a YUVJ420P image
emit no deprecated-format message, plus a luma check that the range handling
still survives the mapping.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01NDhTBPj9xEaT52pRmAufaP
2026-08-05 17:44:37 -04:00
Isaac Connor ad77e89341 Merge pull request #4894 from IgorA100/patch-673172
Fix: keyframe-only decoding restoring mode=single and snapshot generation
2026-07-22 21:40:16 -04:00
Isaac ConnorandCopilot Autofix powered by AI ff7fae4a00 Potential fix for pull request finding
Co-authored-by: Copilot Autofix powered by AI <175728472+Copilot@users.noreply.github.com>
2026-07-22 21:37:19 -04:00
Isaac Connor fbec4546c5 Only alocate analysis_image if we have a motion score and hence might want an analysis jpg. Fixes #4996 2026-07-22 20:04:24 -04:00
IgorA100 1d558c68ff Optimizations and improvements
- Moved decoder_requires_next_packet = false to the end of phase 5
- Moved decoder_requires_next_packet = true before decoding duration analysis, not after sending the packet
- ​​Changed debug information
- No longer uses waiting_for_followup. Analyze only decoder_requires_next_packet
- ​​Clear flag when packet->transfer_hwframe(context) < 0 (i.e., error)
2026-07-22 20:31:36 +03:00
IgorA100 ffc3fb7dd7 Don't use startup_keyframe_packet
Restore the decoder_requires_next_packet flag to be set immediately after decoder_queue.pop_front(), rather than at the end of phase 5.
2026-07-21 20:08:12 +03:00
IgorA100 dde54be051 Use the startup_keyframe_packet class variable instead of keyframe_startup 2026-07-21 18:49:17 +03:00
IgorA100 3ed88ea88b Let's move the reset of the decoder_requires_next_packet flag to the end of the fifth phase 2026-07-21 17:38:34 +03:00
IgorA100 02c1a2b547 Update zm_monitor.cpp 2026-07-21 17:12:03 +03:00
IgorA100 1592ab8629 Move the keyframe_startup flag setting before front_packet->receive_frame and do not parse packet->keyframe 2026-07-21 17:01:35 +03:00
IgorA100 04d3a15b18 Undo the last three commits. (zm_monitor.cpp) 2026-07-21 16:36:07 +03:00
IgorA100 7be510f678 Update zm_monitor.cpp 2026-07-21 12:56:48 +03:00
IgorA100 6b3f785b51 Moving the keyframe_startup definition to phase 1 2026-07-21 12:42:42 +03:00
IgorA100 829b700137 Set the decoder_requires_next_packet flag immediately before "packet->send_packet(context)" 2026-07-21 11:50:22 +03:00
IgorA100 bfa2ee1c2b Changed the logic of warnings when decoding keyframes (zm_monitor.cpp) 2026-07-21 11:14:05 +03:00
IgorA100 e3ec73a6cf Update zm_monitor.cpp 2026-07-21 00:41:43 +03:00
IgorA100 e7dcf296cf We use the auxiliary variable "waiting_for_followup" to generate a warning, because "decoder_requires_next_packet" may change at any time due to the receipt of a decoded frame (zm_monitor.cpp) 2026-07-20 23:19:08 +03:00
IgorA100 582e68501a Set the decoder_requires_next_packet flag after the decoder receives a packet
Optimizing debug information logging
Relax slow send_packet warning threshold while decoder requires follow-up packets
2026-07-20 20:51:34 +03:00
IgorA100 d5e8aa278e Merge branch 'master' into patch-673172 2026-07-20 00:25:10 +03:00