nvrspatialtracking

package
v0.0.59 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Jan 8, 2026 License: MIT Imports: 17 Imported by: 0

Documentation

Overview

Package nvrspatialtracking provides multi-camera spatial awareness and cross-camera tracking

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type Analytics

type Analytics struct {
	TotalTracks        int                  `json:"total_tracks"`
	ActiveTracks       int                  `json:"active_tracks"`
	TotalHandoffs      int                  `json:"total_handoffs"`
	SuccessfulHandoffs int                  `json:"successful_handoffs"`
	OverallSuccessRate float64              `json:"overall_success_rate"`
	TransitionStats    []TransitionStat     `json:"transition_stats"`
	HourlyActivity     []HourlyActivityStat `json:"hourly_activity"`
}

Analytics contains aggregate tracking statistics

type BoundingBoxSample

type BoundingBoxSample struct {
	Timestamp time.Time `json:"timestamp"`
	X         float64   `json:"x"` // Normalized 0-1
	Y         float64   `json:"y"` // Normalized 0-1
	Width     float64   `json:"width"`
	Height    float64   `json:"height"`
}

BoundingBoxSample is a sampled position within a camera

type CalibrationSession

type CalibrationSession struct {
	ID           string    `json:"id"`
	CameraID     string    `json:"camera_id"`
	StartedAt    time.Time `json:"started_at"`
	Status       string    `json:"status"` // "pending", "in_progress", "completed"
	Instructions string    `json:"instructions"`
}

CalibrationSession represents an active calibration

type CameraPlacement

type CameraPlacement struct {
	ID              string    `json:"id"`
	CameraID        string    `json:"camera_id"`                  // Reference to NVR camera
	MapID           string    `json:"map_id"`                     // Which spatial map
	Position        Point     `json:"position"`                   // Position on map
	Rotation        float64   `json:"rotation"`                   // Degrees, 0 = pointing right
	FOVAngle        float64   `json:"fov_angle"`                  // Field of view angle (degrees)
	FOVDepth        float64   `json:"fov_depth"`                  // How far camera sees (units)
	CoveragePolygon Polygon   `json:"coverage_polygon,omitempty"` // Optional manual override
	MountHeight     float64   `json:"mount_height,omitempty"`     // Height in meters
	TiltAngle       float64   `json:"tilt_angle,omitempty"`       // Vertical tilt
	CreatedAt       time.Time `json:"created_at"`
	UpdatedAt       time.Time `json:"updated_at"`
}

CameraPlacement represents where a camera is positioned on a spatial map

func (*CameraPlacement) CalculateFOVPolygon

func (cp *CameraPlacement) CalculateFOVPolygon() Polygon

CalculateFOVPolygon generates the camera's field of view polygon

type CameraTransition

type CameraTransition struct {
	ID            string         `json:"id"`
	FromCameraID  string         `json:"from_camera_id"`
	ToCameraID    string         `json:"to_camera_id"`
	Type          TransitionType `json:"type"`
	Bidirectional bool           `json:"bidirectional"` // If true, works both ways

	// For overlap transitions
	OverlapZone Polygon `json:"overlap_zone,omitempty"`

	// For gap transitions
	ExpectedTransitTime float64 `json:"expected_transit_time,omitempty"` // Seconds
	TransitTimeVariance float64 `json:"transit_time_variance,omitempty"` // +/- seconds

	// Exit/entry zones on camera frames
	ExitZone  *ZoneDefinition `json:"exit_zone,omitempty"`
	EntryZone *ZoneDefinition `json:"entry_zone,omitempty"`

	// Learned statistics
	AvgTransitTime     float64 `json:"avg_transit_time,omitempty"`
	SuccessRate        float64 `json:"success_rate,omitempty"`
	TotalHandoffs      int     `json:"total_handoffs"`
	SuccessfulHandoffs int     `json:"successful_handoffs"`

	CreatedAt time.Time `json:"created_at"`
	UpdatedAt time.Time `json:"updated_at"`
}

CameraTransition defines how objects move between cameras

type EdgeDirection

type EdgeDirection string

EdgeDirection represents which edge of the camera frame

const (
	EdgeTop    EdgeDirection = "top"
	EdgeBottom EdgeDirection = "bottom"
	EdgeLeft   EdgeDirection = "left"
	EdgeRight  EdgeDirection = "right"
)

type GlobalTrack

type GlobalTrack struct {
	ID                string    `json:"id"`
	FirstSeen         time.Time `json:"first_seen"`
	LastSeen          time.Time `json:"last_seen"`
	CurrentCameraID   string    `json:"current_camera_id"`
	CurrentLocalTrack string    `json:"current_local_track"` // Track ID from detection

	// Object identification
	ObjectType string `json:"object_type"` // "person", "vehicle", etc.

	// Appearance for Re-ID (stored as base64 encoded embedding)
	Embedding     []byte  `json:"embedding,omitempty"`
	EmbeddingConf float64 `json:"embedding_confidence"`

	// Visual attributes for quick matching
	DominantColors  []string `json:"dominant_colors,omitempty"`
	EstimatedHeight float64  `json:"estimated_height,omitempty"`

	// State
	State TrackState `json:"state"`

	// Predictions
	PredictedNext    string     `json:"predicted_next_camera,omitempty"`
	PredictedArrival *time.Time `json:"predicted_arrival,omitempty"`

	// History
	Path []TrackSegment `json:"path"`

	CreatedAt time.Time `json:"created_at"`
	UpdatedAt time.Time `json:"updated_at"`
}

GlobalTrack represents a tracked object across multiple cameras

type HandoffTestResult

type HandoffTestResult struct {
	FromCameraID   string         `json:"from_camera_id"`
	ToCameraID     string         `json:"to_camera_id"`
	TransitionType TransitionType `json:"transition_type"`
	ExpectedTime   float64        `json:"expected_time_seconds"`
	Status         string         `json:"status"`
	Message        string         `json:"message"`
}

HandoffTestResult contains results from a handoff test

type HourlyActivityStat

type HourlyActivityStat struct {
	Hour       int `json:"hour"`
	TrackCount int `json:"track_count"`
}

HourlyActivityStat contains hourly tracking activity

type MapAnalytics

type MapAnalytics struct {
	ActiveTracks       int      `json:"active_tracks"`
	TotalTracks        int      `json:"total_tracks"`
	SuccessfulHandoffs int      `json:"successful_handoffs"`
	FailedHandoffs     int      `json:"failed_handoffs"`
	TotalHandoffs      int      `json:"total_handoffs,omitempty"`
	AverageTransitTime float64  `json:"average_transit_time"`
	CoverageGaps       []string `json:"coverage_gaps"`
}

MapAnalytics contains analytics for a specific map (matches frontend SpatialAnalytics type)

type MapMeta

type MapMeta struct {
	Building string `json:"building,omitempty"`
	Floor    string `json:"floor,omitempty"`
	Area     string `json:"area,omitempty"`
}

MapMeta contains optional metadata for a spatial map

type PendingHandoff

type PendingHandoff struct {
	ID             string         `json:"id"`
	GlobalTrackID  string         `json:"global_track_id"`
	FromCameraID   string         `json:"from_camera_id"`
	ToCameraIDs    []string       `json:"to_camera_ids"` // Possible destination cameras
	TransitionType TransitionType `json:"transition_type"`
	ExitedAt       time.Time      `json:"exited_at"`
	ExpectedBy     time.Time      `json:"expected_by"` // Deadline for match
	ExitDirection  EdgeDirection  `json:"exit_direction"`
	ExitPosition   Point          `json:"exit_position"`
	Embedding      []byte         `json:"embedding,omitempty"`
	DominantColors []string       `json:"dominant_colors,omitempty"`
}

PendingHandoff represents an object that exited one camera and is expected in another

type Plugin

type Plugin struct {
	// contains filtered or unexported fields
}

Plugin implements the spatial tracking plugin

func New

func New() *Plugin

New creates a new spatial tracking plugin instance

func (*Plugin) Health

func (p *Plugin) Health() sdk.HealthStatus

Health returns the plugin health status

func (*Plugin) Initialize

func (p *Plugin) Initialize(ctx context.Context, runtime *sdk.PluginRuntime) error

Initialize prepares the plugin

func (*Plugin) Manifest

func (p *Plugin) Manifest() sdk.PluginManifest

Manifest returns the plugin manifest

func (*Plugin) Routes

func (p *Plugin) Routes() http.Handler

Routes returns the HTTP handler for plugin routes

func (*Plugin) Start

func (p *Plugin) Start(ctx context.Context) error

Start begins plugin operation

func (*Plugin) Stop

func (p *Plugin) Stop(ctx context.Context) error

Stop gracefully shuts down the plugin

type Point

type Point struct {
	X float64 `json:"x"`
	Y float64 `json:"y"`
}

Point represents a 2D coordinate

func (Point) Distance

func (p Point) Distance(other Point) float64

Distance calculates distance between two points

type Polygon

type Polygon []Point

Polygon is a series of points forming a closed shape

func (Polygon) ContainsPoint

func (p Polygon) ContainsPoint(pt Point) bool

ContainsPoint checks if a point is inside the polygon using ray casting

func (Polygon) Intersects

func (p Polygon) Intersects(other Polygon) bool

Intersects checks if two polygons overlap

func (Polygon) MarshalJSON

func (p Polygon) MarshalJSON() ([]byte, error)

MarshalJSON custom marshaler for Polygon to handle empty slices

type SpatialMap

type SpatialMap struct {
	ID        string    `json:"id"`
	Name      string    `json:"name"`
	ImageURL  string    `json:"image_url,omitempty"`
	Width     float64   `json:"width"`  // Logical width in units
	Height    float64   `json:"height"` // Logical height in units
	Scale     float64   `json:"scale"`  // Units per meter (for distance calculations)
	Metadata  MapMeta   `json:"metadata,omitempty"`
	CreatedAt time.Time `json:"created_at"`
	UpdatedAt time.Time `json:"updated_at"`
}

SpatialMap represents a floor plan or area where cameras are positioned

type Store

type Store struct {
	// contains filtered or unexported fields
}

Store handles database operations for spatial tracking

func NewStore

func NewStore(db *sql.DB) *Store

NewStore creates a new Store instance

func (*Store) AutoDetectTransitions

func (s *Store) AutoDetectTransitions(ctx context.Context, mapID string) ([]CameraTransition, error)

AutoDetectTransitions analyzes camera placements and detects transitions

func (*Store) CleanupExpiredHandoffs

func (s *Store) CleanupExpiredHandoffs() (int64, error)

CleanupExpiredHandoffs removes expired pending handoffs

func (*Store) CreateMap

func (s *Store) CreateMap(m *SpatialMap) error

CreateMap creates a new spatial map

func (*Store) CreateMapCtx

func (s *Store) CreateMapCtx(ctx context.Context, m *SpatialMap) error

CreateMapCtx creates a new spatial map (context-aware wrapper)

func (*Store) CreatePendingHandoff

func (s *Store) CreatePendingHandoff(ph *PendingHandoff) error

CreatePendingHandoff creates a new pending handoff

func (*Store) CreatePlacement

func (s *Store) CreatePlacement(cp *CameraPlacement) error

CreatePlacement creates a new camera placement

func (*Store) CreatePlacementCtx

func (s *Store) CreatePlacementCtx(ctx context.Context, cp *CameraPlacement) error

CreatePlacementCtx creates a new camera placement (context-aware wrapper)

func (*Store) CreateSegment

func (s *Store) CreateSegment(ts *TrackSegment) error

CreateSegment creates a new track segment

func (*Store) CreateTrack

func (s *Store) CreateTrack(gt *GlobalTrack) error

CreateTrack creates a new global track

func (*Store) CreateTransition

func (s *Store) CreateTransition(ct *CameraTransition) error

CreateTransition creates a new camera transition

func (*Store) CreateTransitionCtx

func (s *Store) CreateTransitionCtx(ctx context.Context, ct *CameraTransition) error

CreateTransitionCtx creates a new camera transition (context-aware wrapper)

func (*Store) DeleteMap

func (s *Store) DeleteMap(id string) error

DeleteMap deletes a spatial map

func (*Store) DeleteMapCtx

func (s *Store) DeleteMapCtx(ctx context.Context, id string) error

DeleteMapCtx deletes a spatial map (context-aware wrapper)

func (*Store) DeletePendingHandoff

func (s *Store) DeletePendingHandoff(id string) error

DeletePendingHandoff deletes a pending handoff

func (*Store) DeletePlacement

func (s *Store) DeletePlacement(id string) error

DeletePlacement deletes a camera placement

func (*Store) DeletePlacementCtx

func (s *Store) DeletePlacementCtx(ctx context.Context, id string) error

DeletePlacementCtx deletes a camera placement (context-aware wrapper)

func (*Store) DeleteTrack

func (s *Store) DeleteTrack(id string) error

DeleteTrack deletes a global track and its segments

func (*Store) DeleteTransition

func (s *Store) DeleteTransition(id string) error

DeleteTransition deletes a camera transition

func (*Store) DeleteTransitionCtx

func (s *Store) DeleteTransitionCtx(ctx context.Context, id string) error

DeleteTransitionCtx deletes a camera transition (context-aware wrapper)

func (*Store) GetAnalytics

func (s *Store) GetAnalytics() (*Analytics, error)

GetAnalytics returns aggregate tracking statistics

func (*Store) GetAnalyticsCtx

func (s *Store) GetAnalyticsCtx(ctx context.Context) (*Analytics, error)

GetAnalyticsCtx returns aggregate tracking statistics (context-aware wrapper)

func (*Store) GetMap

func (s *Store) GetMap(id string) (*SpatialMap, error)

GetMap retrieves a spatial map by ID

func (*Store) GetMapAnalytics

func (s *Store) GetMapAnalytics(mapID string) (*MapAnalytics, error)

GetMapAnalytics returns analytics for a specific map

func (*Store) GetMapCtx

func (s *Store) GetMapCtx(ctx context.Context, id string) (*SpatialMap, error)

GetMapCtx retrieves a spatial map by ID (context-aware wrapper)

func (*Store) GetPendingHandoff

func (s *Store) GetPendingHandoff(id string) (*PendingHandoff, error)

GetPendingHandoff retrieves a pending handoff by ID

func (*Store) GetPlacement

func (s *Store) GetPlacement(id string) (*CameraPlacement, error)

GetPlacement retrieves a camera placement by ID

func (*Store) GetPlacementByCameraID

func (s *Store) GetPlacementByCameraID(cameraID string) (*CameraPlacement, error)

GetPlacementByCameraID retrieves a camera placement by camera ID

func (*Store) GetPlacementCtx

func (s *Store) GetPlacementCtx(ctx context.Context, id string) (*CameraPlacement, error)

GetPlacementCtx retrieves a camera placement by ID (context-aware wrapper)

func (*Store) GetTrack

func (s *Store) GetTrack(id string) (*GlobalTrack, error)

GetTrack retrieves a global track by ID

func (*Store) GetTransition

func (s *Store) GetTransition(id string) (*CameraTransition, error)

GetTransition retrieves a camera transition by ID

func (*Store) GetTransitionByCameras

func (s *Store) GetTransitionByCameras(fromCameraID, toCameraID string) (*CameraTransition, error)

GetTransitionByCameras retrieves a transition by from/to camera IDs

func (*Store) GetTransitionCtx

func (s *Store) GetTransitionCtx(ctx context.Context, id string) (*CameraTransition, error)

GetTransitionCtx retrieves a camera transition by ID (context-aware wrapper)

func (*Store) ListActiveTracks

func (s *Store) ListActiveTracks() ([]GlobalTrack, error)

ListActiveTracks returns all active tracks

func (*Store) ListMaps

func (s *Store) ListMaps() ([]SpatialMap, error)

ListMaps returns all spatial maps

func (*Store) ListMapsCtx

func (s *Store) ListMapsCtx(ctx context.Context) ([]SpatialMap, error)

ListMaps returns all spatial maps (context-aware wrapper)

func (*Store) ListPendingHandoffs

func (s *Store) ListPendingHandoffs() ([]PendingHandoff, error)

ListPendingHandoffs returns all pending handoffs

func (*Store) ListPendingHandoffsForCamera

func (s *Store) ListPendingHandoffsForCamera(cameraID string) ([]PendingHandoff, error)

ListPendingHandoffsForCamera returns pending handoffs expecting arrival at a camera

func (*Store) ListPlacementsByMap

func (s *Store) ListPlacementsByMap(mapID string) ([]CameraPlacement, error)

ListPlacementsByMap returns all camera placements for a map

func (*Store) ListPlacementsCtx

func (s *Store) ListPlacementsCtx(ctx context.Context, mapID string) ([]CameraPlacement, error)

ListPlacementsCtx returns camera placements for a map (context-aware wrapper)

func (*Store) ListSegmentsByTrack

func (s *Store) ListSegmentsByTrack(trackID string) ([]TrackSegment, error)

ListSegmentsByTrack returns all segments for a track

func (*Store) ListTransitions

func (s *Store) ListTransitions() ([]CameraTransition, error)

ListTransitions returns all camera transitions

func (*Store) ListTransitionsCtx

func (s *Store) ListTransitionsCtx(ctx context.Context) ([]CameraTransition, error)

ListTransitionsCtx returns all camera transitions (context-aware wrapper)

func (*Store) ListTransitionsFromCamera

func (s *Store) ListTransitionsFromCamera(cameraID string) ([]CameraTransition, error)

ListTransitionsFromCamera returns all transitions from a specific camera

func (*Store) Migrate

func (s *Store) Migrate(ctx context.Context) error

Migrate creates the database schema

func (*Store) RecordHandoff

func (s *Store) RecordHandoff(transitionID string, transitTime float64, success bool) error

RecordHandoff updates transition statistics after a handoff attempt

func (*Store) SaveMapImage

func (s *Store) SaveMapImage(ctx context.Context, mapID string, file io.Reader, filename string) (string, error)

SaveMapImage saves a map image file and returns its URL

func (*Store) SetDataPath

func (s *Store) SetDataPath(path string)

SetDataPath sets the path for storing images and other data

func (*Store) UpdateMap

func (s *Store) UpdateMap(m *SpatialMap) error

UpdateMap updates a spatial map

func (*Store) UpdateMapCtx

func (s *Store) UpdateMapCtx(ctx context.Context, m *SpatialMap) error

UpdateMapCtx updates a spatial map (context-aware wrapper)

func (*Store) UpdatePlacement

func (s *Store) UpdatePlacement(cp *CameraPlacement) error

UpdatePlacement updates a camera placement

func (*Store) UpdatePlacementCtx

func (s *Store) UpdatePlacementCtx(ctx context.Context, cp *CameraPlacement) error

UpdatePlacementCtx updates a camera placement (context-aware wrapper)

func (*Store) UpdateSegment

func (s *Store) UpdateSegment(ts *TrackSegment) error

UpdateSegment updates a track segment

func (*Store) UpdateTrack

func (s *Store) UpdateTrack(gt *GlobalTrack) error

UpdateTrack updates a global track

func (*Store) UpdateTransition

func (s *Store) UpdateTransition(ct *CameraTransition) error

UpdateTransition updates a camera transition

func (*Store) UpdateTransitionCtx

func (s *Store) UpdateTransitionCtx(ctx context.Context, ct *CameraTransition) error

UpdateTransitionCtx updates a camera transition (context-aware wrapper)

type TrackManager

type TrackManager struct {
	// contains filtered or unexported fields
}

TrackManager handles active cross-camera tracking

func NewTrackManager

func NewTrackManager(store *Store, logger *slog.Logger) *TrackManager

NewTrackManager creates a new track manager

func (*TrackManager) ActiveTrackCount

func (tm *TrackManager) ActiveTrackCount() int

ActiveTrackCount returns the number of active tracks

func (*TrackManager) GetTrack

func (tm *TrackManager) GetTrack(id string) (*GlobalTrack, bool)

GetTrack returns a specific track by ID

func (*TrackManager) GetTrackPath

func (tm *TrackManager) GetTrackPath(ctx context.Context, trackID string) (*TrackPath, error)

GetTrackPath returns the spatial path of a track on the map

func (*TrackManager) HandleTrackExit

func (tm *TrackManager) HandleTrackExit(ctx context.Context, cameraID, localTrackID string, exitDirection EdgeDirection, exitPosition Point)

HandleTrackExit processes when a track exits a camera's view

func (*TrackManager) ListActiveTracks

func (tm *TrackManager) ListActiveTracks() []GlobalTrack

ListActiveTracks returns all currently active tracks

func (*TrackManager) ProcessDetection

func (tm *TrackManager) ProcessDetection(ctx context.Context, event *sdk.Event)

ProcessDetection handles an incoming detection event

func (*TrackManager) Run

func (tm *TrackManager) Run(ctx context.Context)

Run starts background processing

func (*TrackManager) StartCalibration

func (tm *TrackManager) StartCalibration(ctx context.Context, cameraID string) (*CalibrationSession, error)

StartCalibration begins a calibration session for a camera

func (*TrackManager) TestHandoff

func (tm *TrackManager) TestHandoff(ctx context.Context, fromCameraID, toCameraID string) (*HandoffTestResult, error)

TestHandoff tests if a handoff between two cameras is configured correctly

type TrackPath

type TrackPath struct {
	TrackID   string     `json:"track_id"`
	MapID     string     `json:"map_id"`
	Waypoints []Waypoint `json:"waypoints"`
}

TrackPath represents a track's journey on the spatial map

type TrackSegment

type TrackSegment struct {
	ID            string              `json:"id"`
	GlobalTrackID string              `json:"global_track_id"`
	CameraID      string              `json:"camera_id"`
	LocalTrackID  string              `json:"local_track_id"`
	EnteredAt     time.Time           `json:"entered_at"`
	ExitedAt      *time.Time          `json:"exited_at,omitempty"`
	ExitDirection EdgeDirection       `json:"exit_direction,omitempty"`
	ExitPosition  *Point              `json:"exit_position,omitempty"`
	BoundingBoxes []BoundingBoxSample `json:"bounding_boxes,omitempty"`
}

TrackSegment represents a portion of a track within a single camera

type TrackState

type TrackState string

TrackState represents the current state of a global track

const (
	TrackStateActive    TrackState = "active"    // Currently visible in a camera
	TrackStateTransit   TrackState = "transit"   // In gap between cameras
	TrackStatePending   TrackState = "pending"   // Waiting for handoff match
	TrackStateLost      TrackState = "lost"      // No match found, may recover
	TrackStateCompleted TrackState = "completed" // Track finished
)

type TransitionStat

type TransitionStat struct {
	TransitionID   string  `json:"transition_id"`
	FromCameraID   string  `json:"from_camera_id"`
	ToCameraID     string  `json:"to_camera_id"`
	Type           string  `json:"type"`
	TotalHandoffs  int     `json:"total_handoffs"`
	SuccessRate    float64 `json:"success_rate"`
	AvgTransitTime float64 `json:"avg_transit_time"`
}

TransitionStat contains stats for a specific transition

type TransitionType

type TransitionType string

TransitionType defines how cameras are connected

const (
	TransitionOverlap  TransitionType = "overlap"  // Cameras share common view
	TransitionAdjacent TransitionType = "adjacent" // Cameras touch but don't overlap
	TransitionGap      TransitionType = "gap"      // Space between camera views
)

type Waypoint

type Waypoint struct {
	Timestamp  time.Time `json:"timestamp"`
	CameraID   string    `json:"camera_id"`
	Position   Point     `json:"position"` // Position on spatial map
	Confidence float64   `json:"confidence"`
}

Waypoint is a point along a track's path

type ZoneDefinition

type ZoneDefinition struct {
	Edge  EdgeDirection `json:"edge"`
	Start float64       `json:"start"` // 0.0 to 1.0, start position along edge
	End   float64       `json:"end"`   // 0.0 to 1.0, end position along edge
}

ZoneDefinition defines an area on the camera frame

Directories

Path Synopsis

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL