ts

package
v0.2.3 Latest Latest
Warning

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

Go to latest
Published: Oct 27, 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.

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) 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. The MPEG-TS output never suffered because it builds a new muxer, and so a new Clock, per connection; an RTSP session outlives the camera connection and so its clock must be told.

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) 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. Relabelling 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) 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) 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.

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