streamd: preview quality picker, dashboard polish, C4 wrap keys
All checks were successful
release / build-and-upload (push) Successful in 6m18s
modules-release / build-and-upload (push) Successful in 5m18s

- Preview player can select FHD/HD/SD (or ABR master) from publish links
- Embed dashboard screenshots in README; Linux streamd+agent setup guide
- C4 Widevine wrap license mode + require --wvd; prefer Widevine PSSH
- Channel 4 and My5 modules; streamd auth, variants, schedules, HLS gate
This commit is contained in:
404errordeveloper 2026-10-09 20:57:43 +02:00
parent b3955bd81e
commit 066e018749
113 changed files with 19002 additions and 1541 deletions

View file

@ -0,0 +1,333 @@
// 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
}

View file

@ -0,0 +1,304 @@
package tsfanout
import (
"bytes"
"errors"
"io"
"testing"
"time"
)
// tsPacket builds one 188-byte TS packet for the given PID.
func tsPacket(pid int, fill byte) []byte {
p := make([]byte, packetSize)
p[0] = syncByte
p[1] = byte(pid>>8) & 0x1F
p[2] = byte(pid & 0xFF)
p[3] = 0x10
for i := 4; i < packetSize; i++ {
p[i] = fill
}
return p
}
// tsStream builds a stream whose every n-th packet is a PAT, as ffmpeg's
// mpegts muxer emits.
func tsStream(packets int, patEvery int) []byte {
var b bytes.Buffer
for i := 0; i < packets; i++ {
if patEvery > 0 && i%patEvery == 0 {
b.Write(tsPacket(pidPAT, byte(i)))
continue
}
b.Write(tsPacket(0x100, byte(i)))
}
return b.Bytes()
}
func TestWriteReturnsFullLength(t *testing.T) {
r := New(DefaultBufferBytes)
data := tsStream(10, 5)
n, err := r.Write(data)
if err != nil {
t.Fatal(err)
}
if n != len(data) {
t.Errorf("Write returned %d, want %d — an io.Writer that under-reports breaks io.Copy", n, len(data))
}
}
// A client joining mid-stream must start at a PAT packet, or its decoder has
// no idea what it is looking at.
func TestReaderJoinsAtPATBoundary(t *testing.T) {
r := New(64 * packetSize)
// PAT every 5 packets.
r.Write(tsStream(20, 5))
rd := r.NewReader()
defer rd.Close()
buf := make([]byte, packetSize)
if _, err := io.ReadFull(rd, buf); err != nil {
t.Fatal(err)
}
if buf[0] != syncByte {
t.Fatalf("reader did not start on a packet boundary: first byte %#x", buf[0])
}
pid := (int(buf[1]&0x1F) << 8) | int(buf[2])
if pid != pidPAT {
t.Errorf("reader started at PID %d, want the PAT (%d)", pid, pidPAT)
}
}
// Even when the writes are chopped at arbitrary, non-packet-aligned sizes, the
// scanner must still find the grid. A pipe gives no alignment guarantees.
func TestPATDetectionAcrossSplitWrites(t *testing.T) {
r := New(64 * packetSize)
data := tsStream(20, 5)
// Deliberately awkward chunk size, coprime with 188.
for i := 0; i < len(data); i += 77 {
end := i + 77
if end > len(data) {
end = len(data)
}
if _, err := r.Write(data[i:end]); err != nil {
t.Fatal(err)
}
}
rd := r.NewReader()
defer rd.Close()
buf := make([]byte, packetSize)
if _, err := io.ReadFull(rd, buf); err != nil {
t.Fatal(err)
}
pid := (int(buf[1]&0x1F) << 8) | int(buf[2])
if buf[0] != syncByte || pid != pidPAT {
t.Errorf("split writes broke PAT detection: sync=%#x pid=%d", buf[0], pid)
}
}
func TestReaderStreamsSubsequentWrites(t *testing.T) {
r := New(64 * packetSize)
r.Write(tsStream(5, 5))
rd := r.NewReader()
defer rd.Close()
// Drain what is buffered.
buf := make([]byte, 5*packetSize)
if _, err := io.ReadFull(rd, buf); err != nil {
t.Fatal(err)
}
// A read with nothing available must block, then return new data.
type res struct {
n int
err error
}
ch := make(chan res, 1)
go func() {
b := make([]byte, packetSize)
n, err := rd.Read(b)
ch <- res{n, err}
}()
select {
case got := <-ch:
t.Fatalf("Read returned early (%d, %v) instead of waiting for data", got.n, got.err)
case <-time.After(50 * time.Millisecond):
}
r.Write(tsPacket(0x100, 9))
select {
case got := <-ch:
if got.err != nil || got.n == 0 {
t.Fatalf("Read after write: %d %v", got.n, got.err)
}
case <-time.After(2 * time.Second):
t.Fatal("Read did not wake after a write")
}
}
// A stalled client must be dropped, not allowed to stall the writer or grow
// memory. This is the backpressure decision that keeps one slow viewer from
// affecting the stream.
func TestLaggedReaderIsDropped(t *testing.T) {
size := 8 * packetSize
r := New(size)
r.Write(tsStream(4, 4))
rd := r.NewReader()
defer rd.Close()
// Overwrite the whole buffer several times without the reader consuming.
for i := 0; i < 5; i++ {
r.Write(tsStream(8, 8))
}
buf := make([]byte, packetSize)
_, err := rd.Read(buf)
if !errors.Is(err, ErrLagged) {
t.Errorf("want ErrLagged for a stalled client, got %v", err)
}
}
func TestMultipleReadersGetSameBytes(t *testing.T) {
r := New(64 * packetSize)
// Three clients, one source: the whole point of the package.
a, b, c := r.NewReader(), r.NewReader(), r.NewReader()
defer a.Close()
defer b.Close()
defer c.Close()
if got := r.Readers(); got != 3 {
t.Fatalf("Readers() = %d, want 3", got)
}
data := tsStream(10, 5)
r.Write(data)
read := func(rd *Reader) []byte {
out := make([]byte, 10*packetSize)
if _, err := io.ReadFull(rd, out); err != nil {
t.Fatalf("read: %v", err)
}
return out
}
ra, rb, rc := read(a), read(b), read(c)
if !bytes.Equal(ra, rb) || !bytes.Equal(rb, rc) {
t.Error("readers received different bytes from the same source")
}
// Closing one must not disturb the others.
_ = a.Close()
if got := r.Readers(); got != 2 {
t.Errorf("after one close, Readers() = %d, want 2", got)
}
r.Write(tsPacket(0x100, 1))
one := make([]byte, packetSize)
if _, err := io.ReadFull(b, one); err != nil {
t.Errorf("surviving reader broke after another closed: %v", err)
}
}
func TestCloseEndsReaders(t *testing.T) {
r := New(64 * packetSize)
rd := r.NewReader()
defer rd.Close()
done := make(chan error, 1)
go func() {
b := make([]byte, packetSize)
_, err := rd.Read(b)
done <- err
}()
time.Sleep(20 * time.Millisecond)
_ = r.Close()
select {
case err := <-done:
if !errors.Is(err, io.EOF) {
t.Errorf("want io.EOF after Close, got %v", err)
}
case <-time.After(2 * time.Second):
t.Fatal("Close did not wake a blocked reader")
}
if _, err := r.Write([]byte("x")); !errors.Is(err, ErrClosed) {
t.Errorf("write after close should fail, got %v", err)
}
}
// The ring must wrap correctly: reading across the seam has to produce the
// bytes that were written, not a torn copy.
func TestRingWrapsCorrectly(t *testing.T) {
size := 16 * packetSize
r := New(size)
rd := r.NewReader()
defer rd.Close()
// Write and drain repeatedly so the write position passes the end of the
// array several times.
var want, got bytes.Buffer
for round := 0; round < 10; round++ {
chunk := tsStream(6, 6)
r.Write(chunk)
want.Write(chunk)
buf := make([]byte, len(chunk))
if _, err := io.ReadFull(rd, buf); err != nil {
t.Fatalf("round %d: %v", round, err)
}
got.Write(buf)
}
if !bytes.Equal(want.Bytes(), got.Bytes()) {
t.Error("data read across the ring wrap does not match what was written")
}
}
func TestSetLifecycle(t *testing.T) {
s := NewSet(16 * packetSize)
if _, ok := s.Get("city-news"); ok {
t.Error("empty set should not resolve a key")
}
r := s.Create("city-news")
if got, ok := s.Get("city-news"); !ok || got != r {
t.Error("Create then Get should return the same ring")
}
// Creating again replaces and closes the old ring, so its readers drop.
rd := r.NewReader()
defer rd.Close()
r2 := s.Create("city-news")
if r2 == r {
t.Error("Create should replace the existing ring")
}
if !r.Closed() {
t.Error("the replaced ring should be closed")
}
// Prefix removal covers a stream and all of its variants at once.
s.Create("city-news-hd")
s.Create("other")
s.RemovePrefix("city-news")
if _, ok := s.Get("city-news"); ok {
t.Error("city-news should be gone")
}
if _, ok := s.Get("city-news-hd"); ok {
t.Error("city-news-hd should be gone")
}
if _, ok := s.Get("other"); !ok {
t.Error("unrelated key should survive RemovePrefix")
}
}
func TestSetReadersCountsAcrossVariants(t *testing.T) {
s := NewSet(16 * packetSize)
a := s.Create("news")
b := s.Create("news-hd")
r1, r2, r3 := a.NewReader(), b.NewReader(), b.NewReader()
defer r1.Close()
defer r2.Close()
defer r3.Close()
if got := s.Readers("news"); got != 3 {
t.Errorf("Readers(news) = %d, want 3 across both variants", got)
}
}
// A closed ring must not be handed out as live.
func TestGetSkipsClosedRing(t *testing.T) {
s := NewSet(16 * packetSize)
r := s.Create("x")
_ = r.Close()
if _, ok := s.Get("x"); ok {
t.Error("Get should not return a closed ring")
}
}