Commit Graph
210 Commits
Author SHA1 Message Date
Isaac ConnorandClaude Opus 5.5 fc8791e52a fix: wait for the UI's next event in zms and encode any frame safely refs #4186
Gapless playback over zms follows the next/prev events the event view
sends with CMD_SET_EVENT. Reviewing the first version found these gaps:

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

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

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-04 19:32:53 -05:00
Isaac ConnorandClaude Opus 5.5 d9a629bcda fix: access SharedData fields as relaxed atomics fixes #5238
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>
2026-11-03 08:47:05 -05:00
Isaac Connor 7f82b7db9f Merge pull request #5264 from nabbi/fix/b78-zms-paused-keepalive
fix-low: send one paused keepalive per command in buffered live playback
2026-10-16 19:02:32 -04:00
Isaac Connor 4aca8852cd Merge pull request #5268 from nabbi/fix/b80-zms-step-wrapped
fix-low: stay on the newest frame when stepping forward in wrapped buffered playback
2026-10-14 17:54:38 -04:00
Isaac Connor 3ecadeb66d Merge pull request #5231 from nabbi/fix/b71-zms-command-thread-race
fix-low: stop the nph-zms command thread racing runStream on frame bookkeeping
2026-10-13 18:08:22 -04:00
Nic BoetandClaude Opus 5.5 1386625113 fix: clear got_command before the paused keepalive is sent
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>
2026-10-12 20:38:38 -05:00
Nic BoetandClaude Opus 5.5 e44c59afc5 fix: stay on the newest frame when stepping forward in wrapped buffered playback
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>
2026-10-12 15:51:46 -05:00
Nic BoetandClaude Opus 5.5 f27489aa7f fix: send one paused keepalive per command in buffered live playback
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>
2026-10-12 15:47:32 -05:00
Isaac Connor 233a158282 Merge pull request #5227 from nabbi/fix/b74-zms-raw-frame-boundary
fix: write the multipart boundary for stored JPEGs sent by nph-zms
2026-10-12 15:16:04 -04:00
Isaac Connor c53ce77132 Merge pull request #5225 from nabbi/fix/b73-zms-slowfwd-unwritten
fix: don't step nph-zms buffered playback onto an unwritten slot
2026-10-12 15:06:27 -04:00
Nic BoetandClaude Opus 5.5 22d02ce066 fix: stop the nph-zms command thread racing runStream on frame bookkeeping
checkCommandQueue runs processCommand on its own thread, which read
`now` and frame_count and wrote last_frame_sent (CMD_PAUSE) and
got_command while the streaming loop writes or reads them.
ThreadSanitizer reports these as data races (zm_monitorstream.cpp
processCommand and runStream's got_command read against the command
thread, and checkCommandQueue's `now` read against EventStream::runStream).

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

fixes #5230

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-12 10:55:01 -05:00
Nic BoetandClaude Opus 5.5 2e1c97b100 fix: write the multipart boundary for stored JPEGs sent by nph-zms
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>
2026-10-12 10:50:53 -05:00
Nic BoetandClaude Opus 5.5 ae36a306dc fix: don't step nph-zms buffered playback onto an unwritten slot
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>
2026-10-12 10:48:50 -05:00
Nic BoetandClaude Opus 5.5 c9a5964254 fix: take the paused image on the first loop pass that sees nph-zms paused
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>
2026-10-12 10:46:46 -05:00
Nic BoetandClaude Opus 5.5 f7306fe9b9 fix: don't send a missing paused image when the zoom changes in nph-zms
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>
2026-10-12 09:42:09 -05:00
nicandClaude Opus 5.5 596fb5ab70 fix: free a stream's monitor and playback buffer when nph-zms exits (#5186)
* fix: free a stream's monitor and playback buffer when nph-zms exits

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

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

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

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

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

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

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

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

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

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

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-06 17:34:09 -04:00
Isaac ConnorandClaude Opus 5 f46cc1bcd8 fix: release held frames and set the terminate flag on every stream exit
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
2026-09-12 12:44:55 -04:00
Isaac ConnorandClaude Opus 5 2958b1047a fix: let a stopped zms notice a departed client and honour its ttl
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>
2026-09-12 12:44:54 -04:00
Isaac Connor bb1b3d8dbe Take Importance into account when logging about timing out waiting for capture in monitorstream 2026-08-18 22:09:14 -04:00
Jash f5cfbcd54c fix: make MonitorStream playback state shared with the command thread atomic fixes #4939 2026-08-16 16:46:47 +05:30
Isaac ConnorandClaude Opus 4.8 7cd4be5cfb feat: add nph-zms memory diagnostics refs #5006
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>
2026-07-26 09:48:44 -04:00
Isaac Connor 9424399ed0 Improve timed out log message to add ttl 2026-07-11 12:43:37 -07:00
Isaac Connor 356f22c9cc Warning=>Debug 2026-06-25 17:30:35 -04:00
SteveGilvarryandClaude Opus 4.8 629842c938 fix: start zms command processor after buffer state is initialised refs #4936
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>
2026-06-18 08:56:11 +10:00
Steve GilvarryandClaude Opus 4.8 dc4cf32a63 fix: guard zms buffer_level against zero buffer count refs #4936
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>
2026-06-18 08:21:29 +10:00
Isaac ConnorandClaude Opus 4.8 bc15782474 fix: skip final stream sleep when zm_terminate is already set
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>
2026-06-14 19:11:51 -04:00
Isaac ConnorandClaude Opus 4.8 a36375585c refactor: make zm_terminate a std::atomic<bool>
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>
2026-06-14 19:11:51 -04:00
Isaac ConnorandClaude Opus 4.7 6765962737 fix: nullptr-safe pixfmt name; route GetImage/getSnapshot through ReadShmFrame (PR #4788)
- 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>
2026-05-31 09:22:09 -04:00
Isaac Connor a7c3fb7ce6 Merge branch 'master' into fix/avpixelformat-respin 2026-05-21 21:11:40 -04:00
copilot-swe-agent[bot]andconnortechnology 03801a9e23 fix: reset step/send_twice in MonitorStream CMD_STOP; reset stopped in EventStream.js lifecycle
Agent-Logs-Url: https://github.com/ZoneMinder/zoneminder/sessions/8c14d453-7815-44fd-956a-0cda13c218f9

Co-authored-by: connortechnology <925519+connortechnology@users.noreply.github.com>
2026-05-17 12:37:39 +00:00
copilot-swe-agent[bot]andconnortechnology 1bce09f4e8 fix: address review feedback - endian decode, send_twice init, setLastViewed, curr_frame_id gating
Agent-Logs-Url: https://github.com/ZoneMinder/zoneminder/sessions/b457dcf6-616f-4df9-bc28-76640bf5dd39

Co-authored-by: connortechnology <925519+connortechnology@users.noreply.github.com>
2026-05-17 03:29:41 +00:00
copilot-swe-agent[bot]andconnortechnology 1be352c790 fix: add stopped state for CMD_STOP, fixing paused=true response bug
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>
2026-05-06 01:58:48 +00:00
Isaac ConnorandClaude Opus 4.7 c8d8cc384a feat: SHM cross-process format consistency via per-slot AVPixelFormat
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>
2026-05-03 13:03:53 -04:00
Isaac Connor 8b4c93ea1f fix: bail from MonitorStream::runStream when monitor failed to load
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.
2026-04-30 18:11:55 -04:00
Isaac ConnorandClaude Opus 4.6 2526b9b85e feat: install SIGPIPE handler in zms for clean browser-disconnect shutdown
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>
2026-04-18 09:53:23 -04:00
Isaac ConnorandClaude Opus 4.6 4df2bf4f0b feat: add analysis_image field to stream status for client-side verification
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>
2026-03-08 15:44:49 -04:00
copilot-swe-agent[bot]andconnortechnology 2dfb79975d fix: prevent segfault when MPEG stream codec fails to open
Co-authored-by: connortechnology <925519+connortechnology@users.noreply.github.com>
2026-03-05 02:15:08 +00:00
Isaac ConnorandClaude Opus 4.6 29541c9aa7 fix: prevent segfault in MonitorStream::processCommand from shared memory race
The command processor thread could crash dereferencing monitor->shared_data
or monitor->trigger_data while the main thread was in loadMonitor() calling
disconnect() which munmaps shared memory and nulls those pointers.

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

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-23 18:19:20 -05:00
Isaac Connor f90c4a4d35 Add timeout when waiting for zmc. Fixes 620 2026-02-11 22:35:00 -05:00
Isaac Connor 0f92ad79b0 Remove debug 2026-02-05 09:07:22 -05:00
Isaac Connor 45fe630677 Spacing and improve debug 2026-02-04 22:55:50 -05:00
Isaac Connor b64520649d Use std::shared_ptr to fix memory leak due to use of GetSnapshot and not freeing the returned packet. 2026-01-20 16:18:43 -05:00
Isaac Connor 47cc713eaa Re-enable analysis image viewing 2026-01-16 16:02:19 -05:00
Isaac ConnorandClaude Opus 4.5 2f73e0591d feat: add last_analysis_viewed_time tracking for analysis image viewers
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>
2026-01-16 10:13:23 -05:00
Isaac Connor adba371cd1 pause when we receive CMD_STOP 2025-08-07 14:39:04 -04:00
Isaac Connor 283b62a3bf Fix format string for size_t 2025-07-19 16:58:29 -04:00
Isaac Connor 4757d711ef Change various cases of int img_buffer_size to size_t 2025-07-19 14:18:32 -04:00
Isaac Connor 14d6234e57 Make frame send time a debug 2024-12-09 12:26:51 -05:00
Isaac Connor 42914b63c0 Remove unneeded initialisations and group command processor code together 2024-10-20 18:04:12 -04:00
Isaac Connor bc1a7af1fc Add analysing to monitor status stream 2024-10-02 09:30:03 -04:00