ffmpeg

package
v0.48.0 Latest Latest
Warning

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

Go to latest
Published: Nov 24, 2026 License: MIT Imports: 32 Imported by: 1 module, 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 ffmpeg probes media, builds filter graphs and runs FFmpeg.

Index

Constants

View Source
const (
	// MaxAnimFrames is the most frames an animated image may have (SDD-001 section 3.2).
	MaxAnimFrames = 1000
	// MaxAnimPixels is the most pixels, summed over all frames, an animated image may decode to. It
	// bounds the work and the disk of the frame sequence: 128 Mpixel is 512 MiB of raw RGBA.
	MaxAnimPixels int64 = 134_217_728
)
View Source
const (
	CodecH264 = "h264"
	CodecHEVC = "hevc"
	CodecAV1  = "av1"
)

The video codecs an export can write (SDD-004 sections 8.2 and 8.3). They are the names of core/export; the engine keeps its own constants so that this package imports no domain package.

View Source
const (
	EnvFFmpeg  = "STUARTY_FFMPEG"
	EnvFFprobe = "STUARTY_FFPROBE"
)

EnvFFmpeg and EnvFFprobe name the variables of the configured source (SDD-000 section 10). The caller reads them; this package never touches the environment of the server.

View Source
const (
	CodeFFmpegMissing    = "E_FFMPEG_MISSING"
	CodeNoEncoder        = "E_NO_ENCODER"
	CodeUnsupportedMedia = "E_UNSUPPORTED_MEDIA"
	CodeLimitExceeded    = "E_LIMIT_EXCEEDED"
	CodeInternal         = "E_INTERNAL"
)

Error codes of SDD-000 section 8 that this package raises.

View Source
const (
	// OpenH264Tool is the name of the install step: "stuarty tools:install openh264".
	OpenH264Tool = "openh264"
	// EnvOpenH264Dir is the variable that tells the own build where the verified library is. It is set
	// only for the tools of an installation whose library passed verification, and only the own build reads it.
	// The name is the one the pinned build ffmpeg-9.0.2-2 reads (.config/ffmpeg-build/patches/); it
	// changes with the next rebuild of that build, not before.
	EnvOpenH264Dir = "VUKEM_VIDEO_OPENH264_DIR"
	// OpenH264InstallCommand is what an error says to run.
	OpenH264InstallCommand = "stuarty tools:install " + OpenH264Tool
)

The Cisco OpenH264 library of the own FFmpeg build (D-017, ADR-0011). The build does not carry it: it is downloaded by an explicit install step, never by an export, a transcription or an agent call, and the build loads it at run time from the directory the runner names in EnvOpenH264Dir.

View Source
const (
	ReasonOpenH264NotInstalled = "openh264_not_installed"
	ReasonOpenH264Changed      = "openh264_changed"
	ReasonOpenH264Platform     = "openh264_unsupported_platform"
	ReasonChecksumMismatch     = "checksum_mismatch"
	ReasonSizeMismatch         = "size_mismatch"
	ReasonNotPublished         = "not_published"
	ReasonDownloadFailed       = "download_failed"
	ReasonBadArchive           = "bad_archive"
)

Reasons of the errors of the OpenH264 library (details.reason).

View Source
const (
	// MaxSourceEdge is the fixed limit of the longest side of a source.
	MaxSourceEdge = 8192
	// MaxStreams is the stream limit of FF-06.
	MaxStreams = 16

	// DefaultMaxPixels is the default of STUARTY_MAX_IMPORT_PIXELS.
	DefaultMaxPixels int64 = 33_177_600
	// DefaultMaxSeconds is the default of STUARTY_MAX_IMPORT_SECONDS.
	DefaultMaxSeconds float64 = 14400
)
View Source
const (
	ProbeTimeout = 30 * time.Second
	FrameTimeout = 30 * time.Second
	StallTimeout = 120 * time.Second
	MaxProbeJSON = 4 << 20

	// OutputPollInterval is how often the size watchdog looks at the output file.
	OutputPollInterval = 2 * time.Second
	// CancelGrace is how long a cancelled run may take to end before the job is failed with
	// details.reason "cancel_timeout" (SDD-007 6.6).
	CancelGrace = 5 * time.Second
)

Timeouts and limits of SDD-007 6.5 (defaults; the multipliers may change after the ALPHA measurements). Every run gets a context deadline from this table, so the 5 minute default of contrib/engine never widens it.

View Source
const EnvAllowRoot = "STUARTY_INSECURE_ALLOW_ROOT"

EnvAllowRoot is the variable that lets the runner start children as root. The service validates the same name at boot (SDD-007 4.5); the engine does not import the service, so the name is repeated here.

View Source
const ReasonCancelTimeout = "cancel_timeout"

ReasonCancelTimeout is details.reason of a job whose process could not be killed (SDD-007 6.6): the run directory is kept for doctor.

View Source
const ReasonCodecUnavailable = "codec_unavailable"

ReasonCodecUnavailable is details.reason of E_NO_ENCODER when the codec an export asks for has no encoder that works on this machine.

View Source
const ReasonRefusedEncoder = "refused_encoder"

ReasonRefusedEncoder is the Reason of a candidate that was never tried because it is a GPL or nonfree encoder.

View Source
const SandboxBwrap = "bwrap"

SandboxBwrap is the value of STUARTY_SANDBOX that wraps every tool in bubblewrap (SDD-007 6.7).

View Source
const SniffSize = 4096

SniffSize is how much of a file FF-05 reads before FFmpeg is started.

View Source
const TestedVersion = "9.0.2"

TestedVersion is the release the product was tested on (SDD-011 8.2).

Variables

View Source
var (
	HEVCEncoders = []string{
		"hevc_videotoolbox", "hevc_nvenc", "hevc_qsv", "hevc_amf", "hevc_mf", "hevc_vaapi",
	}
	AV1Encoders = []string{
		"av1_nvenc", "av1_qsv", "av1_amf", "av1_vaapi", "libsvtav1", "libaom-av1",
	}
)

HEVCEncoders and AV1Encoders are the allow list of RF-089 and D-067, in the order they are tried: the vendor encoders of the three systems, then software encoders with a permissive licence. There is no software HEVC encoder here: libx265 is GPL, and the only other one in common builds is slower than the H.264 fall back, so HEVC is a hardware codec.

View Source
var (
	// ErrStalled means -progress showed no advance for the stall window and the run was killed.
	ErrStalled = errors.New("ffmpeg: no progress, run stalled")
	// ErrDeadline means the run exceeded its deadline and was killed.
	ErrDeadline = errors.New("ffmpeg: deadline exceeded")
)

Sentinels a caller tells apart with errors.Is.

View Source
var (
	ExportDeadlineCeiling = ExportDeadline(10 * time.Hour)
	IngestDeadlineCeiling = IngestDeadline(10 * time.Hour)
)

ExportDeadlineCeiling and IngestDeadlineCeiling are the caps already applied by ExportDeadline and by IngestDeadline / IngestDeadlineFor. A deadline that grows because other runs share the process stops at the ceiling of its kind.

View Source
var EncoderOrder = []string{
	"h264_videotoolbox", "h264_nvenc", "h264_qsv", "h264_amf", "h264_mf", "h264_vaapi", "libopenh264", "libx264",
}

EncoderOrder is ADR-0011 item 5: the first H.264 encoder that works on the machine wins. libx264 is last and only for the user's own FFmpeg when the user enabled it.

View Source
var ErrEncoderSize = errors.New("ffmpeg: the encoder cannot encode this size and frame rate")

ErrEncoderSize means the chosen encoder could not encode the size and rate that was asked for.

View Source
var ErrHelperSandboxed = errors.New("ffmpeg: a graphics helper cannot run inside the sandbox")

ErrHelperSandboxed means a helper that needs the graphics devices was asked for while the runner wraps its tools in bubblewrap: the wrapper hides the devices, so the caller uses its fallback.

View Source
var ErrOutputTooLarge = errors.New("ffmpeg: output over the size cap")

ErrOutputTooLarge means the output file passed the size cap and the run was killed.

View Source
var ErrRefusedRoot = errors.New("ffmpeg: refusing to start a child as root")

ErrRefusedRoot means the process runs as uid 0 and STUARTY_INSECURE_ALLOW_ROOT is not true, so no child was started (SDD-007 T-16).

View Source
var ErrStdinUnsupported = errors.New("ffmpeg: an argv that reads pipe:0 needs a Stdin")

ErrStdinUnsupported is returned for an argv that reads pipe:0 when the request has no Stdin.

View Source
var ErrSymlinkInStore = errors.New("ffmpeg: a symbolic link inside the store")

ErrSymlinkInStore is returned for a link inside store/: the store holds only regular files that this product wrote (SDD-007 6.4).

View Source
var RefusedEncoders = []string{"libx265", "libx264rgb", "libxavs2", "libxvid", "libfdk_aac"}

RefusedEncoders are the encoders that are never used, even when the user's FFmpeg has them and even when one is forced: they are GPL or nonfree (ADR-0011, ADR-0003, NFR-043). libx264 is not here because the H.264 detection already allows it for a user's own build with an explicit opt-in.

Functions

func AudioExtractDeadline

func AudioExtractDeadline(audio time.Duration) time.Duration

AudioExtractDeadline is 60 s + 1 x audio duration, at most 1 h.

func BwrapArgs

func BwrapArgs(toolPath, storeDir, runDir string, inputDirs []string, argv []string) []string

BwrapArgs is the argv that runs tool with argv inside bubblewrap: every namespace unshared (so no network), the tool and its libraries and the store read-only, the run directory the only writable place, and the child dying with its parent.

func CheckAnimation

func CheckAnimation(frames, width, height int) error

CheckAnimation applies the animation ceilings of SDD-007 9.1 to the frame count and the size of an animated image, known from the packets and the stream header and before any frame is decoded (T-17).

func CodecOf added in v0.33.0

func CodecOf(encoder string) string

CodecOf is the codec an allowed encoder writes, or "" for a name that is not on an allow list.

func EncodersFor added in v0.33.0

func EncodersFor(codec string) []string

EncodersFor is the allow list of a codec in the order it is tried; nil for a codec that has none.

func ExportDeadline

func ExportDeadline(timeline time.Duration) time.Duration

ExportDeadline is 120 s + 6 x timeline duration, at most 2 h.

func IngestDeadline

func IngestDeadline(media time.Duration) time.Duration

IngestDeadline is 60 s + 3 x media duration, at most 4 h.

func IngestDeadlineFor

func IngestDeadlineFor(media time.Duration, sizeBytes int64) time.Duration

IngestDeadlineFor is IngestDeadline plus 1 s per MiB of the source file: a heavy intermediate codec (ProRes 4444 with alpha) takes time in proportion to its bytes, not to its duration.

func IsHardwareEncoder added in v0.33.0

func IsHardwareEncoder(encoder string) bool

IsHardwareEncoder says whether the encoder is a vendor encoder, whose driver maps very large address ranges (SDD-007 section 6.5). The software encoders are libopenh264, libx264, libsvtav1 and libaom-av1.

func IsRefusedEncoder added in v0.33.0

func IsRefusedEncoder(encoder string) bool

IsRefusedEncoder says whether the encoder is one the product never uses.

func LimitsAvailable

func LimitsAvailable() (bool, string)

LimitsAvailable reports whether prlimit(1) from util-linux is installed. When it is not, the owner process must start with a boot error that names the package, never with children that are silently unlimited; doctor reports "unavailable".

func LimitsFor

func LimitsFor(kind RunKind, deadline time.Duration, cpus int, fileBytes int64) engine.Limits

LimitsFor returns the limits of a run kind; prlimit(1) applies them (SDD-007 6.5).

func LimitsForWhisper

func LimitsForWhisper(modelBytes int64, cpus int) engine.Limits

LimitsForWhisper returns the limits of a whisper-cli run: the memory of its model.

func MissingFilters

func MissingFilters(filters map[string]bool) []string

MissingFilters lists the filters the argv checker accepts and the engine needs that a build does not have. A build that lacks one fails here instead of in the middle of an export (SDD-004, SDD-011).

func OpenH264Path

func OpenH264Path(toolsDir string, e OpenH264Entry) string

OpenH264Path is where the verified library of an entry lives under the tools directory.

func ResolveSandbox

func ResolveSandbox(ctx context.Context, mode string) (string, error)

ResolveSandbox returns the path of bwrap for STUARTY_SANDBOX=bwrap, or "" for no sandbox. A bwrap that is missing or cannot create its namespaces is an error, so the owner process does not start with a sandbox that is not there.

func Scrub

func Scrub(s string, limit int) string

Scrub removes paths and control characters from tool output and keeps the last limit characters, so a message or a detail never carries a server path (SDD-002 A.8).

func Sniff

func Sniff(head []byte) error

Sniff applies FF-05 to the first bytes of a stored file: a known media signature is required, and text is refused without FFmpeg ever reading the file. head is at most SniffSize bytes.

func SniffFile

func SniffFile(path string) error

SniffFile reads the first SniffSize bytes of path and applies Sniff. It is the check that runs before ffprobe for every stored original.

func TranscribeDeadline

func TranscribeDeadline(audio time.Duration) time.Duration

TranscribeDeadline is 120 s + 3 x audio duration, at most 6 h.

Types

type Candidate

type Candidate struct {
	Name       string
	Status     EncoderStatus
	MS         int64
	StderrTail string // at most 300 characters, paths removed
	// Reason is a machine readable cause for a candidate that was not tried, such as
	// ReasonOpenH264NotInstalled; empty otherwise.
	Reason string
	// Input is what the export must use with this encoder (SDD-011 8.4, DS-13).
	Input ffargs.DetectInput
}

Candidate is one encoder tried by detection.

type Capabilities

type Capabilities struct {
	Encoders, Decoders, Filters, Muxers map[string]bool
	// Optional capabilities, recorded and never required.
	Zscale, Tonemap, Bwdif, Yadif bool
	// HDROK is true when the HDR tone-mapping chain ran on a synthetic HLG source.
	HDROK bool
	// License is the classification of 8.2 with the rule that libx264 or libx265 among the
	// encoders implies gpl.
	License License
}

Capabilities is the listing of SDD-011 8.3.

type Ceilings

type Ceilings struct {
	MaxPixels  int64   // STUARTY_MAX_IMPORT_PIXELS
	MaxSeconds float64 // STUARTY_MAX_IMPORT_SECONDS
}

Ceilings of SDD-007 9.1 that the probe enforces before any decode (9.2 item 1). A zero field takes its default; the variable names are those of SDD-000 section 10.

type Config

type Config struct {
	// FFmpegPath and FFprobePath are STUARTY_FFMPEG and STUARTY_FFPROBE. A set
	// FFmpegPath that is unusable is an error, never a silent fallback.
	FFmpegPath, FFprobePath string
	// ExecDir is the directory of the stuarty executable, for the bundled copy.
	// Empty skips the bundled source.
	ExecDir string
	// CPUCount is the CPU budget of a run (vukem cpu.Count, read by the caller). Zero means the
	// machine's logical CPU count.
	CPUCount int
	// ToolsDir is <workspace>/tools, where the explicit install step puts the Cisco OpenH264 library the
	// own FFmpeg build loads (D-017). Empty means none is installed.
	ToolsDir string
	// OpenH264Manifest pins that library; the embedded manifest when it has no entries. Tests replace it.
	OpenH264Manifest OpenH264Manifest
	// Limits bound every run through prlimit(1). Linux only: the caller leaves it zero elsewhere.
	Limits engine.Limits
	// LookPath resolves ffmpeg on the PATH; exec.LookPath when nil. Tests replace it.
	LookPath func(string) (string, error)
	Log      *slog.Logger
}

Config says where to look and how runs are bounded.

type DetectOptions

type DetectOptions struct {
	// Forced is STUARTY_ENCODER: only that candidate is tested and it is never replaced.
	Forced string
	// AllowUserX264 is STUARTY_ALLOW_USER_X264; it matters only for a user's own build.
	AllowUserX264 bool
	// Candidates replaces the default order when non-nil. An empty non-nil list disables
	// every encoder, which is how tests simulate a machine with none.
	Candidates []string
	// Refresh ignores the cached result (doctor always re-runs, SDD-011 8.5).
	Refresh bool
}

DetectOptions are the inputs of encoder detection.

type Downloader

type Downloader interface {
	Do(req *http.Request) (*http.Response, error)
}

Downloader does one HTTP request. In the product it is the client of outbound.HelperDownload, the only one that may dial, which checks every hop against the manifest hosts.

type EncoderDetection

type EncoderDetection struct {
	Chosen     string // empty when none works
	Forced     bool
	Candidates []Candidate
}

EncoderDetection is the cached result of the test encodes.

func (*EncoderDetection) ChosenCandidate

func (d *EncoderDetection) ChosenCandidate() (Candidate, bool)

ChosenCandidate returns the candidate record of the chosen encoder.

type EncoderStatus

type EncoderStatus string

EncoderStatus is the result of one candidate (SDD-011 8.4).

const (
	EncoderOK        EncoderStatus = "ok"
	EncoderFailed    EncoderStatus = "failed"
	EncoderNotListed EncoderStatus = "not_listed"
)

The results of one candidate.

type Error

type Error struct {
	Code    string
	Reason  string // details.reason
	Message string
	Hint    string
	Details map[string]any
	Err     error
}

Error carries an SDD-000 error code, a machine readable reason, what to do about it and the details of SDD-011 section 5.3, so an adapter maps it without parsing text.

func (*Error) Error

func (e *Error) Error() string

func (*Error) Unwrap

func (e *Error) Unwrap() error

type Flavour

type Flavour struct {
	Name    FlavourName
	License License
	// GPL and Nonfree are true when --enable-gpl or --enable-nonfree is on the line.
	GPL, Nonfree bool
	// LinksOpenH264 is true when --enable-libopenh264 is on the line: the encoder is in the build
	// and needs a Cisco or a distribution library to work.
	LinksOpenH264 bool
	// ExtraVersion is the value of --extra-version.
	ExtraVersion string
}

Flavour is what the configure line says about a build: which one it is and its licence flags. It is read from the output of -version, so a fake is enough to test it.

func (Flavour) LGPLOnly

func (f Flavour) LGPLOnly() bool

LGPLOnly is true when neither --enable-gpl nor --enable-nonfree is on the line (NFR-043).

func (Flavour) Problems

func (f Flavour) Problems() []string

Problems lists what is wrong with a build the project distributes: an own or BtbN build with a GPL or nonfree flag must never reach a user. A user's FFmpeg is the user's choice and has none.

type FlavourName

type FlavourName string

FlavourName tells which build of FFmpeg is running (ADR-0011, D-017).

const (
	// FlavourOwn is the build this project makes (P3-REL-001): LGPL, no OpenH264 compiled in, the Cisco
	// library loaded at run time. Its configure line carries --extra-version=vukem<N>.
	FlavourOwn FlavourName = "vukem"
	// FlavourBtbN is the BtbN lgpl build pinned through the Prototype and ALPHA.
	FlavourBtbN FlavourName = "btbn"
	// FlavourOther is any other FFmpeg: the user's own.
	FlavourOther FlavourName = "other"
)

The builds the product knows by their configure line.

type HelperRequest

type HelperRequest struct {
	Tool *engine.Tool
	Dir  *RunDir
	Argv []string
	// Deadline bounds the run; there is no stall watchdog, the helper answers requests and is idle
	// between them.
	Deadline time.Duration
	// Stdin and Stdout carry the protocol of the helper. A Stdin that blocks in Read must return
	// when the run ends (contrib/engine).
	Stdin  io.Reader
	Stdout io.Writer
}

HelperRequest is one run of a helper.

type InstallOpenH264Options

type InstallOpenH264Options struct {
	// ToolsDir is <workspace>/tools.
	ToolsDir string
	Manifest OpenH264Manifest
	Client   Downloader
	// GOOS and GOARCH select the entry; the runtime's when empty.
	GOOS, GOARCH string
	// Progress, when set, is told the bytes of the download read so far and the total.
	Progress func(done, total int64)
}

InstallOpenH264Options is what the install step needs.

type Installation

type Installation struct {
	FFmpeg, FFprobe *engine.Tool
	Source          Source
	Info            VersionInfo // of ffmpeg
	ProbeInfo       VersionInfo // of ffprobe
	CPUCount        int
	// UserBuild is true when the pair is the user's own: configured, or found on the PATH.
	// A bundled build is never a user build (libx264 is not offered for it, SDD-011 8.4).
	UserBuild bool
	// OpenH264 is the state of the Cisco library, checked once at discovery and meaningful only for the own
	// build (Flavour). Installed means the file passed its size and SHA-256 check.
	OpenH264 OpenH264State
	// contains filtered or unexported fields
}

Installation is a usable FFmpeg and ffprobe pair.

func Discover

func Discover(ctx context.Context, cfg Config) (*Installation, error)

Discover finds FFmpeg in the order of ADR-0011 and SDD-011 8.1: the configured path, the copy next to the executable, then the PATH. The first usable pair wins.

func (*Installation) Flavour

func (in *Installation) Flavour() Flavour

Flavour is the build of the ffmpeg of the installation.

func (*Installation) ThreadLimit

func (in *Installation) ThreadLimit() int

ThreadLimit is the value to put in -threads and -filter_threads, or zero when the CPU budget equals the machine's and FFmpeg's own count is right (SDD-011 1.3).

func (*Installation) Warnings

func (in *Installation) Warnings() []string

Warnings lists the version warnings of SDD-011 8.2.

func (*Installation) WithLimits

func (in *Installation) WithLimits(ctx context.Context, l engine.Limits) (*Installation, error)

WithLimits returns a copy of the installation whose tools run under the limits. The pinned contrib/engine applies limits per tool, so a run kind with other limits needs its own pair. With no limits (the zero value, always the case on macOS) the installation is returned as it is.

type License

type License struct {
	Name     string // "lgpl", "gpl" or "nonfree"
	Version3 bool   // LGPL v3 (--enable-version3), else v2.1
}

License is the classification of SDD-011 8.2.

type OpenH264Entry

type OpenH264Entry struct {
	Name    string `json:"name"`
	Version string `json:"version"`
	OS      string `json:"os"`
	Arch    string `json:"arch"`
	URL     string `json:"url"`
	Bytes   int64  `json:"bytes"`
	SHA256  string `json:"sha256"`
	// File is the name of the library under tools/openh264/<version>/, the name the own build loads.
	File          string `json:"file"`
	LibraryBytes  int64  `json:"library_bytes"`
	LibrarySHA256 string `json:"library_sha256"`
	License       string `json:"license"`
	// Published is false for an entry whose size and digests are not known yet: the install refuses it.
	Published bool `json:"published"`
}

OpenH264Entry pins the download of the Cisco library for one platform: the compressed file (size and SHA-256 of what the host serves) and the library inside it (size and SHA-256 of what is run).

type OpenH264Manifest

type OpenH264Manifest struct {
	// Hosts is the allowlist of every hop of the download, redirects included.
	Hosts   []string        `json:"hosts"`
	Entries []OpenH264Entry `json:"entries"`
}

OpenH264Manifest lists what the install step may download for the own build (SDD-007 6.8).

func DefaultOpenH264Manifest

func DefaultOpenH264Manifest() (OpenH264Manifest, error)

DefaultOpenH264Manifest is the embedded manifest, validated.

func ParseOpenH264Manifest

func ParseOpenH264Manifest(data []byte) (OpenH264Manifest, error)

ParseOpenH264Manifest reads and validates a manifest: https URLs on listed hosts only, plain file names, and for a published entry the exact sizes and the digests in lower-case hex.

func (OpenH264Manifest) For

func (m OpenH264Manifest) For(goos, goarch string) (OpenH264Entry, bool)

For returns the entry of a platform.

type OpenH264State

type OpenH264State struct {
	// Dir is the directory that holds the library; empty unless Installed.
	Dir       string
	Installed bool
	// Reason is empty when Installed, else ReasonOpenH264NotInstalled, ReasonOpenH264Changed or
	// ReasonOpenH264Platform.
	Reason string
	Entry  OpenH264Entry
}

OpenH264State is the answer of CheckOpenH264.

func CheckOpenH264

func CheckOpenH264(toolsDir string, m OpenH264Manifest, goos, goarch string) OpenH264State

CheckOpenH264 says whether the library of this platform is installed and unchanged: the file must exist with the exact size of the manifest and its SHA-256 must match, which is checked at each start (SDD-007 6.8 item 6). It reads files only and never starts a download.

func InstallOpenH264

func InstallOpenH264(ctx context.Context, opt InstallOpenH264Options) (OpenH264State, error)

InstallOpenH264 downloads the Cisco library of the platform, checks the size and the SHA-256 of the download and of the library inside it, and only then moves it to tools/openh264/<version>/. A wrong size or digest deletes everything of the attempt and leaves no library. It is the only function of the engine that downloads, and only the explicit install step calls it (SDD-007 6.8, T-26).

type ProbeFormat

type ProbeFormat struct {
	Name      string  `json:"format_name"`
	NbStreams int     `json:"nb_streams"`
	Duration  string  `json:"duration"`
	Size      string  `json:"size"`
	Seconds   float64 `json:"-"`
}

ProbeFormat is the container block.

type ProbeResult

type ProbeResult struct {
	Raw     []byte // the JSON as ffprobe printed it
	Format  ProbeFormat
	Streams []ProbeStream
}

ProbeResult is a checked ffprobe answer.

func CheckProbe

func CheckProbe(raw []byte, c Ceilings) (*ProbeResult, error)

CheckProbe applies FF-06 to the JSON of ffprobe -show_format -show_streams.

type ProbeStream

type ProbeStream struct {
	Index       int    `json:"index"`
	CodecType   string `json:"codec_type"`
	CodecName   string `json:"codec_name"`
	Width       int    `json:"width"`
	Height      int    `json:"height"`
	Disposition struct {
		AttachedPic int `json:"attached_pic"`
		Default     int `json:"default"`
	} `json:"disposition"`
}

ProbeStream is the part of an ffprobe stream the checks need. Raw keeps everything for ingest.

type Progress

type Progress struct {
	Frame     int64
	OutTimeUS int64
	End       bool
}

Progress is one block of the -progress output.

type Request

type Request struct {
	Dir  *RunDir
	Argv []string
	// InputDirs are artifact directories the argv may read from (see ffargs.Policy).
	InputDirs []string
	// Deadline bounds the run (SDD-007 6.5); required. While other runs are in flight it is
	// multiplied by that count, then capped at DeadlineCeiling.
	Deadline time.Duration
	// DeadlineCeiling caps a deadline that was multiplied because other runs share the process.
	// Zero uses ExportDeadlineCeiling when Deadline is within it, and IngestDeadlineCeiling when
	// Deadline is already longer (only an ingest deadline exceeds the export cap).
	DeadlineCeiling time.Duration
	// Stall overrides StallTimeout; used only when argv has -progress pipe:1.
	Stall time.Duration
	// OnProgress receives each progress block, from the goroutine that reads the pipe.
	OnProgress func(Progress)
	// Stdout receives the standard output of a run whose output is pipe:1 (raw frames).
	// An *os.File is handed to the child as it is, with no copy through this process.
	Stdout io.Writer
	// Stdin feeds a run whose input is pipe:0 (raw frames to the encoder). An *os.File is
	// handed to the child as it is. The runner never closes it: the caller owns both ends.
	Stdin io.Reader
	// OutputPath and MaxOutputBytes arm the size watchdog (STUARTY_MAX_EXPORT_BYTES): the file is
	// polled every OutputPollInterval and a run that grows it past the cap is killed with
	// ErrOutputTooLarge. The path must be inside the run directory.
	OutputPath     string
	MaxOutputBytes int64
}

Request is one ffmpeg run.

type Result

type Result struct {
	Stderr   string // tail, at most 4 MiB
	ExitCode int
	Duration time.Duration
}

Result is what a run produced.

type RunDir

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

RunDir is the directory of one job: the child's working directory, HOME and temp directory, and the only place it writes (SDD-007 6.4).

func (*RunDir) Dir

func (d *RunDir) Dir() string

Dir is the directory path.

func (*RunDir) Path

func (d *RunDir) Path(name string) (string, error)

Path returns a generated file name inside the run directory (engine.Sanitized).

func (*RunDir) Remove

func (d *RunDir) Remove() error

Remove deletes the directory after the process tree has ended. On Windows a handle that the dying process still holds can fail the first attempts, so it retries briefly.

func (*RunDir) Sub

func (d *RunDir) Sub(name string) (string, error)

Sub creates a subdirectory (for example the thumbnail tiles) and returns its path.

type RunKind

type RunKind int

RunKind says what a run is for, which decides its address space ceiling (SDD-007 6.5).

const (
	KindProbe RunKind = iota
	KindIngest
	KindFrame
	// KindExportSoftware is an export with a software encoder.
	KindExportSoftware
	// KindExportHardware is an export with h264_nvenc, h264_qsv, h264_vaapi or h264_amf: GPU
	// drivers map very large address ranges, so RLIMIT_AS is not set for it.
	KindExportHardware
)

The kinds of run.

type Runner

type Runner struct {
	In *Installation
	// Workspace is the workspace root; run directories are Workspace/tmp/<job id>.
	Workspace string
	// StoreDir is the content store, Workspace/store unless it is a link elsewhere.
	StoreDir string

	// Sandbox is the path of bwrap (ResolveSandbox) or empty: the tools then run inside it (Linux).
	Sandbox string
	// Grace is how long a cancelled run may take to end; CancelGrace when zero.
	Grace time.Duration
	// contains filtered or unexported fields
}

Runner starts FFmpeg and ffprobe for one workspace. Every argv goes through ffargs.Check first; a refused argv starts nothing.

func NewRunner

func NewRunner(in *Installation, workspace string) (*Runner, error)

NewRunner returns a runner for the installation and the workspace root.

func (*Runner) DetectCodec added in v0.33.0

func (r *Runner) DetectCodec(
	ctx context.Context,
	caps *Capabilities,
	codec string,
	opt DetectOptions,
) (*EncoderDetection, error)

DetectCodec is DetectEncoder for a codec: it runs the test encode of each allowed encoder of the codec that the build lists, in order, and caches the answer for the life of the runner. H.264 is DetectEncoder itself. When no encoder works the error is E_NO_ENCODER with the reason codec_unavailable and the answer of every candidate; the detection is still returned, so a caller can report why. A refused encoder (libx265) is never a candidate.

func (*Runner) DetectEncoder

func (r *Runner) DetectEncoder(ctx context.Context, caps *Capabilities, opt DetectOptions) (*EncoderDetection, error)

DetectEncoder runs a real test encode for each candidate, in the order of ADR-0011 item 5, and caches the result for the life of the runner. No working encoder is E_NO_ENCODER and the message says how to fix it.

func (*Runner) EncoderForSize

func (r *Runner) EncoderForSize(ctx context.Context, det *EncoderDetection, p SizeProbe) (Candidate, error)

EncoderForSize is the encoder an export at this size and rate uses (D-034, SDD-004 section 8): the one detection chose when its test encode at that size passes, else the next working candidate of the same order that passes it, down to the software encoder, so a GPU that cannot do 4K or 60 fps does not stop an export that libopenh264 can do. A forced encoder (STUARTY_ENCODER) is never replaced. When none passes, the error is the one of the chosen encoder and wraps ErrEncoderSize; a cancelled run or a failure that is not about the size ends the search at once.

func (*Runner) HelperTool

func (r *Runner) HelperTool(ctx context.Context, path string, deadline time.Duration) (*engine.Tool, error)

HelperTool resolves a helper of this product (the GPU host stuarty-render) as a tool that runs under the limits of an export with a hardware encoder: a CPU backstop and no address space ceiling, because graphics drivers map very large ranges (SDD-007 6.5). The path must be absolute; the helper answers --version, which the discovery reads.

func (*Runner) NewJobRunDir

func (r *Runner) NewJobRunDir(jobID string) (*RunDir, error)

NewJobRunDir is NewRunDir for a job's own directory. A job id belongs to one job, so a directory that already exists is the leftover of an interrupted earlier attempt (the process was closed mid-encode and the job was requeued): it is removed first.

func (*Runner) NewRunDir

func (r *Runner) NewRunDir(jobID string) (*RunDir, error)

NewRunDir creates <workspace>/tmp/<job id> with mode 0700. The directory must not exist.

func (*Runner) OpenStoreFile

func (r *Runner) OpenStoreFile(name string) (*os.File, error)

OpenStoreFile opens a file of the store, named relative to it, through os.Root, so a name cannot leave the store, and refuses a link anywhere in the path of the file.

func (*Runner) Policy

func (r *Runner) Policy(d *RunDir, inputDirs ...string) ffargs.Policy

Policy is the argv policy of a run: the store, the run directory, the extra input directories and the CPU budget.

func (*Runner) Probe

func (r *Runner) Probe(ctx context.Context, dir *RunDir, path string, c Ceilings) (*ProbeResult, error)

Probe is the entry of ingest: FF-05 (signature before FFmpeg), the ffprobe run with the caps of FF-09, and the checks of FF-06 (format allowlist, stream count, a usable stream, the ceilings). path is a file of the store; dir is the run directory of the probe.

func (*Runner) ReadCapabilities

func (r *Runner) ReadCapabilities(ctx context.Context) (*Capabilities, error)

ReadCapabilities parses the four listings, requires what SDD-011 8.3 requires, runs the smoke encodes of the required encoders and the HDR chain. A missing or failing required item is E_FFMPEG_MISSING with details.missing.

func (*Runner) RunFFmpeg

func (r *Runner) RunFFmpeg(ctx context.Context, req Request) (Result, error)

RunFFmpeg checks the argv, then runs ffmpeg in the run directory with the deadline and the stall watchdog. A cancelled ctx kills the whole process tree and the error wraps ctx.Err().

func (*Runner) RunFFprobe

func (r *Runner) RunFFprobe(
	ctx context.Context,
	dir *RunDir,
	argv []string,
	deadline time.Duration,
	inputDirs ...string,
) ([]byte, Result, error)

RunFFprobe checks the argv and runs ffprobe. Its JSON is read through a writer capped at 4 MiB (FF-09); more than that is E_UNSUPPORTED_MEDIA.

func (*Runner) RunHelper

func (r *Runner) RunHelper(ctx context.Context, req HelperRequest) (Result, error)

RunHelper runs a helper under the process policy of FFmpeg: no root, the minimal environment, its own run directory, a deadline, the cancel grace and the kill of the whole process tree (SDD-007 6.4 to 6.6). The argv is the caller's own constant, never user text.

func (*Runner) TestEncoderAt

func (r *Runner) TestEncoderAt(ctx context.Context, c Candidate, p SizeProbe) error

TestEncoderAt runs the test encode of SDD-011 8.4 at another size and rate (an export at 4K or at 60 fps, SDD-004 section 8) on the candidate that detection chose, and checks the 15 packets it wrote. The answer, good or bad, is cached for the life of the runner; a cancelled run is not. A failure wraps ErrEncoderSize and carries the first line of what the encoder said.

type SizeProbe

type SizeProbe struct {
	Width, Height  int
	FPSNum, FPSDen int
}

SizeProbe is the size and the frame rate a test encode is asked for.

type Source

type Source string

Source is where an FFmpeg came from (SDD-011 8.1).

const (
	SourceConfigured Source = "configured"
	SourceBundled    Source = "bundled"
	SourcePath       Source = "path"
)

The sources of an FFmpeg, in the order they are tried.

type VersionInfo

type VersionInfo struct {
	Version    string   // the token after "ffmpeg version "
	Major      int      // -1 when the version is not numeric (a master build)
	ConfigLine string   // the line after "configuration:"
	Flags      []string // the configure flags
	License    License
	Warnings   []string // untested_ffmpeg_version, old_ffmpeg_version
}

VersionInfo is what ffmpeg -hide_banner -version prints, parsed.

func ParseVersion

func ParseVersion(tool, out string) (VersionInfo, bool)

ParseVersion reads the output of "-version". tool is "ffmpeg" or "ffprobe".

func (VersionInfo) Flavour

func (v VersionInfo) Flavour() Flavour

Flavour identifies the build from its configure line.

Directories

Path Synopsis
Package ffargs builds and checks every FFmpeg and ffprobe argument list the product starts (SDD-007 section 6, rules FF-01 to FF-16).
Package ffargs builds and checks every FFmpeg and ffprobe argument list the product starts (SDD-007 section 6, rules FF-01 to FF-16).

Jump to

Keyboard shortcuts

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