stream

package
v0.2.10 Latest Latest
Warning

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

Go to latest
Published: Nov 19, 2026 License: AGPL-3.0 Imports: 34 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 stream serves media files directly or through on-the-fly HLS transcodes.

Index

Constants

View Source
const (
	PCMRate     = 44100
	PCMChannels = 2
)

PCM is the audio ServePCM sends: 16-bit little-endian stereo at 44.1 kHz, the format AirPlay speakers and Air-Mixer use, so they can play it without decoding anything.

View Source
const (
	ConvertCodec    = "codec"    // the player doesn't decode this video codec
	ConvertHDR      = "hdr"      // the screen doesn't show this HDR
	ConvertSubtitle = "subtitle" // a picture subtitle is drawn into the video
	ConvertQuality  = "quality"  // a lower quality, or an adaptive stream, was asked for
)

Why a transcode converts the picture rather than copying it.

View Source
const (
	ToneMapOff      = "off"
	ToneMapHable    = "hable"
	ToneMapMobius   = "mobius"
	ToneMapReinhard = "reinhard"
)

The ways to tone map an admin can pick, and ToneMapOff for none.

View Source
const ClearVoiceFilter = "aformat=channel_layouts=5.1,pan=stereo|FL=0.6*FL+FC+0.4*BL|FR=0.6*FR+FC+0.4*BR," +
	"acompressor=threshold=0.063:ratio=4:attack=5:release=150:makeup=4,alimiter=limit=0.95:level=disabled"

ClearVoiceFilter mixes the sound down to stereo with the centre channel, where films put the dialogue, brought forward and the low-frequency channel left out, then evens out loud and quiet moments so explosions don't drown out what's said. Any layout is made 5.1 first, so mono and stereo work too (mono lands in the centre).

View Source
const MaxAudioDelayMs = 2000

MaxAudioDelayMs is how far the sound can be moved either way.

View Source
const MaxGapless = 100

MaxGapless is the most songs one gapless stream joins.

Variables

View Source
var (
	VideoCodecs = []string{"h264", "hevc", "av1"}
	HDRKinds    = []string{"hdr10", "hdr10+", "hlg", "dolby-vision"}
)

VideoCodecs and HDRKinds are the values Plays may hold.

View Source
var AllowHomeNetwork atomic.Bool

AllowHomeNetwork lets Remote reach addresses on the home network and the server itself. Off, anyone who can add a podcast can't use a feed to make the server fetch from other devices at home, like a router's page.

View Source
var ErrHomeNetwork = errors.New("addresses on the home network aren't allowed")

ErrHomeNetwork is a connection Remote refused to make.

View Source
var ErrNoSpace = errors.New("not enough room in the transcode folder")

ErrNoSpace means the transcode folder hasn't room for even the few minutes of video a transcode that saves space keeps.

View Source
var ErrSuperseded = errors.New("replaced by a newer transcode")

ErrSuperseded means a newer Start for the same viewer and item replaced this one before it was ready, as happens while dragging the seek bar.

View Source
var Home = &http.Client{Transport: &http.Transport{
	Proxy:                 http.ProxyFromEnvironment,
	DialContext:           (&net.Dialer{Timeout: 15 * time.Second}).DialContext,
	ResponseHeaderTimeout: 20 * time.Second,
	IdleConnTimeout:       90 * time.Second,
	MaxIdleConnsPerHost:   4,
}}

Home is Remote without the home network check, for streams an admin chose to add from the home network, such as an Air-Mixer output played as a radio station.

View Source
var Remote = &http.Client{Transport: &http.Transport{
	Proxy:                 http.ProxyFromEnvironment,
	DialContext:           (&net.Dialer{Timeout: 15 * time.Second, Control: publicOnly}).DialContext,
	ResponseHeaderTimeout: 20 * time.Second,
	IdleConnTimeout:       90 * time.Second,
	MaxIdleConnsPerHost:   4,
}}

Remote is how the server fetches media that lives on the internet, such as podcast episodes: no overall time limit, since an episode can play for hours, but a quick one for the answer to start.

View Source
var Steps = []Step{
	{ID: "1080p", Label: "1080p", Width: 1920, Height: 1080, VideoBPS: 8_000_000, AudioBPS: 192_000},
	{ID: "720p", Label: "720p", Width: 1280, Height: 720, VideoBPS: 4_000_000, AudioBPS: 128_000},
	{ID: "480p", Label: "480p", Width: 854, Height: 480, VideoBPS: 1_500_000, AudioBPS: 96_000},
	{ID: "360p", Label: "360p", Width: 640, Height: 360, VideoBPS: 700_000, AudioBPS: 96_000},
}

Steps are every quality Matinee offers, best first. An admin picks which ones adaptive streams use.

ToneMapAlgorithms are the ways to tone map, the default first.

Functions

func AudioDelayFilter added in v0.2.1

func AudioDelayFilter(ms int) string

AudioDelayFilter is the audio filter that moves the sound by ms against the picture, or "" for none. Later pads the start with silence; earlier drops that much of the start, so the rest arrives sooner.

func DirSize added in v0.2.4

func DirSize(dir string, skip ...string) int64

DirSize is how many bytes the files under dir take, skipping the folders in skip and any folder on another disk (a volume mounted inside it), as a Kubernetes emptyDir counts what's in it.

func Input added in v0.1.7

func Input(it store.Item) []string

Input is FFmpeg's input options for an item's media: its file, or its address on the internet, reconnecting if the host drops the connection.

func MimeType

func MimeType(path string) string

MimeType guesses a file's content type for clients deciding whether they can play it.

func Offsets added in v0.1.13

func Offsets(tracks []store.Item, startSec float64) []float64

Offsets says where each song starts in a gapless stream that begins at startSec into the first one, in seconds on the stream's clock (the first is 0, or less when the stream starts partway into it), from the songs' lengths.

func Playlist added in v0.1.5

func Playlist(steps []Step) string

Playlist is the playlist a transcode of steps starts from: a master playlist naming one playlist per step for an adaptive stream, or the single stream's own.

func ReadProbe added in v0.2.0

func ReadProbe(path string, offset int64, limit time.Duration) (ms, bps int64, ok bool)

ReadProbe reads a piece of the file at path from offset and says how long it took and how fast it went, giving up after limit (then ms is limit and bps how much it got through). Files elsewhere (addresses) aren't probed: ok is false.

func ServeAAC added in v0.2.3

func ServeAAC(w http.ResponseWriter, r *http.Request, ffmpeg string, body io.Reader)

ServeAAC encodes an endless WAV, such as an Air-Mixer output's, to AAC (ADTS) as it comes, for players that can't play WAV streams. It's the radio.Converter for stations that stream PCM.

func ServeDirect

func ServeDirect(w http.ResponseWriter, r *http.Request, it store.Item)

ServeDirect streams the original file with range support, so seeking is instant.

func ServePCM added in v0.2.3

func ServePCM(w http.ResponseWriter, r *http.Request, ffmpeg string, it store.Item, src string, client *http.Client, start time.Duration)

ServePCM decodes an item's first audio stream with FFmpeg and sends it as an endless WAV, from start on. It's for speakers that can't decode the file themselves (see GET /items/{id}/audio). Files on the server seek straight to start; podcast episodes and radio stations are fetched with client (Remote, or Home for a station an admin added from the home network). The response ends when the audio does, or when the listener leaves.

func StyledFilter added in v0.2.1

func StyledFilter(path string, stream int, startSec float64) string

StyledFilter is the filter that draws an ASS/SSA track with libass, with the fonts attached to the file. libass reads the track from the start of the file, so the picture's clock is moved to the file's while it draws and back again after, as a transcode that starts partway in begins at zero. stream is the track's index among the file's subtitle streams, or -1 for a file that holds only the track.

func ToneMap added in v0.2.0

func ToneMap(pic Picture, algorithm string, tools ToneTools) (chain string, input []string)

ToneMap is the filter chain that tone maps pic with algorithm (see ToneMapAlgorithms), and what it needs before -i; "" when the picture isn't HDR, tone mapping is off, or FFmpeg can't.

func WAVHeader added in v0.2.3

func WAVHeader(rate, channels int) []byte

WAVHeader is the header of a 16-bit PCM WAV of unknown length: the sizes say "as long as it goes", which players of live WAV streams expect.

Types

type Accelerator

type Accelerator interface {
	Active() *hwaccel.Accel
}

Accelerator says which hardware accelerator new transcodes use (see hwaccel.Manager); nil means the CPU.

type Histogram added in v0.2.4

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

Histogram counts durations (in seconds) into buckets, for Prometheus.

func NewHistogram added in v0.2.4

func NewHistogram(bounds ...float64) *Histogram

NewHistogram makes a histogram with these bucket upper bounds, ascending.

func (*Histogram) Observe added in v0.2.4

func (h *Histogram) Observe(v float64)

Observe adds one duration.

func (*Histogram) Snapshot added in v0.2.4

func (h *Histogram) Snapshot() (bounds []float64, cumulative []uint64, sum float64)

Snapshot returns the bucket bounds, the cumulative count at or under each (the last entry is every observation, +Inf), and the sum.

type LiveInput added in v0.2.0

type LiveInput struct {
	Channel   string // the channel's id, so a viewer has one stream per channel
	URL       string
	UserAgent string
	Referrer  string
}

LiveInput is a live TV channel that doesn't stream as HLS, such as an MPEG-TS stream from a tuner.

type Picture added in v0.2.0

type Picture struct {
	Known        bool
	HDR, HDRBase string
	// DVProfile is the Dolby Vision profile (5, 7, 8 or 10), 0 when it isn't.
	DVProfile int
}

Picture is what the closer look at a file (media analysis) found about its video. Until it has looked, Known is false and the picture may be HDR of any kind.

type Plays added in v0.2.0

type Plays struct {
	Video []string // h264, hevc, av1
	HDR   []string // hdr10, hdr10+, hlg, dolby-vision
}

Plays is what a player takes as it is inside the server's HLS: the video codecs it decodes and the kinds of HDR its screen shows. A player that says nothing gets H.264 in SDR, which every HLS player plays.

func ParsePlays added in v0.2.0

func ParsePlays(video, hdr string) Plays

ParsePlays reads Plays from comma-separated lists, as in ?video=h264,hevc&hdr=hdr10. Values Matinee doesn't know are left out.

type Request added in v0.2.0

type Request struct {
	// BurnSub is an embedded subtitle stream to draw into the video, or -1
	// for none, and Audio which audio stream to play (see Start).
	BurnSub, Audio int
	// Plays is what the player takes as it is: video it decodes is copied
	// rather than converted (see videoPlan). Picture is what's known about
	// the file's HDR.
	Plays   Plays
	Picture Picture
	// ToneMap is how an HDR picture that's converted is made SDR: one of
	// ToneMapAlgorithms, or ToneMapOff.
	ToneMap string
	// AudioDelayMs moves the sound against the picture, for lip sync: later
	// when positive, earlier when negative (see AudioDelayFilter).
	AudioDelayMs int
	// ClearVoice makes dialogue easier to hear (see ClearVoiceFilter).
	ClearVoice bool
	// BurnFile, when set, is a picture subtitle file next to the video
	// (VobSub .idx, Blu-ray .sup) to draw in, instead of an embedded stream.
	BurnFile string
	// Styled draws ASS/SSA subtitles with their styling into the video,
	// for players that can't draw them: the track's file (the video itself
	// for an embedded one) and its subtitle stream there.
	Styled *StyledSub
}

Request is what a player asks of a transcode besides where to start and the quality.

type SessionInfo added in v0.1.11

type SessionInfo struct {
	ID     string `json:"id"`
	UserID int64  `json:"userId"`
	ItemID int64  `json:"itemId"`
	// Started is when FFmpeg started (milliseconds), StartSec where in the
	// file it started, and LastSeen when a player last asked for a piece.
	Started  int64   `json:"started"`
	StartSec float64 `json:"startSec"`
	LastSeen int64   `json:"lastSeen"`
	// Kind is what FFmpeg does: "video" converts the picture, "copy" only
	// repackages it (the sound may still be converted), "audio" converts
	// sound alone.
	Kind string `json:"kind"`
	// Why says why the picture is converted: codec (the player doesn't
	// decode it), hdr (its screen doesn't show the file's HDR), subtitle
	// (one is drawn in) or quality (a lower one was asked for). Empty
	// when the picture is copied, or for sound.
	Why string `json:"why,omitempty"`
	// ToneMapped says an HDR picture is converted to SDR.
	ToneMapped bool `json:"toneMapped,omitempty"`
	// Accel names the hardware doing the work, such as "VAAPI"; empty for
	// the CPU. Mode is how much of it is on the GPU: cpu, encode or full.
	Accel     string   `json:"accel,omitempty"`
	AccelID   string   `json:"accelId,omitempty"`
	Mode      string   `json:"mode"`
	Quality   []string `json:"quality,omitempty"`
	BurnSub   bool     `json:"burnSub,omitempty"`
	Adaptive  bool     `json:"adaptive,omitempty"`
	FFmpegPID int      `json:"pid,omitempty"`
	// Speed is how fast FFmpeg makes the stream, as a multiple of real
	// time: below 1 it can't keep up. 0 once it has finished, or before
	// it has made anything.
	Speed float64 `json:"speed,omitempty"`
	// Saving says the transcode folder hasn't room for all of it, so it
	// keeps only the minutes around where it plays (see space.go); Waiting
	// says FFmpeg is paused, far enough ahead of the player.
	Saving  bool `json:"saving,omitempty"`
	Waiting bool `json:"waiting,omitempty"`
}

SessionInfo describes a running transcode, for the admin dashboard.

type Space added in v0.2.4

type Space struct {
	// Free is what transcodes can still use (after the reserve kept for
	// everything else), Used what they use now, and Limit the cap from
	// MATINEE_CACHE_LIMIT, 0 for none.
	Free  int64 `json:"free"`
	Used  int64 `json:"used"`
	Limit int64 `json:"limit,omitempty"`
	// Short says running transcodes don't all fit: they keep only the
	// minutes around where they play.
	Short bool `json:"short,omitempty"`
	// OutOfSpace is when a transcode last couldn't start or stopped for
	// lack of room (milliseconds), 0 for not lately.
	OutOfSpace int64 `json:"outOfSpace,omitempty"`
}

Space is the room transcodes have, for Server health.

type SpaceLimit added in v0.2.4

type SpaceLimit struct {
	// Size is how much the volume the transcode folder is on may hold,
	// when that's less than its disk: a Kubernetes emptyDir's sizeLimit,
	// which evicts the pod when it's passed. 0 means the disk itself.
	Size int64
	// Others is how much of Size things other than transcodes use (the
	// image cache, say); nil counts only transcodes.
	Others func() int64
}

SpaceLimit is a cap on the transcode folder below its disk's free space.

type Step added in v0.1.5

type Step struct {
	ID    string `json:"id"`
	Label string `json:"label"`
	// Width caps the picture's width; narrower video keeps its size.
	Width  int `json:"width"`
	Height int `json:"height"`
	// VideoBPS is the peak video bitrate and AudioBPS the audio's, in bits
	// per second.
	VideoBPS int `json:"videoBps"`
	AudioBPS int `json:"audioBps"`
}

Step is one picture quality a transcode can make. A transcode made of several steps is an adaptive stream: players move between them as the connection allows.

func Ladder added in v0.1.5

func Ladder(it store.Item, offered []Step, onCPU bool) []Step

Ladder picks the steps an adaptive stream of it makes, best first: the ones offered that aren't bigger than the file itself. A file smaller than every step still gets the smallest. onCPU keeps it to the best step and one from the middle, so there's somewhere to step down to.

func StepByID added in v0.1.5

func StepByID(id string) (Step, bool)

StepByID finds one of Steps.

type StyledSub added in v0.2.1

type StyledSub struct {
	Path   string
	Stream int
}

StyledSub is an ASS/SSA track to draw with libass.

type ToneTools added in v0.2.0

type ToneTools struct {
	// Zscale converts HDR10 and HLG (FFmpeg built with zimg).
	Zscale bool `json:"zscale"`
	// Placebo also converts Dolby Vision with no HDR10 layer under it
	// (profile 5), which needs the Dolby Vision metadata applied
	// (libplacebo, on a Vulkan device).
	Placebo bool `json:"placebo"`
}

ToneTools is what this server's FFmpeg can tone map with.

type Transcoder

type Transcoder struct {
	FFmpeg string
	Dir    string
	Log    *slog.Logger
	// HW picks the hardware accelerator, if any; nil transcodes on the CPU.
	HW Accelerator

	// How long players wait for a stream to start, and for its pieces.
	StartTimes, SegmentWaits *Histogram

	// Limit caps the room transcodes have below their disk's free space
	// (see space.go). OnNoSpace, if set, hears when a transcode couldn't
	// start or stopped for lack of room, at most hourly, to alert admins.
	Limit     SpaceLimit
	OnNoSpace func(detail string)
	// OnShort, if set, hears (at most daily) when transcodes start saving
	// space because the folder is short of room, with how much is free.
	OnShort func(free string)
	// contains filtered or unexported fields
}

Transcoder runs one FFmpeg process per playback session and serves its HLS output.

func NewTranscoder

func NewTranscoder(ffmpeg, dir string, hw Accelerator, log *slog.Logger) *Transcoder

func (*Transcoder) Active

func (t *Transcoder) Active() int

Active is how many transcodes are running, so background work can wait until nobody is watching.

func (*Transcoder) Close

func (t *Transcoder) Close()

Close stops every session and waits a few seconds for their FFmpegs to exit and their files to go.

func (*Transcoder) Counts added in v0.1.12

func (t *Transcoder) Counts() (started, failed int64)

Counts is how many transcodes have started since the server started, and how many of them failed: those that never got going (after any retries on the CPU) and those whose FFmpeg broke off partway through.

func (*Transcoder) Kill

func (t *Transcoder) Kill(id string)

Kill stops a session and deletes its files.

func (*Transcoder) OutOfSpace added in v0.2.4

func (t *Transcoder) OutOfSpace(user, item int64) bool

OutOfSpace says whether user's transcode of item stopped, or couldn't start, for lack of room in the last half hour.

func (*Transcoder) ServeFile

func (t *Transcoder) ServeFile(w http.ResponseWriter, r *http.Request, userID int64, sessionID, name string)

ServeFile serves a playlist or segment, waiting briefly for segments FFmpeg hasn't written yet.

func (*Transcoder) SessionFor added in v0.2.0

func (t *Transcoder) SessionFor(user, item int64) (SessionInfo, bool)

SessionFor is the running transcode of item for user, if there is one.

func (*Transcoder) Sessions added in v0.1.11

func (t *Transcoder) Sessions() []SessionInfo

Sessions lists the running transcodes, oldest first.

func (*Transcoder) Space added in v0.2.4

func (t *Transcoder) Space() (Space, bool)

Space is the room transcodes have now, for Server health; ok is false when it can't be told.

func (*Transcoder) Start

func (t *Transcoder) Start(ctx context.Context, userID int64, it store.Item, startSec float64, burnSub, audio int, steps ...Step) (string, error)

Start begins a transcode of item from startSec and returns the session id once the first segment is ready. A user watching an item has at most one session for it, so seeking far ahead replaces the old one. burnSub is an embedded subtitle stream to draw into the video, or -1 for none. audio is which of the file's audio streams to play (FFmpeg's 0:a:N), 0 for the first.

steps picks the picture quality. None keeps the original as far as it can (video that's already H.264 is copied, anything else re-encoded at up to 1080p). One makes that quality. Several make an adaptive stream of the ones that suit the file (see Ladder), with a master playlist; Playlist says which playlist the session starts from.

With a hardware accelerator, a transcode that fails to start on the GPU starts again with less of it on the GPU, and finally on the CPU alone.

func (*Transcoder) StartFor added in v0.2.0

func (t *Transcoder) StartFor(ctx context.Context, userID int64, it store.Item, startSec float64, req Request, steps ...Step) (string, error)

StartFor is Start for a player that says what it plays: a picture it decodes (HEVC or AV1 at 4K in HDR, say) is repackaged as it is, and only what it can't take, usually the sound, is converted.

func (*Transcoder) StartGapless added in v0.1.13

func (t *Transcoder) StartGapless(ctx context.Context, userID int64, group string, tracks []store.Item, startSec float64) (string, error)

StartGapless begins one continuous stream of songs, so they play without a gap between them, the way a DJ mix or a live album is meant to. FFmpeg decodes each file exactly, without the silence encoders pad MP3 and AAC files with, and joins the sound sample to sample, from startSec into the first song. A user has at most one such stream per album (group).

func (*Transcoder) StartLive added in v0.2.0

func (t *Transcoder) StartLive(ctx context.Context, userID int64, in LiveInput) (string, error)

StartLive repackages a live channel's stream as HLS, so every player can play it: the picture is copied as it is and the sound made AAC. FFmpeg keeps the last minute or so, and stops once nobody asks for it.

func (*Transcoder) Stats added in v0.2.4

func (t *Transcoder) Stats() (superseded, processes int64)

Stats is the transcoder's numbers for metrics: starts a newer seek replaced, and FFmpeg processes running now.

func (*Transcoder) ToneTools added in v0.2.0

func (t *Transcoder) ToneTools() ToneTools

ToneTools finds what the transcoder's FFmpeg can tone map with, once.

Jump to

Keyboard shortcuts

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