hub

package
v0.2.0 Latest Latest
Warning

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

Go to latest
Published: Oct 24, 2026 License: AGPL-3.0 Imports: 2 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 hub broadcasts MPEG-TS chunks from one camera goroutine to any number of HTTP clients.

It is the boundary that decides whether a slow client can hurt a camera. Neolink's per-consumer queues were unbounded, and a client that stopped reading (a stalled browser tab, a dead TCP connection the kernel had not noticed yet) grew forever until the process ran out of memory. This hub never lets that happen: a subscriber that cannot keep up is disconnected, not buffered.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type FrameStats

type FrameStats struct {
	FPS          float64
	BitrateBps   float64
	LastFrameAt  time.Time
	ConnectedAt  time.Time
	AudioFrames  int
	DroppedAudio int
}

FrameStats is a stream's throughput and health, as last reported by whatever is publishing to this hub.

The hub does not compute any of this itself: it has no idea whether a published chunk is video or audio, or whether a frame just got dropped for an unsupported codec, only internal/stream does. Pushing the numbers up from there, rather than the hub or internal/server reaching down past it, is what keeps a hub a plain byte broadcaster and keeps HTTP concerns out of internal/stream.

func (FrameStats) Age

func (s FrameStats) Age() time.Duration

Age reports how long ago the last frame was recorded, falling back to how long the current connection attempt has been open if no frame has arrived yet, or zero if there is no active connection at all.

The fallback exists because of a real incident, not a hypothetical one: a stream that connects and then never delivers a single frame (a camera holding a stale session, answering login but never sending media) has a zero LastFrameAt forever, and a zero-valued time.Time reports Age 0 just like a stream that published a frame an instant ago. Both looked identically healthy on /api/status during the 2026-09-08 incident. Falling back to ConnectedAt means a stream stuck since the moment it connected shows a growing, honest age instead of a permanent, misleading 0.

func (FrameStats) Seen added in v0.1.2

func (s FrameStats) Seen() bool

Seen reports whether this stream has ever connected or delivered a frame.

This is the other half of the hole Age's fallback closes. Age can only measure from a moment that happened, so a stream that has never had one, a camera that is powered off or at an address nothing answers, reports age 0, and 0 is indistinguishable from a frame that arrived this instant. A camera configured at an unreachable address therefore read as healthy indefinitely: connected, streaming, zero restarts, age 0.

Callers deciding whether a stream is live have to ask this first.

type Hub

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

Hub fans out frames to subscribers. The zero value is not usable; build one with New.

func New

func New(buffer int) *Hub

New creates a Hub whose subscriber channels each hold up to buffer frames before being considered stalled.

func (*Hub) AddAudioFrames

func (h *Hub) AddAudioFrames(n int)

AddAudioFrames adds n to the running count of audio frames actually muxed and published. Every stream now declares an audio track whether or not its camera ever sends one (see NewMuxerWithAudio), so DroppedAudio alone cannot tell "no audio arrives" from "audio is flowing fine": both read as 0. AudioFrames closes that gap. A camera with AudioFrames > 0 has working audio; one with AudioFrames == 0 and DroppedAudio == 0 sends no audio at all, which is a config or wiring question, not a codec one; DroppedAudio > 0 on its own means audio arrives but in a codec that gets discarded. All three are distinguishable only with both counters present.

func (*Hub) AddDroppedAudio

func (h *Hub) AddDroppedAudio(n int)

AddDroppedAudio adds n to the running count of audio frames dropped for lacking a supported codec (see ts.Muxer.DroppedAudio). This total lives on the hub, not the muxer, because a muxer is rebuilt on every reconnect: a camera stuck sending ADPCM would otherwise look healthy again after every backoff cycle, resetting to 0 each time, which is exactly the kind of silent-audio condition this counter exists to catch.

func (*Hub) Clients

func (h *Hub) Clients() int

Clients returns the current subscriber count.

func (*Hub) Close

func (h *Hub) Close()

Close closes every current subscriber's channel and marks the hub closed, so a later Publish or Subscribe is a no-op rather than a send on, or a registration into, a hub nobody is going to deliver to again.

Call this when the stream feeding the hub stops. Without it, an HTTP handler blocked in its read select (internal/server) only notices its stream is gone when its request context is cancelled, which on shutdown is the full 5 second timeout rather than an immediate close.

func (*Hub) Dropped

func (h *Hub) Dropped() int

Dropped returns the total number of subscribers disconnected for falling behind, since the Hub was created.

func (*Hub) Header

func (h *Hub) Header() []byte

Header returns the current cached header, or nil if none has been set yet.

func (*Hub) Keyframe

func (h *Hub) Keyframe() (codec string, es []byte)

Keyframe returns the most recently recorded keyframe and its codec, or ("", nil) if no video keyframe has arrived yet.

func (*Hub) KeyframeAt added in v0.2.0

func (h *Hub) KeyframeAt() time.Time

KeyframeAt is when the last keyframe arrived (zero if none has).

func (*Hub) Kick added in v0.2.0

func (h *Hub) Kick()

Kick ends every current subscriber without closing the hub, so a battery camera's session can be stopped while the hub, and the last keyframe it holds, stays for the next wake.

func (*Hub) MarkConnected

func (h *Hub) MarkConnected()

MarkConnected records that a new connection attempt has begun, for Age's fallback (see FrameStats.Age). Call it once a stream has actually asked the camera for video, not at dial time: StartVideo succeeding is the moment a held session first has the chance to go silent forever, and is the same moment the supervisor's Connected/Running status starts reporting true, so the two stay consistent.

func (*Hub) MarkDisconnected

func (h *Hub) MarkDisconnected()

MarkDisconnected zeroes the fps and bitrate gauges, and clears the connected-at fallback Age uses. Call it whenever the stream feeding this hub stops, whether for good or just for the next backoff cycle: without this, a camera that drops off mid-stream keeps reporting its last known rate on /api/status and /metrics forever, looking healthy to anyone glancing at fps or bitrate alone rather than cross-checking last_frame_age_seconds too. Clearing ConnectedAt matches that: a stream that is not currently attempting a connection at all should report Age 0, not a duration that keeps growing across an entire backoff cycle as if it were still the stuck-since-connect case Age's fallback exists for. AudioFrames and DroppedAudio are untouched: those are cumulative health counters meant to survive a reconnect, not an instantaneous rate.

func (*Hub) OnDemand added in v0.2.0

func (h *Hub) OnDemand() bool

OnDemand reports whether subscribing to this hub wakes a battery camera. The public listeners refuse such a hub, so only a signed-in viewer can.

func (*Hub) Publish

func (h *Hub) Publish(b []byte)

Publish delivers b to every synced subscriber, meaning "not a keyframe boundary": it is PublishKey(b, false). Every caller that has no notion of keyframes, audio in particular, calls this directly.

func (*Hub) PublishKey

func (h *Hub) PublishKey(b []byte, startsKeyframe bool)

PublishKey delivers b to every subscriber, gated by whether that subscriber has synced to the stream yet. A subscriber that joins mid GOP must not receive anything until startsKeyframe is true for it: see subscriber.synced for why this is measured, not theoretical. Once a subscriber has synced, every later call, keyframe or not, delivers to it normally; startsKeyframe only matters for the transition.

It never blocks: a subscriber whose buffer is full is dropped instead of stalling this call, because this is called from the camera's read goroutine and any delay here is a delay in draining the socket.

b is not copied per subscriber. The MPEG-TS muxer (internal/ts) allocates a fresh slice for every chunk it returns, so subscribers never see a buffer that gets mutated out from under them. A caller that reused buffers would need this to change.

func (*Hub) RecordFrame

func (h *Hub) RecordFrame(n int)

RecordFrame reports that n bytes of a published packet came from a video frame, for fps and bitrate. It is not the same call as Publish: a caller still calls Publish separately to actually deliver the bytes, since a muxer's PAT/PMT repeats and PCR-only packets also flow through Publish but are not a "frame" in any sense worth counting here.

fps and bitrate are only ever computed from video: audio here is a constant-rate AAC track with no frame-rate concept worth reporting alongside it, and folding its bytes into "bitrate" would make the number jump depending on whether the camera happens to be sending audio this second, without saying why.

func (*Hub) RestoreKeyframe added in v0.2.0

func (h *Hub) RestoreKeyframe(codec string, es []byte, at time.Time)

RestoreKeyframe puts back a keyframe saved before a restart, with the time it was taken, so a sleeping camera still has its last picture.

func (*Hub) SetHeader

func (h *Hub) SetHeader(b []byte)

SetHeader records the MPEG-TS PAT/PMT pair a new subscriber should be sent before any live data. It is set once the muxer has seen the first frame and knows the codec; before that Header returns nil, and callers must not turn a nil header into an empty write.

This is one snapshot, not a header rebuilt per joiner. Its PAT/PMT continuity counters are frozen at whatever they were the moment the caller built b, while the in-band PAT/PMT the muxer repeats every tableRepeatTicks keep advancing theirs (see ts.Muxer.Header). A joining client sees one continuity jump on PIDPAT and PIDPMT at join time, never again. ffmpeg does not check PSI continuity; a demuxer built strictly to the T-STD model can log it, but a table PID discontinuity carries no decode consequence the way one on PIDVideo would. Rebuilding it per joiner would mean the hub calling back into ts.Muxer for fresh counters, which does not fit the hub's job of only ever moving bytes it is handed; one cosmetic counter jump is cheaper than that coupling.

func (*Hub) SetKeyframe

func (h *Hub) SetKeyframe(codec string, es []byte)

SetKeyframe records the most recent video keyframe's raw elementary stream bytes (baichuan.Frame.Video, not muxed into any container) along with the codec they are encoded in, "h264" or "h265" matching ts.NewMuxer's own spelling. internal/server's snapshot endpoint reads this back to answer a health check without opening a stream, which would cost a client slot and a keyframe wait for no reason: a still only needs the bytes that are already sitting here.

es is not copied. internal/baichuan.Depacketiser allocates a fresh Data slice per frame (see its Next), so this never ends up holding a buffer that gets overwritten by the next frame out from under a concurrent reader.

func (*Hub) SetOnDemand added in v0.2.0

func (h *Hub) SetOnDemand(on bool)

SetOnDemand marks a hub whose stream only runs while someone watches: a battery camera's. See OnDemand.

func (*Hub) Stats

func (h *Hub) Stats() FrameStats

Stats returns a snapshot of the hub's current frame statistics.

func (*Hub) Subscribe

func (h *Hub) Subscribe() (<-chan []byte, func())

Subscribe registers a new listener and returns its channel along with a cancel function to unsubscribe. The cancel function is safe to call more than once, and safe to call concurrently with a Publish that is dropping the same subscriber: both paths call closeOnce, which only one of them wins.

Jump to

Keyboard shortcuts

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