Documentation
¶
Overview ¶
Package transcode wraps Ether's bundled ffmpeg: discovery, hardware encoder detection, probing, the direct play / remux / transcode decision and HLS and MPEG-DASH sessions. Manager implements core.Transcoder.
These helpers support offline acceptance tests across package boundaries. Runtime callers use the production APIs in the other files.
Index ¶
- Constants
- Variables
- func ApplyForcedOverrides(c core.ClientCaps, model string, overrides []core.ClientCapabilityOverride) core.ClientCaps
- func AuthorCopyTimeline(q core.HLSRequest) core.HLSRequest
- func AuthorDistributedRamp(q core.HLSRequest, c config.Transcode) core.HLSRequest
- func BurnsSubtitle(sub core.StreamInfo, caps core.ClientCaps, opts core.DecideOptions) bool
- func ContinuousFrameRate(num, den int) bool
- func Decide(info core.MediaInfo, caps core.ClientCaps, opts core.DecideOptions, pol Policy) core.Decision
- func DecisionOutputSize(v *core.StreamInfo, d core.Decision) (int, int)
- func DownloadCopyable(info core.MediaInfo, audioStream int, caps core.ClientCaps) (video, audio *core.StreamInfo, ok bool)
- func GPUVendor(device string) string
- func H264HighLevel(width, height int, fps float64, peakKbps, dpbFrames int) int
- func H264HighLevelLimits(level int) (int, int, bool)
- func HLSContainer(caps core.ClientCaps, videoCodec, audioCodec string) string
- func HLSCopyPeakKbps(info core.MediaInfo, segDur time.Duration) int
- func HLSVariantAttributes(info core.MediaInfo, d core.Decision) string
- func HLSVariantGeometry(info core.MediaInfo, d core.Decision) string
- func HasHDR10Base(v *core.StreamInfo, caps core.ClientCaps) bool
- func HasQuirk(product, platform, device, model, version, name string) bool
- func IsImageSubtitle(codec string) bool
- func IsJPEG(b []byte) bool
- func IsTextSubtitle(codec string) bool
- func MarshalBIF(frames []BIFFrame) ([]byte, error)
- func NormalizeCodec(c string) string
- func NormalizeContainer(formatName string) string
- func OutputGeometry(v *core.StreamInfo, maxHeight int) (int, int)
- func ParseProbe(b []byte) (*core.MediaInfo, error)
- func ParseSegmentName(name string) (int, bool)
- func PlexDASHURLs(sessionID string) (string, string)
- func PolicyStamp(product, platform, device, model, version string, ...) (dv []int, subs []string, dvChanged, subsChanged bool)
- func ProbeHeader(ctx context.Context, src io.ReaderAt, size int64, budget int) (*core.MediaInfo, error)
- func ProbeSource(ctx context.Context, src io.ReaderAt, size int64) (*core.MediaInfo, error)
- func ProbeTrailer(ctx context.Context, src io.ReaderAt, size int64, m *core.MediaInfo) bool
- func ProfileVideoKbps(height int) int
- func SchedulerLate(window time.Duration) time.Duration
- func SegmentName(n int, container string) string
- func SegmentedAudioCopyOK(caps core.ClientCaps, codec string) bool
- func SegmentedVideoCopyOK(caps core.ClientCaps, codec string) bool
- func SupportsDVProfile(c core.ClientCaps, profile int) bool
- func SupportsDistributedEnhancement(e core.VideoEnhancement) bool
- func ValidCopyTimeline(q core.HLSRequest) bool
- func ValidDistributedRamp(q core.HLSRequest) bool
- func ValidRecoveryStartShape(r core.HLSRequest) bool
- func ValidateDistributedKeyframes(info core.MediaInfo) bool
- func VelaQualityVariants(info core.MediaInfo, base core.Decision, caps core.ClientCaps, ...) ([]core.QualityVariant, []core.QualityLimitation)
- func WithSubtitleReader(ctx context.Context, open SubtitleReaderOpener) context.Context
- func WithSubtitleSource(ctx context.Context, source string) context.Context
- func WriteBIF(w io.Writer, frames []BIFFrame) error
- type BIF
- type BIFFrame
- type Capability
- type ClientPolicy
- type Command
- type ContinuousEncoder
- type ContinuousRunner
- type DASHSegmentIndex
- type DASHTrack
- type DASHURLs
- type Decoder
- type DecoderRequest
- type DownloadRemuxer
- func (d *DownloadRemuxer) ReleaseDownload(path string)
- func (d *DownloadRemuxer) RemuxDownload(ctx context.Context, req core.DownloadRemuxRequest, progress func(float64)) (string, int64, error)
- func (d *DownloadRemuxer) RetainDownload(path string, expires time.Time) error
- func (d *DownloadRemuxer) UsedBytes() int64
- type EncoderRequest
- type ExecRunner
- type GraphError
- type Manager
- func (m *Manager) AcquireTranscodeSlot(ctx context.Context, p SlotPriority) (context.Context, func(), error)
- func (m *Manager) AdaptiveBudgetInfo(sessionID string) (rungsKbps []int, currentCapKbps int, adaptive bool)
- func (m *Manager) AudioFallbackAvailable() bool
- func (m *Manager) CachedSubtitle(ctx context.Context, streamIndex int, codec string) ([]byte, bool)
- func (m *Manager) Capability() Capability
- func (m *Manager) Close() error
- func (m *Manager) ContinuousBudget() (cores float64, hardware bool)
- func (m *Manager) Decide(info core.MediaInfo, caps core.ClientCaps, opts core.DecideOptions) core.Decision
- func (m *Manager) DetectHardSubs(ctx context.Context, input string, duration time.Duration) (bool, bool)
- func (m *Manager) DistributedHardwareEncoder(req core.HLSRequest) string
- func (m *Manager) EncodingCount() int
- func (m *Manager) EnhancementStatus() core.VideoEnhancementSupport
- func (m *Manager) ExtractSubtitle(ctx context.Context, inputURL string, streamIndex int, codec string, ...) error
- func (m *Manager) FFmpegPath() string
- func (m *Manager) FFprobePath() string
- func (m *Manager) HWAccel() core.HWAccel
- func (m *Manager) NewDownloadRemuxer(cfg config.Downloads) (*DownloadRemuxer, error)
- func (m *Manager) OnAirEncoderOptions(w, h int) (input, video []string)
- func (m *Manager) Policy() Policy
- func (m *Manager) ProactiveFallbackAvailable() bool
- func (m *Manager) Probe(ctx context.Context, inputURL string) (*core.MediaInfo, error)
- func (m *Manager) ProbeLive(ctx context.Context, inputURL string) (*core.MediaInfo, error)
- func (m *Manager) ProbeLiveWithHeaders(ctx context.Context, input string, headers map[string]string) (*core.MediaInfo, error)
- func (m *Manager) QualitySupport() QualitySupport
- func (m *Manager) Session(id string) (core.HLSSession, bool)
- func (m *Manager) SessionBudgetStatus(sessionID string) (capKbps int, active bool, rungID string)
- func (m *Manager) Sessions() []*Session
- func (m *Manager) SetRemoteDeliveryObserver(fn func(RemoteDeliveryEvent))
- func (m *Manager) SetSessionBudgetCap(sessionID string, capKbps int) (applied bool, rungID string)
- func (m *Manager) StartDecoder(ctx context.Context, r DecoderRequest) (Decoder, error)
- func (m *Manager) StartEncoder(ctx context.Context, r EncoderRequest) (ContinuousEncoder, error)
- func (m *Manager) StartHLS(ctx context.Context, req core.HLSRequest) (core.HLSSession, error)
- func (m *Manager) StartHLSOwned(ctx context.Context, req core.HLSRequest) (core.HLSSession, core.EncoderRetirement, error)
- func (m *Manager) StartRenditions(ctx context.Context, requests []EncoderRequest) ([]ContinuousEncoder, error)
- func (m *Manager) Stop(id string)
- func (m *Manager) StreamSubtitle(ctx context.Context, inputURL string, streamIndex int, codec string, ...) error
- func (m *Manager) SupportsDistributedRequest(req core.HLSRequest) bool
- func (m *Manager) ToneMapsDolbyVisionProfile5() bool
- func (m *Manager) UpdateConfig(cfg config.Transcode)
- func (m *Manager) Version() string
- func (m *Manager) VideoTranscodingOff() bool
- type Option
- func WithBuffering(restartAhead, maxAhead, keepBehind time.Duration) Option
- func WithDecodeStore(db *sql.DB) Option
- func WithEncoderObserver(f func(sessionID string, started bool, excerpt string)) Option
- func WithEvents(bus *events.Bus) Option
- func WithIdleTimeout(d time.Duration) Option
- func WithInputFailureHandler(f func(sessionID, inputURL string, at time.Duration, err error)) Option
- func WithOnChange(f func()) Option
- func WithRunStartHandler(f func(inputURL string, from, to time.Duration)) Option
- func WithRunner(r Runner) Option
- func WithRuntimeDir(dir string) Option
- func WithSegmentPadLimit(d time.Duration) Option
- func WithSegmentTimeout(d time.Duration) Option
- func WithStallTimeout(d time.Duration) Option
- func WithSubtitleOpener(f func(id, format, source string) (io.ReadCloser, string, error)) Option
- func WithTracePlayback(on bool) Option
- func WithoutHWDetection() Option
- type PlaybackDefaults
- type Policy
- type Process
- type Progress
- type QualitySupport
- type RTXRunner
- type RawFormat
- type RawFrame
- type RemoteDeliveryEvent
- type Runner
- type SegMode
- type Segment
- type SegmentIndex
- type SegmentPlan
- type Session
- func (s *Session) AdaptiveBudgetInfo() (rungsKbps []int, currentCapKbps int, adaptive bool)
- func (s *Session) BudgetStatus() (capKbps int, active bool, rungID string)
- func (s *Session) CheckSwap(info core.MediaInfo) error
- func (s *Session) Close() error
- func (s *Session) Container() string
- func (s *Session) CurrentSwapInput() string
- func (s *Session) Decision() core.Decision
- func (s *Session) EncoderRetirement() core.EncoderRetirement
- func (s *Session) EncoderStatus() *core.EncoderStatus
- func (s *Session) GoodputKbps() int
- func (s *Session) HWAccelerated() bool
- func (s *Session) HasTextSubtitle(index int) bool
- func (s *Session) ID() string
- func (s *Session) IndependentSegments() bool
- func (s *Session) Info() core.MediaInfo
- func (s *Session) LastAccess() time.Time
- func (s *Session) LastMediaAccess() time.Time
- func (s *Session) PlaybackDelivered() bool
- func (s *Session) PlaybackDiagnostics() core.HLSPlaybackDiagnostics
- func (s *Session) PlaybackState(state string)
- func (s *Session) PrepareRung(ctx context.Context, id string, position time.Duration) error
- func (s *Session) PrepareSwap(ctx context.Context, input string, info core.MediaInfo, at time.Duration) error
- func (s *Session) Progress() Progress
- func (s *Session) Protocol() string
- func (s *Session) RecoveryBuffer() core.RecoveryBuffer
- func (s *Session) RequestedPosition() time.Duration
- func (s *Session) RetireEncoder() error
- func (s *Session) Rungs() []core.HLSRung
- func (s *Session) SegmentDuration() time.Duration
- func (s *Session) ServeInit(w http.ResponseWriter, r *http.Request, rep int)
- func (s *Session) ServeManifest(w http.ResponseWriter, r *http.Request)
- func (s *Session) ServeMedia(w http.ResponseWriter, r *http.Request, rep, n int)
- func (s *Session) ServePlaylist(w http.ResponseWriter, r *http.Request)
- func (s *Session) ServeRungPlaylist(w http.ResponseWriter, r *http.Request, rungID string)
- func (s *Session) ServeRungSegment(w http.ResponseWriter, r *http.Request, rungID string, n int)
- func (s *Session) ServeSegment(w http.ResponseWriter, r *http.Request, n int)
- func (s *Session) ServeSoftSubtitle(w http.ResponseWriter, req *http.Request, index int) bool
- func (s *Session) ServeTextSubtitlePlaylist(w http.ResponseWriter, r *http.Request, index int)
- func (s *Session) ServeTextSubtitleSegment(w http.ResponseWriter, r *http.Request, index, n int)
- func (s *Session) SetBudgetCapKbps(capKbps int) (applied bool, rungID string)
- func (s *Session) SkipDamagedSegment(ctx context.Context, inputURL string, info core.MediaInfo, at time.Duration) error
- func (s *Session) SwapInput(ctx context.Context, inputURL string, info core.MediaInfo, at time.Duration) error
- func (s *Session) SwapInputBuffered(ctx context.Context, inputURL string, info core.MediaInfo, at time.Duration) error
- func (s *Session) SwapWouldCopyVideo(info core.MediaInfo) bool
- func (s *Session) TextSubtitleCues(index int, from, to time.Duration) ([]subtitles.Cue, error)
- func (s *Session) TimelineOrigin() time.Duration
- func (s *Session) Touch()
- func (s *Session) WaitForReplacementOutput(ctx context.Context, input string) error
- type SlotPriority
- type SourceProbeOptions
- type SourceProber
- type SubtitleReaderOpener
- type ThumbOptions
- type Thumbnails
- func (t *Thumbnails) CancelTrickplay(releaseID string)
- func (t *Thumbnails) Close() error
- func (t *Thumbnails) EnsureTrickplay(_ context.Context, src core.TrickplaySource)
- func (t *Thumbnails) PreviewInterval() time.Duration
- func (t *Thumbnails) PreviewWidth() int
- func (t *Thumbnails) SetTrickplayFallback(releaseID string, jpeg []byte)
- func (t *Thumbnails) TrickplayAvailable(releaseID string) bool
- func (t *Thumbnails) TrickplayBIF(releaseID string) ([]byte, bool)
- func (t *Thumbnails) TrickplayFrame(releaseID string, at time.Duration) ([]byte, bool)
- type Timeline
- func (tl *Timeline) ClampKbps(n int) int
- func (tl *Timeline) Dur(n int) time.Duration
- func (tl *Timeline) IndexAt(rel time.Duration) int
- func (tl *Timeline) Keyframed() bool
- func (tl *Timeline) ModeAt(n int) SegMode
- func (tl *Timeline) NextChange(n int) int
- func (tl *Timeline) Plan(n int) SegmentPlan
- func (tl *Timeline) SetClamp(n, kbps int)
- func (tl *Timeline) Start(n int) time.Duration
- func (tl *Timeline) TargetDuration() time.Duration
- func (tl *Timeline) Total() int
Constants ¶
const ( ContainerMPEGTS = "mpegts" ContainerFMP4 = "fmp4" ContainerMatroska = "mkv" )
HLS segment containers reported in core.Decision.Container.
const ( AccelNone = "none" AccelVideoToolbox = "videotoolbox" AccelNVENC = "nvenc" AccelQSV = "qsv" AccelVAAPI = "vaapi" )
Hardware accelerator names, as used in config.Transcode.HWAccel and core.HWAccel.Name.
const AudioFallbackSegmentDuration = 1536 * time.Millisecond
AudioFallbackSegmentDuration is 72 AAC frames at the fallback's 48 kHz output rate. Even a folded tail (less than a quarter segment) stays below 1.92s, leaving room for encoder priming within Vela's strict 2s limit.
const DefaultDASHSegmentDuration = 5 * time.Second
DefaultDASHSegmentDuration is the DASH segment length when a request leaves it unset; PMS uses 5 s.
const ( // DefaultHeaderProbeBudget bounds low-priority container header probes // (MKV EBML/Info/Tracks or MP4 moov). DefaultHeaderProbeBudget = 2 << 20 )
const DefaultSegmentDuration = 4 * time.Second
DefaultSegmentDuration is the HLS segment length when a request leaves it unset.
const DefaultVAAPIDevice = "/dev/dri/renderD128"
DefaultVAAPIDevice is the render node used when none is configured.
const InitSegment = -1
InitSegment is the segment number ServeSegment uses for the fMP4 initialization segment (init.mp4).
const InitSegmentName = "init.mp4"
InitSegmentName is the init segment's URI in media playlists.
const MatroskaHeaderName = "header"
MatroskaHeaderName matches Plex's segmented-Matroska initialization URI.
const MaxDistributedKeyframes = 1024
Variables ¶
var ErrEncoderCapacity = errors.New("transcode: encoder retirement capacity exhausted")
var ErrFFmpegNotFound = errors.New("transcode: ffmpeg not found")
ErrFFmpegNotFound means no usable ffmpeg/ffprobe executable was found in the configured path, the bundled locations or PATH.
var ErrImageSubtitle = errors.New("transcode: bitmap subtitles cannot be converted to text")
ErrImageSubtitle is returned when a bitmap subtitle is asked for as text.
var ErrIncompatibleSwap = errors.New("transcode: replacement cannot match the delivered video")
ErrIncompatibleSwap reports a replacement source whose video cannot be delivered in the session's fixed output contract.
var ErrInputChanged = errors.New("transcode: live input changed its streams")
ErrInputChanged reports that a live input changed its codec or stream set mid-stream affecting the selected audio/video (such as a new codec on a PID): one elementary stream keeps flowing while the other can no longer be decoded. The caller splices a replacement decoder into its existing output timeline. PMT version bumps and unrelated elementary streams alone are not changes.
var ErrPauseUnsupported = errors.New("transcode: pausing processes is not supported on this platform")
ErrPauseUnsupported is returned by Process.Pause on platforms that cannot suspend a process.
var ErrProbeIncomplete = errors.New("transcode: native probe incomplete")
ErrProbeIncomplete means native probing cannot vouch for the stream parameters; ffprobe must run.
var ErrRecoveryUnsupported = errors.New("transcode: verified recovery source/cursor provider unavailable")
var ErrSourceProbe = errors.New("transcode: source probe unavailable")
var ErrSourceProbeClosed = errors.New("transcode: source prober closed")
var ErrTooManyTranscodes = errors.New("transcode: too many concurrent transcodes")
ErrTooManyTranscodes is returned by StartHLS when config MaxTranscodes video transcodes are already running. Remuxes are not counted.
var ErrVideoTranscodingDisabled = core.ErrVideoTranscodingDisabled
ErrVideoTranscodingDisabled is returned when a non-live movie or show requires video re-encoding while transcode.videoTranscoding is "off".
Functions ¶
func ApplyForcedOverrides ¶
func ApplyForcedOverrides(c core.ClientCaps, model string, overrides []core.ClientCapabilityOverride) core.ClientCaps
ApplyForcedOverrides replaces only explicitly edited facts after runtime declarations. Matching is identical to the registry baseline's selectors.
func AuthorCopyTimeline ¶
func AuthorCopyTimeline(q core.HLSRequest) core.HLSRequest
AuthorCopyTimeline freezes the proven source grid before durable admission.
func AuthorDistributedRamp ¶
func AuthorDistributedRamp(q core.HLSRequest, c config.Transcode) core.HLSRequest
AuthorDistributedRamp snapshots shared configuration once, before durable admission. Unsupported requests remain on their legacy steady private path. Reencoded audio stays steady until combined ramp/audio recovery is qualified.
func BurnsSubtitle ¶ added in v0.3.3
func BurnsSubtitle(sub core.StreamInfo, caps core.ClientCaps, opts core.DecideOptions) bool
BurnsSubtitle reports whether Decide burns sub into the video. Text subtitles remain sidecars, including legacy burn requests, unless the client cannot draw a soft text track here (BurnTextSubtitles); an image subtitle is burned when asked or when the client cannot draw it.
func ContinuousFrameRate ¶
ContinuousFrameRate reports a broadcast frame rate a continuous output can run at: 24, 25, 30, 50 and 60 frames per second and their NTSC forms.
func Decide ¶
func Decide(info core.MediaInfo, caps core.ClientCaps, opts core.DecideOptions, pol Policy) core.Decision
func DecisionOutputSize ¶
DecisionOutputSize is the encoded (square-pixel) picture size a decision produces from v, for manifest and client metadata. It matches planPicture: an anamorphic source is sized by its display aspect.
func DownloadCopyable ¶
func DownloadCopyable(info core.MediaInfo, audioStream int, caps core.ClientCaps) (video, audio *core.StreamInfo, ok bool)
DownloadCopyable reports whether info's video (and chosen audio) can be stream-copied to MP4, returning the streams a remux would keep.
func GPUVendor ¶ added in v0.3.2
GPUVendor names the vendor of a DRM render node ("/dev/dri/renderD128") from its PCI vendor id in sysfs: "intel", "amd", "nvidia", or "" when it is unknown or not on Linux. VA-API runs on Intel and AMD alike, so the backend name alone does not say whose hardware it is (#261).
func H264HighLevel ¶ added in v0.3.0
H264HighLevel returns the smallest supported High-profile level for a known encode geometry, rate, peak bitrate and decoded-picture budget. Zero means the facts are unknown or exceed this encoder contract.
func H264HighLevelLimits ¶ added in v0.3.0
H264HighLevelLimits returns peak bitrate and decoded-picture limits for a level selected by H264HighLevel.
func HLSContainer ¶
func HLSContainer(caps core.ClientCaps, videoCodec, audioCodec string) string
HLSContainer preserves explicit client targets separately from the formats its direct-play decoder accepts. Plex's enhanced player requests segmented Matroska; AVPlayer and browser HLS keep the standard TS/fMP4 path.
func HLSCopyPeakKbps ¶
HLSCopyPeakKbps is the BANDWIDTH, in kbit/s, of an HLS variant copying the source video, for segments of segDur (0: the default). 0 when the source bit rate is unknown.
func HLSVariantGeometry ¶
HLSVariantAttributes returns the CODECS, VIDEO-RANGE and SUPPLEMENTAL-CODECS attributes (each with its leading comma) for the master playlist's #EXT-X-STREAM-INF line, describing the output the media decision selected. Apple HLS requires CODECS; HDR and Dolby Vision also need explicit signaling. https://developer.apple.com/streaming/hls-authoring-specification-for-apple-devices.html
One transport is deliberately different: for the Plex for Android Matroska HLS session (d.AndroidMatroskaHLS with a Matroska container) CODECS and SUPPLEMENTAL-CODECS are left out on purpose. See the comment at the omission before changing that. HLSVariantGeometry returns the RESOLUTION and FRAME-RATE attributes (each with its leading comma) for the output video the decision selects, or nothing when the size is unknown. Apple's authoring spec requires both on every video variant (9.2, 9.15), and tvOS AVPlayer enforces it for HDR: a PQ or Dolby Vision variant without them is rejected at the master playlist, while SDR is tolerated.
func HasHDR10Base ¶ added in v0.3.3
func HasHDR10Base(v *core.StreamInfo, caps core.ClientCaps) bool
HasHDR10Base is hasHDR10Base for callers outside the package.
func IsImageSubtitle ¶
IsImageSubtitle reports whether a subtitle codec is bitmap-based and so must be burned in to be shown in HLS.
func IsTextSubtitle ¶
IsTextSubtitle reports whether a subtitle codec can be converted to WebVTT.
func MarshalBIF ¶
MarshalBIF encodes frames as a BIF file. Frames are sorted by time (stable, on a copy) and duplicate timestamps keep the first frame, so the output is deterministic for a given input order. At least one frame with image data is required.
func NormalizeCodec ¶
NormalizeCodec maps ffprobe codec names to Ether/Plex codec names.
func NormalizeContainer ¶
NormalizeContainer maps an ffprobe format_name to Ether's container name.
func OutputGeometry ¶ added in v0.3.0
func OutputGeometry(v *core.StreamInfo, maxHeight int) (int, int)
OutputGeometry uses the same geometry as the encoder's scale plan: the square-pixel display size at the height cap.
func ParseProbe ¶
ParseProbe maps ffprobe -print_format json -show_format -show_streams output to MediaInfo.
func ParseSegmentName ¶
ParseSegmentName parses a segment URI produced by SegmentName (or InitSegmentName) back to its number; init.mp4 yields InitSegment.
func PlexDASHURLs ¶
PlexDASHURLs is the URL layout real PMS uses (captured from a PMS start.mpd): segments live next to start.mpd under session/{id}/.
func PolicyStamp ¶ added in v0.3.0
func PolicyStamp(product, platform, device, model, version string, overrides []core.ClientCapabilityOverride) (dv []int, subs []string, dvChanged, subsChanged bool)
PolicyStamp returns Dolby Vision profiles and subtitle codecs when an owner override changed them. Unchanged defaults stay unset so a Plex client cap matches the historical shape.
func ProbeHeader ¶
func ProbeHeader(ctx context.Context, src io.ReaderAt, size int64, budget int) (*core.MediaInfo, error)
ProbeHeader probes only container headers (Matroska EBML/Info/Tracks or MP4 moov) within a strict byte budget, skipping tail tag/cluster bitrate reads and never invoking ffprobe.
func ProbeSource ¶ added in v0.2.4
ProbeSource probes a media source natively: Matroska/WebM and MP4/MOV/M4V. Other containers return ErrProbeIncomplete.
func ProbeTrailer ¶ added in v0.2.4
ProbeTrailer reads metadata Matroska keeps after the media (tail Chapters, mkvmerge statistics tags). It fills only facts that are not already known and never changes stream identity or codec parameters, so it can run after playback has started.
func ProfileVideoKbps ¶ added in v0.3.0
bitrateCeiling is the bitrate past which a height gains little. ProfileVideoKbps is the H.264 video target Decide uses for a quality profile height. Silo publishes the same number on that rung.
func SchedulerLate ¶
SchedulerLate is the watchdog's worst lateness within window (zero before it starts). Compare it with a pipeline delay of the same moment.
func SegmentName ¶
SegmentName is the default playlist URI of segment n: "00042.ts" or "00042.m4s" or "00042.mkv" (relative to index.m3u8).
func SegmentedAudioCopyOK ¶
func SegmentedAudioCopyOK(caps core.ClientCaps, codec string) bool
SegmentedAudioCopyOK reports whether codec may be copied into this client's segmented output: its streaming target lists it, when it declares one, the muxer supports it, and neither the client registry nor a remembered stall refuses it.
func SegmentedVideoCopyOK ¶
func SegmentedVideoCopyOK(caps core.ClientCaps, codec string) bool
SegmentedVideoCopyOK reports whether codec may be copied into this client's segmented output when the client declared a streaming target.
func SupportsDVProfile ¶
func SupportsDVProfile(c core.ClientCaps, profile int) bool
SupportsDVProfile requires both the generic DV flag and a compatible profile. With no model evidence an unspecified profile is accepted only if the client explicitly advertised DV; known unsupported profiles use their base layer.
func SupportsDistributedEnhancement ¶
func SupportsDistributedEnhancement(e core.VideoEnhancement) bool
SupportsDistributedEnhancement accepts inert observation metadata only. A genuine default CPU decision reports RTX disabled/off with a reason; retain that status unchanged rather than discarding it to fake compatibility.
func ValidCopyTimeline ¶
func ValidCopyTimeline(q core.HLSRequest) bool
ValidCopyTimeline checks shape, not authenticity. The private source-owner handshake must match the fact against the pinned source before worker start.
func ValidDistributedRamp ¶
func ValidDistributedRamp(q core.HLSRequest) bool
ValidDistributedRamp bounds the versioned, deterministic encoded-HLS plan. Copy, live, offset, subtitles and native recovery retain their existing paths.
func ValidRecoveryStartShape ¶
func ValidRecoveryStartShape(r core.HLSRequest) bool
ValidRecoveryStartShape checks only the bounded candidate instruction/profile. It performs no I/O and proves none of the expected facts. In particular true does not imply Manager support: an authenticated immutable source/AU index, actual final-byte validation and client acceptance are still required.
func ValidateDistributedKeyframes ¶
ValidateDistributedKeyframes checks a complete lossless index. It never sorts, truncates or downsamples source metadata to make a request fit admission.
func VelaQualityVariants ¶
func VelaQualityVariants(info core.MediaInfo, base core.Decision, caps core.ClientCaps, maxWidth, maxHeight, maxKbps int, support QualitySupport) ([]core.QualityVariant, []core.QualityLimitation)
VelaQualityVariants is an explicit menu, independent of the throughput-drop heuristics in buildRungs. Same-resolution bitrate choices are intentional. All bitrates here are video targets; audio is added exactly once.
func WithSubtitleReader ¶
func WithSubtitleReader(ctx context.Context, open SubtitleReaderOpener) context.Context
WithSubtitleReader lets ExtractSubtitle read an indexed track from the source directly instead of having FFmpeg read the whole input.
func WithSubtitleSource ¶ added in v0.3.0
WithSubtitleSource names the source an extraction reads, the same for every session of that source (its release). ExtractSubtitle caches the track's WebVTT under it; an empty name extracts uncached.
Types ¶
type BIF ¶
type BIF struct {
Version uint32
Multiplier uint32 // ms per timestamp unit
// contains filtered or unexported fields
}
BIF is a parsed BIF file.
type Capability ¶ added in v0.3.0
type Capability struct {
Notice string `json:"notice,omitempty"`
PlaybackError string `json:"playbackError,omitempty"`
FiltersProbed bool `json:"filtersProbed"`
HardwareToneMap *bool `json:"hardwareToneMap,omitempty"`
ToneMap []string `json:"toneMap,omitempty"`
Colour []string `json:"colour,omitempty"`
}
Capability is the owner-visible transcoder health card: which colour and tone-map paths were probed, plus the latest graph failure.
type ClientPolicy ¶
type ClientPolicy struct {
Family string `json:"family"`
DolbyVisionProfiles []int `json:"dolbyVisionProfiles"`
SubtitleCodecs []string `json:"subtitleCodecs"`
Notes string `json:"notes"`
AlwaysEncodeVideo bool `json:"alwaysEncodeVideo,omitempty"`
}
ClientPolicy records the registry's family defaults for one client. Headers and profile declarations remain authoritative; a model name alone does not certify a display or an audio chain.
func ClientPolicyFor ¶
func ClientPolicyFor(c core.ClientCaps) ClientPolicy
ClientPolicyFor resolves the embedded registry with no owner overrides.
func ResolvePolicy ¶ added in v0.3.0
func ResolvePolicy(c core.ClientCaps, overrides []core.ClientCapabilityOverride) ClientPolicy
ResolvePolicy layers owner overrides on the registry, then lets a runtime declaration replace Dolby Vision profiles and subtitle codecs unless forced.
type Command ¶
type Command struct {
Path string
Args []string
Dir string
Stdout io.Writer
Stderr io.Writer
// Background runs the process below live outputs' scheduling priority
// (copy-only playback and background jobs): a real-time Live TV encoder
// must not miss its segment deadline because the host is busy.
Background bool
}
Command describes one ffmpeg/ffprobe invocation.
type ContinuousEncoder ¶
type ContinuousEncoder interface {
Write(ctx context.Context, f RawFrame) error
Segments() SegmentIndex
Close() error
}
ContinuousEncoder never restarts and never changes output parameters. Its timestamps come from the tick counter (monotonic, no discontinuities). Write takes exactly one tick and may block during encoder scheduling dips. Callers buffer ticks independently of the output clock, preserving PCM while repeating pictures under pressure. Context cancellation interrupts a write. Segments exposes finished media for Live TV to build viewer responses.
type ContinuousRunner ¶
type ContinuousRunner interface {
StartDecoder(ctx context.Context, r DecoderRequest) (Decoder, error)
StartEncoder(ctx context.Context, r EncoderRequest) (ContinuousEncoder, error)
}
type DASHSegmentIndex ¶
type DASHSegmentIndex interface {
DASHTracks() ([]DASHTrack, error)
ServeDASHTrack(http.ResponseWriter, *http.Request, int, int64, bool)
}
DASHSegmentIndex preserves the shared encoder while exposing separate tracks to DASH clients whose capability checks reject multiplexed representations.
type DASHTrack ¶
type DASHTrack struct {
ID uint32
Kind, Codec string
Width, Height, SampleRate, Channels, Bandwidth int
}
DASHTrack describes a separately addressable track of a shared broadcast.
type DASHURLs ¶
DASHURLs returns the initialization and media SegmentTemplate URLs of a session, relative to the MPD, with $RepresentationID$ and $Number$.
type Decoder ¶
Decoder yields frames already in Format, one per call, paced by the caller. Next blocks until a frame is ready; it returns io.EOF at end of input, and returns promptly with ctx.Err() on cancellation or after Close. The first frame after start is a keyframe of the input. Prewarm: a non-live decoder may be started ahead of time. It holds at most 8 decoded frames and then applies backpressure to ffmpeg (no unbounded buffering) until Next is called.
type DecoderRequest ¶
type DecoderRequest struct {
SessionID string
InputURL string // playback input or loopback-granted provider URL; never put on a command line raw
InputHeaders http.Header
Format RawFormat // decoder scales, frame-rate converts and resamples to this
Offset time.Duration
// Seeked marks a trusted indexed projection already starting at a keyframe.
// Offset is then a small forward trim, without another demuxer seek.
Seeked bool
Live bool // IPTV/live input: no seeking, no prewarm hold
// PrimeLive reads four provider segments on the first open only. Callers
// with an aired source timestamp must leave it false on reconnect.
PrimeLive bool
// ReserveStart starts an HLS live input at the first segment the relay
// lists, which is the stability reserve, instead of near the live edge.
ReserveStart bool
// InputFormat is the probed live container ("hls" or "mpegts"; empty when
// unknown). Demuxer-private options are only valid for their own demuxer.
InputFormat string
Loop bool // repeat a local cached master seamlessly; incompatible with Live and URLs
// AudioIndex is the input's audio track to decode, counted among its
// audio streams (0 = first). Callers pick it by language.
AudioIndex int
}
type DownloadRemuxer ¶
type DownloadRemuxer struct {
// contains filtered or unexported fields
}
DownloadRemuxer remuxes resolved sources to temporary MP4s. It implements core.DownloadRemuxer.
func (*DownloadRemuxer) ReleaseDownload ¶
func (d *DownloadRemuxer) ReleaseDownload(path string)
ReleaseDownload implements core.DownloadRemuxer.
func (*DownloadRemuxer) RemuxDownload ¶
func (d *DownloadRemuxer) RemuxDownload(ctx context.Context, req core.DownloadRemuxRequest, progress func(float64)) (string, int64, error)
RemuxDownload implements core.DownloadRemuxer.
func (*DownloadRemuxer) RetainDownload ¶
func (d *DownloadRemuxer) RetainDownload(path string, expires time.Time) error
RetainDownload binds a completed file to its queue retention. The small marker also protects it from boot orphan cleanup before the queue is loaded.
func (*DownloadRemuxer) UsedBytes ¶
func (d *DownloadRemuxer) UsedBytes() int64
UsedBytes is the budget currently held by finished and in-flight downloads (tests and diagnostics).
type EncoderRequest ¶
type EncoderRequest struct {
SessionID string
Source RawFormat // what Write receives
Decision core.Decision // output codec, size, bitrate, audio; fixed for life; HW from HWAccel
ClientCaps core.ClientCaps // viewer limits used for optional RTX VSR upscale headroom
SegmentDuration time.Duration // 4 s; keyframe exactly at every segment start
DVRWindow time.Duration // segments kept on node-local disk for timeshift (30 min default; 0 = live window only)
// LiveSource marks a provider (IPTV) channel: rate control may use one
// segment of VBV buffer under the ceiling, so keyframes of moving
// pictures are not starved. Scheduled channels keep a one-second bound.
LiveSource bool
}
type ExecRunner ¶
type ExecRunner struct{}
ExecRunner runs real executables with os/exec.
func (ExecRunner) Run ¶
func (ExecRunner) Run(ctx context.Context, c Command) error
Run implements Runner.
type GraphError ¶ added in v0.3.0
type GraphError struct{ Message string }
GraphError is a transcode this ffmpeg cannot build. The message is owner-visible (Activity and the transcoder health card). It is not an ffmpeg stderr tail, and it is not retried as the same filter graph.
func (*GraphError) Error ¶ added in v0.3.0
func (e *GraphError) Error() string
type Manager ¶
type Manager struct {
// contains filtered or unexported fields
}
Manager runs ffmpeg for Ether. It implements core.Transcoder.
func New ¶
New finds ffmpeg/ffprobe, detects hardware encoders and starts the idle session reaper. It fails with ErrFFmpegNotFound when no ffmpeg exists.
func (*Manager) AcquireTranscodeSlot ¶
func (m *Manager) AcquireTranscodeSlot(ctx context.Context, p SlotPriority) (context.Context, func(), error)
AcquireTranscodeSlot reserves the shared encoder budget. Run the job under jobCtx, and always release after its process has stopped. Viewers preempt the newest background holder; preemption cancels jobCtx and reclaims its charge immediately. Background callers wait behind every queued viewer.
func (*Manager) AdaptiveBudgetInfo ¶
func (m *Manager) AdaptiveBudgetInfo(sessionID string) (rungsKbps []int, currentCapKbps int, adaptive bool)
AdaptiveBudgetInfo returns the ladder rung bitrates (kbps, descending), the currently applied budget cap (0 = uncapped), and whether sessionID supports mid-stream adaptive budget stepping.
func (*Manager) AudioFallbackAvailable ¶
AudioFallbackAvailable requires the actual AAC encoder and fragmented MP4 segment muxers discovered at startup. Unknown inventory fails closed.
func (*Manager) CachedSubtitle ¶ added in v0.3.3
CachedSubtitle is the WebVTT of a track ExtractSubtitle already read whole for the source named by WithSubtitleSource, without reading anything.
func (*Manager) Capability ¶ added in v0.3.0
func (m *Manager) Capability() Capability
Capability reports probed filters and any owner-visible limitation.
func (*Manager) ContinuousBudget ¶
ContinuousBudget reports the CPU cores continuous outputs may use on this host, and whether a hardware video encoder takes their encode work.
func (*Manager) Decide ¶
func (m *Manager) Decide(info core.MediaInfo, caps core.ClientCaps, opts core.DecideOptions) core.Decision
Decide implements core.Transcoder.
func (*Manager) DetectHardSubs ¶
func (m *Manager) DetectHardSubs(ctx context.Context, input string, duration time.Duration) (bool, bool)
DetectHardSubs samples four scenes, at most one decoder per manager, with single-thread decoding and an eight-second wall budget. Inconclusive reads remain unknown. No OCR, subtitle service, or media upload is involved.
func (*Manager) DistributedHardwareEncoder ¶
func (m *Manager) DistributedHardwareEncoder(req core.HLSRequest) string
DistributedHardwareEncoder reports the encoder selected by this Manager's startup-verified hardware inventory for the exact supported request. The same planner validates its codec, picture size/depth/profile, filters and muxers; a software fallback never advertises hardware just because a GPU is present. This performs no process, source or reservation work.
func (*Manager) EncodingCount ¶
EncodingCount reports held encoding slots, including runs awaiting retirement.
func (*Manager) EnhancementStatus ¶ added in v0.2.4
func (m *Manager) EnhancementStatus() core.VideoEnhancementSupport
EnhancementStatus is suitable for an owner status API. Available means detection passed; it deliberately does not mean a VSR run has succeeded.
func (*Manager) ExtractSubtitle ¶
func (m *Manager) ExtractSubtitle(ctx context.Context, inputURL string, streamIndex int, codec string, w io.Writer) error
ExtractSubtitle writes an embedded text subtitle stream as WebVTT. It reads the whole input (subtitle packets are interleaved through it).
func (*Manager) FFmpegPath ¶
FFmpegPath is the ffmpeg executable in use.
func (*Manager) FFprobePath ¶
FFprobePath is the ffprobe executable in use.
func (*Manager) NewDownloadRemuxer ¶
func (m *Manager) NewDownloadRemuxer(cfg config.Downloads) (*DownloadRemuxer, error)
NewDownloadRemuxer prepares the download temp dir under the transcode temp dir. Boot cleanup follows the single stale-download policy (see staleDownloadAge in manager.go for who deletes what): stale dl-* orphans are removed by cleanStaleDownloads, while fresh dl-* orphans it keeps are ADOPTED by the new remuxer — registered in files/used at their real size, with their real mtime, so they count against the disk budget from the start and expire at runtime via expireStaleAdopted once they cross staleDownloadAge.
func (*Manager) OnAirEncoderOptions ¶
OnAirEncoderOptions shares the confirmed encoder and rate-control builder with playback. Inputs are software RGBA frames; VAAPI requires an explicit upload.
func (*Manager) ProactiveFallbackAvailable ¶
func (*Manager) ProbeLive ¶
ProbeLive accepts complete audio/video parameters without a finite duration. Requiring a duration on an endless feed always forces the expensive retry. This optional capability leaves ordinary file probing unchanged.
func (*Manager) ProbeLiveWithHeaders ¶
func (m *Manager) ProbeLiveWithHeaders(ctx context.Context, input string, headers map[string]string) (*core.MediaInfo, error)
ProbeLiveWithHeaders is the authenticated variant of the optional live probe.
func (*Manager) QualitySupport ¶
func (m *Manager) QualitySupport() QualitySupport
func (*Manager) Session ¶
func (m *Manager) Session(id string) (core.HLSSession, bool)
Session implements core.Transcoder.
func (*Manager) SessionBudgetStatus ¶
SessionBudgetStatus returns the active budget cap (kbps), whether a budget cap is active, and the active stepped rung id (if any) for sessionID.
func (*Manager) SetRemoteDeliveryObserver ¶
func (m *Manager) SetRemoteDeliveryObserver(fn func(RemoteDeliveryEvent))
SetRemoteDeliveryObserver installs an optional callback invoked after completed non-loopback media segment deliveries.
func (*Manager) SetSessionBudgetCap ¶
SetSessionBudgetCap applies (or clears when capKbps <= 0) a dynamic shared upload budget cap on a running adaptive HLS session.
func (*Manager) StartDecoder ¶
func (*Manager) StartEncoder ¶
func (m *Manager) StartEncoder(ctx context.Context, r EncoderRequest) (ContinuousEncoder, error)
StartEncoder starts a fixed rendition. Scaling stays in ffmpeg (one scale per rendition); callers send the same largest working frame to every rendition.
func (*Manager) StartHLS ¶
func (m *Manager) StartHLS(ctx context.Context, req core.HLSRequest) (core.HLSSession, error)
StartHLS implements core.Transcoder. A replacement cannot begin until the prior exact session has completed its process and directory cleanup.
func (*Manager) StartHLSOwned ¶ added in v0.3.0
func (m *Manager) StartHLSOwned(ctx context.Context, req core.HLSRequest) (core.HLSSession, core.EncoderRetirement, error)
func (*Manager) StartRenditions ¶
func (m *Manager) StartRenditions(ctx context.Context, requests []EncoderRequest) ([]ContinuousEncoder, error)
StartRenditions starts encoders sharing one switcher working format. Each encoder performs its own native scale; no Go image scaling or extra decoder is needed. Failure closes every encoder already started by this call.
func (*Manager) StreamSubtitle ¶ added in v0.3.3
func (m *Manager) StreamSubtitle(ctx context.Context, inputURL string, streamIndex int, codec string, from time.Duration, w io.Writer) error
StreamSubtitle writes one embedded text subtitle stream as an ASS script while it reads the input from from onward: the header first, then each event as its packet is read, on the title clock (-copyts). This is what Plex's HTML player reads (libjass parses the script as it arrives), so the cues around the playhead arrive in seconds instead of after the whole release. After a one-minute burst the input is read at 1.5x real time, as a background read, so it stays ahead of playback without competing with it. At most maxSubtitleStreams run at once; a caller waits for a slot until ctx ends.
func (*Manager) SupportsDistributedRequest ¶
func (m *Manager) SupportsDistributedRequest(req core.HLSRequest) bool
SupportsDistributedRequest checks the actual normalized command dependencies against startup-probed inventory. It performs no source, process, assignment or reservation work. Transport capability/policy checks remain mandatory too. The same fixed dedicated Manager must be used for preflight and actual start; this is not a promise of future capacity or successful device/process execution.
func (*Manager) ToneMapsDolbyVisionProfile5 ¶
ToneMapsDolbyVisionProfile5 reports whether this ffmpeg can reshape a Dolby Vision profile 5 (IPTPQc2) picture through its RPU and tone-map it to SDR. Profile 5 has no HDR10 base, so without it a video conversion of such a source is refused.
func (*Manager) UpdateConfig ¶
UpdateConfig applies changed limits (MaxTranscodes, RemoteMaxBitrateKbps) and schedules optional RTX runtime setup. FFmpeg paths and the ordinary hardware encoder choice still need a restart.
func (*Manager) VideoTranscodingOff ¶
VideoTranscodingOff reports whether video re-encoding is disabled for movies and shows in the current configuration.
type Option ¶
type Option func(*options)
Option tunes a Manager.
func WithBuffering ¶
WithBuffering tunes seeking and disk use: a request more than restartAhead past the encoder restarts ffmpeg there (default 24s); ffmpeg is suspended when maxAhead in front of the player (default 2m, 0 = never); segments more than keepBehind behind the player are deleted (default 3m, 0 = never).
func WithDecodeStore ¶
WithDecodeStore persists device decode capability results across restarts.
func WithEncoderObserver ¶ added in v0.2.49
WithEncoderObserver is told when ffmpeg starts or fails to start. excerpt is already redacted argument text and must not be required for playback.
func WithEvents ¶
WithEvents configures the domain event bus for transcode events such as hardware-to-software fallback notifications.
func WithIdleTimeout ¶
WithIdleTimeout sets how long an unrequested session lives (default 2m).
func WithInputFailureHandler ¶ added in v0.2.4
func WithInputFailureHandler(f func(sessionID, inputURL string, at time.Duration, err error)) Option
WithInputFailureHandler includes the failed input generation, so delayed encoder exits cannot fail over a healthy replacement that is already playing.
func WithOnChange ¶
func WithOnChange(f func()) Option
WithOnChange is notified when owner-visible transcoder capability state changes.
func WithRunStartHandler ¶ added in v0.2.4
WithRunStartHandler is told, before ffmpeg is spawned, which part of the input a new run will read first, so the source can fetch it in parallel while the encoder starts and locates it.
func WithRuntimeDir ¶ added in v0.2.10
WithRuntimeDir enables managed optional tool installation in this node-local directory. No downloads occur while RTX Video is off. Embedded/test managers that omit this option never install software.
func WithSegmentPadLimit ¶
WithSegmentPadLimit bounds how long a slow segment's response is padded before the request aborts (default segmentPadMax).
func WithSegmentTimeout ¶
WithSegmentTimeout bounds how long ServeSegment waits for ffmpeg (default 45s).
func WithStallTimeout ¶ added in v0.3.4
WithStallTimeout sets the no-progress timeout for an actively requested on-demand segment. Zero disables the watchdog.
func WithSubtitleOpener ¶
WithSubtitleOpener resolves ether-subtitle:<id> sidecars into session-local files so burn-in and Matroska soft-subtitle muxing use aligned timing.
func WithTracePlayback ¶ added in v0.3.0
WithTracePlayback logs Plex HLS playhead decisions and ffmpeg run start/stop reasons. It does not change encoding or delivery.
func WithoutHWDetection ¶
func WithoutHWDetection() Option
WithoutHWDetection skips the startup hardware probe and encodes on CPU.
type PlaybackDefaults ¶ added in v0.3.0
type PlaybackDefaults struct {
ID string
Video, Audio, Containers []string
MaxHeight int
HDR10, DolbyVision, HeightLocked bool
// DolbyVisionOff: an owner override turned Dolby Vision off, so a
// profile 7/8 copy carries only its compatible base layer.
DolbyVisionOff bool
// AlwaysEncodeVideo: an owner override disabled video copy on streams.
AlwaysEncodeVideo bool
}
PlaybackDefaults is the registry baseline for a client that sent no profile. ID is the matched playback record. "generic" means nothing more specific matched.
func PlaybackDefaultsFor ¶ added in v0.3.0
func PlaybackDefaultsFor(product, platform, device, model, version string, overrides []core.ClientCapabilityOverride) PlaybackDefaults
PlaybackDefaultsFor evaluates the registry, including owner overrides. Model is separate from ClientCaps because Plex carries it on the request.
type Policy ¶
type Policy struct {
// RemoteMaxBitrateKbps caps streams to clients outside the LAN; 0 = none.
RemoteMaxBitrateKbps int
// HEVCEncoder is true when HEVC can be encoded in real time (Manager
// sets it only for hardware encoders). It is required to keep HDR in a
// transcode; without it HDR is tone-mapped to SDR H.264.
HEVCEncoder bool
// HEVCHardware is true when HEVC encoding is hardware accelerated, which
// makes HEVC a good target for 4K transcodes.
HEVCHardware bool
}
Policy is the server-side input to Decide that is not per request.
type Process ¶
type Process interface {
// Done is closed when the process has exited.
Done() <-chan struct{}
// Err is the exit error; valid once Done is closed.
Err() error
// Stop kills the process and blocks until it is gone. It is safe to
// call more than once and after exit.
Stop()
// Pause suspends the process (throttling); ErrPauseUnsupported where
// the platform cannot.
Pause() error
// Resume continues a paused process.
Resume() error
}
Process is a started long-running command (an ffmpeg HLS run).
type Progress ¶
type Progress struct {
Frame int64 `json:"frame"`
FPS float64 `json:"fps"`
Speed float64 `json:"speed"` // x realtime
OutTime time.Duration `json:"outTime"` // media time reached
Bitrate string `json:"bitrate,omitempty"`
Ended bool `json:"ended"`
Updated time.Time `json:"updated"`
}
Progress is the latest `-progress` report of a session's ffmpeg run.
type QualitySupport ¶
type QualitySupport struct{ HEVC, ToneMap, DolbyVision5 bool }
QualitySupport is a snapshot of already-probed local encoder capabilities. Planning must never probe hardware or start a process.
type RawFormat ¶
type RawFormat struct {
Width, Height int // even; the channel's largest rendition size
FPSNum, FPSDen int // a broadcast rate: 24, 25, 30, 50 or 60 (and the /1001 NTSC forms)
SampleRate int // 48000
Channels int // 2
PixelFormat string // "yuv420p" (I420, planar, tightly packed: Y then U then V, no row padding)
}
RawFormat is the switcher's working format. It is fixed for a channel output's life.
type RawFrame ¶
type RawFrame struct {
// GraphicsTransition marks the first animated frame replacing a title plate.
GraphicsTransition bool
OutputTime time.Time // scheduled output-clock time, independent of delivery/burst time
// PolicyTags are immutable comparable identities supplied by the planner.
// Every identity represented in a segment survives encoder publication.
PolicyTags []any
// SourcePTS is the original live input presentation time, before re-timing
// onto the output clock. Live decoders always set SourcePTSValid; encoders
// ignore this metadata. It detects stale media across provider reconnects.
SourcePTS time.Duration
SourcePTSValid bool
RepeatVideo bool // encoder may repeat this picture at a lower input cadence
Video []byte // len = W*H*3/2
PCM []byte // len = samples*Channels*2
}
RawFrame is exactly one output tick: one video frame, plus the PCM for that tick (interleaved signed 16-bit little-endian). Samples per tick follow an exact accumulator: tick n carries floor((n+1)*SR*FPSDen/FPSNum) - floor(n*SR*FPSDen/FPSNum) samples per channel, so audio never drifts (1600 every tick at 48 kHz / 30 fps).
type RemoteDeliveryEvent ¶
type RemoteDeliveryEvent struct {
SessionID string
RemoteAddr string
Bytes int64
Duration time.Duration
SegDuration time.Duration
MediaBitrateKbps int
TCPBacklogBytes int
}
RemoteDeliveryEvent reports one completed media-segment delivery write phase so the upload budget estimator can passively measure link upload throughput and TCP send backpressure from real remote streams.
type Runner ¶
type Runner interface {
// Start launches a long-running command.
Start(cmd Command) (Process, error)
// Run executes a command to completion, killing it when ctx ends.
Run(ctx context.Context, cmd Command) error
}
Runner starts processes. The default runs real executables; tests inject fakes.
type Segment ¶
Segment is one finished segment. Seq is contiguous from 0 for the encoder's life; Start is the wall-clock time of its first frame (PROGRAM-DATE-TIME); Duration is exact (120 frames at 30000/1001 = 4.004 s).
type SegmentIndex ¶
type SegmentIndex interface {
Latest() (Segment, bool) // newest finished segment
Window(from, until time.Time) []Segment // segments overlapping [from, until), oldest first
Since(seq int64, max int) []Segment // up to max segments with Seq > seq
Wait(ctx context.Context, after int64) (Segment, error) // blocks until segment after+1 is finished
ServeTS(w http.ResponseWriter, r *http.Request, seq int64) // MPEG-TS segment (HLS)
ServeInit(w http.ResponseWriter, r *http.Request) // fMP4 init (DASH)
ServeFMP4(w http.ResponseWriter, r *http.Request, seq int64) // fMP4 media segment (DASH)
AttachTS(ctx context.Context) (io.ReadCloser, error) // live continuous TS from the live edge; bounded fan-out
Format() (codecs string, width, height int, bandwidth int) // for playlists and MPD Representation attributes
}
SegmentIndex is safe for concurrent use. Only finished segments are listed. Segments older than DVRWindow are evicted; Window never returns evicted segments, and serving one returns core.ErrNotFound.
type SegmentPlan ¶
type SegmentPlan struct {
Index int
Start time.Duration // playlist-relative
Duration time.Duration
Mode SegMode
}
SegmentPlan is one planned segment, for tests and admin reporting.
type Session ¶
type Session struct {
// contains filtered or unexported fields
}
Session is one HLS or DASH remux or transcode. It implements core.HLSSession, and core.DASHSession for DASH sessions.
Segment n always covers media time base+n*segDur (base is the request's StartOffset for HLS and 0 for DASH, whose MPD always spans the whole title). ffmpeg runs are started at a segment boundary with -ss and -copyts, so restarting at any segment (a seek far ahead or behind, a failover to another release) keeps numbering and timestamps continuous.
An HLS session has one track of muxed segments. A DASH session has one track per representation (video, audio); ffmpeg's dash muxer writes short chunks that the session regroups into numbered segments by timestamp.
func (*Session) AdaptiveBudgetInfo ¶
AdaptiveBudgetInfo reports ladder rung bitrates (descending) and whether this session can step down/up mid-stream for the shared upload budget.
func (*Session) BudgetStatus ¶
BudgetStatus reports the session's active shared upload budget cap.
func (*Session) CheckSwap ¶ added in v0.2.4
CheckSwap reports whether SwapInput can deliver info's video in the format the client already opened. Playback calls it before committing a replacement so an incompatible candidate is skipped, not spliced.
func (*Session) CurrentSwapInput ¶ added in v0.3.3
func (*Session) EncoderRetirement ¶ added in v0.3.0
func (s *Session) EncoderRetirement() core.EncoderRetirement
func (*Session) EncoderStatus ¶ added in v0.3.3
func (s *Session) EncoderStatus() *core.EncoderStatus
EncoderStatus snapshots the active run, including adaptive copy-to-encode transitions that do not change the initially negotiated decision.
func (*Session) GoodputKbps ¶
GoodputKbps is the session's measured client delivery goodput.
func (*Session) HWAccelerated ¶
HWAccelerated reports whether the current run encodes on hardware.
func (*Session) HasTextSubtitle ¶
HasTextSubtitle reports tracks attached to this playback's source read.
func (*Session) IndependentSegments ¶ added in v0.3.0
IndependentSegments implements core.HLSIndependentSegments. It reports a proven all-renditions guarantee, not the legacy playlist convention.
func (*Session) LastAccess ¶
LastAccess implements core.HLSSession.
func (*Session) LastMediaAccess ¶
LastMediaAccess implements core.MediaAccessTracker. It stays zero until a client-facing media/init segment is served (creation, playlists, and paused timelines do not advance it).
func (*Session) PlaybackDelivered ¶
PlaybackDelivered distinguishes actual output from ffmpeg input/read-ahead.
func (*Session) PlaybackDiagnostics ¶
func (s *Session) PlaybackDiagnostics() core.HLSPlaybackDiagnostics
func (*Session) PlaybackState ¶ added in v0.2.9
func (*Session) PrepareRung ¶
PrepareRung requests the existing ladder's segment; it creates no parallel encoder.
func (*Session) PrepareSwap ¶ added in v0.2.9
func (s *Session) PrepareSwap(ctx context.Context, input string, info core.MediaInfo, at time.Duration) error
PrepareSwap checks real replacement pixels while the old generation still owns playback. Failed reads reject only this candidate, never the title.
func (*Session) RecoveryBuffer ¶ added in v0.2.8
func (s *Session) RecoveryBuffer() core.RecoveryBuffer
func (*Session) RequestedPosition ¶ added in v0.2.4
RequestedPosition is the title position of the player's latest segment request. Source reads can be far ahead or at the container's tail index.
func (*Session) RetireEncoder ¶ added in v0.3.0
func (*Session) SegmentDuration ¶
SegmentDuration is the session's segment length.
func (*Session) ServeInit ¶
ServeInit implements core.DASHSession: representation rep's initialization segment.
func (*Session) ServeManifest ¶
func (s *Session) ServeManifest(w http.ResponseWriter, r *http.Request)
ServeManifest implements core.DASHSession: the static, full-length MPD. The first request waits (bounded) for ffmpeg's init segments so the MPD carries exact codecs strings; until then they are estimated.
func (*Session) ServeMedia ¶
ServeMedia implements core.DASHSession: media segment n of representation rep. Each segment starts with its run's init segment, so segments from different ffmpeg runs (seeks, failovers) play back to back.
func (*Session) ServePlaylist ¶
func (s *Session) ServePlaylist(w http.ResponseWriter, r *http.Request)
ServePlaylist implements core.HLSSession: the full-length VOD playlist (the MPD for DASH sessions).
func (*Session) ServeRungPlaylist ¶
ServeRungPlaylist implements core.HLSLadderSession.
func (*Session) ServeRungSegment ¶
ServeRungSegment implements core.HLSLadderSession.
func (*Session) ServeSegment ¶
ServeSegment implements core.HLSSession. n == InitSegment serves the fMP4 init segment. For DASH sessions it serves the first representation.
func (*Session) ServeSoftSubtitle ¶ added in v0.3.4
ServeSoftSubtitle attaches to the ASS output of the active encoder. The output belongs to the run, not the HTTP request, so retries do not open a second source reader. Encoder replacements are followed on the same stream.
func (*Session) ServeTextSubtitlePlaylist ¶
ServeTextSubtitlePlaylist follows the video plan, including its ramp and discontinuities. Each subtitle fragment is fetched independently, so native HLS clients never wait for a complete sidecar or retain an incomplete one.
func (*Session) ServeTextSubtitleSegment ¶
ServeTextSubtitleSegment waits for the matching video window. A subtitle request never seeks or starts an encoder: only video requests drive playback.
func (*Session) SetBudgetCapKbps ¶
SetBudgetCapKbps steps a running adaptive HLS session down when capKbps > 0 tightens its allowance and back up when capKbps widens or clears (0). Unserved future segments are discarded and the current encoder is stopped so the next segment request seamlessly encodes at the new bitrate/rung.
func (*Session) SkipDamagedSegment ¶
func (s *Session) SkipDamagedSegment(ctx context.Context, inputURL string, info core.MediaInfo, at time.Duration) error
SkipDamagedSegment implements core.DamagedSegmentSkipper: after failover cannot recover a corrupt mid-stream segment on another release, alias up to maxDamagedSkipsIncident consecutive segments with valid empty placeholders and seek ffmpeg past the damaged range, bounded by exponential backoff, per-session hard caps, and client liveness.
func (*Session) SwapInput ¶
func (s *Session) SwapInput(ctx context.Context, inputURL string, info core.MediaInfo, at time.Duration) error
SwapInput implements core.HLSSession: restart on a new input at `at` (mid-stream failover). Segments from `at` on are discarded and produced again from the new input; numbering stays continuous.
func (*Session) SwapInputBuffered ¶ added in v0.2.8
func (*Session) SwapWouldCopyVideo ¶ added in v0.3.3
SwapWouldCopyVideo is a preference only; CheckSwap remains the admission check. It evaluates the probed stream against the delivered contract.
func (*Session) TextSubtitleCues ¶
TextSubtitleCues reads a bounded window from local disk, never the source.
func (*Session) TimelineOrigin ¶
TimelineOrigin is the title time represented by playlist time zero.
func (*Session) Touch ¶
func (s *Session) Touch()
Touch marks the session as in use (e.g. on a Plex timeline ping while the client is paused) so the idle reaper keeps it.
func (*Session) WaitForReplacementOutput ¶ added in v0.3.3
WaitForReplacementOutput waits for the first segment at the handoff and for the published sequence from the current playhead to reach past it. This is server-side publication evidence, not client delivery or decode.
type SlotPriority ¶
type SlotPriority uint8
SlotPriority separates interactive viewing from cancellable render jobs.
const ( SlotViewer SlotPriority = iota SlotBackground // SlotLivePrep is a single reserved lane for imminent channel masters. // It cannot be preempted by a viewer or consume the viewer encoder budget. SlotLivePrep )
type SourceProbeOptions ¶
type SourceProbeOptions struct {
FFprobePath, FFmpegPath string
Runner Runner
Timeout time.Duration // default 20s, max 1m, including queue time
Concurrency int // default 2, max 16
}
SourceProbeOptions creates no encoder/hardware/session manager. FFmpegPath is only a sibling-directory hint for the existing bundled ffprobe discovery.
type SourceProber ¶
type SourceProber struct {
// contains filtered or unexported fields
}
SourceProber owns all invocations and joins them on Close. Runner.Run must return only after its child and output readers have joined (ExecRunner does). No process, sampling loop or provider connection starts in the constructor.
func NewSourceProber ¶
func NewSourceProber(o SourceProbeOptions) (*SourceProber, error)
func (*SourceProber) Close ¶
func (p *SourceProber) Close() error
type SubtitleReaderOpener ¶
SubtitleReaderOpener opens the session's source for direct reads. release ends the hold on it.
type ThumbOptions ¶
type ThumbOptions struct {
Runner Runner
FFmpeg string
Logger *slog.Logger
Interval time.Duration // frame spacing (default 10s)
Width int // thumbnail width px (default 320, Plex "sd")
Quality int // ffmpeg -q:v (default 7)
FrameTimeout time.Duration // per-frame extraction cap (default 25s)
BatchFrames int // frames per batch before a pause (default 12)
BatchPause time.Duration // pause between batches (default 4s)
MaxConcurrent int // global extraction jobs (default 2)
MaxBytes int64 // total stored JPEG bytes, LRU-evicted (default 256MiB)
MaxReleases int // releases kept, LRU-evicted (default 32)
RetryBackoff time.Duration // pause before retrying a failed release (default 2m)
}
ThumbOptions tunes a Thumbnails store. Runner and FFmpeg are required; zero limits take the defaults documented on each field.
type Thumbnails ¶
type Thumbnails struct {
// contains filtered or unexported fields
}
Thumbnails builds sparse BIF preview indexes for releases while they stream. Extraction only ever reads a source handed to EnsureTrickplay (the loopback input of an active playback or warmup session): one fast-seek ffmpeg run per frame decodes a single (key)frame, so bytes are read around the requested frame only — never the whole file ahead of playback. Jobs run at most one per release under a small global cap, fill in bounded batches with pauses, and stop when the source stops answering (the session ended) or Close is called.
It implements core.TrickplayProvider.
func NewThumbnails ¶
func NewThumbnails(o ThumbOptions) *Thumbnails
NewThumbnails builds an empty thumbnail store. Call Close on shutdown.
func (*Thumbnails) CancelTrickplay ¶
func (t *Thumbnails) CancelTrickplay(releaseID string)
CancelTrickplay stops the active extraction for a release. Playback calls this after the last viewer session for that release ends.
func (*Thumbnails) Close ¶
func (t *Thumbnails) Close() error
Close stops all generation and waits for jobs to finish.
func (*Thumbnails) EnsureTrickplay ¶
func (t *Thumbnails) EnsureTrickplay(_ context.Context, src core.TrickplaySource)
EnsureTrickplay implements core.TrickplayProvider.
func (*Thumbnails) PreviewInterval ¶ added in v0.3.0
func (t *Thumbnails) PreviewInterval() time.Duration
PreviewInterval and PreviewWidth describe the grid the shared provider generates. Callers compose sheets from these values instead of assuming a second thumbnail cache.
func (*Thumbnails) PreviewWidth ¶ added in v0.3.0
func (t *Thumbnails) PreviewWidth() int
func (*Thumbnails) SetTrickplayFallback ¶
func (t *Thumbnails) SetTrickplayFallback(releaseID string, jpeg []byte)
SetTrickplayFallback implements core.TrickplayProvider.
func (*Thumbnails) TrickplayAvailable ¶
func (t *Thumbnails) TrickplayAvailable(releaseID string) bool
TrickplayAvailable implements core.TrickplayProvider.
func (*Thumbnails) TrickplayBIF ¶
func (t *Thumbnails) TrickplayBIF(releaseID string) ([]byte, bool)
TrickplayBIF implements core.TrickplayProvider.
func (*Thumbnails) TrickplayFrame ¶
TrickplayFrame implements core.TrickplayProvider.
type Timeline ¶
type Timeline struct {
// SwitchSeg is the first steady segment after the fast-start ramp
// (== len(durs) when the whole title is ramp, 0 when there is none).
SwitchSeg int
// contains filtered or unexported fields
}
Continuous opening cuts retain the encoder mode and mux clock: encoded output forces 0.5/0.5/1s cuts, while copied output ends its first segment at the next observed keyframe. One source GOP is the copy latency floor; short hls_time alone cannot split it. Subsequent cuts use the steady plan.
Timeline is a session's segment plan. Starts are relative to the session's playlist position zero (the HLS StartOffset); callers add base for absolute media time.
func (*Timeline) Keyframed ¶ added in v0.2.4
Keyframed reports whether the boundaries come from a keyframe index.
func (*Timeline) NextChange ¶
NextChange is the first segment after n produced in a different mode than n (the exclusive end of a run starting at n), or -1 when the mode runs to the end of what is known.
func (*Timeline) Plan ¶
func (tl *Timeline) Plan(n int) SegmentPlan
Plan returns segment n's plan. discont reports discontinuities for the primary encode; rung playlists pass their own via playlist rendering.
func (*Timeline) TargetDuration ¶
TargetDuration is the HLS #EXT-X-TARGETDURATION: the ceiling of the longest segment duration.
Source Files
¶
- aac_pce.go
- args.go
- audio_match.go
- bif.go
- bif_thumbs.go
- bitmap_pipeline.go
- bitstream.go
- capabilities.go
- capability_assertions.go
- chunks.go
- clientpolicy.go
- colour.go
- continuous.go
- continuous_capacity.go
- continuous_dash.go
- continuous_decoder.go
- continuous_encoder.go
- continuous_output.go
- continuous_process.go
- continuous_rawvideo.go
- continuous_rtx.go
- continuous_store.go
- continuous_timeline.go
- continuous_watchdog.go
- contract.go
- copy_damage.go
- copy_seek.go
- copy_timeline.go
- dash.go
- dash_session.go
- decide.go
- decode_caps.go
- decode_store.go
- discover.go
- distributed_enhancement.go
- distributed_features.go
- distributed_keyframes.go
- distributed_ramp.go
- distributed_support.go
- download.go
- download_watchdog.go
- encoder.go
- encoder_input.go
- encoder_retirement.go
- events.go
- failover_audio.go
- fmp4.go
- fmp4_edit.go
- goodput.go
- gpu_pipeline.go
- gpu_vendor.go
- guardian.go
- h264_level.go
- hardsub.go
- hevc_parameters.go
- hevc_vui.go
- hls_attributes.go
- hls_bandwidth.go
- hls_rate.go
- http_matroska.go
- http_session.go
- hwaccel.go
- input_failure.go
- input_headers.go
- input_safety.go
- ladder.go
- live_audio.go
- live_timestamps.go
- manager.go
- manager_testapi.go
- media_generation.go
- mkv_hls.go
- mux_output.go
- mux_output_other.go
- nativeprobe.go
- nativeprobe_mp4.go
- onair.go
- pce_seek.go
- picture_crop.go
- playback_diagnostics.go
- playlist.go
- priority_unix.go
- probe.go
- probe_live.go
- proc_unix.go
- process_memory_unix.go
- progress.go
- qsv.go
- qsv_tonemap.go
- recovery_buffer.go
- recovery_mp4_index.go
- recovery_request.go
- recovery_ts_aac.go
- remove.go
- resume_warm.go
- rtx_args.go
- rtx_install.go
- rtx_process_other.go
- rtx_session.go
- rtx_setup.go
- rtx_video.go
- runner.go
- seek_ramp_index.go
- segment_files.go
- segment_padding.go
- segment_plan.go
- session.go
- session_delivery.go
- session_encoder.go
- session_monitor.go
- session_playlist.go
- session_soft_subtitle.go
- session_swap.go
- session_watchdog.go
- slate.go
- slots.go
- software_threads.go
- source_probe.go
- stream_match.go
- subtitle_cache.go
- subtitle_index.go
- text_subtitle_delivery.go
- text_subtitle_store.go
- ts_discontinuity.go
- upload_budget.go
- vbv.go
- vela_quality.go
- videotoolbox_compat.go