ts

package
v0.2.16 Latest Latest
Warning

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

Go to latest
Published: Dec 1, 2026 License: AGPL-3.0 Imports: 6 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 ts muxes decoded camera frames into an MPEG-TS byte stream.

It does no I/O. Frames go in, 188 byte transport packets come out, which makes the timing arithmetic here exhaustively testable. That matters more than it sounds: getting timestamps wrong is not a subtle degradation, it produces streams that report impossible frame rates and players that drop thousands of frames.

Index

Constants

View Source
const (
	StreamTypeH264 byte = 0x1B
	StreamTypeHEVC byte = 0x24
	StreamTypeAAC  byte = 0x0F
)

Stream types as registered in the MPEG systems tables.

View Source
const PacketSize = 188

PacketSize is fixed by the transport stream format.

Variables

This section is empty.

Functions

This section is empty.

Types

type AudioClock

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

Audio arrives from these cameras with no timestamp whatsoever. The media packet header for AAC and ADPCM is 8 bytes, magic(4) size(2) size(2), with no field for a capture time anywhere in it, unlike the 24 and 32 byte video headers which carry microseconds at offset 16. So an audio frame's Micros is not a different epoch from video's, it is the zero value, and there is nothing on the wire to recover it from. Its position in time has to be reconstructed here.

The reconstruction is the audio's own sample clock. Every AAC frame these cameras emit is ADTS, and an ADTS header states the sample rate and how many raw data blocks the frame holds, so the frame's duration in samples is exact and free. Counting samples from an anchor taken off the video timeline gives audio a PTS that advances at the audio's real rate while starting in step with the picture. Observed on the committed capture: 16 kHz mono AAC-LC, one 1024 sample block per frame, so 64ms and 5760 ticks per frame; 56 audio frames span 3.584s against 89 video frames at about 24.9fps spanning 3.57s, which is how the rate was confirmed rather than assumed.

Anchoring to video rather than free-running from zero is the whole point. Two independent clocks each rebased to their own first frame would remove the false wraps and silently destroy lip sync, which is a worse bug: it is invisible until a recording is reviewed weeks later.

func NewAudioClock

func NewAudioClock() *AudioClock

func (*AudioClock) PTS

func (a *AudioClock) PTS(videoPTS uint64, adts []byte) uint64

PTS returns the presentation timestamp for one AAC frame, given the video stream's current position (Clock.LastPTS) and the frame's ADTS bytes.

func (*AudioClock) PTSAt added in v0.2.8

func (a *AudioClock) PTSAt(at uint64, adts []byte) uint64

PTSAt is PTS for a frame whose own place on the video timeline is known: at, in 90 kHz ticks. A presence stream knows it for the audio of a clip it plays in (internal/presence). The samples are still counted, so the step from frame to frame stays exact, but the count is held to the stated place rather than to within a second of the picture: it starts there, and is re-anchored there whenever it is off by more than half a frame, after a reader joins mid stream for one.

type Clock

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

Clock converts the camera's capture time into MPEG-TS presentation timestamps.

Two things make this more than a multiplication. The camera's clock starts at an arbitrary value, so the first frame is rebased to zero. And Micros is a uint32 of microseconds, so it wraps roughly every 71.6 minutes; an unnoticed wrap makes PTS jump backwards mid stream.

One Clock carries exactly one timestamped elementary stream. Its wrap detector is a single backward-step test against the previous value it was handed, so feeding it two sources of timestamps makes every alternation between them look like a step backwards. Video is the only stream these cameras timestamp at all (see AudioClock), so in this package that means video frames and nothing else. This is not a style preference: a build that fed audio frames through here counted a false wrap on every audio frame once the camera's uptime passed wrapThreshold, and each false wrap added 2^32 microseconds to every PTS after it. Measured against a live camera, that was 2,265 ffmpeg timestamp discontinuities in 60 seconds.

func NewClock

func NewClock() *Clock

func (*Clock) Followed added in v0.2.9

func (c *Clock) Followed() uint64

Followed reports how many times the clock switched from the camera's own time to arrival time. The stream logs a rise.

func (*Clock) Held added in v0.2.7

func (c *Clock) Held() uint64

Held reports how many frames were given the previous timestamp because the camera's time went backwards. A run of them shows in a player as a frozen picture while the stream itself looks healthy (#25), so the stream logs it.

func (*Clock) LastPTS

func (c *Clock) LastPTS() uint64

LastPTS is the most recent timestamp this clock emitted, which is the stream's current position on the presentation timeline. AudioClock uses it to place audio frames, which arrive with no timestamp of their own.

func (*Clock) PTS

func (c *Clock) PTS(micros uint32) uint64

PTS returns the 90 kHz presentation timestamp for a frame captured at the given camera time.

func (*Clock) Resume added in v0.1.4

func (c *Clock) Resume(gap time.Duration)

Resume tells the clock the camera connection was re-established and the next reading starts a new camera timeline: the camera may have rebooted, in which case its microsecond counter has started over from a small value.

Through the wrap detector a restart is either a backward step too small to count as a wrap, which the clamp below turns into a frozen PTS until the new counter passes the old one (up to 35 minutes), or a step large enough to count as one, which throws the PTS forward by up to 71 minutes. Both were reproduced against the RTSP output after the fleet's weekly scheduled reboot. Both outputs outlive the camera connection, the RTSP session and the MPEG-TS muxer alike (see Muxer.Resume), so each tells its clock.

gap is how long the camera was away, measured by the caller on the wall clock. The timeline continues from the last PTS plus that gap, so a reader sees the outage as the pause it was rather than as a seek, and a recorder keeps its segment timing honest. A clock that has emitted nothing yet is unaffected: its first frame still maps to zero.

func (*Clock) UseArrival added in v0.2.9

func (c *Clock) UseArrival(now func() time.Time)

UseArrival gives the clock the wall clock, read once per frame as that frame's arrival, so a camera whose own timestamps run off from real time can be followed by arrival instead.

The case that needs it is an RLC-823S2 at night (#33): it sends about 13 frames a second but stamps each one 40 ms after the last, as if it were still sending 25. Its clock falls behind real time by about half a second every second, and every 12 s or so it jumps forward 5 to 6 s to catch up. Through camera time alone each jump is a 5 to 6 s hole in both outputs, and in between the picture plays at nearly twice speed.

The signature is a single frame on which the camera's time steps forward by more than jumpAhead while its arrival came only a frame later, after arrival time had been gaining on camera time steadily, frame by frame (creep). A network stall is the opposite shape: arrival leaps while camera time steps a frame, so it neither counts as creep nor looks like a jump, and the timeline keeps the camera's own timing through it, as before. A camera whose clock keeps real time never trips this, and its PTS is exactly what camera time alone gives.

Once tripped, PTS advances by arrival for as long as the camera's time and arrival keep disagreeing, and goes back to the camera's own timing, carrying on from where arrival left it, after agreeWindow in which the two agreed to within agreeSlack: the same camera keeps proper time by day. Audio needs nothing of its own here: AudioClock anchors to this clock's LastPTS, so it follows whichever timing video is on.

Without it (nil, the default) the clock is camera time only, which is what a muxer replaying frames faster than real time needs.

func (*Clock) Wraps

func (c *Clock) Wraps() uint64

Wraps reports how many times this clock has decided the camera's microsecond counter rolled over. On a stream shorter than 71.6 minutes it must be zero, which is what makes it a usable assertion in tests: a nonzero count on a short stream means the wrap detector fired on something that was not a wrap.

type Muxer

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

Muxer turns decoded camera frames into an MPEG-TS byte stream. It holds no socket and does no I/O: callers own delivery, this just produces bytes.

func NewMuxer

func NewMuxer(codec string) (*Muxer, error)

NewMuxer builds a muxer for the given codec, "h264" or "h265", matched case insensitively. baichuan.Frame.Codec comes off the wire as "H264"/"H265", while docs, tests and a future TOML config all write it lowercase; folding the case here, at the one place every caller must pass through, means a caller does not need to remember to normalize it and a config value like "H265" fails as an unsupported-codec message would read like a camera fault instead of a config typo.

func NewMuxerWithAudio

func NewMuxerWithAudio(videoCodec, audioCodec string) (*Muxer, error)

NewMuxerWithAudio builds a muxer that also carries an audio track on its own PID. audioCodec is matched case insensitively for the same reason videoCodec is in NewMuxer.

Only "aac" is accepted. These cameras also emit ADPCM, which has no registered MPEG-TS stream type; the previous tool silently dropped audio entirely regardless of the recorder's configured role, and nothing ever alerted on it. Relabeling ADPCM as AAC would decode as noise, and transcoding it would put ffmpeg back in the serving path, which this project exists to avoid. So an ADPCM frame is counted (DroppedAudio) and dropped, never silently accepted.

func (*Muxer) Carries added in v0.2.6

func (m *Muxer) Carries(codec string, audio bool) bool

Carries reports whether this muxer is the one for codec, with or without an AAC track as audio says.

func (*Muxer) DroppedAudio

func (m *Muxer) DroppedAudio() int

DroppedAudio reports how many audio frames were dropped for lack of a supported codec, such as ADPCM. It should stay zero on a healthy stream configured with an audio role; a climbing count means the camera is sending a codec this muxer cannot carry.

func (*Muxer) FollowArrival added in v0.2.9

func (m *Muxer) FollowArrival(now func() time.Time)

FollowArrival lets the video clock follow frames' arrival on the wall clock when the camera's own time jumps ahead of it (see Clock.UseArrival). It carries over Recodec, which shares the clock.

func (*Muxer) FollowedArrival added in v0.2.9

func (m *Muxer) FollowedArrival() uint64

FollowedArrival is the video clock's Clock.Followed.

func (*Muxer) Frame

func (m *Muxer) Frame(f baichuan.Frame) []byte

Frame encodes one decoded camera frame, returning the transport packets to send. Video frames go on PIDVideo; an audio frame goes on PIDAudio if this muxer was built with NewMuxerWithAudio and the codec matches what it was built for, otherwise it is dropped (silently for a muxer that never declared audio at all, counted via DroppedAudio when audio was declared but the frame's codec, such as ADPCM, is not carried). Info frames and any frame arriving before the first video keyframe are dropped too.

It wraps FrameWithKey, discarding the keyframe flag, for every caller that only ever wanted the bytes.

func (*Muxer) FrameWithKey

func (m *Muxer) FrameWithKey(f baichuan.Frame) (chunk []byte, startsKeyframe bool)

FrameWithKey is Frame plus a flag telling the caller whether chunk begins a video keyframe, meaning it contains that frame's PES start (and, when due, the PAT/PMT ahead of it). Only the muxer knows this: a subscriber that joins mid GOP has to wait for exactly this boundary before its decoder sees anything, since a decoder handed slices before the parameter sets that describe them logs reference errors until the next I frame (measured against a live camera: about 9 error groups in the first 60 seconds of a fresh join, then clean). startsKeyframe is only ever true for a video I frame; audio and P frames always report false.

func (*Muxer) Header

func (m *Muxer) Header() []byte

Header returns a freshly built PAT and PMT pair, for a client that joins after the stream has already started. internal/hub calls this once, when the codec first becomes known, and caches the result for every future joiner; see hub.SetHeader for why that one frozen snapshot is acceptable rather than a fresh call per joiner.

func (*Muxer) HeldFrames added in v0.2.7

func (m *Muxer) HeldFrames() uint64

HeldFrames is the video clock's Clock.Held.

func (*Muxer) Recodec added in v0.2.6

func (m *Muxer) Recodec(codec string, audio bool, gap time.Duration) (*Muxer, error)

Recodec is a muxer for a camera that came back with another video codec (its encoder was changed between connections), or with or without an AAC track where this one had the other. It continues this one's timeline and continuity counters, with Resume's gap, announces the change with a new program map version, and sets the discontinuity indicator on the first packet of each elementary stream.

func (*Muxer) Resume added in v0.2.6

func (m *Muxer) Resume(gap time.Duration)

Resume continues this muxer on a new camera connection: the timeline carries on from the last frame plus gap, the wall time the camera was away (see Clock.Resume), and the continuity counters carry on as they were. A reader that stayed attached through the reconnect, go2rtc reading the .ts for Frigate for one, then sees a pause, not timestamps that start over at zero: those made its recordings unusable for as long as the previous connection had lasted. Nothing goes out again until the new connection's first keyframe, which brings the tables and a PCR.

func (*Muxer) Skip added in v0.2.10

func (m *Muxer) Skip(f baichuan.Frame) (n int, ok bool)

Skip moves the muxer past f exactly as Frame would, keeping its clocks, table and PCR timing and audio counts, without building the transport packets. internal/stream calls it while no HTTP reader is attached: packing every frame of every stream into MPEG-TS that nobody reads was the largest source of garbage in a profile of the work fleet, where the recorder reads RTSP. ok says Frame would have returned packets, and n is about how many bytes they would have been, for the bitrate figure.

The continuity counters do not advance, which no reader can notice: a reader that joins starts its own count at whatever comes next.

type PID

type PID uint16
const (
	PIDPAT   PID = 0x0000
	PIDPMT   PID = 0x1000
	PIDVideo PID = 0x0100
	PIDAudio PID = 0x0101
)

PID assignment. These are arbitrary within the allowed range and only have to agree between the PMT and the packets themselves.

type RecordingWriter added in v0.2.0

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

RecordingWriter muxes the frames of one downloaded recording into a single MPEG-TS stream. The muxer is made from the first video frame's codec, since a recording's codec is only known once it arrives; audio before that, which has no picture to sit beside, is dropped.

func NewRecordingWriter added in v0.2.0

func NewRecordingWriter(w io.Writer, audio bool) *RecordingWriter

NewRecordingWriter writes to w. audio says whether the recording has an AAC track to declare.

func (*RecordingWriter) Write added in v0.2.0

func (r *RecordingWriter) Write(f baichuan.Frame) error

Write adds one frame.

Jump to

Keyboard shortcuts

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