zmc drops the Options field when av_dict_parse_string() fails, so the
camera runs without them. Raise the message from Warning to Error and say
that options are key=value pairs, not command line flags.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Capture() returned early for packets of streams it doesn't use and for
pts/dts jumps before arming av_packet_guard. Before FFmpeg 7,
av_read_frame() resets the packet it is given without unreferencing it,
so each of those packets leaked. A camera that sends a track ZoneMinder
doesn't use (a second audio track, ONVIF metadata) leaked every packet
of it.
refs #4860
A camera that keeps rebooting repeatedly fails avformat_find_stream_info
or reports a video stream with no width/height. Log both at a level
adjusted by the monitor's Importance so Less/Not important monitors
stop flooding the logs with errors and warnings.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
FfmpegCamera opened a decoder for the audio stream, stored it, exposed it
through Camera::getAudioCodecContext() and Monitor::GetAudioCodecContext(), and
freed it in Close(). Nothing decoded a single frame with it.
Both things that decode audio build their own from the stream's codecpar:
VideoStore::open() for transcoding to aac, and AudioDetector::Open() for
levels. The previous commit removed the last place the camera's context was
even passed, and it had been ignored there too.
So there is no audio decoder to move to the monitor, only one to stop opening.
The camera keeps finding the audio stream -- that is discovery, and packet
routing and timestamps need it -- and the secondary-input branch still adopts
mAudioStream from FFmpeg_Input, just not the context that came with it, which
FFmpeg_Input owns and uses itself.
Camera now holds no codec context of any kind. Between this and the video move,
a camera finds streams and produces packets, and whoever needs pixels or
samples opens their own decoder.
Verified end to end rather than by reading, on a camera that really does carry
audio: with RecordAudio on and the encoder transcoding, the recorded file has
both an hevc video track and an aac audio track over 848 frames. 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
With the monitor opening the decoder, the camera's hwaccel_name,
hwaccel_device, hw_device_ctx and hw_pix_fmt are written and never read, and
the two hwaccel arguments to its constructor are passed only to be stored.
Remove them rather than leave fields that look like they still configure
something -- the monitor reads the same settings straight from its own members.
The re-arm comment in Close() described setting use_hwaccel back to true so a
transient hardware failure would not pin the monitor to software for the life
of the process. That flag is gone, but the behaviour is not: OpenDecoder()
builds a fresh decoder on every PrimeCapture(), so a reconnect retries hardware
decoding by construction. The reasoning moved there with it.
Close() keeps freeing mVideoCodecContext. It is a base-class member that an
Ffmpeg camera no longer sets, but RemoteCameraRtsp does, and the base is where
that belongs.
Verified on hardware again after the removal: vaapi still negotiates and 652
frames decoded into a recorded event 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
The camera's job is to produce packets; decoding belongs with the thread that
does it. FfmpegCamera opened the video decoder and handed the context out, so
Monitor::Decode() ran against a pointer whose lifetime the camera controlled.
PrimeCapture() already carried a comment about the consequence: the decoder
thread had to be stopped and joined before re-priming, because
camera->PrimeCapture() frees that context and builds another, and a decoder
running against the dying one is unsafe.
Monitor::OpenDecoder() now opens it, after camera->PrimeCapture() has produced
the stream to decode from, and Monitor::CloseDecoder() releases it where the
decoder thread has already been joined -- at the top of PrimeCapture and in
Pause(). The monitor holds the hw device reference and the hw pix fmt storage
alongside it, which is what the context's opaque pointer refers to, so the
lifetime is now one object's business rather than split across two.
Two cases deliberately do nothing:
Cameras that hand over images rather than packets -- local, vlc, vnc -- have
no video stream, so there is nothing to open.
RemoteCameraRtsp opens its own decoder and decodes through it.
GetVideoCodecContext() falls back to the camera's for that one rather than
running a second decoder over the same stream. That capture method is
deprecated and goes in 1.41, and this branch cannot be tested here, so it is
left as it is rather than changed blind.
Verified on hardware: an rtsp hevc monitor with DecoderHWAccelName=vaapi still
negotiates through the monitor-owned path ("Trying hwdevice vaapi", "Using
vaapi hardware decoding for hevc") and decoded 752 frames into a recorded
event 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
The mismatch Debug compared the monitor's configured size against the decoder
context's. Both hold the same numbers -- the context is filled from the
stream's codecpar a few lines earlier -- but the stream is the thing actually
describing what the camera sends, and reading it here means the check no longer
needs a decoder to have been opened.
That matters for the next step: this was the camera's last use of the decoder
context for anything other than handing it out.
Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_015Y6FieTwEXuLhhR4e2yiax
Second piece of groundwork for letting the decoder thread own decoding. The
whole decoder setup -- codec selection, context allocation, thread count,
option defaults and overrides, hwaccel negotiation, avcodec_open2 and the
fallback -- sat as 184 lines inside FfmpegCamera::OpenFfmpeg(), reachable only
by a camera. Monitor cannot call it there, so the move would have meant
copying it.
Lift it to open_video_decoder() in zm_ffmpeg.cpp, leaving the camera a call
and the null check. No behaviour change: the body is the same code with camera
members replaced by parameters.
hw_pix_fmt and hw_device_ctx are taken by reference and keep their names, which
is not only convenience. The returned context stores &hw_pix_fmt in ctx->opaque
and get_hw_format dereferences it on every format negotiation, so the storage
has to outlive the context. A reference parameter says that at the signature
and makes a temporary impossible; the header says why.
Two things the extraction had to account for:
opts was declared once for the whole of OpenFfmpeg and shared with the input
open. It is freed unconditionally before the decoder block and nothing
repopulates it in between, so a fresh local is equivalent. The
AVDictionaryEntry it scanned with was shared the same way and is now local
too.
use_hwaccel was a camera member but only ever read at the gate inside this
block, cleared when a candidate's hwaccel failed so the next codec attempt
would not retry it. That is entirely internal to the open, so it is a local
now and the member is gone rather than left looking like it still gates
something.
Verified on hardware rather than by reading: an rtsp hevc monitor with
DecoderHWAccelName=vaapi still negotiates ("Decoder hevc supports type vaapi",
"Using vaapi hardware decoding for hevc", now logged from zm_ffmpeg.cpp) and
decoded 749 frames into a recorded event with no errors.
Build clean with no new warnings; suite 147 cases / 12531 assertions.
Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_015Y6FieTwEXuLhhR4e2yiax
Groundwork for moving decoding out of the camera and into the decoder thread.
The parsing of DecoderHWAccelName sat inline in FfmpegCamera::OpenFfmpeg(),
where nothing could test it, and the ai_server branch has a second copy of the
same logic in its Monitor-side decoder open. Moving the decoder without pulling
this out first would carry the duplication across rather than end it.
No behaviour change: same iteration over the types this build offers, same
comma-separated priority list, same warn-and-skip for a name libavutil does not
know, same order.
Being a free function it can now be tested, which it could not be before. The
cases covered are the ones an operator's setting actually runs into -- a single
name, a priority list, spaces around the commas, a typo among good entries,
empty entries -- asserted against whatever device types the host reports rather
than against a fixed list, so the test travels. This host offers seven, so no
section skipped for want of data.
Confirmed non-vacuous by mutation: dropping TrimSpaces fails one case, and
accepting an unknown name instead of skipping it fails two.
Build clean with no warnings; suite 147 cases / 12531 assertions.
Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_015Y6FieTwEXuLhhR4e2yiax
The Options field was a single line text input, so a list of options had to
be typed as one comma separated run. Make it a textarea, sized to the number
of entries it already holds, so each option can go on its own line.
Nothing needs to parse this: both consumers already take a set of separator
characters, they were just never given the newlines.
av_dict_parse_string() (Ffmpeg) and Split() (Libvlc) both skip empty
entries, so a blank line, crlf, or a trailing newline all work, and comma
separated values keep working unchanged.
The separator set is a named constant rather than a literal at each call
site so the tests exercise the value the cameras actually pass - with a
literal they would keep passing if a call site were reverted. Verified by
setting it back to "," which fails both test cases.
use_hwaccel was set to false on the first failure and never restored, so
the decision survived every later PrimeCapture(). A camera that came up
while the GPU was still resetting, or on a host where zmc won the race
against the graphics driver, stayed on software decoding until someone
restarted the process - at roughly one extra CPU core per stream.
Close() already tears down hw_device_ctx and is the entry point of every
reconnect, so reset the flag there and let the next open try again. A
GPU that is genuinely gone simply fails again and now says so.
refs #4984
The fallback path logged at Debug(1), which a default install does not
write, so a monitor that lost hardware decoding looked identical to one
that never asked for it. The message is also emitted once, at capture
start, so the only remaining symptom was a doubled load average.
Restore the visibility that existed before the auto-detection work: if
DecoderHWAccelName names specific hwaccels and none of them can be used,
that is a warning. "auto" keeps logging at Debug, since probing and
finding nothing is the expected outcome there rather than a fault.
refs #4984
Extract the "use whatever decoder ffmpeg provides" logic from
FFmpeg_Input into a shared open_fallback_decoder() and call it from
FfmpegCamera, which had lost the fallback: its generic path only ran
inside the preferred-codec loop, so an empty get_decoder_data() result
failed outright instead of trying the codec's default decoder.
The dec_codecs table stays a preference list; a codec present in the
ffmpeg build but absent from the table (e.g. libopenh264 for H264) now
decodes via the fallback instead of requiring a hard-coded entry.
Add tests/zm_ffmpeg_fallback.cpp covering the fallback with a codec not
in dec_codecs (mpeg2video), the optional codec_out argument, and the
no-decoder case.
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
Follow-up to #4984 as suggested by @connortechnology: besides "auto"
(probe everything) and a single device-type name, DecoderHWAccelName now
accepts a comma-separated priority list such as "cuda,vaapi" - each
name is tried in order and the first type the decoder supports and whose
device can be created wins, with the existing transparent software
fallback when none do. A single name is the one-element case and behaves
exactly as before. Unknown names are skipped with a Warning. Whitespace
around commas is ignored.
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
DecoderHWAccelName previously required naming a specific device type and
only fell back to software if creating that one device failed. This adds
an "auto" value that iterates over every hwaccel type libav exposes and,
for each, checks that the decoder advertises a matching hw config and
that the device can be created — using the first that works and falling
back to software when none do. Explicit names (e.g. "vaapi", "cuda")
behave as before. Makes hardware decoding safe to enable out of the box
across unknown hardware.
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Add a "realtime=1" (alias "re=1") ffmpeg input option, modeled on the
existing "loop" option and equivalent to ffmpeg's -re flag. When set on a
file source, FfmpegCamera throttles packet delivery to the rate implied by
the stream timestamps instead of reading the file as fast as possible.
The option is parsed out of the ffmpeg Options string in OpenFfmpeg and
consumed so it is not passed to the demuxer or decoder. Capture() anchors
wall-clock time to the first delivered packet and sleeps before each
subsequent packet so it is not delivered ahead of schedule. Pacing uses dts
(monotonic in read order) with a pts fallback, runs after the existing
drop/jump filters, and re-anchors on backward jumps or gaps beyond a 10s cap
to avoid stalling on a discontinuity. Works alongside loop, whose
offset-adjusted timestamps stay monotonic across restarts.
The pacing decision is factored into a pure ComputeRealtimePace() function
and unit-tested in tests/zm_ffmpeg_camera.cpp (8 cases covering full/partial
interval waits, behind-schedule, on-schedule, backward jump, over-cap, and
the cap boundary).
Ported from the ai_server branch onto master's OpenFfmpeg structure.
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
When an ffmpeg monitor reads a seekable file source (e.g. file:///x.mp4)
and reaches the end, it previously failed and reconnected. Add a loop
mode, enabled with loop=1 in the monitor Options, that seeks back to the
start and continues instead.
Packet pts/dts are shifted by a per-stream absolute offset recomputed on
each loop (last emitted dts + frame duration - stream start_time) so
timestamps stay monotonically increasing for analysis and recording. The
loop option is consumed before passing options to ffmpeg (both the demuxer
in OpenFfmpeg and the decoder), and non-seekable inputs fall through to the
normal reconnect path.
Ported from the ai_server branch onto master's OpenFfmpeg structure.
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
The field was assigned in three branches of the constructor (always to
the same value as Camera::pixelFormat) and never read anywhere. Unlike
LocalCamera, FfmpegCamera doesn't run a sws_scale step at the Camera
layer — libavcodec hands frames to the pipeline directly — so there's
no separate capture-vs-image format distinction to track.
Drop the redundant assignments and the member declaration. The
canonical camera-side format is now exclusively Camera::pixelFormat
(via Camera::PixelFormat()).
refs #4788
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
Two Debug log sites in the hwaccel selection loop still called
av_get_pix_fmt_name directly. AV_PIX_FMT_NONE is a real possibility for
config->pix_fmt during the loop (the search may hit the sentinel) and
for hw_pix_fmt before find_fmt_by_hw_type returns a match. Route both
through zm_get_pix_fmt_name so a nullptr return can't be passed to %s.
refs #4788
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
- Added zm_get_pix_fmt_name() in zm_pixformat.h: av_get_pix_fmt_name()
returns nullptr for unknown formats (including AV_PIX_FMT_NONE), and
passing nullptr to %s is undefined and can crash. Wraps with an
"unknown" fallback. Replaced the five raw uses flagged by review
(RemoteCameraRtsp/FfmpegCamera/VncCamera/LocalCamera constructors and
MonitorStream::sendFrame's Debug log) with the wrapper. Each can hit
AV_PIX_FMT_NONE before the first frame or via an unexpected
(colours, subpixelorder) pair.
- Monitor::GetImage and Monitor::getSnapshot now route the slot read
through ReadShmFrame so the per-slot AVPixelFormat zmc recorded is
adopted on image_buffer[index] before its bytes are interpreted.
Without this, the JPEG encode in GetImage and the ZMPacket returned
by getSnapshot would interpret SHM bytes using the placeholder format
set at attach time and produce garbled output when the slot's actual
format differs (the contract previously relied on callers calling
ReadShmFrame themselves). getSnapshot/GetTimestamp drop const since
ReadShmFrame mutates image_buffer[index]; callers in this codebase
already use a non-const Monitor pointer.
- Monitor::connect: updated the misleading "+64 bytes reserved" comment
to match the actual reservation of 63 + (alignof(AVPixelFormat) - 1).
refs #4788
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
Six format-dispatch fallbacks were still printing only the legacy
`colours` value, but the dispatch in each spot is now keyed off
pixelFormat/imagePixFormat. With the GRAY8/YUV420P alias collision
(both colours=1) the legacy value frequently doesn't identify the true
format, so a "Unexpected colours: 1" log on a misroute is useless.
Updated each Panic to include the AVPixelFormat enum value and its
human-readable name (via av_get_pix_fmt_name), plus the legacy
(colours, subpixelorder) for context:
- RemoteCameraRtsp constructor
- FfmpegCamera constructor
- VncCamera constructor
- LocalCamera conversion-selection branch
- VideoStream::SetupCodec mpeg helper
- Image::Delta unknown-format fallback
refs #4788
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
ZM_COLOUR_GRAY8, ZM_COLOUR_YUV420P, and ZM_COLOUR_YUVJ420P were all
defined to 1, making format identification via colours ambiguous.
LocalCamera misidentified YUV420P as GRAY8, causing V4L2 MJPEG cameras
to decode to grayscale via expensive sws_scale conversion.
Replace the legacy ZM_COLOUR_*/ZM_SUBPIX_ORDER_* integer pair with
AVPixelFormat as the single source of truth for pixel format dispatch:
- Add src/zm_pixformat.h with central format helpers:
zm_pixformat_from_colours, zm_colours_from_pixformat,
zm_bytes_per_pixel, zm_db_colours_to_pixformat, zm_is_rgb32,
zm_is_rgb24, zm_is_yuv420
- Add AVPixelFormat pixelFormat member + PixelFormat() accessor to Camera
- Add PixFormat() accessor to Image, delegate AVPixFormat methods
to shared helpers
- Migrate all ~100 format dispatch comparisons in zm_image.cpp,
zm_local_camera.cpp, zm_ffmpeg_camera.cpp, zm_remote_camera_rtsp.cpp,
zm_libvlc_camera.cpp, zm_libvnc_camera.cpp, zm_monitor.cpp,
zm_mpeg.cpp from colours/subpixelorder checks to imagePixFormat/
AVPixelFormat checks
- Deprecate GetFFMPEGPixelFormat, delegate to zm_pixformat_from_colours
- Fix DeColourise bug: imagePixFormat was not updated to GRAY8
- Deprecate ZM_COLOUR_* and ZM_SUBPIX_ORDER_* constants in zm_rgb.h
- Add deprecation notice on Monitor.Colours web UI dropdown
- Add 13 Catch2 test cases (105 assertions) for format mapping helpers
refs #4735
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
libavcodec's avcodec_alloc_context3 leaves thread_count at 1, so
software 1080p H.264 decoding hits ~60ms/frame and saturates a core
per camera. Default to 2 frame-threads, which roughly halves per-
frame decode time without oversubscribing systems with many cameras.
User can still override via thread_count in monitor Options (0 = let
ffmpeg auto-detect based on CPU count).
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
The existing PTS backward jump check in FfmpegCamera::Capture() does not
catch cases where DTS jumps back significantly (e.g. stream restarts,
encoder resets) while PTS may remain unaffected. This causes the
VideoStore to spend minutes forcing DTS monotonicity on every packet via
the write_packet fixup path, flooding logs with warnings.
Add per-stream DTS tracking (mLastVideoDTS/mLastAudioDTS) and a backward
jump check mirroring the existing PTS check: if DTS jumps back more than
10 seconds, increment error_count and after 6 occurrences return -1 to
trigger capture reconnection.
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
Replace fragile string manipulation (hardcoded substr offsets) with
CxxUrl's Url parser for injecting mUser/mPass into mPath and
mSecondPath. Only applies credentials when the URL has no existing
auth info, preserving inline credentials on the secondary path.
Non-URL paths (e.g. v4l2 devices) are handled gracefully via
try/catch.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
When mSecondFormatContext is set but no audio stream was found during
PrimeCapture, mAudioStream is null. Dereferencing mAudioStream->time_base
causes a segfault (SIGSEGV at fault address 0x20). Add mAudioStream to
the condition check, consistent with the existing null guard on line 172.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
The nvidia-vaapi-driver would fail with "list argument exceeds maximum
number" when decoding HEVC because GPU surfaces were being held in the
packet queue after transfer, exhausting the VAAPI surface pool.
Changes:
- Transfer hw frames to software immediately in receive_frame() while
the VA context is still valid, then release the GPU surface
- Check hw_frames_ctx in needs_hw_transfer() to detect already-transferred
frames
- Remove extra_hw_frames and thread_count settings (not needed with
immediate surface release)
- Fix EAGAIN handling in send_packet to wait instead of busy-loop
Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
- Apply credentials to secondary stream URL in FFmpegCamera (was causing 401 Unauthorized)
- Add empty check for rtsp_second_path in RTSP2WebManager before applying credentials
- Replace unsafe sprintf pattern in Monitor::DumpSettings with std::string + stringtf
- Refactor Zone::DumpSettings to return std::string instead of writing to char buffer
- Add decimal precision to event duration debug output
Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
- Add null check after avformat_alloc_context() to prevent null pointer
dereference if allocation fails
- Fix incomplete error message that was missing the path parameter
Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>