mediaops

package
v0.206.0 Latest Latest
Warning

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

Go to latest
Published: Oct 29, 2026 License: Apache-2.0 Imports: 19 Imported by: 0 modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Overview

Package mediaops implements the offload_edit_image / offload_media engines: deterministic image edits (PIL worker + GIMP design-file conversion) and ffmpeg av operations. Everything here is CPU work — NO GPU lock, no llama-swap eviction; these ops run in parallel with renders. Spec: the private development record (2026-07-16).

Index

Constants

This section is empty.

Variables

View Source
var ErrEngineAbsent = errors.New("engine absent on this machine")

ErrEngineAbsent marks a defer-class failure: the machine simply lacks the engine (unset/missing binary). Handlers turn any error into a clean defer; this sentinel lets the reason say "engine absent" instead of "failed".

Functions

func BuildConcatList

func BuildConcatList(inputs []string) (string, error)

BuildConcatList renders the concat demuxer list file content. Single quotes in paths use the demuxer's '\” escape. Pure.

func BuildFFmpegArgs

func BuildFFmpegArgs(r MediaRequest) ([]string, error)

BuildFFmpegArgs assembles the ffmpeg argv for one media op. Pure — no filesystem, no exec — so every op's argv is unit-testable. The caller prepends the ffmpeg path.

func BuildGimpScript

func BuildGimpScript(src, dst, layersPath string) (string, error)

BuildGimpScript renders the flatten_design script-fu for (src -> dst raster, layer sidecar). Pure. src must be a .xcf or .psd.

func BuildInstantiateScript

func BuildInstantiateScript(src, dst string, setText, replaceImage map[string]string) (string, error)

BuildInstantiateScript renders the instantiate_design script-fu: open the .xcf/.psd template, set named text layers' copy (gimp-text-layer-set-text), swap named pixel layers for replacement images (loaded via gimp-file-load-layer, inserted at the old layer's offsets, old removed), flatten, save the raster to dst. Pure; deterministic (layer names sorted). A layer-name mismatch errors inside GIMP (gimp-image-get-layer-by-name) and surfaces on stderr — the single most common template failure. PDB names verified against gimp-console-3.2 (2026-07-17): shipped 3.2 scripts use gimp-drawable-get-offsets (3.x rename), insert-layer parent 0.

func GimpArgs

func GimpArgs(scriptFile string) []string

GimpArgs wraps a script FILE (already written to disk by WriteScriptFile) in the gimp-console batch argv via (load ...), always ending with gimp-quit so the console exits.

F-40 (2026-09-24): a built script can carry caller-supplied text — set_text copy for instantiate_design, e.g. Spanish headlines with accents — and this used to be passed as the batch command's own argv element (`-b script` directly). That depends on the child process decoding a non-ASCII argv correctly, which the harness does not control and cannot assume: Windows PowerShell 5.1 was reproduced doing exactly this wrong on the same box (CreateProcess carries clean UTF-16 all the way to the child, but the child's OWN command-line decoding can still re-narrow it through a legacy code page — see internal/winexec's doc comment for the live repro). Loading the script from a file removes the text from argv entirely, so the fix does not depend on any particular GIMP build's own argv-handling being correct.

func ResolveBinary added in v0.206.0

func ResolveBinary(bin string) (string, bool)

ResolveBinary answers "is this executable binding usable?" the way a spawned child process actually resolves it, not the way a bare os.Stat does. Two shapes:

  • An explicit path (contains a separator, or otherwise names a real file in the current directory) is stat'd directly.
  • A bare command name — the shipped config default ("ffmpeg", "node", ...) — is looked up on PATH via exec.LookPath, which on Windows also tries each PATHEXT extension (.exe, .cmd, ...) the way CreateProcess/cmd.exe would.

Before this helper existed, every FFmpeg call site had its own copy of one half of this (mediacap.binaryPresent used LookPath; internal/mediaops.RunMedia and the JS render scripts used only os.Stat/existsSync) — so a box whose config left ffmpeg_path at its bare "ffmpeg" default failed EVERY caller that used the os.Stat-only half, even with ffmpeg correctly installed and on PATH (F-38, 2026-09-24: reproduced identically on <node-c> and <node-a> — see render/audio-qa.mjs's resolveFfmpeg for the JS side of the same bug class).

Returns ("", false) for an empty binding. On success, returns the path that will actually run — the input unchanged for a working explicit path, or the PATH-resolved absolute path for a bare name.

func ResolveEditPython

func ResolveEditPython(editPython, comfyDir string) string

ResolveEditPython resolves the PIL engine's python: the explicit config value when set, else <comfyDir>/.venv/{Scripts/python.exe|bin/python}. "" = absent (the caller defers). Existence-checked — a configured-but-missing engine is absent, not an error at call time.

func ToSeconds

func ToSeconds(v string) (float64, error)

ToSeconds parses "ss", "ss.ms", "mm:ss", or "hh:mm:ss(.ms)" into seconds.

func UsesGimp

func UsesGimp(ops []EditOp) bool

UsesGimp reports whether the pipeline needs the GIMP engine (spec: only flatten_design and instantiate_design do, and validation pins both to ops[0]).

func ValidateOps

func ValidateOps(ops []EditOp) error

ValidateOps checks a whole pipeline BEFORE any work starts, so a bad op defers with a message naming the offending index instead of failing mid-pipeline with a half-written file. Pure.

func ValidateRenditions

func ValidateRenditions(rs []Rendition) error

ValidateRenditions checks the export matrix BEFORE any work starts. Pure. An empty set is valid (renditions are optional).

func WriteScriptFile added in v0.206.0

func WriteScriptFile(script string) (path string, cleanup func(), err error)

WriteScriptFile writes a TinyScheme/script-fu program to a fresh temp .scm file, UTF-8, no BOM (script-fu string literals are byte-based and GIMP's text-layer PDB calls expect UTF-8) — the file GimpArgs then references by path so caller-supplied text never has to survive a child process's argv decoding. The caller MUST invoke the returned cleanup (safe to call once the console has exited; also safe to call on an error path before the file was ever created).

Types

type EditConfig

type EditConfig struct {
	Python      string        // resolved PIL python ("" = absent)
	GimpConsole string        // gimp-console path ("" = absent)
	Worker      string        // absolute path of render/edit_image.py
	Timeout     time.Duration // edit_timeout_sec
}

EditConfig carries this machine's edit-engine bindings (from config).

type EditOp

type EditOp struct {
	Op string `json:"op"`
	// crop / composite / text placement. X/Y have NO omitempty: a crop or composite
	// anchored at the image origin (x:0, y:0) is a legitimate, common request, and
	// omitempty on an int drops the zero value from the JSON entirely — the worker
	// (render/edit_image.py) then saw a missing "x" key and failed the whole pipeline
	// with `pipeline failed: 'x'` (KeyError) instead of cropping/compositing at 0,0
	// (found 2026-09-23 on the <node-e> remediation pass). Width/Height keep
	// omitempty: 0 is never valid for them (ValidateOps rejects it), so there is no
	// zero-vs-absent ambiguity to protect against.
	X      int `json:"x"`
	Y      int `json:"y"`
	Width  int `json:"width,omitempty"`
	Height int `json:"height,omitempty"`
	// resize
	KeepAspect *bool `json:"keep_aspect,omitempty"`
	// convert
	Format string `json:"format,omitempty"`
	// composite
	Overlay string  `json:"overlay,omitempty"`
	Opacity float64 `json:"opacity,omitempty"`
	// text
	Text   string `json:"text,omitempty"`
	Size   int    `json:"size,omitempty"`
	Color  string `json:"color,omitempty"`
	Font   string `json:"font,omitempty"`
	Anchor string `json:"anchor,omitempty"`
	// mask_boxes (white-on-black inpaint mask builder; REPLACES the working image)
	Boxes   []MaskBox `json:"boxes,omitempty"`
	Feather int       `json:"feather,omitempty"`
	Pad     int       `json:"pad,omitempty"`
	Invert  bool      `json:"invert,omitempty"`
	// perspective_composite (overlay reused; quad = 4 [x,y] dest corners UL,UR,LR,LL)
	Quad [][]float64 `json:"quad,omitempty"`
	// lut_cube (.cube 3D LUT; strength 0-1 blends graded over original, nil = 1.0)
	Path     string   `json:"path,omitempty"`
	Strength *float64 `json:"strength,omitempty"`
	// grade (tone/color: everything composes into ONE LUT per channel, single quantize)
	Levels        *GradeLevels `json:"levels,omitempty"`
	Curve         *GradeCurve  `json:"curve,omitempty"`
	WB            *GradeWB     `json:"wb,omitempty"`
	LuminanceOnly bool         `json:"luminance_only,omitempty"`
	// finish (delivery sharpening — MUST be the LAST op, after any resize:
	// sharpening before a resize is undone by resampling)
	Sharpen *FinishSharpen `json:"sharpen,omitempty"`
	Median  int            `json:"median,omitempty"`
	// instantiate_design (FIRST op only; GIMP layered-template factory —
	// layer name -> new text copy / replacement image path)
	SetText      map[string]string `json:"set_text,omitempty"`
	ReplaceImage map[string]string `json:"replace_image,omitempty"`
}

EditOp is one step of an offload_edit_image pipeline (spec §1). Ops are applied in order by render/edit_image.py (PIL); flatten_design runs first via GIMP.

type EditRequest

type EditRequest struct {
	Image      string
	Ops        []EditOp
	Out        string
	Renditions []Rendition // optional export matrix derived from the master Out
}

EditRequest is one offload_edit_image call (ops already shaped; validated here).

type EditResult

type EditResult struct {
	Out        string   `json:"image_path"`
	Width      int      `json:"width"`
	Height     int      `json:"height"`
	OpsApplied int      `json:"ops_applied"`
	Layers     []Layer  `json:"layers,omitempty"`
	Renditions []string `json:"renditions,omitempty"`
	Engine     string   `json:"engine"`
}

EditResult mirrors the tool's return payload (spec §1).

func RunEditImage

func RunEditImage(ctx context.Context, cfg EditConfig, req EditRequest) (EditResult, error)

RunEditImage validates and executes a whole edit pipeline: optional GIMP flatten first (design files), then the PIL worker for the remaining ops.

type FinishSharpen

type FinishSharpen struct {
	Radius    *float64 `json:"radius,omitempty"`
	Percent   *int     `json:"percent,omitempty"`
	Threshold *int     `json:"threshold,omitempty"`
}

FinishSharpen tunes the finish op's unsharp mask. ABSENT fields mean "worker default" (radius 1.2, percent 80, threshold 3 — post-AI-upscale web delivery). Pointers, not values: an EXPLICIT 0 (e.g. percent 0 = no visible sharpening, the Go-path way to get a median-only finish) must survive the struct round-trip — a value field with omitempty silently dropped it and the worker re-defaulted it (review finding 2026-07-17).

type GradeCurve

type GradeCurve struct {
	Points [][]float64 `json:"points"`
}

GradeCurve is a piecewise-linear tone curve through [in,out] control points (0-255).

type GradeLevels

type GradeLevels struct {
	Black int     `json:"black,omitempty"`
	White int     `json:"white,omitempty"`
	Gamma float64 `json:"gamma,omitempty"`
}

GradeLevels is the levels sub-adjustment of a grade op. Zero values mean "worker default" (black 0, white 255, gamma 1.0) — the worker fills them in.

type GradeWB

type GradeWB struct {
	Mode string  `json:"mode"`
	R    float64 `json:"r,omitempty"`
	G    float64 `json:"g,omitempty"`
	B    float64 `json:"b,omitempty"`
}

GradeWB is the white-balance sub-adjustment: mode "gray_world" (automatic) or "scale" with explicit per-channel multipliers (0 = worker default 1.0).

type Layer

type Layer struct {
	Name    string `json:"name"`
	Visible bool   `json:"visible"`
}

Layer is one entry of a design file's layer listing.

func ParseLayerList

func ParseLayerList(content string) []Layer

ParseLayerList parses the sidecar layer file ("LAYER:<name>|visible|hidden" per line; the name may itself contain pipes — split on the LAST one). Pure.

type MaskBox

type MaskBox struct {
	X      int `json:"x"`
	Y      int `json:"y"`
	Width  int `json:"width"`
	Height int `json:"height"`
}

MaskBox is one white rectangle of a mask_boxes op, in pixel coordinates of the working image (the same contract as offload_inpaint_image's mask: white = repaint).

type MediaConfig

type MediaConfig struct {
	FFmpeg  string        // ffmpeg_path ("" = absent)
	Timeout time.Duration // edit_timeout_sec governs media ops too
	// VideoEncoder is config ffmpeg_video_encoder: the encoder for re-encoding ops
	// (trim --reencode, convert with video). "" = ffmpeg default (libx264, CPU).
	VideoEncoder string
}

MediaConfig carries the ffmpeg binding.

type MediaRequest

type MediaRequest struct {
	Op        string   // trim | concat | extract_frames | convert | mux_audio | probe
	In        string   // input path (all ops except concat)
	Inputs    []string // concat inputs (>=2)
	ListPath  string   // concat: path of the demuxer list file the caller wrote
	Out       string   // output path (probe: unused); RunMedia hands ffmpeg a staged sibling and renames it here (deliver.go)
	Start     string   // trim: seconds or hh:mm:ss
	End       string   // trim: absolute end time (resolved to Duration in RunMedia)
	Duration  string   // trim: seconds
	FPS       float64  // extract_frames: sampling rate
	Count     int      // extract_frames: total frames (resolved to FPS via probe in RunMedia)
	Audio     string   // mux_audio: audio input path
	Shortest  bool     // mux_audio: stop at the shorter input (default true at the handler)
	Reencode  bool     // trim: re-encode for exact cuts instead of keyframe-snapped -c copy
	AudioOnly bool     // convert: drop video (-vn)
	VideoOnly bool     // convert: drop audio (-an)
	// VideoEncoder names the ffmpeg video encoder for the two ops that RE-ENCODE video
	// (trim with Reencode, convert with video kept). "" = ffmpeg's container default
	// (libx264 on the CPU). "h264_nvenc" moves draft/QA re-encodes to NVENC — measured
	// 2026-09-05 on <node-b> (CUDA-X plan task 4.2); set from config ffmpeg_video_encoder.
	VideoEncoder string
}

MediaRequest is one offload_media operation. Exactly one op per call (spec §1).

type MediaResult

type MediaResult struct {
	MediaPath   string   `json:"media_path,omitempty"`
	DurationSec float64  `json:"duration_sec,omitempty"`
	Frames      []string `json:"frames,omitempty"`
	Count       int      `json:"count,omitempty"`
	Probe       *Probe   `json:"probe,omitempty"`
}

MediaResult is the op-specific payload (exactly one field group is set).

func RunMedia

func RunMedia(ctx context.Context, cfg MediaConfig, req MediaRequest) (MediaResult, error)

RunMedia executes one offload_media op end-to-end.

type Probe

type Probe struct {
	DurationSec float64       `json:"duration_sec"`
	Format      string        `json:"format"`
	Streams     []ProbeStream `json:"streams"`
}

Probe is the parsed `ffmpeg -i` banner (spec §1: probe op).

func ParseProbe

func ParseProbe(stderr string) (Probe, error)

ParseProbe extracts duration/format/streams from `ffmpeg -i` stderr. The banner grammar is fixture-tested against the REAL imageio ffmpeg 7.1 output so a future ffmpeg bump that changes the banner fails in tests, not silently in production.

type ProbeStream

type ProbeStream struct {
	Type       string  `json:"type"` // video | audio
	Codec      string  `json:"codec"`
	Width      int     `json:"width,omitempty"`
	Height     int     `json:"height,omitempty"`
	FPS        float64 `json:"fps,omitempty"`
	SampleRate int     `json:"sample_rate,omitempty"`
}

type Rendition

type Rendition struct {
	Width  int    `json:"width,omitempty"`
	Height int    `json:"height,omitempty"`
	Format string `json:"format"`
	Suffix string `json:"suffix"`
}

Rendition is one entry of the optional export matrix: after the ops pipeline produces the master out, each rendition re-runs the worker with a resize+convert pair, writing <out-stem><suffix>.<format>.

Jump to

Keyboard shortcuts

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