// Package tsfanout serves one live MPEG-TS pipe to many HTTP clients. // // The packager writes a single progressive mpegts stream to its stdout; this // package buffers the most recent few seconds of it and hands each client a // copy from a decodable starting point. The cost is one encoder regardless of // how many people are watching, rather than an ffmpeg per viewer. package tsfanout import ( "errors" "io" "sync" ) // TS constants. An MPEG-TS stream is a continuous grid of 188-byte packets, // each starting with the sync byte 0x47. const ( packetSize = 188 syncByte = 0x47 // pidPAT is the Program Association Table. A client that starts here // learns the stream's structure and can begin decoding; starting at an // arbitrary byte produces garbage. pidPAT = 0 ) // DefaultBufferBytes is a few seconds of a typical broadcast bitrate. const DefaultBufferBytes = 8 << 20 // ErrLagged is returned to a client that fell so far behind that the bytes it // still needed have been overwritten. Such a client is dropped rather than // allowed to hold the buffer hostage or grow memory. var ErrLagged = errors.New("client fell behind the live buffer") // ErrClosed is returned once the source has ended. var ErrClosed = errors.New("stream closed") // Ring is a fixed-size circular buffer of the live stream, with absolute byte // offsets so each reader can track its own position. type Ring struct { mu sync.Mutex cond *sync.Cond buf []byte // written is the total number of bytes ever written, i.e. the absolute // offset just past the newest byte. written int64 closed bool // joinAt is the absolute offset of the most recent PAT packet, which is // where a new client should start. joinAt int64 // aligned tracks whether we have locked onto the 188-byte packet grid, // and carry holds a partial trailing packet between writes. aligned bool carry []byte // carryAt is the absolute offset of carry[0]. carryAt int64 readers int } func New(size int) *Ring { if size < 4*packetSize { size = DefaultBufferBytes } // Whole packets keep the arithmetic honest. size -= size % packetSize r := &Ring{buf: make([]byte, size)} r.cond = sync.NewCond(&r.mu) return r } // Write implements io.Writer and is wired to the packager's stdout. func (r *Ring) Write(p []byte) (int, error) { if len(p) == 0 { return 0, nil } r.mu.Lock() defer r.mu.Unlock() if r.closed { return 0, ErrClosed } total := len(p) r.scanLocked(p) for len(p) > 0 { off := int(r.written % int64(len(r.buf))) n := copy(r.buf[off:], p) r.written += int64(n) p = p[n:] } r.cond.Broadcast() return total, nil } // scanLocked walks the incoming bytes on the packet grid and records where the // newest PAT begins. It keeps a carry so packets split across writes are still // seen whole. func (r *Ring) scanLocked(p []byte) { // Absolute offset of p[0]. base := r.written var data []byte var dataAt int64 if len(r.carry) > 0 { data = append(r.carry, p...) dataAt = r.carryAt } else { data = p dataAt = base } i := 0 for { if !r.aligned { // Look for a sync byte with another one a packet later, which is // strong evidence of real alignment rather than a stray 0x47. found := -1 for j := i; j+packetSize < len(data); j++ { if data[j] == syncByte && data[j+packetSize] == syncByte { found = j break } } if found < 0 { break } i = found r.aligned = true } if i+packetSize > len(data) { break } if data[i] != syncByte { // Lost the grid; re-acquire from the next byte. r.aligned = false i++ continue } pid := (int(data[i+1]&0x1F) << 8) | int(data[i+2]) if pid == pidPAT { r.joinAt = dataAt + int64(i) } i += packetSize } // Keep whatever is left of the last partial packet. if rest := len(data) - i; rest > 0 && rest < packetSize { r.carry = append(r.carry[:0], data[i:]...) r.carryAt = dataAt + int64(i) } else { r.carry = r.carry[:0] r.carryAt = 0 } } // Close ends the stream and wakes every reader. func (r *Ring) Close() error { r.mu.Lock() r.closed = true r.cond.Broadcast() r.mu.Unlock() return nil } // Closed reports whether the source has ended. func (r *Ring) Closed() bool { r.mu.Lock() defer r.mu.Unlock() return r.closed } // Readers is the current client count. func (r *Ring) Readers() int { r.mu.Lock() defer r.mu.Unlock() return r.readers } // Reader is one client's view of the ring. type Reader struct { ring *Ring pos int64 done bool } // NewReader joins the stream at the most recent decodable point. func (r *Ring) NewReader() *Reader { r.mu.Lock() defer r.mu.Unlock() start := r.joinAt // Nothing useful seen yet, or the PAT has already been overwritten: start // from the oldest byte still held. oldest := r.oldestLocked() if start < oldest { start = oldest } r.readers++ return &Reader{ring: r, pos: start} } func (r *Ring) oldestLocked() int64 { if r.written <= int64(len(r.buf)) { return 0 } return r.written - int64(len(r.buf)) } // Read blocks until bytes are available, the client has lagged, or the stream // ends. func (rd *Reader) Read(p []byte) (int, error) { ring := rd.ring ring.mu.Lock() defer ring.mu.Unlock() for { if rd.pos < ring.oldestLocked() { return 0, ErrLagged } if avail := ring.written - rd.pos; avail > 0 { n := int64(len(p)) if avail < n { n = avail } // Do not read past the end of the circular array in one go. off := int(rd.pos % int64(len(ring.buf))) if tail := int64(len(ring.buf) - off); n > tail { n = tail } copy(p[:n], ring.buf[off:off+int(n)]) rd.pos += n return int(n), nil } if ring.closed { return 0, io.EOF } ring.cond.Wait() } } // Close releases the reader. func (rd *Reader) Close() error { if rd.done { return nil } rd.done = true rd.ring.mu.Lock() rd.ring.readers-- rd.ring.mu.Unlock() return nil } // Set tracks one ring per publish target (a stream's variant), so the HTTP // layer can look one up by name. type Set struct { mu sync.Mutex rings map[string]*Ring size int } func NewSet(bufferBytes int) *Set { if bufferBytes <= 0 { bufferBytes = DefaultBufferBytes } return &Set{rings: map[string]*Ring{}, size: bufferBytes} } // Create replaces any existing ring for key and returns the new one. The old // ring is closed, which drops its readers — they will reconnect. func (s *Set) Create(key string) *Ring { s.mu.Lock() defer s.mu.Unlock() if old, ok := s.rings[key]; ok { _ = old.Close() } r := New(s.size) s.rings[key] = r return r } // Get returns the live ring for key, if any. func (s *Set) Get(key string) (*Ring, bool) { s.mu.Lock() defer s.mu.Unlock() r, ok := s.rings[key] if ok && r.Closed() { return nil, false } return r, ok } // Remove closes and forgets the ring for key. func (s *Set) Remove(key string) { s.mu.Lock() r, ok := s.rings[key] delete(s.rings, key) s.mu.Unlock() if ok { _ = r.Close() } } // RemovePrefix drops every ring whose key starts with prefix, used when a // stream and all its variants stop. func (s *Set) RemovePrefix(prefix string) { s.mu.Lock() var doomed []*Ring for k, r := range s.rings { if k == prefix || (len(k) > len(prefix) && k[:len(prefix)] == prefix) { doomed = append(doomed, r) delete(s.rings, k) } } s.mu.Unlock() for _, r := range doomed { _ = r.Close() } } // Readers totals the clients across every ring whose key starts with prefix. func (s *Set) Readers(prefix string) int { s.mu.Lock() rings := make([]*Ring, 0, len(s.rings)) for k, r := range s.rings { if k == prefix || (len(k) > len(prefix) && k[:len(prefix)] == prefix) { rings = append(rings, r) } } s.mu.Unlock() total := 0 for _, r := range rings { total += r.Readers() } return total }