camera

package
v0.24.1 Latest Latest
Warning

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

Go to latest
Published: Nov 22, 2026 License: Apache-2.0 Imports: 28 Imported by: 0 modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Overview

Package camera is the controller side of Matter camera streaming: how the controller picks, allocates, reuses and frees a camera's streams and keeps the WebRTC sessions it opens on them. It is a port of matterjs-server's stream management at 0bd06f2 (github.com/matter-js/matterjs-server, packages/ws-controller/src/camera/), whose behaviour this package mirrors; matter.js itself models only the WebRTC requestor of a camera controller, so this package is ahead of matter.js.

The policies are pure functions over small types:

  • the stream policy (policy_stream.go): the video window a request asks for (computeVideoEnvelope), the reuse, degraded and eviction choices, and the audio envelope; with the window search (policy_stream_search.go) that walks a plan's windows best first against the camera's answers and the encoder budget;
  • the SDP policy (policy_sdp.go, policy_sdp_levels.go): what an offer constrains — media dispositions, per-codec decode ceilings from a=fmtp and the H.264 / H.265 level tables, talkback — and the rewrites of an offer without talkback and of an answer narrowed to the offer's directions;
  • the snapshot policy (policy_snapshot.go) and the overlay policy (policy_overlay.go);
  • the provider-command boundary (provider_arguments.go): a client's WebRTCTransportProvider payload, keys matched as matterjs-server matches them, checked against the generated model and decoded into the generated request;
  • the field ranges of the model (field_ranges.go) and the session registry (registry.go), which ends and announces every WebRTC session once, whatever order the camera's reports, stops, releases and peer ends arrive in.

The typed errors (errors.go) map one-to-one onto matterjs-server's camera error codes 102 to 106, and ErrInvalidArgument onto its error 8. The camera quirks matterjs-server works around are named constants in types.go.

Over the policies runs the Service, one per controller:

  • the manager (manager*.go): the per-endpoint lock, the stream leases and their grace window, the allocation ladders for video, audio and snapshots, the session start and the stops and releases, every effect of a request given back on its failure;
  • the session layer (provider_sessions.go): ProvideOffer and SolicitOffer with the controller's requestor endpoint as originating endpoint, the stream fields reconciled with the camera's cluster revision, the UTC-time retry, the requestor's session table kept in step, the offers an answer is narrowed to;
  • the watch (session_watch.go): each camera's CurrentSessions at the end of a report batch, a restart told from a drop by the StartUp event, and the sweep of the sessions a camera holds for this controller that nothing here does;
  • the facade (service.go, session.go, capabilities.go, provider_route.go, reports.go): Service.StartStream and its Session with the camera's signals, Service.Snapshot, Service.Capabilities, Service.ReleaseStream, the raw Provider route and the Observer.

The controller serves the requestor the cameras call back (controller.Config.Camera) under its one operational identity; the service needs outgoing TCP (controller.Config.TCP.Outgoing), since ProvideOffer and ProvideAnswer carry the Large Message quality, and the cameras' reports through a Reports installed on the controller's configuration.

Index

Constants

The signal kinds.

Variables

View Source
var (
	// ErrTCPRequired: the controller opens no outgoing TCP
	// (controller.Config.TCP.Outgoing). ProvideOffer and ProvideAnswer
	// carry the Large Message quality, so their exchange requires TCP.
	ErrTCPRequired = errors.New("camera: the controller opens no outgoing TCP (controller.Config.TCP.Outgoing)")
	// ErrNoRequestor: the controller serves no WebRtcTransportRequestor
	// (controller.Config.Camera).
	ErrNoRequestor = errors.New("camera: the controller serves no camera requestor (controller.Config.Camera)")
	// ErrReportsNotInstalled: Config.Reports is nil, or was not installed
	// on the controller's configuration before controller.New.
	ErrReportsNotInstalled = errors.New("camera: Config.Reports is not installed on the controller's configuration")
	// ErrClosed: the service was closed.
	ErrClosed = errors.New("camera: the service is closed")
	// ErrReportsInUse: Config.Reports is held by a Service that is not
	// closed. The refusal also matches [ErrInvalidArgument] with
	// errors.Is, as it did before this sentinel existed (review II,
	// R2-P6-api-2208, decision 248).
	ErrReportsInUse = errors.New("camera: Config.Reports is held by a camera Service that is not closed")
)

The refusals of New.

View Source
var ErrInvalidArgument = errors.New("camera: invalid argument")

ErrInvalidArgument is matterjs-server's error 8: a caller's argument the controller refuses before anything reaches a camera. Every such refusal matches it with errors.Is; its text names the argument.

View Source
var ErrStreamInUse = errors.New("camera: stream is in use and cannot be released")

ErrStreamInUse is error 104: a stream release refused because the device still references the stream. Mirrors matterjs-server packages/ws-controller/src/types/WebSocketMessageTypes.ts:317-324 at 0bd06f2.

Functions

func AudioCodecByName

func AudioCodecByName(name string) (csdef.AudioCodecEnum, bool)

AudioCodecByName is the audio codec name names, ignoring case, or the codec its decimal spelling states — the spelling AudioCodecName reports for a codec this build does not name, so every name parses back. ok=true means the name parsed (a member name or a decimal), not that the device or this module knows the codec. matterjs-server has no audio ByName (only imageCodecByName, wireNames.ts:68-73 at 0bd06f2); this one extends its table by the same rule.

func AudioCodecName

func AudioCodecName(codec csdef.AudioCodecEnum) string

AudioCodecName is an audio codec's wire name (OPUS, AAC), its decimal spelling for a codec without a name.

func ImageCodecByName

func ImageCodecByName(name string) (csdef.ImageCodecEnum, bool)

ImageCodecByName is the image codec name names, ignoring case, or the codec its decimal spelling states — the spelling ImageCodecName reports for a codec this build does not name, as matterjs-server's imageCodecByName accepts it (wireNames.ts:68-73 at 0bd06f2). ok=true means the name parsed (a member name or a decimal), not that the device or this module knows the codec.

func ImageCodecName

func ImageCodecName(codec csdef.ImageCodecEnum) string

ImageCodecName is an image codec's wire name (JPEG, HEIC), its decimal spelling for a codec without a name.

func ParseICECandidates

func ParseICECandidates(candidates json.RawMessage) ([]wpdef.ICECandidateStruct, error)

ParseICECandidates converts a host's JSON list of ICE candidates — the ice_candidates of matterjs-server's camera_provide_ice_candidates, each an object of ICECandidateStruct's fields (candidate, sdpMid, sdpMLineIndex; keys matched with case and word separators ignored) — into the cluster's structs for Session.ProvideICECandidates. It runs the converter Provider.Send runs for ProvideIceCandidates' iceCandidates field, so a refusal is worded as there ("ice_candidates[0] requires sdpMid") and matches ErrInvalidArgument. Mirrors matterjs-server packages/ws-controller/src/camera/cameraCommands.ts:342-366 (parseIceCandidatesArgs, which converts ice_candidates through toProviderCommandFields) at 0bd06f2.

func StreamUsageByName

func StreamUsageByName(name string) (csdef.StreamUsageEnum, bool)

StreamUsageByName is the stream usage name names, ignoring case. Only member names are accepted, as matterjs-server's streamUsageByName does, so a usage the controller cannot check never reaches the device.

func StreamUsageName

func StreamUsageName(usage csdef.StreamUsageEnum) string

StreamUsageName is a stream usage's member name (Internal, Recording, Analysis, LiveView), its decimal spelling for a usage without a name.

func TwoWayTalkSupportName

func TwoWayTalkSupportName(support csdef.TwoWayTalkSupportTypeEnum) string

TwoWayTalkSupportName is a two-way talk support's member name (NotSupported, HalfDuplex, FullDuplex), its decimal spelling for one without a name.

func VideoCodecByName

func VideoCodecByName(name string) (csdef.VideoCodecEnum, bool)

VideoCodecByName is the video codec name names, ignoring case, or the codec its decimal spelling states — the spelling VideoCodecName reports for a codec this build does not name, so every name parses back. ok=true means the name parsed (a member name or a decimal), not that the device or this module knows the codec. matterjs-server has no video ByName (only imageCodecByName, wireNames.ts:68-73 at 0bd06f2); this one extends its table by the same rule.

func VideoCodecName

func VideoCodecName(codec csdef.VideoCodecEnum) string

VideoCodecName is a video codec's wire name (H264, H265, H266, AV1), its decimal spelling for a codec without a name.

Types

type Allocated

type Allocated struct {
	Video    []AllocatedVideo
	Audio    []AllocatedAudio
	Snapshot []AllocatedSnapshot
}

Allocated is the streams the camera reports, each marked when this controller allocated it in this run.

type AllocatedAudio

type AllocatedAudio struct {
	csdef.AudioStreamStruct
	AllocatedByUs bool
}

AllocatedAudio is one AllocatedAudioStreams entry.

type AllocatedSnapshot

type AllocatedSnapshot struct {
	csdef.SnapshotStreamStruct
	AllocatedByUs bool
}

AllocatedSnapshot is one AllocatedSnapshotStreams entry.

type AllocatedVideo

type AllocatedVideo struct {
	csdef.VideoStreamStruct
	AllocatedByUs bool
}

AllocatedVideo is one AllocatedVideoStreams entry.

type AudioBounds

type AudioBounds struct {
	Codecs       []string
	ChannelCount *uint8
	SampleRate   *uint32
	BitRate      *uint32
}

AudioBounds are a start's audio values; each stated one is exact. A nil field is unstated; a stated one is held to its field's range, as VideoBounds' are.

type AudioCapabilities

type AudioCapabilities struct {
	Codecs            []csdef.AudioCodecEnum
	Channels          *uint8
	SampleRates       []uint32
	BitDepths         []uint8
	TwoWayTalkSupport *csdef.TwoWayTalkSupportTypeEnum
}

AudioCapabilities is the camera's microphone and talkback.

type AudioEnvelope

type AudioEnvelope struct {
	Codec        csdef.AudioCodecEnum
	ChannelCount uint8
	SampleRate   uint32
	BitRate      uint32
	BitDepth     uint8
}

AudioEnvelope is what an audio stream delivers.

type BoundField

type BoundField string

BoundField is the caller hint an IncompatibleBound names. Mirrors matterjs-server packages/ws-client/src/models/model.ts:766-779 at 0bd06f2.

const (
	BoundMinResolution BoundField = "min_resolution"
	BoundMinFrameRate  BoundField = "min_frame_rate"
	BoundMinBitRate    BoundField = "min_bit_rate"
	BoundSampleRate    BoundField = "sample_rate"
	BoundChannelCount  BoundField = "channel_count"
)

The hints a bound can name: three video hints, two audio hints.

type BudgetNarrowing

type BudgetNarrowing struct {
	MaxFrameRate  uint16
	MaxResolution *csdef.VideoResolutionStruct
}

BudgetNarrowing is what the camera's encoder budget made a start give up of its first window; a zero field gave up nothing.

type Capabilities

type Capabilities struct {
	// Features are the advertised AVSM features in bit order, nil while the
	// camera has not stated its FeatureMap.
	Features  []string
	Privacy   Privacy
	Video     VideoCapabilities
	Audio     AudioCapabilities
	Snapshot  []csdef.SnapshotCapabilitiesStruct
	Limits    Limits
	Allocated Allocated
	// Sessions is the provider's CurrentSessions, empty without a provider.
	Sessions []DeviceSession
}

Capabilities is what a camera endpoint states and holds: its features, privacy switches, video, audio and snapshot capabilities, its limits, the streams allocated on it and the WebRTC sessions it reports for this fabric. A pointer field is nil when the camera does not state it. Mirrors matterjs-server packages/ws-controller/src/camera/CameraStreamManager.ts:500-535 at 0bd06f2.

type Config

type Config struct {
	// Reports brings the cameras' reports to the service: installed with
	// [Reports.Install] on the controller's configuration before
	// controller.New. Required.
	Reports *Reports
	// Observer receives what no call's own result reports.
	Observer Observer
	// SyncTime pushes the controller's time to a camera that refused an
	// offer for its missing clock; nil sends SetUTCTime on the camera's
	// root endpoint.
	SyncTime func(ctx context.Context, node *client.Node) error
	// Logger is the service's logger, nil discards.
	Logger *slog.Logger
}

Config configures a Service.

type DeviceSession

type DeviceSession struct {
	ID              uint16
	PeerNodeID      uint64
	PeerEndpoint    uint16
	StreamUsage     uint8
	VideoStreams    []uint16
	AudioStreams    []uint16
	EstablishedByUs bool
}

DeviceSession is one entry of a camera's CurrentSessions (§11.5.5.1), its stream ids from the revision-2 lists or the deprecated revision-1 fields. EstablishedByUs: PeerNodeID is this controller's RootNodeID, so only this controller can end the session (§11.5.6.7.3). Mirrors matterjs-server packages/ws-controller/src/camera/cameraTypes.ts:166-180 at 0bd06f2.

type EndCause

type EndCause string

EndCause says why a session ended.

const (
	// EndPeer: the camera sent End; SessionEnd.Reason is its reason.
	EndPeer EndCause = EndCause(endPeer)
	// EndOtherOwner: another owner, or a raw EndSession, stopped it;
	// SessionEnd.RequestedBy names it.
	EndOtherOwner EndCause = EndCause(endOtherConnection)
	// EndCameraRestarted: the camera restarted, or gave the id to a new
	// session.
	EndCameraRestarted EndCause = EndCause(endCameraRestarted)
	// EndCameraDropped: the session is gone from CurrentSessions without an
	// End.
	EndCameraDropped EndCause = EndCause(endCameraDropped)
	// EndNodeRemoved: the node left the fabric.
	EndNodeRemoved EndCause = EndCause(endNodeRemoved)
	// EndReleased: this controller ended it for a released owner or at
	// Close.
	EndReleased EndCause = EndCause(endReleased)
	// EndSignalOverflow: this controller ended it because the host did not
	// read the session's Signals while the camera kept signalling, past
	// the bounds [Session.Signals] states; the signals not yet read were
	// dropped. The module's own cause, which matterjs-server does not
	// spell.
	EndSignalOverflow EndCause = EndCause(endSignalOverflow)
)

The causes, spelled as matterjs-server's camera_session_ended spells them (packages/ws-client/src/models/model.ts:816-836 of matterjs-server at 0bd06f2).

type ExhaustedError

type ExhaustedError struct {
	Allocated []OccupyingStream
	// MaxEncoders is the camera's MaxConcurrentEncoders, nil when it states
	// none.
	MaxEncoders *int
	// MaxPixelRate is the camera's MaxEncodedPixelRate, nil when it states
	// none.
	MaxPixelRate *int
}

ExhaustedError is error 103: the camera refused the allocation for lack of capacity. Mirrors matterjs-server packages/ws-controller/src/types/WebSocketMessageTypes.ts:185-189 at 0bd06f2.

func (*ExhaustedError) Error

func (*ExhaustedError) Error() string

Error is matterjs-server's message for error 103.

type InUseError

type InUseError struct {
	StreamID uint16
	// ReferenceCount is the cached count; 0 when the report states none
	// above zero, since the cache can lag.
	ReferenceCount int
	// contains filtered or unexported fields
}

InUseError is the ErrStreamInUse of one release: the stream and, when the camera's cached report states one above zero, its reference count. It matches ErrStreamInUse with errors.Is and unwraps to the camera's refusal. Mirrors matterjs-server packages/ws-controller/src/types/WebSocketMessageTypes.ts:317-324 at 0bd06f2.

func (*InUseError) Error

func (e *InUseError) Error() string

func (*InUseError) Is

func (e *InUseError) Is(target error) bool

Is makes an InUseError ErrStreamInUse.

func (*InUseError) Unwrap

func (e *InUseError) Unwrap() error

Unwrap is the camera's refusal.

type IncompatibleBound

type IncompatibleBound struct {
	Field BoundField
	// Requested is the value the caller stated, as text: "1920x1080" for a
	// resolution, digits otherwise.
	Requested string
	// Limit is what the limit ran into, as text: the highest possible value
	// for a range, or the camera's list of values for a sample rate.
	Limit string
}

IncompatibleBound is the caller limit ruled out before the camera was asked. Mirrors matterjs-server packages/ws-client/src/models/model.ts:872-883 at 0bd06f2.

type IncompatibleError

type IncompatibleError struct {
	Reason IncompatibleReason
	// Track is the track that failed; "" for [ReasonNoMedia] and for
	// commands without tracks, such as a snapshot.
	Track Track
	// Feature is the AVSM feature the camera does not advertise, for
	// [ReasonFeature] only.
	Feature string
	// Bound is the caller limit that could not be met, for [ReasonBounds]
	// only and only when it was decided before asking the camera.
	Bound *IncompatibleBound
	// Device is the camera's codec names; empty when the camera did not
	// refuse (the offer did), not "supports nothing".
	Device []string
	// Requested is the codec names the caller asked for.
	Requested []string
	// DeviceStatus is the status the camera answered with, when a device
	// rejection produced the error.
	DeviceStatus *im.StatusCode
}

IncompatibleError is error 102: the camera, the offer or the request rules the stream out. Mirrors matterjs-server packages/ws-controller/src/types/WebSocketMessageTypes.ts:119-145 at 0bd06f2.

func (*IncompatibleError) Error

func (e *IncompatibleError) Error() string

Error is the reason's message.

type IncompatibleReason

type IncompatibleReason string

IncompatibleReason says what ruled a stream out. Mirrors matterjs-server packages/ws-client/src/models/model.ts:782-808 at 0bd06f2.

const (
	// ReasonCodec: the camera and the request (or its SDP offer) share no
	// codec.
	ReasonCodec IncompatibleReason = "codec"
	// ReasonBounds: the camera cannot meet a resolution, frame-rate or
	// bit-rate limit; [IncompatibleError.Bound] names it when it was
	// decided before asking the camera.
	ReasonBounds IncompatibleReason = "bounds"
	// ReasonFeature: the camera lacks a feature the request needs;
	// [IncompatibleError.Feature] names it.
	ReasonFeature IncompatibleReason = "feature"
	// ReasonCapability: the camera has the feature but reports nothing
	// usable, such as an empty snapshot capability list.
	ReasonCapability IncompatibleReason = "capability"
	// ReasonOffer: the SDP offer refuses the track, does not receive it, or
	// has no media section for it.
	ReasonOffer IncompatibleReason = "offer"
	// ReasonNoMedia: no track is left, so the session would carry no media.
	ReasonNoMedia IncompatibleReason = "no_media"
	// ReasonLevel: the decode level in the offer's a=fmtp line cannot be
	// read.
	ReasonLevel IncompatibleReason = "level"
)

The reasons of an *IncompatibleError, spelled as matterjs-server's error-102 payload spells them.

type Lease

type Lease struct {
	Kind           StreamKind
	ID             uint16
	Provenance     Provenance
	Degraded       bool
	Video          *VideoEnvelope
	Audio          *AudioEnvelope
	BudgetNarrowed *BudgetNarrowing
}

Lease is a stream a session carries: how it came to serve, and what it delivers (Video for a video stream, Audio for audio). Degraded: the stream misses the window the controller would have allocated.

type Limits

type Limits struct {
	MaxEncodedPixelRate   *uint32
	MaxConcurrentEncoders *uint8
	MaxNetworkBandwidth   *uint32
	SupportedStreamUsages []csdef.StreamUsageEnum
	StreamUsagePriorities []csdef.StreamUsageEnum
}

Limits is the camera's encoder and bandwidth limits and its stream usages.

type Mode

type Mode string

Mode is how a session's SDP exchange runs.

const (
	// ModeProvideOffer: the controller sent the host's offer; the camera
	// answers with an Answer signal.
	ModeProvideOffer Mode = "provide_offer"
	// ModeSolicitOffer: the controller asked the camera for an offer; the
	// camera sends an Offer signal, and the host answers with
	// [Session.ProvideAnswer].
	ModeSolicitOffer Mode = "solicit_offer"
)

The two modes, spelled as matterjs-server's wire spells them.

type NotSupportedError

type NotSupportedError struct {
	// Missing is the ids of the clusters the endpoint lacks.
	Missing []uint32
}

NotSupportedError is error 105: the endpoint lacks clusters camera streaming needs. Mirrors matterjs-server packages/ws-controller/src/types/WebSocketMessageTypes.ts:335-341 at 0bd06f2.

func (*NotSupportedError) Error

func (*NotSupportedError) Error() string

Error is matterjs-server's message for error 105.

type Observer

type Observer struct {
	// SessionEnded is every end of a session this controller holds.
	SessionEnded func(SessionEnd)
	// StreamEvicted is a stream a request deallocated to make room.
	StreamEvicted func(StreamEvicted)
	// Signal is a signal of a session no [Session] of this service holds:
	// one the raw provider route ([Provider]) opened, or a command the
	// requestor refused ([SignalRefused]).
	Signal func(Signal)
}

Observer is the camera effects no caller's own result reports; a nil field is not called. Each runs outside the service's locks, on the goroutine that decided it; it must not block. That goroutine can be the client stack's receive path — a new session registered at its offer's arrival ends a session the camera gave the same id before (EndCameraRestarted) there — so a callback must not call the Service or the node synchronously: a host that waits on the camera from SessionEnded deadlocks that camera's connection.

type OccupyingStream

type OccupyingStream struct {
	Kind           StreamKind
	StreamID       uint16
	ReferenceCount int
}

OccupyingStream is a stream that holds capacity a refused request needed. Its kind can differ from the request's: a refused snapshot allocation reports the video streams, which hold the encoders. Mirrors matterjs-server packages/ws-controller/src/types/WebSocketMessageTypes.ts:157-174 at 0bd06f2.

type Overlays

type Overlays struct {
	Watermark *bool
	OSD       *bool
}

Overlays are the watermark and on-screen display flags; nil is unstated, which is not the same as off.

type Privacy

type Privacy struct {
	SoftRecording  *bool
	SoftLivestream *bool
	Hard           *bool
}

Privacy is the camera's privacy switches (§11.2.7.20 to §11.2.7.22); nil is a switch the camera does not have.

type PrivacyError

type PrivacyError struct {
	// Modes names every switch that forbids the call, since the device
	// answers one status for all of them.
	Modes []PrivacyMode
	// DeviceStatus is the status the camera answered with.
	DeviceStatus im.StatusCode
}

PrivacyError is error 106: a privacy switch of the camera forbids the session or the snapshot. Mirrors matterjs-server packages/ws-controller/src/types/WebSocketMessageTypes.ts:176-183 at 0bd06f2.

func (*PrivacyError) Error

func (e *PrivacyError) Error() string

Error is matterjs-server's message for error 106, with the modes.

type PrivacyMode

type PrivacyMode string

PrivacyMode names one privacy switch of a camera. Mirrors matterjs-server packages/ws-client/src/models/model.ts:629-633 at 0bd06f2.

const (
	// PrivacySoftRecording is SoftRecordingPrivacyModeEnabled: it blocks a
	// session of stream usage Recording or Analysis.
	PrivacySoftRecording PrivacyMode = "soft_recording_mode_enabled"
	// PrivacySoftLivestream is SoftLivestreamPrivacyModeEnabled: it blocks a
	// session of stream usage LiveView, and every snapshot.
	PrivacySoftLivestream PrivacyMode = "soft_livestream_mode_enabled"
	// PrivacyHard is HardPrivacyModeOn, the physical switch: it blocks every
	// session and every snapshot.
	PrivacyHard PrivacyMode = "hard_mode_on"
)

The three privacy switches (§11.2.7.20 to §11.2.7.22).

type Provenance

type Provenance string

Provenance says how a stream came to serve a request.

const (
	// ProvenanceAllocated: this request allocated the stream.
	ProvenanceAllocated Provenance = "allocated"
	// ProvenanceReused: a stream this controller allocated earlier.
	ProvenanceReused Provenance = "reused"
	// ProvenanceAdopted: a stream another controller, or an earlier run of
	// this one, allocated.
	ProvenanceAdopted Provenance = "adopted"
)

The three provenances, spelled as matterjs-server's wire spells them.

type Provider

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

Provider is the raw route to one camera's WebRtcTransportProvider: the cluster's own commands for a host that allocates its streams itself, or re-offers a live session. A session it opens is registered with the controller's requestor, so the camera's signals arrive, on Observer.Signal, since no Session holds it; the service's Close ends it.

func (*Provider) EndSession

func (p *Provider) EndSession(ctx context.Context, req wpdef.EndSessionRequest, requestedBy string) error

EndSession is a host's own EndSession for a session of the camera (a generic device command): it is sent as given, its error passed on, and the controller's records for the session go with it, the end announced as Service.StopSession announces one. requestedBy is the owner asking. After the service's Close it is ErrClosed, as Service.StopSession is. Mirrors matterjs-server packages/ws-controller/src/camera/CameraStreamManager.ts:2303-2321 at 0bd06f2.

func (*Provider) Send

func (p *Provider) Send(ctx context.Context, command string, payload json.RawMessage) (result any, notices []string, err error)

Send sends ProvideOffer, SolicitOffer, ProvideAnswer or ProvideIceCandidates with payload, a JSON object of the command's fields as matter.js names them (keys matched with case and word separators ignored), checked against the cluster's model. An offer gets the controller's requestor endpoint as its originating endpoint, its stream fields reconciled with the camera's cluster revision, and its session registered with the requestor. The result is the generated response (wpdef.ProvideOfferResponse, wpdef.SolicitOfferResponse) or nil; notices are what the boundary forwarded unchanged that the camera may ignore. After the service's Close it is ErrClosed and sends nothing: a session it opened then is one nothing would end (review II, R2-P1-cam-b-04). Mirrors matterjs-server's send_webrtc_provider_command (docs/websockets_api.md:1868-1900 of matterjs-server at 0bd06f2).

type Reports

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

Reports brings the cameras' reports to a Service: each node's applied report batch (its subscription alive), its StartUp event, a new endpoint and its removal from the fabric. Install it on the controller's configuration before controller.New — the node hooks are fixed when a node is built — and pass it in Config.Reports. matterjs-server feeds the same four from its controller's node events (packages/ws-controller/src/controller/WebRtcProviderSessions.ts:120-155 at 0bd06f2).

var reports camera.Reports
reports.Install(&cfg)
ctrl, err := controller.New(ctx, cfg)
…
svc, err := camera.New(ctx, ctrl, camera.Config{Reports: &reports})

One Service at a time holds a Reports: New refuses one a Service that is not closed holds.

func (*Reports) Install

func (r *Reports) Install(cfg *controller.Config)

Install wraps cfg's node hooks — cfg.HooksFor, else the template cfg.Node.Hooks; the host's hooks run first and keep their behaviour. Installing it again on the same configuration changes nothing (review II, R2-P6-api-2208).

type ResolutionTarget

type ResolutionTarget struct {
	Width, Height uint16
}

ResolutionTarget is a snapshot size a host wants: at least one side stated, 0 unstated.

type Service

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

Service is the controller side of Matter camera streaming over one controller: it picks, allocates, reuses and frees a camera's streams, opens the WebRTC sessions on them as the controller's one operational identity, keeps the controller's WebRtcTransportRequestor table in step, routes each camera signal to its Session, and ends the sessions a camera holds for this controller that nothing here does. It is safe for concurrent use; Service.Close ends it. Mirrors matterjs-server's camera stream management at 0bd06f2 (packages/ws-controller/src/camera, packages/ws-controller/src/controller/WebRtcProviderSessions.ts).

func New

func New(ctx context.Context, ctrl *controller.Controller, cfg Config) (*Service, error)

New starts a service over ctrl, attaching to its requestor (ctrl.CameraRequestor) and its signals (ctrl.OnCameraSignal). It refuses a controller without a requestor (ErrNoRequestor), without outgoing TCP (ErrTCPRequired), a Config whose Reports were not installed (ErrReportsNotInstalled) and one whose Reports a Service that is not closed holds (ErrReportsInUse, which also matches ErrInvalidArgument): the first would stop getting its reports (review II, R2-P6-api-2208).

func (*Service) Capabilities

func (s *Service) Capabilities(ctx context.Context, node *client.Node, endpoint uint16) (*Capabilities, error)

Capabilities reads what the camera endpoint states and holds; after Close it is ErrClosed (review II, R2-P6-api-2207). Mirrors matterjs-server packages/ws-controller/src/camera/CameraStreamManager.ts:969-1034 at 0bd06f2.

func (*Service) Close

func (s *Service) Close(ctx context.Context) error

Close ends every session this service holds, stops its sweeps and detaches it from the controller. The sessions it ends are the ones Service.StartStream opened and every other session of the controller's requestor on this fabric — those a host opened through Provider.Send — each with an EndSession (UserHangup) within one cleanup budget, announced as EndReleased (review II, R2-P6-fsm-2202). A raw provider command in flight is waited for; an offer of one answered once Close began ends its session instead of keeping it (review II, R2-P2-stop-03). The wait for those commands is bounded by ctx: a Close whose ctx ends first returns ctx's error and leaves the service closing — the rest of the teardown runs once the commands returned — and a later Close waits for it again. A second Close returns once the teardown finished, or with ctx's error when ctx ends first.

func (*Service) Provider

func (s *Service) Provider(node *client.Node, endpoint uint16) (*Provider, error)

Provider is the raw route to the camera endpoint.

func (*Service) Release

func (s *Service) Release(ctx context.Context, owner string)

Release ends every session owner holds or is starting, as a host does when the owner goes away; only EndSession lowers a stream's ReferenceCount. After Close it stays callable — the one camera-acting method that does: Close claimed every session, so it finds none, or retries the EndSession of one whose end failed at Close. Mirrors matterjs-server packages/ws-controller/src/camera/CameraStreamManager.ts:2327-2331 at 0bd06f2.

func (*Service) ReleaseStream

func (s *Service) ReleaseStream(ctx context.Context, node *client.Node, endpoint uint16, kind StreamKind, id uint16) error

ReleaseStream deallocates one stream, passing the camera's answer on; a stream the camera still references is ErrStreamInUse (an *InUseError). After Close it is ErrClosed and sends nothing (review II, R2-P6-api-2207). Mirrors matterjs-server packages/ws-controller/src/camera/CameraStreamManager.ts:2702-2736 at 0bd06f2.

func (*Service) Snapshot

func (s *Service) Snapshot(ctx context.Context, req SnapshotRequest) (*Snapshot, error)

Snapshot captures one still frame from a snapshot stream the camera keeps, adopting one within the request's bounds or allocating one. After Close it is ErrClosed and allocates nothing (review II, R2-P1-cam-b-04). Mirrors matterjs-server packages/ws-controller/src/camera/CameraStreamManager.ts:2389-2649 at 0bd06f2.

func (*Service) StartStream

func (s *Service) StartStream(ctx context.Context, req StartRequest) (*Session, error)

StartStream resolves the session's streams — reuse, allocate, narrow, evict, degrade — and opens the WebRTC session with ProvideOffer (Offer set) or SolicitOffer, as the controller's identity: the camera stores RootNodeID as the session's peer and signals back to the controller's requestor. Mirrors matterjs-server packages/ws-controller/src/camera/CameraStreamManager.ts:1955-2171 at 0bd06f2.

func (*Service) StopByKey

func (s *Service) StopByKey(ctx context.Context, node *client.Node, endpoint uint16, owner, key string) (bool, error)

StopByKey stops the session owner started with key on the node and endpoint; a start still running is cancelled (its StartStream fails) and this answers once it gave up. false when the key names no session of the owner, or the camera held none. After Close, which ended the service's sessions, it is ErrClosed and sends nothing (review II, R2-P6-api-2207). Mirrors matterjs-server packages/ws-controller/src/camera/CameraStreamManager.ts:2213-2230 at 0bd06f2.

func (*Service) StopSession

func (s *Service) StopSession(ctx context.Context, node *client.Node, endpoint, id uint16, requestedBy string) (bool, error)

StopSession ends a session by its id, whoever opened it: false when the camera answered NOT_FOUND. requestedBy is the owner asking ("" for none); the end is announced to the session's owner naming it. After Close, which ended the service's sessions, it is ErrClosed and sends nothing (review II, R2-P1-cam-b-04). Mirrors matterjs-server packages/ws-controller/src/camera/CameraStreamManager.ts:2243-2269 at 0bd06f2.

type Session

type Session struct {
	ID       uint16
	Node     *client.Node
	Endpoint uint16
	Mode     Mode
	// Streams are the session's video and audio streams.
	Streams []Lease
	// Evicted are the video streams the start deallocated to make room.
	Evicted []uint16
	// Talkback: the host asked for it, the offer's audio can send, the
	// camera states half or full duplex and the session carries audio.
	Talkback bool
	Owner    string
	Key      string
	// contains filtered or unexported fields
}

Session is a WebRTC session the service opened. Signals carries the camera's half of the signalling, from the camera's first signal on — one sent before StartStream returned is kept — and is closed once the session ended, whatever ended it.

func (*Session) ProvideAnswer

func (s *Session) ProvideAnswer(ctx context.Context, sdp string) error

ProvideAnswer sends the host's SDP answer to a camera's Offer (ModeSolicitOffer); it travels over TCP (the command's Large Message quality). After the service's Close it is ErrClosed (review II, R2-P6-api-2207).

func (*Session) ProvideICECandidates

func (s *Session) ProvideICECandidates(ctx context.Context, candidates []wpdef.ICECandidateStruct) error

ProvideICECandidates sends the host's candidates, in order, in as many ProvideICECandidates as keep each within one Matter message over UDP; every send is made, and the first failure is returned. After the service's Close it is ErrClosed (review II, R2-P6-api-2207).

func (*Session) Signals

func (s *Session) Signals() <-chan Signal

Signals is the camera's signalling of the session. The service holds what the host has not read yet up to 1024 signals and 1 MiB of SDP, candidate and ICE server text; a camera that signals past either bound while the host does not read ends the session: Signals closes at once, without the signals it held, and the end is announced as EndSignalOverflow after an EndSession to the camera. Once the session ended otherwise, what the host has not read within ten seconds of the end — the camera's End among it — is discarded and Signals closes (review II, R2-P6-bound-2206): a host that reads its Signals gets every signal, and one that dropped its Session holds nothing past the grace.

func (*Session) Stop

func (s *Session) Stop(ctx context.Context) (ended bool, err error)

Stop ends the session on the camera; its streams stay allocated for a later start. ended false: the camera no longer held it (NOT_FOUND). A refused EndSession is returned; the session stays open then, and Stop again is the retry. After the service's Close, which ended its sessions, it is ErrClosed and sends nothing (review II, R2-P6-api-2207); Service.Release retries an end Close could not make.

type SessionEnd

type SessionEnd struct {
	NodeID      uint64
	Endpoint    uint16
	SessionID   uint16
	Cause       EndCause
	Reason      *uint8
	RequestedBy string
	Owner       string
	Key         string
}

SessionEnd is the end of a session. Owner and Key are the session's owner and its key ("" for a session without an owner, which every owner hears of).

type Signal

type Signal = controller.CameraSignal

Signal is one command a camera invoked on the controller's requestor: its Offer, Answer, ICECandidates or End, or the requestor's refusal of one for a session it does not hold (SignalRefused). An Answer's SDP is narrowed to the directions of the offer the controller sent.

type Snapshot

type Snapshot struct {
	Data       []byte
	Codec      csdef.ImageCodecEnum
	Resolution csdef.VideoResolutionStruct
	Degraded   bool
	StreamID   uint16
	Provenance Provenance
}

Snapshot is one still frame and the stream it came from, which the camera keeps. Degraded: the frame is smaller than the best the request allowed.

type SnapshotRequest

type SnapshotRequest struct {
	Node     *client.Node
	Endpoint uint16
	// MaxResolution is a ceiling on the frame.
	MaxResolution *csdef.VideoResolutionStruct
	// Resolution is the size the host wants; the camera gets the closest
	// it can give.
	Resolution *ResolutionTarget
	Codec      *csdef.ImageCodecEnum
	Overlays   Overlays
}

SnapshotRequest is one still frame. Nil fields are unstated.

type StackError

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

StackError is a failure of the controller's own — a broken device answer, a session given up: matterjs-server's error 7, SDKStackError (packages/ws-controller/src/types/WebSocketMessageTypes.ts:94 at 0bd06f2), the "any other error" a host maps that code onto. Exported so a host matches it with errors.As.

func (*StackError) Error

func (e *StackError) Error() string

type StartRequest

type StartRequest struct {
	Node     *client.Node
	Endpoint uint16
	// Usage is the session's stream usage: Recording, Analysis or
	// LiveView (Internal is the camera's own).
	Usage csdef.StreamUsageEnum
	// Offer is the host's SDP offer (ModeProvideOffer); nil asks the
	// camera for one (ModeSolicitOffer).
	Offer *string
	// Video demands a video stream within its bounds; nil takes one when
	// available. DeclineVideo asks for none.
	Video        *VideoBounds
	DeclineVideo bool
	// Audio demands an audio stream; nil takes one when available.
	// DeclineAudio asks for none.
	Audio        *AudioBounds
	DeclineAudio bool
	// ICEServers and ICETransportPolicy go to the camera as stated.
	ICEServers         []wpdef.ICEServerStruct
	ICETransportPolicy string
	MetadataEnabled    bool
	// AllowEviction lets the start deallocate an unused stream to make
	// room; nil allows it.
	AllowEviction *bool
	// Talkback forwards the offer's sending audio sections unchanged;
	// without it they are rewritten not to send. It needs an Offer.
	Talkback bool
	// Owner is who the session belongs to, as the host names it (a
	// connection); its sessions end with [Service.Release]. Key is the
	// owner's own name for the session, unique among its starting and open
	// sessions, which [Service.StopByKey] takes.
	Owner string
	Key   string
}

StartRequest is one session start. A zero numeric bound and a nil pointer are unstated.

type StreamEvicted

type StreamEvicted struct {
	NodeID   uint64
	Endpoint uint16
	Kind     StreamKind
	StreamID uint16
}

StreamEvicted is a stream a request deallocated to make room. Mirrors matterjs-server packages/ws-controller/src/camera/cameraTypes.ts:158-164 at 0bd06f2.

type StreamKind

type StreamKind string

StreamKind is the kind of a camera stream.

const (
	StreamVideo    StreamKind = "video"
	StreamAudio    StreamKind = "audio"
	StreamSnapshot StreamKind = "snapshot"
)

The three stream kinds.

type Track

type Track string

Track names the track of a session start that failed.

const (
	TrackVideo Track = "video"
	TrackAudio Track = "audio"
)

The two tracks of a session start.

type VideoBounds

type VideoBounds struct {
	// Codecs are the codecs the host accepts, in its order of preference,
	// as SDP spells them (H264, H265, …); nil is any.
	Codecs                       []string
	MinResolution, MaxResolution *csdef.VideoResolutionStruct
	MinFrameRate, MaxFrameRate   *uint16
	MinBitRate, MaxBitRate       *uint32
	Overlays                     Overlays
}

VideoBounds are a start's video bounds; each stated one is hard. A nil field is unstated; a stated one is held to its field's range in the cluster's model, so a stated 0 is refused where the floor is 1, as matterjs-server refuses it (toOptionalNumber against CAMERA_FIELD_RANGES, cameraCommands.ts:378-382 and cameraFieldRanges.ts:48-56 at 0bd06f2).

type VideoCapabilities

type VideoCapabilities struct {
	Sensor               *csdef.VideoResolutionStruct
	MaxFPS               *uint16
	MaxHDRFPS            *uint16
	HDRCapable           *bool
	MinViewport          *csdef.VideoResolutionStruct
	RateDistortionPoints []csdef.RateDistortionTradeOffPointsStruct
	Codecs               []csdef.VideoCodecEnum
}

VideoCapabilities is the camera's video. Codecs are the codecs of RateDistortionPoints, each once, in their order.

type VideoEnvelope

type VideoEnvelope struct {
	Codec                        csdef.VideoCodecEnum
	MinResolution, MaxResolution csdef.VideoResolutionStruct
	MinFrameRate, MaxFrameRate   uint16
	MinBitRate, MaxBitRate       uint32
	KeyFrameInterval             uint16
	// Overlays are nil when the stream has no such overlay.
	Overlays Overlays
}

VideoEnvelope is what a video stream delivers.

Directories

Path Synopsis
Package cameratest is a test camera for a host's in-process tests of controller/camera: a Camera device to bridge into a fabrictest site, and the scripted Port it serves its WebRTC transport and its streams on.
Package cameratest is a test camera for a host's in-process tests of controller/camera: a Camera device to bridge into a fabrictest site, and the scripted Port it serves its WebRTC transport and its streams on.

Jump to

Keyboard shortcuts

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