Documentation
¶
Index ¶
- Constants
- func GenerateConfig(cameras []DiscoveredCamera) string
- func GrabThumbnail(rtspURL string, quality int) ([]byte, error)
- type Camera
- func (c *Camera) DetectURL() string
- func (c *Camera) DoorbellEnabled() bool
- func (c *Camera) FrameSize() int
- func (c *Camera) HasMotion() bool
- func (c *Camera) IsOnline() bool
- func (c *Camera) LastFrameTime() time.Time
- func (c *Camera) LastSnapshot() *image.RGBA
- func (c *Camera) LastSnapshotTime() time.Time
- func (c *Camera) LiveFrame() *image.RGBA
- func (c *Camera) Name() string
- func (c *Camera) PersistCrySnooze(until time.Time, persist func() error) error
- func (c *Camera) PresenceTracker() *PresenceTracker
- func (c *Camera) Reconnects() int64
- func (c *Camera) RecordURL() string
- func (c *Camera) SetTestFrame(img *image.RGBA)
- func (c *Camera) SetTestLastFrameTime(ts time.Time)
- func (c *Camera) SetTestOnDemand(onDemand bool)
- func (c *Camera) SetTestOnline(online bool)
- func (c *Camera) SetTrackName(trackID int, name string)
- func (c *Camera) SetZones(zones []Zone)
- func (c *Camera) SnapshotRGB24(dst []byte) (w, h int, ok bool)
- func (c *Camera) SnoozeCry(until time.Time) bool
- func (c *Camera) Start(ctx context.Context) <-chan struct{}
- func (c *Camera) Status() CameraStatus
- func (c *Camera) Zones() []Zone
- type CameraStartHook
- type CameraStatus
- type DetectionBox
- type DetectionFrame
- type DiscoveredCamera
- type Event
- type EventEnd
- type FaceEvent
- type Manager
- func (m *Manager) AddCamera(cfg config.CameraConfig)
- func (m *Manager) CameraStatuses() []CameraStatus
- func (m *Manager) ConfigureCry(model cry.Scorer, loadError string, cfg config.CryConfig)
- func (m *Manager) GetCamera(name string) *Camera
- func (m *Manager) IsStopped(name string) bool
- func (m *Manager) ListCameras() []string
- func (m *Manager) OnCameraStart(fn CameraStartHook)
- func (m *Manager) RegisterForTest(cam *Camera)
- func (m *Manager) RunningCameraDetectURLs() []string
- func (m *Manager) Start(ctx context.Context, stoppedCameras map[string]bool)
- func (m *Manager) StartCamera(ctx context.Context, name string) error
- func (m *Manager) StopCamera(name string) error
- func (m *Manager) SubmitDoorbellPress(cameraName string) (string, bool)
- type MotionActivity
- type OnvifEvent
- type OnvifEventSubscriber
- type OnvifEventType
- type PTZClient
- type PresenceEvent
- type PresenceKey
- type PresenceStatus
- type PresenceTracker
- func (pt *PresenceTracker) AllPresence() map[PresenceKey]ZonePresence
- func (pt *PresenceTracker) GetPresence(key PresenceKey) (present bool, lastSeen, lastChanged time.Time)
- func (pt *PresenceTracker) GetState(key PresenceKey) (PresenceStatus, time.Time)
- func (pt *PresenceTracker) Update(zoneMatches map[PresenceKey]bool, zones map[int]string) []PresenceEvent
- func (pt *PresenceTracker) UpdateObserved(inZone map[PresenceKey]map[int]bool, detected map[int]bool, ...) []PresenceEvent
- type StreamProfile
- type Zone
- type ZonePresence
Constants ¶
const ( CategoryAlert = "alert" CategoryDetection = "detection" )
Event categories set review/notification priority: alerts are noteworthy (people, animals, and vehicles that are actually traveling); detections are low-priority (a parked/stationary vehicle, including one re-detected after a restart). Consumers (MQTT/Home Assistant, the dashboard) use this to avoid alert fatigue without ever hiding an event.
const ( EventKindObject = "object" EventKindDoorbell = "doorbell" EventKindCry = "cry" )
Event kinds distinguish ordinary detection events from doorbell rings. A ring is injected directly into the event pipeline rather than produced by the detector, and is exempt from the per-(camera,label,zone) cooldown.
const ( EventZoneEnter = "zone_enter" EventZoneLeave = "zone_leave" EventZoneUnknown = "zone_unknown" )
Presence event types.
Variables ¶
This section is empty.
Functions ¶
func GenerateConfig ¶
func GenerateConfig(cameras []DiscoveredCamera) string
GenerateConfig produces a YAML config snippet for discovered cameras.
Types ¶
type Camera ¶
type Camera struct {
// contains filtered or unexported fields
}
Camera manages a single RTSP camera stream.
func NewCamera ¶
func NewCamera(cfg config.CameraConfig, detector *detect.Detector, motion config.MotionConfig, events chan<- Event, eventEnds chan<- EventEnd, presenceEvents chan<- PresenceEvent, hub *rtsp.Hub, snapshotPath string, snapshotQuality int, recordingPath string, faceRecognizer *detect.FaceRecognizer, faceEvents chan<- FaceEvent, faceCropDir string, motionActivity chan<- MotionActivity, detections chan<- DetectionFrame) *Camera
func NewTestCamera ¶
NewTestCamera builds a Camera with no RTSP/detector wiring, suitable for exercising HTTP handlers that depend on a registered camera. Production goroutines are not started; LiveFrame returns the frame set via SetTestFrame, or nil.
func (*Camera) DoorbellEnabled ¶ added in v0.7.19
DoorbellEnabled reports whether this camera is configured as a doorbell, so callers can decide whether to start doorbell-specific background work.
func (*Camera) IsOnline ¶
IsOnline returns true when the camera has decoded a frame within the freshness window. This reflects the user-visible "can I see this camera right now?" semantics — the raw RTSP source's Connected() flag can lag real frame flow after reconnects and is unreliable as a health signal.
func (*Camera) LastFrameTime ¶
LastFrameTime returns the wall-clock time at which the most recent frame was decoded. Zero value means no frame has ever been seen.
func (*Camera) LastSnapshot ¶
LastSnapshot converts the stored RGB24 frame to RGBA on demand.
func (*Camera) LastSnapshotTime ¶
LastSnapshotTime returns the age of the last-known frame available to show: the live decode time when one exists this session, otherwise the mtime of the snapshot loaded from disk. Zero value means no frame is available at all.
func (*Camera) LiveFrame ¶
LiveFrame returns the highest-quality recent decoded frame for downstream processing (e.g. on-demand OSNet embedding from the live overlay). Prefers the main-stream snapshot consumer's full-res frame; falls back to the detect-resolution frame when the snap consumer has nothing yet. Returns nil if no frame has been decoded.
func (*Camera) PersistCrySnooze ¶ added in v0.7.21
func (*Camera) PresenceTracker ¶
func (c *Camera) PresenceTracker() *PresenceTracker
PresenceTracker returns the camera's presence tracker for API access.
func (*Camera) Reconnects ¶
Reconnects returns the cumulative number of times this camera's RTSP source(s) have lost an established connection. The count is monotonic across camera stop/start: sources feed this counter via SetReconnectSink, so it survives the source being removed from the hub and recreated.
func (*Camera) SetTestFrame ¶
SetTestFrame primes the camera with a synthetic frame. Subsequent calls to LiveFrame and LastSnapshot will return a copy of this frame.
func (*Camera) SetTestLastFrameTime ¶
SetTestLastFrameTime primes lastFrameTime so handlers exercising Last-Modified or freshness logic have a deterministic timestamp.
func (*Camera) SetTestOnDemand ¶
SetTestOnDemand marks the camera as an on-demand (battery) camera, so Status reports Sleeping while no frames are arriving. Intended for handler tests covering the sleeping state.
func (*Camera) SetTestOnline ¶
SetTestOnline overrides IsOnline to return the given value. Intended for handler tests that need deterministic online/offline state without a running RTSP source.
func (*Camera) SetTrackName ¶
SetTrackName attaches a display name to a live track so subsequent overlay frames render it as a known object. Called from the central event loop after re-ID matching, and from the click-to-name API handler. Safe to call from any goroutine; a no-op once the track is deleted.
func (*Camera) SnapshotRGB24 ¶
SnapshotRGB24 copies the raw RGB24 frame into dst and returns dimensions.
func (*Camera) Start ¶
Start begins reading frames from the RTSP stream via the Hub. Start begins frame processing for the camera. It returns a channel that is closed once every goroutine it started has returned, so a caller that cancels ctx can wait for the camera to have actually stopped instead of assuming it has.
func (*Camera) Status ¶
func (c *Camera) Status() CameraStatus
Status returns the current status of the camera. Online is derived from frame freshness — see IsOnline.
type CameraStartHook ¶ added in v0.7.19
CameraStartHook runs when a camera starts, receiving that camera's own context. Work started from it is cancelled when the camera is stopped.
type CameraStatus ¶
type CameraStatus struct {
Cry *cry.Status `json:"cry,omitempty"`
Name string `json:"name"`
Online bool `json:"online"`
HasMotion bool `json:"has_motion"`
LastFrame time.Time `json:"last_frame"`
// LastSeen dates the last-known frame still available to display (live
// decode time, or the cached disk snapshot's mtime after a restart). Unlike
// LastFrame it is non-zero for an offline camera whose only frame came from
// disk, so the dashboard can caption offline tiles with "last seen".
LastSeen time.Time `json:"last_seen"`
Degraded bool `json:"degraded"`
DegradedReason string `json:"degraded_reason,omitempty"`
PTZ bool `json:"ptz"`
Stopped bool `json:"stopped"`
SourceFPS float64 `json:"source_fps"`
// Sleeping distinguishes an on-demand camera resting between events from one
// that is genuinely unreachable. Both are Online=false, because no frames are
// arriving and that is the honest reading, but only the latter is a fault
// worth alerting on. Always false for a normal mains-powered camera, whose
// stream really should be there.
Sleeping bool `json:"sleeping"`
// LastConnected dates the last time this camera's RTSP source reached PLAY.
// Omitted when it has not connected since Vedetta started, which is a
// different fact from a zero time and must not be rendered as an age.
//
// For an on-demand camera this is the only signal separating one napping
// between events from one that has been unplugged or removed from its
// bridge: both answer "no such stream" indefinitely, so a stale timestamp
// here is the whole warning.
LastConnected time.Time `json:"last_connected,omitempty"`
// StreamError carries the most recent RTSP connection failure when it is
// something other than the stream not being published, with credentials
// redacted. Empty while connected, and empty for an on-demand camera
// resting between events, because that is not a fault.
StreamError string `json:"stream_error,omitempty"`
}
CameraStatus represents the current status of a camera.
type DetectionBox ¶
type DetectionBox struct {
Label string `json:"label"`
Score float32 `json:"score"`
TrackID int `json:"track_id"`
Name string `json:"name,omitempty"` // user-assigned object name when this track has been re-IDed
X1 float32 `json:"x1"`
Y1 float32 `json:"y1"`
X2 float32 `json:"x2"`
Y2 float32 `json:"y2"`
}
DetectionBox is a single tracked object for the live overlay. Coords are normalized (0..1) against the detector frame.
type DetectionFrame ¶
type DetectionFrame struct {
Camera string `json:"camera"`
Timestamp time.Time `json:"ts"`
Boxes []DetectionBox `json:"boxes"`
}
DetectionFrame is a snapshot of currently tracked objects for a camera, emitted once per detector run for use by the live bounding-box overlay.
type DiscoveredCamera ¶
type DiscoveredCamera struct {
IP string `json:"ip"`
Port int `json:"port"`
Name string `json:"name"`
Manufacturer string `json:"manufacturer"`
Model string `json:"model"`
XAddrs []string `json:"xaddrs"`
Scopes []string `json:"scopes"`
}
DiscoveredCamera represents a camera found via ONVIF WS-Discovery.
func DiscoverCameras ¶
func DiscoverCameras(timeout time.Duration) ([]DiscoveredCamera, error)
DiscoverCameras sends a WS-Discovery probe and collects ONVIF camera responses.
type Event ¶
type Event struct {
ID string `json:"id"`
CameraName string `json:"camera"`
Label string `json:"label"`
Score float32 `json:"score"`
TrackID int `json:"track_id"`
Box [4]int `json:"box"` // x1, y1, x2, y2
Timestamp time.Time `json:"timestamp"`
EndTime time.Time `json:"end_time,omitempty"` // when the tracked object left the frame
SnapshotPath string `json:"snapshot_path,omitempty"`
SnapshotAvailable bool `json:"snapshot_available"`
ClipPath string `json:"clip_path,omitempty"`
ClipAvailable bool `json:"clip_available"`
ZoneName string `json:"zone_name,omitempty"`
ObjectName string `json:"object_name,omitempty"`
SubLabel string `json:"sub_label,omitempty"`
Kind string `json:"kind"` // "object" (default) or "doorbell"
AnsweredAt time.Time `json:"answered_at,omitempty"` // doorbell rings: when acknowledged (zero = unanswered)
AnsweredBy string `json:"answered_by,omitempty"` // doorbell rings: who acknowledged
Category string `json:"category,omitempty"` // "alert" (notify) or "detection" (low priority)
SnapshotImage *image.RGBA `json:"-"` // clean frame for disk/embeddings
NotificationJPEG []byte `json:"-"` // immutable, bounded inline notification attachment
AnnotatedImage *image.RGBA `json:"-"` // annotated frame for MQTT display
}
Event represents a detected object event from a camera.
type FaceEvent ¶
type FaceEvent struct {
Camera string
EventID string
Results []detect.FaceResult
// Kind is the event kind that triggered face recognition (e.g. EventKindDoorbell).
// Zero value means a standard object-detection event.
Kind string
}
FaceEvent carries face detection results from the camera detection loop.
type Manager ¶
type Manager struct {
// contains filtered or unexported fields
}
Manager manages all camera streams.
func NewManager ¶
func NewManager(configs []config.CameraConfig, detector *detect.Detector, motion config.MotionConfig, events chan<- Event, eventEnds chan<- EventEnd, presenceEvents chan<- PresenceEvent, hub *rtsp.Hub, snapshotPath string, snapshotQuality int, recordingPath string, faceRecognizer *detect.FaceRecognizer, faceEvents chan<- FaceEvent, faceCropDir string, motionActivity chan<- MotionActivity, detections chan<- DetectionFrame) *Manager
func NewManagerForTest ¶
func NewManagerForTest() *Manager
NewManagerForTest returns a Manager with buffered channels suitable for handler tests. No RTSP hub, detector, or recording path is wired; only camera lookup and doorbell submission work correctly.
func (*Manager) AddCamera ¶
func (m *Manager) AddCamera(cfg config.CameraConfig)
AddCamera adds a new camera to the manager at runtime. If a camera with the same name already exists, the call is a no-op.
func (*Manager) CameraStatuses ¶
func (m *Manager) CameraStatuses() []CameraStatus
CameraStatuses returns the status of all managed cameras in config-file order.
func (*Manager) ConfigureCry ¶ added in v0.7.21
func (*Manager) IsStopped ¶
IsStopped returns true when the named camera exists but has no active context. Returns false for unknown camera names.
func (*Manager) ListCameras ¶
func (*Manager) OnCameraStart ¶ added in v0.7.19
func (m *Manager) OnCameraStart(fn CameraStartHook)
OnCameraStart registers fn to run each time a camera starts, with that camera's own context. Background work started from fn is therefore cancelled when that camera is stopped, instead of living until the process exits. Cameras that are already running when fn is registered get an immediate call, so registration order does not decide whether a camera is covered.
func (*Manager) RegisterForTest ¶
RegisterForTest installs a pre-built Camera into the manager without starting its RTSP/detect goroutines. Intended for handler tests.
The camera is registered as running. The manager derives Stopped from the presence of a running entry, so without one every test camera would report as administratively stopped - which is the opposite of what a handler test means by "a registered camera". The entry carries an already-closed stopped channel because there are no goroutines to wait for.
func (*Manager) RunningCameraDetectURLs ¶
RunningCameraDetectURLs returns the DetectURL of every currently-running (not stopped) camera, in config order. A camera is running iff it has an active cancel func, mirroring CameraStatuses. Used to keep each running camera's live-HLS sub-stream consumer warm.
func (*Manager) Start ¶
Start brings up every camera that is not marked stopped, staggering them so they do not all open their RTSP connections at once.
func (*Manager) StartCamera ¶
StartCamera starts the named camera with its own derived context and runs every registered start hook against it.
func (*Manager) StopCamera ¶
StopCamera cancels the named camera and waits, bounded, for its goroutines to finish. Returning before the camera has stopped would let a caller restart it, or report it stopped, while its old RTSP consumer is still attached.
func (*Manager) SubmitDoorbellPress ¶
SubmitDoorbellPress synthesizes a doorbell event for the named camera and injects it into the event pipeline. It selects an already-scored visitor image from the preceding two seconds, falling back to the latest main-stream frame or detection frame when no suitable visitor image is available. Returns the event ID and true on success, or an empty string and false when the camera is unknown or has no frame yet.
type MotionActivity ¶
MotionActivity carries per-minute motion intensity for timeline display.
type OnvifEvent ¶
type OnvifEvent struct {
Type OnvifEventType
Camera string
Timestamp time.Time
Topic string
Value bool
}
OnvifEvent represents a parsed ONVIF notification.
type OnvifEventSubscriber ¶
type OnvifEventSubscriber struct {
// contains filtered or unexported fields
}
OnvifEventSubscriber subscribes to a camera's ONVIF events via PullPoint.
func NewOnvifEventSubscriber ¶
func NewOnvifEventSubscriber(cameraName, rtspURL string, events chan<- OnvifEvent) (*OnvifEventSubscriber, error)
func (*OnvifEventSubscriber) Run ¶
func (s *OnvifEventSubscriber) Run(ctx context.Context)
Run subscribes and polls for events until ctx is cancelled.
type OnvifEventType ¶
type OnvifEventType string
OnvifEventType classifies ONVIF events.
const ( OnvifEventDoorbell OnvifEventType = "doorbell" OnvifEventMotion OnvifEventType = "motion" OnvifEventUnknown OnvifEventType = "unknown" )
type PTZClient ¶
type PTZClient struct {
// contains filtered or unexported fields
}
PTZClient communicates with an ONVIF PTZ service endpoint.
func NewPTZClient ¶
NewPTZClient creates a PTZClient by probing ONVIF endpoints on the camera. It derives the ONVIF HTTP endpoint from the RTSP URL (same host, port 80), discovers PTZ capabilities, and finds a media profile with PTZ support.
func NewTestPTZClient ¶
NewTestPTZClient creates a PTZClient for testing with no real ONVIF connection.
func (*PTZClient) ContinuousMove ¶
ContinuousMove starts continuous PTZ movement with the given velocity values. Pan and tilt range from -1.0 to 1.0; zoom ranges from -1.0 to 1.0.
type PresenceEvent ¶
type PresenceEvent struct {
ZoneID int
ZoneName string
Label string
Type string // EventZoneEnter, EventZoneLeave or EventZoneUnknown
Time time.Time
}
PresenceEvent represents a change in presence state.
type PresenceKey ¶
PresenceKey identifies a unique zone+label combination for presence tracking.
type PresenceStatus ¶
type PresenceStatus int
PresenceStatus is what a zone knows about a label.
Unknown is not a shade of Absent. A zone reports Unknown when the objects that established its presence stopped being detected anywhere, without ever being seen to leave: the detector loses a parked car in the dark, or the camera goes blind. Collapsing that into Absent asserts a departure from an absence of evidence, which is how the driveway sensor came to claim the car had left while it sat on the drive.
const ( PresenceAbsent PresenceStatus = iota PresencePresent PresenceUnknown )
func (PresenceStatus) String ¶
func (s PresenceStatus) String() string
type PresenceTracker ¶
type PresenceTracker struct {
// contains filtered or unexported fields
}
PresenceTracker manages presence state for zones with track_presence enabled.
func NewPresenceTracker ¶
func NewPresenceTracker() *PresenceTracker
NewPresenceTracker creates a new PresenceTracker with default debounce timings.
func (*PresenceTracker) AllPresence ¶
func (pt *PresenceTracker) AllPresence() map[PresenceKey]ZonePresence
AllPresence returns all current presence states.
func (*PresenceTracker) GetPresence ¶
func (pt *PresenceTracker) GetPresence(key PresenceKey) (present bool, lastSeen, lastChanged time.Time)
GetPresence returns the current presence state for a given key.
func (*PresenceTracker) GetState ¶
func (pt *PresenceTracker) GetState(key PresenceKey) (PresenceStatus, time.Time)
GetState returns the current status for a key, and when it last changed.
func (*PresenceTracker) Update ¶
func (pt *PresenceTracker) Update(zoneMatches map[PresenceKey]bool, zones map[int]string) []PresenceEvent
Update is the legacy entry point: it knows only which zones hold a detection of each label, so an object that stops matching a zone is indistinguishable from one that stopped being detected. It therefore treats every disappearance as a loss, never as a departure. Callers that can see the tracks should use UpdateObserved.
func (*PresenceTracker) UpdateObserved ¶
func (pt *PresenceTracker) UpdateObserved( inZone map[PresenceKey]map[int]bool, detected map[int]bool, zones map[int]string, ) []PresenceEvent
UpdateObserved processes one frame of observations and returns presence changes.
inZone maps each zone+label to the track IDs a detection placed inside that zone on this frame. detected holds every track ID a detection matched this frame, wherever it was. The difference between the two is the whole point: a member track missing from its zone but present in detected walked out of the zone, and a member missing from both was simply lost.
type StreamProfile ¶
type StreamProfile struct {
URL string `json:"url"`
Resolution string `json:"resolution"` // "main" or "sub"
}
StreamProfile represents an RTSP stream endpoint.
func ProbeRTSP ¶
func ProbeRTSP(ip string, port int) ([]StreamProfile, error)
ProbeRTSP tests common RTSP URL patterns for a camera and returns valid streams.
func ProbeRTSPForBrand ¶
func ProbeRTSPForBrand(ip string, port int, manufacturer string) ([]StreamProfile, error)
ProbeRTSPForBrand tests RTSP URL patterns specific to a camera brand.
func ProbeRTSPWithCredentials ¶
func ProbeRTSPWithCredentials(ip string, port int, manufacturer, username, password string) ([]StreamProfile, error)
ProbeRTSPWithCredentials discovers RTSP streams using credentials. It first tries unauthenticated discovery, then injects credentials. If the camera requires auth even for RTSP Describe (common for Tapo, Reolink, etc.), it probes known URL patterns with credentials directly.
type Zone ¶
type Zone struct {
ID int `json:"id"`
Camera string `json:"camera"`
Name string `json:"name"`
Points [][]float64 `json:"points"`
X1 float64 `json:"-"`
Y1 float64 `json:"-"`
X2 float64 `json:"-"`
Y2 float64 `json:"-"`
Labels []string `json:"labels"`
TrackPresence bool `json:"track_presence"`
FaceRecognition bool `json:"face_recognition"`
Enabled bool `json:"enabled"`
}
Zone represents a spatial region on a camera view. Coordinates are percentages (0.0-1.0) relative to the frame dimensions.
func MatchZones ¶
MatchZones returns the zones that contain the detection anchor point. The anchor point is the bottom-center of the detection box, normalized to 0..1.
func (Zone) LabelsJSON ¶
LabelsJSON returns the JSON representation of the zone's labels.
type ZonePresence ¶
type ZonePresence struct {
ZoneID int `json:"zone_id"`
Label string `json:"label"`
Present bool `json:"present"`
LastSeen time.Time `json:"last_seen,omitempty"`
LastChanged time.Time `json:"last_changed,omitempty"`
}
ZonePresence tracks the presence state of a label within a zone.